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
70f4711998e8539f0069688078c9b58d057b4da1
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/nat/choose/vandermonde.lean
909280a1c668ba60dffef6304aa72108d2ece575
[ "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,240
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 data.polynomial.coeff import data.nat.choose.basic /-! # Vandermonde's identity > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove Vandermonde's identity (`nat.add_choose_eq`): `(m + n).choose k = ∑ (ij : ℕ × ℕ) in antidiagonal k, m.choose ij.1 * n.choose ij.2` We follow the algebraic proof from https://en.wikipedia.org/wiki/Vandermonde%27s_identity#Algebraic_proof . -/ open_locale big_operators open polynomial finset.nat /-- Vandermonde's identity -/ lemma nat.add_choose_eq (m n k : ℕ) : (m + n).choose k = ∑ (ij : ℕ × ℕ) in antidiagonal k, m.choose ij.1 * n.choose ij.2 := begin calc (m + n).choose k = ((X + 1) ^ (m + n)).coeff k : _ ... = ((X + 1) ^ m * (X + 1) ^ n).coeff k : by rw pow_add ... = ∑ (ij : ℕ × ℕ) in antidiagonal k, m.choose ij.1 * n.choose ij.2 : _, { rw [coeff_X_add_one_pow, nat.cast_id], }, { rw [coeff_mul, finset.sum_congr rfl], simp only [coeff_X_add_one_pow, nat.cast_id, eq_self_iff_true, imp_true_iff], } end
a248f39603600a8e674f19f91b849c332e26da78
5ae4db17340efed4ead2959639668fe1f2e6b8d7
/sphinxcontrib/leansrc/export_json.lean
9f3193434fcc64d70f42f2e1445218f3af67274d
[ "MIT" ]
permissive
Julian/sphinxcontrib-lean
341be077242ea6c53f39c77328206057548c0475
41b40635be4f8082e02dbe1651a8d61fe44c14d6
refs/heads/main
1,673,587,461,238
1,603,763,127,000
1,603,763,127,000
299,142,489
0
0
null
null
null
null
UTF-8
Lean
false
false
15,248
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license. See https://raw.githubusercontent.com/leanprover-community/lean/master/LICENSE. Author: Robert Y. Lewis Minor modifications (by Julian Berman) to: * not reference mathlib (since it can be used generically) but instead use the directory that all.lean is found in * filter out declarations in a dependency rather than in the current project -/ import tactic.core system.io data.string.defs tactic.interactive data.list.sort import all /-! 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; module_id: string; line: int; attributes: string[]; 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; ``` Make sure the target project is precompiled, with `all.lean` generated by `leanproject mk-all`. Usage: `lean --run export_json.lean` prints the generated JSON to stdout. -/ 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 (equations : list efmt) (kind : string) -- def, thm, cnst, ax (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) meta def ext_tactic_doc_entry.to_json : ext_tactic_doc_entry → json | ⟨name, category, decl_names, tags, description, _, imported⟩ := json.object [ ("name", name), ("category", category.to_string), ("decl_names", json.of_string_list (decl_names.map to_string)), ("tags", json.of_string_list tags), ("description", description), ("import", imported)] end meta def print_arg : bool × efmt → json | (b, s) := let bstr := if b then "true" else "false" in json.object [("arg", s.to_json), ("implicit", bstr)] meta def decl_info.to_json : decl_info → json | ⟨name, is_meta, args, type, doc_string, filename, line, attributes, equations, kind, structure_fields, constructors⟩ := json.object [ ("name", to_string name), ("is_meta", is_meta), ("args", args.map print_arg), ("type", type.to_json), ("doc_string", doc_string.get_or_else ""), ("filename", filename), ("line", line), ("attributes", json.of_string_list attributes), ("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 meta def count_named_intros : expr → tactic ℕ | e@(expr.pi _ bi _ _) := do ([_], b) ← open_n_pis e 1, v ← count_named_intros b, return $ if v = 0 ∧ e.is_arrow ∧ ¬ bi.is_inst_implicit then v else v + 1 | _ := return 0 /- meta def count_named_intros : expr → ℕ | e@(expr.pi _ _ _ b) := let v := count_named_intros b in if v = 0 ∧ e.is_arrow then v else v + 1 | _ := 0 -/ -- tt means implicit meta def get_args_and_type (e : expr) : tactic (list (bool × efmt) × efmt) := prod.fst <$> solve_aux e ( do count_named_intros e >>= intron, 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, `squash_cast, `move_cast, `elim_cast, `nolint, `ext, `instance, `class] meta def attributes_of (n : name) : tactic (list string) := list.map to_string <$> attribute_list.mfilter (λ attr, succeeds $ has_attribute attr n) meta def declaration.kind : declaration → string | (declaration.defn a a_1 a_2 a_3 a_4 a_5) := "def" | (declaration.thm a a_1 a_2 a_3) := "thm" | (declaration.cnst a a_1 a_2 a_3) := "cnst" | (declaration.ax a a_1 a_2) := "ax" -- does this not exist already? I'm confused. meta def expr.instantiate_pis : list expr → expr → expr | (e'::es) (expr.pi n bi t e) := expr.instantiate_pis es (e.instantiate_var e') | _ e := e 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 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 locs (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 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_project_dir : string := (string.popn_back (module_info.of_module_name "all").id "all.lean".length) /-- extracts `decl_info` from `d`. Should return `none` instead of failing. -/ meta def process_decl (d : declaration) (project_dir: string) : 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, if ¬project_dir.is_prefix_of filename then return none else do 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, 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, equations, d.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 (project_dir : string) : tactic (list (string × json)) := do docs ← olean_doc_strings, return (docs.foldl (λ rest p, match p with | (none, _) := rest | (_, []) := rest | (some filename, l) := if project_dir.is_prefix_of filename then (filename, json.array $ l.map write_module_doc_pair) :: rest else rest end) []) meta def get_instances : tactic (rb_lmap string string) := attribute.get_instances `instance >>= list.mfoldl (λ map inst_nm, do (_, e) ← mk_const inst_nm >>= infer_type >>= mk_local_pis, (expr.const class_nm _) ← return e.get_app_fn, return $ map.insert class_nm.to_string inst_nm.to_string) mk_rb_map meta def format_instance_list : tactic json := do map ← get_instances, pure $ json.object $ 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 → ext_tactic_doc_entry | ⟨name, category, [], tags, description, idf⟩ := ⟨name, category, [], tags, description, idf, ""⟩ | ⟨name, category, rel_decls@(decl_name::_), tags, description, idf⟩ := let imported := 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 "" in ⟨name, category, rel_decls, tags, description, idf, imported⟩ meta def format_tactic_docs (project_dir : string) : 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, /- Using `environment.mfold` is much cleaner. Unfortunately this led to a segfault, I think because of a stack overflow. Converting the environment to a list of declarations and folding over that led to "deep recursion detected". -/ s ← read, let project_dir := get_project_dir, let decls := e.fold ([] : list json) (λ decl acc, match (enable_links *> process_decl decl project_dir) s with | result.success (some di) _ := di.to_json :: acc | _:= acc end), mod_docs ← write_olean_docs project_dir, notes ← format_notes, tactic_docs ← format_tactic_docs project_dir, instl ← format_instance_list, pure $ json.object [ ("decls", decls), ("mod_docs", json.object mod_docs), ("notes", notes), ("tactic_docs", tactic_docs), ("instances", instl) ] meta def main : io unit := do json ← run_tactic mk_export_json, put_str json.unparse -- HACK: print gadgets with less fluff notation x ` := `:10 y := opt_param x y -- HACKIER: print last component of name as string (because we can't do any better...) notation x ` . `:10 y := auto_param x (name.mk_string y _)
423c413b0651abee1f7f6fa37196d04471e50a10
b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77
/src/topology/subset_properties.lean
86b13f63d0d5ea7a6a26f567daf42649e1aad727
[ "Apache-2.0" ]
permissive
molodiuc/mathlib
cae2ba3ef1601c1f42ca0b625c79b061b63fef5b
98ebe5a6739fbe254f9ee9d401882d4388f91035
refs/heads/master
1,674,237,127,059
1,606,353,533,000
1,606,353,533,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
59,608
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import topology.continuous_on import data.finset.order /-! # Properties of subsets of topological spaces ## Main definitions `compact`, `is_clopen`, `is_irreducible`, `is_connected`, `is_totally_disconnected`, `is_totally_separated` TODO: write better docs ## On the definition of irreducible and connected sets/spaces In informal mathematics, irreducible and connected spaces are assumed to be nonempty. We formalise the predicate without that assumption as `is_preirreducible` and `is_preconnected` respectively. In other words, the only difference is whether the empty space counts as irreducible and/or connected. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open set filter classical open_locale classical topological_space filter universes u v variables {α : Type u} {β : Type v} [topological_space α] {s t : set α} /- compact sets -/ section compact /-- A set `s` is compact if for every filter `f` that contains `s`, every set of `f` also meets every neighborhood of some `a ∈ s`. -/ def is_compact (s : set α) := ∀ ⦃f⦄ [ne_bot f], f ≤ 𝓟 s → ∃a∈s, cluster_pt a f /-- The complement to a compact set belongs to a filter `f` if it belongs to each filter `𝓝 a ⊓ f`, `a ∈ s`. -/ lemma is_compact.compl_mem_sets (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, sᶜ ∈ 𝓝 a ⊓ f) : sᶜ ∈ f := begin contrapose! hf, simp only [mem_iff_inf_principal_compl, compl_compl, inf_assoc, ← exists_prop] at hf ⊢, exact @hs _ hf inf_le_right end /-- The complement to a compact set belongs to a filter `f` if each `a ∈ s` has a neighborhood `t` within `s` such that `tᶜ` belongs to `f`. -/ lemma is_compact.compl_mem_sets_of_nhds_within (hs : is_compact s) {f : filter α} (hf : ∀ a ∈ s, ∃ t ∈ 𝓝[s] a, tᶜ ∈ f) : sᶜ ∈ f := begin refine hs.compl_mem_sets (λ a ha, _), rcases hf a ha with ⟨t, ht, hst⟩, replace ht := mem_inf_principal.1 ht, refine mem_inf_sets.2 ⟨_, ht, _, hst, _⟩, rintros x ⟨h₁, h₂⟩ hs, exact h₂ (h₁ hs) end /-- If `p : set α → Prop` is stable under restriction and union, and each point `x of a compact set `s` has a neighborhood `t` within `s` such that `p t`, then `p s` holds. -/ @[elab_as_eliminator] lemma is_compact.induction_on {s : set α} (hs : is_compact s) {p : set α → Prop} (he : p ∅) (hmono : ∀ ⦃s t⦄, s ⊆ t → p t → p s) (hunion : ∀ ⦃s t⦄, p s → p t → p (s ∪ t)) (hnhds : ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, p t) : p s := let f : filter α := { sets := {t | p tᶜ}, univ_sets := by simpa, sets_of_superset := λ t₁ t₂ ht₁ ht, hmono (compl_subset_compl.2 ht) ht₁, inter_sets := λ t₁ t₂ ht₁ ht₂, by simp [compl_inter, hunion ht₁ ht₂] } in have sᶜ ∈ f, from hs.compl_mem_sets_of_nhds_within (by simpa using hnhds), by simpa /-- The intersection of a compact set and a closed set is a compact set. -/ lemma is_compact.inter_right (hs : is_compact s) (ht : is_closed t) : is_compact (s ∩ t) := begin introsI f hnf hstf, obtain ⟨a, hsa, ha⟩ : ∃ a ∈ s, cluster_pt a f := hs (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))), have : a ∈ t := (ht.mem_of_nhds_within_ne_bot $ ha.mono $ le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))), exact ⟨a, ⟨hsa, this⟩, ha⟩ end /-- The intersection of a closed set and a compact set is a compact set. -/ lemma is_compact.inter_left (ht : is_compact t) (hs : is_closed s) : is_compact (s ∩ t) := inter_comm t s ▸ ht.inter_right hs /-- The set difference of a compact set and an open set is a compact set. -/ lemma compact_diff (hs : is_compact s) (ht : is_open t) : is_compact (s \ t) := hs.inter_right (is_closed_compl_iff.mpr ht) /-- A closed subset of a compact set is a compact set. -/ lemma compact_of_is_closed_subset (hs : is_compact s) (ht : is_closed t) (h : t ⊆ s) : is_compact t := inter_eq_self_of_subset_right h ▸ hs.inter_right ht lemma is_compact.adherence_nhdset {f : filter α} (hs : is_compact s) (hf₂ : f ≤ 𝓟 s) (ht₁ : is_open t) (ht₂ : ∀a∈s, cluster_pt a f → a ∈ t) : t ∈ f := classical.by_cases mem_sets_of_eq_bot $ assume : f ⊓ 𝓟 tᶜ ≠ ⊥, let ⟨a, ha, (hfa : cluster_pt a $ f ⊓ 𝓟 tᶜ)⟩ := @@hs this $ inf_le_left_of_le hf₂ in have a ∈ t, from ht₂ a ha (hfa.of_inf_left), have tᶜ ∩ t ∈ 𝓝[tᶜ] a, from inter_mem_nhds_within _ (mem_nhds_sets ht₁ this), have A : 𝓝[tᶜ] a = ⊥, from empty_in_sets_eq_bot.1 $ compl_inter_self t ▸ this, have 𝓝[tᶜ] a ≠ ⊥, from hfa.of_inf_right, absurd A this lemma compact_iff_ultrafilter_le_nhds : is_compact s ↔ (∀f, is_ultrafilter f → f ≤ 𝓟 s → ∃a∈s, f ≤ 𝓝 a) := ⟨assume hs : is_compact s, assume f hf hfs, let ⟨a, ha, h⟩ := @hs _ hf.left hfs in ⟨a, ha, le_of_ultrafilter hf h⟩, assume hs : (∀f, is_ultrafilter f → f ≤ 𝓟 s → ∃a∈s, f ≤ 𝓝 a), assume f hf hfs, let ⟨a, ha, (h : ultrafilter_of f ≤ 𝓝 a)⟩ := hs (ultrafilter_of f) (ultrafilter_ultrafilter_of' hf) (le_trans ultrafilter_of_le hfs) in have cluster_pt a (ultrafilter_of f), from cluster_pt.of_le_nhds' h (ultrafilter_ultrafilter_of' hf).left, ⟨a, ha, this.mono ultrafilter_of_le⟩⟩ /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma is_compact.elim_finite_subcover {ι : Type v} (hs : is_compact s) (U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) : ∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i := is_compact.induction_on hs ⟨∅, empty_subset _⟩ (λ s₁ s₂ hs ⟨t, hs₂⟩, ⟨t, subset.trans hs hs₂⟩) (λ s₁ s₂ ⟨t₁, ht₁⟩ ⟨t₂, ht₂⟩, ⟨t₁ ∪ t₂, by { rw [finset.bUnion_union], exact union_subset_union ht₁ ht₂ }⟩) (λ x hx, let ⟨i, hi⟩ := mem_Union.1 (hsU hx) in ⟨U i, mem_nhds_within.2 ⟨U i, hUo i, hi, inter_subset_left _ _⟩, {i}, by simp⟩) /-- For every family of closed sets whose intersection avoids a compact set, there exists a finite subfamily whose intersection avoids this compact set. -/ lemma is_compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : is_compact s) (Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) : ∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ := let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, (Z i)ᶜ) hZc (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩ /-- To show that a compact set intersects the intersection of a family of closed sets, it is sufficient to show that it intersects every finite subfamily. -/ lemma is_compact.inter_Inter_nonempty {s : set α} {ι : Type v} (hs : is_compact s) (Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : ∀ t : finset ι, (s ∩ ⋂ i ∈ t, Z i).nonempty) : (s ∩ ⋂ i, Z i).nonempty := begin simp only [← ne_empty_iff_nonempty] at hsZ ⊢, apply mt (hs.elim_finite_subfamily_closed Z hZc), push_neg, exact hsZ end /-- Cantor's intersection theorem: the intersection of a directed family of nonempty compact closed sets is nonempty. -/ lemma is_compact.nonempty_Inter_of_directed_nonempty_compact_closed {ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z) (hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, is_compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := begin apply hι.elim, intro i₀, let Z' := λ i, Z i ∩ Z i₀, suffices : (⋂ i, Z' i).nonempty, { exact nonempty.mono (Inter_subset_Inter $ assume i, inter_subset_left (Z i) (Z i₀)) this }, rw ← ne_empty_iff_nonempty, intro H, obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅, from (hZc i₀).elim_finite_subfamily_closed Z' (assume i, is_closed_inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]), obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i, { rcases directed.finset_le hZd t with ⟨i, hi⟩, rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩, use [i₁, hi₁₀], intros j hj, exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ }, suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty, { rw ← ne_empty_iff_nonempty at this, contradiction }, refine nonempty.mono _ (hZn i₁), exact subset_inter hi₁.left (subset_bInter hi₁.right) end /-- Cantor's intersection theorem for sequences indexed by `ℕ`: the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/ lemma is_compact.nonempty_Inter_of_sequence_nonempty_compact_closed (Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i) (hZn : ∀ i, (Z i).nonempty) (hZ0 : is_compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := have Zmono : _, from @monotone_of_monotone_nat (order_dual _) _ Z hZd, have hZd : directed (⊇) Z, from directed_of_sup Zmono, have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i, have hZc : ∀ i, is_compact (Z i), from assume i, compact_of_is_closed_subset hZ0 (hZcl i) (this i), is_compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma is_compact.elim_finite_subcover_image {b : set β} {c : β → set α} (hs : is_compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) : ∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i := begin rcases hs.elim_finite_subcover (λ i, c i.1 : b → set α) _ _ with ⟨d, hd⟩, refine ⟨↑(d.image subtype.val), _, finset.finite_to_set _, _⟩, { intros i hi, erw finset.mem_image at hi, rcases hi with ⟨s, hsd, rfl⟩, exact s.property }, { refine subset.trans hd _, rintros x ⟨_, ⟨s, rfl⟩, ⟨_, ⟨hsd, rfl⟩, H⟩⟩, refine ⟨c s.val, ⟨s.val, _⟩, H⟩, simp [finset.mem_image_of_mem subtype.val hsd] }, { rintro ⟨i, hi⟩, exact hc₁ i hi }, { refine subset.trans hc₂ _, rintros x ⟨_, ⟨i, rfl⟩, ⟨_, ⟨hib, rfl⟩, H⟩⟩, exact ⟨_, ⟨⟨i, hib⟩, rfl⟩, H⟩ }, end /-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem compact_of_finite_subfamily_closed (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) : is_compact s := assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, cluster_pt x f), have hf : ∀x∈s, 𝓝 x ⊓ f = ⊥, by simpa only [cluster_pt, not_exists, not_not, ne_bot], have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t, from assume ⟨x, hxs, hx⟩, have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_in_sets_eq_bot, hf x hxs], let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in have ∅ ∈ 𝓝[t₂] x, from (𝓝[t₂] x).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht, have 𝓝[t₂] x = ⊥, by rwa [empty_in_sets_eq_bot] at this, by simp only [closure_eq_cluster_pts] at hx; exact hx t₂ ht₂ this, let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure) (by simpa [eq_empty_iff_forall_not_mem, not_exists]) in have (⋂i∈t, subtype.val i) ∈ f, from Inter_mem_sets t.finite_to_set $ assume i hi, i.2, have s ∩ (⋂i∈t, subtype.val i) ∈ f, from inter_mem_sets (le_principal_iff.1 hfs) this, have ∅ ∈ f, from mem_sets_of_superset this $ assume x ⟨hxs, hx⟩, let ⟨i, hit, hxi⟩ := (show ∃i ∈ t, x ∉ closure (subtype.val i), by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in have x ∈ closure i.val, from subset_closure (mem_bInter_iff.mp hx i hit), show false, from hxi this, hfn $ by rwa [empty_in_sets_eq_bot] at this /-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/ lemma compact_of_finite_subcover (h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) : is_compact s := compact_of_finite_subfamily_closed $ assume ι Z hZc hsZ, let ⟨t, ht⟩ := h (λ i, (Z i)ᶜ) (assume i, is_open_compl_iff.mpr $ hZc i) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩ /-- A set `s` is compact if and only if for every open cover of `s`, there exists a finite subcover. -/ lemma compact_iff_finite_subcover : is_compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) := ⟨assume hs ι, hs.elim_finite_subcover, compact_of_finite_subcover⟩ /-- A set `s` is compact if and only if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem compact_iff_finite_subfamily_closed : is_compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) := ⟨assume hs ι, hs.elim_finite_subfamily_closed, compact_of_finite_subfamily_closed⟩ @[simp] lemma compact_empty : is_compact (∅ : set α) := assume f hnf hsf, not.elim hnf $ empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf @[simp] lemma compact_singleton {a : α} : is_compact ({a} : set α) := λ f hf hfa, ⟨a, rfl, cluster_pt.of_le_nhds' (hfa.trans $ by simpa only [principal_singleton] using pure_le_nhds a) hf⟩ lemma set.finite.compact_bUnion {s : set β} {f : β → set α} (hs : finite s) (hf : ∀i ∈ s, is_compact (f i)) : is_compact (⋃i ∈ s, f i) := compact_of_finite_subcover $ assume ι U hUo hsU, have ∀i : subtype s, ∃t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo (calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi ... ⊆ ⋃j, U j : hsU), let ⟨finite_subcovers, h⟩ := axiom_of_choice this in by haveI : fintype (subtype s) := hs.fintype; exact let t := finset.bind finset.univ finite_subcovers in have (⋃i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from bUnion_subset $ assume i hi, calc f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩) ... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $ assume j hj, finset.mem_bind.mpr ⟨_, finset.mem_univ _, hj⟩, ⟨t, this⟩ lemma compact_Union {f : β → set α} [fintype β] (h : ∀i, is_compact (f i)) : is_compact (⋃i, f i) := by rw ← bUnion_univ; exact finite_univ.compact_bUnion (λ i _, h i) lemma set.finite.is_compact (hs : finite s) : is_compact s := bUnion_of_singleton s ▸ hs.compact_bUnion (λ _ _, compact_singleton) lemma is_compact.union (hs : is_compact s) (ht : is_compact t) : is_compact (s ∪ t) := by rw union_eq_Union; exact compact_Union (λ b, by cases b; assumption) lemma is_compact.insert (hs : is_compact s) (a) : is_compact (insert a s) := compact_singleton.union hs /-- `filter.cocompact` is the filter generated by complements to compact sets. -/ def filter.cocompact (α : Type*) [topological_space α] : filter α := ⨅ (s : set α) (hs : is_compact s), 𝓟 (sᶜ) lemma filter.has_basis_cocompact : (filter.cocompact α).has_basis is_compact compl := has_basis_binfi_principal' (λ s hs t ht, ⟨s ∪ t, hs.union ht, compl_subset_compl.2 (subset_union_left s t), compl_subset_compl.2 (subset_union_right s t)⟩) ⟨∅, compact_empty⟩ lemma filter.mem_cocompact : s ∈ filter.cocompact α ↔ ∃ t, is_compact t ∧ tᶜ ⊆ s := filter.has_basis_cocompact.mem_iff.trans $ exists_congr $ λ t, exists_prop lemma filter.mem_cocompact' : s ∈ filter.cocompact α ↔ ∃ t, is_compact t ∧ sᶜ ⊆ t := filter.mem_cocompact.trans $ exists_congr $ λ t, and_congr_right $ λ ht, compl_subset_comm lemma is_compact.compl_mem_cocompact (hs : is_compact s) : sᶜ ∈ filter.cocompact α := filter.has_basis_cocompact.mem_of_mem hs section tube_lemma variables [topological_space β] /-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes a product of an open neighborhood of `s` by an open neighborhood of `t`. -/ def nhds_contain_boxes (s : set α) (t : set β) : Prop := ∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n), ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n lemma nhds_contain_boxes.symm {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := assume H n hn hp, let ⟨u, v, uo, vo, su, tv, p⟩ := H (prod.swap ⁻¹' n) (hn.preimage continuous_swap) (by rwa [←image_subset_iff, image_swap_prod]) in ⟨v, u, vo, uo, tv, su, by rwa [←image_subset_iff, image_swap_prod] at p⟩ lemma nhds_contain_boxes.comm {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm lemma nhds_contain_boxes_of_singleton {x : α} {y : β} : nhds_contain_boxes ({x} : set α) ({y} : set β) := assume n hn hp, let ⟨u, v, uo, vo, xu, yv, hp'⟩ := is_open_prod_iff.mp hn x y (hp $ by simp) in ⟨u, v, uo, vo, by simpa, by simpa, hp'⟩ lemma nhds_contain_boxes_of_compact {s : set α} (hs : is_compact s) (t : set β) (H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t := assume n hn hp, have ∀x : subtype s, ∃uv : set α × set β, is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n, from assume ⟨x, hx⟩, have set.prod {x} t ⊆ n, from subset.trans (prod_mono (by simpa) (subset.refl _)) hp, let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩, let ⟨uvs, h⟩ := classical.axiom_of_choice this in have us_cover : s ⊆ ⋃i, (uvs i).1, from assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1), let ⟨s0, s0_cover⟩ := hs.elim_finite_subcover _ (λi, (h i).1) us_cover in let u := ⋃(i ∈ s0), (uvs i).1 in let v := ⋂(i ∈ s0), (uvs i).2 in have is_open u, from is_open_bUnion (λi _, (h i).1), have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1), have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1), have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩, have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx', let ⟨i,is0,hi⟩ := this in (h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩, ⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩ /-- If `s` and `t` are compact sets and `n` is an open neighborhood of `s × t`, then there exist open neighborhoods `u ⊇ s` and `v ⊇ t` such that `u × v ⊆ n`. -/ lemma generalized_tube_lemma {s : set α} (hs : is_compact s) {t : set β} (ht : is_compact t) {n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) : ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n := have _, from nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $ nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton, this n hn hp end tube_lemma /-- Type class for compact spaces. Separation is sometimes included in the definition, especially in the French literature, but we do not include it here. -/ class compact_space (α : Type*) [topological_space α] : Prop := (compact_univ : is_compact (univ : set α)) lemma compact_univ [h : compact_space α] : is_compact (univ : set α) := h.compact_univ lemma cluster_point_of_compact [compact_space α] (f : filter α) [ne_bot f] : ∃ x, cluster_pt x f := by simpa using compact_univ (show f ≤ 𝓟 univ, by simp) theorem compact_space_of_finite_subfamily_closed {α : Type u} [topological_space α] (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → (⋂ i, Z i) = ∅ → (∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅)) : compact_space α := { compact_univ := begin apply compact_of_finite_subfamily_closed, intros ι Z, specialize h Z, simpa using h end } lemma is_closed.compact [compact_space α] {s : set α} (h : is_closed s) : is_compact s := compact_of_is_closed_subset compact_univ h (subset_univ _) variables [topological_space β] lemma is_compact.image_of_continuous_on {f : α → β} (hs : is_compact s) (hf : continuous_on f s) : is_compact (f '' s) := begin intros l lne ls, have : ne_bot (l.comap f ⊓ 𝓟 s) := comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls), obtain ⟨a, has, ha⟩ : ∃ a ∈ s, cluster_pt a (l.comap f ⊓ 𝓟 s) := @@hs this inf_le_right, use [f a, mem_image_of_mem f has], have : tendsto f (𝓝 a ⊓ (comap f l ⊓ 𝓟 s)) (𝓝 (f a) ⊓ l), { convert (hf a has).inf (@tendsto_comap _ _ f l) using 1, rw nhds_within, ac_refl }, exact @@tendsto.ne_bot _ this ha, end lemma is_compact.image {f : α → β} (hs : is_compact s) (hf : continuous f) : is_compact (f '' s) := hs.image_of_continuous_on hf.continuous_on lemma compact_range [compact_space α] {f : α → β} (hf : continuous f) : is_compact (range f) := by rw ← image_univ; exact compact_univ.image hf /-- If X is is_compact then pr₂ : X × Y → Y is a closed map -/ theorem is_closed_proj_of_compact {X : Type*} [topological_space X] [compact_space X] {Y : Type*} [topological_space Y] : is_closed_map (prod.snd : X × Y → Y) := begin set πX := (prod.fst : X × Y → X), set πY := (prod.snd : X × Y → Y), assume C (hC : is_closed C), rw is_closed_iff_cluster_pt at hC ⊢, assume y (y_closure : cluster_pt y $ 𝓟 (πY '' C)), have : ne_bot (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)), { suffices : ne_bot (map πY (comap πY (𝓝 y) ⊓ 𝓟 C)), by simpa only [map_ne_bot_iff], calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) = 𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _ ... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal ... ≠ ⊥ : y_closure }, resetI, obtain ⟨x, hx⟩ : ∃ x, cluster_pt x (map πX (comap πY (𝓝 y) ⊓ 𝓟 C)), from cluster_point_of_compact _, refine ⟨⟨x, y⟩, _, by simp [πY]⟩, apply hC, rw [cluster_pt, ← filter.map_ne_bot_iff πX], calc map πX (𝓝 (x, y) ⊓ 𝓟 C) = map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod] ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull ... = 𝓝 x ⊓ map πX (comap πY (𝓝 y) ⊓ 𝓟 C) : by rw inf_comm ... ≠ ⊥ : hx, end lemma embedding.compact_iff_compact_image {f : α → β} (hf : embedding f) : is_compact s ↔ is_compact (f '' s) := iff.intro (assume h, h.image hf.continuous) $ assume h, begin rw compact_iff_ultrafilter_le_nhds at ⊢ h, intros u hu us', let u' : filter β := map f u, have : u' ≤ 𝓟 (f '' s), begin rw [map_le_iff_le_comap, comap_principal], convert us', exact preimage_image_eq _ hf.inj end, rcases h u' (ultrafilter_map hu) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩, refine ⟨a, ha, _⟩, rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap] end lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} : is_compact s ↔ is_compact ((coe : _ → α) '' s) := embedding_subtype_coe.compact_iff_compact_image lemma compact_iff_compact_univ {s : set α} : is_compact s ↔ is_compact (univ : set s) := by rw [compact_iff_compact_in_subtype, image_univ, subtype.range_coe]; refl lemma compact_iff_compact_space {s : set α} : is_compact s ↔ compact_space s := compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩ lemma is_compact.prod {s : set α} {t : set β} (hs : is_compact s) (ht : is_compact t) : is_compact (set.prod s t) := begin rw compact_iff_ultrafilter_le_nhds at hs ht ⊢, intros f hf hfs, rw le_principal_iff at hfs, rcases hs (map prod.fst f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.1)⟩)) with ⟨a, sa, ha⟩, rcases ht (map prod.snd f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.2)⟩)) with ⟨b, tb, hb⟩, rw map_le_iff_le_comap at ha hb, refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩, rw nhds_prod_eq, exact le_inf ha hb end /-- Finite topological spaces are compact. -/ @[priority 100] instance fintype.compact_space [fintype α] : compact_space α := { compact_univ := set.finite_univ.is_compact } /-- The product of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α × β) := ⟨by { rw ← univ_prod_univ, exact compact_univ.prod compact_univ }⟩ /-- The disjoint union of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) := ⟨begin rw ← range_inl_union_range_inr, exact (compact_range continuous_inl).union (compact_range continuous_inr) end⟩ section tychonoff variables {ι : Type*} {π : ι → Type*} [∀i, topological_space (π i)] /-- Tychonoff's theorem -/ lemma compact_pi_infinite {s : Πi:ι, set (π i)} : (∀i, is_compact (s i)) → is_compact {x : Πi:ι, π i | ∀i, x i ∈ s i} := begin simp only [compact_iff_ultrafilter_le_nhds, nhds_pi, exists_prop, mem_set_of_eq, le_infi_iff, le_principal_iff], intros h f hf hfs, have : ∀i:ι, ∃a, a∈s i ∧ tendsto (λx:Πi:ι, π i, x i) f (𝓝 a), { refine λ i, h i _ (ultrafilter_map hf) (mem_map.2 _), exact mem_sets_of_superset hfs (λ x hx, hx i) }, choose a ha, exact ⟨a, assume i, (ha i).left, assume i, (ha i).right.le_comap⟩ end /-- A version of Tychonoff's theorem that uses `set.pi`. -/ lemma compact_univ_pi {s : Πi:ι, set (π i)} (h : ∀i, is_compact (s i)) : is_compact (set.pi set.univ s) := by { convert compact_pi_infinite h, simp only [pi, forall_prop_of_true, mem_univ] } instance pi.compact [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) := ⟨begin have A : is_compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} := compact_pi_infinite (λi, compact_univ), have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp, rwa this at A, end⟩ end tychonoff instance quot.compact_space {r : α → α → Prop} [compact_space α] : compact_space (quot r) := ⟨by { rw ← range_quot_mk, exact compact_range continuous_quot_mk }⟩ instance quotient.compact_space {s : setoid α} [compact_space α] : compact_space (quotient s) := quot.compact_space /-- There are various definitions of "locally compact space" in the literature, which agree for Hausdorff spaces but not in general. This one is the precise condition on X needed for the evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the compact-open topology. -/ class locally_compact_space (α : Type*) [topological_space α] : Prop := (local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ is_compact s) /-- A reformulation of the definition of locally compact space: In a locally compact space, every open set containing `x` has a compact subset containing `x` in its interior. -/ lemma exists_compact_subset [locally_compact_space α] {x : α} {U : set α} (hU : is_open U) (hx : x ∈ U) : ∃ (K : set α), is_compact K ∧ x ∈ interior K ∧ K ⊆ U := begin rcases locally_compact_space.local_compact_nhds x U _ with ⟨K, h1K, h2K, h3K⟩, { refine ⟨K, h3K, _, h2K⟩, rwa [ mem_interior_iff_mem_nhds] }, rwa [← mem_interior_iff_mem_nhds, hU.interior_eq] end lemma is_ultrafilter.le_nhds_Lim [compact_space α] (F : ultrafilter α) : F.1 ≤ nhds (@Lim _ _ F.1.nonempty_of_ne_bot F.1) := begin rcases compact_iff_ultrafilter_le_nhds.mp compact_univ F.1 F.2 (by simp) with ⟨x, -, h⟩, exact le_nhds_Lim ⟨x,h⟩, end end compact section clopen /-- A set is clopen if it is both open and closed. -/ def is_clopen (s : set α) : Prop := is_open s ∧ is_closed s theorem is_clopen_union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) := ⟨is_open_union hs.1 ht.1, is_closed_union hs.2 ht.2⟩ theorem is_clopen_inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) := ⟨is_open_inter hs.1 ht.1, is_closed_inter hs.2 ht.2⟩ @[simp] theorem is_clopen_empty : is_clopen (∅ : set α) := ⟨is_open_empty, is_closed_empty⟩ @[simp] theorem is_clopen_univ : is_clopen (univ : set α) := ⟨is_open_univ, is_closed_univ⟩ theorem is_clopen_compl {s : set α} (hs : is_clopen s) : is_clopen sᶜ := ⟨hs.2, is_closed_compl_iff.2 hs.1⟩ @[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen sᶜ ↔ is_clopen s := ⟨λ h, compl_compl s ▸ is_clopen_compl h, is_clopen_compl⟩ theorem is_clopen_diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s \ t) := is_clopen_inter hs (is_clopen_compl ht) end clopen section preirreducible /-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/ def is_preirreducible (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- An irreducible set `s` is one that is nonempty and where there is no non-trivial pair of disjoint opens on `s`. -/ def is_irreducible (s : set α) : Prop := s.nonempty ∧ is_preirreducible s lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) : s.nonempty := h.1 lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) : is_preirreducible s := h.2 theorem is_preirreducible_empty : is_preirreducible (∅ : set α) := λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) := ⟨singleton_nonempty x, λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3; substs y z; exact ⟨x, rfl, h2, h4⟩⟩ theorem is_preirreducible.closure {s : set α} (H : is_preirreducible s) : is_preirreducible (closure s) := λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ lemma is_irreducible.closure {s : set α} (h : is_irreducible s) : is_irreducible (closure s) := ⟨h.nonempty.closure, h.is_preirreducible.closure⟩ theorem exists_preirreducible (s : set α) (H : is_preirreducible s) : ∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t := let ⟨m, hm, hsm, hmm⟩ := zorn.zorn_subset₀ {t : set α | is_preirreducible t} (λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in ⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩, let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy, ⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in or.cases_on (zorn.chain.total hcc hpc hqc) (assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv ⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩) (assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv ⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩), λ x hxc, set.subset_sUnion_of_mem hxc⟩) s H in ⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩ /-- A maximal irreducible set that contains a given point. -/ def irreducible_component (x : α) : set α := classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) lemma irreducible_component_property (x : α) : is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧ ∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) := classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x := singleton_subset_iff.1 (irreducible_component_property x).2.1 theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) := ⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩ theorem eq_irreducible_component {x : α} : ∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x := (irreducible_component_property x).2.2 theorem is_closed_irreducible_component {x : α} : is_closed (irreducible_component x) := closure_eq_iff_is_closed.1 $ eq_irreducible_component is_irreducible_irreducible_component.is_preirreducible.closure subset_closure /-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/ class preirreducible_space (α : Type u) [topological_space α] : Prop := (is_preirreducible_univ [] : is_preirreducible (univ : set α)) /-- An irreducible space is one that is nonempty and where there is no non-trivial pair of disjoint opens. -/ class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop := (to_nonempty [] : nonempty α) attribute [instance, priority 50] irreducible_space.to_nonempty -- see Note [lower instance priority] theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} : is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preirreducible_space.is_preirreducible_univ α _ _ s t theorem is_preirreducible.image [topological_space β] {s : set α} (H : is_preirreducible s) (f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) := begin rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩, rw ← set.mem_preimage at hxu hyv, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, have := H u' v' hu' hv', rw [set.inter_comm s u', ← u'_eq] at this, rw [set.inter_comm s v', ← v'_eq] at this, rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩, refine ⟨f z, mem_image_of_mem f hzs, _, _⟩, all_goals { rw ← set.mem_preimage, apply set.mem_of_mem_inter_left, show z ∈ _ ∩ s, simp [*] } end theorem is_irreducible.image [topological_space β] {s : set α} (H : is_irreducible s) (f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preirreducible.image f hf⟩ lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) : preirreducible_space s := { is_preirreducible_univ := begin intros u v hu hv hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩ end } lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) : irreducible_space s := { is_preirreducible_univ := (subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ, to_nonempty := h.nonempty.to_subtype } /-- A set `s` is irreducible if and only if for every finite collection of open sets all of whose members intersect `s`, `s` also intersects the intersection of the entire collection (i.e., there is an element of `s` contained in every member of the collection). -/ lemma is_irreducible_iff_sInter {s : set α} : is_irreducible s ↔ ∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty), (s ∩ ⋂₀ ↑U).nonempty := begin split; intro h, { intro U, apply finset.induction_on U, { intros, simpa using h.nonempty }, { intros u U hu IH hU H, rw [finset.coe_insert, sInter_insert], apply h.2, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sInter (finset.finite_to_set U), intros, solve_by_elim [finset.mem_insert_of_mem] }, { solve_by_elim [finset.mem_insert_self] }, { apply IH, all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } }, { split, { simpa using h ∅ _ _; intro u; simp }, intros u v hu hv hu' hv', simpa using h {u,v} _ _, all_goals { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption } } end /-- A set is preirreducible if and only if for every cover by two closed sets, it is contained in one of the two covering sets. -/ lemma is_preirreducible_iff_closed_union_closed {s : set α} : is_preirreducible s ↔ ∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ := begin split, all_goals { intros h t₁ t₂ ht₁ ht₂, specialize h t₁ᶜ t₂ᶜ, simp only [is_open_compl_iff, is_closed_compl_iff] at h, specialize h ht₁ ht₂ }, { contrapose!, simp only [not_subset], rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩, rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩, rw ← compl_union at hz', exact ⟨z, hz, hz'⟩ }, { rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, rw ← compl_inter at h, delta set.nonempty, rw imp_iff_not_or at h, contrapose! h, split, { intros z hz hz', exact h z ⟨hz, hz'⟩ }, { split; intro H; refine H _ ‹_›; assumption } } end /-- A set is irreducible if and only if for every cover by a finite collection of closed sets, it is contained in one of the members of the collection. -/ lemma is_irreducible_iff_sUnion_closed {s : set α} : is_irreducible s ↔ ∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z), ∃ z ∈ Z, s ⊆ z := begin rw [is_irreducible, is_preirreducible_iff_closed_union_closed], split; intro h, { intro Z, apply finset.induction_on Z, { intros, rw [finset.coe_empty, sUnion_empty] at H, rcases h.1 with ⟨x, hx⟩, exfalso, tauto }, { intros z Z hz IH hZ H, cases h.2 z (⋃₀ ↑Z) _ _ _ with h' h', { exact ⟨z, finset.mem_insert_self _ _, h'⟩ }, { rcases IH _ h' with ⟨z', hz', hsz'⟩, { exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { rw sUnion_eq_bUnion, apply is_closed_bUnion (finset.finite_to_set Z), { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { simpa using H } } }, { split, { by_contradiction hs, simpa using h ∅ _ _, { intro z, simp }, { simpa [set.nonempty] using hs } }, intros z₁ z₂ hz₁ hz₂ H, have := h {z₁, z₂} _ _, simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this, { rcases this with ⟨z, rfl|rfl, hz⟩; tauto }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using H } } end end preirreducible section preconnected /-- A preconnected set is one where there is no non-trivial open partition. -/ def is_preconnected (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- A connected set is one that is nonempty and where there is no non-trivial open partition. -/ def is_connected (s : set α) : Prop := s.nonempty ∧ is_preconnected s lemma is_connected.nonempty {s : set α} (h : is_connected s) : s.nonempty := h.1 lemma is_connected.is_preconnected {s : set α} (h : is_connected s) : is_preconnected s := h.2 theorem is_preirreducible.is_preconnected {s : set α} (H : is_preirreducible s) : is_preconnected s := λ _ _ hu hv _, H _ _ hu hv theorem is_irreducible.is_connected {s : set α} (H : is_irreducible s) : is_connected s := ⟨H.nonempty, H.is_preirreducible.is_preconnected⟩ theorem is_preconnected_empty : is_preconnected (∅ : set α) := is_preirreducible_empty.is_preconnected theorem is_connected_singleton {x} : is_connected ({x} : set α) := is_irreducible_singleton.is_connected /-- If any point of a set is joined to a fixed point by a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall {s : set α} (x : α) (H : ∀ y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨z, zs, zu⟩ ⟨y, ys, yv⟩, have xs : x ∈ s, by { rcases H y ys with ⟨t, ts, xt, yt, ht⟩, exact ts xt }, wlog xu : x ∈ u := hs xs using [u v y z, v u z y], rcases H y ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- If any two points of a set are contained in a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall_pair {s : set α} (H : ∀ x y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, rcases H x y xs ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- A union of a family of preconnected sets with a common point is preconnected as well. -/ theorem is_preconnected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s) (H2 : ∀ s ∈ c, is_preconnected s) : is_preconnected (⋃₀ c) := begin apply is_preconnected_of_forall x, rintros y ⟨s, sc, ys⟩, exact ⟨s, subset_sUnion_of_mem sc, H1 s sc, ys, H2 s sc⟩ end theorem is_preconnected.union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t) (H3 : is_preconnected s) (H4 : is_preconnected t) : is_preconnected (s ∪ t) := sUnion_pair s t ▸ is_preconnected_sUnion x {s, t} (by rintro r (rfl | rfl | h); assumption) (by rintro r (rfl | rfl | h); assumption) theorem is_connected.union {s t : set α} (H : (s ∩ t).nonempty) (Hs : is_connected s) (Ht : is_connected t) : is_connected (s ∪ t) := begin rcases H with ⟨x, hx⟩, refine ⟨⟨x, mem_union_left t (mem_of_mem_inter_left hx)⟩, _⟩, exact is_preconnected.union x (mem_of_mem_inter_left hx) (mem_of_mem_inter_right hx) Hs.is_preconnected Ht.is_preconnected end theorem is_preconnected.closure {s : set α} (H : is_preconnected s) : is_preconnected (closure s) := λ u v hu hv hcsuv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans subset_closure hcsuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ theorem is_connected.closure {s : set α} (H : is_connected s) : is_connected (closure s) := ⟨H.nonempty.closure, H.is_preconnected.closure⟩ theorem is_preconnected.image [topological_space β] {s : set α} (H : is_preconnected s) (f : α → β) (hf : continuous_on f s) : is_preconnected (f '' s) := begin -- Unfold/destruct definitions in hypotheses rintros u v hu hv huv ⟨_, ⟨x, xs, rfl⟩, xu⟩ ⟨_, ⟨y, ys, rfl⟩, yv⟩, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, -- Reformulate `huv : f '' s ⊆ u ∪ v` in terms of `u'` and `v'` replace huv : s ⊆ u' ∪ v', { rw [image_subset_iff, preimage_union] at huv, replace huv := subset_inter huv (subset.refl _), rw [inter_distrib_right, u'_eq, v'_eq, ← inter_distrib_right] at huv, exact (subset_inter_iff.1 huv).1 }, -- Now `s ⊆ u' ∪ v'`, so we can apply `‹is_preconnected s›` obtain ⟨z, hz⟩ : (s ∩ (u' ∩ v')).nonempty, { refine H u' v' hu' hv' huv ⟨x, _⟩ ⟨y, _⟩; rw inter_comm, exacts [u'_eq ▸ ⟨xu, xs⟩, v'_eq ▸ ⟨yv, ys⟩] }, rw [← inter_self s, inter_assoc, inter_left_comm s u', ← inter_assoc, inter_comm s, inter_comm s, ← u'_eq, ← v'_eq] at hz, exact ⟨f z, ⟨z, hz.1.2, rfl⟩, hz.1.1, hz.2.1⟩ end theorem is_connected.image [topological_space β] {s : set α} (H : is_connected s) (f : α → β) (hf : continuous_on f s) : is_connected (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preconnected.image f hf⟩ theorem is_preconnected_closed_iff {s : set α} : is_preconnected s ↔ ∀ t t', is_closed t → is_closed t' → s ⊆ t ∪ t' → (s ∩ t).nonempty → (s ∩ t').nonempty → (s ∩ (t ∩ t')).nonempty := ⟨begin rintros h t t' ht ht' htt' ⟨x, xs, xt⟩ ⟨y, ys, yt'⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xt' : x ∉ t', from (h' xs).elim (absurd xt) id, have yt : y ∉ t, from (h' ys).elim id (absurd yt'), have := ne_empty_iff_nonempty.2 (h tᶜ t'ᶜ (is_open_compl_iff.2 ht) (is_open_compl_iff.2 ht') h' ⟨y, ys, yt⟩ ⟨x, xs, xt'⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end, begin rintros h u v hu hv huv ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xv : x ∉ v, from (h' xs).elim (absurd xu) id, have yu : y ∉ u, from (h' ys).elim id (absurd yv), have := ne_empty_iff_nonempty.2 (h uᶜ vᶜ (is_closed_compl_iff.2 hu) (is_closed_compl_iff.2 hv) h' ⟨y, ys, yu⟩ ⟨x, xs, xv⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end⟩ /-- The connected component of a point is the maximal connected set that contains this point. -/ def connected_component (x : α) : set α := ⋃₀ { s : set α | is_preconnected s ∧ x ∈ s } /-- The connected component of a point inside a set. -/ def connected_component_in (F : set α) (x : F) : set α := coe '' (connected_component x) theorem mem_connected_component {x : α} : x ∈ connected_component x := mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton.is_preconnected, mem_singleton x⟩ theorem is_connected_connected_component {x : α} : is_connected (connected_component x) := ⟨⟨x, mem_connected_component⟩, is_preconnected_sUnion x _ (λ _, and.right) (λ _, and.left)⟩ theorem subset_connected_component {x : α} {s : set α} (H1 : is_preconnected s) (H2 : x ∈ s) : s ⊆ connected_component x := λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩ theorem is_closed_connected_component {x : α} : is_closed (connected_component x) := closure_eq_iff_is_closed.1 $ subset.antisymm (subset_connected_component is_connected_connected_component.closure.is_preconnected (subset_closure mem_connected_component)) subset_closure theorem irreducible_component_subset_connected_component {x : α} : irreducible_component x ⊆ connected_component x := subset_connected_component is_irreducible_irreducible_component.is_connected.is_preconnected mem_irreducible_component /-- A preconnected space is one where there is no non-trivial open partition. -/ class preconnected_space (α : Type u) [topological_space α] : Prop := (is_preconnected_univ : is_preconnected (univ : set α)) export preconnected_space (is_preconnected_univ) /-- A connected space is a nonempty one where there is no non-trivial open partition. -/ class connected_space (α : Type u) [topological_space α] extends preconnected_space α : Prop := (to_nonempty : nonempty α) attribute [instance, priority 50] connected_space.to_nonempty -- see Note [lower instance priority] lemma is_connected_range [topological_space β] [connected_space α] {f : α → β} (h : continuous f) : is_connected (range f) := begin inhabit α, rw ← image_univ, exact ⟨⟨f (default α), mem_image_of_mem _ (mem_univ _)⟩, is_preconnected.image is_preconnected_univ _ h.continuous_on⟩ end lemma connected_space_iff_connected_component : connected_space α ↔ ∃ x : α, connected_component x = univ := begin split, { rintros ⟨h, ⟨x⟩⟩, exactI ⟨x, eq_univ_of_univ_subset $ subset_connected_component is_preconnected_univ (mem_univ x)⟩ }, { rintros ⟨x, h⟩, haveI : preconnected_space α := ⟨by {rw ← h, exact is_connected_connected_component.2 }⟩, exact ⟨⟨x⟩⟩ } end @[priority 100] -- see Note [lower instance priority] instance preirreducible_space.preconnected_space (α : Type u) [topological_space α] [preirreducible_space α] : preconnected_space α := ⟨(preirreducible_space.is_preirreducible_univ α).is_preconnected⟩ @[priority 100] -- see Note [lower instance priority] instance irreducible_space.connected_space (α : Type u) [topological_space α] [irreducible_space α] : connected_space α := { to_nonempty := irreducible_space.to_nonempty α } theorem nonempty_inter [preconnected_space α] {s t : set α} : is_open s → is_open t → s ∪ t = univ → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preconnected_space.is_preconnected_univ α _ _ s t theorem is_clopen_iff [preconnected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ := ⟨λ hs, classical.by_contradiction $ λ h, have h1 : s ≠ ∅ ∧ sᶜ ≠ ∅, from ⟨mt or.inl h, mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩, let ⟨_, h2, h3⟩ := nonempty_inter hs.1 hs.2 (union_compl_self s) (ne_empty_iff_nonempty.1 h1.1) (ne_empty_iff_nonempty.1 h1.2) in h3 h2, by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩ lemma eq_univ_of_nonempty_clopen [preconnected_space α] {s : set α} (h : s.nonempty) (h' : is_clopen s) : s = univ := by { rw is_clopen_iff at h', finish [h.ne_empty] } lemma subtype.preconnected_space {s : set α} (h : is_preconnected s) : preconnected_space s := { is_preconnected_univ := begin intros u v hu hv hs hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv _ ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩, intros z hz, rcases hs (set.mem_univ ⟨z, hz⟩) with hzu|hzv, { left, assumption }, { right, assumption } end } lemma subtype.connected_space {s : set α} (h : is_connected s) : connected_space s := { is_preconnected_univ := (subtype.preconnected_space h.is_preconnected).is_preconnected_univ, to_nonempty := h.nonempty.to_subtype } lemma is_preconnected_iff_preconnected_space {s : set α} : is_preconnected s ↔ preconnected_space s := ⟨subtype.preconnected_space, begin introI, simpa using is_preconnected_univ.image (coe : s → α) continuous_subtype_coe.continuous_on end⟩ lemma is_connected_iff_connected_space {s : set α} : is_connected s ↔ connected_space s := ⟨subtype.connected_space, λ h, ⟨nonempty_subtype.mp h.2, is_preconnected_iff_preconnected_space.mpr h.1⟩⟩ /-- A set `s` is preconnected if and only if for every cover by two open sets that are disjoint on `s`, it is contained in one of the two covering sets. -/ lemma is_preconnected_iff_subset_of_disjoint {s : set α} : is_preconnected s ↔ ∀ (u v : set α) (hu : is_open u) (hv : is_open v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅), s ⊆ u ∨ s ⊆ v := begin split; intro h, { intros u v hu hv hs huv, specialize h u v hu hv hs, contrapose! huv, rw ne_empty_iff_nonempty, simp [not_subset] at huv, rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩, have hxv : x ∈ v := or_iff_not_imp_left.mp (hs hxs) hxu, have hyu : y ∈ u := or_iff_not_imp_right.mp (hs hys) hyv, exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ }, { intros u v hu hv hs hsu hsv, rw ← ne_empty_iff_nonempty, intro H, specialize h u v hu hv hs H, contrapose H, apply ne_empty_iff_nonempty.mpr, cases h, { rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ }, { rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } } end /-- A set `s` is connected if and only if for every cover by a finite collection of open sets that are pairwise disjoint on `s`, it is contained in one of the members of the collection. -/ lemma is_connected_iff_sUnion_disjoint_open {s : set α} : is_connected s ↔ ∀ (U : finset (set α)) (H : ∀ (u v : set α), u ∈ U → v ∈ U → (s ∩ (u ∩ v)).nonempty → u = v) (hU : ∀ u ∈ U, is_open u) (hs : s ⊆ ⋃₀ ↑U), ∃ u ∈ U, s ⊆ u := begin rw [is_connected, is_preconnected_iff_subset_of_disjoint], split; intro h, { intro U, apply finset.induction_on U, { rcases h.left, suffices : s ⊆ ∅ → false, { simpa }, intro, solve_by_elim }, { intros u U hu IH hs hU H, rw [finset.coe_insert, sUnion_insert] at H, cases h.2 u (⋃₀ ↑U) _ _ H _ with hsu hsU, { exact ⟨u, finset.mem_insert_self _ _, hsu⟩ }, { rcases IH _ _ hsU with ⟨v, hvU, hsv⟩, { exact ⟨v, finset.mem_insert_of_mem hvU, hsv⟩ }, { intros, apply hs; solve_by_elim [finset.mem_insert_of_mem] }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sUnion, intros, solve_by_elim [finset.mem_insert_of_mem] }, { apply eq_empty_of_subset_empty, rintro x ⟨hxs, hxu, hxU⟩, rw mem_sUnion at hxU, rcases hxU with ⟨v, hvU, hxv⟩, rcases hs u v (finset.mem_insert_self _ _) (finset.mem_insert_of_mem hvU) _ with rfl, { contradiction }, { exact ⟨x, hxs, hxu, hxv⟩ } } } }, { split, { rw ← ne_empty_iff_nonempty, by_contradiction hs, push_neg at hs, subst hs, simpa using h ∅ _ _ _; simp }, intros u v hu hv hs hsuv, rcases h {u, v} _ _ _ with ⟨t, ht, ht'⟩, { rw [finset.mem_insert, finset.mem_singleton] at ht, rcases ht with rfl|rfl; tauto }, { intros t₁ t₂ ht₁ ht₂ hst, rw ← ne_empty_iff_nonempty at hst, rw [finset.mem_insert, finset.mem_singleton] at ht₁ ht₂, rcases ht₁ with rfl|rfl; rcases ht₂ with rfl|rfl, all_goals { refl <|> contradiction <|> skip }, rw inter_comm t₁ at hst, contradiction }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using hs } } end end preconnected section totally_disconnected /-- A set is called totally disconnected if all of its connected components are singletons. -/ def is_totally_disconnected (s : set α) : Prop := ∀ t, t ⊆ s → is_preconnected t → subsingleton t theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) := λ t ht _, ⟨λ ⟨_, h⟩, (ht h).elim⟩ theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) := λ t ht _, ⟨λ ⟨p, hp⟩ ⟨q, hq⟩, subtype.eq $ show p = q, from (eq_of_mem_singleton (ht hp)).symm ▸ (eq_of_mem_singleton (ht hq)).symm⟩ /-- A space is totally disconnected if all of its connected components are singletons. -/ class totally_disconnected_space (α : Type u) [topological_space α] : Prop := (is_totally_disconnected_univ : is_totally_disconnected (univ : set α)) end totally_disconnected section totally_separated /-- A set `s` is called totally separated if any two points of this set can be separated by two disjoint open sets covering `s`. -/ def is_totally_separated (s : set α) : Prop := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅ theorem is_totally_separated_empty : is_totally_separated (∅ : set α) := λ x, false.elim theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) := λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim theorem is_totally_disconnected_of_is_totally_separated {s : set α} (H : is_totally_separated s) : is_totally_disconnected s := λ t hts ht, ⟨λ ⟨x, hxt⟩ ⟨y, hyt⟩, subtype.eq $ classical.by_contradiction $ assume hxy : x ≠ y, let ⟨u, v, hu, hv, hxu, hyv, hsuv, huv⟩ := H x (hts hxt) y (hts hyt) hxy in let ⟨r, hrt, hruv⟩ := ht u v hu hv (subset.trans hts hsuv) ⟨x, hxt, hxu⟩ ⟨y, hyt, hyv⟩ in (ext_iff.1 huv r).1 hruv⟩ /-- A space is totally separated if any two points can be separated by two disjoint open sets covering the whole space. -/ class totally_separated_space (α : Type u) [topological_space α] : Prop := (is_totally_separated_univ [] : is_totally_separated (univ : set α)) @[priority 100] -- see Note [lower instance priority] instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α] [totally_separated_space α] : totally_disconnected_space α := ⟨is_totally_disconnected_of_is_totally_separated $ totally_separated_space.is_totally_separated_univ α⟩ @[priority 100] -- see Note [lower instance priority] instance totally_separated_space.of_discrete (α : Type*) [topological_space α] [discrete_topology α] : totally_separated_space α := ⟨λ a _ b _ h, ⟨{b}ᶜ, {b}, is_open_discrete _, is_open_discrete _, by simpa⟩⟩ end totally_separated
da6ee50e9fd1bfbc154dac457f2904e86f4d374f
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/star/module.lean
7ed9bcc4b125d98c5e44ead2327beddacdf24917
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,529
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser, Frédéric Dupuis -/ import algebra.star.self_adjoint import algebra.module.equiv import linear_algebra.prod /-! # The star operation, bundled as a star-linear equiv We define `star_linear_equiv`, which is the star operation bundled as a star-linear map. It is defined on a star algebra `A` over the base ring `R`. This file also provides some lemmas that need `algebra.module.basic` imported to prove. ## TODO - Define `star_linear_equiv` for noncommutative `R`. We only the commutative case for now since, in the noncommutative case, the ring hom needs to reverse the order of multiplication. This requires a ring hom of type `R →+* Rᵐᵒᵖ`, which is very undesirable in the commutative case. One way out would be to define a new typeclass `is_op R S` and have an instance `is_op R R` for commutative `R`. - Also note that such a definition involving `Rᵐᵒᵖ` or `is_op R S` would require adding the appropriate `ring_hom_inv_pair` instances to be able to define the semilinear equivalence. -/ section smul_lemmas variables {R M : Type*} @[simp] lemma star_int_cast_smul [ring R] [add_comm_group M] [module R M] [star_add_monoid M] (n : ℤ) (x : M) : star ((n : R) • x) = (n : R) • star x := map_int_cast_smul (star_add_equiv : M ≃+ M) R R n x @[simp] lemma star_nat_cast_smul [semiring R] [add_comm_monoid M] [module R M] [star_add_monoid M] (n : ℕ) (x : M) : star ((n : R) • x) = (n : R) • star x := map_nat_cast_smul (star_add_equiv : M ≃+ M) R R n x @[simp] lemma star_inv_int_cast_smul [division_ring R] [add_comm_group M] [module R M] [star_add_monoid M] (n : ℤ) (x : M) : star ((n⁻¹ : R) • x) = (n⁻¹ : R) • star x := map_inv_int_cast_smul (star_add_equiv : M ≃+ M) R R n x @[simp] lemma star_inv_nat_cast_smul [division_ring R] [add_comm_group M] [module R M] [star_add_monoid M] (n : ℕ) (x : M) : star ((n⁻¹ : R) • x) = (n⁻¹ : R) • star x := map_inv_nat_cast_smul (star_add_equiv : M ≃+ M) R R n x @[simp] lemma star_rat_cast_smul [division_ring R] [add_comm_group M] [module R M] [star_add_monoid M] (n : ℚ) (x : M) : star ((n : R) • x) = (n : R) • star x := map_rat_cast_smul (star_add_equiv : M ≃+ M) _ _ _ x @[simp] lemma star_rat_smul {R : Type*} [add_comm_group R] [star_add_monoid R] [module ℚ R] (x : R) (n : ℚ) : star (n • x) = n • star x := map_rat_smul (star_add_equiv : R ≃+ R) _ _ end smul_lemmas /-- If `A` is a module over a commutative `R` with compatible actions, then `star` is a semilinear equivalence. -/ @[simps] def star_linear_equiv (R : Type*) {A : Type*} [comm_ring R] [star_ring R] [semiring A] [star_ring A] [module R A] [star_module R A] : A ≃ₗ⋆[R] A := { to_fun := star, map_smul' := star_smul, .. star_add_equiv } variables (R : Type*) (A : Type*) [semiring R] [star_semigroup R] [has_trivial_star R] [add_comm_group A] [module R A] [star_add_monoid A] [star_module R A] /-- The self-adjoint elements of a star module, as a submodule. -/ def self_adjoint.submodule : submodule R A := { smul_mem' := self_adjoint.smul_mem, ..self_adjoint A } /-- The skew-adjoint elements of a star module, as a submodule. -/ def skew_adjoint.submodule : submodule R A := { smul_mem' := skew_adjoint.smul_mem, ..skew_adjoint A } variables {A} [invertible (2 : R)] /-- The self-adjoint part of an element of a star module, as a linear map. -/ @[simps] def self_adjoint_part : A →ₗ[R] self_adjoint A := { to_fun := λ x, ⟨(⅟2 : R) • (x + star x), by simp only [self_adjoint.mem_iff, star_smul, add_comm, star_add_monoid.star_add, star_inv', star_bit0, star_one, star_star, star_inv_of (2 : R), star_trivial]⟩, map_add' := λ x y, by { ext, simp [add_add_add_comm] }, map_smul' := λ r x, by { ext, simp [←mul_smul, show ⅟ 2 * r = r * ⅟ 2, from commute.inv_of_left (commute.one_left r).bit0_left] } } /-- The skew-adjoint part of an element of a star module, as a linear map. -/ @[simps] def skew_adjoint_part : A →ₗ[R] skew_adjoint A := { to_fun := λ x, ⟨(⅟2 : R) • (x - star x), by simp only [skew_adjoint.mem_iff, star_smul, star_sub, star_star, star_trivial, ←smul_neg, neg_sub]⟩, map_add' := λ x y, by { ext, simp only [sub_add, ←smul_add, sub_sub_eq_add_sub, star_add, add_subgroup.coe_mk, add_subgroup.coe_add] }, map_smul' := λ r x, by { ext, simp [←mul_smul, ←smul_sub, show r * ⅟ 2 = ⅟ 2 * r, from commute.inv_of_right (commute.one_right r).bit0_right] } } lemma star_module.self_adjoint_part_add_skew_adjoint_part (x : A) : (self_adjoint_part R x : A) + skew_adjoint_part R x = x := by simp only [smul_sub, self_adjoint_part_apply_coe, smul_add, skew_adjoint_part_apply_coe, add_add_sub_cancel, inv_of_two_smul_add_inv_of_two_smul] variables (A) /-- The decomposition of elements of a star module into their self- and skew-adjoint parts, as a linear equivalence. -/ @[simps] def star_module.decompose_prod_adjoint : A ≃ₗ[R] self_adjoint A × skew_adjoint A := linear_equiv.of_linear ((self_adjoint_part R).prod (skew_adjoint_part R)) ((self_adjoint.submodule R A).subtype.coprod (skew_adjoint.submodule R A).subtype) (by ext; simp) (linear_map.ext $ star_module.self_adjoint_part_add_skew_adjoint_part R)
0f04952eb11f5f481ec0a16731094c3db6738abf
f20db13587f4dd28a4b1fbd31953afd491691fa0
/tests/lean/run/quote_bas.lean
b5233540997999e48243827a61200126f9a8388d
[ "Apache-2.0" ]
permissive
AHartNtkn/lean
9a971edfc6857c63edcbf96bea6841b9a84cf916
0d83a74b26541421fc1aa33044c35b03759710ed
refs/heads/master
1,620,592,591,236
1,516,749,881,000
1,516,749,881,000
118,697,288
1
0
null
1,516,759,470,000
1,516,759,470,000
null
UTF-8
Lean
false
false
2,524
lean
universes u v w namespace quote_bas inductive Expr (V : Type u) | One {} : Expr | Var (v : V) : Expr | Mult (a b : Expr) : Expr @[reducible] def Value := nat def Env (V : Type u) := V → Value open Expr def evalExpr {V} (vs : Env V) : Expr V → Value | One := 1 | (Var v) := vs v | (Mult a b) := evalExpr a * evalExpr b def novars : Env empty := empty.rec _ def singlevar (x : Value) : Env unit := λ _, x open sum def merge {A : Type u} {B : Type v} (a : Env A) (b : Env B) : Env (sum A B) | (inl j) := a j | (inr j) := b j def map_var {A : Type u} {B : Type v} (f : A → B) : Expr A → Expr B | One := One | (Var v) := Var (f v) | (Mult a b) := Mult (map_var a) (map_var b) def sum_assoc {A : Type u} {B : Type v} {C : Type w} : sum (sum A B) C → sum A (sum B C) | (inl (inl a)) := inl a | (inl (inr b)) := inr (inl b) | (inr c) := inr (inr c) attribute [simp] evalExpr map_var sum_assoc merge @[simp] lemma eval_map_var_shift {A : Type u} {B : Type v} (v : Env A) (v' : Env B) (e : Expr A) : evalExpr (merge v v') (map_var inl e) = evalExpr v e := begin induction e, reflexivity, reflexivity, simp [*] end @[simp] lemma eval_map_var_sum_assoc {A : Type u} {B : Type v} {C : Type w} (v : Env A) (v' : Env B) (v'' : Env C) (e : Expr (sum (sum A B) C)) : evalExpr (merge v (merge v' v'')) (map_var sum_assoc e) = evalExpr (merge (merge v v') v'') e := begin induction e, reflexivity, { cases e with v₁, cases v₁, all_goals {simp} }, { simp [*] } end class Quote {V : out_param $ Type u} (l : out_param $ Env V) (n : Value) {V' : out_param $ Type v} (r : out_param $ Env V') := (quote : Expr (sum V V')) (eval_quote : evalExpr (merge l r) quote = n) def quote {V : Type u} {l : Env V} (n : nat) {V' : Type v} {r : Env V'} [Quote l n r] : Expr (sum V V') := Quote.quote l n r @[simp] lemma eval_quote {V : Type u} {l : Env V} (n : nat) {V' : Type v} {r : Env V'} [Quote l n r] : evalExpr (merge l r) (quote n) = n := Quote.eval_quote l n r instance quote_one (V) (v : Env V) : Quote v 1 novars := { quote := One, eval_quote := rfl } instance quote_mul {V : Type u} (v : Env V) (n) {V' : Type v} (v' : Env V') (m) {V'' : Type w} (v'' : Env V'') [Quote v n v'] [Quote (merge v v') m v''] : Quote v (n * m) (merge v' v'') := { quote := Mult (map_var sum_assoc (map_var inl (quote n))) (map_var sum_assoc (quote m)), eval_quote := by simp } end quote_bas
bf22f9595695e715f0235f67598c3564d4a32d00
246309748072bf9f8da313401699689ebbecd94d
/src/category_theory/limits/types.lean
bdf50daa8167b5cd996c8fe37e0c06e3672b1bd7
[ "Apache-2.0" ]
permissive
YJMD/mathlib
b703a641e5f32a996f7842f7c0043bab2b462ee2
7310eab9fa8c1b1229dca42682f1fa6bfb7dbbf9
refs/heads/master
1,670,714,479,314
1,599,035,445,000
1,599,035,445,000
292,279,930
0
0
null
1,599,050,561,000
1,599,050,560,000
null
UTF-8
Lean
false
false
11,311
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Reid Barton -/ import category_theory.limits.shapes.images import category_theory.filtered import tactic.equiv_rw universes u open category_theory open category_theory.limits namespace category_theory.limits.types variables {J : Type u} [small_category J] /-- (internal implementation) the limit cone of a functor, implemented as flat sections of a pi type -/ def limit_cone (F : J ⥤ Type u) : cone F := { X := F.sections, π := { app := λ j u, u.val j } } local attribute [elab_simple] congr_fun /-- (internal implementation) the fact that the proposed limit cone is the limit -/ def limit_cone_is_limit (F : J ⥤ Type u) : is_limit (limit_cone F) := { lift := λ s v, ⟨λ j, s.π.app j v, λ j j' f, congr_fun (cone.w s f) _⟩, uniq' := by { intros, ext x j, exact congr_fun (w j) x } } instance : has_limits (Type u) := { has_limits_of_shape := λ J 𝒥, by exactI { has_limit := λ F, { cone := limit_cone F, is_limit := limit_cone_is_limit F } } } /-- The equivalence between the abstract limit of `F` in `Type u` and the "concrete" definition as the sections of `F`. -/ def limit_equiv_sections (F : J ⥤ Type u) : (limit F : Type u) ≃ F.sections := (is_limit.cone_point_unique_up_to_iso (limit.is_limit F) (limit_cone_is_limit F)).to_equiv @[simp] lemma limit_equiv_sections_apply (F : J ⥤ Type u) (x : limit F) (j : J) : (((limit_equiv_sections F) x) : Π j, F.obj j) j = limit.π F j x := rfl @[simp] lemma limit_equiv_sections_symm_apply (F : J ⥤ Type u) (x : F.sections) (j : J) : limit.π F j ((limit_equiv_sections F).symm x) = (x : Π j, F.obj j) j := begin equiv_rw (limit_equiv_sections F).symm at x, simp, end -- PROJECT: prove this for concrete categories where the forgetful functor preserves limits lemma limit_ext (F : J ⥤ Type u) (x y : limit F) (w : ∀ j, limit.π F j x = limit.π F j y) : x = y := begin apply (limit_equiv_sections F).injective, ext j, simp [w j], end -- TODO: are there other limits lemmas that should have `_apply` versions? -- Can we generate these like with `@[reassoc]`? -- PROJECT: prove these for any concrete category where the forgetful functor preserves limits? @[simp] lemma lift_π_apply (F : J ⥤ Type u) (s : cone F) (j : J) (x : s.X) : limit.π F j (limit.lift F s x) = s.π.app j x := congr_fun (limit.lift_π s j) x /-- A quotient type implementing the colimit of a functor `F : J ⥤ Type u`, as pairs `⟨j, x⟩` where `x : F.obj j`, modulo the equivalence relation generated by `⟨j, x⟩ ~ ⟨j', x'⟩` whenever there is a morphism `f : j ⟶ j'` so `F.map f x = x'`. -/ @[nolint has_inhabited_instance] def quot (F : J ⥤ Type u) : Type u := @quot (Σ j, F.obj j) (λ p p', ∃ f : p.1 ⟶ p'.1, p'.2 = F.map f p.2) /-- (internal implementation) the colimit cocone of a functor, implemented as a quotient of a sigma type -/ def colimit_cocone (F : J ⥤ Type u) : cocone F := { X := quot F, ι := { app := λ j x, quot.mk _ ⟨j, x⟩, naturality' := λ j j' f, funext $ λ x, eq.symm (quot.sound ⟨f, rfl⟩) } } local attribute [elab_with_expected_type] quot.lift /-- (internal implementation) the fact that the proposed colimit cocone is the colimit -/ def colimit_cocone_is_colimit (F : J ⥤ Type u) : is_colimit (colimit_cocone F) := { desc := λ s, quot.lift (λ (p : Σ j, F.obj j), s.ι.app p.1 p.2) (assume ⟨j, x⟩ ⟨j', x'⟩ ⟨f, hf⟩, by rw hf; exact (congr_fun (cocone.w s f) x).symm) } instance : has_colimits (Type u) := { has_colimits_of_shape := λ J 𝒥, by exactI { has_colimit := λ F, { cocone := colimit_cocone F, is_colimit := colimit_cocone_is_colimit F } } } /-- The equivalence between the abstract colimit of `F` in `Type u` and the "concrete" definition as a quotient. -/ def colimit_equiv_quot (F : J ⥤ Type u) : (colimit F : Type u) ≃ quot F := (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) (colimit_cocone_is_colimit F)).to_equiv @[simp] lemma colimit_equiv_quot_symm_apply (F : J ⥤ Type u) (j : J) (x : F.obj j) : (colimit_equiv_quot F).symm (quot.mk _ ⟨j, x⟩) = colimit.ι F j x := rfl @[simp] lemma ι_desc_apply (F : J ⥤ Type u) (s : cocone F) (j : J) (x : F.obj j) : colimit.desc F s (colimit.ι F j x) = s.ι.app j x := congr_fun (colimit.ι_desc s j) x lemma jointly_surjective (F : J ⥤ Type u) {t : cocone F} (h : is_colimit t) (x : t.X) : ∃ j y, t.ι.app j y = x := begin suffices : (λ (x : t.X), ulift.up (∃ j y, t.ι.app j y = x)) = (λ _, ulift.up true), { have := congr_fun this x, have H := congr_arg ulift.down this, dsimp at H, rwa eq_true at H }, refine h.hom_ext _, intro j, ext y, erw iff_true, exact ⟨j, y, rfl⟩ end /-- A variant of `jointly_surjective` for `x : colimit F`. -/ lemma jointly_surjective' {F : J ⥤ Type u} (x : colimit F) : ∃ j y, colimit.ι F j y = x := jointly_surjective F (colimit.is_colimit _) x namespace filtered_colimit /- For filtered colimits of types, we can give an explicit description of the equivalence relation generated by the relation used to form the colimit. -/ variables (F : J ⥤ Type u) /-- An alternative relation on `Σ j, F.obj j`, which generates the same equivalence relation as we use to define the colimit in `Type` above, but that is more convenient when working with filtered colimits. Elements in `F.obj j` and `F.obj j'` are equivalent if there is some `k : J` to the right where their images are equal. -/ protected def r (x y : Σ j, F.obj j) : Prop := ∃ k (f : x.1 ⟶ k) (g : y.1 ⟶ k), F.map f x.2 = F.map g y.2 protected lemma r_ge (x y : Σ j, F.obj j) : (∃ f : x.1 ⟶ y.1, y.2 = F.map f x.2) → filtered_colimit.r F x y := λ ⟨f, hf⟩, ⟨y.1, f, 𝟙 y.1, by simp [hf]⟩ variables (t : cocone F) local attribute [elab_simple] nat_trans.app /-- Recognizing filtered colimits of types. -/ noncomputable def is_colimit_of (hsurj : ∀ (x : t.X), ∃ i xi, x = t.ι.app i xi) (hinj : ∀ i j xi xj, t.ι.app i xi = t.ι.app j xj → ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj) : is_colimit t := -- Strategy: Prove that the map from "the" colimit of F (defined above) to t.X -- is a bijection. begin apply is_colimit.of_iso_colimit (colimit.is_colimit F), refine cocones.ext (equiv.to_iso (equiv.of_bijective _ _)) _, { exact colimit.desc F t }, { split, { show function.injective _, intros a b h, rcases jointly_surjective F (colimit.is_colimit F) a with ⟨i, xi, rfl⟩, rcases jointly_surjective F (colimit.is_colimit F) b with ⟨j, xj, rfl⟩, change (colimit.ι F i ≫ colimit.desc F t) xi = (colimit.ι F j ≫ colimit.desc F t) xj at h, rw [colimit.ι_desc, colimit.ι_desc] at h, rcases hinj i j xi xj h with ⟨k, f, g, h'⟩, change colimit.ι F i xi = colimit.ι F j xj, rw [←colimit.w F f, ←colimit.w F g], change colimit.ι F k (F.map f xi) = colimit.ι F k (F.map g xj), rw h' }, { show function.surjective _, intro x, rcases hsurj x with ⟨i, xi, rfl⟩, use colimit.ι F i xi, simp } }, { intro j, apply colimit.ι_desc } end variables [is_filtered_or_empty J] protected lemma r_equiv : equivalence (filtered_colimit.r F) := ⟨λ x, ⟨x.1, 𝟙 x.1, 𝟙 x.1, rfl⟩, λ x y ⟨k, f, g, h⟩, ⟨k, g, f, h.symm⟩, λ x y z ⟨k, f, g, h⟩ ⟨k', f', g', h'⟩, let ⟨l, fl, gl, _⟩ := is_filtered_or_empty.cocone_objs k k', ⟨m, n, hn⟩ := is_filtered_or_empty.cocone_maps (g ≫ fl) (f' ≫ gl) in ⟨m, f ≫ fl ≫ n, g' ≫ gl ≫ n, calc F.map (f ≫ fl ≫ n) x.2 = F.map (fl ≫ n) (F.map f x.2) : by simp ... = F.map (fl ≫ n) (F.map g y.2) : by rw h ... = F.map ((g ≫ fl) ≫ n) y.2 : by simp ... = F.map ((f' ≫ gl) ≫ n) y.2 : by rw hn ... = F.map (gl ≫ n) (F.map f' y.2) : by simp ... = F.map (gl ≫ n) (F.map g' z.2) : by rw h' ... = F.map (g' ≫ gl ≫ n) z.2 : by simp⟩⟩ protected lemma r_eq : filtered_colimit.r F = eqv_gen (λ x y, ∃ f : x.1 ⟶ y.1, y.2 = F.map f x.2) := begin apply le_antisymm, { rintros ⟨i, x⟩ ⟨j, y⟩ ⟨k, f, g, h⟩, exact eqv_gen.trans _ ⟨k, F.map f x⟩ _ (eqv_gen.rel _ _ ⟨f, rfl⟩) (eqv_gen.symm _ _ (eqv_gen.rel _ _ ⟨g, h⟩)) }, { intros x y, convert relation.eqv_gen_mono (filtered_colimit.r_ge F), apply propext, symmetry, exact relation.eqv_gen_iff_of_equivalence (filtered_colimit.r_equiv F) } end lemma colimit_eq_iff {i j : J} {xi : F.obj i} {xj : F.obj j} : colimit.ι F i xi = colimit.ι F j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj := begin change quot.mk _ _ = quot.mk _ _ ↔ _, rw [quot.eq, ←filtered_colimit.r_eq], refl end variables {t} (ht : is_colimit t) lemma is_colimit_eq_iff {i j : J} {xi : F.obj i} {xj : F.obj j} : t.ι.app i xi = t.ι.app j xj ↔ ∃ k (f : i ⟶ k) (g : j ⟶ k), F.map f xi = F.map g xj := let t' := colimit.cocone F, e : t' ≅ t := is_colimit.unique_up_to_iso (colimit.is_colimit F) ht, e' : t'.X ≅ t.X := (cocones.forget _).map_iso e in begin refine iff.trans _ (colimit_eq_iff F), convert equiv.apply_eq_iff_eq e'.to_equiv _ _; rw ←e.hom.w; refl end end filtered_colimit variables {α β : Type u} (f : α ⟶ β) section -- implementation of `has_image` /-- the image of a morphism in Type is just `set.range f` -/ def image : Type u := set.range f instance [inhabited α] : inhabited (image f) := { default := ⟨f (default α), ⟨_, rfl⟩⟩ } /-- the inclusion of `image f` into the target -/ def image.ι : image f ⟶ β := subtype.val instance : mono (image.ι f) := (mono_iff_injective _).2 subtype.val_injective variables {f} /-- the universal property for the image factorisation -/ noncomputable def image.lift (F' : mono_factorisation f) : image f ⟶ F'.I := (λ x, F'.e (classical.indefinite_description _ x.2).1 : image f → F'.I) lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' ≫ F'.m = image.ι f := begin ext x, change (F'.e ≫ F'.m) _ = _, rw [F'.fac, (classical.indefinite_description _ x.2).2], refl, end end /-- the factorisation of any morphism in AddCommGroup through a mono. -/ def mono_factorisation : mono_factorisation f := { I := image f, m := image.ι f, e := set.range_factorization f } noncomputable instance : has_image f := { F := mono_factorisation f, is_image := { lift := image.lift, lift_fac' := image.lift_fac } } noncomputable instance : has_images (Type u) := { has_image := infer_instance } noncomputable instance : has_image_maps (Type u) := { has_image_map := λ f g st, { map := λ x, ⟨st.right x.1, ⟨st.left (classical.some x.2), begin have p := st.w, replace p := congr_fun p (classical.some x.2), simp only [functor.id_map, types_comp_apply, subtype.val_eq_coe] at p, erw [p, classical.some_spec x.2], end⟩⟩ } } @[simp] lemma image_map {f g : arrow (Type u)} (st : f ⟶ g) (x : image f.hom) : (image.map st x).val = st.right x.1 := rfl end category_theory.limits.types
c490a688ce400e0019b0eb9e520fca30f5e3be96
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Lean/Compiler/LCNF.lean
60b1861290f0450e5f03bfc3d799aa1b37b5d914
[ "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
16,362
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ProjFns import Lean.ToExpr import Lean.Util.Recognizers import Lean.Meta.Match.MatcherInfo import Lean.Meta.Transform import Lean.Compiler.InlineAttrs import Lean.Compiler.InferType import Lean.Compiler.Util namespace Lean.Compiler /-! # Lean Compiler Normal Form (LCNF) It is based on the [A-normal form](https://en.wikipedia.org/wiki/A-normal_form), and the approach described in the paper [Compiling without continuations](https://www.microsoft.com/en-us/research/wp-content/uploads/2016/11/compiling-without-continuations.pdf). Remark, in LCNF, the terminal expression in a `let`-declaration block is never a lambda. The idea is to make sure we can easily compute the "true arity" of a join point. For example, consider the following two join points ``` let _jp.1 := fun x y => x + y let _jp.2 := fun x => let f := fun y => x + y f ``` `_jp.1` is a join point of arity 2, and `_jp.2` is a join point of arity 1. -/ namespace ToLCNF structure Context where root : Bool structure State where /-- Local context containing the original Lean types (not LCNF ones). -/ lctx : LocalContext := {} /-- Local context containing Lean LCNF types. -/ lctx' : LocalContext := {} letFVars : Array Expr := #[] /-- Next auxiliary variable suffix -/ nextIdx : Nat := 1 /-- Cache from Lean regular expression to LCNF expression. -/ cache : PersistentExprMap Expr := {} abbrev M := ReaderT Context $ StateRefT State CoreM instance : MonadInferType M where inferType e := do InferType.inferType e { lctx := (← get).lctx' } @[inline] def liftMetaM (x : MetaM α) : M α := do x.run' { lctx := (← get).lctx } @[inline] def withRoot (flag : Bool) (x : M α) : M α := withReader (fun _ => { root := flag }) x def withNewRootScope (x : M α) : M α := do let saved ← get modify fun s => { s with letFVars := #[] } try withRoot true x finally let saved := { saved with nextIdx := (← get).nextIdx } set saved /-- Create a new local declaration using a Lean regular type. -/ def mkLocalDecl (binderName : Name) (type : Expr) (bi := BinderInfo.default) : M Expr := do let fvarId ← mkFreshFVarId let type' ← liftMetaM <| toLCNFType type modify fun s => { s with lctx := s.lctx.mkLocalDecl fvarId binderName type bi lctx' := s.lctx'.mkLocalDecl fvarId binderName type' bi } return .fvar fvarId def mkFreshBinderName : M Name := do let declName := .num `_x (← get).nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1 } return declName def mkLetDecl (binderName : Name) (type : Expr) (value : Expr) (type' : Expr) (value' : Expr) : M Expr := do let fvarId ← mkFreshFVarId let binderName ← if binderName.isInternal then mkFreshBinderName else pure binderName let x := .fvar fvarId modify fun s => { s with lctx := s.lctx.mkLetDecl fvarId binderName type value false lctx' := s.lctx'.mkLetDecl fvarId binderName type' value' true letFVars := s.letFVars.push x } return x /-- Create an auxiliary `let`-declaration for the given LCNF expression. -/ def mkAuxLetDecl (e : Expr) : M Expr := do if (← read).root then return e else let fvarId ← mkFreshFVarId let binderName ← mkFreshBinderName let type ← inferType e let x := .fvar fvarId modify fun s => { s with lctx' := s.lctx'.mkLetDecl fvarId binderName type e true letFVars := s.letFVars.push x } return x def visitLambda (e : Expr) : M (Array Expr × Expr) := go e #[] where go (e : Expr) (fvars : Array Expr) := do if let .lam binderName type body binderInfo := e then let type := type.instantiateRev fvars let fvar ← mkLocalDecl binderName type binderInfo go body (fvars.push fvar) else return (fvars, e.instantiateRev fvars) def visitBoundedLambda (e : Expr) (n : Nat) : M (Array Expr × Expr) := go e n #[] where go (e : Expr) (n : Nat) (fvars : Array Expr) := do if n == 0 then return (fvars, e.instantiateRev fvars) else if let .lam binderName type body binderInfo := e then let type := type.instantiateRev fvars let fvar ← mkLocalDecl binderName type binderInfo go body (n-1) (fvars.push fvar) else return (fvars, e.instantiateRev fvars) def mkLetUsingScope (e : Expr) : M Expr := do let e ← if e.isLambda then /- In LCNF, terminal expression in a `let`-block must not be a lambda. -/ withRoot false <| mkAuxLetDecl e else pure e return (← get).lctx'.mkLambda (← get).letFVars e def mkLambda (xs : Array Expr) (e : Expr) : M Expr := return (← get).lctx'.mkLambda xs e /-- Eta-expand with `n` lambdas. -/ def etaExpandN (e : Expr) (n : Nat) : M Expr := do if n == 0 then return e else liftMetaM do Meta.forallBoundedTelescope (← Meta.inferType e) n fun xs _ => Meta.mkLambdaFVars xs (mkAppN e xs) /-- Put the given expression in `LCNF`. - Nested proofs are replaced with `lcProof`-applications. - Eta-expand applications of declarations that satisfy `shouldEtaExpand`. - Put computationally relevant expressions in A-normal form. -/ partial def toLCNF (e : Expr) : CoreM Expr := do let (e, s) ← visit e |>.run { root := true } |>.run {} return s.lctx'.mkLambda s.letFVars e where visitCore (e : Expr) : M Expr := withIncRecDepth do if let some e := (← get).cache.find? e then return e let r ← match e with | .app .. => visitApp e | .const .. => visitApp e | .proj s i e => visitProj s i e | .mdata d e => visitMData d e | .lam .. => visitLambda e | .letE .. => visitLet e #[] | .lit .. => mkAuxLetDecl e | .forallE .. => unreachable! | .mvar .. => throwError "unexpected occurrence of metavariable in code generator{indentExpr e}" | .bvar .. => unreachable! | _ => pure e modify fun s => { s with cache := s.cache.insert e r } return r visit (e : Expr) : M Expr := withIncRecDepth do if isLCProof e then return mkConst ``lcErased let type ← liftMetaM <| Meta.inferType e if (← liftMetaM <| Meta.isProp type) then /- We erase proofs. -/ return mkConst ``lcErased if (← liftMetaM <| Meta.isTypeFormerType type) then /- We erase type formers unless they occur as application arguments. Recall that we usually do not generate code for functions that return type, by this branch can be reachable if we cannot establish whether the function produces a type or not. See `visitAppArg` -/ return mkConst ``lcErased visitCore e visitChild (e : Expr) : M Expr := withRoot false <| visit e visitAppArg (e : Expr) : M Expr := do if isLCProof e then return mkConst ``lcErased let type ← liftMetaM <| Meta.inferType e if (← liftMetaM <| Meta.isProp type) then /- We erase proofs. -/ return mkConst ``lcErased if (← liftMetaM <| Meta.isTypeFormerType type) then /- Types and Type formers are not put into A-normal form -/ return (← liftMetaM <| toLCNFType e) else withRoot false <| visitCore e /-- Visit args, and return `f args` -/ visitAppDefault (f : Expr) (args : Array Expr) : M Expr := do if f.isConstOf ``lcErased then return f else let args ← args.mapM visitAppArg mkAuxLetDecl <| mkAppN f args /-- Eta expand if under applied, otherwise apply k -/ etaIfUnderApplied (e : Expr) (arity : Nat) (k : M Expr) : M Expr := do let numArgs := e.getAppNumArgs if numArgs < arity then visit (← etaExpandN e (arity - numArgs)) else k /-- If `args.size == arity`, then just return `app`. Otherwise return ``` let k := app k args[arity:] ``` -/ mkOverApplication (app : Expr) (args : Array Expr) (arity : Nat) : M Expr := do if args.size == arity then mkAuxLetDecl app else let k ← withRoot false <| mkAuxLetDecl app let mut args := args for i in [arity : args.size] do args ← args.modifyM i visitAppArg mkAuxLetDecl (mkAppN k args[arity:]) /-- Visit a `matcher`/`casesOn` alternative. -/ visitAlt (e : Expr) (numParams : Nat) : M (Expr × Expr) := do withNewRootScope do let mut (as, e) ← visitBoundedLambda e numParams if as.size < numParams then e ← etaExpandN e (numParams - as.size) let (as', e') ← ToLCNF.visitLambda e as := as ++ as' e := e' e ← mkLetUsingScope (← visit e) let eType ← inferType e return (eType, (← mkLambda as e)) visitCases (casesInfo : CasesInfo) (e : Expr) : M Expr := etaIfUnderApplied e casesInfo.arity do let mut args := e.getAppArgs let mut resultType ← liftMetaM do toLCNFType (← Meta.inferType (mkAppN e.getAppFn args[:casesInfo.arity])) let mut discrTypes := #[] for i in [:casesInfo.numParams] do -- `cases` and `match` parameters are irrelevant at LCNF args := args.modify i fun _ => mkConst ``lcErased for i in casesInfo.discrsRange do let discrType ← inferType args[i]! args ← args.modifyM i visitAppArg discrTypes := discrTypes.push discrType for i in casesInfo.altsRange, numParams in casesInfo.altNumParams do let (altType, alt) ← visitAlt args[i]! numParams unless compatibleTypes altType resultType do resultType := anyTypeExpr args := args.set! i alt let motive ← discrTypes.foldrM (init := resultType) fun discrType resultType => return .lam (← mkFreshUserName `x) discrType resultType .default args := args.set! casesInfo.motivePos motive let result := mkAppN e.getAppFn args[:casesInfo.arity] if args.size == casesInfo.arity then mkAuxLetDecl result else mkOverApplication result args casesInfo.arity visitCtor (arity : Nat) (e : Expr) : M Expr := etaIfUnderApplied e arity do visitAppDefault e.getAppFn e.getAppArgs visitQuotLift (e : Expr) : M Expr := do let arity := 6 etaIfUnderApplied e arity do let mut args := e.getAppArgs let α := args[0]! let r := args[1]! let f ← visitAppArg args[3]! let q ← visitAppArg args[5]! let .const _ [u, _] := e.getAppFn | unreachable! let invq ← withRoot false <| mkAuxLetDecl (mkApp3 (.const ``Quot.lcInv [u]) α r q) let r := mkApp f invq mkOverApplication r args arity visitEqRec (e : Expr) : M Expr := let arity := 6 etaIfUnderApplied e arity do let args := e.getAppArgs let f := e.getAppFn let recType ← liftMetaM do toLCNFType (← Meta.inferType (mkAppN f args[:arity])) let minor := if e.isAppOf ``Eq.rec || e.isAppOf ``Eq.ndrec then args[3]! else args[5]! let minor ← visit minor let minorType ← inferType minor let cast ← if compatibleTypes minorType recType then -- Recall that many types become compatible after LCNF conversion -- Example: `Fin 10` and `Fin n` pure minor else mkLcCast (← withRoot false <| mkAuxLetDecl minor) recType mkOverApplication cast args arity visitFalseRec (e : Expr) : M Expr := let arity := 2 etaIfUnderApplied e arity do let type ← liftMetaM do toLCNFType (← Meta.inferType e) mkAuxLetDecl (← mkLcUnreachable type) visitAndRec (e : Expr) : M Expr := let arity := 5 etaIfUnderApplied e arity do let args := e.getAppArgs let ha := mkLcProof args[0]! -- We should not use `lcErased` here since we use it to create a pre-LCNF Expr. let hb := mkLcProof args[1]! let minor := if e.isAppOf ``And.rec then args[3]! else args[4]! let minor := minor.beta #[ha, hb] visit (mkAppN minor args[arity:]) visitNoConfusion (e : Expr) : M Expr := do let .const declName _ := e.getAppFn | unreachable! let typeName := declName.getPrefix let .inductInfo inductVal ← getConstInfo typeName | unreachable! let arity := inductVal.numParams + inductVal.numIndices + 1 /- motive -/ + 2 /- lhs/rhs-/ + 1 /- equality -/ etaIfUnderApplied e arity do let args := e.getAppArgs let lhs ← liftMetaM do Meta.whnf args[inductVal.numParams + inductVal.numIndices + 1]! let rhs ← liftMetaM do Meta.whnf args[inductVal.numParams + inductVal.numIndices + 2]! let lhs := lhs.toCtorIfLit let rhs := rhs.toCtorIfLit match lhs.isConstructorApp? (← getEnv), rhs.isConstructorApp? (← getEnv) with | some lhsCtorVal, some rhsCtorVal => if lhsCtorVal.name == rhsCtorVal.name then etaIfUnderApplied e (arity+1) do let major := args[arity]! let major ← expandNoConfusionMajor major lhsCtorVal.numFields let major := mkAppN major args[arity+1:] visit major else mkAuxLetDecl (← mkLcUnreachable (← inferType e)) | _, _ => throwError "code generator failed, unsupported occurrence of `{declName}`" expandNoConfusionMajor (major : Expr) (numFields : Nat) : M Expr := do match numFields with | 0 => return major | n+1 => if let .lam _ d b _ := major then let proof := mkLcProof d expandNoConfusionMajor (b.instantiate1 proof) n else expandNoConfusionMajor (← etaExpandN major (n+1)) (n+1) visitProjFn (projInfo : ProjectionFunctionInfo) (e : Expr) : M Expr := do let typeName := projInfo.ctorName.getPrefix if isRuntimeBultinType typeName then let numArgs := e.getAppNumArgs let arity := projInfo.numParams + 1 if numArgs < arity then visit (← etaExpandN e (arity - numArgs)) else visitAppDefault e.getAppFn e.getAppArgs else let .const declName us := e.getAppFn | unreachable! let info ← getConstInfo declName let f ← Core.instantiateValueLevelParams info us visit (f.beta e.getAppArgs) visitApp (e : Expr) : M Expr := do if let .const declName _ := e.getAppFn then if declName == ``Quot.lift then visitQuotLift e else if declName == ``Quot.mk then visitCtor 3 e else if declName == ``Eq.casesOn || declName == ``Eq.rec || declName == ``Eq.ndrec then visitEqRec e else if declName == ``And.rec || declName == ``And.casesOn then visitAndRec e else if declName == ``False.rec || declName == ``Empty.rec || declName == ``False.casesOn || declName == ``Empty.casesOn then visitFalseRec e else if let some casesInfo ← getCasesInfo? declName then visitCases casesInfo e else if let some arity ← getCtorArity? declName then visitCtor arity e else if isNoConfusion (← getEnv) declName then visitNoConfusion e else if let some projInfo ← getProjectionFnInfo? declName then visitProjFn projInfo e else e.withApp visitAppDefault else e.withApp fun f args => do visitAppDefault (← visitChild f) args visitLambda (e : Expr) : M Expr := do let r ← withNewRootScope do let (as, e) ← ToLCNF.visitLambda e let e ← mkLetUsingScope (← visit e) mkLambda as e mkAuxLetDecl r visitMData (mdata : MData) (e : Expr) : M Expr := do if isCompilerRelevantMData mdata then mkAuxLetDecl <| .mdata mdata (← visitChild e) else visit e visitProj (s : Name) (i : Nat) (e : Expr) : M Expr := do mkAuxLetDecl <| .proj s i (← visitChild e) visitLet (e : Expr) (xs : Array Expr) : M Expr := do match e with | .letE binderName type value body _ => let type := type.instantiateRev xs let value := value.instantiateRev xs if (← liftMetaM <| Meta.isProp type <||> Meta.isTypeFormerType type) then visitLet body (xs.push value) else let type' ← liftMetaM <| toLCNFType type let value' ← visit value let x ← mkLetDecl binderName type value type' value' visitLet body (xs.push x) | _ => let e := e.instantiateRev xs visit e end ToLCNF export ToLCNF (toLCNF) end Lean.Compiler
2cfd648bd98d11a3a87e3db4ea7ba17eaf484243
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/preadditive/biproducts.lean
565b1742dd75f040be31043b76d8dab9175cf59e
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
11,457
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.abel import category_theory.limits.shapes.biproducts import category_theory.preadditive /-! # Basic facts about morphisms between biproducts in preadditive categories. * In any category (with zero morphisms), if `biprod.map f g` is an isomorphism, then both `f` and `g` are isomorphisms. The remaining lemmas hold in any preadditive category. * If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. * As a corollary of the previous two facts, if we have an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, we can construct an isomorphism `X₂ ≅ Y₂`. * If `f : W ⊞ X ⟶ Y ⊞ Z` is an isomorphism, either `𝟙 W = 0`, or at least one of the component maps `W ⟶ Y` and `W ⟶ Z` is nonzero. * If `f : ⨁ S ⟶ ⨁ T` is an isomorphism, then every column (corresponding to a nonzero summand in the domain) has some nonzero matrix entry. -/ open category_theory open category_theory.preadditive open category_theory.limits universes v u noncomputable theory namespace category_theory variables {C : Type u} [category.{v} C] section variables [has_zero_morphisms.{v} C] [has_binary_biproducts.{v} C] /-- If ``` (f 0) (0 g) ``` is invertible, then `f` is invertible. -/ def is_iso_left_of_is_iso_biprod_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [is_iso (biprod.map f g)] : is_iso f := { inv := biprod.inl ≫ inv (biprod.map f g) ≫ biprod.fst, hom_inv_id' := begin have t := congr_arg (λ p : W ⊞ X ⟶ W ⊞ X, biprod.inl ≫ p ≫ biprod.fst) (is_iso.hom_inv_id (biprod.map f g)), simp only [category.id_comp, category.assoc, biprod.inl_map_assoc] at t, simp [t], end, inv_hom_id' := begin have t := congr_arg (λ p : Y ⊞ Z ⟶ Y ⊞ Z, biprod.inl ≫ p ≫ biprod.fst) (is_iso.inv_hom_id (biprod.map f g)), simp only [category.id_comp, category.assoc, biprod.map_fst] at t, simp only [category.assoc], simp [t], end } /-- If ``` (f 0) (0 g) ``` is invertible, then `g` is invertible. -/ def is_iso_right_of_is_iso_biprod_map {W X Y Z : C} (f : W ⟶ Y) (g : X ⟶ Z) [is_iso (biprod.map f g)] : is_iso g := begin letI : is_iso (biprod.map g f) := by { rw [←biprod.braiding_map_braiding], apply_instance, }, exact is_iso_left_of_is_iso_biprod_map g f, end end section variables [preadditive.{v} C] [has_binary_biproducts.{v} C] variables {X₁ X₂ Y₁ Y₂ : C} variables (f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂) /-- The "matrix" morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` with specified components. -/ def biprod.of_components : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂ := biprod.fst ≫ f₁₁ ≫ biprod.inl + biprod.fst ≫ f₁₂ ≫ biprod.inr + biprod.snd ≫ f₂₁ ≫ biprod.inl + biprod.snd ≫ f₂₂ ≫ biprod.inr @[simp] lemma biprod.inl_of_components : biprod.inl ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ = f₁₁ ≫ biprod.inl + f₁₂ ≫ biprod.inr := by simp [biprod.of_components] @[simp] lemma biprod.inr_of_components : biprod.inr ≫ biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ = f₂₁ ≫ biprod.inl + f₂₂ ≫ biprod.inr := by simp [biprod.of_components] @[simp] lemma biprod.of_components_fst : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.fst = biprod.fst ≫ f₁₁ + biprod.snd ≫ f₂₁ := by simp [biprod.of_components] @[simp] lemma biprod.of_components_snd : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.snd = biprod.fst ≫ f₁₂ + biprod.snd ≫ f₂₂ := by simp [biprod.of_components] @[simp] lemma biprod.of_components_eq (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) : biprod.of_components (biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd) (biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd) = f := begin ext; simp, end @[simp] lemma biprod.of_components_comp {X₁ X₂ Y₁ Y₂ Z₁ Z₂ : C} (f₁₁ : X₁ ⟶ Y₁) (f₁₂ : X₁ ⟶ Y₂) (f₂₁ : X₂ ⟶ Y₁) (f₂₂ : X₂ ⟶ Y₂) (g₁₁ : Y₁ ⟶ Z₁) (g₁₂ : Y₁ ⟶ Z₂) (g₂₁ : Y₂ ⟶ Z₁) (g₂₂ : Y₂ ⟶ Z₂) : biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂ ≫ biprod.of_components g₁₁ g₁₂ g₂₁ g₂₂ = biprod.of_components (f₁₁ ≫ g₁₁ + f₁₂ ≫ g₂₁) (f₁₁ ≫ g₁₂ + f₁₂ ≫ g₂₂) (f₂₁ ≫ g₁₁ + f₂₂ ≫ g₂₁) (f₂₁ ≫ g₁₂ + f₂₂ ≫ g₂₂) := begin dsimp [biprod.of_components], apply biprod.hom_ext; apply biprod.hom_ext'; simp only [add_comp, comp_add, add_comp_assoc, add_zero, zero_add, biprod.inl_fst, biprod.inl_snd, biprod.inr_fst, biprod.inr_snd, biprod.inl_fst_assoc, biprod.inl_snd_assoc, biprod.inr_fst_assoc, biprod.inr_snd_assoc, comp_zero, zero_comp, category.comp_id, category.assoc], end /-- The unipotent upper triangular matrix ``` (1 r) (0 1) ``` as an isomorphism. -/ @[simps] def biprod.unipotent_upper {X₁ X₂ : C} (r : X₁ ⟶ X₂) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ := { hom := biprod.of_components (𝟙 _) r 0 (𝟙 _), inv := biprod.of_components (𝟙 _) (-r) 0 (𝟙 _), } /-- The unipotent lower triangular matrix ``` (1 0) (r 1) ``` as an isomorphism. -/ @[simps] def biprod.unipotent_lower {X₁ X₂ : C} (r : X₂ ⟶ X₁) : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂ := { hom := biprod.of_components (𝟙 _) 0 r (𝟙 _), inv := biprod.of_components (𝟙 _) 0 (-r) (𝟙 _), } /-- If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. (This is the version of `biprod.gaussian` written in terms of components.) -/ def biprod.gaussian' [is_iso f₁₁] : Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂), L.hom ≫ (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂) ≫ R.hom = biprod.map f₁₁ g₂₂ := ⟨biprod.unipotent_lower (-(f₂₁ ≫ inv f₁₁)), biprod.unipotent_upper (-(inv f₁₁ ≫ f₁₂)), f₂₂ - f₂₁ ≫ (inv f₁₁) ≫ f₁₂, by ext; simp; abel⟩ /-- If `f` is a morphism `X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct isomorphisms `L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂` and `R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂` so that `L.hom ≫ g ≫ R.hom` is diagonal (with `X₁ ⟶ Y₁` component still `f`), via Gaussian elimination. -/ def biprod.gaussian (f : X₁ ⊞ X₂ ⟶ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f ≫ biprod.fst)] : Σ' (L : X₁ ⊞ X₂ ≅ X₁ ⊞ X₂) (R : Y₁ ⊞ Y₂ ≅ Y₁ ⊞ Y₂) (g₂₂ : X₂ ⟶ Y₂), L.hom ≫ f ≫ R.hom = biprod.map (biprod.inl ≫ f ≫ biprod.fst) g₂₂ := begin let := biprod.gaussian' (biprod.inl ≫ f ≫ biprod.fst) (biprod.inl ≫ f ≫ biprod.snd) (biprod.inr ≫ f ≫ biprod.fst) (biprod.inr ≫ f ≫ biprod.snd), simpa [biprod.of_components_eq], end /-- If `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` via a two-by-two matrix whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination. -/ def biprod.iso_elim' [is_iso f₁₁] [is_iso (biprod.of_components f₁₁ f₁₂ f₂₁ f₂₂)] : X₂ ≅ Y₂ := begin obtain ⟨L, R, g, w⟩ := biprod.gaussian' f₁₁ f₁₂ f₂₁ f₂₂, letI : is_iso (biprod.map f₁₁ g) := by { rw ←w, apply_instance, }, letI : is_iso g := (is_iso_right_of_is_iso_biprod_map f₁₁ g), exact as_iso g, end /-- If `f` is an isomorphism `X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂` whose `X₁ ⟶ Y₁` entry is an isomorphism, then we can construct an isomorphism `X₂ ≅ Y₂`, via Gaussian elimination. -/ def biprod.iso_elim (f : X₁ ⊞ X₂ ≅ Y₁ ⊞ Y₂) [is_iso (biprod.inl ≫ f.hom ≫ biprod.fst)] : X₂ ≅ Y₂ := begin letI : is_iso (biprod.of_components (biprod.inl ≫ f.hom ≫ biprod.fst) (biprod.inl ≫ f.hom ≫ biprod.snd) (biprod.inr ≫ f.hom ≫ biprod.fst) (biprod.inr ≫ f.hom ≫ biprod.snd)) := by { simp only [biprod.of_components_eq], apply_instance, }, exact biprod.iso_elim' (biprod.inl ≫ f.hom ≫ biprod.fst) (biprod.inl ≫ f.hom ≫ biprod.snd) (biprod.inr ≫ f.hom ≫ biprod.fst) (biprod.inr ≫ f.hom ≫ biprod.snd) end lemma biprod.column_nonzero_of_iso {W X Y Z : C} (f : W ⊞ X ⟶ Y ⊞ Z) [is_iso f] : 𝟙 W = 0 ∨ biprod.inl ≫ f ≫ biprod.fst ≠ 0 ∨ biprod.inl ≫ f ≫ biprod.snd ≠ 0 := begin by_contradiction, rw [not_or_distrib, not_or_distrib, not_not, not_not] at h, rcases h with ⟨nz, a₁, a₂⟩, set x := biprod.inl ≫ f ≫ inv f ≫ biprod.fst, have h₁ : x = 𝟙 W, by simp [x], have h₀ : x = 0, { dsimp [x], rw [←category.id_comp (inv f), category.assoc, ←biprod.total], conv_lhs { slice 2 3, rw [comp_add], }, simp only [category.assoc], rw [comp_add_assoc, add_comp], conv_lhs { congr, skip, slice 1 3, rw a₂, }, simp only [zero_comp, add_zero], conv_lhs { slice 1 3, rw a₁, }, simp only [zero_comp], }, exact nz (h₁.symm.trans h₀), end end variables [preadditive.{v} C] lemma biproduct.column_nonzero_of_iso' {σ τ : Type v} [decidable_eq σ] [decidable_eq τ] [fintype τ] {S : σ → C} [has_biproduct.{v} S] {T : τ → C} [has_biproduct.{v} T] (s : σ) (f : ⨁ S ⟶ ⨁ T) [is_iso f] : (∀ t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t = 0) → 𝟙 (S s) = 0 := begin intro z, set x := biproduct.ι S s ≫ f ≫ inv f ≫ biproduct.π S s, have h₁ : x = 𝟙 (S s), by simp [x], have h₀ : x = 0, { dsimp [x], rw [←category.id_comp (inv f), category.assoc, ←biproduct.total], simp only [comp_sum_assoc], conv_lhs { congr, apply_congr, skip, simp only [reassoc_of z], }, simp, }, exact h₁.symm.trans h₀, end /-- If `f : ⨁ S ⟶ ⨁ T` is an isomorphism, and `s` is a non-trivial summand of the source, then there is some `t` in the target so that the `s, t` matrix entry of `f` is nonzero. -/ def biproduct.column_nonzero_of_iso {σ τ : Type v} [decidable_eq σ] [decidable_eq τ] [fintype τ] {S : σ → C} [has_biproduct.{v} S] {T : τ → C} [has_biproduct.{v} T] (s : σ) (nz : 𝟙 (S s) ≠ 0) [∀ t, decidable_eq (S s ⟶ T t)] (f : ⨁ S ⟶ ⨁ T) [is_iso f] : trunc (Σ' t : τ, biproduct.ι S s ≫ f ≫ biproduct.π T t ≠ 0) := begin apply trunc_sigma_of_exists, -- Do this before we run `classical`, so we get the right `decidable_eq` instances. have t := biproduct.column_nonzero_of_iso'.{v} s f, by_contradiction h, simp only [not_exists_not] at h, exact nz (t h) end end category_theory
fdee48c1e84f6c3581cdd0386c59768829baaf3a
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/calculus/mean_value.lean
a33c995c3c0709d319db2aee7b2d104aded3cc5d
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
62,640
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.local_extr import analysis.convex.topology import data.complex.is_R_or_C /-! # The mean value inequality and equalities In this file we prove the following facts: * `convex.norm_image_sub_le_of_norm_deriv_le` : if `f` is differentiable on a convex set `s` and the norm of its derivative is bounded by `C`, then `f` is Lipschitz continuous on `s` with constant `C`; also a variant in which what is bounded by `C` is the norm of the difference of the derivative from a fixed linear map. This lemma and its versions are formulated using `is_R_or_C`, so they work both for real and complex derivatives. * `image_le_of*`, `image_norm_le_of_*` : several similar lemmas deducing `f x ≤ B x` or `∥f x∥ ≤ B x` from upper estimates on `f'` or `∥f'∥`, respectively. These lemmas differ by their assumptions: * `of_liminf_*` lemmas assume that limit inferior of some ratio is less than `B' x`; * `of_deriv_right_*`, `of_norm_deriv_right_*` lemmas assume that the right derivative or its norm is less than `B' x`; * `of_*_lt_*` lemmas assume a strict inequality whenever `f x = B x` or `∥f x∥ = B x`; * `of_*_le_*` lemmas assume a non-strict inequality everywhere on `[a, b)`; * name of a lemma ends with `'` if (1) it assumes that `B` is continuous on `[a, b]` and has a right derivative at every point of `[a, b)`, and (2) the lemma has a counterpart assuming that `B` is differentiable everywhere on `ℝ` * `norm_image_sub_le_*_segment` : if derivative of `f` on `[a, b]` is bounded above by a constant `C`, then `∥f x - f a∥ ≤ C * ∥x - a∥`; several versions deal with right derivative and derivative within `[a, b]` (`has_deriv_within_at` or `deriv_within`). * `convex.is_const_of_fderiv_within_eq_zero` : if a function has derivative `0` on a convex set `s`, then it is a constant on `s`. * `exists_ratio_has_deriv_at_eq_ratio_slope` and `exists_ratio_deriv_eq_ratio_slope` : Cauchy's Mean Value Theorem. * `exists_has_deriv_at_eq_slope` and `exists_deriv_eq_slope` : Lagrange's Mean Value Theorem. * `domain_mvt` : Lagrange's Mean Value Theorem, applied to a segment in a convex domain. * `convex.image_sub_lt_mul_sub_of_deriv_lt`, `convex.mul_sub_lt_image_sub_of_lt_deriv`, `convex.image_sub_le_mul_sub_of_deriv_le`, `convex.mul_sub_le_image_sub_of_le_deriv`, if `∀ x, C (</≤/>/≥) (f' x)`, then `C * (y - x) (</≤/>/≥) (f y - f x)` whenever `x < y`. * `convex.mono_of_deriv_nonneg`, `convex.antimono_of_deriv_nonpos`, `convex.strict_mono_of_deriv_pos`, `convex.strict_antimono_of_deriv_neg` : if the derivative of a function is non-negative/non-positive/positive/negative, then the function is monotone/monotonically decreasing/strictly monotone/strictly monotonically decreasing. * `convex_on_of_deriv_mono`, `convex_on_of_deriv2_nonneg` : if the derivative of a function is increasing or its second derivative is nonnegative, then the original function is convex. * `strict_fderiv_of_cont_diff` : a C^1 function over the reals is strictly differentiable. (This is a corollary of the mean value inequality.) -/ variables {E : Type*} [normed_group E] [normed_space ℝ E] {F : Type*} [normed_group F] [normed_space ℝ F] open metric set asymptotics continuous_linear_map filter open_locale classical topological_space nnreal /-! ### One-dimensional fencing inequalities -/ /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin change Icc a b ⊆ {x | f x ≤ B x}, set s := {x | f x ≤ B x} ∩ Icc a b, have A : continuous_on (λ x, (f x, B x)) (Icc a b), from hf.prod hB, have : is_closed s, { simp only [s, inter_comm], exact A.preimage_closed_of_closed is_closed_Icc order_closed_topology.is_closed_le' }, apply this.Icc_subset_of_forall_exists_gt ha, rintros x ⟨hxB : f x ≤ B x, xab⟩ y hy, cases hxB.lt_or_eq with hxB hxB, { -- If `f x < B x`, then all we need is continuity of both sides refine nonempty_of_mem_sets (inter_mem_sets _ (Ioc_mem_nhds_within_Ioi ⟨le_rfl, hy⟩)), have : ∀ᶠ x in 𝓝[Icc a b] x, f x < B x, from A x (Ico_subset_Icc_self xab) (is_open.mem_nhds (is_open_lt continuous_fst continuous_snd) hxB), have : ∀ᶠ x in 𝓝[Ioi x] x, f x < B x, from nhds_within_le_of_mem (Icc_mem_nhds_within_Ioi xab) this, exact this.mono (λ y, le_of_lt) }, { rcases exists_between (bound x xab hxB) with ⟨r, hfr, hrB⟩, specialize hf' x xab r hfr, have HB : ∀ᶠ z in 𝓝[Ioi x] x, r < (z - x)⁻¹ * (B z - B x), from (has_deriv_within_at_iff_tendsto_slope' $ lt_irrefl x).1 (hB' x xab).Ioi_of_Ici (Ioi_mem_nhds hrB), obtain ⟨z, ⟨hfz, hzB⟩, hz⟩ : ∃ z, ((z - x)⁻¹ * (f z - f x) < r ∧ r < (z - x)⁻¹ * (B z - B x)) ∧ z ∈ Ioc x y, from ((hf'.and_eventually HB).and_eventually (Ioc_mem_nhds_within_Ioi ⟨le_rfl, hy⟩)).exists, refine ⟨z, _, hz⟩, have := (hfz.trans hzB).le, rwa [mul_le_mul_left (inv_pos.2 $ sub_pos.2 hz.1), hxB, sub_le_sub_iff_right] at this } end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)` is bounded above by `B'`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_liminf_slope_right_le_deriv_boundary {f : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) -- `bound` actually says `liminf (z - x)⁻¹ * (f z - f x) ≤ B' x` (bound : ∀ x ∈ Ico a b, ∀ r, B' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (f z - f x) < r) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := begin have Hr : ∀ x ∈ Icc a b, ∀ r > 0, f x ≤ B x + r * (x - a), { intros x hx r hr, apply image_le_of_liminf_slope_right_lt_deriv_boundary' hf bound, { rwa [sub_self, mul_zero, add_zero] }, { exact hB.add (continuous_on_const.mul (continuous_id.continuous_on.sub continuous_on_const)) }, { assume x hx, exact (hB' x hx).add (((has_deriv_within_at_id x (Ici x)).sub_const a).const_mul r) }, { assume x hx _, rw [mul_one], exact (lt_add_iff_pos_right _).2 hr }, exact hx }, assume x hx, have : continuous_within_at (λ r, B x + r * (x - a)) (Ioi 0) 0, from continuous_within_at_const.add (continuous_within_at_id.mul continuous_within_at_const), convert continuous_within_at_const.closure_le _ this (Hr x hx); simp end /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has right derivative `B'` at every point of `[a, b)`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' hf (λ x hx r hr, (hf' x hx).liminf_right_slope_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x < B' x` whenever `f x = B x`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `f a ≤ B a`; * `B` has derivative `B'` everywhere on `ℝ`; * `f` has right derivative `f'` at every point of `[a, b)`; * we have `f' x ≤ B' x` on `[a, b)`. Then `f x ≤ B x` everywhere on `[a, b]`. -/ lemma image_le_of_deriv_right_le_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, f' x ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary hf ha hB hB' $ assume x hx r hr, (hf' x hx).liminf_right_slope_le (lt_of_le_of_lt (bound x hx) hr) /-! ### Vector-valued functions `f : ℝ → E` -/ section variables {f : ℝ → E} {a b : ℝ} /-- General fencing theorem for continuous functions with an estimate on the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `B` has right derivative at every point of `[a, b)`; * for each `x ∈ [a, b)` the right-side limit inferior of `(∥f z∥ - ∥f x∥) / (z - x)` is bounded above by a function `f'`; * we have `f' x < B' x` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. -/ lemma image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary {E : Type*} [normed_group E] {f : ℝ → E} {f' : ℝ → ℝ} (hf : continuous_on f (Icc a b)) -- `hf'` actually says `liminf ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) ≤ f' x` (hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[Ioi x] x, (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → f' x < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_le_of_liminf_slope_right_lt_deriv_boundary' (continuous_norm.comp_continuous_on hf) hf' ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary hf (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le hr) ha hB hB' bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_norm_deriv_right_lt_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`; * we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary' {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b)) (hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_le_of_liminf_slope_right_le_deriv_boundary (continuous_norm.comp_continuous_on hf) ha hB hB' $ (λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le (lt_of_le_of_lt (bound x hx) hr)) /-- General fencing theorem for continuous functions with an estimate on the norm of the derivative. Let `f` and `B` be continuous functions on `[a, b]` such that * `∥f a∥ ≤ B a`; * `f` has right derivative `f'` at every point of `[a, b)`; * `B` has derivative `B'` everywhere on `ℝ`; * we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`. Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions to make this theorem work for piecewise differentiable functions. -/ lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary {f' : ℝ → E} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) {B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x) (bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) : ∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x := image_norm_le_of_norm_deriv_right_le_deriv_boundary' hf hf' ha (λ x hx, (hB x).continuous_at.continuous_within_at) (λ x hx, (hB x).has_deriv_within_at) bound /-- A function on `[a, b]` with the norm of the right derivative bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`. -/ theorem norm_image_sub_le_of_norm_deriv_right_le_segment {f' : ℝ → E} {C : ℝ} (hf : continuous_on f (Icc a b)) (hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin let g := λ x, f x - f a, have hg : continuous_on g (Icc a b), from hf.sub continuous_on_const, have hg' : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ici x) x, { assume x hx, simpa using (hf' x hx).sub (has_deriv_within_at_const _ _ _) }, let B := λ x, C * (x - a), have hB : ∀ x, has_deriv_at B C x, { assume x, simpa using (has_deriv_at_const x C).mul ((has_deriv_at_id x).sub (has_deriv_at_const x a)) }, convert image_norm_le_of_norm_deriv_right_le_deriv_boundary hg hg' _ hB bound, simp only [g, B], rw [sub_self, norm_zero, sub_self, mul_zero] end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc a b, has_deriv_within_at f (f' x) (Icc a b) x) (bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_right_le_segment (λ x hx, (hf x hx).continuous_within_at) (λ x hx, _) bound, exact (hf x $ Ico_subset_Icc_self hx).nhds_within (Icc_mem_nhds_within_Ici hx) end /-- A function on `[a, b]` with the norm of the derivative within `[a, b]` bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment {C : ℝ} (hf : differentiable_on ℝ f (Icc a b)) (bound : ∀x ∈ Ico a b, ∥deriv_within f (Icc a b) x∥ ≤ C) : ∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) := begin refine norm_image_sub_le_of_norm_deriv_le_segment' _ bound, exact λ x hx, (hf x hx).has_deriv_within_at end /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `has_deriv_within_at` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01' {f' : ℝ → E} {C : ℝ} (hf : ∀ x ∈ Icc (0:ℝ) 1, has_deriv_within_at f (f' x) (Icc (0:ℝ) 1) x) (bound : ∀x ∈ Ico (0:ℝ) 1, ∥f' x∥ ≤ C) : ∥f 1 - f 0∥ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment' hf bound 1 (right_mem_Icc.2 zero_le_one) /-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]` bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `deriv_within` version. -/ theorem norm_image_sub_le_of_norm_deriv_le_segment_01 {C : ℝ} (hf : differentiable_on ℝ f (Icc (0:ℝ) 1)) (bound : ∀x ∈ Ico (0:ℝ) 1, ∥deriv_within f (Icc (0:ℝ) 1) x∥ ≤ C) : ∥f 1 - f 0∥ ≤ C := by simpa only [sub_zero, mul_one] using norm_image_sub_le_of_norm_deriv_le_segment hf bound 1 (right_mem_Icc.2 zero_le_one) theorem constant_of_has_deriv_right_zero (hcont : continuous_on f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, has_deriv_within_at f 0 (Ici x) x) : ∀ x ∈ Icc a b, f x = f a := by simpa only [zero_mul, norm_le_zero_iff, sub_eq_zero] using λ x hx, norm_image_sub_le_of_norm_deriv_right_le_segment hcont hderiv (λ y hy, by rw norm_le_zero_iff) x hx theorem constant_of_deriv_within_zero (hdiff : differentiable_on ℝ f (Icc a b)) (hderiv : ∀ x ∈ Ico a b, deriv_within f (Icc a b) x = 0) : ∀ x ∈ Icc a b, f x = f a := begin have H : ∀ x ∈ Ico a b, ∥deriv_within f (Icc a b) x∥ ≤ 0 := by simpa only [norm_le_zero_iff] using λ x hx, hderiv x hx, simpa only [zero_mul, norm_le_zero_iff, sub_eq_zero] using λ x hx, norm_image_sub_le_of_norm_deriv_le_segment hdiff H x hx, end variables {f' g : ℝ → E} /-- If two continuous functions on `[a, b]` have the same right derivative and are equal at `a`, then they are equal everywhere on `[a, b]`. -/ theorem eq_of_has_deriv_right_eq (derivf : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x) (derivg : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ici x) x) (fcont : continuous_on f (Icc a b)) (gcont : continuous_on g (Icc a b)) (hi : f a = g a) : ∀ y ∈ Icc a b, f y = g y := begin simp only [← @sub_eq_zero _ _ (f _)] at hi ⊢, exact hi ▸ constant_of_has_deriv_right_zero (fcont.sub gcont) (λ y hy, by simpa only [sub_self] using (derivf y hy).sub (derivg y hy)), end /-- If two differentiable functions on `[a, b]` have the same derivative within `[a, b]` everywhere on `[a, b)` and are equal at `a`, then they are equal everywhere on `[a, b]`. -/ theorem eq_of_deriv_within_eq (fdiff : differentiable_on ℝ f (Icc a b)) (gdiff : differentiable_on ℝ g (Icc a b)) (hderiv : eq_on (deriv_within f (Icc a b)) (deriv_within g (Icc a b)) (Ico a b)) (hi : f a = g a) : ∀ y ∈ Icc a b, f y = g y := begin have A : ∀ y ∈ Ico a b, has_deriv_within_at f (deriv_within f (Icc a b) y) (Ici y) y := λ y hy, (fdiff y (mem_Icc_of_Ico hy)).has_deriv_within_at.nhds_within (Icc_mem_nhds_within_Ici hy), have B : ∀ y ∈ Ico a b, has_deriv_within_at g (deriv_within g (Icc a b) y) (Ici y) y := λ y hy, (gdiff y (mem_Icc_of_Ico hy)).has_deriv_within_at.nhds_within (Icc_mem_nhds_within_Ici hy), exact eq_of_has_deriv_right_eq A (λ y hy, (hderiv hy).symm ▸ B y hy) fdiff.continuous_on gdiff.continuous_on hi end end /-! ### Vector-valued functions `f : E → G` Theorems in this section work both for real and complex differentiable functions. We use assumptions `[is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 G]` to achieve this result. For the domain `E` we also assume `[normed_space ℝ E] [is_scalar_tower ℝ 𝕜 E]` to have a notion of a `convex` set. In both interesting cases `𝕜 = ℝ` and `𝕜 = ℂ` the assumption `[is_scalar_tower ℝ 𝕜 E]` is satisfied automatically. -/ section variables {𝕜 G : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] [is_scalar_tower ℝ 𝕜 E] [normed_group G] [normed_space 𝕜 G] {f : E → G} {C : ℝ} {s : set E} {x y : E} {f' : E → E →L[𝕜] G} {φ : E →L[𝕜] G} /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `has_fderiv_within`. -/ theorem convex.norm_image_sub_le_of_norm_has_fderiv_within_le (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥ ≤ C) (hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := begin letI : normed_space ℝ G := restrict_scalars.normed_space ℝ 𝕜 G, letI : is_scalar_tower ℝ 𝕜 G := restrict_scalars.is_scalar_tower _ _ _, /- By composition with `t ↦ x + t • (y-x)`, we reduce to a statement for functions defined on `[0,1]`, for which it is proved in `norm_image_sub_le_of_norm_deriv_le_segment`. We just have to check the differentiability of the composition and bounds on its derivative, which is straightforward but tedious for lack of automation. -/ have C0 : 0 ≤ C := le_trans (norm_nonneg _) (bound x xs), set g : ℝ → E := λ t, x + t • (y - x), have Dg : ∀ t, has_deriv_at g (y-x) t, { assume t, simpa only [one_smul] using ((has_deriv_at_id t).smul_const (y - x)).const_add x }, have segm : Icc 0 1 ⊆ g ⁻¹' s, { rw [← image_subset_iff, ← segment_eq_image'], apply hs.segment_subset xs ys }, have : f x = f (g 0), by { simp only [g], rw [zero_smul, add_zero] }, rw this, have : f y = f (g 1), by { simp only [g], rw [one_smul, add_sub_cancel'_right] }, rw this, have D2: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g) (f' (g t) (y - x)) (Icc 0 1) t, { intros t ht, have : has_fderiv_within_at f ((f' (g t)).restrict_scalars ℝ) s (g t), from hf (g t) (segm ht), exact this.comp_has_deriv_within_at _ (Dg t).has_deriv_within_at segm }, apply norm_image_sub_le_of_norm_deriv_le_segment_01' D2, refine λ t ht, le_of_op_norm_le _ _ _, exact bound (g t) (segm $ Ico_subset_Icc_self ht) end /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `has_fderiv_within` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_has_fderiv_within_le {C : ℝ≥0} (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥₊ ≤ C) (hs : convex s) : lipschitz_on_with C f s := begin rw lipschitz_on_with_iff_norm_sub_le, intros x x_in y y_in, exact hs.norm_image_sub_le_of_norm_has_fderiv_within_le hf bound y_in x_in end /-- Let `s` be a convex set in a real normed vector space `E`, let `f : E → G` be a function differentiable within `s` in a neighborhood of `x : E` with derivative `f'`. Suppose that `f'` is continuous within `s` at `x`. Then for any number `K : ℝ≥0` larger than `∥f' x∥₊`, `f` is `K`-Lipschitz on some neighborhood of `x` within `s`. See also `convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at` for a version that claims existence of `K` instead of an explicit estimate. -/ lemma convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt (hs : convex s) {f : E → G} (hder : ∀ᶠ y in 𝓝[s] x, has_fderiv_within_at f (f' y) s y) (hcont : continuous_within_at f' s x) (K : ℝ≥0) (hK : ∥f' x∥₊ < K) : ∃ t ∈ 𝓝[s] x, lipschitz_on_with K f t := begin obtain ⟨ε, ε0, hε⟩ : ∃ ε > 0, ball x ε ∩ s ⊆ {y | has_fderiv_within_at f (f' y) s y ∧ ∥f' y∥₊ < K}, from mem_nhds_within_iff.1 (hder.and $ hcont.nnnorm.eventually (gt_mem_nhds hK)), rw inter_comm at hε, refine ⟨s ∩ ball x ε, inter_mem_nhds_within _ (ball_mem_nhds _ ε0), _⟩, exact (hs.inter (convex_ball _ _)).lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ y hy, (hε hy).1.mono (inter_subset_left _ _)) (λ y hy, (hε hy).2.le) end /-- Let `s` be a convex set in a real normed vector space `E`, let `f : E → G` be a function differentiable within `s` in a neighborhood of `x : E` with derivative `f'`. Suppose that `f'` is continuous within `s` at `x`. Then for any number `K : ℝ≥0` larger than `∥f' x∥₊`, `f` is Lipschitz on some neighborhood of `x` within `s`. See also `convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt` for a version with an explicit estimate on the Lipschitz constant. -/ lemma convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at (hs : convex s) {f : E → G} (hder : ∀ᶠ y in 𝓝[s] x, has_fderiv_within_at f (f' y) s y) (hcont : continuous_within_at f' s x) : ∃ K (t ∈ 𝓝[s] x), lipschitz_on_with K f t := (no_top _).imp $ hs.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt hder hcont /-- The mean value theorem on a convex set: if the derivative of a function within this set is bounded by `C`, then the function is `C`-Lipschitz. Version with `fderiv_within`. -/ theorem convex.norm_image_sub_le_of_norm_fderiv_within_le (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥fderiv_within 𝕜 f s x∥ ≤ C) (hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) bound xs ys /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `fderiv_within` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_fderiv_within_le {C : ℝ≥0} (hf : differentiable_on 𝕜 f s) (bound : ∀ x ∈ s, ∥fderiv_within 𝕜 f s x∥₊ ≤ C) (hs : convex s) : lipschitz_on_with C f s:= hs.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) bound /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `fderiv`. -/ theorem convex.norm_image_sub_le_of_norm_fderiv_le (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x∥ ≤ C) (hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound xs ys /-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `fderiv` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_fderiv_le {C : ℝ≥0} (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x∥₊ ≤ C) (hs : convex s) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound /-- Variant of the mean value inequality on a convex set, using a bound on the difference between the derivative and a fixed linear map, rather than a bound on the derivative itself. Version with `has_fderiv_within`. -/ theorem convex.norm_image_sub_le_of_norm_has_fderiv_within_le' (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x - φ∥ ≤ C) (hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ := begin /- We subtract `φ` to define a new function `g` for which `g' = 0`, for which the previous theorem applies, `convex.norm_image_sub_le_of_norm_has_fderiv_within_le`. Then, we just need to glue together the pieces, expressing back `f` in terms of `g`. -/ let g := λy, f y - φ y, have hg : ∀ x ∈ s, has_fderiv_within_at g (f' x - φ) s x := λ x xs, (hf x xs).sub φ.has_fderiv_within_at, calc ∥f y - f x - φ (y - x)∥ = ∥f y - f x - (φ y - φ x)∥ : by simp ... = ∥(f y - φ y) - (f x - φ x)∥ : by abel ... = ∥g y - g x∥ : by simp ... ≤ C * ∥y - x∥ : convex.norm_image_sub_le_of_norm_has_fderiv_within_le hg bound hs xs ys, end /-- Variant of the mean value inequality on a convex set. Version with `fderiv_within`. -/ theorem convex.norm_image_sub_le_of_norm_fderiv_within_le' (hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥fderiv_within 𝕜 f s x - φ∥ ≤ C) (hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le' (λ x hx, (hf x hx).has_fderiv_within_at) bound xs ys /-- Variant of the mean value inequality on a convex set. Version with `fderiv`. -/ theorem convex.norm_image_sub_le_of_norm_fderiv_le' (hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x - φ∥ ≤ C) (hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_fderiv_within_le' (λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound xs ys /-- If a function has zero Fréchet derivative at every point of a convex set, then it is a constant on this set. -/ theorem convex.is_const_of_fderiv_within_eq_zero (hs : convex s) (hf : differentiable_on 𝕜 f s) (hf' : ∀ x ∈ s, fderiv_within 𝕜 f s x = 0) (hx : x ∈ s) (hy : y ∈ s) : f x = f y := have bound : ∀ x ∈ s, ∥fderiv_within 𝕜 f s x∥ ≤ 0, from λ x hx, by simp only [hf' x hx, norm_zero], by simpa only [(dist_eq_norm _ _).symm, zero_mul, dist_le_zero, eq_comm] using hs.norm_image_sub_le_of_norm_fderiv_within_le hf bound hx hy theorem is_const_of_fderiv_eq_zero (hf : differentiable 𝕜 f) (hf' : ∀ x, fderiv 𝕜 f x = 0) (x y : E) : f x = f y := convex_univ.is_const_of_fderiv_within_eq_zero hf.differentiable_on (λ x _, by rw fderiv_within_univ; exact hf' x) trivial trivial end /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `has_deriv_within`. -/ theorem convex.norm_image_sub_le_of_norm_has_deriv_within_le {f f' : ℝ → F} {C : ℝ} {s : set ℝ} {x y : ℝ} (hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥ ≤ C) (hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := convex.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) (λ x hx, le_trans (by simp) (bound x hx)) hs xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `has_deriv_within` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_has_deriv_within_le {f f' : ℝ → F} {C : ℝ≥0} {s : set ℝ} (hs : convex s) (hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥₊ ≤ C) : lipschitz_on_with C f s := convex.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) (λ x hx, le_trans (by simp) (bound x hx)) hs /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function within this set is bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv_within` -/ theorem convex.norm_image_sub_le_of_norm_deriv_within_le {f : ℝ → F} {C : ℝ} {s : set ℝ} {x y : ℝ} (hf : differentiable_on ℝ f s) (bound : ∀x∈s, ∥deriv_within f s x∥ ≤ C) (hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_within_at) bound xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `deriv_within` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_deriv_within_le {f : ℝ → F} {C : ℝ≥0} {s : set ℝ} (hs : convex s) (hf : differentiable_on ℝ f s) (bound : ∀x∈s, ∥deriv_within f s x∥₊ ≤ C) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_within_at) bound /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv`. -/ theorem convex.norm_image_sub_le_of_norm_deriv_le {f : ℝ → F} {C : ℝ} {s : set ℝ} {x y : ℝ} (hf : ∀ x ∈ s, differentiable_at ℝ f x) (bound : ∀x∈s, ∥deriv f x∥ ≤ C) (hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ := hs.norm_image_sub_le_of_norm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_at.has_deriv_within_at) bound xs ys /-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`. Version with `deriv` and `lipschitz_on_with`. -/ theorem convex.lipschitz_on_with_of_nnnorm_deriv_le {f : ℝ → F} {C : ℝ≥0} {s : set ℝ} (hf : ∀ x ∈ s, differentiable_at ℝ f x) (bound : ∀x∈s, ∥deriv f x∥₊ ≤ C) (hs : convex s) : lipschitz_on_with C f s := hs.lipschitz_on_with_of_nnnorm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_at.has_deriv_within_at) bound /-! ### Functions `[a, b] → ℝ`. -/ section interval -- Declare all variables here to make sure they come in a correct order variables (f f' : ℝ → ℝ) {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b)) (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hfd : differentiable_on ℝ f (Ioo a b)) (g g' : ℝ → ℝ) (hgc : continuous_on g (Icc a b)) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hgd : differentiable_on ℝ g (Ioo a b)) include hab hfc hff' hgc hgg' /-- Cauchy's **Mean Value Theorem**, `has_deriv_at` version. -/ lemma exists_ratio_has_deriv_at_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * f' c = (f b - f a) * g' c := begin let h := λ x, (g b - g a) * f x - (f b - f a) * g x, have hI : h a = h b, { simp only [h], ring }, let h' := λ x, (g b - g a) * f' x - (f b - f a) * g' x, have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x, from λ x hx, ((hff' x hx).const_mul (g b - g a)).sub ((hgg' x hx).const_mul (f b - f a)), have hhc : continuous_on h (Icc a b), from (continuous_on_const.mul hfc).sub (continuous_on_const.mul hgc), rcases exists_has_deriv_at_eq_zero h h' hab hhc hI hhh' with ⟨c, cmem, hc⟩, exact ⟨c, cmem, sub_eq_zero.1 hc⟩ end omit hfc hgc /-- Cauchy's **Mean Value Theorem**, extended `has_deriv_at` version. -/ lemma exists_ratio_has_deriv_at_eq_ratio_slope' {lfa lga lfb lgb : ℝ} (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 lfa)) (hga : tendsto g (𝓝[Ioi a] a) (𝓝 lga)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 lfb)) (hgb : tendsto g (𝓝[Iio b] b) (𝓝 lgb)) : ∃ c ∈ Ioo a b, (lgb - lga) * (f' c) = (lfb - lfa) * (g' c) := begin let h := λ x, (lgb - lga) * f x - (lfb - lfa) * g x, have hha : tendsto h (𝓝[Ioi a] a) (𝓝 $ lgb * lfa - lfb * lga), { have : tendsto h (𝓝[Ioi a] a)(𝓝 $ (lgb - lga) * lfa - (lfb - lfa) * lga) := (tendsto_const_nhds.mul hfa).sub (tendsto_const_nhds.mul hga), convert this using 2, ring }, have hhb : tendsto h (𝓝[Iio b] b) (𝓝 $ lgb * lfa - lfb * lga), { have : tendsto h (𝓝[Iio b] b)(𝓝 $ (lgb - lga) * lfb - (lfb - lfa) * lgb) := (tendsto_const_nhds.mul hfb).sub (tendsto_const_nhds.mul hgb), convert this using 2, ring }, let h' := λ x, (lgb - lga) * f' x - (lfb - lfa) * g' x, have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x, { intros x hx, exact ((hff' x hx).const_mul _ ).sub (((hgg' x hx)).const_mul _) }, rcases exists_has_deriv_at_eq_zero' hab hha hhb hhh' with ⟨c, cmem, hc⟩, exact ⟨c, cmem, sub_eq_zero.1 hc⟩ end include hfc omit hgg' /-- Lagrange's Mean Value Theorem, `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_slope : ∃ c ∈ Ioo a b, f' c = (f b - f a) / (b - a) := begin rcases exists_ratio_has_deriv_at_eq_ratio_slope f f' hab hfc hff' id 1 continuous_id.continuous_on (λ x hx, has_deriv_at_id x) with ⟨c, cmem, hc⟩, use [c, cmem], simp only [_root_.id, pi.one_apply, mul_one] at hc, rw [← hc, mul_div_cancel_left], exact ne_of_gt (sub_pos.2 hab) end omit hff' /-- Cauchy's Mean Value Theorem, `deriv` version. -/ lemma exists_ratio_deriv_eq_ratio_slope : ∃ c ∈ Ioo a b, (g b - g a) * (deriv f c) = (f b - f a) * (deriv g c) := exists_ratio_has_deriv_at_eq_ratio_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at) g (deriv g) hgc $ λ x hx, ((hgd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at omit hfc /-- Cauchy's Mean Value Theorem, extended `deriv` version. -/ lemma exists_ratio_deriv_eq_ratio_slope' {lfa lga lfb lgb : ℝ} (hdf : differentiable_on ℝ f $ Ioo a b) (hdg : differentiable_on ℝ g $ Ioo a b) (hfa : tendsto f (𝓝[Ioi a] a) (𝓝 lfa)) (hga : tendsto g (𝓝[Ioi a] a) (𝓝 lga)) (hfb : tendsto f (𝓝[Iio b] b) (𝓝 lfb)) (hgb : tendsto g (𝓝[Iio b] b) (𝓝 lgb)) : ∃ c ∈ Ioo a b, (lgb - lga) * (deriv f c) = (lfb - lfa) * (deriv g c) := exists_ratio_has_deriv_at_eq_ratio_slope' _ _ hab _ _ (λ x hx, ((hdf x hx).differentiable_at $ Ioo_mem_nhds hx.1 hx.2).has_deriv_at) (λ x hx, ((hdg x hx).differentiable_at $ Ioo_mem_nhds hx.1 hx.2).has_deriv_at) hfa hga hfb hgb /-- Lagrange's **Mean Value Theorem**, `deriv` version. -/ lemma exists_deriv_eq_slope : ∃ c ∈ Ioo a b, deriv f c = (f b - f a) / (b - a) := exists_has_deriv_at_eq_slope f (deriv f) hab hfc (λ x hx, ((hfd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at) end interval /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C < f'`, then `f` grows faster than `C * x` on `D`, i.e., `C * (y - x) < f y - f x` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.mul_sub_lt_image_sub_of_lt_deriv {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_gt : ∀ x ∈ interior D, C < deriv f x) : ∀ x y ∈ D, x < y → C * (y - x) < f y - f x := begin assume x y hx hy hxy, have hxyD : Icc x y ⊆ D, from hD.ord_connected.out hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), have : C < (f y - f x) / (y - x), by { rw [← ha], exact hf'_gt _ (hxyD' a_mem) }, exact (lt_div_iff (sub_pos.2 hxy)).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C < f'`, then `f` grows faster than `C * x`, i.e., `C * (y - x) < f y - f x` whenever `x < y`. -/ theorem mul_sub_lt_image_sub_of_lt_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_gt : ∀ x, C < deriv f x) ⦃x y⦄ (hxy : x < y) : C * (y - x) < f y - f x := convex_univ.mul_sub_lt_image_sub_of_lt_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_gt x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `C ≤ f'`, then `f` grows at least as fast as `C * x` on `D`, i.e., `C * (y - x) ≤ f y - f x` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.mul_sub_le_image_sub_of_le_deriv {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (hf'_ge : ∀ x ∈ interior D, C ≤ deriv f x) : ∀ x y ∈ D, x ≤ y → C * (y - x) ≤ f y - f x := begin assume x y hx hy hxy, cases eq_or_lt_of_le hxy with hxy' hxy', by rw [hxy', sub_self, sub_self, mul_zero], have hxyD : Icc x y ⊆ D, from hD.ord_connected.out hx hy, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy' (hf.mono hxyD) (hf'.mono hxyD'), have : C ≤ (f y - f x) / (y - x), by { rw [← ha], exact hf'_ge _ (hxyD' a_mem) }, exact (le_div_iff (sub_pos.2 hxy')).1 this end /-- Let `f : ℝ → ℝ` be a differentiable function. If `C ≤ f'`, then `f` grows at least as fast as `C * x`, i.e., `C * (y - x) ≤ f y - f x` whenever `x ≤ y`. -/ theorem mul_sub_le_image_sub_of_le_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (hf'_ge : ∀ x, C ≤ deriv f x) ⦃x y⦄ (hxy : x ≤ y) : C * (y - x) ≤ f y - f x := convex_univ.mul_sub_le_image_sub_of_le_deriv hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_ge x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x, y ∈ D`, `x < y`. -/ theorem convex.image_sub_lt_mul_sub_of_deriv_lt {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (lt_hf' : ∀ x ∈ interior D, deriv f x < C) : ∀ x y ∈ D, x < y → f y - f x < C * (y - x) := begin assume x y hx hy hxy, have hf'_gt : ∀ x ∈ interior D, -C < deriv (λ y, -f y) x, { assume x hx, rw [deriv.neg, neg_lt_neg_iff], exact lt_hf' x hx }, simpa [-neg_lt_neg_iff] using neg_lt_neg (hD.mul_sub_lt_image_sub_of_lt_deriv hf.neg hf'.neg hf'_gt x y hx hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' < C`, then `f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x < y`. -/ theorem image_sub_lt_mul_sub_of_deriv_lt {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (lt_hf' : ∀ x, deriv f x < C) ⦃x y⦄ (hxy : x < y) : f y - f x < C * (y - x) := convex_univ.image_sub_lt_mul_sub_of_deriv_lt hf.continuous.continuous_on hf.differentiable_on (λ x _, lt_hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f' ≤ C`, then `f` grows at most as fast as `C * x` on `D`, i.e., `f y - f x ≤ C * (y - x)` whenever `x, y ∈ D`, `x ≤ y`. -/ theorem convex.image_sub_le_mul_sub_of_deriv_le {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) {C} (le_hf' : ∀ x ∈ interior D, deriv f x ≤ C) : ∀ x y ∈ D, x ≤ y → f y - f x ≤ C * (y - x) := begin assume x y hx hy hxy, have hf'_ge : ∀ x ∈ interior D, -C ≤ deriv (λ y, -f y) x, { assume x hx, rw [deriv.neg, neg_le_neg_iff], exact le_hf' x hx }, simpa [-neg_le_neg_iff] using neg_le_neg (hD.mul_sub_le_image_sub_of_le_deriv hf.neg hf'.neg hf'_ge x y hx hy hxy) end /-- Let `f : ℝ → ℝ` be a differentiable function. If `f' ≤ C`, then `f` grows at most as fast as `C * x`, i.e., `f y - f x ≤ C * (y - x)` whenever `x ≤ y`. -/ theorem image_sub_le_mul_sub_of_deriv_le {f : ℝ → ℝ} (hf : differentiable ℝ f) {C} (le_hf' : ∀ x, deriv f x ≤ C) ⦃x y⦄ (hxy : x ≤ y) : f y - f x ≤ C * (y - x) := convex_univ.image_sub_le_mul_sub_of_deriv_le hf.continuous.continuous_on hf.differentiable_on (λ x _, le_hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is positive, then `f` is a strictly monotonically increasing function on `D`. -/ theorem convex.strict_mono_of_deriv_pos {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_pos : ∀ x ∈ interior D, 0 < deriv f x) : ∀ x y ∈ D, x < y → f x < f y := by simpa only [zero_mul, sub_pos] using hD.mul_sub_lt_image_sub_of_lt_deriv hf hf' hf'_pos /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is positive, then `f` is a strictly monotonically increasing function. -/ theorem strict_mono_of_deriv_pos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_pos : ∀ x, 0 < deriv f x) : strict_mono f := λ x y hxy, convex_univ.strict_mono_of_deriv_pos hf.continuous.continuous_on hf.differentiable_on (λ x _, hf'_pos x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonnegative, then `f` is a monotonically increasing function on `D`. -/ theorem convex.mono_of_deriv_nonneg {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonneg : ∀ x ∈ interior D, 0 ≤ deriv f x) : ∀ x y ∈ D, x ≤ y → f x ≤ f y := by simpa only [zero_mul, sub_nonneg] using hD.mul_sub_le_image_sub_of_le_deriv hf hf' hf'_nonneg /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonnegative, then `f` is a monotonically increasing function. -/ theorem mono_of_deriv_nonneg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, 0 ≤ deriv f x) : monotone f := λ x y hxy, convex_univ.mono_of_deriv_nonneg hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is negative, then `f` is a strictly monotonically decreasing function on `D`. -/ theorem convex.strict_antimono_of_deriv_neg {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_neg : ∀ x ∈ interior D, deriv f x < 0) : ∀ x y ∈ D, x < y → f y < f x := by simpa only [zero_mul, sub_lt_zero] using hD.image_sub_lt_mul_sub_of_deriv_lt hf hf' hf'_neg /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is negative, then `f` is a strictly monotonically decreasing function. -/ theorem strict_antimono_of_deriv_neg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x < 0) : ∀ ⦃x y⦄, x < y → f y < f x := λ x y hxy, convex_univ.strict_antimono_of_deriv_neg hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) x y trivial trivial hxy /-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D` of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonpositive, then `f` is a monotonically decreasing function on `D`. -/ theorem convex.antimono_of_deriv_nonpos {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_nonpos : ∀ x ∈ interior D, deriv f x ≤ 0) : ∀ x y ∈ D, x ≤ y → f y ≤ f x := by simpa only [zero_mul, sub_nonpos] using hD.image_sub_le_mul_sub_of_deriv_le hf hf' hf'_nonpos /-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonpositive, then `f` is a monotonically decreasing function. -/ theorem antimono_of_deriv_nonpos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x ≤ 0) : ∀ ⦃x y⦄, x ≤ y → f y ≤ f x := λ x y hxy, convex_univ.antimono_of_deriv_nonpos hf.continuous.continuous_on hf.differentiable_on (λ x _, hf' x) x y trivial trivial hxy /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is monotone on the interior, then `f` is convex on `D`. -/ theorem convex_on_of_deriv_mono {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_mono : ∀ x y ∈ interior D, x ≤ y → deriv f x ≤ deriv f y) : convex_on D f := convex_on_real_of_slope_mono_adjacent hD begin intros x y z hx hz hxy hyz, -- First we prove some trivial inclusions have hxzD : Icc x z ⊆ D, from hD.ord_connected.out hx hz, have hxyD : Icc x y ⊆ D, from subset.trans (Icc_subset_Icc_right $ le_of_lt hyz) hxzD, have hxyD' : Ioo x y ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩, have hyzD : Icc y z ⊆ D, from subset.trans (Icc_subset_Icc_left $ le_of_lt hxy) hxzD, have hyzD' : Ioo y z ⊆ interior D, from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hyzD⟩, -- Then we apply MVT to both `[x, y]` and `[y, z]` obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x), from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'), obtain ⟨b, ⟨hyb, hbz⟩, hb⟩ : ∃ b ∈ Ioo y z, deriv f b = (f z - f y) / (z - y), from exists_deriv_eq_slope f hyz (hf.mono hyzD) (hf'.mono hyzD'), rw [← ha, ← hb], exact hf'_mono a b (hxyD' ⟨hxa, hay⟩) (hyzD' ⟨hyb, hbz⟩) (le_of_lt $ lt_trans hay hyb) end /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior, and `f'` is antimonotone on the interior, then `f` is concave on `D`. -/ theorem concave_on_of_deriv_antimono {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'_mono : ∀ x y ∈ interior D, x ≤ y → deriv f y ≤ deriv f x) : concave_on D f := begin have : ∀ x y ∈ interior D, x ≤ y → deriv (-f) x ≤ deriv (-f) y, { intros x y hx hy hxy, convert neg_le_neg (hf'_mono x y hx hy hxy); convert deriv.neg }, exact (neg_convex_on_iff D f).mp (convex_on_of_deriv_mono hD hf.neg hf'.neg this), end /-- If a function `f` is differentiable and `f'` is monotone on `ℝ` then `f` is convex. -/ theorem convex_on_univ_of_deriv_mono {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_mono : monotone (deriv f)) : convex_on univ f := convex_on_of_deriv_mono convex_univ hf.continuous.continuous_on hf.differentiable_on (λ x y _ _ h, hf'_mono h) /-- If a function `f` is differentiable and `f'` is antimonotone on `ℝ` then `f` is concave. -/ theorem concave_on_univ_of_deriv_antimono {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf'_antimono : ∀⦃a b⦄, a ≤ b → (deriv f) b ≤ (deriv f) a) : concave_on univ f := concave_on_of_deriv_antimono convex_univ hf.continuous.continuous_on hf.differentiable_on (λ x y _ _ h, hf'_antimono h) /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is nonnegative on the interior, then `f` is convex on `D`. -/ theorem convex_on_of_deriv2_nonneg {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : differentiable_on ℝ (deriv f) (interior D)) (hf''_nonneg : ∀ x ∈ interior D, 0 ≤ (deriv^[2] f x)) : convex_on D f := convex_on_of_deriv_mono hD hf hf' $ assume x y hx hy hxy, hD.interior.mono_of_deriv_nonneg hf''.continuous_on (by rwa [interior_interior]) (by rwa [interior_interior]) _ _ hx hy hxy /-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its interior, and `f''` is nonpositive on the interior, then `f` is concave on `D`. -/ theorem concave_on_of_deriv2_nonpos {D : set ℝ} (hD : convex D) {f : ℝ → ℝ} (hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D)) (hf'' : differentiable_on ℝ (deriv f) (interior D)) (hf''_nonpos : ∀ x ∈ interior D, (deriv^[2] f x) ≤ 0) : concave_on D f := concave_on_of_deriv_antimono hD hf hf' $ assume x y hx hy hxy, hD.interior.antimono_of_deriv_nonpos hf''.continuous_on (by rwa [interior_interior]) (by rwa [interior_interior]) _ _ hx hy hxy /-- If a function `f` is twice differentiable on a open convex set `D ⊆ ℝ` and `f''` is nonnegative on `D`, then `f` is convex on `D`. -/ theorem convex_on_open_of_deriv2_nonneg {D : set ℝ} (hD : convex D) (hD₂ : is_open D) {f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : differentiable_on ℝ (deriv f) D) (hf''_nonneg : ∀ x ∈ D, 0 ≤ (deriv^[2] f x)) : convex_on D f := convex_on_of_deriv2_nonneg hD hf'.continuous_on (by simpa [hD₂.interior_eq] using hf') (by simpa [hD₂.interior_eq] using hf'') (by simpa [hD₂.interior_eq] using hf''_nonneg) /-- If a function `f` is twice differentiable on a open convex set `D ⊆ ℝ` and `f''` is nonpositive on `D`, then `f` is concave on `D`. -/ theorem concave_on_open_of_deriv2_nonpos {D : set ℝ} (hD : convex D) (hD₂ : is_open D) {f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : differentiable_on ℝ (deriv f) D) (hf''_nonpos : ∀ x ∈ D, (deriv^[2] f x) ≤ 0) : concave_on D f := concave_on_of_deriv2_nonpos hD hf'.continuous_on (by simpa [hD₂.interior_eq] using hf') (by simpa [hD₂.interior_eq] using hf'') (by simpa [hD₂.interior_eq] using hf''_nonpos) /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonnegative on `ℝ`, then `f` is convex on `ℝ`. -/ theorem convex_on_univ_of_deriv2_nonneg {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : differentiable ℝ (deriv f)) (hf''_nonneg : ∀ x, 0 ≤ (deriv^[2] f x)) : convex_on univ f := convex_on_open_of_deriv2_nonneg convex_univ is_open_univ hf'.differentiable_on hf''.differentiable_on (λ x _, hf''_nonneg x) /-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonpositive on `ℝ`, then `f` is concave on `ℝ`. -/ theorem concave_on_univ_of_deriv2_nonpos {f : ℝ → ℝ} (hf' : differentiable ℝ f) (hf'' : differentiable ℝ (deriv f)) (hf''_nonpos : ∀ x, (deriv^[2] f x) ≤ 0) : concave_on univ f := concave_on_open_of_deriv2_nonpos convex_univ is_open_univ hf'.differentiable_on hf''.differentiable_on (λ x _, hf''_nonpos x) /-! ### Functions `f : E → ℝ` -/ /-- Lagrange's Mean Value Theorem, applied to convex domains. -/ theorem domain_mvt {f : E → ℝ} {s : set E} {x y : E} {f' : E → (E →L[ℝ] ℝ)} (hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hs : convex s) (xs : x ∈ s) (ys : y ∈ s) : ∃ z ∈ segment x y, f y - f x = f' z (y - x) := begin have hIccIoo := @Ioo_subset_Icc_self ℝ _ 0 1, -- parametrize segment set g : ℝ → E := λ t, x + t • (y - x), have hseg : ∀ t ∈ Icc (0:ℝ) 1, g t ∈ segment x y, { rw segment_eq_image', simp only [mem_image, and_imp, add_right_inj], intros t ht, exact ⟨t, ht, rfl⟩ }, have hseg' : Icc 0 1 ⊆ g ⁻¹' s, { rw ← image_subset_iff, unfold image, change ∀ _, _, intros z Hz, rw mem_set_of_eq at Hz, rcases Hz with ⟨t, Ht, hgt⟩, rw ← hgt, exact hs.segment_subset xs ys (hseg t Ht) }, -- derivative of pullback of f under parametrization have hfg: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g) ((f' (g t) : E → ℝ) (y-x)) (Icc (0:ℝ) 1) t, { intros t Ht, have hg : has_deriv_at g (y-x) t, { have := ((has_deriv_at_id t).smul_const (y - x)).const_add x, rwa one_smul at this }, exact (hf (g t) $ hseg' Ht).comp_has_deriv_within_at _ hg.has_deriv_within_at hseg' }, -- apply 1-variable mean value theorem to pullback have hMVT : ∃ (t ∈ Ioo (0:ℝ) 1), ((f' (g t) : E → ℝ) (y-x)) = (f (g 1) - f (g 0)) / (1 - 0), { refine exists_has_deriv_at_eq_slope (f ∘ g) _ (by norm_num) _ _, { unfold continuous_on, exact λ t Ht, (hfg t Ht).continuous_within_at }, { refine λ t Ht, (hfg t $ hIccIoo Ht).has_deriv_at _, refine _root_.mem_nhds_iff.mpr _, use (Ioo (0:ℝ) 1), refine ⟨hIccIoo, _, Ht⟩, simp [real.Ioo_eq_ball, is_open_ball] } }, -- reinterpret on domain rcases hMVT with ⟨t, Ht, hMVT'⟩, use g t, refine ⟨hseg t $ hIccIoo Ht, _⟩, simp [g, hMVT'], end section is_R_or_C /-! ### Vector-valued functions `f : E → F`. Strict differentiability. A `C^1` function is strictly differentiable, when the field is `ℝ` or `ℂ`. This follows from the mean value inequality on balls, which is a particular case of the above results after restricting the scalars to `ℝ`. Note that it does not make sense to talk of a convex set over `ℂ`, but balls make sense and are enough. Many formulations of the mean value inequality could be generalized to balls over `ℝ` or `ℂ`. For now, we only include the ones that we need. -/ variables {𝕜 : Type*} [is_R_or_C 𝕜] {G : Type*} [normed_group G] [normed_space 𝕜 G] {H : Type*} [normed_group H] [normed_space 𝕜 H] {f : G → H} {f' : G → G →L[𝕜] H} {x : G} /-- Over the reals or the complexes, a continuously differentiable function is strictly differentiable. -/ lemma has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hder : ∀ᶠ y in 𝓝 x, has_fderiv_at f (f' y) y) (hcont : continuous_at f' x) : has_strict_fderiv_at f (f' x) x := begin -- turn little-o definition of strict_fderiv into an epsilon-delta statement refine is_o_iff.mpr (λ c hc, metric.eventually_nhds_iff_ball.mpr _), -- the correct ε is the modulus of continuity of f' rcases metric.mem_nhds_iff.mp (inter_mem_sets hder (hcont $ ball_mem_nhds _ hc)) with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, _⟩, -- simplify formulas involving the product E × E rintros ⟨a, b⟩ h, rw [← ball_prod_same, prod_mk_mem_set_prod_eq] at h, -- exploit the choice of ε as the modulus of continuity of f' have hf' : ∀ x' ∈ ball x ε, ∥f' x' - f' x∥ ≤ c, { intros x' H', rw ← dist_eq_norm, exact le_of_lt (hε H').2 }, -- apply mean value theorem letI : normed_space ℝ G := restrict_scalars.normed_space ℝ 𝕜 G, letI : is_scalar_tower ℝ 𝕜 G := restrict_scalars.is_scalar_tower _ _ _, refine (convex_ball _ _).norm_image_sub_le_of_norm_has_fderiv_within_le' _ hf' h.2 h.1, exact λ y hy, (hε hy).1.has_fderiv_within_at end /-- Over the reals or the complexes, a continuously differentiable function is strictly differentiable. -/ lemma has_strict_deriv_at_of_has_deriv_at_of_continuous_at {f f' : 𝕜 → G} {x : 𝕜} (hder : ∀ᶠ y in 𝓝 x, has_deriv_at f (f' y) y) (hcont : continuous_at f' x) : has_strict_deriv_at f (f' x) x := has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hder.mono (λ y hy, hy.has_fderiv_at)) $ (smul_rightL 𝕜 _ _ 1).continuous.continuous_at.comp hcont end is_R_or_C
4856b8617bcfc9066f2dbf061e0f648e11ed2be8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/set_theory/zfc/basic.lean
78ba1fc1517e3149d4973bf524893070724baafb
[ "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
49,514
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 data.set.lattice import logic.small.basic import order.well_founded /-! # A model of ZFC > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file, we model Zermelo-Fraenkel set theory (+ Choice) using Lean's underlying type theory. We do this in four main steps: * Define pre-sets inductively. * Define extensional equivalence on pre-sets and give it a `setoid` instance. * Define ZFC sets by quotienting pre-sets by extensional equivalence. * Define classes as sets of ZFC sets. Then the rest is usual set theory. ## The model * `pSet`: Pre-set. A pre-set is inductively defined by its indexing type and its members, which are themselves pre-sets. * `Set`: ZFC set. Defined as `pSet` quotiented by `pSet.equiv`, the extensional equivalence. * `Class`: Class. Defined as `set Set`. * `Set.choice`: Axiom of choice. Proved from Lean's axiom of choice. ## Other definitions * `arity α n`: `n`-ary function `α → α → ... → α`. Defined inductively. * `arity.const a n`: `n`-ary constant function equal to `a`. * `pSet.type`: Underlying type of a pre-set. * `pSet.func`: Underlying family of pre-sets of a pre-set. * `pSet.equiv`: Extensional equivalence of pre-sets. Defined inductively. * `pSet.omega`, `Set.omega`: The von Neumann ordinal `ω` as a `pSet`, as a `Set`. * `pSet.arity.equiv`: Extensional equivalence of `n`-ary `pSet`-valued functions. Extension of `pSet.equiv`. * `pSet.resp`: Collection of `n`-ary `pSet`-valued functions that respect extensional equivalence. * `pSet.eval`: Turns a `pSet`-valued function that respect extensional equivalence into a `Set`-valued function. * `classical.all_definable`: All functions are classically definable. * `Set.is_func` : Predicate that a ZFC set is a subset of `x × y` that can be considered as a ZFC function `x → y`. That is, each member of `x` is related by the ZFC set to exactly one member of `y`. * `Set.funs`: ZFC set of ZFC functions `x → y`. * `Set.hereditarily p x`: Predicate that every set in the transitive closure of `x` has property `p`. * `Class.iota`: Definite description operator. ## Notes To avoid confusion between the Lean `set` and the ZFC `Set`, docstrings in this file refer to them respectively as "`set`" and "ZFC set". ## TODO Prove `Set.map_definable_aux` computably. -/ universes u v /-- The type of `n`-ary functions `α → α → ... → α`. -/ def arity (α : Type u) : ℕ → Type u | 0 := α | (n+1) := α → arity n @[simp] theorem arity_zero (α : Type u) : arity α 0 = α := rfl @[simp] theorem arity_succ (α : Type u) (n : ℕ) : arity α n.succ = (α → arity α n) := rfl namespace arity /-- Constant `n`-ary function with value `a`. -/ def const {α : Type u} (a : α) : ∀ n, arity α n | 0 := a | (n+1) := λ _, const n @[simp] theorem const_zero {α : Type u} (a : α) : const a 0 = a := rfl @[simp] theorem const_succ {α : Type u} (a : α) (n : ℕ) : const a n.succ = λ _, const a n := rfl theorem const_succ_apply {α : Type u} (a : α) (n : ℕ) (x : α) : const a n.succ x = const a n := rfl instance arity.inhabited {α n} [inhabited α] : inhabited (arity α n) := ⟨const default _⟩ end arity /-- The type of pre-sets in universe `u`. A pre-set is a family of pre-sets indexed by a type in `Type u`. The ZFC universe is defined as a quotient of this to ensure extensionality. -/ inductive pSet : Type (u+1) | mk (α : Type u) (A : α → pSet) : pSet namespace pSet /-- The underlying type of a pre-set -/ def type : pSet → Type u | ⟨α, A⟩ := α /-- The underlying pre-set family of a pre-set -/ def func : Π (x : pSet), x.type → pSet | ⟨α, A⟩ := A @[simp] theorem mk_type (α A) : type ⟨α, A⟩ = α := rfl @[simp] theorem mk_func (α A) : func ⟨α, A⟩ = A := rfl @[simp] theorem eta : Π (x : pSet), mk x.type x.func = x | ⟨α, A⟩ := rfl /-- Two pre-sets are extensionally equivalent if every element of the first family is extensionally equivalent to some element of the second family and vice-versa. -/ def equiv (x y : pSet) : Prop := pSet.rec (λ α z m ⟨β, B⟩, (∀ a, ∃ b, m a (B b)) ∧ (∀ b, ∃ a, m a (B b))) x y theorem equiv_iff : Π {x y : pSet}, equiv x y ↔ (∀ i, ∃ j, equiv (x.func i) (y.func j)) ∧ (∀ j, ∃ i, equiv (x.func i) (y.func j)) | ⟨α, A⟩ ⟨β, B⟩ := iff.rfl theorem equiv.exists_left {x y : pSet} (h : equiv x y) : ∀ i, ∃ j, equiv (x.func i) (y.func j) := (equiv_iff.1 h).1 theorem equiv.exists_right {x y : pSet} (h : equiv x y) : ∀ j, ∃ i, equiv (x.func i) (y.func j) := (equiv_iff.1 h).2 @[refl] protected theorem equiv.refl (x) : equiv x x := pSet.rec_on x $ λ α A IH, ⟨λ a, ⟨a, IH a⟩, λ a, ⟨a, IH a⟩⟩ protected theorem equiv.rfl : ∀ {x}, equiv x x := equiv.refl protected theorem equiv.euc {x} : Π {y z}, equiv x y → equiv z y → equiv x z := pSet.rec_on x $ λ α A IH y, pSet.cases_on y $ λ β B ⟨γ, Γ⟩ ⟨αβ, βα⟩ ⟨γβ, βγ⟩, ⟨λ a, let ⟨b, ab⟩ := αβ a, ⟨c, bc⟩ := βγ b in ⟨c, IH a ab bc⟩, λ c, let ⟨b, cb⟩ := γβ c, ⟨a, ba⟩ := βα b in ⟨a, IH a ba cb⟩⟩ @[symm] protected theorem equiv.symm {x y} : equiv x y → equiv y x := (equiv.refl y).euc protected theorem equiv.comm {x y} : equiv x y ↔ equiv y x := ⟨equiv.symm, equiv.symm⟩ @[trans] protected theorem equiv.trans {x y z} (h1 : equiv x y) (h2 : equiv y z) : equiv x z := h1.euc h2.symm protected theorem equiv_of_is_empty (x y : pSet) [is_empty x.type] [is_empty y.type] : equiv x y := equiv_iff.2 $ by simp instance setoid : setoid pSet := ⟨pSet.equiv, equiv.refl, λ x y, equiv.symm, λ x y z, equiv.trans⟩ /-- A pre-set is a subset of another pre-set if every element of the first family is extensionally equivalent to some element of the second family.-/ protected def subset (x y : pSet) : Prop := ∀ a, ∃ b, equiv (x.func a) (y.func b) instance : has_subset pSet := ⟨pSet.subset⟩ instance : is_refl pSet (⊆) := ⟨λ x a, ⟨a, equiv.refl _⟩⟩ instance : is_trans pSet (⊆) := ⟨λ x y z hxy hyz a, begin cases hxy a with b hb, cases hyz b with c hc, exact ⟨c, hb.trans hc⟩ end⟩ theorem equiv.ext : Π (x y : pSet), equiv x y ↔ (x ⊆ y ∧ y ⊆ x) | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ ⟨αβ, βα⟩, ⟨αβ, λ b, let ⟨a, h⟩ := βα b in ⟨a, equiv.symm h⟩⟩, λ ⟨αβ, βα⟩, ⟨αβ, λ b, let ⟨a, h⟩ := βα b in ⟨a, equiv.symm h⟩⟩⟩ theorem subset.congr_left : Π {x y z : pSet}, equiv x y → (x ⊆ z ↔ y ⊆ z) | ⟨α, A⟩ ⟨β, B⟩ ⟨γ, Γ⟩ ⟨αβ, βα⟩ := ⟨λ αγ b, let ⟨a, ba⟩ := βα b, ⟨c, ac⟩ := αγ a in ⟨c, (equiv.symm ba).trans ac⟩, λ βγ a, let ⟨b, ab⟩ := αβ a, ⟨c, bc⟩ := βγ b in ⟨c, equiv.trans ab bc⟩⟩ theorem subset.congr_right : Π {x y z : pSet}, equiv x y → (z ⊆ x ↔ z ⊆ y) | ⟨α, A⟩ ⟨β, B⟩ ⟨γ, Γ⟩ ⟨αβ, βα⟩ := ⟨λ γα c, let ⟨a, ca⟩ := γα c, ⟨b, ab⟩ := αβ a in ⟨b, ca.trans ab⟩, λ γβ c, let ⟨b, cb⟩ := γβ c, ⟨a, ab⟩ := βα b in ⟨a, cb.trans (equiv.symm ab)⟩⟩ /-- `x ∈ y` as pre-sets if `x` is extensionally equivalent to a member of the family `y`. -/ protected def mem (x y : pSet.{u}) : Prop := ∃ b, equiv x (y.func b) instance : has_mem pSet pSet := ⟨pSet.mem⟩ theorem mem.mk {α : Type u} (A : α → pSet) (a : α) : A a ∈ mk α A := ⟨a, equiv.refl (A a)⟩ theorem func_mem (x : pSet) (i : x.type) : x.func i ∈ x := by { cases x, apply mem.mk } theorem mem.ext : Π {x y : pSet.{u}}, (∀ w : pSet.{u}, w ∈ x ↔ w ∈ y) → equiv x y | ⟨α, A⟩ ⟨β, B⟩ h := ⟨λ a, (h (A a)).1 (mem.mk A a), λ b, let ⟨a, ha⟩ := (h (B b)).2 (mem.mk B b) in ⟨a, ha.symm⟩⟩ theorem mem.congr_right : Π {x y : pSet.{u}}, equiv x y → (∀ {w : pSet.{u}}, w ∈ x ↔ w ∈ y) | ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩ w := ⟨λ ⟨a, ha⟩, let ⟨b, hb⟩ := αβ a in ⟨b, ha.trans hb⟩, λ ⟨b, hb⟩, let ⟨a, ha⟩ := βα b in ⟨a, hb.euc ha⟩⟩ theorem equiv_iff_mem {x y : pSet.{u}} : equiv x y ↔ (∀ {w : pSet.{u}}, w ∈ x ↔ w ∈ y) := ⟨mem.congr_right, match x, y with | ⟨α, A⟩, ⟨β, B⟩, h := ⟨λ a, h.1 (mem.mk A a), λ b, let ⟨a, h⟩ := h.2 (mem.mk B b) in ⟨a, h.symm⟩⟩ end⟩ theorem mem.congr_left : Π {x y : pSet.{u}}, equiv x y → (∀ {w : pSet.{u}}, x ∈ w ↔ y ∈ w) | x y h ⟨α, A⟩ := ⟨λ ⟨a, ha⟩, ⟨a, h.symm.trans ha⟩, λ ⟨a, ha⟩, ⟨a, h.trans ha⟩⟩ private theorem mem_wf_aux : Π {x y : pSet.{u}}, equiv x y → acc (∈) y | ⟨α, A⟩ ⟨β, B⟩ H := ⟨_, begin rintros ⟨γ, C⟩ ⟨b, hc⟩, cases H.exists_right b with a ha, have H := ha.trans hc.symm, rw mk_func at H, exact mem_wf_aux H end⟩ theorem mem_wf : @well_founded pSet (∈) := ⟨λ x, mem_wf_aux $ equiv.refl x⟩ instance : has_well_founded pSet := ⟨_, mem_wf⟩ instance : is_asymm pSet (∈) := mem_wf.is_asymm theorem mem_asymm {x y : pSet} : x ∈ y → y ∉ x := asymm theorem mem_irrefl (x : pSet) : x ∉ x := irrefl x /-- Convert a pre-set to a `set` of pre-sets. -/ def to_set (u : pSet.{u}) : set pSet.{u} := {x | x ∈ u} @[simp] theorem mem_to_set (a u : pSet.{u}) : a ∈ u.to_set ↔ a ∈ u := iff.rfl /-- A nonempty set is one that contains some element. -/ protected def nonempty (u : pSet) : Prop := u.to_set.nonempty theorem nonempty_def (u : pSet) : u.nonempty ↔ ∃ x, x ∈ u := iff.rfl theorem nonempty_of_mem {x u : pSet} (h : x ∈ u) : u.nonempty := ⟨x, h⟩ @[simp] theorem nonempty_to_set_iff {u : pSet} : u.to_set.nonempty ↔ u.nonempty := iff.rfl theorem nonempty_type_iff_nonempty {x : pSet} : nonempty x.type ↔ pSet.nonempty x := ⟨λ ⟨i⟩, ⟨_, func_mem _ i⟩, λ ⟨i, j, h⟩, ⟨j⟩⟩ theorem nonempty_of_nonempty_type (x : pSet) [h : nonempty x.type] : pSet.nonempty x := nonempty_type_iff_nonempty.1 h /-- Two pre-sets are equivalent iff they have the same members. -/ theorem equiv.eq {x y : pSet} : equiv x y ↔ to_set x = to_set y := equiv_iff_mem.trans set.ext_iff.symm instance : has_coe pSet (set pSet) := ⟨to_set⟩ /-- The empty pre-set -/ protected def empty : pSet := ⟨_, pempty.elim⟩ instance : has_emptyc pSet := ⟨pSet.empty⟩ instance : inhabited pSet := ⟨∅⟩ instance : is_empty (type (∅)) := pempty.is_empty @[simp] theorem not_mem_empty (x : pSet.{u}) : x ∉ (∅ : pSet.{u}) := is_empty.exists_iff.1 @[simp] theorem to_set_empty : to_set ∅ = ∅ := by simp [to_set] @[simp] theorem empty_subset (x : pSet.{u}) : (∅ : pSet) ⊆ x := λ x, x.elim @[simp] theorem not_nonempty_empty : ¬ pSet.nonempty ∅ := by simp [pSet.nonempty] protected theorem equiv_empty (x : pSet) [is_empty x.type] : equiv x ∅ := pSet.equiv_of_is_empty x _ /-- Insert an element into a pre-set -/ protected def insert (x y : pSet) : pSet := ⟨option y.type, λ o, option.rec x y.func o⟩ instance : has_insert pSet pSet := ⟨pSet.insert⟩ instance : has_singleton pSet pSet := ⟨λ s, insert s ∅⟩ instance : is_lawful_singleton pSet pSet := ⟨λ _, rfl⟩ instance (x y : pSet) : inhabited (insert x y).type := option.inhabited _ /-- The n-th von Neumann ordinal -/ def of_nat : ℕ → pSet | 0 := ∅ | (n+1) := insert (of_nat n) (of_nat n) /-- The von Neumann ordinal ω -/ def omega : pSet := ⟨ulift ℕ, λ n, of_nat n.down⟩ /-- The pre-set separation operation `{x ∈ a | p x}` -/ protected def sep (p : pSet → Prop) (x : pSet) : pSet := ⟨{a // p (x.func a)}, λ y, x.func y.1⟩ instance : has_sep pSet pSet := ⟨pSet.sep⟩ /-- The pre-set powerset operator -/ def powerset (x : pSet) : pSet := ⟨set x.type, λ p, ⟨{a // p a}, λ y, x.func y.1⟩⟩ @[simp] theorem mem_powerset : Π {x y : pSet}, y ∈ powerset x ↔ y ⊆ x | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ ⟨p, e⟩, (subset.congr_left e).2 $ λ ⟨a, pa⟩, ⟨a, equiv.refl (A a)⟩, λ βα, ⟨{a | ∃ b, equiv (B b) (A a)}, λ b, let ⟨a, ba⟩ := βα b in ⟨⟨a, b, ba⟩, ba⟩, λ ⟨a, b, ba⟩, ⟨b, ba⟩⟩⟩ /-- The pre-set union operator -/ def sUnion (a : pSet) : pSet := ⟨Σ x, (a.func x).type, λ ⟨x, y⟩, (a.func x).func y⟩ prefix (name := pSet.sUnion) `⋃₀ `:110 := pSet.sUnion @[simp] theorem mem_sUnion : Π {x y : pSet.{u}}, y ∈ ⋃₀ x ↔ ∃ z ∈ x, y ∈ z | ⟨α, A⟩ y := ⟨λ ⟨⟨a, c⟩, (e : equiv y ((A a).func c))⟩, have func (A a) c ∈ mk (A a).type (A a).func, from mem.mk (A a).func c, ⟨_, mem.mk _ _, (mem.congr_left e).2 (by rwa eta at this)⟩, λ ⟨⟨β, B⟩, ⟨a, (e : equiv (mk β B) (A a))⟩, ⟨b, yb⟩⟩, by { rw ←(eta (A a)) at e, exact let ⟨βt, tβ⟩ := e, ⟨c, bc⟩ := βt b in ⟨⟨a, c⟩, yb.trans bc⟩ }⟩ @[simp] theorem to_set_sUnion (x : pSet.{u}) : (⋃₀ x).to_set = ⋃₀ (to_set '' x.to_set) := by { ext, simp } /-- The image of a function from pre-sets to pre-sets. -/ def image (f : pSet.{u} → pSet.{u}) (x : pSet.{u}) : pSet := ⟨x.type, f ∘ x.func⟩ theorem mem_image {f : pSet.{u} → pSet.{u}} (H : ∀ {x y}, equiv x y → equiv (f x) (f y)) : Π {x y : pSet.{u}}, y ∈ image f x ↔ ∃ z ∈ x, equiv y (f z) | ⟨α, A⟩ y := ⟨λ ⟨a, ya⟩, ⟨A a, mem.mk A a, ya⟩, λ ⟨z, ⟨a, za⟩, yz⟩, ⟨a, yz.trans (H za)⟩⟩ /-- Universe lift operation -/ protected def lift : pSet.{u} → pSet.{max u v} | ⟨α, A⟩ := ⟨ulift α, λ ⟨x⟩, lift (A x)⟩ /-- Embedding of one universe in another -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def embed : pSet.{max (u+1) v} := ⟨ulift.{v u+1} pSet, λ ⟨x⟩, pSet.lift.{u (max (u+1) v)} x⟩ theorem lift_mem_embed : Π (x : pSet.{u}), pSet.lift.{u (max (u+1) v)} x ∈ embed.{u v} := λ x, ⟨⟨x⟩, equiv.rfl⟩ /-- Function equivalence is defined so that `f ~ g` iff `∀ x y, x ~ y → f x ~ g y`. This extends to equivalence of `n`-ary functions. -/ def arity.equiv : Π {n}, arity pSet.{u} n → arity pSet.{u} n → Prop | 0 a b := equiv a b | (n+1) a b := ∀ x y, equiv x y → arity.equiv (a x) (b y) lemma arity.equiv_const {a : pSet.{u}} : ∀ n, arity.equiv (arity.const a n) (arity.const a n) | 0 := equiv.rfl | (n+1) := λ x y h, arity.equiv_const _ /-- `resp n` is the collection of n-ary functions on `pSet` that respect equivalence, i.e. when the inputs are equivalent the output is as well. -/ def resp (n) := {x : arity pSet.{u} n // arity.equiv x x} instance resp.inhabited {n} : inhabited (resp n) := ⟨⟨arity.const default _, arity.equiv_const _⟩⟩ /-- The `n`-ary image of a `(n + 1)`-ary function respecting equivalence as a function respecting equivalence. -/ def resp.f {n} (f : resp (n+1)) (x : pSet) : resp n := ⟨f.1 x, f.2 _ _ $ equiv.refl x⟩ /-- Function equivalence for functions respecting equivalence. See `pSet.arity.equiv`. -/ def resp.equiv {n} (a b : resp n) : Prop := arity.equiv a.1 b.1 protected theorem resp.equiv.refl {n} (a : resp n) : resp.equiv a a := a.2 protected theorem resp.equiv.euc : Π {n} {a b c : resp n}, resp.equiv a b → resp.equiv c b → resp.equiv a c | 0 a b c hab hcb := equiv.euc hab hcb | (n+1) a b c hab hcb := λ x y h, @resp.equiv.euc n (a.f x) (b.f y) (c.f y) (hab _ _ h) (hcb _ _ $ equiv.refl y) protected theorem resp.equiv.symm {n} {a b : resp n} : resp.equiv a b → resp.equiv b a := (resp.equiv.refl b).euc protected theorem resp.equiv.trans {n} {x y z : resp n} (h1 : resp.equiv x y) (h2 : resp.equiv y z) : resp.equiv x z := h1.euc h2.symm instance resp.setoid {n} : setoid (resp n) := ⟨resp.equiv, resp.equiv.refl, λ x y, resp.equiv.symm, λ x y z, resp.equiv.trans⟩ end pSet /-- The ZFC universe of sets consists of the type of pre-sets, quotiented by extensional equivalence. -/ def Set : Type (u+1) := quotient pSet.setoid.{u} namespace pSet namespace resp /-- Helper function for `pSet.eval`. -/ def eval_aux : Π {n}, {f : resp n → arity Set.{u} n // ∀ (a b : resp n), resp.equiv a b → f a = f b} | 0 := ⟨λ a, ⟦a.1⟧, λ a b h, quotient.sound h⟩ | (n+1) := let F : resp (n + 1) → arity Set (n + 1) := λ a, @quotient.lift _ _ pSet.setoid (λ x, eval_aux.1 (a.f x)) (λ b c h, eval_aux.2 _ _ (a.2 _ _ h)) in ⟨F, λ b c h, funext $ @quotient.ind _ _ (λ q, F b q = F c q) $ λ z, eval_aux.2 (resp.f b z) (resp.f c z) (h _ _ (pSet.equiv.refl z))⟩ /-- An equivalence-respecting function yields an n-ary ZFC set function. -/ def eval (n) : resp n → arity Set.{u} n := eval_aux.1 theorem eval_val {n f x} : (@eval (n+1) f : Set → arity Set n) ⟦x⟧ = eval n (resp.f f x) := rfl end resp /-- A set function is "definable" if it is the image of some n-ary pre-set function. This isn't exactly definability, but is useful as a sufficient condition for functions that have a computable image. -/ class inductive definable (n) : arity Set.{u} n → Type (u+1) | mk (f) : definable (resp.eval n f) attribute [instance] definable.mk /-- The evaluation of a function respecting equivalence is definable, by that same function. -/ def definable.eq_mk {n} (f) : Π {s : arity Set.{u} n} (H : resp.eval _ f = s), definable n s | ._ rfl := ⟨f⟩ /-- Turns a definable function into a function that respects equivalence. -/ def definable.resp {n} : Π (s : arity Set.{u} n) [definable n s], resp n | ._ ⟨f⟩ := f theorem definable.eq {n} : Π (s : arity Set.{u} n) [H : definable n s], (@definable.resp n s H).eval _ = s | ._ ⟨f⟩ := rfl end pSet namespace classical open pSet /-- All functions are classically definable. -/ noncomputable def all_definable : Π {n} (F : arity Set.{u} n), definable n F | 0 F := let p := @quotient.exists_rep pSet _ F in definable.eq_mk ⟨some p, equiv.rfl⟩ (some_spec p) | (n+1) (F : arity Set.{u} (n + 1)) := begin have I := λ x, (all_definable (F x)), refine definable.eq_mk ⟨λ x : pSet, (@definable.resp _ _ (I ⟦x⟧)).1, _⟩ _, { dsimp [arity.equiv], introsI x y h, rw @quotient.sound pSet _ _ _ h, exact (definable.resp (F ⟦y⟧)).2 }, refine funext (λ q, quotient.induction_on q $ λ x, _), simp_rw [resp.eval_val, resp.f, subtype.val_eq_coe, subtype.coe_eta], exact @definable.eq _ (F ⟦x⟧) (I ⟦x⟧), end end classical namespace Set open pSet /-- Turns a pre-set into a ZFC set. -/ def mk : pSet → Set := quotient.mk @[simp] theorem mk_eq (x : pSet) : @eq Set ⟦x⟧ (mk x) := rfl @[simp] theorem mk_out : ∀ x : Set, mk x.out = x := quotient.out_eq theorem eq {x y : pSet} : mk x = mk y ↔ equiv x y := quotient.eq theorem sound {x y : pSet} (h : pSet.equiv x y) : mk x = mk y := quotient.sound h theorem exact {x y : pSet} : mk x = mk y → pSet.equiv x y := quotient.exact @[simp] lemma eval_mk {n f x} : (@resp.eval (n+1) f : Set → arity Set n) (mk x) = resp.eval n (resp.f f x) := rfl /-- The membership relation for ZFC sets is inherited from the membership relation for pre-sets. -/ protected def mem : Set → Set → Prop := quotient.lift₂ pSet.mem (λ x y x' y' hx hy, propext ((mem.congr_left hx).trans (mem.congr_right hy))) instance : has_mem Set Set := ⟨Set.mem⟩ @[simp] theorem mk_mem_iff {x y : pSet} : mk x ∈ mk y ↔ x ∈ y := iff.rfl /-- Convert a ZFC set into a `set` of ZFC sets -/ def to_set (u : Set.{u}) : set Set.{u} := {x | x ∈ u} @[simp] theorem mem_to_set (a u : Set.{u}) : a ∈ u.to_set ↔ a ∈ u := iff.rfl instance small_to_set (x : Set.{u}) : small.{u} x.to_set := quotient.induction_on x $ λ a, begin let f : a.type → (mk a).to_set := λ i, ⟨mk $ a.func i, func_mem a i⟩, suffices : function.surjective f, { exact small_of_surjective this }, rintro ⟨y, hb⟩, induction y using quotient.induction_on, cases hb with i h, exact ⟨i, subtype.coe_injective (quotient.sound h.symm)⟩ end /-- A nonempty set is one that contains some element. -/ protected def nonempty (u : Set) : Prop := u.to_set.nonempty theorem nonempty_def (u : Set) : u.nonempty ↔ ∃ x, x ∈ u := iff.rfl theorem nonempty_of_mem {x u : Set} (h : x ∈ u) : u.nonempty := ⟨x, h⟩ @[simp] theorem nonempty_to_set_iff {u : Set} : u.to_set.nonempty ↔ u.nonempty := iff.rfl /-- `x ⊆ y` as ZFC sets means that all members of `x` are members of `y`. -/ protected def subset (x y : Set.{u}) := ∀ ⦃z⦄, z ∈ x → z ∈ y instance has_subset : has_subset Set := ⟨Set.subset⟩ lemma subset_def {x y : Set.{u}} : x ⊆ y ↔ ∀ ⦃z⦄, z ∈ x → z ∈ y := iff.rfl instance : is_refl Set (⊆) := ⟨λ x a, id⟩ instance : is_trans Set (⊆) := ⟨λ x y z hxy hyz a ha, hyz (hxy ha)⟩ @[simp] theorem subset_iff : Π {x y : pSet}, mk x ⊆ mk y ↔ x ⊆ y | ⟨α, A⟩ ⟨β, B⟩ := ⟨λ h a, @h ⟦A a⟧ (mem.mk A a), λ h z, quotient.induction_on z (λ z ⟨a, za⟩, let ⟨b, ab⟩ := h a in ⟨b, za.trans ab⟩)⟩ @[simp] theorem to_set_subset_iff {x y : Set} : x.to_set ⊆ y.to_set ↔ x ⊆ y := by simp [subset_def, set.subset_def] @[ext] theorem ext {x y : Set.{u}} : (∀ z : Set.{u}, z ∈ x ↔ z ∈ y) → x = y := quotient.induction_on₂ x y (λ u v h, quotient.sound (mem.ext (λ w, h ⟦w⟧))) theorem ext_iff {x y : Set.{u}} : x = y ↔ (∀ z : Set.{u}, z ∈ x ↔ z ∈ y) := ⟨λ h, by simp [h], ext⟩ theorem to_set_injective : function.injective to_set := λ x y h, ext $ set.ext_iff.1 h @[simp] theorem to_set_inj {x y : Set} : x.to_set = y.to_set ↔ x = y := to_set_injective.eq_iff instance : is_antisymm Set (⊆) := ⟨λ a b hab hba, ext $ λ c, ⟨@hab c, @hba c⟩⟩ /-- The empty ZFC set -/ protected def empty : Set := mk ∅ instance : has_emptyc Set := ⟨Set.empty⟩ instance : inhabited Set := ⟨∅⟩ @[simp] theorem not_mem_empty (x) : x ∉ (∅ : Set.{u}) := quotient.induction_on x pSet.not_mem_empty @[simp] theorem to_set_empty : to_set ∅ = ∅ := by simp [to_set] @[simp] theorem empty_subset (x : Set.{u}) : (∅ : Set) ⊆ x := quotient.induction_on x $ λ y, subset_iff.2 $ pSet.empty_subset y @[simp] theorem not_nonempty_empty : ¬ Set.nonempty ∅ := by simp [Set.nonempty] @[simp] theorem nonempty_mk_iff {x : pSet} : (mk x).nonempty ↔ x.nonempty := begin refine ⟨_, λ ⟨a, h⟩, ⟨mk a, h⟩⟩, rintro ⟨a, h⟩, induction a using quotient.induction_on, exact ⟨a, h⟩ end theorem eq_empty (x : Set.{u}) : x = ∅ ↔ ∀ y : Set.{u}, y ∉ x := by { rw ext_iff, simp } theorem eq_empty_or_nonempty (u : Set) : u = ∅ ∨ u.nonempty := by { rw [eq_empty, ←not_exists], apply em' } /-- `insert x y` is the set `{x} ∪ y` -/ protected def insert : Set → Set → Set := resp.eval 2 ⟨pSet.insert, λ u v uv ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λ o, match o with | some a := let ⟨b, hb⟩ := αβ a in ⟨some b, hb⟩ | none := ⟨none, uv⟩ end, λ o, match o with | some b := let ⟨a, ha⟩ := βα b in ⟨some a, ha⟩ | none := ⟨none, uv⟩ end⟩⟩ instance : has_insert Set Set := ⟨Set.insert⟩ instance : has_singleton Set Set := ⟨λ x, insert x ∅⟩ instance : is_lawful_singleton Set Set := ⟨λ x, rfl⟩ @[simp] theorem mem_insert_iff {x y z : Set.{u}} : x ∈ insert y z ↔ x = y ∨ x ∈ z := quotient.induction_on₃ x y z (λ x y ⟨α, A⟩, show x ∈ pSet.mk (option α) (λ o, option.rec y A o) ↔ mk x = mk y ∨ x ∈ pSet.mk α A, from ⟨λ m, match m with | ⟨some a, ha⟩ := or.inr ⟨a, ha⟩ | ⟨none, h⟩ := or.inl (quotient.sound h) end, λ m, match m with | or.inr ⟨a, ha⟩ := ⟨some a, ha⟩ | or.inl h := ⟨none, quotient.exact h⟩ end⟩) theorem mem_insert (x y : Set) : x ∈ insert x y := mem_insert_iff.2 $ or.inl rfl theorem mem_insert_of_mem {y z : Set} (x) (h : z ∈ y): z ∈ insert x y := mem_insert_iff.2 $ or.inr h @[simp] theorem to_set_insert (x y : Set) : (insert x y).to_set = insert x y.to_set := by { ext, simp } @[simp] theorem mem_singleton {x y : Set.{u}} : x ∈ @singleton Set.{u} Set.{u} _ y ↔ x = y := iff.trans mem_insert_iff ⟨λ o, or.rec (λ h, h) (λ n, absurd n (not_mem_empty _)) o, or.inl⟩ @[simp] theorem to_set_singleton (x : Set) : ({x} : Set).to_set = {x} := by { ext, simp } theorem insert_nonempty (u v : Set) : (insert u v).nonempty := ⟨u, mem_insert u v⟩ theorem singleton_nonempty (u : Set) : Set.nonempty {u} := insert_nonempty u ∅ @[simp] theorem mem_pair {x y z : Set.{u}} : x ∈ ({y, z} : Set) ↔ x = y ∨ x = z := iff.trans mem_insert_iff $ or_congr iff.rfl mem_singleton /-- `omega` is the first infinite von Neumann ordinal -/ def omega : Set := mk omega @[simp] theorem omega_zero : ∅ ∈ omega := ⟨⟨0⟩, equiv.rfl⟩ @[simp] theorem omega_succ {n} : n ∈ omega.{u} → insert n n ∈ omega.{u} := quotient.induction_on n (λ x ⟨⟨n⟩, h⟩, ⟨⟨n+1⟩, Set.exact $ show insert (mk x) (mk x) = insert (mk $ of_nat n) (mk $ of_nat n), { rw Set.sound h, refl } ⟩) /-- `{x ∈ a | p x}` is the set of elements in `a` satisfying `p` -/ protected def sep (p : Set → Prop) : Set → Set := resp.eval 1 ⟨pSet.sep (λ y, p (mk y)), λ ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λ ⟨a, pa⟩, let ⟨b, hb⟩ := αβ a in ⟨⟨b, by rwa [mk_func, ←Set.sound hb]⟩, hb⟩, λ ⟨b, pb⟩, let ⟨a, ha⟩ := βα b in ⟨⟨a, by rwa [mk_func, Set.sound ha]⟩, ha⟩⟩⟩ instance : has_sep Set Set := ⟨Set.sep⟩ @[simp] theorem mem_sep {p : Set.{u} → Prop} {x y : Set.{u}} : y ∈ {y ∈ x | p y} ↔ y ∈ x ∧ p y := quotient.induction_on₂ x y (λ ⟨α, A⟩ y, ⟨λ ⟨⟨a, pa⟩, h⟩, ⟨⟨a, h⟩, by rwa (@quotient.sound pSet _ _ _ h)⟩, λ ⟨⟨a, h⟩, pa⟩, ⟨⟨a, by { rw mk_func at h, rwa [mk_func, ←Set.sound h] }⟩, h⟩⟩) @[simp] theorem to_set_sep (a : Set) (p : Set → Prop) : {x ∈ a | p x}.to_set = {x ∈ a.to_set | p x} := by { ext, simp } /-- The powerset operation, the collection of subsets of a ZFC set -/ def powerset : Set → Set := resp.eval 1 ⟨powerset, λ ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨λ p, ⟨{b | ∃ a, p a ∧ equiv (A a) (B b)}, λ ⟨a, pa⟩, let ⟨b, ab⟩ := αβ a in ⟨⟨b, a, pa, ab⟩, ab⟩, λ ⟨b, a, pa, ab⟩, ⟨⟨a, pa⟩, ab⟩⟩, λ q, ⟨{a | ∃ b, q b ∧ equiv (A a) (B b)}, λ ⟨a, b, qb, ab⟩, ⟨⟨b, qb⟩, ab⟩, λ ⟨b, qb⟩, let ⟨a, ab⟩ := βα b in ⟨⟨a, b, qb, ab⟩, ab⟩⟩⟩⟩ @[simp] theorem mem_powerset {x y : Set.{u}} : y ∈ powerset x ↔ y ⊆ x := quotient.induction_on₂ x y ( λ ⟨α, A⟩ ⟨β, B⟩, show (⟨β, B⟩ : pSet.{u}) ∈ (pSet.powerset.{u} ⟨α, A⟩) ↔ _, by simp [mem_powerset, subset_iff]) theorem sUnion_lem {α β : Type u} (A : α → pSet) (B : β → pSet) (αβ : ∀ a, ∃ b, equiv (A a) (B b)) : ∀ a, ∃ b, (equiv ((sUnion ⟨α, A⟩).func a) ((sUnion ⟨β, B⟩).func b)) | ⟨a, c⟩ := let ⟨b, hb⟩ := αβ a in begin induction ea : A a with γ Γ, induction eb : B b with δ Δ, rw [ea, eb] at hb, cases hb with γδ δγ, exact let c : type (A a) := c, ⟨d, hd⟩ := γδ (by rwa ea at c) in have pSet.equiv ((A a).func c) ((B b).func (eq.rec d (eq.symm eb))), from match A a, B b, ea, eb, c, d, hd with ._, ._, rfl, rfl, x, y, hd := hd end, ⟨⟨b, by { rw mk_func, exact eq.rec d (eq.symm eb) }⟩, this⟩ end /-- The union operator, the collection of elements of elements of a ZFC set -/ def sUnion : Set → Set := resp.eval 1 ⟨pSet.sUnion, λ ⟨α, A⟩ ⟨β, B⟩ ⟨αβ, βα⟩, ⟨sUnion_lem A B αβ, λ a, exists.elim (sUnion_lem B A (λ b, exists.elim (βα b) (λ c hc, ⟨c, pSet.equiv.symm hc⟩)) a) (λ b hb, ⟨b, pSet.equiv.symm hb⟩)⟩⟩ prefix (name := Set.sUnion) `⋃₀ `:110 := Set.sUnion /-- The intersection operator, the collection of elements in all of the elements of a ZFC set. We special-case `⋂₀ ∅ = ∅`. -/ noncomputable def sInter (x : Set) : Set := by { classical, exact dite x.nonempty (λ h, {y ∈ h.some | ∀ z ∈ x, y ∈ z}) (λ _, ∅) } prefix (name := Set.sInter) `⋂₀ `:110 := Set.sInter @[simp] theorem mem_sUnion {x y : Set.{u}} : y ∈ ⋃₀ x ↔ ∃ z ∈ x, y ∈ z := quotient.induction_on₂ x y (λ x y, iff.trans mem_sUnion ⟨λ ⟨z, h⟩, ⟨⟦z⟧, h⟩, λ ⟨z, h⟩, quotient.induction_on z (λ z h, ⟨z, h⟩) h⟩) theorem mem_sInter {x y : Set} (h : x.nonempty) : y ∈ ⋂₀ x ↔ ∀ z ∈ x, y ∈ z := begin rw [sInter, dif_pos h], simp only [mem_to_set, mem_sep, and_iff_right_iff_imp], exact λ H, H _ h.some_mem end @[simp] theorem sUnion_empty : ⋃₀ (∅ : Set) = ∅ := by { ext, simp } @[simp] theorem sInter_empty : ⋂₀ (∅ : Set) = ∅ := dif_neg $ by simp theorem mem_of_mem_sInter {x y z : Set} (hy : y ∈ ⋂₀ x) (hz : z ∈ x) : y ∈ z := begin rcases eq_empty_or_nonempty x with rfl | hx, { exact (not_mem_empty z hz).elim }, { exact (mem_sInter hx).1 hy z hz } end theorem mem_sUnion_of_mem {x y z : Set} (hy : y ∈ z) (hz : z ∈ x) : y ∈ ⋃₀ x := mem_sUnion.2 ⟨z, hz, hy⟩ theorem not_mem_sInter_of_not_mem {x y z : Set} (hy : ¬ y ∈ z) (hz : z ∈ x) : ¬ y ∈ ⋂₀ x := λ hx, hy $ mem_of_mem_sInter hx hz @[simp] theorem sUnion_singleton {x : Set.{u}} : ⋃₀ ({x} : Set) = x := ext $ λ y, by simp_rw [mem_sUnion, exists_prop, mem_singleton, exists_eq_left] @[simp] theorem sInter_singleton {x : Set.{u}} : ⋂₀ ({x} : Set) = x := ext $ λ y, by simp_rw [mem_sInter (singleton_nonempty x), mem_singleton, forall_eq] @[simp] theorem to_set_sUnion (x : Set.{u}) : (⋃₀ x).to_set = ⋃₀ (to_set '' x.to_set) := by { ext, simp } theorem to_set_sInter {x : Set.{u}} (h : x.nonempty) : (⋂₀ x).to_set = ⋂₀ (to_set '' x.to_set) := by { ext, simp [mem_sInter h] } theorem singleton_injective : function.injective (@singleton Set Set _) := λ x y H, let this := congr_arg sUnion H in by rwa [sUnion_singleton, sUnion_singleton] at this @[simp] theorem singleton_inj {x y : Set} : ({x} : Set) = {y} ↔ x = y := singleton_injective.eq_iff /-- The binary union operation -/ protected def union (x y : Set.{u}) : Set.{u} := ⋃₀ {x, y} /-- The binary intersection operation -/ protected def inter (x y : Set.{u}) : Set.{u} := {z ∈ x | z ∈ y} /-- The set difference operation -/ protected def diff (x y : Set.{u}) : Set.{u} := {z ∈ x | z ∉ y} instance : has_union Set := ⟨Set.union⟩ instance : has_inter Set := ⟨Set.inter⟩ instance : has_sdiff Set := ⟨Set.diff⟩ @[simp] theorem to_set_union (x y : Set.{u}) : (x ∪ y).to_set = x.to_set ∪ y.to_set := by { unfold has_union.union, rw Set.union, simp } @[simp] theorem to_set_inter (x y : Set.{u}) : (x ∩ y).to_set = x.to_set ∩ y.to_set := by { unfold has_inter.inter, rw Set.inter, ext, simp } @[simp] theorem to_set_sdiff (x y : Set.{u}) : (x \ y).to_set = x.to_set \ y.to_set := by { change {z ∈ x | z ∉ y}.to_set = _, ext, simp } @[simp] theorem mem_union {x y z : Set.{u}} : z ∈ x ∪ y ↔ z ∈ x ∨ z ∈ y := by { rw ←mem_to_set, simp } @[simp] theorem mem_inter {x y z : Set.{u}} : z ∈ x ∩ y ↔ z ∈ x ∧ z ∈ y := @@mem_sep (λ z : Set.{u}, z ∈ y) @[simp] theorem mem_diff {x y z : Set.{u}} : z ∈ x \ y ↔ z ∈ x ∧ z ∉ y := @@mem_sep (λ z : Set.{u}, z ∉ y) @[simp] theorem sUnion_pair {x y : Set.{u}} : ⋃₀ ({x, y} : Set.{u}) = x ∪ y := begin ext, simp_rw [mem_union, mem_sUnion, mem_pair], split, { rintro ⟨w, (rfl | rfl), hw⟩, { exact or.inl hw }, { exact or.inr hw } }, { rintro (hz | hz), { exact ⟨x, or.inl rfl, hz⟩ }, { exact ⟨y, or.inr rfl, hz⟩ } } end theorem mem_wf : @well_founded Set (∈) := well_founded_lift₂_iff.mpr pSet.mem_wf /-- Induction on the `∈` relation. -/ @[elab_as_eliminator] theorem induction_on {p : Set → Prop} (x) (h : ∀ x, (∀ y ∈ x, p y) → p x) : p x := mem_wf.induction x h instance : has_well_founded Set := ⟨_, mem_wf⟩ instance : is_asymm Set (∈) := mem_wf.is_asymm theorem mem_asymm {x y : Set} : x ∈ y → y ∉ x := asymm theorem mem_irrefl (x : Set) : x ∉ x := irrefl x theorem regularity (x : Set.{u}) (h : x ≠ ∅) : ∃ y ∈ x, x ∩ y = ∅ := classical.by_contradiction $ λ ne, h $ (eq_empty x).2 $ λ y, induction_on y $ λ z (IH : ∀ w : Set.{u}, w ∈ z → w ∉ x), show z ∉ x, from λ zx, ne ⟨z, zx, (eq_empty _).2 (λ w wxz, let ⟨wx, wz⟩ := mem_inter.1 wxz in IH w wz wx)⟩ /-- The image of a (definable) ZFC set function -/ def image (f : Set → Set) [H : definable 1 f] : Set → Set := let r := @definable.resp 1 f _ in resp.eval 1 ⟨image r.1, λ x y e, mem.ext $ λ z, iff.trans (mem_image r.2) $ iff.trans (by exact ⟨λ ⟨w, h1, h2⟩, ⟨w, (mem.congr_right e).1 h1, h2⟩, λ ⟨w, h1, h2⟩, ⟨w, (mem.congr_right e).2 h1, h2⟩⟩) $ iff.symm (mem_image r.2)⟩ theorem image.mk : Π (f : Set.{u} → Set.{u}) [H : definable 1 f] (x) {y} (h : y ∈ x), f y ∈ @image f H x | ._ ⟨F⟩ x y := quotient.induction_on₂ x y $ λ ⟨α, A⟩ y ⟨a, ya⟩, ⟨a, F.2 _ _ ya⟩ @[simp] theorem mem_image : Π {f : Set.{u} → Set.{u}} [H : definable 1 f] {x y : Set.{u}}, y ∈ @image f H x ↔ ∃ z ∈ x, f z = y | ._ ⟨F⟩ x y := quotient.induction_on₂ x y $ λ ⟨α, A⟩ y, ⟨λ ⟨a, ya⟩, ⟨⟦A a⟧, mem.mk A a, eq.symm $ quotient.sound ya⟩, λ ⟨z, hz, e⟩, e ▸ image.mk _ _ hz⟩ @[simp] theorem to_set_image (f : Set → Set) [H : definable 1 f] (x : Set) : (image f x).to_set = f '' x.to_set := by { ext, simp } /-- The range of an indexed family of sets. The universes allow for a more general index type without manual use of `ulift`. -/ noncomputable def range {α : Type u} (f : α → Set.{max u v}) : Set.{max u v} := ⟦⟨ulift α, quotient.out ∘ f ∘ ulift.down⟩⟧ @[simp] theorem mem_range {α : Type u} {f : α → Set.{max u v}} {x : Set.{max u v}} : x ∈ range f ↔ x ∈ set.range f := quotient.induction_on x (λ y, begin split, { rintro ⟨z, hz⟩, exact ⟨z.down, quotient.eq_mk_iff_out.2 hz.symm⟩ }, { rintro ⟨z, hz⟩, use z, simpa [hz] using pSet.equiv.symm (quotient.mk_out y) } end) @[simp] theorem to_set_range {α : Type u} (f : α → Set.{max u v}) : (range f).to_set = set.range f := by { ext, simp } /-- Kuratowski ordered pair -/ def pair (x y : Set.{u}) : Set.{u} := {{x}, {x, y}} @[simp] theorem to_set_pair (x y : Set.{u}) : (pair x y).to_set = {{x}, {x, y}} := by simp [pair] /-- A subset of pairs `{(a, b) ∈ x × y | p a b}` -/ def pair_sep (p : Set.{u} → Set.{u} → Prop) (x y : Set.{u}) : Set.{u} := {z ∈ powerset (powerset (x ∪ y)) | ∃ a ∈ x, ∃ b ∈ y, z = pair a b ∧ p a b} @[simp] theorem mem_pair_sep {p} {x y z : Set.{u}} : z ∈ pair_sep p x y ↔ ∃ a ∈ x, ∃ b ∈ y, z = pair a b ∧ p a b := begin refine mem_sep.trans ⟨and.right, λ e, ⟨_, e⟩⟩, rcases e with ⟨a, ax, b, bY, rfl, pab⟩, simp only [mem_powerset, subset_def, mem_union, pair, mem_pair], rintros u (rfl|rfl) v; simp only [mem_singleton, mem_pair], { rintro rfl, exact or.inl ax }, { rintro (rfl|rfl); [left, right]; assumption } end theorem pair_injective : function.injective2 pair := λ x x' y y' H, begin have ae := ext_iff.1 H, simp only [pair, mem_pair] at ae, obtain rfl : x = x', { cases (ae {x}).1 (by simp) with h h, { exact singleton_injective h }, { have m : x' ∈ ({x} : Set), { simp [h] }, rw mem_singleton.mp m } }, have he : x = y → y = y', { rintro rfl, cases (ae {x, y'}).2 (by simp only [eq_self_iff_true, or_true]) with xy'x xy'xx, { rw [eq_comm, ←mem_singleton, ←xy'x, mem_pair], exact or.inr rfl }, { simpa [eq_comm] using (ext_iff.1 xy'xx y').1 (by simp) } }, obtain xyx | xyy' := (ae {x, y}).1 (by simp), { obtain rfl := mem_singleton.mp ((ext_iff.1 xyx y).1 $ by simp), simp [he rfl] }, { obtain rfl | yy' := mem_pair.mp ((ext_iff.1 xyy' y).1 $ by simp), { simp [he rfl] }, { simp [yy'] } } end @[simp] theorem pair_inj {x y x' y' : Set} : pair x y = pair x' y' ↔ x = x' ∧ y = y' := pair_injective.eq_iff /-- The cartesian product, `{(a, b) | a ∈ x, b ∈ y}` -/ def prod : Set.{u} → Set.{u} → Set.{u} := pair_sep (λ a b, true) @[simp] theorem mem_prod {x y z : Set.{u}} : z ∈ prod x y ↔ ∃ a ∈ x, ∃ b ∈ y, z = pair a b := by simp [prod] @[simp] theorem pair_mem_prod {x y a b : Set.{u}} : pair a b ∈ prod x y ↔ a ∈ x ∧ b ∈ y := ⟨λ h, let ⟨a', a'x, b', b'y, e⟩ := mem_prod.1 h in match a', b', pair_injective e, a'x, b'y with ._, ._, ⟨rfl, rfl⟩, ax, bY := ⟨ax, bY⟩ end, λ ⟨ax, bY⟩, mem_prod.2 ⟨a, ax, b, bY, rfl⟩⟩ /-- `is_func x y f` is the assertion that `f` is a subset of `x × y` which relates to each element of `x` a unique element of `y`, so that we can consider `f`as a ZFC function `x → y`. -/ def is_func (x y f : Set.{u}) : Prop := f ⊆ prod x y ∧ ∀ z : Set.{u}, z ∈ x → ∃! w, pair z w ∈ f /-- `funs x y` is `y ^ x`, the set of all set functions `x → y` -/ def funs (x y : Set.{u}) : Set.{u} := {f ∈ powerset (prod x y) | is_func x y f} @[simp] theorem mem_funs {x y f : Set.{u}} : f ∈ funs x y ↔ is_func x y f := by simp [funs, is_func] -- TODO(Mario): Prove this computably noncomputable instance map_definable_aux (f : Set → Set) [H : definable 1 f] : definable 1 (λ y, pair y (f y)) := @classical.all_definable 1 _ /-- Graph of a function: `map f x` is the ZFC function which maps `a ∈ x` to `f a` -/ noncomputable def map (f : Set → Set) [H : definable 1 f] : Set → Set := image (λ y, pair y (f y)) @[simp] theorem mem_map {f : Set → Set} [H : definable 1 f] {x y : Set} : y ∈ map f x ↔ ∃ z ∈ x, pair z (f z) = y := mem_image theorem map_unique {f : Set.{u} → Set.{u}} [H : definable 1 f] {x z : Set.{u}} (zx : z ∈ x) : ∃! w, pair z w ∈ map f x := ⟨f z, image.mk _ _ zx, λ y yx, let ⟨w, wx, we⟩ := mem_image.1 yx, ⟨wz, fy⟩ := pair_injective we in by rw[←fy, wz]⟩ @[simp] theorem map_is_func {f : Set → Set} [H : definable 1 f] {x y : Set} : is_func x y (map f x) ↔ ∀ z ∈ x, f z ∈ y := ⟨λ ⟨ss, h⟩ z zx, let ⟨t, t1, t2⟩ := h z zx in (t2 (f z) (image.mk _ _ zx)).symm ▸ (pair_mem_prod.1 (ss t1)).right, λ h, ⟨λ y yx, let ⟨z, zx, ze⟩ := mem_image.1 yx in ze ▸ pair_mem_prod.2 ⟨zx, h z zx⟩, λ z, map_unique⟩⟩ /-- Given a predicate `p` on ZFC sets. `hereditarily p x` means that `x` has property `p` and the members of `x` are all `hereditarily p`. -/ def hereditarily (p : Set → Prop) : Set → Prop | x := p x ∧ ∀ y ∈ x, hereditarily y using_well_founded { dec_tac := `[assumption] } section hereditarily variables {p : Set.{u} → Prop} {x y : Set.{u}} lemma hereditarily_iff : hereditarily p x ↔ p x ∧ ∀ y ∈ x, hereditarily p y := by rw [← hereditarily] alias hereditarily_iff ↔ hereditarily.def _ lemma hereditarily.self (h : x.hereditarily p) : p x := h.def.1 lemma hereditarily.mem (h : x.hereditarily p) (hy : y ∈ x) : y.hereditarily p := h.def.2 _ hy lemma hereditarily.empty : hereditarily p x → p ∅ := begin apply x.induction_on, intros y IH h, rcases Set.eq_empty_or_nonempty y with (rfl|⟨a, ha⟩), { exact h.self }, { exact IH a ha (h.mem ha) } end end hereditarily end Set /-- The collection of all classes. We define `Class` as `set Set`, as this allows us to get many instances automatically. However, in practice, we treat it as (the definitionally equal) `Set → Prop`. This means, the preferred way to state that `x : Set` belongs to `A : Class` is to write `A x`. -/ @[derive [has_subset, has_sep Set, has_emptyc, inhabited, has_insert Set, has_union, has_inter, has_compl, has_sdiff]] def Class := set Set namespace Class @[ext] theorem ext {x y : Class.{u}} : (∀ z : Set.{u}, x z ↔ y z) → x = y := set.ext theorem ext_iff {x y : Class.{u}} : x = y ↔ ∀ z, x z ↔ y z := set.ext_iff /-- Coerce a ZFC set into a class -/ def of_Set (x : Set.{u}) : Class.{u} := {y | y ∈ x} instance : has_coe Set Class := ⟨of_Set⟩ /-- The universal class -/ def univ : Class := set.univ /-- Assert that `A` is a ZFC set satisfying `B` -/ def to_Set (B : Class.{u}) (A : Class.{u}) : Prop := ∃ x, ↑x = A ∧ B x /-- `A ∈ B` if `A` is a ZFC set which satisfies `B` -/ protected def mem (A B : Class.{u}) : Prop := to_Set.{u} B A instance : has_mem Class Class := ⟨Class.mem⟩ theorem mem_def (A B : Class.{u}) : A ∈ B ↔ ∃ x, ↑x = A ∧ B x := iff.rfl @[simp] theorem not_mem_empty (x : Class.{u}) : x ∉ (∅ : Class.{u}) := λ ⟨_, _, h⟩, h @[simp] theorem not_empty_hom (x : Set.{u}) : ¬ (∅ : Class.{u}) x := id @[simp] theorem mem_univ {A : Class.{u}} : A ∈ univ.{u} ↔ ∃ x : Set.{u}, ↑x = A := exists_congr $ λ x, and_true _ @[simp] theorem mem_univ_hom (x : Set.{u}) : univ.{u} x := trivial theorem eq_univ_iff_forall {A : Class.{u}} : A = univ ↔ ∀ x : Set, A x := set.eq_univ_iff_forall theorem eq_univ_of_forall {A : Class.{u}} : (∀ x : Set, A x) → A = univ := set.eq_univ_of_forall theorem mem_wf : @well_founded Class.{u} (∈) := ⟨begin have H : ∀ x : Set.{u}, @acc Class.{u} (∈) ↑x, { refine λ a, Set.induction_on a (λ x IH, ⟨x, _⟩), rintros A ⟨z, rfl, hz⟩, exact IH z hz }, { refine λ A, ⟨A, _⟩, rintros B ⟨x, rfl, hx⟩, exact H x } end⟩ instance : has_well_founded Class := ⟨_, mem_wf⟩ instance : is_asymm Class (∈) := mem_wf.is_asymm theorem mem_asymm {x y : Class} : x ∈ y → y ∉ x := asymm theorem mem_irrefl (x : Class) : x ∉ x := irrefl x /-- **There is no universal set.** This is stated as `univ ∉ univ`, meaning that `univ` (the class of all sets) is proper (does not belong to the class of all sets). -/ theorem univ_not_mem_univ : univ ∉ univ := mem_irrefl _ /-- Convert a conglomerate (a collection of classes) into a class -/ def Cong_to_Class (x : set Class.{u}) : Class.{u} := {y | ↑y ∈ x} @[simp] theorem Cong_to_Class_empty : Cong_to_Class ∅ = ∅ := by { ext, simp [Cong_to_Class] } /-- Convert a class into a conglomerate (a collection of classes) -/ def Class_to_Cong (x : Class.{u}) : set Class.{u} := {y | y ∈ x} @[simp] theorem Class_to_Cong_empty : Class_to_Cong ∅ = ∅ := by { ext, simp [Class_to_Cong] } /-- The power class of a class is the class of all subclasses that are ZFC sets -/ def powerset (x : Class) : Class := Cong_to_Class (set.powerset x) /-- The union of a class is the class of all members of ZFC sets in the class -/ def sUnion (x : Class) : Class := ⋃₀ (Class_to_Cong x) prefix (name := Class.sUnion) `⋃₀ `:110 := Class.sUnion /-- The intersection of a class is the class of all members of ZFC sets in the class -/ def sInter (x : Class) : Class := ⋂₀ Class_to_Cong x prefix (name := Class.sInter) `⋂₀ `:110 := Class.sInter theorem of_Set.inj {x y : Set.{u}} (h : (x : Class.{u}) = y) : x = y := Set.ext $ λ z, by { change (x : Class.{u}) z ↔ (y : Class.{u}) z, rw h } @[simp] theorem to_Set_of_Set (A : Class.{u}) (x : Set.{u}) : to_Set A x ↔ A x := ⟨λ ⟨y, yx, py⟩, by rwa of_Set.inj yx at py, λ px, ⟨x, rfl, px⟩⟩ @[simp, norm_cast] theorem coe_mem {x : Set.{u}} {A : Class.{u}} : (x : Class.{u}) ∈ A ↔ A x := to_Set_of_Set _ _ @[simp] theorem coe_apply {x y : Set.{u}} : (y : Class.{u}) x ↔ x ∈ y := iff.rfl @[simp, norm_cast] theorem coe_subset (x y : Set.{u}) : (x : Class.{u}) ⊆ y ↔ x ⊆ y := iff.rfl @[simp, norm_cast] theorem coe_sep (p : Class.{u}) (x : Set.{u}) : (↑{y ∈ x | p y} : Class.{u}) = {y ∈ x | p y} := ext $ λ y, Set.mem_sep @[simp, norm_cast] theorem coe_empty : ↑(∅ : Set.{u}) = (∅ : Class.{u}) := ext $ λ y, (iff_false _).2 $ Set.not_mem_empty y @[simp, norm_cast] theorem coe_insert (x y : Set.{u}) : ↑(insert x y) = @insert Set.{u} Class.{u} _ x y := ext $ λ z, Set.mem_insert_iff @[simp, norm_cast] theorem coe_union (x y : Set.{u}) : ↑(x ∪ y) = (x : Class.{u}) ∪ y := ext $ λ z, Set.mem_union @[simp, norm_cast] theorem coe_inter (x y : Set.{u}) : ↑(x ∩ y) = (x : Class.{u}) ∩ y := ext $ λ z, Set.mem_inter @[simp, norm_cast] theorem coe_diff (x y : Set.{u}) : ↑(x \ y) = (x : Class.{u}) \ y := ext $ λ z, Set.mem_diff @[simp, norm_cast] theorem coe_powerset (x : Set.{u}) : ↑x.powerset = powerset.{u} x := ext $ λ z, Set.mem_powerset @[simp] theorem powerset_apply {A : Class.{u}} {x : Set.{u}} : powerset A x ↔ ↑x ⊆ A := iff.rfl @[simp] theorem sUnion_apply {x : Class} {y : Set} : (⋃₀ x) y ↔ ∃ z : Set, x z ∧ y ∈ z := begin split, { rintro ⟨-, ⟨z, rfl, hxz⟩, hyz⟩, exact ⟨z, hxz, hyz⟩ }, { exact λ ⟨z, hxz, hyz⟩, ⟨_, coe_mem.2 hxz, hyz⟩ } end @[simp, norm_cast] theorem coe_sUnion (x : Set.{u}) : ↑(⋃₀ x) = ⋃₀ (x : Class.{u}) := ext $ λ y, Set.mem_sUnion.trans (sUnion_apply.trans $ by simp_rw [coe_apply, exists_prop]).symm @[simp] theorem mem_sUnion {x y : Class.{u}} : y ∈ ⋃₀ x ↔ ∃ z, z ∈ x ∧ y ∈ z := begin split, { rintro ⟨w, rfl, z, hzx, hwz⟩, exact ⟨z, hzx, coe_mem.2 hwz⟩ }, { rintro ⟨w, hwx, z, rfl, hwz⟩, exact ⟨z, rfl, w, hwx, hwz⟩ } end @[simp] theorem sInter_apply {x : Class.{u}} {y : Set.{u}} : (⋂₀ x) y ↔ ∀ z : Set.{u}, x z → y ∈ z := begin refine ⟨λ hxy z hxz, hxy _ ⟨z, rfl, hxz⟩, _⟩, rintro H - ⟨z, rfl, hxz⟩, exact H _ hxz end @[simp, norm_cast] theorem coe_sInter {x : Set.{u}} (h : x.nonempty) : ↑(⋂₀ x) = ⋂₀ (x : Class.{u}) := set.ext $ λ y, (Set.mem_sInter h).trans sInter_apply.symm theorem mem_of_mem_sInter {x y z : Class} (hy : y ∈ ⋂₀ x) (hz : z ∈ x) : y ∈ z := by { obtain ⟨w, rfl, hw⟩ := hy, exact coe_mem.2 (hw z hz) } theorem mem_sInter {x y : Class.{u}} (h : x.nonempty) : y ∈ ⋂₀ x ↔ ∀ z, z ∈ x → y ∈ z := begin refine ⟨λ hy z, mem_of_mem_sInter hy, λ H, _⟩, simp_rw [mem_def, sInter_apply], obtain ⟨z, hz⟩ := h, obtain ⟨y, rfl, hzy⟩ := H z (coe_mem.2 hz), refine ⟨y, rfl, λ w hxw, _⟩, simpa only [coe_mem, coe_apply] using H w (coe_mem.2 hxw), end @[simp] theorem sUnion_empty : ⋃₀ (∅ : Class.{u}) = ∅ := by { ext, simp } @[simp] theorem sInter_empty : ⋂₀ (∅ : Class.{u}) = univ := by { ext, simp [sInter, ←univ] } /-- An induction principle for sets. If every subset of a class is a member, then the class is universal. -/ theorem eq_univ_of_powerset_subset {A : Class} (hA : powerset A ⊆ A) : A = univ := eq_univ_of_forall begin by_contra' hnA, exact well_founded.min_mem Set.mem_wf _ hnA (hA $ λ x hx, not_not.1 $ λ hB, well_founded.not_lt_min Set.mem_wf _ hnA hB $ coe_apply.1 hx) end /-- The definite description operator, which is `{x}` if `{y | A y} = {x}` and `∅` otherwise. -/ def iota (A : Class) : Class := ⋃₀ {x | ∀ y, A y ↔ y = x} theorem iota_val (A : Class) (x : Set) (H : ∀ y, A y ↔ y = x) : iota A = ↑x := ext $ λ y, ⟨λ ⟨._, ⟨x', rfl, h⟩, yx'⟩, by rwa ←((H x').1 $ (h x').2 rfl), λ yx, ⟨_, ⟨x, rfl, H⟩, yx⟩⟩ /-- Unlike the other set constructors, the `iota` definite descriptor is a set for any set input, but not constructively so, so there is no associated `Class → Set` function. -/ theorem iota_ex (A) : iota.{u} A ∈ univ.{u} := mem_univ.2 $ or.elim (classical.em $ ∃ x, ∀ y, A y ↔ y = x) (λ ⟨x, h⟩, ⟨x, eq.symm $ iota_val A x h⟩) (λ hn, ⟨∅, ext (λ z, coe_empty.symm ▸ ⟨false.rec _, λ ⟨._, ⟨x, rfl, H⟩, zA⟩, hn ⟨x, H⟩⟩)⟩) /-- Function value -/ def fval (F A : Class.{u}) : Class.{u} := iota (λ y, to_Set (λ x, F (Set.pair x y)) A) infixl ` ′ `:100 := fval theorem fval_ex (F A : Class.{u}) : F ′ A ∈ univ.{u} := iota_ex _ end Class namespace Set @[simp] theorem map_fval {f : Set.{u} → Set.{u}} [H : pSet.definable 1 f] {x y : Set.{u}} (h : y ∈ x) : (Set.map f x ′ y : Class.{u}) = f y := Class.iota_val _ _ (λ z, by { rw [Class.to_Set_of_Set, Class.coe_apply, mem_map], exact ⟨λ ⟨w, wz, pr⟩, let ⟨wy, fw⟩ := Set.pair_injective pr in by rw[←fw, wy], λ e, by { subst e, exact ⟨_, h, rfl⟩ }⟩ }) variables (x : Set.{u}) (h : ∅ ∉ x) /-- A choice function on the class of nonempty ZFC sets. -/ noncomputable def choice : Set := @map (λ y, classical.epsilon (λ z, z ∈ y)) (classical.all_definable _) x include h theorem choice_mem_aux (y : Set.{u}) (yx : y ∈ x) : classical.epsilon (λ z : Set.{u}, z ∈ y) ∈ y := @classical.epsilon_spec _ (λ z : Set.{u}, z ∈ y) $ classical.by_contradiction $ λ n, h $ by rwa ←((eq_empty y).2 $ λ z zx, n ⟨z, zx⟩) theorem choice_is_func : is_func x (⋃₀ x) (choice x) := (@map_is_func _ (classical.all_definable _) _ _).2 $ λ y yx, mem_sUnion.2 ⟨y, yx, choice_mem_aux x h y yx⟩ theorem choice_mem (y : Set.{u}) (yx : y ∈ x) : (choice x ′ y : Class.{u}) ∈ (y : Class.{u}) := begin delta choice, rw [map_fval yx, Class.coe_mem, Class.coe_apply], exact choice_mem_aux x h y yx end end Set
166492cbca2b531d3350c17394d934e0a8e225a8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/monoidal/End.lean
502a540e79c6ebfe96ff4c472ff14d5650630566
[ "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
10,736
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Andrew Yang -/ import category_theory.monoidal.functor /-! # Endofunctors as a monoidal category. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We give the monoidal category structure on `C ⥤ C`, and show that when `C` itself is monoidal, it embeds via a monoidal functor into `C ⥤ C`. ## TODO Can we use this to show coherence results, e.g. a cheap proof that `λ_ (𝟙_ C) = ρ_ (𝟙_ C)`? I suspect this is harder than is usually made out. -/ universes v u namespace category_theory variables (C : Type u) [category.{v} C] /-- The category of endofunctors of any category is a monoidal category, with tensor product given by composition of functors (and horizontal composition of natural transformations). -/ def endofunctor_monoidal_category : monoidal_category (C ⥤ C) := { tensor_obj := λ F G, F ⋙ G, tensor_hom := λ F G F' G' α β, α ◫ β, tensor_unit := 𝟭 C, associator := λ F G H, functor.associator F G H, left_unitor := λ F, functor.left_unitor F, right_unitor := λ F, functor.right_unitor F, }. open category_theory.monoidal_category local attribute [instance] endofunctor_monoidal_category local attribute [reducible] endofunctor_monoidal_category /-- Tensoring on the right gives a monoidal functor from `C` into endofunctors of `C`. -/ @[simps] def tensoring_right_monoidal [monoidal_category.{v} C] : monoidal_functor C (C ⥤ C) := { ε := (right_unitor_nat_iso C).inv, μ := λ X Y, { app := λ Z, (α_ Z X Y).hom, naturality' := λ Z Z' f, by { dsimp, rw associator_naturality, simp, } }, μ_natural' := λ X Y X' Y' f g, by { ext Z, dsimp, simp only [←id_tensor_comp_tensor_id g f, id_tensor_comp, ←tensor_id, category.assoc, associator_naturality, associator_naturality_assoc], }, associativity' := λ X Y Z, by { ext W, dsimp, simp [pentagon], }, left_unitality' := λ X, by { ext Y, dsimp, rw [category.id_comp, triangle, ←tensor_comp], simp, }, right_unitality' := λ X, begin ext Y, dsimp, rw [tensor_id, category.comp_id, right_unitor_tensor_inv, category.assoc, iso.inv_hom_id_assoc, ←id_tensor_comp, iso.inv_hom_id, tensor_id], end, ε_is_iso := by apply_instance, μ_is_iso := λ X Y, -- We could avoid needing to do this explicitly by -- constructing a partially applied analogue of `associator_nat_iso`. ⟨⟨{ app := λ Z, (α_ Z X Y).inv, naturality' := λ Z Z' f, by { dsimp, rw ←associator_inv_naturality, simp, } }, by tidy⟩⟩, ..tensoring_right C }. variable {C} variables {M : Type*} [category M] [monoidal_category M] (F : monoidal_functor M (C ⥤ C)) @[simp, reassoc] lemma μ_hom_inv_app (i j : M) (X : C) : (F.μ i j).app X ≫ (F.μ_iso i j).inv.app X = 𝟙 _ := (F.μ_iso i j).hom_inv_id_app X @[simp, reassoc] lemma μ_inv_hom_app (i j : M) (X : C) : (F.μ_iso i j).inv.app X ≫ (F.μ i j).app X = 𝟙 _ := (F.μ_iso i j).inv_hom_id_app X @[simp, reassoc] lemma ε_hom_inv_app (X : C) : F.ε.app X ≫ F.ε_iso.inv.app X = 𝟙 _ := F.ε_iso.hom_inv_id_app X @[simp, reassoc] lemma ε_inv_hom_app (X : C) : F.ε_iso.inv.app X ≫ F.ε.app X = 𝟙 _ := F.ε_iso.inv_hom_id_app X @[simp, reassoc] lemma ε_naturality {X Y : C} (f : X ⟶ Y) : F.ε.app X ≫ (F.obj (𝟙_M)).map f = f ≫ F.ε.app Y := (F.ε.naturality f).symm @[simp, reassoc] lemma ε_inv_naturality {X Y : C} (f : X ⟶ Y) : (F.obj (𝟙_M)).map f ≫ F.ε_iso.inv.app Y = F.ε_iso.inv.app X ≫ f := F.ε_iso.inv.naturality f @[simp, reassoc] lemma μ_naturality {m n : M} {X Y : C} (f : X ⟶ Y) : (F.obj n).map ((F.obj m).map f) ≫ (F.μ m n).app Y = (F.μ m n).app X ≫ (F.obj _).map f := (F.to_lax_monoidal_functor.μ m n).naturality f -- This is a simp lemma in the reverse direction via `nat_trans.naturality`. @[reassoc] lemma μ_inv_naturality {m n : M} {X Y : C} (f : X ⟶ Y) : (F.μ_iso m n).inv.app X ≫ (F.obj n).map ((F.obj m).map f) = (F.obj _).map f ≫ (F.μ_iso m n).inv.app Y := ((F.μ_iso m n).inv.naturality f).symm -- This is not a simp lemma since it could be proved by the lemmas later. @[reassoc] lemma μ_naturality₂ {m n m' n' : M} (f : m ⟶ m') (g : n ⟶ n') (X : C) : (F.map g).app ((F.obj m).obj X) ≫ (F.obj n').map ((F.map f).app X) ≫ (F.μ m' n').app X = (F.μ m n).app X ≫ (F.map (f ⊗ g)).app X := begin have := congr_app (F.to_lax_monoidal_functor.μ_natural f g) X, dsimp at this, simpa using this, end @[simp, reassoc] lemma μ_naturalityₗ {m n m' : M} (f : m ⟶ m') (X : C) : (F.obj n).map ((F.map f).app X) ≫ (F.μ m' n).app X = (F.μ m n).app X ≫ (F.map (f ⊗ 𝟙 n)).app X := begin rw ← μ_naturality₂ F f (𝟙 n) X, simp, end @[simp, reassoc] lemma μ_naturalityᵣ {m n n' : M} (g : n ⟶ n') (X : C) : (F.map g).app ((F.obj m).obj X) ≫ (F.μ m n').app X = (F.μ m n).app X ≫ (F.map (𝟙 m ⊗ g)).app X := begin rw ← μ_naturality₂ F (𝟙 m) g X, simp, end @[simp, reassoc] lemma μ_inv_naturalityₗ {m n m' : M} (f : m ⟶ m') (X : C) : (F.μ_iso m n).inv.app X ≫ (F.obj n).map ((F.map f).app X) = (F.map (f ⊗ 𝟙 n)).app X ≫ (F.μ_iso m' n).inv.app X := begin rw [← is_iso.comp_inv_eq, category.assoc, ← is_iso.eq_inv_comp], simp, end @[simp, reassoc] lemma μ_inv_naturalityᵣ {m n n' : M} (g : n ⟶ n') (X : C) : (F.μ_iso m n).inv.app X ≫ (F.map g).app ((F.obj m).obj X) = (F.map (𝟙 m ⊗ g)).app X ≫ (F.μ_iso m n').inv.app X := begin rw [← is_iso.comp_inv_eq, category.assoc, ← is_iso.eq_inv_comp], simp, end @[reassoc] lemma left_unitality_app (n : M) (X : C) : (F.obj n).map (F.ε.app X) ≫ (F.μ (𝟙_M) n).app X ≫ (F.map (λ_ n).hom).app X = 𝟙 _ := begin have := congr_app (F.to_lax_monoidal_functor.left_unitality n) X, dsimp at this, simpa using this.symm, end @[reassoc, simp] lemma obj_ε_app (n : M) (X : C) : (F.obj n).map (F.ε.app X) = (F.map (λ_ n).inv).app X ≫ (F.μ_iso (𝟙_M) n).inv.app X := begin refine eq.trans _ (category.id_comp _), rw [← category.assoc, ← is_iso.comp_inv_eq, ← is_iso.comp_inv_eq, category.assoc], convert left_unitality_app F n X, { simp }, { ext, simpa } end @[reassoc, simp] lemma obj_ε_inv_app (n : M) (X : C) : (F.obj n).map (F.ε_iso.inv.app X) = (F.μ (𝟙_M) n).app X ≫ (F.map (λ_ n).hom).app X := begin rw [← cancel_mono ((F.obj n).map (F.ε.app X)), ← functor.map_comp], simpa, end @[reassoc] lemma right_unitality_app (n : M) (X : C) : F.ε.app ((F.obj n).obj X) ≫ (F.μ n (𝟙_M)).app X ≫ (F.map (ρ_ n).hom).app X = 𝟙 _ := begin have := congr_app (F.to_lax_monoidal_functor.right_unitality n) X, dsimp at this, simpa using this.symm, end @[simp] lemma ε_app_obj (n : M) (X : C) : F.ε.app ((F.obj n).obj X) = (F.map (ρ_ n).inv).app X ≫ (F.μ_iso n (𝟙_M)).inv.app X := begin refine eq.trans _ (category.id_comp _), rw [← category.assoc, ← is_iso.comp_inv_eq, ← is_iso.comp_inv_eq, category.assoc], convert right_unitality_app F n X, { simp }, { ext, simpa } end @[simp] lemma ε_inv_app_obj (n : M) (X : C) : F.ε_iso.inv.app ((F.obj n).obj X) = (F.μ n (𝟙_M)).app X ≫ (F.map (ρ_ n).hom).app X := begin rw [← cancel_mono (F.ε.app ((F.obj n).obj X)), ε_inv_hom_app], simpa end @[reassoc] lemma associativity_app (m₁ m₂ m₃: M) (X : C) : (F.obj m₃).map ((F.μ m₁ m₂).app X) ≫ (F.μ (m₁ ⊗ m₂) m₃).app X ≫ (F.map (α_ m₁ m₂ m₃).hom).app X = (F.μ m₂ m₃).app ((F.obj m₁).obj X) ≫ (F.μ m₁ (m₂ ⊗ m₃)).app X := begin have := congr_app (F.to_lax_monoidal_functor.associativity m₁ m₂ m₃) X, dsimp at this, simpa using this, end @[reassoc, simp] lemma obj_μ_app (m₁ m₂ m₃ : M) (X : C) : (F.obj m₃).map ((F.μ m₁ m₂).app X) = (F.μ m₂ m₃).app ((F.obj m₁).obj X) ≫ (F.μ m₁ (m₂ ⊗ m₃)).app X ≫ (F.map (α_ m₁ m₂ m₃).inv).app X ≫ (F.μ_iso (m₁ ⊗ m₂) m₃).inv.app X := begin rw [← associativity_app_assoc], dsimp, simp, dsimp, simp, end @[reassoc, simp] lemma obj_μ_inv_app (m₁ m₂ m₃ : M) (X : C) : (F.obj m₃).map ((F.μ_iso m₁ m₂).inv.app X) = (F.μ (m₁ ⊗ m₂) m₃).app X ≫ (F.map (α_ m₁ m₂ m₃).hom).app X ≫ (F.μ_iso m₁ (m₂ ⊗ m₃)).inv.app X ≫ (F.μ_iso m₂ m₃).inv.app ((F.obj m₁).obj X) := begin rw ← is_iso.inv_eq_inv, convert obj_μ_app F m₁ m₂ m₃ X using 1, { ext, rw ← functor.map_comp, simp }, { simp only [monoidal_functor.μ_iso_hom, category.assoc, nat_iso.inv_inv_app, is_iso.inv_comp], congr, { ext, simp }, { ext, simpa } } end @[simp, reassoc] lemma obj_zero_map_μ_app {m : M} {X Y : C} (f : X ⟶ (F.obj m).obj Y) : (F.obj (𝟙_M)).map f ≫ (F.μ m (𝟙_M)).app _ = F.ε_iso.inv.app _ ≫ f ≫ (F.map (ρ_ m).inv).app _ := begin rw [← is_iso.inv_comp_eq, ← is_iso.comp_inv_eq], simp, end @[simp] lemma obj_μ_zero_app (m₁ m₂ : M) (X : C) : (F.obj m₂).map ((F.μ m₁ (𝟙_M)).app X) = (F.μ (𝟙_M) m₂).app ((F.obj m₁).obj X) ≫ (F.map (λ_ m₂).hom).app ((F.obj m₁).obj X) ≫ (F.obj m₂).map ((F.map (ρ_ m₁).inv).app X) := begin rw [← obj_ε_inv_app_assoc, ← functor.map_comp], congr, simp, end /-- If `m ⊗ n ≅ 𝟙_M`, then `F.obj m` is a left inverse of `F.obj n`. -/ @[simps] noncomputable def unit_of_tensor_iso_unit (m n : M) (h : m ⊗ n ≅ 𝟙_M) : F.obj m ⋙ F.obj n ≅ 𝟭 C := F.μ_iso m n ≪≫ F.to_functor.map_iso h ≪≫ F.ε_iso.symm /-- If `m ⊗ n ≅ 𝟙_M` and `n ⊗ m ≅ 𝟙_M` (subject to some commuting constraints), then `F.obj m` and `F.obj n` forms a self-equivalence of `C`. -/ @[simps] noncomputable def equiv_of_tensor_iso_unit (m n : M) (h₁ : m ⊗ n ≅ 𝟙_M) (h₂ : n ⊗ m ≅ 𝟙_M) (H : (h₁.hom ⊗ 𝟙 m) ≫ (λ_ m).hom = (α_ m n m).hom ≫ (𝟙 m ⊗ h₂.hom) ≫ (ρ_ m).hom) : C ≌ C := { functor := F.obj m, inverse := F.obj n, unit_iso := (unit_of_tensor_iso_unit F m n h₁).symm, counit_iso := unit_of_tensor_iso_unit F n m h₂, functor_unit_iso_comp' := begin intro X, dsimp, simp only [μ_naturalityᵣ_assoc, μ_naturalityₗ_assoc, ε_inv_app_obj, category.assoc, obj_μ_inv_app, functor.map_comp, μ_inv_hom_app_assoc, obj_ε_app, unit_of_tensor_iso_unit_inv_app], simp [← nat_trans.comp_app, ← F.to_functor.map_comp, ← H, - functor.map_comp] end } end category_theory
79085eb7af9f71c07b93b19147adabe2e24f6710
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/convex/specific_functions.lean
f8ad2ed96ed8b1c0259bb4376ed05f731d28570b
[ "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
13,217
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Sébastien Gouëzel -/ import analysis.calculus.mean_value import analysis.special_functions.pow_deriv import analysis.special_functions.sqrt /-! # Collection of convex functions In this file we prove that the following functions are convex: * `strict_convex_on_exp` : The exponential function is strictly convex. * `even.convex_on_pow`, `even.strict_convex_on_pow` : For an even `n : ℕ`, `λ x, x ^ n` is convex and strictly convex when `2 ≤ n`. * `convex_on_pow`, `strict_convex_on_pow` : For `n : ℕ`, `λ x, x ^ n` is convex on $[0, +∞)$ and strictly convex when `2 ≤ n`. * `convex_on_zpow`, `strict_convex_on_zpow` : For `m : ℤ`, `λ x, x ^ m` is convex on $[0, +∞)$ and strictly convex when `m ≠ 0, 1`. * `convex_on_rpow`, `strict_convex_on_rpow` : For `p : ℝ`, `λ x, x ^ p` is convex on $[0, +∞)$ when `1 ≤ p` and strictly convex when `1 < p`. * `strict_concave_on_log_Ioi`, `strict_concave_on_log_Iio`: `real.log` is strictly concave on $(0, +∞)$ and $(-∞, 0)$ respectively. ## TODO For `p : ℝ`, prove that `λ x, x ^ p` is concave when `0 ≤ p ≤ 1` and strictly concave when `0 < p < 1`. -/ open real set open_locale big_operators nnreal /-- `exp` is strictly convex on the whole real line. -/ lemma strict_convex_on_exp : strict_convex_on ℝ univ exp := strict_convex_on_univ_of_deriv2_pos continuous_exp (λ x, (iter_deriv_exp 2).symm ▸ exp_pos x) /-- `exp` is convex on the whole real line. -/ lemma convex_on_exp : convex_on ℝ univ exp := strict_convex_on_exp.convex_on /-- `x^n`, `n : ℕ` is convex on the whole real line whenever `n` is even -/ lemma even.convex_on_pow {n : ℕ} (hn : even n) : convex_on ℝ set.univ (λ x : ℝ, x^n) := begin apply convex_on_univ_of_deriv2_nonneg (differentiable_pow n), { simp only [deriv_pow', differentiable.mul, differentiable_const, differentiable_pow] }, { intro x, obtain ⟨k, hk⟩ := (hn.tsub $ even_bit0 _).exists_two_nsmul _, rw [iter_deriv_pow, finset.prod_range_cast_nat_sub, hk, nsmul_eq_mul, pow_mul'], exact mul_nonneg (nat.cast_nonneg _) (pow_two_nonneg _) } end /-- `x^n`, `n : ℕ` is strictly convex on the whole real line whenever `n ≠ 0` is even. -/ lemma even.strict_convex_on_pow {n : ℕ} (hn : even n) (h : n ≠ 0) : strict_convex_on ℝ set.univ (λ x : ℝ, x^n) := begin apply strict_mono.strict_convex_on_univ_of_deriv (continuous_pow n), rw deriv_pow', replace h := nat.pos_of_ne_zero h, exact strict_mono.const_mul (odd.strict_mono_pow $ nat.even.sub_odd h hn $ nat.odd_iff.2 rfl) (nat.cast_pos.2 h), end /-- `x^n`, `n : ℕ` is convex on `[0, +∞)` for all `n` -/ lemma convex_on_pow (n : ℕ) : convex_on ℝ (Ici 0) (λ x : ℝ, x^n) := begin apply convex_on_of_deriv2_nonneg (convex_Ici _) (continuous_pow n).continuous_on (differentiable_on_pow n), { simp only [deriv_pow'], exact (@differentiable_on_pow ℝ _ _ _).const_mul (n : ℝ) }, { intros x hx, rw [iter_deriv_pow, finset.prod_range_cast_nat_sub], exact mul_nonneg (nat.cast_nonneg _) (pow_nonneg (interior_subset hx) _) } end /-- `x^n`, `n : ℕ` is strictly convex on `[0, +∞)` for all `n` greater than `2`. -/ lemma strict_convex_on_pow {n : ℕ} (hn : 2 ≤ n) : strict_convex_on ℝ (Ici 0) (λ x : ℝ, x^n) := begin apply strict_mono_on.strict_convex_on_of_deriv (convex_Ici _) (continuous_on_pow _), rw [deriv_pow', interior_Ici], exact λ x (hx : 0 < x) y hy hxy, mul_lt_mul_of_pos_left (pow_lt_pow_of_lt_left hxy hx.le $ nat.sub_pos_of_lt hn) (nat.cast_pos.2 $ zero_lt_two.trans_le hn), end /-- Specific case of Jensen's inequality for sums of powers -/ lemma real.pow_sum_div_card_le_sum_pow {α : Type*} {s : finset α} {f : α → ℝ} (n : ℕ) (hf : ∀ a ∈ s, 0 ≤ f a) : (∑ x in s, f x) ^ (n + 1) / s.card ^ n ≤ ∑ x in s, (f x) ^ (n + 1) := begin by_cases hs0 : s = ∅, { simp_rw [hs0, finset.sum_empty, zero_pow' _ (nat.succ_ne_zero n), zero_div] }, { have hs : s.card ≠ 0 := hs0 ∘ finset.card_eq_zero.1, have hs' : (s.card : ℝ) ≠ 0 := (nat.cast_ne_zero.2 hs), have hs'' : 0 < (s.card : ℝ) := nat.cast_pos.2 (nat.pos_of_ne_zero hs), suffices : (∑ x in s, f x / s.card) ^ (n + 1) ≤ ∑ x in s, (f x ^ (n + 1) / s.card), by rwa [← finset.sum_div, ← finset.sum_div, div_pow, pow_succ' (s.card : ℝ), ← div_div, div_le_iff hs'', div_mul, div_self hs', div_one] at this, have := @convex_on.map_sum_le ℝ ℝ ℝ α _ _ _ _ _ _ (set.Ici 0) (λ x, x ^ (n + 1)) s (λ _, 1 / s.card) (coe ∘ f) (convex_on_pow (n + 1)) _ _ (λ i hi, set.mem_Ici.2 (hf i hi)), { simpa only [inv_mul_eq_div, one_div, algebra.id.smul_eq_mul] using this }, { simp only [one_div, inv_nonneg, nat.cast_nonneg, implies_true_iff] }, { simpa only [one_div, finset.sum_const, nsmul_eq_mul] using mul_inv_cancel hs' }} end lemma nnreal.pow_sum_div_card_le_sum_pow {α : Type*} (s : finset α) (f : α → ℝ≥0) (n : ℕ) : (∑ x in s, f x) ^ (n + 1) / s.card ^ n ≤ ∑ x in s, (f x) ^ (n + 1) := by simpa only [← nnreal.coe_le_coe, nnreal.coe_sum, nonneg.coe_div, nnreal.coe_pow] using @real.pow_sum_div_card_le_sum_pow α s (coe ∘ f) n (λ _ _, nnreal.coe_nonneg _) lemma finset.prod_nonneg_of_card_nonpos_even {α β : Type*} [linear_ordered_comm_ring β] {f : α → β} [decidable_pred (λ x, f x ≤ 0)] {s : finset α} (h0 : even (s.filter (λ x, f x ≤ 0)).card) : 0 ≤ ∏ x in s, f x := calc 0 ≤ (∏ x in s, ((if f x ≤ 0 then (-1:β) else 1) * f x)) : finset.prod_nonneg (λ x _, by { split_ifs with hx hx, by simp [hx], simp at hx ⊢, exact le_of_lt hx }) ... = _ : by rw [finset.prod_mul_distrib, finset.prod_ite, finset.prod_const_one, mul_one, finset.prod_const, neg_one_pow_eq_pow_mod_two, nat.even_iff.1 h0, pow_zero, one_mul] lemma int_prod_range_nonneg (m : ℤ) (n : ℕ) (hn : even n) : 0 ≤ ∏ k in finset.range n, (m - k) := begin rcases hn with ⟨n, rfl⟩, induction n with n ihn, { simp }, rw ← two_mul at ihn, rw [← two_mul, nat.succ_eq_add_one, mul_add, mul_one, bit0, ← add_assoc, finset.prod_range_succ, finset.prod_range_succ, mul_assoc], refine mul_nonneg ihn _, generalize : (1 + 1) * n = k, cases le_or_lt m k with hmk hmk, { have : m ≤ k + 1, from hmk.trans (lt_add_one ↑k).le, exact mul_nonneg_of_nonpos_of_nonpos (sub_nonpos_of_le hmk) (sub_nonpos_of_le this) }, { exact mul_nonneg (sub_nonneg_of_le hmk.le) (sub_nonneg_of_le hmk) } end lemma int_prod_range_pos {m : ℤ} {n : ℕ} (hn : even n) (hm : m ∉ Ico (0 : ℤ) n) : 0 < ∏ k in finset.range n, (m - k) := begin refine (int_prod_range_nonneg m n hn).lt_of_ne (λ h, hm _), rw [eq_comm, finset.prod_eq_zero_iff] at h, obtain ⟨a, ha, h⟩ := h, rw sub_eq_zero.1 h, exact ⟨int.coe_zero_le _, int.coe_nat_lt.2 $ finset.mem_range.1 ha⟩, end /-- `x^m`, `m : ℤ` is convex on `(0, +∞)` for all `m` -/ lemma convex_on_zpow (m : ℤ) : convex_on ℝ (Ioi 0) (λ x : ℝ, x^m) := begin have : ∀ n : ℤ, differentiable_on ℝ (λ x, x ^ n) (Ioi (0 : ℝ)), from λ n, differentiable_on_zpow _ _ (or.inl $ lt_irrefl _), apply convex_on_of_deriv2_nonneg (convex_Ioi 0); try { simp only [interior_Ioi, deriv_zpow'] }, { exact (this _).continuous_on }, { exact this _ }, { exact (this _).const_mul _ }, { intros x hx, rw iter_deriv_zpow, refine mul_nonneg _ (zpow_nonneg (le_of_lt hx) _), exact_mod_cast int_prod_range_nonneg _ _ (even_bit0 1) } end /-- `x^m`, `m : ℤ` is convex on `(0, +∞)` for all `m` except `0` and `1`. -/ lemma strict_convex_on_zpow {m : ℤ} (hm₀ : m ≠ 0) (hm₁ : m ≠ 1) : strict_convex_on ℝ (Ioi 0) (λ x : ℝ, x^m) := begin apply strict_convex_on_of_deriv2_pos' (convex_Ioi 0), { exact (continuous_on_zpow₀ m).mono (λ x hx, ne_of_gt hx) }, intros x hx, rw iter_deriv_zpow, refine mul_pos _ (zpow_pos_of_pos hx _), exact_mod_cast int_prod_range_pos (even_bit0 1) (λ hm, _), norm_cast at hm, rw ← finset.coe_Ico at hm, fin_cases hm; cc, end lemma convex_on_rpow {p : ℝ} (hp : 1 ≤ p) : convex_on ℝ (Ici 0) (λ x : ℝ, x^p) := begin have A : deriv (λ (x : ℝ), x ^ p) = λ x, p * x^(p-1), by { ext x, simp [hp] }, apply convex_on_of_deriv2_nonneg (convex_Ici 0), { exact continuous_on_id.rpow_const (λ x _, or.inr (zero_le_one.trans hp)) }, { exact (differentiable_rpow_const hp).differentiable_on }, { rw A, assume x hx, replace hx : x ≠ 0, by { simp at hx, exact ne_of_gt hx }, simp [differentiable_at.differentiable_within_at, hx] }, { assume x hx, replace hx : 0 < x, by simpa using hx, suffices : 0 ≤ p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A], apply mul_nonneg (le_trans zero_le_one hp), exact mul_nonneg (sub_nonneg_of_le hp) (rpow_nonneg_of_nonneg hx.le _) } end lemma strict_convex_on_rpow {p : ℝ} (hp : 1 < p) : strict_convex_on ℝ (Ici 0) (λ x : ℝ, x^p) := begin have A : deriv (λ (x : ℝ), x ^ p) = λ x, p * x^(p-1), by { ext x, simp [hp.le] }, apply strict_convex_on_of_deriv2_pos (convex_Ici 0), { exact continuous_on_id.rpow_const (λ x _, or.inr (zero_le_one.trans hp.le)) }, rw interior_Ici, rintro x (hx : 0 < x), suffices : 0 < p * ((p - 1) * x ^ (p - 1 - 1)), by simpa [ne_of_gt hx, A], exact mul_pos (zero_lt_one.trans hp) (mul_pos (sub_pos_of_lt hp) (rpow_pos_of_pos hx _)), end lemma strict_concave_on_log_Ioi : strict_concave_on ℝ (Ioi 0) log := begin have h₁ : Ioi 0 ⊆ ({0} : set ℝ)ᶜ, { exact λ x (hx : 0 < x) (hx' : x = 0), hx.ne' hx' }, refine strict_concave_on_of_deriv2_neg' (convex_Ioi 0) (continuous_on_log.mono h₁) (λ x (hx : 0 < x), _), rw [function.iterate_succ, function.iterate_one], change (deriv (deriv log)) x < 0, rw [deriv_log', deriv_inv], exact neg_neg_of_pos (inv_pos.2 $ sq_pos_of_ne_zero _ hx.ne'), end lemma strict_concave_on_log_Iio : strict_concave_on ℝ (Iio 0) log := begin have h₁ : Iio 0 ⊆ ({0} : set ℝ)ᶜ, { exact λ x (hx : x < 0) (hx' : x = 0), hx.ne hx' }, refine strict_concave_on_of_deriv2_neg' (convex_Iio 0) (continuous_on_log.mono h₁) (λ x (hx : x < 0), _), rw [function.iterate_succ, function.iterate_one], change (deriv (deriv log)) x < 0, rw [deriv_log', deriv_inv], exact neg_neg_of_pos (inv_pos.2 $ sq_pos_of_ne_zero _ hx.ne), end section sqrt_mul_log lemma has_deriv_at_sqrt_mul_log {x : ℝ} (hx : x ≠ 0) : has_deriv_at (λ x, sqrt x * log x) ((2 + log x) / (2 * sqrt x)) x := begin convert (has_deriv_at_sqrt hx).mul (has_deriv_at_log hx), rw [add_div, div_mul_right (sqrt x) two_ne_zero, ←div_eq_mul_inv, sqrt_div_self', add_comm, div_eq_mul_one_div, mul_comm], end lemma deriv_sqrt_mul_log (x : ℝ) : deriv (λ x, sqrt x * log x) x = (2 + log x) / (2 * sqrt x) := begin cases lt_or_le 0 x with hx hx, { exact (has_deriv_at_sqrt_mul_log hx.ne').deriv }, { rw [sqrt_eq_zero_of_nonpos hx, mul_zero, div_zero], refine has_deriv_within_at.deriv_eq_zero _ (unique_diff_on_Iic 0 x hx), refine (has_deriv_within_at_const x _ 0).congr_of_mem (λ x hx, _) hx, rw [sqrt_eq_zero_of_nonpos hx, zero_mul] }, end lemma deriv_sqrt_mul_log' : deriv (λ x, sqrt x * log x) = λ x, (2 + log x) / (2 * sqrt x) := funext deriv_sqrt_mul_log lemma deriv2_sqrt_mul_log (x : ℝ) : deriv^[2] (λ x, sqrt x * log x) x = -log x / (4 * sqrt x ^ 3) := begin simp only [nat.iterate, deriv_sqrt_mul_log'], cases le_or_lt x 0 with hx hx, { rw [sqrt_eq_zero_of_nonpos hx, zero_pow zero_lt_three, mul_zero, div_zero], refine has_deriv_within_at.deriv_eq_zero _ (unique_diff_on_Iic 0 x hx), refine (has_deriv_within_at_const _ _ 0).congr_of_mem (λ x hx, _) hx, rw [sqrt_eq_zero_of_nonpos hx, mul_zero, div_zero] }, { have h₀ : sqrt x ≠ 0, from sqrt_ne_zero'.2 hx, convert (((has_deriv_at_log hx.ne').const_add 2).div ((has_deriv_at_sqrt hx.ne').const_mul 2) $ mul_ne_zero two_ne_zero h₀).deriv using 1, nth_rewrite 2 [← mul_self_sqrt hx.le], field_simp, ring }, end lemma strict_concave_on_sqrt_mul_log_Ioi : strict_concave_on ℝ (set.Ioi 1) (λ x, sqrt x * log x) := begin apply strict_concave_on_of_deriv2_neg' (convex_Ioi 1) _ (λ x hx, _), { exact continuous_sqrt.continuous_on.mul (continuous_on_log.mono (λ x hx, ne_of_gt (zero_lt_one.trans hx))) }, { rw [deriv2_sqrt_mul_log x], exact div_neg_of_neg_of_pos (neg_neg_of_pos (log_pos hx)) (mul_pos four_pos (pow_pos (sqrt_pos.mpr (zero_lt_one.trans hx)) 3)) }, end end sqrt_mul_log open_locale real lemma strict_concave_on_sin_Icc : strict_concave_on ℝ (Icc 0 π) sin := begin apply strict_concave_on_of_deriv2_neg (convex_Icc _ _) continuous_on_sin (λ x hx, _), rw interior_Icc at hx, simp [sin_pos_of_mem_Ioo hx], end lemma strict_concave_on_cos_Icc : strict_concave_on ℝ (Icc (-(π/2)) (π/2)) cos := begin apply strict_concave_on_of_deriv2_neg (convex_Icc _ _) continuous_on_cos (λ x hx, _), rw interior_Icc at hx, simp [cos_pos_of_mem_Ioo hx], end
f5a889f758490ed41de773a6cf0c0c57d1dd178f
130c49f47783503e462c16b2eff31933442be6ff
/src/Lean/Meta/Tactic/Cases.lean
cf43e0653ea1e91f0da4c2ffbe6445ebe16e4a32
[ "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
16,993
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.AppBuilder import Lean.Meta.Tactic.Induction import Lean.Meta.Tactic.Injection import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Subst namespace Lean.Meta private def throwInductiveTypeExpected {α} (type : Expr) : MetaM α := do throwError "failed to compile pattern matching, inductive type expected{indentExpr type}" def getInductiveUniverseAndParams (type : Expr) : MetaM (List Level × Array Expr) := do let type ← whnfD type matchConstInduct type.getAppFn (fun _ => throwInductiveTypeExpected type) fun val us => let I := type.getAppFn let Iargs := type.getAppArgs let params := Iargs.extract 0 val.numParams pure (us, params) private def mkEqAndProof (lhs rhs : Expr) : MetaM (Expr × Expr) := do let lhsType ← inferType lhs let rhsType ← inferType rhs let u ← getLevel lhsType if (← isDefEq lhsType rhsType) then pure (mkApp3 (mkConst `Eq [u]) lhsType lhs rhs, mkApp2 (mkConst `Eq.refl [u]) lhsType lhs) else pure (mkApp4 (mkConst `HEq [u]) lhsType lhs rhsType rhs, mkApp2 (mkConst `HEq.refl [u]) lhsType lhs) private partial def withNewEqs {α} (targets targetsNew : Array Expr) (k : Array Expr → Array Expr → MetaM α) : MetaM α := let rec loop (i : Nat) (newEqs : Array Expr) (newRefls : Array Expr) := do if h : i < targets.size then let (newEqType, newRefl) ← mkEqAndProof targets[i] targetsNew[i] withLocalDeclD `h newEqType fun newEq => do loop (i+1) (newEqs.push newEq) (newRefls.push newRefl) else k newEqs newRefls loop 0 #[] #[] def generalizeTargets (mvarId : MVarId) (motiveType : Expr) (targets : Array Expr) : MetaM MVarId := withMVarContext mvarId do checkNotAssigned mvarId `generalizeTargets let (typeNew, eqRefls) ← forallTelescopeReducing motiveType fun targetsNew _ => do unless targetsNew.size == targets.size do throwError "invalid number of targets #{targets.size}, motive expects #{targetsNew.size}" withNewEqs targets targetsNew fun eqs eqRefls => do let type ← getMVarType mvarId let typeNew ← mkForallFVars eqs type let typeNew ← mkForallFVars targetsNew typeNew pure (typeNew, eqRefls) let mvarNew ← mkFreshExprSyntheticOpaqueMVar typeNew (← getMVarTag mvarId) assignExprMVar mvarId (mkAppN (mkAppN mvarNew targets) eqRefls) pure mvarNew.mvarId! structure GeneralizeIndicesSubgoal where mvarId : MVarId indicesFVarIds : Array FVarId fvarId : FVarId numEqs : Nat /-- Similar to `generalizeTargets` but customized for the `casesOn` motive. Given a metavariable `mvarId` representing the ``` Ctx, h : I A j, D |- T ``` where `fvarId` is `h`s id, and the type `I A j` is an inductive datatype where `A` are parameters, and `j` the indices. Generate the goal ``` Ctx, h : I A j, D, j' : J, h' : I A j' |- j == j' -> h == h' -> T ``` Remark: `(j == j' -> h == h')` is a "telescopic" equality. Remark: `j` is sequence of terms, and `j'` a sequence of free variables. The result contains the fields - `mvarId`: the new goal - `indicesFVarIds`: `j'` ids - `fvarId`: `h'` id - `numEqs`: number of equations in the target -/ def generalizeIndices (mvarId : MVarId) (fvarId : FVarId) : MetaM GeneralizeIndicesSubgoal := withMVarContext mvarId do let lctx ← getLCtx let localInsts ← getLocalInstances checkNotAssigned mvarId `generalizeIndices let fvarDecl ← getLocalDecl fvarId let type ← whnf fvarDecl.type type.withApp fun f args => matchConstInduct f (fun _ => throwTacticEx `generalizeIndices mvarId "inductive type expected") fun val _ => do unless val.numIndices > 0 do throwTacticEx `generalizeIndices mvarId "indexed inductive type expected" unless args.size == val.numIndices + val.numParams do throwTacticEx `generalizeIndices mvarId "ill-formed inductive datatype" let indices := args.extract (args.size - val.numIndices) args.size let IA := mkAppN f (args.extract 0 val.numParams) -- `I A` let IAType ← inferType IA forallTelescopeReducing IAType fun newIndices _ => do let newType := mkAppN IA newIndices withLocalDeclD fvarDecl.userName newType fun h' => withNewEqs indices newIndices fun newEqs newRefls => do let (newEqType, newRefl) ← mkEqAndProof fvarDecl.toExpr h' let newRefls := newRefls.push newRefl withLocalDeclD `h newEqType fun newEq => do let newEqs := newEqs.push newEq /- auxType `forall (j' : J) (h' : I A j'), j == j' -> h == h' -> target -/ let target ← getMVarType mvarId let tag ← getMVarTag mvarId let auxType ← mkForallFVars newEqs target let auxType ← mkForallFVars #[h'] auxType let auxType ← mkForallFVars newIndices auxType let newMVar ← mkFreshExprMVarAt lctx localInsts auxType MetavarKind.syntheticOpaque tag /- assign mvarId := newMVar indices h refls -/ assignExprMVar mvarId (mkAppN (mkApp (mkAppN newMVar indices) fvarDecl.toExpr) newRefls) let (indicesFVarIds, newMVarId) ← introNP newMVar.mvarId! newIndices.size let (fvarId, newMVarId) ← intro1P newMVarId pure { mvarId := newMVarId, indicesFVarIds := indicesFVarIds, fvarId := fvarId, numEqs := newEqs.size } structure CasesSubgoal extends InductionSubgoal where ctorName : Name namespace Cases structure Context where inductiveVal : InductiveVal casesOnVal : DefinitionVal nminors : Nat := inductiveVal.ctors.length majorDecl : LocalDecl majorTypeFn : Expr majorTypeArgs : Array Expr majorTypeIndices : Array Expr := majorTypeArgs.extract (majorTypeArgs.size - inductiveVal.numIndices) majorTypeArgs.size private def mkCasesContext? (majorFVarId : FVarId) : MetaM (Option Context) := do let env ← getEnv if !env.contains `Eq || !env.contains `HEq then pure none else let majorDecl ← getLocalDecl majorFVarId let majorType ← whnf majorDecl.type majorType.withApp fun f args => matchConstInduct f (fun _ => pure none) fun ival _ => if args.size != ival.numIndices + ival.numParams then pure none else match env.find? (Name.mkStr ival.name "casesOn") with | ConstantInfo.defnInfo cval => pure $ some { inductiveVal := ival, casesOnVal := cval, majorDecl := majorDecl, majorTypeFn := f, majorTypeArgs := args } | _ => pure none /- We say the major premise has independent indices IF 1- its type is *not* an indexed inductive family, OR 2- its type is an indexed inductive family, but all indices are distinct free variables, and all local declarations different from the major and its indices do not depend on the indices. -/ private def hasIndepIndices (ctx : Context) : MetaM Bool := do if ctx.majorTypeIndices.isEmpty then pure true else if ctx.majorTypeIndices.any $ fun idx => !idx.isFVar then /- One of the indices is not a free variable. -/ pure false else if ctx.majorTypeIndices.size.any fun i => i.any fun j => ctx.majorTypeIndices[i] == ctx.majorTypeIndices[j] then /- An index ocurrs more than once -/ pure false else let lctx ← getLCtx let mctx ← getMCtx pure $ lctx.all fun decl => decl.fvarId == ctx.majorDecl.fvarId || -- decl is the major ctx.majorTypeIndices.any (fun index => decl.fvarId == index.fvarId!) || -- decl is one of the indices mctx.findLocalDeclDependsOn decl (fun fvarId => ctx.majorTypeIndices.all $ fun idx => idx.fvarId! != fvarId) -- or does not depend on any index private def elimAuxIndices (s₁ : GeneralizeIndicesSubgoal) (s₂ : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := let indicesFVarIds := s₁.indicesFVarIds s₂.mapM fun s => do indicesFVarIds.foldlM (init := s) fun s indexFVarId => match s.subst.get indexFVarId with | Expr.fvar indexFVarId' _ => (do let mvarId ← clear s.mvarId indexFVarId'; pure { s with mvarId := mvarId, subst := s.subst.erase indexFVarId }) <|> (pure s) | _ => pure s /- Convert `s` into an array of `CasesSubgoal`, by attaching the corresponding constructor name, and adding the substitution `majorFVarId -> ctor_i us params fields` into each subgoal. -/ private def toCasesSubgoals (s : Array InductionSubgoal) (ctorNames : Array Name) (majorFVarId : FVarId) (us : List Level) (params : Array Expr) : Array CasesSubgoal := s.mapIdx fun i s => let ctorName := ctorNames[i] let ctorApp := mkAppN (mkAppN (mkConst ctorName us) params) s.fields let s := { s with subst := s.subst.insert majorFVarId ctorApp } { ctorName := ctorName, toInductionSubgoal := s } /- Convert heterogeneous equality into a homegeneous one -/ private def heqToEq (mvarId : MVarId) (eqDecl : LocalDecl) : MetaM MVarId := do /- Convert heterogeneous equality into a homegeneous one -/ let prf ← mkEqOfHEq (mkFVar eqDecl.fvarId) let aEqb ← whnf (← inferType prf) let mvarId ← assert mvarId eqDecl.userName aEqb prf clear mvarId eqDecl.fvarId partial def unifyEqs (numEqs : Nat) (mvarId : MVarId) (subst : FVarSubst) (caseName? : Option Name := none): MetaM (Option (MVarId × FVarSubst)) := do if numEqs == 0 then pure (some (mvarId, subst)) else let (eqFVarId, mvarId) ← intro1 mvarId withMVarContext mvarId do let eqDecl ← getLocalDecl eqFVarId if eqDecl.type.isHEq then let mvarId ← heqToEq mvarId eqDecl unifyEqs numEqs mvarId subst caseName? else match eqDecl.type.eq? with | none => throwError "equality expected{indentExpr eqDecl.type}" | some (α, a, b) => /- Remark: we do not check `isDefeq` here because we would fail to substitute equalities such as `x = t` and `t = x` when `x` and `t` are proofs (proof irrelanvance). -/ /- Remark: we use `let rec` here because otherwise the compiler would generate an insane amount of code. We can remove the `rec` after we fix the eagerly inlining issue in the compiler. -/ let rec substEq (symm : Bool) := do /- TODO: support for acyclicity (e.g., `xs ≠ x :: xs`) -/ /- Remark: `substCore` fails if the equation is of the form `x = x` -/ if let some (substNew, mvarId) ← observing? (substCore mvarId eqFVarId symm subst) then unifyEqs (numEqs - 1) mvarId substNew caseName? else if (← isDefEq a b) then /- Skip equality -/ unifyEqs (numEqs - 1) (← clear mvarId eqFVarId) subst caseName? else throwError "dependent elimination failed, failed to solve equation{indentExpr eqDecl.type}" let rec injection (a b : Expr) := do let env ← getEnv if a.isConstructorApp env && b.isConstructorApp env then /- ctor_i ... = ctor_j ... -/ match (← injectionCore mvarId eqFVarId) with | InjectionResultCore.solved => pure none -- this alternative has been solved | InjectionResultCore.subgoal mvarId numEqsNew => unifyEqs (numEqs - 1 + numEqsNew) mvarId subst caseName? else let a' ← whnf a let b' ← whnf b if a' != a || b' != b then /- Reduced lhs/rhs of current equality -/ let prf := mkFVar eqFVarId let aEqb' ← mkEq a' b' let mvarId ← assert mvarId eqDecl.userName aEqb' prf let mvarId ← clear mvarId eqFVarId unifyEqs numEqs mvarId subst caseName? else match caseName? with | none => throwError "dependent elimination failed, failed to solve equation{indentExpr eqDecl.type}" | some caseName => throwError "dependent elimination failed, failed to solve equation{indentExpr eqDecl.type}\nat case {mkConst caseName}" let a ← instantiateMVars a let b ← instantiateMVars b match a, b with | Expr.fvar aFVarId _, Expr.fvar bFVarId _ => /- x = y -/ let aDecl ← getLocalDecl aFVarId let bDecl ← getLocalDecl bFVarId substEq (aDecl.index < bDecl.index) | Expr.fvar .., _ => /- x = t -/ substEq (symm := false) | _, Expr.fvar .. => /- t = x -/ substEq (symm := true) | a, b => if (← isDefEq a b) then /- Skip equality -/ unifyEqs (numEqs - 1) (← clear mvarId eqFVarId) subst caseName? else injection a b private def unifyCasesEqs (numEqs : Nat) (subgoals : Array CasesSubgoal) : MetaM (Array CasesSubgoal) := subgoals.foldlM (init := #[]) fun subgoals s => do match (← unifyEqs numEqs s.mvarId s.subst s.ctorName) with | none => pure subgoals | some (mvarId, subst) => pure $ subgoals.push { s with mvarId := mvarId, subst := subst, fields := s.fields.map (subst.apply ·) } private def inductionCasesOn (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames) (ctx : Context) : MetaM (Array CasesSubgoal) := do withMVarContext mvarId do let majorType ← inferType (mkFVar majorFVarId) let (us, params) ← getInductiveUniverseAndParams majorType let casesOn := mkCasesOnName ctx.inductiveVal.name let ctors := ctx.inductiveVal.ctors.toArray let s ← induction mvarId majorFVarId casesOn givenNames return toCasesSubgoals s ctors majorFVarId us params def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames := #[]) : MetaM (Array CasesSubgoal) := withMVarContext mvarId do checkNotAssigned mvarId `cases let context? ← mkCasesContext? majorFVarId match context? with | none => throwTacticEx `cases mvarId "not applicable to the given hypothesis" | some ctx => /- Remark: if caller does not need a `FVarSubst` (variable substitution), and `hasIndepIndices ctx` is true, then we can also use the simple case. This is a minor optimization, and we currently do not even allow callers to specify whether they want the `FVarSubst` or not. -/ if ctx.inductiveVal.numIndices == 0 then -- Simple case inductionCasesOn mvarId majorFVarId givenNames ctx else let s₁ ← generalizeIndices mvarId majorFVarId trace[Meta.Tactic.cases] "after generalizeIndices\n{MessageData.ofGoal s₁.mvarId}" let s₂ ← inductionCasesOn s₁.mvarId s₁.fvarId givenNames ctx let s₂ ← elimAuxIndices s₁ s₂ unifyCasesEqs s₁.numEqs s₂ end Cases def cases (mvarId : MVarId) (majorFVarId : FVarId) (givenNames : Array AltVarNames := #[]) : MetaM (Array CasesSubgoal) := Cases.cases mvarId majorFVarId givenNames def casesRec (mvarId : MVarId) (p : LocalDecl → MetaM Bool) : MetaM (List MVarId) := saturate mvarId fun mvarId => withMVarContext mvarId do for localDecl in (← getLCtx) do if (← p localDecl) then let r? ← observing? do let r ← cases mvarId localDecl.fvarId return r.toList.map (·.mvarId) if r?.isSome then return r? return none def casesAnd (mvarId : MVarId) : MetaM MVarId := do let mvarIds ← casesRec mvarId fun localDecl => return (← instantiateMVars localDecl.type).isAppOfArity ``And 2 exactlyOne mvarIds def substEqs (mvarId : MVarId) : MetaM MVarId := do let mvarIds ← casesRec mvarId fun localDecl => do let type ← instantiateMVars localDecl.type return type.isEq || type.isHEq exactlyOne mvarIds structure ByCasesSubgoal where mvarId : MVarId fvarId : FVarId def byCases (mvarId : MVarId) (p : Expr) (hName : Name := `h) : MetaM (ByCasesSubgoal × ByCasesSubgoal) := do let mvarId ← assert mvarId `hByCases (mkOr p (mkNot p)) (mkEM p) let (fvarId, mvarId) ← intro1 mvarId let #[s₁, s₂] ← cases mvarId fvarId #[{ varNames := [hName] }, { varNames := [hName] }] | throwError "'byCases' tactic failed, unexpected number of subgoals" return ((← toByCasesSubgoal s₁), (← toByCasesSubgoal s₂)) where toByCasesSubgoal (s : CasesSubgoal) : MetaM ByCasesSubgoal := do let #[Expr.fvar fvarId ..] ← pure s.fields | throwError "'byCases' tactic failed, unexpected new hypothesis" return { mvarId := s.mvarId, fvarId } builtin_initialize registerTraceClass `Meta.Tactic.cases end Lean.Meta
e0c564b315f95f51d96bbc4a9a6ef5a3c019fecc
737dc4b96c97368cb66b925eeea3ab633ec3d702
/stage0/src/Lean/Elab/PatternVar.lean
8e576dedc69754ceae2cfadb30e34817d273f4b0
[ "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
13,843
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Match.MatchPatternAttr import Lean.Elab.Arg import Lean.Elab.MatchAltView namespace Lean.Elab.Term open Meta inductive PatternVar where | localVar (userName : Name) -- anonymous variables (`_`) are encoded using metavariables | anonymousVar (mvarId : MVarId) instance : ToString PatternVar := ⟨fun | PatternVar.localVar x => toString x | PatternVar.anonymousVar mvarId => s!"?m{mvarId}"⟩ /-- Create an auxiliary Syntax node wrapping a fresh metavariable id. We use this kind of Syntax for representing `_` occurring in patterns. The metavariables are created before we elaborate the patterns into `Expr`s. -/ private def mkMVarSyntax : TermElabM Syntax := do let mvarId ← mkFreshId return Syntax.node `MVarWithIdKind #[Syntax.node mvarId #[]] /-- Given a syntax node constructed using `mkMVarSyntax`, return its MVarId -/ def getMVarSyntaxMVarId (stx : Syntax) : MVarId := stx[0].getKind /- Patterns define new local variables. This module collect them and preprocess `_` occurring in patterns. Recall that an `_` may represent anonymous variables or inaccessible terms that are implied by typing constraints. Thus, we represent them with fresh named holes `?x`. After we elaborate the pattern, if the metavariable remains unassigned, we transform it into a regular pattern variable. Otherwise, it becomes an inaccessible term. Macros occurring in patterns are expanded before the `collectPatternVars` method is executed. The following kinds of Syntax are handled by this module - Constructor applications - Applications of functions tagged with the `[matchPattern]` attribute - Identifiers - Anonymous constructors - Structure instances - Inaccessible terms - Named patterns - Tuple literals - Type ascriptions - Literals: num, string and char -/ namespace CollectPatternVars structure State where found : NameSet := {} vars : Array PatternVar := #[] abbrev M := StateRefT State TermElabM private def throwCtorExpected {α} : M α := throwError "invalid pattern, constructor or constant marked with '[matchPattern]' expected" private def getNumExplicitCtorParams (ctorVal : ConstructorVal) : TermElabM Nat := forallBoundedTelescope ctorVal.type ctorVal.numParams fun ps _ => do let mut result := 0 for p in ps do let localDecl ← getLocalDecl p.fvarId! if localDecl.binderInfo.isExplicit then result := result+1 pure result private def throwInvalidPattern {α} : M α := throwError "invalid pattern" /- An application in a pattern can be 1- A constructor application The elaborator assumes fields are accessible and inductive parameters are not accessible. 2- A regular application `(f ...)` where `f` is tagged with `[matchPattern]`. The elaborator assumes implicit arguments are not accessible and explicit ones are accessible. -/ structure Context where funId : Syntax ctorVal? : Option ConstructorVal -- It is `some`, if constructor application explicit : Bool ellipsis : Bool paramDecls : Array (Name × BinderInfo) -- parameters names and binder information paramDeclIdx : Nat := 0 namedArgs : Array NamedArg args : List Arg newArgs : Array Syntax := #[] deriving Inhabited private def isDone (ctx : Context) : Bool := ctx.paramDeclIdx ≥ ctx.paramDecls.size private def finalize (ctx : Context) : M Syntax := do if ctx.namedArgs.isEmpty && ctx.args.isEmpty then let fStx ← `(@$(ctx.funId):ident) return Syntax.mkApp fStx ctx.newArgs else throwError "too many arguments" private def isNextArgAccessible (ctx : Context) : Bool := let i := ctx.paramDeclIdx match ctx.ctorVal? with | some ctorVal => i ≥ ctorVal.numParams -- For constructor applications only fields are accessible | none => if h : i < ctx.paramDecls.size then -- For `[matchPattern]` applications, only explicit parameters are accessible. let d := ctx.paramDecls.get ⟨i, h⟩ d.2.isExplicit else false private def getNextParam (ctx : Context) : (Name × BinderInfo) × Context := let i := ctx.paramDeclIdx let d := ctx.paramDecls[i] (d, { ctx with paramDeclIdx := ctx.paramDeclIdx + 1 }) private def processVar (idStx : Syntax) : M Syntax := do unless idStx.isIdent do throwErrorAt idStx "identifier expected" let id := idStx.getId unless id.eraseMacroScopes.isAtomic do throwError "invalid pattern variable, must be atomic" if (← get).found.contains id then throwError "invalid pattern, variable '{id}' occurred more than once" modify fun s => { s with vars := s.vars.push (PatternVar.localVar id), found := s.found.insert id } return idStx private def nameToPattern : Name → TermElabM Syntax | Name.anonymous => `(Name.anonymous) | Name.str p s _ => do let p ← nameToPattern p; `(Name.str $p $(quote s) _) | Name.num p n _ => do let p ← nameToPattern p; `(Name.num $p $(quote n) _) private def quotedNameToPattern (stx : Syntax) : TermElabM Syntax := match stx[0].isNameLit? with | some val => nameToPattern val | none => throwIllFormedSyntax private def doubleQuotedNameToPattern (stx : Syntax) : TermElabM Syntax := do nameToPattern (← resolveGlobalConstNoOverloadWithInfo stx[2]) partial def collect (stx : Syntax) : M Syntax := withRef stx <| withFreshMacroScope do let k := stx.getKind if k == identKind then processId stx else if k == ``Lean.Parser.Term.app then processCtorApp stx else if k == ``Lean.Parser.Term.anonymousCtor then let elems ← stx[1].getArgs.mapSepElemsM collect return stx.setArg 1 <| mkNullNode elems else if k == ``Lean.Parser.Term.structInst then /- ``` leading_parser "{" >> optional (atomic (termParser >> " with ")) >> manyIndent (group (structInstField >> optional ", ")) >> optional ".." >> optional (" : " >> termParser) >> " }" ``` -/ let withMod := stx[1] unless withMod.isNone do throwErrorAt withMod "invalid struct instance pattern, 'with' is not allowed in patterns" let fields ← stx[2].getArgs.mapM fun p => do -- p is of the form (group (structInstField >> optional ", ")) let field := p[0] -- leading_parser structInstLVal >> " := " >> termParser let newVal ← collect field[2] let field := field.setArg 2 newVal pure <| field.setArg 0 field return stx.setArg 2 <| mkNullNode fields else if k == ``Lean.Parser.Term.hole then let r ← mkMVarSyntax modify fun s => { s with vars := s.vars.push <| PatternVar.anonymousVar <| getMVarSyntaxMVarId r } return r else if k == ``Lean.Parser.Term.paren then let arg := stx[1] if arg.isNone then return stx -- `()` else let t := arg[0] let s := arg[1] if s.isNone || s[0].getKind == ``Lean.Parser.Term.typeAscription then -- Ignore `s`, since it empty or it is a type ascription let t ← collect t let arg := arg.setArg 0 t return stx.setArg 1 arg else return stx else if k == ``Lean.Parser.Term.explicitUniv then processCtor stx[0] else if k == ``Lean.Parser.Term.namedPattern then /- Recall that def namedPattern := check... >> trailing_parser "@" >> termParser -/ let id := stx[0] discard <| processVar id let pat := stx[2] let pat ← collect pat `(_root_.namedPattern $id $pat) else if k == ``Lean.Parser.Term.binop then let lhs ← collect stx[2] let rhs ← collect stx[3] return stx.setArg 2 lhs |>.setArg 3 rhs else if k == ``Lean.Parser.Term.inaccessible then return stx else if k == strLitKind then return stx else if k == numLitKind then return stx else if k == scientificLitKind then return stx else if k == charLitKind then return stx else if k == ``Lean.Parser.Term.quotedName then /- Quoted names have an elaboration function associated with them, and they will not be macro expanded. Note that macro expansion is not a good option since it produces a term using the smart constructors `Name.mkStr`, `Name.mkNum` instead of the constructors `Name.str` and `Name.num` -/ quotedNameToPattern stx else if k == ``Lean.Parser.Term.doubleQuotedName then /- Similar to previous case -/ doubleQuotedNameToPattern stx else if k == choiceKind then throwError "invalid pattern, notation is ambiguous" else throwInvalidPattern where processCtorApp (stx : Syntax) : M Syntax := do let (f, namedArgs, args, ellipsis) ← expandApp stx true processCtorAppCore f namedArgs args ellipsis processCtor (stx : Syntax) : M Syntax := do processCtorAppCore stx #[] #[] false /- Check whether `stx` is a pattern variable or constructor-like (i.e., constructor or constant tagged with `[matchPattern]` attribute) -/ processId (stx : Syntax) : M Syntax := do match (← resolveId? stx "pattern" (withInfo := true)) with | none => processVar stx | some f => match f with | Expr.const fName _ _ => match (← getEnv).find? fName with | some (ConstantInfo.ctorInfo _) => processCtor stx | some _ => if hasMatchPatternAttribute (← getEnv) fName then processCtor stx else processVar stx | none => throwCtorExpected | _ => processVar stx pushNewArg (accessible : Bool) (ctx : Context) (arg : Arg) : M Context := do match arg with | Arg.stx stx => let stx ← if accessible then collect stx else pure stx return { ctx with newArgs := ctx.newArgs.push stx } | _ => unreachable! processExplicitArg (accessible : Bool) (ctx : Context) : M Context := do match ctx.args with | [] => if ctx.ellipsis then pushNewArg accessible ctx (Arg.stx (← `(_))) else throwError "explicit parameter is missing, unused named arguments {ctx.namedArgs.map fun narg => narg.name}" | arg::args => pushNewArg accessible { ctx with args := args } arg processImplicitArg (accessible : Bool) (ctx : Context) : M Context := do if ctx.explicit then processExplicitArg accessible ctx else pushNewArg accessible ctx (Arg.stx (← `(_))) processCtorAppContext (ctx : Context) : M Syntax := do if isDone ctx then finalize ctx else let accessible := isNextArgAccessible ctx let (d, ctx) := getNextParam ctx match ctx.namedArgs.findIdx? fun namedArg => namedArg.name == d.1 with | some idx => let arg := ctx.namedArgs[idx] let ctx := { ctx with namedArgs := ctx.namedArgs.eraseIdx idx } let ctx ← pushNewArg accessible ctx arg.val processCtorAppContext ctx | none => let ctx ← match d.2 with | BinderInfo.implicit => processImplicitArg accessible ctx | BinderInfo.strictImplicit => processImplicitArg accessible ctx | BinderInfo.instImplicit => processImplicitArg accessible ctx | _ => processExplicitArg accessible ctx processCtorAppContext ctx processCtorAppCore (f : Syntax) (namedArgs : Array NamedArg) (args : Array Arg) (ellipsis : Bool) : M Syntax := do let args := args.toList let (fId, explicit) ← match f with | `($fId:ident) => pure (fId, false) | `(@$fId:ident) => pure (fId, true) | _ => throwError "identifier expected" let some (Expr.const fName _ _) ← resolveId? fId "pattern" (withInfo := true) | throwCtorExpected let fInfo ← getConstInfo fName let paramDecls ← forallTelescopeReducing fInfo.type fun xs _ => xs.mapM fun x => do let d ← getFVarLocalDecl x return (d.userName, d.binderInfo) match fInfo with | ConstantInfo.ctorInfo val => processCtorAppContext { funId := fId, explicit := explicit, ctorVal? := val, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } | _ => if hasMatchPatternAttribute (← getEnv) fName then processCtorAppContext { funId := fId, explicit := explicit, ctorVal? := none, paramDecls := paramDecls, namedArgs := namedArgs, args := args, ellipsis := ellipsis } else throwCtorExpected def main (alt : MatchAltView) : M MatchAltView := do let patterns ← alt.patterns.mapM fun p => do trace[Elab.match] "collecting variables at pattern: {p}" collect p return { alt with patterns := patterns } end CollectPatternVars def collectPatternVars (alt : MatchAltView) : TermElabM (Array PatternVar × MatchAltView) := do let (alt, s) ← (CollectPatternVars.main alt).run {} return (s.vars, alt) /- Return the pattern variables in the given pattern. Remark: this method is not used by the main `match` elaborator, but in the precheck hook and other macros (e.g., at `Do.lean`). -/ def getPatternVars (patternStx : Syntax) : TermElabM (Array PatternVar) := do let patternStx ← liftMacroM <| expandMacros patternStx let (_, s) ← (CollectPatternVars.collect patternStx).run {} return s.vars def getPatternsVars (patterns : Array Syntax) : TermElabM (Array PatternVar) := do let collect : CollectPatternVars.M Unit := do for pattern in patterns do discard <| CollectPatternVars.collect (← liftMacroM <| expandMacros pattern) let (_, s) ← collect.run {} return s.vars def getPatternVarNames (pvars : Array PatternVar) : Array Name := pvars.filterMap fun | PatternVar.localVar x => some x | _ => none end Lean.Elab.Term
3e9b3c2e8bbc4954bcd9bc899e3a35e50b789526
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/geometry/euclidean/inversion.lean
e16f28592db29207605e9ea52bed6d5ea1c02c6c
[ "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
5,387
lean
/- Copyright (c) 2022 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.inner_product_space.basic /-! # Inversion in an affine space In this file we define inversion in a sphere in an affine space. This map sends each point `x` to the point `y` such that `y -ᵥ c = (R / dist x c) ^ 2 • (x -ᵥ c)`, where `c` and `R` are the center and the radius the sphere. In many applications, it is convenient to assume that the inversions swaps the center and the point at infinity. In order to stay in the original affine space, we define the map so that it sends center to itself. Currently, we prove only a few basic lemmas needed to prove Ptolemy's inequality, see `euclidean_geometry.mul_dist_le_mul_dist_add_mul_dist`. -/ noncomputable theory open metric real function namespace euclidean_geometry variables {V P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] {a b c d x y z : P} {R : ℝ} include V /-- Inversion in a sphere in an affine space. This map sends each point `x` to the point `y` such that `y -ᵥ c = (R / dist x c) ^ 2 • (x -ᵥ c)`, where `c` and `R` are the center and the radius the sphere. -/ def inversion (c : P) (R : ℝ) (x : P) : P := (R / dist x c) ^ 2 • (x -ᵥ c) +ᵥ c lemma inversion_vsub_center (c : P) (R : ℝ) (x : P) : inversion c R x -ᵥ c = (R / dist x c) ^ 2 • (x -ᵥ c) := vadd_vsub _ _ @[simp] lemma inversion_self (c : P) (R : ℝ) : inversion c R c = c := by simp [inversion] @[simp] lemma inversion_dist_center (c x : P) : inversion c (dist x c) x = x := begin rcases eq_or_ne x c with rfl|hne, { apply inversion_self }, { rw [inversion, div_self, one_pow, one_smul, vsub_vadd], rwa [dist_ne_zero] } end lemma inversion_of_mem_sphere (h : x ∈ metric.sphere c R) : inversion c R x = x := h.out ▸ inversion_dist_center c x /-- Distance from the image of a point under inversion to the center. This formula accidentally works for `x = c`. -/ lemma dist_inversion_center (c x : P) (R : ℝ) : dist (inversion c R x) c = R ^ 2 / dist x c := begin rcases eq_or_ne x c with (rfl|hx), { simp }, have : dist x c ≠ 0, from dist_ne_zero.2 hx, field_simp [inversion, norm_smul, abs_div, ← dist_eq_norm_vsub, sq, mul_assoc] end /-- Distance from the center of an inversion to the image of a point under the inversion. This formula accidentally works for `x = c`. -/ lemma dist_center_inversion (c x : P) (R : ℝ) : dist c (inversion c R x) = R ^ 2 / dist c x := by rw [dist_comm c, dist_comm c, dist_inversion_center] @[simp] lemma inversion_inversion (c : P) {R : ℝ} (hR : R ≠ 0) (x : P) : inversion c R (inversion c R x) = x := begin rcases eq_or_ne x c with rfl|hne, { rw [inversion_self, inversion_self] }, { rw [inversion, dist_inversion_center, inversion_vsub_center, smul_smul, ← mul_pow, div_mul_div_comm, div_mul_cancel _ (dist_ne_zero.2 hne), ← sq, div_self, one_pow, one_smul, vsub_vadd], exact pow_ne_zero _ hR } end lemma inversion_involutive (c : P) {R : ℝ} (hR : R ≠ 0) : involutive (inversion c R) := inversion_inversion c hR lemma inversion_surjective (c : P) {R : ℝ} (hR : R ≠ 0) : surjective (inversion c R) := (inversion_involutive c hR).surjective lemma inversion_injective (c : P) {R : ℝ} (hR : R ≠ 0) : injective (inversion c R) := (inversion_involutive c hR).injective lemma inversion_bijective (c : P) {R : ℝ} (hR : R ≠ 0) : bijective (inversion c R) := (inversion_involutive c hR).bijective /-- Distance between the images of two points under an inversion. -/ lemma dist_inversion_inversion (hx : x ≠ c) (hy : y ≠ c) (R : ℝ) : dist (inversion c R x) (inversion c R y) = (R ^ 2 / (dist x c * dist y c)) * dist x y := begin dunfold inversion, simp_rw [dist_vadd_cancel_right, dist_eq_norm_vsub V _ c], simpa only [dist_vsub_cancel_right] using dist_div_norm_sq_smul (vsub_ne_zero.2 hx) (vsub_ne_zero.2 hy) R end /-- **Ptolemy's inequality**: in a quadrangle `ABCD`, `|AC| * |BD| ≤ |AB| * |CD| + |BC| * |AD|`. If `ABCD` is a convex cyclic polygon, then this inequality becomes an equality, see `euclidean_geometry.mul_dist_add_mul_dist_eq_mul_dist_of_cospherical`. -/ lemma mul_dist_le_mul_dist_add_mul_dist (a b c d : P) : dist a c * dist b d ≤ dist a b * dist c d + dist b c * dist a d := begin -- If one of the points `b`, `c`, `d` is equal to `a`, then the inequality is trivial. rcases eq_or_ne b a with rfl|hb, { rw [dist_self, zero_mul, zero_add] }, rcases eq_or_ne c a with rfl|hc, { rw [dist_self, zero_mul], apply_rules [add_nonneg, mul_nonneg, dist_nonneg] }, rcases eq_or_ne d a with rfl|hd, { rw [dist_self, mul_zero, add_zero, dist_comm d, dist_comm d, mul_comm] }, /- Otherwise, we apply the triangle inequality to `euclidean_geometry.inversion a 1 b`, `euclidean_geometry.inversion a 1 c`, and `euclidean_geometry.inversion a 1 d`. -/ have H := dist_triangle (inversion a 1 b) (inversion a 1 c) (inversion a 1 d), rw [dist_inversion_inversion hb hd, dist_inversion_inversion hb hc, dist_inversion_inversion hc hd, one_pow] at H, rw [← dist_pos] at hb hc hd, rw [← div_le_div_right (mul_pos hb (mul_pos hc hd))], convert H; { field_simp [hb.ne', hc.ne', hd.ne', dist_comm a], ring } end end euclidean_geometry
663cbbb720d4bd668569baaa3970b37d899531d9
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/order/category/LinOrd.lean
1c9d29bf5d82a8573968450952dbbd6951a6c8dd
[ "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,170
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import order.category.Lat /-! # Category of linear orders > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This defines `LinOrd`, the category of linear orders with monotone maps. -/ open category_theory universe u /-- The category of linear orders. -/ def LinOrd := bundled linear_order namespace LinOrd instance : bundled_hom.parent_projection @linear_order.to_partial_order := ⟨⟩ attribute [derive [large_category, concrete_category]] LinOrd instance : has_coe_to_sort LinOrd Type* := bundled.has_coe_to_sort /-- Construct a bundled `LinOrd` from the underlying type and typeclass. -/ def of (α : Type*) [linear_order α] : LinOrd := bundled.of α @[simp] lemma coe_of (α : Type*) [linear_order α] : ↥(of α) = α := rfl instance : inhabited LinOrd := ⟨of punit⟩ instance (α : LinOrd) : linear_order α := α.str instance has_forget_to_Lat : has_forget₂ LinOrd Lat := { forget₂ := { obj := λ X, Lat.of X, map := λ X Y f, (order_hom_class.to_lattice_hom X Y f : lattice_hom X Y) } } /-- Constructs an equivalence between linear orders from an order isomorphism between them. -/ @[simps] def iso.mk {α β : LinOrd.{u}} (e : α ≃o β) : α ≅ β := { hom := e, inv := e.symm, hom_inv_id' := by { ext, exact e.symm_apply_apply x }, inv_hom_id' := by { ext, exact e.apply_symm_apply x } } /-- `order_dual` as a functor. -/ @[simps] def dual : LinOrd ⥤ LinOrd := { obj := λ X, of Xᵒᵈ, map := λ X Y, order_hom.dual } /-- The equivalence between `LinOrd` and itself induced by `order_dual` both ways. -/ @[simps functor inverse] def dual_equiv : LinOrd ≌ LinOrd := equivalence.mk dual dual (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) (nat_iso.of_components (λ X, iso.mk $ order_iso.dual_dual X) $ λ X Y f, rfl) end LinOrd lemma LinOrd_dual_comp_forget_to_Lat : LinOrd.dual ⋙ forget₂ LinOrd Lat = forget₂ LinOrd Lat ⋙ Lat.dual := rfl
ce5fdf8f34e5ce0bf2f3338227f3cec47e07dae8
b147e1312077cdcfea8e6756207b3fa538982e12
/data/option.lean
fdd667fd357bb2c898f582635119d15ec757120f
[ "Apache-2.0" ]
permissive
SzJS/mathlib
07836ee708ca27cd18347e1e11ce7dd5afb3e926
23a5591fca0d43ee5d49d89f6f0ee07a24a6ca29
refs/heads/master
1,584,980,332,064
1,532,063,841,000
1,532,063,841,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,137
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import logic.basic data.bool init.data.option.instances tactic.interactive namespace option universe u variables {α β : Type u} instance has_mem : has_mem α (option α) := ⟨λ a b, b = some a⟩ @[simp] theorem mem_def {a : α} {b : option α} : a ∈ b ↔ b = some a := iff.rfl @[simp] theorem get_mem : ∀ {o : option α} (h : is_some o), option.get h ∈ o | (some a) _ := rfl theorem get_of_mem {a : α} : ∀ {o : option α} (h : is_some o), a ∈ o → option.get h = a | _ _ rfl := rfl theorem mem_unique {o : option α} {a b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b := option.some.inj $ ha.symm.trans hb theorem some_inj {a b : α} : some a = some b ↔ a = b := by simp theorem ext : ∀ {o₁ o₂ : option α}, (∀ a, a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂ | none none H := rfl | (some a) o H := ((H _).1 rfl).symm | o (some b) H := (H _).2 rfl theorem eq_none_iff_forall_not_mem {o : option α} : o = none ↔ (∀ a, a ∉ o) := ⟨λ e a h, by rw e at h; cases h, λ h, ext $ by simpa⟩ @[simp] theorem none_bind (f : α → option β) : none >>= f = none := rfl @[simp] theorem some_bind (a : α) (f : α → option β) : some a >>= f = f a := rfl @[simp] theorem none_bind' (f : α → option β) : none.bind f = none := rfl @[simp] theorem some_bind' (a : α) (f : α → option β) : (some a).bind f = f a := rfl @[simp] theorem bind_some : ∀ x : option α, x >>= some = x := @bind_pure α option _ _ @[simp] theorem bind_eq_some {x : option α} {f : α → option β} {b : β} : x >>= f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_some' {x : option α} {f : α → option β} {b : β} : x.bind f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem map_none {f : α → β} : f <$> none = none := rfl @[simp] theorem map_some {a : α} {f : α → β} : f <$> some a = some (f a) := rfl @[simp] theorem map_none' {f : α → β} : option.map f none = none := rfl @[simp] theorem map_some' {a : α} {f : α → β} : option.map f (some a) = some (f a) := rfl @[simp] theorem map_eq_some {x : option α} {f : α → β} {b : β} : f <$> x = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_eq_some' {x : option α} {f : α → β} {b : β} : x.map f = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_id' : option.map (@id α) = id := map_id @[simp] theorem seq_some {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl @[simp] theorem orelse_some' (a : α) (x : option α) : (some a).orelse x = some a := rfl @[simp] theorem orelse_some (a : α) (x : option α) : (some a <|> x) = some a := rfl @[simp] theorem orelse_none' (x : option α) : none.orelse x = x := by cases x; refl @[simp] theorem orelse_none (x : option α) : (none <|> x) = x := orelse_none' x @[simp] theorem is_some_none : @is_some α none = ff := rfl @[simp] theorem is_some_some {a : α} : is_some (some a) = tt := rfl theorem is_some_iff_exists {x : option α} : is_some x ↔ ∃ a, x = some a := by cases x; simp [is_some]; exact ⟨_, rfl⟩ @[simp] theorem is_none_none : @is_none α none = tt := rfl @[simp] theorem is_none_some {a : α} : is_none (some a) = ff := rfl theorem is_none_iff_eq_none {o : option α} : o.is_none ↔ o = none := ⟨option.eq_none_of_is_none, λ e, e.symm ▸ rfl⟩ instance decidable_eq_none {o : option α} : decidable (o = none) := decidable_of_bool _ is_none_iff_eq_none instance decidable_forall_mem {p : α → Prop} [decidable_pred p] : ∀ o : option α, decidable (∀ a ∈ o, p a) | none := is_true (by simp) | (some a) := decidable_of_iff (p a) (by simp) instance decidable_exists_mem {p : α → Prop} [decidable_pred p] : ∀ o : option α, decidable (∃ a ∈ o, p a) | none := is_false (by simp) | (some a) := decidable_of_iff (p a) (by simp) /-- inhabited `get` function. Returns `a` if the input is `some a`, otherwise returns `default`. -/ @[reducible] def iget [inhabited α] : option α → α | (some x) := x | none := default α @[simp] theorem iget_some [inhabited α] {a : α} : (some a).iget = a := rfl theorem iget_mem [inhabited α] : ∀ {o : option α}, is_some o → o.iget ∈ o | (some a) _ := rfl theorem iget_of_mem [inhabited α] {a : α} : ∀ {o : option α}, a ∈ o → o.iget = a | _ rfl := rfl @[simp] theorem guard_eq_some' {p : Prop} [decidable p] : ∀ u, guard p = some u ↔ p | () := by by_cases p; simp [guard, h, pure]; intro; contradiction /-- `guard p a` returns `some a` if `p a` holds, otherwise `none`. -/ def guard (p : α → Prop) [decidable_pred p] (a : α) : option α := if p a then some a else none /-- `filter p o` returns `some a` if `o` is `some a` and `p a` holds, otherwise `none`. -/ def filter (p : α → Prop) [decidable_pred p] (o : option α) : option α := o.bind (guard p) @[simp] theorem guard_eq_some {p : α → Prop} [decidable_pred p] {a b : α} : guard p a = some b ↔ a = b ∧ p a := by by_cases p a; simp [option.guard, h]; intro; contradiction def to_list : option α → list α | none := [] | (some a) := [a] @[simp] theorem mem_to_list {a : α} {o : option α} : a ∈ to_list o ↔ a ∈ o := by cases o; simp [to_list, eq_comm] def lift_or_get (f : α → α → α) : option α → option α → option α | none none := none | (some a) none := some a -- get a | none (some b) := some b -- get b | (some a) (some b) := some (f a b) -- lift f instance lift_or_get_comm (f : α → α → α) [h : is_commutative α f] : is_commutative (option α) (lift_or_get f) := ⟨λ a b, by cases a; cases b; simp [lift_or_get, h.comm]⟩ instance lift_or_get_assoc (f : α → α → α) [h : is_associative α f] : is_associative (option α) (lift_or_get f) := ⟨λ a b c, by cases a; cases b; cases c; simp [lift_or_get, h.assoc]⟩ instance lift_or_get_idem (f : α → α → α) [h : is_idempotent α f] : is_idempotent (option α) (lift_or_get f) := ⟨λ a, by cases a; simp [lift_or_get, h.idempotent]⟩ instance lift_or_get_is_left_id (f : α → α → α) : is_left_id (option α) (lift_or_get f) none := ⟨λ a, by cases a; simp [lift_or_get]⟩ instance lift_or_get_is_right_id (f : α → α → α) : is_right_id (option α) (lift_or_get f) none := ⟨λ a, by cases a; simp [lift_or_get]⟩ theorem lift_or_get_choice {f : α → α → α} (h : ∀ a b, f a b = a ∨ f a b = b) : ∀ o₁ o₂, lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂ | none none := or.inl rfl | (some a) none := or.inl rfl | none (some b) := or.inr rfl | (some a) (some b) := by simpa [lift_or_get] using h a b section rel inductive rel {α : Type*} {β : Type*} (r : α → β → Prop) : option α → option β → Prop | some {a b} : r a b → rel (some a) (some b) | none {} : rel none none end rel end option
97c11179f710a534831bba65c5031f7bdb638733
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/algebra/module/linear_map.lean
d52ff8e5e1cefb86a977765f3cf4a3c55e1bc740
[ "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
28,040
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nathaniel Thomas, Jeremy Avigad, Johannes Hölzl, Mario Carneiro, Anne Baanen, Frédéric Dupuis, Heather Macbeth -/ import algebra.group.hom import algebra.module.basic import algebra.module.pi import algebra.group_action_hom import algebra.ring.comp_typeclasses /-! # (Semi)linear maps In this file we define * `linear_map σ M M₂`, `M →ₛₗ[σ] M₂` : a semilinear map between two `module`s. Here, `σ` is a `ring_hom` from `R` to `R₂` and an `f : M →ₛₗ[σ] M₂` satisfies `f (c • x) = (σ c) • (f x)`. We recover plain linear maps by choosing `σ` to be `ring_hom.id R`. This is denoted by `M →ₗ[R] M₂`. * `is_linear_map R f` : predicate saying that `f : M → M₂` is a linear map. (Note that this was not generalized to semilinear maps.) We then provide `linear_map` with the following instances: * `linear_map.add_comm_monoid` and `linear_map.add_comm_group`: the elementwise addition structures corresponding to addition in the codomain * `linear_map.distrib_mul_action` and `linear_map.module`: the elementwise scalar action structures corresponding to applying the action in the codomain. * `module.End.semiring` and `module.End.ring`: the (semi)ring of endomorphisms formed by taking the additive structure above with composition as multiplication. ## Implementation notes To ensure that composition works smoothly for semilinear maps, we use the typeclasses `ring_hom_comp_triple`, `ring_hom_inv_pair` and `ring_hom_surjective` from `algebra/ring/comp_typeclasses`. ## Notation * Throughout the file, we denote regular linear maps by `fₗ`, `gₗ`, etc, and semilinear maps by `f`, `g`, etc. ## TODO * Parts of this file have not yet been generalized to semilinear maps (i.e. `compatible_smul`) ## Tags linear map -/ open function open_locale big_operators universes u u' v w x y z variables {R : Type*} {R₁ : Type*} {R₂ : Type*} {R₃ : Type*} variables {k : Type*} {S : Type*} {T : Type*} variables {M : Type*} {M₁ : Type*} {M₂ : Type*} {M₃ : Type*} variables {N₁ : Type*} {N₂ : Type*} {N₃ : Type*} {ι : Type*} /-- A map `f` between modules over a semiring is linear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = c • f x`. The predicate `is_linear_map R f` asserts this property. A bundled version is available with `linear_map`, and should be favored over `is_linear_map` most of the time. -/ structure is_linear_map (R : Type u) {M : Type v} {M₂ : Type w} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M → M₂) : Prop := (map_add : ∀ x y, f (x + y) = f x + f y) (map_smul : ∀ (c : R) x, f (c • x) = c • f x) section set_option old_structure_cmd true /-- A map `f` between an `R`-module and an `S`-module over a ring homomorphism `σ : R →+* S` is semilinear if it satisfies the two properties `f (x + y) = f x + f y` and `f (c • x) = (σ c) • f x`. Elements of `linear_map σ M M₂` (available under the notation `M →ₛₗ[σ] M₂`) are bundled versions of such maps. For plain linear maps (i.e. for which `σ = ring_hom.id R`), the notation `M →ₗ[R] M₂` is available. An unbundled version of plain linear maps is available with the predicate `is_linear_map`, but it should be avoided most of the time. -/ structure linear_map {R : Type*} {S : Type*} [semiring R] [semiring S] (σ : R →+* S) (M : Type*) (M₂ : Type*) [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module S M₂] extends add_hom M M₂ := (map_smul' : ∀ (r : R) (x : M), to_fun (r • x) = (σ r) • to_fun x) end /-- The `add_hom` underlying a `linear_map`. -/ add_decl_doc linear_map.to_add_hom notation M ` →ₛₗ[`:25 σ:25 `] `:0 M₂:0 := linear_map σ M M₂ notation M ` →ₗ[`:25 R:25 `] `:0 M₂:0 := linear_map (ring_hom.id R) M M₂ namespace linear_map section add_comm_monoid variables [semiring R] [semiring S] section variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [add_comm_monoid N₁] [add_comm_monoid N₂] [add_comm_monoid N₃] variables [module R M] [module R M₂] [module S M₃] /-- The `distrib_mul_action_hom` underlying a `linear_map`. -/ def to_distrib_mul_action_hom (f : M →ₗ[R] M₂) : distrib_mul_action_hom R M M₂ := { map_zero' := zero_smul R (0 : M) ▸ zero_smul R (f.to_fun 0) ▸ f.map_smul' 0 0, ..f } instance {σ : R →+* S} : has_coe_to_fun (M →ₛₗ[σ] M₃) := ⟨_, to_fun⟩ initialize_simps_projections linear_map (to_fun → apply) @[simp] lemma coe_mk {σ : R →+* S} (f : M → M₃) (h₁ h₂) : ⇑(linear_map.mk f h₁ h₂ : M →ₛₗ[σ] M₃) = f := rfl /-- Identity map as a `linear_map` -/ def id : M →ₗ[R] M := { to_fun := id, ..distrib_mul_action_hom.id R } lemma id_apply (x : M) : @id R M _ _ _ x = x := rfl @[simp, norm_cast] lemma id_coe : ((linear_map.id : M →ₗ[R] M) : M → M) = _root_.id := by { ext x, refl } end section variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [add_comm_monoid N₁] [add_comm_monoid N₂] [add_comm_monoid N₃] variables [module R M] [module R M₂] [module S M₃] variables (σ : R →+* S) variables (fₗ gₗ : M →ₗ[R] M₂) (f g : M →ₛₗ[σ] M₃) @[simp] lemma to_fun_eq_coe : f.to_fun = ⇑f := rfl theorem is_linear : is_linear_map R fₗ := ⟨fₗ.map_add', fₗ.map_smul'⟩ variables {fₗ gₗ f g σ} theorem coe_injective : @injective (M →ₛₗ[σ] M₃) (M → M₃) coe_fn := by rintro ⟨f, _⟩ ⟨g, _⟩ ⟨h⟩; congr @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := coe_injective $ funext H protected lemma congr_arg : Π {x x' : M}, x = x' → f x = f x' | _ _ rfl := rfl /-- If two linear maps are equal, they are equal at each point. -/ protected lemma congr_fun (h : f = g) (x : M) : f x = g x := h ▸ rfl theorem ext_iff : f = g ↔ ∀ x, f x = g x := ⟨by { rintro rfl x, refl }, ext⟩ @[simp] lemma mk_coe (f : M →ₛₗ[σ] M₃) (h₁ h₂) : (linear_map.mk f h₁ h₂ : M →ₛₗ[σ] M₃) = f := ext $ λ _, rfl variables (fₗ gₗ f g) @[simp] lemma map_add (x y : M) : f (x + y) = f x + f y := f.map_add' x y @[simp] lemma map_smulₛₗ (c : R) (x : M) : f (c • x) = (σ c) • f x := f.map_smul' c x lemma map_smul (c : R) (x : M) : fₗ (c • x) = c • fₗ x := fₗ.map_smul' c x lemma map_smul_inv {σ' : S →+* R} [ring_hom_inv_pair σ σ'] (c : S) (x : M) : c • f x = f (σ' c • x) := by simp @[simp] lemma map_zero : f 0 = 0 := by { rw [←zero_smul R (0 : M), map_smulₛₗ], simp } @[simp] lemma map_eq_zero_iff (h : function.injective f) {x : M} : f x = 0 ↔ x = 0 := ⟨λ w, by { apply h, simp [w], }, λ w, by { subst w, simp, }⟩ variables (M M₂) /-- A typeclass for `has_scalar` structures which can be moved through a `linear_map`. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. -/ class compatible_smul (R S : Type*) [semiring S] [has_scalar R M] [module S M] [has_scalar R M₂] [module S M₂] := (map_smul : ∀ (fₗ : M →ₗ[S] M₂) (c : R) (x : M), fₗ (c • x) = c • fₗ x) variables {M M₂} @[priority 100] instance is_scalar_tower.compatible_smul {R S : Type*} [semiring S] [has_scalar R S] [has_scalar R M] [module S M] [is_scalar_tower R S M] [has_scalar R M₂] [module S M₂] [is_scalar_tower R S M₂] : compatible_smul M M₂ R S := ⟨λ fₗ c x, by rw [← smul_one_smul S c x, ← smul_one_smul S c (fₗ x), map_smul]⟩ @[simp, priority 900] lemma map_smul_of_tower {R S : Type*} [semiring S] [has_scalar R M] [module S M] [has_scalar R M₂] [module S M₂] [compatible_smul M M₂ R S] (fₗ : M →ₗ[S] M₂) (c : R) (x : M) : fₗ (c • x) = c • fₗ x := compatible_smul.map_smul fₗ c x /-- convert a linear map to an additive map -/ def to_add_monoid_hom : M →+ M₃ := { to_fun := f, map_zero' := f.map_zero, map_add' := f.map_add } @[simp] lemma to_add_monoid_hom_coe : ⇑f.to_add_monoid_hom = f := rfl section restrict_scalars variables (R) [module S M] [module S M₂] [compatible_smul M M₂ R S] /-- If `M` and `M₂` are both `R`-modules and `S`-modules and `R`-module structures are defined by an action of `R` on `S` (formally, we have two scalar towers), then any `S`-linear map from `M` to `M₂` is `R`-linear. See also `linear_map.map_smul_of_tower`. -/ @[simps] def restrict_scalars (fₗ : M →ₗ[S] M₂) : M →ₗ[R] M₂ := { to_fun := fₗ, map_add' := fₗ.map_add, map_smul' := fₗ.map_smul_of_tower } lemma restrict_scalars_injective : function.injective (restrict_scalars R : (M →ₗ[S] M₂) → (M →ₗ[R] M₂)) := λ fₗ gₗ h, ext (linear_map.congr_fun h : _) @[simp] lemma restrict_scalars_inj (fₗ gₗ : M →ₗ[S] M₂) : fₗ.restrict_scalars R = gₗ.restrict_scalars R ↔ fₗ = gₗ := (restrict_scalars_injective R).eq_iff end restrict_scalars variable {R} @[simp] lemma map_sum {ι} {t : finset ι} {g : ι → M} : f (∑ i in t, g i) = (∑ i in t, f (g i)) := f.to_add_monoid_hom.map_sum _ _ theorem to_add_monoid_hom_injective : function.injective (to_add_monoid_hom : (M →ₛₗ[σ] M₃) → (M →+ M₃)) := λ f g h, ext $ add_monoid_hom.congr_fun h /-- If two `σ`-linear maps from `R` are equal on `1`, then they are equal. -/ @[ext] theorem ext_ring {f g : R →ₛₗ[σ] M₃} (h : f 1 = g 1) : f = g := ext $ λ x, by rw [← mul_one x, ← smul_eq_mul, f.map_smulₛₗ, g.map_smulₛₗ, h] theorem ext_ring_iff {σ : R →+* R} {f g : R →ₛₗ[σ] M} : f = g ↔ f 1 = g 1 := ⟨λ h, h ▸ rfl, ext_ring⟩ end section variables [semiring R₁] [semiring R₂] [semiring R₃] variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃] variables {module_M₁ : module R₁ M₁} {module_M₂ : module R₂ M₂} {module_M₃ : module R₃ M₃} variables {σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R₁ →+* R₃} variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] variables (f : M₂ →ₛₗ[σ₂₃] M₃) (g : M₁ →ₛₗ[σ₁₂] M₂) include module_M₁ module_M₂ module_M₃ /-- Composition of two linear maps is a linear map -/ def comp : M₁ →ₛₗ[σ₁₃] M₃ := { to_fun := f ∘ g, map_add' := by simp only [map_add, forall_const, eq_self_iff_true, comp_app], map_smul' := λ r x, by rw [comp_app, map_smulₛₗ, map_smulₛₗ, ring_hom_comp_triple.comp_apply] } omit module_M₁ module_M₂ module_M₃ infixr ` ∘ₗ `:80 := @linear_map.comp _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ (ring_hom.id _) (ring_hom.id _) (ring_hom.id _) ring_hom_comp_triple.ids include σ₁₃ lemma comp_apply (x : M₁) : f.comp g x = f (g x) := rfl omit σ₁₃ include σ₁₃ @[simp, norm_cast] lemma coe_comp : (f.comp g : M₁ → M₃) = f ∘ g := rfl omit σ₁₃ @[simp] theorem comp_id : f.comp id = f := linear_map.ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := linear_map.ext $ λ x, rfl end variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₃] /-- If a function `g` is a left and right inverse of a linear map `f`, then `g` is linear itself. -/ def inverse [module R M] [module S M₂] {σ : R →+* S} {σ' : S →+* R} [ring_hom_inv_pair σ σ'] (f : M →ₛₗ[σ] M₂) (g : M₂ → M) (h₁ : left_inverse g f) (h₂ : right_inverse g f) : M₂ →ₛₗ[σ'] M := by dsimp [left_inverse, function.right_inverse] at h₁ h₂; exact { to_fun := g, map_add' := λ x y, by { rw [← h₁ (g (x + y)), ← h₁ (g x + g y)]; simp [h₂] }, map_smul' := λ a b, by { rw [← h₁ (g (a • b)), ← h₁ ((σ' a) • g b)], simp [h₂] } } end add_comm_monoid section add_comm_group variables [semiring R] [semiring S] [add_comm_group M] [add_comm_group M₂] variables {module_M : module R M} {module_M₂ : module S M₂} {σ : R →+* S} variables (f : M →ₛₗ[σ] M₂) @[simp] lemma map_neg (x : M) : f (- x) = - f x := f.to_add_monoid_hom.map_neg x @[simp] lemma map_sub (x y : M) : f (x - y) = f x - f y := f.to_add_monoid_hom.map_sub x y instance compatible_smul.int_module {S : Type*} [semiring S] [module S M] [module S M₂] : compatible_smul M M₂ ℤ S := ⟨λ fₗ c x, begin induction c using int.induction_on, case hz : { simp }, case hp : n ih { simp [add_smul, ih] }, case hn : n ih { simp [sub_smul, ih] } end⟩ instance compatible_smul.units {R S : Type*} [monoid R] [mul_action R M] [mul_action R M₂] [semiring S] [module S M] [module S M₂] [compatible_smul M M₂ R S] : compatible_smul M M₂ (units R) S := ⟨λ fₗ c x, (compatible_smul.map_smul fₗ (c : R) x : _)⟩ end add_comm_group end linear_map namespace module /-- `g : R →+* S` is `R`-linear when the module structure on `S` is `module.comp_hom S g` . -/ @[simps] def comp_hom.to_linear_map {R S : Type*} [semiring R] [semiring S] (g : R →+* S) : (by haveI := comp_hom S g; exact (R →ₗ[R] S)) := by exact { to_fun := (g : R → S), map_add' := g.map_add, map_smul' := g.map_mul } end module namespace distrib_mul_action_hom variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] /-- A `distrib_mul_action_hom` between two modules is a linear map. -/ def to_linear_map (fₗ : M →+[R] M₂) : M →ₗ[R] M₂ := { ..fₗ } instance : has_coe (M →+[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ @[simp] lemma to_linear_map_eq_coe (f : M →+[R] M₂) : f.to_linear_map = ↑f := rfl @[simp, norm_cast] lemma coe_to_linear_map (f : M →+[R] M₂) : ((f : M →ₗ[R] M₂) : M → M₂) = f := rfl lemma to_linear_map_injective {f g : M →+[R] M₂} (h : (f : M →ₗ[R] M₂) = (g : M →ₗ[R] M₂)) : f = g := by { ext m, exact linear_map.congr_fun h m, } end distrib_mul_action_hom namespace is_linear_map section add_comm_monoid variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R M₂] include R /-- Convert an `is_linear_map` predicate to a `linear_map` -/ def mk' (f : M → M₂) (H : is_linear_map R f) : M →ₗ[R] M₂ := { to_fun := f, map_add' := H.1, map_smul' := H.2 } @[simp] theorem mk'_apply {f : M → M₂} (H : is_linear_map R f) (x : M) : mk' f H x = f x := rfl lemma is_linear_map_smul {R M : Type*} [comm_semiring R] [add_comm_monoid M] [module R M] (c : R) : is_linear_map R (λ (z : M), c • z) := begin refine is_linear_map.mk (smul_add c) _, intros _ _, simp only [smul_smul, mul_comm] end lemma is_linear_map_smul' {R M : Type*} [semiring R] [add_comm_monoid M] [module R M] (a : M) : is_linear_map R (λ (c : R), c • a) := is_linear_map.mk (λ x y, add_smul x y a) (λ x y, mul_smul x y a) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_zero : f (0 : M) = (0 : M₂) := (lin.mk' f).map_zero end add_comm_monoid section add_comm_group variables [semiring R] [add_comm_group M] [add_comm_group M₂] variables [module R M] [module R M₂] include R lemma is_linear_map_neg : is_linear_map R (λ (z : M), -z) := is_linear_map.mk neg_add (λ x y, (smul_neg x y).symm) variables {f : M → M₂} (lin : is_linear_map R f) include M M₂ lin lemma map_neg (x : M) : f (- x) = - f x := (lin.mk' f).map_neg x lemma map_sub (x y) : f (x - y) = f x - f y := (lin.mk' f).map_sub x y end add_comm_group end is_linear_map /-- Linear endomorphisms of a module, with associated ring structure `module.End.semiring` and algebra structure `module.End.algebra`. -/ abbreviation module.End (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [module R M] := M →ₗ[R] M /-- Reinterpret an additive homomorphism as a `ℕ`-linear map. -/ def add_monoid_hom.to_nat_linear_map [add_comm_monoid M] [add_comm_monoid M₂] (f : M →+ M₂) : M →ₗ[ℕ] M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_nat_module_smul } lemma add_monoid_hom.to_nat_linear_map_injective [add_comm_monoid M] [add_comm_monoid M₂] : function.injective (@add_monoid_hom.to_nat_linear_map M M₂ _ _) := by { intros f g h, ext, exact linear_map.congr_fun h x } /-- Reinterpret an additive homomorphism as a `ℤ`-linear map. -/ def add_monoid_hom.to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : M →ₗ[ℤ] M₂ := { to_fun := f, map_add' := f.map_add, map_smul' := f.map_int_module_smul } lemma add_monoid_hom.to_int_linear_map_injective [add_comm_group M] [add_comm_group M₂] : function.injective (@add_monoid_hom.to_int_linear_map M M₂ _ _) := by { intros f g h, ext, exact linear_map.congr_fun h x } @[simp] lemma add_monoid_hom.coe_to_int_linear_map [add_comm_group M] [add_comm_group M₂] (f : M →+ M₂) : ⇑f.to_int_linear_map = f := rfl /-- Reinterpret an additive homomorphism as a `ℚ`-linear map. -/ def add_monoid_hom.to_rat_linear_map [add_comm_group M] [module ℚ M] [add_comm_group M₂] [module ℚ M₂] (f : M →+ M₂) : M →ₗ[ℚ] M₂ := { map_smul' := f.map_rat_module_smul, ..f } lemma add_monoid_hom.to_rat_linear_map_injective [add_comm_group M] [module ℚ M] [add_comm_group M₂] [module ℚ M₂] : function.injective (@add_monoid_hom.to_rat_linear_map M M₂ _ _ _ _) := by { intros f g h, ext, exact linear_map.congr_fun h x } @[simp] lemma add_monoid_hom.coe_to_rat_linear_map [add_comm_group M] [module ℚ M] [add_comm_group M₂] [module ℚ M₂] (f : M →+ M₂) : ⇑f.to_rat_linear_map = f := rfl namespace linear_map /-! ### Arithmetic on the codomain -/ section arithmetic variables [semiring R₁] [semiring R₂] [semiring R₃] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [add_comm_group N₁] [add_comm_group N₂] [add_comm_group N₃] variables [module R₁ M] [module R₂ M₂] [module R₃ M₃] variables [module R₁ N₁] [module R₂ N₂] [module R₃ N₃] variables {σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R₁ →+* R₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] /-- The constant 0 map is linear. -/ instance : has_zero (M →ₛₗ[σ₁₂] M₂) := ⟨{ to_fun := 0, map_add' := by simp, map_smul' := by simp }⟩ @[simp] lemma zero_apply (x : M) : (0 : M →ₛₗ[σ₁₂] M₂) x = 0 := rfl @[simp] theorem comp_zero (g : M₂ →ₛₗ[σ₂₃] M₃) : (g.comp (0 : M →ₛₗ[σ₁₂] M₂) : M →ₛₗ[σ₁₃] M₃) = 0 := ext $ assume c, by rw [comp_apply, zero_apply, zero_apply, g.map_zero] @[simp] theorem zero_comp (f : M →ₛₗ[σ₁₂] M₂) : ((0 : M₂ →ₛₗ[σ₂₃] M₃).comp f : M →ₛₗ[σ₁₃] M₃) = 0 := rfl instance : inhabited (M →ₛₗ[σ₁₂] M₂) := ⟨0⟩ @[simp] lemma default_def : default (M →ₛₗ[σ₁₂] M₂) = 0 := rfl /-- The sum of two linear maps is linear. -/ instance : has_add (M →ₛₗ[σ₁₂] M₂) := ⟨λ f g, { to_fun := f + g, map_add' := by simp [add_comm, add_left_comm], map_smul' := by simp [smul_add] }⟩ @[simp] lemma add_apply (f g : M →ₛₗ[σ₁₂] M₂) (x : M) : (f + g) x = f x + g x := rfl lemma add_comp (f : M →ₛₗ[σ₁₂] M₂) (g h : M₂ →ₛₗ[σ₂₃] M₃) : ((h + g).comp f : M →ₛₗ[σ₁₃] M₃) = h.comp f + g.comp f := rfl lemma comp_add (f g : M →ₛₗ[σ₁₂] M₂) (h : M₂ →ₛₗ[σ₂₃] M₃) : (h.comp (f + g) : M →ₛₗ[σ₁₃] M₃) = h.comp f + h.comp g := ext $ λ _, h.map_add _ _ /-- The type of linear maps is an additive monoid. -/ instance : add_comm_monoid (M →ₛₗ[σ₁₂] M₂) := { zero := 0, add := (+), add_assoc := λ f g h, linear_map.ext $ λ x, add_assoc _ _ _, zero_add := λ f, linear_map.ext $ λ x, zero_add _, add_zero := λ f, linear_map.ext $ λ x, add_zero _, add_comm := λ f g, linear_map.ext $ λ x, add_comm _ _, nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, begin rw [f.map_smulₛₗ], simp [smul_comm n (σ₁₂ c) (f x)], end }, nsmul_zero' := λ f, linear_map.ext $ λ x, add_comm_monoid.nsmul_zero' _, nsmul_succ' := λ n f, linear_map.ext $ λ x, add_comm_monoid.nsmul_succ' _ _ } /-- The negation of a linear map is linear. -/ instance : has_neg (M →ₛₗ[σ₁₂] N₂) := ⟨λ f, { to_fun := -f, map_add' := by simp [add_comm], map_smul' := by simp }⟩ @[simp] lemma neg_apply (f : M →ₛₗ[σ₁₂] N₂) (x : M) : (- f) x = - f x := rfl include σ₁₃ @[simp] lemma neg_comp (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₃] N₃) : (- g).comp f = - g.comp f := rfl @[simp] lemma comp_neg (f : M →ₛₗ[σ₁₂] N₂) (g : N₂ →ₛₗ[σ₂₃] N₃) : g.comp (- f) = - g.comp f := ext $ λ _, g.map_neg _ omit σ₁₃ /-- The negation of a linear map is linear. -/ instance : has_sub (M →ₛₗ[σ₁₂] N₂) := ⟨λ f g, { to_fun := f - g, map_add' := λ x y, by simp only [pi.sub_apply, map_add, add_sub_comm], map_smul' := λ r x, by simp [pi.sub_apply, map_smul, smul_sub] }⟩ @[simp] lemma sub_apply (f g : M →ₛₗ[σ₁₂] N₂) (x : M) : (f - g) x = f x - g x := rfl include σ₁₃ lemma sub_comp (f : M →ₛₗ[σ₁₂] M₂) (g h : M₂ →ₛₗ[σ₂₃] N₃) : (g - h).comp f = g.comp f - h.comp f := rfl lemma comp_sub (f g : M →ₛₗ[σ₁₂] N₂) (h : N₂ →ₛₗ[σ₂₃] N₃) : h.comp (g - f) = h.comp g - h.comp f := ext $ λ _, h.map_sub _ _ omit σ₁₃ /-- The type of linear maps is an additive group. -/ instance : add_comm_group (M →ₛₗ[σ₁₂] N₂) := { zero := 0, add := (+), neg := has_neg.neg, sub := has_sub.sub, sub_eq_add_neg := λ f g, linear_map.ext $ λ m, sub_eq_add_neg _ _, add_left_neg := λ f, linear_map.ext $ λ m, add_left_neg _, nsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smulₛₗ, smul_comm n (σ₁₂ c) (f x)] }, gsmul := λ n f, { to_fun := λ x, n • (f x), map_add' := λ x y, by rw [f.map_add, smul_add], map_smul' := λ c x, by rw [f.map_smulₛₗ, smul_comm n (σ₁₂ c) (f x)] }, gsmul_zero' := λ a, linear_map.ext $ λ m, zero_smul _ _, gsmul_succ' := λ n a, linear_map.ext $ λ m, add_comm_group.gsmul_succ' n _, gsmul_neg' := λ n a, linear_map.ext $ λ m, add_comm_group.gsmul_neg' n _, .. linear_map.add_comm_monoid } end arithmetic -- TODO: generalize this section to semilinear maps where possible section actions variables [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] section has_scalar variables [monoid S] [distrib_mul_action S M₂] [smul_comm_class R S M₂] variables [monoid T] [distrib_mul_action T M₂] [smul_comm_class R T M₂] instance : has_scalar S (M →ₗ[R] M₂) := ⟨λ a f, { to_fun := a • f, map_add' := λ x y, by simp only [pi.smul_apply, f.map_add, smul_add], map_smul' := λ c x, by simp [pi.smul_apply, f.map_smul, smul_comm c] }⟩ @[simp] lemma smul_apply (a : S) (f : M →ₗ[R] M₂) (x : M) : (a • f) x = a • f x := rfl instance [smul_comm_class S T M₂] : smul_comm_class S T (M →ₗ[R] M₂) := ⟨λ a b f, ext $ λ x, smul_comm _ _ _⟩ -- example application of this instance: if S -> T -> R are homomorphisms of commutative rings and -- M and M₂ are R-modules then the S-module and T-module structures on Hom_R(M,M₂) are compatible. instance [has_scalar S T] [is_scalar_tower S T M₂] : is_scalar_tower S T (M →ₗ[R] M₂) := { smul_assoc := λ _ _ _, ext $ λ _, smul_assoc _ _ _ } instance : distrib_mul_action S (M →ₗ[R] M₂) := { one_smul := λ f, ext $ λ _, one_smul _ _, mul_smul := λ c c' f, ext $ λ _, mul_smul _ _ _, smul_add := λ c f g, ext $ λ x, smul_add _ _ _, smul_zero := λ c, ext $ λ x, smul_zero _ } theorem smul_comp (a : S) (g : M₃ →ₗ[R] M₂) (f : M →ₗ[R] M₃) : (a • g).comp f = a • (g.comp f) := rfl theorem comp_smul [distrib_mul_action S M₃] [smul_comm_class R S M₃] [compatible_smul M₃ M₂ S R] (g : M₃ →ₗ[R] M₂) (a : S) (f : M →ₗ[R] M₃) : g.comp (a • f) = a • (g.comp f) := ext $ λ x, g.map_smul_of_tower _ _ end has_scalar section module variables [semiring S] [module S M₂] [smul_comm_class R S M₂] instance : module S (M →ₗ[R] M₂) := { add_smul := λ a b f, ext $ λ x, add_smul _ _ _, zero_smul := λ f, ext $ λ x, zero_smul _ _ } end module end actions /-! ### Monoid structure of endomorphisms Lemmas about `pow` such as `linear_map.pow_apply` appear in later files. -/ section endomorphisms variables [semiring R] [add_comm_monoid M] [add_comm_group N₁] [module R M] [module R N₁] instance : has_one (module.End R M) := ⟨linear_map.id⟩ instance : has_mul (module.End R M) := ⟨linear_map.comp⟩ lemma one_eq_id : (1 : module.End R M) = id := rfl lemma mul_eq_comp (f g : module.End R M) : f * g = f.comp g := rfl @[simp] lemma one_apply (x : M) : (1 : module.End R M) x = x := rfl @[simp] lemma mul_apply (f g : module.End R M) (x : M) : (f * g) x = f (g x) := rfl lemma coe_one : ⇑(1 : module.End R M) = _root_.id := rfl lemma coe_mul (f g : module.End R M) : ⇑(f * g) = f ∘ g := rfl instance _root_.module.End.monoid : monoid (module.End R M) := { mul := (*), one := (1 : M →ₗ[R] M), mul_assoc := λ f g h, linear_map.ext $ λ x, rfl, mul_one := comp_id, one_mul := id_comp } instance _root_.module.End.semiring : semiring (module.End R M) := { mul := (*), one := (1 : M →ₗ[R] M), zero := 0, add := (+), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, mul_zero := comp_zero, zero_mul := zero_comp, left_distrib := λ f g h, comp_add _ _ _, right_distrib := λ f g h, add_comp _ _ _, .. _root_.module.End.monoid, .. linear_map.add_comm_monoid } instance _root_.module.End.ring : ring (module.End R N₁) := { ..module.End.semiring, ..linear_map.add_comm_group } section variables [monoid S] [distrib_mul_action S M] [smul_comm_class R S M] instance _root_.module.End.is_scalar_tower : is_scalar_tower S (module.End R M) (module.End R M) := ⟨smul_comp⟩ instance _root_.module.End.smul_comm_class [has_scalar S R] [is_scalar_tower S R M] : smul_comm_class S (module.End R M) (module.End R M) := ⟨λ s _ _, (comp_smul _ s _).symm⟩ instance _root_.module.End.smul_comm_class' [has_scalar S R] [is_scalar_tower S R M] : smul_comm_class (module.End R M) S (module.End R M) := smul_comm_class.symm _ _ _ end /-! ### Action by a module endomorphism. -/ /-- The tautological action by `module.End R M` (aka `M →ₗ[R] M`) on `M`. This generalizes `function.End.apply_mul_action`. -/ instance apply_module : module (module.End R M) M := { smul := ($), smul_zero := linear_map.map_zero, smul_add := linear_map.map_add, add_smul := linear_map.add_apply, zero_smul := (linear_map.zero_apply : ∀ m, (0 : M →ₗ[R] M) m = 0), one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma smul_def (f : module.End R M) (a : M) : f • a = f a := rfl /-- `linear_map.apply_module` is faithful. -/ instance apply_has_faithful_scalar : has_faithful_scalar (module.End R M) M := ⟨λ _ _, linear_map.ext⟩ instance apply_smul_comm_class : smul_comm_class R (module.End R M) M := { smul_comm := λ r e m, (e.map_smul r m).symm } instance apply_smul_comm_class' : smul_comm_class (module.End R M) R M := { smul_comm := linear_map.map_smul } end endomorphisms end linear_map
389040cbf6a15818c4b60b17530e63c567700fa4
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/ideal/operations.lean
8a6daae4a1f42a82858003bbff87c5c6966ac360
[ "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
67,359
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.operations import algebra.algebra.tower import data.equiv.ring import data.nat.choose.sum import ring_theory.ideal.basic import ring_theory.non_zero_divisors /-! # More operations on modules and ideals -/ universes u v w x open_locale big_operators namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] instance has_scalar' : has_scalar (ideal R) (submodule R M) := ⟨λ I N, ⨆ r : I, N.map (r.1 • linear_map.id)⟩ /-- `N.annihilator` is the ideal of all elements `r : R` such that `r • N = 0`. -/ def annihilator (N : submodule R M) : ideal R := (linear_map.lsmul R N).ker /-- `N.colon P` is the ideal of all elements `r : R` such that `r • P ⊆ N`. -/ def colon (N P : submodule R M) : ideal R := annihilator (P.map N.mkq) variables {I J : ideal R} {N N₁ N₂ P P₁ P₂ : submodule R M} theorem mem_annihilator {r} : r ∈ N.annihilator ↔ ∀ n ∈ N, r • n = (0:M) := ⟨λ hr n hn, congr_arg subtype.val (linear_map.ext_iff.1 (linear_map.mem_ker.1 hr) ⟨n, hn⟩), λ h, linear_map.mem_ker.2 $ linear_map.ext $ λ n, subtype.eq $ h n.1 n.2⟩ theorem mem_annihilator' {r} : r ∈ N.annihilator ↔ N ≤ comap (r • linear_map.id) ⊥ := mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩ theorem annihilator_bot : (⊥ : submodule R M).annihilator = ⊤ := (ideal.eq_top_iff_one _).2 $ mem_annihilator'.2 bot_le theorem annihilator_eq_top_iff : N.annihilator = ⊤ ↔ N = ⊥ := ⟨λ H, eq_bot_iff.2 $ λ (n:M) hn, (mem_bot R).2 $ one_smul R n ▸ mem_annihilator.1 ((ideal.eq_top_iff_one _).1 H) n hn, λ H, H.symm ▸ annihilator_bot⟩ theorem annihilator_mono (h : N ≤ P) : P.annihilator ≤ N.annihilator := λ r hrp, mem_annihilator.2 $ λ n hn, mem_annihilator.1 hrp n $ h hn theorem annihilator_supr (ι : Sort w) (f : ι → submodule R M) : (annihilator ⨆ i, f i) = ⨅ i, annihilator (f i) := le_antisymm (le_infi $ λ i, annihilator_mono $ le_supr _ _) (λ r H, mem_annihilator'.2 $ supr_le $ λ i, have _ := (mem_infi _).1 H i, mem_annihilator'.1 this) theorem mem_colon {r} : r ∈ N.colon P ↔ ∀ p ∈ P, r • p ∈ N := mem_annihilator.trans ⟨λ H p hp, (quotient.mk_eq_zero N).1 (H (quotient.mk p) (mem_map_of_mem hp)), λ H m ⟨p, hp, hpm⟩, hpm ▸ (N.mkq).map_smul r p ▸ (quotient.mk_eq_zero N).2 $ H p hp⟩ theorem mem_colon' {r} : r ∈ N.colon P ↔ P ≤ comap (r • linear_map.id) N := mem_colon theorem colon_mono (hn : N₁ ≤ N₂) (hp : P₁ ≤ P₂) : N₁.colon P₂ ≤ N₂.colon P₁ := λ r hrnp, mem_colon.2 $ λ p₁ hp₁, hn $ mem_colon.1 hrnp p₁ $ hp hp₁ theorem infi_colon_supr (ι₁ : Sort w) (f : ι₁ → submodule R M) (ι₂ : Sort x) (g : ι₂ → submodule R M) : (⨅ i, f i).colon (⨆ j, g j) = ⨅ i j, (f i).colon (g j) := le_antisymm (le_infi $ λ i, le_infi $ λ j, colon_mono (infi_le _ _) (le_supr _ _)) (λ r H, mem_colon'.2 $ supr_le $ λ j, map_le_iff_le_comap.1 $ le_infi $ λ i, map_le_iff_le_comap.2 $ mem_colon'.1 $ have _ := ((mem_infi _).1 H i), have _ := ((mem_infi _).1 this j), this) theorem smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N := (le_supr _ ⟨r, hr⟩ : _ ≤ I • N) ⟨n, hn, rfl⟩ theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P := ⟨λ H r hr n hn, H $ smul_mem_smul hr hn, λ H, supr_le $ λ r, map_le_iff_le_comap.2 $ λ n hn, H r.1 r.2 n hn⟩ @[elab_as_eliminator] theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N) (Hb : ∀ (r ∈ I) (n ∈ N), p (r • n)) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (c:R) n, p n → p (c • n)) : p x := (@smul_le _ _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hb H theorem mem_smul_span_singleton {I : ideal R} {m : M} {x : M} : x ∈ I • span R ({m} : set M) ↔ ∃ y ∈ I, y • m = x := ⟨λ hx, smul_induction_on hx (λ r hri n hnm, let ⟨s, hs⟩ := mem_span_singleton.1 hnm in ⟨r * s, I.mul_mem_right _ hri, hs ▸ mul_smul r s m⟩) ⟨0, I.zero_mem, by rw [zero_smul]⟩ (λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩, ⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩) (λ c r ⟨y, hyi, hy⟩, ⟨c * y, I.mul_mem_left _ hyi, by rw [mul_smul, hy]⟩), λ ⟨y, hyi, hy⟩, hy ▸ smul_mem_smul hyi (subset_span $ set.mem_singleton m)⟩ theorem smul_le_right : I • N ≤ N := smul_le.2 $ λ r hr n, N.smul_mem r theorem smul_mono (hij : I ≤ J) (hnp : N ≤ P) : I • N ≤ J • P := smul_le.2 $ λ r hr n hn, smul_mem_smul (hij hr) (hnp hn) theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N := smul_mono h (le_refl N) theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P := smul_mono (le_refl I) h variables (I J N P) @[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hri s hsb, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hsb).symm ▸ smul_zero r @[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hrb s hsi, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hrb).symm ▸ zero_smul _ s @[simp] theorem top_smul : (⊤ : ideal R) • N = N := le_antisymm smul_le_right $ λ r hri, one_smul R r ▸ smul_mem_smul mem_top hri theorem smul_sup : I • (N ⊔ P) = I • N ⊔ I • P := le_antisymm (smul_le.2 $ λ r hri m hmnp, let ⟨n, hn, p, hp, hnpm⟩ := mem_sup.1 hmnp in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hri hp, hnpm ▸ (smul_add _ _ _).symm⟩) (sup_le (smul_mono_right le_sup_left) (smul_mono_right le_sup_right)) theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N := le_antisymm (smul_le.2 $ λ r hrij n hn, let ⟨ri, hri, rj, hrj, hrijr⟩ := mem_sup.1 hrij in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hrj hn, hrijr ▸ (add_smul _ _ _).symm⟩) (sup_le (smul_mono_left le_sup_left) (smul_mono_left le_sup_right)) protected theorem smul_assoc : (I • J) • N = I • (J • N) := le_antisymm (smul_le.2 $ λ rs hrsij t htn, smul_induction_on hrsij (λ r hr s hs, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ smul_mem_smul hr (smul_mem_smul hs htn)) ((zero_smul R t).symm ▸ submodule.zero_mem _) (λ x y, (add_smul x y t).symm ▸ submodule.add_mem _) (λ r s h, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ submodule.smul_mem _ _ h)) (smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • linear_map.id) ((I • J) • N), from this hsn, smul_le.2 $ λ s hs n hn, show r • (s • n) ∈ (I • J) • N, from mul_smul r s n ▸ smul_mem_smul (smul_mem_smul hr hs) hn) variables (S : set R) (T : set M) theorem span_smul_span : (ideal.span S) • (span R T) = span R (⋃ (s ∈ S) (t ∈ T), {s • t}) := le_antisymm (smul_le.2 $ λ r hrS n hnT, span_induction hrS (λ r hrS, span_induction hnT (λ n hnT, subset_span $ set.mem_bUnion hrS $ set.mem_bUnion hnT $ set.mem_singleton _) ((smul_zero r : r • 0 = (0:M)).symm ▸ submodule.zero_mem _) (λ x y, (smul_add r x y).symm ▸ submodule.add_mem _) (λ c m, by rw [smul_smul, mul_comm, mul_smul]; exact submodule.smul_mem _ _)) ((zero_smul R n).symm ▸ submodule.zero_mem _) (λ r s, (add_smul r s n).symm ▸ submodule.add_mem _) (λ c r, by rw [smul_eq_mul, mul_smul]; exact submodule.smul_mem _ _)) $ span_le.2 $ set.bUnion_subset $ λ r hrS, set.bUnion_subset $ λ n hnT, set.singleton_subset_iff.2 $ smul_mem_smul (subset_span hrS) (subset_span hnT) variables {M' : Type w} [add_comm_group M'] [module R M'] theorem map_smul'' (f : M →ₗ[R] M') : (I • N).map f = I • N.map f := le_antisymm (map_le_iff_le_comap.2 $ smul_le.2 $ λ r hr n hn, show f (r • n) ∈ I • N.map f, from (f.map_smul r n).symm ▸ smul_mem_smul hr (mem_map_of_mem hn)) $ smul_le.2 $ λ r hr n hn, let ⟨p, hp, hfp⟩ := mem_map.1 hn in hfp ▸ f.map_smul r p ▸ mem_map_of_mem (smul_mem_smul hr hp) end submodule namespace ideal section chinese_remainder variables {R : Type u} [comm_ring R] {ι : Type v} theorem exists_sub_one_mem_and_mem (s : finset ι) {f : ι → ideal R} (hf : ∀ i ∈ s, ∀ j ∈ s, i ≠ j → f i ⊔ f j = ⊤) (i : ι) (his : i ∈ s) : ∃ r : R, r - 1 ∈ f i ∧ ∀ j ∈ s, j ≠ i → r ∈ f j := begin have : ∀ j ∈ s, j ≠ i → ∃ r : R, ∃ H : r - 1 ∈ f i, r ∈ f j, { intros j hjs hji, specialize hf i his j hjs hji.symm, rw [eq_top_iff_one, submodule.mem_sup] at hf, rcases hf with ⟨r, hri, s, hsj, hrs⟩, refine ⟨1 - r, _, _⟩, { rw [sub_right_comm, sub_self, zero_sub], exact (f i).neg_mem hri }, { rw [← hrs, add_sub_cancel'], exact hsj } }, classical, have : ∃ g : ι → R, (∀ j, g j - 1 ∈ f i) ∧ ∀ j ∈ s, j ≠ i → g j ∈ f j, { choose g hg1 hg2, refine ⟨λ j, if H : j ∈ s ∧ j ≠ i then g j H.1 H.2 else 1, λ j, _, λ j, _⟩, { split_ifs with h, { apply hg1 }, rw sub_self, exact (f i).zero_mem }, { intros hjs hji, rw dif_pos, { apply hg2 }, exact ⟨hjs, hji⟩ } }, rcases this with ⟨g, hgi, hgj⟩, use (∏ x in s.erase i, g x), split, { rw [← quotient.eq, ring_hom.map_one, ring_hom.map_prod], apply finset.prod_eq_one, intros, rw [← ring_hom.map_one, quotient.eq], apply hgi }, intros j hjs hji, rw [← quotient.eq_zero_iff_mem, ring_hom.map_prod], refine finset.prod_eq_zero (finset.mem_erase_of_ne_of_mem hji hjs) _, rw quotient.eq_zero_iff_mem, exact hgj j hjs hji end theorem exists_sub_mem [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) (g : ι → R) : ∃ r : R, ∀ i, r - g i ∈ f i := begin have : ∃ φ : ι → R, (∀ i, φ i - 1 ∈ f i) ∧ (∀ i j, i ≠ j → φ i ∈ f j), { have := exists_sub_one_mem_and_mem (finset.univ : finset ι) (λ i _ j _ hij, hf i j hij), choose φ hφ, existsi λ i, φ i (finset.mem_univ i), exact ⟨λ i, (hφ i _).1, λ i j hij, (hφ i _).2 j (finset.mem_univ j) hij.symm⟩ }, rcases this with ⟨φ, hφ1, hφ2⟩, use ∑ i, g i * φ i, intros i, rw [← quotient.eq, ring_hom.map_sum], refine eq.trans (finset.sum_eq_single i _ _) _, { intros j _ hji, rw quotient.eq_zero_iff_mem, exact (f i).mul_mem_left _ (hφ2 j i hji) }, { intros hi, exact (hi $ finset.mem_univ i).elim }, specialize hφ1 i, rw [← quotient.eq, ring_hom.map_one] at hφ1, rw [ring_hom.map_mul, hφ1, mul_one] end /-- The homomorphism from `R/(⋂ i, f i)` to `∏ i, (R / f i)` featured in the Chinese Remainder Theorem. It is bijective if the ideals `f i` are comaximal. -/ def quotient_inf_to_pi_quotient (f : ι → ideal R) : (⨅ i, f i).quotient →+* Π i, (f i).quotient := quotient.lift (⨅ i, f i) (pi.ring_hom (λ i : ι, (quotient.mk (f i) : _))) $ λ r hr, begin rw submodule.mem_infi at hr, ext i, exact quotient.eq_zero_iff_mem.2 (hr i) end theorem quotient_inf_to_pi_quotient_bijective [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : function.bijective (quotient_inf_to_pi_quotient f) := ⟨λ x y, quotient.induction_on₂' x y $ λ r s hrs, quotient.eq.2 $ (submodule.mem_infi _).2 $ λ i, quotient.eq.1 $ show quotient_inf_to_pi_quotient f (quotient.mk' r) i = _, by rw hrs; refl, λ g, let ⟨r, hr⟩ := exists_sub_mem hf (λ i, quotient.out' (g i)) in ⟨quotient.mk _ r, funext $ λ i, quotient.out_eq' (g i) ▸ quotient.eq.2 (hr i)⟩⟩ /-- Chinese Remainder Theorem. Eisenbud Ex.2.6. Similar to Atiyah-Macdonald 1.10 and Stacks 00DT -/ noncomputable def quotient_inf_ring_equiv_pi_quotient [fintype ι] (f : ι → ideal R) (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : (⨅ i, f i).quotient ≃+* Π i, (f i).quotient := { .. equiv.of_bijective _ (quotient_inf_to_pi_quotient_bijective hf), .. quotient_inf_to_pi_quotient f } end chinese_remainder section mul_and_radical variables {R : Type u} {ι : Type*} [comm_ring R] variables {I J K L : ideal R} instance : has_mul (ideal R) := ⟨(•)⟩ @[simp] lemma add_eq_sup : I + J = I ⊔ J := rfl @[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl @[simp] lemma one_eq_top : (1 : ideal R) = ⊤ := by erw [submodule.one_eq_map_top, submodule.map_id] theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J := submodule.smul_mem_smul hr hs theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J := mul_comm r s ▸ mul_mem_mul hr hs theorem mul_le : I * J ≤ K ↔ ∀ (r ∈ I) (s ∈ J), r * s ∈ K := submodule.smul_le lemma mul_le_left : I * J ≤ J := ideal.mul_le.2 (λ r hr s, J.mul_mem_left _) lemma mul_le_right : I * J ≤ I := ideal.mul_le.2 (λ r hr s hs, I.mul_mem_right _ hr) @[simp] lemma sup_mul_right_self : I ⊔ (I * J) = I := sup_eq_left.2 ideal.mul_le_right @[simp] lemma sup_mul_left_self : I ⊔ (J * I) = I := sup_eq_left.2 ideal.mul_le_left @[simp] lemma mul_right_self_sup : (I * J) ⊔ I = I := sup_eq_right.2 ideal.mul_le_right @[simp] lemma mul_left_self_sup : (J * I) ⊔ I = I := sup_eq_right.2 ideal.mul_le_left variables (I J K) protected theorem mul_comm : I * J = J * I := le_antisymm (mul_le.2 $ λ r hrI s hsJ, mul_mem_mul_rev hsJ hrI) (mul_le.2 $ λ r hrJ s hsI, mul_mem_mul_rev hsI hrJ) protected theorem mul_assoc : (I * J) * K = I * (J * K) := submodule.smul_assoc I J K theorem span_mul_span (S T : set R) : span S * span T = span ⋃ (s ∈ S) (t ∈ T), {s * t} := submodule.span_smul_span S T variables {I J K} lemma span_mul_span' (S T : set R) : span S * span T = span (S*T) := by { unfold span, rw submodule.span_mul_span, } lemma span_singleton_mul_span_singleton (r s : R) : span {r} * span {s} = (span {r * s} : ideal R) := by { unfold span, rw [submodule.span_mul_span, set.singleton_mul_singleton], } lemma span_singleton_pow (s : R) (n : ℕ): span {s} ^ n = (span {s ^ n} : ideal R) := begin induction n with n ih, { simp [set.singleton_one], }, simp only [pow_succ, ih, span_singleton_mul_span_singleton], end theorem mul_le_inf : I * J ≤ I ⊓ J := mul_le.2 $ λ r hri s hsj, ⟨I.mul_mem_right s hri, J.mul_mem_left r hsj⟩ theorem prod_le_inf {s : finset ι} {f : ι → ideal R} : s.prod f ≤ s.inf f := begin classical, refine s.induction_on _ _, { rw [finset.prod_empty, finset.inf_empty], exact le_top }, intros a s has ih, rw [finset.prod_insert has, finset.inf_insert], exact le_trans mul_le_inf (inf_le_inf (le_refl _) ih) end theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J := le_antisymm mul_le_inf $ λ r ⟨hri, hrj⟩, let ⟨s, hsi, t, htj, hst⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj) (mul_mem_mul hri htj) variables (I) theorem mul_bot : I * ⊥ = ⊥ := submodule.smul_bot I theorem bot_mul : ⊥ * I = ⊥ := submodule.bot_smul I theorem mul_top : I * ⊤ = I := ideal.mul_comm ⊤ I ▸ submodule.top_smul I theorem top_mul : ⊤ * I = I := submodule.top_smul I variables {I} theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L := submodule.smul_mono hik hjl theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K := submodule.smul_mono_left h theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K := submodule.smul_mono_right h variables (I J K) theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K := submodule.smul_sup I J K theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K := submodule.sup_smul I J K variables {I J K} lemma pow_le_pow {m n : ℕ} (h : m ≤ n) : I^n ≤ I^m := begin cases nat.exists_eq_add_of_le h with k hk, rw [hk, pow_add], exact le_trans (mul_le_inf) (inf_le_left) end lemma mul_eq_bot {R : Type*} [integral_domain R] {I J : ideal R} : I * J = ⊥ ↔ I = ⊥ ∨ J = ⊥ := ⟨λ hij, or_iff_not_imp_left.mpr (λ I_ne_bot, J.eq_bot_iff.mpr (λ j hj, let ⟨i, hi, ne0⟩ := I.ne_bot_iff.mp I_ne_bot in or.resolve_left (mul_eq_zero.mp ((I * J).eq_bot_iff.mp hij _ (mul_mem_mul hi hj))) ne0)), λ h, by cases h; rw [← ideal.mul_bot, h, ideal.mul_comm]⟩ instance {R : Type*} [integral_domain R] : no_zero_divisors (ideal R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ I J, mul_eq_bot.1 } /-- A product of ideals in an integral domain is zero if and only if one of the terms is zero. -/ lemma prod_eq_bot {R : Type*} [integral_domain R] {s : multiset (ideal R)} : s.prod = ⊥ ↔ ∃ I ∈ s, I = ⊥ := prod_zero_iff_exists_zero /-- The radical of an ideal `I` consists of the elements `r` such that `r^n ∈ I` for some `n`. -/ def radical (I : ideal R) : ideal R := { carrier := { r | ∃ n : ℕ, r ^ n ∈ I }, zero_mem' := ⟨1, (pow_one (0:R)).symm ▸ I.zero_mem⟩, add_mem' := λ x y ⟨m, hxmi⟩ ⟨n, hyni⟩, ⟨m + n, (add_pow x y (m + n)).symm ▸ I.sum_mem $ show ∀ c ∈ finset.range (nat.succ (m + n)), x ^ c * y ^ (m + n - c) * (nat.choose (m + n) c) ∈ I, from λ c hc, or.cases_on (le_total c m) (λ hcm, I.mul_mem_right _ $ I.mul_mem_left _ $ nat.add_comm n m ▸ (nat.add_sub_assoc hcm n).symm ▸ (pow_add y n (m-c)).symm ▸ I.mul_mem_right _ hyni) (λ hmc, I.mul_mem_right _ $ I.mul_mem_right _ $ nat.add_sub_cancel' hmc ▸ (pow_add x m (c-m)).symm ▸ I.mul_mem_right _ hxmi)⟩, smul_mem' := λ r s ⟨n, hsni⟩, ⟨n, (mul_pow r s n).symm ▸ I.mul_mem_left (r^n) hsni⟩ } theorem le_radical : I ≤ radical I := λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩ variables (R) theorem radical_top : (radical ⊤ : ideal R) = ⊤ := (eq_top_iff_one _).2 ⟨0, submodule.mem_top⟩ variables {R} theorem radical_mono (H : I ≤ J) : radical I ≤ radical J := λ r ⟨n, hrni⟩, ⟨n, H hrni⟩ variables (I) @[simp] theorem radical_idem : radical (radical I) = radical I := le_antisymm (λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩) le_radical variables {I} theorem radical_le_radical_iff : radical I ≤ radical J ↔ I ≤ radical J := ⟨λ h, le_trans le_radical h, λ h, radical_idem J ▸ radical_mono h⟩ theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ := ⟨λ h, (eq_top_iff_one _).2 $ let ⟨n, hn⟩ := (eq_top_iff_one _).1 h in @one_pow R _ n ▸ hn, λ h, h.symm ▸ radical_top R⟩ theorem is_prime.radical (H : is_prime I) : radical I = I := le_antisymm (λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni) le_radical variables (I J) theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) := le_antisymm (radical_mono $ sup_le_sup le_radical le_radical) $ λ r ⟨n, hrnij⟩, let ⟨s, hs, t, ht, hst⟩ := submodule.mem_sup.1 hrnij in @radical_idem _ _ (I ⊔ J) ▸ ⟨n, hst ▸ ideal.add_mem _ (radical_mono le_sup_left hs) (radical_mono le_sup_right ht)⟩ theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J := le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right)) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right _ hrm, (pow_add r m n).symm ▸ J.mul_mem_left _ hrn⟩) theorem radical_mul : radical (I * J) = radical I ⊓ radical J := le_antisymm (radical_inf I J ▸ radical_mono $ @mul_le_inf _ _ I J) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩) variables {I J} theorem is_prime.radical_le_iff (hj : is_prime J) : radical I ≤ J ↔ I ≤ J := ⟨le_trans le_radical, λ hij r ⟨n, hrni⟩, hj.mem_of_pow_mem n $ hij hrni⟩ theorem radical_eq_Inf (I : ideal R) : radical I = Inf { J : ideal R | I ≤ J ∧ is_prime J } := le_antisymm (le_Inf $ λ J hJ, hJ.2.radical_le_iff.2 hJ.1) $ λ r hr, classical.by_contradiction $ λ hri, let ⟨m, (hrm : r ∉ radical m), him, hm⟩ := zorn.zorn_nonempty_partial_order₀ {K : ideal R | r ∉ radical K} (λ c hc hcc y hyc, ⟨Sup c, λ ⟨n, hrnc⟩, let ⟨y, hyc, hrny⟩ := (submodule.mem_Sup_of_directed ⟨y, hyc⟩ hcc.directed_on).1 hrnc in hc hyc ⟨n, hrny⟩, λ z, le_Sup⟩) I hri in have ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := λ x hxm, classical.by_contradiction $ λ hrmx, hxm $ hm (m ⊔ span {x}) hrmx le_sup_left ▸ (le_sup_right : _ ≤ m ⊔ span {x}) (subset_span $ set.mem_singleton _), have is_prime m, from ⟨by rintro rfl; rw radical_top at hrm; exact hrm trivial, λ x y hxym, or_iff_not_imp_left.2 $ λ hxm, classical.by_contradiction $ λ hym, let ⟨n, hrn⟩ := this _ hxm, ⟨p, hpm, q, hq, hpqrn⟩ := submodule.mem_sup.1 hrn, ⟨c, hcxq⟩ := mem_span_singleton'.1 hq in let ⟨k, hrk⟩ := this _ hym, ⟨f, hfm, g, hg, hfgrk⟩ := submodule.mem_sup.1 hrk, ⟨d, hdyg⟩ := mem_span_singleton'.1 hg in hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c*x), mul_assoc c x (d*y), mul_left_comm x, ← mul_assoc]; refine m.add_mem (m.mul_mem_right _ hpm) (m.add_mem (m.mul_mem_left _ hfm) (m.mul_mem_left _ hxym))⟩⟩, hrm $ this.radical.symm ▸ (Inf_le ⟨him, this⟩ : Inf {J : ideal R | I ≤ J ∧ is_prime J} ≤ m) hr @[simp] lemma radical_bot_of_integral_domain {R : Type u} [integral_domain R] : radical (⊥ : ideal R) = ⊥ := eq_bot_iff.2 (λ x hx, hx.rec_on (λ n hn, pow_eq_zero hn)) instance : comm_semiring (ideal R) := submodule.comm_semiring variables (R) theorem top_pow (n : ℕ) : (⊤ ^ n : ideal R) = ⊤ := nat.rec_on n one_eq_top $ λ n ih, by rw [pow_succ, ih, top_mul] variables {R} variables (I) theorem radical_pow (n : ℕ) (H : n > 0) : radical (I^n) = radical I := nat.rec_on n (not.elim dec_trivial) (λ n ih H, or.cases_on (lt_or_eq_of_le $ nat.le_of_lt_succ H) (λ H, calc radical (I^(n+1)) = radical I ⊓ radical (I^n) : by { rw pow_succ, exact radical_mul _ _ } ... = radical I ⊓ radical I : by rw ih H ... = radical I : inf_idem) (λ H, H ▸ (pow_one I).symm ▸ rfl)) H theorem is_prime.mul_le {I J P : ideal R} (hp : is_prime P) : I * J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, or_iff_not_imp_left.2 $ λ hip j hj, let ⟨i, hi, hip⟩ := set.not_subset.1 hip in (hp.mem_or_mem $ h $ mul_mem_mul hi hj).resolve_left hip, λ h, or.cases_on h (le_trans $ le_trans mul_le_inf inf_le_left) (le_trans $ le_trans mul_le_inf inf_le_right)⟩ theorem is_prime.inf_le {I J P : ideal R} (hp : is_prime P) : I ⊓ J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, hp.mul_le.1 $ le_trans mul_le_inf h, λ h, or.cases_on h (le_trans inf_le_left) (le_trans inf_le_right)⟩ theorem is_prime.prod_le {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hne: s.nonempty) : s.prod f ≤ P ↔ ∃ i ∈ s, f i ≤ P := suffices s.prod f ≤ P → ∃ i ∈ s, f i ≤ P, from ⟨this, λ ⟨i, his, hip⟩, le_trans prod_le_inf $ le_trans (finset.inf_le his) hip⟩, begin classical, obtain ⟨b, hb⟩ : ∃ b, b ∈ s := hne.bex, obtain ⟨t, hbt, rfl⟩ : ∃ t, b ∉ t ∧ s = insert b t, from ⟨s.erase b, s.not_mem_erase b, (finset.insert_erase hb).symm⟩, revert hbt, refine t.induction_on _ _, { simp only [finset.not_mem_empty, insert_emptyc_eq, exists_prop, finset.prod_singleton, imp_self, exists_eq_left, not_false_iff, finset.mem_singleton] }, intros a s has ih hbs h, have : a ∉ insert b s, { contrapose! has, apply finset.mem_of_mem_insert_of_ne has, rintro rfl, contradiction }, rw [finset.insert.comm, finset.prod_insert this, hp.mul_le] at h, rw finset.insert.comm, cases h, { exact ⟨a, finset.mem_insert_self a _, h⟩ }, obtain ⟨i, hi, ih⟩ : ∃ i ∈ insert b s, f i ≤ P := ih (mt finset.mem_insert_of_mem hbs) h, exact ⟨i, finset.mem_insert_of_mem hi, ih⟩ end theorem is_prime.inf_le' {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hsne: s.nonempty) : s.inf f ≤ P ↔ ∃ i ∈ s, f i ≤ P := ⟨λ h, (hp.prod_le hsne).1 $ le_trans prod_le_inf h, λ ⟨i, his, hip⟩, le_trans (finset.inf_le his) hip⟩ theorem subset_union {I J K : ideal R} : (I : set R) ⊆ J ∪ K ↔ I ≤ J ∨ I ≤ K := ⟨λ h, or_iff_not_imp_left.2 $ λ hij s hsi, let ⟨r, hri, hrj⟩ := set.not_subset.1 hij in classical.by_contradiction $ λ hsk, or.cases_on (h $ I.add_mem hri hsi) (λ hj, hrj $ add_sub_cancel r s ▸ J.sub_mem hj ((h hsi).resolve_right hsk)) (λ hk, hsk $ add_sub_cancel' r s ▸ K.sub_mem hk ((h hri).resolve_left hrj)), λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset_union_left J K) (λ h, set.subset.trans h $ set.subset_union_right J K)⟩ theorem subset_union_prime' {s : finset ι} {f : ι → ideal R} {a b : ι} (hp : ∀ i ∈ s, is_prime (f i)) {I : ideal R} : (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) ↔ I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) → I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i, from ⟨this, λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_left _ _) (set.subset_union_left _ _)) $ λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_right _ _) (set.subset_union_left _ _)) $ λ ⟨i, his, hi⟩, by refine (set.subset.trans hi $ set.subset.trans _ $ set.subset_union_right _ _); exact set.subset_bUnion_of_mem (finset.mem_coe.2 his)⟩, begin generalize hn : s.card = n, intros h, unfreezingI { induction n with n ih generalizing a b s }, { clear hp, rw finset.card_eq_zero at hn, subst hn, rw [finset.coe_empty, set.bUnion_empty, set.union_empty, subset_union] at h, simpa only [exists_prop, finset.not_mem_empty, false_and, exists_false, or_false] }, classical, replace hn : ∃ (i : ι) (t : finset ι), i ∉ t ∧ insert i t = s ∧ t.card = n := finset.card_eq_succ.1 hn, unfreezingI { rcases hn with ⟨i, t, hit, rfl, hn⟩ }, replace hp : is_prime (f i) ∧ ∀ x ∈ t, is_prime (f x) := (t.forall_mem_insert _ _).1 hp, by_cases Ht : ∃ j ∈ t, f j ≤ f i, { obtain ⟨j, hjt, hfji⟩ : ∃ j ∈ t, f j ≤ f i := Ht, obtain ⟨u, hju, rfl⟩ : ∃ u, j ∉ u ∧ insert j u = t, { exact ⟨t.erase j, t.not_mem_erase j, finset.insert_erase hjt⟩ }, have hp' : ∀ k ∈ insert i u, is_prime (f k), { rw finset.forall_mem_insert at hp ⊢, exact ⟨hp.1, hp.2.2⟩ }, have hiu : i ∉ u := mt finset.mem_insert_of_mem hit, have hn' : (insert i u).card = n, { rwa finset.card_insert_of_not_mem at hn ⊢, exacts [hiu, hju] }, have h' : (I : set R) ⊆ f a ∪ f b ∪ (⋃ k ∈ (↑(insert i u) : set ι), f k), { rw finset.coe_insert at h ⊢, rw finset.coe_insert at h, simp only [set.bUnion_insert] at h ⊢, rw [← set.union_assoc ↑(f i)] at h, erw [set.union_eq_self_of_subset_right hfji] at h, exact h }, specialize @ih a b (insert i u) hp' hn' h', refine ih.imp id (or.imp id (exists_imp_exists $ λ k, _)), simp only [exists_prop], exact and.imp (λ hk, finset.insert_subset_insert i (finset.subset_insert j u) hk) id }, by_cases Ha : f a ≤ f i, { have h' : (I : set R) ⊆ f i ∪ f b ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_right_comm ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Ha] at h, exact h }, specialize @ih i b t hp.2 hn h', right, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inr ⟨i, finset.mem_insert_self i t, ih⟩ }, { exact or.inl ih }, { exact or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, by_cases Hb : f b ≤ f i, { have h' : (I : set R) ⊆ f a ∪ f i ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_assoc ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Hb] at h, exact h }, specialize @ih a i t hp.2 hn h', rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inl ih }, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, ih⟩) }, { exact or.inr (or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩) } }, by_cases Hi : I ≤ f i, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, Hi⟩) }, have : ¬I ⊓ f a ⊓ f b ⊓ t.inf f ≤ f i, { rcases t.eq_empty_or_nonempty with (rfl | hsne), { rw [finset.inf_empty, inf_top_eq, hp.1.inf_le, hp.1.inf_le, not_or_distrib, not_or_distrib], exact ⟨⟨Hi, Ha⟩, Hb⟩ }, simp only [hp.1.inf_le, hp.1.inf_le' hsne, not_or_distrib], exact ⟨⟨⟨Hi, Ha⟩, Hb⟩, Ht⟩ }, rcases set.not_subset.1 this with ⟨r, ⟨⟨⟨hrI, hra⟩, hrb⟩, hr⟩, hri⟩, by_cases HI : (I : set R) ⊆ f a ∪ f b ∪ ⋃ j ∈ (↑t : set ι), f j, { specialize ih hp.2 hn HI, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { left, exact ih }, { right, left, exact ih }, { right, right, exact ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, exfalso, rcases set.not_subset.1 HI with ⟨s, hsI, hs⟩, rw [finset.coe_insert, set.bUnion_insert] at h, have hsi : s ∈ f i := ((h hsI).resolve_left (mt or.inl hs)).resolve_right (mt or.inr hs), rcases h (I.add_mem hrI hsI) with ⟨ha | hb⟩ | hi | ht, { exact hs (or.inl $ or.inl $ add_sub_cancel' r s ▸ (f a).sub_mem ha hra) }, { exact hs (or.inl $ or.inr $ add_sub_cancel' r s ▸ (f b).sub_mem hb hrb) }, { exact hri (add_sub_cancel r s ▸ (f i).sub_mem hi hsi) }, { rw set.mem_bUnion_iff at ht, rcases ht with ⟨j, hjt, hj⟩, simp only [finset.inf_eq_infi, set_like.mem_coe, submodule.mem_infi] at hr, exact hs (or.inr $ set.mem_bUnion hjt $ add_sub_cancel' r s ▸ (f j).sub_mem hj $ hr j hjt) } end /-- Prime avoidance. Atiyah-Macdonald 1.11, Eisenbud 3.3, Stacks 00DS, Matsumura Ex.1.6. -/ theorem subset_union_prime {s : finset ι} {f : ι → ideal R} (a b : ι) (hp : ∀ i ∈ s, i ≠ a → i ≠ b → is_prime (f i)) {I : ideal R} : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) ↔ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) → ∃ i, i ∈ s ∧ I ≤ f i, from ⟨λ h, bex_def.2 $ this h, λ ⟨i, his, hi⟩, set.subset.trans hi $ set.subset_bUnion_of_mem $ show i ∈ (↑s : set ι), from his⟩, assume h : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i), begin classical, tactic.unfreeze_local_instances, by_cases has : a ∈ s, { obtain ⟨t, hat, rfl⟩ : ∃ t, a ∉ t ∧ insert a t = s := ⟨s.erase a, finset.not_mem_erase a s, finset.insert_erase has⟩, by_cases hbt : b ∈ t, { obtain ⟨u, hbu, rfl⟩ : ∃ u, b ∉ u ∧ insert b u = t := ⟨t.erase b, finset.not_mem_erase b t, finset.insert_erase hbt⟩, have hp' : ∀ i ∈ u, is_prime (f i), { intros i hiu, refine hp i (finset.mem_insert_of_mem (finset.mem_insert_of_mem hiu)) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, finset.coe_insert, set.bUnion_insert, set.bUnion_insert, ← set.union_assoc, subset_union_prime' hp', bex_def] at h, rwa [finset.exists_mem_insert, finset.exists_mem_insert] }, { have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f a : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } }, { by_cases hbs : b ∈ s, { obtain ⟨t, hbt, rfl⟩ : ∃ t, b ∉ t ∧ insert b t = s := ⟨s.erase b, finset.not_mem_erase b s, finset.insert_erase hbs⟩, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f b : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert }, cases s.eq_empty_or_nonempty with hse hsne, { subst hse, rw [finset.coe_empty, set.bUnion_empty, set.subset_empty_iff] at h, have : (I : set R) ≠ ∅ := set.nonempty.ne_empty (set.nonempty_of_mem I.zero_mem), exact absurd h this }, { cases hsne.bex with i his, obtain ⟨t, hit, rfl⟩ : ∃ t, i ∉ t ∧ insert i t = s := ⟨s.erase i, finset.not_mem_erase i s, finset.insert_erase his⟩, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f i : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } } end end mul_and_radical section map_and_comap variables {R : Type u} {S : Type v} [ring R] [ring S] variables (f : R →+* S) variables {I J : ideal R} {K L : ideal S} /-- `I.map f` is the span of the image of the ideal `I` under `f`, which may be bigger than the image itself. -/ def map (I : ideal R) : ideal S := span (f '' I) /-- `I.comap f` is the preimage of `I` under `f`. -/ def comap (I : ideal S) : ideal R := { carrier := f ⁻¹' I, smul_mem' := λ c x hx, show f (c * x) ∈ I, by { rw f.map_mul, exact I.mul_mem_left _ hx }, .. I.to_add_submonoid.comap (f : R →+ S) } variables {f} theorem map_mono (h : I ≤ J) : map f I ≤ map f J := span_mono $ set.image_subset _ h theorem mem_map_of_mem (f : R →+* S) {I : ideal R} {x : R} (h : x ∈ I) : f x ∈ map f I := subset_span ⟨x, h, rfl⟩ lemma apply_coe_mem_map (f : R →+* S) (I : ideal R) (x : I) : f x ∈ I.map f := mem_map_of_mem f x.prop theorem map_le_iff_le_comap : map f I ≤ K ↔ I ≤ comap f K := span_le.trans set.image_subset_iff @[simp] theorem mem_comap {x} : x ∈ comap f K ↔ f x ∈ K := iff.rfl theorem comap_mono (h : K ≤ L) : comap f K ≤ comap f L := set.preimage_mono (λ x hx, h hx) variables (f) theorem comap_ne_top (hK : K ≠ ⊤) : comap f K ≠ ⊤ := (ne_top_iff_one _).2 $ by rw [mem_comap, f.map_one]; exact (ne_top_iff_one _).1 hK instance is_prime.comap [hK : K.is_prime] : (comap f K).is_prime := ⟨comap_ne_top _ hK.1, λ x y, by simp only [mem_comap, f.map_mul]; apply hK.2⟩ variables (I J K L) theorem map_top : map f ⊤ = ⊤ := (eq_top_iff_one _).2 $ subset_span ⟨1, trivial, f.map_one⟩ variable (f) lemma gc_map_comap : galois_connection (ideal.map f) (ideal.comap f) := λ I J, ideal.map_le_iff_le_comap @[simp] lemma comap_id : I.comap (ring_hom.id R) = I := ideal.ext $ λ _, iff.rfl @[simp] lemma map_id : I.map (ring_hom.id R) = I := (gc_map_comap (ring_hom.id R)).l_unique galois_connection.id comap_id lemma comap_comap {T : Type*} [ring T] {I : ideal T} (f : R →+* S) (g : S →+*T) : (I.comap g).comap f = I.comap (g.comp f) := rfl lemma map_map {T : Type*} [ring T] {I : ideal R} (f : R →+* S) (g : S →+*T) : (I.map f).map g = I.map (g.comp f) := ((gc_map_comap f).compose _ _ _ _ (gc_map_comap g)).l_unique (gc_map_comap (g.comp f)) (λ _, comap_comap _ _) variables {f I J K L} lemma map_le_of_le_comap : I ≤ K.comap f → I.map f ≤ K := (gc_map_comap f).l_le lemma le_comap_of_map_le : I.map f ≤ K → I ≤ K.comap f := (gc_map_comap f).le_u lemma le_comap_map : I ≤ (I.map f).comap f := (gc_map_comap f).le_u_l _ lemma map_comap_le : (K.comap f).map f ≤ K := (gc_map_comap f).l_u_le _ @[simp] lemma comap_top : (⊤ : ideal S).comap f = ⊤ := (gc_map_comap f).u_top @[simp] lemma comap_eq_top_iff {I : ideal S} : I.comap f = ⊤ ↔ I = ⊤ := ⟨ λ h, I.eq_top_iff_one.mpr (f.map_one ▸ mem_comap.mp ((I.comap f).eq_top_iff_one.mp h)), λ h, by rw [h, comap_top] ⟩ @[simp] lemma map_bot : (⊥ : ideal R).map f = ⊥ := (gc_map_comap f).l_bot variables (f I J K L) @[simp] lemma map_comap_map : ((I.map f).comap f).map f = I.map f := congr_fun (gc_map_comap f).l_u_l_eq_l I @[simp] lemma comap_map_comap : ((K.comap f).map f).comap f = K.comap f := congr_fun (gc_map_comap f).u_l_u_eq_u K lemma map_sup : (I ⊔ J).map f = I.map f ⊔ J.map f := (gc_map_comap f).l_sup theorem comap_inf : comap f (K ⊓ L) = comap f K ⊓ comap f L := rfl variables {ι : Sort*} lemma map_supr (K : ι → ideal R) : (supr K).map f = ⨆ i, (K i).map f := (gc_map_comap f).l_supr lemma comap_infi (K : ι → ideal S) : (infi K).comap f = ⨅ i, (K i).comap f := (gc_map_comap f).u_infi lemma map_Sup (s : set (ideal R)): (Sup s).map f = ⨆ I ∈ s, (I : ideal R).map f := (gc_map_comap f).l_Sup lemma comap_Inf (s : set (ideal S)): (Inf s).comap f = ⨅ I ∈ s, (I : ideal S).comap f := (gc_map_comap f).u_Inf lemma comap_Inf' (s : set (ideal S)) : (Inf s).comap f = ⨅ I ∈ (comap f '' s), I := trans (comap_Inf f s) (by rw infi_image) theorem comap_is_prime [H : is_prime K] : is_prime (comap f K) := ⟨comap_ne_top f H.ne_top, λ x y h, H.mem_or_mem $ by rwa [mem_comap, ring_hom.map_mul] at h⟩ variables {I J K L} theorem map_inf_le : map f (I ⊓ J) ≤ map f I ⊓ map f J := (gc_map_comap f).monotone_l.map_inf_le _ _ theorem le_comap_sup : comap f K ⊔ comap f L ≤ comap f (K ⊔ L) := (gc_map_comap f).monotone_u.le_map_sup _ _ section surjective variables (hf : function.surjective f) include hf open function theorem map_comap_of_surjective (I : ideal S) : map f (comap f I) = I := le_antisymm (map_le_iff_le_comap.2 (le_refl _)) (λ s hsi, let ⟨r, hfrs⟩ := hf s in hfrs ▸ (mem_map_of_mem f $ show f r ∈ I, from hfrs.symm ▸ hsi)) /-- `map` and `comap` are adjoint, and the composition `map f ∘ comap f` is the identity -/ def gi_map_comap : galois_insertion (map f) (comap f) := galois_insertion.monotone_intro ((gc_map_comap f).monotone_u) ((gc_map_comap f).monotone_l) (λ _, le_comap_map) (map_comap_of_surjective _ hf) lemma map_surjective_of_surjective : surjective (map f) := (gi_map_comap f hf).l_surjective lemma comap_injective_of_surjective : injective (comap f) := (gi_map_comap f hf).u_injective lemma map_sup_comap_of_surjective (I J : ideal S) : (I.comap f ⊔ J.comap f).map f = I ⊔ J := (gi_map_comap f hf).l_sup_u _ _ lemma map_supr_comap_of_surjective (K : ι → ideal S) : (⨆i, (K i).comap f).map f = supr K := (gi_map_comap f hf).l_supr_u _ lemma map_inf_comap_of_surjective (I J : ideal S) : (I.comap f ⊓ J.comap f).map f = I ⊓ J := (gi_map_comap f hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (K : ι → ideal S) : (⨅i, (K i).comap f).map f = infi K := (gi_map_comap f hf).l_infi_u _ theorem mem_image_of_mem_map_of_surjective {I : ideal R} {y} (H : y ∈ map f I) : y ∈ f '' I := submodule.span_induction H (λ _, id) ⟨0, I.zero_mem, f.map_zero⟩ (λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩, ⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ f.map_add _ _⟩) (λ c y ⟨x, hxi, hxy⟩, let ⟨d, hdc⟩ := hf c in ⟨d • x, I.smul_mem _ hxi, hdc ▸ hxy ▸ f.map_mul _ _⟩) lemma mem_map_iff_of_surjective {I : ideal R} {y} : y ∈ map f I ↔ ∃ x, x ∈ I ∧ f x = y := ⟨λ h, (set.mem_image _ _ _).2 (mem_image_of_mem_map_of_surjective f hf h), λ ⟨x, hx⟩, hx.right ▸ (mem_map_of_mem f hx.left)⟩ theorem comap_map_of_surjective (I : ideal R) : comap f (map f I) = I ⊔ comap f ⊥ := le_antisymm (assume r h, let ⟨s, hsi, hfsr⟩ := mem_image_of_mem_map_of_surjective f hf h in submodule.mem_sup.2 ⟨s, hsi, r - s, (submodule.mem_bot S).2 $ by rw [f.map_sub, hfsr, sub_self], add_sub_cancel'_right s r⟩) (sup_le (map_le_iff_le_comap.1 (le_refl _)) (comap_mono bot_le)) lemma le_map_of_comap_le_of_surjective : comap f K ≤ I → K ≤ map f I := λ h, (map_comap_of_surjective f hf K) ▸ map_mono h /-- Correspondence theorem -/ def rel_iso_of_surjective : ideal S ≃o { p : ideal R // comap f ⊥ ≤ p } := { to_fun := λ J, ⟨comap f J, comap_mono bot_le⟩, inv_fun := λ I, map f I.1, left_inv := λ J, map_comap_of_surjective f hf J, right_inv := λ I, subtype.eq $ show comap f (map f I.1) = I.1, from (comap_map_of_surjective f hf I).symm ▸ le_antisymm (sup_le (le_refl _) I.2) le_sup_left, map_rel_iff' := λ I1 I2, ⟨λ H, map_comap_of_surjective f hf I1 ▸ map_comap_of_surjective f hf I2 ▸ map_mono H, comap_mono⟩ } /-- The map on ideals induced by a surjective map preserves inclusion. -/ def order_embedding_of_surjective : ideal S ↪o ideal R := (rel_iso_of_surjective f hf).to_rel_embedding.trans (subtype.rel_embedding _ _) theorem map_eq_top_or_is_maximal_of_surjective (H : is_maximal I) : (map f I) = ⊤ ∨ is_maximal (map f I) := begin refine or_iff_not_imp_left.2 (λ ne_top, ⟨⟨λ h, ne_top h, λ J hJ, _⟩⟩), { refine (rel_iso_of_surjective f hf).injective (subtype.ext_iff.2 (eq.trans (H.1.2 (comap f J) (lt_of_le_of_ne _ _)) comap_top.symm)), { exact (map_le_iff_le_comap).1 (le_of_lt hJ) }, { exact λ h, hJ.right (le_map_of_comap_le_of_surjective f hf (le_of_eq h.symm)) } } end theorem comap_is_maximal_of_surjective [H : is_maximal K] : is_maximal (comap f K) := begin refine ⟨⟨comap_ne_top _ H.1.1, λ J hJ, _⟩⟩, suffices : map f J = ⊤, { replace this := congr_arg (comap f) this, rw [comap_top, comap_map_of_surjective _ hf, eq_top_iff] at this, rw eq_top_iff, exact le_trans this (sup_le (le_of_eq rfl) (le_trans (comap_mono (bot_le)) (le_of_lt hJ))) }, refine H.1.2 (map f J) (lt_of_le_of_ne (le_map_of_comap_le_of_surjective _ hf (le_of_lt hJ)) (λ h, ne_of_lt hJ (trans (congr_arg (comap f) h) _))), rw [comap_map_of_surjective _ hf, sup_eq_left], exact le_trans (comap_mono bot_le) (le_of_lt hJ) end end surjective /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f (map f.symm) = I`. -/ @[simp] lemma map_of_equiv (I : ideal R) (f : R ≃+* S) : (I.map (f : R →+* S)).map (f.symm : S →+* R) = I := by simp [← ring_equiv.to_ring_hom_eq_coe, map_map] /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `comap f.symm (comap f) = I`. -/ @[simp] lemma comap_of_equiv (I : ideal R) (f : R ≃+* S) : (I.comap (f.symm : S →+* R)).comap (f : R →+* S) = I := by simp [← ring_equiv.to_ring_hom_eq_coe, comap_comap] /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f I = comap f.symm I`. -/ lemma map_comap_of_equiv (I : ideal R) (f : R ≃+* S) : I.map (f : R →+* S) = I.comap f.symm := le_antisymm (le_comap_of_map_le (map_of_equiv I f).le) (le_map_of_comap_le_of_surjective _ f.surjective (comap_of_equiv I f).le) section injective variables (hf : function.injective f) include hf open function lemma comap_bot_le_of_injective : comap f ⊥ ≤ I := begin refine le_trans (λ x hx, _) bot_le, rw [mem_comap, submodule.mem_bot, ← ring_hom.map_zero f] at hx, exact eq.symm (hf hx) ▸ (submodule.zero_mem ⊥) end end injective section bijective variables (hf : function.bijective f) include hf open function /-- Special case of the correspondence theorem for isomorphic rings -/ def rel_iso_of_bijective : ideal S ≃o ideal R := { to_fun := comap f, inv_fun := map f, left_inv := (rel_iso_of_surjective f hf.right).left_inv, right_inv := λ J, subtype.ext_iff.1 ((rel_iso_of_surjective f hf.right).right_inv ⟨J, comap_bot_le_of_injective f hf.left⟩), map_rel_iff' := (rel_iso_of_surjective f hf.right).map_rel_iff' } lemma comap_le_iff_le_map : comap f K ≤ I ↔ K ≤ map f I := ⟨λ h, le_map_of_comap_le_of_surjective f hf.right h, λ h, ((rel_iso_of_bijective f hf).right_inv I) ▸ comap_mono h⟩ theorem map.is_maximal (H : is_maximal I) : is_maximal (map f I) := by refine or_iff_not_imp_left.1 (map_eq_top_or_is_maximal_of_surjective f hf.right H) (λ h, H.1.1 _); calc I = comap f (map f I) : ((rel_iso_of_bijective f hf).right_inv I).symm ... = comap f ⊤ : by rw h ... = ⊤ : by rw comap_top end bijective lemma ring_equiv.bot_maximal_iff (e : R ≃+* S) : (⊥ : ideal R).is_maximal ↔ (⊥ : ideal S).is_maximal := ⟨λ h, (@map_bot _ _ _ _ e.to_ring_hom) ▸ map.is_maximal e.to_ring_hom e.bijective h, λ h, (@map_bot _ _ _ _ e.symm.to_ring_hom) ▸ map.is_maximal e.symm.to_ring_hom e.symm.bijective h⟩ end map_and_comap section map_and_comap variables {R : Type u} {S : Type v} [comm_ring R] [comm_ring S] variables (f : R →+* S) variables {I J : ideal R} {K L : ideal S} lemma mem_quotient_iff_mem (hIJ : I ≤ J) {x : R} : quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J := begin refine iff.trans (mem_map_iff_of_surjective _ quotient.mk_surjective) _, split, { rintros ⟨x, x_mem, x_eq⟩, simpa using J.add_mem (hIJ (quotient.eq.mp x_eq.symm)) x_mem }, { intro x_mem, exact ⟨x, x_mem, rfl⟩ } end variables (I J K L) theorem map_mul : map f (I * J) = map f I * map f J := le_antisymm (map_le_iff_le_comap.2 $ mul_le.2 $ λ r hri s hsj, show f (r * s) ∈ _, by rw f.map_mul; exact mul_mem_mul (mem_map_of_mem f hri) (mem_map_of_mem f hsj)) (trans_rel_right _ (span_mul_span _ _) $ span_le.2 $ set.bUnion_subset $ λ i ⟨r, hri, hfri⟩, set.bUnion_subset $ λ j ⟨s, hsj, hfsj⟩, set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸ by rw [← f.map_mul]; exact mem_map_of_mem f (mul_mem_mul hri hsj)) theorem comap_radical : comap f (radical K) = radical (comap f K) := le_antisymm (λ r ⟨n, hfrnk⟩, ⟨n, show f (r ^ n) ∈ K, from (f.map_pow r n).symm ▸ hfrnk⟩) (λ r ⟨n, hfrnk⟩, ⟨n, f.map_pow r n ▸ hfrnk⟩) @[simp] lemma map_quotient_self : map (quotient.mk I) I = ⊥ := eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ λ x hx, (submodule.mem_bot I.quotient).2 $ ideal.quotient.eq_zero_iff_mem.2 hx variables {I J K L} theorem map_radical_le : map f (radical I) ≤ radical (map f I) := map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, f.map_pow r n ▸ mem_map_of_mem f hrni⟩ theorem le_comap_mul : comap f K * comap f L ≤ comap f (K * L) := map_le_iff_le_comap.1 $ (map_mul f (comap f K) (comap f L)).symm ▸ mul_mono (map_le_iff_le_comap.2 $ le_refl _) (map_le_iff_le_comap.2 $ le_refl _) end map_and_comap section is_primary variables {R : Type u} [comm_ring R] /-- A proper ideal `I` is primary iff `xy ∈ I` implies `x ∈ I` or `y ∈ radical I`. -/ def is_primary (I : ideal R) : Prop := I ≠ ⊤ ∧ ∀ {x y : R}, x * y ∈ I → x ∈ I ∨ y ∈ radical I theorem is_primary.to_is_prime (I : ideal R) (hi : is_prime I) : is_primary I := ⟨hi.1, λ x y hxy, (hi.mem_or_mem hxy).imp id $ λ hyi, le_radical hyi⟩ theorem mem_radical_of_pow_mem {I : ideal R} {x : R} {m : ℕ} (hx : x ^ m ∈ radical I) : x ∈ radical I := radical_idem I ▸ ⟨m, hx⟩ theorem is_prime_radical {I : ideal R} (hi : is_primary I) : is_prime (radical I) := ⟨mt radical_eq_top.1 hi.1, λ x y ⟨m, hxy⟩, begin rw mul_pow at hxy, cases hi.2 hxy, { exact or.inl ⟨m, h⟩ }, { exact or.inr (mem_radical_of_pow_mem h) } end⟩ theorem is_primary_inf {I J : ideal R} (hi : is_primary I) (hj : is_primary J) (hij : radical I = radical J) : is_primary (I ⊓ J) := ⟨ne_of_lt $ lt_of_le_of_lt inf_le_left (lt_top_iff_ne_top.2 hi.1), λ x y ⟨hxyi, hxyj⟩, begin rw [radical_inf, hij, inf_idem], cases hi.2 hxyi with hxi hyi, cases hj.2 hxyj with hxj hyj, { exact or.inl ⟨hxi, hxj⟩ }, { exact or.inr hyj }, { rw hij at hyi, exact or.inr hyi } end⟩ end is_primary end ideal namespace ring_hom variables {R : Type u} {S : Type v} section ring variables [ring R] [ring S] (f : R →+* S) /-- Kernel of a ring homomorphism as an ideal of the domain. -/ def ker : ideal R := ideal.comap f ⊥ /-- An element is in the kernel if and only if it maps to zero.-/ lemma mem_ker {r} : r ∈ ker f ↔ f r = 0 := by rw [ker, ideal.mem_comap, submodule.mem_bot] lemma ker_eq : ((ker f) : set R) = is_add_group_hom.ker f := rfl lemma ker_eq_comap_bot (f : R →+* S) : f.ker = ideal.comap f ⊥ := rfl lemma injective_iff_ker_eq_bot : function.injective f ↔ ker f = ⊥ := by rw [set_like.ext'_iff, ker_eq]; exact is_add_group_hom.injective_iff_trivial_ker f lemma ker_eq_bot_iff_eq_zero : ker f = ⊥ ↔ ∀ x, f x = 0 → x = 0 := by rw [set_like.ext'_iff, ker_eq]; exact is_add_group_hom.trivial_ker_iff_eq_zero f /-- If the target is not the zero ring, then one is not in the kernel.-/ lemma not_one_mem_ker [nontrivial S] (f : R →+* S) : (1:R) ∉ ker f := by { rw [mem_ker, f.map_one], exact one_ne_zero } @[simp] lemma ker_coe_equiv (f : R ≃+* S) : ker (f : R →+* S) = ⊥ := by simpa only [←injective_iff_ker_eq_bot] using f.injective end ring section comm_ring variables [comm_ring R] [comm_ring S] (f : R →+* S) /-- The induced map from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_equiv_of_right_inverse`) / is surjective (`quotient_ker_equiv_of_surjective`). -/ def ker_lift (f : R →+* S) : f.ker.quotient →+* S := ideal.quotient.lift _ f $ λ r, f.mem_ker.mp @[simp] lemma ker_lift_mk (f : R →+* S) (r : R) : ker_lift f (ideal.quotient.mk f.ker r) = f r := ideal.quotient.lift_mk _ _ _ /-- The induced map from the quotient by the kernel is injective. -/ lemma ker_lift_injective (f : R →+* S) : function.injective (ker_lift f) := assume a b, quotient.induction_on₂' a b $ assume a b (h : f a = f b), quotient.sound' $ show a - b ∈ ker f, by rw [mem_ker, map_sub, h, sub_self] variable {f} /-- The first isomorphism theorem for commutative rings, computable version. -/ def quotient_ker_equiv_of_right_inverse {g : S → R} (hf : function.right_inverse g f) : f.ker.quotient ≃+* S := { to_fun := ker_lift f, inv_fun := (ideal.quotient.mk f.ker) ∘ g, left_inv := begin rintro ⟨x⟩, apply ker_lift_injective, simp [hf (f x)], end, right_inv := hf, ..ker_lift f} @[simp] lemma quotient_ker_equiv_of_right_inverse.apply {g : S → R} (hf : function.right_inverse g f) (x : f.ker.quotient) : quotient_ker_equiv_of_right_inverse hf x = ker_lift f x := rfl @[simp] lemma quotient_ker_equiv_of_right_inverse.symm.apply {g : S → R} (hf : function.right_inverse g f) (x : S) : (quotient_ker_equiv_of_right_inverse hf).symm x = ideal.quotient.mk f.ker (g x) := rfl /-- The first isomorphism theorem for commutative rings. -/ noncomputable def quotient_ker_equiv_of_surjective (hf : function.surjective f) : f.ker.quotient ≃+* S := quotient_ker_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) end comm_ring /-- The kernel of a homomorphism to an integral domain is a prime ideal.-/ lemma ker_is_prime [ring R] [integral_domain S] (f : R →+* S) : (ker f).is_prime := ⟨by { rw [ne.def, ideal.eq_top_iff_one], exact not_one_mem_ker f }, λ x y, by simpa only [mem_ker, f.map_mul] using @eq_zero_or_eq_zero_of_mul_eq_zero S _ _ _ _ _⟩ end ring_hom namespace ideal variables {R : Type*} {S : Type*} section ring variables [ring R] [ring S] lemma map_eq_bot_iff_le_ker {I : ideal R} (f : R →+* S) : I.map f = ⊥ ↔ I ≤ f.ker := by rw [ring_hom.ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_le_comap {K : ideal S} (f : R →+* S) : f.ker ≤ comap f K := λ x hx, mem_comap.2 (((ring_hom.mem_ker f).1 hx).symm ▸ K.zero_mem) lemma map_Inf {A : set (ideal R)} {f : R →+* S} (hf : function.surjective f) : (∀ J ∈ A, ring_hom.ker f ≤ J) → map f (Inf A) = Inf (map f '' A) := begin refine λ h, le_antisymm (le_Inf _) _, { intros j hj y hy, cases (mem_map_iff_of_surjective f hf).1 hy with x hx, cases (set.mem_image _ _ _).mp hj with J hJ, rw [← hJ.right, ← hx.right], exact mem_map_of_mem f (Inf_le_of_le hJ.left (le_of_eq rfl) hx.left) }, { intros y hy, cases hf y with x hx, refine hx ▸ (mem_map_of_mem f _), have : ∀ I ∈ A, y ∈ map f I, by simpa using hy, rw [submodule.mem_Inf], intros J hJ, rcases (mem_map_iff_of_surjective f hf).1 (this J hJ) with ⟨x', hx', rfl⟩, have : x - x' ∈ J, { apply h J hJ, rw [ring_hom.mem_ker, ring_hom.map_sub, hx, sub_self] }, simpa only [sub_add_cancel] using J.add_mem this hx' } end theorem map_is_prime_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} [H : is_prime I] (hk : ring_hom.ker f ≤ I) : is_prime (map f I) := begin refine ⟨λ h, H.ne_top (eq_top_iff.2 _), λ x y, _⟩, { replace h := congr_arg (comap f) h, rw [comap_map_of_surjective _ hf, comap_top] at h, exact h ▸ sup_le (le_of_eq rfl) hk }, { refine λ hxy, (hf x).rec_on (λ a ha, (hf y).rec_on (λ b hb, _)), rw [← ha, ← hb, ← ring_hom.map_mul, mem_map_iff_of_surjective _ hf] at hxy, rcases hxy with ⟨c, hc, hc'⟩, rw [← sub_eq_zero, ← ring_hom.map_sub] at hc', have : a * b ∈ I, { convert I.sub_mem hc (hk (hc' : c - a * b ∈ f.ker)), abel }, exact (H.mem_or_mem this).imp (λ h, ha ▸ mem_map_of_mem f h) (λ h, hb ▸ mem_map_of_mem f h) } end theorem map_is_prime_of_equiv (f : R ≃+* S) {I : ideal R} [is_prime I] : is_prime (map (f : R →+* S) I) := map_is_prime_of_surjective f.surjective $ by simp end ring section comm_ring variables [comm_ring R] [comm_ring S] @[simp] lemma mk_ker {I : ideal R} : (quotient.mk I).ker = I := by ext; rw [ring_hom.ker, mem_comap, submodule.mem_bot, quotient.eq_zero_iff_mem] theorem map_radical_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} (h : ring_hom.ker f ≤ I) : map f (I.radical) = (map f I).radical := begin rw [radical_eq_Inf, radical_eq_Inf], have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_prime}, f.ker ≤ J := λ J hJ, le_trans h hJ.left, convert map_Inf hf this, refine funext (λ j, propext ⟨_, _⟩), { rintros ⟨hj, hj'⟩, haveI : j.is_prime := hj', exact ⟨comap f j, ⟨⟨map_le_iff_le_comap.1 hj, comap_is_prime f j⟩, map_comap_of_surjective f hf j⟩⟩ }, { rintro ⟨J, ⟨hJ, hJ'⟩⟩, haveI : J.is_prime := hJ.right, refine ⟨hJ' ▸ map_mono hJ.left, hJ' ▸ map_is_prime_of_surjective hf (le_trans h hJ.left)⟩ }, end @[simp] lemma bot_quotient_is_maximal_iff (I : ideal R) : (⊥ : ideal I.quotient).is_maximal ↔ I.is_maximal := ⟨λ hI, (@mk_ker _ _ I) ▸ @comap_is_maximal_of_surjective _ _ _ _ (quotient.mk I) ⊥ quotient.mk_surjective hI, λ hI, @bot_is_maximal _ (@field.to_division_ring _ (@quotient.field _ _ I hI)) ⟩ section quotient_algebra variables (R) {A : Type*} [comm_ring A] [algebra R A] /-- The `R`-algebra structure on `A/I` for an `R`-algebra `A` -/ instance {I : ideal A} : algebra R (ideal.quotient I) := (ring_hom.comp (ideal.quotient.mk I) (algebra_map R A)).to_algebra /-- The canonical morphism `A →ₐ[R] I.quotient` as morphism of `R`-algebras, for `I` an ideal of `A`, where `A` is an `R`-algebra. -/ def quotient.mkₐ (I : ideal A) : A →ₐ[R] I.quotient := ⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl, λ _, rfl⟩ lemma quotient.alg_map_eq (I : ideal A) : algebra_map R I.quotient = (algebra_map A I.quotient).comp (algebra_map R A) := by simp only [ring_hom.algebra_map_to_algebra, ring_hom.comp_id] instance [algebra S A] [algebra S R] [is_scalar_tower S R A] {I : ideal A} : is_scalar_tower S R (ideal.quotient I) := is_scalar_tower.of_algebra_map_eq' $ by rw [quotient.alg_map_eq R, quotient.alg_map_eq S, ring_hom.comp_assoc, is_scalar_tower.algebra_map_eq S R A] lemma quotient.mkₐ_to_ring_hom (I : ideal A) : (quotient.mkₐ R I).to_ring_hom = ideal.quotient.mk I := rfl @[simp] lemma quotient.mkₐ_eq_mk (I : ideal A) : ⇑(quotient.mkₐ R I) = ideal.quotient.mk I := rfl /-- The canonical morphism `A →ₐ[R] I.quotient` is surjective. -/ lemma quotient.mkₐ_surjective (I : ideal A) : function.surjective (quotient.mkₐ R I) := surjective_quot_mk _ /-- The kernel of `A →ₐ[R] I.quotient` is `I`. -/ @[simp] lemma quotient.mkₐ_ker (I : ideal A) : (quotient.mkₐ R I : A →+* I.quotient).ker = I := ideal.mk_ker variables {R} {B : Type*} [comm_ring B] [algebra R B] lemma ker_lift.map_smul (f : A →ₐ[R] B) (r : R) (x : f.to_ring_hom.ker.quotient) : f.to_ring_hom.ker_lift (r • x) = r • f.to_ring_hom.ker_lift x := begin obtain ⟨a, rfl⟩ := quotient.mkₐ_surjective R _ x, rw [← alg_hom.map_smul, quotient.mkₐ_eq_mk, ring_hom.ker_lift_mk], exact f.map_smul _ _ end /-- The induced algebras morphism from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_alg_equiv_of_right_inverse`) / is surjective (`quotient_ker_alg_equiv_of_surjective`). -/ def ker_lift_alg (f : A →ₐ[R] B) : f.to_ring_hom.ker.quotient →ₐ[R] B := alg_hom.mk' f.to_ring_hom.ker_lift (λ _ _, ker_lift.map_smul f _ _) @[simp] lemma ker_lift_alg_mk (f : A →ₐ[R] B) (a : A) : ker_lift_alg f (quotient.mk f.to_ring_hom.ker a) = f a := rfl @[simp] lemma ker_lift_alg_to_ring_hom (f : A →ₐ[R] B) : (ker_lift_alg f).to_ring_hom = ring_hom.ker_lift f := rfl /-- The induced algebra morphism from the quotient by the kernel is injective. -/ lemma ker_lift_alg_injective (f : A →ₐ[R] B) : function.injective (ker_lift_alg f) := ring_hom.ker_lift_injective f /-- The first isomorphism theorem for agebras, computable version. -/ def quotient_ker_alg_equiv_of_right_inverse {f : A →ₐ[R] B} {g : B → A} (hf : function.right_inverse g f) : f.to_ring_hom.ker.quotient ≃ₐ[R] B := { ..ring_hom.quotient_ker_equiv_of_right_inverse (λ x, show f.to_ring_hom (g x) = x, from hf x), ..ker_lift_alg f} @[simp] lemma quotient_ker_alg_equiv_of_right_inverse.apply {f : A →ₐ[R] B} {g : B → A} (hf : function.right_inverse g f) (x : f.to_ring_hom.ker.quotient) : quotient_ker_alg_equiv_of_right_inverse hf x = ker_lift_alg f x := rfl @[simp] lemma quotient_ker_alg_equiv_of_right_inverse_symm.apply {f : A →ₐ[R] B} {g : B → A} (hf : function.right_inverse g f) (x : B) : (quotient_ker_alg_equiv_of_right_inverse hf).symm x = quotient.mkₐ R f.to_ring_hom.ker (g x) := rfl /-- The first isomorphism theorem for algebras. -/ noncomputable def quotient_ker_alg_equiv_of_surjective {f : A →ₐ[R] B} (hf : function.surjective f) : f.to_ring_hom.ker.quotient ≃ₐ[R] B := quotient_ker_alg_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) /-- The ring hom `R/I →+* S/J` induced by a ring hom `f : R →+* S` with `I ≤ f⁻¹(J)` -/ def quotient_map {I : ideal R} (J : ideal S) (f : R →+* S) (hIJ : I ≤ J.comap f) : I.quotient →+* J.quotient := (quotient.lift I ((quotient.mk J).comp f) (λ _ ha, by simpa [function.comp_app, ring_hom.coe_comp, quotient.eq_zero_iff_mem] using hIJ ha)) @[simp] lemma quotient_map_mk {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} {x : R} : quotient_map I f H (quotient.mk J x) = quotient.mk I (f x) := quotient.lift_mk J _ _ lemma quotient_map_comp_mk {J : ideal R} {I : ideal S} {f : R →+* S} (H : J ≤ I.comap f) : (quotient_map I f H).comp (quotient.mk J) = (quotient.mk I).comp f := ring_hom.ext (λ x, by simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient_map_mk]) /-- The ring equiv `R/I ≃+* S/J` induced by a ring equiv `f : R ≃+** S`, where `J = f(I)`. -/ @[simps] def quotient_equiv (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) : I.quotient ≃+* J.quotient := { inv_fun := quotient_map I ↑f.symm (by {rw hIJ, exact le_of_eq (map_comap_of_equiv I f)}), left_inv := by {rintro ⟨r⟩, simp }, right_inv := by {rintro ⟨s⟩, simp }, ..quotient_map J ↑f (by {rw hIJ, exact @le_comap_map _ S _ _ _ _}) } /-- `H` and `h` are kept as separate hypothesis since H is used in constructing the quotient map. -/ lemma quotient_map_injective' {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (h : I.comap f ≤ J) : function.injective (quotient_map I f H) := begin refine (quotient_map I f H).injective_iff.2 (λ a ha, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, rw [quotient_map_mk, quotient.eq_zero_iff_mem] at ha, exact (quotient.eq_zero_iff_mem).mpr (h ha), end /-- If we take `J = I.comap f` then `quotient_map` is injective automatically. -/ lemma quotient_map_injective {I : ideal S} {f : R →+* S} : function.injective (quotient_map I f le_rfl) := quotient_map_injective' le_rfl lemma quotient_map_surjective {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (hf : function.surjective f) : function.surjective (quotient_map I f H) := λ x, let ⟨x, hx⟩ := quotient.mk_surjective x in let ⟨y, hy⟩ := hf x in ⟨(quotient.mk J) y, by simp [hx, hy]⟩ /-- Commutativity of a square is preserved when taking quotients by an ideal. -/ lemma comp_quotient_map_eq_of_comp_eq {R' S' : Type*} [comm_ring R'] [comm_ring S'] {f : R →+* S} {f' : R' →+* S'} {g : R →+* R'} {g' : S →+* S'} (hfg : f'.comp g = g'.comp f) (I : ideal S') : (quotient_map I g' le_rfl).comp (quotient_map (I.comap g') f le_rfl) = (quotient_map I f' le_rfl).comp (quotient_map (I.comap f') g (le_of_eq (trans (comap_comap f g') (hfg ▸ (comap_comap g f'))))) := begin refine ring_hom.ext (λ a, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, simp only [ring_hom.comp_apply, quotient_map_mk], exact congr_arg (quotient.mk I) (trans (g'.comp_apply f r).symm (hfg ▸ (f'.comp_apply g r))), end variables {I : ideal R} {J: ideal S} [algebra R S] /-- The algebra hom `A/I →+* S/J` induced by an algebra hom `f : A →ₐ[R] S` with `I ≤ f⁻¹(J)`. -/ def quotient_mapₐ {I : ideal A} (J : ideal S) (f : A →ₐ[R] S) (hIJ : I ≤ J.comap f) : I.quotient →ₐ[R] J.quotient := { commutes' := λ r, begin have h : (algebra_map R I.quotient) r = (quotient.mk I) (algebra_map R A r) := rfl, simpa [h] end ..quotient_map J ↑f hIJ } @[simp] lemma quotient_map_mkₐ {I : ideal A} (J : ideal S) (f : A →ₐ[R] S) (H : I ≤ J.comap f) {x : A} : quotient_mapₐ J f H (quotient.mk I x) = quotient.mkₐ R J (f x) := rfl lemma quotient_map_comp_mkₐ {I : ideal A} (J : ideal S) (f : A →ₐ[R] S) (H : I ≤ J.comap f) : (quotient_mapₐ J f H).comp (quotient.mkₐ R I) = (quotient.mkₐ R J).comp f := alg_hom.ext (λ x, by simp only [quotient_map_mkₐ, quotient.mkₐ_eq_mk, alg_hom.comp_apply]) /-- The algebra equiv `A/I ≃ₐ[R] S/J` induced by an algebra equiv `f : A ≃ₐ[R] S`, where`J = f(I)`. -/ def quotient_equiv_alg (I : ideal A) (J : ideal S) (f : A ≃ₐ[R] S) (hIJ : J = I.map (f : A →+* S)) : I.quotient ≃ₐ[R] J.quotient := { commutes' := λ r, begin have h : (algebra_map R I.quotient) r = (quotient.mk I) (algebra_map R A r) := rfl, simpa [h] end, ..quotient_equiv I J (f : A ≃+* S) hIJ } @[priority 100] instance quotient_algebra : algebra (J.comap (algebra_map R S)).quotient J.quotient := (quotient_map J (algebra_map R S) (le_of_eq rfl)).to_algebra lemma algebra_map_quotient_injective : function.injective (algebra_map (J.comap (algebra_map R S)).quotient J.quotient) := begin rintros ⟨a⟩ ⟨b⟩ hab, replace hab := quotient.eq.mp hab, rw ← ring_hom.map_sub at hab, exact quotient.eq.mpr hab end end quotient_algebra end comm_ring end ideal namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] -- TODO: show `[algebra R A] : algebra (ideal R) A` too instance module_submodule : module (ideal R) (submodule R M) := { smul_add := smul_sup, add_smul := sup_smul, mul_smul := submodule.smul_assoc, one_smul := by simp, zero_smul := bot_smul, smul_zero := smul_bot } end submodule namespace ring_hom variables {A B C : Type*} [ring A] [ring B] [ring C] variables (f : A →+* B) (f_inv : B → A) /-- Auxiliary definition used to define `lift_of_right_inverse` -/ def lift_of_right_inverse_aux (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) : B →+* C := { to_fun := λ b, g (f_inv b), map_one' := begin rw [← g.map_one, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_one], exact hf 1 end, map_mul' := begin intros x y, rw [← g.map_mul, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_mul], simp only [hf _], end, .. add_monoid_hom.lift_of_right_inverse f.to_add_monoid_hom f_inv hf ⟨g.to_add_monoid_hom, hg⟩ } @[simp] lemma lift_of_right_inverse_aux_comp_apply (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (a : A) : (f.lift_of_right_inverse_aux f_inv hf g hg) (f a) = g a := f.to_add_monoid_hom.lift_of_right_inverse_comp_apply f_inv hf ⟨g.to_add_monoid_hom, hg⟩ a /-- `lift_of_right_inverse f hf g hg` is the unique ring homomorphism `φ` * such that `φ.comp f = g` (`ring_hom.lift_of_right_inverse_comp`), * where `f : A →+* B` is has a right_inverse `f_inv` (`hf`), * and `g : B →+* C` satisfies `hg : f.ker ≤ g.ker`. See `ring_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` A . | \ f | \ g | \ v \⌟ B ----> C ∃!φ ``` -/ def lift_of_right_inverse (hf : function.right_inverse f_inv f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) := { to_fun := λ g, f.lift_of_right_inverse_aux f_inv hf g.1 g.2, inv_fun := λ φ, ⟨φ.comp f, λ x hx, (mem_ker _).mpr $ by simp [(mem_ker _).mp hx]⟩, left_inv := λ g, by { ext, simp only [comp_apply, lift_of_right_inverse_aux_comp_apply, subtype.coe_mk, subtype.val_eq_coe], }, right_inv := λ φ, by { ext b, simp [lift_of_right_inverse_aux, hf b], } } /-- A non-computable version of `ring_hom.lift_of_right_inverse` for when no computable right inverse is available, that uses `function.surj_inv`. -/ @[simp] noncomputable abbreviation lift_of_surjective (hf : function.surjective f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) := f.lift_of_right_inverse (function.surj_inv hf) (function.right_inverse_surj_inv hf) lemma lift_of_right_inverse_comp_apply (hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) (x : A) : (f.lift_of_right_inverse f_inv hf g) (f x) = g x := f.lift_of_right_inverse_aux_comp_apply f_inv hf g.1 g.2 x lemma lift_of_right_inverse_comp (hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) : (f.lift_of_right_inverse f_inv hf g).comp f = g := ring_hom.ext $ f.lift_of_right_inverse_comp_apply f_inv hf g lemma eq_lift_of_right_inverse (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (h : B →+* C) (hh : h.comp f = g) : h = (f.lift_of_right_inverse f_inv hf ⟨g, hg⟩) := begin simp_rw ←hh, exact ((f.lift_of_right_inverse f_inv hf).apply_symm_apply _).symm, end end ring_hom
985f7152d59cd4c5334ebaee9e777795e50080ca
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/limits/over.lean
d2ddd731fa256f4b17afad0ed7cb3a7910b0abfc
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,556
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Reid Barton, Bhavik Mehta -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.over import Mathlib.category_theory.limits.preserves.basic import Mathlib.category_theory.limits.creates import Mathlib.PostPort universes u v namespace Mathlib /-! # Limits and colimits in the over and under categories Show that the forgetful functor `forget X : over X ⥤ C` creates colimits, and hence `over X` has any colimits that `C` has (as well as the dual that `forget X : under X ⟶ C` creates limits). Note that the folder `category_theory.limits.shapes.constructions.over` further shows that `forget X : over X ⥤ C` creates connected limits (so `over X` has connected limits), and that `over X` has `J`-indexed products if `C` has `J`-indexed wide pullbacks. TODO: If `C` has binary products, then `forget X : over X ⥤ C` has a right adjoint. -/ namespace category_theory.functor /-- We can interpret a functor `F` into the category of arrows with codomain `X` as a cocone over the diagram given by the domains of the arrows in the image of `F` such that the apex of the cocone is `X`. -/ @[simp] theorem to_cocone_X {J : Type v} [small_category J] {C : Type u} [category C] {X : C} (F : J ⥤ over X) : limits.cocone.X (to_cocone F) = X := Eq.refl (limits.cocone.X (to_cocone F)) /-- We can interpret a functor `F` into the category of arrows with domain `X` as a cone over the diagram given by the codomains of the arrows in the image of `F` such that the apex of the cone is `X`. -/ @[simp] theorem to_cone_X {J : Type v} [small_category J] {C : Type u} [category C] {X : C} (F : J ⥤ under X) : limits.cone.X (to_cone F) = X := Eq.refl (limits.cone.X (to_cone F)) end category_theory.functor namespace category_theory.over protected instance forget.category_theory.limits.reflects_colimits {C : Type u} [category C] {X : C} : limits.reflects_colimits (forget X) := limits.reflects_colimits.mk fun (J : Type v) (𝒥₁ : small_category J) => limits.reflects_colimits_of_shape.mk fun (F : J ⥤ over X) => limits.reflects_colimit.mk fun (c : limits.cocone F) (t : limits.is_colimit (functor.map_cocone (forget X) c)) => limits.is_colimit.mk fun (s : limits.cocone F) => hom_mk (limits.is_colimit.desc t (functor.map_cocone (forget X) s)) protected instance forget.category_theory.creates_colimits {C : Type u} [category C] {X : C} : creates_colimits (forget X) := creates_colimits.mk fun (J : Type v) (𝒥₁ : small_category J) => creates_colimits_of_shape.mk fun (K : J ⥤ over X) => creates_colimit.mk fun (c : limits.cocone (K ⋙ forget X)) (t : limits.is_colimit c) => liftable_cocone.mk (limits.cocone.mk (mk (limits.is_colimit.desc t (functor.to_cocone K))) (nat_trans.mk fun (j : J) => hom_mk (nat_trans.app (limits.cocone.ι c) j))) (limits.cocones.ext (iso.refl (limits.cocone.X (functor.map_cocone (forget X) (limits.cocone.mk (mk (limits.is_colimit.desc t (functor.to_cocone K))) (nat_trans.mk fun (j : J) => hom_mk (nat_trans.app (limits.cocone.ι c) j)))))) sorry) protected instance has_colimit {J : Type v} [small_category J] {C : Type u} [category C] {X : C} {F : J ⥤ over X} [limits.has_colimit (F ⋙ forget X)] : limits.has_colimit F := has_colimit_of_created F (forget X) protected instance has_colimits_of_shape {J : Type v} [small_category J] {C : Type u} [category C] {X : C} [limits.has_colimits_of_shape J C] : limits.has_colimits_of_shape J (over X) := limits.has_colimits_of_shape.mk fun (F : J ⥤ over X) => over.has_colimit protected instance has_colimits {C : Type u} [category C] {X : C} [limits.has_colimits C] : limits.has_colimits (over X) := limits.has_colimits.mk fun (J : Type v) (𝒥 : small_category J) => over.has_colimits_of_shape -- We can automatically infer that the forgetful functor preserves colimits end category_theory.over namespace category_theory.under protected instance forget.category_theory.limits.reflects_limits {C : Type u} [category C] {X : C} : limits.reflects_limits (forget X) := limits.reflects_limits.mk fun (J : Type v) (𝒥₁ : small_category J) => limits.reflects_limits_of_shape.mk fun (F : J ⥤ under X) => limits.reflects_limit.mk fun (c : limits.cone F) (t : limits.is_limit (functor.map_cone (forget X) c)) => limits.is_limit.mk fun (s : limits.cone F) => hom_mk (limits.is_limit.lift t (functor.map_cone (forget X) s)) protected instance forget.category_theory.creates_limits {C : Type u} [category C] {X : C} : creates_limits (forget X) := creates_limits.mk fun (J : Type v) (𝒥₁ : small_category J) => creates_limits_of_shape.mk fun (K : J ⥤ under X) => creates_limit.mk fun (c : limits.cone (K ⋙ forget X)) (t : limits.is_limit c) => liftable_cone.mk (limits.cone.mk (mk (limits.is_limit.lift t (functor.to_cone K))) (nat_trans.mk fun (j : J) => hom_mk (nat_trans.app (limits.cone.π c) j))) (limits.cones.ext (iso.refl (limits.cone.X (functor.map_cone (forget X) (limits.cone.mk (mk (limits.is_limit.lift t (functor.to_cone K))) (nat_trans.mk fun (j : J) => hom_mk (nat_trans.app (limits.cone.π c) j)))))) sorry) protected instance has_limit {J : Type v} [small_category J] {C : Type u} [category C] {X : C} {F : J ⥤ under X} [limits.has_limit (F ⋙ forget X)] : limits.has_limit F := has_limit_of_created F (forget X) protected instance has_limits_of_shape {J : Type v} [small_category J] {C : Type u} [category C] {X : C} [limits.has_limits_of_shape J C] : limits.has_limits_of_shape J (under X) := limits.has_limits_of_shape.mk fun (F : J ⥤ under X) => under.has_limit protected instance has_limits {C : Type u} [category C] {X : C} [limits.has_limits C] : limits.has_limits (under X) := limits.has_limits.mk fun (J : Type v) (𝒥 : small_category J) => under.has_limits_of_shape
c33537283386b6c984d7be492e2f6d4d34f93d23
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/convex/topology.lean
d1b587b223e4fd3fe694e26ee7c76bdb91da1559
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
19,341
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudryashov -/ import analysis.convex.jensen import analysis.normed.group.pointwise import topology.algebra.module.finite_dimension import analysis.normed_space.ray import topology.path_connected import topology.algebra.affine /-! # Topological and metric properties of convex sets We prove the following facts: * `convex.interior` : interior of a convex set is convex; * `convex.closure` : closure of a convex set is convex; * `set.finite.compact_convex_hull` : convex hull of a finite set is compact; * `set.finite.is_closed_convex_hull` : convex hull of a finite set is closed; * `convex_on_norm`, `convex_on_dist` : norm and distance to a fixed point is convex on any convex set; * `convex_on_univ_norm`, `convex_on_univ_dist` : norm and distance to a fixed point is convex on the whole space; * `convex_hull_ediam`, `convex_hull_diam` : convex hull of a set has the same (e)metric diameter as the original set; * `bounded_convex_hull` : convex hull of a set is bounded if and only if the original set is bounded. * `bounded_std_simplex`, `is_closed_std_simplex`, `compact_std_simplex`: topological properties of the standard simplex; -/ variables {ι : Type*} {E : Type*} open metric set open_locale pointwise convex lemma real.convex_iff_is_preconnected {s : set ℝ} : convex ℝ s ↔ is_preconnected s := convex_iff_ord_connected.trans is_preconnected_iff_ord_connected.symm alias real.convex_iff_is_preconnected ↔ _ is_preconnected.convex /-! ### Standard simplex -/ section std_simplex variables [fintype ι] /-- Every vector in `std_simplex 𝕜 ι` has `max`-norm at most `1`. -/ lemma std_simplex_subset_closed_ball : std_simplex ℝ ι ⊆ metric.closed_ball 0 1 := begin assume f hf, rw [metric.mem_closed_ball, dist_zero_right], refine (nnreal.coe_one ▸ nnreal.coe_le_coe.2 $ finset.sup_le $ λ x hx, _), change |f x| ≤ 1, rw [abs_of_nonneg $ hf.1 x], exact (mem_Icc_of_mem_std_simplex hf x).2 end variable (ι) /-- `std_simplex ℝ ι` is bounded. -/ lemma bounded_std_simplex : metric.bounded (std_simplex ℝ ι) := (metric.bounded_iff_subset_ball 0).2 ⟨1, std_simplex_subset_closed_ball⟩ /-- `std_simplex ℝ ι` is closed. -/ lemma is_closed_std_simplex : is_closed (std_simplex ℝ ι) := (std_simplex_eq_inter ℝ ι).symm ▸ is_closed.inter (is_closed_Inter $ λ i, is_closed_le continuous_const (continuous_apply i)) (is_closed_eq (continuous_finset_sum _ $ λ x _, continuous_apply x) continuous_const) /-- `std_simplex ℝ ι` is compact. -/ lemma compact_std_simplex : is_compact (std_simplex ℝ ι) := metric.compact_iff_closed_bounded.2 ⟨is_closed_std_simplex ι, bounded_std_simplex ι⟩ end std_simplex /-! ### Topological vector space -/ section has_continuous_const_smul variables {𝕜 : Type*} [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] [topological_space E] [topological_add_group E] [has_continuous_const_smul 𝕜 E] /-- If `s` is a convex set, then `a • interior s + b • closure s ⊆ interior s` for all `0 < a`, `0 ≤ b`, `a + b = 1`. See also `convex.combo_interior_self_subset_interior` for a weaker version. -/ lemma convex.combo_interior_closure_subset_interior {s : set E} (hs : convex 𝕜 s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) : a • interior s + b • closure s ⊆ interior s := interior_smul₀ ha.ne' s ▸ calc interior (a • s) + b • closure s ⊆ interior (a • s) + closure (b • s) : add_subset_add subset.rfl (smul_closure_subset b s) ... = interior (a • s) + b • s : by rw is_open_interior.add_closure (b • s) ... ⊆ interior (a • s + b • s) : subset_interior_add_left ... ⊆ interior s : interior_mono $ hs.set_combo_subset ha.le hb hab /-- If `s` is a convex set, then `a • interior s + b • s ⊆ interior s` for all `0 < a`, `0 ≤ b`, `a + b = 1`. See also `convex.combo_interior_closure_subset_interior` for a stronger version. -/ lemma convex.combo_interior_self_subset_interior {s : set E} (hs : convex 𝕜 s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) : a • interior s + b • s ⊆ interior s := calc a • interior s + b • s ⊆ a • interior s + b • closure s : add_subset_add subset.rfl $ image_subset _ subset_closure ... ⊆ interior s : hs.combo_interior_closure_subset_interior ha hb hab /-- If `s` is a convex set, then `a • closure s + b • interior s ⊆ interior s` for all `0 ≤ a`, `0 < b`, `a + b = 1`. See also `convex.combo_self_interior_subset_interior` for a weaker version. -/ lemma convex.combo_closure_interior_subset_interior {s : set E} (hs : convex 𝕜 s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) : a • closure s + b • interior s ⊆ interior s := by { rw add_comm, exact hs.combo_interior_closure_subset_interior hb ha (add_comm a b ▸ hab) } /-- If `s` is a convex set, then `a • s + b • interior s ⊆ interior s` for all `0 ≤ a`, `0 < b`, `a + b = 1`. See also `convex.combo_closure_interior_subset_interior` for a stronger version. -/ lemma convex.combo_self_interior_subset_interior {s : set E} (hs : convex 𝕜 s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) : a • s + b • interior s ⊆ interior s := by { rw add_comm, exact hs.combo_interior_self_subset_interior hb ha (add_comm a b ▸ hab) } lemma convex.combo_interior_closure_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ interior s) (hy : y ∈ closure s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) : a • x + b • y ∈ interior s := hs.combo_interior_closure_subset_interior ha hb hab $ add_mem_add (smul_mem_smul_set hx) (smul_mem_smul_set hy) lemma convex.combo_interior_self_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ interior s) (hy : y ∈ s) {a b : 𝕜} (ha : 0 < a) (hb : 0 ≤ b) (hab : a + b = 1) : a • x + b • y ∈ interior s := hs.combo_interior_closure_mem_interior hx (subset_closure hy) ha hb hab lemma convex.combo_closure_interior_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ closure s) (hy : y ∈ interior s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) : a • x + b • y ∈ interior s := hs.combo_closure_interior_subset_interior ha hb hab $ add_mem_add (smul_mem_smul_set hx) (smul_mem_smul_set hy) lemma convex.combo_self_interior_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ interior s) {a b : 𝕜} (ha : 0 ≤ a) (hb : 0 < b) (hab : a + b = 1) : a • x + b • y ∈ interior s := hs.combo_closure_interior_mem_interior (subset_closure hx) hy ha hb hab lemma convex.open_segment_interior_closure_subset_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ interior s) (hy : y ∈ closure s) : open_segment 𝕜 x y ⊆ interior s := begin rintro _ ⟨a, b, ha, hb, hab, rfl⟩, exact hs.combo_interior_closure_mem_interior hx hy ha hb.le hab end lemma convex.open_segment_interior_self_subset_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ interior s) (hy : y ∈ s) : open_segment 𝕜 x y ⊆ interior s := hs.open_segment_interior_closure_subset_interior hx (subset_closure hy) lemma convex.open_segment_closure_interior_subset_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ closure s) (hy : y ∈ interior s) : open_segment 𝕜 x y ⊆ interior s := begin rintro _ ⟨a, b, ha, hb, hab, rfl⟩, exact hs.combo_closure_interior_mem_interior hx hy ha.le hb hab end lemma convex.open_segment_self_interior_subset_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ interior s) : open_segment 𝕜 x y ⊆ interior s := hs.open_segment_closure_interior_subset_interior (subset_closure hx) hy /-- If `x ∈ closure s` and `y ∈ interior s`, then the segment `(x, y]` is included in `interior s`. -/ lemma convex.add_smul_sub_mem_interior' {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ closure s) (hy : y ∈ interior s) {t : 𝕜} (ht : t ∈ Ioc (0 : 𝕜) 1) : x + t • (y - x) ∈ interior s := by simpa only [sub_smul, smul_sub, one_smul, add_sub, add_comm] using hs.combo_interior_closure_mem_interior hy hx ht.1 (sub_nonneg.mpr ht.2) (add_sub_cancel'_right _ _) /-- If `x ∈ s` and `y ∈ interior s`, then the segment `(x, y]` is included in `interior s`. -/ lemma convex.add_smul_sub_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : y ∈ interior s) {t : 𝕜} (ht : t ∈ Ioc (0 : 𝕜) 1) : x + t • (y - x) ∈ interior s := hs.add_smul_sub_mem_interior' (subset_closure hx) hy ht /-- If `x ∈ closure s` and `x + y ∈ interior s`, then `x + t y ∈ interior s` for `t ∈ (0, 1]`. -/ lemma convex.add_smul_mem_interior' {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ closure s) (hy : x + y ∈ interior s) {t : 𝕜} (ht : t ∈ Ioc (0 : 𝕜) 1) : x + t • y ∈ interior s := by simpa only [add_sub_cancel'] using hs.add_smul_sub_mem_interior' hx hy ht /-- If `x ∈ s` and `x + y ∈ interior s`, then `x + t y ∈ interior s` for `t ∈ (0, 1]`. -/ lemma convex.add_smul_mem_interior {s : set E} (hs : convex 𝕜 s) {x y : E} (hx : x ∈ s) (hy : x + y ∈ interior s) {t : 𝕜} (ht : t ∈ Ioc (0 : 𝕜) 1) : x + t • y ∈ interior s := hs.add_smul_mem_interior' (subset_closure hx) hy ht /-- In a topological vector space, the interior of a convex set is convex. -/ protected lemma convex.interior {s : set E} (hs : convex 𝕜 s) : convex 𝕜 (interior s) := convex_iff_open_segment_subset.mpr $ λ x y hx hy, hs.open_segment_closure_interior_subset_interior (interior_subset_closure hx) hy /-- In a topological vector space, the closure of a convex set is convex. -/ protected lemma convex.closure {s : set E} (hs : convex 𝕜 s) : convex 𝕜 (closure s) := λ x y hx hy a b ha hb hab, let f : E → E → E := λ x' y', a • x' + b • y' in have hf : continuous (λ p : E × E, f p.1 p.2), from (continuous_fst.const_smul _).add (continuous_snd.const_smul _), show f x y ∈ closure s, from mem_closure_of_continuous2 hf hx hy (λ x' hx' y' hy', subset_closure (hs hx' hy' ha hb hab)) end has_continuous_const_smul section has_continuous_smul variables [add_comm_group E] [module ℝ E] [topological_space E] [topological_add_group E] [has_continuous_smul ℝ E] /-- Convex hull of a finite set is compact. -/ lemma set.finite.compact_convex_hull {s : set E} (hs : s.finite) : is_compact (convex_hull ℝ s) := begin rw [hs.convex_hull_eq_image], apply (compact_std_simplex _).image, haveI := hs.fintype, apply linear_map.continuous_on_pi end /-- Convex hull of a finite set is closed. -/ lemma set.finite.is_closed_convex_hull [t2_space E] {s : set E} (hs : s.finite) : is_closed (convex_hull ℝ s) := hs.compact_convex_hull.is_closed open affine_map /-- If we dilate the interior of a convex set about a point in its interior by a scale `t > 1`, the result includes the closure of the original set. TODO Generalise this from convex sets to sets that are balanced / star-shaped about `x`. -/ lemma convex.closure_subset_image_homothety_interior_of_one_lt {s : set E} (hs : convex ℝ s) {x : E} (hx : x ∈ interior s) (t : ℝ) (ht : 1 < t) : closure s ⊆ homothety x t '' interior s := begin intros y hy, have hne : t ≠ 0, from (one_pos.trans ht).ne', refine ⟨homothety x t⁻¹ y, hs.open_segment_interior_closure_subset_interior hx hy _, (affine_equiv.homothety_units_mul_hom x (units.mk0 t hne)).apply_symm_apply y⟩, rw [open_segment_eq_image_line_map, ← inv_one, ← inv_Ioi (@one_pos ℝ _ _), ← image_inv, image_image, homothety_eq_line_map], exact mem_image_of_mem _ ht end /-- If we dilate a convex set about a point in its interior by a scale `t > 1`, the interior of the result includes the closure of the original set. TODO Generalise this from convex sets to sets that are balanced / star-shaped about `x`. -/ lemma convex.closure_subset_interior_image_homothety_of_one_lt {s : set E} (hs : convex ℝ s) {x : E} (hx : x ∈ interior s) (t : ℝ) (ht : 1 < t) : closure s ⊆ interior (homothety x t '' s) := (hs.closure_subset_image_homothety_interior_of_one_lt hx t ht).trans $ (homothety_is_open_map x t (one_pos.trans ht).ne').image_interior_subset _ /-- If we dilate a convex set about a point in its interior by a scale `t > 1`, the interior of the result includes the closure of the original set. TODO Generalise this from convex sets to sets that are balanced / star-shaped about `x`. -/ lemma convex.subset_interior_image_homothety_of_one_lt {s : set E} (hs : convex ℝ s) {x : E} (hx : x ∈ interior s) (t : ℝ) (ht : 1 < t) : s ⊆ interior (homothety x t '' s) := subset_closure.trans $ hs.closure_subset_interior_image_homothety_of_one_lt hx t ht /-- A nonempty convex set is path connected. -/ protected lemma convex.is_path_connected {s : set E} (hconv : convex ℝ s) (hne : s.nonempty) : is_path_connected s := begin refine is_path_connected_iff.mpr ⟨hne, _⟩, intros x x_in y y_in, have H := hconv.segment_subset x_in y_in, rw segment_eq_image_line_map at H, exact joined_in.of_line affine_map.line_map_continuous.continuous_on (line_map_apply_zero _ _) (line_map_apply_one _ _) H end /-- A nonempty convex set is connected. -/ protected lemma convex.is_connected {s : set E} (h : convex ℝ s) (hne : s.nonempty) : is_connected s := (h.is_path_connected hne).is_connected /-- A convex set is preconnected. -/ protected lemma convex.is_preconnected {s : set E} (h : convex ℝ s) : is_preconnected s := s.eq_empty_or_nonempty.elim (λ h, h.symm ▸ is_preconnected_empty) (λ hne, (h.is_connected hne).is_preconnected) /-- Every topological vector space over ℝ is path connected. Not an instance, because it creates enormous TC subproblems (turn on `pp.all`). -/ protected lemma topological_add_group.path_connected : path_connected_space E := path_connected_space_iff_univ.mpr $ convex_univ.is_path_connected ⟨(0 : E), trivial⟩ end has_continuous_smul /-! ### Normed vector space -/ section normed_space variables [seminormed_add_comm_group E] [normed_space ℝ E] {s t : set E} /-- The norm on a real normed space is convex on any convex set. See also `seminorm.convex_on` and `convex_on_univ_norm`. -/ lemma convex_on_norm (hs : convex ℝ s) : convex_on ℝ s norm := ⟨hs, λ x y hx hy a b ha hb hab, calc ∥a • x + b • y∥ ≤ ∥a • x∥ + ∥b • y∥ : norm_add_le _ _ ... = a * ∥x∥ + b * ∥y∥ : by rw [norm_smul, norm_smul, real.norm_of_nonneg ha, real.norm_of_nonneg hb]⟩ /-- The norm on a real normed space is convex on the whole space. See also `seminorm.convex_on` and `convex_on_norm`. -/ lemma convex_on_univ_norm : convex_on ℝ univ (norm : E → ℝ) := convex_on_norm convex_univ lemma convex_on_dist (z : E) (hs : convex ℝ s) : convex_on ℝ s (λ z', dist z' z) := by simpa [dist_eq_norm, preimage_preimage] using (convex_on_norm (hs.translate (-z))).comp_affine_map (affine_map.id ℝ E - affine_map.const ℝ E z) lemma convex_on_univ_dist (z : E) : convex_on ℝ univ (λz', dist z' z) := convex_on_dist z convex_univ lemma convex_ball (a : E) (r : ℝ) : convex ℝ (metric.ball a r) := by simpa only [metric.ball, sep_univ] using (convex_on_univ_dist a).convex_lt r lemma convex_closed_ball (a : E) (r : ℝ) : convex ℝ (metric.closed_ball a r) := by simpa only [metric.closed_ball, sep_univ] using (convex_on_univ_dist a).convex_le r lemma convex.thickening (hs : convex ℝ s) (δ : ℝ) : convex ℝ (thickening δ s) := by { rw ←add_ball_zero, exact hs.add (convex_ball 0 _) } lemma convex.cthickening (hs : convex ℝ s) (δ : ℝ) : convex ℝ (cthickening δ s) := begin obtain hδ | hδ := le_total 0 δ, { rw cthickening_eq_Inter_thickening hδ, exact convex_Inter₂ (λ _ _, hs.thickening _) }, { rw cthickening_of_nonpos hδ, exact hs.closure } end /-- If `s`, `t` are disjoint convex sets, `s` is compact and `t` is closed then we can find open disjoint convex sets containing them. -/ lemma disjoint.exists_open_convexes (disj : disjoint s t) (hs₁ : convex ℝ s) (hs₂ : is_compact s) (ht₁ : convex ℝ t) (ht₂ : is_closed t) : ∃ u v, is_open u ∧ is_open v ∧ convex ℝ u ∧ convex ℝ v ∧ s ⊆ u ∧ t ⊆ v ∧ disjoint u v := let ⟨δ, hδ, hst⟩ := disj.exists_thickenings hs₂ ht₂ in ⟨_, _, is_open_thickening, is_open_thickening, hs₁.thickening _, ht₁.thickening _, self_subset_thickening hδ _, self_subset_thickening hδ _, hst⟩ /-- Given a point `x` in the convex hull of `s` and a point `y`, there exists a point of `s` at distance at least `dist x y` from `y`. -/ lemma convex_hull_exists_dist_ge {s : set E} {x : E} (hx : x ∈ convex_hull ℝ s) (y : E) : ∃ x' ∈ s, dist x y ≤ dist x' y := (convex_on_dist y (convex_convex_hull ℝ _)).exists_ge_of_mem_convex_hull hx /-- Given a point `x` in the convex hull of `s` and a point `y` in the convex hull of `t`, there exist points `x' ∈ s` and `y' ∈ t` at distance at least `dist x y`. -/ lemma convex_hull_exists_dist_ge2 {s t : set E} {x y : E} (hx : x ∈ convex_hull ℝ s) (hy : y ∈ convex_hull ℝ t) : ∃ (x' ∈ s) (y' ∈ t), dist x y ≤ dist x' y' := begin rcases convex_hull_exists_dist_ge hx y with ⟨x', hx', Hx'⟩, rcases convex_hull_exists_dist_ge hy x' with ⟨y', hy', Hy'⟩, use [x', hx', y', hy'], exact le_trans Hx' (dist_comm y x' ▸ dist_comm y' x' ▸ Hy') end /-- Emetric diameter of the convex hull of a set `s` equals the emetric diameter of `s. -/ @[simp] lemma convex_hull_ediam (s : set E) : emetric.diam (convex_hull ℝ s) = emetric.diam s := begin refine (emetric.diam_le $ λ x hx y hy, _).antisymm (emetric.diam_mono $ subset_convex_hull ℝ s), rcases convex_hull_exists_dist_ge2 hx hy with ⟨x', hx', y', hy', H⟩, rw edist_dist, apply le_trans (ennreal.of_real_le_of_real H), rw ← edist_dist, exact emetric.edist_le_diam_of_mem hx' hy' end /-- Diameter of the convex hull of a set `s` equals the emetric diameter of `s. -/ @[simp] lemma convex_hull_diam (s : set E) : metric.diam (convex_hull ℝ s) = metric.diam s := by simp only [metric.diam, convex_hull_ediam] /-- Convex hull of `s` is bounded if and only if `s` is bounded. -/ @[simp] lemma bounded_convex_hull {s : set E} : metric.bounded (convex_hull ℝ s) ↔ metric.bounded s := by simp only [metric.bounded_iff_ediam_ne_top, convex_hull_ediam] @[priority 100] instance normed_space.path_connected : path_connected_space E := topological_add_group.path_connected @[priority 100] instance normed_space.loc_path_connected : loc_path_connected_space E := loc_path_connected_of_bases (λ x, metric.nhds_basis_ball) (λ x r r_pos, (convex_ball x r).is_path_connected $ by simp [r_pos]) lemma dist_add_dist_of_mem_segment {x y z : E} (h : y ∈ [x -[ℝ] z]) : dist x y + dist y z = dist x z := begin simp only [dist_eq_norm, mem_segment_iff_same_ray] at *, simpa only [sub_add_sub_cancel', norm_sub_rev] using h.norm_add.symm end end normed_space
b8e5dd87602c4e1df1f0c9e19c656c6c4f65113b
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Lean/Compiler/IR/FreeVars.lean
b9560361d92c719b8447e537045460689434f4e1
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
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 -/ import Lean.Compiler.IR.Basic namespace Lean.IR namespace MaxIndex /- Compute the maximum index `M` used in a declaration. We `M` to initialize the fresh index generator used to create fresh variable and join point names. Recall that we variable and join points share the same namespace in our implementation. -/ abbrev Collector := Index → Index @[inline] private def skip : Collector := id @[inline] private def collect (x : Index) : Collector := fun y => if x > y then x else y @[inline] private def collectVar (x : VarId) : Collector := collect x.idx @[inline] private def collectJP (j : JoinPointId) : Collector := collect j.idx @[inline] private def seq (k₁ k₂ : Collector) : Collector := k₂ ∘ k₁ instance : AndThen Collector := ⟨seq⟩ private def collectArg : Arg → Collector | Arg.var x => collectVar x | irrelevant => skip @[specialize] private def collectArray {α : Type} (as : Array α) (f : α → Collector) : Collector := fun m => as.foldl (fun m a => f a m) m private def collectArgs (as : Array Arg) : Collector := collectArray as collectArg private def collectParam (p : Param) : Collector := collectVar p.x private def collectParams (ps : Array Param) : Collector := collectArray ps collectParam private def collectExpr : Expr → Collector | Expr.ctor _ ys => collectArgs ys | Expr.reset _ x => collectVar x | Expr.reuse x _ _ ys => collectVar x >> collectArgs ys | Expr.proj _ x => collectVar x | Expr.uproj _ x => collectVar x | Expr.sproj _ _ x => collectVar x | Expr.fap _ ys => collectArgs ys | Expr.pap _ ys => collectArgs ys | Expr.ap x ys => collectVar x >> collectArgs ys | Expr.box _ x => collectVar x | Expr.unbox x => collectVar x | Expr.lit v => skip | Expr.isShared x => collectVar x | Expr.isTaggedPtr x => collectVar x private def collectAlts (f : FnBody → Collector) (alts : Array Alt) : Collector := collectArray alts $ fun alt => f alt.body partial def collectFnBody : FnBody → Collector | FnBody.vdecl x _ v b => collectVar x >> collectExpr v >> collectFnBody b | FnBody.jdecl j ys v b => collectJP j >> collectFnBody v >> collectParams ys >> collectFnBody b | FnBody.set x _ y b => collectVar x >> collectArg y >> collectFnBody b | FnBody.uset x _ y b => collectVar x >> collectVar y >> collectFnBody b | FnBody.sset x _ _ y _ b => collectVar x >> collectVar y >> collectFnBody b | FnBody.setTag x _ b => collectVar x >> collectFnBody b | FnBody.inc x _ _ _ b => collectVar x >> collectFnBody b | FnBody.dec x _ _ _ b => collectVar x >> collectFnBody b | FnBody.del x b => collectVar x >> collectFnBody b | FnBody.mdata _ b => collectFnBody b | FnBody.case _ x _ alts => collectVar x >> collectAlts collectFnBody alts | FnBody.jmp j ys => collectJP j >> collectArgs ys | FnBody.ret x => collectArg x | FnBody.unreachable => skip partial def collectDecl : Decl → Collector | Decl.fdecl _ xs _ b => collectParams xs >> collectFnBody b | Decl.extern _ xs _ _ => collectParams xs end MaxIndex def FnBody.maxIndex (b : FnBody) : Index := MaxIndex.collectFnBody b 0 def Decl.maxIndex (d : Decl) : Index := MaxIndex.collectDecl d 0 namespace FreeIndices /- We say a variable (join point) index (aka name) is free in a function body if there isn't a `FnBody.vdecl` (`Fnbody.jdecl`) binding it. -/ abbrev Collector := IndexSet → IndexSet → IndexSet @[inline] private def skip : Collector := fun bv fv => fv @[inline] private def collectIndex (x : Index) : Collector := fun bv fv => if bv.contains x then fv else fv.insert x @[inline] private def collectVar (x : VarId) : Collector := collectIndex x.idx @[inline] private def collectJP (x : JoinPointId) : Collector := collectIndex x.idx @[inline] private def withIndex (x : Index) : Collector → Collector := fun k bv fv => k (bv.insert x) fv @[inline] private def withVar (x : VarId) : Collector → Collector := withIndex x.idx @[inline] private def withJP (x : JoinPointId) : Collector → Collector := withIndex x.idx def insertParams (s : IndexSet) (ys : Array Param) : IndexSet := ys.foldl (init := s) fun s p => s.insert p.x.idx @[inline] private def withParams (ys : Array Param) : Collector → Collector := fun k bv fv => k (insertParams bv ys) fv @[inline] private def seq : Collector → Collector → Collector := fun k₁ k₂ bv fv => k₂ bv (k₁ bv fv) instance : AndThen Collector := ⟨seq⟩ private def collectArg : Arg → Collector | Arg.var x => collectVar x | irrelevant => skip @[specialize] private def collectArray {α : Type} (as : Array α) (f : α → Collector) : Collector := fun bv fv => as.foldl (fun fv a => f a bv fv) fv private def collectArgs (as : Array Arg) : Collector := collectArray as collectArg private def collectExpr : Expr → Collector | Expr.ctor _ ys => collectArgs ys | Expr.reset _ x => collectVar x | Expr.reuse x _ _ ys => collectVar x >> collectArgs ys | Expr.proj _ x => collectVar x | Expr.uproj _ x => collectVar x | Expr.sproj _ _ x => collectVar x | Expr.fap _ ys => collectArgs ys | Expr.pap _ ys => collectArgs ys | Expr.ap x ys => collectVar x >> collectArgs ys | Expr.box _ x => collectVar x | Expr.unbox x => collectVar x | Expr.lit v => skip | Expr.isShared x => collectVar x | Expr.isTaggedPtr x => collectVar x private def collectAlts (f : FnBody → Collector) (alts : Array Alt) : Collector := collectArray alts $ fun alt => f alt.body partial def collectFnBody : FnBody → Collector | FnBody.vdecl x _ v b => collectExpr v >> withVar x (collectFnBody b) | FnBody.jdecl j ys v b => withParams ys (collectFnBody v) >> withJP j (collectFnBody b) | FnBody.set x _ y b => collectVar x >> collectArg y >> collectFnBody b | FnBody.uset x _ y b => collectVar x >> collectVar y >> collectFnBody b | FnBody.sset x _ _ y _ b => collectVar x >> collectVar y >> collectFnBody b | FnBody.setTag x _ b => collectVar x >> collectFnBody b | FnBody.inc x _ _ _ b => collectVar x >> collectFnBody b | FnBody.dec x _ _ _ b => collectVar x >> collectFnBody b | FnBody.del x b => collectVar x >> collectFnBody b | FnBody.mdata _ b => collectFnBody b | FnBody.case _ x _ alts => collectVar x >> collectAlts collectFnBody alts | FnBody.jmp j ys => collectJP j >> collectArgs ys | FnBody.ret x => collectArg x | FnBody.unreachable => skip end FreeIndices def FnBody.collectFreeIndices (b : FnBody) (vs : IndexSet) : IndexSet := FreeIndices.collectFnBody b {} vs def FnBody.freeIndices (b : FnBody) : IndexSet := b.collectFreeIndices {} namespace HasIndex /- In principle, we can check whether a function body `b` contains an index `i` using `b.freeIndices.contains i`, but it is more efficient to avoid the construction of the set of freeIndices and just search whether `i` occurs in `b` or not. -/ def visitVar (w : Index) (x : VarId) : Bool := w == x.idx def visitJP (w : Index) (x : JoinPointId) : Bool := w == x.idx def visitArg (w : Index) : Arg → Bool | Arg.var x => visitVar w x | _ => false def visitArgs (w : Index) (xs : Array Arg) : Bool := xs.any (visitArg w) def visitParams (w : Index) (ps : Array Param) : Bool := ps.any (fun p => w == p.x.idx) def visitExpr (w : Index) : Expr → Bool | Expr.ctor _ ys => visitArgs w ys | Expr.reset _ x => visitVar w x | Expr.reuse x _ _ ys => visitVar w x || visitArgs w ys | Expr.proj _ x => visitVar w x | Expr.uproj _ x => visitVar w x | Expr.sproj _ _ x => visitVar w x | Expr.fap _ ys => visitArgs w ys | Expr.pap _ ys => visitArgs w ys | Expr.ap x ys => visitVar w x || visitArgs w ys | Expr.box _ x => visitVar w x | Expr.unbox x => visitVar w x | Expr.lit v => false | Expr.isShared x => visitVar w x | Expr.isTaggedPtr x => visitVar w x partial def visitFnBody (w : Index) : FnBody → Bool | FnBody.vdecl x _ v b => visitExpr w v || visitFnBody w b | FnBody.jdecl j ys v b => visitFnBody w v || visitFnBody w b | FnBody.set x _ y b => visitVar w x || visitArg w y || visitFnBody w b | FnBody.uset x _ y b => visitVar w x || visitVar w y || visitFnBody w b | FnBody.sset x _ _ y _ b => visitVar w x || visitVar w y || visitFnBody w b | FnBody.setTag x _ b => visitVar w x || visitFnBody w b | FnBody.inc x _ _ _ b => visitVar w x || visitFnBody w b | FnBody.dec x _ _ _ b => visitVar w x || visitFnBody w b | FnBody.del x b => visitVar w x || visitFnBody w b | FnBody.mdata _ b => visitFnBody w b | FnBody.jmp j ys => visitJP w j || visitArgs w ys | FnBody.ret x => visitArg w x | FnBody.case _ x _ alts => visitVar w x || alts.any (fun alt => visitFnBody w alt.body) | FnBody.unreachable => false end HasIndex def Arg.hasFreeVar (arg : Arg) (x : VarId) : Bool := HasIndex.visitArg x.idx arg def Expr.hasFreeVar (e : Expr) (x : VarId) : Bool := HasIndex.visitExpr x.idx e def FnBody.hasFreeVar (b : FnBody) (x : VarId) : Bool := HasIndex.visitFnBody x.idx b end Lean.IR
e4154a3afdb6aae9792d4ad48e1dfb8a1b9875fb
626e312b5c1cb2d88fca108f5933076012633192
/src/data/equiv/basic.lean
ad998331876e3ebc6d6c435adf68de52d1294447
[ "Apache-2.0" ]
permissive
Bioye97/mathlib
9db2f9ee54418d29dd06996279ba9dc874fd6beb
782a20a27ee83b523f801ff34efb1a9557085019
refs/heads/master
1,690,305,956,488
1,631,067,774,000
1,631,067,774,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
104,437
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro -/ import data.set.function import data.sigma.basic /-! # Equivalence between types In this file we define two types: * `equiv α β` a.k.a. `α ≃ β`: a bijective map `α → β` bundled with its inverse map; we use this (and not equality!) to express that various `Type`s or `Sort`s are equivalent. * `equiv.perm α`: the group of permutations `α ≃ α`. More lemmas about `equiv.perm` can be found in `group_theory/perm`. Then we define * canonical isomorphisms between various types: e.g., - `equiv.refl α` is the identity map interpreted as `α ≃ α`; - `equiv.sum_equiv_sigma_bool` is the canonical equivalence between the sum of two types `α ⊕ β` and the sigma-type `Σ b : bool, cond b α β`; - `equiv.prod_sum_distrib : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ)` shows that type product and type sum satisfy the distributive law up to a canonical equivalence; * operations on equivalences: e.g., - `equiv.symm e : β ≃ α` is the inverse of `e : α ≃ β`; - `equiv.trans e₁ e₂ : α ≃ γ` is the composition of `e₁ : α ≃ β` and `e₂ : β ≃ γ` (note the order of the arguments!); - `equiv.prod_congr ea eb : α₁ × β₁ ≃ α₂ × β₂`: combine two equivalences `ea : α₁ ≃ α₂` and `eb : β₁ ≃ β₂` using `prod.map`. * definitions that transfer some instances along an equivalence. By convention, we transfer instances from right to left. - `equiv.inhabited` takes `e : α ≃ β` and `[inhabited β]` and returns `inhabited α`; - `equiv.unique` takes `e : α ≃ β` and `[unique β]` and returns `unique α`; - `equiv.decidable_eq` takes `e : α ≃ β` and `[decidable_eq β]` and returns `decidable_eq α`. More definitions of this kind can be found in other files. E.g., `data/equiv/transfer_instance` does it for many algebraic type classes like `group`, `module`, etc. ## Tags equivalence, congruence, bijective map -/ open function universes u v w z variables {α : Sort u} {β : Sort v} {γ : Sort w} /-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/ @[nolint has_inhabited_instance] structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) infix ` ≃ `:25 := equiv /-- Convert an involutive function `f` to an equivalence with `to_fun = inv_fun = f`. -/ def function.involutive.to_equiv (f : α → α) (h : involutive f) : α ≃ α := ⟨f, f, h.left_inverse, h.right_inverse⟩ namespace equiv /-- `perm α` is the type of bijections from `α` to itself. -/ @[reducible] def perm (α : Sort*) := equiv α α instance : has_coe_to_fun (α ≃ β) := ⟨_, to_fun⟩ @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f := rfl /-- The map `coe_fn : (r ≃ s) → (r → s)` is injective. -/ theorem coe_fn_injective : @function.injective (α ≃ β) (α → β) coe_fn | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h := have f₁ = f₂, from h, have g₁ = g₂, from l₁.eq_right_inverse (this.symm ▸ r₂), by simp * @[simp, norm_cast] protected lemma coe_inj {e₁ e₂ : α ≃ β} : ⇑e₁ = e₂ ↔ e₁ = e₂ := coe_fn_injective.eq_iff @[ext] lemma ext {f g : equiv α β} (H : ∀ x, f x = g x) : f = g := coe_fn_injective (funext H) protected lemma congr_arg {f : equiv α β} : Π {x x' : α}, x = x' → f x = f x' | _ _ rfl := rfl protected lemma congr_fun {f g : equiv α β} (h : f = g) (x : α) : f x = g x := h ▸ rfl lemma ext_iff {f g : equiv α β} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, ext⟩ @[ext] lemma perm.ext {σ τ : equiv.perm α} (H : ∀ x, σ x = τ x) : σ = τ := equiv.ext H protected lemma perm.congr_arg {f : equiv.perm α} {x x' : α} : x = x' → f x = f x' := equiv.congr_arg protected lemma perm.congr_fun {f g : equiv.perm α} (h : f = g) (x : α) : f x = g x := equiv.congr_fun h x lemma perm.ext_iff {σ τ : equiv.perm α} : σ = τ ↔ ∀ x, σ x = τ x := ext_iff /-- Any type is equivalent to itself. -/ @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩ instance inhabited' : inhabited (α ≃ α) := ⟨equiv.refl α⟩ /-- Inverse of an equivalence `e : α ≃ β`. -/ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ /-- See Note [custom simps projection] -/ def simps.symm_apply (e : α ≃ β) : β → α := e.symm initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply) -- Generate the `simps` projections for previously defined equivs. attribute [simps] function.involutive.to_equiv /-- Composition of equivalences `e₁ : α ≃ β` and `e₂ : β ≃ γ`. -/ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ @[simp] lemma to_fun_as_coe (e : α ≃ β) : e.to_fun = e := rfl @[simp] lemma inv_fun_as_coe (e : α ≃ β) : e.inv_fun = e.symm := rfl protected theorem injective (e : α ≃ β) : injective e := e.left_inv.injective protected theorem surjective (e : α ≃ β) : surjective e := e.right_inv.surjective protected theorem bijective (f : α ≃ β) : bijective f := ⟨f.injective, f.surjective⟩ @[simp] lemma range_eq_univ {α : Type*} {β : Type*} (e : α ≃ β) : set.range e = set.univ := set.eq_univ_of_forall e.surjective protected theorem subsingleton (e : α ≃ β) [subsingleton β] : subsingleton α := e.injective.subsingleton protected theorem subsingleton.symm (e : α ≃ β) [subsingleton α] : subsingleton β := e.symm.injective.subsingleton lemma subsingleton_congr (e : α ≃ β) : subsingleton α ↔ subsingleton β := ⟨λ h, by exactI e.symm.subsingleton, λ h, by exactI e.subsingleton⟩ instance equiv_subsingleton_cod [subsingleton β] : subsingleton (α ≃ β) := ⟨λ f g, equiv.ext $ λ x, subsingleton.elim _ _⟩ instance equiv_subsingleton_dom [subsingleton α] : subsingleton (α ≃ β) := ⟨λ f g, equiv.ext $ λ x, @subsingleton.elim _ (equiv.subsingleton.symm f) _ _⟩ instance perm_unique [subsingleton α] : unique (perm α) := unique_of_subsingleton (equiv.refl α) lemma perm.subsingleton_eq_refl [subsingleton α] (e : perm α) : e = equiv.refl α := subsingleton.elim _ _ /-- Transfer `decidable_eq` across an equivalence. -/ protected def decidable_eq (e : α ≃ β) [decidable_eq β] : decidable_eq α := e.injective.decidable_eq lemma nonempty_congr (e : α ≃ β) : nonempty α ↔ nonempty β := nonempty.congr e e.symm protected lemma nonempty (e : α ≃ β) [nonempty β] : nonempty α := e.nonempty_congr.mpr ‹_› /-- If `α ≃ β` and `β` is inhabited, then so is `α`. -/ protected def inhabited [inhabited β] (e : α ≃ β) : inhabited α := ⟨e.symm (default _)⟩ /-- If `α ≃ β` and `β` is a singleton type, then so is `α`. -/ protected def unique [unique β] (e : α ≃ β) : unique α := e.symm.surjective.unique /-- Equivalence between equal types. -/ protected def cast {α β : Sort*} (h : α = β) : α ≃ β := ⟨cast h, cast h.symm, λ x, by { cases h, refl }, λ x, by { cases h, refl }⟩ @[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g := rfl @[simp] theorem coe_refl : ⇑(equiv.refl α) = id := rfl @[simp] theorem perm.coe_subsingleton {α : Type*} [subsingleton α] (e : perm α) : ⇑(e) = id := by rw [perm.subsingleton_eq_refl e, coe_refl] theorem refl_apply (x : α) : equiv.refl α x = x := rfl @[simp] theorem coe_trans (f : α ≃ β) (g : β ≃ γ) : ⇑(f.trans g) = g ∘ f := rfl theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_symm_apply (e : α ≃ β) (x : β) : e (e.symm x) = x := e.right_inv x @[simp] theorem symm_apply_apply (e : α ≃ β) (x : α) : e.symm (e x) = x := e.left_inv x @[simp] theorem symm_comp_self (e : α ≃ β) : e.symm ∘ e = id := funext e.symm_apply_apply @[simp] theorem self_comp_symm (e : α ≃ β) : e ∘ e.symm = id := funext e.apply_symm_apply @[simp] lemma symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) : (f.trans g).symm a = f.symm (g.symm a) := rfl -- The `simp` attribute is needed to make this a `dsimp` lemma. -- `simp` will always rewrite with `equiv.symm_symm` before this has a chance to fire. @[simp, nolint simp_nf] theorem symm_symm_apply (f : α ≃ β) (b : α) : f.symm.symm b = f b := rfl @[simp] theorem apply_eq_iff_eq (f : α ≃ β) {x y : α} : f x = f y ↔ x = y := f.injective.eq_iff theorem apply_eq_iff_eq_symm_apply {α β : Sort*} (f : α ≃ β) {x : α} {y : β} : f x = y ↔ x = f.symm y := begin conv_lhs { rw ←apply_symm_apply f y, }, rw apply_eq_iff_eq, end @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl @[simp] theorem cast_symm {α β} (h : α = β) : (equiv.cast h).symm = equiv.cast h.symm := rfl @[simp] theorem cast_refl {α} (h : α = α := rfl) : equiv.cast h = equiv.refl α := rfl @[simp] theorem cast_trans {α β γ} (h : α = β) (h2 : β = γ) : (equiv.cast h).trans (equiv.cast h2) = equiv.cast (h.trans h2) := ext $ λ x, by { substs h h2, refl } lemma cast_eq_iff_heq {α β} (h : α = β) {a : α} {b : β} : equiv.cast h a = b ↔ a == b := by { subst h, simp } lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x := (eq_comm.trans e.symm_apply_eq).trans eq_comm @[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by { cases e, refl } @[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by { cases e, refl } @[simp] theorem refl_symm : (equiv.refl α).symm = equiv.refl α := rfl @[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by { cases e, refl } @[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext (by simp) @[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext (by simp) lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) : (ab.trans bc).trans cd = ab.trans (bc.trans cd) := equiv.ext $ assume a, rfl theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv @[simp] lemma injective_comp (e : α ≃ β) (f : β → γ) : injective (f ∘ e) ↔ injective f := injective.of_comp_iff' f e.bijective @[simp] lemma comp_injective (f : α → β) (e : β ≃ γ) : injective (e ∘ f) ↔ injective f := e.injective.of_comp_iff f @[simp] lemma surjective_comp (e : α ≃ β) (f : β → γ) : surjective (f ∘ e) ↔ surjective f := e.surjective.of_comp_iff f @[simp] lemma comp_surjective (f : α → β) (e : β ≃ γ) : surjective (e ∘ f) ↔ surjective f := surjective.of_comp_iff' e.bijective f @[simp] lemma bijective_comp (e : α ≃ β) (f : β → γ) : bijective (f ∘ e) ↔ bijective f := e.bijective.of_comp_iff f @[simp] lemma comp_bijective (f : α → β) (e : β ≃ γ) : bijective (e ∘ f) ↔ bijective f := bijective.of_comp_iff' e.bijective f /-- If `α` is equivalent to `β` and `γ` is equivalent to `δ`, then the type of equivalences `α ≃ γ` is equivalent to the type of equivalences `β ≃ δ`. -/ def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) := ⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm, assume ac, by { ext x, simp }, assume ac, by { ext x, simp } ⟩ @[simp] lemma equiv_congr_refl {α β} : (equiv.refl α).equiv_congr (equiv.refl β) = equiv.refl (α ≃ β) := by { ext, refl } @[simp] lemma equiv_congr_symm {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (ab.equiv_congr cd).symm = ab.symm.equiv_congr cd.symm := by { ext, refl } @[simp] lemma equiv_congr_trans {δ ε ζ} (ab : α ≃ β) (de : δ ≃ ε) (bc : β ≃ γ) (ef : ε ≃ ζ) : (ab.equiv_congr de).trans (bc.equiv_congr ef) = (ab.trans bc).equiv_congr (de.trans ef) := by { ext, refl } @[simp] lemma equiv_congr_refl_left {α β γ} (bg : β ≃ γ) (e : α ≃ β) : (equiv.refl α).equiv_congr bg e = e.trans bg := rfl @[simp] lemma equiv_congr_refl_right {α β} (ab e : α ≃ β) : ab.equiv_congr (equiv.refl β) e = ab.symm.trans e := rfl @[simp] lemma equiv_congr_apply_apply {δ} (ab : α ≃ β) (cd : γ ≃ δ) (e : α ≃ γ) (x) : ab.equiv_congr cd e x = cd (e (ab.symm x)) := rfl section perm_congr variables {α' β' : Type*} (e : α' ≃ β') /-- If `α` is equivalent to `β`, then `perm α` is equivalent to `perm β`. -/ def perm_congr : perm α' ≃ perm β' := equiv_congr e e lemma perm_congr_def (p : equiv.perm α') : e.perm_congr p = (e.symm.trans p).trans e := rfl @[simp] lemma perm_congr_refl : e.perm_congr (equiv.refl _) = equiv.refl _ := by simp [perm_congr_def] @[simp] lemma perm_congr_symm : e.perm_congr.symm = e.symm.perm_congr := rfl @[simp] lemma perm_congr_apply (p : equiv.perm α') (x) : e.perm_congr p x = e (p (e.symm x)) := rfl lemma perm_congr_symm_apply (p : equiv.perm β') (x) : e.perm_congr.symm p x = e.symm (p (e x)) := rfl lemma perm_congr_trans (p p' : equiv.perm α') : (e.perm_congr p).trans (e.perm_congr p') = e.perm_congr (p.trans p') := by { ext, simp } end perm_congr protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv lemma _root_.set.mem_image_equiv {α β} {S : set α} {f : α ≃ β} {x : β} : x ∈ f '' S ↔ f.symm x ∈ S := set.ext_iff.mp (f.image_eq_preimage S) x /-- Alias for `equiv.image_eq_preimage` -/ lemma _root_.set.image_equiv_eq_preimage_symm {α β} (S : set α) (f : α ≃ β) : f '' S = f.symm ⁻¹' S := f.image_eq_preimage S /-- Alias for `equiv.image_eq_preimage` -/ lemma _root_.set.preimage_equiv_eq_image_symm {α β} (S : set α) (f : β ≃ α) : f ⁻¹' S = f.symm '' S := (f.symm.image_eq_preimage S).symm protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ e '' s ↔ e.symm '' t ⊆ s := by rw [set.image_subset_iff, e.image_eq_preimage] @[simp] lemma symm_image_image {α β} (e : α ≃ β) (s : set α) : e.symm '' (e '' s) = s := e.left_inverse_symm.image_image s lemma eq_image_iff_symm_image_eq {α β} (e : α ≃ β) (s : set α) (t : set β) : t = e '' s ↔ e.symm '' t = s := (e.symm.injective.image_injective.eq_iff' (e.symm_image_image s)).symm @[simp] lemma image_symm_image {α β} (e : α ≃ β) (s : set β) : e '' (e.symm '' s) = s := e.symm.symm_image_image s @[simp] lemma image_preimage {α β} (e : α ≃ β) (s : set β) : e '' (e ⁻¹' s) = s := e.surjective.image_preimage s @[simp] lemma preimage_image {α β} (e : α ≃ β) (s : set α) : e ⁻¹' (e '' s) = s := e.injective.preimage_image s protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' sᶜ = (f '' s)ᶜ := set.image_compl_eq f.bijective @[simp] lemma symm_preimage_preimage {α β} (e : α ≃ β) (s : set β) : e.symm ⁻¹' (e ⁻¹' s) = s := e.right_inverse_symm.preimage_preimage s @[simp] lemma preimage_symm_preimage {α β} (e : α ≃ β) (s : set α) : e ⁻¹' (e.symm ⁻¹' s) = s := e.left_inverse_symm.preimage_preimage s @[simp] lemma preimage_subset {α β} (e : α ≃ β) (s t : set β) : e ⁻¹' s ⊆ e ⁻¹' t ↔ s ⊆ t := e.surjective.preimage_subset_preimage_iff @[simp] lemma image_subset {α β} (e : α ≃ β) (s t : set α) : e '' s ⊆ e '' t ↔ s ⊆ t := set.image_subset_image_iff e.injective @[simp] lemma image_eq_iff_eq {α β} (e : α ≃ β) (s t : set α) : e '' s = e '' t ↔ s = t := set.image_eq_image e.injective lemma preimage_eq_iff_eq_image {α β} (e : α ≃ β) (s t) : e ⁻¹' s = t ↔ s = e '' t := set.preimage_eq_iff_eq_image e.bijective lemma eq_preimage_iff_image_eq {α β} (e : α ≃ β) (s t) : s = e ⁻¹' t ↔ e '' s = t := set.eq_preimage_iff_image_eq e.bijective /-- If `α` is an empty type, then it is equivalent to the `empty` type. -/ def equiv_empty (α : Sort u) [is_empty α] : α ≃ empty := ⟨is_empty_elim, λ e, e.rec _, is_empty_elim, λ e, e.rec _⟩ /-- `α` is equivalent to an empty type iff `α` is empty. -/ def equiv_empty_equiv (α : Sort u) : (α ≃ empty) ≃ is_empty α := ⟨λ e, function.is_empty e, @equiv_empty α, λ e, ext $ λ x, (e x).elim, λ p, rfl⟩ /-- `false` is equivalent to `empty`. -/ def false_equiv_empty : false ≃ empty := equiv_empty _ /-- If `α` is an empty type, then it is equivalent to the `pempty` type in any universe. -/ def {u' v'} equiv_pempty (α : Sort v') [is_empty α] : α ≃ pempty.{u'} := ⟨is_empty_elim, λ e, e.rec _, is_empty_elim, λ e, e.rec _⟩ /-- `false` is equivalent to `pempty`. -/ def false_equiv_pempty : false ≃ pempty := equiv_pempty _ /-- `empty` is equivalent to `pempty`. -/ def empty_equiv_pempty : empty ≃ pempty := equiv_pempty _ /-- `pempty` types from any two universes are equivalent. -/ def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} := equiv_pempty _ /-- The `Sort` of proofs of a true proposition is equivalent to `punit`. -/ def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit := ⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩ /-- `true` is equivalent to `punit`. -/ def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial /-- `ulift α` is equivalent to `α`. -/ @[simps apply symm_apply {fully_applied := ff}] protected def ulift {α : Type v} : ulift.{u} α ≃ α := ⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩ /-- `plift α` is equivalent to `α`. -/ @[simps apply symm_apply {fully_applied := ff}] protected def plift : plift α ≃ α := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ /-- equivalence of propositions is the same as iff -/ def of_iff {P Q : Prop} (h : P ↔ Q) : P ≃ Q := { to_fun := h.mp, inv_fun := h.mpr, left_inv := λ x, rfl, right_inv := λ y, rfl } /-- If `α₁` is equivalent to `α₂` and `β₁` is equivalent to `β₂`, then the type of maps `α₁ → β₁` is equivalent to the type of maps `α₂ → β₂`. -/ @[congr, simps apply] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) := { to_fun := λ f, e₂ ∘ f ∘ e₁.symm, inv_fun := λ f, e₂.symm ∘ f ∘ e₁, left_inv := λ f, funext $ λ x, by simp, right_inv := λ f, funext $ λ x, by simp } lemma arrow_congr_comp {α₁ β₁ γ₁ α₂ β₂ γ₂ : Sort*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) (ec : γ₁ ≃ γ₂) (f : α₁ → β₁) (g : β₁ → γ₁) : arrow_congr ea ec (g ∘ f) = (arrow_congr eb ec g) ∘ (arrow_congr ea eb f) := by { ext, simp only [comp, arrow_congr_apply, eb.symm_apply_apply] } @[simp] lemma arrow_congr_refl {α β : Sort*} : arrow_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl @[simp] lemma arrow_congr_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Sort*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr e₁ e₁').trans (arrow_congr e₂ e₂') := rfl @[simp] lemma arrow_congr_symm {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrow_congr e₁ e₂).symm = arrow_congr e₁.symm e₂.symm := rfl /-- A version of `equiv.arrow_congr` in `Type`, rather than `Sort`. The `equiv_rw` tactic is not able to use the default `Sort` level `equiv.arrow_congr`, because Lean's universe rules will not unify `?l_1` with `imax (1 ?m_1)`. -/ @[congr, simps apply] def arrow_congr' {α₁ β₁ α₂ β₂ : Type*} (hα : α₁ ≃ α₂) (hβ : β₁ ≃ β₂) : (α₁ → β₁) ≃ (α₂ → β₂) := equiv.arrow_congr hα hβ @[simp] lemma arrow_congr'_refl {α β : Type*} : arrow_congr' (equiv.refl α) (equiv.refl β) = equiv.refl (α → β) := rfl @[simp] lemma arrow_congr'_trans {α₁ β₁ α₂ β₂ α₃ β₃ : Type*} (e₁ : α₁ ≃ α₂) (e₁' : β₁ ≃ β₂) (e₂ : α₂ ≃ α₃) (e₂' : β₂ ≃ β₃) : arrow_congr' (e₁.trans e₂) (e₁'.trans e₂') = (arrow_congr' e₁ e₁').trans (arrow_congr' e₂ e₂') := rfl @[simp] lemma arrow_congr'_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (arrow_congr' e₁ e₂).symm = arrow_congr' e₁.symm e₂.symm := rfl /-- Conjugate a map `f : α → α` by an equivalence `α ≃ β`. -/ @[simps apply] def conj (e : α ≃ β) : (α → α) ≃ (β → β) := arrow_congr e e @[simp] lemma conj_refl : conj (equiv.refl α) = equiv.refl (α → α) := rfl @[simp] lemma conj_symm (e : α ≃ β) : e.conj.symm = e.symm.conj := rfl @[simp] lemma conj_trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : (e₁.trans e₂).conj = e₁.conj.trans e₂.conj := rfl -- This should not be a simp lemma as long as `(∘)` is reducible: -- when `(∘)` is reducible, Lean can unify `f₁ ∘ f₂` with any `g` using -- `f₁ := g` and `f₂ := λ x, x`. This causes nontermination. lemma conj_comp (e : α ≃ β) (f₁ f₂ : α → α) : e.conj (f₁ ∘ f₂) = (e.conj f₁) ∘ (e.conj f₂) := by apply arrow_congr_comp section binary_op variables {α₁ β₁ : Type*} (e : α₁ ≃ β₁) (f : α₁ → α₁ → α₁) lemma semiconj_conj (f : α₁ → α₁) : semiconj e f (e.conj f) := λ x, by simp lemma semiconj₂_conj : semiconj₂ e f (e.arrow_congr e.conj f) := λ x y, by simp instance [is_associative α₁ f] : is_associative β₁ (e.arrow_congr (e.arrow_congr e) f) := (e.semiconj₂_conj f).is_associative_right e.surjective instance [is_idempotent α₁ f] : is_idempotent β₁ (e.arrow_congr (e.arrow_congr e) f) := (e.semiconj₂_conj f).is_idempotent_right e.surjective instance [is_left_cancel α₁ f] : is_left_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) := ⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_left_cancel.left_cancel _ f _ x y z⟩ instance [is_right_cancel α₁ f] : is_right_cancel β₁ (e.arrow_congr (e.arrow_congr e) f) := ⟨e.surjective.forall₃.2 $ λ x y z, by simpa using @is_right_cancel.right_cancel _ f _ x y z⟩ end binary_op /-- `punit` sorts in any two universes are equivalent. -/ def punit_equiv_punit : punit.{v} ≃ punit.{w} := ⟨λ _, punit.star, λ _, punit.star, λ u, by { cases u, refl }, λ u, by { cases u, reflexivity }⟩ section /-- The sort of maps to `punit.{v}` is equivalent to `punit.{w}`. -/ def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} := ⟨λ f, punit.star, λ u f, punit.star, λ f, by { funext x, cases f x, refl }, λ u, by { cases u, reflexivity }⟩ /-- If `α` has a unique term, then the type of function `α → β` is equivalent to `β`. -/ @[simps] def fun_unique (α β) [unique α] : (α → β) ≃ β := { to_fun := λ f, f (default α), inv_fun := λ b a, b, left_inv := λ f, funext $ λ a, congr_arg f $ subsingleton.elim _ _, right_inv := λ b, rfl } /-- The sort of maps from `punit` is equivalent to the codomain. -/ def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α := fun_unique _ _ /-- The sort of maps from `true` is equivalent to the codomain. -/ def true_arrow_equiv (α : Sort*) : (true → α) ≃ α := fun_unique _ _ /-- The sort of maps from a type that `is_empty` is equivalent to `punit`. -/ def arrow_punit_of_is_empty (α β : Sort*) [is_empty α] : (α → β) ≃ punit.{u} := ⟨λ f, punit.star, λ u, is_empty_elim, λ f, funext is_empty_elim, λ u, by { cases u, refl }⟩ /-- The sort of maps from `empty` is equivalent to `punit`. -/ def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} := arrow_punit_of_is_empty _ _ /-- The sort of maps from `pempty` is equivalent to `punit`. -/ def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} := arrow_punit_of_is_empty _ _ /-- The sort of maps from `false` is equivalent to `punit`. -/ def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} := arrow_punit_of_is_empty _ _ end /-- Product of two equivalences. If `α₁ ≃ α₂` and `β₁ ≃ β₂`, then `α₁ × β₁ ≃ α₂ × β₂`. -/ @[congr, simps apply] def prod_congr {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := ⟨prod.map e₁ e₂, prod.map e₁.symm e₂.symm, λ ⟨a, b⟩, by simp, λ ⟨a, b⟩, by simp⟩ @[simp] theorem prod_congr_symm {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) : (prod_congr e₁ e₂).symm = prod_congr e₁.symm e₂.symm := rfl /-- Type product is commutative up to an equivalence: `α × β ≃ β × α`. -/ @[simps apply] def prod_comm (α β : Type*) : α × β ≃ β × α := ⟨prod.swap, prod.swap, λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ @[simp] lemma prod_comm_symm (α β) : (prod_comm α β).symm = prod_comm β α := rfl /-- Type product is associative up to an equivalence. -/ @[simps] def prod_assoc (α β γ : Sort*) : (α × β) × γ ≃ α × (β × γ) := ⟨λ p, (p.1.1, p.1.2, p.2), λp, ((p.1, p.2.1), p.2.2), λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩ lemma prod_assoc_preimage {α β γ} {s : set α} {t : set β} {u : set γ} : equiv.prod_assoc α β γ ⁻¹' s.prod (t.prod u) = (s.prod t).prod u := by { ext, simp [and_assoc] } /-- Functions on `α × β` are equivalent to functions `α → β → γ`. -/ @[simps {fully_applied := ff}] def curry (α β γ : Type*) : (α × β → γ) ≃ (α → β → γ) := { to_fun := curry, inv_fun := uncurry, left_inv := uncurry_curry, right_inv := curry_uncurry } section /-- `punit` is a right identity for type product up to an equivalence. -/ @[simps] def prod_punit (α : Type*) : α × punit.{u+1} ≃ α := ⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩ /-- `punit` is a left identity for type product up to an equivalence. -/ @[simps] def punit_prod (α : Type*) : punit.{u+1} × α ≃ α := calc punit × α ≃ α × punit : prod_comm _ _ ... ≃ α : prod_punit _ /-- `empty` type is a right absorbing element for type product up to an equivalence. -/ def prod_empty (α : Type*) : α × empty ≃ empty := equiv_empty _ /-- `empty` type is a left absorbing element for type product up to an equivalence. -/ def empty_prod (α : Type*) : empty × α ≃ empty := equiv_empty _ /-- `pempty` type is a right absorbing element for type product up to an equivalence. -/ def prod_pempty (α : Type*) : α × pempty ≃ pempty := equiv_pempty _ /-- `pempty` type is a left absorbing element for type product up to an equivalence. -/ def pempty_prod (α : Type*) : pempty × α ≃ pempty := equiv_pempty _ end section open sum /-- `psum` is equivalent to `sum`. -/ def psum_equiv_sum (α β : Type*) : psum α β ≃ α ⊕ β := ⟨λ s, psum.cases_on s inl inr, λ s, sum.cases_on s psum.inl psum.inr, λ s, by cases s; refl, λ s, by cases s; refl⟩ /-- If `α ≃ α'` and `β ≃ β'`, then `α ⊕ β ≃ α' ⊕ β'`. -/ @[simps apply] def sum_congr {α₁ β₁ α₂ β₂ : Type*} (ea : α₁ ≃ α₂) (eb : β₁ ≃ β₂) : α₁ ⊕ β₁ ≃ α₂ ⊕ β₂ := ⟨sum.map ea eb, sum.map ea.symm eb.symm, λ x, by simp, λ x, by simp⟩ @[simp] lemma sum_congr_trans {α₁ α₂ β₁ β₂ γ₁ γ₂ : Sort*} (e : α₁ ≃ β₁) (f : α₂ ≃ β₂) (g : β₁ ≃ γ₁) (h : β₂ ≃ γ₂) : (equiv.sum_congr e f).trans (equiv.sum_congr g h) = (equiv.sum_congr (e.trans g) (f.trans h)) := by { ext i, cases i; refl } @[simp] lemma sum_congr_symm {α β γ δ : Sort*} (e : α ≃ β) (f : γ ≃ δ) : (equiv.sum_congr e f).symm = (equiv.sum_congr (e.symm) (f.symm)) := rfl @[simp] lemma sum_congr_refl {α β : Sort*} : equiv.sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) := by { ext i, cases i; refl } namespace perm /-- Combine a permutation of `α` and of `β` into a permutation of `α ⊕ β`. -/ @[reducible] def sum_congr {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) : equiv.perm (α ⊕ β) := equiv.sum_congr ea eb @[simp] lemma sum_congr_apply {α β : Type*} (ea : equiv.perm α) (eb : equiv.perm β) (x : α ⊕ β) : sum_congr ea eb x = sum.map ⇑ea ⇑eb x := equiv.sum_congr_apply ea eb x @[simp] lemma sum_congr_trans {α β : Sort*} (e : equiv.perm α) (f : equiv.perm β) (g : equiv.perm α) (h : equiv.perm β) : (sum_congr e f).trans (sum_congr g h) = sum_congr (e.trans g) (f.trans h) := equiv.sum_congr_trans e f g h @[simp] lemma sum_congr_symm {α β : Sort*} (e : equiv.perm α) (f : equiv.perm β) : (sum_congr e f).symm = sum_congr (e.symm) (f.symm) := equiv.sum_congr_symm e f @[simp] lemma sum_congr_refl {α β : Sort*} : sum_congr (equiv.refl α) (equiv.refl β) = equiv.refl (α ⊕ β) := equiv.sum_congr_refl end perm /-- `bool` is equivalent the sum of two `punit`s. -/ def bool_equiv_punit_sum_punit : bool ≃ punit.{u+1} ⊕ punit.{v+1} := ⟨λ b, cond b (inr punit.star) (inl punit.star), λ s, sum.rec_on s (λ_, ff) (λ_, tt), λ b, by cases b; refl, λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ /-- `Prop` is noncomputably equivalent to `bool`. -/ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), λ b, b, λ p, by simp, λ b, by simp⟩ /-- Sum of types is commutative up to an equivalence. -/ @[simps apply] def sum_comm (α β : Sort*) : α ⊕ β ≃ β ⊕ α := ⟨sum.swap, sum.swap, sum.swap_swap, sum.swap_swap⟩ @[simp] lemma sum_comm_symm (α β) : (sum_comm α β).symm = sum_comm β α := rfl /-- Sum of types is associative up to an equivalence. -/ def sum_assoc (α β γ : Sort*) : (α ⊕ β) ⊕ γ ≃ α ⊕ (β ⊕ γ) := ⟨sum.elim (sum.elim sum.inl (sum.inr ∘ sum.inl)) (sum.inr ∘ sum.inr), sum.elim (sum.inl ∘ sum.inl) $ sum.elim (sum.inl ∘ sum.inr) sum.inr, by rintros (⟨_ | _⟩ | _); refl, by rintros (_ | ⟨_ | _⟩); refl⟩ @[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl /-- Sum with `empty` is equivalent to the original type. -/ @[simps symm_apply] def sum_empty (α β : Type*) [is_empty β] : α ⊕ β ≃ α := ⟨sum.elim id is_empty_elim, inl, λ s, by { rcases s with _ | x, refl, exact is_empty_elim x }, λ a, rfl⟩ @[simp] lemma sum_empty_apply_inl {α β : Type*} [is_empty β] (a : α) : sum_empty α β (sum.inl a) = a := rfl /-- The sum of `empty` with any `Sort*` is equivalent to the right summand. -/ @[simps symm_apply] def empty_sum (α β : Type*) [is_empty α] : α ⊕ β ≃ β := (sum_comm _ _).trans $ sum_empty _ _ @[simp] lemma empty_sum_apply_inr {α β : Type*} [is_empty α] (b : β) : empty_sum α β (sum.inr b) = b := rfl /-- `option α` is equivalent to `α ⊕ punit` -/ def option_equiv_sum_punit (α : Type*) : option α ≃ α ⊕ punit.{u+1} := ⟨λ o, match o with none := inr punit.star | some a := inl a end, λ s, match s with inr _ := none | inl a := some a end, λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ @[simp] lemma option_equiv_sum_punit_none {α} : option_equiv_sum_punit α none = sum.inr punit.star := rfl @[simp] lemma option_equiv_sum_punit_some {α} (a) : option_equiv_sum_punit α (some a) = sum.inl a := rfl @[simp] lemma option_equiv_sum_punit_coe {α} (a : α) : option_equiv_sum_punit α a = sum.inl a := rfl @[simp] lemma option_equiv_sum_punit_symm_inl {α} (a) : (option_equiv_sum_punit α).symm (sum.inl a) = a := rfl @[simp] lemma option_equiv_sum_punit_symm_inr {α} (a) : (option_equiv_sum_punit α).symm (sum.inr a) = none := rfl /-- The set of `x : option α` such that `is_some x` is equivalent to `α`. -/ def option_is_some_equiv (α : Type*) : {x : option α // x.is_some} ≃ α := { to_fun := λ o, option.get o.2, inv_fun := λ x, ⟨some x, dec_trivial⟩, left_inv := λ o, subtype.eq $ option.some_get _, right_inv := λ x, option.get_some _ _ } /-- The product over `option α` of `β a` is the binary product of the product over `α` of `β (some α)` and `β none` -/ @[simps] def pi_option_equiv_prod {α : Type*} {β : option α → Type*} : (Π a : option α, β a) ≃ (β none × Π a : α, β (some a)) := { to_fun := λ f, (f none, λ a, f (some a)), inv_fun := λ x a, option.cases_on a x.fst x.snd, left_inv := λ f, funext $ λ a, by cases a; refl, right_inv := λ x, by simp } /-- `α ⊕ β` is equivalent to a `sigma`-type over `bool`. Note that this definition assumes `α` and `β` to be types from the same universe, so it cannot by used directly to transfer theorems about sigma types to theorems about sum types. In many cases one can use `ulift` to work around this difficulty. -/ def sum_equiv_sigma_bool (α β : Type u) : α ⊕ β ≃ (Σ b: bool, cond b α β) := ⟨λ s, s.elim (λ x, ⟨tt, x⟩) (λ x, ⟨ff, x⟩), λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ /-- `sigma_preimage_equiv f` for `f : α → β` is the natural equivalence between the type of all fibres of `f` and the total space `α`. -/ @[simps] def sigma_preimage_equiv {α β : Type*} (f : α → β) : (Σ y : β, {x // f x = y}) ≃ α := ⟨λ x, ↑x.2, λ x, ⟨f x, x, rfl⟩, λ ⟨y, x, rfl⟩, rfl, λ x, rfl⟩ /-- A set `s` in `α × β` is equivalent to the sigma-type `Σ x, {y | (x, y) ∈ s}`. -/ def set_prod_equiv_sigma {α β : Type*} (s : set (α × β)) : s ≃ Σ x : α, {y | (x, y) ∈ s} := { to_fun := λ x, ⟨x.1.1, x.1.2, by simp⟩, inv_fun := λ x, ⟨(x.1, x.2.1), x.2.2⟩, left_inv := λ ⟨⟨x, y⟩, h⟩, rfl, right_inv := λ ⟨x, y, h⟩, rfl } end section sum_compl /-- For any predicate `p` on `α`, the sum of the two subtypes `{a // p a}` and its complement `{a // ¬ p a}` is naturally equivalent to `α`. See `subtype_or_equiv` for sum types over subtypes `{x // p x}` and `{x // q x}` that are not necessarily `is_compl p q`. -/ def sum_compl {α : Type*} (p : α → Prop) [decidable_pred p] : {a // p a} ⊕ {a // ¬ p a} ≃ α := { to_fun := sum.elim coe coe, inv_fun := λ a, if h : p a then sum.inl ⟨a, h⟩ else sum.inr ⟨a, h⟩, left_inv := by { rintros (⟨x,hx⟩|⟨x,hx⟩); dsimp; [rw dif_pos, rw dif_neg], }, right_inv := λ a, by { dsimp, split_ifs; refl } } @[simp] lemma sum_compl_apply_inl {α : Type*} (p : α → Prop) [decidable_pred p] (x : {a // p a}) : sum_compl p (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type*} (p : α → Prop) [decidable_pred p] (x : {a // ¬ p a}) : sum_compl p (sum.inr x) = x := rfl @[simp] lemma sum_compl_apply_symm_of_pos {α : Type*} (p : α → Prop) [decidable_pred p] (a : α) (h : p a) : (sum_compl p).symm a = sum.inl ⟨a, h⟩ := dif_pos h @[simp] lemma sum_compl_apply_symm_of_neg {α : Type*} (p : α → Prop) [decidable_pred p] (a : α) (h : ¬ p a) : (sum_compl p).symm a = sum.inr ⟨a, h⟩ := dif_neg h /-- Combines an `equiv` between two subtypes with an `equiv` between their complements to form a permutation. -/ def subtype_congr {α : Type*} {p q : α → Prop} [decidable_pred p] [decidable_pred q] (e : {x // p x} ≃ {x // q x}) (f : {x // ¬p x} ≃ {x // ¬q x}) : perm α := (sum_compl p).symm.trans ((sum_congr e f).trans (sum_compl q)) open equiv variables {ε : Type*} {p : ε → Prop} [decidable_pred p] variables (ep ep' : perm {a // p a}) (en en' : perm {a // ¬ p a}) /-- Combining permutations on `ε` that permute only inside or outside the subtype split induced by `p : ε → Prop` constructs a permutation on `ε`. -/ def perm.subtype_congr : equiv.perm ε := perm_congr (sum_compl p) (sum_congr ep en) lemma perm.subtype_congr.apply (a : ε) : ep.subtype_congr en a = if h : p a then ep ⟨a, h⟩ else en ⟨a, h⟩ := by { by_cases h : p a; simp [perm.subtype_congr, h] } @[simp] lemma perm.subtype_congr.left_apply {a : ε} (h : p a) : ep.subtype_congr en a = ep ⟨a, h⟩ := by simp [perm.subtype_congr.apply, h] @[simp] lemma perm.subtype_congr.left_apply_subtype (a : {a // p a}) : ep.subtype_congr en a = ep a := by { convert perm.subtype_congr.left_apply _ _ a.property, simp } @[simp] lemma perm.subtype_congr.right_apply {a : ε} (h : ¬ p a) : ep.subtype_congr en a = en ⟨a, h⟩ := by simp [perm.subtype_congr.apply, h] @[simp] lemma perm.subtype_congr.right_apply_subtype (a : {a // ¬ p a}) : ep.subtype_congr en a = en a := by { convert perm.subtype_congr.right_apply _ _ a.property, simp } @[simp] lemma perm.subtype_congr.refl : perm.subtype_congr (equiv.refl {a // p a}) (equiv.refl {a // ¬ p a}) = equiv.refl ε := by { ext x, by_cases h : p x; simp [h] } @[simp] lemma perm.subtype_congr.symm : (ep.subtype_congr en).symm = perm.subtype_congr ep.symm en.symm := begin ext x, by_cases h : p x, { have : p (ep.symm ⟨x, h⟩) := subtype.property _, simp [perm.subtype_congr.apply, h, symm_apply_eq, this] }, { have : ¬ p (en.symm ⟨x, h⟩) := subtype.property (en.symm _), simp [perm.subtype_congr.apply, h, symm_apply_eq, this] } end @[simp] lemma perm.subtype_congr.trans : (ep.subtype_congr en).trans (ep'.subtype_congr en') = perm.subtype_congr (ep.trans ep') (en.trans en') := begin ext x, by_cases h : p x, { have : p (ep ⟨x, h⟩) := subtype.property _, simp [perm.subtype_congr.apply, h, this] }, { have : ¬ p (en ⟨x, h⟩) := subtype.property (en _), simp [perm.subtype_congr.apply, h, symm_apply_eq, this] } end end sum_compl section subtype_preimage variables (p : α → Prop) [decidable_pred p] (x₀ : {a // p a} → β) /-- For a fixed function `x₀ : {a // p a} → β` defined on a subtype of `α`, the subtype of functions `x : α → β` that agree with `x₀` on the subtype `{a // p a}` is naturally equivalent to the type of functions `{a // ¬ p a} → β`. -/ @[simps] def subtype_preimage : {x : α → β // x ∘ coe = x₀} ≃ ({a // ¬ p a} → β) := { to_fun := λ (x : {x : α → β // x ∘ coe = x₀}) a, (x : α → β) a, inv_fun := λ x, ⟨λ a, if h : p a then x₀ ⟨a, h⟩ else x ⟨a, h⟩, funext $ λ ⟨a, h⟩, dif_pos h⟩, left_inv := λ ⟨x, hx⟩, subtype.val_injective $ funext $ λ a, (by { dsimp, split_ifs; [ rw ← hx, skip ]; refl }), right_inv := λ x, funext $ λ ⟨a, h⟩, show dite (p a) _ _ = _, by { dsimp, rw [dif_neg h] } } lemma subtype_preimage_symm_apply_coe_pos (x : {a // ¬ p a} → β) (a : α) (h : p a) : ((subtype_preimage p x₀).symm x : α → β) a = x₀ ⟨a, h⟩ := dif_pos h lemma subtype_preimage_symm_apply_coe_neg (x : {a // ¬ p a} → β) (a : α) (h : ¬ p a) : ((subtype_preimage p x₀).symm x : α → β) a = x ⟨a, h⟩ := dif_neg h end subtype_preimage section /-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Π a, β₁ a` and `Π a, β₂ a`. -/ def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) := ⟨λ H a, F a (H a), λ H a, (F a).symm (H a), λ H, funext $ by simp, λ H, funext $ by simp⟩ /-- Dependent `curry` equivalence: the type of dependent functions on `Σ i, β i` is equivalent to the type of dependent functions of two arguments (i.e., functions to the space of functions). This is `sigma.curry` and `sigma.uncurry` together as an equiv. -/ def Pi_curry {α} {β : α → Sort*} (γ : Π a, β a → Sort*) : (Π x : Σ i, β i, γ x.1 x.2) ≃ (Π a b, γ a b) := { to_fun := sigma.curry, inv_fun := sigma.uncurry, left_inv := sigma.uncurry_curry, right_inv := sigma.curry_uncurry } end section /-- A `psigma`-type is equivalent to the corresponding `sigma`-type. -/ @[simps apply symm_apply] def psigma_equiv_sigma {α} (β : α → Sort*) : (Σ' i, β i) ≃ Σ i, β i := ⟨λ a, ⟨a.1, a.2⟩, λ a, ⟨a.1, a.2⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ /-- A family of equivalences `Π a, β₁ a ≃ β₂ a` generates an equivalence between `Σ a, β₁ a` and `Σ a, β₂ a`. -/ @[simps apply] def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (Σ a, β₁ a) ≃ Σ a, β₂ a := ⟨λ a, ⟨a.1, F a.1 a.2⟩, λ a, ⟨a.1, (F a.1).symm a.2⟩, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ symm_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_symm_apply (F a) b⟩ @[simp] lemma sigma_congr_right_trans {α} {β₁ β₂ β₃ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) (G : Π a, β₂ a ≃ β₃ a) : (sigma_congr_right F).trans (sigma_congr_right G) = sigma_congr_right (λ a, (F a).trans (G a)) := by { ext1 x, cases x, refl } @[simp] lemma sigma_congr_right_symm {α} {β₁ β₂ : α → Sort*} (F : Π a, β₁ a ≃ β₂ a) : (sigma_congr_right F).symm = sigma_congr_right (λ a, (F a).symm) := by { ext1 x, cases x, refl } @[simp] lemma sigma_congr_right_refl {α} {β : α → Sort*} : (sigma_congr_right (λ a, equiv.refl (β a))) = equiv.refl (Σ a, β a) := by { ext1 x, cases x, refl } namespace perm /-- A family of permutations `Π a, perm (β a)` generates a permuation `perm (Σ a, β₁ a)`. -/ @[reducible] def sigma_congr_right {α} {β : α → Sort*} (F : Π a, perm (β a)) : perm (Σ a, β a) := equiv.sigma_congr_right F @[simp] lemma sigma_congr_right_trans {α} {β : α → Sort*} (F : Π a, perm (β a)) (G : Π a, perm (β a)) : (sigma_congr_right F).trans (sigma_congr_right G) = sigma_congr_right (λ a, (F a).trans (G a)) := equiv.sigma_congr_right_trans F G @[simp] lemma sigma_congr_right_symm {α} {β : α → Sort*} (F : Π a, perm (β a)) : (sigma_congr_right F).symm = sigma_congr_right (λ a, (F a).symm) := equiv.sigma_congr_right_symm F @[simp] lemma sigma_congr_right_refl {α} {β : α → Sort*} : (sigma_congr_right (λ a, equiv.refl (β a))) = equiv.refl (Σ a, β a) := equiv.sigma_congr_right_refl end perm /-- An equivalence `f : α₁ ≃ α₂` generates an equivalence between `Σ a, β (f a)` and `Σ a, β a`. -/ @[simps apply] def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} (e : α₁ ≃ α₂) : (Σ a:α₁, β (e a)) ≃ (Σ a:α₂, β a) := ⟨λ a, ⟨e a.1, a.2⟩, λ a, ⟨e.symm a.1, @@eq.rec β a.2 (e.right_inv a.1).symm⟩, λ ⟨a, b⟩, match e.symm (e a), e.left_inv a : ∀ a' (h : a' = a), @sigma.mk _ (β ∘ e) _ (@@eq.rec β b (congr_arg e h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, λ ⟨a, b⟩, match e (e.symm a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ /-- Transporting a sigma type through an equivalence of the base -/ def sigma_congr_left' {α₁ α₂} {β : α₁ → Sort*} (f : α₁ ≃ α₂) : (Σ a:α₁, β a) ≃ (Σ a:α₂, β (f.symm a)) := (sigma_congr_left f.symm).symm /-- Transporting a sigma type through an equivalence of the base and a family of equivalences of matching fibers -/ def sigma_congr {α₁ α₂} {β₁ : α₁ → Sort*} {β₂ : α₂ → Sort*} (f : α₁ ≃ α₂) (F : ∀ a, β₁ a ≃ β₂ (f a)) : sigma β₁ ≃ sigma β₂ := (sigma_congr_right F).trans (sigma_congr_left f) /-- `sigma` type with a constant fiber is equivalent to the product. -/ @[simps apply symm_apply] def sigma_equiv_prod (α β : Type*) : (Σ_:α, β) ≃ α × β := ⟨λ a, ⟨a.1, a.2⟩, λ a, ⟨a.1, a.2⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ /-- If each fiber of a `sigma` type is equivalent to a fixed type, then the sigma type is equivalent to the product. -/ def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : Π a, β₁ a ≃ β) : sigma β₁ ≃ α × β := (sigma_congr_right F).trans (sigma_equiv_prod α β) /-- Dependent product of types is associative up to an equivalence. -/ def sigma_assoc {α : Type*} {β : α → Type*} (γ : Π (a : α), β a → Type*) : (Σ (ab : Σ (a : α), β a), γ ab.1 ab.2) ≃ Σ (a : α), (Σ (b : β a), γ a b) := { to_fun := λ x, ⟨x.1.1, ⟨x.1.2, x.2⟩⟩, inv_fun := λ x, ⟨⟨x.1, x.2.1⟩, x.2.2⟩, left_inv := λ ⟨⟨a, b⟩, c⟩, rfl, right_inv := λ ⟨a, ⟨b, c⟩⟩, rfl } end section prod_congr variables {α₁ β₁ β₂ : Type*} (e : α₁ → β₁ ≃ β₂) /-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence between `β₁ × α₁` and `β₂ × α₁`. -/ def prod_congr_left : β₁ × α₁ ≃ β₂ × α₁ := { to_fun := λ ab, ⟨e ab.2 ab.1, ab.2⟩, inv_fun := λ ab, ⟨(e ab.2).symm ab.1, ab.2⟩, left_inv := by { rintros ⟨a, b⟩, simp }, right_inv := by { rintros ⟨a, b⟩, simp } } @[simp] lemma prod_congr_left_apply (b : β₁) (a : α₁) : prod_congr_left e (b, a) = (e a b, a) := rfl lemma prod_congr_refl_right (e : β₁ ≃ β₂) : prod_congr e (equiv.refl α₁) = prod_congr_left (λ _, e) := by { ext ⟨a, b⟩ : 1, simp } /-- A family of equivalences `Π (a : α₁), β₁ ≃ β₂` generates an equivalence between `α₁ × β₁` and `α₁ × β₂`. -/ def prod_congr_right : α₁ × β₁ ≃ α₁ × β₂ := { to_fun := λ ab, ⟨ab.1, e ab.1 ab.2⟩, inv_fun := λ ab, ⟨ab.1, (e ab.1).symm ab.2⟩, left_inv := by { rintros ⟨a, b⟩, simp }, right_inv := by { rintros ⟨a, b⟩, simp } } @[simp] lemma prod_congr_right_apply (a : α₁) (b : β₁) : prod_congr_right e (a, b) = (a, e a b) := rfl lemma prod_congr_refl_left (e : β₁ ≃ β₂) : prod_congr (equiv.refl α₁) e = prod_congr_right (λ _, e) := by { ext ⟨a, b⟩ : 1, simp } @[simp] lemma prod_congr_left_trans_prod_comm : (prod_congr_left e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_right e) := by { ext ⟨a, b⟩ : 1, simp } @[simp] lemma prod_congr_right_trans_prod_comm : (prod_congr_right e).trans (prod_comm _ _) = (prod_comm _ _).trans (prod_congr_left e) := by { ext ⟨a, b⟩ : 1, simp } lemma sigma_congr_right_sigma_equiv_prod : (sigma_congr_right e).trans (sigma_equiv_prod α₁ β₂) = (sigma_equiv_prod α₁ β₁).trans (prod_congr_right e) := by { ext ⟨a, b⟩ : 1, simp } lemma sigma_equiv_prod_sigma_congr_right : (sigma_equiv_prod α₁ β₁).symm.trans (sigma_congr_right e) = (prod_congr_right e).trans (sigma_equiv_prod α₁ β₂).symm := by { ext ⟨a, b⟩ : 1, simp } /-- A variation on `equiv.prod_congr` where the equivalence in the second component can depend on the first component. A typical example is a shear mapping, explaining the name of this declaration. -/ @[simps {fully_applied := ff}] def prod_shear {α₁ β₁ α₂ β₂ : Type*} (e₁ : α₁ ≃ α₂) (e₂ : α₁ → β₁ ≃ β₂) : α₁ × β₁ ≃ α₂ × β₂ := { to_fun := λ x : α₁ × β₁, (e₁ x.1, e₂ x.1 x.2), inv_fun := λ y : α₂ × β₂, (e₁.symm y.1, (e₂ $ e₁.symm y.1).symm y.2), left_inv := by { rintro ⟨x₁, y₁⟩, simp only [symm_apply_apply] }, right_inv := by { rintro ⟨x₁, y₁⟩, simp only [apply_symm_apply] } } end prod_congr namespace perm variables {α₁ β₁ β₂ : Type*} [decidable_eq α₁] (a : α₁) (e : perm β₁) /-- `prod_extend_right a e` extends `e : perm β` to `perm (α × β)` by sending `(a, b)` to `(a, e b)` and keeping the other `(a', b)` fixed. -/ def prod_extend_right : perm (α₁ × β₁) := { to_fun := λ ab, if ab.fst = a then (a, e ab.snd) else ab, inv_fun := λ ab, if ab.fst = a then (a, e.symm ab.snd) else ab, left_inv := by { rintros ⟨k', x⟩, simp only, split_ifs with h; simp [h] }, right_inv := by { rintros ⟨k', x⟩, simp only, split_ifs with h; simp [h] } } @[simp] lemma prod_extend_right_apply_eq (b : β₁) : prod_extend_right a e (a, b) = (a, e b) := if_pos rfl lemma prod_extend_right_apply_ne {a a' : α₁} (h : a' ≠ a) (b : β₁) : prod_extend_right a e (a', b) = (a', b) := if_neg h lemma eq_of_prod_extend_right_ne {e : perm β₁} {a a' : α₁} {b : β₁} (h : prod_extend_right a e (a', b) ≠ (a', b)) : a' = a := by { contrapose! h, exact prod_extend_right_apply_ne _ h _ } @[simp] lemma fst_prod_extend_right (ab : α₁ × β₁) : (prod_extend_right a e ab).fst = ab.fst := begin rw [prod_extend_right, coe_fn_mk], split_ifs with h, { rw h }, { refl } end end perm section /-- The type of functions to a product `α × β` is equivalent to the type of pairs of functions `γ → α` and `γ → β`. -/ def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ (γ → α) × (γ → β) := ⟨λ f, (λ c, (f c).1, λ c, (f c).2), λ p c, (p.1 c, p.2 c), λ f, funext $ λ c, prod.mk.eta, λ p, by { cases p, refl }⟩ open sum /-- The type of functions on a sum type `α ⊕ β` is equivalent to the type of pairs of functions on `α` and on `β`. -/ def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ (α → γ) × (β → γ) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p, sum.elim p.1 p.2, λ f, by { ext ⟨⟩; refl }, λ p, by { cases p, refl }⟩ @[simp] lemma sum_arrow_equiv_prod_arrow_apply_fst {α β γ} (f : (α ⊕ β) → γ) (a : α) : (sum_arrow_equiv_prod_arrow α β γ f).1 a = f (inl a) := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_apply_snd {α β γ} (f : (α ⊕ β) → γ) (b : β) : (sum_arrow_equiv_prod_arrow α β γ f).2 b = f (inr b) := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_symm_apply_inl {α β γ} (f : α → γ) (g : β → γ) (a : α) : ((sum_arrow_equiv_prod_arrow α β γ).symm (f, g)) (inl a) = f a := rfl @[simp] lemma sum_arrow_equiv_prod_arrow_symm_apply_inr {α β γ} (f : α → γ) (g : β → γ) (b : β) : ((sum_arrow_equiv_prod_arrow α β γ).symm (f, g)) (inr b) = g b := rfl /-- Type product is right distributive with respect to type sum up to an equivalence. -/ def sum_prod_distrib (α β γ : Sort*) : (α ⊕ β) × γ ≃ (α × γ) ⊕ (β × γ) := ⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end, λ s, match s with inl q := (inl q.1, q.2) | inr q := (inr q.1, q.2) end, λ p, by rcases p with ⟨_ | _, _⟩; refl, λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩ @[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) : sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) : sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl /-- Type product is left distributive with respect to type sum up to an equivalence. -/ def prod_sum_distrib (α β γ : Sort*) : α × (β ⊕ γ) ≃ (α × β) ⊕ (α × γ) := calc α × (β ⊕ γ) ≃ (β ⊕ γ) × α : prod_comm _ _ ... ≃ (β × α) ⊕ (γ × α) : sum_prod_distrib _ _ _ ... ≃ (α × β) ⊕ (α × γ) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) : prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) : prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl /-- The product of an indexed sum of types (formally, a `sigma`-type `Σ i, α i`) by a type `β` is equivalent to the sum of products `Σ i, (α i × β)`. -/ def sigma_prod_distrib {ι : Type*} (α : ι → Type*) (β : Type*) : ((Σ i, α i) × β) ≃ (Σ i, (α i × β)) := ⟨λ p, ⟨p.1.1, (p.1.2, p.2)⟩, λ p, (⟨p.1, p.2.1⟩, p.2.2), λ p, by { rcases p with ⟨⟨_, _⟩, _⟩, refl }, λ p, by { rcases p with ⟨_, ⟨_, _⟩⟩, refl }⟩ /-- The product `bool × α` is equivalent to `α ⊕ α`. -/ def bool_prod_equiv_sum (α : Type u) : bool × α ≃ α ⊕ α := calc bool × α ≃ (unit ⊕ unit) × α : prod_congr bool_equiv_punit_sum_punit (equiv.refl _) ... ≃ (unit × α) ⊕ (unit × α) : sum_prod_distrib _ _ _ ... ≃ α ⊕ α : sum_congr (punit_prod _) (punit_prod _) /-- The function type `bool → α` is equivalent to `α × α`. -/ def bool_to_equiv_prod (α : Type u) : (bool → α) ≃ α × α := calc (bool → α) ≃ ((unit ⊕ unit) → α) : (arrow_congr bool_equiv_punit_sum_punit (equiv.refl α)) ... ≃ (unit → α) × (unit → α) : sum_arrow_equiv_prod_arrow _ _ _ ... ≃ α × α : prod_congr (punit_arrow_equiv _) (punit_arrow_equiv _) @[simp] lemma bool_to_equiv_prod_apply {α : Type u} (f : bool → α) : bool_to_equiv_prod α f = (f ff, f tt) := rfl @[simp] lemma bool_to_equiv_prod_symm_apply_ff {α : Type u} (p : α × α) : (bool_to_equiv_prod α).symm p ff = p.1 := rfl @[simp] lemma bool_to_equiv_prod_symm_apply_tt {α : Type u} (p : α × α) : (bool_to_equiv_prod α).symm p tt = p.2 := rfl end section open sum nat /-- The set of natural numbers is equivalent to `ℕ ⊕ punit`. -/ def nat_equiv_nat_sum_punit : ℕ ≃ ℕ ⊕ punit.{u+1} := ⟨λ n, match n with zero := inr punit.star | succ a := inl a end, λ s, match s with inl n := succ n | inr punit.star := zero end, λ n, begin cases n, repeat { refl } end, λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩ /-- `ℕ ⊕ punit` is equivalent to `ℕ`. -/ def nat_sum_punit_equiv_nat : ℕ ⊕ punit.{u+1} ≃ ℕ := nat_equiv_nat_sum_punit.symm /-- The type of integer numbers is equivalent to `ℕ ⊕ ℕ`. -/ def int_equiv_nat_sum_nat : ℤ ≃ ℕ ⊕ ℕ := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} end /-- An equivalence between `α` and `β` generates an equivalence between `list α` and `list β`. -/ def list_equiv_of_equiv {α β : Type*} (e : α ≃ β) : list α ≃ list β := { to_fun := list.map e, inv_fun := list.map e.symm, left_inv := λ l, by rw [list.map_map, e.symm_comp_self, list.map_id], right_inv := λ l, by rw [list.map_map, e.self_comp_symm, list.map_id] } /-- `fin n` is equivalent to `{m // m < n}`. -/ def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} := ⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩ /-- If `α` is equivalent to `β`, then `unique α` is equivalent to `unique β`. -/ def unique_congr (e : α ≃ β) : unique α ≃ unique β := { to_fun := λ h, @equiv.unique _ _ h e.symm, inv_fun := λ h, @equiv.unique _ _ h e, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- If `α` is equivalent to `β`, then `is_empty α` is equivalent to `is_empty β`. -/ lemma is_empty_congr (e : α ≃ β) : is_empty α ↔ is_empty β := ⟨λ h, @function.is_empty _ _ h e.symm, λ h, @function.is_empty _ _ h e⟩ protected lemma is_empty (e : α ≃ β) [is_empty β] : is_empty α := e.is_empty_congr.mpr ‹_› section open subtype /-- If `α` is equivalent to `β` and the predicates `p : α → Prop` and `q : β → Prop` are equivalent at corresponding points, then `{a // p a}` is equivalent to `{b // q b}`. For the statement where `α = β`, that is, `e : perm α`, see `perm.subtype_perm`. -/ def subtype_equiv {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} := ⟨λ x, ⟨e x, (h _).1 x.2⟩, λ y, ⟨e.symm y, (h _).2 (by { simp, exact y.2 })⟩, λ ⟨x, h⟩, subtype.ext_val $ by simp, λ ⟨y, h⟩, subtype.ext_val $ by simp⟩ @[simp] lemma subtype_equiv_refl {p : α → Prop} (h : ∀ a, p a ↔ p (equiv.refl _ a) := λ a, iff.rfl) : (equiv.refl α).subtype_equiv h = equiv.refl {a : α // p a} := by { ext, refl } @[simp] lemma subtype_equiv_symm {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ (a : α), p a ↔ q (e a)) : (e.subtype_equiv h).symm = e.symm.subtype_equiv (λ a, by { convert (h $ e.symm a).symm, exact (e.apply_symm_apply a).symm }) := rfl @[simp] lemma subtype_equiv_trans {p : α → Prop} {q : β → Prop} {r : γ → Prop} (e : α ≃ β) (f : β ≃ γ) (h : ∀ (a : α), p a ↔ q (e a)) (h' : ∀ (b : β), q b ↔ r (f b)): (e.subtype_equiv h).trans (f.subtype_equiv h') = (e.trans f).subtype_equiv (λ a, (h a).trans (h' $ e a)) := rfl @[simp] lemma subtype_equiv_apply {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ (a : α), p a ↔ q (e a)) (x : {x // p x}) : e.subtype_equiv h x = ⟨e x, (h _).1 x.2⟩ := rfl /-- If two predicates `p` and `q` are pointwise equivalent, then `{x // p x}` is equivalent to `{x // q x}`. -/ @[simps] def subtype_equiv_right {p q : α → Prop} (e : ∀x, p x ↔ q x) : {x // p x} ≃ {x // q x} := subtype_equiv (equiv.refl _) e /-- If `α ≃ β`, then for any predicate `p : β → Prop` the subtype `{a // p (e a)}` is equivalent to the subtype `{b // p b}`. -/ def subtype_equiv_of_subtype {p : β → Prop} (e : α ≃ β) : {a : α // p (e a)} ≃ {b : β // p b} := subtype_equiv e $ by simp /-- If `α ≃ β`, then for any predicate `p : α → Prop` the subtype `{a // p a}` is equivalent to the subtype `{b // p (e.symm b)}`. This version is used by `equiv_rw`. -/ def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) : {a : α // p a} ≃ {b : β // p (e.symm b)} := e.symm.subtype_equiv_of_subtype.symm /-- If two predicates are equal, then the corresponding subtypes are equivalent. -/ def subtype_equiv_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q := subtype_equiv (equiv.refl α) (assume a, h ▸ iff.rfl) /-- The subtypes corresponding to equal sets are equivalent. -/ @[simps apply] def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t := subtype_equiv_prop h /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. This version allows the “inner” predicate to depend on `h : p a`. -/ def subtype_subtype_equiv_subtype_exists {α : Type u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩, λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by { cases ha, exact ha_h }⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ @[simp] lemma subtype_subtype_equiv_subtype_exists_apply {α : Type u} (p : α → Prop) (q : subtype p → Prop) (a) : (subtype_subtype_equiv_subtype_exists p q a : α) = a := by { cases a, cases a_val, refl } /-- A subtype of a subtype is equivalent to the subtype of elements satisfying both predicates. -/ def subtype_subtype_equiv_subtype_inter {α : Type u} (p q : α → Prop) : {x : subtype p // q x.1} ≃ subtype (λ x, p x ∧ q x) := (subtype_subtype_equiv_subtype_exists p _).trans $ subtype_equiv_right $ λ x, exists_prop @[simp] lemma subtype_subtype_equiv_subtype_inter_apply {α : Type u} (p q : α → Prop) (a) : (subtype_subtype_equiv_subtype_inter p q a : α) = a := by { cases a, cases a_val, refl } /-- If the outer subtype has more restrictive predicate than the inner one, then we can drop the latter. -/ def subtype_subtype_equiv_subtype {α : Type u} {p q : α → Prop} (h : ∀ {x}, q x → p x) : {x : subtype p // q x.1} ≃ subtype q := (subtype_subtype_equiv_subtype_inter p _).trans $ subtype_equiv_right $ assume x, ⟨and.right, λ h₁, ⟨h h₁, h₁⟩⟩ @[simp] lemma subtype_subtype_equiv_subtype_apply {α : Type u} {p q : α → Prop} (h : ∀ x, q x → p x) (a : {x : subtype p // q x.1}) : (subtype_subtype_equiv_subtype h a : α) = a := by { cases a, cases a_val, refl } /-- If a proposition holds for all elements, then the subtype is equivalent to the original type. -/ @[simps apply symm_apply] def subtype_univ_equiv {α : Type u} {p : α → Prop} (h : ∀ x, p x) : subtype p ≃ α := ⟨λ x, x, λ x, ⟨x, h x⟩, λ x, subtype.eq rfl, λ x, rfl⟩ /-- A subtype of a sigma-type is a sigma-type over a subtype. -/ def subtype_sigma_equiv {α : Type u} (p : α → Type v) (q : α → Prop) : { y : sigma p // q y.1 } ≃ Σ(x : subtype q), p x.1 := ⟨λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ x, ⟨⟨x.1.1, x.2⟩, x.1.2⟩, λ ⟨⟨x, h⟩, y⟩, rfl, λ ⟨⟨x, y⟩, h⟩, rfl⟩ /-- A sigma type over a subtype is equivalent to the sigma set over the original type, if the fiber is empty outside of the subset -/ def sigma_subtype_equiv_of_subset {α : Type u} (p : α → Type v) (q : α → Prop) (h : ∀ x, p x → q x) : (Σ x : subtype q, p x) ≃ Σ x : α, p x := (subtype_sigma_equiv p q).symm.trans $ subtype_univ_equiv $ λ x, h x.1 x.2 /-- If a predicate `p : β → Prop` is true on the range of a map `f : α → β`, then `Σ y : {y // p y}, {x // f x = y}` is equivalent to `α`. -/ def sigma_subtype_preimage_equiv {α : Type u} {β : Type v} (f : α → β) (p : β → Prop) (h : ∀ x, p (f x)) : (Σ y : subtype p, {x : α // f x = y}) ≃ α := calc _ ≃ Σ y : β, {x : α // f x = y} : sigma_subtype_equiv_of_subset _ p (λ y ⟨x, h'⟩, h' ▸ h x) ... ≃ α : sigma_preimage_equiv f /-- If for each `x` we have `p x ↔ q (f x)`, then `Σ y : {y // q y}, f ⁻¹' {y}` is equivalent to `{x // p x}`. -/ def sigma_subtype_preimage_equiv_subtype {α : Type u} {β : Type v} (f : α → β) {p : α → Prop} {q : β → Prop} (h : ∀ x, p x ↔ q (f x)) : (Σ y : subtype q, {x : α // f x = y}) ≃ subtype p := calc (Σ y : subtype q, {x : α // f x = y}) ≃ Σ y : subtype q, {x : subtype p // subtype.mk (f x) ((h x).1 x.2) = y} : begin apply sigma_congr_right, assume y, symmetry, refine (subtype_subtype_equiv_subtype_exists _ _).trans (subtype_equiv_right _), assume x, exact ⟨λ ⟨hp, h'⟩, congr_arg subtype.val h', λ h', ⟨(h x).2 (h'.symm ▸ y.2), subtype.eq h'⟩⟩ end ... ≃ subtype p : sigma_preimage_equiv (λ x : subtype p, (⟨f x, (h x).1 x.property⟩ : subtype q)) /-- The `pi`-type `Π i, π i` is equivalent to the type of sections `f : ι → Σ i, π i` of the `sigma` type such that for all `i` we have `(f i).fst = i`. -/ def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) : (Πi, π i) ≃ {f : ι → Σi, π i | ∀i, (f i).1 = i } := ⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end, assume f, funext $ assume i, rfl, assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $ eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩ /-- The set of functions `f : Π a, β a` such that for all `a` we have `p a (f a)` is equivalent to the set of functions `Π a, {b : β a // p a b}`. -/ def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} : {f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } := ⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩, by { rintro ⟨f, h⟩, refl }, by { rintro f, funext a, exact subtype.ext_val rfl }⟩ /-- A subtype of a product defined by componentwise conditions is equivalent to a product of subtypes. -/ def subtype_prod_equiv_prod {α : Type u} {β : Type v} {p : α → Prop} {q : β → Prop} : {c : α × β // p c.1 ∧ q c.2} ≃ ({a // p a} × {b // q b}) := ⟨λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, λ x, ⟨⟨x.1.1, x.2.1⟩, ⟨x.1.2, x.2.2⟩⟩, λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl, λ ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl⟩ /-- A subtype of a `prod` is equivalent to a sigma type whose fibers are subtypes. -/ def subtype_prod_equiv_sigma_subtype {α β : Type*} (p : α → β → Prop) : {x : α × β // p x.1 x.2} ≃ Σ a, {b : β // p a b} := { to_fun := λ x, ⟨x.1.1, x.1.2, x.prop⟩, inv_fun := λ x, ⟨⟨x.1, x.2⟩, x.2.prop⟩, left_inv := λ x, by ext; refl, right_inv := λ ⟨a, b, pab⟩, rfl } end section subtype_equiv_codomain variables {X : Type*} {Y : Type*} [decidable_eq X] {x : X} /-- The type of all functions `X → Y` with prescribed values for all `x' ≠ x` is equivalent to the codomain `Y`. -/ def subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) : {g : X → Y // g ∘ coe = f} ≃ Y := (subtype_preimage _ f).trans $ @fun_unique {x' // ¬ x' ≠ x} _ $ show unique {x' // ¬ x' ≠ x}, from @equiv.unique _ _ (show unique {x' // x' = x}, from { default := ⟨x, rfl⟩, uniq := λ ⟨x', h⟩, subtype.val_injective h }) (subtype_equiv_right $ λ a, not_not) @[simp] lemma coe_subtype_equiv_codomain (f : {x' // x' ≠ x} → Y) : (subtype_equiv_codomain f : {g : X → Y // g ∘ coe = f} → Y) = λ g, (g : X → Y) x := rfl @[simp] lemma subtype_equiv_codomain_apply (f : {x' // x' ≠ x} → Y) (g : {g : X → Y // g ∘ coe = f}) : subtype_equiv_codomain f g = (g : X → Y) x := rfl lemma coe_subtype_equiv_codomain_symm (f : {x' // x' ≠ x} → Y) : ((subtype_equiv_codomain f).symm : Y → {g : X → Y // g ∘ coe = f}) = λ y, ⟨λ x', if h : x' ≠ x then f ⟨x', h⟩ else y, by { funext x', dsimp, erw [dif_pos x'.2, subtype.coe_eta] }⟩ := rfl @[simp] lemma subtype_equiv_codomain_symm_apply (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) : ((subtype_equiv_codomain f).symm y : X → Y) x' = if h : x' ≠ x then f ⟨x', h⟩ else y := rfl @[simp] lemma subtype_equiv_codomain_symm_apply_eq (f : {x' // x' ≠ x} → Y) (y : Y) : ((subtype_equiv_codomain f).symm y : X → Y) x = y := dif_neg (not_not.mpr rfl) lemma subtype_equiv_codomain_symm_apply_ne (f : {x' // x' ≠ x} → Y) (y : Y) (x' : X) (h : x' ≠ x) : ((subtype_equiv_codomain f).symm y : X → Y) x' = f ⟨x', h⟩ := dif_pos h end subtype_equiv_codomain /-- A set is equivalent to its image under an equivalence. -/ -- We could construct this using `equiv.set.image e s e.injective`, -- but this definition provides an explicit inverse. @[simps] def image {α β : Type*} (e : α ≃ β) (s : set α) : s ≃ e '' s := { to_fun := λ x, ⟨e x.1, by simp⟩, inv_fun := λ y, ⟨e.symm y.1, by { rcases y with ⟨-, ⟨a, ⟨m, rfl⟩⟩⟩, simpa using m, }⟩, left_inv := λ x, by simp, right_inv := λ y, by simp, }. namespace set open set /-- `univ α` is equivalent to `α`. -/ @[simps apply symm_apply] protected def univ (α) : @univ α ≃ α := ⟨coe, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ /-- An empty set is equivalent to the `empty` type. -/ protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty _ /-- An empty set is equivalent to a `pempty` type. -/ protected def pempty (α) : (∅ : set α) ≃ pempty := equiv_pempty _ /-- If sets `s` and `t` are separated by a decidable predicate, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union' {α} {s t : set α} (p : α → Prop) [decidable_pred p] (hs : ∀ x ∈ s, p x) (ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ s ⊕ t := { to_fun := λ x, if hp : p x then sum.inl ⟨_, x.2.resolve_right (λ xt, ht _ xt hp)⟩ else sum.inr ⟨_, x.2.resolve_left (λ xs, hp (hs _ xs))⟩, inv_fun := λ o, match o with | (sum.inl x) := ⟨x, or.inl x.2⟩ | (sum.inr x) := ⟨x, or.inr x.2⟩ end, left_inv := λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, h]; congr, right_inv := λ o, begin rcases o with ⟨x, h⟩ | ⟨x, h⟩; dsimp [union'._match_1]; [simp [hs _ h], simp [ht _ h]] end } /-- If sets `s` and `t` are disjoint, then `s ∪ t` is equivalent to `s ⊕ t`. -/ protected def union {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) : (s ∪ t : set α) ≃ s ⊕ t := set.union' (λ x, x ∈ s) (λ _, id) (λ x xt xs, H ⟨xs, xt⟩) lemma union_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ s) : equiv.set.union H a = sum.inl ⟨a, ha⟩ := dif_pos ha lemma union_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) {a : (s ∪ t : set α)} (ha : ↑a ∈ t) : equiv.set.union H a = sum.inr ⟨a, ha⟩ := dif_neg $ λ h, H ⟨h, ha⟩ @[simp] lemma union_symm_apply_left {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) (a : s) : (equiv.set.union H).symm (sum.inl a) = ⟨a, subset_union_left _ _ a.2⟩ := rfl @[simp] lemma union_symm_apply_right {α} {s t : set α} [decidable_pred (λ x, x ∈ s)] (H : s ∩ t ⊆ ∅) (a : t) : (equiv.set.union H).symm (sum.inr a) = ⟨a, subset_union_right _ _ a.2⟩ := rfl /-- A singleton set is equivalent to a `punit` type. -/ protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by { simp at h, subst x }, λ ⟨⟩, rfl⟩ /-- Equal sets are equivalent. -/ @[simps apply symm_apply] protected def of_eq {α : Type u} {s t : set α} (h : s = t) : s ≃ t := { to_fun := λ x, ⟨x, h ▸ x.2⟩, inv_fun := λ x, ⟨x, h.symm ▸ x.2⟩, left_inv := λ _, subtype.eq rfl, right_inv := λ _, subtype.eq rfl } /-- If `a ∉ s`, then `insert a s` is equivalent to `s ⊕ punit`. -/ protected def insert {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ s ⊕ punit.{u+1} := calc (insert a s : set α) ≃ ↥(s ∪ {a}) : equiv.set.of_eq (by simp) ... ≃ s ⊕ ({a} : set α) : equiv.set.union (by finish [set.subset_def]) ... ≃ s ⊕ punit.{u+1} : sum_congr (equiv.refl _) (equiv.set.singleton _) @[simp] lemma insert_symm_apply_inl {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : s) : (equiv.set.insert H).symm (sum.inl b) = ⟨b, or.inr b.2⟩ := rfl @[simp] lemma insert_symm_apply_inr {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : punit.{u+1}) : (equiv.set.insert H).symm (sum.inr b) = ⟨a, or.inl rfl⟩ := rfl @[simp] lemma insert_apply_left {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) : equiv.set.insert H ⟨a, or.inl rfl⟩ = sum.inr punit.star := (equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl @[simp] lemma insert_apply_right {α} {s : set.{u} α} [decidable_pred (∈ s)] {a : α} (H : a ∉ s) (b : s) : equiv.set.insert H ⟨b, or.inr b.2⟩ = sum.inl b := (equiv.set.insert H).apply_eq_iff_eq_symm_apply.2 rfl /-- If `s : set α` is a set with decidable membership, then `s ⊕ sᶜ` is equivalent to `α`. -/ protected def sum_compl {α} (s : set α) [decidable_pred (∈ s)] : s ⊕ (sᶜ : set α) ≃ α := calc s ⊕ (sᶜ : set α) ≃ ↥(s ∪ sᶜ) : (equiv.set.union (by simp [set.ext_iff])).symm ... ≃ @univ α : equiv.set.of_eq (by simp) ... ≃ α : equiv.set.univ _ @[simp] lemma sum_compl_apply_inl {α : Type u} (s : set α) [decidable_pred (∈ s)] (x : s) : equiv.set.sum_compl s (sum.inl x) = x := rfl @[simp] lemma sum_compl_apply_inr {α : Type u} (s : set α) [decidable_pred (∈ s)] (x : sᶜ) : equiv.set.sum_compl s (sum.inr x) = x := rfl lemma sum_compl_symm_apply_of_mem {α : Type u} {s : set α} [decidable_pred (∈ s)] {x : α} (hx : x ∈ s) : (equiv.set.sum_compl s).symm x = sum.inl ⟨x, hx⟩ := have ↑(⟨x, or.inl hx⟩ : (s ∪ sᶜ : set α)) ∈ s, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_left _ this } lemma sum_compl_symm_apply_of_not_mem {α : Type u} {s : set α} [decidable_pred (∈ s)] {x : α} (hx : x ∉ s) : (equiv.set.sum_compl s).symm x = sum.inr ⟨x, hx⟩ := have ↑(⟨x, or.inr hx⟩ : (s ∪ sᶜ : set α)) ∈ sᶜ, from hx, by { rw [equiv.set.sum_compl], simpa using set.union_apply_right _ this } @[simp] lemma sum_compl_symm_apply {α : Type*} {s : set α} [decidable_pred (∈ s)] {x : s} : (equiv.set.sum_compl s).symm x = sum.inl x := by cases x with x hx; exact set.sum_compl_symm_apply_of_mem hx @[simp] lemma sum_compl_symm_apply_compl {α : Type*} {s : set α} [decidable_pred (∈ s)] {x : sᶜ} : (equiv.set.sum_compl s).symm x = sum.inr x := by cases x with x hx; exact set.sum_compl_symm_apply_of_not_mem hx /-- `sum_diff_subset s t` is the natural equivalence between `s ⊕ (t \ s)` and `t`, where `s` and `t` are two sets. -/ protected def sum_diff_subset {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] : s ⊕ (t \ s : set α) ≃ t := calc s ⊕ (t \ s : set α) ≃ (s ∪ (t \ s) : set α) : (equiv.set.union (by simp [inter_diff_self])).symm ... ≃ t : equiv.set.of_eq (by { simp [union_diff_self, union_eq_self_of_subset_left h] }) @[simp] lemma sum_diff_subset_apply_inl {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] (x : s) : equiv.set.sum_diff_subset h (sum.inl x) = inclusion h x := rfl @[simp] lemma sum_diff_subset_apply_inr {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] (x : t \ s) : equiv.set.sum_diff_subset h (sum.inr x) = inclusion (diff_subset t s) x := rfl lemma sum_diff_subset_symm_apply_of_mem {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] {x : t} (hx : x.1 ∈ s) : (equiv.set.sum_diff_subset h).symm x = sum.inl ⟨x, hx⟩ := begin apply (equiv.set.sum_diff_subset h).injective, simp only [apply_symm_apply, sum_diff_subset_apply_inl], exact subtype.eq rfl, end lemma sum_diff_subset_symm_apply_of_not_mem {α} {s t : set α} (h : s ⊆ t) [decidable_pred (∈ s)] {x : t} (hx : x.1 ∉ s) : (equiv.set.sum_diff_subset h).symm x = sum.inr ⟨x, ⟨x.2, hx⟩⟩ := begin apply (equiv.set.sum_diff_subset h).injective, simp only [apply_symm_apply, sum_diff_subset_apply_inr], exact subtype.eq rfl, end /-- If `s` is a set with decidable membership, then the sum of `s ∪ t` and `s ∩ t` is equivalent to `s ⊕ t`. -/ protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred (∈ s)] : (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ s ⊕ t := calc (s ∪ t : set α) ⊕ (s ∩ t : set α) ≃ (s ∪ t \ s : set α) ⊕ (s ∩ t : set α) : by rw [union_diff_self] ... ≃ (s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α) : sum_congr (set.union $ subset_empty_iff.2 (inter_diff_self _ _)) (equiv.refl _) ... ≃ s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α) : sum_assoc _ _ _ ... ≃ s ⊕ (t \ s ∪ s ∩ t : set α) : sum_congr (equiv.refl _) begin refine (set.union' (∉ s) _ _).symm, exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1] end ... ≃ s ⊕ t : by { rw (_ : t \ s ∪ s ∩ t = t), rw [union_comm, inter_comm, inter_union_diff] } /-- Given an equivalence `e₀` between sets `s : set α` and `t : set β`, the set of equivalences `e : α ≃ β` such that `e ↑x = ↑(e₀ x)` for each `x : s` is equivalent to the set of equivalences between `sᶜ` and `tᶜ`. -/ protected def compl {α : Type u} {β : Type v} {s : set α} {t : set β} [decidable_pred (∈ s)] [decidable_pred (∈ t)] (e₀ : s ≃ t) : {e : α ≃ β // ∀ x : s, e x = e₀ x} ≃ ((sᶜ : set α) ≃ (tᶜ : set β)) := { to_fun := λ e, subtype_equiv e (λ a, not_congr $ iff.symm $ maps_to.mem_iff (maps_to_iff_exists_map_subtype.2 ⟨e₀, e.2⟩) (surj_on.maps_to_compl (surj_on_iff_exists_map_subtype.2 ⟨t, e₀, subset.refl t, e₀.surjective, e.2⟩) e.1.injective)), inv_fun := λ e₁, subtype.mk (calc α ≃ s ⊕ (sᶜ : set α) : (set.sum_compl s).symm ... ≃ t ⊕ (tᶜ : set β) : e₀.sum_congr e₁ ... ≃ β : set.sum_compl t) (λ x, by simp only [sum.map_inl, trans_apply, sum_congr_apply, set.sum_compl_apply_inl, set.sum_compl_symm_apply]), left_inv := λ e, begin ext x, by_cases hx : x ∈ s, { simp only [set.sum_compl_symm_apply_of_mem hx, ←e.prop ⟨x, hx⟩, sum.map_inl, sum_congr_apply, trans_apply, subtype.coe_mk, set.sum_compl_apply_inl] }, { simp only [set.sum_compl_symm_apply_of_not_mem hx, sum.map_inr, subtype_equiv_apply, set.sum_compl_apply_inr, trans_apply, sum_congr_apply, subtype.coe_mk] }, end, right_inv := λ e, equiv.ext $ λ x, by simp only [sum.map_inr, subtype_equiv_apply, set.sum_compl_apply_inr, function.comp_app, sum_congr_apply, equiv.coe_trans, subtype.coe_eta, subtype.coe_mk, set.sum_compl_symm_apply_compl] } /-- The set product of two sets is equivalent to the type product of their coercions to types. -/ protected def prod {α β} (s : set α) (t : set β) : s.prod t ≃ s × t := @subtype_prod_equiv_prod α β s t /-- If a function `f` is injective on a set `s`, then `s` is equivalent to `f '' s`. -/ protected noncomputable def image_of_inj_on {α β} (f : α → β) (s : set α) (H : inj_on f s) : s ≃ (f '' s) := ⟨λ p, ⟨f p, mem_image_of_mem f p.2⟩, λ p, ⟨classical.some p.2, (classical.some_spec p.2).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).1 h (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ /-- If `f` is an injective function, then `s` is equivalent to `f '' s`. -/ @[simps apply] protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := equiv.set.image_of_inj_on f s (H.inj_on s) @[simp] protected lemma image_symm_apply {α β} (f : α → β) (s : set α) (H : injective f) (x : α) (h : x ∈ s) : (set.image f s H).symm ⟨f x, ⟨x, ⟨h, rfl⟩⟩⟩ = ⟨x, h⟩ := begin apply (set.image f s H).injective, simp [(set.image f s H).apply_symm_apply], end lemma image_symm_preimage {α β} {f : α → β} (hf : injective f) (u s : set α) : (λ x, (set.image f s hf).symm x : f '' s → α) ⁻¹' u = coe ⁻¹' (f '' u) := begin ext ⟨b, a, has, rfl⟩, have : ∀(h : ∃a', a' ∈ s ∧ a' = a), classical.some h = a := λ h, (classical.some_spec h).2, simp [equiv.set.image, equiv.set.image_of_inj_on, hf.eq_iff, this], end /-- If `α` is equivalent to `β`, then `set α` is equivalent to `set β`. -/ @[simps] protected def congr {α β : Type*} (e : α ≃ β) : set α ≃ set β := ⟨λ s, e '' s, λ t, e.symm '' t, symm_image_image e, symm_image_image e.symm⟩ /-- The set `{x ∈ s | t x}` is equivalent to the set of `x : s` such that `t x`. -/ protected def sep {α : Type u} (s : set α) (t : α → Prop) : ({ x ∈ s | t x } : set α) ≃ { x : s | t x } := (equiv.subtype_subtype_equiv_subtype_inter s t).symm /-- The set `𝒫 S := {x | x ⊆ S}` is equivalent to the type `set S`. -/ protected def powerset {α} (S : set α) : 𝒫 S ≃ set S := { to_fun := λ x : 𝒫 S, coe ⁻¹' (x : set α), inv_fun := λ x : set S, ⟨coe '' x, by rintro _ ⟨a : S, _, rfl⟩; exact a.2⟩, left_inv := λ x, by ext y; exact ⟨λ ⟨⟨_, _⟩, h, rfl⟩, h, λ h, ⟨⟨_, x.2 h⟩, h, rfl⟩⟩, right_inv := λ x, by ext; simp } /-- If `s` is a set in `range f`, then its image under `range_splitting f` is in bijection (via `f`) with `s`. -/ @[simps] noncomputable def range_splitting_image_equiv {α β : Type*} (f : α → β) (s : set (range f)) : range_splitting f '' s ≃ s := { to_fun := λ x, ⟨⟨f x, by simp⟩, (by { rcases x with ⟨x, ⟨y, ⟨m, rfl⟩⟩⟩, simpa [apply_range_splitting f] using m, })⟩, inv_fun := λ x, ⟨range_splitting f x, ⟨x, ⟨x.2, rfl⟩⟩⟩, left_inv := λ x, by { rcases x with ⟨x, ⟨y, ⟨m, rfl⟩⟩⟩, simp [apply_range_splitting f] }, right_inv := λ x, by simp [apply_range_splitting f], } end set /-- If `f : α → β` has a left-inverse when `α` is nonempty, then `α` is computably equivalent to the range of `f`. While awkward, the `nonempty α` hypothesis on `f_inv` and `hf` allows this to be used when `α` is empty too. This hypothesis is absent on analogous definitions on stronger `equiv`s like `linear_equiv.of_left_inverse` and `ring_equiv.of_left_inverse` as their typeclass assumptions are already sufficient to ensure non-emptiness. -/ @[simps] def of_left_inverse {α β : Sort*} (f : α → β) (f_inv : nonempty α → β → α) (hf : Π h : nonempty α, left_inverse (f_inv h) f) : α ≃ set.range f := { to_fun := λ a, ⟨f a, a, rfl⟩, inv_fun := λ b, f_inv (nonempty_of_exists b.2) b, left_inv := λ a, hf ⟨a⟩ a, right_inv := λ ⟨b, a, ha⟩, subtype.eq $ show f (f_inv ⟨a⟩ b) = b, from eq.trans (congr_arg f $ by exact ha ▸ (hf _ a)) ha } /-- If `f : α → β` has a left-inverse, then `α` is computably equivalent to the range of `f`. Note that if `α` is empty, no such `f_inv` exists and so this definition can't be used, unlike the stronger but less convenient `of_left_inverse`. -/ abbreviation of_left_inverse' {α β : Sort*} (f : α → β) (f_inv : β → α) (hf : left_inverse f_inv f) : α ≃ set.range f := of_left_inverse f (λ _, f_inv) (λ _, hf) /-- If `f : α → β` is an injective function, then domain `α` is equivalent to the range of `f`. -/ @[simps apply] noncomputable def of_injective {α β} (f : α → β) (hf : injective f) : α ≃ set.range f := equiv.of_left_inverse f (λ h, by exactI function.inv_fun f) (λ h, by exactI function.left_inverse_inv_fun hf) theorem apply_of_injective_symm {α β} (f : α → β) (hf : injective f) (b : set.range f) : f ((of_injective f hf).symm b) = b := subtype.ext_iff.1 $ (of_injective f hf).apply_symm_apply b @[simp] theorem of_injective_symm_apply {α β} (f : α → β) (hf : injective f) (a : α) : (of_injective f hf).symm ⟨f a, ⟨a, rfl⟩⟩ = a := begin apply (of_injective f hf).injective, simp [apply_of_injective_symm f hf], end @[simp] lemma self_comp_of_injective_symm {α β} (f : α → β) (hf : injective f) : f ∘ ((of_injective f hf).symm) = coe := funext (λ x, apply_of_injective_symm f hf x) lemma of_left_inverse_eq_of_injective {α β : Type*} (f : α → β) (f_inv : nonempty α → β → α) (hf : Π h : nonempty α, left_inverse (f_inv h) f) : of_left_inverse f f_inv hf = of_injective f ((em (nonempty α)).elim (λ h, (hf h).injective) (λ h _ _ _, by { haveI : subsingleton α := subsingleton_of_not_nonempty h, simp })) := by { ext, simp } lemma of_left_inverse'_eq_of_injective {α β : Type*} (f : α → β) (f_inv : β → α) (hf : left_inverse f_inv f) : of_left_inverse' f f_inv hf = of_injective f hf.injective := by { ext, simp } /-- If `f` is a bijective function, then its domain is equivalent to its codomain. -/ @[simps apply] noncomputable def of_bijective {α β} (f : α → β) (hf : bijective f) : α ≃ β := (of_injective f hf.1).trans $ (set_congr hf.2.range_eq).trans $ equiv.set.univ β lemma of_bijective_apply_symm_apply {α β} (f : α → β) (hf : bijective f) (x : β) : f ((of_bijective f hf).symm x) = x := (of_bijective f hf).apply_symm_apply x @[simp] lemma of_bijective_symm_apply_apply {α β} (f : α → β) (hf : bijective f) (x : α) : (of_bijective f hf).symm (f x) = x := (of_bijective f hf).symm_apply_apply x section variables {α' β' : Type*} (e : perm α') {p : β' → Prop} [decidable_pred p] (f : α' ≃ subtype p) /-- Extend the domain of `e : equiv.perm α` to one that is over `β` via `f : α → subtype p`, where `p : β → Prop`, permuting only the `b : β` that satisfy `p b`. This can be used to extend the domain across a function `f : α → β`, keeping everything outside of `set.range f` fixed. For this use-case `equiv` given by `f` can be constructed by `equiv.of_left_inverse'` or `equiv.of_left_inverse` when there is a known inverse, or `equiv.of_injective` in the general case.`. -/ def perm.extend_domain : perm β' := (perm_congr f e).subtype_congr (equiv.refl _) @[simp] lemma perm.extend_domain_apply_image (a : α') : e.extend_domain f (f a) = f (e a) := by simp [perm.extend_domain] lemma perm.extend_domain_apply_subtype {b : β'} (h : p b) : e.extend_domain f b = f (e (f.symm ⟨b, h⟩)) := by simp [perm.extend_domain, h] lemma perm.extend_domain_apply_not_subtype {b : β'} (h : ¬ p b) : e.extend_domain f b = b := by simp [perm.extend_domain, h] @[simp] lemma perm.extend_domain_refl : perm.extend_domain (equiv.refl _) f = equiv.refl _ := by simp [perm.extend_domain] @[simp] lemma perm.extend_domain_symm : (e.extend_domain f).symm = perm.extend_domain e.symm f := rfl lemma perm.extend_domain_trans (e e' : perm α') : (e.extend_domain f).trans (e'.extend_domain f) = perm.extend_domain (e.trans e') f := by simp [perm.extend_domain, perm_congr_trans] end /-- Subtype of the quotient is equivalent to the quotient of the subtype. Let `α` be a setoid with equivalence relation `~`. Let `p₂` be a predicate on the quotient type `α/~`, and `p₁` be the lift of this predicate to `α`: `p₁ a ↔ p₂ ⟦a⟧`. Let `~₂` be the restriction of `~` to `{x // p₁ x}`. Then `{x // p₂ x}` is equivalent to the quotient of `{x // p₁ x}` by `~₂`. -/ def subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) : {x // p₂ x} ≃ quotient s₂ := { to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧) (λ a b hab, hfunext (by rw quotient.sound hab) (λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2, inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x})) (λ a b hab, subtype.ext_val (quotient.sound ((h _ _).1 hab))), left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha, right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) } section swap variable [decidable_eq α] /-- A helper function for `equiv.swap`. -/ def swap_core (a b r : α) : α := if r = a then b else if r = b then a else r theorem swap_core_self (r a : α) : swap_core a a r = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r := by { unfold swap_core, split_ifs; cc } theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r := by { unfold swap_core, split_ifs; cc } /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : perm α := ⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩ @[simp] theorem swap_self (a : α) : swap a a = equiv.refl _ := ext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := ext $ λ r, swap_core_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : α) : swap a b b = a := by { by_cases h : b = a; simp [swap_apply_def, h], } theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp [swap_apply_def] {contextual := tt} @[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ := ext $ λ x, swap_core_swap_core _ _ _ @[simp] lemma symm_swap (a b : α) : (swap a b).symm = swap a b := rfl @[simp] lemma swap_eq_refl_iff {x y : α} : swap x y = equiv.refl _ ↔ x = y := begin refine ⟨λ h, (equiv.refl _).injective _, λ h, h ▸ (swap_self _)⟩, rw [←h, swap_apply_left, h, refl_apply] end theorem swap_comp_apply {a b x : α} (π : perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by { cases π, refl } lemma swap_eq_update (i j : α) : ⇑(equiv.swap i j) = update (update id j i) i j := funext $ λ x, by rw [update_apply _ i j, update_apply _ j i, equiv.swap_apply_def, id.def] lemma comp_swap_eq_update (i j : α) (f : α → β) : f ∘ equiv.swap i j = update (update f j (f i)) i (f j) := by rw [swap_eq_update, comp_update, comp_update, comp.right_id] @[simp] lemma symm_trans_swap_trans [decidable_eq β] (a b : α) (e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext (λ x, begin have : ∀ a, e.symm x = a ↔ x = e a := λ a, by { rw @eq_comm _ (e.symm x), split; intros; simp * at * }, simp [swap_apply_def, this], split_ifs; simp end) @[simp] lemma trans_swap_trans_symm [decidable_eq β] (a b : β) (e : α ≃ β) : (e.trans (swap a b)).trans e.symm = swap (e.symm a) (e.symm b) := symm_trans_swap_trans a b e.symm @[simp] lemma swap_apply_self (i j a : α) : swap i j (swap i j a) = a := by rw [← equiv.trans_apply, equiv.swap_swap, equiv.refl_apply] /-- A function is invariant to a swap if it is equal at both elements -/ lemma apply_swap_eq_self {v : α → β} {i j : α} (hv : v i = v j) (k : α) : v (swap i j k) = v k := begin by_cases hi : k = i, { rw [hi, swap_apply_left, hv] }, by_cases hj : k = j, { rw [hj, swap_apply_right, hv] }, rw swap_apply_of_ne_of_ne hi hj, end lemma swap_apply_eq_iff {x y z w : α} : swap x y z = w ↔ z = swap x y w := by rw [apply_eq_iff_eq_symm_apply, symm_swap] lemma swap_apply_ne_self_iff {a b x : α} : swap a b x ≠ x ↔ a ≠ b ∧ (x = a ∨ x = b) := begin by_cases hab : a = b, { simp [hab] }, by_cases hax : x = a, { simp [hax, eq_comm] }, by_cases hbx : x = b, { simp [hbx] }, simp [hab, hax, hbx, swap_apply_of_ne_of_ne] end namespace perm @[simp] lemma sum_congr_swap_refl {α β : Sort*} [decidable_eq α] [decidable_eq β] (i j : α) : equiv.perm.sum_congr (equiv.swap i j) (equiv.refl β) = equiv.swap (sum.inl i) (sum.inl j) := begin ext x, cases x, { simp [sum.map, swap_apply_def], split_ifs; refl}, { simp [sum.map, swap_apply_of_ne_of_ne] }, end @[simp] lemma sum_congr_refl_swap {α β : Sort*} [decidable_eq α] [decidable_eq β] (i j : β) : equiv.perm.sum_congr (equiv.refl α) (equiv.swap i j) = equiv.swap (sum.inr i) (sum.inr j) := begin ext x, cases x, { simp [sum.map, swap_apply_of_ne_of_ne] }, { simp [sum.map, swap_apply_def], split_ifs; refl}, end end perm /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b := by { dsimp [set_value], simp [swap_apply_left] } end swap end equiv lemma plift.eq_up_iff_down_eq {x : plift α} {y : α} : x = plift.up y ↔ x.down = y := equiv.plift.eq_symm_apply lemma function.injective.map_swap {α β : Type*} [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y z : α) : f (equiv.swap x y z) = equiv.swap (f x) (f y) (f z) := begin conv_rhs { rw equiv.swap_apply_def }, split_ifs with h₁ h₂, { rw [hf h₁, equiv.swap_apply_left] }, { rw [hf h₂, equiv.swap_apply_right] }, { rw [equiv.swap_apply_of_ne_of_ne (mt (congr_arg f) h₁) (mt (congr_arg f) h₂)] } end namespace equiv protected lemma exists_unique_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p x ↔ q (f x)) : (∃! x, p x) ↔ ∃! y, q y := begin split, { rintro ⟨a, ha₁, ha₂⟩, exact ⟨f a, h.1 ha₁, λ b hb, f.symm_apply_eq.1 (ha₂ (f.symm b) (h.2 (by simpa using hb)))⟩ }, { rintro ⟨b, hb₁, hb₂⟩, exact ⟨f.symm b, h.2 (by simpa using hb₁), λ y hy, (eq_symm_apply f).2 (hb₂ _ (h.1 hy))⟩ } end protected lemma exists_unique_congr_left' {p : α → Prop} (f : α ≃ β) : (∃! x, p x) ↔ (∃! y, p (f.symm y)) := equiv.exists_unique_congr f (λx, by simp) protected lemma exists_unique_congr_left {p : β → Prop} (f : α ≃ β) : (∃! x, p (f x)) ↔ (∃! y, p y) := (equiv.exists_unique_congr_left' f.symm).symm protected lemma forall_congr {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p x ↔ q (f x)) : (∀x, p x) ↔ (∀y, q y) := begin split; intros h₂ x, { rw [←f.right_inv x], apply h.mp, apply h₂ }, apply h.mpr, apply h₂ end protected lemma forall_congr' {p : α → Prop} {q : β → Prop} (f : α ≃ β) (h : ∀{x}, p (f.symm x) ↔ q x) : (∀x, p x) ↔ (∀y, q y) := (equiv.forall_congr f.symm (λ x, h.symm)).symm -- We next build some higher arity versions of `equiv.forall_congr`. -- Although they appear to just be repeated applications of `equiv.forall_congr`, -- unification of metavariables works better with these versions. -- In particular, they are necessary in `equiv_rw`. -- (Stopping at ternary functions seems reasonable: at least in 1-categorical mathematics, -- it's rare to have axioms involving more than 3 elements at once.) universes ua1 ua2 ub1 ub2 ug1 ug2 variables {α₁ : Sort ua1} {α₂ : Sort ua2} {β₁ : Sort ub1} {β₂ : Sort ub2} {γ₁ : Sort ug1} {γ₂ : Sort ug2} protected lemma forall₂_congr {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀{x y}, p x y ↔ q (eα x) (eβ y)) : (∀x y, p x y) ↔ (∀x y, q x y) := begin apply equiv.forall_congr, intros, apply equiv.forall_congr, intros, apply h, end protected lemma forall₂_congr' {p : α₁ → β₁ → Prop} {q : α₂ → β₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (h : ∀{x y}, p (eα.symm x) (eβ.symm y) ↔ q x y) : (∀x y, p x y) ↔ (∀x y, q x y) := (equiv.forall₂_congr eα.symm eβ.symm (λ x y, h.symm)).symm protected lemma forall₃_congr {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀{x y z}, p x y z ↔ q (eα x) (eβ y) (eγ z)) : (∀x y z, p x y z) ↔ (∀x y z, q x y z) := begin apply equiv.forall₂_congr, intros, apply equiv.forall_congr, intros, apply h, end protected lemma forall₃_congr' {p : α₁ → β₁ → γ₁ → Prop} {q : α₂ → β₂ → γ₂ → Prop} (eα : α₁ ≃ α₂) (eβ : β₁ ≃ β₂) (eγ : γ₁ ≃ γ₂) (h : ∀{x y z}, p (eα.symm x) (eβ.symm y) (eγ.symm z) ↔ q x y z) : (∀x y z, p x y z) ↔ (∀x y z, q x y z) := (equiv.forall₃_congr eα.symm eβ.symm eγ.symm (λ x y z, h.symm)).symm protected lemma forall_congr_left' {p : α → Prop} (f : α ≃ β) : (∀x, p x) ↔ (∀y, p (f.symm y)) := equiv.forall_congr f (λx, by simp) protected lemma forall_congr_left {p : β → Prop} (f : α ≃ β) : (∀x, p (f x)) ↔ (∀y, p y) := (equiv.forall_congr_left' f.symm).symm protected lemma exists_congr_left {α β} (f : α ≃ β) {p : α → Prop} : (∃ a, p a) ↔ (∃ b, p (f.symm b)) := ⟨λ ⟨a, h⟩, ⟨f a, by simpa using h⟩, λ ⟨b, h⟩, ⟨_, h⟩⟩ protected lemma set_forall_iff {α β} (e : α ≃ β) {p : set α → Prop} : (∀ a, p a) ↔ (∀ a, p (e ⁻¹' a)) := by simpa [equiv.image_eq_preimage] using (equiv.set.congr e).forall_congr_left' protected lemma preimage_sUnion {α β} (f : α ≃ β) {s : set (set β)} : f ⁻¹' (⋃₀ s) = ⋃₀ (_root_.set.image f ⁻¹' s) := by { ext x, simp [(equiv.set.congr f).symm.exists_congr_left] } section variables (P : α → Sort w) (e : α ≃ β) /-- Transport dependent functions through an equivalence of the base space. -/ @[simps] def Pi_congr_left' : (Π a, P a) ≃ (Π b, P (e.symm b)) := { to_fun := λ f x, f (e.symm x), inv_fun := λ f x, begin rw [← e.symm_apply_apply x], exact f (e x) end, left_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans (by { dsimp, rw e.symm_apply_apply })), right_inv := λ f, funext $ λ x, eq_of_heq ((eq_rec_heq _ _).trans (by { rw e.apply_symm_apply })) } end section variables (P : β → Sort w) (e : α ≃ β) /-- Transporting dependent functions through an equivalence of the base, expressed as a "simplification". -/ def Pi_congr_left : (Π a, P (e a)) ≃ (Π b, P b) := (Pi_congr_left' P e.symm).symm end section variables {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π a : α, (W a ≃ Z (h₁ a))) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibers. -/ def Pi_congr : (Π a, W a) ≃ (Π b, Z b) := (equiv.Pi_congr_right h₂).trans (equiv.Pi_congr_left _ h₁) end section variables {W : α → Sort w} {Z : β → Sort z} (h₁ : α ≃ β) (h₂ : Π b : β, (W (h₁.symm b) ≃ Z b)) /-- Transport dependent functions through an equivalence of the base spaces and a family of equivalences of the matching fibres. -/ def Pi_congr' : (Π a, W a) ≃ (Π b, Z b) := (Pi_congr h₁.symm (λ b, (h₂ b).symm)).symm end end equiv lemma function.injective.swap_apply [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y z : α) : equiv.swap (f x) (f y) (f z) = f (equiv.swap x y z) := begin by_cases hx : z = x, by simp [hx], by_cases hy : z = y, by simp [hy], rw [equiv.swap_apply_of_ne_of_ne hx hy, equiv.swap_apply_of_ne_of_ne (hf.ne hx) (hf.ne hy)] end lemma function.injective.swap_comp [decidable_eq α] [decidable_eq β] {f : α → β} (hf : function.injective f) (x y : α) : equiv.swap (f x) (f y) ∘ f = f ∘ equiv.swap x y := funext $ λ z, hf.swap_apply _ _ _ /-- If both `α` and `β` are singletons, then `α ≃ β`. -/ def equiv_of_unique_of_unique [unique α] [unique β] : α ≃ β := { to_fun := λ _, default β, inv_fun := λ _, default α, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- If `α` is a singleton, then it is equivalent to any `punit`. -/ def equiv_punit_of_unique [unique α] : α ≃ punit.{v} := equiv_of_unique_of_unique /-- If `α` is a subsingleton, then it is equivalent to `α × α`. -/ def subsingleton_prod_self_equiv {α : Type*} [subsingleton α] : α × α ≃ α := { to_fun := λ p, p.1, inv_fun := λ a, (a, a), left_inv := λ p, subsingleton.elim _ _, right_inv := λ p, subsingleton.elim _ _, } /-- To give an equivalence between two subsingleton types, it is sufficient to give any two functions between them. -/ def equiv_of_subsingleton_of_subsingleton [subsingleton α] [subsingleton β] (f : α → β) (g : β → α) : α ≃ β := { to_fun := f, inv_fun := g, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } /-- A nonempty subsingleton type is (noncomputably) equivalent to `punit`. -/ noncomputable def equiv.punit_of_nonempty_of_subsingleton {α : Sort*} [h : nonempty α] [subsingleton α] : α ≃ punit.{v} := equiv_of_subsingleton_of_subsingleton (λ _, punit.star) (λ _, h.some) /-- `unique (unique α)` is equivalent to `unique α`. -/ def unique_unique_equiv : unique (unique α) ≃ unique α := equiv_of_subsingleton_of_subsingleton (λ h, h.default) (λ h, { default := h, uniq := λ _, subsingleton.elim _ _ }) namespace quot /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/ protected def congr {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β) (eq : ∀a₁ a₂, ra a₁ a₂ ↔ rb (e a₁) (e a₂)) : quot ra ≃ quot rb := { to_fun := quot.map e (assume a₁ a₂, (eq a₁ a₂).1), inv_fun := quot.map e.symm (assume b₁ b₂ h, (eq (e.symm b₁) (e.symm b₂)).2 ((e.apply_symm_apply b₁).symm ▸ (e.apply_symm_apply b₂).symm ▸ h)), left_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.symm_apply_apply] }, right_inv := by { rintros ⟨a⟩, dunfold quot.map, simp only [equiv.apply_symm_apply] } } @[simp] lemma congr_mk {ra : α → α → Prop} {rb : β → β → Prop} (e : α ≃ β) (eq : ∀ (a₁ a₂ : α), ra a₁ a₂ ↔ rb (e a₁) (e a₂)) (a : α) : quot.congr e eq (quot.mk ra a) = quot.mk rb (e a) := rfl /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr_right {r r' : α → α → Prop} (eq : ∀a₁ a₂, r a₁ a₂ ↔ r' a₁ a₂) : quot r ≃ quot r' := quot.congr (equiv.refl α) eq /-- An equivalence `e : α ≃ β` generates an equivalence between the quotient space of `α` by a relation `ra` and the quotient space of `β` by the image of this relation under `e`. -/ protected def congr_left {r : α → α → Prop} (e : α ≃ β) : quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) := @quot.congr α β r (λ b b', r (e.symm b) (e.symm b')) e (λ a₁ a₂, by simp only [e.symm_apply_apply]) end quot namespace quotient /-- An equivalence `e : α ≃ β` generates an equivalence between quotient spaces, if `ra a₁ a₂ ↔ rb (e a₁) (e a₂). -/ protected def congr {ra : setoid α} {rb : setoid β} (e : α ≃ β) (eq : ∀a₁ a₂, @setoid.r α ra a₁ a₂ ↔ @setoid.r β rb (e a₁) (e a₂)) : quotient ra ≃ quotient rb := quot.congr e eq @[simp] lemma congr_mk {ra : setoid α} {rb : setoid β} (e : α ≃ β) (eq : ∀ (a₁ a₂ : α), setoid.r a₁ a₂ ↔ setoid.r (e a₁) (e a₂)) (a : α): quotient.congr e eq (quotient.mk a) = quotient.mk (e a) := rfl /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr_right {r r' : setoid α} (eq : ∀a₁ a₂, @setoid.r α r a₁ a₂ ↔ @setoid.r α r' a₁ a₂) : quotient r ≃ quotient r' := quot.congr_right eq end quotient /-- If a function is a bijection between two sets `s` and `t`, then it induces an equivalence between the the types `↥s` and ``↥t`. -/ noncomputable def set.bij_on.equiv {α : Type*} {β : Type*} {s : set α} {t : set β} (f : α → β) (h : set.bij_on f s t) : s ≃ t := equiv.of_bijective _ h.bijective namespace function lemma update_comp_equiv {α β α' : Sort*} [decidable_eq α'] [decidable_eq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) : update f a v ∘ g = update (f ∘ g) (g.symm a) v := by rw [← update_comp_eq_of_injective _ g.injective, g.apply_symm_apply] lemma update_apply_equiv_apply {α β α' : Sort*} [decidable_eq α'] [decidable_eq α] (f : α → β) (g : α' ≃ α) (a : α) (v : β) (a' : α') : update f a v (g a') = update (f ∘ g) (g.symm a) v a' := congr_fun (update_comp_equiv f g a v) a' end function /-- The composition of an updated function with an equiv on a subset can be expressed as an updated function. -/ lemma dite_comp_equiv_update {α : Type*} {β : Sort*} {γ : Sort*} {s : set α} (e : β ≃ s) (v : β → γ) (w : α → γ) (j : β) (x : γ) [decidable_eq β] [decidable_eq α] [∀ j, decidable (j ∈ s)] : (λ (i : α), if h : i ∈ s then (function.update v j x) (e.symm ⟨i, h⟩) else w i) = function.update (λ (i : α), if h : i ∈ s then v (e.symm ⟨i, h⟩) else w i) (e j) x := begin ext i, by_cases h : i ∈ s, { rw [dif_pos h, function.update_apply_equiv_apply, equiv.symm_symm, function.comp, function.update_apply, function.update_apply, dif_pos h], have h_coe : (⟨i, h⟩ : s) = e j ↔ i = e j := subtype.ext_iff.trans (by rw subtype.coe_mk), simp_rw h_coe, congr, }, { have : i ≠ e j, by { contrapose! h, have : (e j : α) ∈ s := (e j).2, rwa ← h at this }, simp [h, this] } end
de013276268cd46818fccd9562b8f82f483bdbac
491068d2ad28831e7dade8d6dff871c3e49d9431
/hott/init/equiv.hlean
b29987fbbaf34113417a5a3cb64da48ed17ea151
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,523
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Jakob von Raumer Ported from Coq HoTT -/ prelude import .path .function open eq function lift /- Equivalences -/ -- This is our definition of equivalence. In the HoTT-book it's called -- ihae (half-adjoint equivalence). structure is_equiv [class] {A B : Type} (f : A → B) := mk' :: (inv : B → A) (right_inv : Πb, f (inv b) = b) (left_inv : Πa, inv (f a) = a) (adj : Πx, right_inv (f x) = ap f (left_inv x)) attribute is_equiv.inv [quasireducible] -- A more bundled version of equivalence structure equiv (A B : Type) := (to_fun : A → B) (to_is_equiv : is_equiv to_fun) namespace is_equiv /- Some instances and closure properties of equivalences -/ postfix ⁻¹ := inv /- a second notation for the inverse, which is not overloaded -/ postfix [parsing-only] `⁻¹ᶠ`:std.prec.max_plus := inv section variables {A B C : Type} (f : A → B) (g : B → C) {f' : A → B} -- The variant of mk' where f is explicit. protected abbreviation mk [constructor] := @is_equiv.mk' A B f -- The identity function is an equivalence. definition is_equiv_id (A : Type) : (is_equiv (id : A → A)) := is_equiv.mk id id (λa, idp) (λa, idp) (λa, idp) -- The composition of two equivalences is, again, an equivalence. definition is_equiv_compose [constructor] [Hf : is_equiv f] [Hg : is_equiv g] : is_equiv (g ∘ f) := is_equiv.mk (g ∘ f) (f⁻¹ ∘ g⁻¹) (λc, ap g (right_inv f (g⁻¹ c)) ⬝ right_inv g c) (λa, ap (inv f) (left_inv g (f a)) ⬝ left_inv f a) (λa, (whisker_left _ (adj g (f a))) ⬝ (ap_con g _ _)⁻¹ ⬝ ap02 g ((ap_con_eq_con (right_inv f) (left_inv g (f a)))⁻¹ ⬝ (ap_compose f (inv f) _ ◾ adj f a) ⬝ (ap_con f _ _)⁻¹ ) ⬝ (ap_compose g f _)⁻¹ ) -- Any function equal to an equivalence is an equivlance as well. variable {f} definition is_equiv_eq_closed [Hf : is_equiv f] (Heq : f = f') : is_equiv f' := eq.rec_on Heq Hf end section parameters {A B : Type} (f : A → B) (g : B → A) (ret : Πb, f (g b) = b) (sec : Πa, g (f a) = a) private abbreviation adjointify_left_inv' (a : A) : g (f a) = a := ap g (ap f (inverse (sec a))) ⬝ ap g (ret (f a)) ⬝ sec a private theorem adjointify_adj' (a : A) : ret (f a) = ap f (adjointify_left_inv' a) := let fgretrfa := ap f (ap g (ret (f a))) in let fgfinvsect := ap f (ap g (ap f (sec a)⁻¹)) in let fgfa := f (g (f a)) in let retrfa := ret (f a) in have eq1 : ap f (sec a) = _, from calc ap f (sec a) = idp ⬝ ap f (sec a) : by rewrite idp_con ... = (ret (f a) ⬝ (ret (f a))⁻¹) ⬝ ap f (sec a) : by rewrite con.right_inv ... = ((ret fgfa)⁻¹ ⬝ ap (f ∘ g) (ret (f a))) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((ret fgfa)⁻¹ ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc, have eq2 : ap f (sec a) ⬝ idp = (ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a)), from !con_idp ⬝ eq1, have eq3 : idp = _, from calc idp = (ap f (sec a))⁻¹ ⬝ ((ret fgfa)⁻¹ ⬝ (fgretrfa ⬝ ap f (sec a))) : eq_inv_con_of_con_eq eq2 ... = ((ap f (sec a))⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite con.assoc' ... = (ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ (fgretrfa ⬝ ap f (sec a)) : by rewrite ap_inv ... = ((ap f (sec a)⁻¹ ⬝ (ret fgfa)⁻¹) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con.assoc' ... = ((retrfa⁻¹ ⬝ ap (f ∘ g) (ap f (sec a)⁻¹)) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite con_ap_eq_con ... = ((retrfa⁻¹ ⬝ fgfinvsect) ⬝ fgretrfa) ⬝ ap f (sec a) : by rewrite ap_compose ... = (retrfa⁻¹ ⬝ (fgfinvsect ⬝ fgretrfa)) ⬝ ap f (sec a) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a) : by rewrite ap_con ... = retrfa⁻¹ ⬝ (ap f (ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ ap f (sec a)) : by rewrite con.assoc' ... = retrfa⁻¹ ⬝ ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a) : by rewrite -ap_con, have eq4 : ret (f a) = ap f ((ap g (ap f (sec a)⁻¹) ⬝ ap g (ret (f a))) ⬝ sec a), from eq_of_idp_eq_inv_con eq3, eq4 definition adjointify [constructor] : is_equiv f := is_equiv.mk f g ret adjointify_left_inv' adjointify_adj' end -- Any function pointwise equal to an equivalence is an equivalence as well. definition homotopy_closed [constructor] {A B : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (Hty : f ~ f') : is_equiv f' := adjointify f' (inv f) (λ b, (Hty (inv f b))⁻¹ ⬝ right_inv f b) (λ a, (ap (inv f) (Hty a))⁻¹ ⬝ left_inv f a) definition inv_homotopy_closed [constructor] {A B : Type} {f : A → B} {f' : B → A} [Hf : is_equiv f] (Hty : f⁻¹ ~ f') : is_equiv f := adjointify f f' (λ b, ap f !Hty⁻¹ ⬝ right_inv f b) (λ a, !Hty⁻¹ ⬝ left_inv f a) definition is_equiv_up [instance] [constructor] (A : Type) : is_equiv (up : A → lift A) := adjointify up down (λa, by induction a;reflexivity) (λa, idp) section variables {A B C : Type} (f : A → B) {f' : A → B} [Hf : is_equiv f] (g : B → C) include Hf --The inverse of an equivalence is, again, an equivalence. definition is_equiv_inv [instance] [constructor] : is_equiv f⁻¹ := adjointify f⁻¹ f (left_inv f) (right_inv f) definition cancel_right (g : B → C) [Hgf : is_equiv (g ∘ f)] : (is_equiv g) := have Hfinv [visible] : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose f⁻¹ (g ∘ f)) (λb, ap g (@right_inv _ _ f _ b)) definition cancel_left (g : C → A) [Hgf : is_equiv (f ∘ g)] : (is_equiv g) := have Hfinv [visible] : is_equiv f⁻¹, from is_equiv_inv f, @homotopy_closed _ _ _ _ (is_equiv_compose (f ∘ g) f⁻¹) (λa, left_inv f (g a)) definition eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y theorem ap_eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : ap f (eq_of_fn_eq_fn' f q) = q := begin rewrite [↑eq_of_fn_eq_fn',+ap_con,ap_inv,-+adj,-ap_compose,con.assoc, ap_con_eq_con_ap (right_inv f) q,inv_con_cancel_left,ap_id], end definition is_equiv_ap [instance] (x y : A) : is_equiv (ap f : x = y → f x = f y) := adjointify (ap f) (eq_of_fn_eq_fn' f) (λq, !ap_con ⬝ whisker_right !ap_con _ ⬝ ((!ap_inv ⬝ inverse2 (adj f _)⁻¹) ◾ (inverse (ap_compose f f⁻¹ _)) ◾ (adj f _)⁻¹) ⬝ con_ap_con_eq_con_con (right_inv f) _ _ ⬝ whisker_right !con.left_inv _ ⬝ !idp_con) (λp, whisker_right (whisker_left _ (ap_compose f⁻¹ f _)⁻¹) _ ⬝ con_ap_con_eq_con_con (left_inv f) _ _ ⬝ whisker_right !con.left_inv _ ⬝ !idp_con) -- The function equiv_rect says that given an equivalence f : A → B, -- and a hypothesis from B, one may always assume that the hypothesis -- is in the image of e. -- In fibrational terms, if we have a fibration over B which has a section -- once pulled back along an equivalence f : A → B, then it has a section -- over all of B. definition is_equiv_rect (P : B → Type) (g : Πa, P (f a)) (b : B) : P b := right_inv f b ▸ g (f⁻¹ b) definition is_equiv_rect' (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a ▸ g (f a) definition is_equiv_rect_comp (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : is_equiv_rect f P df (f x) = df x := calc is_equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apd df (left_inv f x)) theorem adj_inv (b : B) : left_inv f (f⁻¹ b) = ap f⁻¹ (right_inv f b) := is_equiv_rect f _ (λa, eq.cancel_right (whisker_left _ !ap_id⁻¹ ⬝ (ap_con_eq_con_ap (left_inv f) (left_inv f a))⁻¹) ⬝ !ap_compose ⬝ ap02 f⁻¹ (adj f a)⁻¹) b end section variables {A B : Type} {f : A → B} [Hf : is_equiv f] {a : A} {b : B} include Hf --Rewrite rules definition eq_of_eq_inv (p : a = f⁻¹ b) : f a = b := ap f p ⬝ right_inv f b definition eq_of_inv_eq (p : f⁻¹ b = a) : b = f a := (eq_of_eq_inv p⁻¹)⁻¹ definition inv_eq_of_eq (p : b = f a) : f⁻¹ b = a := ap f⁻¹ p ⬝ left_inv f a definition eq_inv_of_eq (p : f a = b) : a = f⁻¹ b := (inv_eq_of_eq p⁻¹)⁻¹ end --Transporting is an equivalence definition is_equiv_tr [instance] [constructor] {A : Type} (P : A → Type) {x y : A} (p : x = y) : (is_equiv (transport P p)) := is_equiv.mk _ (transport P p⁻¹) (tr_inv_tr p) (inv_tr_tr p) (tr_inv_tr_lemma p) section variables {A : Type} {B C : A → Type} (f : Π{a}, B a → C a) [H : Πa, is_equiv (@f a)] {g : A → A} (h : Π{a}, B a → B (g a)) (h' : Π{a}, C a → C (g a)) include H definition inv_commute' (p : Π⦃a : A⦄ (b : B a), f (h b) = h' (f b)) {a : A} (c : C a) : f⁻¹ (h' c) = h (f⁻¹ c) := eq_of_fn_eq_fn' f (right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹) definition fun_commute_of_inv_commute' (p : Π⦃a : A⦄ (c : C a), f⁻¹ (h' c) = h (f⁻¹ c)) {a : A} (b : B a) : f (h b) = h' (f b) := eq_of_fn_eq_fn' f⁻¹ (left_inv f (h b) ⬝ ap h (left_inv f b)⁻¹ ⬝ (p (f b))⁻¹) definition ap_inv_commute' (p : Π⦃a : A⦄ (b : B a), f (h b) = h' (f b)) {a : A} (c : C a) : ap f (inv_commute' @f @h @h' p c) = right_inv f (h' c) ⬝ ap h' (right_inv f c)⁻¹ ⬝ (p (f⁻¹ c))⁻¹ := !ap_eq_of_fn_eq_fn' end end is_equiv open is_equiv namespace eq definition tr_inv_fn {A : Type} {B : A → Type} {a a' : A} (p : a = a') : transport B p⁻¹ = (transport B p)⁻¹ := idp definition tr_inv {A : Type} {B : A → Type} {a a' : A} (p : a = a') (b : B a') : p⁻¹ ▸ b = (transport B p)⁻¹ b := idp definition cast_inv_fn {A B : Type} (p : A = B) : cast p⁻¹ = (cast p)⁻¹ := idp definition cast_inv {A B : Type} (p : A = B) (b : B) : cast p⁻¹ b = (cast p)⁻¹ b := idp end eq namespace equiv namespace ops attribute to_fun [coercion] end ops open equiv.ops attribute to_is_equiv [instance] infix ` ≃ `:25 := equiv section variables {A B C : Type} protected definition MK [reducible] [constructor] (f : A → B) (g : B → A) (right_inv : Πb, f (g b) = b) (left_inv : Πa, g (f a) = a) : A ≃ B := equiv.mk f (adjointify f g right_inv left_inv) definition to_inv [reducible] [unfold 3] (f : A ≃ B) : B → A := f⁻¹ definition to_right_inv [reducible] [unfold 3] (f : A ≃ B) (b : B) : f (f⁻¹ b) = b := right_inv f b definition to_left_inv [reducible] [unfold 3] (f : A ≃ B) (a : A) : f⁻¹ (f a) = a := left_inv f a protected definition refl [refl] [constructor] : A ≃ A := equiv.mk id !is_equiv_id protected definition symm [symm] (f : A ≃ B) : B ≃ A := equiv.mk f⁻¹ !is_equiv_inv protected definition trans [trans] (f : A ≃ B) (g : B ≃ C) : A ≃ C := equiv.mk (g ∘ f) !is_equiv_compose infixl `⬝e`:75 := equiv.trans postfix [parsing-only] `⁻¹ᵉ`:(max + 1) := equiv.symm -- notation for inverse which is not overloaded abbreviation erfl [constructor] := @equiv.refl definition to_inv_trans [reducible] [unfold-full] (f : A ≃ B) (g : B ≃ C) : to_inv (f ⬝e g) = to_fun (g⁻¹ᵉ ⬝e f⁻¹ᵉ) := idp definition equiv_change_fun [constructor] (f : A ≃ B) {f' : A → B} (Heq : f ~ f') : A ≃ B := equiv.mk f' (is_equiv.homotopy_closed f Heq) definition equiv_change_inv [constructor] (f : A ≃ B) {f' : B → A} (Heq : f⁻¹ ~ f') : A ≃ B := equiv.mk f (inv_homotopy_closed Heq) --rename: eq_equiv_fn_eq_of_is_equiv definition eq_equiv_fn_eq [constructor] (f : A → B) [H : is_equiv f] (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap --rename: eq_equiv_fn_eq definition eq_equiv_fn_eq_of_equiv [constructor] (f : A ≃ B) (a b : A) : (a = b) ≃ (f a = f b) := equiv.mk (ap f) !is_equiv_ap definition equiv_ap [constructor] (P : A → Type) {a b : A} (p : a = b) : (P a) ≃ (P b) := equiv.mk (transport P p) !is_equiv_tr definition eq_of_fn_eq_fn (f : A ≃ B) {x y : A} (q : f x = f y) : x = y := (left_inv f x)⁻¹ ⬝ ap f⁻¹ q ⬝ left_inv f y definition eq_of_fn_eq_fn_inv (f : A ≃ B) {x y : B} (q : f⁻¹ x = f⁻¹ y) : x = y := (right_inv f x)⁻¹ ⬝ ap f q ⬝ right_inv f y --we need this theorem for the funext_of_ua proof theorem inv_eq {A B : Type} (eqf eqg : A ≃ B) (p : eqf = eqg) : (to_fun eqf)⁻¹ = (to_fun eqg)⁻¹ := eq.rec_on p idp definition equiv_of_equiv_of_eq [trans] {A B C : Type} (p : A = B) (q : B ≃ C) : A ≃ C := p⁻¹ ▸ q definition equiv_of_eq_of_equiv [trans] {A B C : Type} (p : A ≃ B) (q : B = C) : A ≃ C := q ▸ p definition equiv_lift [constructor] (A : Type) : A ≃ lift A := equiv.mk up _ definition equiv_rect (f : A ≃ B) (P : B → Type) (g : Πa, P (f a)) (b : B) : P b := right_inv f b ▸ g (f⁻¹ b) definition equiv_rect' (f : A ≃ B) (P : A → B → Type) (g : Πb, P (f⁻¹ b) b) (a : A) : P a (f a) := left_inv f a ▸ g (f a) definition equiv_rect_comp (f : A ≃ B) (P : B → Type) (df : Π (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) = df x := calc equiv_rect f P df (f x) = right_inv f (f x) ▸ df (f⁻¹ (f x)) : by esimp ... = ap f (left_inv f x) ▸ df (f⁻¹ (f x)) : by rewrite -adj ... = left_inv f x ▸ df (f⁻¹ (f x)) : by rewrite -tr_compose ... = df x : by rewrite (apd df (left_inv f x)) end section variables {A : Type} {B C : A → Type} (f : Π{a}, B a ≃ C a) {g : A → A} (h : Π{a}, B a → B (g a)) (h' : Π{a}, C a → C (g a)) definition inv_commute (p : Π⦃a : A⦄ (b : B a), f (h b) = h' (f b)) {a : A} (c : C a) : f⁻¹ (h' c) = h (f⁻¹ c) := inv_commute' @f @h @h' p c definition fun_commute_of_inv_commute (p : Π⦃a : A⦄ (c : C a), f⁻¹ (h' c) = h (f⁻¹ c)) {a : A} (b : B a) : f (h b) = h' (f b) := fun_commute_of_inv_commute' @f @h @h' p b end namespace ops postfix ⁻¹ := equiv.symm -- overloaded notation for inverse end ops end equiv open equiv equiv.ops namespace is_equiv definition is_equiv_of_equiv_of_homotopy [constructor] {A B : Type} (f : A ≃ B) {f' : A → B} (Hty : f ~ f') : is_equiv f' := homotopy_closed f Hty end is_equiv export [unfold-hints] equiv [unfold-hints] is_equiv
7ffcfa07ba44237a709d9e416f79b64b21d3d113
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Compiler/TerminalCases.lean
5d3b47763cca426491d58d77adea2d8bbb35faf7
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
3,065
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Check import Lean.Compiler.Util import Lean.Compiler.Decl import Lean.Compiler.CompilerM namespace Lean.Compiler namespace TerminalCases structure Context where jp? : Option Expr := none abbrev M := ReaderT Context CompilerM mutual partial def visitCases (casesInfo : CasesInfo) (cases : Expr) : M Expr := do let mut args := cases.getAppArgs if let some jp := (← read).jp? then let .forallE _ _ b _ ← inferType jp | unreachable! -- jp's type is guaranteed to be an nondependent arrow, see `visitLet` args := casesInfo.updateResultingType args b for i in casesInfo.altsRange do args ← args.modifyM i visitLambda return mkAppN cases.getAppFn args partial def visitLambda (e : Expr) : M Expr := withNewScope do let (as, e) ← Compiler.visitLambda e let e ← mkLetUsingScope (← visitLet e #[]) mkLambda as e partial def visitLet (e : Expr) (fvars : Array Expr) : M Expr := do match e with | .letE binderName type value body nonDep => let type := type.instantiateRev fvars let mut value := value.instantiateRev fvars if let some casesInfo ← isCasesApp? value then let bodyAbst ← withNewScope do let x ← mkLocalDecl binderName type let body ← visitLet body (fvars.push x) let body ← mkLetUsingScope body let bodyAbst := body.abstract #[x] return bodyAbst let jp ← if (← isSimpleLCNF bodyAbst) then -- Join point is too simple, we eagerly inline it. pure <| .lam binderName type bodyAbst .default else mkJpDecl (.lam binderName type bodyAbst .default) withReader (fun _ => { jp? := some jp }) do visitCases casesInfo value else if value.isLambda then value ← withReader (fun _ => {}) <| visitLambda value let fvar ← mkLetDecl binderName type value nonDep visitLet body (fvars.push fvar) | e => let e := e.instantiateRev fvars if let some casesInfo ← isCasesApp? e then visitCases casesInfo e else match (← read).jp? with | none => return e | some jp => let .forallE _ d b _ ← inferType jp | unreachable! let mkJpApp (x : Expr) := mkApp jp x |>.headBeta if isLcUnreachable e then mkLcUnreachable b else if compatibleTypes (← inferType e) d then let x ← mkAuxLetDecl e return mkJpApp x else if let some x := isLcCast? e then let x ← mkAuxLetDecl (← mkLcCast x d) return mkJpApp x else let x ← mkAuxLetDecl e let x ← mkAuxLetDecl (← mkLcCast x d) return mkJpApp x end end TerminalCases /-- Ensure all `casesOn` and `matcher` applications are terminal. -/ def Decl.terminalCases (decl : Decl) : CoreM Decl := decl.mapValue fun value => TerminalCases.visitLambda value |>.run {} end Lean.Compiler
e414ef03a6631d6a830c1dac546187e5e7ead729
38ee9024fb5974f555fb578fcf5a5a7b71e669b5
/Mathlib/Tactic/LibrarySearch.lean
de922cd96ee2ae3483d774ae66645117c0772aeb
[ "Apache-2.0" ]
permissive
denayd/mathlib4
750e0dcd106554640a1ac701e51517501a574715
7f40a5c514066801ab3c6d431e9f405baa9b9c58
refs/heads/master
1,693,743,991,894
1,636,618,048,000
1,636,618,048,000
373,926,241
0
0
null
null
null
null
UTF-8
Lean
false
false
4,632
lean
/- Copyright (c) 2021 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Gabriel Ebner -/ import Mathlib.Tactic.Cache import Mathlib.Tactic.Core import Mathlib.Tactic.SolveByElim import Mathlib.Tactic.TryThis /-! # Library search This file defines a tactic `librarySearch` and a term elaborator `librarySearch%` that tries to find a lemma solving the current goal (subgoals are solved using `solveByElim`). ``` example : x < x + 1 := librarySearch% example : Nat := by librarySearch ``` -/ namespace Tactic namespace LibrarySearch open Lean Meta TryThis initialize registerTraceClass `Tactic.librarySearch -- from Lean.Server.Completion private def isBlackListed (declName : Name) : MetaM Bool := do if declName matches Name.str _ "inj" _ then return false if declName matches Name.str _ "noConfusionType" _ then return false let env ← getEnv declName.isInternal <||> isAuxRecursor env declName <||> isNoConfusion env declName <||> isRec declName <||> isMatcher declName initialize librarySearchLemmas : DeclCache (DiscrTree Name) ← DeclCache.mk "librarySearch: init cache" {} fun name constInfo lemmas => do if constInfo.isUnsafe then return lemmas if ← isBlackListed name then return lemmas withNewMCtxDepth do let (xs, bis, type) ← withReducible <| forallMetaTelescopeReducing constInfo.type let keys ← withReducible <| DiscrTree.mkPath type lemmas.insertCore keys name def librarySearch (mvarId : MVarId) (lemmas : DiscrTree Name) (solveByElimDepth := 6) : MetaM <| Option (Array <| MetavarContext × List MVarId) := do profileitM Exception "librarySearch" (← getOptions) do let mvar := mkMVar mvarId let ty ← inferType mvar let mut suggestions := #[] let state0 ← get try solveByElim solveByElimDepth mvarId return none catch _ => set state0 for lem in ← lemmas.getMatch ty do trace[Tactic.librarySearch] "{lem}" match ← traceCtx `Tactic.librarySearch try let newMVars ← apply mvarId (← mkConstWithFreshMVarLevels lem) (try for newMVar in newMVars do withMVarContext newMVar do trace[Tactic.librarySearch] "proving {← addMessageContextFull (mkMVar newMVar)}" solveByElim solveByElimDepth newMVar some (Sum.inr ()) catch _ => let res := some (Sum.inl <| (← getMCtx, newMVars)) set state0 res) catch _ => set state0 none with | none => () | some (Sum.inr ()) => return none | some (Sum.inl suggestion) => suggestions := suggestions.push suggestion some suggestions def lines (ls : List MessageData) := MessageData.joinSep ls (MessageData.ofFormat Format.line) open Lean.Parser.Tactic -- TODO: implement the additional options for `library_search` from Lean 3, -- in particular including additional lemmas -- with `library_search [X, Y, Z]` or `library_search with attr`, -- or requiring that a particular hypothesis is used in the solution, with `library_search using h`. syntax (name := librarySearch') "librarySearch" (" (" &"config" " := " term ")")? (" [" simpArg,* "]")? (" with " (colGt ident)+)? (" using " (colGt ident)+)? : tactic -- For now we only implement the basic functionality. -- The full syntax is recognized, but will produce a "Tactic has not been implemented" error. open Elab.Tactic Elab Tactic in elab_rules : tactic | `(tactic| librarySearch%$tk) => do withNestedTraces do trace[Tactic.librarySearch] "proving {← getMainTarget}" let mvar ← getMainGoal let (hs, introdMVar) ← intros (← getMainGoal) withMVarContext introdMVar do if let some suggestions ← librarySearch introdMVar (← librarySearchLemmas.get) then for suggestion in suggestions do addExactSuggestion tk (← instantiateMVars (mkMVar mvar)) admitGoal introdMVar else addExactSuggestion tk (← instantiateMVars (mkMVar mvar)) open Elab Term in elab tk:"librarySearch%" : term <= expectedType => do withNestedTraces do trace[Tactic.librarySearch] "proving {expectedType}" let mvar ← mkFreshExprMVar expectedType let (hs, introdMVar) ← intros mvar.mvarId! withMVarContext introdMVar do if let some suggestions ← librarySearch introdMVar (← librarySearchLemmas.get) then for suggestion in suggestions do addTermSuggestion tk (← instantiateMVars mvar) mkSorry expectedType (synthetic := true) else addTermSuggestion tk (← instantiateMVars mvar) instantiateMVars mvar
40ecdb87038ccc22e4034fbf987ce641e8aaadce
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/topology/algebra/ordered.lean
a581eac2d060b151719100766edc551a280c6457
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
152,848
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import tactic.linarith import tactic.tfae import algebra.archimedean import algebra.group.pi import algebra.ordered_ring import order.liminf_limsup import data.set.intervals.image_preimage import data.set.intervals.ord_connected import data.set.intervals.surj_on import data.set.intervals.pi import topology.algebra.group import topology.extend_from_subset import order.filter.interval /-! # Theory of topology on ordered spaces ## Main definitions The order topology on an ordered space is the topology generated by all open intervals (or equivalently by those of the form `(-∞, a)` and `(b, +∞)`). We define it as `preorder.topology α`. However, we do *not* register it as an instance (as many existing ordered types already have topologies, which would be equal but not definitionally equal to `preorder.topology α`). Instead, we introduce a class `order_topology α`(which is a `Prop`, also known as a mixin) saying that on the type `α` having already a topological space structure and a preorder structure, the topological structure is equal to the order topology. We also introduce another (mixin) class `order_closed_topology α` saying that the set of points `(x, y)` with `x ≤ y` is closed in the product space. This is automatically satisfied on a linear order with the order topology. We prove many basic properties of such topologies. ## Main statements This file contains the proofs of the following facts. For exact requirements (`order_closed_topology` vs `order_topology`, `preorder` vs `partial_order` vs `linear_order` etc) see their statements. ### Open / closed sets * `is_open_lt` : if `f` and `g` are continuous functions, then `{x | f x < g x}` is open; * `is_open_Iio`, `is_open_Ioi`, `is_open_Ioo` : open intervals are open; * `is_closed_le` : if `f` and `g` are continuous functions, then `{x | f x ≤ g x}` is closed; * `is_closed_Iic`, `is_closed_Ici`, `is_closed_Icc` : closed intervals are closed; * `frontier_le_subset_eq`, `frontier_lt_subset_eq` : frontiers of both `{x | f x ≤ g x}` and `{x | f x < g x}` are included by `{x | f x = g x}`; * `exists_Ioc_subset_of_mem_nhds`, `exists_Ico_subset_of_mem_nhds` : if `x < y`, then any neighborhood of `x` includes an interval `[x, z)` for some `z ∈ (x, y]`, and any neighborhood of `y` includes an interval `(z, y]` for some `z ∈ [x, y)`. ### Convergence and inequalities * `le_of_tendsto_of_tendsto` : if `f` converges to `a`, `g` converges to `b`, and eventually `f x ≤ g x`, then `a ≤ b` * `le_of_tendsto`, `ge_of_tendsto` : if `f` converges to `a` and eventually `f x ≤ b` (resp., `b ≤ f x`), then `a ≤ b` (resp., `b ≤ a); we also provide primed versions that assume the inequalities to hold for all `x`. ### Min, max, `Sup` and `Inf` * `continuous.min`, `continuous.max`: pointwise `min`/`max` of two continuous functions is continuous. * `tendsto.min`, `tendsto.max` : if `f` tends to `a` and `g` tends to `b`, then their pointwise `min`/`max` tend to `min a b` and `max a b`, respectively. * `tendsto_of_tendsto_of_tendsto_of_le_of_le` : theorem known as squeeze theorem, sandwich theorem, theorem of Carabinieri, and two policemen (and a drunk) theorem; if `g` and `h` both converge to `a`, and eventually `g x ≤ f x ≤ h x`, then `f` converges to `a`. ### Connected sets and Intermediate Value Theorem * `is_preconnected_I??` : all intervals `I??` are preconnected, * `is_preconnected.intermediate_value`, `intermediate_value_univ` : Intermediate Value Theorem for connected sets and connected spaces, respectively; * `intermediate_value_Icc`, `intermediate_value_Icc'`: Intermediate Value Theorem for functions on closed intervals. ### Miscellaneous facts * `is_compact.exists_forall_le`, `is_compact.exists_forall_ge` : extreme value theorem, a continuous function on a compact set takes its minimum and maximum values. * `is_closed.Icc_subset_of_forall_mem_nhds_within` : “Continuous induction” principle; if `s ∩ [a, b]` is closed, `a ∈ s`, and for each `x ∈ [a, b) ∩ s` some of its right neighborhoods is included `s`, then `[a, b] ⊆ s`. * `is_closed.Icc_subset_of_forall_exists_gt`, `is_closed.mem_of_ge_of_forall_exists_gt` : two other versions of the “continuous induction” principle. ## Implementation We do _not_ register the order topology as an instance on a preorder (or even on a linear order). Indeed, on many such spaces, a topology has already been constructed in a different way (think of the discrete spaces `ℕ` or `ℤ`, or `ℝ` that could inherit a topology as the completion of `ℚ`), and is in general not defeq to the one generated by the intervals. We make it available as a definition `preorder.topology α` though, that can be registered as an instance when necessary, or for specific types. -/ open classical set filter topological_space open function (curry uncurry) open_locale topological_space classical filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- A topology on a set which is both a topological space and a preorder is _order-closed_ if the set of points `(x, y)` with `x ≤ y` is closed in the product space. We introduce this as a mixin. This property is satisfied for the order topology on a linear order, but it can be satisfied more generally, and suffices to derive many interesting properties relating order and topology. -/ class order_closed_topology (α : Type*) [topological_space α] [preorder α] : Prop := (is_closed_le' : is_closed {p:α×α | p.1 ≤ p.2}) instance : Π [topological_space α], topological_space (order_dual α) := id section order_closed_topology section preorder variables [topological_space α] [preorder α] [t : order_closed_topology α] include t lemma is_closed_le_prod : is_closed {p : α × α | p.1 ≤ p.2} := t.is_closed_le' lemma is_closed_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_closed {b | f b ≤ g b} := continuous_iff_is_closed.mp (hf.prod_mk hg) _ is_closed_le_prod lemma is_closed_le' (a : α) : is_closed {b | b ≤ a} := is_closed_le continuous_id continuous_const lemma is_closed_Iic {a : α} : is_closed (Iic a) := is_closed_le' a lemma is_closed_ge' (a : α) : is_closed {b | a ≤ b} := is_closed_le continuous_const continuous_id lemma is_closed_Ici {a : α} : is_closed (Ici a) := is_closed_ge' a instance : order_closed_topology (order_dual α) := ⟨(@order_closed_topology.is_closed_le' α _ _ _).preimage continuous_swap⟩ lemma is_closed_Icc {a b : α} : is_closed (Icc a b) := is_closed_inter is_closed_Ici is_closed_Iic @[simp] lemma closure_Icc (a b : α) : closure (Icc a b) = Icc a b := is_closed_Icc.closure_eq @[simp] lemma closure_Iic (a : α) : closure (Iic a) = Iic a := is_closed_Iic.closure_eq @[simp] lemma closure_Ici (a : α) : closure (Ici a) = Ici a := is_closed_Ici.closure_eq lemma le_of_tendsto_of_tendsto {f g : β → α} {b : filter β} {a₁ a₂ : α} [ne_bot b] (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : f ≤ᶠ[b] g) : a₁ ≤ a₂ := have tendsto (λb, (f b, g b)) b (𝓝 (a₁, a₂)), by rw [nhds_prod_eq]; exact hf.prod_mk hg, show (a₁, a₂) ∈ {p:α×α | p.1 ≤ p.2}, from t.is_closed_le'.mem_of_tendsto this h lemma le_of_tendsto_of_tendsto' {f g : β → α} {b : filter β} {a₁ a₂ : α} [ne_bot b] (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) (h : ∀ x, f x ≤ g x) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto hf hg (eventually_of_forall h) lemma le_of_tendsto {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, f c ≤ b) : a ≤ b := le_of_tendsto_of_tendsto lim tendsto_const_nhds h lemma le_of_tendsto' {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ c, f c ≤ b) : a ≤ b := le_of_tendsto lim (eventually_of_forall h) lemma ge_of_tendsto {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ᶠ c in x, b ≤ f c) : b ≤ a := le_of_tendsto_of_tendsto tendsto_const_nhds lim h lemma ge_of_tendsto' {f : β → α} {a b : α} {x : filter β} [ne_bot x] (lim : tendsto f x (𝓝 a)) (h : ∀ c, b ≤ f c) : b ≤ a := ge_of_tendsto lim (eventually_of_forall h) @[simp] lemma closure_le_eq [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b ≤ g b} = {b | f b ≤ g b} := (is_closed_le hf hg).closure_eq lemma closure_lt_subset_le [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : closure {b | f b < g b} ⊆ {b | f b ≤ g b} := by { rw [←closure_le_eq hf hg], exact closure_mono (λ b, le_of_lt) } lemma continuous_within_at.closure_le [topological_space β] {f g : β → α} {s : set β} {x : β} (hx : x ∈ closure s) (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) (h : ∀ y ∈ s, f y ≤ g y) : f x ≤ g x := show (f x, g x) ∈ {p : α × α | p.1 ≤ p.2}, from order_closed_topology.is_closed_le'.closure_subset ((hf.prod hg).mem_closure hx h) /-- If `s` is a closed set and two functions `f` and `g` are continuous on `s`, then the set `{x ∈ s | f x ≤ g x}` is a closed set. -/ lemma is_closed.is_closed_le [topological_space β] {f g : β → α} {s : set β} (hs : is_closed s) (hf : continuous_on f s) (hg : continuous_on g s) : is_closed {x ∈ s | f x ≤ g x} := (hf.prod hg).preimage_closed_of_closed hs order_closed_topology.is_closed_le' omit t lemma nhds_within_Ici_ne_bot {a b : α} (H₂ : a ≤ b) : ne_bot (𝓝[Ici a] b) := nhds_within_ne_bot_of_mem H₂ @[instance] lemma nhds_within_Ici_self_ne_bot (a : α) : ne_bot (𝓝[Ici a] a) := nhds_within_Ici_ne_bot (le_refl a) lemma nhds_within_Iic_ne_bot {a b : α} (H : a ≤ b) : ne_bot (𝓝[Iic b] a) := nhds_within_ne_bot_of_mem H @[instance] lemma nhds_within_Iic_self_ne_bot (a : α) : ne_bot (𝓝[Iic a] a) := nhds_within_Iic_ne_bot (le_refl a) end preorder section partial_order variables [topological_space α] [partial_order α] [t : order_closed_topology α] include t private lemma is_closed_eq : is_closed {p : α × α | p.1 = p.2} := by simp only [le_antisymm_iff]; exact is_closed_inter t.is_closed_le' (is_closed_le continuous_snd continuous_fst) @[priority 90] -- see Note [lower instance priority] instance order_closed_topology.to_t2_space : t2_space α := { t2 := have is_open {p : α × α | p.1 ≠ p.2}, from is_closed_eq, assume a b h, let ⟨u, v, hu, hv, ha, hb, h⟩ := is_open_prod_iff.mp this a b h in ⟨u, v, hu, hv, ha, hb, set.eq_empty_iff_forall_not_mem.2 $ assume a ⟨h₁, h₂⟩, have a ≠ a, from @h (a, a) ⟨h₁, h₂⟩, this rfl⟩ } end partial_order section linear_order variables [topological_space α] [linear_order α] [order_closed_topology α] lemma is_open_lt_prod : is_open {p : α × α | p.1 < p.2} := by { simp_rw [← is_closed_compl_iff, compl_set_of, not_lt], exact is_closed_le continuous_snd continuous_fst } lemma is_open_lt [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : is_open {b | f b < g b} := by simp [lt_iff_not_ge, -not_le]; exact is_closed_le hg hf variables {a b : α} lemma is_open_Iio : is_open (Iio a) := is_open_lt continuous_id continuous_const lemma is_open_Ioi : is_open (Ioi a) := is_open_lt continuous_const continuous_id lemma is_open_Ioo : is_open (Ioo a b) := is_open_inter is_open_Ioi is_open_Iio @[simp] lemma interior_Ioi : interior (Ioi a) = Ioi a := is_open_Ioi.interior_eq @[simp] lemma interior_Iio : interior (Iio a) = Iio a := is_open_Iio.interior_eq @[simp] lemma interior_Ioo : interior (Ioo a b) = Ioo a b := is_open_Ioo.interior_eq variables [topological_space γ] /-- Intermediate value theorem for two functions: if `f` and `g` are two continuous functions on a preconnected space and `f a ≤ g a` and `g b ≤ f b`, then for some `x` we have `f x = g x`. -/ lemma intermediate_value_univ₂ [preconnected_space γ] {a b : γ} {f g : γ → α} (hf : continuous f) (hg : continuous g) (ha : f a ≤ g a) (hb : g b ≤ f b) : ∃ x, f x = g x := begin obtain ⟨x, h, hfg, hgf⟩ : (univ ∩ {x | f x ≤ g x ∧ g x ≤ f x}).nonempty, from is_preconnected_closed_iff.1 preconnected_space.is_preconnected_univ _ _ (is_closed_le hf hg) (is_closed_le hg hf) (λ x hx, le_total _ _) ⟨a, trivial, ha⟩ ⟨b, trivial, hb⟩, exact ⟨x, le_antisymm hfg hgf⟩ end /-- Intermediate value theorem for two functions: if `f` and `g` are two functions continuous on a preconnected set `s` and for some `a b ∈ s` we have `f a ≤ g a` and `g b ≤ f b`, then for some `x ∈ s` we have `f x = g x`. -/ lemma is_preconnected.intermediate_value₂ {s : set γ} (hs : is_preconnected s) {a b : γ} (ha : a ∈ s) (hb : b ∈ s) {f g : γ → α} (hf : continuous_on f s) (hg : continuous_on g s) (ha' : f a ≤ g a) (hb' : g b ≤ f b) : ∃ x ∈ s, f x = g x := let ⟨x, hx⟩ := @intermediate_value_univ₂ α s _ _ _ _ (subtype.preconnected_space hs) ⟨a, ha⟩ ⟨b, hb⟩ _ _ (continuous_on_iff_continuous_restrict.1 hf) (continuous_on_iff_continuous_restrict.1 hg) ha' hb' in ⟨x, x.2, hx⟩ /-- Intermediate Value Theorem for continuous functions on connected sets. -/ lemma is_preconnected.intermediate_value {s : set γ} (hs : is_preconnected s) {a b : γ} (ha : a ∈ s) (hb : b ∈ s) {f : γ → α} (hf : continuous_on f s) : Icc (f a) (f b) ⊆ f '' s := λ x hx, mem_image_iff_bex.2 $ hs.intermediate_value₂ ha hb hf continuous_on_const hx.1 hx.2 /-- Intermediate Value Theorem for continuous functions on connected spaces. -/ lemma intermediate_value_univ [preconnected_space γ] (a b : γ) {f : γ → α} (hf : continuous f) : Icc (f a) (f b) ⊆ range f := λ x hx, intermediate_value_univ₂ hf continuous_const hx.1 hx.2 /-- Intermediate Value Theorem for continuous functions on connected spaces. -/ lemma mem_range_of_exists_le_of_exists_ge [preconnected_space γ] {c : α} {f : γ → α} (hf : continuous f) (h₁ : ∃ a, f a ≤ c) (h₂ : ∃ b, c ≤ f b) : c ∈ range f := let ⟨a, ha⟩ := h₁, ⟨b, hb⟩ := h₂ in intermediate_value_univ a b hf ⟨ha, hb⟩ /-- If a preconnected set contains endpoints of an interval, then it includes the whole interval. -/ lemma is_preconnected.Icc_subset {s : set α} (hs : is_preconnected s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : Icc a b ⊆ s := by simpa only [image_id] using hs.intermediate_value ha hb continuous_on_id /-- If a preconnected set contains endpoints of an interval, then it includes the whole interval. -/ lemma is_connected.Icc_subset {s : set α} (hs : is_connected s) {a b : α} (ha : a ∈ s) (hb : b ∈ s) : Icc a b ⊆ s := hs.2.Icc_subset ha hb /-- If preconnected set in a linear order space is unbounded below and above, then it is the whole space. -/ lemma is_preconnected.eq_univ_of_unbounded {s : set α} (hs : is_preconnected s) (hb : ¬bdd_below s) (ha : ¬bdd_above s) : s = univ := begin refine eq_univ_of_forall (λ x, _), obtain ⟨y, ys, hy⟩ : ∃ y ∈ s, y < x := not_bdd_below_iff.1 hb x, obtain ⟨z, zs, hz⟩ : ∃ z ∈ s, x < z := not_bdd_above_iff.1 ha x, exact hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩ end /-! ### Neighborhoods to the left and to the right on an `order_closed_topology` Limits to the left and to the right of real functions are defined in terms of neighborhoods to the left and to the right, either open or closed, i.e., members of `𝓝[Ioi a] a` and `𝓝[Ici a] a` on the right, and similarly on the left. Here we simply prove that all right-neighborhoods of a point are equal, and we'll prove later other useful characterizations which require the stronger hypothesis `order_topology α` -/ /-! #### Right neighborhoods, point excluded -/ lemma Ioo_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Ioo a c ∈ 𝓝[Ioi b] b := mem_nhds_within.2 ⟨Iio c, is_open_Iio, H.2, by rw [inter_comm, Ioi_inter_Iio]; exact Ioo_subset_Ioo_left H.1⟩ lemma Ioc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Ioc a c ∈ 𝓝[Ioi b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ioc_self lemma Ico_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Ico a c ∈ 𝓝[Ioi b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Ico_self lemma Icc_mem_nhds_within_Ioi {a b c : α} (H : b ∈ Ico a c) : Icc a c ∈ 𝓝[Ioi b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Ioi H) Ioo_subset_Icc_self @[simp] lemma nhds_within_Ioc_eq_nhds_within_Ioi {a b : α} (h : a < b) : 𝓝[Ioc a b] a = 𝓝[Ioi a] a := le_antisymm (nhds_within_mono _ Ioc_subset_Ioi_self) $ nhds_within_le_of_mem $ Ioc_mem_nhds_within_Ioi $ left_mem_Ico.2 h @[simp] lemma nhds_within_Ioo_eq_nhds_within_Ioi {a b : α} (h : a < b) : 𝓝[Ioo a b] a = 𝓝[Ioi a] a := le_antisymm (nhds_within_mono _ Ioo_subset_Ioi_self) $ nhds_within_le_of_mem $ Ioo_mem_nhds_within_Ioi $ left_mem_Ico.2 h @[simp] lemma continuous_within_at_Ioc_iff_Ioi [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioc a b) a ↔ continuous_within_at f (Ioi a) a := by simp only [continuous_within_at, nhds_within_Ioc_eq_nhds_within_Ioi h] @[simp] lemma continuous_within_at_Ioo_iff_Ioi [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioo a b) a ↔ continuous_within_at f (Ioi a) a := by simp only [continuous_within_at, nhds_within_Ioo_eq_nhds_within_Ioi h] /-! #### Left neighborhoods, point excluded -/ lemma Ioo_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Ioo a c ∈ 𝓝[Iio b] b := by simpa only [dual_Ioo] using @Ioo_mem_nhds_within_Ioi (order_dual α) _ _ _ _ _ _ ⟨H.2, H.1⟩ lemma Ico_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Ico a c ∈ 𝓝[Iio b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Ico_self lemma Ioc_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Ioc a c ∈ 𝓝[Iio b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Ioc_self lemma Icc_mem_nhds_within_Iio {a b c : α} (H : b ∈ Ioc a c) : Icc a c ∈ 𝓝[Iio b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Iio H) Ioo_subset_Icc_self @[simp] lemma nhds_within_Ico_eq_nhds_within_Iio {a b : α} (h : a < b) : 𝓝[Ico a b] b = 𝓝[Iio b] b := by simpa only [dual_Ioc] using @nhds_within_Ioc_eq_nhds_within_Ioi (order_dual α) _ _ _ _ _ h @[simp] lemma nhds_within_Ioo_eq_nhds_within_Iio {a b : α} (h : a < b) : 𝓝[Ioo a b] b = 𝓝[Iio b] b := by simpa only [dual_Ioo] using @nhds_within_Ioo_eq_nhds_within_Ioi (order_dual α) _ _ _ _ _ h @[simp] lemma continuous_within_at_Ico_iff_Iio {a b : α} {f : α → γ} (h : a < b) : continuous_within_at f (Ico a b) b ↔ continuous_within_at f (Iio b) b := by simp only [continuous_within_at, nhds_within_Ico_eq_nhds_within_Iio h] @[simp] lemma continuous_within_at_Ioo_iff_Iio {a b : α} {f : α → γ} (h : a < b) : continuous_within_at f (Ioo a b) b ↔ continuous_within_at f (Iio b) b := by simp only [continuous_within_at, nhds_within_Ioo_eq_nhds_within_Iio h] /-! #### Right neighborhoods, point included -/ lemma Ioo_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ioo a c) : Ioo a c ∈ 𝓝[Ici b] b := mem_nhds_within_of_mem_nhds $ mem_nhds_sets is_open_Ioo H lemma Ioc_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ioo a c) : Ioc a c ∈ 𝓝[Ici b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Ici H) Ioo_subset_Ioc_self lemma Ico_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ico a c) : Ico a c ∈ 𝓝[Ici b] b := mem_nhds_within.2 ⟨Iio c, is_open_Iio, H.2, by simp only [inter_comm, Ici_inter_Iio, Ico_subset_Ico_left H.1]⟩ lemma Icc_mem_nhds_within_Ici {a b c : α} (H : b ∈ Ico a c) : Icc a c ∈ 𝓝[Ici b] b := mem_sets_of_superset (Ico_mem_nhds_within_Ici H) Ico_subset_Icc_self @[simp] lemma nhds_within_Icc_eq_nhds_within_Ici {a b : α} (h : a < b) : 𝓝[Icc a b] a = 𝓝[Ici a] a := le_antisymm (nhds_within_mono _ Icc_subset_Ici_self) $ nhds_within_le_of_mem $ Icc_mem_nhds_within_Ici $ left_mem_Ico.2 h @[simp] lemma nhds_within_Ico_eq_nhds_within_Ici {a b : α} (h : a < b) : 𝓝[Ico a b] a = 𝓝[Ici a] a := le_antisymm (nhds_within_mono _ (λ x, and.left)) $ nhds_within_le_of_mem $ Ico_mem_nhds_within_Ici $ left_mem_Ico.2 h @[simp] lemma continuous_within_at_Icc_iff_Ici [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Icc a b) a ↔ continuous_within_at f (Ici a) a := by simp only [continuous_within_at, nhds_within_Icc_eq_nhds_within_Ici h] @[simp] lemma continuous_within_at_Ico_iff_Ici [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ico a b) a ↔ continuous_within_at f (Ici a) a := by simp only [continuous_within_at, nhds_within_Ico_eq_nhds_within_Ici h] /-! #### Left neighborhoods, point included -/ lemma Ioo_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioo a c) : Ioo a c ∈ 𝓝[Iic b] b := mem_nhds_within_of_mem_nhds $ mem_nhds_sets is_open_Ioo H lemma Ico_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioo a c) : Ico a c ∈ 𝓝[Iic b] b := mem_sets_of_superset (Ioo_mem_nhds_within_Iic H) Ioo_subset_Ico_self lemma Ioc_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioc a c) : Ioc a c ∈ 𝓝[Iic b] b := by simpa only [dual_Ico] using @Ico_mem_nhds_within_Ici (order_dual α) _ _ _ _ _ _ ⟨H.2, H.1⟩ lemma Icc_mem_nhds_within_Iic {a b c : α} (H : b ∈ Ioc a c) : Icc a c ∈ 𝓝[Iic b] b := mem_sets_of_superset (Ioc_mem_nhds_within_Iic H) Ioc_subset_Icc_self @[simp] lemma nhds_within_Icc_eq_nhds_within_Iic {a b : α} (h : a < b) : 𝓝[Icc a b] b = 𝓝[Iic b] b := by simpa only [dual_Icc] using @nhds_within_Icc_eq_nhds_within_Ici (order_dual α) _ _ _ _ _ h @[simp] lemma nhds_within_Ioc_eq_nhds_within_Iic {a b : α} (h : a < b) : 𝓝[Ioc a b] b = 𝓝[Iic b] b := by simpa only [dual_Ico] using @nhds_within_Ico_eq_nhds_within_Ici (order_dual α) _ _ _ _ _ h @[simp] lemma continuous_within_at_Icc_iff_Iic [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Icc a b) b ↔ continuous_within_at f (Iic b) b := by simp only [continuous_within_at, nhds_within_Icc_eq_nhds_within_Iic h] @[simp] lemma continuous_within_at_Ioc_iff_Iic [topological_space β] {a b : α} {f : α → β} (h : a < b) : continuous_within_at f (Ioc a b) b ↔ continuous_within_at f (Iic b) b := by simp only [continuous_within_at, nhds_within_Ioc_eq_nhds_within_Iic h] end linear_order section linear_order variables [topological_space α] [linear_order α] [order_closed_topology α] {f g : β → α} section variables [topological_space β] lemma frontier_le_subset_eq (hf : continuous f) (hg : continuous g) : frontier {b | f b ≤ g b} ⊆ {b | f b = g b} := begin rw [frontier_eq_closure_inter_closure, closure_le_eq hf hg], rintros b ⟨hb₁, hb₂⟩, refine le_antisymm hb₁ (closure_lt_subset_le hg hf _), convert hb₂ using 2, simp only [not_le.symm], refl end lemma frontier_Iic_subset (a : α) : frontier (Iic a) ⊆ {a} := frontier_le_subset_eq (@continuous_id α _) continuous_const lemma frontier_Ici_subset (a : α) : frontier (Ici a) ⊆ {a} := @frontier_Iic_subset (order_dual α) _ _ _ _ lemma frontier_lt_subset_eq (hf : continuous f) (hg : continuous g) : frontier {b | f b < g b} ⊆ {b | f b = g b} := by rw ← frontier_compl; convert frontier_le_subset_eq hg hf; simp [ext_iff, eq_comm] lemma continuous_if_le [topological_space γ] [Π x, decidable (f x ≤ g x)] {f' g' : β → γ} (hf : continuous f) (hg : continuous g) (hf' : continuous_on f' {x | f x ≤ g x}) (hg' : continuous_on g' {x | g x ≤ f x}) (hfg : ∀ x, f x = g x → f' x = g' x) : continuous (λ x, if f x ≤ g x then f' x else g' x) := begin refine continuous_if (λ a ha, hfg _ (frontier_le_subset_eq hf hg ha)) _ (hg'.mono _), { rwa [(is_closed_le hf hg).closure_eq] }, { simp only [not_le], exact closure_lt_subset_le hg hf } end lemma continuous.if_le [topological_space γ] [Π x, decidable (f x ≤ g x)] {f' g' : β → γ} (hf' : continuous f') (hg' : continuous g') (hf : continuous f) (hg : continuous g) (hfg : ∀ x, f x = g x → f' x = g' x) : continuous (λ x, if f x ≤ g x then f' x else g' x) := continuous_if_le hf hg hf'.continuous_on hg'.continuous_on hfg @[continuity] lemma continuous.min (hf : continuous f) (hg : continuous g) : continuous (λb, min (f b) (g b)) := hf.if_le hg hf hg (λ x, id) @[continuity] lemma continuous.max (hf : continuous f) (hg : continuous g) : continuous (λb, max (f b) (g b)) := @continuous.min (order_dual α) _ _ _ _ _ _ _ hf hg end lemma continuous_min : continuous (λ p : α × α, min p.1 p.2) := continuous_fst.min continuous_snd lemma continuous_max : continuous (λ p : α × α, max p.1 p.2) := continuous_fst.max continuous_snd lemma filter.tendsto.max {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) : tendsto (λb, max (f b) (g b)) b (𝓝 (max a₁ a₂)) := (continuous_max.tendsto (a₁, a₂)).comp (hf.prod_mk_nhds hg) lemma filter.tendsto.min {b : filter β} {a₁ a₂ : α} (hf : tendsto f b (𝓝 a₁)) (hg : tendsto g b (𝓝 a₂)) : tendsto (λb, min (f b) (g b)) b (𝓝 (min a₁ a₂)) := (continuous_min.tendsto (a₁, a₂)).comp (hf.prod_mk_nhds hg) end linear_order end order_closed_topology /-- The order topology on an ordered type is the topology generated by open intervals. We register it on a preorder, but it is mostly interesting in linear orders, where it is also order-closed. We define it as a mixin. If you want to introduce the order topology on a preorder, use `preorder.topology`. -/ class order_topology (α : Type*) [t : topological_space α] [preorder α] : Prop := (topology_eq_generate_intervals : t = generate_from {s | ∃a, s = Ioi a ∨ s = Iio a}) /-- (Order) topology on a partial order `α` generated by the subbase of open intervals `(a, ∞) = { x ∣ a < x }, (-∞ , b) = {x ∣ x < b}` for all `a, b` in `α`. We do not register it as an instance as many ordered sets are already endowed with the same topology, most often in a non-defeq way though. Register as a local instance when necessary. -/ def preorder.topology (α : Type*) [preorder α] : topological_space α := generate_from {s : set α | ∃ (a : α), s = {b : α | a < b} ∨ s = {b : α | b < a}} section order_topology instance {α : Type*} [topological_space α] [partial_order α] [order_topology α] : order_topology (order_dual α) := ⟨by convert @order_topology.topology_eq_generate_intervals α _ _ _; conv in (_ ∨ _) { rw or.comm }; refl⟩ section partial_order variables [topological_space α] [partial_order α] [t : order_topology α] include t lemma is_open_iff_generate_intervals {s : set α} : is_open s ↔ generate_open {s | ∃a, s = Ioi a ∨ s = Iio a} s := by rw [t.topology_eq_generate_intervals]; refl lemma is_open_lt' (a : α) : is_open {b:α | a < b} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inl rfl⟩ lemma is_open_gt' (a : α) : is_open {b:α | b < a} := by rw [@is_open_iff_generate_intervals α _ _ t]; exact generate_open.basic _ ⟨a, or.inr rfl⟩ lemma lt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a < x := mem_nhds_sets (is_open_lt' _) h lemma le_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 b, a ≤ x := (𝓝 b).sets_of_superset (lt_mem_nhds h) $ assume b hb, le_of_lt hb lemma gt_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x < b := mem_nhds_sets (is_open_gt' _) h lemma ge_mem_nhds {a b : α} (h : a < b) : ∀ᶠ x in 𝓝 a, x ≤ b := (𝓝 a).sets_of_superset (gt_mem_nhds h) $ assume b hb, le_of_lt hb lemma nhds_eq_order (a : α) : 𝓝 a = (⨅b ∈ Iio a, 𝓟 (Ioi b)) ⊓ (⨅b ∈ Ioi a, 𝓟 (Iio b)) := by rw [t.topology_eq_generate_intervals, nhds_generate_from]; from le_antisymm (le_inf (le_binfi $ assume b hb, infi_le_of_le {c : α | b < c} $ infi_le _ ⟨hb, b, or.inl rfl⟩) (le_binfi $ assume b hb, infi_le_of_le {c : α | c < b} $ infi_le _ ⟨hb, b, or.inr rfl⟩)) (le_infi $ assume s, le_infi $ assume ⟨ha, b, hs⟩, match s, ha, hs with | _, h, (or.inl rfl) := inf_le_left_of_le $ infi_le_of_le b $ infi_le _ h | _, h, (or.inr rfl) := inf_le_right_of_le $ infi_le_of_le b $ infi_le _ h end) lemma tendsto_order {f : β → α} {a : α} {x : filter β} : tendsto f x (𝓝 a) ↔ (∀ a' < a, ∀ᶠ b in x, a' < f b) ∧ (∀ a' > a, ∀ᶠ b in x, f b < a') := by simp [nhds_eq_order a, tendsto_inf, tendsto_infi, tendsto_principal] instance tendsto_Icc_class_nhds (a : α) : tendsto_Ixx_class Icc (𝓝 a) (𝓝 a) := begin simp only [nhds_eq_order, infi_subtype'], refine ((has_basis_infi_principal_finite _).inf (has_basis_infi_principal_finite _)).tendsto_Ixx_class (λ s hs, _), refine (ord_connected_bInter _).inter (ord_connected_bInter _); intros _ _, exacts [ord_connected_Ioi, ord_connected_Iio] end instance tendsto_Ico_class_nhds (a : α) : tendsto_Ixx_class Ico (𝓝 a) (𝓝 a) := tendsto_Ixx_class_of_subset (λ _ _, Ico_subset_Icc_self) instance tendsto_Ioc_class_nhds (a : α) : tendsto_Ixx_class Ioc (𝓝 a) (𝓝 a) := tendsto_Ixx_class_of_subset (λ _ _, Ioc_subset_Icc_self) instance tendsto_Ioo_class_nhds (a : α) : tendsto_Ixx_class Ioo (𝓝 a) (𝓝 a) := tendsto_Ixx_class_of_subset (λ _ _, Ioo_subset_Icc_self) /-- Also known as squeeze or sandwich theorem. This version assumes that inequalities hold eventually for the filter. -/ lemma tendsto_of_tendsto_of_tendsto_of_le_of_le' {f g h : β → α} {b : filter β} {a : α} (hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a)) (hgf : ∀ᶠ b in b, g b ≤ f b) (hfh : ∀ᶠ b in b, f b ≤ h b) : tendsto f b (𝓝 a) := tendsto_order.2 ⟨assume a' h', have ∀ᶠ b in b, a' < g b, from (tendsto_order.1 hg).left a' h', by filter_upwards [this, hgf] assume a, lt_of_lt_of_le, assume a' h', have ∀ᶠ b in b, h b < a', from (tendsto_order.1 hh).right a' h', by filter_upwards [this, hfh] assume a h₁ h₂, lt_of_le_of_lt h₂ h₁⟩ /-- Also known as squeeze or sandwich theorem. This version assumes that inequalities hold everywhere. -/ lemma tendsto_of_tendsto_of_tendsto_of_le_of_le {f g h : β → α} {b : filter β} {a : α} (hg : tendsto g b (𝓝 a)) (hh : tendsto h b (𝓝 a)) (hgf : g ≤ f) (hfh : f ≤ h) : tendsto f b (𝓝 a) := tendsto_of_tendsto_of_tendsto_of_le_of_le' hg hh (eventually_of_forall hgf) (eventually_of_forall hfh) lemma nhds_order_unbounded {a : α} (hu : ∃u, a < u) (hl : ∃l, l < a) : 𝓝 a = (⨅l (h₂ : l < a) u (h₂ : a < u), 𝓟 (Ioo l u)) := have ∃ u, u ∈ Ioi a, from hu, have ∃ l, l ∈ Iio a, from hl, by { simp only [nhds_eq_order, inf_binfi, binfi_inf, *, inf_principal, Ioi_inter_Iio], refl } lemma tendsto_order_unbounded {f : β → α} {a : α} {x : filter β} (hu : ∃u, a < u) (hl : ∃l, l < a) (h : ∀l u, l < a → a < u → ∀ᶠ b in x, l < f b ∧ f b < u) : tendsto f x (𝓝 a) := by rw [nhds_order_unbounded hu hl]; from (tendsto_infi.2 $ assume l, tendsto_infi.2 $ assume hl, tendsto_infi.2 $ assume u, tendsto_infi.2 $ assume hu, tendsto_principal.2 $ h l u hl hu) end partial_order instance tendsto_Ixx_nhds_within {α : Type*} [preorder α] [topological_space α] (a : α) {s t : set α} {Ixx} [tendsto_Ixx_class Ixx (𝓝 a) (𝓝 a)] [tendsto_Ixx_class Ixx (𝓟 s) (𝓟 t)]: tendsto_Ixx_class Ixx (𝓝[s] a) (𝓝[t] a) := filter.tendsto_Ixx_class_inf instance tendsto_Icc_class_nhds_pi {ι : Type*} {α : ι → Type*} [nonempty ι] [Π i, partial_order (α i)] [Π i, topological_space (α i)] [∀ i, order_topology (α i)] (f : Π i, α i) : tendsto_Ixx_class Icc (𝓝 f) (𝓝 f) := begin constructor, conv in ((𝓝 f).lift' powerset) { rw [nhds_pi] }, simp only [lift'_infi_powerset, comap_lift'_eq2 monotone_powerset, tendsto_infi, tendsto_lift', mem_powerset_iff, subset_def, mem_preimage], intros i s hs, have : tendsto (λ g : Π i, α i, g i) (𝓝 f) (𝓝 (f i)) := ((continuous_apply i).tendsto f), refine (tendsto_lift'.1 ((this.comp tendsto_fst).Icc (this.comp tendsto_snd)) s hs).mono _, exact λ p hp g hg, hp ⟨hg.1 _, hg.2 _⟩ end theorem induced_order_topology' {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [order_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H₁ : ∀ {a x}, x < f a → ∃ b < a, x ≤ f b) (H₂ : ∀ {a x}, f a < x → ∃ b > a, f b ≤ x) : @order_topology _ (induced f ta) _ := begin letI := induced f ta, refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩, rw [nhds_induced, nhds_generate_from, nhds_eq_order (f a)], apply le_antisymm, { refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _), rcases hs with ⟨ab, b, rfl|rfl⟩, { exact mem_comap_sets.2 ⟨{x | f b < x}, mem_inf_sets_of_left $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ }, { exact mem_comap_sets.2 ⟨{x | x < f b}, mem_inf_sets_of_right $ mem_infi_sets _ $ mem_infi_sets (hf.2 ab) $ mem_principal_self _, λ x, hf.1⟩ } }, { rw [← map_le_iff_le_comap], refine le_inf _ _; refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _); simp, { rcases H₁ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inl rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_le_of_lt xb (hf.2 hc) }, { rcases H₂ h with ⟨b, ab, xb⟩, refine mem_infi_sets _ (mem_infi_sets ⟨ab, b, or.inr rfl⟩ (mem_principal_sets.2 _)), exact λ c hc, lt_of_lt_of_le (hf.2 hc) xb } }, end theorem induced_order_topology {α : Type u} {β : Type v} [partial_order α] [ta : topological_space β] [partial_order β] [order_topology β] (f : α → β) (hf : ∀ {x y}, f x < f y ↔ x < y) (H : ∀ {x y}, x < y → ∃ a, x < f a ∧ f a < y) : @order_topology _ (induced f ta) _ := induced_order_topology' f @hf (λ a x xa, let ⟨b, xb, ba⟩ := H xa in ⟨b, hf.1 ba, le_of_lt xb⟩) (λ a x ax, let ⟨b, ab, bx⟩ := H ax in ⟨b, hf.1 ab, le_of_lt bx⟩) /-- On an `ord_connected` subset of a linear order, the order topology for the restriction of the order is the same as the restriction to the subset of the order topology. -/ instance order_topology_of_ord_connected {α : Type u} [ta : topological_space α] [linear_order α] [order_topology α] {t : set α} [ht : ord_connected t] : order_topology t := begin letI := induced (coe : t → α) ta, refine ⟨eq_of_nhds_eq_nhds (λ a, _)⟩, rw [nhds_induced, nhds_generate_from, nhds_eq_order (a : α)], apply le_antisymm, { refine le_infi (λ s, le_infi $ λ hs, le_principal_iff.2 _), rcases hs with ⟨ab, b, rfl|rfl⟩, { refine ⟨Ioi b, _, λ _, id⟩, refine mem_inf_sets_of_left (mem_infi_sets b _), exact mem_infi_sets ab (mem_principal_self (Ioi ↑b)) }, { refine ⟨Iio b, _, λ _, id⟩, refine mem_inf_sets_of_right (mem_infi_sets b _), exact mem_infi_sets ab (mem_principal_self (Iio b)) } }, { rw [← map_le_iff_le_comap], refine le_inf _ _, { refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _), by_cases hx : x ∈ t, { refine mem_infi_sets (Ioi ⟨x, hx⟩) (mem_infi_sets ⟨h, ⟨⟨x, hx⟩, or.inl rfl⟩⟩ _), exact λ _, id }, simp only [set_coe.exists, mem_set_of_eq, mem_map], convert univ_sets _, suffices hx' : ∀ (y : t), ↑y ∈ Ioi x, { simp [hx'] }, intros y, revert hx, contrapose!, -- here we use the `ord_connected` hypothesis exact λ hx, ht y.2 a.2 ⟨le_of_not_gt hx, le_of_lt h⟩ }, { refine le_infi (λ x, le_infi $ λ h, le_principal_iff.2 _), by_cases hx : x ∈ t, { refine mem_infi_sets (Iio ⟨x, hx⟩) (mem_infi_sets ⟨h, ⟨⟨x, hx⟩, or.inr rfl⟩⟩ _), exact λ _, id }, simp only [set_coe.exists, mem_set_of_eq, mem_map], convert univ_sets _, suffices hx' : ∀ (y : t), ↑y ∈ Iio x, { simp [hx'] }, intros y, revert hx, contrapose!, -- here we use the `ord_connected` hypothesis exact λ hx, ht a.2 y.2 ⟨le_of_lt h, le_of_not_gt hx⟩ } } end lemma nhds_top_order [topological_space α] [order_top α] [order_topology α] : 𝓝 (⊤:α) = (⨅l (h₂ : l < ⊤), 𝓟 (Ioi l)) := by simp [nhds_eq_order (⊤:α)] lemma nhds_bot_order [topological_space α] [order_bot α] [order_topology α] : 𝓝 (⊥:α) = (⨅l (h₂ : ⊥ < l), 𝓟 (Iio l)) := by simp [nhds_eq_order (⊥:α)] lemma tendsto_nhds_top_mono [topological_space β] [order_top β] [order_topology β] {l : filter α} {f g : α → β} (hf : tendsto f l (𝓝 ⊤)) (hg : f ≤ᶠ[l] g) : tendsto g l (𝓝 ⊤) := begin simp only [nhds_top_order, tendsto_infi, tendsto_principal] at hf ⊢, intros x hx, filter_upwards [hf x hx, hg], exact λ x, lt_of_lt_of_le end lemma tendsto_nhds_bot_mono [topological_space β] [order_bot β] [order_topology β] {l : filter α} {f g : α → β} (hf : tendsto f l (𝓝 ⊥)) (hg : g ≤ᶠ[l] f) : tendsto g l (𝓝 ⊥) := @tendsto_nhds_top_mono α (order_dual β) _ _ _ _ _ _ hf hg lemma tendsto_nhds_top_mono' [topological_space β] [order_top β] [order_topology β] {l : filter α} {f g : α → β} (hf : tendsto f l (𝓝 ⊤)) (hg : f ≤ g) : tendsto g l (𝓝 ⊤) := tendsto_nhds_top_mono hf (eventually_of_forall hg) lemma tendsto_nhds_bot_mono' [topological_space β] [order_bot β] [order_topology β] {l : filter α} {f g : α → β} (hf : tendsto f l (𝓝 ⊥)) (hg : g ≤ f) : tendsto g l (𝓝 ⊥) := tendsto_nhds_bot_mono hf (eventually_of_forall hg) section linear_order variables [topological_space α] [linear_order α] [order_topology α] lemma exists_Ioc_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {l : α} (hl : l < a) : ∃ l' ∈ Ico l a, Ioc l' a ⊆ s := begin rw [nhds_eq_order a] at hs, rcases hs with ⟨t₁, ht₁, t₂, ht₂, hts⟩, -- First we show that `t₂` includes `(-∞, a]`, so it suffices to show `(l', ∞) ⊆ t₁` suffices : ∃ l' ∈ Ico l a, Ioi l' ⊆ t₁, { have A : 𝓟 (Iic a) ≤ ⨅ b ∈ Ioi a, 𝓟 (Iio b), from (le_infi $ λ b, le_infi $ λ hb, principal_mono.2 $ Iic_subset_Iio.2 hb), have B : t₁ ∩ Iic a ⊆ s, from subset.trans (inter_subset_inter_right _ (A ht₂)) hts, from this.imp (λ l', Exists.imp $ λ hl' hl x hx, B ⟨hl hx.1, hx.2⟩) }, clear hts ht₂ t₂, -- Now we find `l` such that `(l', ∞) ⊆ t₁` rw [mem_binfi] at ht₁, { rcases ht₁ with ⟨b, hb, hb'⟩, exact ⟨max b l, ⟨le_max_right _ _, max_lt hb hl⟩, λ x hx, hb' $ Ioi_subset_Ioi (le_max_left _ _) hx⟩ }, { intros b hb b' hb', simp only [mem_Iio] at hb hb', use [max b b', max_lt hb hb'], simp [le_refl] }, exact ⟨l, hl⟩ end lemma exists_Ico_subset_of_mem_nhds' {a : α} {s : set α} (hs : s ∈ 𝓝 a) {u : α} (hu : a < u) : ∃ u' ∈ Ioc a u, Ico a u' ⊆ s := begin convert @exists_Ioc_subset_of_mem_nhds' (order_dual α) _ _ _ _ _ hs _ hu, ext, rw [dual_Ico, dual_Ioc] end lemma exists_Ioc_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ l, l < a) : ∃ l < a, Ioc l a ⊆ s := let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ioc_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.2, hl.snd⟩ lemma exists_Ico_subset_of_mem_nhds {a : α} {s : set α} (hs : s ∈ 𝓝 a) (h : ∃ u, a < u) : ∃ u (_ : a < u), Ico a u ⊆ s := let ⟨l', hl'⟩ := h in let ⟨l, hl⟩ := exists_Ico_subset_of_mem_nhds' hs hl' in ⟨l, hl.fst.1, hl.snd⟩ lemma order_separated {a₁ a₂ : α} (h : a₁ < a₂) : ∃u v : set α, is_open u ∧ is_open v ∧ a₁ ∈ u ∧ a₂ ∈ v ∧ (∀b₁∈u, ∀b₂∈v, b₁ < b₂) := match dense_or_discrete a₁ a₂ with | or.inl ⟨a, ha₁, ha₂⟩ := ⟨{a' | a' < a}, {a' | a < a'}, is_open_gt' a, is_open_lt' a, ha₁, ha₂, assume b₁ h₁ b₂ h₂, lt_trans h₁ h₂⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a | a < a₂}, {a | a₁ < a}, is_open_gt' a₂, is_open_lt' a₁, h, h, assume b₁ hb₁ b₂ hb₂, calc b₁ ≤ a₁ : h₂ _ hb₁ ... < a₂ : h ... ≤ b₂ : h₁ _ hb₂⟩ end @[priority 100] -- see Note [lower instance priority] instance order_topology.to_order_closed_topology : order_closed_topology α := { is_closed_le' := is_open_prod_iff.mpr $ assume a₁ a₂ (h : ¬ a₁ ≤ a₂), have h : a₂ < a₁, from lt_of_not_ge h, let ⟨u, v, hu, hv, ha₁, ha₂, h⟩ := order_separated h in ⟨v, u, hv, hu, ha₂, ha₁, assume ⟨b₁, b₂⟩ ⟨h₁, h₂⟩, not_le_of_gt $ h b₂ h₂ b₁ h₁⟩ } lemma order_topology.t2_space : t2_space α := by apply_instance @[priority 100] -- see Note [lower instance priority] instance order_topology.regular_space : regular_space α := { regular := assume s a hs ha, have hs' : sᶜ ∈ 𝓝 a, from mem_nhds_sets hs ha, have ∃t:set α, is_open t ∧ (∀l∈ s, l < a → l ∈ t) ∧ 𝓝[t] a = ⊥, from by_cases (assume h : ∃l, l < a, let ⟨l, hl, h⟩ := exists_Ioc_subset_of_mem_nhds hs' h in match dense_or_discrete l a with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | a < b}, is_open_gt' _, assume c hcs hca, show c < b, from lt_of_not_ge $ assume hbc, h ⟨lt_of_lt_of_le hb₁ hbc, le_of_lt hca⟩ hcs, inf_principal_eq_bot.2 $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hb₂) $ assume x (hx : b < x), show ¬ x < b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' < a}, is_open_gt' _, assume b hbs hba, hba, inf_principal_eq_bot.2 $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_lt' _) hl) $ assume x (hx : l < x), show ¬ x < a, from not_lt.2 $ h₁ _ hx⟩ end) (assume : ¬ ∃l, l < a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, nhds_within_empty _⟩), let ⟨t₁, ht₁o, ht₁s, ht₁a⟩ := this in have ∃t:set α, is_open t ∧ (∀u∈ s, u>a → u ∈ t) ∧ 𝓝[t] a = ⊥, from by_cases (assume h : ∃u, u > a, let ⟨u, hu, h⟩ := exists_Ico_subset_of_mem_nhds hs' h in match dense_or_discrete a u with | or.inl ⟨b, hb₁, hb₂⟩ := ⟨{a | b < a}, is_open_lt' _, assume c hcs hca, show c > b, from lt_of_not_ge $ assume hbc, h ⟨le_of_lt hca, lt_of_le_of_lt hbc hb₂⟩ hcs, inf_principal_eq_bot.2 $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hb₁) $ assume x (hx : b > x), show ¬ x > b, from not_lt.2 $ le_of_lt hx⟩ | or.inr ⟨h₁, h₂⟩ := ⟨{a' | a' > a}, is_open_lt' _, assume b hbs hba, hba, inf_principal_eq_bot.2 $ (𝓝 a).sets_of_superset (mem_nhds_sets (is_open_gt' _) hu) $ assume x (hx : u > x), show ¬ x > a, from not_lt.2 $ h₂ _ hx⟩ end) (assume : ¬ ∃u, u > a, ⟨∅, is_open_empty, assume l _ hl, (this ⟨l, hl⟩).elim, nhds_within_empty _⟩), let ⟨t₂, ht₂o, ht₂s, ht₂a⟩ := this in ⟨t₁ ∪ t₂, is_open_union ht₁o ht₂o, assume x hx, have x ≠ a, from assume eq, ha $ eq ▸ hx, (ne_iff_lt_or_gt.mp this).imp (ht₁s _ hx) (ht₂s _ hx), by rw [nhds_within_union, ht₁a, ht₂a, bot_sup_eq]⟩, ..order_topology.t2_space } /-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`, provided `a` is neither a bottom element nor a top element. -/ lemma mem_nhds_iff_exists_Ioo_subset' {a : α} {s : set α} (hl : ∃ l, l < a) (hu : ∃ u, a < u) : s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s := begin split, { assume h, rcases exists_Ico_subset_of_mem_nhds h hu with ⟨u, au, hu⟩, rcases exists_Ioc_subset_of_mem_nhds h hl with ⟨l, la, hl⟩, refine ⟨l, u, ⟨la, au⟩, λx hx, _⟩, cases le_total a x with hax hax, { exact hu ⟨hax, hx.2⟩ }, { exact hl ⟨hx.1, hax⟩ } }, { rintros ⟨l, u, ha, h⟩, apply mem_sets_of_superset (mem_nhds_sets is_open_Ioo ha) h } end /-- A set is a neighborhood of `a` if and only if it contains an interval `(l, u)` containing `a`. -/ lemma mem_nhds_iff_exists_Ioo_subset [no_top_order α] [no_bot_order α] {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃l u, a ∈ Ioo l u ∧ Ioo l u ⊆ s := mem_nhds_iff_exists_Ioo_subset' (no_bot a) (no_top a) lemma nhds_basis_Ioo' {a : α} (hl : ∃l, l < a) (hu : ∃u, a < u) : (𝓝 a).has_basis (λ b : α × α, b.1 < a ∧ a < b.2) (λ b, Ioo b.1 b.2) := ⟨λ s, (mem_nhds_iff_exists_Ioo_subset' hl hu).trans $ by simp⟩ lemma nhds_basis_Ioo [no_top_order α] [no_bot_order α] {a : α} : (𝓝 a).has_basis (λ b : α × α, b.1 < a ∧ a < b.2) (λ b, Ioo b.1 b.2) := nhds_basis_Ioo' (no_bot a) (no_top a) lemma filter.eventually.exists_Ioo_subset [no_top_order α] [no_bot_order α] {a : α} {p : α → Prop} (hp : ∀ᶠ x in 𝓝 a, p x) : ∃ l u, a ∈ Ioo l u ∧ Ioo l u ⊆ {x | p x} := mem_nhds_iff_exists_Ioo_subset.1 hp lemma Iio_mem_nhds {a b : α} (h : a < b) : Iio b ∈ 𝓝 a := mem_nhds_sets is_open_Iio h lemma Ioi_mem_nhds {a b : α} (h : a < b) : Ioi a ∈ 𝓝 b := mem_nhds_sets is_open_Ioi h lemma Iic_mem_nhds {a b : α} (h : a < b) : Iic b ∈ 𝓝 a := mem_sets_of_superset (Iio_mem_nhds h) Iio_subset_Iic_self lemma Ici_mem_nhds {a b : α} (h : a < b) : Ici a ∈ 𝓝 b := mem_sets_of_superset (Ioi_mem_nhds h) Ioi_subset_Ici_self lemma Ioo_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Ioo a b ∈ 𝓝 x := mem_nhds_sets is_open_Ioo ⟨ha, hb⟩ lemma Ioc_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Ioc a b ∈ 𝓝 x := mem_sets_of_superset (Ioo_mem_nhds ha hb) Ioo_subset_Ioc_self lemma Ico_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Ico a b ∈ 𝓝 x := mem_sets_of_superset (Ioo_mem_nhds ha hb) Ioo_subset_Ico_self lemma Icc_mem_nhds {a b x : α} (ha : a < x) (hb : x < b) : Icc a b ∈ 𝓝 x := mem_sets_of_superset (Ioo_mem_nhds ha hb) Ioo_subset_Icc_self section pi /-! ### Intervals in `Π i, π i` belong to `𝓝 x` For each leamma `pi_Ixx_mem_nhds` we add a non-dependent version `pi_Ixx_mem_nhds'` because sometimes Lean fails to unify different instances while trying to apply the dependent version to, e.g., `ι → ℝ`. -/ variables {ι : Type*} {π : ι → Type*} [fintype ι] [Π i, linear_order (π i)] [Π i, topological_space (π i)] [∀ i, order_topology (π i)] {a b x : Π i, π i} {a' b' x' : ι → α} lemma pi_Iic_mem_nhds (ha : ∀ i, x i < a i) : Iic a ∈ 𝓝 x := pi_univ_Iic a ▸ set_pi_mem_nhds (finite.of_fintype _) (λ i _, Iic_mem_nhds (ha _)) lemma pi_Iic_mem_nhds' (ha : ∀ i, x' i < a' i) : Iic a' ∈ 𝓝 x' := pi_Iic_mem_nhds ha lemma pi_Ici_mem_nhds (ha : ∀ i, a i < x i) : Ici a ∈ 𝓝 x := pi_univ_Ici a ▸ set_pi_mem_nhds (finite.of_fintype _) (λ i _, Ici_mem_nhds (ha _)) lemma pi_Ici_mem_nhds' (ha : ∀ i, a' i < x' i) : Ici a' ∈ 𝓝 x' := pi_Ici_mem_nhds ha lemma pi_Icc_mem_nhds (ha : ∀ i, a i < x i) (hb : ∀ i, x i < b i) : Icc a b ∈ 𝓝 x := pi_univ_Icc a b ▸ set_pi_mem_nhds (finite.of_fintype _) (λ i _, Icc_mem_nhds (ha _) (hb _)) lemma pi_Icc_mem_nhds' (ha : ∀ i, a' i < x' i) (hb : ∀ i, x' i < b' i) : Icc a' b' ∈ 𝓝 x' := pi_Icc_mem_nhds ha hb variables [nonempty ι] lemma pi_Iio_mem_nhds (ha : ∀ i, x i < a i) : Iio a ∈ 𝓝 x := begin refine mem_sets_of_superset (set_pi_mem_nhds (finite.of_fintype _) (λ i _, _)) (pi_univ_Iio_subset a), exact Iio_mem_nhds (ha i) end lemma pi_Iio_mem_nhds' (ha : ∀ i, x' i < a' i) : Iio a' ∈ 𝓝 x' := pi_Iio_mem_nhds ha lemma pi_Ioi_mem_nhds (ha : ∀ i, a i < x i) : Ioi a ∈ 𝓝 x := @pi_Iio_mem_nhds ι (λ i, order_dual (π i)) _ _ _ _ _ _ _ ha lemma pi_Ioi_mem_nhds' (ha : ∀ i, a' i < x' i) : Ioi a' ∈ 𝓝 x' := pi_Ioi_mem_nhds ha lemma pi_Ioc_mem_nhds (ha : ∀ i, a i < x i) (hb : ∀ i, x i < b i) : Ioc a b ∈ 𝓝 x := begin refine mem_sets_of_superset (set_pi_mem_nhds (finite.of_fintype _) (λ i _, _)) (pi_univ_Ioc_subset a b), exact Ioc_mem_nhds (ha i) (hb i) end lemma pi_Ioc_mem_nhds' (ha : ∀ i, a' i < x' i) (hb : ∀ i, x' i < b' i) : Ioc a' b' ∈ 𝓝 x' := pi_Ioc_mem_nhds ha hb lemma pi_Ico_mem_nhds (ha : ∀ i, a i < x i) (hb : ∀ i, x i < b i) : Ico a b ∈ 𝓝 x := begin refine mem_sets_of_superset (set_pi_mem_nhds (finite.of_fintype _) (λ i _, _)) (pi_univ_Ico_subset a b), exact Ico_mem_nhds (ha i) (hb i) end lemma pi_Ico_mem_nhds' (ha : ∀ i, a' i < x' i) (hb : ∀ i, x' i < b' i) : Ico a' b' ∈ 𝓝 x' := pi_Ico_mem_nhds ha hb lemma pi_Ioo_mem_nhds (ha : ∀ i, a i < x i) (hb : ∀ i, x i < b i) : Ioo a b ∈ 𝓝 x := begin refine mem_sets_of_superset (set_pi_mem_nhds (finite.of_fintype _) (λ i _, _)) (pi_univ_Ioo_subset a b), exact Ioo_mem_nhds (ha i) (hb i) end lemma pi_Ioo_mem_nhds' (ha : ∀ i, a' i < x' i) (hb : ∀ i, x' i < b' i) : Ioo a' b' ∈ 𝓝 x' := pi_Ioo_mem_nhds ha hb end pi lemma disjoint_nhds_at_top [no_top_order α] (x : α) : disjoint (𝓝 x) at_top := begin rw filter.disjoint_iff, cases no_top x with a ha, use [Iio a, Iio_mem_nhds ha, Ici a, mem_at_top a], rw [inter_comm, Ici_inter_Iio, Ico_self] end @[simp] lemma inf_nhds_at_top [no_top_order α] (x : α) : 𝓝 x ⊓ at_top = ⊥ := disjoint_iff.1 (disjoint_nhds_at_top x) lemma disjoint_nhds_at_bot [no_bot_order α] (x : α) : disjoint (𝓝 x) at_bot := @disjoint_nhds_at_top (order_dual α) _ _ _ _ x @[simp] lemma inf_nhds_at_bot [no_bot_order α] (x : α) : 𝓝 x ⊓ at_bot = ⊥ := @inf_nhds_at_top (order_dual α) _ _ _ _ x lemma not_tendsto_nhds_of_tendsto_at_top [no_top_order α] {F : filter β} [ne_bot F] {f : β → α} (hf : tendsto f F at_top) (x : α) : ¬ tendsto f F (𝓝 x) := hf.not_tendsto (disjoint_nhds_at_top x).symm lemma not_tendsto_at_top_of_tendsto_nhds [no_top_order α] {F : filter β} [ne_bot F] {f : β → α} {x : α} (hf : tendsto f F (𝓝 x)) : ¬ tendsto f F at_top := hf.not_tendsto (disjoint_nhds_at_top x) lemma not_tendsto_nhds_of_tendsto_at_bot [no_bot_order α] {F : filter β} [ne_bot F] {f : β → α} (hf : tendsto f F at_bot) (x : α) : ¬ tendsto f F (𝓝 x) := hf.not_tendsto (disjoint_nhds_at_bot x).symm lemma not_tendsto_at_bot_of_tendsto_nhds [no_bot_order α] {F : filter β} [ne_bot F] {f : β → α} {x : α} (hf : tendsto f F (𝓝 x)) : ¬ tendsto f F at_bot := hf.not_tendsto (disjoint_nhds_at_bot x) /-! ### Neighborhoods to the left and to the right on an `order_topology` We've seen some properties of left and right neighborhood of a point in an `order_closed_topology`. In an `order_topology`, such neighborhoods can be characterized as the sets containing suitable intervals to the right or to the left of `a`. We give now these characterizations. -/ -- NB: If you extend the list, append to the end please to avoid breaking the API /-- The following statements are equivalent: 0. `s` is a neighborhood of `a` within `(a, +∞)` 1. `s` is a neighborhood of `a` within `(a, b]` 2. `s` is a neighborhood of `a` within `(a, b)` 3. `s` includes `(a, u)` for some `u ∈ (a, b]` 4. `s` includes `(a, u)` for some `u > a` -/ lemma tfae_mem_nhds_within_Ioi {a b : α} (hab : a < b) (s : set α) : tfae [s ∈ 𝓝[Ioi a] a, -- 0 : `s` is a neighborhood of `a` within `(a, +∞)` s ∈ 𝓝[Ioc a b] a, -- 1 : `s` is a neighborhood of `a` within `(a, b]` s ∈ 𝓝[Ioo a b] a, -- 2 : `s` is a neighborhood of `a` within `(a, b)` ∃ u ∈ Ioc a b, Ioo a u ⊆ s, -- 3 : `s` includes `(a, u)` for some `u ∈ (a, b]` ∃ u ∈ Ioi a, Ioo a u ⊆ s] := -- 4 : `s` includes `(a, u)` for some `u > a` begin tfae_have : 1 ↔ 2, by rw [nhds_within_Ioc_eq_nhds_within_Ioi hab], tfae_have : 1 ↔ 3, by rw [nhds_within_Ioo_eq_nhds_within_Ioi hab], tfae_have : 4 → 5, from λ ⟨u, umem, hu⟩, ⟨u, umem.1, hu⟩, tfae_have : 5 → 1, { rintros ⟨u, hau, hu⟩, exact mem_sets_of_superset (Ioo_mem_nhds_within_Ioi ⟨le_refl a, hau⟩) hu }, tfae_have : 1 → 4, { assume h, rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩, rcases exists_Ico_subset_of_mem_nhds' va hab with ⟨u, au, hu⟩, refine ⟨u, au, λx hx, _⟩, refine hv ⟨hu ⟨le_of_lt hx.1, hx.2⟩, _⟩, exact hx.1 }, tfae_finish end lemma mem_nhds_within_Ioi_iff_exists_mem_Ioc_Ioo_subset {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioc a u', Ioo a u ⊆ s := (tfae_mem_nhds_within_Ioi hu' s).out 0 3 /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)` with `a < u < u'`, provided `a` is not a top element. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset' {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s := (tfae_mem_nhds_within_Ioi hu' s).out 0 4 /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u)` with `a < u`. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioo_subset [no_top_order α] {a : α} {s : set α} : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioo a u ⊆ s := let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ioi_iff_exists_Ioo_subset' hu' /-- A set is a neighborhood of `a` within `(a, +∞)` if and only if it contains an interval `(a, u]` with `a < u`. -/ lemma mem_nhds_within_Ioi_iff_exists_Ioc_subset [no_top_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Ioi a] a ↔ ∃u ∈ Ioi a, Ioc a u ⊆ s := begin rw mem_nhds_within_Ioi_iff_exists_Ioo_subset, split, { rintros ⟨u, au, as⟩, rcases exists_between au with ⟨v, hv⟩, exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ }, { rintros ⟨u, au, as⟩, exact ⟨u, au, subset.trans Ioo_subset_Ioc_self as⟩ } end /-- The following statements are equivalent: 0. `s` is a neighborhood of `b` within `(-∞, b)` 1. `s` is a neighborhood of `b` within `[a, b)` 2. `s` is a neighborhood of `b` within `(a, b)` 3. `s` includes `(l, b)` for some `l ∈ [a, b)` 4. `s` includes `(l, b)` for some `l < b` -/ lemma tfae_mem_nhds_within_Iio {a b : α} (h : a < b) (s : set α) : tfae [s ∈ 𝓝[Iio b] b, -- 0 : `s` is a neighborhood of `b` within `(-∞, b)` s ∈ 𝓝[Ico a b] b, -- 1 : `s` is a neighborhood of `b` within `[a, b)` s ∈ 𝓝[Ioo a b] b, -- 2 : `s` is a neighborhood of `b` within `(a, b)` ∃ l ∈ Ico a b, Ioo l b ⊆ s, -- 3 : `s` includes `(l, b)` for some `l ∈ [a, b)` ∃ l ∈ Iio b, Ioo l b ⊆ s] := -- 4 : `s` includes `(l, b)` for some `l < b` begin have := @tfae_mem_nhds_within_Ioi (order_dual α) _ _ _ _ _ h s, -- If we call `convert` here, it generates wrong equations, so we need to simplify first simp only [exists_prop] at this ⊢, rw [dual_Ioi, dual_Ioc, dual_Ioo] at this, convert this; ext l; rw [dual_Ioo] end lemma mem_nhds_within_Iio_iff_exists_mem_Ico_Ioo_subset {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Ico l' a, Ioo l a ⊆ s := (tfae_mem_nhds_within_Iio hl' s).out 0 3 /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)` with `l < a`, provided `a` is not a bottom element. -/ lemma mem_nhds_within_Iio_iff_exists_Ioo_subset' {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ioo l a ⊆ s := (tfae_mem_nhds_within_Iio hl' s).out 0 4 /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `(l, a)` with `l < a`. -/ lemma mem_nhds_within_Iio_iff_exists_Ioo_subset [no_bot_order α] {a : α} {s : set α} : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ioo l a ⊆ s := let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iio_iff_exists_Ioo_subset' hl' /-- A set is a neighborhood of `a` within `(-∞, a)` if and only if it contains an interval `[l, a)` with `l < a`. -/ lemma mem_nhds_within_Iio_iff_exists_Ico_subset [no_bot_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Iio a] a ↔ ∃l ∈ Iio a, Ico l a ⊆ s := begin convert @mem_nhds_within_Ioi_iff_exists_Ioc_subset (order_dual α) _ _ _ _ _ _ _, simp only [dual_Ioc], refl end /-- The following statements are equivalent: 0. `s` is a neighborhood of `a` within `[a, +∞)` 1. `s` is a neighborhood of `a` within `[a, b]` 2. `s` is a neighborhood of `a` within `[a, b)` 3. `s` includes `[a, u)` for some `u ∈ (a, b]` 4. `s` includes `[a, u)` for some `u > a` -/ lemma tfae_mem_nhds_within_Ici {a b : α} (hab : a < b) (s : set α) : tfae [s ∈ 𝓝[Ici a] a, -- 0 : `s` is a neighborhood of `a` within `[a, +∞)` s ∈ 𝓝[Icc a b] a, -- 1 : `s` is a neighborhood of `a` within `[a, b]` s ∈ 𝓝[Ico a b] a, -- 2 : `s` is a neighborhood of `a` within `[a, b)` ∃ u ∈ Ioc a b, Ico a u ⊆ s, -- 3 : `s` includes `[a, u)` for some `u ∈ (a, b]` ∃ u ∈ Ioi a, Ico a u ⊆ s] := -- 4 : `s` includes `[a, u)` for some `u > a` begin tfae_have : 1 ↔ 2, by rw [nhds_within_Icc_eq_nhds_within_Ici hab], tfae_have : 1 ↔ 3, by rw [nhds_within_Ico_eq_nhds_within_Ici hab], tfae_have : 4 → 5, from λ ⟨u, umem, hu⟩, ⟨u, umem.1, hu⟩, tfae_have : 5 → 1, { rintros ⟨u, hau, hu⟩, exact mem_sets_of_superset (Ico_mem_nhds_within_Ici ⟨le_refl a, hau⟩) hu }, tfae_have : 1 → 4, { assume h, rcases mem_nhds_within_iff_exists_mem_nhds_inter.1 h with ⟨v, va, hv⟩, rcases exists_Ico_subset_of_mem_nhds' va hab with ⟨u, au, hu⟩, refine ⟨u, au, λx hx, _⟩, refine hv ⟨hu ⟨hx.1, hx.2⟩, _⟩, exact hx.1 }, tfae_finish end lemma mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioc a u', Ico a u ⊆ s := (tfae_mem_nhds_within_Ici hu' s).out 0 3 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)` with `a < u < u'`, provided `a` is not a top element. -/ lemma mem_nhds_within_Ici_iff_exists_Ico_subset' {a u' : α} {s : set α} (hu' : a < u') : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Ico a u ⊆ s := (tfae_mem_nhds_within_Ici hu' s).out 0 4 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u)` with `a < u`. -/ lemma mem_nhds_within_Ici_iff_exists_Ico_subset [no_top_order α] {a : α} {s : set α} : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Ico a u ⊆ s := let ⟨u', hu'⟩ := no_top a in mem_nhds_within_Ici_iff_exists_Ico_subset' hu' /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u]` with `a < u`. -/ lemma mem_nhds_within_Ici_iff_exists_Icc_subset' [no_top_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Ici a] a ↔ ∃u ∈ Ioi a, Icc a u ⊆ s := begin rw mem_nhds_within_Ici_iff_exists_Ico_subset, split, { rintros ⟨u, au, as⟩, rcases exists_between au with ⟨v, hv⟩, exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ }, { rintros ⟨u, au, as⟩, exact ⟨u, au, subset.trans Ico_subset_Icc_self as⟩ } end /-- The following statements are equivalent: 0. `s` is a neighborhood of `b` within `(-∞, b]` 1. `s` is a neighborhood of `b` within `[a, b]` 2. `s` is a neighborhood of `b` within `(a, b]` 3. `s` includes `(l, b]` for some `l ∈ [a, b)` 4. `s` includes `(l, b]` for some `l < b` -/ lemma tfae_mem_nhds_within_Iic {a b : α} (h : a < b) (s : set α) : tfae [s ∈ 𝓝[Iic b] b, -- 0 : `s` is a neighborhood of `b` within `(-∞, b]` s ∈ 𝓝[Icc a b] b, -- 1 : `s` is a neighborhood of `b` within `[a, b]` s ∈ 𝓝[Ioc a b] b, -- 2 : `s` is a neighborhood of `b` within `(a, b]` ∃ l ∈ Ico a b, Ioc l b ⊆ s, -- 3 : `s` includes `(l, b]` for some `l ∈ [a, b)` ∃ l ∈ Iio b, Ioc l b ⊆ s] := -- 4 : `s` includes `(l, b]` for some `l < b` begin have := @tfae_mem_nhds_within_Ici (order_dual α) _ _ _ _ _ h s, -- If we call `convert` here, it generates wrong equations, so we need to simplify first simp only [exists_prop] at this ⊢, rw [dual_Icc, dual_Ioc, dual_Ioi] at this, convert this; ext l; rw [dual_Ico] end lemma mem_nhds_within_Iic_iff_exists_mem_Ico_Ioc_subset {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Ico l' a, Ioc l a ⊆ s := (tfae_mem_nhds_within_Iic hl' s).out 0 3 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]` with `l < a`, provided `a` is not a bottom element. -/ lemma mem_nhds_within_Iic_iff_exists_Ioc_subset' {a l' : α} {s : set α} (hl' : l' < a) : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Ioc l a ⊆ s := (tfae_mem_nhds_within_Iic hl' s).out 0 4 (by norm_num) (by norm_num) /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `(l, a]` with `l < a`. -/ lemma mem_nhds_within_Iic_iff_exists_Ioc_subset [no_bot_order α] {a : α} {s : set α} : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Ioc l a ⊆ s := let ⟨l', hl'⟩ := no_bot a in mem_nhds_within_Iic_iff_exists_Ioc_subset' hl' /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `[l, a]` with `l < a`. -/ lemma mem_nhds_within_Iic_iff_exists_Icc_subset' [no_bot_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Iic a] a ↔ ∃l ∈ Iio a, Icc l a ⊆ s := begin convert @mem_nhds_within_Ici_iff_exists_Icc_subset' (order_dual α) _ _ _ _ _ _ _, simp_rw (show ∀ u : order_dual α, @Icc (order_dual α) _ a u = @Icc α _ u a, from λ u, dual_Icc), refl, end /-- A set is a neighborhood of `a` within `[a, +∞)` if and only if it contains an interval `[a, u]` with `a < u`. -/ lemma mem_nhds_within_Ici_iff_exists_Icc_subset [no_top_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Ici a] a ↔ ∃u, a < u ∧ Icc a u ⊆ s := begin rw mem_nhds_within_Ici_iff_exists_Ico_subset, split, { rintros ⟨u, au, as⟩, rcases exists_between au with ⟨v, hv⟩, exact ⟨v, hv.1, λx hx, as ⟨hx.1, lt_of_le_of_lt hx.2 hv.2⟩⟩ }, { rintros ⟨u, au, as⟩, exact ⟨u, au, subset.trans Ico_subset_Icc_self as⟩ } end /-- A set is a neighborhood of `a` within `(-∞, a]` if and only if it contains an interval `[l, a]` with `l < a`. -/ lemma mem_nhds_within_Iic_iff_exists_Icc_subset [no_bot_order α] [densely_ordered α] {a : α} {s : set α} : s ∈ 𝓝[Iic a] a ↔ ∃l, l < a ∧ Icc l a ⊆ s := begin rw mem_nhds_within_Iic_iff_exists_Ioc_subset, split, { rintros ⟨l, la, as⟩, rcases exists_between la with ⟨v, hv⟩, refine ⟨v, hv.2, λx hx, as ⟨lt_of_lt_of_le hv.1 hx.1, hx.2⟩⟩, }, { rintros ⟨l, la, as⟩, exact ⟨l, la, subset.trans Ioc_subset_Icc_self as⟩ } end end linear_order section linear_ordered_add_comm_group variables [topological_space α] [linear_ordered_add_comm_group α] [order_topology α] variables {l : filter β} {f g : β → α} local notation `|` x `|` := abs x lemma nhds_eq_infi_abs_sub (a : α) : 𝓝 a = (⨅r>0, 𝓟 {b | |a - b| < r}) := begin simp only [le_antisymm_iff, nhds_eq_order, le_inf_iff, le_infi_iff, le_principal_iff, mem_Ioi, mem_Iio, abs_sub_lt_iff, @sub_lt_iff_lt_add _ _ _ _ a, @sub_lt _ _ a, set_of_and], refine ⟨_, _, _⟩, { intros ε ε0, exact inter_mem_inf_sets (mem_infi_sets (a - ε) $ mem_infi_sets (sub_lt_self a ε0) (mem_principal_self _)) (mem_infi_sets (ε + a) $ mem_infi_sets (by simpa) (mem_principal_self _)) }, { intros b hb, exact mem_infi_sets (a - b) (mem_infi_sets (sub_pos.2 hb) (by simp [Ioi])) }, { intros b hb, exact mem_infi_sets (b - a) (mem_infi_sets (sub_pos.2 hb) (by simp [Iio])) } end lemma order_topology_of_nhds_abs {α : Type*} [topological_space α] [linear_ordered_add_comm_group α] (h_nhds : ∀a:α, 𝓝 a = (⨅r>0, 𝓟 {b | |a - b| < r})) : order_topology α := begin refine ⟨eq_of_nhds_eq_nhds $ λ a, _⟩, rw [h_nhds], letI := preorder.topology α, letI : order_topology α := ⟨rfl⟩, exact (nhds_eq_infi_abs_sub a).symm end lemma linear_ordered_add_comm_group.tendsto_nhds {x : filter β} {a : α} : tendsto f x (𝓝 a) ↔ ∀ ε > (0 : α), ∀ᶠ b in x, |f b - a| < ε := by simp [nhds_eq_infi_abs_sub, abs_sub a] lemma eventually_abs_sub_lt (a : α) {ε : α} (hε : 0 < ε) : ∀ᶠ x in 𝓝 a, |x - a| < ε := (nhds_eq_infi_abs_sub a).symm ▸ mem_infi_sets ε (mem_infi_sets hε $ by simp only [abs_sub, mem_principal_self]) @[priority 100] -- see Note [lower instance priority] instance linear_ordered_add_comm_group.topological_add_group : topological_add_group α := { continuous_add := begin refine continuous_iff_continuous_at.2 _, rintro ⟨a, b⟩, refine linear_ordered_add_comm_group.tendsto_nhds.2 (λ ε ε0, _), rcases dense_or_discrete 0 ε with (⟨δ, δ0, δε⟩|⟨h₁, h₂⟩), { -- If there exists `δ ∈ (0, ε)`, then we choose `δ`-nhd of `a` and `(ε-δ)`-nhd of `b` filter_upwards [prod_mem_nhds_sets (eventually_abs_sub_lt a δ0) (eventually_abs_sub_lt b (sub_pos.2 δε))], rintros ⟨x, y⟩ ⟨hx : |x - a| < δ, hy : |y - b| < ε - δ⟩, rw [add_sub_comm], calc |x - a + (y - b)| ≤ |x - a| + |y - b| : abs_add _ _ ... < δ + (ε - δ) : add_lt_add hx hy ... = ε : add_sub_cancel'_right _ _ }, { -- Otherewise `ε`-nhd of each point `a` is `{a}` have hε : ∀ {x y}, abs (x - y) < ε → x = y, { intros x y h, simpa [sub_eq_zero] using h₂ _ h }, filter_upwards [prod_mem_nhds_sets (eventually_abs_sub_lt a ε0) (eventually_abs_sub_lt b ε0)], rintros ⟨x, y⟩ ⟨hx : |x - a| < ε, hy : |y - b| < ε⟩, simpa [hε hx, hε hy] } end, continuous_neg := continuous_iff_continuous_at.2 $ λ a, linear_ordered_add_comm_group.tendsto_nhds.2 $ λ ε ε0, (eventually_abs_sub_lt a ε0).mono $ λ x hx, by rwa [neg_sub_neg, abs_sub] } @[continuity] lemma continuous_abs : continuous (abs : α → α) := continuous_id.max continuous_neg lemma filter.tendsto.abs {f : β → α} {a : α} {l : filter β} (h : tendsto f l (𝓝 a)) : tendsto (λ x, |f x|) l (𝓝 (|a|)) := (continuous_abs.tendsto _).comp h section variables [topological_space β] {b : β} {a : α} {s : set β} lemma continuous.abs (h : continuous f) : continuous (λ x, |f x|) := continuous_abs.comp h lemma continuous_at.abs (h : continuous_at f b) : continuous_at (λ x, |f x|) b := h.abs lemma continuous_within_at.abs (h : continuous_within_at f s b) : continuous_within_at (λ x, |f x|) s b := h.abs lemma continuous_on.abs (h : continuous_on f s) : continuous_on (λ x, |f x|) s := λ x hx, (h x hx).abs lemma tendsto_abs_nhds_within_zero : tendsto (abs : α → α) (𝓝[{0}ᶜ] 0) (𝓝[Ioi 0] 0) := (continuous_abs.tendsto' (0 : α) 0 abs_zero).inf $ tendsto_principal_principal.2 $ λ x, abs_pos.2 end /-- In a linearly ordered additive commutative group with the order topology, if `f` tends to `C` and `g` tends to `at_top` then `f + g` tends to `at_top`. -/ lemma filter.tendsto.add_at_top {C : α} (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := begin nontriviality α, obtain ⟨C', hC'⟩ : ∃ C', C' < C := no_bot C, refine tendsto_at_top_add_left_of_le' _ C' _ hg, exact (hf.eventually (lt_mem_nhds hC')).mono (λ x, le_of_lt) end /-- In a linearly ordered additive commutative group with the order topology, if `f` tends to `C` and `g` tends to `at_bot` then `f + g` tends to `at_bot`. -/ lemma filter.tendsto.add_at_bot {C : α} (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @filter.tendsto.add_at_top (order_dual α) _ _ _ _ _ _ _ _ hf hg /-- In a linearly ordered additive commutative group with the order topology, if `f` tends to `at_top` and `g` tends to `C` then `f + g` tends to `at_top`. -/ lemma filter.tendsto.at_top_add {C : α} (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, f x + g x) l at_top := by { conv in (_ + _) { rw add_comm }, exact hg.add_at_top hf } /-- In a linearly ordered additive commutative group with the order topology, if `f` tends to `at_bot` and `g` tends to `C` then `f + g` tends to `at_bot`. -/ lemma filter.tendsto.at_bot_add {C : α} (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, f x + g x) l at_bot := by { conv in (_ + _) { rw add_comm }, exact hg.add_at_bot hf } end linear_ordered_add_comm_group section linear_ordered_field variables [linear_ordered_field α] [topological_space α] [order_topology α] variables {l : filter β} {f g : β → α} /-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to a positive constant `C` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.at_top_mul {C : α} (hC : 0 < C) (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_top := begin refine tendsto_at_top_mono' _ _ (hf.at_top_mul_const (half_pos hC)), filter_upwards [hg.eventually (lt_mem_nhds (half_lt_self hC)), hf.eventually (eventually_ge_at_top 0)], exact λ x hg hf, mul_le_mul_of_nonneg_left hg.le hf end /-- In a linearly ordered field with the order topology, if `f` tends to a positive constant `C` and `g` tends to `at_top` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.mul_at_top {C : α} (hC : 0 < C) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) : tendsto (λ x, (f x * g x)) l at_top := by simpa only [mul_comm] using hg.at_top_mul hC hf /-- In a linearly ordered field with the order topology, if `f` tends to `at_top` and `g` tends to a negative constant `C` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.at_top_mul_neg {C : α} (hC : C < 0) (hf : tendsto f l at_top) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_bot := by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp (hf.at_top_mul (neg_pos.2 hC) hg.neg) /-- In a linearly ordered field with the order topology, if `f` tends to a negative constant `C` and `g` tends to `at_top` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.neg_mul_at_top {C : α} (hC : C < 0) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_top) : tendsto (λ x, (f x * g x)) l at_bot := by simpa only [mul_comm] using hg.at_top_mul_neg hC hf /-- In a linearly ordered field with the order topology, if `f` tends to `at_bot` and `g` tends to a positive constant `C` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.at_bot_mul {C : α} (hC : 0 < C) (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_bot := by simpa [(∘)] using tendsto_neg_at_top_at_bot.comp ((tendsto_neg_at_bot_at_top.comp hf).at_top_mul hC hg) /-- In a linearly ordered field with the order topology, if `f` tends to `at_bot` and `g` tends to a negative constant `C` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.at_bot_mul_neg {C : α} (hC : C < 0) (hf : tendsto f l at_bot) (hg : tendsto g l (𝓝 C)) : tendsto (λ x, (f x * g x)) l at_top := by simpa [(∘)] using tendsto_neg_at_bot_at_top.comp ((tendsto_neg_at_bot_at_top.comp hf).at_top_mul_neg hC hg) /-- In a linearly ordered field with the order topology, if `f` tends to a positive constant `C` and `g` tends to `at_bot` then `f * g` tends to `at_bot`. -/ lemma filter.tendsto.mul_at_bot {C : α} (hC : 0 < C) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) : tendsto (λ x, (f x * g x)) l at_bot := by simpa only [mul_comm] using hg.at_bot_mul hC hf /-- In a linearly ordered field with the order topology, if `f` tends to a negative constant `C` and `g` tends to `at_bot` then `f * g` tends to `at_top`. -/ lemma filter.tendsto.neg_mul_at_bot {C : α} (hC : C < 0) (hf : tendsto f l (𝓝 C)) (hg : tendsto g l at_bot) : tendsto (λ x, (f x * g x)) l at_top := by simpa only [mul_comm] using hg.at_bot_mul_neg hC hf /-- The function `x ↦ x⁻¹` tends to `+∞` on the right of `0`. -/ lemma tendsto_inv_zero_at_top : tendsto (λx:α, x⁻¹) (𝓝[set.Ioi (0:α)] 0) at_top := begin refine (at_top_basis' 1).tendsto_right_iff.2 (λ b hb, _), have hb' : 0 < b := zero_lt_one.trans_le hb, filter_upwards [Ioc_mem_nhds_within_Ioi ⟨le_rfl, inv_pos.2 hb'⟩], exact λ x hx, (le_inv hx.1 hb').1 hx.2 end /-- The function `r ↦ r⁻¹` tends to `0` on the right as `r → +∞`. -/ lemma tendsto_inv_at_top_zero' : tendsto (λr:α, r⁻¹) at_top (𝓝[set.Ioi (0:α)] 0) := begin refine (has_basis.tendsto_iff at_top_basis ⟨λ s, mem_nhds_within_Ioi_iff_exists_Ioc_subset⟩).2 _, refine λ b hb, ⟨b⁻¹, trivial, λ x hx, _⟩, have : 0 < x := lt_of_lt_of_le (inv_pos.2 hb) hx, exact ⟨inv_pos.2 this, (inv_le this hb).2 hx⟩ end lemma tendsto_inv_at_top_zero : tendsto (λr:α, r⁻¹) at_top (𝓝 0) := tendsto_inv_at_top_zero'.mono_right inf_le_left lemma filter.tendsto.div_at_top [has_continuous_mul α] {f g : β → α} {l : filter β} {a : α} (h : tendsto f l (𝓝 a)) (hg : tendsto g l at_top) : tendsto (λ x, f x / g x) l (𝓝 0) := by { simp only [div_eq_mul_inv], exact mul_zero a ▸ h.mul (tendsto_inv_at_top_zero.comp hg) } lemma filter.tendsto.inv_tendsto_at_top (h : tendsto f l at_top) : tendsto (f⁻¹) l (𝓝 0) := tendsto_inv_at_top_zero.comp h lemma filter.tendsto.inv_tendsto_zero (h : tendsto f l (𝓝[set.Ioi 0] 0)) : tendsto (f⁻¹) l at_top := tendsto_inv_zero_at_top.comp h /-- The function `x^(-n)` tends to `0` at `+∞` for any positive natural `n`. A version for positive real powers exists as `tendsto_rpow_neg_at_top`. -/ lemma tendsto_pow_neg_at_top {n : ℕ} (hn : 1 ≤ n) : tendsto (λ x : α, x ^ (-(n:ℤ))) at_top (𝓝 0) := tendsto.congr (λ x, (fpow_neg x n).symm) (filter.tendsto.inv_tendsto_at_top (tendsto_pow_at_top hn)) lemma tendsto_fpow_at_top_zero {n : ℤ} (hn : n < 0) : tendsto (λ x : α, x^n) at_top (𝓝 0) := begin have : 1 ≤ -n, by linarith, apply tendsto.congr (show ∀ x : α, x^-(-n) = x^n, by simp), lift -n to ℕ using le_of_lt (neg_pos.mpr hn) with N, exact tendsto_pow_neg_at_top (by exact_mod_cast this) end end linear_ordered_field lemma preimage_neg [add_group α] : preimage (has_neg.neg : α → α) = image (has_neg.neg : α → α) := (image_eq_preimage_of_inverse neg_neg neg_neg).symm lemma filter.map_neg [add_group α] : map (has_neg.neg : α → α) = comap (has_neg.neg : α → α) := funext $ assume f, map_eq_comap_of_inverse (funext neg_neg) (funext neg_neg) section order_topology variables [topological_space α] [topological_space β] [linear_order α] [linear_order β] [order_topology α] [order_topology β] lemma is_lub.frequently_mem {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) : ∃ᶠ x in 𝓝[Iic a] a, x ∈ s := begin rcases hs with ⟨a', ha'⟩, intro h, rcases (ha.1 ha').eq_or_lt with (rfl|ha'a), { exact h.self_of_nhds_within le_rfl ha' }, { rcases (mem_nhds_within_Iic_iff_exists_Ioc_subset' ha'a).1 h with ⟨b, hba, hb⟩, rcases ha.exists_between hba with ⟨b', hb's, hb'⟩, exact hb hb' hb's }, end lemma is_lub.frequently_nhds_mem {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) : ∃ᶠ x in 𝓝 a, x ∈ s := (ha.frequently_mem hs).filter_mono inf_le_left lemma is_glb.frequently_mem {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) : ∃ᶠ x in 𝓝[Ici a] a, x ∈ s := @is_lub.frequently_mem (order_dual α) _ _ _ _ _ ha hs lemma is_glb.frequently_nhds_mem {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) : ∃ᶠ x in 𝓝 a, x ∈ s := (ha.frequently_mem hs).filter_mono inf_le_left lemma is_lub.mem_closure {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) : a ∈ closure s := (ha.frequently_nhds_mem hs).mem_closure lemma is_glb.mem_closure {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) : a ∈ closure s := (ha.frequently_nhds_mem hs).mem_closure lemma is_lub.nhds_within_ne_bot {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) : ne_bot (𝓝[s] a) := mem_closure_iff_nhds_within_ne_bot.1 (ha.mem_closure hs) lemma is_glb.nhds_within_ne_bot : ∀ {a : α} {s : set α}, is_glb s a → s.nonempty → ne_bot (𝓝[s] a) := @is_lub.nhds_within_ne_bot (order_dual α) _ _ _ lemma is_lub_of_mem_nhds {s : set α} {a : α} {f : filter α} (hsa : a ∈ upper_bounds s) (hsf : s ∈ f) [ne_bot (f ⊓ 𝓝 a)] : is_lub s a := ⟨hsa, assume b hb, not_lt.1 $ assume hba, have s ∩ {a | b < a} ∈ f ⊓ 𝓝 a, from inter_mem_inf_sets hsf (mem_nhds_sets (is_open_lt' _) hba), let ⟨x, ⟨hxs, hxb⟩⟩ := nonempty_of_mem_sets this in have b < b, from lt_of_lt_of_le hxb $ hb hxs, lt_irrefl b this⟩ lemma is_glb_of_mem_nhds : ∀ {s : set α} {a : α} {f : filter α}, a ∈ lower_bounds s → s ∈ f → ne_bot (f ⊓ 𝓝 a) → is_glb s a := @is_lub_of_mem_nhds (order_dual α) _ _ _ lemma is_lub.mem_upper_bounds_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_lub s a) (hb : tendsto f (𝓝[s] a) (𝓝 b)) : b ∈ upper_bounds (f '' s) := begin rintro _ ⟨x, hx, rfl⟩, replace ha := ha.inter_Ici_of_mem hx, haveI := ha.nhds_within_ne_bot ⟨x, hx, le_rfl⟩, refine ge_of_tendsto (hb.mono_left (nhds_within_mono _ (inter_subset_left s (Ici x)))) _, exact mem_sets_of_superset self_mem_nhds_within (λ y hy, hf _ hx _ hy.1 hy.2) end lemma is_lub.is_lub_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_lub s a) (hs : s.nonempty) (hb : tendsto f (𝓝[s] a) (𝓝 b)) : is_lub (f '' s) b := begin haveI := ha.nhds_within_ne_bot hs, exact ⟨ha.mem_upper_bounds_of_tendsto hf hb, λ b' hb', le_of_tendsto hb (mem_sets_of_superset self_mem_nhds_within $ λ x hx, hb' $ mem_image_of_mem _ hx)⟩ end lemma is_glb.mem_lower_bounds_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) (ha : is_glb s a) (hb : tendsto f (𝓝[s] a) (𝓝 b)) : b ∈ lower_bounds (f '' s) := @is_lub.mem_upper_bounds_of_tendsto (order_dual α) (order_dual γ) _ _ _ _ _ _ _ _ _ _ (λ x hx y hy, hf y hy x hx) ha hb lemma is_glb.is_glb_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ} (hf : ∀x∈s, ∀y∈s, x ≤ y → f x ≤ f y) : is_glb s a → s.nonempty → tendsto f (𝓝[s] a) (𝓝 b) → is_glb (f '' s) b := @is_lub.is_lub_of_tendsto (order_dual α) (order_dual γ) _ _ _ _ _ _ f s a b (λ x hx y hy, hf y hy x hx) lemma is_lub.mem_lower_bounds_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ} (hf : ∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) (ha : is_lub s a) (hb : tendsto f (𝓝[s] a) (𝓝 b)) : b ∈ lower_bounds (f '' s) := @is_lub.mem_upper_bounds_of_tendsto α (order_dual γ) _ _ _ _ _ _ _ _ _ _ hf ha hb lemma is_lub.is_glb_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] : ∀ {f : α → γ} {s : set α} {a : α} {b : γ}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_lub s a → s.nonempty → tendsto f (𝓝[s] a) (𝓝 b) → is_glb (f '' s) b := @is_lub.is_lub_of_tendsto α (order_dual γ) _ _ _ _ _ _ lemma is_glb.mem_upper_bounds_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] {f : α → γ} {s : set α} {a : α} {b : γ} (hf : ∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) (ha : is_glb s a) (hb : tendsto f (𝓝[s] a) (𝓝 b)) : b ∈ upper_bounds (f '' s) := @is_glb.mem_lower_bounds_of_tendsto α (order_dual γ) _ _ _ _ _ _ _ _ _ _ hf ha hb lemma is_glb.is_lub_of_tendsto [preorder γ] [topological_space γ] [order_closed_topology γ] : ∀ {f : α → γ} {s : set α} {a : α} {b : γ}, (∀x∈s, ∀y∈s, x ≤ y → f y ≤ f x) → is_glb s a → s.nonempty → tendsto f (𝓝[s] a) (𝓝 b) → is_lub (f '' s) b := @is_glb.is_glb_of_tendsto α (order_dual γ) _ _ _ _ _ _ lemma is_lub.mem_of_is_closed {a : α} {s : set α} (ha : is_lub s a) (hs : s.nonempty) (sc : is_closed s) : a ∈ s := sc.closure_subset $ ha.mem_closure hs alias is_lub.mem_of_is_closed ← is_closed.is_lub_mem lemma is_glb.mem_of_is_closed {a : α} {s : set α} (ha : is_glb s a) (hs : s.nonempty) (sc : is_closed s) : a ∈ s := sc.closure_subset $ ha.mem_closure hs alias is_glb.mem_of_is_closed ← is_closed.is_glb_mem /-- A compact set is bounded below -/ lemma is_compact.bdd_below {α : Type u} [topological_space α] [linear_order α] [order_closed_topology α] [nonempty α] {s : set α} (hs : is_compact s) : bdd_below s := begin by_contra H, rcases hs.elim_finite_subcover_image (λ x (_ : x ∈ s), @is_open_Ioi _ _ _ _ x) _ with ⟨t, st, ft, ht⟩, { refine H (ft.bdd_below.imp $ λ C hC y hy, _), rcases mem_bUnion_iff.1 (ht hy) with ⟨x, hx, xy⟩, exact le_trans (hC hx) (le_of_lt xy) }, { refine λ x hx, mem_bUnion_iff.2 (not_imp_comm.1 _ H), exact λ h, ⟨x, λ y hy, le_of_not_lt (h.imp $ λ ys, ⟨_, hy, ys⟩)⟩ } end /-- A compact set is bounded above -/ lemma is_compact.bdd_above {α : Type u} [topological_space α] [linear_order α] [order_topology α] : Π [nonempty α] {s : set α}, is_compact s → bdd_above s := @is_compact.bdd_below (order_dual α) _ _ _ end order_topology section linear_order variables [topological_space α] [linear_order α] [order_topology α] [densely_ordered α] /-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`, unless `a` is a top element. -/ lemma closure_Ioi' {a b : α} (hab : a < b) : closure (Ioi a) = Ici a := begin apply subset.antisymm, { exact closure_minimal Ioi_subset_Ici_self is_closed_Ici }, { rw [← diff_subset_closure_iff, Ici_diff_Ioi_same, singleton_subset_iff], exact is_glb_Ioi.mem_closure ⟨_, hab⟩ } end /-- The closure of the interval `(a, +∞)` is the closed interval `[a, +∞)`. -/ @[simp] lemma closure_Ioi (a : α) [no_top_order α] : closure (Ioi a) = Ici a := let ⟨b, hb⟩ := no_top a in closure_Ioi' hb /-- The closure of the interval `(-∞, a)` is the closed interval `(-∞, a]`, unless `a` is a bottom element. -/ lemma closure_Iio' {a b : α} (hab : b < a) : closure (Iio a) = Iic a := @closure_Ioi' (order_dual α) _ _ _ _ _ _ hab /-- The closure of the interval `(-∞, a)` is the interval `(-∞, a]`. -/ @[simp] lemma closure_Iio (a : α) [no_bot_order α] : closure (Iio a) = Iic a := let ⟨b, hb⟩ := no_bot a in closure_Iio' hb /-- The closure of the open interval `(a, b)` is the closed interval `[a, b]`. -/ @[simp] lemma closure_Ioo {a b : α} (hab : a < b) : closure (Ioo a b) = Icc a b := begin apply subset.antisymm, { exact closure_minimal Ioo_subset_Icc_self is_closed_Icc }, { rw [← diff_subset_closure_iff, Icc_diff_Ioo_same hab.le], have hab' : (Ioo a b).nonempty, from nonempty_Ioo.2 hab, simp only [insert_subset, singleton_subset_iff], exact ⟨(is_glb_Ioo hab).mem_closure hab', (is_lub_Ioo hab).mem_closure hab'⟩ } end /-- The closure of the interval `(a, b]` is the closed interval `[a, b]`. -/ @[simp] lemma closure_Ioc {a b : α} (hab : a < b) : closure (Ioc a b) = Icc a b := begin apply subset.antisymm, { exact closure_minimal Ioc_subset_Icc_self is_closed_Icc }, { apply subset.trans _ (closure_mono Ioo_subset_Ioc_self), rw closure_Ioo hab } end /-- The closure of the interval `[a, b)` is the closed interval `[a, b]`. -/ @[simp] lemma closure_Ico {a b : α} (hab : a < b) : closure (Ico a b) = Icc a b := begin apply subset.antisymm, { exact closure_minimal Ico_subset_Icc_self is_closed_Icc }, { apply subset.trans _ (closure_mono Ioo_subset_Ico_self), rw closure_Ioo hab } end @[simp] lemma interior_Ici [no_bot_order α] {a : α} : interior (Ici a) = Ioi a := by rw [← compl_Iio, interior_compl, closure_Iio, compl_Iic] @[simp] lemma interior_Iic [no_top_order α] {a : α} : interior (Iic a) = Iio a := by rw [← compl_Ioi, interior_compl, closure_Ioi, compl_Ici] @[simp] lemma interior_Icc [no_bot_order α] [no_top_order α] {a b : α}: interior (Icc a b) = Ioo a b := by rw [← Ici_inter_Iic, interior_inter, interior_Ici, interior_Iic, Ioi_inter_Iio] @[simp] lemma interior_Ico [no_bot_order α] {a b : α} : interior (Ico a b) = Ioo a b := by rw [← Ici_inter_Iio, interior_inter, interior_Ici, interior_Iio, Ioi_inter_Iio] @[simp] lemma interior_Ioc [no_top_order α] {a b : α} : interior (Ioc a b) = Ioo a b := by rw [← Ioi_inter_Iic, interior_inter, interior_Ioi, interior_Iic, Ioi_inter_Iio] @[simp] lemma frontier_Ici [no_bot_order α] {a : α} : frontier (Ici a) = {a} := by simp [frontier] @[simp] lemma frontier_Iic [no_top_order α] {a : α} : frontier (Iic a) = {a} := by simp [frontier] @[simp] lemma frontier_Ioi [no_top_order α] {a : α} : frontier (Ioi a) = {a} := by simp [frontier] @[simp] lemma frontier_Iio [no_bot_order α] {a : α} : frontier (Iio a) = {a} := by simp [frontier] @[simp] lemma frontier_Icc [no_bot_order α] [no_top_order α] {a b : α} (h : a < b) : frontier (Icc a b) = {a, b} := by simp [frontier, le_of_lt h, Icc_diff_Ioo_same] @[simp] lemma frontier_Ioo {a b : α} (h : a < b) : frontier (Ioo a b) = {a, b} := by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same] @[simp] lemma frontier_Ico [no_bot_order α] {a b : α} (h : a < b) : frontier (Ico a b) = {a, b} := by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same] @[simp] lemma frontier_Ioc [no_top_order α] {a b : α} (h : a < b) : frontier (Ioc a b) = {a, b} := by simp [frontier, h, le_of_lt h, Icc_diff_Ioo_same] lemma nhds_within_Ioi_ne_bot' {a b c : α} (H₁ : a < c) (H₂ : a ≤ b) : ne_bot (𝓝[Ioi a] b) := mem_closure_iff_nhds_within_ne_bot.1 $ by { rw [closure_Ioi' H₁], exact H₂ } lemma nhds_within_Ioi_ne_bot [no_top_order α] {a b : α} (H : a ≤ b) : ne_bot (𝓝[Ioi a] b) := let ⟨c, hc⟩ := no_top a in nhds_within_Ioi_ne_bot' hc H lemma nhds_within_Ioi_self_ne_bot' {a b : α} (H : a < b) : ne_bot (𝓝[Ioi a] a) := nhds_within_Ioi_ne_bot' H (le_refl a) @[instance] lemma nhds_within_Ioi_self_ne_bot [no_top_order α] (a : α) : ne_bot (𝓝[Ioi a] a) := nhds_within_Ioi_ne_bot (le_refl a) lemma nhds_within_Iio_ne_bot' {a b c : α} (H₁ : a < c) (H₂ : b ≤ c) : ne_bot (𝓝[Iio c] b) := mem_closure_iff_nhds_within_ne_bot.1 $ by { rw [closure_Iio' H₁], exact H₂ } lemma nhds_within_Iio_ne_bot [no_bot_order α] {a b : α} (H : a ≤ b) : ne_bot (𝓝[Iio b] a) := let ⟨c, hc⟩ := no_bot b in nhds_within_Iio_ne_bot' hc H lemma nhds_within_Iio_self_ne_bot' {a b : α} (H : a < b) : ne_bot (𝓝[Iio b] b) := nhds_within_Iio_ne_bot' H (le_refl b) @[instance] lemma nhds_within_Iio_self_ne_bot [no_bot_order α] (a : α) : ne_bot (𝓝[Iio a] a) := nhds_within_Iio_ne_bot (le_refl a) end linear_order section linear_order variables [topological_space α] [linear_order α] [order_topology α] [densely_ordered α] {a b : α} {s : set α} lemma comap_coe_nhds_within_Iio_of_Ioo_subset (hb : s ⊆ Iio b) (hs : s.nonempty → ∃ a < b, Ioo a b ⊆ s) : comap (coe : s → α) (𝓝[Iio b] b) = at_top := begin nontriviality, haveI : nonempty s := nontrivial_iff_nonempty.1 ‹_›, rcases hs (nonempty_subtype.1 ‹_›) with ⟨a, h, hs⟩, ext u, split, { rintros ⟨t, ht, hts⟩, obtain ⟨x, ⟨hxa : a ≤ x, hxb : x < b⟩, hxt : Ioo x b ⊆ t⟩ := (mem_nhds_within_Iio_iff_exists_mem_Ico_Ioo_subset h).mp ht, obtain ⟨y, hxy, hyb⟩ := exists_between hxb, refine mem_sets_of_superset (mem_at_top ⟨y, hs ⟨hxa.trans_lt hxy, hyb⟩⟩) _, rintros ⟨z, hzs⟩ (hyz : y ≤ z), refine hts (hxt ⟨hxy.trans_le _, hb _⟩); assumption }, { intros hu, obtain ⟨x : s, hx : ∀ z, x ≤ z → z ∈ u⟩ := mem_at_top_sets.1 hu, exact ⟨Ioo x b, Ioo_mem_nhds_within_Iio (right_mem_Ioc.2 $ hb x.2), λ z hz, hx _ hz.1.le⟩ } end lemma comap_coe_nhds_within_Ioi_of_Ioo_subset (ha : s ⊆ Ioi a) (hs : s.nonempty → ∃ b > a, Ioo a b ⊆ s) : comap (coe : s → α) (𝓝[Ioi a] a) = at_bot := begin refine @comap_coe_nhds_within_Iio_of_Ioo_subset (order_dual α) _ _ _ _ _ _ ha (λ h, _), rcases hs h with ⟨b, hab, h⟩, use [b, hab], rwa dual_Ioo end lemma map_coe_at_top_of_Ioo_subset (hb : s ⊆ Iio b) (hs : ∀ a' < b, ∃ a < b, Ioo a b ⊆ s) : map (coe : s → α) at_top = 𝓝[Iio b] b := begin rcases eq_empty_or_nonempty (Iio b) with (hb'|⟨a, ha⟩), { rw [filter_eq_bot_of_not_nonempty at_top, map_bot, hb', nhds_within_empty], exact λ ⟨⟨x, hx⟩⟩, not_nonempty_iff_eq_empty.2 hb' ⟨x, hb hx⟩ }, { rw [← comap_coe_nhds_within_Iio_of_Ioo_subset hb (λ _, hs a ha), map_comap_of_mem], rw subtype.range_coe, exact (mem_nhds_within_Iio_iff_exists_Ioo_subset' ha).2 (hs a ha) }, end lemma map_coe_at_bot_of_Ioo_subset (ha : s ⊆ Ioi a) (hs : ∀ b' > a, ∃ b > a, Ioo a b ⊆ s) : map (coe : s → α) at_bot = (𝓝[Ioi a] a) := begin refine @map_coe_at_top_of_Ioo_subset (order_dual α) _ _ _ _ a s ha (λ b' hb', _), rcases hs b' hb' with ⟨b, hab, hbs⟩, use [b, hab], rwa dual_Ioo end /-- The `at_top` filter for an open interval `Ioo a b` comes from the left-neighbourhoods filter at the right endpoint in the ambient order. -/ lemma comap_coe_Ioo_nhds_within_Iio (a b : α) : comap (coe : Ioo a b → α) (𝓝[Iio b] b) = at_top := comap_coe_nhds_within_Iio_of_Ioo_subset Ioo_subset_Iio_self $ λ h, ⟨a, nonempty_Ioo.1 h, subset.refl _⟩ /-- The `at_bot` filter for an open interval `Ioo a b` comes from the right-neighbourhoods filter at the left endpoint in the ambient order. -/ lemma comap_coe_Ioo_nhds_within_Ioi (a b : α) : comap (coe : Ioo a b → α) (𝓝[Ioi a] a) = at_bot := comap_coe_nhds_within_Ioi_of_Ioo_subset Ioo_subset_Ioi_self $ λ h, ⟨b, nonempty_Ioo.1 h, subset.refl _⟩ lemma comap_coe_Ioi_nhds_within_Ioi (a : α) : comap (coe : Ioi a → α) (𝓝[Ioi a] a) = at_bot := comap_coe_nhds_within_Ioi_of_Ioo_subset (subset.refl _) $ λ ⟨x, hx⟩, ⟨x, hx, Ioo_subset_Ioi_self⟩ lemma comap_coe_Iio_nhds_within_Iio (a : α) : comap (coe : Iio a → α) (𝓝[Iio a] a) = at_top := @comap_coe_Ioi_nhds_within_Ioi (order_dual α) _ _ _ _ a @[simp] lemma map_coe_Ioo_at_top {a b : α} (h : a < b) : map (coe : Ioo a b → α) at_top = 𝓝[Iio b] b := map_coe_at_top_of_Ioo_subset Ioo_subset_Iio_self $ λ _ _, ⟨_, h, subset.refl _⟩ @[simp] lemma map_coe_Ioo_at_bot {a b : α} (h : a < b) : map (coe : Ioo a b → α) at_bot = 𝓝[Ioi a] a := map_coe_at_bot_of_Ioo_subset Ioo_subset_Ioi_self $ λ _ _, ⟨_, h, subset.refl _⟩ @[simp] lemma map_coe_Ioi_at_bot (a : α) : map (coe : Ioi a → α) at_bot = 𝓝[Ioi a] a := map_coe_at_bot_of_Ioo_subset (subset.refl _) $ λ b hb, ⟨b, hb, Ioo_subset_Ioi_self⟩ @[simp] lemma map_coe_Iio_at_top (a : α) : map (coe : Iio a → α) at_top = 𝓝[Iio a] a := @map_coe_Ioi_at_bot (order_dual α) _ _ _ _ _ variables {l : filter β} {f : α → β} @[simp] lemma tendsto_comp_coe_Ioo_at_top (h : a < b) : tendsto (λ x : Ioo a b, f x) at_top l ↔ tendsto f (𝓝[Iio b] b) l := by rw [← map_coe_Ioo_at_top h, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Ioo_at_bot (h : a < b) : tendsto (λ x : Ioo a b, f x) at_bot l ↔ tendsto f (𝓝[Ioi a] a) l := by rw [← map_coe_Ioo_at_bot h, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Ioi_at_bot : tendsto (λ x : Ioi a, f x) at_bot l ↔ tendsto f (𝓝[Ioi a] a) l := by rw [← map_coe_Ioi_at_bot, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Iio_at_top : tendsto (λ x : Iio a, f x) at_top l ↔ tendsto f (𝓝[Iio a] a) l := by rw [← map_coe_Iio_at_top, tendsto_map'_iff] @[simp] lemma tendsto_Ioo_at_top {f : β → Ioo a b} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l (𝓝[Iio b] b) := by rw [← comap_coe_Ioo_nhds_within_Iio, tendsto_comap_iff] @[simp] lemma tendsto_Ioo_at_bot {f : β → Ioo a b} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l (𝓝[Ioi a] a) := by rw [← comap_coe_Ioo_nhds_within_Ioi, tendsto_comap_iff] @[simp] lemma tendsto_Ioi_at_bot {f : β → Ioi a} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l (𝓝[Ioi a] a) := by rw [← comap_coe_Ioi_nhds_within_Ioi, tendsto_comap_iff] @[simp] lemma tendsto_Iio_at_top {f : β → Iio a} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l (𝓝[Iio a] a) := by rw [← comap_coe_Iio_nhds_within_Iio, tendsto_comap_iff] end linear_order section complete_linear_order variables [complete_linear_order α] [topological_space α] [order_topology α] [complete_linear_order β] [topological_space β] [order_topology β] [nonempty γ] lemma Sup_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) : Sup s ∈ closure s := (is_lub_Sup s).mem_closure hs lemma Inf_mem_closure {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) : Inf s ∈ closure s := (is_glb_Inf s).mem_closure hs lemma is_closed.Sup_mem {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) (hc : is_closed s) : Sup s ∈ s := (is_lub_Sup s).mem_of_is_closed hs hc lemma is_closed.Inf_mem {α : Type u} [topological_space α] [complete_linear_order α] [order_topology α] {s : set α} (hs : s.nonempty) (hc : is_closed s) : Inf s ∈ s := (is_glb_Inf s).mem_of_is_closed hs hc /-- A monotone function continuous at the supremum of a nonempty set sends this supremum to the supremum of the image of this set. -/ lemma map_Sup_of_continuous_at_of_monotone' {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Mf : monotone f) (hs : s.nonempty) : f (Sup s) = Sup (f '' s) := --This is a particular case of the more general is_lub.is_lub_of_tendsto ((is_lub_Sup _).is_lub_of_tendsto (λ x hx y hy xy, Mf xy) hs $ Cf.mono_left inf_le_left).Sup_eq.symm /-- A monotone function `s` sending `bot` to `bot` and continuous at the supremum of a set sends this supremum to the supremum of the image of this set. -/ lemma map_Sup_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Mf : monotone f) (fbot : f ⊥ = ⊥) : f (Sup s) = Sup (f '' s) := begin cases s.eq_empty_or_nonempty with h h, { simp [h, fbot] }, { exact map_Sup_of_continuous_at_of_monotone' Cf Mf h } end /-- A monotone function continuous at the indexed supremum over a nonempty `Sort` sends this indexed supremum to the indexed supremum of the composition. -/ lemma map_supr_of_continuous_at_of_monotone' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α} (Cf : continuous_at f (supr g)) (Mf : monotone f) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, map_Sup_of_continuous_at_of_monotone' Cf Mf (range_nonempty g), ← range_comp, supr] /-- If a monotone function sending `bot` to `bot` is continuous at the indexed supremum over a `Sort`, then it sends this indexed supremum to the indexed supremum of the composition. -/ lemma map_supr_of_continuous_at_of_monotone {ι : Sort*} {f : α → β} {g : ι → α} (Cf : continuous_at f (supr g)) (Mf : monotone f) (fbot : f ⊥ = ⊥) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, map_Sup_of_continuous_at_of_monotone Cf Mf fbot, ← range_comp, supr] /-- A monotone function continuous at the infimum of a nonempty set sends this infimum to the infimum of the image of this set. -/ lemma map_Inf_of_continuous_at_of_monotone' {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Mf : monotone f) (hs : s.nonempty) : f (Inf s) = Inf (f '' s) := @map_Sup_of_continuous_at_of_monotone' (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf Mf.order_dual hs /-- A monotone function `s` sending `top` to `top` and continuous at the infimum of a set sends this infimum to the infimum of the image of this set. -/ lemma map_Inf_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Mf : monotone f) (ftop : f ⊤ = ⊤) : f (Inf s) = Inf (f '' s) := @map_Sup_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf Mf.order_dual ftop /-- A monotone function continuous at the indexed infimum over a nonempty `Sort` sends this indexed infimum to the indexed infimum of the composition. -/ lemma map_infi_of_continuous_at_of_monotone' {ι : Sort*} [nonempty ι] {f : α → β} {g : ι → α} (Cf : continuous_at f (infi g)) (Mf : monotone f) : f (⨅ i, g i) = ⨅ i, f (g i) := @map_supr_of_continuous_at_of_monotone' (order_dual α) (order_dual β) _ _ _ _ _ _ ι _ f g Cf Mf.order_dual /-- If a monotone function sending `top` to `top` is continuous at the indexed infimum over a `Sort`, then it sends this indexed infimum to the indexed infimum of the composition. -/ lemma map_infi_of_continuous_at_of_monotone {ι : Sort*} {f : α → β} {g : ι → α} (Cf : continuous_at f (infi g)) (Mf : monotone f) (ftop : f ⊤ = ⊤) : f (infi g) = infi (f ∘ g) := @map_supr_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ ι f g Cf Mf.order_dual ftop end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [topological_space α] [order_topology α] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [nonempty γ] lemma cSup_mem_closure {s : set α} (hs : s.nonempty) (B : bdd_above s) : Sup s ∈ closure s := (is_lub_cSup hs B).mem_closure hs lemma cInf_mem_closure {s : set α} (hs : s.nonempty) (B : bdd_below s) : Inf s ∈ closure s := (is_glb_cInf hs B).mem_closure hs lemma is_closed.cSup_mem {s : set α} (hc : is_closed s) (hs : s.nonempty) (B : bdd_above s) : Sup s ∈ s := (is_lub_cSup hs B).mem_of_is_closed hs hc lemma is_closed.cInf_mem {s : set α} (hc : is_closed s) (hs : s.nonempty) (B : bdd_below s) : Inf s ∈ s := (is_glb_cInf hs B).mem_of_is_closed hs hc /-- If a monotone function is continuous at the supremum of a nonempty bounded above set `s`, then it sends this supremum to the supremum of the image of `s`. -/ lemma map_cSup_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Sup s)) (Mf : monotone f) (ne : s.nonempty) (H : bdd_above s) : f (Sup s) = Sup (f '' s) := begin refine ((is_lub_cSup (ne.image f) (Mf.map_bdd_above H)).unique _).symm, refine (is_lub_cSup ne H).is_lub_of_tendsto (λx hx y hy xy, Mf xy) ne _, exact Cf.mono_left inf_le_left end /-- If a monotone function is continuous at the indexed supremum of a bounded function on a nonempty `Sort`, then it sends this supremum to the supremum of the composition. -/ lemma map_csupr_of_continuous_at_of_monotone {f : α → β} {g : γ → α} (Cf : continuous_at f (⨆ i, g i)) (Mf : monotone f) (H : bdd_above (range g)) : f (⨆ i, g i) = ⨆ i, f (g i) := by rw [supr, map_cSup_of_continuous_at_of_monotone Cf Mf (range_nonempty _) H, ← range_comp, supr] /-- If a monotone function is continuous at the infimum of a nonempty bounded below set `s`, then it sends this infimum to the infimum of the image of `s`. -/ lemma map_cInf_of_continuous_at_of_monotone {f : α → β} {s : set α} (Cf : continuous_at f (Inf s)) (Mf : monotone f) (ne : s.nonempty) (H : bdd_below s) : f (Inf s) = Inf (f '' s) := @map_cSup_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ f s Cf Mf.order_dual ne H /-- A continuous monotone function sends indexed infimum to indexed infimum in conditionally complete linear order, under a boundedness assumption. -/ lemma map_cinfi_of_continuous_at_of_monotone {f : α → β} {g : γ → α} (Cf : continuous_at f (⨅ i, g i)) (Mf : monotone f) (H : bdd_below (range g)) : f (⨅ i, g i) = ⨅ i, f (g i) := @map_csupr_of_continuous_at_of_monotone (order_dual α) (order_dual β) _ _ _ _ _ _ _ _ _ _ Cf Mf.order_dual H /-- A bounded connected subset of a conditionally complete linear order includes the open interval `(Inf s, Sup s)`. -/ lemma is_connected.Ioo_cInf_cSup_subset {s : set α} (hs : is_connected s) (hb : bdd_below s) (ha : bdd_above s) : Ioo (Inf s) (Sup s) ⊆ s := λ x hx, let ⟨y, ys, hy⟩ := (is_glb_lt_iff (is_glb_cInf hs.nonempty hb)).1 hx.1 in let ⟨z, zs, hz⟩ := (lt_is_lub_iff (is_lub_cSup hs.nonempty ha)).1 hx.2 in hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩ lemma eq_Icc_cInf_cSup_of_connected_bdd_closed {s : set α} (hc : is_connected s) (hb : bdd_below s) (ha : bdd_above s) (hcl : is_closed s) : s = Icc (Inf s) (Sup s) := subset.antisymm (subset_Icc_cInf_cSup hb ha) $ hc.Icc_subset (hcl.cInf_mem hc.nonempty hb) (hcl.cSup_mem hc.nonempty ha) lemma is_preconnected.Ioi_cInf_subset {s : set α} (hs : is_preconnected s) (hb : bdd_below s) (ha : ¬bdd_above s) : Ioi (Inf s) ⊆ s := begin have sne : s.nonempty := @nonempty_of_not_bdd_above α _ s ⟨Inf ∅⟩ ha, intros x hx, obtain ⟨y, ys, hy⟩ : ∃ y ∈ s, y < x := (is_glb_lt_iff (is_glb_cInf sne hb)).1 hx, obtain ⟨z, zs, hz⟩ : ∃ z ∈ s, x < z := not_bdd_above_iff.1 ha x, exact hs.Icc_subset ys zs ⟨le_of_lt hy, le_of_lt hz⟩ end lemma is_preconnected.Iio_cSup_subset {s : set α} (hs : is_preconnected s) (hb : ¬bdd_below s) (ha : bdd_above s) : Iio (Sup s) ⊆ s := @is_preconnected.Ioi_cInf_subset (order_dual α) _ _ _ s hs ha hb /-- A preconnected set in a conditionally complete linear order is either one of the intervals `[Inf s, Sup s]`, `[Inf s, Sup s)`, `(Inf s, Sup s]`, `(Inf s, Sup s)`, `[Inf s, +∞)`, `(Inf s, +∞)`, `(-∞, Sup s]`, `(-∞, Sup s)`, `(-∞, +∞)`, or `∅`. The converse statement requires `α` to be densely ordererd. -/ lemma is_preconnected.mem_intervals {s : set α} (hs : is_preconnected s) : s ∈ ({Icc (Inf s) (Sup s), Ico (Inf s) (Sup s), Ioc (Inf s) (Sup s), Ioo (Inf s) (Sup s), Ici (Inf s), Ioi (Inf s), Iic (Sup s), Iio (Sup s), univ, ∅} : set (set α)) := begin rcases s.eq_empty_or_nonempty with rfl|hne, { apply_rules [or.inr, mem_singleton] }, have hs' : is_connected s := ⟨hne, hs⟩, by_cases hb : bdd_below s; by_cases ha : bdd_above s, { rcases mem_Icc_Ico_Ioc_Ioo_of_subset_of_subset (hs'.Ioo_cInf_cSup_subset hb ha) (subset_Icc_cInf_cSup hb ha) with hs|hs|hs|hs, { exact (or.inl hs) }, { exact (or.inr $ or.inl hs) }, { exact (or.inr $ or.inr $ or.inl hs) }, { exact (or.inr $ or.inr $ or.inr $ or.inl hs) } }, { refine (or.inr $ or.inr $ or.inr $ or.inr _), cases mem_Ici_Ioi_of_subset_of_subset (hs.Ioi_cInf_subset hb ha) (λ x hx, cInf_le hb hx) with hs hs, { exact or.inl hs }, { exact or.inr (or.inl hs) } }, { iterate 6 { apply or.inr }, cases mem_Iic_Iio_of_subset_of_subset (hs.Iio_cSup_subset hb ha) (λ x hx, le_cSup ha hx) with hs hs, { exact or.inl hs }, { exact or.inr (or.inl hs) } }, { iterate 8 { apply or.inr }, exact or.inl (hs.eq_univ_of_unbounded hb ha) } end /-- A preconnected set is either one of the intervals `Icc`, `Ico`, `Ioc`, `Ioo`, `Ici`, `Ioi`, `Iic`, `Iio`, or `univ`, or `∅`. The converse statement requires `α` to be densely ordererd. Though one can represent `∅` as `(Inf s, Inf s)`, we include it into the list of possible cases to improve readability. -/ lemma set_of_is_preconnected_subset_of_ordered : {s : set α | is_preconnected s} ⊆ -- bounded intervals (range (uncurry Icc) ∪ range (uncurry Ico) ∪ range (uncurry Ioc) ∪ range (uncurry Ioo)) ∪ -- unbounded intervals and `univ` (range Ici ∪ range Ioi ∪ range Iic ∪ range Iio ∪ {univ, ∅}) := begin intros s hs, rcases hs.mem_intervals with hs|hs|hs|hs|hs|hs|hs|hs|hs|hs, { exact (or.inl $ or.inl $ or.inl $ or.inl ⟨(Inf s, Sup s), hs.symm⟩) }, { exact (or.inl $ or.inl $ or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) }, { exact (or.inl $ or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) }, { exact (or.inl $ or.inr ⟨(Inf s, Sup s), hs.symm⟩) }, { exact (or.inr $ or.inl $ or.inl $ or.inl $ or.inl ⟨Inf s, hs.symm⟩) }, { exact (or.inr $ or.inl $ or.inl $ or.inl $ or.inr ⟨Inf s, hs.symm⟩) }, { exact (or.inr $ or.inl $ or.inl $ or.inr ⟨Sup s, hs.symm⟩) }, { exact (or.inr $ or.inl $ or.inr ⟨Sup s, hs.symm⟩) }, { exact (or.inr $ or.inr $ or.inl hs) }, { exact (or.inr $ or.inr $ or.inr hs) } end /-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]` on a closed subset, contains `a`, and the set `s ∩ [a, b)` has no maximal point, then `b ∈ s`. -/ lemma is_closed.mem_of_ge_of_forall_exists_gt {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b)) (ha : a ∈ s) (hab : a ≤ b) (hgt : ∀ x ∈ s ∩ Ico a b, (s ∩ Ioc x b).nonempty) : b ∈ s := begin let S := s ∩ Icc a b, replace ha : a ∈ S, from ⟨ha, left_mem_Icc.2 hab⟩, have Sbd : bdd_above S, from ⟨b, λ z hz, hz.2.2⟩, let c := Sup (s ∩ Icc a b), have c_mem : c ∈ S, from hs.cSup_mem ⟨_, ha⟩ Sbd, have c_le : c ≤ b, from cSup_le ⟨_, ha⟩ (λ x hx, hx.2.2), cases eq_or_lt_of_le c_le with hc hc, from hc ▸ c_mem.1, exfalso, rcases hgt c ⟨c_mem.1, c_mem.2.1, hc⟩ with ⟨x, xs, cx, xb⟩, exact not_lt_of_le (le_cSup Sbd ⟨xs, le_trans (le_cSup Sbd ha) (le_of_lt cx), xb⟩) cx end /-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]` on a closed subset, contains `a`, and for any `a ≤ x < y ≤ b`, `x ∈ s`, the set `s ∩ (x, y]` is not empty, then `[a, b] ⊆ s`. -/ lemma is_closed.Icc_subset_of_forall_exists_gt {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b)) (ha : a ∈ s) (hgt : ∀ x ∈ s ∩ Ico a b, ∀ y ∈ Ioi x, (s ∩ Ioc x y).nonempty) : Icc a b ⊆ s := begin assume y hy, have : is_closed (s ∩ Icc a y), { suffices : s ∩ Icc a y = s ∩ Icc a b ∩ Icc a y, { rw this, exact is_closed_inter hs is_closed_Icc }, rw [inter_assoc], congr, exact (inter_eq_self_of_subset_right $ Icc_subset_Icc_right hy.2).symm }, exact is_closed.mem_of_ge_of_forall_exists_gt this ha hy.1 (λ x hx, hgt x ⟨hx.1, Ico_subset_Ico_right hy.2 hx.2⟩ y hx.2.2) end section densely_ordered variables [densely_ordered α] {a b : α} /-- A "continuous induction principle" for a closed interval: if a set `s` meets `[a, b]` on a closed subset, contains `a`, and for any `x ∈ s ∩ [a, b)` the set `s` includes some open neighborhood of `x` within `(x, +∞)`, then `[a, b] ⊆ s`. -/ lemma is_closed.Icc_subset_of_forall_mem_nhds_within {a b : α} {s : set α} (hs : is_closed (s ∩ Icc a b)) (ha : a ∈ s) (hgt : ∀ x ∈ s ∩ Ico a b, s ∈ 𝓝[Ioi x] x) : Icc a b ⊆ s := begin apply hs.Icc_subset_of_forall_exists_gt ha, rintros x ⟨hxs, hxab⟩ y hyxb, have : s ∩ Ioc x y ∈ 𝓝[Ioi x] x, from inter_mem_sets (hgt x ⟨hxs, hxab⟩) (Ioc_mem_nhds_within_Ioi ⟨le_refl _, hyxb⟩), exact (nhds_within_Ioi_self_ne_bot' hxab.2).nonempty_of_mem this end /-- A closed interval in a densely ordered conditionally complete linear order is preconnected. -/ lemma is_preconnected_Icc : is_preconnected (Icc a b) := is_preconnected_closed_iff.2 begin rintros s t hs ht hab ⟨x, hx⟩ ⟨y, hy⟩, wlog hxy : x ≤ y := le_total x y using [x y s t, y x t s], have xyab : Icc x y ⊆ Icc a b := Icc_subset_Icc hx.1.1 hy.1.2, by_contradiction hst, suffices : Icc x y ⊆ s, from hst ⟨y, xyab $ right_mem_Icc.2 hxy, this $ right_mem_Icc.2 hxy, hy.2⟩, apply (is_closed_inter hs is_closed_Icc).Icc_subset_of_forall_mem_nhds_within hx.2, rintros z ⟨zs, hz⟩, have zt : z ∈ tᶜ, from λ zt, hst ⟨z, xyab $ Ico_subset_Icc_self hz, zs, zt⟩, have : tᶜ ∩ Ioc z y ∈ 𝓝[Ioi z] z, { rw [← nhds_within_Ioc_eq_nhds_within_Ioi hz.2], exact mem_nhds_within.2 ⟨tᶜ, ht, zt, subset.refl _⟩}, apply mem_sets_of_superset this, have : Ioc z y ⊆ s ∪ t, from λ w hw, hab (xyab ⟨le_trans hz.1 (le_of_lt hw.1), hw.2⟩), exact λ w ⟨wt, wzy⟩, (this wzy).elim id (λ h, (wt h).elim) end lemma is_preconnected_interval : is_preconnected (interval a b) := is_preconnected_Icc lemma is_preconnected_iff_ord_connected {s : set α} : is_preconnected s ↔ ord_connected s := ⟨λ h x hx y hy, h.Icc_subset hx hy, λ h, is_preconnected_of_forall_pair $ λ x y hx hy, ⟨interval x y, h.interval_subset hx hy, left_mem_interval, right_mem_interval, is_preconnected_interval⟩⟩ alias is_preconnected_iff_ord_connected ↔ is_preconnected.ord_connected set.ord_connected.is_preconnected lemma is_preconnected_Ici : is_preconnected (Ici a) := ord_connected_Ici.is_preconnected lemma is_preconnected_Iic : is_preconnected (Iic a) := ord_connected_Iic.is_preconnected lemma is_preconnected_Iio : is_preconnected (Iio a) := ord_connected_Iio.is_preconnected lemma is_preconnected_Ioi : is_preconnected (Ioi a) := ord_connected_Ioi.is_preconnected lemma is_preconnected_Ioo : is_preconnected (Ioo a b) := ord_connected_Ioo.is_preconnected lemma is_preconnected_Ioc : is_preconnected (Ioc a b) := ord_connected_Ioc.is_preconnected lemma is_preconnected_Ico : is_preconnected (Ico a b) := ord_connected_Ico.is_preconnected @[priority 100] instance ordered_connected_space : preconnected_space α := ⟨ord_connected_univ.is_preconnected⟩ /-- In a dense conditionally complete linear order, the set of preconnected sets is exactly the set of the intervals `Icc`, `Ico`, `Ioc`, `Ioo`, `Ici`, `Ioi`, `Iic`, `Iio`, `(-∞, +∞)`, or `∅`. Though one can represent `∅` as `(Inf s, Inf s)`, we include it into the list of possible cases to improve readability. -/ lemma set_of_is_preconnected_eq_of_ordered : {s : set α | is_preconnected s} = -- bounded intervals (range (uncurry Icc) ∪ range (uncurry Ico) ∪ range (uncurry Ioc) ∪ range (uncurry Ioo)) ∪ -- unbounded intervals and `univ` (range Ici ∪ range Ioi ∪ range Iic ∪ range Iio ∪ {univ, ∅}) := begin refine subset.antisymm set_of_is_preconnected_subset_of_ordered _, simp only [subset_def, -mem_range, forall_range_iff, uncurry, or_imp_distrib, forall_and_distrib, mem_union, mem_set_of_eq, insert_eq, mem_singleton_iff, forall_eq, forall_true_iff, and_true, is_preconnected_Icc, is_preconnected_Ico, is_preconnected_Ioc, is_preconnected_Ioo, is_preconnected_Ioi, is_preconnected_Iio, is_preconnected_Ici, is_preconnected_Iic, is_preconnected_univ, is_preconnected_empty], end variables {δ : Type*} [linear_order δ] [topological_space δ] [order_closed_topology δ] /--Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≤ t ≤ f b`.-/ lemma intermediate_value_Icc {a b : α} (hab : a ≤ b) {f : α → δ} (hf : continuous_on f (Icc a b)) : Icc (f a) (f b) ⊆ f '' (Icc a b) := is_preconnected_Icc.intermediate_value (left_mem_Icc.2 hab) (right_mem_Icc.2 hab) hf /--Intermediate Value Theorem for continuous functions on closed intervals, case `f a ≥ t ≥ f b`.-/ lemma intermediate_value_Icc' {a b : α} (hab : a ≤ b) {f : α → δ} (hf : continuous_on f (Icc a b)) : Icc (f b) (f a) ⊆ f '' (Icc a b) := is_preconnected_Icc.intermediate_value (right_mem_Icc.2 hab) (left_mem_Icc.2 hab) hf /-- A continuous function which tendsto `at_top` `at_top` and to `at_bot` `at_bot` is surjective. -/ lemma continuous.surjective {f : α → δ} (hf : continuous f) (h_top : tendsto f at_top at_top) (h_bot : tendsto f at_bot at_bot) : function.surjective f := λ p, mem_range_of_exists_le_of_exists_ge hf (h_bot.eventually (eventually_le_at_bot p)).exists (h_top.eventually (eventually_ge_at_top p)).exists /-- A continuous function which tendsto `at_bot` `at_top` and to `at_top` `at_bot` is surjective. -/ lemma continuous.surjective' {f : α → δ} (hf : continuous f) (h_top : tendsto f at_bot at_top) (h_bot : tendsto f at_top at_bot) : function.surjective f := @continuous.surjective (order_dual α) _ _ _ _ _ _ _ _ _ hf h_top h_bot /-- If a function `f : α → β` is continuous on a nonempty interval `s`, its restriction to `s` tends to `at_bot : filter β` along `at_bot : filter ↥s` and tends to `at_top : filter β` along `at_top : filter ↥s`, then the restriction of `f` to `s` is surjective. We formulate the conclusion as `surj_on f s univ`. -/ lemma continuous_on.surj_on_of_tendsto {f : α → β} {s : set α} [ord_connected s] (hs : s.nonempty) (hf : continuous_on f s) (hbot : tendsto (λ x : s, f x) at_bot at_bot) (htop : tendsto (λ x : s, f x) at_top at_top) : surj_on f s univ := by haveI := inhabited_of_nonempty hs.to_subtype; exact (surj_on_iff_surjective.2 $ (continuous_on_iff_continuous_restrict.1 hf).surjective htop hbot) /-- If a function `f : α → β` is continuous on a nonempty interval `s`, its restriction to `s` tends to `at_top : filter β` along `at_bot : filter ↥s` and tends to `at_bot : filter β` along `at_top : filter ↥s`, then the restriction of `f` to `s` is surjective. We formulate the conclusion as `surj_on f s univ`. -/ lemma continuous_on.surj_on_of_tendsto' {f : α → β} {s : set α} [ord_connected s] (hs : s.nonempty) (hf : continuous_on f s) (hbot : tendsto (λ x : s, f x) at_bot at_top) (htop : tendsto (λ x : s, f x) at_top at_bot) : surj_on f s univ := @continuous_on.surj_on_of_tendsto α (order_dual β) _ _ _ _ _ _ _ _ _ _ hs hf hbot htop end densely_ordered lemma is_compact.Inf_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : Inf s ∈ s := hs.is_closed.cInf_mem ne_s hs.bdd_below lemma is_compact.Sup_mem {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : Sup s ∈ s := @is_compact.Inf_mem (order_dual α) _ _ _ _ hs ne_s lemma is_compact.is_glb_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_glb s (Inf s) := is_glb_cInf ne_s hs.bdd_below lemma is_compact.is_lub_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_lub s (Sup s) := @is_compact.is_glb_Inf (order_dual α) _ _ _ _ hs ne_s lemma is_compact.is_least_Inf {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_least s (Inf s) := ⟨hs.Inf_mem ne_s, (hs.is_glb_Inf ne_s).1⟩ lemma is_compact.is_greatest_Sup {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : is_greatest s (Sup s) := @is_compact.is_least_Inf (order_dual α) _ _ _ _ hs ne_s lemma is_compact.exists_is_least {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x, is_least s x := ⟨_, hs.is_least_Inf ne_s⟩ lemma is_compact.exists_is_greatest {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x, is_greatest s x := ⟨_, hs.is_greatest_Sup ne_s⟩ lemma is_compact.exists_is_glb {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x ∈ s, is_glb s x := ⟨_, hs.Inf_mem ne_s, hs.is_glb_Inf ne_s⟩ lemma is_compact.exists_is_lub {s : set α} (hs : is_compact s) (ne_s : s.nonempty) : ∃ x ∈ s, is_lub s x := ⟨_, hs.Sup_mem ne_s, hs.is_lub_Sup ne_s⟩ lemma is_compact.exists_Inf_image_eq {α : Type u} [topological_space α] {s : set α} (hs : is_compact s) (ne_s : s.nonempty) {f : α → β} (hf : continuous_on f s) : ∃ x ∈ s, Inf (f '' s) = f x := let ⟨x, hxs, hx⟩ := (hs.image_of_continuous_on hf).Inf_mem (ne_s.image f) in ⟨x, hxs, hx.symm⟩ lemma is_compact.exists_Sup_image_eq {α : Type u} [topological_space α]: ∀ {s : set α}, is_compact s → s.nonempty → ∀ {f : α → β}, continuous_on f s → ∃ x ∈ s, Sup (f '' s) = f x := @is_compact.exists_Inf_image_eq (order_dual β) _ _ _ _ _ lemma eq_Icc_of_connected_compact {s : set α} (h₁ : is_connected s) (h₂ : is_compact s) : s = Icc (Inf s) (Sup s) := eq_Icc_cInf_cSup_of_connected_bdd_closed h₁ h₂.bdd_below h₂.bdd_above h₂.is_closed /-- The extreme value theorem: a continuous function realizes its minimum on a compact set -/ lemma is_compact.exists_forall_le {α : Type u} [topological_space α] {s : set α} (hs : is_compact s) (ne_s : s.nonempty) {f : α → β} (hf : continuous_on f s) : ∃x∈s, ∀y∈s, f x ≤ f y := begin rcases hs.exists_Inf_image_eq ne_s hf with ⟨x, hxs, hx⟩, refine ⟨x, hxs, λ y hy, _⟩, rw ← hx, exact ((hs.image_of_continuous_on hf).is_glb_Inf (ne_s.image f)).1 (mem_image_of_mem _ hy) end /-- The extreme value theorem: a continuous function realizes its maximum on a compact set -/ lemma is_compact.exists_forall_ge {α : Type u} [topological_space α]: ∀ {s : set α}, is_compact s → s.nonempty → ∀ {f : α → β}, continuous_on f s → ∃x∈s, ∀y∈s, f y ≤ f x := @is_compact.exists_forall_le (order_dual β) _ _ _ _ _ /-- The extreme value theorem: if a continuous function `f` tends to infinity away from compact sets, then it has a global minimum. -/ lemma continuous.exists_forall_le {α : Type*} [topological_space α] [nonempty α] {f : α → β} (hf : continuous f) (hlim : tendsto f (cocompact α) at_top) : ∃ x, ∀ y, f x ≤ f y := begin inhabit α, obtain ⟨s : set α, hsc : is_compact s, hsf : ∀ x ∉ s, f (default α) ≤ f x⟩ := (has_basis_cocompact.tendsto_iff at_top_basis).1 hlim (f $ default α) trivial, obtain ⟨x, -, hx⟩ := (hsc.insert (default α)).exists_forall_le (nonempty_insert _ _) hf.continuous_on, refine ⟨x, λ y, _⟩, by_cases hy : y ∈ s, exacts [hx y (or.inr hy), (hx _ (or.inl rfl)).trans (hsf y hy)] end /-- The extreme value theorem: if a continuous function `f` tends to negative infinity away from compactx sets, then it has a global maximum. -/ lemma continuous.exists_forall_ge {α : Type*} [topological_space α] [nonempty α] {f : α → β} (hf : continuous f) (hlim : tendsto f (cocompact α) at_bot) : ∃ x, ∀ y, f y ≤ f x := @continuous.exists_forall_le (order_dual β) _ _ _ _ _ _ _ hf hlim end conditionally_complete_linear_order section liminf_limsup section order_closed_topology variables [semilattice_sup α] [topological_space α] [order_topology α] lemma is_bounded_le_nhds (a : α) : (𝓝 a).is_bounded (≤) := match forall_le_or_exists_lt_sup a with | or.inl h := ⟨a, eventually_of_forall h⟩ | or.inr ⟨b, hb⟩ := ⟨b, ge_mem_nhds hb⟩ end lemma filter.tendsto.is_bounded_under_le {f : filter β} {u : β → α} {a : α} (h : tendsto u f (𝓝 a)) : f.is_bounded_under (≤) u := (is_bounded_le_nhds a).mono h lemma is_cobounded_ge_nhds (a : α) : (𝓝 a).is_cobounded (≥) := (is_bounded_le_nhds a).is_cobounded_flip lemma filter.tendsto.is_cobounded_under_ge {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≥) u := h.is_bounded_under_le.is_cobounded_flip end order_closed_topology section order_closed_topology variables [semilattice_inf α] [topological_space α] [order_topology α] lemma is_bounded_ge_nhds (a : α) : (𝓝 a).is_bounded (≥) := @is_bounded_le_nhds (order_dual α) _ _ _ a lemma filter.tendsto.is_bounded_under_ge {f : filter β} {u : β → α} {a : α} (h : tendsto u f (𝓝 a)) : f.is_bounded_under (≥) u := (is_bounded_ge_nhds a).mono h lemma is_cobounded_le_nhds (a : α) : (𝓝 a).is_cobounded (≤) := (is_bounded_ge_nhds a).is_cobounded_flip lemma filter.tendsto.is_cobounded_under_le {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : f.is_cobounded_under (≤) u := h.is_bounded_under_ge.is_cobounded_flip end order_closed_topology section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] theorem lt_mem_sets_of_Limsup_lt {f : filter α} {b} (h : f.is_bounded (≤)) (l : f.Limsup < b) : ∀ᶠ a in f, a < b := let ⟨c, (h : ∀ᶠ a in f, a ≤ c), hcb⟩ := exists_lt_of_cInf_lt h l in mem_sets_of_superset h $ assume a hac, lt_of_le_of_lt hac hcb theorem gt_mem_sets_of_Liminf_gt : ∀ {f : filter α} {b}, f.is_bounded (≥) → b < f.Liminf → ∀ᶠ a in f, b < a := @lt_mem_sets_of_Limsup_lt (order_dual α) _ variables [topological_space α] [order_topology α] /-- If the liminf and the limsup of a filter coincide, then this filter converges to their common value, at least if the filter is eventually bounded above and below. -/ theorem le_nhds_of_Limsup_eq_Liminf {f : filter α} {a : α} (hl : f.is_bounded (≤)) (hg : f.is_bounded (≥)) (hs : f.Limsup = a) (hi : f.Liminf = a) : f ≤ 𝓝 a := tendsto_order.2 $ and.intro (assume b hb, gt_mem_sets_of_Liminf_gt hg $ hi.symm ▸ hb) (assume b hb, lt_mem_sets_of_Limsup_lt hl $ hs.symm ▸ hb) theorem Limsup_nhds (a : α) : Limsup (𝓝 a) = a := cInf_intro (is_bounded_le_nhds a) (assume a' (h : {n : α | n ≤ a'} ∈ 𝓝 a), show a ≤ a', from @mem_of_nhds α _ a _ h) (assume b (hba : a < b), show ∃c (h : {n : α | n ≤ c} ∈ 𝓝 a), c < b, from match dense_or_discrete a b with | or.inl ⟨c, hac, hcb⟩ := ⟨c, ge_mem_nhds hac, hcb⟩ | or.inr ⟨_, h⟩ := ⟨a, (𝓝 a).sets_of_superset (gt_mem_nhds hba) h, hba⟩ end) theorem Liminf_nhds : ∀ (a : α), Liminf (𝓝 a) = a := @Limsup_nhds (order_dual α) _ _ _ /-- If a filter is converging, its limsup coincides with its limit. -/ theorem Liminf_eq_of_le_nhds {f : filter α} {a : α} [ne_bot f] (h : f ≤ 𝓝 a) : f.Liminf = a := have hb_ge : is_bounded (≥) f, from (is_bounded_ge_nhds a).mono h, have hb_le : is_bounded (≤) f, from (is_bounded_le_nhds a).mono h, le_antisymm (calc f.Liminf ≤ f.Limsup : Liminf_le_Limsup hb_le hb_ge ... ≤ (𝓝 a).Limsup : Limsup_le_Limsup_of_le h hb_ge.is_cobounded_flip (is_bounded_le_nhds a) ... = a : Limsup_nhds a) (calc a = (𝓝 a).Liminf : (Liminf_nhds a).symm ... ≤ f.Liminf : Liminf_le_Liminf_of_le h (is_bounded_ge_nhds a) hb_le.is_cobounded_flip) /-- If a filter is converging, its liminf coincides with its limit. -/ theorem Limsup_eq_of_le_nhds : ∀ {f : filter α} {a : α} [ne_bot f], f ≤ 𝓝 a → f.Limsup = a := @Liminf_eq_of_le_nhds (order_dual α) _ _ _ /-- If a function has a limit, then its limsup coincides with its limit. -/ theorem filter.tendsto.limsup_eq {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : limsup f u = a := Limsup_eq_of_le_nhds h /-- If a function has a limit, then its liminf coincides with its limit. -/ theorem filter.tendsto.liminf_eq {f : filter β} {u : β → α} {a : α} [ne_bot f] (h : tendsto u f (𝓝 a)) : liminf f u = a := Liminf_eq_of_le_nhds h end conditionally_complete_linear_order section complete_linear_order variables [complete_linear_order α] [topological_space α] [order_topology α] -- In complete_linear_order, the above theorems take a simpler form /-- If the liminf and the limsup of a function coincide, then the limit of the function exists and has the same value -/ theorem tendsto_of_liminf_eq_limsup {f : filter β} {u : β → α} {a : α} (hinf : liminf f u = a) (hsup : limsup f u = a) : tendsto u f (𝓝 a) := le_nhds_of_Limsup_eq_Liminf is_bounded_le_of_top is_bounded_ge_of_bot hsup hinf /-- If a number `a` is less than or equal to the `liminf` of a function `f` at some filter and is greater than or equal to the `limsup` of `f`, then `f` tends to `a` along this filter. -/ theorem tendsto_of_le_liminf_of_limsup_le {f : filter β} {u : β → α} {a : α} (hinf : a ≤ liminf f u) (hsup : limsup f u ≤ a) : tendsto u f (𝓝 a) := if hf : f = ⊥ then hf.symm ▸ tendsto_bot else by haveI : ne_bot f := ⟨hf⟩; exact tendsto_of_liminf_eq_limsup (le_antisymm (le_trans liminf_le_limsup hsup) hinf) (le_antisymm hsup (le_trans hinf liminf_le_limsup)) end complete_linear_order end liminf_limsup end order_topology /-! Here is a counter-example to a version of the following with `conditionally_complete_lattice α`. Take `α = [0, 1) → ℝ` with the natural lattice structure, `ι = ℕ`. Put `f n x = -x^n`. Then `⨆ n, f n = 0` while none of `f n` is strictly greater than the constant function `-0.5`. -/ lemma tendsto_at_top_csupr {ι α : Type*} [preorder ι] [topological_space α] [conditionally_complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) (hbdd : bdd_above $ range f) : tendsto f at_top (𝓝 (⨆i, f i)) := begin by_cases hi : nonempty ι, { resetI, rw tendsto_order, split, { intros a h, cases exists_lt_of_lt_csupr h with N hN, apply eventually.mono (mem_at_top N), exact λ i hi, lt_of_lt_of_le hN (h_mono hi) }, { exact λ a h, eventually_of_forall (λ n, lt_of_le_of_lt (le_csupr hbdd n) h) } }, { exact tendsto_of_not_nonempty hi } end lemma tendsto_at_top_cinfi {ι α : Type*} [preorder ι] [topological_space α] [conditionally_complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : ∀ ⦃i j⦄, i ≤ j → f j ≤ f i) (hbdd : bdd_below $ range f) : tendsto f at_top (𝓝 (⨅i, f i)) := @tendsto_at_top_csupr _ (order_dual α) _ _ _ _ _ @h_mono hbdd lemma tendsto_at_top_supr {ι α : Type*} [preorder ι] [topological_space α] [complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) : tendsto f at_top (𝓝 (⨆i, f i)) := tendsto_at_top_csupr h_mono (order_top.bdd_above _) lemma tendsto_at_top_infi {ι α : Type*} [preorder ι] [topological_space α] [complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : ∀ ⦃i j⦄, i ≤ j → f j ≤ f i) : tendsto f at_top (𝓝 (⨅i, f i)) := tendsto_at_top_cinfi @h_mono (order_bot.bdd_below _) lemma tendsto_of_monotone {ι α : Type*} [preorder ι] [topological_space α] [conditionally_complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) : tendsto f at_top at_top ∨ (∃ l, tendsto f at_top (𝓝 l)) := if H : bdd_above (range f) then or.inr ⟨_, tendsto_at_top_csupr h_mono H⟩ else or.inl $ tendsto_at_top_at_top_of_monotone' h_mono H lemma supr_eq_of_tendsto {α β} [topological_space α] [complete_linear_order α] [order_topology α] [nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : monotone f) : tendsto f at_top (𝓝 a) → supr f = a := tendsto_nhds_unique (tendsto_at_top_supr hf) lemma infi_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [order_topology α] [nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : ∀n m, n ≤ m → f m ≤ f n) : tendsto f at_top (𝓝 a) → infi f = a := tendsto_nhds_unique (tendsto_at_top_infi hf) @[to_additive] lemma tendsto_inv_nhds_within_Ioi [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Ioi a] a) (𝓝[Iio (a⁻¹)] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Iio [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Iio a] a) (𝓝[Ioi (a⁻¹)] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Ioi_inv [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Ioi (a⁻¹)] (a⁻¹)) (𝓝[Iio a] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ioi _ _ _ _ (a⁻¹) @[to_additive] lemma tendsto_inv_nhds_within_Iio_inv [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Iio (a⁻¹)] (a⁻¹)) (𝓝[Ioi a] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iio _ _ _ _ (a⁻¹) @[to_additive] lemma tendsto_inv_nhds_within_Ici [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Ici a] a) (𝓝[Iic (a⁻¹)] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Iic [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Iic a] a) (𝓝[Ici (a⁻¹)] (a⁻¹)) := (continuous_inv.tendsto a).inf $ by simp [tendsto_principal_principal] @[to_additive] lemma tendsto_inv_nhds_within_Ici_inv [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Ici (a⁻¹)] (a⁻¹)) (𝓝[Iic a] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Ici _ _ _ _ (a⁻¹) @[to_additive] lemma tendsto_inv_nhds_within_Iic_inv [ordered_comm_group α] [topological_space α] [topological_group α] {a : α} : tendsto has_inv.inv (𝓝[Iic (a⁻¹)] (a⁻¹)) (𝓝[Ici a] a) := by simpa only [inv_inv] using @tendsto_inv_nhds_within_Iic _ _ _ _ (a⁻¹) lemma nhds_left_sup_nhds_right (a : α) [topological_space α] [linear_order α] : 𝓝[Iic a] a ⊔ 𝓝[Ici a] a = 𝓝 a := by rw [← nhds_within_union, Iic_union_Ici, nhds_within_univ] lemma nhds_left'_sup_nhds_right (a : α) [topological_space α] [linear_order α] : 𝓝[Iio a] a ⊔ 𝓝[Ici a] a = 𝓝 a := by rw [← nhds_within_union, Iio_union_Ici, nhds_within_univ] lemma nhds_left_sup_nhds_right' (a : α) [topological_space α] [linear_order α] : 𝓝[Iic a] a ⊔ 𝓝[Ioi a] a = 𝓝 a := by rw [← nhds_within_union, Iic_union_Ioi, nhds_within_univ] lemma continuous_at_iff_continuous_left_right [topological_space α] [linear_order α] [topological_space β] {a : α} {f : α → β} : continuous_at f a ↔ continuous_within_at f (Iic a) a ∧ continuous_within_at f (Ici a) a := by simp only [continuous_within_at, continuous_at, ← tendsto_sup, nhds_left_sup_nhds_right] lemma continuous_on_Icc_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [regular_space β] {f : α → β} {a b : α} {la lb : β} (hab : a < b) (hf : continuous_on f (Ioo a b)) (ha : tendsto f (𝓝[Ioi a] a) (𝓝 la)) (hb : tendsto f (𝓝[Iio b] b) (𝓝 lb)) : continuous_on (extend_from (Ioo a b) f) (Icc a b) := begin apply continuous_on_extend_from, { rw closure_Ioo hab, }, { intros x x_in, rcases mem_Ioo_or_eq_endpoints_of_mem_Icc x_in with rfl | rfl | h, { use la, simpa [hab] }, { use lb, simpa [hab] }, { use [f x, hf x h] } } end lemma eq_lim_at_left_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [t2_space β] {f : α → β} {a b : α} {la : β} (hab : a < b) (ha : tendsto f (𝓝[Ioi a] a) (𝓝 la)) : extend_from (Ioo a b) f a = la := begin apply extend_from_eq, { rw closure_Ioo hab, simp only [le_of_lt hab, left_mem_Icc, right_mem_Icc] }, { simpa [hab] } end lemma eq_lim_at_right_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [t2_space β] {f : α → β} {a b : α} {lb : β} (hab : a < b) (hb : tendsto f (𝓝[Iio b] b) (𝓝 lb)) : extend_from (Ioo a b) f b = lb := begin apply extend_from_eq, { rw closure_Ioo hab, simp only [le_of_lt hab, left_mem_Icc, right_mem_Icc] }, { simpa [hab] } end lemma continuous_on_Ico_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [regular_space β] {f : α → β} {a b : α} {la : β} (hab : a < b) (hf : continuous_on f (Ioo a b)) (ha : tendsto f (𝓝[Ioi a] a) (𝓝 la)) : continuous_on (extend_from (Ioo a b) f) (Ico a b) := begin apply continuous_on_extend_from, { rw [closure_Ioo hab], exact Ico_subset_Icc_self, }, { intros x x_in, rcases mem_Ioo_or_eq_left_of_mem_Ico x_in with rfl | h, { use la, simpa [hab] }, { use [f x, hf x h] } } end lemma continuous_on_Ioc_extend_from_Ioo [topological_space α] [linear_order α] [densely_ordered α] [order_topology α] [topological_space β] [regular_space β] {f : α → β} {a b : α} {lb : β} (hab : a < b) (hf : continuous_on f (Ioo a b)) (hb : tendsto f (𝓝[Iio b] b) (𝓝 lb)) : continuous_on (extend_from (Ioo a b) f) (Ioc a b) := begin have := @continuous_on_Ico_extend_from_Ioo (order_dual α) _ _ _ _ _ _ _ f _ _ _ hab, erw [dual_Ico, dual_Ioi, dual_Ioo] at this, exact this hf hb end lemma continuous_within_at_Ioi_iff_Ici {α β : Type*} [topological_space α] [partial_order α] [topological_space β] {a : α} {f : α → β} : continuous_within_at f (Ioi a) a ↔ continuous_within_at f (Ici a) a := by simp only [← Ici_diff_left, continuous_within_at_diff_self] lemma continuous_within_at_Iio_iff_Iic {α β : Type*} [topological_space α] [linear_order α] [topological_space β] {a : α} {f : α → β} : continuous_within_at f (Iio a) a ↔ continuous_within_at f (Iic a) a := begin have := @continuous_within_at_Ioi_iff_Ici (order_dual α) _ _ _ _ _ f, erw [dual_Ici, dual_Ioi] at this, exact this, end lemma continuous_at_iff_continuous_left'_right' [topological_space α] [linear_order α] [topological_space β] {a : α} {f : α → β} : continuous_at f a ↔ continuous_within_at f (Iio a) a ∧ continuous_within_at f (Ioi a) a := by rw [continuous_within_at_Ioi_iff_Ici, continuous_within_at_Iio_iff_Iic, continuous_at_iff_continuous_left_right] /-! ### Continuity of monotone functions In this section we prove the following fact: if `f` is a monotone function on a neighborhood of `a` and the image of this neighborhood is a neighborhood of `f a`, then `f` is continuous at `a`, see `continuous_at_of_mono_incr_on_of_image_mem_nhds`, as well as several similar facts. -/ section linear_order variables [linear_order α] [topological_space α] [order_topology α] variables [linear_order β] [topological_space β] [order_topology β] /-- If `f` is a function strictly monotonically increasing on a right neighborhood of `a` and the image of this neighborhood under `f` meets every interval `(f a, b]`, `b > f a`, then `f` is continuous at `a` from the right. The assumption `hfs : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioc (f a) b` is required because otherwise the function `f : ℝ → ℝ` given by `f x = if x ≤ 0 then x else x + 1` would be a counter-example at `a = 0`. -/ lemma strict_mono_incr_on.continuous_at_right_of_exists_between {f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Ici a] a) (hfs : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioc (f a) b) : continuous_within_at f (Ici a) a := begin have ha : a ∈ Ici a := left_mem_Ici, have has : a ∈ s := mem_of_mem_nhds_within ha hs, refine tendsto_order.2 ⟨λ b hb, _, λ b hb, _⟩, { filter_upwards [hs, self_mem_nhds_within], intros x hxs hxa, exact hb.trans_le ((h_mono.le_iff_le has hxs).2 hxa) }, { rcases hfs b hb with ⟨c, hcs, hac, hcb⟩, rw [h_mono.lt_iff_lt has hcs] at hac, filter_upwards [hs, Ico_mem_nhds_within_Ici (left_mem_Ico.2 hac)], rintros x hx ⟨hax, hxc⟩, exact ((h_mono.lt_iff_lt hx hcs).2 hxc).trans_le hcb } end /-- If `f` is a function monotonically increasing function on a right neighborhood of `a` and the image of this neighborhood under `f` meets every interval `(f a, b)`, `b > f a`, then `f` is continuous at `a` from the right. The assumption `hfs : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioo (f a) b` cannot be replaced by the weaker assumption `hfs : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioc (f a) b` we use for strictly monotone functions because otherwise the function `ceil : ℝ → ℤ` would be a counter-example at `a = 0`. -/ lemma continuous_at_right_of_mono_incr_on_of_exists_between {f : α → β} {s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝[Ici a] a) (hfs : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioo (f a) b) : continuous_within_at f (Ici a) a := begin have ha : a ∈ Ici a := left_mem_Ici, have has : a ∈ s := mem_of_mem_nhds_within ha hs, refine tendsto_order.2 ⟨λ b hb, _, λ b hb, _⟩, { filter_upwards [hs, self_mem_nhds_within], intros x hxs hxa, exact hb.trans_le (h_mono _ has _ hxs hxa) }, { rcases hfs b hb with ⟨c, hcs, hac, hcb⟩, have : a < c, from not_le.1 (λ h, hac.not_le $ h_mono _ hcs _ has h), filter_upwards [hs, Ico_mem_nhds_within_Ici (left_mem_Ico.2 this)], rintros x hx ⟨hax, hxc⟩, exact (h_mono _ hx _ hcs hxc.le).trans_lt hcb } end /-- If a function `f` with a densely ordered codomain is monotonically increasing on a right neighborhood of `a` and the closure of the image of this neighborhood under `f` is a right neighborhood of `f a`, then `f` is continuous at `a` from the right. -/ lemma continuous_at_right_of_mono_incr_on_of_closure_image_mem_nhds_within [densely_ordered β] {f : α → β} {s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝[Ici a] a) (hfs : closure (f '' s) ∈ 𝓝[Ici (f a)] (f a)) : continuous_within_at f (Ici a) a := begin refine continuous_at_right_of_mono_incr_on_of_exists_between h_mono hs (λ b hb, _), rcases (mem_nhds_within_Ici_iff_exists_mem_Ioc_Ico_subset hb).1 hfs with ⟨b', ⟨hab', hbb'⟩, hb'⟩, rcases exists_between hab' with ⟨c', hc'⟩, rcases mem_closure_iff.1 (hb' ⟨hc'.1.le, hc'.2⟩) (Ioo (f a) b') is_open_Ioo hc' with ⟨_, hc, ⟨c, hcs, rfl⟩⟩, exact ⟨c, hcs, hc.1, hc.2.trans_le hbb'⟩ end /-- If a function `f` with a densely ordered codomain is monotonically increasing on a right neighborhood of `a` and the image of this neighborhood under `f` is a right neighborhood of `f a`, then `f` is continuous at `a` from the right. -/ lemma continuous_at_right_of_mono_incr_on_of_image_mem_nhds_within [densely_ordered β] {f : α → β} {s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝[Ici a] a) (hfs : f '' s ∈ 𝓝[Ici (f a)] (f a)) : continuous_within_at f (Ici a) a := continuous_at_right_of_mono_incr_on_of_closure_image_mem_nhds_within h_mono hs $ mem_sets_of_superset hfs subset_closure /-- If a function `f` with a densely ordered codomain is strictly monotonically increasing on a right neighborhood of `a` and the closure of the image of this neighborhood under `f` is a right neighborhood of `f a`, then `f` is continuous at `a` from the right. -/ lemma strict_mono_incr_on.continuous_at_right_of_closure_image_mem_nhds_within [densely_ordered β] {f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Ici a] a) (hfs : closure (f '' s) ∈ 𝓝[Ici (f a)] (f a)) : continuous_within_at f (Ici a) a := continuous_at_right_of_mono_incr_on_of_closure_image_mem_nhds_within (λ x hx y hy, (h_mono.le_iff_le hx hy).2) hs hfs /-- If a function `f` with a densely ordered codomain is strictly monotonically increasing on a right neighborhood of `a` and the image of this neighborhood under `f` is a right neighborhood of `f a`, then `f` is continuous at `a` from the right. -/ lemma strict_mono_incr_on.continuous_at_right_of_image_mem_nhds_within [densely_ordered β] {f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Ici a] a) (hfs : f '' s ∈ 𝓝[Ici (f a)] (f a)) : continuous_within_at f (Ici a) a := h_mono.continuous_at_right_of_closure_image_mem_nhds_within hs (mem_sets_of_superset hfs subset_closure) /-- If a function `f` is strictly monotonically increasing on a right neighborhood of `a` and the image of this neighborhood under `f` includes `Ioi (f a)`, then `f` is continuous at `a` from the right. -/ lemma strict_mono_incr_on.continuous_at_right_of_surj_on {f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Ici a] a) (hfs : surj_on f s (Ioi (f a))) : continuous_within_at f (Ici a) a := h_mono.continuous_at_right_of_exists_between hs $ λ b hb, let ⟨c, hcs, hcb⟩ := hfs hb in ⟨c, hcs, hcb.symm ▸ hb, hcb.le⟩ /-- If `f` is a function strictly monotonically increasing on a left neighborhood of `a` and the image of this neighborhood under `f` meets every interval `[b, f a)`, `b < f a`, then `f` is continuous at `a` from the left. The assumption `hfs : ∀ b < f a, ∃ c ∈ s, f c ∈ Ico b (f a)` is required because otherwise the function `f : ℝ → ℝ` given by `f x = if x < 0 then x else x + 1` would be a counter-example at `a = 0`. -/ lemma strict_mono_incr_on.continuous_at_left_of_exists_between {f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Iic a] a) (hfs : ∀ b < f a, ∃ c ∈ s, f c ∈ Ico b (f a)) : continuous_within_at f (Iic a) a := h_mono.dual.continuous_at_right_of_exists_between hs $ λ b hb, let ⟨c, hcs, hcb, hca⟩ := hfs b hb in ⟨c, hcs, hca, hcb⟩ /-- If `f` is a function monotonically increasing function on a left neighborhood of `a` and the image of this neighborhood under `f` meets every interval `(b, f a)`, `b < f a`, then `f` is continuous at `a` from the left. The assumption `hfs : ∀ b < f a, ∃ c ∈ s, f c ∈ Ioo b (f a)` cannot be replaced by the weaker assumption `hfs : ∀ b < f a, ∃ c ∈ s, f c ∈ Ico b (f a)` we use for strictly monotone functions because otherwise the function `floor : ℝ → ℤ` would be a counter-example at `a = 0`. -/ lemma continuous_at_left_of_mono_incr_on_of_exists_between {f : α → β} {s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝[Iic a] a) (hfs : ∀ b < f a, ∃ c ∈ s, f c ∈ Ioo b (f a)) : continuous_within_at f (Iic a) a := @continuous_at_right_of_mono_incr_on_of_exists_between (order_dual α) (order_dual β) _ _ _ _ _ _ f s a (λ x hx y hy, h_mono y hy x hx) hs $ λ b hb, let ⟨c, hcs, hcb, hca⟩ := hfs b hb in ⟨c, hcs, hca, hcb⟩ /-- If a function `f` with a densely ordered codomain is monotonically increasing on a left neighborhood of `a` and the closure of the image of this neighborhood under `f` is a left neighborhood of `f a`, then `f` is continuous at `a` from the left -/ lemma continuous_at_left_of_mono_incr_on_of_closure_image_mem_nhds_within [densely_ordered β] {f : α → β} {s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝[Iic a] a) (hfs : closure (f '' s) ∈ 𝓝[Iic (f a)] (f a)) : continuous_within_at f (Iic a) a := @continuous_at_right_of_mono_incr_on_of_closure_image_mem_nhds_within (order_dual α) (order_dual β) _ _ _ _ _ _ _ f s a (λ x hx y hy, h_mono y hy x hx) hs hfs /-- If a function `f` with a densely ordered codomain is monotonically increasing on a left neighborhood of `a` and the image of this neighborhood under `f` is a left neighborhood of `f a`, then `f` is continuous at `a` from the left. -/ lemma continuous_at_left_of_mono_incr_on_of_image_mem_nhds_within [densely_ordered β] {f : α → β} {s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝[Iic a] a) (hfs : f '' s ∈ 𝓝[Iic (f a)] (f a)) : continuous_within_at f (Iic a) a := continuous_at_left_of_mono_incr_on_of_closure_image_mem_nhds_within h_mono hs (mem_sets_of_superset hfs subset_closure) /-- If a function `f` with a densely ordered codomain is strictly monotonically increasing on a left neighborhood of `a` and the closure of the image of this neighborhood under `f` is a left neighborhood of `f a`, then `f` is continuous at `a` from the left. -/ lemma strict_mono_incr_on.continuous_at_left_of_closure_image_mem_nhds_within [densely_ordered β] {f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Iic a] a) (hfs : closure (f '' s) ∈ 𝓝[Iic (f a)] (f a)) : continuous_within_at f (Iic a) a := h_mono.dual.continuous_at_right_of_closure_image_mem_nhds_within hs hfs /-- If a function `f` with a densely ordered codomain is strictly monotonically increasing on a left neighborhood of `a` and the image of this neighborhood under `f` is a left neighborhood of `f a`, then `f` is continuous at `a` from the left. -/ lemma strict_mono_incr_on.continuous_at_left_of_image_mem_nhds_within [densely_ordered β] {f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Iic a] a) (hfs : f '' s ∈ 𝓝[Iic (f a)] (f a)) : continuous_within_at f (Iic a) a := h_mono.dual.continuous_at_right_of_image_mem_nhds_within hs hfs /-- If a function `f` is strictly monotonically increasing on a left neighborhood of `a` and the image of this neighborhood under `f` includes `Iio (f a)`, then `f` is continuous at `a` from the left. -/ lemma strict_mono_incr_on.continuous_at_left_of_surj_on {f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝[Iic a] a) (hfs : surj_on f s (Iio (f a))) : continuous_within_at f (Iic a) a := h_mono.dual.continuous_at_right_of_surj_on hs hfs /-- If a function `f` is strictly monotonically increasing on a neighborhood of `a` and the image of this neighborhood under `f` meets every interval `[b, f a)`, `b < f a`, and every interval `(f a, b]`, `b > f a`, then `f` is continuous at `a`. -/ lemma strict_mono_incr_on.continuous_at_of_exists_between {f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝 a) (hfs_l : ∀ b < f a, ∃ c ∈ s, f c ∈ Ico b (f a)) (hfs_r : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioc (f a) b) : continuous_at f a := continuous_at_iff_continuous_left_right.2 ⟨h_mono.continuous_at_left_of_exists_between (mem_nhds_within_of_mem_nhds hs) hfs_l, h_mono.continuous_at_right_of_exists_between (mem_nhds_within_of_mem_nhds hs) hfs_r⟩ /-- If a function `f` with a densely ordered codomain is strictly monotonically increasing on a neighborhood of `a` and the closure of the image of this neighborhood under `f` is a neighborhood of `f a`, then `f` is continuous at `a`. -/ lemma strict_mono_incr_on.continuous_at_of_closure_image_mem_nhds [densely_ordered β] {f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝 a) (hfs : closure (f '' s) ∈ 𝓝 (f a)) : continuous_at f a := continuous_at_iff_continuous_left_right.2 ⟨h_mono.continuous_at_left_of_closure_image_mem_nhds_within (mem_nhds_within_of_mem_nhds hs) (mem_nhds_within_of_mem_nhds hfs), h_mono.continuous_at_right_of_closure_image_mem_nhds_within (mem_nhds_within_of_mem_nhds hs) (mem_nhds_within_of_mem_nhds hfs)⟩ /-- If a function `f` with a densely ordered codomain is strictly monotonically increasing on a neighborhood of `a` and the image of this set under `f` is a neighborhood of `f a`, then `f` is continuous at `a`. -/ lemma strict_mono_incr_on.continuous_at_of_image_mem_nhds [densely_ordered β] {f : α → β} {s : set α} {a : α} (h_mono : strict_mono_incr_on f s) (hs : s ∈ 𝓝 a) (hfs : f '' s ∈ 𝓝 (f a)) : continuous_at f a := h_mono.continuous_at_of_closure_image_mem_nhds hs (mem_sets_of_superset hfs subset_closure) /-- If `f` is a function monotonically increasing function on a neighborhood of `a` and the image of this neighborhood under `f` meets every interval `(b, f a)`, `b < f a`, and every interval `(f a, b)`, `b > f a`, then `f` is continuous at `a`. -/ lemma continuous_at_of_mono_incr_on_of_exists_between {f : α → β} {s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝 a) (hfs_l : ∀ b < f a, ∃ c ∈ s, f c ∈ Ioo b (f a)) (hfs_r : ∀ b > f a, ∃ c ∈ s, f c ∈ Ioo (f a) b) : continuous_at f a := continuous_at_iff_continuous_left_right.2 ⟨continuous_at_left_of_mono_incr_on_of_exists_between h_mono (mem_nhds_within_of_mem_nhds hs) hfs_l, continuous_at_right_of_mono_incr_on_of_exists_between h_mono (mem_nhds_within_of_mem_nhds hs) hfs_r⟩ /-- If a function `f` with a densely ordered codomain is monotonically increasing on a neighborhood of `a` and the closure of the image of this neighborhood under `f` is a neighborhood of `f a`, then `f` is continuous at `a`. -/ lemma continuous_at_of_mono_incr_on_of_closure_image_mem_nhds [densely_ordered β] {f : α → β} {s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝 a) (hfs : closure (f '' s) ∈ 𝓝 (f a)) : continuous_at f a := continuous_at_iff_continuous_left_right.2 ⟨continuous_at_left_of_mono_incr_on_of_closure_image_mem_nhds_within h_mono (mem_nhds_within_of_mem_nhds hs) (mem_nhds_within_of_mem_nhds hfs), continuous_at_right_of_mono_incr_on_of_closure_image_mem_nhds_within h_mono (mem_nhds_within_of_mem_nhds hs) (mem_nhds_within_of_mem_nhds hfs)⟩ /-- If a function `f` with a densely ordered codomain is monotonically increasing on a neighborhood of `a` and the image of this neighborhood under `f` is a neighborhood of `f a`, then `f` is continuous at `a`. -/ lemma continuous_at_of_mono_incr_on_of_image_mem_nhds [densely_ordered β] {f : α → β} {s : set α} {a : α} (h_mono : ∀ (x ∈ s) (y ∈ s), x ≤ y → f x ≤ f y) (hs : s ∈ 𝓝 a) (hfs : f '' s ∈ 𝓝 (f a)) : continuous_at f a := continuous_at_of_mono_incr_on_of_closure_image_mem_nhds h_mono hs (mem_sets_of_superset hfs subset_closure) /-- A monotone function with densely ordered codomain and a dense range is continuous. -/ lemma monotone.continuous_of_dense_range [densely_ordered β] {f : α → β} (h_mono : monotone f) (h_dense : dense_range f) : continuous f := continuous_iff_continuous_at.mpr $ λ a, continuous_at_of_mono_incr_on_of_closure_image_mem_nhds (λ x hx y hy hxy, h_mono hxy) univ_mem_sets $ by simp only [image_univ, h_dense.closure_eq, univ_mem_sets] /-- A monotone surjective function with a densely ordered codomain is surjective. -/ lemma monotone.continuous_of_surjective [densely_ordered β] {f : α → β} (h_mono : monotone f) (h_surj : function.surjective f) : continuous f := h_mono.continuous_of_dense_range h_surj.dense_range end linear_order /-! ### Continuity of order isomorphisms In this section we prove that an `order_iso` is continuous, hence it is a `homeomorph`. We prove this for an `order_iso` between to partial orders with order topology. -/ namespace order_iso variables [partial_order α] [partial_order β] [topological_space α] [topological_space β] [order_topology α] [order_topology β] protected lemma continuous (e : α ≃o β) : continuous e := begin rw [‹order_topology β›.topology_eq_generate_intervals], refine continuous_generated_from (λ s hs, _), rcases hs with ⟨a, rfl|rfl⟩, { rw e.preimage_Ioi, apply is_open_lt' }, { rw e.preimage_Iio, apply is_open_gt' } end /-- An order isomorphism between two linear order `order_topology` spaces is a homeomorphism. -/ def to_homeomorph (e : α ≃o β) : α ≃ₜ β := { continuous_to_fun := e.continuous, continuous_inv_fun := e.symm.continuous, .. e } @[simp] lemma coe_to_homeomorph (e : α ≃o β) : ⇑e.to_homeomorph = e := rfl @[simp] lemma coe_to_homeomorph_symm (e : α ≃o β) : ⇑e.to_homeomorph.symm = e.symm := rfl end order_iso
fe7a470862a280510c7aaf865e5abc2d60fd31ce
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/real/irrational.lean
4305b60717c5e4c9c9c658fccafb1eb43b7969ca
[ "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
8,255
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Yury Kudryashov. -/ import data.real.basic import data.rat.sqrt import algebra.gcd_monoid import ring_theory.multiplicity /-! # Irrational real numbers In this file we define a predicate `irrational` on `ℝ`, prove that the `n`-th root of an integer number is irrational if it is not integer, and that `sqrt q` is irrational if and only if `rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q`. We also provide dot-style constructors like `irrational.add_rat`, `irrational.rat_sub` etc. -/ open rat real multiplicity /-- A real number is irrational if it is not equal to any rational number. -/ def irrational (x : ℝ) := x ∉ set.range (coe : ℚ → ℝ) /-! ### Irrationality of roots of integer and rational numbers -/ /-- If `x^n`, `n > 0`, is integer and is not the `n`-th power of an integer, then `x` is irrational. -/ theorem irrational_nrt_of_notint_nrt {x : ℝ} (n : ℕ) (m : ℤ) (hxr : x ^ n = m) (hv : ¬ ∃ y : ℤ, x = y) (hnpos : 0 < n) : irrational x := begin rintros ⟨⟨N, D, P, C⟩, rfl⟩, rw [← cast_pow] at hxr, have c1 : ((D : ℤ) : ℝ) ≠ 0, { rw [int.cast_ne_zero, int.coe_nat_ne_zero], exact ne_of_gt P }, have c2 : ((D : ℤ) : ℝ) ^ n ≠ 0 := pow_ne_zero _ c1, rw [num_denom', cast_pow, cast_mk, div_pow, div_eq_iff_mul_eq c2, ← int.cast_pow, ← int.cast_pow, ← int.cast_mul, int.cast_inj] at hxr, have hdivn : ↑D ^ n ∣ N ^ n := dvd.intro_left m hxr, rw [← int.dvd_nat_abs, ← int.coe_nat_pow, int.coe_nat_dvd, int.nat_abs_pow, nat.pow_dvd_pow_iff hnpos] at hdivn, have hD : D = 1 := by rw [← nat.gcd_eq_right hdivn, C.gcd_eq_one], subst D, refine hv ⟨N, _⟩, rw [num_denom', int.coe_nat_one, mk_eq_div, int.cast_one, div_one, cast_coe_int] end /-- If `x^n = m` is an integer and `n` does not divide the `multiplicity p m`, then `x` is irrational. -/ theorem irrational_nrt_of_n_not_dvd_multiplicity {x : ℝ} (n : ℕ) {m : ℤ} (hm : m ≠ 0) (p : ℕ) [hp : fact p.prime] (hxr : x ^ n = m) (hv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.ne_one, hm⟩) % n ≠ 0) : irrational x := begin rcases nat.eq_zero_or_pos n with rfl | hnpos, { rw [eq_comm, pow_zero, ← int.cast_one, int.cast_inj] at hxr, simpa [hxr, multiplicity.one_right (mt is_unit_iff_dvd_one.1 (mt int.coe_nat_dvd.1 hp.not_dvd_one)), nat.zero_mod] using hv }, refine irrational_nrt_of_notint_nrt _ _ hxr _ hnpos, rintro ⟨y, rfl⟩, rw [← int.cast_pow, int.cast_inj] at hxr, subst m, have : y ≠ 0, { rintro rfl, rw zero_pow hnpos at hm, exact hm rfl }, erw [multiplicity.pow' (nat.prime_iff_prime_int.1 hp) (finite_int_iff.2 ⟨hp.ne_one, this⟩), nat.mul_mod_right] at hv, exact hv rfl end theorem irrational_sqrt_of_multiplicity_odd (m : ℤ) (hm : 0 < m) (p : ℕ) [hp : fact p.prime] (Hpv : (multiplicity (p : ℤ) m).get (finite_int_iff.2 ⟨hp.ne_one, (ne_of_lt hm).symm⟩) % 2 = 1) : irrational (sqrt m) := @irrational_nrt_of_n_not_dvd_multiplicity _ 2 _ (ne.symm (ne_of_lt hm)) p hp (sqr_sqrt (int.cast_nonneg.2 $ le_of_lt hm)) (by rw Hpv; exact one_ne_zero) theorem nat.prime.irrational_sqrt {p : ℕ} (hp : nat.prime p) : irrational (sqrt p) := @irrational_sqrt_of_multiplicity_odd p (int.coe_nat_pos.2 hp.pos) p hp $ by simp [multiplicity_self (mt is_unit_iff_dvd_one.1 (mt int.coe_nat_dvd.1 hp.not_dvd_one) : _)]; refl theorem irrational_sqrt_two : irrational (sqrt 2) := by simpa using nat.prime_two.irrational_sqrt theorem irrational_sqrt_rat_iff (q : ℚ) : irrational (sqrt q) ↔ rat.sqrt q * rat.sqrt q ≠ q ∧ 0 ≤ q := if H1 : rat.sqrt q * rat.sqrt q = q then iff_of_false (not_not_intro ⟨rat.sqrt q, by rw [← H1, cast_mul, sqrt_mul_self (cast_nonneg.2 $ rat.sqrt_nonneg q), sqrt_eq, abs_of_nonneg (rat.sqrt_nonneg q)]⟩) (λ h, h.1 H1) else if H2 : 0 ≤ q then iff_of_true (λ ⟨r, hr⟩, H1 $ (exists_mul_self _).1 ⟨r, by rwa [eq_comm, sqrt_eq_iff_mul_self_eq (cast_nonneg.2 H2), ← cast_mul, cast_inj] at hr; rw [← hr]; exact real.sqrt_nonneg _⟩) ⟨H1, H2⟩ else iff_of_false (not_not_intro ⟨0, by rw cast_zero; exact (sqrt_eq_zero_of_nonpos (rat.cast_nonpos.2 $ le_of_not_le H2)).symm⟩) (λ h, H2 h.2) instance (q : ℚ) : decidable (irrational (sqrt q)) := decidable_of_iff' _ (irrational_sqrt_rat_iff q) /-! ### Adding/subtracting/multiplying by rational numbers -/ lemma rat.not_irrational (q : ℚ) : ¬irrational q := λ h, h ⟨q, rfl⟩ namespace irrational variables (q : ℚ) {x y : ℝ} open_locale classical theorem add_cases : irrational (x + y) → irrational x ∨ irrational y := begin delta irrational, contrapose!, rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩, exact ⟨rx + ry, cast_add rx ry⟩ end theorem of_rat_add (h : irrational (q + x)) : irrational x := h.add_cases.elim (λ h, absurd h q.not_irrational) id theorem rat_add (h : irrational x) : irrational (q + x) := of_rat_add (-q) $ by rwa [cast_neg, neg_add_cancel_left] theorem of_add_rat : irrational (x + q) → irrational x := add_comm ↑q x ▸ of_rat_add q theorem add_rat (h : irrational x) : irrational (x + q) := add_comm ↑q x ▸ h.rat_add q theorem of_neg (h : irrational (-x)) : irrational x := λ ⟨q, hx⟩, h ⟨-q, by rw [cast_neg, hx]⟩ protected theorem neg (h : irrational x) : irrational (-x) := of_neg $ by rwa neg_neg theorem sub_rat (h : irrational x) : irrational (x - q) := by simpa only [cast_neg] using h.add_rat (-q) theorem rat_sub (h : irrational x) : irrational (q - x) := h.neg.rat_add q theorem of_sub_rat (h : irrational (x - q)) : irrational x := of_add_rat (-q) $ by simpa only [cast_neg] theorem of_rat_sub (h : irrational (q - x)) : irrational x := (h.of_rat_add _).of_neg theorem mul_cases : irrational (x * y) → irrational x ∨ irrational y := begin delta irrational, contrapose!, rintros ⟨⟨rx, rfl⟩, ⟨ry, rfl⟩⟩, exact ⟨rx * ry, cast_mul rx ry⟩ end theorem of_mul_rat (h : irrational (x * q)) : irrational x := h.mul_cases.elim id (λ h, absurd h q.not_irrational) theorem mul_rat (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (x * q) := of_mul_rat q⁻¹ $ by rwa [mul_assoc, ← cast_mul, mul_inv_cancel hq, cast_one, mul_one] theorem of_rat_mul : irrational (q * x) → irrational x := mul_comm x q ▸ of_mul_rat q theorem rat_mul (h : irrational x) {q : ℚ} (hq : q ≠ 0) : irrational (q * x) := mul_comm x q ▸ h.mul_rat hq theorem of_mul_self (h : irrational (x * x)) : irrational x := h.mul_cases.elim id id theorem of_inv (h : irrational x⁻¹) : irrational x := λ ⟨q, hq⟩, h $ hq ▸ ⟨q⁻¹, q.cast_inv⟩ protected theorem inv (h : irrational x) : irrational x⁻¹ := of_inv $ by rwa inv_inv' theorem div_cases (h : irrational (x / y)) : irrational x ∨ irrational y := h.mul_cases.imp id of_inv theorem of_rat_div (h : irrational (q / x)) : irrational x := (h.of_rat_mul q).of_inv theorem of_one_div (h : irrational (1 / x)) : irrational x := of_rat_div 1 $ by rwa [cast_one] theorem of_pow : ∀ n : ℕ, irrational (x^n) → irrational x | 0 := λ h, (h ⟨1, cast_one⟩).elim | (n+1) := λ h, h.mul_cases.elim id (of_pow n) theorem of_fpow : ∀ m : ℤ, irrational (x^m) → irrational x | (n:ℕ) := of_pow n | -[1+n] := λ h, by { rw fpow_neg_succ_of_nat at h, exact h.of_inv.of_pow _ } end irrational section variables {q : ℚ} {x : ℝ} open irrational @[simp] theorem irrational_rat_add_iff : irrational (q + x) ↔ irrational x := ⟨of_rat_add q, rat_add q⟩ @[simp] theorem irrational_add_rat_iff : irrational (x + q) ↔ irrational x := ⟨of_add_rat q, add_rat q⟩ @[simp] theorem irrational_rat_sub_iff : irrational (q - x) ↔ irrational x := ⟨of_rat_sub q, rat_sub q⟩ @[simp] theorem irrational_sub_rat_iff : irrational (x - q) ↔ irrational x := ⟨of_sub_rat q, sub_rat q⟩ @[simp] theorem irrational_neg_iff : irrational (-x) ↔ irrational x := ⟨of_neg, irrational.neg⟩ @[simp] theorem irrational_inv_iff : irrational x⁻¹ ↔ irrational x := ⟨of_inv, irrational.inv⟩ end
84acba2e663a3d87b18b5d7269b4eacdad3e91ad
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/order/group.lean
c4aac1da2e3f1b333ecbb7e723091c61600fc4e0
[ "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,637
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.order.basic import topology.algebra.group.basic /-! # Topology on a linear ordered additive commutative group > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove that a linear ordered additive commutative group with order topology is a topological group. We also prove continuity of `abs : G → G` and provide convenience lemmas like `continuous_at.abs`. -/ open set filter open_locale topology filter variables {α G : Type*} [topological_space G] [linear_ordered_add_comm_group G] [order_topology G] variables {l : filter α} {f g : α → G} @[priority 100] -- see Note [lower instance priority] instance linear_ordered_add_comm_group.topological_add_group : topological_add_group G := { continuous_add := begin refine continuous_iff_continuous_at.2 _, rintro ⟨a, b⟩, refine linear_ordered_add_comm_group.tendsto_nhds.2 (λ ε ε0, _), rcases dense_or_discrete 0 ε with (⟨δ, δ0, δε⟩|⟨h₁, h₂⟩), { -- If there exists `δ ∈ (0, ε)`, then we choose `δ`-nhd of `a` and `(ε-δ)`-nhd of `b` filter_upwards [(eventually_abs_sub_lt a δ0).prod_nhds (eventually_abs_sub_lt b (sub_pos.2 δε))], rintros ⟨x, y⟩ ⟨hx : |x - a| < δ, hy : |y - b| < ε - δ⟩, rw [add_sub_add_comm], calc |x - a + (y - b)| ≤ |x - a| + |y - b| : abs_add _ _ ... < δ + (ε - δ) : add_lt_add hx hy ... = ε : add_sub_cancel'_right _ _ }, { -- Otherwise `ε`-nhd of each point `a` is `{a}` have hε : ∀ {x y}, |x - y| < ε → x = y, { intros x y h, simpa [sub_eq_zero] using h₂ _ h }, filter_upwards [(eventually_abs_sub_lt a ε0).prod_nhds (eventually_abs_sub_lt b ε0)], rintros ⟨x, y⟩ ⟨hx : |x - a| < ε, hy : |y - b| < ε⟩, simpa [hε hx, hε hy] } end, continuous_neg := continuous_iff_continuous_at.2 $ λ a, linear_ordered_add_comm_group.tendsto_nhds.2 $ λ ε ε0, (eventually_abs_sub_lt a ε0).mono $ λ x hx, by rwa [neg_sub_neg, abs_sub_comm] } @[continuity] lemma continuous_abs : continuous (abs : G → G) := continuous_id.max continuous_neg protected lemma filter.tendsto.abs {a : G} (h : tendsto f l (𝓝 a)) : tendsto (λ x, |f x|) l (𝓝 (|a|)) := (continuous_abs.tendsto _).comp h lemma tendsto_zero_iff_abs_tendsto_zero (f : α → G) : tendsto f l (𝓝 0) ↔ tendsto (abs ∘ f) l (𝓝 0) := begin refine ⟨λ h, (abs_zero : |(0 : G)| = 0) ▸ h.abs, λ h, _⟩, have : tendsto (λ a, -|f a|) l (𝓝 0) := (neg_zero : -(0 : G) = 0) ▸ h.neg, exact tendsto_of_tendsto_of_tendsto_of_le_of_le this h (λ x, neg_abs_le_self $ f x) (λ x, le_abs_self $ f x), end variables [topological_space α] {a : α} {s : set α} protected lemma continuous.abs (h : continuous f) : continuous (λ x, |f x|) := continuous_abs.comp h protected lemma continuous_at.abs (h : continuous_at f a) : continuous_at (λ x, |f x|) a := h.abs protected lemma continuous_within_at.abs (h : continuous_within_at f s a) : continuous_within_at (λ x, |f x|) s a := h.abs protected lemma continuous_on.abs (h : continuous_on f s) : continuous_on (λ x, |f x|) s := λ x hx, (h x hx).abs lemma tendsto_abs_nhds_within_zero : tendsto (abs : G → G) (𝓝[≠] 0) (𝓝[>] 0) := (continuous_abs.tendsto' (0 : G) 0 abs_zero).inf $ tendsto_principal_principal.2 $ λ x, abs_pos.2
8ed714bdd13c59848e9ce3b08b2466d197817af3
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/deBruijn.lean
32c1a5a98bd2ac1db1db103f4dbe6fed0246d310
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,892
lean
inductive HList {α : Type v} (β : α → Type u) : List α → Type (max u v) | nil : HList β [] | cons : β i → HList β is → HList β (i::is) infix:67 " :: " => HList.cons inductive Member : α → List α → Type _ | head : Member a (a::as) | tail : Member a bs → Member a (b::bs) def HList.get : HList β is → Member i is → β i | a::as, .head => a | a::as, .tail h => as.get h inductive Ty where | nat | fn : Ty → Ty → Ty abbrev Ty.denote : Ty → Type | nat => Nat | fn a b => a.denote → b.denote inductive Term : List Ty → Ty → Type | var : Member ty ctx → Term ctx ty | const : Nat → Term ctx .nat | plus : Term ctx .nat → Term ctx .nat → Term ctx .nat | app : Term ctx (.fn dom ran) → Term ctx dom → Term ctx ran | lam : Term (dom :: ctx) ran → Term ctx (.fn dom ran) | «let» : Term ctx ty₁ → Term (ty₁ :: ctx) ty₂ → Term ctx ty₂ @[simp] def Term.denote : Term ctx ty → HList Ty.denote ctx → ty.denote | var h, env => env.get h | const n, _ => n | plus a b, env => a.denote env + b.denote env | app f a, env => f.denote env (a.denote env) | lam b, env => fun x => b.denote (x :: env) | «let» a b, env => b.denote (a.denote env :: env) @[simp] def Term.constFold : Term ctx ty → Term ctx ty | const n => const n | var h => var h | app f a => app f.constFold a.constFold | lam b => lam b.constFold | «let» a b => «let» a.constFold b.constFold | plus a b => match a.constFold, b.constFold with | const n, const m => const (n+m) | a', b' => plus a' b' theorem Term.constFold_sound (e : Term ctx ty) : e.constFold.denote env = e.denote env := by induction e with simp [*] | plus a b iha ihb => split next he₁ he₂ => simp [← iha, ← ihb, he₁, he₂] next => simp [iha, ihb]
3451460928db0c5f13512e23d3eadb84c40aa0f5
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/preserves/shapes.lean
458f9531332f78d8ff7bb3c8d36a0d17e01c1f60
[ "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,526
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.limits.preserves.limits import category_theory.limits.shapes universes v u₁ u₂ noncomputable theory open category_theory category_theory.category category_theory.limits variables {C : Type u₁} [category.{v} C] variables {D : Type u₂} [category.{v} D] variables (G : C ⥤ D) [preserves_limits G] section preserve_products variables {J : Type v} (f : J → C) /-- If `G` preserves limits, we have an isomorphism from the image of a product to the product of the images. -/ -- TODO perhaps weaken the assumptions here, to just require the relevant limits? def preserves_products_iso {J : Type v} (f : J → C) [has_limits C] [has_limits D] : G.obj (pi_obj f) ≅ pi_obj (λ j, G.obj (f j)) := preserves_limit_iso G (discrete.functor f) ≪≫ has_limit.iso_of_nat_iso (discrete.nat_iso (λ j, iso.refl _)) @[simp, reassoc] lemma preserves_products_iso_hom_π {J : Type v} (f : J → C) [has_limits C] [has_limits D] (j) : (preserves_products_iso G f).hom ≫ pi.π _ j = G.map (pi.π f j) := by simp [preserves_products_iso] @[simp, reassoc] lemma map_lift_comp_preserves_products_iso_hom {J : Type v} (f : J → C) [has_limits C] [has_limits D] (P : C) (g : Π j, P ⟶ f j) : G.map (pi.lift g) ≫ (preserves_products_iso G f).hom = pi.lift (λ j, G.map (g j)) := by { ext, simp [←G.map_comp] } end preserve_products
2941a6598801a372335b93088a693f9a877ae7c7
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/set/intervals/ord_connected_component.lean
3c9878d4ef42f06429bfe13c0f92cbb33b1e4392
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
9,238
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import data.set.intervals.ord_connected import tactic.wlog /-! # Order connected components of a set In this file we define `set.ord_connected_component s x` to be the set of `y` such that `set.interval x y ⊆ s` and prove some basic facts about this definition. At the moment of writing, this construction is used only to prove that any linear order with order topology is a T₅ space, so we only add API needed for this lemma. -/ open function order_dual open_locale interval namespace set variables {α : Type*} [linear_order α] {s t : set α} {x y z : α} /-- Order-connected component of a point `x` in a set `s`. It is defined as the set of `y` such that `set.interval x y ⊆ s`. Note that it is empty if and only if `x ∉ s`. -/ def ord_connected_component (s : set α) (x : α) : set α := {y | [x, y] ⊆ s} lemma mem_ord_connected_component : y ∈ ord_connected_component s x ↔ [x, y] ⊆ s := iff.rfl lemma dual_ord_connected_component : ord_connected_component (of_dual ⁻¹' s) (to_dual x) = of_dual ⁻¹' (ord_connected_component s x) := ext $ to_dual.surjective.forall.2 $ λ x, by { rw [mem_ord_connected_component, dual_interval], refl } lemma ord_connected_component_subset : ord_connected_component s x ⊆ s := λ y hy, hy right_mem_interval lemma subset_ord_connected_component {t} [h : ord_connected s] (hs : x ∈ s) (ht : s ⊆ t) : s ⊆ ord_connected_component t x := λ y hy, (h.interval_subset hs hy).trans ht @[simp] lemma self_mem_ord_connected_component : x ∈ ord_connected_component s x ↔ x ∈ s := by rw [mem_ord_connected_component, interval_self, singleton_subset_iff] @[simp] lemma nonempty_ord_connected_component : (ord_connected_component s x).nonempty ↔ x ∈ s := ⟨λ ⟨y, hy⟩, hy $ left_mem_interval, λ h, ⟨x, self_mem_ord_connected_component.2 h⟩⟩ @[simp] lemma ord_connected_component_eq_empty : ord_connected_component s x = ∅ ↔ x ∉ s := by rw [← not_nonempty_iff_eq_empty, nonempty_ord_connected_component] @[simp] lemma ord_connected_component_empty : ord_connected_component ∅ x = ∅ := ord_connected_component_eq_empty.2 (not_mem_empty x) @[simp] lemma ord_connected_component_univ : ord_connected_component univ x = univ := by simp [ord_connected_component] lemma ord_connected_component_inter (s t : set α) (x : α) : ord_connected_component (s ∩ t) x = ord_connected_component s x ∩ ord_connected_component t x := by simp [ord_connected_component, set_of_and] lemma mem_ord_connected_component_comm : y ∈ ord_connected_component s x ↔ x ∈ ord_connected_component s y := by rw [mem_ord_connected_component, mem_ord_connected_component, interval_swap] lemma mem_ord_connected_component_trans (hxy : y ∈ ord_connected_component s x) (hyz : z ∈ ord_connected_component s y) : z ∈ ord_connected_component s x := calc [x, z] ⊆ [x, y] ∪ [y, z] : interval_subset_interval_union_interval ... ⊆ s : union_subset hxy hyz lemma ord_connected_component_eq (h : [x, y] ⊆ s) : ord_connected_component s x = ord_connected_component s y := ext $ λ z, ⟨mem_ord_connected_component_trans (mem_ord_connected_component_comm.2 h), mem_ord_connected_component_trans h⟩ instance : ord_connected (ord_connected_component s x) := ord_connected_of_interval_subset_left $ λ y hy z hz, (interval_subset_interval_left hz).trans hy /-- Projection from `s : set α` to `α` sending each order connected component of `s` to a single point of this component. -/ noncomputable def ord_connected_proj (s : set α) : s → α := λ x : s, (nonempty_ord_connected_component.2 x.prop).some lemma ord_connected_proj_mem_ord_connected_component (s : set α) (x : s) : ord_connected_proj s x ∈ ord_connected_component s x := nonempty.some_mem _ lemma mem_ord_connected_component_ord_connected_proj (s : set α) (x : s) : ↑x ∈ ord_connected_component s (ord_connected_proj s x) := mem_ord_connected_component_comm.2 $ ord_connected_proj_mem_ord_connected_component s x @[simp] lemma ord_connected_component_ord_connected_proj (s : set α) (x : s) : ord_connected_component s (ord_connected_proj s x) = ord_connected_component s x := ord_connected_component_eq $ mem_ord_connected_component_ord_connected_proj _ _ @[simp] lemma ord_connected_proj_eq {x y : s} : ord_connected_proj s x = ord_connected_proj s y ↔ [(x : α), y] ⊆ s := begin split; intro h, { rw [← mem_ord_connected_component, ← ord_connected_component_ord_connected_proj, h, ord_connected_component_ord_connected_proj, self_mem_ord_connected_component], exact y.2 }, { simp only [ord_connected_proj], congr' 1, exact ord_connected_component_eq h } end /-- A set that intersects each order connected component of a set by a single point. Defined as the range of `set.ord_connected_proj s`. -/ def ord_connected_section (s : set α) : set α := range $ ord_connected_proj s lemma dual_ord_connected_section (s : set α) : ord_connected_section (of_dual ⁻¹' s) = of_dual ⁻¹' (ord_connected_section s) := begin simp only [ord_connected_section, ord_connected_proj], congr' 1 with x, simp only, congr' 1, exact dual_ord_connected_component end lemma ord_connected_section_subset : ord_connected_section s ⊆ s := range_subset_iff.2 $ λ x, ord_connected_component_subset $ nonempty.some_mem _ lemma eq_of_mem_ord_connected_section_of_interval_subset (hx : x ∈ ord_connected_section s) (hy : y ∈ ord_connected_section s) (h : [x, y] ⊆ s) : x = y := begin rcases hx with ⟨x, rfl⟩, rcases hy with ⟨y, rfl⟩, exact ord_connected_proj_eq.2 (mem_ord_connected_component_trans (mem_ord_connected_component_trans (ord_connected_proj_mem_ord_connected_component _ _) h) (mem_ord_connected_component_ord_connected_proj _ _)) end /-- Given two sets `s t : set α`, the set `set.order_separating_set s t` is the set of points that belong both to some `set.ord_connected_component tᶜ x`, `x ∈ s`, and to some `set.ord_connected_component sᶜ x`, `x ∈ t`. In the case of two disjoint closed sets, this is the union of all open intervals $(a, b)$ such that their endpoints belong to different sets. -/ def ord_separating_set (s t : set α) : set α := (⋃ x ∈ s, ord_connected_component tᶜ x) ∩ (⋃ x ∈ t, ord_connected_component sᶜ x) lemma ord_separating_set_comm (s t : set α) : ord_separating_set s t = ord_separating_set t s := inter_comm _ _ lemma disjoint_left_ord_separating_set : disjoint s (ord_separating_set s t) := disjoint.inter_right' _ $ disjoint_Union₂_right.2 $ λ x hx, disjoint_compl_right.mono_right $ ord_connected_component_subset lemma disjoint_right_ord_separating_set : disjoint t (ord_separating_set s t) := ord_separating_set_comm t s ▸ disjoint_left_ord_separating_set lemma dual_ord_separating_set : ord_separating_set (of_dual ⁻¹' s) (of_dual ⁻¹' t) = of_dual ⁻¹' (ord_separating_set s t) := by simp only [ord_separating_set, mem_preimage, ← to_dual.surjective.Union_comp, of_dual_to_dual, dual_ord_connected_component, ← preimage_compl, preimage_inter, preimage_Union] /-- An auxiliary neighborhood that will be used in the proof of `order_topology.t5_space`. -/ def ord_t5_nhd (s t : set α) : set α := ⋃ x ∈ s, ord_connected_component (tᶜ ∩ (ord_connected_section $ ord_separating_set s t)ᶜ) x lemma disjoint_ord_t5_nhd : disjoint (ord_t5_nhd s t) (ord_t5_nhd t s) := begin rw disjoint_iff_inf_le, rintro x ⟨hx₁, hx₂⟩, rcases mem_Union₂.1 hx₁ with ⟨a, has, ha⟩, clear hx₁, rcases mem_Union₂.1 hx₂ with ⟨b, hbt, hb⟩, clear hx₂, rw [mem_ord_connected_component, subset_inter_iff] at ha hb, wlog hab : a ≤ b := le_total a b using [a b s t, b a t s] tactic.skip, rotate, from λ h₁ h₂ h₃ h₄, this h₂ h₁ h₄ h₃, cases ha with ha ha', cases hb with hb hb', have hsub : [a, b] ⊆ (ord_separating_set s t).ord_connected_sectionᶜ, { rw [ord_separating_set_comm, interval_swap] at hb', calc [a, b] ⊆ [a, x] ∪ [x, b] : interval_subset_interval_union_interval ... ⊆ (ord_separating_set s t).ord_connected_sectionᶜ : union_subset ha' hb' }, clear ha' hb', cases le_total x a with hxa hax, { exact hb (Icc_subset_interval' ⟨hxa, hab⟩) has }, cases le_total b x with hbx hxb, { exact ha (Icc_subset_interval ⟨hab, hbx⟩) hbt }, have : x ∈ ord_separating_set s t, { exact ⟨mem_Union₂.2 ⟨a, has, ha⟩, mem_Union₂.2 ⟨b, hbt, hb⟩⟩ }, lift x to ord_separating_set s t using this, suffices : ord_connected_component (ord_separating_set s t) x ⊆ [a, b], from hsub (this $ ord_connected_proj_mem_ord_connected_component _ _) (mem_range_self _), rintros y (hy : [↑x, y] ⊆ ord_separating_set s t), rw [interval_of_le hab, mem_Icc, ← not_lt, ← not_lt], exact ⟨λ hya, disjoint_left.1 disjoint_left_ord_separating_set has (hy $ Icc_subset_interval' ⟨hya.le, hax⟩), λ hyb, disjoint_left.1 disjoint_right_ord_separating_set hbt (hy $ Icc_subset_interval ⟨hxb, hyb.le⟩)⟩ end end set
043d84a6876eb4887836581c79f200fb61d0fa28
4727251e0cd73359b15b664c3170e5d754078599
/src/data/real/nnreal.lean
e66e36994532deb94b01afa1c0437bd53f097633
[ "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
31,344
lean
/- Copyright (c) 2018 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import algebra.big_operators.ring import data.real.basic import algebra.indicator_function import algebra.algebra.basic import algebra.order.nonneg /-! # Nonnegative real numbers In this file we define `nnreal` (notation: `ℝ≥0`) to be the type of non-negative real numbers, a.k.a. the interval `[0, ∞)`. We also define the following operations and structures on `ℝ≥0`: * the order on `ℝ≥0` is the restriction of the order on `ℝ`; these relations define a conditionally complete linear order with a bottom element, `conditionally_complete_linear_order_bot`; * `a + b` and `a * b` are the restrictions of addition and multiplication of real numbers to `ℝ≥0`; these operations together with `0 = ⟨0, _⟩` and `1 = ⟨1, _⟩` turn `ℝ≥0` into a conditionally complete linear ordered archimedean commutative semifield; we have no typeclass for this in `mathlib` yet, so we define the following instances instead: - `linear_ordered_semiring ℝ≥0`; - `ordered_comm_semiring ℝ≥0`; - `canonically_ordered_comm_semiring ℝ≥0`; - `linear_ordered_comm_group_with_zero ℝ≥0`; - `canonically_linear_ordered_add_monoid ℝ≥0`; - `archimedean ℝ≥0`; - `conditionally_complete_linear_order_bot ℝ≥0`. These instances are derived from corresponding instances about the type `{x : α // 0 ≤ x}` in an appropriate ordered field/ring/group/monoid `α`. See `algebra/order/nonneg`. * `real.to_nnreal x` is defined as `⟨max x 0, _⟩`, i.e. `↑(real.to_nnreal x) = x` when `0 ≤ x` and `↑(real.to_nnreal x) = 0` otherwise. We also define an instance `can_lift ℝ ℝ≥0`. This instance can be used by the `lift` tactic to replace `x : ℝ` and `hx : 0 ≤ x` in the proof context with `x : ℝ≥0` while replacing all occurences of `x` with `↑x`. This tactic also works for a function `f : α → ℝ` with a hypothesis `hf : ∀ x, 0 ≤ f x`. ## Notations This file defines `ℝ≥0` as a localized notation for `nnreal`. -/ open_locale classical big_operators /-- Nonnegative real numbers. -/ @[derive [ ordered_semiring, comm_monoid_with_zero, -- to ensure these instance are computable floor_semiring, semilattice_inf, densely_ordered, order_bot, canonically_linear_ordered_add_monoid, linear_ordered_comm_group_with_zero, archimedean, linear_ordered_semiring, ordered_comm_semiring, canonically_ordered_comm_semiring, has_sub, has_ordered_sub, has_div, inhabited]] def nnreal := {r : ℝ // 0 ≤ r} localized "notation ` ℝ≥0 ` := nnreal" in nnreal namespace nnreal instance : has_coe ℝ≥0 ℝ := ⟨subtype.val⟩ /- Simp lemma to put back `n.val` into the normal form given by the coercion. -/ @[simp] lemma val_eq_coe (n : ℝ≥0) : n.val = n := rfl instance : can_lift ℝ ℝ≥0 := { coe := coe, cond := λ r, 0 ≤ r, prf := λ x hx, ⟨⟨x, hx⟩, rfl⟩ } protected lemma eq {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) → n = m := subtype.eq protected lemma eq_iff {n m : ℝ≥0} : (n : ℝ) = (m : ℝ) ↔ n = m := iff.intro nnreal.eq (congr_arg coe) lemma ne_iff {x y : ℝ≥0} : (x : ℝ) ≠ (y : ℝ) ↔ x ≠ y := not_iff_not_of_iff $ nnreal.eq_iff protected lemma «forall» {p : ℝ≥0 → Prop} : (∀ x : ℝ≥0, p x) ↔ ∀ (x : ℝ) (hx : 0 ≤ x), p ⟨x, hx⟩ := subtype.forall protected lemma «exists» {p : ℝ≥0 → Prop} : (∃ x : ℝ≥0, p x) ↔ ∃ (x : ℝ) (hx : 0 ≤ x), p ⟨x, hx⟩ := subtype.exists /-- Reinterpret a real number `r` as a non-negative real number. Returns `0` if `r < 0`. -/ noncomputable def _root_.real.to_nnreal (r : ℝ) : ℝ≥0 := ⟨max r 0, le_max_right _ _⟩ lemma _root_.real.coe_to_nnreal (r : ℝ) (hr : 0 ≤ r) : (real.to_nnreal r : ℝ) = r := max_eq_left hr lemma _root_.real.le_coe_to_nnreal (r : ℝ) : r ≤ real.to_nnreal r := le_max_left r 0 lemma coe_nonneg (r : ℝ≥0) : (0 : ℝ) ≤ r := r.2 @[norm_cast] theorem coe_mk (a : ℝ) (ha) : ((⟨a, ha⟩ : ℝ≥0) : ℝ) = a := rfl example : has_zero ℝ≥0 := by apply_instance example : has_one ℝ≥0 := by apply_instance example : has_add ℝ≥0 := by apply_instance noncomputable example : has_sub ℝ≥0 := by apply_instance example : has_mul ℝ≥0 := by apply_instance noncomputable example : has_inv ℝ≥0 := by apply_instance noncomputable example : has_div ℝ≥0 := by apply_instance example : has_le ℝ≥0 := by apply_instance example : has_bot ℝ≥0 := by apply_instance example : inhabited ℝ≥0 := by apply_instance example : nontrivial ℝ≥0 := by apply_instance protected lemma coe_injective : function.injective (coe : ℝ≥0 → ℝ) := subtype.coe_injective @[simp, norm_cast] protected lemma coe_eq {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) = r₂ ↔ r₁ = r₂ := nnreal.coe_injective.eq_iff protected lemma coe_zero : ((0 : ℝ≥0) : ℝ) = 0 := rfl protected lemma coe_one : ((1 : ℝ≥0) : ℝ) = 1 := rfl protected lemma coe_add (r₁ r₂ : ℝ≥0) : ((r₁ + r₂ : ℝ≥0) : ℝ) = r₁ + r₂ := rfl protected lemma coe_mul (r₁ r₂ : ℝ≥0) : ((r₁ * r₂ : ℝ≥0) : ℝ) = r₁ * r₂ := rfl protected lemma coe_inv (r : ℝ≥0) : ((r⁻¹ : ℝ≥0) : ℝ) = r⁻¹ := rfl protected lemma coe_div (r₁ r₂ : ℝ≥0) : ((r₁ / r₂ : ℝ≥0) : ℝ) = r₁ / r₂ := rfl @[simp, norm_cast] protected lemma coe_bit0 (r : ℝ≥0) : ((bit0 r : ℝ≥0) : ℝ) = bit0 r := rfl @[simp, norm_cast] protected lemma coe_bit1 (r : ℝ≥0) : ((bit1 r : ℝ≥0) : ℝ) = bit1 r := rfl @[simp, norm_cast] protected lemma coe_sub {r₁ r₂ : ℝ≥0} (h : r₂ ≤ r₁) : ((r₁ - r₂ : ℝ≥0) : ℝ) = r₁ - r₂ := max_eq_left $ le_sub.2 $ by simp [show (r₂ : ℝ) ≤ r₁, from h] -- TODO: setup semifield! @[simp, norm_cast] protected lemma coe_eq_zero (r : ℝ≥0) : ↑r = (0 : ℝ) ↔ r = 0 := by rw [← nnreal.coe_zero, nnreal.coe_eq] @[simp, norm_cast] protected lemma coe_eq_one (r : ℝ≥0) : ↑r = (1 : ℝ) ↔ r = 1 := by rw [← nnreal.coe_one, nnreal.coe_eq] lemma coe_ne_zero {r : ℝ≥0} : (r : ℝ) ≠ 0 ↔ r ≠ 0 := by norm_cast example : comm_semiring ℝ≥0 := by apply_instance /-- Coercion `ℝ≥0 → ℝ` as a `ring_hom`. -/ def to_real_hom : ℝ≥0 →+* ℝ := ⟨coe, nnreal.coe_one, nnreal.coe_mul, nnreal.coe_zero, nnreal.coe_add⟩ @[simp] lemma coe_to_real_hom : ⇑to_real_hom = coe := rfl section actions /-- A `mul_action` over `ℝ` restricts to a `mul_action` over `ℝ≥0`. -/ instance {M : Type*} [mul_action ℝ M] : mul_action ℝ≥0 M := mul_action.comp_hom M to_real_hom.to_monoid_hom lemma smul_def {M : Type*} [mul_action ℝ M] (c : ℝ≥0) (x : M) : c • x = (c : ℝ) • x := rfl instance {M N : Type*} [mul_action ℝ M] [mul_action ℝ N] [has_scalar M N] [is_scalar_tower ℝ M N] : is_scalar_tower ℝ≥0 M N := { smul_assoc := λ r, (smul_assoc (r : ℝ) : _)} instance smul_comm_class_left {M N : Type*} [mul_action ℝ N] [has_scalar M N] [smul_comm_class ℝ M N] : smul_comm_class ℝ≥0 M N := { smul_comm := λ r, (smul_comm (r : ℝ) : _)} instance smul_comm_class_right {M N : Type*} [mul_action ℝ N] [has_scalar M N] [smul_comm_class M ℝ N] : smul_comm_class M ℝ≥0 N := { smul_comm := λ m r, (smul_comm m (r : ℝ) : _)} /-- A `distrib_mul_action` over `ℝ` restricts to a `distrib_mul_action` over `ℝ≥0`. -/ instance {M : Type*} [add_monoid M] [distrib_mul_action ℝ M] : distrib_mul_action ℝ≥0 M := distrib_mul_action.comp_hom M to_real_hom.to_monoid_hom /-- A `module` over `ℝ` restricts to a `module` over `ℝ≥0`. -/ instance {M : Type*} [add_comm_monoid M] [module ℝ M] : module ℝ≥0 M := module.comp_hom M to_real_hom /-- An `algebra` over `ℝ` restricts to an `algebra` over `ℝ≥0`. -/ instance {A : Type*} [semiring A] [algebra ℝ A] : algebra ℝ≥0 A := { smul := (•), commutes' := λ r x, by simp [algebra.commutes], smul_def' := λ r x, by simp [←algebra.smul_def (r : ℝ) x, smul_def], to_ring_hom := ((algebra_map ℝ A).comp (to_real_hom : ℝ≥0 →+* ℝ)) } -- verify that the above produces instances we might care about example : algebra ℝ≥0 ℝ := by apply_instance example : distrib_mul_action ℝ≥0ˣ ℝ := by apply_instance end actions example : monoid_with_zero ℝ≥0 := by apply_instance example : comm_monoid_with_zero ℝ≥0 := by apply_instance noncomputable example : comm_group_with_zero ℝ≥0 := by apply_instance @[simp, norm_cast] lemma coe_indicator {α} (s : set α) (f : α → ℝ≥0) (a : α) : ((s.indicator f a : ℝ≥0) : ℝ) = s.indicator (λ x, f x) a := (to_real_hom : ℝ≥0 →+ ℝ).map_indicator _ _ _ @[simp, norm_cast] lemma coe_pow (r : ℝ≥0) (n : ℕ) : ((r^n : ℝ≥0) : ℝ) = r^n := to_real_hom.map_pow r n @[simp, norm_cast] lemma coe_zpow (r : ℝ≥0) (n : ℤ) : ((r^n : ℝ≥0) : ℝ) = r^n := by cases n; simp @[norm_cast] lemma coe_list_sum (l : list ℝ≥0) : ((l.sum : ℝ≥0) : ℝ) = (l.map coe).sum := to_real_hom.map_list_sum l @[norm_cast] lemma coe_list_prod (l : list ℝ≥0) : ((l.prod : ℝ≥0) : ℝ) = (l.map coe).prod := to_real_hom.map_list_prod l @[norm_cast] lemma coe_multiset_sum (s : multiset ℝ≥0) : ((s.sum : ℝ≥0) : ℝ) = (s.map coe).sum := to_real_hom.map_multiset_sum s @[norm_cast] lemma coe_multiset_prod (s : multiset ℝ≥0) : ((s.prod : ℝ≥0) : ℝ) = (s.map coe).prod := to_real_hom.map_multiset_prod s @[norm_cast] lemma coe_sum {α} {s : finset α} {f : α → ℝ≥0} : ↑(∑ a in s, f a) = ∑ a in s, (f a : ℝ) := to_real_hom.map_sum _ _ lemma _root_.real.to_nnreal_sum_of_nonneg {α} {s : finset α} {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : real.to_nnreal (∑ a in s, f a) = ∑ a in s, real.to_nnreal (f a) := begin rw [←nnreal.coe_eq, nnreal.coe_sum, real.coe_to_nnreal _ (finset.sum_nonneg hf)], exact finset.sum_congr rfl (λ x hxs, by rw real.coe_to_nnreal _ (hf x hxs)), end @[norm_cast] lemma coe_prod {α} {s : finset α} {f : α → ℝ≥0} : ↑(∏ a in s, f a) = ∏ a in s, (f a : ℝ) := to_real_hom.map_prod _ _ lemma _root_.real.to_nnreal_prod_of_nonneg {α} {s : finset α} {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : real.to_nnreal (∏ a in s, f a) = ∏ a in s, real.to_nnreal (f a) := begin rw [←nnreal.coe_eq, nnreal.coe_prod, real.coe_to_nnreal _ (finset.prod_nonneg hf)], exact finset.prod_congr rfl (λ x hxs, by rw real.coe_to_nnreal _ (hf x hxs)), end lemma nsmul_coe (r : ℝ≥0) (n : ℕ) : ↑(n • r) = n • (r:ℝ) := by norm_cast @[simp, norm_cast] protected lemma coe_nat_cast (n : ℕ) : (↑(↑n : ℝ≥0) : ℝ) = n := map_nat_cast to_real_hom n noncomputable example : linear_order ℝ≥0 := by apply_instance @[simp, norm_cast] protected lemma coe_le_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) ≤ r₂ ↔ r₁ ≤ r₂ := iff.rfl @[simp, norm_cast] protected lemma coe_lt_coe {r₁ r₂ : ℝ≥0} : (r₁ : ℝ) < r₂ ↔ r₁ < r₂ := iff.rfl @[simp, norm_cast] protected lemma coe_pos {r : ℝ≥0} : (0 : ℝ) < r ↔ 0 < r := iff.rfl protected lemma coe_mono : monotone (coe : ℝ≥0 → ℝ) := λ _ _, nnreal.coe_le_coe.2 protected lemma _root_.real.to_nnreal_mono : monotone real.to_nnreal := λ x y h, max_le_max h (le_refl 0) @[simp] lemma _root_.real.to_nnreal_coe {r : ℝ≥0} : real.to_nnreal r = r := nnreal.eq $ max_eq_left r.2 @[simp] lemma mk_coe_nat (n : ℕ) : @eq ℝ≥0 (⟨(n : ℝ), n.cast_nonneg⟩ : ℝ≥0) n := nnreal.eq (nnreal.coe_nat_cast n).symm @[simp] lemma to_nnreal_coe_nat (n : ℕ) : real.to_nnreal n = n := nnreal.eq $ by simp [real.coe_to_nnreal] /-- `real.to_nnreal` and `coe : ℝ≥0 → ℝ` form a Galois insertion. -/ noncomputable def gi : galois_insertion real.to_nnreal coe := galois_insertion.monotone_intro nnreal.coe_mono real.to_nnreal_mono real.le_coe_to_nnreal (λ _, real.to_nnreal_coe) -- note that anything involving the (decidability of the) linear order, including `⊔`/`⊓` (min, max) -- will be noncomputable, everything else should not be. example : order_bot ℝ≥0 := by apply_instance example : partial_order ℝ≥0 := by apply_instance noncomputable example : canonically_linear_ordered_add_monoid ℝ≥0 := by apply_instance noncomputable example : linear_ordered_add_comm_monoid ℝ≥0 := by apply_instance noncomputable example : distrib_lattice ℝ≥0 := by apply_instance noncomputable example : semilattice_inf ℝ≥0 := by apply_instance noncomputable example : semilattice_sup ℝ≥0 := by apply_instance noncomputable example : linear_ordered_semiring ℝ≥0 := by apply_instance example : ordered_comm_semiring ℝ≥0 := by apply_instance noncomputable example : linear_ordered_comm_monoid ℝ≥0 := by apply_instance noncomputable example : linear_ordered_comm_monoid_with_zero ℝ≥0 := by apply_instance noncomputable example : linear_ordered_comm_group_with_zero ℝ≥0 := by apply_instance example : canonically_ordered_comm_semiring ℝ≥0 := by apply_instance example : densely_ordered ℝ≥0 := by apply_instance example : no_max_order ℝ≥0 := by apply_instance -- note we need the `@` to make the `has_mem.mem` have a sensible type lemma coe_image {s : set ℝ≥0} : coe '' s = {x : ℝ | ∃ h : 0 ≤ x, @has_mem.mem (ℝ≥0) _ _ ⟨x, h⟩ s} := subtype.coe_image lemma bdd_above_coe {s : set ℝ≥0} : bdd_above ((coe : ℝ≥0 → ℝ) '' s) ↔ bdd_above s := iff.intro (assume ⟨b, hb⟩, ⟨real.to_nnreal b, assume ⟨y, hy⟩ hys, show y ≤ max b 0, from le_max_of_le_left $ hb $ set.mem_image_of_mem _ hys⟩) (assume ⟨b, hb⟩, ⟨b, assume y ⟨x, hx, eq⟩, eq ▸ hb hx⟩) lemma bdd_below_coe (s : set ℝ≥0) : bdd_below ((coe : ℝ≥0 → ℝ) '' s) := ⟨0, assume r ⟨q, _, eq⟩, eq ▸ q.2⟩ noncomputable instance : conditionally_complete_linear_order_bot ℝ≥0 := nonneg.conditionally_complete_linear_order_bot real.Sup_empty.le @[norm_cast] lemma coe_Sup (s : set ℝ≥0) : (↑(Sup s) : ℝ) = Sup ((coe : ℝ≥0 → ℝ) '' s) := eq.symm $ @subset_Sup_of_within ℝ (set.Ici 0) _ ⟨(0 : ℝ≥0)⟩ s $ real.Sup_nonneg _ $ λ y ⟨x, _, hy⟩, hy ▸ x.2 @[norm_cast] lemma coe_supr {ι : Sort*} (s : ι → ℝ≥0) : (↑(⨆ i, s i) : ℝ) = ⨆ i, (s i) := by rw [supr, supr, coe_Sup, set.range_comp] @[norm_cast] lemma coe_Inf (s : set ℝ≥0) : (↑(Inf s) : ℝ) = Inf ((coe : ℝ≥0 → ℝ) '' s) := eq.symm $ @subset_Inf_of_within ℝ (set.Ici 0) _ ⟨(0 : ℝ≥0)⟩ s $ real.Inf_nonneg _ $ λ y ⟨x, _, hy⟩, hy ▸ x.2 @[norm_cast] lemma coe_infi {ι : Sort*} (s : ι → ℝ≥0) : (↑(⨅ i, s i) : ℝ) = ⨅ i, (s i) := by rw [infi, infi, coe_Inf, set.range_comp] example : archimedean ℝ≥0 := by apply_instance -- TODO: why are these three instances necessary? why aren't they inferred? instance covariant_add : covariant_class ℝ≥0 ℝ≥0 (+) (≤) := ordered_add_comm_monoid.to_covariant_class_left ℝ≥0 instance contravariant_add : contravariant_class ℝ≥0 ℝ≥0 (+) (<) := ordered_cancel_add_comm_monoid.to_contravariant_class_left ℝ≥0 instance covariant_mul : covariant_class ℝ≥0 ℝ≥0 (*) (≤) := ordered_comm_monoid.to_covariant_class_left ℝ≥0 lemma le_of_forall_pos_le_add {a b : ℝ≥0} (h : ∀ε, 0 < ε → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ assume x hxb, begin rcases le_iff_exists_add.1 (le_of_lt hxb) with ⟨ε, rfl⟩, exact h _ ((lt_add_iff_pos_right b).1 hxb) end -- TODO: generalize to some ordered add_monoids, based on #6145 lemma le_of_add_le_left {a b c : ℝ≥0} (h : a + b ≤ c) : a ≤ c := by { refine le_trans _ h, exact (le_add_iff_nonneg_right _).mpr zero_le' } lemma le_of_add_le_right {a b c : ℝ≥0} (h : a + b ≤ c) : b ≤ c := by { refine le_trans _ h, exact (le_add_iff_nonneg_left _).mpr zero_le' } lemma lt_iff_exists_rat_btwn (a b : ℝ≥0) : a < b ↔ (∃q:ℚ, 0 ≤ q ∧ a < real.to_nnreal q ∧ real.to_nnreal q < b) := iff.intro (assume (h : (↑a:ℝ) < (↑b:ℝ)), let ⟨q, haq, hqb⟩ := exists_rat_btwn h in have 0 ≤ (q : ℝ), from le_trans a.2 $ le_of_lt haq, ⟨q, rat.cast_nonneg.1 this, by simp [real.coe_to_nnreal _ this, nnreal.coe_lt_coe.symm, haq, hqb]⟩) (assume ⟨q, _, haq, hqb⟩, lt_trans haq hqb) lemma bot_eq_zero : (⊥ : ℝ≥0) = 0 := rfl lemma mul_sup (a b c : ℝ≥0) : a * (b ⊔ c) = (a * b) ⊔ (a * c) := mul_max_of_nonneg _ _ $ zero_le a lemma sup_mul (a b c : ℝ≥0) : (a ⊔ b) * c = (a * c) ⊔ (b * c) := max_mul_of_nonneg _ _ $ zero_le c lemma mul_finset_sup {α} (r : ℝ≥0) (s : finset α) (f : α → ℝ≥0) : r * s.sup f = s.sup (λ a, r * f a) := (finset.comp_sup_eq_sup_comp _ (nnreal.mul_sup r) (mul_zero r)) lemma finset_sup_mul {α} (s : finset α) (f : α → ℝ≥0) (r : ℝ≥0) : s.sup f * r = s.sup (λ a, f a * r) := (finset.comp_sup_eq_sup_comp (* r) (λ x y, nnreal.sup_mul x y r) (zero_mul r)) lemma finset_sup_div {α} {f : α → ℝ≥0} {s : finset α} (r : ℝ≥0) : s.sup f / r = s.sup (λ a, f a / r) := by simp only [div_eq_inv_mul, mul_finset_sup] @[simp, norm_cast] lemma coe_max (x y : ℝ≥0) : ((max x y : ℝ≥0) : ℝ) = max (x : ℝ) (y : ℝ) := nnreal.coe_mono.map_max @[simp, norm_cast] lemma coe_min (x y : ℝ≥0) : ((min x y : ℝ≥0) : ℝ) = min (x : ℝ) (y : ℝ) := nnreal.coe_mono.map_min @[simp] lemma zero_le_coe {q : ℝ≥0} : 0 ≤ (q : ℝ) := q.2 end nnreal namespace real section to_nnreal @[simp] lemma to_nnreal_zero : real.to_nnreal 0 = 0 := by simp [real.to_nnreal]; refl @[simp] lemma to_nnreal_one : real.to_nnreal 1 = 1 := by simp [real.to_nnreal, max_eq_left (zero_le_one : (0 :ℝ) ≤ 1)]; refl @[simp] lemma to_nnreal_pos {r : ℝ} : 0 < real.to_nnreal r ↔ 0 < r := by simp [real.to_nnreal, nnreal.coe_lt_coe.symm, lt_irrefl] @[simp] lemma to_nnreal_eq_zero {r : ℝ} : real.to_nnreal r = 0 ↔ r ≤ 0 := by simpa [-to_nnreal_pos] using (not_iff_not.2 (@to_nnreal_pos r)) lemma to_nnreal_of_nonpos {r : ℝ} : r ≤ 0 → real.to_nnreal r = 0 := to_nnreal_eq_zero.2 @[simp] lemma coe_to_nnreal' (r : ℝ) : (real.to_nnreal r : ℝ) = max r 0 := rfl @[simp] lemma to_nnreal_le_to_nnreal_iff {r p : ℝ} (hp : 0 ≤ p) : real.to_nnreal r ≤ real.to_nnreal p ↔ r ≤ p := by simp [nnreal.coe_le_coe.symm, real.to_nnreal, hp] @[simp] lemma to_nnreal_lt_to_nnreal_iff' {r p : ℝ} : real.to_nnreal r < real.to_nnreal p ↔ r < p ∧ 0 < p := nnreal.coe_lt_coe.symm.trans max_lt_max_left_iff lemma to_nnreal_lt_to_nnreal_iff {r p : ℝ} (h : 0 < p) : real.to_nnreal r < real.to_nnreal p ↔ r < p := to_nnreal_lt_to_nnreal_iff'.trans (and_iff_left h) lemma to_nnreal_lt_to_nnreal_iff_of_nonneg {r p : ℝ} (hr : 0 ≤ r) : real.to_nnreal r < real.to_nnreal p ↔ r < p := to_nnreal_lt_to_nnreal_iff'.trans ⟨and.left, λ h, ⟨h, lt_of_le_of_lt hr h⟩⟩ @[simp] lemma to_nnreal_add {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : real.to_nnreal (r + p) = real.to_nnreal r + real.to_nnreal p := nnreal.eq $ by simp [real.to_nnreal, hr, hp, add_nonneg] lemma to_nnreal_add_to_nnreal {r p : ℝ} (hr : 0 ≤ r) (hp : 0 ≤ p) : real.to_nnreal r + real.to_nnreal p = real.to_nnreal (r + p) := (real.to_nnreal_add hr hp).symm lemma to_nnreal_le_to_nnreal {r p : ℝ} (h : r ≤ p) : real.to_nnreal r ≤ real.to_nnreal p := real.to_nnreal_mono h lemma to_nnreal_add_le {r p : ℝ} : real.to_nnreal (r + p) ≤ real.to_nnreal r + real.to_nnreal p := nnreal.coe_le_coe.1 $ max_le (add_le_add (le_max_left _ _) (le_max_left _ _)) nnreal.zero_le_coe lemma to_nnreal_le_iff_le_coe {r : ℝ} {p : ℝ≥0} : real.to_nnreal r ≤ p ↔ r ≤ ↑p := nnreal.gi.gc r p lemma le_to_nnreal_iff_coe_le {r : ℝ≥0} {p : ℝ} (hp : 0 ≤ p) : r ≤ real.to_nnreal p ↔ ↑r ≤ p := by rw [← nnreal.coe_le_coe, real.coe_to_nnreal p hp] lemma le_to_nnreal_iff_coe_le' {r : ℝ≥0} {p : ℝ} (hr : 0 < r) : r ≤ real.to_nnreal p ↔ ↑r ≤ p := (le_or_lt 0 p).elim le_to_nnreal_iff_coe_le $ λ hp, by simp only [(hp.trans_le r.coe_nonneg).not_le, to_nnreal_eq_zero.2 hp.le, hr.not_le] lemma to_nnreal_lt_iff_lt_coe {r : ℝ} {p : ℝ≥0} (ha : 0 ≤ r) : real.to_nnreal r < p ↔ r < ↑p := by rw [← nnreal.coe_lt_coe, real.coe_to_nnreal r ha] lemma lt_to_nnreal_iff_coe_lt {r : ℝ≥0} {p : ℝ} : r < real.to_nnreal p ↔ ↑r < p := begin cases le_total 0 p, { rw [← nnreal.coe_lt_coe, real.coe_to_nnreal p h] }, { rw [to_nnreal_eq_zero.2 h], split, { intro, have := not_lt_of_le (zero_le r), contradiction }, { intro rp, have : ¬(p ≤ 0) := not_le_of_lt (lt_of_le_of_lt (nnreal.coe_nonneg _) rp), contradiction } } end @[simp] lemma to_nnreal_bit0 {r : ℝ} (hr : 0 ≤ r) : real.to_nnreal (bit0 r) = bit0 (real.to_nnreal r) := real.to_nnreal_add hr hr @[simp] lemma to_nnreal_bit1 {r : ℝ} (hr : 0 ≤ r) : real.to_nnreal (bit1 r) = bit1 (real.to_nnreal r) := (real.to_nnreal_add (by simp [hr]) zero_le_one).trans (by simp [to_nnreal_one, bit1, hr]) end to_nnreal end real open real namespace nnreal section mul lemma mul_eq_mul_left {a b c : ℝ≥0} (h : a ≠ 0) : (a * b = a * c ↔ b = c) := begin rw [← nnreal.eq_iff, ← nnreal.eq_iff, nnreal.coe_mul, nnreal.coe_mul], split, { exact mul_left_cancel₀ (mt (@nnreal.eq_iff a 0).1 h) }, { assume h, rw [h] } end lemma _root_.real.to_nnreal_mul {p q : ℝ} (hp : 0 ≤ p) : real.to_nnreal (p * q) = real.to_nnreal p * real.to_nnreal q := begin cases le_total 0 q with hq hq, { apply nnreal.eq, simp [real.to_nnreal, hp, hq, max_eq_left, mul_nonneg] }, { have hpq := mul_nonpos_of_nonneg_of_nonpos hp hq, rw [to_nnreal_eq_zero.2 hq, to_nnreal_eq_zero.2 hpq, mul_zero] } end end mul section pow lemma pow_antitone_exp {a : ℝ≥0} (m n : ℕ) (mn : m ≤ n) (a1 : a ≤ 1) : a ^ n ≤ a ^ m := pow_le_pow_of_le_one (zero_le a) a1 mn lemma exists_pow_lt_of_lt_one {a b : ℝ≥0} (ha : 0 < a) (hb : b < 1) : ∃ n : ℕ, b ^ n < a := by simpa only [← coe_pow, nnreal.coe_lt_coe] using exists_pow_lt_of_lt_one (nnreal.coe_pos.2 ha) (nnreal.coe_lt_coe.2 hb) lemma exists_mem_Ico_zpow {x : ℝ≥0} {y : ℝ≥0} (hx : x ≠ 0) (hy : 1 < y) : ∃ n : ℤ, x ∈ set.Ico (y ^ n) (y ^ (n + 1)) := begin obtain ⟨n, hn, h'n⟩ : ∃ n : ℤ, (y : ℝ) ^ n ≤ x ∧ (x : ℝ) < y ^ (n + 1) := exists_mem_Ico_zpow (bot_lt_iff_ne_bot.mpr hx) hy, rw ← nnreal.coe_zpow at hn h'n, exact ⟨n, hn, h'n⟩, end lemma exists_mem_Ioc_zpow {x : ℝ≥0} {y : ℝ≥0} (hx : x ≠ 0) (hy : 1 < y) : ∃ n : ℤ, x ∈ set.Ioc (y ^ n) (y ^ (n + 1)) := begin obtain ⟨n, hn, h'n⟩ : ∃ n : ℤ, (y : ℝ) ^ n < x ∧ (x : ℝ) ≤ y ^ (n + 1) := exists_mem_Ioc_zpow (bot_lt_iff_ne_bot.mpr hx) hy, rw ← nnreal.coe_zpow at hn h'n, exact ⟨n, hn, h'n⟩, end end pow section sub /-! ### Lemmas about subtraction In this section we provide a few lemmas about subtraction that do not fit well into any other typeclass. For lemmas about subtraction and addition see lemmas about `has_ordered_sub` in the file `algebra.order.sub`. See also `mul_tsub` and `tsub_mul`. -/ lemma sub_def {r p : ℝ≥0} : r - p = real.to_nnreal (r - p) := rfl lemma coe_sub_def {r p : ℝ≥0} : ↑(r - p) = max (r - p : ℝ) 0 := rfl noncomputable example : has_ordered_sub ℝ≥0 := by apply_instance lemma sub_div (a b c : ℝ≥0) : (a - b) / c = a / c - b / c := by simp only [div_eq_mul_inv, tsub_mul] end sub section inv lemma sum_div {ι} (s : finset ι) (f : ι → ℝ≥0) (b : ℝ≥0) : (∑ i in s, f i) / b = ∑ i in s, (f i / b) := by simp only [div_eq_mul_inv, finset.sum_mul] @[simp] lemma inv_pos {r : ℝ≥0} : 0 < r⁻¹ ↔ 0 < r := by simp [pos_iff_ne_zero] lemma div_pos {r p : ℝ≥0} (hr : 0 < r) (hp : 0 < p) : 0 < r / p := by simpa only [div_eq_mul_inv] using mul_pos hr (inv_pos.2 hp) protected lemma mul_inv {r p : ℝ≥0} : (r * p)⁻¹ = p⁻¹ * r⁻¹ := nnreal.eq $ mul_inv_rev _ _ lemma div_self_le (r : ℝ≥0) : r / r ≤ 1 := div_self_le_one (r : ℝ) @[simp] lemma inv_le {r p : ℝ≥0} (h : r ≠ 0) : r⁻¹ ≤ p ↔ 1 ≤ r * p := by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h] lemma inv_le_of_le_mul {r p : ℝ≥0} (h : 1 ≤ r * p) : r⁻¹ ≤ p := by by_cases r = 0; simp [*, inv_le] @[simp] lemma le_inv_iff_mul_le {r p : ℝ≥0} (h : p ≠ 0) : (r ≤ p⁻¹ ↔ r * p ≤ 1) := by rw [← mul_le_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] @[simp] lemma lt_inv_iff_mul_lt {r p : ℝ≥0} (h : p ≠ 0) : (r < p⁻¹ ↔ r * p < 1) := by rw [← mul_lt_mul_left (pos_iff_ne_zero.2 h), mul_inv_cancel h, mul_comm] lemma mul_le_iff_le_inv {a b r : ℝ≥0} (hr : r ≠ 0) : r * a ≤ b ↔ a ≤ r⁻¹ * b := have 0 < r, from lt_of_le_of_ne (zero_le r) hr.symm, by rw [← @mul_le_mul_left _ _ a _ r this, ← mul_assoc, mul_inv_cancel hr, one_mul] lemma le_div_iff_mul_le {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := by rw [div_eq_inv_mul, ← mul_le_iff_le_inv hr, mul_comm] lemma div_le_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ b * r := @div_le_iff ℝ _ a r b $ pos_iff_ne_zero.2 hr lemma div_le_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a / r ≤ b ↔ a ≤ r * b := @div_le_iff' ℝ _ a r b $ pos_iff_ne_zero.2 hr lemma div_le_of_le_mul {a b c : ℝ≥0} (h : a ≤ b * c) : a / c ≤ b := if h0 : c = 0 then by simp [h0] else (div_le_iff h0).2 h lemma div_le_of_le_mul' {a b c : ℝ≥0} (h : a ≤ b * c) : a / b ≤ c := div_le_of_le_mul $ mul_comm b c ▸ h lemma le_div_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ a * r ≤ b := @le_div_iff ℝ _ a b r $ pos_iff_ne_zero.2 hr lemma le_div_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a ≤ b / r ↔ r * a ≤ b := @le_div_iff' ℝ _ a b r $ pos_iff_ne_zero.2 hr lemma div_lt_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a / r < b ↔ a < b * r := lt_iff_lt_of_le_iff_le (le_div_iff hr) lemma div_lt_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a / r < b ↔ a < r * b := lt_iff_lt_of_le_iff_le (le_div_iff' hr) lemma lt_div_iff {a b r : ℝ≥0} (hr : r ≠ 0) : a < b / r ↔ a * r < b := lt_iff_lt_of_le_iff_le (div_le_iff hr) lemma lt_div_iff' {a b r : ℝ≥0} (hr : r ≠ 0) : a < b / r ↔ r * a < b := lt_iff_lt_of_le_iff_le (div_le_iff' hr) lemma mul_lt_of_lt_div {a b r : ℝ≥0} (h : a < b / r) : a * r < b := begin refine (lt_div_iff $ λ hr, false.elim _).1 h, subst r, simpa using h end lemma div_le_div_left_of_le {a b c : ℝ≥0} (b0 : 0 < b) (c0 : 0 < c) (cb : c ≤ b) : a / b ≤ a / c := begin by_cases a0 : a = 0, { rw [a0, zero_div, zero_div] }, { cases a with a ha, replace a0 : 0 < a := lt_of_le_of_ne ha (ne_of_lt (zero_lt_iff.mpr a0)), exact (div_le_div_left a0 b0 c0).mpr cb } end lemma div_le_div_left {a b c : ℝ≥0} (a0 : 0 < a) (b0 : 0 < b) (c0 : 0 < c) : a / b ≤ a / c ↔ c ≤ b := by rw [nnreal.div_le_iff b0.ne.symm, div_mul_eq_mul_div, nnreal.le_div_iff_mul_le c0.ne.symm, mul_le_mul_left a0] lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0} (h : ∀a<1, a * x ≤ y) : x ≤ y := le_of_forall_ge_of_dense $ assume a ha, have hx : x ≠ 0 := pos_iff_ne_zero.1 (lt_of_le_of_lt (zero_le _) ha), have hx' : x⁻¹ ≠ 0, by rwa [(≠), inv_eq_zero], have a * x⁻¹ < 1, by rwa [← lt_inv_iff_mul_lt hx', inv_inv], have (a * x⁻¹) * x ≤ y, from h _ this, by rwa [mul_assoc, inv_mul_cancel hx, mul_one] at this lemma div_add_div_same (a b c : ℝ≥0) : a / c + b / c = (a + b) / c := eq.symm $ right_distrib a b (c⁻¹) lemma half_pos {a : ℝ≥0} (h : 0 < a) : 0 < a / 2 := div_pos h zero_lt_two lemma add_halves (a : ℝ≥0) : a / 2 + a / 2 = a := nnreal.eq (add_halves a) lemma half_lt_self {a : ℝ≥0} (h : a ≠ 0) : a / 2 < a := by rw [← nnreal.coe_lt_coe, nnreal.coe_div]; exact half_lt_self (bot_lt_iff_ne_bot.2 h) lemma two_inv_lt_one : (2⁻¹:ℝ≥0) < 1 := by simpa using half_lt_self zero_ne_one.symm lemma div_lt_one_of_lt {a b : ℝ≥0} (h : a < b) : a / b < 1 := begin rwa [div_lt_iff, one_mul], exact ne_of_gt (lt_of_le_of_lt (zero_le _) h) end @[field_simps] lemma div_add_div (a : ℝ≥0) {b : ℝ≥0} (c : ℝ≥0) {d : ℝ≥0} (hb : b ≠ 0) (hd : d ≠ 0) : a / b + c / d = (a * d + b * c) / (b * d) := begin rw ← nnreal.eq_iff, simp only [nnreal.coe_add, nnreal.coe_div, nnreal.coe_mul], exact div_add_div _ _ (coe_ne_zero.2 hb) (coe_ne_zero.2 hd) end @[field_simps] lemma add_div' (a b c : ℝ≥0) (hc : c ≠ 0) : b + a / c = (b * c + a) / c := by simpa using div_add_div b a one_ne_zero hc @[field_simps] lemma div_add' (a b c : ℝ≥0) (hc : c ≠ 0) : a / c + b = (a + b * c) / c := by rwa [add_comm, add_div', add_comm] lemma _root_.real.to_nnreal_inv {x : ℝ} : real.to_nnreal x⁻¹ = (real.to_nnreal x)⁻¹ := begin by_cases hx : 0 ≤ x, { nth_rewrite 0 ← real.coe_to_nnreal x hx, rw [←nnreal.coe_inv, real.to_nnreal_coe], }, { have hx' := le_of_not_ge hx, rw [to_nnreal_eq_zero.mpr hx', inv_zero, to_nnreal_eq_zero.mpr (inv_nonpos.mpr hx')], }, end lemma _root_.real.to_nnreal_div {x y : ℝ} (hx : 0 ≤ x) : real.to_nnreal (x / y) = real.to_nnreal x / real.to_nnreal y := by rw [div_eq_mul_inv, div_eq_mul_inv, ← real.to_nnreal_inv, ← real.to_nnreal_mul hx] lemma _root_.real.to_nnreal_div' {x y : ℝ} (hy : 0 ≤ y) : real.to_nnreal (x / y) = real.to_nnreal x / real.to_nnreal y := by rw [div_eq_inv_mul, div_eq_inv_mul, real.to_nnreal_mul (inv_nonneg.2 hy), real.to_nnreal_inv] lemma inv_lt_one_iff {x : ℝ≥0} (hx : x ≠ 0) : x⁻¹ < 1 ↔ 1 < x := by rwa [← one_div, div_lt_iff hx, one_mul] lemma inv_lt_one {x : ℝ≥0} (hx : 1 < x) : x⁻¹ < 1 := (inv_lt_one_iff (zero_lt_one.trans hx).ne').2 hx lemma zpow_pos {x : ℝ≥0} (hx : x ≠ 0) (n : ℤ) : 0 < x ^ n := begin cases n, { simp [pow_pos hx.bot_lt _] }, { simp [pow_pos hx.bot_lt _] } end lemma inv_lt_inv_iff {x y : ℝ≥0} (hx : x ≠ 0) (hy : y ≠ 0) : y⁻¹ < x⁻¹ ↔ x < y := by rw [← one_div, div_lt_iff hy, ← div_eq_inv_mul, lt_div_iff hx, one_mul] lemma inv_lt_inv {x y : ℝ≥0} (hx : x ≠ 0) (h : x < y) : y⁻¹ < x⁻¹ := (inv_lt_inv_iff hx ((bot_le.trans_lt h).ne')).2 h end inv @[simp] lemma abs_eq (x : ℝ≥0) : |(x : ℝ)| = x := abs_of_nonneg x.property end nnreal namespace real /-- The absolute value on `ℝ` as a map to `ℝ≥0`. -/ @[pp_nodot] noncomputable def nnabs : ℝ →*₀ ℝ≥0 := { to_fun := λ x, ⟨|x|, abs_nonneg x⟩, map_zero' := by { ext, simp }, map_one' := by { ext, simp }, map_mul' := λ x y, by { ext, simp [abs_mul] } } @[norm_cast, simp] lemma coe_nnabs (x : ℝ) : (nnabs x : ℝ) = |x| := rfl @[simp] lemma nnabs_of_nonneg {x : ℝ} (h : 0 ≤ x) : nnabs x = to_nnreal x := by { ext, simp [coe_to_nnreal x h, abs_of_nonneg h] } lemma coe_to_nnreal_le (x : ℝ) : (to_nnreal x : ℝ) ≤ |x| := max_le (le_abs_self _) (abs_nonneg _) lemma cast_nat_abs_eq_nnabs_cast (n : ℤ) : (n.nat_abs : ℝ≥0) = nnabs n := by { ext, rw [nnreal.coe_nat_cast, int.cast_nat_abs, real.coe_nnabs] } end real
d7bc824fdab60c25ff6f1272803081f8a51ff578
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/probability/martingale/convergence.lean
69fca0645ba62969316729f9116fe529e4af8310
[ "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
25,477
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import probability.martingale.upcrossing import measure_theory.function.uniform_integrable import measure_theory.constructions.polish /-! # Martingale convergence theorems The martingale convergence theorems are a collection of theorems characterizing the convergence of a martingale provided it satisfies some boundedness conditions. This file contains the almost everywhere martingale convergence theorem which provides an almost everywhere limit to an L¹ bounded submartingale. It also contains the L¹ martingale convergence theorem which provides an L¹ limit to a uniformly integrable submartingale. Finally, it also contains the Lévy upwards theorems. ## Main results * `measure_theory.submartingale.ae_tendsto_limit_process`: the almost everywhere martingale convergence theorem: an L¹-bounded submartingale adapted to the filtration `ℱ` converges almost everywhere to its limit process. * `measure_theory.submartingale.mem_ℒp_limit_process`: the limit process of an Lᵖ-bounded submartingale is Lᵖ. * `measure_theory.submartingale.tendsto_snorm_one_limit_process`: part a of the L¹ martingale convergence theorem: a uniformly integrable submartingale adapted to the filtration `ℱ` converges almost everywhere and in L¹ to an integrable function which is measurable with respect to the σ-algebra `⨆ n, ℱ n`. * `measure_theory.martingale.ae_eq_condexp_limit_process`: part b the L¹ martingale convergence theorem: if `f` is a uniformly integrable martingale adapted to the filtration `ℱ`, then `f n` equals `𝔼[g | ℱ n]` almost everywhere where `g` is the limiting process of `f`. * `measure_theory.integrable.tendsto_ae_condexp`: part c the L¹ martingale convergence theorem: given a `⨆ n, ℱ n`-measurable function `g` where `ℱ` is a filtration, `𝔼[g | ℱ n]` converges almost everywhere to `g`. * `measure_theory.integrable.tendsto_snorm_condexp`: part c the L¹ martingale convergence theorem: given a `⨆ n, ℱ n`-measurable function `g` where `ℱ` is a filtration, `𝔼[g | ℱ n]` converges in L¹ to `g`. -/ open topological_space filter measure_theory.filtration open_locale nnreal ennreal measure_theory probability_theory big_operators topological_space namespace measure_theory variables {Ω ι : Type*} {m0 : measurable_space Ω} {μ : measure Ω} {ℱ : filtration ℕ m0} variables {a b : ℝ} {f : ℕ → Ω → ℝ} {ω : Ω} {R : ℝ≥0} section ae_convergence /-! ### Almost everywhere martingale convergence theorem We will now prove the almost everywhere martingale convergence theorem. The a.e. martingale convergence theorem states: if `f` is an L¹-bounded `ℱ`-submartingale, then it converges almost everywhere to an integrable function which is measurable with respect to the σ-algebra `ℱ∞ := ⨆ n, ℱ n`. Mathematically, we proceed by first noting that a real sequence $(x_n)$ converges if (a) $\limsup_{n \to \infty} |x_n| < \infty$, (b) for all $a < b \in \mathbb{Q}$ we have the number of upcrossings of $(x_n)$ from below $a$ to above $b$ is finite. Thus, for all $\omega$ satisfying $\limsup_{n \to \infty} |f_n(\omega)| < \infty$ and the number of upcrossings of $(f_n(\omega))$ from below $a$ to above $b$ is finite for all $a < b \in \mathbb{Q}$, we have $(f_n(\omega))$ is convergent. Hence, assuming $(f_n)$ is L¹-bounded, using Fatou's lemma, we have $$ \mathbb{E} \limsup_{n \to \infty} |f_n| \le \limsup_{n \to \infty} \mathbb{E}|f_n| < \infty $$ implying $\limsup_{n \to \infty} |f_n| < \infty$ a.e. Furthermore, by the upcrossing estimate, the number of upcrossings is finite almost everywhere implying $f$ converges pointwise almost everywhere. Thus, denoting $g$ the a.e. limit of $(f_n)$, $g$ is $\mathcal{F}_\infty$-measurable as for all $n$, $f_n$ is $\mathcal{F}_n$-measurable and $\mathcal{F}_n \le \mathcal{F}_\infty$. Finally, $g$ is integrable as $|g| \le \liminf_{n \to \infty} |f_n|$ so $$ \mathbb{E}|g| \le \mathbb{E} \limsup_{n \to \infty} |f_n| \le \limsup_{n \to \infty} \mathbb{E}|f_n| < \infty $$ as required. Implementation wise, we have `tendsto_of_no_upcrossings` which showed that a bounded sequence converges if it does not visit below $a$ and above $b$ infinitely often for all $a, b ∈ s$ for some dense set $s$. So, we may skip the first step provided we can prove that the realizations are bounded almost everywhere. Indeed, suppose $(|f_n(\omega)|)$ is not bounded, then either $f_n(\omega) \to \pm \infty$ or one of $\limsup f_n(\omega)$ or $\liminf f_n(\omega)$ equals $\pm \infty$ while the other is finite. But the first case contradicts $\liminf |f_n(\omega)| < \infty$ while the second case contradicts finite upcrossings. Furthermore, we introduced `filtration.limit_process` which chooses the limiting random variable of a stochastic process if it exists, otherwise it returns 0. Hence, instead of showing an existence statement, we phrased the a.e. martingale convergence theorem by showed that a submartingale converges to its `limit_process` almost everywhere. -/ /-- If a stochastic process has bounded upcrossing from below `a` to above `b`, then it does not frequently visit both below `a` and above `b`. -/ lemma not_frequently_of_upcrossings_lt_top (hab : a < b) (hω : upcrossings a b f ω ≠ ∞) : ¬((∃ᶠ n in at_top, f n ω < a) ∧ (∃ᶠ n in at_top, b < f n ω)) := begin rw [← lt_top_iff_ne_top, upcrossings_lt_top_iff] at hω, replace hω : ∃ k, ∀ N, upcrossings_before a b f N ω < k, { obtain ⟨k, hk⟩ := hω, exact ⟨k + 1, λ N, lt_of_le_of_lt (hk N) k.lt_succ_self⟩ }, rintro ⟨h₁, h₂⟩, rw frequently_at_top at h₁ h₂, refine not_not.2 hω _, push_neg, intro k, induction k with k ih, { simp only [zero_le', exists_const] }, { obtain ⟨N, hN⟩ := ih, obtain ⟨N₁, hN₁, hN₁'⟩ := h₁ N, obtain ⟨N₂, hN₂, hN₂'⟩ := h₂ N₁, exact ⟨(N₂ + 1), nat.succ_le_of_lt $ lt_of_le_of_lt hN (upcrossings_before_lt_of_exists_upcrossing hab hN₁ hN₁' hN₂ hN₂')⟩ } end /-- A stochastic process that frequently visits below `a` and above `b` have infinite upcrossings. -/ lemma upcrossings_eq_top_of_frequently_lt (hab : a < b) (h₁ : ∃ᶠ n in at_top, f n ω < a) (h₂ : ∃ᶠ n in at_top, b < f n ω) : upcrossings a b f ω = ∞ := classical.by_contradiction (λ h, not_frequently_of_upcrossings_lt_top hab h ⟨h₁, h₂⟩) /-- A realization of a stochastic process with bounded upcrossings and bounded liminfs is convergent. We use the spelling `< ∞` instead of the standard `≠ ∞` in the assumptions since it is not as easy to change `<` to `≠` under binders. -/ lemma tendsto_of_uncrossing_lt_top (hf₁ : liminf (λ n, (‖f n ω‖₊ : ℝ≥0∞)) at_top < ∞) (hf₂ : ∀ a b : ℚ, a < b → upcrossings a b f ω < ∞) : ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := begin by_cases h : is_bounded_under (≤) at_top (λ n, |f n ω|), { rw is_bounded_under_le_abs at h, refine tendsto_of_no_upcrossings rat.dense_range_cast _ h.1 h.2, { intros a ha b hb hab, obtain ⟨⟨a, rfl⟩, ⟨b, rfl⟩⟩ := ⟨ha, hb⟩, exact not_frequently_of_upcrossings_lt_top hab (hf₂ a b (rat.cast_lt.1 hab)).ne } }, { obtain ⟨a, b, hab, h₁, h₂⟩ := ennreal.exists_upcrossings_of_not_bounded_under hf₁.ne h, exact false.elim ((hf₂ a b hab).ne (upcrossings_eq_top_of_frequently_lt (rat.cast_lt.2 hab) h₁ h₂)) } end /-- An L¹-bounded submartingale has bounded upcrossings almost everywhere. -/ lemma submartingale.upcrossings_ae_lt_top' [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) (hab : a < b) : ∀ᵐ ω ∂μ, upcrossings a b f ω < ∞ := begin refine ae_lt_top (hf.adapted.measurable_upcrossings hab) _, have := hf.mul_lintegral_upcrossings_le_lintegral_pos_part a b, rw [mul_comm, ← ennreal.le_div_iff_mul_le] at this, { refine (lt_of_le_of_lt this (ennreal.div_lt_top _ _)).ne, { have hR' : ∀ n, ∫⁻ ω, ‖f n ω - a‖₊ ∂μ ≤ R + ‖a‖₊ * μ set.univ, { simp_rw snorm_one_eq_lintegral_nnnorm at hbdd, intro n, refine (lintegral_mono _ : ∫⁻ ω, ‖f n ω - a‖₊ ∂μ ≤ ∫⁻ ω, ‖f n ω‖₊ + ‖a‖₊ ∂μ).trans _, { intro ω, simp_rw [sub_eq_add_neg, ← nnnorm_neg a, ← ennreal.coe_add, ennreal.coe_le_coe], exact nnnorm_add_le _ _ }, { simp_rw [ lintegral_add_right _ measurable_const, lintegral_const], exact add_le_add (hbdd _) le_rfl } }, refine ne_of_lt (supr_lt_iff.2 ⟨R + ‖a‖₊ * μ set.univ, ennreal.add_lt_top.2 ⟨ennreal.coe_lt_top, ennreal.mul_lt_top ennreal.coe_lt_top.ne (measure_ne_top _ _)⟩, λ n, le_trans _ (hR' n)⟩), refine lintegral_mono (λ ω, _), rw [ennreal.of_real_le_iff_le_to_real, ennreal.coe_to_real, coe_nnnorm], by_cases hnonneg : 0 ≤ f n ω - a, { rw [lattice_ordered_comm_group.pos_of_nonneg _ hnonneg, real.norm_eq_abs, abs_of_nonneg hnonneg] }, { rw lattice_ordered_comm_group.pos_of_nonpos _ (not_le.1 hnonneg).le, exact norm_nonneg _ }, { simp only [ne.def, ennreal.coe_ne_top, not_false_iff] } }, { simp only [hab, ne.def, ennreal.of_real_eq_zero, sub_nonpos, not_le] } }, { simp only [hab, ne.def, ennreal.of_real_eq_zero, sub_nonpos, not_le, true_or]}, { simp only [ne.def, ennreal.of_real_ne_top, not_false_iff, true_or] } end lemma submartingale.upcrossings_ae_lt_top [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) : ∀ᵐ ω ∂μ, ∀ a b : ℚ, a < b → upcrossings a b f ω < ∞ := begin simp only [ae_all_iff, eventually_imp_distrib_left], rintro a b hab, exact hf.upcrossings_ae_lt_top' hbdd (rat.cast_lt.2 hab), end /-- An L¹-bounded submartingale converges almost everywhere. -/ lemma submartingale.exists_ae_tendsto_of_bdd [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) : ∀ᵐ ω ∂μ, ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := begin filter_upwards [hf.upcrossings_ae_lt_top hbdd, ae_bdd_liminf_at_top_of_snorm_bdd one_ne_zero (λ n, (hf.strongly_measurable n).measurable.mono (ℱ.le n) le_rfl) hbdd] with ω h₁ h₂, exact tendsto_of_uncrossing_lt_top h₂ h₁, end lemma submartingale.exists_ae_trim_tendsto_of_bdd [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) : ∀ᵐ ω ∂(μ.trim (Sup_le (λ m ⟨n, hn⟩, hn ▸ ℱ.le _) : (⨆ n, ℱ n) ≤ m0)), ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) := begin rw [ae_iff, trim_measurable_set_eq], { exact hf.exists_ae_tendsto_of_bdd hbdd }, { exact measurable_set.compl (@measurable_set_exists_tendsto _ _ _ _ _ _ (⨆ n, ℱ n) _ _ _ _ _ (λ n, ((hf.strongly_measurable n).measurable.mono (le_Sup ⟨n, rfl⟩) le_rfl))) } end /-- **Almost everywhere martingale convergence theorem**: An L¹-bounded submartingale converges almost everywhere to a `⨆ n, ℱ n`-measurable function. -/ lemma submartingale.ae_tendsto_limit_process [is_finite_measure μ] (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) 1 μ ≤ R) : ∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top (𝓝 (ℱ.limit_process f μ ω)) := begin classical, suffices : ∃ g, strongly_measurable[⨆ n, ℱ n] g ∧ ∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top (𝓝 (g ω)), { rw [limit_process, dif_pos this], exact (classical.some_spec this).2 }, set g' : Ω → ℝ := λ ω, if h : ∃ c, tendsto (λ n, f n ω) at_top (𝓝 c) then h.some else 0, have hle : (⨆ n, ℱ n) ≤ m0 := Sup_le (λ m ⟨n, hn⟩, hn ▸ ℱ.le _), have hg' : ∀ᵐ ω ∂(μ.trim hle), tendsto (λ n, f n ω) at_top (𝓝 (g' ω)), { filter_upwards [hf.exists_ae_trim_tendsto_of_bdd hbdd] with ω hω, simp_rw [g', dif_pos hω], exact hω.some_spec }, have hg'm : @ae_strongly_measurable _ _ _ (⨆ n, ℱ n) g' (μ.trim hle) := (@ae_measurable_of_tendsto_metrizable_ae' _ _ (⨆ n, ℱ n) _ _ _ _ _ _ _ (λ n, ((hf.strongly_measurable n).measurable.mono (le_Sup ⟨n, rfl⟩ : ℱ n ≤ ⨆ n, ℱ n) le_rfl).ae_measurable) hg').ae_strongly_measurable, obtain ⟨g, hgm, hae⟩ := hg'm, have hg : ∀ᵐ ω ∂μ.trim hle, tendsto (λ n, f n ω) at_top (𝓝 (g ω)), { filter_upwards [hae, hg'] with ω hω hg'ω, exact hω ▸ hg'ω }, exact ⟨g, hgm, measure_eq_zero_of_trim_eq_zero hle hg⟩, end /-- The limiting process of an Lᵖ-bounded submartingale is Lᵖ. -/ lemma submartingale.mem_ℒp_limit_process {p : ℝ≥0∞} (hf : submartingale f ℱ μ) (hbdd : ∀ n, snorm (f n) p μ ≤ R) : mem_ℒp (ℱ.limit_process f μ) p μ := mem_ℒp_limit_process_of_snorm_bdd (λ n, ((hf.strongly_measurable n).mono (ℱ.le n)).ae_strongly_measurable) hbdd end ae_convergence section L1_convergence variables [is_finite_measure μ] {g : Ω → ℝ} /-! ### L¹ martingale convergence theorem We will now prove the L¹ martingale convergence theorems. The L¹ martingale convergence theorem states that: (a) if `f` is a uniformly integrable (in the probability sense) submartingale adapted to the filtration `ℱ`, it converges in L¹ to an integrable function `g` which is measurable with respect to `ℱ∞ := ⨆ n, ℱ n` and (b) if `f` is actually a martingale, `f n = 𝔼[g | ℱ n]` almost everywhere. (c) Finally, if `h` is integrable and measurable with respect to `ℱ∞`, `(𝔼[h | ℱ n])ₙ` is a uniformly integrable martingale which converges to `h` almost everywhere and in L¹. The proof is quite simple. (a) follows directly from the a.e. martingale convergence theorem and the Vitali convergence theorem as our definition of uniform integrability (in the probability sense) directly implies L¹-uniform boundedness. We note that our definition of uniform integrability is slightly non-standard but is equivalent to the usual literary definition. This equivalence is provided by `measure_theory.uniform_integrable_iff`. (b) follows since given $n$, we have for all $m \ge n$, $$ \|f_n - \mathbb{E}[g \mid \mathcal{F}_n]\|_1 = \|\mathbb{E}[f_m - g \mid \mathcal{F}_n]\|_1 \le \|\|f_m - g\|_1. $$ Thus, taking $m \to \infty$ provides the almost everywhere equality. Finally, to prove (c), we define $f_n := \mathbb{E}[h \mid \mathcal{F}_n]$. It is clear that $(f_n)_n$ is a martingale by the tower property for conditional expectations. Furthermore, $(f_n)_n$ is uniformly integrable in the probability sense. Indeed, as a single function is uniformly integrable in the measure theory sense, for all $\epsilon > 0$, there exists some $\delta > 0$ such that for all measurable set $A$ with $\mu(A) < δ$, we have $\mathbb{E}|h|\mathbf{1}_A < \epsilon$. So, since for sufficently large $\lambda$, by the Markov inequality, we have for all $n$, $$ \mu(|f_n| \ge \lambda) \le \lambda^{-1}\mathbb{E}|f_n| \le \lambda^{-1}\mathbb|g| < \delta, $$ we have for sufficently large $\lambda$, for all $n$, $$ \mathbb{E}|f_n|\mathbf{1}_{|f_n| \ge \lambda} \le \mathbb|g|\mathbf{1}_{|f_n| \ge \lambda} < \epsilon, $$ implying $(f_n)_n$ is uniformly integrable. Now, to prove $f_n \to h$ almost everywhere and in L¹, it suffices to show that $h = g$ almost everywhere where $g$ is the almost everywhere and L¹ limit of $(f_n)_n$ from part (b) of the theorem. By noting that, for all $s \in \mathcal{F}_n$, we have $$ \mathbb{E}g\mathbf{1}_s = \mathbb{E}[\mathbb{E}[g \mid \mathcal{F}_n]\mathbf{1}_s] = \mathbb{E}[\mathbb{E}[h \mid \mathcal{F}_n]\mathbf{1}_s] = \mathbb{E}h\mathbf{1}_s $$ where $\mathbb{E}[g \mid \mathcal{F}_n = \mathbb{E}[h \mid \mathcal{F}_n]$ almost everywhere by part (b); the equality also holds for all $s \in \mathcal{F}_\infty$ by Dynkin's theorem. Thus, as both $h$ and $g$ are $\mathcal{F}_\infty$-measurable, $h = g$ almost everywhere as required. Similar to the a.e. martingale convergence theorem, rather than showing the existence of the limiting process, we phrased the L¹-martingale convergence theorem by proving that a submartingale does converge in L¹ to its `limit_process`. However, in contrast to the a.e. martingale convergence theorem, we do not need to introduce a L¹ version of `filtration.limit_process` as the L¹ limit and the a.e. limit of a submartingale coincide. -/ /-- Part a of the **L¹ martingale convergence theorem**: a uniformly integrable submartingale adapted to the filtration `ℱ` converges a.e. and in L¹ to an integrable function which is measurable with respect to the σ-algebra `⨆ n, ℱ n`. -/ lemma submartingale.tendsto_snorm_one_limit_process (hf : submartingale f ℱ μ) (hunif : uniform_integrable f 1 μ) : tendsto (λ n, snorm (f n - ℱ.limit_process f μ) 1 μ) at_top (𝓝 0) := begin obtain ⟨R, hR⟩ := hunif.2.2, have hmeas : ∀ n, ae_strongly_measurable (f n) μ := λ n, ((hf.strongly_measurable n).mono (ℱ.le _)).ae_strongly_measurable, exact tendsto_Lp_of_tendsto_in_measure _ le_rfl ennreal.one_ne_top hmeas (mem_ℒp_limit_process_of_snorm_bdd hmeas hR) hunif.2.1 (tendsto_in_measure_of_tendsto_ae hmeas $ hf.ae_tendsto_limit_process hR), end lemma submartingale.ae_tendsto_limit_process_of_uniform_integrable (hf : submartingale f ℱ μ) (hunif : uniform_integrable f 1 μ) : ∀ᵐ ω ∂μ, tendsto (λ n, f n ω) at_top (𝓝 (ℱ.limit_process f μ ω)) := let ⟨R, hR⟩ := hunif.2.2 in hf.ae_tendsto_limit_process hR /-- If a martingale `f` adapted to `ℱ` converges in L¹ to `g`, then for all `n`, `f n` is almost everywhere equal to `𝔼[g | ℱ n]`. -/ lemma martingale.eq_condexp_of_tendsto_snorm {μ : measure Ω} (hf : martingale f ℱ μ) (hg : integrable g μ) (hgtends : tendsto (λ n, snorm (f n - g) 1 μ) at_top (𝓝 0)) (n : ℕ) : f n =ᵐ[μ] μ[g | ℱ n] := begin rw [← sub_ae_eq_zero, ← snorm_eq_zero_iff ((((hf.strongly_measurable n).mono (ℱ.le _)).sub (strongly_measurable_condexp.mono (ℱ.le _))).ae_strongly_measurable) one_ne_zero], have ht : tendsto (λ m, snorm (μ[f m - g | ℱ n]) 1 μ) at_top (𝓝 0), { have hint : ∀ m, integrable (f m - g) μ := λ m, (hf.integrable m).sub hg, exact tendsto_of_tendsto_of_tendsto_of_le_of_le tendsto_const_nhds hgtends (λ m, zero_le _) (λ m, snorm_one_condexp_le_snorm _) }, have hev : ∀ m ≥ n, snorm (μ[f m - g | ℱ n]) 1 μ = snorm (f n - μ[g | ℱ n]) 1 μ, { refine λ m hm, snorm_congr_ae ((condexp_sub (hf.integrable m) hg).trans _), filter_upwards [hf.2 n m hm] with x hx, simp only [hx, pi.sub_apply] }, exact tendsto_nhds_unique (tendsto_at_top_of_eventually_const hev) ht, end /-- Part b of the **L¹ martingale convergence theorem**: if `f` is a uniformly integrable martingale adapted to the filtration `ℱ`, then for all `n`, `f n` is almost everywhere equal to the conditional expectation of its limiting process wrt. `ℱ n`. -/ lemma martingale.ae_eq_condexp_limit_process (hf : martingale f ℱ μ) (hbdd : uniform_integrable f 1 μ) (n : ℕ) : f n =ᵐ[μ] μ[ℱ.limit_process f μ | ℱ n] := let ⟨R, hR⟩ := hbdd.2.2 in hf.eq_condexp_of_tendsto_snorm ((mem_ℒp_limit_process_of_snorm_bdd hbdd.1 hR).integrable le_rfl) (hf.submartingale.tendsto_snorm_one_limit_process hbdd) n /-- Part c of the **L¹ martingale convergnce theorem**: Given a integrable function `g` which is measurable with respect to `⨆ n, ℱ n` where `ℱ` is a filtration, the martingale defined by `𝔼[g | ℱ n]` converges almost everywhere to `g`. This martingale also converges to `g` in L¹ and this result is provided by `measure_theory.integrable.tendsto_snorm_condexp` -/ lemma integrable.tendsto_ae_condexp (hg : integrable g μ) (hgmeas : strongly_measurable[⨆ n, ℱ n] g) : ∀ᵐ x ∂μ, tendsto (λ n, μ[g | ℱ n] x) at_top (𝓝 (g x)) := begin have hle : (⨆ n, ℱ n) ≤ m0 := Sup_le (λ m ⟨n, hn⟩, hn ▸ ℱ.le _), have hunif : uniform_integrable (λ n, μ[g | ℱ n]) 1 μ := hg.uniform_integrable_condexp_filtration, obtain ⟨R, hR⟩ := hunif.2.2, have hlimint : integrable (ℱ.limit_process (λ n, μ[g | ℱ n]) μ) μ := (mem_ℒp_limit_process_of_snorm_bdd hunif.1 hR).integrable le_rfl, suffices : g =ᵐ[μ] ℱ.limit_process (λ n x, μ[g | ℱ n] x) μ, { filter_upwards [this, (martingale_condexp g ℱ μ).submartingale.ae_tendsto_limit_process hR] with x heq ht, rwa heq }, have : ∀ n s, measurable_set[ℱ n] s → ∫ x in s, g x ∂μ = ∫ x in s, ℱ.limit_process (λ n x, μ[g | ℱ n] x) μ x ∂μ, { intros n s hs, rw [← set_integral_condexp (ℱ.le n) hg hs, ← set_integral_condexp (ℱ.le n) hlimint hs], refine set_integral_congr_ae (ℱ.le _ _ hs) _, filter_upwards [(martingale_condexp g ℱ μ).ae_eq_condexp_limit_process hunif n] with x hx _, rwa hx }, refine ae_eq_of_forall_set_integral_eq_of_sigma_finite' hle (λ s _ _, hg.integrable_on) (λ s _ _, hlimint.integrable_on) (λ s hs, _) hgmeas.ae_strongly_measurable' strongly_measurable_limit_process.ae_strongly_measurable', refine @measurable_space.induction_on_inter _ _ _ (⨆ n, ℱ n) (measurable_space.measurable_space_supr_eq ℱ) _ _ _ _ _ _ hs, { rintro s ⟨n, hs⟩ t ⟨m, ht⟩ -, by_cases hnm : n ≤ m, { exact ⟨m, (ℱ.mono hnm _ hs).inter ht⟩ }, { exact ⟨n, hs.inter (ℱ.mono (not_le.1 hnm).le _ ht)⟩ } }, { simp only [measure_empty, with_top.zero_lt_top, measure.restrict_empty, integral_zero_measure, forall_true_left] }, { rintro t ⟨n, ht⟩ -, exact this n _ ht }, { rintro t htmeas ht -, have hgeq := @integral_add_compl _ _ (⨆ n, ℱ n) _ _ _ _ _ _ htmeas (hg.trim hle hgmeas), have hheq := @integral_add_compl _ _ (⨆ n, ℱ n) _ _ _ _ _ _ htmeas (hlimint.trim hle strongly_measurable_limit_process), rw [add_comm, ← eq_sub_iff_add_eq] at hgeq hheq, rw [set_integral_trim hle hgmeas htmeas.compl, set_integral_trim hle strongly_measurable_limit_process htmeas.compl, hgeq, hheq, ← set_integral_trim hle hgmeas htmeas, ← set_integral_trim hle strongly_measurable_limit_process htmeas, ← integral_trim hle hgmeas, ← integral_trim hle strongly_measurable_limit_process, ← integral_univ, this 0 _ measurable_set.univ, integral_univ, ht (measure_lt_top _ _)] }, { rintro f hf hfmeas heq -, rw [integral_Union (λ n, hle _ (hfmeas n)) hf hg.integrable_on, integral_Union (λ n, hle _ (hfmeas n)) hf hlimint.integrable_on], exact tsum_congr (λ n, heq _ (measure_lt_top _ _)) } end /-- Part c of the **L¹ martingale convergnce theorem**: Given a integrable function `g` which is measurable with respect to `⨆ n, ℱ n` where `ℱ` is a filtration, the martingale defined by `𝔼[g | ℱ n]` converges in L¹ to `g`. This martingale also converges to `g` almost everywhere and this result is provided by `measure_theory.integrable.tendsto_ae_condexp` -/ lemma integrable.tendsto_snorm_condexp (hg : integrable g μ) (hgmeas : strongly_measurable[⨆ n, ℱ n] g) : tendsto (λ n, snorm (μ[g | ℱ n] - g) 1 μ) at_top (𝓝 0) := tendsto_Lp_of_tendsto_in_measure _ le_rfl ennreal.one_ne_top (λ n, (strongly_measurable_condexp.mono (ℱ.le n)).ae_strongly_measurable) (mem_ℒp_one_iff_integrable.2 hg) (hg.uniform_integrable_condexp_filtration).2.1 (tendsto_in_measure_of_tendsto_ae (λ n,(strongly_measurable_condexp.mono (ℱ.le n)).ae_strongly_measurable) (hg.tendsto_ae_condexp hgmeas)) /-- **Lévy's upward theorem**, almost everywhere version: given a function `g` and a filtration `ℱ`, the sequence defined by `𝔼[g | ℱ n]` converges almost everywhere to `𝔼[g | ⨆ n, ℱ n]`. -/ lemma tendsto_ae_condexp (g : Ω → ℝ) : ∀ᵐ x ∂μ, tendsto (λ n, μ[g | ℱ n] x) at_top (𝓝 (μ[g | ⨆ n, ℱ n] x)) := begin have ht : ∀ᵐ x ∂μ, tendsto (λ n, μ[μ[g | ⨆ n, ℱ n] | ℱ n] x) at_top (𝓝 (μ[g | ⨆ n, ℱ n] x)) := integrable_condexp.tendsto_ae_condexp strongly_measurable_condexp, have heq : ∀ n, ∀ᵐ x ∂μ, μ[μ[g | ⨆ n, ℱ n] | ℱ n] x = μ[g | ℱ n] x := λ n, condexp_condexp_of_le (le_supr _ n) (supr_le (λ n, ℱ.le n)), rw ← ae_all_iff at heq, filter_upwards [heq, ht] with x hxeq hxt, exact hxt.congr hxeq, end /-- **Lévy's upward theorem**, L¹ version: given a function `g` and a filtration `ℱ`, the sequence defined by `𝔼[g | ℱ n]` converges in L¹ to `𝔼[g | ⨆ n, ℱ n]`. -/ lemma tendsto_snorm_condexp (g : Ω → ℝ) : tendsto (λ n, snorm (μ[g | ℱ n] - μ[g | ⨆ n, ℱ n]) 1 μ) at_top (𝓝 0) := begin have ht : tendsto (λ n, snorm (μ[μ[g | ⨆ n, ℱ n] | ℱ n] - μ[g | ⨆ n, ℱ n]) 1 μ) at_top (𝓝 0) := integrable_condexp.tendsto_snorm_condexp strongly_measurable_condexp, have heq : ∀ n, ∀ᵐ x ∂μ, μ[μ[g | ⨆ n, ℱ n] | ℱ n] x = μ[g | ℱ n] x := λ n, condexp_condexp_of_le (le_supr _ n) (supr_le (λ n, ℱ.le n)), refine ht.congr (λ n, snorm_congr_ae _), filter_upwards [heq n] with x hxeq, simp only [hxeq, pi.sub_apply], end end L1_convergence end measure_theory
adebcb003d62304a4d9adcbfd8dbf557b94912dd
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/print_ax1.lean
ed0c9f99cd3e1039a0b88bdbb9d207bca34168f9
[ "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
26
lean
open subtype print axioms
db68960a682a98b960b01b1cb24dcebe1645775a
7282d49021d38dacd06c4ce45a48d09627687fe0
/src/builtin/kernel.lean
15659f2651b0a989277685db729b351f232f432b
[ "Apache-2.0" ]
permissive
steveluc/lean
5a0b4431acefaf77f15b25bbb49294c2449923ad
92ba4e8b2d040a799eda7deb8d2a7cdd3e69c496
refs/heads/master
1,611,332,256,930
1,391,013,244,000
1,391,013,244,000
16,361,079
1
0
null
null
null
null
UTF-8
Lean
false
false
26,133
lean
import macros universe U ≥ 1 definition TypeU := (Type U) variable Bool : Type -- The following builtin declarations can be removed as soon as Lean supports inductive datatypes and match expressions builtin true : Bool builtin false : Bool definition not (a : Bool) := a → false notation 40 ¬ _ : not definition or (a b : Bool) := ¬ a → b infixr 30 || : or infixr 30 \/ : or infixr 30 ∨ : or definition and (a b : Bool) := ¬ (a → ¬ b) infixr 35 && : and infixr 35 /\ : and infixr 35 ∧ : and definition implies (a b : Bool) := a → b builtin eq {A : (Type U)} (a b : A) : Bool infix 50 = : eq definition neq {A : TypeU} (a b : A) := ¬ (a = b) infix 50 ≠ : neq definition iff (a b : Bool) := a = b infixr 25 <-> : iff infixr 25 ↔ : iff -- The Lean parser has special treatment for the constant exists. -- It allows us to write -- exists x y : A, P x y and ∃ x y : A, P x y -- as syntax sugar for -- exists A (fun x : A, exists A (fun y : A, P x y)) -- That is, it treats the exists as an extra binder such as fun and forall. -- It also provides an alias (Exists) that should be used when we -- want to treat exists as a constant. definition Exists (A : TypeU) (P : A → Bool) := ¬ (∀ x, ¬ (P x)) definition nonempty (A : TypeU) := ∃ x : A, true -- If we have an element of type A, then A is nonempty theorem nonempty_intro {A : TypeU} (a : A) : nonempty A := assume H : (∀ x, ¬ true), (H a) theorem em (a : Bool) : a ∨ ¬ a := assume Hna : ¬ a, Hna axiom case (P : Bool → Bool) (H1 : P true) (H2 : P false) (a : Bool) : P a axiom refl {A : TypeU} (a : A) : a = a axiom subst {A : TypeU} {a b : A} {P : A → Bool} (H1 : P a) (H2 : a = b) : P b -- Function extensionality axiom funext {A : TypeU} {B : A → TypeU} {f g : ∀ x : A, B x} (H : ∀ x : A, f x = g x) : f = g -- Forall extensionality axiom allext {A : TypeU} {B C : A → Bool} (H : ∀ x : A, B x = C x) : (∀ x : A, B x) = (∀ x : A, C x) -- Epsilon (Hilbert's operator) variable eps {A : TypeU} (H : nonempty A) (P : A → Bool) : A alias ε : eps axiom eps_ax {A : TypeU} (H : nonempty A) {P : A → Bool} (a : A) : P a → P (ε H P) -- Proof irrelevance axiom proof_irrel {a : Bool} (H1 H2 : a) : H1 = H2 theorem eps_th {A : TypeU} {P : A → Bool} (a : A) : P a → P (ε (nonempty_intro a) P) := assume H : P a, @eps_ax A (nonempty_intro a) P a H -- Alias for subst where we can provide P explicitly, but keep A,a,b implicit theorem substp {A : TypeU} {a b : A} (P : A → Bool) (H1 : P a) (H2 : a = b) : P b := subst H1 H2 -- We will mark not as opaque later theorem not_intro {a : Bool} (H : a → false) : ¬ a := H theorem eta {A : TypeU} {B : A → TypeU} (f : ∀ x : A, B x) : (λ x : A, f x) = f := funext (λ x : A, refl (f x)) -- create default rewrite rule set (* mk_rewrite_rule_set() *) theorem trivial : true := refl true theorem absurd {a : Bool} (H1 : a) (H2 : ¬ a) : false := H2 H1 theorem eqmp {a b : Bool} (H1 : a = b) (H2 : a) : b := subst H2 H1 infixl 100 <| : eqmp infixl 100 ◂ : eqmp theorem boolcomplete (a : Bool) : a = true ∨ a = false := case (λ x, x = true ∨ x = false) trivial trivial a theorem false_elim (a : Bool) (H : false) : a := case (λ x, x) trivial H a theorem imp_trans {a b c : Bool} (H1 : a → b) (H2 : b → c) : a → c := assume Ha, H2 (H1 Ha) theorem imp_eq_trans {a b c : Bool} (H1 : a → b) (H2 : b = c) : a → c := assume Ha, H2 ◂ (H1 Ha) theorem eq_imp_trans {a b c : Bool} (H1 : a = b) (H2 : b → c) : a → c := assume Ha, H2 (H1 ◂ Ha) theorem not_not_eq (a : Bool) : ¬ ¬ a ↔ a := case (λ x, ¬ ¬ x ↔ x) trivial trivial a theorem not_not_elim {a : Bool} (H : ¬ ¬ a) : a := (not_not_eq a) ◂ H theorem mt {a b : Bool} (H1 : a → b) (H2 : ¬ b) : ¬ a := assume Ha : a, absurd (H1 Ha) H2 theorem contrapos {a b : Bool} (H : a → b) : ¬ b → ¬ a := assume Hnb : ¬ b, mt H Hnb theorem absurd_elim {a : Bool} (b : Bool) (H1 : a) (H2 : ¬ a) : b := false_elim b (absurd H1 H2) theorem not_imp_eliml {a b : Bool} (Hnab : ¬ (a → b)) : a := not_not_elim (have ¬ ¬ a : assume Hna : ¬ a, absurd (assume Ha : a, absurd_elim b Ha Hna) Hnab) theorem not_imp_elimr {a b : Bool} (H : ¬ (a → b)) : ¬ b := assume Hb : b, absurd (assume Ha : a, Hb) H theorem resolve1 {a b : Bool} (H1 : a ∨ b) (H2 : ¬ a) : b := H1 H2 -- Recall that and is defined as ¬ (a → ¬ b) theorem and_intro {a b : Bool} (H1 : a) (H2 : b) : a ∧ b := assume H : a → ¬ b, absurd H2 (H H1) theorem and_eliml {a b : Bool} (H : a ∧ b) : a := not_imp_eliml H theorem and_elimr {a b : Bool} (H : a ∧ b) : b := not_not_elim (not_imp_elimr H) -- Recall that or is defined as ¬ a → b theorem or_introl {a : Bool} (H : a) (b : Bool) : a ∨ b := assume H1 : ¬ a, absurd_elim b H H1 theorem or_intror {b : Bool} (a : Bool) (H : b) : a ∨ b := assume H1 : ¬ a, H theorem or_elim {a b c : Bool} (H1 : a ∨ b) (H2 : a → c) (H3 : b → c) : c := not_not_elim (assume H : ¬ c, absurd (have c : H3 (have b : resolve1 H1 (have ¬ a : (mt (assume Ha : a, H2 Ha) H)))) H) theorem refute {a : Bool} (H : ¬ a → false) : a := or_elim (em a) (λ H1 : a, H1) (λ H1 : ¬ a, false_elim a (H H1)) theorem symm {A : TypeU} {a b : A} (H : a = b) : b = a := subst (refl a) H theorem eqmpr {a b : Bool} (H1 : a = b) (H2 : b) : a := (symm H1) ◂ H2 theorem trans {A : TypeU} {a b c : A} (H1 : a = b) (H2 : b = c) : a = c := subst H1 H2 theorem ne_symm {A : TypeU} {a b : A} (H : a ≠ b) : b ≠ a := assume H1 : b = a, H (symm H1) theorem eq_ne_trans {A : TypeU} {a b c : A} (H1 : a = b) (H2 : b ≠ c) : a ≠ c := subst H2 (symm H1) theorem ne_eq_trans {A : TypeU} {a b c : A} (H1 : a ≠ b) (H2 : b = c) : a ≠ c := subst H1 H2 theorem eqt_elim {a : Bool} (H : a = true) : a := (symm H) ◂ trivial theorem eqf_elim {a : Bool} (H : a = false) : ¬ a := not_intro (λ Ha : a, H ◂ Ha) theorem congr1 {A B : TypeU} {f g : A → B} (a : A) (H : f = g) : f a = g a := substp (fun h : A → B, f a = h a) (refl (f a)) H theorem congr2 {A B : TypeU} {a b : A} (f : A → B) (H : a = b) : f a = f b := substp (fun x : A, f a = f x) (refl (f a)) H theorem congr {A B : TypeU} {f g : A → B} {a b : A} (H1 : f = g) (H2 : a = b) : f a = g b := subst (congr2 f H2) (congr1 b H1) -- Recall that exists is defined as ¬ ∀ x : A, ¬ P x theorem exists_elim {A : TypeU} {P : A → Bool} {B : Bool} (H1 : Exists A P) (H2 : ∀ (a : A) (H : P a), B) : B := refute (λ R : ¬ B, absurd (take a : A, mt (assume H : P a, H2 a H) R) H1) theorem exists_intro {A : TypeU} {P : A → Bool} (a : A) (H : P a) : Exists A P := assume H1 : (∀ x : A, ¬ P x), absurd H (H1 a) theorem nonempty_elim {A : TypeU} (H1 : nonempty A) {B : Bool} (H2 : A → B) : B := obtain (w : A) (Hw : true), from H1, H2 w theorem nonempty_ex_intro {A : TypeU} {P : A → Bool} (H : ∃ x, P x) : nonempty A := obtain (w : A) (Hw : P w), from H, exists_intro w trivial theorem exists_to_eps {A : TypeU} {P : A → Bool} (H : ∃ x, P x) : P (ε (nonempty_ex_intro H) P) := obtain (w : A) (Hw : P w), from H, eps_ax (nonempty_ex_intro H) w Hw theorem axiom_of_choice {A : TypeU} {B : A → TypeU} {R : ∀ x : A, B x → Bool} (H : ∀ x, ∃ y, R x y) : ∃ f, ∀ x, R x (f x) := exists_intro (λ x, ε (nonempty_ex_intro (H x)) (λ y, R x y)) -- witness for f (λ x, exists_to_eps (H x)) -- proof that witness satisfies ∀ x, R x (f x) theorem boolext {a b : Bool} (Hab : a → b) (Hba : b → a) : a = b := or_elim (boolcomplete a) (λ Hat : a = true, or_elim (boolcomplete b) (λ Hbt : b = true, trans Hat (symm Hbt)) (λ Hbf : b = false, false_elim (a = b) (subst (Hab (eqt_elim Hat)) Hbf))) (λ Haf : a = false, or_elim (boolcomplete b) (λ Hbt : b = true, false_elim (a = b) (subst (Hba (eqt_elim Hbt)) Haf)) (λ Hbf : b = false, trans Haf (symm Hbf))) theorem iff_intro {a b : Bool} (Hab : a → b) (Hba : b → a) : a ↔ b := boolext Hab Hba theorem iff_eliml {a b : Bool} (H : a ↔ b) : a → b := (λ Ha : a, eqmp H Ha) theorem iff_elimr {a b : Bool} (H : a ↔ b) : b → a := (λ Hb : b, eqmpr H Hb) theorem skolem_th {A : TypeU} {B : A → TypeU} {P : ∀ x : A, B x → Bool} : (∀ x, ∃ y, P x y) ↔ ∃ f, (∀ x, P x (f x)) := iff_intro (λ H : (∀ x, ∃ y, P x y), axiom_of_choice H) (λ H : (∃ f, (∀ x, P x (f x))), take x, obtain (fw : ∀ x, B x) (Hw : ∀ x, P x (fw x)), from H, exists_intro (fw x) (Hw x)) theorem eqt_intro {a : Bool} (H : a) : a = true := boolext (assume H1 : a, trivial) (assume H2 : true, H) theorem eqf_intro {a : Bool} (H : ¬ a) : a = false := boolext (assume H1 : a, absurd H1 H) (assume H2 : false, false_elim a H2) theorem neq_elim {A : TypeU} {a b : A} (H : a ≠ b) : a = b ↔ false := eqf_intro H theorem eq_id {A : TypeU} (a : A) : (a = a) ↔ true := eqt_intro (refl a) theorem iff_id (a : Bool) : (a ↔ a) ↔ true := eqt_intro (refl a) theorem or_comm (a b : Bool) : (a ∨ b) = (b ∨ a) := boolext (assume H, or_elim H (λ H1, or_intror b H1) (λ H2, or_introl H2 a)) (assume H, or_elim H (λ H1, or_intror a H1) (λ H2, or_introl H2 b)) theorem or_assoc (a b c : Bool) : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := boolext (assume H : (a ∨ b) ∨ c, or_elim H (λ H1 : a ∨ b, or_elim H1 (λ Ha : a, or_introl Ha (b ∨ c)) (λ Hb : b, or_intror a (or_introl Hb c))) (λ Hc : c, or_intror a (or_intror b Hc))) (assume H : a ∨ (b ∨ c), or_elim H (λ Ha : a, (or_introl (or_introl Ha b) c)) (λ H1 : b ∨ c, or_elim H1 (λ Hb : b, or_introl (or_intror a Hb) c) (λ Hc : c, or_intror (a ∨ b) Hc))) theorem or_id (a : Bool) : a ∨ a ↔ a := boolext (assume H, or_elim H (λ H1, H1) (λ H2, H2)) (assume H, or_introl H a) theorem or_falsel (a : Bool) : a ∨ false ↔ a := boolext (assume H, or_elim H (λ H1, H1) (λ H2, false_elim a H2)) (assume H, or_introl H false) theorem or_falser (a : Bool) : false ∨ a ↔ a := trans (or_comm false a) (or_falsel a) theorem or_truel (a : Bool) : true ∨ a ↔ true := eqt_intro (case (λ x : Bool, true ∨ x) trivial trivial a) theorem or_truer (a : Bool) : a ∨ true ↔ true := trans (or_comm a true) (or_truel a) theorem or_tauto (a : Bool) : a ∨ ¬ a ↔ true := eqt_intro (em a) theorem and_comm (a b : Bool) : a ∧ b ↔ b ∧ a := boolext (assume H, and_intro (and_elimr H) (and_eliml H)) (assume H, and_intro (and_elimr H) (and_eliml H)) theorem and_id (a : Bool) : a ∧ a ↔ a := boolext (assume H, and_eliml H) (assume H, and_intro H H) theorem and_assoc (a b c : Bool) : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := boolext (assume H, and_intro (and_eliml (and_eliml H)) (and_intro (and_elimr (and_eliml H)) (and_elimr H))) (assume H, and_intro (and_intro (and_eliml H) (and_eliml (and_elimr H))) (and_elimr (and_elimr H))) theorem and_truer (a : Bool) : a ∧ true ↔ a := boolext (assume H : a ∧ true, and_eliml H) (assume H : a, and_intro H trivial) theorem and_truel (a : Bool) : true ∧ a ↔ a := trans (and_comm true a) (and_truer a) theorem and_falsel (a : Bool) : a ∧ false ↔ false := boolext (assume H, and_elimr H) (assume H, false_elim (a ∧ false) H) theorem and_falser (a : Bool) : false ∧ a ↔ false := trans (and_comm false a) (and_falsel a) theorem and_absurd (a : Bool) : a ∧ ¬ a ↔ false := boolext (assume H, absurd (and_eliml H) (and_elimr H)) (assume H, false_elim (a ∧ ¬ a) H) theorem imp_truer (a : Bool) : (a → true) ↔ true := case (λ x, (x → true) ↔ true) trivial trivial a theorem imp_truel (a : Bool) : (true → a) ↔ a := case (λ x, (true → x) ↔ x) trivial trivial a theorem imp_falser (a : Bool) : (a → false) ↔ ¬ a := refl _ theorem imp_falsel (a : Bool) : (false → a) ↔ true := case (λ x, (false → x) ↔ true) trivial trivial a theorem imp_id (a : Bool) : (a → a) ↔ true := eqt_intro (λ H : a, H) theorem imp_or (a b : Bool) : (a → b) ↔ ¬ a ∨ b := iff_intro (assume H : a → b, (or_elim (em a) (λ Ha : a, or_intror (¬ a) (H Ha)) (λ Hna : ¬ a, or_introl Hna b))) (assume H : ¬ a ∨ b, assume Ha : a, resolve1 H ((symm (not_not_eq a)) ◂ Ha)) theorem not_true : ¬ true ↔ false := trivial theorem not_false : ¬ false ↔ true := trivial theorem not_neq {A : TypeU} (a b : A) : ¬ (a ≠ b) ↔ a = b := not_not_eq (a = b) theorem not_neq_elim {A : TypeU} {a b : A} (H : ¬ (a ≠ b)) : a = b := (not_neq a b) ◂ H theorem not_and (a b : Bool) : ¬ (a ∧ b) ↔ ¬ a ∨ ¬ b := case (λ x, ¬ (x ∧ b) ↔ ¬ x ∨ ¬ b) (case (λ y, ¬ (true ∧ y) ↔ ¬ true ∨ ¬ y) trivial trivial b) (case (λ y, ¬ (false ∧ y) ↔ ¬ false ∨ ¬ y) trivial trivial b) a theorem not_and_elim {a b : Bool} (H : ¬ (a ∧ b)) : ¬ a ∨ ¬ b := (not_and a b) ◂ H theorem not_or (a b : Bool) : ¬ (a ∨ b) ↔ ¬ a ∧ ¬ b := case (λ x, ¬ (x ∨ b) ↔ ¬ x ∧ ¬ b) (case (λ y, ¬ (true ∨ y) ↔ ¬ true ∧ ¬ y) trivial trivial b) (case (λ y, ¬ (false ∨ y) ↔ ¬ false ∧ ¬ y) trivial trivial b) a theorem not_or_elim {a b : Bool} (H : ¬ (a ∨ b)) : ¬ a ∧ ¬ b := (not_or a b) ◂ H theorem not_iff (a b : Bool) : ¬ (a ↔ b) ↔ (¬ a ↔ b) := case (λ x, ¬ (x ↔ b) ↔ ((¬ x) ↔ b)) (case (λ y, ¬ (true ↔ y) ↔ ((¬ true) ↔ y)) trivial trivial b) (case (λ y, ¬ (false ↔ y) ↔ ((¬ false) ↔ y)) trivial trivial b) a theorem not_iff_elim {a b : Bool} (H : ¬ (a ↔ b)) : (¬ a) ↔ b := (not_iff a b) ◂ H theorem not_implies (a b : Bool) : ¬ (a → b) ↔ a ∧ ¬ b := case (λ x, ¬ (x → b) ↔ x ∧ ¬ b) (case (λ y, ¬ (true → y) ↔ true ∧ ¬ y) trivial trivial b) (case (λ y, ¬ (false → y) ↔ false ∧ ¬ y) trivial trivial b) a theorem not_implies_elim {a b : Bool} (H : ¬ (a → b)) : a ∧ ¬ b := (not_implies a b) ◂ H theorem not_congr {a b : Bool} (H : a ↔ b) : ¬ a ↔ ¬ b := congr2 not H theorem exists_rem {A : TypeU} (H : nonempty A) (p : Bool) : (∃ x : A, p) ↔ p := iff_intro (assume Hl : (∃ x : A, p), obtain (w : A) (Hw : p), from Hl, Hw) (assume Hr : p, nonempty_elim H (λ w, exists_intro w Hr)) theorem forall_rem {A : TypeU} (H : nonempty A) (p : Bool) : (∀ x : A, p) ↔ p := iff_intro (assume Hl : (∀ x : A, p), nonempty_elim H (λ w, Hl w)) (assume Hr : p, take x, Hr) theorem eq_exists_intro {A : (Type U)} {P Q : A → Bool} (H : ∀ x : A, P x ↔ Q x) : (∃ x : A, P x) ↔ (∃ x : A, Q x) := congr2 (Exists A) (funext H) theorem not_forall (A : (Type U)) (P : A → Bool) : ¬ (∀ x : A, P x) ↔ (∃ x : A, ¬ P x) := calc (¬ ∀ x : A, P x) = ¬ ∀ x : A, ¬ ¬ P x : not_congr (allext (λ x : A, symm (not_not_eq (P x)))) ... = ∃ x : A, ¬ P x : refl (∃ x : A, ¬ P x) theorem not_forall_elim {A : (Type U)} {P : A → Bool} (H : ¬ (∀ x : A, P x)) : ∃ x : A, ¬ P x := (not_forall A P) ◂ H theorem not_exists (A : (Type U)) (P : A → Bool) : ¬ (∃ x : A, P x) ↔ (∀ x : A, ¬ P x) := calc (¬ ∃ x : A, P x) = ¬ ¬ ∀ x : A, ¬ P x : refl (¬ ∃ x : A, P x) ... = ∀ x : A, ¬ P x : not_not_eq (∀ x : A, ¬ P x) theorem not_exists_elim {A : (Type U)} {P : A → Bool} (H : ¬ ∃ x : A, P x) : ∀ x : A, ¬ P x := (not_exists A P) ◂ H theorem exists_unfold1 {A : TypeU} {P : A → Bool} (a : A) (H : ∃ x : A, P x) : P a ∨ (∃ x : A, x ≠ a ∧ P x) := exists_elim H (λ (w : A) (H1 : P w), or_elim (em (w = a)) (λ Heq : w = a, or_introl (subst H1 Heq) (∃ x : A, x ≠ a ∧ P x)) (λ Hne : w ≠ a, or_intror (P a) (exists_intro w (and_intro Hne H1)))) theorem exists_unfold2 {A : TypeU} {P : A → Bool} (a : A) (H : P a ∨ (∃ x : A, x ≠ a ∧ P x)) : ∃ x : A, P x := or_elim H (λ H1 : P a, exists_intro a H1) (λ H2 : (∃ x : A, x ≠ a ∧ P x), exists_elim H2 (λ (w : A) (Hw : w ≠ a ∧ P w), exists_intro w (and_elimr Hw))) theorem exists_unfold {A : TypeU} (P : A → Bool) (a : A) : (∃ x : A, P x) ↔ (P a ∨ (∃ x : A, x ≠ a ∧ P x)) := boolext (assume H : (∃ x : A, P x), exists_unfold1 a H) (assume H : (P a ∨ (∃ x : A, x ≠ a ∧ P x)), exists_unfold2 a H) -- Remark: ordered rewriting + assoc + comm + left_comm sorts a term lexicographically theorem left_comm {A : TypeU} {R : A -> A -> A} (comm : ∀ x y, R x y = R y x) (assoc : ∀ x y z, R (R x y) z = R x (R y z)) : ∀ x y z, R x (R y z) = R y (R x z) := take x y z, calc R x (R y z) = R (R x y) z : symm (assoc x y z) ... = R (R y x) z : { comm x y } ... = R y (R x z) : assoc y x z theorem and_left_comm (a b c : Bool) : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := left_comm and_comm and_assoc a b c theorem or_left_comm (a b c : Bool) : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := left_comm or_comm or_assoc a b c -- Congruence theorems for contextual simplification -- Simplify a → b, by first simplifying a to c using the fact that ¬ b is true, and then -- b to d using the fact that c is true theorem imp_congrr {a b c d : Bool} (H_ac : ∀ (H_nb : ¬ b), a = c) (H_bd : ∀ (H_c : c), b = d) : (a → b) = (c → d) := or_elim (em b) (λ H_b : b, or_elim (em c) (λ H_c : c, calc (a → b) = (a → true) : { eqt_intro H_b } ... = true : imp_truer a ... = (c → true) : symm (imp_truer c) ... = (c → b) : { symm (eqt_intro H_b) } ... = (c → d) : { H_bd H_c }) (λ H_nc : ¬ c, calc (a → b) = (a → true) : { eqt_intro H_b } ... = true : imp_truer a ... = (false → d) : symm (imp_falsel d) ... = (c → d) : { symm (eqf_intro H_nc) })) (λ H_nb : ¬ b, or_elim (em c) (λ H_c : c, calc (a → b) = (c → b) : { H_ac H_nb } ... = (c → d) : { H_bd H_c }) (λ H_nc : ¬ c, calc (a → b) = (c → b) : { H_ac H_nb } ... = (false → b) : { eqf_intro H_nc } ... = true : imp_falsel b ... = (false → d) : symm (imp_falsel d) ... = (c → d) : { symm (eqf_intro H_nc) })) -- Simplify a → b, by first simplifying b to d using the fact that a is true, and then -- b to d using the fact that ¬ d is true. -- This kind of congruence seems to be useful in very rare cases. theorem imp_congrl {a b c d : Bool} (H_bd : ∀ (H_a : a), b = d) (H_ac : ∀ (H_nd : ¬ d), a = c) : (a → b) = (c → d) := or_elim (em a) (λ H_a : a, or_elim (em d) (λ H_d : d, calc (a → b) = (a → d) : { H_bd H_a } ... = (a → true) : { eqt_intro H_d } ... = true : imp_truer a ... = (c → true) : symm (imp_truer c) ... = (c → d) : { symm (eqt_intro H_d) }) (λ H_nd : ¬ d, calc (a → b) = (c → b) : { H_ac H_nd } ... = (c → d) : { H_bd H_a })) (λ H_na : ¬ a, or_elim (em d) (λ H_d : d, calc (a → b) = (false → b) : { eqf_intro H_na } ... = true : imp_falsel b ... = (c → true) : symm (imp_truer c) ... = (c → d) : { symm (eqt_intro H_d) }) (λ H_nd : ¬ d, calc (a → b) = (false → b) : { eqf_intro H_na } ... = true : imp_falsel b ... = (false → d) : symm (imp_falsel d) ... = (a → d) : { symm (eqf_intro H_na) } ... = (c → d) : { H_ac H_nd })) -- (Common case) simplify a to c, and then b to d using the fact that c is true theorem imp_congr {a b c d : Bool} (H_ac : a = c) (H_bd : ∀ (H_c : c), b = d) : (a → b) = (c → d) := imp_congrr (λ H, H_ac) H_bd -- In the following theorems we are using the fact that a ∨ b is defined as ¬ a → b theorem or_congrr {a b c d : Bool} (H_ac : ∀ (H_nb : ¬ b), a = c) (H_bd : ∀ (H_nc : ¬ c), b = d) : a ∨ b ↔ c ∨ d := imp_congrr (λ H_nb : ¬ b, congr2 not (H_ac H_nb)) H_bd theorem or_congrl {a b c d : Bool} (H_bd : ∀ (H_na : ¬ a), b = d) (H_ac : ∀ (H_nd : ¬ d), a = c) : a ∨ b ↔ c ∨ d := imp_congrl H_bd (λ H_nd : ¬ d, congr2 not (H_ac H_nd)) -- (Common case) simplify a to c, and then b to d using the fact that ¬ c is true theorem or_congr {a b c d : Bool} (H_ac : a = c) (H_bd : ∀ (H_nc : ¬ c), b = d) : a ∨ b ↔ c ∨ d := or_congrr (λ H, H_ac) H_bd -- In the following theorems we are using the fact hat a ∧ b is defined as ¬ (a → ¬ b) theorem and_congrr {a b c d : Bool} (H_ac : ∀ (H_b : b), a = c) (H_bd : ∀ (H_c : c), b = d) : a ∧ b ↔ c ∧ d := congr2 not (imp_congrr (λ (H_nnb : ¬ ¬ b), H_ac (not_not_elim H_nnb)) (λ H_c : c, congr2 not (H_bd H_c))) theorem and_congrl {a b c d : Bool} (H_bd : ∀ (H_a : a), b = d) (H_ac : ∀ (H_d : d), a = c) : a ∧ b ↔ c ∧ d := congr2 not (imp_congrl (λ H_a : a, congr2 not (H_bd H_a)) (λ (H_nnd : ¬ ¬ d), H_ac (not_not_elim H_nnd))) -- (Common case) simplify a to c, and then b to d using the fact that c is true theorem and_congr {a b c d : Bool} (H_ac : a = c) (H_bd : ∀ (H_c : c), b = d) : a ∧ b ↔ c ∧ d := and_congrr (λ H, H_ac) H_bd theorem forall_or_distributer {A : TypeU} (p : Bool) (φ : A → Bool) : (∀ x, p ∨ φ x) = (p ∨ ∀ x, φ x) := boolext (assume H : (∀ x, p ∨ φ x), or_elim (em p) (λ Hp : p, or_introl Hp (∀ x, φ x)) (λ Hnp : ¬ p, or_intror p (take x, resolve1 (H x) Hnp))) (assume H : (p ∨ ∀ x, φ x), take x, or_elim H (λ H1 : p, or_introl H1 (φ x)) (λ H2 : (∀ x, φ x), or_intror p (H2 x))) theorem forall_or_distributel {A : Type} (p : Bool) (φ : A → Bool) : (∀ x, φ x ∨ p) = ((∀ x, φ x) ∨ p) := calc (∀ x, φ x ∨ p) = (∀ x, p ∨ φ x) : allext (λ x, or_comm (φ x) p) ... = (p ∨ ∀ x, φ x) : forall_or_distributer p φ ... = ((∀ x, φ x) ∨ p) : or_comm p (∀ x, φ x) theorem forall_and_distribute {A : TypeU} (φ ψ : A → Bool) : (∀ x, φ x ∧ ψ x) ↔ (∀ x, φ x) ∧ (∀ x, ψ x) := boolext (assume H : (∀ x, φ x ∧ ψ x), and_intro (take x, and_eliml (H x)) (take x, and_elimr (H x))) (assume H : (∀ x, φ x) ∧ (∀ x, ψ x), take x, and_intro (and_eliml H x) (and_elimr H x)) theorem exists_and_distributer {A : TypeU} (p : Bool) (φ : A → Bool) : (∃ x, p ∧ φ x) ↔ p ∧ ∃ x, φ x := boolext (assume H : (∃ x, p ∧ φ x), obtain (w : A) (Hw : p ∧ φ w), from H, and_intro (and_eliml Hw) (exists_intro w (and_elimr Hw))) (assume H : (p ∧ ∃ x, φ x), obtain (w : A) (Hw : φ w), from (and_elimr H), exists_intro w (and_intro (and_eliml H) Hw)) theorem exists_and_distributel {A : TypeU} (p : Bool) (φ : A → Bool) : (∃ x, φ x ∧ p) ↔ (∃ x, φ x) ∧ p := calc (∃ x, φ x ∧ p) = (∃ x, p ∧ φ x) : eq_exists_intro (λ x, and_comm (φ x) p) ... = (p ∧ (∃ x, φ x)) : exists_and_distributer p φ ... = ((∃ x, φ x) ∧ p) : and_comm p (∃ x, φ x) theorem exists_or_distribute {A : TypeU} (φ ψ : A → Bool) : (∃ x, φ x ∨ ψ x) ↔ (∃ x, φ x) ∨ (∃ x, ψ x) := boolext (assume H : (∃ x, φ x ∨ ψ x), obtain (w : A) (Hw : φ w ∨ ψ w), from H, or_elim Hw (λ Hw1 : φ w, or_introl (exists_intro w Hw1) (∃ x, ψ x)) (λ Hw2 : ψ w, or_intror (∃ x, φ x) (exists_intro w Hw2))) (assume H : (∃ x, φ x) ∨ (∃ x, ψ x), or_elim H (λ H1 : (∃ x, φ x), obtain (w : A) (Hw : φ w), from H1, exists_intro w (or_introl Hw (ψ w))) (λ H2 : (∃ x, ψ x), obtain (w : A) (Hw : ψ w), from H2, exists_intro w (or_intror (φ w) Hw))) theorem exists_imp_distribute {A : TypeU} (φ ψ : A → Bool) : (∃ x, φ x → ψ x) ↔ ((∀ x, φ x) → (∃ x, ψ x)) := calc (∃ x, φ x → ψ x) = (∃ x, ¬ φ x ∨ ψ x) : eq_exists_intro (λ x, imp_or (φ x) (ψ x)) ... = (∃ x, ¬ φ x) ∨ (∃ x, ψ x) : exists_or_distribute _ _ ... = ¬ (∀ x, φ x) ∨ (∃ x, ψ x) : { symm (not_forall A φ) } ... = (∀ x, φ x) → (∃ x, ψ x) : symm (imp_or _ _) set_opaque exists true set_opaque not true set_opaque or true set_opaque and true set_opaque implies true
5e7e22dd820383d5f9c0fca80a8c537d450a3cd6
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/data/array/slice.lean
4898a8a838738e16dc917cbbc72c04742ee708ec
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
1,305
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ prelude import init.data.nat init.data.array.basic init.data.nat.lemmas universes u variables {α : Type u} {n : nat} namespace array def slice (a : array n α) (k l : nat) (h₁ : k ≤ l) (h₂ : l ≤ n) : array (l - k) α := ⟨ λ ⟨ i, hi ⟩, a.read ⟨ i + k, calc i + k < (l - k) + k : add_lt_add_right hi _ ... = l : nat.sub_add_cancel h₁ ... ≤ n : h₂⟩ ⟩ def take (a : array n α) (m : nat) (h : m ≤ n) : array m α := cast (by simp) $ a.slice 0 m (nat.zero_le _) h def drop (a : array n α) (m : nat) (h : m ≤ n) : array (n-m) α := a.slice m n h (le_refl _) private lemma sub_sub_cancel (m n : ℕ) (h : m ≤ n) : n - (n - m) = m := calc n - (n - m) = (n - m) + m - (n - m) : by rw nat.sub_add_cancel; assumption ... = m : nat.add_sub_cancel_left _ _ def take_right (a : array n α) (m : nat) (h : m ≤ n) : array m α := cast (by simp [*, sub_sub_cancel]) $ a.drop (n - m) (nat.sub_le _ _) def reverse (a : array n α) : array n α := ⟨ λ ⟨ i, hi ⟩, a.read ⟨ n - (i + 1), begin apply nat.sub_lt_of_pos_le, apply nat.zero_lt_succ, assumption end ⟩ ⟩ end array
48c1ea36307d2e216ba8af09123c425427f906d2
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/order/category/LinearOrder.lean
fd5e616315cb5931d3a6b90ef7cac0883001bc8e
[ "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
811
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import order.category.PartialOrder /-! # Category of linearly ordered types -/ open category_theory /-- The category of linearly ordered types. -/ def LinearOrder := bundled linear_order namespace LinearOrder instance : bundled_hom.parent_projection @linear_order.to_partial_order := ⟨⟩ attribute [derive [has_coe_to_sort, large_category, concrete_category]] LinearOrder /-- Construct a bundled LinearOrder from the underlying type and typeclass. -/ def of (α : Type*) [linear_order α] : LinearOrder := bundled.of α instance : inhabited LinearOrder := ⟨of punit⟩ instance (α : LinearOrder) : linear_order α := α.str end LinearOrder
70fb2572b11126989ea2d32e2bf9c3f9e8c1714b
c45b34bfd44d8607a2e8762c926e3cfaa7436201
/uexp/src/uexp/rules/removeSemiJoinRight.lean
77f5dae940f9d38979dd577bd15d8192525dd052
[ "BSD-2-Clause" ]
permissive
Shamrock-Frost/Cosette
b477c442c07e45082348a145f19ebb35a7f29392
24cbc4adebf627f13f5eac878f04ffa20d1209af
refs/heads/master
1,619,721,304,969
1,526,082,841,000
1,526,082,841,000
121,695,605
1
0
null
1,518,737,210,000
1,518,737,210,000
null
UTF-8
Lean
false
false
1,486
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..ucongr import ..TDP set_option profiler true open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int theorem rule: forall ( Γ scm_dept scm_emp: Schema) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL ((SELECT1 (right⋅left⋅emp_ename) FROM1 (product (table rel_emp) (product (table rel_dept) (table rel_emp))) WHERE (and (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅left⋅dept_deptno))) (equal (uvariable (right⋅right⋅left⋅dept_deptno)) (uvariable (right⋅right⋅right⋅emp_deptno))))) :SQL Γ _) = denoteSQL ((SELECT1 (right⋅left⋅emp_ename) FROM1 (product (table rel_emp) (product (table rel_dept) (table rel_emp))) WHERE (and (equal (uvariable (right⋅left⋅emp_deptno)) (uvariable (right⋅right⋅left⋅dept_deptno))) (equal (uvariable (right⋅right⋅left⋅dept_deptno)) (uvariable (right⋅right⋅right⋅emp_deptno))))) :SQL Γ _) := begin intros, unfold_all_denotations, funext, try {simp}, try {TDP' ucongr}, end
67da68b952510d2f93bbdf7c30a47268b8215618
ee8cdbabf07f77e7be63a449b8483ce308d37218
/lean/src/valid/mathd-algebra-140.lean
9a2dfb974e90094bd872de4665d01564b5fa9325
[ "MIT", "Apache-2.0" ]
permissive
zeta1999/miniF2F
6d66c75d1c18152e224d07d5eed57624f731d4b7
c1ba9629559c5273c92ec226894baa0c1ce27861
refs/heads/main
1,681,897,460,642
1,620,646,361,000
1,620,646,361,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
436
lean
/- Copyright (c) 2021 OpenAI. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kunhao Zheng -/ import data.real.basic example(a b c : ℝ) (h₀ : 0 < a ∧ 0 < b ∧ 0 < c) (h₁ : ∀ x, 24 * x ^ 2 - 19 * x - 35 = ( ( ( a * x ) - 5 ) * ( ( 2 * ( b * x ) ) + c ) ) ) : a * b - 3 * c = -9 := begin have h₂ := h₁ 0, have h₂ := h₁ 1, have h₃ := h₁ (-1), linarith, end
500d251a5d6bd2b0b50c03b7638e9688b06d7b6b
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Elab/Notation.lean
f7b9a284fde92d144707c575c327ab0536e8b677
[ "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", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
7,366
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Syntax import Lean.Elab.AuxDef import Lean.Elab.BuiltinNotation namespace Lean.Elab.Command open Lean.Syntax open Lean.Parser.Term hiding macroArg open Lean.Parser.Command /-- Wrap all occurrences of the given `ident` nodes in antiquotations -/ private partial def antiquote (vars : Array Syntax) : Syntax → Syntax | stx => match stx with | `($id:ident) => if (vars.findIdx? (fun var => var.getId == id.getId)).isSome then mkAntiquotNode id (kind := `term) (isPseudoKind := true) else stx | _ => match stx with | Syntax.node i k args => Syntax.node i k (args.map (antiquote vars)) | stx => stx def addInheritDocDefault (rhs : Term) (attrs? : Option (TSepArray ``attrInstance ",")) : Option (TSepArray ``attrInstance ",") := attrs?.map fun attrs => match rhs with | `($f:ident $_args*) | `($f:ident) => attrs.getElems.map fun stx => Unhygienic.run do if let `(attrInstance| $attr:ident) := stx then if attr.getId.eraseMacroScopes == `inherit_doc then return ← `(attrInstance| $attr:ident $f:ident) pure ⟨stx⟩ | _ => attrs /-- Convert `notation` command lhs item into a `syntax` command item -/ def expandNotationItemIntoSyntaxItem : TSyntax ``notationItem → MacroM (TSyntax `stx) | `(notationItem| $_:ident$[:$prec?]?) => `(stx| term $[:$prec?]?) | `(notationItem| $s:str) => `(stx| $s:str) | _ => Macro.throwUnsupported /-- Convert `notation` command lhs item into a pattern element -/ def expandNotationItemIntoPattern (stx : Syntax) : MacroM Syntax := let k := stx.getKind if k == `Lean.Parser.Command.identPrec then return mkAntiquotNode stx[0] (kind := `term) (isPseudoKind := true) else if k == strLitKind then strLitToPattern stx else Macro.throwUnsupported def removeParenthesesAux (parens body : Syntax) : Syntax := match parens.getHeadInfo, body.getHeadInfo, body.getTailInfo, parens.getTailInfo with | .original lead _ _ _, .original _ pos trail pos', .original endLead endPos _ endPos', .original _ _ endTrail _ => body.setHeadInfo (.original lead pos trail pos') |>.setTailInfo (.original endLead endPos endTrail endPos') | _, _, _, _ => body partial def removeParentheses (stx : Syntax) : MacroM Syntax := do match stx with | `(($e)) => pure $ removeParenthesesAux stx (←removeParentheses $ (←Term.expandCDot? e).getD e) | _ => match stx with | .node info kind args => pure $ .node info kind (←args.mapM removeParentheses) | _ => pure stx partial def hasDuplicateAntiquot (stxs : Array Syntax) : Bool := Id.run do let mut seen := NameSet.empty for stx in stxs do for node in Syntax.topDown stx true do if node.isAntiquot then let ident := node.getAntiquotTerm.getId if seen.contains ident then return true else seen := seen.insert ident pure false /-- Try to derive a `SimpleDelab` from a notation. The notation must be of the form `notation ... => c body` where `c` is a declaration in the current scope and `body` any syntax that contains each variable from the LHS at most once. -/ def mkSimpleDelab (attrKind : TSyntax ``attrKind) (pat qrhs : Term) : OptionT MacroM Syntax := do let (c, args) ← match qrhs with | `($c:ident $args*) => pure (c, args) | `($c:ident) => pure (c, #[]) | _ => failure let [(c, [])] ← Macro.resolveGlobalName c.getId | failure /- Try to remove all non semantic parenthesis. Since the parenthesizer runs after appUnexpanders we should not match on parenthesis that the user syntax inserted here for example the right hand side of: notation "{" x "|" p "}" => setOf (fun x => p) Should be matched as: setOf fun x => p -/ let args ← liftM <| args.mapM removeParentheses /- The user could mention the same antiquotation from the lhs multiple times on the rhs, this heuristic does not support this. -/ guard !hasDuplicateAntiquot args -- replace head constant with antiquotation so we're not dependent on the exact pretty printing of the head -- The reference is attached to the syntactic representation of the called function itself, not the entire function application let lhs ← `($$f:ident) let lhs := Syntax.mkApp lhs (.mk args) `(@[$attrKind app_unexpander $(mkIdent c)] aux_def unexpand $(mkIdent c) : Lean.PrettyPrinter.Unexpander := fun | `($lhs) => withRef f `($pat) -- must be a separate case as the LHS and RHS above might not be `app` nodes | `($lhs $$moreArgs*) => withRef f `($pat $$moreArgs*) | _ => throw ()) private def expandNotationAux (ref : Syntax) (currNamespace : Name) (doc? : Option (TSyntax ``docComment)) (attrs? : Option (TSepArray ``attrInstance ",")) (attrKind : TSyntax ``attrKind) (prec? : Option Prec) (name? : Option Ident) (prio? : Option Prio) (items : Array (TSyntax ``notationItem)) (rhs : Term) : MacroM Syntax := do let prio ← evalOptPrio prio? -- build parser let syntaxParts ← items.mapM expandNotationItemIntoSyntaxItem let cat := mkIdentFrom ref `term let name ← match name? with | some name => pure name.getId | none => addMacroScopeIfLocal (← mkNameFromParserSyntax `term (mkNullNode syntaxParts)) attrKind -- build macro rules let vars := items.filter fun item => item.raw.getKind == ``identPrec let vars := vars.map fun var => var.raw[0] let qrhs := ⟨antiquote vars rhs⟩ let attrs? := addInheritDocDefault rhs attrs? let patArgs ← items.mapM expandNotationItemIntoPattern /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let fullName := currNamespace ++ name let pat : Term := ⟨mkNode fullName patArgs⟩ let stxDecl ← `($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind syntax $[: $prec?]? (name := $(name?.getD (mkIdent name))) (priority := $(quote prio)) $[$syntaxParts]* : $cat) let macroDecl ← `(macro_rules | `($pat) => ``($qrhs)) let macroDecls ← if isLocalAttrKind attrKind then -- Make sure the quotation pre-checker takes section variables into account for local notation. `(section set_option quotPrecheck.allowSectionVars true $macroDecl end) else pure ⟨mkNullNode #[macroDecl]⟩ match (← mkSimpleDelab attrKind pat qrhs |>.run) with | some delabDecl => return mkNullNode #[stxDecl, macroDecls, delabDecl] | none => return mkNullNode #[stxDecl, macroDecls] @[builtin_macro Lean.Parser.Command.notation] def expandNotation : Macro | stx@`($[$doc?:docComment]? $[@[$attrs?,*]]? $attrKind:attrKind notation $[: $prec?]? $[(name := $name?)]? $[(priority := $prio?)]? $items* => $rhs) => do -- trigger scoped checks early and only once let _ ← toAttributeKind attrKind expandNotationAux stx (← Macro.getCurrNamespace) doc? attrs? attrKind prec? name? prio? items rhs | _ => Macro.throwUnsupported end Lean.Elab.Command
dd12a3cc8da8b4d6edae876fe4d8ee6a979bb1b3
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/algebra/floor_ring.lean
575ecfa64158675a0b1e03d72db6acf15d786e06
[ "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
9,350
lean
/- Copyright (c) 2020 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker Basic topological facts (limits and continuity) about `floor`, `ceil` and `fract` in a `floor_ring`. -/ import topology.algebra.ordered import algebra.floor open set function filter open_locale topological_space variables {α : Type*} [linear_ordered_ring α] [floor_ring α] lemma tendsto_floor_at_top : tendsto (floor : α → ℤ) at_top at_top := begin refine monotone.tendsto_at_top_at_top (λ a b hab, floor_mono hab) (λ b, _), use (b : α) + ((1 : ℤ) : α), rw [floor_add_int, floor_coe], exact (lt_add_one _).le end lemma tendsto_floor_at_bot : tendsto (floor : α → ℤ) at_bot at_bot := begin refine monotone.tendsto_at_bot_at_bot (λ a b hab, floor_mono hab) (λ b, ⟨b, _⟩), rw floor_coe end lemma tendsto_ceil_at_top : tendsto (ceil : α → ℤ) at_top at_top := tendsto_neg_at_bot_at_top.comp (tendsto_floor_at_bot.comp tendsto_neg_at_top_at_bot) lemma tendsto_ceil_at_bot : tendsto (ceil : α → ℤ) at_bot at_bot := tendsto_neg_at_top_at_bot.comp (tendsto_floor_at_top.comp tendsto_neg_at_bot_at_top) variables [topological_space α] lemma continuous_on_floor (n : ℤ) : continuous_on (λ x, floor x : α → α) (Ico n (n+1) : set α) := (continuous_on_congr $ floor_eq_on_Ico' n).mpr continuous_on_const lemma continuous_on_ceil (n : ℤ) : continuous_on (λ x, ceil x : α → α) (Ioc (n-1) n : set α) := (continuous_on_congr $ ceil_eq_on_Ioc' n).mpr continuous_on_const lemma tendsto_floor_right' [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[Ici n] n) (𝓝 n) := begin rw ← nhds_within_Ico_eq_nhds_within_Ici (lt_add_one (n : α)), convert ← (continuous_on_floor _ _ (left_mem_Ico.mpr $ lt_add_one (_ : α))).tendsto, rw floor_eq_iff, exact ⟨le_refl _, lt_add_one _⟩ end lemma tendsto_ceil_left' [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[Iic n] n) (𝓝 n) := begin rw ← nhds_within_Ioc_eq_nhds_within_Iic (sub_one_lt (n : α)), convert ← (continuous_on_ceil _ _ (right_mem_Ioc.mpr $ sub_one_lt (_ : α))).tendsto, rw ceil_eq_iff, exact ⟨sub_one_lt _, le_refl _⟩ end lemma tendsto_floor_right [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[Ici n] n) (𝓝[Ici n] n) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_floor_right' _) begin refine (eventually_nhds_with_of_forall $ λ x (hx : (n : α) ≤ x), _), change _ ≤ _, norm_cast, convert ← floor_mono hx, rw floor_eq_iff, exact ⟨le_refl _, lt_add_one _⟩ end lemma tendsto_ceil_left [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[Iic n] n) (𝓝[Iic n] n) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_ceil_left' _) begin refine (eventually_nhds_with_of_forall $ λ x (hx : x ≤ (n : α)), _), change _ ≤ _, norm_cast, convert ← ceil_mono hx, rw ceil_eq_iff, exact ⟨sub_one_lt _, le_refl _⟩ end lemma tendsto_floor_left [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[Iio n] n) (𝓝[Iic (n-1)] (n-1)) := begin rw ← nhds_within_Ico_eq_nhds_within_Iio (sub_one_lt (n : α)), convert (tendsto_nhds_within_congr $ (λ x hx, (floor_eq_on_Ico' (n-1) x hx).symm)) (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ tendsto_const_nhds (eventually_of_forall (λ _, mem_Iic.mpr $ le_refl _))); norm_cast <|> apply_instance, ring end lemma tendsto_ceil_right [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[Ioi n] n) (𝓝[Ici (n+1)] (n+1)) := begin rw ← nhds_within_Ioc_eq_nhds_within_Ioi (lt_add_one (n : α)), convert (tendsto_nhds_within_congr $ (λ x hx, (ceil_eq_on_Ioc' (n+1) x hx).symm)) (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ tendsto_const_nhds (eventually_of_forall (λ _, mem_Ici.mpr $ le_refl _))); norm_cast <|> apply_instance, ring end lemma tendsto_floor_left' [order_closed_topology α] (n : ℤ) : tendsto (λ x, floor x : α → α) (𝓝[Iio n] n) (𝓝 (n-1)) := begin rw ← nhds_within_univ, exact tendsto_nhds_within_mono_right (subset_univ _) (tendsto_floor_left n), end lemma tendsto_ceil_right' [order_closed_topology α] (n : ℤ) : tendsto (λ x, ceil x : α → α) (𝓝[Ioi n] n) (𝓝 (n+1)) := begin rw ← nhds_within_univ, exact tendsto_nhds_within_mono_right (subset_univ _) (tendsto_ceil_right n), end lemma continuous_on_fract [topological_add_group α] (n : ℤ) : continuous_on (fract : α → α) (Ico n (n+1) : set α) := continuous_on_id.sub (continuous_on_floor n) lemma tendsto_fract_left' [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[Iio n] n) (𝓝 1) := begin convert (tendsto_nhds_within_of_tendsto_nhds tendsto_id).sub (tendsto_floor_left' n); [{norm_cast, ring}, apply_instance, apply_instance] end lemma tendsto_fract_left [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[Iio n] n) (𝓝[Iio 1] 1) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_fract_left' _) (eventually_of_forall fract_lt_one) lemma tendsto_fract_right' [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[Ici n] n) (𝓝 0) := begin convert (tendsto_nhds_within_of_tendsto_nhds tendsto_id).sub (tendsto_floor_right' n); [exact (sub_self _).symm, apply_instance, apply_instance] end lemma tendsto_fract_right [order_closed_topology α] [topological_add_group α] (n : ℤ) : tendsto (fract : α → α) (𝓝[Ici n] n) (𝓝[Ici 0] 0) := tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (tendsto_fract_right' _) (eventually_of_forall fract_nonneg) local notation `I` := (Icc 0 1 : set α) lemma continuous_on.comp_fract' {β γ : Type*} [order_topology α] [topological_add_group α] [topological_space β] [topological_space γ] {f : β → α → γ} (h : continuous_on (uncurry f) $ (univ : set β).prod I) (hf : ∀ s, f s 0 = f s 1) : continuous (λ st : β × α, f st.1 $ fract st.2) := begin change continuous ((uncurry f) ∘ (prod.map id (fract))), rw continuous_iff_continuous_at, rintro ⟨s, t⟩, by_cases ht : t = floor t, { rw ht, rw ← continuous_within_at_univ, have : (univ : set (β × α)) ⊆ (set.prod univ (Iio $ floor t)) ∪ (set.prod univ (Ici $ floor t)), { rintros p -, rw ← prod_union, exact ⟨true.intro, lt_or_le _ _⟩ }, refine continuous_within_at.mono _ this, refine continuous_within_at.union _ _, { simp only [continuous_within_at, fract_coe, nhds_within_prod_eq, nhds_within_univ, id.def, comp_app, prod.map_mk], have : (uncurry f) (s, 0) = (uncurry f) (s, (1 : α)), by simp [uncurry, hf], rw this, refine (h _ ⟨true.intro, by exact_mod_cast right_mem_Icc.mpr zero_le_one⟩).tendsto.comp _, rw [nhds_within_prod_eq, nhds_within_univ], rw nhds_within_Icc_eq_nhds_within_Iic (@zero_lt_one α _ _), exact tendsto_id.prod_map (tendsto_nhds_within_mono_right Iio_subset_Iic_self $ tendsto_fract_left _) }, { simp only [continuous_within_at, fract_coe, nhds_within_prod_eq, nhds_within_univ, id.def, comp_app, prod.map_mk], refine (h _ ⟨true.intro, by exact_mod_cast left_mem_Icc.mpr zero_le_one⟩).tendsto.comp _, rw [nhds_within_prod_eq, nhds_within_univ, nhds_within_Icc_eq_nhds_within_Ici (@zero_lt_one α _ _)], exact tendsto_id.prod_map (tendsto_fract_right _) } }, { have : t ∈ Ioo (floor t : α) ((floor t : α) + 1), from ⟨lt_of_le_of_ne (floor_le t) (ne.symm ht), lt_floor_add_one _⟩, refine (h ((prod.map _ fract) _) ⟨trivial, ⟨fract_nonneg _, (fract_lt_one _).le⟩⟩).tendsto.comp _, simp only [nhds_prod_eq, nhds_within_prod_eq, nhds_within_univ, id.def, prod.map_mk], exact continuous_at_id.tendsto.prod_map (tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (((continuous_on_fract _ _ (Ioo_subset_Ico_self this)).mono Ioo_subset_Ico_self).continuous_at (Ioo_mem_nhds this.1 this.2)) (eventually_of_forall (λ x, ⟨fract_nonneg _, (fract_lt_one _).le⟩)) ) } end lemma continuous_on.comp_fract {β : Type*} [order_topology α] [topological_add_group α] [topological_space β] {f : α → β} (h : continuous_on f I) (hf : f 0 = f 1) : continuous (f ∘ fract) := begin let f' : unit → α → β := λ x y, f y, have : continuous_on (uncurry f') ((univ : set unit).prod I), { rintros ⟨s, t⟩ ⟨-, ht : t ∈ I⟩, simp only [continuous_within_at, uncurry, nhds_within_prod_eq, nhds_within_univ, f'], rw tendsto_prod_iff, intros W hW, specialize h t ht hW, rw mem_map_sets_iff at h, rcases h with ⟨V, hV, hVW⟩, rw image_subset_iff at hVW, use [univ, univ_mem_sets, V, hV], intros x y hx hy, exact hVW hy }, have key : continuous (λ s, ⟨unit.star, s⟩ : α → unit × α) := by continuity, exact (this.comp_fract' (λ s, hf)).comp key end
63c1ca2565b7119e5121b4f392defd60d380e191
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category/bitraversable/instances.lean
af9b06e12549ccb540654b6d938b7ed17e75e658
[ "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
4,430
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import category.bitraversable.basic category.bitraversable.lemmas category.traversable.lemmas tactic.solve_by_elim /-! # bitraversable instances ## Instances * prod * sum * const * flip * bicompl * bicompr ## References * Hackage: <https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bitraversable.html> ## Tags traversable bitraversable functor bifunctor applicative -/ universes u v w variables {t : Type u → Type u → Type u} [bitraversable t] section variables {F : Type u → Type u} [applicative F] def prod.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α × β → F (α' × β') | (x,y) := prod.mk <$> f x <*> f' y instance : bitraversable prod := { bitraverse := @prod.bitraverse } instance : is_lawful_bitraversable prod := by constructor; introsI; cases x; simp [bitraverse,prod.bitraverse] with functor_norm; refl open functor def sum.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : α ⊕ β → F (α' ⊕ β') | (sum.inl x) := sum.inl <$> f x | (sum.inr x) := sum.inr <$> f' x instance : bitraversable sum := { bitraverse := @sum.bitraverse } instance : is_lawful_bitraversable sum := by constructor; introsI; cases x; simp [bitraverse,sum.bitraverse] with functor_norm; refl def const.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : const α β → F (const α' β') := f instance bitraversable.const : bitraversable const := { bitraverse := @const.bitraverse } instance is_lawful_bitraversable.const : is_lawful_bitraversable const := by constructor; introsI; simp [bitraverse,const.bitraverse] with functor_norm; refl def flip.bitraverse {α α' β β'} (f : α → F α') (f' : β → F β') : flip t α β → F (flip t α' β') := (bitraverse f' f : t β α → F (t β' α')) instance bitraversable.flip : bitraversable (flip t) := { bitraverse := @flip.bitraverse t _ } open is_lawful_bitraversable instance is_lawful_bitraversable.flip [is_lawful_bitraversable t] : is_lawful_bitraversable (flip t) := by constructor; introsI; casesm is_lawful_bitraversable t; apply_assumption open bitraversable functor @[priority 10] instance bitraversable.traversable {α} : traversable (t α) := { traverse := @tsnd t _ _ } @[priority 10] instance bitraversable.is_lawful_traversable [is_lawful_bitraversable t] {α} : is_lawful_traversable (t α) := by { constructor; introsI; simp [traverse,comp_tsnd] with functor_norm, { refl }, { simp [tsnd_eq_snd_id], refl }, { simp [tsnd,binaturality,function.comp] with functor_norm } } end open bifunctor traversable is_lawful_traversable is_lawful_bitraversable open function (bicompl bicompr) section bicompl variables (F G : Type u → Type u) [traversable F] [traversable G] def bicompl.bitraverse {m} [applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') : bicompl t F G α α' → m (bicompl t F G β β') := (bitraverse (traverse f) (traverse f') : t (F α) (G α') → m _) instance : bitraversable (bicompl t F G) := { bitraverse := @bicompl.bitraverse t _ F G _ _ } instance [is_lawful_traversable F] [is_lawful_traversable G] [is_lawful_bitraversable t] : is_lawful_bitraversable (bicompl t F G) := begin constructor; introsI; simp [bitraverse,bicompl.bitraverse,bimap,traverse_id,bitraverse_id_id,comp_bitraverse] with functor_norm, { simp [traverse_eq_map_id',bitraverse_eq_bimap_id], }, { revert x, dunfold bicompl, simp [binaturality,naturality_pf] } end end bicompl section bicompr variables (F : Type u → Type u) [traversable F] def bicompr.bitraverse {m} [applicative m] {α β α' β'} (f : α → m β) (f' : α' → m β') : bicompr F t α α' → m (bicompr F t β β') := (traverse (bitraverse f f') : F (t α α') → m _) instance : bitraversable (bicompr F t) := { bitraverse := @bicompr.bitraverse t _ F _ } instance [is_lawful_traversable F] [is_lawful_bitraversable t] : is_lawful_bitraversable (bicompr F t) := begin constructor; introsI; simp [bitraverse,bicompr.bitraverse,bitraverse_id_id] with functor_norm, { simp [bitraverse_eq_bimap_id',traverse_eq_map_id'], refl }, { revert x, dunfold bicompr, intro, simp [naturality,binaturality'] } end end bicompr
45204d62bf6afcf63013a5e52d1ec532383892ee
bb31430994044506fa42fd667e2d556327e18dfe
/src/analysis/convex/segment.lean
341637fafe1686d1061645d7b4f92fbce8d6a0ea
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
20,208
lean
/- Copyright (c) 2019 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp, Yury Kudriashov, Yaël Dillies -/ import algebra.order.invertible import algebra.order.smul import linear_algebra.affine_space.midpoint import linear_algebra.ray import tactic.positivity /-! # Segments in vector spaces In a 𝕜-vector space, we define the following objects and properties. * `segment 𝕜 x y`: Closed segment joining `x` and `y`. * `open_segment 𝕜 x y`: Open segment joining `x` and `y`. ## Notations We provide the following notation: * `[x -[𝕜] y] = segment 𝕜 x y` in locale `convex` ## TODO Generalize all this file to affine spaces. Should we rename `segment` and `open_segment` to `convex.Icc` and `convex.Ioo`? Should we also define `clopen_segment`/`convex.Ico`/`convex.Ioc`? -/ variables {𝕜 E F : Type*} open set section ordered_semiring variables [ordered_semiring 𝕜] [add_comm_monoid E] section has_smul variables (𝕜) [has_smul 𝕜 E] {s : set E} {x y : E} /-- Segments in a vector space. -/ def segment (x y : E) : set E := {z : E | ∃ (a b : 𝕜) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1), a • x + b • y = z} /-- Open segment in a vector space. Note that `open_segment 𝕜 x x = {x}` instead of being `∅` when the base semiring has some element between `0` and `1`. -/ def open_segment (x y : E) : set E := {z : E | ∃ (a b : 𝕜) (ha : 0 < a) (hb : 0 < b) (hab : a + b = 1), a • x + b • y = z} localized "notation (name := segment) `[` x ` -[` 𝕜 `] ` y `]` := segment 𝕜 x y" in convex lemma segment_eq_image₂ (x y : E) : [x -[𝕜] y] = (λ p : 𝕜 × 𝕜, p.1 • x + p.2 • y) '' {p | 0 ≤ p.1 ∧ 0 ≤ p.2 ∧ p.1 + p.2 = 1} := by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma open_segment_eq_image₂ (x y : E) : open_segment 𝕜 x y = (λ p : 𝕜 × 𝕜, p.1 • x + p.2 • y) '' {p | 0 < p.1 ∧ 0 < p.2 ∧ p.1 + p.2 = 1} := by simp only [open_segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc] lemma segment_symm (x y : E) : [x -[𝕜] y] = [y -[𝕜] x] := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma open_segment_symm (x y : E) : open_segment 𝕜 x y = open_segment 𝕜 y x := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩, λ ⟨a, b, ha, hb, hab, H⟩, ⟨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans H⟩⟩ lemma open_segment_subset_segment (x y : E) : open_segment 𝕜 x y ⊆ [x -[𝕜] y] := λ z ⟨a, b, ha, hb, hab, hz⟩, ⟨a, b, ha.le, hb.le, hab, hz⟩ lemma segment_subset_iff : [x -[𝕜] y] ⊆ s ↔ ∀ a b : 𝕜, 0 ≤ a → 0 ≤ b → a + b = 1 → a • x + b • y ∈ s := ⟨λ H a b ha hb hab, H ⟨a, b, ha, hb, hab, rfl⟩, λ H z ⟨a, b, ha, hb, hab, hz⟩, hz ▸ H a b ha hb hab⟩ lemma open_segment_subset_iff : open_segment 𝕜 x y ⊆ s ↔ ∀ a b : 𝕜, 0 < a → 0 < b → a + b = 1 → a • x + b • y ∈ s := ⟨λ H a b ha hb hab, H ⟨a, b, ha, hb, hab, rfl⟩, λ H z ⟨a, b, ha, hb, hab, hz⟩, hz ▸ H a b ha hb hab⟩ end has_smul open_locale convex section mul_action_with_zero variables (𝕜) [mul_action_with_zero 𝕜 E] lemma left_mem_segment (x y : E) : x ∈ [x -[𝕜] y] := ⟨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]⟩ lemma right_mem_segment (x y : E) : y ∈ [x -[𝕜] y] := segment_symm 𝕜 y x ▸ left_mem_segment 𝕜 y x end mul_action_with_zero section module variables (𝕜) [module 𝕜 E] {s : set E} {x y z : E} @[simp] lemma segment_same (x : E) : [x -[𝕜] x] = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ h, mem_singleton_iff.1 h ▸ left_mem_segment 𝕜 z z⟩ lemma insert_endpoints_open_segment (x y : E) : insert x (insert y (open_segment 𝕜 x y)) = [x -[𝕜] y] := begin simp only [subset_antisymm_iff, insert_subset, left_mem_segment, right_mem_segment, open_segment_subset_segment, true_and], rintro z ⟨a, b, ha, hb, hab, rfl⟩, refine hb.eq_or_gt.imp _ (λ hb', ha.eq_or_gt.imp _ $ λ ha', _), { rintro rfl, rw [← add_zero a, hab, one_smul, zero_smul, add_zero] }, { rintro rfl, rw [← zero_add b, hab, one_smul, zero_smul, zero_add] }, { exact ⟨a, b, ha', hb', hab, rfl⟩ } end variables {𝕜} lemma mem_open_segment_of_ne_left_right (hx : x ≠ z) (hy : y ≠ z) (hz : z ∈ [x -[𝕜] y]) : z ∈ open_segment 𝕜 x y := begin rw [←insert_endpoints_open_segment] at hz, exact ((hz.resolve_left hx.symm).resolve_left hy.symm) end lemma open_segment_subset_iff_segment_subset (hx : x ∈ s) (hy : y ∈ s) : open_segment 𝕜 x y ⊆ s ↔ [x -[𝕜] y] ⊆ s := by simp only [←insert_endpoints_open_segment, insert_subset, *, true_and] end module end ordered_semiring open_locale convex section ordered_ring variables (𝕜) [ordered_ring 𝕜] [add_comm_group E] [add_comm_group F] [module 𝕜 E] [module 𝕜 F] section densely_ordered variables [nontrivial 𝕜] [densely_ordered 𝕜] @[simp] lemma open_segment_same (x : E) : open_segment 𝕜 x x = {x} := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, by simpa only [←add_smul, mem_singleton_iff, hab, one_smul, eq_comm] using hz, λ (h : z = x), begin obtain ⟨a, ha₀, ha₁⟩ := densely_ordered.dense (0 : 𝕜) 1 zero_lt_one, refine ⟨a, 1 - a, ha₀, sub_pos_of_lt ha₁, add_sub_cancel'_right _ _, _⟩, rw [←add_smul, add_sub_cancel'_right, one_smul, h], end⟩ end densely_ordered lemma segment_eq_image (x y : E) : [x -[𝕜] y] = (λ θ : 𝕜, (1 - θ) • x + θ • y) '' Icc (0 : 𝕜) 1 := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ le_add_of_nonneg_left ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1-θ, θ, sub_nonneg.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma open_segment_eq_image (x y : E) : open_segment 𝕜 x y = (λ (θ : 𝕜), (1 - θ) • x + θ • y) '' Ioo (0 : 𝕜) 1 := set.ext $ λ z, ⟨λ ⟨a, b, ha, hb, hab, hz⟩, ⟨b, ⟨hb, hab ▸ lt_add_of_pos_left _ ha⟩, hab ▸ hz ▸ by simp only [add_sub_cancel]⟩, λ ⟨θ, ⟨hθ₀, hθ₁⟩, hz⟩, ⟨1 - θ, θ, sub_pos.2 hθ₁, hθ₀, sub_add_cancel _ _, hz⟩⟩ lemma segment_eq_image' (x y : E) : [x -[𝕜] y] = (λ (θ : 𝕜), x + θ • (y - x)) '' Icc (0 : 𝕜) 1 := by { convert segment_eq_image 𝕜 x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma open_segment_eq_image' (x y : E) : open_segment 𝕜 x y = (λ (θ : 𝕜), x + θ • (y - x)) '' Ioo (0 : 𝕜) 1 := by { convert open_segment_eq_image 𝕜 x y, ext θ, simp only [smul_sub, sub_smul, one_smul], abel } lemma segment_eq_image_line_map (x y : E) : [x -[𝕜] y] = affine_map.line_map x y '' Icc (0 : 𝕜) 1 := by { convert segment_eq_image 𝕜 x y, ext, exact affine_map.line_map_apply_module _ _ _ } lemma open_segment_eq_image_line_map (x y : E) : open_segment 𝕜 x y = affine_map.line_map x y '' Ioo (0 : 𝕜) 1 := by { convert open_segment_eq_image 𝕜 x y, ext, exact affine_map.line_map_apply_module _ _ _ } lemma segment_image (f : E →ₗ[𝕜] F) (a b : E) : f '' [a -[𝕜] b] = [f a -[𝕜] f b] := set.ext (λ x, by simp_rw [segment_eq_image, mem_image, exists_exists_and_eq_and, map_add, map_smul]) @[simp] lemma open_segment_image (f : E →ₗ[𝕜] F) (a b : E) : f '' open_segment 𝕜 a b = open_segment 𝕜 (f a) (f b) := set.ext (λ x, by simp_rw [open_segment_eq_image, mem_image, exists_exists_and_eq_and, map_add, map_smul]) lemma mem_segment_translate (a : E) {x b c} : a + x ∈ [a + b -[𝕜] a + c] ↔ x ∈ [b -[𝕜] c] := begin rw [segment_eq_image', segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj], end @[simp] lemma mem_open_segment_translate (a : E) {x b c : E} : a + x ∈ open_segment 𝕜 (a + b) (a + c) ↔ x ∈ open_segment 𝕜 b c := begin rw [open_segment_eq_image', open_segment_eq_image'], refine exists_congr (λ θ, and_congr iff.rfl _), simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj], end lemma segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' [a + b -[𝕜] a + c] = [b -[𝕜] c] := set.ext $ λ x, mem_segment_translate 𝕜 a lemma open_segment_translate_preimage (a b c : E) : (λ x, a + x) ⁻¹' open_segment 𝕜 (a + b) (a + c) = open_segment 𝕜 b c := set.ext $ λ x, mem_open_segment_translate 𝕜 a lemma segment_translate_image (a b c : E) : (λ x, a + x) '' [b -[𝕜] c] = [a + b -[𝕜] a + c] := segment_translate_preimage 𝕜 a b c ▸ image_preimage_eq _ $ add_left_surjective a lemma open_segment_translate_image (a b c : E) : (λ x, a + x) '' open_segment 𝕜 b c = open_segment 𝕜 (a + b) (a + c) := open_segment_translate_preimage 𝕜 a b c ▸ image_preimage_eq _ $ add_left_surjective a end ordered_ring lemma same_ray_of_mem_segment [strict_ordered_comm_ring 𝕜] [add_comm_group E] [module 𝕜 E] {x y z : E} (h : x ∈ [y -[𝕜] z]) : same_ray 𝕜 (x - y) (z - x) := begin rw segment_eq_image' at h, rcases h with ⟨θ, ⟨hθ₀, hθ₁⟩, rfl⟩, simpa only [add_sub_cancel', ←sub_sub, sub_smul, one_smul] using (same_ray_nonneg_smul_left (z - y) hθ₀).nonneg_smul_right (sub_nonneg.2 hθ₁) end section linear_ordered_ring variables [linear_ordered_ring 𝕜] [add_comm_group E] [module 𝕜 E] {x y : E} lemma midpoint_mem_segment [invertible (2 : 𝕜)] (x y : E) : midpoint 𝕜 x y ∈ [x -[𝕜] y] := begin rw segment_eq_image_line_map, exact ⟨⅟2, ⟨inv_of_nonneg.mpr zero_le_two, inv_of_le_one one_le_two⟩, rfl⟩, end lemma mem_segment_sub_add [invertible (2 : 𝕜)] (x y : E) : x ∈ [x - y -[𝕜] x + y] := by { convert @midpoint_mem_segment 𝕜 _ _ _ _ _ _ _, rw midpoint_sub_add } lemma mem_segment_add_sub [invertible (2 : 𝕜)] (x y : E) : x ∈ [x + y -[𝕜] x - y] := by { convert @midpoint_mem_segment 𝕜 _ _ _ _ _ _ _, rw midpoint_add_sub } @[simp] lemma left_mem_open_segment_iff [densely_ordered 𝕜] [no_zero_smul_divisors 𝕜 E] : x ∈ open_segment 𝕜 x y ↔ x = y := begin split, { rintro ⟨a, b, ha, hb, hab, hx⟩, refine smul_right_injective _ hb.ne' ((add_right_inj (a • x)).1 _), rw [hx, ←add_smul, hab, one_smul] }, { rintro rfl, rw open_segment_same, exact mem_singleton _ } end @[simp] lemma right_mem_open_segment_iff [densely_ordered 𝕜] [no_zero_smul_divisors 𝕜 E] : y ∈ open_segment 𝕜 x y ↔ x = y := by rw [open_segment_symm, left_mem_open_segment_iff, eq_comm] end linear_ordered_ring section linear_ordered_semifield variables [linear_ordered_semifield 𝕜] [add_comm_group E] [module 𝕜 E] {x y z : E} lemma mem_segment_iff_div : x ∈ [y -[𝕜] z] ↔ ∃ a b : 𝕜, 0 ≤ a ∧ 0 ≤ b ∧ 0 < a + b ∧ (a / (a + b)) • y + (b / (a + b)) • z = x := begin split, { rintro ⟨a, b, ha, hb, hab, rfl⟩, use [a, b, ha, hb], simp * }, { rintro ⟨a, b, ha, hb, hab, rfl⟩, refine ⟨a / (a + b), b / (a + b), div_nonneg ha hab.le, div_nonneg hb hab.le, _, rfl⟩, rw [←add_div, div_self hab.ne'] } end lemma mem_open_segment_iff_div : x ∈ open_segment 𝕜 y z ↔ ∃ a b : 𝕜, 0 < a ∧ 0 < b ∧ (a / (a + b)) • y + (b / (a + b)) • z = x := begin split, { rintro ⟨a, b, ha, hb, hab, rfl⟩, use [a, b, ha, hb], rw [hab, div_one, div_one] }, { rintro ⟨a, b, ha, hb, rfl⟩, have hab : 0 < a + b := by positivity, refine ⟨a / (a + b), b / (a + b), by positivity, by positivity, _, rfl⟩, rw [←add_div, div_self hab.ne'] } end end linear_ordered_semifield section linear_ordered_field variables [linear_ordered_field 𝕜] [add_comm_group E] [module 𝕜 E] {x y z : E} lemma mem_segment_iff_same_ray : x ∈ [y -[𝕜] z] ↔ same_ray 𝕜 (x - y) (z - x) := begin refine ⟨same_ray_of_mem_segment, λ h, _⟩, rcases h.exists_eq_smul_add with ⟨a, b, ha, hb, hab, hxy, hzx⟩, rw [add_comm, sub_add_sub_cancel] at hxy hzx, rw [←mem_segment_translate _ (-x), neg_add_self], refine ⟨b, a, hb, ha, add_comm a b ▸ hab, _⟩, rw [←sub_eq_neg_add, ←neg_sub, hxy, ←sub_eq_neg_add, hzx, smul_neg, smul_comm, neg_add_self] end open affine_map /-- If `z = line_map x y c` is a point on the line passing through `x` and `y`, then the open segment `open_segment 𝕜 x y` is included in the union of the open segments `open_segment 𝕜 x z`, `open_segment 𝕜 z y`, and the point `z`. Informally, `(x, y) ⊆ {z} ∪ (x, z) ∪ (z, y)`. -/ lemma open_segment_subset_union (x y : E) {z : E} (hz : z ∈ range (line_map x y : 𝕜 → E)) : open_segment 𝕜 x y ⊆ insert z (open_segment 𝕜 x z ∪ open_segment 𝕜 z y) := begin rcases hz with ⟨c, rfl⟩, simp only [open_segment_eq_image_line_map, ← maps_to'], rintro a ⟨h₀, h₁⟩, rcases lt_trichotomy a c with hac|rfl|hca, { right, left, have hc : 0 < c, from h₀.trans hac, refine ⟨a / c, ⟨div_pos h₀ hc, (div_lt_one hc).2 hac⟩, _⟩, simp only [← homothety_eq_line_map, ← homothety_mul_apply, div_mul_cancel _ hc.ne'] }, { left, refl }, { right, right, have hc : 0 < 1 - c, from sub_pos.2 (hca.trans h₁), simp only [← line_map_apply_one_sub y], refine ⟨(a - c) / (1 - c), ⟨div_pos (sub_pos.2 hca) hc, (div_lt_one hc).2 $ sub_lt_sub_right h₁ _⟩, _⟩, simp only [← homothety_eq_line_map, ← homothety_mul_apply, sub_mul, one_mul, div_mul_cancel _ hc.ne', sub_sub_sub_cancel_right] } end end linear_ordered_field /-! #### Segments in an ordered space Relates `segment`, `open_segment` and `set.Icc`, `set.Ico`, `set.Ioc`, `set.Ioo` -/ section ordered_semiring variables [ordered_semiring 𝕜] section ordered_add_comm_monoid variables [ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] {x y : E} lemma segment_subset_Icc (h : x ≤ y) : [x -[𝕜] y] ⊆ Icc x y := begin rintro z ⟨a, b, ha, hb, hab, rfl⟩, split, calc x = a • x + b • x :(convex.combo_self hab _).symm ... ≤ a • x + b • y : add_le_add_left (smul_le_smul_of_nonneg h hb) _, calc a • x + b • y ≤ a • y + b • y : add_le_add_right (smul_le_smul_of_nonneg h ha) _ ... = y : convex.combo_self hab _, end end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] {x y : E} lemma open_segment_subset_Ioo (h : x < y) : open_segment 𝕜 x y ⊆ Ioo x y := begin rintro z ⟨a, b, ha, hb, hab, rfl⟩, split, calc x = a • x + b • x : (convex.combo_self hab _).symm ... < a • x + b • y : add_lt_add_left (smul_lt_smul_of_pos h hb) _, calc a • x + b • y < a • y + b • y : add_lt_add_right (smul_lt_smul_of_pos h ha) _ ... = y : convex.combo_self hab _, end end ordered_cancel_add_comm_monoid section linear_ordered_add_comm_monoid variables [linear_ordered_add_comm_monoid E] [module 𝕜 E] [ordered_smul 𝕜 E] {𝕜} {a b : 𝕜} lemma segment_subset_uIcc (x y : E) : [x -[𝕜] y] ⊆ uIcc x y := begin cases le_total x y, { rw uIcc_of_le h, exact segment_subset_Icc h }, { rw [uIcc_of_ge h, segment_symm], exact segment_subset_Icc h } end lemma convex.min_le_combo (x y : E) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : min x y ≤ a • x + b • y := (segment_subset_uIcc x y ⟨_, _, ha, hb, hab, rfl⟩).1 lemma convex.combo_le_max (x y : E) (ha : 0 ≤ a) (hb : 0 ≤ b) (hab : a + b = 1) : a • x + b • y ≤ max x y := (segment_subset_uIcc x y ⟨_, _, ha, hb, hab, rfl⟩).2 end linear_ordered_add_comm_monoid end ordered_semiring section linear_ordered_field variables [linear_ordered_field 𝕜] {x y z : 𝕜} lemma Icc_subset_segment : Icc x y ⊆ [x -[𝕜] y] := begin rintro z ⟨hxz, hyz⟩, obtain rfl | h := (hxz.trans hyz).eq_or_lt, { rw segment_same, exact hyz.antisymm hxz }, rw ←sub_nonneg at hxz hyz, rw ←sub_pos at h, refine ⟨(y - z) / (y - x), (z - x) / (y - x), div_nonneg hyz h.le, div_nonneg hxz h.le, _, _⟩, { rw [←add_div, sub_add_sub_cancel, div_self h.ne'] }, { rw [smul_eq_mul, smul_eq_mul, ←mul_div_right_comm, ←mul_div_right_comm, ←add_div, div_eq_iff h.ne', add_comm, sub_mul, sub_mul, mul_comm x, sub_add_sub_cancel, mul_sub] } end @[simp] lemma segment_eq_Icc (h : x ≤ y) : [x -[𝕜] y] = Icc x y := (segment_subset_Icc h).antisymm Icc_subset_segment lemma Ioo_subset_open_segment : Ioo x y ⊆ open_segment 𝕜 x y := λ z hz, mem_open_segment_of_ne_left_right hz.1.ne hz.2.ne' $ Icc_subset_segment $ Ioo_subset_Icc_self hz @[simp] lemma open_segment_eq_Ioo (h : x < y) : open_segment 𝕜 x y = Ioo x y := (open_segment_subset_Ioo h).antisymm Ioo_subset_open_segment lemma segment_eq_Icc' (x y : 𝕜) : [x -[𝕜] y] = Icc (min x y) (max x y) := begin cases le_total x y, { rw [segment_eq_Icc h, max_eq_right h, min_eq_left h] }, { rw [segment_symm, segment_eq_Icc h, max_eq_left h, min_eq_right h] } end lemma open_segment_eq_Ioo' (hxy : x ≠ y) : open_segment 𝕜 x y = Ioo (min x y) (max x y) := begin cases hxy.lt_or_lt, { rw [open_segment_eq_Ioo h, max_eq_right h.le, min_eq_left h.le] }, { rw [open_segment_symm, open_segment_eq_Ioo h, max_eq_left h.le, min_eq_right h.le] } end lemma segment_eq_uIcc (x y : 𝕜) : [x -[𝕜] y] = uIcc x y := segment_eq_Icc' _ _ /-- A point is in an `Icc` iff it can be expressed as a convex combination of the endpoints. -/ lemma convex.mem_Icc (h : x ≤ y) : z ∈ Icc x y ↔ ∃ a b, 0 ≤ a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z := by { rw ←segment_eq_Icc h, simp_rw [←exists_prop], refl } /-- A point is in an `Ioo` iff it can be expressed as a strict convex combination of the endpoints. -/ lemma convex.mem_Ioo (h : x < y) : z ∈ Ioo x y ↔ ∃ a b, 0 < a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z := by { rw ←open_segment_eq_Ioo h, simp_rw [←exists_prop], refl } /-- A point is in an `Ioc` iff it can be expressed as a semistrict convex combination of the endpoints. -/ lemma convex.mem_Ioc (h : x < y) : z ∈ Ioc x y ↔ ∃ a b, 0 ≤ a ∧ 0 < b ∧ a + b = 1 ∧ a * x + b * y = z := begin refine ⟨λ hz, _, _⟩, { obtain ⟨a, b, ha, hb, hab, rfl⟩ := (convex.mem_Icc h.le).1 (Ioc_subset_Icc_self hz), obtain rfl | hb' := hb.eq_or_lt, { rw add_zero at hab, rw [hab, one_mul, zero_mul, add_zero] at hz, exact (hz.1.ne rfl).elim }, { exact ⟨a, b, ha, hb', hab, rfl⟩ } }, { rintro ⟨a, b, ha, hb, hab, rfl⟩, obtain rfl | ha' := ha.eq_or_lt, { rw zero_add at hab, rwa [hab, one_mul, zero_mul, zero_add, right_mem_Ioc] }, { exact Ioo_subset_Ioc_self ((convex.mem_Ioo h).2 ⟨a, b, ha', hb, hab, rfl⟩) } } end /-- A point is in an `Ico` iff it can be expressed as a semistrict convex combination of the endpoints. -/ lemma convex.mem_Ico (h : x < y) : z ∈ Ico x y ↔ ∃ a b, 0 < a ∧ 0 ≤ b ∧ a + b = 1 ∧ a * x + b * y = z := begin refine ⟨λ hz, _, _⟩, { obtain ⟨a, b, ha, hb, hab, rfl⟩ := (convex.mem_Icc h.le).1 (Ico_subset_Icc_self hz), obtain rfl | ha' := ha.eq_or_lt, { rw zero_add at hab, rw [hab, one_mul, zero_mul, zero_add] at hz, exact (hz.2.ne rfl).elim }, { exact ⟨a, b, ha', hb, hab, rfl⟩ } }, { rintro ⟨a, b, ha, hb, hab, rfl⟩, obtain rfl | hb' := hb.eq_or_lt, { rw add_zero at hab, rwa [hab, one_mul, zero_mul, add_zero, left_mem_Ico] }, { exact Ioo_subset_Ico_self ((convex.mem_Ioo h).2 ⟨a, b, ha, hb', hab, rfl⟩) } } end end linear_ordered_field
e81aa1f982e15952583ed7569d1cfa544074d1e5
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/measure_theory/haar_measure.lean
1715db6223de80601e7a731aaa2a9535c41038ab
[ "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
25,958
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import measure_theory.content import measure_theory.prod_group /-! # Haar measure In this file we prove the existence of Haar measure for a locally compact Hausdorff topological group. For the construction, we follow the write-up by Jonathan Gleason, *Existence and Uniqueness of Haar Measure*. This is essentially the same argument as in https://en.wikipedia.org/wiki/Haar_measure#A_construction_using_compact_subsets. We construct the Haar measure first on compact sets. For this we define `(K : U)` as the (smallest) number of left-translates of `U` are needed to cover `K` (`index` in the formalization). Then we define a function `h` on compact sets as `lim_U (K : U) / (K₀ : U)`, where `U` becomes a smaller and smaller open neighborhood of `1`, and `K₀` is a fixed compact set with nonempty interior. This function is `chaar` in the formalization, and we define the limit formally using Tychonoff's theorem. This function `h` forms a content, which we can extend to an outer measure and then a measure (`haar_measure`). We normalize the Haar measure so that the measure of `K₀` is `1`. We show that for second countable spaces any left invariant Borel measure is a scalar multiple of the Haar measure. Note that `μ` need not coincide with `h` on compact sets, according to [halmos1950measure, ch. X, §53 p.233]. However, we know that `h(K)` lies between `μ(Kᵒ)` and `μ(K)`, where `ᵒ` denotes the interior. ## Main Declarations * `haar_measure`: the Haar measure on a locally compact Hausdorff group. This is a left invariant regular measure. It takes as argument a compact set of the group (with non-empty interior), and is normalized so that the measure of the given set is 1. * `haar_measure_self`: the Haar measure is normalized. * `is_left_invariant_haar_measure`: the Haar measure is left invariant. * `regular_haar_measure`: the Haar measure is a regular measure. ## References * Paul Halmos (1950), Measure Theory, §53 * Jonathan Gleason, Existence and Uniqueness of Haar Measure - Note: step 9, page 8 contains a mistake: the last defined `μ` does not extend the `μ` on compact sets, see Halmos (1950) p. 233, bottom of the page. This makes some other steps (like step 11) invalid. * https://en.wikipedia.org/wiki/Haar_measure -/ noncomputable theory open set has_inv function topological_space measurable_space open_locale nnreal classical ennreal variables {G : Type*} [group G] namespace measure_theory namespace measure /-! We put the internal functions in the construction of the Haar measure in a namespace, so that the chosen names don't clash with other declarations. We first define a couple of the functions before proving the properties (that require that `G` is a topological group). -/ namespace haar /-- The index or Haar covering number or ratio of `K` w.r.t. `V`, denoted `(K : V)`: it is the smallest number of (left) translates of `V` that is necessary to cover `K`. It is defined to be 0 if no finite number of translates cover `K`. -/ def index (K V : set G) : ℕ := Inf $ finset.card '' {t : finset G | K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V } lemma index_empty {V : set G} : index ∅ V = 0 := begin simp only [index, nat.Inf_eq_zero], left, use ∅, simp only [finset.card_empty, empty_subset, mem_set_of_eq, eq_self_iff_true, and_self], end variables [topological_space G] /-- `prehaar K₀ U K` is a weighted version of the index, defined as `(K : U)/(K₀ : U)`. In the applications `K₀` is compact with non-empty interior, `U` is open containing `1`, and `K` is any compact set. The argument `K` is a (bundled) compact set, so that we can consider `prehaar K₀ U` as an element of `haar_product` (below). -/ def prehaar (K₀ U : set G) (K : compacts G) : ℝ := (index K.1 U : ℝ) / index K₀ U lemma prehaar_empty (K₀ : positive_compacts G) {U : set G} : prehaar K₀.1 U ⊥ = 0 := by { simp only [prehaar, compacts.bot_val, index_empty, nat.cast_zero, zero_div] } lemma prehaar_nonneg (K₀ : positive_compacts G) {U : set G} (K : compacts G) : 0 ≤ prehaar K₀.1 U K := by apply div_nonneg; norm_cast; apply zero_le /-- `haar_product K₀` is the product of intervals `[0, (K : K₀)]`, for all compact sets `K`. For all `U`, we can show that `prehaar K₀ U ∈ haar_product K₀`. -/ def haar_product (K₀ : set G) : set (compacts G → ℝ) := pi univ (λ K, Icc 0 $ index K.1 K₀) @[simp] lemma mem_prehaar_empty {K₀ : set G} {f : compacts G → ℝ} : f ∈ haar_product K₀ ↔ ∀ K : compacts G, f K ∈ Icc (0 : ℝ) (index K.1 K₀) := by simp only [haar_product, pi, forall_prop_of_true, mem_univ, mem_set_of_eq] /-- The closure of the collection of elements of the form `prehaar K₀ U`, for `U` open neighbourhoods of `1`, contained in `V`. The closure is taken in the space `compacts G → ℝ`, with the topology of pointwise convergence. We show that the intersection of all these sets is nonempty, and the Haar measure on compact sets is defined to be an element in the closure of this intersection. -/ def cl_prehaar (K₀ : set G) (V : open_nhds_of (1 : G)) : set (compacts G → ℝ) := closure $ prehaar K₀ '' { U : set G | U ⊆ V.1 ∧ is_open U ∧ (1 : G) ∈ U } variables [topological_group G] /-! ### Lemmas about `index` -/ /-- If `K` is compact and `V` has nonempty interior, then the index `(K : V)` is well-defined, there is a finite set `t` satisfying the desired properties. -/ lemma index_defined {K V : set G} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ n : ℕ, n ∈ finset.card '' {t : finset G | K ⊆ ⋃ g ∈ t, (λ h, g * h) ⁻¹' V } := by { rcases compact_covered_by_mul_left_translates hK hV with ⟨t, ht⟩, exact ⟨t.card, t, ht, rfl⟩ } lemma index_elim {K V : set G} (hK : is_compact K) (hV : (interior V).nonempty) : ∃ (t : finset G), K ⊆ (⋃ g ∈ t, (λ h, g * h) ⁻¹' V) ∧ finset.card t = index K V := by { have := nat.Inf_mem (index_defined hK hV), rwa [mem_image] at this } lemma le_index_mul (K₀ : positive_compacts G) (K : compacts G) {V : set G} (hV : (interior V).nonempty) : index K.1 V ≤ index K.1 K₀.1 * index K₀.1 V := begin rcases index_elim K.2 K₀.2.2 with ⟨s, h1s, h2s⟩, rcases index_elim K₀.2.1 hV with ⟨t, h1t, h2t⟩, rw [← h2s, ← h2t, mul_comm], refine le_trans _ finset.mul_card_le, apply nat.Inf_le, refine ⟨_, _, rfl⟩, rw [mem_set_of_eq], refine subset.trans h1s _, apply bUnion_subset, intros g₁ hg₁, rw preimage_subset_iff, intros g₂ hg₂, have := h1t hg₂, rcases this with ⟨_, ⟨g₃, rfl⟩, A, ⟨hg₃, rfl⟩, h2V⟩, rw [mem_preimage, ← mul_assoc] at h2V, exact mem_bUnion (finset.mul_mem_mul hg₃ hg₁) h2V end lemma index_pos (K : positive_compacts G) {V : set G} (hV : (interior V).nonempty) : 0 < index K.1 V := begin unfold index, rw [nat.Inf_def, nat.find_pos, mem_image], { rintro ⟨t, h1t, h2t⟩, rw [finset.card_eq_zero] at h2t, subst h2t, cases K.2.2 with g hg, show g ∈ (∅ : set G), convert h1t (interior_subset hg), symmetry, apply bUnion_empty }, { exact index_defined K.2.1 hV } end lemma index_mono {K K' V : set G} (hK' : is_compact K') (h : K ⊆ K') (hV : (interior V).nonempty) : index K V ≤ index K' V := begin rcases index_elim hK' hV with ⟨s, h1s, h2s⟩, apply nat.Inf_le, rw [mem_image], refine ⟨s, subset.trans h h1s, h2s⟩ end lemma index_union_le (K₁ K₂ : compacts G) {V : set G} (hV : (interior V).nonempty) : index (K₁.1 ∪ K₂.1) V ≤ index K₁.1 V + index K₂.1 V := begin rcases index_elim K₁.2 hV with ⟨s, h1s, h2s⟩, rcases index_elim K₂.2 hV with ⟨t, h1t, h2t⟩, rw [← h2s, ← h2t], refine le_trans _ (finset.card_union_le _ _), apply nat.Inf_le, refine ⟨_, _, rfl⟩, rw [mem_set_of_eq], apply union_subset; refine subset.trans (by assumption) _; apply bUnion_subset_bUnion_left; intros g hg; simp only [mem_def] at hg; simp only [mem_def, multiset.mem_union, finset.union_val, hg, or_true, true_or] end lemma index_union_eq (K₁ K₂ : compacts G) {V : set G} (hV : (interior V).nonempty) (h : disjoint (K₁.1 * V⁻¹) (K₂.1 * V⁻¹)) : index (K₁.1 ∪ K₂.1) V = index K₁.1 V + index K₂.1 V := begin apply le_antisymm (index_union_le K₁ K₂ hV), rcases index_elim (K₁.2.union K₂.2) hV with ⟨s, h1s, h2s⟩, rw [← h2s], have : ∀ (K : set G) , K ⊆ (⋃ g ∈ s, (λ h, g * h) ⁻¹' V) → index K V ≤ (s.filter (λ g, ((λ (h : G), g * h) ⁻¹' V ∩ K).nonempty)).card, { intros K hK, apply nat.Inf_le, refine ⟨_, _, rfl⟩, rw [mem_set_of_eq], intros g hg, rcases hK hg with ⟨_, ⟨g₀, rfl⟩, _, ⟨h1g₀, rfl⟩, h2g₀⟩, simp only [mem_preimage] at h2g₀, simp only [mem_Union], use g₀, split, { simp only [finset.mem_filter, h1g₀, true_and], use g, simp only [hg, h2g₀, mem_inter_eq, mem_preimage, and_self] }, exact h2g₀ }, refine le_trans (add_le_add (this K₁.1 $ subset.trans (subset_union_left _ _) h1s) (this K₂.1 $ subset.trans (subset_union_right _ _) h1s)) _, rw [← finset.card_union_eq, finset.filter_union_right], exact s.card_filter_le _, apply finset.disjoint_filter.mpr, rintro g₁ h1g₁ ⟨g₂, h1g₂, h2g₂⟩ ⟨g₃, h1g₃, h2g₃⟩, simp only [mem_preimage] at h1g₃ h1g₂, apply @h g₁⁻¹, split; simp only [set.mem_inv, set.mem_mul, exists_exists_and_eq_and, exists_and_distrib_left], { refine ⟨_, h2g₂, (g₁ * g₂)⁻¹, _, _⟩, simp only [inv_inv, h1g₂], simp only [mul_inv_rev, mul_inv_cancel_left] }, { refine ⟨_, h2g₃, (g₁ * g₃)⁻¹, _, _⟩, simp only [inv_inv, h1g₃], simp only [mul_inv_rev, mul_inv_cancel_left] } end lemma mul_left_index_le {K : set G} (hK : is_compact K) {V : set G} (hV : (interior V).nonempty) (g : G) : index ((λ h, g * h) '' K) V ≤ index K V := begin rcases index_elim hK hV with ⟨s, h1s, h2s⟩, rw [← h2s], apply nat.Inf_le, rw [mem_image], refine ⟨s.map (equiv.mul_right g⁻¹).to_embedding, _, finset.card_map _⟩, { simp only [mem_set_of_eq], refine subset.trans (image_subset _ h1s) _, rintro _ ⟨g₁, ⟨_, ⟨g₂, rfl⟩, ⟨_, ⟨hg₂, rfl⟩, hg₁⟩⟩, rfl⟩, simp only [mem_preimage] at hg₁, simp only [exists_prop, mem_Union, finset.mem_map, equiv.coe_mul_right, exists_exists_and_eq_and, mem_preimage, equiv.to_embedding_apply], refine ⟨_, hg₂, _⟩, simp only [mul_assoc, hg₁, inv_mul_cancel_left] } end lemma is_left_invariant_index {K : set G} (hK : is_compact K) (g : G) {V : set G} (hV : (interior V).nonempty) : index ((λ h, g * h) '' K) V = index K V := begin refine le_antisymm (mul_left_index_le hK hV g) _, convert mul_left_index_le (hK.image $ continuous_mul_left g) hV g⁻¹, rw [image_image], symmetry, convert image_id' _, ext h, apply inv_mul_cancel_left end /-! ### Lemmas about `prehaar` -/ lemma prehaar_le_index (K₀ : positive_compacts G) {U : set G} (K : compacts G) (hU : (interior U).nonempty) : prehaar K₀.1 U K ≤ index K.1 K₀.1 := begin unfold prehaar, rw [div_le_iff]; norm_cast, { apply le_index_mul K₀ K hU }, { exact index_pos K₀ hU } end lemma prehaar_pos (K₀ : positive_compacts G) {U : set G} (hU : (interior U).nonempty) {K : set G} (h1K : is_compact K) (h2K : (interior K).nonempty) : 0 < prehaar K₀.1 U ⟨K, h1K⟩ := by { apply div_pos; norm_cast, apply index_pos ⟨K, h1K, h2K⟩ hU, exact index_pos K₀ hU } lemma prehaar_mono {K₀ : positive_compacts G} {U : set G} (hU : (interior U).nonempty) {K₁ K₂ : compacts G} (h : K₁.1 ⊆ K₂.1) : prehaar K₀.1 U K₁ ≤ prehaar K₀.1 U K₂ := begin simp only [prehaar], rw [div_le_div_right], exact_mod_cast index_mono K₂.2 h hU, exact_mod_cast index_pos K₀ hU end lemma prehaar_self {K₀ : positive_compacts G} {U : set G} (hU : (interior U).nonempty) : prehaar K₀.1 U ⟨K₀.1, K₀.2.1⟩ = 1 := by { simp only [prehaar], rw [div_self], apply ne_of_gt, exact_mod_cast index_pos K₀ hU } lemma prehaar_sup_le {K₀ : positive_compacts G} {U : set G} (K₁ K₂ : compacts G) (hU : (interior U).nonempty) : prehaar K₀.1 U (K₁ ⊔ K₂) ≤ prehaar K₀.1 U K₁ + prehaar K₀.1 U K₂ := begin simp only [prehaar], rw [div_add_div_same, div_le_div_right], exact_mod_cast index_union_le K₁ K₂ hU, exact_mod_cast index_pos K₀ hU end lemma prehaar_sup_eq {K₀ : positive_compacts G} {U : set G} {K₁ K₂ : compacts G} (hU : (interior U).nonempty) (h : disjoint (K₁.1 * U⁻¹) (K₂.1 * U⁻¹)) : prehaar K₀.1 U (K₁ ⊔ K₂) = prehaar K₀.1 U K₁ + prehaar K₀.1 U K₂ := by { simp only [prehaar], rw [div_add_div_same], congr', exact_mod_cast index_union_eq K₁ K₂ hU h } lemma is_left_invariant_prehaar {K₀ : positive_compacts G} {U : set G} (hU : (interior U).nonempty) (g : G) (K : compacts G) : prehaar K₀.1 U (K.map _ $ continuous_mul_left g) = prehaar K₀.1 U K := by simp only [prehaar, compacts.map_val, is_left_invariant_index K.2 _ hU] /-! ### Lemmas about `haar_product` -/ lemma prehaar_mem_haar_product (K₀ : positive_compacts G) {U : set G} (hU : (interior U).nonempty) : prehaar K₀.1 U ∈ haar_product K₀.1 := by { rintro ⟨K, hK⟩ h2K, rw [mem_Icc], exact ⟨prehaar_nonneg K₀ _, prehaar_le_index K₀ _ hU⟩ } lemma nonempty_Inter_cl_prehaar (K₀ : positive_compacts G) : (haar_product K₀.1 ∩ ⋂ (V : open_nhds_of (1 : G)), cl_prehaar K₀.1 V).nonempty := begin have : is_compact (haar_product K₀.1), { apply is_compact_univ_pi, intro K, apply is_compact_Icc }, refine this.inter_Inter_nonempty (cl_prehaar K₀.1) (λ s, is_closed_closure) (λ t, _), let V₀ := ⋂ (V ∈ t), (V : open_nhds_of 1).1, have h1V₀ : is_open V₀, { apply is_open_bInter, apply finite_mem_finset, rintro ⟨V, hV⟩ h2V, exact hV.1 }, have h2V₀ : (1 : G) ∈ V₀, { simp only [mem_Inter], rintro ⟨V, hV⟩ h2V, exact hV.2 }, refine ⟨prehaar K₀.1 V₀, _⟩, split, { apply prehaar_mem_haar_product K₀, use 1, rwa h1V₀.interior_eq }, { simp only [mem_Inter], rintro ⟨V, hV⟩ h2V, apply subset_closure, apply mem_image_of_mem, rw [mem_set_of_eq], exact ⟨subset.trans (Inter_subset _ ⟨V, hV⟩) (Inter_subset _ h2V), h1V₀, h2V₀⟩ }, end /-! ### Lemmas about `chaar` -/ /-- This is the "limit" of `prehaar K₀.1 U K` as `U` becomes a smaller and smaller open neighborhood of `(1 : G)`. More precisely, it is defined to be an arbitrary element in the intersection of all the sets `cl_prehaar K₀ V` in `haar_product K₀`. This is roughly equal to the Haar measure on compact sets, but it can differ slightly. We do know that `haar_measure K₀ (interior K.1) ≤ chaar K₀ K ≤ haar_measure K₀ K.1`. -/ def chaar (K₀ : positive_compacts G) (K : compacts G) : ℝ := classical.some (nonempty_Inter_cl_prehaar K₀) K lemma chaar_mem_haar_product (K₀ : positive_compacts G) : chaar K₀ ∈ haar_product K₀.1 := (classical.some_spec (nonempty_Inter_cl_prehaar K₀)).1 lemma chaar_mem_cl_prehaar (K₀ : positive_compacts G) (V : open_nhds_of (1 : G)) : chaar K₀ ∈ cl_prehaar K₀.1 V := by { have := (classical.some_spec (nonempty_Inter_cl_prehaar K₀)).2, rw [mem_Inter] at this, exact this V } lemma chaar_nonneg (K₀ : positive_compacts G) (K : compacts G) : 0 ≤ chaar K₀ K := by { have := chaar_mem_haar_product K₀ K (mem_univ _), rw mem_Icc at this, exact this.1 } lemma chaar_empty (K₀ : positive_compacts G) : chaar K₀ ⊥ = 0 := begin let eval : (compacts G → ℝ) → ℝ := λ f, f ⊥, have : continuous eval := continuous_apply ⊥, show chaar K₀ ∈ eval ⁻¹' {(0 : ℝ)}, apply mem_of_subset_of_mem _ (chaar_mem_cl_prehaar K₀ ⟨set.univ, is_open_univ, mem_univ _⟩), unfold cl_prehaar, rw is_closed.closure_subset_iff, { rintro _ ⟨U, ⟨h1U, h2U, h3U⟩, rfl⟩, apply prehaar_empty }, { apply continuous_iff_is_closed.mp this, exact is_closed_singleton }, end lemma chaar_self (K₀ : positive_compacts G) : chaar K₀ ⟨K₀.1, K₀.2.1⟩ = 1 := begin let eval : (compacts G → ℝ) → ℝ := λ f, f ⟨K₀.1, K₀.2.1⟩, have : continuous eval := continuous_apply _, show chaar K₀ ∈ eval ⁻¹' {(1 : ℝ)}, apply mem_of_subset_of_mem _ (chaar_mem_cl_prehaar K₀ ⟨set.univ, is_open_univ, mem_univ _⟩), unfold cl_prehaar, rw is_closed.closure_subset_iff, { rintro _ ⟨U, ⟨h1U, h2U, h3U⟩, rfl⟩, apply prehaar_self, rw h2U.interior_eq, exact ⟨1, h3U⟩ }, { apply continuous_iff_is_closed.mp this, exact is_closed_singleton } end lemma chaar_mono {K₀ : positive_compacts G} {K₁ K₂ : compacts G} (h : K₁.1 ⊆ K₂.1) : chaar K₀ K₁ ≤ chaar K₀ K₂ := begin let eval : (compacts G → ℝ) → ℝ := λ f, f K₂ - f K₁, have : continuous eval := (continuous_apply K₂).sub (continuous_apply K₁), rw [← sub_nonneg], show chaar K₀ ∈ eval ⁻¹' (Ici (0 : ℝ)), apply mem_of_subset_of_mem _ (chaar_mem_cl_prehaar K₀ ⟨set.univ, is_open_univ, mem_univ _⟩), unfold cl_prehaar, rw is_closed.closure_subset_iff, { rintro _ ⟨U, ⟨h1U, h2U, h3U⟩, rfl⟩, simp only [mem_preimage, mem_Ici, eval, sub_nonneg], apply prehaar_mono _ h, rw h2U.interior_eq, exact ⟨1, h3U⟩ }, { apply continuous_iff_is_closed.mp this, exact is_closed_Ici }, end lemma chaar_sup_le {K₀ : positive_compacts G} (K₁ K₂ : compacts G) : chaar K₀ (K₁ ⊔ K₂) ≤ chaar K₀ K₁ + chaar K₀ K₂ := begin let eval : (compacts G → ℝ) → ℝ := λ f, f K₁ + f K₂ - f (K₁ ⊔ K₂), have : continuous eval := ((@continuous_add ℝ _ _ _).comp ((continuous_apply K₁).prod_mk (continuous_apply K₂))).sub (continuous_apply (K₁ ⊔ K₂)), rw [← sub_nonneg], show chaar K₀ ∈ eval ⁻¹' (Ici (0 : ℝ)), apply mem_of_subset_of_mem _ (chaar_mem_cl_prehaar K₀ ⟨set.univ, is_open_univ, mem_univ _⟩), unfold cl_prehaar, rw is_closed.closure_subset_iff, { rintro _ ⟨U, ⟨h1U, h2U, h3U⟩, rfl⟩, simp only [mem_preimage, mem_Ici, eval, sub_nonneg], apply prehaar_sup_le, rw h2U.interior_eq, exact ⟨1, h3U⟩ }, { apply continuous_iff_is_closed.mp this, exact is_closed_Ici }, end lemma chaar_sup_eq [t2_space G] {K₀ : positive_compacts G} {K₁ K₂ : compacts G} (h : disjoint K₁.1 K₂.1) : chaar K₀ (K₁ ⊔ K₂) = chaar K₀ K₁ + chaar K₀ K₂ := begin rcases compact_compact_separated K₁.2 K₂.2 (disjoint_iff.mp h) with ⟨U₁, U₂, h1U₁, h1U₂, h2U₁, h2U₂, hU⟩, rw [← disjoint_iff_inter_eq_empty] at hU, rcases compact_open_separated_mul K₁.2 h1U₁ h2U₁ with ⟨V₁, h1V₁, h2V₁, h3V₁⟩, rcases compact_open_separated_mul K₂.2 h1U₂ h2U₂ with ⟨V₂, h1V₂, h2V₂, h3V₂⟩, let eval : (compacts G → ℝ) → ℝ := λ f, f K₁ + f K₂ - f (K₁ ⊔ K₂), have : continuous eval := ((@continuous_add ℝ _ _ _).comp ((continuous_apply K₁).prod_mk (continuous_apply K₂))).sub (continuous_apply (K₁ ⊔ K₂)), rw [eq_comm, ← sub_eq_zero], show chaar K₀ ∈ eval ⁻¹' {(0 : ℝ)}, let V := V₁ ∩ V₂, apply mem_of_subset_of_mem _ (chaar_mem_cl_prehaar K₀ ⟨V⁻¹, (is_open.inter h1V₁ h1V₂).preimage continuous_inv, by simp only [mem_inv, one_inv, h2V₁, h2V₂, V, mem_inter_eq, true_and]⟩), unfold cl_prehaar, rw is_closed.closure_subset_iff, { rintro _ ⟨U, ⟨h1U, h2U, h3U⟩, rfl⟩, simp only [mem_preimage, eval, sub_eq_zero, mem_singleton_iff], rw [eq_comm], apply prehaar_sup_eq, { rw h2U.interior_eq, exact ⟨1, h3U⟩ }, { refine disjoint_of_subset _ _ hU, { refine subset.trans (mul_subset_mul subset.rfl _) h3V₁, exact subset.trans (inv_subset.mpr h1U) (inter_subset_left _ _) }, { refine subset.trans (mul_subset_mul subset.rfl _) h3V₂, exact subset.trans (inv_subset.mpr h1U) (inter_subset_right _ _) }}}, { apply continuous_iff_is_closed.mp this, exact is_closed_singleton }, end lemma is_left_invariant_chaar {K₀ : positive_compacts G} (g : G) (K : compacts G) : chaar K₀ (K.map _ $ continuous_mul_left g) = chaar K₀ K := begin let eval : (compacts G → ℝ) → ℝ := λ f, f (K.map _ $ continuous_mul_left g) - f K, have : continuous eval := (continuous_apply (K.map _ _)).sub (continuous_apply K), rw [← sub_eq_zero], show chaar K₀ ∈ eval ⁻¹' {(0 : ℝ)}, apply mem_of_subset_of_mem _ (chaar_mem_cl_prehaar K₀ ⟨set.univ, is_open_univ, mem_univ _⟩), unfold cl_prehaar, rw is_closed.closure_subset_iff, { rintro _ ⟨U, ⟨h1U, h2U, h3U⟩, rfl⟩, simp only [mem_singleton_iff, mem_preimage, eval, sub_eq_zero], apply is_left_invariant_prehaar, rw h2U.interior_eq, exact ⟨1, h3U⟩ }, { apply continuous_iff_is_closed.mp this, exact is_closed_singleton }, end variable [t2_space G] /-- The function `chaar` interpreted in `ℝ≥0`, as a content -/ def haar_content (K₀ : positive_compacts G) : content G := { to_fun := λ K, ⟨chaar K₀ K, chaar_nonneg _ _⟩, mono' := λ K₁ K₂ h, by simp only [←nnreal.coe_le_coe, subtype.coe_mk, chaar_mono, h], sup_disjoint' := λ K₁ K₂ h, by { simp only [chaar_sup_eq h], refl }, sup_le' := λ K₁ K₂, by simp only [←nnreal.coe_le_coe, nnreal.coe_add, subtype.coe_mk, chaar_sup_le] } /-! We only prove the properties for `haar_content` that we use at least twice below. -/ lemma haar_content_apply (K₀ : positive_compacts G) (K : compacts G) : haar_content K₀ K = show nnreal, from ⟨chaar K₀ K, chaar_nonneg _ _⟩ := rfl /-- The variant of `chaar_self` for `haar_content` -/ lemma haar_content_self {K₀ : positive_compacts G} : haar_content K₀ ⟨K₀.1, K₀.2.1⟩ = 1 := by { simp_rw [← ennreal.coe_one, haar_content_apply, ennreal.coe_eq_coe, chaar_self], refl } /-- The variant of `is_left_invariant_chaar` for `haar_content` -/ lemma is_left_invariant_haar_content {K₀ : positive_compacts G} (g : G) (K : compacts G) : haar_content K₀ (K.map _ $ continuous_mul_left g) = haar_content K₀ K := by simpa only [ennreal.coe_eq_coe, ←nnreal.coe_eq, haar_content_apply] using is_left_invariant_chaar g K lemma haar_content_outer_measure_self_pos {K₀ : positive_compacts G} : 0 < (haar_content K₀).outer_measure K₀.1 := begin apply ennreal.zero_lt_one.trans_le, rw [content.outer_measure_eq_infi], refine le_binfi _, intros U hU, refine le_infi _, intros h2U, refine le_trans (le_of_eq _) (le_bsupr ⟨K₀.1, K₀.2.1⟩ h2U), exact haar_content_self.symm end end haar open haar /-! ### The Haar measure -/ variables [topological_space G] [t2_space G] [topological_group G] [measurable_space G] [borel_space G] /-- the Haar measure on `G`, scaled so that `haar_measure K₀ K₀ = 1`. -/ def haar_measure (K₀ : positive_compacts G) : measure G := ((haar_content K₀).outer_measure K₀.1)⁻¹ • (haar_content K₀).measure lemma haar_measure_apply {K₀ : positive_compacts G} {s : set G} (hs : measurable_set s) : haar_measure K₀ s = (haar_content K₀).outer_measure s / (haar_content K₀).outer_measure K₀.1 := by simp only [haar_measure, hs, div_eq_mul_inv, mul_comm, content.measure_apply, algebra.id.smul_eq_mul, pi.smul_apply, measure.coe_smul] lemma is_mul_left_invariant_haar_measure (K₀ : positive_compacts G) : is_mul_left_invariant (haar_measure K₀) := begin intros g A hA, rw [haar_measure_apply hA, haar_measure_apply (measurable_const_mul g hA)], congr' 1, apply content.is_mul_left_invariant_outer_measure, apply is_left_invariant_haar_content, end lemma haar_measure_self [locally_compact_space G] {K₀ : positive_compacts G} : haar_measure K₀ K₀.1 = 1 := begin rw [haar_measure_apply K₀.2.1.measurable_set, ennreal.div_self], { rw [← pos_iff_ne_zero], exact haar_content_outer_measure_self_pos }, { exact ne_of_lt (content.outer_measure_lt_top_of_is_compact _ K₀.2.1) } end lemma haar_measure_pos_of_is_open [locally_compact_space G] {K₀ : positive_compacts G} {U : set G} (hU : is_open U) (h2U : U.nonempty) : 0 < haar_measure K₀ U := begin rw [haar_measure_apply hU.measurable_set, ennreal.div_pos_iff], refine ⟨_, ne_of_lt $ content.outer_measure_lt_top_of_is_compact _ K₀.2.1⟩, rw [← pos_iff_ne_zero], exact content.outer_measure_pos_of_is_mul_left_invariant _ is_left_invariant_haar_content ⟨K₀.1, K₀.2.1⟩ (by simp only [haar_content_self, ennreal.zero_lt_one]) hU h2U end /-- The Haar measure is regular. -/ instance regular_haar_measure [locally_compact_space G] {K₀ : positive_compacts G} : (haar_measure K₀).regular := begin apply regular.smul, rw ennreal.inv_lt_top, exact haar_content_outer_measure_self_pos, end section unique variables [locally_compact_space G] [second_countable_topology G] {μ : measure G} [sigma_finite μ] /-- The Haar measure is unique up to scaling. More precisely: every σ-finite left invariant measure is a scalar multiple of the Haar measure. -/ theorem haar_measure_unique (hμ : is_mul_left_invariant μ) (K₀ : positive_compacts G) : μ = μ K₀.1 • haar_measure K₀ := begin ext1 s hs, have := measure_mul_measure_eq hμ (is_mul_left_invariant_haar_measure K₀) K₀.2.1 hs, rw [haar_measure_self, one_mul] at this, rw [← this (by norm_num), smul_apply], end theorem regular_of_left_invariant (hμ : is_mul_left_invariant μ) {K} (hK : is_compact K) (h2K : (interior K).nonempty) (hμK : μ K < ∞) : regular μ := begin rw [haar_measure_unique hμ ⟨K, hK, h2K⟩], exact regular.smul hμK end end unique end measure end measure_theory
8e09baae85a5fa82776a19535547fda45ebcc18e
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/control/monad.lean
eafc109cd59d6c2ca4cf52c53d7c3b80acefdf1f
[ "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
1,054
lean
/- Copyright (c) Luke Nelson and Jared Roesch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Luke Nelson, Jared Roesch, Sebastian Ullrich -/ prelude import init.control.applicative universes u v open function class has_bind (m : Type u → Type v) := (bind : Π {α β : Type u}, m α → (α → m β) → m β) export has_bind (bind) @[inline] def has_bind.and_then {α β : Type u} {m : Type u → Type v} [has_bind m] (x : m α) (y : m β) : m β := do x, y infixl ` >>= `:55 := bind infixl ` >> `:55 := has_bind.and_then class monad (m : Type u → Type v) extends applicative m, has_bind m : Type (max (u+1) v) := (map := λ α β f x, x >>= pure ∘ f) (seq := λ α β f x, f >>= (<$> x)) @[reducible, inline] def return {m : Type u → Type v} [monad m] {α : Type u} : α → m α := pure /-- Identical to `has_bind.and_then`, but it is not inlined. -/ def has_bind.seq {α β : Type u} {m : Type u → Type v} [has_bind m] (x : m α) (y : m β) : m β := do x, y
336e7e44d460c7c79064ad3583acb0a3d547b0a4
63abd62053d479eae5abf4951554e1064a4c45b4
/src/algebra/gcd_monoid.lean
7ab501e7c259d6468cf7d04dcecb0779fdc19272
[ "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
35,097
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker TODO: Provide a GCD monoid instance for `ℕ`, port GCD facts about nats TODO: Generalize normalization monoids commutative (cancellative) monoids with or without zero TODO: Generalize GCD monoid to not require normalization in all cases -/ import algebra.associated /-! # Monoids with normalization functions, `gcd`, and `lcm` This file defines extra structures on `comm_cancel_monoid_with_zero`s, including `integral_domain`s. ## Main Definitions * `normalization_monoid` * `gcd_monoid` * `gcd_monoid_of_exists_gcd` * `gcd_monoid_of_exists_lcm` ## Implementation Notes * `normalization_monoid` is defined by assigning to each element a `norm_unit` such that multiplying by that unit normalizes the monoid, and `normalize` is an idempotent monoid homomorphism. This definition as currently implemented does casework on `0`. * `gcd_monoid` extends `normalization_monoid`, so the `gcd` and `lcm` are always normalized. This makes `gcd`s of polynomials easier to work with, but excludes Euclidean domains, and monoids without zero. * `gcd_monoid_of_gcd` noncomputably constructs a `gcd_monoid` structure just from the `gcd` and its properties. * `gcd_monoid_of_exists_gcd` noncomputably constructs a `gcd_monoid` structure just from a proof that any two elements have a (not necessarily normalized) `gcd`. * `gcd_monoid_of_lcm` noncomputably constructs a `gcd_monoid` structure just from the `lcm` and its properties. * `gcd_monoid_of_exists_lcm` noncomputably constructs a `gcd_monoid` structure just from a proof that any two elements have a (not necessarily normalized) `lcm`. ## TODO * Provide a GCD monoid instance for `ℕ`, port GCD facts about nats, definition of coprime * Generalize normalization monoids to commutative (cancellative) monoids with or without zero * Generalize GCD monoid to not require normalization in all cases ## Tags divisibility, gcd, lcm, normalize -/ variables {α : Type*} set_option old_structure_cmd true /-- Normalization monoid: multiplying with `norm_unit` gives a normal form for associated elements. -/ @[protect_proj] class normalization_monoid (α : Type*) [nontrivial α] [comm_cancel_monoid_with_zero α] := (norm_unit : α → units α) (norm_unit_zero : norm_unit 0 = 1) (norm_unit_mul : ∀{a b}, a ≠ 0 → b ≠ 0 → norm_unit (a * b) = norm_unit a * norm_unit b) (norm_unit_coe_units : ∀(u : units α), norm_unit u = u⁻¹) export normalization_monoid (norm_unit norm_unit_zero norm_unit_mul norm_unit_coe_units) attribute [simp] norm_unit_coe_units norm_unit_zero norm_unit_mul section normalization_monoid variables [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] @[simp] theorem norm_unit_one : norm_unit (1:α) = 1 := norm_unit_coe_units 1 /-- Chooses an element of each associate class, by multiplying by `norm_unit` -/ def normalize : α →* α := { to_fun := λ x, x * norm_unit x, map_one' := by rw [norm_unit_one, units.coe_one, mul_one], map_mul' := λ x y, classical.by_cases (λ hx : x = 0, by rw [hx, zero_mul, zero_mul, zero_mul]) $ λ hx, classical.by_cases (λ hy : y = 0, by rw [hy, mul_zero, zero_mul, mul_zero]) $ λ hy, by simp only [norm_unit_mul hx hy, units.coe_mul]; simp only [mul_assoc, mul_left_comm y], } theorem associated_normalize {x : α} : associated x (normalize x) := ⟨_, rfl⟩ theorem normalize_associated {x : α} : associated (normalize x) x := associated_normalize.symm lemma associates.mk_normalize {x : α} : associates.mk (normalize x) = associates.mk x := associates.mk_eq_mk_iff_associated.2 normalize_associated @[simp] lemma normalize_apply {x : α} : normalize x = x * norm_unit x := rfl @[simp] lemma normalize_zero : normalize (0 : α) = 0 := by simp @[simp] lemma normalize_one : normalize (1 : α) = 1 := normalize.map_one lemma normalize_coe_units (u : units α) : normalize (u : α) = 1 := by simp lemma normalize_eq_zero {x : α} : normalize x = 0 ↔ x = 0 := ⟨λ hx, (associated_zero_iff_eq_zero x).1 $ hx ▸ associated_normalize, by rintro rfl; exact normalize_zero⟩ lemma normalize_eq_one {x : α} : normalize x = 1 ↔ is_unit x := ⟨λ hx, is_unit_iff_exists_inv.2 ⟨_, hx⟩, λ ⟨u, hu⟩, hu ▸ normalize_coe_units u⟩ @[simp] theorem norm_unit_mul_norm_unit (a : α) : norm_unit (a * norm_unit a) = 1 := classical.by_cases (assume : a = 0, by simp only [this, norm_unit_zero, zero_mul]) $ assume h, by rw [norm_unit_mul h (units.ne_zero _), norm_unit_coe_units, mul_inv_eq_one] theorem normalize_idem (x : α) : normalize (normalize x) = normalize x := by simp theorem normalize_eq_normalize {a b : α} (hab : a ∣ b) (hba : b ∣ a) : normalize a = normalize b := begin rcases associated_of_dvd_dvd hab hba with ⟨u, rfl⟩, refine classical.by_cases (by rintro rfl; simp only [zero_mul]) (assume ha : a ≠ 0, _), suffices : a * ↑(norm_unit a) = a * ↑u * ↑(norm_unit a) * ↑u⁻¹, by simpa only [normalize_apply, mul_assoc, norm_unit_mul ha u.ne_zero, norm_unit_coe_units], calc a * ↑(norm_unit a) = a * ↑(norm_unit a) * ↑u * ↑u⁻¹: (units.mul_inv_cancel_right _ _).symm ... = a * ↑u * ↑(norm_unit a) * ↑u⁻¹ : by rw mul_right_comm a end lemma normalize_eq_normalize_iff {x y : α} : normalize x = normalize y ↔ x ∣ y ∧ y ∣ x := ⟨λ h, ⟨units.dvd_mul_right.1 ⟨_, h.symm⟩, units.dvd_mul_right.1 ⟨_, h⟩⟩, λ ⟨hxy, hyx⟩, normalize_eq_normalize hxy hyx⟩ theorem dvd_antisymm_of_normalize_eq {a b : α} (ha : normalize a = a) (hb : normalize b = b) (hab : a ∣ b) (hba : b ∣ a) : a = b := ha ▸ hb ▸ normalize_eq_normalize hab hba --can be proven by simp lemma dvd_normalize_iff {a b : α} : a ∣ normalize b ↔ a ∣ b := units.dvd_mul_right --can be proven by simp lemma normalize_dvd_iff {a b : α} : normalize a ∣ b ↔ a ∣ b := units.mul_right_dvd end normalization_monoid namespace comm_group_with_zero variables [decidable_eq α] [comm_group_with_zero α] @[priority 100] -- see Note [lower instance priority] instance : normalization_monoid α := { norm_unit := λ x, if h : x = 0 then 1 else (units.mk0 x h)⁻¹, norm_unit_zero := dif_pos rfl, norm_unit_mul := λ x y x0 y0, units.eq_iff.1 (by simp [x0, y0, mul_inv']), norm_unit_coe_units := λ u, by { rw [dif_neg (units.ne_zero _), units.mk0_coe], apply_instance } } @[simp] lemma coe_norm_unit {a : α} (h0 : a ≠ 0) : (↑(norm_unit a) : α) = a⁻¹ := by simp [norm_unit, h0] end comm_group_with_zero namespace associates variables [comm_cancel_monoid_with_zero α] [nontrivial α] [normalization_monoid α] local attribute [instance] associated.setoid /-- Maps an element of `associates` back to the normalized element of its associate class -/ protected def out : associates α → α := quotient.lift (normalize : α → α) $ λ a b ⟨u, hu⟩, hu ▸ normalize_eq_normalize ⟨_, rfl⟩ (units.mul_right_dvd.2 $ dvd_refl a) lemma out_mk (a : α) : (associates.mk a).out = normalize a := rfl @[simp] lemma out_one : (1 : associates α).out = 1 := normalize_one lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out := quotient.induction_on₂ a b $ assume a b, by simp only [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk, normalize.map_mul] lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] @[simp] lemma out_top : (⊤ : associates α).out = 0 := normalize_zero @[simp] lemma normalize_out (a : associates α) : normalize a.out = a.out := quotient.induction_on a normalize_idem end associates /-- GCD monoid: a `comm_cancel_monoid_with_zero` with normalization and `gcd` (greatest common divisor) and `lcm` (least common multiple) operations. In this setting `gcd` and `lcm` form a bounded lattice on the associated elements where `gcd` is the infimum, `lcm` is the supremum, `1` is bottom, and `0` is top. The type class focuses on `gcd` and we derive the corresponding `lcm` facts from `gcd`. -/ @[protect_proj] class gcd_monoid (α : Type*) [comm_cancel_monoid_with_zero α] [nontrivial α] extends normalization_monoid α := (gcd : α → α → α) (lcm : α → α → α) (gcd_dvd_left : ∀a b, gcd a b ∣ a) (gcd_dvd_right : ∀a b, gcd a b ∣ b) (dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) (normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) (gcd_mul_lcm : ∀a b, gcd a b * lcm a b = normalize (a * b)) (lcm_zero_left : ∀a, lcm 0 a = 0) (lcm_zero_right : ∀a, lcm a 0 = 0) export gcd_monoid (gcd lcm gcd_dvd_left gcd_dvd_right dvd_gcd lcm_zero_left lcm_zero_right) attribute [simp] lcm_zero_left lcm_zero_right section gcd_monoid variables [comm_cancel_monoid_with_zero α] [nontrivial α] [gcd_monoid α] @[simp] theorem normalize_gcd : ∀a b:α, normalize (gcd a b) = gcd a b := gcd_monoid.normalize_gcd @[simp] theorem gcd_mul_lcm : ∀a b:α, gcd a b * lcm a b = normalize (a * b) := gcd_monoid.gcd_mul_lcm section gcd theorem dvd_gcd_iff (a b c : α) : a ∣ gcd b c ↔ (a ∣ b ∧ a ∣ c) := iff.intro (assume h, ⟨dvd_trans h (gcd_dvd_left _ _), dvd_trans h (gcd_dvd_right _ _)⟩) (assume ⟨hab, hac⟩, dvd_gcd hab hac) theorem gcd_comm (a b : α) : gcd a b = gcd b a := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) (dvd_gcd (gcd_dvd_right _ _) (gcd_dvd_left _ _)) theorem gcd_assoc (m n k : α) : gcd (gcd m n) k = gcd m (gcd n k) := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_left m n)) (dvd_gcd (dvd.trans (gcd_dvd_left (gcd m n) k) (gcd_dvd_right m n)) (gcd_dvd_right (gcd m n) k))) (dvd_gcd (dvd_gcd (gcd_dvd_left m (gcd n k)) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_left n k))) (dvd.trans (gcd_dvd_right m (gcd n k)) (gcd_dvd_right n k))) instance : is_commutative α gcd := ⟨gcd_comm⟩ instance : is_associative α gcd := ⟨gcd_assoc⟩ theorem gcd_eq_normalize {a b c : α} (habc : gcd a b ∣ c) (hcab : c ∣ gcd a b) : gcd a b = normalize c := normalize_gcd a b ▸ normalize_eq_normalize habc hcab @[simp] theorem gcd_zero_left (a : α) : gcd 0 a = normalize a := gcd_eq_normalize (gcd_dvd_right 0 a) (dvd_gcd (dvd_zero _) (dvd_refl a)) @[simp] theorem gcd_zero_right (a : α) : gcd a 0 = normalize a := gcd_eq_normalize (gcd_dvd_left a 0) (dvd_gcd (dvd_refl a) (dvd_zero _)) @[simp] theorem gcd_eq_zero_iff (a b : α) : gcd a b = 0 ↔ a = 0 ∧ b = 0 := iff.intro (assume h, let ⟨ca, ha⟩ := gcd_dvd_left a b, ⟨cb, hb⟩ := gcd_dvd_right a b in by rw [h, zero_mul] at ha hb; exact ⟨ha, hb⟩) (assume ⟨ha, hb⟩, by rw [ha, hb, gcd_zero_left, normalize_zero]) @[simp] theorem gcd_one_left (a : α) : gcd 1 a = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_left _ _) (one_dvd _) @[simp] theorem gcd_one_right (a : α) : gcd a 1 = 1 := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) normalize_one (gcd_dvd_right _ _) (one_dvd _) theorem gcd_dvd_gcd {a b c d: α} (hab : a ∣ b) (hcd : c ∣ d) : gcd a c ∣ gcd b d := dvd_gcd (dvd.trans (gcd_dvd_left _ _) hab) (dvd.trans (gcd_dvd_right _ _) hcd) @[simp] theorem gcd_same (a : α) : gcd a a = normalize a := gcd_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_refl a)) @[simp] theorem gcd_mul_left (a b c : α) : gcd (a * b) (a * c) = normalize a * gcd b c := classical.by_cases (by rintro rfl; simp only [zero_mul, gcd_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices gcd (a * b) (a * c) = normalize (a * gcd b c), by simpa only [normalize.map_mul, normalize_gcd], let ⟨d, eq⟩ := dvd_gcd (dvd_mul_right a b) (dvd_mul_right a c) in gcd_eq_normalize (eq.symm ▸ mul_dvd_mul_left a $ show d ∣ gcd b c, from dvd_gcd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ gcd_dvd_right _ _)) (dvd_gcd (mul_dvd_mul_left a $ gcd_dvd_left _ _) (mul_dvd_mul_left a $ gcd_dvd_right _ _)) @[simp] theorem gcd_mul_right (a b c : α) : gcd (b * a) (c * a) = gcd b c * normalize a := by simp only [mul_comm, gcd_mul_left] theorem gcd_eq_left_iff (a b : α) (h : normalize a = a) : gcd a b = a ↔ a ∣ b := iff.intro (assume eq, eq ▸ gcd_dvd_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_gcd _ _) h (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) hab) theorem gcd_eq_right_iff (a b : α) (h : normalize b = b) : gcd a b = b ↔ b ∣ a := by simpa only [gcd_comm a b] using gcd_eq_left_iff b a h theorem gcd_dvd_gcd_mul_left (m n k : α) : gcd m n ∣ gcd (k * m) n := gcd_dvd_gcd (dvd_mul_left _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_right (m n k : α) : gcd m n ∣ gcd (m * k) n := gcd_dvd_gcd (dvd_mul_right _ _) (dvd_refl _) theorem gcd_dvd_gcd_mul_left_right (m n k : α) : gcd m n ∣ gcd m (k * n) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_left _ _) theorem gcd_dvd_gcd_mul_right_right (m n k : α) : gcd m n ∣ gcd m (n * k) := gcd_dvd_gcd (dvd_refl _) (dvd_mul_right _ _) theorem gcd_eq_of_associated_left {m n : α} (h : associated m n) (k : α) : gcd m k = gcd n k := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (gcd_dvd_gcd (dvd_of_associated h) (dvd_refl _)) (gcd_dvd_gcd (dvd_of_associated h.symm) (dvd_refl _)) theorem gcd_eq_of_associated_right {m n : α} (h : associated m n) (k : α) : gcd k m = gcd k n := dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _) (gcd_dvd_gcd (dvd_refl _) (dvd_of_associated h)) (gcd_dvd_gcd (dvd_refl _) (dvd_of_associated h.symm)) lemma dvd_gcd_mul_of_dvd_mul {m n k : α} (H : k ∣ m * n) : k ∣ (gcd k m) * n := begin transitivity gcd k m * normalize n, { rw ← gcd_mul_right, exact dvd_gcd (dvd_mul_right _ _) H }, { apply dvd.intro ↑(norm_unit n)⁻¹, rw [normalize_apply, mul_assoc, mul_assoc, ← units.coe_mul], simp } end lemma dvd_mul_gcd_of_dvd_mul {m n k : α} (H : k ∣ m * n) : k ∣ m * gcd k n := by { rw mul_comm at H ⊢, exact dvd_gcd_mul_of_dvd_mul H } /-- Represent a divisor of `m * n` as a product of a divisor of `m` and a divisor of `n`. Note: In general, this representation is highly non-unique. -/ lemma exists_dvd_and_dvd_of_dvd_mul {m n k : α} (H : k ∣ m * n) : ∃ d₁ (hd₁ : d₁ ∣ m) d₂ (hd₂ : d₂ ∣ n), k = d₁ * d₂ := begin by_cases h0 : gcd k m = 0, { rw gcd_eq_zero_iff at h0, rcases h0 with ⟨rfl, rfl⟩, refine ⟨0, dvd_refl 0, n, dvd_refl n, _⟩, simp }, { obtain ⟨a, ha⟩ := gcd_dvd_left k m, refine ⟨gcd k m, gcd_dvd_right _ _, a, _, ha⟩, suffices h : gcd k m * a ∣ gcd k m * n, { cases h with b hb, use b, rw mul_assoc at hb, apply mul_left_cancel' h0 hb }, rw ← ha, exact dvd_gcd_mul_of_dvd_mul H } end theorem gcd_mul_dvd_mul_gcd (k m n : α) : gcd k (m * n) ∣ gcd k m * gcd k n := begin obtain ⟨m', hm', n', hn', h⟩ := (exists_dvd_and_dvd_of_dvd_mul $ gcd_dvd_right k (m * n)), replace h : gcd k (m * n) = m' * n' := h, rw h, have hm'n' : m' * n' ∣ k := h ▸ gcd_dvd_left _ _, apply mul_dvd_mul, { have hm'k : m' ∣ k := dvd_trans (dvd_mul_right m' n') hm'n', exact dvd_gcd hm'k hm' }, { have hn'k : n' ∣ k := dvd_trans (dvd_mul_left n' m') hm'n', exact dvd_gcd hn'k hn' } end theorem gcd_pow_right_dvd_pow_gcd {a b : α} {k : ℕ} : gcd a (b ^ k) ∣ (gcd a b) ^ k := begin by_cases hg : gcd a b = 0, { rw gcd_eq_zero_iff at hg, rcases hg with ⟨rfl, rfl⟩, simp }, { induction k with k hk, simp, rw [pow_succ, pow_succ], transitivity gcd a b * gcd a (b ^ k), apply gcd_mul_dvd_mul_gcd a b (b ^ k), refine (mul_dvd_mul_iff_left hg).mpr hk } end theorem gcd_pow_left_dvd_pow_gcd {a b : α} {k : ℕ} : gcd (a ^ k) b ∣ (gcd a b) ^ k := by { rw [gcd_comm, gcd_comm a b], exact gcd_pow_right_dvd_pow_gcd } theorem pow_dvd_of_mul_eq_pow {a b c d₁ d₂ : α} (ha : a ≠ 0) (hab : gcd a b = 1) {k : ℕ} (h : a * b = c ^ k) (hc : c = d₁ * d₂) (hd₁ : d₁ ∣ a) : d₁ ^ k ≠ 0 ∧ d₁ ^ k ∣ a := begin have h1 : gcd (d₁ ^ k) b = 1, { rw ← normalize_gcd (d₁ ^ k) b, rw normalize_eq_one, apply is_unit_of_dvd_one, transitivity (gcd d₁ b) ^ k, { exact gcd_pow_left_dvd_pow_gcd }, { apply is_unit.dvd, apply is_unit.pow, apply is_unit_of_dvd_one, rw ← hab, apply gcd_dvd_gcd hd₁ (dvd_refl b) } }, have h2 : d₁ ^ k ∣ a * b, { use d₂ ^ k, rw [h, hc], exact mul_pow d₁ d₂ k }, rw mul_comm at h2, have h3 : d₁ ^ k ∣ a, { rw [← one_mul a, ← h1], apply dvd_gcd_mul_of_dvd_mul h2 }, have h4 : d₁ ^ k ≠ 0, { intro hdk, rw hdk at h3, apply absurd (zero_dvd_iff.mp h3) ha }, tauto end theorem exists_associated_pow_of_mul_eq_pow {a b c : α} (hab : gcd a b = 1) {k : ℕ} (h : a * b = c ^ k) : ∃ (d : α), associated (d ^ k) a := begin by_cases ha : a = 0, { use 0, rw ha, by_cases hk : k = 0, { exfalso, revert h, rw [ha, hk, zero_mul, pow_zero], apply zero_ne_one }, { rw zero_pow (nat.pos_of_ne_zero hk) }}, by_cases hb : b = 0, { rw [hb, gcd_zero_right] at hab, use 1, rw one_pow, apply (associated_one_iff_is_unit.mpr (normalize_eq_one.mp hab)).symm }, by_cases hk : k = 0, { use 1, rw [hk, pow_zero] at h ⊢, use units.mk_of_mul_eq_one _ _ h, rw [units.coe_mk_of_mul_eq_one, one_mul] }, have hc : c ∣ a * b, { rw h, refine dvd_pow (dvd_refl c) hk }, obtain ⟨d₁, hd₁, d₂, hd₂, hc⟩ := exists_dvd_and_dvd_of_dvd_mul hc, use d₁, obtain ⟨h0₁, ⟨a', ha'⟩⟩ := pow_dvd_of_mul_eq_pow ha hab h hc hd₁, rw [mul_comm] at h hc, rw [gcd_comm] at hab, obtain ⟨h0₂, ⟨b', hb'⟩⟩ := pow_dvd_of_mul_eq_pow hb hab h hc hd₂, rw [ha', hb', hc, mul_pow] at h, have h' : a' * b' = 1, { apply (mul_right_inj' h0₁).mp, rw mul_one, apply (mul_right_inj' h0₂).mp, rw ← h, rw [mul_assoc, mul_comm a', ← mul_assoc (d₁ ^ k), ← mul_assoc _ (d₁ ^ k), mul_comm b'] }, use units.mk_of_mul_eq_one _ _ h', rw [units.coe_mk_of_mul_eq_one, ha'] end end gcd section lcm lemma lcm_dvd_iff {a b c : α} : lcm a b ∣ c ↔ a ∣ c ∧ b ∣ c := classical.by_cases (assume : a = 0 ∨ b = 0, by rcases this with rfl | rfl; simp only [iff_def, lcm_zero_left, lcm_zero_right, zero_dvd_iff, dvd_zero, eq_self_iff_true, and_true, imp_true_iff] {contextual:=tt}) (assume this : ¬ (a = 0 ∨ b = 0), let ⟨h1, h2⟩ := not_or_distrib.1 this in have h : gcd a b ≠ 0, from λ H, h1 ((gcd_eq_zero_iff _ _).1 H).1, by rw [← mul_dvd_mul_iff_left h, gcd_mul_lcm, normalize_dvd_iff, ← dvd_normalize_iff, normalize.map_mul, normalize_gcd, ← gcd_mul_right, dvd_gcd_iff, mul_comm b c, mul_dvd_mul_iff_left h1, mul_dvd_mul_iff_right h2, and_comm]) lemma dvd_lcm_left (a b : α) : a ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).1 lemma dvd_lcm_right (a b : α) : b ∣ lcm a b := (lcm_dvd_iff.1 (dvd_refl _)).2 lemma lcm_dvd {a b c : α} (hab : a ∣ b) (hcb : c ∣ b) : lcm a c ∣ b := lcm_dvd_iff.2 ⟨hab, hcb⟩ @[simp] theorem lcm_eq_zero_iff (a b : α) : lcm a b = 0 ↔ a = 0 ∨ b = 0 := iff.intro (assume h : lcm a b = 0, have normalize (a * b) = 0, by rw [← gcd_mul_lcm _ _, h, mul_zero], by simpa only [normalize_eq_zero, mul_eq_zero, units.ne_zero, or_false]) (by rintro (rfl | rfl); [apply lcm_zero_left, apply lcm_zero_right]) @[simp] lemma normalize_lcm (a b : α) : normalize (lcm a b) = lcm a b := classical.by_cases (assume : lcm a b = 0, by rw [this, normalize_zero]) $ assume h_lcm : lcm a b ≠ 0, have h1 : gcd a b ≠ 0, from mt (by rw [gcd_eq_zero_iff, lcm_eq_zero_iff]; rintros ⟨rfl, rfl⟩; left; refl) h_lcm, have h2 : normalize (gcd a b * lcm a b) = gcd a b * lcm a b, by rw [gcd_mul_lcm, normalize_idem], by simpa only [normalize.map_mul, normalize_gcd, one_mul, mul_right_inj' h1] using h2 theorem lcm_comm (a b : α) : lcm a b = lcm b a := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd_lcm_right _ _) (dvd_lcm_left _ _)) theorem lcm_assoc (m n k : α) : lcm (lcm m n) k = lcm m (lcm n k) := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd (lcm_dvd (dvd_lcm_left _ _) (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_right _ _))) (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_right _ _))) (lcm_dvd (dvd.trans (dvd_lcm_left _ _) (dvd_lcm_left _ _)) (lcm_dvd (dvd.trans (dvd_lcm_right _ _) (dvd_lcm_left _ _)) (dvd_lcm_right _ _))) instance : is_commutative α lcm := ⟨lcm_comm⟩ instance : is_associative α lcm := ⟨lcm_assoc⟩ lemma lcm_eq_normalize {a b c : α} (habc : lcm a b ∣ c) (hcab : c ∣ lcm a b) : lcm a b = normalize c := normalize_lcm a b ▸ normalize_eq_normalize habc hcab theorem lcm_dvd_lcm {a b c d : α} (hab : a ∣ b) (hcd : c ∣ d) : lcm a c ∣ lcm b d := lcm_dvd (dvd.trans hab (dvd_lcm_left _ _)) (dvd.trans hcd (dvd_lcm_right _ _)) @[simp] theorem lcm_units_coe_left (u : units α) (a : α) : lcm ↑u a = normalize a := lcm_eq_normalize (lcm_dvd units.coe_dvd (dvd_refl _)) (dvd_lcm_right _ _) @[simp] theorem lcm_units_coe_right (a : α) (u : units α) : lcm a ↑u = normalize a := (lcm_comm a u).trans $ lcm_units_coe_left _ _ @[simp] theorem lcm_one_left (a : α) : lcm 1 a = normalize a := lcm_units_coe_left 1 a @[simp] theorem lcm_one_right (a : α) : lcm a 1 = normalize a := lcm_units_coe_right a 1 @[simp] theorem lcm_same (a : α) : lcm a a = normalize a := lcm_eq_normalize (lcm_dvd (dvd_refl _) (dvd_refl _)) (dvd_lcm_left _ _) @[simp] theorem lcm_eq_one_iff (a b : α) : lcm a b = 1 ↔ a ∣ 1 ∧ b ∣ 1 := iff.intro (assume eq, eq ▸ ⟨dvd_lcm_left _ _, dvd_lcm_right _ _⟩) (assume ⟨⟨c, hc⟩, ⟨d, hd⟩⟩, show lcm (units.mk_of_mul_eq_one a c hc.symm : α) (units.mk_of_mul_eq_one b d hd.symm) = 1, by rw [lcm_units_coe_left, normalize_coe_units]) @[simp] theorem lcm_mul_left (a b c : α) : lcm (a * b) (a * c) = normalize a * lcm b c := classical.by_cases (by rintro rfl; simp only [zero_mul, lcm_zero_left, normalize_zero]) $ assume ha : a ≠ 0, suffices lcm (a * b) (a * c) = normalize (a * lcm b c), by simpa only [normalize.map_mul, normalize_lcm], have a ∣ lcm (a * b) (a * c), from dvd.trans (dvd_mul_right _ _) (dvd_lcm_left _ _), let ⟨d, eq⟩ := this in lcm_eq_normalize (lcm_dvd (mul_dvd_mul_left a (dvd_lcm_left _ _)) (mul_dvd_mul_left a (dvd_lcm_right _ _))) (eq.symm ▸ (mul_dvd_mul_left a $ lcm_dvd ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_left _ _) ((mul_dvd_mul_iff_left ha).1 $ eq ▸ dvd_lcm_right _ _))) @[simp] theorem lcm_mul_right (a b c : α) : lcm (b * a) (c * a) = lcm b c * normalize a := by simp only [mul_comm, lcm_mul_left] theorem lcm_eq_left_iff (a b : α) (h : normalize a = a) : lcm a b = a ↔ b ∣ a := iff.intro (assume eq, eq ▸ dvd_lcm_right _ _) $ assume hab, dvd_antisymm_of_normalize_eq (normalize_lcm _ _) h (lcm_dvd (dvd_refl a) hab) (dvd_lcm_left _ _) theorem lcm_eq_right_iff (a b : α) (h : normalize b = b) : lcm a b = b ↔ a ∣ b := by simpa only [lcm_comm b a] using lcm_eq_left_iff b a h theorem lcm_dvd_lcm_mul_left (m n k : α) : lcm m n ∣ lcm (k * m) n := lcm_dvd_lcm (dvd_mul_left _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_right (m n k : α) : lcm m n ∣ lcm (m * k) n := lcm_dvd_lcm (dvd_mul_right _ _) (dvd_refl _) theorem lcm_dvd_lcm_mul_left_right (m n k : α) : lcm m n ∣ lcm m (k * n) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_left _ _) theorem lcm_dvd_lcm_mul_right_right (m n k : α) : lcm m n ∣ lcm m (n * k) := lcm_dvd_lcm (dvd_refl _) (dvd_mul_right _ _) theorem lcm_eq_of_associated_left {m n : α} (h : associated m n) (k : α) : lcm m k = lcm n k := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd_lcm (dvd_of_associated h) (dvd_refl _)) (lcm_dvd_lcm (dvd_of_associated h.symm) (dvd_refl _)) theorem lcm_eq_of_associated_right {m n : α} (h : associated m n) (k : α) : lcm k m = lcm k n := dvd_antisymm_of_normalize_eq (normalize_lcm _ _) (normalize_lcm _ _) (lcm_dvd_lcm (dvd_refl _) (dvd_of_associated h)) (lcm_dvd_lcm (dvd_refl _) (dvd_of_associated h.symm)) end lcm namespace gcd_monoid theorem prime_of_irreducible {x : α} (hi: irreducible x) : prime x := ⟨hi.ne_zero, ⟨hi.1, λ a b h, begin cases gcd_dvd_left x a with y hy, cases hi.2 _ _ hy with hu hu; cases hu with u hu, { right, transitivity (gcd (x * b) (a * b)), apply dvd_gcd (dvd_mul_right x b) h, rw gcd_mul_right, rw ← hu, apply dvd_of_associated, transitivity (normalize b), symmetry, use u, apply mul_comm, apply normalize_associated, }, { left, rw [hy, ← hu], transitivity, {apply dvd_of_associated, symmetry, use u}, apply gcd_dvd_right, } end ⟩⟩ theorem irreducible_iff_prime {p : α} : irreducible p ↔ prime p := ⟨prime_of_irreducible, irreducible_of_prime⟩ end gcd_monoid end gcd_monoid section unique_unit variables [comm_cancel_monoid_with_zero α] [unique (units α)] lemma units_eq_one (u : units α) : u = 1 := subsingleton.elim u 1 variable [nontrivial α] @[priority 100] -- see Note [lower instance priority] instance normalization_monoid_of_unique_units : normalization_monoid α := { norm_unit := λ x, 1, norm_unit_zero := rfl, norm_unit_mul := λ x y hx hy, (mul_one 1).symm, norm_unit_coe_units := λ u, subsingleton.elim _ _ } @[simp] lemma norm_unit_eq_one (x : α) : norm_unit x = 1 := rfl @[simp] lemma normalize_eq (x : α) : normalize x = x := mul_one x end unique_unit section integral_domain variables [integral_domain α] [gcd_monoid α] lemma gcd_eq_of_dvd_sub_right {a b c : α} (h : a ∣ b - c) : gcd a b = gcd a c := begin apply dvd_antisymm_of_normalize_eq (normalize_gcd _ _) (normalize_gcd _ _); rw dvd_gcd_iff; refine ⟨gcd_dvd_left _ _, _⟩, { rcases h with ⟨d, hd⟩, rcases gcd_dvd_right a b with ⟨e, he⟩, rcases gcd_dvd_left a b with ⟨f, hf⟩, use e - f * d, rw [mul_sub, ← he, ← mul_assoc, ← hf, ← hd, sub_sub_cancel] }, { rcases h with ⟨d, hd⟩, rcases gcd_dvd_right a c with ⟨e, he⟩, rcases gcd_dvd_left a c with ⟨f, hf⟩, use e + f * d, rw [mul_add, ← he, ← mul_assoc, ← hf, ← hd, ← add_sub_assoc, add_comm c b, add_sub_cancel] } end lemma gcd_eq_of_dvd_sub_left {a b c : α} (h : a ∣ b - c) : gcd b a = gcd c a := by rw [gcd_comm _ a, gcd_comm _ a, gcd_eq_of_dvd_sub_right h] end integral_domain section constructors noncomputable theory open associates variables [comm_cancel_monoid_with_zero α] [nontrivial α] private lemma map_mk_unit_aux [decidable_eq α] {f : associates α →* α} (hinv : function.right_inverse f associates.mk) (a : α) : a * ↑(classical.some (associated_map_mk hinv a)) = f (associates.mk a) := classical.some_spec (associated_map_mk hinv a) /-- Define `normalization_monoid` on a structure from a `monoid_hom` inverse to `associates.mk`. -/ def normalization_monoid_of_monoid_hom_right_inverse [decidable_eq α] (f : associates α →* α) (hinv : function.right_inverse f associates.mk) : normalization_monoid α := { norm_unit := λ a, if a = 0 then 1 else classical.some (associates.mk_eq_mk_iff_associated.1 (hinv (associates.mk a)).symm), norm_unit_zero := if_pos rfl, norm_unit_mul := λ a b ha hb, by { rw [if_neg (mul_ne_zero ha hb), if_neg ha, if_neg hb, units.ext_iff, units.coe_mul], suffices : (a * b) * ↑(classical.some (associated_map_mk hinv (a * b))) = (a * ↑(classical.some (associated_map_mk hinv a))) * (b * ↑(classical.some (associated_map_mk hinv b))), { apply mul_left_cancel' (mul_ne_zero ha hb) _, simpa only [mul_assoc, mul_comm, mul_left_comm] using this }, rw [map_mk_unit_aux hinv a, map_mk_unit_aux hinv (a * b), map_mk_unit_aux hinv b, ← monoid_hom.map_mul, associates.mk_mul_mk] }, norm_unit_coe_units := λ u, by { rw [if_neg (units.ne_zero u), units.ext_iff], apply mul_left_cancel' (units.ne_zero u), rw [units.mul_inv, map_mk_unit_aux hinv u, associates.mk_eq_mk_iff_associated.2 (associated_one_iff_is_unit.2 ⟨u, rfl⟩), associates.mk_one, monoid_hom.map_one] } } variable [normalization_monoid α] /-- Define `gcd_monoid` on a structure just from the `gcd` and its properties. -/ noncomputable def gcd_monoid_of_gcd [decidable_eq α] (gcd : α → α → α) (gcd_dvd_left : ∀a b, gcd a b ∣ a) (gcd_dvd_right : ∀a b, gcd a b ∣ b) (dvd_gcd : ∀{a b c}, a ∣ c → a ∣ b → a ∣ gcd c b) (normalize_gcd : ∀a b, normalize (gcd a b) = gcd a b) : gcd_monoid α := { gcd := gcd, gcd_dvd_left := gcd_dvd_left, gcd_dvd_right := gcd_dvd_right, dvd_gcd := λ a b c, dvd_gcd, normalize_gcd := normalize_gcd, lcm := λ a b, if a = 0 then 0 else classical.some (dvd_normalize_iff.2 (dvd.trans (gcd_dvd_left a b) (dvd.intro b rfl))), gcd_mul_lcm := λ a b, by { split_ifs with a0, { rw [mul_zero, a0, zero_mul, normalize_zero] }, { exact (classical.some_spec (dvd_normalize_iff.2 (dvd.trans (gcd_dvd_left a b) (dvd.intro b rfl)))).symm } }, lcm_zero_left := λ a, if_pos rfl, lcm_zero_right := λ a, by { split_ifs with a0, { refl }, rw ← normalize_eq_zero at a0, have h := (classical.some_spec (dvd_normalize_iff.2 (dvd.trans (gcd_dvd_left a 0) (dvd.intro 0 rfl)))).symm, have gcd0 : gcd a 0 = normalize a, { rw ← normalize_gcd, exact normalize_eq_normalize (gcd_dvd_left _ _) (dvd_gcd (dvd_refl a) (dvd_zero a)) }, rw ← gcd0 at a0, apply or.resolve_left (mul_eq_zero.1 _) a0, rw [h, mul_zero, normalize_zero] }, .. (infer_instance : normalization_monoid α) } /-- Define `gcd_monoid` on a structure just from the `lcm` and its properties. -/ noncomputable def gcd_monoid_of_lcm [decidable_eq α] (lcm : α → α → α) (dvd_lcm_left : ∀a b, a ∣ lcm a b) (dvd_lcm_right : ∀a b, b ∣ lcm a b) (lcm_dvd : ∀{a b c}, c ∣ a → b ∣ a → lcm c b ∣ a) (normalize_lcm : ∀a b, normalize (lcm a b) = lcm a b) : gcd_monoid α := let exists_gcd := λ a b, dvd_normalize_iff.2 (lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl)) in { lcm := lcm, gcd := λ a b, if a = 0 then normalize b else (if b = 0 then normalize a else classical.some (exists_gcd a b)), gcd_mul_lcm := λ a b, by { split_ifs, { rw [h, zero_dvd_iff.1 (dvd_lcm_left _ _), mul_zero, zero_mul, normalize_zero] }, { rw [h_1, zero_dvd_iff.1 (dvd_lcm_right _ _), mul_zero, mul_zero, normalize_zero] }, apply eq.trans (mul_comm _ _) (classical.some_spec (dvd_normalize_iff.2 (lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl)))).symm }, normalize_gcd := λ a b, by { split_ifs, { apply normalize_idem }, { apply normalize_idem }, have h0 : lcm a b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, apply mul_left_cancel' h0, refine trans _ (classical.some_spec (exists_gcd a b)), conv_lhs { congr, rw [← normalize_lcm a b] }, erw [← normalize.map_mul, ← classical.some_spec (exists_gcd a b), normalize_idem] }, lcm_zero_left := λ a, zero_dvd_iff.1 (dvd_lcm_left _ _), lcm_zero_right := λ a, zero_dvd_iff.1 (dvd_lcm_right _ _), gcd_dvd_left := λ a b, by { split_ifs, { rw h, apply dvd_zero }, { apply dvd_of_associated normalize_associated }, have h0 : lcm a b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b), normalize_dvd_iff, mul_comm, mul_dvd_mul_iff_right h], apply dvd_lcm_right }, gcd_dvd_right := λ a b, by { split_ifs, { apply dvd_of_associated normalize_associated }, { rw h_1, apply dvd_zero }, have h0 : lcm a b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left a rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (exists_gcd a b), normalize_dvd_iff, mul_dvd_mul_iff_right h_1], apply dvd_lcm_left }, dvd_gcd := λ a b c ac ab, by { split_ifs, { apply dvd_normalize_iff.2 ab }, { apply dvd_normalize_iff.2 ac }, have h0 : lcm c b ≠ 0, { intro con, have h := lcm_dvd (dvd.intro b rfl) (dvd.intro_left c rfl), rw [con, zero_dvd_iff, mul_eq_zero] at h, cases h; tauto }, rw [← mul_dvd_mul_iff_left h0, ← classical.some_spec (dvd_normalize_iff.2 (lcm_dvd (dvd.intro b rfl) (dvd.intro_left c rfl))), dvd_normalize_iff], rcases ab with ⟨d, rfl⟩, rw mul_eq_zero at h_1, push_neg at h_1, rw [mul_comm a, ← mul_assoc, mul_dvd_mul_iff_right h_1.1], apply lcm_dvd (dvd.intro d rfl), rw [mul_comm, mul_dvd_mul_iff_right h_1.2], apply ac }, .. (infer_instance : normalization_monoid α) } /-- Define a `gcd_monoid` structure on a monoid just from the existence of a `gcd`. -/ noncomputable def gcd_monoid_of_exists_gcd [decidable_eq α] (h : ∀ a b : α, ∃ c : α, ∀ d : α, d ∣ a ∧ d ∣ b ↔ d ∣ c) : gcd_monoid α := gcd_monoid_of_gcd (λ a b, normalize (classical.some (h a b))) (λ a b, normalize_dvd_iff.2 (((classical.some_spec (h a b) (classical.some (h a b))).2 (dvd_refl _))).1) (λ a b, normalize_dvd_iff.2 (((classical.some_spec (h a b) (classical.some (h a b))).2 (dvd_refl _))).2) (λ a b c ac ab, dvd_normalize_iff.2 ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩)) (λ a b, normalize_idem _) /-- Define a `gcd_monoid` structure on a monoid just from the existence of an `lcm`. -/ noncomputable def gcd_monoid_of_exists_lcm [decidable_eq α] (h : ∀ a b : α, ∃ c : α, ∀ d : α, a ∣ d ∧ b ∣ d ↔ c ∣ d) : gcd_monoid α := gcd_monoid_of_lcm (λ a b, normalize (classical.some (h a b))) (λ a b, dvd_normalize_iff.2 (((classical.some_spec (h a b) (classical.some (h a b))).2 (dvd_refl _))).1) (λ a b, dvd_normalize_iff.2 (((classical.some_spec (h a b) (classical.some (h a b))).2 (dvd_refl _))).2) (λ a b c ac ab, normalize_dvd_iff.2 ((classical.some_spec (h c b) a).1 ⟨ac, ab⟩)) (λ a b, normalize_idem _) end constructors
449d10ea89ca49a921dc17f9c67f3f2b77a0d5e1
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/09_Type_Classes.org.23.lean
40986860aae02e4b139e6cf6f0e5524122600ee3
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
54
lean
import standard set_option class.instance_max_depth 5
3008c60dbe7bcd8c80c2b2d49ffb8b18f1c79a3b
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/ring_theory/subring.lean
8b4448e19c8ded140500fac4f02c04aecde0cf76
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
31,895
lean
/- Copyright (c) 2020 Ashvni Narayanan. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors : Ashvni Narayanan -/ import deprecated.subring import group_theory.subgroup import ring_theory.subsemiring /-! # Subrings Let `R` be a ring. This file defines the "bundled" subring type `subring R`, a type whose terms correspond to subrings of `R`. This is the preferred way to talk about subrings in mathlib. Unbundled subrings (`s : set R` and `is_subring s`) are not in this file, and they will ultimately be deprecated. We prove that subrings are a complete lattice, and that you can `map` (pushforward) and `comap` (pull back) them along ring homomorphisms. We define the `closure` construction from `set R` to `subring R`, sending a subset of `R` to the subring it generates, and prove that it is a Galois insertion. ## Main definitions Notation used here: `(R : Type u) [ring R] (S : Type u) [ring S] (f g : R →+* S)` `(A : subring R) (B : subring S) (s : set R)` * `subring R` : the type of subrings of a ring `R`. * `instance : complete_lattice (subring R)` : the complete lattice structure on the subrings. * `subring.closure` : subring closure of a set, i.e., the smallest subring that includes the set. * `subring.gi` : `closure : set M → subring M` and coercion `coe : subring M → set M` form a `galois_insertion`. * `comap f B : subring A` : the preimage of a subring `B` along the ring homomorphism `f` * `map f A : subring B` : the image of a subring `A` along the ring homomorphism `f`. * `prod A B : subring (R × S)` : the product of subrings * `f.range : subring B` : the range of the ring homomorphism `f`. * `eq_locus f g : subring R` : given ring homomorphisms `f g : R →+* S`, the subring of `R` where `f x = g x` ## Implementation notes A subring is implemented as a subsemiring which is also an additive subgroup. The initial PR was as a submonoid which is also an additive subgroup. Lattice inclusion (e.g. `≤` and `⊓`) is used rather than set notation (`⊆` and `∩`), although `∈` is defined as membership of a subring's underlying set. ## Tags subring, subrings -/ open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {T : Type w} [ring R] [ring S] [ring T] set_option old_structure_cmd true /-- `subring R` is the type of subrings of `R`. A subring of `R` is a subset `s` that is a multiplicative submonoid and an additive subgroup. Note in particular that it shares the same 0 and 1 as R. -/ structure subring (R : Type u) [ring R] extends subsemiring R, add_subgroup R /-- Reinterpret a `subring` as a `subsemiring`. -/ add_decl_doc subring.to_subsemiring /-- Reinterpret a `subring` as an `add_subgroup`. -/ add_decl_doc subring.to_add_subgroup namespace subring /-- The underlying submonoid of a subring. -/ def to_submonoid (s : subring R) : submonoid R := { carrier := s.carrier, ..s.to_subsemiring.to_submonoid } instance : has_coe (subring R) (set R) := ⟨subring.carrier⟩ instance : has_mem R (subring R) := ⟨λ m S, m ∈ (S:set R)⟩ instance : has_coe_to_sort (subring R) := ⟨Type*, λ S, {x : R // x ∈ S}⟩ /-- Construct a `subring R` from a set `s`, a submonoid `sm`, and an additive subgroup `sa` such that `x ∈ s ↔ x ∈ sm ↔ x ∈ sa`. -/ protected def mk' (s : set R) (sm : submonoid R) (sa : add_subgroup R) (hm : ↑sm = s) (ha : ↑sa = s) : subring R := { carrier := s, zero_mem' := ha ▸ sa.zero_mem, one_mem' := hm ▸ sm.one_mem, add_mem' := λ x y, by simpa only [← ha] using sa.add_mem, mul_mem' := λ x y, by simpa only [← hm] using sm.mul_mem, neg_mem' := λ x, by simpa only [← ha] using sa.neg_mem, } @[simp] lemma coe_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) : (subring.mk' s sm sa hm ha : set R) = s := rfl @[simp] lemma mem_mk' {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) {x : R} : x ∈ subring.mk' s sm sa hm ha ↔ x ∈ s := iff.rfl @[simp] lemma mk'_to_submonoid {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa = s) : (subring.mk' s sm sa hm ha).to_submonoid = sm := submonoid.ext' hm.symm @[simp] lemma mk'_to_add_subgroup {s : set R} {sm : submonoid R} (hm : ↑sm = s) {sa : add_subgroup R} (ha : ↑sa =s) : (subring.mk' s sm sa hm ha).to_add_subgroup = sa := add_subgroup.ext' ha.symm end subring /-- Construct a `subring` from a set satisfying `is_subring`. -/ def set.to_subring (S : set R) [is_subring S] : subring R := { carrier := S, one_mem' := is_submonoid.one_mem, mul_mem' := λ a b, is_submonoid.mul_mem, zero_mem' := is_add_submonoid.zero_mem, add_mem' := λ a b, is_add_submonoid.add_mem, neg_mem' := λ a, is_add_subgroup.neg_mem } protected lemma subring.exists {s : subring R} {p : s → Prop} : (∃ x : s, p x) ↔ ∃ x ∈ s, p ⟨x, ‹x ∈ s›⟩ := set_coe.exists protected lemma subring.forall {s : subring R} {p : s → Prop} : (∀ x : s, p x) ↔ ∀ x ∈ s, p ⟨x, ‹x ∈ s›⟩ := set_coe.forall /-- A `subsemiring` containing -1 is a `subring`. -/ def subsemiring.to_subring (s : subsemiring R) (hneg : (-1 : R) ∈ s) : subring R := { neg_mem' := by { rintros x, rw <-neg_one_mul, apply subsemiring.mul_mem, exact hneg, } ..s.to_submonoid, ..s.to_add_submonoid } namespace subring variables (s : subring R) /-- Two subrings are equal if the underlying subsets are equal. -/ theorem ext' ⦃s t : subring R⦄ (h : (s : set R) = t) : s = t := by { cases s, cases t, congr' } /-- Two subrings are equal if and only if the underlying subsets are equal. -/ protected theorem ext'_iff {s t : subring R} : s = t ↔ (s : set R) = t := ⟨λ h, h ▸ rfl, λ h, ext' h⟩ /-- Two subrings are equal if they have the same elements. -/ @[ext] theorem ext {S T : subring R} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h /-- A subring contains the ring's 1. -/ theorem one_mem : (1 : R) ∈ s := s.one_mem' /-- A subring contains the ring's 0. -/ theorem zero_mem : (0 : R) ∈ s := s.zero_mem' /-- A subring is closed under multiplication. -/ theorem mul_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x * y ∈ s := s.mul_mem' /-- A subring is closed under addition. -/ theorem add_mem : ∀ {x y : R}, x ∈ s → y ∈ s → x + y ∈ s := s.add_mem' /-- A subring is closed under negation. -/ theorem neg_mem : ∀ {x : R}, x ∈ s → -x ∈ s := s.neg_mem' /-- A subring is closed under subtraction -/ theorem sub_mem {x y : R} (hx : x ∈ s) (hy : y ∈ s) : x - y ∈ s := by { rw sub_eq_add_neg, exact s.add_mem hx (s.neg_mem hy) } /-- Product of a list of elements in a subring is in the subring. -/ lemma list_prod_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.prod ∈ s := s.to_submonoid.list_prod_mem /-- Sum of a list of elements in a subring is in the subring. -/ lemma list_sum_mem {l : list R} : (∀x ∈ l, x ∈ s) → l.sum ∈ s := s.to_add_subgroup.list_sum_mem /-- Product of a multiset of elements in a subring of a `comm_ring` is in the subring. -/ lemma multiset_prod_mem {R} [comm_ring R] (s : subring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.prod ∈ s := s.to_submonoid.multiset_prod_mem m /-- Sum of a multiset of elements in an `subring` of a `ring` is in the `subring`. -/ lemma multiset_sum_mem {R} [ring R] (s : subring R) (m : multiset R) : (∀a ∈ m, a ∈ s) → m.sum ∈ s := s.to_add_subgroup.multiset_sum_mem m /-- Product of elements of a subring of a `comm_ring` indexed by a `finset` is in the subring. -/ lemma prod_mem {R : Type*} [comm_ring R] (s : subring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∏ i in t, f i ∈ s := s.to_submonoid.prod_mem h /-- Sum of elements in a `subring` of a `ring` indexed by a `finset` is in the `subring`. -/ lemma sum_mem {R : Type*} [ring R] (s : subring R) {ι : Type*} {t : finset ι} {f : ι → R} (h : ∀c ∈ t, f c ∈ s) : ∑ i in t, f i ∈ s := s.to_add_subgroup.sum_mem h lemma pow_mem {x : R} (hx : x ∈ s) (n : ℕ) : x^n ∈ s := s.to_submonoid.pow_mem hx n lemma gsmul_mem {x : R} (hx : x ∈ s) (n : ℤ) : n •ℤ x ∈ s := s.to_add_subgroup.gsmul_mem hx n lemma coe_int_mem (n : ℤ) : (n : R) ∈ s := by simp only [← gsmul_one, gsmul_mem, one_mem] /-- A subring of a ring inherits a ring structure -/ instance to_ring : ring s := { right_distrib := λ x y z, subtype.eq $ right_distrib x y z, left_distrib := λ x y z, subtype.eq $ left_distrib x y z, .. s.to_submonoid.to_monoid, .. s.to_add_subgroup.to_add_comm_group } @[simp, norm_cast] lemma coe_add (x y : s) : (↑(x + y) : R) = ↑x + ↑y := rfl @[simp, norm_cast] lemma coe_neg (x : s) : (↑(-x) : R) = -↑x := rfl @[simp, norm_cast] lemma coe_mul (x y : s) : (↑(x * y) : R) = ↑x * ↑y := rfl @[simp, norm_cast] lemma coe_zero : ((0 : s) : R) = 0 := rfl @[simp, norm_cast] lemma coe_one : ((1 : s) : R) = 1 := rfl @[simp] lemma coe_eq_zero_iff {x : s} : (x : R) = 0 ↔ x = 0 := ⟨λ h, subtype.ext (trans h s.coe_zero.symm), λ h, h.symm ▸ s.coe_zero⟩ /-- A subring of a `comm_ring` is a `comm_ring`. -/ instance to_comm_ring {R} [comm_ring R] (s : subring R) : comm_ring s := { mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..subring.to_ring s} /-- The natural ring hom from a subring of ring `R` to `R`. -/ def subtype (s : subring R) : s →+* R := { to_fun := coe, .. s.to_submonoid.subtype, .. s.to_add_subgroup.subtype } @[simp] theorem coe_subtype : ⇑s.subtype = coe := rfl /-! # Partial order -/ instance : partial_order (subring R) := { le := λ s t, ∀ ⦃x⦄, x ∈ s → x ∈ t, .. partial_order.lift (coe : subring R → set R) ext' } lemma le_def {s t : subring R} : s ≤ t ↔ ∀ ⦃x : R⦄, x ∈ s → x ∈ t := iff.rfl @[simp, norm_cast] lemma coe_subset_coe {s t : subring R} : (s : set R) ⊆ t ↔ s ≤ t := iff.rfl @[simp, norm_cast] lemma coe_ssubset_coe {s t : subring R} : (s : set R) ⊂ t ↔ s < t := iff.rfl @[simp, norm_cast] lemma mem_coe {S : subring R} {m : R} : m ∈ (S : set R) ↔ m ∈ S := iff.rfl @[simp, norm_cast] lemma coe_coe (s : subring R) : ↥(s : set R) = s := rfl @[simp] lemma mem_to_submonoid {s : subring R} {x : R} : x ∈ s.to_submonoid ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_submonoid (s : subring R) : (s.to_submonoid : set R) = s := rfl @[simp] lemma mem_to_add_subgroup {s : subring R} {x : R} : x ∈ s.to_add_subgroup ↔ x ∈ s := iff.rfl @[simp] lemma coe_to_add_subgroup (s : subring R) : (s.to_add_subgroup : set R) = s := rfl /-! # top -/ /-- The subring `R` of the ring `R`. -/ instance : has_top (subring R) := ⟨{ .. (⊤ : submonoid R), .. (⊤ : add_subgroup R) }⟩ @[simp] lemma mem_top (x : R) : x ∈ (⊤ : subring R) := set.mem_univ x @[simp] lemma coe_top : ((⊤ : subring R) : set R) = set.univ := rfl /-! # comap -/ /-- The preimage of a subring along a ring homomorphism is a subring. -/ def comap {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring S) : subring R := { carrier := f ⁻¹' s.carrier, .. s.to_submonoid.comap (f : R →* S), .. s.to_add_subgroup.comap (f : R →+ S) } @[simp] lemma coe_comap (s : subring S) (f : R →+* S) : (s.comap f : set R) = f ⁻¹' s := rfl @[simp] lemma mem_comap {s : subring S} {f : R →+* S} {x : R} : x ∈ s.comap f ↔ f x ∈ s := iff.rfl lemma comap_comap (s : subring T) (g : S →+* T) (f : R →+* S) : (s.comap g).comap f = s.comap (g.comp f) := rfl /-! # map -/ /-- The image of a subring along a ring homomorphism is a subring. -/ def map {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring R) : subring S := { carrier := f '' s.carrier, .. s.to_submonoid.map (f : R →* S), .. s.to_add_subgroup.map (f : R →+ S) } @[simp] lemma coe_map (f : R →+* S) (s : subring R) : (s.map f : set S) = f '' s := rfl @[simp] lemma mem_map {f : R →+* S} {s : subring R} {y : S} : y ∈ s.map f ↔ ∃ x ∈ s, f x = y := set.mem_image_iff_bex lemma map_map (g : S →+* T) (f : R →+* S) : (s.map f).map g = s.map (g.comp f) := ext' $ set.image_image _ _ _ lemma map_le_iff_le_comap {f : R →+* S} {s : subring R} {t : subring S} : s.map f ≤ t ↔ s ≤ t.comap f := set.image_subset_iff lemma gc_map_comap (f : R →+* S) : galois_connection (map f) (comap f) := λ S T, map_le_iff_le_comap end subring namespace ring_hom variables (g : S →+* T) (f : R →+* S) /-! # range -/ /-- The range of a ring homomorphism, as a subring of the target. -/ def range {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) : subring S := (⊤ : subring R).map f @[simp] lemma coe_range : (f.range : set S) = set.range f := set.image_univ @[simp] lemma mem_range {f : R →+* S} {y : S} : y ∈ f.range ↔ ∃ x, f x = y := by simp [range] lemma mem_range_self (f : R →+* S) (x : R) : f x ∈ f.range := mem_range.mpr ⟨x, rfl⟩ lemma map_range : f.range.map g = (g.comp f).range := (⊤ : subring R).map_map g f -- TODO -- rename to `cod_restrict` when is_ring_hom is deprecated /-- Restrict the codomain of a ring homomorphism to a subring that includes the range. -/ def cod_restrict' {R : Type u} {S : Type v} [ring R] [ring S] (f : R →+* S) (s : subring S) (h : ∀ x, f x ∈ s) : R →+* s := { to_fun := λ x, ⟨f x, h x⟩, map_add' := λ x y, subtype.eq $ f.map_add x y, map_zero' := subtype.eq f.map_zero, map_mul' := λ x y, subtype.eq $ f.map_mul x y, map_one' := subtype.eq f.map_one } end ring_hom namespace subring variables {cR : Type u} [comm_ring cR] /-- A subring of a commutative ring is a commutative ring. -/ def subset_comm_ring (S : subring cR) : comm_ring S := {mul_comm := λ _ _, subtype.eq $ mul_comm _ _, ..subring.to_ring S} /-- A subring of a non-trivial ring is non-trivial. -/ instance {D : Type*} [ring D] [nontrivial D] (S : subring D) : nontrivial S := S.to_subsemiring.nontrivial /-- A subring of a ring with no zero divisors has no zero divisors. -/ instance {D : Type*} [ring D] [no_zero_divisors D] (S : subring D) : no_zero_divisors S := S.to_subsemiring.no_zero_divisors /-- A subring of an integral domain is an integral domain. -/ instance subring.domain {D : Type*} [integral_domain D] (S : subring D) : integral_domain S := { .. S.nontrivial, .. S.no_zero_divisors, .. S.subset_comm_ring } /-! # bot -/ instance : has_bot (subring R) := ⟨(int.cast_ring_hom R).range⟩ instance : inhabited (subring R) := ⟨⊥⟩ lemma coe_bot : ((⊥ : subring R) : set R) = set.range (coe : ℤ → R) := ring_hom.coe_range (int.cast_ring_hom R) lemma mem_bot {x : R} : x ∈ (⊥ : subring R) ↔ ∃ (n : ℤ), ↑n = x := ring_hom.mem_range /-! # inf -/ /-- The inf of two subrings is their intersection. -/ instance : has_inf (subring R) := ⟨λ s t, { carrier := s ∩ t, .. s.to_submonoid ⊓ t.to_submonoid, .. s.to_add_subgroup ⊓ t.to_add_subgroup }⟩ @[simp] lemma coe_inf (p p' : subring R) : ((p ⊓ p' : subring R) : set R) = p ∩ p' := rfl @[simp] lemma mem_inf {p p' : subring R} {x : R} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl instance : has_Inf (subring R) := ⟨λ s, subring.mk' (⋂ t ∈ s, ↑t) (⨅ t ∈ s, subring.to_submonoid t ) (⨅ t ∈ s, subring.to_add_subgroup t) (by simp) (by simp)⟩ @[simp, norm_cast] lemma coe_Inf (S : set (subring R)) : ((Inf S : subring R) : set R) = ⋂ s ∈ S, ↑s := rfl lemma mem_Inf {S : set (subring R)} {x : R} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[simp] lemma Inf_to_submonoid (s : set (subring R)) : (Inf s).to_submonoid = ⨅ t ∈ s, subring.to_submonoid t := mk'_to_submonoid _ _ @[simp] lemma Inf_to_add_subgroup (s : set (subring R)) : (Inf s).to_add_subgroup = ⨅ t ∈ s, subring.to_add_subgroup t := mk'_to_add_subgroup _ _ /-- Subrings of a ring form a complete lattice. -/ instance : complete_lattice (subring R) := { bot := (⊥), bot_le := λ s x hx, let ⟨n, hn⟩ := mem_bot.1 hx in hn ▸ s.coe_int_mem n, top := (⊤), le_top := λ s x hx, trivial, inf := (⊓), inf_le_left := λ s t x, and.left, inf_le_right := λ s t x, and.right, le_inf := λ s t₁ t₂ h₁ h₂ x hx, ⟨h₁ hx, h₂ hx⟩, .. complete_lattice_of_Inf (subring R) (λ s, is_glb.of_image (λ s t, show (s : set R) ≤ t ↔ s ≤ t, from coe_subset_coe) is_glb_binfi)} /-! # subring closure of a subset -/ /-- The `subring` generated by a set. -/ def closure (s : set R) : subring R := Inf {S | s ⊆ S} lemma mem_closure {x : R} {s : set R} : x ∈ closure s ↔ ∀ S : subring R, s ⊆ S → x ∈ S := mem_Inf /-- The subring generated by a set includes the set. -/ @[simp] lemma subset_closure {s : set R} : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx /-- A subring `t` includes `closure s` if and only if it includes `s`. -/ @[simp] lemma closure_le {s : set R} {t : subring R} : closure s ≤ t ↔ s ⊆ t := ⟨set.subset.trans subset_closure, λ h, Inf_le h⟩ /-- Subring closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ lemma closure_mono ⦃s t : set R⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ set.subset.trans h subset_closure lemma closure_eq_of_le {s : set R} {t : subring R} (h₁ : s ⊆ t) (h₂ : t ≤ closure s) : closure s = t := le_antisymm (closure_le.2 h₁) h₂ /-- An induction principle for closure membership. If `p` holds for `0`, `1`, and all elements of `s`, and is preserved under addition, negation, and multiplication, then `p` holds for all elements of the closure of `s`. -/ @[elab_as_eliminator] lemma closure_induction {s : set R} {p : R → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : p 1) (Hadd : ∀ x y, p x → p y → p (x + y)) (Hneg : ∀ (x : R), p x → p (-x)) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, H1, Hmul, H0, Hadd, Hneg⟩).2 Hs h lemma mem_closure_iff {s : set R} {x} : x ∈ closure s ↔ x ∈ add_subgroup.closure (submonoid.closure s : set R) := ⟨ λ h, closure_induction h (λ x hx, add_subgroup.subset_closure $ submonoid.subset_closure hx ) (add_subgroup.zero_mem _) (add_subgroup.subset_closure ( submonoid.one_mem (submonoid.closure s)) ) (λ x y hx hy, add_subgroup.add_mem _ hx hy ) (λ x hx, add_subgroup.neg_mem _ hx ) ( λ x y hx hy, add_subgroup.closure_induction hy (λ q hq, add_subgroup.closure_induction hx ( λ p hp, add_subgroup.subset_closure ((submonoid.closure s).mul_mem hp hq) ) ( begin rw zero_mul q, apply add_subgroup.zero_mem _, end ) ( λ p₁ p₂ ihp₁ ihp₂, begin rw add_mul p₁ p₂ q, apply add_subgroup.add_mem _ ihp₁ ihp₂, end ) ( λ x hx, begin have f : -x * q = -(x*q) := by simp, rw f, apply add_subgroup.neg_mem _ hx, end ) ) ( begin rw mul_zero x, apply add_subgroup.zero_mem _, end ) ( λ q₁ q₂ ihq₁ ihq₂, begin rw mul_add x q₁ q₂, apply add_subgroup.add_mem _ ihq₁ ihq₂ end ) ( λ z hz, begin have f : x * -z = -(x*z) := by simp, rw f, apply add_subgroup.neg_mem _ hz, end ) ), λ h, add_subgroup.closure_induction h ( λ x hx, submonoid.closure_induction hx ( λ x hx, subset_closure hx ) ( one_mem _ ) ( λ x y hx hy, mul_mem _ hx hy ) ) ( zero_mem _ ) (λ x y hx hy, add_mem _ hx hy) ( λ x hx, neg_mem _ hx ) ⟩ theorem exists_list_of_mem_closure {s : set R} {x : R} (h : x ∈ closure s) : (∃ L : list (list R), (∀ t ∈ L, ∀ y ∈ t, y ∈ s ∨ y = (-1:R)) ∧ (L.map list.prod).sum = x) := add_subgroup.closure_induction (mem_closure_iff.1 h) (λ x hx, let ⟨l, hl, h⟩ :=submonoid.exists_list_of_mem_closure hx in ⟨[l], by simp [h]; clear_aux_decl; tauto!⟩) ⟨[], by simp⟩ (λ x y ⟨l, hl1, hl2⟩ ⟨m, hm1, hm2⟩, ⟨l ++ m, λ t ht, (list.mem_append.1 ht).elim (hl1 t) (hm1 t), by simp [hl2, hm2]⟩) (λ x ⟨L, hL⟩, ⟨L.map (list.cons (-1)), list.forall_mem_map_iff.2 $ λ j hj, list.forall_mem_cons.2 ⟨or.inr rfl, hL.1 j hj⟩, hL.2 ▸ list.rec_on L (by simp) (by simp [list.map_cons, add_comm] {contextual := tt})⟩) variable (R) /-- `closure` forms a Galois insertion with the coercion to set. -/ protected def gi : galois_insertion (@closure R _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {R} /-- Closure of a subring `S` equals `S`. -/ lemma closure_eq (s : subring R) : closure (s : set R) = s := (subring.gi R).l_u_eq s @[simp] lemma closure_empty : closure (∅ : set R) = ⊥ := (subring.gi R).gc.l_bot @[simp] lemma closure_univ : closure (set.univ : set R) = ⊤ := @coe_top R _ ▸ closure_eq ⊤ lemma closure_union (s t : set R) : closure (s ∪ t) = closure s ⊔ closure t := (subring.gi R).gc.l_sup lemma closure_Union {ι} (s : ι → set R) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (subring.gi R).gc.l_supr lemma closure_sUnion (s : set (set R)) : closure (⋃₀ s) = ⨆ t ∈ s, closure t := (subring.gi R).gc.l_Sup lemma map_sup (s t : subring R) (f : R →+* S) : (s ⊔ t).map f = s.map f ⊔ t.map f := (gc_map_comap f).l_sup lemma map_supr {ι : Sort*} (f : R →+* S) (s : ι → subring R) : (supr s).map f = ⨆ i, (s i).map f := (gc_map_comap f).l_supr lemma comap_inf (s t : subring S) (f : R →+* S) : (s ⊓ t).comap f = s.comap f ⊓ t.comap f := (gc_map_comap f).u_inf lemma comap_infi {ι : Sort*} (f : R →+* S) (s : ι → subring S) : (infi s).comap f = ⨅ i, (s i).comap f := (gc_map_comap f).u_infi @[simp] lemma map_bot (f : R →+* S) : (⊥ : subring R).map f = ⊥ := (gc_map_comap f).l_bot @[simp] lemma comap_top (f : R →+* S) : (⊤ : subring S).comap f = ⊤ := (gc_map_comap f).u_top /-- Given `subring`s `s`, `t` of rings `R`, `S` respectively, `s.prod t` is `s × t` as a subring of `R × S`. -/ def prod (s : subring R) (t : subring S) : subring (R × S) := { carrier := (s : set R).prod t, .. s.to_submonoid.prod t.to_submonoid, .. s.to_add_subgroup.prod t.to_add_subgroup} @[norm_cast] lemma coe_prod (s : subring R) (t : subring S) : (s.prod t : set (R × S)) = (s : set R).prod (t : set S) := rfl lemma mem_prod {s : subring R} {t : subring S} {p : R × S} : p ∈ s.prod t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[mono] lemma prod_mono ⦃s₁ s₂ : subring R⦄ (hs : s₁ ≤ s₂) ⦃t₁ t₂ : subring S⦄ (ht : t₁ ≤ t₂) : s₁.prod t₁ ≤ s₂.prod t₂ := set.prod_mono hs ht lemma prod_mono_right (s : subring R) : monotone (λ t : subring S, s.prod t) := prod_mono (le_refl s) lemma prod_mono_left (t : subring S) : monotone (λ s : subring R, s.prod t) := λ s₁ s₂ hs, prod_mono hs (le_refl t) lemma prod_top (s : subring R) : s.prod (⊤ : subring S) = s.comap (ring_hom.fst R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_fst] lemma top_prod (s : subring S) : (⊤ : subring R).prod s = s.comap (ring_hom.snd R S) := ext $ λ x, by simp [mem_prod, monoid_hom.coe_snd] @[simp] lemma top_prod_top : (⊤ : subring R).prod (⊤ : subring S) = ⊤ := (top_prod _).trans $ comap_top _ /-- Product of subrings is isomorphic to their product as rings. -/ def prod_equiv (s : subring R) (t : subring S) : s.prod t ≃+* s × t := { map_mul' := λ x y, rfl, map_add' := λ x y, rfl, .. equiv.set.prod ↑s ↑t } /-- The underlying set of a non-empty directed Sup of subrings is just a union of the subrings. Note that this fails without the directedness assumption (the union of two subrings is typically not a subring) -/ lemma mem_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) {x : R} : x ∈ (⨆ i, S i) ↔ ∃ i, x ∈ S i := begin refine ⟨_, λ ⟨i, hi⟩, (le_def.1 $ le_supr S i) hi⟩, let U : subring R := subring.mk' (⋃ i, (S i : set R)) (⨆ i, (S i).to_submonoid) (⨆ i, (S i).to_add_subgroup) (submonoid.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)) (add_subgroup.coe_supr_of_directed $ hS.mono_comp _ (λ _ _, id)), suffices : (⨆ i, S i) ≤ U, by simpa using @this x, exact supr_le (λ i x hx, set.mem_Union.2 ⟨i, hx⟩), end lemma coe_supr_of_directed {ι} [hι : nonempty ι] {S : ι → subring R} (hS : directed (≤) S) : ((⨆ i, S i : subring R) : set R) = ⋃ i, ↑(S i) := set.ext $ λ x, by simp [mem_supr_of_directed hS] lemma mem_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) {x : R} : x ∈ Sup S ↔ ∃ s ∈ S, x ∈ s := begin haveI : nonempty S := Sne.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed hS.directed_coe, set_coe.exists, subtype.coe_mk] end lemma coe_Sup_of_directed_on {S : set (subring R)} (Sne : S.nonempty) (hS : directed_on (≤) S) : (↑(Sup S) : set R) = ⋃ s ∈ S, ↑s := set.ext $ λ x, by simp [mem_Sup_of_directed_on Sne hS] end subring namespace ring_hom variables [ring T] {s : subring R} open subring /-- Restriction of a ring homomorphism to a subring of the domain. -/ def restrict (f : R →+* S) (s : subring R) : s →+* S := f.comp s.subtype @[simp] lemma restrict_apply (f : R →+* S) (x : s) : f.restrict s x = f x := rfl /-- Restriction of a ring homomorphism to its range interpreted as a subsemiring. This is the bundled version of `set.range_factorization`. -/ def range_restrict (f : R →+* S) : R →+* f.range := f.cod_restrict' f.range $ λ x, ⟨x, subring.mem_top x, rfl⟩ @[simp] lemma coe_range_restrict (f : R →+* S) (x : R) : (f.range_restrict x : S) = f x := rfl lemma range_restrict_surjective (f : R →+* S) : function.surjective f.range_restrict := λ ⟨y, hy⟩, let ⟨x, hx⟩ := mem_range.mp hy in ⟨x, subtype.ext hx⟩ lemma range_top_iff_surjective {f : R →+* S} : f.range = (⊤ : subring S) ↔ function.surjective f := subring.ext'_iff.trans $ iff.trans (by rw [coe_range, coe_top]) set.range_iff_surjective /-- The range of a surjective ring homomorphism is the whole of the codomain. -/ lemma range_top_of_surjective (f : R →+* S) (hf : function.surjective f) : f.range = (⊤ : subring S) := range_top_iff_surjective.2 hf /-- The subring of elements `x : R` such that `f x = g x`, i.e., the equalizer of f and g as a subring of R -/ def eq_locus (f g : R →+* S) : subring R := { carrier := {x | f x = g x}, .. (f : R →* S).eq_mlocus g, .. (f : R →+ S).eq_locus g } /-- If two ring homomorphisms are equal on a set, then they are equal on its subring closure. -/ lemma eq_on_set_closure {f g : R →+* S} {s : set R} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_locus g, from closure_le.2 h lemma eq_of_eq_on_set_top {f g : R →+* S} (h : set.eq_on f g (⊤ : subring R)) : f = g := ext $ λ x, h trivial lemma eq_of_eq_on_set_dense {s : set R} (hs : closure s = ⊤) {f g : R →+* S} (h : s.eq_on f g) : f = g := eq_of_eq_on_set_top $ hs ▸ eq_on_set_closure h lemma closure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx /-- The image under a ring homomorphism of the subring generated by a set equals the subring generated by the image of the set. -/ lemma map_closure (f : R →+* S) (s : set R) : (closure s).map f = closure (f '' s) := le_antisymm (map_le_iff_le_comap.2 $ le_trans (closure_mono $ set.subset_preimage_image _ _) (closure_preimage_le _ _)) (closure_le.2 $ set.image_subset _ subset_closure) end ring_hom namespace subring open ring_hom /-- The ring homomorphism associated to an inclusion of subrings. -/ def inclusion {S T : subring R} (h : S ≤ T) : S →* T := S.subtype.cod_restrict' _ (λ x, h x.2) @[simp] lemma range_subtype (s : subring R) : s.subtype.range = s := ext' $ (coe_srange _).trans subtype.range_coe @[simp] lemma range_fst : (fst R S).srange = ⊤ := (fst R S).srange_top_of_surjective $ prod.fst_surjective @[simp] lemma range_snd : (snd R S).srange = ⊤ := (snd R S).srange_top_of_surjective $ prod.snd_surjective @[simp] lemma prod_bot_sup_bot_prod (s : subring R) (t : subring S) : (s.prod ⊥) ⊔ (prod ⊥ t) = s.prod t := le_antisymm (sup_le (prod_mono_right s bot_le) (prod_mono_left t bot_le)) $ assume p hp, prod.fst_mul_snd p ▸ mul_mem _ ((le_sup_left : s.prod ⊥ ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨hp.1, mem_coe.2 $ one_mem ⊥⟩) ((le_sup_right : prod ⊥ t ≤ s.prod ⊥ ⊔ prod ⊥ t) ⟨mem_coe.2 $ one_mem ⊥, hp.2⟩) end subring namespace ring_equiv variables {s t : subring R} /-- Makes the identity isomorphism from a proof two subrings of a multiplicative monoid are equal. -/ def subring_congr (h : s = t) : s ≃+* t := { map_mul' := λ _ _, rfl, map_add' := λ _ _, rfl, ..equiv.set_congr $ subring.ext'_iff.1 h } /-- Restrict a ring homomorphism with a left inverse to a ring isomorphism to its `ring_hom.range`. -/ def of_left_inverse {g : S → R} {f : R →+* S} (h : function.left_inverse g f) : R ≃+* f.range := { to_fun := λ x, f.range_restrict x, inv_fun := λ x, (g ∘ f.range.subtype) x, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := ring_hom.mem_range.mp x.prop in show f (g x) = x, by rw [←hx', h x'], ..f.range_restrict } @[simp] lemma of_left_inverse_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : R) : ↑(of_left_inverse h x) = f x := rfl @[simp] lemma of_left_inverse_symm_apply {g : S → R} {f : R →+* S} (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl end ring_equiv namespace subring variables {s : set R} local attribute [reducible] closure @[elab_as_eliminator] protected theorem in_closure.rec_on {C : R → Prop} {x : R} (hx : x ∈ closure s) (h1 : C 1) (hneg1 : C (-1)) (hs : ∀ z ∈ s, ∀ n, C n → C (z * n)) (ha : ∀ {x y}, C x → C y → C (x + y)) : C x := begin have h0 : C 0 := add_neg_self (1:R) ▸ ha h1 hneg1, rcases exists_list_of_mem_closure hx with ⟨L, HL, rfl⟩, clear hx, induction L with hd tl ih, { exact h0 }, rw list.forall_mem_cons at HL, suffices : C (list.prod hd), { rw [list.map_cons, list.sum_cons], exact ha this (ih HL.2) }, replace HL := HL.1, clear ih tl, suffices : ∃ L : list R, (∀ x ∈ L, x ∈ s) ∧ (list.prod hd = list.prod L ∨ list.prod hd = -list.prod L), { rcases this with ⟨L, HL', HP | HP⟩, { rw HP, clear HP HL hd, induction L with hd tl ih, { exact h1 }, rw list.forall_mem_cons at HL', rw list.prod_cons, exact hs _ HL'.1 _ (ih HL'.2) }, rw HP, clear HP HL hd, induction L with hd tl ih, { exact hneg1 }, rw [list.prod_cons, neg_mul_eq_mul_neg], rw list.forall_mem_cons at HL', exact hs _ HL'.1 _ (ih HL'.2) }, induction hd with hd tl ih, { exact ⟨[], list.forall_mem_nil _, or.inl rfl⟩ }, rw list.forall_mem_cons at HL, rcases ih HL.2 with ⟨L, HL', HP | HP⟩; cases HL.1 with hhd hhd, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inl $ by rw [list.prod_cons, list.prod_cons, HP]⟩ }, { exact ⟨L, HL', or.inr $ by rw [list.prod_cons, hhd, neg_one_mul, HP]⟩ }, { exact ⟨hd :: L, list.forall_mem_cons.2 ⟨hhd, HL'⟩, or.inr $ by rw [list.prod_cons, list.prod_cons, HP, neg_mul_eq_mul_neg]⟩ }, { exact ⟨L, HL', or.inl $ by rw [list.prod_cons, hhd, HP, neg_one_mul, neg_neg]⟩ } end lemma closure_preimage_le (f : R →+* S) (s : set S) : closure (f ⁻¹' s) ≤ (closure s).comap f := closure_le.2 $ λ x hx, mem_coe.2 $ mem_comap.2 $ subset_closure hx end subring lemma add_subgroup.int_mul_mem {G : add_subgroup R} (k : ℤ) {g : R} (h : g ∈ G) : (k : R) * g ∈ G := by { convert add_subgroup.gsmul_mem G h k, simp }
544b2cd2bdf1555301962ed892ddc035d26365de
205f0fc16279a69ea36e9fd158e3a97b06834ce2
/src/14.Inductive_Definitions/Data_Types/student-question-metavariables.lean
f6af29e4b5adf4606119d9381cd0e84ee43e4456
[]
no_license
kevinsullivan/cs-dm-lean
b21d3ca1a9b2a0751ba13fcb4e7b258010a5d124
a06a94e98be77170ca1df486c8189338b16cf6c6
refs/heads/master
1,585,948,743,595
1,544,339,346,000
1,544,339,346,000
155,570,767
1
3
null
1,541,540,372,000
1,540,995,993,000
Lean
UTF-8
Lean
false
false
1,320
lean
-- just an old factorial function def fac : ℕ → ℕ | 0 := 1 | (nat.succ n') := (nat.succ n') * (fac n') /- Let's look at proofs of (fac k = 0) in two different styles. In one style we'll use metavariables and axioms. In the other, it's ordinary variables and constructive proofs. -/ -- with metavariables and axioms variable k : ℕ #check k #reduce k -- can't reduce a metavariable axiom k0 : k = 0 -- omg, it's a real function #check k0 -- wait, that's kind of weird #check k0 k -- we can create proofs of k = 0 variable l : ℕ -- for any k, let's try it on l #check k0 l -- here we have a proof of l = 0 #reduce k0 k -- but again can't reduce metavar -- that said, we can use the axiom in proofs example : fac k = 1 := begin have keq0 := k0 k, rw keq0, trivial, end -- QED /- Now with ordinary variables: it's just rfl. In a way, rfl causes (fac k) to compute, to reduce, after which it's just reflexive eq. -/ /- Here's a zero-valued (non-meta) variable. It thus has a definite value, which, in this case is zero. There's a constructive proof, namely 0, of the type of k', i.e., ℕ. -/ def k' := 0 /- Now the proof is literally trivial. In this case, the trivial tactic tries applying rfl and that is all it takes. -/ example : fac k' = 1 := begin trivial, end
53fdc4a7bc109bcf26b1e2bfe3f2fced0740a1c5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/order/bounded_lattice.lean
ce1307b870e467766bc4ecd8daccd27a3c510a93
[]
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
43,993
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl Defines bounded lattice type class hierarchy. Includes the Prop and fun instances. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.order.lattice import Mathlib.data.option.basic import Mathlib.tactic.pi_instances import Mathlib.logic.nontrivial import Mathlib.PostPort universes u l v u_1 u_2 namespace Mathlib /-- Typeclass for the `⊤` (`\top`) notation -/ /-- Typeclass for the `⊥` (`\bot`) notation -/ class has_top (α : Type u) where top : α class has_bot (α : Type u) where bot : α notation:1024 "⊤" => Mathlib.has_top.top notation:1024 "⊥" => Mathlib.has_bot.bot /-- An `order_top` is a partial order with a maximal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_top (α : Type u) extends has_top α, partial_order α where le_top : ∀ (a : α), a ≤ ⊤ @[simp] theorem le_top {α : Type u} [order_top α] {a : α} : a ≤ ⊤ := order_top.le_top a theorem top_unique {α : Type u} [order_top α] {a : α} (h : ⊤ ≤ a) : a = ⊤ := le_antisymm le_top h -- TODO: delete in favor of the next? theorem eq_top_iff {α : Type u} [order_top α] {a : α} : a = ⊤ ↔ ⊤ ≤ a := { mp := fun (eq : a = ⊤) => Eq.symm eq ▸ le_refl ⊤, mpr := top_unique } @[simp] theorem top_le_iff {α : Type u} [order_top α] {a : α} : ⊤ ≤ a ↔ a = ⊤ := { mp := top_unique, mpr := fun (h : a = ⊤) => Eq.symm h ▸ le_refl ⊤ } @[simp] theorem not_top_lt {α : Type u} [order_top α] {a : α} : ¬⊤ < a := fun (h : ⊤ < a) => lt_irrefl a (lt_of_le_of_lt le_top h) theorem eq_top_mono {α : Type u} [order_top α] {a : α} {b : α} (h : a ≤ b) (h₂ : a = ⊤) : b = ⊤ := iff.mp top_le_iff (h₂ ▸ h) theorem lt_top_iff_ne_top {α : Type u} [order_top α] {a : α} : a < ⊤ ↔ a ≠ ⊤ := sorry theorem ne_top_of_lt {α : Type u} [order_top α] {a : α} {b : α} (h : a < b) : a ≠ ⊤ := iff.mp lt_top_iff_ne_top (lt_of_lt_of_le h le_top) theorem ne_top_of_le_ne_top {α : Type u} [order_top α] {a : α} {b : α} (hb : b ≠ ⊤) (hab : a ≤ b) : a ≠ ⊤ := fun (ha : a = ⊤) => hb (top_unique (ha ▸ hab)) theorem strict_mono.top_preimage_top' {α : Type u} {β : Type v} [linear_order α] [order_top β] {f : α → β} (H : strict_mono f) {a : α} (h_top : f a = ⊤) (x : α) : x ≤ a := strict_mono.top_preimage_top H (fun (p : β) => eq.mpr (id (Eq._oldrec (Eq.refl (p ≤ f a)) h_top)) le_top) x theorem order_top.ext_top {α : Type u_1} {A : order_top α} {B : order_top α} (H : ∀ (x y : α), x ≤ y ↔ x ≤ y) : ⊤ = ⊤ := top_unique (eq.mpr (id (Eq._oldrec (Eq.refl (⊤ ≤ ⊤)) (Eq.symm (propext (H ⊤ ⊤))))) le_top) theorem order_top.ext {α : Type u_1} {A : order_top α} {B : order_top α} (H : ∀ (x y : α), x ≤ y ↔ x ≤ y) : A = B := sorry /-- An `order_bot` is a partial order with a minimal element. (We could state this on preorders, but then it wouldn't be unique so distinguishing one would seem odd.) -/ class order_bot (α : Type u) extends has_bot α, partial_order α where bot_le : ∀ (a : α), ⊥ ≤ a @[simp] theorem bot_le {α : Type u} [order_bot α] {a : α} : ⊥ ≤ a := order_bot.bot_le a theorem bot_unique {α : Type u} [order_bot α] {a : α} (h : a ≤ ⊥) : a = ⊥ := le_antisymm h bot_le -- TODO: delete? theorem eq_bot_iff {α : Type u} [order_bot α] {a : α} : a = ⊥ ↔ a ≤ ⊥ := { mp := fun (eq : a = ⊥) => Eq.symm eq ▸ le_refl ⊥, mpr := bot_unique } @[simp] theorem le_bot_iff {α : Type u} [order_bot α] {a : α} : a ≤ ⊥ ↔ a = ⊥ := { mp := bot_unique, mpr := fun (h : a = ⊥) => Eq.symm h ▸ le_refl ⊥ } @[simp] theorem not_lt_bot {α : Type u} [order_bot α] {a : α} : ¬a < ⊥ := fun (h : a < ⊥) => lt_irrefl a (lt_of_lt_of_le h bot_le) theorem ne_bot_of_le_ne_bot {α : Type u} [order_bot α] {a : α} {b : α} (hb : b ≠ ⊥) (hab : b ≤ a) : a ≠ ⊥ := fun (ha : a = ⊥) => hb (bot_unique (ha ▸ hab)) theorem eq_bot_mono {α : Type u} [order_bot α] {a : α} {b : α} (h : a ≤ b) (h₂ : b = ⊥) : a = ⊥ := iff.mp le_bot_iff (h₂ ▸ h) theorem bot_lt_iff_ne_bot {α : Type u} [order_bot α] {a : α} : ⊥ < a ↔ a ≠ ⊥ := sorry theorem ne_bot_of_gt {α : Type u} [order_bot α] {a : α} {b : α} (h : a < b) : b ≠ ⊥ := iff.mp bot_lt_iff_ne_bot (lt_of_le_of_lt bot_le h) theorem strict_mono.bot_preimage_bot' {α : Type u} {β : Type v} [linear_order α] [order_bot β] {f : α → β} (H : strict_mono f) {a : α} (h_bot : f a = ⊥) (x : α) : a ≤ x := strict_mono.bot_preimage_bot H (fun (p : β) => eq.mpr (id (Eq._oldrec (Eq.refl (f a ≤ p)) h_bot)) bot_le) x theorem order_bot.ext_bot {α : Type u_1} {A : order_bot α} {B : order_bot α} (H : ∀ (x y : α), x ≤ y ↔ x ≤ y) : ⊥ = ⊥ := bot_unique (eq.mpr (id (Eq._oldrec (Eq.refl (⊥ ≤ ⊥)) (Eq.symm (propext (H ⊥ ⊥))))) bot_le) theorem order_bot.ext {α : Type u_1} {A : order_bot α} {B : order_bot α} (H : ∀ (x y : α), x ≤ y ↔ x ≤ y) : A = B := sorry /-- A `semilattice_sup_top` is a semilattice with top and join. -/ class semilattice_sup_top (α : Type u) extends semilattice_sup α, order_top α where @[simp] theorem top_sup_eq {α : Type u} [semilattice_sup_top α] {a : α} : ⊤ ⊔ a = ⊤ := sup_of_le_left le_top @[simp] theorem sup_top_eq {α : Type u} [semilattice_sup_top α] {a : α} : a ⊔ ⊤ = ⊤ := sup_of_le_right le_top /-- A `semilattice_sup_bot` is a semilattice with bottom and join. -/ class semilattice_sup_bot (α : Type u) extends order_bot α, semilattice_sup α where @[simp] theorem bot_sup_eq {α : Type u} [semilattice_sup_bot α] {a : α} : ⊥ ⊔ a = a := sup_of_le_right bot_le @[simp] theorem sup_bot_eq {α : Type u} [semilattice_sup_bot α] {a : α} : a ⊔ ⊥ = a := sup_of_le_left bot_le @[simp] theorem sup_eq_bot_iff {α : Type u} [semilattice_sup_bot α] {a : α} {b : α} : a ⊔ b = ⊥ ↔ a = ⊥ ∧ b = ⊥ := sorry protected instance nat.semilattice_sup_bot : semilattice_sup_bot ℕ := semilattice_sup_bot.mk 0 distrib_lattice.le distrib_lattice.lt distrib_lattice.le_refl distrib_lattice.le_trans distrib_lattice.le_antisymm nat.zero_le distrib_lattice.sup distrib_lattice.le_sup_left distrib_lattice.le_sup_right distrib_lattice.sup_le /-- A `semilattice_inf_top` is a semilattice with top and meet. -/ class semilattice_inf_top (α : Type u) extends semilattice_inf α, order_top α where @[simp] theorem top_inf_eq {α : Type u} [semilattice_inf_top α] {a : α} : ⊤ ⊓ a = a := inf_of_le_right le_top @[simp] theorem inf_top_eq {α : Type u} [semilattice_inf_top α] {a : α} : a ⊓ ⊤ = a := inf_of_le_left le_top @[simp] theorem inf_eq_top_iff {α : Type u} [semilattice_inf_top α] {a : α} {b : α} : a ⊓ b = ⊤ ↔ a = ⊤ ∧ b = ⊤ := sorry /-- A `semilattice_inf_bot` is a semilattice with bottom and meet. -/ class semilattice_inf_bot (α : Type u) extends order_bot α, semilattice_inf α where @[simp] theorem bot_inf_eq {α : Type u} [semilattice_inf_bot α] {a : α} : ⊥ ⊓ a = ⊥ := inf_of_le_left bot_le @[simp] theorem inf_bot_eq {α : Type u} [semilattice_inf_bot α] {a : α} : a ⊓ ⊥ = ⊥ := inf_of_le_right bot_le /- Bounded lattices -/ /-- A bounded lattice is a lattice with a top and bottom element, denoted `⊤` and `⊥` respectively. This allows for the interpretation of all finite suprema and infima, taking `inf ∅ = ⊤` and `sup ∅ = ⊥`. -/ class bounded_lattice (α : Type u) extends order_bot α, order_top α, lattice α where protected instance semilattice_inf_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_top α := semilattice_inf_top.mk bounded_lattice.top bounded_lattice.le bounded_lattice.lt bounded_lattice.le_refl bounded_lattice.le_trans bounded_lattice.le_antisymm sorry bounded_lattice.inf bounded_lattice.inf_le_left bounded_lattice.inf_le_right bounded_lattice.le_inf protected instance semilattice_inf_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_inf_bot α := semilattice_inf_bot.mk bounded_lattice.bot bounded_lattice.le bounded_lattice.lt bounded_lattice.le_refl bounded_lattice.le_trans bounded_lattice.le_antisymm sorry bounded_lattice.inf bounded_lattice.inf_le_left bounded_lattice.inf_le_right bounded_lattice.le_inf protected instance semilattice_sup_top_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_top α := semilattice_sup_top.mk bounded_lattice.top bounded_lattice.le bounded_lattice.lt bounded_lattice.le_refl bounded_lattice.le_trans bounded_lattice.le_antisymm sorry bounded_lattice.sup bounded_lattice.le_sup_left bounded_lattice.le_sup_right bounded_lattice.sup_le protected instance semilattice_sup_bot_of_bounded_lattice (α : Type u) [bl : bounded_lattice α] : semilattice_sup_bot α := semilattice_sup_bot.mk bounded_lattice.bot bounded_lattice.le bounded_lattice.lt bounded_lattice.le_refl bounded_lattice.le_trans bounded_lattice.le_antisymm sorry bounded_lattice.sup bounded_lattice.le_sup_left bounded_lattice.le_sup_right bounded_lattice.sup_le theorem bounded_lattice.ext {α : Type u_1} {A : bounded_lattice α} {B : bounded_lattice α} (H : ∀ (x y : α), x ≤ y ↔ x ≤ y) : A = B := sorry /-- A bounded distributive lattice is exactly what it sounds like. -/ class bounded_distrib_lattice (α : Type u_1) extends distrib_lattice α, bounded_lattice α where theorem inf_eq_bot_iff_le_compl {α : Type u} [bounded_distrib_lattice α] {a : α} {b : α} {c : α} (h₁ : b ⊔ c = ⊤) (h₂ : b ⊓ c = ⊥) : a ⊓ b = ⊥ ↔ a ≤ c := sorry /- Prop instance -/ protected instance bounded_distrib_lattice_Prop : bounded_distrib_lattice Prop := bounded_distrib_lattice.mk Or (fun (a b : Prop) => a → b) (distrib_lattice.lt._default fun (a b : Prop) => a → b) sorry sorry sorry Or.inl Or.inr sorry And and.left and.right sorry sorry True sorry False false.elim protected instance Prop.linear_order : linear_order Prop := linear_order.mk partial_order.le partial_order.lt sorry sorry sorry sorry (classical.dec_rel LessEq) Mathlib.decidable_eq_of_decidable_le Mathlib.decidable_lt_of_decidable_le @[simp] theorem le_iff_imp {p : Prop} {q : Prop} : p ≤ q ↔ p → q := iff.rfl theorem monotone_and {α : Type u} [preorder α] {p : α → Prop} {q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone fun (x : α) => p x ∧ q x := fun (a b : α) (h : a ≤ b) => and.imp (m_p h) (m_q h) -- Note: by finish [monotone] doesn't work theorem monotone_or {α : Type u} [preorder α] {p : α → Prop} {q : α → Prop} (m_p : monotone p) (m_q : monotone q) : monotone fun (x : α) => p x ∨ q x := fun (a b : α) (h : a ≤ b) => or.imp (m_p h) (m_q h) protected instance pi.order_bot {α : Type u_1} {β : α → Type u_2} [(a : α) → order_bot (β a)] : order_bot ((a : α) → β a) := order_bot.mk (fun (_x : α) => ⊥) partial_order.le partial_order.lt sorry sorry sorry sorry /- Function lattices -/ protected instance pi.has_sup {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → has_sup (α i)] : has_sup ((i : ι) → α i) := has_sup.mk fun (f g : (i : ι) → α i) (i : ι) => f i ⊔ g i @[simp] theorem sup_apply {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → has_sup (α i)] (f : (i : ι) → α i) (g : (i : ι) → α i) (i : ι) : has_sup.sup f g i = f i ⊔ g i := rfl protected instance pi.has_inf {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → has_inf (α i)] : has_inf ((i : ι) → α i) := has_inf.mk fun (f g : (i : ι) → α i) (i : ι) => f i ⊓ g i @[simp] theorem inf_apply {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → has_inf (α i)] (f : (i : ι) → α i) (g : (i : ι) → α i) (i : ι) : has_inf.inf f g i = f i ⊓ g i := rfl protected instance pi.has_bot {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → has_bot (α i)] : has_bot ((i : ι) → α i) := has_bot.mk fun (i : ι) => ⊥ @[simp] theorem bot_apply {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → has_bot (α i)] (i : ι) : ⊥ = ⊥ := rfl protected instance pi.has_top {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → has_top (α i)] : has_top ((i : ι) → α i) := has_top.mk fun (i : ι) => ⊤ @[simp] theorem top_apply {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → has_top (α i)] (i : ι) : ⊤ = ⊤ := rfl protected instance pi.semilattice_sup {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → semilattice_sup (α i)] : semilattice_sup ((i : ι) → α i) := semilattice_sup.mk has_sup.sup partial_order.le partial_order.lt sorry sorry sorry sorry sorry sorry protected instance pi.semilattice_inf {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → semilattice_inf (α i)] : semilattice_inf ((i : ι) → α i) := semilattice_inf.mk has_inf.inf partial_order.le partial_order.lt sorry sorry sorry sorry sorry sorry protected instance pi.semilattice_inf_bot {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → semilattice_inf_bot (α i)] : semilattice_inf_bot ((i : ι) → α i) := semilattice_inf_bot.mk ⊥ partial_order.le partial_order.lt sorry sorry sorry sorry has_inf.inf sorry sorry sorry protected instance pi.semilattice_inf_top {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → semilattice_inf_top (α i)] : semilattice_inf_top ((i : ι) → α i) := semilattice_inf_top.mk ⊤ partial_order.le partial_order.lt sorry sorry sorry sorry has_inf.inf sorry sorry sorry protected instance pi.semilattice_sup_bot {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → semilattice_sup_bot (α i)] : semilattice_sup_bot ((i : ι) → α i) := semilattice_sup_bot.mk ⊥ partial_order.le partial_order.lt sorry sorry sorry sorry has_sup.sup sorry sorry sorry protected instance pi.semilattice_sup_top {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → semilattice_sup_top (α i)] : semilattice_sup_top ((i : ι) → α i) := semilattice_sup_top.mk ⊤ partial_order.le partial_order.lt sorry sorry sorry sorry has_sup.sup sorry sorry sorry protected instance pi.lattice {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → lattice (α i)] : lattice ((i : ι) → α i) := lattice.mk semilattice_sup.sup semilattice_sup.le semilattice_sup.lt sorry sorry sorry sorry sorry sorry semilattice_inf.inf sorry sorry sorry protected instance pi.bounded_lattice {ι : Type u_1} {α : ι → Type u_2} [(i : ι) → bounded_lattice (α i)] : bounded_lattice ((i : ι) → α i) := bounded_lattice.mk semilattice_sup_top.sup semilattice_sup_top.le semilattice_sup_top.lt sorry sorry sorry sorry sorry sorry semilattice_inf_bot.inf sorry sorry sorry semilattice_sup_top.top sorry semilattice_inf_bot.bot sorry theorem eq_bot_of_bot_eq_top {α : Type u_1} [bounded_lattice α] (hα : ⊥ = ⊤) (x : α) : x = ⊥ := eq_bot_mono le_top (Eq.symm hα) theorem eq_top_of_bot_eq_top {α : Type u_1} [bounded_lattice α] (hα : ⊥ = ⊤) (x : α) : x = ⊤ := eq_top_mono bot_le hα theorem subsingleton_of_top_le_bot {α : Type u_1} [bounded_lattice α] (h : ⊤ ≤ ⊥) : subsingleton α := subsingleton.intro fun (a b : α) => le_antisymm (le_trans le_top (le_trans h bot_le)) (le_trans le_top (le_trans h bot_le)) theorem subsingleton_of_bot_eq_top {α : Type u_1} [bounded_lattice α] (hα : ⊥ = ⊤) : subsingleton α := subsingleton_of_top_le_bot (ge_of_eq hα) theorem subsingleton_iff_bot_eq_top {α : Type u_1} [bounded_lattice α] : ⊥ = ⊤ ↔ subsingleton α := { mp := subsingleton_of_bot_eq_top, mpr := fun (h : subsingleton α) => subsingleton.elim ⊥ ⊤ } /-- Attach `⊥` to a type. -/ def with_bot (α : Type u_1) := Option α namespace with_bot protected instance has_coe_t {α : Type u} : has_coe_t α (with_bot α) := has_coe_t.mk some protected instance has_bot {α : Type u} : has_bot (with_bot α) := has_bot.mk none protected instance inhabited {α : Type u} : Inhabited (with_bot α) := { default := ⊥ } theorem none_eq_bot {α : Type u} : none = ⊥ := rfl theorem some_eq_coe {α : Type u} (a : α) : some a = ↑a := rfl /-- Recursor for `with_bot` using the preferred forms `⊥` and `↑a`. -/ def rec_bot_coe {α : Type u} {C : with_bot α → Sort u_1} (h₁ : C ⊥) (h₂ : (a : α) → C ↑a) (n : with_bot α) : C n := Option.rec h₁ h₂ theorem coe_eq_coe {α : Type u} {a : α} {b : α} : ↑a = ↑b ↔ a = b := eq.mpr (id (Eq._oldrec (Eq.refl (↑a = ↑b ↔ a = b)) (Eq.symm (option.some.inj_eq a b)))) (iff.refl (↑a = ↑b)) protected instance has_lt {α : Type u} [HasLess α] : HasLess (with_bot α) := { Less := fun (o₁ o₂ : Option α) => ∃ (b : α), ∃ (H : b ∈ o₂), ∀ (a : α), a ∈ o₁ → a < b } @[simp] theorem some_lt_some {α : Type u} [HasLess α] {a : α} {b : α} : some a < some b ↔ a < b := sorry theorem bot_lt_some {α : Type u} [HasLess α] (a : α) : ⊥ < some a := Exists.intro a (Exists.intro rfl fun (b : α) (hb : b ∈ ⊥) => false.elim (option.not_mem_none b hb)) theorem bot_lt_coe {α : Type u} [HasLess α] (a : α) : ⊥ < ↑a := bot_lt_some a protected instance preorder {α : Type u} [preorder α] : preorder (with_bot α) := preorder.mk (fun (o₁ o₂ : Option α) => ∀ (a : α) (H : a ∈ o₁), ∃ (b : α), ∃ (H : b ∈ o₂), a ≤ b) Less sorry sorry protected instance partial_order {α : Type u} [partial_order α] : partial_order (with_bot α) := partial_order.mk preorder.le preorder.lt sorry sorry sorry protected instance order_bot {α : Type u} [partial_order α] : order_bot (with_bot α) := order_bot.mk ⊥ partial_order.le partial_order.lt sorry sorry sorry sorry @[simp] theorem coe_le_coe {α : Type u} [preorder α] {a : α} {b : α} : ↑a ≤ ↑b ↔ a ≤ b := sorry @[simp] theorem some_le_some {α : Type u} [preorder α] {a : α} {b : α} : some a ≤ some b ↔ a ≤ b := coe_le_coe theorem coe_le {α : Type u} [partial_order α] {a : α} {b : α} {o : Option α} : b ∈ o → (↑a ≤ o ↔ a ≤ b) := sorry theorem coe_lt_coe {α : Type u} [partial_order α] {a : α} {b : α} : ↑a < ↑b ↔ a < b := some_lt_some theorem le_coe_get_or_else {α : Type u} [preorder α] (a : with_bot α) (b : α) : a ≤ ↑(option.get_or_else a b) := sorry @[simp] theorem get_or_else_bot {α : Type u} (a : α) : option.get_or_else ⊥ a = a := rfl theorem get_or_else_bot_le_iff {α : Type u} [order_bot α] {a : with_bot α} {b : α} : option.get_or_else a ⊥ ≤ b ↔ a ≤ ↑b := sorry protected instance decidable_le {α : Type u} [preorder α] [DecidableRel LessEq] : DecidableRel LessEq := sorry protected instance decidable_lt {α : Type u} [HasLess α] [DecidableRel Less] : DecidableRel Less := sorry protected instance linear_order {α : Type u} [linear_order α] : linear_order (with_bot α) := linear_order.mk partial_order.le partial_order.lt sorry sorry sorry sorry with_bot.decidable_le Mathlib.decidable_eq_of_decidable_le with_bot.decidable_lt protected instance semilattice_sup {α : Type u} [semilattice_sup α] : semilattice_sup_bot (with_bot α) := semilattice_sup_bot.mk order_bot.bot order_bot.le order_bot.lt sorry sorry sorry sorry (option.lift_or_get has_sup.sup) sorry sorry sorry protected instance semilattice_inf {α : Type u} [semilattice_inf α] : semilattice_inf_bot (with_bot α) := semilattice_inf_bot.mk order_bot.bot order_bot.le order_bot.lt sorry sorry sorry sorry (fun (o₁ o₂ : with_bot α) => option.bind o₁ fun (a : α) => option.map (fun (b : α) => a ⊓ b) o₂) sorry sorry sorry protected instance lattice {α : Type u} [lattice α] : lattice (with_bot α) := lattice.mk semilattice_sup_bot.sup semilattice_sup_bot.le semilattice_sup_bot.lt sorry sorry sorry sorry sorry sorry semilattice_inf_bot.inf sorry sorry sorry theorem lattice_eq_DLO {α : Type u} [linear_order α] : Mathlib.lattice_of_linear_order = with_bot.lattice := lattice.ext fun (x y : with_bot α) => iff.rfl theorem sup_eq_max {α : Type u} [linear_order α] (x : with_bot α) (y : with_bot α) : x ⊔ y = max x y := eq.mpr (id (Eq._oldrec (Eq.refl (x ⊔ y = max x y)) (Eq.symm sup_eq_max))) (eq.mpr (id (Eq._oldrec (Eq.refl (x ⊔ y = x ⊔ y)) lattice_eq_DLO)) (Eq.refl (x ⊔ y))) theorem inf_eq_min {α : Type u} [linear_order α] (x : with_bot α) (y : with_bot α) : x ⊓ y = min x y := eq.mpr (id (Eq._oldrec (Eq.refl (x ⊓ y = min x y)) (Eq.symm inf_eq_min))) (eq.mpr (id (Eq._oldrec (Eq.refl (x ⊓ y = x ⊓ y)) lattice_eq_DLO)) (Eq.refl (x ⊓ y))) protected instance order_top {α : Type u} [order_top α] : order_top (with_bot α) := order_top.mk (some ⊤) partial_order.le partial_order.lt sorry sorry sorry sorry protected instance bounded_lattice {α : Type u} [bounded_lattice α] : bounded_lattice (with_bot α) := bounded_lattice.mk lattice.sup lattice.le lattice.lt sorry sorry sorry sorry sorry sorry lattice.inf sorry sorry sorry order_top.top sorry order_bot.bot sorry theorem well_founded_lt {α : Type u} [partial_order α] (h : well_founded Less) : well_founded Less := sorry protected instance densely_ordered {α : Type u} [partial_order α] [densely_ordered α] [no_bot_order α] : densely_ordered (with_bot α) := densely_ordered.mk fun (a b : with_bot α) => sorry end with_bot --TODO(Mario): Construct using order dual on with_bot /-- Attach `⊤` to a type. -/ def with_top (α : Type u_1) := Option α namespace with_top protected instance has_coe_t {α : Type u} : has_coe_t α (with_top α) := has_coe_t.mk some protected instance has_top {α : Type u} : has_top (with_top α) := has_top.mk none protected instance inhabited {α : Type u} : Inhabited (with_top α) := { default := ⊤ } theorem none_eq_top {α : Type u} : none = ⊤ := rfl theorem some_eq_coe {α : Type u} (a : α) : some a = ↑a := rfl /-- Recursor for `with_top` using the preferred forms `⊤` and `↑a`. -/ def rec_top_coe {α : Type u} {C : with_top α → Sort u_1} (h₁ : C ⊤) (h₂ : (a : α) → C ↑a) (n : with_top α) : C n := Option.rec h₁ h₂ theorem coe_eq_coe {α : Type u} {a : α} {b : α} : ↑a = ↑b ↔ a = b := eq.mpr (id (Eq._oldrec (Eq.refl (↑a = ↑b ↔ a = b)) (Eq.symm (option.some.inj_eq a b)))) (iff.refl (↑a = ↑b)) @[simp] theorem top_ne_coe {α : Type u} {a : α} : ⊤ ≠ ↑a := fun (ᾰ : ⊤ = ↑a) => eq.dcases_on ᾰ (fun (a_1 : some a = none) => option.no_confusion a_1) (Eq.refl ↑a) (HEq.refl ᾰ) @[simp] theorem coe_ne_top {α : Type u} {a : α} : ↑a ≠ ⊤ := fun (ᾰ : ↑a = ⊤) => eq.dcases_on ᾰ (fun (a_1 : none = some a) => option.no_confusion a_1) (Eq.refl ⊤) (HEq.refl ᾰ) protected instance has_lt {α : Type u} [HasLess α] : HasLess (with_top α) := { Less := fun (o₁ o₂ : Option α) => ∃ (b : α), ∃ (H : b ∈ o₁), ∀ (a : α), a ∈ o₂ → b < a } protected instance has_le {α : Type u} [HasLessEq α] : HasLessEq (with_top α) := { LessEq := fun (o₁ o₂ : Option α) => ∀ (a : α) (H : a ∈ o₂), ∃ (b : α), ∃ (H : b ∈ o₁), b ≤ a } @[simp] theorem some_lt_some {α : Type u} [HasLess α] {a : α} {b : α} : some a < some b ↔ a < b := sorry @[simp] theorem some_le_some {α : Type u} [HasLessEq α] {a : α} {b : α} : some a ≤ some b ↔ a ≤ b := sorry @[simp] theorem le_none {α : Type u} [HasLessEq α] {a : with_top α} : a ≤ none := sorry @[simp] theorem some_lt_none {α : Type u} [HasLess α] {a : α} : some a < none := sorry protected instance can_lift {α : Type u} : can_lift (with_top α) α := can_lift.mk coe (fun (r : with_top α) => r ≠ ⊤) sorry protected instance preorder {α : Type u} [preorder α] : preorder (with_top α) := preorder.mk (fun (o₁ o₂ : Option α) => ∀ (a : α) (H : a ∈ o₂), ∃ (b : α), ∃ (H : b ∈ o₁), b ≤ a) Less sorry sorry protected instance partial_order {α : Type u} [partial_order α] : partial_order (with_top α) := partial_order.mk preorder.le preorder.lt sorry sorry sorry protected instance order_top {α : Type u} [partial_order α] : order_top (with_top α) := order_top.mk ⊤ partial_order.le partial_order.lt sorry sorry sorry sorry @[simp] theorem coe_le_coe {α : Type u} [partial_order α] {a : α} {b : α} : ↑a ≤ ↑b ↔ a ≤ b := sorry theorem le_coe {α : Type u} [partial_order α] {a : α} {b : α} {o : Option α} : a ∈ o → (o ≤ ↑b ↔ a ≤ b) := sorry theorem le_coe_iff {α : Type u} [partial_order α] {b : α} {x : with_top α} : x ≤ ↑b ↔ ∃ (a : α), x = ↑a ∧ a ≤ b := sorry theorem coe_le_iff {α : Type u} [partial_order α] {a : α} {x : with_top α} : ↑a ≤ x ↔ ∀ (b : α), x = ↑b → a ≤ b := sorry theorem lt_iff_exists_coe {α : Type u} [partial_order α] {a : with_top α} {b : with_top α} : a < b ↔ ∃ (p : α), a = ↑p ∧ ↑p < b := sorry theorem coe_lt_coe {α : Type u} [partial_order α] {a : α} {b : α} : ↑a < ↑b ↔ a < b := some_lt_some theorem coe_lt_top {α : Type u} [partial_order α] (a : α) : ↑a < ⊤ := some_lt_none theorem coe_lt_iff {α : Type u} [partial_order α] {a : α} {x : with_top α} : ↑a < x ↔ ∀ (b : α), x = ↑b → a < b := sorry theorem not_top_le_coe {α : Type u} [partial_order α] (a : α) : ¬⊤ ≤ ↑a := fun (h : ⊤ ≤ ↑a) => false.elim (lt_irrefl ⊤ (lt_of_le_of_lt h (coe_lt_top a))) protected instance decidable_le {α : Type u} [preorder α] [DecidableRel LessEq] : DecidableRel LessEq := fun (x y : with_top α) => with_bot.decidable_le y x protected instance decidable_lt {α : Type u} [HasLess α] [DecidableRel Less] : DecidableRel Less := fun (x y : with_top α) => with_bot.decidable_lt y x protected instance linear_order {α : Type u} [linear_order α] : linear_order (with_top α) := linear_order.mk partial_order.le partial_order.lt sorry sorry sorry sorry with_top.decidable_le Mathlib.decidable_eq_of_decidable_le with_top.decidable_lt protected instance semilattice_inf {α : Type u} [semilattice_inf α] : semilattice_inf_top (with_top α) := semilattice_inf_top.mk order_top.top order_top.le order_top.lt sorry sorry sorry sorry (option.lift_or_get has_inf.inf) sorry sorry sorry theorem coe_inf {α : Type u} [semilattice_inf α] (a : α) (b : α) : ↑(a ⊓ b) = ↑a ⊓ ↑b := rfl protected instance semilattice_sup {α : Type u} [semilattice_sup α] : semilattice_sup_top (with_top α) := semilattice_sup_top.mk order_top.top order_top.le order_top.lt sorry sorry sorry sorry (fun (o₁ o₂ : with_top α) => option.bind o₁ fun (a : α) => option.map (fun (b : α) => a ⊔ b) o₂) sorry sorry sorry theorem coe_sup {α : Type u} [semilattice_sup α] (a : α) (b : α) : ↑(a ⊔ b) = ↑a ⊔ ↑b := rfl protected instance lattice {α : Type u} [lattice α] : lattice (with_top α) := lattice.mk semilattice_sup_top.sup semilattice_sup_top.le semilattice_sup_top.lt sorry sorry sorry sorry sorry sorry semilattice_inf_top.inf sorry sorry sorry theorem lattice_eq_DLO {α : Type u} [linear_order α] : Mathlib.lattice_of_linear_order = with_top.lattice := lattice.ext fun (x y : with_top α) => iff.rfl theorem sup_eq_max {α : Type u} [linear_order α] (x : with_top α) (y : with_top α) : x ⊔ y = max x y := eq.mpr (id (Eq._oldrec (Eq.refl (x ⊔ y = max x y)) (Eq.symm sup_eq_max))) (eq.mpr (id (Eq._oldrec (Eq.refl (x ⊔ y = x ⊔ y)) lattice_eq_DLO)) (Eq.refl (x ⊔ y))) theorem inf_eq_min {α : Type u} [linear_order α] (x : with_top α) (y : with_top α) : x ⊓ y = min x y := eq.mpr (id (Eq._oldrec (Eq.refl (x ⊓ y = min x y)) (Eq.symm inf_eq_min))) (eq.mpr (id (Eq._oldrec (Eq.refl (x ⊓ y = x ⊓ y)) lattice_eq_DLO)) (Eq.refl (x ⊓ y))) protected instance order_bot {α : Type u} [order_bot α] : order_bot (with_top α) := order_bot.mk (some ⊥) partial_order.le partial_order.lt sorry sorry sorry sorry protected instance bounded_lattice {α : Type u} [bounded_lattice α] : bounded_lattice (with_top α) := bounded_lattice.mk lattice.sup lattice.le lattice.lt sorry sorry sorry sorry sorry sorry lattice.inf sorry sorry sorry order_top.top sorry order_bot.bot sorry theorem well_founded_lt {α : Type u_1} [partial_order α] (h : well_founded Less) : well_founded Less := sorry protected instance densely_ordered {α : Type u} [partial_order α] [densely_ordered α] [no_top_order α] : densely_ordered (with_top α) := densely_ordered.mk fun (a b : with_top α) => sorry theorem lt_iff_exists_coe_btwn {α : Type u} [partial_order α] [densely_ordered α] [no_top_order α] {a : with_top α} {b : with_top α} : a < b ↔ ∃ (x : α), a < ↑x ∧ ↑x < b := sorry end with_top namespace subtype /-- A subtype forms a `⊔`-`⊥`-semilattice if `⊥` and `⊔` preserve the property. -/ protected def semilattice_sup_bot {α : Type u} [semilattice_sup_bot α] {P : α → Prop} (Pbot : P ⊥) (Psup : ∀ {x y : α}, P x → P y → P (x ⊔ y)) : semilattice_sup_bot (Subtype fun (x : α) => P x) := semilattice_sup_bot.mk { val := ⊥, property := Pbot } semilattice_sup.le semilattice_sup.lt sorry sorry sorry sorry semilattice_sup.sup sorry sorry sorry /-- A subtype forms a `⊓`-`⊥`-semilattice if `⊥` and `⊓` preserve the property. -/ protected def semilattice_inf_bot {α : Type u} [semilattice_inf_bot α] {P : α → Prop} (Pbot : P ⊥) (Pinf : ∀ {x y : α}, P x → P y → P (x ⊓ y)) : semilattice_inf_bot (Subtype fun (x : α) => P x) := semilattice_inf_bot.mk { val := ⊥, property := Pbot } semilattice_inf.le semilattice_inf.lt sorry sorry sorry sorry semilattice_inf.inf sorry sorry sorry /-- A subtype forms a `⊓`-`⊤`-semilattice if `⊤` and `⊓` preserve the property. -/ protected def semilattice_inf_top {α : Type u} [semilattice_inf_top α] {P : α → Prop} (Ptop : P ⊤) (Pinf : ∀ {x y : α}, P x → P y → P (x ⊓ y)) : semilattice_inf_top (Subtype fun (x : α) => P x) := semilattice_inf_top.mk { val := ⊤, property := Ptop } semilattice_inf.le semilattice_inf.lt sorry sorry sorry sorry semilattice_inf.inf sorry sorry sorry end subtype namespace order_dual protected instance has_top (α : Type u) [has_bot α] : has_top (order_dual α) := has_top.mk ⊥ protected instance has_bot (α : Type u) [has_top α] : has_bot (order_dual α) := has_bot.mk ⊤ protected instance order_top (α : Type u) [order_bot α] : order_top (order_dual α) := order_top.mk ⊤ partial_order.le partial_order.lt sorry sorry sorry bot_le protected instance order_bot (α : Type u) [order_top α] : order_bot (order_dual α) := order_bot.mk ⊥ partial_order.le partial_order.lt sorry sorry sorry le_top protected instance semilattice_sup_top (α : Type u) [semilattice_inf_bot α] : semilattice_sup_top (order_dual α) := semilattice_sup_top.mk order_top.top semilattice_sup.le semilattice_sup.lt sorry sorry sorry sorry semilattice_sup.sup sorry sorry sorry protected instance semilattice_sup_bot (α : Type u) [semilattice_inf_top α] : semilattice_sup_bot (order_dual α) := semilattice_sup_bot.mk order_bot.bot semilattice_sup.le semilattice_sup.lt sorry sorry sorry sorry semilattice_sup.sup sorry sorry sorry protected instance semilattice_inf_top (α : Type u) [semilattice_sup_bot α] : semilattice_inf_top (order_dual α) := semilattice_inf_top.mk order_top.top semilattice_inf.le semilattice_inf.lt sorry sorry sorry sorry semilattice_inf.inf sorry sorry sorry protected instance semilattice_inf_bot (α : Type u) [semilattice_sup_top α] : semilattice_inf_bot (order_dual α) := semilattice_inf_bot.mk order_bot.bot semilattice_inf.le semilattice_inf.lt sorry sorry sorry sorry semilattice_inf.inf sorry sorry sorry protected instance bounded_lattice (α : Type u) [bounded_lattice α] : bounded_lattice (order_dual α) := bounded_lattice.mk lattice.sup lattice.le lattice.lt sorry sorry sorry sorry sorry sorry lattice.inf sorry sorry sorry order_top.top sorry order_bot.bot sorry protected instance bounded_distrib_lattice (α : Type u) [bounded_distrib_lattice α] : bounded_distrib_lattice (order_dual α) := bounded_distrib_lattice.mk bounded_lattice.sup bounded_lattice.le bounded_lattice.lt sorry sorry sorry sorry sorry sorry bounded_lattice.inf sorry sorry sorry sorry bounded_lattice.top sorry bounded_lattice.bot sorry end order_dual namespace prod protected instance has_top (α : Type u) (β : Type v) [has_top α] [has_top β] : has_top (α × β) := has_top.mk (⊤, ⊤) protected instance has_bot (α : Type u) (β : Type v) [has_bot α] [has_bot β] : has_bot (α × β) := has_bot.mk (⊥, ⊥) protected instance order_top (α : Type u) (β : Type v) [order_top α] [order_top β] : order_top (α × β) := order_top.mk ⊤ partial_order.le partial_order.lt sorry sorry sorry sorry protected instance order_bot (α : Type u) (β : Type v) [order_bot α] [order_bot β] : order_bot (α × β) := order_bot.mk ⊥ partial_order.le partial_order.lt sorry sorry sorry sorry protected instance semilattice_sup_top (α : Type u) (β : Type v) [semilattice_sup_top α] [semilattice_sup_top β] : semilattice_sup_top (α × β) := semilattice_sup_top.mk order_top.top semilattice_sup.le semilattice_sup.lt sorry sorry sorry sorry semilattice_sup.sup sorry sorry sorry protected instance semilattice_inf_top (α : Type u) (β : Type v) [semilattice_inf_top α] [semilattice_inf_top β] : semilattice_inf_top (α × β) := semilattice_inf_top.mk order_top.top semilattice_inf.le semilattice_inf.lt sorry sorry sorry sorry semilattice_inf.inf sorry sorry sorry protected instance semilattice_sup_bot (α : Type u) (β : Type v) [semilattice_sup_bot α] [semilattice_sup_bot β] : semilattice_sup_bot (α × β) := semilattice_sup_bot.mk order_bot.bot semilattice_sup.le semilattice_sup.lt sorry sorry sorry sorry semilattice_sup.sup sorry sorry sorry protected instance semilattice_inf_bot (α : Type u) (β : Type v) [semilattice_inf_bot α] [semilattice_inf_bot β] : semilattice_inf_bot (α × β) := semilattice_inf_bot.mk order_bot.bot semilattice_inf.le semilattice_inf.lt sorry sorry sorry sorry semilattice_inf.inf sorry sorry sorry protected instance bounded_lattice (α : Type u) (β : Type v) [bounded_lattice α] [bounded_lattice β] : bounded_lattice (α × β) := bounded_lattice.mk lattice.sup lattice.le lattice.lt sorry sorry sorry sorry sorry sorry lattice.inf sorry sorry sorry order_top.top sorry order_bot.bot sorry protected instance bounded_distrib_lattice (α : Type u) (β : Type v) [bounded_distrib_lattice α] [bounded_distrib_lattice β] : bounded_distrib_lattice (α × β) := bounded_distrib_lattice.mk bounded_lattice.sup bounded_lattice.le bounded_lattice.lt sorry sorry sorry sorry sorry sorry bounded_lattice.inf sorry sorry sorry sorry bounded_lattice.top sorry bounded_lattice.bot sorry end prod /-- Two elements of a lattice are disjoint if their inf is the bottom element. (This generalizes disjoint sets, viewed as members of the subset lattice.) -/ def disjoint {α : Type u} [semilattice_inf_bot α] (a : α) (b : α) := a ⊓ b ≤ ⊥ theorem disjoint.eq_bot {α : Type u} [semilattice_inf_bot α] {a : α} {b : α} (h : disjoint a b) : a ⊓ b = ⊥ := iff.mpr eq_bot_iff h theorem disjoint_iff {α : Type u} [semilattice_inf_bot α] {a : α} {b : α} : disjoint a b ↔ a ⊓ b = ⊥ := iff.symm eq_bot_iff theorem disjoint.comm {α : Type u} [semilattice_inf_bot α] {a : α} {b : α} : disjoint a b ↔ disjoint b a := eq.mpr (id (Eq._oldrec (Eq.refl (disjoint a b ↔ disjoint b a)) (disjoint.equations._eqn_1 a b))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ⊓ b ≤ ⊥ ↔ disjoint b a)) (disjoint.equations._eqn_1 b a))) (eq.mpr (id (Eq._oldrec (Eq.refl (a ⊓ b ≤ ⊥ ↔ b ⊓ a ≤ ⊥)) inf_comm)) (iff.refl (b ⊓ a ≤ ⊥)))) theorem disjoint.symm {α : Type u} [semilattice_inf_bot α] {a : α} {b : α} : disjoint a b → disjoint b a := iff.mp disjoint.comm @[simp] theorem disjoint_bot_left {α : Type u} [semilattice_inf_bot α] {a : α} : disjoint ⊥ a := inf_le_left @[simp] theorem disjoint_bot_right {α : Type u} [semilattice_inf_bot α] {a : α} : disjoint a ⊥ := inf_le_right theorem disjoint.mono {α : Type u} [semilattice_inf_bot α] {a : α} {b : α} {c : α} {d : α} (h₁ : a ≤ b) (h₂ : c ≤ d) : disjoint b d → disjoint a c := le_trans (inf_le_inf h₁ h₂) theorem disjoint.mono_left {α : Type u} [semilattice_inf_bot α] {a : α} {b : α} {c : α} (h : a ≤ b) : disjoint b c → disjoint a c := disjoint.mono h (le_refl c) theorem disjoint.mono_right {α : Type u} [semilattice_inf_bot α] {a : α} {b : α} {c : α} (h : b ≤ c) : disjoint a c → disjoint a b := disjoint.mono (le_refl a) h @[simp] theorem disjoint_self {α : Type u} [semilattice_inf_bot α] {a : α} : disjoint a a ↔ a = ⊥ := sorry theorem disjoint.ne {α : Type u} [semilattice_inf_bot α] {a : α} {b : α} (ha : a ≠ ⊥) (hab : disjoint a b) : a ≠ b := sorry @[simp] theorem disjoint_top {α : Type u} [bounded_lattice α] {a : α} : disjoint a ⊤ ↔ a = ⊥ := sorry @[simp] theorem top_disjoint {α : Type u} [bounded_lattice α] {a : α} : disjoint ⊤ a ↔ a = ⊥ := sorry @[simp] theorem disjoint_sup_left {α : Type u} [bounded_distrib_lattice α] {a : α} {b : α} {c : α} : disjoint (a ⊔ b) c ↔ disjoint a c ∧ disjoint b c := sorry @[simp] theorem disjoint_sup_right {α : Type u} [bounded_distrib_lattice α] {a : α} {b : α} {c : α} : disjoint a (b ⊔ c) ↔ disjoint a b ∧ disjoint a c := sorry theorem disjoint.sup_left {α : Type u} [bounded_distrib_lattice α] {a : α} {b : α} {c : α} (ha : disjoint a c) (hb : disjoint b c) : disjoint (a ⊔ b) c := iff.mpr disjoint_sup_left { left := ha, right := hb } theorem disjoint.sup_right {α : Type u} [bounded_distrib_lattice α] {a : α} {b : α} {c : α} (hb : disjoint a b) (hc : disjoint a c) : disjoint a (b ⊔ c) := iff.mpr disjoint_sup_right { left := hb, right := hc } theorem disjoint.left_le_of_le_sup_right {α : Type u} [bounded_distrib_lattice α] {a : α} {b : α} {c : α} (h : a ≤ b ⊔ c) (hd : disjoint a c) : a ≤ b := (fun (x : a ⊓ c ≤ b ⊓ c) => le_of_inf_le_sup_le x (sup_le h le_sup_right)) (Eq.symm (iff.mp disjoint_iff hd) ▸ bot_le) theorem disjoint.left_le_of_le_sup_left {α : Type u} [bounded_distrib_lattice α] {a : α} {b : α} {c : α} (h : a ≤ c ⊔ b) (hd : disjoint a c) : a ≤ b := le_of_inf_le_sup_le (Eq.symm (iff.mp disjoint_iff hd) ▸ bot_le) (sup_comm ▸ sup_le h le_sup_left) /-! ### `is_compl` predicate -/ /-- Two elements `x` and `y` are complements of each other if `x ⊔ y = ⊤` and `x ⊓ y = ⊥`. -/ structure is_compl {α : Type u} [bounded_lattice α] (x : α) (y : α) where inf_le_bot : x ⊓ y ≤ ⊥ top_le_sup : ⊤ ≤ x ⊔ y namespace is_compl protected theorem disjoint {α : Type u} [bounded_lattice α] {x : α} {y : α} (h : is_compl x y) : disjoint x y := inf_le_bot h protected theorem symm {α : Type u} [bounded_lattice α] {x : α} {y : α} (h : is_compl x y) : is_compl y x := mk (eq.mpr (id (Eq._oldrec (Eq.refl (y ⊓ x ≤ ⊥)) inf_comm)) (inf_le_bot h)) (eq.mpr (id (Eq._oldrec (Eq.refl (⊤ ≤ y ⊔ x)) sup_comm)) (top_le_sup h)) theorem of_eq {α : Type u} [bounded_lattice α] {x : α} {y : α} (h₁ : x ⊓ y = ⊥) (h₂ : x ⊔ y = ⊤) : is_compl x y := mk (le_of_eq h₁) (le_of_eq (Eq.symm h₂)) theorem inf_eq_bot {α : Type u} [bounded_lattice α] {x : α} {y : α} (h : is_compl x y) : x ⊓ y = ⊥ := disjoint.eq_bot (is_compl.disjoint h) theorem sup_eq_top {α : Type u} [bounded_lattice α] {x : α} {y : α} (h : is_compl x y) : x ⊔ y = ⊤ := top_unique (top_le_sup h) theorem to_order_dual {α : Type u} [bounded_lattice α] {x : α} {y : α} (h : is_compl x y) : is_compl x y := mk (top_le_sup h) (inf_le_bot h) theorem le_left_iff {α : Type u} [bounded_distrib_lattice α] {x : α} {y : α} {z : α} (h : is_compl x y) : z ≤ x ↔ disjoint z y := { mp := fun (hz : z ≤ x) => disjoint.mono_left hz (is_compl.disjoint h), mpr := fun (hz : disjoint z y) => le_of_inf_le_sup_le (le_trans hz bot_le) (le_trans le_top (top_le_sup h)) } theorem le_right_iff {α : Type u} [bounded_distrib_lattice α] {x : α} {y : α} {z : α} (h : is_compl x y) : z ≤ y ↔ disjoint z x := le_left_iff (is_compl.symm h) theorem left_le_iff {α : Type u} [bounded_distrib_lattice α] {x : α} {y : α} {z : α} (h : is_compl x y) : x ≤ z ↔ ⊤ ≤ z ⊔ y := le_left_iff (to_order_dual h) theorem right_le_iff {α : Type u} [bounded_distrib_lattice α] {x : α} {y : α} {z : α} (h : is_compl x y) : y ≤ z ↔ ⊤ ≤ z ⊔ x := left_le_iff (is_compl.symm h) theorem antimono {α : Type u} [bounded_distrib_lattice α] {x : α} {y : α} {x' : α} {y' : α} (h : is_compl x y) (h' : is_compl x' y') (hx : x ≤ x') : y' ≤ y := iff.mpr (right_le_iff h') (le_trans (top_le_sup (is_compl.symm h)) (sup_le_sup_left hx y)) theorem right_unique {α : Type u} [bounded_distrib_lattice α] {x : α} {y : α} {z : α} (hxy : is_compl x y) (hxz : is_compl x z) : y = z := le_antisymm (antimono hxz hxy (le_refl x)) (antimono hxy hxz (le_refl x)) theorem left_unique {α : Type u} [bounded_distrib_lattice α] {x : α} {y : α} {z : α} (hxz : is_compl x z) (hyz : is_compl y z) : x = y := right_unique (is_compl.symm hxz) (is_compl.symm hyz) theorem sup_inf {α : Type u} [bounded_distrib_lattice α] {x : α} {y : α} {x' : α} {y' : α} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊔ x') (y ⊓ y') := sorry theorem inf_sup {α : Type u} [bounded_distrib_lattice α] {x : α} {y : α} {x' : α} {y' : α} (h : is_compl x y) (h' : is_compl x' y') : is_compl (x ⊓ x') (y ⊔ y') := is_compl.symm (sup_inf (is_compl.symm h) (is_compl.symm h')) theorem inf_left_eq_bot_iff {α : Type u} [bounded_distrib_lattice α] {x : α} {y : α} {z : α} (h : is_compl y z) : x ⊓ y = ⊥ ↔ x ≤ z := inf_eq_bot_iff_le_compl (sup_eq_top h) (inf_eq_bot h) theorem inf_right_eq_bot_iff {α : Type u} [bounded_distrib_lattice α] {x : α} {y : α} {z : α} (h : is_compl y z) : x ⊓ z = ⊥ ↔ x ≤ y := inf_left_eq_bot_iff (is_compl.symm h) theorem disjoint_left_iff {α : Type u} [bounded_distrib_lattice α] {x : α} {y : α} {z : α} (h : is_compl y z) : disjoint x y ↔ x ≤ z := iff.trans disjoint_iff (inf_left_eq_bot_iff h) theorem disjoint_right_iff {α : Type u} [bounded_distrib_lattice α] {x : α} {y : α} {z : α} (h : is_compl y z) : disjoint x z ↔ x ≤ y := disjoint_left_iff (is_compl.symm h) end is_compl theorem is_compl_bot_top {α : Type u} [bounded_lattice α] : is_compl ⊥ ⊤ := is_compl.of_eq bot_inf_eq sup_top_eq theorem is_compl_top_bot {α : Type u} [bounded_lattice α] : is_compl ⊤ ⊥ := is_compl.of_eq inf_bot_eq top_sup_eq theorem bot_ne_top {α : Type u} [bounded_lattice α] [nontrivial α] : ⊥ ≠ ⊤ := fun (H : ⊥ = ⊤) => iff.mpr not_nontrivial_iff_subsingleton (subsingleton_of_bot_eq_top H) _inst_2 theorem top_ne_bot {α : Type u} [bounded_lattice α] [nontrivial α] : ⊤ ≠ ⊥ := ne.symm bot_ne_top namespace bool protected instance bounded_lattice : bounded_lattice Bool := bounded_lattice.mk lattice.sup lattice.le lattice.lt sorry sorry sorry sorry sorry sorry lattice.inf sorry sorry sorry tt sorry false sorry end bool @[simp] theorem top_eq_tt : ⊤ = tt := rfl @[simp] theorem bot_eq_ff : ⊥ = false := rfl
37839e4ea9af33e0884c192f3e58e6d26737bc97
40ad357bbd0d327dd1e3e7f7beb868bd4e5b0a9d
/src/temporal_logic/feasibility.lean
fa00c4026b5af02d8fe446e90c83241f1033b7b1
[]
no_license
unitb/temporal-logic
9966424f015976d5997a9ffa30cbd77cc3a9cb1c
accec04d1b09ca841be065511c9e206b725b16e9
refs/heads/master
1,633,868,382,769
1,541,072,223,000
1,541,072,223,000
114,790,987
5
3
null
null
null
null
UTF-8
Lean
false
false
4,305
lean
import .refinement.one_to_one universe variables u u₀ u₁ u₂ namespace temporal namespace feasibility open fairness predicate nat local infix ` ≃ `:75 := v_eq section feasibility parameters {α : Type u} parameters {evt : Type u₂} parameters {p : pred' α} parameters (A : evt → act α) parameters {cs₀ fs₀ : evt → pred' α} parameters (J : pred' α) parameters [inhabited evt] [inhabited α] parameter init_FIS : ∃ s, s ⊨ p parameter init_INV : ∀ s, s ⊨ p → s ⊨ J parameter DLF : ∀ s, s ⊨ J → ∃ e, s ⊨ cs₀ e ∧ s ⊨ fs₀ e parameter evt_FIS : ∀ e s, s ⊨ J → s ⊨ cs₀ e → s ⊨ fs₀ e → ∃ s', A e s s' parameter evt_INV : ∀ e s s', A e s s' → s ⊨ J → s' ⊨ J def SPEC₀ (v : tvar α) : cpred := spec p cs₀ fs₀ A v def p' : pred' (unit × α) := p ! pair.snd def q' : pred' (unit × unit) := True open prod def A' (e : evt) : act (unit × α) := λ σ σ', (A e on snd) σ σ' def C (e : evt) : act (unit × unit) := λ _ _, true def C' (e : evt) : act (evt × unit × unit) := λ ⟨sch,_⟩ _, sch = e abbreviation J' : pred' (unit × α × unit) := J ! pair.fst ! pair.snd abbreviation cs₀' (e : evt) : pred' (unit × α) := cs₀ e ! pair.snd abbreviation fs₀' (e : evt) : pred' (unit × α) := fs₀ e ! pair.snd abbreviation cs₁ (e : evt) : pred' (unit × unit) := True abbreviation fs₁ (e : evt) : pred' (unit × unit) := True section include init_FIS init_INV DLF lemma SIM₀' (v o : unit) (h : (o, v) ⊨ q') : (∃ (w : α), (o, w) ⊨ p' ∧ (o, w, v) ⊨ J') := by { simp [q',p'] at *, apply exists_imp_exists _ init_FIS, intros, split, assumption, apply init_INV, assumption } end open function section include evt_FIS evt_INV DLF lemma SIM' (w : α) (v o v' o' : unit) (e : evt) (hJ : (o, w, v) ⊨ J') (_ : true) (_ : true) (_ : true) (hC : C e (o, v) (o', v')) : (∃ (w' : α), (o,w) ⊨ cs₀' e ∧ (o,w) ⊨ fs₀' e ∧ A' e (o, w) (o', w') ∧ (o', w', v') ⊨ J') := begin -- simp [comp,A',on_fun] at *, -- casesm* [_ ∧ _, Exists _, unit], -- constructor_matching* [_ ∧ _], -- apply exists_imp_exists _ (evt_FIS e w _), -- intros, split, admit, assumption, -- tauto, admit, end end def o : tvar unit := ↑() -- parameter Hpo -- : ∀ c a e, one_to_one_po' (SPEC₀.saf a o ⋀ ◻(J ! ⦃o,a,c⦄)) -- ⟨cs₁ e,fs₁ e,C' e⟩ -- ⟨cs₀ e,fs₀ e,A' e⟩ ⦃o,c⦄ ⦃o,a⦄) def SPEC₀.saf' (v : tvar α) (sch : tvar evt) : cpred := spec_saf_spec p' cs₀' fs₀' A' ⦃o,v⦄ sch def SPEC₁ (v : tvar unit) : cpred := spec q' cs₁ fs₁ C ⦃o,v⦄ lemma Hpo' : ∀ c a e sch, one_to_one_po' (SPEC₁ c ⋀ SPEC₀.saf' a sch ⋀ ◻(J' ! ⦃o,a,c⦄)) ⟨cs₁ e!pair.snd,fs₁ e!pair.snd,one_to_one.C' C e⟩ ⟨cs₀' e,fs₀' e,A' e⟩ ⦃sch,o,c⦄ ⦃o,a⦄ := begin intros, constructor, { simp [tl_leads_to], }, { simp [tl_leads_to], }, { simp [tl_leads_to], }, begin [temporal] simp [SPEC₁,q',sched,SPEC₀.saf'], intros _ _ _ h _, henceforth! at *, intros, cases h with x h, explicit' [C,one_to_one.C',A'] with h a_3 { cc }, end, end include J init_INV init_FIS evt_INV evt_FIS Hpo' DLF lemma feasibility [schedulable evt] : ⊩ (∃∃ v, SPEC₀ v) := begin [temporal] have := temporal.feasibility.SIM', have := @one_to_one.refinement α unit unit evt temporal.feasibility.p' temporal.feasibility.q' temporal.feasibility.A' temporal.feasibility.C temporal.feasibility.cs₀' temporal.feasibility.fs₀' temporal.feasibility.cs₁ temporal.feasibility.fs₁ temporal.feasibility.J' True _ _ _ _ temporal.feasibility.SIM₀' temporal.feasibility.SIM' o _ _ Γ _, { simp [one_to_one.SPEC₀,SPEC₀] at this ⊢, casesm* [p_exists _, _ ⋀ _], existsi _, solve_by_elim, split, { simp [A',p',action_on' _ _ prod.snd] at *, tauto, }, { simp [A',action_on' _ _ prod.snd] at *, assumption, }, }, { intros, simp, }, { intros, simp, }, apply temporal.feasibility.Hpo' , { existsi o, simp [one_to_one.SPEC₁,q',C,C',sched], } end end feasibility end feasibility end temporal
ae6956f7bb9bd7d0c444d1e690e20eeec16b5140
e61a235b8468b03aee0120bf26ec615c045005d2
/stage0/src/Init/Lean/Meta/Basic.lean
5024cf1b285046ab0a40bb55a424c24d16863492
[ "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
33,684
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.Reader import Init.Lean.Data.LOption import Init.Lean.Environment import Init.Lean.Class import Init.Lean.ReducibilityAttrs import Init.Lean.Util.Trace import Init.Lean.Util.RecDepth import Init.Lean.Util.Closure import Init.Lean.Meta.Exception import Init.Lean.Meta.DiscrTreeTypes import Init.Lean.Eval /- This module provides four (mutually dependent) goodies that are needed for building the elaborator and tactic frameworks. 1- Weak head normal form computation with support for metavariables and transparency modes. 2- Definitionally equality checking with support for metavariables (aka unification modulo definitional equality). 3- Type inference. 4- Type class resolution. They are packed into the MetaM monad. -/ namespace Lean namespace Meta inductive TransparencyMode | all | default | reducible namespace TransparencyMode instance : Inhabited TransparencyMode := ⟨TransparencyMode.default⟩ def beq : TransparencyMode → TransparencyMode → Bool | all, all => true | default, default => true | reducible, reducible => true | _, _ => false instance : HasBeq TransparencyMode := ⟨beq⟩ def hash : TransparencyMode → USize | all => 7 | default => 11 | reducible => 13 instance : Hashable TransparencyMode := ⟨hash⟩ def lt : TransparencyMode → TransparencyMode → Bool | reducible, default => true | reducible, all => true | default, all => true | _, _ => false end TransparencyMode structure Config := (opts : Options := {}) (foApprox : Bool := false) (ctxApprox : Bool := false) (quasiPatternApprox : Bool := false) /- When `constApprox` is set to true, we solve `?m t =?= c` using `?m := fun _ => c` when `?m t` is not a higher-order pattern and `c` is not an application as -/ (constApprox : Bool := false) /- When the following flag is set, `isDefEq` throws the exeption `Exeption.isDefEqStuck` whenever it encounters a constraint `?m ... =?= t` where `?m` is read only. This feature is useful for type class resolution where we may want to notify the caller that the TC problem may be solveable later after it assigns `?m`. -/ (isDefEqStuckEx : Bool := false) (debug : Bool := false) (transparency : TransparencyMode := TransparencyMode.default) structure ParamInfo := (implicit : Bool := false) (instImplicit : Bool := false) (hasFwdDeps : Bool := false) (backDeps : Array Nat := #[]) instance ParamInfo.inhabited : Inhabited ParamInfo := ⟨{}⟩ structure FunInfo := (paramInfo : Array ParamInfo := #[]) (resultDeps : Array Nat := #[]) structure InfoCacheKey := (transparency : TransparencyMode) (expr : Expr) (nargs? : Option Nat) namespace InfoCacheKey instance : Inhabited InfoCacheKey := ⟨⟨arbitrary _, arbitrary _, arbitrary _⟩⟩ instance : Hashable InfoCacheKey := ⟨fun ⟨transparency, expr, nargs⟩ => mixHash (hash transparency) $ mixHash (hash expr) (hash nargs)⟩ instance : HasBeq InfoCacheKey := ⟨fun ⟨t₁, e₁, n₁⟩ ⟨t₂, e₂, n₂⟩ => t₁ == t₂ && n₁ == n₂ && e₁ == e₂⟩ end InfoCacheKey structure Cache := (inferType : PersistentExprStructMap Expr := {}) (funInfo : PersistentHashMap InfoCacheKey FunInfo := {}) (synthInstance : PersistentHashMap Expr (Option Expr) := {}) (whnfDefault : PersistentExprStructMap Expr := {}) -- cache for closed terms and `TransparencyMode.default` structure Context := (config : Config := {}) (lctx : LocalContext := {}) (localInstances : LocalInstances := #[]) (currRecDepth : Nat) (maxRecDepth : Nat) structure PostponedEntry := (lhs : Level) (rhs : Level) structure State := (env : Environment) (mctx : MetavarContext := {}) (cache : Cache := {}) (ngen : NameGenerator := {}) (traceState : TraceState := {}) (postponed : PersistentArray PostponedEntry := {}) abbrev MetaM := ReaderT Context (EStateM Exception State) instance MetaM.inhabited {α} : Inhabited (MetaM α) := ⟨fun c s => EStateM.Result.error (arbitrary _) s⟩ @[inline] def withIncRecDepth {α} (x : MetaM α) : MetaM α := do ctx ← read; when (ctx.currRecDepth == ctx.maxRecDepth) $ throw $ Exception.other maxRecDepthErrorMessage; adaptReader (fun (ctx : Context) => { ctx with currRecDepth := ctx.currRecDepth + 1 }) x @[inline] def getLCtx : MetaM LocalContext := do ctx ← read; pure ctx.lctx @[inline] def getLocalInstances : MetaM LocalInstances := do ctx ← read; pure ctx.localInstances @[inline] def getConfig : MetaM Config := do ctx ← read; pure ctx.config @[inline] def getMCtx : MetaM MetavarContext := do s ← get; pure s.mctx @[inline] def getEnv : MetaM Environment := do s ← get; pure s.env @[inline] def setEnv (env : Environment) : MetaM Unit := do modify $ fun s => { s with env := env } def mkWHNFRef : IO (IO.Ref (Expr → MetaM Expr)) := IO.mkRef $ fun _ => throw $ Exception.other "whnf implementation was not set" @[init mkWHNFRef] def whnfRef : IO.Ref (Expr → MetaM Expr) := arbitrary _ def mkInferTypeRef : IO (IO.Ref (Expr → MetaM Expr)) := IO.mkRef $ fun _ => throw $ Exception.other "inferType implementation was not set" @[init mkInferTypeRef] def inferTypeRef : IO.Ref (Expr → MetaM Expr) := arbitrary _ def mkIsExprDefEqAuxRef : IO (IO.Ref (Expr → Expr → MetaM Bool)) := IO.mkRef $ fun _ _ => throw $ Exception.other "isDefEq implementation was not set" @[init mkIsExprDefEqAuxRef] def isExprDefEqAuxRef : IO.Ref (Expr → Expr → MetaM Bool) := arbitrary _ def mkSynthPendingRef : IO (IO.Ref (MVarId → MetaM Bool)) := IO.mkRef $ fun _ => pure false @[init mkSynthPendingRef] def synthPendingRef : IO.Ref (MVarId → MetaM Bool) := arbitrary _ structure MetaExtState := (whnf : Expr → MetaM Expr) (inferType : Expr → MetaM Expr) (isDefEqAux : Expr → Expr → MetaM Bool) (synthPending : MVarId → MetaM Bool) instance MetaExtState.inhabited : Inhabited MetaExtState := ⟨{ whnf := arbitrary _, inferType := arbitrary _, isDefEqAux := arbitrary _, synthPending := arbitrary _ }⟩ def mkMetaExtension : IO (EnvExtension MetaExtState) := registerEnvExtension $ do whnf ← whnfRef.get; inferType ← inferTypeRef.get; isDefEqAux ← isExprDefEqAuxRef.get; synthPending ← synthPendingRef.get; pure { whnf := whnf, inferType := inferType, isDefEqAux := isDefEqAux, synthPending := synthPending } @[init mkMetaExtension] constant metaExt : EnvExtension MetaExtState := arbitrary _ def whnf (e : Expr) : MetaM Expr := withIncRecDepth $ do env ← getEnv; (metaExt.getState env).whnf e def whnfForall (e : Expr) : MetaM Expr := do e' ← whnf e; if e'.isForall then pure e' else pure e def inferType (e : Expr) : MetaM Expr := withIncRecDepth $ do env ← getEnv; (metaExt.getState env).inferType e def isExprDefEqAux (t s : Expr) : MetaM Bool := withIncRecDepth $ do env ← getEnv; (metaExt.getState env).isDefEqAux t s def synthPending (mvarId : MVarId) : MetaM Bool := withIncRecDepth $ do env ← getEnv; (metaExt.getState env).synthPending mvarId def mkFreshId : MetaM Name := do s ← get; let id := s.ngen.curr; modify $ fun s => { s with ngen := s.ngen.next }; pure id def mkFreshExprMVarAt (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (userName : Name := Name.anonymous) (kind : MetavarKind := MetavarKind.natural) : MetaM Expr := do mvarId ← mkFreshId; modify $ fun s => { s with mctx := s.mctx.addExprMVarDecl mvarId userName lctx localInsts type kind }; pure $ mkMVar mvarId def mkFreshExprMVar (type : Expr) (userName : Name := Name.anonymous) (kind : MetavarKind := MetavarKind.natural) : MetaM Expr := do lctx ← getLCtx; localInsts ← getLocalInstances; mkFreshExprMVarAt lctx localInsts type userName kind def mkFreshLevelMVar : MetaM Level := do mvarId ← mkFreshId; modify $ fun s => { s with mctx := s.mctx.addLevelMVarDecl mvarId }; pure $ mkLevelMVar mvarId @[inline] def throwEx {α} (f : ExceptionContext → Exception) : MetaM α := do ctx ← read; s ← get; throw (f { env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts }) def throwBug {α} (b : Bug) : MetaM α := throwEx $ Exception.bug b /-- Execute `x` only in debugging mode. -/ @[inline] private def whenDebugging (x : MetaM Unit) : MetaM Unit := do ctx ← read; when ctx.config.debug x @[inline] def shouldReduceAll : MetaM Bool := do ctx ← read; pure $ ctx.config.transparency == TransparencyMode.all @[inline] def shouldReduceReducibleOnly : MetaM Bool := do ctx ← read; pure $ ctx.config.transparency == TransparencyMode.reducible @[inline] def getTransparency : MetaM TransparencyMode := do ctx ← read; pure $ ctx.config.transparency @[inline] def getOptions : MetaM Options := do ctx ← read; pure ctx.config.opts -- Remark: wanted to use `private`, but in C++ parser, `private` declarations do not shadow outer public ones. -- TODO: fix this bug @[inline] def isReducible (constName : Name) : MetaM Bool := do env ← getEnv; pure $ isReducible env constName @[inline] def withConfig {α} (f : Config → Config) (x : MetaM α) : MetaM α := adaptReader (fun (ctx : Context) => { ctx with config := f ctx.config }) x /-- While executing `x`, ensure the given transparency mode is used. -/ @[inline] def withTransparency {α} (mode : TransparencyMode) (x : MetaM α) : MetaM α := withConfig (fun config => { config with transparency := mode }) x @[inline] def withReducible {α} (x : MetaM α) : MetaM α := withTransparency TransparencyMode.reducible x @[inline] def withAtLeastTransparency {α} (mode : TransparencyMode) (x : MetaM α) : MetaM α := withConfig (fun config => let oldMode := config.transparency; let mode := if oldMode.lt mode then mode else oldMode; { config with transparency := mode }) x def getMVarDecl (mvarId : MVarId) : MetaM MetavarDecl := do mctx ← getMCtx; match mctx.findDecl? mvarId with | some d => pure d | none => throwEx $ Exception.unknownExprMVar mvarId def setMVarKind (mvarId : MVarId) (kind : MetavarKind) : MetaM Unit := modify $ fun s => { s with mctx := s.mctx.setMVarKind mvarId kind } def isReadOnlyExprMVar (mvarId : MVarId) : MetaM Bool := do mvarDecl ← getMVarDecl mvarId; mctx ← getMCtx; pure $ mvarDecl.depth != mctx.depth def isReadOnlyOrSyntheticOpaqueExprMVar (mvarId : MVarId) : MetaM Bool := do mvarDecl ← getMVarDecl mvarId; match mvarDecl.kind with | MetavarKind.syntheticOpaque => pure true | _ => do mctx ← getMCtx; pure $ mvarDecl.depth != mctx.depth def isReadOnlyLevelMVar (mvarId : MVarId) : MetaM Bool := do mctx ← getMCtx; match mctx.findLevelDepth? mvarId with | some depth => pure $ depth != mctx.depth | _ => throwEx $ Exception.unknownLevelMVar mvarId def renameMVar (mvarId : MVarId) (newUserName : Name) : MetaM Unit := modify $ fun s => { s with mctx := s.mctx.renameMVar mvarId newUserName } @[inline] def isExprMVarAssigned (mvarId : MVarId) : MetaM Bool := do mctx ← getMCtx; pure $ mctx.isExprAssigned mvarId @[inline] def getExprMVarAssignment? (mvarId : MVarId) : MetaM (Option Expr) := do mctx ← getMCtx; pure (mctx.getExprAssignment? mvarId) def assignExprMVar (mvarId : MVarId) (val : Expr) : MetaM Unit := do whenDebugging $ whenM (isExprMVarAssigned mvarId) $ throwBug $ Bug.overwritingExprMVar mvarId; modify $ fun s => { s with mctx := s.mctx.assignExpr mvarId val } def isDelayedAssigned (mvarId : MVarId) : MetaM Bool := do mctx ← getMCtx; pure $ mctx.isDelayedAssigned mvarId def hasAssignableMVar (e : Expr) : MetaM Bool := do mctx ← getMCtx; pure $ mctx.hasAssignableMVar e def dbgTrace {α} [HasToString α] (a : α) : MetaM Unit := _root_.dbgTrace (toString a) $ fun _ => pure () @[inline] private def getTraceState : MetaM TraceState := do s ← get; pure s.traceState def addContext (msg : MessageData) : MetaM MessageData := do ctx ← read; s ← get; pure $ MessageData.withContext { env := s.env, mctx := s.mctx, lctx := ctx.lctx, opts := ctx.config.opts } msg instance tracer : SimpleMonadTracerAdapter MetaM := { getOptions := getOptions, getTraceState := getTraceState, addContext := addContext, modifyTraceState := fun f => modify $ fun s => { s with traceState := f s.traceState } } def getConstAux (constName : Name) (exception? : Bool) : MetaM (Option ConstantInfo) := do env ← getEnv; match env.find? constName with | some (info@(ConstantInfo.thmInfo _)) => condM shouldReduceAll (pure (some info)) (pure none) | some (info@(ConstantInfo.defnInfo _)) => condM shouldReduceReducibleOnly (condM (isReducible constName) (pure (some info)) (pure none)) (pure (some info)) | some info => pure (some info) | none => if exception? then throwEx $ Exception.unknownConst constName else pure none @[inline] def getConst (constName : Name) : MetaM (Option ConstantInfo) := getConstAux constName true @[inline] def getConstNoEx (constName : Name) : MetaM (Option ConstantInfo) := getConstAux constName false def getConstInfo (constName : Name) : MetaM ConstantInfo := do env ← getEnv; match env.find? constName with | some info => pure info | none => throwEx $ Exception.unknownConst constName def getLocalDecl (fvarId : FVarId) : MetaM LocalDecl := do lctx ← getLCtx; match lctx.find? fvarId with | some d => pure d | none => throwEx $ Exception.unknownFVar fvarId def getFVarLocalDecl (fvar : Expr) : MetaM LocalDecl := getLocalDecl fvar.fvarId! def instantiateMVars (e : Expr) : MetaM Expr := if e.hasMVar then modifyGet $ fun s => let (e, mctx) := s.mctx.instantiateMVars e; (e, { s with mctx := mctx }) else pure e @[inline] private def liftMkBindingM {α} (x : MetavarContext.MkBindingM α) : MetaM α := fun ctx s => match x ctx.lctx { mctx := s.mctx, ngen := s.ngen } with | EStateM.Result.ok e newS => EStateM.Result.ok e { s with mctx := newS.mctx, ngen := newS.ngen } | EStateM.Result.error (MetavarContext.MkBinding.Exception.revertFailure mctx lctx toRevert decl) newS => EStateM.Result.error (Exception.revertFailure toRevert decl { lctx := lctx, mctx := mctx, env := s.env, opts := ctx.config.opts }) { s with mctx := newS.mctx, ngen := newS.ngen } def mkForall (xs : Array Expr) (e : Expr) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM $ MetavarContext.mkForall xs e def mkLambda (xs : Array Expr) (e : Expr) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM $ MetavarContext.mkLambda xs e def mkForallUsedOnly (xs : Array Expr) (e : Expr) : MetaM (Expr × Nat) := if xs.isEmpty then pure (e, 0) else liftMkBindingM $ MetavarContext.mkForallUsedOnly xs e def elimMVarDeps (xs : Array Expr) (e : Expr) (preserveOrder : Bool := false) : MetaM Expr := if xs.isEmpty then pure e else liftMkBindingM $ MetavarContext.elimMVarDeps xs e preserveOrder /-- Save cache, execute `x`, restore cache -/ @[inline] def savingCache {α} (x : MetaM α) : MetaM α := do s ← get; let savedCache := s.cache; finally x (modify $ fun s => { s with cache := savedCache }) def isClassQuickConst (constName : Name) : MetaM (LOption Name) := do env ← getEnv; if isClass env constName then pure (LOption.some constName) else do cinfo? ← getConst constName; match cinfo? with | some _ => pure LOption.undef | none => pure LOption.none partial def isClassQuick : Expr → MetaM (LOption Name) | Expr.bvar _ _ => pure LOption.none | Expr.lit _ _ => pure LOption.none | Expr.fvar _ _ => pure LOption.none | Expr.sort _ _ => pure LOption.none | Expr.lam _ _ _ _ => pure LOption.none | Expr.letE _ _ _ _ _ => pure LOption.undef | Expr.proj _ _ _ _ => pure LOption.undef | Expr.forallE _ _ b _ => isClassQuick b | Expr.mdata _ e _ => isClassQuick e | Expr.const n _ _ => isClassQuickConst n | Expr.mvar mvarId _ => do val? ← getExprMVarAssignment? mvarId; match val? with | some val => isClassQuick val | none => pure LOption.none | Expr.app f _ _ => match f.getAppFn with | Expr.const n _ _ => isClassQuickConst n | Expr.lam _ _ _ _ => pure LOption.undef | _ => pure LOption.none | Expr.localE _ _ _ _ => unreachable! /-- Reset `synthInstance` cache, execute `x`, and restore cache -/ @[inline] def resettingSynthInstanceCache {α} (x : MetaM α) : MetaM α := do s ← get; let savedSythInstance := s.cache.synthInstance; modify $ fun s => { s with cache := { s.cache with synthInstance := {} } }; finally x (modify $ fun s => { s with cache := { s.cache with synthInstance := savedSythInstance } }) /-- Add entry `{ className := className, fvar := fvar }` to localInstances, and then execute continuation `k`. It resets the type class cache using `resettingSynthInstanceCache`. -/ @[inline] def withNewLocalInstance {α} (className : Name) (fvar : Expr) (k : MetaM α) : MetaM α := resettingSynthInstanceCache $ adaptReader (fun (ctx : Context) => { ctx with localInstances := ctx.localInstances.push { className := className, fvar := fvar } }) k /-- `withNewLocalInstances isClassExpensive fvars j k` updates the vector or local instances using free variables `fvars[j] ... fvars.back`, and execute `k`. - `isClassExpensive` is defined later. - The type class chache is reset whenever a new local instance is found. - `isClassExpensive` uses `whnf` which depends (indirectly) on the set of local instances. Thus, each new local instance requires a new `resettingSynthInstanceCache`. -/ @[specialize] partial def withNewLocalInstances {α} (isClassExpensive : Expr → MetaM (Option Name)) (fvars : Array Expr) : Nat → MetaM α → MetaM α | i, k => if h : i < fvars.size then do let fvar := fvars.get ⟨i, h⟩; decl ← getFVarLocalDecl fvar; c? ← isClassQuick decl.type; match c? with | LOption.none => withNewLocalInstances (i+1) k | LOption.undef => do c? ← isClassExpensive decl.type; match c? with | none => withNewLocalInstances (i+1) k | some c => withNewLocalInstance c fvar $ withNewLocalInstances (i+1) k | LOption.some c => withNewLocalInstance c fvar $ withNewLocalInstances (i+1) k else k /-- `forallTelescopeAux whnf k lctx fvars j type` Remarks: - `lctx` is the `MetaM` local context exteded with the declaration for `fvars`. - `type` is the type we are computing the telescope for. It contains only dangling bound variables in the range `[j, fvars.size)` - if `reducing? == true` and `type` is not `forallE`, we use `whnf`. - when `type` is not a `forallE` nor it can't be reduced to one, we excute the continuation `k`. Here is an example that demonstrates the `reducing?`. Suppose we have ``` abbrev StateM s a := s -> Prod a s ``` Now, assume we are trying to build the telescope for ``` forall (x : Nat), StateM Int Bool ``` if `reducing? == true`, the function executes `k #[(x : Nat) (s : Int)] Bool`. if `reducing? == false`, the function executes `k #[(x : Nat)] (StateM Int Bool)` if `maxFVars?` is `some max`, then we interrupt the telescope construction when `fvars.size == max` -/ @[specialize] private partial def forallTelescopeReducingAuxAux {α} (isClassExpensive : Expr → MetaM (Option Name)) (reducing? : Bool) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : LocalContext → Array Expr → Nat → Expr → MetaM α | lctx, fvars, j, type@(Expr.forallE n d b c) => do let process : Unit → MetaM α := fun _ => do { let d := d.instantiateRevRange j fvars.size fvars; fvarId ← mkFreshId; let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo; let fvar := mkFVar fvarId; let fvars := fvars.push fvar; forallTelescopeReducingAuxAux lctx fvars j b }; match maxFVars? with | none => process () | some maxFVars => if fvars.size < maxFVars then process () else let type := type.instantiateRevRange j fvars.size fvars; adaptReader (fun (ctx : Context) => { ctx with lctx := lctx }) $ withNewLocalInstances isClassExpensive fvars j $ k fvars type | lctx, fvars, j, type => let type := type.instantiateRevRange j fvars.size fvars; adaptReader (fun (ctx : Context) => { ctx with lctx := lctx }) $ withNewLocalInstances isClassExpensive fvars j $ if reducing? then do newType ← whnf type; if newType.isForall then forallTelescopeReducingAuxAux lctx fvars fvars.size newType else k fvars type else k fvars type /- We need this auxiliary definition because it depends on `isClassExpensive`, and `isClassExpensive` depends on it. -/ @[specialize] private def forallTelescopeReducingAux {α} (isClassExpensive : Expr → MetaM (Option Name)) (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := do newType ← whnf type; if newType.isForall then do lctx ← getLCtx; forallTelescopeReducingAuxAux isClassExpensive true maxFVars? k lctx #[] 0 newType else k #[] type partial def isClassExpensive : Expr → MetaM (Option Name) | type => withReducible $ -- when testing whether a type is a type class, we only unfold reducible constants. forallTelescopeReducingAux isClassExpensive type none $ fun xs type => do match type.getAppFn with | Expr.const c _ _ => do env ← getEnv; pure $ if isClass env c then some c else none | _ => pure none /-- Given `type` of the form `forall xs, A`, execute `k xs A`. This combinator will declare local declarations, create free variables for them, execute `k` with updated local context, and make sure the cache is restored after executing `k`. -/ def forallTelescope {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do lctx ← getLCtx; forallTelescopeReducingAuxAux isClassExpensive false none k lctx #[] 0 type /-- Similar to `forallTelescope`, but given `type` of the form `forall xs, A`, it reduces `A` and continues bulding the telescope if it is a `forall`. -/ def forallTelescopeReducing {α} (type : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux isClassExpensive type none k /-- Similar to `forallTelescopeReducing`, stops constructing the telescope when it reaches size `maxFVars`. -/ def forallBoundedTelescope {α} (type : Expr) (maxFVars? : Option Nat) (k : Array Expr → Expr → MetaM α) : MetaM α := forallTelescopeReducingAux isClassExpensive type maxFVars? k /-- Return the parameter names for the givel global declaration. -/ def getParamNames (declName : Name) : MetaM (Array Name) := do cinfo ← getConstInfo declName; forallTelescopeReducing cinfo.type $ fun xs _ => do xs.mapM $ fun x => do localDecl ← getLocalDecl x.fvarId!; pure localDecl.userName def isClass (type : Expr) : MetaM (Option Name) := do c? ← isClassQuick type; match c? with | LOption.none => pure none | LOption.some c => pure (some c) | LOption.undef => isClassExpensive type /-- Similar to `forallTelescopeAuxAux` but for lambda and let expressions. -/ private partial def lambdaTelescopeAux {α} (k : Array Expr → Expr → MetaM α) : LocalContext → Array Expr → Nat → Expr → MetaM α | lctx, fvars, j, Expr.lam n d b c => do let d := d.instantiateRevRange j fvars.size fvars; fvarId ← mkFreshId; let lctx := lctx.mkLocalDecl fvarId n d c.binderInfo; let fvar := mkFVar fvarId; lambdaTelescopeAux lctx (fvars.push fvar) j b | lctx, fvars, j, Expr.letE n t v b _ => do let t := t.instantiateRevRange j fvars.size fvars; let v := v.instantiateRevRange j fvars.size fvars; fvarId ← mkFreshId; let lctx := lctx.mkLetDecl fvarId n t v; let fvar := mkFVar fvarId; lambdaTelescopeAux lctx (fvars.push fvar) j b | lctx, fvars, j, e => let e := e.instantiateRevRange j fvars.size fvars; adaptReader (fun (ctx : Context) => { ctx with lctx := lctx }) $ withNewLocalInstances isClassExpensive fvars j $ do k fvars e /-- Similar to `forallTelescope` but for lambda and let expressions. -/ def lambdaTelescope {α} (e : Expr) (k : Array Expr → Expr → MetaM α) : MetaM α := do lctx ← getLCtx; lambdaTelescopeAux k lctx #[] 0 e -- `kind` specifies the metavariable kind for metavariables not corresponding to instance implicit `[ ... ]` arguments. private partial def forallMetaTelescopeReducingAux (reducing? : Bool) (maxMVars? : Option Nat) (kind : MetavarKind) : Array Expr → Array BinderInfo → Nat → Expr → MetaM (Array Expr × Array BinderInfo × Expr) | mvars, bis, j, type@(Expr.forallE n d b c) => do let process : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do { let d := d.instantiateRevRange j mvars.size mvars; let k := if c.binderInfo.isInstImplicit then MetavarKind.synthetic else kind; mvar ← mkFreshExprMVar d n k; let mvars := mvars.push mvar; let bis := bis.push c.binderInfo; forallMetaTelescopeReducingAux mvars bis j b }; match maxMVars? with | none => process () | some maxMVars => if mvars.size < maxMVars then process () else let type := type.instantiateRevRange j mvars.size mvars; pure (mvars, bis, type) | mvars, bis, j, type => let type := type.instantiateRevRange j mvars.size mvars; if reducing? then do newType ← whnf type; if newType.isForall then forallMetaTelescopeReducingAux mvars bis mvars.size newType else pure (mvars, bis, type) else pure (mvars, bis, type) /-- Similar to `forallTelescope`, but creates metavariables instead of free variables. -/ def forallMetaTelescope (e : Expr) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux false none kind #[] #[] 0 e /-- Similar to `forallTelescopeReducing`, but creates metavariables instead of free variables. -/ def forallMetaTelescopeReducing (e : Expr) (maxMVars? : Option Nat := none) (kind := MetavarKind.natural) : MetaM (Array Expr × Array BinderInfo × Expr) := forallMetaTelescopeReducingAux true maxMVars? kind #[] #[] 0 e /-- Similar to `forallMetaTelescopeReducingAux` but for lambda expressions. -/ private partial def lambdaMetaTelescopeAux (maxMVars? : Option Nat) : Array Expr → Array BinderInfo → Nat → Expr → MetaM (Array Expr × Array BinderInfo × Expr) | mvars, bis, j, type => do let finalize : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do { let type := type.instantiateRevRange j mvars.size mvars; pure (mvars, bis, type) }; let process : Unit → MetaM (Array Expr × Array BinderInfo × Expr) := fun _ => do { match type with | Expr.lam n d b c => do let d := d.instantiateRevRange j mvars.size mvars; mvar ← mkFreshExprMVar d; let mvars := mvars.push mvar; let bis := bis.push c.binderInfo; lambdaMetaTelescopeAux mvars bis j b | _ => finalize () }; match maxMVars? with | none => process () | some maxMVars => if mvars.size < maxMVars then process () else finalize () /-- Similar to `forallMetaTelescope` but for lambda expressions. -/ def lambdaMetaTelescope (e : Expr) (maxMVars? : Option Nat := none) : MetaM (Array Expr × Array BinderInfo × Expr) := lambdaMetaTelescopeAux maxMVars? #[] #[] 0 e @[inline] def liftStateMCtx {α} (x : StateM MetavarContext α) : MetaM α := fun _ s => let (a, mctx) := x.run s.mctx; EStateM.Result.ok a { s with mctx := mctx } def instantiateLevelMVars (lvl : Level) : MetaM Level := liftStateMCtx $ MetavarContext.instantiateLevelMVars lvl def assignLevelMVar (mvarId : MVarId) (lvl : Level) : MetaM Unit := modify $ fun s => { s with mctx := MetavarContext.assignLevel s.mctx mvarId lvl } def mkFreshLevelMVarId : MetaM MVarId := do mvarId ← mkFreshId; modify $ fun s => { s with mctx := s.mctx.addLevelMVarDecl mvarId }; pure mvarId def whnfD : Expr → MetaM Expr := fun e => withTransparency TransparencyMode.default $ whnf e /-- Execute `x` using approximate unification: `foApprox`, `ctxApprox` and `quasiPatternApprox`. -/ @[inline] def approxDefEq {α} (x : MetaM α) : MetaM α := adaptReader (fun (ctx : Context) => { ctx with config := { ctx.config with foApprox := true, ctxApprox := true, quasiPatternApprox := true} }) x /-- Similar to `approxDefEq`, but uses all available approximations. We don't use `constApprox` by default at `approxDefEq` because it often produces undesirable solution for monadic code. For example, suppose we have `pure (x > 0)` which has type `?m Prop`. We also have the goal `[HasPure ?m]`. Now, assume the expected type is `IO Bool`. Then, the unification constraint `?m Prop =?= IO Bool` could be solved as `?m := fun _ => IO Bool` using `constApprox`, but this spurious solution would generate a failure when we try to solve `[HasPure (fun _ => IO Bool)]` -/ @[inline] def fullApproxDefEq {α} (x : MetaM α) : MetaM α := adaptReader (fun (ctx : Context) => { ctx with config := { ctx.config with foApprox := true, ctxApprox := true, quasiPatternApprox := true, constApprox := true } }) x @[inline] private def withNewFVar {α} (fvar fvarType : Expr) (k : Expr → MetaM α) : MetaM α := do c? ← isClass fvarType; match c? with | none => k fvar | some c => withNewLocalInstance c fvar $ k fvar def withLocalDecl {α} (n : Name) (type : Expr) (bi : BinderInfo) (k : Expr → MetaM α) : MetaM α := do fvarId ← mkFreshId; ctx ← read; let lctx := ctx.lctx.mkLocalDecl fvarId n type bi; let fvar := mkFVar fvarId; adaptReader (fun (ctx : Context) => { ctx with lctx := lctx }) $ withNewFVar fvar type k def withLocalDeclD {α} (n : Name) (type : Expr) (k : Expr → MetaM α) : MetaM α := withLocalDecl n type BinderInfo.default k def withLetDecl {α} (n : Name) (type : Expr) (val : Expr) (k : Expr → MetaM α) : MetaM α := do fvarId ← mkFreshId; ctx ← read; let lctx := ctx.lctx.mkLetDecl fvarId n type val; let fvar := mkFVar fvarId; adaptReader (fun (ctx : Context) => { ctx with lctx := lctx }) $ withNewFVar fvar type k /-- Save cache and `MetavarContext`, bump the `MetavarContext` depth, execute `x`, and restore saved data. -/ @[inline] def withNewMCtxDepth {α} (x : MetaM α) : MetaM α := do s ← get; let savedMCtx := s.mctx; modify $ fun s => { s with mctx := s.mctx.incDepth }; finally x (modify $ fun s => { s with mctx := savedMCtx }) def withLocalContext {α} (lctx : LocalContext) (localInsts : LocalInstances) (x : MetaM α) : MetaM α := do localInstsCurr ← getLocalInstances; adaptReader (fun (ctx : Context) => { ctx with lctx := lctx, localInstances := localInsts }) $ if localInsts == localInstsCurr then x else resettingSynthInstanceCache x /-- Execute `x` using the given metavariable `LocalContext` and `LocalInstances`. The type class resolution cache is flushed when executing `x` if its `LocalInstances` are different from the current ones. -/ @[inline] def withMVarContext {α} (mvarId : MVarId) (x : MetaM α) : MetaM α := do mvarDecl ← getMVarDecl mvarId; withLocalContext mvarDecl.lctx mvarDecl.localInstances x @[inline] def withMCtx {α} (mctx : MetavarContext) (x : MetaM α) : MetaM α := do mctx' ← getMCtx; modify $ fun s => { s with mctx := mctx }; finally x (modify $ fun s => { s with mctx := mctx' }) /-- Create an auxiliary definition with the given name, type and value. The parameters `type` and `value` may contain free and meta variables. A "closure" is computed, and a term of the form `name.{u_1 ... u_n} t_1 ... t_m` is returned where `u_i`s are universe parameters and metavariables `type` and `value` depend on, and `t_j`s are free and meta variables `type` and `value` depend on. -/ def mkAuxDefinition (name : Name) (type : Expr) (value : Expr) : MetaM Expr := do env ← getEnv; opts ← getOptions; mctx ← getMCtx; lctx ← getLCtx; match Lean.mkAuxDefinition env opts mctx lctx name type value with | Except.error ex => throw $ Exception.kernel ex opts | Except.ok (e, env) => do setEnv env; pure e /-- Similar to `mkAuxDefinition`, but infers the type of `value`. -/ def mkAuxDefinitionFor (name : Name) (value : Expr) : MetaM Expr := do type ← inferType value; let type := type.headBeta; mkAuxDefinition name type value @[init] private def regTraceClasses : IO Unit := do registerTraceClass `Meta; registerTraceClass `Meta.debug def run {α} (env : Environment) (x : MetaM α) (maxRecDepth := 10000) : Except Exception α := match x { maxRecDepth := maxRecDepth, currRecDepth := 0 } { env := env } with | EStateM.Result.ok a _ => Except.ok a | EStateM.Result.error ex _ => Except.error ex end Meta export Meta (MetaM) end Lean open Lean open Lean.Meta /-- Helper function for running `MetaM` methods in attributes -/ @[inline] def IO.runMeta {α} (x : MetaM α) (env : Environment) (cfg : Config := {}) : IO (α × Environment) := match (x { config := cfg, currRecDepth := 0, maxRecDepth := defaultMaxRecDepth }).run { env := env } with | EStateM.Result.ok a s => pure (a, s.env) | EStateM.Result.error ex _ => throw (IO.userError (toString ex))
3080cd3feffa685046948cb3c3fdfce63a3c580e
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/sums/associator.lean
015315a9954e7bb272434f6b064a5eaf6547f376
[ "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
3,161
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.sums.basic /-# The associator functor `((C ⊕ D) ⊕ E) ⥤ (C ⊕ (D ⊕ E))` and its inverse form an equivalence. -/ universes v u open category_theory open sum namespace category_theory.sum variables (C : Type u) [category.{v} C] (D : Type u) [category.{v} D] (E : Type u) [category.{v} E] def associator : ((C ⊕ D) ⊕ E) ⥤ (C ⊕ (D ⊕ E)) := { obj := λ X, match X with | inl (inl X) := inl X | inl (inr X) := inr (inl X) | inr X := inr (inr X) end, map := λ X Y f, match X, Y, f with | inl (inl X), inl (inl Y), f := f | inl (inr X), inl (inr Y), f := f | inr X, inr Y, f := f end } @[simp] lemma associator_obj_inl_inl (X) : (associator C D E).obj (inl (inl X)) = inl X := rfl @[simp] lemma associator_obj_inl_inr (X) : (associator C D E).obj (inl (inr X)) = inr (inl X) := rfl @[simp] lemma associator_obj_inr (X) : (associator C D E).obj (inr X) = inr (inr X) := rfl @[simp] lemma associator_map_inl_inl {X Y : C} (f : inl (inl X) ⟶ inl (inl Y)) : (associator C D E).map f = f := rfl @[simp] lemma associator_map_inl_inr {X Y : D} (f : inl (inr X) ⟶ inl (inr Y)) : (associator C D E).map f = f := rfl @[simp] lemma associator_map_inr {X Y : E} (f : inr X ⟶ inr Y) : (associator C D E).map f = f := rfl def inverse_associator : (C ⊕ (D ⊕ E)) ⥤ ((C ⊕ D) ⊕ E) := { obj := λ X, match X with | inl X := inl (inl X) | inr (inl X) := inl (inr X) | inr (inr X) := inr X end, map := λ X Y f, match X, Y, f with | inl X, inl Y, f := f | inr (inl X), inr (inl Y), f := f | inr (inr X), inr (inr Y), f := f end } @[simp] lemma inverse_associator_obj_inl (X) : (inverse_associator C D E).obj (inl X) = inl (inl X) := rfl @[simp] lemma inverse_associator_obj_inr_inl (X) : (inverse_associator C D E).obj (inr (inl X)) = inl (inr X) := rfl @[simp] lemma inverse_associator_obj_inr_inr (X) : (inverse_associator C D E).obj (inr (inr X)) = inr X := rfl @[simp] lemma inverse_associator_map_inl {X Y : C} (f : inl X ⟶ inl Y) : (inverse_associator C D E).map f = f := rfl @[simp] lemma inverse_associator_map_inr_inl {X Y : D} (f : inr (inl X) ⟶ inr (inl Y)) : (inverse_associator C D E).map f = f := rfl @[simp] lemma inverse_associator_map_inr_inr {X Y : E} (f : inr (inr X) ⟶ inr (inr Y)) : (inverse_associator C D E).map f = f := rfl def associativity : (C ⊕ D) ⊕ E ≌ C ⊕ (D ⊕ E) := equivalence.mk (associator C D E) (inverse_associator C D E) (nat_iso.of_components (λ X, eq_to_iso (by tidy)) (by tidy)) (nat_iso.of_components (λ X, eq_to_iso (by tidy)) (by tidy)) instance associator_is_equivalence : is_equivalence (associator C D E) := (by apply_instance : is_equivalence (associativity C D E).functor) instance inverse_associator_is_equivalence : is_equivalence (inverse_associator C D E) := (by apply_instance : is_equivalence (associativity C D E).inverse) -- TODO unitors? -- TODO pentagon natural transformation? ...satisfying? end category_theory.sum
e2e1c98fd6e9c62d7bb1946043987fda3d270d0f
ec5e5a9dbe7f60fa5784d15211d8bf24ada0825c
/src/LLVMFFI.lean
c1cc0219c263e6b543488aca6d9bef2c05b01334
[]
no_license
pnwamk/lean-llvm
fcd9a828e52e80eb197f7d9032b3846f2e09ef74
ebc3bca9a57a6aef29529d46394f560398fb5c9c
refs/heads/master
1,668,418,078,706
1,593,548,643,000
1,593,548,643,000
258,617,753
0
0
null
1,587,760,298,000
1,587,760,298,000
null
UTF-8
Lean
false
false
9,855
lean
/- Copyright (c) 2019 Galois, Inc. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Dockins, Joe Hendrix Lean declarations to link against LLVM C++ declarations. -/ import Init.Core import LeanLLVM.LLVMCodes namespace LLVM namespace FFI constant Context := Unit constant Type_ := Unit constant Value := Unit def Function := Value def BasicBlock := Value def Instruction := Value def Constant := Value def GlobalVar := Value constant Module := Unit constant MemoryBuffer := Unit def Triple := Unit instance Triple.inhabited : Inhabited Triple := inferInstanceAs (Inhabited Unit) ------------------------------------------------------------------------ -- Context @[extern 1 "lean_llvm_newContext"] def newContext : IO Context := arbitrary _ ------------------------------------------------------------------------ -- Types @[extern 2 "lean_llvm_getTypeTag"] def getTypeTag : @& Type_ -> IO Code.TypeID := arbitrary _ @[extern 2 "lean_llvm_getTypeName"] def getTypeName : @& Type_ -> IO (Option String) := arbitrary _ @[extern 2 "lean_llvm_typeIsOpaque"] def typeIsOpaque : @& Type_ -> IO Bool := arbitrary _ @[extern 2 "lean_llvm_getIntegerTypeWidth"] def getIntegerTypeWidth : @& Type_ -> IO Nat := arbitrary _ @[extern 2 "lean_llvm_getPointerElementType"] def getPointerElementType : @& Type_ -> IO (Option Type_) := arbitrary _ @[extern 2 "lean_llvm_getSequentialTypeData"] def getSequentialTypeData : @&Type_ -> IO (Option (Nat × Type_)) := arbitrary _ @[extern 2 "lean_llvm_getStructTypeData"] def getStructTypeData : @&Type_ -> IO (Option (Bool × Array Type_)) := arbitrary _ @[extern 2 "lean_llvm_getFunctionTypeData"] def getFunctionTypeData : @&Type_ -> IO (Option (Type_ × (Array Type_ × Bool))) := arbitrary _ @[extern 3 "lean_llvm_newPrimitiveType"] def newPrimitiveType : @& Context → @& Code.TypeID → IO Type_ := arbitrary _ @[extern 3 "lean_llvm_newIntegerType"] def newIntegerType : @& Context → @& Nat → IO Type_ := arbitrary _ @[extern 3 "lean_llvm_newArrayType"] def newArrayType : @& Nat → @& Type_ → IO Type_ := arbitrary _ @[extern 3 "lean_llvm_newVectorType"] def newVectorType : @& Nat → @& Type_ → IO Type_ := arbitrary _ @[extern 2 "lean_llvm_newPointerType"] def newPointerType : @& Type_ → IO Type_ := arbitrary _ @[extern 4 "lean_llvm_newFunctionType"] def newFunctionType : @& Type_ → @& Array Type_ → Bool → IO Type_ := arbitrary _ @[extern 3 "lean_llvm_newLiteralStructType"] def newLiteralStructType : @& Bool → @& Array Type_ → IO Type_ := arbitrary _ @[extern 2 "lean_llvm_newOpaqueStructType"] def newOpaqueStructType : @& Context → @& String → IO Type_ := arbitrary _ @[extern 4 "lean_llvm_setStructTypeBody"] def setStructTypeBody : @& Type_ → @& Bool → @& Array Type_ → IO Unit := arbitrary _ ------------------------------------------------------------------------ -- Value @[extern 2 "lean_llvm_getValueType"] def getValueType : @& Value -> IO Type_ := arbitrary _ inductive ValueView | unknown | constantView (c:Constant) | argument (a:Nat) | block (b:BasicBlock) | instruction (i:Instruction) @[extern 2 "lean_llvm_decomposeValue"] def decomposeValue : @& Value -> IO ValueView := arbitrary _ def functionToValue (f:Function) : Value := f def basicBlockToValue (bb:BasicBlock) : Value := bb def instructionToValue (i:Instruction) : Value := i def constantToValue (c:Constant) : Value := c ------------------------------------------------------------------------ -- Constant @[extern 2 "lean_llvm_getConstantName"] def getConstantName : @& Constant -> IO (Option String) := arbitrary _ @[extern 2 "lean_llvm_getConstantTag"] def getConstantTag : @&Constant -> IO Code.Const := arbitrary _ -- return bitwidth and value @[extern 2 "lean_llvm_getConstIntData"] def getConstIntData : @& Constant -> IO (Option (Nat × Nat)) := arbitrary _ @[extern 2 "lean_llvm_getConstExprData"] def getConstExprData : @& Constant -> IO (Option (Code.Instr × Array Constant)) := arbitrary _ @[extern 2 "lean_llvm_getConstArrayData"] def getConstArrayData : @& Constant -> IO (Option (Type_ × Array Constant)) := arbitrary _ ------------------------------------------------------------------------ -- Instruction @[extern 2 "lean_llvm_instructionLt"] def instructionLt : @& Instruction -> @&Instruction -> Bool := arbitrary _ @[extern 2 "lean_llvm_getInstructionName"] def getInstructionName : @& Instruction -> IO (Option String) := arbitrary _ @[extern 2 "lean_llvm_getInstructionType"] def getInstructionType : @& Instruction -> IO Type_ := arbitrary _ @[extern 2 "lean_llvm_getInstructionOpcode"] def getInstructionOpcode : @& Instruction -> IO Code.Instr := arbitrary _ @[extern 2 "lean_llvm_getInstructionReturnValue"] def getInstructionReturnValue : @& Instruction -> IO (Option Value) := arbitrary _ @[extern 2 "lean_llvm_getBinaryOperatorValues"] def getBinaryOperatorValues : @& Instruction -> IO (Option (Value × Value)) := arbitrary _ @[extern 2 "lean_llvm_hasNoSignedWrap"] def hasNoSignedWrap : @& Instruction -> IO Bool := arbitrary _ @[extern 2 "lean_llvm_hasNoUnsignedWrap"] def hasNoUnsignedWrap : @& Instruction -> IO Bool := arbitrary _ @[extern 2 "lean_llvm_isExact"] def isExact : @&Instruction -> IO Bool := arbitrary _ @[extern 2 "lean_llvm_getICmpInstData"] def getICmpInstData : @& Instruction -> IO (Option (Code.ICmp × (Value × Value))) := arbitrary _ @[extern 2 "lean_llvm_getSelectInstData"] def getSelectInstData : @& Instruction -> IO (Option (Value × (Value × Value))) := arbitrary _ inductive BranchView | unconditional (b:BasicBlock) | conditional (c:Value) (t f : BasicBlock) @[extern 2 "lean_llvm_getBranchInstData"] def getBranchInstData : @& Instruction -> IO (Option BranchView) := arbitrary _ @[extern 2 "lean_llvm_getPhiData"] def getPhiData : @& Instruction -> IO (Option (Array (Value × BasicBlock))) := arbitrary _ @[extern 2 "lean_llvm_getCastInstData"] def getCastInstData : @& Instruction -> IO (Option (Nat × Value)) := arbitrary _ @[extern 2 "lean_llvm_getAllocaData"] def getAllocaData : @& Instruction -> IO (Option (Type_ × (Option Value × Option Nat))) := arbitrary _ @[extern 2 "lean_llvm_getStoreData"] def getStoreData : @& Instruction -> IO (Option (Value × (Value × Option Nat))) := arbitrary _ @[extern 2 "lean_llvm_getLoadData"] def getLoadData : @& Instruction -> IO (Option (Value × Option Nat)) := arbitrary _ @[extern 2 "lean_llvm_getGEPData"] def getGEPData : @& Instruction -> IO (Option (Bool × (Value × Array Value))) := arbitrary _ @[extern 2 "lean_llvm_getCallInstData"] def getCallInstData : @& Instruction -> IO (Option (Bool × (Type_ × (Value × Array Value)))) := arbitrary _ ------------------------------------------------------------------------ -- Basic block @[extern 2 "lean_llvm_basicBlockLt"] def basicBlockLt : @& BasicBlock -> @& BasicBlock -> Bool := arbitrary _ @[extern 2 "lean_llvm_getBBName"] def getBBName : @& BasicBlock -> IO (Option String) := arbitrary _ @[extern 2 "lean_llvm_getInstructionArray"] def getInstructionArray : @& BasicBlock -> IO (Array Instruction) := arbitrary _ ------------------------------------------------------------------------ -- Function @[extern 3 "lean_llvm_newFunction"] def newFunction : Module → @&Type_ → @&String → IO Function := arbitrary _ @[extern 2 "lean_llvm_getFunctionName"] def getFunctionName : @& Function -> IO String := arbitrary _ @[extern 2 "lean_llvm_getFunctionArgs"] def getFunctionArgs : @& Function -> IO (Array (Option String × Type_)) := arbitrary _ @[extern 2 "lean_llvm_getReturnType"] def getReturnType : @& Function -> IO Type_ := arbitrary _ @[extern 2 "lean_llvm_getBasicBlockArray"] def getBasicBlockArray : @& Function -> IO (Array BasicBlock) := arbitrary _ ------------------------------------------------------------------------ -- GlobalVar @[extern 2 "lean_llvm_getGlobalVarData"] def getGlobalVarData : @& GlobalVar → IO (Option (String × (Option Value × Nat))) := arbitrary _ ------------------------------------------------------------------------ -- Module @[extern 3 "lean_llvm_parseBitcodeFile"] def parseBitcodeFile : @&MemoryBuffer → Context → IO Module := arbitrary _ @[extern 3 "lean_llvm_parseAssembly"] def parseAssembly : @&MemoryBuffer → Context → IO Module := arbitrary _ @[extern 2 "lean_llvm_printModule"] def printModule : @& Module -> IO Unit := arbitrary _ @[extern 3 "lean_llvm_newModule"] def newModule : Context → @&String → IO Module := arbitrary _ @[extern 2 "lean_llvm_getModuleIdentifier"] def getModuleIdentifier : @&Module → IO String := arbitrary _ @[extern 3 "lean_llvm_setModuleIdentifier"] def setModuleIdentifier : @&Module → @&String → IO Unit := arbitrary _ @[extern 2 "lean_llvm_getModuleDataLayoutStr"] def getModuleDataLayoutStr : @& Module → IO String := arbitrary _ @[extern 2 "lean_llvm_getFunctionArray"] def getFunctionArray : @& Module -> IO (Array Function) := arbitrary _ @[extern 2 "lean_llvm_getGlobalArray"] def getGlobalArray : @& Module -> IO (Array GlobalVar) := arbitrary _ ------------------------------------------------------------------------ -- Other /-- Initialize machine code functions for the current architecture. -/ @[extern 1 "lean_llvm_initNativeFns"] def initNativeFns : IO Unit := arbitrary _ @[extern 2 "lean_llvm_newMemoryBufferFromFile"] def newMemoryBufferFromFile : String → IO MemoryBuffer := arbitrary _ ------------------------------------------------------------------------ -- Triple @[extern "lean_llvm_getProcessTriple"] def processTriple : Unit → String := arbitrary _ /-- This constructs a compiler session and frees it when done. -/ @[extern "lean_llvm_newTriple"] constant newTriple : String → Triple := arbitrary _ end FFI end LLVM
8ed9503f5099032202190266c894b0699dd5b3d3
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Elab/Tactic/Simp.lean
86e1c56c88eb66cea3a593cf1f44762e6c5f412e
[ "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
14,728
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Tactic.Simp import Lean.Meta.Tactic.Replace import Lean.Elab.BuiltinNotation import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.ElabTerm import Lean.Elab.Tactic.Location import Lean.Elab.Tactic.Config namespace Lean.Elab.Tactic open Meta open TSyntax.Compat open Simp (UsedSimps) declare_config_elab elabSimpConfigCore Meta.Simp.Config declare_config_elab elabSimpConfigCtxCore Meta.Simp.ConfigCtx declare_config_elab elabDSimpConfigCore Meta.DSimp.Config inductive SimpKind where | simp | simpAll | dsimp deriving Inhabited, BEq /-- Implement a `simp` discharge function using the given tactic syntax code. Recall that `simp` dischargers are in `SimpM` which does not have access to `Term.State`. We need access to `Term.State` to store messages and update the info tree. Thus, we create an `IO.ref` to track these changes at `Term.State` when we execute `tacticCode`. We must set this reference with the current `Term.State` before we execute `simp` using the generated `Simp.Discharge`. -/ def tacticToDischarge (tacticCode : Syntax) : TacticM (IO.Ref Term.State × Simp.Discharge) := do let tacticCode ← `(tactic| try ($tacticCode:tacticSeq)) let ref ← IO.mkRef (← getThe Term.State) let ctx ← readThe Term.Context let disch : Simp.Discharge := fun e => do let mvar ← mkFreshExprSyntheticOpaqueMVar e `simp.discharger let s ← ref.get let runTac? : TermElabM (Option Expr) := try /- We must only save messages and info tree changes. Recall that `simp` uses temporary metavariables (`withNewMCtxDepth`). So, we must not save references to them at `Term.State`. -/ withoutModifyingStateWithInfoAndMessages do Term.withSynthesize (mayPostpone := false) <| Term.runTactic mvar.mvarId! tacticCode let result ← instantiateMVars mvar if result.hasExprMVar then return none else return some result catch _ => return none let (result?, s) ← liftM (m := MetaM) <| Term.TermElabM.run runTac? ctx s ref.set s return result? return (ref, disch) inductive Simp.DischargeWrapper where | default | custom (ref : IO.Ref Term.State) (discharge : Simp.Discharge) def Simp.DischargeWrapper.with (w : Simp.DischargeWrapper) (x : Option Simp.Discharge → TacticM α) : TacticM α := do match w with | default => x none | custom ref d => ref.set (← getThe Term.State) try x d finally set (← ref.get) private def mkDischargeWrapper (optDischargeSyntax : Syntax) : TacticM Simp.DischargeWrapper := do if optDischargeSyntax.isNone then return Simp.DischargeWrapper.default else let (ref, d) ← tacticToDischarge optDischargeSyntax[0][3] return Simp.DischargeWrapper.custom ref d /- `optConfig` is of the form `("(" "config" ":=" term ")")?` -/ def elabSimpConfig (optConfig : Syntax) (kind : SimpKind) : TermElabM Meta.Simp.Config := do match kind with | .simp => elabSimpConfigCore optConfig | .simpAll => return (← elabSimpConfigCtxCore optConfig).toConfig | .dsimp => return { (← elabDSimpConfigCore optConfig) with } private def addDeclToUnfoldOrTheorem (thms : Meta.SimpTheorems) (id : Origin) (e : Expr) (post : Bool) (inv : Bool) (kind : SimpKind) : MetaM Meta.SimpTheorems := do if e.isConst then let declName := e.constName! let info ← getConstInfo declName if (← isProp info.type) then thms.addConst declName (post := post) (inv := inv) else if inv then throwError "invalid '←' modifier, '{declName}' is a declaration name to be unfolded" if kind == .dsimp then return thms.addDeclToUnfoldCore declName else thms.addDeclToUnfold declName else thms.add id #[] e (post := post) (inv := inv) private def addSimpTheorem (thms : Meta.SimpTheorems) (id : Origin) (stx : Syntax) (post : Bool) (inv : Bool) : TermElabM Meta.SimpTheorems := do let (levelParams, proof) ← Term.withoutModifyingElabMetaStateWithInfo <| withRef stx <| Term.withoutErrToSorry do let e ← Term.elabTerm stx none Term.synthesizeSyntheticMVars (mayPostpone := false) (ignoreStuckTC := true) let e ← instantiateMVars e let e := e.eta if e.hasMVar then let r ← abstractMVars e return (r.paramNames, r.expr) else return (#[], e) thms.add id levelParams proof (post := post) (inv := inv) structure ElabSimpArgsResult where ctx : Simp.Context starArg : Bool := false inductive ResolveSimpIdResult where | none | expr (e : Expr) | ext (ext : SimpExtension) /-- Elaborate extra simp theorems provided to `simp`. `stx` is of the form `"[" simpTheorem,* "]"` If `eraseLocal == true`, then we consider local declarations when resolving names for erased theorems (`- id`), this option only makes sense for `simp_all` or `*` is used. -/ def elabSimpArgs (stx : Syntax) (ctx : Simp.Context) (eraseLocal : Bool) (kind : SimpKind) : TacticM ElabSimpArgsResult := do if stx.isNone then return { ctx } else /- syntax simpPre := "↓" syntax simpPost := "↑" syntax simpLemma := (simpPre <|> simpPost)? term syntax simpErase := "-" ident -/ withMainContext do let mut thmsArray := ctx.simpTheorems let mut thms := thmsArray[0]! let mut starArg := false for arg in stx[1].getSepArgs do if arg.getKind == ``Lean.Parser.Tactic.simpErase then let fvar ← if eraseLocal || starArg then Term.isLocalIdent? arg[1] else pure none if let some fvar := fvar then -- We use `eraseCore` because the simp theorem for the hypothesis was not added yet thms := thms.eraseCore (.fvar fvar.fvarId!) else let declName ← resolveGlobalConstNoOverloadWithInfo arg[1] if ctx.config.autoUnfold then thms := thms.eraseCore (.decl declName) else thms ← thms.erase (.decl declName) else if arg.getKind == ``Lean.Parser.Tactic.simpLemma then let post := if arg[0].isNone then true else arg[0][0].getKind == ``Parser.Tactic.simpPost let inv := !arg[1].isNone let term := arg[2] match (← resolveSimpIdTheorem? term) with | .expr e => let name ← mkFreshId thms ← addDeclToUnfoldOrTheorem thms (.stx name arg) e post inv kind | .ext ext => thmsArray := thmsArray.push (← ext.getTheorems) | .none => let name ← mkFreshId thms ← addSimpTheorem thms (.stx name arg) term post inv else if arg.getKind == ``Lean.Parser.Tactic.simpStar then starArg := true else throwUnsupportedSyntax return { ctx := { ctx with simpTheorems := thmsArray.set! 0 thms }, starArg } where resolveSimpIdTheorem? (simpArgTerm : Term) : TacticM ResolveSimpIdResult := do let resolveExt (n : Name) : TacticM ResolveSimpIdResult := do if let some ext ← getSimpExtension? n then return .ext ext else return .none match simpArgTerm with | `($id:ident) => try if let some e ← Term.resolveId? simpArgTerm (withInfo := true) then return .expr e else resolveExt id.getId.eraseMacroScopes catch _ => resolveExt id.getId.eraseMacroScopes | _ => if let some e ← Term.elabCDotFunctionAlias? simpArgTerm then return .expr e else return .none @[inline] def simpOnlyBuiltins : List Name := [``eq_self] structure MkSimpContextResult where ctx : Simp.Context dischargeWrapper : Simp.DischargeWrapper /-- Create the `Simp.Context` for the `simp`, `dsimp`, and `simp_all` tactics. If `kind != SimpKind.simp`, the `discharge` option must be `none` TODO: generate error message if non `rfl` theorems are provided as arguments to `dsimp`. -/ def mkSimpContext (stx : Syntax) (eraseLocal : Bool) (kind := SimpKind.simp) (ignoreStarArg : Bool := false) : TacticM MkSimpContextResult := do if !stx[2].isNone then if kind == SimpKind.simpAll then throwError "'simp_all' tactic does not support 'discharger' option" if kind == SimpKind.dsimp then throwError "'dsimp' tactic does not support 'discharger' option" let dischargeWrapper ← mkDischargeWrapper stx[2] let simpOnly := !stx[3].isNone let simpTheorems ← if simpOnly then simpOnlyBuiltins.foldlM (·.addConst ·) ({} : SimpTheorems) else getSimpTheorems let congrTheorems ← getSimpCongrTheorems let r ← elabSimpArgs stx[4] (eraseLocal := eraseLocal) (kind := kind) { config := (← elabSimpConfig stx[1] (kind := kind)) simpTheorems := #[simpTheorems], congrTheorems } if !r.starArg || ignoreStarArg then return { r with dischargeWrapper } else let ctx := r.ctx let mut simpTheorems := ctx.simpTheorems let hs ← getPropHyps for h in hs do unless simpTheorems.isErased (.fvar h) do simpTheorems ← simpTheorems.addTheorem (.fvar h) (← h.getDecl).toExpr let ctx := { ctx with simpTheorems } return { ctx, dischargeWrapper } register_builtin_option tactic.simp.trace : Bool := { defValue := false descr := "When tracing is enabled, calls to `simp` or `dsimp` will print an equivalent `simp only` call." } def traceSimpCall (stx : Syntax) (usedSimps : UsedSimps) : MetaM Unit := do let mut stx := stx if stx[3].isNone then stx := stx.setArg 3 (mkNullNode #[mkAtom "only"]) let mut args := #[] let mut localsOrStar := some #[] let lctx ← getLCtx let env ← getEnv for (thm, _) in usedSimps.toArray.qsort (·.2 < ·.2) do match thm with | .decl declName => -- global definitions in the environment if env.contains declName && !simpOnlyBuiltins.contains declName then args := args.push (← `(Parser.Tactic.simpLemma| $(mkIdent (← unresolveNameGlobal declName)):ident)) | .fvar fvarId => -- local hypotheses in the context if let some ldecl := lctx.find? fvarId then localsOrStar := localsOrStar.bind fun locals => if !ldecl.userName.isInaccessibleUserName && (lctx.findFromUserName? ldecl.userName).get!.fvarId == ldecl.fvarId then some (locals.push ldecl.userName) else none -- Note: the `if let` can fail for `simp (config := {contextual := true})` when -- rewriting with a variable that was introduced in a scope. In that case we just ignore. | .stx _ thmStx => -- simp theorems provided in the local invocation args := args.push thmStx | .other _ => -- Ignore "special" simp lemmas such as constructed by `simp_all`. pure () -- We can't display them anyway. if let some locals := localsOrStar then args := args ++ (← locals.mapM fun id => `(Parser.Tactic.simpLemma| $(mkIdent id):ident)) else args := args.push (← `(Parser.Tactic.simpStar| *)) let argsStx := if args.isEmpty then #[] else #[mkAtom "[", (mkAtom ",").mkSep args, mkAtom "]"] stx := stx.setArg 4 (mkNullNode argsStx) logInfoAt stx[0] m!"Try this: {stx}" /-- `simpLocation ctx discharge? varIdToLemmaId loc` runs the simplifier at locations specified by `loc`, using the simp theorems collected in `ctx` optionally running a discharger specified in `discharge?` on generated subgoals. Its primary use is as the implementation of the `simp [...] at ...` and `simp only [...] at ...` syntaxes, but can also be used by other tactics when a `Syntax` is not available. For many tactics other than the simplifier, one should use the `withLocation` tactic combinator when working with a `location`. -/ def simpLocation (ctx : Simp.Context) (discharge? : Option Simp.Discharge := none) (loc : Location) : TacticM UsedSimps := do match loc with | Location.targets hyps simplifyTarget => withMainContext do let fvarIds ← getFVarIds hyps go fvarIds simplifyTarget | Location.wildcard => withMainContext do go (← (← getMainGoal).getNondepPropHyps) (simplifyTarget := true) where go (fvarIdsToSimp : Array FVarId) (simplifyTarget : Bool) : TacticM UsedSimps := do let mvarId ← getMainGoal let (result?, usedSimps) ← simpGoal mvarId ctx (simplifyTarget := simplifyTarget) (discharge? := discharge?) (fvarIdsToSimp := fvarIdsToSimp) match result? with | none => replaceMainGoal [] | some (_, mvarId) => replaceMainGoal [mvarId] return usedSimps /- "simp " (config)? (discharger)? ("only ")? ("[" simpLemma,* "]")? (location)? -/ @[builtinTactic Lean.Parser.Tactic.simp] def evalSimp : Tactic := fun stx => do let { ctx, dischargeWrapper } ← withMainContext <| mkSimpContext stx (eraseLocal := false) let usedSimps ← dischargeWrapper.with fun discharge? => simpLocation ctx discharge? (expandOptLocation stx[5]) if tactic.simp.trace.get (← getOptions) then traceSimpCall stx usedSimps @[builtinTactic Lean.Parser.Tactic.simpAll] def evalSimpAll : Tactic := fun stx => do let { ctx, .. } ← mkSimpContext stx (eraseLocal := true) (kind := .simpAll) (ignoreStarArg := true) let (result?, usedSimps) ← simpAll (← getMainGoal) ctx match result? with | none => replaceMainGoal [] | some mvarId => replaceMainGoal [mvarId] if tactic.simp.trace.get (← getOptions) then traceSimpCall stx usedSimps def dsimpLocation (ctx : Simp.Context) (loc : Location) : TacticM Unit := do match loc with | Location.targets hyps simplifyTarget => withMainContext do let fvarIds ← getFVarIds hyps go fvarIds simplifyTarget | Location.wildcard => withMainContext do go (← (← getMainGoal).getNondepPropHyps) (simplifyTarget := true) where go (fvarIdsToSimp : Array FVarId) (simplifyTarget : Bool) : TacticM Unit := do let mvarId ← getMainGoal let (result?, usedSimps) ← dsimpGoal mvarId ctx (simplifyTarget := simplifyTarget) (fvarIdsToSimp := fvarIdsToSimp) match result? with | none => replaceMainGoal [] | some mvarId => replaceMainGoal [mvarId] if tactic.simp.trace.get (← getOptions) then traceSimpCall (← getRef) usedSimps @[builtinTactic Lean.Parser.Tactic.dsimp] def evalDSimp : Tactic := fun stx => do let { ctx, .. } ← withMainContext <| mkSimpContext stx (eraseLocal := false) (kind := .dsimp) dsimpLocation ctx (expandOptLocation stx[5]) end Lean.Elab.Tactic
738f1fbe80506882e00cd805062c985b15ac014a
968e2f50b755d3048175f176376eff7139e9df70
/examples/prop_logic_theory/unnamed_176.lean
5d2332938b607eae0eb47732b3e74bcb168a761a
[]
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
39
lean
p q r : Prop, h : (p ∧ q) ∧ r ⊢ q
fb2e60d37e4f27fe490a39fb5a68a16f06a6f593
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/algebra/category/nat_trans.hlean
8af5e8de4de01ff5e094e90d423488302ef14d13
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
7,835
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Floris van Doorn, Jakob von Raumer -/ import .functor.basic open eq category functor is_trunc equiv sigma.ops sigma is_equiv function pi funext iso structure nat_trans {C : Precategory} {D : Precategory} (F G : C ⇒ D) : Type := (natural_map : Π (a : C), hom (F a) (G a)) (naturality : Π {a b : C} (f : hom a b), G f ∘ natural_map a = natural_map b ∘ F f) namespace nat_trans infixl ` ⟹ `:25 := nat_trans -- \==> variables {B C D E : Precategory} {F G H I : C ⇒ D} {F' G' : D ⇒ E} {F'' G'' : E ⇒ B} {J : C ⇒ C} attribute natural_map [coercion] protected definition compose [constructor] (η : G ⟹ H) (θ : F ⟹ G) : F ⟹ H := nat_trans.mk (λ a, η a ∘ θ a) (λ a b f, abstract calc H f ∘ (η a ∘ θ a) = (H f ∘ η a) ∘ θ a : by rewrite assoc ... = (η b ∘ G f) ∘ θ a : by rewrite naturality ... = η b ∘ (G f ∘ θ a) : by rewrite assoc ... = η b ∘ (θ b ∘ F f) : by rewrite naturality ... = (η b ∘ θ b) ∘ F f : by rewrite assoc end) infixr ` ∘n `:60 := nat_trans.compose definition compose_def (η : G ⟹ H) (θ : F ⟹ G) (c : C) : (η ∘n θ) c = η c ∘ θ c := idp protected definition id [reducible] [constructor] {F : C ⇒ D} : nat_trans F F := mk (λa, id) (λa b f, !id_right ⬝ !id_left⁻¹) protected definition ID [reducible] [constructor] (F : C ⇒ D) : nat_trans F F := (@nat_trans.id C D F) notation 1 := nat_trans.id definition constant_nat_trans [constructor] (C : Precategory) {D : Precategory} {d d' : D} (g : d ⟶ d') : constant_functor C d ⟹ constant_functor C d' := mk (λc, g) (λc c' f, !id_comp_eq_comp_id) open iso definition naturality_iso_left (η : F ⟹ G) {a b : C} (f : a ≅ b) : η a = (G f)⁻¹ ∘ η b ∘ F f := by apply eq_inverse_comp_of_comp_eq; apply naturality definition naturality_iso_right (η : F ⟹ G) {a b : C} (f : a ≅ b) : η b = G f ∘ η a ∘ (F f)⁻¹ := by refine _⁻¹ ⬝ !assoc⁻¹; apply comp_inverse_eq_of_eq_comp; apply naturality definition nat_trans_mk_eq {η₁ η₂ : Π (a : C), hom (F a) (G a)} (nat₁ : Π (a b : C) (f : hom a b), G f ∘ η₁ a = η₁ b ∘ F f) (nat₂ : Π (a b : C) (f : hom a b), G f ∘ η₂ a = η₂ b ∘ F f) (p : η₁ ~ η₂) : nat_trans.mk η₁ nat₁ = nat_trans.mk η₂ nat₂ := apd011 nat_trans.mk (eq_of_homotopy p) !is_prop.elimo definition nat_trans_eq {η₁ η₂ : F ⟹ G} : natural_map η₁ ~ natural_map η₂ → η₁ = η₂ := by induction η₁; induction η₂; apply nat_trans_mk_eq protected definition assoc (η₃ : H ⟹ I) (η₂ : G ⟹ H) (η₁ : F ⟹ G) : η₃ ∘n (η₂ ∘n η₁) = (η₃ ∘n η₂) ∘n η₁ := nat_trans_eq (λa, !assoc) protected definition id_left (η : F ⟹ G) : 1 ∘n η = η := nat_trans_eq (λa, !id_left) protected definition id_right (η : F ⟹ G) : η ∘n 1 = η := nat_trans_eq (λa, !id_right) protected definition sigma_char (F G : C ⇒ D) : (Σ (η : Π (a : C), hom (F a) (G a)), Π (a b : C) (f : hom a b), G f ∘ η a = η b ∘ F f) ≃ (F ⟹ G) := begin fapply equiv.mk, -- TODO(Leo): investigate why we need to use rexact in the following line {intro S, apply nat_trans.mk, rexact (S.2)}, fapply adjointify, intro H, fapply sigma.mk, intro a, exact (H a), intro a b f, exact (naturality H f), intro η, apply nat_trans_eq, intro a, apply idp, intro S, fapply sigma_eq, { apply eq_of_homotopy, intro a, apply idp}, { apply is_prop.elimo} end definition is_set_nat_trans [instance] : is_set (F ⟹ G) := is_trunc_equiv_closed _ !nat_trans.sigma_char _ definition change_natural_map [constructor] (η : F ⟹ G) (f : Π (a : C), F a ⟶ G a) (p : Πa, η a = f a) : F ⟹ G := nat_trans.mk f (λa b g, p a ▸ p b ▸ naturality η g) definition nat_trans_functor_compose [constructor] (η : G ⟹ H) (F : E ⇒ C) : G ∘f F ⟹ H ∘f F := nat_trans.mk (λ a, η (F a)) (λ a b f, naturality η (F f)) definition functor_nat_trans_compose [constructor] (F : D ⇒ E) (η : G ⟹ H) : F ∘f G ⟹ F ∘f H := nat_trans.mk (λ a, F (η a)) (λ a b f, calc F (H f) ∘ F (η a) = F (H f ∘ η a) : by rewrite respect_comp ... = F (η b ∘ G f) : by rewrite (naturality η f) ... = F (η b) ∘ F (G f) : by rewrite respect_comp) definition nat_trans_id_functor_compose [constructor] (η : J ⟹ 1) (F : E ⇒ C) : J ∘f F ⟹ F := nat_trans.mk (λ a, η (F a)) (λ a b f, naturality η (F f)) definition id_nat_trans_functor_compose [constructor] (η : 1 ⟹ J) (F : E ⇒ C) : F ⟹ J ∘f F := nat_trans.mk (λ a, η (F a)) (λ a b f, naturality η (F f)) definition functor_nat_trans_id_compose [constructor] (F : C ⇒ D) (η : J ⟹ 1) : F ∘f J ⟹ F := nat_trans.mk (λ a, F (η a)) (λ a b f, calc F f ∘ F (η a) = F (f ∘ η a) : by rewrite respect_comp ... = F (η b ∘ J f) : by rewrite (naturality η f) ... = F (η b) ∘ F (J f) : by rewrite respect_comp) definition functor_id_nat_trans_compose [constructor] (F : C ⇒ D) (η : 1 ⟹ J) : F ⟹ F ∘f J := nat_trans.mk (λ a, F (η a)) (λ a b f, calc F (J f) ∘ F (η a) = F (J f ∘ η a) : by rewrite respect_comp ... = F (η b ∘ f) : by rewrite (naturality η f) ... = F (η b) ∘ F f : by rewrite respect_comp) infixr ` ∘nf ` :62 := nat_trans_functor_compose infixr ` ∘fn ` :62 := functor_nat_trans_compose infixr ` ∘n1f `:62 := nat_trans_id_functor_compose infixr ` ∘1nf `:62 := id_nat_trans_functor_compose infixr ` ∘f1n `:62 := functor_id_nat_trans_compose infixr ` ∘fn1 `:62 := functor_nat_trans_id_compose definition nf_fn_eq_fn_nf_pt (η : F ⟹ G) (θ : F' ⟹ G') (c : C) : (θ (G c)) ∘ (F' (η c)) = (G' (η c)) ∘ (θ (F c)) := (naturality θ (η c))⁻¹ variable (F') definition nf_fn_eq_fn_nf_pt' (η : F ⟹ G) (θ : F'' ⟹ G'') (c : C) : (θ (F' (G c))) ∘ (F'' (F' (η c))) = (G'' (F' (η c))) ∘ (θ (F' (F c))) := (naturality θ (F' (η c)))⁻¹ variable {F'} definition nf_fn_eq_fn_nf (η : F ⟹ G) (θ : F' ⟹ G') : (θ ∘nf G) ∘n (F' ∘fn η) = (G' ∘fn η) ∘n (θ ∘nf F) := nat_trans_eq (λ c, nf_fn_eq_fn_nf_pt η θ c) definition fn_n_distrib (F' : D ⇒ E) (η : G ⟹ H) (θ : F ⟹ G) : F' ∘fn (η ∘n θ) = (F' ∘fn η) ∘n (F' ∘fn θ) := nat_trans_eq (λc, by apply respect_comp) definition n_nf_distrib (η : G ⟹ H) (θ : F ⟹ G) (F' : B ⇒ C) : (η ∘n θ) ∘nf F' = (η ∘nf F') ∘n (θ ∘nf F') := nat_trans_eq (λc, idp) definition fn_id (F' : D ⇒ E) : F' ∘fn nat_trans.ID F = 1 := nat_trans_eq (λc, by apply respect_id) definition id_nf (F' : B ⇒ C) : nat_trans.ID F ∘nf F' = 1 := nat_trans_eq (λc, idp) definition id_fn (η : G ⟹ H) (c : C) : (1 ∘fn η) c = η c := idp definition nf_id (η : G ⟹ H) (c : C) : (η ∘nf 1) c = η c := idp definition nat_trans_of_eq [reducible] [constructor] (p : F = G) : F ⟹ G := nat_trans.mk (λc, hom_of_eq (ap010 to_fun_ob p c)) (λa b f, eq.rec_on p (!id_right ⬝ !id_left⁻¹)) definition compose_rev [unfold_full] (θ : F ⟹ G) (η : G ⟹ H) : F ⟹ H := η ∘n θ end nat_trans attribute nat_trans.compose_rev [trans] attribute nat_trans.id [refl]
abb2f23440b8eba55271b63af92aca48067a8218
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/syntheticHolesAsPatterns.lean
f45c0f51aceb23cca2dee8ad6ad3a7e40d05ba00
[ "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
335
lean
inductive Fam2 : Type → Type → Type 1 where | any : Fam2 α α | nat : Nat → Fam2 Nat Nat example (a : α) (x : Fam2 α β) : β := match α, β, a, x with | ?α, ?β, ?a, Fam2.any => _ | ?α, ?β, ?a, Fam2.nat n => _ example (a : α) (x : Fam2 α β) : β := match x with | Fam2.any => _ | Fam2.nat n => _
62e850eed0ff97fd1e483c27feb3ec65b86e88da
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/linarith/elimination_auto.lean
07602a1ccc27ca44ec3ad8f3525aa14a0d6ad91f
[]
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,432
lean
/- Copyright (c) 2020 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.linarith.datatypes import Mathlib.PostPort universes l namespace Mathlib /-! # The Fourier-Motzkin elimination procedure The Fourier-Motzkin procedure is a variable elimination method for linear inequalities. <https://en.wikipedia.org/wiki/Fourier%E2%80%93Motzkin_elimination> Given a set of linear inequalities `comps = {tᵢ Rᵢ 0}`, we aim to eliminate a single variable `a` from the set. We partition `comps` into `comps_pos`, `comps_neg`, and `comps_zero`, where `comps_pos` contains the comparisons `tᵢ Rᵢ 0` in which the coefficient of `a` in `tᵢ` is positive, and similar. For each pair of comparisons `tᵢ Rᵢ 0 ∈ comps_pos`, `tⱼ Rⱼ 0 ∈ comps_neg`, we compute coefficients `vᵢ, vⱼ ∈ ℕ` such that `vᵢ*tᵢ + vⱼ*tⱼ` cancels out `a`. We collect these sums `vᵢ*tᵢ + vⱼ*tⱼ R' 0` in a set `S` and set `comps' = S ∪ comps_zero`, a new set of comparisons in which `a` has been eliminated. Theorem: `comps` and `comps'` are equisatisfiable. We recursively eliminate all variables from the system. If we derive an empty clause `0 < 0`, we conclude that the original system was unsatisfiable. -/ namespace linarith /-! ### Datatypes The `comp_source` and `pcomp` datatypes are specific to the FM elimination routine; they are not shared with other components of `linarith`. -/ /-- `comp_source` tracks the source of a comparison. The atomic source of a comparison is an assumption, indexed by a natural number. Two comparisons can be added to produce a new comparison, and one comparison can be scaled by a natural number to produce a new comparison. -/ inductive comp_source where | assump : ℕ → comp_source | add : comp_source → comp_source → comp_source | scale : ℕ → comp_source → comp_source /-- Given a `comp_source` `cs`, `cs.flatten` maps an assumption index to the number of copies of that assumption that appear in the history of `cs`. For example, suppose `cs` is produced by scaling assumption 2 by 5, and adding to that the sum of assumptions 1 and 2. `cs.flatten` maps `1 ↦ 1, 2 ↦ 6`. -/ /-- Formats a `comp_source` for printing. -/ def comp_source.to_string : comp_source → string := sorry end Mathlib
8108287311452146f4560f179d43403618b89616
5719a16e23dfc08cdea7a5bf035b81690f307965
/stage0/src/Init/Lean/Elab/Command.lean
baccd8be4011a194a8bb00a790661c8cbc5a1bcf
[ "Apache-2.0" ]
permissive
postmasters/lean4
488b03969a371e1507e1e8a4df9ebf63c7cbe7ac
f3976fc53a883ac7606fc59357d43f4b51016ca7
refs/heads/master
1,655,582,707,480
1,588,682,595,000
1,588,682,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,704
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.Elab.Alias import Init.Lean.Elab.Log import Init.Lean.Elab.ResolveName import Init.Lean.Elab.Term import Init.Lean.Elab.Binders import Init.Lean.Elab.SyntheticMVars namespace Lean namespace Elab namespace Command structure Scope := (kind : String) (header : String) (opts : Options := {}) (currNamespace : Name := Name.anonymous) (openDecls : List OpenDecl := []) (levelNames : List Name := []) (varDecls : Array Syntax := #[]) instance Scope.inhabited : Inhabited Scope := ⟨{ kind := "", header := "" }⟩ structure State := (env : Environment) (messages : MessageLog := {}) (scopes : List Scope := [{ kind := "root", header := "" }]) (nextMacroScope : Nat := firstFrontendMacroScope + 1) (maxRecDepth : Nat) instance State.inhabited : Inhabited State := ⟨{ env := arbitrary _, maxRecDepth := 0 }⟩ def mkState (env : Environment) (messages : MessageLog := {}) (opts : Options := {}) : State := { env := env, messages := messages, scopes := [{ kind := "root", header := "", opts := opts }], maxRecDepth := getMaxRecDepth opts } structure Context := (fileName : String) (fileMap : FileMap) (stateRef : IO.Ref State) (currRecDepth : Nat := 0) (cmdPos : String.Pos := 0) (macroStack : MacroStack := []) (currMacroScope : MacroScope := firstFrontendMacroScope) instance Exception.inhabited : Inhabited Exception := ⟨Exception.error $ arbitrary _⟩ abbrev CommandElabCoreM (ε) := ReaderT Context (EIO ε) abbrev CommandElabM := CommandElabCoreM Exception abbrev CommandElab := Syntax → CommandElabM Unit def mkMessageAux (ctx : Context) (ref : Syntax) (msgData : MessageData) (severity : MessageSeverity) : Message := mkMessageCore ctx.fileName ctx.fileMap msgData severity (ref.getPos.getD ctx.cmdPos) private def ioErrorToMessage (ctx : Context) (ref : Syntax) (err : IO.Error) : Message := let ref := getBetterRef ref ctx.macroStack; mkMessageAux ctx ref (addMacroStack (toString err) ctx.macroStack) MessageSeverity.error @[inline] def liftIOCore {α} (ctx : Context) (ref : Syntax) (x : IO α) : EIO Exception α := EIO.adaptExcept (fun ex => Exception.error $ ioErrorToMessage ctx ref ex) x @[inline] def liftIO {α} (ref : Syntax) (x : IO α) : CommandElabM α := fun ctx => liftIOCore ctx ref x private def getState : CommandElabM State := fun ctx => liftIOCore ctx Syntax.missing $ ctx.stateRef.get private def setState (s : State) : CommandElabM Unit := fun ctx => liftIOCore ctx Syntax.missing $ ctx.stateRef.set s @[inline] private def modifyGetState {α} (f : State → α × State) : CommandElabM α := do s ← getState; let (a, s) := f s; setState s; pure a instance CommandElabCoreM.monadState : MonadState State CommandElabM := { get := getState, set := setState, modifyGet := @modifyGetState } def getEnv : CommandElabM Environment := do s ← get; pure s.env def getScope : CommandElabM Scope := do s ← get; pure s.scopes.head! def getOptions : CommandElabM Options := do scope ← getScope; pure scope.opts def addContext (msg : MessageData) : CommandElabM MessageData := do env ← getEnv; opts ← getOptions; pure (MessageData.withContext { env := env, mctx := {}, lctx := {}, opts := opts } msg) instance CommandElabM.monadLog : MonadLog CommandElabM := { getCmdPos := do ctx ← read; pure ctx.cmdPos, getFileMap := do ctx ← read; pure ctx.fileMap, getFileName := do ctx ← read; pure ctx.fileName, addContext := addContext, logMessage := fun msg => modify $ fun s => { messages := s.messages.add msg, .. s } } /-- Throws an error with the given `msgData` and extracting position information from `ref`. If `ref` does not contain position information, then use `cmdPos` -/ def throwError {α} (ref : Syntax) (msgData : MessageData) : CommandElabM α := do ctx ← read; let ref := getBetterRef ref ctx.macroStack; let msgData := addMacroStack msgData ctx.macroStack; msg ← mkMessage msgData MessageSeverity.error ref; throw (Exception.error msg) def logTrace (cls : Name) (ref : Syntax) (msg : MessageData) : CommandElabM Unit := do msg ← addContext $ MessageData.tagged cls msg; logInfo ref msg @[inline] def trace (cls : Name) (ref : Syntax) (msg : Unit → MessageData) : CommandElabM Unit := do opts ← getOptions; when (checkTraceOption opts cls) $ logTrace cls ref (msg ()) def throwUnsupportedSyntax {α} : CommandElabM α := throw Elab.Exception.unsupportedSyntax protected def getCurrMacroScope : CommandElabM Nat := do ctx ← read; pure ctx.currMacroScope protected def getMainModule : CommandElabM Name := do env ← getEnv; pure env.mainModule @[inline] protected def withFreshMacroScope {α} (x : CommandElabM α) : CommandElabM α := do fresh ← modifyGet (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })); adaptReader (fun (ctx : Context) => { ctx with currMacroScope := fresh }) x instance CommandElabM.MonadQuotation : MonadQuotation CommandElabM := { getCurrMacroScope := Command.getCurrMacroScope, getMainModule := Command.getMainModule, withFreshMacroScope := @Command.withFreshMacroScope } unsafe def mkCommandElabAttribute : IO (KeyedDeclsAttribute CommandElab) := mkElabAttribute CommandElab `Lean.Elab.Command.commandElabAttribute `builtinCommandElab `commandElab `Lean.Parser.Command `Lean.Elab.Command.CommandElab "command" @[init mkCommandElabAttribute] constant commandElabAttribute : KeyedDeclsAttribute CommandElab := arbitrary _ @[inline] def withIncRecDepth {α} (ref : Syntax) (x : CommandElabM α) : CommandElabM α := do ctx ← read; s ← get; when (ctx.currRecDepth == s.maxRecDepth) $ throwError ref maxRecDepthErrorMessage; adaptReader (fun (ctx : Context) => { currRecDepth := ctx.currRecDepth + 1, .. ctx }) x private def elabCommandUsing (s : State) (stx : Syntax) : List CommandElab → CommandElabM Unit | [] => do let refFmt := stx.prettyPrint; throwError stx ("unexpected syntax" ++ MessageData.nest 2 (Format.line ++ refFmt)) | (elabFn::elabFns) => catch (elabFn stx) (fun ex => match ex with | Exception.error _ => throw ex | Exception.unsupportedSyntax => do set s; elabCommandUsing elabFns) /- Elaborate `x` with `stx` on the macro stack -/ @[inline] def withMacroExpansion {α} (beforeStx afterStx : Syntax) (x : CommandElabM α) : CommandElabM α := adaptReader (fun (ctx : Context) => { macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack, .. ctx }) x instance : MonadMacroAdapter CommandElabM := { getEnv := getEnv, getCurrMacroScope := getCurrMacroScope, getNextMacroScope := do s ← get; pure s.nextMacroScope, setNextMacroScope := fun next => modify $ fun s => { nextMacroScope := next, .. s }, throwError := @throwError, throwUnsupportedSyntax := @throwUnsupportedSyntax} partial def elabCommand : Syntax → CommandElabM Unit | stx => withIncRecDepth stx $ withFreshMacroScope $ match stx with | Syntax.node k args => if k == nullKind then -- list of commands => elaborate in order -- The parser will only ever return a single command at a time, but syntax quotations can return multiple ones args.forM elabCommand else do trace `Elab.step stx $ fun _ => stx; s ← get; stxNew? ← catch (do newStx ← adaptMacro (getMacros s.env) stx; pure (some newStx)) (fun ex => match ex with | Exception.unsupportedSyntax => pure none | _ => throw ex); match stxNew? with | some stxNew => withMacroExpansion stx stxNew $ elabCommand stxNew | _ => do let table := (commandElabAttribute.ext.getState s.env).table; let k := stx.getKind; match table.find? k with | some elabFns => elabCommandUsing s stx elabFns | none => throwError stx ("elaboration function for '" ++ toString k ++ "' has not been implemented") | _ => throwError stx "unexpected command" /-- Adapt a syntax transformation to a regular, command-producing elaborator. -/ def adaptExpander (exp : Syntax → CommandElabM Syntax) : CommandElab := fun stx => do stx' ← exp stx; withMacroExpansion stx stx' $ elabCommand stx' private def mkTermContext (ctx : Context) (s : State) (declName? : Option Name) : Term.Context := let scope := s.scopes.head!; { config := { opts := scope.opts, foApprox := true, ctxApprox := true, quasiPatternApprox := true, isDefEqStuckEx := true }, fileName := ctx.fileName, fileMap := ctx.fileMap, currRecDepth := ctx.currRecDepth, maxRecDepth := s.maxRecDepth, cmdPos := ctx.cmdPos, declName? := declName?, macroStack := ctx.macroStack, currMacroScope := ctx.currMacroScope, currNamespace := scope.currNamespace, levelNames := scope.levelNames, openDecls := scope.openDecls } private def mkTermState (s : State) : Term.State := { env := s.env, messages := s.messages, nextMacroScope := s.nextMacroScope } private def updateState (s : State) (newS : Term.State) : State := { env := newS.env, messages := newS.messages, nextMacroScope := newS.nextMacroScope, .. s } private def getVarDecls (s : State) : Array Syntax := s.scopes.head!.varDecls private def toCommandResult {α} (ctx : Context) (s : State) (result : EStateM.Result Term.Exception Term.State α) : EStateM.Result Exception State α := match result with | EStateM.Result.ok a newS => EStateM.Result.ok a (updateState s newS) | EStateM.Result.error (Term.Exception.ex ex) newS => EStateM.Result.error ex (updateState s newS) | EStateM.Result.error Term.Exception.postpone newS => unreachable! instance CommandElabM.inhabited {α} : Inhabited (CommandElabM α) := ⟨throw $ arbitrary _⟩ @[inline] def liftTermElabM {α} (declName? : Option Name) (x : TermElabM α) : CommandElabM α := do ctx ← read; s ← get; match (x $ mkTermContext ctx s declName?).run (mkTermState s) with | EStateM.Result.ok a newS => do modify $ fun s => { env := newS.env, messages := newS.messages, .. s }; pure a | EStateM.Result.error (Term.Exception.ex ex) newS => do modify $ fun s => { env := newS.env, messages := newS.messages, .. s }; throw ex | EStateM.Result.error Term.Exception.postpone newS => unreachable! @[inline] def runTermElabM {α} (declName? : Option Name) (elab : Array Expr → TermElabM α) : CommandElabM α := do s ← get; liftTermElabM declName? (Term.elabBinders (getVarDecls s) elab) @[inline] def withLogging (x : CommandElabM Unit) : CommandElabM Unit := catch x (fun ex => match ex with | Exception.error ex => do logMessage ex; pure () | Exception.unsupportedSyntax => unreachable!) @[inline] def catchExceptions (x : CommandElabM Unit) : CommandElabCoreM Empty Unit := fun ctx => EIO.catchExceptions (withLogging x ctx) (fun _ => pure ()) def dbgTrace {α} [HasToString α] (a : α) : CommandElabM Unit := _root_.dbgTrace (toString a) $ fun _ => pure () def setEnv (newEnv : Environment) : CommandElabM Unit := modify $ fun s => { env := newEnv, .. s } def getCurrNamespace : CommandElabM Name := do scope ← getScope; pure scope.currNamespace private def addScope (kind : String) (header : String) (newNamespace : Name) : CommandElabM Unit := modify $ fun s => { env := s.env.registerNamespace newNamespace, scopes := { kind := kind, header := header, currNamespace := newNamespace, .. s.scopes.head! } :: s.scopes, .. s } private def addScopes (ref : Syntax) (kind : String) (updateNamespace : Bool) : Name → CommandElabM Unit | Name.anonymous => pure () | Name.str p header _ => do addScopes p; currNamespace ← getCurrNamespace; addScope kind header (if updateNamespace then currNamespace ++ header else currNamespace) | _ => throwError ref "invalid scope" private def addNamespace (ref : Syntax) (header : Name) : CommandElabM Unit := addScopes ref "namespace" true header @[builtinCommandElab «namespace»] def elabNamespace : CommandElab := fun stx => match_syntax stx with | `(namespace $n) => addNamespace stx n.getId | _ => throw Exception.unsupportedSyntax @[builtinCommandElab «section»] def elabSection : CommandElab := fun stx => match_syntax stx with | `(section $header:ident) => addScopes stx "section" false header.getId | `(section) => do currNamespace ← getCurrNamespace; addScope "section" "" currNamespace | _ => throw Exception.unsupportedSyntax def getScopes : CommandElabM (List Scope) := do s ← get; pure s.scopes private def checkAnonymousScope : List Scope → Bool | { header := "", .. } :: _ => true | _ => false private def checkEndHeader : Name → List Scope → Bool | Name.anonymous, _ => true | Name.str p s _, { header := h, .. } :: scopes => h == s && checkEndHeader p scopes | _, _ => false @[builtinCommandElab «end»] def elabEnd : CommandElab := fun stx => do let header? := (stx.getArg 1).getOptionalIdent?; let endSize := match header? with | none => 1 | some n => n.getNumParts; scopes ← getScopes; if endSize < scopes.length then modify $ fun s => { scopes := s.scopes.drop endSize, .. s } else do { -- we keep "root" scope modify $ fun s => { scopes := s.scopes.drop (s.scopes.length - 1), .. s }; throwError stx "invalid 'end', insufficient scopes" }; match header? with | none => unless (checkAnonymousScope scopes) $ throwError stx "invalid 'end', name is missing" | some header => unless (checkEndHeader header scopes) $ throwError stx "invalid 'end', name mismatch" @[inline] def withNamespace {α} (ref : Syntax) (ns : Name) (elab : CommandElabM α) : CommandElabM α := do addNamespace ref ns; a ← elab; modify $ fun s => { scopes := s.scopes.drop ns.getNumParts, .. s }; pure a @[specialize] def modifyScope (f : Scope → Scope) : CommandElabM Unit := modify $ fun s => { scopes := match s.scopes with | h::t => f h :: t | [] => unreachable!, .. s } def getLevelNames : CommandElabM (List Name) := do scope ← getScope; pure scope.levelNames def throwAlreadyDeclaredUniverseLevel {α} (ref : Syntax) (u : Name) : CommandElabM α := throwError ref ("a universe level named '" ++ toString u ++ "' has already been declared") def addUnivLevel (idStx : Syntax) : CommandElabM Unit := do let id := idStx.getId; levelNames ← getLevelNames; if levelNames.elem id then throwAlreadyDeclaredUniverseLevel idStx id else modifyScope $ fun scope => { levelNames := id :: scope.levelNames, .. scope } partial def elabChoiceAux (cmds : Array Syntax) : Nat → CommandElabM Unit | i => if h : i < cmds.size then let cmd := cmds.get ⟨i, h⟩; catch (elabCommand cmd) (fun ex => match ex with | Exception.unsupportedSyntax => elabChoiceAux (i+1) | _ => throw ex) else throwUnsupportedSyntax @[builtinCommandElab choice] def elbChoice : CommandElab := fun stx => elabChoiceAux stx.getArgs 0 @[builtinCommandElab «universe»] def elabUniverse : CommandElab := fun n => do addUnivLevel (n.getArg 1) @[builtinCommandElab «universes»] def elabUniverses : CommandElab := fun n => do let idsStx := n.getArg 1; idsStx.forArgsM addUnivLevel @[builtinCommandElab «init_quot»] def elabInitQuot : CommandElab := fun stx => do env ← getEnv; match env.addDecl Declaration.quotDecl with | Except.ok env => setEnv env | Except.error ex => do opts ← getOptions; throwError stx (ex.toMessageData opts) def getOpenDecls : CommandElabM (List OpenDecl) := do scope ← getScope; pure scope.openDecls def logUnknownDecl (stx : Syntax) (declName : Name) : CommandElabM Unit := logError stx ("unknown declaration '" ++ toString declName ++ "'") def resolveNamespace (id : Name) : CommandElabM Name := do env ← getEnv; currNamespace ← getCurrNamespace; openDecls ← getOpenDecls; match Elab.resolveNamespace env currNamespace openDecls id with | some ns => pure ns | none => throw Exception.unsupportedSyntax @[builtinCommandElab «export»] def elabExport : CommandElab := fun stx => do -- `stx` is of the form (Command.export "export" <namespace> "(" (null <ids>*) ")") let id := stx.getIdAt 1; ns ← resolveNamespace id; currNamespace ← getCurrNamespace; when (ns == currNamespace) $ throwError stx "invalid 'export', self export"; env ← getEnv; let ids := (stx.getArg 3).getArgs; aliases ← ids.foldlM (fun (aliases : List (Name × Name)) (idStx : Syntax) => do { let id := idStx.getId; let declName := ns ++ id; if env.contains declName then pure $ (currNamespace ++ id, declName) :: aliases else do logUnknownDecl idStx declName; pure aliases }) []; modify $ fun s => { env := aliases.foldl (fun env p => addAlias env p.1 p.2) s.env, .. s } def addOpenDecl (d : OpenDecl) : CommandElabM Unit := modifyScope $ fun scope => { openDecls := d :: scope.openDecls, .. scope } def elabOpenSimple (n : SyntaxNode) : CommandElabM Unit := -- `open` id+ let nss := n.getArg 0; nss.forArgsM $ fun ns => do ns ← resolveNamespace ns.getId; addOpenDecl (OpenDecl.simple ns []) -- `open` id `(` id+ `)` def elabOpenOnly (n : SyntaxNode) : CommandElabM Unit := do let ns := n.getIdAt 0; ns ← resolveNamespace ns; let ids := n.getArg 2; ids.forArgsM $ fun idStx => do let id := idStx.getId; let declName := ns ++ id; env ← getEnv; if env.contains declName then addOpenDecl (OpenDecl.explicit id declName) else logUnknownDecl idStx declName -- `open` id `hiding` id+ def elabOpenHiding (n : SyntaxNode) : CommandElabM Unit := do let ns := n.getIdAt 0; ns ← resolveNamespace ns; let idsStx := n.getArg 2; env ← getEnv; ids : List Name ← idsStx.foldArgsM (fun idStx ids => do let id := idStx.getId; let declName := ns ++ id; if env.contains declName then pure (id::ids) else do logUnknownDecl idStx declName; pure ids) []; addOpenDecl (OpenDecl.simple ns ids) -- `open` id `renaming` sepBy (id `->` id) `,` def elabOpenRenaming (n : SyntaxNode) : CommandElabM Unit := do let ns := n.getIdAt 0; ns ← resolveNamespace ns; let rs := (n.getArg 2); rs.forSepArgsM $ fun stx => do let fromId := stx.getIdAt 0; let toId := stx.getIdAt 2; let declName := ns ++ fromId; env ← getEnv; if env.contains declName then addOpenDecl (OpenDecl.explicit toId declName) else logUnknownDecl stx declName @[builtinCommandElab «open»] def elabOpen : CommandElab := fun n => do let body := (n.getArg 1).asNode; let k := body.getKind; if k == `Lean.Parser.Command.openSimple then elabOpenSimple body else if k == `Lean.Parser.Command.openOnly then elabOpenOnly body else if k == `Lean.Parser.Command.openHiding then elabOpenHiding body else elabOpenRenaming body @[builtinCommandElab «variable»] def elabVariable : CommandElab := fun n => do -- `variable` bracketedBinder let binder := n.getArg 1; -- Try to elaborate `binder` for sanity checking runTermElabM none $ fun _ => Term.elabBinder binder $ fun _ => pure (); modifyScope $ fun scope => { varDecls := scope.varDecls.push binder, .. scope } @[builtinCommandElab «variables»] def elabVariables : CommandElab := fun n => do -- `variables` bracketedBinder+ let binders := (n.getArg 1).getArgs; -- Try to elaborate `binders` for sanity checking runTermElabM none $ fun _ => Term.elabBinders binders $ fun _ => pure (); modifyScope $ fun scope => { varDecls := scope.varDecls ++ binders, .. scope } @[inline] def withoutModifyingEnv {α} (x : CommandElabM α) : CommandElabM α := do env ← getEnv; finally x (setEnv env) @[builtinCommandElab «check»] def elabCheck : CommandElab := fun stx => do let term := stx.getArg 1; withoutModifyingEnv $ runTermElabM (some `_check) $ fun _ => do e ← Term.elabTerm term none; Term.synthesizeSyntheticMVars false; type ← Term.inferType stx e; logInfo stx (e ++ " : " ++ type); pure () def hasNoErrorMessages : CommandElabM Bool := do s ← get; pure $ !s.messages.hasErrors def failIfSucceeds {α} (ref : Syntax) (x : CommandElabM α) : CommandElabM Unit := do let resetMessages : CommandElabM MessageLog := do { s ← get; let messages := s.messages; modify $ fun s => { messages := {}, .. s }; pure messages }; let restoreMessages (prevMessages : MessageLog) : CommandElabM Unit := do { modify $ fun s => { messages := prevMessages ++ s.messages.errorsToWarnings, .. s } }; prevMessages ← resetMessages; succeeded ← finally (catch (do x; hasNoErrorMessages) (fun ex => match ex with | Exception.error msg => do modify (fun s => { messages := s.messages.add msg, .. s }); pure false | Exception.unsupportedSyntax => do logError ref "unsupported syntax"; pure false)) (restoreMessages prevMessages); when succeeded $ throwError ref "unexpected success" @[builtinCommandElab «check_failure»] def elabCheckFailure : CommandElab := fun stx => failIfSucceeds stx $ elabCheck stx @[builtinCommandElab «synth»] def elabSynth : CommandElab := fun stx => do let ref := stx; let term := stx.getArg 1; withoutModifyingEnv $ runTermElabM `_synth_cmd $ fun _ => do inst ← Term.elabTerm term none; Term.synthesizeSyntheticMVars false; inst ← Term.instantiateMVars ref inst; val ← Term.liftMetaM ref $ Meta.synthInstance inst; logInfo stx val; pure () def setOption (ref : Syntax) (optionName : Name) (val : DataValue) : CommandElabM Unit := do decl ← liftIO ref $ getOptionDecl optionName; unless (decl.defValue.sameCtor val) $ throwError ref "type mismatch at set_option"; modifyScope $ fun scope => { opts := scope.opts.insert optionName val, .. scope }; match optionName, val with | `maxRecDepth, DataValue.ofNat max => modify $ fun s => { maxRecDepth := max, .. s} | _, _ => pure () @[builtinCommandElab «set_option»] def elabSetOption : CommandElab := fun stx => do let ref := stx; let optionName := stx.getIdAt 1; let val := stx.getArg 2; match val.isStrLit? with | some str => setOption ref optionName (DataValue.ofString str) | none => match val.isNatLit? with | some num => setOption ref optionName (DataValue.ofNat num) | none => match val with | Syntax.atom _ "true" => setOption ref optionName (DataValue.ofBool true) | Syntax.atom _ "false" => setOption ref optionName (DataValue.ofBool false) | _ => logError val ("unexpected set_option value " ++ toString val) /- `declId` is of the form ``` parser! ident >> optional (".{" >> sepBy1 ident ", " >> "}") ``` but we also accept a single identifier to users to make macro writing more convenient . -/ def expandDeclId (declId : Syntax) : Name × Syntax := if declId.isIdent then (declId.getId, mkNullNode) else let id := declId.getIdAt 0; let optUnivDeclStx := declId.getArg 1; (id, optUnivDeclStx) @[inline] def withDeclId (declId : Syntax) (f : Name → CommandElabM Unit) : CommandElabM Unit := do -- ident >> optional (".{" >> sepBy1 ident ", " >> "}") let (id, optUnivDeclStx) := expandDeclId declId; savedLevelNames ← getLevelNames; levelNames ← if optUnivDeclStx.isNone then pure savedLevelNames else do { let extraLevels := (optUnivDeclStx.getArg 1).getArgs.getEvenElems; extraLevels.foldlM (fun levelNames idStx => let id := idStx.getId; if levelNames.elem id then throwAlreadyDeclaredUniverseLevel idStx id else pure (id :: levelNames)) savedLevelNames }; let ref := declId; -- extract (optional) namespace part of id, after decoding macro scopes that would interfere with the check let scpView := extractMacroScopes id; match scpView.name with | Name.str pre s _ => /- Add back macro scopes. We assume a declaration like `def a.b[1,2] ...` with macro scopes `[1,2]` is always meant to mean `namespace a def b[1,2] ...`. -/ let id := { name := mkNameSimple s, .. scpView }.review; withNamespace ref pre $ do modifyScope $ fun scope => { levelNames := levelNames, .. scope }; finally (f id) (modifyScope $ fun scope => { levelNames := savedLevelNames, .. scope }) | _ => throwError ref "invalid declaration name" /-- Sort the given list of `usedParams` using the following order: - If it is an explicit level `explicitParams`, then use user given order. - Otherwise, use lexicographical. Remark: `explicitParams` are in reverse declaration order. That is, the head is the last declared parameter. -/ def sortDeclLevelParams (explicitParams : List Name) (usedParams : Array Name) : List Name := let result := explicitParams.foldl (fun result levelName => if usedParams.elem levelName then levelName :: result else result) []; let remaining := usedParams.filter (fun levelParam => !explicitParams.elem levelParam); let remaining := remaining.qsort Name.lt; result ++ remaining.toList def addDecl (ref : Syntax) (decl : Declaration) : CommandElabM Unit := liftTermElabM none $ Term.addDecl ref decl def compileDecl (ref : Syntax) (decl : Declaration) : CommandElabM Unit := liftTermElabM none $ Term.compileDecl ref decl end Command end Elab end Lean
0d364bcd12d750d2894aa7723bd08aaef64df88b
43390109ab88557e6090f3245c47479c123ee500
/src/M1F/problem_bank/0204/Q0204.lean
cc40a69b32a83280fff07f4030b23f8291697eaf
[ "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
247
lean
import data.real.basic theorem Q4a : ¬ (∀ (x y : ℝ), M1F.is_irrational x → M1F.is_irrational y → M1F.is_irrational (x+y)) := sorry theorem Q4b : ¬ (∀ (a : ℝ), ∀ (b : ℚ), M1F.is_irrational a → M1F.is_irrational (a*b)) := sorry
68ac3e83a68e9caaaf4b8c2bdf63cc625cd5a305
ce89339993655da64b6ccb555c837ce6c10f9ef4
/bluejam/topprover/39.lean
d5d0a2eb0d0f40d3cb1e6d1e85432b946e1d9df7
[]
no_license
zeptometer/LearnLean
ef32dc36a22119f18d843f548d0bb42f907bff5d
bb84d5dbe521127ba134d4dbf9559b294a80b9f7
refs/heads/master
1,625,710,824,322
1,601,382,570,000
1,601,382,570,000
195,228,870
2
0
null
null
null
null
UTF-8
Lean
false
false
355
lean
example : (forall P Q R, (P <-> Q) \/ (Q <-> R) \/ (R <-> P)) -> forall P, P \/ ¬ P := begin intros, cases a true false P, have: false, apply true_ne_false, rw h, contradiction, cases h, right, intro, apply h.mpr, assumption, left, apply h.mpr, trivial, end
4b412edd3edfd29863d715d520c6bbb37539cc4a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/polynomial/reverse.lean
eb328346d277f9bfc575c299a2b58096bef5763d
[ "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,940
lean
/- Copyright (c) 2020 Damiano Testa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa -/ import data.polynomial.degree.trailing_degree import data.polynomial.erase_lead import data.polynomial.eval /-! # Reverse of a univariate polynomial The main definition is `reverse`. Applying `reverse` to a polynomial `f : R[X]` produces the polynomial with a reversed list of coefficients, equivalent to `X^f.nat_degree * f(1/X)`. The main result is that `reverse (f * g) = reverse f * reverse g`, provided the leading coefficients of `f` and `g` do not multiply to zero. -/ namespace polynomial open polynomial finsupp finset open_locale classical polynomial section semiring variables {R : Type*} [semiring R] {f : R[X]} /-- If `i ≤ N`, then `rev_at_fun N i` returns `N - i`, otherwise it returns `i`. This is the map used by the embedding `rev_at`. -/ def rev_at_fun (N i : ℕ) : ℕ := ite (i ≤ N) (N-i) i lemma rev_at_fun_invol {N i : ℕ} : rev_at_fun N (rev_at_fun N i) = i := begin unfold rev_at_fun, split_ifs with h j, { exact tsub_tsub_cancel_of_le h, }, { exfalso, apply j, exact nat.sub_le N i, }, { refl, }, end lemma rev_at_fun_inj {N : ℕ} : function.injective (rev_at_fun N) := begin intros a b hab, rw [← @rev_at_fun_invol N a, hab, rev_at_fun_invol], end /-- If `i ≤ N`, then `rev_at N i` returns `N - i`, otherwise it returns `i`. Essentially, this embedding is only used for `i ≤ N`. The advantage of `rev_at N i` over `N - i` is that `rev_at` is an involution. -/ def rev_at (N : ℕ) : function.embedding ℕ ℕ := { to_fun := λ i , (ite (i ≤ N) (N-i) i), inj' := rev_at_fun_inj } /-- We prefer to use the bundled `rev_at` over unbundled `rev_at_fun`. -/ @[simp] lemma rev_at_fun_eq (N i : ℕ) : rev_at_fun N i = rev_at N i := rfl @[simp] lemma rev_at_invol {N i : ℕ} : (rev_at N) (rev_at N i) = i := rev_at_fun_invol @[simp] lemma rev_at_le {N i : ℕ} (H : i ≤ N) : rev_at N i = N - i := if_pos H lemma rev_at_add {N O n o : ℕ} (hn : n ≤ N) (ho : o ≤ O) : rev_at (N + O) (n + o) = rev_at N n + rev_at O o := begin rcases nat.le.dest hn with ⟨n', rfl⟩, rcases nat.le.dest ho with ⟨o', rfl⟩, repeat { rw rev_at_le (le_add_right rfl.le) }, rw [add_assoc, add_left_comm n' o, ← add_assoc, rev_at_le (le_add_right rfl.le)], repeat {rw add_tsub_cancel_left}, end @[simp] lemma rev_at_zero (N : ℕ) : rev_at N 0 = N := by simp [rev_at] /-- `reflect N f` is the polynomial such that `(reflect N f).coeff i = f.coeff (rev_at N i)`. In other words, the terms with exponent `[0, ..., N]` now have exponent `[N, ..., 0]`. In practice, `reflect` is only used when `N` is at least as large as the degree of `f`. Eventually, it will be used with `N` exactly equal to the degree of `f`. -/ noncomputable def reflect (N : ℕ) : R[X] → R[X] | ⟨f⟩ := ⟨finsupp.emb_domain (rev_at N) f⟩ lemma reflect_support (N : ℕ) (f : R[X]) : (reflect N f).support = finset.image (rev_at N) f.support := begin rcases f, ext1, simp only [reflect, support_of_finsupp, support_emb_domain, finset.mem_map, finset.mem_image], end @[simp] lemma coeff_reflect (N : ℕ) (f : R[X]) (i : ℕ) : coeff (reflect N f) i = f.coeff (rev_at N i) := begin rcases f, simp only [reflect, coeff], calc finsupp.emb_domain (rev_at N) f i = finsupp.emb_domain (rev_at N) f (rev_at N (rev_at N i)) : by rw rev_at_invol ... = f (rev_at N i) : finsupp.emb_domain_apply _ _ _ end @[simp] lemma reflect_zero {N : ℕ} : reflect N (0 : R[X]) = 0 := rfl @[simp] lemma reflect_eq_zero_iff {N : ℕ} {f : R[X]} : reflect N (f : R[X]) = 0 ↔ f = 0 := by { rcases f, simp [reflect] } @[simp] lemma reflect_add (f g : R[X]) (N : ℕ) : reflect N (f + g) = reflect N f + reflect N g := by { ext, simp only [coeff_add, coeff_reflect], } @[simp] lemma reflect_C_mul (f : R[X]) (r : R) (N : ℕ) : reflect N (C r * f) = C r * (reflect N f) := by { ext, simp only [coeff_reflect, coeff_C_mul], } @[simp] lemma reflect_C_mul_X_pow (N n : ℕ) {c : R} : reflect N (C c * X ^ n) = C c * X ^ (rev_at N n) := begin ext, rw [reflect_C_mul, coeff_C_mul, coeff_C_mul, coeff_X_pow, coeff_reflect], split_ifs with h j, { rw [h, rev_at_invol, coeff_X_pow_self], }, { rw [not_mem_support_iff.mp], intro a, rw [← one_mul (X ^ n), ← C_1] at a, apply h, rw [← (mem_support_C_mul_X_pow a), rev_at_invol], }, end @[simp] lemma reflect_C (r : R) (N : ℕ) : reflect N (C r) = C r * X ^ N := by conv_lhs { rw [← mul_one (C r), ← pow_zero X, reflect_C_mul_X_pow, rev_at_zero] } @[simp] lemma reflect_monomial (N n : ℕ) : reflect N ((X : R[X]) ^ n) = X ^ (rev_at N n) := by rw [← one_mul (X ^ n), ← one_mul (X ^ (rev_at N n)), ← C_1, reflect_C_mul_X_pow] lemma reflect_mul_induction (cf cg : ℕ) : ∀ N O : ℕ, ∀ f g : R[X], f.support.card ≤ cf.succ → g.support.card ≤ cg.succ → f.nat_degree ≤ N → g.nat_degree ≤ O → (reflect (N + O) (f * g)) = (reflect N f) * (reflect O g) := begin induction cf with cf hcf, --first induction (left): base case { induction cg with cg hcg, -- second induction (right): base case { intros N O f g Cf Cg Nf Og, rw [← C_mul_X_pow_eq_self Cf, ← C_mul_X_pow_eq_self Cg], simp_rw [mul_assoc, X_pow_mul, mul_assoc, ← pow_add (X : R[X]), reflect_C_mul, reflect_monomial, add_comm, rev_at_add Nf Og, mul_assoc, X_pow_mul, mul_assoc, ← pow_add (X : R[X]), add_comm], }, -- second induction (right): induction step { intros N O f g Cf Cg Nf Og, by_cases g0 : g = 0, { rw [g0, reflect_zero, mul_zero, mul_zero, reflect_zero], }, rw [← erase_lead_add_C_mul_X_pow g, mul_add, reflect_add, reflect_add, mul_add, hcg, hcg]; try { assumption }, { exact le_add_left card_support_C_mul_X_pow_le_one }, { exact (le_trans (nat_degree_C_mul_X_pow_le g.leading_coeff g.nat_degree) Og) }, { exact nat.lt_succ_iff.mp (gt_of_ge_of_gt Cg (erase_lead_support_card_lt g0)) }, { exact le_trans erase_lead_nat_degree_le_aux Og } } }, --first induction (left): induction step { intros N O f g Cf Cg Nf Og, by_cases f0 : f = 0, { rw [f0, reflect_zero, zero_mul, zero_mul, reflect_zero], }, rw [← erase_lead_add_C_mul_X_pow f, add_mul, reflect_add, reflect_add, add_mul, hcf, hcf]; try { assumption }, { exact le_add_left card_support_C_mul_X_pow_le_one }, { exact (le_trans (nat_degree_C_mul_X_pow_le f.leading_coeff f.nat_degree) Nf) }, { exact nat.lt_succ_iff.mp (gt_of_ge_of_gt Cf (erase_lead_support_card_lt f0)) }, { exact (le_trans erase_lead_nat_degree_le_aux Nf) } } end @[simp] theorem reflect_mul (f g : R[X]) {F G : ℕ} (Ff : f.nat_degree ≤ F) (Gg : g.nat_degree ≤ G) : reflect (F + G) (f * g) = reflect F f * reflect G g := reflect_mul_induction _ _ F G f g f.support.card.le_succ g.support.card.le_succ Ff Gg section eval₂ variables {S : Type*} [comm_semiring S] lemma eval₂_reflect_mul_pow (i : R →+* S) (x : S) [invertible x] (N : ℕ) (f : R[X]) (hf : f.nat_degree ≤ N) : eval₂ i (⅟x) (reflect N f) * x ^ N = eval₂ i x f := begin refine induction_with_nat_degree_le (λ f, eval₂ i (⅟x) (reflect N f) * x ^ N = eval₂ i x f) _ _ _ _ f hf, { simp }, { intros n r hr0 hnN, simp only [rev_at_le hnN, reflect_C_mul_X_pow, eval₂_X_pow, eval₂_C, eval₂_mul], conv in (x ^ N) { rw [← nat.sub_add_cancel hnN] }, rw [pow_add, ← mul_assoc, mul_assoc (i r), ← mul_pow, inv_of_mul_self, one_pow, mul_one] }, { intros, simp [*, add_mul] } end lemma eval₂_reflect_eq_zero_iff (i : R →+* S) (x : S) [invertible x] (N : ℕ) (f : R[X]) (hf : f.nat_degree ≤ N) : eval₂ i (⅟x) (reflect N f) = 0 ↔ eval₂ i x f = 0 := begin conv_rhs { rw [← eval₂_reflect_mul_pow i x N f hf] }, split, { intro h, rw [h, zero_mul] }, { intro h, rw [← mul_one (eval₂ i (⅟x) _), ← one_pow N, ← mul_inv_of_self x, mul_pow, ← mul_assoc, h, zero_mul] } end end eval₂ /-- The reverse of a polynomial f is the polynomial obtained by "reading f backwards". Even though this is not the actual definition, reverse f = f (1/X) * X ^ f.nat_degree. -/ noncomputable def reverse (f : R[X]) : R[X] := reflect f.nat_degree f lemma coeff_reverse (f : R[X]) (n : ℕ) : f.reverse.coeff n = f.coeff (rev_at f.nat_degree n) := by rw [reverse, coeff_reflect] @[simp] lemma coeff_zero_reverse (f : R[X]) : coeff (reverse f) 0 = leading_coeff f := by rw [coeff_reverse, rev_at_le (zero_le f.nat_degree), tsub_zero, leading_coeff] @[simp] lemma reverse_zero : reverse (0 : R[X]) = 0 := rfl @[simp] lemma reverse_eq_zero : f.reverse = 0 ↔ f = 0 := by simp [reverse] lemma reverse_nat_degree_le (f : R[X]) : f.reverse.nat_degree ≤ f.nat_degree := begin rw [nat_degree_le_iff_degree_le, degree_le_iff_coeff_zero], intros n hn, rw with_bot.coe_lt_coe at hn, rw [coeff_reverse, rev_at, function.embedding.coe_fn_mk, if_neg (not_le_of_gt hn), coeff_eq_zero_of_nat_degree_lt hn], end lemma nat_degree_eq_reverse_nat_degree_add_nat_trailing_degree (f : R[X]) : f.nat_degree = f.reverse.nat_degree + f.nat_trailing_degree := begin by_cases hf : f = 0, { rw [hf, reverse_zero, nat_degree_zero, nat_trailing_degree_zero] }, apply le_antisymm, { refine tsub_le_iff_right.mp _, apply le_nat_degree_of_ne_zero, rw [reverse, coeff_reflect, ←rev_at_le f.nat_trailing_degree_le_nat_degree, rev_at_invol], exact trailing_coeff_nonzero_iff_nonzero.mpr hf }, { rw ← le_tsub_iff_left f.reverse_nat_degree_le, apply nat_trailing_degree_le_of_ne_zero, have key := mt leading_coeff_eq_zero.mp (mt reverse_eq_zero.mp hf), rwa [leading_coeff, coeff_reverse, rev_at_le f.reverse_nat_degree_le] at key }, end lemma reverse_nat_degree (f : R[X]) : f.reverse.nat_degree = f.nat_degree - f.nat_trailing_degree := by rw [f.nat_degree_eq_reverse_nat_degree_add_nat_trailing_degree, add_tsub_cancel_right] lemma reverse_leading_coeff (f : R[X]) : f.reverse.leading_coeff = f.trailing_coeff := by rw [leading_coeff, reverse_nat_degree, ←rev_at_le f.nat_trailing_degree_le_nat_degree, coeff_reverse, rev_at_invol, trailing_coeff] lemma reverse_nat_trailing_degree (f : R[X]) : f.reverse.nat_trailing_degree = 0 := begin by_cases hf : f = 0, { rw [hf, reverse_zero, nat_trailing_degree_zero] }, { rw ← le_zero_iff, apply nat_trailing_degree_le_of_ne_zero, rw [coeff_zero_reverse], exact mt leading_coeff_eq_zero.mp hf }, end lemma reverse_trailing_coeff (f : R[X]) : f.reverse.trailing_coeff = f.leading_coeff := by rw [trailing_coeff, reverse_nat_trailing_degree, coeff_zero_reverse] theorem reverse_mul {f g : R[X]} (fg : f.leading_coeff * g.leading_coeff ≠ 0) : reverse (f * g) = reverse f * reverse g := begin unfold reverse, rw [nat_degree_mul' fg, reflect_mul f g rfl.le rfl.le], end @[simp] lemma reverse_mul_of_domain {R : Type*} [ring R] [no_zero_divisors R] (f g : R[X]) : reverse (f * g) = reverse f * reverse g := begin by_cases f0 : f=0, { simp only [f0, zero_mul, reverse_zero], }, by_cases g0 : g=0, { rw [g0, mul_zero, reverse_zero, mul_zero], }, simp [reverse_mul, *], end lemma trailing_coeff_mul {R : Type*} [ring R] [no_zero_divisors R] (p q : R[X]) : (p * q).trailing_coeff = p.trailing_coeff * q.trailing_coeff := by rw [←reverse_leading_coeff, reverse_mul_of_domain, leading_coeff_mul, reverse_leading_coeff, reverse_leading_coeff] @[simp] lemma coeff_one_reverse (f : R[X]) : coeff (reverse f) 1 = next_coeff f := begin rw [coeff_reverse, next_coeff], split_ifs with hf, { have : coeff f 1 = 0 := coeff_eq_zero_of_nat_degree_lt (by simp only [hf, zero_lt_one]), simp [*, rev_at] }, { rw rev_at_le, exact nat.succ_le_iff.2 (pos_iff_ne_zero.2 hf) } end section eval₂ variables {S : Type*} [comm_semiring S] lemma eval₂_reverse_mul_pow (i : R →+* S) (x : S) [invertible x] (f : R[X]) : eval₂ i (⅟x) (reverse f) * x ^ f.nat_degree = eval₂ i x f := eval₂_reflect_mul_pow i _ _ f le_rfl @[simp] lemma eval₂_reverse_eq_zero_iff (i : R →+* S) (x : S) [invertible x] (f : R[X]) : eval₂ i (⅟x) (reverse f) = 0 ↔ eval₂ i x f = 0 := eval₂_reflect_eq_zero_iff i x _ _ le_rfl end eval₂ end semiring section ring variables {R : Type*} [ring R] @[simp] lemma reflect_neg (f : R[X]) (N : ℕ) : reflect N (- f) = - reflect N f := by rw [neg_eq_neg_one_mul, ←C_1, ←C_neg, reflect_C_mul, C_neg, C_1, ←neg_eq_neg_one_mul] @[simp] lemma reflect_sub (f g : R[X]) (N : ℕ) : reflect N (f - g) = reflect N f - reflect N g := by rw [sub_eq_add_neg, sub_eq_add_neg, reflect_add, reflect_neg] @[simp] lemma reverse_neg (f : R[X]) : reverse (- f) = - reverse f := by rw [reverse, reverse, reflect_neg, nat_degree_neg] end ring end polynomial
8c0704edc46110ae971f8d3ed67678a285783c9c
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/direct_sum_graded.lean
881c274be3009a763952b544182e83ccad174234
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
26,118
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.direct_sum import algebra.algebra.basic import algebra.algebra.operations import group_theory.subgroup /-! # Additively-graded multiplicative structures on `⨁ i, A i` This module provides a set of heterogeneous typeclasses for defining a multiplicative structure over `⨁ i, A i` such that `(*) : A i → A j → A (i + j)`; that is to say, `A` forms an additively-graded ring. The typeclasses are: * `direct_sum.ghas_one A` * `direct_sum.ghas_mul A` * `direct_sum.gmonoid A` * `direct_sum.gcomm_monoid A` Respectively, these imbue the direct sum `⨁ i, A i` with: * `direct_sum.has_one` * `direct_sum.mul_zero_class`, `direct_sum.distrib` * `direct_sum.semiring`, `direct_sum.ring` * `direct_sum.comm_semiring`, `direct_sum.comm_ring` the base ring `A 0` with: * `direct_sum.grade_zero.has_one` * `direct_sum.grade_zero.mul_zero_class`, `direct_sum.grade_zero.distrib` * `direct_sum.grade_zero.semiring`, `direct_sum.grade_zero.ring` * `direct_sum.grade_zero.comm_semiring`, `direct_sum.grade_zero.comm_ring` and the `i`th grade `A i` with `A 0`-actions (`•`) defined as left-multiplication: * (nothing) * `direct_sum.grade_zero.has_scalar (A 0)`, `direct_sum.grade_zero.smul_with_zero (A 0)` * `direct_sum.grade_zero.module (A 0)` * (nothing) Note that in the presence of these instances, `⨁ i, A i` itself inherits an `A 0`-action. `direct_sum.of_zero_ring_hom : A 0 →+* ⨁ i, A i` provides `direct_sum.of A 0` as a ring homomorphism. `direct_sum.to_semiring` extends `direct_sum.to_add_monoid` to produce a `ring_hom`. ## Direct sums of subobjects Additionally, this module provides helper functions to construct `gmonoid` and `gcomm_monoid` instances for: * `A : ι → submonoid S`: `direct_sum.ghas_one.of_add_submonoids`, `direct_sum.ghas_mul.of_add_submonoids`, `direct_sum.gmonoid.of_add_submonoids`, `direct_sum.gcomm_monoid.of_add_submonoids`. * `A : ι → subgroup S`: `direct_sum.ghas_one.of_add_subgroups`, `direct_sum.ghas_mul.of_add_subgroups`, `direct_sum.gmonoid.of_add_subgroups`, `direct_sum.gcomm_monoid.of_add_subgroups`. * `A : ι → submodule S`: `direct_sum.ghas_one.of_submodules`, `direct_sum.ghas_mul.of_submodules`, `direct_sum.gmonoid.of_submodules`, `direct_sum.gcomm_monoid.of_submodules`. If `complete_lattice.independent (set.range A)`, these provide a gradation of `⨆ i, A i`, and the mapping `⨁ i, A i →+ ⨆ i, A i` can be obtained as `direct_sum.to_monoid (λ i, add_submonoid.inclusion $ le_supr A i)`. ## tags graded ring, filtered ring, direct sum, add_submonoid -/ variables {ι : Type*} [decidable_eq ι] namespace direct_sum open_locale direct_sum /-! ### Typeclasses -/ section defs variables (A : ι → Type*) /-- A graded version of `has_one`, which must be of grade 0. -/ class ghas_one [has_zero ι] := (one : A 0) /-- A graded version of `has_mul` that also subsumes `distrib` and `mul_zero_class` by requiring the multiplication be an `add_monoid_hom`. Multiplication combines grades additively, like `add_monoid_algebra`. -/ class ghas_mul [has_add ι] [Π i, add_comm_monoid (A i)] := (mul {i j} : A i →+ A j →+ A (i + j)) variables {A} /-- `direct_sum.ghas_one` implies a `has_one (Σ i, A i)`, although this is only used as an instance locally to define notation in `direct_sum.gmonoid`. -/ def ghas_one.to_sigma_has_one [has_zero ι] [ghas_one A] : has_one (Σ i, A i) := ⟨⟨_, ghas_one.one⟩⟩ /-- `direct_sum.ghas_mul` implies a `has_mul (Σ i, A i)`, although this is only used as an instance locally to define notation in `direct_sum.gmonoid`. -/ def ghas_mul.to_sigma_has_mul [has_add ι] [Π i, add_comm_monoid (A i)] [ghas_mul A] : has_mul (Σ i, A i) := ⟨λ (x y : Σ i, A i), ⟨_, ghas_mul.mul x.snd y.snd⟩⟩ end defs section defs variables (A : ι → Type*) local attribute [instance] ghas_one.to_sigma_has_one local attribute [instance] ghas_mul.to_sigma_has_mul /-- A graded version of `monoid`. -/ class gmonoid [add_monoid ι] [Π i, add_comm_monoid (A i)] extends ghas_mul A, ghas_one A := (one_mul (a : Σ i, A i) : 1 * a = a) (mul_one (a : Σ i, A i) : a * 1 = a) (mul_assoc (a : Σ i, A i) (b : Σ i, A i) (c : Σ i, A i) : a * b * c = a * (b * c)) /-- A graded version of `comm_monoid`. -/ class gcomm_monoid [add_comm_monoid ι] [Π i, add_comm_monoid (A i)] extends gmonoid A := (mul_comm (a : Σ i, A i) (b : Σ i, A i) : a * b = b * a) end defs /-! ### Shorthands for creating the above typeclasses -/ section shorthands variables {R : Type*} /-! #### From `add_submonoid`s -/ /-- Build a `ghas_one` instance for a collection of `add_submonoid`s. -/ @[simps one] def ghas_one.of_add_submonoids [semiring R] [has_zero ι] (carriers : ι → add_submonoid R) (one_mem : (1 : R) ∈ carriers 0) : ghas_one (λ i, carriers i) := { one := ⟨1, one_mem⟩ } -- `@[simps]` doesn't generate a useful lemma, so we state one manually below. /-- Build a `ghas_mul` instance for a collection of `add_submonoids`. -/ def ghas_mul.of_add_submonoids [semiring R] [has_add ι] (carriers : ι → add_submonoid R) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : ghas_mul (λ i, carriers i) := { mul := λ i j, { to_fun := λ a, { to_fun := λ b, ⟨(a * b : R), mul_mem a b⟩, map_add' := λ _ _, subtype.ext (mul_add _ _ _), map_zero' := subtype.ext (mul_zero _), }, map_add' := λ _ _, add_monoid_hom.ext $ λ _, subtype.ext (add_mul _ _ _), map_zero' := add_monoid_hom.ext $ λ _, subtype.ext (zero_mul _) }, } -- `@[simps]` doesn't generate this well @[simp] lemma ghas_mul.of_add_submonoids_mul [semiring R] [has_add ι] (carriers : ι → add_submonoid R) (mul_mem) {i j} (a : carriers i) (b : carriers j) : @ghas_mul.mul _ _ _ _ _ (ghas_mul.of_add_submonoids carriers mul_mem) i j a b = ⟨a * b, mul_mem a b⟩ := rfl /-- Build a `gmonoid` instance for a collection of `add_submonoid`s. -/ @[simps to_ghas_one to_ghas_mul] def gmonoid.of_add_submonoids [semiring R] [add_monoid ι] (carriers : ι → add_submonoid R) (one_mem : (1 : R) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : gmonoid (λ i, carriers i) := { one_mul := λ ⟨i, a, h⟩, sigma.subtype_ext (zero_add _) (one_mul _), mul_one := λ ⟨i, a, h⟩, sigma.subtype_ext (add_zero _) (mul_one _), mul_assoc := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩ ⟨k, c, hc⟩, sigma.subtype_ext (add_assoc _ _ _) (mul_assoc _ _ _), ..ghas_one.of_add_submonoids carriers one_mem, ..ghas_mul.of_add_submonoids carriers mul_mem } /-- Build a `gcomm_monoid` instance for a collection of `add_submonoid`s. -/ @[simps to_gmonoid] def gcomm_monoid.of_add_submonoids [comm_semiring R] [add_comm_monoid ι] (carriers : ι → add_submonoid R) (one_mem : (1 : R) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : gcomm_monoid (λ i, carriers i) := { mul_comm := λ ⟨i, a, ha⟩ ⟨j, b, hb⟩, sigma.subtype_ext (add_comm _ _) (mul_comm _ _), ..gmonoid.of_add_submonoids carriers one_mem mul_mem} /-! #### From `add_subgroup`s -/ /-- Build a `ghas_one` instance for a collection of `add_subgroup`s. -/ @[simps one] def ghas_one.of_add_subgroups [ring R] [has_zero ι] (carriers : ι → add_subgroup R) (one_mem : (1 : R) ∈ carriers 0) : ghas_one (λ i, carriers i) := ghas_one.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem -- `@[simps]` doesn't generate a useful lemma, so we state one manually below. /-- Build a `ghas_mul` instance for a collection of `add_subgroup`s. -/ def ghas_mul.of_add_subgroups [ring R] [has_add ι] (carriers : ι → add_subgroup R) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : ghas_mul (λ i, carriers i) := ghas_mul.of_add_submonoids (λ i, (carriers i).to_add_submonoid) mul_mem -- `@[simps]` doesn't generate this well @[simp] lemma ghas_mul.of_add_subgroups_mul [ring R] [has_add ι] (carriers : ι → add_subgroup R) (mul_mem) {i j} (a : carriers i) (b : carriers j) : @ghas_mul.mul _ _ _ _ _ (ghas_mul.of_add_subgroups carriers mul_mem) i j a b = ⟨a * b, mul_mem a b⟩ := rfl /-- Build a `gmonoid` instance for a collection of `add_subgroup`s. -/ @[simps to_ghas_one to_ghas_mul] def gmonoid.of_add_subgroups [ring R] [add_monoid ι] (carriers : ι → add_subgroup R) (one_mem : (1 : R) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : gmonoid (λ i, carriers i) := gmonoid.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem mul_mem /-- Build a `gcomm_monoid` instance for a collection of `add_subgroup`s. -/ @[simps to_gmonoid] def gcomm_monoid.of_add_subgroups [comm_ring R] [add_comm_monoid ι] (carriers : ι → add_subgroup R) (one_mem : (1 : R) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : R) ∈ carriers (i + j)) : gcomm_monoid (λ i, carriers i) := gcomm_monoid.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem mul_mem /-! #### From `submodules`s -/ variables {A : Type*} /-- Build a `ghas_one` instance for a collection of `submodule`s. -/ @[simps one] def ghas_one.of_submodules [comm_semiring R] [semiring A] [algebra R A] [has_zero ι] (carriers : ι → submodule R A) (one_mem : (1 : A) ∈ carriers 0) : ghas_one (λ i, carriers i) := ghas_one.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem -- `@[simps]` doesn't generate a useful lemma, so we state one manually below. /-- Build a `ghas_mul` instance for a collection of `submodule`s. -/ def ghas_mul.of_submodules [comm_semiring R] [semiring A] [algebra R A] [has_add ι] (carriers : ι → submodule R A) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : A) ∈ carriers (i + j)) : ghas_mul (λ i, carriers i) := ghas_mul.of_add_submonoids (λ i, (carriers i).to_add_submonoid) mul_mem -- `@[simps]` doesn't generate this well @[simp] lemma ghas_mul.of_submodules_mul [comm_semiring R] [semiring A] [algebra R A] [has_add ι] (carriers : ι → submodule R A) (mul_mem) {i j} (a : carriers i) (b : carriers j) : @ghas_mul.mul _ _ _ _ _ (ghas_mul.of_submodules carriers mul_mem) i j a b = ⟨a * b, mul_mem a b⟩ := rfl /-- Build a `gmonoid` instance for a collection of `submodules`s. -/ @[simps to_ghas_one to_ghas_mul] def gmonoid.of_submodules [comm_semiring R] [semiring A] [algebra R A] [add_monoid ι] (carriers : ι → submodule R A) (one_mem : (1 : A) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : A) ∈ carriers (i + j)) : gmonoid (λ i, carriers i) := gmonoid.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem mul_mem /-- Build a `gcomm_monoid` instance for a collection of `submodules`s. -/ @[simps to_gmonoid] def gcomm_monoid.of_submodules [comm_semiring R] [comm_semiring A] [algebra R A] [add_comm_monoid ι] (carriers : ι → submodule R A) (one_mem : (1 : A) ∈ carriers 0) (mul_mem : ∀ ⦃i j⦄ (gi : carriers i) (gj : carriers j), (gi * gj : A) ∈ carriers (i + j)) : gcomm_monoid (λ i, carriers i) := gcomm_monoid.of_add_submonoids (λ i, (carriers i).to_add_submonoid) one_mem mul_mem end shorthands variables (A : ι → Type*) /-! ### Instances for `⨁ i, A i` -/ section one variables [has_zero ι] [ghas_one A] [Π i, add_comm_monoid (A i)] instance : has_one (⨁ i, A i) := { one := direct_sum.of (λ i, A i) 0 ghas_one.one} end one section mul variables [has_add ι] [Π i, add_comm_monoid (A i)] [ghas_mul A] open add_monoid_hom (map_zero map_add flip_apply coe_comp comp_hom_apply_apply) /-- The multiplication from the `has_mul` instance, as a bundled homomorphism. -/ def mul_hom : (⨁ i, A i) →+ (⨁ i, A i) →+ ⨁ i, A i := direct_sum.to_add_monoid $ λ i, add_monoid_hom.flip $ direct_sum.to_add_monoid $ λ j, add_monoid_hom.flip $ (direct_sum.of A _).comp_hom.comp ghas_mul.mul instance : has_mul (⨁ i, A i) := { mul := λ a b, mul_hom A a b } instance : mul_zero_class (⨁ i, A i) := { mul := (*), zero := 0, zero_mul := λ a, by { unfold has_mul.mul, simp only [map_zero, add_monoid_hom.zero_apply]}, mul_zero := λ a, by { unfold has_mul.mul, simp only [map_zero] } } instance : distrib (⨁ i, A i) := { mul := (*), add := (+), left_distrib := λ a b c, by { unfold has_mul.mul, simp only [map_add]}, right_distrib := λ a b c, by { unfold has_mul.mul, simp only [map_add, add_monoid_hom.add_apply]}} variables {A} lemma mul_hom_of_of {i j} (a : A i) (b : A j) : mul_hom A (of _ i a) (of _ j b) = of _ (i + j) (ghas_mul.mul a b) := begin unfold mul_hom, rw [to_add_monoid_of, flip_apply, to_add_monoid_of, flip_apply, coe_comp, function.comp_app, comp_hom_apply_apply, coe_comp, function.comp_app], end lemma of_mul_of {i j} (a : A i) (b : A j) : of _ i a * of _ j b = of _ (i + j) (ghas_mul.mul a b) := mul_hom_of_of a b end mul section semiring variables [Π i, add_comm_monoid (A i)] [add_monoid ι] [gmonoid A] open add_monoid_hom (flip_hom coe_comp comp_hom_apply_apply flip_apply flip_hom_apply) private lemma one_mul (x : ⨁ i, A i) : 1 * x = x := suffices mul_hom A 1 = add_monoid_hom.id (⨁ i, A i), from add_monoid_hom.congr_fun this x, begin apply add_hom_ext, intros i xi, unfold has_one.one, rw mul_hom_of_of, exact dfinsupp.single_eq_of_sigma_eq (gmonoid.one_mul ⟨i, xi⟩), end private lemma mul_one (x : ⨁ i, A i) : x * 1 = x := suffices (mul_hom A).flip 1 = add_monoid_hom.id (⨁ i, A i), from add_monoid_hom.congr_fun this x, begin apply add_hom_ext, intros i xi, unfold has_one.one, rw [flip_apply, mul_hom_of_of], exact dfinsupp.single_eq_of_sigma_eq (gmonoid.mul_one ⟨i, xi⟩), end private lemma mul_assoc (a b c : ⨁ i, A i) : a * b * c = a * (b * c) := suffices (mul_hom A).comp_hom.comp (mul_hom A) -- `λ a b c, a * b * c` as a bundled hom = (add_monoid_hom.comp_hom flip_hom $ -- `λ a b c, a * (b * c)` as a bundled hom (mul_hom A).flip.comp_hom.comp (mul_hom A)).flip, from add_monoid_hom.congr_fun (add_monoid_hom.congr_fun (add_monoid_hom.congr_fun this a) b) c, begin ext ai ax bi bx ci cx : 6, dsimp only [coe_comp, function.comp_app, comp_hom_apply_apply, flip_apply, flip_hom_apply], rw [mul_hom_of_of, mul_hom_of_of, mul_hom_of_of, mul_hom_of_of], exact dfinsupp.single_eq_of_sigma_eq (gmonoid.mul_assoc ⟨ai, ax⟩ ⟨bi, bx⟩ ⟨ci, cx⟩), end /-- The `semiring` structure derived from `gmonoid A`. -/ instance semiring : semiring (⨁ i, A i) := { one := 1, mul := (*), zero := 0, add := (+), one_mul := one_mul A, mul_one := mul_one A, mul_assoc := mul_assoc A, ..direct_sum.mul_zero_class A, ..direct_sum.distrib A, ..direct_sum.add_comm_monoid _ _, } end semiring section comm_semiring variables [Π i, add_comm_monoid (A i)] [add_comm_monoid ι] [gcomm_monoid A] private lemma mul_comm (a b : ⨁ i, A i) : a * b = b * a := suffices mul_hom A = (mul_hom A).flip, from add_monoid_hom.congr_fun (add_monoid_hom.congr_fun this a) b, begin apply add_hom_ext, intros ai ax, apply add_hom_ext, intros bi bx, rw [add_monoid_hom.flip_apply, mul_hom_of_of, mul_hom_of_of], exact dfinsupp.single_eq_of_sigma_eq (gcomm_monoid.mul_comm ⟨ai, ax⟩ ⟨bi, bx⟩), end /-- The `comm_semiring` structure derived from `gcomm_monoid A`. -/ instance comm_semiring : comm_semiring (⨁ i, A i) := { one := 1, mul := (*), zero := 0, add := (+), mul_comm := mul_comm A, ..direct_sum.semiring _, } end comm_semiring section ring variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gmonoid A] /-- The `ring` derived from `gmonoid A`. -/ instance ring : ring (⨁ i, A i) := { one := 1, mul := (*), zero := 0, add := (+), neg := has_neg.neg, ..(direct_sum.semiring _), ..(direct_sum.add_comm_group _), } end ring section comm_ring variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gcomm_monoid A] /-- The `comm_ring` derived from `gcomm_monoid A`. -/ instance comm_ring : comm_ring (⨁ i, A i) := { one := 1, mul := (*), zero := 0, add := (+), neg := has_neg.neg, ..(direct_sum.ring _), ..(direct_sum.comm_semiring _), } end comm_ring /-! ### Instances for `A 0` The various `g*` instances are enough to promote the `add_comm_monoid (A 0)` structure to various types of multiplicative structure. -/ section grade_zero section one variables [has_zero ι] [ghas_one A] [Π i, add_comm_monoid (A i)] /-- `1 : A 0` is the value provided in `direct_sum.ghas_one.one`. -/ @[nolint unused_arguments] instance grade_zero.has_one : has_one (A 0) := ⟨ghas_one.one⟩ @[simp] lemma of_zero_one : of _ 0 (1 : A 0) = 1 := rfl end one section mul variables [add_monoid ι] [Π i, add_comm_monoid (A i)] [ghas_mul A] /-- `(•) : A 0 → A i → A i` is the value provided in `direct_sum.ghas_mul.mul`, composed with an `eq.rec` to turn `A (0 + i)` into `A i`. -/ instance grade_zero.has_scalar (i : ι) : has_scalar (A 0) (A i) := { smul := λ x y, (zero_add i).rec (ghas_mul.mul x y) } /-- `(*) : A 0 → A 0 → A 0` is the value provided in `direct_sum.ghas_mul.mul`, composed with an `eq.rec` to turn `A (0 + 0)` into `A 0`. -/ instance grade_zero.has_mul : has_mul (A 0) := { mul := (•) } @[simp]lemma grade_zero.smul_eq_mul (a b : A 0) : a • b = a * b := rfl @[simp] lemma of_zero_smul {i} (a : A 0) (b : A i) : of _ _ (a • b) = of _ _ a * of _ _ b := begin rw of_mul_of, dsimp [has_mul.mul, direct_sum.of, dfinsupp.single_add_hom_apply], congr' 1, rw zero_add, apply eq_rec_heq, end @[simp] lemma of_zero_mul (a b : A 0) : of _ 0 (a * b) = of _ 0 a * of _ 0 b:= of_zero_smul A a b instance grade_zero.mul_zero_class : mul_zero_class (A 0) := function.injective.mul_zero_class (of A 0) dfinsupp.single_injective (of A 0).map_zero (of_zero_mul A) instance grade_zero.distrib : distrib (A 0) := function.injective.distrib (of A 0) dfinsupp.single_injective (of A 0).map_add (of_zero_mul A) instance grade_zero.smul_with_zero (i : ι) : smul_with_zero (A 0) (A i) := begin letI := smul_with_zero.comp_hom (⨁ i, A i) (of A 0).to_zero_hom, refine dfinsupp.single_injective.smul_with_zero (of A i).to_zero_hom (of_zero_smul A), end end mul section semiring variables [Π i, add_comm_monoid (A i)] [add_monoid ι] [gmonoid A] /-- The `semiring` structure derived from `gmonoid A`. -/ instance grade_zero.semiring : semiring (A 0) := function.injective.semiring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A) /-- `of A 0` is a `ring_hom`, using the `direct_sum.grade_zero.semiring` structure. -/ def of_zero_ring_hom : A 0 →+* (⨁ i, A i) := { map_one' := of_zero_one A, map_mul' := of_zero_mul A, ..(of _ 0) } /-- Each grade `A i` derives a `A 0`-module structure from `gmonoid A`. Note that this results in an overall `module (A 0) (⨁ i, A i)` structure via `direct_sum.module`. -/ instance grade_zero.module {i} : module (A 0) (A i) := begin letI := module.comp_hom (⨁ i, A i) (of_zero_ring_hom A), exact dfinsupp.single_injective.module (A 0) (of A i) (λ a, of_zero_smul A a), end end semiring section comm_semiring variables [Π i, add_comm_monoid (A i)] [add_comm_monoid ι] [gcomm_monoid A] /-- The `comm_semiring` structure derived from `gcomm_monoid A`. -/ instance grade_zero.comm_semiring : comm_semiring (A 0) := function.injective.comm_semiring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A) end comm_semiring section ring variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gmonoid A] /-- The `ring` derived from `gmonoid A`. -/ instance grade_zero.ring : ring (A 0) := function.injective.ring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A) (of A 0).map_neg (of A 0).map_sub end ring section comm_ring variables [Π i, add_comm_group (A i)] [add_comm_monoid ι] [gcomm_monoid A] /-- The `comm_ring` derived from `gcomm_monoid A`. -/ instance grade_zero.comm_ring : comm_ring (A 0) := function.injective.comm_ring (of A 0) dfinsupp.single_injective (of A 0).map_zero (of_zero_one A) (of A 0).map_add (of_zero_mul A) (of A 0).map_neg (of A 0).map_sub end comm_ring end grade_zero section to_semiring variables {R : Type*} [Π i, add_comm_monoid (A i)] [add_monoid ι] [gmonoid A] [semiring R] variables {A} /-- If two ring homomorphisms from `⨁ i, A i` are equal on each `of A i y`, then they are equal. See note [partially-applied ext lemmas]. -/ @[ext] lemma ring_hom_ext' (F G : (⨁ i, A i) →+* R) (h : ∀ i, (F : (⨁ i, A i) →+ R).comp (of _ i) = (G : (⨁ i, A i) →+ R).comp (of _ i)) : F = G := ring_hom.coe_add_monoid_hom_injective $ direct_sum.add_hom_ext' h /-- A family of `add_monoid_hom`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul` describes a `ring_hom`s on `⨁ i, A i`. This is a stronger version of `direct_sum.to_monoid`. Of particular interest is the case when `A i` are bundled subojects, `f` is the family of coercions such as `add_submonoid.subtype (A i)`, and the `[gmonoid A]` structure originates from `direct_sum.gmonoid.of_add_submonoids`, in which case the proofs about `ghas_one` and `ghas_mul` can be discharged by `rfl`. -/ @[simps] def to_semiring (f : Π i, A i →+ R) (hone : f _ (ghas_one.one) = 1) (hmul : ∀ {i j} (ai : A i) (aj : A j), f _ (ghas_mul.mul ai aj) = f _ ai * f _ aj) : (⨁ i, A i) →+* R := { to_fun := to_add_monoid f, map_one' := begin change (to_add_monoid f) (of _ 0 _) = 1, rw to_add_monoid_of, exact hone end, map_mul' := begin rw (to_add_monoid f).map_mul_iff, ext xi xv yi yv : 4, show to_add_monoid f (of A xi xv * of A yi yv) = to_add_monoid f (of A xi xv) * to_add_monoid f (of A yi yv), rw [of_mul_of, to_add_monoid_of, to_add_monoid_of, to_add_monoid_of], exact hmul _ _, end, .. to_add_monoid f} @[simp] lemma to_semiring_of (f : Π i, A i →+ R) (hone hmul) (i : ι) (x : A i) : to_semiring f hone hmul (of _ i x) = f _ x := to_add_monoid_of f i x @[simp] lemma to_semiring_coe_add_monoid_hom (f : Π i, A i →+ R) (hone hmul): (to_semiring f hone hmul : (⨁ i, A i) →+ R) = to_add_monoid f := rfl /-- Families of `add_monoid_hom`s preserving `direct_sum.ghas_one.one` and `direct_sum.ghas_mul.mul` are isomorphic to `ring_hom`s on `⨁ i, A i`. This is a stronger version of `dfinsupp.lift_add_hom`. -/ @[simps] def lift_ring_hom : {f : Π {i}, A i →+ R // f (ghas_one.one) = 1 ∧ ∀ {i j} (ai : A i) (aj : A j), f (ghas_mul.mul ai aj) = f ai * f aj} ≃ ((⨁ i, A i) →+* R) := { to_fun := λ f, to_semiring f.1 f.2.1 f.2.2, inv_fun := λ F, ⟨λ i, (F : (⨁ i, A i) →+ R).comp (of _ i), begin simp only [add_monoid_hom.comp_apply, ring_hom.coe_add_monoid_hom], rw ←F.map_one, refl end, λ i j ai aj, begin simp only [add_monoid_hom.comp_apply, ring_hom.coe_add_monoid_hom], rw [←F.map_mul, of_mul_of], end⟩, left_inv := λ f, begin ext xi xv, exact to_add_monoid_of f.1 xi xv, end, right_inv := λ F, begin apply ring_hom.coe_add_monoid_hom_injective, ext xi xv, simp only [ring_hom.coe_add_monoid_hom_mk, direct_sum.to_add_monoid_of, add_monoid_hom.mk_coe, add_monoid_hom.comp_apply, to_semiring_coe_add_monoid_hom], end} end to_semiring end direct_sum /-! ### Concrete instances -/ /-- A direct sum of copies of a `semiring` inherits the multiplication structure. -/ instance semiring.direct_sum_gmonoid {R : Type*} [add_monoid ι] [semiring R] : direct_sum.gmonoid (λ i : ι, R) := { mul := λ i j, add_monoid_hom.mul, one_mul := λ a, sigma.ext (zero_add _) (heq_of_eq (one_mul _)), mul_one := λ a, sigma.ext (add_zero _) (heq_of_eq (mul_one _)), mul_assoc := λ a b c, sigma.ext (add_assoc _ _ _) (heq_of_eq (mul_assoc _ _ _)), one := 1 } @[simp] lemma semiring.direct_sum_mul {R : Type*} [add_monoid ι] [semiring R] {i j} (x y : R) : @direct_sum.ghas_mul.mul _ _ (λ _ : ι, R) _ _ _ i j x y = x * y := rfl open_locale direct_sum -- To check the lemma above does match example {R : Type*} [add_monoid ι] [semiring R] (i j : ι) (a b : R) : (direct_sum.of _ i a * direct_sum.of _ j b : ⨁ i, R) = direct_sum.of _ (i + j) (by exact a * b) := by rw [direct_sum.of_mul_of, semiring.direct_sum_mul] /-- A direct sum of copies of a `comm_semiring` inherits the commutative multiplication structure. -/ instance comm_semiring.direct_sum_gcomm_monoid {R : Type*} [add_comm_monoid ι] [comm_semiring R] : direct_sum.gcomm_monoid (λ i : ι, R) := { mul_comm := λ a b, sigma.ext (add_comm _ _) (heq_of_eq (mul_comm _ _)), .. semiring.direct_sum_gmonoid } namespace submodule variables {R A : Type*} [comm_semiring R] /-- A direct sum of powers of a submodule of an algebra has a multiplicative structure. -/ instance nat_power_direct_sum_gmonoid [semiring A] [algebra R A] (S : submodule R A) : direct_sum.gmonoid (λ i : ℕ, ↥(S ^ i)) := direct_sum.gmonoid.of_submodules _ (by { rw [←one_le, pow_zero], exact le_rfl }) (λ i j p q, by { rw pow_add, exact submodule.mul_mem_mul p.prop q.prop }) /-- A direct sum of powers of a submodule of a commutative algebra has a commutative multiplicative structure. -/ instance nat_power_direct_sum_gcomm_monoid [comm_semiring A] [algebra R A] (S : submodule R A) : direct_sum.gcomm_monoid (λ i : ℕ, ↥(S ^ i)) := direct_sum.gcomm_monoid.of_submodules _ (by { rw [←one_le, pow_zero], exact le_rfl }) (λ i j p q, by { rw pow_add, exact submodule.mul_mem_mul p.prop q.prop }) end submodule
6fc3a2838b516f195cfa81c9e3d346c5ac2ea7ba
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/monoid_algebra/to_direct_sum.lean
59c97d5c9f9a6c64a93de3df689b738f83680bbf
[ "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
7,861
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.direct_sum.algebra import algebra.monoid_algebra.basic import data.finsupp.to_dfinsupp /-! # Conversion between `add_monoid_algebra` and homogenous `direct_sum` This module provides conversions between `add_monoid_algebra` and `direct_sum`. The latter is essentially a dependent version of the former. Note that since `direct_sum.has_mul` combines indices additively, there is no equivalent to `monoid_algebra`. ## Main definitions * `add_monoid_algebra.to_direct_sum : add_monoid_algebra M ι → (⨁ i : ι, M)` * `direct_sum.to_add_monoid_algebra : (⨁ i : ι, M) → add_monoid_algebra M ι` * Bundled equiv versions of the above: * `add_monoid_algebra_equiv_direct_sum : add_monoid_algebra M ι ≃ (⨁ i : ι, M)` * `add_monoid_algebra_add_equiv_direct_sum : add_monoid_algebra M ι ≃+ (⨁ i : ι, M)` * `add_monoid_algebra_ring_equiv_direct_sum R : add_monoid_algebra M ι ≃+* (⨁ i : ι, M)` * `add_monoid_algebra_alg_equiv_direct_sum R : add_monoid_algebra A ι ≃ₐ[R] (⨁ i : ι, A)` ## Theorems The defining feature of these operations is that they map `finsupp.single` to `direct_sum.of` and vice versa: * `add_monoid_algebra.to_direct_sum_single` * `direct_sum.to_add_monoid_algebra_of` as well as preserving arithmetic operations. For the bundled equivalences, we provide lemmas that they reduce to `add_monoid_algebra.to_direct_sum`: * `add_monoid_algebra_add_equiv_direct_sum_apply` * `add_monoid_algebra_lequiv_direct_sum_apply` * `add_monoid_algebra_add_equiv_direct_sum_symm_apply` * `add_monoid_algebra_lequiv_direct_sum_symm_apply` ## Implementation notes This file largely just copies the API of `data/finsupp/to_dfinsupp`, and reuses the proofs. Recall that `add_monoid_algebra M ι` is defeq to `ι →₀ M` and `⨁ i : ι, M` is defeq to `Π₀ i : ι, M`. Note that there is no `add_monoid_algebra` equivalent to `finsupp.single`, so many statements still involve this definition. -/ variables {ι : Type*} {R : Type*} {M : Type*} {A : Type*} open_locale direct_sum /-! ### Basic definitions and lemmas -/ section defs /-- Interpret a `add_monoid_algebra` as a homogenous `direct_sum`. -/ def add_monoid_algebra.to_direct_sum [semiring M] (f : add_monoid_algebra M ι) : ⨁ i : ι, M := finsupp.to_dfinsupp f section variables [decidable_eq ι] [semiring M] @[simp] lemma add_monoid_algebra.to_direct_sum_single (i : ι) (m : M) : add_monoid_algebra.to_direct_sum (finsupp.single i m) = direct_sum.of _ i m := finsupp.to_dfinsupp_single i m variables [Π m : M, decidable (m ≠ 0)] /-- Interpret a homogenous `direct_sum` as a `add_monoid_algebra`. -/ def direct_sum.to_add_monoid_algebra (f : ⨁ i : ι, M) : add_monoid_algebra M ι := dfinsupp.to_finsupp f @[simp] lemma direct_sum.to_add_monoid_algebra_of (i : ι) (m : M) : (direct_sum.of _ i m : ⨁ i : ι, M).to_add_monoid_algebra = finsupp.single i m := dfinsupp.to_finsupp_single i m @[simp] lemma add_monoid_algebra.to_direct_sum_to_add_monoid_algebra (f : add_monoid_algebra M ι) : f.to_direct_sum.to_add_monoid_algebra = f := finsupp.to_dfinsupp_to_finsupp f @[simp] lemma direct_sum.to_add_monoid_algebra_to_direct_sum (f : ⨁ i : ι, M) : f.to_add_monoid_algebra.to_direct_sum = f := dfinsupp.to_finsupp_to_dfinsupp f end end defs /-! ### Lemmas about arithmetic operations -/ section lemmas namespace add_monoid_algebra @[simp] lemma to_direct_sum_zero [semiring M] : (0 : add_monoid_algebra M ι).to_direct_sum = 0 := finsupp.to_dfinsupp_zero @[simp] lemma to_direct_sum_add [semiring M] (f g : add_monoid_algebra M ι) : (f + g).to_direct_sum = f.to_direct_sum + g.to_direct_sum := finsupp.to_dfinsupp_add _ _ @[simp] lemma to_direct_sum_mul [decidable_eq ι] [add_monoid ι] [semiring M] (f g : add_monoid_algebra M ι) : (f * g).to_direct_sum = f.to_direct_sum * g.to_direct_sum := begin let to_hom : add_monoid_algebra M ι →+ (⨁ i : ι, M) := ⟨to_direct_sum, to_direct_sum_zero, to_direct_sum_add⟩, show to_hom (f * g) = to_hom f * to_hom g, revert f g, rw add_monoid_hom.map_mul_iff, ext xi xv yi yv : 4, dsimp only [add_monoid_hom.comp_apply, add_monoid_hom.compl₂_apply, add_monoid_hom.compr₂_apply, add_monoid_hom.mul_apply, add_equiv.coe_to_add_monoid_hom, finsupp.single_add_hom_apply], simp only [add_monoid_algebra.single_mul_single, to_hom, add_monoid_hom.coe_mk, add_monoid_algebra.to_direct_sum_single, direct_sum.of_mul_of, has_mul.ghas_mul_mul] end end add_monoid_algebra namespace direct_sum variables [decidable_eq ι] @[simp] lemma to_add_monoid_algebra_zero [semiring M] [Π m : M, decidable (m ≠ 0)] : to_add_monoid_algebra 0 = (0 : add_monoid_algebra M ι) := dfinsupp.to_finsupp_zero @[simp] lemma to_add_monoid_algebra_add [semiring M] [Π m : M, decidable (m ≠ 0)] (f g : ⨁ i : ι, M) : (f + g).to_add_monoid_algebra = to_add_monoid_algebra f + to_add_monoid_algebra g := dfinsupp.to_finsupp_add _ _ @[simp] lemma to_add_monoid_algebra_mul [add_monoid ι] [semiring M] [Π m : M, decidable (m ≠ 0)] (f g : ⨁ i : ι, M) : (f * g).to_add_monoid_algebra = to_add_monoid_algebra f * to_add_monoid_algebra g := begin apply_fun add_monoid_algebra.to_direct_sum, { simp }, { apply function.left_inverse.injective, apply add_monoid_algebra.to_direct_sum_to_add_monoid_algebra } end end direct_sum end lemmas /-! ### Bundled `equiv`s -/ section equivs /-- `add_monoid_algebra.to_direct_sum` and `direct_sum.to_add_monoid_algebra` together form an equiv. -/ @[simps {fully_applied := ff}] def add_monoid_algebra_equiv_direct_sum [decidable_eq ι] [semiring M] [Π m : M, decidable (m ≠ 0)] : add_monoid_algebra M ι ≃ (⨁ i : ι, M) := { to_fun := add_monoid_algebra.to_direct_sum, inv_fun := direct_sum.to_add_monoid_algebra, ..finsupp_equiv_dfinsupp } /-- The additive version of `add_monoid_algebra.to_add_monoid_algebra`. Note that this is `noncomputable` because `add_monoid_algebra.has_add` is noncomputable. -/ @[simps {fully_applied := ff}] noncomputable def add_monoid_algebra_add_equiv_direct_sum [decidable_eq ι] [semiring M] [Π m : M, decidable (m ≠ 0)] : add_monoid_algebra M ι ≃+ (⨁ i : ι, M) := { to_fun := add_monoid_algebra.to_direct_sum, inv_fun := direct_sum.to_add_monoid_algebra, map_add' := add_monoid_algebra.to_direct_sum_add, .. add_monoid_algebra_equiv_direct_sum} /-- The ring version of `add_monoid_algebra.to_add_monoid_algebra`. Note that this is `noncomputable` because `add_monoid_algebra.has_add` is noncomputable. -/ @[simps {fully_applied := ff}] noncomputable def add_monoid_algebra_ring_equiv_direct_sum [decidable_eq ι] [add_monoid ι] [semiring M] [Π m : M, decidable (m ≠ 0)] : add_monoid_algebra M ι ≃+* ⨁ i : ι, M := { to_fun := add_monoid_algebra.to_direct_sum, inv_fun := direct_sum.to_add_monoid_algebra, map_mul' := add_monoid_algebra.to_direct_sum_mul, ..(add_monoid_algebra_add_equiv_direct_sum : add_monoid_algebra M ι ≃+ ⨁ i : ι, M) } /-- The algebra version of `add_monoid_algebra.to_add_monoid_algebra`. Note that this is `noncomputable` because `add_monoid_algebra.has_add` is noncomputable. -/ @[simps {fully_applied := ff}] noncomputable def add_monoid_algebra_alg_equiv_direct_sum [decidable_eq ι] [add_monoid ι] [comm_semiring R] [semiring A] [algebra R A] [Π m : A, decidable (m ≠ 0)] : add_monoid_algebra A ι ≃ₐ[R] ⨁ i : ι, A := { to_fun := add_monoid_algebra.to_direct_sum, inv_fun := direct_sum.to_add_monoid_algebra, commutes' := λ r, add_monoid_algebra.to_direct_sum_single _ _, ..(add_monoid_algebra_ring_equiv_direct_sum : add_monoid_algebra A ι ≃+* ⨁ i : ι, A) } end equivs
8534a99c085db9cf78e8ed4e965469d08b8ace72
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/localization/opposite.lean
97b70abd9b35482acae0dfba6937efcd83f89a26
[ "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,073
lean
/- Copyright (c) 2022 Joël Riou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joël Riou -/ import category_theory.localization.predicate /-! # Localization of the opposite category > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. If a functor `L : C ⥤ D` is a localization functor for `W : morphism_property C`, it is shown in this file that `L.op : Cᵒᵖ ⥤ Dᵒᵖ` is also a localization functor. -/ noncomputable theory open category_theory category_theory.category namespace category_theory variables {C D : Type*} [category C] [category D] {L : C ⥤ D} {W : morphism_property C} namespace localization /-- If `L : C ⥤ D` satisfies the universal property of the localisation for `W : morphism_property C`, then `L.op` also does. -/ def strict_universal_property_fixed_target.op {E : Type*} [category E] (h : strict_universal_property_fixed_target L W Eᵒᵖ): strict_universal_property_fixed_target L.op W.op E := { inverts := h.inverts.op, lift := λ F hF, (h.lift F.right_op hF.right_op).left_op, fac := λ F hF, begin convert congr_arg functor.left_op (h.fac F.right_op hF.right_op), exact F.right_op_left_op_eq.symm, end, uniq := λ F₁ F₂ eq, begin suffices : F₁.right_op = F₂.right_op, { rw [← F₁.right_op_left_op_eq, ← F₂.right_op_left_op_eq, this], }, have eq' := congr_arg functor.right_op eq, exact h.uniq _ _ eq', end, } instance is_localization_op : W.Q.op.is_localization W.op := functor.is_localization.mk' W.Q.op W.op (strict_universal_property_fixed_target_Q W _).op (strict_universal_property_fixed_target_Q W _).op end localization namespace functor instance is_localization.op [h : L.is_localization W] : L.op.is_localization W.op := is_localization.of_equivalence_target W.Q.op W.op L.op (localization.equivalence_from_model L W).op (nat_iso.op (localization.Q_comp_equivalence_from_model_functor_iso L W).symm) end functor end category_theory
9f9045de2219d1bf7a446e8ff0daa6f4dc9d667c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/dual_number.lean
9aa9098f64a4c416c4cf63044996ea33d0bc5768
[ "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
3,351
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.triv_sq_zero_ext /-! # Dual numbers The dual numbers over `R` are of the form `a + bε`, where `a` and `b` are typically elements of a commutative ring `R`, and `ε` is a symbol satisfying `ε^2 = 0`. They are a special case of `triv_sq_zero_ext R M` with `M = R`. ## Notation In the `dual_number` locale: * `R[ε]` is a shorthand for `dual_number R` * `ε` is a shorthand for `dual_number.eps` ## Main definitions * `dual_number` * `dual_number.eps` * `dual_number.lift` ## Implementation notes Rather than duplicating the API of `triv_sq_zero_ext`, this file reuses the functions there. ## References * https://en.wikipedia.org/wiki/Dual_number -/ variables {R : Type*} /-- The type of dual numbers, numbers of the form $a + bε$ where $ε^2 = 0$.-/ abbreviation dual_number (R : Type*) : Type* := triv_sq_zero_ext R R /-- The unit element $ε$ that squares to zero. -/ def dual_number.eps [has_zero R] [has_one R] : dual_number R := triv_sq_zero_ext.inr 1 localized "notation (name := dual_number.eps) `ε` := dual_number.eps" in dual_number localized "postfix (name := dual_number) `[ε]`:1025 := dual_number" in dual_number open_locale dual_number namespace dual_number open triv_sq_zero_ext @[simp] lemma fst_eps [has_zero R] [has_one R] : fst ε = (0 : R) := fst_inr _ _ @[simp] lemma snd_eps [has_zero R] [has_one R] : snd ε = (1 : R) := snd_inr _ _ /-- A version of `triv_sq_zero_ext.snd_mul` with `*` instead of `•`. -/ @[simp] lemma snd_mul [semiring R] (x y : R[ε]) : snd (x * y) = fst x * snd y + fst y * snd x := snd_mul _ _ @[simp] lemma eps_mul_eps [semiring R] : (ε * ε : R[ε]) = 0 := inr_mul_inr _ _ _ @[simp] lemma inr_eq_smul_eps [mul_zero_one_class R] (r : R) : inr r = (r • ε : R[ε]) := ext (mul_zero r).symm (mul_one r).symm /-- For two algebra morphisms out of `R[ε]` to agree, it suffices for them to agree on `ε`. -/ @[ext] lemma alg_hom_ext {A} [comm_semiring R] [semiring A] [algebra R A] ⦃f g : R[ε] →ₐ[R] A⦄ (h : f ε = g ε) : f = g := alg_hom_ext' $ linear_map.ext_ring $ h variables {A : Type*} [comm_semiring R] [semiring A] [algebra R A] /-- A universal property of the dual numbers, providing a unique `R[ε] →ₐ[R] A` for every element of `A` which squares to `0`. This isomorphism is named to match the very similar `complex.lift`. -/ @[simps {attrs := []}] def lift : {e : A // e * e = 0} ≃ (R[ε] →ₐ[R] A) := equiv.trans (show {e : A // e * e = 0} ≃ {f : R →ₗ[R] A // ∀ x y, f x * f y = 0}, from (linear_map.ring_lmap_equiv_self R ℕ A).symm.to_equiv.subtype_equiv $ λ a, begin dsimp, simp_rw smul_mul_smul, refine ⟨λ h x y, h.symm ▸ smul_zero _, λ h, by simpa using h 1 1⟩, end) triv_sq_zero_ext.lift /- When applied to `ε`, `dual_number.lift` produces the element of `A` that squares to 0. -/ @[simp] lemma lift_apply_eps (e : {e : A // e * e = 0}) : lift e (ε : R[ε]) = e := (triv_sq_zero_ext.lift_aux_apply_inr _ _ _).trans $ one_smul _ _ /- Lifting `dual_number.eps` itself gives the identity. -/ @[simp] lemma lift_eps : lift ⟨ε, by exact eps_mul_eps⟩ = alg_hom.id R R[ε] := alg_hom_ext $ lift_apply_eps _ end dual_number
dc36f81bb14e9d7af6cc7408b35ac20e40b54d63
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/W.lean
484cdd8d13388a9d74523c9da6c03aec500289a0
[ "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
4,022
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad -/ import data.equiv.list /-! # W types Given `α : Type` and `β : α → Type`, the W type determined by this data, `W β`, is the inductively defined type of trees where the nodes are labeled by elements of `α` and the children of a node labeled `a` are indexed by elements of `β a`. This file is currently a stub, awaiting a full development of the theory. Currently, the main result is that if `α` is an encodable fintype and `β a` is encodable for every `a : α`, then `W β` is encodable. This can be used to show the encodability of other inductive types, such as those that are commonly used to formalize syntax, e.g. terms and expressions in a given language. The strategy is illustrated in the example found in the file `prop_encodable` in the `archive/examples` folder of mathlib. -/ /-- Given `β : α → Type*`, `W β` is the type of finitely branching trees where nodes are labeled by elements of `α` and the children of a node labeled `a` are indexed by elements of `β a`. -/ inductive W {α : Type*} (β : α → Type*) | mk (a : α) (f : β a → W) : W instance : inhabited (W (λ (_ : unit), empty)) := ⟨W.mk unit.star empty.elim⟩ namespace W variables {α : Type*} {β : α → Type*} [Π a : α, fintype (β a)] /-- The depth of a finitely branching tree. -/ def depth : W β → ℕ | ⟨a, f⟩ := finset.sup finset.univ (λ n, depth (f n)) + 1 lemma depth_pos (t : W β) : 0 < t.depth := by { cases t, apply nat.succ_pos } lemma depth_lt_depth_mk (a : α) (f : β a → W β) (i : β a) : depth (f i) < depth ⟨a, f⟩ := nat.lt_succ_of_le (finset.le_sup (finset.mem_univ i)) end W /- Show that W types are encodable when `α` is an encodable fintype and for every `a : α`, `β a` is encodable. We define an auxiliary type `W' β n` of trees of depth at most `n`, and then we show by induction on `n` that these are all encodable. These auxiliary constructions are not interesting in and of themselves, so we mark them as `private`. -/ namespace encodable @[reducible] private def W' {α : Type*} (β : α → Type*) [Π a : α, fintype (β a)] [Π a : α, encodable (β a)] (n : ℕ) := { t : W β // t.depth ≤ n} variables {α : Type*} {β : α → Type*} [Π a : α, fintype (β a)] [Π a : α, encodable (β a)] private def encodable_zero : encodable (W' β 0) := let f : W' β 0 → empty := λ ⟨x, h⟩, false.elim $ not_lt_of_ge h (W.depth_pos _), finv : empty → W' β 0 := by { intro x, cases x} in have ∀ x, finv (f x) = x, from λ ⟨x, h⟩, false.elim $ not_lt_of_ge h (W.depth_pos _), encodable.of_left_inverse f finv this private def f (n : ℕ) : W' β (n + 1) → Σ a : α, β a → W' β n | ⟨t, h⟩ := begin cases t with a f, have h₀ : ∀ i : β a, W.depth (f i) ≤ n, from λ i, nat.le_of_lt_succ (lt_of_lt_of_le (W.depth_lt_depth_mk a f i) h), exact ⟨a, λ i : β a, ⟨f i, h₀ i⟩⟩ end private def finv (n : ℕ) : (Σ a : α, β a → W' β n) → W' β (n + 1) | ⟨a, f⟩ := let f' := λ i : β a, (f i).val in have W.depth ⟨a, f'⟩ ≤ n + 1, from add_le_add_right (finset.sup_le (λ b h, (f b).2)) 1, ⟨⟨a, f'⟩, this⟩ variables [encodable α] private def encodable_succ (n : nat) (h : encodable (W' β n)) : encodable (W' β (n + 1)) := encodable.of_left_inverse (f n) (finv n) (by { rintro ⟨⟨_, _⟩, _⟩, refl }) /-- `W` is encodable when `α` is an encodable fintype and for every `a : α`, `β a` is encodable. -/ instance : encodable (W β) := begin haveI h' : Π n, encodable (W' β n) := λ n, nat.rec_on n encodable_zero encodable_succ, let f : W β → Σ n, W' β n := λ t, ⟨t.depth, ⟨t, le_refl _⟩⟩, let finv : (Σ n, W' β n) → W β := λ p, p.2.1, have : ∀ t, finv (f t) = t, from λ t, rfl, exact encodable.of_left_inverse f finv this end end encodable
bbf329eb088ab525010300d6875478faee95e5e2
680b0d1592ce164979dab866b232f6fa743f2cc8
/library/data/equiv.lean
42829f6cad8230d438379b797afe9ba7ca609ac0
[ "Apache-2.0" ]
permissive
syohex/lean
657428ab520f8277fc18cf04bea2ad200dbae782
081ad1212b686780f3ff8a6d0e5f8a1d29a7d8bc
refs/heads/master
1,611,274,838,635
1,452,668,188,000
1,452,668,188,000
49,562,028
0
0
null
1,452,675,604,000
1,452,675,602,000
null
UTF-8
Lean
false
false
16,527
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 In the standard library we cannot assume the univalence axiom. We say two types are equivalent if they are isomorphic. Two equivalent types have the same cardinality. -/ import data.sum data.nat open function structure equiv [class] (A B : Type) := (to_fun : A → B) (inv_fun : B → A) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) namespace equiv definition perm [reducible] (A : Type) := equiv A A infix ` ≃ `:50 := equiv definition fn {A B : Type} (e : equiv A B) : A → B := @equiv.to_fun A B e infixr ` ∙ `:100 := fn definition inv {A B : Type} [e : equiv A B] : B → A := @equiv.inv_fun A B e lemma eq_of_to_fun_eq {A B : Type} : ∀ {e₁ e₂ : equiv A B}, fn e₁ = fn e₂ → e₁ = e₂ | (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) h := assert f₁ = f₂, from h, assert g₁ = g₂, from funext (λ x, assert f₁ (g₁ x) = f₂ (g₂ x), from eq.trans (r₁ x) (eq.symm (r₂ x)), have f₁ (g₁ x) = f₁ (g₂ x), by rewrite [-h at this]; exact this, show g₁ x = g₂ x, from injective_of_left_inverse l₁ this), by congruence; repeat assumption protected definition refl [refl] (A : Type) : A ≃ A := mk (@id A) (@id A) (λ x, rfl) (λ x, rfl) protected definition symm [symm] {A B : Type} : A ≃ B → B ≃ A | (mk f g h₁ h₂) := mk g f h₂ h₁ protected definition trans [trans] {A B C : Type} : A ≃ B → B ≃ C → A ≃ C | (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) := mk (f₂ ∘ f₁) (g₁ ∘ g₂) (show ∀ x, g₁ (g₂ (f₂ (f₁ x))) = x, by intros; rewrite [l₂, l₁]; reflexivity) (show ∀ x, f₂ (f₁ (g₁ (g₂ x))) = x, by intros; rewrite [r₁, r₂]; reflexivity) abbreviation id {A : Type} := equiv.refl A namespace ops postfix ⁻¹ := equiv.symm postfix ⁻¹ := equiv.inv notation e₁ ∘ e₂ := equiv.trans e₂ e₁ end ops open equiv.ops lemma id_apply {A : Type} (x : A) : id ∙ x = x := rfl lemma compose_apply {A B C : Type} (g : B ≃ C) (f : A ≃ B) (x : A) : (g ∘ f) ∙ x = g ∙ f ∙ x := begin cases g, cases f, esimp end lemma inverse_apply_apply {A B : Type} : ∀ (e : A ≃ B) (x : A), e⁻¹ ∙ e ∙ x = x | (mk f₁ g₁ l₁ r₁) x := begin unfold [equiv.symm, fn], rewrite l₁ end lemma eq_iff_eq_of_injective {A B : Type} {f : A → B} (inj : injective f) (a b : A) : f a = f b ↔ a = b := iff.intro (suppose f a = f b, inj this) (suppose a = b, by rewrite this) lemma apply_eq_iff_eq {A B : Type} : ∀ (f : A ≃ B) (x y : A), f ∙ x = f ∙ y ↔ x = y | (mk f₁ g₁ l₁ r₁) x y := eq_iff_eq_of_injective (injective_of_left_inverse l₁) x y lemma apply_eq_iff_eq_inverse_apply {A B : Type} : ∀ (f : A ≃ B) (x : A) (y : B), f ∙ x = y ↔ x = f⁻¹ ∙ y | (mk f₁ g₁ l₁ r₁) x y := begin esimp, unfold [equiv.symm, fn], apply iff.intro, suppose f₁ x = y, by subst y; rewrite l₁, suppose x = g₁ y, by subst x; rewrite r₁ end definition false_equiv_empty : empty ≃ false := mk (λ e, empty.rec _ e) (λ h, false.rec _ h) (λ e, empty.rec _ e) (λ h, false.rec _ h) definition arrow_congr [congr] {A₁ B₁ A₂ B₂ : Type} : A₁ ≃ A₂ → B₁ ≃ B₂ → (A₁ → B₁) ≃ (A₂ → B₂) | (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) := mk (λ (h : A₁ → B₁) (a : A₂), f₂ (h (g₁ a))) (λ (h : A₂ → B₂) (a : A₁), g₂ (h (f₁ a))) (λ h, funext (λ a, by rewrite [l₁, l₂]; reflexivity)) (λ h, funext (λ a, by rewrite [r₁, r₂]; reflexivity)) section open unit definition arrow_unit_equiv_unit [simp] (A : Type) : (A → unit) ≃ unit := mk (λ f, star) (λ u, (λ f, star)) (λ f, funext (λ x, by cases (f x); reflexivity)) (λ u, by cases u; reflexivity) definition unit_arrow_equiv [simp] (A : Type) : (unit → A) ≃ A := mk (λ f, f star) (λ a, (λ u, a)) (λ f, funext (λ x, by cases x; reflexivity)) (λ u, rfl) definition empty_arrow_equiv_unit [simp] (A : Type) : (empty → A) ≃ unit := mk (λ f, star) (λ u, λ e, empty.rec _ e) (λ f, funext (λ x, empty.rec _ x)) (λ u, by cases u; reflexivity) definition false_arrow_equiv_unit [simp] (A : Type) : (false → A) ≃ unit := calc (false → A) ≃ (empty → A) : arrow_congr false_equiv_empty !equiv.refl ... ≃ unit : empty_arrow_equiv_unit end definition prod_congr [congr] {A₁ B₁ A₂ B₂ : Type} : A₁ ≃ A₂ → B₁ ≃ B₂ → (A₁ × B₁) ≃ (A₂ × B₂) | (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) := mk (λ p, match p with (a₁, b₁) := (f₁ a₁, f₂ b₁) end) (λ p, match p with (a₂, b₂) := (g₁ a₂, g₂ b₂) end) (λ p, begin cases p, esimp, rewrite [l₁, l₂], reflexivity end) (λ p, begin cases p, esimp, rewrite [r₁, r₂], reflexivity end) definition prod_comm [simp] (A B : Type) : (A × B) ≃ (B × A) := mk (λ p, match p with (a, b) := (b, a) end) (λ p, match p with (b, a) := (a, b) end) (λ p, begin cases p, esimp end) (λ p, begin cases p, esimp end) definition prod_assoc [simp] (A B C : Type) : ((A × B) × C) ≃ (A × (B × C)) := mk (λ t, match t with ((a, b), c) := (a, (b, c)) end) (λ t, match t with (a, (b, c)) := ((a, b), c) end) (λ t, begin cases t with ab c, cases ab, esimp end) (λ t, begin cases t with a bc, cases bc, esimp end) section open unit prod.ops definition prod_unit_right [simp] (A : Type) : (A × unit) ≃ A := mk (λ p, p.1) (λ a, (a, star)) (λ p, begin cases p with a u, cases u, esimp end) (λ a, rfl) definition prod_unit_left [simp] (A : Type) : (unit × A) ≃ A := calc (unit × A) ≃ (A × unit) : prod_comm ... ≃ A : prod_unit_right definition prod_empty_right [simp] (A : Type) : (A × empty) ≃ empty := mk (λ p, empty.rec _ p.2) (λ e, empty.rec _ e) (λ p, empty.rec _ p.2) (λ e, empty.rec _ e) definition prod_empty_left [simp] (A : Type) : (empty × A) ≃ empty := calc (empty × A) ≃ (A × empty) : prod_comm ... ≃ empty : prod_empty_right end section open sum definition sum_congr [congr] {A₁ B₁ A₂ B₂ : Type} : A₁ ≃ A₂ → B₁ ≃ B₂ → (A₁ + B₁) ≃ (A₂ + B₂) | (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) := mk (λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end) (λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end) (λ s, begin cases s, {esimp, rewrite l₁, reflexivity}, {esimp, rewrite l₂, reflexivity} end) (λ s, begin cases s, {esimp, rewrite r₁, reflexivity}, {esimp, rewrite r₂, reflexivity} end) open bool unit definition bool_equiv_unit_sum_unit : bool ≃ (unit + unit) := mk (λ b, match b with tt := inl star | ff := inr star end) (λ s, match s with inl star := tt | inr star := ff end) (λ b, begin cases b, esimp, esimp end) (λ s, begin cases s with u u, {cases u, esimp}, {cases u, esimp} end) definition sum_comm [simp] (A B : Type) : (A + B) ≃ (B + A) := mk (λ s, match s with inl a := inr a | inr b := inl b end) (λ s, match s with inl b := inr b | inr a := inl a end) (λ s, begin cases s, esimp, esimp end) (λ s, begin cases s, esimp, esimp end) definition sum_assoc [simp] (A B C : Type) : ((A + B) + C) ≃ (A + (B + C)) := mk (λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end) (λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end) (λ s, begin cases s with ab c, cases ab, repeat esimp end) (λ s, begin cases s with a bc, esimp, cases bc, repeat esimp end) definition sum_empty_right [simp] (A : Type) : (A + empty) ≃ A := mk (λ s, match s with inl a := a | inr e := empty.rec _ e end) (λ a, inl a) (λ s, begin cases s with a e, esimp, exact empty.rec _ e end) (λ a, rfl) definition sum_empty_left [simp] (A : Type) : (empty + A) ≃ A := calc (empty + A) ≃ (A + empty) : sum_comm ... ≃ A : sum_empty_right end section open prod.ops definition arrow_prod_equiv_prod_arrow (A B C : Type) : (C → A × B) ≃ ((C → A) × (C → B)) := mk (λ f, (λ c, (f c).1, λ c, (f c).2)) (λ p, λ c, (p.1 c, p.2 c)) (λ f, funext (λ c, begin esimp, cases f c, esimp end)) (λ p, begin cases p, esimp end) definition arrow_arrow_equiv_prod_arrow (A B C : Type) : (A → B → C) ≃ (A × B → C) := mk (λ f, λ p, f p.1 p.2) (λ f, λ a b, f (a, b)) (λ f, rfl) (λ f, funext (λ p, begin cases p, esimp end)) open sum definition sum_arrow_equiv_prod_arrow (A B C : Type) : ((A + B) → C) ≃ ((A → C) × (B → C)) := mk (λ f, (λ a, f (inl a), λ b, f (inr b))) (λ p, (λ s, match s with inl a := p.1 a | inr b := p.2 b end)) (λ f, funext (λ s, begin cases s, esimp, esimp end)) (λ p, begin cases p, esimp end) definition sum_prod_distrib (A B C : Type) : ((A + B) × C) ≃ ((A × C) + (B × C)) := mk (λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end) (λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end) (λ p, begin cases p with ab c, cases ab, repeat esimp end) (λ s, begin cases s with ac bc, cases ac, esimp, cases bc, esimp end) definition prod_sum_distrib (A B C : Type) : (A × (B + C)) ≃ ((A × B) + (A × C)) := calc (A × (B + C)) ≃ ((B + C) × A) : prod_comm ... ≃ ((B × A) + (C × A)) : sum_prod_distrib ... ≃ ((A × B) + (A × C)) : sum_congr !prod_comm !prod_comm definition bool_prod_equiv_sum (A : Type) : (bool × A) ≃ (A + A) := calc (bool × A) ≃ ((unit + unit) × A) : prod_congr bool_equiv_unit_sum_unit !equiv.refl ... ≃ (A × (unit + unit)) : prod_comm ... ≃ ((A × unit) + (A × unit)) : prod_sum_distrib ... ≃ (A + A) : sum_congr !prod_unit_right !prod_unit_right end section open sum nat unit prod.ops definition nat_equiv_nat_sum_unit : nat ≃ (nat + unit) := mk (λ n, match n with zero := inr star | succ a := inl a end) (λ s, match s with inl n := succ n | inr star := zero end) (λ n, begin cases n, repeat esimp end) (λ s, begin cases s with a u, esimp, {cases u, esimp} end) definition nat_sum_unit_equiv_nat [simp] : (nat + unit) ≃ nat := equiv.symm nat_equiv_nat_sum_unit definition nat_prod_nat_equiv_nat [simp] : (nat × nat) ≃ nat := mk (λ p, mkpair p.1 p.2) (λ n, unpair n) (λ p, begin cases p, apply unpair_mkpair end) (λ n, mkpair_unpair n) definition nat_sum_bool_equiv_nat [simp] : (nat + bool) ≃ nat := calc (nat + bool) ≃ (nat + (unit + unit)) : sum_congr !equiv.refl bool_equiv_unit_sum_unit ... ≃ ((nat + unit) + unit) : sum_assoc ... ≃ (nat + unit) : sum_congr nat_sum_unit_equiv_nat !equiv.refl ... ≃ nat : nat_sum_unit_equiv_nat open decidable definition nat_sum_nat_equiv_nat [simp] : (nat + nat) ≃ nat := mk (λ s, match s with inl n := 2*n | inr n := 2*n+1 end) (λ n, if even n then inl (n / 2) else inr ((n - 1) / 2)) (λ s, begin have two_gt_0 : 2 > zero, from dec_trivial, cases s, {esimp, rewrite [if_pos (even_two_mul _), nat.mul_div_cancel_left _ two_gt_0]}, {esimp, rewrite [if_neg (not_even_two_mul_plus_one _), nat.add_sub_cancel, nat.mul_div_cancel_left _ two_gt_0]} end) (λ n, by_cases (λ h : even n, by rewrite [if_pos h]; esimp; rewrite [nat.mul_div_cancel' (dvd_of_even h)]) (λ h : ¬ even n, begin rewrite [if_neg h], esimp, cases n, {exact absurd even_zero h}, {rewrite [-(add_one a), nat.add_sub_cancel, nat.mul_div_cancel' (dvd_of_even (even_of_odd_succ (odd_of_not_even h)))]} end)) definition prod_equiv_of_equiv_nat {A : Type} : A ≃ nat → (A × A) ≃ A := take e, calc (A × A) ≃ (nat × nat) : prod_congr e e ... ≃ nat : nat_prod_nat_equiv_nat ... ≃ A : equiv.symm e end section open decidable definition decidable_eq_of_equiv {A B : Type} [h : decidable_eq A] : A ≃ B → decidable_eq B | (mk f g l r) := take b₁ b₂, match h (g b₁) (g b₂) with | inl he := inl (assert aux : f (g b₁) = f (g b₂), from congr_arg f he, begin rewrite *r at aux, exact aux end) | inr hn := inr (λ b₁eqb₂, by subst b₁eqb₂; exact absurd rfl hn) end end definition inhabited_of_equiv {A B : Type} [h : inhabited A] : A ≃ B → inhabited B | (mk f g l r) := inhabited.mk (f (inhabited.value h)) section open subtype definition subtype_equiv_of_subtype {A B : Type} {p : A → Prop} : A ≃ B → {a : A | p a} ≃ {b : B | p b⁻¹} | (mk f g l r) := mk (λ s, match s with tag v h := tag (f v) (eq.rec_on (eq.symm (l v)) h) end) (λ s, match s with tag v h := tag (g v) (eq.rec_on (eq.symm (r v)) h) end) (λ s, begin cases s, esimp, congruence, rewrite l, reflexivity end) (λ s, begin cases s, esimp, congruence, rewrite r, reflexivity end) end section swap variable {A : Type} variable [h : decidable_eq A] include h open decidable definition swap_core (a b r : A) : A := if r = a then b else if r = b then a else r lemma swap_core_swap_core (r a b : A) : swap_core a b (swap_core a b r) = r := by_cases (suppose r = a, by_cases (suppose r = b, begin unfold swap_core, rewrite [if_pos `r = a`, if_pos (eq.refl b), -`r = a`, -`r = b`, if_pos (eq.refl r)] end) (suppose ¬ r = b, assert b ≠ a, from assume h, begin rewrite h at this, contradiction end, begin unfold swap_core, rewrite [*if_pos `r = a`, if_pos (eq.refl b), if_neg `b ≠ a`, `r = a`] end)) (suppose ¬ r = a, by_cases (suppose r = b, begin unfold swap_core, rewrite [if_neg `¬ r = a`, *if_pos `r = b`, if_pos (eq.refl a), this] end) (suppose ¬ r = b, begin unfold swap_core, rewrite [*if_neg `¬ r = a`, *if_neg `¬ r = b`, if_neg `¬ r = a`] end)) lemma swap_core_self (r a : A) : swap_core a a r = r := by_cases (suppose r = a, begin unfold swap_core, rewrite [*if_pos this, this] end) (suppose r ≠ a, begin unfold swap_core, rewrite [*if_neg this] end) lemma swap_core_comm (r a b : A) : swap_core a b r = swap_core b a r := by_cases (suppose r = a, by_cases (suppose r = b, begin unfold swap_core, rewrite [if_pos `r = a`, if_pos `r = b`, -`r = a`, -`r = b`] end) (suppose ¬ r = b, begin unfold swap_core, rewrite [*if_pos `r = a`, if_neg `¬ r = b`] end)) (suppose ¬ r = a, by_cases (suppose r = b, begin unfold swap_core, rewrite [if_neg `¬ r = a`, *if_pos `r = b`] end) (suppose ¬ r = b, begin unfold swap_core, rewrite [*if_neg `¬ r = a`, *if_neg `¬ r = b`] end)) definition swap (a b : A) : perm A := mk (swap_core a b) (swap_core a b) (λ x, abstract by rewrite swap_core_swap_core end) (λ x, abstract by rewrite swap_core_swap_core end) lemma swap_self (a : A) : swap a a = id := eq_of_to_fun_eq (funext (λ x, begin unfold [swap, fn], rewrite swap_core_self end)) lemma swap_comm (a b : A) : swap a b = swap b a := eq_of_to_fun_eq (funext (λ x, begin unfold [swap, fn], rewrite swap_core_comm end)) lemma swap_apply_def (a b : A) (x : A) : swap a b ∙ x = if x = a then b else if x = b then a else x := rfl lemma swap_apply_left (a b : A) : swap a b ∙ a = b := if_pos rfl lemma swap_apply_right (a b : A) : swap a b ∙ b = a := by_cases (suppose b = a, by rewrite [swap_apply_def, this, *if_pos rfl]) (suppose b ≠ a, by rewrite [swap_apply_def, if_pos rfl, if_neg this]) lemma swap_apply_of_ne_of_ne {a b : A} {x : A} : x ≠ a → x ≠ b → swap a b ∙ x = x := assume h₁ h₂, by rewrite [swap_apply_def, if_neg h₁, if_neg h₂] lemma swap_swap (a b : A) : swap a b ∘ swap a b = id := eq_of_to_fun_eq (funext (λ x, begin unfold [swap, fn, equiv.trans, equiv.refl], rewrite swap_core_swap_core end)) lemma swap_compose_apply (a b : A) (π : perm A) (x : A) : (swap a b ∘ π) ∙ x = if π ∙ x = a then b else if π ∙ x = b then a else π ∙ x := begin cases π, reflexivity end end swap end equiv
1a8a98514619469f68bd270c9255e016e2801e7e
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/field_theory/finite.lean
831d8c72af3fe5a9bf962ae4376c3b70fc9fe6d6
[ "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
10,083
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Joey van Langen, Casper Putz -/ import tactic.apply_fun import data.equiv.ring import data.zmod.basic import linear_algebra.basis import ring_theory.integral_domain /-! # Finite fields This file contains basic results about finite fields. Throughout most of this file, `K` denotes a finite field and `q` is notation for the cardinality of `K`. ## Main results 1. Every finite integral domain is a field (`field_of_integral_domain`). 2. The unit group of a finite field is a cyclic group of order `q - 1`. (`finite_field.is_cyclic` and `card_units`) 3. `sum_pow_units`: The sum of `x^i`, where `x` ranges over the units of `K`, is - `q-1` if `q-1 ∣ i` - `0` otherwise 4. `finite_field.card`: The cardinality `q` is a power of the characteristic of `K`. See `card'` for a variant. ## Notation Throughout most of this file, `K` denotes a finite field and `q` is notation for the cardinality of `K`. -/ variables {K : Type*} [field K] [fintype K] variables {R : Type*} [integral_domain R] local notation `q` := fintype.card K open_locale big_operators namespace finite_field open finset function section polynomial open polynomial /-- The cardinality of a field is at most `n` times the cardinality of the image of a degree `n` polynomial -/ lemma card_image_polynomial_eval [fintype R] [decidable_eq R] {p : polynomial R} (hp : 0 < p.degree) : fintype.card R ≤ nat_degree p * (univ.image (λ x, eval x p)).card := finset.card_le_mul_card_image _ _ (λ a _, calc _ = (p - C a).roots.card : congr_arg card (by simp [finset.ext_iff, mem_roots_sub_C hp, -sub_eq_add_neg]) ... ≤ _ : card_roots_sub_C' hp) /-- If `f` and `g` are quadratic polynomials, then the `f.eval a + g.eval b = 0` has a solution. -/ lemma exists_root_sum_quadratic [fintype R] {f g : polynomial R} (hf2 : degree f = 2) (hg2 : degree g = 2) (hR : fintype.card R % 2 = 1) : ∃ a b, f.eval a + g.eval b = 0 := by letI := classical.dec_eq R; exact suffices ¬ disjoint (univ.image (λ x : R, eval x f)) (univ.image (λ x : R, eval x (-g))), begin simp only [disjoint_left, mem_image] at this, push_neg at this, rcases this with ⟨x, ⟨a, _, ha⟩, ⟨b, _, hb⟩⟩, exact ⟨a, b, by rw [ha, ← hb, eval_neg, neg_add_self]⟩ end, assume hd : disjoint _ _, lt_irrefl (2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card) $ calc 2 * ((univ.image (λ x : R, eval x f)) ∪ (univ.image (λ x : R, eval x (-g)))).card ≤ 2 * fintype.card R : nat.mul_le_mul_left _ (finset.card_le_of_subset (subset_univ _)) ... = fintype.card R + fintype.card R : two_mul _ ... < nat_degree f * (univ.image (λ x : R, eval x f)).card + nat_degree (-g) * (univ.image (λ x : R, eval x (-g))).card : add_lt_add_of_lt_of_le (lt_of_le_of_ne (card_image_polynomial_eval (by rw hf2; exact dec_trivial)) (mt (congr_arg (%2)) (by simp [nat_degree_eq_of_degree_eq_some hf2, hR]))) (card_image_polynomial_eval (by rw [degree_neg, hg2]; exact dec_trivial)) ... = 2 * (univ.image (λ x : R, eval x f) ∪ univ.image (λ x : R, eval x (-g))).card : by rw [card_disjoint_union hd]; simp [nat_degree_eq_of_degree_eq_some hf2, nat_degree_eq_of_degree_eq_some hg2, bit0, mul_add] end polynomial lemma card_units : fintype.card (units K) = fintype.card K - 1 := begin classical, rw [eq_comm, nat.sub_eq_iff_eq_add (fintype.card_pos_iff.2 ⟨(0 : K)⟩)], haveI := set_fintype {a : K | a ≠ 0}, haveI := set_fintype (@set.univ K), rw [fintype.card_congr (equiv.units_equiv_ne_zero _), ← @set.card_insert _ _ {a : K | a ≠ 0} _ (not_not.2 (eq.refl (0 : K))) (set.fintype_insert _ _), fintype.card_congr (equiv.set.univ K).symm], congr; simp [set.ext_iff, classical.em] end lemma prod_univ_units_id_eq_neg_one : (∏ x : units K, x) = (-1 : units K) := begin classical, have : (∏ x in (@univ (units K) _).erase (-1), 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), rw [← insert_erase (mem_univ (-1 : units K)), prod_insert (not_mem_erase _ _), this, mul_one] end lemma pow_card_sub_one_eq_one (a : K) (ha : a ≠ 0) : a ^ (fintype.card K - 1) = 1 := calc a ^ (fintype.card K - 1) = (units.mk0 a ha ^ (fintype.card K - 1) : units K) : by rw [units.coe_pow, units.coe_mk0] ... = 1 : by { classical, rw [← card_units, pow_card_eq_one], refl } variable (K) theorem card (p : ℕ) [char_p K p] : ∃ (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) := begin haveI hp : fact p.prime := char_p.char_is_prime K p, letI : vector_space (zmod p) K := { .. (zmod.cast_hom (dvd_refl _) K).to_semimodule }, obtain ⟨n, h⟩ := vector_space.card_fintype (zmod p) K, rw zmod.card at h, refine ⟨⟨n, _⟩, hp, h⟩, apply or.resolve_left (nat.eq_zero_or_pos n), rintro rfl, rw nat.pow_zero at h, have : (0 : K) = 1, { apply fintype.card_le_one_iff.mp (le_of_eq h) }, exact absurd this zero_ne_one, end theorem card' : ∃ (p : ℕ) (n : ℕ+), nat.prime p ∧ q = p^(n : ℕ) := let ⟨p, hc⟩ := char_p.exists K in ⟨p, @finite_field.card K _ _ p hc⟩ @[simp] lemma cast_card_eq_zero : (q : K) = 0 := begin rcases char_p.exists K with ⟨p, _char_p⟩, resetI, rcases card K p with ⟨n, hp, hn⟩, simp only [char_p.cast_eq_zero_iff K p, hn], conv { congr, rw [← nat.pow_one p] }, exact nat.pow_dvd_pow _ n.2, end lemma forall_pow_eq_one_iff (i : ℕ) : (∀ x : units K, x ^ i = 1) ↔ q - 1 ∣ i := begin obtain ⟨x, hx⟩ := is_cyclic.exists_generator (units K), classical, rw [← card_units, ← order_of_eq_card_of_forall_mem_gpowers hx, order_of_dvd_iff_pow_eq_one], split, { intro h, apply h }, { intros h y, rw ← powers_eq_gpowers at hx, rcases hx y with ⟨j, rfl⟩, rw [← pow_mul, mul_comm, pow_mul, h, one_pow], } end /-- The sum of `x ^ i` as `x` ranges over the units of a finite field of cardinality `q` is equal to `0` unless `(q - 1) ∣ i`, in which case the sum is `q - 1`. -/ lemma sum_pow_units (i : ℕ) : ∑ x : units K, (x ^ i : K) = if (q - 1) ∣ i then -1 else 0 := begin let φ : units K →* K := { to_fun := λ x, x ^ i, map_one' := by rw [units.coe_one, one_pow], map_mul' := by { intros, rw [units.coe_mul, mul_pow] } }, haveI : decidable (φ = 1) := by { classical, apply_instance }, calc ∑ x : units K, φ x = if φ = 1 then fintype.card (units K) else 0 : sum_hom_units φ ... = if (q - 1) ∣ i then -1 else 0 : _, suffices : (q - 1) ∣ i ↔ φ = 1, { simp only [this], split_ifs with h h, swap, refl, rw [card_units, nat.cast_sub, cast_card_eq_zero, nat.cast_one, zero_sub], show 1 ≤ q, from fintype.card_pos_iff.mpr ⟨0⟩ }, rw [← forall_pow_eq_one_iff, monoid_hom.ext_iff], apply forall_congr, intro x, rw [units.ext_iff, units.coe_pow, units.coe_one, monoid_hom.one_apply], refl, end /-- The sum of `x ^ i` as `x` ranges over a finite field of cardinality `q` is equal to `0` if `i < q - 1`. -/ lemma sum_pow_lt_card_sub_one (i : ℕ) (h : i < q - 1) : ∑ x : K, x ^ i = 0 := begin by_cases hi : i = 0, { simp only [hi, nsmul_one, sum_const, pow_zero, card_univ, cast_card_eq_zero], }, classical, have hiq : ¬ (q - 1) ∣ i, { contrapose! h, exact nat.le_of_dvd (nat.pos_of_ne_zero hi) h }, let φ : units K ↪ K := ⟨coe, units.ext⟩, have : univ.map φ = univ \ {0}, { ext x, simp only [true_and, embedding.coe_fn_mk, mem_sdiff, units.exists_iff_ne_zero, mem_univ, mem_map, exists_prop_of_true, mem_singleton] }, calc ∑ x : K, x ^ i = ∑ x in univ \ {(0 : K)}, x ^ i : by rw [← sum_sdiff ({0} : finset K).subset_univ, sum_singleton, zero_pow (nat.pos_of_ne_zero hi), add_zero] ... = ∑ x : units K, x ^ i : by { rw [← this, univ.sum_map φ], refl } ... = 0 : by { rw [sum_pow_units K i, if_neg], exact hiq, } end end finite_field namespace zmod open finite_field polynomial lemma sum_two_squares (p : ℕ) [hp : fact p.prime] (x : zmod p) : ∃ a b : zmod p, a^2 + b^2 = x := begin cases hp.eq_two_or_odd with hp2 hp_odd, { substI p, revert x, exact dec_trivial }, let f : polynomial (zmod p) := X^2, let g : polynomial (zmod p) := X^2 - C x, obtain ⟨a, b, hab⟩ : ∃ a b, f.eval a + g.eval b = 0 := @exists_root_sum_quadratic _ _ _ f g (degree_X_pow 2) (degree_X_pow_sub_C dec_trivial _) (by rw [zmod.card, hp_odd]), refine ⟨a, b, _⟩, rw ← sub_eq_zero, simpa only [eval_C, eval_X, eval_pow, eval_sub, ← add_sub_assoc] using hab, end end zmod namespace char_p lemma sum_two_squares (R : Type*) [integral_domain R] (p : ℕ) [fact (0 < p)] [char_p R p] (x : ℤ) : ∃ a b : ℕ, (a^2 + b^2 : R) = x := begin haveI := char_is_prime_of_pos R p, obtain ⟨a, b, hab⟩ := zmod.sum_two_squares p x, refine ⟨a.val, b.val, _⟩, simpa using congr_arg (zmod.cast_hom (dvd_refl _) R) hab end end char_p open_locale nat open zmod /-- The Fermat-Euler totient theorem. `nat.modeq.pow_totient` is an alternative statement of the same theorem. -/ @[simp] lemma zmod.pow_totient {n : ℕ} [fact (0 < n)] (x : units (zmod n)) : x ^ φ n = 1 := by rw [← card_units_eq_totient, pow_card_eq_one] /-- The Fermat-Euler totient theorem. `zmod.pow_totient` is an alternative statement of the same theorem. -/ lemma nat.modeq.pow_totient {x n : ℕ} (h : nat.coprime x n) : x ^ φ n ≡ 1 [MOD n] := begin cases n, {simp}, rw ← zmod.eq_iff_modeq_nat, let x' : units (zmod (n+1)) := zmod.unit_of_coprime _ h, have := zmod.pow_totient x', apply_fun (coe : units (zmod (n+1)) → zmod (n+1)) at this, simpa only [-zmod.pow_totient, nat.succ_eq_add_one, nat.cast_pow, units.coe_one, nat.cast_one, cast_unit_of_coprime, units.coe_pow], end
063151e2fa53893e3cbd2b4bb1c18291d37957f9
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/polynomial/degree/default.lean
049cf1a50ebf921fcddf9fa9e18d46c7b02a4f3c
[ "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
37
lean
import data.polynomial.degree.lemmas
5fa52074ba1ed7f1138205dcdc9c3a7e5ee7bd78
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/category/Mon/default_auto.lean
89aef40c9580870f310cf05121bb0b02229a4e84
[]
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
160
lean
import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.category.Mon.colimits import Mathlib.PostPort namespace Mathlib end Mathlib
351d3e83d9476b05d5d9c85389b15a122ee8c10f
3dd1b66af77106badae6edb1c4dea91a146ead30
/tests/lean/run/algebra1.lean
95c167dc2d4dfce28787ef79ed23a0269886ee8e
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
3,282
lean
import standard using num abbreviation Type1 := Type.{1} section parameter {A : Type} parameter f : A → A → A parameter one : A parameter inv : A → A infixl `*`:75 := f postfix `^-1`:100 := inv definition is_assoc := ∀ a b c, (a*b)*c = a*b*c definition is_id := ∀ a, a*one = a definition is_inv := ∀ a, a*a^-1 = one end namespace algebra inductive mul_struct (A : Type) : Type := | mk_mul_struct : (A → A → A) → mul_struct A inductive add_struct (A : Type) : Type := | mk_add_struct : (A → A → A) → add_struct A definition mul [inline] {A : Type} {s : mul_struct A} (a b : A) := mul_struct_rec (fun f, f) s a b infixl `*`:75 := mul definition add [inline] {A : Type} {s : add_struct A} (a b : A) := add_struct_rec (fun f, f) s a b infixl `+`:65 := add end namespace nat inductive nat : Type := | zero : nat | succ : nat → nat variable add : nat → nat → nat variable mul : nat → nat → nat definition is_mul_struct [inline] [instance] : algebra.mul_struct nat := algebra.mk_mul_struct mul definition is_add_struct [inline] [instance] : algebra.add_struct nat := algebra.mk_add_struct add definition to_nat (n : num) : nat := #algebra num_rec zero (λ n, pos_num_rec (succ zero) (λ n r, r + r) (λ n r, r + r + succ zero) n) n end namespace algebra namespace semigroup inductive semigroup_struct (A : Type) : Type := | mk_semigroup_struct : Π (mul : A → A → A), is_assoc mul → semigroup_struct A definition mul [inline] {A : Type} (s : semigroup_struct A) (a b : A) := semigroup_struct_rec (fun f h, f) s a b definition assoc [inline] {A : Type} (s : semigroup_struct A) : is_assoc (mul s) := semigroup_struct_rec (fun f h, h) s definition is_mul_struct [inline] [instance] (A : Type) (s : semigroup_struct A) : mul_struct A := mk_mul_struct (mul s) inductive semigroup : Type := | mk_semigroup : Π (A : Type), semigroup_struct A → semigroup definition carrier [inline] [coercion] (g : semigroup) := semigroup_rec (fun c s, c) g definition is_semigroup [inline] [instance] (g : semigroup) : semigroup_struct (carrier g) := semigroup_rec (fun c s, s) g end namespace monoid check semigroup.mul inductive monoid_struct (A : Type) : Type := | mk_monoid_struct : Π (mul : A → A → A) (id : A), is_assoc mul → is_id mul id → monoid_struct A definition mul [inline] {A : Type} (s : monoid_struct A) (a b : A) := monoid_struct_rec (fun mul id a i, mul) s a b definition assoc [inline] {A : Type} (s : monoid_struct A) : is_assoc (mul s) := monoid_struct_rec (fun mul id a i, a) s using semigroup definition is_semigroup_struct [inline] [instance] (A : Type) (s : monoid_struct A) : semigroup_struct A := mk_semigroup_struct (mul s) (assoc s) inductive monoid : Type := | mk_monoid : Π (A : Type), monoid_struct A → monoid definition carrier [inline] [coercion] (m : monoid) := monoid_rec (fun c s, c) m definition is_monoid [inline] [instance] (m : monoid) : monoid_struct (carrier m) := monoid_rec (fun c s, s) m end end section using algebra algebra.semigroup algebra.monoid variable M : monoid variables a b c : M check a*b*c*a*b*c*a*b*a*b*c*a check a*b end
2b522d7b049886435b72249369a9e84eb90a42c1
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Elab/Tactic/ElabTerm.lean
75cba225b133d287ff8695e200720a0ef8e6a119
[ "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
14,336
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.CollectMVars import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Constructor import Lean.Meta.Tactic.Assert import Lean.Meta.Tactic.Rename import Lean.Elab.Tactic.Basic import Lean.Elab.SyntheticMVars namespace Lean.Elab.Tactic open Meta /-! # `elabTerm` for Tactics and basic tactics that use it. -/ /-- Elaborate `stx` in the current `MVarContext`. If given, the `expectedType` will be used to help elaboration but not enforced (use `elabTermEnsuringType` to enforce an expected type). -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do /- If error recovery is disabled, we disable `Term.withoutErrToSorry` -/ if (← read).recover then go else Term.withoutErrToSorry go where go : TermElabM Expr := withRef stx do -- <| let e ← Term.elabTerm stx expectedType? Term.synthesizeSyntheticMVars mayPostpone instantiateMVars e /-- Elaborate `stx` in the current `MVarContext`. If given, the `expectedType` will be used to help elaboration and then a `TypeMismatchError` will be thrown if the elaborated type doesn't match. -/ def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (mayPostpone := false) : TacticM Expr := do let e ← elabTerm stx expectedType? mayPostpone -- We do use `Term.ensureExpectedType` because we don't want coercions being inserted here. match expectedType? with | none => return e | some expectedType => let eType ← inferType e -- We allow synthetic opaque metavars to be assigned in the following step since the `isDefEq` is not really -- part of the elaboration, but part of the tactic. See issue #492 unless (← withAssignableSyntheticOpaque <| isDefEq eType expectedType) do Term.throwTypeMismatchError none expectedType eType e return e /-- Try to close main goal using `x target`, where `target` is the type of the main goal. -/ def closeMainGoalUsing (x : Expr → TacticM Expr) (checkUnassigned := true) : TacticM Unit := withMainContext do closeMainGoal (checkUnassigned := checkUnassigned) (← x (← getMainTarget)) def logUnassignedAndAbort (mvarIds : Array MVarId) : TacticM Unit := do if (← Term.logUnassignedUsingErrorInfos mvarIds) then throwAbortTactic def filterOldMVars (mvarIds : Array MVarId) (mvarCounterSaved : Nat) : MetaM (Array MVarId) := do let mctx ← getMCtx return mvarIds.filter fun mvarId => (mctx.getDecl mvarId |>.index) >= mvarCounterSaved @[builtinTactic «exact»] def evalExact : Tactic := fun stx => match stx with | `(tactic| exact $e) => closeMainGoalUsing (checkUnassigned := false) fun type => do let mvarCounterSaved := (← getMCtx).mvarCounter let r ← elabTermEnsuringType e type logUnassignedAndAbort (← filterOldMVars (← getMVars r) mvarCounterSaved) return r | _ => throwUnsupportedSyntax /-- Execute `k`, and collect new "holes" in the resulting expression. -/ def withCollectingNewGoalsFrom (k : TacticM Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr × List MVarId) := do let mvarCounterSaved := (← getMCtx).mvarCounter let val ← k let newMVarIds ← getMVarsNoDelayed val /- ignore let-rec auxiliary variables, they are synthesized automatically later -/ let newMVarIds ← newMVarIds.filterM fun mvarId => return !(← Term.isLetRecAuxMVar mvarId) let newMVarIds ← if allowNaturalHoles then pure newMVarIds.toList else let naturalMVarIds ← newMVarIds.filterM fun mvarId => return (← mvarId.getKind).isNatural let syntheticMVarIds ← newMVarIds.filterM fun mvarId => return !(← mvarId.getKind).isNatural let naturalMVarIds ← filterOldMVars naturalMVarIds mvarCounterSaved logUnassignedAndAbort naturalMVarIds pure syntheticMVarIds.toList tagUntaggedGoals (← getMainTag) tagSuffix newMVarIds return (val, newMVarIds) def elabTermWithHoles (stx : Syntax) (expectedType? : Option Expr) (tagSuffix : Name) (allowNaturalHoles := false) : TacticM (Expr × List MVarId) := do withCollectingNewGoalsFrom (elabTermEnsuringType stx expectedType?) tagSuffix allowNaturalHoles /-- If `allowNaturalHoles == true`, then we allow the resultant expression to contain unassigned "natural" metavariables. Recall that "natutal" metavariables are created for explicit holes `_` and implicit arguments. They are meant to be filled by typing constraints. "Synthetic" metavariables are meant to be filled by tactics and are usually created using the synthetic hole notation `?<hole-name>`. -/ def refineCore (stx : Syntax) (tagSuffix : Name) (allowNaturalHoles : Bool) : TacticM Unit := do withMainContext do let (val, mvarIds') ← elabTermWithHoles stx (← getMainTarget) tagSuffix allowNaturalHoles let mvarId ← getMainGoal let val ← instantiateMVars val unless val == mkMVar mvarId do if val.findMVar? (· == mvarId) matches some _ then throwError "'refine' tactic failed, value{indentExpr val}\ndepends on the main goal metavariable '{mkMVar mvarId}'" mvarId.assign val replaceMainGoal mvarIds' @[builtinTactic «refine»] def evalRefine : Tactic := fun stx => match stx with | `(tactic| refine $e) => refineCore e `refine (allowNaturalHoles := false) | _ => throwUnsupportedSyntax @[builtinTactic «refine'»] def evalRefine' : Tactic := fun stx => match stx with | `(tactic| refine' $e) => refineCore e `refine' (allowNaturalHoles := true) | _ => throwUnsupportedSyntax @[builtinTactic «specialize»] def evalSpecialize : Tactic := fun stx => withMainContext do match stx with | `(tactic| specialize $e:term) => let (e, mvarIds') ← elabTermWithHoles e none `specialize (allowNaturalHoles := true) let h := e.getAppFn if h.isFVar then let localDecl ← h.fvarId!.getDecl let mvarId ← (← getMainGoal).assert localDecl.userName (← inferType e).headBeta e let (_, mvarId) ← mvarId.intro1P let mvarId ← mvarId.tryClear h.fvarId! replaceMainGoal (mvarId :: mvarIds') else throwError "'specialize' requires a term of the form `h x_1 .. x_n` where `h` appears in the local context" | _ => throwUnsupportedSyntax /-- Given a tactic ``` apply f ``` we want the `apply` tactic to create all metavariables. The following definition will return `@f` for `f`. That is, it will **not** create metavariables for implicit arguments. A similar method is also used in Lean 3. This method is useful when applying lemmas such as: ``` theorem infLeRight {s t : Set α} : s ⊓ t ≤ t ``` where `s ≤ t` here is defined as ``` ∀ {x : α}, x ∈ s → x ∈ t ``` -/ def elabTermForApply (stx : Syntax) (mayPostpone := true) : TacticM Expr := do if stx.isIdent then match (← Term.resolveId? stx (withInfo := true)) with | some e => return e | _ => pure () /- By disabling the "error recovery" (and consequently "error to sorry") feature, we make sure an `apply e` fails without logging an error message. The motivation is that `apply` is frequently used when writing tactic such as ``` cases h <;> intro h' <;> first | apply t[h'] | .... ``` Here the type of `h'` may be different in each case, and the term `t[h']` containing `h'` may even fail to be elaborated in some cases. When this happens we want the tactic to fail without reporting any error to the user, and the next tactic is tried. A drawback of disabling "error to sorry" is that there is no error recovery after the error is thrown, and features such as auto-completion are affected. By disabling "error to sorry", we also limit ourselves to at most one error at `t[h']`. By disabling "error to sorry", we also miss the opportunity to catch mistakes is tactic code such as `first | apply nonsensical-term | assumption` This should not be a big problem for the `apply` tactic since we usually provide small terms there. Note that we do not disable "error to sorry" at `exact` and `refine` since they are often used to elaborate big terms, and we do want error recovery there, and we want to see the error messages. We should probably provide options for allowing users to control this behavior. see issue #1037 More complex solution: - We do not disable "error to sorry" - We elaborate term and check whether errors were produced - If there are other tactic braches and there are errors, we remove the errors from the log, and throw a new error to force the tactic to backtrack. -/ withoutRecover <| elabTerm stx none mayPostpone def evalApplyLikeTactic (tac : MVarId → Expr → MetaM (List MVarId)) (e : Syntax) : TacticM Unit := do withMainContext do let val ← elabTermForApply e let mvarIds' ← tac (← getMainGoal) val Term.synthesizeSyntheticMVarsNoPostponing replaceMainGoal mvarIds' def getFVarId (id : Syntax) : TacticM FVarId := withRef id do -- use apply-like elaboration to suppress insertion of implicit arguments let e ← withMainContext do elabTermForApply id (mayPostpone := false) match e with | Expr.fvar fvarId => return fvarId | _ => throwError "unexpected term '{e}'; expected single reference to variable" def getFVarIds (ids : Array Syntax) : TacticM (Array FVarId) := do withMainContext do ids.mapM getFVarId @[builtinTactic Lean.Parser.Tactic.apply] def evalApply : Tactic := fun stx => match stx with | `(tactic| apply $e) => evalApplyLikeTactic (·.apply) e | _ => throwUnsupportedSyntax @[builtinTactic Lean.Parser.Tactic.constructor] def evalConstructor : Tactic := fun _ => withMainContext do let mvarIds' ← (← getMainGoal).constructor Term.synthesizeSyntheticMVarsNoPostponing replaceMainGoal mvarIds' @[builtinTactic Lean.Parser.Tactic.withReducible] def evalWithReducible : Tactic := fun stx => withReducible <| evalTactic stx[1] @[builtinTactic Lean.Parser.Tactic.withReducibleAndInstances] def evalWithReducibleAndInstances : Tactic := fun stx => withReducibleAndInstances <| evalTactic stx[1] @[builtinTactic Lean.Parser.Tactic.withUnfoldingAll] def evalWithUnfoldingAll : Tactic := fun stx => withTransparency TransparencyMode.all <| evalTactic stx[1] /-- Elaborate `stx`. If it a free variable, return it. Otherwise, assert it, and return the free variable. Note that, the main goal is updated when `Meta.assert` is used in the second case. -/ def elabAsFVar (stx : Syntax) (userName? : Option Name := none) : TacticM FVarId := withMainContext do let e ← elabTerm stx none match e with | .fvar fvarId => pure fvarId | _ => let type ← inferType e let intro (userName : Name) (preserveBinderNames : Bool) : TacticM FVarId := do let mvarId ← getMainGoal let (fvarId, mvarId) ← liftMetaM do let mvarId ← mvarId.assert userName type e Meta.intro1Core mvarId preserveBinderNames replaceMainGoal [mvarId] return fvarId match userName? with | none => intro `h false | some userName => intro userName true @[builtinTactic Lean.Parser.Tactic.rename] def evalRename : Tactic := fun stx => match stx with | `(tactic| rename $typeStx:term => $h:ident) => do withMainContext do /- Remark: we also use `withoutRecover` to make sure `elabTerm` does not succeed using `sorryAx`, and we get `"failed to find ..."` which will not be logged because it contains synthetic sorry's -/ let fvarId ← withoutModifyingState <| withNewMCtxDepth <| withoutRecover do let type ← elabTerm typeStx none (mayPostpone := true) let fvarId? ← (← getLCtx).findDeclRevM? fun localDecl => do if (← isDefEq type localDecl.type) then return localDecl.fvarId else return none match fvarId? with | none => throwError "failed to find a hypothesis with type{indentExpr type}" | some fvarId => return fvarId replaceMainGoal [← (← getMainGoal).rename fvarId h.getId] | _ => throwUnsupportedSyntax /-- Make sure `expectedType` does not contain free and metavariables. It applies zeta-reduction to eliminate let-free-vars. -/ private def preprocessPropToDecide (expectedType : Expr) : TermElabM Expr := do let mut expectedType ← instantiateMVars expectedType if expectedType.hasFVar then expectedType ← zetaReduce expectedType if expectedType.hasFVar || expectedType.hasMVar then throwError "expected type must not contain free or meta variables{indentExpr expectedType}" return expectedType @[builtinTactic Lean.Parser.Tactic.decide] def evalDecide : Tactic := fun _ => closeMainGoalUsing fun expectedType => do let expectedType ← preprocessPropToDecide expectedType let d ← mkDecide expectedType let d ← instantiateMVars d let r ← withDefault <| whnf d unless r.isConstOf ``true do throwError "failed to reduce to 'true'{indentExpr r}" let s := d.appArg! -- get instance from `d` let rflPrf ← mkEqRefl (toExpr true) return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s rflPrf private def mkNativeAuxDecl (baseName : Name) (type value : Expr) : TermElabM Name := do let auxName ← Term.mkAuxName baseName let decl := Declaration.defnDecl { name := auxName, levelParams := [], type, value hints := .abbrev safety := .safe } addDecl decl compileDecl decl pure auxName @[builtinTactic Lean.Parser.Tactic.nativeDecide] def evalNativeDecide : Tactic := fun _ => closeMainGoalUsing fun expectedType => do let expectedType ← preprocessPropToDecide expectedType let d ← mkDecide expectedType let auxDeclName ← mkNativeAuxDecl `_nativeDecide (Lean.mkConst `Bool) d let rflPrf ← mkEqRefl (toExpr true) let s := d.appArg! -- get instance from `d` return mkApp3 (Lean.mkConst ``of_decide_eq_true) expectedType s <| mkApp3 (Lean.mkConst ``Lean.ofReduceBool) (Lean.mkConst auxDeclName) (toExpr true) rflPrf end Lean.Elab.Tactic
bc20bac5d14cbffee049f253154f390fc518e4dd
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/measure_theory/group/arithmetic.lean
58c0ebe94b5212d7d0e6fa923f8d18135b8f3770
[ "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
26,743
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import measure_theory.measure.measure_space /-! # Typeclasses for measurability of operations In this file we define classes `has_measurable_mul` etc and prove dot-style lemmas (`measurable.mul`, `ae_measurable.mul` etc). For binary operations we define two typeclasses: - `has_measurable_mul` says that both left and right multiplication are measurable; - `has_measurable_mul₂` says that `λ p : α × α, p.1 * p.2` is measurable, and similarly for other binary operations. The reason for introducing these classes is that in case of topological space `α` equipped with the Borel `σ`-algebra, instances for `has_measurable_mul₂` etc require `α` to have a second countable topology. We define separate classes for `has_measurable_div`/`has_measurable_sub` because on some types (e.g., `ℕ`, `ℝ≥0∞`) division and/or subtraction are not defined as `a * b⁻¹` / `a + (-b)`. For instances relating, e.g., `has_continuous_mul` to `has_measurable_mul` see file `measure_theory.borel_space`. ## Implementation notes For the heuristics of `@[to_additive]` it is important that the type with a multiplication (or another multiplicative operations) is the first (implicit) argument of all declarations. ## Tags measurable function, arithmetic operator ## Todo * Uniformize the treatment of `pow` and `smul`. * Use `@[to_additive]` to send `has_measurable_pow` to `has_measurable_smul₂`. * This might require changing the definition (swapping the arguments in the function that is in the conclusion of `measurable_smul`.) -/ universes u v open_locale big_operators open measure_theory /-! ### Binary operations: `(+)`, `(*)`, `(-)`, `(/)` -/ /-- We say that a type `has_measurable_add` if `((+) c)` and `(+ c)` are measurable functions. For a typeclass assuming measurability of `uncurry (+)` see `has_measurable_add₂`. -/ class has_measurable_add (M : Type*) [measurable_space M] [has_add M] : Prop := (measurable_const_add : ∀ c : M, measurable ((+) c)) (measurable_add_const : ∀ c : M, measurable (+ c)) /-- We say that a type `has_measurable_add` if `uncurry (+)` is a measurable functions. For a typeclass assuming measurability of `((+) c)` and `(+ c)` see `has_measurable_add`. -/ class has_measurable_add₂ (M : Type*) [measurable_space M] [has_add M] : Prop := (measurable_add : measurable (λ p : M × M, p.1 + p.2)) export has_measurable_add₂ (measurable_add) has_measurable_add (measurable_const_add measurable_add_const) /-- We say that a type `has_measurable_mul` if `((*) c)` and `(* c)` are measurable functions. For a typeclass assuming measurability of `uncurry (*)` see `has_measurable_mul₂`. -/ @[to_additive] class has_measurable_mul (M : Type*) [measurable_space M] [has_mul M] : Prop := (measurable_const_mul : ∀ c : M, measurable ((*) c)) (measurable_mul_const : ∀ c : M, measurable (* c)) /-- We say that a type `has_measurable_mul` if `uncurry (*)` is a measurable functions. For a typeclass assuming measurability of `((*) c)` and `(* c)` see `has_measurable_mul`. -/ @[to_additive has_measurable_add₂] class has_measurable_mul₂ (M : Type*) [measurable_space M] [has_mul M] : Prop := (measurable_mul : measurable (λ p : M × M, p.1 * p.2)) export has_measurable_mul₂ (measurable_mul) has_measurable_mul (measurable_const_mul measurable_mul_const) section mul variables {M α : Type*} [measurable_space M] [has_mul M] [measurable_space α] @[to_additive, measurability] lemma measurable.const_mul [has_measurable_mul M] {f : α → M} (hf : measurable f) (c : M) : measurable (λ x, c * f x) := (measurable_const_mul c).comp hf @[to_additive, measurability] lemma ae_measurable.const_mul [has_measurable_mul M] {f : α → M} {μ : measure α} (hf : ae_measurable f μ) (c : M) : ae_measurable (λ x, c * f x) μ := (has_measurable_mul.measurable_const_mul c).comp_ae_measurable hf @[to_additive, measurability] lemma measurable.mul_const [has_measurable_mul M] {f : α → M} (hf : measurable f) (c : M) : measurable (λ x, f x * c) := (measurable_mul_const c).comp hf @[to_additive, measurability] lemma ae_measurable.mul_const [has_measurable_mul M] {f : α → M} {μ : measure α} (hf : ae_measurable f μ) (c : M) : ae_measurable (λ x, f x * c) μ := (measurable_mul_const c).comp_ae_measurable hf @[to_additive, measurability] lemma measurable.mul' [has_measurable_mul₂ M] {f g : α → M} (hf : measurable f) (hg : measurable g) : measurable (f * g) := measurable_mul.comp (hf.prod_mk hg) @[to_additive, measurability] lemma measurable.mul [has_measurable_mul₂ M] {f g : α → M} (hf : measurable f) (hg : measurable g) : measurable (λ a, f a * g a) := measurable_mul.comp (hf.prod_mk hg) @[to_additive, measurability] lemma ae_measurable.mul' [has_measurable_mul₂ M] {μ : measure α} {f g : α → M} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (f * g) μ := measurable_mul.comp_ae_measurable (hf.prod_mk hg) @[to_additive, measurability] lemma ae_measurable.mul [has_measurable_mul₂ M] {μ : measure α} {f g : α → M} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, f a * g a) μ := measurable_mul.comp_ae_measurable (hf.prod_mk hg) @[priority 100, to_additive] instance has_measurable_mul₂.to_has_measurable_mul [has_measurable_mul₂ M] : has_measurable_mul M := ⟨λ c, measurable_const.mul measurable_id, λ c, measurable_id.mul measurable_const⟩ attribute [measurability] measurable.add' measurable.add ae_measurable.add ae_measurable.add' measurable.const_add ae_measurable.const_add measurable.add_const ae_measurable.add_const end mul /-- This class assumes that the map `β × γ → β` given by `(x, y) ↦ x ^ y` is measurable. -/ class has_measurable_pow (β γ : Type*) [measurable_space β] [measurable_space γ] [has_pow β γ] := (measurable_pow : measurable (λ p : β × γ, p.1 ^ p.2)) export has_measurable_pow (measurable_pow) instance has_measurable_mul.has_measurable_pow (M : Type*) [monoid M] [measurable_space M] [has_measurable_mul₂ M] : has_measurable_pow M ℕ := ⟨begin haveI : measurable_singleton_class ℕ := ⟨λ _, trivial⟩, refine measurable_from_prod_encodable (λ n, _), induction n with n ih, { simp [pow_zero, measurable_one] }, { simp only [pow_succ], exact measurable_id.mul ih } end⟩ section pow variables {β γ α : Type*} [measurable_space β] [measurable_space γ] [has_pow β γ] [has_measurable_pow β γ] [measurable_space α] @[measurability] lemma measurable.pow {f : α → β} {g : α → γ} (hf : measurable f) (hg : measurable g) : measurable (λ x, f x ^ g x) := measurable_pow.comp (hf.prod_mk hg) @[measurability] lemma ae_measurable.pow {μ : measure α} {f : α → β} {g : α → γ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, f x ^ g x) μ := measurable_pow.comp_ae_measurable (hf.prod_mk hg) @[measurability] lemma measurable.pow_const {f : α → β} (hf : measurable f) (c : γ) : measurable (λ x, f x ^ c) := hf.pow measurable_const @[measurability] lemma ae_measurable.pow_const {μ : measure α} {f : α → β} (hf : ae_measurable f μ) (c : γ) : ae_measurable (λ x, f x ^ c) μ := hf.pow ae_measurable_const @[measurability] lemma measurable.const_pow {f : α → γ} (hf : measurable f) (c : β) : measurable (λ x, c ^ f x) := measurable_const.pow hf @[measurability] lemma ae_measurable.const_pow {μ : measure α} {f : α → γ} (hf : ae_measurable f μ) (c : β) : ae_measurable (λ x, c ^ f x) μ := ae_measurable_const.pow hf end pow /-- We say that a type `has_measurable_sub` if `(λ x, c - x)` and `(λ x, x - c)` are measurable functions. For a typeclass assuming measurability of `uncurry (-)` see `has_measurable_sub₂`. -/ class has_measurable_sub (G : Type*) [measurable_space G] [has_sub G] : Prop := (measurable_const_sub : ∀ c : G, measurable (λ x, c - x)) (measurable_sub_const : ∀ c : G, measurable (λ x, x - c)) /-- We say that a type `has_measurable_sub` if `uncurry (-)` is a measurable functions. For a typeclass assuming measurability of `((-) c)` and `(- c)` see `has_measurable_sub`. -/ class has_measurable_sub₂ (G : Type*) [measurable_space G] [has_sub G] : Prop := (measurable_sub : measurable (λ p : G × G, p.1 - p.2)) export has_measurable_sub₂ (measurable_sub) /-- We say that a type `has_measurable_div` if `((/) c)` and `(/ c)` are measurable functions. For a typeclass assuming measurability of `uncurry (/)` see `has_measurable_div₂`. -/ @[to_additive] class has_measurable_div (G₀: Type*) [measurable_space G₀] [has_div G₀] : Prop := (measurable_const_div : ∀ c : G₀, measurable ((/) c)) (measurable_div_const : ∀ c : G₀, measurable (/ c)) /-- We say that a type `has_measurable_div` if `uncurry (/)` is a measurable functions. For a typeclass assuming measurability of `((/) c)` and `(/ c)` see `has_measurable_div`. -/ @[to_additive has_measurable_sub₂] class has_measurable_div₂ (G₀: Type*) [measurable_space G₀] [has_div G₀] : Prop := (measurable_div : measurable (λ p : G₀× G₀, p.1 / p.2)) export has_measurable_div₂ (measurable_div) section div variables {G α : Type*} [measurable_space G] [has_div G] [measurable_space α] @[to_additive, measurability] lemma measurable.const_div [has_measurable_div G] {f : α → G} (hf : measurable f) (c : G) : measurable (λ x, c / f x) := (has_measurable_div.measurable_const_div c).comp hf @[to_additive, measurability] lemma ae_measurable.const_div [has_measurable_div G] {f : α → G} {μ : measure α} (hf : ae_measurable f μ) (c : G) : ae_measurable (λ x, c / f x) μ := (has_measurable_div.measurable_const_div c).comp_ae_measurable hf @[to_additive, measurability] lemma measurable.div_const [has_measurable_div G] {f : α → G} (hf : measurable f) (c : G) : measurable (λ x, f x / c) := (has_measurable_div.measurable_div_const c).comp hf @[to_additive, measurability] lemma ae_measurable.div_const [has_measurable_div G] {f : α → G} {μ : measure α} (hf : ae_measurable f μ) (c : G) : ae_measurable (λ x, f x / c) μ := (has_measurable_div.measurable_div_const c).comp_ae_measurable hf @[to_additive, measurability] lemma measurable.div' [has_measurable_div₂ G] {f g : α → G} (hf : measurable f) (hg : measurable g) : measurable (f / g) := measurable_div.comp (hf.prod_mk hg) @[to_additive, measurability] lemma measurable.div [has_measurable_div₂ G] {f g : α → G} (hf : measurable f) (hg : measurable g) : measurable (λ a, f a / g a) := measurable_div.comp (hf.prod_mk hg) @[to_additive, measurability] lemma ae_measurable.div' [has_measurable_div₂ G] {f g : α → G} {μ : measure α} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (f / g) μ := measurable_div.comp_ae_measurable (hf.prod_mk hg) @[to_additive, measurability] lemma ae_measurable.div [has_measurable_div₂ G] {f g : α → G} {μ : measure α} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, f a / g a) μ := measurable_div.comp_ae_measurable (hf.prod_mk hg) @[priority 100, to_additive] instance has_measurable_div₂.to_has_measurable_div [has_measurable_div₂ G] : has_measurable_div G := ⟨λ c, measurable_const.div measurable_id, λ c, measurable_id.div measurable_const⟩ attribute [measurability] measurable.sub measurable.sub' ae_measurable.sub ae_measurable.sub' measurable.const_sub ae_measurable.const_sub measurable.sub_const ae_measurable.sub_const @[measurability] lemma measurable_set_eq_fun {E} [measurable_space E] [add_group E] [measurable_singleton_class E] [has_measurable_sub₂ E] {f g : α → E} (hf : measurable f) (hg : measurable g) : measurable_set {x | f x = g x} := begin suffices h_set_eq : {x : α | f x = g x} = {x | (f-g) x = (0 : E)}, { rw h_set_eq, exact (hf.sub hg) measurable_set_eq, }, ext, simp_rw [set.mem_set_of_eq, pi.sub_apply, sub_eq_zero], end lemma ae_eq_trim_of_measurable {α E} {m m0 : measurable_space α} {μ : measure α} [measurable_space E] [add_group E] [measurable_singleton_class E] [has_measurable_sub₂ E] (hm : m ≤ m0) {f g : α → E} (hf : @measurable _ _ m _ f) (hg : @measurable _ _ m _ g) (hfg : f =ᵐ[μ] g) : f =ᶠ[@measure.ae α m (μ.trim hm)] g := begin rwa [filter.eventually_eq, ae_iff, trim_measurable_set_eq hm _], exact (@measurable_set.compl α _ m (@measurable_set_eq_fun α m E _ _ _ _ _ _ hf hg)), end end div /-- We say that a type `has_measurable_neg` if `x ↦ -x` is a measurable function. -/ class has_measurable_neg (G : Type*) [has_neg G] [measurable_space G] : Prop := (measurable_neg : measurable (has_neg.neg : G → G)) /-- We say that a type `has_measurable_inv` if `x ↦ x⁻¹` is a measurable function. -/ @[to_additive] class has_measurable_inv (G : Type*) [has_inv G] [measurable_space G] : Prop := (measurable_inv : measurable (has_inv.inv : G → G)) export has_measurable_inv (measurable_inv) has_measurable_neg (measurable_neg) @[priority 100, to_additive] instance has_measurable_div_of_mul_inv (G : Type*) [measurable_space G] [div_inv_monoid G] [has_measurable_mul G] [has_measurable_inv G] : has_measurable_div G := { measurable_const_div := λ c, by { convert (measurable_inv.const_mul c), ext1, apply div_eq_mul_inv }, measurable_div_const := λ c, by { convert (measurable_id.mul_const c⁻¹), ext1, apply div_eq_mul_inv } } section inv variables {G α : Type*} [has_inv G] [measurable_space G] [has_measurable_inv G] [measurable_space α] @[to_additive, measurability] lemma measurable.inv {f : α → G} (hf : measurable f) : measurable (λ x, (f x)⁻¹) := measurable_inv.comp hf @[to_additive, measurability] lemma ae_measurable.inv {f : α → G} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x)⁻¹) μ := measurable_inv.comp_ae_measurable hf attribute [measurability] measurable.neg ae_measurable.neg @[simp, to_additive] lemma measurable_inv_iff {G : Type*} [group G] [measurable_space G] [has_measurable_inv G] {f : α → G} : measurable (λ x, (f x)⁻¹) ↔ measurable f := ⟨λ h, by simpa only [inv_inv] using h.inv, λ h, h.inv⟩ @[simp, to_additive] lemma ae_measurable_inv_iff {G : Type*} [group G] [measurable_space G] [has_measurable_inv G] {f : α → G} {μ : measure α} : ae_measurable (λ x, (f x)⁻¹) μ ↔ ae_measurable f μ := ⟨λ h, by simpa only [inv_inv] using h.inv, λ h, h.inv⟩ @[simp] lemma measurable_inv_iff₀ {G₀ : Type*} [group_with_zero G₀] [measurable_space G₀] [has_measurable_inv G₀] {f : α → G₀} : measurable (λ x, (f x)⁻¹) ↔ measurable f := ⟨λ h, by simpa only [inv_inv₀] using h.inv, λ h, h.inv⟩ @[simp] lemma ae_measurable_inv_iff₀ {G₀ : Type*} [group_with_zero G₀] [measurable_space G₀] [has_measurable_inv G₀] {f : α → G₀} {μ : measure α} : ae_measurable (λ x, (f x)⁻¹) μ ↔ ae_measurable f μ := ⟨λ h, by simpa only [inv_inv₀] using h.inv, λ h, h.inv⟩ end inv /- There is something extremely strange here: copy-pasting the proof of this lemma in the proof of `has_measurable_gpow` fails, while `pp.all` does not show any difference in the goal. Keep it as a separate lemmas as a workaround. -/ private lemma has_measurable_gpow_aux (G : Type u) [div_inv_monoid G] [measurable_space G] [has_measurable_mul₂ G] [has_measurable_inv G] (k : ℕ) : measurable (λ (x : G), x ^(-[1+ k])) := begin simp_rw [gpow_neg_succ_of_nat], exact (measurable_id.pow_const (k + 1)).inv end instance has_measurable_gpow (G : Type u) [div_inv_monoid G] [measurable_space G] [has_measurable_mul₂ G] [has_measurable_inv G] : has_measurable_pow G ℤ := begin letI : measurable_singleton_class ℤ := ⟨λ _, trivial⟩, constructor, refine measurable_from_prod_encodable (λ n, _), dsimp, apply int.cases_on n, { simpa using measurable_id.pow_const }, { exact has_measurable_gpow_aux G } end @[priority 100, to_additive] instance has_measurable_div₂_of_mul_inv (G : Type*) [measurable_space G] [div_inv_monoid G] [has_measurable_mul₂ G] [has_measurable_inv G] : has_measurable_div₂ G := ⟨by { simp only [div_eq_mul_inv], exact measurable_fst.mul measurable_snd.inv }⟩ /-- We say that the action of `M` on `α` `has_measurable_vadd` if for each `c` the map `x ↦ c +ᵥ x` is a measurable function and for each `x` the map `c ↦ c +ᵥ x` is a measurable function. -/ class has_measurable_vadd (M α : Type*) [has_vadd M α] [measurable_space M] [measurable_space α] : Prop := (measurable_const_vadd : ∀ c : M, measurable ((+ᵥ) c : α → α)) (measurable_vadd_const : ∀ x : α, measurable (λ c : M, c +ᵥ x)) /-- We say that the action of `M` on `α` `has_measurable_smul` if for each `c` the map `x ↦ c • x` is a measurable function and for each `x` the map `c ↦ c • x` is a measurable function. -/ @[to_additive] class has_measurable_smul (M α : Type*) [has_scalar M α] [measurable_space M] [measurable_space α] : Prop := (measurable_const_smul : ∀ c : M, measurable ((•) c : α → α)) (measurable_smul_const : ∀ x : α, measurable (λ c : M, c • x)) /-- We say that the action of `M` on `α` `has_measurable_vadd₂` if the map `(c, x) ↦ c +ᵥ x` is a measurable function. -/ class has_measurable_vadd₂ (M α : Type*) [has_vadd M α] [measurable_space M] [measurable_space α] : Prop := (measurable_vadd : measurable (function.uncurry (+ᵥ) : M × α → α)) /-- We say that the action of `M` on `α` `has_measurable_smul₂` if the map `(c, x) ↦ c • x` is a measurable function. -/ @[to_additive has_measurable_vadd₂] class has_measurable_smul₂ (M α : Type*) [has_scalar M α] [measurable_space M] [measurable_space α] : Prop := (measurable_smul : measurable (function.uncurry (•) : M × α → α)) export has_measurable_smul (measurable_const_smul measurable_smul_const) has_measurable_smul₂ (measurable_smul) export has_measurable_vadd (measurable_const_vadd measurable_vadd_const) has_measurable_vadd₂ (measurable_vadd) @[to_additive] instance has_measurable_smul_of_mul (M : Type*) [monoid M] [measurable_space M] [has_measurable_mul M] : has_measurable_smul M M := ⟨measurable_id.const_mul, measurable_id.mul_const⟩ @[to_additive] instance has_measurable_smul₂_of_mul (M : Type*) [monoid M] [measurable_space M] [has_measurable_mul₂ M] : has_measurable_smul₂ M M := ⟨measurable_mul⟩ section smul variables {M β α : Type*} [measurable_space M] [measurable_space β] [has_scalar M β] [measurable_space α] @[measurability, to_additive] lemma measurable.smul [has_measurable_smul₂ M β] {f : α → M} {g : α → β} (hf : measurable f) (hg : measurable g) : measurable (λ x, f x • g x) := measurable_smul.comp (hf.prod_mk hg) @[measurability, to_additive] lemma ae_measurable.smul [has_measurable_smul₂ M β] {f : α → M} {g : α → β} {μ : measure α} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ x, f x • g x) μ := has_measurable_smul₂.measurable_smul.comp_ae_measurable (hf.prod_mk hg) @[priority 100, to_additive] instance has_measurable_smul₂.to_has_measurable_smul [has_measurable_smul₂ M β] : has_measurable_smul M β := ⟨λ c, measurable_const.smul measurable_id, λ y, measurable_id.smul measurable_const⟩ variables [has_measurable_smul M β] {μ : measure α} @[measurability, to_additive] lemma measurable.smul_const {f : α → M} (hf : measurable f) (y : β) : measurable (λ x, f x • y) := (has_measurable_smul.measurable_smul_const y).comp hf @[measurability, to_additive] lemma ae_measurable.smul_const {f : α → M} (hf : ae_measurable f μ) (y : β) : ae_measurable (λ x, f x • y) μ := (has_measurable_smul.measurable_smul_const y).comp_ae_measurable hf @[measurability, to_additive] lemma measurable.const_smul' {f : α → β} (hf : measurable f) (c : M) : measurable (λ x, c • f x) := (has_measurable_smul.measurable_const_smul c).comp hf @[measurability, to_additive] lemma measurable.const_smul {f : α → β} (hf : measurable f) (c : M) : measurable (c • f) := hf.const_smul' c @[measurability, to_additive] lemma ae_measurable.const_smul' {f : α → β} (hf : ae_measurable f μ) (c : M) : ae_measurable (λ x, c • f x) μ := (has_measurable_smul.measurable_const_smul c).comp_ae_measurable hf @[measurability, to_additive] lemma ae_measurable.const_smul {f : α → β} (hf : ae_measurable f μ) (c : M) : ae_measurable (c • f) μ := hf.const_smul' c end smul section mul_action variables {M β α : Type*} [measurable_space M] [measurable_space β] [monoid M] [mul_action M β] [has_measurable_smul M β] [measurable_space α] {f : α → β} {μ : measure α} variables {G : Type*} [group G] [measurable_space G] [mul_action G β] [has_measurable_smul G β] @[to_additive] lemma measurable_const_smul_iff (c : G) : measurable (λ x, c • f x) ↔ measurable f := ⟨λ h, by simpa only [inv_smul_smul] using h.const_smul' c⁻¹, λ h, h.const_smul c⟩ @[to_additive] lemma ae_measurable_const_smul_iff (c : G) : ae_measurable (λ x, c • f x) μ ↔ ae_measurable f μ := ⟨λ h, by simpa only [inv_smul_smul] using h.const_smul' c⁻¹, λ h, h.const_smul c⟩ @[to_additive] instance : measurable_space (units M) := measurable_space.comap (coe : units M → M) ‹_› @[to_additive] instance units.has_measurable_smul : has_measurable_smul (units M) β := { measurable_const_smul := λ c, (measurable_const_smul (c : M) : _), measurable_smul_const := λ x, (measurable_smul_const x : measurable (λ c : M, c • x)).comp measurable_space.le_map_comap, } @[to_additive] lemma is_unit.measurable_const_smul_iff {c : M} (hc : is_unit c) : measurable (λ x, c • f x) ↔ measurable f := let ⟨u, hu⟩ := hc in hu ▸ measurable_const_smul_iff u @[to_additive] lemma is_unit.ae_measurable_const_smul_iff {c : M} (hc : is_unit c) : ae_measurable (λ x, c • f x) μ ↔ ae_measurable f μ := let ⟨u, hu⟩ := hc in hu ▸ ae_measurable_const_smul_iff u variables {G₀ : Type*} [group_with_zero G₀] [measurable_space G₀] [mul_action G₀ β] [has_measurable_smul G₀ β] lemma measurable_const_smul_iff₀ {c : G₀} (hc : c ≠ 0) : measurable (λ x, c • f x) ↔ measurable f := (is_unit.mk0 c hc).measurable_const_smul_iff lemma ae_measurable_const_smul_iff₀ {c : G₀} (hc : c ≠ 0) : ae_measurable (λ x, c • f x) μ ↔ ae_measurable f μ := (is_unit.mk0 c hc).ae_measurable_const_smul_iff end mul_action /-! ### Big operators: `∏` and `∑` -/ section monoid variables {M α : Type*} [monoid M] [measurable_space M] [has_measurable_mul₂ M] [measurable_space α] @[to_additive, measurability] lemma list.measurable_prod' (l : list (α → M)) (hl : ∀ f ∈ l, measurable f) : measurable l.prod := begin induction l with f l ihl, { exact measurable_one }, rw [list.forall_mem_cons] at hl, rw [list.prod_cons], exact hl.1.mul (ihl hl.2) end @[to_additive, measurability] lemma list.ae_measurable_prod' {μ : measure α} (l : list (α → M)) (hl : ∀ f ∈ l, ae_measurable f μ) : ae_measurable l.prod μ := begin induction l with f l ihl, { exact ae_measurable_one }, rw [list.forall_mem_cons] at hl, rw [list.prod_cons], exact hl.1.mul (ihl hl.2) end @[to_additive, measurability] lemma list.measurable_prod (l : list (α → M)) (hl : ∀ f ∈ l, measurable f) : measurable (λ x, (l.map (λ f : α → M, f x)).prod) := by simpa only [← pi.list_prod_apply] using l.measurable_prod' hl @[to_additive, measurability] lemma list.ae_measurable_prod {μ : measure α} (l : list (α → M)) (hl : ∀ f ∈ l, ae_measurable f μ) : ae_measurable (λ x, (l.map (λ f : α → M, f x)).prod) μ := by simpa only [← pi.list_prod_apply] using l.ae_measurable_prod' hl end monoid section comm_monoid variables {M ι α : Type*} [comm_monoid M] [measurable_space M] [has_measurable_mul₂ M] [measurable_space α] @[to_additive, measurability] lemma multiset.measurable_prod' (l : multiset (α → M)) (hl : ∀ f ∈ l, measurable f) : measurable l.prod := by { rcases l with ⟨l⟩, simpa using l.measurable_prod' (by simpa using hl) } @[to_additive, measurability] lemma multiset.ae_measurable_prod' {μ : measure α} (l : multiset (α → M)) (hl : ∀ f ∈ l, ae_measurable f μ) : ae_measurable l.prod μ := by { rcases l with ⟨l⟩, simpa using l.ae_measurable_prod' (by simpa using hl) } @[to_additive, measurability] lemma multiset.measurable_prod (s : multiset (α → M)) (hs : ∀ f ∈ s, measurable f) : measurable (λ x, (s.map (λ f : α → M, f x)).prod) := by simpa only [← pi.multiset_prod_apply] using s.measurable_prod' hs @[to_additive, measurability] lemma multiset.ae_measurable_prod {μ : measure α} (s : multiset (α → M)) (hs : ∀ f ∈ s, ae_measurable f μ) : ae_measurable (λ x, (s.map (λ f : α → M, f x)).prod) μ := by simpa only [← pi.multiset_prod_apply] using s.ae_measurable_prod' hs @[to_additive, measurability] lemma finset.measurable_prod' {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, measurable (f i)) : measurable (∏ i in s, f i) := finset.prod_induction _ _ (λ _ _, measurable.mul) (@measurable_one M _ _ _ _) hf @[to_additive, measurability] lemma finset.measurable_prod {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, measurable (f i)) : measurable (λ a, ∏ i in s, f i a) := by simpa only [← finset.prod_apply] using s.measurable_prod' hf @[to_additive, measurability] lemma finset.ae_measurable_prod' {μ : measure α} {f : ι → α → M} (s : finset ι) (hf : ∀i ∈ s, ae_measurable (f i) μ) : ae_measurable (∏ i in s, f i) μ := multiset.ae_measurable_prod' _ $ λ g hg, let ⟨i, hi, hg⟩ := multiset.mem_map.1 hg in (hg ▸ hf _ hi) @[to_additive, measurability] lemma finset.ae_measurable_prod {f : ι → α → M} {μ : measure α} (s : finset ι) (hf : ∀i ∈ s, ae_measurable (f i) μ) : ae_measurable (λ a, ∏ i in s, f i a) μ := by simpa only [← finset.prod_apply] using s.ae_measurable_prod' hf end comm_monoid attribute [measurability] list.measurable_sum' list.ae_measurable_sum' list.measurable_sum list.ae_measurable_sum multiset.measurable_sum' multiset.ae_measurable_sum' multiset.measurable_sum multiset.ae_measurable_sum finset.measurable_sum' finset.ae_measurable_sum' finset.measurable_sum finset.ae_measurable_sum
3a89cdde90240b1964096b9e3a8b5dbc6915f1d4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/combinatorics/set_family/compression/uv.lean
704e6b0f708dcd070e20ba3463436bf180d814d4
[ "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
17,756
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import combinatorics.set_family.shadow import data.finset.sort /-! # UV-compressions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines UV-compression. It is an operation on a set family that reduces its shadow. UV-compressing `a : α` along `u v : α` means replacing `a` by `(a ⊔ u) \ v` if `a` and `u` are disjoint and `v ≤ a`. In some sense, it's moving `a` from `v` to `u`. UV-compressions are immensely useful to prove the Kruskal-Katona theorem. The idea is that compressing a set family might decrease the size of its shadow, so iterated compressions hopefully minimise the shadow. ## Main declarations * `uv.compress`: `compress u v a` is `a` compressed along `u` and `v`. * `uv.compression`: `compression u v s` is the compression of the set family `s` along `u` and `v`. It is the compressions of the elements of `s` whose compression is not already in `s` along with the element whose compression is already in `s`. This way of splitting into what moves and what does not ensures the compression doesn't squash the set family, which is proved by `uv.card_compression`. * `uv.card_shadow_compression_le`: Compressing reduces the size of the shadow. This is a key fact in the proof of Kruskal-Katona. ## Notation `𝓒` (typed with `\MCC`) is notation for `uv.compression` in locale `finset_family`. ## Notes Even though our emphasis is on `finset α`, we define UV-compressions more generally in a generalized boolean algebra, so that one can use it for `set α`. ## References * https://github.com/b-mehta/maths-notes/blob/master/iii/mich/combinatorics.pdf ## Tags compression, UV-compression, shadow -/ open finset variable {α : Type*} /-- UV-compression is injective on the elements it moves. See `uv.compress`. -/ lemma sup_sdiff_inj_on [generalized_boolean_algebra α] (u v : α) : {x | disjoint u x ∧ v ≤ x}.inj_on (λ x, (x ⊔ u) \ v) := begin rintro a ha b hb hab, have h : (a ⊔ u) \ v \ u ⊔ v = (b ⊔ u) \ v \ u ⊔ v, { dsimp at hab, rw hab }, rwa [sdiff_sdiff_comm, ha.1.symm.sup_sdiff_cancel_right, sdiff_sdiff_comm, hb.1.symm.sup_sdiff_cancel_right, sdiff_sup_cancel ha.2, sdiff_sup_cancel hb.2] at h, end -- The namespace is here to distinguish from other compressions. namespace uv /-! ### UV-compression in generalized boolean algebras -/ section generalized_boolean_algebra variables [generalized_boolean_algebra α] [decidable_rel (@disjoint α _ _)] [decidable_rel ((≤) : α → α → Prop)] {s : finset α} {u v a b : α} local attribute [instance] decidable_eq_of_decidable_le /-- UV-compressing `a` means removing `v` from it and adding `u` if `a` and `u` are disjoint and `v ≤ a` (it replaces the `v` part of `a` by the `u` part). Else, UV-compressing `a` doesn't do anything. This is most useful when `u` and `v` are disjoint finsets of the same size. -/ def compress (u v a : α) : α := if disjoint u a ∧ v ≤ a then (a ⊔ u) \ v else a /-- To UV-compress a set family, we compress each of its elements, except that we don't want to reduce the cardinality, so we keep all elements whose compression is already present. -/ def compression (u v : α) (s : finset α) := s.filter (λ a, compress u v a ∈ s) ∪ (s.image $ compress u v).filter (λ a, a ∉ s) localized "notation (name := uv.compression) `𝓒 ` := uv.compression" in finset_family /-- `is_compressed u v s` expresses that `s` is UV-compressed. -/ def is_compressed (u v : α) (s : finset α) := 𝓒 u v s = s lemma compress_of_disjoint_of_le (hua : disjoint u a) (hva : v ≤ a) : compress u v a = (a ⊔ u) \ v := if_pos ⟨hua, hva⟩ lemma compress_of_disjoint_of_le' (hva : disjoint v a) (hua : u ≤ a) : compress u v ((a ⊔ v) \ u) = a := by rw [compress_of_disjoint_of_le disjoint_sdiff_self_right (le_sdiff.2 ⟨(le_sup_right : v ≤ a ⊔ v), hva.mono_right hua⟩), sdiff_sup_cancel (le_sup_of_le_left hua), hva.symm.sup_sdiff_cancel_right] /-- `a` is in the UV-compressed family iff it's in the original and its compression is in the original, or it's not in the original but it's the compression of something in the original. -/ lemma mem_compression : a ∈ 𝓒 u v s ↔ a ∈ s ∧ compress u v a ∈ s ∨ a ∉ s ∧ ∃ b ∈ s, compress u v b = a := by simp_rw [compression, mem_union, mem_filter, mem_image, and_comm (a ∉ s)] protected lemma is_compressed.eq (h : is_compressed u v s) : 𝓒 u v s = s := h @[simp] lemma compress_self (u a : α) : compress u u a = a := begin unfold compress, split_ifs, { exact h.1.symm.sup_sdiff_cancel_right }, { refl } end @[simp] lemma compression_self (u : α) (s : finset α) : 𝓒 u u s = s := begin unfold compression, convert union_empty s, { ext a, rw [mem_filter, compress_self, and_self] }, { refine eq_empty_of_forall_not_mem (λ a ha, _), simp_rw [mem_filter, mem_image, compress_self] at ha, obtain ⟨⟨b, hb, rfl⟩, hb'⟩ := ha, exact hb' hb } end /-- Any family is compressed along two identical elements. -/ lemma is_compressed_self (u : α) (s : finset α) : is_compressed u u s := compression_self u s /-- An element can be compressed to any other element by removing/adding the differences. -/ @[simp] lemma compress_sdiff_sdiff (a b : α) : compress (a \ b) (b \ a) b = a := begin refine (compress_of_disjoint_of_le disjoint_sdiff_self_left sdiff_le).trans _, rw [sup_sdiff_self_right, sup_sdiff, disjoint_sdiff_self_right.sdiff_eq_left, sup_eq_right], exact sdiff_sdiff_le, end lemma compress_disjoint (u v : α) : disjoint (s.filter (λ a, compress u v a ∈ s)) ((s.image $ compress u v).filter (λ a, a ∉ s)) := disjoint_left.2 $ λ a ha₁ ha₂, (mem_filter.1 ha₂).2 (mem_filter.1 ha₁).1 /-- Compressing an element is idempotent. -/ @[simp] lemma compress_idem (u v a : α) : compress u v (compress u v a) = compress u v a := begin unfold compress, split_ifs with h h', { rw [le_sdiff_iff.1 h'.2, sdiff_bot, sdiff_bot, sup_assoc, sup_idem] }, { refl }, { refl } end lemma compress_mem_compression (ha : a ∈ s) : compress u v a ∈ 𝓒 u v s := begin rw mem_compression, by_cases compress u v a ∈ s, { rw compress_idem, exact or.inl ⟨h, h⟩ }, { exact or.inr ⟨h, a, ha, rfl⟩ } end -- This is a special case of `compress_mem_compression` once we have `compression_idem`. lemma compress_mem_compression_of_mem_compression (ha : a ∈ 𝓒 u v s) : compress u v a ∈ 𝓒 u v s := begin rw mem_compression at ⊢ ha, simp only [compress_idem, exists_prop], obtain ⟨_, ha⟩ | ⟨_, b, hb, rfl⟩ := ha, { exact or.inl ⟨ha, ha⟩ }, { exact or.inr ⟨by rwa compress_idem, b, hb, (compress_idem _ _ _).symm⟩ } end /-- Compressing a family is idempotent. -/ @[simp] lemma compression_idem (u v : α) (s : finset α) : 𝓒 u v (𝓒 u v s) = 𝓒 u v s := begin have h : filter (λ a, compress u v a ∉ 𝓒 u v s) (𝓒 u v s) = ∅ := filter_false_of_mem (λ a ha h, h $ compress_mem_compression_of_mem_compression ha), rw [compression, image_filter, h, image_empty, ←h], exact filter_union_filter_neg_eq _ (compression u v s), end /-- Compressing a family doesn't change its size. -/ @[simp] lemma card_compression (u v : α) (s : finset α) : (𝓒 u v s).card = s.card := begin rw [compression, card_disjoint_union (compress_disjoint _ _), image_filter, card_image_of_inj_on, ←card_disjoint_union, filter_union_filter_neg_eq], { rw disjoint_iff_inter_eq_empty, exact filter_inter_filter_neg_eq _ _ _ }, intros a ha b hb hab, dsimp at hab, rw [mem_coe, mem_filter, function.comp_app] at ha hb, rw compress at ha hab, split_ifs at ha hab with has, { rw compress at hb hab, split_ifs at hb hab with hbs, { exact sup_sdiff_inj_on u v has hbs hab }, { exact (hb.2 hb.1).elim } }, { exact (ha.2 ha.1).elim } end lemma le_of_mem_compression_of_not_mem (h : a ∈ 𝓒 u v s) (ha : a ∉ s) : u ≤ a := begin rw mem_compression at h, obtain _ | ⟨-, b, hb, hba⟩ := h, { cases ha h.1 }, unfold compress at hba, split_ifs at hba, { rw [←hba, le_sdiff], exact ⟨le_sup_right, h.1.mono_right h.2⟩ }, { cases ne_of_mem_of_not_mem hb ha hba } end lemma disjoint_of_mem_compression_of_not_mem (h : a ∈ 𝓒 u v s) (ha : a ∉ s) : disjoint v a := begin rw mem_compression at h, obtain _ | ⟨-, b, hb, hba⟩ := h, { cases ha h.1 }, unfold compress at hba, split_ifs at hba, { rw ←hba, exact disjoint_sdiff_self_right }, { cases ne_of_mem_of_not_mem hb ha hba } end lemma sup_sdiff_mem_of_mem_compression_of_not_mem (h : a ∈ 𝓒 u v s) (ha : a ∉ s) : (a ⊔ v) \ u ∈ s := begin rw mem_compression at h, obtain _ | ⟨-, b, hb, hba⟩ := h, { cases ha h.1 }, unfold compress at hba, split_ifs at hba, { rwa [←hba, sdiff_sup_cancel (le_sup_of_le_left h.2), sup_sdiff_right_self, h.1.symm.sdiff_eq_left] }, { cases ne_of_mem_of_not_mem hb ha hba } end /-- If `a` is in the family compression and can be compressed, then its compression is in the original family. -/ lemma sup_sdiff_mem_of_mem_compression (ha : a ∈ 𝓒 u v s) (hva : v ≤ a) (hua : disjoint u a) : (a ⊔ u) \ v ∈ s := begin rw [mem_compression, compress_of_disjoint_of_le hua hva] at ha, obtain ⟨_, ha⟩ | ⟨_, b, hb, rfl⟩ := ha, { exact ha }, have hu : u = ⊥, { suffices : disjoint u (u \ v), { rwa [(hua.mono_right hva).sdiff_eq_left, disjoint_self] at this }, refine hua.mono_right _, rw [←compress_idem, compress_of_disjoint_of_le hua hva], exact sdiff_le_sdiff_right le_sup_right }, have hv : v = ⊥, { rw ←disjoint_self, apply disjoint.mono_right hva, rw [←compress_idem, compress_of_disjoint_of_le hua hva], exact disjoint_sdiff_self_right }, rwa [hu, hv, compress_self, sup_bot_eq, sdiff_bot], end /-- If `a` is in the `u, v`-compression but `v ≤ a`, then `a` must have been in the original family. -/ lemma mem_of_mem_compression (ha : a ∈ 𝓒 u v s) (hva : v ≤ a) (hvu : v = ⊥ → u = ⊥) : a ∈ s := begin rw mem_compression at ha, obtain ha | ⟨_, b, hb, h⟩ := ha, { exact ha.1 }, unfold compress at h, split_ifs at h, { rw [←h, le_sdiff_iff] at hva, rwa [←h, hvu hva, hva, sup_bot_eq, sdiff_bot] }, { rwa ←h } end end generalized_boolean_algebra /-! ### UV-compression on finsets -/ open_locale finset_family variables [decidable_eq α] {𝒜 : finset (finset α)} {u v a : finset α} /-- Compressing a finset doesn't change its size. -/ lemma card_compress (hUV : u.card = v.card) (A : finset α) : (compress u v A).card = A.card := begin unfold compress, split_ifs, { rw [card_sdiff (h.2.trans le_sup_left), sup_eq_union, card_disjoint_union h.1.symm, hUV, add_tsub_cancel_right] }, { refl } end private lemma aux (huv : ∀ x ∈ u, ∃ y ∈ v, is_compressed (u.erase x) (v.erase y) 𝒜) : v = ∅ → u = ∅ := by { rintro rfl, refine eq_empty_of_forall_not_mem (λ a ha, _), obtain ⟨_, ⟨⟩, -⟩ := huv a ha } /-- UV-compression reduces the size of the shadow of `𝒜` if, for all `x ∈ u` there is `y ∈ v` such that `𝒜` is `(u.erase x, v.erase y)`-compressed. This is the key fact about compression for Kruskal-Katona. -/ lemma shadow_compression_subset_compression_shadow (u v : finset α) (huv : ∀ x ∈ u, ∃ y ∈ v, is_compressed (u.erase x) (v.erase y) 𝒜) : ∂ (𝓒 u v 𝒜) ⊆ 𝓒 u v (∂ 𝒜) := begin set 𝒜' := 𝓒 u v 𝒜, suffices H : ∀ s, s ∈ ∂ 𝒜' → s ∉ ∂ 𝒜 → u ⊆ s ∧ disjoint v s ∧ (s ∪ v) \ u ∈ ∂ 𝒜 ∧ (s ∪ v) \ u ∉ ∂ 𝒜', { rintro s hs', rw mem_compression, by_cases hs : s ∈ 𝒜.shadow, swap, { obtain ⟨hus, hvs, h, _⟩ := H _ hs' hs, exact or.inr ⟨hs, _, h, compress_of_disjoint_of_le' hvs hus⟩ }, refine or.inl ⟨hs, _⟩, rw compress, split_ifs with huvs, swap, { exact hs }, rw mem_shadow_iff at hs', obtain ⟨t, Ht, a, hat, rfl⟩ := hs', have hav : a ∉ v := not_mem_mono huvs.2 (not_mem_erase a t), have hvt : v ≤ t := huvs.2.trans (erase_subset _ t), have ht : t ∈ 𝒜 := mem_of_mem_compression Ht hvt (aux huv), by_cases hau : a ∈ u, { obtain ⟨b, hbv, Hcomp⟩ := huv a hau, refine mem_shadow_iff_insert_mem.2 ⟨b, not_mem_sdiff_of_mem_right hbv, _⟩, rw ←Hcomp.eq at ht, have hsb := sup_sdiff_mem_of_mem_compression ht ((erase_subset _ _).trans hvt) (disjoint_erase_comm.2 huvs.1), rwa [sup_eq_union, sdiff_erase (mem_union_left _ $ hvt hbv), union_erase_of_mem hat, ←erase_union_of_mem hau] at hsb }, { refine mem_shadow_iff.2 ⟨(t ⊔ u) \ v, sup_sdiff_mem_of_mem_compression Ht hvt $ disjoint_of_erase_right hau huvs.1, a, _, _⟩, { rw [sup_eq_union, mem_sdiff, mem_union], exact ⟨or.inl hat, hav⟩ }, { rw [←erase_sdiff_comm, sup_eq_union, erase_union_distrib, erase_eq_of_not_mem hau] } } }, intros s hs𝒜' hs𝒜, -- This is gonna be useful a couple of times so let's name it. have m : ∀ y ∉ s, insert y s ∉ 𝒜 := λ y h a, hs𝒜 (mem_shadow_iff_insert_mem.2 ⟨y, h, a⟩), obtain ⟨x, _, _⟩ := mem_shadow_iff_insert_mem.1 hs𝒜', have hus : u ⊆ insert x s := le_of_mem_compression_of_not_mem ‹_ ∈ 𝒜'› (m _ ‹x ∉ s›), have hvs : disjoint v (insert x s) := disjoint_of_mem_compression_of_not_mem ‹_› (m _ ‹x ∉ s›), have : (insert x s ∪ v) \ u ∈ 𝒜 := sup_sdiff_mem_of_mem_compression_of_not_mem ‹_› (m _ ‹x ∉ s›), have hsv : disjoint s v := hvs.symm.mono_left (subset_insert _ _), have hvu : disjoint v u := disjoint_of_subset_right hus hvs, have hxv : x ∉ v := disjoint_right.1 hvs (mem_insert_self _ _), have : v \ u = v := ‹disjoint v u›.sdiff_eq_left, -- The first key part is that `x ∉ u` have : x ∉ u, { intro hxu, obtain ⟨y, hyv, hxy⟩ := huv x hxu, -- If `x ∈ u`, we can get `y ∈ v` so that `𝒜` is `(u.erase x, v.erase y)`-compressed apply m y (disjoint_right.1 hsv hyv), -- and we will use this `y` to contradict `m`, so we would like to show `insert y s ∈ 𝒜`. -- We do this by showing the below have : ((insert x s ∪ v) \ u ∪ erase u x) \ erase v y ∈ 𝒜, { refine sup_sdiff_mem_of_mem_compression (by rwa hxy.eq) _ (disjoint_of_subset_left (erase_subset _ _) disjoint_sdiff), rw [union_sdiff_distrib, ‹v \ u = v›], exact (erase_subset _ _).trans (subset_union_right _ _) }, -- and then arguing that it's the same convert this, rw [sdiff_union_erase_cancel (hus.trans $ subset_union_left _ _) ‹x ∈ u›, erase_union_distrib, erase_insert ‹x ∉ s›, erase_eq_of_not_mem ‹x ∉ v›, sdiff_erase (mem_union_right _ hyv), union_sdiff_cancel_right hsv] }, -- Now that this is done, it's immediate that `u ⊆ s` have hus : u ⊆ s, { rwa [←erase_eq_of_not_mem ‹x ∉ u›, ←subset_insert_iff] }, -- and we already had that `v` and `s` are disjoint, -- so it only remains to get `(s ∪ v) \ u ∈ ∂ 𝒜 \ ∂ 𝒜'` simp_rw [mem_shadow_iff_insert_mem], refine ⟨hus, hsv.symm, ⟨x, _, _⟩, _⟩, -- `(s ∪ v) \ u ∈ ∂ 𝒜` is pretty direct: { exact not_mem_sdiff_of_not_mem_left (not_mem_union.2 ⟨‹x ∉ s›, ‹x ∉ v›⟩) }, { rwa [←insert_sdiff_of_not_mem _ ‹x ∉ u›, ←insert_union] }, -- For (s ∪ v) \ u ∉ ∂ 𝒜', we split up based on w ∈ u rintro ⟨w, hwB, hw𝒜'⟩, have : v ⊆ insert w ((s ∪ v) \ u) := (subset_sdiff.2 ⟨subset_union_right _ _, hvu⟩).trans (subset_insert _ _), by_cases hwu : w ∈ u, -- If `w ∈ u`, we find `z ∈ v`, and contradict `m` again { obtain ⟨z, hz, hxy⟩ := huv w hwu, apply m z (disjoint_right.1 hsv hz), have : insert w ((s ∪ v) \ u) ∈ 𝒜 := mem_of_mem_compression hw𝒜' ‹_› (aux huv), have : (insert w ((s ∪ v) \ u) ∪ erase u w) \ erase v z ∈ 𝒜, { refine sup_sdiff_mem_of_mem_compression (by rwa hxy.eq) ((erase_subset _ _).trans ‹_›) _, rw ←sdiff_erase (mem_union_left _ $ hus hwu), exact disjoint_sdiff }, convert this, rw [insert_union_comm, insert_erase ‹w ∈ u›, sdiff_union_of_subset (hus.trans $ subset_union_left _ _), sdiff_erase (mem_union_right _ ‹z ∈ v›), union_sdiff_cancel_right hsv] }, -- If `w ∉ u`, we contradict `m` again rw [mem_sdiff, ←not_imp, not_not] at hwB, apply m w (hwu ∘ hwB ∘ mem_union_left _), have : (insert w ((s ∪ v) \ u) ∪ u) \ v ∈ 𝒜 := sup_sdiff_mem_of_mem_compression ‹insert w ((s ∪ v) \ u) ∈ 𝒜'› ‹_› (disjoint_insert_right.2 ⟨‹_›, disjoint_sdiff⟩), convert this, rw [insert_union, sdiff_union_of_subset (hus.trans $ subset_union_left _ _), insert_sdiff_of_not_mem _ (hwu ∘ hwB ∘ mem_union_right _), union_sdiff_cancel_right hsv], end /-- UV-compression reduces the size of the shadow of `𝒜` if, for all `x ∈ u` there is `y ∈ v` such that `𝒜` is `(u.erase x, v.erase y)`-compressed. This is the key UV-compression fact needed for Kruskal-Katona. -/ lemma card_shadow_compression_le (u v : finset α) (huv : ∀ x ∈ u, ∃ y ∈ v, is_compressed (u.erase x) (v.erase y) 𝒜) : (∂ (𝓒 u v 𝒜)).card ≤ (∂ 𝒜).card := (card_le_of_subset $ shadow_compression_subset_compression_shadow _ _ huv).trans (card_compression _ _ _).le end uv
9b12ed83cd7c5fa3b1b9025a1d1b27fbdef27979
f57749ca63d6416f807b770f67559503fdb21001
/hott/algebra/category/adjoint.hlean
5e44dbe514222ccda4f83ea8812fad737030242f
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,789
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn -/ import algebra.category.constructions .constructions types.function arity open category functor nat_trans eq is_trunc iso equiv prod trunc function namespace category variables {C D : Precategory} {F : C ⇒ D} -- do we want to have a structure "is_adjoint" and define -- structure is_left_adjoint (F : C ⇒ D) := -- (right_adjoint : D ⇒ C) -- G -- (is_adjoint : adjoint F right_adjoint) structure is_left_adjoint [class] (F : C ⇒ D) := (G : D ⇒ C) (η : functor.id ⟹ G ∘f F) (ε : F ∘f G ⟹ functor.id) (H : Π(c : C), (ε (F c)) ∘ (F (η c)) = ID (F c)) (K : Π(d : D), (G (ε d)) ∘ (η (G d)) = ID (G d)) abbreviation right_adjoint := @is_left_adjoint.G abbreviation unit := @is_left_adjoint.η abbreviation counit := @is_left_adjoint.ε -- structure is_left_adjoint [class] (F : C ⇒ D) := -- (right_adjoint : D ⇒ C) -- G -- (unit : functor.id ⟹ right_adjoint ∘f F) -- η -- (counit : F ∘f right_adjoint ⟹ functor.id) -- ε -- (H : Π(c : C), (counit (F c)) ∘ (F (unit c)) = ID (F c)) -- (K : Π(d : D), (right_adjoint (counit d)) ∘ (unit (right_adjoint d)) = ID (right_adjoint d)) structure is_equivalence [class] (F : C ⇒ D) extends is_left_adjoint F := mk' :: (is_iso_unit : is_iso η) (is_iso_counit : is_iso ε) structure equivalence (C D : Precategory) := (to_functor : C ⇒ D) (struct : is_equivalence to_functor) --TODO: review and change --TODO: make some or all of these structures? definition faithful (F : C ⇒ D) := Π⦃c c' : C⦄ (f f' : c ⟶ c'), F f = F f' → f = f' definition full (F : C ⇒ D) := Π⦃c c' : C⦄ (g : F c ⟶ F c'), ∃(f : c ⟶ c'), F f = g definition fully_faithful [reducible] (F : C ⇒ D) := Π⦃c c' : C⦄, is_equiv (@(to_fun_hom F) c c') definition split_essentially_surjective (F : C ⇒ D) := Π⦃d : D⦄, Σ(c : C), F c ≅ d definition essentially_surjective (F : C ⇒ D) := Π⦃d : D⦄, ∃(c : C), F c ≅ d definition is_weak_equivalence (F : C ⇒ D) := fully_faithful F × essentially_surjective F definition is_isomorphism (F : C ⇒ D) := fully_faithful F × is_equiv (to_fun_ob F) structure isomorphism (C D : Precategory) := (to_functor : C ⇒ D) (struct : is_isomorphism to_functor) -- infix `⊣`:55 := adjoint infix `⋍`:25 := equivalence -- \backsimeq or \equiv infix `≌`:25 := isomorphism -- \backcong or \iso /- definition is_hprop_is_left_adjoint {C : Category} {D : Precategory} (F : C ⇒ D) : is_hprop (is_left_adjoint F) := begin apply is_hprop.mk, intro G G', cases G with G η ε H K, cases G' with G' η' ε' H' K', fapply (apd011111 is_left_adjoint.mk), { fapply functor_eq, { intro d, apply eq_of_iso, fapply iso.MK, { exact (G' (ε d) ∘ η' (G d))}, { exact (G (ε' d) ∘ η (G' d))}, { apply sorry /-rewrite [assoc, -{((G (ε' d)) ∘ (η (G' d))) ∘ (G' (ε d))}(assoc)],-/ -- apply concat, apply (ap (λc, c ∘ η' _)), rewrite -assoc, apply idp }, -- rewrite [-nat_trans.assoc] apply sorry ---assoc (G (ε' d)) (η (G' d)) (G' (ε d)) { apply sorry}}, { apply sorry}, }, { apply sorry}, { apply sorry}, { apply is_hprop.elim}, { apply is_hprop.elim}, end definition is_equivalence.mk (F : C ⇒ D) (G : D ⇒ C) (η : G ∘f F ≅ functor.id) (ε : F ∘f G ≅ functor.id) : is_equivalence F := sorry definition full_of_fully_faithful (H : fully_faithful F) : full F := sorry -- λc c' g, exists.intro ((@(to_fun_hom F) c c')⁻¹ g) _ definition faithful_of_fully_faithful (H : fully_faithful F) : faithful F := λc c' f f' p, is_injective_of_is_embedding p definition fully_faithful_of_full_of_faithful (H : faithful F) (K : full F) : fully_faithful F := sorry definition fully_faithful_equiv (F : C ⇒ D) : fully_faithful F ≃ (faithful F × full F) := sorry definition is_equivalence_equiv (F : C ⇒ D) : is_equivalence F ≃ (fully_faithful F × split_essentially_surjective F) := sorry definition is_hprop_is_weak_equivalence (F : C ⇒ D) : is_hprop (is_weak_equivalence F) := sorry definition is_hprop_is_equivalence {C D : Category} (F : C ⇒ D) : is_hprop (is_equivalence F) := sorry definition is_equivalence_equiv_is_weak_equivalence {C D : Category} (F : C ⇒ D) : is_equivalence F ≃ is_weak_equivalence F := sorry definition is_hprop_is_isomorphism (F : C ⇒ D) : is_hprop (is_isomorphism F) := sorry definition is_isomorphism_equiv1 (F : C ⇒ D) : is_equivalence F ≃ Σ(G : D ⇒ C) (η : functor.id = G ∘f F) (ε : F ∘f G = functor.id), sorry ▸ ap (λ(H : C ⇒ C), F ∘f H) η = ap (λ(H : D ⇒ D), H ∘f F) ε⁻¹ := sorry definition is_isomorphism_equiv2 (F : C ⇒ D) : is_equivalence F ≃ ∃(G : D ⇒ C), functor.id = G ∘f F × F ∘f G = functor.id := sorry definition is_equivalence_of_isomorphism (H : is_isomorphism F) : is_equivalence F := sorry definition is_isomorphism_of_is_equivalence {C D : Category} {F : C ⇒ D} (H : is_equivalence F) : is_isomorphism F := sorry definition isomorphism_of_eq {C D : Precategory} (p : C = D) : C ≌ D := sorry definition is_equiv_isomorphism_of_eq (C D : Precategory) : is_equiv (@isomorphism_of_eq C D) := sorry definition equivalence_of_eq {C D : Precategory} (p : C = D) : C ⋍ D := sorry definition is_equiv_equivalence_of_eq (C D : Category) : is_equiv (@equivalence_of_eq C D) := sorry -/ end category
ed2c533e5d7c61e5e81c9e949856a000a7b39a34
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/ring.lean
0207bf147824de9db048bcef3757c96690dd6b4a
[ "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
29,973
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 tactic.norm_num import data.int.range /-! # `ring` Evaluate expressions in the language of commutative (semi)rings. Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> . -/ namespace tactic namespace ring /-- The normal form that `ring` uses is mediated by the function `horner a x n b := a * x ^ n + b`. The reason we use a definition rather than the (more readable) expression on the right is because this expression contains a number of typeclass arguments in different positions, while `horner` contains only one `comm_semiring` instance at the top level. See also `horner_expr` for a description of normal form. -/ def horner {α} [comm_semiring α] (a x : α) (n : ℕ) (b : α) := a * x ^ n + b /-- This cache contains data required by the `ring` tactic during execution. -/ meta structure cache := (α : expr) (univ : level) (comm_semiring_inst : expr) (red : transparency) (ic : ref instance_cache) (nc : ref instance_cache) (atoms : ref (buffer expr)) /-- The monad that `ring` works in. This is a reader monad containing a mutable cache (using `ref` for mutability), as well as the list of atoms-up-to-defeq encountered thus far, used for atom sorting. -/ @[derive [monad, alternative]] meta def ring_m (α : Type) : Type := reader_t cache tactic α /-- Get the `ring` data from the monad. -/ meta def get_cache : ring_m cache := reader_t.read /-- Get an already encountered atom by its index. -/ meta def get_atom (n : ℕ) : ring_m expr := ⟨λ c, do es ← read_ref c.atoms, pure (es.read' n)⟩ /-- Get the index corresponding to an atomic expression, if it has already been encountered, or put it in the list of atoms and return the new index, otherwise. -/ meta def add_atom (e : expr) : ring_m ℕ := ⟨λ c, do let red := c.red, es ← read_ref c.atoms, es.iterate failed (λ n e' t, t <|> (is_def_eq e e' red $> n)) <|> (es.size <$ write_ref c.atoms (es.push_back e))⟩ /-- Lift a tactic into the `ring_m` monad. -/ @[inline] meta def lift {α} (m : tactic α) : ring_m α := reader_t.lift m /-- Run a `ring_m` tactic in the tactic monad. This version of `ring_m.run` uses an external atoms ref, so that subexpressions can be named across multiple `ring_m` calls. -/ meta def ring_m.run' (red : transparency) (atoms : ref (buffer expr)) (e : expr) {α} (m : ring_m α) : tactic α := do α ← infer_type e, u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, ic ← mk_instance_cache α, (ic, c) ← ic.get ``comm_semiring, nc ← mk_instance_cache `(ℕ), using_new_ref ic $ λ r, using_new_ref nc $ λ nr, reader_t.run m ⟨α, u, c, red, r, nr, atoms⟩ /-- Run a `ring_m` tactic in the tactic monad. -/ meta def ring_m.run (red : transparency) (e : expr) {α} (m : ring_m α) : tactic α := using_new_ref mk_buffer $ λ atoms, ring_m.run' red atoms e m /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This version is abstract over the instance cache in question (either the ring `α`, or `ℕ` for exponents). -/ @[inline] meta def ic_lift' (icf : cache → ref instance_cache) {α} (f : instance_cache → tactic (instance_cache × α)) : ring_m α := ⟨λ c, do let r := icf c, ic ← read_ref r, (ic', a) ← f ic, a <$ write_ref r ic'⟩ /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to the ring `α`. -/ @[inline] meta def ic_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.ic /-- Lift an instance cache tactic (probably from `norm_num`) to the `ring_m` monad. This uses the instance cache corresponding to `ℕ`, which is used for computations in the exponent. -/ @[inline] meta def nc_lift {α} : (instance_cache → tactic (instance_cache × α)) → ring_m α := ic_lift' cache.nc /-- Apply a theorem that expects a `comm_semiring` instance. This is a special case of `ic_lift mk_app`, but it comes up often because `horner` and all its theorems have this assumption; it also does not require the tactic monad which improves access speed a bit. -/ meta def cache.cs_app (c : cache) (n : name) : list expr → expr := (@expr.const tt n [c.univ] c.α c.comm_semiring_inst).mk_app /-- Every expression in the language of commutative semirings can be viewed as a sum of monomials, where each monomial is a product of powers of atoms. We fix a global order on atoms (up to definitional equality), and then separate the terms according to their smallest atom. So the top level expression is `a * x^n + b` where `x` is the smallest atom and `n > 0` is a numeral, and `n` is maximal (so `a` contains at least one monomial not containing an `x`), and `b` contains no monomials with an `x` (hence all atoms in `b` are larger than `x`). If there is no `x` satisfying these constraints, then the expression must be a numeral. Even though we are working over rings, we allow rational constants when these can be interpreted in the ring, so we can solve problems like `x / 3 = 1 / 3 * x` even though these are not technically in the language of rings. These constraints ensure that there is a unique normal form for each ring expression, and so the algorithm is simply to calculate the normal form of each side and compare for equality. To allow us to efficiently pattern match on normal forms, we maintain this inductive type that holds a normalized expression together with its structure. All the `expr`s in this type could be removed without loss of information, and conversely the `horner_expr` structure and the `ℕ` and `ℚ` values can be recovered from the top level `expr`, but we keep both in order to keep proof producing normalization functions efficient. -/ meta inductive horner_expr : Type | const (e : expr) (coeff : ℚ) : horner_expr | xadd (e : expr) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr /-- Get the expression corresponding to a `horner_expr`. This can be calculated recursively from the structure, but we cache the exprs in all subterms so that this function can be computed in constant time. -/ meta def horner_expr.e : horner_expr → expr | (horner_expr.const e _) := e | (horner_expr.xadd e _ _ _ _) := e /-- Is this expr the constant `0`? -/ meta def horner_expr.is_zero : horner_expr → bool | (horner_expr.const _ c) := c = 0 | _ := ff meta instance : has_coe horner_expr expr := ⟨horner_expr.e⟩ meta instance : has_coe_to_fun horner_expr := ⟨_, λ e, ((e : expr) : expr → expr)⟩ /-- Construct a `xadd` node, generating the cached expr using the input cache. -/ meta def horner_expr.xadd' (c : cache) (a : horner_expr) (x : expr × ℕ) (n : expr × ℕ) (b : horner_expr) : horner_expr := horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b open horner_expr /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.to_string : horner_expr → string | (const e c) := to_string (e, c) | (xadd e a x (_, n) b) := "(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^" ++ to_string n ++ " + " ++ b.to_string /-- Pretty printer for `horner_expr`. -/ meta def horner_expr.pp : horner_expr → tactic format | (const e c) := pp (e, c) | (xadd e a x (_, n) b) := do pa ← a.pp, pb ← b.pp, px ← pp x.1, return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb meta instance : has_to_tactic_format horner_expr := ⟨horner_expr.pp⟩ /-- Reflexivity conversion for a `horner_expr`. -/ meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr × expr) := do p ← lift $ mk_eq_refl e, return (e, p) theorem zero_horner {α} [comm_semiring α] (x n b) : @horner α _ 0 x n b = b := by simp [horner] theorem horner_horner {α} [comm_semiring α] (a₁ x n₁ n₂ b n') (h : n₁ + n₂ = n') : @horner α _ (horner a₁ x n₁ 0) x n₂ b = horner a₁ x n' b := by simp [h.symm, horner, pow_add, mul_assoc] /-- Evaluate `horner a n x b` where `a` and `b` are already in normal form. -/ meta def eval_horner : horner_expr → expr × ℕ → expr × ℕ → horner_expr → ring_m (horner_expr × expr) | ha@(const a coeff) x n b := do c ← get_cache, if coeff = 0 then return (b, c.cs_app ``zero_horner [x.1, n.1, b]) else (xadd' c ha x n b).refl_conv | ha@(xadd a a₁ x₁ n₁ b₁) x n b := do c ← get_cache, if x₁.2 = x.2 ∧ b₁.e.to_nat = some 0 then do (n', h) ← nc_lift $ λ nc, norm_num.prove_add_nat' nc n₁.1 n.1, return (xadd' c a₁ x (n', n₁.2 + n.2) b, c.cs_app ``horner_horner [a₁, x.1, n₁.1, n.1, b, n', h]) else (xadd' c ha x n b).refl_conv theorem const_add_horner {α} [comm_semiring α] (k a x n b b') (h : k + b = b') : k + @horner α _ a x n b = horner a x n b' := by simp [h.symm, horner]; cc theorem horner_add_const {α} [comm_semiring α] (a x n b k b') (h : b + k = b') : @horner α _ a x n b + k = horner a x n b' := by simp [h.symm, horner, add_assoc] theorem horner_add_horner_lt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₁ + k = n₂) (h₂ : (a₁ + horner a₂ x k 0 : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₁ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_gt {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ k a' b') (h₁ : n₂ + k = n₁) (h₂ : (horner a₁ x k 0 + a₂ : α) = a') (h₃ : b₁ + b₂ = b') : @horner α _ a₁ x n₁ b₁ + horner a₂ x n₂ b₂ = horner a' x n₂ b' := by simp [h₂.symm, h₃.symm, h₁.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc theorem horner_add_horner_eq {α} [comm_semiring α] (a₁ x n b₁ a₂ b₂ a' b' t) (h₁ : a₁ + a₂ = a') (h₂ : b₁ + b₂ = b') (h₃ : horner a' x n b' = t) : @horner α _ a₁ x n b₁ + horner a₂ x n b₂ = t := by simp [h₃.symm, h₂.symm, h₁.symm, horner, add_mul, mul_comm (x ^ n)]; cc /-- Evaluate `a + b` where `a` and `b` are already in normal form. -/ meta def eval_add : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := ic_lift $ λ ic, do let n := c₁ + c₂, (ic, e) ← ic.of_rat n, (ic, p) ← norm_num.prove_add_rat ic e₁ e₂ e c₁ c₂ n, return (ic, const e n, p) | he₁@(const e₁ c₁) he₂@(xadd e₂ a x n b) := do c ← get_cache, if c₁ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``zero_add [e₂], return (ic, he₂, p) else do (b', h) ← eval_add he₁ b, return (xadd' c a x n b', c.cs_app ``const_add_horner [e₁, a, x.1, n.1, b, b', h]) | he₁@(xadd e₁ a x n b) he₂@(const e₂ c₂) := do c ← get_cache, if c₂ = 0 then ic_lift $ λ ic, do (ic, p) ← ic.mk_app ``add_zero [e₁], return (ic, he₁, p) else do (b', h) ← eval_add b he₂, return (xadd' c a x n b', c.cs_app ``horner_add_const [a, x.1, n.1, b, e₂, b', h]) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (b', h) ← eval_add b₁ he₂, return (xadd' c a₁ x₁ n₁ b', c.cs_app ``horner_add_const [a₁, x₁.1, n₁.1, b₁, e₂, b', h]) else if x₁.2 ≠ x₂.2 then do (b', h) ← eval_add he₁ b₂, return (xadd' c a₂ x₂ n₂ b', c.cs_app ``const_add_horner [e₁, a₂, x₂.1, n₂.1, b₂, b', h]) else if n₁.2 < n₂.2 then do let k := n₂.2 - n₁.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₁.1 ek n₂.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add a₁ (xadd' c a₂ x₁ (ek, k) (const α0 0)), (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_add_horner_lt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else if n₁.2 ≠ n₂.2 then do let k := n₁.2 - n₂.2, (ek, h₁) ← nc_lift (λ nc, do (nc, ek) ← nc.of_nat k, (nc, h₁) ← norm_num.prove_add_nat nc n₂.1 ek n₁.1, return (nc, ek, h₁)), α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (a', h₂) ← eval_add (xadd' c a₁ x₁ (ek, k) (const α0 0)) a₂, (b', h₃) ← eval_add b₁ b₂, return (xadd' c a' x₁ n₂ b', c.cs_app ``horner_add_horner_gt [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, ek, a', b', h₁, h₂, h₃]) else do (a', h₁) ← eval_add a₁ a₂, (b', h₂) ← eval_add b₁ b₂, (t, h₃) ← eval_horner a' x₁ n₁ b', return (t, c.cs_app ``horner_add_horner_eq [a₁, x₁.1, n₁.1, b₁, a₂, b₂, a', b', t, h₁, h₂, h₃]) theorem horner_neg {α} [comm_ring α] (a x n b a' b') (h₁ : -a = a') (h₂ : -b = b') : -@horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner]; cc /-- Evaluate `-a` where `a` is already in normal form. -/ meta def eval_neg : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_neg ic e, return (const e' (-coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_neg a, (b', h₂) ← eval_neg b, p ← ic_lift $ λ ic, ic.mk_app ``horner_neg [a, x.1, n.1, b, a', b', h₁, h₂], return (xadd' c a' x n b', p) theorem horner_const_mul {α} [comm_semiring α] (c a x n b a' b') (h₁ : c * a = a') (h₂ : c * b = b') : c * @horner α _ a x n b = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, mul_add, mul_assoc] theorem horner_mul_const {α} [comm_semiring α] (a x n b c a' b') (h₁ : a * c = a') (h₂ : b * c = b') : @horner α _ a x n b * c = horner a' x n b' := by simp [h₂.symm, h₁.symm, horner, add_mul, mul_right_comm] /-- Evaluate `k * a` where `k` is a rational numeral and `a` is in normal form. -/ meta def eval_const_mul (k : expr × ℚ) : horner_expr → ring_m (horner_expr × expr) | (const e coeff) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic k.1 e k.2 coeff, return (const e' (k.2 * coeff), p) | (xadd e a x n b) := do c ← get_cache, (a', h₁) ← eval_const_mul a, (b', h₂) ← eval_const_mul b, return (xadd' c a' x n b', c.cs_app ``horner_const_mul [k.1, a, x.1, n.1, b, a', b', h₁, h₂]) theorem horner_mul_horner_zero {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ aa t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ 0 = t := by rw [← h₂, ← h₁]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] theorem horner_mul_horner {α} [comm_semiring α] (a₁ x n₁ b₁ a₂ n₂ b₂ aa haa ab bb t) (h₁ : @horner α _ a₁ x n₁ b₁ * a₂ = aa) (h₂ : horner aa x n₂ 0 = haa) (h₃ : a₁ * b₂ = ab) (h₄ : b₁ * b₂ = bb) (H : haa + horner ab x n₁ bb = t) : horner a₁ x n₁ b₁ * horner a₂ x n₂ b₂ = t := by rw [← H, ← h₂, ← h₁, ← h₃, ← h₄]; simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc] /-- Evaluate `a * b` where `a` and `b` are in normal form. -/ meta def eval_mul : horner_expr → horner_expr → ring_m (horner_expr × expr) | (const e₁ c₁) (const e₂ c₂) := do (e', p) ← ic_lift $ λ ic, norm_num.prove_mul_rat ic e₁ e₂ c₁ c₂, return (const e' (c₁ * c₂), p) | (const e₁ c₁) e₂ := if c₁ = 0 then do c ← get_cache, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], p ← ic_lift $ λ ic, ic.mk_app ``zero_mul [e₂], return (const α0 0, p) else if c₁ = 1 then do p ← ic_lift $ λ ic, ic.mk_app ``one_mul [e₂], return (e₂, p) else eval_const_mul (e₁, c₁) e₂ | e₁ he₂@(const e₂ c₂) := do p₁ ← ic_lift $ λ ic, ic.mk_app ``mul_comm [e₁, e₂], (e', p₂) ← eval_mul he₂ e₁, p ← lift $ mk_eq_trans p₁ p₂, return (e', p) | he₁@(xadd e₁ a₁ x₁ n₁ b₁) he₂@(xadd e₂ a₂ x₂ n₂ b₂) := do c ← get_cache, if x₁.2 < x₂.2 then do (a', h₁) ← eval_mul a₁ he₂, (b', h₂) ← eval_mul b₁ he₂, return (xadd' c a' x₁ n₁ b', c.cs_app ``horner_mul_const [a₁, x₁.1, n₁.1, b₁, e₂, a', b', h₁, h₂]) else if x₁.2 ≠ x₂.2 then do (a', h₁) ← eval_mul he₁ a₂, (b', h₂) ← eval_mul he₁ b₂, return (xadd' c a' x₂ n₂ b', c.cs_app ``horner_const_mul [e₁, a₂, x₂.1, n₂.1, b₂, a', b', h₁, h₂]) else do (aa, h₁) ← eval_mul he₁ a₂, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], (haa, h₂) ← eval_horner aa x₁ n₂ (const α0 0), if b₂.is_zero then return (haa, c.cs_app ``horner_mul_horner_zero [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, aa, haa, h₁, h₂]) else do (ab, h₃) ← eval_mul a₁ b₂, (bb, h₄) ← eval_mul b₁ b₂, (t, H) ← eval_add haa (xadd' c ab x₁ n₁ bb), return (t, c.cs_app ``horner_mul_horner [a₁, x₁.1, n₁.1, b₁, a₂, n₂.1, b₂, aa, haa, ab, bb, t, h₁, h₂, h₃, h₄, H]) theorem horner_pow {α} [comm_semiring α] (a x n m n' a') (h₁ : n * m = n') (h₂ : a ^ m = a') : @horner α _ a x n 0 ^ m = horner a' x n' 0 := by simp [h₁.symm, h₂.symm, horner, mul_pow, pow_mul] theorem pow_succ {α} [comm_semiring α] (a n b c) (h₁ : (a:α) ^ n = b) (h₂ : b * a = c) : a ^ (n + 1) = c := by rw [← h₂, ← h₁, pow_succ'] /-- Evaluate `a ^ n` where `a` is in normal form and `n` is a natural numeral. -/ meta def eval_pow : horner_expr → expr × ℕ → ring_m (horner_expr × expr) | e (_, 0) := do c ← get_cache, α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], p ← ic_lift $ λ ic, ic.mk_app ``pow_zero [e], return (const α1 1, p) | e (_, 1) := do p ← ic_lift $ λ ic, ic.mk_app ``pow_one [e], return (e, p) | (const e coeff) (e₂, m) := ic_lift $ λ ic, do (ic, e', p) ← norm_num.prove_pow e coeff ic e₂, return (ic, const e' (coeff ^ m), p) | he@(xadd e a x n b) m := do c ← get_cache, match b.e.to_nat with | some 0 := do (n', h₁) ← nc_lift $ λ nc, norm_num.prove_mul_rat nc n.1 m.1 n.2 m.2, (a', h₂) ← eval_pow a m, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], return (xadd' c a' x (n', n.2 * m.2) (const α0 0), c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', h₁, h₂]) | _ := do e₂ ← nc_lift $ λ nc, nc.of_nat (m.2-1), (tl, hl) ← eval_pow he (e₂, m.2-1), (t, p₂) ← eval_mul tl he, return (t, c.cs_app ``pow_succ [e, e₂, tl, t, hl, p₂]) end theorem horner_atom {α} [comm_semiring α] (x : α) : x = horner 1 x 1 0 := by simp [horner] /-- Evaluate `a` where `a` is an atom. -/ meta def eval_atom (e : expr) : ring_m (horner_expr × expr) := do c ← get_cache, i ← add_atom e, α0 ← ic_lift $ λ ic, ic.mk_app ``has_zero.zero [], α1 ← ic_lift $ λ ic, ic.mk_app ``has_one.one [], return (xadd' c (const α1 1) (e, i) (`(1), 1) (const α0 0), c.cs_app ``horner_atom [e]) lemma subst_into_pow {α} [monoid α] (l r tl tr t) (prl : (l : α) = tl) (prr : (r : ℕ) = tr) (prt : tl ^ tr = t) : l ^ r = t := by rw [prl, prr, prt] lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := by rw [sub_eq_add_neg, h] lemma unfold_div {α} [division_ring α] (a b c : α) (h : a * b⁻¹ = c) : a / b = c := by rw [div_eq_mul_inv, h] /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval : expr → ring_m (horner_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(@has_sub.sub %%α %%inst %%e₁ %%e₂) := mcond (succeeds (lift $ mk_app ``comm_ring [α] >>= mk_instance)) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_neg.neg [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_sub [e₁, e₂, e', p], return (e', p')) (eval_atom e) | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg e₁, p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(%%e₁ * %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_mul e₁' e₂', p ← ic_lift $ λ ic, ic.mk_app ``norm_num.subst_into_mul [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | e@`(has_inv.inv %%_) := (do (e', p) ← lift $ norm_num.derive e <|> refl_conv e, n ← lift $ e'.to_rat, return (const e' n, p)) <|> eval_atom e | e@`(@has_div.div _ %%inst %%e₁ %%e₂) := mcond (succeeds (do inst' ← ic_lift $ λ ic, ic.mk_app ``div_inv_monoid.to_has_div [], lift $ is_def_eq inst inst')) (do e₂' ← ic_lift $ λ ic, ic.mk_app ``has_inv.inv [e₂], e ← ic_lift $ λ ic, ic.mk_app ``has_mul.mul [e₁, e₂'], (e', p) ← eval e, p' ← ic_lift $ λ ic, ic.mk_app ``unfold_div [e₁, e₂, e', p], return (e', p')) (eval_atom e) | e@`(@has_pow.pow _ _ %%P %%e₁ %%e₂) := do (e₂', p₂) ← lift $ norm_num.derive e₂ <|> refl_conv e₂, match e₂'.to_nat, P with | some k, `(monoid.has_pow) := do (e₁', p₁) ← eval e₁, (e', p') ← eval_pow e₁' (e₂, k), p ← ic_lift $ λ ic, ic.mk_app ``subst_into_pow [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | _, _ := eval_atom e end | e := match e.to_nat with | some n := (const e (rat.of_int n)).refl_conv | none := eval_atom e end /-- Evaluate a ring expression `e` recursively to normal form, together with a proof of equality. -/ meta def eval' (red : transparency) (atoms : ref (buffer expr)) (e : expr) : tactic (expr × expr) := ring_m.run' red atoms e $ do (e', p) ← eval e, return (e', p) theorem horner_def' {α} [comm_semiring α] (a x n b) : @horner α _ a x n b = x ^ n * a + b := by simp [horner, mul_comm] theorem mul_assoc_rev {α} [semigroup α] (a b c : α) : a * (b * c) = a * b * c := by simp [mul_assoc] theorem pow_add_rev {α} [monoid α] (a : α) (m n : ℕ) : a ^ m * a ^ n = a ^ (m + n) := by simp [pow_add] theorem pow_add_rev_right {α} [monoid α] (a b : α) (m n : ℕ) : b * a ^ m * a ^ n = b * a ^ (m + n) := by simp [pow_add, mul_assoc] theorem add_neg_eq_sub {α} [add_group α] (a b : α) : a + -b = a - b := (sub_eq_add_neg a b).symm /-- If `ring` fails to close the goal, it falls back on normalizing the expression to a "pretty" form so that you can see why it failed. This setting adjusts the resulting form: * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ @[derive has_reflect] inductive normalize_mode | raw | SOP | horner instance : inhabited normalize_mode := ⟨normalize_mode.horner⟩ /-- A `ring`-based normalization simplifier that rewrites ring expressions into the specified mode. * `raw` is the form that `ring` actually uses internally, with iterated applications of `horner`. Not very readable but useful if you don't want any postprocessing. This results in terms like `horner (horner (horner 3 y 1 0) x 2 1) x 1 (horner 1 y 1 0)`. * `horner` maintains the Horner form structure, but it unfolds the `horner` definition itself, and tries to otherwise minimize parentheses. This results in terms like `(3 * x ^ 2 * y + 1) * x + y`. * `SOP` means sum of products form, expanding everything to monomials. This results in terms like `3 * x ^ 3 * y + x + y`. -/ meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr × expr) := using_new_ref mk_buffer $ λ atoms, do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.SOP := [``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub, ``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right, ``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub] | normalize_mode.horner := [``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one, ``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do (new_e, pr) ← match mode with | normalize_mode.raw := eval' red atoms | normalize_mode.horner := trans_conv (eval' red atoms) (λ e, do (e', prf, _) ← simplify lemmas [] e, return (e', prf)) | normalize_mode.SOP := trans_conv (eval' red atoms) $ trans_conv (λ e, do (e', prf, _) ← simplify lemmas [] e, return (e', prf)) $ simp_bottom_up' (λ e, norm_num.derive e <|> pow_lemma.rewrite e) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end ring namespace interactive open interactive interactive.types lean.parser open tactic.ring local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *commutative* (semi)rings. This version of `ring` fails if the target is not an equality that is provable by the axioms of commutative (semi)rings. -/ meta def ring1 (red : parse (tk "!")?) : tactic unit := let transp := if red.is_some then semireducible else reducible in do `(%%e₁ = %%e₂) ← target, ((e₁', p₁), (e₂', p₂)) ← ring_m.run transp e₁ $ prod.mk <$> eval e₁ <*> eval e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p /-- Parser for `ring_nf`'s `mode` argument, which can only be the "keywords" `raw`, `horner` or `SOP`. (Because these are not actually keywords we use a name parser and postprocess the result.) -/ meta def ring.mode : lean.parser ring.normalize_mode := with_desc "(SOP|raw|horner)?" $ do mode ← ident?, match mode with | none := return ring.normalize_mode.horner | some `horner := return ring.normalize_mode.horner | some `SOP := return ring.normalize_mode.SOP | some `raw := return ring.normalize_mode.raw | _ := failed end /-- Simplification tactic for expressions in the language of commutative (semi)rings, which rewrites all ring expressions into a normal form. When writing a normal form, `ring_nf SOP` will use sum-of-products form instead of horner form. `ring_nf!` will use a more aggressive reducibility setting to identify atoms. -/ meta def ring_nf (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit := do ns ← loc.get_locals, let transp := if red.is_some then semireducible else reducible, tt ← tactic.replace_at (normalize transp SOP) ns loc.include_goal | fail "ring_nf failed to simplify", when loc.include_goal $ try tactic.reflexivity /-- Tactic for solving equations in the language of *commutative* (semi)rings. `ring!` will use a more aggressive reducibility setting to identify atoms. If the goal is not solvable, it falls back to rewriting all ring expressions into a normal form, with a suggestion to use `ring_nf` instead, if this is the intent. See also `ring1`, which is the same as `ring` but without the fallback behavior. Based on [Proving Equalities in a Commutative Ring Done Right in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin Grégoire and Assia Mahboubi. -/ meta def ring (red : parse (tk "!")?) : tactic unit := ring1 red <|> (ring_nf red normalize_mode.horner (loc.ns [none]) >> trace "Try this: ring_nf") add_hint_tactic "ring" add_tactic_doc { name := "ring", category := doc_category.tactic, decl_names := [``ring, ``ring_nf, ``ring1], inherit_description_from := ``ring, tags := ["arithmetic", "simplification", "decision procedure"] } end interactive end tactic namespace conv.interactive open conv interactive open tactic tactic.interactive (ring.mode ring1) open tactic.ring (normalize normalize_mode.horner) local postfix `?`:9001 := optional /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring_nf (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit := let transp := if red.is_some then semireducible else reducible in replace_lhs (normalize transp SOP) <|> fail "ring_nf failed to simplify" /-- Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic `ring`. -/ meta def ring (red : parse (lean.parser.tk "!")?) : conv unit := let transp := if red.is_some then semireducible else reducible in discharge_eq_lhs (ring1 red) <|> (replace_lhs (normalize transp normalize_mode.horner) >> trace "Try this: ring_nf") <|> fail "ring failed to simplify" end conv.interactive
12d86c92fd3eaa6635b2a9277d05dbac196dc84b
2fbe653e4bc441efde5e5d250566e65538709888
/scripts/mk_nolint.lean
34d168b5897ac05df5e4ee36b2bbe382e4403b21
[ "Apache-2.0" ]
permissive
aceg00/mathlib
5e15e79a8af87ff7eb8c17e2629c442ef24e746b
8786ea6d6d46d6969ac9a869eb818bf100802882
refs/heads/master
1,649,202,698,930
1,580,924,783,000
1,580,924,783,000
149,197,272
0
0
Apache-2.0
1,537,224,208,000
1,537,224,207,000
null
UTF-8
Lean
false
false
1,482
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.lint system.io data.list.sort -- these are required import all -- then import everything, to parse the library for failing linters /-! # mk_nolint Defines a function that writes a file containing the names of all declarations that fail the linting tests in `active_linters`. This is mainly used in the Travis check for mathlib. It assumes that files generated by `mk_all.sh` are present. Usage: `lean --run mk_nolint.lean` writes a file `nolints.txt` in the current directory. -/ open io io.fs /-- Defines the list of linters that will be considered. -/ meta def active_linters := [`linter.unused_arguments, `linter.dup_namespace, `linter.doc_blame, `linter.ge_or_gt, `linter.def_lemma, `linter.instance_priority, --`linter.has_inhabited_instance, `linter.impossible_instance, `linter.incorrect_type_class_argument, `linter.dangerous_instance] /-- Runs when called with `lean --run` -/ meta def main : io unit := do (ns, _) ← run_tactic $ lint_mathlib tt tt active_linters tt, handle ← mk_file_handle "nolints.txt" mode.write, put_str_ln handle "import .all", put_str_ln handle "run_cmd tactic.skip", put_str_ln handle "apply_nolint", (ns.to_list.merge_sort (λ a b, name.lex_cmp a b = ordering.lt)).mmap $ λ n, put_str_ln handle (to_string n) >> return n, close handle
5c41dcd45390e28c4d45498236be677a64e2a63b
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/group_theory/submonoid/basic.lean
5a78845eb91cd946fe6954899750683ed0248f4f
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
15,887
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Kenny Lau, Johan Commelin, Mario Carneiro, Kevin Buzzard, Amelia Livingston, Yury Kudryashov -/ import algebra.group.basic import data.set.lattice /-! # Submonoids: definition and `complete_lattice` structure This file defines bundled multiplicative and additive submonoids. We also define a `complete_lattice` structure on `submonoid`s, define the closure of a set as the minimal submonoid that includes this set, and prove a few results about extending properties from a dense set (i.e. a set with `closure s = ⊤`) to the whole monoid, see `submonoid.dense_induction` and `monoid_hom.of_mdense`. ## Main definitions * `submonoid M`: the type of bundled submonoids of a monoid `M`; the underlying set is given in the `carrier` field of the structure, and should be accessed through coercion as in `(S : set M)`. * `add_submonoid M` : the type of bundled submonoids of an additive monoid `M`. For each of the following definitions in the `submonoid` namespace, there is a corresponding definition in the `add_submonoid` namespace. * `submonoid.copy` : copy of a submonoid with `carrier` replaced by a set that is equal but possibly not definitionally equal to the carrier of the original `submonoid`. * `submonoid.closure` : monoid closure of a set, i.e., the least submonoid that includes the set. * `submonoid.gi` : `closure : set M → submonoid M` and coercion `coe : submonoid M → set M` form a `galois_insertion`; * `monoid_hom.eq_mlocus`: the submonoid of elements `x : M` such that `f x = g x`; * `monoid_hom.of_mdense`: if a map `f : M → N` between two monoids satisfies `f 1 = 1` and `f (x * y) = f x * f y` for `y` from some dense set `s`, then `f` is a monoid homomorphism. E.g., if `f : ℕ → M` satisfies `f 0 = 0` and `f (x + 1) = f x + f 1`, then `f` is an additive monoid homomorphism. ## Implementation notes Submonoid inclusion is denoted `≤` rather than `⊆`, although `∈` is defined as membership of a submonoid's underlying set. This file is designed to have very few dependencies. In particular, it should not use natural numbers. ## Tags submonoid, submonoids -/ variables {M : Type*} [monoid M] {s : set M} variables {A : Type*} [add_monoid A] {t : set A} /-- A submonoid of a monoid `M` is a subset containing 1 and closed under multiplication. -/ structure submonoid (M : Type*) [monoid M] := (carrier : set M) (one_mem' : (1 : M) ∈ carrier) (mul_mem' {a b} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier) /-- An additive submonoid of an additive monoid `M` is a subset containing 0 and closed under addition. -/ structure add_submonoid (M : Type*) [add_monoid M] := (carrier : set M) (zero_mem' : (0 : M) ∈ carrier) (add_mem' {a b} : a ∈ carrier → b ∈ carrier → a + b ∈ carrier) attribute [to_additive add_submonoid] submonoid namespace submonoid @[to_additive] instance : has_coe (submonoid M) (set M) := ⟨submonoid.carrier⟩ @[to_additive] instance : has_coe_to_sort (submonoid M) := ⟨Type*, λ S, S.carrier⟩ @[to_additive] instance : has_mem M (submonoid M) := ⟨λ m S, m ∈ (S:set M)⟩ @[simp, to_additive] lemma mem_carrier {s : submonoid M} {x : M} : x ∈ s.carrier ↔ x ∈ s := iff.rfl @[simp, norm_cast, to_additive] lemma mem_coe {S : submonoid M} {m : M} : m ∈ (S : set M) ↔ m ∈ S := iff.rfl @[simp, norm_cast, to_additive] lemma coe_coe (s : submonoid M) : ↥(s : set M) = s := rfl attribute [norm_cast] add_submonoid.mem_coe add_submonoid.coe_coe @[to_additive] protected lemma «exists» {s : submonoid M} {p : s → Prop} : (∃ x : s, p x) ↔ ∃ x ∈ s, p ⟨x, ‹x ∈ s›⟩ := set_coe.exists @[to_additive] protected lemma «forall» {s : submonoid M} {p : s → Prop} : (∀ x : s, p x) ↔ ∀ x ∈ s, p ⟨x, ‹x ∈ s›⟩ := set_coe.forall /-- Two submonoids are equal if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if the underlying subsets are equal."] theorem ext' ⦃S T : submonoid M⦄ (h : (S : set M) = T) : S = T := by cases S; cases T; congr' /-- Two submonoids are equal if and only if the underlying subsets are equal. -/ @[to_additive "Two `add_submonoid`s are equal if and only if the underlying subsets are equal."] protected theorem ext'_iff {S T : submonoid M} : S = T ↔ (S : set M) = T := ⟨λ h, h ▸ rfl, λ h, ext' h⟩ /-- Two submonoids are equal if they have the same elements. -/ @[ext, to_additive "Two `add_submonoid`s are equal if they have the same elements."] theorem ext {S T : submonoid M} (h : ∀ x, x ∈ S ↔ x ∈ T) : S = T := ext' $ set.ext h attribute [ext] add_submonoid.ext /-- Copy a submonoid replacing `carrier` with a set that is equal to it. -/ @[to_additive "Copy an additive submonoid replacing `carrier` with a set that is equal to it."] def copy (S : submonoid M) (s : set M) (hs : s = S) : submonoid M := { carrier := s, one_mem' := hs.symm ▸ S.one_mem', mul_mem' := hs.symm ▸ S.mul_mem' } variable {S : submonoid M} @[simp, to_additive] lemma coe_copy {s : set M} (hs : s = S) : (S.copy s hs : set M) = s := rfl @[to_additive] lemma copy_eq {s : set M} (hs : s = S) : S.copy s hs = S := ext' hs variable (S) /-- A submonoid contains the monoid's 1. -/ @[to_additive "An `add_submonoid` contains the monoid's 0."] theorem one_mem : (1 : M) ∈ S := S.one_mem' /-- A submonoid is closed under multiplication. -/ @[to_additive "An `add_submonoid` is closed under addition."] theorem mul_mem {x y : M} : x ∈ S → y ∈ S → x * y ∈ S := submonoid.mul_mem' S @[simp, to_additive] lemma coe_eq_coe (x y : S) : (x : M) = y ↔ x = y := set_coe.ext_iff attribute [norm_cast] coe_eq_coe add_submonoid.coe_eq_coe @[to_additive] instance : has_le (submonoid M) := ⟨λ S T, ∀ ⦃x⦄, x ∈ S → x ∈ T⟩ @[to_additive] lemma le_def {S T : submonoid M} : S ≤ T ↔ ∀ ⦃x : M⦄, x ∈ S → x ∈ T := iff.rfl @[simp, norm_cast, to_additive] lemma coe_subset_coe {S T : submonoid M} : (S : set M) ⊆ T ↔ S ≤ T := iff.rfl @[to_additive] instance : partial_order (submonoid M) := { le := λ S T, ∀ ⦃x⦄, x ∈ S → x ∈ T, .. partial_order.lift (coe : submonoid M → set M) ext' } @[simp, norm_cast, to_additive] lemma coe_ssubset_coe {S T : submonoid M} : (S : set M) ⊂ T ↔ S < T := iff.rfl attribute [norm_cast] add_submonoid.coe_subset_coe add_submonoid.coe_ssubset_coe /-- The submonoid `M` of the monoid `M`. -/ @[to_additive "The additive submonoid `M` of the `add_monoid M`."] instance : has_top (submonoid M) := ⟨{ carrier := set.univ, one_mem' := set.mem_univ 1, mul_mem' := λ _ _ _ _, set.mem_univ _ }⟩ /-- The trivial submonoid `{1}` of an monoid `M`. -/ @[to_additive "The trivial `add_submonoid` `{0}` of an `add_monoid` `M`."] instance : has_bot (submonoid M) := ⟨{ carrier := {1}, one_mem' := set.mem_singleton 1, mul_mem' := λ a b ha hb, by { simp only [set.mem_singleton_iff] at *, rw [ha, hb, mul_one] }}⟩ @[to_additive] instance : inhabited (submonoid M) := ⟨⊥⟩ @[simp, to_additive] lemma mem_bot {x : M} : x ∈ (⊥ : submonoid M) ↔ x = 1 := set.mem_singleton_iff @[simp, to_additive] lemma mem_top (x : M) : x ∈ (⊤ : submonoid M) := set.mem_univ x @[simp, to_additive] lemma coe_top : ((⊤ : submonoid M) : set M) = set.univ := rfl @[simp, to_additive] lemma coe_bot : ((⊥ : submonoid M) : set M) = {1} := rfl /-- The inf of two submonoids is their intersection. -/ @[to_additive "The inf of two `add_submonoid`s is their intersection."] instance : has_inf (submonoid M) := ⟨λ S₁ S₂, { carrier := S₁ ∩ S₂, one_mem' := ⟨S₁.one_mem, S₂.one_mem⟩, mul_mem' := λ _ _ ⟨hx, hx'⟩ ⟨hy, hy'⟩, ⟨S₁.mul_mem hx hy, S₂.mul_mem hx' hy'⟩ }⟩ @[simp, to_additive] lemma coe_inf (p p' : submonoid M) : ((p ⊓ p' : submonoid M) : set M) = p ∩ p' := rfl @[simp, to_additive] lemma mem_inf {p p' : submonoid M} {x : M} : x ∈ p ⊓ p' ↔ x ∈ p ∧ x ∈ p' := iff.rfl @[to_additive] instance : has_Inf (submonoid M) := ⟨λ s, { carrier := ⋂ t ∈ s, ↑t, one_mem' := set.mem_bInter $ λ i h, i.one_mem, mul_mem' := λ x y hx hy, set.mem_bInter $ λ i h, i.mul_mem (by apply set.mem_bInter_iff.1 hx i h) (by apply set.mem_bInter_iff.1 hy i h) }⟩ @[simp, to_additive] lemma coe_Inf (S : set (submonoid M)) : ((Inf S : submonoid M) : set M) = ⋂ s ∈ S, ↑s := rfl @[to_additive] lemma mem_Inf {S : set (submonoid M)} {x : M} : x ∈ Inf S ↔ ∀ p ∈ S, x ∈ p := set.mem_bInter_iff @[to_additive] lemma mem_infi {ι : Sort*} {S : ι → submonoid M} {x : M} : (x ∈ ⨅ i, S i) ↔ ∀ i, x ∈ S i := by simp only [infi, mem_Inf, set.forall_range_iff] @[simp, to_additive] lemma coe_infi {ι : Sort*} {S : ι → submonoid M} : (↑(⨅ i, S i) : set M) = ⋂ i, S i := by simp only [infi, coe_Inf, set.bInter_range] attribute [norm_cast] coe_Inf coe_infi /-- Submonoids of a monoid form a complete lattice. -/ @[to_additive "The `add_submonoid`s of an `add_monoid` form a complete lattice."] instance : complete_lattice (submonoid M) := { le := (≤), lt := (<), bot := (⊥), bot_le := λ S x hx, (mem_bot.1 hx).symm ▸ S.one_mem, top := (⊤), le_top := λ S x hx, mem_top x, inf := (⊓), Inf := has_Inf.Inf, le_inf := λ a b c ha hb x hx, ⟨ha hx, hb hx⟩, inf_le_left := λ a b x, and.left, inf_le_right := λ a b x, and.right, .. complete_lattice_of_Inf (submonoid M) $ λ s, is_glb.of_image (λ S T, show (S : set M) ≤ T ↔ S ≤ T, from coe_subset_coe) is_glb_binfi } /-- The `submonoid` generated by a set. -/ @[to_additive "The `add_submonoid` generated by a set"] def closure (s : set M) : submonoid M := Inf {S | s ⊆ S} @[to_additive] lemma mem_closure {x : M} : x ∈ closure s ↔ ∀ S : submonoid M, s ⊆ S → x ∈ S := mem_Inf /-- The submonoid generated by a set includes the set. -/ @[simp, to_additive "The `add_submonoid` generated by a set includes the set."] lemma subset_closure : s ⊆ closure s := λ x hx, mem_closure.2 $ λ S hS, hS hx variable {S} open set /-- A submonoid `S` includes `closure s` if and only if it includes `s`. -/ @[simp, to_additive "An additive submonoid `S` includes `closure s` if and only if it includes `s`"] lemma closure_le : closure s ≤ S ↔ s ⊆ S := ⟨subset.trans subset_closure, λ h, Inf_le h⟩ /-- Submonoid closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`. -/ @[to_additive "Additive submonoid closure of a set is monotone in its argument: if `s ⊆ t`, then `closure s ≤ closure t`"] lemma closure_mono ⦃s t : set M⦄ (h : s ⊆ t) : closure s ≤ closure t := closure_le.2 $ subset.trans h subset_closure @[to_additive] lemma closure_eq_of_le (h₁ : s ⊆ S) (h₂ : S ≤ closure s) : closure s = S := le_antisymm (closure_le.2 h₁) h₂ variable (S) /-- An induction principle for closure membership. If `p` holds for `1` and all elements of `s`, and is preserved under multiplication, then `p` holds for all elements of the closure of `s`. -/ @[to_additive "An induction principle for additive closure membership. If `p` holds for `0` and all elements of `s`, and is preserved under addition, then `p` holds for all elements of the additive closure of `s`."] lemma closure_induction {p : M → Prop} {x} (h : x ∈ closure s) (Hs : ∀ x ∈ s, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := (@closure_le _ _ _ ⟨p, H1, Hmul⟩).2 Hs h attribute [elab_as_eliminator] submonoid.closure_induction add_submonoid.closure_induction /-- If `s` is a dense set in a monoid `M`, `submonoid.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 1`, and verify that `p x` and `p y` imply `p (x * y)`. -/ @[to_additive] lemma dense_induction {p : M → Prop} (x : M) {s : set M} (hs : closure s = ⊤) (Hs : ∀ x ∈ s, p x) (H1 : p 1) (Hmul : ∀ x y, p x → p y → p (x * y)) : p x := have ∀ x ∈ closure s, p x, from λ x hx, closure_induction hx Hs H1 Hmul, by simpa [hs] using this x /-- If `s` is a dense set in an additive monoid `M`, `add_submonoid.closure s = ⊤`, then in order to prove that some predicate `p` holds for all `x : M` it suffices to verify `p x` for `x ∈ s`, verify `p 0`, and verify that `p x` and `p y` imply `p (x + y)`. -/ add_decl_doc add_submonoid.dense_induction attribute [elab_as_eliminator] dense_induction add_submonoid.dense_induction variable (M) /-- `closure` forms a Galois insertion with the coercion to set. -/ @[to_additive "`closure` forms a Galois insertion with the coercion to set."] protected def gi : galois_insertion (@closure M _) coe := { choice := λ s _, closure s, gc := λ s t, closure_le, le_l_u := λ s, subset_closure, choice_eq := λ s h, rfl } variable {M} /-- Closure of a submonoid `S` equals `S`. -/ @[simp, to_additive "Additive closure of an additive submonoid `S` equals `S`"] lemma closure_eq : closure (S : set M) = S := (submonoid.gi M).l_u_eq S @[simp, to_additive] lemma closure_empty : closure (∅ : set M) = ⊥ := (submonoid.gi M).gc.l_bot @[simp, to_additive] lemma closure_univ : closure (univ : set M) = ⊤ := @coe_top M _ ▸ closure_eq ⊤ @[to_additive] lemma closure_union (s t : set M) : closure (s ∪ t) = closure s ⊔ closure t := (submonoid.gi M).gc.l_sup @[to_additive] lemma closure_Union {ι} (s : ι → set M) : closure (⋃ i, s i) = ⨆ i, closure (s i) := (submonoid.gi M).gc.l_supr end submonoid namespace monoid_hom variables {N : Type*} {P : Type*} [monoid N] [monoid P] (S : submonoid M) open submonoid /-- The submonoid of elements `x : M` such that `f x = g x` -/ @[to_additive "The additive submonoid of elements `x : M` such that `f x = g x`"] def eq_mlocus (f g : M →* N) : submonoid M := { carrier := {x | f x = g x}, one_mem' := by rw [set.mem_set_of_eq, f.map_one, g.map_one], mul_mem' := λ x y (hx : _ = _) (hy : _ = _), by simp [*] } /-- If two monoid homomorphisms are equal on a set, then they are equal on its submonoid closure. -/ @[to_additive] lemma eq_on_mclosure {f g : M →* N} {s : set M} (h : set.eq_on f g s) : set.eq_on f g (closure s) := show closure s ≤ f.eq_mlocus g, from closure_le.2 h @[to_additive] lemma eq_of_eq_on_mtop {f g : M →* N} (h : set.eq_on f g (⊤ : submonoid M)) : f = g := ext $ λ x, h trivial @[to_additive] lemma eq_of_eq_on_mdense {s : set M} (hs : closure s = ⊤) {f g : M →* N} (h : s.eq_on f g) : f = g := eq_of_eq_on_mtop $ hs ▸ eq_on_mclosure h /-- Let `s` be a subset of a monoid `M` such that the closure of `s` is the whole monoid. Then `monoid_hom.of_mdense` defines a monoid homomorphism from `M` asking for a proof of `f (x * y) = f x * f y` only for `y ∈ s`. -/ @[to_additive] def of_mdense (f : M → N) (hs : closure s = ⊤) (h1 : f 1 = 1) (hmul : ∀ x (y ∈ s), f (x * y) = f x * f y) : M →* N := { to_fun := f, map_one' := h1, map_mul' := λ x y, dense_induction y hs (λ y hy x, hmul x y hy) (by simp [h1]) (λ y₁ y₂ h₁ h₂ x, by simp only [← mul_assoc, h₁, h₂]) x } /-- Let `s` be a subset of an additive monoid `M` such that the closure of `s` is the whole monoid. Then `add_monoid_hom.of_mdense` defines an additive monoid homomorphism from `M` asking for a proof of `f (x + y) = f x + f y` only for `y ∈ s`. -/ add_decl_doc add_monoid_hom.of_mdense @[simp, to_additive] lemma coe_of_mdense (f : M → N) (hs : closure s = ⊤) (h1 hmul) : ⇑(of_mdense f hs h1 hmul) = f := rfl attribute [norm_cast] coe_of_mdense add_monoid_hom.coe_of_mdense end monoid_hom
9d356e1010d9a574d3fff2cdbbcf5904336489d6
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/tools/converter/interactive.lean
f16941f286e4d9a847221a68e3b5238f34abd610
[]
no_license
avigad/library_dev
27b47257382667b5eb7e6476c4f5b0d685dd3ddc
9d8ac7c7798ca550874e90fed585caad030bbfac
refs/heads/master
1,610,452,468,791
1,500,712,839,000
1,500,713,478,000
69,311,142
1
0
null
1,474,942,903,000
1,474,942,902,000
null
UTF-8
Lean
false
false
2,380
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 Converter monad for building simplifiers. -/ import tools.converter.old_conv namespace old_conv meta def save_info (p : pos) : old_conv unit := λ r lhs, do ts ← tactic.read, -- TODO(Leo): include context tactic.save_info_thunk p (λ _, ts.format_expr lhs) >> return ⟨(), lhs, none⟩ meta def step {α : Type} (c : old_conv α) : old_conv unit := c >> return () meta def istep {α : Type} (line0 col0 line col : nat) (c : old_conv α) : old_conv unit := λ r lhs ts, (@scope_trace _ line col (λ _, (c >> return ()) r lhs ts)).clamp_pos line0 line col meta def execute (c : old_conv unit) : tactic unit := conversion c namespace interactive open lean.parser open interactive open interactive.types meta def itactic : Type := old_conv unit meta def whnf : old_conv unit := old_conv.whnf meta def dsimp : old_conv unit := old_conv.dsimp meta def trace_state : old_conv unit := old_conv.trace_lhs meta def change (p : parse texpr) : old_conv unit := old_conv.change p meta def find (p : parse lean.parser.pexpr) (c : itactic) : old_conv unit := λ r lhs, do pat ← tactic.pexpr_to_pattern p, s ← simp_lemmas.mk_default, -- to be able to use congruence lemmas @[congr] (found, new_lhs, pr) ← tactic.ext_simplify_core ff {zeta := ff, beta := ff, single_pass := tt, eta := ff, proj := ff} s (λ u, return u) (λ found s r p e, do guard (not found), matched ← (tactic.match_pattern_core reducible pat e >> return tt) <|> return ff, guard matched, ⟨u, new_e, pr⟩ ← c r e, return (tt, new_e, pr, ff)) (λ a s r p e, tactic.failed) r lhs, if not found then tactic.fail "find converter failed, pattern was not found" else return ⟨(), new_lhs, some pr⟩ end interactive end old_conv namespace tactic namespace interactive open lean.parser open interactive open interactive.types meta def old_conv (c : old_conv.interactive.itactic) : tactic unit := do t ← target, (new_t, pr) ← c.to_tactic `eq t, replace_target new_t pr meta def find (p : parse lean.parser.pexpr) (c : old_conv.interactive.itactic) : tactic unit := old_conv $ old_conv.interactive.find p c end interactive end tactic
3645a685868e9b9970e580034a1600da21b856fd
e0b0b1648286e442507eb62344760d5cd8d13f2d
/src/Init/Data/Nat/Basic.lean
422c3337ce0d46730f249126a8c31de583854c9d
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,710
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura -/ prelude import Init.SimpLemmas universes u namespace Nat @[specialize] def foldAux {α : Type u} (f : Nat → α → α) (s : Nat) : Nat → α → α | 0, a => a | succ n, a => foldAux f s n (f (s - (succ n)) a) @[inline] def fold {α : Type u} (f : Nat → α → α) (n : Nat) (init : α) : α := foldAux f n n init @[inline] def foldRev {α : Type u} (f : Nat → α → α) (n : Nat) (init : α) : α := let rec @[specialize] loop | 0, a => a | succ n, a => loop n (f n a) loop n init @[specialize] def anyAux (f : Nat → Bool) (s : Nat) : Nat → Bool | 0 => false | succ n => f (s - (succ n)) || anyAux f s n /- `any f n = true` iff there is `i in [0, n-1]` s.t. `f i = true` -/ @[inline] def any (f : Nat → Bool) (n : Nat) : Bool := anyAux f n n @[inline] def all (f : Nat → Bool) (n : Nat) : Bool := !any (fun i => !f i) n @[inline] def repeat {α : Type u} (f : α → α) (n : Nat) (a : α) : α := let rec @[specialize] loop | 0, a => a | succ n, a => loop n (f a) loop n a /- Nat.add theorems -/ @[simp] theorem zero_Eq : Nat.zero = 0 := rfl @[simp] protected theorem zero_add : ∀ (n : Nat), 0 + n = n | 0 => rfl | n+1 => congrArg succ (Nat.zero_add n) theorem succ_add : ∀ (n m : Nat), (succ n) + m = succ (n + m) | n, 0 => rfl | n, m+1 => congrArg succ (succ_add n m) theorem add_succ (n m : Nat) : n + succ m = succ (n + m) := rfl @[simp] protected theorem add_zero (n : Nat) : n + 0 = n := rfl theorem add_one (n : Nat) : n + 1 = succ n := rfl theorem succ_Eq_add_one (n : Nat) : succ n = n + 1 := rfl protected theorem add_comm : ∀ (n m : Nat), n + m = m + n | n, 0 => Eq.symm (Nat.zero_add n) | n, m+1 => by have succ (n + m) = succ (m + n) by apply congrArg; apply Nat.add_comm rw [succ_add m n] apply this protected theorem add_assoc : ∀ (n m k : Nat), (n + m) + k = n + (m + k) | n, m, 0 => rfl | n, m, succ k => congrArg succ (Nat.add_assoc n m k) protected theorem add_left_comm (n m k : Nat) : n + (m + k) = m + (n + k) := by rw [← Nat.add_assoc, Nat.add_comm n m, Nat.add_assoc] protected theorem add_right_comm (n m k : Nat) : (n + m) + k = (n + k) + m := by rw [Nat.add_assoc, Nat.add_comm m k, ← Nat.add_assoc] protected theorem add_left_cancel {n m k : Nat} : n + m = n + k → m = k := by induction n with | zero => simp; intros; assumption | succ n ih => simp [succ_add]; intro h; injection h with h; apply ih h protected theorem add_right_cancel {n m k : Nat} (h : n + m = k + m) : n = k := by rw [Nat.add_comm n m, Nat.add_comm k m] at h apply Nat.add_left_cancel h /- Nat.mul theorems -/ @[simp] protected theorem mul_zero (n : Nat) : n * 0 = 0 := rfl theorem mul_succ (n m : Nat) : n * succ m = n * m + n := rfl @[simp] protected theorem zero_mul : ∀ (n : Nat), 0 * n = 0 | 0 => rfl | succ n => mul_succ 0 n ▸ (Nat.zero_mul n).symm ▸ rfl theorem succ_mul (n m : Nat) : (succ n) * m = (n * m) + m := by induction m with | zero => rfl | succ m ih => rw [mul_succ, add_succ, ih, mul_succ, add_succ, Nat.add_right_comm] protected theorem mul_comm : ∀ (n m : Nat), n * m = m * n | n, 0 => (Nat.zero_mul n).symm ▸ (Nat.mul_zero n).symm ▸ rfl | n, succ m => (mul_succ n m).symm ▸ (succ_mul m n).symm ▸ (Nat.mul_comm n m).symm ▸ rfl @[simp] protected theorem mul_one : ∀ (n : Nat), n * 1 = n := Nat.zero_add @[simp] protected theorem one_mul (n : Nat) : 1 * n = n := Nat.mul_comm n 1 ▸ Nat.mul_one n protected theorem left_distrib (n m k : Nat) : n * (m + k) = n * m + n * k := by induction n generalizing m k with | zero => repeat rw [Nat.zero_mul] | succ n ih => simp [succ_mul, ih]; rw [Nat.add_assoc, Nat.add_assoc (n*m)]; apply congrArg; apply Nat.add_left_comm protected theorem right_distrib (n m k : Nat) : (n + m) * k = n * k + m * k := have h₁ : (n + m) * k = k * (n + m) from Nat.mul_comm .. have h₂ : k * (n + m) = k * n + k * m from Nat.left_distrib .. have h₃ : k * n + k * m = n * k + k * m from Nat.mul_comm n k ▸ rfl have h₄ : n * k + k * m = n * k + m * k from Nat.mul_comm m k ▸ rfl ((h₁.trans h₂).trans h₃).trans h₄ protected theorem mul_assoc : ∀ (n m k : Nat), (n * m) * k = n * (m * k) | n, m, 0 => rfl | n, m, succ k => have h₁ : n * m * succ k = n * m * (k + 1) from rfl have h₂ : n * m * (k + 1) = (n * m * k) + n * m * 1 from Nat.left_distrib .. have h₃ : (n * m * k) + n * m * 1 = (n * m * k) + n * m by rw [Nat.mul_one (n*m)] have h₄ : (n * m * k) + n * m = (n * (m * k)) + n * m by rw [Nat.mul_assoc n m k] have h₅ : (n * (m * k)) + n * m = n * (m * k + m) from (Nat.left_distrib n (m*k) m).symm have h₆ : n * (m * k + m) = n * (m * succ k) from Nat.mul_succ m k ▸ rfl ((((h₁.trans h₂).trans h₃).trans h₄).trans h₅).trans h₆ /- Inequalities -/ theorem succ_lt_succ {n m : Nat} : n < m → succ n < succ m := succLeSucc theorem lt_succ_of_le {n m : Nat} : n ≤ m → n < succ m := succLeSucc @[simp] protected theorem sub_zero (n : Nat) : n - 0 = n := rfl theorem succ_sub_succ_eq_sub (n m : Nat) : succ n - succ m = n - m := by induction m with | zero => exact rfl | succ m ih => apply congrArg pred ih theorem notSuccLeSelf (n : Nat) : ¬succ n ≤ n := by induction n with | zero => intro h; apply notSuccLeZero 0 h | succ n ih => intro h; exact ih (leOfSuccLeSucc h) protected theorem ltIrrefl (n : Nat) : ¬n < n := notSuccLeSelf n theorem predLe : ∀ (n : Nat), pred n ≤ n | zero => rfl | succ n => leSucc _ theorem predLt : ∀ {n : Nat}, n ≠ 0 → pred n < n | zero, h => absurd rfl h | succ n, h => lt_succ_of_le (Nat.leRefl _) theorem subLe (n m : Nat) : n - m ≤ n := by induction m with | zero => exact Nat.leRefl (n - 0) | succ m ih => apply Nat.leTrans (predLe (n - m)) ih theorem subLt : ∀ {n m : Nat}, 0 < n → 0 < m → n - m < n | 0, m, h1, h2 => absurd h1 (Nat.ltIrrefl 0) | n+1, 0, h1, h2 => absurd h2 (Nat.ltIrrefl 0) | n+1, m+1, h1, h2 => Eq.symm (succ_sub_succ_eq_sub n m) ▸ show n - m < succ n from lt_succ_of_le (subLe n m) theorem sub_succ (n m : Nat) : n - succ m = pred (n - m) := rfl theorem succ_sub_succ (n m : Nat) : succ n - succ m = n - m := succ_sub_succ_eq_sub n m protected theorem sub_self : ∀ (n : Nat), n - n = 0 | 0 => by rw [Nat.sub_zero] | (succ n) => by rw [succ_sub_succ, Nat.sub_self n] protected theorem ltOfLtOfLe {n m k : Nat} : n < m → m ≤ k → n < k := Nat.leTrans protected theorem ltOfLtOfEq {n m k : Nat} : n < m → m = k → n < k := fun h₁ h₂ => h₂ ▸ h₁ protected theorem leOfEq {n m : Nat} (p : n = m) : n ≤ m := p ▸ Nat.leRefl n theorem leOfSuccLe {n m : Nat} (h : succ n ≤ m) : n ≤ m := Nat.leTrans (leSucc n) h protected theorem leOfLt {n m : Nat} (h : n < m) : n ≤ m := leOfSuccLe h def lt.step {n m : Nat} : n < m → n < succ m := leStep def succPos := zeroLtSucc theorem eqZeroOrPos : ∀ (n : Nat), n = 0 ∨ n > 0 | 0 => Or.inl rfl | n+1 => Or.inr (succPos _) protected theorem ltOfLeOfLt {n m k : Nat} (h₁ : n ≤ m) : m < k → n < k := Nat.leTrans (succLeSucc h₁) def lt.base (n : Nat) : n < succ n := Nat.leRefl (succ n) theorem ltSuccSelf (n : Nat) : n < succ n := lt.base n protected theorem leTotal (m n : Nat) : m ≤ n ∨ n ≤ m := match Nat.ltOrGe m n with | Or.inl h => Or.inl (Nat.leOfLt h) | Or.inr h => Or.inr h protected theorem ltOfLeAndNe {m n : Nat} (h₁ : m ≤ n) (h₂ : m ≠ n) : m < n := match Nat.eqOrLtOfLe h₁ with | Or.inl h => absurd h h₂ | Or.inr h => h theorem eqZeroOfLeZero {n : Nat} (h : n ≤ 0) : n = 0 := Nat.leAntisymm h (zeroLe _) theorem ltOfSuccLt {n m : Nat} : succ n < m → n < m := leOfSuccLe theorem lt_of_succ_lt_succ {n m : Nat} : succ n < succ m → n < m := leOfSuccLeSucc theorem ltOfSuccLe {n m : Nat} (h : succ n ≤ m) : n < m := h theorem succLeOfLt {n m : Nat} (h : n < m) : succ n ≤ m := h theorem ltOrEqOrLeSucc {m n : Nat} (h : m ≤ succ n) : m ≤ n ∨ m = succ n := Decidable.byCases (fun (h' : m = succ n) => Or.inr h') (fun (h' : m ≠ succ n) => have m < succ n from Nat.ltOfLeAndNe h h' have succ m ≤ succ n from succLeOfLt this Or.inl (leOfSuccLeSucc this)) theorem leAddRight : ∀ (n k : Nat), n ≤ n + k | n, 0 => Nat.leRefl n | n, k+1 => leSuccOfLe (leAddRight n k) theorem leAddLeft (n m : Nat): n ≤ m + n := Nat.add_comm n m ▸ leAddRight n m theorem le.dest : ∀ {n m : Nat}, n ≤ m → Exists (fun k => n + k = m) | zero, zero, h => ⟨0, rfl⟩ | zero, succ n, h => ⟨succ n, Nat.add_comm 0 (succ n) ▸ rfl⟩ | succ n, zero, h => Bool.noConfusion h | succ n, succ m, h => have n ≤ m from h have Exists (fun k => n + k = m) from dest this match this with | ⟨k, h⟩ => ⟨k, show succ n + k = succ m from ((succ_add n k).symm ▸ h ▸ rfl)⟩ theorem le.intro {n m k : Nat} (h : n + k = m) : n ≤ m := h ▸ leAddRight n k protected theorem notLeOfGt {n m : Nat} (h : n > m) : ¬ n ≤ m := fun h₁ => match Nat.ltOrGe n m with | Or.inl h₂ => absurd (Nat.ltTrans h h₂) (Nat.ltIrrefl _) | Or.inr h₂ => have Heq : n = m from Nat.leAntisymm h₁ h₂ absurd (@Eq.subst _ _ _ _ Heq h) (Nat.ltIrrefl m) theorem gtOfNotLe {n m : Nat} (h : ¬ n ≤ m) : n > m := match Nat.ltOrGe m n with | Or.inl h₁ => h₁ | Or.inr h₁ => absurd h₁ h protected theorem addLeAddLeft {n m : Nat} (h : n ≤ m) (k : Nat) : k + n ≤ k + m := match le.dest h with | ⟨w, hw⟩ => have h₁ : k + n + w = k + (n + w) from Nat.add_assoc .. have h₂ : k + (n + w) = k + m from congrArg _ hw le.intro <| h₁.trans h₂ protected theorem addLeAddRight {n m : Nat} (h : n ≤ m) (k : Nat) : n + k ≤ m + k := by rw [Nat.add_comm n k, Nat.add_comm m k] apply Nat.addLeAddLeft assumption protected theorem addLtAddLeft {n m : Nat} (h : n < m) (k : Nat) : k + n < k + m := ltOfSuccLe (add_succ k n ▸ Nat.addLeAddLeft (succLeOfLt h) k) protected theorem addLtAddRight {n m : Nat} (h : n < m) (k : Nat) : n + k < m + k := Nat.add_comm k m ▸ Nat.add_comm k n ▸ Nat.addLtAddLeft h k protected theorem zeroLtOne : 0 < (1:Nat) := zeroLtSucc 0 theorem addLeAdd {a b c d : Nat} (h₁ : a ≤ b) (h₂ : c ≤ d) : a + c ≤ b + d := Nat.leTrans (Nat.addLeAddRight h₁ c) (Nat.addLeAddLeft h₂ b) theorem addLtAdd {a b c d : Nat} (h₁ : a < b) (h₂ : c < d) : a + c < b + d := Nat.ltTrans (Nat.addLtAddRight h₁ c) (Nat.addLtAddLeft h₂ b) /- Basic theorems for comparing numerals -/ theorem natZeroEqZero : Nat.zero = 0 := rfl protected theorem oneNeZero : 1 ≠ (0 : Nat) := fun h => Nat.noConfusion h protected theorem zeroNeOne : 0 ≠ (1 : Nat) := fun h => Nat.noConfusion h theorem succNeZero (n : Nat) : succ n ≠ 0 := fun h => Nat.noConfusion h /- mul + order -/ theorem mulLeMulLeft {n m : Nat} (k : Nat) (h : n ≤ m) : k * n ≤ k * m := match le.dest h with | ⟨l, hl⟩ => have k * n + k * l = k * m from Nat.left_distrib k n l ▸ hl.symm ▸ rfl le.intro this theorem mulLeMulRight {n m : Nat} (k : Nat) (h : n ≤ m) : n * k ≤ m * k := Nat.mul_comm k m ▸ Nat.mul_comm k n ▸ mulLeMulLeft k h protected theorem mulLeMul {n₁ m₁ n₂ m₂ : Nat} (h₁ : n₁ ≤ n₂) (h₂ : m₁ ≤ m₂) : n₁ * m₁ ≤ n₂ * m₂ := Nat.leTrans (mulLeMulRight _ h₁) (mulLeMulLeft _ h₂) protected theorem mulLtMulOfPosLeft {n m k : Nat} (h : n < m) (hk : k > 0) : k * n < k * m := Nat.ltOfLtOfLe (Nat.addLtAddLeft hk _) (Nat.mul_succ k n ▸ Nat.mulLeMulLeft k (succLeOfLt h)) protected theorem mulLtMulOfPosRight {n m k : Nat} (h : n < m) (hk : k > 0) : n * k < m * k := Nat.mul_comm k m ▸ Nat.mul_comm k n ▸ Nat.mulLtMulOfPosLeft h hk protected theorem mulPos {n m : Nat} (ha : n > 0) (hb : m > 0) : n * m > 0 := have h : 0 * m < n * m from Nat.mulLtMulOfPosRight ha hb Nat.zero_mul m ▸ h /- power -/ theorem powSucc (n m : Nat) : n^(succ m) = n^m * n := rfl theorem powZero (n : Nat) : n^0 = 1 := rfl theorem powLePowOfLeLeft {n m : Nat} (h : n ≤ m) : ∀ (i : Nat), n^i ≤ m^i | 0 => Nat.leRefl _ | succ i => Nat.mulLeMul (powLePowOfLeLeft h i) h theorem powLePowOfLeRight {n : Nat} (hx : n > 0) {i : Nat} : ∀ {j}, i ≤ j → n^i ≤ n^j | 0, h => have i = 0 from eqZeroOfLeZero h this.symm ▸ Nat.leRefl _ | succ j, h => match ltOrEqOrLeSucc h with | Or.inl h => show n^i ≤ n^j * n from have n^i * 1 ≤ n^j * n from Nat.mulLeMul (powLePowOfLeRight hx h) hx Nat.mul_one (n^i) ▸ this | Or.inr h => h.symm ▸ Nat.leRefl _ theorem posPowOfPos {n : Nat} (m : Nat) (h : 0 < n) : 0 < n^m := powLePowOfLeRight h (Nat.zeroLe _) /- min/max -/ protected def min (n m : Nat) : Nat := if n ≤ m then n else m protected def max (n m : Nat) : Nat := if n ≤ m then m else n end Nat namespace Prod @[inline] def foldI {α : Type u} (f : Nat → α → α) (i : Nat × Nat) (a : α) : α := Nat.foldAux f i.2 (i.2 - i.1) a @[inline] def anyI (f : Nat → Bool) (i : Nat × Nat) : Bool := Nat.anyAux f i.2 (i.2 - i.1) @[inline] def allI (f : Nat → Bool) (i : Nat × Nat) : Bool := Nat.anyAux (fun a => !f a) i.2 (i.2 - i.1) end Prod
4cd59fd2d645976fd29849afa9444971c2f5f5fc
6214e13b31733dc9aeb4833db6a6466005763162
/src/definitions3.lean
104bd84fcc35189e8894f4c2ae5a99911b562f5a
[]
no_license
joshua0pang/esverify-theory
272a250445f3aeea49a7e72d1ab58c2da6618bbe
8565b123c87b0113f83553d7732cd6696c9b5807
refs/heads/master
1,585,873,849,081
1,527,304,393,000
1,527,304,393,000
154,901,199
1
0
null
1,540,593,067,000
1,540,593,067,000
null
UTF-8
Lean
false
false
13,211
lean
-- definitions that are used by the lemmas but not referenced by the a theorem import .definitions2 -- (∀x {call(x)} ⇒ P) ∈ CallQuantifiers structure callquantifier := (x: var) (P: prop) -- s ∈ DStacks := (R, σ, e) | s · (R, σ, let y = f(x) in e) inductive dstack | top : spec → env → exp → dstack | cons : dstack → spec → env → var → var → var → exp → dstack -- (R, σ, e) : dstack instance : has_coe (spec × env × exp) dstack := ⟨λe, dstack.top e.1 e.2.1 e.2.2⟩ -- stack precondition projection def dstack.pre: dstack → spec | (dstack.top R _ _) := R | (dstack.cons _ R _ _ _ _ _) := R lemma sizeof_substack {s: dstack} {R: spec} {σ: env} {f x y: var} {e: exp}: s.sizeof < (dstack.cons s R σ f x y e).sizeof := begin unfold dstack.sizeof, change sizeof s < 1 + sizeof s + sizeof R + sizeof σ + sizeof f + sizeof x + sizeof y + sizeof e, rw[add_assoc], rw[add_assoc], rw[add_assoc], rw[add_assoc], rw[add_assoc], rw[add_assoc], rw[add_comm], rw[add_assoc], apply lt_add_of_pos_right, rw[add_comm], rw[add_comm], apply lt_add_of_le_of_pos nonneg_of_nat, from zero_lt_one end -- top-level calls and quantifiers in positive and negative positions mutual inductive prop.has_call_p, prop.has_call_n with prop.has_call_p: calltrigger → prop → Prop | calltrigger {x: term} : prop.has_call_p ⟨x⟩ (prop.call x) | not {P: prop} {c: calltrigger} : prop.has_call_n c P → prop.has_call_p c P.not | and₁ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_p c P₁ → prop.has_call_p c (P₁ ⋀ P₂) | and₂ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_p c P₂ → prop.has_call_p c (P₁ ⋀ P₂) | or₁ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_p c P₁ → prop.has_call_p c (P₁ ⋁ P₂) | or₂ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_p c P₂ → prop.has_call_p c (P₁ ⋁ P₂) with prop.has_call_n: calltrigger → prop → Prop | not {P: prop} {c: calltrigger} : prop.has_call_p c P → prop.has_call_n c P.not | and₁ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_n c P₁ → prop.has_call_n c (P₁ ⋀ P₂) | and₂ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_n c P₂ → prop.has_call_n c (P₁ ⋀ P₂) | or₁ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_n c P₁ → prop.has_call_n c (P₁ ⋁ P₂) | or₂ {P₁ P₂: prop} {c: calltrigger} : prop.has_call_n c P₂ → prop.has_call_n c (P₁ ⋁ P₂) -- sets of calls def calls_p (P: prop): set calltrigger := λc, prop.has_call_p c P def calls_n (P: prop): set calltrigger := λc, prop.has_call_n c P mutual inductive prop.has_quantifier_p, prop.has_quantifier_n with prop.has_quantifier_p: callquantifier → prop → Prop | callquantifier {x: var} {P: prop} : prop.has_quantifier_p ⟨x, P⟩ (prop.forallc x P) | not {P: prop} {q: callquantifier} : prop.has_quantifier_n q P → prop.has_quantifier_p q P.not | and₁ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_p q P₁ → prop.has_quantifier_p q (P₁ ⋀ P₂) | and₂ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_p q P₂ → prop.has_quantifier_p q (P₁ ⋀ P₂) | or₁ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_p q P₁ → prop.has_quantifier_p q (P₁ ⋁ P₂) | or₂ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_p q P₂ → prop.has_quantifier_p q (P₁ ⋁ P₂) with prop.has_quantifier_n: callquantifier → prop → Prop | not {P: prop} {q: callquantifier} : prop.has_quantifier_p q P → prop.has_quantifier_n q P.not | and₁ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_n q P₁ → prop.has_quantifier_n q (P₁ ⋀ P₂) | and₂ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_n q P₂ → prop.has_quantifier_n q (P₁ ⋀ P₂) | or₁ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_n q P₁ → prop.has_quantifier_n q (P₁ ⋁ P₂) | or₂ {P₁ P₂: prop} {q: callquantifier} : prop.has_quantifier_n q P₂ → prop.has_quantifier_n q (P₁ ⋁ P₂) -- universal quantifiers below existential quantifiers only occur in positive positions, -- so can be skolemized instead of instantiated -- sets of quantifiers def quantifiers_p (P: prop): set callquantifier := λc, has_quantifier_p c P def quantifiers_n (P: prop): set callquantifier := λc, has_quantifier_n c P def quantifiers (P: prop): set callquantifier := quantifiers_p P ∪ quantifiers_n P -- propositions without call triggers or quantifiers do not participate in instantiations def no_instantiations(P: prop): Prop := (calls_p P = ∅) ∧ (calls_n P = ∅) ∧ (quantifiers_p P = ∅) ∧ (quantifiers_n P = ∅) -- set of calltriggers after substitution def calltrigger.subst (σ: env) (c: calltrigger): calltrigger := ⟨term.subst_env σ c.x⟩ def calls_p_subst (σ: env) (P: prop): set calltrigger := (calltrigger.subst σ) '' calls_p P def calls_n_subst (σ: env) (P: prop): set calltrigger := (calltrigger.subst σ) '' calls_n P -- uses variables (either free or quantified) inductive prop.uses_var (x: var) : prop → Prop | term {t: term} : free_in_term x t → prop.uses_var t | not {P: prop} : prop.uses_var P → prop.uses_var (prop.not P) | and₁ {P₁ P₂: prop} : prop.uses_var P₁ → prop.uses_var (prop.and P₁ P₂) | and₂ {P₁ P₂: prop} : prop.uses_var P₂ → prop.uses_var (prop.and P₁ P₂) | or₁ {P₁ P₂: prop} : prop.uses_var P₁ → prop.uses_var (prop.or P₁ P₂) | or₂ {P₁ P₂: prop} : prop.uses_var P₂ → prop.uses_var (prop.or P₁ P₂) | pre₁ {t₁ t₂: term} : free_in_term x t₁ → prop.uses_var (prop.pre t₁ t₂) | pre₂ {t₁ t₂: term} : free_in_term x t₂ → prop.uses_var (prop.pre t₁ t₂) | preop {t: term} {op: unop} : free_in_term x t → prop.uses_var (prop.pre₁ op t) | preop₁ {t₁ t₂: term} {op: binop} : free_in_term x t₁ → prop.uses_var (prop.pre₂ op t₁ t₂) | preop₂ {t₁ t₂: term} {op: binop} : free_in_term x t₂ → prop.uses_var (prop.pre₂ op t₁ t₂) | post₁ {t₁ t₂: term} : free_in_term x t₁ → prop.uses_var (prop.post t₁ t₂) | post₂ {t₁ t₂: term} : free_in_term x t₂ → prop.uses_var (prop.post t₁ t₂) | call {t: term} : free_in_term x t → prop.uses_var (prop.call t) | forallc {y: var} {P: prop} : prop.uses_var P → prop.uses_var (prop.forallc y P) | uquantified {P: prop} : prop.uses_var (prop.forallc x P) | exis {y: var} {P: prop} : prop.uses_var P → prop.uses_var (prop.exis y P) | equantified {P: prop} : prop.uses_var (prop.exis x P) inductive vc.uses_var (x: var) : vc → Prop | term {t: term} : free_in_term x t → vc.uses_var t | not {P: vc} : vc.uses_var P → vc.uses_var (vc.not P) | and₁ {P₁ P₂: vc} : vc.uses_var P₁ → vc.uses_var (vc.and P₁ P₂) | and₂ {P₁ P₂: vc} : vc.uses_var P₂ → vc.uses_var (vc.and P₁ P₂) | or₁ {P₁ P₂: vc} : vc.uses_var P₁ → vc.uses_var (vc.or P₁ P₂) | or₂ {P₁ P₂: vc} : vc.uses_var P₂ → vc.uses_var (vc.or P₁ P₂) | pre₁ {t₁ t₂: term} : free_in_term x t₁ → vc.uses_var (vc.pre t₁ t₂) | pre₂ {t₁ t₂: term} : free_in_term x t₂ → vc.uses_var (vc.pre t₁ t₂) | preop {t: term} {op: unop} : free_in_term x t → vc.uses_var (vc.pre₁ op t) | preop₁ {t₁ t₂: term} {op: binop} : free_in_term x t₁ → vc.uses_var (vc.pre₂ op t₁ t₂) | preop₂ {t₁ t₂: term} {op: binop} : free_in_term x t₂ → vc.uses_var (vc.pre₂ op t₁ t₂) | post₁ {t₁ t₂: term} : free_in_term x t₁ → vc.uses_var (vc.post t₁ t₂) | post₂ {t₁ t₂: term} : free_in_term x t₂ → vc.uses_var (vc.post t₁ t₂) | univ {y: var} {P: vc} : vc.uses_var P → vc.uses_var (vc.univ y P) | quantified {P: vc} : vc.uses_var (vc.univ x P) -- evaluation relation that includes the current function precondition for each stack frame inductive dstep : dstack → dstack → Prop notation s₁ `⟹` s₂:100 := dstep s₁ s₂ | ctx {s s': dstack} {R: spec} {σ: env} {y f x: var} {e: exp}: (s ⟹ s') → (dstack.cons s R σ y f x e ⟹ dstack.cons s' R σ y f x e) | tru {R: spec} {σ: env} {x: var} {e: exp}: (R, σ, lett x = true in e) ⟹ (R, σ[x↦value.true], e) | fals {R: spec} {σ: env} {x: var} {e: exp}: (R, σ, letf x = false in e) ⟹ (R, σ[x↦value.false], e) | num {R: spec} {σ: env} {x: var} {e: exp} {n: ℤ}: (R, σ, letn x = n in e) ⟹ (R, σ[x↦value.num n], e) | closure {σ: env} {R' R S: spec} {f x: var} {e₁ e₂: exp}: (R', σ, letf f[x] req R ens S {e₁} in e₂) ⟹ (R', σ[f↦value.func f x R S e₁ σ], e₂) | unop {R: spec} {op: unop} {σ: env} {x y: var} {e: exp} {v₁ v: value}: (σ x = v₁) → (unop.apply op v₁ = v) → ((R, σ, letop y = op [x] in e) ⟹ (R, σ[y↦v], e)) | binop {R: spec} {op: binop} {σ: env} {x y z: var} {e: exp} {v₁ v₂ v: value}: (σ x = v₁) → (σ y = v₂) → (binop.apply op v₁ v₂ = v) → ((R, σ, letop2 z = op [x, y] in e) ⟹ (R, σ[z↦v], e)) | app {σ σ': env} {R' R S: spec} {f g x y z: var} {e e': exp} {v: value}: (σ f = value.func g z R S e σ') → (σ x = v) → ((R', σ, letapp y = f[x] in e') ⟹ (dstack.cons (R, (σ'[g↦value.func g z R S e σ'][z↦v]), e) R' σ y f x e')) | return {σ₁ σ₂ σ₃: env} {f g gx x y z: var} {R₁ R₂ R S: spec} {e e': exp} {v vₓ: value}: (σ₁ z = v) → (σ₂ f = value.func g gx R S e σ₃) → (σ₂ x = vₓ) → (dstack.cons (R₁, σ₁, exp.return z) R₂ σ₂ y f x e' ⟹ (R₂, σ₂[y↦v], e')) | ite_true {R: spec} {σ: env} {e₁ e₂: exp} {x: var}: (σ x = value.true) → ((R, σ, exp.ite x e₁ e₂) ⟹ (R, σ, e₁)) | ite_false {R: spec} {σ: env} {e₁ e₂: exp} {x: var}: (σ x = value.false) → ((R, σ, exp.ite x e₁ e₂) ⟹ (R, σ, e₂)) notation s₁ `⟹` s₂:100 := dstep s₁ s₂ -- transitive closure inductive trans_dstep : dstack → dstack → Prop notation s `⟹*` s':100 := trans_dstep s s' | rfl {s: dstack} : s ⟹* s | trans {s s' s'': dstack} : (s ⟹* s') → (s' ⟹ s'') → (s ⟹* s'') notation s `⟹*` s':100 := trans_dstep s s' def is_dvalue (s: dstack) := ∃(R: spec) (σ: env) (x: var) (v: value), s = (R, σ, exp.return x) ∧ (σ x = v) -- runtime verification of stacks inductive stack.dvcgen : dstack → propctx → Prop notation `⊩ₛ` s `:` Q : 10 := stack.dvcgen s Q | top {R: spec} {P: prop} {σ: env} {e: exp} {Q: propctx}: (⊩ σ : P) → FV R.to_prop ⊆ FV P → (σ ⊨ R.to_prop.to_vc) → (R ⋀ P ⊩ e : Q) → (⊩ₛ (R, σ, e) : P ⋀ Q) | cons {P₁ P₂ P₃: prop} {s: dstack} {σ₁ σ₂: env} {f fx g x y: var} {R₁ R₂ S₂: spec} {e₁ e₂: exp} {v: value} {Q₁ Q₂ Q₂': propctx}: (⊩ₛ s : Q₂') → y ∉ σ₁ → (⊩ σ₁ : P₁) → (⊩ σ₂ : P₂ ) → (⊩ (σ₂[f↦value.func f fx R₂ S₂ e₂ σ₂][fx↦v]) : P₃) → FV R₁.to_prop ⊆ FV P₁ → (σ₁ ⊨ R₁.to_prop.to_vc) → (σ₁ g = value.func f fx R₂ S₂ e₂ σ₂) → (σ₁ x = v) → (R₁ ⋀ P₁ ⋀ prop.call x ⋀ prop.post g x ⋀ y ≡ term.app g x ⊩ e₁ : Q₁) → (P₂ ⋀ spec.func f fx R₂ S₂ ⋀ R₂ ⊩ e₂ : Q₂) → (∀σ' t, (σ' ⊨ (Q₂' t).to_vc) → σ' ⊨ (P₃ ⋀ (Q₂ t)).to_vc) → (∀v: value, FV (P₃ ⋀ (Q₂ v)) ⊆ FV (Q₂' v)) → ⦃ prop.implies (R₁ ⋀ P₁ ⋀ prop.call x) (term.unop unop.isFunc g ⋀ prop.pre g x) ⦄ → ((R₂, σ₂[f↦value.func f fx R₂ S₂ e₂ σ₂][fx↦v], e₂) ⟹* s) → (⊩ₛ dstack.cons s R₁ σ₁ y g x e₁ : P₁ ⋀ propctx.exis y (prop.call x ⋀ prop.post g x ⋀ y ≡ term.app g x ⋀ Q₁)) notation `⊩ₛ` s `:` Q : 10 := stack.dvcgen s Q inductive stack_equiv_dstack : stack → dstack → Prop | top {R: spec} {σ: env} {e: exp} : stack_equiv_dstack (stack.top σ e) (dstack.top R σ e) | cons {s': stack} {d': dstack} {R: spec} {σ: env} {f x y: var} {e: exp}: stack_equiv_dstack s' d' → stack_equiv_dstack (stack.cons s' σ f x y e) (dstack.cons d' R σ f x y e)
67f1ad44b045e52d55be69d1ecc1668ca710624b
1dd482be3f611941db7801003235dc84147ec60a
/src/ring_theory/associated.lean
e2a7ede9f302c5812b5a41121a1c210732b9cda8
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
29,718
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker Associated and irreducible elements. -/ import order.galois_connection algebra.group data.equiv.basic data.multiset data.int.gcd variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} open lattice /-- is unit -/ def is_unit [monoid α] (a : α) : Prop := ∃u:units α, a = u @[simp] lemma is_unit_unit [monoid α] (u : units α) : is_unit (u : α) := ⟨u, rfl⟩ @[simp] theorem is_unit_zero_iff [semiring α] : is_unit (0 : α) ↔ (0:α) = 1 := ⟨λ ⟨⟨_, a, (a0 : 0 * a = 1), _⟩, rfl⟩, by rwa zero_mul at a0, λ h, begin haveI := subsingleton_of_zero_eq_one _ h, refine ⟨⟨0, 0, _, _⟩, rfl⟩; apply subsingleton.elim end⟩ @[simp] theorem not_is_unit_zero [nonzero_comm_ring α] : ¬ is_unit (0 : α) := mt is_unit_zero_iff.1 zero_ne_one @[simp] theorem is_unit_one [monoid α] : is_unit (1:α) := ⟨1, rfl⟩ theorem is_unit_of_mul_one [comm_monoid α] (a b : α) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ theorem is_unit_iff_exists_inv [comm_monoid α] {a : α} : is_unit a ↔ ∃ b, a * b = 1 := ⟨by rintro ⟨⟨a, b, hab, _⟩, rfl⟩; exact ⟨b, hab⟩, λ ⟨b, hab⟩, is_unit_of_mul_one _ b hab⟩ theorem is_unit_iff_exists_inv' [comm_monoid α] {a : α} : is_unit a ↔ ∃ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] lemma is_unit_pow [monoid α] {a : α} (n : ℕ) : is_unit a → is_unit (a ^ n) := λ ⟨u, hu⟩, ⟨u ^ n, by simp *⟩ @[simp] theorem units.is_unit_mul_units [monoid α] (a : α) (u : units α) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (assume ⟨v, hv⟩, hv.symm ▸ ⟨v * u, (units.coe_mul v u).symm⟩) theorem is_unit_of_mul_is_unit_left {α} [comm_monoid α] {x y : α} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ theorem is_unit_of_mul_is_unit_right {α} [comm_monoid α] {x y : α} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm theorem is_unit_iff_dvd_one [comm_semiring α] {x : α} : is_unit x ↔ x ∣ 1 := ⟨by rintro ⟨u, rfl⟩; exact ⟨_, u.mul_inv.symm⟩, λ ⟨y, h⟩, ⟨⟨x, y, h.symm, by rw [h, mul_comm]⟩, rfl⟩⟩ theorem is_unit_iff_forall_dvd [comm_semiring α] {x : α} : is_unit x ↔ ∀ y, x ∣ y := is_unit_iff_dvd_one.trans ⟨λ h y, dvd.trans h (one_dvd _), λ h, h _⟩ theorem mul_dvd_of_is_unit_left [comm_semiring α] {x y z : α} (h : is_unit x) : x * y ∣ z ↔ y ∣ z := ⟨dvd_trans (dvd_mul_left _ _), dvd_trans $ by simpa using mul_dvd_mul_right (is_unit_iff_dvd_one.1 h) y⟩ theorem mul_dvd_of_is_unit_right [comm_semiring α] {x y z : α} (h : is_unit y) : x * y ∣ z ↔ x ∣ z := by rw [mul_comm, mul_dvd_of_is_unit_left h] @[simp] lemma unit_mul_dvd_iff [comm_semiring α] {a b : α} {u : units α} : (u : α) * a ∣ b ↔ a ∣ b := mul_dvd_of_is_unit_left (is_unit_unit _) @[simp] lemma mul_unit_dvd_iff [comm_semiring α] {a b : α} {u : units α} : a * u ∣ b ↔ a ∣ b := mul_dvd_of_is_unit_right (is_unit_unit _) theorem is_unit_of_dvd_unit {α} [comm_semiring α] {x y : α} (xy : x ∣ y) (hu : is_unit y) : is_unit x := is_unit_iff_dvd_one.2 $ dvd_trans xy $ is_unit_iff_dvd_one.1 hu @[simp] theorem is_unit_nat {n : ℕ} : is_unit n ↔ n = 1 := iff.intro (assume ⟨u, hu⟩, match n, u, hu, nat.units_eq_one u with _, _, rfl, rfl := rfl end) (assume h, h.symm ▸ ⟨1, rfl⟩) theorem is_unit_int {n : ℤ} : is_unit n ↔ n.nat_abs = 1 := ⟨λ ⟨u, hu⟩, (int.units_eq_one_or u).elim (by simp *) (by simp *), λ h, is_unit_iff_dvd_one.2 ⟨n, by rw [← int.nat_abs_mul_self, h]; refl⟩⟩ lemma is_unit_of_dvd_one [comm_semiring α] : ∀a ∣ 1, is_unit (a:α) | a ⟨b, eq⟩ := ⟨units.mk_of_mul_eq_one a b eq.symm, rfl⟩ lemma dvd_and_not_dvd_iff [integral_domain α] {x y : α} : x ∣ y ∧ ¬y ∣ x ↔ x ≠ 0 ∧ ∃ d : α, ¬ is_unit d ∧ y = x * d := ⟨λ ⟨⟨d, hd⟩, hyx⟩, ⟨λ hx0, by simpa [hx0] using hyx, ⟨d, mt is_unit_iff_dvd_one.1 (λ ⟨e, he⟩, hyx ⟨e, by rw [hd, mul_assoc, ← he, mul_one]⟩), hd⟩⟩, λ ⟨hx0, d, hdu, hdx⟩, ⟨⟨d, hdx⟩, λ ⟨e, he⟩, hdu (is_unit_of_dvd_one _ ⟨e, (domain.mul_left_inj hx0).1 $ by conv {to_lhs, rw [he, hdx]};simp [mul_assoc]⟩)⟩⟩ /-- prime element of a semiring -/ def prime [comm_semiring α] (p : α) : Prop := p ≠ 0 ∧ ¬ is_unit p ∧ (∀a b, p ∣ a * b → p ∣ a ∨ p ∣ b) @[simp] lemma not_prime_zero [integral_domain α] : ¬ prime (0 : α) | ⟨h, _⟩ := h rfl @[simp] lemma not_prime_one [comm_semiring α] : ¬ prime (1 : α) := λ h, h.2.1 is_unit_one lemma exists_mem_multiset_dvd_of_prime [comm_semiring α] {s : multiset α} {p : α} (hp : prime p) : p ∣ s.prod → ∃a∈s, p ∣ a := multiset.induction_on s (assume h, (hp.2.1 $ is_unit_of_dvd_one _ h).elim) $ assume a s ih h, have p ∣ a * s.prod, by simpa using h, match hp.2.2 a s.prod this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end /-- `irreducible p` states that `p` is non-unit and only factors into units. We explicitly avoid stating that `p` is non-zero, this would require a semiring. Assuming only a monoid allows us to reuse irreducible for associated elements. -/ @[class] def irreducible [monoid α] (p : α) : Prop := ¬ is_unit p ∧ ∀a b, p = a * b → is_unit a ∨ is_unit b @[simp] theorem not_irreducible_one [monoid α] : ¬ irreducible (1 : α) := by simp [irreducible] @[simp] theorem not_irreducible_zero [semiring α] : ¬ irreducible (0 : α) | ⟨hn0, h⟩ := have is_unit (0:α) ∨ is_unit (0:α), from h 0 0 ((mul_zero 0).symm), this.elim hn0 hn0 theorem nonzero_of_irreducible [semiring α] : ∀ {p:α}, irreducible p → p ≠ 0 | _ hp rfl := not_irreducible_zero hp theorem of_irreducible_mul {α} [monoid α] {x y : α} : irreducible (x * y) → is_unit x ∨ is_unit y | ⟨_, h⟩ := h _ _ rfl theorem irreducible_or_factor {α} [monoid α] (x : α) (h : ¬ is_unit x) : irreducible x ∨ ∃ a b, ¬ is_unit a ∧ ¬ is_unit b ∧ a * b = x := begin haveI := classical.dec, refine or_iff_not_imp_right.2 (λ H, _), simp [h, irreducible] at H ⊢, refine λ a b h, classical.by_contradiction $ λ o, _, simp [not_or_distrib] at o, exact H _ o.1 _ o.2 h.symm end theorem irreducible_iff_nat_prime : ∀(a : ℕ), irreducible a ↔ nat.prime a | 0 := by simp [nat.not_prime_zero] | 1 := by simp [nat.prime, one_lt_two] | (n + 2) := have h₁ : ¬n + 2 = 1, from dec_trivial, begin simp [h₁, nat.prime, irreducible, (≥), nat.le_add_left 2 n, (∣)], refine forall_congr (assume a, forall_congr $ assume b, forall_congr $ assume hab, _), by_cases a = 1; simp [h], split, { assume hb, simpa [hb] using hab.symm }, { assume ha, subst ha, have : n + 2 > 0, from dec_trivial, refine nat.eq_of_mul_eq_mul_left this _, rw [← hab, mul_one] } end lemma nat.prime_iff_prime {p : ℕ} : p.prime ↔ _root_.prime (p : ℕ) := ⟨λ hp, ⟨nat.pos_iff_ne_zero.1 hp.pos, mt is_unit_iff_dvd_one.1 hp.not_dvd_one, λ a b, hp.dvd_mul.1⟩, λ hp, ⟨nat.one_lt_iff_ne_zero_and_ne_one.2 ⟨hp.1, λ h1, hp.2.1 $ h1.symm ▸ is_unit_one⟩, λ a h, let ⟨b, hab⟩ := h in (hp.2.2 a b (hab ▸ dvd_refl _)).elim (λ ha, or.inr (nat.dvd_antisymm h ha)) (λ hb, or.inl (have hpb : p = b, from nat.dvd_antisymm hb (hab.symm ▸ dvd_mul_left _ _), (nat.mul_left_inj (show 0 < p, from nat.pos_of_ne_zero hp.1)).1 $ by rw [hpb, mul_comm, ← hab, hpb, mul_one]))⟩⟩ lemma nat.prime_iff_prime_int {p : ℕ} : p.prime ↔ _root_.prime (p : ℤ) := ⟨λ hp, ⟨int.coe_nat_ne_zero_iff_pos.2 hp.pos, mt is_unit_int.1 hp.ne_one, λ a b h, by rw [← int.dvd_nat_abs, int.coe_nat_dvd, int.nat_abs_mul, hp.dvd_mul] at h; rwa [← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd]⟩, λ hp, nat.prime_iff_prime.2 ⟨int.coe_nat_ne_zero.1 hp.1, mt is_unit_nat.1 $ λ h, by simpa [h, not_prime_one] using hp, λ a b, by simpa only [int.coe_nat_dvd, (int.coe_nat_mul _ _).symm] using hp.2.2 a b⟩⟩ lemma irreducible_of_prime [integral_domain α] {p : α} (hp : prime p) : irreducible p := ⟨hp.2.1, λ a b hab, (show a * b ∣ a ∨ a * b ∣ b, from hab ▸ hp.2.2 a b (hab ▸ (dvd_refl _))).elim (λ ⟨x, hx⟩, or.inr (is_unit_iff_dvd_one.2 ⟨x, (domain.mul_left_inj (show a ≠ 0, from λ h, by simp [*, prime] at *)).1 $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩)) (λ ⟨x, hx⟩, or.inl (is_unit_iff_dvd_one.2 ⟨x, (domain.mul_left_inj (show b ≠ 0, from λ h, by simp [*, prime] at *)).1 $ by conv {to_lhs, rw hx}; simp [mul_comm, mul_assoc, mul_left_comm]⟩))⟩ lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul [integral_domain α] {p : α} (hp : prime p) {a b : α} {k l : ℕ} : p ^ k ∣ a → p ^ l ∣ b → p ^ ((k + l) + 1) ∣ a * b → p ^ (k + 1) ∣ a ∨ p ^ (l + 1) ∣ b := λ ⟨x, hx⟩ ⟨y, hy⟩ ⟨z, hz⟩, have h : p ^ (k + l) * (x * y) = p ^ (k + l) * (p * z), by simpa [mul_comm, _root_.pow_add, hx, hy, mul_assoc, mul_left_comm] using hz, have hp0: p ^ (k + l) ≠ 0, from pow_ne_zero _ hp.1, have hpd : p ∣ x * y, from ⟨z, by rwa [domain.mul_left_inj hp0] at h⟩, (hp.2.2 x y hpd).elim (λ ⟨d, hd⟩, or.inl ⟨d, by simp [*, _root_.pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) (λ ⟨d, hd⟩, or.inr ⟨d, by simp [*, _root_.pow_succ, mul_comm, mul_left_comm, mul_assoc]⟩) def associated [monoid α] (x y : α) : Prop := ∃u:units α, x * u = y local infix ` ~ᵤ ` : 50 := associated namespace associated @[refl] protected theorem refl [monoid α] (x : α) : x ~ᵤ x := ⟨1, by simp⟩ @[symm] protected theorem symm [monoid α] : ∀{x y : α}, x ~ᵤ y → y ~ᵤ x | x _ ⟨u, rfl⟩ := ⟨u⁻¹, by rw [mul_assoc, units.mul_inv, mul_one]⟩ @[trans] protected theorem trans [monoid α] : ∀{x y z : α}, x ~ᵤ y → y ~ᵤ z → x ~ᵤ z | x _ _ ⟨u, rfl⟩ ⟨v, rfl⟩ := ⟨u * v, by rw [units.coe_mul, mul_assoc]⟩ protected def setoid (α : Type*) [monoid α] : setoid α := { r := associated, iseqv := ⟨associated.refl, λa b, associated.symm, λa b c, associated.trans⟩ } end associated local attribute [instance] associated.setoid theorem unit_associated_one [monoid α] {u : units α} : (u : α) ~ᵤ 1 := ⟨u⁻¹, units.mul_inv u⟩ theorem associated_one_iff_is_unit [monoid α] {a : α} : (a : α) ~ᵤ 1 ↔ is_unit a := iff.intro (assume h, let ⟨c, h⟩ := h.symm in h ▸ ⟨c, one_mul _⟩) (assume ⟨c, h⟩, associated.symm ⟨c, by simp [h]⟩) theorem associated_zero_iff_eq_zero [comm_semiring α] (a : α) : a ~ᵤ 0 ↔ a = 0 := iff.intro (assume h, let ⟨u, h⟩ := h.symm in by simpa using h.symm) (assume h, h ▸ associated.refl a) theorem associated_one_of_mul_eq_one [comm_monoid α] {a : α} (b : α) (hab : a * b = 1) : a ~ᵤ 1 := show (units.mk_of_mul_eq_one a b hab : α) ~ᵤ 1, from unit_associated_one theorem associated_one_of_associated_mul_one [comm_monoid α] {a b : α} : a * b ~ᵤ 1 → a ~ᵤ 1 | ⟨u, h⟩ := associated_one_of_mul_eq_one (b * u) $ by simpa [mul_assoc] using h lemma associated_mul_mul [comm_monoid α] {a₁ a₂ b₁ b₂ : α} : a₁ ~ᵤ b₁ → a₂ ~ᵤ b₂ → (a₁ * a₂) ~ᵤ (b₁ * b₂) | ⟨c₁, h₁⟩ ⟨c₂, h₂⟩ := ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩ theorem associated_of_dvd_dvd [integral_domain α] {a b : α} (hab : a ∣ b) (hba : b ∣ a) : a ~ᵤ b := begin haveI := classical.dec_eq α, rcases hab with ⟨c, rfl⟩, rcases hba with ⟨d, a_eq⟩, by_cases ha0 : a = 0, { simp [*] at * }, have : a * 1 = a * (c * d), { simpa [mul_assoc] using a_eq }, have : 1 = (c * d), from eq_of_mul_eq_mul_left ha0 this, exact ⟨units.mk_of_mul_eq_one c d (this.symm), by rw [units.mk_of_mul_eq_one, units.val_coe]⟩ end lemma exists_associated_mem_of_dvd_prod [integral_domain α] {p : α} (hp : prime p) {s : multiset α} : (∀ r ∈ s, prime r) → p ∣ s.prod → ∃ q ∈ s, p ~ᵤ q := multiset.induction_on s (by simp [mt is_unit_iff_dvd_one.2 hp.2.1]) (λ a s ih hs hps, begin rw [multiset.prod_cons] at hps, cases hp.2.2 _ _ hps with h h, { use [a, by simp], cases h with u hu, cases ((irreducible_of_prime (hs a (multiset.mem_cons.2 (or.inl rfl)))).2 p u hu).resolve_left hp.2.1 with v hv, exact ⟨v, by simp [hu, hv]⟩ }, { rcases ih (λ r hr, hs _ (multiset.mem_cons.2 (or.inr hr))) h with ⟨q, hq₁, hq₂⟩, exact ⟨q, multiset.mem_cons.2 (or.inr hq₁), hq₂⟩ } end) lemma dvd_iff_dvd_of_rel_left [comm_semiring α] {a b c : α} (h : a ~ᵤ b) : a ∣ c ↔ b ∣ c := let ⟨u, hu⟩ := h in hu ▸ mul_unit_dvd_iff.symm @[simp] lemma dvd_mul_unit_iff [comm_semiring α] {a b : α} {u : units α} : a ∣ b * u ↔ a ∣ b := ⟨λ ⟨d, hd⟩, ⟨d * (u⁻¹ : units α), by simp [(mul_assoc _ _ _).symm, hd.symm]⟩, λ h, dvd.trans h (by simp)⟩ lemma dvd_iff_dvd_of_rel_right [comm_semiring α] {a b c : α} (h : b ~ᵤ c) : a ∣ b ↔ a ∣ c := let ⟨u, hu⟩ := h in hu ▸ dvd_mul_unit_iff.symm lemma eq_zero_iff_of_associated [comm_semiring α] {a b : α} (h : a ~ᵤ b) : a = 0 ↔ b = 0 := ⟨λ ha, let ⟨u, hu⟩ := h in by simp [hu.symm, ha], λ hb, let ⟨u, hu⟩ := h.symm in by simp [hu.symm, hb]⟩ lemma ne_zero_iff_of_associated [comm_semiring α] {a b : α} (h : a ~ᵤ b) : a ≠ 0 ↔ b ≠ 0 := by haveI := classical.dec; exact not_iff_not.2 (eq_zero_iff_of_associated h) lemma prime_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) (hp : prime p) : prime q := ⟨(ne_zero_iff_of_associated h).1 hp.1, let ⟨u, hu⟩ := h in ⟨λ ⟨v, hv⟩, hp.2.1 ⟨v * u⁻¹, by simp [hv.symm, hu.symm]⟩, hu ▸ by simp [mul_unit_dvd_iff]; exact hp.2.2⟩⟩ lemma prime_iff_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) : prime p ↔ prime q := ⟨prime_of_associated h, prime_of_associated h.symm⟩ lemma is_unit_iff_of_associated [monoid α] {a b : α} (h : a ~ᵤ b) : is_unit a ↔ is_unit b := ⟨let ⟨u, hu⟩ := h in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩, let ⟨u, hu⟩ := h.symm in λ ⟨v, hv⟩, ⟨v * u, by simp [hv, hu.symm]⟩⟩ lemma irreducible_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) (hp : irreducible p) : irreducible q := ⟨mt (is_unit_iff_of_associated h).2 hp.1, let ⟨u, hu⟩ := h in λ a b hab, have hpab : p = a * (b * (u⁻¹ : units α)), from calc p = (p * u) * (u ⁻¹ : units α) : by simp ... = _ : by rw hu; simp [hab, mul_assoc], (hp.2 _ _ hpab).elim or.inl (λ ⟨v, hv⟩, or.inr ⟨v * u, by simp [hv.symm]⟩)⟩ lemma irreducible_iff_of_associated [comm_semiring α] {p q : α} (h : p ~ᵤ q) : irreducible p ↔ irreducible q := ⟨irreducible_of_associated h, irreducible_of_associated h.symm⟩ lemma associated_mul_left_cancel [integral_domain α] {a b c d : α} (h : a * b ~ᵤ c * d) (h₁ : a ~ᵤ c) (ha : a ≠ 0) : b ~ᵤ d := let ⟨u, hu⟩ := h in let ⟨v, hv⟩ := associated.symm h₁ in ⟨u * (v : units α), (domain.mul_left_inj ha).1 begin rw [← hv, mul_assoc c (v : α) d, mul_left_comm c, ← hu], simp [hv.symm, mul_assoc, mul_comm, mul_left_comm] end⟩ lemma associated_mul_right_cancel [integral_domain α] {a b c d : α} : a * b ~ᵤ c * d → b ~ᵤ d → b ≠ 0 → a ~ᵤ c := by rw [mul_comm a, mul_comm c]; exact associated_mul_left_cancel def associates (α : Type*) [monoid α] : Type* := quotient (associated.setoid α) namespace associates open associated protected def mk {α : Type*} [monoid α] (a : α) : associates α := ⟦ a ⟧ theorem mk_eq_mk_iff_associated [monoid α] {a b : α} : associates.mk a = associates.mk b ↔ a ~ᵤ b := iff.intro quotient.exact quot.sound theorem quotient_mk_eq_mk [monoid α] (a : α) : ⟦ a ⟧ = associates.mk a := rfl theorem quot_mk_eq_mk [monoid α] (a : α) : quot.mk setoid.r a = associates.mk a := rfl theorem forall_associated [monoid α] {p : associates α → Prop} : (∀a, p a) ↔ (∀a, p (associates.mk a)) := iff.intro (assume h a, h _) (assume h a, quotient.induction_on a h) instance [monoid α] : has_one (associates α) := ⟨⟦ 1 ⟧⟩ theorem one_eq_mk_one [monoid α] : (1 : associates α) = associates.mk 1 := rfl instance [monoid α] : has_bot (associates α) := ⟨1⟩ section comm_monoid variable [comm_monoid α] instance : has_mul (associates α) := ⟨λa' b', quotient.lift_on₂ a' b' (λa b, ⟦ a * b ⟧) $ assume a₁ a₂ b₁ b₂ ⟨c₁, h₁⟩ ⟨c₂, h₂⟩, quotient.sound $ ⟨c₁ * c₂, by simp [h₁.symm, h₂.symm, mul_assoc, mul_comm, mul_left_comm]⟩⟩ theorem mk_mul_mk {x y : α} : associates.mk x * associates.mk y = associates.mk (x * y) := rfl instance : comm_monoid (associates α) := { one := 1, mul := (*), mul_one := assume a', quotient.induction_on a' $ assume a, show ⟦a * 1⟧ = ⟦ a ⟧, by simp, one_mul := assume a', quotient.induction_on a' $ assume a, show ⟦1 * a⟧ = ⟦ a ⟧, by simp, mul_assoc := assume a' b' c', quotient.induction_on₃ a' b' c' $ assume a b c, show ⟦a * b * c⟧ = ⟦a * (b * c)⟧, by rw [mul_assoc], mul_comm := assume a' b', quotient.induction_on₂ a' b' $ assume a b, show ⟦a * b⟧ = ⟦b * a⟧, by rw [mul_comm] } instance : preorder (associates α) := { le := λa b, ∃c, a * c = b, le_refl := assume a, ⟨1, by simp⟩, le_trans := assume a b c ⟨f₁, h₁⟩ ⟨f₂, h₂⟩, ⟨f₁ * f₂, h₂ ▸ h₁ ▸ (mul_assoc _ _ _).symm⟩} instance [comm_monoid α] : has_dvd (associates α) := ⟨(≤)⟩ @[simp] lemma mk_one : associates.mk (1 : α) = 1 := rfl lemma mk_pow (a : α) (n : ℕ) : associates.mk (a ^ n) = (associates.mk a) ^ n := by induction n; simp [*, pow_succ, associates.mk_mul_mk.symm] lemma dvd_eq_le [comm_monoid α] : ((∣) : associates α → associates α → Prop) = (≤) := rfl theorem prod_mk {p : multiset α} : (p.map associates.mk).prod = associates.mk p.prod := multiset.induction_on p (by simp; refl) $ assume a s ih, by simp [ih]; refl theorem rel_associated_iff_map_eq_map {p q : multiset α} : multiset.rel associated p q ↔ p.map associates.mk = q.map associates.mk := by rw [← multiset.rel_eq]; simp [multiset.rel_map_left, multiset.rel_map_right, mk_eq_mk_iff_associated] theorem mul_eq_one_iff {x y : associates α} : x * y = 1 ↔ (x = 1 ∧ y = 1) := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b ~ᵤ 1, from quotient.exact h, ⟨quotient.sound $ associated_one_of_associated_mul_one this, quotient.sound $ associated_one_of_associated_mul_one $ by rwa [mul_comm] at this⟩) (by simp {contextual := tt}) theorem prod_eq_one_iff {p : multiset (associates α)} : p.prod = 1 ↔ (∀a ∈ p, (a:associates α) = 1) := multiset.induction_on p (by simp) (by simp [mul_eq_one_iff, or_imp_distrib, forall_and_distrib] {contextual := tt}) theorem coe_unit_eq_one : ∀u:units (associates α), (u : associates α) = 1 | ⟨u, v, huv, hvu⟩ := by rw [mul_eq_one_iff] at huv; exact huv.1 theorem is_unit_iff_eq_one (a : associates α) : is_unit a ↔ a = 1 := iff.intro (assume ⟨u, h⟩, h.symm ▸ coe_unit_eq_one _) (assume h, h.symm ▸ is_unit_one) theorem is_unit_mk {a : α} : is_unit (associates.mk a) ↔ is_unit a := calc is_unit (associates.mk a) ↔ a ~ᵤ 1 : by rw [is_unit_iff_eq_one, one_eq_mk_one, mk_eq_mk_iff_associated] ... ↔ is_unit a : associated_one_iff_is_unit section order theorem mul_mono {a b c d : associates α} (h₁ : a ≤ b) (h₂ : c ≤ d) : a * c ≤ b * d := let ⟨x, hx⟩ := h₁, ⟨y, hy⟩ := h₂ in ⟨x * y, by simp [hx.symm, hy.symm, mul_comm, mul_assoc, mul_left_comm]⟩ theorem one_le {a : associates α} : 1 ≤ a := ⟨a, one_mul a⟩ theorem prod_le_prod {p q : multiset (associates α)} (h : p ≤ q) : p.prod ≤ q.prod := begin haveI := classical.dec_eq (associates α), haveI := classical.dec_eq α, suffices : p.prod ≤ (p + (q - p)).prod, { rwa [multiset.add_sub_of_le h] at this }, suffices : p.prod * 1 ≤ p.prod * (q - p).prod, { simpa }, exact mul_mono (le_refl p.prod) one_le end theorem le_mul_right {a b : associates α} : a ≤ a * b := ⟨b, rfl⟩ theorem le_mul_left {a b : associates α} : a ≤ b * a := by rw [mul_comm]; exact le_mul_right end order end comm_monoid instance [has_zero α] [monoid α] : has_zero (associates α) := ⟨⟦ 0 ⟧⟩ instance [has_zero α] [monoid α] : has_top (associates α) := ⟨0⟩ section comm_semiring variables [comm_semiring α] @[simp] theorem mk_zero_eq (a : α) : associates.mk a = 0 ↔ a = 0 := ⟨assume h, (associated_zero_iff_eq_zero a).1 $ quotient.exact h, assume h, h.symm ▸ rfl⟩ @[simp] theorem mul_zero : ∀(a : associates α), a * 0 = 0 := by rintros ⟨a⟩; show associates.mk (a * 0) = associates.mk 0; rw [mul_zero] @[simp] protected theorem zero_mul : ∀(a : associates α), 0 * a = 0 := by rintros ⟨a⟩; show associates.mk (0 * a) = associates.mk 0; rw [zero_mul] theorem mk_eq_zero_iff_eq_zero {a : α} : associates.mk a = 0 ↔ a = 0 := calc associates.mk a = 0 ↔ (a ~ᵤ 0) : mk_eq_mk_iff_associated ... ↔ a = 0 : associated_zero_iff_eq_zero a theorem dvd_of_mk_le_mk {a b : α} : associates.mk a ≤ associates.mk b → a ∣ b | ⟨c', hc'⟩ := (quotient.induction_on c' $ assume c hc, let ⟨d, hd⟩ := (quotient.exact hc).symm in ⟨(↑d⁻¹) * c, calc b = (a * c) * ↑d⁻¹ : by rw [← hd, mul_assoc, units.mul_inv, mul_one] ... = a * (↑d⁻¹ * c) : by ac_refl⟩) hc' theorem mk_le_mk_of_dvd {a b : α} : a ∣ b → associates.mk a ≤ associates.mk b := assume ⟨c, hc⟩, ⟨associates.mk c, by simp [hc]; refl⟩ theorem mk_le_mk_iff_dvd_iff {a b : α} : associates.mk a ≤ associates.mk b ↔ a ∣ b := iff.intro dvd_of_mk_le_mk mk_le_mk_of_dvd def prime (p : associates α) : Prop := p ≠ 0 ∧ p ≠ 1 ∧ (∀a b, p ≤ a * b → p ≤ a ∨ p ≤ b) lemma exists_mem_multiset_le_of_prime {s : multiset (associates α)} {p : associates α} (hp : prime p) : p ≤ s.prod → ∃a∈s, p ≤ a := multiset.induction_on s (assume ⟨d, eq⟩, (hp.2.1 (mul_eq_one_iff.1 eq).1).elim) $ assume a s ih h, have p ≤ a * s.prod, by simpa using h, match hp.2.2 a s.prod this with | or.inl h := ⟨a, multiset.mem_cons_self a s, h⟩ | or.inr h := let ⟨a, has, h⟩ := ih h in ⟨a, multiset.mem_cons_of_mem has, h⟩ end lemma prime_mk (p : α) : prime (associates.mk p) ↔ _root_.prime p := begin rw [associates.prime, _root_.prime, forall_associated], transitivity, { apply and_congr, refl, apply and_congr, refl, apply forall_congr, assume a, exact forall_associated }, apply and_congr, { rw [(≠), mk_zero_eq] }, apply and_congr, { rw [(≠), ← is_unit_iff_eq_one, is_unit_mk], }, apply forall_congr, assume a, apply forall_congr, assume b, rw [mk_mul_mk, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff] end end comm_semiring section integral_domain variable [integral_domain α] instance : partial_order (associates α) := { le_antisymm := assume a' b', quotient.induction_on₂ a' b' $ assume a b ⟨f₁', h₁⟩ ⟨f₂', h₂⟩, (quotient.induction_on₂ f₁' f₂' $ assume f₁ f₂ h₁ h₂, let ⟨c₁, h₁⟩ := quotient.exact h₁, ⟨c₂, h₂⟩ := quotient.exact h₂ in quotient.sound $ associated_of_dvd_dvd (h₁ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _) (h₂ ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _)) h₁ h₂ .. associates.preorder } instance : lattice.order_bot (associates α) := { bot := 1, bot_le := assume a, one_le, .. associates.partial_order } instance : lattice.order_top (associates α) := { top := 0, le_top := assume a, ⟨0, mul_zero a⟩, .. associates.partial_order } theorem zero_ne_one : (0 : associates α) ≠ 1 := assume h, have (0 : α) ~ᵤ 1, from quotient.exact h, have (0 : α) = 1, from ((associated_zero_iff_eq_zero 1).1 this.symm).symm, zero_ne_one this theorem mul_eq_zero_iff {x y : associates α} : x * y = 0 ↔ x = 0 ∨ y = 0 := iff.intro (quotient.induction_on₂ x y $ assume a b h, have a * b = 0, from (associated_zero_iff_eq_zero _).1 (quotient.exact h), have a = 0 ∨ b = 0, from mul_eq_zero_iff_eq_zero_or_eq_zero.1 this, this.imp (assume h, h.symm ▸ rfl) (assume h, h.symm ▸ rfl)) (by simp [or_imp_distrib] {contextual := tt}) theorem prod_eq_zero_iff {s : multiset (associates α)} : s.prod = 0 ↔ (0 : associates α) ∈ s := multiset.induction_on s (by simp; exact zero_ne_one.symm) $ assume a s, by simp [mul_eq_zero_iff, @eq_comm _ 0 a] {contextual := tt} theorem irreducible_mk_iff (a : α) : irreducible (associates.mk a) ↔ irreducible a := begin simp [irreducible, is_unit_mk], apply and_congr (iff.refl _), split, { assume h x y eq, have : is_unit (associates.mk x) ∨ is_unit (associates.mk y), from h _ _ (by rw [eq]; refl), simpa [is_unit_mk] }, { refine assume h x y, quotient.induction_on₂ x y (assume x y eq, _), rcases quotient.exact eq.symm with ⟨u, eq⟩, have : a = x * (y * u), by rwa [mul_assoc, eq_comm] at eq, show is_unit (associates.mk x) ∨ is_unit (associates.mk y), simpa [is_unit_mk] using h _ _ this } end lemma eq_of_mul_eq_mul_left [integral_domain α] : ∀(a b c : associates α), a ≠ 0 → a * b = a * c → b = c := begin rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ha h, rcases quotient.exact' h with ⟨u, hu⟩, have hu : a * (b * ↑u) = a * c, { rwa [← mul_assoc] }, exact quotient.sound' ⟨u, eq_of_mul_eq_mul_left (mt (mk_zero_eq a).2 ha) hu⟩ end lemma le_of_mul_le_mul_left [integral_domain α] (a b c : associates α) (ha : a ≠ 0) : a * b ≤ a * c → b ≤ c | ⟨d, hd⟩ := ⟨d, eq_of_mul_eq_mul_left a _ _ ha $ by rwa ← mul_assoc⟩ lemma one_or_eq_of_le_of_prime [integral_domain α] : ∀(p m : associates α), prime p → m ≤ p → (m = 1 ∨ m = p) | _ m ⟨hp0, hp1, h⟩ ⟨d, rfl⟩ := match h m d (le_refl _) with | or.inl h := classical.by_cases (assume : m = 0, by simp [this]) $ assume : m ≠ 0, have m * d ≤ m * 1, by simpa using h, have d ≤ 1, from associates.le_of_mul_le_mul_left m d 1 ‹m ≠ 0› this, have d = 1, from lattice.bot_unique this, by simp [this] | or.inr h := classical.by_cases (assume : d = 0, by simp [this] at hp0; contradiction) $ assume : d ≠ 0, have d * m ≤ d * 1, by simpa [mul_comm] using h, or.inl $ lattice.bot_unique $ associates.le_of_mul_le_mul_left d m 1 ‹d ≠ 0› this end end integral_domain section normalization_domain variable [normalization_domain α] protected def out : associates α → α := begin refine quotient.lift (λa, a * ↑(norm_unit a)) _, letI := classical.dec_eq α, rintros a _ ⟨u, rfl⟩, by_cases a = 0, { simp [h] }, calc a * ↑(norm_unit a) = a * ↑(u * norm_unit a * u⁻¹) : by rw [mul_comm u, mul_assoc, mul_inv_self, mul_one] ... = a * ↑u * ↑(norm_unit (a * ↑u)) : by simp [h, norm_unit_mul, units.coe_mul, units.coe_inv, mul_assoc] end lemma out_mk (a : α) : (associates.mk a).out = a * ↑(norm_unit a) := rfl @[simp] lemma out_one : (1 : associates α).out = 1 := calc (1 : associates α).out = 1 * ↑(norm_unit (1 : α)) : out_mk _ ... = 1 : by simp lemma out_mul (a b : associates α) : (a * b).out = a.out * b.out := begin refine quotient.induction_on₂ a b (assume a b, _), simp [associates.quotient_mk_eq_mk, out_mk, mk_mul_mk], letI := classical.dec_eq α, by_cases a = 0; by_cases b = 0; simp [*, mul_assoc, mul_comm, mul_left_comm] end lemma dvd_out_iff (a : α) (b : associates α) : a ∣ b.out ↔ associates.mk a ≤ b := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] lemma out_dvd_iff (a : α) (b : associates α) : b.out ∣ a ↔ b ≤ associates.mk a := quotient.induction_on b $ by simp [associates.out_mk, associates.quotient_mk_eq_mk, mk_le_mk_iff_dvd_iff] @[simp] lemma out_top : (⊤ : associates α).out = 0 := calc (⊤ : associates α).out = 0 * ↑(norm_unit (0:α)) : out_mk _ ... = 0 : by simp @[simp] lemma norm_unit_out (a : associates α) : norm_unit a.out = 1 := quotient.induction_on a $ assume a, by rw [associates.quotient_mk_eq_mk, associates.out_mk, norm_unit_mul_norm_unit] end normalization_domain end associates def associates_int_equiv_nat : (associates ℤ) ≃ ℕ := begin refine ⟨λz, z.out.nat_abs, λn, associates.mk n, _, _⟩, { refine (assume a, quotient.induction_on a $ assume a, associates.mk_eq_mk_iff_associated.2 $ associated.symm $ ⟨norm_unit a, _⟩), simp [associates.out_mk, associates.quotient_mk_eq_mk, associated, int.coe_nat_abs_eq_mul_norm_unit.symm] }, { assume n, simp [associates.out_mk, int.coe_nat_abs_eq_mul_norm_unit.symm] } end
8e9ce8049d613ea7aba64ba8b0bbadc5369cce04
159fed64bfae88f3b6a6166836d6278f953bcbf9
/Structure/Generic/Axioms/FunctorExtensionality.lean
dc4614822794c22a1e2dedf25f5d872b56adaa4f
[ "MIT" ]
permissive
SReichelt/lean4-experiments
3e56830c8b2fbe3814eda071c48e3c8810d254a8
ff55357a01a34a91bf670d712637480089085ee4
refs/heads/main
1,683,977,454,907
1,622,991,121,000
1,622,991,121,000
340,765,677
2
0
null
null
null
null
UTF-8
Lean
false
false
1,374
lean
import Structure.Generic.Axioms.Universes import Structure.Generic.Axioms.AbstractFunctors import Structure.Generic.Axioms.InstanceEquivalences import Structure.Generic.Axioms.CategoryTheory set_option autoBoundImplicitLocal false --set_option pp.universes true def FunctorEquiv {U : Universe} [HasInternalFunctors U] [h : HasInstanceEquivalences U] [HasEquivCongrArg U U] [HasInstanceEquivalences h.equivUniverse] {α β : U} (F G : α ⟶ β) := NaturalQuantification (h.Equiv α) (h.Equiv β) (HasEquivCongrArg.equivCongrArg (HasInternalFunctors.toBundled F)) (HasEquivCongrArg.equivCongrArg (HasInternalFunctors.toBundled G)) class HasFunctorExtensionality (U : Universe) [HasInternalFunctors U] [h : HasInstanceEquivalences U] [HasEquivCongrArg U U] [HasInstanceEquivalences h.equivUniverse] where (funEquivEquiv {α β : U} {F G : α ⟶ β} : ⌈F ≃ G⌉ ≃ FunctorEquiv F G) -- TODO: This should follow from functor extensionality. Maybe because of the special role of equality in functors? --class HasLinearFunOpMorphisms (U : Universe) [HasInternalFunctors U] [HasLinearFunOp U] [HasInstanceEquivalences U] where --(leftId (α β : U) : HasLinearFunOp.revCompFunFun α (HasLinearFunOp.idFun β) ≃ HasLinearFunOp.idFun (α ⟶ β)) --(rightId (α β : U) : HasLinearFunOp.compFunFun (HasLinearFunOp.idFun α) β ≃ HasLinearFunOp.idFun (α ⟶ β))
50d0b1bc54f0b68f198b89e333c50dcdb2c0da6f
e4d500be102d7cc2cf7c341f360db71d9125c19b
/src/topology/subset_properties.lean
929189d257f7df50e51b31e5741c4677901bf22c
[ "Apache-2.0" ]
permissive
mgrabovsky/mathlib
3cbc6c54dab5f277f0abf4195a1b0e6e39b9971f
e397b4c1266ee241e9412e17b1dd8724f56fba09
refs/heads/master
1,664,687,987,155
1,591,255,329,000
1,591,255,329,000
269,361,264
0
0
Apache-2.0
1,591,275,784,000
1,591,275,783,000
null
UTF-8
Lean
false
false
54,402
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Yury Kudryashov -/ import topology.continuous_on /-! # Properties of subsets of topological spaces ## Main definitions `compact`, `is_clopen`, `is_irreducible`, `is_connected`, `is_totally_disconnected`, `is_totally_separated` TODO: write better docs ## On the definition of irreducible and connected sets/spaces In informal mathematics, irreducible and connected spaces are assumed to be nonempty. We formalise the predicate without that assumption as `is_preirreducible` and `is_preconnected` respectively. In other words, the only difference is whether the empty space counts as irreducible and/or connected. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open set filter classical open_locale classical topological_space universes u v variables {α : Type u} {β : Type v} [topological_space α] /- compact sets -/ section compact /-- A set `s` is compact if for every filter `f` that contains `s`, every set of `f` also meets every neighborhood of some `a ∈ s`. -/ def compact (s : set α) := ∀f, f ≠ ⊥ → f ≤ principal s → ∃a∈s, f ⊓ 𝓝 a ≠ ⊥ lemma compact.inter_right {s t : set α} (hs : compact s) (ht : is_closed t) : compact (s ∩ t) := assume f hnf hstf, let ⟨a, hsa, (ha : f ⊓ 𝓝 a ≠ ⊥)⟩ := hs f hnf (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))) in have a ∈ t, from ht.mem_of_nhds_within_ne_bot $ ne_bot_of_le_ne_bot (by { rw inf_comm at ha, exact ha }) $ inf_le_inf_left _ (le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))), ⟨a, ⟨hsa, this⟩, ha⟩ lemma compact.inter_left {s t : set α} (ht : compact t) (hs : is_closed s) : compact (s ∩ t) := inter_comm t s ▸ ht.inter_right hs lemma compact_diff {s t : set α} (hs : compact s) (ht : is_open t) : compact (s \ t) := hs.inter_right (is_closed_compl_iff.mpr ht) lemma compact_of_is_closed_subset {s t : set α} (hs : compact s) (ht : is_closed t) (h : t ⊆ s) : compact t := inter_eq_self_of_subset_right h ▸ hs.inter_right ht lemma compact.adherence_nhdset {s t : set α} {f : filter α} (hs : compact s) (hf₂ : f ≤ principal s) (ht₁ : is_open t) (ht₂ : ∀a∈s, 𝓝 a ⊓ f ≠ ⊥ → a ∈ t) : t ∈ f := classical.by_cases mem_sets_of_eq_bot $ assume : f ⊓ principal (- t) ≠ ⊥, let ⟨a, ha, (hfa : f ⊓ principal (-t) ⊓ 𝓝 a ≠ ⊥)⟩ := hs _ this $ inf_le_left_of_le hf₂ in have a ∈ t, from ht₂ a ha $ ne_bot_of_le_ne_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_left, have (-t) ∩ t ∈ nhds_within a (-t), from inter_mem_nhds_within _ (mem_nhds_sets ht₁ this), have A : nhds_within a (-t) = ⊥, from empty_in_sets_eq_bot.1 $ compl_inter_self t ▸ this, have nhds_within a (-t) ≠ ⊥, from ne_bot_of_le_ne_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_right, absurd A this lemma compact_iff_ultrafilter_le_nhds {s : set α} : compact s ↔ (∀f, is_ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ 𝓝 a) := ⟨assume hs : compact s, assume f hf hfs, let ⟨a, ha, h⟩ := hs _ hf.left hfs in ⟨a, ha, le_of_ultrafilter hf h⟩, assume hs : (∀f, is_ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ 𝓝 a), assume f hf hfs, let ⟨a, ha, (h : ultrafilter_of f ≤ 𝓝 a)⟩ := hs (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs) in have ultrafilter_of f ⊓ 𝓝 a ≠ ⊥, by simp only [inf_of_le_left, h]; exact (ultrafilter_ultrafilter_of hf).left, ⟨a, ha, ne_bot_of_le_ne_bot this (inf_le_inf_right _ ultrafilter_of_le)⟩⟩ /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma compact.elim_finite_subcover {s : set α} {ι : Type v} (hs : compact s) (U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) : ∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i := classical.by_contradiction $ assume h, have h : ∀ t : finset ι, ¬ s ⊆ ⋃ i ∈ t, U i, from assume t ht, h ⟨t, ht⟩, let f : filter α := (⨅t:finset ι, principal (s - ⋃ i ∈ t, U i)), ⟨a, ha⟩ := (@ne_empty_iff_nonempty α s).1 (assume h', h ∅ $ h'.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_ne_bot_of_directed ⟨a⟩ (assume t₁ t₂, ⟨t₁ ∪ t₂, principal_mono.mpr $ diff_subset_diff_right $ bUnion_subset_bUnion_left $ finset.subset_union_left _ _, principal_mono.mpr $ diff_subset_diff_right $ bUnion_subset_bUnion_left $ finset.subset_union_right _ _⟩) (assume t, show principal (s \ _) ≠ ⊥, by simp only [ne.def, principal_eq_bot_iff, diff_eq_empty]; exact h _), have f ≤ principal s, from infi_le_of_le ∅ $ show principal (s \ _) ≤ principal s, from le_principal_iff.2 (diff_subset _ _), let ⟨a, ha, (h : f ⊓ 𝓝 a ≠ ⊥)⟩ := hs f ‹f ≠ ⊥› this, ⟨_, ⟨i, rfl⟩, (ha : a ∈ U i)⟩ := hsU ha in have f ≤ principal (- U i), from infi_le_of_le {i} $ principal_mono.mpr $ show s - _ ⊆ - U i, by simp [diff_subset_iff], have is_closed (- U i), from is_open_compl_iff.mp $ by rw compl_compl; exact hUo i, have a ∈ - U i, from is_closed_iff_nhds.mp this _ $ ne_bot_of_le_ne_bot h $ le_inf inf_le_right (inf_le_left_of_le ‹f ≤ principal (- U i)›), this ‹a ∈ U i› /-- For every family of closed sets whose intersection avoids a compact set, there exists a finite subfamily whose intersection avoids this compact set. -/ lemma compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : compact s) (Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) : ∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ := let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, - Z i) hZc (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩ /-- Cantor's intersection theorem: the intersection of a directed family of nonempty compact closed sets is nonempty. -/ lemma compact.nonempty_Inter_of_directed_nonempty_compact_closed {ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z) (hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := begin apply hι.elim, intro i₀, let Z' := λ i, Z i ∩ Z i₀, suffices : (⋂ i, Z' i).nonempty, { exact nonempty.mono (Inter_subset_Inter $ assume i, inter_subset_left (Z i) (Z i₀)) this }, rw ← ne_empty_iff_nonempty, intro H, obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅, from (hZc i₀).elim_finite_subfamily_closed Z' (assume i, is_closed_inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]), obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i, { rcases directed.finset_le hι hZd t with ⟨i, hi⟩, rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩, use [i₁, hi₁₀], intros j hj, exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ }, suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty, { rw ← ne_empty_iff_nonempty at this, contradiction }, refine nonempty.mono _ (hZn i₁), exact subset_inter hi₁.left (subset_bInter hi₁.right) end /-- Cantor's intersection theorem for sequences indexed by `ℕ`: the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/ lemma compact.nonempty_Inter_of_sequence_nonempty_compact_closed (Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i) (hZn : ∀ i, (Z i).nonempty) (hZ0 : compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := have Zmono : _, from @monotone_of_monotone_nat (order_dual _) _ Z hZd, have hZd : directed (⊇) Z, from directed_of_mono Z Zmono, have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i, have hZc : ∀ i, compact (Z i), from assume i, compact_of_is_closed_subset hZ0 (hZcl i) (this i), compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma compact.elim_finite_subcover_image {s : set α} {b : set β} {c : β → set α} (hs : compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) : ∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i := begin rcases hs.elim_finite_subcover (λ i, c i.1 : b → set α) _ _ with ⟨d, hd⟩, refine ⟨↑(d.image subtype.val), _, finset.finite_to_set _, _⟩, { intros i hi, erw finset.mem_image at hi, rcases hi with ⟨s, hsd, rfl⟩, exact s.property }, { refine subset.trans hd _, rintros x ⟨_, ⟨s, rfl⟩, ⟨_, ⟨hsd, rfl⟩, H⟩⟩, refine ⟨c s.val, ⟨s.val, _⟩, H⟩, simp [finset.mem_image_of_mem subtype.val hsd] }, { rintro ⟨i, hi⟩, exact hc₁ i hi }, { refine subset.trans hc₂ _, rintros x ⟨_, ⟨i, rfl⟩, ⟨_, ⟨hib, rfl⟩, H⟩⟩, exact ⟨_, ⟨⟨i, hib⟩, rfl⟩, H⟩ }, end /-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem compact_of_finite_subfamily_closed {s : set α} (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) : compact s := assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, f ⊓ 𝓝 x ≠ ⊥), have hf : ∀x∈s, 𝓝 x ⊓ f = ⊥, by simpa only [not_exists, not_not, inf_comm], have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t, from assume ⟨x, hxs, hx⟩, have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_in_sets_eq_bot, hf x hxs], let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in have ∅ ∈ 𝓝 x ⊓ principal t₂, from (𝓝 x ⊓ principal t₂).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht, have 𝓝 x ⊓ principal t₂ = ⊥, by rwa [empty_in_sets_eq_bot] at this, by simp only [closure_eq_nhds] at hx; exact hx t₂ ht₂ this, let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure) (by simpa [eq_empty_iff_forall_not_mem, not_exists]) in have (⋂i∈t, subtype.val i) ∈ f, from Inter_mem_sets t.finite_to_set $ assume i hi, i.2, have s ∩ (⋂i∈t, subtype.val i) ∈ f, from inter_mem_sets (le_principal_iff.1 hfs) this, have ∅ ∈ f, from mem_sets_of_superset this $ assume x ⟨hxs, hx⟩, let ⟨i, hit, hxi⟩ := (show ∃i ∈ t, x ∉ closure (subtype.val i), by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in have x ∈ closure i.val, from subset_closure (mem_bInter_iff.mp hx i hit), show false, from hxi this, hfn $ by rwa [empty_in_sets_eq_bot] at this /-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/ lemma compact_of_finite_subcover {s : set α} (h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) : compact s := compact_of_finite_subfamily_closed $ assume ι Z hZc hsZ, let ⟨t, ht⟩ := h (λ i, - Z i) (assume i, is_open_compl_iff.mpr $ hZc i) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩ /-- A set `s` is compact if and only if for every open cover of `s`, there exists a finite subcover. -/ lemma compact_iff_finite_subcover {s : set α} : compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) := ⟨assume hs ι, hs.elim_finite_subcover, compact_of_finite_subcover⟩ /-- A set `s` is compact if and only if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem compact_iff_finite_subfamily_closed {s : set α} : compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) := ⟨assume hs ι, hs.elim_finite_subfamily_closed, compact_of_finite_subfamily_closed⟩ @[simp] lemma compact_empty : compact (∅ : set α) := assume f hnf hsf, not.elim hnf $ empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf @[simp] lemma compact_singleton {a : α} : compact ({a} : set α) := compact_of_finite_subcover $ assume ι U hUo hsU, let ⟨i, hai⟩ := (show ∃i : ι, a ∈ U i, from mem_Union.1 $ singleton_subset_iff.1 hsU) in ⟨{i}, singleton_subset_iff.2 (by simpa only [finset.bUnion_singleton])⟩ lemma set.finite.compact_bUnion {s : set β} {f : β → set α} (hs : finite s) (hf : ∀i ∈ s, compact (f i)) : compact (⋃i ∈ s, f i) := compact_of_finite_subcover $ assume ι U hUo hsU, have ∀i : subtype s, ∃t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo (calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi ... ⊆ ⋃j, U j : hsU), let ⟨finite_subcovers, h⟩ := axiom_of_choice this in by haveI : fintype (subtype s) := hs.fintype; exact let t := finset.bind finset.univ finite_subcovers in have (⋃i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from bUnion_subset $ assume i hi, calc f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩) ... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $ assume j hj, finset.mem_bind.mpr ⟨_, finset.mem_univ _, hj⟩, ⟨t, this⟩ lemma compact_Union {f : β → set α} [fintype β] (h : ∀i, compact (f i)) : compact (⋃i, f i) := by rw ← bUnion_univ; exact finite_univ.compact_bUnion (λ i _, h i) lemma set.finite.compact {s : set α} (hs : finite s) : compact s := bUnion_of_singleton s ▸ hs.compact_bUnion (λ _ _, compact_singleton) lemma compact.union {s t : set α} (hs : compact s) (ht : compact t) : compact (s ∪ t) := by rw union_eq_Union; exact compact_Union (λ b, by cases b; assumption) section tube_lemma variables [topological_space β] /-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes a product of an open neighborhood of `s` by an open neighborhood of `t`. -/ def nhds_contain_boxes (s : set α) (t : set β) : Prop := ∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n), ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n lemma nhds_contain_boxes.symm {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := assume H n hn hp, let ⟨u, v, uo, vo, su, tv, p⟩ := H (prod.swap ⁻¹' n) (continuous_swap n hn) (by rwa [←image_subset_iff, prod.swap, image_swap_prod]) in ⟨v, u, vo, uo, tv, su, by rwa [←image_subset_iff, prod.swap, image_swap_prod] at p⟩ lemma nhds_contain_boxes.comm {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm lemma nhds_contain_boxes_of_singleton {x : α} {y : β} : nhds_contain_boxes ({x} : set α) ({y} : set β) := assume n hn hp, let ⟨u, v, uo, vo, xu, yv, hp'⟩ := is_open_prod_iff.mp hn x y (hp $ by simp) in ⟨u, v, uo, vo, by simpa, by simpa, hp'⟩ lemma nhds_contain_boxes_of_compact {s : set α} (hs : compact s) (t : set β) (H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t := assume n hn hp, have ∀x : subtype s, ∃uv : set α × set β, is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n, from assume ⟨x, hx⟩, have set.prod {x} t ⊆ n, from subset.trans (prod_mono (by simpa) (subset.refl _)) hp, let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩, let ⟨uvs, h⟩ := classical.axiom_of_choice this in have us_cover : s ⊆ ⋃i, (uvs i).1, from assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1), let ⟨s0, s0_cover⟩ := hs.elim_finite_subcover _ (λi, (h i).1) us_cover in let u := ⋃(i ∈ s0), (uvs i).1 in let v := ⋂(i ∈ s0), (uvs i).2 in have is_open u, from is_open_bUnion (λi _, (h i).1), have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1), have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1), have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩, have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx', let ⟨i,is0,hi⟩ := this in (h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩, ⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩ lemma generalized_tube_lemma {s : set α} (hs : compact s) {t : set β} (ht : compact t) {n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) : ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n := have _, from nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $ nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton, this n hn hp end tube_lemma /-- Type class for compact spaces. Separation is sometimes included in the definition, especially in the French literature, but we do not include it here. -/ class compact_space (α : Type*) [topological_space α] : Prop := (compact_univ : compact (univ : set α)) lemma compact_univ [h : compact_space α] : compact (univ : set α) := h.compact_univ lemma cluster_point_of_compact [compact_space α] {f : filter α} (h : f ≠ ⊥) : ∃ x, f ⊓ 𝓝 x ≠ ⊥ := by simpa using compact_univ f h (by simpa using f.univ_sets) theorem compact_space_of_finite_subfamily_closed {α : Type u} [topological_space α] (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → (⋂ i, Z i) = ∅ → (∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅)) : compact_space α := { compact_univ := begin apply compact_of_finite_subfamily_closed, intros ι Z, specialize h Z, simpa using h end } lemma is_closed.compact [compact_space α] {s : set α} (h : is_closed s) : compact s := compact_of_is_closed_subset compact_univ h (subset_univ _) variables [topological_space β] lemma compact.image_of_continuous_on {s : set α} {f : α → β} (hs : compact s) (hf : continuous_on f s) : compact (f '' s) := begin intros l lne ls, have ne_bot : l.comap f ⊓ principal s ≠ ⊥, from comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls), rcases hs (l.comap f ⊓ principal s) ne_bot inf_le_right with ⟨a, has, ha⟩, use [f a, mem_image_of_mem f has], rw [inf_assoc, @inf_comm _ _ _ (𝓝 a)] at ha, exact ne_bot_of_le_ne_bot (@@map_ne_bot f ha) (tendsto_comap.inf $ hf a has) end lemma compact.image {s : set α} {f : α → β} (hs : compact s) (hf : continuous f) : compact (f '' s) := hs.image_of_continuous_on hf.continuous_on lemma compact_range [compact_space α] {f : α → β} (hf : continuous f) : compact (range f) := by rw ← image_univ; exact compact_univ.image hf local notation `𝓟` := principal /-- If X is compact then pr₂ : X × Y → Y is a closed map -/ theorem is_closed_proj_of_compact {X : Type*} [topological_space X] [compact_space X] {Y : Type*} [topological_space Y] : is_closed_map (prod.snd : X × Y → Y) := begin set πX := (prod.fst : X × Y → X), set πY := (prod.snd : X × Y → Y), assume C (hC : is_closed C), rw is_closed_iff_nhds at hC ⊢, assume y (y_closure : 𝓝 y ⊓ 𝓟 (πY '' C) ≠ ⊥), have : map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ≠ ⊥, { suffices : map πY (comap πY (𝓝 y) ⊓ 𝓟 C) ≠ ⊥, from map_ne_bot (λ h, this $ by rw h ; exact map_bot ), calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) = 𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _ ... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal ... ≠ ⊥ : y_closure }, obtain ⟨x, hx⟩ : ∃ x, map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x ≠ ⊥, from cluster_point_of_compact this, refine ⟨⟨x, y⟩, _, by simp [πY]⟩, apply hC, rw ← filter.map_ne_bot_iff πX, calc map πX (𝓝 (x, y) ⊓ 𝓟 C) = map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod] ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull ... ≠ ⊥ : hx, end lemma embedding.compact_iff_compact_image {s : set α} {f : α → β} (hf : embedding f) : compact s ↔ compact (f '' s) := iff.intro (assume h, h.image hf.continuous) $ assume h, begin rw compact_iff_ultrafilter_le_nhds at ⊢ h, intros u hu us', let u' : filter β := map f u, have : u' ≤ principal (f '' s), begin rw [map_le_iff_le_comap, comap_principal], convert us', exact preimage_image_eq _ hf.inj end, rcases h u' (ultrafilter_map hu) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩, refine ⟨a, ha, _⟩, rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap] end lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} : compact s ↔ compact (subtype.val '' s) := embedding_subtype_val.compact_iff_compact_image lemma compact_iff_compact_univ {s : set α} : compact s ↔ compact (univ : set (subtype s)) := by rw [compact_iff_compact_in_subtype, image_univ, subtype.val_range]; refl lemma compact_iff_compact_space {s : set α} : compact s ↔ compact_space s := compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩ lemma compact.prod {s : set α} {t : set β} (hs : compact s) (ht : compact t) : compact (set.prod s t) := begin rw compact_iff_ultrafilter_le_nhds at hs ht ⊢, intros f hf hfs, rw le_principal_iff at hfs, rcases hs (map prod.fst f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.1)⟩)) with ⟨a, sa, ha⟩, rcases ht (map prod.snd f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.2)⟩)) with ⟨b, tb, hb⟩, rw map_le_iff_le_comap at ha hb, refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩, rw nhds_prod_eq, exact le_inf ha hb end /-- Finite topological spaces are compact. -/ @[priority 100] instance fintype.compact_space [fintype α] : compact_space α := { compact_univ := set.finite_univ.compact } /-- The product of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α × β) := ⟨by { rw ← univ_prod_univ, exact compact_univ.prod compact_univ }⟩ /-- The disjoint union of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) := ⟨begin rw ← range_inl_union_range_inr, exact (compact_range continuous_inl).union (compact_range continuous_inr) end⟩ section tychonoff variables {ι : Type*} {π : ι → Type*} [∀i, topological_space (π i)] /-- Tychonoff's theorem -/ lemma compact_pi_infinite {s : Πi:ι, set (π i)} : (∀i, compact (s i)) → compact {x : Πi:ι, π i | ∀i, x i ∈ s i} := begin simp [compact_iff_ultrafilter_le_nhds, nhds_pi], exact assume h f hf hfs, let p : Πi:ι, filter (π i) := λi, map (λx:Πi:ι, π i, x i) f in have ∀i:ι, ∃a, a∈s i ∧ p i ≤ 𝓝 a, from assume i, h i (p i) (ultrafilter_map hf) $ show (λx:Πi:ι, π i, x i) ⁻¹' s i ∈ f.sets, from mem_sets_of_superset hfs $ assume x (hx : ∀i, x i ∈ s i), hx i, let ⟨a, ha⟩ := classical.axiom_of_choice this in ⟨a, assume i, (ha i).left, assume i, map_le_iff_le_comap.mp $ (ha i).right⟩ end instance pi.compact [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) := ⟨begin have A : compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} := compact_pi_infinite (λi, compact_univ), have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp, rwa this at A, end⟩ end tychonoff instance quot.compact_space {r : α → α → Prop} [compact_space α] : compact_space (quot r) := ⟨by { rw ← range_quot_mk, exact compact_range continuous_quot_mk }⟩ instance quotient.compact_space {s : setoid α} [compact_space α] : compact_space (quotient s) := quot.compact_space /-- There are various definitions of "locally compact space" in the literature, which agree for Hausdorff spaces but not in general. This one is the precise condition on X needed for the evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the compact-open topology. -/ class locally_compact_space (α : Type*) [topological_space α] : Prop := (local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ compact s) end compact section clopen /-- A set is clopen if it is both open and closed. -/ def is_clopen (s : set α) : Prop := is_open s ∧ is_closed s theorem is_clopen_union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) := ⟨is_open_union hs.1 ht.1, is_closed_union hs.2 ht.2⟩ theorem is_clopen_inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) := ⟨is_open_inter hs.1 ht.1, is_closed_inter hs.2 ht.2⟩ @[simp] theorem is_clopen_empty : is_clopen (∅ : set α) := ⟨is_open_empty, is_closed_empty⟩ @[simp] theorem is_clopen_univ : is_clopen (univ : set α) := ⟨is_open_univ, is_closed_univ⟩ theorem is_clopen_compl {s : set α} (hs : is_clopen s) : is_clopen (-s) := ⟨hs.2, is_closed_compl_iff.2 hs.1⟩ @[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen (-s) ↔ is_clopen s := ⟨λ h, compl_compl s ▸ is_clopen_compl h, is_clopen_compl⟩ theorem is_clopen_diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s-t) := is_clopen_inter hs (is_clopen_compl ht) end clopen section preirreducible /-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/ def is_preirreducible (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- An irreducible set `s` is one that is nonempty and where there is no non-trivial pair of disjoint opens on `s`. -/ def is_irreducible (s : set α) : Prop := s.nonempty ∧ is_preirreducible s lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) : s.nonempty := h.1 lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) : is_preirreducible s := h.2 theorem is_preirreducible_empty : is_preirreducible (∅ : set α) := λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) := ⟨singleton_nonempty x, λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3; substs y z; exact ⟨x, rfl, h2, h4⟩⟩ theorem is_preirreducible.closure {s : set α} (H : is_preirreducible s) : is_preirreducible (closure s) := λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ lemma is_irreducible.closure {s : set α} (h : is_irreducible s) : is_irreducible (closure s) := ⟨h.nonempty.closure, h.is_preirreducible.closure⟩ theorem exists_preirreducible (s : set α) (H : is_preirreducible s) : ∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t := let ⟨m, hm, hsm, hmm⟩ := zorn.zorn_subset₀ {t : set α | is_preirreducible t} (λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in ⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩, let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy, ⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in or.cases_on (zorn.chain.total hcc hpc hqc) (assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv ⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩) (assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv ⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩), λ x hxc, set.subset_sUnion_of_mem hxc⟩) s H in ⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩ /-- A maximal irreducible set that contains a given point. -/ def irreducible_component (x : α) : set α := classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) lemma irreducible_component_property (x : α) : is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧ ∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) := classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x := singleton_subset_iff.1 (irreducible_component_property x).2.1 theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) := ⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩ theorem eq_irreducible_component {x : α} : ∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x := (irreducible_component_property x).2.2 theorem is_closed_irreducible_component {x : α} : is_closed (irreducible_component x) := closure_eq_iff_is_closed.1 $ eq_irreducible_component is_irreducible_irreducible_component.is_preirreducible.closure subset_closure /-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/ class preirreducible_space (α : Type u) [topological_space α] : Prop := (is_preirreducible_univ [] : is_preirreducible (univ : set α)) section prio set_option default_priority 100 -- see Note [default priority] /-- An irreducible space is one that is nonempty and where there is no non-trivial pair of disjoint opens. -/ class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop := (to_nonempty [] : nonempty α) end prio attribute [instance, priority 50] irreducible_space.to_nonempty -- see Note [lower instance priority] theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} : is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preirreducible_space.is_preirreducible_univ α _ _ s t theorem is_preirreducible.image [topological_space β] {s : set α} (H : is_preirreducible s) (f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) := begin rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩, rw ← set.mem_preimage at hxu hyv, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, have := H u' v' hu' hv', rw [set.inter_comm s u', ← u'_eq] at this, rw [set.inter_comm s v', ← v'_eq] at this, rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩, refine ⟨f z, mem_image_of_mem f hzs, _, _⟩, all_goals { rw ← set.mem_preimage, apply set.mem_of_mem_inter_left, show z ∈ _ ∩ s, simp [*] } end theorem is_irreducible.image [topological_space β] {s : set α} (H : is_irreducible s) (f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preirreducible.image f hf⟩ lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) : preirreducible_space s := { is_preirreducible_univ := begin intros u v hu hv hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩ end } lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) : irreducible_space s := { is_preirreducible_univ := (subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ, to_nonempty := h.nonempty.to_subtype } /-- A set `s` is irreducible if and only if for every finite collection of open sets all of whose members intersect `s`, `s` also intersects the intersection of the entire collection (i.e., there is an element of `s` contained in every member of the collection). -/ lemma is_irreducible_iff_sInter {s : set α} : is_irreducible s ↔ ∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty), (s ∩ ⋂₀ ↑U).nonempty := begin split; intro h, { intro U, apply finset.induction_on U, { intros, simpa using h.nonempty }, { intros u U hu IH hU H, rw [finset.coe_insert, sInter_insert], apply h.2, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sInter (finset.finite_to_set U), intros, solve_by_elim [finset.mem_insert_of_mem] }, { solve_by_elim [finset.mem_insert_self] }, { apply IH, all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } }, { split, { simpa using h ∅ _ _; intro u; simp }, intros u v hu hv hu' hv', simpa using h {u,v} _ _, all_goals { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption } } end /-- A set is preirreducible if and only if for every cover by two closed sets, it is contained in one of the two covering sets. -/ lemma is_preirreducible_iff_closed_union_closed {s : set α} : is_preirreducible s ↔ ∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ := begin split, all_goals { intros h t₁ t₂ ht₁ ht₂, specialize h (-t₁) (-t₂), simp only [is_open_compl_iff, is_closed_compl_iff] at h, specialize h ht₁ ht₂ }, { contrapose!, simp only [not_subset], rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩, rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩, rw ← compl_union at hz', exact ⟨z, hz, hz'⟩ }, { rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, rw ← compl_inter at h, delta set.nonempty, rw imp_iff_not_or at h, contrapose! h, split, { intros z hz hz', exact h z ⟨hz, hz'⟩ }, { split; intro H; refine H _ ‹_›; assumption } } end /-- A set is irreducible if and only if for every cover by a finite collection of closed sets, it is contained in one of the members of the collection. -/ lemma is_irreducible_iff_sUnion_closed {s : set α} : is_irreducible s ↔ ∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z), ∃ z ∈ Z, s ⊆ z := begin rw [is_irreducible, is_preirreducible_iff_closed_union_closed], split; intro h, { intro Z, apply finset.induction_on Z, { intros, rw [finset.coe_empty, sUnion_empty] at H, rcases h.1 with ⟨x, hx⟩, exfalso, tauto }, { intros z Z hz IH hZ H, cases h.2 z (⋃₀ ↑Z) _ _ _ with h' h', { exact ⟨z, finset.mem_insert_self _ _, h'⟩ }, { rcases IH _ h' with ⟨z', hz', hsz'⟩, { exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { rw sUnion_eq_bUnion, apply is_closed_bUnion (finset.finite_to_set Z), { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { simpa using H } } }, { split, { by_contradiction hs, simpa using h ∅ _ _, { intro z, simp }, { simpa [set.nonempty] using hs } }, intros z₁ z₂ hz₁ hz₂ H, have := h {z₁, z₂} _ _, simp only [exists_prop, finset.mem_insert, finset.mem_singleton] at this, { rcases this with ⟨z, rfl|rfl, hz⟩; tauto }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using H } } end end preirreducible section preconnected /-- A preconnected set is one where there is no non-trivial open partition. -/ def is_preconnected (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- A connected set is one that is nonempty and where there is no non-trivial open partition. -/ def is_connected (s : set α) : Prop := s.nonempty ∧ is_preconnected s lemma is_connected.nonempty {s : set α} (h : is_connected s) : s.nonempty := h.1 lemma is_connected.is_preconnected {s : set α} (h : is_connected s) : is_preconnected s := h.2 theorem is_preirreducible.is_preconnected {s : set α} (H : is_preirreducible s) : is_preconnected s := λ _ _ hu hv _, H _ _ hu hv theorem is_irreducible.is_connected {s : set α} (H : is_irreducible s) : is_connected s := ⟨H.nonempty, H.is_preirreducible.is_preconnected⟩ theorem is_preconnected_empty : is_preconnected (∅ : set α) := is_preirreducible_empty.is_preconnected theorem is_connected_singleton {x} : is_connected ({x} : set α) := is_irreducible_singleton.is_connected /-- If any point of a set is joined to a fixed point by a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall {s : set α} (x : α) (H : ∀ y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨z, zs, zu⟩ ⟨y, ys, yv⟩, have xs : x ∈ s, by { rcases H y ys with ⟨t, ts, xt, yt, ht⟩, exact ts xt }, wlog xu : x ∈ u := hs xs using [u v y z, v u z y], rcases H y ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- If any two points of a set are contained in a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall_pair {s : set α} (H : ∀ x y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, rcases H x y xs ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- A union of a family of preconnected sets with a common point is preconnected as well. -/ theorem is_preconnected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s) (H2 : ∀ s ∈ c, is_preconnected s) : is_preconnected (⋃₀ c) := begin apply is_preconnected_of_forall x, rintros y ⟨s, sc, ys⟩, exact ⟨s, subset_sUnion_of_mem sc, H1 s sc, ys, H2 s sc⟩ end theorem is_preconnected.union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t) (H3 : is_preconnected s) (H4 : is_preconnected t) : is_preconnected (s ∪ t) := sUnion_pair s t ▸ is_preconnected_sUnion x {s, t} (by rintro r (rfl | rfl | h); assumption) (by rintro r (rfl | rfl | h); assumption) theorem is_connected.union {s t : set α} (H : (s ∩ t).nonempty) (Hs : is_connected s) (Ht : is_connected t) : is_connected (s ∪ t) := begin rcases H with ⟨x, hx⟩, refine ⟨⟨x, mem_union_left t (mem_of_mem_inter_left hx)⟩, _⟩, exact is_preconnected.union x (mem_of_mem_inter_left hx) (mem_of_mem_inter_right hx) Hs.is_preconnected Ht.is_preconnected end theorem is_preconnected.closure {s : set α} (H : is_preconnected s) : is_preconnected (closure s) := λ u v hu hv hcsuv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans subset_closure hcsuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ theorem is_connected.closure {s : set α} (H : is_connected s) : is_connected (closure s) := ⟨H.nonempty.closure, H.is_preconnected.closure⟩ theorem is_preconnected.image [topological_space β] {s : set α} (H : is_preconnected s) (f : α → β) (hf : continuous_on f s) : is_preconnected (f '' s) := begin -- Unfold/destruct definitions in hypotheses rintros u v hu hv huv ⟨_, ⟨x, xs, rfl⟩, xu⟩ ⟨_, ⟨y, ys, rfl⟩, yv⟩, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, -- Reformulate `huv : f '' s ⊆ u ∪ v` in terms of `u'` and `v'` replace huv : s ⊆ u' ∪ v', { rw [image_subset_iff, preimage_union] at huv, replace huv := subset_inter huv (subset.refl _), rw [inter_distrib_right, u'_eq, v'_eq, ← inter_distrib_right] at huv, exact (subset_inter_iff.1 huv).1 }, -- Now `s ⊆ u' ∪ v'`, so we can apply `‹is_preconnected s›` obtain ⟨z, hz⟩ : (s ∩ (u' ∩ v')).nonempty, { refine H u' v' hu' hv' huv ⟨x, _⟩ ⟨y, _⟩; rw inter_comm, exacts [u'_eq ▸ ⟨xu, xs⟩, v'_eq ▸ ⟨yv, ys⟩] }, rw [← inter_self s, inter_assoc, inter_left_comm s u', ← inter_assoc, inter_comm s, inter_comm s, ← u'_eq, ← v'_eq] at hz, exact ⟨f z, ⟨z, hz.1.2, rfl⟩, hz.1.1, hz.2.1⟩ end theorem is_connected.image [topological_space β] {s : set α} (H : is_connected s) (f : α → β) (hf : continuous_on f s) : is_connected (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preconnected.image f hf⟩ theorem is_preconnected_closed_iff {s : set α} : is_preconnected s ↔ ∀ t t', is_closed t → is_closed t' → s ⊆ t ∪ t' → (s ∩ t).nonempty → (s ∩ t').nonempty → (s ∩ (t ∩ t')).nonempty := ⟨begin rintros h t t' ht ht' htt' ⟨x, xs, xt⟩ ⟨y, ys, yt'⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xt' : x ∉ t', from (h' xs).elim (absurd xt) id, have yt : y ∉ t, from (h' ys).elim id (absurd yt'), have := ne_empty_iff_nonempty.2 (h (-t) (-t') (is_open_compl_iff.2 ht) (is_open_compl_iff.2 ht') h' ⟨y, ys, yt⟩ ⟨x, xs, xt'⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end, begin rintros h u v hu hv huv ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xv : x ∉ v, from (h' xs).elim (absurd xu) id, have yu : y ∉ u, from (h' ys).elim id (absurd yv), have := ne_empty_iff_nonempty.2 (h (-u) (-v) (is_closed_compl_iff.2 hu) (is_closed_compl_iff.2 hv) h' ⟨y, ys, yu⟩ ⟨x, xs, xv⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end⟩ /-- The connected component of a point is the maximal connected set that contains this point. -/ def connected_component (x : α) : set α := ⋃₀ { s : set α | is_preconnected s ∧ x ∈ s } theorem mem_connected_component {x : α} : x ∈ connected_component x := mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton.is_preconnected, mem_singleton x⟩ theorem is_connected_connected_component {x : α} : is_connected (connected_component x) := ⟨⟨x, mem_connected_component⟩, is_preconnected_sUnion x _ (λ _, and.right) (λ _, and.left)⟩ theorem subset_connected_component {x : α} {s : set α} (H1 : is_preconnected s) (H2 : x ∈ s) : s ⊆ connected_component x := λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩ theorem is_closed_connected_component {x : α} : is_closed (connected_component x) := closure_eq_iff_is_closed.1 $ subset.antisymm (subset_connected_component is_connected_connected_component.closure.is_preconnected (subset_closure mem_connected_component)) subset_closure theorem irreducible_component_subset_connected_component {x : α} : irreducible_component x ⊆ connected_component x := subset_connected_component is_irreducible_irreducible_component.is_connected.is_preconnected mem_irreducible_component /-- A preconnected space is one where there is no non-trivial open partition. -/ class preconnected_space (α : Type u) [topological_space α] : Prop := (is_preconnected_univ : is_preconnected (univ : set α)) section prio set_option default_priority 100 -- see Note [default priority] /-- A connected space is a nonempty one where there is no non-trivial open partition. -/ class connected_space (α : Type u) [topological_space α] extends preconnected_space α : Prop := (to_nonempty : nonempty α) end prio attribute [instance, priority 50] connected_space.to_nonempty -- see Note [lower instance priority] @[priority 100] -- see Note [lower instance priority] instance preirreducible_space.preconnected_space (α : Type u) [topological_space α] [preirreducible_space α] : preconnected_space α := ⟨(preirreducible_space.is_preirreducible_univ α).is_preconnected⟩ @[priority 100] -- see Note [lower instance priority] instance irreducible_space.connected_space (α : Type u) [topological_space α] [irreducible_space α] : connected_space α := { to_nonempty := irreducible_space.to_nonempty α } theorem nonempty_inter [preconnected_space α] {s t : set α} : is_open s → is_open t → s ∪ t = univ → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preconnected_space.is_preconnected_univ α _ _ s t theorem is_clopen_iff [preconnected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ := ⟨λ hs, classical.by_contradiction $ λ h, have h1 : s ≠ ∅ ∧ -s ≠ ∅, from ⟨mt or.inl h, mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩, let ⟨_, h2, h3⟩ := nonempty_inter hs.1 hs.2 (union_compl_self s) (ne_empty_iff_nonempty.1 h1.1) (ne_empty_iff_nonempty.1 h1.2) in h3 h2, by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩ lemma subtype.preconnected_space {s : set α} (h : is_preconnected s) : preconnected_space s := { is_preconnected_univ := begin intros u v hu hv hs hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv _ ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩, intros z hz, rcases hs (set.mem_univ ⟨z, hz⟩) with hzu|hzv, { left, assumption }, { right, assumption } end } lemma subtype.connected_space {s : set α} (h : is_connected s) : connected_space s := { is_preconnected_univ := (subtype.preconnected_space h.is_preconnected).is_preconnected_univ, to_nonempty := h.nonempty.to_subtype } /-- A set `s` is preconnected if and only if for every cover by two open sets that are disjoint on `s`, it is contained in one of the two covering sets. -/ lemma is_preconnected_iff_subset_of_disjoint {s : set α} : is_preconnected s ↔ ∀ (u v : set α) (hu : is_open u) (hv : is_open v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅), s ⊆ u ∨ s ⊆ v := begin split; intro h, { intros u v hu hv hs huv, specialize h u v hu hv hs, contrapose! huv, rw ne_empty_iff_nonempty, simp [not_subset] at huv, rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩, have hxv : x ∈ v := classical.or_iff_not_imp_left.mp (hs hxs) hxu, have hyu : y ∈ u := classical.or_iff_not_imp_right.mp (hs hys) hyv, exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ }, { intros u v hu hv hs hsu hsv, rw ← ne_empty_iff_nonempty, intro H, specialize h u v hu hv hs H, contrapose H, apply ne_empty_iff_nonempty.mpr, cases h, { rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ }, { rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } } end /-- A set `s` is connected if and only if for every cover by a finite collection of open sets that are pairwise disjoint on `s`, it is contained in one of the members of the collection. -/ lemma is_connected_iff_sUnion_disjoint_open {s : set α} : is_connected s ↔ ∀ (U : finset (set α)) (H : ∀ (u v : set α), u ∈ U → v ∈ U → (s ∩ (u ∩ v)).nonempty → u = v) (hU : ∀ u ∈ U, is_open u) (hs : s ⊆ ⋃₀ ↑U), ∃ u ∈ U, s ⊆ u := begin rw [is_connected, is_preconnected_iff_subset_of_disjoint], split; intro h, { intro U, apply finset.induction_on U, { rcases h.left, suffices : s ⊆ ∅ → false, { simpa }, intro, solve_by_elim }, { intros u U hu IH hs hU H, rw [finset.coe_insert, sUnion_insert] at H, cases h.2 u (⋃₀ ↑U) _ _ H _ with hsu hsU, { exact ⟨u, finset.mem_insert_self _ _, hsu⟩ }, { rcases IH _ _ hsU with ⟨v, hvU, hsv⟩, { exact ⟨v, finset.mem_insert_of_mem hvU, hsv⟩ }, { intros, apply hs; solve_by_elim [finset.mem_insert_of_mem] }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sUnion, intros, solve_by_elim [finset.mem_insert_of_mem] }, { apply eq_empty_of_subset_empty, rintro x ⟨hxs, hxu, hxU⟩, rw mem_sUnion at hxU, rcases hxU with ⟨v, hvU, hxv⟩, rcases hs u v (finset.mem_insert_self _ _) (finset.mem_insert_of_mem hvU) _ with rfl, { contradiction }, { exact ⟨x, hxs, hxu, hxv⟩ } } } }, { split, { rw ← ne_empty_iff_nonempty, by_contradiction hs, push_neg at hs, subst hs, simpa using h ∅ _ _ _; simp }, intros u v hu hv hs hsuv, rcases h {u, v} _ _ _ with ⟨t, ht, ht'⟩, { rw [finset.mem_insert, finset.mem_singleton] at ht, rcases ht with rfl|rfl; tauto }, { intros t₁ t₂ ht₁ ht₂ hst, rw ← ne_empty_iff_nonempty at hst, rw [finset.mem_insert, finset.mem_singleton] at ht₁ ht₂, rcases ht₁ with rfl|rfl; rcases ht₂ with rfl|rfl, all_goals { refl <|> contradiction <|> skip }, rw inter_comm t₁ at hst, contradiction }, { intro t, rw [finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using hs } } end end preconnected section totally_disconnected /-- A set is called totally disconnected if all of its connected components are singletons. -/ def is_totally_disconnected (s : set α) : Prop := ∀ t, t ⊆ s → is_preconnected t → subsingleton t theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) := λ t ht _, ⟨λ ⟨_, h⟩, (ht h).elim⟩ theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) := λ t ht _, ⟨λ ⟨p, hp⟩ ⟨q, hq⟩, subtype.eq $ show p = q, from (eq_of_mem_singleton (ht hp)).symm ▸ (eq_of_mem_singleton (ht hq)).symm⟩ /-- A space is totally disconnected if all of its connected components are singletons. -/ class totally_disconnected_space (α : Type u) [topological_space α] : Prop := (is_totally_disconnected_univ : is_totally_disconnected (univ : set α)) end totally_disconnected section totally_separated /-- A set `s` is called totally separated if any two points of this set can be separated by two disjoint open sets covering `s`. -/ def is_totally_separated (s : set α) : Prop := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅ theorem is_totally_separated_empty : is_totally_separated (∅ : set α) := λ x, false.elim theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) := λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim theorem is_totally_disconnected_of_is_totally_separated {s : set α} (H : is_totally_separated s) : is_totally_disconnected s := λ t hts ht, ⟨λ ⟨x, hxt⟩ ⟨y, hyt⟩, subtype.eq $ classical.by_contradiction $ assume hxy : x ≠ y, let ⟨u, v, hu, hv, hxu, hyv, hsuv, huv⟩ := H x (hts hxt) y (hts hyt) hxy in let ⟨r, hrt, hruv⟩ := ht u v hu hv (subset.trans hts hsuv) ⟨x, hxt, hxu⟩ ⟨y, hyt, hyv⟩ in (ext_iff.1 huv r).1 hruv⟩ /-- A space is totally separated if any two points can be separated by two disjoint open sets covering the whole space. -/ class totally_separated_space (α : Type u) [topological_space α] : Prop := (is_totally_separated_univ [] : is_totally_separated (univ : set α)) @[priority 100] -- see Note [lower instance priority] instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α] [totally_separated_space α] : totally_disconnected_space α := ⟨is_totally_disconnected_of_is_totally_separated $ totally_separated_space.is_totally_separated_univ α⟩ end totally_separated
3a6749224c81060c9f0f3d12dc7261335a63cfb1
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/playground/DiscrTree.lean
c8d22fbd4d7155c9574a15c6582c6ee2dbf5f39c
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
9,362
lean
import Init.Lean.Format open Lean def List.insert {α} [HasBeq α] (as : List α) (a : α) : List α := if as.contains a then as else a::as inductive Term | var : Nat → Term | app : String → Array Term → Term instance : Inhabited Term := ⟨Term.var 0⟩ inductive Key | var : Key | sym : String → Nat → Key instance : Inhabited Key := ⟨Key.var⟩ def Key.beq : Key → Key → Bool | Key.var, Key.var => true | Key.sym k₁ a₁, Key.sym k₂ a₂ => k₁ == k₂ && a₁ == a₂ | _, _ => false instance : HasBeq Key := ⟨Key.beq⟩ def Key.lt : Key → Key → Bool | Key.var, Key.var => false | Key.var, _ => true | Key.sym k₁ a₁, Key.sym k₂ a₂ => k₁ < k₂ || (k₁ == k₂ && a₁ < a₂) | _, _ => false instance : HasLess Key := ⟨fun k₁ k₂ => k₁.lt k₂⟩ def Key.format : Key → Format | Key.var => "*" | Key.sym k a => if a > 0 then k ++ "." ++ fmt a else k instance : HasFormat Key := ⟨Key.format⟩ def Term.key : Term → Key | Term.var _ => Key.var | Term.app f as => Key.sym f as.size def Term.args : Term → Array Term | Term.var _ => #[] | Term.app f as => as -- TODO: root should be a persistent hash map inductive Trie (α : Type) | node (vals : List α) (children : Array (Key × Trie)) : Trie namespace Trie def empty {α} : Trie α := node [] #[] instance {α} : Inhabited (Trie α) := ⟨empty⟩ partial def appendTodoAux (as : Array Term) : Nat → Array Term → Array Term | 0, todo => todo | i+1, todo => appendTodoAux i (todo.push (as.get! i)) def appendTodo (todo : Array Term) (as : Array Term) : Array Term := appendTodoAux as as.size todo partial def createNodes {α} (v : α) : Array Term → Trie α | todo => if todo.isEmpty then node [v] #[] else let t := todo.back; let todo := todo.pop; node [] #[(t.key, createNodes (appendTodo todo t.args))] partial def insertAux {α} [HasBeq α] (v : α) : Array Term → Trie α → Trie α | todo, node vs cs => if todo.isEmpty then node (vs.insert v) cs else let t := todo.back; let todo := todo.pop; let todo := appendTodo todo t.args; let k := t.key; node vs $ Id.run $ cs.binInsertM (fun a b => a.1 < b.1) (fun ⟨_, s⟩ => (k, insertAux todo s)) -- merge with existing (fun _ => (k, createNodes v todo)) -- add new node (k, arbitrary _) def insert {α} [HasBeq α] (d : Trie α) (k : Term) (v : α) : Trie α := let todo : Array Term := Array.mkEmpty 32; let todo := todo.push k; insertAux v todo d partial def format {α} [HasFormat α] : Trie α → Format | node vs cs => Format.group $ Format.paren $ "node" ++ (if vs.isEmpty then Format.nil else " " ++ fmt vs) ++ Format.join (cs.toList.map $ fun ⟨k, c⟩ => Format.line ++ Format.paren (fmt k ++ " => " ++ format c)) instance {α} [HasFormat α] : HasFormat (Trie α) := ⟨format⟩ @[specialize] partial def foldMatchAux {α β} {m : Type → Type} [Monad m] (f : β → α → m β) : Array Term → Trie α → β → m β | todo, node vs cs, b => if todo.isEmpty then vs.foldlM f b else if cs.isEmpty then pure b else let t := todo.back; let todo := todo.pop; let first := cs.get! 0; let k := t.key; match k with | Key.var => if first.1 == Key.var then foldMatchAux todo first.2 b else pure b | Key.sym _ _ => do match cs.binSearch (k, arbitrary _) (fun a b => a.1 < b.1) with | none => if first.1 == Key.var then foldMatchAux todo first.2 b else pure b | some c => do b ← if first.1 == Key.var then foldMatchAux todo first.2 b else pure b; let todo := appendTodo todo t.args; foldMatchAux todo c.2 b @[specialize] def foldMatch {α β} {m : Type → Type} [Monad m] (d : Trie α) (k : Term) (f : β → α → m β) (b : β) : m β := let todo : Array Term := Array.mkEmpty 32; let todo := todo.push k; foldMatchAux f todo d b /-- Return all (approximate) matches (aka generalizations) of the term `k` -/ def getMatch {α} (d : Trie α) (k : Term) : Array α := Id.run $ d.foldMatch k (fun (r : Array α) v => pure $ r.push v) #[] @[specialize] partial def foldUnifyAux {α β} {m : Type → Type} [Monad m] (f : β → α → m β) : Nat → Array Term → Trie α → β → m β | skip+1, todo, node vs cs, b => if cs.isEmpty then pure b else cs.foldlM (fun b ⟨k, c⟩ => match k with | Key.var => foldUnifyAux skip todo c b | Key.sym _ a => foldUnifyAux (skip + a) todo c b) b | 0, todo, node vs cs, b => if todo.isEmpty then vs.foldlM f b else if cs.isEmpty then pure b else let t := todo.back; let todo := todo.pop; let first := cs.get! 0; let k := t.key; match k with | Key.var => cs.foldlM (fun b ⟨k, c⟩ => match k with | Key.var => foldUnifyAux 0 todo c b | Key.sym _ a => foldUnifyAux a todo c b) b | Key.sym _ _ => do match cs.binSearch (k, arbitrary _) (fun a b => a.1 < b.1) with | none => if first.1 == Key.var then foldUnifyAux 0 todo first.2 b else pure b | some c => do b ← if first.1 == Key.var then foldUnifyAux 0 todo first.2 b else pure b; let todo := appendTodo todo t.args; foldUnifyAux 0 todo c.2 b @[specialize] def foldUnify {α β} {m : Type → Type} [Monad m] (d : Trie α) (k : Term) (f : β → α → m β) (b : β) : m β := let todo : Array Term := Array.mkEmpty 32; let todo := todo.push k; foldUnifyAux f 0 todo d b /-- Return all candidate unifiers of the term `k` -/ def getUnify {α} (d : Trie α) (k : Term) : Array α := Id.run $ d.foldUnify k (fun (r : Array α) v => pure $ r.push v) #[] end Trie def mkApp (s : String) (cs : Array Term) := Term.app s cs def mkConst (s : String) := Term.app s #[] def mkVar (i : Nat) := Term.var i def tst1 : IO Unit := let d := @Trie.empty Nat; let t := mkApp "f" #[mkApp "g" #[mkConst "a"], mkApp "g" #[mkConst "b"]]; let d := d.insert t 10; let t := mkApp "f" #[mkApp "h" #[mkConst "a", mkVar 0], mkConst "b"]; let d := d.insert t 20; let t := mkApp "f" #[mkConst "b", mkConst "c", mkConst "d"]; let d := d.insert t 20; let d := (20:Nat).fold (fun i (d : Trie Nat) => let t := mkApp "f" #[mkApp "h" #[mkConst "a", mkVar 0], mkApp "f" #[mkConst ("c" ++ toString i)]]; d.insert t i) d; let d := (20:Nat).fold (fun i (d : Trie Nat) => let t := mkApp "f" #[mkApp "g" #[mkConst ("a" ++ toString i)], mkApp "g" #[mkConst "b"]]; d.insert t i) d; -- let t := mkApp "g" [mkApp "h" [mkConst "a"]]; -- let d := d.insert t 10; IO.println (format d) #eval tst1 def check (as bs : Array Nat) : IO Unit := let as := as.qsort (fun a b => a < b); let bs := bs.qsort (fun a b => a < b); unless (as == bs) $ throw $ IO.userError "check failed" def tst2 : IO Unit := do let d := @Trie.empty Nat; let d := d.insert (mkApp "f" #[mkVar 0, mkConst "a"]) 1; -- f * a let d := d.insert (mkApp "f" #[mkConst "b", mkVar 0]) 2; -- f b * let d := d.insert (mkApp "f" #[mkVar 0, mkVar 0]) 3; -- f * * let d := d.insert (mkApp "f" #[mkVar 0, mkConst "b"]) 4; -- f * b let d := d.insert (mkApp "f" #[mkApp "h" #[mkVar 0], mkConst "b"]) 5; -- f (h *) b let d := d.insert (mkApp "f" #[mkApp "h" #[mkConst "a"], mkConst "b"]) 6; -- f (h a) b let d := d.insert (mkApp "f" #[mkApp "h" #[mkConst "a"], mkVar 1]) 7; -- f (h a) * let d := d.insert (mkApp "f" #[mkApp "h" #[mkConst "a"], mkVar 0]) 8; -- f (h a) * let d := d.insert (mkApp "f" #[mkApp "h" #[mkVar 0], mkApp "h" #[mkConst "b"]]) 9; -- f (h *) (h b) let d := d.insert (mkApp "g" #[mkVar 0, mkConst "a"]) 10; -- g * a let d := d.insert (mkApp "g" #[mkConst "b", mkVar 0]) 11; -- g b * let d := d.insert (mkApp "g" #[mkVar 0, mkVar 0]) 12; -- g * * let d := d.insert (mkApp "g" #[mkApp "h" #[mkConst "a"], mkConst "b"]) 13; -- g (h a) b let d := d.insert (mkApp "g" #[mkApp "h" #[mkConst "a"], mkVar 1]) 14; -- g (h a) * IO.println (format d); let vs := d.getMatch (mkApp "f" #[mkApp "h" #[mkConst "a"], mkApp "h" #[mkConst "b"]]); -- f (h a) (h b) check vs #[3, 7, 8, 9]; let vs := d.getMatch (mkApp "f" #[mkConst "b", mkConst "a"]); -- f a b check vs #[1, 2, 3]; let vs := d.getMatch (mkApp "g" #[mkConst "b", mkConst "b"]); -- g b b check vs #[11, 12]; let vs := d.getUnify (mkApp "f" #[mkApp "h" #[mkVar 0], mkApp "h" #[mkVar 0]]); -- f (h *) (h *) check vs #[3, 7, 8, 9]; let vs := d.getUnify (mkApp "f" #[mkApp "h" #[mkVar 0], mkVar 0]); -- f (h *) * check vs #[1, 3, 4, 5, 6, 7, 8, 9]; let vs := d.getUnify (mkApp "f" #[mkApp "h" #[mkConst "b"], mkVar 0]); -- f (h b) * check vs #[1, 3, 4, 5, 9]; let vs := d.getUnify (mkVar 0); -- * check vs (List.iota 14).toArray; let vs := d.getUnify (mkApp "g" #[mkVar 0, mkConst "b"]); -- g * b check vs #[11, 12, 13, 14]; let vs := d.getUnify (mkApp "g" #[mkApp "h" #[mkVar 0], mkConst "b"]); -- g (h *) b check vs #[12, 13, 14]; let vs := d.getUnify (mkApp "g" #[mkApp "h" #[mkConst "b"], mkVar 0]); -- g (h b) * check vs #[10, 12]; pure () #eval tst2
3f10a4770767bee9348900323875ff110dc79212
80746c6dba6a866de5431094bf9f8f841b043d77
/src/data/finmap.lean
b046f05e139914fdbb1774e67a65e68638610cda
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
7,731
lean
/- Copyright (c) 2018 Sean Leather. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sean Leather, Mario Carneiro Finite maps over `multiset`. -/ import data.list.alist data.finset data.pfun universes u v w open list namespace multiset variables {α : Type*} {β : α → Type*} /-- `nodupkeys s` means that `s` has no duplicate keys. -/ def nodupkeys (s : multiset (sigma β)) : Prop := quot.lift_on s list.nodupkeys (λ s t p, propext $ perm_nodupkeys p) @[simp] theorem coe_nodupkeys {l : list (sigma β)} : @nodupkeys α β l ↔ l.nodupkeys := iff.rfl end multiset /-- `finmap α β` is the type of finite maps over a multiset. It is effectively a quotient of `alist α β` by permutation of the underlying list. -/ structure finmap (α : Type u) (β : α → Type v) : Type (max u v) := (entries : multiset (sigma β)) (nodupkeys : entries.nodupkeys) /-- The quotient map from `alist` to `finmap`. -/ def alist.to_finmap {α β} (s : alist α β) : finmap α β := ⟨s.entries, s.nodupkeys⟩ local notation `⟦`:max a `⟧`:0 := alist.to_finmap a theorem alist.to_finmap_eq {α β} {s₁ s₂ : alist α β} : ⟦s₁⟧ = ⟦s₂⟧ ↔ s₁.entries ~ s₂.entries := by cases s₁; cases s₂; simp [alist.to_finmap] @[simp] theorem alist.to_finmap_entries {α β} (s : alist α β) : ⟦s⟧.entries = s.entries := rfl namespace finmap variables {α : Type u} {β : α → Type v} open alist /-- Lift a permutation-respecting function on `alist` to `finmap`. -/ @[elab_as_eliminator] def lift_on {γ} (s : finmap α β) (f : alist α β → γ) (H : ∀ a b : alist α β, a.entries ~ b.entries → f a = f b) : γ := begin refine (quotient.lift_on s.1 (λ l, (⟨_, λ nd, f ⟨l, nd⟩⟩ : roption γ)) (λ l₁ l₂ p, roption.ext' (perm_nodupkeys p) _) : roption γ).get _, { exact λ h₁ h₂, H _ _ (by exact p) }, { have := s.nodupkeys, rcases s.entries with ⟨l⟩, exact id } end @[simp] theorem lift_on_to_finmap {γ} (s : alist α β) (f : alist α β → γ) (H) : lift_on ⟦s⟧ f H = f s := by cases s; refl @[elab_as_eliminator] theorem induction_on {C : finmap α β → Prop} (s : finmap α β) (H : ∀ (a : alist α β), C ⟦a⟧) : C s := by rcases s with ⟨⟨a⟩, h⟩; exact H ⟨a, h⟩ @[extensionality] theorem ext : ∀ {s t : finmap α β}, s.entries = t.entries → s = t | ⟨l₁, h₁⟩ ⟨l₂, h₂⟩ H := by congr' /-- The predicate `a ∈ s` means that `s` has a value associated to the key `a`. -/ instance : has_mem α (finmap α β) := ⟨λ a s, ∃ b : β a, sigma.mk a b ∈ s.entries⟩ theorem mem_def {a : α} {s : finmap α β} : a ∈ s ↔ ∃ b : β a, sigma.mk a b ∈ s.entries := iff.rfl @[simp] theorem mem_to_finmap {a : α} {s : alist α β} : a ∈ ⟦s⟧ ↔ a ∈ s := iff.rfl /-- The set of keys of a finite map. -/ def keys (s : finmap α β) : finset α := ⟨s.entries.map sigma.fst, induction_on s $ λ s, s.keys_nodup⟩ @[simp] theorem keys_val (s : alist α β) : (keys ⟦s⟧).val = s.keys := rfl @[simp] theorem keys_ext {s₁ s₂ : alist α β} : keys ⟦s₁⟧ = keys ⟦s₂⟧ ↔ s₁.keys ~ s₂.keys := by simp [keys, alist.keys] theorem mem_keys {a : α} {s : finmap α β} : a ∈ s.keys ↔ a ∈ s := induction_on s $ λ s, mem_keys /-- The empty map. -/ instance : has_emptyc (finmap α β) := ⟨⟨0, nodupkeys_nil⟩⟩ @[simp] theorem empty_to_finmap (s : alist α β) : (⟦∅⟧ : finmap α β) = ∅ := rfl theorem not_mem_empty_entries {s : sigma β} : s ∉ (∅ : finmap α β).entries := multiset.not_mem_zero _ theorem not_mem_empty {a : α} : a ∉ (∅ : finmap α β) := λ ⟨b, h⟩, not_mem_empty_entries h @[simp] theorem keys_empty : (∅ : finmap α β).keys = ∅ := rfl /-- The singleton map. -/ def singleton (a : α) (b : β a) : finmap α β := ⟨⟨a, b⟩::0, nodupkeys_singleton _⟩ @[simp] theorem keys_singleton (a : α) (b : β a) : (singleton a b).keys = finset.singleton a := rfl variables [decidable_eq α] /-- Look up the value associated to a key in a map. -/ def lookup (a : α) (s : finmap α β) : option (β a) := lift_on s (lookup a) (λ s t, perm_lookup) @[simp] theorem lookup_to_finmap (a : α) (s : alist α β) : lookup a ⟦s⟧ = s.lookup a := rfl theorem lookup_is_some {a : α} {s : finmap α β} : (s.lookup a).is_some ↔ a ∈ s := induction_on s $ λ s, alist.lookup_is_some instance (a : α) (s : finmap α β) : decidable (a ∈ s) := decidable_of_iff _ lookup_is_some /-- Insert a key-value pair into a finite map. If the key is already present it does nothing. -/ def insert (a : α) (b : β a) (s : finmap α β) : finmap α β := lift_on s (λ t, ⟦insert a b t⟧) $ λ s₁ s₂ p, to_finmap_eq.2 $ perm_insert p @[simp] theorem insert_to_finmap (a : α) (b : β a) (s : alist α β) : insert a b ⟦s⟧ = ⟦s.insert a b⟧ := by simp [insert] @[simp] theorem insert_of_pos {a : α} {b : β a} {s : finmap α β} : a ∈ s → insert a b s = s := induction_on s $ λ ⟨s, nd⟩ h, congr_arg to_finmap $ insert_of_pos (mem_to_finmap.2 h) theorem insert_entries_of_neg {a : α} {b : β a} {s : finmap α β} : a ∉ s → (insert a b s).entries = ⟨a, b⟩ :: s.entries := induction_on s $ λ s h, by simp [insert_entries_of_neg (mt mem_to_finmap.1 h)] @[simp] theorem mem_insert {a a' : α} {b : β a} {s : finmap α β} : a' ∈ insert a b s ↔ a' = a ∨ a' ∈ s := induction_on s $ by simp /-- Replace a key with a given value in a finite map. If the key is not present it does nothing. -/ def replace (a : α) (b : β a) (s : finmap α β) : finmap α β := lift_on s (λ t, ⟦replace a b t⟧) $ λ s₁ s₂ p, to_finmap_eq.2 $ perm_replace p @[simp] theorem replace_to_finmap (a : α) (b : β a) (s : alist α β) : replace a b ⟦s⟧ = ⟦s.replace a b⟧ := by simp [replace] @[simp] theorem keys_replace (a : α) (b : β a) (s : finmap α β) : (replace a b s).keys = s.keys := induction_on s $ λ s, by simp @[simp] theorem mem_replace {a a' : α} {b : β a} {s : finmap α β} : a' ∈ replace a b s ↔ a' ∈ s := induction_on s $ λ s, by simp /-- Fold a commutative function over the key-value pairs in the map -/ def foldl {δ : Type w} (f : δ → Π a, β a → δ) (H : ∀ d a₁ b₁ a₂ b₂, f (f d a₁ b₁) a₂ b₂ = f (f d a₂ b₂) a₁ b₁) (d : δ) (m : finmap α β) : δ := m.entries.foldl (λ d s, f d s.1 s.2) (λ d s t, H _ _ _ _ _) d /-- Erase a key from the map. If the key is not present it does nothing. -/ def erase (a : α) (s : finmap α β) : finmap α β := lift_on s (λ t, ⟦erase a t⟧) $ λ s₁ s₂ p, to_finmap_eq.2 $ perm_erase p @[simp] theorem erase_to_finmap (a : α) (s : alist α β) : erase a ⟦s⟧ = ⟦s.erase a⟧ := by simp [erase] @[simp] theorem keys_erase_to_finset (a : α) (s : alist α β) : keys ⟦s.erase a⟧ = (keys ⟦s⟧).erase a := by simp [finset.erase, keys, alist.erase, list.kerase_map_fst] @[simp] theorem keys_erase (a : α) (s : finmap α β) : (erase a s).keys = s.keys.erase a := induction_on s $ λ s, by simp @[simp] theorem mem_erase {a a' : α} {s : finmap α β} : a' ∈ erase a s ↔ a' ≠ a ∧ a' ∈ s := induction_on s $ λ s, by simp /-- Erase a key from the map, and return the corresponding value, if found. -/ def extract (a : α) (s : finmap α β) : option (β a) × finmap α β := lift_on s (λ t, prod.map id to_finmap (extract a t)) $ λ s₁ s₂ p, by simp [perm_lookup p, to_finmap_eq, perm_erase p] @[simp] theorem extract_eq_lookup_erase (a : α) (s : finmap α β) : extract a s = (lookup a s, erase a s) := induction_on s $ λ s, by simp [extract] end finmap
11d40be95f81a6fed56ae8c10c160afb20f2a572
8e6cad62ec62c6c348e5faaa3c3f2079012bdd69
/src/data/polynomial/basic.lean
bd44ae8ebbcb5934416f303a0f2494f58fcdbd14
[ "Apache-2.0" ]
permissive
benjamindavidson/mathlib
8cc81c865aa8e7cf4462245f58d35ae9a56b150d
fad44b9f670670d87c8e25ff9cdf63af87ad731e
refs/heads/master
1,679,545,578,362
1,615,343,014,000
1,615,343,014,000
312,926,983
0
0
Apache-2.0
1,615,360,301,000
1,605,399,418,000
Lean
UTF-8
Lean
false
false
7,665
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import tactic.ring_exp import tactic.chain import algebra.monoid_algebra import data.finset.sort /-! # Theory of univariate polynomials Polynomials are represented as `add_monoid_algebra R ℕ`, where `R` is a commutative semiring. In this file, we define `polynomial`, provide basic instances, and prove an `ext` lemma. -/ noncomputable theory /-- `polynomial R` is the type of univariate polynomials over `R`. Polynomials should be seen as (semi-)rings with the additional constructor `X`. The embedding from `R` is called `C`. -/ def polynomial (R : Type*) [semiring R] := add_monoid_algebra R ℕ open finsupp add_monoid_algebra open_locale big_operators namespace polynomial universes u variables {R : Type u} {a : R} {m n : ℕ} section semiring variables [semiring R] {p q : polynomial R} instance : inhabited (polynomial R) := add_monoid_algebra.inhabited _ _ instance : semiring (polynomial R) := add_monoid_algebra.semiring instance {S} [semiring S] [semimodule S R] : semimodule S (polynomial R) := add_monoid_algebra.semimodule instance {S₁ S₂} [semiring S₁] [semiring S₂] [semimodule S₁ R] [semimodule S₂ R] [smul_comm_class S₁ S₂ R] : smul_comm_class S₁ S₂ (polynomial R) := add_monoid_algebra.smul_comm_class instance {S₁ S₂} [has_scalar S₁ S₂] [semiring S₁] [semiring S₂] [semimodule S₁ R] [semimodule S₂ R] [is_scalar_tower S₁ S₂ R] : is_scalar_tower S₁ S₂ (polynomial R) := add_monoid_algebra.is_scalar_tower instance [subsingleton R] : unique (polynomial R) := add_monoid_algebra.unique @[simp] lemma support_zero : (0 : polynomial R).support = ∅ := rfl /-- `monomial s a` is the monomial `a * X^s` -/ def monomial (n : ℕ) : R →ₗ[R] polynomial R := finsupp.lsingle n lemma monomial_zero_right (n : ℕ) : monomial n (0 : R) = 0 := finsupp.single_zero lemma monomial_def (n : ℕ) (a : R) : monomial n a = finsupp.single n a := rfl lemma monomial_add (n : ℕ) (r s : R) : monomial n (r + s) = monomial n r + monomial n s := finsupp.single_add lemma monomial_mul_monomial (n m : ℕ) (r s : R) : monomial n r * monomial m s = monomial (n + m) (r * s) := add_monoid_algebra.single_mul_single lemma smul_monomial {S} [semiring S] [semimodule S R] (a : S) (n : ℕ) (b : R) : a • monomial n b = monomial n (a • b) := finsupp.smul_single _ _ _ /-- `X` is the polynomial variable (aka indeterminant). -/ def X : polynomial R := monomial 1 1 /-- `X` commutes with everything, even when the coefficients are noncommutative. -/ lemma X_mul : X * p = p * X := by { ext, simp [X, monomial, add_monoid_algebra.mul_apply, sum_single_index, add_comm] } lemma X_pow_mul {n : ℕ} : X^n * p = p * X^n := begin induction n with n ih, { simp, }, { conv_lhs { rw pow_succ', }, rw [mul_assoc, X_mul, ←mul_assoc, ih, mul_assoc, ←pow_succ'], } end lemma X_pow_mul_assoc {n : ℕ} : (p * X^n) * q = (p * q) * X^n := by rw [mul_assoc, X_pow_mul, ←mul_assoc] lemma commute_X (p : polynomial R) : commute X p := X_mul /-- coeff p n is the coefficient of X^n in p -/ def coeff (p : polynomial R) : ℕ → R := @coe_fn (ℕ →₀ R) _ p @[simp] lemma coeff_mk (s) (f) (h) : coeff (finsupp.mk s f h : polynomial R) = f := rfl lemma coeff_monomial : coeff (monomial n a) m = if n = m then a else 0 := by { dsimp [monomial, coeff], rw finsupp.single_apply, congr } @[simp] lemma coeff_zero (n : ℕ) : coeff (0 : polynomial R) n = 0 := rfl @[simp] lemma coeff_one_zero : coeff (1 : polynomial R) 0 = 1 := coeff_monomial @[simp] lemma coeff_X_one : coeff (X : polynomial R) 1 = 1 := coeff_monomial @[simp] lemma coeff_X_zero : coeff (X : polynomial R) 0 = 0 := coeff_monomial @[simp] lemma coeff_monomial_succ : coeff (monomial (n+1) a) 0 = 0 := by simp [coeff_monomial] lemma coeff_X : coeff (X : polynomial R) n = if 1 = n then 1 else 0 := coeff_monomial lemma coeff_X_of_ne_one {n : ℕ} (hn : n ≠ 1) : coeff (X : polynomial R) n = 0 := by rw [coeff_X, if_neg hn.symm] theorem ext_iff {p q : polynomial R} : p = q ↔ ∀ n, coeff p n = coeff q n := finsupp.ext_iff @[ext] lemma ext {p q : polynomial R} : (∀ n, coeff p n = coeff q n) → p = q := finsupp.ext @[ext] lemma add_hom_ext' {M : Type*} [add_monoid M] {f g : polynomial R →+ M} (h : ∀ n, f.comp (monomial n).to_add_monoid_hom = g.comp (monomial n).to_add_monoid_hom) : f = g := finsupp.add_hom_ext' h lemma add_hom_ext {M : Type*} [add_monoid M] {f g : polynomial R →+ M} (h : ∀ n a, f (monomial n a) = g (monomial n a)) : f = g := finsupp.add_hom_ext h @[ext] lemma lhom_ext' {M : Type*} [add_comm_monoid M] [semimodule R M] {f g : polynomial R →ₗ[R] M} (h : ∀ n, f.comp (monomial n) = g.comp (monomial n)) : f = g := finsupp.lhom_ext' h -- this has the same content as the subsingleton lemma eq_zero_of_eq_zero (h : (0 : R) = (1 : R)) (p : polynomial R) : p = 0 := by rw [←one_smul R p, ←h, zero_smul] lemma support_monomial (n) (a : R) (H : a ≠ 0) : (monomial n a).support = singleton n := finsupp.support_single_ne_zero H lemma support_monomial' (n) (a : R) : (monomial n a).support ⊆ singleton n := finsupp.support_single_subset lemma X_pow_eq_monomial (n) : X ^ n = monomial n (1:R) := begin induction n with n hn, { refl, }, { rw [pow_succ', hn, X, monomial_mul_monomial, one_mul] }, end lemma support_X_pow (H : ¬ (1:R) = 0) (n : ℕ) : (X^n : polynomial R).support = singleton n := begin convert support_monomial n 1 H, exact X_pow_eq_monomial n, end lemma support_X_empty (H : (1:R)=0) : (X : polynomial R).support = ∅ := begin rw [X, H, monomial_zero_right, support_zero], end lemma support_X (H : ¬ (1 : R) = 0) : (X : polynomial R).support = singleton 1 := begin rw [← pow_one X, support_X_pow H 1], end lemma monomial_left_inj {R : Type*} [semiring R] {a : R} (ha : a ≠ 0) {i j : ℕ} : (monomial i a) = (monomial j a) ↔ i = j := finsupp.single_left_inj ha end semiring section comm_semiring variables [comm_semiring R] instance : comm_semiring (polynomial R) := add_monoid_algebra.comm_semiring end comm_semiring section ring variables [ring R] instance : ring (polynomial R) := add_monoid_algebra.ring @[simp] lemma coeff_neg (p : polynomial R) (n : ℕ) : coeff (-p) n = -coeff p n := rfl @[simp] lemma coeff_sub (p q : polynomial R) (n : ℕ) : coeff (p - q) n = coeff p n - coeff q n := rfl @[simp] lemma monomial_neg (n : ℕ) (a : R) : monomial n (-a) = -(monomial n a) := by rw [eq_neg_iff_add_eq_zero, ←monomial_add, neg_add_self, monomial_zero_right] end ring instance [comm_ring R] : comm_ring (polynomial R) := add_monoid_algebra.comm_ring section nonzero_semiring variables [semiring R] [nontrivial R] instance : nontrivial (polynomial R) := add_monoid_algebra.nontrivial lemma X_ne_zero : (X : polynomial R) ≠ 0 := mt (congr_arg (λ p, coeff p 1)) (by simp) end nonzero_semiring section repr variables [semiring R] local attribute [instance, priority 100] classical.prop_decidable instance [has_repr R] : has_repr (polynomial R) := ⟨λ p, if p = 0 then "0" else (p.support.sort (≤)).foldr (λ n a, a ++ (if a = "" then "" else " + ") ++ if n = 0 then "C (" ++ repr (coeff p n) ++ ")" else if n = 1 then if (coeff p n) = 1 then "X" else "C (" ++ repr (coeff p n) ++ ") * X" else if (coeff p n) = 1 then "X ^ " ++ repr n else "C (" ++ repr (coeff p n) ++ ") * X ^ " ++ repr n) ""⟩ end repr end polynomial
49b6c361bef4ed950b3b3a4bde6b5fd77126ef2d
4767244035cdd124e1ce3d0c81128f8929df6163
/data/rat.lean
cf16aa80cd60dc091365e5409108ef71ba211767
[ "Apache-2.0" ]
permissive
5HT/mathlib
b941fecacd31a9c5dd0abad58770084b8a1e56b1
40fa9ade2f5649569639608db5e621e5fad0cc02
refs/heads/master
1,586,978,681,358
1,546,681,764,000
1,546,681,764,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
44,330
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro Introduces the rational numbers as discrete, linear ordered field. -/ import data.nat.gcd data.pnat data.int.sqrt data.equiv.encodable order.basic algebra.ordered_field data.real.cau_seq /- rational numbers -/ /-- `rat`, or `ℚ`, is the type of rational numbers. It is defined as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and `d` are coprime. This representation is preferred to the quotient because without periodic reduction, the numerator and denominator can grow exponentially (for example, adding 1/2 to itself repeatedly). -/ structure rat := mk' :: (num : ℤ) (denom : ℕ) (pos : denom > 0) (cop : num.nat_abs.coprime denom) notation `ℚ` := rat namespace rat protected def repr : ℚ → string | ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else _root_.repr n ++ "/" ++ _root_.repr d instance : has_repr ℚ := ⟨rat.repr⟩ instance : has_to_string ℚ := ⟨rat.repr⟩ meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩ instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // d > 0 ∧ n.nat_abs.coprime d}) ⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩ /-- Embed an integer as a rational number -/ def of_int (n : ℤ) : ℚ := ⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩ instance : has_zero ℚ := ⟨of_int 0⟩ instance : has_one ℚ := ⟨of_int 1⟩ instance : inhabited ℚ := ⟨0⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/ def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ := let n' := n.nat_abs, g := n'.gcd d in ⟨n / g, d / g, begin apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2, simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _) end, begin have : int.nat_abs (n / ↑g) = n' / g, { cases int.nat_abs_eq n with e e; rw e, { refl }, rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl }, exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) }, rw this, exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos) end⟩ /-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we define `n / 0 = 0` by convention. -/ def mk_nat (n : ℤ) (d : ℕ) : ℚ := if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩ /-- Form the quotient `n / d` where `n d : ℤ`. -/ def mk : ℤ → ℤ → ℚ | n (int.of_nat d) := mk_nat n d | n -[1+ d] := mk_pnat (-n) d.succ_pnat local infix ` /. `:70 := mk theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d := by change n /. d with dite _ _ _; simp [ne_of_gt h] theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl @[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl @[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 := by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl @[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 := by by_cases n = 0; simp [*, mk_nat] @[simp] theorem zero_mk (n) : 0 /. n = 0 := by cases n; simp [mk] private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a := int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b @[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 := begin constructor; intro h; [skip, {subst a, simp}], have : ∀ {a b}, mk_pnat a b = 0 → a = 0, { intros a b e, cases b with b h, injection e with e, apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e }, cases b with b; simp [mk, mk_nat] at h, { simp [mt (congr_arg int.of_nat) b0] at h, exact this h }, { apply neg_inj, simp [this h] } end theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0), a /. b = c /. d ↔ a * d = c * b := suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b, begin intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hb], all_goals { cases d with d d; simp [mk, mk_nat, nat.succ_pnat], simp [mt (congr_arg int.of_nat) hd], all_goals { rw this, try {refl} } }, { change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b, constructor; intro h; apply neg_inj; simpa [left_distrib, neg_add_eq_iff_eq_add, eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h }, { change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ, constructor; intro h; apply neg_inj; simpa [left_distrib, eq_comm] using h }, { change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ, simp [left_distrib] } end, begin intros, simp [mk_pnat], constructor; intro h, { cases h with ha hb, have ha, { have dv := @gcd_abs_dvd_left, have := int.eq_mul_of_div_eq_right dv ha, rw ← int.mul_div_assoc _ dv at this, exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have hb, { have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b, have := nat.eq_mul_of_div_eq_right dv hb, rw ← nat.mul_div_assoc _ dv at this, exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm }, have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0, { refine int.coe_nat_ne_zero.2 (ne_of_gt _), apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption }, apply eq_of_mul_eq_mul_right m0, simpa [mul_comm, mul_left_comm] using congr (congr_arg (*) ha.symm) (congr_arg coe hb) }, { suffices : ∀ a c, a * d = c * b → a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d, { cases this a.nat_abs c.nat_abs (by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂, have hs := congr_arg int.sign h, simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb), int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs, conv in a { rw ← int.sign_mul_nat_abs a }, conv in c { rw ← int.sign_mul_nat_abs c }, rw [int.mul_div_assoc, int.mul_div_assoc], exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩, all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } }, intros a c h, suffices bd : b / a.gcd b = d / c.gcd d, { refine ⟨_, bd⟩, apply nat.eq_of_mul_eq_mul_left hb, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd, ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm, nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] }, suffices : ∀ {a c : ℕ} (b>0) (d>0), a * d = c * b → b / a.gcd b ≤ d / c.gcd d, { exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) }, intros a c b hb d hd h, have gb0 := nat.gcd_pos_of_pos_right a hb, have gd0 := nat.gcd_pos_of_pos_right c hd, apply nat.le_of_dvd, apply (nat.le_div_iff_mul_le _ _ gd0).2, simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _), apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left, refine ⟨c / c.gcd d, _⟩, rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), ← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)], apply congr_arg (/ c.gcd d), rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] } end @[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) : (a * c) /. (b * c) = a /. b := begin by_cases b0 : b = 0, { subst b0, simp }, apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc] end theorem num_denom : ∀ a : ℚ, a = a.num /. a.denom | ⟨n, d, h, (c:_=1)⟩ := show _ = mk_nat n d, by simp [mk_nat, ne_of_gt h, mk_pnat, c] theorem num_denom' (n d h c) : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom _ @[elab_as_eliminator] theorem {u} num_denom_cases_on {C : ℚ → Sort u} : ∀ (a : ℚ) (H : ∀ n d, d > 0 → (int.nat_abs n).coprime d → C (n /. d)), C a | ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c @[elab_as_eliminator] theorem {u} num_denom_cases_on' {C : ℚ → Sort u} (a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a := num_denom_cases_on a $ λ n d h c, H n d $ ne_of_gt h theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a := begin cases e : a /. b with n d h c, rw [rat.num_denom', rat.mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.dvd_of_dvd_mul_right _), have := congr_arg int.nat_abs e, simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this] end theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b := begin by_cases b0 : b = 0, {simp [b0]}, cases e : a /. b with n d h c, rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e, refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _), rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp end protected def add : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_add ℚ := ⟨rat.add⟩ theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ) (fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂}, f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂) (f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0) (a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0) (H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d), f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) : f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc, rw fv, have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁), have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂), exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc)) end @[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b + c /. d = (a * d + c * b) /. (b * d) := begin apply lift_binop_eq rat.add; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, calc (n₁ * d₂ + n₂ * d₁) * (b * d) = (n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm] ... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂] ... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm] end protected def neg : ℚ → ℚ | ⟨n, d, h, c⟩ := ⟨-n, d, h, by simp [c]⟩ instance : has_neg ℚ := ⟨rat.neg⟩ @[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b := begin by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, show rat.mk' _ _ _ _ = _, rw num_denom', have d0 := ne_of_gt (int.coe_nat_lt.2 h₁), apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha, simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁] end protected def mul : ℚ → ℚ → ℚ | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩ instance : has_mul ℚ := ⟨rat.mul⟩ @[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : (a /. b) * (c /. d) = (a * c) /. (b * d) := begin apply lift_binop_eq rat.mul; intros; try {assumption}, { apply mk_pnat_eq }, { apply mul_ne_zero d₁0 d₂0 }, cc end protected def inv : ℚ → ℚ | ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩ | ⟨0, d, h, c⟩ := 0 | ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩ instance : has_inv ℚ := ⟨rat.inv⟩ @[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a := begin by_cases a0 : a = 0, { subst a0, simp, refl }, by_cases b0 : b = 0, { subst b0, simp, refl }, generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha, refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _, { cases n with n; [cases n with n, skip], { refl }, { change int.of_nat n.succ with (n+1:ℕ), unfold rat.inv, rw num_denom' }, { unfold rat.inv, rw num_denom', refl } }, have n0 : n ≠ 0, { refine mt (λ (n0 : n = 0), _) a0, subst n0, simp at ha, exact (mk_eq_zero b0).1 ha }, have d0 := ne_of_gt (int.coe_nat_lt.2 h), have ha := (mk_eq b0 d0).1 ha, apply (mk_eq n0 a0).2, cc end variables (a b c : ℚ) protected theorem add_zero : a + 0 = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem zero_add : 0 + a = a := num_denom_cases_on' a $ λ n d h, by rw [← zero_mk d]; simp [h, -zero_mk] protected theorem add_comm : a + b = b + a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂, mul_comm] protected theorem add_assoc : a + b + c = a + (b + c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm] protected theorem add_left_neg : -a + a = 0 := num_denom_cases_on' a $ λ n d h, by simp [h] protected theorem mul_one : a * 1 = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem one_mul : 1 * a = a := num_denom_cases_on' a $ λ n d h, by change (1:ℚ) with 1 /. 1; simp [h] protected theorem mul_comm : a * b = b * a := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, by simp [h₁, h₂, mul_comm] protected theorem mul_assoc : a * b * c = a * (b * c) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm] protected theorem add_mul : (a + b) * c = a * c + b * c := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, num_denom_cases_on' c $ λ n₃ d₃ h₃, by simp [h₁, h₂, h₃, mul_ne_zero]; refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _; simp [mul_add, mul_comm, mul_assoc, mul_left_comm] protected theorem mul_add : a * (b + c) = a * b + a * c := by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a] protected theorem zero_ne_one : 0 ≠ (1:ℚ) := mt (λ (h : 0 = 1 /. 1), (mk_eq_zero one_ne_zero).1 h.symm) one_ne_zero protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 := num_denom_cases_on' a $ λ n d h a0, have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0, by simp [h, n0, mul_comm]; exact eq.trans (by simp) (@div_mk_div_cancel_left 1 1 _ n0) protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 := eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h) instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance instance : discrete_field ℚ := { zero := 0, add := rat.add, neg := rat.neg, one := 1, mul := rat.mul, inv := rat.inv, zero_add := rat.zero_add, add_zero := rat.add_zero, add_comm := rat.add_comm, add_assoc := rat.add_assoc, add_left_neg := rat.add_left_neg, mul_one := rat.mul_one, one_mul := rat.one_mul, mul_comm := rat.mul_comm, mul_assoc := rat.mul_assoc, left_distrib := rat.mul_add, right_distrib := rat.add_mul, zero_ne_one := rat.zero_ne_one, mul_inv_cancel := rat.mul_inv_cancel, inv_mul_cancel := rat.inv_mul_cancel, has_decidable_eq := rat.decidable_eq, inv_zero := rfl } /- Extra instances to short-circuit type class resolution -/ instance : field ℚ := by apply_instance instance : division_ring ℚ := by apply_instance instance : integral_domain ℚ := by apply_instance -- TODO(Mario): this instance slows down data.real.basic --instance : domain ℚ := by apply_instance instance : nonzero_comm_ring ℚ := by apply_instance instance : comm_ring ℚ := by apply_instance --instance : ring ℚ := by apply_instance instance : comm_semiring ℚ := by apply_instance instance : semiring ℚ := by apply_instance instance : add_comm_group ℚ := by apply_instance instance : add_group ℚ := by apply_instance instance : add_comm_monoid ℚ := by apply_instance instance : add_monoid ℚ := by apply_instance instance : add_left_cancel_semigroup ℚ := by apply_instance instance : add_right_cancel_semigroup ℚ := by apply_instance instance : add_comm_semigroup ℚ := by apply_instance instance : add_semigroup ℚ := by apply_instance instance : comm_monoid ℚ := by apply_instance instance : monoid ℚ := by apply_instance instance : comm_semigroup ℚ := by apply_instance instance : semigroup ℚ := by apply_instance theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) : a /. b - c /. d = (a * d - c * b) /. (b * d) := by simp [b0, d0] protected def nonneg : ℚ → Prop | ⟨n, d, h, c⟩ := n ≥ 0 @[simp] theorem mk_nonneg (a : ℤ) {b : ℤ} (h : b > 0) : (a /. b).nonneg ↔ a ≥ 0 := begin generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha, simp [rat.nonneg], have d0 := int.coe_nat_lt.2 h₁, have := (mk_eq (ne_of_gt h) (ne_of_gt d0)).1 ha, constructor; intro h₂, { apply nonneg_of_mul_nonneg_right _ d0, rw this, exact mul_nonneg h₂ (le_of_lt h) }, { apply nonneg_of_mul_nonneg_right _ h, rw ← this, exact mul_nonneg h₂ (int.coe_zero_le _) }, end protected def nonneg_add {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a + b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : (d₁:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : (d₂:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0], intros n₁0 n₂0, apply add_nonneg; apply mul_nonneg; {assumption <|> apply int.coe_zero_le} end protected def nonneg_mul {a b} : rat.nonneg a → rat.nonneg b → rat.nonneg (a * b) := num_denom_cases_on' a $ λ n₁ d₁ h₁, num_denom_cases_on' b $ λ n₂ d₂ h₂, begin have d₁0 : (d₁:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₁), have d₂0 : (d₂:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h₂), simp [d₁0, d₂0, h₁, h₂, mul_pos d₁0 d₂0], exact mul_nonneg end protected def nonneg_antisymm {a} : rat.nonneg a → rat.nonneg (-a) → a = 0 := num_denom_cases_on' a $ λ n d h, begin have d0 : (d:ℤ) > 0 := int.coe_nat_pos.2 (nat.pos_of_ne_zero h), simp [d0, h], exact λ h₁ h₂, le_antisymm (nonpos_of_neg_nonneg h₂) h₁ end protected def nonneg_total : rat.nonneg a ∨ rat.nonneg (-a) := by cases a with n; exact or.imp_right neg_nonneg_of_nonpos (le_total 0 n) instance decidable_nonneg : decidable (rat.nonneg a) := by cases a; unfold rat.nonneg; apply_instance protected def le (a b : ℚ) := rat.nonneg (b - a) instance : has_le ℚ := ⟨rat.le⟩ instance decidable_le : decidable_rel ((≤) : ℚ → ℚ → Prop) | a b := show decidable (rat.nonneg (b - a)), by apply_instance protected theorem le_def {a b c d : ℤ} (b0 : b > 0) (d0 : d > 0) : a /. b ≤ c /. d ↔ a * d ≤ c * b := show rat.nonneg _ ↔ _, by simpa [ne_of_gt b0, ne_of_gt d0, mul_pos b0 d0, mul_comm] using @sub_nonneg _ _ (b * c) (a * d) protected theorem le_refl : a ≤ a := show rat.nonneg (a - a), by rw sub_self; exact le_refl (0 : ℤ) protected theorem le_total : a ≤ b ∨ b ≤ a := by have := rat.nonneg_total (b - a); rwa neg_sub at this protected theorem le_antisymm {a b : ℚ} (hab : a ≤ b) (hba : b ≤ a) : a = b := by have := eq_neg_of_add_eq_zero (rat.nonneg_antisymm hba $ by simpa); rwa neg_neg at this protected theorem le_trans {a b c : ℚ} (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c := have rat.nonneg (b - a + (c - b)), from rat.nonneg_add hab hbc, by simpa instance : decidable_linear_order ℚ := { le := rat.le, le_refl := rat.le_refl, le_trans := @rat.le_trans, le_antisymm := @rat.le_antisymm, le_total := rat.le_total, decidable_eq := by apply_instance, decidable_le := assume a b, rat.decidable_nonneg (b - a) } /- Extra instances to short-circuit type class resolution -/ instance : has_lt ℚ := by apply_instance instance : lattice.distrib_lattice ℚ := by apply_instance instance : lattice.lattice ℚ := by apply_instance instance : lattice.semilattice_inf ℚ := by apply_instance instance : lattice.semilattice_sup ℚ := by apply_instance instance : lattice.has_inf ℚ := by apply_instance instance : lattice.has_sup ℚ := by apply_instance instance : linear_order ℚ := by apply_instance instance : partial_order ℚ := by apply_instance instance : preorder ℚ := by apply_instance theorem nonneg_iff_zero_le {a} : rat.nonneg a ↔ 0 ≤ a := show rat.nonneg a ↔ rat.nonneg (a - 0), by simp theorem num_nonneg_iff_zero_le : ∀ {a : ℚ}, 0 ≤ a.num ↔ 0 ≤ a | ⟨n, d, h, c⟩ := @nonneg_iff_zero_le ⟨n, d, h, c⟩ theorem mk_le {a b c d : ℤ} (h₁ : b > 0) (h₂ : d > 0) : a /. b ≤ c /. d ↔ a * d ≤ c * b := by conv in (_ ≤ _) { simp only [(≤), rat.le], rw [sub_def (ne_of_gt h₂) (ne_of_gt h₁), mk_nonneg _ (mul_pos h₂ h₁), ge, sub_nonneg] } protected theorem add_le_add_left {a b c : ℚ} : c + a ≤ c + b ↔ a ≤ b := by unfold has_le.le rat.le; rw add_sub_add_left_eq_sub protected theorem mul_nonneg {a b : ℚ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a * b := by rw ← nonneg_iff_zero_le at ha hb ⊢; exact rat.nonneg_mul ha hb instance : discrete_linear_ordered_field ℚ := { zero_lt_one := dec_trivial, add_le_add_left := assume a b ab c, rat.add_le_add_left.2 ab, add_lt_add_left := assume a b ab c, lt_of_not_ge $ λ ba, not_le_of_lt ab $ rat.add_le_add_left.1 ba, mul_nonneg := @rat.mul_nonneg, mul_pos := assume a b ha hb, lt_of_le_of_ne (rat.mul_nonneg (le_of_lt ha) (le_of_lt hb)) (mul_ne_zero (ne_of_lt ha).symm (ne_of_lt hb).symm).symm, ..rat.discrete_field, ..rat.decidable_linear_order } /- Extra instances to short-circuit type class resolution -/ instance : linear_ordered_field ℚ := by apply_instance instance : decidable_linear_ordered_comm_ring ℚ := by apply_instance instance : linear_ordered_comm_ring ℚ := by apply_instance instance : linear_ordered_ring ℚ := by apply_instance instance : ordered_ring ℚ := by apply_instance instance : decidable_linear_ordered_semiring ℚ := by apply_instance instance : linear_ordered_semiring ℚ := by apply_instance instance : ordered_semiring ℚ := by apply_instance instance : decidable_linear_ordered_comm_group ℚ := by apply_instance instance : ordered_comm_group ℚ := by apply_instance instance : ordered_cancel_comm_monoid ℚ := by apply_instance instance : ordered_comm_monoid ℚ := by apply_instance attribute [irreducible] rat.le theorem num_pos_iff_pos {a : ℚ} : 0 < a.num ↔ 0 < a := lt_iff_lt_of_le_iff_le $ by simpa [(by cases a; refl : (-a).num = -a.num)] using @num_nonneg_iff_zero_le (-a) theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom' _ _ _ _ theorem coe_int_eq_mk : ∀ z : ℤ, ↑z = z /. 1 | (n : ℕ) := show (n:ℚ) = n /. 1, by induction n with n IH n; simp [*, show (1:ℚ) = 1 /. 1, from rfl] | -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin induction n with n IH, {refl}, show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1, rw [neg_add, IH], simpa [show -1 = (-1) /. 1, from rfl] end theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z := (coe_int_eq_mk z).trans (of_int_eq_mk z).symm theorem mk_eq_div (n d : ℤ) : n /. d = (n / d : ℚ) := begin by_cases d0 : d = 0, {simp [d0, div_zero]}, rw [division_def, coe_int_eq_mk, coe_int_eq_mk, inv_def, mul_def one_ne_zero d0, one_mul, mul_one] end /-- `floor q` is the largest integer `z` such that `z ≤ q` -/ def floor : ℚ → ℤ | ⟨n, d, h, c⟩ := n / d theorem le_floor {z : ℤ} : ∀ {r : ℚ}, z ≤ floor r ↔ (z : ℚ) ≤ r | ⟨n, d, h, c⟩ := begin simp [floor], rw [num_denom'], have h' := int.coe_nat_lt.2 h, conv { to_rhs, rw [coe_int_eq_mk, mk_le zero_lt_one h', mul_one] }, exact int.le_div_iff_mul_le h' end theorem floor_lt {r : ℚ} {z : ℤ} : floor r < z ↔ r < z := lt_iff_lt_of_le_iff_le le_floor theorem floor_le (r : ℚ) : (floor r : ℚ) ≤ r := le_floor.1 (le_refl _) theorem lt_succ_floor (r : ℚ) : r < (floor r).succ := floor_lt.1 $ int.lt_succ_self _ @[simp] theorem floor_coe (z : ℤ) : floor z = z := eq_of_forall_le_iff $ λ a, by rw [le_floor, int.cast_le] theorem floor_mono {a b : ℚ} (h : a ≤ b) : floor a ≤ floor b := le_floor.2 (le_trans (floor_le _) h) @[simp] theorem floor_add_int (r : ℚ) (z : ℤ) : floor (r + z) = floor r + z := eq_of_forall_le_iff $ λ a, by rw [le_floor, ← sub_le_iff_le_add, ← sub_le_iff_le_add, le_floor, int.cast_sub] theorem floor_sub_int (r : ℚ) (z : ℤ) : floor (r - z) = floor r - z := eq.trans (by rw [int.cast_neg]; refl) (floor_add_int _ _) /-- `ceil q` is the smallest integer `z` such that `q ≤ z` -/ def ceil (r : ℚ) : ℤ := -(floor (-r)) theorem ceil_le {z : ℤ} {r : ℚ} : ceil r ≤ z ↔ r ≤ z := by rw [ceil, neg_le, le_floor, int.cast_neg, neg_le_neg_iff] theorem le_ceil (r : ℚ) : r ≤ ceil r := ceil_le.1 (le_refl _) @[simp] theorem ceil_coe (z : ℤ) : ceil z = z := by rw [ceil, ← int.cast_neg, floor_coe, neg_neg] theorem ceil_mono {a b : ℚ} (h : a ≤ b) : ceil a ≤ ceil b := ceil_le.2 (le_trans h (le_ceil _)) @[simp] theorem ceil_add_int (r : ℚ) (z : ℤ) : ceil (r + z) = ceil r + z := by rw [ceil, neg_add', floor_sub_int, neg_sub, sub_eq_neg_add]; refl theorem ceil_sub_int (r : ℚ) (z : ℤ) : ceil (r - z) = ceil r - z := eq.trans (by rw [int.cast_neg]; refl) (ceil_add_int _ _) /- cast (injection into fields) -/ section cast variables {α : Type*} section variables [division_ring α] /-- Construct the canonical injection from `ℚ` into an arbitrary division ring. If the field has positive characteristic `p`, we define `1 / p = 1 / 0 = 0` for consistency with our division by zero convention. -/ protected def cast : ℚ → α | ⟨n, d, h, c⟩ := n / d @[priority 0] instance cast_coe : has_coe ℚ α := ⟨rat.cast⟩ @[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n := show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one] @[simp] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n := by rw [coe_int_eq_of_int, cast_of_int] @[simp] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n := by rw coe_int_eq_of_int; refl @[simp] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 := by rw coe_int_eq_of_int; refl @[simp] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n := by rw [← int.cast_coe_nat, coe_int_num] @[simp] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 := by rw [← int.cast_coe_nat, coe_int_denom] @[simp] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n @[simp] theorem cast_zero : ((0 : ℚ) : α) = 0 := (cast_of_int _).trans int.cast_zero @[simp] theorem cast_one : ((1 : ℚ) : α) = 1 := (cast_of_int _).trans int.cast_one theorem mul_cast_comm (a : α) : ∀ (n : ℚ), (n.denom : α) ≠ 0 → a * n = n * a | ⟨n, d, h, c⟩ h₂ := show a * (n * d⁻¹) = n * d⁻¹ * a, by rw [← mul_assoc, int.mul_cast_comm, mul_assoc, mul_assoc, ← show (d:α)⁻¹ * a = a * d⁻¹, from division_ring.inv_comm_of_comm h₂ (int.mul_cast_comm a d).symm] theorem cast_mk_of_ne_zero (a b : ℤ) (b0 : (b:α) ≠ 0) : (a /. b : α) = a / b := begin have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} }, cases e : a /. b with n d h c, have d0 : (d:α) ≠ 0, { intro d0, have dd := denom_dvd a b, cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke, have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl}, rw [d0, zero_mul] at this, contradiction }, rw [num_denom'] at e, have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e), rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this, symmetry, change (a * b⁻¹ : α) = n / d, rw [eq_div_iff_mul_eq _ _ d0, mul_assoc, nat.mul_cast_comm, ← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one] end theorem cast_add_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', add_def d₁0' d₂0'], suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) + n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹, { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, left_distrib, right_distrib, mul_inv_eq, d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} }, rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul, ← nat.mul_cast_comm], simp [d₁0, mul_assoc] end @[simp] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n | ⟨n, d, h, c⟩ := show (↑-n * d⁻¹ : α) = -(n * d⁻¹), by rw [int.cast_neg, neg_mul_eq_neg_mul] theorem cast_sub_of_ne_zero {m n : ℚ} (m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n := have ((-n).denom : α) ≠ 0, by cases n; exact n0, by simp [m0, this, cast_add_of_ne_zero] theorem cast_mul_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', mul_def d₁0' d₂0'], suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)), { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, mul_inv_eq, d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0, division_ring.mul_ne_zero d₁0 d₂0]} }, rw [division_ring.inv_comm_of_comm d₁0 (nat.mul_cast_comm _ _).symm] end theorem cast_inv_of_ne_zero : ∀ {n : ℚ}, (n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹ | ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl, have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl), rw [num_denom', inv_def], rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div]; simp [n0, d0] end theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0) (nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n := have (n⁻¹.denom : ℤ) ∣ n.num, by conv in n⁻¹.denom { rw [num_denom n, inv_def] }; apply denom_dvd, have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from λ h, let ⟨k, e⟩ := this in by have := congr_arg (coe : ℤ → α) e; rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this, by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def] @[simp] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin refine ⟨λ h, _, congr_arg _⟩, have d₁0 : d₁ ≠ 0 := ne_of_gt h₁, have d₂0 : d₂ ≠ 0 := ne_of_gt h₂, have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0, have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0, rw [num_denom', num_denom'] at h ⊢, rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢, rwa [eq_div_iff_mul_eq _ _ d₂a, division_def, mul_assoc, division_ring.inv_comm_of_comm d₁a (nat.mul_cast_comm _ _), ← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq _ _ d₁a, eq_comm, ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul, int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h end theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α) | m n := cast_inj.1 @[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] @[simp] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero theorem eq_cast_of_ne_zero (f : ℚ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (Hmul : ∀ x y, f (x * y) = f x * f y) : ∀ n : ℚ, (n.denom : α) ≠ 0 → f n = n | ⟨n, d, h, c⟩ := λ (h₂ : ((d:ℤ):α) ≠ 0), show _ = (n / (d:ℤ) : α), begin rw [num_denom', mk_eq_div, eq_div_iff_mul_eq _ _ h₂], have : ∀ n : ℤ, f n = n, { apply int.eq_cast; simp [H1, Hadd] }, rw [← this, ← this, ← Hmul, div_mul_cancel], exact int.cast_ne_zero.2 (int.coe_nat_ne_zero.2 $ ne_of_gt h), end theorem eq_cast [char_zero α] (f : ℚ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) (Hmul : ∀ x y, f (x * y) = f x * f y) (n : ℚ) : f n = n := eq_cast_of_ne_zero _ H1 Hadd Hmul _ $ nat.cast_ne_zero.2 $ ne_of_gt n.pos end theorem cast_mk [discrete_field α] [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b := if b0 : b = 0 then by simp [b0, div_zero] else cast_mk_of_ne_zero a b (int.cast_ne_zero.2 b0) @[simp] theorem cast_add [division_ring α] [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n := cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp] theorem cast_sub [division_ring α] [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n := cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp] theorem cast_mul [division_ring α] [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n := cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp] theorem cast_inv [discrete_field α] [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ := if n0 : n.num = 0 then by simp [show n = 0, by rw [num_denom n, n0]; simp, inv_zero] else cast_inv_of_ne_zero (int.cast_ne_zero.2 n0) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp] theorem cast_div [discrete_field α] [char_zero α] (m n) : ((m / n : ℚ) : α) = m / n := by rw [division_def, cast_mul, cast_inv, division_def] @[simp] theorem cast_pow [discrete_field α] [char_zero α] (q) (k : ℕ) : ((q ^ k : ℚ) : α) = q ^ k := by induction k; simp only [*, cast_one, cast_mul, pow_zero, pow_succ] @[simp] theorem cast_bit0 [division_ring α] [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _ @[simp] theorem cast_bit1 [division_ring α] [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl @[simp] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n | ⟨n, d, h, c⟩ := show 0 ≤ (n * d⁻¹ : α) ↔ 0 ≤ (⟨n, d, h, c⟩ : ℚ), by rw [num_denom', ← nonneg_iff_zero_le, mk_nonneg _ (int.coe_nat_pos.2 h), mul_nonneg_iff_right_nonneg_of_pos (@inv_pos α _ _ (nat.cast_pos.2 h)), int.cast_nonneg] @[simp] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp] theorem cast_id : ∀ n : ℚ, ↑n = n | ⟨n, d, h, c⟩ := show (n / (d : ℤ) : ℚ) = _, by rw [num_denom', mk_eq_div] @[simp] theorem cast_min [discrete_linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp] theorem cast_max [discrete_linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp] theorem cast_abs [discrete_linear_ordered_field α] {q : ℚ} : ((abs q : ℚ) : α) = abs q := by simp [abs] end cast /- nat ceiling -/ /-- `nat_ceil q` is the smallest nonnegative integer `n` with `q ≤ n`. It is the same as `ceil q` when `q ≥ 0`, otherwise it is `0`. -/ def nat_ceil (q : ℚ) : ℕ := int.to_nat (ceil q) theorem nat_ceil_le {q : ℚ} {n : ℕ} : nat_ceil q ≤ n ↔ q ≤ n := by rw [nat_ceil, int.to_nat_le, ceil_le]; refl theorem lt_nat_ceil {q : ℚ} {n : ℕ} : n < nat_ceil q ↔ (n : ℚ) < q := not_iff_not.1 $ by rw [not_lt, not_lt, nat_ceil_le] theorem le_nat_ceil (q : ℚ) : q ≤ nat_ceil q := nat_ceil_le.1 (le_refl _) theorem nat_ceil_mono {q₁ q₂ : ℚ} (h : q₁ ≤ q₂) : nat_ceil q₁ ≤ nat_ceil q₂ := nat_ceil_le.2 (le_trans h (le_nat_ceil _)) @[simp] theorem nat_ceil_coe (n : ℕ) : nat_ceil n = n := show (ceil (n:ℤ)).to_nat = n, by rw [ceil_coe]; refl @[simp] theorem nat_ceil_zero : nat_ceil 0 = 0 := nat_ceil_coe 0 theorem nat_ceil_add_nat {q : ℚ} (hq : 0 ≤ q) (n : ℕ) : nat_ceil (q + n) = nat_ceil q + n := show int.to_nat (ceil (q + (n:ℤ))) = int.to_nat (ceil q) + n, by rw [ceil_add_int]; exact match ceil q, int.eq_coe_of_zero_le (ceil_mono hq) with | _, ⟨m, rfl⟩ := rfl end theorem nat_ceil_lt_add_one {q : ℚ} (hq : q ≥ 0) : ↑(nat_ceil q) < q + 1 := lt_nat_ceil.1 $ by rw [ show nat_ceil (q+1) = nat_ceil q+1, from nat_ceil_add_nat hq 1]; apply nat.lt_succ_self @[simp] lemma denom_neg_eq_denom : ∀ q : ℚ, (-q).denom = q.denom | ⟨_, d, _, _⟩ := rfl @[simp] lemma num_neg_eq_neg_num : ∀ q : ℚ, (-q).num = -(q.num) | ⟨n, _, _, _⟩ := rfl @[simp] lemma num_zero : rat.num 0 = 0 := rfl lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 := have q = q.num /. q.denom, from num_denom _, by simpa [hq] lemma zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 := ⟨λ _, by simp *, zero_of_num_zero⟩ lemma num_ne_zero_of_ne_zero {q : ℚ} (h : q ≠ 0) : q.num ≠ 0 := assume : q.num = 0, h $ zero_of_num_zero this lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 := ne_of_gt q.pos lemma mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 := assume : n = 0, hq $ by simpa [this] using hqnd lemma mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 := assume : d = 0, hq $ by simpa [this] using hqnd lemma mk_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 := assume : n /. d = 0, h $ (mk_eq_zero hd).1 this lemma mul_num_denom (q r : ℚ) : q * r = (q.num * r.num) /. ↑(q.denom * r.denom) := have hq' : (↑q.denom : ℤ) ≠ 0, by have := denom_ne_zero q; simpa, have hr' : (↑r.denom : ℤ) ≠ 0, by have := denom_ne_zero r; simpa, suffices (q.num /. ↑q.denom) * (r.num /. ↑r.denom) = (q.num * r.num) /. ↑(q.denom * r.denom), by rwa [←num_denom q, ←num_denom r] at this, by simp [mul_def hq' hr'] lemma div_num_denom (q r : ℚ) : q / r = (q.num * r.denom) /. (q.denom * r.num) := if hr : r.num = 0 then have hr' : r = 0, from zero_of_num_zero hr, by simp * else calc q / r = q * r⁻¹ : div_eq_mul_inv ... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by rw [←num_denom q, ←num_denom r] ... = (q.num /. q.denom) * (r.denom /. r.num) : by rw inv_def ... = (q.num * r.denom) /. (q.denom * r.num) : mul_def (by simpa using denom_ne_zero q) hr lemma num_denom_mk {q : ℚ} {n d : ℤ} (hn : n ≠ 0) (hd : d ≠ 0) (qdf : q = n /. d) : ∃ c : ℤ, n = c * q.num ∧ d = c * q.denom := have hq : q ≠ 0, from assume : q = 0, hn $ (rat.mk_eq_zero hd).1 (by cc), have q.num /. q.denom = n /. d, by rwa [←rat.num_denom q], have q.num * d = n * ↑(q.denom), from (rat.mk_eq (by simp [rat.denom_ne_zero]) hd).1 this, begin existsi n / q.num, have hqdn : q.num ∣ n, begin rw qdf, apply rat.num_dvd, assumption end, split, { rw int.div_mul_cancel hqdn }, { apply int.eq_mul_div_of_mul_eq_mul_of_dvd_left, {apply rat.num_ne_zero_of_ne_zero hq}, {simp [rat.denom_ne_zero]}, repeat {assumption} } end theorem mk_pnat_num (n : ℤ) (d : ℕ+) : (mk_pnat n d).num = n / nat.gcd n.nat_abs d := by cases d; refl theorem mk_pnat_denom (n : ℤ) (d : ℕ+) : (mk_pnat n d).denom = d / nat.gcd n.nat_abs d := by cases d; refl theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num = (q₁.num * q₂.num) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_denom (q₁ q₂ : ℚ) : (q₁ * q₂).denom = (q₁.denom * q₂.denom) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) := by cases q₁; cases q₂; refl theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num := by rw [mul_num, int.nat_abs_mul, nat.coprime.gcd_eq_one, int.coe_nat_one, int.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) theorem mul_self_denom (q : ℚ) : (q * q).denom = q.denom * q.denom := by rw [rat.mul_denom, int.nat_abs_mul, nat.coprime.gcd_eq_one, nat.div_one]; exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop) theorem abs_def (q : ℚ) : abs q = q.num.nat_abs /. q.denom := begin have hz : (0:ℚ) = 0 /. 1 := rfl, cases le_total q 0 with hq hq, { rw [abs_of_nonpos hq], rw [num_denom q, hz, rat.le_def (int.coe_nat_pos.2 q.pos) zero_lt_one, mul_one, zero_mul] at hq, rw [int.of_nat_nat_abs_of_nonpos hq, ← neg_def, ← num_denom q] }, { rw [abs_of_nonneg hq], rw [num_denom q, hz, rat.le_def zero_lt_one (int.coe_nat_pos.2 q.pos), mul_one, zero_mul] at hq, rw [int.nat_abs_of_nonneg hq, ← num_denom q] } end def sqrt (q : ℚ) : ℚ := rat.mk (int.sqrt q.num) (nat.sqrt q.denom) theorem sqrt_eq (q : ℚ) : rat.sqrt (q*q) = abs q := by rw [sqrt, mul_self_num, mul_self_denom, int.sqrt_eq, nat.sqrt_eq, abs_def] theorem exists_mul_self (x : ℚ) : (∃ q, q * q = x) ↔ rat.sqrt x * rat.sqrt x = x := ⟨λ ⟨n, hn⟩, by rw [← hn, sqrt_eq, abs_mul_abs_self], λ h, ⟨rat.sqrt x, h⟩⟩ theorem sqrt_nonneg (q : ℚ) : 0 ≤ rat.sqrt q := nonneg_iff_zero_le.1 $ (mk_nonneg _ $ int.coe_nat_pos.2 $ nat.pos_of_ne_zero $ λ H, nat.pos_iff_ne_zero.1 q.pos $ nat.sqrt_eq_zero.1 H).2 trivial end rat
9e8e3c88c824cac6c6e30fbfecda5bc7854937f9
618003631150032a5676f229d13a079ac875ff77
/src/init_/data/nat/lemmas.lean
2de5d3bacde42df61ef0d897a170064061d73ce8
[ "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
3,514
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, Jeremy Avigad -/ import algebra.ordered_ring /- Results copied from the core library to mathlib by Johan Commelin -/ namespace nat instance : nonzero ℕ := { zero_ne_one := nat.zero_ne_one } instance : comm_semiring nat := { add := nat.add, add_assoc := nat.add_assoc, zero := nat.zero, zero_add := nat.zero_add, add_zero := nat.add_zero, add_comm := nat.add_comm, mul := nat.mul, mul_assoc := nat.mul_assoc, one := nat.succ nat.zero, one_mul := nat.one_mul, mul_one := nat.mul_one, left_distrib := nat.left_distrib, right_distrib := nat.right_distrib, zero_mul := nat.zero_mul, mul_zero := nat.mul_zero, mul_comm := nat.mul_comm } instance : decidable_linear_ordered_semiring nat := { add_left_cancel := @nat.add_left_cancel, add_right_cancel := @nat.add_right_cancel, lt := nat.lt, add_le_add_left := @nat.add_le_add_left, le_of_add_le_add_left := @nat.le_of_add_le_add_left, zero_lt_one := zero_lt_succ 0, mul_lt_mul_of_pos_left := @nat.mul_lt_mul_of_pos_left, mul_lt_mul_of_pos_right := @nat.mul_lt_mul_of_pos_right, decidable_eq := nat.decidable_eq, ..nat.comm_semiring, ..nat.decidable_linear_order } -- all the fields are already included in the decidable_linear_ordered_semiring instance instance : decidable_linear_ordered_cancel_add_comm_monoid ℕ := { add_left_cancel := @nat.add_left_cancel, ..nat.decidable_linear_ordered_semiring } /- Extra instances to short-circuit type class resolution -/ instance : add_comm_monoid nat := by apply_instance instance : add_monoid nat := by apply_instance instance : monoid nat := by apply_instance instance : comm_monoid nat := by apply_instance instance : comm_semigroup nat := by apply_instance instance : semigroup nat := by apply_instance instance : add_comm_semigroup nat := by apply_instance instance : add_semigroup nat := by apply_instance instance : distrib nat := by apply_instance instance : semiring nat := by apply_instance instance : ordered_semiring nat := by apply_instance theorem mul_self_le_mul_self {n m : ℕ} (h : n ≤ m) : n * n ≤ m * m := mul_le_mul h h (zero_le _) (zero_le _) theorem mul_self_lt_mul_self : Π {n m : ℕ}, n < m → n * n < m * m | 0 m h := mul_pos h h | (succ n) m h := mul_lt_mul h (le_of_lt h) (succ_pos _) (zero_le _) theorem mul_self_le_mul_self_iff {n m : ℕ} : n ≤ m ↔ n * n ≤ m * m := ⟨mul_self_le_mul_self, λh, decidable.by_contradiction $ λhn, not_lt_of_ge h $ mul_self_lt_mul_self $ lt_of_not_ge hn⟩ theorem mul_self_lt_mul_self_iff {n m : ℕ} : n < m ↔ n * n < m * m := iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff mul_self_le_mul_self_iff) $ iff.symm (lt_iff_not_ge _ _) theorem le_mul_self : Π (n : ℕ), n ≤ n * n | 0 := le_refl _ | (n+1) := let t := mul_le_mul_left (n+1) (succ_pos n) in by simp at t; exact t theorem eq_of_mul_eq_mul_right {n m k : ℕ} (Hm : m > 0) (H : n * m = k * m) : n = k := by rw [mul_comm n m, mul_comm k m] at H; exact eq_of_mul_eq_mul_left Hm H theorem one_add (n : ℕ) : 1 + n = succ n := by simp [add_comm] end nat
8e959adf77806f760851f659ed03ff6662dd7879
bb31430994044506fa42fd667e2d556327e18dfe
/src/measure_theory/integral/circle_transform.lean
1356aa0a5464c09730400cc241fde12b78946846
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
7,857
lean
/- Copyright (c) 2022 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck -/ import data.complex.basic import measure_theory.integral.circle_integral /-! # Circle integral transform In this file we define the circle integral transform of a function `f` with complex domain. This is defined as $(2πi)^{-1}\frac{f(x)}{x-w}$ where `x` moves along a circle. We then prove some basic facts about these functions. These results are useful for proving that the uniform limit of a sequence of holomorphic functions is holomorphic. -/ open set measure_theory metric filter function open_locale interval real noncomputable theory variables {E : Type} [normed_add_comm_group E] [normed_space ℂ E] (R : ℝ) (z w : ℂ) namespace complex /-- Given a function `f : ℂ → E`, `circle_transform R z w f` is the functions mapping `θ` to `(2 * ↑π * I)⁻¹ • deriv (circle_map z R) θ • ((circle_map z R θ) - w)⁻¹ • f (circle_map z R θ)`. If `f` is differentiable and `w` is in the interior of the ball, then the integral from `0` to `2 * π` of this gives the value `f(w)`. -/ def circle_transform (f : ℂ → E) (θ : ℝ) : E := (2 * ↑π * I)⁻¹ • deriv (circle_map z R) θ • ((circle_map z R θ) - w)⁻¹ • f (circle_map z R θ) /-- The derivative of `circle_transform` w.r.t `w`.-/ def circle_transform_deriv (f : ℂ → E) (θ : ℝ) : E := (2 * ↑π * I)⁻¹ • deriv (circle_map z R) θ • ((circle_map z R θ - w) ^ 2)⁻¹ • f (circle_map z R θ) lemma circle_transform_deriv_periodic (f : ℂ → E) : periodic (circle_transform_deriv R z w f) (2 * π) := begin have := periodic_circle_map, simp_rw periodic at *, intro x, simp_rw [circle_transform_deriv, this], congr' 2, simp [this], end lemma circle_transform_deriv_eq (f : ℂ → E) : circle_transform_deriv R z w f = (λ θ, (circle_map z R θ - w)⁻¹ • (circle_transform R z w f θ)) := begin ext, simp_rw [circle_transform_deriv, circle_transform, ←mul_smul, ←mul_assoc], ring_nf, rw inv_pow, congr, ring, end lemma integral_circle_transform [complete_space E] (f : ℂ → E) : ∫ (θ : ℝ) in 0..2 * π, circle_transform R z w f θ = (2 * ↑π * I)⁻¹ • ∮ z in C(z, R), (z - w)⁻¹ • f z := begin simp_rw [circle_transform, circle_integral, deriv_circle_map, circle_map], simp, end lemma continuous_circle_transform {R : ℝ} (hR : 0 < R) {f : ℂ → E} {z w : ℂ} (hf : continuous_on f $ sphere z R) (hw : w ∈ ball z R) : continuous (circle_transform R z w f) := begin apply_rules [continuous.smul, continuous_const], simp_rw deriv_circle_map, apply_rules [continuous.mul, (continuous_circle_map 0 R), continuous_const], { apply continuous_circle_map_inv hw }, { apply continuous_on.comp_continuous hf (continuous_circle_map z R), exact (λ _, (circle_map_mem_sphere _ hR.le) _) }, end lemma continuous_circle_transform_deriv {R : ℝ} (hR : 0 < R) {f : ℂ → E} {z w : ℂ} (hf : continuous_on f (sphere z R)) (hw : w ∈ ball z R) : continuous (circle_transform_deriv R z w f) := begin rw circle_transform_deriv_eq, exact (continuous_circle_map_inv hw).smul (continuous_circle_transform hR hf hw), end /--A useful bound for circle integrals (with complex codomain)-/ def circle_transform_bounding_function (R : ℝ) (z : ℂ) (w : ℂ × ℝ) : ℂ := circle_transform_deriv R z w.1 (λ x, 1) w.2 lemma continuous_on_prod_circle_transform_function {R r : ℝ} (hr : r < R) {z : ℂ} : continuous_on (λ w : ℂ × ℝ, ((circle_map z R w.snd - w.fst)⁻¹) ^ 2) (closed_ball z r ×ˢ univ) := begin simp_rw ←one_div, apply_rules [continuous_on.pow, continuous_on.div, continuous_on_const], refine ((continuous_circle_map z R).continuous_on.comp continuous_on_snd (λ _, and.right)).sub (continuous_on_id.comp continuous_on_fst (λ _, and.left)), simp only [mem_prod, ne.def, and_imp, prod.forall], intros a b ha hb, have ha2 : a ∈ ball z R, by {simp at *, linarith,}, exact (sub_ne_zero.2 (circle_map_ne_mem_ball ha2 b)), end lemma continuous_on_abs_circle_transform_bounding_function {R r : ℝ} (hr : r < R) (z : ℂ) : continuous_on (abs ∘ (λ t, circle_transform_bounding_function R z t)) (closed_ball z r ×ˢ univ) := begin have : continuous_on (circle_transform_bounding_function R z) (closed_ball z r ×ˢ (⊤ : set ℝ)), { apply_rules [continuous_on.smul, continuous_on_const], simp only [deriv_circle_map], have c := (continuous_circle_map 0 R).continuous_on, apply_rules [continuous_on.mul, c.comp continuous_on_snd (λ _, and.right), continuous_on_const], simp_rw ←inv_pow, apply continuous_on_prod_circle_transform_function hr, }, refine continuous_abs.continuous_on.comp this _, show maps_to _ _ (⊤ : set ℂ), simp [maps_to], end lemma abs_circle_transform_bounding_function_le {R r : ℝ} (hr : r < R) (hr' : 0 ≤ r) (z : ℂ) : ∃ x : closed_ball z r ×ˢ [0, 2 * π], ∀ y : closed_ball z r ×ˢ [0, 2 * π], abs (circle_transform_bounding_function R z y) ≤ abs (circle_transform_bounding_function R z x) := begin have cts := continuous_on_abs_circle_transform_bounding_function hr z, have comp : is_compact (closed_ball z r ×ˢ [0, 2 * π]), { apply_rules [is_compact.prod, proper_space.is_compact_closed_ball z r, is_compact_uIcc], }, have none : (closed_ball z r ×ˢ [0, 2 * π]).nonempty := (nonempty_closed_ball.2 hr').prod nonempty_uIcc, have := is_compact.exists_forall_ge comp none (cts.mono (by { intro z, simp only [mem_prod, mem_closed_ball, mem_univ, and_true, and_imp], tauto })), simpa only [set_coe.forall, subtype.coe_mk, set_coe.exists], end /-- The derivative of a `circle_transform` is locally bounded. -/ lemma circle_transform_deriv_bound {R : ℝ} (hR : 0 < R) {z x : ℂ} {f : ℂ → ℂ} (hx : x ∈ ball z R) (hf : continuous_on f (sphere z R)) : ∃ (B ε : ℝ), 0 < ε ∧ ball x ε ⊆ ball z R ∧ (∀ (t : ℝ) (y ∈ ball x ε), ‖circle_transform_deriv R z y f t‖ ≤ B) := begin obtain ⟨r, hr, hrx⟩ := exists_lt_mem_ball_of_mem_ball hx, obtain ⟨ε', hε', H⟩ := exists_ball_subset_ball hrx, obtain ⟨⟨⟨a, b⟩, ⟨ha, hb⟩⟩, hab⟩ := abs_circle_transform_bounding_function_le hr (pos_of_mem_ball hrx).le z, let V : ℝ → (ℂ → ℂ) := λ θ w, circle_transform_deriv R z w (λ x, 1) θ, have funccomp : continuous_on (λ r , abs (f r)) (sphere z R), by { have cabs : continuous_on abs ⊤ := by apply continuous_abs.continuous_on, apply cabs.comp (hf), rw maps_to, tauto,}, have sbou := is_compact.exists_forall_ge (is_compact_sphere z R) (normed_space.sphere_nonempty.2 hR.le) funccomp, obtain ⟨X, HX, HX2⟩ := sbou, refine ⟨abs (V b a) * abs (f X), ε' , hε', subset.trans H (ball_subset_ball hr.le), _ ⟩, intros y v hv, obtain ⟨y1, hy1, hfun⟩ := periodic.exists_mem_Ico₀ (circle_transform_deriv_periodic R z v f) real.two_pi_pos y, have hy2: y1 ∈ [0, 2*π], by {convert (Ico_subset_Icc_self hy1), simp [uIcc_of_le real.two_pi_pos.le]}, have := mul_le_mul (hab ⟨⟨v, y1⟩, ⟨ball_subset_closed_ball (H hv), hy2⟩⟩) (HX2 (circle_map z R y1) (circle_map_mem_sphere z hR.le y1)) (complex.abs.nonneg _) (complex.abs.nonneg _), simp_rw hfun, simp only [circle_transform_bounding_function, circle_transform_deriv, V, norm_eq_abs, algebra.id.smul_eq_mul, deriv_circle_map, map_mul, abs_circle_map_zero, abs_I, mul_one, ←mul_assoc, mul_inv_rev, inv_I, abs_neg, abs_inv, abs_of_real, one_mul, abs_two, abs_pow, mem_ball, gt_iff_lt, subtype.coe_mk, set_coe.forall, mem_prod, mem_closed_ball, and_imp, prod.forall, normed_space.sphere_nonempty, mem_sphere_iff_norm] at *, exact this, end end complex
fd7a6196b2fe5719a8c3a57cf447fdf1b2a511c0
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/tools/super/cdcl_solver.lean
ed5b402cc354c40fa262544233b799b067faaf38
[ "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
14,076
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause open tactic expr monad super namespace cdcl @[reducible] meta def prop_var := expr @[reducible] meta def proof_term := expr @[reducible] meta def proof_hyp := expr meta inductive trail_elem | dec : prop_var → bool → proof_hyp → trail_elem | propg : prop_var → bool → proof_term → proof_hyp → trail_elem | dbl_neg_propg : prop_var → bool → proof_term → proof_hyp → trail_elem namespace trail_elem meta def var : trail_elem → prop_var | (dec v _ _) := v | (propg v _ _ _) := v | (dbl_neg_propg v _ _ _) := v meta def phase : trail_elem → bool | (dec _ ph _) := ph | (propg _ ph _ _) := ph | (dbl_neg_propg _ ph _ _) := ph meta def hyp : trail_elem → proof_hyp | (dec _ _ h) := h | (propg _ _ _ h) := h | (dbl_neg_propg _ _ _ h) := h meta def is_decision : trail_elem → bool | (dec _ _ _) := tt | (propg _ _ _ _) := ff | (dbl_neg_propg _ _ _ _) := ff end trail_elem meta structure var_state := (phase : bool) (assigned : option proof_hyp) meta structure learned_clause := (c : clause) (actual_proof : proof_term) meta inductive prop_lit | neg : prop_var → prop_lit | pos : prop_var → prop_lit namespace prop_lit meta instance : has_ordering prop_lit := ⟨λl₁ l₂, match l₁, l₂ with | pos _, neg _ := ordering.gt | neg _, pos _ := ordering.lt | pos v₁, pos v₂ := has_ordering.cmp v₁ v₂ | neg v₁, neg v₂ := has_ordering.cmp v₁ v₂ end⟩ meta def of_cls_lit : clause.literal → prop_lit | (clause.literal.left v) := neg v | (clause.literal.right v) := pos v meta def of_var_and_phase (v : prop_var) : bool → prop_lit | tt := pos v | ff := neg v end prop_lit meta def watch_map := rb_map name (ℕ × ℕ × clause) meta structure state := (trail : list trail_elem) (vars : rb_map prop_var var_state) (unassigned : rb_map prop_var prop_var) (clauses : list clause) (learned : list learned_clause) (watches : rb_map prop_lit watch_map) (conflict : option proof_term) (unitp_queue : list prop_var) (local_false : expr) namespace state meta def initial (local_false : expr) : state := { trail := [], vars := rb_map.mk _ _, unassigned := rb_map.mk _ _, clauses := [], learned := [], watches := rb_map.mk _ _, conflict := none, unitp_queue := [], local_false := local_false } meta def watches_for (st : state) (pl : prop_lit) : watch_map := (st^.watches^.find pl)^.get_or_else (rb_map.mk _ _) end state meta def solver := state_t state tactic meta instance : monad solver := state_t.monad _ _ meta instance : has_monad_lift tactic solver := monad.monad_transformer_lift (state_t state) tactic meta instance (α : Type) : has_coe (tactic α) (solver α) := ⟨monad.monad_lift⟩ meta def fail {A B} [has_to_format B] (b : B) : solver A := @tactic.fail A B _ b meta def get_local_false : solver expr := do st ← state_t.read, return st^.local_false meta def mk_var_core (v : prop_var) (ph : bool) : solver unit := do state_t.modify $ λst, match st^.vars^.find v with | (some _) := st | none := { st with vars := st^.vars^.insert v ⟨ph, none⟩, unassigned := st^.unassigned^.insert v v } end meta def mk_var (v : prop_var) : solver unit := mk_var_core v ff meta def set_conflict (proof : proof_term) : solver unit := state_t.modify $ λst, { st with conflict := some proof } meta def has_conflict : solver bool := do st ← state_t.read, return st^.conflict^.is_some meta def push_trail (elem : trail_elem) : solver unit := do st ← state_t.read, match st^.vars^.find elem^.var with | none := fail $ "unknown variable: " ++ elem^.var^.to_string | some ⟨_, some _⟩ := fail $ "adding already assigned variable to trail: " ++ elem^.var^.to_string | some ⟨_, none⟩ := state_t.write { st with vars := st^.vars^.insert elem^.var ⟨elem^.phase, some elem^.hyp⟩, unassigned := st^.unassigned^.erase elem^.var, trail := elem :: st^.trail, unitp_queue := elem^.var :: st^.unitp_queue } end meta def pop_trail_core : solver (option trail_elem) := do st ← state_t.read, match st^.trail with | elem :: rest := do state_t.write { st with trail := rest, vars := st^.vars^.insert elem^.var ⟨elem^.phase, none⟩, unassigned := st^.unassigned^.insert elem^.var elem^.var, unitp_queue := [] }, return $ some elem | [] := return none end meta def is_decision_level_zero : solver bool := do st ← state_t.read, return $ st^.trail^.for_all $ λelem, ¬elem^.is_decision meta def revert_to_decision_level_zero : unit → solver unit | () := do is_dl0 ← is_decision_level_zero, if is_dl0 then return () else do pop_trail_core, revert_to_decision_level_zero () meta def formula_of_lit (local_false : expr) (v : prop_var) (ph : bool) := if ph then v else imp v local_false meta def lookup_var (v : prop_var) : solver (option var_state) := do st ← state_t.read, return $ st^.vars^.find v meta def add_propagation (v : prop_var) (ph : bool) (just : proof_term) (just_is_dn : bool) : solver unit := do v_st ← lookup_var v, local_false ← get_local_false, match v_st with | none := fail $ "propagating unknown variable: " ++ v^.to_string | some ⟨assg_ph, some proof⟩ := if ph = assg_ph then return () else if assg_ph ∧ ¬just_is_dn then set_conflict (app just proof) else set_conflict (app proof just) | some ⟨_, none⟩ := do hyp_name ← mk_fresh_name, hyp ← return $ local_const hyp_name hyp_name binder_info.default (formula_of_lit local_false v ph), if just_is_dn then do push_trail $ trail_elem.dbl_neg_propg v ph just hyp else do push_trail $ trail_elem.propg v ph just hyp end meta def add_decision (v : prop_var) (ph : bool) : solver unit := do hyp_name ← mk_fresh_name, local_false ← get_local_false, hyp ← return $ local_const hyp_name hyp_name binder_info.default (formula_of_lit local_false v ph), push_trail $ trail_elem.dec v ph hyp meta def lookup_lit (l : clause.literal) : solver (option (bool × proof_hyp)) := do var_st_opt ← lookup_var l^.formula, match var_st_opt with | none := return none | some ⟨ph, none⟩ := return none | some ⟨ph, some proof⟩ := return $ some (if l^.is_neg then bnot ph else ph, proof) end meta def lit_is_false (l : clause.literal) : solver bool := do s ← lookup_lit l, return $ match s with | some (ff, _) := tt | _ := ff end meta def lit_is_not_false (l : clause.literal) : solver bool := do isf ← lit_is_false l, return $ bnot isf meta def cls_is_false (c : clause) : solver bool := lift list.band $ mapm lit_is_false c^.get_lits private meta def unit_propg_cls' : clause → solver (option prop_var) | c := if c^.num_lits = 0 then return (some c^.proof) else let hd := c^.get_lit 0 in do lit_st ← lookup_lit hd, match lit_st with | some (ff, isf_prf) := unit_propg_cls' (c^.inst isf_prf) | _ := return none end meta def unit_propg_cls : clause → solver unit | c := do has_confl ← has_conflict, if has_confl then return () else if c^.num_lits = 0 then do set_conflict c^.proof else let hd := c^.get_lit 0 in do lit_st ← lookup_lit hd, match lit_st with | some (ff, isf_prf) := unit_propg_cls (c^.inst isf_prf) | some (tt, _) := return () | none := do fls_prf_opt ← unit_propg_cls' (c^.inst (expr.mk_var 0)), match fls_prf_opt with | some fls_prf := do fls_prf' ← return $ lam `H binder_info.default c^.type^.binding_domain fls_prf, if hd^.is_neg then add_propagation hd^.formula ff fls_prf' ff else add_propagation hd^.formula tt fls_prf' tt | none := return () end end private meta def modify_watches_for (pl : prop_lit) (f : watch_map → watch_map) : solver unit := state_t.modify $ λst, { st with watches := st^.watches^.insert pl $ f $ st^.watches_for pl } private meta def add_watch (n : name) (c : clause) (i j : ℕ) : solver unit := let l := c^.get_lit i, pl := prop_lit.of_cls_lit l in modify_watches_for pl $ λw, w^.insert n (i,j,c) private meta def remove_watch (n : name) (c : clause) (i : ℕ) : solver unit := let l := c^.get_lit i, pl := prop_lit.of_cls_lit l in modify_watches_for pl $ λw, w^.erase n private meta def set_watches (n : name) (c : clause) : solver unit := if c^.num_lits = 0 then set_conflict c^.proof else if c^.num_lits = 1 then unit_propg_cls c else do not_false_lits ← filter (λi, lit_is_not_false (c^.get_lit i)) (list.range c^.num_lits), match not_false_lits with | [] := do add_watch n c 0 1, add_watch n c 1 0, unit_propg_cls c | [i] := let j := if i = 0 then 1 else 0 in do add_watch n c i j, add_watch n c j i, unit_propg_cls c | (i::j::_) := do add_watch n c i j, add_watch n c j i end meta def update_watches (n : name) (c : clause) (i₁ i₂ : ℕ) : solver unit := do remove_watch n c i₁, remove_watch n c i₂, set_watches n c meta def mk_clause (c : clause) : solver unit := do c : clause ← c^.distinct, for c^.get_lits (λl, mk_var l^.formula), revert_to_decision_level_zero (), state_t.modify $ λst, { st with clauses := c :: st^.clauses }, c_name ← mk_fresh_name, set_watches c_name c meta def unit_propg_var (v : prop_var) : solver unit := do st ← state_t.read, if st^.conflict^.is_some then return () else match st^.vars^.find v with | some ⟨ph, none⟩ := fail $ "propagating unassigned variable: " ++ v^.to_string | none := fail $ "unknown variable: " ++ v^.to_string | some ⟨ph, some _⟩ := let watches := st^.watches_for $ prop_lit.of_var_and_phase v (bnot ph) in for' watches^.to_list $ λw, update_watches w.1 w.2.2.2 w.2.1 w.2.2.1 end meta def analyze_conflict' (local_false : expr) : proof_term → list trail_elem → clause | proof (trail_elem.dec v ph hyp :: es) := let abs_prf := abstract_local proof hyp^.local_uniq_name in if has_var abs_prf then clause.close_const (analyze_conflict' proof es) hyp else analyze_conflict' proof es | proof (trail_elem.propg v ph l_prf hyp :: es) := let abs_prf := abstract_local proof hyp^.local_uniq_name in if has_var abs_prf then analyze_conflict' (app (lam hyp^.local_pp_name binder_info.default (formula_of_lit local_false v ph) abs_prf) l_prf) es else analyze_conflict' proof es | proof (trail_elem.dbl_neg_propg v ph l_prf hyp :: es) := let abs_prf := abstract_local proof hyp^.local_uniq_name in if has_var abs_prf then analyze_conflict' (app l_prf (lambdas [hyp] proof)) es else analyze_conflict' proof es | proof [] := ⟨0, 0, proof, local_false, local_false⟩ meta def analyze_conflict (proof : proof_term) : solver clause := do st ← state_t.read, return $ analyze_conflict' st^.local_false proof st^.trail meta def add_learned (c : clause) : solver unit := do prf_abbrev_name ← mk_fresh_name, c' ← return { c with proof := local_const prf_abbrev_name prf_abbrev_name binder_info.default c^.type }, state_t.modify $ λst, { st with learned := ⟨c', c^.proof⟩ :: st^.learned }, c_name ← mk_fresh_name, set_watches c_name c' meta def backtrack_with : clause → solver unit | conflict_clause := do isf ← cls_is_false conflict_clause, if ¬isf then state_t.modify (λst, { st with conflict := none }) else do removed_elem ← pop_trail_core, if removed_elem^.is_some then backtrack_with conflict_clause else return () meta def replace_learned_clauses' : proof_term → list learned_clause → proof_term | proof [] := proof | proof (⟨c, actual_proof⟩ :: lcs) := let abs_prf := abstract_local proof c^.proof^.local_uniq_name in if has_var abs_prf then replace_learned_clauses' (elet c^.proof^.local_pp_name c^.type actual_proof abs_prf) lcs else replace_learned_clauses' proof lcs meta def replace_learned_clauses (proof : proof_term) : solver proof_term := do st ← state_t.read, return $ replace_learned_clauses' proof st^.learned meta inductive result | unsat : proof_term → result | sat : rb_map prop_var bool → result variable theory_solver : solver (option proof_term) meta def unit_propg : unit → solver unit | () := do st ← state_t.read, if st^.conflict^.is_some then return () else match st^.unitp_queue with | [] := return () | (v::vs) := do state_t.write { st with unitp_queue := vs }, unit_propg_var v, unit_propg () end private meta def run' : unit → solver result | () := do unit_propg (), st ← state_t.read, match st^.conflict with | some conflict := do conflict_clause ← analyze_conflict conflict, if conflict_clause^.num_lits = 0 then do proof ← replace_learned_clauses conflict_clause^.proof, return (result.unsat proof) else do backtrack_with conflict_clause, add_learned conflict_clause, run' () | none := match st^.unassigned^.min with | none := do theory_conflict ← theory_solver, match theory_conflict with | some conflict := do set_conflict conflict, run' () | none := return $ result.sat (st^.vars^.for (λvar_st, var_st^.phase)) end | some unassigned := match st^.vars^.find unassigned with | some ⟨ph, none⟩ := do add_decision unassigned ph, run' () | _ := fail $ "unassigned variable is assigned: " ++ unassigned^.to_string end end end meta def run : solver result := run' theory_solver () meta def solve (local_false : expr) (clauses : list clause) : tactic result := do res ← (do for clauses mk_clause, run theory_solver) (state.initial local_false), return res.1 meta def theory_solver_of_tactic (th_solver : tactic unit) : cdcl.solver (option cdcl.proof_term) := do s ← state_t.read, ↑do hyps ← return $ s^.trail^.for (λe, e^.hyp), subgoal ← mk_meta_var s^.local_false, goals ← get_goals, set_goals [subgoal], hvs ← for hyps (λhyp, assertv hyp^.local_pp_name hyp^.local_type hyp), solved ← (do th_solver, now, return tt) <|> return ff, set_goals goals, if solved then do proof ← instantiate_mvars subgoal, proof' ← whnf proof, -- gets rid of the unnecessary asserts return $ some proof' else return none end cdcl
3901f2f951e321a7635e46beb999db08d7fb533b
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/alexandroff.lean
19f3661877107829bdf2d191ccf921e9b1e6a76c
[ "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
17,982
lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang, Yury Kudryashov -/ import topology.separation import topology.sets.opens /-! # The Alexandroff Compactification We construct the Alexandroff compactification (the one-point compactification) of an arbitrary topological space `X` and prove some properties inherited from `X`. ## Main definitions * `alexandroff`: the Alexandroff compactification, we use coercion for the canonical embedding `X → alexandroff X`; when `X` is already compact, the compactification adds an isolated point to the space. * `alexandroff.infty`: the extra point ## Main results * The topological structure of `alexandroff X` * The connectedness of `alexandroff X` for a noncompact, preconnected `X` * `alexandroff X` is `T₀` for a T₀ space `X` * `alexandroff X` is `T₁` for a T₁ space `X` * `alexandroff X` is normal if `X` is a locally compact Hausdorff space ## Tags one-point compactification, compactness -/ open set filter open_locale classical topological_space filter /-! ### Definition and basic properties In this section we define `alexandroff X` to be the disjoint union of `X` and `∞`, implemented as `option X`. Then we restate some lemmas about `option X` for `alexandroff X`. -/ variables {X : Type*} /-- The Alexandroff extension of an arbitrary topological space `X` -/ def alexandroff (X : Type*) := option X /-- The repr uses the notation from the `alexandroff` locale. -/ instance [has_repr X] : has_repr (alexandroff X) := ⟨λ o, match o with | none := "∞" | (some a) := "↑" ++ repr a end⟩ namespace alexandroff /-- The point at infinity -/ def infty : alexandroff X := none localized "notation `∞` := alexandroff.infty" in alexandroff instance : has_coe_t X (alexandroff X) := ⟨option.some⟩ instance : inhabited (alexandroff X) := ⟨∞⟩ instance [fintype X] : fintype (alexandroff X) := option.fintype instance infinite [infinite X] : infinite (alexandroff X) := option.infinite lemma coe_injective : function.injective (coe : X → alexandroff X) := option.some_injective X @[norm_cast] lemma coe_eq_coe {x y : X} : (x : alexandroff X) = y ↔ x = y := coe_injective.eq_iff @[simp] lemma coe_ne_infty (x : X) : (x : alexandroff X) ≠ ∞ . @[simp] lemma infty_ne_coe (x : X) : ∞ ≠ (x : alexandroff X) . /-- Recursor for `alexandroff` using the preferred forms `∞` and `↑x`. -/ @[elab_as_eliminator] protected def rec (C : alexandroff X → Sort*) (h₁ : C ∞) (h₂ : Π x : X, C x) : Π (z : alexandroff X), C z := option.rec h₁ h₂ lemma is_compl_range_coe_infty : is_compl (range (coe : X → alexandroff X)) {∞} := is_compl_range_some_none X @[simp] lemma range_coe_union_infty : (range (coe : X → alexandroff X) ∪ {∞}) = univ := range_some_union_none X @[simp] lemma range_coe_inter_infty : (range (coe : X → alexandroff X) ∩ {∞}) = ∅ := range_some_inter_none X @[simp] lemma compl_range_coe : (range (coe : X → alexandroff X))ᶜ = {∞} := compl_range_some X lemma compl_infty : ({∞}ᶜ : set (alexandroff X)) = range (coe : X → alexandroff X) := (@is_compl_range_coe_infty X).symm.compl_eq lemma compl_image_coe (s : set X) : (coe '' s : set (alexandroff X))ᶜ = coe '' sᶜ ∪ {∞} := by rw [coe_injective.compl_image_eq, compl_range_coe] lemma ne_infty_iff_exists {x : alexandroff X} : x ≠ ∞ ↔ ∃ (y : X), (y : alexandroff X) = x := by induction x using alexandroff.rec; simp instance : can_lift (alexandroff X) X := { coe := coe, cond := λ x, x ≠ ∞, prf := λ x, ne_infty_iff_exists.1 } lemma not_mem_range_coe_iff {x : alexandroff X} : x ∉ range (coe : X → alexandroff X) ↔ x = ∞ := by rw [← mem_compl_iff, compl_range_coe, mem_singleton_iff] lemma infty_not_mem_range_coe : ∞ ∉ range (coe : X → alexandroff X) := not_mem_range_coe_iff.2 rfl lemma infty_not_mem_image_coe {s : set X} : ∞ ∉ (coe : X → alexandroff X) '' s := not_mem_subset (image_subset_range _ _) infty_not_mem_range_coe @[simp] lemma coe_preimage_infty : (coe : X → alexandroff X) ⁻¹' {∞} = ∅ := by { ext, simp } /-! ### Topological space structure on `alexandroff X` We define a topological space structure on `alexandroff X` so that `s` is open if and only if * `coe ⁻¹' s` is open in `X`; * if `∞ ∈ s`, then `(coe ⁻¹' s)ᶜ` is compact. Then we reformulate this definition in a few different ways, and prove that `coe : X → alexandroff X` is an open embedding. If `X` is not a compact space, then we also prove that `coe` has dense range, so it is a dense embedding. -/ variables [topological_space X] instance : topological_space (alexandroff X) := { is_open := λ s, (∞ ∈ s → is_compact ((coe : X → alexandroff X) ⁻¹' s)ᶜ) ∧ is_open ((coe : X → alexandroff X) ⁻¹' s), is_open_univ := by simp, is_open_inter := λ s t, begin rintros ⟨hms, hs⟩ ⟨hmt, ht⟩, refine ⟨_, hs.inter ht⟩, rintros ⟨hms', hmt'⟩, simpa [compl_inter] using (hms hms').union (hmt hmt') end, is_open_sUnion := λ S ho, begin suffices : is_open (coe ⁻¹' ⋃₀ S : set X), { refine ⟨_, this⟩, rintro ⟨s, hsS : s ∈ S, hs : ∞ ∈ s⟩, refine compact_of_is_closed_subset ((ho s hsS).1 hs) this.is_closed_compl _, exact compl_subset_compl.mpr (preimage_mono $ subset_sUnion_of_mem hsS) }, rw [preimage_sUnion], exact is_open_bUnion (λ s hs, (ho s hs).2) end } variables {s : set (alexandroff X)} {t : set X} lemma is_open_def : is_open s ↔ (∞ ∈ s → is_compact (coe ⁻¹' s : set X)ᶜ) ∧ is_open (coe ⁻¹' s : set X) := iff.rfl lemma is_open_iff_of_mem' (h : ∞ ∈ s) : is_open s ↔ is_compact (coe ⁻¹' s : set X)ᶜ ∧ is_open (coe ⁻¹' s : set X) := by simp [is_open_def, h] lemma is_open_iff_of_mem (h : ∞ ∈ s) : is_open s ↔ is_closed (coe ⁻¹' s : set X)ᶜ ∧ is_compact (coe ⁻¹' s : set X)ᶜ := by simp only [is_open_iff_of_mem' h, is_closed_compl_iff, and.comm] lemma is_open_iff_of_not_mem (h : ∞ ∉ s) : is_open s ↔ is_open (coe ⁻¹' s : set X) := by simp [is_open_def, h] lemma is_closed_iff_of_mem (h : ∞ ∈ s) : is_closed s ↔ is_closed (coe ⁻¹' s : set X) := have ∞ ∉ sᶜ, from λ H, H h, by rw [← is_open_compl_iff, is_open_iff_of_not_mem this, ← is_open_compl_iff, preimage_compl] lemma is_closed_iff_of_not_mem (h : ∞ ∉ s) : is_closed s ↔ is_closed (coe ⁻¹' s : set X) ∧ is_compact (coe ⁻¹' s : set X) := by rw [← is_open_compl_iff, is_open_iff_of_mem (mem_compl h), ← preimage_compl, compl_compl] @[simp] lemma is_open_image_coe {s : set X} : is_open (coe '' s : set (alexandroff X)) ↔ is_open s := by rw [is_open_iff_of_not_mem infty_not_mem_image_coe, preimage_image_eq _ coe_injective] lemma is_open_compl_image_coe {s : set X} : is_open (coe '' s : set (alexandroff X))ᶜ ↔ is_closed s ∧ is_compact s := begin rw [is_open_iff_of_mem, ← preimage_compl, compl_compl, preimage_image_eq _ coe_injective], exact infty_not_mem_image_coe end @[simp] lemma is_closed_image_coe {s : set X} : is_closed (coe '' s : set (alexandroff X)) ↔ is_closed s ∧ is_compact s := by rw [← is_open_compl_iff, is_open_compl_image_coe] /-- An open set in `alexandroff X` constructed from a closed compact set in `X` -/ def opens_of_compl (s : set X) (h₁ : is_closed s) (h₂ : is_compact s) : topological_space.opens (alexandroff X) := ⟨(coe '' s)ᶜ, is_open_compl_image_coe.2 ⟨h₁, h₂⟩⟩ lemma infty_mem_opens_of_compl {s : set X} (h₁ : is_closed s) (h₂ : is_compact s) : ∞ ∈ opens_of_compl s h₁ h₂ := mem_compl infty_not_mem_image_coe @[continuity] lemma continuous_coe : continuous (coe : X → alexandroff X) := continuous_def.mpr (λ s hs, hs.right) lemma is_open_map_coe : is_open_map (coe : X → alexandroff X) := λ s, is_open_image_coe.2 lemma open_embedding_coe : open_embedding (coe : X → alexandroff X) := open_embedding_of_continuous_injective_open continuous_coe coe_injective is_open_map_coe lemma is_open_range_coe : is_open (range (coe : X → alexandroff X)) := open_embedding_coe.open_range lemma is_closed_infty : is_closed ({∞} : set (alexandroff X)) := by { rw [← compl_range_coe, is_closed_compl_iff], exact is_open_range_coe } lemma nhds_coe_eq (x : X) : 𝓝 ↑x = map (coe : X → alexandroff X) (𝓝 x) := (open_embedding_coe.map_nhds_eq x).symm lemma nhds_within_coe_image (s : set X) (x : X) : 𝓝[coe '' s] (x : alexandroff X) = map coe (𝓝[s] x) := (open_embedding_coe.to_embedding.map_nhds_within_eq _ _).symm lemma nhds_within_coe (s : set (alexandroff X)) (x : X) : 𝓝[s] ↑x = map coe (𝓝[coe ⁻¹' s] x) := (open_embedding_coe.map_nhds_within_preimage_eq _ _).symm lemma comap_coe_nhds (x : X) : comap (coe : X → alexandroff X) (𝓝 x) = 𝓝 x := (open_embedding_coe.to_inducing.nhds_eq_comap x).symm /-- If `x` is not an isolated point of `X`, then `x : alexandroff X` is not an isolated point of `alexandroff X`. -/ instance nhds_within_compl_coe_ne_bot (x : X) [h : ne_bot (𝓝[≠] x)] : ne_bot (𝓝[≠] (x : alexandroff X)) := by simpa [nhds_within_coe, preimage, coe_eq_coe] using h.map coe lemma nhds_within_compl_infty_eq : 𝓝[≠] (∞ : alexandroff X) = map coe (coclosed_compact X) := begin refine (nhds_within_basis_open ∞ _).ext (has_basis_coclosed_compact.map _) _ _, { rintro s ⟨hs, hso⟩, refine ⟨_, (is_open_iff_of_mem hs).mp hso, _⟩, simp }, { rintro s ⟨h₁, h₂⟩, refine ⟨_, ⟨mem_compl infty_not_mem_image_coe, is_open_compl_image_coe.2 ⟨h₁, h₂⟩⟩, _⟩, simp [compl_image_coe, ← diff_eq, subset_preimage_image] } end /-- If `X` is a non-compact space, then `∞` is not an isolated point of `alexandroff X`. -/ instance nhds_within_compl_infty_ne_bot [noncompact_space X] : ne_bot (𝓝[≠] (∞ : alexandroff X)) := by { rw nhds_within_compl_infty_eq, apply_instance } @[priority 900] instance nhds_within_compl_ne_bot [∀ x : X, ne_bot (𝓝[≠] x)] [noncompact_space X] (x : alexandroff X) : ne_bot (𝓝[≠] x) := alexandroff.rec _ alexandroff.nhds_within_compl_infty_ne_bot (λ y, alexandroff.nhds_within_compl_coe_ne_bot y) x lemma nhds_infty_eq : 𝓝 (∞ : alexandroff X) = map coe (coclosed_compact X) ⊔ pure ∞ := by rw [← nhds_within_compl_infty_eq, nhds_within_compl_singleton_sup_pure] lemma has_basis_nhds_infty : (𝓝 (∞ : alexandroff X)).has_basis (λ s : set X, is_closed s ∧ is_compact s) (λ s, coe '' sᶜ ∪ {∞}) := begin rw nhds_infty_eq, exact (has_basis_coclosed_compact.map _).sup_pure _ end @[simp] lemma comap_coe_nhds_infty : comap (coe : X → alexandroff X) (𝓝 ∞) = coclosed_compact X := by simp [nhds_infty_eq, comap_sup, comap_map coe_injective] lemma le_nhds_infty {f : filter (alexandroff X)} : f ≤ 𝓝 ∞ ↔ ∀ s : set X, is_closed s → is_compact s → coe '' sᶜ ∪ {∞} ∈ f := by simp only [has_basis_nhds_infty.ge_iff, and_imp] lemma ultrafilter_le_nhds_infty {f : ultrafilter (alexandroff X)} : (f : filter (alexandroff X)) ≤ 𝓝 ∞ ↔ ∀ s : set X, is_closed s → is_compact s → coe '' s ∉ f := by simp only [le_nhds_infty, ← compl_image_coe, ultrafilter.mem_coe, ultrafilter.compl_mem_iff_not_mem] lemma tendsto_nhds_infty' {α : Type*} {f : alexandroff X → α} {l : filter α} : tendsto f (𝓝 ∞) l ↔ tendsto f (pure ∞) l ∧ tendsto (f ∘ coe) (coclosed_compact X) l := by simp [nhds_infty_eq, and_comm] lemma tendsto_nhds_infty {α : Type*} {f : alexandroff X → α} {l : filter α} : tendsto f (𝓝 ∞) l ↔ ∀ s ∈ l, f ∞ ∈ s ∧ ∃ t : set X, is_closed t ∧ is_compact t ∧ maps_to (f ∘ coe) tᶜ s := tendsto_nhds_infty'.trans $ by simp only [tendsto_pure_left, has_basis_coclosed_compact.tendsto_left_iff, forall_and_distrib, and_assoc, exists_prop] lemma continuous_at_infty' {Y : Type*} [topological_space Y] {f : alexandroff X → Y} : continuous_at f ∞ ↔ tendsto (f ∘ coe) (coclosed_compact X) (𝓝 (f ∞)) := tendsto_nhds_infty'.trans $ and_iff_right (tendsto_pure_nhds _ _) lemma continuous_at_infty {Y : Type*} [topological_space Y] {f : alexandroff X → Y} : continuous_at f ∞ ↔ ∀ s ∈ 𝓝 (f ∞), ∃ t : set X, is_closed t ∧ is_compact t ∧ maps_to (f ∘ coe) tᶜ s := continuous_at_infty'.trans $ by simp only [has_basis_coclosed_compact.tendsto_left_iff, exists_prop, and_assoc] lemma continuous_at_coe {Y : Type*} [topological_space Y] {f : alexandroff X → Y} {x : X} : continuous_at f x ↔ continuous_at (f ∘ coe) x := by rw [continuous_at, nhds_coe_eq, tendsto_map'_iff, continuous_at] /-- If `X` is not a compact space, then the natural embedding `X → alexandroff X` has dense range. -/ lemma dense_range_coe [noncompact_space X] : dense_range (coe : X → alexandroff X) := begin rw [dense_range, ← compl_infty], exact dense_compl_singleton _ end lemma dense_embedding_coe [noncompact_space X] : dense_embedding (coe : X → alexandroff X) := { dense := dense_range_coe, .. open_embedding_coe } /-! ### Compactness and separation properties In this section we prove that `alexandroff X` is a compact space; it is a T₀ (resp., T₁) space if the original space satisfies the same separation axiom. If the original space is a locally compact Hausdorff space, then `alexandroff X` is a normal (hence, regular and Hausdorff) space. Finally, if the original space `X` is *not* compact and is a preconnected space, then `alexandroff X` is a connected space. -/ /-- For any topological space `X`, its one point compactification is a compact space. -/ instance : compact_space (alexandroff X) := { compact_univ := begin have : tendsto (coe : X → alexandroff X) (cocompact X) (𝓝 ∞), { rw [nhds_infty_eq], exact (tendsto_map.mono_left cocompact_le_coclosed_compact).mono_right le_sup_left }, convert ← this.is_compact_insert_range_of_cocompact continuous_coe, exact insert_none_range_some X end } /-- The one point compactification of a `t0_space` space is a `t0_space`. -/ instance [t0_space X] : t0_space (alexandroff X) := begin refine ⟨λ x y hxy, _⟩, induction x using alexandroff.rec; induction y using alexandroff.rec, { exact (hxy rfl).elim }, { use {∞}ᶜ, simp [is_closed_infty] }, { use {∞}ᶜ, simp [is_closed_infty] }, { rcases t0_space.t0 x y (mt coe_eq_coe.mpr hxy) with ⟨U, hUo, hU⟩, refine ⟨coe '' U, is_open_image_coe.2 hUo, _⟩, simpa [coe_eq_coe] } end /-- The one point compactification of a `t1_space` space is a `t1_space`. -/ instance [t1_space X] : t1_space (alexandroff X) := { t1 := λ z, begin induction z using alexandroff.rec, { exact is_closed_infty }, { simp only [← image_singleton, is_closed_image_coe], exact ⟨is_closed_singleton, is_compact_singleton⟩ } end } /-- The one point compactification of a locally compact Hausdorff space is a normal (hence, Hausdorff and regular) topological space. -/ instance [locally_compact_space X] [t2_space X] : normal_space (alexandroff X) := begin have key : ∀ z : X, ∃ u v : set (alexandroff X), is_open u ∧ is_open v ∧ ↑z ∈ u ∧ ∞ ∈ v ∧ u ∩ v = ∅, { intro z, rcases exists_open_with_compact_closure z with ⟨u, hu, huy', Hu⟩, refine ⟨coe '' u, (coe '' closure u)ᶜ, is_open_image_coe.2 hu, is_open_compl_image_coe.2 ⟨is_closed_closure, Hu⟩, mem_image_of_mem _ huy', mem_compl infty_not_mem_image_coe, _⟩, rw [← subset_compl_iff_disjoint, compl_compl], exact image_subset _ subset_closure }, refine @normal_of_compact_t2 _ _ _ ⟨λ x y hxy, _⟩, induction x using alexandroff.rec; induction y using alexandroff.rec, { exact (hxy rfl).elim }, { rcases key y with ⟨u, v, hu, hv, hxu, hyv, huv⟩, exact ⟨v, u, hv, hu, hyv, hxu, (inter_comm u v) ▸ huv⟩ }, { exact key x }, { exact separated_by_open_embedding open_embedding_coe (mt coe_eq_coe.mpr hxy) } end /-- If `X` is not a compact space, then `alexandroff X` is a connected space. -/ instance [preconnected_space X] [noncompact_space X] : connected_space (alexandroff X) := { to_preconnected_space := dense_embedding_coe.to_dense_inducing.preconnected_space, to_nonempty := infer_instance } /-- If `X` is an infinite type with discrete topology (e.g., `ℕ`), then the identity map from `cofinite_topology (alexandroff X)` to `alexandroff X` is not continuous. -/ lemma not_continuous_cofinite_topology_of_symm [infinite X] [discrete_topology X] : ¬(continuous (@cofinite_topology.of (alexandroff X)).symm) := begin inhabit X, simp only [continuous_iff_continuous_at, continuous_at, not_forall], use [cofinite_topology.of ↑(default : X)], simpa [nhds_coe_eq, nhds_discrete, cofinite_topology.nhds_eq] using (finite_singleton ((default : X) : alexandroff X)).infinite_compl end end alexandroff /-- A concrete counterexample shows that `continuous.homeo_of_equiv_compact_to_t2` cannot be generalized from `t2_space` to `t1_space`. Let `α = alexandroff ℕ` be the one-point compactification of `ℕ`, and let `β` be the same space `alexandroff ℕ` with the cofinite topology. Then `α` is compact, `β` is T1, and the identity map `id : α → β` is a continuous equivalence that is not a homeomorphism. -/ lemma continuous.homeo_of_equiv_compact_to_t2.t1_counterexample : ∃ (α β : Type) (Iα : topological_space α) (Iβ : topological_space β), by exactI compact_space α ∧ t1_space β ∧ ∃ f : α ≃ β, continuous f ∧ ¬ continuous f.symm := ⟨alexandroff ℕ, cofinite_topology (alexandroff ℕ), infer_instance, infer_instance, infer_instance, infer_instance, cofinite_topology.of, cofinite_topology.continuous_of, alexandroff.not_continuous_cofinite_topology_of_symm⟩
bb363d8da351c88244fbad85a9db5e2c4b83fb52
618003631150032a5676f229d13a079ac875ff77
/src/topology/metric_space/contracting.lean
4cbf4c35127f743a2735cc9d335bed8d19e3c713
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
15,741
lean
/- Copyright (c) 2019 Rohan Mitta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Rohan Mitta, Kevin Buzzard, Alistair Tucker, Johannes Hölzl, Yury Kudryashov -/ import analysis.specific_limits import data.setoid.basic import dynamics.fixed_points /-! # Contracting maps A Lipschitz continuous self-map with Lipschitz constant `K < 1` is called a *contracting map*. In this file we prove the Banach fixed point theorem, some explicit estimates on the rate of convergence, and some properties of the map sending a contracting map to its fixed point. ## Main definitions * `contracting_with K f` : a Lipschitz continuous self-map with `K < 1`; * `efixed_point` : given a contracting map `f` on a complete emetric space and a point `x` such that `edist x (f x) < ∞`, `efixed_point f hf x hx` is the unique fixed point of `f` in `emetric.ball x ∞`; * `fixed_point` : the unique fixed point of a contracting map on a complete nonempty metric space. ## Tags contracting map, fixed point, Banach fixed point theorem -/ open_locale nnreal topological_space classical open filter function variables {α : Type*} /-- If the iterates `f^[n] x₀` converge to `x` and `f` is continuous at `x`, then `x` is a fixed point for `f`. -/ lemma is_fixed_pt_of_tendsto_iterate [topological_space α] [t2_space α] {f : α → α} {x : α} (hf : continuous_at f x) (hx : ∃ x₀ : α, tendsto (λ n, f^[n] x₀) at_top (𝓝 x)) : is_fixed_pt f x := begin rcases hx with ⟨x₀, hx⟩, refine tendsto_nhds_unique at_top_ne_bot ((tendsto_add_at_top_iff_nat 1).1 _) hx, simp only [iterate_succ' f], exact tendsto.comp hf hx end /-- A map is said to be `contracting_with K`, if `K < 1` and `f` is `lipschitz_with K`. -/ def contracting_with [emetric_space α] (K : ℝ≥0) (f : α → α) := (K < 1) ∧ lipschitz_with K f namespace contracting_with variables [emetric_space α] [cs : complete_space α] {K : ℝ≥0} {f : α → α} open emetric set lemma to_lipschitz_with (hf : contracting_with K f) : lipschitz_with K f := hf.2 lemma one_sub_K_pos' (hf : contracting_with K f) : (0:ennreal) < 1 - K := by simp [hf.1] lemma one_sub_K_ne_zero (hf : contracting_with K f) : (1:ennreal) - K ≠ 0 := ne_of_gt hf.one_sub_K_pos' lemma one_sub_K_ne_top : (1:ennreal) - K ≠ ⊤ := by { norm_cast, exact ennreal.coe_ne_top } lemma edist_inequality (hf : contracting_with K f) {x y} (h : edist x y < ⊤) : edist x y ≤ (edist x (f x) + edist y (f y)) / (1 - K) := suffices edist x y ≤ edist x (f x) + edist y (f y) + K * edist x y, by rwa [ennreal.le_div_iff_mul_le (or.inl hf.one_sub_K_ne_zero) (or.inl one_sub_K_ne_top), mul_comm, ennreal.sub_mul (λ _ _, ne_of_lt h), one_mul, ennreal.sub_le_iff_le_add], calc edist x y ≤ edist x (f x) + edist (f x) (f y) + edist (f y) y : edist_triangle4 _ _ _ _ ... = edist x (f x) + edist y (f y) + edist (f x) (f y) : by rw [edist_comm y, add_right_comm] ... ≤ edist x (f x) + edist y (f y) + K * edist x y : add_le_add' (le_refl _) (hf.2 _ _) lemma edist_le_of_fixed_point (hf : contracting_with K f) {x y} (h : edist x y < ⊤) (hy : is_fixed_pt f y) : edist x y ≤ (edist x (f x)) / (1 - K) := by simpa only [hy.eq, edist_self, add_zero] using hf.edist_inequality h lemma eq_or_edist_eq_top_of_fixed_points (hf : contracting_with K f) {x y} (hx : is_fixed_pt f x) (hy : is_fixed_pt f y) : x = y ∨ edist x y = ⊤ := begin cases eq_or_lt_of_le (le_top : edist x y ≤ ⊤), from or.inr h, refine or.inl (edist_le_zero.1 _), simpa only [hx.eq, edist_self, add_zero, ennreal.zero_div] using hf.edist_le_of_fixed_point h hy end /-- If a map `f` is `contracting_with K`, and `s` is a forward-invariant set, then restriction of `f` to `s` is `contracting_with K` as well. -/ lemma restrict (hf : contracting_with K f) {s : set α} (hs : maps_to f s s) : contracting_with K (hs.restrict f s s) := ⟨hf.1, λ x y, hf.2 x y⟩ include cs /-- Banach fixed-point theorem, contraction mapping theorem, `emetric_space` version. A contracting map on a complete metric space has a fixed point. We include more conclusions in this theorem to avoid proving them again later. The main API for this theorem are the functions `efixed_point` and `fixed_point`, and lemmas about these functions. -/ theorem exists_fixed_point (hf : contracting_with K f) (x : α) (hx : edist x (f x) < ⊤) : ∃ y, is_fixed_pt f y ∧ tendsto (λ n, f^[n] x) at_top (𝓝 y) ∧ ∀ n:ℕ, edist (f^[n] x) y ≤ (edist x (f x)) * K^n / (1 - K) := have cauchy_seq (λ n, f^[n] x), from cauchy_seq_of_edist_le_geometric K (edist x (f x)) (ennreal.coe_lt_one_iff.2 hf.1) (ne_of_lt hx) (hf.to_lipschitz_with.edist_iterate_succ_le_geometric x), let ⟨y, hy⟩ := cauchy_seq_tendsto_of_complete this in ⟨y, is_fixed_pt_of_tendsto_iterate hf.2.continuous.continuous_at ⟨x, hy⟩, hy, edist_le_of_edist_le_geometric_of_tendsto K (edist x (f x)) (hf.to_lipschitz_with.edist_iterate_succ_le_geometric x) hy⟩ variable (f) -- avoid `efixed_point _` in pretty printer /-- Let `x` be a point of a complete emetric space. Suppose that `f` is a contracting map, and `edist x (f x) < ∞`. Then `efixed_point` is the unique fixed point of `f` in `emetric.ball x ∞`. -/ noncomputable def efixed_point (hf : contracting_with K f) (x : α) (hx : edist x (f x) < ⊤) : α := classical.some $ hf.exists_fixed_point x hx variables {f} lemma efixed_point_is_fixed_pt (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) : is_fixed_pt f (efixed_point f hf x hx) := (classical.some_spec $ hf.exists_fixed_point x hx).1 lemma tendsto_iterate_efixed_point (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) : tendsto (λn, f^[n] x) at_top (𝓝 $ efixed_point f hf x hx) := (classical.some_spec $ hf.exists_fixed_point x hx).2.1 lemma apriori_edist_iterate_efixed_point_le (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) (n : ℕ) : edist (f^[n] x) (efixed_point f hf x hx) ≤ (edist x (f x)) * K^n / (1 - K) := (classical.some_spec $ hf.exists_fixed_point x hx).2.2 n lemma edist_efixed_point_le (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) : edist x (efixed_point f hf x hx) ≤ (edist x (f x)) / (1 - K) := by { convert hf.apriori_edist_iterate_efixed_point_le hx 0, simp only [pow_zero, mul_one] } lemma edist_efixed_point_lt_top (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) : edist x (efixed_point f hf x hx) < ⊤ := lt_of_le_of_lt (hf.edist_efixed_point_le hx) (ennreal.mul_lt_top hx $ ennreal.lt_top_iff_ne_top.2 $ ennreal.inv_ne_top.2 hf.one_sub_K_ne_zero) lemma efixed_point_eq_of_edist_lt_top (hf : contracting_with K f) {x : α} (hx : edist x (f x) < ⊤) {y : α} (hy : edist y (f y) < ⊤) (h : edist x y < ⊤) : efixed_point f hf x hx = efixed_point f hf y hy := begin refine (hf.eq_or_edist_eq_top_of_fixed_points _ _).elim id (λ h', false.elim (ne_of_lt _ h')); try { apply efixed_point_is_fixed_pt }, change edist_lt_top_setoid.rel _ _, transitivity x, by { symmetry, exact hf.edist_efixed_point_lt_top hx }, transitivity y, exacts [h, hf.edist_efixed_point_lt_top hy] end omit cs /-- Banach fixed-point theorem for maps contracting on a complete subset. -/ theorem exists_fixed_point' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : ∃ y ∈ s, is_fixed_pt f y ∧ tendsto (λ n, f^[n] x) at_top (𝓝 y) ∧ ∀ n:ℕ, edist (f^[n] x) y ≤ (edist x (f x)) * K^n / (1 - K) := begin haveI := hsc.complete_space_coe, rcases hf.exists_fixed_point ⟨x, hxs⟩ hx with ⟨y, hfy, h_tendsto, hle⟩, refine ⟨y, y.2, subtype.ext.1 hfy, _, λ n, _⟩, { convert (continuous_subtype_coe.tendsto _).comp h_tendsto, ext n, simp only [(∘), maps_to.iterate_restrict, maps_to.coe_restrict_apply, subtype.coe_mk] }, { convert hle n, rw [maps_to.iterate_restrict, eq_comm, maps_to.coe_restrict_apply, subtype.coe_mk] } end variable (f) -- avoid `efixed_point _` in pretty printer /-- Let `s` be a complete forward-invariant set of a self-map `f`. If `f` contracts on `s` and `x ∈ s` satisfies `edist x (f x) < ⊤`, then `efixed_point'` is the unique fixed point of the restriction of `f` to `s ∩ emetric.ball x ⊤`. -/ noncomputable def efixed_point' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) (x : α) (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : α := classical.some $ hf.exists_fixed_point' hsc hsf hxs hx variables {f} lemma efixed_point_mem' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : efixed_point' f hsc hsf hf x hxs hx ∈ s := (classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).fst lemma efixed_point_is_fixed_pt' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : is_fixed_pt f (efixed_point' f hsc hsf hf x hxs hx) := (classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).snd.1 lemma tendsto_iterate_efixed_point' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : tendsto (λn, f^[n] x) at_top (𝓝 $ efixed_point' f hsc hsf hf x hxs hx) := (classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).snd.2.1 lemma apriori_edist_iterate_efixed_point_le' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) (n : ℕ) : edist (f^[n] x) (efixed_point' f hsc hsf hf x hxs hx) ≤ (edist x (f x)) * K^n / (1 - K) := (classical.some_spec $ hf.exists_fixed_point' hsc hsf hxs hx).snd.2.2 n lemma edist_efixed_point_le' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : edist x (efixed_point' f hsc hsf hf x hxs hx) ≤ (edist x (f x)) / (1 - K) := by { convert hf.apriori_edist_iterate_efixed_point_le' hsc hsf hxs hx 0, rw [pow_zero, mul_one] } lemma edist_efixed_point_lt_top' {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hf : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) : edist x (efixed_point' f hsc hsf hf x hxs hx) < ⊤ := lt_of_le_of_lt (hf.edist_efixed_point_le' hsc hsf hxs hx) (ennreal.mul_lt_top hx $ ennreal.lt_top_iff_ne_top.2 $ ennreal.inv_ne_top.2 hf.one_sub_K_ne_zero) /-- If a globally contracting map `f` has two complete forward-invariant sets `s`, `t`, and `x ∈ s` is at a finite distance from `y ∈ t`, then the `efixed_point'` constructed by `x` is the same as the `efixed_point'` constructed by `y`. This lemma takes additional arguments stating that `f` contracts on `s` and `t` because this way it can be used to prove the desired equality with non-trivial proofs of these facts. -/ lemma efixed_point_eq_of_edist_lt_top' (hf : contracting_with K f) {s : set α} (hsc : is_complete s) (hsf : maps_to f s s) (hfs : contracting_with K $ hsf.restrict f s s) {x : α} (hxs : x ∈ s) (hx : edist x (f x) < ⊤) {t : set α} (htc : is_complete t) (htf : maps_to f t t) (hft : contracting_with K $ htf.restrict f t t) {y : α} (hyt : y ∈ t) (hy : edist y (f y) < ⊤) (hxy : edist x y < ⊤) : efixed_point' f hsc hsf hfs x hxs hx = efixed_point' f htc htf hft y hyt hy := begin refine (hf.eq_or_edist_eq_top_of_fixed_points _ _).elim id (λ h', false.elim (ne_of_lt _ h')); try { apply efixed_point_is_fixed_pt' }, change edist_lt_top_setoid.rel _ _, transitivity x, by { symmetry, apply edist_efixed_point_lt_top' }, transitivity y, exact hxy, apply edist_efixed_point_lt_top' end end contracting_with namespace contracting_with variables [metric_space α] {K : ℝ≥0} {f : α → α} (hf : contracting_with K f) include hf lemma one_sub_K_pos (hf : contracting_with K f) : (0:ℝ) < 1 - K := sub_pos.2 hf.1 lemma dist_le_mul (x y : α) : dist (f x) (f y) ≤ K * dist x y := hf.to_lipschitz_with.dist_le_mul x y lemma dist_inequality (x y) : dist x y ≤ (dist x (f x) + dist y (f y)) / (1 - K) := suffices dist x y ≤ dist x (f x) + dist y (f y) + K * dist x y, by rwa [le_div_iff hf.one_sub_K_pos, mul_comm, sub_mul, one_mul, sub_le_iff_le_add], calc dist x y ≤ dist x (f x) + dist y (f y) + dist (f x) (f y) : dist_triangle4_right _ _ _ _ ... ≤ dist x (f x) + dist y (f y) + K * dist x y : add_le_add_left (hf.dist_le_mul _ _) _ lemma dist_le_of_fixed_point (x) {y} (hy : is_fixed_pt f y) : dist x y ≤ (dist x (f x)) / (1 - K) := by simpa only [hy.eq, dist_self, add_zero] using hf.dist_inequality x y theorem fixed_point_unique' {x y} (hx : is_fixed_pt f x) (hy : is_fixed_pt f y) : x = y := (hf.eq_or_edist_eq_top_of_fixed_points hx hy).resolve_right (edist_ne_top _ _) /-- Let `f` be a contracting map with constant `K`; let `g` be another map uniformly `C`-close to `f`. If `x` and `y` are their fixed points, then `dist x y ≤ C / (1 - K)`. -/ lemma dist_fixed_point_fixed_point_of_dist_le' (g : α → α) {x y} (hx : is_fixed_pt f x) (hy : is_fixed_pt g y) {C} (hfg : ∀ z, dist (f z) (g z) ≤ C) : dist x y ≤ C / (1 - K) := calc dist x y = dist y x : dist_comm x y ... ≤ (dist y (f y)) / (1 - K) : hf.dist_le_of_fixed_point y hx ... = (dist (f y) (g y)) / (1 - K) : by rw [hy.eq, dist_comm] ... ≤ C / (1 - K) : (div_le_div_right hf.one_sub_K_pos).2 (hfg y) noncomputable theory variables [nonempty α] [complete_space α] variable (f) /-- The unique fixed point of a contracting map in a nonempty complete metric space. -/ def fixed_point : α := efixed_point f hf _ (edist_lt_top (classical.choice ‹nonempty α›) _) variable {f} /-- The point provided by `contracting_with.fixed_point` is actually a fixed point. -/ lemma fixed_point_is_fixed_pt : is_fixed_pt f (fixed_point f hf) := hf.efixed_point_is_fixed_pt _ lemma fixed_point_unique {x} (hx : is_fixed_pt f x) : x = fixed_point f hf := hf.fixed_point_unique' hx hf.fixed_point_is_fixed_pt lemma dist_fixed_point_le (x) : dist x (fixed_point f hf) ≤ (dist x (f x)) / (1 - K) := hf.dist_le_of_fixed_point x hf.fixed_point_is_fixed_pt /-- Aposteriori estimates on the convergence of iterates to the fixed point. -/ lemma aposteriori_dist_iterate_fixed_point_le (x n) : dist (f^[n] x) (fixed_point f hf) ≤ (dist (f^[n] x) (f^[n+1] x)) / (1 - K) := by { rw [iterate_succ'], apply hf.dist_fixed_point_le } lemma apriori_dist_iterate_fixed_point_le (x n) : dist (f^[n] x) (fixed_point f hf) ≤ (dist x (f x)) * K^n / (1 - K) := le_trans (hf.aposteriori_dist_iterate_fixed_point_le x n) $ (div_le_div_right hf.one_sub_K_pos).2 $ hf.to_lipschitz_with.dist_iterate_succ_le_geometric x n lemma tendsto_iterate_fixed_point (x) : tendsto (λn, f^[n] x) at_top (𝓝 $ fixed_point f hf) := begin convert tendsto_iterate_efixed_point hf (edist_lt_top x _), refine (fixed_point_unique _ _).symm, apply efixed_point_is_fixed_pt end lemma fixed_point_lipschitz_in_map {g : α → α} (hg : contracting_with K g) {C} (hfg : ∀ z, dist (f z) (g z) ≤ C) : dist (fixed_point f hf) (fixed_point g hg) ≤ C / (1 - K) := hf.dist_fixed_point_fixed_point_of_dist_le' g hf.fixed_point_is_fixed_pt hg.fixed_point_is_fixed_pt hfg end contracting_with
a4529360035453287c25ad784050eb2e230040ba
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/free_monoid/basic.lean
7ccb6fdeddc5f217c1c29291d8f611ac9a470499
[ "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
9,512
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Yury Kudryashov -/ import data.list.big_operators.basic /-! # Free monoid over a given alphabet > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main definitions * `free_monoid α`: free monoid over alphabet `α`; defined as a synonym for `list α` with multiplication given by `(++)`. * `free_monoid.of`: embedding `α → free_monoid α` sending each element `x` to `[x]`; * `free_monoid.lift`: natural equivalence between `α → M` and `free_monoid α →* M` * `free_monoid.map`: embedding of `α → β` into `free_monoid α →* free_monoid β` given by `list.map`. -/ variables {α : Type*} {β : Type*} {γ : Type*} {M : Type*} [monoid M] {N : Type*} [monoid N] /-- Free monoid over a given alphabet. -/ @[to_additive "Free nonabelian additive monoid over a given alphabet"] def free_monoid (α) := list α namespace free_monoid @[to_additive] instance [decidable_eq α] : decidable_eq (free_monoid α) := list.decidable_eq /-- The identity equivalence between `free_monoid α` and `list α`. -/ @[to_additive "The identity equivalence between `free_add_monoid α` and `list α`."] def to_list : free_monoid α ≃ list α := equiv.refl _ /-- The identity equivalence between `list α` and `free_monoid α`. -/ @[to_additive "The identity equivalence between `list α` and `free_add_monoid α`."] def of_list : list α ≃ free_monoid α := equiv.refl _ @[simp, to_additive] lemma to_list_symm : (@to_list α).symm = of_list := rfl @[simp, to_additive] lemma of_list_symm : (@of_list α).symm = to_list := rfl @[simp, to_additive] lemma to_list_of_list (l : list α) : to_list (of_list l) = l := rfl @[simp, to_additive] lemma of_list_to_list (xs : free_monoid α) : of_list (to_list xs) = xs := rfl @[simp, to_additive] lemma to_list_comp_of_list : @to_list α ∘ of_list = id := rfl @[simp, to_additive] lemma of_list_comp_to_list : @of_list α ∘ to_list = id := rfl @[to_additive] instance : cancel_monoid (free_monoid α) := { one := of_list [], mul := λ x y, of_list (x.to_list ++ y.to_list), mul_one := list.append_nil, one_mul := list.nil_append, mul_assoc := list.append_assoc, mul_left_cancel := λ _ _ _, list.append_left_cancel, mul_right_cancel := λ _ _ _, list.append_right_cancel } @[to_additive] instance : inhabited (free_monoid α) := ⟨1⟩ @[simp, to_additive] lemma to_list_one : (1 : free_monoid α).to_list = [] := rfl @[simp, to_additive] lemma of_list_nil : of_list ([] : list α) = 1 := rfl @[simp, to_additive] lemma to_list_mul (xs ys : free_monoid α) : (xs * ys).to_list = xs.to_list ++ ys.to_list := rfl @[simp, to_additive] lemma of_list_append (xs ys : list α) : of_list (xs ++ ys) = of_list xs * of_list ys := rfl @[simp, to_additive] lemma to_list_prod (xs : list (free_monoid α)) : to_list xs.prod = (xs.map to_list).join := by induction xs; simp [*, list.join] @[simp, to_additive] lemma of_list_join (xs : list (list α)) : of_list xs.join = (xs.map of_list).prod := to_list.injective $ by simp /-- Embeds an element of `α` into `free_monoid α` as a singleton list. -/ @[to_additive "Embeds an element of `α` into `free_add_monoid α` as a singleton list." ] def of (x : α) : free_monoid α := of_list [x] @[simp, to_additive] lemma to_list_of (x : α) : to_list (of x) = [x] := rfl @[to_additive] lemma of_list_singleton (x : α) : of_list [x] = of x := rfl @[simp, to_additive] lemma of_list_cons (x : α) (xs : list α) : of_list (x :: xs) = of x * of_list xs := rfl @[to_additive] lemma to_list_of_mul (x : α) (xs : free_monoid α) : to_list (of x * xs) = x :: xs.to_list := rfl @[to_additive] lemma of_injective : function.injective (@of α) := list.singleton_injective /-- Recursor for `free_monoid` using `1` and `free_monoid.of x * xs` instead of `[]` and `x :: xs`. -/ @[elab_as_eliminator, to_additive "Recursor for `free_add_monoid` using `0` and `free_add_monoid.of x + xs` instead of `[]` and `x :: xs`."] def rec_on {C : free_monoid α → Sort*} (xs : free_monoid α) (h0 : C 1) (ih : Π x xs, C xs → C (of x * xs)) : C xs := list.rec_on xs h0 ih @[simp, to_additive] lemma rec_on_one {C : free_monoid α → Sort*} (h0 : C 1) (ih : Π x xs, C xs → C (of x * xs)) : @rec_on α C 1 h0 ih = h0 := rfl @[simp, to_additive] lemma rec_on_of_mul {C : free_monoid α → Sort*} (x : α) (xs : free_monoid α) (h0 : C 1) (ih : Π x xs, C xs → C (of x * xs)) : @rec_on α C (of x * xs) h0 ih = ih x xs (rec_on xs h0 ih) := rfl /-- A version of `list.cases_on` for `free_monoid` using `1` and `free_monoid.of x * xs` instead of `[]` and `x :: xs`. -/ @[elab_as_eliminator, to_additive "A version of `list.cases_on` for `free_add_monoid` using `0` and `free_add_monoid.of x + xs` instead of `[]` and `x :: xs`."] def cases_on {C : free_monoid α → Sort*} (xs : free_monoid α) (h0 : C 1) (ih : Π x xs, C (of x * xs)) : C xs := list.cases_on xs h0 ih @[simp, to_additive] lemma cases_on_one {C : free_monoid α → Sort*} (h0 : C 1) (ih : Π x xs, C (of x * xs)) : @cases_on α C 1 h0 ih = h0 := rfl @[simp, to_additive] lemma cases_on_of_mul {C : free_monoid α → Sort*} (x : α) (xs : free_monoid α) (h0 : C 1) (ih : Π x xs, C (of x * xs)) : @cases_on α C (of x * xs) h0 ih = ih x xs := rfl @[ext, to_additive] lemma hom_eq ⦃f g : free_monoid α →* M⦄ (h : ∀ x, f (of x) = g (of x)) : f = g := monoid_hom.ext $ λ l, rec_on l (f.map_one.trans g.map_one.symm) $ λ x xs hxs, by simp only [h, hxs, monoid_hom.map_mul] /-- A variant of `list.prod` that has `[x].prod = x` true definitionally. The purpose is to make `free_monoid.lift_eval_of` true by `rfl`. -/ @[to_additive "A variant of `list.sum` that has `[x].sum = x` true definitionally. The purpose is to make `free_add_monoid.lift_eval_of` true by `rfl`."] def prod_aux {M} [monoid M] (l : list M) : M := l.rec_on 1 (λ x xs (_ : M), list.foldl (*) x xs) @[to_additive] lemma prod_aux_eq : ∀ l : list M, free_monoid.prod_aux l = l.prod | [] := rfl | (x :: xs) := congr_arg (λ x, list.foldl (*) x xs) (one_mul _).symm /-- Equivalence between maps `α → M` and monoid homomorphisms `free_monoid α →* M`. -/ @[to_additive "Equivalence between maps `α → A` and additive monoid homomorphisms `free_add_monoid α →+ A`."] def lift : (α → M) ≃ (free_monoid α →* M) := { to_fun := λ f, ⟨λ l, free_monoid.prod_aux (l.to_list.map f), rfl, λ l₁ l₂, by simp only [prod_aux_eq, to_list_mul, list.map_append, list.prod_append]⟩, inv_fun := λ f x, f (of x), left_inv := λ f, rfl, right_inv := λ f, hom_eq $ λ x, rfl } @[simp, to_additive] lemma lift_symm_apply (f : free_monoid α →* M) : lift.symm f = f ∘ of := rfl @[to_additive] lemma lift_apply (f : α → M) (l : free_monoid α) : lift f l = (l.to_list.map f).prod := prod_aux_eq _ @[to_additive] lemma lift_comp_of (f : α → M) : lift f ∘ of = f := rfl @[simp, to_additive] lemma lift_eval_of (f : α → M) (x : α) : lift f (of x) = f x := rfl @[simp, to_additive] lemma lift_restrict (f : free_monoid α →* M) : lift (f ∘ of) = f := lift.apply_symm_apply f @[to_additive] lemma comp_lift (g : M →* N) (f : α → M) : g.comp (lift f) = lift (g ∘ f) := by { ext, simp } @[to_additive] lemma hom_map_lift (g : M →* N) (f : α → M) (x : free_monoid α) : g (lift f x) = lift (g ∘ f) x := monoid_hom.ext_iff.1 (comp_lift g f) x /-- Define a multiplicative action of `free_monoid α` on `β`. -/ @[to_additive "Define an additive action of `free_add_monoid α` on `β`."] def mk_mul_action (f : α → β → β) : mul_action (free_monoid α) β := { smul := λ l b, l.to_list.foldr f b, one_smul := λ x, rfl, mul_smul := λ xs ys b, list.foldr_append _ _ _ _ } @[to_additive] lemma smul_def (f : α → β → β) (l : free_monoid α) (b : β) : (by haveI := mk_mul_action f; exact l • b = l.to_list.foldr f b) := rfl @[to_additive] lemma of_list_smul (f : α → β → β) (l : list α) (b : β) : (by haveI := mk_mul_action f; exact (of_list l) • b = l.foldr f b) := rfl @[simp, to_additive] lemma of_smul (f : α → β → β) (x : α) (y : β) : (by haveI := mk_mul_action f; exact of x • y) = f x y := rfl /-- The unique monoid homomorphism `free_monoid α →* free_monoid β` that sends each `of x` to `of (f x)`. -/ @[to_additive "The unique additive monoid homomorphism `free_add_monoid α →+ free_add_monoid β` that sends each `of x` to `of (f x)`."] def map (f : α → β) : free_monoid α →* free_monoid β := { to_fun := λ l, of_list $ l.to_list.map f, map_one' := rfl, map_mul' := λ l₁ l₂, list.map_append _ _ _ } @[simp, to_additive] lemma map_of (f : α → β) (x : α) : map f (of x) = of (f x) := rfl @[to_additive] lemma to_list_map (f : α → β) (xs : free_monoid α) : (map f xs).to_list = xs.to_list.map f := rfl @[to_additive] lemma of_list_map (f : α → β) (xs : list α) : of_list (xs.map f) = map f (of_list xs) := rfl @[to_additive] lemma lift_of_comp_eq_map (f : α → β) : lift (λ x, of (f x)) = map f := hom_eq $ λ x, rfl @[to_additive] lemma map_comp (g : β → γ) (f : α → β) : map (g ∘ f) = (map g).comp (map f) := hom_eq $ λ x, rfl @[simp, to_additive] lemma map_id : map (@id α) = monoid_hom.id (free_monoid α) := hom_eq $ λ x, rfl end free_monoid
8d3e681d55664e30ce0b21cffc1f20d02dbac135
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/topology/continuous_function/basic.lean
93c10eac78fce824d4805bdb3cbe21dfe0e85334
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,383
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import topology.subset_properties import topology.tactic import topology.algebra.ordered /-! # Continuous bundled map In this file we define the type `continuous_map` of continuous bundled maps. -/ /-- Bundled continuous maps. -/ @[protect_proj] structure continuous_map (α : Type*) (β : Type*) [topological_space α] [topological_space β] := (to_fun : α → β) (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') notation `C(` α `, ` β `)` := continuous_map α β namespace continuous_map attribute [continuity] continuous_map.continuous_to_fun variables {α : Type*} {β : Type*} {γ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] instance : has_coe_to_fun (C(α, β)) := ⟨_, continuous_map.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : C(α, β)} : f.to_fun = (f : α → β) := rfl variables {α β} {f g : continuous_map α β} protected lemma continuous (f : C(α, β)) : continuous f := f.continuous_to_fun @[continuity] lemma coe_continuous : continuous (f : α → β) := f.continuous_to_fun @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext H instance [inhabited β] : inhabited C(α, β) := ⟨{ to_fun := λ _, default _, }⟩ lemma coe_inj ⦃f g : C(α, β)⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[simp] lemma coe_mk (f : α → β) (h : continuous f) : ⇑(⟨f, h⟩ : continuous_map α β) = f := rfl section variables (α β) /-- The continuous functions from `α` to `β` are the same as the plain functions when `α` is discrete. -/ @[simps] def equiv_fn_of_discrete [discrete_topology α] : C(α, β) ≃ (α → β) := ⟨(λ f, f), (λ f, ⟨f, continuous_of_discrete_topology⟩), λ f, by { ext, refl, }, λ f, by { ext, refl, }⟩ end /-- The identity as a continuous map. -/ def id : C(α, α) := ⟨id⟩ @[simp] lemma id_coe : (id : α → α) = id := rfl lemma id_apply (a : α) : id a = a := rfl /-- The composition of continuous maps, as a continuous map. -/ def comp (f : C(β, γ)) (g : C(α, β)) : C(α, γ) := ⟨f ∘ g⟩ @[simp] lemma comp_coe (f : C(β, γ)) (g : C(α, β)) : (comp f g : α → γ) = f ∘ g := rfl lemma comp_apply (f : C(β, γ)) (g : C(α, β)) (a : α) : comp f g a = f (g a) := rfl /-- Constant map as a continuous map -/ def const (b : β) : C(α, β) := ⟨λ x, b⟩ @[simp] lemma const_coe (b : β) : (const b : α → β) = (λ x, b) := rfl lemma const_apply (b : β) (a : α) : const b a = b := rfl instance [nonempty α] [nontrivial β] : nontrivial C(α, β) := { exists_pair_ne := begin obtain ⟨b₁, b₂, hb⟩ := exists_pair_ne β, refine ⟨const b₁, const b₂, _⟩, contrapose! hb, inhabit α, change const b₁ (default α) = const b₂ (default α), simp [hb] end } section variables [linear_ordered_add_comm_group β] [order_topology β] /-- The pointwise absolute value of a continuous function as a continuous function. -/ def abs (f : C(α, β)) : C(α, β) := { to_fun := λ x, abs (f x), } @[simp] lemma abs_apply (f : C(α, β)) (x : α) : f.abs x = _root_.abs (f x) := rfl end /-! We now set up the partial order and lattice structure (given by pointwise min and max) on continuous functions. -/ section lattice instance partial_order [partial_order β] : partial_order C(α, β) := partial_order.lift (λ f, f.to_fun) (by tidy) lemma le_def [partial_order β] {f g : C(α, β)} : f ≤ g ↔ ∀ a, f a ≤ g a := pi.le_def lemma lt_def [partial_order β] {f g : C(α, β)} : f < g ↔ (∀ a, f a ≤ g a) ∧ (∃ a, f a < g a) := pi.lt_def instance has_sup [linear_order β] [order_closed_topology β] : has_sup C(α, β) := { sup := λ f g, { to_fun := λ a, max (f a) (g a), } } @[simp] lemma sup_apply [linear_order β] [order_closed_topology β] (f g : C(α, β)) (a : α) : (f ⊔ g) a = max (f a) (g a) := rfl instance [linear_order β] [order_closed_topology β] : semilattice_sup C(α, β) := { le_sup_left := λ f g, le_def.mpr (by simp [le_refl]), le_sup_right := λ f g, le_def.mpr (by simp [le_refl]), sup_le := λ f₁ f₂ g w₁ w₂, le_def.mpr (λ a, by simp [le_def.mp w₁ a, le_def.mp w₂ a]), ..continuous_map.partial_order, ..continuous_map.has_sup, } instance has_inf [linear_order β] [order_closed_topology β] : has_inf C(α, β) := { inf := λ f g, { to_fun := λ a, min (f a) (g a), } } @[simp] lemma inf_apply [linear_order β] [order_closed_topology β] (f g : C(α, β)) (a : α) : (f ⊓ g) a = min (f a) (g a) := rfl instance [linear_order β] [order_closed_topology β] : semilattice_inf C(α, β) := { inf_le_left := λ f g, le_def.mpr (by simp [le_refl]), inf_le_right := λ f g, le_def.mpr (by simp [le_refl]), le_inf := λ f₁ f₂ g w₁ w₂, le_def.mpr (λ a, by simp [le_def.mp w₁ a, le_def.mp w₂ a]), ..continuous_map.partial_order, ..continuous_map.has_inf, } instance [linear_order β] [order_closed_topology β] : lattice C(α, β) := { ..continuous_map.semilattice_inf, ..continuous_map.semilattice_sup } -- TODO transfer this lattice structure to `bounded_continuous_function` end lattice end continuous_map
f3473d08fdd374ab1d22a6bee5c8ebee0738c4b5
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/run/ptst.lean
dd4bdb8a031a5af2a8dc3f089f841c95ac99cbd6
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
83
lean
import logic data.prod open prod -- Test tuple notation check (3, false, 1, true)
d8fd7aebf34392af9cfbef11e3c848414ab13fee
c45b34bfd44d8607a2e8762c926e3cfaa7436201
/uexp/src/uexp/rules/fkPennTR.lean
a61f97fe40ff9bb8c956395b947f8000df233720
[ "BSD-2-Clause" ]
permissive
Shamrock-Frost/Cosette
b477c442c07e45082348a145f19ebb35a7f29392
24cbc4adebf627f13f5eac878f04ffa20d1209af
refs/heads/master
1,619,721,304,969
1,526,082,841,000
1,526,082,841,000
121,695,605
1
0
null
1,518,737,210,000
1,518,737,210,000
null
UTF-8
Lean
false
false
2,850
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..cosette_tactics open Expr open Proj open Pred open SQL variable str_security_ : const datatypes.int theorem rule : forall (Γ scm_payroll scm_teams scm_depts : Schema) (rel_payroll : relation scm_payroll) (rel_teams : relation scm_teams) (rel_depts : relation scm_depts) (payroll_pdept : Column datatypes.int scm_payroll) (payroll_empl : Column datatypes.int scm_payroll) (teams_tproj : Column datatypes.int scm_teams) (teams_tmember : Column datatypes.int scm_teams) (depts_dname : Column datatypes.int scm_depts) (depts_dproj : Column datatypes.int scm_depts) (k : isKey payroll_empl rel_payroll) (fk : fKey payroll_empl teams_tmember rel_payroll rel_teams k), denoteSQL (SELECT1 (right⋅right⋅teams_tmember) FROM1 (product (table rel_depts) (table rel_teams)) WHERE (and (equal (uvariable (right⋅left⋅depts_dproj)) (uvariable (right⋅right⋅teams_tproj))) (equal (uvariable (right⋅left⋅depts_dname)) (constantExpr str_security_))) : SQL Γ _) = denoteSQL (SELECT1 (right⋅left⋅right⋅right) FROM1 (product ((SELECT1 (combine (right⋅left⋅depts_dname) (combine (right⋅left⋅depts_dproj) (right⋅right⋅payroll_empl))) FROM1 (product (table rel_depts) (table rel_payroll)) WHERE (equal (uvariable (right⋅left⋅depts_dname)) (uvariable (right⋅right⋅payroll_pdept))))) ((SELECT1 (combine (right⋅left⋅teams_tmember) (combine (right⋅right⋅payroll_pdept) (right⋅left⋅teams_tproj))) FROM1 (product (table rel_teams) (table rel_payroll)) WHERE (equal (uvariable (right⋅left⋅teams_tmember)) (uvariable (right⋅right⋅payroll_empl)))))) WHERE (and (and (and (equal (uvariable (right⋅left⋅left)) (constantExpr str_security_)) (equal (uvariable (right⋅left⋅right⋅left)) (uvariable (right⋅right⋅right⋅right)))) (equal (uvariable (right⋅left⋅right⋅right)) (uvariable (right⋅right⋅left)))) (equal (uvariable (right⋅left⋅left)) (uvariable (right⋅right⋅right⋅left)))) : SQL Γ _) := begin admit end