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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8098652703cdc9ce1058dca82e46887ecb10d7c3 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /07_Induction_and_Recursion.org.6.lean | 6935a79f18b4d2d399d86fc37a58d9ebd4acdf66 | [] | 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 | 604 | lean | /- page 101 -/
import standard
namespace hide
inductive nat : Type :=
| zero : nat
| succ : nat → nat
namespace nat
notation 0 := zero
-- BEGIN
definition add : nat → nat → nat
| add m 0 := m
| add m (succ n) := succ (add m n)
infix `+` := add
theorem add_zero (m : nat) : m + 0 = m := rfl
theorem add_succ (m n : nat) : m + succ n = succ (m + n) := rfl
theorem zero_add : ∀ n, 0 + n = n
| zero_add 0 := rfl
| zero_add (succ n) := eq.subst (zero_add n) rfl
definition mul : nat → nat → nat
| mul n 0 := 0
| mul n (succ m) := mul n m + m
-- END
end nat
end hide
|
1a94419bb00d37a3bd64d9ce4e2f40bee5a86fee | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/tactic/simps.lean | e608251bef0caad3f77d52d4d7b34b4d29af99e6 | [
"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 | 33,270 | lean | /-
Copyright (c) 2019 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
-/
import tactic.core
/-!
# simps attribute
This file defines the `@[simps]` attribute, to automatically generate simp-lemmas
reducing a definition when projections are applied to it.
## Implementation Notes
There are three attributes being defined here
* `@[simps]` is the attribute for objects of a structure or instances of a class. It will
automatically generate simplification lemmas for each projection of the object/instance that
contains data. See the doc strings for `simps_attr` and `simps_cfg` for more details and
configuration options.
* `@[_simps_str]` is automatically added to structures that have been used in `@[simps]` at least
once. This attribute contains the data of the projections used for this structure by all following
invocations of `@[simps]`.
* `@[notation_class]` should be added to all classes that define notation, like `has_mul` and
`has_zero`. This specifies that the projections that `@[simps]` used are the projections from
these notation classes instead of the projections of the superclasses.
Example: if `has_mul` is tagged with `@[notation_class]` then the projection used for `semigroup`
will be `λ α hα, @has_mul.mul α (@semigroup.to_has_mul α hα)` instead of `@semigroup.mul`.
## Tags
structures, projections, simp, simplifier, generates declarations
-/
open option tactic expr
setup_tactic_parser
declare_trace simps.verbose
declare_trace simps.debug
/--
The `@[_simps_str]` attribute specifies the preferred projections of the given structure,
used by the `@[simps]` attribute.
- This will usually be tagged by the `@[simps]` tactic.
- You can also generate this with the command `initialize_simps_projections`.
- To change the default value, see Note [custom simps projection].
- You are strongly discouraged to add this attribute manually.
- The first argument is the list of names of the universe variables used in the structure
- The second argument is a list that consists of
- a custom name for each projection of the structure
- an expressions for each projections of the structure (definitionally equal to the
corresponding projection). These expressions can contain the universe parameters specified
in the first argument).
-/
@[user_attribute] meta def simps_str_attr : user_attribute unit (list name × list (name × expr)) :=
{ name := `_simps_str,
descr := "An attribute specifying the projection of the given structure.",
parser := do e ← texpr, eval_pexpr _ e }
/--
The `@[notation_class]` attribute specifies that this is a notation class,
and this notation should be used instead of projections by @[simps].
* The first argument `tt` for notation classes and `ff` for classes applied to the structure,
like `has_coe_to_sort` and `has_coe_to_fun`
* The second argument is the name of the projection (by default it is the first projection
of the structure)
-/
@[user_attribute] meta def notation_class_attr : user_attribute unit (bool × option name) :=
{ name := `notation_class,
descr := "An attribute specifying that this is a notation class. Used by @[simps].",
parser := prod.mk <$> (option.is_none <$> (tk "*")?) <*> ident? }
attribute [notation_class] has_zero has_one has_add has_mul has_inv has_neg has_sub has_div has_dvd
has_mod has_le has_lt has_append has_andthen has_union has_inter has_sdiff has_equiv has_subset
has_ssubset has_emptyc has_insert has_singleton has_sep has_mem has_pow
attribute [notation_class* coe_sort] has_coe_to_sort
attribute [notation_class* coe_fn] has_coe_to_fun
/--
Get the projections used by `simps` associated to a given structure `str`. The second component is
the list of projections, and the first component the (shared) list of universe levels used by the
projections.
The returned information is also stored in a parameter of the attribute `@[_simps_str]`, which
is given to `str`. If `str` already has this attribute, the information is read from this
attribute instead.
The returned universe levels are the universe levels of the structure. For the projections there
are three cases
* If the declaration `{structure_name}.simps.{projection_name}` has been declared, then the value
of this declaration is used (after checking that it is definitionally equal to the actual
projection
* Otherwise, for every class with the `notation_class` attribute, and the structure has an
instance of that notation class, then the projection of that notation class is used for the
projection that is definitionally equal to it (if there is such a projection).
This means in practice that coercions to function types and sorts will be used instead of
a projection, if this coercion is definitionally equal to a projection. Furthermore, for
notation classes like `has_mul` and `has_zero` those projections are used instead of the
corresponding projection
* Otherwise, the projection of the structure is chosen.
For example: ``simps_get_raw_projections env `prod`` gives the default projections
```
([u, v], [prod.fst.{u v}, prod.snd.{u v}])
```
while ``simps_get_raw_projections env `equiv`` gives
```
([u_1, u_2], [λ α β, coe_fn, λ {α β} (e : α ≃ β), ⇑(e.symm), left_inv, right_inv])
```
after declaring the coercion from `equiv` to function and adding the declaration
```
def equiv.simps.inv_fun {α β} (e : α ≃ β) : β → α := e.symm
```
Optionally, this command accepts three optional arguments
* If `trace_if_exists` the command will always generate a trace message when the structure already
has the attribute `@[_simps_str]`.
* The `name_changes` argument accepts a list of pairs `(old_name, new_name)`. This is used to
change the projection name `old_name` to the custom projection name `new_name`. Example:
for the structure `equiv` the projection `to_fun` could be renamed `apply`. This name will be
used for parsing and generating projection names. This argument is ignored if the structure
already has an existing attribute.
* if `trc` is true, this tactic will trace information.
-/
-- if performance becomes a problem, possible heuristic: use the names of the projections to
-- skip all classes that don't have the corresponding field.
meta def simps_get_raw_projections (e : environment) (str : name) (trace_if_exists : bool := ff)
(name_changes : list (name × name) := []) (trc := ff) :
tactic (list name × list (name × expr)) := do
let trc := trc || is_trace_enabled_for `simps.verbose,
has_attr ← has_attribute' `_simps_str str,
if has_attr then do
data ← simps_str_attr.get_param str,
to_print ← data.2.mmap $ λ s, to_string <$> pformat!"Projection {s.1}: {s.2}",
let to_print := string.join $ to_print.intersperse "\n > ",
-- We always trace this when called by `initialize_simps_projections`,
-- because this doesn't do anything extra (so should not occur in mathlib).
-- It can be useful to find the projection names.
when (trc || trace_if_exists) trace!
"[simps] > Already found projection information for structure {str}:\n > {to_print}",
return data
else do
when trc trace!
"[simps] > generating projection information for structure {str}:",
d_str ← e.get str,
projs ← e.structure_fields_full str,
let raw_univs := d_str.univ_params,
let raw_levels := level.param <$> raw_univs,
/- Define the raw expressions for the projections, by default as the projections
(as an expression), but this can be overriden by the user. -/
raw_exprs ← projs.mmap (λ proj, let raw_expr : expr := expr.const proj raw_levels in do
custom_proj ← (do
decl ← e.get (str ++ `simps ++ proj.last),
let custom_proj := decl.value.instantiate_univ_params $ decl.univ_params.zip raw_levels,
when trc trace!
"[simps] > found custom projection for {proj}:\n > {custom_proj}",
return custom_proj) <|> return raw_expr,
is_def_eq custom_proj raw_expr <|>
-- if the type of the expression is different, we show a different error message, because
-- that is more likely going to be helpful.
do {
custom_proj_type ← infer_type custom_proj,
raw_expr_type ← infer_type raw_expr,
b ← succeeds (is_def_eq custom_proj_type raw_expr_type),
if b then fail!"Invalid custom projection:\n {custom_proj}
Expression is not definitionally equal to {raw_expr}."
else fail!"Invalid custom projection:\n {custom_proj}
Expression has different type than {raw_expr}. Given type:\n {custom_proj_type}
Expected type:\n {raw_expr_type}" },
return custom_proj),
/- Check for other coercions and type-class arguments to use as projections instead. -/
(args, _) ← open_pis d_str.type,
let e_str := (expr.const str raw_levels).mk_app args,
automatic_projs ← attribute.get_instances `notation_class,
raw_exprs ← automatic_projs.mfoldl (λ (raw_exprs : list expr) class_nm, (do
(is_class, proj_nm) ← notation_class_attr.get_param class_nm,
proj_nm ← proj_nm <|> (e.structure_fields_full class_nm).map list.head,
/- For this class, find the projection. `raw_expr` is the projection found applied to `args`,
and `lambda_raw_expr` has the arguments `args` abstracted. -/
(raw_expr, lambda_raw_expr) ← if is_class then (do
guard $ args.length = 1,
let e_inst_type := (expr.const class_nm raw_levels).mk_app args,
(hyp, e_inst) ← try_for 1000 (mk_conditional_instance e_str e_inst_type),
raw_expr ← mk_mapp proj_nm [args.head, e_inst],
clear hyp,
-- Note: `expr.bind_lambda` doesn't give the correct type
raw_expr_lambda ← lambdas [hyp] raw_expr,
return (raw_expr, raw_expr_lambda.lambdas args))
else (do
e_inst_type ← to_expr ((expr.const class_nm []).app (pexpr.of_expr e_str)),
e_inst ← try_for 1000 (mk_instance e_inst_type),
raw_expr ← mk_mapp proj_nm [e_str, e_inst],
return (raw_expr, raw_expr.lambdas args)),
raw_expr_whnf ← whnf raw_expr,
let relevant_proj := raw_expr_whnf.binding_body.get_app_fn.const_name,
/- Use this as projection, if the function reduces to a projection, and this projection has
not been overrriden by the user. -/
guard (projs.any (= relevant_proj) ∧ ¬ e.contains (str ++ `simps ++ relevant_proj.last)),
let pos := projs.find_index (= relevant_proj),
when trc trace!
" > using {proj_nm} instead of the default projection {relevant_proj.last}.",
return $ raw_exprs.update_nth pos lambda_raw_expr) <|> return raw_exprs) raw_exprs,
proj_names ← e.structure_fields str,
-- if we find the name in name_changes, change the name
let proj_names : list name := proj_names.map $
λ nm, (name_changes.find $ λ p : _ × _, p.1 = nm).elim nm prod.snd,
let projs := proj_names.zip raw_exprs,
when trc $ do {
to_print ← projs.mmap $ λ s, to_string <$> pformat!"Projection {s.1}: {s.2}",
let to_print := string.join $ to_print.intersperse "\n > ",
trace!"[simps] > generated projections for {str}:\n > {to_print}" },
simps_str_attr.set str (raw_univs, projs) tt,
return (raw_univs, projs)
/--
You can specify custom projections for the `@[simps]` attribute.
To do this for the projection `my_structure.awesome_projection` by adding a declaration
`my_structure.simps.awesome_projection` that is definitionally equal to
`my_structure.awesome_projection` but has the projection in the desired (simp-normal) form.
You can initialize the projections `@[simps]` uses with `initialize_simps_projections`
(after declaring any custom projections). This is not necessary, it has the same effect
if you just add `@[simps]` to a declaration.
If you do anything to change the default projections, make sure to call either `@[simps]` or
`initialize_simps_projections` in the same file as the structure declaration. Otherwise, you might
have a file that imports the structure, but not your custom projections.
-/
library_note "custom simps projection"
/-- Specify simps projections, see Note [custom simps projection].
You can specify custom names by writing e.g.
`initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)`.
Set `trace.simps.verbose` to true to see the generated projections.
Run `initialize_simps_projections?` to see which projections are generated. -/
@[user_command] meta def initialize_simps_projections_cmd
(_ : parse $ tk "initialize_simps_projections") : parser unit := do
env ← get_env,
trc ← is_some <$> (tk "?")?,
ns ← (prod.mk <$> ident <*> (tk "(" >>
sep_by (tk ",") (prod.mk <$> ident <*> (tk "->" >> ident)) <* tk ")")?)*,
ns.mmap' $ λ data, do
nm ← resolve_constant data.1,
simps_get_raw_projections env nm tt (data.2.get_or_else []) trc
/--
Get the projections of a structure used by `@[simps]` applied to the appropriate arguments.
Returns a list of quadruples
(projection expression, given projection name, original (full) projection name,
corresponding right-hand-side),
one for each projection. The given projection name is the name for the projection used by the user
used to generate (and parse) projection names. The original projection name is the actual
projection name in the structure, which is only used to check whether the expression is an
eta-expansion of some other expression. For example, in the structure
Example 1: ``simps_get_projection_exprs env `(α × β) `(⟨x, y⟩)`` will give the output
```
[(`(@prod.fst.{u v} α β), `fst, `prod.fst, `(x)),
(`(@prod.snd.{u v} α β), `snd, `prod.snd, `(y))]
```
Example 2: ``simps_get_projection_exprs env `(α ≃ α) `(⟨id, id, λ _, rfl, λ _, rfl⟩)``
will give the output
```
[(`(@equiv.to_fun.{u u} α α), `apply, `equiv.to_fun, `(id)),
(`(@equiv.inv_fun.{u u} α α), `symm_apply, `equiv.inv_fun, `(id)),
...,
...]
```
The last two fields of the list correspond to the propositional fields of the structure,
and are rarely/never used.
-/
-- This function does not use `tactic.mk_app` or `tactic.mk_mapp`, because the the given arguments
-- might not uniquely specify the universe levels yet.
meta def simps_get_projection_exprs (e : environment) (tgt : expr)
(rhs : expr) : tactic $ list $ expr × name × name × expr := do
let params := get_app_args tgt, -- the parameters of the structure
(params.zip $ (get_app_args rhs).take params.length).mmap' (λ ⟨a, b⟩, is_def_eq a b)
<|> fail "unreachable code (1)",
let str := tgt.get_app_fn.const_name,
let rhs_args := (get_app_args rhs).drop params.length, -- the fields of the object
(raw_univs, projs_and_raw_exprs) ← simps_get_raw_projections e str ff,
guard (rhs_args.length = projs_and_raw_exprs.length) <|> fail "unreachable code (2)",
let univs := raw_univs.zip tgt.get_app_fn.univ_levels,
let projs := projs_and_raw_exprs.map $ prod.fst,
original_projection_names ← e.structure_fields_full str,
let raw_exprs := projs_and_raw_exprs.map $ prod.snd,
let proj_exprs := raw_exprs.map $
λ raw_expr, (raw_expr.instantiate_univ_params univs).instantiate_lambdas_or_apps params,
return $ proj_exprs.zip $ projs.zip $ original_projection_names.zip rhs_args
/--
Configuration options for the `@[simps]` attribute.
* `attrs` specifies the list of attributes given to the generated lemmas. Default: ``[`simp]``.
The attributes can be either basic attributes, or user attributes without parameters.
There are two attributes which `simps` might add itself:
* If ``[`simp]`` is in the list, then ``[`_refl_lemma]`` is added automatically if appropriate.
* If the definition is marked with `@[to_additive ...]` then all generated lemmas are marked
with `@[to_additive]`
* `short_name` gives the generated lemmas a shorter name. This only has an effect when multiple
projections are applied in a lemma. When this is `ff` (default) all projection names will be
appended to the definition name to form the lemma name, and when this is `tt`, only the
last projection name will be appended.
* if `simp_rhs` is `tt` then the right-hand-side of the generated lemmas will be put in
simp-normal form. More precisely: `dsimp, simp` will be called on all these expressions.
See note [dsimp, simp].
* `type_md` specifies how aggressively definitions are unfolded in the type of expressions
for the purposes of finding out whether the type is a function type.
Default: `instances`. This will unfold coercion instances (so that a coercion to a function type
is recognized as a function type), but not declarations like `set`.
* `rhs_md` specifies how aggressively definition in the declaration are unfolded for the purposes
of finding out whether it is a constructor.
Default: `none`
Exception: `@[simps]` will automatically add the options
`{rhs_md := semireducible, simp_rhs := tt}` if the given definition is not a constructor with
the given reducibility setting for `rhs_md`.
* If `fully_applied` is `ff` then the generated simp-lemmas will be between non-fully applied
terms, i.e. equalities between functions. This does not restrict the recursive behavior of
`@[simps]`, so only the "final" projection will be non-fully applied.
However, it can be used in combination with explicit field names, to get a partially applied
intermediate projection.
* The option `not_recursive` contains the list of names of types for which `@[simps]` doesn't
recursively apply projections. For example, given an equivalence `α × β ≃ β × α` one usually
wants to only apply the projections for `equiv`, and not also those for `×`. This option is
only relevant if no explicit projection names are given as argument to `@[simps]`.
* The option `trace` is set to `tt` when you write `@[simps?]`. In this case, the attribute will
print all generated lemmas. It is almost the same as setting the option `trace.simps.verbose`,
except that it doesn't print information about the found projections.
-/
@[derive [has_reflect, inhabited]] structure simps_cfg :=
(attrs := [`simp])
(short_name := ff)
(simp_rhs := ff)
(type_md := transparency.instances)
(rhs_md := transparency.none)
(fully_applied := tt)
(not_recursive := [`prod, `pprod])
(trace := ff)
/-- Add a lemma with `nm` stating that `lhs = rhs`. `type` is the type of both `lhs` and `rhs`,
`args` is the list of local constants occurring, and `univs` is the list of universe variables.
If `add_simp` then we make the resulting lemma a simp-lemma. -/
meta def simps_add_projection (nm : name) (type lhs rhs : expr) (args : list expr)
(univs : list name) (cfg : simps_cfg) : tactic unit := do
when_tracing `simps.debug trace!
"[simps] > Planning to add the equality\n > {lhs} = ({rhs} : {type})",
-- simplify `rhs` if `cfg.simp_rhs` is true
(rhs, prf) ← do { guard cfg.simp_rhs,
rhs' ← rhs.dsimp {fail_if_unchanged := ff},
when_tracing `simps.debug $ when (rhs ≠ rhs') trace!
"[simps] > `dsimp` simplified rhs to\n > {rhs'}",
(rhsprf1, rhsprf2, ns) ← rhs'.simp {fail_if_unchanged := ff},
when_tracing `simps.debug $ when (rhs' ≠ rhsprf1) trace!
"[simps] > `simp` simplified rhs to\n > {rhsprf1}",
return (prod.mk rhsprf1 rhsprf2) }
<|> prod.mk rhs <$> mk_app `eq.refl [type, lhs],
eq_ap ← mk_mapp `eq $ [type, lhs, rhs].map some,
decl_name ← get_unused_decl_name nm,
let decl_type := eq_ap.pis args,
let decl_value := prf.lambdas args,
let decl := declaration.thm decl_name univs decl_type (pure decl_value),
when cfg.trace trace!
"[simps] > adding projection {decl_name}:\n > {decl_type}",
decorate_error ("failed to add projection lemma " ++ decl_name.to_string ++ ". Nested error:") $
add_decl decl,
b ← succeeds $ is_def_eq lhs rhs,
when (b ∧ `simp ∈ cfg.attrs) (set_basic_attribute `_refl_lemma decl_name tt),
cfg.attrs.mmap' $ λ nm, set_attribute nm decl_name tt
/-- Derive lemmas specifying the projections of the declaration.
If `todo` is non-empty, it will generate exactly the names in `todo`. -/
meta def simps_add_projections : ∀(e : environment) (nm : name) (suffix : string)
(type lhs rhs : expr) (args : list expr) (univs : list name) (must_be_str : bool)
(cfg : simps_cfg) (todo : list string), tactic unit
| e nm suffix type lhs rhs args univs must_be_str cfg todo := do
-- we don't want to unfold non-reducible definitions (like `set`) to apply more arguments
when_tracing `simps.debug trace!
"[simps] > Trying to add simp-lemmas for\n > {lhs}
[simps] > Type of the expression before normalizing: {type}",
(type_args, tgt) ← open_pis_whnf type cfg.type_md,
when_tracing `simps.debug trace!
"[simps] > Type after removing pi's: {tgt}",
tgt ← whnf tgt,
when_tracing `simps.debug trace!
"[simps] > Type after reduction: {tgt}",
let new_args := args ++ type_args,
let lhs_ap := lhs.mk_app type_args,
let rhs_ap := rhs.instantiate_lambdas_or_apps type_args,
let str := tgt.get_app_fn.const_name,
let new_nm := nm.append_suffix suffix,
/- We want to generate the current projection if it is in `todo` -/
let todo_next := todo.filter (≠ ""),
/- Don't recursively continue if `str` is not a structure or if the structure is in
`not_recursive`. -/
if e.is_structure str ∧ ¬(todo = [] ∧ str ∈ cfg.not_recursive ∧ ¬must_be_str) then do
[intro] ← return $ e.constructors_of str | fail "unreachable code (3)",
rhs_whnf ← whnf rhs_ap cfg.rhs_md,
(rhs_ap, todo_now) ← if h : ¬ is_constant_of rhs_ap.get_app_fn intro ∧
is_constant_of rhs_whnf.get_app_fn intro then
/- If this was a desired projection, we want to apply it before taking the whnf.
However, if the current field is an eta-expansion (see below), we first want
to eta-reduce it and only then construct the projection.
This makes the flow of this function hard to follow. -/
when ("" ∈ todo) (if cfg.fully_applied then
simps_add_projection new_nm tgt lhs_ap rhs_ap new_args univs cfg else
simps_add_projection new_nm type lhs rhs args univs cfg) >>
return (rhs_whnf, ff) else
return (rhs_ap, "" ∈ todo),
if is_constant_of (get_app_fn rhs_ap) intro then do -- if the value is a constructor application
tuples ← simps_get_projection_exprs e tgt rhs_ap,
let projs := tuples.map $ λ x, x.2.1,
let pairs := tuples.map $ λ x, x.2.2,
eta ← rhs_ap.is_eta_expansion_aux pairs, -- check whether `rhs_ap` is an eta-expansion
let rhs_ap := eta.lhoare rhs_ap, -- eta-reduce `rhs_ap`
/- As a special case, we want to automatically generate the current projection if `rhs_ap`
was an eta-expansion. Also, when this was a desired projection, we need to generate the
current projection if we haven't done it above. -/
when (todo_now ∨ (todo = [] ∧ eta.is_some)) $
if cfg.fully_applied then
simps_add_projection new_nm tgt lhs_ap rhs_ap new_args univs cfg else
simps_add_projection new_nm type lhs rhs args univs cfg,
/- We stop if no further projection is specified or if we just reduced an eta-expansion and we
automatically choose projections -/
when ¬(todo = [""] ∨ (eta.is_some ∧ todo = [])) $ do
let todo := todo_next,
-- check whether all elements in `todo` have a projection as prefix
guard (todo.all $ λ x, projs.any $ λ proj, ("_" ++ proj.last).is_prefix_of x) <|>
let x := (todo.find $ λ x, projs.all $ λ proj, ¬ ("_" ++ proj.last).is_prefix_of x).iget,
simp_lemma := nm.append_suffix $ suffix ++ x,
needed_proj := (x.split_on '_').tail.head in
fail!
"Invalid simp-lemma {simp_lemma}. Structure {str} does not have projection {needed_proj}.
The known projections are:
{projs}
You can also see this information by running
`initialize_simps_projections {str}`.
Note: the projection names used by @[simps] might not correspond to the projection names in the structure.",
tuples.mmap' $ λ ⟨proj_expr, proj, _, new_rhs⟩, do
new_type ← infer_type new_rhs,
let new_todo := todo.filter_map $ λ x, string.get_rest x $ "_" ++ proj.last,
b ← is_prop new_type,
-- we only continue with this field if it is non-propositional or mentioned in todo
when ((¬ b ∧ todo = []) ∨ new_todo ≠ []) $ do
let new_lhs := proj_expr.instantiate_lambdas_or_apps [lhs_ap],
let new_suffix := if cfg.short_name then "_" ++ proj.last else
suffix ++ "_" ++ proj.last,
simps_add_projections e nm new_suffix new_type new_lhs new_rhs new_args univs
ff cfg new_todo
-- if I'm about to run into an error, try to set the transparency for `rhs_md` higher.
else if cfg.rhs_md = transparency.none ∧ (must_be_str ∨ todo_next ≠ []) then do
when cfg.trace trace!
"[simps] > The given definition is not a constructor application:
> {rhs_ap}
> Retrying with the options {{ rhs_md := semireducible, simp_rhs := tt}.",
simps_add_projections e nm suffix type lhs rhs args univs must_be_str
{ rhs_md := semireducible, simp_rhs := tt, ..cfg} todo
else do
when must_be_str $
fail!"Invalid `simps` attribute. The body is not a constructor application:\n {rhs_ap}",
when (todo_next ≠ []) $
fail!"Invalid simp-lemma {nm.append_suffix $ suffix ++ todo_next.head}.
The given definition is not a constructor application:\n {rhs_ap}",
if cfg.fully_applied then
simps_add_projection new_nm tgt lhs_ap rhs_ap new_args univs cfg else
simps_add_projection new_nm type lhs rhs args univs cfg
else do
when must_be_str $
fail!"Invalid `simps` attribute. Target {str} is not a structure",
when (todo_next ≠ [] ∧ str ∉ cfg.not_recursive) $
fail!"Invalid simp-lemma {nm.append_suffix $ suffix ++ todo_next.head}.
Projection {(todo_next.head.split_on '_').tail.head} doesn't exist, because target is not a structure.",
if cfg.fully_applied then
simps_add_projection new_nm tgt lhs_ap rhs_ap new_args univs cfg else
simps_add_projection new_nm type lhs rhs args univs cfg
/-- `simps_tac` derives simp-lemmas for all (nested) non-Prop projections of the declaration.
If `todo` is non-empty, it will generate exactly the names in `todo`.
If `short_nm` is true, the generated names will only use the last projection name.
If `trc` is true, trace as if `trace.simps.verbose` is true. -/
meta def simps_tac (nm : name) (cfg : simps_cfg := {}) (todo : list string := []) (trc := ff) :
tactic unit :=
do
e ← get_env,
d ← e.get nm,
let lhs : expr := const d.to_name (d.univ_params.map level.param),
let todo := todo.erase_dup.map $ λ proj, "_" ++ proj,
b ← has_attribute' `to_additive nm,
let cfg := if b then { attrs := cfg.attrs ++ [`to_additive], ..cfg } else cfg,
let cfg := { trace := cfg.trace || is_trace_enabled_for `simps.verbose || trc, ..cfg },
when (cfg.trace ∧ `to_additive ∈ cfg.attrs)
trace!"[simps] > @[to_additive] will be added to all generated lemmas.",
simps_add_projections e nm "" d.type lhs d.value [] d.univ_params tt cfg todo
/-- The parser for the `@[simps]` attribute. -/
meta def simps_parser : parser (bool × list string × simps_cfg) := do
/- note: we don't check whether the user has written a nonsense namespace in an argument. -/
prod.mk <$> is_some <$> (tk "?")? <*>
(prod.mk <$> many (name.last <$> ident) <*>
(do some e ← parser.pexpr? | return {}, eval_pexpr simps_cfg e))
/--
The `@[simps]` attribute automatically derives lemmas specifying the projections of this
declaration.
Example:
```lean
@[simps] def foo : ℕ × ℤ := (1, 2)
```
derives two simp-lemmas:
```lean
@[simp] lemma foo_fst : foo.fst = 1
@[simp] lemma foo_snd : foo.snd = 2
```
* It does not derive simp-lemmas for the prop-valued projections.
* It will automatically reduce newly created beta-redexes, but will not unfold any definitions.
* If the structure has a coercion to either sorts or functions, and this is defined to be one
of the projections, then this coercion will be used instead of the projection.
* If the structure is a class that has an instance to a notation class, like `has_mul`, then this
notation is used instead of the corresponding projection.
* You can specify custom projections, by giving a declaration with name
`{structure_name}.simps.{projection_name}`. See Note [custom simps projection].
Example:
```lean
def equiv.simps.inv_fun (e : α ≃ β) : β → α := e.symm
@[simps] def equiv.trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ :=
⟨e₂ ∘ e₁, e₁.symm ∘ e₂.symm⟩
```
generates
```
@[simp] lemma equiv.trans_to_fun : ∀ {α β γ} (e₁ e₂) (a : α), ⇑(e₁.trans e₂) a = (⇑e₂ ∘ ⇑e₁) a
@[simp] lemma equiv.trans_inv_fun : ∀ {α β γ} (e₁ e₂) (a : γ),
⇑((e₁.trans e₂).symm) a = (⇑(e₁.symm) ∘ ⇑(e₂.symm)) a
```
* You can specify custom projection names, by specifying the new projection names using
`initialize_simps_projections`.
Example: `initialize_simps_projections equiv (to_fun → apply, inv_fun → symm_apply)`.
* If one of the fields itself is a structure, this command will recursively create
simp-lemmas for all fields in that structure.
* Exception: by default it will not recursively create simp-lemmas for fields in the structures
`prod` and `pprod`. Give explicit projection names to override this behavior.
Example:
```lean
structure my_prod (α β : Type*) := (fst : α) (snd : β)
@[simps] def foo : prod ℕ ℕ × my_prod ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩
```
generates
```lean
@[simp] lemma foo_fst : foo.fst = (1, 2)
@[simp] lemma foo_snd_fst : foo.snd.fst = 3
@[simp] lemma foo_snd_snd : foo.snd.snd = 4
```
* You can use `@[simps proj1 proj2 ...]` to only generate the projection lemmas for the specified
projections.
* Recursive projection names can be specified using `proj1_proj2_proj3`.
This will create a lemma of the form `foo.proj1.proj2.proj3 = ...`.
Example:
```lean
structure my_prod (α β : Type*) := (fst : α) (snd : β)
@[simps fst fst_fst snd] def foo : prod ℕ ℕ × my_prod ℕ ℕ := ⟨⟨1, 2⟩, 3, 4⟩
```
generates
```lean
@[simp] lemma foo_fst : foo.fst = (1, 2)
@[simp] lemma foo_fst_fst : foo.fst.fst = 1
@[simp] lemma foo_snd : foo.snd = {fst := 3, snd := 4}
```
* If one of the values is an eta-expanded structure, we will eta-reduce this structure.
Example:
```lean
structure equiv_plus_data (α β) extends α ≃ β := (data : bool)
@[simps] def bar {α} : equiv_plus_data α α := { data := tt, ..equiv.refl α }
```
generates the following, even though Lean inserts an eta-expanded version of `equiv.refl α` in the
definition of `bar`:
```lean
@[simp] lemma bar_to_equiv : ∀ {α : Sort u_1}, bar.to_equiv = equiv.refl α
@[simp] lemma bar_data : ∀ {α : Sort u_1}, bar.data = tt
```
* For configuration options, see the doc string of `simps_cfg`.
* The precise syntax is `('simps' ident* e)`, where `e` is an expression of type `simps_cfg`.
* `@[simps]` reduces let-expressions where necessary.
* If one of the fields is a partially applied constructor, we will eta-expand it
(this likely never happens).
* When option `trace.simps.verbose` is true, `simps` will print the projections it finds and the
lemmas it generates. The same can be achieved by using `@[simps?]`, except that in this case it
will not print projection information.
* Use `@[to_additive, simps]` to apply both `to_additive` and `simps` to a definition, making sure
that `simps` comes after `to_additive`. This will also generate the additive versions of all
simp-lemmas. Note however, that the additive versions of the simp-lemmas always use the default
name generated by `to_additive`, even if a custom name is given for the additive version of the
definition.
-/
@[user_attribute] meta def simps_attr : user_attribute unit (bool × list string × simps_cfg) :=
{ name := `simps,
descr := "Automatically derive lemmas specifying the projections of this declaration.",
parser := simps_parser,
after_set := some $
λ n _ persistent, do
guard persistent <|> fail "`simps` currently cannot be used as a local attribute",
(trc, todo, cfg) ← simps_attr.get_param n,
simps_tac n cfg todo trc }
add_tactic_doc
{ name := "simps",
category := doc_category.attr,
decl_names := [`simps_attr],
tags := ["simplification"] }
|
eea9fdb0ef8418d08ad2e718f96d16cfa1746b92 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/tactic/ring_exp.lean | c2c1fa4dfa40fea7137b843f2ebbd098b801df2c | [
"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 | 57,155 | lean | /-
Copyright (c) 2019 Tim Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Tim Baanen
Solve equations in commutative (semi)rings with exponents.
-/
import tactic.norm_num
import control.traversable.basic
/-!
# `ring_exp` tactic
A tactic for solving equations in commutative (semi)rings,
where the exponents can also contain variables.
More precisely, expressions of the following form are supported:
- constants (non-negative integers)
- variables
- coefficients (any rational number, embedded into the (semi)ring)
- addition of expressions
- multiplication of expressions
- exponentiation of expressions (the exponent must have type `ℕ`)
- subtraction and negation of expressions (if the base is a full ring)
The motivating example is proving `2 * 2^n * b = b * 2^(n+1)`,
something that the `ring` tactic cannot do, but `ring_exp` can.
## Implementation notes
The basic approach to prove equalities is to normalise both sides and check for equality.
The normalisation is guided by building a value in the type `ex` at the meta level,
together with a proof (at the base level) that the original value is equal to
the normalised version.
The normalised version and normalisation proofs are also stored in the `ex` type.
The outline of the file:
- Define an inductive family of types `ex`, parametrised over `ex_type`,
which can represent expressions with `+`, `*`, `^` and rational numerals.
The parametrisation over `ex_type` ensures that associativity and distributivity are applied,
by restricting which kinds of subexpressions appear as arguments to the various operators.
- Represent addition, multiplication and exponentiation in the `ex` type,
thus allowing us to map expressions to `ex` (the `eval` function drives this).
We apply associativity and distributivity of the operators here (helped by `ex_type`)
and commutativity as well (by sorting the subterms; unfortunately not helped by anything).
Any expression not of the above formats is treated as an atom (the same as a variable).
There are some details we glossed over which make the plan more complicated:
- The order on atoms is not initially obvious.
We construct a list containing them in order of initial appearance in the expression,
then use the index into the list as a key to order on.
- In the tactic, a normalized expression `ps : ex` lives in the meta-world,
but the normalization proofs live in the real world.
Thus, we cannot directly say `ps.orig = ps.pretty` anywhere,
but we have to carefully construct the proof when we compute `ps`.
This was a major source of bugs in development!
- For `pow`, the exponent must be a natural number, while the base can be any semiring `α`.
We swap out operations for the base ring `α` with those for the exponent ring `ℕ`
as soon as we deal with exponents.
This is accomplished by the `in_exponent` function and is relatively painless since
we work in a `reader` monad.
- The normalized form of an expression is the one that is useful for the tactic,
but not as nice to read. To remedy this, the user-facing normalization calls `ex.simp`.
## Caveats and future work
Subtraction cancels out identical terms, but division does not.
That is: `a - a = 0 := by ring_exp` solves the goal,
but `a / a := 1 by ring_exp` doesn't.
Note that `0 / 0` is generally defined to be `0`,
so division cancelling out is not true in general.
Multiplication of powers can be simplified a little bit further:
`2 ^ n * 2 ^ n = 4 ^ n := by ring_exp` could be implemented
in a similar way that `2 * a + 2 * a = 4 * a := by ring_exp` already works.
This feature wasn't needed yet, so it's not implemented yet.
## Tags
ring, semiring, exponent, power
-/
-- The base ring `α` will have a universe level `u`.
-- We do not introduce `α` as a variable yet,
-- in order to make it explicit or implicit as required.
universes u
namespace tactic.ring_exp
open nat
/--
The `atom` structure is used to represent atomic expressions:
those which `ring_exp` cannot parse any further.
For instance, `a + (a % b)` has `a` and `(a % b)` as atoms.
The `ring_exp_eq` tactic does not normalize the subexpressions in atoms,
but `ring_exp` does if `ring_exp_eq` was not sufficient.
Atoms in fact represent equivalence classes of expressions,
modulo definitional equality.
The field `index : ℕ` should be a unique number for each class,
while `value : expr` contains a representative of this class.
The function `resolve_atom` determines the appropriate atom
for a given expression.
-/
meta structure atom : Type := (value : expr) (index : ℕ)
namespace atom
/--
The `eq` operation on `atom`s works modulo definitional equality,
ignoring their `value`s.
The invariants on `atom` ensure indices are unique per value.
Thus, `eq` indicates equality as long as the `atom`s come from the same context.
-/
meta def eq (a b : atom) : bool := a.index = b.index
/--
We order `atom`s on the order of appearance in the main expression.
-/
meta def lt (a b : atom) : bool := a.index < b.index
meta instance : has_repr atom := ⟨λ x, "(atom " ++ repr x.2 ++ ")"⟩
end atom
section expression
/-!
### `expression` section
In this section, we define the `ex` type and its basic operations.
First, we introduce the supporting types `coeff`, `ex_type` and `ex_info`.
For understanding the code, it's easier to check out `ex` itself first,
then refer back to the supporting types.
The arithmetic operations on `ex` need additional definitions,
so they are defined in a later section.
-/
/--
Coefficients in the expression are stored in a wrapper structure,
allowing for easier modification of the data structures.
The modifications might be caching of the result of `expr.of_rat`,
or using a different meta representation of numerals.
-/
@[derive decidable_eq, derive inhabited]
structure coeff : Type := (value : ℚ)
/-- The values in `ex_type` are used as parameters to `ex` to control the expression's structure. -/
@[derive decidable_eq, derive inhabited]
inductive ex_type : Type
| base : ex_type
| sum : ex_type
| prod : ex_type
| exp : ex_type
open ex_type
/--
Each `ex` stores information for its normalization proof.
The `orig` expression is the expression that was passed to `eval`.
The `pretty` expression is the normalised form that the `ex` represents.
(I didn't call this something like `norm`, because there are already
too many things called `norm` in mathematics!)
The field `proof` contains an optional proof term of type `%%orig = %%pretty`.
The value `none` for the proof indicates that everything reduces to reflexivity.
(Which saves space in quite a lot of cases.)
-/
meta structure ex_info : Type :=
(orig : expr) (pretty : expr) (proof : option expr)
/--
The `ex` type is an abstract representation of an expression with `+`, `*` and `^`.
Those operators are mapped to the `sum`, `prod` and `exp` constructors respectively.
The `zero` constructor is the base case for `ex sum`, e.g. `1 + 2` is represented
by (something along the lines of) `sum 1 (sum 2 zero)`.
The `coeff` constructor is the base case for `ex prod`, and is used for numerals.
The code maintains the invariant that the coefficient is never `0`.
The `var` constructor is the base case for `ex exp`, and is used for atoms.
The `sum_b` constructor allows for addition in the base of an exponentiation;
it serves a similar purpose as the parentheses in `(a + b)^c`.
The code maintains the invariant that the argument to `sum_b` is not `zero`
or `sum _ zero`.
All of the constructors contain an `ex_info` field,
used to carry around (arguments to) proof terms.
While the `ex_type` parameter enforces some simplification invariants,
the following ones must be manually maintained at the risk of insufficient power:
- the argument to `coeff` must be nonzero (to ensure `0 = 0 * 1`)
- the argument to `sum_b` must be of the form `sum a (sum b bs)` (to ensure `(a + 0)^n = a^n`)
- normalisation proofs of subexpressions must be `refl ps.pretty`
- if we replace `sum` with `cons` and `zero` with `nil`, the resulting list is sorted
according to the `lt` relation defined further down; similarly for `prod` and `coeff`
(to ensure `a + b = b + a`).
The first two invariants could be encoded in a subtype of `ex`,
but aren't (yet) to spare some implementation burden.
The other invariants cannot be encoded because we need the `tactic` monad to check them.
(For example, the correct equality check of `expr` is `is_def_eq : expr → expr → tactic unit`.)
-/
meta inductive ex : ex_type → Type
| zero (info : ex_info) : ex sum
| sum (info : ex_info) : ex prod → ex sum → ex sum
| coeff (info : ex_info) : coeff → ex prod
| prod (info : ex_info) : ex exp → ex prod → ex prod
| var (info : ex_info) : atom → ex base
| sum_b (info : ex_info) : ex sum → ex base
| exp (info : ex_info) : ex base → ex prod → ex exp
/--
Return the proof information associated to the `ex`.
-/
meta def ex.info : Π {et : ex_type} (ps : ex et), ex_info
| sum (ex.zero i) := i
| sum (ex.sum i _ _) := i
| prod (ex.coeff i _) := i
| prod (ex.prod i _ _) := i
| base (ex.var i _) := i
| base (ex.sum_b i _) := i
| exp (ex.exp i _ _) := i
/--
Return the original, non-normalized version of this `ex`.
Note that arguments to another `ex` are always "pre-normalized":
their `orig` and `pretty` are equal, and their `proof` is reflexivity.
-/
meta def ex.orig {et : ex_type} (ps : ex et) : expr := ps.info.orig
/--
Return the normalized version of this `ex`.
-/
meta def ex.pretty {et : ex_type} (ps : ex et) : expr := ps.info.pretty
/--
Return the normalisation proof of the given expression.
If the proof is `refl`, we give `none` instead,
which helps to control the size of proof terms.
To get an actual term, use `ex.proof_term`,
or use `mk_proof` with the correct set of arguments.
-/
meta def ex.proof {et : ex_type} (ps : ex et) : option expr := ps.info.proof
/--
Update the `orig` and `proof` fields of the `ex_info`.
Intended for use in `ex.set_info`.
-/
meta def ex_info.set (i : ex_info) (o : option expr) (pf : option expr) : ex_info :=
{orig := o.get_or_else i.pretty, proof := pf, .. i}
/--
Update the `ex_info` of the given expression.
We use this to combine intermediate normalisation proofs.
Since `pretty` only depends on the subexpressions,
which do not change, we do not set `pretty`.
-/
meta def ex.set_info : Π {et : ex_type} (ps : ex et), option expr → option expr → ex et
| sum (ex.zero i) o pf := ex.zero (i.set o pf)
| sum (ex.sum i p ps) o pf := ex.sum (i.set o pf) p ps
| prod (ex.coeff i x) o pf := ex.coeff (i.set o pf) x
| prod (ex.prod i p ps) o pf := ex.prod (i.set o pf) p ps
| base (ex.var i x) o pf := ex.var (i.set o pf) x
| base (ex.sum_b i ps) o pf := ex.sum_b (i.set o pf) ps
| exp (ex.exp i p ps) o pf := ex.exp (i.set o pf) p ps
instance coeff_has_repr : has_repr coeff := ⟨λ x, repr x.1⟩
/-- Convert an `ex` to a `string`. -/
meta def ex.repr : Π {et : ex_type}, ex et → string
| sum (ex.zero _) := "0"
| sum (ex.sum _ p ps) := ex.repr p ++ " + " ++ ex.repr ps
| prod (ex.coeff _ x) := repr x
| prod (ex.prod _ p ps) := ex.repr p ++ " * " ++ ex.repr ps
| base (ex.var _ x) := repr x
| base (ex.sum_b _ ps) := "(" ++ ex.repr ps ++ ")"
| exp (ex.exp _ p ps) := ex.repr p ++ " ^ " ++ ex.repr ps
meta instance {et : ex_type} : has_repr (ex et) := ⟨ex.repr⟩
/--
Equality test for expressions.
Since equivalence of `atom`s is not the same as equality,
we cannot make a true `(=)` operator for `ex` either.
-/
meta def ex.eq : Π {et : ex_type}, ex et → ex et → bool
| sum (ex.zero _) (ex.zero _) := tt
| sum (ex.zero _) (ex.sum _ _ _) := ff
| sum (ex.sum _ _ _) (ex.zero _) := ff
| sum (ex.sum _ p ps) (ex.sum _ q qs) := p.eq q && ps.eq qs
| prod (ex.coeff _ x) (ex.coeff _ y) := x = y
| prod (ex.coeff _ _) (ex.prod _ _ _) := ff
| prod (ex.prod _ _ _) (ex.coeff _ _) := ff
| prod (ex.prod _ p ps) (ex.prod _ q qs) := p.eq q && ps.eq qs
| base (ex.var _ x) (ex.var _ y) := x.eq y
| base (ex.var _ _) (ex.sum_b _ _) := ff
| base (ex.sum_b _ _) (ex.var _ _) := ff
| base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.eq qs
| exp (ex.exp _ p ps) (ex.exp _ q qs) := p.eq q && ps.eq qs
/--
The ordering on expressions.
As for `ex.eq`, this is a linear order only in one context.
-/
meta def ex.lt : Π {et : ex_type}, ex et → ex et → bool
| sum _ (ex.zero _) := ff
| sum (ex.zero _) _ := tt
| sum (ex.sum _ p ps) (ex.sum _ q qs) := p.lt q || (p.eq q && ps.lt qs)
| prod (ex.coeff _ x) (ex.coeff _ y) := x.1 < y.1
| prod (ex.coeff _ _) _ := tt
| prod _ (ex.coeff _ _) := ff
| prod (ex.prod _ p ps) (ex.prod _ q qs) := p.lt q || (p.eq q && ps.lt qs)
| base (ex.var _ x) (ex.var _ y) := x.lt y
| base (ex.var _ _) (ex.sum_b _ _) := tt
| base (ex.sum_b _ _) (ex.var _ _) := ff
| base (ex.sum_b _ ps) (ex.sum_b _ qs) := ps.lt qs
| exp (ex.exp _ p ps) (ex.exp _ q qs) := p.lt q || (p.eq q && ps.lt qs)
end expression
section operations
/-!
### `operations` section
This section defines the operations (on `ex`) that use tactics.
They live in the `ring_exp_m` monad,
which adds a cache and a list of encountered atoms to the `tactic` monad.
Throughout this section, we will be constructing proof terms.
The lemmas used in the construction are all defined over a commutative semiring α.
-/
variables {α : Type u} [comm_semiring α]
open tactic
open ex_type
/--
Stores the information needed in the `eval` function and its dependencies,
so they can (re)construct expressions.
The `eval_info` structure stores this information for one type,
and the `context` combines the two types, one for bases and one for exponents.
-/
meta structure eval_info :=
(α : expr) (univ : level)
-- Cache the instances for optimization and consistency
(csr_instance : expr) (ha_instance : expr) (hm_instance : expr) (hp_instance : expr)
-- Optional instances (only required for (-) and (/) respectively)
(ring_instance : option expr) (dr_instance : option expr)
-- Cache common constants.
(zero : expr) (one : expr)
/--
The `context` contains the full set of information needed for the `eval` function.
This structure has two copies of `eval_info`:
one is for the base (typically some semiring `α`) and another for the exponent (always `ℕ`).
When evaluating an exponent, we put `info_e` in `info_b`.
-/
meta structure context :=
(info_b : eval_info) (info_e : eval_info) (transp : transparency)
/--
The `ring_exp_m` monad is used instead of `tactic` to store the context.
-/
@[derive [monad, alternative]]
meta def ring_exp_m (α : Type) : Type := reader_t context (state_t (list atom) tactic) α
/--
Access the instance cache.
-/
meta def get_context : ring_exp_m context := reader_t.read
/--
Lift an operation in the `tactic` monad to the `ring_exp_m` monad.
This operation will not access the cache.
-/
meta def lift {α} (m : tactic α) : ring_exp_m α := reader_t.lift (state_t.lift m)
/--
Change the context of the given computation,
so that expressions are evaluated in the exponent ring,
instead of the base ring.
-/
meta def in_exponent {α} (mx : ring_exp_m α) : ring_exp_m α := do
ctx ← get_context,
reader_t.lift $ mx.run ⟨ctx.info_e, ctx.info_e, ctx.transp⟩
/--
Specialized version of `mk_app` where the first two arguments are `{α}` `[some_class α]`.
Should be faster because it can use the cached instances.
-/
meta def mk_app_class (f : name) (inst : expr) (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
pure $ (@expr.const tt f [ctx.info_b.univ] ctx.info_b.α inst).mk_app args
/--
Specialized version of `mk_app` where the first two arguments are `{α}` `[comm_semiring α]`.
Should be faster because it can use the cached instances.
-/
meta def mk_app_csr (f : name) (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class f (ctx.info_b.csr_instance) args
/--
Specialized version of `mk_app ``has_add.add`.
Should be faster because it can use the cached instances.
-/
meta def mk_add (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class ``has_add.add ctx.info_b.ha_instance args
/--
Specialized version of `mk_app ``has_mul.mul`.
Should be faster because it can use the cached instances.
-/
meta def mk_mul (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
mk_app_class ``has_mul.mul ctx.info_b.hm_instance args
/--
Specialized version of `mk_app ``has_pow.pow`.
Should be faster because it can use the cached instances.
-/
meta def mk_pow (args : list expr) : ring_exp_m expr := do
ctx ← get_context,
pure $ (@expr.const tt ``has_pow.pow
[ctx.info_b.univ, ctx.info_e.univ]
ctx.info_b.α ctx.info_e.α
ctx.info_b.hp_instance).mk_app args
/-- Construct a normalization proof term or return the cached one. -/
meta def ex_info.proof_term (ps : ex_info) : ring_exp_m expr :=
match ps.proof with
| none := lift $ tactic.mk_eq_refl ps.pretty
| (some p) := pure p
end
/-- Construct a normalization proof term or return the cached one. -/
meta def ex.proof_term {et : ex_type} (ps : ex et) : ring_exp_m expr := ps.info.proof_term
/--
If all `ex_info` have trivial proofs, return a trivial proof.
Otherwise, construct all proof terms.
Useful in applications where trivial proofs combine to another trivial proof,
most importantly to pass to `mk_proof_or_refl`.
-/
meta def none_or_proof_term : list ex_info → ring_exp_m (option (list expr))
| [] := pure none
| (x :: xs) := do
xs_pfs ← none_or_proof_term xs,
match (x.proof, xs_pfs) with
| (none, none) := pure none
| (some x_pf, none) := do
xs_pfs ← traverse ex_info.proof_term xs,
pure (some (x_pf :: xs_pfs))
| (_, some xs_pfs) := do
x_pf ← x.proof_term,
pure (some (x_pf :: xs_pfs))
end
/--
Use the proof terms as arguments to the given lemma.
If the lemma could reduce to reflexivity, consider using `mk_proof_or_refl.`
-/
meta def mk_proof (lem : name) (args : list expr) (hs : list ex_info) : ring_exp_m expr := do
hs' ← traverse ex_info.proof_term hs,
mk_app_csr lem (args ++ hs')
/--
Use the proof terms as arguments to the given lemma.
Often, we construct a proof term using congruence where reflexivity suffices.
To solve this, the following function tries to get away with reflexivity.
-/
meta def mk_proof_or_refl (term : expr) (lem : name) (args : list expr) (hs : list ex_info) :
ring_exp_m expr := do
hs_full ← none_or_proof_term hs,
match hs_full with
| none := lift $ mk_eq_refl term
| (some hs') := mk_app_csr lem (args ++ hs')
end
/-- A shortcut for adding the original terms of two expressions. -/
meta def add_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_add [ps.orig, qs.orig]
/-- A shortcut for multiplying the original terms of two expressions. -/
meta def mul_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_mul [ps.orig, qs.orig]
/-- A shortcut for exponentiating the original terms of two expressions. -/
meta def pow_orig {et et'} (ps : ex et) (qs : ex et') : ring_exp_m expr :=
mk_pow [ps.orig, qs.orig]
/-- Congruence lemma for constructing `ex.sum`. -/
lemma sum_congr {p p' ps ps' : α} : p = p' → ps = ps' → p + ps = p' + ps' := by cc
/-- Congruence lemma for constructing `ex.prod`. -/
lemma prod_congr {p p' ps ps' : α} : p = p' → ps = ps' → p * ps = p' * ps' := by cc
/-- Congruence lemma for constructing `ex.exp`. -/
lemma exp_congr {p p' : α} {ps ps' : ℕ} : p = p' → ps = ps' → p ^ ps = p' ^ ps' := by cc
/-- Constructs `ex.zero` with the correct arguments. -/
meta def ex_zero : ring_exp_m (ex sum) := do
ctx ← get_context,
pure $ ex.zero ⟨ctx.info_b.zero, ctx.info_b.zero, none⟩
/-- Constructs `ex.sum` with the correct arguments. -/
meta def ex_sum (p : ex prod) (ps : ex sum) : ring_exp_m (ex sum) := do
pps_o ← add_orig p ps,
pps_p ← mk_add [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``sum_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.sum ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
/--
Constructs `ex.coeff` with the correct arguments.
There are more efficient constructors for specific numerals:
if `x = 0`, you should use `ex_zero`; if `x = 1`, use `ex_one`.
-/
meta def ex_coeff (x : rat) : ring_exp_m (ex prod) := do
ctx ← get_context,
x_p ← lift $ expr.of_rat ctx.info_b.α x,
pure (ex.coeff ⟨x_p, x_p, none⟩ ⟨x⟩)
/--
Constructs `ex.coeff 1` with the correct arguments.
This is a special case for optimization purposes.
-/
meta def ex_one : ring_exp_m (ex prod) := do
ctx ← get_context,
pure $ ex.coeff ⟨ctx.info_b.one, ctx.info_b.one, none⟩ ⟨1⟩
/-- Constructs `ex.prod` with the correct arguments. -/
meta def ex_prod (p : ex exp) (ps : ex prod) : ring_exp_m (ex prod) := do
pps_o ← mul_orig p ps,
pps_p ← mk_mul [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``prod_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.prod ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
/-- Constructs `ex.var` with the correct arguments. -/
meta def ex_var (p : atom) : ring_exp_m (ex base) := pure (ex.var ⟨p.1, p.1, none⟩ p)
/-- Constructs `ex.sum_b` with the correct arguments. -/
meta def ex_sum_b (ps : ex sum) : ring_exp_m (ex base) :=
pure (ex.sum_b ps.info (ps.set_info none none))
/-- Constructs `ex.exp` with the correct arguments. -/
meta def ex_exp (p : ex base) (ps : ex prod) : ring_exp_m (ex exp) := do
ctx ← get_context,
pps_o ← pow_orig p ps,
pps_p ← mk_pow [p.pretty, ps.pretty],
pps_pf ← mk_proof_or_refl pps_p ``exp_congr
[p.orig, p.pretty, ps.orig, ps.pretty]
[p.info, ps.info],
pure (ex.exp ⟨pps_o, pps_p, pps_pf⟩ (p.set_info none none) (ps.set_info none none))
lemma base_to_exp_pf {p p' : α} : p = p' → p = p' ^ 1 := by simp
/-- Conversion from `ex base` to `ex exp`. -/
meta def base_to_exp (p : ex base) : ring_exp_m (ex exp) := do
o ← in_exponent $ ex_one,
ps ← ex_exp p o,
pf ← mk_proof ``base_to_exp_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma exp_to_prod_pf {p p' : α} : p = p' → p = p' * 1 := by simp
/-- Conversion from `ex exp` to `ex prod`. -/
meta def exp_to_prod (p : ex exp) : ring_exp_m (ex prod) := do
o ← ex_one,
ps ← ex_prod p o,
pf ← mk_proof ``exp_to_prod_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma prod_to_sum_pf {p p' : α} : p = p' → p = p' + 0 := by simp
/-- Conversion from `ex prod` to `ex sum`. -/
meta def prod_to_sum (p : ex prod) : ring_exp_m (ex sum) := do
z ← ex_zero,
ps ← ex_sum p z,
pf ← mk_proof ``prod_to_sum_pf [p.orig, p.pretty] [p.info],
pure $ ps.set_info p.orig pf
lemma atom_to_sum_pf (p : α) : p = p ^ 1 * 1 + 0 := by simp
/--
A more efficient conversion from `atom` to `ex sum`.
The result should be the same as `ex_var p >>= base_to_exp >>= exp_to_prod >>= prod_to_sum`,
except we need to calculate less intermediate steps.
-/
meta def atom_to_sum (p : atom) : ring_exp_m (ex sum) := do
p' ← ex_var p,
o ← in_exponent $ ex_one,
p' ← ex_exp p' o,
o ← ex_one,
p' ← ex_prod p' o,
z ← ex_zero,
p' ← ex_sum p' z,
pf ← mk_proof ``atom_to_sum_pf [p.1] [],
pure $ p'.set_info p.1 pf
/--
Compute the sum of two coefficients.
Note that the result might not be a valid expression:
if `p = -q`, then the result should be `ex.zero : ex sum` instead.
The caller must detect when this happens!
The returned value is of the form `ex.coeff _ (p + q)`,
with the proof of `expr.of_rat p + expr.of_rat q = expr.of_rat (p + q)`.
-/
meta def add_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do
ctx ← get_context,
pq_o ← mk_add [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_field pq_o,
pure $ ex.coeff ⟨pq_o, pq_p, pq_pf⟩ ⟨p.1 + q.1⟩
lemma mul_coeff_pf_one_mul (q : α) : 1 * q = q := one_mul q
lemma mul_coeff_pf_mul_one (p : α) : p * 1 = p := mul_one p
/--
Compute the product of two coefficients.
The returned value is of the form `ex.coeff _ (p * q)`,
with the proof of `expr.of_rat p * expr.of_rat q = expr.of_rat (p * q)`.
-/
meta def mul_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) :=
match p.1, q.1 with -- Special case to speed up multiplication with 1.
| ⟨1, 1, _, _⟩, _ := do
ctx ← get_context,
pq_o ← mk_mul [p_p, q_p],
pf ← mk_app_csr ``mul_coeff_pf_one_mul [q_p],
pure $ ex.coeff ⟨pq_o, q_p, pf⟩ ⟨q.1⟩
| _, ⟨1, 1, _, _⟩ := do
ctx ← get_context,
pq_o ← mk_mul [p_p, q_p],
pf ← mk_app_csr ``mul_coeff_pf_mul_one [p_p],
pure $ ex.coeff ⟨pq_o, p_p, pf⟩ ⟨p.1⟩
| _, _ := do
ctx ← get_context,
pq' ← mk_mul [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_field pq',
pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩
end
section rewrite
/-! ### `rewrite` section
In this section we deal with rewriting terms to fit in the basic grammar of `eval`.
For example, `nat.succ n` is rewritten to `n + 1` before it is evaluated further.
-/
/-- Given a proof that the expressions `ps_o` and `ps'.orig` are equal,
show that `ps_o` and `ps'.pretty` are equal.
Useful to deal with aliases in `eval`. For instance, `nat.succ p` can be handled
as an alias of `p + 1` as follows:
```
| ps_o@`(nat.succ %%p_o) := do
ps' ← eval `(%%p_o + 1),
pf ← lift $ mk_app ``nat.succ_eq_add_one [p_o],
rewrite ps_o ps' pf
```
-/
meta def rewrite (ps_o : expr) (ps' : ex sum) (pf : expr) : ring_exp_m (ex sum) :=
do
ps'_pf ← ps'.info.proof_term,
pf ← lift $ mk_eq_trans pf ps'_pf,
pure $ ps'.set_info ps_o pf
end rewrite
/--
Represents the way in which two products are equal except coefficient.
This type is used in the function `add_overlap`.
In order to deal with equations of the form `a * 2 + a = 3 * a`,
the `add` function will add up overlapping products,
turning `a * 2 + a` into `a * 3`.
We need to distinguish `a * 2 + a` from `a * 2 + b` in order to do this,
and the `overlap` type carries the information on how it overlaps.
The case `none` corresponds to non-overlapping products, e.g. `a * 2 + b`;
the case `nonzero` to overlapping products adding to non-zero, e.g. `a * 2 + a`
(the `ex prod` field will then look like `a * 3` with a proof that `a * 2 + a = a * 3`);
the case `zero` to overlapping products adding to zero, e.g. `a * 2 + a * -2`.
We distinguish those two cases because in the second, the whole product reduces to `0`.
A potential extension to the tactic would also do this for the base of exponents,
e.g. to show `2^n * 2^n = 4^n`.
-/
meta inductive overlap : Type
| none : overlap
| nonzero : ex prod → overlap
| zero : ex sum → overlap
lemma add_overlap_pf {ps qs pq} (p : α) : ps + qs = pq → p * ps + p * qs = p * pq := λ pq_pf, calc
p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _)
... = p * pq : by rw pq_pf
lemma add_overlap_pf_zero {ps qs} (p : α) : ps + qs = 0 → p * ps + p * qs = 0 := λ pq_pf, calc
p * ps + p * qs = p * (ps + qs) : symm (mul_add _ _ _)
... = p * 0 : by rw pq_pf
... = 0 : mul_zero _
/--
Given arguments `ps`, `qs` of the form `ps' * x` and `ps' * y` respectively
return `ps + qs = ps' * (x + y)` (with `x` and `y` arbitrary coefficients).
For other arguments, return `overlap.none`.
-/
meta def add_overlap : ex prod → ex prod → ring_exp_m overlap
| (ex.coeff x_i x) (ex.coeff y_i y) := do
xy@(ex.coeff _ xy_c) ← add_coeff x_i.pretty y_i.pretty x y
| lift $ fail "internal error: add_coeff should return ex.coeff",
if xy_c.1 = 0
then do
z ← ex_zero,
pure $ overlap.zero (z.set_info xy.orig xy.proof)
else pure $ overlap.nonzero xy
| (ex.prod _ _ _) (ex.coeff _ _) := pure overlap.none
| (ex.coeff _ _) (ex.prod _ _ _) := pure overlap.none
| pps@(ex.prod _ p ps) qqs@(ex.prod _ q qs) := if p.eq q
then do
pq_ol ← add_overlap ps qs,
pqs_o ← add_orig pps qqs,
match pq_ol with
| overlap.none := pure overlap.none
| (overlap.nonzero pq) := do
pqs ← ex_prod p pq,
pf ← mk_proof ``add_overlap_pf
[ps.pretty, qs.pretty, pq.pretty, p.pretty]
[pq.info],
pure $ overlap.nonzero (pqs.set_info pqs_o pf)
| (overlap.zero pq) := do
z ← ex_zero,
pf ← mk_proof ``add_overlap_pf_zero
[ps.pretty, qs.pretty, p.pretty]
[pq.info],
pure $ overlap.zero (z.set_info pqs_o pf)
end
else pure overlap.none
section addition
lemma add_pf_z_sum {ps qs qs' : α} : ps = 0 → qs = qs' → ps + qs = qs' := λ ps_pf qs_pf, calc
ps + qs = 0 + qs' : by rw [ps_pf, qs_pf]
... = qs' : zero_add _
lemma add_pf_sum_z {ps ps' qs : α} : ps = ps' → qs = 0 → ps + qs = ps' := λ ps_pf qs_pf, calc
ps + qs = ps' + 0 : by rw [ps_pf, qs_pf]
... = ps' : add_zero _
lemma add_pf_sum_overlap {pps p ps qqs q qs pq pqs : α} :
pps = p + ps → qqs = q + qs → p + q = pq → ps + qs = pqs → pps + qqs = pq + pqs := by cc
lemma add_pf_sum_overlap_zero {pps p ps qqs q qs pqs : α} :
pps = p + ps → qqs = q + qs → p + q = 0 → ps + qs = pqs → pps + qqs = pqs :=
λ pps_pf qqs_pf pq_pf pqs_pf, calc
pps + qqs = (p + ps) + (q + qs) : by rw [pps_pf, qqs_pf]
... = (p + q) + (ps + qs) : by cc
... = 0 + pqs : by rw [pq_pf, pqs_pf]
... = pqs : zero_add _
lemma add_pf_sum_lt {pps p ps qqs pqs : α} :
pps = p + ps → ps + qqs = pqs → pps + qqs = p + pqs := by cc
lemma add_pf_sum_gt {pps qqs q qs pqs : α} :
qqs = q + qs → pps + qs = pqs → pps + qqs = q + pqs := by cc
/--
Add two expressions.
* `0 + qs = 0`
* `ps + 0 = 0`
* `ps * x + ps * y = ps * (x + y)` (for `x`, `y` coefficients; uses `add_overlap`)
* `(p + ps) + (q + qs) = p + (ps + (q + qs))` (if `p.lt q`)
* `(p + ps) + (q + qs) = q + ((p + ps) + qs)` (if not `p.lt q`)
-/
meta def add : ex sum → ex sum → ring_exp_m (ex sum)
| ps@(ex.zero ps_i) qs := do
pf ← mk_proof ``add_pf_z_sum [ps.orig, qs.orig, qs.pretty] [ps.info, qs.info],
pqs_o ← add_orig ps qs,
pure $ qs.set_info pqs_o pf
| ps qs@(ex.zero qs_i) := do
pf ← mk_proof ``add_pf_sum_z [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info],
pqs_o ← add_orig ps qs,
pure $ ps.set_info pqs_o pf
| pps@(ex.sum pps_i p ps) qqs@(ex.sum qqs_i q qs) := do
ol ← add_overlap p q,
ppqqs_o ← add_orig pps qqs,
match ol with
| (overlap.nonzero pq) := do
pqs ← add ps qs,
pqqs ← ex_sum pq pqs,
qqs_pf ← qqs.proof_term,
pf ← mk_proof ``add_pf_sum_overlap
[pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pq.pretty, pqs.pretty]
[pps.info, qqs.info, pq.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
| (overlap.zero pq) := do
pqs ← add ps qs,
pf ← mk_proof ``add_pf_sum_overlap_zero
[pps.orig, p.pretty, ps.pretty, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[pps.info, qqs.info, pq.info, pqs.info],
pure $ pqs.set_info ppqqs_o pf
| overlap.none := if p.lt q
then do
pqs ← add ps qqs,
ppqs ← ex_sum p pqs,
pf ← mk_proof ``add_pf_sum_lt
[pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqqs_o pf
else do
pqs ← add pps qs,
pqqs ← ex_sum q pqs,
pf ← mk_proof ``add_pf_sum_gt
[pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
end
end addition
section multiplication
lemma mul_pf_c_c {ps ps' qs qs' pq : α} :
ps = ps' → qs = qs' → ps' * qs' = pq → ps * qs = pq := by cc
lemma mul_pf_c_prod {ps qqs q qs pqs : α} :
qqs = q * qs → ps * qs = pqs → ps * qqs = q * pqs := by cc
lemma mul_pf_prod_c {pps p ps qs pqs : α} :
pps = p * ps → ps * qs = pqs → pps * qs = p * pqs := by cc
lemma mul_pp_pf_overlap {pps p_b ps qqs qs psqs : α} {p_e q_e : ℕ} :
pps = p_b ^ p_e * ps → qqs = p_b ^ q_e * qs →
p_b ^ (p_e + q_e) * (ps * qs) = psqs → pps * qqs = psqs
:= λ ps_pf qs_pf psqs_pf, by simp [symm psqs_pf, pow_add, ps_pf, qs_pf]; ac_refl
lemma mul_pp_pf_prod_lt {pps p ps qqs pqs : α} :
pps = p * ps → ps * qqs = pqs → pps * qqs = p * pqs := by cc
lemma mul_pp_pf_prod_gt {pps qqs q qs pqs : α} :
qqs = q * qs → pps * qs = pqs → pps * qqs = q * pqs := by cc
/--
Multiply two expressions.
* `x * y = (x * y)` (for `x`, `y` coefficients)
* `x * (q * qs) = q * (qs * x)` (for `x` coefficient)
* `(p * ps) * y = p * (ps * y)` (for `y` coefficient)
* `(p_b^p_e * ps) * (p_b^q_e * qs) = p_b^(p_e + q_e) * (ps * qs)`
(if `p_e` and `q_e` are identical except coefficient)
* `(p * ps) * (q * qs) = p * (ps * (q * qs))` (if `p.lt q`)
* `(p * ps) * (q * qs) = q * ((p * ps) * qs)` (if not `p.lt q`)
-/
meta def mul_pp : ex prod → ex prod → ring_exp_m (ex prod)
| ps@(ex.coeff _ x) qs@(ex.coeff _ y) := do
pq ← mul_coeff ps.pretty qs.pretty x y,
pq_o ← mul_orig ps qs,
pf ← mk_proof_or_refl pq.pretty ``mul_pf_c_c
[ps.orig, ps.pretty, qs.orig, qs.pretty, pq.pretty]
[ps.info, qs.info, pq.info],
pure $ pq.set_info pq_o pf
| ps@(ex.coeff _ x) qqs@(ex.prod _ q qs) := do
pqs ← mul_pp ps qs,
pqqs ← ex_prod q pqs,
pqqs_o ← mul_orig ps qqs,
pf ← mk_proof ``mul_pf_c_prod
[ps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info pqqs_o pf
| pps@(ex.prod _ p ps) qs@(ex.coeff _ y) := do
pqs ← mul_pp ps qs,
ppqs ← ex_prod p pqs,
ppqs_o ← mul_orig pps qs,
pf ← mk_proof ``mul_pf_prod_c
[pps.orig, p.pretty, ps.pretty, qs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqs_o pf
| pps@(ex.prod _ p@(ex.exp _ p_b p_e) ps) qqs@(ex.prod _ q@(ex.exp _ q_b q_e) qs) := do
ppqqs_o ← mul_orig pps qqs,
pq_ol ← in_exponent $ add_overlap p_e q_e,
match pq_ol, p_b.eq q_b with
| (overlap.nonzero pq_e), tt := do
psqs ← mul_pp ps qs,
pq ← ex_exp p_b pq_e,
ppsqqs ← ex_prod pq psqs,
pf ← mk_proof ``mul_pp_pf_overlap
[pps.orig, p_b.pretty, ps.pretty, qqs.orig, qs.pretty, ppsqqs.pretty, p_e.pretty, q_e.pretty]
[pps.info, qqs.info, ppsqqs.info],
pure $ ppsqqs.set_info ppqqs_o pf
| _, _ := if p.lt q then do
pqs ← mul_pp ps qqs,
ppqs ← ex_prod p pqs,
pf ← mk_proof ``mul_pp_pf_prod_lt
[pps.orig, p.pretty, ps.pretty, qqs.orig, pqs.pretty]
[pps.info, pqs.info],
pure $ ppqs.set_info ppqqs_o pf
else do
pqs ← mul_pp pps qs,
pqqs ← ex_prod q pqs,
pf ← mk_proof ``mul_pp_pf_prod_gt
[pps.orig, qqs.orig, q.pretty, qs.pretty, pqs.pretty]
[qqs.info, pqs.info],
pure $ pqqs.set_info ppqqs_o pf
end
lemma mul_p_pf_zero {ps qs : α} : ps = 0 → ps * qs = 0 :=
λ ps_pf, by rw [ps_pf, zero_mul]
lemma mul_p_pf_sum {pps p ps qs ppsqs : α} : pps = p + ps →
p * qs + ps * qs = ppsqs → pps * qs = ppsqs := λ pps_pf ppsqs_pf, calc
pps * qs = (p + ps) * qs : by rw [pps_pf]
... = p * qs + ps * qs : add_mul _ _ _
... = ppsqs : ppsqs_pf
/--
Multiply two expressions.
* `0 * qs = 0`
* `(p + ps) * qs = (p * qs) + (ps * qs)`
-/
meta def mul_p : ex sum → ex prod → ring_exp_m (ex sum)
| ps@(ex.zero ps_i) qs := do
z ← ex_zero,
z_o ← mul_orig ps qs,
pf ← mk_proof ``mul_p_pf_zero [ps.orig, qs.orig] [ps.info],
pure $ z.set_info z_o pf
| pps@(ex.sum pps_i p ps) qs := do
pqs ← mul_pp p qs >>= prod_to_sum,
psqs ← mul_p ps qs,
ppsqs ← add pqs psqs,
pps_pf ← pps.proof_term,
ppsqs_o ← mul_orig pps qs,
ppsqs_pf ← ppsqs.proof_term,
pf ← mk_proof ``mul_p_pf_sum
[pps.orig, p.pretty, ps.pretty, qs.orig, ppsqs.pretty]
[pps.info, ppsqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma mul_pf_zero {ps qs : α} : qs = 0 → ps * qs = 0 :=
λ qs_pf, by rw [qs_pf, mul_zero]
lemma mul_pf_sum {ps qqs q qs psqqs : α} : qqs = q + qs → ps * q + ps * qs = psqqs →
ps * qqs = psqqs := λ qs_pf psqqs_pf, calc
ps * qqs = ps * (q + qs) : by rw [qs_pf]
... = ps * q + ps * qs : mul_add _ _ _
... = psqqs : psqqs_pf
/--
Multiply two expressions.
* `ps * 0 = 0`
* `ps * (q + qs) = (ps * q) + (ps * qs)`
-/
meta def mul : ex sum → ex sum → ring_exp_m (ex sum)
| ps qs@(ex.zero qs_i) := do
z ← ex_zero,
z_o ← mul_orig ps qs,
pf ← mk_proof ``mul_pf_zero [ps.orig, qs.orig] [qs.info],
pure $ z.set_info z_o pf
| ps qqs@(ex.sum qqs_i q qs) := do
psq ← mul_p ps q,
psqs ← mul ps qs,
psqqs ← add psq psqs,
psqqs_o ← mul_orig ps qqs,
pf ← mk_proof ``mul_pf_sum
[ps.orig, qqs.orig, q.orig, qs.orig, psqqs.pretty]
[qqs.info, psqqs.info],
pure $ psqqs.set_info psqqs_o pf
end multiplication
section exponentiation
lemma pow_e_pf_exp {pps p : α} {ps qs psqs : ℕ} :
pps = p ^ ps → ps * qs = psqs → pps ^ qs = p ^ psqs :=
λ pps_pf psqs_pf, calc
pps ^ qs = (p ^ ps) ^ qs : by rw [pps_pf]
... = p ^ (ps * qs) : symm (pow_mul _ _ _)
... = p ^ psqs : by rw [psqs_pf]
/--
Compute the exponentiation of two coefficients.
The returned value is of the form `ex.coeff _ (p ^ q)`,
with the proof of `expr.of_rat p ^ expr.of_rat q = expr.of_rat (p ^ q)`.
-/
meta def pow_coeff (p_p q_p : expr) (p q : coeff) : ring_exp_m (ex prod) := do
ctx ← get_context,
pq' ← mk_pow [p_p, q_p],
(pq_p, pq_pf) ← lift $ norm_num.eval_pow pq',
pure $ ex.coeff ⟨pq_p, pq_p, pq_pf⟩ ⟨p.1 * q.1⟩
/--
Exponentiate two expressions.
* `(p ^ ps) ^ qs = p ^ (ps * qs)`
-/
meta def pow_e : ex exp → ex prod → ring_exp_m (ex exp)
| pps@(ex.exp pps_i p ps) qs := do
psqs ← in_exponent $ mul_pp ps qs,
ppsqs ← ex_exp p psqs,
ppsqs_o ← pow_orig pps qs,
pf ← mk_proof ``pow_e_pf_exp
[pps.orig, p.pretty, ps.pretty, qs.orig, psqs.pretty]
[pps.info, psqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma pow_pp_pf_one {ps : α} {qs : ℕ} : ps = 1 → ps ^ qs = 1 :=
λ ps_pf, by rw [ps_pf, one_pow]
lemma pow_pf_c_c {ps ps' pq : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps' ^ qs' = pq → ps ^ qs = pq := by cc
lemma pow_pp_pf_c {ps ps' pqs : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps' ^ qs' = pqs → ps ^ qs = pqs * 1 :=
by simp; cc
lemma pow_pp_pf_prod {pps p ps pqs psqs : α} {qs : ℕ} : pps = p * ps →
p ^ qs = pqs → ps ^ qs = psqs → pps ^ qs = pqs * psqs :=
λ pps_pf pqs_pf psqs_pf, calc
pps ^ qs = (p * ps) ^ qs : by rw [pps_pf]
... = p ^ qs * ps ^ qs : mul_pow _ _ _
... = pqs * psqs : by rw [pqs_pf, psqs_pf]
/--
Exponentiate two expressions.
* `1 ^ qs = 1`
* `x ^ qs = x ^ qs` (for `x` coefficient)
* `(p * ps) ^ qs = p ^ qs + ps ^ qs`
-/
meta def pow_pp : ex prod → ex prod → ring_exp_m (ex prod)
| ps@(ex.coeff ps_i ⟨⟨1, 1, _, _⟩⟩) qs := do
o ← ex_one,
o_o ← pow_orig ps qs,
pf ← mk_proof ``pow_pp_pf_one [ps.orig, qs.orig] [ps.info],
pure $ o.set_info o_o pf
| ps@(ex.coeff ps_i x) qs@(ex.coeff qs_i y) := do
pq ← pow_coeff ps.pretty qs.pretty x y,
pq_o ← pow_orig ps qs,
pf ← mk_proof_or_refl pq.pretty ``pow_pf_c_c
[ps.orig, ps.pretty, pq.pretty, qs.orig, qs.pretty]
[ps.info, qs.info, pq.info],
pure $ pq.set_info pq_o pf
| ps@(ex.coeff ps_i x) qs := do
ps'' ← pure ps >>= prod_to_sum >>= ex_sum_b,
pqs ← ex_exp ps'' qs,
pqs_o ← pow_orig ps qs,
pf ← mk_proof_or_refl pqs.pretty ``pow_pp_pf_c
[ps.orig, ps.pretty, pqs.pretty, qs.orig, qs.pretty]
[ps.info, qs.info, pqs.info],
pqs' ← exp_to_prod pqs,
pure $ pqs'.set_info pqs_o pf
| pps@(ex.prod pps_i p ps) qs := do
pqs ← pow_e p qs,
psqs ← pow_pp ps qs,
ppsqs ← ex_prod pqs psqs,
ppsqs_o ← pow_orig pps qs,
pf ← mk_proof ``pow_pp_pf_prod
[pps.orig, p.pretty, ps.pretty, pqs.pretty, psqs.pretty, qs.orig]
[pps.info, pqs.info, psqs.info],
pure $ ppsqs.set_info ppsqs_o pf
lemma pow_p_pf_one {ps ps' : α} {qs : ℕ} : ps = ps' → qs = succ zero → ps ^ qs = ps' :=
λ ps_pf qs_pf, calc
ps ^ qs = ps' ^ 1 : by rw [ps_pf, qs_pf]
... = ps' : pow_one _
lemma pow_p_pf_zero {ps : α} {qs qs' : ℕ} : ps = 0 → qs = succ qs' → ps ^ qs = 0 :=
λ ps_pf qs_pf, calc
ps ^ qs = 0 ^ (succ qs') : by rw [ps_pf, qs_pf]
... = 0 : zero_pow (succ_pos qs')
lemma pow_p_pf_succ {ps pqqs : α} {qs qs' : ℕ} :
qs = succ qs' → ps * ps ^ qs' = pqqs → ps ^ qs = pqqs :=
λ qs_pf pqqs_pf, calc
ps ^ qs = ps ^ succ qs' : by rw [qs_pf]
... = ps * ps ^ qs' : pow_succ _ _
... = pqqs : by rw [pqqs_pf]
lemma pow_p_pf_singleton {pps p pqs : α} {qs : ℕ} :
pps = p + 0 → p ^ qs = pqs → pps ^ qs = pqs :=
λ pps_pf pqs_pf, by rw [pps_pf, add_zero, pqs_pf]
lemma pow_p_pf_cons {ps ps' : α} {qs qs' : ℕ} :
ps = ps' → qs = qs' → ps ^ qs = ps' ^ qs' := by cc
/--
Exponentiate two expressions.
* `ps ^ 1 = ps`
* `0 ^ qs = 0` (note that this is handled *after* `ps ^ 0 = 1`)
* `(p + 0) ^ qs = p ^ qs`
* `ps ^ (qs + 1) = ps * ps ^ qs` (note that this is handled *after* `p + 0 ^ qs = p ^ qs`)
* `ps ^ qs = ps ^ qs` (otherwise)
-/
meta def pow_p : ex sum → ex prod → ring_exp_m (ex sum)
| ps qs@(ex.coeff qs_i ⟨⟨1, 1, _, _⟩⟩) := do
ps_o ← pow_orig ps qs,
pf ← mk_proof ``pow_p_pf_one [ps.orig, ps.pretty, qs.orig] [ps.info, qs.info],
pure $ ps.set_info ps_o pf
| ps@(ex.zero ps_i) qs@(ex.coeff qs_i ⟨⟨succ y, 1, _, _⟩⟩) := do
ctx ← get_context,
z ← ex_zero,
qs_pred ← lift $ expr.of_nat ctx.info_e.α y,
pf ← mk_proof ``pow_p_pf_zero [ps.orig, qs.orig, qs_pred] [ps.info, qs.info],
z_o ← pow_orig ps qs,
pure $ z.set_info z_o pf
| pps@(ex.sum pps_i p (ex.zero _)) qqs := do
pqs ← pow_pp p qqs,
pqs_o ← pow_orig pps qqs,
pf ← mk_proof ``pow_p_pf_singleton
[pps.orig, p.pretty, pqs.pretty, qqs.orig]
[pps.info, pqs.info],
prod_to_sum $ pqs.set_info pqs_o pf
| ps qs@(ex.coeff qs_i ⟨⟨int.of_nat (succ n), 1, den_pos, _⟩⟩) := do
qs' ← in_exponent $ ex_coeff ⟨int.of_nat n, 1, den_pos, coprime_one_right _⟩,
pqs ← pow_p ps qs',
pqqs ← mul ps pqs,
pqqs_o ← pow_orig ps qs,
pf ← mk_proof ``pow_p_pf_succ
[ps.orig, pqqs.pretty, qs.orig, qs'.pretty]
[qs.info, pqqs.info],
pure $ pqqs.set_info pqqs_o pf
| pps qqs := do -- fallback: treat them as atoms
pps' ← ex_sum_b pps,
psqs ← ex_exp pps' qqs,
psqs_o ← pow_orig pps qqs,
pf ← mk_proof_or_refl psqs.pretty ``pow_p_pf_cons
[pps.orig, pps.pretty, qqs.orig, qqs.pretty]
[pps.info, qqs.info],
exp_to_prod (psqs.set_info psqs_o pf) >>= prod_to_sum
lemma pow_pf_zero {ps : α} {qs : ℕ} : qs = 0 → ps ^ qs = 1 := λ qs_pf, calc
ps ^ qs = ps ^ 0 : by rw [qs_pf]
... = 1 : pow_zero _
lemma pow_pf_sum {ps psqqs : α} {qqs q qs : ℕ} : qqs = q + qs →
ps ^ q * ps ^ qs = psqqs → ps ^ qqs = psqqs := λ qqs_pf psqqs_pf, calc
ps ^ qqs = ps ^ (q + qs) : by rw [qqs_pf]
... = ps ^ q * ps ^ qs : pow_add _ _ _
... = psqqs : psqqs_pf
/--
Exponentiate two expressions.
* `ps ^ 0 = 1`
* `ps ^ (q + qs) = ps ^ q * ps ^ qs`
-/
meta def pow : ex sum → ex sum → ring_exp_m (ex sum)
| ps qs@(ex.zero qs_i) := do
o ← ex_one,
o_o ← pow_orig ps qs,
pf ← mk_proof ``pow_pf_zero [ps.orig, qs.orig] [qs.info],
prod_to_sum $ o.set_info o_o pf
| ps qqs@(ex.sum qqs_i q qs) := do
psq ← pow_p ps q,
psqs ← pow ps qs,
psqqs ← mul psq psqs,
psqqs_o ← pow_orig ps qqs,
pf ← mk_proof ``pow_pf_sum
[ps.orig, psqqs.pretty, qqs.orig, q.pretty, qs.pretty]
[qqs.info, psqqs.info],
pure $ psqqs.set_info psqqs_o pf
end exponentiation
lemma simple_pf_sum_zero {p p' : α} : p = p' → p + 0 = p' := by simp
lemma simple_pf_prod_one {p p' : α} : p = p' → p * 1 = p' := by simp
lemma simple_pf_prod_neg_one {α} [ring α] {p p' : α} : p = p' → p * -1 = - p' := by simp
lemma simple_pf_var_one (p : α) : p ^ 1 = p := by simp
lemma simple_pf_exp_one {p p' : α} : p = p' → p ^ 1 = p' := by simp
/--
Give a simpler, more human-readable representation of the normalized expression.
Normalized expressions might have the form `a^1 * 1 + 0`,
since the dummy operations reduce special cases in pattern-matching.
Humans prefer to read `a` instead.
This tactic gets rid of the dummy additions, multiplications and exponentiations.
-/
meta def ex.simple : Π {et : ex_type}, ex et → ring_exp_m (expr × expr)
| sum pps@(ex.sum pps_i p (ex.zero _)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_sum_zero [p.pretty, p_p, p_pf]
| sum (ex.sum pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← ps.simple,
prod.mk
<$> mk_add [p_p, ps_p]
<*> mk_app_csr ``sum_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| prod (ex.prod pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_prod_one [p.pretty, p_p, p_pf]
| prod pps@(ex.prod pps_i p (ex.coeff _ ⟨⟨-1, 1, _, _⟩⟩)) := do
ctx ← get_context,
match ctx.info_b.ring_instance with
| none := prod.mk pps.pretty <$> pps.proof_term
| (some ringi) := do
(p_p, p_pf) ← p.simple,
prod.mk
<$> lift (mk_app ``has_neg.neg [p_p])
<*> mk_app_class ``simple_pf_prod_neg_one ringi [p.pretty, p_p, p_pf]
end
| prod (ex.prod pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← ps.simple,
prod.mk
<$> mk_mul [p_p, ps_p]
<*> mk_app_csr ``prod_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| base (ex.sum_b pps_i ps) := ps.simple
| exp (ex.exp pps_i p (ex.coeff _ ⟨⟨1, 1, _, _⟩⟩)) := do
(p_p, p_pf) ← p.simple,
prod.mk p_p <$> mk_app_csr ``simple_pf_exp_one [p.pretty, p_p, p_pf]
| exp (ex.exp pps_i p ps) := do
(p_p, p_pf) ← p.simple,
(ps_p, ps_pf) ← in_exponent $ ps.simple,
prod.mk
<$> mk_pow [p_p, ps_p]
<*> mk_app_csr ``exp_congr [p.pretty, p_p, ps.pretty, ps_p, p_pf, ps_pf]
| et ps := prod.mk ps.pretty <$> ps.proof_term
/--
Performs a lookup of the atom `a` in the list of known atoms,
or allocates a new one.
If `a` is not definitionally equal to any of the list's entries,
a new atom is appended to the list and returned.
The index of this atom is kept track of in the second inductive argument.
This function is mostly useful in `resolve_atom`,
which updates the state with the new list of atoms.
-/
meta def resolve_atom_aux (a : expr) : list atom → ℕ → ring_exp_m (atom × list atom)
| [] n := let atm : atom := ⟨a, n⟩ in pure (atm, [atm])
| bas@(b :: as) n := do
ctx ← get_context,
(lift $ is_def_eq a b.value ctx.transp >> pure (b , bas)) <|> do
(atm, as') ← resolve_atom_aux as (succ n),
pure (atm, b :: as')
/--
Convert the expression to an atom:
either look up a definitionally equal atom,
or allocate it as a new atom.
You probably want to use `eval_base` if `eval` doesn't work
instead of directly calling `resolve_atom`,
since `eval_base` can also handle numerals.
-/
meta def resolve_atom (a : expr) : ring_exp_m atom := do
atoms ← reader_t.lift $ state_t.get,
(atm, atoms') ← resolve_atom_aux a atoms 0,
reader_t.lift $ state_t.put atoms',
pure atm
/--
Treat the expression atomically: as a coefficient or atom.
Handles cases where `eval` cannot treat the expression as a known operation
because it is just a number or single variable.
-/
meta def eval_base (ps : expr) : ring_exp_m (ex sum) :=
match ps.to_rat with
| some ⟨0, 1, _, _⟩ := ex_zero
| some x := ex_coeff x >>= prod_to_sum
| none := do
a ← resolve_atom ps,
atom_to_sum a
end
lemma negate_pf {α} [ring α] {ps ps' : α} : (-1) * ps = ps' → -ps = ps' := by simp
/--
Negate an expression by multiplying with `-1`.
Only works if there is a `ring` instance; otherwise it will `fail`.
-/
meta def negate (ps : ex sum) : ring_exp_m (ex sum) := do
ctx ← get_context,
match ctx.info_b.ring_instance with
| none := lift $ fail "internal error: negate called in semiring"
| (some ring_instance) := do
minus_one ← ex_coeff (-1) >>= prod_to_sum,
ps' ← mul minus_one ps,
ps_pf ← ps'.proof_term,
pf ← mk_app_class ``negate_pf ring_instance [ps.orig, ps'.pretty, ps_pf],
ps'_o ← lift $ mk_app ``has_neg.neg [ps.orig],
pure $ ps'.set_info ps'_o pf
end
lemma inverse_pf {α} [division_ring α] {ps ps_u ps_p e' e'' : α} :
ps = ps_u → ps_u = ps_p → ps_p ⁻¹ = e' → e' = e'' → ps ⁻¹ = e'' :=
by cc
/--
Invert an expression by simplifying, applying `has_inv.inv` and treating the result as an atom.
Only works if there is a `division_ring` instance; otherwise it will `fail`.
-/
meta def inverse (ps : ex sum) : ring_exp_m (ex sum) := do
ctx ← get_context,
dri ← match ctx.info_b.dr_instance with
| none := lift $ fail "division is only supported in a division ring"
| (some dri) := pure dri
end,
(ps_simple, ps_simple_pf) ← ps.simple,
e ← lift $ mk_app ``has_inv.inv [ps_simple],
(e', e_pf) ← lift (norm_num.derive e) <|> ((λ e_pf, (e, e_pf)) <$> lift (mk_eq_refl e)),
e'' ← eval_base e',
ps_pf ← ps.proof_term,
e''_pf ← e''.proof_term,
pf ← mk_app_class ``inverse_pf dri
[ ps.orig, ps.pretty, ps_simple, e', e''.pretty,
ps_pf, ps_simple_pf, e_pf, e''_pf],
e''_o ← lift $ mk_app ``has_inv.inv [ps.orig],
pure $ e''.set_info e''_o pf
lemma sub_pf {α} [ring α] {ps qs psqs : α} (h : ps + -qs = psqs) : ps - qs = psqs :=
by rwa sub_eq_add_neg
lemma div_pf {α} [division_ring α] {ps qs psqs : α} (h : ps * qs⁻¹ = psqs) : ps / qs = psqs :=
by rwa div_eq_mul_inv
end operations
section wiring
/-!
### `wiring` section
This section deals with going from `expr` to `ex` and back.
The main attraction is `eval`, which uses `add`, `mul`, etc.
to calculate an `ex` from a given `expr`.
Other functions use `ex`es to produce `expr`s together with a proof,
or produce the context to run `ring_exp_m` from an `expr`.
-/
open tactic
open ex_type
/--
Compute a normalized form (of type `ex`) from an expression (of type `expr`).
This is the main driver of the `ring_exp` tactic,
calling out to `add`, `mul`, `pow`, etc. to parse the `expr`.
-/
meta def eval : expr → ring_exp_m (ex sum)
| e@`(%%ps + %%qs) := do
ps' ← eval ps,
qs' ← eval qs,
add ps' qs'
| ps_o@`(nat.succ %%p_o) := do
ps' ← eval `(%%p_o + 1),
pf ← lift $ mk_app ``nat.succ_eq_add_one [p_o],
rewrite ps_o ps' pf
| e@`(%%ps - %%qs) := (do
ctx ← get_context,
ri ← match ctx.info_b.ring_instance with
| none := lift $ fail "subtraction is not directly supported in a semiring"
| (some ri) := pure ri
end,
ps' ← eval ps,
qs' ← eval qs >>= negate,
psqs ← add ps' qs',
psqs_pf ← psqs.proof_term,
pf ← mk_app_class ``sub_pf ri [ps, qs, psqs.pretty, psqs_pf],
pure (psqs.set_info e pf)) <|> eval_base e
| e@`(- %%ps) := do
ps' ← eval ps,
negate ps' <|> eval_base e
| e@`(%%ps * %%qs) := do
ps' ← eval ps,
qs' ← eval qs,
mul ps' qs'
| e@`(has_inv.inv %%ps) := do
ps' ← eval ps,
inverse ps' <|> eval_base e
| e@`(%%ps / %%qs) := do
ctx ← get_context,
dri ← match ctx.info_b.dr_instance with
| none := lift $ fail "division is only directly supported in a division ring"
| (some dri) := pure dri
end,
ps' ← eval ps,
qs' ← eval qs,
(do qs'' ← inverse qs',
psqs ← mul ps' qs'',
psqs_pf ← psqs.proof_term,
pf ← mk_app_class ``div_pf dri [ps, qs, psqs.pretty, psqs_pf],
pure (psqs.set_info e pf)) <|> eval_base e
| e@`(@has_pow.pow _ _ %%hp_instance %%ps %%qs) := do
ps' ← eval ps,
qs' ← in_exponent $ eval qs,
psqs ← pow ps' qs',
psqs_pf ← psqs.proof_term,
(do has_pow_pf ← match hp_instance with
| `(monoid.has_pow) := lift $ mk_eq_refl e
| _ := lift $ fail "has_pow instance must be nat.has_pow or monoid.has_pow"
end,
pf ← lift $ mk_eq_trans has_pow_pf psqs_pf,
pure $ psqs.set_info e pf) <|> eval_base e
| ps := eval_base ps
/--
Run `eval` on the expression and return the result together with normalization proof.
See also `eval_simple` if you want something that behaves like `norm_num`.
-/
meta def eval_with_proof (e : expr) : ring_exp_m (ex sum × expr) := do
e' ← eval e,
prod.mk e' <$> e'.proof_term
/--
Run `eval` on the expression and simplify the result.
Returns a simplified normalized expression, together with an equality proof.
See also `eval_with_proof` if you just want to check the equality of two expressions.
-/
meta def eval_simple (e : expr) : ring_exp_m (expr × expr) := do
(complicated, complicated_pf) ← eval_with_proof e,
(simple, simple_pf) ← complicated.simple,
prod.mk simple <$> lift (mk_eq_trans complicated_pf simple_pf)
/-- Compute the `eval_info` for a given type `α`. -/
meta def make_eval_info (α : expr) : tactic eval_info := do
u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
csr_instance ← mk_app ``comm_semiring [α] >>= mk_instance,
ring_instance ← (some <$> (mk_app ``ring [α] >>= mk_instance) <|> pure none),
dr_instance ← (some <$> (mk_app ``division_ring [α] >>= mk_instance) <|> pure none),
ha_instance ← mk_app ``has_add [α] >>= mk_instance,
hm_instance ← mk_app ``has_mul [α] >>= mk_instance,
hp_instance ← mk_mapp ``monoid.has_pow [some α, none],
z ← mk_mapp ``has_zero.zero [α, none],
o ← mk_mapp ``has_one.one [α, none],
pure ⟨α, u, csr_instance, ha_instance, hm_instance, hp_instance, ring_instance, dr_instance, z, o⟩
/-- Use `e` to build the context for running `mx`. -/
meta def run_ring_exp {α} (transp : transparency) (e : expr) (mx : ring_exp_m α) : tactic α := do
info_b ← infer_type e >>= make_eval_info,
info_e ← mk_const ``nat >>= make_eval_info,
(λ x : (_ × _), x.1) <$> (state_t.run (reader_t.run mx ⟨info_b, info_e, transp⟩) [])
/-- Repeatedly apply `eval_simple` on (sub)expressions. -/
meta def normalize (transp : transparency) (e : expr) : tactic (expr × expr) := do
(_, e', pf') ← ext_simplify_core () {}
simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do
(e'', pf) ← run_ring_exp transp e $ eval_simple e,
guard (¬ e'' =ₐ e),
return ((), e'', some pf, ff))
(λ _ _ _ _ _, failed) `eq e,
pure (e', pf')
end wiring
end tactic.ring_exp
namespace tactic.interactive
open interactive interactive.types lean.parser tactic tactic.ring_exp
local postfix `?`:9001 := optional
/--
Tactic for solving equations of *commutative* (semi)rings,
allowing variables in the exponent.
This version of `ring_exp` fails if the target is not an equality.
The variant `ring_exp_eq!` will use a more aggressive reducibility setting
to determine equality of atoms.
-/
meta def ring_exp_eq (red : parse (tk "!")?) : tactic unit := do
`(eq %%ps %%qs) ← target >>= whnf,
let transp := if red.is_some then semireducible else reducible,
((ps', ps_pf), (qs', qs_pf)) ← run_ring_exp transp ps $
prod.mk <$> eval_with_proof ps <*> eval_with_proof qs,
if ps'.eq qs'
then do
qs_pf_inv ← mk_eq_symm qs_pf,
pf ← mk_eq_trans ps_pf qs_pf_inv,
tactic.interactive.exact ``(%%pf)
else fail "ring_exp failed to prove equality"
/--
Tactic for evaluating expressions in *commutative* (semi)rings, allowing for variables in the
exponent.
This tactic extends `ring`: it should solve every goal that `ring` can solve.
Additionally, it knows how to evaluate expressions with complicated exponents
(where `ring` only understands constant exponents).
The variants `ring_exp!` and `ring_exp_eq!` use a more aggessive reducibility setting to determine
equality of atoms.
For example:
```lean
example (n : ℕ) (m : ℤ) : 2^(n+1) * m = 2 * 2^n * m := by ring_exp
example (a b : ℤ) (n : ℕ) : (a + b)^(n + 2) = (a^2 + b^2 + a * b + b * a) * (a + b)^n := by ring_exp
example (x y : ℕ) : x + id y = y + id x := by ring_exp!
```
-/
meta def ring_exp (red : parse (tk "!")?) (loc : parse location) : tactic unit :=
match loc with
| interactive.loc.ns [none] := ring_exp_eq red
| _ := failed
end <|>
do ns ← loc.get_locals,
let transp := if red.is_some then semireducible else reducible,
tt ← tactic.replace_at (normalize transp) ns loc.include_goal
| fail "ring_exp failed to simplify",
when loc.include_goal $ try tactic.reflexivity
add_tactic_doc
{ name := "ring_exp",
category := doc_category.tactic,
decl_names := [`tactic.interactive.ring_exp],
tags := ["arithmetic", "simplification", "decision procedure"] }
end tactic.interactive
namespace conv.interactive
open conv interactive
open tactic tactic.interactive (ring_exp_eq)
open tactic.ring_exp (normalize)
local postfix `?`:9001 := optional
/--
Normalises expressions in commutative (semi-)rings inside of a `conv` block using the tactic
`ring_exp`.
-/
meta def ring_exp (red : parse (lean.parser.tk "!")?) : conv unit :=
let transp := if red.is_some then semireducible else reducible in
discharge_eq_lhs (ring_exp_eq red)
<|> replace_lhs (normalize transp)
<|> fail "ring_exp failed to simplify"
end conv.interactive
|
1a073801a0bd2506ae52164cb96388ad6cab7e94 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/group_power/basic.lean | c49fea6331e4961be0f209cafc6d719f302d09e2 | [] | 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 | 24,808 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.ordered_ring
import Mathlib.tactic.monotonicity.basic
import Mathlib.deprecated.group
import Mathlib.PostPort
universes u y v z u₁ w u₂ u_1
namespace Mathlib
/-!
# Power operations on monoids and groups
The power operation on monoids and groups.
We separate this from group, because it depends on `ℕ`,
which in turn depends on other parts of algebra.
This module contains the definitions of `monoid.pow` and `group.pow`
and their additive counterparts `nsmul` and `gsmul`, along with a few lemmas.
Further lemmas can be found in `algebra.group_power.lemmas`.
## Notation
The class `has_pow α β` provides the notation `a^b` for powers.
We define instances of `has_pow M ℕ`, for monoids `M`, and `has_pow G ℤ` for groups `G`.
We also define infix operators `•ℕ` and `•ℤ` for scalar multiplication by a natural and an integer
numbers, respectively.
## Implementation details
We adopt the convention that `0^0 = 1`.
This module provides the instance `has_pow ℕ ℕ` (via `monoid.has_pow`)
and is imported by `data.nat.basic`, so it has to live low in the import hierarchy.
Not all of its imports are needed yet; the intent is to move more lemmas here from `.lemmas`
so that they are available in `data.nat.basic`, and the imports will be required then.
-/
/-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/
def monoid.pow {M : Type u} [Mul M] [HasOne M] (a : M) : ℕ → M :=
sorry
/-- The scalar multiplication in an additive monoid.
`n •ℕ a = a+a+...+a` n times. -/
def nsmul {A : Type y} [Add A] [HasZero A] (n : ℕ) (a : A) : A :=
monoid.pow a n
infixl:70 " •ℕ " => Mathlib.nsmul
protected instance monoid.has_pow {M : Type u} [monoid M] : has_pow M ℕ :=
has_pow.mk monoid.pow
@[simp] theorem monoid.pow_eq_has_pow {M : Type u} [monoid M] (a : M) (n : ℕ) : monoid.pow a n = a ^ n :=
rfl
/-!
### Commutativity
First we prove some facts about `semiconj_by` and `commute`. They do not require any theory about
`pow` and/or `nsmul` and will be useful later in this file.
-/
namespace semiconj_by
@[simp] theorem pow_right {M : Type u} [monoid M] {a : M} {x : M} {y : M} (h : semiconj_by a x y) (n : ℕ) : semiconj_by a (x ^ n) (y ^ n) :=
nat.rec_on n (one_right a) fun (n : ℕ) (ihn : semiconj_by a (x ^ n) (y ^ n)) => mul_right h ihn
end semiconj_by
namespace commute
@[simp] theorem pow_right {M : Type u} [monoid M] {a : M} {b : M} (h : commute a b) (n : ℕ) : commute a (b ^ n) :=
semiconj_by.pow_right h n
@[simp] theorem pow_left {M : Type u} [monoid M] {a : M} {b : M} (h : commute a b) (n : ℕ) : commute (a ^ n) b :=
commute.symm (pow_right (commute.symm h) n)
@[simp] theorem pow_pow {M : Type u} [monoid M] {a : M} {b : M} (h : commute a b) (m : ℕ) (n : ℕ) : commute (a ^ m) (b ^ n) :=
pow_right (pow_left h m) n
@[simp] theorem self_pow {M : Type u} [monoid M] (a : M) (n : ℕ) : commute a (a ^ n) :=
pow_right (commute.refl a) n
@[simp] theorem pow_self {M : Type u} [monoid M] (a : M) (n : ℕ) : commute (a ^ n) a :=
pow_left (commute.refl a) n
@[simp] theorem pow_pow_self {M : Type u} [monoid M] (a : M) (m : ℕ) (n : ℕ) : commute (a ^ m) (a ^ n) :=
pow_pow (commute.refl a) m n
end commute
@[simp] theorem pow_zero {M : Type u} [monoid M] (a : M) : a ^ 0 = 1 :=
rfl
@[simp] theorem zero_nsmul {A : Type y} [add_monoid A] (a : A) : 0 •ℕ a = 0 :=
rfl
theorem pow_succ {M : Type u} [monoid M] (a : M) (n : ℕ) : a ^ (n + 1) = a * a ^ n :=
rfl
theorem succ_nsmul {A : Type y} [add_monoid A] (a : A) (n : ℕ) : (n + 1) •ℕ a = a + n •ℕ a :=
rfl
theorem pow_two {M : Type u} [monoid M] (a : M) : a ^ bit0 1 = a * a :=
(fun (this : a * (a * 1) = a * a) => this)
(eq.mpr (id (Eq._oldrec (Eq.refl (a * (a * 1) = a * a)) (mul_one a))) (Eq.refl (a * a)))
theorem two_nsmul {A : Type y} [add_monoid A] (a : A) : bit0 1 •ℕ a = a + a :=
pow_two a
theorem pow_mul_comm' {M : Type u} [monoid M] (a : M) (n : ℕ) : a ^ n * a = a * a ^ n :=
commute.pow_self a n
theorem nsmul_add_comm' {A : Type y} [add_monoid A] (a : A) (n : ℕ) : n •ℕ a + a = a + n •ℕ a :=
pow_mul_comm'
theorem pow_succ' {M : Type u} [monoid M] (a : M) (n : ℕ) : a ^ (n + 1) = a ^ n * a :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (n + 1) = a ^ n * a)) (pow_succ a n)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a * a ^ n = a ^ n * a)) (pow_mul_comm' a n))) (Eq.refl (a * a ^ n)))
theorem succ_nsmul' {A : Type y} [add_monoid A] (a : A) (n : ℕ) : (n + 1) •ℕ a = n •ℕ a + a :=
pow_succ' a n
theorem pow_add {M : Type u} [monoid M] (a : M) (m : ℕ) (n : ℕ) : a ^ (m + n) = a ^ m * a ^ n := sorry
theorem add_nsmul {A : Type y} [add_monoid A] (a : A) (m : ℕ) (n : ℕ) : (m + n) •ℕ a = m •ℕ a + n •ℕ a :=
pow_add
@[simp] theorem pow_one {M : Type u} [monoid M] (a : M) : a ^ 1 = a :=
mul_one a
@[simp] theorem one_nsmul {A : Type y} [add_monoid A] (a : A) : 1 •ℕ a = a :=
add_zero (coe_fn multiplicative.to_add a)
@[simp] theorem pow_ite {M : Type u} [monoid M] (P : Prop) [Decidable P] (a : M) (b : ℕ) (c : ℕ) : a ^ ite P b c = ite P (a ^ b) (a ^ c) := sorry
@[simp] theorem ite_pow {M : Type u} [monoid M] (P : Prop) [Decidable P] (a : M) (b : M) (c : ℕ) : ite P a b ^ c = ite P (a ^ c) (b ^ c) := sorry
@[simp] theorem pow_boole {M : Type u} [monoid M] (P : Prop) [Decidable P] (a : M) : a ^ ite P 1 0 = ite P a 1 := sorry
@[simp] theorem one_pow {M : Type u} [monoid M] (n : ℕ) : 1 ^ n = 1 := sorry
@[simp] theorem nsmul_zero {A : Type y} [add_monoid A] (n : ℕ) : n •ℕ 0 = 0 := sorry
theorem pow_mul {M : Type u} [monoid M] (a : M) (m : ℕ) (n : ℕ) : a ^ (m * n) = (a ^ m) ^ n := sorry
theorem mul_nsmul' {A : Type y} [add_monoid A] (a : A) (m : ℕ) (n : ℕ) : m * n •ℕ a = n •ℕ (m •ℕ a) :=
pow_mul
theorem pow_mul' {M : Type u} [monoid M] (a : M) (m : ℕ) (n : ℕ) : a ^ (m * n) = (a ^ n) ^ m :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (m * n) = (a ^ n) ^ m)) (nat.mul_comm m n)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (n * m) = (a ^ n) ^ m)) (pow_mul a n m))) (Eq.refl ((a ^ n) ^ m)))
theorem mul_nsmul {A : Type y} [add_monoid A] (a : A) (m : ℕ) (n : ℕ) : m * n •ℕ a = m •ℕ (n •ℕ a) :=
pow_mul' a m n
theorem pow_mul_pow_sub {M : Type u} [monoid M] (a : M) {m : ℕ} {n : ℕ} (h : m ≤ n) : a ^ m * a ^ (n - m) = a ^ n :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ^ m * a ^ (n - m) = a ^ n)) (Eq.symm (pow_add a m (n - m)))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (m + (n - m)) = a ^ n)) (nat.add_comm m (n - m))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (n - m + m) = a ^ n)) (nat.sub_add_cancel h))) (Eq.refl (a ^ n))))
theorem nsmul_add_sub_nsmul {A : Type y} [add_monoid A] (a : A) {m : ℕ} {n : ℕ} (h : m ≤ n) : m •ℕ a + (n - m) •ℕ a = n •ℕ a :=
pow_mul_pow_sub a h
theorem pow_sub_mul_pow {M : Type u} [monoid M] (a : M) {m : ℕ} {n : ℕ} (h : m ≤ n) : a ^ (n - m) * a ^ m = a ^ n :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (n - m) * a ^ m = a ^ n)) (Eq.symm (pow_add a (n - m) m))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (n - m + m) = a ^ n)) (nat.sub_add_cancel h))) (Eq.refl (a ^ n)))
theorem sub_nsmul_nsmul_add {A : Type y} [add_monoid A] (a : A) {m : ℕ} {n : ℕ} (h : m ≤ n) : (n - m) •ℕ a + m •ℕ a = n •ℕ a :=
pow_sub_mul_pow a h
theorem pow_bit0 {M : Type u} [monoid M] (a : M) (n : ℕ) : a ^ bit0 n = a ^ n * a ^ n :=
pow_add a n n
theorem bit0_nsmul {A : Type y} [add_monoid A] (a : A) (n : ℕ) : bit0 n •ℕ a = n •ℕ a + n •ℕ a :=
add_nsmul a n n
theorem pow_bit1 {M : Type u} [monoid M] (a : M) (n : ℕ) : a ^ bit1 n = a ^ n * a ^ n * a := sorry
theorem bit1_nsmul {A : Type y} [add_monoid A] (a : A) (n : ℕ) : bit1 n •ℕ a = n •ℕ a + n •ℕ a + a :=
pow_bit1
theorem pow_mul_comm {M : Type u} [monoid M] (a : M) (m : ℕ) (n : ℕ) : a ^ m * a ^ n = a ^ n * a ^ m :=
commute.pow_pow_self a m n
theorem nsmul_add_comm {A : Type y} [add_monoid A] (a : A) (m : ℕ) (n : ℕ) : m •ℕ a + n •ℕ a = n •ℕ a + m •ℕ a :=
pow_mul_comm
@[simp] theorem monoid_hom.map_pow {M : Type u} {N : Type v} [monoid M] [monoid N] (f : M →* N) (a : M) (n : ℕ) : coe_fn f (a ^ n) = coe_fn f a ^ n := sorry
@[simp] theorem add_monoid_hom.map_nsmul {A : Type y} {B : Type z} [add_monoid A] [add_monoid B] (f : A →+ B) (a : A) (n : ℕ) : coe_fn f (n •ℕ a) = n •ℕ coe_fn f a :=
monoid_hom.map_pow (coe_fn add_monoid_hom.to_multiplicative f) a n
theorem is_monoid_hom.map_pow {M : Type u} {N : Type v} [monoid M] [monoid N] (f : M → N) [is_monoid_hom f] (a : M) (n : ℕ) : f (a ^ n) = f a ^ n :=
monoid_hom.map_pow (monoid_hom.of f) a
theorem is_add_monoid_hom.map_nsmul {A : Type y} {B : Type z} [add_monoid A] [add_monoid B] (f : A → B) [is_add_monoid_hom f] (a : A) (n : ℕ) : f (n •ℕ a) = n •ℕ f a :=
add_monoid_hom.map_nsmul (add_monoid_hom.of f) a n
theorem commute.mul_pow {M : Type u} [monoid M] {a : M} {b : M} (h : commute a b) (n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := sorry
theorem neg_pow {R : Type u₁} [ring R] (a : R) (n : ℕ) : (-a) ^ n = (-1) ^ n * a ^ n :=
neg_one_mul a ▸ commute.mul_pow (commute.neg_one_left a) n
theorem pow_bit0' {M : Type u} [monoid M] (a : M) (n : ℕ) : a ^ bit0 n = (a * a) ^ n :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ^ bit0 n = (a * a) ^ n)) (pow_bit0 a n)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ^ n * a ^ n = (a * a) ^ n)) (commute.mul_pow (commute.refl a) n)))
(Eq.refl (a ^ n * a ^ n)))
theorem bit0_nsmul' {A : Type y} [add_monoid A] (a : A) (n : ℕ) : bit0 n •ℕ a = n •ℕ (a + a) :=
pow_bit0' a n
theorem pow_bit1' {M : Type u} [monoid M] (a : M) (n : ℕ) : a ^ bit1 n = (a * a) ^ n * a :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ^ bit1 n = (a * a) ^ n * a)) (bit1.equations._eqn_1 n)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ^ (bit0 n + 1) = (a * a) ^ n * a)) (pow_succ' a (bit0 n))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ^ bit0 n * a = (a * a) ^ n * a)) (pow_bit0' a n))) (Eq.refl ((a * a) ^ n * a))))
theorem bit1_nsmul' {A : Type y} [add_monoid A] (a : A) (n : ℕ) : bit1 n •ℕ a = n •ℕ (a + a) + a :=
pow_bit1'
@[simp] theorem neg_pow_bit0 {R : Type u₁} [ring R] (a : R) (n : ℕ) : (-a) ^ bit0 n = a ^ bit0 n :=
eq.mpr (id (Eq._oldrec (Eq.refl ((-a) ^ bit0 n = a ^ bit0 n)) (pow_bit0' (-a) n)))
(eq.mpr (id (Eq._oldrec (Eq.refl ((-a * -a) ^ n = a ^ bit0 n)) (neg_mul_neg a a)))
(eq.mpr (id (Eq._oldrec (Eq.refl ((a * a) ^ n = a ^ bit0 n)) (pow_bit0' a n))) (Eq.refl ((a * a) ^ n))))
@[simp] theorem neg_pow_bit1 {R : Type u₁} [ring R] (a : R) (n : ℕ) : (-a) ^ bit1 n = -a ^ bit1 n := sorry
/-!
### Commutative (additive) monoid
-/
theorem mul_pow {M : Type u} [comm_monoid M] (a : M) (b : M) (n : ℕ) : (a * b) ^ n = a ^ n * b ^ n :=
commute.mul_pow (commute.all a b) n
theorem nsmul_add {A : Type y} [add_comm_monoid A] (a : A) (b : A) (n : ℕ) : n •ℕ (a + b) = n •ℕ a + n •ℕ b :=
mul_pow
protected instance pow.is_monoid_hom {M : Type u} [comm_monoid M] (n : ℕ) : is_monoid_hom fun (_x : M) => _x ^ n :=
is_monoid_hom.mk (one_pow n)
protected instance nsmul.is_add_monoid_hom {A : Type y} [add_comm_monoid A] (n : ℕ) : is_add_monoid_hom (nsmul n) :=
is_add_monoid_hom.mk (nsmul_zero n)
theorem dvd_pow {M : Type u} [comm_monoid M] {x : M} {y : M} {n : ℕ} (hxy : x ∣ y) (hn : n ≠ 0) : x ∣ y ^ n := sorry
/--
The power operation in a group. This extends `monoid.pow` to negative integers
with the definition `a^(-n) = (a^n)⁻¹`.
-/
def gpow {G : Type w} [group G] (a : G) : ℤ → G :=
sorry
/--
The scalar multiplication by integers on an additive group.
This extends `nsmul` to negative integers
with the definition `(-n) •ℤ a = -(n •ℕ a)`.
-/
def gsmul {A : Type y} [add_group A] (n : ℤ) (a : A) : A :=
gpow a n
protected instance group.has_pow {G : Type w} [group G] : has_pow G ℤ :=
has_pow.mk gpow
infixl:70 " •ℤ " => Mathlib.gsmul
@[simp] theorem group.gpow_eq_has_pow {G : Type w} [group G] (a : G) (n : ℤ) : gpow a n = a ^ n :=
rfl
@[simp] theorem inv_pow {G : Type w} [group G] (a : G) (n : ℕ) : a⁻¹ ^ n = (a ^ n⁻¹) := sorry
@[simp] theorem neg_nsmul {A : Type y} [add_group A] (a : A) (n : ℕ) : n •ℕ -a = -(n •ℕ a) :=
inv_pow
theorem pow_sub {G : Type w} [group G] (a : G) {m : ℕ} {n : ℕ} (h : n ≤ m) : a ^ (m - n) = a ^ m * (a ^ n⁻¹) := sorry
theorem nsmul_sub {A : Type y} [add_group A] (a : A) {m : ℕ} {n : ℕ} : n ≤ m → (m - n) •ℕ a = m •ℕ a - n •ℕ a := sorry
theorem pow_inv_comm {G : Type w} [group G] (a : G) (m : ℕ) (n : ℕ) : a⁻¹ ^ m * a ^ n = a ^ n * a⁻¹ ^ m :=
commute.pow_pow (commute.inv_left (commute.refl a)) m n
theorem nsmul_neg_comm {A : Type y} [add_group A] (a : A) (m : ℕ) (n : ℕ) : m •ℕ -a + n •ℕ a = n •ℕ a + m •ℕ -a :=
pow_inv_comm
@[simp] theorem gpow_coe_nat {G : Type w} [group G] (a : G) (n : ℕ) : a ^ ↑n = a ^ n :=
rfl
@[simp] theorem gsmul_coe_nat {A : Type y} [add_group A] (a : A) (n : ℕ) : ↑n •ℤ a = n •ℕ a :=
rfl
theorem gpow_of_nat {G : Type w} [group G] (a : G) (n : ℕ) : a ^ Int.ofNat n = a ^ n :=
rfl
theorem gsmul_of_nat {A : Type y} [add_group A] (a : A) (n : ℕ) : Int.ofNat n •ℤ a = n •ℕ a :=
rfl
@[simp] theorem gpow_neg_succ_of_nat {G : Type w} [group G] (a : G) (n : ℕ) : a ^ Int.negSucc n = (a ^ Nat.succ n⁻¹) :=
rfl
@[simp] theorem gsmul_neg_succ_of_nat {A : Type y} [add_group A] (a : A) (n : ℕ) : Int.negSucc n •ℤ a = -(Nat.succ n •ℕ a) :=
rfl
@[simp] theorem gpow_zero {G : Type w} [group G] (a : G) : a ^ 0 = 1 :=
rfl
@[simp] theorem zero_gsmul {A : Type y} [add_group A] (a : A) : 0 •ℤ a = 0 :=
rfl
@[simp] theorem gpow_one {G : Type w} [group G] (a : G) : a ^ 1 = a :=
pow_one a
@[simp] theorem one_gsmul {A : Type y} [add_group A] (a : A) : 1 •ℤ a = a :=
add_zero (coe_fn multiplicative.to_add a)
@[simp] theorem one_gpow {G : Type w} [group G] (n : ℤ) : 1 ^ n = 1 := sorry
@[simp] theorem gsmul_zero {A : Type y} [add_group A] (n : ℤ) : n •ℤ 0 = 0 :=
one_gpow
@[simp] theorem gpow_neg {G : Type w} [group G] (a : G) (n : ℤ) : a ^ (-n) = (a ^ n⁻¹) := sorry
theorem mul_gpow_neg_one {G : Type w} [group G] (a : G) (b : G) : (a * b) ^ (-1) = b ^ (-1) * a ^ (-1) := sorry
@[simp] theorem neg_gsmul {A : Type y} [add_group A] (a : A) (n : ℤ) : -n •ℤ a = -(n •ℤ a) :=
gpow_neg
theorem gpow_neg_one {G : Type w} [group G] (x : G) : x ^ (-1) = (x⁻¹) :=
congr_arg has_inv.inv (pow_one x)
theorem neg_one_gsmul {A : Type y} [add_group A] (x : A) : -1 •ℤ x = -x :=
congr_arg Neg.neg (one_nsmul x)
theorem inv_gpow {G : Type w} [group G] (a : G) (n : ℤ) : a⁻¹ ^ n = (a ^ n⁻¹) :=
int.cases_on n (fun (n : ℕ) => idRhs (a⁻¹ ^ n = (a ^ n⁻¹)) (inv_pow a n))
fun (n : ℕ) => idRhs (a⁻¹ ^ (n + 1)⁻¹ = (a ^ (n + 1)⁻¹⁻¹)) (congr_arg has_inv.inv (inv_pow a (n + 1)))
theorem gsmul_neg {A : Type y} [add_group A] (a : A) (n : ℤ) : n •ℤ -a = -(n •ℤ a) :=
inv_gpow a n
theorem commute.mul_gpow {G : Type w} [group G] {a : G} {b : G} (h : commute a b) (n : ℤ) : (a * b) ^ n = a ^ n * b ^ n := sorry
theorem mul_gpow {G : Type w} [comm_group G] (a : G) (b : G) (n : ℤ) : (a * b) ^ n = a ^ n * b ^ n :=
commute.mul_gpow (commute.all a b) n
theorem gsmul_add {A : Type y} [add_comm_group A] (a : A) (b : A) (n : ℤ) : n •ℤ (a + b) = n •ℤ a + n •ℤ b :=
mul_gpow
theorem gsmul_sub {A : Type y} [add_comm_group A] (a : A) (b : A) (n : ℤ) : n •ℤ (a - b) = n •ℤ a - n •ℤ b := sorry
protected instance gpow.is_group_hom {G : Type w} [comm_group G] (n : ℤ) : is_group_hom fun (_x : G) => _x ^ n :=
is_group_hom.mk
protected instance gsmul.is_add_group_hom {A : Type y} [add_comm_group A] (n : ℤ) : is_add_group_hom (gsmul n) :=
is_add_group_hom.mk
theorem zero_pow {R : Type u₁} [monoid_with_zero R] {n : ℕ} : 0 < n → 0 ^ n = 0 := sorry
namespace ring_hom
@[simp] theorem map_pow {R : Type u₁} {S : Type u₂} [semiring R] [semiring S] (f : R →+* S) (a : R) (n : ℕ) : coe_fn f (a ^ n) = coe_fn f a ^ n :=
monoid_hom.map_pow (to_monoid_hom f) a
end ring_hom
theorem neg_one_pow_eq_or {R : Type u₁} [ring R] (n : ℕ) : (-1) ^ n = 1 ∨ (-1) ^ n = -1 := sorry
theorem pow_dvd_pow {R : Type u₁} [monoid R] (a : R) {m : ℕ} {n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := sorry
theorem pow_dvd_pow_of_dvd {R : Type u₁} [comm_monoid R] {a : R} {b : R} (h : a ∣ b) (n : ℕ) : a ^ n ∣ b ^ n := sorry
theorem pow_two_sub_pow_two {R : Type u_1} [comm_ring R] (a : R) (b : R) : a ^ bit0 1 - b ^ bit0 1 = (a + b) * (a - b) := sorry
theorem eq_or_eq_neg_of_pow_two_eq_pow_two {R : Type u₁} [integral_domain R] (a : R) (b : R) (h : a ^ bit0 1 = b ^ bit0 1) : a = b ∨ a = -b := sorry
theorem sq_sub_sq {R : Type u₁} [comm_ring R] (a : R) (b : R) : a ^ bit0 1 - b ^ bit0 1 = (a + b) * (a - b) := sorry
theorem pow_eq_zero {R : Type u₁} [monoid_with_zero R] [no_zero_divisors R] {x : R} {n : ℕ} (H : x ^ n = 0) : x = 0 := sorry
@[simp] theorem pow_eq_zero_iff {R : Type u₁} [monoid_with_zero R] [no_zero_divisors R] {a : R} {n : ℕ} (hn : 0 < n) : a ^ n = 0 ↔ a = 0 :=
{ mp := pow_eq_zero, mpr := fun (ᾰ : a = 0) => Eq._oldrec (zero_pow hn) (Eq.symm ᾰ) }
theorem pow_ne_zero {R : Type u₁} [monoid_with_zero R] [no_zero_divisors R] {a : R} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 :=
mt pow_eq_zero h
theorem pow_abs {R : Type u₁} [linear_ordered_comm_ring R] (a : R) (n : ℕ) : abs a ^ n = abs (a ^ n) :=
Eq.symm (monoid_hom.map_pow (monoid_with_zero_hom.to_monoid_hom abs_hom) a n)
theorem abs_neg_one_pow {R : Type u₁} [linear_ordered_comm_ring R] (n : ℕ) : abs ((-1) ^ n) = 1 := sorry
theorem nsmul_nonneg {A : Type y} [ordered_add_comm_monoid A] {a : A} (H : 0 ≤ a) (n : ℕ) : 0 ≤ n •ℕ a := sorry
theorem nsmul_pos {A : Type y} [ordered_add_comm_monoid A] {a : A} (ha : 0 < a) {k : ℕ} (hk : 0 < k) : 0 < k •ℕ a := sorry
theorem nsmul_le_nsmul {A : Type y} [ordered_add_comm_monoid A] {a : A} {n : ℕ} {m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℕ a ≤ m •ℕ a := sorry
theorem nsmul_le_nsmul_of_le_right {A : Type y} [ordered_add_comm_monoid A] {a : A} {b : A} (hab : a ≤ b) (i : ℕ) : i •ℕ a ≤ i •ℕ b := sorry
theorem gsmul_nonneg {A : Type y} [ordered_add_comm_group A] {a : A} (H : 0 ≤ a) {n : ℤ} (hn : 0 ≤ n) : 0 ≤ n •ℤ a := sorry
theorem nsmul_lt_nsmul {A : Type y} [ordered_cancel_add_comm_monoid A] {a : A} {n : ℕ} {m : ℕ} (ha : 0 < a) (h : n < m) : n •ℕ a < m •ℕ a := sorry
theorem min_pow_dvd_add {R : Type u₁} [semiring R] {n : ℕ} {m : ℕ} {a : R} {b : R} {c : R} (ha : c ^ n ∣ a) (hb : c ^ m ∣ b) : c ^ min n m ∣ a + b :=
dvd_add (dvd.trans (pow_dvd_pow c (min_le_left n m)) ha) (dvd.trans (pow_dvd_pow c (min_le_right n m)) hb)
theorem add_pow_two {R : Type u₁} [comm_semiring R] (a : R) (b : R) : (a + b) ^ bit0 1 = a ^ bit0 1 + bit0 1 * a * b + b ^ bit0 1 := sorry
namespace canonically_ordered_semiring
theorem pow_pos {R : Type u₁} [canonically_ordered_comm_semiring R] {a : R} (H : 0 < a) (n : ℕ) : 0 < a ^ n := sorry
theorem pow_le_pow_of_le_left {R : Type u₁} [canonically_ordered_comm_semiring R] {a : R} {b : R} (hab : a ≤ b) (i : ℕ) : a ^ i ≤ b ^ i := sorry
theorem one_le_pow_of_one_le {R : Type u₁} [canonically_ordered_comm_semiring R] {a : R} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n := sorry
theorem pow_le_one {R : Type u₁} [canonically_ordered_comm_semiring R] {a : R} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1 := sorry
end canonically_ordered_semiring
@[simp] theorem pow_pos {R : Type u₁} [ordered_semiring R] {a : R} (H : 0 < a) (n : ℕ) : 0 < a ^ n := sorry
@[simp] theorem pow_nonneg {R : Type u₁} [ordered_semiring R] {a : R} (H : 0 ≤ a) (n : ℕ) : 0 ≤ a ^ n := sorry
theorem pow_lt_pow_of_lt_left {R : Type u₁} [ordered_semiring R] {x : R} {y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := sorry
theorem strict_mono_incr_on_pow {R : Type u₁} [ordered_semiring R] {n : ℕ} (hn : 0 < n) : strict_mono_incr_on (fun (x : R) => x ^ n) (set.Ici 0) :=
fun (x : R) (hx : x ∈ set.Ici 0) (y : R) (hy : y ∈ set.Ici 0) (h : x < y) => pow_lt_pow_of_lt_left h hx hn
theorem one_le_pow_of_one_le {R : Type u₁} [ordered_semiring R] {a : R} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n := sorry
theorem pow_mono {R : Type u₁} [ordered_semiring R] {a : R} (h : 1 ≤ a) : monotone fun (n : ℕ) => a ^ n :=
monotone_of_monotone_nat fun (n : ℕ) => le_mul_of_one_le_left (pow_nonneg (has_le.le.trans zero_le_one h) n) h
theorem pow_le_pow {R : Type u₁} [ordered_semiring R] {a : R} {n : ℕ} {m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m :=
pow_mono ha h
theorem strict_mono_pow {R : Type u₁} [ordered_semiring R] {a : R} (h : 1 < a) : strict_mono fun (n : ℕ) => a ^ n := sorry
theorem pow_lt_pow {R : Type u₁} [ordered_semiring R] {a : R} {n : ℕ} {m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m :=
strict_mono_pow h h2
theorem pow_lt_pow_iff {R : Type u₁} [ordered_semiring R] {a : R} {n : ℕ} {m : ℕ} (h : 1 < a) : a ^ n < a ^ m ↔ n < m :=
strict_mono.lt_iff_lt (strict_mono_pow h)
theorem pow_le_pow_of_le_left {R : Type u₁} [ordered_semiring R] {a : R} {b : R} (ha : 0 ≤ a) (hab : a ≤ b) (i : ℕ) : a ^ i ≤ b ^ i := sorry
theorem pow_left_inj {R : Type u₁} [linear_ordered_semiring R] {x : R} {y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) (Hxyn : x ^ n = y ^ n) : x = y :=
strict_mono_incr_on.inj_on (strict_mono_incr_on_pow Hnpos) Hxpos Hypos Hxyn
theorem lt_of_pow_lt_pow {R : Type u₁} [linear_ordered_semiring R] {a : R} {b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b :=
lt_of_not_ge fun (hn : a ≥ b) => not_lt_of_ge (pow_le_pow_of_le_left hb hn n) h
theorem le_of_pow_le_pow {R : Type u₁} [linear_ordered_semiring R] {a : R} {b : R} (n : ℕ) (hb : 0 ≤ b) (hn : 0 < n) (h : a ^ n ≤ b ^ n) : a ≤ b :=
le_of_not_lt fun (h1 : b < a) => not_le_of_lt (pow_lt_pow_of_lt_left h1 hb hn) h
theorem pow_bit0_nonneg {R : Type u₁} [linear_ordered_ring R] (a : R) (n : ℕ) : 0 ≤ a ^ bit0 n :=
eq.mpr (id (Eq._oldrec (Eq.refl (0 ≤ a ^ bit0 n)) (pow_bit0 a n))) (mul_self_nonneg (a ^ n))
theorem pow_two_nonneg {R : Type u₁} [linear_ordered_ring R] (a : R) : 0 ≤ a ^ bit0 1 :=
pow_bit0_nonneg a 1
theorem pow_bit0_pos {R : Type u₁} [linear_ordered_ring R] {a : R} (h : a ≠ 0) (n : ℕ) : 0 < a ^ bit0 n :=
has_le.le.lt_of_ne (pow_bit0_nonneg a n) (ne.symm (pow_ne_zero (bit0 n) h))
theorem pow_two_pos_of_ne_zero {R : Type u₁} [linear_ordered_ring R] (a : R) (h : a ≠ 0) : 0 < a ^ bit0 1 :=
pow_bit0_pos h 1
@[simp] theorem eq_of_pow_two_eq_pow_two {R : Type u₁} [linear_ordered_comm_ring R] {a : R} {b : R} (ha : 0 ≤ a) (hb : 0 ≤ b) : a ^ bit0 1 = b ^ bit0 1 ↔ a = b := sorry
@[simp] theorem neg_square {α : Type u_1} [ring α] (z : α) : (-z) ^ bit0 1 = z ^ bit0 1 := sorry
theorem of_add_nsmul {A : Type y} [add_monoid A] (x : A) (n : ℕ) : coe_fn multiplicative.of_add (n •ℕ x) = coe_fn multiplicative.of_add x ^ n :=
rfl
theorem of_add_gsmul {A : Type y} [add_group A] (x : A) (n : ℤ) : coe_fn multiplicative.of_add (n •ℤ x) = coe_fn multiplicative.of_add x ^ n :=
rfl
@[simp] theorem semiconj_by.gpow_right {G : Type w} [group G] {a : G} {x : G} {y : G} (h : semiconj_by a x y) (m : ℤ) : semiconj_by a (x ^ m) (y ^ m) := sorry
namespace commute
@[simp] theorem gpow_right {G : Type w} [group G] {a : G} {b : G} (h : commute a b) (m : ℤ) : commute a (b ^ m) :=
semiconj_by.gpow_right h m
@[simp] theorem gpow_left {G : Type w} [group G] {a : G} {b : G} (h : commute a b) (m : ℤ) : commute (a ^ m) b :=
commute.symm (gpow_right (commute.symm h) m)
theorem gpow_gpow {G : Type w} [group G] {a : G} {b : G} (h : commute a b) (m : ℤ) (n : ℤ) : commute (a ^ m) (b ^ n) :=
gpow_right (gpow_left h m) n
@[simp] theorem self_gpow {G : Type w} [group G] (a : G) (n : ℕ) : commute a (a ^ n) :=
gpow_right (commute.refl a) ↑n
@[simp] theorem gpow_self {G : Type w} [group G] (a : G) (n : ℕ) : commute (a ^ n) a :=
gpow_left (commute.refl a) ↑n
@[simp] theorem gpow_gpow_self {G : Type w} [group G] (a : G) (m : ℕ) (n : ℕ) : commute (a ^ m) (a ^ n) :=
gpow_gpow (commute.refl a) ↑m ↑n
|
19d7e85f6f7ee23d73dd8ee20e48b192e891cb32 | 4ad6af7525e674c3cdc623c1495472954f3ce34c | /src/01_first.lean | 0faad887842b0abf971ef139b3c3eb97d3f81d68 | [] | no_license | alcides/lean3_tutorial | 4bf48026f7cfa5ae80e9a75f46ca23364d455810 | 7a871e00c4fd5cb000929a59e1bd804a626ef277 | refs/heads/master | 1,663,719,613,974 | 1,591,141,389,000 | 1,591,141,389,000 | 268,600,781 | 5 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,162 | lean | /-
How to learn LEAN by reading code:
Place your cursor before and after each line within the begin-end block.
The goal is prove the goal (after :) from whatever we have in the arguments of the function/theorem/lemma/example
-/
theorem my_first_theorem :
∀ p, p → p :=
begin
intro p,
intro proof_of_p,
exact proof_of_p,
end
/-
A theorem is made of a name, arguments, goal and proof.
The first example has no arguments and has type "∀ p, p → p" and this is what we want to prove.
In each line we make progress either on the context (what comes before the turnstile ⊢) or the goal (after it).
Each line has a tactic and arguments. (It is similar to haskell's do-notation for monads, if you known what it is.)
The first tactic here is intro, which pushes the left-most ∀ or → into the context with the given name and out of the goal.
Another name for this tactic is "assume", which might be more familiar for those with a math background.
The second tactic is exact, which provides exactly a proof of the goal (similarly to monad's return).
-/
theorem my_first_theorem_2 :
∀ p, p → p :=
begin
intro p,
exact id,
end
/-
This second version of the same theorem uses an existing lemma for this purpose.
This theorem was defined in the first "language" of lean: the implementation language.
Theorems are implemented as functions and they are exactly the same thing. If you have a
moment, please see Phil Wadler's talk on Propositions as Types (https://www.youtube.com/watch?v=IOiZatlZtGU&t=11s).
def id {α : Sort u} (a : α) : α := a
-/
theorem my_first_theorem_3 (p:Prop):
p → p :=
begin
exact id,
end
/-
This third version moves the universial quantifier from the goal to the context directly in the definition (as opposed to using intro).
This is akin to haskell's function definition using lambda or using arguments.
f a = a + 1
f = \ a -> a + 1
-/
theorem my_first_theorem_4 (p:Prop) (proof_of_p:p):
p :=
begin
exact proof_of_p,
end
/-
This fourth version moves both the universial quantifier and the p into the context in the definition. This is the more popular style.
-/
lemma my_first_theorem_5 (p:Prop):
p → p :=
begin
exact id,
end
/-
Lemmas and Theorems are the same thing for the language. You can choose which one serves your purpose.
-/
example (p:Prop):
p → p :=
begin
exact id,
end
/-
Examples are anonymous lemmas or theorems. We use when there is no point in giving it a name.
-/
theorem my_first_theorem_6 (p:Prop) : p → p := by exact id
/-
This is the most common style for proofs. I don't like it, so we will always use begin-end blocks.
-/
theorem my_first_theorem_7 :
∀ p:Prop, p → p :=
begin
intros p proof_of_p,
exact proof_of_p,
end
/-
This seventh version uses intros p proof_of_p, instead of two intro. You can use this
shortcut to introduce as many variables into context as you want.
-/
/-
Exercice time! Now it's your turn to apply what you did:
-/
theorem my_second_theorem :
∀ p q : Prop, p → q → p :=
begin
sorry, -- now it's your turn to do some proving.
end |
ea53c4fcf96fdb96f9570cd83a451945bab1b3e7 | bb31430994044506fa42fd667e2d556327e18dfe | /src/algebra/ring_quot.lean | 3c0b59d055a7edecc008d14c823d23d3e0feb4cd | [
"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 | 17,973 | 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 algebra.algebra.hom
import ring_theory.ideal.quotient
/-!
# Quotients of non-commutative rings
Unfortunately, ideals have only been developed in the commutative case as `ideal`,
and it's not immediately clear how one should formalise ideals in the non-commutative case.
In this file, we directly define the quotient of a semiring by any relation,
by building a bigger relation that represents the ideal generated by that relation.
We prove the universal properties of the quotient, and recommend avoiding relying on the actual
definition, which is made irreducible for this purpose.
Since everything runs in parallel for quotients of `R`-algebras, we do that case at the same time.
-/
universes u₁ u₂ u₃ u₄
variables {R : Type u₁} [semiring R]
variables {S : Type u₂} [comm_semiring S]
variables {A : Type u₃} [semiring A] [algebra S A]
namespace ring_quot
/--
Given an arbitrary relation `r` on a ring, we strengthen it to a relation `rel r`,
such that the equivalence relation generated by `rel r` has `x ~ y` if and only if
`x - y` is in the ideal generated by elements `a - b` such that `r a b`.
-/
inductive rel (r : R → R → Prop) : R → R → Prop
| of ⦃x y : R⦄ (h : r x y) : rel x y
| add_left ⦃a b c⦄ : rel a b → rel (a + c) (b + c)
| mul_left ⦃a b c⦄ : rel a b → rel (a * c) (b * c)
| mul_right ⦃a b c⦄ : rel b c → rel (a * b) (a * c)
theorem rel.add_right {r : R → R → Prop} ⦃a b c : R⦄ (h : rel r b c) : rel r (a + b) (a + c) :=
by { rw [add_comm a b, add_comm a c], exact rel.add_left h }
theorem rel.neg {R : Type u₁} [ring R] {r : R → R → Prop} ⦃a b : R⦄ (h : rel r a b) :
rel r (-a) (-b) :=
by simp only [neg_eq_neg_one_mul a, neg_eq_neg_one_mul b, rel.mul_right h]
theorem rel.sub_left {R : Type u₁} [ring R] {r : R → R → Prop} ⦃a b c : R⦄ (h : rel r a b) :
rel r (a - c) (b - c) :=
by simp only [sub_eq_add_neg, h.add_left]
theorem rel.sub_right {R : Type u₁} [ring R] {r : R → R → Prop} ⦃a b c : R⦄ (h : rel r b c) :
rel r (a - b) (a - c) :=
by simp only [sub_eq_add_neg, h.neg.add_right]
theorem rel.smul {r : A → A → Prop} (k : S) ⦃a b : A⦄ (h : rel r a b) : rel r (k • a) (k • b) :=
by simp only [algebra.smul_def, rel.mul_right h]
end ring_quot
/-- The quotient of a ring by an arbitrary relation. -/
structure ring_quot (r : R → R → Prop) :=
(to_quot : quot (ring_quot.rel r))
namespace ring_quot
variable (r : R → R → Prop)
@[irreducible] private def nat_cast (n : ℕ) : ring_quot r := ⟨quot.mk _ n⟩
@[irreducible] private def zero : ring_quot r := ⟨quot.mk _ 0⟩
@[irreducible] private def one : ring_quot r := ⟨quot.mk _ 1⟩
@[irreducible] private def add : ring_quot r → ring_quot r → ring_quot r
| ⟨a⟩ ⟨b⟩ := ⟨quot.map₂ (+) rel.add_right rel.add_left a b⟩
@[irreducible] private def mul : ring_quot r → ring_quot r → ring_quot r
| ⟨a⟩ ⟨b⟩ := ⟨quot.map₂ (*) rel.mul_right rel.mul_left a b⟩
@[irreducible] private def neg {R : Type u₁} [ring R] (r : R → R → Prop) : ring_quot r → ring_quot r
| ⟨a⟩:= ⟨quot.map (λ a, -a) rel.neg a⟩
@[irreducible] private def sub {R : Type u₁} [ring R] (r : R → R → Prop) :
ring_quot r → ring_quot r → ring_quot r
| ⟨a⟩ ⟨b⟩ := ⟨quot.map₂ has_sub.sub rel.sub_right rel.sub_left a b⟩
@[irreducible] private def npow (n : ℕ) : ring_quot r → ring_quot r
| ⟨a⟩ := ⟨quot.lift
(λ a, quot.mk (ring_quot.rel r) (a ^ n))
(λ a b (h : rel r a b), begin
-- note we can't define a `rel.pow` as `rel` isn't reflexive so `rel r 1 1` isn't true
dsimp only,
induction n,
{ rw [pow_zero, pow_zero] },
{ rw [pow_succ, pow_succ],
simpa only [mul] using congr_arg2 (λ x y, mul r ⟨x⟩ ⟨y⟩) (quot.sound h) n_ih }
end)
a⟩
@[irreducible] private def smul [algebra S R] (n : S) : ring_quot r → ring_quot r
| ⟨a⟩ := ⟨quot.map (λ a, n • a) (rel.smul n) a⟩
instance : has_zero (ring_quot r) := ⟨zero r⟩
instance : has_one (ring_quot r) := ⟨one r⟩
instance : has_add (ring_quot r) := ⟨add r⟩
instance : has_mul (ring_quot r) := ⟨mul r⟩
instance : has_pow (ring_quot r) ℕ := ⟨λ x n, npow r n x⟩
instance {R : Type u₁} [ring R] (r : R → R → Prop) : has_neg (ring_quot r) := ⟨neg r⟩
instance {R : Type u₁} [ring R] (r : R → R → Prop) : has_sub (ring_quot r) := ⟨sub r⟩
instance [algebra S R] : has_smul S (ring_quot r) := ⟨smul r⟩
lemma zero_quot : (⟨quot.mk _ 0⟩ : ring_quot r) = 0 := show _ = zero r, by rw zero
lemma one_quot : (⟨quot.mk _ 1⟩ : ring_quot r) = 1 := show _ = one r, by rw one
lemma add_quot {a b} : (⟨quot.mk _ a⟩ + ⟨quot.mk _ b⟩ : ring_quot r) = ⟨quot.mk _ (a + b)⟩ :=
by { show add r _ _ = _, rw add, refl }
lemma mul_quot {a b} : (⟨quot.mk _ a⟩ * ⟨quot.mk _ b⟩ : ring_quot r) = ⟨quot.mk _ (a * b)⟩ :=
by { show mul r _ _ = _, rw mul, refl }
lemma pow_quot {a} {n : ℕ}: (⟨quot.mk _ a⟩ ^ n : ring_quot r) = ⟨quot.mk _ (a ^ n)⟩ :=
by { show npow r _ _ = _, rw npow }
lemma neg_quot {R : Type u₁} [ring R] (r : R → R → Prop) {a} :
(-⟨quot.mk _ a⟩ : ring_quot r) = ⟨quot.mk _ (-a)⟩ :=
by { show neg r _ = _, rw neg, refl }
lemma sub_quot {R : Type u₁} [ring R] (r : R → R → Prop) {a b} :
(⟨quot.mk _ a⟩ - ⟨ quot.mk _ b⟩ : ring_quot r) = ⟨quot.mk _ (a - b)⟩ :=
by { show sub r _ _ = _, rw sub, refl }
lemma smul_quot [algebra S R] {n : S} {a : R} :
(n • ⟨quot.mk _ a⟩ : ring_quot r) = ⟨quot.mk _ (n • a)⟩ :=
by { show smul r _ _ = _, rw smul, refl }
instance (r : R → R → Prop) : semiring (ring_quot r) :=
{ add := (+),
mul := (*),
zero := 0,
one := 1,
nat_cast := nat_cast r,
nat_cast_zero := by simp [nat.cast, nat_cast, ← zero_quot],
nat_cast_succ := by simp [nat.cast, nat_cast, ← one_quot, add_quot],
add_assoc := by { rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨⟨⟩⟩, simp [add_quot, add_assoc] },
zero_add := by { rintros ⟨⟨⟩⟩, simp [add_quot, ← zero_quot] },
add_zero := by { rintros ⟨⟨⟩⟩, simp [add_quot, ← zero_quot], },
zero_mul := by { rintros ⟨⟨⟩⟩, simp [mul_quot, ← zero_quot], },
mul_zero := by { rintros ⟨⟨⟩⟩, simp [mul_quot, ← zero_quot], },
add_comm := by { rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩, simp [add_quot, add_comm], },
mul_assoc := by { rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨⟨⟩⟩, simp [mul_quot, mul_assoc] },
one_mul := by { rintros ⟨⟨⟩⟩, simp [mul_quot, ← one_quot] },
mul_one := by { rintros ⟨⟨⟩⟩, simp [mul_quot, ← one_quot] },
left_distrib := by { rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨⟨⟩⟩, simp [mul_quot, add_quot, left_distrib] },
right_distrib := by { rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩ ⟨⟨⟩⟩, simp [mul_quot, add_quot, right_distrib] },
npow := λ n x, x ^ n,
npow_zero' := by { rintros ⟨⟨⟩⟩, simp [pow_quot, ← one_quot] },
npow_succ' := by { rintros n ⟨⟨⟩⟩, simp [pow_quot, mul_quot, pow_succ] },
nsmul := (•),
nsmul_zero' := by { rintros ⟨⟨⟩⟩, simp [smul_quot, ← zero_quot] },
nsmul_succ' := by { rintros n ⟨⟨⟩⟩, simp [smul_quot, add_quot, add_mul, add_comm] } }
instance {R : Type u₁} [ring R] (r : R → R → Prop) : ring (ring_quot r) :=
{ neg := has_neg.neg,
add_left_neg := by { rintros ⟨⟨⟩⟩, simp [neg_quot, add_quot, ← zero_quot], },
sub := has_sub.sub,
sub_eq_add_neg := by { rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩, simp [neg_quot, sub_quot, add_quot, sub_eq_add_neg] },
zsmul := (•),
zsmul_zero' := by { rintros ⟨⟨⟩⟩, simp [smul_quot, ← zero_quot] },
zsmul_succ' := by { rintros n ⟨⟨⟩⟩, simp [smul_quot, add_quot, add_mul, add_comm] },
zsmul_neg' := by { rintros n ⟨⟨⟩⟩, simp [smul_quot, neg_quot, add_mul] },
.. (ring_quot.semiring r) }
instance {R : Type u₁} [comm_semiring R] (r : R → R → Prop) : comm_semiring (ring_quot r) :=
{ mul_comm := by { rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩, simp [mul_quot, mul_comm], }
.. (ring_quot.semiring r) }
instance {R : Type u₁} [comm_ring R] (r : R → R → Prop) : comm_ring (ring_quot r) :=
{ .. (ring_quot.comm_semiring r),
.. (ring_quot.ring r) }
instance (r : R → R → Prop) : inhabited (ring_quot r) := ⟨0⟩
instance [algebra S R] (r : R → R → Prop) : algebra S (ring_quot r) :=
{ smul := (•),
to_fun := λ r, ⟨quot.mk _ (algebra_map S R r)⟩,
map_one' := by simp [← one_quot],
map_mul' := by simp [mul_quot],
map_zero' := by simp [← zero_quot],
map_add' := by simp [add_quot],
commutes' := λ r, by { rintro ⟨⟨a⟩⟩, simp [algebra.commutes, mul_quot] },
smul_def' := λ r, by { rintro ⟨⟨a⟩⟩, simp [smul_quot, algebra.smul_def, mul_quot], }, }
/--
The quotient map from a ring to its quotient, as a homomorphism of rings.
-/
def mk_ring_hom (r : R → R → Prop) : R →+* ring_quot r :=
{ to_fun := λ x, ⟨quot.mk _ x⟩,
map_one' := by simp [← one_quot],
map_mul' := by simp [mul_quot],
map_zero' := by simp [← zero_quot],
map_add' := by simp [add_quot], }
lemma mk_ring_hom_rel {r : R → R → Prop} {x y : R} (w : r x y) :
mk_ring_hom r x = mk_ring_hom r y :=
by simp [mk_ring_hom, quot.sound (rel.of w)]
lemma mk_ring_hom_surjective (r : R → R → Prop) : function.surjective (mk_ring_hom r) :=
by { dsimp [mk_ring_hom], rintro ⟨⟨⟩⟩, simp, }
@[ext]
lemma ring_quot_ext {T : Type u₄} [semiring T] {r : R → R → Prop} (f g : ring_quot r →+* T)
(w : f.comp (mk_ring_hom r) = g.comp (mk_ring_hom r)) : f = g :=
begin
ext,
rcases mk_ring_hom_surjective r x with ⟨x, rfl⟩,
exact (ring_hom.congr_fun w x : _),
end
variables {T : Type u₄} [semiring T]
/--
Any ring homomorphism `f : R →+* T` which respects a relation `r : R → R → Prop`
factors uniquely through a morphism `ring_quot r →+* T`.
-/
def lift {r : R → R → Prop} :
{f : R →+* T // ∀ ⦃x y⦄, r x y → f x = f y} ≃ (ring_quot r →+* T) :=
{ to_fun := λ f', let f := (f' : R →+* T) in
{ to_fun := λ x, quot.lift f
begin
rintros _ _ r,
induction r,
case of : _ _ r { exact f'.prop r, },
case add_left : _ _ _ _ r' { simp [r'], },
case mul_left : _ _ _ _ r' { simp [r'], },
case mul_right : _ _ _ _ r' { simp [r'], },
end x.to_quot,
map_zero' := by simp [← zero_quot, f.map_zero],
map_add' := by { rintros ⟨⟨x⟩⟩ ⟨⟨y⟩⟩, simp [add_quot, f.map_add x y], },
map_one' := by simp [← one_quot, f.map_one],
map_mul' := by { rintros ⟨⟨x⟩⟩ ⟨⟨y⟩⟩, simp [mul_quot, f.map_mul x y] }, },
inv_fun := λ F, ⟨F.comp (mk_ring_hom r), λ x y h, by { dsimp, rw mk_ring_hom_rel h, }⟩,
left_inv := λ f, by { ext, simp, refl },
right_inv := λ F, by { ext, simp, refl } }
@[simp]
lemma lift_mk_ring_hom_apply (f : R →+* T) {r : R → R → Prop} (w : ∀ ⦃x y⦄, r x y → f x = f y) (x) :
lift ⟨f, w⟩ (mk_ring_hom r x) = f x :=
rfl
-- note this is essentially `lift.symm_apply_eq.mp h`
lemma lift_unique (f : R →+* T) {r : R → R → Prop} (w : ∀ ⦃x y⦄, r x y → f x = f y)
(g : ring_quot r →+* T) (h : g.comp (mk_ring_hom r) = f) : g = lift ⟨f, w⟩ :=
by { ext, simp [h], }
lemma eq_lift_comp_mk_ring_hom {r : R → R → Prop} (f : ring_quot r →+* T) :
f = lift ⟨f.comp (mk_ring_hom r), λ x y h, by { dsimp, rw mk_ring_hom_rel h, }⟩ :=
(lift.apply_symm_apply f).symm
section comm_ring
/-!
We now verify that in the case of a commutative ring, the `ring_quot` construction
agrees with the quotient by the appropriate ideal.
-/
variables {B : Type u₁} [comm_ring B]
/-- The universal ring homomorphism from `ring_quot r` to `B ⧸ ideal.of_rel r`. -/
def ring_quot_to_ideal_quotient (r : B → B → Prop) :
ring_quot r →+* B ⧸ ideal.of_rel r :=
lift
⟨ideal.quotient.mk (ideal.of_rel r),
λ x y h, ideal.quotient.eq.2 $ submodule.mem_Inf.mpr (λ p w, w ⟨x, y, h, sub_add_cancel x y⟩)⟩
@[simp] lemma ring_quot_to_ideal_quotient_apply (r : B → B → Prop) (x : B) :
ring_quot_to_ideal_quotient r (mk_ring_hom r x) = ideal.quotient.mk _ x := rfl
/-- The universal ring homomorphism from `B ⧸ ideal.of_rel r` to `ring_quot r`. -/
def ideal_quotient_to_ring_quot (r : B → B → Prop) :
B ⧸ ideal.of_rel r →+* ring_quot r :=
ideal.quotient.lift (ideal.of_rel r) (mk_ring_hom r)
begin
refine λ x h, submodule.span_induction h _ _ _ _,
{ rintro y ⟨a, b, h, su⟩,
symmetry' at su,
rw ←sub_eq_iff_eq_add at su,
rw [ ← su, ring_hom.map_sub, mk_ring_hom_rel h, sub_self], },
{ simp, },
{ intros a b ha hb, simp [ha, hb], },
{ intros a x hx, simp [hx], },
end
@[simp] lemma ideal_quotient_to_ring_quot_apply (r : B → B → Prop) (x : B) :
ideal_quotient_to_ring_quot r (ideal.quotient.mk _ x) = mk_ring_hom r x := rfl
/--
The ring equivalence between `ring_quot r` and `(ideal.of_rel r).quotient`
-/
def ring_quot_equiv_ideal_quotient (r : B → B → Prop) :
ring_quot r ≃+* B ⧸ ideal.of_rel r :=
ring_equiv.of_hom_inv (ring_quot_to_ideal_quotient r) (ideal_quotient_to_ring_quot r)
(by { ext, refl, }) (by { ext, refl, })
end comm_ring
section star_ring
variables [star_ring R] (r) (hr : ∀ a b, r a b → r (star a) (star b))
include hr
theorem rel.star ⦃a b : R⦄ (h : rel r a b) :
rel r (star a) (star b) :=
begin
induction h,
{ exact rel.of (hr _ _ h_h) },
{ rw [star_add, star_add], exact rel.add_left h_ih, },
{ rw [star_mul, star_mul], exact rel.mul_right h_ih, },
{ rw [star_mul, star_mul], exact rel.mul_left h_ih, },
end
@[irreducible] private def star' : ring_quot r → ring_quot r
| ⟨a⟩ := ⟨quot.map (star : R → R) (rel.star r hr) a⟩
lemma star'_quot (hr : ∀ a b, r a b → r (star a) (star b)) {a} :
(star' r hr ⟨quot.mk _ a⟩ : ring_quot r) = ⟨quot.mk _ (star a)⟩ :=
by { show star' r _ _ = _, rw star', refl }
/-- Transfer a star_ring instance through a quotient, if the quotient is invariant to `star` -/
def star_ring {R : Type u₁} [semiring R] [star_ring R] (r : R → R → Prop)
(hr : ∀ a b, r a b → r (star a) (star b)) :
star_ring (ring_quot r) :=
{ star := star' r hr,
star_involutive := by { rintros ⟨⟨⟩⟩, simp [star'_quot], },
star_mul := by { rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩, simp [star'_quot, mul_quot, star_mul], },
star_add := by { rintros ⟨⟨⟩⟩ ⟨⟨⟩⟩, simp [star'_quot, add_quot, star_add], } }
end star_ring
section algebra
variables (S)
/--
The quotient map from an `S`-algebra to its quotient, as a homomorphism of `S`-algebras.
-/
def mk_alg_hom (s : A → A → Prop) : A →ₐ[S] ring_quot s :=
{ commutes' := λ r, rfl,
..mk_ring_hom s }
@[simp]
lemma mk_alg_hom_coe (s : A → A → Prop) : (mk_alg_hom S s : A →+* ring_quot s) = mk_ring_hom s :=
rfl
lemma mk_alg_hom_rel {s : A → A → Prop} {x y : A} (w : s x y) :
mk_alg_hom S s x = mk_alg_hom S s y :=
by simp [mk_alg_hom, mk_ring_hom, quot.sound (rel.of w)]
lemma mk_alg_hom_surjective (s : A → A → Prop) : function.surjective (mk_alg_hom S s) :=
by { dsimp [mk_alg_hom], rintro ⟨⟨a⟩⟩, use a, refl, }
variables {B : Type u₄} [semiring B] [algebra S B]
@[ext]
lemma ring_quot_ext' {s : A → A → Prop}
(f g : ring_quot s →ₐ[S] B) (w : f.comp (mk_alg_hom S s) = g.comp (mk_alg_hom S s)) : f = g :=
begin
ext,
rcases mk_alg_hom_surjective S s x with ⟨x, rfl⟩,
exact (alg_hom.congr_fun w x : _),
end
/--
Any `S`-algebra homomorphism `f : A →ₐ[S] B` which respects a relation `s : A → A → Prop`
factors uniquely through a morphism `ring_quot s →ₐ[S] B`.
-/
def lift_alg_hom {s : A → A → Prop} :
{ f : A →ₐ[S] B // ∀ ⦃x y⦄, s x y → f x = f y} ≃ (ring_quot s →ₐ[S] B) :=
{ to_fun := λ f', let f := (f' : A →ₐ[S] B) in
{ to_fun := λ x, quot.lift f
begin
rintros _ _ r,
induction r,
case of : _ _ r { exact f'.prop r, },
case add_left : _ _ _ _ r' { simp [r'], },
case mul_left : _ _ _ _ r' { simp [r'], },
case mul_right : _ _ _ _ r' { simp [r'], },
end x.to_quot,
map_zero' := by simp [← zero_quot, f.map_zero],
map_add' := by { rintros ⟨⟨x⟩⟩ ⟨⟨y⟩⟩, simp [add_quot, f.map_add x y] },
map_one' := by simp [← one_quot, f.map_one],
map_mul' := by { rintros ⟨⟨x⟩⟩ ⟨⟨y⟩⟩, simp [mul_quot, f.map_mul x y], },
commutes' := by { rintros x, simp [← one_quot, smul_quot, algebra.algebra_map_eq_smul_one] } },
inv_fun := λ F, ⟨F.comp (mk_alg_hom S s), λ _ _ h, by { dsimp, erw mk_alg_hom_rel S h }⟩,
left_inv := λ f, by { ext, simp, refl },
right_inv := λ F, by { ext, simp, refl } }
@[simp]
lemma lift_alg_hom_mk_alg_hom_apply (f : A →ₐ[S] B) {s : A → A → Prop}
(w : ∀ ⦃x y⦄, s x y → f x = f y) (x) :
(lift_alg_hom S ⟨f, w⟩) ((mk_alg_hom S s) x) = f x :=
rfl
-- note this is essentially `(lift_alg_hom S).symm_apply_eq.mp h`
lemma lift_alg_hom_unique (f : A →ₐ[S] B) {s : A → A → Prop} (w : ∀ ⦃x y⦄, s x y → f x = f y)
(g : ring_quot s →ₐ[S] B) (h : g.comp (mk_alg_hom S s) = f) : g = lift_alg_hom S ⟨f, w⟩ :=
by { ext, simp [h], }
lemma eq_lift_alg_hom_comp_mk_alg_hom {s : A → A → Prop} (f : ring_quot s →ₐ[S] B) :
f = lift_alg_hom S ⟨f.comp (mk_alg_hom S s), λ x y h, by { dsimp, erw mk_alg_hom_rel S h, }⟩ :=
((lift_alg_hom S).apply_symm_apply f).symm
end algebra
attribute [irreducible] mk_ring_hom mk_alg_hom lift lift_alg_hom
end ring_quot
|
20768978d47ad009e07f1ba4d0486e0791038f50 | c9ba4946202cfd1e2586e71960dfed00503dcdf4 | /src/meta_k/meta_sort.lean | 1b3b819b70d4d5fbca6e2d66d387acda1de2ee4f | [] | no_license | ammkrn/learning_semantics_of_k | f55f669b369e32ef8407c16521b21ac5c106dc4d | c1487b538e1decc0f1fd389cd36bc36d2da012ab | refs/heads/master | 1,588,081,593,954 | 1,552,449,093,000 | 1,552,449,093,000 | 175,315,800 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,338 | lean | open nat
-- #########################################################
-- ##### meta-sort ########################################
instance {α : Type*} [has_repr α] : has_repr (id α) := by dsimp; apply_instance
class has_name (α : Type) :=
(get_name : α → string)
notation `getName` := has_name.get_name
class is_Sort (α : Type) :=
(get_sort_params : α → list α)
notation `getSortParameters` := is_Sort.get_sort_params
class has_sort (α : Type) (S : out_param Type) [out_param (is_Sort S)] :=
(get_sort : α → S)
notation `getSort` := has_sort.get_sort
class is_Variable (V : Type) :=
(witness : V → string)
class is_Symbol (σ : Type) :=
(S : Type) [S_ : is_Sort S]
(get_argument_sorts : σ → list S)
(get_return_sort : σ → S)
notation `getArgumentSorts` := is_Symbol.get_argument_sorts
notation `getReturnSort` := is_Symbol.get_return_sorts
class is_Pattern (φ : Type) :=
(V : Type) [V_ : is_Variable V]
(S : Type) [S_ : is_Sort S]
(isTop : φ → bool)
(isBottom : φ → bool)
(getFV : φ → list V)
(getFVFromPatterns : list φ → list V)
(occursFree : S → V → φ → φ)
(BtoP : bool → (S → φ))
(sc : S → φ → φ → φ)
(sc_l : S → φ → list φ → φ)
(freshName : list φ → string)
(substitute_i : φ → φ → V → option φ)
notation `#String` := string
inductive meta_sort_variable
| mk : string → meta_sort_variable
/-
Lean does allow for this to be defined as a nested inductive type,
(IE mk : string → list meta_sort → meta_sort), but in the current version
it gets reduced to a very scary looking regular inductive type that ends up
not working very well (especially wrt VM evaluation), so for now
I'm just defining it as a mutual inductive.
-/
mutual inductive meta_sort, meta_sort_list
with meta_sort : Type
| mk : string → meta_sort_list → meta_sort
with meta_sort_list : Type
| nil : meta_sort_list
| cons : meta_sort → meta_sort_list → meta_sort_list
open meta_sort
open meta_sort_list
def meta_sort_list.to_list_meta_sort : meta_sort_list → list meta_sort
| nil := []
| (cons hd tl) := hd :: (meta_sort_list.to_list_meta_sort tl)
def list_meta_sort.to_meta_sort_list : list meta_sort → meta_sort_list
| [] := meta_sort_list.nil
| (hd :: tl) := cons hd (list_meta_sort.to_meta_sort_list tl)
instance meta_sort_list_to_list_meta_sort_lift :
has_lift meta_sort_list (list meta_sort) :=
⟨ meta_sort_list.to_list_meta_sort ⟩
instance list_meta_sort_to_meta_sort_list :
has_lift (list meta_sort) (meta_sort_list) :=
⟨ list_meta_sort.to_meta_sort_list ⟩
instance : decidable_eq meta_sort_variable :=
by tactic.mk_dec_eq_instance
instance : decidable_eq meta_sort :=
by tactic.mk_dec_eq_instance
instance : decidable_eq meta_sort_list :=
by tactic.mk_dec_eq_instance
notation `#Sort` := meta_sort
notation `#SortList` := list meta_sort
notation `#sort` := meta_sort.mk
notation `#ε` := meta_sort_list.nil
notation `#nilSortList` := (meta_sort_list.nil)
notation `#consSortList` := (meta_sort_list.cons)
def meta_sort_variable.to_string : meta_sort_variable → string
| (meta_sort_variable.mk str) := str
instance : has_repr meta_sort_variable := ⟨ meta_sort_variable.to_string ⟩
mutual def meta_sort_to_string, meta_sort_list_to_string
with meta_sort_to_string : meta_sort → string
| (#sort str L) := "#Sort : (" ++ repr str ++ ", " ++ (meta_sort_list_to_string L) ++ "), "
with meta_sort_list_to_string : meta_sort_list → string
| (meta_sort_list.nil) := "#sort_ε"
| (meta_sort_list.cons s l) := meta_sort_to_string s ++ meta_sort_list_to_string l
def pretty_meta_sort_list_to_string : meta_sort_list → string
| meta_sort_list.nil := ""
| l := "[" ++ string.popn_back (meta_sort_list_to_string l) 7 ++ "]"
instance : has_repr meta_sort_list := ⟨ pretty_meta_sort_list_to_string ⟩
def pretty_meta_sort_to_string : meta_sort → string
| (#sort str meta_sort_list.nil) := (repr str) ++ " #ε"
| (#sort str L) := "#sort " ++ (repr str) ++ " : " ++ repr L
instance : has_repr meta_sort := ⟨ pretty_meta_sort_to_string ⟩
def meta_sort_name : meta_sort → string
| (#sort a b) := a
def meta_sort_list_name : meta_sort_list → string
| (meta_sort_list.nil) := ""
| (meta_sort_list.cons s l) := meta_sort_name s
def meta_sort_params : meta_sort → meta_sort_list
| (#sort a b) := b
def meta_sort_params_for_class : meta_sort → list meta_sort
| (#sort a b) := (lift b)
instance : is_Sort meta_sort := ⟨ meta_sort_params_for_class ⟩
-- This cannot be implemented as a lift, since the items being
-- converted are going from type land to value land.
def meta_sort_sort : #Sort := #sort "#Sort" #ε
def meta_sort_sort_list : #Sort := #sort "#SortList" #ε
def meta_sort_var : #Sort := #sort "#Variable" #ε
def meta_sort_var_list : #Sort := #sort "#VariableList" #ε
def meta_sort_symbol : #Sort := #sort "#Symbol" #ε
def meta_sort_symbol_list : #Sort := #sort "#SymbolList" #ε
def meta_sort_pattern : #Sort := #sort "#Pattern" #ε
def meta_sort_pattern_list : #Sort := #sort "#PatternList" #ε
def meta_sort_char : #Sort := #sort "#Char" #ε
def meta_sort_char_list : #Sort := #sort "#CharList" #ε
def meta_sort_string : #Sort := #sort "#String" #ε
notation `%Sort` := meta_sort_sort
notation `%SortList` := meta_sort_sort_list
notation `%Variable` := meta_sort_var
notation `%VariableList` := meta_sort_var_list
notation `%Symbol` := meta_sort_symbol
notation `%SymbolList` := meta_sort_symbol_list
notation `%Pattern` := meta_sort_pattern
notation `%PatternList` := meta_sort_pattern_list
notation `%Char` := meta_sort_char
notation `%CharList` := meta_sort_char_list
notation `%String` := meta_sort_string
-- ############ Coercions/Lifts
@[reducible]
def meta_sort_list.to_meta_sort : #SortList → #Sort
| L := #sort "#SortList" (lift L)
instance meta_sort_list_to_meta_sort_lift : has_lift #SortList #Sort := ⟨ meta_sort_list.to_meta_sort ⟩
def Sₖ : list #Sort := [
%Sort,
%SortList,
%Variable,
%VariableList,
%Symbol,
%SymbolList,
%Pattern,
%PatternList,
%Char,
%CharList,
%String
]
def delete_sort_list {S : Type} [is_Sort S] [decidable_eq S]: S → list S → list S
| s [] := []
| s (hd :: tl) := if s = hd then delete_sort_list s tl else hd :: delete_sort_list s tl
|
b32e0ef21fdcf05ffc20a1c14f1ee2dd04611611 | 30b012bb72d640ec30c8fdd4c45fdfa67beb012c | /data/list/sort.lean | df34d9aade784058dcf15f758161b9b6ec07bc7f | [
"Apache-2.0"
] | permissive | kckennylau/mathlib | 21fb810b701b10d6606d9002a4004f7672262e83 | 47b3477e20ffb5a06588dd3abb01fe0fe3205646 | refs/heads/master | 1,634,976,409,281 | 1,542,042,832,000 | 1,542,319,733,000 | 109,560,458 | 0 | 0 | Apache-2.0 | 1,542,369,208,000 | 1,509,867,494,000 | Lean | UTF-8 | Lean | false | false | 10,223 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad
Insertion sort and merge sort.
-/
import data.list.perm
open list.perm
namespace list
section sorted
universe variable uu
variables {α : Type uu} {r : α → α → Prop}
/-- `sorted r l` is the same as `pairwise r l`, preferred in the case that `r`
is a `<` or `≤`-like relation (transitive and antisymmetric or asymmetric) -/
def sorted := @pairwise
@[simp] theorem sorted_nil : sorted r [] := pairwise.nil _
@[simp] theorem sorted_singleton (a : α) : sorted r [a] := pairwise_singleton _ _
theorem sorted_of_sorted_cons {a : α} {l : list α} : sorted r (a :: l) → sorted r l :=
pairwise_of_pairwise_cons
theorem rel_of_sorted_cons {a : α} {l : list α} : sorted r (a :: l) →
∀ b ∈ l, r a b :=
rel_of_pairwise_cons
@[simp] theorem sorted_cons {a : α} {l : list α} :
sorted r (a :: l) ↔ (∀ b ∈ l, r a b) ∧ sorted r l :=
pairwise_cons
theorem eq_of_sorted_of_perm [is_antisymm α r]
{l₁ l₂ : list α} (p : l₁ ~ l₂) (s₁ : sorted r l₁) (s₂ : sorted r l₂) : l₁ = l₂ :=
begin
induction s₁ with a l₁ h₁ s₁ IH generalizing l₂,
{ rw eq_nil_of_perm_nil p },
{ have : a ∈ l₂ := perm_subset p (mem_cons_self _ _),
rcases mem_split this with ⟨u₂, v₂, rfl⟩,
have p' := (perm_cons a).1 (p.trans perm_middle),
have := IH p' (pairwise_of_sublist (by simp) s₂), subst l₁,
change a::u₂ ++ v₂ = u₂ ++ ([a] ++ v₂), rw ← append_assoc, congr,
have : ∀ (x : α) (h : x ∈ u₂), x = a := λ x m,
antisymm ((pairwise_append.1 s₂).2.2 _ m a (mem_cons_self _ _))
(h₁ _ (by simp [m])),
rw [(@eq_repeat _ a (length u₂ + 1) (a::u₂)).2,
(@eq_repeat _ a (length u₂ + 1) (u₂++[a])).2];
split; simp [iff_true_intro this, or_comm] }
end
end sorted
/-
sorting procedures
-/
section sort
universe variable uu
parameters {α : Type uu} (r : α → α → Prop) [decidable_rel r]
local infix `≼` : 50 := r
/- insertion sort -/
section insertion_sort
/-- `ordered_insert a l` inserts `a` into `l` at such that
`ordered_insert a l` is sorted if `l` is. -/
@[simp] def ordered_insert (a : α) : list α → list α
| [] := [a]
| (b :: l) := if a ≼ b then a :: b :: l else b :: ordered_insert l
/-- `insertion_sort l` returns `l` sorted using the insertion sort algorithm. -/
@[simp] def insertion_sort : list α → list α
| [] := []
| (b :: l) := ordered_insert b (insertion_sort l)
section correctness
open perm
theorem perm_ordered_insert (a) : ∀ l : list α, ordered_insert a l ~ a :: l
| [] := perm.refl _
| (b :: l) := by by_cases a ≼ b; [simp [ordered_insert, h],
simpa [ordered_insert, h] using
(perm.skip _ (perm_ordered_insert l)).trans (perm.swap _ _ _)]
theorem perm_insertion_sort : ∀ l : list α, insertion_sort l ~ l
| [] := perm.nil
| (b :: l) := by simpa [insertion_sort] using
(perm_ordered_insert _ _ _).trans (perm.skip b (perm_insertion_sort l))
section total_and_transitive
variables [is_total α r] [is_trans α r]
theorem sorted_ordered_insert (a : α) : ∀ l, sorted r l → sorted r (ordered_insert a l)
| [] h := sorted_singleton a
| (b :: l) h := begin
by_cases h' : a ≼ b,
{ simpa [ordered_insert, h', h] using λ b' bm, trans h' (rel_of_sorted_cons h _ bm) },
{ suffices : ∀ (b' : α), b' ∈ ordered_insert r a l → r b b',
{ simpa [ordered_insert, h', sorted_ordered_insert l (sorted_of_sorted_cons h)] },
intros b' bm,
cases (show b' = a ∨ b' ∈ l, by simpa using
perm_subset (perm_ordered_insert _ _ _) bm) with be bm,
{ subst b', exact (total_of r _ _).resolve_left h' },
{ exact rel_of_sorted_cons h _ bm } }
end
theorem sorted_insertion_sort : ∀ l, sorted r (insertion_sort l)
| [] := sorted_nil
| (a :: l) := sorted_ordered_insert a _ (sorted_insertion_sort l)
end total_and_transitive
end correctness
end insertion_sort
/- merge sort -/
section merge_sort
-- TODO(Jeremy): observation: if instead we write (a :: (split l).1, b :: (split l).2), the
-- equation compiler can't prove the third equation
/-- Split `l` into two lists of approximately equal length.
split [1, 2, 3, 4, 5] = ([1, 3, 5], [2, 4]) -/
@[simp] def split : list α → list α × list α
| [] := ([], [])
| (a :: l) := let (l₁, l₂) := split l in (a :: l₂, l₁)
theorem split_cons_of_eq (a : α) {l l₁ l₂ : list α} (h : split l = (l₁, l₂)) :
split (a :: l) = (a :: l₂, l₁) :=
by rw [split, h]; refl
theorem length_split_le : ∀ {l l₁ l₂ : list α},
split l = (l₁, l₂) → length l₁ ≤ length l ∧ length l₂ ≤ length l
| [] ._ ._ rfl := ⟨nat.le_refl 0, nat.le_refl 0⟩
| (a::l) l₁' l₂' h := begin
cases e : split l with l₁ l₂,
injection (split_cons_of_eq _ e).symm.trans h, substs l₁' l₂',
cases length_split_le e with h₁ h₂,
exact ⟨nat.succ_le_succ h₂, nat.le_succ_of_le h₁⟩
end
theorem length_split_lt {a b} {l l₁ l₂ : list α} (h : split (a::b::l) = (l₁, l₂)) :
length l₁ < length (a::b::l) ∧ length l₂ < length (a::b::l) :=
begin
cases e : split l with l₁' l₂',
injection (split_cons_of_eq _ (split_cons_of_eq _ e)).symm.trans h, substs l₁ l₂,
cases length_split_le e with h₁ h₂,
exact ⟨nat.succ_le_succ (nat.succ_le_succ h₁), nat.succ_le_succ (nat.succ_le_succ h₂)⟩
end
theorem perm_split : ∀ {l l₁ l₂ : list α}, split l = (l₁, l₂) → l ~ l₁ ++ l₂
| [] ._ ._ rfl := perm.refl _
| (a::l) l₁' l₂' h := begin
cases e : split l with l₁ l₂,
injection (split_cons_of_eq _ e).symm.trans h, substs l₁' l₂',
exact perm.skip a ((perm_split e).trans perm_app_comm),
end
/-- Merge two sorted lists into one in linear time.
merge [1, 2, 4, 5] [0, 1, 3, 4] = [0, 1, 1, 2, 3, 4, 4, 5] -/
def merge : list α → list α → list α
| [] l' := l'
| l [] := l
| (a :: l) (b :: l') := if a ≼ b then a :: merge l (b :: l') else b :: merge (a :: l) l'
include r
/-- Implementation of a merge sort algorithm to sort a list. -/
def merge_sort : list α → list α
| [] := []
| [a] := [a]
| (a::b::l) := begin
cases e : split (a::b::l) with l₁ l₂,
cases length_split_lt e with h₁ h₂,
exact merge r (merge_sort l₁) (merge_sort l₂)
end
using_well_founded {
rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩],
dec_tac := tactic.assumption }
theorem merge_sort_cons_cons {a b} {l l₁ l₂ : list α}
(h : split (a::b::l) = (l₁, l₂)) :
merge_sort (a::b::l) = merge (merge_sort l₁) (merge_sort l₂) :=
begin
suffices : ∀ (L : list α) h1, @@and.rec
(λ a a (_ : length l₁ < length l + 1 + 1 ∧
length l₂ < length l + 1 + 1), L) h1 h1 = L,
{ simp [merge_sort, h], apply this },
intros, cases h1, refl
end
section correctness
theorem perm_merge : ∀ (l l' : list α), merge l l' ~ l ++ l'
| [] [] := perm.nil
| [] (b :: l') := by simp [merge]
| (a :: l) [] := by simp [merge]
| (a :: l) (b :: l') := begin
by_cases a ≼ b,
{ simpa [merge, h] using skip _ (perm_merge _ _) },
{ suffices : b :: merge r (a :: l) l' ~ a :: (l ++ b :: l'), {simpa [merge, h]},
exact (skip _ (perm_merge _ _)).trans ((swap _ _ _).trans (skip _ perm_middle.symm)) }
end
theorem perm_merge_sort : ∀ l : list α, merge_sort l ~ l
| [] := perm.refl _
| [a] := perm.refl _
| (a::b::l) := begin
cases e : split (a::b::l) with l₁ l₂,
cases length_split_lt e with h₁ h₂,
rw [merge_sort_cons_cons r e],
apply (perm_merge r _ _).trans,
exact (perm_app (perm_merge_sort l₁) (perm_merge_sort l₂)).trans (perm_split e).symm
end
using_well_founded {
rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩],
dec_tac := tactic.assumption }
section total_and_transitive
variables [is_total α r] [is_trans α r]
theorem sorted_merge : ∀ {l l' : list α}, sorted r l → sorted r l' → sorted r (merge l l')
| [] [] h₁ h₂ := sorted_nil
| [] (b :: l') h₁ h₂ := by simpa [merge] using h₂
| (a :: l) [] h₁ h₂ := by simpa [merge] using h₁
| (a :: l) (b :: l') h₁ h₂ := begin
by_cases a ≼ b,
{ suffices : ∀ (b' : α) (_ : b' ∈ merge r l (b :: l')), r a b',
{ simpa [merge, h, sorted_merge (sorted_of_sorted_cons h₁) h₂] },
intros b' bm,
rcases (show b' = b ∨ b' ∈ l ∨ b' ∈ l', by simpa [or.left_comm] using
perm_subset (perm_merge _ _ _) bm) with be | bl | bl',
{ subst b', assumption },
{ exact rel_of_sorted_cons h₁ _ bl },
{ exact trans h (rel_of_sorted_cons h₂ _ bl') } },
{ suffices : ∀ (b' : α) (_ : b' ∈ merge r (a :: l) l'), r b b',
{ simpa [merge, h, sorted_merge h₁ (sorted_of_sorted_cons h₂)] },
intros b' bm,
have ba : b ≼ a := (total_of r _ _).resolve_left h,
rcases (show b' = a ∨ b' ∈ l ∨ b' ∈ l', by simpa using
perm_subset (perm_merge _ _ _) bm) with be | bl | bl',
{ subst b', assumption },
{ exact trans ba (rel_of_sorted_cons h₁ _ bl) },
{ exact rel_of_sorted_cons h₂ _ bl' } }
end
theorem sorted_merge_sort : ∀ l : list α, sorted r (merge_sort l)
| [] := sorted_nil
| [a] := sorted_singleton _
| (a::b::l) := begin
cases e : split (a::b::l) with l₁ l₂,
cases length_split_lt e with h₁ h₂,
rw [merge_sort_cons_cons r e],
exact sorted_merge r (sorted_merge_sort l₁) (sorted_merge_sort l₂)
end
using_well_founded {
rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩],
dec_tac := tactic.assumption }
theorem merge_sort_eq_self [is_antisymm α r] {l : list α} : sorted r l → merge_sort l = l :=
eq_of_sorted_of_perm (perm_merge_sort _) (sorted_merge_sort _)
end total_and_transitive
end correctness
end merge_sort
end sort
/- try them out! -/
--#eval insertion_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12]
--#eval merge_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12]
end list
|
e371c44411a4117697505d447a56c205f74b73f0 | 6e41ee3ac9b96e8980a16295cc21f131e731884f | /hott/init/axioms/funext_varieties.hlean | b3d5b4ff8dc6e0fe7d41782f3371d087cf84f6f3 | [
"Apache-2.0"
] | permissive | EgbertRijke/lean | 3426cfa0e5b3d35d12fc3fd7318b35574cb67dc3 | 4f2e0c6d7fc9274d953cfa1c37ab2f3e799ab183 | refs/heads/master | 1,610,834,871,476 | 1,422,159,801,000 | 1,422,159,801,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,408 | hlean | -- Copyright (c) 2014 Jakob von Raumer. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Jakob von Raumer
-- Ported from Coq HoTT
prelude
import ..path ..trunc ..equiv .funext
open eq truncation sigma function
/- In hott.axioms.funext, we defined function extensionality to be the assertion
that the map apD10 is an equivalence. We now prove that this follows
from a couple of weaker-looking forms of function extensionality. We do
require eta conversion, which Coq 8.4+ has judgmentally.
This proof is originally due to Voevodsky; it has since been simplified
by Peter Lumsdaine and Michael Shulman. -/
-- Naive funext is the simple assertion that pointwise equal functions are equal.
-- TODO think about universe levels
definition naive_funext :=
Π {A : Type} {P : A → Type} (f g : Πx, P x), (f ∼ g) → f = g
-- Weak funext says that a product of contractible types is contractible.
definition weak_funext :=
Π {A : Type} (P : A → Type) [H: Πx, is_contr (P x)], is_contr (Πx, P x)
-- The obvious implications are Funext -> NaiveFunext -> WeakFunext
-- TODO: Get class inference to work locally
definition naive_funext_from_funext [F : funext] : naive_funext :=
(λ A P f g h,
have Fefg: is_equiv (@apD10 A P f g),
from (@funext.ap F A P f g),
have eq1 : _, from (@is_equiv.inv _ _ (@apD10 A P f g) Fefg h),
eq1
)
definition weak_funext_from_naive_funext : naive_funext → weak_funext :=
(λ nf A P (Pc : Πx, is_contr (P x)),
let c := λx, center (P x) in
is_contr.mk c (λ f,
have eq' : (λx, center (P x)) ∼ f,
from (λx, contr (f x)),
have eq : (λx, center (P x)) = f,
from nf A P (λx, center (P x)) f eq',
eq
)
)
/- The less obvious direction is that WeakFunext implies Funext
(and hence all three are logically equivalent). The point is that under weak
funext, the space of "pointwise homotopies" has the same universal property as
the space of paths. -/
context
universes l k
parameters (wf : weak_funext.{l k}) {A : Type.{l}} {B : A → Type.{k}} (f : Π x, B x)
protected definition idhtpy : f ∼ f := (λ x, idp)
definition contr_basedhtpy [instance] : is_contr (Σ (g : Π x, B x), f ∼ g) :=
is_contr.mk (sigma.mk f idhtpy)
(λ dp, sigma.rec_on dp
(λ (g : Π x, B x) (h : f ∼ g),
let r := λ (k : Π x, Σ y, f x = y),
@sigma.mk _ (λg, f ∼ g)
(λx, pr1 (k x)) (λx, pr2 (k x)) in
let s := λ g h x, @sigma.mk _ (λy, f x = y) (g x) (h x) in
have t1 : Πx, is_contr (Σ y, f x = y),
from (λx, !contr_basedpaths),
have t2 : is_contr (Πx, Σ y, f x = y),
from !wf,
have t3 : (λ x, @sigma.mk _ (λ y, f x = y) (f x) idp) = s g h,
from @path_contr (Π x, Σ y, f x = y) t2 _ _,
have t4 : r (λ x, sigma.mk (f x) idp) = r (s g h),
from ap r t3,
have endt : sigma.mk f idhtpy = sigma.mk g h,
from t4,
endt
)
)
parameters (Q : Π g (h : f ∼ g), Type) (d : Q f idhtpy)
definition htpy_ind (g : Πx, B x) (h : f ∼ g) : Q g h :=
@transport _ (λ gh, Q (pr1 gh) (pr2 gh)) (sigma.mk f idhtpy) (sigma.mk g h)
(@path_contr _ contr_basedhtpy _ _) d
attribute htpy_ind [reducible]
definition htpy_ind_beta : htpy_ind f idhtpy = d :=
(@path2_contr _ _ _ _ !path_contr idp)⁻¹ ▹ idp
end
-- Now the proof is fairly easy; we can just use the same induction principle on both sides.
universe variables l k
theorem funext_from_weak_funext (wf : weak_funext.{l k}) : funext.{l k} :=
funext.mk (λ A B f g,
let eq_to_f := (λ g' x, f = g') in
let sim2path := htpy_ind _ f eq_to_f idp in
have t1 : sim2path f (idhtpy f) = idp,
proof htpy_ind_beta _ f eq_to_f idp qed,
have t2 : apD10 (sim2path f (idhtpy f)) = (idhtpy f),
proof ap apD10 t1 qed,
have sect : apD10 ∘ (sim2path g) ∼ id,
proof (htpy_ind _ f (λ g' x, apD10 (sim2path g' x) = x) t2) g qed,
have retr : (sim2path g) ∘ apD10 ∼ id,
from (λ h, eq.rec_on h (htpy_ind_beta _ f _ idp)),
is_equiv.adjointify apD10 (sim2path g) sect retr)
definition funext_from_naive_funext : naive_funext -> funext :=
compose funext_from_weak_funext weak_funext_from_naive_funext
|
5e912f6479f4419ac58e7984db2fed092abb713c | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/algebraic_topology/simplex_category.lean | 5281c9f780845a95e810a371213bd620ccad4bab | [
"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 | 14,113 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Scott Morrison, Adam Topaz
-/
import order.category.NonemptyFinLinOrd
import category_theory.skeletal
import data.finset.sort
import tactic.linarith
/-! # The simplex category
We construct a skeletal model of the simplex category, with objects `ℕ` and the
morphism `n ⟶ m` being the monotone maps from `fin (n+1)` to `fin (m+1)`.
We show that this category is equivalent to `NonemptyFinLinOrd`.
## Remarks
The definitions `simplex_category` and `simplex_category.hom` are marked as irreducible.
We provide the following functions to work with these objects:
1. `simplex_category.mk` creates an object of `simplex_category` out of a natural number.
Use the notation `[n]` in the `simplicial` locale.
2. `simplex_category.len` gives the "length" of an object of `simplex_category`, as a natural.
3. `simplex_category.hom.mk` makes a morphism out of a monotone map between `fin`'s.
4. `simplex_category.hom.to_preorder_hom` gives the underlying monotone map associated to a
term of `simplex_category.hom`.
-/
universe variables u
open category_theory
/-- The simplex category:
* objects are natural numbers `n : ℕ`
* morphisms from `n` to `m` are monotone functions `fin (n+1) → fin (m+1)`
-/
@[derive inhabited, irreducible]
def simplex_category := ulift.{u} ℕ
namespace simplex_category
section
local attribute [semireducible] simplex_category
-- TODO: Make `mk` irreducible.
/-- Interpet a natural number as an object of the simplex category. -/
def mk (n : ℕ) : simplex_category := ulift.up n
localized "notation `[`n`]` := simplex_category.mk n" in simplicial
-- TODO: Make `len` irreducible.
/-- The length of an object of `simplex_category`. -/
def len (n : simplex_category) : ℕ := n.down
@[ext] lemma ext (a b : simplex_category) : a.len = b.len → a = b := ulift.ext a b
@[simp] lemma len_mk (n : ℕ) : [n].len = n := rfl
@[simp] lemma mk_len (n : simplex_category) : [n.len] = n := by {cases n, refl}
/-- Morphisms in the simplex_category. -/
@[irreducible, nolint has_inhabited_instance]
protected def hom (a b : simplex_category.{u}) : Type u :=
ulift (fin (a.len + 1) →ₘ fin (b.len + 1))
namespace hom
local attribute [semireducible] simplex_category.hom
/-- Make a moprhism in `simplex_category` from a monotone map of fin's. -/
def mk {a b : simplex_category.{u}} (f : fin (a.len + 1) →ₘ fin (b.len + 1)) :
simplex_category.hom a b :=
ulift.up f
/-- Recover the monotone map from a morphism in the simplex category. -/
def to_preorder_hom {a b : simplex_category.{u}} (f : simplex_category.hom a b) :
fin (a.len + 1) →ₘ fin (b.len + 1) :=
ulift.down f
@[ext] lemma ext {a b : simplex_category.{u}} (f g : simplex_category.hom a b) :
f.to_preorder_hom = g.to_preorder_hom → f = g := ulift.ext _ _
@[simp] lemma mk_to_preorder_hom {a b : simplex_category.{u}}
(f : simplex_category.hom a b) : mk (f.to_preorder_hom) = f :=
by {cases f, refl}
@[simp] lemma to_preorder_hom_mk {a b : simplex_category.{u}}
(f : fin (a.len + 1) →ₘ fin (b.len + 1)) : (mk f).to_preorder_hom = f :=
by simp [to_preorder_hom, mk]
lemma mk_to_preorder_hom_apply {a b : simplex_category.{u}}
(f : fin (a.len + 1) →ₘ fin (b.len + 1)) (i : fin (a.len + 1)) :
(mk f).to_preorder_hom i = f i := rfl
/-- Identity morphisms of `simplex_category`. -/
@[simp]
def id (a : simplex_category.{u}) :
simplex_category.hom a a :=
mk preorder_hom.id
/-- Composition of morphisms of `simplex_category`. -/
@[simp]
def comp {a b c : simplex_category.{u}} (f : simplex_category.hom b c)
(g : simplex_category.hom a b) : simplex_category.hom a c :=
mk $ f.to_preorder_hom.comp g.to_preorder_hom
end hom
@[simps]
instance small_category : small_category.{u} simplex_category :=
{ hom := λ n m, simplex_category.hom n m,
id := λ m, simplex_category.hom.id _,
comp := λ _ _ _ f g, simplex_category.hom.comp g f, }
/--
Make a morphism `[n] ⟶ [m]` from a monotone map between fin's.
This is useful for constructing morphisms beetween `[n]` directly
without identifying `n` with `[n].len`.
-/
@[simp]
def mk_hom {n m : ℕ} (f : (fin (n+1)) →ₘ (fin (m+1))) : [n] ⟶ [m] :=
simplex_category.hom.mk f
end
open_locale simplicial
section generators
/-!
## Generating maps for the simplex category
TODO: prove that the simplex category is equivalent to
one given by the following generators and relations.
-/
/-- The `i`-th face map from `[n]` to `[n+1]` -/
def δ {n} (i : fin (n+2)) : [n] ⟶ [n+1] :=
mk_hom (fin.succ_above i).to_preorder_hom
/-- The `i`-th degeneracy map from `[n+1]` to `[n]` -/
def σ {n} (i : fin (n+1)) : [n+1] ⟶ [n] := mk_hom
{ to_fun := fin.pred_above i,
monotone' := fin.pred_above_right_monotone i }
/-- The generic case of the first simplicial identity -/
lemma δ_comp_δ {n} {i j : fin (n+2)} (H : i ≤ j) :
δ i ≫ δ j.succ = δ j ≫ δ i.cast_succ :=
begin
ext k,
dsimp [δ, fin.succ_above],
simp only [order_embedding.to_preorder_hom_coe,
order_embedding.coe_of_strict_mono,
function.comp_app,
simplex_category.hom.to_preorder_hom_mk,
preorder_hom.comp_to_fun],
rcases i with ⟨i, _⟩,
rcases j with ⟨j, _⟩,
rcases k with ⟨k, _⟩,
split_ifs; { simp at *; linarith },
end
/-- The special case of the first simplicial identity -/
lemma δ_comp_δ_self {n} {i : fin (n+2)} : δ i ≫ δ i.cast_succ = δ i ≫ δ i.succ :=
begin
ext j,
dsimp [δ, fin.succ_above],
simp only [order_embedding.to_preorder_hom_coe,
order_embedding.coe_of_strict_mono,
function.comp_app,
simplex_category.hom.to_preorder_hom_mk,
preorder_hom.comp_to_fun],
rcases i with ⟨i, _⟩,
rcases j with ⟨j, _⟩,
split_ifs; { simp at *; linarith },
end
/-- The second simplicial identity -/
lemma δ_comp_σ_of_le {n} {i : fin (n+2)} {j : fin (n+1)} (H : i ≤ j.cast_succ) :
δ i.cast_succ ≫ σ j.succ = σ j ≫ δ i :=
begin
ext k,
suffices : ite (j.succ.cast_succ < ite (k < i) k.cast_succ k.succ)
(ite (k < i) (k:ℕ) (k + 1) - 1) (ite (k < i) k (k + 1)) =
ite ((if h : (j:ℕ) < k
then k.pred (by { rintro rfl, exact nat.not_lt_zero _ h })
else k.cast_lt (by { cases j, cases k, simp only [len_mk], linarith })).cast_succ < i)
(ite (j.cast_succ < k) (k - 1) k) (ite (j.cast_succ < k) (k - 1) k + 1),
{ dsimp [δ, σ, fin.succ_above, fin.pred_above],
simpa [fin.pred_above] with push_cast },
rcases i with ⟨i, _⟩,
rcases j with ⟨j, _⟩,
rcases k with ⟨k, _⟩,
simp only [subtype.mk_le_mk, fin.cast_succ_mk] at H,
dsimp, simp only [if_congr, subtype.mk_lt_mk, dif_ctx_congr],
split_ifs,
-- Most of the goals can now be handled by `linarith`,
-- but we have to deal with two of them by hand.
swap 8,
{ exact (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) ‹_›)).symm, },
swap 7,
{ have : k ≤ i := nat.le_of_pred_lt ‹_›, linarith, },
-- Hope for the best from `linarith`:
all_goals { try { refl <|> simp at * }; linarith, },
end
/-- The first part of the third simplicial identity -/
lemma δ_comp_σ_self {n} {i : fin (n+1)} :
δ i.cast_succ ≫ σ i = 𝟙 [n] :=
begin
ext j,
suffices : ite (fin.cast_succ i < ite (j < i) (fin.cast_succ j) j.succ)
(ite (j < i) (j:ℕ) (j + 1) - 1) (ite (j < i) j (j + 1)) = j,
{ dsimp [δ, σ, fin.succ_above, fin.pred_above], simpa [fin.pred_above] with push_cast },
rcases i with ⟨i, _⟩,
rcases j with ⟨j, _⟩,
dsimp, simp only [if_congr, subtype.mk_lt_mk],
split_ifs; { simp at *; linarith, },
end
/-- The second part of the third simplicial identity -/
lemma δ_comp_σ_succ {n} {i : fin (n+1)} :
δ i.succ ≫ σ i = 𝟙 [n] :=
begin
ext j,
rcases i with ⟨i, _⟩,
rcases j with ⟨j, _⟩,
dsimp [δ, σ, fin.succ_above, fin.pred_above],
simp [fin.pred_above] with push_cast,
split_ifs; { simp at *; linarith, },
end
/-- The fourth simplicial identity -/
lemma δ_comp_σ_of_gt {n} {i : fin (n+2)} {j : fin (n+1)} (H : j.cast_succ < i) :
δ i.succ ≫ σ j.cast_succ = σ j ≫ δ i :=
begin
ext k,
dsimp [δ, σ, fin.succ_above, fin.pred_above],
rcases i with ⟨i, _⟩,
rcases j with ⟨j, _⟩,
rcases k with ⟨k, _⟩,
simp only [subtype.mk_lt_mk, fin.cast_succ_mk] at H,
suffices : ite (_ < ite (k < i + 1) _ _) _ _ =
ite _ (ite (j < k) (k - 1) k) (ite (j < k) (k - 1) k + 1),
{ simpa [apply_dite fin.cast_succ, fin.pred_above] with push_cast, },
split_ifs,
-- Most of the goals can now be handled by `linarith`,
-- but we have to deal with three of them by hand.
swap 2,
{ simp only [subtype.mk_lt_mk] at h_1,
simp only [not_lt] at h_2,
simp only [self_eq_add_right, one_ne_zero],
exact lt_irrefl (k - 1) (lt_of_lt_of_le
(nat.pred_lt (ne_of_lt (lt_of_le_of_lt (zero_le _) h_1)).symm)
(le_trans (nat.le_of_lt_succ h) h_2)) },
swap 4,
{ simp only [subtype.mk_lt_mk] at h_1,
simp only [not_lt] at h,
simp only [nat.add_succ_sub_one, add_zero],
exfalso,
exact lt_irrefl _ (lt_of_le_of_lt (nat.le_pred_of_lt (nat.lt_of_succ_le h)) h_3), },
swap 4,
{ simp only [subtype.mk_lt_mk] at h_1,
simp only [not_lt] at h_3,
simp only [nat.add_succ_sub_one, add_zero],
exact (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) h_2)).symm, },
-- Hope for the best from `linarith`:
all_goals { simp at h_1 h_2 ⊢; linarith, },
end
local attribute [simp] fin.pred_mk
/-- The fifth simplicial identity -/
lemma σ_comp_σ {n} {i j : fin (n+1)} (H : i ≤ j) :
σ i.cast_succ ≫ σ j = σ j.succ ≫ σ i :=
begin
ext k,
dsimp [σ, fin.pred_above],
rcases i with ⟨i, _⟩,
rcases j with ⟨j, _⟩,
rcases k with ⟨k, _⟩,
simp only [subtype.mk_le_mk] at H,
-- At this point `simp with push_cast` makes good progress, but neither `simp?` nor `squeeze_simp`
-- return usable sets of lemmas.
-- To avoid using a non-terminal simp, we make a `suffices` statement indicating the shape
-- of the goal we're looking for, and then use `simpa with push_cast`.
-- I'm not sure this is actually much more robust that a non-terminal simp.
suffices : ite (_ < dite (i < k) _ _) _ _ =
ite (_ < dite (j + 1 < k) _ _) _ _,
{ simpa [fin.pred_above] with push_cast, },
split_ifs,
-- `split_ifs` created 12 goals.
-- Most of them are dealt with `by simp at *; linarith`,
-- but we pull out two harder ones to do by hand.
swap 3,
{ simp only [not_lt] at h_2,
exact false.elim
(lt_irrefl (k - 1)
(lt_of_lt_of_le (nat.pred_lt (id (ne_of_lt (lt_of_le_of_lt (zero_le i) h)).symm))
(le_trans h_2 (nat.succ_le_of_lt h_1)))) },
swap 3,
{ simp only [subtype.mk_lt_mk, not_lt] at h_1,
exact false.elim
(lt_irrefl j (lt_of_lt_of_le (nat.pred_lt_pred (nat.succ_ne_zero j) h_2) h_1)) },
-- Deal with the rest automatically.
all_goals { simp at *; linarith, },
end
end generators
section skeleton
/-- The functor that exhibits `simplex_category` as skeleton
of `NonemptyFinLinOrd` -/
def skeletal_functor : simplex_category ⥤ NonemptyFinLinOrd :=
{ obj := λ a, NonemptyFinLinOrd.of $ ulift (fin (a.len + 1)),
map := λ a b f,
⟨λ i, ulift.up (f.to_preorder_hom i.down), λ i j h, f.to_preorder_hom.monotone h⟩ }
lemma skeletal : skeletal simplex_category :=
λ X Y ⟨I⟩,
begin
suffices : fintype.card (fin (X.len+1)) = fintype.card (fin (Y.len+1)),
{ ext, simpa },
{ apply fintype.card_congr,
refine equiv.ulift.symm.trans (((skeletal_functor ⋙ forget _).map_iso I).to_equiv.trans _),
apply equiv.ulift }
end
namespace skeletal_functor
instance : full skeletal_functor :=
{ preimage := λ a b f, simplex_category.hom.mk ⟨λ i, (f (ulift.up i)).down, λ i j h, f.monotone h⟩,
witness' := by { intros m n f, dsimp at *, ext1 ⟨i⟩, ext1, refl } }
instance : faithful skeletal_functor :=
{ map_injective' := λ m n f g h,
begin
ext1, ext1 i, apply ulift.up.inj,
change (skeletal_functor.map f) ⟨i⟩ = (skeletal_functor.map g) ⟨i⟩,
rw h,
end }
instance : ess_surj skeletal_functor :=
{ mem_ess_image := λ X, ⟨mk (fintype.card X - 1 : ℕ), ⟨begin
have aux : fintype.card X = fintype.card X - 1 + 1,
{ exact (nat.succ_pred_eq_of_pos $ fintype.card_pos_iff.mpr ⟨⊥⟩).symm, },
let f := mono_equiv_of_fin X aux,
have hf := (finset.univ.order_emb_of_fin aux).strict_mono,
refine
{ hom := ⟨λ i, f i.down, _⟩,
inv := ⟨λ i, ⟨f.symm i⟩, _⟩,
hom_inv_id' := _,
inv_hom_id' := _ },
{ rintro ⟨i⟩ ⟨j⟩ h, show f i ≤ f j, exact hf.monotone h, },
{ intros i j h, show f.symm i ≤ f.symm j, rw ← hf.le_iff_le,
show f (f.symm i) ≤ f (f.symm j), simpa only [order_iso.apply_symm_apply], },
{ ext1 ⟨i⟩, ext1, exact f.symm_apply_apply i },
{ ext1 i, exact f.apply_symm_apply i },
end⟩⟩,}
noncomputable instance is_equivalence : is_equivalence skeletal_functor :=
equivalence.equivalence_of_fully_faithfully_ess_surj skeletal_functor
end skeletal_functor
/-- The equivalence that exhibits `simplex_category` as skeleton
of `NonemptyFinLinOrd` -/
noncomputable def skeletal_equivalence : simplex_category ≌ NonemptyFinLinOrd :=
functor.as_equivalence skeletal_functor
end skeleton
/--
`simplex_category` is a skeleton of `NonemptyFinLinOrd`.
-/
noncomputable
def is_skeleton_of : is_skeleton_of NonemptyFinLinOrd simplex_category skeletal_functor :=
{ skel := skeletal,
eqv := skeletal_functor.is_equivalence }
/-- The truncated simplex category. -/
@[derive small_category]
def truncated (n : ℕ) := {a : simplex_category // a.len ≤ n}
namespace truncated
instance {n} : inhabited (truncated n) := ⟨⟨[0],by simp⟩⟩
/--
The fully faithful inclusion of the truncated simplex category into the usual
simplex category.
-/
@[derive [full, faithful]]
def inclusion {n : ℕ} : simplex_category.truncated n ⥤ simplex_category :=
full_subcategory_inclusion _
end truncated
end simplex_category
|
f5997ce2afa10cd9d76e65444eeca55554e501c2 | e0b0b1648286e442507eb62344760d5cd8d13f2d | /src/Init/Core.lean | 9c7b2cdcf3e092def476595174e821c9078383c6 | [
"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 | 34,384 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
notation, basic datatypes and type classes
-/
prelude
import Init.Prelude
import Init.SizeOf
universes u v w
def inline {α : Sort u} (a : α) : α := a
@[inline] def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ :=
fun b a => f a b
/--
Thunks are "lazy" values that are evaluated when first accessed using `Thunk.get/map/bind`.
The value is then stored and not recomputed for all further accesses. -/
-- NOTE: the runtime has special support for the `Thunk` type to implement this behavior
structure Thunk (α : Type u) : Type u where
-- TODO: make private
fn : Unit → α
attribute [extern "lean_mk_thunk"] Thunk.mk
/-- Store a value in a thunk. Note that the value has already been computed, so there is no laziness. -/
@[extern "lean_thunk_pure"] protected def Thunk.pure (a : α) : Thunk α :=
⟨fun _ => a⟩
-- NOTE: we use `Thunk.get` instead of `Thunk.fn` as the accessor primitive as the latter has an additional `Unit` argument
@[extern "lean_thunk_get_own"] protected def Thunk.get (x : @& Thunk α) : α :=
x.fn ()
@[inline] protected def Thunk.map (f : α → β) (x : Thunk α) : Thunk β :=
⟨fun _ => f x.get⟩
@[inline] protected def Thunk.bind (x : Thunk α) (f : α → Thunk β) : Thunk β :=
⟨fun _ => (f x.get).get⟩
abbrev Eq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : α → Sort u1} {b : α} (h : a = b) (m : motive a) : motive b :=
Eq.ndrec m h
structure Iff (a b : Prop) : Prop where
intro :: (mp : a → b) (mpr : b → a)
infix:20 " <-> " => Iff
infix:20 " ↔ " => Iff
/- Eq basic support -/
inductive Sum (α : Type u) (β : Type v) where
| inl (val : α) : Sum α β
| inr (val : β) : Sum α β
inductive PSum (α : Sort u) (β : Sort v) where
| inl (val : α) : PSum α β
| inr (val : β) : PSum α β
structure Sigma {α : Type u} (β : α → Type v) where
fst : α
snd : β fst
attribute [unbox] Sigma
structure PSigma {α : Sort u} (β : α → Sort v) where
fst : α
snd : β fst
inductive Exists {α : Sort u} (p : α → Prop) : Prop where
| intro (w : α) (h : p w) : Exists p
/- Auxiliary type used to compile `for x in xs` notation. -/
inductive ForInStep (α : Type u) where
| done : α → ForInStep α
| yield : α → ForInStep α
class ForIn (m : Type u₁ → Type u₂) (ρ : Type u) (α : outParam (Type v)) where
forIn {β} [Monad m] (x : ρ) (b : β) (f : α → β → m (ForInStep β)) : m β
export ForIn (forIn)
/- Auxiliary type used to compile `do` notation. -/
inductive DoResultPRBC (α β σ : Type u) where
| «pure» : α → σ → DoResultPRBC α β σ
| «return» : β → σ → DoResultPRBC α β σ
| «break» : σ → DoResultPRBC α β σ
| «continue» : σ → DoResultPRBC α β σ
/- Auxiliary type used to compile `do` notation. -/
inductive DoResultPR (α β σ : Type u) where
| «pure» : α → σ → DoResultPR α β σ
| «return» : β → σ → DoResultPR α β σ
/- Auxiliary type used to compile `do` notation. -/
inductive DoResultBC (σ : Type u) where
| «break» : σ → DoResultBC σ
| «continue» : σ → DoResultBC σ
/- Auxiliary type used to compile `do` notation. -/
inductive DoResultSBC (α σ : Type u) where
| «pureReturn» : α → σ → DoResultSBC α σ
| «break» : σ → DoResultSBC α σ
| «continue» : σ → DoResultSBC α σ
class HasEquiv (α : Sort u) where
Equiv : α → α → Sort v
infix:50 " ≈ " => HasEquiv.Equiv
class EmptyCollection (α : Type u) where
emptyCollection : α
notation "{" "}" => EmptyCollection.emptyCollection
notation "∅" => EmptyCollection.emptyCollection
/- Remark: tasks have an efficient implementation in the runtime. -/
structure Task (α : Type u) : Type u where
pure :: (get : α)
attribute [extern "lean_task_pure"] Task.pure
attribute [extern "lean_task_get_own"] Task.get
namespace Task
/-- Task priority. Tasks with higher priority will always be scheduled before ones with lower priority. -/
abbrev Priority := Nat
def Priority.default : Priority := 0
-- see `LEAN_MAX_PRIO`
def Priority.max : Priority := 8
/--
Any priority higher than `Task.Priority.max` will result in the task being scheduled immediately on a dedicated thread.
This is particularly useful for long-running and/or I/O-bound tasks since Lean will by default allocate no more
non-dedicated workers than the number of cores to reduce context switches. -/
def Priority.dedicated : Priority := 9
@[noinline, extern "lean_task_spawn"]
protected def spawn {α : Type u} (fn : Unit → α) (prio := Priority.default) : Task α :=
⟨fn ()⟩
@[noinline, extern "lean_task_map"]
protected def map {α : Type u} {β : Type v} (f : α → β) (x : Task α) (prio := Priority.default) : Task β :=
⟨f x.get⟩
@[noinline, extern "lean_task_bind"]
protected def bind {α : Type u} {β : Type v} (x : Task α) (f : α → Task β) (prio := Priority.default) : Task β :=
⟨(f x.get).get⟩
end Task
/- Some type that is not a scalar value in our runtime. -/
structure NonScalar where
val : Nat
/- Some type that is not a scalar value in our runtime and is universe polymorphic. -/
inductive PNonScalar : Type u where
| mk (v : Nat) : PNonScalar
theorem natAddZero (n : Nat) : n + 0 = n := rfl
theorem optParamEq (α : Sort u) (default : α) : optParam α default = α := rfl
/- Boolean operators -/
@[extern c inline "#1 || #2"] def strictOr (b₁ b₂ : Bool) := b₁ || b₂
@[extern c inline "#1 && #2"] def strictAnd (b₁ b₂ : Bool) := b₁ && b₂
@[inline] def bne {α : Type u} [BEq α] (a b : α) : Bool :=
!(a == b)
infix:50 " != " => bne
/- Logical connectives an equality -/
def implies (a b : Prop) := a → b
theorem implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r :=
fun hp => h₂ (h₁ hp)
def trivial : True := ⟨⟩
theorem mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a :=
fun ha => h₂ (h₁ ha)
theorem notFalse : ¬False := id
-- proof irrelevance is built in
theorem proofIrrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl
theorem id.def {α : Sort u} (a : α) : id a = a := rfl
@[macroInline] def Eq.mp {α β : Sort u} (h : α = β) (a : α) : β :=
h ▸ a
@[macroInline] def Eq.mpr {α β : Sort u} (h : α = β) (b : β) : α :=
h ▸ b
theorem Eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) (h₂ : p a) : p b :=
h₁ ▸ h₂
theorem castEq {α : Sort u} (h : α = α) (a : α) : cast h a = a :=
rfl
@[reducible] def Ne {α : Sort u} (a b : α) :=
¬(a = b)
infix:50 " ≠ " => Ne
section Ne
variable {α : Sort u}
variable {a b : α} {p : Prop}
theorem Ne.intro (h : a = b → False) : a ≠ b := h
theorem Ne.elim (h : a ≠ b) : a = b → False := h
theorem Ne.irrefl (h : a ≠ a) : False := h rfl
theorem Ne.symm (h : a ≠ b) : b ≠ a :=
fun h₁ => h (h₁.symm)
theorem falseOfNe : a ≠ a → False := Ne.irrefl
theorem neFalseOfSelf : p → p ≠ False :=
fun (hp : p) (h : p = False) => h ▸ hp
theorem neTrueOfNot : ¬p → p ≠ True :=
fun (hnp : ¬p) (h : p = True) =>
have ¬True from h ▸ hnp
this trivial
theorem trueNeFalse : ¬True = False :=
neFalseOfSelf trivial
end Ne
section
variable {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ}
theorem HEq.ndrec.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} (m : motive a) {β : Sort u2} {b : β} (h : a ≅ b) : motive b :=
@HEq.rec α a (fun b _ => motive b) m β b h
theorem HEq.ndrecOn.{u1, u2} {α : Sort u2} {a : α} {motive : {β : Sort u2} → β → Sort u1} {β : Sort u2} {b : β} (h : a ≅ b) (m : motive a) : motive b :=
@HEq.rec α a (fun b _ => motive b) m β b h
theorem HEq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a ≅ b) (h₂ : p a) : p b :=
eqOfHEq h₁ ▸ h₂
theorem HEq.subst {p : (T : Sort u) → T → Prop} (h₁ : a ≅ b) (h₂ : p α a) : p β b :=
HEq.ndrecOn h₁ h₂
theorem HEq.symm (h : a ≅ b) : b ≅ a :=
HEq.ndrecOn (motive := fun x => x ≅ a) h (HEq.refl a)
theorem heqOfEq (h : a = a') : a ≅ a' :=
Eq.subst h (HEq.refl a)
theorem HEq.trans (h₁ : a ≅ b) (h₂ : b ≅ c) : a ≅ c :=
HEq.subst h₂ h₁
theorem heqOfHEqOfEq (h₁ : a ≅ b) (h₂ : b = b') : a ≅ b' :=
HEq.trans h₁ (heqOfEq h₂)
theorem heqOfEqOfHEq (h₁ : a = a') (h₂ : a' ≅ b) : a ≅ b :=
HEq.trans (heqOfEq h₁) h₂
def typeEqOfHEq (h : a ≅ b) : α = β :=
HEq.ndrecOn (motive := @fun (x : Sort u) _ => α = x) h (Eq.refl α)
end
theorem eqRecHEq {α : Sort u} {φ : α → Sort v} {a a' : α} : (h : a = a') → (p : φ a) → (Eq.recOn (motive := fun x _ => φ x) h p) ≅ p
| rfl, p => HEq.refl p
theorem heqOfEqRecEq {α β : Sort u} {a : α} {b : β} (h₁ : α = β) (h₂ : Eq.rec (motive := fun α _ => α) a h₁ = b) : a ≅ b := by
subst h₁
apply heqOfEq
exact h₂
done
theorem castHEq {α β : Sort u} : (h : α = β) → (a : α) → cast h a ≅ a
| rfl, a => HEq.refl a
variable {a b c d : Prop}
theorem iffIffImpliesAndImplies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) :=
Iff.intro (fun h => And.intro h.mp h.mpr) (fun h => Iff.intro h.left h.right)
theorem Iff.refl (a : Prop) : a ↔ a :=
Iff.intro (fun h => h) (fun h => h)
theorem Iff.rfl {a : Prop} : a ↔ a :=
Iff.refl a
theorem Iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c :=
Iff.intro
(fun ha => Iff.mp h₂ (Iff.mp h₁ ha))
(fun hc => Iff.mpr h₁ (Iff.mpr h₂ hc))
theorem Iff.symm (h : a ↔ b) : b ↔ a :=
Iff.intro (Iff.mpr h) (Iff.mp h)
theorem Iff.comm : (a ↔ b) ↔ (b ↔ a) :=
Iff.intro Iff.symm Iff.symm
/- Exists -/
theorem Exists.elim {α : Sort u} {p : α → Prop} {b : Prop}
(h₁ : Exists (fun x => p x)) (h₂ : ∀ (a : α), p a → b) : b :=
h₂ h₁.1 h₁.2
/- Decidable -/
theorem decideTrueEqTrue (h : Decidable True) : @decide True h = true :=
match h with
| isTrue h => rfl
| isFalse h => False.elim <| h ⟨⟩
theorem decideFalseEqFalse (h : Decidable False) : @decide False h = false :=
match h with
| isFalse h => rfl
| isTrue h => False.elim h
/-- Similar to `decide`, but uses an explicit instance -/
@[inline] def toBoolUsing {p : Prop} (d : Decidable p) : Bool :=
decide p (h := d)
theorem toBoolUsingEqTrue {p : Prop} (d : Decidable p) (h : p) : toBoolUsing d = true :=
decideEqTrue (s := d) h
theorem ofBoolUsingEqTrue {p : Prop} {d : Decidable p} (h : toBoolUsing d = true) : p :=
ofDecideEqTrue (s := d) h
theorem ofBoolUsingEqFalse {p : Prop} {d : Decidable p} (h : toBoolUsing d = false) : ¬ p :=
ofDecideEqFalse (s := d) h
instance : Decidable True :=
isTrue trivial
instance : Decidable False :=
isFalse notFalse
namespace Decidable
variable {p q : Prop}
@[macroInline] def byCases {q : Sort u} [dec : Decidable p] (h1 : p → q) (h2 : ¬p → q) : q :=
match dec with
| isTrue h => h1 h
| isFalse h => h2 h
theorem em (p : Prop) [Decidable p] : p ∨ ¬p :=
byCases Or.inl Or.inr
theorem byContradiction [dec : Decidable p] (h : ¬p → False) : p :=
byCases id (fun np => False.elim (h np))
theorem ofNotNot [Decidable p] : ¬ ¬ p → p :=
fun hnn => byContradiction (fun hn => absurd hn hnn)
theorem notAndIffOrNot (p q : Prop) [d₁ : Decidable p] [d₂ : Decidable q] : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q :=
Iff.intro
(fun h => match d₁, d₂ with
| isTrue h₁, isTrue h₂ => absurd (And.intro h₁ h₂) h
| _, isFalse h₂ => Or.inr h₂
| isFalse h₁, _ => Or.inl h₁)
(fun (h) ⟨hp, hq⟩ => match h with
| Or.inl h => h hp
| Or.inr h => h hq)
end Decidable
section
variable {p q : Prop}
@[inline] def decidableOfDecidableOfIff (hp : Decidable p) (h : p ↔ q) : Decidable q :=
if hp : p then
isTrue (Iff.mp h hp)
else
isFalse fun hq => absurd (Iff.mpr h hq) hp
@[inline] def decidableOfDecidableOfEq (hp : Decidable p) (h : p = q) : Decidable q :=
h ▸ hp
end
@[macroInline] instance {p q} [Decidable p] [Decidable q] : Decidable (p → q) :=
if hp : p then
if hq : q then isTrue (fun h => hq)
else isFalse (fun h => absurd (h hp) hq)
else isTrue (fun h => absurd h hp)
instance {p q} [Decidable p] [Decidable q] : Decidable (p ↔ q) :=
if hp : p then
if hq : q then
isTrue ⟨fun _ => hq, fun _ => hp⟩
else
isFalse fun h => hq (h.1 hp)
else
if hq : q then
isFalse fun h => hp (h.2 hq)
else
isTrue ⟨fun h => absurd h hp, fun h => absurd h hq⟩
/- if-then-else expression theorems -/
theorem ifPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t :=
match h with
| isTrue hc => rfl
| isFalse hnc => absurd hc hnc
theorem ifNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e :=
match h with
| isTrue hc => absurd hc hnc
| isFalse hnc => rfl
theorem difPos {c : Prop} [h : Decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = t hc :=
match h with
| isTrue hc => rfl
| isFalse hnc => absurd hc hnc
theorem difNeg {c : Prop} [h : Decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : (dite c t e) = e hnc :=
match h with
| isTrue hc => absurd hc hnc
| isFalse hnc => rfl
-- Remark: dite and ite are "defally equal" when we ignore the proofs.
theorem difEqIf (c : Prop) [h : Decidable c] {α : Sort u} (t : α) (e : α) : dite c (fun h => t) (fun h => e) = ite c t e :=
match h with
| isTrue hc => rfl
| isFalse hnc => rfl
instance {c t e : Prop} [dC : Decidable c] [dT : Decidable t] [dE : Decidable e] : Decidable (if c then t else e) :=
match dC with
| isTrue hc => dT
| isFalse hc => dE
instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [dC : Decidable c] [dT : ∀ h, Decidable (t h)] [dE : ∀ h, Decidable (e h)] : Decidable (if h : c then t h else e h) :=
match dC with
| isTrue hc => dT hc
| isFalse hc => dE hc
/- Inhabited -/
instance : Inhabited Prop where
default := True
deriving instance Inhabited for NonScalar, PNonScalar, True, ForInStep
class inductive Nonempty (α : Sort u) : Prop where
| intro (val : α) : Nonempty α
protected def Nonempty.elim {α : Sort u} {p : Prop} (h₁ : Nonempty α) (h₂ : α → p) : p :=
h₂ h₁.1
instance {α : Sort u} [Inhabited α] : Nonempty α where
val := arbitrary
theorem nonemptyOfExists {α : Sort u} {p : α → Prop} : Exists (fun x => p x) → Nonempty α
| ⟨w, h⟩ => ⟨w⟩
/- Subsingleton -/
class Subsingleton (α : Sort u) : Prop where
intro :: allEq : (a b : α) → a = b
protected def Subsingleton.elim {α : Sort u} [h : Subsingleton α] : (a b : α) → a = b :=
h.allEq
protected def Subsingleton.helim {α β : Sort u} [h₁ : Subsingleton α] (h₂ : α = β) (a : α) (b : β) : a ≅ b := by
subst h₂
apply heqOfEq
apply Subsingleton.elim
instance (p : Prop) : Subsingleton p :=
⟨fun a b => proofIrrel a b⟩
instance (p : Prop) : Subsingleton (Decidable p) :=
Subsingleton.intro fun
| isTrue t₁ => fun
| isTrue t₂ => rfl
| isFalse f₂ => absurd t₁ f₂
| isFalse f₁ => fun
| isTrue t₂ => absurd t₂ f₁
| isFalse f₂ => rfl
theorem recSubsingleton
{p : Prop} [h : Decidable p]
{h₁ : p → Sort u}
{h₂ : ¬p → Sort u}
[h₃ : ∀ (h : p), Subsingleton (h₁ h)]
[h₄ : ∀ (h : ¬p), Subsingleton (h₂ h)]
: Subsingleton (Decidable.casesOn (motive := fun _ => Sort u) h h₂ h₁) :=
match h with
| isTrue h => h₃ h
| isFalse h => h₄ h
structure Equivalence {α : Sort u} (r : α → α → Prop) : Prop where
refl : ∀ x, r x x
symm : ∀ {x y}, r x y → r y x
trans : ∀ {x y z}, r x y → r y z → r x z
def emptyRelation {α : Sort u} (a₁ a₂ : α) : Prop :=
False
def Subrelation {α : Sort u} (q r : α → α → Prop) :=
∀ {x y}, q x y → r x y
def InvImage {α : Sort u} {β : Sort v} (r : β → β → Prop) (f : α → β) : α → α → Prop :=
fun a₁ a₂ => r (f a₁) (f a₂)
inductive TC {α : Sort u} (r : α → α → Prop) : α → α → Prop where
| base : ∀ a b, r a b → TC r a b
| trans : ∀ a b c, TC r a b → TC r b c → TC r a c
/- Subtype -/
namespace Subtype
def existsOfSubtype {α : Type u} {p : α → Prop} : { x // p x } → Exists (fun x => p x)
| ⟨a, h⟩ => ⟨a, h⟩
variable {α : Type u} {p : α → Prop}
protected theorem eq : ∀ {a1 a2 : {x // p x}}, val a1 = val a2 → a1 = a2
| ⟨x, h1⟩, ⟨_, _⟩, rfl => rfl
theorem eta (a : {x // p x}) (h : p (val a)) : mk (val a) h = a := by
cases a
exact rfl
instance {α : Type u} {p : α → Prop} {a : α} (h : p a) : Inhabited {x // p x} where
default := ⟨a, h⟩
instance {α : Type u} {p : α → Prop} [DecidableEq α] : DecidableEq {x : α // p x} :=
fun ⟨a, h₁⟩ ⟨b, h₂⟩ =>
if h : a = b then isTrue (by subst h; exact rfl)
else isFalse (fun h' => Subtype.noConfusion h' (fun h' => absurd h' h))
end Subtype
/- Sum -/
section
variable {α : Type u} {β : Type v}
instance Sum.inhabitedLeft [h : Inhabited α] : Inhabited (Sum α β) where
default := Sum.inl arbitrary
instance Sum.inhabitedRight [h : Inhabited β] : Inhabited (Sum α β) where
default := Sum.inr arbitrary
instance {α : Type u} {β : Type v} [DecidableEq α] [DecidableEq β] : DecidableEq (Sum α β) := fun a b =>
match a, b with
| Sum.inl a, Sum.inl b =>
if h : a = b then isTrue (h ▸ rfl)
else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h
| Sum.inr a, Sum.inr b =>
if h : a = b then isTrue (h ▸ rfl)
else isFalse fun h' => Sum.noConfusion h' fun h' => absurd h' h
| Sum.inr a, Sum.inl b => isFalse fun h => Sum.noConfusion h
| Sum.inl a, Sum.inr b => isFalse fun h => Sum.noConfusion h
end
/- Product -/
instance [Inhabited α] [Inhabited β] : Inhabited (α × β) where
default := (arbitrary, arbitrary)
instance [DecidableEq α] [DecidableEq β] : DecidableEq (α × β) :=
fun (a, b) (a', b') =>
match decEq a a' with
| isTrue e₁ =>
match decEq b b' with
| isTrue e₂ => isTrue (e₁ ▸ e₂ ▸ rfl)
| isFalse n₂ => isFalse fun h => Prod.noConfusion h fun e₁' e₂' => absurd e₂' n₂
| isFalse n₁ => isFalse fun h => Prod.noConfusion h fun e₁' e₂' => absurd e₁' n₁
instance [BEq α] [BEq β] : BEq (α × β) where
beq := fun (a₁, b₁) (a₂, b₂) => a₁ == a₂ && b₁ == b₂
instance [LT α] [LT β] : LT (α × β) where
lt s t := s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)
instance prodHasDecidableLt
[LT α] [LT β] [DecidableEq α] [DecidableEq β]
[(a b : α) → Decidable (a < b)] [(a b : β) → Decidable (a < b)]
: (s t : α × β) → Decidable (s < t) :=
fun t s => inferInstanceAs (Decidable (_ ∨ _))
theorem Prod.ltDef [LT α] [LT β] (s t : α × β) : (s < t) = (s.1 < t.1 ∨ (s.1 = t.1 ∧ s.2 < t.2)) :=
rfl
theorem Prod.ext (p : α × β) : (p.1, p.2) = p := by
cases p; rfl
def Prod.map {α₁ : Type u₁} {α₂ : Type u₂} {β₁ : Type v₁} {β₂ : Type v₂}
(f : α₁ → α₂) (g : β₁ → β₂) : α₁ × β₁ → α₂ × β₂
| (a, b) => (f a, g b)
/- Dependent products -/
theorem exOfPsig {α : Type u} {p : α → Prop} : (PSigma (fun x => p x)) → Exists (fun x => p x)
| ⟨x, hx⟩ => ⟨x, hx⟩
protected theorem PSigma.eta {α : Sort u} {β : α → Sort v} {a₁ a₂ : α} {b₁ : β a₁} {b₂ : β a₂}
(h₁ : a₁ = a₂) (h₂ : Eq.ndrec b₁ h₁ = b₂) : PSigma.mk a₁ b₁ = PSigma.mk a₂ b₂ := by
subst h₁
subst h₂
exact rfl
/- Universe polymorphic unit -/
theorem PUnit.subsingleton (a b : PUnit) : a = b := by
cases a; cases b; exact rfl
@[simp] theorem PUnit.eq_punit (a : PUnit) : a = ⟨⟩ :=
PUnit.subsingleton a ⟨⟩
instance : Subsingleton PUnit :=
Subsingleton.intro PUnit.subsingleton
instance : Inhabited PUnit where
default := ⟨⟩
instance : DecidableEq PUnit :=
fun a b => isTrue (PUnit.subsingleton a b)
/- Setoid -/
class Setoid (α : Sort u) where
r : α → α → Prop
iseqv {} : Equivalence r
instance {α : Sort u} [Setoid α] : HasEquiv α :=
⟨Setoid.r⟩
namespace Setoid
variable {α : Sort u} [Setoid α]
theorem refl (a : α) : a ≈ a :=
(Setoid.iseqv α).refl a
theorem symm {a b : α} (hab : a ≈ b) : b ≈ a :=
(Setoid.iseqv α).symm hab
theorem trans {a b c : α} (hab : a ≈ b) (hbc : b ≈ c) : a ≈ c :=
(Setoid.iseqv α).trans hab hbc
end Setoid
/- Propositional extensionality -/
axiom propext {a b : Prop} : (a ↔ b) → a = b
/- Quotients -/
-- Iff can now be used to do substitutions in a calculation
theorem iffSubst {a b : Prop} {p : Prop → Prop} (h₁ : a ↔ b) (h₂ : p a) : p b :=
Eq.subst (propext h₁) h₂
namespace Quot
axiom sound : ∀ {α : Sort u} {r : α → α → Prop} {a b : α}, r a b → Quot.mk r a = Quot.mk r b
protected theorem liftBeta {α : Sort u} {r : α → α → Prop} {β : Sort v}
(f : α → β)
(c : (a b : α) → r a b → f a = f b)
(a : α)
: lift f c (Quot.mk r a) = f a :=
rfl
protected theorem indBeta {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop}
(p : (a : α) → motive (Quot.mk r a))
(a : α)
: (ind p (Quot.mk r a) : motive (Quot.mk r a)) = p a :=
rfl
protected abbrev liftOn {α : Sort u} {β : Sort v} {r : α → α → Prop} (q : Quot r) (f : α → β) (c : (a b : α) → r a b → f a = f b) : β :=
lift f c q
protected theorem inductionOn {α : Sort u} {r : α → α → Prop} {motive : Quot r → Prop}
(q : Quot r)
(h : (a : α) → motive (Quot.mk r a))
: motive q :=
ind h q
theorem existsRep {α : Sort u} {r : α → α → Prop} (q : Quot r) : Exists (fun a => (Quot.mk r a) = q) :=
Quot.inductionOn (motive := fun q => Exists (fun a => (Quot.mk r a) = q)) q (fun a => ⟨a, rfl⟩)
section
variable {α : Sort u}
variable {r : α → α → Prop}
variable {motive : Quot r → Sort v}
@[reducible, macroInline]
protected def indep (f : (a : α) → motive (Quot.mk r a)) (a : α) : PSigma motive :=
⟨Quot.mk r a, f a⟩
protected theorem indepCoherent
(f : (a : α) → motive (Quot.mk r a))
(h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b)
: (a b : α) → r a b → Quot.indep f a = Quot.indep f b :=
fun a b e => PSigma.eta (sound e) (h a b e)
protected theorem liftIndepPr1
(f : (a : α) → motive (Quot.mk r a))
(h : ∀ (a b : α) (p : r a b), Eq.ndrec (f a) (sound p) = f b)
(q : Quot r)
: (lift (Quot.indep f) (Quot.indepCoherent f h) q).1 = q := by
induction q using Quot.ind
exact rfl
protected abbrev rec
(f : (a : α) → motive (Quot.mk r a))
(h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b)
(q : Quot r) : motive q :=
Eq.ndrecOn (Quot.liftIndepPr1 f h q) ((lift (Quot.indep f) (Quot.indepCoherent f h) q).2)
protected abbrev recOn
(q : Quot r)
(f : (a : α) → motive (Quot.mk r a))
(h : (a b : α) → (p : r a b) → Eq.ndrec (f a) (sound p) = f b)
: motive q :=
Quot.rec f h q
protected abbrev recOnSubsingleton
[h : (a : α) → Subsingleton (motive (Quot.mk r a))]
(q : Quot r)
(f : (a : α) → motive (Quot.mk r a))
: motive q := by
induction q using Quot.rec
apply f
apply Subsingleton.elim
protected abbrev hrecOn
(q : Quot r)
(f : (a : α) → motive (Quot.mk r a))
(c : (a b : α) → (p : r a b) → f a ≅ f b)
: motive q :=
Quot.recOn q f fun a b p => eqOfHEq <|
have p₁ : Eq.ndrec (f a) (sound p) ≅ f a := eqRecHEq (sound p) (f a)
HEq.trans p₁ (c a b p)
end
end Quot
def Quotient {α : Sort u} (s : Setoid α) :=
@Quot α Setoid.r
namespace Quotient
@[inline]
protected def mk {α : Sort u} [s : Setoid α] (a : α) : Quotient s :=
Quot.mk Setoid.r a
def sound {α : Sort u} [s : Setoid α] {a b : α} : a ≈ b → Quotient.mk a = Quotient.mk b :=
Quot.sound
protected abbrev lift {α : Sort u} {β : Sort v} [s : Setoid α] (f : α → β) : ((a b : α) → a ≈ b → f a = f b) → Quotient s → β :=
Quot.lift f
protected theorem ind {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop} : ((a : α) → motive (Quotient.mk a)) → (q : Quot Setoid.r) → motive q :=
Quot.ind
protected abbrev liftOn {α : Sort u} {β : Sort v} [s : Setoid α] (q : Quotient s) (f : α → β) (c : (a b : α) → a ≈ b → f a = f b) : β :=
Quot.liftOn q f c
protected theorem inductionOn {α : Sort u} [s : Setoid α] {motive : Quotient s → Prop}
(q : Quotient s)
(h : (a : α) → motive (Quotient.mk a))
: motive q :=
Quot.inductionOn q h
theorem existsRep {α : Sort u} [s : Setoid α] (q : Quotient s) : Exists (fun (a : α) => Quotient.mk a = q) :=
Quot.existsRep q
section
variable {α : Sort u}
variable [s : Setoid α]
variable {motive : Quotient s → Sort v}
@[inline]
protected def rec
(f : (a : α) → motive (Quotient.mk a))
(h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b)
(q : Quotient s)
: motive q :=
Quot.rec f h q
protected abbrev recOn
(q : Quotient s)
(f : (a : α) → motive (Quotient.mk a))
(h : (a b : α) → (p : a ≈ b) → Eq.ndrec (f a) (Quotient.sound p) = f b)
: motive q :=
Quot.recOn q f h
protected abbrev recOnSubsingleton
[h : (a : α) → Subsingleton (motive (Quotient.mk a))]
(q : Quotient s)
(f : (a : α) → motive (Quotient.mk a))
: motive q :=
Quot.recOnSubsingleton (h := h) q f
protected abbrev hrecOn
(q : Quotient s)
(f : (a : α) → motive (Quotient.mk a))
(c : (a b : α) → (p : a ≈ b) → f a ≅ f b)
: motive q :=
Quot.hrecOn q f c
end
section
universes uA uB uC
variable {α : Sort uA} {β : Sort uB} {φ : Sort uC}
variable [s₁ : Setoid α] [s₂ : Setoid β]
protected abbrev lift₂
(f : α → β → φ)
(c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂)
(q₁ : Quotient s₁) (q₂ : Quotient s₂)
: φ := by
apply Quotient.lift (fun (a₁ : α) => Quotient.lift (f a₁) (fun (a b : β) => c a₁ a a₁ b (Setoid.refl a₁)) q₂) _ q₁
intros
induction q₂ using Quotient.ind
apply c; assumption; apply Setoid.refl
protected abbrev liftOn₂
(q₁ : Quotient s₁)
(q₂ : Quotient s₂)
(f : α → β → φ)
(c : (a₁ : α) → (b₁ : β) → (a₂ : α) → (b₂ : β) → a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ = f a₂ b₂)
: φ :=
Quotient.lift₂ f c q₁ q₂
protected theorem ind₂
{motive : Quotient s₁ → Quotient s₂ → Prop}
(h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b))
(q₁ : Quotient s₁)
(q₂ : Quotient s₂)
: motive q₁ q₂ := by
induction q₁ using Quotient.ind
induction q₂ using Quotient.ind
apply h
protected theorem inductionOn₂
{motive : Quotient s₁ → Quotient s₂ → Prop}
(q₁ : Quotient s₁)
(q₂ : Quotient s₂)
(h : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b))
: motive q₁ q₂ := by
induction q₁ using Quotient.ind
induction q₂ using Quotient.ind
apply h
protected theorem inductionOn₃
[s₃ : Setoid φ]
{motive : Quotient s₁ → Quotient s₂ → Quotient s₃ → Prop}
(q₁ : Quotient s₁)
(q₂ : Quotient s₂)
(q₃ : Quotient s₃)
(h : (a : α) → (b : β) → (c : φ) → motive (Quotient.mk a) (Quotient.mk b) (Quotient.mk c))
: motive q₁ q₂ q₃ := by
induction q₁ using Quotient.ind
induction q₂ using Quotient.ind
induction q₃ using Quotient.ind
apply h
end
section Exact
variable {α : Sort u}
private def rel [s : Setoid α] (q₁ q₂ : Quotient s) : Prop :=
Quotient.liftOn₂ q₁ q₂
(fun a₁ a₂ => a₁ ≈ a₂)
(fun a₁ a₂ b₁ b₂ a₁b₁ a₂b₂ =>
propext (Iff.intro
(fun a₁a₂ => Setoid.trans (Setoid.symm a₁b₁) (Setoid.trans a₁a₂ a₂b₂))
(fun b₁b₂ => Setoid.trans a₁b₁ (Setoid.trans b₁b₂ (Setoid.symm a₂b₂)))))
private theorem rel.refl [s : Setoid α] (q : Quotient s) : rel q q :=
Quot.inductionOn (motive := fun q => rel q q) q (fun a => Setoid.refl a)
private theorem eqImpRel [s : Setoid α] {q₁ q₂ : Quotient s} : q₁ = q₂ → rel q₁ q₂ :=
fun h => Eq.ndrecOn h (rel.refl q₁)
theorem exact [s : Setoid α] {a b : α} : Quotient.mk a = Quotient.mk b → a ≈ b :=
fun h => eqImpRel h
end Exact
section
universes uA uB uC
variable {α : Sort uA} {β : Sort uB}
variable [s₁ : Setoid α] [s₂ : Setoid β]
protected abbrev recOnSubsingleton₂
{motive : Quotient s₁ → Quotient s₂ → Sort uC}
[s : (a : α) → (b : β) → Subsingleton (motive (Quotient.mk a) (Quotient.mk b))]
(q₁ : Quotient s₁)
(q₂ : Quotient s₂)
(g : (a : α) → (b : β) → motive (Quotient.mk a) (Quotient.mk b))
: motive q₁ q₂ := by
induction q₁ using Quot.recOnSubsingleton
induction q₂ using Quot.recOnSubsingleton
apply g
intro a; apply s
induction q₂ using Quot.recOnSubsingleton
intro a; apply s
inferInstance
end
end Quotient
section
variable {α : Type u}
variable (r : α → α → Prop)
instance {α : Sort u} {s : Setoid α} [d : ∀ (a b : α), Decidable (a ≈ b)] : DecidableEq (Quotient s) :=
fun (q₁ q₂ : Quotient s) =>
Quotient.recOnSubsingleton₂ (motive := fun a b => Decidable (a = b)) q₁ q₂
fun a₁ a₂ =>
match d a₁ a₂ with
| isTrue h₁ => isTrue (Quotient.sound h₁)
| isFalse h₂ => isFalse fun h => absurd (Quotient.exact h) h₂
/- Function extensionality -/
namespace Function
variable {α : Sort u} {β : α → Sort v}
def Equiv (f₁ f₂ : ∀ (x : α), β x) : Prop := ∀ x, f₁ x = f₂ x
protected theorem Equiv.refl (f : ∀ (x : α), β x) : Equiv f f :=
fun x => rfl
protected theorem Equiv.symm {f₁ f₂ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₁ :=
fun h x => Eq.symm (h x)
protected theorem Equiv.trans {f₁ f₂ f₃ : ∀ (x : α), β x} : Equiv f₁ f₂ → Equiv f₂ f₃ → Equiv f₁ f₃ :=
fun h₁ h₂ x => Eq.trans (h₁ x) (h₂ x)
protected theorem Equiv.isEquivalence (α : Sort u) (β : α → Sort v) : Equivalence (@Function.Equiv α β) := {
refl := Equiv.refl
symm := Equiv.symm
trans := Equiv.trans
}
end Function
section
open Quotient
variable {α : Sort u} {β : α → Sort v}
@[instance]
private def funSetoid (α : Sort u) (β : α → Sort v) : Setoid (∀ (x : α), β x) :=
Setoid.mk (@Function.Equiv α β) (Function.Equiv.isEquivalence α β)
private def extfunApp (f : Quotient <| funSetoid α β) (x : α) : β x :=
Quot.liftOn f
(fun (f : ∀ (x : α), β x) => f x)
(fun f₁ f₂ h => h x)
theorem funext {f₁ f₂ : ∀ (x : α), β x} (h : ∀ x, f₁ x = f₂ x) : f₁ = f₂ := by
show extfunApp (Quotient.mk f₁) = extfunApp (Quotient.mk f₂)
apply congrArg
apply Quotient.sound
exact h
end
instance {α : Sort u} {β : α → Sort v} [∀ a, Subsingleton (β a)] : Subsingleton (∀ a, β a) where
allEq f₁ f₂ :=
funext (fun a => Subsingleton.elim (f₁ a) (f₂ a))
/- Squash -/
def Squash (α : Type u) := Quot (fun (a b : α) => True)
def Squash.mk {α : Type u} (x : α) : Squash α := Quot.mk _ x
theorem Squash.ind {α : Type u} {motive : Squash α → Prop} (h : ∀ (a : α), motive (Squash.mk a)) : ∀ (q : Squash α), motive q :=
Quot.ind h
@[inline] def Squash.lift {α β} [Subsingleton β] (s : Squash α) (f : α → β) : β :=
Quot.lift f (fun a b _ => Subsingleton.elim _ _) s
instance : Subsingleton (Squash α) where
allEq a b := by
induction a using Squash.ind
induction b using Squash.ind
apply Quot.sound
trivial
namespace Lean
/- Kernel reduction hints -/
/--
When the kernel tries to reduce a term `Lean.reduceBool c`, it will invoke the Lean interpreter to evaluate `c`.
The kernel will not use the interpreter if `c` is not a constant.
This feature is useful for performing proofs by reflection.
Remark: the Lean frontend allows terms of the from `Lean.reduceBool t` where `t` is a term not containing
free variables. The frontend automatically declares a fresh auxiliary constant `c` and replaces the term with
`Lean.reduceBool c`. The main motivation is that the code for `t` will be pre-compiled.
Warning: by using this feature, the Lean compiler and interpreter become part of your trusted code base.
This is extra 30k lines of code. More importantly, you will probably not be able to check your developement using
external type checkers (e.g., Trepplein) that do not implement this feature.
Keep in mind that if you are using Lean as programming language, you are already trusting the Lean compiler and interpreter.
So, you are mainly losing the capability of type checking your developement using external checkers.
Recall that the compiler trusts the correctness of all `[implementedBy ...]` and `[extern ...]` annotations.
If an extern function is executed, then the trusted code base will also include the implementation of the associated
foreign function.
-/
constant reduceBool (b : Bool) : Bool := b
/--
Similar to `Lean.reduceBool` for closed `Nat` terms.
Remark: we do not have plans for supporting a generic `reduceValue {α} (a : α) : α := a`.
The main issue is that it is non-trivial to convert an arbitrary runtime object back into a Lean expression.
We believe `Lean.reduceBool` enables most interesting applications (e.g., proof by reflection). -/
constant reduceNat (n : Nat) : Nat := n
axiom ofReduceBool (a b : Bool) (h : reduceBool a = b) : a = b
axiom ofReduceNat (a b : Nat) (h : reduceNat a = b) : a = b
end Lean
|
4ac45f7456c7fdaf399c06d2eb79bdb5af2c3e60 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/order/filter/cofinite.lean | 6706656e87e2185284be8ddc84c98264c0ea4663 | [
"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 | 7,266 | 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, Jeremy Avigad, Yury Kudryashov
-/
import order.filter.at_top_bot
import order.filter.pi
/-!
# The cofinite filter
In this file we define
`cofinite`: the filter of sets with finite complement
and prove its basic properties. In particular, we prove that for `ℕ` it is equal to `at_top`.
## TODO
Define filters for other cardinalities of the complement.
-/
open set function
open_locale classical
variables {ι α β : Type*}
namespace filter
/-- The cofinite filter is the filter of subsets whose complements are finite. -/
def cofinite : filter α :=
{ sets := {s | sᶜ.finite},
univ_sets := by simp only [compl_univ, finite_empty, mem_set_of_eq],
sets_of_superset := assume s t (hs : sᶜ.finite) (st: s ⊆ t),
hs.subset $ compl_subset_compl.2 st,
inter_sets := assume s t (hs : sᶜ.finite) (ht : tᶜ.finite),
by simp only [compl_inter, finite.union, ht, hs, mem_set_of_eq] }
@[simp] lemma mem_cofinite {s : set α} : s ∈ (@cofinite α) ↔ sᶜ.finite := iff.rfl
@[simp] lemma eventually_cofinite {p : α → Prop} :
(∀ᶠ x in cofinite, p x) ↔ {x | ¬p x}.finite := iff.rfl
lemma has_basis_cofinite : has_basis cofinite (λ s : set α, s.finite) compl :=
⟨λ s, ⟨λ h, ⟨sᶜ, h, (compl_compl s).subset⟩, λ ⟨t, htf, hts⟩, htf.subset $ compl_subset_comm.2 hts⟩⟩
instance cofinite_ne_bot [infinite α] : ne_bot (@cofinite α) :=
has_basis_cofinite.ne_bot_iff.2 $ λ s hs, hs.infinite_compl.nonempty
lemma frequently_cofinite_iff_infinite {p : α → Prop} :
(∃ᶠ x in cofinite, p x) ↔ set.infinite {x | p x} :=
by simp only [filter.frequently, filter.eventually, mem_cofinite, compl_set_of, not_not,
set.infinite]
lemma _root_.set.finite.compl_mem_cofinite {s : set α} (hs : s.finite) : sᶜ ∈ (@cofinite α) :=
mem_cofinite.2 $ (compl_compl s).symm ▸ hs
lemma _root_.set.finite.eventually_cofinite_nmem {s : set α} (hs : s.finite) :
∀ᶠ x in cofinite, x ∉ s :=
hs.compl_mem_cofinite
lemma _root_.finset.eventually_cofinite_nmem (s : finset α) : ∀ᶠ x in cofinite, x ∉ s :=
s.finite_to_set.eventually_cofinite_nmem
lemma _root_.set.infinite_iff_frequently_cofinite {s : set α} :
set.infinite s ↔ (∃ᶠ x in cofinite, x ∈ s) :=
frequently_cofinite_iff_infinite.symm
lemma eventually_cofinite_ne (x : α) : ∀ᶠ a in cofinite, a ≠ x :=
(set.finite_singleton x).eventually_cofinite_nmem
lemma le_cofinite_iff_compl_singleton_mem {l : filter α} :
l ≤ cofinite ↔ ∀ x, {x}ᶜ ∈ l :=
begin
refine ⟨λ h x, h (finite_singleton x).compl_mem_cofinite, λ h s (hs : sᶜ.finite), _⟩,
rw [← compl_compl s, ← bUnion_of_singleton sᶜ, compl_Union₂,filter.bInter_mem hs],
exact λ x _, h x
end
lemma le_cofinite_iff_eventually_ne {l : filter α} :
l ≤ cofinite ↔ ∀ x, ∀ᶠ y in l, y ≠ x :=
le_cofinite_iff_compl_singleton_mem
/-- If `α` is a preorder with no maximal element, then `at_top ≤ cofinite`. -/
lemma at_top_le_cofinite [preorder α] [no_max_order α] : (at_top : filter α) ≤ cofinite :=
le_cofinite_iff_eventually_ne.mpr eventually_ne_at_top
lemma comap_cofinite_le (f : α → β) : comap f cofinite ≤ cofinite :=
le_cofinite_iff_eventually_ne.mpr $ λ x,
mem_comap.2 ⟨{f x}ᶜ, (finite_singleton _).compl_mem_cofinite, λ y, ne_of_apply_ne f⟩
/-- The coproduct of the cofinite filters on two types is the cofinite filter on their product. -/
lemma coprod_cofinite : (cofinite : filter α).coprod (cofinite : filter β) = cofinite :=
filter.coext $ λ s, by simp only [compl_mem_coprod, mem_cofinite, compl_compl,
finite_image_fst_and_snd_iff]
/-- Finite product of finite sets is finite -/
lemma Coprod_cofinite {α : ι → Type*} [finite ι] :
filter.Coprod (λ i, (cofinite : filter (α i))) = cofinite :=
filter.coext $ λ s, by simp only [compl_mem_Coprod, mem_cofinite, compl_compl,
forall_finite_image_eval_iff]
end filter
open filter
/-- For natural numbers the filters `cofinite` and `at_top` coincide. -/
lemma nat.cofinite_eq_at_top : @cofinite ℕ = at_top :=
begin
refine le_antisymm _ at_top_le_cofinite,
refine at_top_basis.ge_iff.2 (λ N hN, _),
simpa only [mem_cofinite, compl_Ici] using finite_lt_nat N
end
lemma nat.frequently_at_top_iff_infinite {p : ℕ → Prop} :
(∃ᶠ n in at_top, p n) ↔ set.infinite {n | p n} :=
by rw [← nat.cofinite_eq_at_top, frequently_cofinite_iff_infinite]
lemma filter.tendsto.exists_within_forall_le {α β : Type*} [linear_order β] {s : set α}
(hs : s.nonempty)
{f : α → β} (hf : filter.tendsto f filter.cofinite filter.at_top) :
∃ a₀ ∈ s, ∀ a ∈ s, f a₀ ≤ f a :=
begin
rcases em (∃ y ∈ s, ∃ x, f y < x) with ⟨y, hys, x, hx⟩|not_all_top,
{ -- the set of points `{y | f y < x}` is nonempty and finite, so we take `min` over this set
have : {y | ¬x ≤ f y}.finite := (filter.eventually_cofinite.mp (tendsto_at_top.1 hf x)),
simp only [not_le] at this,
obtain ⟨a₀, ⟨ha₀ : f a₀ < x, ha₀s⟩, others_bigger⟩ :=
exists_min_image _ f (this.inter_of_left s) ⟨y, hx, hys⟩,
refine ⟨a₀, ha₀s, λ a has, (lt_or_le (f a) x).elim _ (le_trans ha₀.le)⟩,
exact λ h, others_bigger a ⟨h, has⟩ },
{ -- in this case, f is constant because all values are at top
push_neg at not_all_top,
obtain ⟨a₀, ha₀s⟩ := hs,
exact ⟨a₀, ha₀s, λ a ha, not_all_top a ha (f a₀)⟩ }
end
lemma filter.tendsto.exists_forall_le [nonempty α] [linear_order β] {f : α → β}
(hf : tendsto f cofinite at_top) :
∃ a₀, ∀ a, f a₀ ≤ f a :=
let ⟨a₀, _, ha₀⟩ := hf.exists_within_forall_le univ_nonempty in ⟨a₀, λ a, ha₀ a (mem_univ _)⟩
lemma filter.tendsto.exists_within_forall_ge [linear_order β] {s : set α} (hs : s.nonempty)
{f : α → β} (hf : filter.tendsto f filter.cofinite filter.at_bot) :
∃ a₀ ∈ s, ∀ a ∈ s, f a ≤ f a₀ :=
@filter.tendsto.exists_within_forall_le _ βᵒᵈ _ _ hs _ hf
lemma filter.tendsto.exists_forall_ge [nonempty α] [linear_order β] {f : α → β}
(hf : tendsto f cofinite at_bot) :
∃ a₀, ∀ a, f a ≤ f a₀ :=
@filter.tendsto.exists_forall_le _ βᵒᵈ _ _ _ hf
/-- For an injective function `f`, inverse images of finite sets are finite. See also
`filter.comap_cofinite_le` and `function.injective.comap_cofinite_eq`. -/
lemma function.injective.tendsto_cofinite {f : α → β} (hf : injective f) :
tendsto f cofinite cofinite :=
λ s h, h.preimage (hf.inj_on _)
/-- The pullback of the `filter.cofinite` under an injective function is equal to `filter.cofinite`.
See also `filter.comap_cofinite_le` and `function.injective.tendsto_cofinite`. -/
lemma function.injective.comap_cofinite_eq {f : α → β} (hf : injective f) :
comap f cofinite = cofinite :=
(comap_cofinite_le f).antisymm hf.tendsto_cofinite.le_comap
/-- An injective sequence `f : ℕ → ℕ` tends to infinity at infinity. -/
lemma function.injective.nat_tendsto_at_top {f : ℕ → ℕ} (hf : injective f) :
tendsto f at_top at_top :=
nat.cofinite_eq_at_top ▸ hf.tendsto_cofinite
|
0f2761ccdcbe775fdf39de72086fdc56f623335a | 076f5040b63237c6dd928c6401329ed5adcb0e44 | /assignments/hw8_intro_proofs.lean | 302e714d549ebda9c19a51741e671f8548978998 | [] | no_license | kevinsullivan/uva-cs-dm-f19 | 0f123689cf6cb078f263950b18382a7086bf30be | 09a950752884bd7ade4be33e9e89a2c4b1927167 | refs/heads/master | 1,594,771,841,541 | 1,575,853,850,000 | 1,575,853,850,000 | 205,433,890 | 4 | 9 | null | 1,571,592,121,000 | 1,567,188,539,000 | Lean | UTF-8 | Lean | false | false | 9,038 | lean | /-
CS 2102 F19, Homework #8, Predicate Logic & Proofs.
-/
namespace hw8
/-
#1. Equality and proofs of equality.
-/
/-
A. [10 points] Fill in the blank.
When we say that the binary equality relation,
=, on objects of any type, α, is reflexive, we
mean that for any value, a, of type, α, _______.
ANSWER:
-/
/-
B. [10 points]
Complete the following definition in Lean
to formalize the proposition that 1 equals
1.
-/
def one_eq_one : Prop :=
-- ANSWER
_
/-
C. [10 points]
Give an English language proof of the
proposition that 1 = 1 by completing the
following incomplete proof.
To obtain a proof of 1 = 1 we apply the ________
property of the ________ relation to the specific
value, _________.
ANSWER:
-/
/-
D. [10 points]
Give a formal proof of this proposition
by completing the following definition.
-/
def proof_that_one_eq_one : one_eq_one :=
-- ANSWER
_
/- [10 points]
E. Complete the following test case to produce
an example that suggests (correctly) that Lean
will accept a proof that two *different terms* are
equal as long as they reduce to the same value.
-/
-- ANSWER: Give a proposition and proof in Lean
def two_plus_two_eq_four : _ := _
-- ANSWER Does eq.refl work as suggested? _____
/-
#2. Predicates and Properties
A predicate is a parameterized proposition. By
applying a predicate to different arguments, we get
different propositions. Such a propopsition can
be said to be "about" the argument to which it was
applied.
We interpret such a proposition as asserting that
its argument has a *property* of interest. If the
proposition has a proof (is true), the object does
have the asserted property, and if the proposition
is not true, the object doesn't have that property.
In the following set of problems, we will take the
property of a natural number "being even" as a case
in point.
In natural language, we will say that a natural
number, n, is even if and only if (1) it is zero,
or, (2) it is two more than another even number.
Think about this inductive definition. Why does it
cover all possible cases -- an infinitude of cases?
(No need for an answer here.)
-/
/-
A. [10 points]
We have accepted as *axioms* in our definition
of evennness that zero is even and that any number
that is two more than another even number is even.
These are the only axioms you may use in giving a
proof that four is even. Give a natural language
proof now. Hint, start by saying the following:
Proof: To prove that four is even, *it will suffice*
to show that 2 is even, because if two is even then,
given that 4 is two more than two, if two is even
then so is four, by rule (2). Now all that remains
to be proved is that _______________.
Give the rest of your natural language proof here,
and be sure to indicate which of the two rules you
are applying at each step in your reasoning.
ANSWER:
-/
/-
B. [10 points]
We formalize a predicate, such as is_even, as a
family of "inductive propositions" given by a
function from argument values to propositions.
Such an inductive definition thus has the type,
α → Prop, where α is the type of argument to
which the predicate is applied.
Please see the first line of the definition of
is_even that follows for an example.
Having specified the *type* of a predicate, in
this case from ℕ → Prop, we then define the set
of constructors to define the logical rules that
can be used to construct proofs of any such
proposition.
These rules are the (formal) axioms that can be
used to construct proofs. The first one (below)
states that the term, pf_zero_is_even, is to be
accepted as a proof of is_even 0 (which is how
we write the application of a predicate to a value
to obtain a proposition, here that "0 is even").
The second constructor/axiom/rule provides a way
to build a proof of (is_even 2+n) by applying the
constructor to any n along with a proof that that
particular n is even. (Yes: the ∀ specifies the
first argument to pf_even_plus_two_is_even. This
is necessary to give the argument a name, here n,
so that that name can be used in defining the rest
of the constructor's type).
-/
inductive is_even : ℕ → Prop
| pf_zero_is_even : (is_even 0)
| pf_even_plus_two_is_even :
∀ (n : ℕ), is_even n → is_even (nat.succ (nat.succ n))
/-
Give formal proofs for each of the following
propositions. (Notice how we obtain different
propositions by applying the predicate, is_even,
to different argument values. This is what we
mean when we say that a predicate defines a
family of propositions.)
-/
open is_even
theorem zero_even : is_even 0 :=
-- ANSWER
_
/-
In this case, give a proof term without using
a begin/end proof script.
-/
theorem two_even : is_even 2 :=
-- ANSWER
pf_even_plus_two_is_even _ _
/-
In this case, give a proof using a begin/end
proof script.
-/
theorem eight_even : is_even 8 :=
begin
apply pf_even_plus_two_is_even,
sorry -- replace this with answer
end
/-
C. [10 points]
Formally specify a predicate, is_odd, on the
natural numbers. You can reason about any
natural number being odd using two rules, just
as for being even. Once you've defined your
predicate (an inductive family of proposition,
just like is_even), formally state and prove
the following propositions (however you wish).
- 1 is odd
- 7 is odd
-/
-- ANSWER
open is_odd
-- ANSWER
-- ANSWER
/-
Introducing an important concept. In the preceding
problems, we've seen that we can think of a predicate
with one argument as defining a property objects, such
as the property of being even. Now we shift perspective
from the concept of a property, per se, to the concept
of "the set of objects that have a given property." The
set of objects that have the is_even property, for
example, could be written as
evens = {0, 2, 4, 6, 8, 10, ...}
or more formally as
evens = { n : ℕ | is_even n}
The elements of these sets are all, and only,
the values that "satisfy" the is_even predicate.
A value satisfies its predicate if, when plugged
in, the resulting proposition has a proof (and so
is true). The key conclusion is that a predicate
with a single argument defines a *set*, namely
the set of all and only those objects that have
that property.
-/
/-
#4. Predicates and binary relations
Mathematicians define *binary relations* as sets
of ordered pairs. For example, the equality relation
on natural numbers comprises the set of of all pairs
of natural numbers such that the first and second
elements are the same. We could write this set like
this:
equals = { (0,0), (1,1), (2,2), ...},
or like this:
equals = { (m : ℕ, n : ℕ) | m = n }
We formalize binary relations as predicates with
*two* arguments. The type of such a predicate in
Lean is thus α → β → Prop, where α and β are the
types of the arguments.
In our example, we have a two-place predicate that
defines the set of ordered pairs of natural numbers
where the two elements of each pair are co-equal.
Study and understand the following specification
of this binary relation. Look at the construtor,
mk, in particular: it says that you can construct
a proof that a pair of values, n and m, is in our
id_nat_relation if you have a proof of n = m. (In
other words, it suffices to show that n = m using
Lean's built in equality relation to construct a
proof that (n, m) is in our id_nat_relation.)
-/
inductive id_nat_relation : ℕ → ℕ → Prop
| mk : ∀ (n m : ℕ), n = m → id_nat_relation n m
/-
A. [10 points]
Give a formal proof that id_nat_relation contains
the pair, (3, 3). Do it by completing the following
proof. Think carefully about the third argument: you
need a *value* of what type here? What do we call a
value of a logical type?
-/
theorem three_three_in_id : id_nat_relation 3 3 :=
-- ANSWER (apply a constructor, of course)
id_nat_relation.mk _ _ _
/-
B. [10 points]
Explain in just a few words why it is not
possible to prove that (3,5) is in this relation.
-/
-- ANSWER
/-
EXTRA CREDIT.
-/
/-
Here's a definition of what it means for a
relation to be reflexive.
-/
def reflexive {α : Type} (r : α → α → Prop) :=
∀ (a : α), r a a
/-
A. Formally state and prove that id_nat_relation
is reflexive. Hint: use a script and start it
with "assume (a : ℕ)". Remember that to prove a ∀
proposition, we *assume* that we're given some
arbitrary but specific value of the given type,
then we prove the rest of the proposition about
it. But because we didn't say anything about
the element we picked, we can conclude that the
statement must be true of any element of the type.
-/
-- ANSWER
theorem id_nat_refl : reflexive id_nat_relation :=
begin
assume (a : ℕ),
sorry -- replace this
end
/-
B. [Double extra credit.]
Formally define what we mean by a relation being
symmetric and transitive, in the style of the above
definition of reflexive, and formally state and show
that our id_nat_reflexive relation is also symmetric
and transitive.
-/
end hw8 |
c78d9f44c3001ec723225267f7d93c83e4be6985 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/squeeze.lean | ae29739d8947aa67e1f378a3fbdaec32a2ffaa21 | [
"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 | 15,210 | lean | /-
Copyright (c) 2019 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import control.traversable.basic
import tactic.simpa
setup_tactic_parser
private meta def loc.to_string_aux : option name → string
| none := "⊢"
| (some x) := to_string x
/-- pretty print a `loc` -/
meta def loc.to_string : loc → string
| (loc.ns []) := ""
| (loc.ns [none]) := ""
| (loc.ns ls) := string.join $ list.intersperse " " (" at" :: ls.map loc.to_string_aux)
| loc.wildcard := " at *"
/-- shift `pos` `n` columns to the left -/
meta def pos.move_left (p : pos) (n : ℕ) : pos :=
{ line := p.line, column := p.column - n }
namespace tactic
attribute [derive decidable_eq] simp_arg_type
/-- Turn a `simp_arg_type` into a string. -/
meta instance simp_arg_type.has_to_string : has_to_string simp_arg_type :=
⟨λ a, match a with
| simp_arg_type.all_hyps := "*"
| (simp_arg_type.except n) := "-" ++ to_string n
| (simp_arg_type.expr e) := to_string e
| (simp_arg_type.symm_expr e) := "←" ++ to_string e
end⟩
open list
/-- parse structure instance of the shape `{ field1 := value1, .. , field2 := value2 }` -/
meta def struct_inst : lean.parser pexpr :=
with_desc "cfg" $ do
tk "{",
ls ← sep_by (skip_info (tk ","))
( sum.inl <$> (tk ".." *> texpr) <|>
sum.inr <$> (prod.mk <$> ident <* tk ":=" <*> texpr)),
tk "}",
let (srcs,fields) := partition_map id ls,
let (names,values) := unzip fields,
pure $ pexpr.mk_structure_instance
{ field_names := names,
field_values := values,
sources := srcs }
/-- pretty print structure instance -/
meta def struct.to_tactic_format (e : pexpr) : tactic format :=
do r ← e.get_structure_instance_info,
fs ← mzip_with (λ n v,
do v ← to_expr v >>= pp,
pure $ format!"{n} := {v}" )
r.field_names r.field_values,
let ss := r.sources.map (λ s, format!" .. {s}"),
let x : format := format.join $ list.intersperse ", " (fs ++ ss),
pure format!" {{{x}}}"
/-- Attribute containing a table that accumulates multiple `squeeze_simp` suggestions -/
@[user_attribute]
private meta def squeeze_loc_attr :
user_attribute unit (option (list (pos × string × list simp_arg_type × string))) :=
{ name := `_squeeze_loc,
parser := fail "this attribute should not be used",
descr := "table to accumulate multiple `squeeze_simp` suggestions" }
/-- dummy declaration used as target of `squeeze_loc` attribute -/
def squeeze_loc_attr_carrier := ()
run_cmd squeeze_loc_attr.set ``squeeze_loc_attr_carrier none tt
/-- Format a list of arguments for use with `simp` and friends. This omits the
list entirely if it is empty.
Patch: `pp` was changed to `to_string` because it was getting rid of prefixes
that would be necessary for some disambiguations. -/
meta def render_simp_arg_list : list simp_arg_type → format
| [] := ""
| args := (++) " " $ to_line_wrap_format $ args.map to_string
/-- Emit a suggestion to the user. If inside a `squeeze_scope` block,
the suggestions emitted through `mk_suggestion` will be aggregated so that
every tactic that makes a suggestion can consider multiple execution of the
same invocation.
If `at_pos` is true, make the suggestion at `p` instead of the current position. -/
meta def mk_suggestion (p : pos) (pre post : string) (args : list simp_arg_type)
(at_pos := ff) : tactic unit :=
do xs ← squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier,
match xs with
| none := do
let args := render_simp_arg_list args,
if at_pos then
@scope_trace _ p.line p.column $
λ _, _root_.trace sformat!"{pre}{args}{post}" (pure () : tactic unit)
else
trace sformat!"{pre}{args}{post}"
| some xs := do
squeeze_loc_attr.set ``squeeze_loc_attr_carrier ((p,pre,args,post) :: xs) ff
end
/-- translate a `pexpr` into a `simp` configuration -/
meta def parse_config : option pexpr → tactic (simp_config_ext × format)
| none := pure ({}, "")
| (some cfg) :=
do e ← to_expr ``(%%cfg : simp_config_ext),
fmt ← has_to_tactic_format.to_tactic_format cfg,
prod.mk <$> eval_expr simp_config_ext e
<*> struct.to_tactic_format cfg
/-- translate a `pexpr` into a `dsimp` configuration -/
meta def parse_dsimp_config : option pexpr → tactic (dsimp_config × format)
| none := pure ({}, "")
| (some cfg) :=
do e ← to_expr ``(%%cfg : simp_config_ext),
fmt ← has_to_tactic_format.to_tactic_format cfg,
prod.mk <$> eval_expr dsimp_config e
<*> struct.to_tactic_format cfg
/-- `same_result proof tac` runs tactic `tac` and checks if the proof
produced by `tac` is equivalent to `proof`. -/
meta def same_result (pr : proof_state) (tac : tactic unit) : tactic bool :=
do s ← get_proof_state_after tac,
pure $ some pr = s
/--
Consumes the first list of `simp` arguments, accumulating required arguments
on the second one and unnecessary arguments on the third one.
-/
private meta def filter_simp_set_aux
(tac : bool → list simp_arg_type → tactic unit)
(args : list simp_arg_type) (pr : proof_state) :
list simp_arg_type → list simp_arg_type →
list simp_arg_type → tactic (list simp_arg_type × list simp_arg_type)
| [] ys ds := pure (ys, ds)
| (x :: xs) ys ds :=
do b ← same_result pr (tac tt (args ++ xs ++ ys)),
if b
then filter_simp_set_aux xs ys (ds.concat x)
else filter_simp_set_aux xs (ys.concat x) ds
declare_trace squeeze.deleted
/--
`filter_simp_set g call_simp user_args simp_args` returns `args'` such that, when calling
`call_simp tt /- only -/ args'` on the goal `g` (`g` is a meta var) we end up in the same
state as if we had called `call_simp ff (user_args ++ simp_args)` and removing any one
element of `args'` changes the resulting proof.
-/
meta def filter_simp_set
(tac : bool → list simp_arg_type → tactic unit)
(user_args simp_args : list simp_arg_type) : tactic (list simp_arg_type) :=
do some s ← get_proof_state_after (tac ff (user_args ++ simp_args)),
(simp_args', _) ← filter_simp_set_aux tac user_args s simp_args [] [],
(user_args', ds) ← filter_simp_set_aux tac simp_args' s user_args [] [],
when (is_trace_enabled_for `squeeze.deleted = tt ∧ ¬ ds.empty)
trace!"deleting provided arguments {ds}",
pure (user_args' ++ simp_args')
/-- make a `simp_arg_type` that references the name given as an argument -/
meta def name.to_simp_args (n : name) : simp_arg_type :=
simp_arg_type.expr $ @expr.local_const ff n n (default) pexpr.mk_placeholder
/-- If the `name` is (likely) to be overloaded, then prepend a `_root_` on it. The `expr` of an
overloaded name is constructed using `expr.macro`; this is how we guess whether it's overloaded. -/
meta def prepend_root_if_needed (n : name) : tactic name :=
do x ← resolve_name' n,
return $ match x with
| expr.macro _ _ := `_root_ ++ n
| _ := n
end
/-- tactic combinator to create a `simp`-like tactic that minimizes its
argument list.
* `slow`: adds all rfl-lemmas from the environment to the initial list (this is a slower but more
accurate strategy)
* `no_dflt`: did the user use the `only` keyword?
* `args`: list of `simp` arguments
* `tac`: how to invoke the underlying `simp` tactic
-/
meta def squeeze_simp_core
(slow no_dflt : bool) (args : list simp_arg_type)
(tac : Π (no_dflt : bool) (args : list simp_arg_type), tactic unit)
(mk_suggestion : list simp_arg_type → tactic unit) : tactic unit :=
do v ← target >>= mk_meta_var,
args ← if slow then do
simp_set ← attribute.get_instances `simp,
simp_set ← simp_set.mfilter $ has_attribute' `_refl_lemma,
simp_set ← simp_set.mmap $ resolve_name' >=> pure ∘ simp_arg_type.expr,
pure $ args ++ simp_set
else pure args,
g ← retrieve $ do
{ g ← main_goal,
tac no_dflt args,
instantiate_mvars g },
let vs := g.list_constant',
vs ← vs.mfilter is_simp_lemma,
vs ← vs.mmap strip_prefix,
vs ← vs.mmap prepend_root_if_needed,
with_local_goals' [v] (filter_simp_set tac args $ vs.map name.to_simp_args)
>>= mk_suggestion,
tac no_dflt args
namespace interactive
/-- combinator meant to aggregate the suggestions issued by multiple calls
of `squeeze_simp` (due, for instance, to `;`).
Can be used as:
```lean
example {α β} (xs ys : list α) (f : α → β) :
(xs ++ ys.tail).map f = xs.map f ∧ (xs.tail.map f).length = xs.length :=
begin
have : xs = ys, admit,
squeeze_scope
{ split; squeeze_simp,
-- `squeeze_simp` is run twice, the first one requires
-- `list.map_append` and the second one
-- `[list.length_map, list.length_tail]`
-- prints only one message and combine the suggestions:
-- > Try this: simp only [list.length_map, list.length_tail, list.map_append]
squeeze_simp [this]
-- `squeeze_simp` is run only once
-- prints:
-- > Try this: simp only [this] },
end
```
-/
meta def squeeze_scope (tac : itactic) : tactic unit :=
do none ← squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | pure (),
squeeze_loc_attr.set ``squeeze_loc_attr_carrier (some []) ff,
finally tac $ do
some xs ← squeeze_loc_attr.get_param ``squeeze_loc_attr_carrier | fail "invalid state",
let m := native.rb_lmap.of_list xs,
squeeze_loc_attr.set ``squeeze_loc_attr_carrier none ff,
m.to_list.reverse.mmap' $ λ ⟨p,suggs⟩, do
{ let ⟨pre,_,post⟩ := suggs.head,
let suggs : list (list simp_arg_type) := suggs.map $ prod.fst ∘ prod.snd,
mk_suggestion p pre post (suggs.foldl list.union []) tt, pure () }
/--
`squeeze_simp`, `squeeze_simpa` and `squeeze_dsimp` perform the same
task with the difference that `squeeze_simp` relates to `simp` while
`squeeze_simpa` relates to `simpa` and `squeeze_dsimp` relates to
`dsimp`. The following applies to `squeeze_simp`, `squeeze_simpa` and
`squeeze_dsimp`.
`squeeze_simp` behaves like `simp` (including all its arguments)
and prints a `simp only` invocation to skip the search through the
`simp` lemma list.
For instance, the following is easily solved with `simp`:
```lean
example : 0 + 1 = 1 + 0 := by simp
```
To guide the proof search and speed it up, we may replace `simp`
with `squeeze_simp`:
```lean
example : 0 + 1 = 1 + 0 := by squeeze_simp
-- prints:
-- Try this: simp only [add_zero, eq_self_iff_true, zero_add]
```
`squeeze_simp` suggests a replacement which we can use instead of
`squeeze_simp`.
```lean
example : 0 + 1 = 1 + 0 := by simp only [add_zero, eq_self_iff_true, zero_add]
```
`squeeze_simp only` prints nothing as it already skips the `simp` list.
This tactic is useful for speeding up the compilation of a complete file.
Steps:
1. search and replace ` simp` with ` squeeze_simp` (the space helps avoid the
replacement of `simp` in `@[simp]`) throughout the file.
2. Starting at the beginning of the file, go to each printout in turn, copy
the suggestion in place of `squeeze_simp`.
3. after all the suggestions were applied, search and replace `squeeze_simp` with
`simp` to remove the occurrences of `squeeze_simp` that did not produce a suggestion.
Known limitation(s):
* in cases where `squeeze_simp` is used after a `;` (e.g. `cases x; squeeze_simp`),
`squeeze_simp` will produce as many suggestions as the number of goals it is applied to.
It is likely that none of the suggestion is a good replacement but they can all be
combined by concatenating their list of lemmas. `squeeze_scope` can be used to
combine the suggestions: `by squeeze_scope { cases x; squeeze_simp }`
* sometimes, `simp` lemmas are also `_refl_lemma` and they can be used without appearing in the
resulting proof. `squeeze_simp` won't know to try that lemma unless it is called as
`squeeze_simp?`
-/
meta def squeeze_simp
(key : parse cur_pos)
(slow_and_accurate : parse (tk "?")?)
(use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)
(attr_names : parse with_ident_list) (locat : parse location)
(cfg : parse struct_inst?) : tactic unit :=
do (cfg',c) ← parse_config cfg,
squeeze_simp_core slow_and_accurate.is_some no_dflt hs
(λ l_no_dft l_args, simp use_iota_eqn none l_no_dft l_args attr_names locat cfg')
(λ args,
let use_iota_eqn := if use_iota_eqn.is_some then "!" else "",
attrs := if attr_names.empty then ""
else string.join (list.intersperse " " (" with" :: attr_names.map to_string)),
loc := loc.to_string locat in
mk_suggestion (key.move_left 1)
sformat!"Try this: simp{use_iota_eqn} only"
sformat!"{attrs}{loc}{c}" args)
/-- see `squeeze_simp` -/
meta def squeeze_simpa
(key : parse cur_pos)
(slow_and_accurate : parse (tk "?")?)
(use_iota_eqn : parse (tk "!")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list)
(attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?)
(cfg : parse struct_inst?) : tactic unit :=
do (cfg',c) ← parse_config cfg,
tgt' ← traverse (λ t, do t ← to_expr t >>= pp,
pure format!" using {t}") tgt,
squeeze_simp_core slow_and_accurate.is_some no_dflt hs
(λ l_no_dft l_args, simpa use_iota_eqn none l_no_dft l_args attr_names tgt cfg')
(λ args,
let use_iota_eqn := if use_iota_eqn.is_some then "!" else "",
attrs := if attr_names.empty then ""
else string.join (list.intersperse " " (" with" :: attr_names.map to_string)),
tgt' := tgt'.get_or_else "" in
mk_suggestion (key.move_left 1)
sformat!"Try this: simpa{use_iota_eqn} only"
sformat!"{attrs}{tgt'}{c}" args)
/-- `squeeze_dsimp` behaves like `dsimp` (including all its arguments)
and prints a `dsimp only` invocation to skip the search through the
`simp` lemma list. See the doc string of `squeeze_simp` for examples.
-/
meta def squeeze_dsimp
(key : parse cur_pos)
(slow_and_accurate : parse (tk "?")?)
(use_iota_eqn : parse (tk "!")?)
(no_dflt : parse only_flag) (hs : parse simp_arg_list)
(attr_names : parse with_ident_list) (locat : parse location)
(cfg : parse struct_inst?) : tactic unit :=
do (cfg',c) ← parse_dsimp_config cfg,
squeeze_simp_core slow_and_accurate.is_some no_dflt hs
(λ l_no_dft l_args, dsimp l_no_dft l_args attr_names locat cfg')
(λ args,
let use_iota_eqn := if use_iota_eqn.is_some then "!" else "",
attrs := if attr_names.empty then ""
else string.join (list.intersperse " " (" with" :: attr_names.map to_string)),
loc := loc.to_string locat in
mk_suggestion (key.move_left 1)
sformat!"Try this: dsimp{use_iota_eqn} only"
sformat!"{attrs}{loc}{c}" args)
end interactive
end tactic
open tactic.interactive
add_tactic_doc
{ name := "squeeze_simp / squeeze_simpa / squeeze_dsimp / squeeze_scope",
category := doc_category.tactic,
decl_names :=
[``squeeze_simp,
``squeeze_dsimp,
``squeeze_simpa,
``squeeze_scope],
tags := ["simplification", "Try this"],
inherit_description_from := ``squeeze_simp }
|
69d48ea45120f389a4d23b3036591b8196879087 | 1e3a43e8ba59c6fe1c66775b6e833e721eaf1675 | /src/topology/algebra/polynomial.lean | 67dc2ebbb5e88d2914e27792a373ab3addb5deac | [
"Apache-2.0"
] | permissive | Sterrs/mathlib | ea6910847b8dfd18500486de9ab0ee35704a3f52 | d9327e433804004aa1dc65091bbe0de1e5a08c5e | refs/heads/master | 1,650,769,884,257 | 1,587,808,694,000 | 1,587,808,694,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,031 | lean | /-
Copyright (c) 2018 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Robert Y. Lewis
Analytic facts about polynomials.
-/
import topology.algebra.ring
import data.polynomial
open polynomial is_absolute_value
lemma polynomial.tendsto_infinity {α β : Type*} [comm_ring α] [discrete_linear_ordered_field β]
(abv : α → β) [is_absolute_value abv] {p : polynomial α} (h : 0 < degree p) :
∀ x : β, ∃ r > 0, ∀ z : α, r < abv z → x < abv (p.eval z) :=
degree_pos_induction_on p h
(λ a ha x, ⟨max (x / abv a) 1, (lt_max_iff.2 (or.inr zero_lt_one)), λ z hz,
by simp [max_lt_iff, div_lt_iff' ((abv_pos abv).2 ha), abv_mul abv] at *; tauto⟩)
(λ p hp ih x, let ⟨r, hr0, hr⟩ := ih x in
⟨max r 1, lt_max_iff.2 (or.inr zero_lt_one), λ z hz, by rw [eval_mul, eval_X, abv_mul abv];
calc x < abv (p.eval z) : hr _ (max_lt_iff.1 hz).1
... ≤ abv (eval z p) * abv z : le_mul_of_ge_one_right
(abv_nonneg _ _) (max_le_iff.1 (le_of_lt hz)).2⟩)
(λ p a hp ih x, let ⟨r, hr0, hr⟩ := ih (x + abv a) in
⟨r, hr0, λ z hz, by rw [eval_add, eval_C, ← sub_neg_eq_add];
exact lt_of_lt_of_le (lt_sub_iff_add_lt.2
(by rw abv_neg abv; exact (hr z hz)))
(le_trans (le_abs_self _) (abs_abv_sub_le_abv_sub _ _ _))⟩)
lemma polynomial.continuous_eval {α} [comm_semiring α] [topological_space α]
[topological_semiring α] (p : polynomial α) : continuous (λ x, p.eval x) :=
begin
apply p.induction,
{ convert continuous_const,
ext, show polynomial.eval x 0 = 0, from rfl },
{ intros a b f haf hb hcts,
simp only [polynomial.eval_add],
refine continuous.add _ hcts,
have : ∀ x, finsupp.sum (finsupp.single a b) (λ (e : ℕ) (a : α), a * x ^ e) = b * x ^a,
from λ x, finsupp.sum_single_index (by simp),
convert continuous.mul _ _,
{ ext, apply this },
{ apply_instance },
{ apply continuous_const },
{ apply continuous_pow }}
end
|
4ca89d011d9c1d9c5ad3d4a71228ac36e952d5b3 | e21db629d2e37a833531fdcb0b37ce4d71825408 | /src/mcl/rhl.lean | 2b94e82630e906a1ff5ac2c46f6c6cc27941c919 | [] | no_license | fischerman/GPU-transformation-verifier | 614a28cb4606a05a0eb27e8d4eab999f4f5ea60c | 75a5016f05382738ff93ce5859c4cfa47ccb63c1 | refs/heads/master | 1,586,985,789,300 | 1,579,290,514,000 | 1,579,290,514,000 | 165,031,073 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 22,802 | lean | import mcl.defs
import parlang.rhl
namespace mcl
namespace rhl
open parlang
open mclk
@[reducible]
def state_assert (sig₁ sig₂ : signature) := Π n₁:ℕ, parlang.state n₁ (memory (parlang_mcl_tlocal sig₁)) (parlang_mcl_shared sig₁) → vector bool n₁ → Π n₂:ℕ, parlang.state n₂ (memory (parlang_mcl_tlocal sig₂)) (parlang_mcl_shared sig₂) → vector bool n₂ → Prop
def mclk_rel {sig₁ sig₂ : signature}
(P : state_assert sig₁ sig₂)
(k₁ : mclk sig₁) (k₂ : mclk sig₂)
(Q : state_assert sig₁ sig₂) :=
rel_hoare_state P (mclk_to_kernel k₁) (mclk_to_kernel k₂) Q
notation `{* ` P : 1 ` *} ` k₁ : 1 ` ~> ` k₂ : 1 ` {* ` Q : 1 ` *}` := mclk_rel P k₁ k₂ Q
def mclp_rel {sig₁ sig₂ : signature} (P) (p₁ : mclp sig₁) (p₂ : mclp sig₂) (Q) := rel_hoare_program mcl_init mcl_init P (mclp_to_program p₁) (mclp_to_program p₂) Q
--def eq_assert (sig₁ : signature) : state_assert sig₁ sig₁ := λ n₁ s₁ ac₁ n₂ s₂ ac₂, n₁ = n₂ ∧ s₁ = s₂ ∧ ac₁ = ac₂
-- we have to show some sort of non-interference
-- example {sig : signature} {n} {k₁} {P Q : state_assert sig sig} (h : sig "i" = { scope := scope.shared, type := ⟨_, [0], type.int⟩}) (hpi : ∀ n₁ s₁ ac₁ n₂ s₂ ac₂, P n₁ s₁ ac₁ n₂ s₂ ac₂ → n₁ = n ∧ n₂ = 1) :
-- mclk_rel P k₁ (for "i" h _ 0 (λ s, s.get' h < n) (tlocal_assign "i" (var "i" (by refl) + (literal_int 1 h))) k₁) Q := begin
-- sorry
-- end
-- example {t : type} {n : string} {sig₁ sig₂ : signature} {P Q} {expr} {k₂ : mclk sig₂} (hu : ¬expr_reads n expr)
-- (hr : @mclk_rel sig₁ sig₂ P (tlocal_assign n idx _ _ expr ;; tlocal_assign n idx _ _ expr) k₂ Q) :
-- @mclk_rel sig₁ sig₂ P (tlocal_assign n expr) k₂ Q := begin
-- unfold mclk_rel,
-- rw mclk_to_kernel,
-- intros _ _ _ _ _ _ _ hp hek₁,
-- specialize hr n₁ n₂ s₁ s₁' s₂ ac₁ ac₂ hp,
-- apply hr,
-- unfold mclk_to_kernel,
-- apply exec_state.seq,
-- {
-- apply exec_state.compute,
-- }, {
-- suffices : s₁' = state.map_active_threads ac₁ (thread_state.map (λ (s : state sig₁), state.update' _ (eval expr s) s)) (state.map_active_threads ac₁ (thread_state.map (λ (s : state sig₁), state.update' _ (eval expr s) s)) s₁),
-- {
-- subst this,
-- apply exec_state.compute,
-- }, {
-- sorry,
-- }
-- }
-- end
variables {sig sig₁ sig₂ : signature} {k₁ k₁' : mclk sig₁} {k₂ k₂' : mclk sig₂} {P P' Q Q' R : Π n₁:ℕ, parlang.state n₁ (memory $ parlang_mcl_tlocal sig₁) (parlang_mcl_shared sig₁) → vector bool n₁ → Π n₂:ℕ, parlang.state n₂ (memory $ parlang_mcl_tlocal sig₂) (parlang_mcl_shared sig₂) → vector bool n₂ → Prop}
lemma rel_mclk_to_mclp {sig₁ sig₂ : signature} (f₁ : memory (parlang_mcl_shared sig₁) → ℕ) (f₂ : memory (parlang_mcl_shared sig₂) → ℕ)
(P Q : memory (parlang_mcl_shared sig₁) → memory (parlang_mcl_shared sig₂) → Prop)
(k₁ : mclk sig₁) (k₂ : mclk sig₂) (h : mclk_rel
(λ n₁ s₁ ac₁ n₂ s₂ ac₂, ∃ m₁ m₂, initial_kernel_assertion mcl_init mcl_init P f₁ f₂ m₁ m₂ n₁ s₁ ac₁ n₂ s₂ ac₂)
k₁ k₂
(λ n₁ s₁ ac₁ n₂ s₂ ac₂, (∃ m₁, s₁.syncable m₁) → ∃ m₁ m₂, s₁.syncable m₁ ∧ s₂.syncable m₂ ∧ Q m₁ m₂))
(hg : ∀ {m₁ m₂}, P m₁ m₂ → 0 < f₁ m₁) :
mclp_rel P (mclp.intro f₁ k₁) (mclp.intro f₂ k₂) Q := rel_kernel_to_program h @hg
-- lemma assign_swap {sig : signature} {t : type} (n₁ n₂) (dim₁ dim₂) (idx₁ : vector (expression sig type.int) dim₁) (idx₂ : vector (expression sig type.int) dim₂) (h₁ h₂) (expr₁ : expression sig (type_of (sig n₁))) (expr₂ : expression sig (type_of (sig n₂))) (q) (ac : vector _ q) (s u) :
-- exec_state (mclk_to_kernel ((tlocal_assign n₁ idx₁ h₁ expr₁) ;; tlocal_assign n₂ idx₂ h₂ expr₂)) ac s u →
-- exec_state (mclk_to_kernel ((tlocal_assign n₂ idx₂ h₂ expr₂) ;; (tlocal_assign n₁ idx₁ h₁ expr₁))) ac s u := begin
-- intro h,
-- cases h,
-- rename h_t t,
-- rename h_a hl,
-- rename h_a_1 hr,
-- -- break out the compute and replace it with skip
-- apply exec_state.seq,
-- {
-- }
-- end
--todo define interference (maybe choose another name) and define swap on non-interference
--lemma rel_assign_swap {sig₁ sig₂ : signature}
/-- Prepend skip to the left program -/
lemma add_skip_left : {* P *} k₁ ~> k₂ {* Q *} ↔
{* P *} skip ;; k₁ ~> k₂ {* Q *} := begin
-- this only solves ltr
unfold mclk_rel,
apply iff.intro,
{
intro h,
intros n₁ n₂ s₁ s₁' s₂ ac₁ ac₂ hp he₁,
apply h,
exact hp,
cases he₁,
cases he₁_a,
sorry --trivial from he₁_a_1
}, {
intro h,
intros n₁ n₂ s₁ s₁' s₂ ac₁ ac₂ hp he₁,
apply h,
exact hp,
apply exec_state.seq _ _ _ _ _ _ _ he₁,
sorry,
}
end
lemma skip_left_after : {* P *} k₁ ~> k₂ {* Q *} ↔
{* P *} k₁ ;; skip ~> k₂ {* Q *} := sorry
lemma skip_right : {* P *} k₁ ~> k₂ {* Q *} ↔
{* P *} k₁ ~> skip ;; k₂ {* Q *} := sorry
lemma skip_right_after : {* P *} k₁ ~> k₂ {* Q *} ↔
{* P *} k₁ ~> k₂ ;; skip {* Q *} := sorry
lemma single_step_left :
{* P *} k₁ ~> skip {* Q *} →
{* Q *} k₁' ~> k₂ {* R *} →
{* P *} (k₁ ;; k₁') ~> k₂ {* R *} := parlang.single_step_left Q
@[irreducible]
def exprs_to_indices {n dim} {idx : vector (expression sig type.int) dim} (h : ((sig.val n).type).dim = vector.length idx) (s : (memory $ parlang_mcl_tlocal sig)) :
(sig.val n).type.dim = (idx.map (eval s)).length := h
open expression
lemma seq (Q) (h₁ : {* P *} k₁ ~> k₂ {* Q *}) (h₂ : {* Q *} k₁' ~> k₂' {* R *}) :
{* P *} k₁ ;; k₁' ~> k₂ ;; k₂' {* R *} := parlang.seq Q h₁ h₂
lemma seq_left {P R} (Q) (h₁ : {* P *} k₁ ~> skip {* Q *}) (h₂ : {* Q *} k₁' ~> k₂' {* R *}) :
mclk_rel P (k₁ ;; k₁') k₂' R := skip_right.mpr (seq Q h₁ h₂)
lemma consequence (h : {* P *} k₁ ~> k₂ {* Q *})
(hp : ∀ n₁ s₁ ac₁ n₂ s₂ ac₂, P' n₁ s₁ ac₁ n₂ s₂ ac₂ → P n₁ s₁ ac₁ n₂ s₂ ac₂)
(hq : ∀ n₁ s₁ ac₁ n₂ s₂ ac₂, Q n₁ s₁ ac₁ n₂ s₂ ac₂ → Q' n₁ s₁ ac₁ n₂ s₂ ac₂) :
{* P' *} k₁ ~> k₂ {* Q' *} := consequence h hp hq
lemma swap_skip (h : {* parlang.assertion_swap_side P *} skip ~> k₁ {* parlang.assertion_swap_side Q *}) :
{* P *} k₁ ~> skip {* Q *} := begin
apply parlang.swap h,
intros,
use s₁,
apply exec_skip,
end
-- todo relate to load_shared_vars_for_expr
/-- Copy values from shared to tlocal memory for all occurences of shared variables in *expr*. If there are no references, this definition is equal to *id*. This definition is the equivalent of load_shared_vars_for_expr for *thread_state*. -/
def thread_state.update_shared_vars_for_expr {t : type} (expr : expression sig t) :
thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) :=
expression.rec_on expr
-- tlocal
(λ t dim n idx h₁ h₂ h₃ ih, id)
-- shared
(λ t dim n idx h₁ h₂ h₃ ih, λ ts,
((list.range_fin dim).foldl (λ ts e, ih e ts) ts
).load (λ m, ⟨mcl_addr_from_var h₂ (vector.of_fn idx) m, λ v, m.update (mcl_addr_from_var h₂ (vector.of_fn idx) m) v⟩))
-- add
(λ t a b ih_a ih_b, ih_b ∘ ih_a)
-- mult
(λ t a b ih_a ih_b, ih_b ∘ ih_a)
-- literal_int
(λ t n h, id)
-- lt
(λ t h a b ih_a ih_b, ih_b ∘ ih_a)
/-- Lifts *thread_state.update_shared_vars_for_expr* to a vector -/
def thread_state.update_shared_vars_for_exprs {n} {t : type} (exprs : vector (expression sig t) n) :
thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) → thread_state (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig) :=
λts, exprs.to_list.foldr (λexpr ts, thread_state.update_shared_vars_for_expr expr ts) ts
-- TODO: change to double implication
/-- Resolve semantics of loading_shared_vars_for_expr to the relation on state -/
lemma update_load_shared_vars_for_expr {sig t} {expr : expression sig t} {n} {ac : vector bool n} {s u} :
exec_state (list.foldr kernel.seq (kernel.compute id) (load_shared_vars_for_expr expr)) ac s u ↔
u = s.map_active_threads ac (thread_state.update_shared_vars_for_expr expr) := begin
sorry,
-- apply iff.intro,
-- {
-- induction expr generalizing s u,
-- case mcl.expression.tlocal_var {
-- intro h,
-- delta thread_state.update_shared_vars_for_expr,
-- unfold load_shared_vars_for_expr at h,
-- cases h,
-- have : (λ (a : state sig), a) = id := by refl,
-- rw this,
-- rw ← parlang.state.map_active_threads_id s ac,
-- simp [state.map_active_threads],
-- sorry,
-- },
-- case mcl.expression.shared_var {
-- cases h,
-- cases h_a_1,
-- cases h_a,
-- have : (λ (a : state sig), a) = id := by refl,
-- rw this,
-- sorry,
-- },
-- case mcl.expression.add {
-- rw load_shared_vars_for_expr at h,
-- simp at h,
-- rw kernel_foldr_skip at h,
-- cases h,
-- specialize expr_ih_a h_a,
-- specialize expr_ih_a_1 h_a_1,
-- subst expr_ih_a_1,
-- subst expr_ih_a,
-- rw parlang.state.map_map_active_threads',
-- refl,
-- },
-- case mcl.expression.literal_int {
-- cases h,
-- sorry,
-- },
-- case mcl.expression.lt {
-- rw load_shared_vars_for_expr at h,
-- simp at h,
-- rw kernel_foldr_skip at h,
-- cases h,
-- specialize expr_ih_a h_a,
-- specialize expr_ih_a_1 h_a_1,
-- subst expr_ih_a_1,
-- subst expr_ih_a,
-- rw parlang.state.map_map_active_threads',
-- refl,
-- }
-- }
end
lemma update_load_shared_vars_for_exprs {sig t m} {exprs : vector (expression sig t) m} {n} {ac : vector bool n} {s u} :
exec_state (exprs.to_list.foldr (λexpr' k, prepend_load_expr expr' k) (kernel.compute id)) ac s u ↔
u = s.map_active_threads ac (thread_state.update_shared_vars_for_exprs exprs) := begin
unfold thread_state.update_shared_vars_for_exprs,
cases exprs,
simp,
sorry, -- induction exprs_val and update_load_shared_vars_for_expr
end
lemma foldr_prepend_load_expr_skip {sig t} {k : kernel (memory $ parlang_mcl_tlocal sig) (parlang_mcl_shared sig)} {n} {s u} {ac : vector bool n} {v : list $ expression sig t} : exec_state
(list.foldr (λ expr' k, prepend_load_expr expr' k) k v)
ac s u ↔
exec_state
((list.foldr (λ expr' k, prepend_load_expr expr' k) (kernel.compute id) v) ;; k)
ac s u := sorry
/-- Single-sided inference rule -/
lemma update_load_shared_vars_for_expr_right {t} {expr : expression sig₂ t} :
{* λn₁ s₁ ac₁ n₂ (s₂ : state n₂ (memory (parlang_mcl_tlocal sig₂)) (parlang_mcl_shared sig₂)) ac₂, P n₁ s₁ ac₁ n₂ (s₂.map_active_threads ac₂ (thread_state.update_shared_vars_for_expr expr)) ac₂ *}
kernel.compute id ~> list.foldr kernel.seq (kernel.compute id) (load_shared_vars_for_expr expr)
{* P *} := begin
intros _ _ _ _ _ _ _ hp he,
use (s₂.map_active_threads ac₂ (thread_state.update_shared_vars_for_expr expr)),
split, {
rw update_load_shared_vars_for_expr,
}, {
cases he,
sorry, -- trivial
}
end
def f := λ n, n * 2
def g := λ(n : nat), n + 1
#check g
#eval (f ∘ g) 4
-- TODO should this moved to defs?
/-- Stores the locally computed value in the shadow memory. This is an abstraction over *thread_state.store*, which hides the lambda-term. This makes it easier to rewrite. -/
@[irreducible]
def thread_state.tlocal_to_shared {sig : signature} {t} {dim} (var : string) (idx : vector (expression sig type.int) dim) (h₁ : type_of (sig.val var) = t) (h₂ : ((sig.val var).type).dim = dim) :=
@thread_state.store _ _ (parlang_mcl_shared sig) _ (λ (m : memory $ parlang_mcl_tlocal sig), ⟨mcl_addr_from_var h₂ idx m, m.get $ mcl_addr_from_var h₂ idx m⟩)
/-- Evaluates an expressions and assigns the value -/
def thread_state.assign_expr {sig : signature} (var) (expr : expression sig $ sig.type_of var)
(idx : vector (expression sig type.int) (sig.val var).type.dim) :=
@thread_state.compute (memory $ parlang_mcl_tlocal sig) _ (parlang_mcl_shared sig) _
$ λs, s.update ⟨var, idx.map (eval s)⟩ $ eval s expr
/-- Processes a single tlocal assign on the right side. Proven by operational semantics -/
lemma tlocal_assign_right {var}
{expr : expression sig₂ $ sig₂.type_of var}
{idx : vector (expression sig₂ type.int) (sig₂.val var).type.dim} :
{* (λ n₁ s₁ ac₁ n₂ s₂ ac₂, P n₁ s₁ ac₁ n₂
((s₂ : parlang.state n₂ (memory $ parlang_mcl_tlocal sig₂) (parlang_mcl_shared sig₂)).map_active_threads ac₂ (
thread_state.assign_expr var expr idx ∘
thread_state.update_shared_vars_for_expr expr
)) ac₂) *}
(skip : mclk sig₁) ~> tlocal_assign var idx rfl rfl expr {* P *} := begin
unfold mclk_rel,
unfold mclk_to_kernel,
unfold prepend_load_expr,
sorry,
end
-- lemma tlocal_assign_right {t dim n expr} {idx : vector (expression sig₂ type.int) dim} {h₁ : type_of (sig₂ n) = t} {h₂ : ((sig₂ n).type).dim = vector.length idx} :
-- mclk_rel (λ n₁ s₁ ac₁ n₂ s₂ ac₂, P n₁ s₁ ac₁ n₂ (s₂.map_active_threads ac₂ (λ ts, (thread_state.update_shared_vars_for_expr expr ts).map (λ s, s.update' h₁ (exprs_to_indices h₂ s) (eval s expr)))) ac₂) (skip : mclk sig₁) (tlocal_assign n idx h₁ h₂ expr) P := begin
-- intros n₁ n₂ s₁ s₁' s₂ ac₁ ac₂ hp he₁,
-- use (s₂.map_active_threads ac₂ (λ ts, (thread_state.update_shared_vars_for_expr expr ts).map (λ s, s.update' h₁ (exprs_to_indices h₂ s) (eval s expr)))),
-- split, {
-- unfold mclk_to_kernel,
-- unfold prepend_load_expr,
-- rw kernel_foldr_skip,
-- apply exec_state.seq,
-- {
-- rw update_load_shared_vars_for_expr,
-- }, {
-- rw [← parlang.state.map_map_active_threads'],
-- apply exec_state.compute,
-- }
-- }, {
-- have : s₁ = s₁' := sorry, -- trivial skip
-- subst this,
-- exact hp,
-- }
-- end
-- lemma tlocal_assign_right' {t dim n expr} {idx : vector (expression sig₂ type.int) dim} {h₁ : type_of (sig₂ n) = t} {h₂ : ((sig₂ n).type).dim = vector.length idx}
-- (hi : ∀ n₁ s₁ ac₁ n₂ s₂ ac₂, P n₁ s₁ ac₁ n₂ s₂ ac₂ → Q n₁ s₁ ac₁ n₂ (s₂.map_active_threads ac₂ (λ ts, (thread_state.update_shared_vars_for_expr ts expr).map (λ s, s.update' h₁ (exprs_to_indices h₂ s) (eval s expr)))) ac₂) :
-- mclk_rel P (skip : mclk sig₁) (tlocal_assign n idx h₁ h₂ expr) Q := begin
-- apply consequence tlocal_assign_right hi,
-- intros _ _ _ _ _ _ _,
-- assumption,
-- end
-- lemma tlocal_assign_left {t dim n expr} {idx : vector (expression sig₁ type.int) dim} {h₁ : type_of (sig₁ n) = t} {h₂ : ((sig₁ n).type).dim = vector.length idx} :
-- mclk_rel (λ n₁ s₁ ac₁ n₂ s₂ ac₂, P n₁ (s₁.map_active_threads ac₁ (λ ts, (thread_state.update_shared_vars_for_expr ts expr).map (λ s, s.update' h₁ (exprs_to_indices h₂ s) (eval s expr)))) ac₁ n₂ s₂ ac₂)
-- (tlocal_assign n idx h₁ h₂ expr) (skip : mclk sig₂) P := begin
-- apply swap_skip tlocal_assign_right,
-- end
-- lemma tlocal_assign_left' {t dim n expr} {idx : vector (expression sig₁ type.int) dim} {h₁ : type_of (sig₁ n) = t} {h₂ : ((sig₁ n).type).dim = vector.length idx}
-- (hi : ∀ n₁ s₁ ac₁ n₂ s₂ ac₂, P n₁ s₁ ac₁ n₂ s₂ ac₂ → Q n₁ (s₁.map_active_threads ac₁ (λ ts, (thread_state.update_shared_vars_for_expr ts expr).map (λ s, s.update' h₁ (exprs_to_indices h₂ s) (eval s expr)))) ac₁ n₂ s₂ ac₂) :
-- mclk_rel P (tlocal_assign n idx h₁ h₂ expr) (skip : mclk sig₂) Q := begin
-- apply consequence tlocal_assign_left hi,
-- intros _ _ _ _ _ _ _,
-- assumption,
-- end
-- todo define in terms of
/-- Processes a single shared assign on the right side. Proven by operational semantics -/
lemma shared_assign_right'' {var}
{expr : expression sig₂ $ sig₂.type_of var}
{idx : vector (expression sig₂ type.int) (sig₂.val var).type.dim} :
{* (λ n₁ s₁ ac₁ n₂ s₂ ac₂, P n₁ s₁ ac₁ n₂
((s₂ : parlang.state n₂ (memory $ parlang_mcl_tlocal sig₂) (parlang_mcl_shared sig₂)).map_active_threads ac₂ (
thread_state.tlocal_to_shared var idx rfl rfl ∘
thread_state.assign_expr var expr idx ∘
thread_state.update_shared_vars_for_expr expr ∘
thread_state.update_shared_vars_for_exprs idx
)) ac₂) *}
(skip : mclk sig₁) ~> shared_assign var idx rfl rfl expr {* P *} := begin
unfold mclk_rel,
unfold mclk_to_kernel,
unfold prepend_load_expr,
sorry,
end
/-- Processes a single shared assign on the right side. Proven by operational semantics -/
lemma shared_assign_right {t dim n} {idx : vector (expression sig₂ type.int) dim} {h₁ : type_of (sig₂.val n) = t} {h₂ : ((sig₂.val n).type).dim = dim} {expr : expression sig₂ t} :
{* (λ n₁ s₁ ac₁ n₂ s₂ ac₂, P n₁ s₁ ac₁ n₂
((s₂ : parlang.state n₂ (memory $ parlang_mcl_tlocal sig₂) (parlang_mcl_shared sig₂)).map_active_threads ac₂ (
thread_state.tlocal_to_shared n idx h₁ h₂ ∘
thread_state.compute (memory.update_assign n idx h₁ h₂ expr) ∘
thread_state.update_shared_vars_for_expr expr ∘
thread_state.update_shared_vars_for_exprs idx
)) ac₂) *}
(skip : mclk sig₁) ~> shared_assign n idx h₁ h₂ expr {* P *} := begin
intros n₁ n₂ s₁ s₁' s₂ ac₁ ac₂ hp he₁,
use ((s₂ : parlang.state n₂ (memory $ parlang_mcl_tlocal sig₂) (parlang_mcl_shared sig₂)).map_active_threads ac₂ (
thread_state.tlocal_to_shared n idx h₁ h₂ ∘
thread_state.compute (memory.update_assign n idx h₁ h₂ expr) ∘
thread_state.update_shared_vars_for_expr expr ∘
thread_state.update_shared_vars_for_exprs idx
)),
split, {
unfold mclk_to_kernel,
rw foldr_prepend_load_expr_skip,
apply exec_state.seq,
{
rw update_load_shared_vars_for_exprs,
},
apply exec_state.seq,
{
unfold prepend_load_expr,
rw kernel_foldr_skip,
apply exec_state.seq,
{
rw update_load_shared_vars_for_expr,
}, {
apply exec_state.compute,
}
}, {
rw parlang.state.map_map_active_threads',
rw parlang.state.map_map_active_threads',
unfold thread_state.tlocal_to_shared,
rw [← parlang.state.map_map_active_threads' _ (thread_state.store _)],
apply exec_state.store,
}
}, {
have : s₁ = s₁' := sorry, -- trivial skip
subst this,
exact hp,
},
end
/-- Proven by Parlang inference rules -/
lemma shared_assign_right' {t dim n} {idx : vector (expression sig₂ type.int) dim} {h₁ : type_of (sig₂.val n) = t} {h₂ : ((sig₂.val n).type).dim = dim} {expr : expression sig₂ t} :
{* (λ n₁ s₁ ac₁ n₂ s₂ ac₂, P n₁ s₁ ac₁ n₂
((s₂ : parlang.state n₂ (memory $ parlang_mcl_tlocal sig₂) (parlang_mcl_shared sig₂)).map_active_threads ac₂ (
thread_state.tlocal_to_shared n idx h₁ h₂ ∘
thread_state.compute (λ s : memory $ parlang_mcl_tlocal sig₂, s.update ⟨n, by rw h₂; exact idx.map (eval s)⟩ (begin unfold parlang_mcl_tlocal signature.lean_type_of lean_type_of, rw h₁, exact (eval s expr) end)) ∘
thread_state.update_shared_vars_for_expr expr ∘
thread_state.update_shared_vars_for_exprs idx
)) ac₂) *}
(skip : mclk sig₁) ~> shared_assign n idx h₁ h₂ expr {* P *} := begin
rw skip_left_after,
rw skip_left_after,
unfold mclk_rel mclk_to_kernel,
sorry,
/- apply parlang.seq,
swap, {
apply parlang.store_right,
}, {
unfold prepend_load_expr,
rw kernel_foldr_skip_right,
apply parlang.seq,
swap,
apply parlang.compute_right,
apply parlang.consequence_pre,
exact update_load_shared_vars_for_expr_right,
{
intros,
repeat { rw parlang.state.map_map_active_threads },
sorry,
}
} -/
end
lemma shared_assign_left {t dim n expr} {idx : vector (expression sig₁ type.int) dim} {h₁ : type_of (sig₁.val n) = t} {h₂ : ((sig₁.val n).type).dim = vector.length idx} :
mclk_rel (λ n₁ s₁ ac₁ n₂ s₂ ac₂, P n₁
((s₁ : parlang.state n₁ (memory $ parlang_mcl_tlocal sig₁) (parlang_mcl_shared sig₁)).map_active_threads ac₁ (
thread_state.tlocal_to_shared n idx h₁ h₂ ∘
thread_state.compute (memory.update_assign n idx h₁ h₂ expr) ∘
thread_state.update_shared_vars_for_expr expr ∘
thread_state.update_shared_vars_for_exprs idx
)) ac₁ n₂ s₂ ac₂)
(shared_assign n idx h₁ h₂ expr) (skip : mclk sig₂) P := begin
apply swap_skip shared_assign_right,
end
lemma shared_assign_left' {t dim n expr} {idx : vector (expression sig₁ type.int) dim} {h₁ : type_of (sig₁.val n) = t} {h₂ : ((sig₁.val n).type).dim = vector.length idx}
(hi : ∀ n₁ s₁ ac₁ n₂ s₂ ac₂, P n₁ s₁ ac₁ n₂ s₂ ac₂ → Q n₁
(s₁.map_active_threads ac₁ (
thread_state.tlocal_to_shared n idx h₁ h₂ ∘
thread_state.compute (memory.update_assign n idx h₁ h₂ expr) ∘
thread_state.update_shared_vars_for_expr expr ∘
thread_state.update_shared_vars_for_exprs idx
)) ac₁ n₂ s₂ ac₂) :
mclk_rel P (shared_assign n idx h₁ h₂ expr) (skip : mclk sig₂) Q := begin
apply consequence shared_assign_left hi,
intros _ _ _ _ _ _ _,
assumption,
end
end rhl
end mcl |
72eac42a5a7b0cad056e9a90b716436a6d565aa0 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /11_Tactic-Style_Proofs.org.14.lean | f1ae1f865e9b2bcc3404aadc371e69a5e6ca591d | [] | 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 | 139 | lean | import standard
example : ∀ a b c : nat, a = b → a = c → c = b :=
begin
intros,
apply eq.trans,
apply eq.symm,
repeat assumption
end
|
a4a753309274bbadda1cc1117fbe00e9b7bc37ba | 6e9cd8d58e550c481a3b45806bd34a3514c6b3e0 | /src/data/real/cau_seq.lean | 28c80bf52a2271edbf940d55c223ac91e7b02d3c | [
"Apache-2.0"
] | permissive | sflicht/mathlib | 220fd16e463928110e7b0a50bbed7b731979407f | 1b2048d7195314a7e34e06770948ee00f0ac3545 | refs/heads/master | 1,665,934,056,043 | 1,591,373,803,000 | 1,591,373,803,000 | 269,815,267 | 0 | 0 | Apache-2.0 | 1,591,402,068,000 | 1,591,402,067,000 | null | UTF-8 | Lean | false | false | 24,863 | 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 algebra.big_operators
/-!
# Cauchy sequences
A basic theory of Cauchy sequences, used in the construction of the reals and p-adic numbers. Where
applicable, lemmas that will be reused in other contexts have been stated in extra generality.
There are other "versions" of Cauchyness in the library, in particular Cauchy filters in topology.
This is a concrete implementation that is useful for simplicity and computability reasons.
## Important definitions
* `is_absolute_value`: a type class stating that `f : β → α` satisfies the axioms of an abs val
* `is_cau_seq`: a predicate that says `f : ℕ → β` is Cauchy.
## Tags
sequence, cauchy, abs val, absolute value
-/
/-- A function f is an absolute value if it is nonnegative, zero only at 0, additive, and
multiplicative. -/
class is_absolute_value {α} [discrete_linear_ordered_field α]
{β} [ring β] (f : β → α) : Prop :=
(abv_nonneg [] : ∀ x, 0 ≤ f x)
(abv_eq_zero [] : ∀ {x}, f x = 0 ↔ x = 0)
(abv_add [] : ∀ x y, f (x + y) ≤ f x + f y)
(abv_mul [] : ∀ x y, f (x * y) = f x * f y)
namespace is_absolute_value
variables {α : Type*} [discrete_linear_ordered_field α]
{β : Type*} [ring β] (abv : β → α) [is_absolute_value abv]
theorem abv_zero : abv 0 = 0 := (abv_eq_zero abv).2 rfl
theorem abv_one' (h : (1:β) ≠ 0) : abv 1 = 1 :=
(domain.mul_right_inj $ mt (abv_eq_zero abv).1 h).1 $
by rw [← abv_mul abv, mul_one, mul_one]
theorem abv_one
{β : Type*} [domain β] (abv : β → α) [is_absolute_value abv] :
abv 1 = 1 := abv_one' abv one_ne_zero
theorem abv_pos {a : β} : 0 < abv a ↔ a ≠ 0 :=
by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [abv_eq_zero abv, abv_nonneg abv]
theorem abv_neg (a : β) : abv (-a) = abv a :=
by rw [← mul_self_inj_of_nonneg (abv_nonneg abv _) (abv_nonneg abv _),
← abv_mul abv, ← abv_mul abv]; simp
theorem abv_sub (a b : β) : abv (a - b) = abv (b - a) :=
by rw [← neg_sub, abv_neg abv]
theorem abv_inv
{β : Type*} [field β] (abv : β → α) [is_absolute_value abv]
(a : β) : abv a⁻¹ = (abv a)⁻¹ :=
classical.by_cases
(λ h : a = 0, by simp [h, abv_zero abv])
(λ h, (domain.mul_left_inj (mt (abv_eq_zero abv).1 h)).1 $
by rw [← abv_mul abv]; simp [h, mt (abv_eq_zero abv).1 h, abv_one abv])
theorem abv_div
{β : Type*} [field β] (abv : β → α) [is_absolute_value abv]
(a b : β) : abv (a / b) = abv a / abv b :=
by rw [division_def, abv_mul abv, abv_inv abv]; refl
lemma abv_sub_le (a b c : β) : abv (a - c) ≤ abv (a - b) + abv (b - c) :=
by simpa [sub_eq_add_neg, add_assoc] using abv_add abv (a - b) (b - c)
lemma sub_abv_le_abv_sub (a b : β) : abv a - abv b ≤ abv (a - b) :=
sub_le_iff_le_add.2 $ by simpa using abv_add abv (a - b) b
lemma abs_abv_sub_le_abv_sub (a b : β) :
abs (abv a - abv b) ≤ abv (a - b) :=
abs_sub_le_iff.2 ⟨sub_abv_le_abv_sub abv _ _,
by rw abv_sub abv; apply sub_abv_le_abv_sub abv⟩
lemma abv_pow {β : Type*} [domain β] (abv : β → α) [is_absolute_value abv]
(a : β) (n : ℕ) : abv (a ^ n) = abv a ^ n :=
by induction n; simp [abv_mul abv, _root_.pow_succ, abv_one abv, *]
end is_absolute_value
instance abs_is_absolute_value {α} [discrete_linear_ordered_field α] :
is_absolute_value (abs : α → α) :=
{ abv_nonneg := abs_nonneg,
abv_eq_zero := λ _, abs_eq_zero,
abv_add := abs_add,
abv_mul := abs_mul }
open is_absolute_value
theorem exists_forall_ge_and {α} [linear_order α] {P Q : α → Prop} :
(∃ i, ∀ j ≥ i, P j) → (∃ i, ∀ j ≥ i, Q j) →
∃ i, ∀ j ≥ i, P j ∧ Q j
| ⟨a, h₁⟩ ⟨b, h₂⟩ := let ⟨c, ac, bc⟩ := exists_ge_of_linear a b in
⟨c, λ j hj, ⟨h₁ _ (le_trans ac hj), h₂ _ (le_trans bc hj)⟩⟩
section
variables {α : Type*} [discrete_linear_ordered_field α]
{β : Type*} [ring β] (abv : β → α) [is_absolute_value abv]
theorem rat_add_continuous_lemma
{ε : α} (ε0 : 0 < ε) : ∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β},
abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ + a₂ - (b₁ + b₂)) < ε :=
⟨ε / 2, half_pos ε0, λ a₁ a₂ b₁ b₂ h₁ h₂,
by simpa [add_halves, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]
using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add h₁ h₂)⟩
theorem rat_mul_continuous_lemma
{ε K₁ K₂ : α} (ε0 : 0 < ε) :
∃ δ > 0, ∀ {a₁ a₂ b₁ b₂ : β}, abv a₁ < K₁ → abv b₂ < K₂ →
abv (a₁ - b₁) < δ → abv (a₂ - b₂) < δ → abv (a₁ * a₂ - b₁ * b₂) < ε :=
begin
have K0 : (0 : α) < max 1 (max K₁ K₂) := lt_of_lt_of_le zero_lt_one (le_max_left _ _),
have εK := div_pos (half_pos ε0) K0,
refine ⟨_, εK, λ a₁ a₂ b₁ b₂ ha₁ hb₂ h₁ h₂, _⟩,
replace ha₁ := lt_of_lt_of_le ha₁ (le_trans (le_max_left _ K₂) (le_max_right 1 _)),
replace hb₂ := lt_of_lt_of_le hb₂ (le_trans (le_max_right K₁ _) (le_max_right 1 _)),
have := add_lt_add
(mul_lt_mul' (le_of_lt h₁) hb₂ (abv_nonneg abv _) εK)
(mul_lt_mul' (le_of_lt h₂) ha₁ (abv_nonneg abv _) εK),
rw [← abv_mul abv, mul_comm, div_mul_cancel _ (ne_of_gt K0), ← abv_mul abv, add_halves] at this,
simpa [mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm]
using lt_of_le_of_lt (abv_add abv _ _) this
end
theorem rat_inv_continuous_lemma
{β : Type*} [field β] (abv : β → α) [is_absolute_value abv]
{ε K : α} (ε0 : 0 < ε) (K0 : 0 < K) :
∃ δ > 0, ∀ {a b : β}, K ≤ abv a → K ≤ abv b →
abv (a - b) < δ → abv (a⁻¹ - b⁻¹) < ε :=
begin
have KK := mul_pos K0 K0,
have εK := mul_pos ε0 KK,
refine ⟨_, εK, λ a b ha hb h, _⟩,
have a0 := lt_of_lt_of_le K0 ha,
have b0 := lt_of_lt_of_le K0 hb,
rw [inv_sub_inv ((abv_pos abv).1 a0) ((abv_pos abv).1 b0),
abv_div abv, abv_mul abv, mul_comm, abv_sub abv,
← mul_div_cancel ε (ne_of_gt KK)],
exact div_lt_div h
(mul_le_mul hb ha (le_of_lt K0) (abv_nonneg abv _))
(le_of_lt $ mul_pos ε0 KK) KK
end
end
/-- A sequence is Cauchy if the distance between its entries tends to zero. -/
def is_cau_seq {α : Type*} [discrete_linear_ordered_field α]
{β : Type*} [ring β] (abv : β → α) (f : ℕ → β) :=
∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - f i) < ε
namespace is_cau_seq
variables {α : Type*} [discrete_linear_ordered_field α]
{β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] {f : ℕ → β}
theorem cauchy₂ (hf : is_cau_seq abv f) {ε:α} (ε0 : ε > 0) :
∃ i, ∀ j k ≥ i, abv (f j - f k) < ε :=
begin
refine (hf _ (half_pos ε0)).imp (λ i hi j k ij ik, _),
rw ← add_halves ε,
refine lt_of_le_of_lt (abv_sub_le abv _ _ _) (add_lt_add (hi _ ij) _),
rw abv_sub abv, exact hi _ ik
end
theorem cauchy₃ (hf : is_cau_seq abv f) {ε:α} (ε0 : ε > 0) :
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε :=
let ⟨i, H⟩ := hf.cauchy₂ ε0 in ⟨i, λ j ij k jk, H _ _ (le_trans ij jk) ij⟩
end is_cau_seq
def cau_seq {α : Type*} [discrete_linear_ordered_field α]
(β : Type*) [ring β] (abv : β → α) :=
{f : ℕ → β // is_cau_seq abv f}
namespace cau_seq
variables {α : Type*} [discrete_linear_ordered_field α]
section ring
variables {β : Type*} [ring β] {abv : β → α}
instance : has_coe_to_fun (cau_seq β abv) := ⟨_, subtype.val⟩
@[simp] theorem mk_to_fun (f) (hf : is_cau_seq abv f) :
@coe_fn (cau_seq β abv) _ ⟨f, hf⟩ = f := rfl
theorem ext {f g : cau_seq β abv} (h : ∀ i, f i = g i) : f = g :=
subtype.eq (funext h)
theorem is_cau (f : cau_seq β abv) : is_cau_seq abv f := f.2
theorem cauchy (f : cau_seq β abv) :
∀ {ε}, ε > 0 → ∃ i, ∀ j ≥ i, abv (f j - f i) < ε := f.2
def of_eq (f : cau_seq β abv) (g : ℕ → β) (e : ∀ i, f i = g i) : cau_seq β abv :=
⟨g, λ ε, by rw [show g = f, from (funext e).symm]; exact f.cauchy⟩
variable [is_absolute_value abv]
theorem cauchy₂ (f : cau_seq β abv) {ε:α} : ε > 0 →
∃ i, ∀ j k ≥ i, abv (f j - f k) < ε := f.2.cauchy₂
theorem cauchy₃ (f : cau_seq β abv) {ε:α} : ε > 0 →
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - f j) < ε := f.2.cauchy₃
theorem bounded (f : cau_seq β abv) : ∃ r, ∀ i, abv (f i) < r :=
begin
cases f.cauchy zero_lt_one with i h,
let R := (finset.range (i+1)).sum (λ j, abv (f j)),
have : ∀ j ≤ i, abv (f j) ≤ R,
{ intros j ij, change (λ j, abv (f j)) j ≤ R,
apply finset.single_le_sum,
{ intros, apply abv_nonneg abv },
{ rwa [finset.mem_range, nat.lt_succ_iff] } },
refine ⟨R + 1, λ j, _⟩,
cases lt_or_le j i with ij ij,
{ exact lt_of_le_of_lt (this _ (le_of_lt ij)) (lt_add_one _) },
{ have := lt_of_le_of_lt (abv_add abv _ _)
(add_lt_add_of_le_of_lt (this _ (le_refl _)) (h _ ij)),
rw [add_sub, add_comm] at this, simpa }
end
theorem bounded' (f : cau_seq β abv) (x : α) : ∃ r > x, ∀ i, abv (f i) < r :=
let ⟨r, h⟩ := f.bounded in
⟨max r (x+1), lt_of_lt_of_le (lt_add_one _) (le_max_right _ _),
λ i, lt_of_lt_of_le (h i) (le_max_left _ _)⟩
instance : has_add (cau_seq β abv) :=
⟨λ f g, ⟨λ i, (f i + g i : β), λ ε ε0,
let ⟨δ, δ0, Hδ⟩ := rat_add_continuous_lemma abv ε0,
⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in Hδ (H₁ _ ij) (H₂ _ ij)⟩⟩⟩
@[simp] theorem add_apply (f g : cau_seq β abv) (i : ℕ) : (f + g) i = f i + g i := rfl
variable (abv)
/-- The constant Cauchy sequence. -/
def const (x : β) : cau_seq β abv :=
⟨λ i, x, λ ε ε0, ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩⟩
variable {abv}
local notation `const` := const abv
@[simp] theorem const_apply (x : β) (i : ℕ) : (const x : ℕ → β) i = x := rfl
theorem const_inj {x y : β} : (const x : cau_seq β abv) = const y ↔ x = y :=
⟨λ h, congr_arg (λ f:cau_seq β abv, (f:ℕ→β) 0) h, congr_arg _⟩
instance : has_zero (cau_seq β abv) := ⟨const 0⟩
instance : has_one (cau_seq β abv) := ⟨const 1⟩
instance : inhabited (cau_seq β abv) := ⟨0⟩
@[simp] theorem zero_apply (i) : (0 : cau_seq β abv) i = 0 := rfl
@[simp] theorem one_apply (i) : (1 : cau_seq β abv) i = 1 := rfl
theorem const_add (x y : β) : const (x + y) = const x + const y :=
ext $ λ i, rfl
instance : has_mul (cau_seq β abv) :=
⟨λ f g, ⟨λ i, (f i * g i : β), λ ε ε0,
let ⟨F, F0, hF⟩ := f.bounded' 0, ⟨G, G0, hG⟩ := g.bounded' 0,
⟨δ, δ0, Hδ⟩ := rat_mul_continuous_lemma abv ε0,
⟨i, H⟩ := exists_forall_ge_and (f.cauchy₃ δ0) (g.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨H₁, H₂⟩ := H _ (le_refl _) in
Hδ (hF j) (hG i) (H₁ _ ij) (H₂ _ ij)⟩⟩⟩
@[simp] theorem mul_apply (f g : cau_seq β abv) (i : ℕ) : (f * g) i = f i * g i := rfl
theorem const_mul (x y : β) : const (x * y) = const x * const y :=
ext $ λ i, rfl
instance : has_neg (cau_seq β abv) :=
⟨λ f, of_eq (const (-1) * f) (λ x, -f x) (λ i, by simp)⟩
@[simp] theorem neg_apply (f : cau_seq β abv) (i) : (-f) i = -f i := rfl
theorem const_neg (x : β) : const (-x) = -const x :=
ext $ λ i, rfl
instance : ring (cau_seq β abv) :=
by refine {neg := has_neg.neg, add := (+), zero := 0, mul := (*), one := 1, ..};
{ intros, apply ext, simp [mul_add, mul_assoc, add_mul, add_comm, add_left_comm] }
instance {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] :
comm_ring (cau_seq β abv) :=
{ mul_comm := by intros; apply ext; simp [mul_left_comm, mul_comm],
..cau_seq.ring }
theorem const_sub (x y : β) : const (x - y) = const x - const y :=
by rw [sub_eq_add_neg, const_add, const_neg, sub_eq_add_neg]
@[simp] theorem sub_apply (f g : cau_seq β abv) (i : ℕ) : (f - g) i = f i - g i := rfl
/-- `lim_zero f` holds when `f` approaches 0. -/
def lim_zero (f : cau_seq β abv) := ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j) < ε
theorem add_lim_zero {f g : cau_seq β abv}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f + g)
| ε ε0 := (exists_forall_ge_and
(hf _ $ half_pos ε0) (hg _ $ half_pos ε0)).imp $
λ i H j ij, let ⟨H₁, H₂⟩ := H _ ij in
by simpa [add_halves ε] using lt_of_le_of_lt (abv_add abv _ _) (add_lt_add H₁ H₂)
theorem mul_lim_zero_right (f : cau_seq β abv) {g}
(hg : lim_zero g) : lim_zero (f * g)
| ε ε0 := let ⟨F, F0, hF⟩ := f.bounded' 0 in
(hg _ $ div_pos ε0 F0).imp $ λ i H j ij,
by have := mul_lt_mul' (le_of_lt $ hF j) (H _ ij) (abv_nonneg abv _) F0;
rwa [mul_comm F, div_mul_cancel _ (ne_of_gt F0), ← abv_mul abv] at this
theorem mul_lim_zero_left {f} (g : cau_seq β abv)
(hg : lim_zero f) : lim_zero (f * g)
| ε ε0 := let ⟨G, G0, hG⟩ := g.bounded' 0 in
(hg _ $ div_pos ε0 G0).imp $ λ i H j ij,
by have := mul_lt_mul'' (H _ ij) (hG j) (abv_nonneg abv _) (abv_nonneg abv _);
rwa [div_mul_cancel _ (ne_of_gt G0), ← abv_mul abv] at this
theorem neg_lim_zero {f : cau_seq β abv} (hf : lim_zero f) : lim_zero (-f) :=
by rw ← neg_one_mul; exact mul_lim_zero_right _ hf
theorem sub_lim_zero {f g : cau_seq β abv}
(hf : lim_zero f) (hg : lim_zero g) : lim_zero (f - g) :=
add_lim_zero hf (neg_lim_zero hg)
theorem lim_zero_sub_rev {f g : cau_seq β abv} (hfg : lim_zero (f - g)) : lim_zero (g - f) :=
by simpa using neg_lim_zero hfg
theorem zero_lim_zero : lim_zero (0 : cau_seq β abv)
| ε ε0 := ⟨0, λ j ij, by simpa [abv_zero abv] using ε0⟩
theorem const_lim_zero {x : β} : lim_zero (const x) ↔ x = 0 :=
⟨λ H, (abv_eq_zero abv).1 $
eq_of_le_of_forall_le_of_dense (abv_nonneg abv _) $
λ ε ε0, let ⟨i, hi⟩ := H _ ε0 in le_of_lt $ hi _ (le_refl _),
λ e, e.symm ▸ zero_lim_zero⟩
instance equiv : setoid (cau_seq β abv) :=
⟨λ f g, lim_zero (f - g),
⟨λ f, by simp [zero_lim_zero],
λ f g h, by simpa using neg_lim_zero h,
λ f g h fg gh, by simpa [sub_eq_add_neg, add_assoc] using add_lim_zero fg gh⟩⟩
theorem equiv_def₃ {f g : cau_seq β abv} (h : f ≈ g) {ε:α} (ε0 : 0 < ε) :
∃ i, ∀ j ≥ i, ∀ k ≥ j, abv (f k - g j) < ε :=
(exists_forall_ge_and (h _ $ half_pos ε0) (f.cauchy₃ $ half_pos ε0)).imp $
λ i H j ij k jk, let ⟨h₁, h₂⟩ := H _ ij in
by have := lt_of_le_of_lt (abv_add abv (f j - g j) _) (add_lt_add h₁ (h₂ _ jk));
rwa [sub_add_sub_cancel', add_halves] at this
theorem lim_zero_congr {f g : cau_seq β abv} (h : f ≈ g) : lim_zero f ↔ lim_zero g :=
⟨λ l, by simpa using add_lim_zero (setoid.symm h) l,
λ l, by simpa using add_lim_zero h l⟩
theorem abv_pos_of_not_lim_zero {f : cau_seq β abv} (hf : ¬ lim_zero f) :
∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ abv (f j) :=
begin
haveI := classical.prop_decidable,
by_contra nk,
refine hf (λ ε ε0, _),
simp [not_forall] at nk,
cases f.cauchy₃ (half_pos ε0) with i hi,
rcases nk _ (half_pos ε0) i with ⟨j, ij, hj⟩,
refine ⟨j, λ k jk, _⟩,
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi j ij k jk) hj),
rwa [sub_add_cancel, add_halves] at this
end
theorem of_near (f : ℕ → β) (g : cau_seq β abv)
(h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abv (f j - g j) < ε) : is_cau_seq abv f
| ε ε0 :=
let ⟨i, hi⟩ := exists_forall_ge_and
(h _ (half_pos $ half_pos ε0)) (g.cauchy₃ $ half_pos ε0) in
⟨i, λ j ij, begin
cases hi _ (le_refl _) with h₁ h₂, rw abv_sub abv at h₁,
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add (hi _ ij).1 h₁),
have := lt_of_le_of_lt (abv_add abv _ _) (add_lt_add this (h₂ _ ij)),
rwa [add_halves, add_halves, add_right_comm,
sub_add_sub_cancel, sub_add_sub_cancel] at this
end⟩
lemma not_lim_zero_of_not_congr_zero {f : cau_seq _ abv} (hf : ¬ f ≈ 0) : ¬ lim_zero f :=
assume : lim_zero f,
have lim_zero (f - 0), by simpa,
hf this
lemma mul_equiv_zero (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : g * f ≈ 0 :=
have lim_zero (f - 0), from hf,
have lim_zero (g*f), from mul_lim_zero_right _ $ by simpa,
show lim_zero (g*f - 0), by simpa
lemma mul_not_equiv_zero {f g : cau_seq _ abv} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : ¬ (f * g) ≈ 0 :=
assume : lim_zero (f*g - 0),
have hlz : lim_zero (f*g), by simpa,
have hf' : ¬ lim_zero f, by simpa using (show ¬ lim_zero (f - 0), from hf),
have hg' : ¬ lim_zero g, by simpa using (show ¬ lim_zero (g - 0), from hg),
begin
rcases abv_pos_of_not_lim_zero hf' with ⟨a1, ha1, N1, hN1⟩,
rcases abv_pos_of_not_lim_zero hg' with ⟨a2, ha2, N2, hN2⟩,
have : a1 * a2 > 0, from mul_pos ha1 ha2,
cases hlz _ this with N hN,
let i := max N (max N1 N2),
have hN' := hN i (le_max_left _ _),
have hN1' := hN1 i (le_trans (le_max_left _ _) (le_max_right _ _)),
have hN1' := hN2 i (le_trans (le_max_right _ _) (le_max_right _ _)),
apply not_le_of_lt hN',
change _ ≤ abv (_ * _),
rw is_absolute_value.abv_mul abv,
apply mul_le_mul; try { assumption },
{ apply le_of_lt ha2 },
{ apply is_absolute_value.abv_nonneg abv }
end
theorem const_equiv {x y : β} : const x ≈ const y ↔ x = y :=
show lim_zero _ ↔ _, by rw [← const_sub, const_lim_zero, sub_eq_zero]
end ring
section comm_ring
variables {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv]
lemma mul_equiv_zero' (g : cau_seq _ abv) {f : cau_seq _ abv} (hf : f ≈ 0) : f * g ≈ 0 :=
by rw mul_comm; apply mul_equiv_zero _ hf
end comm_ring
section integral_domain
variables {β : Type*} [integral_domain β] (abv : β → α) [is_absolute_value abv]
lemma one_not_equiv_zero : ¬ (const abv 1) ≈ (const abv 0) :=
assume h,
have ∀ ε > 0, ∃ i, ∀ k, k ≥ i → abv (1 - 0) < ε, from h,
have h1 : abv 1 ≤ 0, from le_of_not_gt $
assume h2 : abv 1 > 0,
exists.elim (this _ h2) $ λ i hi,
lt_irrefl (abv 1) $ by simpa using hi _ (le_refl _),
have h2 : abv 1 ≥ 0, from is_absolute_value.abv_nonneg _ _,
have abv 1 = 0, from le_antisymm h1 h2,
have (1 : β) = 0, from (is_absolute_value.abv_eq_zero abv).1 this,
absurd this one_ne_zero
end integral_domain
section field
variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv]
theorem inv_aux {f : cau_seq β abv} (hf : ¬ lim_zero f) :
∀ ε > 0, ∃ i, ∀ j ≥ i, abv ((f j)⁻¹ - (f i)⁻¹) < ε | ε ε0 :=
let ⟨K, K0, HK⟩ := abv_pos_of_not_lim_zero hf,
⟨δ, δ0, Hδ⟩ := rat_inv_continuous_lemma abv ε0 K0,
⟨i, H⟩ := exists_forall_ge_and HK (f.cauchy₃ δ0) in
⟨i, λ j ij, let ⟨iK, H'⟩ := H _ (le_refl _) in Hδ (H _ ij).1 iK (H' _ ij)⟩
def inv (f) (hf : ¬ lim_zero f) : cau_seq β abv := ⟨_, inv_aux hf⟩
@[simp] theorem inv_apply {f : cau_seq β abv} (hf i) : inv f hf i = (f i)⁻¹ := rfl
theorem inv_mul_cancel {f : cau_seq β abv} (hf) : inv f hf * f ≈ 1 :=
λ ε ε0, let ⟨K, K0, i, H⟩ := abv_pos_of_not_lim_zero hf in
⟨i, λ j ij,
by simpa [(abv_pos abv).1 (lt_of_lt_of_le K0 (H _ ij)),
abv_zero abv] using ε0⟩
theorem const_inv {x : β} (hx : x ≠ 0) :
const abv (x⁻¹) = inv (const abv x) (by rwa const_lim_zero) :=
ext (assume n, by simp[inv_apply, const_apply])
end field
section abs
local notation `const` := const abs
/-- The entries of a positive Cauchy sequence eventually have a positive lower bound. -/
def pos (f : cau_seq α abs) : Prop := ∃ K > 0, ∃ i, ∀ j ≥ i, K ≤ f j
theorem not_lim_zero_of_pos {f : cau_seq α abs} : pos f → ¬ lim_zero f
| ⟨F, F0, hF⟩ H :=
let ⟨i, h⟩ := exists_forall_ge_and hF (H _ F0),
⟨h₁, h₂⟩ := h _ (le_refl _) in
not_lt_of_le h₁ (abs_lt.1 h₂).2
theorem const_pos {x : α} : pos (const x) ↔ 0 < x :=
⟨λ ⟨K, K0, i, h⟩, lt_of_lt_of_le K0 (h _ (le_refl _)),
λ h, ⟨x, h, 0, λ j _, le_refl _⟩⟩
theorem add_pos {f g : cau_seq α abs} : pos f → pos g → pos (f + g)
| ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ :=
let ⟨i, h⟩ := exists_forall_ge_and hF hG in
⟨_, _root_.add_pos F0 G0, i,
λ j ij, let ⟨h₁, h₂⟩ := h _ ij in add_le_add h₁ h₂⟩
theorem pos_add_lim_zero {f g : cau_seq α abs} : pos f → lim_zero g → pos (f + g)
| ⟨F, F0, hF⟩ H :=
let ⟨i, h⟩ := exists_forall_ge_and hF (H _ (half_pos F0)) in
⟨_, half_pos F0, i, λ j ij, begin
cases h j ij with h₁ h₂,
have := add_le_add h₁ (le_of_lt (abs_lt.1 h₂).1),
rwa [← sub_eq_add_neg, sub_self_div_two] at this
end⟩
protected theorem mul_pos {f g : cau_seq α abs} : pos f → pos g → pos (f * g)
| ⟨F, F0, hF⟩ ⟨G, G0, hG⟩ :=
let ⟨i, h⟩ := exists_forall_ge_and hF hG in
⟨_, _root_.mul_pos F0 G0, i,
λ j ij, let ⟨h₁, h₂⟩ := h _ ij in
mul_le_mul h₁ h₂ (le_of_lt G0) (le_trans (le_of_lt F0) h₁)⟩
theorem trichotomy (f : cau_seq α abs) : pos f ∨ lim_zero f ∨ pos (-f) :=
begin
cases classical.em (lim_zero f); simp *,
rcases abv_pos_of_not_lim_zero h with ⟨K, K0, hK⟩,
rcases exists_forall_ge_and hK (f.cauchy₃ K0) with ⟨i, hi⟩,
refine (le_total 0 (f i)).imp _ _;
refine (λ h, ⟨K, K0, i, λ j ij, _⟩);
have := (hi _ ij).1;
cases hi _ (le_refl _) with h₁ h₂,
{ rwa abs_of_nonneg at this,
rw abs_of_nonneg h at h₁,
exact (le_add_iff_nonneg_right _).1
(le_trans h₁ $ neg_le_sub_iff_le_add'.1 $
le_of_lt (abs_lt.1 $ h₂ _ ij).1) },
{ rwa abs_of_nonpos at this,
rw abs_of_nonpos h at h₁,
rw [← sub_le_sub_iff_right, zero_sub],
exact le_trans (le_of_lt (abs_lt.1 $ h₂ _ ij).2) h₁ }
end
instance : has_lt (cau_seq α abs) := ⟨λ f g, pos (g - f)⟩
instance : has_le (cau_seq α abs) := ⟨λ f g, f < g ∨ f ≈ g⟩
theorem lt_of_lt_of_eq {f g h : cau_seq α abs}
(fg : f < g) (gh : g ≈ h) : f < h :=
by simpa [sub_eq_add_neg, add_comm, add_left_comm] using pos_add_lim_zero fg (neg_lim_zero gh)
theorem lt_of_eq_of_lt {f g h : cau_seq α abs}
(fg : f ≈ g) (gh : g < h) : f < h :=
by have := pos_add_lim_zero gh (neg_lim_zero fg);
rwa [← sub_eq_add_neg, sub_sub_sub_cancel_right] at this
theorem lt_trans {f g h : cau_seq α abs} (fg : f < g) (gh : g < h) : f < h :=
by simpa [sub_eq_add_neg, add_comm, add_left_comm] using add_pos fg gh
theorem lt_irrefl {f : cau_seq α abs} : ¬ f < f
| h := not_lim_zero_of_pos h (by simp [zero_lim_zero])
lemma le_of_eq_of_le {f g h : cau_seq α abs}
(hfg : f ≈ g) (hgh : g ≤ h) : f ≤ h :=
hgh.elim (or.inl ∘ cau_seq.lt_of_eq_of_lt hfg)
(or.inr ∘ setoid.trans hfg)
lemma le_of_le_of_eq {f g h : cau_seq α abs}
(hfg : f ≤ g) (hgh : g ≈ h) : f ≤ h :=
hfg.elim (λ h, or.inl (cau_seq.lt_of_lt_of_eq h hgh))
(λ h, or.inr (setoid.trans h hgh))
instance : preorder (cau_seq α abs) :=
{ lt := (<),
le := λ f g, f < g ∨ f ≈ g,
le_refl := λ f, or.inr (setoid.refl _),
le_trans := λ f g h fg, match fg with
| or.inl fg, or.inl gh := or.inl $ lt_trans fg gh
| or.inl fg, or.inr gh := or.inl $ lt_of_lt_of_eq fg gh
| or.inr fg, or.inl gh := or.inl $ lt_of_eq_of_lt fg gh
| or.inr fg, or.inr gh := or.inr $ setoid.trans fg gh
end,
lt_iff_le_not_le := λ f g,
⟨λ h, ⟨or.inl h,
not_or (mt (lt_trans h) lt_irrefl) (not_lim_zero_of_pos h)⟩,
λ ⟨h₁, h₂⟩, h₁.resolve_right
(mt (λ h, or.inr (setoid.symm h)) h₂)⟩ }
theorem le_antisymm {f g : cau_seq α abs} (fg : f ≤ g) (gf : g ≤ f) : f ≈ g :=
fg.resolve_left (not_lt_of_le gf)
theorem lt_total (f g : cau_seq α abs) : f < g ∨ f ≈ g ∨ g < f :=
(trichotomy (g - f)).imp_right
(λ h, h.imp (λ h, setoid.symm h) (λ h, by rwa neg_sub at h))
theorem le_total (f g : cau_seq α abs) : f ≤ g ∨ g ≤ f :=
(or.assoc.2 (lt_total f g)).imp_right or.inl
theorem const_lt {x y : α} : const x < const y ↔ x < y :=
show pos _ ↔ _, by rw [← const_sub, const_pos, sub_pos]
theorem const_le {x y : α} : const x ≤ const y ↔ x ≤ y :=
by rw le_iff_lt_or_eq; exact or_congr const_lt const_equiv
lemma le_of_exists {f g : cau_seq α abs}
(h : ∃ i, ∀ j ≥ i, f j ≤ g j) : f ≤ g :=
let ⟨i, hi⟩ := h in
(or.assoc.2 (cau_seq.lt_total f g)).elim
id
(λ hgf, false.elim (let ⟨K, hK0, j, hKj⟩ := hgf in
not_lt_of_ge (hi (max i j) (le_max_left _ _))
(sub_pos.1 (lt_of_lt_of_le hK0 (hKj _ (le_max_right _ _))))))
theorem exists_gt (f : cau_seq α abs) : ∃ a : α, f < const a :=
let ⟨K, H⟩ := f.bounded in
⟨K + 1, 1, zero_lt_one, 0, λ i _, begin
rw [sub_apply, const_apply, le_sub_iff_add_le', add_le_add_iff_right],
exact le_of_lt (abs_lt.1 (H _)).2
end⟩
theorem exists_lt (f : cau_seq α abs) : ∃ a : α, const a < f :=
let ⟨a, h⟩ := (-f).exists_gt in ⟨-a, show pos _,
by rwa [const_neg, sub_neg_eq_add, add_comm, ← sub_neg_eq_add]⟩
end abs
end cau_seq
|
1fc539af64596fb148fffa678fb7b8460d682f42 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/field_theory/abel_ruffini.lean | 3ad2249b55471a5a7f9c22b14b00b72df8ef1e87 | [
"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 | 17,304 | lean | /-
Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning, Patrick Lutz
-/
import group_theory.solvable
import field_theory.polynomial_galois_group
import ring_theory.roots_of_unity
/-!
# The Abel-Ruffini Theorem
This file proves one direction of the Abel-Ruffini theorem, namely that if an element is solvable
by radicals, then its minimal polynomial has solvable Galois group.
## Main definitions
* `SBF F E` : the intermediate field of solvable-by-radicals elements
## Main results
* `solvable_gal_of_solvable_by_rad` : the minimal polynomial of an element of `SBF F E` has
solvable Galois group
-/
noncomputable theory
open_locale classical
open polynomial intermediate_field
section abel_ruffini
variables {F : Type*} [field F] {E : Type*} [field E] [algebra F E]
lemma gal_zero_is_solvable : is_solvable (0 : polynomial F).gal :=
by apply_instance
lemma gal_one_is_solvable : is_solvable (1 : polynomial F).gal :=
by apply_instance
lemma gal_C_is_solvable (x : F) : is_solvable (C x).gal :=
by apply_instance
lemma gal_X_is_solvable : is_solvable (X : polynomial F).gal :=
by apply_instance
lemma gal_X_sub_C_is_solvable (x : F) : is_solvable (X - C x).gal :=
by apply_instance
lemma gal_X_pow_is_solvable (n : ℕ) : is_solvable (X ^ n : polynomial F).gal :=
by apply_instance
lemma gal_mul_is_solvable {p q : polynomial F}
(hp : is_solvable p.gal) (hq : is_solvable q.gal) : is_solvable (p * q).gal :=
solvable_of_solvable_injective (gal.restrict_prod_injective p q)
lemma gal_prod_is_solvable {s : multiset (polynomial F)}
(hs : ∀ p ∈ s, is_solvable (gal p)) : is_solvable s.prod.gal :=
begin
apply multiset.induction_on' s,
{ exact gal_one_is_solvable },
{ intros p t hps hts ht,
rw [multiset.insert_eq_cons, multiset.prod_cons],
exact gal_mul_is_solvable (hs p hps) ht },
end
lemma gal_is_solvable_of_splits {p q : polynomial F}
(hpq : fact (p.splits (algebra_map F q.splitting_field))) (hq : is_solvable q.gal) :
is_solvable p.gal :=
begin
haveI : is_solvable (q.splitting_field ≃ₐ[F] q.splitting_field) := hq,
exact solvable_of_surjective (alg_equiv.restrict_normal_hom_surjective q.splitting_field),
end
lemma gal_is_solvable_tower (p q : polynomial F)
(hpq : p.splits (algebra_map F q.splitting_field))
(hp : is_solvable p.gal)
(hq : is_solvable (q.map (algebra_map F p.splitting_field)).gal) :
is_solvable q.gal :=
begin
let K := p.splitting_field,
let L := q.splitting_field,
haveI : fact (p.splits (algebra_map F L)) := ⟨hpq⟩,
let ϕ : (L ≃ₐ[K] L) ≃* (q.map (algebra_map F K)).gal :=
(is_splitting_field.alg_equiv L (q.map (algebra_map F K))).aut_congr,
have ϕ_inj : function.injective ϕ.to_monoid_hom := ϕ.injective,
haveI : is_solvable (K ≃ₐ[F] K) := hp,
haveI : is_solvable (L ≃ₐ[K] L) := solvable_of_solvable_injective ϕ_inj,
exact is_solvable_of_is_scalar_tower F p.splitting_field q.splitting_field,
end
section gal_X_pow_sub_C
lemma gal_X_pow_sub_one_is_solvable (n : ℕ) : is_solvable (X ^ n - 1 : polynomial F).gal :=
begin
by_cases hn : n = 0,
{ rw [hn, pow_zero, sub_self],
exact gal_zero_is_solvable },
have hn' : 0 < n := pos_iff_ne_zero.mpr hn,
have hn'' : (X ^ n - 1 : polynomial F) ≠ 0 :=
λ h, one_ne_zero ((leading_coeff_X_pow_sub_one hn').symm.trans (congr_arg leading_coeff h)),
apply is_solvable_of_comm,
intros σ τ,
ext a ha,
rw [mem_root_set hn'', alg_hom.map_sub, aeval_X_pow, aeval_one, sub_eq_zero] at ha,
have key : ∀ σ : (X ^ n - 1 : polynomial F).gal, ∃ m : ℕ, σ a = a ^ m,
{ intro σ,
obtain ⟨m, hm⟩ := σ.to_alg_hom.to_ring_hom.map_root_of_unity_eq_pow_self
⟨is_unit.unit (is_unit_of_pow_eq_one a n ha hn'),
by { ext, rwa [units.coe_pow, is_unit.unit_spec, subtype.coe_mk n hn'] }⟩,
use m,
convert hm,
all_goals { exact (is_unit.unit_spec _).symm } },
obtain ⟨c, hc⟩ := key σ,
obtain ⟨d, hd⟩ := key τ,
rw [σ.mul_apply, τ.mul_apply, hc, τ.map_pow, hd, σ.map_pow, hc, ←pow_mul, pow_mul'],
end
lemma gal_X_pow_sub_C_is_solvable_aux (n : ℕ) (a : F)
(h : (X ^ n - 1 : polynomial F).splits (ring_hom.id F)) : is_solvable (X ^ n - C a).gal :=
begin
by_cases ha : a = 0,
{ rw [ha, C_0, sub_zero],
exact gal_X_pow_is_solvable n },
have ha' : algebra_map F (X ^ n - C a).splitting_field a ≠ 0 :=
mt ((ring_hom.injective_iff _).mp (ring_hom.injective _) a) ha,
by_cases hn : n = 0,
{ rw [hn, pow_zero, ←C_1, ←C_sub],
exact gal_C_is_solvable (1 - a) },
have hn' : 0 < n := pos_iff_ne_zero.mpr hn,
have hn'' : X ^ n - C a ≠ 0 :=
λ h, one_ne_zero ((leading_coeff_X_pow_sub_C hn').symm.trans (congr_arg leading_coeff h)),
have hn''' : (X ^ n - 1 : polynomial F) ≠ 0 :=
λ h, one_ne_zero ((leading_coeff_X_pow_sub_one hn').symm.trans (congr_arg leading_coeff h)),
have mem_range : ∀ {c}, c ^ n = 1 → ∃ d, algebra_map F (X ^ n - C a).splitting_field d = c :=
λ c hc, ring_hom.mem_range.mp (minpoly.mem_range_of_degree_eq_one F c (or.resolve_left h hn'''
(minpoly.irreducible ((splitting_field.normal (X ^ n - C a)).is_integral c)) (minpoly.dvd F c
(by rwa [map_id, alg_hom.map_sub, sub_eq_zero, aeval_X_pow, aeval_one])))),
apply is_solvable_of_comm,
intros σ τ,
ext b hb,
rw [mem_root_set hn'', alg_hom.map_sub, aeval_X_pow, aeval_C, sub_eq_zero] at hb,
have hb' : b ≠ 0,
{ intro hb',
rw [hb', zero_pow hn'] at hb,
exact ha' hb.symm },
have key : ∀ σ : (X ^ n - C a).gal, ∃ c, σ b = b * algebra_map F _ c,
{ intro σ,
have key : (σ b / b) ^ n = 1 := by rw [div_pow, ←σ.map_pow, hb, σ.commutes, div_self ha'],
obtain ⟨c, hc⟩ := mem_range key,
use c,
rw [hc, mul_div_cancel' (σ b) hb'] },
obtain ⟨c, hc⟩ := key σ,
obtain ⟨d, hd⟩ := key τ,
rw [σ.mul_apply, τ.mul_apply, hc, τ.map_mul, τ.commutes, hd, σ.map_mul, σ.commutes, hc],
rw [mul_assoc, mul_assoc, mul_right_inj' hb', mul_comm],
end
lemma splits_X_pow_sub_one_of_X_pow_sub_C {F : Type*} [field F] {E : Type*} [field E]
(i : F →+* E) (n : ℕ) {a : F} (ha : a ≠ 0) (h : (X ^ n - C a).splits i) : (X ^ n - 1).splits i :=
begin
have ha' : i a ≠ 0 := mt (i.injective_iff.mp (i.injective) a) ha,
by_cases hn : n = 0,
{ rw [hn, pow_zero, sub_self],
exact splits_zero i },
have hn' : 0 < n := pos_iff_ne_zero.mpr hn,
have hn'' : (X ^ n - C a).degree ≠ 0 :=
ne_of_eq_of_ne (degree_X_pow_sub_C hn' a) (mt with_bot.coe_eq_coe.mp hn),
obtain ⟨b, hb⟩ := exists_root_of_splits i h hn'',
rw [eval₂_sub, eval₂_X_pow, eval₂_C, sub_eq_zero] at hb,
have hb' : b ≠ 0,
{ intro hb',
rw [hb', zero_pow hn'] at hb,
exact ha' hb.symm },
let s := ((X ^ n - C a).map i).roots,
have hs : _ = _ * (s.map _).prod := eq_prod_roots_of_splits h,
rw [leading_coeff_X_pow_sub_C hn', ring_hom.map_one, C_1, one_mul] at hs,
have hs' : s.card = n := (nat_degree_eq_card_roots h).symm.trans nat_degree_X_pow_sub_C,
apply @splits_of_exists_multiset F E _ _ i (X ^ n - 1) (s.map (λ c : E, c / b)),
rw [leading_coeff_X_pow_sub_one hn', ring_hom.map_one, C_1, one_mul, multiset.map_map],
have C_mul_C : (C (i a⁻¹)) * (C (i a)) = 1,
{ rw [←C_mul, ←i.map_mul, inv_mul_cancel ha, i.map_one, C_1] },
have key1 : (X ^ n - 1).map i = C (i a⁻¹) * ((X ^ n - C a).map i).comp (C b * X),
{ rw [map_sub, map_sub, map_pow, map_X, map_C, map_one, sub_comp, pow_comp, X_comp, C_comp,
mul_pow, ←C_pow, hb, mul_sub, ←mul_assoc, C_mul_C, one_mul] },
have key2 : (λ q : polynomial E, q.comp (C b * X)) ∘ (λ c : E, X - C c) =
(λ c : E, C b * (X - C (c / b))),
{ ext1 c,
change (X - C c).comp (C b * X) = C b * (X - C (c / b)),
rw [sub_comp, X_comp, C_comp, mul_sub, ←C_mul, mul_div_cancel' c hb'] },
rw [key1, hs, prod_comp, multiset.map_map, key2, multiset.prod_map_mul, multiset.map_const,
multiset.prod_repeat, hs', ←C_pow, hb, ←mul_assoc, C_mul_C, one_mul],
all_goals { exact field.to_nontrivial F },
end
lemma gal_X_pow_sub_C_is_solvable (n : ℕ) (x : F) : is_solvable (X ^ n - C x).gal :=
begin
by_cases hx : x = 0,
{ rw [hx, C_0, sub_zero],
exact gal_X_pow_is_solvable n },
apply gal_is_solvable_tower (X ^ n - 1) (X ^ n - C x),
{ exact splits_X_pow_sub_one_of_X_pow_sub_C _ n hx (splitting_field.splits _) },
{ exact gal_X_pow_sub_one_is_solvable n },
{ rw [map_sub, map_pow, map_X, map_C],
apply gal_X_pow_sub_C_is_solvable_aux,
have key := splitting_field.splits (X ^ n - 1 : polynomial F),
rwa [←splits_id_iff_splits, map_sub, map_pow, map_X, map_one] at key },
end
end gal_X_pow_sub_C
variables (F)
/-- Inductive definition of solvable by radicals -/
inductive is_solvable_by_rad : E → Prop
| base (a : F) : is_solvable_by_rad (algebra_map F E a)
| add (a b : E) : is_solvable_by_rad a → is_solvable_by_rad b → is_solvable_by_rad (a + b)
| neg (α : E) : is_solvable_by_rad α → is_solvable_by_rad (-α)
| mul (α β : E) : is_solvable_by_rad α → is_solvable_by_rad β → is_solvable_by_rad (α * β)
| inv (α : E) : is_solvable_by_rad α → is_solvable_by_rad α⁻¹
| rad (α : E) (n : ℕ) (hn : n ≠ 0) : is_solvable_by_rad (α^n) → is_solvable_by_rad α
variables (E)
/-- The intermediate field of solvable-by-radicals elements -/
def solvable_by_rad : intermediate_field F E :=
{ carrier := is_solvable_by_rad F,
zero_mem' := by { convert is_solvable_by_rad.base (0 : F), rw ring_hom.map_zero },
add_mem' := is_solvable_by_rad.add,
neg_mem' := is_solvable_by_rad.neg,
one_mem' := by { convert is_solvable_by_rad.base (1 : F), rw ring_hom.map_one },
mul_mem' := is_solvable_by_rad.mul,
inv_mem' := is_solvable_by_rad.inv,
algebra_map_mem' := is_solvable_by_rad.base }
namespace solvable_by_rad
variables {F} {E} {α : E}
lemma induction (P : solvable_by_rad F E → Prop)
(base : ∀ α : F, P (algebra_map F (solvable_by_rad F E) α))
(add : ∀ α β : solvable_by_rad F E, P α → P β → P (α + β))
(neg : ∀ α : solvable_by_rad F E, P α → P (-α))
(mul : ∀ α β : solvable_by_rad F E, P α → P β → P (α * β))
(inv : ∀ α : solvable_by_rad F E, P α → P α⁻¹)
(rad : ∀ α : solvable_by_rad F E, ∀ n : ℕ, n ≠ 0 → P (α^n) → P α)
(α : solvable_by_rad F E) : P α :=
begin
revert α,
suffices : ∀ (α : E), is_solvable_by_rad F α → (∃ β : solvable_by_rad F E, ↑β = α ∧ P β),
{ intro α,
obtain ⟨α₀, hα₀, Pα⟩ := this α (subtype.mem α),
convert Pα,
exact subtype.ext hα₀.symm },
apply is_solvable_by_rad.rec,
{ exact λ α, ⟨algebra_map F (solvable_by_rad F E) α, rfl, base α⟩ },
{ intros α β hα hβ Pα Pβ,
obtain ⟨⟨α₀, hα₀, Pα⟩, β₀, hβ₀, Pβ⟩ := ⟨Pα, Pβ⟩,
exact ⟨α₀ + β₀, by {rw [←hα₀, ←hβ₀], refl }, add α₀ β₀ Pα Pβ⟩ },
{ intros α hα Pα,
obtain ⟨α₀, hα₀, Pα⟩ := Pα,
exact ⟨-α₀, by {rw ←hα₀, refl }, neg α₀ Pα⟩ },
{ intros α β hα hβ Pα Pβ,
obtain ⟨⟨α₀, hα₀, Pα⟩, β₀, hβ₀, Pβ⟩ := ⟨Pα, Pβ⟩,
exact ⟨α₀ * β₀, by {rw [←hα₀, ←hβ₀], refl }, mul α₀ β₀ Pα Pβ⟩ },
{ intros α hα Pα,
obtain ⟨α₀, hα₀, Pα⟩ := Pα,
exact ⟨α₀⁻¹, by {rw ←hα₀, refl }, inv α₀ Pα⟩ },
{ intros α n hn hα Pα,
obtain ⟨α₀, hα₀, Pα⟩ := Pα,
refine ⟨⟨α, is_solvable_by_rad.rad α n hn hα⟩, rfl, rad _ n hn _⟩,
convert Pα,
exact subtype.ext (eq.trans ((solvable_by_rad F E).coe_pow _ n) hα₀.symm) }
end
theorem is_integral (α : solvable_by_rad F E) : is_integral F α :=
begin
revert α,
apply solvable_by_rad.induction,
{ exact λ _, is_integral_algebra_map },
{ exact λ _ _, is_integral_add },
{ exact λ _, is_integral_neg },
{ exact λ _ _, is_integral_mul },
{ exact λ α hα, subalgebra.inv_mem_of_algebraic (integral_closure F (solvable_by_rad F E))
(show is_algebraic F ↑(⟨α, hα⟩ : integral_closure F (solvable_by_rad F E)),
by exact (is_algebraic_iff_is_integral F).mpr hα) },
{ intros α n hn hα,
obtain ⟨p, h1, h2⟩ := (is_algebraic_iff_is_integral F).mpr hα,
refine (is_algebraic_iff_is_integral F).mp ⟨p.comp (X ^ n),
⟨λ h, h1 (leading_coeff_eq_zero.mp _), by rw [aeval_comp, aeval_X_pow, h2]⟩⟩,
rwa [←leading_coeff_eq_zero, leading_coeff_comp, leading_coeff_X_pow, one_pow, mul_one] at h,
rwa nat_degree_X_pow }
end
/-- The statement to be proved inductively -/
def P (α : solvable_by_rad F E) : Prop := is_solvable (minpoly F α).gal
/-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/
lemma induction3 {α : solvable_by_rad F E} {n : ℕ} (hn : n ≠ 0) (hα : P (α ^ n)) : P α :=
begin
let p := minpoly F (α ^ n),
have hp : p.comp (X ^ n) ≠ 0,
{ intro h,
cases (comp_eq_zero_iff.mp h) with h' h',
{ exact minpoly.ne_zero (is_integral (α ^ n)) h' },
{ exact hn (by rw [←nat_degree_C _, ←h'.2, nat_degree_X_pow]) } },
apply gal_is_solvable_of_splits,
{ exact ⟨splits_of_splits_of_dvd _ hp (splitting_field.splits (p.comp (X ^ n)))
(minpoly.dvd F α (by rw [aeval_comp, aeval_X_pow, minpoly.aeval]))⟩ },
{ refine gal_is_solvable_tower p (p.comp (X ^ n)) _ hα _,
{ exact gal.splits_in_splitting_field_of_comp _ _ (by rwa [nat_degree_X_pow]) },
{ obtain ⟨s, hs⟩ := exists_multiset_of_splits _ (splitting_field.splits p),
rw [map_comp, map_pow, map_X, hs, mul_comp, C_comp],
apply gal_mul_is_solvable (gal_C_is_solvable _),
rw prod_comp,
apply gal_prod_is_solvable,
intros q hq,
rw multiset.mem_map at hq,
obtain ⟨q, hq, rfl⟩ := hq,
rw multiset.mem_map at hq,
obtain ⟨q, hq, rfl⟩ := hq,
rw [sub_comp, X_comp, C_comp],
exact gal_X_pow_sub_C_is_solvable n q } },
end
/-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/
lemma induction2 {α β γ : solvable_by_rad F E} (hγ : γ ∈ F⟮α, β⟯) (hα : P α) (hβ : P β) : P γ :=
begin
let p := (minpoly F α),
let q := (minpoly F β),
have hpq := polynomial.splits_of_splits_mul _ (mul_ne_zero (minpoly.ne_zero (is_integral α))
(minpoly.ne_zero (is_integral β))) (splitting_field.splits (p * q)),
let f : F⟮α, β⟯ →ₐ[F] (p * q).splitting_field := classical.choice (alg_hom_mk_adjoin_splits
begin
intros x hx,
cases hx,
rw hx,
exact ⟨is_integral α, hpq.1⟩,
cases hx,
exact ⟨is_integral β, hpq.2⟩,
end),
have key : minpoly F γ = minpoly F (f ⟨γ, hγ⟩) := minpoly.unique'
(minpoly.irreducible (is_integral γ)) begin
suffices : aeval (⟨γ, hγ⟩ : F ⟮α, β⟯) (minpoly F γ) = 0,
{ rw [aeval_alg_hom_apply, this, alg_hom.map_zero] },
apply (algebra_map F⟮α, β⟯ (solvable_by_rad F E)).injective,
rw [ring_hom.map_zero, is_scalar_tower.algebra_map_aeval],
exact minpoly.aeval F γ,
end (minpoly.monic (is_integral γ)),
rw [P, key],
exact gal_is_solvable_of_splits ⟨normal.splits (splitting_field.normal _) _⟩
(gal_mul_is_solvable hα hβ),
end
/-- An auxiliary induction lemma, which is generalized by `solvable_by_rad.is_solvable`. -/
lemma induction1 {α β : solvable_by_rad F E} (hβ : β ∈ F⟮α⟯) (hα : P α) : P β :=
induction2 (adjoin.mono F _ _ (ge_of_eq (set.pair_eq_singleton α)) hβ) hα hα
theorem is_solvable (α : solvable_by_rad F E) :
is_solvable (minpoly F α).gal :=
begin
revert α,
apply solvable_by_rad.induction,
{ exact λ α, by { rw minpoly.eq_X_sub_C, exact gal_X_sub_C_is_solvable α } },
{ exact λ α β, induction2 (add_mem _ (subset_adjoin F _ (set.mem_insert α _))
(subset_adjoin F _ (set.mem_insert_of_mem α (set.mem_singleton β)))) },
{ exact λ α, induction1 (neg_mem _ (mem_adjoin_simple_self F α)) },
{ exact λ α β, induction2 (mul_mem _ (subset_adjoin F _ (set.mem_insert α _))
(subset_adjoin F _ (set.mem_insert_of_mem α (set.mem_singleton β)))) },
{ exact λ α, induction1 (inv_mem _ (mem_adjoin_simple_self F α)) },
{ exact λ α n, induction3 },
end
/-- **Abel-Ruffini Theorem** (one direction): An irreducible polynomial with an
`is_solvable_by_rad` root has solvable Galois group -/
lemma is_solvable' {α : E} {q : polynomial F} (q_irred : irreducible q)
(q_aeval : aeval α q = 0) (hα : is_solvable_by_rad F α) :
_root_.is_solvable q.gal :=
begin
haveI : _root_.is_solvable (q * C q.leading_coeff⁻¹).gal := by
{ rw [minpoly.unique'' q_irred q_aeval,
←show minpoly F (⟨α, hα⟩ : solvable_by_rad F E) = minpoly F α,
from minpoly.eq_of_algebra_map_eq (ring_hom.injective _) (is_integral ⟨α, hα⟩) rfl],
exact is_solvable ⟨α, hα⟩ },
refine solvable_of_surjective (gal.restrict_dvd_surjective ⟨C q.leading_coeff⁻¹, rfl⟩ _),
rw [mul_ne_zero_iff, ne, ne, C_eq_zero, inv_eq_zero],
exact ⟨q_irred.ne_zero, leading_coeff_ne_zero.mpr q_irred.ne_zero⟩,
end
end solvable_by_rad
end abel_ruffini
|
fb3694af79fc9e75d74e39dff091d56edcf306a5 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/calc_heq_symm.lean | ab71da57e5b76f0fff837cde9c9909b2d5ff31c3 | [
"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 | 313 | lean | theorem tst {A B C D : Type} {a₁ a₂ : A} {b : B} {c : C} {d : D}
(H₀ : a₁ = a₂) (H₁ : a₂ == b) (H₂ : b == c) (H₃ : c == d) : d == a₁ :=
calc d == c : heq.symm H₃
... == b : heq.symm H₂
... == a₂ : heq.symm H₁
... = a₁ : eq.symm H₀
print definition tst
|
42439815fd20f5521c768731c8fabb9856212834 | 4727251e0cd73359b15b664c3170e5d754078599 | /test/instance_diamonds.lean | 981910ae27a2d9e593c11f9e15ab39f1fe24e35e | [
"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,678 | 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.module.pi
import data.polynomial.basic
import group_theory.group_action.prod
import group_theory.group_action.units
import data.complex.module
import ring_theory.algebraic
/-! # Tests that instances do not form diamonds -/
/-! ## Scalar action instances -/
section has_scalar
open_locale polynomial
example :
(sub_neg_monoid.has_scalar_int : has_scalar ℤ ℂ) = (complex.has_scalar : has_scalar ℤ ℂ) :=
rfl
example : restrict_scalars.module ℝ ℂ ℂ = complex.module := rfl
example : restrict_scalars.algebra ℝ ℂ ℂ = complex.algebra := rfl
example (α β : Type*) [add_monoid α] [add_monoid β] :
(prod.has_scalar : has_scalar ℕ (α × β)) = add_monoid.has_scalar_nat := rfl
example (α β : Type*) [sub_neg_monoid α] [sub_neg_monoid β] :
(prod.has_scalar : has_scalar ℤ (α × β)) = sub_neg_monoid.has_scalar_int := rfl
example (α : Type*) (β : α → Type*) [Π a, add_monoid (β a)] :
(pi.has_scalar : has_scalar ℕ (Π a, β a)) = add_monoid.has_scalar_nat := rfl
example (α : Type*) (β : α → Type*) [Π a, sub_neg_monoid (β a)] :
(pi.has_scalar : has_scalar ℤ (Π a, β a)) = sub_neg_monoid.has_scalar_int := rfl
section units
example (α : Type*) [monoid α] :
(units.mul_action : mul_action αˣ (α × α)) = prod.mul_action := rfl
example (R α : Type*) (β : α → Type*) [monoid R] [Π i, mul_action R (β i)] :
(units.mul_action : mul_action Rˣ (Π i, β i)) = pi.mul_action _ := rfl
example (R α : Type*) (β : α → Type*) [monoid R] [semiring α] [distrib_mul_action R α] :
(units.distrib_mul_action : distrib_mul_action Rˣ α[X]) =
polynomial.distrib_mul_action :=
rfl
/-!
TODO: https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/units.2Emul_action'.20diamond/near/246402813
```lean
example {α : Type*} [comm_monoid α] :
(units.mul_action' : mul_action αˣ αˣ) = monoid.to_mul_action _ :=
rfl -- fails
```
-/
end units
end has_scalar
/-! ## `with_top` (Type with point at infinity) instances -/
section with_top
example (R : Type*) [h : ordered_semiring R] :
(@with_top.add_comm_monoid R
(@non_unital_non_assoc_semiring.to_add_comm_monoid R
(@non_assoc_semiring.to_non_unital_non_assoc_semiring R
(@semiring.to_non_assoc_semiring R
(@ordered_semiring.to_semiring R h)))))
=
(@ordered_add_comm_monoid.to_add_comm_monoid (with_top R)
(@with_top.ordered_add_comm_monoid R
(@ordered_cancel_add_comm_monoid.to_ordered_add_comm_monoid R
(@ordered_semiring.to_ordered_cancel_add_comm_monoid R h)))) :=
rfl
end with_top
/-! ## `multiplicative` instances -/
section multiplicative
example :
@monoid.to_mul_one_class (multiplicative ℕ) (comm_monoid.to_monoid _) =
multiplicative.mul_one_class :=
rfl
-- `dunfold` can still break unification, but it's better to have `dunfold` break it than have the
-- above example fail.
example :
@monoid.to_mul_one_class (multiplicative ℕ) (comm_monoid.to_monoid _) =
multiplicative.mul_one_class :=
begin
dunfold has_one.one multiplicative.mul_one_class,
success_if_fail { refl, },
ext,
refl
end
end multiplicative
/-! ## `finsupp` instances-/
section finsupp
open finsupp
/-- `finsupp.comap_has_scalar` can form a non-equal diamond with `finsupp.has_scalar` -/
example {k : Type*} [semiring k] [nontrivial k] :
(finsupp.comap_has_scalar : has_scalar k (k →₀ k)) ≠ finsupp.has_scalar :=
begin
obtain ⟨u : k, hu⟩ := exists_ne (1 : k),
intro h,
simp only [has_scalar.ext_iff, function.funext_iff, finsupp.ext_iff] at h,
replace h := h u (finsupp.single 1 1) u,
classical,
rw [comap_smul_single, smul_apply, smul_eq_mul, mul_one, single_eq_same,
smul_eq_mul, single_eq_of_ne hu.symm, mul_zero] at h,
exact one_ne_zero h,
end
/-- `finsupp.comap_has_scalar` can form a non-equal diamond with `finsupp.has_scalar` even when
the domain is a group. -/
example {k : Type*} [semiring k] [nontrivial kˣ] :
(finsupp.comap_has_scalar : has_scalar kˣ (kˣ →₀ k)) ≠ finsupp.has_scalar :=
begin
obtain ⟨u : kˣ, hu⟩ := exists_ne (1 : kˣ),
haveI : nontrivial k := ⟨⟨u, 1, units.ext.ne hu⟩⟩,
intro h,
simp only [has_scalar.ext_iff, function.funext_iff, finsupp.ext_iff] at h,
replace h := h u (finsupp.single 1 1) u,
classical,
rw [comap_smul_single, smul_apply, units.smul_def, smul_eq_mul, mul_one, single_eq_same,
smul_eq_mul, single_eq_of_ne hu.symm, mul_zero] at h,
exact one_ne_zero h,
end
end finsupp
/-! ## `polynomial` instances -/
section polynomial
variables (R A : Type*)
open_locale polynomial
open polynomial
/-- `polynomial.has_scalar_pi` forms a diamond with `pi.has_scalar`. -/
example [semiring R] [nontrivial R] :
polynomial.has_scalar_pi _ _ ≠ (pi.has_scalar : has_scalar R[X] (R → R[X])) :=
begin
intro h,
simp_rw [has_scalar.ext_iff, function.funext_iff, polynomial.ext_iff] at h,
simpa using h X 1 1 0,
end
/-- `polynomial.has_scalar_pi'` forms a diamond with `pi.has_scalar`. -/
example [comm_semiring R] [nontrivial R] :
polynomial.has_scalar_pi' _ _ _ ≠ (pi.has_scalar : has_scalar R[X] (R → R[X])) :=
begin
intro h,
simp_rw [has_scalar.ext_iff, function.funext_iff, polynomial.ext_iff] at h,
simpa using h X 1 1 0,
end
/-- `polynomial.has_scalar_pi'` is consistent with `polynomial.has_scalar_pi`. -/
example [comm_semiring R] [nontrivial R] :
polynomial.has_scalar_pi' _ _ _ = (polynomial.has_scalar_pi _ _ : has_scalar R[X] (R → R[X])) :=
rfl
end polynomial
|
1892900bad1f5895cf3315ea414519da626a3cf1 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/analysis/inner_product_space/pi_L2.lean | ccad358197cccab570e034cc525106c0dc7af0e0 | [
"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 | 40,084 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Sébastien Gouëzel, Heather Macbeth
-/
import analysis.inner_product_space.projection
import analysis.normed_space.pi_Lp
import linear_algebra.finite_dimensional
import linear_algebra.unitary_group
/-!
# `L²` inner product space structure on finite products of inner product spaces
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
The `L²` norm on a finite product of inner product spaces is compatible with an inner product
$$
\langle x, y\rangle = \sum \langle x_i, y_i \rangle.
$$
This is recorded in this file as an inner product space instance on `pi_Lp 2`.
This file develops the notion of a finite dimensional Hilbert space over `𝕜 = ℂ, ℝ`, referred to as
`E`. We define an `orthonormal_basis 𝕜 ι E` as a linear isometric equivalence
between `E` and `euclidean_space 𝕜 ι`. Then `std_orthonormal_basis` shows that such an equivalence
always exists if `E` is finite dimensional. We provide language for converting between a basis
that is orthonormal and an orthonormal basis (e.g. `basis.to_orthonormal_basis`). We show that
orthonormal bases for each summand in a direct sum of spaces can be combined into an orthonormal
basis for the the whole sum in `direct_sum.submodule_is_internal.subordinate_orthonormal_basis`. In
the last section, various properties of matrices are explored.
## Main definitions
- `euclidean_space 𝕜 n`: defined to be `pi_Lp 2 (n → 𝕜)` for any `fintype n`, i.e., the space
from functions to `n` to `𝕜` with the `L²` norm. We register several instances on it (notably
that it is a finite-dimensional inner product space).
- `orthonormal_basis 𝕜 ι`: defined to be an isometry to Euclidean space from a given
finite-dimensional innner product space, `E ≃ₗᵢ[𝕜] euclidean_space 𝕜 ι`.
- `basis.to_orthonormal_basis`: constructs an `orthonormal_basis` for a finite-dimensional
Euclidean space from a `basis` which is `orthonormal`.
- `orthonormal.exists_orthonormal_basis_extension`: provides an existential result of an
`orthonormal_basis` extending a given orthonormal set
- `exists_orthonormal_basis`: provides an orthonormal basis on a finite dimensional vector space
- `std_orthonormal_basis`: provides an arbitrarily-chosen `orthonormal_basis` of a given finite
dimensional inner product space
For consequences in infinite dimension (Hilbert bases, etc.), see the file
`analysis.inner_product_space.l2_space`.
-/
open real set filter is_R_or_C submodule function
open_locale big_operators uniformity topology nnreal ennreal complex_conjugate direct_sum
noncomputable theory
variables {ι : Type*} {ι' : Type*}
variables {𝕜 : Type*} [is_R_or_C 𝕜]
variables {E : Type*} [normed_add_comm_group E] [inner_product_space 𝕜 E]
variables {E' : Type*} [normed_add_comm_group E'] [inner_product_space 𝕜 E']
variables {F : Type*} [normed_add_comm_group F] [inner_product_space ℝ F]
variables {F' : Type*} [normed_add_comm_group F'] [inner_product_space ℝ F']
local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y
/-
If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space,
then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm,
we use instead `pi_Lp 2 f` for the product space, which is endowed with the `L^2` norm.
-/
instance pi_Lp.inner_product_space {ι : Type*} [fintype ι] (f : ι → Type*)
[Π i, normed_add_comm_group (f i)] [Π i, inner_product_space 𝕜 (f i)] :
inner_product_space 𝕜 (pi_Lp 2 f) :=
{ inner := λ x y, ∑ i, inner (x i) (y i),
norm_sq_eq_inner := λ x,
by simp only [pi_Lp.norm_sq_eq_of_L2, add_monoid_hom.map_sum, ← norm_sq_eq_inner, one_div],
conj_symm :=
begin
intros x y,
unfold inner,
rw ring_hom.map_sum,
apply finset.sum_congr rfl,
rintros z -,
apply inner_conj_symm,
end,
add_left := λ x y z,
show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i),
by simp only [inner_add_left, finset.sum_add_distrib],
smul_left := λ x y r,
show ∑ (i : ι), inner (r • x i) (y i) = (conj r) * ∑ i, inner (x i) (y i),
by simp only [finset.mul_sum, inner_smul_left] }
@[simp] lemma pi_Lp.inner_apply {ι : Type*} [fintype ι] {f : ι → Type*}
[Π i, normed_add_comm_group (f i)] [Π i, inner_product_space 𝕜 (f i)] (x y : pi_Lp 2 f) :
⟪x, y⟫ = ∑ i, ⟪x i, y i⟫ :=
rfl
/-- The standard real/complex Euclidean space, functions on a finite type. For an `n`-dimensional
space use `euclidean_space 𝕜 (fin n)`. -/
@[reducible, nolint unused_arguments]
def euclidean_space (𝕜 : Type*) [is_R_or_C 𝕜]
(n : Type*) [fintype n] : Type* := pi_Lp 2 (λ (i : n), 𝕜)
lemma euclidean_space.nnnorm_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n]
(x : euclidean_space 𝕜 n) : ‖x‖₊ = nnreal.sqrt (∑ i, ‖x i‖₊ ^ 2) :=
pi_Lp.nnnorm_eq_of_L2 x
lemma euclidean_space.norm_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n]
(x : euclidean_space 𝕜 n) : ‖x‖ = real.sqrt (∑ i, ‖x i‖ ^ 2) :=
by simpa only [real.coe_sqrt, nnreal.coe_sum] using congr_arg (coe : ℝ≥0 → ℝ) x.nnnorm_eq
lemma euclidean_space.dist_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n]
(x y : euclidean_space 𝕜 n) : dist x y = (∑ i, dist (x i) (y i) ^ 2).sqrt :=
(pi_Lp.dist_eq_of_L2 x y : _)
lemma euclidean_space.nndist_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n]
(x y : euclidean_space 𝕜 n) : nndist x y = (∑ i, nndist (x i) (y i) ^ 2).sqrt :=
(pi_Lp.nndist_eq_of_L2 x y : _)
lemma euclidean_space.edist_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n]
(x y : euclidean_space 𝕜 n) : edist x y = (∑ i, edist (x i) (y i) ^ 2) ^ (1 / 2 : ℝ) :=
(pi_Lp.edist_eq_of_L2 x y : _)
variables [fintype ι]
section
local attribute [reducible] pi_Lp
instance : finite_dimensional 𝕜 (euclidean_space 𝕜 ι) := by apply_instance
instance : inner_product_space 𝕜 (euclidean_space 𝕜 ι) := by apply_instance
@[simp] lemma finrank_euclidean_space :
finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 ι) = fintype.card ι := by simp
lemma finrank_euclidean_space_fin {n : ℕ} :
finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 (fin n)) = n := by simp
lemma euclidean_space.inner_eq_star_dot_product (x y : euclidean_space 𝕜 ι) :
⟪x, y⟫ = matrix.dot_product (star $ pi_Lp.equiv _ _ x) (pi_Lp.equiv _ _ y) := rfl
lemma euclidean_space.inner_pi_Lp_equiv_symm (x y : ι → 𝕜) :
⟪(pi_Lp.equiv 2 _).symm x, (pi_Lp.equiv 2 _).symm y⟫ = matrix.dot_product (star x) y := rfl
/-- A finite, mutually orthogonal family of subspaces of `E`, which span `E`, induce an isometry
from `E` to `pi_Lp 2` of the subspaces equipped with the `L2` inner product. -/
def direct_sum.is_internal.isometry_L2_of_orthogonal_family
[decidable_eq ι] {V : ι → submodule 𝕜 E} (hV : direct_sum.is_internal V)
(hV' : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ)) :
E ≃ₗᵢ[𝕜] pi_Lp 2 (λ i, V i) :=
begin
let e₁ := direct_sum.linear_equiv_fun_on_fintype 𝕜 ι (λ i, V i),
let e₂ := linear_equiv.of_bijective (direct_sum.coe_linear_map V) hV,
refine linear_equiv.isometry_of_inner (e₂.symm.trans e₁) _,
suffices : ∀ v w, ⟪v, w⟫ = ⟪e₂ (e₁.symm v), e₂ (e₁.symm w)⟫,
{ intros v₀ w₀,
convert this (e₁ (e₂.symm v₀)) (e₁ (e₂.symm w₀));
simp only [linear_equiv.symm_apply_apply, linear_equiv.apply_symm_apply] },
intros v w,
transitivity ⟪(∑ i, (V i).subtypeₗᵢ (v i)), ∑ i, (V i).subtypeₗᵢ (w i)⟫,
{ simp only [sum_inner, hV'.inner_right_fintype, pi_Lp.inner_apply] },
{ congr; simp }
end
@[simp] lemma direct_sum.is_internal.isometry_L2_of_orthogonal_family_symm_apply
[decidable_eq ι] {V : ι → submodule 𝕜 E} (hV : direct_sum.is_internal V)
(hV' : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ))
(w : pi_Lp 2 (λ i, V i)) :
(hV.isometry_L2_of_orthogonal_family hV').symm w = ∑ i, (w i : E) :=
begin
classical,
let e₁ := direct_sum.linear_equiv_fun_on_fintype 𝕜 ι (λ i, V i),
let e₂ := linear_equiv.of_bijective (direct_sum.coe_linear_map V) hV,
suffices : ∀ v : ⨁ i, V i, e₂ v = ∑ i, e₁ v i,
{ exact this (e₁.symm w) },
intros v,
simp [e₂, direct_sum.coe_linear_map, direct_sum.to_module, dfinsupp.sum_add_hom_apply]
end
end
variables (ι 𝕜)
-- TODO : This should be generalized to `pi_Lp` with finite dimensional factors.
/-- `pi_Lp.linear_equiv` upgraded to a continuous linear map between `euclidean_space 𝕜 ι`
and `ι → 𝕜`. -/
@[simps] def euclidean_space.equiv :
euclidean_space 𝕜 ι ≃L[𝕜] (ι → 𝕜) :=
(pi_Lp.linear_equiv 2 𝕜 (λ i : ι, 𝕜)).to_continuous_linear_equiv
variables {ι 𝕜}
-- TODO : This should be generalized to `pi_Lp`.
/-- The projection on the `i`-th coordinate of `euclidean_space 𝕜 ι`, as a linear map. -/
@[simps] def euclidean_space.projₗ (i : ι) :
euclidean_space 𝕜 ι →ₗ[𝕜] 𝕜 :=
(linear_map.proj i).comp (pi_Lp.linear_equiv 2 𝕜 (λ i : ι, 𝕜) : euclidean_space 𝕜 ι →ₗ[𝕜] ι → 𝕜)
-- TODO : This should be generalized to `pi_Lp`.
/-- The projection on the `i`-th coordinate of `euclidean_space 𝕜 ι`,
as a continuous linear map. -/
@[simps] def euclidean_space.proj (i : ι) :
euclidean_space 𝕜 ι →L[𝕜] 𝕜 :=
⟨euclidean_space.projₗ i, continuous_apply i⟩
-- TODO : This should be generalized to `pi_Lp`.
/-- The vector given in euclidean space by being `1 : 𝕜` at coordinate `i : ι` and `0 : 𝕜` at
all other coordinates. -/
def euclidean_space.single [decidable_eq ι] (i : ι) (a : 𝕜) :
euclidean_space 𝕜 ι :=
(pi_Lp.equiv _ _).symm (pi.single i a)
@[simp] lemma pi_Lp.equiv_single [decidable_eq ι] (i : ι) (a : 𝕜) :
pi_Lp.equiv _ _ (euclidean_space.single i a) = pi.single i a := rfl
@[simp] lemma pi_Lp.equiv_symm_single [decidable_eq ι] (i : ι) (a : 𝕜) :
(pi_Lp.equiv _ _).symm (pi.single i a) = euclidean_space.single i a := rfl
@[simp] theorem euclidean_space.single_apply [decidable_eq ι] (i : ι) (a : 𝕜) (j : ι) :
(euclidean_space.single i a) j = ite (j = i) a 0 :=
by { rw [euclidean_space.single, pi_Lp.equiv_symm_apply, ← pi.single_apply i a j] }
lemma euclidean_space.inner_single_left [decidable_eq ι] (i : ι) (a : 𝕜) (v : euclidean_space 𝕜 ι) :
⟪euclidean_space.single i (a : 𝕜), v⟫ = conj a * (v i) :=
by simp [apply_ite conj]
lemma euclidean_space.inner_single_right [decidable_eq ι] (i : ι) (a : 𝕜)
(v : euclidean_space 𝕜 ι) :
⟪v, euclidean_space.single i (a : 𝕜)⟫ = a * conj (v i) :=
by simp [apply_ite conj, mul_comm]
@[simp] lemma euclidean_space.norm_single [decidable_eq ι] (i : ι) (a : 𝕜) :
‖euclidean_space.single i (a : 𝕜)‖ = ‖a‖ :=
(pi_Lp.norm_equiv_symm_single 2 (λ i, 𝕜) i a : _)
@[simp] lemma euclidean_space.nnnorm_single [decidable_eq ι] (i : ι) (a : 𝕜) :
‖euclidean_space.single i (a : 𝕜)‖₊ = ‖a‖₊ :=
(pi_Lp.nnnorm_equiv_symm_single 2 (λ i, 𝕜) i a : _)
@[simp] lemma euclidean_space.dist_single_same [decidable_eq ι] (i : ι) (a b : 𝕜) :
dist (euclidean_space.single i (a : 𝕜)) (euclidean_space.single i (b : 𝕜)) = dist a b :=
(pi_Lp.dist_equiv_symm_single_same 2 (λ i, 𝕜) i a b : _)
@[simp] lemma euclidean_space.nndist_single_same [decidable_eq ι] (i : ι) (a b : 𝕜) :
nndist (euclidean_space.single i (a : 𝕜)) (euclidean_space.single i (b : 𝕜)) = nndist a b :=
(pi_Lp.nndist_equiv_symm_single_same 2 (λ i, 𝕜) i a b : _)
@[simp] lemma euclidean_space.edist_single_same [decidable_eq ι] (i : ι) (a b : 𝕜) :
edist (euclidean_space.single i (a : 𝕜)) (euclidean_space.single i (b : 𝕜)) = edist a b :=
(pi_Lp.edist_equiv_symm_single_same 2 (λ i, 𝕜) i a b : _)
/-- `euclidean_space.single` forms an orthonormal family. -/
lemma euclidean_space.orthonormal_single [decidable_eq ι] :
orthonormal 𝕜 (λ i : ι, euclidean_space.single i (1 : 𝕜)) :=
begin
simp_rw [orthonormal_iff_ite, euclidean_space.inner_single_left, map_one, one_mul,
euclidean_space.single_apply],
intros i j,
refl,
end
lemma euclidean_space.pi_Lp_congr_left_single [decidable_eq ι] {ι' : Type*} [fintype ι']
[decidable_eq ι'] (e : ι' ≃ ι) (i' : ι') (v : 𝕜):
linear_isometry_equiv.pi_Lp_congr_left 2 𝕜 𝕜 e (euclidean_space.single i' v) =
euclidean_space.single (e i') v :=
linear_isometry_equiv.pi_Lp_congr_left_single e i' _
variables (ι 𝕜 E)
/-- An orthonormal basis on E is an identification of `E` with its dimensional-matching
`euclidean_space 𝕜 ι`. -/
structure orthonormal_basis := of_repr :: (repr : E ≃ₗᵢ[𝕜] euclidean_space 𝕜 ι)
variables {ι 𝕜 E}
namespace orthonormal_basis
instance : inhabited (orthonormal_basis ι 𝕜 (euclidean_space 𝕜 ι)) :=
⟨of_repr (linear_isometry_equiv.refl 𝕜 (euclidean_space 𝕜 ι))⟩
/-- `b i` is the `i`th basis vector. -/
instance : has_coe_to_fun (orthonormal_basis ι 𝕜 E) (λ _, ι → E) :=
{ coe := λ b i, by classical; exact b.repr.symm (euclidean_space.single i (1 : 𝕜)) }
@[simp] lemma coe_of_repr [decidable_eq ι] (e : E ≃ₗᵢ[𝕜] euclidean_space 𝕜 ι) :
⇑(orthonormal_basis.of_repr e) = λ i, e.symm (euclidean_space.single i (1 : 𝕜)) :=
begin
rw coe_fn,
unfold has_coe_to_fun.coe,
funext,
congr,
simp only [eq_iff_true_of_subsingleton],
end
@[simp] protected lemma repr_symm_single [decidable_eq ι] (b : orthonormal_basis ι 𝕜 E) (i : ι) :
b.repr.symm (euclidean_space.single i (1:𝕜)) = b i :=
by { classical, congr, simp, }
@[simp] protected lemma repr_self [decidable_eq ι] (b : orthonormal_basis ι 𝕜 E) (i : ι) :
b.repr (b i) = euclidean_space.single i (1:𝕜) :=
by rw [← b.repr_symm_single i, linear_isometry_equiv.apply_symm_apply]
protected lemma repr_apply_apply (b : orthonormal_basis ι 𝕜 E) (v : E) (i : ι) :
b.repr v i = ⟪b i, v⟫ :=
begin
classical,
rw [← b.repr.inner_map_map (b i) v, b.repr_self i, euclidean_space.inner_single_left],
simp only [one_mul, eq_self_iff_true, map_one],
end
@[simp]
protected lemma orthonormal (b : orthonormal_basis ι 𝕜 E) : orthonormal 𝕜 b :=
begin
classical,
rw orthonormal_iff_ite,
intros i j,
rw [← b.repr.inner_map_map (b i) (b j), b.repr_self i, b.repr_self j,
euclidean_space.inner_single_left, euclidean_space.single_apply, map_one, one_mul],
end
/-- The `basis ι 𝕜 E` underlying the `orthonormal_basis` -/
protected def to_basis (b : orthonormal_basis ι 𝕜 E) : basis ι 𝕜 E :=
basis.of_equiv_fun b.repr.to_linear_equiv
@[simp] protected lemma coe_to_basis (b : orthonormal_basis ι 𝕜 E) :
(⇑b.to_basis : ι → E) = ⇑b :=
begin
change ⇑(basis.of_equiv_fun b.repr.to_linear_equiv) = b,
ext j,
classical,
rw basis.coe_of_equiv_fun,
congr,
end
@[simp] protected lemma coe_to_basis_repr (b : orthonormal_basis ι 𝕜 E) :
b.to_basis.equiv_fun = b.repr.to_linear_equiv :=
basis.equiv_fun_of_equiv_fun _
@[simp] protected lemma coe_to_basis_repr_apply (b : orthonormal_basis ι 𝕜 E) (x : E) (i : ι) :
b.to_basis.repr x i = b.repr x i :=
by {rw [← basis.equiv_fun_apply, orthonormal_basis.coe_to_basis_repr,
linear_isometry_equiv.coe_to_linear_equiv]}
protected lemma sum_repr (b : orthonormal_basis ι 𝕜 E) (x : E) :
∑ i, b.repr x i • b i = x :=
by { simp_rw [← b.coe_to_basis_repr_apply, ← b.coe_to_basis], exact b.to_basis.sum_repr x }
protected lemma sum_repr_symm (b : orthonormal_basis ι 𝕜 E) (v : euclidean_space 𝕜 ι) :
∑ i , v i • b i = (b.repr.symm v) :=
by { simpa using (b.to_basis.equiv_fun_symm_apply v).symm }
protected lemma sum_inner_mul_inner (b : orthonormal_basis ι 𝕜 E) (x y : E) :
∑ i, ⟪x, b i⟫ * ⟪b i, y⟫ = ⟪x, y⟫ :=
begin
have := congr_arg (innerSL 𝕜 x) (b.sum_repr y),
rw map_sum at this,
convert this,
ext i,
rw [smul_hom_class.map_smul, b.repr_apply_apply, mul_comm],
refl,
end
protected lemma orthogonal_projection_eq_sum {U : submodule 𝕜 E} [complete_space U]
(b : orthonormal_basis ι 𝕜 U) (x : E) :
orthogonal_projection U x = ∑ i, ⟪(b i : E), x⟫ • b i :=
by simpa only [b.repr_apply_apply, inner_orthogonal_projection_eq_of_mem_left]
using (b.sum_repr (orthogonal_projection U x)).symm
/-- Mapping an orthonormal basis along a `linear_isometry_equiv`. -/
protected def map {G : Type*}
[normed_add_comm_group G] [inner_product_space 𝕜 G] (b : orthonormal_basis ι 𝕜 E)
(L : E ≃ₗᵢ[𝕜] G) :
orthonormal_basis ι 𝕜 G :=
{ repr := L.symm.trans b.repr }
@[simp] protected lemma map_apply {G : Type*} [normed_add_comm_group G] [inner_product_space 𝕜 G]
(b : orthonormal_basis ι 𝕜 E) (L : E ≃ₗᵢ[𝕜] G) (i : ι) :
b.map L i = L (b i) := rfl
@[simp] protected lemma to_basis_map {G : Type*} [normed_add_comm_group G] [inner_product_space 𝕜 G]
(b : orthonormal_basis ι 𝕜 E) (L : E ≃ₗᵢ[𝕜] G) :
(b.map L).to_basis = b.to_basis.map L.to_linear_equiv :=
rfl
/-- A basis that is orthonormal is an orthonormal basis. -/
def _root_.basis.to_orthonormal_basis (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) :
orthonormal_basis ι 𝕜 E :=
orthonormal_basis.of_repr $
linear_equiv.isometry_of_inner v.equiv_fun
begin
intros x y,
let p : euclidean_space 𝕜 ι := v.equiv_fun x,
let q : euclidean_space 𝕜 ι := v.equiv_fun y,
have key : ⟪p, q⟫ = ⟪∑ i, p i • v i, ∑ i, q i • v i⟫,
{ simp [sum_inner, inner_smul_left, hv.inner_right_fintype] },
convert key,
{ rw [← v.equiv_fun.symm_apply_apply x, v.equiv_fun_symm_apply] },
{ rw [← v.equiv_fun.symm_apply_apply y, v.equiv_fun_symm_apply] }
end
@[simp] lemma _root_.basis.coe_to_orthonormal_basis_repr (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) :
((v.to_orthonormal_basis hv).repr : E → euclidean_space 𝕜 ι) = v.equiv_fun :=
rfl
@[simp] lemma _root_.basis.coe_to_orthonormal_basis_repr_symm
(v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) :
((v.to_orthonormal_basis hv).repr.symm : euclidean_space 𝕜 ι → E) = v.equiv_fun.symm :=
rfl
@[simp] lemma _root_.basis.to_basis_to_orthonormal_basis (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) :
(v.to_orthonormal_basis hv).to_basis = v :=
by simp [basis.to_orthonormal_basis, orthonormal_basis.to_basis]
@[simp] lemma _root_.basis.coe_to_orthonormal_basis (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) :
(v.to_orthonormal_basis hv : ι → E) = (v : ι → E) :=
calc (v.to_orthonormal_basis hv : ι → E) = ((v.to_orthonormal_basis hv).to_basis : ι → E) :
by { classical, rw orthonormal_basis.coe_to_basis }
... = (v : ι → E) : by simp
variable {v : ι → E}
/-- A finite orthonormal set that spans is an orthonormal basis -/
protected def mk (hon : orthonormal 𝕜 v) (hsp: ⊤ ≤ submodule.span 𝕜 (set.range v)):
orthonormal_basis ι 𝕜 E :=
(basis.mk (orthonormal.linear_independent hon) hsp).to_orthonormal_basis (by rwa basis.coe_mk)
@[simp]
protected lemma coe_mk (hon : orthonormal 𝕜 v) (hsp: ⊤ ≤ submodule.span 𝕜 (set.range v)) :
⇑(orthonormal_basis.mk hon hsp) = v :=
by classical; rw [orthonormal_basis.mk, _root_.basis.coe_to_orthonormal_basis, basis.coe_mk]
/-- Any finite subset of a orthonormal family is an `orthonormal_basis` for its span. -/
protected def span [decidable_eq E] {v' : ι' → E} (h : orthonormal 𝕜 v') (s : finset ι') :
orthonormal_basis s 𝕜 (span 𝕜 (s.image v' : set E)) :=
let
e₀' : basis s 𝕜 _ := basis.span (h.linear_independent.comp (coe : s → ι') subtype.coe_injective),
e₀ : orthonormal_basis s 𝕜 _ := orthonormal_basis.mk
begin
convert orthonormal_span (h.comp (coe : s → ι') subtype.coe_injective),
ext,
simp [e₀', basis.span_apply],
end e₀'.span_eq.ge,
φ : span 𝕜 (s.image v' : set E) ≃ₗᵢ[𝕜] span 𝕜 (range (v' ∘ (coe : s → ι'))) :=
linear_isometry_equiv.of_eq _ _
begin
rw [finset.coe_image, image_eq_range],
refl
end
in
e₀.map φ.symm
@[simp] protected lemma span_apply [decidable_eq E]
{v' : ι' → E} (h : orthonormal 𝕜 v') (s : finset ι') (i : s) :
(orthonormal_basis.span h s i : E) = v' i :=
by simp only [orthonormal_basis.span, basis.span_apply, linear_isometry_equiv.of_eq_symm,
orthonormal_basis.map_apply, orthonormal_basis.coe_mk,
linear_isometry_equiv.coe_of_eq_apply]
open submodule
/-- A finite orthonormal family of vectors whose span has trivial orthogonal complement is an
orthonormal basis. -/
protected def mk_of_orthogonal_eq_bot (hon : orthonormal 𝕜 v) (hsp : (span 𝕜 (set.range v))ᗮ = ⊥) :
orthonormal_basis ι 𝕜 E :=
orthonormal_basis.mk hon
begin
refine eq.ge _,
haveI : finite_dimensional 𝕜 (span 𝕜 (range v)) :=
finite_dimensional.span_of_finite 𝕜 (finite_range v),
haveI : complete_space (span 𝕜 (range v)) := finite_dimensional.complete 𝕜 _,
rwa orthogonal_eq_bot_iff at hsp,
end
@[simp] protected lemma coe_of_orthogonal_eq_bot_mk (hon : orthonormal 𝕜 v)
(hsp : (span 𝕜 (set.range v))ᗮ = ⊥) :
⇑(orthonormal_basis.mk_of_orthogonal_eq_bot hon hsp) = v :=
orthonormal_basis.coe_mk hon _
variables [fintype ι']
/-- `b.reindex (e : ι ≃ ι')` is an `orthonormal_basis` indexed by `ι'` -/
def reindex (b : orthonormal_basis ι 𝕜 E) (e : ι ≃ ι') : orthonormal_basis ι' 𝕜 E :=
orthonormal_basis.of_repr (b.repr.trans (linear_isometry_equiv.pi_Lp_congr_left 2 𝕜 𝕜 e))
protected lemma reindex_apply (b : orthonormal_basis ι 𝕜 E) (e : ι ≃ ι') (i' : ι') :
(b.reindex e) i' = b (e.symm i') :=
begin
classical,
dsimp [reindex, orthonormal_basis.has_coe_to_fun],
rw coe_of_repr,
dsimp,
rw [← b.repr_symm_single, linear_isometry_equiv.pi_Lp_congr_left_symm,
euclidean_space.pi_Lp_congr_left_single],
end
@[simp] protected lemma coe_reindex (b : orthonormal_basis ι 𝕜 E) (e : ι ≃ ι') :
⇑(b.reindex e) = ⇑b ∘ ⇑(e.symm) :=
funext (b.reindex_apply e)
@[simp] protected lemma repr_reindex
(b : orthonormal_basis ι 𝕜 E) (e : ι ≃ ι') (x : E) (i' : ι') :
(b.reindex e).repr x i' = b.repr x (e.symm i') :=
by { classical,
rw [orthonormal_basis.repr_apply_apply, b.repr_apply_apply, orthonormal_basis.coe_reindex] }
end orthonormal_basis
/-- `![1, I]` is an orthonormal basis for `ℂ` considered as a real inner product space. -/
def complex.orthonormal_basis_one_I : orthonormal_basis (fin 2) ℝ ℂ :=
(complex.basis_one_I.to_orthonormal_basis
begin
rw orthonormal_iff_ite,
intros i, fin_cases i;
intros j; fin_cases j;
simp [real_inner_eq_re_inner]
end)
@[simp] lemma complex.orthonormal_basis_one_I_repr_apply (z : ℂ) :
complex.orthonormal_basis_one_I.repr z = ![z.re, z.im] :=
rfl
@[simp] lemma complex.orthonormal_basis_one_I_repr_symm_apply (x : euclidean_space ℝ (fin 2)) :
complex.orthonormal_basis_one_I.repr.symm x = (x 0) + (x 1) * I :=
rfl
@[simp] lemma complex.to_basis_orthonormal_basis_one_I :
complex.orthonormal_basis_one_I.to_basis = complex.basis_one_I :=
basis.to_basis_to_orthonormal_basis _ _
@[simp] lemma complex.coe_orthonormal_basis_one_I :
(complex.orthonormal_basis_one_I : (fin 2) → ℂ) = ![1, I] :=
by simp [complex.orthonormal_basis_one_I]
/-- The isometry between `ℂ` and a two-dimensional real inner product space given by a basis. -/
def complex.isometry_of_orthonormal (v : orthonormal_basis (fin 2) ℝ F) : ℂ ≃ₗᵢ[ℝ] F :=
complex.orthonormal_basis_one_I.repr.trans v.repr.symm
@[simp] lemma complex.map_isometry_of_orthonormal (v : orthonormal_basis (fin 2) ℝ F)
(f : F ≃ₗᵢ[ℝ] F') :
complex.isometry_of_orthonormal (v.map f) =
(complex.isometry_of_orthonormal v).trans f :=
by simp [complex.isometry_of_orthonormal, linear_isometry_equiv.trans_assoc, orthonormal_basis.map]
lemma complex.isometry_of_orthonormal_symm_apply
(v : orthonormal_basis (fin 2) ℝ F) (f : F) :
(complex.isometry_of_orthonormal v).symm f
= (v.to_basis.coord 0 f : ℂ) + (v.to_basis.coord 1 f : ℂ) * I :=
by simp [complex.isometry_of_orthonormal]
lemma complex.isometry_of_orthonormal_apply
(v : orthonormal_basis (fin 2) ℝ F) (z : ℂ) :
complex.isometry_of_orthonormal v z = z.re • v 0 + z.im • v 1 :=
by simp [complex.isometry_of_orthonormal, ← v.sum_repr_symm]
open finite_dimensional
/-! ### Matrix representation of an orthonormal basis with respect to another -/
section to_matrix
variables [decidable_eq ι]
section
variables (a b : orthonormal_basis ι 𝕜 E)
/-- The change-of-basis matrix between two orthonormal bases `a`, `b` is a unitary matrix. -/
lemma orthonormal_basis.to_matrix_orthonormal_basis_mem_unitary :
a.to_basis.to_matrix b ∈ matrix.unitary_group ι 𝕜 :=
begin
rw matrix.mem_unitary_group_iff',
ext i j,
convert a.repr.inner_map_map (b i) (b j),
rw orthonormal_iff_ite.mp b.orthonormal i j,
refl,
end
/-- The determinant of the change-of-basis matrix between two orthonormal bases `a`, `b` has
unit length. -/
@[simp] lemma orthonormal_basis.det_to_matrix_orthonormal_basis :
‖a.to_basis.det b‖ = 1 :=
begin
have : (norm_sq (a.to_basis.det b) : 𝕜) = 1,
{ simpa [is_R_or_C.mul_conj]
using (matrix.det_of_mem_unitary (a.to_matrix_orthonormal_basis_mem_unitary b)).2 },
norm_cast at this,
rwa [← sqrt_norm_sq_eq_norm, sqrt_eq_one],
end
end
section real
variables (a b : orthonormal_basis ι ℝ F)
/-- The change-of-basis matrix between two orthonormal bases `a`, `b` is an orthogonal matrix. -/
lemma orthonormal_basis.to_matrix_orthonormal_basis_mem_orthogonal :
a.to_basis.to_matrix b ∈ matrix.orthogonal_group ι ℝ :=
a.to_matrix_orthonormal_basis_mem_unitary b
/-- The determinant of the change-of-basis matrix between two orthonormal bases `a`, `b` is ±1. -/
lemma orthonormal_basis.det_to_matrix_orthonormal_basis_real :
a.to_basis.det b = 1 ∨ a.to_basis.det b = -1 :=
begin
rw ← sq_eq_one_iff,
simpa [unitary, sq] using matrix.det_of_mem_unitary (a.to_matrix_orthonormal_basis_mem_unitary b)
end
end real
end to_matrix
/-! ### Existence of orthonormal basis, etc. -/
section finite_dimensional
variables {v : set E}
variables {A : ι → submodule 𝕜 E}
/-- Given an internal direct sum decomposition of a module `M`, and an orthonormal basis for each
of the components of the direct sum, the disjoint union of these orthonormal bases is an
orthonormal basis for `M`. -/
noncomputable def direct_sum.is_internal.collected_orthonormal_basis
(hV : orthogonal_family 𝕜 (λ i, A i) (λ i, (A i).subtypeₗᵢ))
[decidable_eq ι] (hV_sum : direct_sum.is_internal (λ i, A i)) {α : ι → Type*}
[Π i, fintype (α i)] (v_family : Π i, orthonormal_basis (α i) 𝕜 (A i)) :
orthonormal_basis (Σ i, α i) 𝕜 E :=
(hV_sum.collected_basis (λ i, (v_family i).to_basis)).to_orthonormal_basis $
by simpa using hV.orthonormal_sigma_orthonormal
(show (∀ i, orthonormal 𝕜 (v_family i).to_basis), by simp)
lemma direct_sum.is_internal.collected_orthonormal_basis_mem [decidable_eq ι]
(h : direct_sum.is_internal A) {α : ι → Type*}
[Π i, fintype (α i)] (hV : orthogonal_family 𝕜 (λ i, A i) (λ i, (A i).subtypeₗᵢ))
(v : Π i, orthonormal_basis (α i) 𝕜 (A i)) (a : Σ i, α i) :
h.collected_orthonormal_basis hV v a ∈ A a.1 :=
by simp [direct_sum.is_internal.collected_orthonormal_basis]
variables [finite_dimensional 𝕜 E]
/-- In a finite-dimensional `inner_product_space`, any orthonormal subset can be extended to an
orthonormal basis. -/
lemma _root_.orthonormal.exists_orthonormal_basis_extension (hv : orthonormal 𝕜 (coe : v → E)) :
∃ {u : finset E} (b : orthonormal_basis u 𝕜 E), v ⊆ u ∧ ⇑b = coe :=
begin
obtain ⟨u₀, hu₀s, hu₀, hu₀_max⟩ := exists_maximal_orthonormal hv,
rw maximal_orthonormal_iff_orthogonal_complement_eq_bot hu₀ at hu₀_max,
have hu₀_finite : u₀.finite := hu₀.linear_independent.finite,
let u : finset E := hu₀_finite.to_finset,
let fu : ↥u ≃ ↥u₀ := equiv.cast (congr_arg coe_sort hu₀_finite.coe_to_finset),
have hfu : (coe : u → E) = (coe : u₀ → E) ∘ fu := by { ext, simp },
have hu : orthonormal 𝕜 (coe : u → E) := by simpa [hfu] using hu₀.comp _ fu.injective,
refine ⟨u, orthonormal_basis.mk_of_orthogonal_eq_bot hu _, _, _⟩,
{ simpa using hu₀_max },
{ simpa using hu₀s },
{ simp },
end
lemma _root_.orthonormal.exists_orthonormal_basis_extension_of_card_eq
{ι : Type*} [fintype ι] (card_ι : finrank 𝕜 E = fintype.card ι) {v : ι → E} {s : set ι}
(hv : orthonormal 𝕜 (s.restrict v)) :
∃ b : orthonormal_basis ι 𝕜 E, ∀ i ∈ s, b i = v i :=
begin
have hsv : injective (s.restrict v) := hv.linear_independent.injective,
have hX : orthonormal 𝕜 (coe : set.range (s.restrict v) → E),
{ rwa orthonormal_subtype_range hsv },
obtain ⟨Y, b₀, hX, hb₀⟩ := hX.exists_orthonormal_basis_extension,
have hιY : fintype.card ι = Y.card,
{ refine (card_ι.symm.trans _),
exact finite_dimensional.finrank_eq_card_finset_basis b₀.to_basis },
have hvsY : s.maps_to v Y := (s.maps_to_image v).mono_right (by rwa ← range_restrict),
have hsv' : set.inj_on v s,
{ rw set.inj_on_iff_injective,
exact hsv },
obtain ⟨g, hg⟩ := hvsY.exists_equiv_extend_of_card_eq hιY hsv',
use b₀.reindex g.symm,
intros i hi,
{ simp [hb₀, hg i hi] },
end
variables (𝕜 E)
/-- A finite-dimensional inner product space admits an orthonormal basis. -/
lemma _root_.exists_orthonormal_basis :
∃ (w : finset E) (b : orthonormal_basis w 𝕜 E), ⇑b = (coe : w → E) :=
let ⟨w, hw, hw', hw''⟩ := (orthonormal_empty 𝕜 E).exists_orthonormal_basis_extension in
⟨w, hw, hw''⟩
/-- A finite-dimensional `inner_product_space` has an orthonormal basis. -/
@[irreducible] def std_orthonormal_basis : orthonormal_basis (fin (finrank 𝕜 E)) 𝕜 E :=
begin
let b := classical.some (classical.some_spec $ exists_orthonormal_basis 𝕜 E),
rw [finrank_eq_card_basis b.to_basis],
exact b.reindex (fintype.equiv_fin_of_card_eq rfl),
end
/-- An orthonormal basis of `ℝ` is made either of the vector `1`, or of the vector `-1`. -/
lemma orthonormal_basis_one_dim (b : orthonormal_basis ι ℝ ℝ) :
⇑b = (λ _, (1 : ℝ)) ∨ ⇑b = (λ _, (-1 : ℝ)) :=
begin
haveI : unique ι, from b.to_basis.unique,
have : b default = 1 ∨ b default = - 1,
{ have : ‖b default‖ = 1, from b.orthonormal.1 _,
rwa [real.norm_eq_abs, abs_eq (zero_le_one : (0 : ℝ) ≤ 1)] at this },
rw eq_const_of_unique b,
refine this.imp _ _; simp,
end
variables {𝕜 E}
section subordinate_orthonormal_basis
open direct_sum
variables {n : ℕ} (hn : finrank 𝕜 E = n) [decidable_eq ι]
{V : ι → submodule 𝕜 E} (hV : is_internal V)
/-- Exhibit a bijection between `fin n` and the index set of a certain basis of an `n`-dimensional
inner product space `E`. This should not be accessed directly, but only via the subsequent API. -/
@[irreducible] def direct_sum.is_internal.sigma_orthonormal_basis_index_equiv
(hV' : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ)) :
(Σ i, fin (finrank 𝕜 (V i))) ≃ fin n :=
let b := hV.collected_orthonormal_basis hV' (λ i, (std_orthonormal_basis 𝕜 (V i))) in
fintype.equiv_fin_of_card_eq $ (finite_dimensional.finrank_eq_card_basis b.to_basis).symm.trans hn
/-- An `n`-dimensional `inner_product_space` equipped with a decomposition as an internal direct
sum has an orthonormal basis indexed by `fin n` and subordinate to that direct sum. -/
@[irreducible] def direct_sum.is_internal.subordinate_orthonormal_basis
(hV' : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ)) :
orthonormal_basis (fin n) 𝕜 E :=
((hV.collected_orthonormal_basis hV' (λ i, (std_orthonormal_basis 𝕜 (V i)))).reindex
(hV.sigma_orthonormal_basis_index_equiv hn hV'))
/-- An `n`-dimensional `inner_product_space` equipped with a decomposition as an internal direct
sum has an orthonormal basis indexed by `fin n` and subordinate to that direct sum. This function
provides the mapping by which it is subordinate. -/
@[irreducible] def direct_sum.is_internal.subordinate_orthonormal_basis_index
(a : fin n) (hV' : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ)) : ι :=
((hV.sigma_orthonormal_basis_index_equiv hn hV').symm a).1
/-- The basis constructed in `orthogonal_family.subordinate_orthonormal_basis` is subordinate to
the `orthogonal_family` in question. -/
lemma direct_sum.is_internal.subordinate_orthonormal_basis_subordinate
(a : fin n) (hV' : orthogonal_family 𝕜 (λ i, V i) (λ i, (V i).subtypeₗᵢ)) :
(hV.subordinate_orthonormal_basis hn hV' a) ∈
V (hV.subordinate_orthonormal_basis_index hn a hV') :=
by simpa only [direct_sum.is_internal.subordinate_orthonormal_basis,
orthonormal_basis.coe_reindex, direct_sum.is_internal.subordinate_orthonormal_basis_index]
using hV.collected_orthonormal_basis_mem hV' (λ i, (std_orthonormal_basis 𝕜 (V i)))
((hV.sigma_orthonormal_basis_index_equiv hn hV').symm a)
end subordinate_orthonormal_basis
end finite_dimensional
local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ
/-- Given a natural number `n` one less than the `finrank` of a finite-dimensional inner product
space, there exists an isometry from the orthogonal complement of a nonzero singleton to
`euclidean_space 𝕜 (fin n)`. -/
def orthonormal_basis.from_orthogonal_span_singleton
(n : ℕ) [fact (finrank 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) :
orthonormal_basis (fin n) 𝕜 (𝕜 ∙ v)ᗮ :=
(std_orthonormal_basis _ _).reindex $ fin_congr $ finrank_orthogonal_span_singleton hv
section linear_isometry
variables {V : Type*} [normed_add_comm_group V] [inner_product_space 𝕜 V] [finite_dimensional 𝕜 V]
variables {S : submodule 𝕜 V} {L : S →ₗᵢ[𝕜] V}
open finite_dimensional
/-- Let `S` be a subspace of a finite-dimensional complex inner product space `V`. A linear
isometry mapping `S` into `V` can be extended to a full isometry of `V`.
TODO: The case when `S` is a finite-dimensional subspace of an infinite-dimensional `V`.-/
noncomputable def linear_isometry.extend (L : S →ₗᵢ[𝕜] V): V →ₗᵢ[𝕜] V :=
begin
-- Build an isometry from Sᗮ to L(S)ᗮ through euclidean_space
let d := finrank 𝕜 Sᗮ,
have dim_S_perp : finrank 𝕜 Sᗮ = d := rfl,
let LS := L.to_linear_map.range,
have E : Sᗮ ≃ₗᵢ[𝕜] LSᗮ,
{ have dim_LS_perp : finrank 𝕜 LSᗮ = d,
calc finrank 𝕜 LSᗮ = finrank 𝕜 V - finrank 𝕜 LS : by simp only
[← LS.finrank_add_finrank_orthogonal, add_tsub_cancel_left]
... = finrank 𝕜 V - finrank 𝕜 S : by simp only
[linear_map.finrank_range_of_inj L.injective]
... = finrank 𝕜 Sᗮ : by simp only
[← S.finrank_add_finrank_orthogonal, add_tsub_cancel_left],
exact (std_orthonormal_basis 𝕜 Sᗮ).repr.trans
((std_orthonormal_basis 𝕜 LSᗮ).reindex $ fin_congr dim_LS_perp).repr.symm },
let L3 := (LS)ᗮ.subtypeₗᵢ.comp E.to_linear_isometry,
-- Project onto S and Sᗮ
haveI : complete_space S := finite_dimensional.complete 𝕜 S,
haveI : complete_space V := finite_dimensional.complete 𝕜 V,
let p1 := (orthogonal_projection S).to_linear_map,
let p2 := (orthogonal_projection Sᗮ).to_linear_map,
-- Build a linear map from the isometries on S and Sᗮ
let M := L.to_linear_map.comp p1 + L3.to_linear_map.comp p2,
-- Prove that M is an isometry
have M_norm_map : ∀ (x : V), ‖M x‖ = ‖x‖,
{ intro x,
-- Apply M to the orthogonal decomposition of x
have Mx_decomp : M x = L (p1 x) + L3 (p2 x),
{ simp only [linear_map.add_apply, linear_map.comp_apply, linear_map.comp_apply,
linear_isometry.coe_to_linear_map]},
-- Mx_decomp is the orthogonal decomposition of M x
have Mx_orth : ⟪ L (p1 x), L3 (p2 x) ⟫ = 0,
{ have Lp1x : L (p1 x) ∈ L.to_linear_map.range :=
linear_map.mem_range_self L.to_linear_map (p1 x),
have Lp2x : L3 (p2 x) ∈ (L.to_linear_map.range)ᗮ,
{ simp only [L3, linear_isometry.coe_comp, function.comp_app, submodule.coe_subtypeₗᵢ,
← submodule.range_subtype (LSᗮ)],
apply linear_map.mem_range_self},
apply submodule.inner_right_of_mem_orthogonal Lp1x Lp2x},
-- Apply the Pythagorean theorem and simplify
rw [← sq_eq_sq (norm_nonneg _) (norm_nonneg _), norm_sq_eq_add_norm_sq_projection x S],
simp only [sq, Mx_decomp],
rw norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (L (p1 x)) (L3 (p2 x)) Mx_orth,
simp only [linear_isometry.norm_map, p1, p2, continuous_linear_map.to_linear_map_eq_coe,
add_left_inj, mul_eq_mul_left_iff, norm_eq_zero, true_or, eq_self_iff_true,
continuous_linear_map.coe_coe, submodule.coe_norm, submodule.coe_eq_zero] },
exact { to_linear_map := M, norm_map' := M_norm_map },
end
lemma linear_isometry.extend_apply (L : S →ₗᵢ[𝕜] V) (s : S):
L.extend s = L s :=
begin
haveI : complete_space S := finite_dimensional.complete 𝕜 S,
simp only [linear_isometry.extend, continuous_linear_map.to_linear_map_eq_coe,
←linear_isometry.coe_to_linear_map],
simp only [add_right_eq_self, linear_isometry.coe_to_linear_map,
linear_isometry_equiv.coe_to_linear_isometry, linear_isometry.coe_comp, function.comp_app,
orthogonal_projection_mem_subspace_eq_self, linear_map.coe_comp, continuous_linear_map.coe_coe,
submodule.coe_subtype, linear_map.add_apply, submodule.coe_eq_zero,
linear_isometry_equiv.map_eq_zero_iff, submodule.coe_subtypeₗᵢ,
orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero,
submodule.orthogonal_orthogonal, submodule.coe_mem],
end
end linear_isometry
section matrix
open_locale matrix
variables {m n : Type*}
namespace matrix
variables [fintype m] [fintype n] [decidable_eq n]
/-- `matrix.to_lin'` adapted for `euclidean_space 𝕜 _`. -/
def to_euclidean_lin : matrix m n 𝕜 ≃ₗ[𝕜] (euclidean_space 𝕜 n →ₗ[𝕜] euclidean_space 𝕜 m) :=
matrix.to_lin' ≪≫ₗ linear_equiv.arrow_congr
(pi_Lp.linear_equiv _ 𝕜 (λ _ : n, 𝕜)).symm (pi_Lp.linear_equiv _ 𝕜 (λ _ : m, 𝕜)).symm
@[simp]
lemma to_euclidean_lin_pi_Lp_equiv_symm (A : matrix m n 𝕜) (x : n → 𝕜) :
A.to_euclidean_lin ((pi_Lp.equiv _ _).symm x) = (pi_Lp.equiv _ _).symm (A.to_lin' x) := rfl
@[simp]
lemma pi_Lp_equiv_to_euclidean_lin (A : matrix m n 𝕜) (x : euclidean_space 𝕜 n) :
pi_Lp.equiv _ _ (A.to_euclidean_lin x) = A.to_lin' (pi_Lp.equiv _ _ x) := rfl
/- `matrix.to_euclidean_lin` is the same as `matrix.to_lin` applied to `pi_Lp.basis_fun`, -/
lemma to_euclidean_lin_eq_to_lin :
(to_euclidean_lin : matrix m n 𝕜 ≃ₗ[𝕜] _) =
matrix.to_lin (pi_Lp.basis_fun _ _ _) (pi_Lp.basis_fun _ _ _) := rfl
end matrix
local notation `⟪`x`, `y`⟫ₑ` := @inner 𝕜 _ _ ((pi_Lp.equiv 2 _).symm x) ((pi_Lp.equiv 2 _).symm y)
/-- The inner product of a row of `A` and a row of `B` is an entry of `B ⬝ Aᴴ`. -/
lemma inner_matrix_row_row [fintype n] (A B : matrix m n 𝕜) (i j : m) :
⟪A i, B j⟫ₑ = (B ⬝ Aᴴ) j i :=
by simp_rw [euclidean_space.inner_pi_Lp_equiv_symm, matrix.mul_apply', matrix.dot_product_comm,
matrix.conj_transpose_apply, pi.star_def]
/-- The inner product of a column of `A` and a column of `B` is an entry of `Aᴴ ⬝ B`. -/
lemma inner_matrix_col_col [fintype m] (A B : matrix m n 𝕜) (i j : n) :
⟪Aᵀ i, Bᵀ j⟫ₑ = (Aᴴ ⬝ B) i j := rfl
end matrix
|
d1f5d11ea5eae3e3bd68ead444eef289ec23d450 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/measure_theory/probability_mass_function/constructions.lean | 6632f112eee3963fe913530a3a1b1eae542af524 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 10,824 | 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, Devon Tuma
-/
import measure_theory.probability_mass_function.monad
/-!
# Specific Constructions of Probability Mass Functions
This file gives a number of different `pmf` constructions for common probability distributions.
`map` and `seq` allow pushing a `pmf α` along a function `f : α → β` (or distribution of
functions `f : pmf (α → β)`) to get a `pmf β`
`of_finset` and `of_fintype` simplify the construction of a `pmf α` from a function `f : α → ℝ≥0`,
by allowing the "sum equals 1" constraint to be in terms of `finset.sum` instead of `tsum`.
`of_multiset`, `uniform_of_finset`, and `uniform_of_fintype` construct probability mass functions
from the corresponding object, with proportional weighting for each element of the object.
`normalize` constructs a `pmf α` by normalizing a function `f : α → ℝ≥0` by its sum,
and `filter` uses this to filter the support of a `pmf` and re-normalize the new distribution.
`bernoulli` represents the bernoulli distribution on `bool`
-/
namespace pmf
noncomputable theory
variables {α : Type*} {β : Type*} {γ : Type*}
open_locale classical big_operators nnreal ennreal
section map
/-- The functorial action of a function on a `pmf`. -/
def map (f : α → β) (p : pmf α) : pmf β := bind p (pure ∘ f)
variables (f : α → β) (p : pmf α) (b : β)
@[simp] lemma map_apply : (map f p) b = ∑' a, if b = f a then p a else 0 := by simp [map]
@[simp] lemma support_map : (map f p).support = f '' p.support :=
set.ext (λ b, by simp [map, @eq_comm β b])
lemma mem_support_map_iff : b ∈ (map f p).support ↔ ∃ a ∈ p.support, f a = b := by simp
lemma bind_pure_comp : bind p (pure ∘ f) = map f p := rfl
lemma map_id : map id p = p := by simp [map]
lemma map_comp (g : β → γ) : (p.map f).map g = p.map (g ∘ f) :=
by simp [map]
lemma pure_map (a : α) : (pure a).map f = pure (f a) :=
by simp [map]
end map
section seq
/-- The monadic sequencing operation for `pmf`. -/
def seq (q : pmf (α → β)) (p : pmf α) : pmf β := q.bind (λ m, p.bind $ λ a, pure (m a))
variables (q : pmf (α → β)) (p : pmf α) (b : β)
@[simp] lemma seq_apply : (seq q p) b = ∑' (f : α → β) (a : α), if b = f a then q f * p a else 0 :=
begin
simp only [seq, mul_boole, bind_apply, pure_apply],
refine tsum_congr (λ f, (nnreal.tsum_mul_left (q f) _).symm.trans (tsum_congr (λ a, _))),
simpa only [mul_zero] using mul_ite (b = f a) (q f) (p a) 0
end
@[simp] lemma support_seq : (seq q p).support = ⋃ f ∈ q.support, f '' p.support :=
set.ext (λ b, by simp [-mem_support_iff, seq, @eq_comm β b])
lemma mem_support_seq_iff : b ∈ (seq q p).support ↔ ∃ (f ∈ q.support), b ∈ f '' p.support :=
by simp
end seq
section of_finset
/-- Given a finset `s` and a function `f : α → ℝ≥0` with sum `1` on `s`,
such that `f a = 0` for `a ∉ s`, we get a `pmf` -/
def of_finset (f : α → ℝ≥0) (s : finset α) (h : ∑ a in s, f a = 1)
(h' : ∀ a ∉ s, f a = 0) : pmf α :=
⟨f, h ▸ has_sum_sum_of_ne_finset_zero h'⟩
variables {f : α → ℝ≥0} {s : finset α} (h : ∑ a in s, f a = 1) (h' : ∀ a ∉ s, f a = 0)
@[simp] lemma of_finset_apply (a : α) : of_finset f s h h' a = f a := rfl
@[simp] lemma support_of_finset : (of_finset f s h h').support = s ∩ (function.support f) :=
set.ext (λ a, by simpa [mem_support_iff] using mt (h' a))
lemma mem_support_of_finset_iff (a : α) : a ∈ (of_finset f s h h').support ↔ a ∈ s ∧ f a ≠ 0 :=
by simp
lemma of_finset_apply_of_not_mem {a : α} (ha : a ∉ s) : of_finset f s h h' a = 0 :=
h' a ha
end of_finset
section of_fintype
/-- Given a finite type `α` and a function `f : α → ℝ≥0` with sum 1, we get a `pmf`. -/
def of_fintype [fintype α] (f : α → ℝ≥0) (h : ∑ a, f a = 1) : pmf α :=
of_finset f finset.univ h (λ a ha, absurd (finset.mem_univ a) ha)
variables [fintype α] {f : α → ℝ≥0} (h : ∑ a, f a = 1)
@[simp] lemma of_fintype_apply (a : α) : of_fintype f h a = f a := rfl
@[simp] lemma support_of_fintype : (of_fintype f h).support = function.support f := rfl
lemma mem_support_of_fintype_iff (a : α) : a ∈ (of_fintype f h).support ↔ f a ≠ 0 := iff.rfl
end of_fintype
section of_multiset
/-- Given a non-empty multiset `s` we construct the `pmf` which sends `a` to the fraction of
elements in `s` that are `a`. -/
def of_multiset (s : multiset α) (hs : s ≠ 0) : pmf α :=
⟨λ a, s.count a / s.card,
have ∑ a in s.to_finset, (s.count a : ℝ) / s.card = 1,
by simp [div_eq_inv_mul, finset.mul_sum.symm, (nat.cast_sum _ _).symm, hs],
have ∑ a in s.to_finset, (s.count a : ℝ≥0) / s.card = 1,
by rw [← nnreal.eq_iff, nnreal.coe_one, ← this, nnreal.coe_sum]; simp,
begin
rw ← this,
apply has_sum_sum_of_ne_finset_zero,
simp {contextual := tt},
end⟩
variables {s : multiset α} (hs : s ≠ 0)
@[simp] lemma of_multiset_apply (a : α) : of_multiset s hs a = s.count a / s.card := rfl
@[simp] lemma support_of_multiset : (of_multiset s hs).support = s.to_finset :=
set.ext (by simp [mem_support_iff, hs])
lemma mem_support_of_multiset_iff (a : α) : a ∈ (of_multiset s hs).support ↔ a ∈ s.to_finset :=
by simp
lemma of_multiset_apply_of_not_mem {a : α} (ha : a ∉ s) : of_multiset s hs a = 0 :=
div_eq_zero_iff.2 (or.inl $ nat.cast_eq_zero.2 $ multiset.count_eq_zero_of_not_mem ha)
end of_multiset
section uniform
section uniform_of_finset
/-- Uniform distribution taking the same non-zero probability on the nonempty finset `s` -/
def uniform_of_finset (s : finset α) (hs : s.nonempty) : pmf α :=
of_finset (λ a, if a ∈ s then (s.card : ℝ≥0)⁻¹ else 0) s (Exists.rec_on hs (λ x hx,
calc ∑ (a : α) in s, ite (a ∈ s) (s.card : ℝ≥0)⁻¹ 0
= ∑ (a : α) in s, (s.card : ℝ≥0)⁻¹ : finset.sum_congr rfl (λ x hx, by simp [hx])
... = s.card • (s.card : ℝ≥0)⁻¹ : finset.sum_const _
... = (s.card : ℝ≥0) * (s.card : ℝ≥0)⁻¹ : by rw nsmul_eq_mul
... = 1 : div_self (nat.cast_ne_zero.2 $ finset.card_ne_zero_of_mem hx)
)) (λ x hx, by simp only [hx, if_false])
variables {s : finset α} (hs : s.nonempty) {a : α}
@[simp] lemma uniform_of_finset_apply (a : α) :
uniform_of_finset s hs a = if a ∈ s then (s.card : ℝ≥0)⁻¹ else 0 := rfl
lemma uniform_of_finset_apply_of_mem (ha : a ∈ s) : uniform_of_finset s hs a = (s.card)⁻¹ :=
by simp [ha]
lemma uniform_of_finset_apply_of_not_mem (ha : a ∉ s) : uniform_of_finset s hs a = 0 :=
by simp [ha]
@[simp] lemma support_uniform_of_finset : (uniform_of_finset s hs).support = s :=
set.ext (let ⟨a, ha⟩ := hs in by simp [mem_support_iff, finset.ne_empty_of_mem ha])
lemma mem_support_uniform_of_finset_iff (a : α) : a ∈ (uniform_of_finset s hs).support ↔ a ∈ s :=
by simp
end uniform_of_finset
section uniform_of_fintype
/-- The uniform pmf taking the same uniform value on all of the fintype `α` -/
def uniform_of_fintype (α : Type*) [fintype α] [nonempty α] : pmf α :=
uniform_of_finset (finset.univ) (finset.univ_nonempty)
variables [fintype α] [nonempty α]
@[simp] lemma uniform_of_fintype_apply (a : α) : uniform_of_fintype α a = (fintype.card α)⁻¹ :=
by simpa only [uniform_of_fintype, finset.mem_univ, if_true, uniform_of_finset_apply]
variable (α)
@[simp] lemma support_uniform_of_fintype : (uniform_of_fintype α).support = ⊤ :=
set.ext (λ x, by simpa [mem_support_iff] using fintype.card_ne_zero)
variable {α}
lemma mem_support_uniform_of_fintype_iff (a : α) : a ∈ (uniform_of_fintype α).support := by simp
end uniform_of_fintype
end uniform
section normalize
/-- Given a `f` with non-zero sum, we get a `pmf` by normalizing `f` by it's `tsum` -/
def normalize (f : α → ℝ≥0) (hf0 : tsum f ≠ 0) : pmf α :=
⟨λ a, f a * (∑' x, f x)⁻¹,
(mul_inv_cancel hf0) ▸ has_sum.mul_right (∑' x, f x)⁻¹
(not_not.mp (mt tsum_eq_zero_of_not_summable hf0 : ¬¬summable f)).has_sum⟩
variables {f : α → ℝ≥0} (hf0 : tsum f ≠ 0)
@[simp] lemma normalize_apply (a : α) : (normalize f hf0) a = f a * (∑' x, f x)⁻¹ := rfl
@[simp] lemma support_normalize : (normalize f hf0).support = function.support f :=
set.ext (by simp [mem_support_iff, hf0])
lemma mem_support_normalize_iff (a : α) : a ∈ (normalize f hf0).support ↔ f a ≠ 0 := by simp
end normalize
section filter
/-- Create new `pmf` by filtering on a set with non-zero measure and normalizing -/
def filter (p : pmf α) (s : set α) (h : ∃ a ∈ s, a ∈ p.support) : pmf α :=
pmf.normalize (s.indicator p) $ nnreal.tsum_indicator_ne_zero p.2.summable h
variables {p : pmf α} {s : set α} (h : ∃ a ∈ s, a ∈ p.support)
@[simp]
lemma filter_apply (a : α) : (p.filter s h) a = (s.indicator p a) * (∑' a', (s.indicator p) a')⁻¹ :=
by rw [filter, normalize_apply]
lemma filter_apply_eq_zero_of_not_mem {a : α} (ha : a ∉ s) : (p.filter s h) a = 0 :=
by rw [filter_apply, set.indicator_apply_eq_zero.mpr (λ ha', absurd ha' ha), zero_mul]
@[simp] lemma support_filter : (p.filter s h).support = s ∩ p.support:=
begin
refine set.ext (λ a, _),
rw [mem_support_iff, filter_apply, mul_ne_zero_iff, set.indicator_eq_zero_iff],
exact ⟨λ ha, ha.1, λ ha, ⟨ha, inv_ne_zero (nnreal.tsum_indicator_ne_zero p.2.summable h)⟩⟩
end
lemma mem_support_filter_iff (a : α) : a ∈ (p.filter s h).support ↔ a ∈ s ∧ a ∈ p.support :=
by simp
lemma filter_apply_eq_zero_iff (a : α) : (p.filter s h) a = 0 ↔ a ∉ s ∨ a ∉ p.support :=
by erw [apply_eq_zero_iff, support_filter, set.mem_inter_iff, not_and_distrib]
lemma filter_apply_ne_zero_iff (a : α) : (p.filter s h) a ≠ 0 ↔ a ∈ s ∧ a ∈ p.support :=
by rw [ne.def, filter_apply_eq_zero_iff, not_or_distrib, not_not, not_not]
end filter
section bernoulli
/-- A `pmf` which assigns probability `p` to `tt` and `1 - p` to `ff`. -/
def bernoulli (p : ℝ≥0) (h : p ≤ 1) : pmf bool :=
of_fintype (λ b, cond b p (1 - p)) (nnreal.eq $ by simp [h])
variables {p : ℝ≥0} (h : p ≤ 1) (b : bool)
@[simp] lemma bernoulli_apply : bernoulli p h b = cond b p (1 - p) := rfl
@[simp] lemma support_bernoulli : (bernoulli p h).support = {b | cond b (p ≠ 0) (p ≠ 1)} :=
begin
refine set.ext (λ b, _),
induction b,
{ simp_rw [mem_support_iff, bernoulli_apply, bool.cond_ff, ne.def, tsub_eq_zero_iff_le, not_le],
exact ⟨ne_of_lt, lt_of_le_of_ne h⟩ },
{ simp only [mem_support_iff, bernoulli_apply, bool.cond_tt, set.mem_set_of_eq], }
end
lemma mem_support_bernoulli_iff : b ∈ (bernoulli p h).support ↔ cond b (p ≠ 0) (p ≠ 1) := by simp
end bernoulli
end pmf
|
bbd0f4424bb964f68e9e196de68c04d0bcf4087b | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/linear_algebra/matrix/to_lin.lean | 949323d8d408f43dfc81941d218db668951f2f81 | [
"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 | 36,453 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen
-/
import data.matrix.block
import data.matrix.notation
import linear_algebra.std_basis
import ring_theory.algebra_tower
import algebra.module.algebra
import algebra.algebra.subalgebra.tower
/-!
# Linear maps and matrices
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines the maps to send matrices to a linear map,
and to send linear maps between modules with a finite bases
to matrices. This defines a linear equivalence between linear maps
between finite-dimensional vector spaces and matrices indexed by
the respective bases.
## Main definitions
In the list below, and in all this file, `R` is a commutative ring (semiring
is sometimes enough), `M` and its variations are `R`-modules, `ι`, `κ`, `n` and `m` are finite
types used for indexing.
* `linear_map.to_matrix`: given bases `v₁ : ι → M₁` and `v₂ : κ → M₂`,
the `R`-linear equivalence from `M₁ →ₗ[R] M₂` to `matrix κ ι R`
* `matrix.to_lin`: the inverse of `linear_map.to_matrix`
* `linear_map.to_matrix'`: the `R`-linear equivalence from `(m → R) →ₗ[R] (n → R)`
to `matrix m n R` (with the standard basis on `m → R` and `n → R`)
* `matrix.to_lin'`: the inverse of `linear_map.to_matrix'`
* `alg_equiv_matrix`: given a basis indexed by `n`, the `R`-algebra equivalence between
`R`-endomorphisms of `M` and `matrix n n R`
## Issues
This file was originally written without attention to non-commutative rings,
and so mostly only works in the commutative setting. This should be fixed.
In particular, `matrix.mul_vec` gives us a linear equivalence
`matrix m n R ≃ₗ[R] (n → R) →ₗ[Rᵐᵒᵖ] (m → R)`
while `matrix.vec_mul` gives us a linear equivalence
`matrix m n R ≃ₗ[Rᵐᵒᵖ] (m → R) →ₗ[R] (n → R)`.
At present, the first equivalence is developed in detail but only for commutative rings
(and we omit the distinction between `Rᵐᵒᵖ` and `R`),
while the second equivalence is developed only in brief, but for not-necessarily-commutative rings.
Naming is slightly inconsistent between the two developments.
In the original (commutative) development `linear` is abbreviated to `lin`,
although this is not consistent with the rest of mathlib.
In the new (non-commutative) development `linear` is not abbreviated, and declarations use `_right`
to indicate they use the right action of matrices on vectors (via `matrix.vec_mul`).
When the two developments are made uniform, the names should be made uniform, too,
by choosing between `linear` and `lin` consistently,
and (presumably) adding `_left` where necessary.
## Tags
linear_map, matrix, linear_equiv, diagonal, det, trace
-/
noncomputable theory
open linear_map matrix set submodule
open_locale big_operators
open_locale matrix
universes u v w
instance {n m} [fintype m] [decidable_eq m] [fintype n] [decidable_eq n] (R) [fintype R] :
fintype (matrix m n R) := by unfold matrix; apply_instance
section to_matrix_right
variables {R : Type*} [semiring R]
variables {l m n : Type*}
/-- `matrix.vec_mul M` is a linear map. -/
@[simps] def matrix.vec_mul_linear [fintype m] (M : matrix m n R) : (m → R) →ₗ[R] (n → R) :=
{ to_fun := λ x, M.vec_mul x,
map_add' := λ v w, funext (λ i, add_dot_product _ _ _),
map_smul' := λ c v, funext (λ i, smul_dot_product _ _ _) }
variables [fintype m] [decidable_eq m]
@[simp] lemma matrix.vec_mul_std_basis (M : matrix m n R) (i j) :
M.vec_mul (std_basis R (λ _, R) i 1) j = M i j :=
begin
have : (∑ i', (if i = i' then 1 else 0) * M i' j) = M i j,
{ simp_rw [boole_mul, finset.sum_ite_eq, finset.mem_univ, if_true] },
convert this,
ext,
split_ifs with h; simp only [std_basis_apply],
{ rw [h, function.update_same] },
{ rw [function.update_noteq (ne.symm h), pi.zero_apply] }
end
/--
Linear maps `(m → R) →ₗ[R] (n → R)` are linearly equivalent over `Rᵐᵒᵖ` to `matrix m n R`,
by having matrices act by right multiplication.
-/
def linear_map.to_matrix_right' : ((m → R) →ₗ[R] (n → R)) ≃ₗ[Rᵐᵒᵖ] matrix m n R :=
{ to_fun := λ f i j, f (std_basis R (λ _, R) i 1) j,
inv_fun := matrix.vec_mul_linear,
right_inv := λ M, by
{ ext i j, simp only [matrix.vec_mul_std_basis, matrix.vec_mul_linear_apply] },
left_inv := λ f, begin
apply (pi.basis_fun R m).ext,
intro j, ext i,
simp only [pi.basis_fun_apply, matrix.vec_mul_std_basis, matrix.vec_mul_linear_apply]
end,
map_add' := λ f g, by { ext i j, simp only [pi.add_apply, linear_map.add_apply] },
map_smul' := λ c f, by { ext i j, simp only [pi.smul_apply, linear_map.smul_apply,
ring_hom.id_apply] } }
/-- A `matrix m n R` is linearly equivalent over `Rᵐᵒᵖ` to a linear map `(m → R) →ₗ[R] (n → R)`,
by having matrices act by right multiplication. -/
abbreviation matrix.to_linear_map_right' : matrix m n R ≃ₗ[Rᵐᵒᵖ] ((m → R) →ₗ[R] (n → R)) :=
linear_map.to_matrix_right'.symm
@[simp] lemma matrix.to_linear_map_right'_apply (M : matrix m n R) (v : m → R) :
matrix.to_linear_map_right' M v = M.vec_mul v := rfl
@[simp] lemma matrix.to_linear_map_right'_mul [fintype l] [decidable_eq l] (M : matrix l m R)
(N : matrix m n R) : matrix.to_linear_map_right' (M ⬝ N) =
(matrix.to_linear_map_right' N).comp (matrix.to_linear_map_right' M) :=
linear_map.ext $ λ x, (vec_mul_vec_mul _ M N).symm
lemma matrix.to_linear_map_right'_mul_apply [fintype l] [decidable_eq l] (M : matrix l m R)
(N : matrix m n R) (x) : matrix.to_linear_map_right' (M ⬝ N) x =
(matrix.to_linear_map_right' N (matrix.to_linear_map_right' M x)) :=
(vec_mul_vec_mul _ M N).symm
@[simp] lemma matrix.to_linear_map_right'_one :
matrix.to_linear_map_right' (1 : matrix m m R) = id :=
by { ext, simp [linear_map.one_apply, std_basis_apply] }
/-- If `M` and `M'` are each other's inverse matrices, they provide an equivalence between `n → A`
and `m → A` corresponding to `M.vec_mul` and `M'.vec_mul`. -/
@[simps]
def matrix.to_linear_equiv_right'_of_inv [fintype n] [decidable_eq n]
{M : matrix m n R} {M' : matrix n m R}
(hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) :
(n → R) ≃ₗ[R] (m → R) :=
{ to_fun := M'.to_linear_map_right',
inv_fun := M.to_linear_map_right',
left_inv := λ x, by
rw [← matrix.to_linear_map_right'_mul_apply, hM'M, matrix.to_linear_map_right'_one, id_apply],
right_inv := λ x, by
rw [← matrix.to_linear_map_right'_mul_apply, hMM', matrix.to_linear_map_right'_one, id_apply],
..linear_map.to_matrix_right'.symm M' }
end to_matrix_right
/-!
From this point on, we only work with commutative rings,
and fail to distinguish between `Rᵐᵒᵖ` and `R`.
This should eventually be remedied.
-/
section to_matrix'
variables {R : Type*} [comm_semiring R]
variables {k l m n : Type*}
/-- `matrix.mul_vec M` is a linear map. -/
def matrix.mul_vec_lin [fintype n] (M : matrix m n R) : (n → R) →ₗ[R] (m → R) :=
{ to_fun := M.mul_vec,
map_add' := λ v w, funext (λ i, dot_product_add _ _ _),
map_smul' := λ c v, funext (λ i, dot_product_smul _ _ _) }
@[simp] lemma matrix.mul_vec_lin_apply [fintype n] (M : matrix m n R) (v : n → R) :
M.mul_vec_lin v = M.mul_vec v := rfl
@[simp] lemma matrix.mul_vec_lin_zero [fintype n] : matrix.mul_vec_lin (0 : matrix m n R) = 0 :=
linear_map.ext zero_mul_vec
@[simp] lemma matrix.mul_vec_lin_add [fintype n] (M N : matrix m n R) :
(M + N).mul_vec_lin = M.mul_vec_lin + N.mul_vec_lin :=
linear_map.ext $ λ _, add_mul_vec _ _ _
lemma matrix.mul_vec_lin_submatrix [fintype n] [fintype l] (f₁ : m → k) (e₂ : n ≃ l)
(M : matrix k l R) :
(M.submatrix f₁ e₂).mul_vec_lin = fun_left R R f₁ ∘ₗ M.mul_vec_lin ∘ₗ fun_left _ _ e₂.symm :=
linear_map.ext $ λ x, submatrix_mul_vec_equiv _ _ _ _
/-- A variant of `matrix.mul_vec_lin_submatrix` that keeps around `linear_equiv`s. -/
lemma matrix.mul_vec_lin_reindex [fintype n] [fintype l] (e₁ : k ≃ m) (e₂ : l ≃ n)
(M : matrix k l R) :
(reindex e₁ e₂ M).mul_vec_lin = ↑(linear_equiv.fun_congr_left R R e₁.symm)
∘ₗ M.mul_vec_lin ∘ₗ ↑(linear_equiv.fun_congr_left R R e₂) :=
matrix.mul_vec_lin_submatrix _ _ _
variables [fintype n]
@[simp] lemma matrix.mul_vec_lin_one [decidable_eq n] :
matrix.mul_vec_lin (1 : matrix n n R) = id :=
by { ext, simp [linear_map.one_apply, std_basis_apply] }
@[simp] lemma matrix.mul_vec_lin_mul [fintype m] (M : matrix l m R)
(N : matrix m n R) :
matrix.mul_vec_lin (M ⬝ N) = (matrix.mul_vec_lin M).comp (matrix.mul_vec_lin N) :=
linear_map.ext $ λ x, (mul_vec_mul_vec _ _ _).symm
lemma matrix.ker_mul_vec_lin_eq_bot_iff {M : matrix n n R} :
M.mul_vec_lin.ker = ⊥ ↔ ∀ v, M.mul_vec v = 0 → v = 0 :=
by simp only [submodule.eq_bot_iff, linear_map.mem_ker, matrix.mul_vec_lin_apply]
lemma matrix.mul_vec_std_basis [decidable_eq n] (M : matrix m n R) (i j) :
M.mul_vec (std_basis R (λ _, R) j 1) i = M i j :=
(congr_fun (matrix.mul_vec_single _ _ (1 : R)) i).trans $ mul_one _
@[simp] lemma matrix.mul_vec_std_basis_apply [decidable_eq n] (M : matrix m n R) (j) :
M.mul_vec (std_basis R (λ _, R) j 1) = Mᵀ j :=
funext $ λ i, matrix.mul_vec_std_basis M i j
lemma matrix.range_mul_vec_lin (M : matrix m n R) : M.mul_vec_lin.range = span R (range Mᵀ) :=
begin
letI := classical.dec_eq n,
simp_rw [range_eq_map, ←supr_range_std_basis, submodule.map_supr, range_eq_map,
←ideal.span_singleton_one, ideal.span, submodule.map_span, image_image, image_singleton,
matrix.mul_vec_lin_apply, M.mul_vec_std_basis_apply, supr_span, range_eq_Union]
end
variables [decidable_eq n]
/-- Linear maps `(n → R) →ₗ[R] (m → R)` are linearly equivalent to `matrix m n R`. -/
def linear_map.to_matrix' : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] matrix m n R :=
{ to_fun := λ f, of (λ i j, f (std_basis R (λ _, R) j 1) i),
inv_fun := matrix.mul_vec_lin,
right_inv := λ M, by { ext i j, simp only [matrix.mul_vec_std_basis, matrix.mul_vec_lin_apply,
of_apply] },
left_inv := λ f, begin
apply (pi.basis_fun R n).ext,
intro j, ext i,
simp only [pi.basis_fun_apply, matrix.mul_vec_std_basis, matrix.mul_vec_lin_apply,
of_apply]
end,
map_add' := λ f g, by { ext i j, simp only [pi.add_apply, linear_map.add_apply, of_apply] },
map_smul' := λ c f, by { ext i j, simp only [pi.smul_apply, linear_map.smul_apply,
ring_hom.id_apply, of_apply] } }
/-- A `matrix m n R` is linearly equivalent to a linear map `(n → R) →ₗ[R] (m → R)`.
Note that the forward-direction does not require `decidable_eq` and is `matrix.vec_mul_lin`. -/
def matrix.to_lin' : matrix m n R ≃ₗ[R] ((n → R) →ₗ[R] (m → R)) :=
linear_map.to_matrix'.symm
lemma matrix.to_lin'_apply' (M : matrix m n R) : matrix.to_lin' M = M.mul_vec_lin := rfl
@[simp] lemma linear_map.to_matrix'_symm :
(linear_map.to_matrix'.symm : matrix m n R ≃ₗ[R] _) = matrix.to_lin' :=
rfl
@[simp] lemma matrix.to_lin'_symm :
(matrix.to_lin'.symm : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] _) = linear_map.to_matrix' :=
rfl
@[simp] lemma linear_map.to_matrix'_to_lin' (M : matrix m n R) :
linear_map.to_matrix' (matrix.to_lin' M) = M :=
linear_map.to_matrix'.apply_symm_apply M
@[simp] lemma matrix.to_lin'_to_matrix' (f : (n → R) →ₗ[R] (m → R)) :
matrix.to_lin' (linear_map.to_matrix' f) = f :=
matrix.to_lin'.apply_symm_apply f
@[simp] lemma linear_map.to_matrix'_apply (f : (n → R) →ₗ[R] (m → R)) (i j) :
linear_map.to_matrix' f i j = f (λ j', if j' = j then 1 else 0) i :=
begin
simp only [linear_map.to_matrix', linear_equiv.coe_mk, of_apply],
congr,
ext j',
split_ifs with h,
{ rw [h, std_basis_same] },
apply std_basis_ne _ _ _ _ h
end
@[simp] lemma matrix.to_lin'_apply (M : matrix m n R) (v : n → R) :
matrix.to_lin' M v = M.mul_vec v := rfl
@[simp] lemma matrix.to_lin'_one :
matrix.to_lin' (1 : matrix n n R) = id := matrix.mul_vec_lin_one
@[simp] lemma linear_map.to_matrix'_id :
(linear_map.to_matrix' (linear_map.id : (n → R) →ₗ[R] (n → R))) = 1 :=
by { ext, rw [matrix.one_apply, linear_map.to_matrix'_apply, id_apply] }
@[simp] lemma matrix.to_lin'_mul [fintype m] [decidable_eq m] (M : matrix l m R)
(N : matrix m n R) : matrix.to_lin' (M ⬝ N) = (matrix.to_lin' M).comp (matrix.to_lin' N) :=
matrix.mul_vec_lin_mul _ _
@[simp] lemma matrix.to_lin'_submatrix [fintype l] [decidable_eq l] (f₁ : m → k) (e₂ : n ≃ l)
(M : matrix k l R) :
(M.submatrix f₁ e₂).to_lin' = fun_left R R f₁ ∘ₗ M.to_lin' ∘ₗ fun_left _ _ e₂.symm :=
matrix.mul_vec_lin_submatrix _ _ _
/-- A variant of `matrix.to_lin'_submatrix` that keeps around `linear_equiv`s. -/
lemma matrix.to_lin'_reindex [fintype l] [decidable_eq l] (e₁ : k ≃ m) (e₂ : l ≃ n)
(M : matrix k l R) :
(reindex e₁ e₂ M).to_lin' = ↑(linear_equiv.fun_congr_left R R e₁.symm)
∘ₗ M.to_lin' ∘ₗ ↑(linear_equiv.fun_congr_left R R e₂) :=
matrix.mul_vec_lin_reindex _ _ _
/-- Shortcut lemma for `matrix.to_lin'_mul` and `linear_map.comp_apply` -/
lemma matrix.to_lin'_mul_apply [fintype m] [decidable_eq m] (M : matrix l m R)
(N : matrix m n R) (x) : matrix.to_lin' (M ⬝ N) x = (matrix.to_lin' M (matrix.to_lin' N x)) :=
by rw [matrix.to_lin'_mul, linear_map.comp_apply]
lemma linear_map.to_matrix'_comp [fintype l] [decidable_eq l]
(f : (n → R) →ₗ[R] (m → R)) (g : (l → R) →ₗ[R] (n → R)) :
(f.comp g).to_matrix' = f.to_matrix' ⬝ g.to_matrix' :=
suffices (f.comp g) = (f.to_matrix' ⬝ g.to_matrix').to_lin',
by rw [this, linear_map.to_matrix'_to_lin'],
by rw [matrix.to_lin'_mul, matrix.to_lin'_to_matrix', matrix.to_lin'_to_matrix']
lemma linear_map.to_matrix'_mul [fintype m] [decidable_eq m]
(f g : (m → R) →ₗ[R] (m → R)) :
(f * g).to_matrix' = f.to_matrix' ⬝ g.to_matrix' :=
linear_map.to_matrix'_comp f g
@[simp] lemma linear_map.to_matrix'_algebra_map (x : R) :
linear_map.to_matrix' (algebra_map R (module.End R (n → R)) x) = scalar n x :=
by simp [module.algebra_map_End_eq_smul_id]
lemma matrix.ker_to_lin'_eq_bot_iff {M : matrix n n R} :
M.to_lin'.ker = ⊥ ↔ ∀ v, M.mul_vec v = 0 → v = 0 :=
matrix.ker_mul_vec_lin_eq_bot_iff
lemma matrix.range_to_lin' (M : matrix m n R) : M.to_lin'.range = span R (range Mᵀ) :=
matrix.range_mul_vec_lin _
/-- If `M` and `M'` are each other's inverse matrices, they provide an equivalence between `m → A`
and `n → A` corresponding to `M.mul_vec` and `M'.mul_vec`. -/
@[simps]
def matrix.to_lin'_of_inv [fintype m] [decidable_eq m]
{M : matrix m n R} {M' : matrix n m R}
(hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) :
(m → R) ≃ₗ[R] (n → R) :=
{ to_fun := matrix.to_lin' M',
inv_fun := M.to_lin',
left_inv := λ x, by rw [← matrix.to_lin'_mul_apply, hMM', matrix.to_lin'_one, id_apply],
right_inv := λ x, by rw [← matrix.to_lin'_mul_apply, hM'M, matrix.to_lin'_one, id_apply],
.. matrix.to_lin' M' }
/-- Linear maps `(n → R) →ₗ[R] (n → R)` are algebra equivalent to `matrix n n R`. -/
def linear_map.to_matrix_alg_equiv' : ((n → R) →ₗ[R] (n → R)) ≃ₐ[R] matrix n n R :=
alg_equiv.of_linear_equiv linear_map.to_matrix' linear_map.to_matrix'_mul
linear_map.to_matrix'_algebra_map
/-- A `matrix n n R` is algebra equivalent to a linear map `(n → R) →ₗ[R] (n → R)`. -/
def matrix.to_lin_alg_equiv' : matrix n n R ≃ₐ[R] ((n → R) →ₗ[R] (n → R)) :=
linear_map.to_matrix_alg_equiv'.symm
@[simp] lemma linear_map.to_matrix_alg_equiv'_symm :
(linear_map.to_matrix_alg_equiv'.symm : matrix n n R ≃ₐ[R] _) = matrix.to_lin_alg_equiv' :=
rfl
@[simp] lemma matrix.to_lin_alg_equiv'_symm :
(matrix.to_lin_alg_equiv'.symm : ((n → R) →ₗ[R] (n → R)) ≃ₐ[R] _) =
linear_map.to_matrix_alg_equiv' :=
rfl
@[simp] lemma linear_map.to_matrix_alg_equiv'_to_lin_alg_equiv' (M : matrix n n R) :
linear_map.to_matrix_alg_equiv' (matrix.to_lin_alg_equiv' M) = M :=
linear_map.to_matrix_alg_equiv'.apply_symm_apply M
@[simp] lemma matrix.to_lin_alg_equiv'_to_matrix_alg_equiv' (f : (n → R) →ₗ[R] (n → R)) :
matrix.to_lin_alg_equiv' (linear_map.to_matrix_alg_equiv' f) = f :=
matrix.to_lin_alg_equiv'.apply_symm_apply f
@[simp] lemma linear_map.to_matrix_alg_equiv'_apply (f : (n → R) →ₗ[R] (n → R)) (i j) :
linear_map.to_matrix_alg_equiv' f i j = f (λ j', if j' = j then 1 else 0) i :=
by simp [linear_map.to_matrix_alg_equiv']
@[simp] lemma matrix.to_lin_alg_equiv'_apply (M : matrix n n R) (v : n → R) :
matrix.to_lin_alg_equiv' M v = M.mul_vec v := rfl
@[simp] lemma matrix.to_lin_alg_equiv'_one :
matrix.to_lin_alg_equiv' (1 : matrix n n R) = id :=
matrix.to_lin'_one
@[simp] lemma linear_map.to_matrix_alg_equiv'_id :
(linear_map.to_matrix_alg_equiv' (linear_map.id : (n → R) →ₗ[R] (n → R))) = 1 :=
linear_map.to_matrix'_id
@[simp] lemma matrix.to_lin_alg_equiv'_mul (M N : matrix n n R) :
matrix.to_lin_alg_equiv' (M ⬝ N) =
(matrix.to_lin_alg_equiv' M).comp (matrix.to_lin_alg_equiv' N) :=
matrix.to_lin'_mul _ _
lemma linear_map.to_matrix_alg_equiv'_comp (f g : (n → R) →ₗ[R] (n → R)) :
(f.comp g).to_matrix_alg_equiv' = f.to_matrix_alg_equiv' ⬝ g.to_matrix_alg_equiv' :=
linear_map.to_matrix'_comp _ _
lemma linear_map.to_matrix_alg_equiv'_mul
(f g : (n → R) →ₗ[R] (n → R)) :
(f * g).to_matrix_alg_equiv' = f.to_matrix_alg_equiv' ⬝ g.to_matrix_alg_equiv' :=
linear_map.to_matrix_alg_equiv'_comp f g
end to_matrix'
section to_matrix
variables {R : Type*} [comm_semiring R]
variables {l m n : Type*} [fintype n] [fintype m] [decidable_eq n]
variables {M₁ M₂ : Type*} [add_comm_monoid M₁] [add_comm_monoid M₂] [module R M₁] [module R M₂]
variables (v₁ : basis n R M₁) (v₂ : basis m R M₂)
/-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear
equivalence between linear maps `M₁ →ₗ M₂` and matrices over `R` indexed by the bases. -/
def linear_map.to_matrix : (M₁ →ₗ[R] M₂) ≃ₗ[R] matrix m n R :=
linear_equiv.trans (linear_equiv.arrow_congr v₁.equiv_fun v₂.equiv_fun) linear_map.to_matrix'
/-- `linear_map.to_matrix'` is a particular case of `linear_map.to_matrix`, for the standard basis
`pi.basis_fun R n`. -/
lemma linear_map.to_matrix_eq_to_matrix' :
linear_map.to_matrix (pi.basis_fun R n) (pi.basis_fun R n) = linear_map.to_matrix' :=
rfl
/-- Given bases of two modules `M₁` and `M₂` over a commutative ring `R`, we get a linear
equivalence between matrices over `R` indexed by the bases and linear maps `M₁ →ₗ M₂`. -/
def matrix.to_lin : matrix m n R ≃ₗ[R] (M₁ →ₗ[R] M₂) :=
(linear_map.to_matrix v₁ v₂).symm
/-- `matrix.to_lin'` is a particular case of `matrix.to_lin`, for the standard basis
`pi.basis_fun R n`. -/
lemma matrix.to_lin_eq_to_lin' :
matrix.to_lin (pi.basis_fun R n) (pi.basis_fun R m) = matrix.to_lin' :=
rfl
@[simp] lemma linear_map.to_matrix_symm :
(linear_map.to_matrix v₁ v₂).symm = matrix.to_lin v₁ v₂ :=
rfl
@[simp] lemma matrix.to_lin_symm :
(matrix.to_lin v₁ v₂).symm = linear_map.to_matrix v₁ v₂ :=
rfl
@[simp] lemma matrix.to_lin_to_matrix (f : M₁ →ₗ[R] M₂) :
matrix.to_lin v₁ v₂ (linear_map.to_matrix v₁ v₂ f) = f :=
by rw [← matrix.to_lin_symm, linear_equiv.apply_symm_apply]
@[simp] lemma linear_map.to_matrix_to_lin (M : matrix m n R) :
linear_map.to_matrix v₁ v₂ (matrix.to_lin v₁ v₂ M) = M :=
by rw [← matrix.to_lin_symm, linear_equiv.symm_apply_apply]
lemma linear_map.to_matrix_apply (f : M₁ →ₗ[R] M₂) (i : m) (j : n) :
linear_map.to_matrix v₁ v₂ f i j = v₂.repr (f (v₁ j)) i :=
begin
rw [linear_map.to_matrix, linear_equiv.trans_apply, linear_map.to_matrix'_apply,
linear_equiv.arrow_congr_apply, basis.equiv_fun_symm_apply, finset.sum_eq_single j,
if_pos rfl, one_smul, basis.equiv_fun_apply],
{ intros j' _ hj',
rw [if_neg hj', zero_smul] },
{ intro hj,
have := finset.mem_univ j,
contradiction }
end
lemma linear_map.to_matrix_transpose_apply (f : M₁ →ₗ[R] M₂) (j : n) :
(linear_map.to_matrix v₁ v₂ f)ᵀ j = v₂.repr (f (v₁ j)) :=
funext $ λ i, f.to_matrix_apply _ _ i j
lemma linear_map.to_matrix_apply' (f : M₁ →ₗ[R] M₂) (i : m) (j : n) :
linear_map.to_matrix v₁ v₂ f i j = v₂.repr (f (v₁ j)) i :=
linear_map.to_matrix_apply v₁ v₂ f i j
lemma linear_map.to_matrix_transpose_apply' (f : M₁ →ₗ[R] M₂) (j : n) :
(linear_map.to_matrix v₁ v₂ f)ᵀ j = v₂.repr (f (v₁ j)) :=
linear_map.to_matrix_transpose_apply v₁ v₂ f j
lemma matrix.to_lin_apply (M : matrix m n R) (v : M₁) :
matrix.to_lin v₁ v₂ M v = ∑ j, M.mul_vec (v₁.repr v) j • v₂ j :=
show v₂.equiv_fun.symm (matrix.to_lin' M (v₁.repr v)) = _,
by rw [matrix.to_lin'_apply, v₂.equiv_fun_symm_apply]
@[simp] lemma matrix.to_lin_self (M : matrix m n R) (i : n) :
matrix.to_lin v₁ v₂ M (v₁ i) = ∑ j, M j i • v₂ j :=
begin
rw [matrix.to_lin_apply, finset.sum_congr rfl (λ j hj, _)],
rw [basis.repr_self, matrix.mul_vec, dot_product, finset.sum_eq_single i,
finsupp.single_eq_same, mul_one],
{ intros i' _ i'_ne, rw [finsupp.single_eq_of_ne i'_ne.symm, mul_zero] },
{ intros,
have := finset.mem_univ i,
contradiction },
end
/-- This will be a special case of `linear_map.to_matrix_id_eq_basis_to_matrix`. -/
lemma linear_map.to_matrix_id : linear_map.to_matrix v₁ v₁ id = 1 :=
begin
ext i j,
simp [linear_map.to_matrix_apply, matrix.one_apply, finsupp.single_apply, eq_comm]
end
lemma linear_map.to_matrix_one : linear_map.to_matrix v₁ v₁ 1 = 1 :=
linear_map.to_matrix_id v₁
@[simp]
lemma matrix.to_lin_one : matrix.to_lin v₁ v₁ 1 = id :=
by rw [← linear_map.to_matrix_id v₁, matrix.to_lin_to_matrix]
theorem linear_map.to_matrix_reindex_range [decidable_eq M₁] [decidable_eq M₂]
(f : M₁ →ₗ[R] M₂) (k : m) (i : n) :
linear_map.to_matrix v₁.reindex_range v₂.reindex_range f
⟨v₂ k, mem_range_self k⟩ ⟨v₁ i, mem_range_self i⟩ =
linear_map.to_matrix v₁ v₂ f k i :=
by simp_rw [linear_map.to_matrix_apply, basis.reindex_range_self, basis.reindex_range_repr]
variables {M₃ : Type*} [add_comm_monoid M₃] [module R M₃] (v₃ : basis l R M₃)
lemma linear_map.to_matrix_comp [fintype l] [decidable_eq m] (f : M₂ →ₗ[R] M₃) (g : M₁ →ₗ[R] M₂) :
linear_map.to_matrix v₁ v₃ (f.comp g) =
linear_map.to_matrix v₂ v₃ f ⬝ linear_map.to_matrix v₁ v₂ g :=
by simp_rw [linear_map.to_matrix, linear_equiv.trans_apply,
linear_equiv.arrow_congr_comp _ v₂.equiv_fun, linear_map.to_matrix'_comp]
lemma linear_map.to_matrix_mul (f g : M₁ →ₗ[R] M₁) :
linear_map.to_matrix v₁ v₁ (f * g) =
linear_map.to_matrix v₁ v₁ f ⬝ linear_map.to_matrix v₁ v₁ g :=
by { rw [show (@has_mul.mul (M₁ →ₗ[R] M₁) _) = linear_map.comp, from rfl,
linear_map.to_matrix_comp v₁ v₁ v₁ f g] }
@[simp] lemma linear_map.to_matrix_algebra_map (x : R) :
linear_map.to_matrix v₁ v₁ (algebra_map R (module.End R M₁) x) = scalar n x :=
by simp [module.algebra_map_End_eq_smul_id, linear_map.to_matrix_id]
lemma linear_map.to_matrix_mul_vec_repr (f : M₁ →ₗ[R] M₂) (x : M₁) :
(linear_map.to_matrix v₁ v₂ f).mul_vec (v₁.repr x) = v₂.repr (f x) :=
by { ext i,
rw [← matrix.to_lin'_apply, linear_map.to_matrix, linear_equiv.trans_apply,
matrix.to_lin'_to_matrix', linear_equiv.arrow_congr_apply, v₂.equiv_fun_apply],
congr,
exact v₁.equiv_fun.symm_apply_apply x }
@[simp] lemma linear_map.to_matrix_basis_equiv [fintype l] [decidable_eq l]
(b : basis l R M₁) (b' : basis l R M₂) :
linear_map.to_matrix b' b (b'.equiv b (equiv.refl l) : M₂ →ₗ[R] M₁) = 1 :=
begin
ext i j,
simp [linear_map.to_matrix_apply, matrix.one_apply, finsupp.single_apply, eq_comm],
end
lemma matrix.to_lin_mul [fintype l] [decidable_eq m] (A : matrix l m R) (B : matrix m n R) :
matrix.to_lin v₁ v₃ (A ⬝ B) =
(matrix.to_lin v₂ v₃ A).comp (matrix.to_lin v₁ v₂ B) :=
begin
apply (linear_map.to_matrix v₁ v₃).injective,
haveI : decidable_eq l := λ _ _, classical.prop_decidable _,
rw linear_map.to_matrix_comp v₁ v₂ v₃,
repeat { rw linear_map.to_matrix_to_lin },
end
/-- Shortcut lemma for `matrix.to_lin_mul` and `linear_map.comp_apply`. -/
lemma matrix.to_lin_mul_apply [fintype l] [decidable_eq m]
(A : matrix l m R) (B : matrix m n R) (x) :
matrix.to_lin v₁ v₃ (A ⬝ B) x =
(matrix.to_lin v₂ v₃ A) (matrix.to_lin v₁ v₂ B x) :=
by rw [matrix.to_lin_mul v₁ v₂, linear_map.comp_apply]
/-- If `M` and `M` are each other's inverse matrices, `matrix.to_lin M` and `matrix.to_lin M'`
form a linear equivalence. -/
@[simps]
def matrix.to_lin_of_inv [decidable_eq m]
{M : matrix m n R} {M' : matrix n m R}
(hMM' : M ⬝ M' = 1) (hM'M : M' ⬝ M = 1) :
M₁ ≃ₗ[R] M₂ :=
{ to_fun := matrix.to_lin v₁ v₂ M,
inv_fun := matrix.to_lin v₂ v₁ M',
left_inv := λ x, by rw [← matrix.to_lin_mul_apply, hM'M, matrix.to_lin_one, id_apply],
right_inv := λ x, by rw [← matrix.to_lin_mul_apply, hMM', matrix.to_lin_one, id_apply],
.. matrix.to_lin v₁ v₂ M }
/-- Given a basis of a module `M₁` over a commutative ring `R`, we get an algebra
equivalence between linear maps `M₁ →ₗ M₁` and square matrices over `R` indexed by the basis. -/
def linear_map.to_matrix_alg_equiv :
(M₁ →ₗ[R] M₁) ≃ₐ[R] matrix n n R :=
alg_equiv.of_linear_equiv (linear_map.to_matrix v₁ v₁) (linear_map.to_matrix_mul v₁)
(linear_map.to_matrix_algebra_map v₁)
/-- Given a basis of a module `M₁` over a commutative ring `R`, we get an algebra
equivalence between square matrices over `R` indexed by the basis and linear maps `M₁ →ₗ M₁`. -/
def matrix.to_lin_alg_equiv : matrix n n R ≃ₐ[R] (M₁ →ₗ[R] M₁) :=
(linear_map.to_matrix_alg_equiv v₁).symm
@[simp] lemma linear_map.to_matrix_alg_equiv_symm :
(linear_map.to_matrix_alg_equiv v₁).symm = matrix.to_lin_alg_equiv v₁ :=
rfl
@[simp] lemma matrix.to_lin_alg_equiv_symm :
(matrix.to_lin_alg_equiv v₁).symm = linear_map.to_matrix_alg_equiv v₁ :=
rfl
@[simp] lemma matrix.to_lin_alg_equiv_to_matrix_alg_equiv (f : M₁ →ₗ[R] M₁) :
matrix.to_lin_alg_equiv v₁ (linear_map.to_matrix_alg_equiv v₁ f) = f :=
by rw [← matrix.to_lin_alg_equiv_symm, alg_equiv.apply_symm_apply]
@[simp] lemma linear_map.to_matrix_alg_equiv_to_lin_alg_equiv (M : matrix n n R) :
linear_map.to_matrix_alg_equiv v₁ (matrix.to_lin_alg_equiv v₁ M) = M :=
by rw [← matrix.to_lin_alg_equiv_symm, alg_equiv.symm_apply_apply]
lemma linear_map.to_matrix_alg_equiv_apply (f : M₁ →ₗ[R] M₁) (i j : n) :
linear_map.to_matrix_alg_equiv v₁ f i j = v₁.repr (f (v₁ j)) i :=
by simp [linear_map.to_matrix_alg_equiv, linear_map.to_matrix_apply]
lemma linear_map.to_matrix_alg_equiv_transpose_apply (f : M₁ →ₗ[R] M₁) (j : n) :
(linear_map.to_matrix_alg_equiv v₁ f)ᵀ j = v₁.repr (f (v₁ j)) :=
funext $ λ i, f.to_matrix_apply _ _ i j
lemma linear_map.to_matrix_alg_equiv_apply' (f : M₁ →ₗ[R] M₁) (i j : n) :
linear_map.to_matrix_alg_equiv v₁ f i j = v₁.repr (f (v₁ j)) i :=
linear_map.to_matrix_alg_equiv_apply v₁ f i j
lemma linear_map.to_matrix_alg_equiv_transpose_apply' (f : M₁ →ₗ[R] M₁) (j : n) :
(linear_map.to_matrix_alg_equiv v₁ f)ᵀ j = v₁.repr (f (v₁ j)) :=
linear_map.to_matrix_alg_equiv_transpose_apply v₁ f j
lemma matrix.to_lin_alg_equiv_apply (M : matrix n n R) (v : M₁) :
matrix.to_lin_alg_equiv v₁ M v = ∑ j, M.mul_vec (v₁.repr v) j • v₁ j :=
show v₁.equiv_fun.symm (matrix.to_lin_alg_equiv' M (v₁.repr v)) = _,
by rw [matrix.to_lin_alg_equiv'_apply, v₁.equiv_fun_symm_apply]
@[simp] lemma matrix.to_lin_alg_equiv_self (M : matrix n n R) (i : n) :
matrix.to_lin_alg_equiv v₁ M (v₁ i) = ∑ j, M j i • v₁ j :=
matrix.to_lin_self _ _ _ _
lemma linear_map.to_matrix_alg_equiv_id : linear_map.to_matrix_alg_equiv v₁ id = 1 :=
by simp_rw [linear_map.to_matrix_alg_equiv, alg_equiv.of_linear_equiv_apply,
linear_map.to_matrix_id]
@[simp]
lemma matrix.to_lin_alg_equiv_one : matrix.to_lin_alg_equiv v₁ 1 = id :=
by rw [← linear_map.to_matrix_alg_equiv_id v₁, matrix.to_lin_alg_equiv_to_matrix_alg_equiv]
theorem linear_map.to_matrix_alg_equiv_reindex_range [decidable_eq M₁]
(f : M₁ →ₗ[R] M₁) (k i : n) :
linear_map.to_matrix_alg_equiv v₁.reindex_range f
⟨v₁ k, mem_range_self k⟩ ⟨v₁ i, mem_range_self i⟩ =
linear_map.to_matrix_alg_equiv v₁ f k i :=
by simp_rw [linear_map.to_matrix_alg_equiv_apply,
basis.reindex_range_self, basis.reindex_range_repr]
lemma linear_map.to_matrix_alg_equiv_comp (f g : M₁ →ₗ[R] M₁) :
linear_map.to_matrix_alg_equiv v₁ (f.comp g) =
linear_map.to_matrix_alg_equiv v₁ f ⬝ linear_map.to_matrix_alg_equiv v₁ g :=
by simp [linear_map.to_matrix_alg_equiv, linear_map.to_matrix_comp v₁ v₁ v₁ f g]
lemma linear_map.to_matrix_alg_equiv_mul (f g : M₁ →ₗ[R] M₁) :
linear_map.to_matrix_alg_equiv v₁ (f * g) =
linear_map.to_matrix_alg_equiv v₁ f ⬝ linear_map.to_matrix_alg_equiv v₁ g :=
by { rw [show (@has_mul.mul (M₁ →ₗ[R] M₁) _) = linear_map.comp, from rfl,
linear_map.to_matrix_alg_equiv_comp v₁ f g] }
lemma matrix.to_lin_alg_equiv_mul (A B : matrix n n R) :
matrix.to_lin_alg_equiv v₁ (A ⬝ B) =
(matrix.to_lin_alg_equiv v₁ A).comp (matrix.to_lin_alg_equiv v₁ B) :=
by convert matrix.to_lin_mul v₁ v₁ v₁ A B
@[simp] lemma matrix.to_lin_fin_two_prod_apply (a b c d : R) (x : R × R) :
matrix.to_lin (basis.fin_two_prod R) (basis.fin_two_prod R) !![a, b; c, d] x =
(a * x.fst + b * x.snd, c * x.fst + d * x.snd) :=
by simp [matrix.to_lin_apply, matrix.mul_vec, matrix.dot_product]
lemma matrix.to_lin_fin_two_prod (a b c d : R) :
matrix.to_lin (basis.fin_two_prod R) (basis.fin_two_prod R) !![a, b; c, d] =
(a • linear_map.fst R R R + b • linear_map.snd R R R).prod
(c • linear_map.fst R R R + d • linear_map.snd R R R) :=
linear_map.ext $ matrix.to_lin_fin_two_prod_apply _ _ _ _
@[simp] lemma to_matrix_distrib_mul_action_to_linear_map (x : R) :
linear_map.to_matrix v₁ v₁ (distrib_mul_action.to_linear_map R M₁ x) = matrix.diagonal (λ _, x) :=
begin
ext,
rw [linear_map.to_matrix_apply, distrib_mul_action.to_linear_map_apply, linear_equiv.map_smul,
basis.repr_self, finsupp.smul_single_one, finsupp.single_eq_pi_single, matrix.diagonal_apply,
pi.single_apply],
end
end to_matrix
namespace algebra
section lmul
variables {R S : Type*} [comm_ring R] [ring S] [algebra R S]
variables {m : Type*} [fintype m] [decidable_eq m] (b : basis m R S)
lemma to_matrix_lmul' (x : S) (i j) :
linear_map.to_matrix b b (lmul R S x) i j = b.repr (x * b j) i :=
by simp only [linear_map.to_matrix_apply', coe_lmul_eq_mul, linear_map.mul_apply']
@[simp] lemma to_matrix_lsmul (x : R) :
linear_map.to_matrix b b (algebra.lsmul R S x) = matrix.diagonal (λ _, x) :=
to_matrix_distrib_mul_action_to_linear_map b x
/-- `left_mul_matrix b x` is the matrix corresponding to the linear map `λ y, x * y`.
`left_mul_matrix_eq_repr_mul` gives a formula for the entries of `left_mul_matrix`.
This definition is useful for doing (more) explicit computations with `linear_map.mul_left`,
such as the trace form or norm map for algebras.
-/
noncomputable def left_mul_matrix : S →ₐ[R] matrix m m R :=
{ to_fun := λ x, linear_map.to_matrix b b (algebra.lmul R S x),
map_zero' := by rw [alg_hom.map_zero, linear_equiv.map_zero],
map_one' := by rw [alg_hom.map_one, linear_map.to_matrix_one],
map_add' := λ x y, by rw [alg_hom.map_add, linear_equiv.map_add],
map_mul' := λ x y, by rw [alg_hom.map_mul, linear_map.to_matrix_mul, matrix.mul_eq_mul],
commutes' := λ r, by { ext, rw [lmul_algebra_map, to_matrix_lsmul, algebra_map_eq_diagonal,
pi.algebra_map_def, algebra.id.map_eq_self] } }
lemma left_mul_matrix_apply (x : S) :
left_mul_matrix b x = linear_map.to_matrix b b (lmul R S x) := rfl
lemma left_mul_matrix_eq_repr_mul (x : S) (i j) :
left_mul_matrix b x i j = b.repr (x * b j) i :=
-- This is defeq to just `to_matrix_lmul' b x i j`,
-- but the unfolding goes a lot faster with this explicit `rw`.
by rw [left_mul_matrix_apply, to_matrix_lmul' b x i j]
lemma left_mul_matrix_mul_vec_repr (x y : S) :
(left_mul_matrix b x).mul_vec (b.repr y) = b.repr (x * y) :=
(linear_map.mul_left R x).to_matrix_mul_vec_repr b b y
@[simp] lemma to_matrix_lmul_eq (x : S) :
linear_map.to_matrix b b (linear_map.mul_left R x) = left_mul_matrix b x :=
rfl
lemma left_mul_matrix_injective : function.injective (left_mul_matrix b) :=
λ x x' h, calc x = algebra.lmul R S x 1 : (mul_one x).symm
... = algebra.lmul R S x' 1 : by rw (linear_map.to_matrix b b).injective h
... = x' : mul_one x'
end lmul
section lmul_tower
variables {R S T : Type*} [comm_ring R] [comm_ring S] [ring T]
variables [algebra R S] [algebra S T] [algebra R T] [is_scalar_tower R S T]
variables {m n : Type*} [fintype m] [fintype n] [decidable_eq m] [decidable_eq n]
variables (b : basis m R S) (c : basis n S T)
lemma smul_left_mul_matrix (x) (ik jk) :
left_mul_matrix (b.smul c) x ik jk =
left_mul_matrix b (left_mul_matrix c x ik.2 jk.2) ik.1 jk.1 :=
by simp only [left_mul_matrix_apply, linear_map.to_matrix_apply, mul_comm, basis.smul_apply,
basis.smul_repr, finsupp.smul_apply, id.smul_eq_mul, linear_equiv.map_smul, mul_smul_comm,
coe_lmul_eq_mul, linear_map.mul_apply']
lemma smul_left_mul_matrix_algebra_map (x : S) :
left_mul_matrix (b.smul c) (algebra_map _ _ x) = block_diagonal (λ k, left_mul_matrix b x) :=
begin
ext ⟨i, k⟩ ⟨j, k'⟩,
rw [smul_left_mul_matrix, alg_hom.commutes, block_diagonal_apply, algebra_map_matrix_apply],
split_ifs with h; simp [h],
end
lemma smul_left_mul_matrix_algebra_map_eq (x : S) (i j k) :
left_mul_matrix (b.smul c) (algebra_map _ _ x) (i, k) (j, k) = left_mul_matrix b x i j :=
by rw [smul_left_mul_matrix_algebra_map, block_diagonal_apply_eq]
lemma smul_left_mul_matrix_algebra_map_ne (x : S) (i j) {k k'}
(h : k ≠ k') : left_mul_matrix (b.smul c) (algebra_map _ _ x) (i, k) (j, k') = 0 :=
by rw [smul_left_mul_matrix_algebra_map, block_diagonal_apply_ne _ _ _ h]
end lmul_tower
end algebra
section
variables {R : Type v} [comm_ring R] {n : Type*} [decidable_eq n]
variables {M M₁ M₂ : Type*} [add_comm_group M] [module R M]
variables [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂]
/-- The natural equivalence between linear endomorphisms of finite free modules and square matrices
is compatible with the algebra structures. -/
def alg_equiv_matrix' [fintype n] : module.End R (n → R) ≃ₐ[R] matrix n n R :=
{ map_mul' := linear_map.to_matrix'_comp,
map_add' := linear_map.to_matrix'.map_add,
commutes' := λ r, by { change (r • (linear_map.id : module.End R _)).to_matrix' = r • 1,
rw ←linear_map.to_matrix'_id, refl, apply_instance },
..linear_map.to_matrix' }
/-- A linear equivalence of two modules induces an equivalence of algebras of their
endomorphisms. -/
def linear_equiv.alg_conj (e : M₁ ≃ₗ[R] M₂) :
module.End R M₁ ≃ₐ[R] module.End R M₂ :=
{ map_mul' := λ f g, by apply e.arrow_congr_comp,
map_add' := e.conj.map_add,
commutes' := λ r, by { change e.conj (r • linear_map.id) = r • linear_map.id,
rw [linear_equiv.map_smul, linear_equiv.conj_id], },
..e.conj }
/-- A basis of a module induces an equivalence of algebras from the endomorphisms of the module to
square matrices. -/
def alg_equiv_matrix [fintype n] (h : basis n R M) : module.End R M ≃ₐ[R] matrix n n R :=
h.equiv_fun.alg_conj.trans alg_equiv_matrix'
end
|
956badfd694b274763d4ba00e093af3f0abf4251 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Init/Tactics.lean | 4936ab13fdc3d029ee3e8a366157d471b8c94dcb | [
"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 | 32,432 | 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
-/
prelude
import Init.Notation
namespace Lean
syntax binderIdent := ident <|> hole
namespace Parser.Tactic
/-- `with_annotate_state stx t` annotates the lexical range of `stx : Syntax` with the initial and final state of running tactic `t`. -/
scoped syntax (name := withAnnotateState) "with_annotate_state " rawStx ppSpace tactic : tactic
/--
Introduce one or more hypotheses, optionally naming and/or pattern-matching them.
For each hypothesis to be introduced, the remaining main goal's target type must be a `let` or function type.
* `intro` by itself introduces one anonymous hypothesis, which can be accessed by e.g. `assumption`.
* `intro x y` introduces two hypotheses and names them. Individual hypotheses can be anonymized via `_`,
or matched against a pattern:
```lean
-- ... ⊢ α × β → ...
intro (a, b)
-- ..., a : α, b : β ⊢ ...
```
* Alternatively, `intro` can be combined with pattern matching much like `fun`:
```lean
intro
| n + 1, 0 => tac
| ...
```
-/
syntax (name := intro) "intro " notFollowedBy("|") (colGt term:max)* : tactic
/-- `intros x...` behaves like `intro x...`, but then keeps introducing (anonymous) hypotheses until goal is not of a function type. -/
syntax (name := intros) "intros " (colGt (ident <|> hole))* : tactic
/--
`rename t => x` renames the most recent hypothesis whose type matches `t` (which may contain placeholders) to `x`,
or fails if no such hypothesis could be found. -/
syntax (name := rename) "rename " term " => " ident : tactic
/-- `revert x...` is the inverse of `intro x...`: it moves the given hypotheses into the main goal's target type. -/
syntax (name := revert) "revert " (colGt term:max)+ : tactic
/-- `clear x...` removes the given hypotheses, or fails if there are remaining references to a hypothesis. -/
syntax (name := clear) "clear " (colGt term:max)+ : tactic
/--
`subst x...` substitutes each `x` with `e` in the goal if there is a hypothesis of type `x = e` or `e = x`.
If `x` is itself a hypothesis of type `y = e` or `e = y`, `y` is substituted instead. -/
syntax (name := subst) "subst " (colGt term:max)+ : tactic
/--
Apply `subst` to all hypotheses of the form `h : x = t` or `h : t = x`.
-/
syntax (name := substVars) "subst_vars" : tactic
/--
`assumption` tries to solve the main goal using a hypothesis of compatible type, or else fails.
Note also the `‹t›` term notation, which is a shorthand for `show t by assumption`. -/
syntax (name := assumption) "assumption" : tactic
/--
`contradiction` closes the main goal if its hypotheses are "trivially contradictory".
- Inductive type/family with no applicable constructors
```lean
example (h : False) : p := by contradiction
```
- Injectivity of constructors
```lean
example (h : none = some true) : p := by contradiction --
```
- Decidable false proposition
```lean
example (h : 2 + 2 = 3) : p := by contradiction
```
- Contradictory hypotheses
```lean
example (h : p) (h' : ¬ p) : q := by contradiction
```
- Other simple contradictions such as
```lean
example (x : Nat) (h : x ≠ x) : p := by contradiction
```
-/
syntax (name := contradiction) "contradiction" : tactic
/--
`apply e` tries to match the current goal against the conclusion of `e`'s type.
If it succeeds, then the tactic returns as many subgoals as the number of premises that
have not been fixed by type inference or type class resolution.
Non-dependent premises are added before dependent ones.
The `apply` tactic uses higher-order pattern matching, type class resolution, and first-order unification with dependent types.
-/
syntax (name := apply) "apply " term : tactic
/--
`exact e` closes the main goal if its target type matches that of `e`.
-/
syntax (name := exact) "exact " term : tactic
/--
`refine e` behaves like `exact e`, except that named (`?x`) or unnamed (`?_`) holes in `e` that are not solved
by unification with the main goal's target type are converted into new goals, using the hole's name, if any, as the goal case name.
-/
syntax (name := refine) "refine " term : tactic
/-- `refine' e` behaves like `refine e`, except that unsolved placeholders (`_`) and implicit parameters are also converted into new goals. -/
syntax (name := refine') "refine' " term : tactic
/-- If the main goal's target type is an inductive type, `constructor` solves it with the first matching constructor, or else fails. -/
syntax (name := constructor) "constructor" : tactic
/--
`case tag => tac` focuses on the goal with case name `tag` and solves it using `tac`, or else fails.
`case tag x₁ ... xₙ => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/
syntax (name := case) "case " binderIdent binderIdent* " => " tacticSeq : tactic
/--
`case'` is similar to the `case tag => tac` tactic, but does not ensure the goal has been solved after applying `tac`, nor
admits the goal if `tac` failed. Recall that `case` closes the goal using `sorry` when `tac` fails, and
the tactic execution is not interrupted.
-/
syntax (name := case') "case' " binderIdent binderIdent* " => " tacticSeq : tactic
/--
`next => tac` focuses on the next goal solves it using `tac`, or else fails.
`next x₁ ... xₙ => tac` additionally renames the `n` most recent hypotheses with inaccessible names to the given names. -/
macro "next " args:binderIdent* " => " tac:tacticSeq : tactic => `(tactic| case _ $args* => $tac)
/-- `all_goals tac` runs `tac` on each goal, concatenating the resulting goals, if any. -/
syntax (name := allGoals) "all_goals " tacticSeq : tactic
/-- `any_goals tac` applies the tactic `tac` to every goal, and succeeds if at least one application succeeds. -/
syntax (name := anyGoals) "any_goals " tacticSeq : tactic
/--
`focus tac` focuses on the main goal, suppressing all other goals, and runs `tac` on it.
Usually `· tac`, which enforces that the goal is closed by `tac`, should be preferred. -/
syntax (name := focus) "focus " tacticSeq : tactic
/-- `skip` does nothing. -/
syntax (name := skip) "skip" : tactic
/-- `done` succeeds iff there are no remaining goals. -/
syntax (name := done) "done" : tactic
/-- `trace_state` displays the current state in the info view. -/
syntax (name := traceState) "trace_state" : tactic
/-- `trace msg` displays `msg` in the info view. -/
syntax (name := traceMessage) "trace " str : tactic
/-- `fail_if_success t` fails if the tactic `t` succeeds. -/
syntax (name := failIfSuccess) "fail_if_success " tacticSeq : tactic
/-- `(tacs)` executes a list of tactics in sequence, without requiring that
the goal be closed at the end like `· tacs`. Like `by` itself, the tactics
can be either separated by newlines or `;`. -/
syntax (name := paren) "(" tacticSeq ")" : tactic
/-- `with_reducible tacs` excutes `tacs` using the reducible transparency setting.
In this setting only definitions tagged as `[reducible]` are unfolded. -/
syntax (name := withReducible) "with_reducible " tacticSeq : tactic
/-- `with_reducible_and_instances tacs` excutes `tacs` using the `.instances` transparency setting.
In this setting only definitions tagged as `[reducible]` or type class instances are unfolded. -/
syntax (name := withReducibleAndInstances) "with_reducible_and_instances " tacticSeq : tactic
/-- `with_unfolding_all tacs` excutes `tacs` using the `.all` transparency setting.
In this setting all definitions that are not opaque are unfolded. -/
syntax (name := withUnfoldingAll) "with_unfolding_all " tacticSeq : tactic
/-- `first | tac | ...` runs each `tac` until one succeeds, or else fails. -/
syntax (name := first) "first " withPosition((colGe "|" tacticSeq)+) : tactic
/-- `rotate_left n` rotates goals to the left by `n`. That is, `rotate_left 1`
takes the main goal and puts it to the back of the subgoal list.
If `n` is omitted, it defaults to `1`. -/
syntax (name := rotateLeft) "rotate_left" (num)? : tactic
/-- Rotate the goals to the right by `n`. That is, take the goal at the back
and push it to the front `n` times. If `n` is omitted, it defaults to `1`. -/
syntax (name := rotateRight) "rotate_right" (num)? : tactic
/-- `try tac` runs `tac` and succeeds even if `tac` failed. -/
macro "try " t:tacticSeq : tactic => `(first | $t | skip)
/-- `tac <;> tac'` runs `tac` on the main goal and `tac'` on each produced goal, concatenating all goals produced by `tac'`. -/
macro:1 x:tactic tk:" <;> " y:tactic:0 : tactic => `(tactic|
focus
$x:tactic
-- annotate token with state after executing `x`
with_annotate_state $tk skip
all_goals $y:tactic)
/-- `eq_refl` is equivalent to `exact rfl`, but has a few optimizations. -/
syntax (name := refl) "eq_refl" : tactic
/--
`rfl` tries to close the current goal using reflexivity.
This is supposed to be an extensible tactic and users can add their own support
for new reflexive relations.
-/
macro "rfl" : tactic => `(eq_refl)
/--
`rfl'` is similar to `rfl`, but disables smart unfolding and unfolds all kinds of definitions,
theorems included (relevant for declarations defined by well-founded recursion). -/
macro "rfl'" : tactic => `(set_option smartUnfolding false in with_unfolding_all rfl)
/-- `ac_rfl` proves equalities up to application of an associative and commutative operator.
```
instance : IsAssociative (α := Nat) (.+.) := ⟨Nat.add_assoc⟩
instance : IsCommutative (α := Nat) (.+.) := ⟨Nat.add_comm⟩
example (a b c d : Nat) : a + b + c + d = d + (b + c) + a := by ac_rfl
```
-/
syntax (name := acRfl) "ac_rfl" : tactic
/-- `admit` is a shorthand for `exact sorry`. -/
macro "admit" : tactic => `(exact @sorryAx _ false)
/-- The `sorry` tactic is a shorthand for `exact sorry`. -/
macro "sorry" : tactic => `(exact @sorryAx _ false)
/-- `infer_instance` is an abbreviation for `exact inferInstance` -/
macro "infer_instance" : tactic => `(exact inferInstance)
/-- Optional configuration option for tactics -/
syntax config := atomic("(" &"config") " := " term ")"
syntax locationWildcard := "*"
syntax locationHyp := (colGt term:max)+ ("⊢" <|> "|-")?
syntax location := withPosition(" at " (locationWildcard <|> locationHyp))
/--
* `change tgt'` will change the goal from `tgt` to `tgt'`,
assuming these are definitionally equal.
* `change t' at h` will change hypothesis `h : t` to have type `t'`, assuming
assuming `t` and `t'` are definitionally equal.
-/
syntax (name := change) "change " term (location)? : tactic
/--
* `change a with b` will change occurrences of `a` to `b` in the goal,
assuming `a` and `b` are are definitionally equal.
* `change a with b at h` similarly changes `a` to `b` in the type of hypothesis `h`.
-/
syntax (name := changeWith) "change " term " with " term (location)? : tactic
syntax rwRule := ("← " <|> "<- ")? term
syntax rwRuleSeq := "[" rwRule,*,? "]"
/--
`rewrite [e]` applies identity `e` as a rewrite rule to the target of the main goal.
If `e` is preceded by left arrow (`←` or `<-`), the rewrite is applied in the reverse direction.
If `e` is a defined constant, then the equational theorems associated with `e` are used. This provides a convenient way to unfold `e`.
- `rewrite [e₁, ..., eₙ]` applies the given rules sequentially.
- `rewrite [e] at l` rewrites `e` at location(s) `l`, where `l` is either `*` or a list of hypotheses in the local context. In the latter case, a turnstile `⊢` or `|-` can also be used, to signify the target of the goal.
-/
syntax (name := rewriteSeq) "rewrite " (config)? rwRuleSeq (location)? : tactic
/--
`rw` is like `rewrite`, but also tries to close the goal by "cheap" (reducible) `rfl` afterwards.
-/
macro (name := rwSeq) "rw " c:(config)? s:rwRuleSeq l:(location)? : tactic =>
match s with
| `(rwRuleSeq| [$rs,*]%$rbrak) =>
-- We show the `rfl` state on `]`
`(tactic| rewrite $(c)? [$rs,*] $(l)?; with_annotate_state $rbrak (try (with_reducible rfl)))
| _ => Macro.throwUnsupported
/--
The `injection` tactic is based on the fact that constructors of inductive data types are injections.
That means that if `c` is a constructor of an inductive datatype, and if `(c t₁)` and `(c t₂)` are two terms that are equal then `t₁` and `t₂` are equal too.
If `q` is a proof of a statement of conclusion `t₁ = t₂`, then injection applies injectivity to derive the equality of all arguments of `t₁` and `t₂`
placed in the same positions. For example, from `(a::b) = (c::d)` we derive `a=c` and `b=d`. To use this tactic `t₁` and `t₂`
should be constructor applications of the same constructor.
Given `h : a::b = c::d`, the tactic `injection h` adds two new hypothesis with types `a = c` and `b = d` to the main goal.
The tactic `injection h with h₁ h₂` uses the names `h₁` and `h₂` to name the new hypotheses.
-/
syntax (name := injection) "injection " term (" with " (colGt (ident <|> hole))+)? : tactic
/-- `injections` applies `injection` to all hypotheses recursively
(since `injection` can produce new hypotheses). Useful for destructing nested
constructor equalities like `(a::b::c) = (d::e::f)`. -/
-- TODO: add with
syntax (name := injections) "injections" : tactic
syntax discharger := atomic("(" (&"discharger" <|> &"disch")) " := " tacticSeq ")"
syntax simpPre := "↓"
syntax simpPost := "↑"
syntax simpLemma := (simpPre <|> simpPost)? ("← " <|> "<- ")? term
syntax simpErase := "-" term:max
syntax simpStar := "*"
/--
The `simp` tactic uses lemmas and hypotheses to simplify the main goal target or non-dependent hypotheses. It has many variants.
- `simp` simplifies the main goal target using lemmas tagged with the attribute `[simp]`.
- `simp [h₁, h₂, ..., hₙ]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and the given `hᵢ`'s, where the `hᵢ`'s are expressions. If an `hᵢ` is a defined constant `f`, then the equational lemmas associated with `f` are used. This provides a convenient way to unfold `f`.
- `simp [*]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]` and all hypotheses.
- `simp only [h₁, h₂, ..., hₙ]` is like `simp [h₁, h₂, ..., hₙ]` but does not use `[simp]` lemmas
- `simp [-id₁, ..., -idₙ]` simplifies the main goal target using the lemmas tagged with the attribute `[simp]`, but removes the ones named `idᵢ`.
- `simp at h₁ h₂ ... hₙ` simplifies the hypotheses `h₁ : T₁` ... `hₙ : Tₙ`. If the target or another hypothesis depends on `hᵢ`, a new simplified hypothesis `hᵢ` is introduced, but the old one remains in the local context.
- `simp at *` simplifies all the hypotheses and the target.
- `simp [*] at *` simplifies target and all (propositional) hypotheses using the other hypotheses.
-/
syntax (name := simp) "simp " (config)? (discharger)? (&"only ")? ("[" (simpStar <|> simpErase <|> simpLemma),* "]")? (location)? : tactic
/--
`simp_all` is a stronger version of `simp [*] at *` where the hypotheses and target are simplified
multiple times until no simplication is applicable.
Only non-dependent propositional hypotheses are considered.
-/
syntax (name := simpAll) "simp_all " (config)? (discharger)? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? : tactic
/--
The `dsimp` tactic is the definitional simplifier. It is similar to `simp` but only applies theorems that hold by
reflexivity. Thus, the result is guaranteed to be definitionally equal to the input.
-/
syntax (name := dsimp) "dsimp " (config)? (discharger)? (&"only ")? ("[" (simpErase <|> simpLemma),* "]")? (location)? : tactic
/--
`delta id` delta-expands the definition `id`.
This is a low-level tactic, it will expose how recursive definitions have been compiled by Lean. -/
syntax (name := delta) "delta " ident (location)? : tactic
/--
`unfold id,+` unfolds definition `id`. For non-recursive definitions, this tactic is identical to `delta`.
For recursive definitions, it hides the encoding tricks used by the Lean frontend to convince the
kernel that the definition terminates. -/
syntax (name := unfold) "unfold " ident,+ (location)? : tactic
/-- Auxiliary macro for lifting have/suffices/let/...
It makes sure the "continuation" `?_` is the main goal after refining. -/
macro "refine_lift " e:term : tactic => `(focus (refine no_implicit_lambda% $e; rotate_right))
/--
`have h : t := e` adds the hypothesis `h : t` to the current goal if `e` a term of type `t`. If `t` is omitted, it will be inferred.
If `h` is omitted, the name `this` is used.
The variant `have pattern := e` is equivalent to `match e with | pattern => _`, and it is convenient for types that have only applicable constructor.
Example: given `h : p ∧ q ∧ r`, `have ⟨h₁, h₂, h₃⟩ := h` produces the hypotheses `h₁ : p`, `h₂ : q`, and `h₃ : r`.
-/
macro "have " d:haveDecl : tactic => `(refine_lift have $d:haveDecl; ?_)
/--
Given a main goal `ctx |- t`, `suffices h : t' from e` replaces the main goal with `ctx |- t'`,
`e` must have type `t` in the context `ctx, h : t'`.
The variant `suffices h : t' by tac` is a shorthand for `suffices h : t' from by tac`.
If `h :` is omitted, the name `this` is used.
-/
macro "suffices " d:sufficesDecl : tactic => `(refine_lift suffices $d; ?_)
/--
`let h : t := e` adds the hypothesis `h : t := e` to the current goal if `e` a term of type `t`.
If `t` is omitted, it will be inferred.
The variant `let pattern := e` is equivalent to `match e with | pattern => _`, and it is convenient for types that have only applicable constructor.
Example: given `h : p ∧ q ∧ r`, `let ⟨h₁, h₂, h₃⟩ := h` produces the hypotheses `h₁ : p`, `h₂ : q`, and `h₃ : r`.
-/
macro "let " d:letDecl : tactic => `(refine_lift let $d:letDecl; ?_)
/--
`show t` finds the first goal whose target unifies with `t`. It makes that the main goal,
performs the unification, and replaces the target with the unified version of `t`.
-/
macro "show " e:term : tactic => `(refine_lift show $e from ?_) -- TODO: fix, see comment
/-- `let rec f : t := e` adds a recursive definition `f` to the current goal.
The syntax is the same as term-mode `let rec`. -/
syntax (name := letrec) withPosition(atomic("let " &"rec ") letRecDecls) : tactic
macro_rules
| `(tactic| let rec $d) => `(tactic| refine_lift let rec $d; ?_)
/-- Similar to `refine_lift`, but using `refine'` -/
macro "refine_lift' " e:term : tactic => `(focus (refine' no_implicit_lambda% $e; rotate_right))
/-- Similar to `have`, but using `refine'` -/
macro "have' " d:haveDecl : tactic => `(refine_lift' have $d:haveDecl; ?_)
/-- Similar to `have`, but using `refine'` -/
macro (priority := high) "have'" x:ident " := " p:term : tactic => `(have' $x : _ := $p)
/-- Similar to `let`, but using `refine'` -/
macro "let' " d:letDecl : tactic => `(refine_lift' let $d:letDecl; ?_)
syntax inductionAltLHS := "| " (("@"? ident) <|> hole) (ident <|> hole)*
syntax inductionAlt := ppDedent(ppLine) inductionAltLHS+ " => " (hole <|> syntheticHole <|> tacticSeq)
syntax inductionAlts := "with " (tactic)? withPosition( (colGe inductionAlt)+)
/--
Assuming `x` is a variable in the local context with an inductive type, `induction x` applies induction on `x` to the main goal,
producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor
and an inductive hypothesis is added for each recursive argument to the constructor.
If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward,
so that the inductive hypothesis incorporates that hypothesis as well.
For example, given `n : Nat` and a goal with a hypothesis `h : P n` and target `Q n`, `induction n` produces one goal
with hypothesis `h : P 0` and target `Q 0`, and one goal with hypotheses `h : P (Nat.succ a)` and `ih₁ : P a → Q a` and target `Q (Nat.succ a)`.
Here the names `a` and `ih₁` are chosen automatically and are not accessible. You can use `with` to provide the variables names for each constructor.
- `induction e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then performs induction on the resulting variable.
- `induction e using r` allows the user to specify the principle of induction that should be used. Here `r` should be a theorem whose result type must be of the form `C t`, where `C` is a bound variable and `t` is a (possibly empty) sequence of bound variables
- `induction e generalizing z₁ ... zₙ`, where `z₁ ... zₙ` are variables in the local context, generalizes over `z₁ ... zₙ` before applying the induction but then introduces them in each goal. In other words, the net effect is that each inductive hypothesis is generalized.
- Given `x : Nat`, `induction x with | zero => tac₁ | succ x' ih => tac₂` uses tactic `tac₁` for the `zero` case, and `tac₂` for the `succ` case.
-/
syntax (name := induction) "induction " term,+ (" using " ident)? ("generalizing " (colGt term:max)+)? (inductionAlts)? : tactic
syntax generalizeArg := atomic(ident " : ")? term:51 " = " ident
/--
`generalize ([h :] e = x),+` replaces all occurrences `e`s in the main goal with a fresh hypothesis `x`s.
If `h` is given, `h : e = x` is introduced as well. -/
syntax (name := generalize) "generalize " generalizeArg,+ : tactic
syntax casesTarget := atomic(ident " : ")? term
/--
Assuming `x` is a variable in the local context with an inductive type, `cases x` splits the main goal,
producing one goal for each constructor of the inductive type, in which the target is replaced by a general instance of that constructor.
If the type of an element in the local context depends on `x`, that element is reverted and reintroduced afterward,
so that the case split affects that hypothesis as well. `cases` detects unreachable cases and closes them automatically.
For example, given `n : Nat` and a goal with a hypothesis `h : P n` and target `Q n`, `cases n` produces one goal with hypothesis `h : P 0` and target `Q 0`,
and one goal with hypothesis `h : P (Nat.succ a)` and target `Q (Nat.succ a)`. Here the name `a` is chosen automatically and are not accessible. You can use `with` to provide the variables names for each constructor.
- `cases e`, where `e` is an expression instead of a variable, generalizes `e` in the goal, and then cases on the resulting variable.
- Given `as : List α`, `cases as with | nil => tac₁ | cons a as' => tac₂`, uses tactic `tac₁` for the `nil` case, and `tac₂` for the `cons` case, and `a` and `as'` are used as names for the new variables introduced.
- `cases h : e`, where `e` is a variable or an expression, performs cases on `e` as above, but also adds a hypothesis `h : e = ...` to each hypothesis, where `...` is the constructor instance for that particular case.
-/
syntax (name := cases) "cases " casesTarget,+ (" using " ident)? (inductionAlts)? : tactic
/-- `rename_i x_1 ... x_n` renames the last `n` inaccessible names using the given names. -/
syntax (name := renameI) "rename_i " (colGt binderIdent)+ : tactic
/--
`repeat tac` applies `tac` to main goal. If the application succeeds,
the tactic is applied recursively to the generated subgoals until it eventually fails.
-/
syntax "repeat " tacticSeq : tactic
macro_rules
| `(tactic| repeat $seq) => `(tactic| first | ($seq); repeat $seq | skip)
/--
`trivial` tries different simple tactics (e.g., `rfl`, `contradiction`, ...) to close the current goal.
You can use the command `macro_rules` to extend the set of tactics used. Example:
```
macro_rules | `(tactic| trivial) => `(tactic| simp)
```
-/
syntax "trivial" : tactic
/--
The `split` tactic is useful for breaking nested if-then-else and match expressions in cases.
For a `match` expression with `n` cases, the `split` tactic generates at most `n` subgoals
-/
syntax (name := split) "split " (colGt term)? (location)? : tactic
/-- `dbg_trace "foo"` prints `foo` when elaborated.
Useful for debugging tactic control flow:
```
example : False ∨ True := by
first
| apply Or.inl; trivial; dbg_trace "left"
| apply Or.inr; trivial; dbg_trace "right"
```
-/
syntax (name := dbgTrace) "dbg_trace " str : tactic
/-- `stop` is a helper tactic for "discarding" the rest of a proof. It is useful when working on the middle of a complex proofs,
and less messy than commenting the remainder of the proof. -/
macro "stop" tacticSeq : tactic => `(repeat sorry)
/--
The tactic `specialize h a₁ ... aₙ` works on local hypothesis `h`.
The premises of this hypothesis, either universal quantifications or non-dependent implications,
are instantiated by concrete terms coming either from arguments `a₁` ... `aₙ`.
The tactic adds a new hypothesis with the same name `h := h a₁ ... aₙ` and tries to clear the previous one.
-/
syntax (name := specialize) "specialize " term : tactic
macro_rules | `(tactic| trivial) => `(tactic| assumption)
macro_rules | `(tactic| trivial) => `(tactic| rfl)
macro_rules | `(tactic| trivial) => `(tactic| contradiction)
macro_rules | `(tactic| trivial) => `(tactic| decide)
macro_rules | `(tactic| trivial) => `(tactic| apply True.intro)
macro_rules | `(tactic| trivial) => `(tactic| apply And.intro <;> trivial)
/-- `unhygienic tacs` runs `tacs` with name hygiene disabled.
This means that tactics that would normally create inaccessible names will instead
make regular variables. **Warning**: Tactics may change their variable naming
strategies at any time, so code that depends on autogenerated names is brittle.
Users should try not to use `unhygienic` if possible.
```
example : ∀ x : Nat, x = x := by unhygienic
intro -- x would normally be intro'd as inaccessible
exact Eq.refl x -- refer to x
```
-/
macro "unhygienic " t:tacticSeq : tactic => `(set_option tactic.hygienic false in $t)
/-- `fail msg` is a tactic that always fail and produces an error using the given message. -/
syntax (name := fail) "fail " (str)? : tactic
/-- `checkpoint tac` acts the same as `tac`, but it caches the input and output of `tac`,
and if the file is re-elaborated and the input matches, the tactic is not re-run and
its effects are reapplied to the state. This is useful for improving responsiveness
when working on a long tactic proof, by wrapping expensive tactics with `checkpoint`.
See the `save` tactic, which may be more convenient to use.
(TODO: do this automatically and transparently so that users don't have to use
this combinator explicitly.) -/
syntax (name := checkpoint) "checkpoint " tacticSeq : tactic
/-- `save` is defined to be the same as `skip`, but the elaborator has
special handling for occurrences of `save` in tactic scripts and will transform
`by tac1; save; tac2` to `by (checkpoint tac1); tac2`, meaning that the effect of `tac1`
will be cached and replayed. This is useful for improving responsiveness
when working on a long tactic proof, by using `save` after expensive tactics.
(TODO: do this automatically and transparently so that users don't have to use
this combinator explicitly.) -/
macro (name := save) "save" : tactic => `(skip)
/-- The tactic `sleep ms` sleeps for `ms` milliseconds and does nothing. It is used for debugging purposes only. -/
syntax (name := sleep) "sleep" num : tactic
/-- `exists e₁, e₂, ...` is shorthand for `refine ⟨e₁, e₂, ...⟩; try trivial`. It is useful for existential goals. -/
macro "exists " es:term,+ : tactic =>
`(tactic| (refine ⟨$es,*, ?_⟩; try trivial))
/--
Apply congruence (recursively) to goals of the form `⊢ f as = f bs` and `⊢ HEq (f as) (f bs)`.
The optional parameter is the depth of the recursive applications. This is useful when `congr` is too aggressive
in breaking down the goal.
For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr` produces the goals `⊢ x = y` and `⊢ y = x`,
while `congr 2` produces the intended `⊢ x + y = y + x`.
-/
syntax (name := congr) "congr " (num)? : tactic
end Tactic
namespace Attr
/--
Theorems tagged with the `simp` attribute are by the simplifier (i.e., the `simp` tactic, and its variants) to simplify
expressions occurring in your goals.
We call theorems tagged with the `simp` attribute "simp theorems" or "simp lemmas".
Lean maintains a database/index containing all active simp theorems.
Here is an example of a simp theorem.
```lean
@[simp] theorem ne_eq (a b : α) : (a ≠ b) = Not (a = b) := rfl
```
This simp theorem instructs the simplifier to replace instances of the term `a ≠ b` (e.g. `x + 0 ≠ y`) with `Not (a = b)`
(e.g., `Not (x + 0 = y)`).
The simplifier applies simp theorems in one direction only: if `A = B` is a simp theorem, then `simp`
replaces `A`s with `B`s, but it doesn't replace `B`s with `A`s. Hence a simp theorem should have the
property that its right-hand side is "simpler" than its left-hand side.
In particular, `=` and `↔` should not be viewed as symmetric operators in this situation.
The following would be a terrible simp theorem (if it were even allowed):
```lean
@[simp] lemma mul_right_inv_bad (a : G) : 1 = a * a⁻¹ := ...
```
Replacing 1 with a * a⁻¹ is not a sensible default direction to travel. Even worse would be a theorem
that causes expressions to grow without bound, causing simp to loop forever.
By default the simplifier applies `simp` theorems to an expression `e` after its sub-expressions have been simplified.
We say it performs a bottom-up simplification. You can instruct the simplifier to apply a theorem before its sub-expressions
have been simplified by using the modifier `↓`. Here is an example
```lean
@[simp↓] theorem not_and_eq (p q : Prop) : (¬ (p ∧ q)) = (¬p ∨ ¬q) :=
```
When multiple simp theorems are applicable, the simplifier uses the one with highest priority. If there are several with
the same priority, it is uses the "most recent one". Example:
```lean
@[simp high] theorem cond_true (a b : α) : cond true a b = a := rfl
@[simp low+1] theorem or_true (p : Prop) : (p ∨ True) = True := propext <| Iff.intro (fun _ => trivial) (fun _ => Or.inr trivial)
@[simp 100] theorem ite_self {d : Decidable c} (a : α) : ite c a a = a := by cases d <;> rfl
```
-/
syntax (name := simp) "simp" (Tactic.simpPre <|> Tactic.simpPost)? (prio)? : attr
end Attr
end Parser
end Lean
/--
`‹t›` resolves to an (arbitrary) hypothesis of type `t`. It is useful for referring to hypotheses without accessible names.
`t` may contain holes that are solved by unification with the expected type; in particular, `‹_›` is a shortcut for `by assumption`. -/
macro "‹" type:term "›" : term => `((by assumption : $type))
/-- `get_elem_tactic_trivial` is an extensible tactic automatically called
by the notation `arr[i]` to prove any side conditions that arise when
constructing the term (e.g. the index is in bounds of the array).
The default behavior is to just try `trivial` (which handles the case
where `i < arr.size` is in the context) and `simp_arith`
(for doing linear arithmetic in the index). -/
syntax "get_elem_tactic_trivial" : tactic
macro_rules | `(tactic| get_elem_tactic_trivial) => `(tactic| trivial)
macro_rules | `(tactic| get_elem_tactic_trivial) => `(tactic| simp (config := { arith := true }); done)
/-- `get_elem_tactic` is the tactic automatically called by the notation `arr[i]`
to prove any side conditions that arise when constructing the term
(e.g. the index is in bounds of the array). It just delegates to
`get_elem_tactic_trivial` and gives a diagnostic error message otherwise;
users are encouraged to extend `get_elem_tactic_trivial` instead of this tactic. -/
macro "get_elem_tactic" : tactic =>
`(first
| get_elem_tactic_trivial
| fail "failed to prove index is valid, possible solutions:
- Use `have`-expressions to prove the index is valid
- Use `a[i]!` notation instead, runtime check is perfomed, and 'Panic' error message is produced if index is not valid
- Use `a[i]?` notation instead, result is an `Option` type
- Use `a[i]'h` notation instead, where `h` is a proof that index is valid"
)
macro:max x:term noWs "[" i:term "]" : term => `(getElem $x $i (by get_elem_tactic))
/-- Helper declaration for the unexpander -/
@[inline] def getElem' [GetElem cont idx elem dom] (xs : cont) (i : idx) (h : dom xs i) : elem :=
getElem xs i h
macro x:term noWs "[" i:term "]'" h:term:max : term => `(getElem' $x $i $h)
|
61da61816ee174a2ba4dda5dd8cfe63e260e07b1 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/analysis/p_series.lean | 8ab578774374395077afdc5325b275dbe533b125 | [
"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 | 10,228 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import analysis.special_functions.pow
/-!
# Convergence of `p`-series
In this file we prove that the series `∑' k in ℕ, 1 / k ^ p` converges if and only if `p > 1`.
The proof is based on the
[Cauchy condensation test](https://en.wikipedia.org/wiki/Cauchy_condensation_test): `∑ k, f k`
converges if and only if so does `∑ k, 2 ^ k f (2 ^ k)`. We prove this test in
`nnreal.summable_condensed_iff` and `summable_condensed_iff_of_nonneg`, then use it to prove
`summable_one_div_rpow`. After this transformation, a `p`-series turns into a geometric series.
## TODO
It should be easy to generalize arguments to Schlömilch's generalization of the Cauchy condensation
test once we need it.
## Tags
p-series, Cauchy condensation test
-/
open filter
open_locale big_operators ennreal nnreal topological_space
/-!
### Cauchy condensation test
In this section we prove the Cauchy condensation test: for `f : ℕ → ℝ≥0` or `f : ℕ → ℝ`,
`∑ k, f k` converges if and only if so does `∑ k, 2 ^ k f (2 ^ k)`. Instead of giving a monolithic
proof, we split it into a series of lemmas with explicit estimates of partial sums of each series in
terms of the partial sums of the other series.
-/
namespace finset
variables {M : Type*} [ordered_add_comm_monoid M] {f : ℕ → M}
lemma le_sum_condensed' (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) (n : ℕ) :
(∑ k in Ico 1 (2 ^ n), f k) ≤ ∑ k in range n, (2 ^ k) • f (2 ^ k) :=
begin
induction n with n ihn, { simp },
suffices : (∑ k in Ico (2 ^ n) (2 ^ (n + 1)), f k) ≤ (2 ^ n) • f (2 ^ n),
{ rw [sum_range_succ, ← sum_Ico_consecutive],
exact add_le_add ihn this,
exacts [n.one_le_two_pow, nat.pow_le_pow_of_le_right zero_lt_two n.le_succ] },
have : ∀ k ∈ Ico (2 ^ n) (2 ^ (n + 1)), f k ≤ f (2 ^ n) :=
λ k hk, hf (pow_pos zero_lt_two _) (Ico.mem.mp hk).1,
convert sum_le_sum this,
simp [pow_succ, two_mul]
end
lemma le_sum_condensed (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) (n : ℕ) :
(∑ k in range (2 ^ n), f k) ≤ f 0 + ∑ k in range n, (2 ^ k) • f (2 ^ k) :=
begin
convert add_le_add_left (le_sum_condensed' hf n) (f 0),
rw [← sum_range_add_sum_Ico _ n.one_le_two_pow, sum_range_succ, sum_range_zero, zero_add]
end
lemma sum_condensed_le' (hf : ∀ ⦃m n⦄, 1 < m → m ≤ n → f n ≤ f m) (n : ℕ) :
(∑ k in range n, (2 ^ k) • f (2 ^ (k + 1))) ≤ ∑ k in Ico 2 (2 ^ n + 1), f k :=
begin
induction n with n ihn, { simp },
suffices : (2 ^ n) • f (2 ^ (n + 1)) ≤ ∑ k in Ico (2 ^ n + 1) (2 ^ (n + 1) + 1), f k,
{ rw [sum_range_succ, ← sum_Ico_consecutive],
exact add_le_add ihn this,
exacts [add_le_add_right n.one_le_two_pow _,
add_le_add_right (nat.pow_le_pow_of_le_right zero_lt_two n.le_succ) _] },
have : ∀ k ∈ Ico (2 ^ n + 1) (2 ^ (n + 1) + 1), f (2 ^ (n + 1)) ≤ f k :=
λ k hk, hf (n.one_le_two_pow.trans_lt $ (nat.lt_succ_of_le le_rfl).trans_le (Ico.mem.mp hk).1)
(nat.le_of_lt_succ $ (Ico.mem.mp hk).2),
convert sum_le_sum this,
simp [pow_succ, two_mul]
end
lemma sum_condensed_le (hf : ∀ ⦃m n⦄, 1 < m → m ≤ n → f n ≤ f m) (n : ℕ) :
(∑ k in range (n + 1), (2 ^ k) • f (2 ^ k)) ≤ f 1 + 2 • ∑ k in Ico 2 (2 ^ n + 1), f k :=
begin
convert add_le_add_left (nsmul_le_nsmul_of_le_right (sum_condensed_le' hf n) 2) (f 1),
simp [sum_range_succ', add_comm, pow_succ, mul_nsmul, sum_nsmul]
end
end finset
namespace ennreal
variable {f : ℕ → ℝ≥0∞}
lemma le_tsum_condensed (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) :
∑' k, f k ≤ f 0 + ∑' k : ℕ, (2 ^ k) * f (2 ^ k) :=
begin
rw [ennreal.tsum_eq_supr_nat' (nat.tendsto_pow_at_top_at_top_of_one_lt _root_.one_lt_two)],
refine supr_le (λ n, (finset.le_sum_condensed hf n).trans (add_le_add_left _ _)),
simp only [nsmul_eq_mul, nat.cast_pow, nat.cast_two],
apply ennreal.sum_le_tsum
end
lemma tsum_condensed_le (hf : ∀ ⦃m n⦄, 1 < m → m ≤ n → f n ≤ f m) :
∑' k : ℕ, (2 ^ k * f (2 ^ k)) ≤ f 1 + 2 * ∑' k, f k :=
begin
rw [ennreal.tsum_eq_supr_nat' (tendsto_at_top_mono nat.le_succ tendsto_id), two_mul, ← two_nsmul],
refine supr_le (λ n, le_trans _ (add_le_add_left (nsmul_le_nsmul_of_le_right
(ennreal.sum_le_tsum $ finset.Ico 2 (2^n + 1)) _) _)),
simpa using finset.sum_condensed_le hf n
end
end ennreal
namespace nnreal
/-- Cauchy condensation test for a series of `nnreal` version. -/
lemma summable_condensed_iff {f : ℕ → ℝ≥0} (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) :
summable (λ k : ℕ, (2 ^ k) * f (2 ^ k)) ↔ summable f :=
begin
simp only [← ennreal.tsum_coe_ne_top_iff_summable, ne.def, not_iff_not, ennreal.coe_mul,
ennreal.coe_pow, ennreal.coe_two],
split; intro h,
{ replace hf : ∀ m n, 1 < m → m ≤ n → (f n : ℝ≥0∞) ≤ f m :=
λ m n hm hmn, ennreal.coe_le_coe.2 (hf (zero_lt_one.trans hm) hmn),
simpa [h, ennreal.add_eq_top] using (ennreal.tsum_condensed_le hf) },
{ replace hf : ∀ m n, 0 < m → m ≤ n → (f n : ℝ≥0∞) ≤ f m :=
λ m n hm hmn, ennreal.coe_le_coe.2 (hf hm hmn),
simpa [h, ennreal.add_eq_top] using (ennreal.le_tsum_condensed hf) }
end
end nnreal
/-- Cauchy condensation test for series of nonnegative real numbers. -/
lemma summable_condensed_iff_of_nonneg {f : ℕ → ℝ} (h_nonneg : ∀ n, 0 ≤ f n)
(h_mono : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) :
summable (λ k : ℕ, (2 ^ k) * f (2 ^ k)) ↔ summable f :=
begin
set g : ℕ → ℝ≥0 := λ n, ⟨f n, h_nonneg n⟩,
have : f = λ n, g n := rfl,
simp only [this],
have : ∀ ⦃m n⦄, 0 < m → m ≤ n → g n ≤ g m := λ m n hm h, nnreal.coe_le_coe.2 (h_mono hm h),
exact_mod_cast nnreal.summable_condensed_iff this
end
open real
/-!
### Convergence of the `p`-series
In this section we prove that for a real number `p`, the series `∑' n : ℕ, 1 / (n ^ p)` converges if
and only if `1 < p`. There are many different proofs of this fact. The proof in this file uses the
Cauchy condensation test we formalized above. This test implies that `∑ n, 1 / (n ^ p)` converges if
and only if `∑ n, 2 ^ n / ((2 ^ n) ^ p)` converges, and the latter series is a geometric series with
common ratio `2 ^ {1 - p}`. -/
/-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, (n ^ p)⁻¹` converges
if and only if `1 < p`. -/
@[simp] lemma real.summable_nat_rpow_inv {p : ℝ} : summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ) ↔ 1 < p :=
begin
cases le_or_lt 0 p with hp hp,
/- Cauchy condensation test applies only to monotonically decreasing sequences, so we consider the
cases `0 ≤ p` and `p < 0` separately. -/
{ rw ← summable_condensed_iff_of_nonneg,
{ simp_rw [nat.cast_pow, nat.cast_two, ← rpow_nat_cast, ← rpow_mul zero_lt_two.le, mul_comm _ p,
rpow_mul zero_lt_two.le, rpow_nat_cast, ← inv_pow', ← mul_pow,
summable_geometric_iff_norm_lt_1],
nth_rewrite 0 [← rpow_one 2],
rw [← division_def, ← rpow_sub zero_lt_two, norm_eq_abs,
abs_of_pos (rpow_pos_of_pos zero_lt_two _), rpow_lt_one_iff zero_lt_two.le],
norm_num },
{ intro n,
exact inv_nonneg.2 (rpow_nonneg_of_nonneg n.cast_nonneg _) },
{ intros m n hm hmn,
exact inv_le_inv_of_le (rpow_pos_of_pos (nat.cast_pos.2 hm) _)
(rpow_le_rpow m.cast_nonneg (nat.cast_le.2 hmn) hp) } },
/- If `p < 0`, then `1 / n ^ p` tends to infinity, thus the series diverges. -/
{ suffices : ¬summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ),
{ have : ¬(1 < p) := λ hp₁, hp.not_le (zero_le_one.trans hp₁.le),
simpa [this, -one_div] },
{ intro h,
obtain ⟨k : ℕ, hk₁ : ((k ^ p)⁻¹ : ℝ) < 1, hk₀ : k ≠ 0⟩ :=
((h.tendsto_cofinite_zero.eventually (gt_mem_nhds zero_lt_one)).and
(eventually_cofinite_ne 0)).exists,
apply hk₀,
rw [← pos_iff_ne_zero, ← @nat.cast_pos ℝ] at hk₀,
simpa [inv_lt_one_iff_of_pos (rpow_pos_of_pos hk₀ _), one_lt_rpow_iff_of_pos hk₀, hp,
hp.not_lt, hk₀] using hk₁ } }
end
/-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, 1 / n ^ p` converges
if and only if `1 < p`. -/
lemma real.summable_one_div_nat_rpow {p : ℝ} : summable (λ n, 1 / n ^ p : ℕ → ℝ) ↔ 1 < p :=
by simp
/-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, (n ^ p)⁻¹` converges
if and only if `1 < p`. -/
@[simp] lemma real.summable_nat_pow_inv {p : ℕ} : summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ) ↔ 1 < p :=
by simp only [← rpow_nat_cast, real.summable_nat_rpow_inv, nat.one_lt_cast]
/-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, 1 / n ^ p` converges
if and only if `1 < p`. -/
lemma real.summable_one_div_nat_pow {p : ℕ} : summable (λ n, 1 / n ^ p : ℕ → ℝ) ↔ 1 < p :=
by simp
/-- Harmonic series is not unconditionally summable. -/
lemma real.not_summable_nat_cast_inv : ¬summable (λ n, n⁻¹ : ℕ → ℝ) :=
have ¬summable (λ n, (n^1)⁻¹ : ℕ → ℝ), from mt real.summable_nat_pow_inv.1 (lt_irrefl 1),
by simpa
/-- Harmonic series is not unconditionally summable. -/
lemma real.not_summable_one_div_nat_cast : ¬summable (λ n, 1 / n : ℕ → ℝ) :=
by simpa only [inv_eq_one_div] using real.not_summable_nat_cast_inv
/-- Harmonic series diverges. -/
lemma real.tendsto_sum_range_one_div_nat_succ_at_top :
tendsto (λ n, ∑ i in finset.range n, (1 / (i + 1) : ℝ)) at_top at_top :=
begin
rw ← not_summable_iff_tendsto_nat_at_top_of_nonneg,
{ exact_mod_cast mt (summable_nat_add_iff 1).1 real.not_summable_one_div_nat_cast },
{ exact λ i, div_nonneg zero_le_one i.cast_add_one_pos.le }
end
@[simp] lemma nnreal.summable_one_rpow_inv {p : ℝ} : summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ≥0) ↔ 1 < p :=
by simp [← nnreal.summable_coe]
lemma nnreal.summable_one_div_rpow {p : ℝ} : summable (λ n, 1 / n ^ p : ℕ → ℝ≥0) ↔ 1 < p :=
by simp
|
98f444b113f6e82763229f17af52dc4b356836c7 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/lean/run/470_lean3.lean | aa6269dea878e47dc9e6e0e45e99aca3b8bee60b | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 59 | lean | section foo
axiom foo : Type
constant bla : Nat
end foo
|
97f2cf85afef6102f8ee79ae694393751c3a0dc9 | 022215fec0be87ac6243b0f4fa3cc2939361d7d0 | /src/category_theory/instances/Top/open_nhds.lean | 5dd584af849dc2b608aae9dfd42d323b832159b6 | [
"Apache-2.0"
] | permissive | PaulGustafson/mathlib | 4aa7bc81ca971fdd7b6e50bf3a245fade2978391 | c49ac06ff9fa1371e9b6050a121df618cfd3fb80 | refs/heads/master | 1,590,798,947,521 | 1,559,220,227,000 | 1,559,220,227,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,835 | 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.instances.Top.opens
import category_theory.full_subcategory
open category_theory
open category_theory.instances
open topological_space
open opposite
universe u
namespace topological_space.open_nhds
variables {X Y : Top.{u}} (f : X ⟶ Y)
def open_nhds (x : X.α) := { U : opens X // x ∈ U }
instance open_nhds_category (x : X.α) : category.{u+1} (open_nhds x) := by {unfold open_nhds, apply_instance}
def inclusion (x : X.α) : open_nhds x ⥤ opens X :=
full_subcategory_inclusion _
@[simp] lemma inclusion_obj (x : X.α) (U) (p) : (inclusion x).obj ⟨U,p⟩ = U := rfl
def map (x : X) : open_nhds (f x) ⥤ open_nhds x :=
{ obj := λ U, ⟨(opens.map f).obj U.1, by tidy⟩,
map := λ U V i, (opens.map f).map i }
@[simp] lemma map_obj (x : X) (U) (q) : (map f x).obj ⟨U, q⟩ = ⟨(opens.map f).obj U, by tidy⟩ :=
rfl
@[simp] lemma map_id_obj' (x : X) (U) (p) (q) : (map (𝟙 X) x).obj ⟨⟨U, p⟩, q⟩ = ⟨⟨U, p⟩, q⟩ :=
rfl
@[simp] lemma map_id_obj (x : X) (U) : (map (𝟙 X) x).obj U = U :=
by tidy
@[simp] lemma map_id_obj_unop (x : X) (U : (open_nhds x)ᵒᵖ) : (map (𝟙 X) x).obj (unop U) = unop U :=
by simp
@[simp] lemma op_map_id_obj (x : X) (U : (open_nhds x)ᵒᵖ) : (map (𝟙 X) x).op.obj U = U :=
by simp
def inclusion_map_iso (x : X) : inclusion (f x) ⋙ opens.map f ≅ map f x ⋙ inclusion x :=
nat_iso.of_components
(λ U, begin split, exact 𝟙 _, exact 𝟙 _ end)
(by tidy)
@[simp] lemma inclusion_map_iso_hom (x : X) : (inclusion_map_iso f x).hom = 𝟙 _ := rfl
@[simp] lemma inclusion_map_iso_inv (x : X) : (inclusion_map_iso f x).inv = 𝟙 _ := rfl
end topological_space.open_nhds
|
56ad6ad997a4da79fe7ba9d37aff7c8161b1d221 | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /library/data/bool.lean | 452c578f6f352fdf7bc307605aaf69740b307c58 | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,595 | lean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Module: data.bool
Author: Leonardo de Moura
-/
import logic.eq
open eq eq.ops decidable
namespace bool
local attribute bor [reducible]
local attribute band [reducible]
theorem dichotomy (b : bool) : b = ff ∨ b = tt :=
cases_on b (or.inl rfl) (or.inr rfl)
theorem cond.ff {A : Type} (t e : A) : cond ff t e = e :=
rfl
theorem cond.tt {A : Type} (t e : A) : cond tt t e = t :=
rfl
theorem ff_ne_tt : ¬ ff = tt :=
assume H : ff = tt, absurd
(calc true = cond tt true false : !cond.tt⁻¹
... = cond ff true false : {H⁻¹}
... = false : cond.ff)
true_ne_false
theorem bor.tt_left (a : bool) : bor tt a = tt :=
rfl
notation a || b := bor a b
theorem bor.tt_right (a : bool) : a || tt = tt :=
cases_on a rfl rfl
theorem bor.ff_left (a : bool) : ff || a = a :=
cases_on a rfl rfl
theorem bor.ff_right (a : bool) : a || ff = a :=
cases_on a rfl rfl
theorem bor.id (a : bool) : a || a = a :=
cases_on a rfl rfl
theorem bor.comm (a b : bool) : a || b = b || a :=
cases_on a
(cases_on b rfl rfl)
(cases_on b rfl rfl)
theorem bor.assoc (a b c : bool) : (a || b) || c = a || (b || c) :=
cases_on a
(calc (ff || b) || c = b || c : {!bor.ff_left}
... = ff || (b || c) : !bor.ff_left⁻¹)
(calc (tt || b) || c = tt || c : {!bor.tt_left}
... = tt : !bor.tt_left
... = tt || (b || c) : !bor.tt_left⁻¹)
theorem bor.to_or {a b : bool} : a || b = tt → a = tt ∨ b = tt :=
rec_on a
(assume H : ff || b = tt,
have Hb : b = tt, from !bor.ff_left ▸ H,
or.inr Hb)
(assume H, or.inl rfl)
theorem band.ff_left (a : bool) : ff && a = ff :=
rfl
theorem band.tt_left (a : bool) : tt && a = a :=
cases_on a rfl rfl
theorem band.ff_right (a : bool) : a && ff = ff :=
cases_on a rfl rfl
theorem band.tt_right (a : bool) : a && tt = a :=
cases_on a rfl rfl
theorem band.id (a : bool) : a && a = a :=
cases_on a rfl rfl
theorem band.comm (a b : bool) : a && b = b && a :=
cases_on a
(cases_on b rfl rfl)
(cases_on b rfl rfl)
theorem band.assoc (a b c : bool) : (a && b) && c = a && (b && c) :=
cases_on a
(calc (ff && b) && c = ff && c : {!band.ff_left}
... = ff : !band.ff_left
... = ff && (b && c) : !band.ff_left⁻¹)
(calc (tt && b) && c = b && c : {!band.tt_left}
... = tt && (b && c) : !band.tt_left⁻¹)
theorem band.eq_tt_elim_left {a b : bool} (H : a && b = tt) : a = tt :=
or.elim (dichotomy a)
(assume H0 : a = ff,
absurd
(calc ff = ff && b : !band.ff_left⁻¹
... = a && b : {H0⁻¹}
... = tt : H)
ff_ne_tt)
(assume H1 : a = tt, H1)
theorem band.eq_tt_elim_right {a b : bool} (H : a && b = tt) : b = tt :=
band.eq_tt_elim_left (!band.comm ⬝ H)
theorem bnot.bnot (a : bool) : bnot (bnot a) = a :=
cases_on a rfl rfl
theorem bnot.false : bnot ff = tt :=
rfl
theorem bnot.true : bnot tt = ff :=
rfl
protected definition is_inhabited [instance] : inhabited bool :=
inhabited.mk ff
protected definition has_decidable_eq [instance] : decidable_eq bool :=
take a b : bool,
rec_on a
(rec_on b (inl rfl) (inr ff_ne_tt))
(rec_on b (inr (ne.symm ff_ne_tt)) (inl rfl))
end bool
|
7480862eefaa171cc8f31eb320626ed31ab45a60 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/category/CommRing/default.lean | d2ebccabca5c2577d4f1b6f8190c9aa9996442a2 | [
"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 | 127 | lean | import algebra.category.CommRing.adjunctions
import algebra.category.CommRing.limits
import algebra.category.CommRing.colimits
|
10dc8c753aa65d834d9aaf04316499ec1fc641ef | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Lean/Compiler/IR/EmitC.lean | 3b3e72d7e96879ca925ad70a17e4ac20649c712c | [
"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 | 26,104 | 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.Runtime
import Lean.Compiler.NameMangling
import Lean.Compiler.ExportAttr
import Lean.Compiler.InitAttr
import Lean.Compiler.IR.CompilerM
import Lean.Compiler.IR.EmitUtil
import Lean.Compiler.IR.NormIds
import Lean.Compiler.IR.SimpCase
import Lean.Compiler.IR.Boxing
namespace Lean.IR.EmitC
open ExplicitBoxing (requiresBoxedVersion mkBoxedName isBoxedName)
def leanMainFn := "_lean_main"
structure Context where
env : Environment
modName : Name
jpMap : JPParamsMap := {}
mainFn : FunId := default
mainParams : Array Param := #[]
abbrev M := ReaderT Context (EStateM String String)
def getEnv : M Environment := Context.env <$> read
def getModName : M Name := Context.modName <$> read
def getDecl (n : Name) : M Decl := do
let env ← getEnv
match findEnvDecl env n with
| some d => pure d
| none => throw s!"unknown declaration '{n}'"
@[inline] def emit {α : Type} [ToString α] (a : α) : M Unit :=
modify fun out => out ++ toString a
@[inline] def emitLn {α : Type} [ToString α] (a : α) : M Unit := do
emit a; emit "\n"
def emitLns {α : Type} [ToString α] (as : List α) : M Unit :=
as.forM fun a => emitLn a
def argToCString (x : Arg) : String :=
match x with
| Arg.var x => toString x
| _ => "lean_box(0)"
def emitArg (x : Arg) : M Unit :=
emit (argToCString x)
def toCType : IRType → String
| IRType.float => "double"
| IRType.uint8 => "uint8_t"
| IRType.uint16 => "uint16_t"
| IRType.uint32 => "uint32_t"
| IRType.uint64 => "uint64_t"
| IRType.usize => "size_t"
| IRType.object => "lean_object*"
| IRType.tobject => "lean_object*"
| IRType.irrelevant => "lean_object*"
| IRType.struct _ _ => panic! "not implemented yet"
| IRType.union _ _ => panic! "not implemented yet"
def throwInvalidExportName {α : Type} (n : Name) : M α :=
throw s!"invalid export name '{n}'"
def toCName (n : Name) : M String := do
let env ← getEnv;
-- TODO: we should support simple export names only
match getExportNameFor? env n with
| some (.str .anonymous s) => pure s
| some _ => throwInvalidExportName n
| none => if n == `main then pure leanMainFn else pure n.mangle
def emitCName (n : Name) : M Unit :=
toCName n >>= emit
def toCInitName (n : Name) : M String := do
let env ← getEnv;
-- TODO: we should support simple export names only
match getExportNameFor? env n with
| some (.str .anonymous s) => return "_init_" ++ s
| some _ => throwInvalidExportName n
| none => pure ("_init_" ++ n.mangle)
def emitCInitName (n : Name) : M Unit :=
toCInitName n >>= emit
def emitFnDeclAux (decl : Decl) (cppBaseName : String) (isExternal : Bool) : M Unit := do
let ps := decl.params
let env ← getEnv
if ps.isEmpty then
if isClosedTermName env decl.name then emit "static "
else if isExternal then emit "extern "
else emit "LEAN_EXPORT "
else
if !isExternal then emit "LEAN_EXPORT "
emit (toCType decl.resultType ++ " " ++ cppBaseName)
unless ps.isEmpty do
emit "("
-- We omit irrelevant parameters for extern constants
let ps := if isExternC env decl.name then ps.filter (fun p => !p.ty.isIrrelevant) else ps
if ps.size > closureMaxArgs && isBoxedName decl.name then
emit "lean_object**"
else
ps.size.forM fun i => do
if i > 0 then emit ", "
emit (toCType ps[i]!.ty)
emit ")"
emitLn ";"
def emitFnDecl (decl : Decl) (isExternal : Bool) : M Unit := do
let cppBaseName ← toCName decl.name
emitFnDeclAux decl cppBaseName isExternal
def emitExternDeclAux (decl : Decl) (cNameStr : String) : M Unit := do
let env ← getEnv
let extC := isExternC env decl.name
emitFnDeclAux decl cNameStr extC
def emitFnDecls : M Unit := do
let env ← getEnv
let decls := getDecls env
let modDecls : NameSet := decls.foldl (fun s d => s.insert d.name) {}
let usedDecls : NameSet := decls.foldl (fun s d => collectUsedDecls env d (s.insert d.name)) {}
let usedDecls := usedDecls.toList
usedDecls.forM fun n => do
let decl ← getDecl n;
match getExternNameFor env `c decl.name with
| some cName => emitExternDeclAux decl cName
| none => emitFnDecl decl (!modDecls.contains n)
def emitMainFn : M Unit := do
let d ← getDecl `main
match d with
| .fdecl (xs := xs) .. => do
unless xs.size == 2 || xs.size == 1 do throw "invalid main function, incorrect arity when generating code"
let env ← getEnv
let usesLeanAPI := usesModuleFrom env `Lean
if usesLeanAPI then
emitLn "void lean_initialize();"
else
emitLn "void lean_initialize_runtime_module();";
emitLn "
#if defined(WIN32) || defined(_WIN32)
#include <windows.h>
#endif
int main(int argc, char ** argv) {
#if defined(WIN32) || defined(_WIN32)
SetErrorMode(SEM_FAILCRITICALERRORS);
#endif
lean_object* in; lean_object* res;";
if usesLeanAPI then
emitLn "lean_initialize();"
else
emitLn "lean_initialize_runtime_module();"
let modName ← getModName
/- We disable panic messages because they do not mesh well with extracted closed terms.
See issue #534. We can remove this workaround after we implement issue #467. -/
emitLn "lean_set_panic_messages(false);"
emitLn ("res = " ++ mkModuleInitializationFunctionName modName ++ "(1 /* builtin */, lean_io_mk_world());")
emitLn "lean_set_panic_messages(true);"
emitLns ["lean_io_mark_end_initialization();",
"if (lean_io_result_is_ok(res)) {",
"lean_dec_ref(res);",
"lean_init_task_manager();"];
if xs.size == 2 then
emitLns ["in = lean_box(0);",
"int i = argc;",
"while (i > 1) {",
" lean_object* n;",
" i--;",
" n = lean_alloc_ctor(1,2,0); lean_ctor_set(n, 0, lean_mk_string(argv[i])); lean_ctor_set(n, 1, in);",
" in = n;",
"}"]
emitLn ("res = " ++ leanMainFn ++ "(in, lean_io_mk_world());")
else
emitLn ("res = " ++ leanMainFn ++ "(lean_io_mk_world());")
emitLn "}"
-- `IO _`
let retTy := env.find? `main |>.get! |>.type |>.getForallBody
-- either `UInt32` or `(P)Unit`
let retTy := retTy.appArg!
-- finalize at least the task manager to avoid leak sanitizer false positives from tasks outliving the main thread
emitLns ["lean_finalize_task_manager();",
"if (lean_io_result_is_ok(res)) {",
" int ret = " ++ if retTy.constName? == some ``UInt32 then "lean_unbox_uint32(lean_io_result_get_value(res));" else "0;",
" lean_dec_ref(res);",
" return ret;",
"} else {",
" lean_io_result_show_error(res);",
" lean_dec_ref(res);",
" return 1;",
"}"]
emitLn "}"
| _ => throw "function declaration expected"
def hasMainFn : M Bool := do
let env ← getEnv
let decls := getDecls env
return decls.any (fun d => d.name == `main)
def emitMainFnIfNeeded : M Unit := do
if (← hasMainFn) then emitMainFn
def emitFileHeader : M Unit := do
let env ← getEnv
let modName ← getModName
emitLn "// Lean compiler output"
emitLn ("// Module: " ++ toString modName)
emit "// Imports:"
env.imports.forM fun m => emit (" " ++ toString m)
emitLn ""
emitLn "#include <lean/lean.h>"
emitLns [
"#if defined(__clang__)",
"#pragma clang diagnostic ignored \"-Wunused-parameter\"",
"#pragma clang diagnostic ignored \"-Wunused-label\"",
"#elif defined(__GNUC__) && !defined(__CLANG__)",
"#pragma GCC diagnostic ignored \"-Wunused-parameter\"",
"#pragma GCC diagnostic ignored \"-Wunused-label\"",
"#pragma GCC diagnostic ignored \"-Wunused-but-set-variable\"",
"#endif",
"#ifdef __cplusplus",
"extern \"C\" {",
"#endif"
]
def emitFileFooter : M Unit :=
emitLns [
"#ifdef __cplusplus",
"}",
"#endif"
]
def throwUnknownVar {α : Type} (x : VarId) : M α :=
throw s!"unknown variable '{x}'"
def getJPParams (j : JoinPointId) : M (Array Param) := do
let ctx ← read;
match ctx.jpMap.find? j with
| some ps => pure ps
| none => throw "unknown join point"
def declareVar (x : VarId) (t : IRType) : M Unit := do
emit (toCType t); emit " "; emit x; emit "; "
def declareParams (ps : Array Param) : M Unit :=
ps.forM fun p => declareVar p.x p.ty
partial def declareVars : FnBody → Bool → M Bool
| e@(FnBody.vdecl x t _ b), d => do
let ctx ← read
if isTailCallTo ctx.mainFn e then
pure d
else
declareVar x t; declareVars b true
| FnBody.jdecl _ xs _ b, d => do declareParams xs; declareVars b (d || xs.size > 0)
| e, d => if e.isTerminal then pure d else declareVars e.body d
def emitTag (x : VarId) (xType : IRType) : M Unit := do
if xType.isObj then do
emit "lean_obj_tag("; emit x; emit ")"
else
emit x
def isIf (alts : Array Alt) : Option (Nat × FnBody × FnBody) :=
if alts.size != 2 then none
else match alts[0]! with
| Alt.ctor c b => some (c.cidx, b, alts[1]!.body)
| _ => none
def emitInc (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do
emit $
if checkRef then (if n == 1 then "lean_inc" else "lean_inc_n")
else (if n == 1 then "lean_inc_ref" else "lean_inc_ref_n")
emit "("; emit x
if n != 1 then emit ", "; emit n
emitLn ");"
def emitDec (x : VarId) (n : Nat) (checkRef : Bool) : M Unit := do
emit (if checkRef then "lean_dec" else "lean_dec_ref");
emit "("; emit x;
if n != 1 then emit ", "; emit n
emitLn ");"
def emitDel (x : VarId) : M Unit := do
emit "lean_free_object("; emit x; emitLn ");"
def emitSetTag (x : VarId) (i : Nat) : M Unit := do
emit "lean_ctor_set_tag("; emit x; emit ", "; emit i; emitLn ");"
def emitSet (x : VarId) (i : Nat) (y : Arg) : M Unit := do
emit "lean_ctor_set("; emit x; emit ", "; emit i; emit ", "; emitArg y; emitLn ");"
def emitOffset (n : Nat) (offset : Nat) : M Unit := do
if n > 0 then
emit "sizeof(void*)*"; emit n;
if offset > 0 then emit " + "; emit offset
else
emit offset
def emitUSet (x : VarId) (n : Nat) (y : VarId) : M Unit := do
emit "lean_ctor_set_usize("; emit x; emit ", "; emit n; emit ", "; emit y; emitLn ");"
def emitSSet (x : VarId) (n : Nat) (offset : Nat) (y : VarId) (t : IRType) : M Unit := do
match t with
| IRType.float => emit "lean_ctor_set_float"
| IRType.uint8 => emit "lean_ctor_set_uint8"
| IRType.uint16 => emit "lean_ctor_set_uint16"
| IRType.uint32 => emit "lean_ctor_set_uint32"
| IRType.uint64 => emit "lean_ctor_set_uint64"
| _ => throw "invalid instruction";
emit "("; emit x; emit ", "; emitOffset n offset; emit ", "; emit y; emitLn ");"
def emitJmp (j : JoinPointId) (xs : Array Arg) : M Unit := do
let ps ← getJPParams j
unless xs.size == ps.size do throw "invalid goto"
xs.size.forM fun i => do
let p := ps[i]!
let x := xs[i]!
emit p.x; emit " = "; emitArg x; emitLn ";"
emit "goto "; emit j; emitLn ";"
def emitLhs (z : VarId) : M Unit := do
emit z; emit " = "
def emitArgs (ys : Array Arg) : M Unit :=
ys.size.forM fun i => do
if i > 0 then emit ", "
emitArg ys[i]!
def emitCtorScalarSize (usize : Nat) (ssize : Nat) : M Unit := do
if usize == 0 then emit ssize
else if ssize == 0 then emit "sizeof(size_t)*"; emit usize
else emit "sizeof(size_t)*"; emit usize; emit " + "; emit ssize
def emitAllocCtor (c : CtorInfo) : M Unit := do
emit "lean_alloc_ctor("; emit c.cidx; emit ", "; emit c.size; emit ", "
emitCtorScalarSize c.usize c.ssize; emitLn ");"
def emitCtorSetArgs (z : VarId) (ys : Array Arg) : M Unit :=
ys.size.forM fun i => do
emit "lean_ctor_set("; emit z; emit ", "; emit i; emit ", "; emitArg ys[i]!; emitLn ");"
def emitCtor (z : VarId) (c : CtorInfo) (ys : Array Arg) : M Unit := do
emitLhs z;
if c.size == 0 && c.usize == 0 && c.ssize == 0 then do
emit "lean_box("; emit c.cidx; emitLn ");"
else do
emitAllocCtor c; emitCtorSetArgs z ys
def emitReset (z : VarId) (n : Nat) (x : VarId) : M Unit := do
emit "if (lean_is_exclusive("; emit x; emitLn ")) {";
n.forM fun i => do
emit " lean_ctor_release("; emit x; emit ", "; emit i; emitLn ");"
emit " "; emitLhs z; emit x; emitLn ";";
emitLn "} else {";
emit " lean_dec_ref("; emit x; emitLn ");";
emit " "; emitLhs z; emitLn "lean_box(0);";
emitLn "}"
def emitReuse (z : VarId) (x : VarId) (c : CtorInfo) (updtHeader : Bool) (ys : Array Arg) : M Unit := do
emit "if (lean_is_scalar("; emit x; emitLn ")) {";
emit " "; emitLhs z; emitAllocCtor c;
emitLn "} else {";
emit " "; emitLhs z; emit x; emitLn ";";
if updtHeader then emit " lean_ctor_set_tag("; emit z; emit ", "; emit c.cidx; emitLn ");"
emitLn "}";
emitCtorSetArgs z ys
def emitProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do
emitLhs z; emit "lean_ctor_get("; emit x; emit ", "; emit i; emitLn ");"
def emitUProj (z : VarId) (i : Nat) (x : VarId) : M Unit := do
emitLhs z; emit "lean_ctor_get_usize("; emit x; emit ", "; emit i; emitLn ");"
def emitSProj (z : VarId) (t : IRType) (n offset : Nat) (x : VarId) : M Unit := do
emitLhs z;
match t with
| IRType.float => emit "lean_ctor_get_float"
| IRType.uint8 => emit "lean_ctor_get_uint8"
| IRType.uint16 => emit "lean_ctor_get_uint16"
| IRType.uint32 => emit "lean_ctor_get_uint32"
| IRType.uint64 => emit "lean_ctor_get_uint64"
| _ => throw "invalid instruction"
emit "("; emit x; emit ", "; emitOffset n offset; emitLn ");"
def toStringArgs (ys : Array Arg) : List String :=
ys.toList.map argToCString
def emitSimpleExternalCall (f : String) (ps : Array Param) (ys : Array Arg) : M Unit := do
emit f; emit "("
-- We must remove irrelevant arguments to extern calls.
discard <| ys.size.foldM
(fun i (first : Bool) =>
if ps[i]!.ty.isIrrelevant then
pure first
else do
unless first do emit ", "
emitArg ys[i]!
pure false)
true
emitLn ");"
pure ()
def emitExternCall (f : FunId) (ps : Array Param) (extData : ExternAttrData) (ys : Array Arg) : M Unit :=
match getExternEntryFor extData `c with
| some (ExternEntry.standard _ extFn) => emitSimpleExternalCall extFn ps ys
| some (ExternEntry.inline _ pat) => do emit (expandExternPattern pat (toStringArgs ys)); emitLn ";"
| some (ExternEntry.foreign _ extFn) => emitSimpleExternalCall extFn ps ys
| _ => throw s!"failed to emit extern application '{f}'"
def emitFullApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do
emitLhs z
let decl ← getDecl f
match decl with
| Decl.extern _ ps _ extData => emitExternCall f ps extData ys
| _ =>
emitCName f
if ys.size > 0 then emit "("; emitArgs ys; emit ")"
emitLn ";"
def emitPartialApp (z : VarId) (f : FunId) (ys : Array Arg) : M Unit := do
let decl ← getDecl f
let arity := decl.params.size;
emitLhs z; emit "lean_alloc_closure((void*)("; emitCName f; emit "), "; emit arity; emit ", "; emit ys.size; emitLn ");";
ys.size.forM fun i => do
let y := ys[i]!
emit "lean_closure_set("; emit z; emit ", "; emit i; emit ", "; emitArg y; emitLn ");"
def emitApp (z : VarId) (f : VarId) (ys : Array Arg) : M Unit :=
if ys.size > closureMaxArgs then do
emit "{ lean_object* _aargs[] = {"; emitArgs ys; emitLn "};";
emitLhs z; emit "lean_apply_m("; emit f; emit ", "; emit ys.size; emitLn ", _aargs); }"
else do
emitLhs z; emit "lean_apply_"; emit ys.size; emit "("; emit f; emit ", "; emitArgs ys; emitLn ");"
def emitBoxFn (xType : IRType) : M Unit :=
match xType with
| IRType.usize => emit "lean_box_usize"
| IRType.uint32 => emit "lean_box_uint32"
| IRType.uint64 => emit "lean_box_uint64"
| IRType.float => emit "lean_box_float"
| _ => emit "lean_box"
def emitBox (z : VarId) (x : VarId) (xType : IRType) : M Unit := do
emitLhs z; emitBoxFn xType; emit "("; emit x; emitLn ");"
def emitUnbox (z : VarId) (t : IRType) (x : VarId) : M Unit := do
emitLhs z
emit (getUnboxOpName t)
emit "("; emit x; emitLn ");"
def emitIsShared (z : VarId) (x : VarId) : M Unit := do
emitLhs z; emit "!lean_is_exclusive("; emit x; emitLn ");"
def toHexDigit (c : Nat) : String :=
String.singleton c.digitChar
def quoteString (s : String) : String :=
let q := "\"";
let q := s.foldl
(fun q c => q ++
if c == '\n' then "\\n"
else if c == '\r' then "\\r"
else if c == '\t' then "\\t"
else if c == '\\' then "\\\\"
else if c == '\"' then "\\\""
else if c.toNat <= 31 then
"\\x" ++ toHexDigit (c.toNat / 16) ++ toHexDigit (c.toNat % 16)
-- TODO(Leo): we should use `\unnnn` for escaping unicode characters.
else String.singleton c)
q;
q ++ "\""
def emitNumLit (t : IRType) (v : Nat) : M Unit := do
if t.isObj then
if v < UInt32.size then
emit "lean_unsigned_to_nat("; emit v; emit "u)"
else
emit "lean_cstr_to_nat(\""; emit v; emit "\")"
else
emit v
def emitLit (z : VarId) (t : IRType) (v : LitVal) : M Unit := do
emitLhs z;
match v with
| LitVal.num v => emitNumLit t v; emitLn ";"
| LitVal.str v => emit "lean_mk_string_from_bytes("; emit (quoteString v); emit ", "; emit v.utf8ByteSize; emitLn ");"
def emitVDecl (z : VarId) (t : IRType) (v : Expr) : M Unit :=
match v with
| Expr.ctor c ys => emitCtor z c ys
| Expr.reset n x => emitReset z n x
| Expr.reuse x c u ys => emitReuse z x c u ys
| Expr.proj i x => emitProj z i x
| Expr.uproj i x => emitUProj z i x
| Expr.sproj n o x => emitSProj z t n o x
| Expr.fap c ys => emitFullApp z c ys
| Expr.pap c ys => emitPartialApp z c ys
| Expr.ap x ys => emitApp z x ys
| Expr.box t x => emitBox z x t
| Expr.unbox x => emitUnbox z t x
| Expr.isShared x => emitIsShared z x
| Expr.lit v => emitLit z t v
def isTailCall (x : VarId) (v : Expr) (b : FnBody) : M Bool := do
let ctx ← read;
match v, b with
| Expr.fap f _, FnBody.ret (Arg.var y) => return f == ctx.mainFn && x == y
| _, _ => pure false
def paramEqArg (p : Param) (x : Arg) : Bool :=
match x with
| Arg.var x => p.x == x
| _ => false
/--
Given `[p_0, ..., p_{n-1}]`, `[y_0, ..., y_{n-1}]`, representing the assignments
```
p_0 := y_0,
...
p_{n-1} := y_{n-1}
```
Return true iff we have `(i, j)` where `j > i`, and `y_j == p_i`.
That is, we have
```
p_i := y_i,
...
p_j := p_i, -- p_i was overwritten above
```
-/
def overwriteParam (ps : Array Param) (ys : Array Arg) : Bool :=
let n := ps.size;
n.any fun i =>
let p := ps[i]!
(i+1, n).anyI fun j => paramEqArg p ys[j]!
def emitTailCall (v : Expr) : M Unit :=
match v with
| Expr.fap _ ys => do
let ctx ← read
let ps := ctx.mainParams
unless ps.size == ys.size do throw "invalid tail call"
if overwriteParam ps ys then
emitLn "{"
ps.size.forM fun i => do
let p := ps[i]!
let y := ys[i]!
unless paramEqArg p y do
emit (toCType p.ty); emit " _tmp_"; emit i; emit " = "; emitArg y; emitLn ";"
ps.size.forM fun i => do
let p := ps[i]!
let y := ys[i]!
unless paramEqArg p y do emit p.x; emit " = _tmp_"; emit i; emitLn ";"
emitLn "}"
else
ys.size.forM fun i => do
let p := ps[i]!
let y := ys[i]!
unless paramEqArg p y do emit p.x; emit " = "; emitArg y; emitLn ";"
emitLn "goto _start;"
| _ => throw "bug at emitTailCall"
mutual
partial def emitIf (x : VarId) (xType : IRType) (tag : Nat) (t : FnBody) (e : FnBody) : M Unit := do
emit "if ("; emitTag x xType; emit " == "; emit tag; emitLn ")";
emitFnBody t;
emitLn "else";
emitFnBody e
partial def emitCase (x : VarId) (xType : IRType) (alts : Array Alt) : M Unit :=
match isIf alts with
| some (tag, t, e) => emitIf x xType tag t e
| _ => do
emit "switch ("; emitTag x xType; emitLn ") {";
let alts := ensureHasDefault alts;
alts.forM fun alt => do
match alt with
| Alt.ctor c b => emit "case "; emit c.cidx; emitLn ":"; emitFnBody b
| Alt.default b => emitLn "default: "; emitFnBody b
emitLn "}"
partial def emitBlock (b : FnBody) : M Unit := do
match b with
| FnBody.jdecl _ _ _ b => emitBlock b
| d@(FnBody.vdecl x t v b) =>
let ctx ← read
if isTailCallTo ctx.mainFn d then
emitTailCall v
else
emitVDecl x t v
emitBlock b
| FnBody.inc x n c p b =>
unless p do emitInc x n c
emitBlock b
| FnBody.dec x n c p b =>
unless p do emitDec x n c
emitBlock b
| FnBody.del x b => emitDel x; emitBlock b
| FnBody.setTag x i b => emitSetTag x i; emitBlock b
| FnBody.set x i y b => emitSet x i y; emitBlock b
| FnBody.uset x i y b => emitUSet x i y; emitBlock b
| FnBody.sset x i o y t b => emitSSet x i o y t; emitBlock b
| FnBody.mdata _ b => emitBlock b
| FnBody.ret x => emit "return "; emitArg x; emitLn ";"
| FnBody.case _ x xType alts => emitCase x xType alts
| FnBody.jmp j xs => emitJmp j xs
| FnBody.unreachable => emitLn "lean_internal_panic_unreachable();"
partial def emitJPs : FnBody → M Unit
| FnBody.jdecl j _ v b => do emit j; emitLn ":"; emitFnBody v; emitJPs b
| e => do unless e.isTerminal do emitJPs e.body
partial def emitFnBody (b : FnBody) : M Unit := do
emitLn "{"
let declared ← declareVars b false
if declared then emitLn ""
emitBlock b
emitJPs b
emitLn "}"
end
def emitDeclAux (d : Decl) : M Unit := do
let env ← getEnv
let (_, jpMap) := mkVarJPMaps d
withReader (fun ctx => { ctx with jpMap := jpMap }) do
unless hasInitAttr env d.name do
match d with
| .fdecl (f := f) (xs := xs) (type := t) (body := b) .. =>
let baseName ← toCName f;
if xs.size == 0 then
emit "static "
else
emit "LEAN_EXPORT " -- make symbol visible to the interpreter
emit (toCType t); emit " ";
if xs.size > 0 then
emit baseName;
emit "(";
if xs.size > closureMaxArgs && isBoxedName d.name then
emit "lean_object** _args"
else
xs.size.forM fun i => do
if i > 0 then emit ", "
let x := xs[i]!
emit (toCType x.ty); emit " "; emit x.x
emit ")"
else
emit ("_init_" ++ baseName ++ "()")
emitLn " {";
if xs.size > closureMaxArgs && isBoxedName d.name then
xs.size.forM fun i => do
let x := xs[i]!
emit "lean_object* "; emit x.x; emit " = _args["; emit i; emitLn "];"
emitLn "_start:";
withReader (fun ctx => { ctx with mainFn := f, mainParams := xs }) (emitFnBody b);
emitLn "}"
| _ => pure ()
def emitDecl (d : Decl) : M Unit := do
let d := d.normalizeIds; -- ensure we don't have gaps in the variable indices
try
emitDeclAux d
catch err =>
throw s!"{err}\ncompiling:\n{d}"
def emitFns : M Unit := do
let env ← getEnv;
let decls := getDecls env;
decls.reverse.forM emitDecl
def emitMarkPersistent (d : Decl) (n : Name) : M Unit := do
if d.resultType.isObj then
emit "lean_mark_persistent("
emitCName n
emitLn ");"
def emitDeclInit (d : Decl) : M Unit := do
let env ← getEnv
let n := d.name
if isIOUnitInitFn env n then
if isIOUnitBuiltinInitFn env n then
emit "if (builtin) {"
emit "res = "; emitCName n; emitLn "(lean_io_mk_world());"
emitLn "if (lean_io_result_is_error(res)) return res;"
emitLn "lean_dec_ref(res);"
if isIOUnitBuiltinInitFn env n then
emit "}"
else if d.params.size == 0 then
match getInitFnNameFor? env d.name with
| some initFn =>
if getBuiltinInitFnNameFor? env d.name |>.isSome then
emit "if (builtin) {"
emit "res = "; emitCName initFn; emitLn "(lean_io_mk_world());"
emitLn "if (lean_io_result_is_error(res)) return res;"
emitCName n
if d.resultType.isScalar then
emitLn (" = " ++ getUnboxOpName d.resultType ++ "(lean_io_result_get_value(res));")
else
emitLn " = lean_io_result_get_value(res);"
emitMarkPersistent d n
emitLn "lean_dec_ref(res);"
if getBuiltinInitFnNameFor? env d.name |>.isSome then
emit "}"
| _ =>
emitCName n; emit " = "; emitCInitName n; emitLn "();"; emitMarkPersistent d n
def emitInitFn : M Unit := do
let env ← getEnv
let modName ← getModName
env.imports.forM fun imp => emitLn ("lean_object* " ++ mkModuleInitializationFunctionName imp.module ++ "(uint8_t builtin, lean_object*);")
emitLns [
"static bool _G_initialized = false;",
"LEAN_EXPORT lean_object* " ++ mkModuleInitializationFunctionName modName ++ "(uint8_t builtin, lean_object* w) {",
"lean_object * res;",
"if (_G_initialized) return lean_io_result_mk_ok(lean_box(0));",
"_G_initialized = true;"
]
env.imports.forM fun imp => emitLns [
"res = " ++ mkModuleInitializationFunctionName imp.module ++ "(builtin, lean_io_mk_world());",
"if (lean_io_result_is_error(res)) return res;",
"lean_dec_ref(res);"]
let decls := getDecls env
decls.reverse.forM emitDeclInit
emitLns ["return lean_io_result_mk_ok(lean_box(0));", "}"]
def main : M Unit := do
emitFileHeader
emitFnDecls
emitFns
emitInitFn
emitMainFnIfNeeded
emitFileFooter
end EmitC
@[export lean_ir_emit_c]
def emitC (env : Environment) (modName : Name) : Except String String :=
match (EmitC.main { env := env, modName := modName }).run "" with
| EStateM.Result.ok _ s => Except.ok s
| EStateM.Result.error err _ => Except.error err
end Lean.IR
|
82b4bf7f5504a7c485a6bed09cc5a5284df50bc5 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/measure_theory/measure_space_auto.lean | 3eae6033aa27db8b2648ffe10aa5f2cce86c419e | [] | 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 | 110,880 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.measure_theory.outer_measure
import Mathlib.order.filter.countable_Inter
import Mathlib.data.set.accumulate
import Mathlib.PostPort
universes u_6 l u_1 u_2 u_5 u_3 u_4
namespace Mathlib
/-!
# Measure spaces
Given a measurable space `α`, a measure on `α` is a function that sends measurable sets to the
extended nonnegative reals that satisfies the following conditions:
1. `μ ∅ = 0`;
2. `μ` is countably additive. This means that the measure of a countable union of pairwise disjoint
sets is equal to the measure of the individual sets.
Every measure can be canonically extended to an outer measure, so that it assigns values to
all subsets, not just the measurable subsets. On the other hand, a measure that is countably
additive on measurable sets can be restricted to measurable sets to obtain a measure.
In this file a measure is defined to be an outer measure that is countably additive on
measurable sets, with the additional assumption that the outer measure is the canonical
extension of the restricted measure.
Measures on `α` form a complete lattice, and are closed under scalar multiplication with `ennreal`.
We introduce the following typeclasses for measures:
* `probability_measure μ`: `μ univ = 1`;
* `finite_measure μ`: `μ univ < ⊤`;
* `sigma_finite μ`: there exists a countable collection of measurable sets that cover `univ`
where `μ` is finite;
* `locally_finite_measure μ` : `∀ x, ∃ s ∈ 𝓝 x, μ s < ⊤`;
* `has_no_atoms μ` : `∀ x, μ {x} = 0`; possibly should be redefined as
`∀ s, 0 < μ s → ∃ t ⊆ s, 0 < μ t ∧ μ t < μ s`.
Given a measure, the null sets are the sets where `μ s = 0`, where `μ` denotes the corresponding
outer measure (so `s` might not be measurable). We can then define the completion of `μ` as the
measure on the least `σ`-algebra that also contains all null sets, by defining the measure to be `0`
on the null sets.
## Main statements
* `completion` is the completion of a measure to all null measurable sets.
* `measure.of_measurable` and `outer_measure.to_measure` are two important ways to define a measure.
## Implementation notes
Given `μ : measure α`, `μ s` is the value of the *outer measure* applied to `s`.
This conveniently allows us to apply the measure to sets without proving that they are measurable.
We get countable subadditivity for all sets, but only countable additivity for measurable sets.
You often don't want to define a measure via its constructor.
Two ways that are sometimes more convenient:
* `measure.of_measurable` is a way to define a measure by only giving its value on measurable sets
and proving the properties (1) and (2) mentioned above.
* `outer_measure.to_measure` is a way of obtaining a measure from an outer measure by showing that
all measurable sets in the measurable space are Carathéodory measurable.
To prove that two measures are equal, there are multiple options:
* `ext`: two measures are equal if they are equal on all measurable sets.
* `ext_of_generate_from_of_Union`: two measures are equal if they are equal on a π-system generating
the measurable sets, if the π-system contains a spanning increasing sequence of sets where the
measures take finite value (in particular the measures are σ-finite). This is a special case of the
more general `ext_of_generate_from_of_cover`
* `ext_of_generate_finite`: two finite measures are equal if they are equal on a π-system
generating the measurable sets. This is a special case of `ext_of_generate_from_of_Union` using
`C ∪ {univ}`, but is easier to work with.
A `measure_space` is a class that is a measurable space with a canonical measure.
The measure is denoted `volume`.
## References
* <https://en.wikipedia.org/wiki/Measure_(mathematics)>
* <https://en.wikipedia.org/wiki/Complete_measure>
* <https://en.wikipedia.org/wiki/Almost_everywhere>
## Tags
measure, almost everywhere, measure space, completion, null set, null measurable set
-/
namespace measure_theory
/-- A measure is defined to be an outer measure that is countably additive on
measurable sets, with the additional assumption that the outer measure is the canonical
extension of the restricted measure. -/
structure measure (α : Type u_6) [measurable_space α] extends outer_measure α where
m_Union :
∀ {f : ℕ → set α},
(∀ (i : ℕ), is_measurable (f i)) →
pairwise (disjoint on f) →
outer_measure.measure_of _to_outer_measure (set.Union fun (i : ℕ) => f i) =
tsum fun (i : ℕ) => outer_measure.measure_of _to_outer_measure (f i)
trimmed : outer_measure.trim _to_outer_measure = _to_outer_measure
/-- Measure projections for a measure space.
For measurable sets this returns the measure assigned by the `measure_of` field in `measure`.
But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and
subadditivity for all sets.
-/
protected instance measure.has_coe_to_fun {α : Type u_1} [measurable_space α] :
has_coe_to_fun (measure α) :=
has_coe_to_fun.mk (fun (_x : measure α) => set α → ennreal)
fun (m : measure α) => ⇑(measure.to_outer_measure m)
namespace measure
/-! ### General facts about measures -/
/-- Obtain a measure by giving a countably additive function that sends `∅` to `0`. -/
def of_measurable {α : Type u_1} [measurable_space α] (m : (s : set α) → is_measurable s → ennreal)
(m0 : m ∅ is_measurable.empty = 0)
(mU :
∀ {f : ℕ → set α} (h : ∀ (i : ℕ), is_measurable (f i)),
pairwise (disjoint on f) →
m (set.Union fun (i : ℕ) => f i) (of_measurable._proof_1 h) =
tsum fun (i : ℕ) => m (f i) (h i)) :
measure α :=
mk
(outer_measure.mk (outer_measure.measure_of (induced_outer_measure m is_measurable.empty m0))
sorry sorry sorry)
sorry sorry
theorem of_measurable_apply {α : Type u_1} [measurable_space α]
{m : (s : set α) → is_measurable s → ennreal} {m0 : m ∅ is_measurable.empty = 0}
{mU :
∀ {f : ℕ → set α} (h : ∀ (i : ℕ), is_measurable (f i)),
pairwise (disjoint on f) →
m (set.Union fun (i : ℕ) => f i) (is_measurable.Union h) =
tsum fun (i : ℕ) => m (f i) (h i)}
(s : set α) (hs : is_measurable s) : coe_fn (of_measurable m m0 mU) s = m s hs :=
induced_outer_measure_eq m0 mU hs
theorem to_outer_measure_injective {α : Type u_1} [measurable_space α] :
function.injective to_outer_measure :=
sorry
theorem ext {α : Type u_1} [measurable_space α] {μ₁ : measure α} {μ₂ : measure α}
(h : ∀ (s : set α), is_measurable s → coe_fn μ₁ s = coe_fn μ₂ s) : μ₁ = μ₂ :=
sorry
theorem ext_iff {α : Type u_1} [measurable_space α] {μ₁ : measure α} {μ₂ : measure α} :
μ₁ = μ₂ ↔ ∀ (s : set α), is_measurable s → coe_fn μ₁ s = coe_fn μ₂ s :=
{ mp :=
fun (ᾰ : μ₁ = μ₂) (s : set α) (hs : is_measurable s) => Eq._oldrec (Eq.refl (coe_fn μ₁ s)) ᾰ,
mpr := ext }
end measure
@[simp] theorem coe_to_outer_measure {α : Type u_1} [measurable_space α] {μ : measure α} :
⇑(measure.to_outer_measure μ) = ⇑μ :=
rfl
theorem to_outer_measure_apply {α : Type u_1} [measurable_space α] {μ : measure α} (s : set α) :
coe_fn (measure.to_outer_measure μ) s = coe_fn μ s :=
rfl
theorem measure_eq_trim {α : Type u_1} [measurable_space α] {μ : measure α} (s : set α) :
coe_fn μ s = coe_fn (outer_measure.trim (measure.to_outer_measure μ)) s :=
sorry
theorem measure_eq_infi {α : Type u_1} [measurable_space α] {μ : measure α} (s : set α) :
coe_fn μ s =
infi
fun (t : set α) =>
infi fun (st : s ⊆ t) => infi fun (ht : is_measurable t) => coe_fn μ t :=
sorry
/-- A variant of `measure_eq_infi` which has a single `infi`. This is useful when applying a
lemma next that only works for non-empty infima, in which case you can use
`nonempty_measurable_superset`. -/
theorem measure_eq_infi' {α : Type u_1} [measurable_space α] (μ : measure α) (s : set α) :
coe_fn μ s = infi fun (t : Subtype fun (t : set α) => s ⊆ t ∧ is_measurable t) => coe_fn μ ↑t :=
sorry
theorem measure_eq_induced_outer_measure {α : Type u_1} [measurable_space α] {μ : measure α}
{s : set α} :
coe_fn μ s =
coe_fn
(induced_outer_measure (fun (s : set α) (_x : is_measurable s) => coe_fn μ s)
is_measurable.empty (outer_measure.empty (measure.to_outer_measure μ)))
s :=
measure_eq_trim s
theorem to_outer_measure_eq_induced_outer_measure {α : Type u_1} [measurable_space α]
{μ : measure α} :
measure.to_outer_measure μ =
induced_outer_measure (fun (s : set α) (_x : is_measurable s) => coe_fn μ s)
is_measurable.empty (outer_measure.empty (measure.to_outer_measure μ)) :=
Eq.symm (measure.trimmed μ)
theorem measure_eq_extend {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
(hs : is_measurable s) :
coe_fn μ s = extend (fun (t : set α) (ht : is_measurable t) => coe_fn μ t) s :=
sorry
@[simp] theorem measure_empty {α : Type u_1} [measurable_space α] {μ : measure α} :
coe_fn μ ∅ = 0 :=
outer_measure.empty (measure.to_outer_measure μ)
theorem nonempty_of_measure_ne_zero {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
(h : coe_fn μ s ≠ 0) : set.nonempty s :=
iff.mp set.ne_empty_iff_nonempty fun (h' : s = ∅) => h (Eq.symm h' ▸ measure_empty)
theorem measure_mono {α : Type u_1} [measurable_space α] {μ : measure α} {s₁ : set α} {s₂ : set α}
(h : s₁ ⊆ s₂) : coe_fn μ s₁ ≤ coe_fn μ s₂ :=
outer_measure.mono (measure.to_outer_measure μ) h
theorem measure_mono_null {α : Type u_1} [measurable_space α] {μ : measure α} {s₁ : set α}
{s₂ : set α} (h : s₁ ⊆ s₂) (h₂ : coe_fn μ s₂ = 0) : coe_fn μ s₁ = 0 :=
iff.mp nonpos_iff_eq_zero (h₂ ▸ measure_mono h)
theorem measure_mono_top {α : Type u_1} [measurable_space α] {μ : measure α} {s₁ : set α}
{s₂ : set α} (h : s₁ ⊆ s₂) (h₁ : coe_fn μ s₁ = ⊤) : coe_fn μ s₂ = ⊤ :=
top_unique (h₁ ▸ measure_mono h)
theorem exists_is_measurable_superset {α : Type u_1} [measurable_space α] (μ : measure α)
(s : set α) : ∃ (t : set α), s ⊆ t ∧ is_measurable t ∧ coe_fn μ t = coe_fn μ s :=
sorry
/-- A measurable set `t ⊇ s` such that `μ t = μ s`. -/
def to_measurable {α : Type u_1} [measurable_space α] (μ : measure α) (s : set α) : set α :=
classical.some (exists_is_measurable_superset μ s)
theorem subset_to_measurable {α : Type u_1} [measurable_space α] (μ : measure α) (s : set α) :
s ⊆ to_measurable μ s :=
and.left (classical.some_spec (exists_is_measurable_superset μ s))
@[simp] theorem is_measurable_to_measurable {α : Type u_1} [measurable_space α] (μ : measure α)
(s : set α) : is_measurable (to_measurable μ s) :=
and.left (and.right (classical.some_spec (exists_is_measurable_superset μ s)))
@[simp] theorem measure_to_measurable {α : Type u_1} [measurable_space α] {μ : measure α}
(s : set α) : coe_fn μ (to_measurable μ s) = coe_fn μ s :=
and.right (and.right (classical.some_spec (exists_is_measurable_superset μ s)))
theorem exists_is_measurable_superset_of_null {α : Type u_1} [measurable_space α] {μ : measure α}
{s : set α} (h : coe_fn μ s = 0) : ∃ (t : set α), s ⊆ t ∧ is_measurable t ∧ coe_fn μ t = 0 :=
sorry
theorem exists_is_measurable_superset_iff_measure_eq_zero {α : Type u_1} [measurable_space α]
{μ : measure α} {s : set α} :
(∃ (t : set α), s ⊆ t ∧ is_measurable t ∧ coe_fn μ t = 0) ↔ coe_fn μ s = 0 :=
sorry
theorem measure_Union_le {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α}
[encodable β] (s : β → set α) :
coe_fn μ (set.Union fun (i : β) => s i) ≤ tsum fun (i : β) => coe_fn μ (s i) :=
outer_measure.Union (measure.to_outer_measure μ) fun (i : β) => s i
theorem measure_bUnion_le {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α}
{s : set β} (hs : set.countable s) (f : β → set α) :
coe_fn μ (set.Union fun (b : β) => set.Union fun (H : b ∈ s) => f b) ≤
tsum fun (p : ↥s) => coe_fn μ (f ↑p) :=
sorry
theorem measure_bUnion_finset_le {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α}
(s : finset β) (f : β → set α) :
coe_fn μ (set.Union fun (b : β) => set.Union fun (H : b ∈ s) => f b) ≤
finset.sum s fun (p : β) => coe_fn μ (f p) :=
sorry
theorem measure_bUnion_lt_top {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α}
{s : set β} {f : β → set α} (hs : set.finite s) (hfin : ∀ (i : β), i ∈ s → coe_fn μ (f i) < ⊤) :
coe_fn μ (set.Union fun (i : β) => set.Union fun (H : i ∈ s) => f i) < ⊤ :=
sorry
theorem measure_Union_null {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α}
[encodable β] {s : β → set α} :
(∀ (i : β), coe_fn μ (s i) = 0) → coe_fn μ (set.Union fun (i : β) => s i) = 0 :=
outer_measure.Union_null (measure.to_outer_measure μ)
theorem measure_Union_null_iff {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
[encodable ι] {s : ι → set α} :
coe_fn μ (set.Union fun (i : ι) => s i) = 0 ↔ ∀ (i : ι), coe_fn μ (s i) = 0 :=
{ mp :=
fun (h : coe_fn μ (set.Union fun (i : ι) => s i) = 0) (i : ι) =>
measure_mono_null (set.subset_Union s i) h,
mpr := measure_Union_null }
theorem measure_union_le {α : Type u_1} [measurable_space α] {μ : measure α} (s₁ : set α)
(s₂ : set α) : coe_fn μ (s₁ ∪ s₂) ≤ coe_fn μ s₁ + coe_fn μ s₂ :=
outer_measure.union (measure.to_outer_measure μ) s₁ s₂
theorem measure_union_null {α : Type u_1} [measurable_space α] {μ : measure α} {s₁ : set α}
{s₂ : set α} : coe_fn μ s₁ = 0 → coe_fn μ s₂ = 0 → coe_fn μ (s₁ ∪ s₂) = 0 :=
outer_measure.union_null (measure.to_outer_measure μ)
theorem measure_union_null_iff {α : Type u_1} [measurable_space α] {μ : measure α} {s₁ : set α}
{s₂ : set α} : coe_fn μ (s₁ ∪ s₂) = 0 ↔ coe_fn μ s₁ = 0 ∧ coe_fn μ s₂ = 0 :=
sorry
theorem measure_Union {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α}
[encodable β] {f : β → set α} (hn : pairwise (disjoint on f))
(h : ∀ (i : β), is_measurable (f i)) :
coe_fn μ (set.Union fun (i : β) => f i) = tsum fun (i : β) => coe_fn μ (f i) :=
sorry
theorem measure_union {α : Type u_1} [measurable_space α] {μ : measure α} {s₁ : set α} {s₂ : set α}
(hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
coe_fn μ (s₁ ∪ s₂) = coe_fn μ s₁ + coe_fn μ s₂ :=
sorry
theorem measure_bUnion {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α}
{s : set β} {f : β → set α} (hs : set.countable s) (hd : set.pairwise_on s (disjoint on f))
(h : ∀ (b : β), b ∈ s → is_measurable (f b)) :
coe_fn μ (set.Union fun (b : β) => set.Union fun (H : b ∈ s) => f b) =
tsum fun (p : ↥s) => coe_fn μ (f ↑p) :=
sorry
theorem measure_sUnion {α : Type u_1} [measurable_space α] {μ : measure α} {S : set (set α)}
(hs : set.countable S) (hd : set.pairwise_on S disjoint)
(h : ∀ (s : set α), s ∈ S → is_measurable s) :
coe_fn μ (⋃₀S) = tsum fun (s : ↥S) => coe_fn μ ↑s :=
sorry
theorem measure_bUnion_finset {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
{s : finset ι} {f : ι → set α} (hd : set.pairwise_on (↑s) (disjoint on f))
(hm : ∀ (b : ι), b ∈ s → is_measurable (f b)) :
coe_fn μ (set.Union fun (b : ι) => set.Union fun (H : b ∈ s) => f b) =
finset.sum s fun (p : ι) => coe_fn μ (f p) :=
sorry
/-- If `s` is a countable set, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
theorem tsum_measure_preimage_singleton {α : Type u_1} {β : Type u_2} [measurable_space α]
{μ : measure α} {s : set β} (hs : set.countable s) {f : α → β}
(hf : ∀ (y : β), y ∈ s → is_measurable (f ⁻¹' singleton y)) :
(tsum fun (b : ↥s) => coe_fn μ (f ⁻¹' singleton ↑b)) = coe_fn μ (f ⁻¹' s) :=
sorry
/-- If `s` is a `finset`, then the measure of its preimage can be found as the sum of measures
of the fibers `f ⁻¹' {y}`. -/
theorem sum_measure_preimage_singleton {α : Type u_1} {β : Type u_2} [measurable_space α]
{μ : measure α} (s : finset β) {f : α → β}
(hf : ∀ (y : β), y ∈ s → is_measurable (f ⁻¹' singleton y)) :
(finset.sum s fun (b : β) => coe_fn μ (f ⁻¹' singleton b)) = coe_fn μ (f ⁻¹' ↑s) :=
sorry
theorem measure_diff {α : Type u_1} [measurable_space α] {μ : measure α} {s₁ : set α} {s₂ : set α}
(h : s₂ ⊆ s₁) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) (h_fin : coe_fn μ s₂ < ⊤) :
coe_fn μ (s₁ \ s₂) = coe_fn μ s₁ - coe_fn μ s₂ :=
sorry
theorem measure_compl {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
(h₁ : is_measurable s) (h_fin : coe_fn μ s < ⊤) :
coe_fn μ (sᶜ) = coe_fn μ set.univ - coe_fn μ s :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (coe_fn μ (sᶜ) = coe_fn μ set.univ - coe_fn μ s))
(set.compl_eq_univ_diff s)))
(measure_diff (set.subset_univ s) is_measurable.univ h₁ h_fin)
theorem sum_measure_le_measure_univ {α : Type u_1} {ι : Type u_5} [measurable_space α]
{μ : measure α} {s : finset ι} {t : ι → set α} (h : ∀ (i : ι), i ∈ s → is_measurable (t i))
(H : set.pairwise_on (↑s) (disjoint on t)) :
(finset.sum s fun (i : ι) => coe_fn μ (t i)) ≤ coe_fn μ set.univ :=
sorry
theorem tsum_measure_le_measure_univ {α : Type u_1} {ι : Type u_5} [measurable_space α]
{μ : measure α} {s : ι → set α} (hs : ∀ (i : ι), is_measurable (s i))
(H : pairwise (disjoint on s)) : (tsum fun (i : ι) => coe_fn μ (s i)) ≤ coe_fn μ set.univ :=
sorry
/-- Pigeonhole principle for measure spaces: if `∑' i, μ (s i) > μ univ`, then
one of the intersections `s i ∩ s j` is not empty. -/
theorem exists_nonempty_inter_of_measure_univ_lt_tsum_measure {α : Type u_1} {ι : Type u_5}
[measurable_space α] (μ : measure α) {s : ι → set α} (hs : ∀ (i : ι), is_measurable (s i))
(H : coe_fn μ set.univ < tsum fun (i : ι) => coe_fn μ (s i)) :
∃ (i : ι), ∃ (j : ι), ∃ (h : i ≠ j), set.nonempty (s i ∩ s j) :=
sorry
/-- Pigeonhole principle for measure spaces: if `s` is a `finset` and
`∑ i in s, μ (t i) > μ univ`, then one of the intersections `t i ∩ t j` is not empty. -/
theorem exists_nonempty_inter_of_measure_univ_lt_sum_measure {α : Type u_1} {ι : Type u_5}
[measurable_space α] (μ : measure α) {s : finset ι} {t : ι → set α}
(h : ∀ (i : ι), i ∈ s → is_measurable (t i))
(H : coe_fn μ set.univ < finset.sum s fun (i : ι) => coe_fn μ (t i)) :
∃ (i : ι), ∃ (H : i ∈ s), ∃ (j : ι), ∃ (H : j ∈ s), ∃ (h : i ≠ j), set.nonempty (t i ∩ t j) :=
sorry
/-- Continuity from below: the measure of the union of a directed sequence of measurable sets
is the supremum of the measures. -/
theorem measure_Union_eq_supr {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
[encodable ι] {s : ι → set α} (h : ∀ (i : ι), is_measurable (s i))
(hd : directed has_subset.subset s) :
coe_fn μ (set.Union fun (i : ι) => s i) = supr fun (i : ι) => coe_fn μ (s i) :=
sorry
theorem measure_bUnion_eq_supr {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
{s : ι → set α} {t : set ι} (ht : set.countable t) (h : ∀ (i : ι), i ∈ t → is_measurable (s i))
(hd : directed_on (has_subset.subset on s) t) :
coe_fn μ (set.Union fun (i : ι) => set.Union fun (H : i ∈ t) => s i) =
supr fun (i : ι) => supr fun (H : i ∈ t) => coe_fn μ (s i) :=
sorry
/-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable
sets is the infimum of the measures. -/
theorem measure_Inter_eq_infi {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
[encodable ι] {s : ι → set α} (h : ∀ (i : ι), is_measurable (s i)) (hd : directed superset s)
(hfin : ∃ (i : ι), coe_fn μ (s i) < ⊤) :
coe_fn μ (set.Inter fun (i : ι) => s i) = infi fun (i : ι) => coe_fn μ (s i) :=
sorry
theorem measure_eq_inter_diff {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{t : set α} (hs : is_measurable s) (ht : is_measurable t) :
coe_fn μ s = coe_fn μ (s ∩ t) + coe_fn μ (s \ t) :=
sorry
theorem measure_union_add_inter {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{t : set α} (hs : is_measurable s) (ht : is_measurable t) :
coe_fn μ (s ∪ t) + coe_fn μ (s ∩ t) = coe_fn μ s + coe_fn μ t :=
sorry
/-- Continuity from below: the measure of the union of an increasing sequence of measurable sets
is the limit of the measures. -/
theorem tendsto_measure_Union {α : Type u_1} [measurable_space α] {μ : measure α} {s : ℕ → set α}
(hs : ∀ (n : ℕ), is_measurable (s n)) (hm : monotone s) :
filter.tendsto (⇑μ ∘ s) filter.at_top (nhds (coe_fn μ (set.Union fun (n : ℕ) => s n))) :=
sorry
/-- Continuity from above: the measure of the intersection of a decreasing sequence of measurable
sets is the limit of the measures. -/
theorem tendsto_measure_Inter {α : Type u_1} [measurable_space α] {μ : measure α} {s : ℕ → set α}
(hs : ∀ (n : ℕ), is_measurable (s n)) (hm : ∀ {n m : ℕ}, n ≤ m → s m ⊆ s n)
(hf : ∃ (i : ℕ), coe_fn μ (s i) < ⊤) :
filter.tendsto (⇑μ ∘ s) filter.at_top (nhds (coe_fn μ (set.Inter fun (n : ℕ) => s n))) :=
sorry
/-- One direction of the Borel-Cantelli lemma: if (sᵢ) is a sequence of measurable sets such that
∑ μ sᵢ exists, then the limit superior of the sᵢ is a null set. -/
theorem measure_limsup_eq_zero {α : Type u_1} [measurable_space α] {μ : measure α} {s : ℕ → set α}
(hs : ∀ (i : ℕ), is_measurable (s i)) (hs' : (tsum fun (i : ℕ) => coe_fn μ (s i)) ≠ ⊤) :
coe_fn μ (filter.limsup filter.at_top s) = 0 :=
sorry
theorem measure_if {α : Type u_1} {β : Type u_2} [measurable_space α] {x : β} {t : set β}
{s : set α} {μ : measure α} :
coe_fn μ (ite (x ∈ t) s ∅) = set.indicator t (fun (_x : β) => coe_fn μ s) x :=
sorry
/-- Obtain a measure by giving an outer measure where all sets in the σ-algebra are
Carathéodory measurable. -/
def outer_measure.to_measure {α : Type u_1} [ms : measurable_space α] (m : outer_measure α)
(h : ms ≤ outer_measure.caratheodory m) : measure α :=
measure.of_measurable (fun (s : set α) (_x : is_measurable s) => coe_fn m s)
(outer_measure.empty m) sorry
theorem le_to_outer_measure_caratheodory {α : Type u_1} [ms : measurable_space α] (μ : measure α) :
ms ≤ outer_measure.caratheodory (measure.to_outer_measure μ) :=
sorry
@[simp] theorem to_measure_to_outer_measure {α : Type u_1} [ms : measurable_space α]
(m : outer_measure α) (h : ms ≤ outer_measure.caratheodory m) :
measure.to_outer_measure (outer_measure.to_measure m h) = outer_measure.trim m :=
rfl
@[simp] theorem to_measure_apply {α : Type u_1} [ms : measurable_space α] (m : outer_measure α)
(h : ms ≤ outer_measure.caratheodory m) {s : set α} (hs : is_measurable s) :
coe_fn (outer_measure.to_measure m h) s = coe_fn m s :=
outer_measure.trim_eq m hs
theorem le_to_measure_apply {α : Type u_1} [ms : measurable_space α] (m : outer_measure α)
(h : ms ≤ outer_measure.caratheodory m) (s : set α) :
coe_fn m s ≤ coe_fn (outer_measure.to_measure m h) s :=
outer_measure.le_trim m s
@[simp] theorem to_outer_measure_to_measure {α : Type u_1} [ms : measurable_space α]
{μ : measure α} :
outer_measure.to_measure (measure.to_outer_measure μ) (le_to_outer_measure_caratheodory μ) =
μ :=
measure.ext fun (s : set α) => outer_measure.trim_eq (measure.to_outer_measure μ)
namespace measure
protected theorem caratheodory {α : Type u_1} [measurable_space α] {s : set α} {t : set α}
(μ : measure α) (hs : is_measurable s) : coe_fn μ (t ∩ s) + coe_fn μ (t \ s) = coe_fn μ t :=
Eq.symm (le_to_outer_measure_caratheodory μ s hs t)
/-! ### The `ennreal`-module of measures -/
protected instance has_zero {α : Type u_1} [measurable_space α] : HasZero (measure α) :=
{ zero := mk 0 sorry outer_measure.trim_zero }
@[simp] theorem zero_to_outer_measure {α : Type u_1} [measurable_space α] :
to_outer_measure 0 = 0 :=
rfl
@[simp] theorem coe_zero {α : Type u_1} [measurable_space α] : ⇑0 = 0 := rfl
theorem eq_zero_of_not_nonempty {α : Type u_1} [measurable_space α] (h : ¬Nonempty α)
(μ : measure α) : μ = 0 :=
sorry
protected instance inhabited {α : Type u_1} [measurable_space α] : Inhabited (measure α) :=
{ default := 0 }
protected instance has_add {α : Type u_1} [measurable_space α] : Add (measure α) :=
{ add := fun (μ₁ μ₂ : measure α) => mk (to_outer_measure μ₁ + to_outer_measure μ₂) sorry sorry }
@[simp] theorem add_to_outer_measure {α : Type u_1} [measurable_space α] (μ₁ : measure α)
(μ₂ : measure α) : to_outer_measure (μ₁ + μ₂) = to_outer_measure μ₁ + to_outer_measure μ₂ :=
rfl
@[simp] theorem coe_add {α : Type u_1} [measurable_space α] (μ₁ : measure α) (μ₂ : measure α) :
⇑(μ₁ + μ₂) = ⇑μ₁ + ⇑μ₂ :=
rfl
theorem add_apply {α : Type u_1} [measurable_space α] (μ₁ : measure α) (μ₂ : measure α)
(s : set α) : coe_fn (μ₁ + μ₂) s = coe_fn μ₁ s + coe_fn μ₂ s :=
rfl
protected instance add_comm_monoid {α : Type u_1} [measurable_space α] :
add_comm_monoid (measure α) :=
function.injective.add_comm_monoid to_outer_measure to_outer_measure_injective
zero_to_outer_measure add_to_outer_measure
protected instance has_scalar {α : Type u_1} [measurable_space α] :
has_scalar ennreal (measure α) :=
has_scalar.mk fun (c : ennreal) (μ : measure α) => mk (c • to_outer_measure μ) sorry sorry
@[simp] theorem smul_to_outer_measure {α : Type u_1} [measurable_space α] (c : ennreal)
(μ : measure α) : to_outer_measure (c • μ) = c • to_outer_measure μ :=
rfl
@[simp] theorem coe_smul {α : Type u_1} [measurable_space α] (c : ennreal) (μ : measure α) :
⇑(c • μ) = c • ⇑μ :=
rfl
theorem smul_apply {α : Type u_1} [measurable_space α] (c : ennreal) (μ : measure α) (s : set α) :
coe_fn (c • μ) s = c * coe_fn μ s :=
rfl
protected instance semimodule {α : Type u_1} [measurable_space α] :
semimodule ennreal (measure α) :=
function.injective.semimodule ennreal
(add_monoid_hom.mk to_outer_measure zero_to_outer_measure add_to_outer_measure)
to_outer_measure_injective smul_to_outer_measure
/-! ### The complete lattice of measures -/
protected instance partial_order {α : Type u_1} [measurable_space α] : partial_order (measure α) :=
partial_order.mk
(fun (m₁ m₂ : measure α) => ∀ (s : set α), is_measurable s → coe_fn m₁ s ≤ coe_fn m₂ s)
(preorder.lt._default
fun (m₁ m₂ : measure α) => ∀ (s : set α), is_measurable s → coe_fn m₁ s ≤ coe_fn m₂ s)
sorry sorry sorry
theorem le_iff {α : Type u_1} [measurable_space α] {μ₁ : measure α} {μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ (s : set α), is_measurable s → coe_fn μ₁ s ≤ coe_fn μ₂ s :=
iff.rfl
theorem to_outer_measure_le {α : Type u_1} [measurable_space α] {μ₁ : measure α} {μ₂ : measure α} :
to_outer_measure μ₁ ≤ to_outer_measure μ₂ ↔ μ₁ ≤ μ₂ :=
sorry
theorem le_iff' {α : Type u_1} [measurable_space α] {μ₁ : measure α} {μ₂ : measure α} :
μ₁ ≤ μ₂ ↔ ∀ (s : set α), coe_fn μ₁ s ≤ coe_fn μ₂ s :=
iff.symm to_outer_measure_le
theorem lt_iff {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α} :
μ < ν ↔ μ ≤ ν ∧ ∃ (s : set α), is_measurable s ∧ coe_fn μ s < coe_fn ν s :=
sorry
theorem lt_iff' {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α} :
μ < ν ↔ μ ≤ ν ∧ ∃ (s : set α), coe_fn μ s < coe_fn ν s :=
sorry
-- TODO: add typeclasses for `∀ c, monotone ((*) c)` and `∀ c, monotone ((+) c)`
protected theorem add_le_add_left {α : Type u_1} [measurable_space α] {μ₁ : measure α}
{μ₂ : measure α} (ν : measure α) (hμ : μ₁ ≤ μ₂) : ν + μ₁ ≤ ν + μ₂ :=
fun (s : set α) (hs : is_measurable s) =>
add_le_add_left (hμ s hs) (coe_fn (to_outer_measure ν) s)
protected theorem add_le_add_right {α : Type u_1} [measurable_space α] {μ₁ : measure α}
{μ₂ : measure α} (hμ : μ₁ ≤ μ₂) (ν : measure α) : μ₁ + ν ≤ μ₂ + ν :=
fun (s : set α) (hs : is_measurable s) =>
add_le_add_right (hμ s hs) (coe_fn (to_outer_measure ν) s)
protected theorem add_le_add {α : Type u_1} [measurable_space α] {μ₁ : measure α} {μ₂ : measure α}
{ν₁ : measure α} {ν₂ : measure α} (hμ : μ₁ ≤ μ₂) (hν : ν₁ ≤ ν₂) : μ₁ + ν₁ ≤ μ₂ + ν₂ :=
fun (s : set α) (hs : is_measurable s) => add_le_add (hμ s hs) (hν s hs)
protected theorem le_add_left {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α}
{ν' : measure α} (h : μ ≤ ν) : μ ≤ ν' + ν :=
fun (s : set α) (hs : is_measurable s) => le_add_left (h s hs)
protected theorem le_add_right {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α}
{ν' : measure α} (h : μ ≤ ν) : μ ≤ ν + ν' :=
fun (s : set α) (hs : is_measurable s) => le_add_right (h s hs)
theorem Inf_caratheodory {α : Type u_1} [measurable_space α] {m : set (measure α)} (s : set α)
(hs : is_measurable s) :
measurable_space.is_measurable' (outer_measure.caratheodory (Inf (to_outer_measure '' m))) s :=
sorry
protected instance has_Inf {α : Type u_1} [measurable_space α] : has_Inf (measure α) :=
has_Inf.mk
fun (m : set (measure α)) =>
outer_measure.to_measure (Inf (to_outer_measure '' m)) Inf_caratheodory
theorem Inf_apply {α : Type u_1} [measurable_space α] {s : set α} {m : set (measure α)}
(hs : is_measurable s) : coe_fn (Inf m) s = coe_fn (Inf (to_outer_measure '' m)) s :=
to_measure_apply (Inf (to_outer_measure '' m)) Inf_caratheodory hs
protected instance complete_lattice {α : Type u_1} [measurable_space α] :
complete_lattice (measure α) :=
complete_lattice.mk complete_lattice.sup complete_lattice.le complete_lattice.lt sorry sorry sorry
sorry sorry sorry complete_lattice.inf sorry sorry sorry complete_lattice.top sorry 0 sorry
complete_lattice.Sup complete_lattice.Inf sorry sorry sorry sorry
/- Adding an explicit `top` makes `leanchecker` fail, see lean#364, disable for now
top := (⊤ : outer_measure α).to_measure (by rw [outer_measure.top_caratheodory]; exact le_top),
le_top := assume a s hs,
by cases s.eq_empty_or_nonempty with h h;
simp [h, to_measure_apply ⊤ _ hs, outer_measure.top_apply],
-/
protected theorem zero_le {α : Type u_1} [measurable_space α] (μ : measure α) : 0 ≤ μ := bot_le
theorem nonpos_iff_eq_zero' {α : Type u_1} [measurable_space α] {μ : measure α} : μ ≤ 0 ↔ μ = 0 :=
has_le.le.le_iff_eq (measure.zero_le μ)
@[simp] theorem measure_univ_eq_zero {α : Type u_1} [measurable_space α] {μ : measure α} :
coe_fn μ set.univ = 0 ↔ μ = 0 :=
sorry
/-! ### Pushforward and pullback -/
/-- Lift a linear map between `outer_measure` spaces such that for each measure `μ` every measurable
set is caratheodory-measurable w.r.t. `f μ` to a linear map between `measure` spaces. -/
def lift_linear {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
(f : linear_map ennreal (outer_measure α) (outer_measure β))
(hf : ∀ (μ : measure α), _inst_2 ≤ outer_measure.caratheodory (coe_fn f (to_outer_measure μ))) :
linear_map ennreal (measure α) (measure β) :=
linear_map.mk
(fun (μ : measure α) => outer_measure.to_measure (coe_fn f (to_outer_measure μ)) (hf μ)) sorry
sorry
@[simp] theorem lift_linear_apply {α : Type u_1} {β : Type u_2} [measurable_space α]
[measurable_space β] {μ : measure α}
{f : linear_map ennreal (outer_measure α) (outer_measure β)}
(hf : ∀ (μ : measure α), _inst_2 ≤ outer_measure.caratheodory (coe_fn f (to_outer_measure μ)))
{s : set β} (hs : is_measurable s) :
coe_fn (coe_fn (lift_linear f hf) μ) s = coe_fn (coe_fn f (to_outer_measure μ)) s :=
to_measure_apply (coe_fn f (to_outer_measure μ)) (hf μ) hs
theorem le_lift_linear_apply {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{μ : measure α} {f : linear_map ennreal (outer_measure α) (outer_measure β)}
(hf : ∀ (μ : measure α), _inst_2 ≤ outer_measure.caratheodory (coe_fn f (to_outer_measure μ)))
(s : set β) :
coe_fn (coe_fn f (to_outer_measure μ)) s ≤ coe_fn (coe_fn (lift_linear f hf) μ) s :=
le_to_measure_apply (coe_fn f (to_outer_measure μ)) (hf μ) s
/-- The pushforward of a measure. It is defined to be `0` if `f` is not a measurable function. -/
def map {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (f : α → β) :
linear_map ennreal (measure α) (measure β) :=
dite (measurable f) (fun (hf : measurable f) => lift_linear (outer_measure.map f) sorry)
fun (hf : ¬measurable f) => 0
/-- We can evaluate the pushforward on measurable sets. For non-measurable sets, see
`measure_theory.measure.le_map_apply` and `measurable_equiv.map_apply`. -/
@[simp] theorem map_apply {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{μ : measure α} {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) :
coe_fn (coe_fn (map f) μ) s = coe_fn μ (f ⁻¹' s) :=
sorry
@[simp] theorem map_id {α : Type u_1} [measurable_space α] {μ : measure α} :
coe_fn (map id) μ = μ :=
ext fun (s : set α) => map_apply measurable_id
theorem map_map {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α]
[measurable_space β] [measurable_space γ] {μ : measure α} {g : β → γ} {f : α → β}
(hg : measurable g) (hf : measurable f) :
coe_fn (map g) (coe_fn (map f) μ) = coe_fn (map (g ∘ f)) μ :=
sorry
theorem map_mono {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{μ : measure α} {ν : measure α} {f : α → β} (hf : measurable f) (h : μ ≤ ν) :
coe_fn (map f) μ ≤ coe_fn (map f) ν :=
sorry
/-- Even if `s` is not measurable, we can bound `map f μ s` from below.
See also `measurable_equiv.map_apply`. -/
theorem le_map_apply {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{μ : measure α} {f : α → β} (hf : measurable f) (s : set β) :
coe_fn μ (f ⁻¹' s) ≤ coe_fn (coe_fn (map f) μ) s :=
sorry
/-- Pullback of a `measure`. If `f` sends each `measurable` set to a `measurable` set, then for each
measurable set `s` we have `comap f μ s = μ (f '' s)`. -/
def comap {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] (f : α → β) :
linear_map ennreal (measure β) (measure α) :=
dite (function.injective f ∧ ∀ (s : set α), is_measurable s → is_measurable (f '' s))
(fun (hf : function.injective f ∧ ∀ (s : set α), is_measurable s → is_measurable (f '' s)) =>
lift_linear (outer_measure.comap f) sorry)
fun (hf : ¬(function.injective f ∧ ∀ (s : set α), is_measurable s → is_measurable (f '' s))) =>
0
theorem comap_apply {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{s : set α} (f : α → β) (hfi : function.injective f)
(hf : ∀ (s : set α), is_measurable s → is_measurable (f '' s)) (μ : measure β)
(hs : is_measurable s) : coe_fn (coe_fn (comap f) μ) s = coe_fn μ (f '' s) :=
sorry
/-! ### Restricting a measure -/
/-- Restrict a measure `μ` to a set `s` as an `ennreal`-linear map. -/
def restrictₗ {α : Type u_1} [measurable_space α] (s : set α) :
linear_map ennreal (measure α) (measure α) :=
lift_linear (outer_measure.restrict s) sorry
/-- Restrict a measure `μ` to a set `s`. -/
def restrict {α : Type u_1} [measurable_space α] (μ : measure α) (s : set α) : measure α :=
coe_fn (restrictₗ s) μ
@[simp] theorem restrictₗ_apply {α : Type u_1} [measurable_space α] (s : set α) (μ : measure α) :
coe_fn (restrictₗ s) μ = restrict μ s :=
rfl
@[simp] theorem restrict_apply {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{t : set α} (ht : is_measurable t) : coe_fn (restrict μ s) t = coe_fn μ (t ∩ s) :=
sorry
theorem restrict_apply_univ {α : Type u_1} [measurable_space α] {μ : measure α} (s : set α) :
coe_fn (restrict μ s) set.univ = coe_fn μ s :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (coe_fn (restrict μ s) set.univ = coe_fn μ s))
(restrict_apply is_measurable.univ)))
(eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn μ (set.univ ∩ s) = coe_fn μ s)) (set.univ_inter s)))
(Eq.refl (coe_fn μ s)))
theorem le_restrict_apply {α : Type u_1} [measurable_space α] {μ : measure α} (s : set α)
(t : set α) : coe_fn μ (t ∩ s) ≤ coe_fn (restrict μ s) t :=
sorry
@[simp] theorem restrict_add {α : Type u_1} [measurable_space α] (μ : measure α) (ν : measure α)
(s : set α) : restrict (μ + ν) s = restrict μ s + restrict ν s :=
linear_map.map_add (restrictₗ s) μ ν
@[simp] theorem restrict_zero {α : Type u_1} [measurable_space α] (s : set α) : restrict 0 s = 0 :=
linear_map.map_zero (restrictₗ s)
@[simp] theorem restrict_smul {α : Type u_1} [measurable_space α] (c : ennreal) (μ : measure α)
(s : set α) : restrict (c • μ) s = c • restrict μ s :=
linear_map.map_smul (restrictₗ s) c μ
@[simp] theorem restrict_restrict {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{t : set α} (hs : is_measurable s) : restrict (restrict μ t) s = restrict μ (s ∩ t) :=
sorry
theorem restrict_apply_eq_zero {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{t : set α} (ht : is_measurable t) : coe_fn (restrict μ s) t = 0 ↔ coe_fn μ (t ∩ s) = 0 :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (coe_fn (restrict μ s) t = 0 ↔ coe_fn μ (t ∩ s) = 0))
(restrict_apply ht)))
(iff.refl (coe_fn μ (t ∩ s) = 0))
theorem measure_inter_eq_zero_of_restrict {α : Type u_1} [measurable_space α] {μ : measure α}
{s : set α} {t : set α} (h : coe_fn (restrict μ s) t = 0) : coe_fn μ (t ∩ s) = 0 :=
iff.mp nonpos_iff_eq_zero (h ▸ le_restrict_apply s t)
theorem restrict_apply_eq_zero' {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{t : set α} (hs : is_measurable s) : coe_fn (restrict μ s) t = 0 ↔ coe_fn μ (t ∩ s) = 0 :=
sorry
@[simp] theorem restrict_eq_zero {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} :
restrict μ s = 0 ↔ coe_fn μ s = 0 :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (restrict μ s = 0 ↔ coe_fn μ s = 0))
(Eq.symm (propext measure_univ_eq_zero))))
(eq.mpr
(id
(Eq._oldrec (Eq.refl (coe_fn (restrict μ s) set.univ = 0 ↔ coe_fn μ s = 0))
(restrict_apply_univ s)))
(iff.refl (coe_fn μ s = 0)))
@[simp] theorem restrict_empty {α : Type u_1} [measurable_space α] {μ : measure α} :
restrict μ ∅ = 0 :=
sorry
@[simp] theorem restrict_univ {α : Type u_1} [measurable_space α] {μ : measure α} :
restrict μ set.univ = μ :=
sorry
theorem restrict_union_apply {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{s' : set α} {t : set α} (h : disjoint (t ∩ s) (t ∩ s')) (hs : is_measurable s)
(hs' : is_measurable s') (ht : is_measurable t) :
coe_fn (restrict μ (s ∪ s')) t = coe_fn (restrict μ s) t + coe_fn (restrict μ s') t :=
sorry
theorem restrict_union {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} {t : set α}
(h : disjoint s t) (hs : is_measurable s) (ht : is_measurable t) :
restrict μ (s ∪ t) = restrict μ s + restrict μ t :=
ext
fun (t' : set α) (ht' : is_measurable t') =>
restrict_union_apply (disjoint.mono inf_le_right inf_le_right h) hs ht ht'
theorem restrict_union_add_inter {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{t : set α} (hs : is_measurable s) (ht : is_measurable t) :
restrict μ (s ∪ t) + restrict μ (s ∩ t) = restrict μ s + restrict μ t :=
sorry
@[simp] theorem restrict_add_restrict_compl {α : Type u_1} [measurable_space α] {μ : measure α}
{s : set α} (hs : is_measurable s) : restrict μ s + restrict μ (sᶜ) = μ :=
sorry
@[simp] theorem restrict_compl_add_restrict {α : Type u_1} [measurable_space α] {μ : measure α}
{s : set α} (hs : is_measurable s) : restrict μ (sᶜ) + restrict μ s = μ :=
eq.mpr
(id
(Eq._oldrec (Eq.refl (restrict μ (sᶜ) + restrict μ s = μ))
(add_comm (restrict μ (sᶜ)) (restrict μ s))))
(eq.mpr
(id
(Eq._oldrec (Eq.refl (restrict μ s + restrict μ (sᶜ) = μ))
(restrict_add_restrict_compl hs)))
(Eq.refl μ))
theorem restrict_union_le {α : Type u_1} [measurable_space α] {μ : measure α} (s : set α)
(s' : set α) : restrict μ (s ∪ s') ≤ restrict μ s + restrict μ s' :=
sorry
theorem restrict_Union_apply {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
[encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ (i : ι), is_measurable (s i)) {t : set α} (ht : is_measurable t) :
coe_fn (restrict μ (set.Union fun (i : ι) => s i)) t =
tsum fun (i : ι) => coe_fn (restrict μ (s i)) t :=
sorry
theorem restrict_Union_apply_eq_supr {α : Type u_1} {ι : Type u_5} [measurable_space α]
{μ : measure α} [encodable ι] {s : ι → set α} (hm : ∀ (i : ι), is_measurable (s i))
(hd : directed has_subset.subset s) {t : set α} (ht : is_measurable t) :
coe_fn (restrict μ (set.Union fun (i : ι) => s i)) t =
supr fun (i : ι) => coe_fn (restrict μ (s i)) t :=
sorry
theorem restrict_map {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{μ : measure α} {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) :
restrict (coe_fn (map f) μ) s = coe_fn (map f) (restrict μ (f ⁻¹' s)) :=
sorry
theorem map_comap_subtype_coe {α : Type u_1} [measurable_space α] {s : set α}
(hs : is_measurable s) : linear_map.comp (map coe) (comap coe) = restrictₗ s :=
sorry
/-- Restriction of a measure to a subset is monotone both in set and in measure. -/
theorem restrict_mono {α : Type u_1} [measurable_space α] {s : set α} {s' : set α} (hs : s ⊆ s')
{μ : measure α} {ν : measure α} (hμν : μ ≤ ν) : restrict μ s ≤ restrict ν s' :=
sorry
theorem restrict_le_self {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} :
restrict μ s ≤ μ :=
fun (t : set α) (ht : is_measurable t) =>
trans_rel_right LessEq (restrict_apply ht) (measure_mono (set.inter_subset_left t s))
theorem restrict_congr_meas {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α}
{s : set α} (hs : is_measurable s) :
restrict μ s = restrict ν s ↔
∀ (t : set α), t ⊆ s → is_measurable t → coe_fn μ t = coe_fn ν t :=
sorry
theorem restrict_congr_mono {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α}
{s : set α} {t : set α} (hs : s ⊆ t) (hm : is_measurable s) (h : restrict μ t = restrict ν t) :
restrict μ s = restrict ν s :=
sorry
/-- If two measures agree on all measurable subsets of `s` and `t`, then they agree on all
measurable subsets of `s ∪ t`. -/
theorem restrict_union_congr {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α}
{s : set α} {t : set α} (hsm : is_measurable s) (htm : is_measurable t) :
restrict μ (s ∪ t) = restrict ν (s ∪ t) ↔
restrict μ s = restrict ν s ∧ restrict μ t = restrict ν t :=
sorry
theorem restrict_finset_bUnion_congr {α : Type u_1} {ι : Type u_5} [measurable_space α]
{μ : measure α} {ν : measure α} {s : finset ι} {t : ι → set α}
(htm : ∀ (i : ι), i ∈ s → is_measurable (t i)) :
restrict μ (set.Union fun (i : ι) => set.Union fun (H : i ∈ s) => t i) =
restrict ν (set.Union fun (i : ι) => set.Union fun (H : i ∈ s) => t i) ↔
∀ (i : ι), i ∈ s → restrict μ (t i) = restrict ν (t i) :=
sorry
theorem restrict_Union_congr {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
{ν : measure α} [encodable ι] {s : ι → set α} (hm : ∀ (i : ι), is_measurable (s i)) :
restrict μ (set.Union fun (i : ι) => s i) = restrict ν (set.Union fun (i : ι) => s i) ↔
∀ (i : ι), restrict μ (s i) = restrict ν (s i) :=
sorry
theorem restrict_bUnion_congr {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
{ν : measure α} {s : set ι} {t : ι → set α} (hc : set.countable s)
(htm : ∀ (i : ι), i ∈ s → is_measurable (t i)) :
restrict μ (set.Union fun (i : ι) => set.Union fun (H : i ∈ s) => t i) =
restrict ν (set.Union fun (i : ι) => set.Union fun (H : i ∈ s) => t i) ↔
∀ (i : ι), i ∈ s → restrict μ (t i) = restrict ν (t i) :=
sorry
theorem restrict_sUnion_congr {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α}
{S : set (set α)} (hc : set.countable S) (hm : ∀ (s : set α), s ∈ S → is_measurable s) :
restrict μ (⋃₀S) = restrict ν (⋃₀S) ↔ ∀ (s : set α), s ∈ S → restrict μ s = restrict ν s :=
sorry
/-- This lemma shows that `restrict` and `to_outer_measure` commute. Note that the LHS has a
restrict on measures and the RHS has a restrict on outer measures. -/
theorem restrict_to_outer_measure_eq_to_outer_measure_restrict {α : Type u_1} [measurable_space α]
{μ : measure α} {s : set α} (h : is_measurable s) :
to_outer_measure (restrict μ s) = coe_fn (outer_measure.restrict s) (to_outer_measure μ) :=
sorry
/-- This lemma shows that `Inf` and `restrict` commute for measures. -/
theorem restrict_Inf_eq_Inf_restrict {α : Type u_1} [measurable_space α] {t : set α}
{m : set (measure α)} (hm : set.nonempty m) (ht : is_measurable t) :
restrict (Inf m) t = Inf ((fun (μ : measure α) => restrict μ t) '' m) :=
sorry
/-! ### Extensionality results -/
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `Union`). -/
theorem ext_iff_of_Union_eq_univ {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
{ν : measure α} [encodable ι] {s : ι → set α} (hm : ∀ (i : ι), is_measurable (s i))
(hs : (set.Union fun (i : ι) => s i) = set.univ) :
μ = ν ↔ ∀ (i : ι), restrict μ (s i) = restrict ν (s i) :=
sorry
theorem ext_of_Union_eq_univ {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
{ν : measure α} [encodable ι] {s : ι → set α} (hm : ∀ (i : ι), is_measurable (s i))
(hs : (set.Union fun (i : ι) => s i) = set.univ) :
(∀ (i : ι), restrict μ (s i) = restrict ν (s i)) → μ = ν :=
iff.mpr (ext_iff_of_Union_eq_univ hm hs)
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `bUnion`). -/
theorem ext_iff_of_bUnion_eq_univ {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
{ν : measure α} {S : set ι} {s : ι → set α} (hc : set.countable S)
(hm : ∀ (i : ι), i ∈ S → is_measurable (s i))
(hs : (set.Union fun (i : ι) => set.Union fun (H : i ∈ S) => s i) = set.univ) :
μ = ν ↔ ∀ (i : ι), i ∈ S → restrict μ (s i) = restrict ν (s i) :=
sorry
theorem ext_of_bUnion_eq_univ {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
{ν : measure α} {S : set ι} {s : ι → set α} (hc : set.countable S)
(hm : ∀ (i : ι), i ∈ S → is_measurable (s i))
(hs : (set.Union fun (i : ι) => set.Union fun (H : i ∈ S) => s i) = set.univ) :
(∀ (i : ι), i ∈ S → restrict μ (s i) = restrict ν (s i)) → μ = ν :=
iff.mpr (ext_iff_of_bUnion_eq_univ hc hm hs)
/-- Two measures are equal if they have equal restrictions on a spanning collection of sets
(formulated using `sUnion`). -/
theorem ext_iff_of_sUnion_eq_univ {α : Type u_1} [measurable_space α] {μ : measure α}
{ν : measure α} {S : set (set α)} (hc : set.countable S)
(hm : ∀ (s : set α), s ∈ S → is_measurable s) (hs : ⋃₀S = set.univ) :
μ = ν ↔ ∀ (s : set α), s ∈ S → restrict μ s = restrict ν s :=
sorry
theorem ext_of_sUnion_eq_univ {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α}
{S : set (set α)} (hc : set.countable S) (hm : ∀ (s : set α), s ∈ S → is_measurable s)
(hs : ⋃₀S = set.univ) : (∀ (s : set α), s ∈ S → restrict μ s = restrict ν s) → μ = ν :=
iff.mpr (ext_iff_of_sUnion_eq_univ hc hm hs)
theorem ext_of_generate_from_of_cover {α : Type u_1} [measurable_space α] {μ : measure α}
{ν : measure α} {S : set (set α)} {T : set (set α)}
(h_gen : _inst_1 = measurable_space.generate_from S) (hc : set.countable T)
(h_inter : is_pi_system S) (hm : ∀ (t : set α), t ∈ T → is_measurable t) (hU : ⋃₀T = set.univ)
(htop : ∀ (t : set α), t ∈ T → coe_fn μ t < ⊤)
(ST_eq : ∀ (t : set α), t ∈ T → ∀ (s : set α), s ∈ S → coe_fn μ (s ∩ t) = coe_fn ν (s ∩ t))
(T_eq : ∀ (t : set α), t ∈ T → coe_fn μ t = coe_fn ν t) : μ = ν :=
sorry
/-- Two measures are equal if they are equal on the π-system generating the σ-algebra,
and they are both finite on a increasing spanning sequence of sets in the π-system.
This lemma is formulated using `sUnion`. -/
theorem ext_of_generate_from_of_cover_subset {α : Type u_1} [measurable_space α] {μ : measure α}
{ν : measure α} {S : set (set α)} {T : set (set α)}
(h_gen : _inst_1 = measurable_space.generate_from S) (h_inter : is_pi_system S) (h_sub : T ⊆ S)
(hc : set.countable T) (hU : ⋃₀T = set.univ) (htop : ∀ (s : set α), s ∈ T → coe_fn μ s < ⊤)
(h_eq : ∀ (s : set α), s ∈ S → coe_fn μ s = coe_fn ν s) : μ = ν :=
sorry
/-- Two measures are equal if they are equal on the π-system generating the σ-algebra,
and they are both finite on a increasing spanning sequence of sets in the π-system.
This lemma is formulated using `Union`.
`finite_spanning_sets_in.ext` is a reformulation of this lemma. -/
theorem ext_of_generate_from_of_Union {α : Type u_1} [measurable_space α] {μ : measure α}
{ν : measure α} (C : set (set α)) (B : ℕ → set α)
(hA : _inst_1 = measurable_space.generate_from C) (hC : is_pi_system C)
(h1B : (set.Union fun (i : ℕ) => B i) = set.univ) (h2B : ∀ (i : ℕ), B i ∈ C)
(hμB : ∀ (i : ℕ), coe_fn μ (B i) < ⊤) (h_eq : ∀ (s : set α), s ∈ C → coe_fn μ s = coe_fn ν s) :
μ = ν :=
sorry
/-- The dirac measure. -/
def dirac {α : Type u_1} [measurable_space α] (a : α) : measure α :=
outer_measure.to_measure (outer_measure.dirac a) sorry
theorem le_dirac_apply {α : Type u_1} [measurable_space α] {s : set α} {a : α} :
set.indicator s 1 a ≤ coe_fn (dirac a) s :=
outer_measure.dirac_apply a s ▸ le_to_measure_apply (outer_measure.dirac a) (dirac._proof_1 a) s
@[simp] theorem dirac_apply' {α : Type u_1} [measurable_space α] {s : set α} (a : α)
(hs : is_measurable s) : coe_fn (dirac a) s = set.indicator s 1 a :=
to_measure_apply (outer_measure.dirac a) (dirac._proof_1 a) hs
@[simp] theorem dirac_apply_of_mem {α : Type u_1} [measurable_space α] {s : set α} {a : α}
(h : a ∈ s) : coe_fn (dirac a) s = 1 :=
sorry
@[simp] theorem dirac_apply {α : Type u_1} [measurable_space α] [measurable_singleton_class α]
(a : α) (s : set α) : coe_fn (dirac a) s = set.indicator s 1 a :=
sorry
theorem map_dirac {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{f : α → β} (hf : measurable f) (a : α) : coe_fn (map f) (dirac a) = dirac (f a) :=
sorry
/-- Sum of an indexed family of measures. -/
def sum {α : Type u_1} {ι : Type u_5} [measurable_space α] (f : ι → measure α) : measure α :=
outer_measure.to_measure (outer_measure.sum fun (i : ι) => to_outer_measure (f i)) sorry
theorem le_sum_apply {α : Type u_1} {ι : Type u_5} [measurable_space α] (f : ι → measure α)
(s : set α) : (tsum fun (i : ι) => coe_fn (f i) s) ≤ coe_fn (sum f) s :=
le_to_measure_apply (outer_measure.sum fun (i : ι) => to_outer_measure (f i)) (sum._proof_1 f) s
@[simp] theorem sum_apply {α : Type u_1} {ι : Type u_5} [measurable_space α] (f : ι → measure α)
{s : set α} (hs : is_measurable s) : coe_fn (sum f) s = tsum fun (i : ι) => coe_fn (f i) s :=
to_measure_apply (outer_measure.sum fun (i : ι) => to_outer_measure (f i)) (sum._proof_1 f) hs
theorem le_sum {α : Type u_1} {ι : Type u_5} [measurable_space α] (μ : ι → measure α) (i : ι) :
μ i ≤ sum μ :=
sorry
theorem restrict_Union {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
[encodable ι] {s : ι → set α} (hd : pairwise (disjoint on s))
(hm : ∀ (i : ι), is_measurable (s i)) :
restrict μ (set.Union fun (i : ι) => s i) = sum fun (i : ι) => restrict μ (s i) :=
sorry
theorem restrict_Union_le {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α}
[encodable ι] {s : ι → set α} :
restrict μ (set.Union fun (i : ι) => s i) ≤ sum fun (i : ι) => restrict μ (s i) :=
sorry
@[simp] theorem sum_bool {α : Type u_1} [measurable_space α] (f : Bool → measure α) :
sum f = f tt + f false :=
sorry
@[simp] theorem sum_cond {α : Type u_1} [measurable_space α] (μ : measure α) (ν : measure α) :
(sum fun (b : Bool) => cond b μ ν) = μ + ν :=
sum_bool fun (b : Bool) => cond b μ ν
@[simp] theorem restrict_sum {α : Type u_1} {ι : Type u_5} [measurable_space α] (μ : ι → measure α)
{s : set α} (hs : is_measurable s) : restrict (sum μ) s = sum fun (i : ι) => restrict (μ i) s :=
sorry
/-- Counting measure on any measurable space. -/
def count {α : Type u_1} [measurable_space α] : measure α := sum dirac
theorem le_count_apply {α : Type u_1} [measurable_space α] {s : set α} :
(tsum fun (i : ↥s) => 1) ≤ coe_fn count s :=
le_trans
(trans_rel_right LessEq (tsum_subtype s 1) (ennreal.tsum_le_tsum fun (x : α) => le_dirac_apply))
(le_sum_apply (fun (i : α) => dirac i) s)
theorem count_apply {α : Type u_1} [measurable_space α] {s : set α} (hs : is_measurable s) :
coe_fn count s = tsum fun (i : ↥s) => 1 :=
sorry
@[simp] theorem count_apply_finset {α : Type u_1} [measurable_space α]
[measurable_singleton_class α] (s : finset α) : coe_fn count ↑s = ↑(finset.card s) :=
sorry
theorem count_apply_finite {α : Type u_1} [measurable_space α] [measurable_singleton_class α]
(s : set α) (hs : set.finite s) : coe_fn count s = ↑(finset.card (set.finite.to_finset hs)) :=
sorry
/-- `count` measure evaluates to infinity at infinite sets. -/
theorem count_apply_infinite {α : Type u_1} [measurable_space α] {s : set α} (hs : set.infinite s) :
coe_fn count s = ⊤ :=
sorry
@[simp] theorem count_apply_eq_top {α : Type u_1} [measurable_space α] {s : set α}
[measurable_singleton_class α] : coe_fn count s = ⊤ ↔ set.infinite s :=
sorry
@[simp] theorem count_apply_lt_top {α : Type u_1} [measurable_space α] {s : set α}
[measurable_singleton_class α] : coe_fn count s < ⊤ ↔ set.finite s :=
iff.trans (iff.trans lt_top_iff_ne_top (not_congr count_apply_eq_top)) not_not
/-! ### The almost everywhere filter -/
/-- The “almost everywhere” filter of co-null sets. -/
def ae {α : Type u_1} [measurable_space α] (μ : measure α) : filter α :=
filter.mk (set_of fun (s : set α) => coe_fn μ (sᶜ) = 0) sorry sorry sorry
/-- The filter of sets `s` such that `sᶜ` has finite measure. -/
def cofinite {α : Type u_1} [measurable_space α] (μ : measure α) : filter α :=
filter.mk (set_of fun (s : set α) => coe_fn μ (sᶜ) < ⊤) sorry sorry sorry
theorem mem_cofinite {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} :
s ∈ cofinite μ ↔ coe_fn μ (sᶜ) < ⊤ :=
iff.rfl
theorem compl_mem_cofinite {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} :
sᶜ ∈ cofinite μ ↔ coe_fn μ s < ⊤ :=
eq.mpr (id (Eq._oldrec (Eq.refl (sᶜ ∈ cofinite μ ↔ coe_fn μ s < ⊤)) (propext mem_cofinite)))
(eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn μ (sᶜᶜ) < ⊤ ↔ coe_fn μ s < ⊤)) (compl_compl s)))
(iff.refl (coe_fn μ s < ⊤)))
theorem eventually_cofinite {α : Type u_1} [measurable_space α] {μ : measure α} {p : α → Prop} :
filter.eventually (fun (x : α) => p x) (cofinite μ) ↔
coe_fn μ (set_of fun (x : α) => ¬p x) < ⊤ :=
iff.rfl
end measure
theorem mem_ae_iff {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} :
s ∈ measure.ae μ ↔ coe_fn μ (sᶜ) = 0 :=
iff.rfl
theorem ae_iff {α : Type u_1} [measurable_space α] {μ : measure α} {p : α → Prop} :
filter.eventually (fun (a : α) => p a) (measure.ae μ) ↔
coe_fn μ (set_of fun (a : α) => ¬p a) = 0 :=
iff.rfl
theorem compl_mem_ae_iff {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} :
sᶜ ∈ measure.ae μ ↔ coe_fn μ s = 0 :=
sorry
theorem measure_zero_iff_ae_nmem {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} :
coe_fn μ s = 0 ↔ filter.eventually (fun (a : α) => ¬a ∈ s) (measure.ae μ) :=
iff.symm compl_mem_ae_iff
@[simp] theorem ae_eq_bot {α : Type u_1} [measurable_space α] {μ : measure α} :
measure.ae μ = ⊥ ↔ μ = 0 :=
sorry
@[simp] theorem ae_zero {α : Type u_1} [measurable_space α] : measure.ae 0 = ⊥ :=
iff.mpr ae_eq_bot rfl
theorem ae_of_all {α : Type u_1} [measurable_space α] {p : α → Prop} (μ : measure α) :
(∀ (a : α), p a) → filter.eventually (fun (a : α) => p a) (measure.ae μ) :=
filter.eventually_of_forall
theorem ae_mono {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α} (h : μ ≤ ν) :
measure.ae μ ≤ measure.ae ν :=
fun (s : set α) (hs : s ∈ measure.ae ν) =>
bot_unique (trans_rel_left LessEq (iff.mp measure.le_iff' h (sᶜ)) hs)
protected instance measure.ae.countable_Inter_filter {α : Type u_1} [measurable_space α]
{μ : measure α} : countable_Inter_filter (measure.ae μ) :=
countable_Inter_filter.mk
fun (S : set (set α)) (hSc : set.countable S) (hS : ∀ (s : set α), s ∈ S → s ∈ measure.ae μ) =>
eq.mpr
(id
(Eq.trans (propext mem_ae_iff)
((fun (a a_1 : ennreal) (e_1 : a = a_1) (ᾰ ᾰ_1 : ennreal) (e_2 : ᾰ = ᾰ_1) =>
congr (congr_arg Eq e_1) e_2)
(coe_fn μ (⋂₀Sᶜ)) (coe_fn μ (set.Union fun (x : ↥S) => ↑xᶜ))
((fun (x x_1 : measure α) (e_1 : x = x_1) (ᾰ ᾰ_1 : set α) (e_2 : ᾰ = ᾰ_1) =>
congr (congr_arg coe_fn e_1) e_2)
μ μ (Eq.refl μ) (⋂₀Sᶜ) (set.Union fun (x : ↥S) => ↑xᶜ)
(Eq.trans (Eq.trans (set.compl_sInter S) (set.sUnion_image compl S))
(set.bUnion_eq_Union S fun (x : set α) (H : x ∈ S) => xᶜ)))
0 0 (Eq.refl 0))))
(measure_Union_null
(iff.mpr subtype.forall
(eq.mp
(forall_congr_eq
fun (s : set α) => imp_congr_eq (Eq.refl (s ∈ S)) (propext mem_ae_iff))
hS)))
protected instance ae_is_measurably_generated {α : Type u_1} [measurable_space α] {μ : measure α} :
filter.is_measurably_generated (measure.ae μ) :=
filter.is_measurably_generated.mk fun (s : set α) (hs : s ∈ measure.ae μ) => sorry
theorem ae_all_iff {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α} [encodable ι]
{p : α → ι → Prop} :
filter.eventually (fun (a : α) => ∀ (i : ι), p a i) (measure.ae μ) ↔
∀ (i : ι), filter.eventually (fun (a : α) => p a i) (measure.ae μ) :=
eventually_countable_forall
theorem ae_ball_iff {α : Type u_1} {ι : Type u_5} [measurable_space α] {μ : measure α} {S : set ι}
(hS : set.countable S) {p : α → (i : ι) → i ∈ S → Prop} :
filter.eventually (fun (x : α) => ∀ (i : ι) (H : i ∈ S), p x i H) (measure.ae μ) ↔
∀ (i : ι) (H : i ∈ S), filter.eventually (fun (x : α) => p x i H) (measure.ae μ) :=
eventually_countable_ball hS
theorem ae_eq_refl {α : Type u_1} {δ : Type u_4} [measurable_space α] {μ : measure α} (f : α → δ) :
filter.eventually_eq (measure.ae μ) f f :=
filter.eventually_eq.rfl
theorem ae_eq_symm {α : Type u_1} {δ : Type u_4} [measurable_space α] {μ : measure α} {f : α → δ}
{g : α → δ} (h : filter.eventually_eq (measure.ae μ) f g) :
filter.eventually_eq (measure.ae μ) g f :=
filter.eventually_eq.symm h
theorem ae_eq_trans {α : Type u_1} {δ : Type u_4} [measurable_space α] {μ : measure α} {f : α → δ}
{g : α → δ} {h : α → δ} (h₁ : filter.eventually_eq (measure.ae μ) f g)
(h₂ : filter.eventually_eq (measure.ae μ) g h) : filter.eventually_eq (measure.ae μ) f h :=
filter.eventually_eq.trans h₁ h₂
theorem ae_eq_empty {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} :
filter.eventually_eq (measure.ae μ) s ∅ ↔ coe_fn μ s = 0 :=
sorry
theorem ae_le_set {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} {t : set α} :
filter.eventually_le (measure.ae μ) s t ↔ coe_fn μ (s \ t) = 0 :=
sorry
theorem union_ae_eq_right {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{t : set α} : filter.eventually_eq (measure.ae μ) (s ∪ t) t ↔ coe_fn μ (s \ t) = 0 :=
sorry
theorem diff_ae_eq_self {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{t : set α} : filter.eventually_eq (measure.ae μ) (s \ t) s ↔ coe_fn μ (s ∩ t) = 0 :=
sorry
theorem ae_eq_set {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} {t : set α} :
filter.eventually_eq (measure.ae μ) s t ↔ coe_fn μ (s \ t) = 0 ∧ coe_fn μ (t \ s) = 0 :=
sorry
theorem mem_ae_map_iff {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{μ : measure α} {f : α → β} (hf : measurable f) {s : set β} (hs : is_measurable s) :
s ∈ measure.ae (coe_fn (measure.map f) μ) ↔ f ⁻¹' s ∈ measure.ae μ :=
sorry
theorem ae_map_iff {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{μ : measure α} {f : α → β} (hf : measurable f) {p : β → Prop}
(hp : is_measurable (set_of fun (x : β) => p x)) :
filter.eventually (fun (x : β) => p x) (measure.ae (coe_fn (measure.map f) μ)) ↔
filter.eventually (fun (x : α) => p (f x)) (measure.ae μ) :=
mem_ae_map_iff hf hp
theorem ae_restrict_iff {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{p : α → Prop} (hp : is_measurable (set_of fun (x : α) => p x)) :
filter.eventually (fun (x : α) => p x) (measure.ae (measure.restrict μ s)) ↔
filter.eventually (fun (x : α) => x ∈ s → p x) (measure.ae μ) :=
sorry
theorem ae_imp_of_ae_restrict {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{p : α → Prop}
(h : filter.eventually (fun (x : α) => p x) (measure.ae (measure.restrict μ s))) :
filter.eventually (fun (x : α) => x ∈ s → p x) (measure.ae μ) :=
sorry
theorem ae_restrict_iff' {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{p : α → Prop} (hp : is_measurable s) :
filter.eventually (fun (x : α) => p x) (measure.ae (measure.restrict μ s)) ↔
filter.eventually (fun (x : α) => x ∈ s → p x) (measure.ae μ) :=
sorry
theorem ae_smul_measure {α : Type u_1} [measurable_space α] {μ : measure α} {p : α → Prop}
(h : filter.eventually (fun (x : α) => p x) (measure.ae μ)) (c : ennreal) :
filter.eventually (fun (x : α) => p x) (measure.ae (c • μ)) :=
sorry
theorem ae_smul_measure_iff {α : Type u_1} [measurable_space α] {μ : measure α} {p : α → Prop}
{c : ennreal} (hc : c ≠ 0) :
filter.eventually (fun (x : α) => p x) (measure.ae (c • μ)) ↔
filter.eventually (fun (x : α) => p x) (measure.ae μ) :=
sorry
theorem ae_add_measure_iff {α : Type u_1} [measurable_space α] {μ : measure α} {p : α → Prop}
{ν : measure α} :
filter.eventually (fun (x : α) => p x) (measure.ae (μ + ν)) ↔
filter.eventually (fun (x : α) => p x) (measure.ae μ) ∧
filter.eventually (fun (x : α) => p x) (measure.ae ν) :=
add_eq_zero_iff
theorem ae_eq_comp {α : Type u_1} {β : Type u_2} {δ : Type u_4} [measurable_space α]
[measurable_space β] {μ : measure α} {f : α → β} {g : β → δ} {g' : β → δ} (hf : measurable f)
(h : filter.eventually_eq (measure.ae (coe_fn (measure.map f) μ)) g g') :
filter.eventually_eq (measure.ae μ) (g ∘ f) (g' ∘ f) :=
sorry
theorem le_ae_restrict {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} :
measure.ae μ ⊓ filter.principal s ≤ measure.ae (measure.restrict μ s) :=
fun (s_1 : set α) (hs : s_1 ∈ measure.ae (measure.restrict μ s)) =>
iff.mpr filter.eventually_inf_principal (ae_imp_of_ae_restrict hs)
@[simp] theorem ae_restrict_eq {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
(hs : is_measurable s) :
measure.ae (measure.restrict μ s) = measure.ae μ ⊓ filter.principal s :=
sorry
@[simp] theorem ae_restrict_eq_bot {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} :
measure.ae (measure.restrict μ s) = ⊥ ↔ coe_fn μ s = 0 :=
iff.trans ae_eq_bot measure.restrict_eq_zero
@[simp] theorem ae_restrict_ne_bot {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} :
filter.ne_bot (measure.ae (measure.restrict μ s)) ↔ 0 < coe_fn μ s :=
iff.trans (not_congr ae_restrict_eq_bot) (iff.symm pos_iff_ne_zero)
theorem self_mem_ae_restrict {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
(hs : is_measurable s) : s ∈ measure.ae (measure.restrict μ s) :=
sorry
/-- A version of the Borel-Cantelli lemma: if `sᵢ` is a sequence of measurable sets such that
`∑ μ sᵢ` exists, then for almost all `x`, `x` does not belong to almost all `sᵢ`. -/
theorem ae_eventually_not_mem {α : Type u_1} [measurable_space α] {μ : measure α} {s : ℕ → set α}
(hs : ∀ (i : ℕ), is_measurable (s i)) (hs' : (tsum fun (i : ℕ) => coe_fn μ (s i)) ≠ ⊤) :
filter.eventually (fun (x : α) => filter.eventually (fun (n : ℕ) => ¬x ∈ s n) filter.at_top)
(measure.ae μ) :=
sorry
theorem mem_ae_dirac_iff {α : Type u_1} [measurable_space α] {s : set α} {a : α}
(hs : is_measurable s) : s ∈ measure.ae (measure.dirac a) ↔ a ∈ s :=
sorry
theorem ae_dirac_iff {α : Type u_1} [measurable_space α] {a : α} {p : α → Prop}
(hp : is_measurable (set_of fun (x : α) => p x)) :
filter.eventually (fun (x : α) => p x) (measure.ae (measure.dirac a)) ↔ p a :=
mem_ae_dirac_iff hp
@[simp] theorem ae_dirac_eq {α : Type u_1} [measurable_space α] [measurable_singleton_class α]
(a : α) : measure.ae (measure.dirac a) = pure a :=
sorry
theorem ae_eq_dirac' {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
[measurable_singleton_class β] {a : α} {f : α → β} (hf : measurable f) :
filter.eventually_eq (measure.ae (measure.dirac a)) f (function.const α (f a)) :=
iff.mpr
(ae_dirac_iff
((fun (this : is_measurable (f ⁻¹' singleton (f a))) => this)
(hf (is_measurable_singleton (f a)))))
rfl
theorem ae_eq_dirac {α : Type u_1} {δ : Type u_4} [measurable_space α]
[measurable_singleton_class α] {a : α} (f : α → δ) :
filter.eventually_eq (measure.ae (measure.dirac a)) f (function.const α (f a)) :=
sorry
/-- If `s ⊆ t` modulo a set of measure `0`, then `μ s ≤ μ t`. -/
theorem measure_mono_ae {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} {t : set α}
(H : filter.eventually_le (measure.ae μ) s t) : coe_fn μ s ≤ coe_fn μ t :=
sorry
theorem Mathlib.filter.eventually_le.measure_le {α : Type u_1} [measurable_space α] {μ : measure α}
{s : set α} {t : set α} (H : filter.eventually_le (measure.ae μ) s t) :
coe_fn μ s ≤ coe_fn μ t :=
measure_mono_ae
/-- If two sets are equal modulo a set of measure zero, then `μ s = μ t`. -/
theorem measure_congr {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} {t : set α}
(H : filter.eventually_eq (measure.ae μ) s t) : coe_fn μ s = coe_fn μ t :=
le_antisymm (filter.eventually_le.measure_le (filter.eventually_eq.le H))
(filter.eventually_le.measure_le (filter.eventually_eq.le (filter.eventually_eq.symm H)))
theorem restrict_mono_ae {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α} {t : set α}
(h : filter.eventually_le (measure.ae μ) s t) : measure.restrict μ s ≤ measure.restrict μ t :=
sorry
theorem restrict_congr_set {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
{t : set α} (H : filter.eventually_eq (measure.ae μ) s t) :
measure.restrict μ s = measure.restrict μ t :=
le_antisymm (restrict_mono_ae (filter.eventually_eq.le H))
(restrict_mono_ae (filter.eventually_eq.le (filter.eventually_eq.symm H)))
/-- A measure `μ` is called a probability measure if `μ univ = 1`. -/
class probability_measure {α : Type u_1} [measurable_space α] (μ : measure α) where
measure_univ : coe_fn μ set.univ = 1
protected instance measure.dirac.probability_measure {α : Type u_1} [measurable_space α] {x : α} :
probability_measure (measure.dirac x) :=
probability_measure.mk (measure.dirac_apply_of_mem (set.mem_univ x))
/-- A measure `μ` is called finite if `μ univ < ⊤`. -/
class finite_measure {α : Type u_1} [measurable_space α] (μ : measure α) where
measure_univ_lt_top : coe_fn μ set.univ < ⊤
protected instance restrict.finite_measure {α : Type u_1} [measurable_space α] {s : set α}
(μ : measure α) [hs : fact (coe_fn μ s < ⊤)] : finite_measure (measure.restrict μ s) :=
finite_measure.mk
(eq.mpr
(id
(Eq.trans
((fun (ᾰ ᾰ_1 : ennreal) (e_2 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : ennreal) (e_3 : ᾰ_2 = ᾰ_3) =>
congr (congr_arg Less e_2) e_3)
(coe_fn (measure.restrict μ s) set.univ) (coe_fn μ s)
(Eq.trans
(measure.restrict_apply (iff.mpr (iff_true_intro is_measurable.univ) True.intro))
((fun (x x_1 : measure α) (e_1 : x = x_1) (ᾰ ᾰ_1 : set α) (e_2 : ᾰ = ᾰ_1) =>
congr (congr_arg coe_fn e_1) e_2)
μ μ (Eq.refl μ) (set.univ ∩ s) s (set.univ_inter s)))
⊤ ⊤ (Eq.refl ⊤))
(propext (iff_true_intro (fact.elim hs)))))
trivial)
/-- Measure `μ` *has no atoms* if the measure of each singleton is zero.
NB: Wikipedia assumes that for any measurable set `s` with positive `μ`-measure,
there exists a measurable `t ⊆ s` such that `0 < μ t < μ s`. While this implies `μ {x} = 0`,
the converse is not true. -/
class has_no_atoms {α : Type u_1} [measurable_space α] (μ : measure α) where
measure_singleton : ∀ (x : α), coe_fn μ (singleton x) = 0
theorem measure_lt_top {α : Type u_1} [measurable_space α] (μ : measure α) [finite_measure μ]
(s : set α) : coe_fn μ s < ⊤ :=
has_le.le.trans_lt (measure_mono (set.subset_univ s)) finite_measure.measure_univ_lt_top
theorem measure_ne_top {α : Type u_1} [measurable_space α] (μ : measure α) [finite_measure μ]
(s : set α) : coe_fn μ s ≠ ⊤ :=
ne_of_lt (measure_lt_top μ s)
/-- `le_of_add_le_add_left` is normally applicable to `ordered_cancel_add_comm_monoid`,
but it holds for measures with the additional assumption that μ is finite. -/
theorem measure.le_of_add_le_add_left {α : Type u_1} [measurable_space α] {μ : measure α}
{ν₁ : measure α} {ν₂ : measure α} [finite_measure μ] (A2 : μ + ν₁ ≤ μ + ν₂) : ν₁ ≤ ν₂ :=
fun (S : set α) (B1 : is_measurable S) =>
ennreal.le_of_add_le_add_left (measure_lt_top μ S) (A2 S B1)
protected instance probability_measure.to_finite_measure {α : Type u_1} [measurable_space α]
(μ : measure α) [probability_measure μ] : finite_measure μ :=
finite_measure.mk
(eq.mpr
(id
(Eq.trans
((fun (ᾰ ᾰ_1 : ennreal) (e_2 : ᾰ = ᾰ_1) (ᾰ_2 ᾰ_3 : ennreal) (e_3 : ᾰ_2 = ᾰ_3) =>
congr (congr_arg Less e_2) e_3)
(coe_fn μ set.univ) 1 measure_univ ⊤ ⊤ (Eq.refl ⊤))
(propext (iff_true_intro ennreal.one_lt_top))))
trivial)
theorem probability_measure.ne_zero {α : Type u_1} [measurable_space α] (μ : measure α)
[probability_measure μ] : μ ≠ 0 :=
sorry
theorem measure_countable {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
[has_no_atoms μ] (h : set.countable s) : coe_fn μ s = 0 :=
sorry
theorem measure_finite {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
[has_no_atoms μ] (h : set.finite s) : coe_fn μ s = 0 :=
measure_countable (set.finite.countable h)
theorem measure_finset {α : Type u_1} [measurable_space α] {μ : measure α} [has_no_atoms μ]
(s : finset α) : coe_fn μ ↑s = 0 :=
measure_finite (finset.finite_to_set s)
theorem insert_ae_eq_self {α : Type u_1} [measurable_space α] {μ : measure α} [has_no_atoms μ]
(a : α) (s : set α) : filter.eventually_eq (measure.ae μ) (insert a s) s :=
iff.mpr union_ae_eq_right
(measure_mono_null (set.diff_subset (fun (b : α) => b = a) s) (measure_singleton a))
theorem Iio_ae_eq_Iic {α : Type u_1} [measurable_space α] {μ : measure α} [has_no_atoms μ]
[partial_order α] {a : α} : filter.eventually_eq (measure.ae μ) (set.Iio a) (set.Iic a) :=
sorry
theorem Ioi_ae_eq_Ici {α : Type u_1} [measurable_space α] {μ : measure α} [has_no_atoms μ]
[partial_order α] {a : α} : filter.eventually_eq (measure.ae μ) (set.Ioi a) (set.Ici a) :=
Iio_ae_eq_Iic
theorem Ioo_ae_eq_Ioc {α : Type u_1} [measurable_space α] {μ : measure α} [has_no_atoms μ]
[partial_order α] {a : α} {b : α} :
filter.eventually_eq (measure.ae μ) (set.Ioo a b) (set.Ioc a b) :=
filter.eventually_eq.inter (ae_eq_refl fun (x : α) => preorder.lt a x) Iio_ae_eq_Iic
theorem Ioc_ae_eq_Icc {α : Type u_1} [measurable_space α] {μ : measure α} [has_no_atoms μ]
[partial_order α] {a : α} {b : α} :
filter.eventually_eq (measure.ae μ) (set.Ioc a b) (set.Icc a b) :=
filter.eventually_eq.inter Ioi_ae_eq_Ici (ae_eq_refl fun (x : α) => preorder.le x b)
theorem Ioo_ae_eq_Ico {α : Type u_1} [measurable_space α] {μ : measure α} [has_no_atoms μ]
[partial_order α] {a : α} {b : α} :
filter.eventually_eq (measure.ae μ) (set.Ioo a b) (set.Ico a b) :=
filter.eventually_eq.inter Ioi_ae_eq_Ici (ae_eq_refl fun (x : α) => preorder.lt x b)
theorem Ioo_ae_eq_Icc {α : Type u_1} [measurable_space α] {μ : measure α} [has_no_atoms μ]
[partial_order α] {a : α} {b : α} :
filter.eventually_eq (measure.ae μ) (set.Ioo a b) (set.Icc a b) :=
filter.eventually_eq.inter Ioi_ae_eq_Ici Iio_ae_eq_Iic
theorem Ico_ae_eq_Icc {α : Type u_1} [measurable_space α] {μ : measure α} [has_no_atoms μ]
[partial_order α] {a : α} {b : α} :
filter.eventually_eq (measure.ae μ) (set.Ico a b) (set.Icc a b) :=
filter.eventually_eq.inter (ae_eq_refl fun (x : α) => preorder.le a x) Iio_ae_eq_Iic
theorem Ico_ae_eq_Ioc {α : Type u_1} [measurable_space α] {μ : measure α} [has_no_atoms μ]
[partial_order α] {a : α} {b : α} :
filter.eventually_eq (measure.ae μ) (set.Ico a b) (set.Ioc a b) :=
filter.eventually_eq.trans (filter.eventually_eq.symm Ioo_ae_eq_Ico) Ioo_ae_eq_Ioc
theorem ite_ae_eq_of_measure_zero {α : Type u_1} [measurable_space α] {μ : measure α} {γ : Type u_2}
(f : α → γ) (g : α → γ) (s : set α) (hs_zero : coe_fn μ s = 0) :
filter.eventually_eq (measure.ae μ) (fun (x : α) => ite (x ∈ s) (f x) (g x)) g :=
sorry
theorem ite_ae_eq_of_measure_compl_zero {α : Type u_1} [measurable_space α] {μ : measure α}
{γ : Type u_2} (f : α → γ) (g : α → γ) (s : set α) (hs_zero : coe_fn μ (sᶜ) = 0) :
filter.eventually_eq (measure.ae μ) (fun (x : α) => ite (x ∈ s) (f x) (g x)) f :=
sorry
namespace measure
/-- A measure is called finite at filter `f` if it is finite at some set `s ∈ f`.
Equivalently, it is eventually finite at `s` in `f.lift' powerset`. -/
def finite_at_filter {α : Type u_1} [measurable_space α] (μ : measure α) (f : filter α) :=
∃ (s : set α), ∃ (H : s ∈ f), coe_fn μ s < ⊤
theorem finite_at_filter_of_finite {α : Type u_1} [measurable_space α] (μ : measure α)
[finite_measure μ] (f : filter α) : finite_at_filter μ f :=
Exists.intro set.univ (Exists.intro filter.univ_mem_sets (measure_lt_top μ set.univ))
theorem finite_at_filter.exists_mem_basis {α : Type u_1} {ι : Type u_5} [measurable_space α]
{μ : measure α} {f : filter α} (hμ : finite_at_filter μ f) {p : ι → Prop} {s : ι → set α}
(hf : filter.has_basis f p s) : ∃ (i : ι), ∃ (hi : p i), coe_fn μ (s i) < ⊤ :=
sorry
theorem finite_at_bot {α : Type u_1} [measurable_space α] (μ : measure α) : finite_at_filter μ ⊥ :=
sorry
/-- `μ` has finite spanning sets in `C` if there is a countable sequence of sets in `C` that have
finite measures. This structure is a type, which is useful if we want to record extra properties
about the sets, such as that they are monotone.
`sigma_finite` is defined in terms of this: `μ` is σ-finite if there exists a sequence of
finite spanning sets in the collection of all measurable sets. -/
structure finite_spanning_sets_in {α : Type u_1} [measurable_space α] (μ : measure α)
(C : set (set α))
where
set : ℕ → set α
set_mem : ∀ (i : ℕ), set i ∈ C
finite : ∀ (i : ℕ), coe_fn μ (set i) < ⊤
spanning : (set.Union fun (i : ℕ) => set i) = set.univ
end measure
/-- A measure `μ` is called σ-finite if there is a countable collection of sets
`{ A i | i ∈ ℕ }` such that `μ (A i) < ⊤` and `⋃ i, A i = s`. -/
def sigma_finite {α : Type u_1} [measurable_space α] (μ : measure α) :=
Nonempty (measure.finite_spanning_sets_in μ (set_of fun (s : set α) => is_measurable s))
/-- If `μ` is σ-finite it has finite spanning sets in the collection of all measurable sets. -/
def measure.to_finite_spanning_sets_in {α : Type u_1} [measurable_space α] (μ : measure α)
[h : sigma_finite μ] :
measure.finite_spanning_sets_in μ (set_of fun (s : set α) => is_measurable s) :=
Classical.choice h
/-- A noncomputable way to get a monotone collection of sets that span `univ` and have finite
measure using `classical.some`. This definition satisfies monotonicity in addition to all other
properties in `sigma_finite`. -/
def spanning_sets {α : Type u_1} [measurable_space α] (μ : measure α) [sigma_finite μ] (i : ℕ) :
set α :=
set.accumulate (measure.finite_spanning_sets_in.set (measure.to_finite_spanning_sets_in μ)) i
theorem monotone_spanning_sets {α : Type u_1} [measurable_space α] (μ : measure α)
[sigma_finite μ] : monotone (spanning_sets μ) :=
set.monotone_accumulate
theorem is_measurable_spanning_sets {α : Type u_1} [measurable_space α] (μ : measure α)
[sigma_finite μ] (i : ℕ) : is_measurable (spanning_sets μ i) :=
sorry
theorem measure_spanning_sets_lt_top {α : Type u_1} [measurable_space α] (μ : measure α)
[sigma_finite μ] (i : ℕ) : coe_fn μ (spanning_sets μ i) < ⊤ :=
measure_bUnion_lt_top (set.finite_le_nat i)
fun (j : ℕ) (_x : j ∈ fun (y : ℕ) => nat.less_than_or_equal y i) =>
measure.finite_spanning_sets_in.finite (measure.to_finite_spanning_sets_in μ) j
theorem Union_spanning_sets {α : Type u_1} [measurable_space α] (μ : measure α) [sigma_finite μ] :
(set.Union fun (i : ℕ) => spanning_sets μ i) = set.univ :=
sorry
theorem is_countably_spanning_spanning_sets {α : Type u_1} [measurable_space α] (μ : measure α)
[sigma_finite μ] : is_countably_spanning (set.range (spanning_sets μ)) :=
Exists.intro (spanning_sets μ) { left := set.mem_range_self, right := Union_spanning_sets μ }
namespace measure
theorem supr_restrict_spanning_sets {α : Type u_1} [measurable_space α] {μ : measure α} {s : set α}
[sigma_finite μ] (hs : is_measurable s) :
(supr fun (i : ℕ) => coe_fn (restrict μ (spanning_sets μ i)) s) = coe_fn μ s :=
sorry
namespace finite_spanning_sets_in
/-- If `μ` has finite spanning sets in `C` and `C ⊆ D` then `μ` has finite spanning sets in `D`. -/
protected def mono {α : Type u_1} [measurable_space α] {μ : measure α} {C : set (set α)}
{D : set (set α)} (h : finite_spanning_sets_in μ C) (hC : C ⊆ D) :
finite_spanning_sets_in μ D :=
mk (finite_spanning_sets_in.set h) sorry (finite_spanning_sets_in.finite h)
(finite_spanning_sets_in.spanning h)
/-- If `μ` has finite spanning sets in the collection of measurable sets `C`, then `μ` is σ-finite.
-/
protected theorem sigma_finite {α : Type u_1} [measurable_space α] {μ : measure α} {C : set (set α)}
(h : finite_spanning_sets_in μ C) (hC : ∀ (s : set α), s ∈ C → is_measurable s) :
sigma_finite μ :=
Nonempty.intro (finite_spanning_sets_in.mono h hC)
/-- An extensionality for measures. It is `ext_of_generate_from_of_Union` formulated in terms of
`finite_spanning_sets_in`. -/
protected theorem ext {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α}
{C : set (set α)} (hA : _inst_1 = measurable_space.generate_from C) (hC : is_pi_system C)
(h : finite_spanning_sets_in μ C) (h_eq : ∀ (s : set α), s ∈ C → coe_fn μ s = coe_fn ν s) :
μ = ν :=
ext_of_generate_from_of_Union C (fun (i : ℕ) => finite_spanning_sets_in.set h i) hA hC
(finite_spanning_sets_in.spanning h) (finite_spanning_sets_in.set_mem h)
(finite_spanning_sets_in.finite h) h_eq
protected theorem is_countably_spanning {α : Type u_1} [measurable_space α] {μ : measure α}
{C : set (set α)} (h : finite_spanning_sets_in μ C) : is_countably_spanning C :=
Exists.intro (fun (i : ℕ) => finite_spanning_sets_in.set h i)
{ left := finite_spanning_sets_in.set_mem h, right := finite_spanning_sets_in.spanning h }
end finite_spanning_sets_in
theorem sigma_finite_of_not_nonempty {α : Type u_1} [measurable_space α] (μ : measure α)
(hα : ¬Nonempty α) : sigma_finite μ :=
sorry
theorem sigma_finite_of_countable {α : Type u_1} [measurable_space α] {μ : measure α}
{S : set (set α)} (hc : set.countable S) (hμ : ∀ (s : set α), s ∈ S → coe_fn μ s < ⊤)
(hU : ⋃₀S = set.univ) : sigma_finite μ :=
sorry
end measure
/-- Every finite measure is σ-finite. -/
protected instance finite_measure.to_sigma_finite {α : Type u_1} [measurable_space α]
(μ : measure α) [finite_measure μ] : sigma_finite μ :=
Nonempty.intro
(measure.finite_spanning_sets_in.mk (fun (_x : ℕ) => set.univ)
(fun (_x : ℕ) => is_measurable.univ) (fun (_x : ℕ) => measure_lt_top μ set.univ)
(set.Union_const set.univ))
protected instance restrict.sigma_finite {α : Type u_1} [measurable_space α] (μ : measure α)
[sigma_finite μ] (s : set α) : sigma_finite (measure.restrict μ s) :=
Nonempty.intro
(measure.finite_spanning_sets_in.mk (spanning_sets μ) (is_measurable_spanning_sets μ)
(fun (i : ℕ) =>
eq.mpr
(id
(Eq._oldrec (Eq.refl (coe_fn (measure.restrict μ s) (spanning_sets μ i) < ⊤))
(measure.restrict_apply (is_measurable_spanning_sets μ i))))
(has_le.le.trans_lt (measure_mono (set.inter_subset_left (spanning_sets μ i) s))
(measure_spanning_sets_lt_top μ i)))
(Union_spanning_sets μ))
protected instance sum.sigma_finite {α : Type u_1} [measurable_space α] {ι : Type u_2} [fintype ι]
(μ : ι → measure α) [∀ (i : ι), sigma_finite (μ i)] : sigma_finite (measure.sum μ) :=
sorry
protected instance add.sigma_finite {α : Type u_1} [measurable_space α] (μ : measure α)
(ν : measure α) [sigma_finite μ] [sigma_finite ν] : sigma_finite (μ + ν) :=
eq.mpr (id (Eq._oldrec (Eq.refl (sigma_finite (μ + ν))) (Eq.symm (measure.sum_cond μ ν))))
(sum.sigma_finite fun (b : Bool) => cond b μ ν)
/-- A measure is called locally finite if it is finite in some neighborhood of each point. -/
class locally_finite_measure {α : Type u_1} [measurable_space α] [topological_space α]
(μ : measure α)
where
finite_at_nhds : ∀ (x : α), measure.finite_at_filter μ (nhds x)
protected instance finite_measure.to_locally_finite_measure {α : Type u_1} [measurable_space α]
[topological_space α] (μ : measure α) [finite_measure μ] : locally_finite_measure μ :=
locally_finite_measure.mk fun (x : α) => measure.finite_at_filter_of_finite μ (nhds x)
theorem measure.finite_at_nhds {α : Type u_1} [measurable_space α] [topological_space α]
(μ : measure α) [locally_finite_measure μ] (x : α) : measure.finite_at_filter μ (nhds x) :=
locally_finite_measure.finite_at_nhds x
theorem measure.smul_finite {α : Type u_1} [measurable_space α] (μ : measure α) [finite_measure μ]
{c : ennreal} (hc : c < ⊤) : finite_measure (c • μ) :=
finite_measure.mk
(eq.mpr
(id (Eq._oldrec (Eq.refl (coe_fn (c • μ) set.univ < ⊤)) (measure.smul_apply c μ set.univ)))
(ennreal.mul_lt_top hc (measure_lt_top μ set.univ)))
theorem measure.exists_is_open_measure_lt_top {α : Type u_1} [measurable_space α]
[topological_space α] (μ : measure α) [locally_finite_measure μ] (x : α) :
∃ (s : set α), x ∈ s ∧ is_open s ∧ coe_fn μ s < ⊤ :=
sorry
protected instance sigma_finite_of_locally_finite {α : Type u_1} [measurable_space α]
[topological_space α] [topological_space.second_countable_topology α] {μ : measure α}
[locally_finite_measure μ] : sigma_finite μ :=
sorry
/-- If two finite measures give the same mass to the whole space and coincide on a π-system made
of measurable sets, then they coincide on all sets in the σ-algebra generated by the π-system. -/
theorem ext_on_measurable_space_of_generate_finite {α : Type u_1} (m₀ : measurable_space α)
{μ : measure α} {ν : measure α} [finite_measure μ] (C : set (set α))
(hμν : ∀ (s : set α), s ∈ C → coe_fn μ s = coe_fn ν s) {m : measurable_space α} (h : m ≤ m₀)
(hA : m = measurable_space.generate_from C) (hC : is_pi_system C)
(h_univ : coe_fn μ set.univ = coe_fn ν set.univ) {s : set α}
(hs : measurable_space.is_measurable' m s) : coe_fn μ s = coe_fn ν s :=
sorry
/-- Two finite measures are equal if they are equal on the π-system generating the σ-algebra
(and `univ`). -/
theorem ext_of_generate_finite {α : Type u_1} [measurable_space α] (C : set (set α))
(hA : _inst_1 = measurable_space.generate_from C) (hC : is_pi_system C) {μ : measure α}
{ν : measure α} [finite_measure μ] (hμν : ∀ (s : set α), s ∈ C → coe_fn μ s = coe_fn ν s)
(h_univ : coe_fn μ set.univ = coe_fn ν set.univ) : μ = ν :=
measure.ext
fun (s : set α) (hs : is_measurable s) =>
ext_on_measurable_space_of_generate_finite _inst_1 C hμν (le_refl _inst_1) hA hC h_univ hs
namespace measure
namespace finite_at_filter
theorem filter_mono {α : Type u_1} [measurable_space α] {μ : measure α} {f : filter α}
{g : filter α} (h : f ≤ g) : finite_at_filter μ g → finite_at_filter μ f :=
sorry
theorem inf_of_left {α : Type u_1} [measurable_space α] {μ : measure α} {f : filter α}
{g : filter α} (h : finite_at_filter μ f) : finite_at_filter μ (f ⊓ g) :=
filter_mono inf_le_left h
theorem inf_of_right {α : Type u_1} [measurable_space α] {μ : measure α} {f : filter α}
{g : filter α} (h : finite_at_filter μ g) : finite_at_filter μ (f ⊓ g) :=
filter_mono inf_le_right h
@[simp] theorem inf_ae_iff {α : Type u_1} [measurable_space α] {μ : measure α} {f : filter α} :
finite_at_filter μ (f ⊓ ae μ) ↔ finite_at_filter μ f :=
sorry
theorem of_inf_ae {α : Type u_1} [measurable_space α] {μ : measure α} {f : filter α} :
finite_at_filter μ (f ⊓ ae μ) → finite_at_filter μ f :=
iff.mp inf_ae_iff
theorem filter_mono_ae {α : Type u_1} [measurable_space α] {μ : measure α} {f : filter α}
{g : filter α} (h : f ⊓ ae μ ≤ g) (hg : finite_at_filter μ g) : finite_at_filter μ f :=
iff.mp inf_ae_iff (filter_mono h hg)
protected theorem measure_mono {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α}
{f : filter α} (h : μ ≤ ν) : finite_at_filter ν f → finite_at_filter μ f :=
sorry
protected theorem mono {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α}
{f : filter α} {g : filter α} (hf : f ≤ g) (hμ : μ ≤ ν) :
finite_at_filter ν g → finite_at_filter μ f :=
fun (h : finite_at_filter ν g) => finite_at_filter.measure_mono hμ (filter_mono hf h)
protected theorem eventually {α : Type u_1} [measurable_space α] {μ : measure α} {f : filter α}
(h : finite_at_filter μ f) :
filter.eventually (fun (s : set α) => coe_fn μ s < ⊤) (filter.lift' f set.powerset) :=
sorry
theorem filter_sup {α : Type u_1} [measurable_space α] {μ : measure α} {f : filter α}
{g : filter α} : finite_at_filter μ f → finite_at_filter μ g → finite_at_filter μ (f ⊔ g) :=
sorry
end finite_at_filter
theorem finite_at_nhds_within {α : Type u_1} [measurable_space α] [topological_space α]
(μ : measure α) [locally_finite_measure μ] (x : α) (s : set α) :
finite_at_filter μ (nhds_within x s) :=
finite_at_filter.inf_of_left (finite_at_nhds μ x)
@[simp] theorem finite_at_principal {α : Type u_1} [measurable_space α] {μ : measure α}
{s : set α} : finite_at_filter μ (filter.principal s) ↔ coe_fn μ s < ⊤ :=
sorry
/-! ### Subtraction of measures -/
/-- The measure `μ - ν` is defined to be the least measure `τ` such that `μ ≤ τ + ν`.
It is the equivalent of `(μ - ν) ⊔ 0` if `μ` and `ν` were signed measures.
Compare with `ennreal.has_sub`.
Specifically, note that if you have `α = {1,2}`, and `μ {1} = 2`, `μ {2} = 0`, and
`ν {2} = 2`, `ν {1} = 0`, then `(μ - ν) {1, 2} = 2`. However, if `μ ≤ ν`, and
`ν univ ≠ ⊤`, then `(μ - ν) + ν = μ`. -/
protected instance has_sub {α : Type u_1} [measurable_space α] : Sub (measure α) :=
{ sub := fun (μ ν : measure α) => Inf (set_of fun (τ : measure α) => μ ≤ τ + ν) }
theorem sub_def {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α} :
μ - ν = Inf (set_of fun (d : measure α) => μ ≤ d + ν) :=
rfl
theorem sub_eq_zero_of_le {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α}
(h : μ ≤ ν) : μ - ν = 0 :=
sorry
/-- This application lemma only works in special circumstances. Given knowledge of
when `μ ≤ ν` and `ν ≤ μ`, a more general application lemma can be written. -/
theorem sub_apply {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α} {s : set α}
[finite_measure ν] (h₁ : is_measurable s) (h₂ : ν ≤ μ) :
coe_fn (μ - ν) s = coe_fn μ s - coe_fn ν s :=
sorry
theorem sub_add_cancel_of_le {α : Type u_1} [measurable_space α] {μ : measure α} {ν : measure α}
[finite_measure ν] (h₁ : ν ≤ μ) : μ - ν + ν = μ :=
sorry
end measure
end measure_theory
namespace measurable_equiv
/-! Interactions of measurable equivalences and measures -/
/-- If we map a measure along a measurable equivalence, we can compute the measure on all sets
(not just the measurable ones). -/
protected theorem map_apply {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{μ : measure_theory.measure α} (f : α ≃ᵐ β) (s : set β) :
coe_fn (coe_fn (measure_theory.measure.map ⇑f) μ) s = coe_fn μ (⇑f ⁻¹' s) :=
sorry
@[simp] theorem map_symm_map {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{μ : measure_theory.measure α} (e : α ≃ᵐ β) :
coe_fn (measure_theory.measure.map ⇑(symm e)) (coe_fn (measure_theory.measure.map ⇑e) μ) = μ :=
sorry
@[simp] theorem map_map_symm {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{ν : measure_theory.measure β} (e : α ≃ᵐ β) :
coe_fn (measure_theory.measure.map ⇑e) (coe_fn (measure_theory.measure.map ⇑(symm e)) ν) = ν :=
sorry
theorem map_measurable_equiv_injective {α : Type u_1} {β : Type u_2} [measurable_space α]
[measurable_space β] (e : α ≃ᵐ β) : function.injective ⇑(measure_theory.measure.map ⇑e) :=
sorry
theorem map_apply_eq_iff_map_symm_apply_eq {α : Type u_1} {β : Type u_2} [measurable_space α]
[measurable_space β] {μ : measure_theory.measure α} {ν : measure_theory.measure β}
(e : α ≃ᵐ β) :
coe_fn (measure_theory.measure.map ⇑e) μ = ν ↔
coe_fn (measure_theory.measure.map ⇑(symm e)) ν = μ :=
sorry
end measurable_equiv
/-- A measure is complete if every null set is also measurable.
A null set is a subset of a measurable set with measure `0`.
Since every measure is defined as a special case of an outer measure, we can more simply state
that a set `s` is null if `μ s = 0`. -/
def measure_theory.measure.is_complete {α : Type u_1} {_x : measurable_space α}
(μ : measure_theory.measure α) :=
∀ (s : set α), coe_fn μ s = 0 → is_measurable s
/-- A set is null measurable if it is the union of a null set and a measurable set. -/
def is_null_measurable {α : Type u_1} [measurable_space α] (μ : measure_theory.measure α)
(s : set α) :=
∃ (t : set α), ∃ (z : set α), s = t ∪ z ∧ is_measurable t ∧ coe_fn μ z = 0
theorem is_null_measurable_iff {α : Type u_1} [measurable_space α] {μ : measure_theory.measure α}
{s : set α} :
is_null_measurable μ s ↔ ∃ (t : set α), t ⊆ s ∧ is_measurable t ∧ coe_fn μ (s \ t) = 0 :=
sorry
theorem is_null_measurable_measure_eq {α : Type u_1} [measurable_space α]
{μ : measure_theory.measure α} {s : set α} {t : set α} (st : t ⊆ s)
(hz : coe_fn μ (s \ t) = 0) : coe_fn μ s = coe_fn μ t :=
sorry
theorem is_measurable.is_null_measurable {α : Type u_1} [measurable_space α] {s : set α}
(μ : measure_theory.measure α) (hs : is_measurable s) : is_null_measurable μ s :=
sorry
theorem is_null_measurable_of_complete {α : Type u_1} [measurable_space α] {s : set α}
(μ : measure_theory.measure α) [c : measure_theory.measure.is_complete μ] :
is_null_measurable μ s ↔ is_measurable s :=
sorry
theorem is_null_measurable.union_null {α : Type u_1} [measurable_space α]
{μ : measure_theory.measure α} {s : set α} {z : set α} (hs : is_null_measurable μ s)
(hz : coe_fn μ z = 0) : is_null_measurable μ (s ∪ z) :=
sorry
theorem null_is_null_measurable {α : Type u_1} [measurable_space α] {μ : measure_theory.measure α}
{z : set α} (hz : coe_fn μ z = 0) : is_null_measurable μ z :=
sorry
theorem is_null_measurable.Union_nat {α : Type u_1} [measurable_space α]
{μ : measure_theory.measure α} {s : ℕ → set α} (hs : ∀ (i : ℕ), is_null_measurable μ (s i)) :
is_null_measurable μ (set.Union s) :=
sorry
theorem is_measurable.diff_null {α : Type u_1} [measurable_space α] {μ : measure_theory.measure α}
{s : set α} {z : set α} (hs : is_measurable s) (hz : coe_fn μ z = 0) :
is_null_measurable μ (s \ z) :=
sorry
theorem is_null_measurable.diff_null {α : Type u_1} [measurable_space α]
{μ : measure_theory.measure α} {s : set α} {z : set α} (hs : is_null_measurable μ s)
(hz : coe_fn μ z = 0) : is_null_measurable μ (s \ z) :=
sorry
theorem is_null_measurable.compl {α : Type u_1} [measurable_space α] {μ : measure_theory.measure α}
{s : set α} (hs : is_null_measurable μ s) : is_null_measurable μ (sᶜ) :=
sorry
theorem is_null_measurable_iff_ae {α : Type u_1} [measurable_space α] {μ : measure_theory.measure α}
{s : set α} :
is_null_measurable μ s ↔
∃ (t : set α), is_measurable t ∧ filter.eventually_eq (measure_theory.measure.ae μ) s t :=
sorry
theorem is_null_measurable_iff_sandwich {α : Type u_1} [measurable_space α]
{μ : measure_theory.measure α} {s : set α} :
is_null_measurable μ s ↔
∃ (t : set α),
∃ (u : set α), is_measurable t ∧ is_measurable u ∧ t ⊆ s ∧ s ⊆ u ∧ coe_fn μ (u \ t) = 0 :=
sorry
theorem restrict_apply_of_is_null_measurable {α : Type u_1} [measurable_space α]
{μ : measure_theory.measure α} {s : set α} {t : set α}
(ht : is_null_measurable (measure_theory.measure.restrict μ s) t) :
coe_fn (measure_theory.measure.restrict μ s) t = coe_fn μ (t ∩ s) :=
sorry
/-- The measurable space of all null measurable sets. -/
def null_measurable {α : Type u_1} [measurable_space α] (μ : measure_theory.measure α) :
measurable_space α :=
measurable_space.mk (is_null_measurable μ) sorry sorry sorry
/-- Given a measure we can complete it to a (complete) measure on all null measurable sets. -/
def completion {α : Type u_1} [measurable_space α] (μ : measure_theory.measure α) :
measure_theory.measure α :=
measure_theory.measure.mk (measure_theory.measure.to_outer_measure μ) sorry sorry
protected instance completion.is_complete {α : Type u_1} [measurable_space α]
(μ : measure_theory.measure α) : measure_theory.measure.is_complete (completion μ) :=
fun (z : set α) (hz : coe_fn (completion μ) z = 0) => null_is_null_measurable hz
theorem measurable.ae_eq {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{μ : measure_theory.measure α} [hμ : measure_theory.measure.is_complete μ] {f : α → β}
{g : α → β} (hf : measurable f) (hfg : filter.eventually_eq (measure_theory.measure.ae μ) f g) :
measurable g :=
sorry
namespace measure_theory
/-- A measure space is a measurable space equipped with a
measure, referred to as `volume`. -/
class measure_space (α : Type u_6) extends measurable_space α where
volume : measure α
/-- `volume` is the canonical measure on `α`. -/
/-- The tactic `exact volume`, to be used in optional (`auto_param`) arguments. -/
end measure_theory
/-!
# Almost everywhere measurable functions
A function is almost everywhere measurable if it coincides almost everywhere with a measurable
function. We define this property, called `ae_measurable f μ`, and discuss several of its properties
that are analogous to properties of measurable functions.
-/
/-- A function is almost everywhere measurable if it coincides almost everywhere with a measurable
function. -/
def ae_measurable {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
(f : α → β)
(μ :
autoParam (measure_theory.measure α)
(Lean.Syntax.ident Lean.SourceInfo.none
(String.toSubstring "Mathlib.measure_theory.volume_tac")
(Lean.Name.mkStr
(Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "measure_theory")
"volume_tac")
[])) :=
∃ (g : α → β), measurable g ∧ filter.eventually_eq (measure_theory.measure.ae μ) f g
theorem measurable.ae_measurable {α : Type u_1} {β : Type u_2} [measurable_space α]
[measurable_space β] {f : α → β} {μ : measure_theory.measure α} (h : measurable f) :
ae_measurable f :=
Exists.intro f { left := h, right := measure_theory.ae_eq_refl f }
theorem subsingleton.ae_measurable {α : Type u_1} {β : Type u_2} [measurable_space α]
[measurable_space β] {f : α → β} {μ : measure_theory.measure α} [subsingleton α] :
ae_measurable f :=
measurable.ae_measurable subsingleton.measurable
@[simp] theorem ae_measurable_zero {α : Type u_1} {β : Type u_2} [measurable_space α]
[measurable_space β] {f : α → β} : ae_measurable f :=
sorry
theorem ae_measurable_iff_measurable {α : Type u_1} {β : Type u_2} [measurable_space α]
[measurable_space β] {f : α → β} {μ : measure_theory.measure α}
[measure_theory.measure.is_complete μ] : ae_measurable f ↔ measurable f :=
sorry
namespace ae_measurable
/-- Given an almost everywhere measurable function `f`, associate to it a measurable function
that coincides with it almost everywhere. `f` is explicit in the definition to make sure that
it shows in pretty-printing. -/
def mk {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{μ : measure_theory.measure α} (f : α → β) (h : ae_measurable f) : α → β :=
classical.some h
theorem measurable_mk {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{f : α → β} {μ : measure_theory.measure α} (h : ae_measurable f) : measurable (mk f h) :=
and.left (classical.some_spec h)
theorem ae_eq_mk {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {f : α → β}
{μ : measure_theory.measure α} (h : ae_measurable f) :
filter.eventually_eq (measure_theory.measure.ae μ) f (mk f h) :=
and.right (classical.some_spec h)
theorem congr {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {f : α → β}
{g : α → β} {μ : measure_theory.measure α} (hf : ae_measurable f)
(h : filter.eventually_eq (measure_theory.measure.ae μ) f g) : ae_measurable g :=
Exists.intro (mk f hf)
{ left := measurable_mk hf,
right := filter.eventually_eq.trans (filter.eventually_eq.symm h) (ae_eq_mk hf) }
theorem mono_measure {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{f : α → β} {μ : measure_theory.measure α} {ν : measure_theory.measure α} (h : ae_measurable f)
(h' : ν ≤ μ) : ae_measurable f :=
Exists.intro (mk f h)
{ left := measurable_mk h,
right := filter.eventually.filter_mono (measure_theory.ae_mono h') (ae_eq_mk h) }
theorem mono_set {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β] {f : α → β}
{μ : measure_theory.measure α} {s : set α} {t : set α} (h : s ⊆ t) (ht : ae_measurable f) :
ae_measurable f :=
mono_measure ht (measure_theory.measure.restrict_mono h le_rfl)
theorem ae_mem_imp_eq_mk {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{f : α → β} {μ : measure_theory.measure α} {s : set α} (h : ae_measurable f) :
filter.eventually (fun (x : α) => x ∈ s → f x = mk f h x) (measure_theory.measure.ae μ) :=
measure_theory.ae_imp_of_ae_restrict (ae_eq_mk h)
theorem ae_inf_principal_eq_mk {α : Type u_1} {β : Type u_2} [measurable_space α]
[measurable_space β] {f : α → β} {μ : measure_theory.measure α} {s : set α}
(h : ae_measurable f) :
filter.eventually_eq (measure_theory.measure.ae μ ⊓ filter.principal s) f (mk f h) :=
measure_theory.le_ae_restrict (ae_eq_mk h)
theorem add_measure {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{μ : measure_theory.measure α} {ν : measure_theory.measure α} {f : α → β} (hμ : ae_measurable f)
(hν : ae_measurable f) : ae_measurable f :=
sorry
theorem smul_measure {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{f : α → β} {μ : measure_theory.measure α} (h : ae_measurable f) (c : ennreal) :
ae_measurable f :=
Exists.intro (mk f h)
{ left := measurable_mk h, right := measure_theory.ae_smul_measure (ae_eq_mk h) c }
theorem comp_measurable {α : Type u_1} {β : Type u_2} {δ : Type u_4} [measurable_space α]
[measurable_space β] {μ : measure_theory.measure α} [measurable_space δ] {f : α → δ} {g : δ → β}
(hg : ae_measurable g) (hf : measurable f) : ae_measurable (g ∘ f) :=
Exists.intro (mk g hg ∘ f)
{ left := measurable.comp (measurable_mk hg) hf,
right := measure_theory.ae_eq_comp hf (ae_eq_mk hg) }
theorem prod_mk {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{μ : measure_theory.measure α} {γ : Type u_3} [measurable_space γ] {f : α → β} {g : α → γ}
(hf : ae_measurable f) (hg : ae_measurable g) : ae_measurable fun (x : α) => (f x, g x) :=
Exists.intro (fun (a : α) => (mk f hf a, mk g hg a))
{ left := measurable.prod_mk (measurable_mk hf) (measurable_mk hg),
right := filter.eventually_eq.prod_mk (ae_eq_mk hf) (ae_eq_mk hg) }
theorem is_null_measurable {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{f : α → β} {μ : measure_theory.measure α} (h : ae_measurable f) {s : set β}
(hs : is_measurable s) : is_null_measurable μ (f ⁻¹' s) :=
sorry
end ae_measurable
theorem ae_measurable_congr {α : Type u_1} {β : Type u_2} [measurable_space α] [measurable_space β]
{f : α → β} {g : α → β} {μ : measure_theory.measure α}
(h : filter.eventually_eq (measure_theory.measure.ae μ) f g) :
ae_measurable f ↔ ae_measurable g :=
{ mp := fun (hf : ae_measurable f) => ae_measurable.congr hf h,
mpr := fun (hg : ae_measurable g) => ae_measurable.congr hg (filter.eventually_eq.symm h) }
@[simp] theorem ae_measurable_add_measure_iff {α : Type u_1} {β : Type u_2} [measurable_space α]
[measurable_space β] {f : α → β} {μ : measure_theory.measure α} {ν : measure_theory.measure α} :
ae_measurable f ↔ ae_measurable f ∧ ae_measurable f :=
sorry
@[simp] theorem ae_measurable_const {α : Type u_1} {β : Type u_2} [measurable_space α]
[measurable_space β] {μ : measure_theory.measure α} {b : β} : ae_measurable fun (a : α) => b :=
measurable.ae_measurable measurable_const
@[simp] theorem ae_measurable_smul_measure_iff {α : Type u_1} {β : Type u_2} [measurable_space α]
[measurable_space β] {f : α → β} {μ : measure_theory.measure α} {c : ennreal} (hc : c ≠ 0) :
ae_measurable f ↔ ae_measurable f :=
sorry
theorem measurable.comp_ae_measurable {α : Type u_1} {β : Type u_2} {δ : Type u_4}
[measurable_space α] [measurable_space β] {μ : measure_theory.measure α} [measurable_space δ]
{f : α → δ} {g : δ → β} (hg : measurable g) (hf : ae_measurable f) : ae_measurable (g ∘ f) :=
Exists.intro (g ∘ ae_measurable.mk f hf)
{ left := measurable.comp hg (ae_measurable.measurable_mk hf),
right := filter.eventually_eq.fun_comp (ae_measurable.ae_eq_mk hf) g }
theorem ae_measurable_of_zero_measure {α : Type u_1} {β : Type u_2} [measurable_space α]
[measurable_space β] {f : α → β} : ae_measurable f :=
dite (Nonempty α) (fun (h : Nonempty α) => ae_measurable.congr ae_measurable_const rfl)
fun (h : ¬Nonempty α) => measurable.ae_measurable (measurable_of_not_nonempty h f)
namespace is_compact
theorem finite_measure_of_nhds_within {α : Type u_1} [topological_space α] [measurable_space α]
{μ : measure_theory.measure α} {s : set α} (hs : is_compact s) :
(∀ (a : α), a ∈ s → measure_theory.measure.finite_at_filter μ (nhds_within a s)) →
coe_fn μ s < ⊤ :=
sorry
theorem finite_measure {α : Type u_1} [topological_space α] [measurable_space α]
{μ : measure_theory.measure α} {s : set α} [measure_theory.locally_finite_measure μ]
(hs : is_compact s) : coe_fn μ s < ⊤ :=
finite_measure_of_nhds_within hs
fun (a : α) (ha : a ∈ s) => measure_theory.measure.finite_at_nhds_within μ a s
theorem measure_zero_of_nhds_within {α : Type u_1} [topological_space α] [measurable_space α]
{μ : measure_theory.measure α} {s : set α} (hs : is_compact s) :
(∀ (a : α) (H : a ∈ s), ∃ (t : set α), ∃ (H : t ∈ nhds_within a s), coe_fn μ t = 0) →
coe_fn μ s = 0 :=
sorry
end is_compact
theorem metric.bounded.finite_measure {α : Type u_1} [metric_space α] [proper_space α]
[measurable_space α] {μ : measure_theory.measure α} [measure_theory.locally_finite_measure μ]
{s : set α} (hs : metric.bounded s) : coe_fn μ s < ⊤ :=
sorry
end Mathlib |
9ae2f4852d10f8a390a7c75d04bc06d354f9172c | 57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d | /src/Std/Data/Stack.lean | 19a561190f277064ba4de70f8c3a4e11f7cfaea9 | [
"Apache-2.0"
] | permissive | collares/lean4 | 861a9269c4592bce49b71059e232ff0bfe4594cc | 52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee | refs/heads/master | 1,691,419,031,324 | 1,618,678,138,000 | 1,618,678,138,000 | 358,989,750 | 0 | 0 | Apache-2.0 | 1,618,696,333,000 | 1,618,696,333,000 | null | UTF-8 | Lean | false | false | 901 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Daniel Selsam
Simple stack API implemented using an array.
-/
namespace Std
universes u v w
structure Stack (α : Type u) where
vals : Array α := #[]
namespace Stack
variable {α : Type u}
def empty : Stack α := {}
def isEmpty (s : Stack α) : Bool :=
s.vals.isEmpty
def push (v : α) (s : Stack α) : Stack α :=
{ s with vals := s.vals.push v }
def peek? (s : Stack α) : Option α :=
if s.vals.isEmpty then none else s.vals.get? (s.vals.size-1)
def peek! [Inhabited α] (s : Stack α) : α :=
s.vals.back
def pop [Inhabited α] (s : Stack α) : Stack α :=
{ s with vals := s.vals.pop }
def modify [Inhabited α] (s : Stack α) (f : α → α) : Stack α :=
{ s with vals := s.vals.modify (s.vals.size-1) f }
end Stack
end Std
|
1d70dde6c6987e4fb247c4aa33dfae717a927d1e | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/order/positive/ring.lean | 9b76e2a533f778242a4beb85edf1d5c0053a0c71 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 4,624 | 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 algebra.order.ring.defs
import algebra.ring.inj_surj
/-!
# Algebraic structures on the set of positive numbers
In this file we define various instances (`add_semigroup`, `ordered_comm_monoid` etc) on the
type `{x : R // 0 < x}`. In each case we try to require the weakest possible typeclass
assumptions on `R` but possibly, there is a room for improvements.
-/
open function
namespace positive
variables {M R K : Type*}
section add_basic
variables [add_monoid M] [preorder M] [covariant_class M M (+) (<)]
instance : has_add {x : M // 0 < x} := ⟨λ x y, ⟨x + y, add_pos x.2 y.2⟩⟩
@[simp, norm_cast] lemma coe_add (x y : {x : M // 0 < x}) : ↑(x + y) = (x + y : M) := rfl
instance : add_semigroup {x : M // 0 < x} := subtype.coe_injective.add_semigroup _ coe_add
instance {M : Type*} [add_comm_monoid M] [preorder M] [covariant_class M M (+) (<)] :
add_comm_semigroup {x : M // 0 < x} :=
subtype.coe_injective.add_comm_semigroup _ coe_add
instance {M : Type*} [add_left_cancel_monoid M] [preorder M] [covariant_class M M (+) (<)] :
add_left_cancel_semigroup {x : M // 0 < x} :=
subtype.coe_injective.add_left_cancel_semigroup _ coe_add
instance {M : Type*} [add_right_cancel_monoid M] [preorder M] [covariant_class M M (+) (<)] :
add_right_cancel_semigroup {x : M // 0 < x} :=
subtype.coe_injective.add_right_cancel_semigroup _ coe_add
instance covariant_class_add_lt : covariant_class {x : M // 0 < x} {x : M // 0 < x} (+) (<) :=
⟨λ x y z hyz, subtype.coe_lt_coe.1 $ add_lt_add_left hyz _⟩
instance covariant_class_swap_add_lt [covariant_class M M (swap (+)) (<)] :
covariant_class {x : M // 0 < x} {x : M // 0 < x} (swap (+)) (<) :=
⟨λ x y z hyz, subtype.coe_lt_coe.1 $ add_lt_add_right hyz _⟩
instance contravariant_class_add_lt [contravariant_class M M (+) (<)] :
contravariant_class {x : M // 0 < x} {x : M // 0 < x} (+) (<) :=
⟨λ x y z h, subtype.coe_lt_coe.1 $ lt_of_add_lt_add_left h⟩
instance contravariant_class_swap_add_lt [contravariant_class M M (swap (+)) (<)] :
contravariant_class {x : M // 0 < x} {x : M // 0 < x} (swap (+)) (<) :=
⟨λ x y z h, subtype.coe_lt_coe.1 $ lt_of_add_lt_add_right h⟩
instance contravariant_class_add_le [contravariant_class M M (+) (≤)] :
contravariant_class {x : M // 0 < x} {x : M // 0 < x} (+) (≤) :=
⟨λ x y z h, subtype.coe_le_coe.1 $ le_of_add_le_add_left h⟩
instance contravariant_class_swap_add_le [contravariant_class M M (swap (+)) (≤)] :
contravariant_class {x : M // 0 < x} {x : M // 0 < x} (swap (+)) (≤) :=
⟨λ x y z h, subtype.coe_le_coe.1 $ le_of_add_le_add_right h⟩
end add_basic
instance covariant_class_add_le [add_monoid M] [partial_order M] [covariant_class M M (+) (<)] :
covariant_class {x : M // 0 < x} {x : M // 0 < x} (+) (≤) :=
⟨λ x, strict_mono.monotone $ λ _ _ h, add_lt_add_left h _⟩
section mul
variables [strict_ordered_semiring R]
instance : has_mul {x : R // 0 < x} := ⟨λ x y, ⟨x * y, mul_pos x.2 y.2⟩⟩
@[simp] lemma coe_mul (x y : {x : R // 0 < x}) : ↑(x * y) = (x * y : R) := rfl
instance : has_pow {x : R // 0 < x} ℕ := ⟨λ x n, ⟨x ^ n, pow_pos x.2 n⟩⟩
@[simp] lemma coe_pow (x : {x : R // 0 < x}) (n : ℕ) : ↑(x ^ n) = (x ^ n : R) := rfl
instance : semigroup {x : R // 0 < x} := subtype.coe_injective.semigroup coe coe_mul
instance : distrib {x : R // 0 < x} := subtype.coe_injective.distrib _ coe_add coe_mul
instance [nontrivial R] : has_one {x : R // 0 < x} := ⟨⟨1, one_pos⟩⟩
@[simp] lemma coe_one [nontrivial R] : ((1 : {x : R // 0 < x}) : R) = 1 := rfl
instance [nontrivial R] : monoid {x : R // 0 < x} :=
subtype.coe_injective.monoid _ coe_one coe_mul coe_pow
end mul
section mul_comm
instance [strict_ordered_comm_semiring R] [nontrivial R] : ordered_comm_monoid {x : R // 0 < x} :=
{ mul_le_mul_left := λ x y hxy c, subtype.coe_le_coe.1 $ mul_le_mul_of_nonneg_left hxy c.2.le,
.. subtype.partial_order _,
.. subtype.coe_injective.comm_monoid (coe : {x : R // 0 < x} → R) coe_one coe_mul coe_pow }
/-- If `R` is a nontrivial linear ordered commutative semiring, then `{x : R // 0 < x}` is a linear
ordered cancellative commutative monoid. -/
instance [linear_ordered_comm_semiring R] : linear_ordered_cancel_comm_monoid {x : R // 0 < x} :=
{ le_of_mul_le_mul_left := λ a b c h, subtype.coe_le_coe.1 $ (mul_le_mul_left a.2).1 h,
.. subtype.linear_order _, .. positive.subtype.ordered_comm_monoid }
end mul_comm
end positive
|
a34ddd688856511ddc3006c30f2d502bde19a499 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/elabissues/equation_compiler_slow_with_many_constructors.lean | 4931ed57d0c3be1d2575192842aa415feba89dbb | [
"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 | 3,720 | lean | /-
This file contains an example of an inductive type with many constructors,
for which pattern matching is expensive enough to noticeably slow down Emacs.
Note that the annoyance is magnified with the current Emacs mode
because every modification to the inductive type immediately triggers
recompilation of the downstream equations.
-/
inductive Op : Type
| add, mul, inv, div, sub, fact, pow
inductive Term : Type
| ofInt : Int → Term
| var : Nat → Term
| varPow : Nat → Nat → Term
| app : Op → Term → Term → Term
open Term
inductive Proof : Type
| addZero : Term → Proof
| zeroAdd : Term → Proof
| addComm : Term → Term → Proof
| addCommL : Term → Term → Term → Proof
| addAssoc : Term → Term → Term → Proof
| mulZero : Term → Proof
| zeroMul : Term → Proof
| mulOne : Term → Proof
| oneMul : Term → Proof
| mulComm : Term → Term → Proof
| mulCommL : Term → Term → Term → Proof
| mulAssoc : Term → Term → Term → Proof
| distribL : Term → Term → Term → Proof
| distribR : Term → Term → Term → Proof
| fact0 : Proof
| factS : Nat → Proof
| tpow0 : Term → Proof
| tpow1 : Term → Proof
| tpowS : Term → Term → Proof
| ofIntAdd : Int → Int → Proof
| ofIntMul : Int → Int → Proof
| subDef : Term → Term → Proof
| powZero : Nat → Proof
| powOne : Nat → Proof
| powMerge : Nat → Nat → Nat → Proof
| powMergeL : Nat → Nat → Nat → Term → Proof
| mulInvCan : Term → Proof
| invMulCan : Term → Proof
| fuse : Term → Term → Proof
| fuseL : Term → Term → Term → Proof
| oneDivInv : Term → Proof
| oneInvEq : Proof
| divDef : Term → Term → Proof
| congrArg₁ : Op → Proof → Term → Proof
| congrArg₂ : Op → Term → Proof → Proof
| congrArgs : Op → Proof → Proof → Proof
| refl : Term → Proof
| trans : Proof → Proof → Proof
open Proof
structure Result : Type :=
(val : Term)
(pf : Proof)
set_option eqn_compiler.max_steps 5000
def mergeCongr1 (op : Op) (x₁ y₁ : Term) : Result → Result → Result
| ⟨_, refl _⟩, ⟨_, refl _⟩ => ⟨app op x₁ y₁, refl $ app op x₁ y₁⟩
| ⟨x₂, px⟩, ⟨_, refl _⟩ => ⟨app op x₂ y₁, congrArg₁ op px y₁⟩
| ⟨_, refl _⟩, ⟨y₂, py⟩ => ⟨app op x₁ y₂, congrArg₂ op x₁ py⟩
| ⟨x₂, px⟩, ⟨y₂, py⟩ => ⟨app op x₂ y₂, congrArgs op px py⟩
-- The following is much faster (but still slow) because the current equation compiler is dumb and is doing a lot of duplicate work.
def mergeCongr2 (op : Op) (x₁ y₁ : Term) (r₁ r₂ : Result) : Result :=
match r₁ with
| ⟨_, refl _⟩ =>
match r₂ with
| ⟨_, refl _⟩ => ⟨app op x₁ y₁, refl $ app op x₁ y₁⟩
| ⟨y₂, py⟩ => ⟨app op x₁ y₂, congrArg₂ op x₁ py⟩
| ⟨x₂, px⟩ =>
match r₂ with
| ⟨_, refl _⟩ => ⟨app op x₂ y₁, congrArg₁ op px y₁⟩
| ⟨y₂, py⟩ => ⟨app op x₂ y₂, congrArgs op px py⟩
-- Plan: in the new equation compiler we should use join points (special kind of let-decls) to avoid duplicate work.
def isRefl : Proof → Bool
| refl _ => true
| _ => false
-- Very fast to compile using Lean3 equation compiler
def mergeCongr3 (op : Op) (x₁ y₁ : Term) : Result → Result → Result
| ⟨x₂, px⟩, ⟨y₂, py⟩ =>
match isRefl px, isRefl py with
| true, true => ⟨app op x₁ y₁, refl $ app op x₁ y₁⟩
| false, true => ⟨app op x₂ y₁, congrArg₁ op px y₁⟩
| true, false => ⟨app op x₁ y₂, congrArg₂ op x₁ py⟩
| false, false => ⟨app op x₂ y₂, congrArgs op px py⟩
|
64d66a45c60803c26d221f4cf0a7bbdec38cfbf0 | 4950bf76e5ae40ba9f8491647d0b6f228ddce173 | /src/analysis/analytic/composition.lean | d16b99c85f650f657182ca02f62c3521ee0cfc3b | [
"Apache-2.0"
] | permissive | ntzwq/mathlib | ca50b21079b0a7c6781c34b62199a396dd00cee2 | 36eec1a98f22df82eaccd354a758ef8576af2a7f | refs/heads/master | 1,675,193,391,478 | 1,607,822,996,000 | 1,607,822,996,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 56,698 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Johan Commelin
-/
import analysis.analytic.basic
import combinatorics.composition
/-!
# Composition of analytic functions
in this file we prove that the composition of analytic functions is analytic.
The argument is the following. Assume `g z = ∑' qₙ (z, ..., z)` and `f y = ∑' pₖ (y, ..., y)`. Then
`g (f y) = ∑' qₙ (∑' pₖ (y, ..., y), ..., ∑' pₖ (y, ..., y))
= ∑' qₙ (p_{i₁} (y, ..., y), ..., p_{iₙ} (y, ..., y))`.
For each `n` and `i₁, ..., iₙ`, define a `i₁ + ... + iₙ` multilinear function mapping
`(y₀, ..., y_{i₁ + ... + iₙ - 1})` to
`qₙ (p_{i₁} (y₀, ..., y_{i₁-1}), p_{i₂} (y_{i₁}, ..., y_{i₁ + i₂ - 1}), ..., p_{iₙ} (....)))`.
Then `g ∘ f` is obtained by summing all these multilinear functions.
To formalize this, we use compositions of an integer `N`, i.e., its decompositions into
a sum `i₁ + ... + iₙ` of positive integers. Given such a composition `c` and two formal
multilinear series `q` and `p`, let `q.comp_along_composition p c` be the above multilinear
function. Then the `N`-th coefficient in the power series expansion of `g ∘ f` is the sum of these
terms over all `c : composition N`.
To complete the proof, we need to show that this power series has a positive radius of convergence.
This follows from the fact that `composition N` has cardinality `2^(N-1)` and estimates on
the norm of `qₙ` and `pₖ`, which give summability. We also need to show that it indeed converges to
`g ∘ f`. For this, we note that the composition of partial sums converges to `g ∘ f`, and that it
corresponds to a part of the whole sum, on a subset that increases to the whole space. By
summability of the norms, this implies the overall convergence.
## Main results
* `q.comp p` is the formal composition of the formal multilinear series `q` and `p`.
* `has_fpower_series_at.comp` states that if two functions `g` and `f` admit power series expansions
`q` and `p`, then `g ∘ f` admits a power series expansion given by `q.comp p`.
* `analytic_at.comp` states that the composition of analytic functions is analytic.
* `formal_multilinear_series.comp_assoc` states that composition is associative on formal
multilinear series.
## Implementation details
The main technical difficulty is to write down things. In particular, we need to define precisely
`q.comp_along_composition p c` and to show that it is indeed a continuous multilinear
function. This requires a whole interface built on the class `composition`. Once this is set,
the main difficulty is to reorder the sums, writing the composition of the partial sums as a sum
over some subset of `Σ n, composition n`. We need to check that the reordering is a bijection,
running over difficulties due to the dependent nature of the types under consideration, that are
controlled thanks to the interface for `composition`.
The associativity of composition on formal multilinear series is a nontrivial result: it does not
follow from the associativity of composition of analytic functions, as there is no uniqueness for
the formal multilinear series representing a function (and also, it holds even when the radius of
convergence of the series is `0`). Instead, we give a direct proof, which amounts to reordering
double sums in a careful way. The change of variables is a canonical (combinatorial) bijection
`composition.sigma_equiv_sigma_pi` between `(Σ (a : composition n), composition a.length)` and
`(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, and is described
in more details below in the paragraph on associativity.
-/
noncomputable theory
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
{E : Type*} [normed_group E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [normed_space 𝕜 F]
{G : Type*} [normed_group G] [normed_space 𝕜 G]
{H : Type*} [normed_group H] [normed_space 𝕜 H]
open filter list
open_locale topological_space big_operators classical
/-! ### Composing formal multilinear series -/
namespace formal_multilinear_series
/-!
In this paragraph, we define the composition of formal multilinear series, by summing over all
possible compositions of `n`.
-/
/-- Given a formal multilinear series `p`, a composition `c` of `n` and the index `i` of a
block of `c`, we may define a function on `fin n → E` by picking the variables in the `i`-th block
of `n`, and applying the corresponding coefficient of `p` to these variables. This function is
called `p.apply_composition c v i` for `v : fin n → E` and `i : fin c.length`. -/
def apply_composition
(p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n) :
(fin n → E) → (fin (c.length) → F) :=
λ v i, p (c.blocks_fun i) (v ∘ (c.embedding i))
lemma apply_composition_ones (p : formal_multilinear_series 𝕜 E F) (n : ℕ) :
apply_composition p (composition.ones n) =
λ v i, p 1 (λ _, v (fin.cast_le (composition.length_le _) i)) :=
begin
funext v i,
apply p.congr (composition.ones_blocks_fun _ _),
intros j hjn hj1,
obtain rfl : j = 0, { linarith },
refine congr_arg v _,
rw [fin.ext_iff, fin.coe_cast_le, composition.ones_embedding, fin.coe_mk],
end
/-- Technical lemma stating how `p.apply_composition` commutes with updating variables. This
will be the key point to show that functions constructed from `apply_composition` retain
multilinearity. -/
lemma apply_composition_update
(p : formal_multilinear_series 𝕜 E F) {n : ℕ} (c : composition n)
(j : fin n) (v : fin n → E) (z : E) :
p.apply_composition c (function.update v j z) =
function.update (p.apply_composition c v) (c.index j)
(p (c.blocks_fun (c.index j))
(function.update (v ∘ (c.embedding (c.index j))) (c.inv_embedding j) z)) :=
begin
ext k,
by_cases h : k = c.index j,
{ rw h,
let r : fin (c.blocks_fun (c.index j)) → fin n := c.embedding (c.index j),
simp only [function.update_same],
change p (c.blocks_fun (c.index j)) ((function.update v j z) ∘ r) = _,
let j' := c.inv_embedding j,
suffices B : (function.update v j z) ∘ r = function.update (v ∘ r) j' z,
by rw B,
suffices C : (function.update v (r j') z) ∘ r = function.update (v ∘ r) j' z,
by { convert C, exact (c.embedding_comp_inv j).symm },
exact function.update_comp_eq_of_injective _ (c.embedding _).injective _ _ },
{ simp only [h, function.update_eq_self, function.update_noteq, ne.def, not_false_iff],
let r : fin (c.blocks_fun k) → fin n := c.embedding k,
change p (c.blocks_fun k) ((function.update v j z) ∘ r) = p (c.blocks_fun k) (v ∘ r),
suffices B : (function.update v j z) ∘ r = v ∘ r, by rw B,
apply function.update_comp_eq_of_not_mem_range,
rwa c.mem_range_embedding_iff' }
end
/-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may
form a multilinear map in `n` variables by applying the right coefficient of `p` to each block of
the composition, and then applying `q c.length` to the resulting vector. It is called
`q.comp_along_composition_multilinear p c`. This function admits a version as a continuous
multilinear map, called `q.comp_along_composition p c` below. -/
def comp_along_composition_multilinear {n : ℕ}
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(c : composition n) : multilinear_map 𝕜 (λ i : fin n, E) G :=
{ to_fun := λ v, q c.length (p.apply_composition c v),
map_add' := λ v i x y, by simp only [apply_composition_update,
continuous_multilinear_map.map_add],
map_smul' := λ v i c x, by simp only [apply_composition_update,
continuous_multilinear_map.map_smul] }
/-- The norm of `q.comp_along_composition_multilinear p c` is controlled by the product of
the norms of the relevant bits of `q` and `p`. -/
lemma comp_along_composition_multilinear_bound {n : ℕ}
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(c : composition n) (v : fin n → E) :
∥q.comp_along_composition_multilinear p c v∥ ≤
∥q c.length∥ * (∏ i, ∥p (c.blocks_fun i)∥) * (∏ i : fin n, ∥v i∥) :=
calc ∥q.comp_along_composition_multilinear p c v∥ = ∥q c.length (p.apply_composition c v)∥ : rfl
... ≤ ∥q c.length∥ * ∏ i, ∥p.apply_composition c v i∥ : continuous_multilinear_map.le_op_norm _ _
... ≤ ∥q c.length∥ * ∏ i, ∥p (c.blocks_fun i)∥ * ∏ j : fin (c.blocks_fun i), ∥(v ∘ (c.embedding i)) j∥ :
begin
apply mul_le_mul_of_nonneg_left _ (norm_nonneg _),
refine finset.prod_le_prod (λ i hi, norm_nonneg _) (λ i hi, _),
apply continuous_multilinear_map.le_op_norm,
end
... = ∥q c.length∥ * (∏ i, ∥p (c.blocks_fun i)∥) *
∏ i (j : fin (c.blocks_fun i)), ∥(v ∘ (c.embedding i)) j∥ :
by rw [finset.prod_mul_distrib, mul_assoc]
... = ∥q c.length∥ * (∏ i, ∥p (c.blocks_fun i)∥) * (∏ i : fin n, ∥v i∥) :
by { rw [← c.blocks_fin_equiv.prod_comp, ← finset.univ_sigma_univ, finset.prod_sigma],
congr }
/-- Given two formal multilinear series `q` and `p` and a composition `c` of `n`, one may
form a continuous multilinear map in `n` variables by applying the right coefficient of `p` to each
block of the composition, and then applying `q c.length` to the resulting vector. It is
called `q.comp_along_composition p c`. It is constructed from the analogous multilinear
function `q.comp_along_composition_multilinear p c`, together with a norm control to get
the continuity. -/
def comp_along_composition {n : ℕ}
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(c : composition n) : continuous_multilinear_map 𝕜 (λ i : fin n, E) G :=
(q.comp_along_composition_multilinear p c).mk_continuous _
(q.comp_along_composition_multilinear_bound p c)
@[simp] lemma comp_along_composition_apply {n : ℕ}
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(c : composition n) (v : fin n → E) :
(q.comp_along_composition p c) v = q c.length (p.apply_composition c v) := rfl
/-- The norm of `q.comp_along_composition p c` is controlled by the product of
the norms of the relevant bits of `q` and `p`. -/
lemma comp_along_composition_norm {n : ℕ}
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(c : composition n) :
∥q.comp_along_composition p c∥ ≤ ∥q c.length∥ * ∏ i, ∥p (c.blocks_fun i)∥ :=
multilinear_map.mk_continuous_norm_le _
(mul_nonneg (norm_nonneg _) (finset.prod_nonneg (λ i hi, norm_nonneg _))) _
lemma comp_along_composition_nnnorm {n : ℕ}
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(c : composition n) :
nnnorm (q.comp_along_composition p c) ≤ nnnorm (q c.length) * ∏ i, nnnorm (p (c.blocks_fun i)) :=
by simpa only [← nnreal.coe_le_coe, coe_nnnorm, nnreal.coe_mul, coe_nnnorm, nnreal.coe_prod, coe_nnnorm]
using q.comp_along_composition_norm p c
/-- Formal composition of two formal multilinear series. The `n`-th coefficient in the composition
is defined to be the sum of `q.comp_along_composition p c` over all compositions of
`n`. In other words, this term (as a multilinear function applied to `v_0, ..., v_{n-1}`) is
`∑'_{k} ∑'_{i₁ + ... + iₖ = n} pₖ (q_{i_1} (...), ..., q_{i_k} (...))`, where one puts all variables
`v_0, ..., v_{n-1}` in increasing order in the dots.-/
protected def comp (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) :
formal_multilinear_series 𝕜 E G :=
λ n, ∑ c : composition n, q.comp_along_composition p c
/-- The `0`-th coefficient of `q.comp p` is `q 0`. Since these maps are multilinear maps in zero
variables, but on different spaces, we can not state this directly, so we state it when applied to
arbitrary vectors (which have to be the zero vector). -/
lemma comp_coeff_zero (q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(v : fin 0 → E) (v' : fin 0 → F) :
(q.comp p) 0 v = q 0 v' :=
begin
let c : composition 0 := composition.ones 0,
dsimp [formal_multilinear_series.comp],
have : {c} = (finset.univ : finset (composition 0)),
{ apply finset.eq_of_subset_of_card_le; simp [finset.card_univ, composition_card 0] },
rw ← this,
simp only [finset.sum_singleton, continuous_multilinear_map.sum_apply],
change q c.length (p.apply_composition c v) = q 0 v',
congr' with i,
simp only [composition.ones_length] at i,
exact fin_zero_elim i
end
@[simp] lemma comp_coeff_zero'
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (v : fin 0 → E) :
(q.comp p) 0 v = q 0 (λ i, 0) :=
q.comp_coeff_zero p v _
/-- The `0`-th coefficient of `q.comp p` is `q 0`. When `p` goes from `E` to `E`, this can be
expressed as a direct equality -/
lemma comp_coeff_zero'' (q : formal_multilinear_series 𝕜 E F) (p : formal_multilinear_series 𝕜 E E) :
(q.comp p) 0 = q 0 :=
by { ext v, exact q.comp_coeff_zero p _ _ }
/-!
### The identity formal power series
We will now define the identity power series, and show that it is a neutral element for left and
right composition.
-/
section
variables (𝕜 E)
/-- The identity formal multilinear series, with all coefficients equal to `0` except for `n = 1`
where it is (the continuous multilinear version of) the identity. -/
def id : formal_multilinear_series 𝕜 E E
| 0 := 0
| 1 := (continuous_multilinear_curry_fin1 𝕜 E E).symm (continuous_linear_map.id 𝕜 E)
| _ := 0
/-- The first coefficient of `id 𝕜 E` is the identity. -/
@[simp] lemma id_apply_one (v : fin 1 → E) : (formal_multilinear_series.id 𝕜 E) 1 v = v 0 := rfl
/-- The `n`th coefficient of `id 𝕜 E` is the identity when `n = 1`. We state this in a dependent
way, as it will often appear in this form. -/
lemma id_apply_one' {n : ℕ} (h : n = 1) (v : fin n → E) :
(id 𝕜 E) n v = v ⟨0, h.symm ▸ zero_lt_one⟩ :=
begin
let w : fin 1 → E := λ i, v ⟨i.1, h.symm ▸ i.2⟩,
have : v ⟨0, h.symm ▸ zero_lt_one⟩ = w 0 := rfl,
rw [this, ← id_apply_one 𝕜 E w],
apply congr _ h,
intros,
obtain rfl : i = 0, { linarith },
exact this,
end
/-- For `n ≠ 1`, the `n`-th coefficient of `id 𝕜 E` is zero, by definition. -/
@[simp] lemma id_apply_ne_one {n : ℕ} (h : n ≠ 1) : (formal_multilinear_series.id 𝕜 E) n = 0 :=
by { cases n, { refl }, cases n, { contradiction }, refl }
end
@[simp] theorem comp_id (p : formal_multilinear_series 𝕜 E F) : p.comp (id 𝕜 E) = p :=
begin
ext1 n,
dsimp [formal_multilinear_series.comp],
rw finset.sum_eq_single (composition.ones n),
show comp_along_composition p (id 𝕜 E) (composition.ones n) = p n,
{ ext v,
rw comp_along_composition_apply,
apply p.congr (composition.ones_length n),
intros,
rw apply_composition_ones,
refine congr_arg v _,
rw [fin.ext_iff, fin.coe_cast_le, fin.coe_mk, fin.coe_mk], },
show ∀ (b : composition n),
b ∈ finset.univ → b ≠ composition.ones n → comp_along_composition p (id 𝕜 E) b = 0,
{ assume b _ hb,
obtain ⟨k, hk, lt_k⟩ : ∃ (k : ℕ) (H : k ∈ composition.blocks b), 1 < k :=
composition.ne_ones_iff.1 hb,
obtain ⟨i, i_lt, hi⟩ : ∃ (i : ℕ) (h : i < b.blocks.length), b.blocks.nth_le i h = k :=
nth_le_of_mem hk,
let j : fin b.length := ⟨i, b.blocks_length ▸ i_lt⟩,
have A : 1 < b.blocks_fun j := by convert lt_k,
ext v,
rw [comp_along_composition_apply, continuous_multilinear_map.zero_apply],
apply continuous_multilinear_map.map_coord_zero _ j,
dsimp [apply_composition],
rw id_apply_ne_one _ _ (ne_of_gt A),
refl },
{ simp }
end
theorem id_comp (p : formal_multilinear_series 𝕜 E F) (h : p 0 = 0) : (id 𝕜 F).comp p = p :=
begin
ext1 n,
by_cases hn : n = 0,
{ rw [hn, h],
ext v,
rw [comp_coeff_zero', id_apply_ne_one _ _ zero_ne_one],
refl },
{ dsimp [formal_multilinear_series.comp],
have n_pos : 0 < n := bot_lt_iff_ne_bot.mpr hn,
rw finset.sum_eq_single (composition.single n n_pos),
show comp_along_composition (id 𝕜 F) p (composition.single n n_pos) = p n,
{ ext v,
rw [comp_along_composition_apply, id_apply_one' _ _ (composition.single_length n_pos)],
dsimp [apply_composition],
refine p.congr rfl (λ i him hin, congr_arg v $ _),
ext, simp },
show ∀ (b : composition n),
b ∈ finset.univ → b ≠ composition.single n n_pos → comp_along_composition (id 𝕜 F) p b = 0,
{ assume b _ hb,
have A : b.length ≠ 1, by simpa [composition.eq_single_iff] using hb,
ext v,
rw [comp_along_composition_apply, id_apply_ne_one _ _ A],
refl },
{ simp } }
end
/-! ### Summability properties of the composition of formal power series-/
/-- If two formal multilinear series have positive radius of convergence, then the terms appearing
in the definition of their composition are also summable (when multiplied by a suitable positive
geometric term). -/
theorem comp_summable_nnreal
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F)
(hq : 0 < q.radius) (hp : 0 < p.radius) :
∃ (r : nnreal), 0 < r ∧ summable (λ i, nnnorm (q.comp_along_composition p i.2) * r ^ i.1 :
(Σ n, composition n) → nnreal) :=
begin
/- This follows from the fact that the growth rate of `∥qₙ∥` and `∥pₙ∥` is at most geometric,
giving a geometric bound on each `∥q.comp_along_composition p op∥`, together with the
fact that there are `2^(n-1)` compositions of `n`, giving at most a geometric loss. -/
rcases ennreal.lt_iff_exists_nnreal_btwn.1 hq with ⟨rq, rq_pos, hrq⟩,
rcases ennreal.lt_iff_exists_nnreal_btwn.1 hp with ⟨rp, rp_pos, hrp⟩,
obtain ⟨Cq, hCq⟩ : ∃ (Cq : nnreal), ∀ n, nnnorm (q n) * rq^n ≤ Cq := q.bound_of_lt_radius hrq,
obtain ⟨Cp, hCp⟩ : ∃ (Cp : nnreal), ∀ n, nnnorm (p n) * rp^n ≤ Cp := p.bound_of_lt_radius hrp,
let r0 : nnreal := (4 * max Cp 1)⁻¹,
set r := min rp 1 * min rq 1 * r0,
have r_pos : 0 < r,
{ apply mul_pos (mul_pos _ _),
{ rw [nnreal.inv_pos],
apply mul_pos,
{ norm_num },
{ exact lt_of_lt_of_le zero_lt_one (le_max_right _ _) } },
{ rw ennreal.coe_pos at rp_pos, simp [rp_pos, zero_lt_one] },
{ rw ennreal.coe_pos at rq_pos, simp [rq_pos, zero_lt_one] } },
let a : ennreal := ((4 : nnreal) ⁻¹ : nnreal),
have two_a : 2 * a < 1,
{ change ((2 : nnreal) : ennreal) * ((4 : nnreal) ⁻¹ : nnreal) < (1 : nnreal),
rw [← ennreal.coe_mul, ennreal.coe_lt_coe, ← nnreal.coe_lt_coe, nnreal.coe_mul],
change (2 : ℝ) * (4 : ℝ)⁻¹ < 1,
norm_num },
have I : ∀ (i : Σ (n : ℕ), composition n),
↑(nnnorm (q.comp_along_composition p i.2) * r ^ i.1) ≤ (Cq : ennreal) * a ^ i.1,
{ rintros ⟨n, c⟩,
rw [← ennreal.coe_pow, ← ennreal.coe_mul, ennreal.coe_le_coe],
calc nnnorm (q.comp_along_composition p c) * r ^ n
≤ (nnnorm (q c.length) * ∏ i, nnnorm (p (c.blocks_fun i))) * r ^ n :
mul_le_mul_of_nonneg_right (q.comp_along_composition_nnnorm p c) (bot_le)
... = (nnnorm (q c.length) * (min rq 1)^n) *
((∏ i, nnnorm (p (c.blocks_fun i))) * (min rp 1) ^ n) *
r0 ^ n : by { dsimp [r], ring_exp }
... ≤ (nnnorm (q c.length) * (min rq 1) ^ c.length) *
(∏ i, nnnorm (p (c.blocks_fun i)) * (min rp 1) ^ (c.blocks_fun i)) * r0 ^ n :
begin
apply_rules [mul_le_mul, bot_le, le_refl, pow_le_pow_of_le_one, min_le_right, c.length_le],
apply le_of_eq,
rw finset.prod_mul_distrib,
congr' 1,
conv_lhs { rw [← c.sum_blocks_fun, ← finset.prod_pow_eq_pow_sum] },
end
... ≤ Cq * (∏ i : fin c.length, Cp) * r0 ^ n :
begin
apply_rules [mul_le_mul, bot_le, le_trans _ (hCq c.length), le_refl, finset.prod_le_prod',
pow_le_pow_of_le_left, min_le_left],
assume i hi,
refine le_trans (mul_le_mul (le_refl _) _ bot_le bot_le) (hCp (c.blocks_fun i)),
exact pow_le_pow_of_le_left bot_le (min_le_left _ _) _
end
... ≤ Cq * (max Cp 1) ^ n * r0 ^ n :
begin
apply_rules [mul_le_mul, bot_le, le_refl],
simp only [finset.card_fin, finset.prod_const],
refine le_trans (pow_le_pow_of_le_left bot_le (le_max_left Cp 1) c.length) _,
apply pow_le_pow (le_max_right Cp 1) c.length_le,
end
... = Cq * 4⁻¹ ^ n :
begin
dsimp [r0],
have A : (4 : nnreal) ≠ 0, by norm_num,
have B : max Cp 1 ≠ 0 :=
ne_of_gt (lt_of_lt_of_le zero_lt_one (le_max_right Cp 1)),
field_simp [A, B],
ring_exp
end },
refine ⟨r, r_pos, _⟩,
rw [← ennreal.tsum_coe_ne_top_iff_summable],
apply ne_of_lt,
calc (∑' (i : Σ (n : ℕ), composition n), ↑(nnnorm (q.comp_along_composition p i.2) * r ^ i.1))
≤ (∑' (i : Σ (n : ℕ), composition n), (Cq : ennreal) * a ^ i.1) : ennreal.tsum_le_tsum I
... = (∑' (n : ℕ), (∑' (c : composition n), (Cq : ennreal) * a ^ n)) : ennreal.tsum_sigma' _
... = (∑' (n : ℕ), ↑(fintype.card (composition n)) * (Cq : ennreal) * a ^ n) :
begin
congr' 1 with n : 1,
rw [tsum_fintype, finset.sum_const, nsmul_eq_mul, finset.card_univ, mul_assoc]
end
... ≤ (∑' (n : ℕ), (2 : ennreal) ^ n * (Cq : ennreal) * a ^ n) :
begin
apply ennreal.tsum_le_tsum (λ n, _),
apply ennreal.mul_le_mul (ennreal.mul_le_mul _ (le_refl _)) (le_refl _),
rw composition_card,
simp only [nat.cast_bit0, nat.cast_one, nat.cast_pow],
apply ennreal.pow_le_pow _ (nat.sub_le n 1),
have : (1 : nnreal) ≤ (2 : nnreal), by norm_num,
rw ← ennreal.coe_le_coe at this,
exact this
end
... = (∑' (n : ℕ), (Cq : ennreal) * (2 * a) ^ n) : by { congr' 1 with n : 1, rw mul_pow, ring }
... = (Cq : ennreal) * (1 - 2 * a) ⁻¹ : by rw [ennreal.tsum_mul_left, ennreal.tsum_geometric]
... < ⊤ : by simp [lt_top_iff_ne_top, ennreal.mul_eq_top, two_a]
end
/-- Bounding below the radius of the composition of two formal multilinear series assuming
summability over all compositions. -/
theorem le_comp_radius_of_summable
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (r : nnreal)
(hr : summable (λ i, nnnorm (q.comp_along_composition p i.2) * r ^ i.1 :
(Σ n, composition n) → nnreal)) :
(r : ennreal) ≤ (q.comp p).radius :=
begin
apply le_radius_of_bound _ (tsum (λ (i : Σ (n : ℕ), composition n),
(nnnorm (comp_along_composition q p i.snd) * r ^ i.fst))),
assume n,
calc nnnorm (formal_multilinear_series.comp q p n) * r ^ n ≤
∑' (c : composition n), nnnorm (comp_along_composition q p c) * r ^ n :
begin
rw [tsum_fintype, ← finset.sum_mul],
exact mul_le_mul_of_nonneg_right (nnnorm_sum_le _ _) bot_le
end
... ≤ ∑' (i : Σ (n : ℕ), composition n),
nnnorm (comp_along_composition q p i.snd) * r ^ i.fst :
begin
let f : composition n → (Σ (n : ℕ), composition n) := λ c, ⟨n, c⟩,
have : function.injective f, by tidy,
convert nnreal.tsum_comp_le_tsum_of_inj hr this
end
end
/-!
### Composing analytic functions
Now, we will prove that the composition of the partial sums of `q` and `p` up to order `N` is
given by a sum over some large subset of `Σ n, composition n` of `q.comp_along_composition p`, to
deduce that the series for `q.comp p` indeed converges to `g ∘ f` when `q` is a power series for
`g` and `p` is a power series for `f`.
This proof is a big reindexing argument of a sum. Since it is a bit involved, we define first
the source of the change of variables (`comp_partial_source`), its target
(`comp_partial_target`) and the change of variables itself (`comp_change_of_variables`) before
giving the main statement in `comp_partial_sum`. -/
/-- Source set in the change of variables to compute the composition of partial sums of formal
power series.
See also `comp_partial_sum`. -/
def comp_partial_sum_source (N : ℕ) : finset (Σ n, (fin n) → ℕ) :=
finset.sigma (finset.range N) (λ (n : ℕ), fintype.pi_finset (λ (i : fin n), finset.Ico 1 N) : _)
@[simp] lemma mem_comp_partial_sum_source_iff (N : ℕ) (i : Σ n, (fin n) → ℕ) :
i ∈ comp_partial_sum_source N ↔ i.1 < N ∧ ∀ (a : fin i.1), 1 ≤ i.2 a ∧ i.2 a < N :=
by simp only [comp_partial_sum_source, finset.Ico.mem,
fintype.mem_pi_finset, finset.mem_sigma, finset.mem_range]
/-- Change of variables appearing to compute the composition of partial sums of formal
power series -/
def comp_change_of_variables (N : ℕ) (i : Σ n, (fin n) → ℕ) (hi : i ∈ comp_partial_sum_source N) :
(Σ n, composition n) :=
begin
rcases i with ⟨n, f⟩,
rw mem_comp_partial_sum_source_iff at hi,
refine ⟨∑ j, f j, of_fn (λ a, f a), λ i hi', _, by simp [sum_of_fn]⟩,
obtain ⟨j, rfl⟩ : ∃ (j : fin n), f j = i, by rwa [mem_of_fn, set.mem_range] at hi',
exact (hi.2 j).1
end
@[simp] lemma comp_change_of_variables_length
(N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source N) :
composition.length (comp_change_of_variables N i hi).2 = i.1 :=
begin
rcases i with ⟨k, blocks_fun⟩,
dsimp [comp_change_of_variables],
simp only [composition.length, map_of_fn, length_of_fn]
end
lemma comp_change_of_variables_blocks_fun
(N : ℕ) {i : Σ n, (fin n) → ℕ} (hi : i ∈ comp_partial_sum_source N) (j : fin i.1) :
(comp_change_of_variables N i hi).2.blocks_fun
⟨j, (comp_change_of_variables_length N hi).symm ▸ j.2⟩ = i.2 j :=
begin
rcases i with ⟨n, f⟩,
dsimp [composition.blocks_fun, composition.blocks, comp_change_of_variables],
simp only [map_of_fn, nth_le_of_fn', function.comp_app],
apply congr_arg,
rw [fin.ext_iff, fin.mk_coe]
end
/-- Target set in the change of variables to compute the composition of partial sums of formal
power series, here given a a set. -/
def comp_partial_sum_target_set (N : ℕ) : set (Σ n, composition n) :=
{i | (i.2.length < N) ∧ (∀ (j : fin i.2.length), i.2.blocks_fun j < N)}
lemma comp_partial_sum_target_subset_image_comp_partial_sum_source
(N : ℕ) (i : Σ n, composition n) (hi : i ∈ comp_partial_sum_target_set N) :
∃ j (hj : j ∈ comp_partial_sum_source N), i = comp_change_of_variables N j hj :=
begin
rcases i with ⟨n, c⟩,
refine ⟨⟨c.length, c.blocks_fun⟩, _, _⟩,
{ simp only [comp_partial_sum_target_set, set.mem_set_of_eq] at hi,
simp only [mem_comp_partial_sum_source_iff, hi.left, hi.right, true_and, and_true],
exact λ a, c.one_le_blocks' _ },
{ dsimp [comp_change_of_variables],
rw composition.sigma_eq_iff_blocks_eq,
simp only [composition.blocks_fun, composition.blocks, subtype.coe_eta, nth_le_map'],
conv_lhs { rw ← of_fn_nth_le c.blocks },
simp only [fin.val_eq_coe], refl, /- where does this fin.val come from? -/ }
end
/-- Target set in the change of variables to compute the composition of partial sums of formal
power series, here given a a finset.
See also `comp_partial_sum`. -/
def comp_partial_sum_target (N : ℕ) : finset (Σ n, composition n) :=
set.finite.to_finset $ (finset.finite_to_set _).dependent_image
(comp_partial_sum_target_subset_image_comp_partial_sum_source N)
@[simp] lemma mem_comp_partial_sum_target_iff {N : ℕ} {a : Σ n, composition n} :
a ∈ comp_partial_sum_target N ↔ a.2.length < N ∧ (∀ (j : fin a.2.length), a.2.blocks_fun j < N) :=
by simp [comp_partial_sum_target, comp_partial_sum_target_set]
/-- The auxiliary set corresponding to the composition of partial sums asymptotically contains
all possible compositions. -/
lemma comp_partial_sum_target_tendsto_at_top :
tendsto comp_partial_sum_target at_top at_top :=
begin
apply monotone.tendsto_at_top_finset,
{ assume m n hmn a ha,
have : ∀ i, i < m → i < n := λ i hi, lt_of_lt_of_le hi hmn,
tidy },
{ rintros ⟨n, c⟩,
simp only [mem_comp_partial_sum_target_iff],
obtain ⟨n, hn⟩ : bdd_above ↑(finset.univ.image (λ (i : fin c.length), c.blocks_fun i)) :=
finset.bdd_above _,
refine ⟨max n c.length + 1, lt_of_le_of_lt (le_max_right n c.length) (lt_add_one _),
λ j, lt_of_le_of_lt (le_trans _ (le_max_left _ _)) (lt_add_one _)⟩,
apply hn,
simp only [finset.mem_image_of_mem, finset.mem_coe, finset.mem_univ] }
end
/-- Composing the partial sums of two multilinear series coincides with the sum over all
compositions in `comp_partial_sum_target N`. This is precisely the motivation for the definition of
`comp_partial_sum_target N`. -/
lemma comp_partial_sum
(q : formal_multilinear_series 𝕜 F G) (p : formal_multilinear_series 𝕜 E F) (N : ℕ) (z : E) :
q.partial_sum N (∑ i in finset.Ico 1 N, p i (λ j, z)) =
∑ i in comp_partial_sum_target N, q.comp_along_composition_multilinear p i.2 (λ j, z) :=
begin
-- we expand the composition, using the multilinearity of `q` to expand along each coordinate.
suffices H : ∑ n in finset.range N, ∑ r in fintype.pi_finset (λ (i : fin n), finset.Ico 1 N),
q n (λ (i : fin n), p (r i) (λ j, z)) =
∑ i in comp_partial_sum_target N, q.comp_along_composition_multilinear p i.2 (λ j, z),
by simpa only [formal_multilinear_series.partial_sum,
continuous_multilinear_map.map_sum_finset] using H,
-- rewrite the first sum as a big sum over a sigma type
rw ← @finset.sum_sigma _ _ _ _
(finset.range N) (λ (n : ℕ), (fintype.pi_finset (λ (i : fin n), finset.Ico 1 N)) : _)
(λ i, q i.1 (λ (j : fin i.1), p (i.2 j) (λ (k : fin (i.2 j)), z))),
show ∑ i in comp_partial_sum_source N,
q i.1 (λ (j : fin i.1), p (i.2 j) (λ (k : fin (i.2 j)), z)) =
∑ i in comp_partial_sum_target N, q.comp_along_composition_multilinear p i.2 (λ j, z),
-- show that the two sums correspond to each other by reindexing the variables.
apply finset.sum_bij (comp_change_of_variables N),
-- To conclude, we should show that the correspondance we have set up is indeed a bijection
-- between the index sets of the two sums.
-- 1 - show that the image belongs to `comp_partial_sum_target N`
{ rintros ⟨k, blocks_fun⟩ H,
rw mem_comp_partial_sum_source_iff at H,
simp only [mem_comp_partial_sum_target_iff, composition.length, composition.blocks, H.left,
map_of_fn, length_of_fn, true_and, comp_change_of_variables],
assume j,
simp only [composition.blocks_fun, (H.right _).right, nth_le_of_fn'] },
-- 2 - show that the composition gives the `comp_along_composition` application
{ rintros ⟨k, blocks_fun⟩ H,
apply congr _ (comp_change_of_variables_length N H).symm,
intros,
rw ← comp_change_of_variables_blocks_fun N H,
refl },
-- 3 - show that the map is injective
{ rintros ⟨k, blocks_fun⟩ ⟨k', blocks_fun'⟩ H H' heq,
obtain rfl : k = k',
{ have := (comp_change_of_variables_length N H).symm,
rwa [heq, comp_change_of_variables_length] at this, },
congr,
funext i,
calc blocks_fun i = (comp_change_of_variables N _ H).2.blocks_fun _ :
(comp_change_of_variables_blocks_fun N H i).symm
... = (comp_change_of_variables N _ H').2.blocks_fun _ :
begin
apply composition.blocks_fun_congr; try { rw heq },
refl
end
... = blocks_fun' i : comp_change_of_variables_blocks_fun N H' i },
-- 4 - show that the map is surjective
{ assume i hi,
apply comp_partial_sum_target_subset_image_comp_partial_sum_source N i,
simpa [comp_partial_sum_target] using hi }
end
end formal_multilinear_series
open formal_multilinear_series
/-- If two functions `g` and `f` have power series `q` and `p` respectively at `f x` and `x`, then
`g ∘ f` admits the power series `q.comp p` at `x`. -/
theorem has_fpower_series_at.comp {g : F → G} {f : E → F}
{q : formal_multilinear_series 𝕜 F G} {p : formal_multilinear_series 𝕜 E F} {x : E}
(hg : has_fpower_series_at g q (f x)) (hf : has_fpower_series_at f p x) :
has_fpower_series_at (g ∘ f) (q.comp p) x :=
begin
/- Consider `rf` and `rg` such that `f` and `g` have power series expansion on the disks
of radius `rf` and `rg`. -/
rcases hg with ⟨rg, Hg⟩,
rcases hf with ⟨rf, Hf⟩,
/- The terms defining `q.comp p` are geometrically summable in a disk of some radius `r`. -/
rcases q.comp_summable_nnreal p Hg.radius_pos Hf.radius_pos with ⟨r, r_pos, hr⟩,
/- We will consider `y` which is smaller than `r` and `rf`, and also small enough that
`f (x + y)` is close enough to `f x` to be in the disk where `g` is well behaved. Let
`min (r, rf, δ)` be this new radius.-/
have : continuous_at f x := Hf.analytic_at.continuous_at,
obtain ⟨δ, δpos, hδ⟩ : ∃ (δ : ennreal) (H : 0 < δ),
∀ {z : E}, z ∈ emetric.ball x δ → f z ∈ emetric.ball (f x) rg,
{ have : emetric.ball (f x) rg ∈ 𝓝 (f x) := emetric.ball_mem_nhds _ Hg.r_pos,
rcases emetric.mem_nhds_iff.1 (Hf.analytic_at.continuous_at this) with ⟨δ, δpos, Hδ⟩,
exact ⟨δ, δpos, λ z hz, Hδ hz⟩ },
let rf' := min rf δ,
have min_pos : 0 < min rf' r,
by simp only [r_pos, Hf.r_pos, δpos, lt_min_iff, ennreal.coe_pos, and_self],
/- We will show that `g ∘ f` admits the power series `q.comp p` in the disk of
radius `min (r, rf', δ)`. -/
refine ⟨min rf' r, _⟩,
refine ⟨le_trans (min_le_right rf' r)
(formal_multilinear_series.le_comp_radius_of_summable q p r hr), min_pos, λ y hy, _⟩,
/- Let `y` satisfy `∥y∥ < min (r, rf', δ)`. We want to show that `g (f (x + y))` is the sum of
`q.comp p` applied to `y`. -/
-- First, check that `y` is small enough so that estimates for `f` and `g` apply.
have y_mem : y ∈ emetric.ball (0 : E) rf :=
(emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_left _ _))) hy,
have fy_mem : f (x + y) ∈ emetric.ball (f x) rg,
{ apply hδ,
have : y ∈ emetric.ball (0 : E) δ :=
(emetric.ball_subset_ball (le_trans (min_le_left _ _) (min_le_right _ _))) hy,
simpa [edist_eq_coe_nnnorm_sub, edist_eq_coe_nnnorm] },
/- Now the proof starts. To show that the sum of `q.comp p` at `y` is `g (f (x + y))`, we will
write `q.comp p` applied to `y` as a big sum over all compositions. Since the sum is
summable, to get its convergence it suffices to get the convergence along some increasing sequence
of sets. We will use the sequence of sets `comp_partial_sum_target n`, along which the sum is
exactly the composition of the partial sums of `q` and `p`, by design. To show that it converges
to `g (f (x + y))`, pointwise convergence would not be enough, but we have uniform convergence
to save the day. -/
-- First step: the partial sum of `p` converges to `f (x + y)`.
have A : tendsto (λ n, ∑ a in finset.Ico 1 n, p a (λ b, y)) at_top (𝓝 (f (x + y) - f x)),
{ have L : ∀ᶠ n in at_top, ∑ a in finset.range n, p a (λ b, y) - f x =
∑ a in finset.Ico 1 n, p a (λ b, y),
{ rw eventually_at_top,
refine ⟨1, λ n hn, _⟩,
symmetry,
rw [eq_sub_iff_add_eq', finset.range_eq_Ico, ← Hf.coeff_zero (λi, y),
finset.sum_eq_sum_Ico_succ_bot hn] },
have : tendsto (λ n, ∑ a in finset.range n, p a (λ b, y) - f x) at_top (𝓝 (f (x + y) - f x)) :=
(Hf.has_sum y_mem).tendsto_sum_nat.sub tendsto_const_nhds,
exact tendsto.congr' L this },
-- Second step: the composition of the partial sums of `q` and `p` converges to `g (f (x + y))`.
have B : tendsto (λ n, q.partial_sum n (∑ a in finset.Ico 1 n, p a (λ b, y)))
at_top (𝓝 (g (f (x + y)))),
{ -- we use the fact that the partial sums of `q` converge locally uniformly to `g`, and that
-- composition passes to the limit under locally uniform convergence.
have B₁ : continuous_at (λ (z : F), g (f x + z)) (f (x + y) - f x),
{ refine continuous_at.comp _ (continuous_const.add continuous_id).continuous_at,
simp only [add_sub_cancel'_right, id.def],
exact Hg.continuous_on.continuous_at (mem_nhds_sets (emetric.is_open_ball) fy_mem) },
have B₂ : f (x + y) - f x ∈ emetric.ball (0 : F) rg,
by simpa [edist_eq_coe_nnnorm, edist_eq_coe_nnnorm_sub] using fy_mem,
rw [← nhds_within_eq_of_open B₂ emetric.is_open_ball] at A,
convert Hg.tendsto_locally_uniformly_on.tendsto_comp B₁.continuous_within_at B₂ A,
simp only [add_sub_cancel'_right] },
-- Third step: the sum over all compositions in `comp_partial_sum_target n` converges to
-- `g (f (x + y))`. As this sum is exactly the composition of the partial sum, this is a direct
-- consequence of the second step
have C : tendsto (λ n,
∑ i in comp_partial_sum_target n, q.comp_along_composition_multilinear p i.2 (λ j, y))
at_top (𝓝 (g (f (x + y)))),
by simpa [comp_partial_sum] using B,
-- Fourth step: the sum over all compositions is `g (f (x + y))`. This follows from the
-- convergence along a subsequence proved in the third step, and the fact that the sum is Cauchy
-- thanks to the summability properties.
have D : has_sum (λ i : (Σ n, composition n),
q.comp_along_composition_multilinear p i.2 (λ j, y)) (g (f (x + y))),
{ have cau : cauchy_seq (λ (s : finset (Σ n, composition n)),
∑ i in s, q.comp_along_composition_multilinear p i.2 (λ j, y)),
{ apply cauchy_seq_finset_of_norm_bounded _ (nnreal.summable_coe.2 hr) _,
simp only [coe_nnnorm, nnreal.coe_mul, nnreal.coe_pow],
rintros ⟨n, c⟩,
calc ∥(comp_along_composition q p c) (λ (j : fin n), y)∥
≤ ∥comp_along_composition q p c∥ * ∏ j : fin n, ∥y∥ :
by apply continuous_multilinear_map.le_op_norm
... ≤ ∥comp_along_composition q p c∥ * (r : ℝ) ^ n :
begin
apply mul_le_mul_of_nonneg_left _ (norm_nonneg _),
rw [finset.prod_const, finset.card_fin],
apply pow_le_pow_of_le_left (norm_nonneg _),
rw [emetric.mem_ball, edist_eq_coe_nnnorm] at hy,
have := (le_trans (le_of_lt hy) (min_le_right _ _)),
rwa [ennreal.coe_le_coe, ← nnreal.coe_le_coe, coe_nnnorm] at this
end },
exact tendsto_nhds_of_cauchy_seq_of_subseq cau
comp_partial_sum_target_tendsto_at_top C },
-- Fifth step: the sum over `n` of `q.comp p n` can be expressed as a particular resummation of
-- the sum over all compositions, by grouping together the compositions of the same
-- integer `n`. The convergence of the whole sum therefore implies the converence of the sum
-- of `q.comp p n`
have E : has_sum (λ n, (q.comp p) n (λ j, y)) (g (f (x + y))),
{ apply D.sigma,
assume n,
dsimp [formal_multilinear_series.comp],
convert has_sum_fintype _,
simp only [continuous_multilinear_map.sum_apply],
refl },
exact E
end
/-- If two functions `g` and `f` are analytic respectively at `f x` and `x`, then `g ∘ f` is
analytic at `x`. -/
theorem analytic_at.comp {g : F → G} {f : E → F} {x : E}
(hg : analytic_at 𝕜 g (f x)) (hf : analytic_at 𝕜 f x) : analytic_at 𝕜 (g ∘ f) x :=
let ⟨q, hq⟩ := hg, ⟨p, hp⟩ := hf in (hq.comp hp).analytic_at
/-!
### Associativity of the composition of formal multilinear series
In this paragraph, we us prove the associativity of the composition of formal power series.
By definition,
```
(r.comp q).comp p n v
= ∑_{i₁ + ... + iₖ = n} (r.comp q)ₖ (p_{i₁} (v₀, ..., v_{i₁ -1}), p_{i₂} (...), ..., p_{iₖ}(...))
= ∑_{a : composition n} (r.comp q) a.length (apply_composition p a v)
```
decomposing `r.comp q` in the same way, we get
```
(r.comp q).comp p n v
= ∑_{a : composition n} ∑_{b : composition a.length}
r b.length (apply_composition q b (apply_composition p a v))
```
On the other hand,
```
r.comp (q.comp p) n v = ∑_{c : composition n} r c.length (apply_composition (q.comp p) c v)
```
Here, `apply_composition (q.comp p) c v` is a vector of length `c.length`, whose `i`-th term is
given by `(q.comp p) (c.blocks_fun i) (v_l, v_{l+1}, ..., v_{m-1})` where `{l, ..., m-1}` is the
`i`-th block in the composition `c`, of length `c.blocks_fun i` by definition. To compute this term,
we expand it as `∑_{dᵢ : composition (c.blocks_fun i)} q dᵢ.length (apply_composition p dᵢ v')`,
where `v' = (v_l, v_{l+1}, ..., v_{m-1})`. Therefore, we get
```
r.comp (q.comp p) n v =
∑_{c : composition n} ∑_{d₀ : composition (c.blocks_fun 0),
..., d_{c.length - 1} : composition (c.blocks_fun (c.length - 1))}
r c.length (λ i, q dᵢ.length (apply_composition p dᵢ v'ᵢ))
```
To show that these terms coincide, we need to explain how to reindex the sums to put them in
bijection (and then the terms we are summing will correspond to each other). Suppose we have a
composition `a` of `n`, and a composition `b` of `a.length`. Then `b` indicates how to group
together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of blocks
can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by saying that
each `dᵢ` is one single block. Conversely, if one starts from `c` and the `dᵢ`s, one can concatenate
the `dᵢ`s to obtain a composition `a` of `n`, and register the lengths of the `dᵢ`s in a composition
`b` of `a.length`.
An example might be enlightening. Suppose `a = [2, 2, 3, 4, 2]`. It is a composition of
length 5 of 13. The content of the blocks may be represented as `0011222333344`.
Now take `b = [2, 3]` as a composition of `a.length = 5`. It says that the first 2 blocks of `a`
should be merged, and the last 3 blocks of `a` should be merged, giving a new composition of `13`
made of two blocks of length `4` and `9`, i.e., `c = [4, 9]`. But one can also remember that
the new first block was initially made of two blocks of size `2`, so `d₀ = [2, 2]`, and the new
second block was initially made of three blocks of size `3`, `4` and `2`, so `d₁ = [3, 4, 2]`.
This equivalence is called `composition.sigma_equiv_sigma_pi n` below.
We start with preliminary results on compositions, of a very specialized nature, then define the
equivalence `composition.sigma_equiv_sigma_pi n`, and we deduce finally the associativity of
composition of formal multilinear series in `formal_multilinear_series.comp_assoc`.
-/
namespace composition
variable {n : ℕ}
/-- Rewriting equality in the dependent type `Σ (a : composition n), composition a.length)` in
non-dependent terms with lists, requiring that the blocks coincide. -/
lemma sigma_composition_eq_iff (i j : Σ (a : composition n), composition a.length) :
i = j ↔ i.1.blocks = j.1.blocks ∧ i.2.blocks = j.2.blocks :=
begin
refine ⟨by rintro rfl; exact ⟨rfl, rfl⟩, _⟩,
rcases i with ⟨a, b⟩,
rcases j with ⟨a', b'⟩,
rintros ⟨h, h'⟩,
have H : a = a', by { ext1, exact h },
induction H, congr, ext1, exact h'
end
/-- Rewriting equality in the dependent type
`Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)` in
non-dependent terms with lists, requiring that the lists of blocks coincide. -/
lemma sigma_pi_composition_eq_iff
(u v : Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) :
u = v ↔ of_fn (λ i, (u.2 i).blocks) = of_fn (λ i, (v.2 i).blocks) :=
begin
refine ⟨λ H, by rw H, λ H, _⟩,
rcases u with ⟨a, b⟩,
rcases v with ⟨a', b'⟩,
dsimp at H,
have h : a = a',
{ ext1,
have : map list.sum (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) =
map list.sum (of_fn (λ (i : fin (composition.length a')), (b' i).blocks)), by rw H,
simp only [map_of_fn] at this,
change of_fn (λ (i : fin (composition.length a)), (b i).blocks.sum) =
of_fn (λ (i : fin (composition.length a')), (b' i).blocks.sum) at this,
simpa [composition.blocks_sum, composition.of_fn_blocks_fun] using this },
induction h,
simp only [true_and, eq_self_iff_true, heq_iff_eq],
ext i : 2,
have : nth_le (of_fn (λ (i : fin (composition.length a)), (b i).blocks)) i (by simp [i.is_lt]) =
nth_le (of_fn (λ (i : fin (composition.length a)), (b' i).blocks)) i (by simp [i.is_lt]) :=
nth_le_of_eq H _,
rwa [nth_le_of_fn, nth_le_of_fn] at this
end
/-- When `a` is a composition of `n` and `b` is a composition of `a.length`, `a.gather b` is the
composition of `n` obtained by gathering all the blocks of `a` corresponding to a block of `b`.
For instance, if `a = [6, 5, 3, 5, 2]` and `b = [2, 3]`, one should gather together
the first two blocks of `a` and its last three blocks, giving `a.gather b = [11, 10]`. -/
def gather (a : composition n) (b : composition a.length) : composition n :=
{ blocks := (a.blocks.split_wrt_composition b).map sum,
blocks_pos :=
begin
rw forall_mem_map_iff,
intros j hj,
suffices H : ∀ i ∈ j, 1 ≤ i, from
calc 0 < j.length : length_pos_of_mem_split_wrt_composition hj
... ≤ j.sum : length_le_sum_of_one_le _ H,
intros i hi,
apply a.one_le_blocks,
rw ← a.blocks.join_split_wrt_composition b,
exact mem_join_of_mem hj hi,
end,
blocks_sum := by { rw [← sum_join, join_split_wrt_composition, a.blocks_sum] } }
lemma length_gather (a : composition n) (b : composition a.length) :
length (a.gather b) = b.length :=
show (map list.sum (a.blocks.split_wrt_composition b)).length = b.blocks.length,
by rw [length_map, length_split_wrt_composition]
/-- An auxiliary function used in the definition of `sigma_equiv_sigma_pi` below, associating to
two compositions `a` of `n` and `b` of `a.length`, and an index `i` bounded by the length of
`a.gather b`, the subcomposition of `a` made of those blocks belonging to the `i`-th block of
`a.gather b`. -/
def sigma_composition_aux (a : composition n) (b : composition a.length)
(i : fin (a.gather b).length) :
composition ((a.gather b).blocks_fun i) :=
{ blocks := nth_le (a.blocks.split_wrt_composition b) i
(by { rw [length_split_wrt_composition, ← length_gather], exact i.2 }),
blocks_pos := assume i hi, a.blocks_pos
(by { rw ← a.blocks.join_split_wrt_composition b, exact mem_join_of_mem (nth_le_mem _ _ _) hi }),
blocks_sum := by simp only [composition.blocks_fun, nth_le_map', composition.gather, fin.val_eq_coe] }
/- Where did the fin.val come from in the proof on the preceding line? -/
lemma length_sigma_composition_aux (a : composition n) (b : composition a.length) (i : fin b.length) :
composition.length (composition.sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ i.2⟩) =
composition.blocks_fun b i :=
show list.length (nth_le (split_wrt_composition a.blocks b) i _) = blocks_fun b i,
by { rw [nth_le_map_rev list.length, nth_le_of_eq (map_length_split_wrt_composition _ _)], refl }
lemma blocks_fun_sigma_composition_aux (a : composition n) (b : composition a.length)
(i : fin b.length) (j : fin (blocks_fun b i)) :
blocks_fun (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ i.2⟩)
⟨j, (length_sigma_composition_aux a b i).symm ▸ j.2⟩ = blocks_fun a (embedding b i j) :=
show nth_le (nth_le _ _ _) _ _ = nth_le a.blocks _ _,
by { rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take'], refl }
/-- Auxiliary lemma to prove that the composition of formal multilinear series is associative.
Consider a composition `a` of `n` and a composition `b` of `a.length`. Grouping together some
blocks of `a` according to `b` as in `a.gather b`, one can compute the total size of the blocks
of `a` up to an index `size_up_to b i + j` (where the `j` corresponds to a set of blocks of `a`
that do not fill a whole block of `a.gather b`). The first part corresponds to a sum of blocks
in `a.gather b`, and the second one to a sum of blocks in the next block of
`sigma_composition_aux a b`. This is the content of this lemma. -/
lemma size_up_to_size_up_to_add (a : composition n) (b : composition a.length)
{i j : ℕ} (hi : i < b.length) (hj : j < blocks_fun b ⟨i, hi⟩) :
size_up_to a (size_up_to b i + j) = size_up_to (a.gather b) i +
(size_up_to (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩) j) :=
begin
induction j with j IHj,
{ show sum (take ((b.blocks.take i).sum) a.blocks) =
sum (take i (map sum (split_wrt_composition a.blocks b))),
induction i with i IH,
{ refl },
{ have A : i < b.length := nat.lt_of_succ_lt hi,
have B : i < list.length (map list.sum (split_wrt_composition a.blocks b)), by simp [A],
have C : 0 < blocks_fun b ⟨i, A⟩ := composition.blocks_pos' _ _ _,
rw [sum_take_succ _ _ B, ← IH A C],
have : take (sum (take i b.blocks)) a.blocks =
take (sum (take i b.blocks)) (take (sum (take (i+1) b.blocks)) a.blocks),
{ rw [take_take, min_eq_left],
apply monotone_sum_take _ (nat.le_succ _) },
rw [this, nth_le_map', nth_le_split_wrt_composition,
← take_append_drop (sum (take i b.blocks)) ((take (sum (take (nat.succ i) b.blocks)) a.blocks)),
sum_append],
congr,
rw [take_append_drop] } },
{ have A : j < blocks_fun b ⟨i, hi⟩ := lt_trans (lt_add_one j) hj,
have B : j < length (sigma_composition_aux a b ⟨i, (length_gather a b).symm ▸ hi⟩),
by { convert A, rw [← length_sigma_composition_aux], refl },
have C : size_up_to b i + j < size_up_to b (i + 1),
{ simp only [size_up_to_succ b hi, add_lt_add_iff_left],
exact A },
have D : size_up_to b i + j < length a := lt_of_lt_of_le C (b.size_up_to_le _),
have : size_up_to b i + nat.succ j = (size_up_to b i + j).succ := rfl,
rw [this, size_up_to_succ _ D, IHj A, size_up_to_succ _ B],
simp only [sigma_composition_aux, add_assoc, add_left_inj, fin.coe_mk],
rw [nth_le_of_eq (nth_le_split_wrt_composition _ _ _), nth_le_drop', nth_le_take _ _ C] }
end
/--
Natural equivalence between `(Σ (a : composition n), composition a.length)` and
`(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i))`, that shows up as a
change of variables in the proof that composition of formal multilinear series is associative.
Consider a composition `a` of `n` and a composition `b` of `a.length`. Then `b` indicates how to
group together some blocks of `a`, giving altogether `b.length` blocks of blocks. These blocks of
blocks can be called `d₀, ..., d_{a.length - 1}`, and one obtains a composition `c` of `n` by
saying that each `dᵢ` is one single block. The map `⟨a, b⟩ → ⟨c, (d₀, ..., d_{a.length - 1})⟩` is
the direct map in the equiv.
Conversely, if one starts from `c` and the `dᵢ`s, one can join the `dᵢ`s to obtain a composition
`a` of `n`, and register the lengths of the `dᵢ`s in a composition `b` of `a.length`. This is the
inverse map of the equiv.
-/
def sigma_equiv_sigma_pi (n : ℕ) :
(Σ (a : composition n), composition a.length) ≃
(Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) :=
{ to_fun := λ i, ⟨i.1.gather i.2, i.1.sigma_composition_aux i.2⟩,
inv_fun := λ i, ⟨
{ blocks := (of_fn (λ j, (i.2 j).blocks)).join,
blocks_pos :=
begin
simp only [and_imp, mem_join, exists_imp_distrib, forall_mem_of_fn_iff],
exact λ i j hj, composition.blocks_pos _ hj
end,
blocks_sum := by simp [sum_of_fn, composition.blocks_sum, composition.sum_blocks_fun] },
{ blocks := of_fn (λ j, (i.2 j).length),
blocks_pos := forall_mem_of_fn_iff.2
(λ j, composition.length_pos_of_pos _ (composition.blocks_pos' _ _ _)),
blocks_sum := by { dsimp only [composition.length], simp [sum_of_fn] } }⟩,
left_inv :=
begin
-- the fact that we have a left inverse is essentially `join_split_wrt_composition`,
-- but we need to massage it to take care of the dependent setting.
rintros ⟨a, b⟩,
rw sigma_composition_eq_iff,
dsimp,
split,
{ have A := length_map list.sum (split_wrt_composition a.blocks b),
conv_rhs { rw [← join_split_wrt_composition a.blocks b,
← of_fn_nth_le (split_wrt_composition a.blocks b)] },
congr,
{ exact A },
{ exact (fin.heq_fun_iff A).2 (λ i, rfl) } },
{ have B : composition.length (composition.gather a b) = list.length b.blocks :=
composition.length_gather _ _,
conv_rhs { rw [← of_fn_nth_le b.blocks] },
congr' 1,
{ exact B },
{ apply (fin.heq_fun_iff B).2 (λ i, _),
rw [sigma_composition_aux, composition.length, nth_le_map_rev list.length,
nth_le_of_eq (map_length_split_wrt_composition _ _)], refl } }
end,
right_inv :=
begin
-- the fact that we have a right inverse is essentially `split_wrt_composition_join`,
-- but we need to massage it to take care of the dependent setting.
rintros ⟨c, d⟩,
have : map list.sum (of_fn (λ (i : fin (composition.length c)), (d i).blocks)) = c.blocks,
by simp [map_of_fn, (∘), composition.blocks_sum, composition.of_fn_blocks_fun],
rw sigma_pi_composition_eq_iff,
dsimp,
congr,
{ ext1,
dsimp [composition.gather],
rwa split_wrt_composition_join,
simp only [map_of_fn] },
{ rw fin.heq_fun_iff,
{ assume i,
dsimp [composition.sigma_composition_aux],
rw [nth_le_of_eq (split_wrt_composition_join _ _ _)],
{ simp only [nth_le_of_fn'] },
{ simp only [map_of_fn] } },
{ congr,
ext1,
dsimp [composition.gather],
rwa split_wrt_composition_join,
simp only [map_of_fn] } }
end }
end composition
namespace formal_multilinear_series
open composition
theorem comp_assoc (r : formal_multilinear_series 𝕜 G H) (q : formal_multilinear_series 𝕜 F G)
(p : formal_multilinear_series 𝕜 E F) :
(r.comp q).comp p = r.comp (q.comp p) :=
begin
ext n v,
/- First, rewrite the two compositions appearing in the theorem as two sums over complicated
sigma types, as in the description of the proof above. -/
let f : (Σ (a : composition n), composition a.length) → H :=
λ ⟨a, b⟩, r b.length (apply_composition q b (apply_composition p a v)),
let g : (Σ (c : composition n), Π (i : fin c.length), composition (c.blocks_fun i)) → H :=
λ ⟨c, d⟩, r c.length
(λ (i : fin c.length), q (d i).length (apply_composition p (d i) (v ∘ c.embedding i))),
suffices A : ∑ c, f c = ∑ c, g c,
{ dsimp [formal_multilinear_series.comp],
simp only [continuous_multilinear_map.sum_apply, comp_along_composition_apply],
rw ← @finset.sum_sigma _ _ _ _ (finset.univ : finset (composition n)) _ f,
dsimp [apply_composition],
simp only [continuous_multilinear_map.sum_apply, comp_along_composition_apply,
continuous_multilinear_map.map_sum],
rw ← @finset.sum_sigma _ _ _ _ (finset.univ : finset (composition n)) _ g,
exact A },
/- Now, we use `composition.sigma_equiv_sigma_pi n` to change
variables in the second sum, and check that we get exactly the same sums. -/
rw ← (sigma_equiv_sigma_pi n).sum_comp,
/- To check that we have the same terms, we should check that we apply the same component of
`r`, and the same component of `q`, and the same component of `p`, to the same coordinate of
`v`. This is true by definition, but at each step one needs to convince Lean that the types
one considers are the same, using a suitable congruence lemma to avoid dependent type issues.
This dance has to be done three times, one for `r`, one for `q` and one for `p`.-/
apply finset.sum_congr rfl,
rintros ⟨a, b⟩ _,
dsimp [f, g, sigma_equiv_sigma_pi],
-- check that the `r` components are the same. Based on `composition.length_gather`
apply r.congr (composition.length_gather a b).symm,
intros i hi1 hi2,
-- check that the `q` components are the same. Based on `length_sigma_composition_aux`
apply q.congr (length_sigma_composition_aux a b _).symm,
intros j hj1 hj2,
-- check that the `p` components are the same. Based on `blocks_fun_sigma_composition_aux`
apply p.congr (blocks_fun_sigma_composition_aux a b _ _).symm,
intros k hk1 hk2,
-- finally, check that the coordinates of `v` one is using are the same. Based on
-- `size_up_to_size_up_to_add`.
refine congr_arg v (fin.eq_of_veq _),
dsimp [composition.embedding],
rw [size_up_to_size_up_to_add _ _ hi1 hj1, add_assoc],
end
end formal_multilinear_series
|
049e5a9b3760b5a9b9d5f1eb1d46e34d977a3757 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/data/quot.lean | b94d055de6738f3bac844956352179995be3b31f | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 10,245 | 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
Quotients -- extends the core library
-/
variables {α : Sort*} {β : Sort*}
namespace setoid
lemma ext {α : Sort*} :
∀{s t : setoid α}, (∀a b, @setoid.r α s a b ↔ @setoid.r α t a b) → s = t
| ⟨r, _⟩ ⟨p, _⟩ eq :=
have r = p, from funext $ assume a, funext $ assume b, propext $ eq a b,
by subst this
end setoid
namespace quot
variables {ra : α → α → Prop} {rb : β → β → Prop} {φ : quot ra → quot rb → Sort*}
local notation `⟦`:max a `⟧` := quot.mk _ a
protected def hrec_on₂ (qa : quot ra) (qb : quot rb) (f : ∀ a b, φ ⟦a⟧ ⟦b⟧)
(ca : ∀ {b a₁ a₂}, ra a₁ a₂ → f a₁ b == f a₂ b)
(cb : ∀ {a b₁ b₂}, rb b₁ b₂ → f a b₁ == f a b₂) : φ qa qb :=
quot.hrec_on qa (λ a, quot.hrec_on qb (f a) (λ b₁ b₂ pb, cb pb)) $ λ a₁ a₂ pa,
quot.induction_on qb $ λ b,
calc @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₁) (@cb _)
== f a₁ b : by simp
... == f a₂ b : ca pa
... == @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₂) (@cb _) : by simp
protected def map {α} (r r' : α → α → Prop) (h : ∀a b, r a b → r' a b) (a : quot r) : quot r' :=
quot.hrec_on a (quot.mk r') $ assume a b hab, by rw [quot.sound (h a b hab)]
end quot
namespace quotient
variables [sa : setoid α] [sb : setoid β]
variables {φ : quotient sa → quotient sb → Sort*}
protected def hrec_on₂ (qa : quotient sa) (qb : quotient sb) (f : ∀ a b, φ ⟦a⟧ ⟦b⟧)
(c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb :=
quot.hrec_on₂ qa qb f
(λ _ _ _ p, c _ _ _ _ p (setoid.refl _))
(λ _ _ _ p, c _ _ _ _ (setoid.refl _) p)
end quotient
@[simp] theorem quotient.eq [r : setoid α] {x y : α} : ⟦x⟧ = ⟦y⟧ ↔ x ≈ y :=
⟨quotient.exact, quotient.sound⟩
theorem forall_quotient_iff {α : Type*} [r : setoid α] {p : quotient r → Prop} :
(∀a:quotient r, p a) ↔ (∀a:α, p ⟦a⟧) :=
⟨assume h x, h _, assume h a, a.induction_on h⟩
@[simp] lemma quotient.lift_beta [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α):
quotient.lift f h (quotient.mk x) = f x := rfl
@[simp] lemma quotient.lift_on_beta [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α):
quotient.lift_on (quotient.mk x) f h = f x := rfl
/-- Choose an element of the equivalence class using the axiom of choice.
Sound but noncomputable. -/
noncomputable def quot.out {r : α → α → Prop} (q : quot r) : α :=
classical.some (quot.exists_rep q)
/-- Unwrap the VM representation of a quotient to obtain an element of the equivalence class.
Computable but unsound. -/
meta def quot.unquot {r : α → α → Prop} : quot r → α := unchecked_cast
@[simp] theorem quot.out_eq {r : α → α → Prop} (q : quot r) : quot.mk r q.out = q :=
classical.some_spec (quot.exists_rep q)
/-- Choose an element of the equivalence class using the axiom of choice.
Sound but noncomputable. -/
noncomputable def quotient.out [s : setoid α] : quotient s → α := quot.out
@[simp] theorem quotient.out_eq [s : setoid α] (q : quotient s) : ⟦q.out⟧ = q := q.out_eq
theorem quotient.mk_out [s : setoid α] (a : α) : ⟦a⟧.out ≈ a :=
quotient.exact (quotient.out_eq _)
instance pi_setoid {ι : Sort*} {α : ι → Sort*} [∀ i, setoid (α i)] : setoid (Π i, α i) :=
{ r := λ a b, ∀ i, a i ≈ b i,
iseqv := ⟨
λ a i, setoid.refl _,
λ a b h i, setoid.symm (h _),
λ a b c h₁ h₂ i, setoid.trans (h₁ _) (h₂ _)⟩ }
noncomputable def quotient.choice {ι : Type*} {α : ι → Type*} [S : ∀ i, setoid (α i)]
(f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) :=
⟦λ i, (f i).out⟧
theorem quotient.choice_eq {ι : Type*} {α : ι → Type*} [∀ i, setoid (α i)]
(f : ∀ i, α i) : quotient.choice (λ i, ⟦f i⟧) = ⟦f⟧ :=
quotient.sound $ λ i, quotient.mk_out _
lemma nonempty_quotient_iff (s : setoid α): nonempty (quotient s) ↔ nonempty α :=
⟨assume ⟨a⟩, quotient.induction_on a nonempty.intro, assume ⟨a⟩, ⟨⟦a⟧⟩⟩
/-- `trunc α` is the quotient of `α` by the always-true relation. This
is related to the propositional truncation in HoTT, and is similar
in effect to `nonempty α`, but unlike `nonempty α`, `trunc α` is data,
so the VM representation is the same as `α`, and so this can be used to
maintain computability. -/
def {u} trunc (α : Sort u) : Sort u := @quot α (λ _ _, true)
theorem true_equivalence : @equivalence α (λ _ _, true) :=
⟨λ _, trivial, λ _ _ _, trivial, λ _ _ _ _ _, trivial⟩
namespace trunc
/-- Constructor for `trunc α` -/
def mk (a : α) : trunc α := quot.mk _ a
/-- Any constant function lifts to a function out of the truncation -/
def lift (f : α → β) (c : ∀ a b : α, f a = f b) : trunc α → β :=
quot.lift f (λ a b _, c a b)
theorem ind {β : trunc α → Prop} : (∀ a : α, β (mk a)) → ∀ q : trunc α, β q := quot.ind
protected theorem lift_beta (f : α → β) (c) (a : α) : lift f c (mk a) = f a := rfl
@[reducible, elab_as_eliminator]
protected def lift_on (q : trunc α) (f : α → β)
(c : ∀ a b : α, f a = f b) : β := lift f c q
@[elab_as_eliminator]
protected theorem induction_on {β : trunc α → Prop} (q : trunc α)
(h : ∀ a, β (mk a)) : β q := ind h q
theorem exists_rep (q : trunc α) : ∃ a : α, mk a = q := quot.exists_rep q
attribute [elab_as_eliminator]
protected theorem induction_on₂
{C : trunc α → trunc β → Prop} (q₁ : trunc α) (q₂ : trunc β) (h : ∀ a b, C (mk a) (mk b)) : C q₁ q₂ :=
trunc.induction_on q₁ $ λ a₁, trunc.induction_on q₂ (h a₁)
protected theorem eq (a b : trunc α) : a = b :=
trunc.induction_on₂ a b (λ x y, quot.sound trivial)
instance : subsingleton (trunc α) := ⟨trunc.eq⟩
def bind (q : trunc α) (f : α → trunc β) : trunc β :=
trunc.lift_on q f (λ a b, trunc.eq _ _)
def map (f : α → β) (q : trunc α) : trunc β := bind q (trunc.mk ∘ f)
instance : monad trunc :=
{ pure := @trunc.mk,
bind := @trunc.bind }
instance : is_lawful_monad trunc :=
{ id_map := λ α q, trunc.eq _ _,
pure_bind := λ α β q f, rfl,
bind_assoc := λ α β γ x f g, trunc.eq _ _ }
variable {C : trunc α → Sort*}
@[reducible, elab_as_eliminator]
protected def rec
(f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b)
(q : trunc α) : C q :=
quot.rec f (λ a b _, h a b) q
@[reducible, elab_as_eliminator]
protected def rec_on (q : trunc α) (f : Π a, C (mk a))
(h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) : C q :=
trunc.rec f h q
@[reducible, elab_as_eliminator]
protected def rec_on_subsingleton
[∀ a, subsingleton (C (mk a))] (q : trunc α) (f : Π a, C (mk a)) : C q :=
trunc.rec f (λ a b, subsingleton.elim _ (f b)) q
/-- Noncomputably extract a representative of `trunc α` (using the axiom of choice). -/
noncomputable def out : trunc α → α := quot.out
@[simp] theorem out_eq (q : trunc α) : mk q.out = q := trunc.eq _ _
end trunc
theorem nonempty_of_trunc (q : trunc α) : nonempty α :=
let ⟨a, _⟩ := q.exists_rep in ⟨a⟩
namespace quotient
variables {γ : Sort*} {φ : Sort*}
{s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ}
/- Versions of quotient definitions and lemmas ending in `'` use unification instead
of typeclass inference for inferring the `setoid` argument. This is useful when there are
several different quotient relations on a type, for example quotient groups, rings and modules -/
protected def mk' (a : α) : quotient s₁ := quot.mk s₁.1 a
@[elab_as_eliminator, reducible]
protected def lift_on' (q : quotient s₁) (f : α → φ)
(h : ∀ a b, @setoid.r α s₁ a b → f a = f b) : φ := quotient.lift_on q f h
@[elab_as_eliminator, reducible]
protected def lift_on₂' (q₁ : quotient s₁) (q₂ : quotient s₂) (f : α → β → γ)
(h : ∀ a₁ a₂ b₁ b₂, @setoid.r α s₁ a₁ b₁ → @setoid.r β s₂ a₂ b₂ → f a₁ a₂ = f b₁ b₂) : γ :=
quotient.lift_on₂ q₁ q₂ f h
@[elab_as_eliminator]
protected lemma ind' {p : quotient s₁ → Prop}
(h : ∀ a, p (quotient.mk' a)) (q : quotient s₁) : p q :=
quotient.ind h q
@[elab_as_eliminator]
protected lemma ind₂' {p : quotient s₁ → quotient s₂ → Prop}
(h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂))
(q₁ : quotient s₁) (q₂ : quotient s₂) : p q₁ q₂ :=
quotient.ind₂ h q₁ q₂
@[elab_as_eliminator]
protected lemma induction_on' {p : quotient s₁ → Prop} (q : quotient s₁)
(h : ∀ a, p (quotient.mk' a)) : p q := quotient.induction_on q h
@[elab_as_eliminator]
protected lemma induction_on₂' {p : quotient s₁ → quotient s₂ → Prop} (q₁ : quotient s₁)
(q₂ : quotient s₂) (h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂)) : p q₁ q₂ :=
quotient.induction_on₂ q₁ q₂ h
@[elab_as_eliminator]
protected lemma induction_on₃' {p : quotient s₁ → quotient s₂ → quotient s₃ → Prop}
(q₁ : quotient s₁) (q₂ : quotient s₂) (q₃ : quotient s₃)
(h : ∀ a₁ a₂ a₃, p (quotient.mk' a₁) (quotient.mk' a₂) (quotient.mk' a₃)) : p q₁ q₂ q₃ :=
quotient.induction_on₃ q₁ q₂ q₃ h
lemma exact' {a b : α} :
(quotient.mk' a : quotient s₁) = quotient.mk' b → @setoid.r _ s₁ a b :=
quotient.exact
lemma sound' {a b : α} : @setoid.r _ s₁ a b → @quotient.mk' α s₁ a = quotient.mk' b :=
quotient.sound
@[simp] protected lemma eq' {a b : α} : @quotient.mk' α s₁ a = quotient.mk' b ↔ @setoid.r _ s₁ a b :=
quotient.eq
noncomputable def out' (a : quotient s₁) : α := quotient.out a
@[simp] theorem out_eq' (q : quotient s₁) : quotient.mk' q.out' = q := q.out_eq
theorem mk_out' (a : α) : @setoid.r α s₁ (quotient.mk' a : quotient s₁).out' a :=
quotient.exact (quotient.out_eq _)
end quotient
|
c13f0b0214168547767e08cef39ec55d83e8dae5 | b7b549d2cf38ac9d4e49372b7ad4d37f70449409 | /src/LeanLLVM/Memory.lean | 0bf6bf0ba0cfef15acf6c112b751ad55d15331e3 | [
"Apache-2.0"
] | permissive | GaloisInc/lean-llvm | 7cc196172fe02ff3554edba6cc82f333c30fdc2b | 36e2ec604ae22d8ec1b1b66eca0f8887880db6c6 | refs/heads/master | 1,637,359,020,356 | 1,629,332,114,000 | 1,629,402,464,000 | 146,700,234 | 29 | 1 | Apache-2.0 | 1,631,225,695,000 | 1,535,607,191,000 | Lean | UTF-8 | Lean | false | false | 5,268 | lean | import Init.Data.Array
import Init.Data.Int
import Std.Data.RBMap
import Galois.Data.Bitvec
import LeanLLVM.AST
import LeanLLVM.PP
import LeanLLVM.TypeContext
import LeanLLVM.SimMonad
import LeanLLVM.Value
open Std (RBMap)
namespace LLVM
open Sim
namespace Mem
partial def decomposeIntLE : Nat → Nat → List (bitvec 8)
| w, v =>
if w <= 8 then
[ bitvec.of_nat 8 v ]
else
(bitvec.of_nat 8 v) :: decomposeIntLE (w - 8) (v / ((2:Nat) ^ (8:Nat)))
partial def decomposeIntBE : Nat → Nat → List (bitvec 8) → List (bitvec 8)
| w, v, bs =>
if w <= 8 then
(bitvec.of_nat 8 v :: bs)
else
decomposeIntBE (w - 8) (v / (2 ^ (8:Nat))) (bitvec.of_nat 8 v :: bs)
def decomposeInt : Endian → Nat → Nat → List (bitvec 8)
| Endian.big, w, v => decomposeIntBE w v []
| Endian.little, w, v => decomposeIntLE w v
def storeBytes : bitvec 64 → List (bitvec 8) → Sim.memMap → Sim.memMap
| _, [], m => m
| p, b::bs, m => storeBytes (p.add (bitvec.of_nat 64 1)) bs (m.insert p b)
def loadBytes : bitvec 64 → Nat → Sim.memMap → Option (List (bitvec 8))
| _p, 0, _mem => some []
| p, Nat.succ n, mem => OptionM.run do
let b ← mem.find? p
let bs ← loadBytes (p.add (bitvec.of_nat 64 1)) n mem
pure (b::bs)
def composeIntBE (w:Nat) : List (bitvec 8) → bitvec w → bitvec w
| [], x => x
| b::bs, x => composeIntBE w bs (bitvec.of_nat w ((x.to_nat * 2^(8:Nat)) + b.to_nat))
def composeIntLE (w:Nat) : List (bitvec 8) → bitvec w
| [] => bitvec.of_nat w 0
| b::bs => bitvec.of_nat w ((composeIntLE w bs).to_nat * 2^(8:Nat) + b.to_nat)
def composeInt (w:Nat) : Endian → List (bitvec 8) → bitvec w
| Endian.big, bs => composeIntBE w bs (bitvec.of_nat w 0)
| Endian.little, bs => composeIntLE w bs
def store_int (w:Nat) (e:Endian) (p:bitvec 64) (v:bitvec w) : Sim Unit := do
let st ← getState
let m' := storeBytes p (decomposeInt e w v.to_nat) st.mem;
setState {st with mem := m' }
def load_int (w:Nat) (e:Endian) (p:bitvec 64) : Sim (bitvec w) := do
let st ← getState
match loadBytes p ((w+7)/8) st.mem with
| none => throw (IO.userError "Failed to load integer value")
| some bs => pure (composeInt w e bs)
def load (dl:DataLayout) : mem_type → bitvec 64 → Sim Sim.Value
| mem_type.ptr _, p => Sim.Value.bv <$> load_int 64 dl.intLayout p
| mem_type.int w, p => Sim.Value.bv <$> load_int w dl.intLayout p
| _, _ => throw (IO.userError "load: NYI!")
partial def store (dl:DataLayout) : mem_type → bitvec 64 → Sim.Value → Sim Unit
| mem_type.ptr _, p, @Value.bv 64 v => store_int 64 dl.intLayout p v
| mem_type.int w, p, @Value.bv w' v =>
if w = w' then
store_int w' dl.intLayout p v
else
throw (IO.userError ("Integer width mismatch in store: " ++ toString w ++ " " ++ toString w'))
| mem_type.struct si, p, Sim.Value.struct fs => do
let mut i := 0
for f in si.fields do
match fs.get? i with
| some fv =>
store dl f.value (p.add (bitvec.of_nat 64 f.offset)) fv.value
i := i+1
| none => throw (IO.userError "Struct type mismatch in store!")
| mem_type.vector n _, p, Sim.Value.vec mt vs =>
let (sz,a) := mem_type.szAndAlign dl mt;
let sz' := bitvec.of_nat 64 (padToAlignment sz a);
if vs.size = n then do
let mut p' := p;
for v in vs do
store dl mt p' v
p' := p'.add sz'
else
throw (IO.userError
("Expected vector value with " ++ toString n ++ " elements, but got " ++ toString vs.size))
| mem_type.array n _, p, Sim.Value.array mt vs => do
let (sz,a) := mem_type.szAndAlign dl mt;
let sz' := bitvec.of_nat 64 (padToAlignment sz a);
if vs.size = n then do
let mut p' := p;
for v in vs do
store dl mt p' v
p' := p'.add sz'
else
throw (IO.userError
("Expected array value with " ++ toString n ++ " elements, but got " ++ toString vs.size))
| _, _, _ => throw (IO.userError "Type/value mismatch in store!")
end Mem
def allocGlobalVariable (gv:Global) : Sim Unit := do
let st ← Sim.getState
let mt ← Sim.eval_mem_type gv.type
let ptr ← match st.symmap.find? gv.sym with
| some ptr => pure ptr
| none => do
let (sz, align) := mem_type.szAndAlign st.dl mt
let (ptr, st') := allocOnHeap sz align st
Sim.setState (linkSymbol st' (gv.sym, ptr))
pure ptr
match gv.value with
| none => pure ()
| some val => do
let v ← Sim.eval mt val
Mem.store st.dl mt ptr v
def allocGlobalSymbols (mod:Module) : Sim Unit := do
let st0 <- getState
let declNames := mod.declares.toList.map (λd => d.name)
let defiNames := mod.defines.toList.map (λd => d.name)
setState (List.foldr allocFunctionSymbol st0 (declNames ++ defiNames))
for gv in mod.globals do
allocGlobalVariable gv
def runInitializers (mod:Module) (dl:DataLayout) (ls:List (Symbol × bitvec 64)): IO State :=
runSim
(allocGlobalSymbols mod)
{ kerr := throw
, kret := λ _ _ => throw (IO.userError "No return point")
, kcall := λ _ _ _ _ => throw (IO.userError "no calls")
, kjump := λ _ _ _ => throw (IO.userError "no jumps")
, ktrace := λ _ a => a
}
(λ _u _frm st => pure st)
arbitrary
(initializeState mod dl ls)
end LLVM
|
6be61661790ee802e3facc9a565bddb84d2ab35a | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /library/logic/nonempty.lean | c620c76da7e92ab65b297be44ed895442e60b1e0 | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 534 | lean | -- Copyright (c) 2014 Microsoft Corporation. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Leonardo de Moura, Jeremy Avigad
import .inhabited
open inhabited
inductive nonempty [class] (A : Type) : Prop :=
intro : A → nonempty A
namespace nonempty
protected definition elim {A : Type} {B : Prop} (H1 : nonempty A) (H2 : A → B) : B :=
rec H2 H1
theorem inhabited_imp_nonempty [instance] {A : Type} (H : inhabited A) : nonempty A :=
intro (default A)
end nonempty
|
80aef7469d1a2be54ab02bd091f47ea8330a6dd5 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/instances/ennreal.lean | fa6138f3f3588ba87f405504811620c036fb9075 | [] | 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 | 27,658 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes Hölzl
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.instances.nnreal
import Mathlib.PostPort
universes u_1 u_2
namespace Mathlib
/-!
# Extended non-negative reals
-/
namespace ennreal
/-- Topology on `ennreal`.
Note: this is different from the `emetric_space` topology. The `emetric_space` topology has
`is_open {⊤}`, while this topology doesn't have singleton elements. -/
protected instance topological_space : topological_space ennreal :=
preorder.topology ennreal
protected instance order_topology : order_topology ennreal :=
order_topology.mk rfl
protected instance t2_space : t2_space ennreal :=
regular_space.t2_space ennreal
protected instance topological_space.second_countable_topology : topological_space.second_countable_topology ennreal := sorry
theorem embedding_coe : embedding coe := sorry
theorem is_open_ne_top : is_open (set_of fun (a : ennreal) => a ≠ ⊤) :=
is_open_ne
theorem is_open_Ico_zero {b : ennreal} : is_open (set.Ico 0 b) :=
eq.mpr (id (Eq._oldrec (Eq.refl (is_open (set.Ico 0 b))) ennreal.Ico_eq_Iio)) is_open_Iio
theorem coe_range_mem_nhds {r : nnreal} : set.range coe ∈ nhds ↑r := sorry
theorem tendsto_coe {α : Type u_1} {f : filter α} {m : α → nnreal} {a : nnreal} : filter.tendsto (fun (a : α) => ↑(m a)) f (nhds ↑a) ↔ filter.tendsto m f (nhds a) :=
iff.symm (embedding.tendsto_nhds_iff embedding_coe)
theorem continuous_coe : continuous coe :=
embedding.continuous embedding_coe
theorem continuous_coe_iff {α : Type u_1} [topological_space α] {f : α → nnreal} : (continuous fun (a : α) => ↑(f a)) ↔ continuous f :=
iff.symm (embedding.continuous_iff embedding_coe)
theorem nhds_coe {r : nnreal} : nhds ↑r = filter.map coe (nhds r) := sorry
theorem nhds_coe_coe {r : nnreal} {p : nnreal} : nhds (↑r, ↑p) = filter.map (fun (p : nnreal × nnreal) => (↑(prod.fst p), ↑(prod.snd p))) (nhds (r, p)) := sorry
theorem continuous_of_real : continuous ennreal.of_real :=
continuous.comp (iff.mpr continuous_coe_iff continuous_id) nnreal.continuous_of_real
theorem tendsto_of_real {α : Type u_1} {f : filter α} {m : α → ℝ} {a : ℝ} (h : filter.tendsto m f (nhds a)) : filter.tendsto (fun (a : α) => ennreal.of_real (m a)) f (nhds (ennreal.of_real a)) :=
filter.tendsto.comp (continuous.tendsto continuous_of_real a) h
theorem tendsto_to_nnreal {a : ennreal} : a ≠ ⊤ → filter.tendsto ennreal.to_nnreal (nhds a) (nhds (ennreal.to_nnreal a)) := sorry
theorem continuous_on_to_nnreal : continuous_on ennreal.to_nnreal (set_of fun (a : ennreal) => a ≠ ⊤) := sorry
theorem tendsto_to_real {a : ennreal} : a ≠ ⊤ → filter.tendsto ennreal.to_real (nhds a) (nhds (ennreal.to_real a)) :=
fun (ha : a ≠ ⊤) => filter.tendsto.comp (iff.mpr nnreal.tendsto_coe filter.tendsto_id) (tendsto_to_nnreal ha)
/-- The set of finite `ennreal` numbers is homeomorphic to `ℝ≥0`. -/
def ne_top_homeomorph_nnreal : ↥(set_of fun (a : ennreal) => a ≠ ⊤) ≃ₜ nnreal :=
homeomorph.mk (equiv.mk (equiv.to_fun ne_top_equiv_nnreal) (equiv.inv_fun ne_top_equiv_nnreal) sorry sorry)
/-- The set of finite `ennreal` numbers is homeomorphic to `ℝ≥0`. -/
def lt_top_homeomorph_nnreal : ↥(set_of fun (a : ennreal) => a < ⊤) ≃ₜ nnreal :=
homeomorph.trans (homeomorph.set_congr sorry) ne_top_homeomorph_nnreal
theorem nhds_top : nhds ⊤ = infi fun (a : ennreal) => infi fun (H : a ≠ ⊤) => filter.principal (set.Ioi a) := sorry
theorem nhds_top' : nhds ⊤ = infi fun (r : nnreal) => filter.principal (set.Ioi ↑r) :=
Eq.trans nhds_top (infi_ne_top fun (a : ennreal) => filter.principal (set.Ioi a))
theorem tendsto_nhds_top_iff_nnreal {α : Type u_1} {m : α → ennreal} {f : filter α} : filter.tendsto m f (nhds ⊤) ↔ ∀ (x : nnreal), filter.eventually (fun (a : α) => ↑x < m a) f := sorry
theorem tendsto_nhds_top_iff_nat {α : Type u_1} {m : α → ennreal} {f : filter α} : filter.tendsto m f (nhds ⊤) ↔ ∀ (n : ℕ), filter.eventually (fun (a : α) => ↑n < m a) f := sorry
theorem tendsto_nhds_top {α : Type u_1} {m : α → ennreal} {f : filter α} (h : ∀ (n : ℕ), filter.eventually (fun (a : α) => ↑n < m a) f) : filter.tendsto m f (nhds ⊤) :=
iff.mpr tendsto_nhds_top_iff_nat h
theorem tendsto_nat_nhds_top : filter.tendsto (fun (n : ℕ) => ↑n) filter.at_top (nhds ⊤) := sorry
@[simp] theorem tendsto_coe_nhds_top {α : Type u_1} {f : α → nnreal} {l : filter α} : filter.tendsto (fun (x : α) => ↑(f x)) l (nhds ⊤) ↔ filter.tendsto f l filter.at_top := sorry
theorem nhds_zero : nhds 0 = infi fun (a : ennreal) => infi fun (H : a ≠ 0) => filter.principal (set.Iio a) := sorry
instance nhds_within_Ioi_coe_ne_bot {r : nnreal} : filter.ne_bot (nhds_within (↑r) (set.Ioi ↑r)) :=
nhds_within_Ioi_self_ne_bot' coe_lt_top
instance nhds_within_Ioi_zero_ne_bot : filter.ne_bot (nhds_within 0 (set.Ioi 0)) :=
nhds_within_Ioi_coe_ne_bot
-- using Icc because
-- • don't have 'Ioo (x - ε) (x + ε) ∈ 𝓝 x' unless x > 0
-- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not
theorem Icc_mem_nhds {x : ennreal} {ε : ennreal} : x ≠ ⊤ → 0 < ε → set.Icc (x - ε) (x + ε) ∈ nhds x := sorry
theorem nhds_of_ne_top {x : ennreal} : x ≠ ⊤ → nhds x = infi fun (ε : ennreal) => infi fun (H : ε > 0) => filter.principal (set.Icc (x - ε) (x + ε)) := sorry
/-- Characterization of neighborhoods for `ennreal` numbers. See also `tendsto_order`
for a version with strict inequalities. -/
protected theorem tendsto_nhds {α : Type u_1} {f : filter α} {u : α → ennreal} {a : ennreal} (ha : a ≠ ⊤) : filter.tendsto u f (nhds a) ↔
∀ (ε : ennreal), ε > 0 → filter.eventually (fun (x : α) => u x ∈ set.Icc (a - ε) (a + ε)) f := sorry
protected theorem tendsto_at_top {β : Type u_2} [Nonempty β] [semilattice_sup β] {f : β → ennreal} {a : ennreal} (ha : a ≠ ⊤) : filter.tendsto f filter.at_top (nhds a) ↔
∀ (ε : ennreal), ε > 0 → ∃ (N : β), ∀ (n : β), n ≥ N → f n ∈ set.Icc (a - ε) (a + ε) := sorry
protected instance has_continuous_add : has_continuous_add ennreal := sorry
protected theorem tendsto_mul {a : ennreal} {b : ennreal} (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) : filter.tendsto (fun (p : ennreal × ennreal) => prod.fst p * prod.snd p) (nhds (a, b)) (nhds (a * b)) := sorry
protected theorem tendsto.mul {α : Type u_1} {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a : ennreal} {b : ennreal} (hma : filter.tendsto ma f (nhds a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : filter.tendsto mb f (nhds b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : filter.tendsto (fun (a : α) => ma a * mb a) f (nhds (a * b)) := sorry
protected theorem tendsto.const_mul {α : Type u_1} {f : filter α} {m : α → ennreal} {a : ennreal} {b : ennreal} (hm : filter.tendsto m f (nhds b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : filter.tendsto (fun (b : α) => a * m b) f (nhds (a * b)) := sorry
protected theorem tendsto.mul_const {α : Type u_1} {f : filter α} {m : α → ennreal} {a : ennreal} {b : ennreal} (hm : filter.tendsto m f (nhds a)) (ha : a ≠ 0 ∨ b ≠ ⊤) : filter.tendsto (fun (x : α) => m x * b) f (nhds (a * b)) := sorry
protected theorem continuous_at_const_mul {a : ennreal} {b : ennreal} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at (Mul.mul a) b :=
tendsto.const_mul filter.tendsto_id (or.symm h)
protected theorem continuous_at_mul_const {a : ennreal} {b : ennreal} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at (fun (x : ennreal) => x * a) b :=
tendsto.mul_const filter.tendsto_id (or.symm h)
protected theorem continuous_const_mul {a : ennreal} (ha : a ≠ ⊤) : continuous (Mul.mul a) :=
iff.mpr continuous_iff_continuous_at fun (x : ennreal) => ennreal.continuous_at_const_mul (Or.inl ha)
protected theorem continuous_mul_const {a : ennreal} (ha : a ≠ ⊤) : continuous fun (x : ennreal) => x * a :=
iff.mpr continuous_iff_continuous_at fun (x : ennreal) => ennreal.continuous_at_mul_const (Or.inl ha)
theorem le_of_forall_lt_one_mul_le {x : ennreal} {y : ennreal} (h : ∀ (a : ennreal), a < 1 → a * x ≤ y) : x ≤ y := sorry
theorem infi_mul_left {ι : Sort u_1} [Nonempty ι] {f : ι → ennreal} {a : ennreal} (h : a = ⊤ → (infi fun (i : ι) => f i) = 0 → ∃ (i : ι), f i = 0) : (infi fun (i : ι) => a * f i) = a * infi fun (i : ι) => f i := sorry
theorem infi_mul_right {ι : Sort u_1} [Nonempty ι] {f : ι → ennreal} {a : ennreal} (h : a = ⊤ → (infi fun (i : ι) => f i) = 0 → ∃ (i : ι), f i = 0) : (infi fun (i : ι) => f i * a) = (infi fun (i : ι) => f i) * a := sorry
protected theorem continuous_inv : continuous has_inv.inv := sorry
@[simp] protected theorem tendsto_inv_iff {α : Type u_1} {f : filter α} {m : α → ennreal} {a : ennreal} : filter.tendsto (fun (x : α) => m x⁻¹) f (nhds (a⁻¹)) ↔ filter.tendsto m f (nhds a) := sorry
protected theorem tendsto.div {α : Type u_1} {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a : ennreal} {b : ennreal} (hma : filter.tendsto ma f (nhds a)) (ha : a ≠ 0 ∨ b ≠ 0) (hmb : filter.tendsto mb f (nhds b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : filter.tendsto (fun (a : α) => ma a / mb a) f (nhds (a / b)) := sorry
protected theorem tendsto.const_div {α : Type u_1} {f : filter α} {m : α → ennreal} {a : ennreal} {b : ennreal} (hm : filter.tendsto m f (nhds b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : filter.tendsto (fun (b : α) => a / m b) f (nhds (a / b)) := sorry
protected theorem tendsto.div_const {α : Type u_1} {f : filter α} {m : α → ennreal} {a : ennreal} {b : ennreal} (hm : filter.tendsto m f (nhds a)) (ha : a ≠ 0 ∨ b ≠ 0) : filter.tendsto (fun (x : α) => m x / b) f (nhds (a / b)) := sorry
protected theorem tendsto_inv_nat_nhds_zero : filter.tendsto (fun (n : ℕ) => ↑n⁻¹) filter.at_top (nhds 0) :=
inv_top ▸ iff.mpr ennreal.tendsto_inv_iff tendsto_nat_nhds_top
theorem bsupr_add {a : ennreal} {ι : Type u_1} {s : set ι} (hs : set.nonempty s) {f : ι → ennreal} : (supr fun (i : ι) => supr fun (H : i ∈ s) => f i) + a = supr fun (i : ι) => supr fun (H : i ∈ s) => f i + a := sorry
theorem Sup_add {a : ennreal} {s : set ennreal} (hs : set.nonempty s) : Sup s + a = supr fun (b : ennreal) => supr fun (H : b ∈ s) => b + a := sorry
theorem supr_add {a : ennreal} {ι : Sort u_1} {s : ι → ennreal} [h : Nonempty ι] : supr s + a = supr fun (b : ι) => s b + a := sorry
theorem add_supr {a : ennreal} {ι : Sort u_1} {s : ι → ennreal} [h : Nonempty ι] : a + supr s = supr fun (b : ι) => a + s b := sorry
theorem supr_add_supr {ι : Sort u_1} {f : ι → ennreal} {g : ι → ennreal} (h : ∀ (i j : ι), ∃ (k : ι), f i + g j ≤ f k + g k) : supr f + supr g = supr fun (a : ι) => f a + g a := sorry
theorem supr_add_supr_of_monotone {ι : Type u_1} [semilattice_sup ι] {f : ι → ennreal} {g : ι → ennreal} (hf : monotone f) (hg : monotone g) : supr f + supr g = supr fun (a : ι) => f a + g a :=
supr_add_supr fun (i j : ι) => Exists.intro (i ⊔ j) (add_le_add (hf le_sup_left) (hg le_sup_right))
theorem finset_sum_supr_nat {α : Type u_1} {ι : Type u_2} [semilattice_sup ι] {s : finset α} {f : α → ι → ennreal} (hf : ∀ (a : α), monotone (f a)) : (finset.sum s fun (a : α) => supr (f a)) = supr fun (n : ι) => finset.sum s fun (a : α) => f a n := sorry
theorem mul_Sup {s : set ennreal} {a : ennreal} : a * Sup s = supr fun (i : ennreal) => supr fun (H : i ∈ s) => a * i := sorry
theorem mul_supr {ι : Sort u_1} {f : ι → ennreal} {a : ennreal} : a * supr f = supr fun (i : ι) => a * f i := sorry
theorem supr_mul {ι : Sort u_1} {f : ι → ennreal} {a : ennreal} : supr f * a = supr fun (i : ι) => f i * a := sorry
protected theorem tendsto_coe_sub {r : nnreal} {b : ennreal} : filter.tendsto (fun (b : ennreal) => ↑r - b) (nhds b) (nhds (↑r - b)) := sorry
theorem sub_supr {a : ennreal} {ι : Sort u_1} [hι : Nonempty ι] {b : ι → ennreal} (hr : a < ⊤) : (a - supr fun (i : ι) => b i) = infi fun (i : ι) => a - b i := sorry
theorem supr_eq_zero {ι : Sort u_1} {f : ι → ennreal} : (supr fun (i : ι) => f i) = 0 ↔ ∀ (i : ι), f i = 0 := sorry
protected theorem has_sum_coe {α : Type u_1} {f : α → nnreal} {r : nnreal} : has_sum (fun (a : α) => ↑(f a)) ↑r ↔ has_sum f r := sorry
protected theorem tsum_coe_eq {α : Type u_1} {r : nnreal} {f : α → nnreal} (h : has_sum f r) : (tsum fun (a : α) => ↑(f a)) = ↑r :=
has_sum.tsum_eq (iff.mpr ennreal.has_sum_coe h)
protected theorem coe_tsum {α : Type u_1} {f : α → nnreal} : summable f → ↑(tsum f) = tsum fun (a : α) => ↑(f a) := sorry
protected theorem has_sum {α : Type u_1} {f : α → ennreal} : has_sum f (supr fun (s : finset α) => finset.sum s fun (a : α) => f a) :=
tendsto_at_top_supr fun (s t : finset α) => finset.sum_le_sum_of_subset
@[simp] protected theorem summable {α : Type u_1} {f : α → ennreal} : summable f :=
Exists.intro (supr fun (s : finset α) => finset.sum s fun (a : α) => f a) ennreal.has_sum
theorem tsum_coe_ne_top_iff_summable {β : Type u_2} {f : β → nnreal} : (tsum fun (b : β) => ↑(f b)) ≠ ⊤ ↔ summable f := sorry
protected theorem tsum_eq_supr_sum {α : Type u_1} {f : α → ennreal} : (tsum fun (a : α) => f a) = supr fun (s : finset α) => finset.sum s fun (a : α) => f a :=
has_sum.tsum_eq ennreal.has_sum
protected theorem tsum_eq_supr_sum' {α : Type u_1} {f : α → ennreal} {ι : Type u_2} (s : ι → finset α) (hs : ∀ (t : finset α), ∃ (i : ι), t ⊆ s i) : (tsum fun (a : α) => f a) = supr fun (i : ι) => finset.sum (s i) fun (a : α) => f a := sorry
protected theorem tsum_sigma {α : Type u_1} {β : α → Type u_2} (f : (a : α) → β a → ennreal) : (tsum fun (p : sigma fun (a : α) => β a) => f (sigma.fst p) (sigma.snd p)) =
tsum fun (a : α) => tsum fun (b : β a) => f a b :=
tsum_sigma' (fun (b : α) => ennreal.summable) ennreal.summable
protected theorem tsum_sigma' {α : Type u_1} {β : α → Type u_2} (f : (sigma fun (a : α) => β a) → ennreal) : (tsum fun (p : sigma fun (a : α) => β a) => f p) = tsum fun (a : α) => tsum fun (b : β a) => f (sigma.mk a b) :=
tsum_sigma' (fun (b : α) => ennreal.summable) ennreal.summable
protected theorem tsum_prod {α : Type u_1} {β : Type u_2} {f : α → β → ennreal} : (tsum fun (p : α × β) => f (prod.fst p) (prod.snd p)) = tsum fun (a : α) => tsum fun (b : β) => f a b :=
tsum_prod' ennreal.summable fun (_x : α) => ennreal.summable
protected theorem tsum_comm {α : Type u_1} {β : Type u_2} {f : α → β → ennreal} : (tsum fun (a : α) => tsum fun (b : β) => f a b) = tsum fun (b : β) => tsum fun (a : α) => f a b :=
tsum_comm' ennreal.summable (fun (_x : β) => ennreal.summable) fun (_x : α) => ennreal.summable
protected theorem tsum_add {α : Type u_1} {f : α → ennreal} {g : α → ennreal} : (tsum fun (a : α) => f a + g a) = (tsum fun (a : α) => f a) + tsum fun (a : α) => g a :=
tsum_add ennreal.summable ennreal.summable
protected theorem tsum_le_tsum {α : Type u_1} {f : α → ennreal} {g : α → ennreal} (h : ∀ (a : α), f a ≤ g a) : (tsum fun (a : α) => f a) ≤ tsum fun (a : α) => g a :=
tsum_le_tsum h ennreal.summable ennreal.summable
protected theorem sum_le_tsum {α : Type u_1} {f : α → ennreal} (s : finset α) : (finset.sum s fun (x : α) => f x) ≤ tsum fun (x : α) => f x :=
sum_le_tsum s (fun (x : α) (hx : ¬x ∈ s) => zero_le (f x)) ennreal.summable
protected theorem tsum_eq_supr_nat' {f : ℕ → ennreal} {N : ℕ → ℕ} (hN : filter.tendsto N filter.at_top filter.at_top) : (tsum fun (i : ℕ) => f i) = supr fun (i : ℕ) => finset.sum (finset.range (N i)) fun (i : ℕ) => f i := sorry
protected theorem tsum_eq_supr_nat {f : ℕ → ennreal} : (tsum fun (i : ℕ) => f i) = supr fun (i : ℕ) => finset.sum (finset.range i) fun (i : ℕ) => f i :=
ennreal.tsum_eq_supr_sum' (fun (i : ℕ) => finset.range i) finset.exists_nat_subset_range
protected theorem le_tsum {α : Type u_1} {f : α → ennreal} (a : α) : f a ≤ tsum fun (a : α) => f a :=
le_tsum' ennreal.summable a
protected theorem tsum_eq_top_of_eq_top {α : Type u_1} {f : α → ennreal} : (∃ (a : α), f a = ⊤) → (tsum fun (a : α) => f a) = ⊤ :=
fun (ᾰ : ∃ (a : α), f a = ⊤) =>
Exists.dcases_on ᾰ
fun (ᾰ_w : α) (ᾰ_h : f ᾰ_w = ⊤) => idRhs ((tsum fun (a : α) => f a) = ⊤) (top_unique (ᾰ_h ▸ ennreal.le_tsum ᾰ_w))
protected theorem ne_top_of_tsum_ne_top {α : Type u_1} {f : α → ennreal} (h : (tsum fun (a : α) => f a) ≠ ⊤) (a : α) : f a ≠ ⊤ :=
fun (ha : f a = ⊤) => h (ennreal.tsum_eq_top_of_eq_top (Exists.intro a ha))
protected theorem tsum_mul_left {α : Type u_1} {a : ennreal} {f : α → ennreal} : (tsum fun (i : α) => a * f i) = a * tsum fun (i : α) => f i := sorry
protected theorem tsum_mul_right {α : Type u_1} {a : ennreal} {f : α → ennreal} : (tsum fun (i : α) => f i * a) = (tsum fun (i : α) => f i) * a := sorry
@[simp] theorem tsum_supr_eq {α : Type u_1} (a : α) {f : α → ennreal} : (tsum fun (b : α) => supr fun (h : a = b) => f b) = f a := sorry
theorem has_sum_iff_tendsto_nat {f : ℕ → ennreal} (r : ennreal) : has_sum f r ↔ filter.tendsto (fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i) filter.at_top (nhds r) := sorry
theorem to_nnreal_apply_of_tsum_ne_top {α : Type u_1} {f : α → ennreal} (hf : (tsum fun (i : α) => f i) ≠ ⊤) (x : α) : ↑(function.comp ennreal.to_nnreal f x) = f x :=
coe_to_nnreal (ennreal.ne_top_of_tsum_ne_top hf x)
theorem summable_to_nnreal_of_tsum_ne_top {α : Type u_1} {f : α → ennreal} (hf : (tsum fun (i : α) => f i) ≠ ⊤) : summable (ennreal.to_nnreal ∘ f) := sorry
protected theorem tsum_apply {ι : Type u_1} {α : Type u_2} {f : ι → α → ennreal} {x : α} : tsum (fun (i : ι) => f i) x = tsum fun (i : ι) => f i x :=
tsum_apply (iff.mpr pi.summable fun (_x : α) => ennreal.summable)
theorem tsum_sub {f : ℕ → ennreal} {g : ℕ → ennreal} (h₁ : (tsum fun (i : ℕ) => g i) < ⊤) (h₂ : g ≤ f) : (tsum fun (i : ℕ) => f i - g i) = (tsum fun (i : ℕ) => f i) - tsum fun (i : ℕ) => g i := sorry
end ennreal
namespace nnreal
/-- Comparison test of convergence of `ℝ≥0`-valued series. -/
theorem exists_le_has_sum_of_le {β : Type u_2} {f : β → nnreal} {g : β → nnreal} {r : nnreal} (hgf : ∀ (b : β), g b ≤ f b) (hfr : has_sum f r) : ∃ (p : nnreal), ∃ (H : p ≤ r), has_sum g p := sorry
/-- Comparison test of convergence of `ℝ≥0`-valued series. -/
theorem summable_of_le {β : Type u_2} {f : β → nnreal} {g : β → nnreal} (hgf : ∀ (b : β), g b ≤ f b) : summable f → summable g := sorry
/-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if
the sequence of partial sum converges to `r`. -/
theorem has_sum_iff_tendsto_nat {f : ℕ → nnreal} {r : nnreal} : has_sum f r ↔ filter.tendsto (fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i) filter.at_top (nhds r) := sorry
theorem not_summable_iff_tendsto_nat_at_top {f : ℕ → nnreal} : ¬summable f ↔ filter.tendsto (fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i) filter.at_top filter.at_top := sorry
theorem summable_iff_not_tendsto_nat_at_top {f : ℕ → nnreal} : summable f ↔ ¬filter.tendsto (fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i) filter.at_top filter.at_top := sorry
theorem summable_of_sum_range_le {f : ℕ → nnreal} {c : nnreal} (h : ∀ (n : ℕ), (finset.sum (finset.range n) fun (i : ℕ) => f i) ≤ c) : summable f := sorry
theorem tsum_le_of_sum_range_le {f : ℕ → nnreal} {c : nnreal} (h : ∀ (n : ℕ), (finset.sum (finset.range n) fun (i : ℕ) => f i) ≤ c) : (tsum fun (i : ℕ) => f i) ≤ c :=
le_of_tendsto' (iff.mp has_sum_iff_tendsto_nat (summable.has_sum (summable_of_sum_range_le h))) h
theorem tsum_comp_le_tsum_of_inj {α : Type u_1} {β : Type u_2} {f : α → nnreal} (hf : summable f) {i : β → α} (hi : function.injective i) : (tsum fun (x : β) => f (i x)) ≤ tsum fun (x : α) => f x :=
tsum_le_tsum_of_inj i hi (fun (c : α) (hc : ¬c ∈ set.range i) => zero_le (f c)) (fun (b : β) => le_refl (f (i b)))
(summable_comp_injective hf hi) hf
theorem summable_sigma {α : Type u_1} {β : α → Type u_2} {f : (sigma fun (x : α) => β x) → nnreal} : summable f ↔
(∀ (x : α), summable fun (y : β x) => f (sigma.mk x y)) ∧
summable fun (x : α) => tsum fun (y : β x) => f (sigma.mk x y) := sorry
/-- For `f : ℕ → ℝ≥0`, then `∑' k, f (k + i)` tends to zero. This does not require a summability
assumption on `f`, as otherwise all sums are zero. -/
theorem tendsto_sum_nat_add (f : ℕ → nnreal) : filter.tendsto (fun (i : ℕ) => tsum fun (k : ℕ) => f (k + i)) filter.at_top (nhds 0) := sorry
end nnreal
namespace ennreal
theorem tendsto_sum_nat_add (f : ℕ → ennreal) (hf : (tsum fun (i : ℕ) => f i) ≠ ⊤) : filter.tendsto (fun (i : ℕ) => tsum fun (k : ℕ) => f (k + i)) filter.at_top (nhds 0) := sorry
end ennreal
theorem tsum_comp_le_tsum_of_inj {α : Type u_1} {β : Type u_2} {f : α → ℝ} (hf : summable f) (hn : ∀ (a : α), 0 ≤ f a) {i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f := sorry
/-- Comparison test of convergence of series of non-negative real numbers. -/
theorem summable_of_nonneg_of_le {β : Type u_2} {f : β → ℝ} {g : β → ℝ} (hg : ∀ (b : β), 0 ≤ g b) (hgf : ∀ (b : β), g b ≤ f b) (hf : summable f) : summable g := sorry
/-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if
the sequence of partial sum converges to `r`. -/
theorem has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀ (i : ℕ), 0 ≤ f i) (r : ℝ) : has_sum f r ↔ filter.tendsto (fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i) filter.at_top (nhds r) := sorry
theorem ennreal.of_real_tsum_of_nonneg {α : Type u_1} {f : α → ℝ} (hf_nonneg : ∀ (n : α), 0 ≤ f n) (hf : summable f) : ennreal.of_real (tsum fun (n : α) => f n) = tsum fun (n : α) => ennreal.of_real (f n) := sorry
theorem not_summable_iff_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ (n : ℕ), 0 ≤ f n) : ¬summable f ↔ filter.tendsto (fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i) filter.at_top filter.at_top := sorry
theorem summable_iff_not_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ (n : ℕ), 0 ≤ f n) : summable f ↔ ¬filter.tendsto (fun (n : ℕ) => finset.sum (finset.range n) fun (i : ℕ) => f i) filter.at_top filter.at_top := sorry
theorem summable_sigma_of_nonneg {α : Type u_1} {β : α → Type u_2} {f : (sigma fun (x : α) => β x) → ℝ} (hf : ∀ (x : sigma fun (x : α) => β x), 0 ≤ f x) : summable f ↔
(∀ (x : α), summable fun (y : β x) => f (sigma.mk x y)) ∧
summable fun (x : α) => tsum fun (y : β x) => f (sigma.mk x y) := sorry
theorem summable_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ (n : ℕ), 0 ≤ f n) (h : ∀ (n : ℕ), (finset.sum (finset.range n) fun (i : ℕ) => f i) ≤ c) : summable f := sorry
theorem tsum_le_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ (n : ℕ), 0 ≤ f n) (h : ∀ (n : ℕ), (finset.sum (finset.range n) fun (i : ℕ) => f i) ≤ c) : (tsum fun (i : ℕ) => f i) ≤ c := sorry
/-- In an emetric ball, the distance between points is everywhere finite -/
theorem edist_ne_top_of_mem_ball {β : Type u_2} [emetric_space β] {a : β} {r : ennreal} (x : ↥(emetric.ball a r)) (y : ↥(emetric.ball a r)) : edist (subtype.val x) (subtype.val y) ≠ ⊤ := sorry
/-- Each ball in an extended metric space gives us a metric space, as the edist
is everywhere finite. -/
def metric_space_emetric_ball {β : Type u_2} [emetric_space β] (a : β) (r : ennreal) : metric_space ↥(emetric.ball a r) :=
emetric_space.to_metric_space edist_ne_top_of_mem_ball
theorem nhds_eq_nhds_emetric_ball {β : Type u_2} [emetric_space β] (a : β) (x : β) (r : ennreal) (h : x ∈ emetric.ball a r) : nhds x = filter.map coe (nhds { val := x, property := h }) :=
Eq.symm (map_nhds_subtype_coe_eq h (mem_nhds_sets emetric.is_open_ball h))
theorem tendsto_iff_edist_tendsto_0 {α : Type u_1} {β : Type u_2} [emetric_space α] {l : filter β} {f : β → α} {y : α} : filter.tendsto f l (nhds y) ↔ filter.tendsto (fun (x : β) => edist (f x) y) l (nhds 0) := sorry
/-- Yet another metric characterization of Cauchy sequences on integers. This one is often the
most efficient. -/
theorem emetric.cauchy_seq_iff_le_tendsto_0 {α : Type u_1} {β : Type u_2} [emetric_space α] [Nonempty β] [semilattice_sup β] {s : β → α} : cauchy_seq s ↔
∃ (b : β → ennreal),
(∀ (n m N : β), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N) ∧ filter.tendsto b filter.at_top (nhds 0) := sorry
theorem continuous_of_le_add_edist {α : Type u_1} [emetric_space α] {f : α → ennreal} (C : ennreal) (hC : C ≠ ⊤) (h : ∀ (x y : α), f x ≤ f y + C * edist x y) : continuous f := sorry
theorem continuous_edist {α : Type u_1} [emetric_space α] : continuous fun (p : α × α) => edist (prod.fst p) (prod.snd p) := sorry
theorem continuous.edist {α : Type u_1} {β : Type u_2} [emetric_space α] [topological_space β] {f : β → α} {g : β → α} (hf : continuous f) (hg : continuous g) : continuous fun (b : β) => edist (f b) (g b) :=
continuous.comp continuous_edist (continuous.prod_mk hf hg)
theorem filter.tendsto.edist {α : Type u_1} {β : Type u_2} [emetric_space α] {f : β → α} {g : β → α} {x : filter β} {a : α} {b : α} (hf : filter.tendsto f x (nhds a)) (hg : filter.tendsto g x (nhds b)) : filter.tendsto (fun (x : β) => edist (f x) (g x)) x (nhds (edist a b)) :=
filter.tendsto.comp (continuous.tendsto continuous_edist (a, b)) (filter.tendsto.prod_mk_nhds hf hg)
theorem cauchy_seq_of_edist_le_of_tsum_ne_top {α : Type u_1} [emetric_space α] {f : ℕ → α} (d : ℕ → ennreal) (hf : ∀ (n : ℕ), edist (f n) (f (Nat.succ n)) ≤ d n) (hd : tsum d ≠ ⊤) : cauchy_seq f := sorry
theorem emetric.is_closed_ball {α : Type u_1} [emetric_space α] {a : α} {r : ennreal} : is_closed (emetric.closed_ball a r) :=
is_closed_le (continuous.edist continuous_id continuous_const) continuous_const
/-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ennreal`,
then the distance from `f n` to the limit is bounded by `∑'_{k=n}^∞ d k`. -/
theorem edist_le_tsum_of_edist_le_of_tendsto {α : Type u_1} [emetric_space α] {f : ℕ → α} (d : ℕ → ennreal) (hf : ∀ (n : ℕ), edist (f n) (f (Nat.succ n)) ≤ d n) {a : α} (ha : filter.tendsto f filter.at_top (nhds a)) (n : ℕ) : edist (f n) a ≤ tsum fun (m : ℕ) => d (n + m) := sorry
/-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ennreal`,
then the distance from `f 0` to the limit is bounded by `∑'_{k=0}^∞ d k`. -/
theorem edist_le_tsum_of_edist_le_of_tendsto₀ {α : Type u_1} [emetric_space α] {f : ℕ → α} (d : ℕ → ennreal) (hf : ∀ (n : ℕ), edist (f n) (f (Nat.succ n)) ≤ d n) {a : α} (ha : filter.tendsto f filter.at_top (nhds a)) : edist (f 0) a ≤ tsum fun (m : ℕ) => d m := sorry
|
b716f9d8531740c90e74df452259bc58f2b4f98a | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /library/theories/analysis/real_limit.lean | 45df21ba8eb3b05cf91567e9e2232fa185afa4b6 | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 25,108 | lean | /-
Copyright (c) 2015 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis
Instantiates the reals as a Banach space.
-/
import .metric_space data.real.complete data.set .normed_space
open real classical analysis nat
noncomputable theory
/- sup and inf -/
-- Expresses completeness, sup, and inf in a manner that is less constructive, but more convenient,
-- than the way it is done in data.real.complete.
-- Issue: real.sup and real.inf conflict with sup and inf in lattice.
-- Perhaps put algebra sup and inf into a namespace?
namespace real
open set
private definition exists_is_sup {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b)) :
∃ y, is_sup X y :=
let x := some (and.left H), b := some (and.right H) in
exists_is_sup_of_inh_of_bdd X x (some_spec (and.left H)) b (some_spec (and.right H))
private definition sup_aux {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b)) :=
some (exists_is_sup H)
private definition sup_aux_spec {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b)) :
is_sup X (sup_aux H) :=
some_spec (exists_is_sup H)
definition sup (X : set ℝ) : ℝ :=
if H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b) then sup_aux H else 0
proposition le_sup {x : ℝ} {X : set ℝ} (Hx : x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → x ≤ b) :
x ≤ sup X :=
have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b),
from and.intro (exists.intro x Hx) (exists.intro b Hb),
by+ rewrite [↑sup, dif_pos H]; exact and.left (sup_aux_spec H) x Hx
proposition sup_le {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → x ≤ b) :
sup X ≤ b :=
have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → x ≤ b),
from and.intro HX (exists.intro b Hb),
by+ rewrite [↑sup, dif_pos H]; exact and.right (sup_aux_spec H) b Hb
proposition exists_mem_and_lt_of_lt_sup {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : b < sup X) :
∃ x, x ∈ X ∧ b < x :=
have ¬ ∀ x, x ∈ X → x ≤ b, from assume H, not_le_of_gt Hb (sup_le HX H),
obtain x (Hx : ¬ (x ∈ X → x ≤ b)), from exists_not_of_not_forall this,
exists.intro x
(have x ∈ X ∧ ¬ x ≤ b, by rewrite [-not_implies_iff_and_not]; apply Hx,
and.intro (and.left this) (lt_of_not_ge (and.right this)))
private definition exists_is_inf {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x)) :
∃ y, is_inf X y :=
let x := some (and.left H), b := some (and.right H) in
exists_is_inf_of_inh_of_bdd X x (some_spec (and.left H)) b (some_spec (and.right H))
private definition inf_aux {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x)) :=
some (exists_is_inf H)
private definition inf_aux_spec {X : set ℝ} (H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x)) :
is_inf X (inf_aux H) :=
some_spec (exists_is_inf H)
definition inf (X : set ℝ) : ℝ :=
if H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x) then inf_aux H else 0
proposition inf_le {x : ℝ} {X : set ℝ} (Hx : x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → b ≤ x) :
inf X ≤ x :=
have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x),
from and.intro (exists.intro x Hx) (exists.intro b Hb),
by+ rewrite [↑inf, dif_pos H]; exact and.left (inf_aux_spec H) x Hx
proposition le_inf {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → b ≤ x) :
b ≤ inf X :=
have H : (∃ x, x ∈ X) ∧ (∃ b, ∀ x, x ∈ X → b ≤ x),
from and.intro HX (exists.intro b Hb),
by+ rewrite [↑inf, dif_pos H]; exact and.right (inf_aux_spec H) b Hb
proposition exists_mem_and_lt_of_inf_lt {X : set ℝ} (HX : ∃ x, x ∈ X) {b : ℝ} (Hb : inf X < b) :
∃ x, x ∈ X ∧ x < b :=
have ¬ ∀ x, x ∈ X → b ≤ x, from assume H, not_le_of_gt Hb (le_inf HX H),
obtain x (Hx : ¬ (x ∈ X → b ≤ x)), from exists_not_of_not_forall this,
exists.intro x
(have x ∈ X ∧ ¬ b ≤ x, by rewrite [-not_implies_iff_and_not]; apply Hx,
and.intro (and.left this) (lt_of_not_ge (and.right this)))
section
local attribute mem [quasireducible]
-- TODO: is there a better place to put this?
proposition image_neg_eq (X : set ℝ) : (λ x, -x) ' X = {x | -x ∈ X} :=
set.ext (take x, iff.intro
(assume H, obtain y [(Hy₁ : y ∈ X) (Hy₂ : -y = x)], from H,
show -x ∈ X, by rewrite [-Hy₂, neg_neg]; exact Hy₁)
(assume H : -x ∈ X, exists.intro (-x) (and.intro H !neg_neg)))
proposition sup_neg {X : set ℝ} (nonempty_X : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → b ≤ x) :
sup {x | -x ∈ X} = - inf X :=
let negX := {x | -x ∈ X} in
have nonempty_negX : ∃ x, x ∈ negX, from
obtain x Hx, from nonempty_X,
have -(-x) ∈ X,
by rewrite neg_neg; apply Hx,
exists.intro (-x) this,
have H₁ : ∀ x, x ∈ negX → x ≤ - inf X, from
take x,
assume H,
have inf X ≤ -x,
from inf_le H Hb,
show x ≤ - inf X,
from le_neg_of_le_neg this,
have H₂ : ∀ x, x ∈ X → -sup negX ≤ x, from
take x,
assume H,
have -(-x) ∈ X, by rewrite neg_neg; apply H,
have -x ≤ sup negX, from le_sup this H₁,
show -sup negX ≤ x,
from !neg_le_of_neg_le this,
eq_of_le_of_ge
(show sup negX ≤ - inf X,
from sup_le nonempty_negX H₁)
(show -inf X ≤ sup negX,
from !neg_le_of_neg_le (le_inf nonempty_X H₂))
proposition inf_neg {X : set ℝ} (nonempty_X : ∃ x, x ∈ X) {b : ℝ} (Hb : ∀ x, x ∈ X → x ≤ b) :
inf {x | -x ∈ X} = - sup X :=
let negX := {x | -x ∈ X} in
have nonempty_negX : ∃ x, x ∈ negX, from
obtain x Hx, from nonempty_X,
have -(-x) ∈ X,
by rewrite neg_neg; apply Hx,
exists.intro (-x) this,
have Hb' : ∀ x, x ∈ negX → -b ≤ x,
from take x, assume H, !neg_le_of_neg_le (Hb _ H),
have HX : X = {x | -x ∈ negX},
from set.ext (take x, by rewrite [↑set_of, ↑mem, +neg_neg]),
show inf {x | -x ∈ X} = - sup X,
using HX Hb' nonempty_negX, by rewrite [HX at {2}, sup_neg nonempty_negX Hb', neg_neg]
end
end real
/- the reals form a complete metric space -/
namespace analysis
theorem dist_eq_abs (x y : real) : dist x y = abs (x - y) := rfl
proposition converges_to_seq_real_intro {X : ℕ → ℝ} {y : ℝ}
(H : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → abs (X n - y) < ε) :
(X ⟶ y in ℕ) := H
proposition converges_to_seq_real_elim {X : ℕ → ℝ} {y : ℝ} (H : X ⟶ y in ℕ) :
∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → abs (X n - y) < ε := H
proposition converges_to_seq_real_intro' {X : ℕ → ℝ} {y : ℝ}
(H : ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ N : ℕ, ∀ {n}, n ≥ N → abs (X n - y) ≤ ε) :
converges_to_seq X y :=
converges_to_seq.intro H
open pnat subtype
local postfix ⁻¹ := pnat.inv
private definition pnat.succ (n : ℕ) : ℕ+ := tag (succ n) !succ_pos
private definition r_seq_of (X : ℕ → ℝ) : r_seq := λ n, X (elt_of n)
private lemma rate_of_cauchy_aux {X : ℕ → ℝ} (H : cauchy X) :
∀ k : ℕ+, ∃ N : ℕ+, ∀ m n : ℕ+,
m ≥ N → n ≥ N → abs (X (elt_of m) - X (elt_of n)) ≤ of_rat k⁻¹ :=
take k : ℕ+,
have H1 : (k⁻¹ >[rat] (rat.of_num 0)), from !pnat.inv_pos,
have H2 : (of_rat k⁻¹ > of_rat (rat.of_num 0)), from !of_rat_lt_of_rat_of_lt H1,
obtain (N : ℕ) (H : ∀ m n, m ≥ N → n ≥ N → abs (X m - X n) < of_rat k⁻¹), from H _ H2,
exists.intro (pnat.succ N)
(take m n : ℕ+,
assume Hm : m ≥ (pnat.succ N),
assume Hn : n ≥ (pnat.succ N),
have Hm' : elt_of m ≥ N, begin apply le.trans, apply le_succ, apply Hm end,
have Hn' : elt_of n ≥ N, begin apply le.trans, apply le_succ, apply Hn end,
show abs (X (elt_of m) - X (elt_of n)) ≤ of_rat k⁻¹, from le_of_lt (H _ _ Hm' Hn'))
private definition rate_of_cauchy {X : ℕ → ℝ} (H : cauchy X) (k : ℕ+) : ℕ+ :=
some (rate_of_cauchy_aux H k)
private lemma cauchy_with_rate_of_cauchy {X : ℕ → ℝ} (H : cauchy X) :
cauchy_with_rate (r_seq_of X) (rate_of_cauchy H) :=
take k : ℕ+,
some_spec (rate_of_cauchy_aux H k)
private lemma converges_to_with_rate_of_cauchy {X : ℕ → ℝ} (H : cauchy X) :
∃ l Nb, converges_to_with_rate (r_seq_of X) l Nb :=
begin
apply exists.intro,
apply exists.intro,
apply converges_to_with_rate_of_cauchy_with_rate,
exact cauchy_with_rate_of_cauchy H
end
theorem converges_seq_of_cauchy {X : ℕ → ℝ} (H : cauchy X) : converges_seq X :=
obtain l Nb (conv : converges_to_with_rate (r_seq_of X) l Nb),
from converges_to_with_rate_of_cauchy H,
exists.intro l
(take ε : ℝ,
suppose ε > 0,
obtain (k' : ℕ) (Hn : 1 / succ k' < ε), from archimedean_small `ε > 0`,
let k : ℕ+ := tag (succ k') !succ_pos,
N : ℕ+ := Nb k in
have Hk : real.of_rat k⁻¹ < ε,
by rewrite [↑pnat.inv, of_rat_divide]; exact Hn,
exists.intro (elt_of N)
(take n : ℕ,
assume Hn : n ≥ elt_of N,
let n' : ℕ+ := tag n (nat.lt_of_lt_of_le (has_property N) Hn) in
have abs (X n - l) ≤ real.of_rat k⁻¹, by apply conv k n' Hn,
show abs (X n - l) < ε, from lt_of_le_of_lt this Hk))
end analysis
definition complete_metric_space_real [reducible] [trans_instance] :
complete_metric_space ℝ :=
⦃complete_metric_space, metric_space_real,
complete := @analysis.converges_seq_of_cauchy
⦄
/- the real numbers can be viewed as a banach space -/
definition real_vector_space_real : real_vector_space ℝ :=
⦃ real_vector_space, real.discrete_linear_ordered_field,
smul := mul,
smul_left_distrib := left_distrib,
smul_right_distrib := right_distrib,
mul_smul := mul.assoc,
one_smul := one_mul
⦄
definition banach_space_real [trans_instance] [reducible] : banach_space ℝ :=
⦃ banach_space, real_vector_space_real,
norm := abs,
norm_zero := abs_zero,
eq_zero_of_norm_eq_zero := λ a H, eq_zero_of_abs_eq_zero H,
norm_triangle := abs_add_le_abs_add_abs,
norm_smul := abs_mul,
complete := λ X H, analysis.complete ℝ H
⦄
/- limits under pointwise operations -/
section limit_operations
variables {X Y : ℕ → ℝ}
variables {x y : ℝ}
proposition mul_left_converges_to_seq (c : ℝ) (HX : X ⟶ x in ℕ) :
(λ n, c * X n) ⟶ c * x in ℕ :=
smul_converges_to_seq c HX
proposition mul_right_converges_to_seq (c : ℝ) (HX : X ⟶ x in ℕ) :
(λ n, X n * c) ⟶ x * c in ℕ :=
have (λ n, X n * c) = (λ n, c * X n), from funext (take x, !mul.comm),
by+ rewrite [this, mul.comm]; apply mul_left_converges_to_seq c HX
theorem converges_to_seq_squeeze (HX : X ⟶ x in ℕ) (HY : Y ⟶ x in ℕ) {Z : ℕ → ℝ} (HZX : ∀ n, X n ≤ Z n)
(HZY : ∀ n, Z n ≤ Y n) : Z ⟶ x in ℕ :=
begin
intros ε Hε,
have Hε4 : ε / 4 > 0, from div_pos_of_pos_of_pos Hε four_pos,
cases HX Hε4 with N1 HN1,
cases HY Hε4 with N2 HN2,
existsi max N1 N2,
intro n Hn,
have HXY : abs (Y n - X n) < ε / 2, begin
apply lt_of_le_of_lt,
apply abs_sub_le _ x,
have Hε24 : ε / 2 = ε / 4 + ε / 4, from eq.symm !add_quarters,
rewrite Hε24,
apply add_lt_add,
apply HN2,
apply ge.trans Hn !le_max_right,
rewrite abs_sub,
apply HN1,
apply ge.trans Hn !le_max_left
end,
have HZX : abs (Z n - X n) < ε / 2, begin
have HZXnp : Z n - X n ≥ 0, from sub_nonneg_of_le !HZX,
have HXYnp : Y n - X n ≥ 0, from sub_nonneg_of_le (le.trans !HZX !HZY),
rewrite [abs_of_nonneg HZXnp, abs_of_nonneg HXYnp at HXY],
note Hgt := lt_add_of_sub_lt_right HXY,
have Hlt : Z n < ε / 2 + X n, from calc
Z n ≤ Y n : HZY
... < ε / 2 + X n : Hgt,
apply sub_lt_right_of_lt_add Hlt
end,
have H : abs (Z n - x) < ε, begin
apply lt_of_le_of_lt,
apply abs_sub_le _ (X n),
apply lt.trans,
apply add_lt_add,
apply HZX,
apply HN1,
apply ge.trans Hn !le_max_left,
apply div_two_add_div_four_lt Hε
end,
exact H
end
proposition converges_to_seq_of_abs_sub_converges_to_seq (Habs : (λ n, abs (X n - x)) ⟶ 0 in ℕ) :
X ⟶ x in ℕ :=
begin
intros ε Hε,
cases Habs Hε with N HN,
existsi N,
intro n Hn,
have Hn' : abs (abs (X n - x) - 0) < ε, from HN Hn,
rewrite [sub_zero at Hn', abs_abs at Hn'],
exact Hn'
end
proposition abs_sub_converges_to_seq_of_converges_to_seq (HX : X ⟶ x in ℕ) :
(λ n, abs (X n - x)) ⟶ 0 in ℕ :=
begin
intros ε Hε,
cases HX Hε with N HN,
existsi N,
intro n Hn,
have Hn' : abs (abs (X n - x) - 0) < ε, by rewrite [sub_zero, abs_abs]; apply HN Hn,
exact Hn'
end
proposition mul_converges_to_seq (HX : X ⟶ x in ℕ) (HY : Y ⟶ y in ℕ) :
(λ n, X n * Y n) ⟶ x * y in ℕ :=
begin
have Hbd : ∃ K : ℝ, ∀ n : ℕ, abs (X n) ≤ K, begin
cases bounded_of_converges_seq HX with K HK,
existsi K + abs x,
intro n,
note Habs := le.trans (abs_abs_sub_abs_le_abs_sub (X n) x) !HK,
apply le_add_of_sub_right_le,
apply le.trans,
apply le_abs_self,
assumption
end,
cases Hbd with K HK,
have Habsle : ∀ n, abs (X n * Y n - x * y) ≤ K * abs (Y n - y) + abs y * abs (X n - x), begin
intro,
have Heq : X n * Y n - x * y = (X n * Y n - X n * y) + (X n * y - x * y), by
rewrite [-sub_add_cancel (X n * Y n) (X n * y) at {1}, sub_eq_add_neg, *add.assoc],
apply le.trans,
rewrite Heq,
apply abs_add_le_abs_add_abs,
apply add_le_add,
rewrite [-mul_sub_left_distrib, abs_mul],
apply mul_le_mul_of_nonneg_right,
apply HK,
apply abs_nonneg,
rewrite [-mul_sub_right_distrib, abs_mul, mul.comm],
apply le.refl
end,
have Hdifflim : (λ n, abs (X n * Y n - x * y)) ⟶ 0 in ℕ, begin
apply converges_to_seq_squeeze,
rotate 2,
intro, apply abs_nonneg,
apply Habsle,
apply converges_to_seq_constant,
rewrite -{0}zero_add,
apply add_converges_to_seq,
krewrite -(mul_zero K),
apply mul_left_converges_to_seq,
apply abs_sub_converges_to_seq_of_converges_to_seq,
exact HY,
krewrite -(mul_zero (abs y)),
apply mul_left_converges_to_seq,
apply abs_sub_converges_to_seq_of_converges_to_seq,
exact HX
end,
apply converges_to_seq_of_abs_sub_converges_to_seq,
apply Hdifflim
end
-- TODO: converges_to_seq_div, converges_to_seq_mul_left_iff, etc.
proposition abs_converges_to_seq_zero (HX : X ⟶ 0 in ℕ) : (λ n, abs (X n)) ⟶ 0 in ℕ :=
norm_converges_to_seq_zero HX
proposition converges_to_seq_zero_of_abs_converges_to_seq_zero (HX : (λ n, abs (X n)) ⟶ 0 in ℕ) :
X ⟶ 0 in ℕ :=
converges_to_seq_zero_of_norm_converges_to_seq_zero HX
proposition abs_converges_to_seq_zero_iff (X : ℕ → ℝ) :
((λ n, abs (X n)) ⟶ 0 in ℕ) ↔ (X ⟶ 0 in ℕ) :=
iff.intro converges_to_seq_zero_of_abs_converges_to_seq_zero abs_converges_to_seq_zero
-- TODO: products of two sequences, converges_seq, limit_seq
end limit_operations
/- properties of converges_to_at -/
section limit_operations_continuous
variables {f g : ℝ → ℝ}
variables {a b x y : ℝ}
theorem mul_converges_to_at (Hf : f ⟶ a at x) (Hg : g ⟶ b at x) : (λ z, f z * g z) ⟶ a * b at x :=
begin
apply converges_to_at_of_all_conv_seqs,
intro X HX,
apply mul_converges_to_seq,
note Hfc := all_conv_seqs_of_converges_to_at Hf,
apply Hfc _ HX,
note Hgb := all_conv_seqs_of_converges_to_at Hg,
apply Hgb _ HX
end
end limit_operations_continuous
/- monotone sequences -/
section monotone_sequences
open real set
variable {X : ℕ → ℝ}
definition nondecreasing (X : ℕ → ℝ) : Prop := ∀ ⦃i j⦄, i ≤ j → X i ≤ X j
proposition nondecreasing_of_forall_le_succ (H : ∀ i, X i ≤ X (succ i)) : nondecreasing X :=
take i j, suppose i ≤ j,
have ∀ n, X i ≤ X (i + n), from
take n, nat.induction_on n
(by rewrite nat.add_zero; apply le.refl)
(take n, assume ih, le.trans ih (H (i + n))),
have X i ≤ X (i + (j - i)), from !this,
by+ rewrite [add_sub_of_le `i ≤ j` at this]; exact this
proposition converges_to_seq_sup_of_nondecreasing (nondecX : nondecreasing X) {b : ℝ}
(Hb : ∀ i, X i ≤ b) : X ⟶ sup (X ' univ) in ℕ :=
let sX := sup (X ' univ) in
have Xle : ∀ i, X i ≤ sX, from
take i,
have ∀ x, x ∈ X ' univ → x ≤ b, from
(take x, assume H,
obtain i [H' (Hi : X i = x)], from H,
by rewrite -Hi; exact Hb i),
show X i ≤ sX, from le_sup (mem_image_of_mem X !mem_univ) this,
have exX : ∃ x, x ∈ X ' univ,
from exists.intro (X 0) (mem_image_of_mem X !mem_univ),
take ε, assume epos : ε > 0,
have sX - ε < sX, from !sub_lt_of_pos epos,
obtain x' [(H₁x' : x' ∈ X ' univ) (H₂x' : sX - ε < x')],
from exists_mem_and_lt_of_lt_sup exX this,
obtain i [H' (Hi : X i = x')], from H₁x',
have Hi' : ∀ j, j ≥ i → sX - ε < X j, from
take j, assume Hj, lt_of_lt_of_le (by rewrite Hi; apply H₂x') (nondecX Hj),
exists.intro i
(take j, assume Hj : j ≥ i,
have X j - sX ≤ 0, from sub_nonpos_of_le (Xle j),
have eq₁ : abs (X j - sX) = sX - X j, using this, by rewrite [abs_of_nonpos this, neg_sub],
have sX - ε < X j, from lt_of_lt_of_le (by rewrite Hi; apply H₂x') (nondecX Hj),
have sX < X j + ε, from lt_add_of_sub_lt_right this,
have sX - X j < ε, from sub_lt_left_of_lt_add this,
show (abs (X j - sX)) < ε, using eq₁ this, by rewrite eq₁; exact this)
definition nonincreasing (X : ℕ → ℝ) : Prop := ∀ ⦃i j⦄, i ≤ j → X i ≥ X j
proposition nodecreasing_of_nonincreasing_neg (nonincX : nonincreasing (λ n, - X n)) :
nondecreasing (λ n, X n) :=
take i j, suppose i ≤ j,
show X i ≤ X j, from le_of_neg_le_neg (nonincX this)
proposition noincreasing_neg_of_nondecreasing (nondecX : nondecreasing X) :
nonincreasing (λ n, - X n) :=
take i j, suppose i ≤ j,
show - X i ≥ - X j, from neg_le_neg (nondecX this)
proposition nonincreasing_neg_iff (X : ℕ → ℝ) : nonincreasing (λ n, - X n) ↔ nondecreasing X :=
iff.intro nodecreasing_of_nonincreasing_neg noincreasing_neg_of_nondecreasing
proposition nonincreasing_of_nondecreasing_neg (nondecX : nondecreasing (λ n, - X n)) :
nonincreasing (λ n, X n) :=
take i j, suppose i ≤ j,
show X i ≥ X j, from le_of_neg_le_neg (nondecX this)
proposition nodecreasing_neg_of_nonincreasing (nonincX : nonincreasing X) :
nondecreasing (λ n, - X n) :=
take i j, suppose i ≤ j,
show - X i ≤ - X j, from neg_le_neg (nonincX this)
proposition nondecreasing_neg_iff (X : ℕ → ℝ) : nondecreasing (λ n, - X n) ↔ nonincreasing X :=
iff.intro nonincreasing_of_nondecreasing_neg nodecreasing_neg_of_nonincreasing
proposition nonincreasing_of_forall_succ_le (H : ∀ i, X (succ i) ≤ X i) : nonincreasing X :=
begin
rewrite -nondecreasing_neg_iff,
show nondecreasing (λ n : ℕ, - X n), from
nondecreasing_of_forall_le_succ (take i, neg_le_neg (H i))
end
proposition converges_to_seq_inf_of_nonincreasing (nonincX : nonincreasing X) {b : ℝ}
(Hb : ∀ i, b ≤ X i) : X ⟶ inf (X ' univ) in ℕ :=
have H₁ : ∃ x, x ∈ X ' univ, from exists.intro (X 0) (mem_image_of_mem X !mem_univ),
have H₂ : ∀ x, x ∈ X ' univ → b ≤ x, from
(take x, assume H,
obtain i [Hi₁ (Hi₂ : X i = x)], from H,
show b ≤ x, by rewrite -Hi₂; apply Hb i),
have H₃ : {x : ℝ | -x ∈ X ' univ} = {x : ℝ | x ∈ (λ n, -X n) ' univ}, from calc
{x : ℝ | -x ∈ X ' univ} = (λ y, -y) ' (X ' univ) : by rewrite image_neg_eq
... = {x : ℝ | x ∈ (λ n, -X n) ' univ} : image_compose,
have H₄ : ∀ i, - X i ≤ - b, from take i, neg_le_neg (Hb i),
begin+
-- need krewrite here
krewrite [-neg_converges_to_seq_iff, -sup_neg H₁ H₂, H₃, -nondecreasing_neg_iff at nonincX],
apply converges_to_seq_sup_of_nondecreasing nonincX H₄
end
end monotone_sequences
/- x^n converges to 0 if abs x < 1 -/
section xn
open nat set
theorem pow_converges_to_seq_zero {x : ℝ} (H : abs x < 1) :
(λ n, x^n) ⟶ 0 in ℕ :=
suffices H' : (λ n, (abs x)^n) ⟶ 0 in ℕ, from
have (λ n, (abs x)^n) = (λ n, abs (x^n)), from funext (take n, eq.symm !abs_pow),
using this,
by rewrite this at H'; exact converges_to_seq_zero_of_abs_converges_to_seq_zero H',
let aX := (λ n, (abs x)^n),
iaX := real.inf (aX ' univ),
asX := (λ n, (abs x)^(succ n)) in
have noninc_aX : nonincreasing aX, from
nonincreasing_of_forall_succ_le
(take i,
assert (abs x) * (abs x)^i ≤ 1 * (abs x)^i,
from mul_le_mul_of_nonneg_right (le_of_lt H) (!pow_nonneg_of_nonneg !abs_nonneg),
assert (abs x) * (abs x)^i ≤ (abs x)^i, by krewrite one_mul at this; exact this,
show (abs x) ^ (succ i) ≤ (abs x)^i, by rewrite pow_succ; apply this),
have bdd_aX : ∀ i, 0 ≤ aX i, from take i, !pow_nonneg_of_nonneg !abs_nonneg,
assert aXconv : aX ⟶ iaX in ℕ, proof converges_to_seq_inf_of_nonincreasing noninc_aX bdd_aX qed,
have asXconv : asX ⟶ iaX in ℕ, from converges_to_seq_offset_succ aXconv,
have asXconv' : asX ⟶ (abs x) * iaX in ℕ, from mul_left_converges_to_seq (abs x) aXconv,
have iaX = (abs x) * iaX, from converges_to_seq_unique asXconv asXconv',
assert iaX = 0, from eq_zero_of_mul_eq_self_left (ne_of_lt H) (eq.symm this),
show aX ⟶ 0 in ℕ, begin rewrite -this, exact aXconv end --from this ▸ aXconv
end xn
/- continuity on the reals -/
section continuous
theorem continuous_real_elim {f : ℝ → ℝ} (H : continuous f) :
∀ x : ℝ, ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ δ : ℝ, δ > 0 ∧ ∀ x' : ℝ,
abs (x' - x) < δ → abs (f x' - f x) < ε :=
H
theorem continuous_real_intro {f : ℝ → ℝ}
(H : ∀ x : ℝ, ∀ ⦃ε : ℝ⦄, ε > 0 → ∃ δ : ℝ, δ > 0 ∧ ∀ x' : ℝ,
abs (x' - x) < δ → abs (f x' - f x) < ε) :
continuous f :=
H
theorem pos_on_nbhd_of_cts_of_pos {f : ℝ → ℝ} (Hf : continuous f) {b : ℝ} (Hb : f b > 0) :
∃ δ : ℝ, δ > 0 ∧ ∀ y, abs (y - b) < δ → f y > 0 :=
begin
let Hcont := continuous_real_elim Hf b Hb,
cases Hcont with δ Hδ,
existsi δ,
split,
exact and.left Hδ,
intro y Hy,
let Hy' := and.right Hδ y Hy,
note Hlt := sub_lt_of_abs_sub_lt_left Hy',
rewrite sub_self at Hlt,
assumption
end
theorem neg_on_nbhd_of_cts_of_neg {f : ℝ → ℝ} (Hf : continuous f) {b : ℝ} (Hb : f b < 0) :
∃ δ : ℝ, δ > 0 ∧ ∀ y, abs (y - b) < δ → f y < 0 :=
begin
let Hcont := continuous_real_elim Hf b (neg_pos_of_neg Hb),
cases Hcont with δ Hδ,
existsi δ,
split,
exact and.left Hδ,
intro y Hy,
let Hy' := and.right Hδ y Hy,
let Hlt := sub_lt_of_abs_sub_lt_right Hy',
note Hlt' := lt_add_of_sub_lt_left Hlt,
rewrite [add.comm at Hlt', -sub_eq_add_neg at Hlt', sub_self at Hlt'],
assumption
end
theorem continuous_neg_of_continuous {f : ℝ → ℝ} (Hcon : continuous f) : continuous (λ x, - f x) :=
begin
apply continuous_real_intro,
intros x ε Hε,
cases continuous_real_elim Hcon x Hε with δ Hδ,
cases Hδ with Hδ₁ Hδ₂,
existsi δ,
split,
assumption,
intros x' Hx',
let HD := Hδ₂ x' Hx',
rewrite [-abs_neg, neg_neg_sub_neg],
exact HD
end
theorem continuous_offset_of_continuous {f : ℝ → ℝ} (Hcon : continuous f) (a : ℝ) :
continuous (λ x, (f x) + a) :=
begin
apply continuous_real_intro,
intros x ε Hε,
cases continuous_real_elim Hcon x Hε with δ Hδ,
cases Hδ with Hδ₁ Hδ₂,
existsi δ,
split,
assumption,
intros x' Hx',
rewrite [add_sub_comm, sub_self, add_zero],
apply Hδ₂,
assumption
end
theorem continuous_mul_of_continuous {f g : ℝ → ℝ} (Hconf : continuous f) (Hcong : continuous g) :
continuous (λ x, f x * g x) :=
begin
intro x,
apply continuous_at_of_converges_to_at,
apply mul_converges_to_at,
all_goals apply converges_to_at_of_continuous_at,
apply Hconf,
apply Hcong
end
end continuous
/-
proposition converges_to_at_unique {f : M → N} {y₁ y₂ : N} {x : M}
(H₁ : f ⟶ y₁ '[at x]) (H₂ : f ⟶ y₂ '[at x]) : y₁ = y₂ :=
eq_of_forall_dist_le
(take ε, suppose ε > 0,
have e2pos : ε / 2 > 0, from div_pos_of_pos_of_pos `ε > 0` two_pos,
obtain δ₁ [(δ₁pos : δ₁ > 0) (Hδ₁ : ∀ x', x ≠ x' ∧ dist x x' < δ₁ → dist (f x') y₁ < ε / 2)],
from H₁ e2pos,
obtain δ₂ [(δ₂pos : δ₂ > 0) (Hδ₂ : ∀ x', x ≠ x' ∧ dist x x' < δ₂ → dist (f x') y₂ < ε / 2)],
from H₂ e2pos,
let δ := min δ₁ δ₂ in
have δ > 0, from lt_min δ₁pos δ₂pos,
-/
|
fc62d14448c119a6b7c459abc3b8917d4c5ff339 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/record2.lean | 395671870366781c135b5014a0eb45fc0d70026f | [
"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 | 265 | lean | set_option pp.universes true
section
parameter (A : Type)
section
parameter (B : Type)
structure point :=
mk :: (x : A) (y : B)
#check point
#check point.mk
#check point.x
end
#check point
#check point.mk
#check point.x
end
|
0eb1abff100ac60dc8ef0e99c288e7f612c3c926 | 75c54c8946bb4203e0aaf196f918424a17b0de99 | /src/summary.lean | 1499b9f4ad2df1eec508e3d8823b279b8578730a | [
"Apache-2.0"
] | permissive | urkud/flypitch | 261e2a45f1038130178575406df8aea78255ba77 | 2250f5eda14b6ef9fc3e4e1f4a9ac4005634de5c | refs/heads/master | 1,653,266,469,246 | 1,577,819,679,000 | 1,577,819,679,000 | 259,862,235 | 1 | 0 | Apache-2.0 | 1,588,147,244,000 | 1,588,147,244,000 | null | UTF-8 | Lean | false | false | 2,177 | lean | /-
Copyright (c) 2019 The Flypitch Project. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jesse Han, Floris van Doorn
-/
import .zfc .completeness .print_formula
open fol bSet pSet lattice collapse_algebra
/-
This file summarizes:
- important definitions with #print statements, and
- important theorems with duplicated proofs
The user is encouraged to use their editor's jump-to-definition
feature to inspect the source code of any expressions which are
printed or which occur in the proofs below.
-/
#print Language
#print preterm
#print preformula
#print term
#print formula
#print sentence
#print soundness
#print prf
#print provable
#print is_consistent
#print pSet
#print bSet
#print L_ZFC
#print ZFC
#eval print_formula_list ([axiom_of_emptyset, axiom_of_ordered_pairs, axiom_of_extensionality, axiom_of_union, axiom_of_powerset, axiom_of_infinity, axiom_of_regularity, zorns_lemma])
#print CH
#print CH_f
#print 𝔹_cohen
#print 𝔹_collapse
theorem godel_completeness_theorem {L} (T) (ψ : sentence L) : T ⊢' ψ ↔ T ⊨ ψ :=
completeness T ψ
theorem boolean_valued_soundness_theorem {L} {β} [complete_boolean_algebra β] {T : Theory L}
{A : sentence L} (H : T ⊢ A) : T ⊨[β] A :=
forced_of_bsatisfied $ boolean_formula_soundness H
theorem fundamental_theorem_of_forcing {β} [nontrivial_complete_boolean_algebra β] :
⊤ ⊩[V β] ZFC :=
bSet_models_ZFC β
theorem ZFC_is_consistent {β : Type} [nontrivial_complete_boolean_algebra β] :
is_consistent ZFC :=
consis_of_exists_bmodel (bSet_models_ZFC β)
theorem CH_unprovable : ¬ (ZFC ⊢' CH_f) :=
CH_f_unprovable
theorem neg_CH_unprovable : ¬ (ZFC ⊢' ∼CH_f) :=
neg_CH_f_unprovable
def independent {L : Language} (T : Theory L) (f : sentence L) : Prop :=
¬ T ⊢' f ∧ ¬ T ⊢' ∼f
theorem independence_of_CH : independent ZFC CH_f :=
by finish [independent, CH_unprovable, neg_CH_unprovable]
#print axioms independence_of_CH
/- `propext` (propositional extensionality),
`classical.choice` (a type-theoretic choice principle), and
`quot.sound` (quotients) are the standard axioms in Lean. -/
|
09292158534af397e9dffb9e391856b2e1389c84 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/category/Algebra/basic_auto.lean | 516445f3482a1c330b86b52bb5e489c3ff47f98d | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,949 | 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 Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.algebra.basic
import Mathlib.algebra.algebra.subalgebra
import Mathlib.algebra.free_algebra
import Mathlib.algebra.category.CommRing.basic
import Mathlib.algebra.category.Module.basic
import Mathlib.PostPort
universes v u l u_1
namespace Mathlib
/-- The category of R-modules and their morphisms. -/
structure Algebra (R : Type u) [comm_ring R] where
carrier : Type v
is_ring : ring carrier
is_algebra : algebra R carrier
namespace Algebra
protected instance has_coe_to_sort (R : Type u) [comm_ring R] : has_coe_to_sort (Algebra R) :=
has_coe_to_sort.mk (Type v) carrier
protected instance category_theory.category (R : Type u) [comm_ring R] :
category_theory.category (Algebra R) :=
category_theory.category.mk
protected instance category_theory.concrete_category (R : Type u) [comm_ring R] :
category_theory.concrete_category (Algebra R) :=
category_theory.concrete_category.mk
(category_theory.functor.mk (fun (R_1 : Algebra R) => ↥R_1)
fun (R_1 S : Algebra R) (f : R_1 ⟶ S) => ⇑f)
protected instance has_forget_to_Ring (R : Type u) [comm_ring R] :
category_theory.has_forget₂ (Algebra R) Ring :=
category_theory.has_forget₂.mk
(category_theory.functor.mk (fun (A : Algebra R) => Ring.of ↥A)
fun (A₁ A₂ : Algebra R) (f : A₁ ⟶ A₂) => alg_hom.to_ring_hom f)
protected instance has_forget_to_Module (R : Type u) [comm_ring R] :
category_theory.has_forget₂ (Algebra R) (Module R) :=
category_theory.has_forget₂.mk
(category_theory.functor.mk (fun (M : Algebra R) => Module.of R ↥M)
fun (M₁ M₂ : Algebra R) (f : M₁ ⟶ M₂) => alg_hom.to_linear_map f)
/-- The object in the category of R-algebras associated to a type equipped with the appropriate
typeclasses. -/
def of (R : Type u) [comm_ring R] (X : Type v) [ring X] [algebra R X] : Algebra R := mk X
protected instance inhabited (R : Type u) [comm_ring R] : Inhabited (Algebra R) :=
{ default := of R R }
@[simp] theorem coe_of (R : Type u) [comm_ring R] (X : Type u) [ring X] [algebra R X] :
↥(of R X) = X :=
rfl
/-- Forgetting to the underlying type and then building the bundled object returns the original
algebra. -/
@[simp] theorem of_self_iso_hom {R : Type u} [comm_ring R] (M : Algebra R) :
category_theory.iso.hom (of_self_iso M) = 𝟙 :=
Eq.refl (category_theory.iso.hom (of_self_iso M))
@[simp] theorem id_apply {R : Type u} [comm_ring R] {M : Module R} (m : ↥M) : coe_fn 𝟙 m = m := rfl
@[simp] theorem coe_comp {R : Type u} [comm_ring R] {M : Module R} {N : Module R} {U : Module R}
(f : M ⟶ N) (g : N ⟶ U) : ⇑(f ≫ g) = ⇑g ∘ ⇑f :=
rfl
/-- The "free algebra" functor, sending a type `S` to the free algebra on `S`. -/
@[simp] theorem free_obj_is_algebra (R : Type u) [comm_ring R] (S : Type u_1) :
is_algebra (category_theory.functor.obj (free R) S) = free_algebra.algebra R S :=
Eq.refl (is_algebra (category_theory.functor.obj (free R) S))
/-- The free/forget ajunction for `R`-algebras. -/
def adj (R : Type u) [comm_ring R] : free R ⊣ category_theory.forget (Algebra R) :=
category_theory.adjunction.mk_of_hom_equiv
(category_theory.adjunction.core_hom_equiv.mk
fun (X : Type (max u u_1)) (A : Algebra R) => equiv.symm (free_algebra.lift R))
end Algebra
/-- Build an isomorphism in the category `Algebra R` from a `alg_equiv` between `algebra`s. -/
@[simp] theorem alg_equiv.to_Algebra_iso_hom {R : Type u} [comm_ring R] {X₁ : Type u} {X₂ : Type u}
{g₁ : ring X₁} {g₂ : ring X₂} {m₁ : algebra R X₁} {m₂ : algebra R X₂} (e : alg_equiv R X₁ X₂) :
category_theory.iso.hom (alg_equiv.to_Algebra_iso e) = ↑e :=
Eq.refl (category_theory.iso.hom (alg_equiv.to_Algebra_iso e))
namespace category_theory.iso
/-- Build a `alg_equiv` from an isomorphism in the category `Algebra R`. -/
@[simp] theorem to_alg_equiv_apply {R : Type u} [comm_ring R] {X : Algebra R} {Y : Algebra R}
(i : X ≅ Y) : ∀ (ᾰ : ↥X), coe_fn (to_alg_equiv i) ᾰ = coe_fn (hom i) ᾰ :=
fun (ᾰ : ↥X) => Eq.refl (coe_fn (to_alg_equiv i) ᾰ)
end category_theory.iso
/-- Algebra equivalences between `algebras`s are the same as (isomorphic to) isomorphisms in
`Algebra`. -/
def alg_equiv_iso_Algebra_iso {R : Type u} [comm_ring R] {X : Type u} {Y : Type u} [ring X] [ring Y]
[algebra R X] [algebra R Y] : alg_equiv R X Y ≅ Algebra.of R X ≅ Algebra.of R Y :=
category_theory.iso.mk (fun (e : alg_equiv R X Y) => alg_equiv.to_Algebra_iso e)
fun (i : Algebra.of R X ≅ Algebra.of R Y) => category_theory.iso.to_alg_equiv i
protected instance Algebra.has_coe {R : Type u} [comm_ring R] (X : Type u) [ring X] [algebra R X] :
has_coe (subalgebra R X) (Algebra R) :=
has_coe.mk fun (N : subalgebra R X) => Algebra.of R ↥N
protected instance Algebra.forget_reflects_isos {R : Type u} [comm_ring R] :
category_theory.reflects_isomorphisms (category_theory.forget (Algebra R)) :=
category_theory.reflects_isomorphisms.mk
fun (X Y : Algebra R) (f : X ⟶ Y)
(_x :
category_theory.is_iso
(category_theory.functor.map (category_theory.forget (Algebra R)) f)) =>
let i :
category_theory.functor.obj (category_theory.forget (Algebra R)) X ≅
category_theory.functor.obj (category_theory.forget (Algebra R)) Y :=
category_theory.as_iso (category_theory.functor.map (category_theory.forget (Algebra R)) f);
let e : alg_equiv R ↥X ↥Y :=
alg_equiv.mk (alg_hom.to_fun f) (equiv.inv_fun (category_theory.iso.to_equiv i)) sorry sorry
sorry sorry sorry;
category_theory.is_iso.mk (category_theory.iso.inv (alg_equiv.to_Algebra_iso e))
end Mathlib |
8a72b4ff36f6a3d90d68ae1ec4abaacf02bd8e66 | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /hott/algebra/category/limits/functor.hlean | 94d3d9a9e801776bebe697d92db5367d34aab401 | [
"Apache-2.0"
] | permissive | jroesch/lean | 30ef0860fa905d35b9ad6f76de1a4f65c9af6871 | 3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2 | refs/heads/master | 1,586,090,835,348 | 1,455,142,203,000 | 1,455,142,277,000 | 51,536,958 | 1 | 0 | null | 1,455,215,811,000 | 1,455,215,811,000 | null | UTF-8 | Lean | false | false | 6,640 | 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, Jakob von Raumer
Functor category has (co)limits if the codomain has them
-/
import .colimits
open functor nat_trans eq is_trunc
namespace category
-- preservation of limits
variables {D C I : Precategory}
definition functor_limit_object [constructor]
[H : has_limits_of_shape D I] (F : I ⇒ D ^c C) : C ⇒ D :=
begin
assert lem : Π(c d : carrier C) (f : hom c d) ⦃i j : carrier I⦄ (k : i ⟶ j),
(constant2_functor F d) k ∘ to_fun_hom (F i) f ∘ limit_morphism (constant2_functor F c) i =
to_fun_hom (F j) f ∘ limit_morphism (constant2_functor F c) j,
{ intro c d f i j k, rewrite [-limit_commute _ k,▸*,+assoc,▸*,-naturality (F k) f]},
fapply functor.mk,
{ intro c, exact limit_object (constant2_functor F c)},
{ intro c d f, fapply hom_limit,
{ intro i, refine to_fun_hom (F i) f ∘ !limit_morphism},
{ apply lem}},
{ exact abstract begin intro c, symmetry, apply eq_hom_limit, intro i,
rewrite [id_right,respect_id,▸*,id_left] end end},
{ intro a b c g f, symmetry, apply eq_hom_limit, intro i, -- report: adding abstract fails here
rewrite [respect_comp,assoc,hom_limit_commute,-assoc,hom_limit_commute,assoc]}
end
definition functor_limit_cone [constructor]
[H : has_limits_of_shape D I] (F : I ⇒ D ^c C) : cone_obj F :=
begin
fapply cone_obj.mk,
{ exact functor_limit_object F},
{ fapply nat_trans.mk,
{ intro i, esimp, fapply nat_trans.mk,
{ intro c, esimp, apply limit_morphism},
{ intro c d f, rewrite [▸*,hom_limit_commute (constant2_functor F d)]}},
{ intro i j k, apply nat_trans_eq, intro c,
rewrite [▸*,id_right,limit_commute (constant2_functor F c)]}}
end
variables (D C I)
definition has_limits_of_shape_functor [instance] [H : has_limits_of_shape D I]
: has_limits_of_shape (D ^c C) I :=
begin
intro F, fapply has_terminal_object.mk,
{ exact functor_limit_cone F},
{ intro c, esimp at *, induction c with G η, induction η with η p, esimp at *,
fapply is_contr.mk,
{ fapply cone_hom.mk,
{ fapply nat_trans.mk,
{ intro c, esimp, fapply hom_limit,
{ intro i, esimp, exact η i c},
{ intro i j k, esimp, exact ap010 natural_map (p k) c ⬝ !id_right}},
{ intro c d f, esimp, fapply @limit_cone_unique,
{ intro i, esimp, exact to_fun_hom (F i) f ∘ η i c},
{ intro i j k, rewrite [▸*,assoc,-naturality,-assoc,-compose_def,p k,▸*,id_right]},
{ intro i, rewrite [assoc, hom_limit_commute (constant2_functor F d),▸*,-assoc,
hom_limit_commute]},
{ intro i, rewrite [assoc, hom_limit_commute (constant2_functor F d),naturality]}}},
{ intro i, apply nat_trans_eq, intro c,
rewrite [▸*,hom_limit_commute (constant2_functor F c)]}},
{ intro h, induction h with f q, apply cone_hom_eq,
apply nat_trans_eq, intro c, esimp at *, symmetry,
apply eq_hom_limit, intro i, exact ap010 natural_map (q i) c}}
end
definition is_complete_functor [instance] [H : is_complete D] : is_complete (D ^c C) :=
λI, _
variables {D C I}
-- preservation of colimits
-- definition constant2_functor_op [constructor] (F : I ⇒ (D ^c C)ᵒᵖ) (c : C) : I ⇒ D :=
-- proof
-- functor.mk (λi, to_fun_ob (F i) c)
-- (λi j f, natural_map (F f) c)
-- abstract (λi, ap010 natural_map !respect_id c ⬝ proof idp qed) end
-- abstract (λi j k g f, ap010 natural_map !respect_comp c) end
-- qed
definition functor_colimit_object [constructor]
[H : has_colimits_of_shape D I] (F : Iᵒᵖ ⇒ (D ^c C)ᵒᵖ) : C ⇒ D :=
begin
fapply functor.mk,
{ intro c, exact colimit_object (constant2_functor Fᵒᵖ' c)},
{ intro c d f, apply colimit_hom_colimit, apply constant2_functor_natural _ f},
{ exact abstract begin intro c, symmetry, apply eq_colimit_hom, intro i,
rewrite [id_left,▸*,respect_id,id_right] end end},
{ intro a b c g f, symmetry, apply eq_colimit_hom, intro i, -- report: adding abstract fails here
rewrite [▸*,respect_comp,-assoc,colimit_hom_commute,assoc,colimit_hom_commute,-assoc]}
end
definition functor_colimit_cone [constructor]
[H : has_colimits_of_shape D I] (F : Iᵒᵖ ⇒ (D ^c C)ᵒᵖ) : cone_obj F :=
begin
fapply cone_obj.mk,
{ exact functor_colimit_object F},
{ fapply nat_trans.mk,
{ intro i, esimp, fapply nat_trans.mk,
{ intro c, esimp, apply colimit_morphism},
{ intro c d f, apply colimit_hom_commute (constant2_functor Fᵒᵖ' c)}},
{ intro i j k, apply nat_trans_eq, intro c,
rewrite [▸*,id_left], apply colimit_commute (constant2_functor Fᵒᵖ' c)}}
end
variables (D C I)
definition has_colimits_of_shape_functor [instance] [H : has_colimits_of_shape D I]
: has_colimits_of_shape (D ^c C) I :=
begin
intro F, fapply has_terminal_object.mk,
{ exact functor_colimit_cone F},
{ intro c, esimp at *, induction c with G η, induction η with η p, esimp at *,
fapply is_contr.mk,
{ fapply cone_hom.mk,
{ fapply nat_trans.mk,
{ intro c, esimp, fapply colimit_hom,
{ intro i, esimp, exact η i c},
{ intro i j k, esimp, exact ap010 natural_map (p k) c ⬝ !id_left}},
{ intro c d f, esimp, fapply @colimit_cocone_unique,
{ intro i, esimp, exact η i d ∘ to_fun_hom (F i) f},
{ intro i j k, rewrite [▸*,-assoc,naturality,assoc,-compose_def,p k,▸*,id_left]},
{ intro i, rewrite [-assoc, colimit_hom_commute (constant2_functor Fᵒᵖ' c),
▸*, naturality]},
{ intro i, rewrite [-assoc, colimit_hom_commute (constant2_functor Fᵒᵖ' c),▸*,assoc,
colimit_hom_commute (constant2_functor Fᵒᵖ' d)]}}},
{ intro i, apply nat_trans_eq, intro c,
rewrite [▸*,colimit_hom_commute (constant2_functor Fᵒᵖ' c)]}},
{ intro h, induction h with f q, apply cone_hom_eq,
apply nat_trans_eq, intro c, esimp at *, symmetry,
apply eq_colimit_hom, intro i, exact ap010 natural_map (q i) c}}
end
local attribute has_limits_of_shape_op_op [instance] [priority 1]
universe variables u v
definition is_cocomplete_functor [instance] [H : is_cocomplete.{_ _ u v} D]
: is_cocomplete.{_ _ u v} (D ^c C) :=
λI, _
end category
|
13a6d08dfe37a84c093d1630f25e923dea70315f | 5f83eb0c32f15aeed5993a3ad5ededb6f31fe7aa | /lean/src/bv/lemmas.lean | 44ac7cb7d54d85474a78d24bbe1849281c13ad9a | [] | no_license | uw-unsat/jitterbug | 45b54979b156c0f5330012313052f8594abd6f14 | 78d1e75ad506498b585fbac66985ff9d9d05952d | refs/heads/master | 1,689,066,921,433 | 1,687,061,448,000 | 1,688,415,161,000 | 244,440,882 | 46 | 5 | null | null | null | null | UTF-8 | Lean | false | false | 20,943 | lean |
import .basic
import .helper
import data.list.of_fn
namespace bv
open nat
open bv.helper
section fin
variable {n : ℕ}
@[simp]
lemma lsb_cons (b : bool) (v : bv n) : (cons b v).lsb = b :=
fin.cons_zero _ _
@[simp]
lemma tail_cons (b : bool) (v : bv n) : (cons b v).tail = v :=
fin.tail_cons _ _
@[simp]
lemma cons_lsb_tail (v : bv (n + 1)) : cons v.lsb v.tail = v :=
fin.cons_self_tail _
@[simp]
lemma msb_snoc (v : bv n) (b : bool) : (snoc v b).msb = b :=
fin.snoc_last _ _
@[simp]
lemma init_snoc (v : bv n) (b : bool) : (snoc v b).init = v :=
fin.init_snoc _ _
@[simp]
lemma snoc_init_msb (v : bv (n + 1)) : snoc v.init v.msb = v :=
fin.snoc_init_self _
lemma cons_snoc_eq_snoc_cons (b₁ : bool) (v : bv n) (b₂ : bool) :
cons b₁ (snoc v b₂) = snoc (cons b₁ v) b₂ :=
fin.cons_snoc_eq_snoc_cons _ _ _
end fin
section list
variable {n : ℕ}
@[norm_cast, simp]
lemma nil_to_list (v : bv 0) : (v : list bool) = [] := rfl
@[norm_cast]
lemma cons_to_list (b : bool) (v : bv n) :
(cons b v : list bool) = b :: (v : list bool) :=
by unfold_coes; simp [to_list, cons, list.of_fn_succ]
@[norm_cast]
lemma snoc_to_list : ∀ {n : ℕ} (v : bv n) (b : bool),
(snoc v b : list bool) = (v : list bool) ++ [b]
| 0 _ _ := rfl
| (n + 1) v b := calc (v.snoc b : list bool)
= (cons v.lsb (snoc v.tail b) : list bool) : by simp [cons_snoc_eq_snoc_cons]
... = (v.lsb :: v.tail : list bool) ++ [b] : by push_cast; simp [snoc_to_list]
... = (v : list bool) ++ [b] : by { norm_cast; simp }
@[simp]
lemma to_list_length {n : ℕ} (v : bv n) :
(v : list bool).length = n :=
list.length_of_fn v
@[norm_cast]
lemma to_list_nth_le {n : ℕ} {v : bv n} (i : ℕ) (h h') :
(v : list bool).nth_le i h' = v ⟨i, h⟩ :=
list.nth_le_of_fn' v h'
@[norm_cast]
theorem to_list_inj (v₁ v₂ : bv n) :
(v₁ : list bool) = (v₂ : list bool) ↔ v₁ = v₂ :=
begin
split; intro h; try { cc },
ext ⟨i, _⟩,
rw [← @to_list_nth_le _ v₁, ← @to_list_nth_le _ v₂]; try { simpa },
congr, cc
end
@[ext]
lemma heq_ext {n₁ n₂ : ℕ} (h : n₁ = n₂) {v₁ : bv n₁} {v₂ : bv n₂} :
(∀ (i : fin n₁), v₁ i = v₂ ⟨i.val, h ▸ i.2⟩) → v₁ == v₂ :=
by simp [fin.heq_fun_iff h]
theorem heq_iff_to_list {n₁ n₂ : ℕ} (h : n₁ = n₂) {v₁ : bv n₁} {v₂ : bv n₂} :
v₁ == v₂ ↔ (v₁ : list bool) = (v₂ : list bool) :=
by induction h; simp [heq_iff_eq, to_list_inj]
end list
section nat
variable {n : ℕ}
@[norm_cast, simp]
lemma nil_to_nat (v : bv 0) : (v : ℕ) = 0 := rfl
@[norm_cast]
lemma cons_to_nat (b : bool) (v : bv n) :
(cons b v : ℕ) = nat.bit b (v : ℕ) :=
by unfold_coes; simp [to_nat]
lemma to_nat_of_lsb_tail (v : bv (n + 1)) :
(v : ℕ) = nat.bit v.lsb (v.tail : ℕ) := rfl
@[norm_cast]
lemma snoc_to_nat : ∀ {n : ℕ} (v : bv n) (b : bool),
(snoc v b : ℕ) = (v : ℕ) + 2^n * cond b 1 0
| 0 _ b := by cases b; refl
| (n + 1) v b := calc (snoc v b : ℕ)
= (cons v.lsb (snoc v.tail b) : ℕ) : by simp [cons_snoc_eq_snoc_cons]
... = 2 * (snoc v.tail b : ℕ) + cond v.lsb 1 0 : by push_cast [bit_val]
... = 2 * (v.tail : ℕ) + cond v.lsb 1 0 + 2^(n + 1) * cond b 1 0 : by rw snoc_to_nat; ring_exp
... = (v : ℕ) + 2^(n + 1) * cond b 1 0 : by rw ← bit_val; norm_cast; simp
lemma to_nat_le : ∀ {n : ℕ} (v : bv n),
(v : ℕ) ≤ 2^n - 1
| 0 _ := by refl
| (n + 1) v := calc (v : ℕ)
= (v.init : ℕ) + 2^n * cond v.msb 1 0 : by norm_cast; simp
... ≤ 2^n - 1 + 2^n * cond v.msb 1 0 : by mono
... ≤ 2^n - 1 + 2^n : by simp only [add_le_add_iff_left, mul_le_iff_le_one_right]; cases v.msb; simp
... = 2^(n + 1) - 1 : by rw ← nat.sub_add_comm (pow2_pos _); ring_exp
lemma to_nat_lt (v : bv n) :
(v : ℕ) < 2^n :=
calc v.to_nat
≤ 2^n - 1 : to_nat_le _
... < 2^n : nat.sub_lt (pow2_pos _) nat.one_pos
@[simp]
lemma to_nat_mod_eq (v : bv n) :
(v : ℕ) % 2^n = (v : ℕ) :=
by { apply mod_eq_of_lt, apply to_nat_lt }
@[norm_cast]
lemma to_of_nat : ∀ (n a : ℕ),
(@of_nat n a : ℕ) = a % 2^n
| 0 _ := by simp [of_nat]
| (n + 1) a := calc (@of_nat (n + 1) a : ℕ)
= bit a.bodd ↑(@of_nat n a.div2) : by norm_cast
... = bit a.bodd (a.div2 % 2^n) : by rw to_of_nat
... = 2 * (a / 2 % 2^n) + a % 2 : by rw [bit_val, div2_val, mod_two_of_bodd]
... = a % 2^(n + 1) : by rw nat.mod_pow_succ
@[simp]
lemma of_to_nat : ∀ {n : ℕ} (v : bv n),
bv.of_nat (v : ℕ) = v
| 0 _ := dec_trivial
| (n + 1) v := calc of_nat (v : ℕ)
= of_nat (cons v.lsb v.tail : ℕ) : by simp
... = v : by push_cast; rw [of_nat, nat.bodd_bit, nat.div2_bit]; simp [of_to_nat]
@[norm_cast]
theorem to_nat_inj (v₁ v₂ : bv n) :
(v₁ : ℕ) = (v₂ : ℕ) ↔ v₁ = v₂ :=
⟨λ h, function.left_inverse.injective of_to_nat h, congr_arg _⟩
lemma to_int_mod_eq (v : bv n) :
v.to_int % 2^n = (v : ℕ) :=
begin
simp [to_int],
cases decidable.em ((v : ℕ) < 2^(n - 1)) with h h; simp [h, int.sub_mod_self];
norm_cast; simp; congr
end
lemma of_to_int (v : bv n) :
bv.of_int v.to_int = v :=
by simp [of_int, to_int_mod_eq]
theorem to_int_inj (v₁ v₂ : bv n) :
v₁.to_int = v₂.to_int ↔ v₁ = v₂ :=
⟨λ h, function.left_inverse.injective of_to_int h, congr_arg _⟩
lemma msb_eq_ff_iff (v : bv (n + 1)) :
v.msb = ff ↔ (v : ℕ) < 2^n :=
begin
rw [← snoc_init_msb v],
push_cast,
cases v.msb; simp,
apply to_nat_lt
end
end nat
section literals
variable {n : ℕ}
@[norm_cast, simp]
lemma zero_to_nat : ∀ {n : ℕ}, ((0 : bv n) : ℕ) = 0
| 0 := rfl
| (n + 1) := calc ((0 : bv (n + 1)) : ℕ)
= (cons ff (0 : bv n) : ℕ) : by push_cast; refl
... = 0 : by push_cast; simpa [zero_to_nat]
@[norm_cast]
lemma umax_to_nat : ∀ {n : ℕ}, ((bv.umax : bv n) : ℕ) = 2^n - 1
| 0 := rfl
| (n + 1) := calc ((bv.umax : bv (n + 1)) : ℕ)
= ((cons tt (bv.umax : bv n)) : ℕ) : by push_cast; refl
... = 2 * (2^n - 1 + 1) - 1: by push_cast [bit_val, umax_to_nat]; ring_nf
... = 2^(n + 1) - 1 : by rw [nat.sub_add_cancel (pow2_pos _)]; ring_exp
@[norm_cast, simp]
lemma one_to_nat : ((1 : bv (n + 1)) : ℕ) = 1 :=
calc ((1 : bv (n + 1)) : ℕ)
= ((cons tt (0 : bv n)) : ℕ) : rfl
... = 1: by push_cast; simp [bit_val]
@[norm_cast]
lemma smin_to_nat : ((bv.smin : bv (n + 1)) : ℕ) = 2^n :=
calc ((bv.smin : bv (n + 1)) : ℕ)
= ((snoc (0 : bv n) tt) : ℕ) : rfl
... = 2^n : by push_cast; simp
@[norm_cast]
lemma smax_to_nat : ((bv.smax : bv (n + 1)) : ℕ) = 2^n - 1 :=
calc ((bv.smax : bv (n + 1)) : ℕ)
= ((snoc (bv.umax : bv n) ff) : ℕ) : rfl
... = 2^n - 1 : by push_cast; simp
end literals
section concatenation
@[norm_cast]
lemma concat_to_list {n₁ n₂ : ℕ} (v₁ : bv n₁) (v₂ : bv n₂) :
(concat v₁ v₂ : list bool) = ↑v₂ ++ ↑v₁ :=
begin
apply list.ext_le,
{ simp [add_comm] },
{ intros i h₁ h₂,
simp at h₁ h₂,
rw to_list_nth_le _ h₁,
cases decidable.em (i < n₂) with hlt hlt; simp [hlt, concat],
{ rw [list.nth_le_append, to_list_nth_le]; simpa },
{ rw [list.nth_le_append_right, to_list_nth_le]; simp; omega } }
end
lemma concat_nil {n₁ : ℕ} (v₁ : bv n₁) (v₂ : bv 0) :
v₁.concat v₂ = v₁ :=
by push_cast [← to_list_inj]; simp
lemma concat_cons {n₁ n₂ : ℕ} (v₁ : bv n₁) (b : bool) (v₂ : bv n₂) :
v₁.concat (cons b v₂) = cons b (v₁.concat v₂) :=
by push_cast [← to_list_inj]; simp
@[norm_cast]
lemma concat_to_nat : ∀ {n₁ n₂ : ℕ} (v₁ : bv n₁) (v₂ : bv n₂),
(concat v₁ v₂ : ℕ) = v₁ * 2^n₂ + v₂
| _ 0 _ _ := by simp [concat_nil]
| _ (n₂ + 1) v₁ v₂ := calc (v₁.concat v₂ : ℕ)
= ↑(v₁.concat (cons v₂.lsb v₂.tail)) : by simp
... = ↑(cons v₂.lsb (v₁.concat v₂.tail)) : by rw concat_cons
... = v₁ * 2^(n₂ + 1) + ↑(cons v₂.lsb v₂.tail) : by push_cast [bit_val, concat_to_nat]; ring_exp
... = v₁ * 2^(n₂ + 1) + v₂ : by simp
@[simp]
lemma zero_extend_to_nat (i : ℕ) {n : ℕ} (v : bv n) :
(v.zero_extend i : ℕ) = v :=
by dsimp [zero_extend]; push_cast; simp
end concatenation
section extraction
variables {n₁ n₂ : ℕ}
@[norm_cast]
lemma extract_to_list {n : ℕ} (i j : ℕ) (h₁ : i < n) (h₂ : j ≤ i) (v : bv n) :
(v.extract i j h₁ h₂ : list bool) = ((v : list bool).take (i + 1)).drop j :=
begin
apply list.ext_le,
{ simp, rw min_eq_left; omega },
{ intros,
rw [← list.nth_le_drop, ← list.nth_le_take],
repeat { rw to_list_nth_le },
simp [extract], all_goals { simp at *; omega } }
end
@[norm_cast]
lemma drop_to_list (v : bv (n₁ + n₂)) :
(v.drop n₂ : list bool) = (v : list bool).drop n₂ :=
begin
apply list.ext_le,
{ simp },
{ intros,
rw ← list.nth_le_drop,
repeat { rw to_list_nth_le },
simp [drop], all_goals { simp at *; omega } }
end
@[norm_cast]
lemma take_to_list (v : bv (n₁ + n₂)) :
(v.take n₂ : list bool) = (v : list bool).take n₂ :=
begin
apply list.ext_le,
{ simp },
{ intros,
rw ← list.nth_le_take,
repeat { rw to_list_nth_le },
simp [take], all_goals { simp at *; omega } }
end
lemma drop_zero {n : ℕ} (v : bv n) :
drop 0 v = v :=
by push_cast [← to_list_inj]; simp
lemma drop_cons {n₁ n₂ : ℕ} (b : bool) (v : bv (n₁ + n₂)) :
drop (n₂ + 1) (cons b v) = drop n₂ v :=
by push_cast [← to_list_inj]; simp
@[norm_cast]
lemma drop_to_nat : ∀ {n₁ n₂ : ℕ} (v : bv (n₁ + n₂)),
(drop n₂ v : ℕ) = (v : ℕ) / 2^n₂
| _ 0 _ := by simp [drop_zero]
| _ (n₂ + 1) v := by
{ rw [← cons_lsb_tail v, drop_cons, drop_to_nat],
push_cast,
simp [pow2_succ, ← nat.div_div_eq_div_mul] }
lemma take_zero {n : ℕ} (v : bv n) :
take 0 v = nil :=
dec_trivial
lemma take_cons {n₁ n₂ : ℕ} (b : bool) (v : bv (n₁ + n₂)) :
take (n₂ + 1) (cons b v) = cons b (take n₂ v) :=
by push_cast [← to_list_inj]; simp
@[norm_cast]
lemma take_to_nat : ∀ {n₁ n₂ : ℕ} (v : bv (n₁ + n₂)),
(take n₂ v : ℕ) = (v : ℕ) % 2^n₂
| _ 0 _ := by simp [take_zero]
| _ (n₂ + 1) v := by
{ rw [← cons_lsb_tail v, take_cons],
push_cast,
simp [take_to_nat, mod_pow_succ, ← bit_val] }
lemma concat_drop_take {n₁ n₂ : ℕ} (v : bv (n₁ + n₂)) :
concat (drop n₂ v) (take n₂ v) = v :=
by push_cast [← to_list_inj]; simp [list.take_append_drop]
lemma drop_concat {n₁ n₂ : ℕ} (v₁ : bv n₁) (v₂ : bv n₂) :
drop n₂ (concat v₁ v₂) = v₁ :=
by push_cast [← to_list_inj]; simp [list.drop_left']
lemma take_concat {n₁ n₂ : ℕ} (v₁ : bv n₁) (v₂ : bv n₂) :
take n₂ (concat v₁ v₂) = v₂ :=
by push_cast [← to_list_inj]; simp [list.take_left']
end extraction
section bitwise
variable {n : ℕ}
@[norm_cast]
lemma not_to_nat (v : bv n) :
(v.not : ℕ) = 2^n - 1 - v :=
begin
apply symm,
rw [nat.sub_eq_iff_eq_add (to_nat_le _),
nat.sub_eq_iff_eq_add (pow2_pos _)],
apply symm,
induction n with n ih; try { refl },
calc (v.not : ℕ) + v + 1
= bit (!v.lsb) v.tail.not + bit v.lsb v.tail + 1 : rfl
... = 2 * (v.tail.not + v.tail + 1) : by cases v.lsb; simp [bit_val]; ring
... = 2^(n + 1) : by rw ih; ring_exp
end
@[norm_cast]
lemma map₂_to_nat {f : bool → bool → bool} (h : f ff ff = ff) : ∀ {n : ℕ} (v₁ v₂ : bv n),
(map₂ f v₁ v₂ : ℕ) = nat.bitwise f ↑v₁ ↑v₂
| 0 _ _ := by simp
| (n + 1) v₁ v₂ := calc ↑(map₂ f v₁ v₂)
= nat.bit (f v₁.lsb v₂.lsb) ↑(map₂ f v₁.tail v₂.tail) : rfl
... = nat.bitwise f (nat.bit v₁.lsb ↑(v₁.tail)) (nat.bit v₂.lsb ↑(v₂.tail)) : by rw [map₂_to_nat, nat.bitwise_bit h]
... = nat.bitwise f ↑v₁ ↑v₂ : by norm_cast; simp
@[norm_cast]
lemma and_to_nat : ∀ (v₁ v₂ : bv n),
(v₁.and v₂ : ℕ) = nat.land ↑v₁ ↑v₂ := map₂_to_nat rfl
@[norm_cast]
lemma or_to_nat : ∀ (v₁ v₂ : bv n),
(v₁.or v₂ : ℕ) = nat.lor ↑v₁ ↑v₂ := map₂_to_nat rfl
@[norm_cast]
lemma xor_to_nat : ∀ (v₁ v₂ : bv n),
(v₁.xor v₂ : ℕ) = nat.lxor ↑v₁ ↑v₂ := map₂_to_nat rfl
end bitwise
section arithmetic
variable {n : ℕ}
@[norm_cast]
lemma neg_to_nat (v : bv n) :
(((-v) : bv n) : ℕ) = if (v : ℕ) = 0 then 0 else 2^n - v :=
begin
have h : -v = bv.neg v := rfl,
push_cast [h, bv.neg],
cases eq.decidable (v : ℕ) 0 with h h; simp [h],
apply mod_eq_of_lt,
apply nat.sub_lt (pow2_pos _) (nat.pos_of_ne_zero h)
end
@[norm_cast]
lemma add_to_nat (v₁ v₂ : bv n) :
((v₁ + v₂ : bv n) : ℕ) = ((v₁ : ℕ) + (v₂ : ℕ)) % 2^n :=
begin
have h : v₁ + v₂ = bv.add v₁ v₂ := rfl,
push_cast [h, bv.add]
end
@[norm_cast]
lemma sub_to_nat (v₁ v₂ : bv n) :
((v₁ - v₂ : bv n) : ℕ) = if (v₂ : ℕ) ≤ (v₁ : ℕ) then (v₁ : ℕ) - (v₂ : ℕ) else 2^n + (v₁ : ℕ) - (v₂ : ℕ) :=
begin
have h : v₁ - v₂ = v₁ + -v₂ := rfl,
push_cast [h],
cases eq.decidable (v₂ : ℕ) 0 with hz hz; simp [hz],
rw [← nat.add_sub_assoc (le_of_lt (to_nat_lt _)), add_comm],
have h₁ := to_nat_lt v₁,
have h₂ := to_nat_lt v₂,
cases decidable.em ((v₂ : ℕ) ≤ (v₁ : ℕ)) with hcmp hcmp; simp [hcmp],
{ rw nat.add_sub_assoc hcmp,
rw add_mod_left,
apply mod_eq_of_lt,
omega },
{ apply mod_eq_of_lt,
omega }
end
@[norm_cast]
lemma mul_to_nat (v₁ v₂ : bv n) :
((v₁ * v₂ : bv n) : ℕ) = ((v₁ : ℕ) * (v₂ : ℕ)) % 2^n :=
begin
have h : v₁ * v₂ = bv.mul v₁ v₂ := rfl,
push_cast [h, bv.mul]
end
-- note that a % 0 = 0 for nat (rather than 2^n - 1)
@[norm_cast]
lemma udiv_to_nat (v₁ v₂ : bv n) :
((v₁ / v₂ : bv n) : ℕ) = if (v₂ : ℕ) = 0 then 2^n - 1 else (v₁ / v₂ : ℕ) :=
begin
have h : v₁ / v₂ = bv.udiv v₁ v₂ := rfl,
push_cast [h, bv.udiv],
cases nat.decidable_eq (v₂ : ℕ) 0 with h h; simp [h],
apply mod_eq_of_lt,
apply lt_of_le_of_lt (nat.div_le_self _ _) (to_nat_lt _)
end
-- drop the zero case as a % 0 = a for nat
@[norm_cast]
lemma urem_to_nat (v₁ v₂ : bv n) :
((v₁ % v₂ : bv n) : ℕ) = (v₁ % v₂ : ℕ) :=
begin
have h : v₁ % v₂ = bv.urem v₁ v₂ := rfl,
push_cast [h, bv.urem],
cases nat.decidable_eq (v₂ : ℕ) 0 with h h; simp [h],
apply mod_eq_of_lt,
apply lt_of_le_of_lt (mod_le _ _) (to_nat_lt _)
end
theorem urem_add_udiv (v₁ v₂ : bv n) :
v₁ % v₂ + v₂ * (v₁ / v₂) = v₁ :=
begin
push_cast [← to_nat_inj],
cases nat.decidable_eq (v₂ : ℕ) 0 with h h; simp [h],
simp [nat.mod_add_div]
end
end arithmetic
section ring
variable {n : ℕ}
protected lemma add_comm (v₁ v₂ : bv n) : v₁ + v₂ = v₂ + v₁ :=
by push_cast [← to_nat_inj, add_comm]
protected lemma add_zero (v : bv n) : v + 0 = v :=
by push_cast [← to_nat_inj]; simp
protected lemma zero_add (v : bv n) : 0 + v = v :=
bv.add_comm v 0 ▸ bv.add_zero v
protected lemma add_assoc (v₁ v₂ v₃ : bv n) : v₁ + v₂ + v₃ = v₁ + (v₂ + v₃) :=
by push_cast [← to_nat_inj]; simp [add_assoc]
protected lemma add_left_neg (v : bv n) : -v + v = 0 :=
begin
push_cast [← to_nat_inj],
cases eq.decidable (v : ℕ) 0 with h h; simp [h],
rw nat.sub_add_cancel,
{ simp [mod_self] },
{ apply le_of_lt (to_nat_lt _) }
end
protected lemma mul_comm (v₁ v₂ : bv n) : v₁ * v₂ = v₂ * v₁ :=
by push_cast [← to_nat_inj, mul_comm]
protected lemma mul_one (v : bv n) : v * 1 = v :=
by cases n; push_cast [← to_nat_inj]; simp
protected lemma one_mul (v : bv n) : 1 * v = v :=
bv.mul_comm v 1 ▸ bv.mul_one v
protected lemma mul_assoc (v₁ v₂ v₃ : bv n) : v₁ * v₂ * v₃ = v₁ * (v₂ * v₃) :=
begin
push_cast [← to_nat_inj],
conv_lhs { rw [mul_mod, mod_mod, ← mul_mod] },
conv_rhs { rw [mul_mod, mod_mod, ← mul_mod] },
rw mul_assoc
end
protected lemma distrib_left (v₁ v₂ v₃ : bv n) : v₁ * (v₂ + v₃) = v₁ * v₂ + v₁ * v₃ :=
begin
push_cast [← to_nat_inj],
conv_lhs { rw [mul_mod, mod_mod, ← mul_mod] },
simp [nat.left_distrib]
end
protected lemma distrib_right (v₁ v₂ v₃ : bv n) : (v₁ + v₂) * v₃ = v₁ * v₃ + v₂ * v₃ :=
begin
rw [bv.mul_comm, bv.distrib_left],
simp [bv.mul_comm]
end
instance : comm_ring (bv n) :=
{ add := bv.add,
add_comm := bv.add_comm,
add_assoc := bv.add_assoc,
zero := 0,
zero_add := bv.zero_add,
add_zero := bv.add_zero,
neg := bv.neg,
add_left_neg := bv.add_left_neg,
mul := bv.mul,
mul_comm := bv.mul_comm,
mul_assoc := bv.mul_assoc,
one := 1,
one_mul := bv.one_mul,
mul_one := bv.mul_one,
left_distrib := bv.distrib_left,
right_distrib := bv.distrib_right }
end ring
section bitwise
variable {n : ℕ}
@[norm_cast]
lemma shl_to_nat (v₁ v₂ : bv n) :
(v₁.shl v₂ : ℕ) = (v₁ : ℕ) * (2^(v₂ : ℕ)) % 2^n :=
by push_cast [shl]
lemma shl_above (v₁ v₂ : bv n) (h : n ≤ v₂.to_nat) :
v₁.shl v₂ = 0 :=
begin
push_cast [← to_nat_inj],
apply mod_eq_zero_of_dvd,
apply dvd_trans _ (dvd_mul_left _ _),
apply pow_dvd_pow _ h
end
@[norm_cast]
lemma lshr_to_nat (v₁ v₂ : bv n) :
(v₁.lshr v₂ : ℕ) = (v₁ : ℕ) / 2^(v₂ : ℕ) :=
begin
push_cast [lshr],
apply mod_eq_of_lt,
apply lt_of_le_of_lt (nat.div_le_self _ _) (to_nat_lt _)
end
lemma lshr_above (v₁ v₂ : bv n) (h : n ≤ v₂.to_nat) :
v₁.lshr v₂ = 0 :=
begin
push_cast [← to_nat_inj],
apply div_eq_of_lt,
apply lt_of_lt_of_le (to_nat_lt _),
apply pow_le_pow_of_le_right two_pos h
end
end bitwise
section order
variable {n : ℕ}
@[norm_cast]
lemma ult_to_nat (v₁ v₂ : bv n) :
((v₁ : ℕ) < (v₂ : ℕ)) = (v₁ < v₂) := rfl
@[norm_cast]
lemma ule_to_nat (v₁ v₂ : bv n) :
((v₁ : ℕ) ≤ (v₂ : ℕ)) ↔ (v₁ ≤ v₂) :=
begin
rw [le_iff_eq_or_lt, or_comm],
norm_cast
end
protected lemma ule_refl (v : bv n) : v ≤ v :=
by simp [← ule_to_nat]
protected lemma ule_trans (v₁ v₂ v₃ : bv n) :
v₁ ≤ v₂ → v₂ ≤ v₃ → v₁ ≤ v₃ :=
begin
simp [← ule_to_nat],
apply le_trans
end
protected lemma ule_antisymm (v₁ v₂ : bv n) :
v₁ ≤ v₂ →
v₂ ≤ v₁ →
v₁ = v₂ :=
begin
simp [← ule_to_nat, ← to_nat_inj],
apply le_antisymm
end
protected lemma ule_total (v₁ v₂ : bv n) :
v₁ ≤ v₂ ∨ v₂ ≤ v₁ :=
by simp [← ule_to_nat, le_total]
protected lemma ult_iff_ule_not_ule (v₁ v₂ : bv n) :
v₁ < v₂ ↔ v₁ ≤ v₂ ∧ ¬ v₂ ≤ v₁ :=
begin
rw ← ult_to_nat,
repeat { rw ← ule_to_nat },
apply lt_iff_le_not_le
end
@[priority 101]
instance unsigned : linear_order (bv n) :=
{ le := bv.ule,
decidable_le := bv.decidable_ule,
le_refl := bv.ule_refl,
le_trans := bv.ule_trans,
le_antisymm := bv.ule_antisymm,
le_total := bv.ule_total,
lt := bv.ult,
decidable_lt := bv.decidable_ult,
lt_iff_le_not_le := bv.ult_iff_ule_not_ule }
lemma slt_to_int (v₁ v₂ : bv (n + 1)) :
v₁.to_int < v₂.to_int = v₁.slt v₂ :=
begin
simp [bv.slt, to_int, ← msb_eq_ff_iff],
have h₁ := to_nat_lt v₁,
have h₂ := to_nat_lt v₂,
cases v₁.msb; cases v₂.msb; simp [← ult_to_nat]; linarith
end
protected lemma sle_iff_eq_or_slt (v₁ v₂ : bv (n + 1)) :
v₁.sle v₂ = (v₁ = v₂ ∨ v₁.slt v₂) :=
begin
simp [bv.sle, bv.slt, le_iff_eq_or_lt],
cases eq.decidable v₁ v₂ with h h; simp [h]
end
lemma sle_to_int (v₁ v₂ : bv (n + 1)) :
(v₁.to_int ≤ v₂.to_int) = v₁.sle v₂ :=
by rw [le_iff_eq_or_lt, to_int_inj, slt_to_int, bv.sle_iff_eq_or_slt]
protected lemma sle_refl (v : bv (n + 1)) :
v.sle v :=
by simp [bv.sle, bv.ule_refl]
protected lemma sle_trans (v₁ v₂ v₃ : bv (n + 1)) :
v₁.sle v₂ →
v₂.sle v₃ →
v₁.sle v₃ :=
begin
simp [← sle_to_int],
apply le_trans
end
protected lemma sle_antisymm (v₁ v₂ : bv (n + 1)) :
v₁.sle v₂ →
v₂.sle v₁ →
v₁ = v₂ :=
begin
simp [bv.sle],
finish
end
protected lemma sle_total (v₁ v₂ : bv (n + 1)) :
v₁.sle v₂ ∨ v₂.sle v₁ :=
by simp [← sle_to_int, le_total]
protected lemma slt_iff_sle_not_sle (v₁ v₂ : bv (n + 1)) :
v₁.slt v₂ ↔ v₁.sle v₂ ∧ ¬ v₂.sle v₁ :=
begin
rw ← slt_to_int,
repeat { rw ← sle_to_int },
apply lt_iff_le_not_le
end
@[priority 100]
instance signed : linear_order (bv (n + 1)) :=
{ le := bv.sle,
decidable_le := bv.decidable_sle,
le_refl := bv.sle_refl,
le_trans := bv.sle_trans,
le_antisymm := bv.sle_antisymm,
le_total := bv.sle_total,
lt := bv.slt,
decidable_lt := bv.decidable_slt,
lt_iff_le_not_le := bv.slt_iff_sle_not_sle }
end order
end bv
|
0981e2f3d96fa2813835f137bfd34565ef9cec73 | 7617a8700fc3eebd9200f1e620ee65b3565d2eff | /src/util/basic.lean | 3af28b11739295189982bc829633435ff6e56708 | [] | no_license | digama0/vc0 | 9747eee791c5c2f58eb53264ca6263ee53de0f87 | b8b192c8c139e0b5a25a7284b93ed53cdf7fd7a5 | refs/heads/master | 1,626,186,940,436 | 1,592,385,972,000 | 1,592,385,972,000 | 158,556,766 | 5 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 23,464 | lean | import data.pfun data.sigma data.finmap
namespace roption
def pmap {α β} (o : roption α) (f : o.dom → α → β) : roption β :=
⟨o.dom, λ h, f h (o.get h)⟩
def forall₂ {α β} (R : α → β → Prop) (o₁ : roption α) (o₂ : roption β) : Prop :=
(∀ x ∈ o₁, ∃ y ∈ o₂, R x y) ∧ (∀ y ∈ o₂, ∃ x ∈ o₁, R x y)
theorem forall₂_dom {α β} {R : α → β → Prop} {o₁ : roption α} {o₂ : roption β}
(H : forall₂ R o₁ o₂) : o₁.dom ↔ o₂.dom :=
⟨λ h, by rcases H.1 _ ⟨h, rfl⟩ with ⟨_, ⟨h', _⟩, _⟩; exact h',
λ h, by rcases H.2 _ ⟨h, rfl⟩ with ⟨_, ⟨h', _⟩, _⟩; exact h'⟩
@[elab_as_eliminator]
def mem_cases {α} (o : roption α) {C : ∀ a ∈ o, Sort*}
(H : ∀ h, C (o.get h) ⟨h, rfl⟩) : ∀ a h, C a h :=
λ a h', begin
have h₂ := h', revert h',
rw ← h₂.snd; exact λ h₂, H _
end
end roption
namespace option
inductive forall₂ {α α'} (R : α → α' → Prop) : option α → option α' → Prop
| none {} : forall₂ none none
| some {a a'} : R a a' → forall₂ (some a) (some a')
theorem forall₂.imp {α α'} {R S : α → α' → Prop} (H : ∀ a a', R a a' → S a a') :
∀ {o o'}, forall₂ R o o' → forall₂ S o o'
| _ _ forall₂.none := forall₂.none
| _ _ (forall₂.some h) := forall₂.some (H _ _ h)
end option
namespace sum
inductive forall₂ {α β α' β'} (R : α → α' → Prop) (S : β → β' → Prop) : α ⊕ β → α' ⊕ β' → Prop
| inl {a a'} : R a a' → forall₂ (sum.inl a) (sum.inl a')
| inr {b b'} : S b b' → forall₂ (sum.inr b) (sum.inr b')
end sum
namespace prod
inductive forall₂ {α β α' β'} (R : α → α' → Prop) (S : β → β' → Prop) :
α × β → α' × β' → Prop
| mk {a b a' b'} : R a a' → S b b' → forall₂ (a, b) (a', b')
theorem forall₂.imp {α β α' β'} {R R' : α → α' → Prop} {S S' : β → β' → Prop}
(H₁ : ∀ a a', R a a' → R' a a') (H₂ : ∀ b b', S b b' → S' b b') :
∀ {x x'}, forall₂ R S x x' → forall₂ R' S' x x'
| _ _ ⟨h₁, h₂⟩ := ⟨H₁ _ _ h₁, H₂ _ _ h₂⟩
end prod
namespace sigma
inductive forall₂ {ι} {α α' : ι → Type*} (R : ∀ i, α i → α' i → Prop) :
(Σ i, α i) → (Σ i, α' i) → Prop
| mk {i a a'} : R i a a' → forall₂ ⟨i, a⟩ ⟨i, a'⟩
theorem forall₂.imp {ι} {α α' : ι → Type*}
{R S : ∀ i, α i → α' i → Prop} (H : ∀ i a a', R i a a' → S i a a') :
∀ {s s'}, forall₂ R s s' → forall₂ S s s'
| _ _ ⟨r⟩ := ⟨H _ _ _ r⟩
theorem forall₂.flip {ι} {α α' : ι → Type*}
{R : ∀ i, α i → α' i → Prop} :
∀ {s s'}, forall₂ (λ i, flip (R i)) s s' → forall₂ R s' s
| _ _ ⟨r⟩ := ⟨r⟩
end sigma
namespace list
inductive update_at {α} (R : α → α → Prop) : ℕ → list α → list α → Prop
| one {a b l} : R a b → update_at 0 (a :: l) (b :: l)
| cons {n a l l'} : update_at n l l' → update_at (n+1) (a :: l) (a :: l')
theorem update_at_forall₂ {α} {R : α → α → Prop} :
∀ {n l₁ l₂}, update_at R n l₁ l₂ → forall₂ (λ x y, R x y ∨ x = y) l₁ l₂
| _ _ _ (@update_at.one _ _ a b l h) :=
forall₂.cons (or.inl h) (@forall₂_refl _ _ ⟨by exact λ a, or.inr rfl⟩ _)
| _ _ _ (@update_at.cons _ _ n a l₁ l₂ h) :=
forall₂.cons (or.inr rfl) (update_at_forall₂ h)
theorem update_at_forall₂' {α} {R : α → α → Prop} [is_refl α R]
{n l₁ l₂} (h : update_at R n l₁ l₂) : forall₂ R l₁ l₂ :=
(update_at_forall₂ h).imp (λ a b, or.rec id (by rintro rfl; apply refl))
lemma forall₂_comm {α β} {r : α → β → Prop} {a b} :
forall₂ r a b ↔ forall₂ (flip r) b a := ⟨forall₂.flip, forall₂.flip⟩
lemma forall₂_and_right {α β} {r : α → β → Prop} {p : β → Prop}
{l u} : forall₂ (λa b, r a b ∧ p b) l u ↔ forall₂ r l u ∧ (∀b∈u, p b) :=
by rw [and_comm, forall₂_comm, @forall₂_comm _ _ r, ← forall₂_and_left];
conv in (_∧_) {rw and_comm}; refl
lemma forall₂.mp_trans {α β γ} {r : α → β → Prop} {q : β → γ → Prop}
{s : α → γ → Prop} (h : ∀a b c, r a b → q b c → s a c) :
∀{l₁ l₂ l₃}, forall₂ r l₁ l₂ → forall₂ q l₂ l₃ → forall₂ s l₁ l₃
| [] [] [] forall₂.nil forall₂.nil := forall₂.nil
| (a::l₁) (b::l₂) (c::l₃) (forall₂.cons hr hrs) (forall₂.cons hq hqs) :=
forall₂.cons (h a b c hr hq) (forall₂.mp_trans hrs hqs)
lemma forall₂.nth {α β} {R : α → β → Prop} :
∀{l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a b n}, a ∈ l₁.nth n → b ∈ l₂.nth n → R a b
| (a::l₁) (b::l₂) (forall₂.cons hr hrs) _ _ 0 rfl rfl := hr
| (a::l₁) (b::l₂) (forall₂.cons hr hrs) a' b' (n+1) h₁ h₂ := forall₂.nth hrs h₁ h₂
lemma forall₂.nth_right {α β} {R : α → β → Prop} :
∀{l₁ l₂}, forall₂ R l₁ l₂ → ∀ {a n}, a ∈ l₁.nth n → ∃ b ∈ l₂.nth n, R a b
| (a::l₁) (b::l₂) (forall₂.cons hr hrs) _ 0 rfl := ⟨_, rfl, hr⟩
| (a::l₁) (b::l₂) (forall₂.cons hr hrs) a' (n+1) h₁ := forall₂.nth_right hrs h₁
lemma forall₂_reverse {α β} {R : α → β → Prop} :
∀ {l₁ l₂}, forall₂ R (reverse l₁) (reverse l₂) ↔ forall₂ R l₁ l₂ :=
suffices ∀ {l₁ l₂}, forall₂ R l₁ l₂ → forall₂ R (reverse l₁) (reverse l₂),
from λ l₁ l₂, ⟨λ h, by simpa using this h, this⟩,
suffices ∀ {l₁ l₂ r₁ r₂}, forall₂ R l₁ l₂ → forall₂ R r₁ r₂ →
forall₂ R (reverse_core l₁ r₁) (reverse_core l₂ r₂),
from λ l₁ l₂ h, this h forall₂.nil,
λ l₁, begin
induction l₁ with a l₁ IH; introv h₁ h₂;
cases h₁ with _ b _ l₂ r h₁',
exacts [h₂, IH h₁' (forall₂.cons r h₂)]
end
lemma forall₂_concat {α β} {R : α → β → Prop}
{a b l₁ l₂} : forall₂ R (l₁ ++ [a]) (l₂ ++ [b]) ↔ forall₂ R l₁ l₂ ∧ R a b :=
by rw ← forall₂_reverse; simp [forall₂_reverse, and_comm]
lemma map_prod_fst_eq_of_forall₂_eq {α β γ} {R : β → γ → Prop} {l₁ l₂}
(h : forall₂ (prod.forall₂ (@eq α) R) l₁ l₂) :
l₁.map prod.fst = l₂.map prod.fst :=
begin
rw [← list.forall₂_eq_eq_eq, list.forall₂_map_left_iff,
list.forall₂_map_right_iff],
refine h.imp _, rintro _ _ ⟨rfl, _⟩, refl
end
lemma map_sigma_fst_eq_of_forall₂_eq {α} {β β' : α → Type*}
{R : ∀ a, β a → β' a → Prop} {l₁ l₂}
(h : forall₂ (sigma.forall₂ R) l₁ l₂) :
l₁.map sigma.fst = l₂.map sigma.fst :=
begin
rw [← list.forall₂_eq_eq_eq, list.forall₂_map_left_iff,
list.forall₂_map_right_iff],
refine h.imp _, rintro _ _ ⟨⟩, refl
end
lemma rel_of_forall₂_of_nodup {α β γ} {R : β → γ → Prop} {l₁ l₂}
(h : forall₂ (prod.forall₂ (@eq α) R) l₁ l₂)
(nd : (l₁.map prod.fst).nodup)
{a b c} (h₁ : (a, b) ∈ l₁) (h₂ : (a, c) ∈ l₂) : R b c :=
begin
have nd' := nd, rw map_prod_fst_eq_of_forall₂_eq h at nd',
induction h, {cases h₁},
rcases h₁ with rfl | h₁; rcases h₂ with rfl | h₂,
{ cases h_a_1, assumption },
{ rcases h_a_1 with ⟨i, _, _, τ', rfl, _⟩,
cases (list.nodup_cons.1 nd').1 (list.mem_map_of_mem prod.fst h₂:_) },
{ rcases h_a_1 with ⟨i, v', _, _, rfl, _⟩,
cases (list.nodup_cons.1 nd).1 (list.mem_map_of_mem prod.fst h₁:_) },
{ exact h_ih (list.nodup_cons.1 nd).2 h₁ h₂ (list.nodup_cons.1 nd').2 }
end
theorem lookmap_forall₂ {α} (f : α → option α) :
∀ l, forall₂ (λ a b, a = b ∨ b ∈ f a) l (lookmap f l)
| [] := forall₂.nil
| (a::l) := begin
dsimp only [lookmap],
cases e : f a,
{ exact forall₂.cons (or.inl rfl) (lookmap_forall₂ l) },
{ refine forall₂.cons (or.inr e) (@forall₂_refl _ _ ⟨_⟩ l),
exact λ _, or.inl rfl },
end
theorem lookmap_forall₂' {α} (f : α → option α)
{β} (g : α → β) (H : ∀ a a' (b ∈ f a) (b' ∈ f a'), g a = g a') :
∀ l : list α, (l.map g).nodup → forall₂ (λ a b, (f a).get_or_else a = b) l (lookmap f l)
| [] nd := forall₂.nil
| (a::l) nd := begin
cases list.nodup_cons.1 nd with nd₁ nd₂,
dsimp only [lookmap],
cases e : f a,
{ exact forall₂.cons (by rw e; refl) (lookmap_forall₂' l nd₂) },
{ refine forall₂.cons (by rw e; refl) (forall₂_same $ λ a' h, _),
cases e' : f a', {refl},
rw H _ _ _ e _ e' at nd₁,
cases nd₁ (mem_map_of_mem _ h) },
end
inductive kreplace_rel {α} {β : α → Type*} (a) (b : β a) : ∀ a, β a → β a → Prop
| repl {} {b'} : kreplace_rel a b' b
| refl {} {a' b'} : a ≠ a' → kreplace_rel a' b' b'
theorem kreplace_forall₂ {α} {β : α → Type*} [decidable_eq α] (a) (b : β a)
{l} (nd : nodupkeys l) : forall₂ (sigma.forall₂ (kreplace_rel a b)) l (kreplace a b l) :=
begin
refine (lookmap_forall₂' _ _ _ _ nd).imp _,
{ rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ h,
split_ifs at h; cases h,
{ cases h_1, exact ⟨kreplace_rel.repl⟩ },
{ exact ⟨kreplace_rel.refl h_1⟩ } },
{ rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ s₁ h₁ s₂ h₂,
split_ifs at h₁ h₂; cases h₁; cases h₂,
exact h_1.symm.trans h }
end
theorem mem_erasep {α} (p : α → Prop) [decidable_pred p] {l : list α}
(H : pairwise (λ a b, p a → p b → false) l)
{a : α} : a ∈ erasep p l ↔ ¬ p a ∧ a ∈ l :=
⟨λ h, begin
by_cases pa : p a,
{ rcases exists_of_erasep (mem_of_mem_erasep h) pa
with ⟨b, l₁, l₂, h₁, pb, rfl, h₂⟩,
rw h₂ at h,
cases mem_append.1 h,
{ cases h₁ _ h_1 pa },
{ cases (pairwise_cons.1 (pairwise_append.1 H).2.1).1 _ h_1 pb pa } },
{ exact ⟨pa, (mem_erasep_of_neg pa).1 h⟩ }
end, λ ⟨h₁, h₂⟩, (mem_erasep_of_neg h₁).2 h₂⟩
theorem mem_kerase {α β} [decidable_eq α] {s : list (sigma β)}
(nd : s.nodupkeys) {a a' : α} {b' : β a'} :
sigma.mk a' b' ∈ kerase a s ↔ a ≠ a' ∧ sigma.mk a' b' ∈ s :=
mem_erasep _ $ (nodupkeys_iff_pairwise.1 nd).imp $
by rintro x y h rfl; exact h
@[simp] theorem cons_to_finset {α} [decidable_eq α] (a l) :
(a :: l : list α).to_finset = insert a l.to_finset :=
by ext; simp
end list
def prod.to_sigma {α β} (x : α × β) : Σ a : α, β := ⟨x.1, x.2⟩
namespace alist
open list
theorem mem_lookup_iff {α} {β : α → Type*} [decidable_eq α]
{a : α} {b : β a} {s : alist β} :
b ∈ lookup a s ↔ sigma.mk a b ∈ s.entries :=
list.mem_lookup_iff s.2
theorem exists_mem_lookup_iff {α} {β : α → Type*} [decidable_eq α]
{a : α} {s : alist β} : (∃ b, b ∈ lookup a s) ↔ a ∈ s :=
option.is_some_iff_exists.symm.trans lookup_is_some
theorem to_sigma_nodupkeys {α β} {l : list (α × β)} :
(l.map prod.to_sigma).nodupkeys ↔ (l.map prod.fst).nodup :=
by rw [list.nodupkeys, list.keys, list.map_map]; refl
def mk' {α β} (l : list (α × β)) (h : (l.map prod.fst).nodup) : alist (λ _, β) :=
⟨l.map prod.to_sigma, to_sigma_nodupkeys.2 h⟩
@[simp] theorem mk'_entries {α β} (l : list (α × β)) (h) :
(mk' l h).entries = l.map prod.to_sigma := rfl
@[simp] theorem mk'_keys {α β} (l : list (α × β)) (h) :
(mk' l h).keys = l.map prod.fst :=
by rw [keys, list.keys, mk'_entries, list.map_map]; refl
def cons {α} {β : α → Type*} (s : alist β)
(a : α) (b : β a) (h : a ∉ s) : alist β :=
⟨⟨a, b⟩ :: s.entries, nodup_cons.2 ⟨mt mem_keys.1 h, s.nodupkeys⟩⟩
theorem insert_eq_cons {α} {β : α → Type*} [decidable_eq α]
{s : alist β} {a : α} {b : β a} (h : a ∉ s) : insert a b s = cons s a b h :=
ext $ by simp only [insert_entries_of_neg h]; refl
theorem cons_inj {α} {β : α → Type*} [decidable_eq α]
{s s' : alist β} {a a' : α} {b : β a} {b' : β a'}
{h : a ∉ s} {h' : a' ∉ s'}
(eq : cons s a b h = cons s' a' b' h') :
sigma.mk a b = ⟨a', b'⟩ ∧ s = s' :=
by cases s; cases s'; cases congr_arg alist.entries eq; exact ⟨rfl, rfl⟩
theorem lookup_cons_iff {α β} [decidable_eq α] {s a b h a' b'} :
b' ∈ lookup a' (@cons α β s a b h) ↔ sigma.mk a' b' = ⟨a, b⟩ ∨ b' ∈ lookup a' s :=
mem_lookup_iff.trans $ or_congr iff.rfl mem_lookup_iff.symm
theorem lookup_cons_of_lookup {α β} [decidable_eq α] {s a b h a' b'}
(H : b' ∈ lookup a' s) : b' ∈ lookup a' (@cons α β s a b h) :=
lookup_cons_iff.2 $ or.inr H
theorem lookup_cons_self {α β} [decidable_eq α] {s a b h} :
b ∈ lookup a (@cons α β s a b h) :=
lookup_cons_iff.2 $ or.inl rfl
@[simp] theorem cons_keys {α} {β : α → Type*} (s : alist β)
(a : α) (b : β a) (h : a ∉ s) : (alist.cons s a b h).keys = a :: s.keys := rfl
def forall₂ {α} {β γ : α → Type*} (R : ∀ a, β a → γ a → Prop)
(l₁ : alist β) (l₂ : alist γ) : Prop :=
list.forall₂ (sigma.forall₂ R) l₁.entries l₂.entries
theorem forall₂.imp {α} {β β' : α → Type*}
{R S : ∀ a, β a → β' a → Prop} (H : ∀ a b b', R a b b' → S a b b')
{s s'} : forall₂ R s s' → forall₂ S s s' :=
list.forall₂.imp $ λ a b, sigma.forall₂.imp H
lemma forall₂_same {α} {β : α → Type*} {r : ∀ a, β a → β a → Prop} {s : alist β}
(h : ∀ a (b : β a), sigma.mk a b ∈ s.entries → r a b b) : forall₂ r s s :=
forall₂_same $ λ ⟨a, b⟩ m, ⟨h _ _ m⟩
theorem forall₂.flip {α} {β β' : α → Type*}
{R : ∀ a, β a → β' a → Prop}
{s s'} (H : forall₂ (λ a, flip (R a)) s s') : forall₂ R s' s :=
H.flip.imp $ λ _ _, sigma.forall₂.flip
theorem forall₂.keys {α} {β β' : α → Type*}
{R : ∀ a, β a → β' a → Prop} {s s'} :
forall₂ R s s' → s.keys = s'.keys :=
map_sigma_fst_eq_of_forall₂_eq
theorem forall₂.mem_iff {α} {β β' : α → Type*}
{R : ∀ a, β a → β' a → Prop} {s s'} (H : forall₂ R s s')
{a} : a ∈ s ↔ a ∈ s' :=
by rw [mem_keys, H.keys, mem_keys]
@[elab_as_eliminator]
theorem forall₂.induction {α} {β γ : α → Type*}
{R : ∀ a, β a → γ a → Prop}
{P : @alist α β → @alist α γ → Prop} {l₁ : alist β} {l₂ : alist γ}
(H : forall₂ R l₁ l₂) (H0 : P ∅ ∅)
(H1 : ∀ l₁ l₂ a b c h₁ h₂, R a b c → forall₂ R l₁ l₂ →
P l₁ l₂ → P (cons l₁ a b h₁) (cons l₂ a c h₂)) :
P l₁ l₂ :=
begin
cases l₁ with l₁ nd₁; cases l₂ with l₂ nd₂,
dsimp [forall₂] at H,
induction H, {exact H0},
rcases H_a_1 with ⟨a, b, c, h⟩,
cases nodupkeys_cons.1 nd₁ with m₁ nd₁,
cases nodupkeys_cons.1 nd₂ with m₂ nd₂,
refine H1 ⟨_, _⟩ ⟨_, _⟩ _ _ _ m₁ m₂ h H_a_2 (H_ih nd₁ nd₂),
end
theorem forall₂_cons {α} {β γ : α → Type*} {R : ∀ a, β a → γ a → Prop}
{l₁ : alist β} {l₂ : alist γ} {a b c h₁ h₂} :
forall₂ R (cons l₁ a b h₁) (cons l₂ a c h₂) ↔ R a b c ∧ forall₂ R l₁ l₂ :=
⟨by rintro (_|⟨_,_,_,_,⟨_,_,_,r⟩,h⟩); exact ⟨r, h⟩,
λ ⟨r, h⟩, list.forall₂.cons ⟨r⟩ h⟩
theorem forall₂.rel_of_mem {α} {β₁ β₂ : α → Type*} [decidable_eq α]
{R : ∀ a, β₁ a → β₂ a → Prop} {s₁ s₂} (H : forall₂ R s₁ s₂)
{a} {b₁ : β₁ a} {b₂ : β₂ a}
(h₁ : sigma.mk a b₁ ∈ s₁.entries)
(h₂ : sigma.mk a b₂ ∈ s₂.entries) : R a b₁ b₂ :=
begin
cases s₁ with l₁ nd₁, cases s₂ with l₂ nd₂,
dsimp only [forall₂] at *,
induction H, {cases h₁},
rcases h₁ with rfl | h₁; rcases h₂ with rfl | h₂,
{ cases H_a_1, assumption },
{ rcases H_a_1 with ⟨i, _, b₂', _⟩,
cases (list.nodupkeys_cons.1 nd₂).1 (list.mem_keys.2 ⟨_, h₂⟩) },
{ rcases H_a_1 with ⟨i, b₁', _, _⟩,
cases (list.nodupkeys_cons.1 nd₁).1 (list.mem_keys.2 ⟨_, h₁⟩) },
{ cases H_a, cases H_b,
exact H_ih (list.nodupkeys_cons.1 nd₁).2 h₁ (list.nodupkeys_cons.1 nd₂).2 h₂ }
end
theorem forall₂.rel_of_lookup {α} {β β' : α → Type*} [decidable_eq α]
{R : ∀ a, β a → β' a → Prop} {s s'} (H : forall₂ R s s')
{a b b'} (h₁ : b ∈ s.lookup a) (h₂ : b' ∈ s'.lookup a) : R a b b' :=
by rw mem_lookup_iff at h₁ h₂; exact H.rel_of_mem h₁ h₂
theorem forall₂.rel_of_lookup_right {α} {β β' : α → Type*} [decidable_eq α]
{R : ∀ a, β a → β' a → Prop} {s s'} (H : forall₂ R s s')
{a b} (h : b ∈ s.lookup a) : ∃ b' ∈ s'.lookup a, R a b b' :=
let ⟨b', h'⟩ := exists_mem_lookup_iff.2
(H.mem_iff.1 (exists_mem_lookup_iff.1 ⟨_, h⟩)) in
⟨b', h', H.rel_of_lookup h h'⟩
theorem replace_forall₂ {α} {β : α → Type*} [decidable_eq α]
(a) (b : β a) (s : alist β) : forall₂ (kreplace_rel a b) s (replace a b s) :=
kreplace_forall₂ _ _ s.2
def map {α} {β γ : α → Type*}
(f : ∀ a, β a → γ a) (s : alist β) : alist γ :=
⟨list.map (sigma.map id f) s.entries, by rw [
list.nodupkeys, list.keys, list.map_map,
(by ext ⟨a, b⟩; refl : sigma.fst ∘ sigma.map id f = sigma.fst)];
exact s.2⟩
theorem map_entries {α} {β γ : α → Type*}
(f : ∀ a, β a → γ a) (s : alist β) :
(map f s).entries = list.map (sigma.map id f) s.entries := rfl
theorem mem_map_entries {α} {β γ : α → Type*}
{f : ∀ a, β a → γ a} {s : alist β} {a} {c : γ a} :
sigma.mk a c ∈ (map f s).entries ↔ ∃ b : β a, sigma.mk a b ∈ s.entries ∧ f a b = c :=
mem_map.trans ⟨
by rintro ⟨⟨a, b⟩, h, ⟨⟩⟩; exact ⟨_, h, rfl⟩,
by rintro ⟨b, h, ⟨⟩⟩; exact ⟨_, h, rfl⟩⟩
theorem lookup_map {α} {β γ : α → Type*} [decidable_eq α]
{f : ∀ a, β a → γ a} {s : alist β} {a} {c : γ a} :
c ∈ (map f s).lookup a ↔ ∃ b : β a, b ∈ s.lookup a ∧ f a b = c :=
mem_lookup_iff.trans $ mem_map_entries.trans $ by simp only [mem_lookup_iff]
theorem forall₂_map_left_iff {α} {β γ δ : α → Type*}
{r : ∀ a, γ a → δ a → Prop} {f : ∀ a, β a → γ a} {l : alist β} {u : alist δ} :
alist.forall₂ r (alist.map f l) u ↔ alist.forall₂ (λ a c d, r a (f a c) d) l u :=
begin
unfold forall₂, refine list.forall₂_map_left_iff.trans _,
apply iff_of_eq, congr', ext ⟨a, b⟩ ⟨a', d⟩,
split; rintro ⟨_, _, d, r⟩; exact ⟨r⟩
end
theorem forall₂_map_right_iff {α} {β γ δ : α → Type*}
{r : ∀ a, β a → δ a → Prop} {f : ∀ a, γ a → δ a} {l : alist β} {u : alist γ} :
alist.forall₂ r l (alist.map f u) ↔ alist.forall₂ (λ a b c, r a b (f a c)) l u :=
⟨λ h, (forall₂_map_left_iff.1 h.flip).flip,
λ h, ((@forall₂_map_left_iff _ _ _ _ (λ a, flip (r a)) _ _ _).2 h.flip).flip⟩
theorem lookup_replace_of_ne {α} {β : α → Type*} [decidable_eq α]
{a} {b : β a} {s : alist β} {a'} (ne : a ≠ a'):
lookup a' (replace a b s) = lookup a' s :=
begin
ext b',
split; intro h,
{ rcases (replace_forall₂ a b s).flip.rel_of_lookup_right h with ⟨b'', m, _|_⟩;
[cases ne rfl, exact m] },
{ rcases (replace_forall₂ a b s).rel_of_lookup_right h with ⟨b'', m, _|_⟩;
[cases ne rfl, exact m] },
end
theorem lookup_replace_self {α} {β : α → Type*} [decidable_eq α]
{a} {b : β a} {s : alist β} (h : a ∈ s) :
b ∈ lookup a (replace a b s) :=
by rcases exists_mem_lookup_iff.2 h with ⟨b', h⟩;
rcases (replace_forall₂ a b s).rel_of_lookup_right h with ⟨b'', m, _|_⟩;
[exact m, cases h_1_h_a rfl]
theorem replace_cons_self {α} {β : α → Type*} [decidable_eq α]
{a} {b b' : β a} {s : alist β} (h) : replace a b' (cons s a b h) = cons s a b' h :=
by simp [replace, cons, kreplace]; rw [lookmap_cons_some]; simp
theorem replace_cons_of_ne {α} {β : α → Type*} [decidable_eq α]
{a} {b : β a} {s : alist β} (h) {a'} {b' : β a'} (ne : a' ≠ a) :
∃ h', replace a' b' (cons s a b h) = cons (replace a' b' s) a b h' :=
⟨mt alist.mem_replace.1 h,
by simp [replace, cons, kreplace]; rw [lookmap_cons_none]; simp [ne]⟩
@[simp] theorem entries_erase {α β} [decidable_eq α] (a : α) (s : alist β) :
(erase a s).entries = s.entries.kerase a := rfl
theorem lookup_erase' {α β} [decidable_eq α] {s : alist β} {a a' : α} {b' : β a'} :
b' ∈ lookup a' (erase a s) ↔ a ≠ a' ∧ b' ∈ lookup a' s :=
by rw [mem_lookup_iff, entries_erase, mem_kerase s.2, mem_lookup_iff]
def values {α β} (s : alist (λ _ : α, β)) : list β := s.entries.map sigma.snd
@[elab_as_eliminator]
def rec' {α β} {C : @alist α β → Sort*}
(H0 : C ∅) (H1 : ∀ s a b h, C s → C (cons s a b h)) (s) : C s :=
begin
cases s with l nd,
induction l with ab l IH,
{ exact H0 },
{ cases ab with a b,
have := list.nodupkeys_cons.1 nd,
exact H1 ⟨l, this.2⟩ a b this.1 (IH this.2) }
end
@[simp] theorem rec'_empty {α β C H0 H1} : @rec' α β C H0 H1 ∅ = H0 := rfl
@[simp] theorem rec'_cons {α β C H0 H1} : ∀ s a b h,
@rec' α β C H0 H1 (cons s a b h) = H1 s a b h (@rec' α β C H0 H1 s)
| ⟨l, nd⟩ a b h := rfl
end alist
namespace finset
theorem singleton_subset {α} {a : α} {s : finset α} :
singleton a ⊆ s ↔ a ∈ s :=
by simp [subset_def]; refl
theorem union_subset_iff {α} [decidable_eq α]
{s₁ s₂ t : finset α} : s₁ ∪ s₂ ⊆ t ↔ s₁ ⊆ t ∧ s₂ ⊆ t :=
⟨λ h, ⟨
subset.trans (subset_union_left _ _) h,
subset.trans (subset_union_right _ _) h⟩,
λ ⟨h₁, h₂⟩, union_subset h₁ h₂⟩
end finset
namespace finmap
open list
theorem mem_lookup_iff {α} {β : α → Type*} [decidable_eq α]
{a : α} {b : β a} {s : finmap β} :
b ∈ lookup a s ↔ sigma.mk a b ∈ s.entries :=
induction_on s $ λ s, alist.mem_lookup_iff
theorem exists_mem_lookup_iff {α} {β : α → Type*} [decidable_eq α]
{a : α} {s : finmap β} : (∃ b, b ∈ lookup a s) ↔ a ∈ s :=
induction_on s $ λ s, alist.exists_mem_lookup_iff
theorem lookup_insert_of_neg {α} {β : α → Type*} [decidable_eq α]
{a : α} {b : β a} {s : finmap β} (h : a ∉ s) {a' : α} {b' : β a'} :
b' ∈ (insert a b s).lookup a' ↔
sigma.mk a' b' = ⟨a, b⟩ ∨ b' ∈ s.lookup a' :=
by rw [mem_lookup_iff, mem_lookup_iff, insert_entries_of_neg h, multiset.mem_cons]
theorem lookup_insert_self {α β} [decidable_eq α] {s a b} :
a ∉ s → b ∈ lookup a (@insert α β _ a b s) :=
induction_on s $ λ s h,
by simp [insert, alist.insert_eq_cons h]; exact alist.lookup_cons_self
theorem lookup_erase' {α β} [decidable_eq α] {s : finmap β} {a a' : α} {b' : β a'} :
b' ∈ lookup a' (erase a s) ↔ a ≠ a' ∧ b' ∈ lookup a' s :=
induction_on s $ λ s, alist.lookup_erase'
theorem lookup_replace_of_ne {α} {β : α → Type*} [decidable_eq α]
{a} {b : β a} {s : finmap β} {a'} : a ≠ a' →
lookup a' (replace a b s) = lookup a' s :=
induction_on s $ λ s, alist.lookup_replace_of_ne
theorem lookup_replace_self {α} {β : α → Type*} [decidable_eq α]
{a} {b : β a} {s : finmap β} : a ∈ s →
b ∈ lookup a (replace a b s) :=
induction_on s $ λ s, alist.lookup_replace_self
@[simp] theorem keys_to_finmap {α} {β : α → Type*} [decidable_eq α]
(s : alist β) : keys s.to_finmap = s.keys.to_finset :=
to_finset_eq _
@[simp] theorem keys_insert {α} {β : α → Type*} [decidable_eq α]
(a : α) (b : β a) (s : finmap β) :
(insert a b s).keys = has_insert.insert a s.keys :=
induction_on s $ λ s, by ext; simp; by_cases a_1 = a; simp [h]
end finmap
|
8534e0a7d05bd2634ba292bc5ac25dd009155926 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/order/closure.lean | 6cb5ebece6ca98e63b7958c5e3b3099f773ed1d6 | [] | 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 | 7,416 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.order.basic
import Mathlib.order.preorder_hom
import Mathlib.order.galois_connection
import Mathlib.tactic.monotonicity.default
import Mathlib.PostPort
universes u l
namespace Mathlib
/-!
# Closure operators on a partial order
We define (bundled) closure operators on a partial order as an monotone (increasing), extensive
(inflationary) and idempotent function.
We define closed elements for the operator as elements which are fixed by it.
Note that there is close connection to Galois connections and Galois insertions: every closure
operator induces a Galois insertion (from the set of closed elements to the underlying type), and
every Galois connection induces a closure operator (namely the composition). In particular,
a Galois insertion can be seen as a general case of a closure operator, where the inclusion is given
by coercion, see `closure_operator.gi`.
## References
* https://en.wikipedia.org/wiki/Closure_operator#Closure_operators_on_partially_ordered_sets
-/
/--
A closure operator on the partial order `α` is a monotone function which is extensive (every `x`
is less than its closure) and idempotent.
-/
structure closure_operator (α : Type u) [partial_order α]
extends α →ₘ α
where
le_closure' : ∀ (x : α), x ≤ preorder_hom.to_fun _to_preorder_hom x
idempotent' : ∀ (x : α),
preorder_hom.to_fun _to_preorder_hom (preorder_hom.to_fun _to_preorder_hom x) = preorder_hom.to_fun _to_preorder_hom x
protected instance closure_operator.has_coe_to_fun (α : Type u) [partial_order α] : has_coe_to_fun (closure_operator α) :=
has_coe_to_fun.mk (fun (c : closure_operator α) => α → α)
fun (c : closure_operator α) => preorder_hom.to_fun (closure_operator.to_preorder_hom c)
namespace closure_operator
/-- The identity function as a closure operator. -/
@[simp] theorem id_to_preorder_hom_to_fun (α : Type u) [partial_order α] (x : α) : coe_fn (to_preorder_hom (id α)) x = x :=
Eq.refl (coe_fn (to_preorder_hom (id α)) x)
protected instance inhabited (α : Type u) [partial_order α] : Inhabited (closure_operator α) :=
{ default := id α }
theorem ext {α : Type u} [partial_order α] (c₁ : closure_operator α) (c₂ : closure_operator α) : ⇑c₁ = ⇑c₂ → c₁ = c₂ := sorry
/-- Constructor for a closure operator using the weaker idempotency axiom: `f (f x) ≤ f x`. -/
def mk' {α : Type u} [partial_order α] (f : α → α) (hf₁ : monotone f) (hf₂ : ∀ (x : α), x ≤ f x) (hf₃ : ∀ (x : α), f (f x) ≤ f x) : closure_operator α :=
mk (preorder_hom.mk f hf₁) hf₂ sorry
/--
theorem monotone {α : Type u} [partial_order α] (c : closure_operator α) : monotone ⇑c :=
preorder_hom.monotone' (to_preorder_hom c)
Every element is less than its closure. This property is sometimes referred to as extensivity or
inflationary.
-/
theorem le_closure {α : Type u} [partial_order α] (c : closure_operator α) (x : α) : x ≤ coe_fn c x :=
le_closure' c x
@[simp] theorem idempotent {α : Type u} [partial_order α] (c : closure_operator α) (x : α) : coe_fn c (coe_fn c x) = coe_fn c x :=
idempotent' c x
theorem le_closure_iff {α : Type u} [partial_order α] (c : closure_operator α) (x : α) (y : α) : x ≤ coe_fn c y ↔ coe_fn c x ≤ coe_fn c y :=
{ mp := fun (h : x ≤ coe_fn c y) => idempotent c y ▸ monotone c h,
mpr := fun (h : coe_fn c x ≤ coe_fn c y) => le_trans (le_closure c x) h }
theorem closure_top {α : Type u} [order_top α] (c : closure_operator α) : coe_fn c ⊤ = ⊤ :=
le_antisymm le_top (le_closure c ⊤)
theorem closure_inter_le {α : Type u} [semilattice_inf α] (c : closure_operator α) (x : α) (y : α) : coe_fn c (x ⊓ y) ≤ coe_fn c x ⊓ coe_fn c y :=
le_inf (monotone c inf_le_left) (monotone c inf_le_right)
theorem closure_union_closure_le {α : Type u} [semilattice_sup α] (c : closure_operator α) (x : α) (y : α) : coe_fn c x ⊔ coe_fn c y ≤ coe_fn c (x ⊔ y) :=
sup_le (monotone c le_sup_left) (monotone c le_sup_right)
/-- An element `x` is closed for the closure operator `c` if it is a fixed point for it. -/
def closed {α : Type u} [partial_order α] (c : closure_operator α) : set α :=
fun (x : α) => coe_fn c x = x
theorem mem_closed_iff {α : Type u} [partial_order α] (c : closure_operator α) (x : α) : x ∈ closed c ↔ coe_fn c x = x :=
iff.rfl
theorem mem_closed_iff_closure_le {α : Type u} [partial_order α] (c : closure_operator α) (x : α) : x ∈ closed c ↔ coe_fn c x ≤ x :=
{ mp := le_of_eq, mpr := fun (h : coe_fn c x ≤ x) => le_antisymm h (le_closure c x) }
theorem closure_eq_self_of_mem_closed {α : Type u} [partial_order α] (c : closure_operator α) {x : α} (h : x ∈ closed c) : coe_fn c x = x :=
h
@[simp] theorem closure_is_closed {α : Type u} [partial_order α] (c : closure_operator α) (x : α) : coe_fn c x ∈ closed c :=
idempotent c x
/-- The set of closed elements for `c` is exactly its range. -/
theorem closed_eq_range_close {α : Type u} [partial_order α] (c : closure_operator α) : closed c = set.range ⇑c := sorry
/-- Send an `x` to an element of the set of closed elements (by taking the closure). -/
def to_closed {α : Type u} [partial_order α] (c : closure_operator α) (x : α) : ↥(closed c) :=
{ val := coe_fn c x, property := closure_is_closed c x }
theorem top_mem_closed {α : Type u} [order_top α] (c : closure_operator α) : ⊤ ∈ closed c :=
closure_top c
theorem closure_le_closed_iff_le {α : Type u} [partial_order α] (c : closure_operator α) {x : α} {y : α} (hy : closed c y) : x ≤ y ↔ coe_fn c x ≤ y :=
eq.mpr (id (Eq._oldrec (Eq.refl (x ≤ y ↔ coe_fn c x ≤ y)) (Eq.symm (closure_eq_self_of_mem_closed c hy))))
(eq.mpr (id (Eq._oldrec (Eq.refl (x ≤ coe_fn c y ↔ coe_fn c x ≤ coe_fn c y)) (propext (le_closure_iff c x y))))
(iff.refl (coe_fn c x ≤ coe_fn c y)))
/-- The set of closed elements has a Galois insertion to the underlying type. -/
def gi {α : Type u} [partial_order α] (c : closure_operator α) : galois_insertion (to_closed c) coe :=
galois_insertion.mk (fun (x : α) (hx : ↑(to_closed c x) ≤ x) => { val := x, property := sorry }) sorry sorry sorry
end closure_operator
/--
Every Galois connection induces a closure operator given by the composition. This is the partial
order version of the statement that every adjunction induces a monad.
-/
@[simp] theorem galois_connection.closure_operator_to_preorder_hom_to_fun {α : Type u} [partial_order α] {β : Type u} [preorder β] {l : α → β} {u : β → α} (gc : galois_connection l u) (x : α) : coe_fn (closure_operator.to_preorder_hom (galois_connection.closure_operator gc)) x = u (l x) :=
Eq.refl (coe_fn (closure_operator.to_preorder_hom (galois_connection.closure_operator gc)) x)
/--
The Galois insertion associated to a closure operator can be used to reconstruct the closure
operator.
Note that the inverse in the opposite direction does not hold in general.
-/
@[simp] theorem closure_operator_gi_self {α : Type u} [partial_order α] (c : closure_operator α) : galois_connection.closure_operator (galois_insertion.gc (closure_operator.gi c)) = c := sorry
|
2fec341b951afc09e1066c4cb6c76ea86e8393cb | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/structAutoBound.lean | b040ab45ab44fb6d919cde7fdfbd8683cecd7510 | [
"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 | 314 | lean | structure Foo (β : α → Type v) where
a : α
b : β a
#print Foo
variable (α : Type u)
structure Bla.{u} /- Error, `u` already declared -/ where
a : α
structure Boo (β : Type v) where
a : α
b : β
#print Boo
structure Boo2.{w /- Error, `w` not used -/} (β : Type v) where
a : α
b : β
|
8fdbb87424645c0f79c294988ca6b46fd3ff136c | 86f6f4f8d827a196a32bfc646234b73328aeb306 | /examples/sets_functions_and_relations/unnamed_196.lean | a4f6dab5ca9b9cfd0e6061192fc498dafb2e23e4 | [] | no_license | jamescheuk91/mathematics_in_lean | 09f1f87d2b0dce53464ff0cbe592c568ff59cf5e | 4452499264e2975bca2f42565c0925506ba5dda3 | refs/heads/master | 1,679,716,410,967 | 1,613,957,947,000 | 1,613,957,947,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 152 | lean | import tactic
open set
variable {α : Type*}
variables (s t u : set α)
-- BEGIN
example : (s ∩ t) ∪ (s ∩ u) ⊆ s ∩ (t ∪ u):=
sorry
-- END |
ba23fd44457432c434c2a0f3fd8850efd3645d71 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/order/conditionally_complete_lattice.lean | 163b2358792dd17f4c1db584ee0d5f13af15a317 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 34,108 | lean | /-
Copyright (c) 2018 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
Adapted from the corresponding theory for complete lattices.
Theory of conditionally complete lattices.
A conditionally complete lattice is a lattice in which every non-empty bounded subset s
has a least upper bound and a greatest lower bound, denoted below by Sup s and Inf s.
Typical examples are real, nat, int with their usual orders.
The theory is very comparable to the theory of complete lattices, except that suitable
boundedness and non-emptyness assumptions have to be added to most statements.
We introduce two predicates bdd_above and bdd_below to express this boundedness, prove
their basic properties, and then go on to prove most useful properties of Sup and Inf
in conditionally complete lattices.
To differentiate the statements between complete lattices and conditionally complete
lattices, we prefix Inf and Sup in the statements by c, giving cInf and cSup. For instance,
Inf_le is a statement in complete lattices ensuring Inf s ≤ x, while cInf_le is the same
statement in conditionally complete lattices with an additional assumption that s is
bounded below.
-/
import
order.lattice order.complete_lattice order.bounds
tactic.finish data.set.finite
set_option old_structure_cmd true
open preorder set lattice
universes u v w
variables {α : Type u} {β : Type v} {ι : Type w}
section preorder
variables [preorder α] [preorder β] {s t : set α} {a b : α}
/-Sets bounded above and bounded below.-/
def bdd_above (s : set α) := ∃x, ∀y∈s, y ≤ x
def bdd_below (s : set α) := ∃x, ∀y∈s, x ≤ y
/-Introduction rules for boundedness above and below.
Most of the time, it is more efficient to use ⟨w, P⟩ where P is a proof
that all elements of the set are bounded by w. However, they are sometimes handy.-/
lemma bdd_above.mk (a : α) (H : ∀y∈s, y≤a) : bdd_above s := ⟨a, H⟩
lemma bdd_below.mk (a : α) (H : ∀y∈s, a≤y) : bdd_below s := ⟨a, H⟩
/-Empty sets and singletons are trivially bounded. For finite sets, we need
a notion of maximum and minimum, i.e., a lattice structure, see later on.-/
@[simp] lemma bdd_above_empty : ∀ [nonempty α], bdd_above (∅ : set α)
| ⟨x⟩ := ⟨x, by simp⟩
@[simp] lemma bdd_below_empty : ∀ [nonempty α], bdd_below (∅ : set α)
| ⟨x⟩ := ⟨x, by simp⟩
@[simp] lemma bdd_above_singleton : bdd_above ({a} : set α) :=
⟨a, by simp only [set.mem_singleton_iff, forall_eq]⟩
@[simp] lemma bdd_below_singleton : bdd_below ({a} : set α) :=
⟨a, by simp only [set.mem_singleton_iff, forall_eq]⟩
/-If a set is included in another one, boundedness of the second implies boundedness
of the first-/
lemma bdd_above_subset (st : s ⊆ t) : bdd_above t → bdd_above s
| ⟨w, hw⟩ := ⟨w, λ y ys, hw _ (st ys)⟩
lemma bdd_below_subset (st : s ⊆ t) : bdd_below t → bdd_below s
| ⟨w, hw⟩ := ⟨w, λ y ys, hw _ (st ys)⟩
/- Boundedness of intersections of sets, in different guises, deduced from the
monotonicity of boundedness.-/
lemma bdd_above_inter_left : bdd_above s → bdd_above (s ∩ t) :=
bdd_above_subset (set.inter_subset_left _ _)
lemma bdd_above_inter_right : bdd_above t → bdd_above (s ∩ t) :=
bdd_above_subset (set.inter_subset_right _ _)
lemma bdd_below_inter_left : bdd_below s → bdd_below (s ∩ t) :=
bdd_below_subset (set.inter_subset_left _ _)
lemma bdd_below_inter_right : bdd_below t → bdd_below (s ∩ t) :=
bdd_below_subset (set.inter_subset_right _ _)
/--The image under a monotone function of a set which is bounded above is bounded above-/
lemma bdd_above_of_bdd_above_of_monotone {f : α → β} (hf : monotone f) : bdd_above s → bdd_above (f '' s)
| ⟨C, hC⟩ := ⟨f C, by rintro y ⟨x, x_bnd, rfl⟩; exact hf (hC x x_bnd)⟩
/--The image under a monotone function of a set which is bounded below is bounded below-/
lemma bdd_below_of_bdd_below_of_monotone {f : α → β} (hf : monotone f) : bdd_below s → bdd_below (f '' s)
| ⟨C, hC⟩ := ⟨f C, by rintro y ⟨x, x_bnd, rfl⟩; exact hf (hC x x_bnd)⟩
end preorder
/--When there is a global maximum, every set is bounded above.-/
@[simp] lemma bdd_above_top [order_top α] (s : set α) : bdd_above s :=
⟨⊤, by intros; apply order_top.le_top⟩
/--When there is a global minimum, every set is bounded below.-/
@[simp] lemma bdd_below_bot [order_bot α] (s : set α): bdd_below s :=
⟨⊥, by intros; apply order_bot.bot_le⟩
/-When there is a max (i.e., in the class semilattice_sup), then the union of
two bounded sets is bounded, by the maximum of the bounds for the two sets.
With this, we deduce that finite sets are bounded by induction, and that a finite
union of bounded sets is bounded.-/
section semilattice_sup
variables [semilattice_sup α] {s t : set α} {a b : α}
/--The union of two sets is bounded above if and only if each of the sets is.-/
@[simp] lemma bdd_above_union : bdd_above (s ∪ t) ↔ bdd_above s ∧ bdd_above t :=
⟨show bdd_above (s ∪ t) → (bdd_above s ∧ bdd_above t), from
assume : bdd_above (s ∪ t),
have S : bdd_above s, by apply bdd_above_subset _ ‹bdd_above (s ∪ t)›; simp only [set.subset_union_left],
have T : bdd_above t, by apply bdd_above_subset _ ‹bdd_above (s ∪ t)›; simp only [set.subset_union_right],
and.intro S T,
show (bdd_above s ∧ bdd_above t) → bdd_above (s ∪ t), from
assume H : bdd_above s ∧ bdd_above t,
let ⟨⟨ws, hs⟩, ⟨wt, ht⟩⟩ := H in
/-hs : ∀ (y : α), y ∈ s → y ≤ ws ht : ∀ (y : α), y ∈ s → y ≤ wt-/
have Bs : ∀b∈s, b ≤ ws ⊔ wt,
by intros; apply le_trans (hs b ‹b ∈ s›) _; simp only [lattice.le_sup_left],
have Bt : ∀b∈t, b ≤ ws ⊔ wt,
by intros; apply le_trans (ht b ‹b ∈ t›) _; simp only [lattice.le_sup_right],
show bdd_above (s ∪ t),
begin
apply bdd_above.mk (ws ⊔ wt),
intros b H_1,
cases H_1,
apply Bs _ ‹b ∈ s›,
apply Bt _ ‹b ∈ t›,
end⟩
/--Adding a point to a set preserves its boundedness above.-/
@[simp] lemma bdd_above_insert : bdd_above (insert a s) ↔ bdd_above s :=
⟨bdd_above_subset (by simp only [set.subset_insert]),
λ h, by rw [insert_eq, bdd_above_union]; exact ⟨bdd_above_singleton, h⟩⟩
/--A finite set is bounded above.-/
lemma bdd_above_finite [nonempty α] (hs : finite s) : bdd_above s :=
finite.induction_on hs bdd_above_empty $ λ a s _ _, bdd_above_insert.2
/--A finite union of sets which are all bounded above is still bounded above.-/
lemma bdd_above_finite_union [nonempty α] {β : Type v} {I : set β} {S : β → set α} (H : finite I) :
(bdd_above (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_above (S i)) :=
⟨λ (bdd : bdd_above (⋃i∈I, S i)) i (hi : i ∈ I),
bdd_above_subset (subset_bUnion_of_mem hi) bdd,
show (∀i ∈ I, bdd_above (S i)) → (bdd_above (⋃i∈I, S i)), from
finite.induction_on H
(λ _, by rw bUnion_empty; exact bdd_above_empty)
(λ x s hn hf IH h, by simp only [
set.mem_insert_iff, or_imp_distrib, forall_and_distrib, forall_eq] at h;
rw [set.bUnion_insert, bdd_above_union]; exact ⟨h.1, IH h.2⟩)⟩
end semilattice_sup
/-When there is a min (i.e., in the class semilattice_inf), then the union of
two sets which are bounded from below is bounded from below, by the minimum of
the bounds for the two sets. With this, we deduce that finite sets are
bounded below by induction, and that a finite union of sets which are bounded below
is still bounded below.-/
section semilattice_inf
variables [semilattice_inf α] {s t : set α} {a b : α}
/--The union of two sets is bounded below if and only if each of the sets is.-/
@[simp] lemma bdd_below_union : bdd_below (s ∪ t) ↔ bdd_below s ∧ bdd_below t :=
⟨show bdd_below (s ∪ t) → (bdd_below s ∧ bdd_below t), from
assume : bdd_below (s ∪ t),
have S : bdd_below s, by apply bdd_below_subset _ ‹bdd_below (s ∪ t)›; simp only [set.subset_union_left],
have T : bdd_below t, by apply bdd_below_subset _ ‹bdd_below (s ∪ t)›; simp only [set.subset_union_right],
and.intro S T,
show (bdd_below s ∧ bdd_below t) → bdd_below (s ∪ t), from
assume H : bdd_below s ∧ bdd_below t,
let ⟨⟨ws, hs⟩, ⟨wt, ht⟩⟩ := H in
/-hs : ∀ (y : α), y ∈ s → ws ≤ y ht : ∀ (y : α), y ∈ s → wt ≤ y-/
have Bs : ∀b∈s, ws ⊓ wt ≤ b,
by intros; apply le_trans _ (hs b ‹b ∈ s›); simp only [lattice.inf_le_left],
have Bt : ∀b∈t, ws ⊓ wt ≤ b,
by intros; apply le_trans _ (ht b ‹b ∈ t›); simp only [lattice.inf_le_right],
show bdd_below (s ∪ t),
begin
apply bdd_below.mk (ws ⊓ wt),
intros b H_1,
cases H_1,
apply Bs _ ‹b ∈ s›,
apply Bt _ ‹b ∈ t›,
end⟩
/--Adding a point to a set preserves its boundedness below.-/
@[simp] lemma bdd_below_insert : bdd_below (insert a s) ↔ bdd_below s :=
⟨show bdd_below (insert a s) → bdd_below s, from bdd_below_subset (by simp only [set.subset_insert]),
show bdd_below s → bdd_below (insert a s),
by rw[insert_eq]; simp only [bdd_below_singleton, bdd_below_union, and_self, forall_true_iff] {contextual := tt}⟩
/--A finite set is bounded below.-/
lemma bdd_below_finite [nonempty α] (hs : finite s) : bdd_below s :=
finite.induction_on hs bdd_below_empty $ λ a s _ _, bdd_below_insert.2
/--A finite union of sets which are all bounded below is still bounded below.-/
lemma bdd_below_finite_union [nonempty α] {β : Type v} {I : set β} {S : β → set α} (H : finite I) :
(bdd_below (⋃i∈I, S i)) ↔ (∀i ∈ I, bdd_below (S i)) :=
⟨λ (bdd : bdd_below (⋃i∈I, S i)) i (hi : i ∈ I),
bdd_below_subset (subset_bUnion_of_mem hi) bdd,
show (∀i ∈ I, bdd_below (S i)) → (bdd_below (⋃i∈I, S i)), from
finite.induction_on H
(λ _, by rw bUnion_empty; exact bdd_below_empty)
(λ x s hn hf IH h, by simp only [
set.mem_insert_iff, or_imp_distrib, forall_and_distrib, forall_eq] at h;
rw [set.bUnion_insert, bdd_below_union]; exact ⟨h.1, IH h.2⟩)⟩
end semilattice_inf
namespace lattice
/-- A conditionally complete lattice is a lattice in which
every nonempty subset which is bounded above has a supremum, and
every nonempty subset which is bounded below has an infimum.
Typical examples are real numbers or natural numbers.
To differentiate the statements from the corresponding statements in (unconditional)
complete lattices, we prefix Inf and Sup by a c everywhere. The same statements should
hold in both worlds, sometimes with additional assumptions of non-emptyness or
boundedness.-/
class conditionally_complete_lattice (α : Type u) extends lattice α, has_Sup α, has_Inf α :=
(le_cSup : ∀s a, bdd_above s → a ∈ s → a ≤ Sup s)
(cSup_le : ∀s a, s ≠ ∅ → (∀b∈s, b ≤ a) → Sup s ≤ a)
(cInf_le : ∀s a, bdd_below s → a ∈ s → Inf s ≤ a)
(le_cInf : ∀s a, s ≠ ∅ → (∀b∈s, a ≤ b) → a ≤ Inf s)
class conditionally_complete_linear_order (α : Type u)
extends conditionally_complete_lattice α, decidable_linear_order α
class conditionally_complete_linear_order_bot (α : Type u)
extends conditionally_complete_lattice α, decidable_linear_order α, order_bot α :=
(cSup_empty : Sup ∅ = ⊥)
/- A complete lattice is a conditionally complete lattice, as there are no restrictions
on the properties of Inf and Sup in a complete lattice.-/
instance conditionally_complete_lattice_of_complete_lattice [complete_lattice α]:
conditionally_complete_lattice α :=
{ le_cSup := by intros; apply le_Sup; assumption,
cSup_le := by intros; apply Sup_le; assumption,
cInf_le := by intros; apply Inf_le; assumption,
le_cInf := by intros; apply le_Inf; assumption,
..‹complete_lattice α›}
instance conditionally_complete_linear_order_of_complete_linear_order [complete_linear_order α]:
conditionally_complete_linear_order α :=
{ ..lattice.conditionally_complete_lattice_of_complete_lattice, .. ‹complete_linear_order α› }
section conditionally_complete_lattice
variables [conditionally_complete_lattice α] {s t : set α} {a b : α}
theorem le_cSup (h₁ : bdd_above s) (h₂ : a ∈ s) : a ≤ Sup s :=
conditionally_complete_lattice.le_cSup s a h₁ h₂
theorem cSup_le (h₁ : s ≠ ∅) (h₂ : ∀b∈s, b ≤ a) : Sup s ≤ a :=
conditionally_complete_lattice.cSup_le s a h₁ h₂
theorem cInf_le (h₁ : bdd_below s) (h₂ : a ∈ s) : Inf s ≤ a :=
conditionally_complete_lattice.cInf_le s a h₁ h₂
theorem le_cInf (h₁ : s ≠ ∅) (h₂ : ∀b∈s, a ≤ b) : a ≤ Inf s :=
conditionally_complete_lattice.le_cInf s a h₁ h₂
theorem le_cSup_of_le (_ : bdd_above s) (hb : b ∈ s) (h : a ≤ b) : a ≤ Sup s :=
le_trans h (le_cSup ‹bdd_above s› hb)
theorem cInf_le_of_le (_ : bdd_below s) (hb : b ∈ s) (h : b ≤ a) : Inf s ≤ a :=
le_trans (cInf_le ‹bdd_below s› hb) h
theorem cSup_le_cSup (_ : bdd_above t) (_ : s ≠ ∅) (h : s ⊆ t) : Sup s ≤ Sup t :=
cSup_le ‹s ≠ ∅› (assume (a) (ha : a ∈ s), le_cSup ‹bdd_above t› (h ha))
theorem cInf_le_cInf (_ : bdd_below t) (_ :s ≠ ∅) (h : s ⊆ t) : Inf t ≤ Inf s :=
le_cInf ‹s ≠ ∅› (assume (a) (ha : a ∈ s), cInf_le ‹bdd_below t› (h ha))
theorem cSup_le_iff (_ : bdd_above s) (_ : s ≠ ∅) : Sup s ≤ a ↔ (∀b ∈ s, b ≤ a) :=
⟨assume (_ : Sup s ≤ a) (b) (_ : b ∈ s),
le_trans (le_cSup ‹bdd_above s› ‹b ∈ s›) ‹Sup s ≤ a›,
cSup_le ‹s ≠ ∅›⟩
theorem le_cInf_iff (_ : bdd_below s) (_ : s ≠ ∅) : a ≤ Inf s ↔ (∀b ∈ s, a ≤ b) :=
⟨assume (_ : a ≤ Inf s) (b) (_ : b ∈ s),
le_trans ‹a ≤ Inf s› (cInf_le ‹bdd_below s› ‹b ∈ s›),
le_cInf ‹s ≠ ∅›⟩
lemma cSup_upper_bounds_eq_cInf {s : set α} (h : bdd_below s) (hs : s ≠ ∅) :
Sup {a | ∀x∈s, a ≤ x} = Inf s :=
let ⟨b, hb⟩ := h, ⟨a, ha⟩ := ne_empty_iff_exists_mem.1 hs in
le_antisymm
(cSup_le (ne_empty_iff_exists_mem.2 ⟨b, hb⟩) $ assume a ha, le_cInf hs ha)
(le_cSup ⟨a, assume y hy, hy a ha⟩ $ assume x hx, cInf_le h hx)
lemma cInf_lower_bounds_eq_cSup {s : set α} (h : bdd_above s) (hs : s ≠ ∅) :
Inf {a | ∀x∈s, x ≤ a} = Sup s :=
let ⟨b, hb⟩ := h, ⟨a, ha⟩ := ne_empty_iff_exists_mem.1 hs in
le_antisymm
(cInf_le ⟨a, assume y hy, hy a ha⟩ $ assume x hx, le_cSup h hx)
(le_cInf (ne_empty_iff_exists_mem.2 ⟨b, hb⟩) $ assume a ha, cSup_le hs ha)
/--Introduction rule to prove that b is the supremum of s: it suffices to check that b
is larger than all elements of s, and that this is not the case of any w<b.-/
theorem cSup_intro (_ : s ≠ ∅) (_ : ∀a∈s, a ≤ b) (H : ∀w, w < b → (∃a∈s, w < a)) : Sup s = b :=
have bdd_above s := ⟨b, by assumption⟩,
have (Sup s < b) ∨ (Sup s = b) := lt_or_eq_of_le (cSup_le ‹s ≠ ∅› ‹∀a∈s, a ≤ b›),
have ¬(Sup s < b) :=
assume: Sup s < b,
let ⟨a, _, _⟩ := (H (Sup s) ‹Sup s < b›) in /- a ∈ s, Sup s < a-/
have Sup s < Sup s := lt_of_lt_of_le ‹Sup s < a› (le_cSup ‹bdd_above s› ‹a ∈ s›),
show false, by finish [lt_irrefl (Sup s)],
show Sup s = b, by finish
/--Introduction rule to prove that b is the infimum of s: it suffices to check that b
is smaller than all elements of s, and that this is not the case of any w>b.-/
theorem cInf_intro (_ : s ≠ ∅) (_ : ∀a∈s, b ≤ a) (H : ∀w, b < w → (∃a∈s, a < w)) : Inf s = b :=
have bdd_below s := ⟨b, by assumption⟩,
have (b < Inf s) ∨ (b = Inf s) := lt_or_eq_of_le (le_cInf ‹s ≠ ∅› ‹∀a∈s, b ≤ a›),
have ¬(b < Inf s) :=
assume: b < Inf s,
let ⟨a, _, _⟩ := (H (Inf s) ‹b < Inf s›) in /- a ∈ s, a < Inf s-/
have Inf s < Inf s := lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < Inf s› ,
show false, by finish [lt_irrefl (Inf s)],
show Inf s = b, by finish
/--When an element a of a set s is larger than all elements of the set, it is Sup s-/
theorem cSup_of_mem_of_le (_ : a ∈ s) (_ : ∀w∈s, w ≤ a) : Sup s = a :=
have bdd_above s := ⟨a, by assumption⟩,
have s ≠ ∅ := ne_empty_of_mem ‹a ∈ s›,
have A : a ≤ Sup s := le_cSup ‹bdd_above s› ‹a ∈ s›,
have B : Sup s ≤ a := cSup_le ‹s ≠ ∅› ‹∀w∈s, w ≤ a›,
le_antisymm B A
/--When an element a of a set s is smaller than all elements of the set, it is Inf s-/
theorem cInf_of_mem_of_le (_ : a ∈ s) (_ : ∀w∈s, a ≤ w) : Inf s = a :=
have bdd_below s := ⟨a, by assumption⟩,
have s ≠ ∅ := ne_empty_of_mem ‹a ∈ s›,
have A : Inf s ≤ a := cInf_le ‹bdd_below s› ‹a ∈ s›,
have B : a ≤ Inf s := le_cInf ‹s ≠ ∅› ‹∀w∈s, a ≤ w›,
le_antisymm A B
/--b < Sup s when there is an element a in s with b < a, when s is bounded above.
This is essentially an iff, except that the assumptions for the two implications are
slightly different (one needs boundedness above for one direction, nonemptyness and linear
order for the other one), so we formulate separately the two implications, contrary to
the complete_lattice case.-/
lemma lt_cSup_of_lt (_ : bdd_above s) (_ : a ∈ s) (_ : b < a) : b < Sup s :=
lt_of_lt_of_le ‹b < a› (le_cSup ‹bdd_above s› ‹a ∈ s›)
/--Inf s < b s when there is an element a in s with a < b, when s is bounded below.
This is essentially an iff, except that the assumptions for the two implications are
slightly different (one needs boundedness below for one direction, nonemptyness and linear
order for the other one), so we formulate separately the two implications, contrary to
the complete_lattice case.-/
lemma cInf_lt_of_lt (_ : bdd_below s) (_ : a ∈ s) (_ : a < b) : Inf s < b :=
lt_of_le_of_lt (cInf_le ‹bdd_below s› ‹a ∈ s›) ‹a < b›
/--The supremum of a singleton is the element of the singleton-/
@[simp] theorem cSup_singleton (a : α) : Sup {a} = a :=
have A : a ≤ Sup {a} :=
by apply le_cSup _ _; simp only [set.mem_singleton,bdd_above_singleton],
have B : Sup {a} ≤ a :=
by apply cSup_le _ _; simp only [set.mem_singleton_iff, forall_eq,ne.def, not_false_iff, set.singleton_ne_empty],
le_antisymm B A
/--The infimum of a singleton is the element of the singleton-/
@[simp] theorem cInf_singleton (a : α) : Inf {a} = a :=
have A : Inf {a} ≤ a :=
by apply cInf_le _ _; simp only [set.mem_singleton,bdd_below_singleton],
have B : a ≤ Inf {a} :=
by apply le_cInf _ _; simp only [set.mem_singleton_iff, forall_eq,ne.def, not_false_iff, set.singleton_ne_empty],
le_antisymm A B
/--If a set is bounded below and above, and nonempty, its infimum is less than or equal to
its supremum.-/
theorem cInf_le_cSup (_ : bdd_below s) (_ : bdd_above s) (_ : s ≠ ∅) : Inf s ≤ Sup s :=
let ⟨w, hw⟩ := exists_mem_of_ne_empty ‹s ≠ ∅› in /-hw : w ∈ s-/
have Inf s ≤ w := cInf_le ‹bdd_below s› ‹w ∈ s›,
have w ≤ Sup s := le_cSup ‹bdd_above s› ‹w ∈ s›,
le_trans ‹Inf s ≤ w› ‹w ≤ Sup s›
/--The sup of a union of sets is the max of the suprema of each subset, under the assumptions
that all sets are bounded above and nonempty.-/
theorem cSup_union (_ : bdd_above s) (_ : s ≠ ∅) (_ : bdd_above t) (_ : t ≠ ∅) :
Sup (s ∪ t) = Sup s ⊔ Sup t :=
have A : Sup (s ∪ t) ≤ Sup s ⊔ Sup t :=
have s ∪ t ≠ ∅ := by simp only [not_and, set.union_empty_iff, ne.def] at *; finish,
have F : ∀b∈ s∪t, b ≤ Sup s ⊔ Sup t :=
begin
intros,
cases H,
apply le_trans (le_cSup ‹bdd_above s› ‹b ∈ s›) _, simp only [lattice.le_sup_left],
apply le_trans (le_cSup ‹bdd_above t› ‹b ∈ t›) _, simp only [lattice.le_sup_right]
end,
cSup_le this F,
have B : Sup s ⊔ Sup t ≤ Sup (s ∪ t) :=
have Sup s ≤ Sup (s ∪ t) := by apply cSup_le_cSup _ ‹s ≠ ∅›; simp only [bdd_above_union,set.subset_union_left]; finish,
have Sup t ≤ Sup (s ∪ t) := by apply cSup_le_cSup _ ‹t ≠ ∅›; simp only [bdd_above_union,set.subset_union_right]; finish,
by simp only [lattice.sup_le_iff]; split; assumption; assumption,
le_antisymm A B
/--The inf of a union of sets is the min of the infima of each subset, under the assumptions
that all sets are bounded below and nonempty.-/
theorem cInf_union (_ : bdd_below s) (_ : s ≠ ∅) (_ : bdd_below t) (_ : t ≠ ∅) :
Inf (s ∪ t) = Inf s ⊓ Inf t :=
have A : Inf s ⊓ Inf t ≤ Inf (s ∪ t) :=
have s ∪ t ≠ ∅ := by simp only [not_and, set.union_empty_iff, ne.def] at *; finish,
have F : ∀b∈ s∪t, Inf s ⊓ Inf t ≤ b :=
begin
intros,
cases H,
apply le_trans _ (cInf_le ‹bdd_below s› ‹b ∈ s›), simp only [lattice.inf_le_left],
apply le_trans _ (cInf_le ‹bdd_below t› ‹b ∈ t›), simp only [lattice.inf_le_right]
end,
le_cInf this F,
have B : Inf (s ∪ t) ≤ Inf s ⊓ Inf t :=
have Inf (s ∪ t) ≤ Inf s := by apply cInf_le_cInf _ ‹s ≠ ∅›; simp only [bdd_below_union,set.subset_union_left]; finish,
have Inf (s ∪ t) ≤ Inf t := by apply cInf_le_cInf _ ‹t ≠ ∅›; simp only [bdd_below_union,set.subset_union_right]; finish,
by simp only [lattice.le_inf_iff]; split; assumption; assumption,
le_antisymm B A
/--The supremum of an intersection of sets is bounded by the minimum of the suprema of each
set, if all sets are bounded above and nonempty.-/
theorem cSup_inter_le (_ : bdd_above s) (_ : bdd_above t) (_ : s ∩ t ≠ ∅) :
Sup (s ∩ t) ≤ Sup s ⊓ Sup t :=
begin
apply cSup_le ‹s ∩ t ≠ ∅› _, simp only [lattice.le_inf_iff, and_imp, set.mem_inter_eq], intros b _ _, split,
apply le_cSup ‹bdd_above s› ‹b ∈ s›,
apply le_cSup ‹bdd_above t› ‹b ∈ t›
end
/--The infimum of an intersection of sets is bounded below by the maximum of the
infima of each set, if all sets are bounded below and nonempty.-/
theorem le_cInf_inter (_ : bdd_below s) (_ : bdd_below t) (_ : s ∩ t ≠ ∅) :
Inf s ⊔ Inf t ≤ Inf (s ∩ t) :=
begin
apply le_cInf ‹s ∩ t ≠ ∅› _, simp only [and_imp, set.mem_inter_eq, lattice.sup_le_iff], intros b _ _, split,
apply cInf_le ‹bdd_below s› ‹b ∈ s›,
apply cInf_le ‹bdd_below t› ‹b ∈ t›
end
/-- The supremum of insert a s is the maximum of a and the supremum of s, if s is
nonempty and bounded above.-/
theorem cSup_insert (_ : bdd_above s) (_ : s ≠ ∅) : Sup (insert a s) = a ⊔ Sup s :=
calc Sup (insert a s)
= Sup ({a} ∪ s) : by rw [insert_eq]
... = Sup {a} ⊔ Sup s : by apply cSup_union _ _ ‹bdd_above s› ‹s ≠ ∅›; simp only [ne.def, not_false_iff, set.singleton_ne_empty,bdd_above_singleton]
... = a ⊔ Sup s : by simp only [eq_self_iff_true, lattice.cSup_singleton]
/-- The infimum of insert a s is the minimum of a and the infimum of s, if s is
nonempty and bounded below.-/
theorem cInf_insert (_ : bdd_below s) (_ : s ≠ ∅) : Inf (insert a s) = a ⊓ Inf s :=
calc Inf (insert a s)
= Inf ({a} ∪ s) : by rw [insert_eq]
... = Inf {a} ⊓ Inf s : by apply cInf_union _ _ ‹bdd_below s› ‹s ≠ ∅›; simp only [ne.def, not_false_iff, set.singleton_ne_empty,bdd_below_singleton]
... = a ⊓ Inf s : by simp only [eq_self_iff_true, lattice.cInf_singleton]
@[simp] lemma cInf_interval [conditionally_complete_lattice α] : Inf {b | a ≤ b} = a :=
cInf_of_mem_of_le (by simp only [set.mem_set_of_eq]) (λw Hw, by simp only [set.mem_set_of_eq] at Hw; apply Hw)
@[simp] lemma cSup_interval [conditionally_complete_lattice α] : Sup {b | b ≤ a} = a :=
cSup_of_mem_of_le (by simp only [set.mem_set_of_eq]) (λw Hw, by simp only [set.mem_set_of_eq] at Hw; apply Hw)
/--The indexed supremum of two functions are comparable if the functions are pointwise comparable-/
lemma csupr_le_csupr {f g : β → α} (B : bdd_above (range g)) (H : ∀x, f x ≤ g x) : supr f ≤ supr g :=
begin
classical, by_cases nonempty β,
{ have Rf : range f ≠ ∅, {simpa},
apply cSup_le Rf,
rintros y ⟨x, rfl⟩,
have : g x ∈ range g := ⟨x, rfl⟩,
exact le_cSup_of_le B this (H x) },
{ have Rf : range f = ∅, {simpa},
have Rg : range g = ∅, {simpa},
unfold supr, rw [Rf, Rg] }
end
/--The indexed supremum of a function is bounded above by a uniform bound-/
lemma csupr_le [ne : nonempty β] {f : β → α} {c : α} (H : ∀x, f x ≤ c) : supr f ≤ c :=
cSup_le (by simp [not_not_intro ne]) (by rwa forall_range_iff)
/--The indexed supremum of a function is bounded below by the value taken at one point-/
lemma le_csupr {f : β → α} (H : bdd_above (range f)) {c : β} : f c ≤ supr f :=
le_cSup H (mem_range_self _)
/--The indexed infimum of two functions are comparable if the functions are pointwise comparable-/
lemma cinfi_le_cinfi {f g : β → α} (B : bdd_below (range f)) (H : ∀x, f x ≤ g x) : infi f ≤ infi g :=
begin
classical, by_cases nonempty β,
{ have Rg : range g ≠ ∅, {simpa},
apply le_cInf Rg,
rintros y ⟨x, rfl⟩,
have : f x ∈ range f := ⟨x, rfl⟩,
exact cInf_le_of_le B this (H x) },
{ have Rf : range f = ∅, {simpa},
have Rg : range g = ∅, {simpa},
unfold infi, rw [Rf, Rg] }
end
/--The indexed minimum of a function is bounded below by a uniform lower bound-/
lemma le_cinfi [ne : nonempty β] {f : β → α} {c : α} (H : ∀x, c ≤ f x) : c ≤ infi f :=
le_cInf (by simp [not_not_intro ne]) (by rwa forall_range_iff)
/--The indexed infimum of a function is bounded above by the value taken at one point-/
lemma cinfi_le {f : β → α} (H : bdd_below (range f)) {c : β} : infi f ≤ f c :=
cInf_le H (mem_range_self _)
lemma is_lub_cSup {s : set α} (ne : s ≠ ∅) (H : bdd_above s) : is_lub s (Sup s) :=
⟨assume x, le_cSup H, assume x, cSup_le ne⟩
lemma is_glb_cInf {s : set α} (ne : s ≠ ∅) (H : bdd_below s) : is_glb s (Inf s) :=
⟨assume x, cInf_le H, assume x, le_cInf ne⟩
@[simp] theorem cinfi_const [nonempty ι] {a : α} : (⨅ b:ι, a) = a :=
begin
rcases exists_mem_of_nonempty ι with ⟨x, _⟩,
refine le_antisymm (@cinfi_le _ _ _ _ _ x) (le_cinfi (λi, _root_.le_refl _)),
rw range_const,
exact bdd_below_singleton
end
@[simp] theorem csupr_const [nonempty ι] {a : α} : (⨆ b:ι, a) = a :=
begin
rcases exists_mem_of_nonempty ι with ⟨x, _⟩,
refine le_antisymm (csupr_le (λi, _root_.le_refl _)) (@le_csupr _ _ _ (λ b:ι, a) _ x),
rw range_const,
exact bdd_above_singleton
end
end conditionally_complete_lattice
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α] {s t : set α} {a b : α}
/--When b < Sup s, there is an element a in s with b < a, if s is nonempty and the order is
a linear order.-/
lemma exists_lt_of_lt_cSup (_ : s ≠ ∅) (_ : b < Sup s) : ∃a∈s, b < a :=
begin
classical, by_contra h,
have : Sup s ≤ b :=
by apply cSup_le ‹s ≠ ∅› _; finish,
apply lt_irrefl b (lt_of_lt_of_le ‹b < Sup s› ‹Sup s ≤ b›)
end
/--When Inf s < b, there is an element a in s with a < b, if s is nonempty and the order is
a linear order.-/
lemma exists_lt_of_cInf_lt (_ : s ≠ ∅) (_ : Inf s < b) : ∃a∈s, a < b :=
begin
classical, by_contra h,
have : b ≤ Inf s :=
by apply le_cInf ‹s ≠ ∅› _; finish,
apply lt_irrefl b (lt_of_le_of_lt ‹b ≤ Inf s› ‹Inf s < b›)
end
/--Introduction rule to prove that b is the supremum of s: it suffices to check that
1) b is an upper bound
2) every other upper bound b' satisfies b ≤ b'.-/
theorem cSup_intro' (_ : s ≠ ∅)
(h_is_ub : ∀ a ∈ s, a ≤ b) (h_b_le_ub : ∀ub, (∀ a ∈ s, a ≤ ub) → (b ≤ ub)) : Sup s = b :=
le_antisymm
(show Sup s ≤ b, from cSup_le ‹s ≠ ∅› h_is_ub)
(show b ≤ Sup s, from h_b_le_ub _ $ assume a, le_cSup ⟨b, h_is_ub⟩)
end conditionally_complete_linear_order
section conditionally_complete_linear_order_bot
variables [conditionally_complete_linear_order_bot α]
lemma cSup_empty [conditionally_complete_linear_order_bot α] : (Sup ∅ : α) = ⊥ :=
conditionally_complete_linear_order_bot.cSup_empty α
end conditionally_complete_linear_order_bot
section
local attribute [instance] classical.prop_decidable
noncomputable instance : has_Inf ℕ :=
⟨λs, if h : ∃n, n ∈ s then @nat.find (λn, n ∈ s) _ h else 0⟩
noncomputable instance : has_Sup ℕ :=
⟨λs, if h : ∃n, ∀a∈s, a ≤ n then @nat.find (λn, ∀a∈s, a ≤ n) _ h else 0⟩
lemma Inf_nat_def {s : set ℕ} (h : ∃n, n ∈ s) : Inf s = @nat.find (λn, n ∈ s) _ h :=
dif_pos _
lemma Sup_nat_def {s : set ℕ} (h : ∃n, ∀a∈s, a ≤ n) :
Sup s = @nat.find (λn, ∀a∈s, a ≤ n) _ h :=
dif_pos _
/-- This instance is necessary, otherwise the lattice operations would be derived via
conditionally_complete_linear_order_bot and marked as noncomputable. -/
instance : lattice ℕ := infer_instance
noncomputable instance : conditionally_complete_linear_order_bot ℕ :=
{ Sup := Sup, Inf := Inf,
le_cSup := assume s a hb ha, by rw [Sup_nat_def hb]; revert a ha; exact @nat.find_spec _ _ hb,
cSup_le := assume s a hs ha, by rw [Sup_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha,
le_cInf := assume s a hs hb,
by rw [Inf_nat_def (ne_empty_iff_exists_mem.1 hs)]; exact hb _ (@nat.find_spec (λn, n ∈ s) _ _),
cInf_le := assume s a hb ha, by rw [Inf_nat_def ⟨a, ha⟩]; exact nat.find_min' _ ha,
cSup_empty :=
begin
simp only [Sup_nat_def, set.mem_empty_eq, forall_const, forall_prop_of_false, not_false_iff, exists_const],
apply bot_unique (nat.find_min' _ _),
trivial
end,
.. (infer_instance : order_bot ℕ), .. (infer_instance : lattice ℕ),
.. (infer_instance : decidable_linear_order ℕ) }
end
end lattice /-end of namespace lattice-/
namespace with_top
open lattice
local attribute [instance] classical.prop_decidable
variables [conditionally_complete_linear_order_bot α]
lemma has_lub (s : set (with_top α)) : ∃a, is_lub s a :=
begin
by_cases hs : s = ∅, { subst hs, exact ⟨⊥, is_lub_empty⟩, },
rcases ne_empty_iff_exists_mem.1 hs with ⟨x, hxs⟩,
by_cases bnd : ∃b:α, ↑b ∈ upper_bounds s,
{ rcases bnd with ⟨b, hb⟩,
have bdd : bdd_above {a : α | ↑a ∈ s}, from ⟨b, assume y hy, coe_le_coe.1 $ hb _ hy⟩,
refine ⟨(Sup {a : α | ↑a ∈ s} : α), _, _⟩,
{ assume a has,
rcases (le_coe_iff _ _).1 (hb _ has) with ⟨a, rfl, h⟩,
exact (coe_le_coe.2 $ le_cSup bdd has) },
{ assume a hs,
rcases (le_coe_iff _ _).1 (hb _ hxs) with ⟨x, rfl, h⟩,
refine (coe_le_iff _ _).2 (assume c hc, _), subst hc,
exact (cSup_le (ne_empty_of_mem hxs) $ assume b (hbs : ↑b ∈ s), coe_le_coe.1 $ hs _ hbs), } },
exact ⟨⊤, assume a _, le_top, assume a,
match a with
| some a, ha := (bnd ⟨a, ha⟩).elim
| none, ha := _root_.le_refl ⊤
end⟩
end
lemma has_glb (s : set (with_top α)) : ∃a, is_glb s a :=
begin
by_cases hs : ∃x:α, ↑x ∈ s,
{ rcases hs with ⟨x, hxs⟩,
refine ⟨(Inf {a : α | ↑a ∈ s} : α), _, _⟩,
exact (assume a has, (coe_le_iff _ _).2 $ assume x hx, cInf_le (bdd_below_bot _) $
show ↑x ∈ s, from hx ▸ has),
{ assume a has,
rcases (le_coe_iff _ _).1 (has _ hxs) with ⟨x, rfl, h⟩,
exact (coe_le_coe.2 $ le_cInf (ne_empty_of_mem hxs) $
assume b hbs, coe_le_coe.1 $ has _ hbs) } },
exact ⟨⊤, assume a, match a with
| some a, ha := (hs ⟨a, ha⟩).elim
| none, ha := _root_.le_refl _
end,
assume a _, le_top⟩
end
noncomputable instance : has_Sup (with_top α) := ⟨λs, classical.some $ has_lub s⟩
noncomputable instance : has_Inf (with_top α) := ⟨λs, classical.some $ has_glb s⟩
lemma is_lub_Sup (s : set (with_top α)) : is_lub s (Sup s) := classical.some_spec _
lemma is_glb_Inf (s : set (with_top α)) : is_glb s (Inf s) := classical.some_spec _
noncomputable instance : complete_linear_order (with_top α) :=
{ Sup := Sup, le_Sup := assume s, (is_lub_Sup s).1, Sup_le := assume s, (is_lub_Sup s).2,
Inf := Inf, le_Inf := assume s, (is_glb_Inf s).2, Inf_le := assume s, (is_glb_Inf s).1,
decidable_le := classical.dec_rel _,
.. with_top.linear_order, ..with_top.lattice, ..with_top.order_top, ..with_top.order_bot }
lemma coe_Sup {s : set α} (hb : bdd_above s) : (↑(Sup s) : with_top α) = (⨆a∈s, ↑a) :=
begin
by_cases hs : s = ∅,
{ rw [hs, cSup_empty], simp only [set.mem_empty_eq, lattice.supr_bot, lattice.supr_false], refl },
apply le_antisymm,
{ refine ((coe_le_iff _ _).2 $ assume b hb, cSup_le hs $ assume a has, coe_le_coe.1 $ hb ▸ _),
exact (le_supr_of_le a $ le_supr_of_le has $ _root_.le_refl _) },
{ exact (supr_le $ assume a, supr_le $ assume ha, coe_le_coe.2 $ le_cSup hb ha) }
end
lemma coe_Inf {s : set α} (hs : s ≠ ∅) : (↑(Inf s) : with_top α) = (⨅a∈s, ↑a) :=
let ⟨x, hx⟩ := ne_empty_iff_exists_mem.1 hs in
have (⨅a∈s, ↑a : with_top α) ≤ x, from infi_le_of_le x $ infi_le_of_le hx $ _root_.le_refl _,
let ⟨r, r_eq, hr⟩ := (le_coe_iff _ _).1 this in
le_antisymm
(le_infi $ assume a, le_infi $ assume ha, coe_le_coe.2 $ cInf_le (bdd_below_bot s) ha)
begin
refine (r_eq.symm ▸ coe_le_coe.2 $ le_cInf hs $ assume a has, coe_le_coe.1 $ _),
refine (r_eq ▸ infi_le_of_le a _),
exact (infi_le_of_le has $ _root_.le_refl _),
end
end with_top
section order_dual
open lattice
instance (α : Type*) [conditionally_complete_lattice α] :
conditionally_complete_lattice (order_dual α) :=
{ le_cSup := @cInf_le α _,
cSup_le := @le_cInf α _,
le_cInf := @cSup_le α _,
cInf_le := @le_cSup α _,
..order_dual.lattice.has_Inf α,
..order_dual.lattice.has_Sup α,
..order_dual.lattice.lattice α }
instance (α : Type*) [conditionally_complete_linear_order α] :
conditionally_complete_linear_order (order_dual α) :=
{ ..order_dual.lattice.conditionally_complete_lattice α,
..order_dual.decidable_linear_order α }
end order_dual
|
cf8568a76d4cd07b21ac39b2925ac49e577fc164 | 271e26e338b0c14544a889c31c30b39c989f2e0f | /src/Init/Lean/Compiler/IR/UnboxResult.lean | f29cad655988308d9220e4061240f70474338b4a | [
"Apache-2.0"
] | permissive | dgorokho/lean4 | 805f99b0b60c545b64ac34ab8237a8504f89d7d4 | e949a052bad59b1c7b54a82d24d516a656487d8a | refs/heads/master | 1,607,061,363,851 | 1,578,006,086,000 | 1,578,006,086,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,000 | 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.Data.Format
import Init.Lean.Compiler.IR.Basic
import Init.Lean.Compiler.IR.CtorLayout
namespace Lean
namespace IR
namespace UnboxResult
def mkUnboxAttr : IO TagAttribute :=
registerTagAttribute `unbox "compiler tries to unbox result values if their types are tagged with `[unbox]`" $ fun env declName =>
match env.find? declName with
| none => Except.error "unknown declaration"
| some cinfo => match cinfo with
| ConstantInfo.inductInfo v =>
if v.isRec then Except.error "recursive inductive datatypes are not supported"
else Except.ok ()
| _ => Except.error "constant must be an inductive type"
@[init mkUnboxAttr]
constant unboxAttr : TagAttribute := arbitrary _
def hasUnboxAttr (env : Environment) (n : Name) : Bool :=
unboxAttr.hasTag env n
end UnboxResult
end IR
end Lean
|
c6e655c9adec9e6dee4800cbec5321453d3164c4 | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/data/finsupp.lean | 17130c1eec70fc96e67d4933c9fabfc2c6f38cb3 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 52,712 | 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
Type of functions with finite support.
Functions with finite support provide the basis for the following concrete instances:
* ℕ →₀ α: Polynomials (where α is a ring)
* (σ →₀ ℕ) →₀ α: Multivariate Polynomials (again α is a ring, and σ are variable names)
* α →₀ ℕ: Multisets
* α →₀ ℤ: Abelian groups freely generated by α
* β →₀ α: Linear combinations over β where α is the scalar ring
Most of the theory assumes that the range is a commutative monoid. This gives us the big sum
operator as a powerful way to construct `finsupp` elements.
A general advice is to not use α →₀ β directly, as the type class setup might not be fitting.
The best is to define a copy and select the instances best suited.
-/
import data.finset data.set.finite algebra.big_operators algebra.module
open finset
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Type*}
{α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*}
reserve infix ` →₀ `:25
/-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that
`f x = 0` for all but finitely many `x`. -/
structure finsupp (α : Type*) (β : Type*) [has_zero β] :=
(support : finset α)
(to_fun : α → β)
(mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0)
infix →₀ := finsupp
namespace finsupp
section basic
variable [has_zero β]
instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, finsupp.to_fun⟩
instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩
@[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 := rfl
@[simp] lemma support_zero : (0 : α →₀ β).support = ∅ := rfl
instance : inhabited (α →₀ β) := ⟨0⟩
@[simp] lemma mem_support_iff {f : α →₀ β} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 :=
f.mem_support_to_fun
lemma not_mem_support_iff {f : α →₀ β} {a} : a ∉ f.support ↔ f a = 0 :=
by haveI := classical.dec; exact not_iff_comm.1 mem_support_iff.symm
@[extensionality]
lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g
| ⟨s, f, hf⟩ ⟨t, g, hg⟩ h :=
begin
have : f = g, { funext a, exact h a },
subst this,
have : s = t, { ext a, exact (hf a).trans (hg a).symm },
subst this
end
lemma ext_iff {f g : α →₀ β} : f = g ↔ (∀a:α, f a = g a) :=
⟨by rintros rfl a; refl, ext⟩
@[simp] lemma support_eq_empty [decidable_eq β] {f : α →₀ β} : f.support = ∅ ↔ f = 0 :=
⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext.1 h a).1 $
mem_support_iff.2 H, by rintro rfl; refl⟩
instance [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) :=
assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a))
⟨assume ⟨h₁, h₂⟩, ext $ assume a,
if h : a ∈ f.support then h₂ a h else
have hf : f a = 0, by rwa [mem_support_iff, not_not] at h,
have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h,
by rw [hf, hg],
by rintro rfl; exact ⟨rfl, λ _ _, rfl⟩⟩
lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} :=
⟨set.fintype_of_finset f.support (λ _, mem_support_iff)⟩
lemma support_subset_iff {s : set α} {f : α →₀ β} [decidable_eq α] :
↑f.support ⊆ s ↔ (∀a∉s, f a = 0) :=
by simp only [set.subset_def, mem_coe, mem_support_iff];
exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _))
def equiv_fun_on_fintype [fintype α] [decidable_eq β]: (α →₀ β) ≃ (α → β) :=
⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp),
begin intro f, ext a, refl end,
begin intro f, ext a, refl end⟩
end basic
section single
variables [decidable_eq α] [decidable_eq β] [has_zero β] {a a' : α} {b : β}
/-- `single a b` is the finitely supported function which has
value `b` at `a` and zero otherwise. -/
def single (a : α) (b : β) : α →₀ β :=
⟨if b = 0 then ∅ else finset.singleton a, λ a', if a = a' then b else 0, λ a', begin
by_cases hb : b = 0; by_cases a = a';
simp only [hb, h, if_pos, if_false, mem_singleton],
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨λ _, hb, λ _, rfl⟩ },
{ exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ }
end⟩
lemma single_apply : (single a b : α →₀ β) a' = if a = a' then b else 0 := rfl
@[simp] lemma single_eq_same : (single a b : α →₀ β) a = b := if_pos rfl
@[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 := if_neg h
@[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, single_eq_same, zero_apply] },
{ rw [single_eq_of_ne h, zero_apply] }
end
lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} :=
if_neg hb
lemma support_single_subset : (single a b).support ⊆ {a} :=
show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _]
lemma injective_single (a : α) : function.injective (single a : β → α →₀ β) :=
assume b₁ b₂ eq,
have (single a b₁ : α →₀ β) a = (single a b₂ : α →₀ β) a, by rw eq,
by rwa [single_eq_same, single_eq_same] at this
lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : β) :
single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)):=
begin
split,
{ assume eq,
by_cases a₁ = a₂,
{ refine or.inl ⟨h, _⟩,
rwa [h, (injective_single a₂).eq_iff] at eq },
{ rw [finsupp.ext_iff] at eq,
have h₁ := eq a₁,
have h₂ := eq a₂,
simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂,
exact or.inr ⟨h₁, h₂.symm⟩ } },
{ rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩),
{ refl },
{ rw [single_zero, single_zero] } }
end
end single
section on_finset
variables [decidable_eq β] [has_zero β]
/-- `on_finset s f hf` is the finsupp function representing `f` restricted to the set `s`.
The function needs to be 0 outside of `s`. Use this when the set needs filtered anyway, otherwise
often better set representation is available. -/
def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β :=
⟨s.filter (λa, f a ≠ 0), f,
assume a, classical.by_cases
(assume h : f a = 0, by rw mem_filter; exact ⟨and.right, λ H, (H h).elim⟩)
(assume h : f a ≠ 0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩
@[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} :
(on_finset s f hf : α →₀ β) a = f a :=
rfl
@[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} :
(on_finset s f hf).support ⊆ s := filter_subset _
end on_finset
section map_range
variables [has_zero β₁] [has_zero β₂] [decidable_eq β₂]
/-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is
`map_range f hf g : α →₀ β₂`, well defined when `f 0 = 0`. -/
def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ :=
on_finset g.support (f ∘ g) $
assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf
@[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} :
map_range f hf g a = f (g a) :=
rfl
@[simp] lemma map_range_zero {f : β₁ → β₂} {hf : f 0 = 0} : map_range f hf (0 : α →₀ β₁) = 0 :=
finsupp.ext $ λ a, by simp [hf]
lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} :
(map_range f hf g).support ⊆ g.support :=
support_on_finset_subset
variables [decidable_eq α] [decidable_eq β₁]
@[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} :
map_range f hf (single a b) = single a (f b) :=
finsupp.ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf]
end map_range
section emb_domain
variables [has_zero β] [decidable_eq α₂]
/-- Given `f : α₁ ↪ α₂` and `v : α₁ →₀ β`, `emb_domain f v : α₂ →₀ β` is the finitely supported
function whose value at `f a : α₂` is `v a`. For a `a : α₁` outside the domain of `f` it is zero. -/
def emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
begin
refine ⟨v.support.map f, λa₂,
if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩,
{ rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩,
exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.inj hb) },
{ assume a₂,
split_ifs,
{ simp [h],
rw [← finsupp.not_mem_support_iff, classical.not_not],
apply finset.choose_mem },
{ simp [h] } }
end
lemma support_emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
(emb_domain f v).support = v.support.map f :=
rfl
lemma emb_domain_zero (f : α₁ ↪ α₂) : (emb_domain f 0 : α₂ →₀ β) = 0 :=
rfl
lemma emb_domain_apply (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₁) :
emb_domain f v (f a) = v a :=
begin
change dite _ _ _ = _,
split_ifs; rw [finset.mem_map' f] at h,
{ refine congr_arg (v : α₁ → β) (f.inj' _),
exact finset.choose_property (λa₁, f a₁ = f a) _ _ },
{ exact (finsupp.not_mem_support_iff.1 h).symm }
end
lemma emb_domain_notin_range (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
emb_domain f v a = 0 :=
begin
refine dif_neg (mt (assume h, _) h),
rcases finset.mem_map.1 h with ⟨a, h, rfl⟩,
exact set.mem_range_self a
end
lemma emb_domain_map_range
{β₁ β₂ : Type*} [has_zero β₁] [has_zero β₂] [decidable_eq β₁] [decidable_eq β₂]
(f : α₁ ↪ α₂) (g : β₁ → β₂) (p : α₁ →₀ β₁) (hg : g 0 = 0) :
emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) :=
begin
ext a,
classical,
by_cases a ∈ set.range f,
{ rcases h with ⟨a', rfl⟩,
rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] },
{ rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption }
end
end emb_domain
section zip_with
variables [has_zero β] [has_zero β₁] [has_zero β₂] [decidable_eq α] [decidable_eq β]
/-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying
`zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and well defined when `f 0 0 = 0`. -/
def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) :=
on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H, begin
haveI := classical.dec_eq β₁,
simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib],
rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf
end
@[simp] lemma zip_with_apply
{f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} :
zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) := rfl
lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} :
(zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support :=
support_on_finset_subset
end zip_with
section erase
variables [decidable_eq α] [decidable_eq β]
def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β :=
⟨f.support.erase a, (λa', if a' = a then 0 else f a'),
assume a', by rw [mem_erase, mem_support_iff]; split_ifs;
[exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩,
exact and_iff_right h]⟩
@[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} :
(f.erase a).support = f.support.erase a :=
rfl
@[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 :=
if_pos rfl
@[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' :=
if_neg h
end erase
-- [to_additive finsupp.sum] for finsupp.prod doesn't work, the equation lemmas are not generated
/-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/
def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
f.support.sum (λa, g a (f a))
/-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/
@[to_additive finsupp.sum]
def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
f.support.prod (λa, g a (f a))
attribute [to_additive finsupp.sum.equations._eqn_1] finsupp.prod.equations._eqn_1
@[to_additive finsupp.sum_map_range_index]
lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ] [decidable_eq β₂]
{f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) :
(map_range f hf g).prod h = g.prod (λa b, h a (f b)) :=
finset.prod_subset support_map_range $ λ _ _ H,
by rw [not_mem_support_iff.1 H, h0]
@[to_additive finsupp.sum_zero_index]
lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} :
(0 : α →₀ β).prod h = 1 := rfl
section decidable
variables [decidable_eq α] [decidable_eq β]
section add_monoid
variables [add_monoid β]
@[to_additive finsupp.sum_single_index]
lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) :
(single a b).prod h = h a b :=
begin
by_cases h : b = 0,
{ simp only [h, h_zero, single_zero]; refl },
{ simp only [finsupp.prod, support_single_ne_zero h, insert_empty_eq_singleton,
prod_singleton, single_eq_same] }
end
instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩
@[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a :=
rfl
lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support :=
support_zip_with
lemma support_add_eq {g₁ g₂ : α →₀ β} (h : disjoint g₁.support g₂.support):
(g₁ + g₂).support = g₁.support ∪ g₂.support :=
le_antisymm support_zip_with $ assume a ha,
(finset.mem_union.1 ha).elim
(assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, add_zero])
(assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, zero_add])
@[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] },
{ rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] }
end
instance : add_monoid (α →₀ β) :=
{ add_monoid .
zero := 0,
add := (+),
add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _,
zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _,
add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ }
instance (a : α) : is_add_monoid_hom (λ g : α →₀ β, g a) :=
{ map_add := λ _ _, add_apply, map_zero := zero_apply }
lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero]
else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)]
lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add]
else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)]
@[elab_as_eliminator]
protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma map_range_add [decidable_eq β₁] [decidable_eq β₂] [add_monoid β₁] [add_monoid β₂]
{f : β₁ → β₂} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ β₁) :
map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ :=
finsupp.ext $ λ a, by simp [hf']
end add_monoid
instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) :=
{ add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _,
.. finsupp.add_monoid }
instance [add_group β] : add_group (α →₀ β) :=
{ neg := map_range (has_neg.neg) neg_zero,
add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _,
.. finsupp.add_monoid }
lemma single_multiset_sum [add_comm_monoid β] [decidable_eq α] [decidable_eq β]
(s : multiset β) (a : α) : single a s.sum = (s.map (single a)).sum :=
multiset.induction_on s single_zero $ λ a s ih,
by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons]
lemma single_finset_sum [add_comm_monoid β] [decidable_eq α] [decidable_eq β]
(s : finset γ) (f : γ → β) (a : α) : single a (s.sum f) = s.sum (λb, single a (f b)) :=
begin
transitivity,
apply single_multiset_sum,
rw [multiset.map_map],
refl
end
lemma single_sum [has_zero γ] [add_comm_monoid β] [decidable_eq α] [decidable_eq β]
(s : δ →₀ γ) (f : δ → γ → β) (a : α) : single a (s.sum f) = s.sum (λd c, single a (f d c)) :=
single_finset_sum _ _ _
@[to_additive finsupp.sum_neg_index]
lemma prod_neg_index [add_group β] [comm_monoid γ]
{g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) :
(-g).prod h = g.prod (λa b, h a (- b)) :=
prod_map_range_index h0
@[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a := rfl
@[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a := rfl
@[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f :=
finset.subset.antisymm
support_map_range
(calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm
... ⊆ support (- f) : support_map_range)
instance [add_comm_group β] : add_comm_group (α →₀ β) :=
{ add_comm := add_comm, ..finsupp.add_group }
@[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} :
(f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) :=
(finset.sum_hom (λf : α →₀ β, f a₂)).symm
lemma support_sum [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} :
(f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) :=
have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 →
(∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0),
from assume a₁ h,
let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in
⟨a, mem_support_iff.mp ha, ne⟩,
by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop] using this
@[simp] lemma sum_zero [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} :
f.sum (λa b, (0 : γ)) = 0 :=
finset.sum_const_zero
@[simp] lemma sum_add [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ :=
finset.sum_add_distrib
@[simp] lemma sum_neg [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h :=
finset.sum_hom (@has_neg.neg γ _)
@[simp] lemma sum_sub [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ :=
by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl
@[simp] lemma sum_single [add_comm_monoid β] (f : α →₀ β) :
f.sum single = f :=
have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) =
({a} : finset α).sum (λa', ite (a' = a) (f a') 0),
begin
intro a,
by_cases h : a ∈ f.support,
{ have : (finset.singleton a : finset α) ⊆ f.support,
{ simpa only [finset.subset_iff, mem_singleton, forall_eq] },
refine (finset.sum_subset this (λ _ _ H, _)).symm,
exact if_neg (mt mem_singleton.2 H) },
{ transitivity (f.support.sum (λa, (0 : β))),
{ refine (finset.sum_congr rfl $ λ a' ha', if_neg _),
rintro rfl, exact h ha' },
{ rw [sum_const_zero, insert_empty_eq_singleton, sum_singleton,
if_pos rfl, not_mem_support_iff.1 h] } }
end,
ext $ assume a, by simp only [sum_apply, single_apply, this,
insert_empty_eq_singleton, sum_singleton, if_pos]
@[to_additive finsupp.sum_add_index]
lemma prod_add_index [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f + g).prod h = f.prod h * g.prod h :=
have f_eq : (f.support ∪ g.support).prod (λa, h a (f a)) = f.prod h,
from (finset.prod_subset (finset.subset_union_left _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
have g_eq : (f.support ∪ g.support).prod (λa, h a (g a)) = g.prod h,
from (finset.prod_subset (finset.subset_union_right _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
calc (f + g).support.prod (λa, h a ((f + g) a)) =
(f.support ∪ g.support).prod (λa, h a ((f + g) a)) :
finset.prod_subset support_add $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]
... = (f.support ∪ g.support).prod (λa, h a (f a)) *
(f.support ∪ g.support).prod (λa, h a (g a)) :
by simp only [add_apply, h_add, finset.prod_mul_distrib]
... = _ : by rw [f_eq, g_eq]
lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β}
{h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) :
(f - g).sum h = f.sum h - g.sum h :=
have h_zero : ∀a, h a 0 = 0,
from assume a,
have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0,
by simpa only [sub_self] using this,
have h_neg : ∀a b, h a (- b) = - h a b,
from assume a b,
have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b,
by simpa only [h_zero, zero_sub] using this,
have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂,
from assume a b₁ b₂,
have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂),
by simpa only [h_neg, sub_neg_eq_add] using this,
calc (f - g).sum h = (f + - g).sum h : rfl
... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero, h_neg, sum_neg]
... = f.sum h - g.sum h : rfl
@[to_additive finsupp.sum_finset_sum_index]
lemma prod_finset_sum_index [add_comm_monoid β] [comm_monoid γ] [decidable_eq ι]
{s : finset ι} {g : ι → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂):
s.prod (λi, (g i).prod h) = (s.sum g).prod h :=
finset.induction_on s rfl $ λ a s has ih,
by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add]
@[to_additive finsupp.sum_sum_index]
lemma prod_sum_index
[decidable_eq α₁] [add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂):
(f.sum g).prod h = f.prod (λa b, (g a b).prod h) :=
(prod_finset_sum_index h_zero h_add).symm
lemma multiset_sum_sum_index
[decidable_eq α] [decidable_eq β] [add_comm_monoid β] [add_comm_monoid γ]
(f : multiset (α →₀ β)) (h : α → β → γ)
(h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : β), h a (b₁ + b₂) = h a b₁ + h a b₂) :
(f.sum.sum h) = (f.map $ λg:α →₀ β, g.sum h).sum :=
multiset.induction_on f rfl $ assume a s ih,
by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih]
lemma multiset_map_sum [has_zero β] {f : α →₀ β} {m : γ → δ} {h : α → β → multiset γ} :
multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) :=
(finset.sum_hom _).symm
lemma multiset_sum_sum [has_zero β] [add_comm_monoid γ] {f : α →₀ β} {h : α → β → multiset γ} :
multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) :=
(finset.sum_hom multiset.sum).symm
section map_range
variables
[decidable_eq β₁] [decidable_eq β₂] [add_comm_monoid β₁] [add_comm_monoid β₂]
(f : β₁ → β₂) [hf : is_add_monoid_hom f]
instance is_add_monoid_hom_map_range :
is_add_monoid_hom (map_range f hf.map_zero : (α →₀ β₁) → (α →₀ β₂)) :=
{ map_zero := map_range_zero, map_add := λ a b, map_range_add hf.map_add _ _ }
lemma map_range_multiset_sum (m : multiset (α →₀ β₁)) :
map_range f hf.map_zero m.sum = (m.map $ λx, map_range f hf.map_zero x).sum :=
(m.sum_hom (map_range f hf.map_zero)).symm
lemma map_range_finset_sum {ι : Type*} [decidable_eq ι] (s : finset ι) (g : ι → (α →₀ β₁)) :
map_range f hf.map_zero (s.sum g) = s.sum (λx, map_range f hf.map_zero (g x)) :=
by rw [finset.sum.equations._eqn_1, map_range_multiset_sum, multiset.map_map]; refl
end map_range
section map_domain
variables [decidable_eq α₁] [decidable_eq α₂] [add_comm_monoid β] {v v₁ v₂ : α →₀ β}
/-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β`
is the finitely supported function whose value at `a : α₂` is the sum
of `v x` over all `x` such that `f x = a`. -/
def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
v.sum $ λa, single (f a)
lemma map_domain_apply {f : α₁ → α₂} (hf : function.injective f) (x : α₁ →₀ β) (a : α₁) :
map_domain f x (f a) = x a :=
begin
rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same],
{ assume b _ hba, exact single_eq_of_ne (hf.ne hba) },
{ simp only [(∉), (≠), not_not, mem_support_iff],
assume h,
rw [h, single_zero],
refl }
end
lemma map_domain_notin_range {f : α₁ → α₂} (x : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
map_domain f x a = 0 :=
begin
rw [map_domain, sum_apply, sum],
exact finset.sum_eq_zero
(assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _)
end
lemma map_domain_id : map_domain id v = v := sum_single _
lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} :
map_domain (g ∘ f) v = map_domain g (map_domain f v) :=
begin
refine ((sum_sum_index _ _).trans _).symm,
{ intros, exact single_zero },
{ intros, exact single_add },
refine sum_congr rfl (λ _ _, sum_single_index _),
{ exact single_zero }
end
lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b :=
sum_single_index single_zero
@[simp] lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) :=
sum_zero_index
lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) :
v.map_domain f = v.map_domain g :=
finset.sum_congr rfl $ λ _ H, by simp only [h _ H]
lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ :=
sum_add_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_finset_sum [decidable_eq ι] {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} :
map_domain f (s.sum v) = s.sum (λi, map_domain f (v i)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} :
map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_support {f : α → α₂} {s : α →₀ β} :
(s.map_domain f).support ⊆ s.support.image f :=
finset.subset.trans support_sum $
finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $
by rw [finset.bind_singleton]; exact subset.refl _
@[to_additive finsupp.sum_map_domain_index]
lemma prod_map_domain_index [comm_monoid γ] {f : α → α₂} {s : α →₀ β}
{h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(s.map_domain f).prod h = s.prod (λa b, h (f a) b) :=
(prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _)
lemma emb_domain_eq_map_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
emb_domain f v = map_domain f v :=
begin
ext a,
classical,
by_cases a ∈ set.range f,
{ rcases h with ⟨a, rfl⟩,
rw [map_domain_apply (function.embedding.inj' _), emb_domain_apply] },
{ rw [map_domain_notin_range, emb_domain_notin_range]; assumption }
end
lemma injective_map_domain {f : α₁ → α₂} (hf : function.injective f) :
function.injective (map_domain f : (α₁ →₀ β) → (α₂ →₀ β)) :=
begin
assume v₁ v₂ eq, ext a,
have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq },
rwa [map_domain_apply hf, map_domain_apply hf] at this,
end
end map_domain
/-- The product of `f g : α →₀ β` is the finitely supported function
whose value at `a` is the sum of `f x * g y` over all pairs `x, y`
such that `x + y = a`. (Think of the product of multivariate
polynomials where `α` is the monoid of monomial exponents.) -/
instance [has_add α] [semiring β] : has_mul (α →₀ β) :=
⟨λf g, f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)⟩
lemma mul_def [has_add α] [semiring β] {f g : α →₀ β} :
f * g = (f.sum $ λa₁ b₁, g.sum $ λa₂ b₂, single (a₁ + a₂) (b₁ * b₂)) := rfl
lemma support_mul [has_add α] [semiring β] (a b : α →₀ β) :
(a * b).support ⊆ a.support.bind (λa₁, b.support.bind $ λa₂, {a₁ + a₂}) :=
subset.trans support_sum $ bind_mono $ assume a₁ _,
subset.trans support_sum $ bind_mono $ assume a₂ _, support_single_subset
/-- The unit of the multiplication is `single 0 1`, i.e. the function
that is 1 at 0 and zero elsewhere. -/
instance [has_zero α] [has_zero β] [has_one β] : has_one (α →₀ β) :=
⟨single 0 1⟩
lemma one_def [has_zero α] [has_zero β] [has_one β] : 1 = (single 0 1 : α →₀ β) := rfl
section filter
section has_zero
variables [has_zero β] (p : α → Prop) [decidable_pred p] (f : α →₀ β)
/-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/
def filter (p : α → Prop) [decidable_pred p] (f : α →₀ β) : α →₀ β :=
on_finset f.support (λa, if p a then f a else 0) $ λ a H,
mem_support_iff.2 $ λ h, by rw [h, if_t_t] at H; exact H rfl
@[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a :=
if_pos h
@[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 :=
if_neg h
@[simp] lemma support_filter : (f.filter p).support = f.support.filter p :=
finset.ext.mpr $ assume a, if H : p a
then by simp only [mem_support_iff, filter_apply_pos _ _ H, mem_filter, H, and_true]
else by simp only [mem_support_iff, filter_apply_neg _ _ H, mem_filter, H, and_false, ne.def, ne_self_iff_false]
lemma filter_zero : (0 : α →₀ β).filter p = 0 :=
by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty]
@[simp] lemma filter_single_of_pos
{a : α} {b : β} (h : p a) : (single a b).filter p = single a b :=
finsupp.ext $ λ x, begin
by_cases h' : p x; simp [h'],
rw single_eq_of_ne, rintro rfl, exact h' h
end
@[simp] lemma filter_single_of_neg
{a : α} {b : β} (h : ¬ p a) : (single a b).filter p = 0 :=
finsupp.ext $ λ x, begin
by_cases h' : p x; simp [h'],
rw single_eq_of_ne, rintro rfl, exact h h'
end
end has_zero
lemma filter_pos_add_filter_neg [add_monoid β] (f : α →₀ β) (p : α → Prop) [decidable_pred p] :
f.filter p + f.filter (λa, ¬ p a) = f :=
finsupp.ext $ assume a, if H : p a
then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero]
else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add]
end filter
section frange
variables [has_zero β]
def frange (f : α →₀ β) : finset β :=
finset.image f f.support
theorem mem_frange {f : α →₀ β} {y : β} :
y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y :=
finset.mem_image.trans
⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩,
λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩
theorem zero_not_mem_frange {f : α →₀ β} : (0:β) ∉ f.frange :=
λ H, (mem_frange.1 H).1 rfl
theorem frange_single {x : α} {y : β} : frange (single x y) ⊆ {y} :=
λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸
(by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc])
end frange
section subtype_domain
variables {α' : Type*} [has_zero δ] {p : α → Prop} [decidable_pred p]
section zero
variables [has_zero β] {v v' : α' →₀ β}
/-- `subtype_domain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtype_domain (p : α → Prop) [decidable_pred p] (f : α →₀ β) : (subtype p →₀ β) :=
⟨f.support.subtype p, f ∘ subtype.val, λ a, by simp only [mem_subtype, mem_support_iff]⟩
@[simp] lemma support_subtype_domain {f : α →₀ β} :
(subtype_domain p f).support = f.support.subtype p :=
rfl
@[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} :
(subtype_domain p v) a = v (a.val) :=
rfl
@[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 :=
rfl
@[to_additive finsupp.sum_subtype_domain_index]
lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β}
{h : α → β → γ} (hp : ∀x∈v.support, p x) :
(v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h :=
prod_bij (λp _, p.val)
(λ _, mem_subtype.1)
(λ _ _, rfl)
(λ _ _ _ _, subtype.eq)
(λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩)
end zero
section monoid
variables [add_monoid β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_add {v v' : α →₀ β} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ λ _, rfl
instance subtype_domain.is_add_monoid_hom [add_monoid β] :
is_add_monoid_hom (subtype_domain p : (α →₀ β) → subtype p →₀ β) :=
{ map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero }
@[simp] lemma filter_add {v v' : α →₀ β} :
(v + v').filter p = v.filter p + v'.filter p :=
ext $ λ a, by by_cases p a; simp [h]
instance filter.is_add_monoid_hom (p : α → Prop) [decidable_pred p] :
is_add_monoid_hom (filter p : (α →₀ β) → (α →₀ β)) :=
{ map_zero := filter_zero p, map_add := λ x y, filter_add }
end monoid
section comm_monoid
variables [add_comm_monoid β]
lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) :=
eq.symm (finset.sum_hom _)
lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) :=
subtype_domain_sum
lemma filter_sum (s : finset γ) (f : γ → α →₀ β) :
(s.sum f).filter p = s.sum (λa, filter p (f a)) :=
(finset.sum_hom (filter p)).symm
end comm_monoid
section group
variables [add_group β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_neg {v : α →₀ β} :
(- v).subtype_domain p = - v.subtype_domain p :=
ext $ λ _, rfl
@[simp] lemma subtype_domain_sub {v v' : α →₀ β} :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ λ _, rfl
end group
end subtype_domain
section multiset
def to_multiset (f : α →₀ ℕ) : multiset α :=
f.sum (λa n, add_monoid.smul n {a})
lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 :=
rfl
lemma to_multiset_add (m n : α →₀ ℕ) :
(m + n).to_multiset = m.to_multiset + n.to_multiset :=
sum_add_index (assume a, add_monoid.zero_smul _) (assume a b₁ b₂, add_monoid.add_smul _ _ _)
lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = add_monoid.smul n {a} :=
by rw [to_multiset, sum_single_index]; apply add_monoid.zero_smul
instance is_add_monoid_hom.to_multiset : is_add_monoid_hom (to_multiset : _ → multiset α) :=
{ map_zero := to_multiset_zero, map_add := to_multiset_add }
lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.card_zero, sum_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.card_add, ih, sum_add_index, to_multiset_single,
sum_single_index, multiset.card_smul, multiset.singleton_eq_singleton,
multiset.card_singleton, mul_one]; intros; refl }
end
lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) :
f.to_multiset.map g = (f.map_domain g).to_multiset :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single,
to_multiset_single, to_multiset_add, to_multiset_single,
is_add_monoid_hom.map_smul (multiset.map g)],
refl }
end
lemma prod_to_multiset [comm_monoid α] (f : α →₀ ℕ) :
f.to_multiset.prod = f.prod (λa n, a ^ n) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index,
finsupp.prod_single_index, multiset.prod_smul, multiset.singleton_eq_singleton,
multiset.prod_singleton],
{ exact pow_zero a },
{ exact pow_zero },
{ exact pow_add } }
end
lemma to_finset_to_multiset (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.to_finset_zero, support_zero] },
{ assume a n f ha hn ih,
rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq,
support_single_ne_zero hn, multiset.to_finset_smul _ _ hn,
multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero],
refl,
refine disjoint_mono support_single_subset (subset.refl _) _,
rwa [finset.singleton_eq_singleton, finset.singleton_disjoint] }
end
@[simp] lemma count_to_multiset [decidable_eq α] (f : α →₀ ℕ) (a : α) :
f.to_multiset.count a = f a :=
calc f.to_multiset.count a = f.sum (λx n, (add_monoid.smul n {x} : multiset α).count a) :
(finset.sum_hom _).symm
... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul]
... = f.sum (λx n, n * (x :: 0 : multiset α).count a) : rfl
... = f a * (a :: 0 : multiset α).count a : sum_eq_single _
(λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero])
(λ H, by simp only [not_mem_support_iff.1 H, zero_mul])
... = f a : by simp only [multiset.count_singleton, mul_one]
def of_multiset [decidable_eq α] (m : multiset α) : α →₀ ℕ :=
on_finset m.to_finset (λa, m.count a) $ λ a H, multiset.mem_to_finset.2 $
by_contradiction (mt multiset.count_eq_zero.2 H)
@[simp] lemma of_multiset_apply [decidable_eq α] (m : multiset α) (a : α) :
of_multiset m a = m.count a :=
rfl
def equiv_multiset [decidable_eq α] : (α →₀ ℕ) ≃ (multiset α) :=
⟨ to_multiset, of_multiset,
assume f, finsupp.ext $ λ a, by rw [of_multiset_apply, count_to_multiset],
assume m, multiset.ext.2 $ λ a, by rw [count_to_multiset, of_multiset_apply] ⟩
lemma mem_support_multiset_sum [decidable_eq α] [decidable_eq β] [add_comm_monoid β]
{s : multiset (α →₀ β)} (a : α) :
a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ β).support :=
multiset.induction_on s false.elim
begin
assume f s ih ha,
by_cases a ∈ f.support,
{ exact ⟨f, multiset.mem_cons_self _ _, h⟩ },
{ simp only [multiset.sum_cons, mem_support_iff, add_apply,
not_mem_support_iff.1 h, zero_add] at ha,
rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩,
exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ }
end
lemma mem_support_finset_sum [decidable_eq α] [decidable_eq β] [add_comm_monoid β]
{s : finset γ} {h : γ → α →₀ β} (a : α) (ha : a ∈ (s.sum h).support) : ∃c∈s, a ∈ (h c).support :=
let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in
let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in
⟨c, hc, eq.symm ▸ hfa⟩
lemma mem_support_single [decidable_eq α] [decidable_eq β] [has_zero β] (a a' : α) (b : β) :
a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 :=
⟨λ H : (a ∈ ite _ _ _), if h : b = 0
then by rw if_pos h at H; exact H.elim
else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩,
λ ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩
end multiset
section curry_uncurry
protected def curry [decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ]
(f : (α × β) →₀ γ) : α →₀ (β →₀ γ) :=
f.sum $ λp c, single p.1 (single p.2 c)
lemma sum_curry_index
[decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ] [add_comm_monoid δ]
(f : (α × β) →₀ γ) (g : α → β → γ → δ)
(hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) :
f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) :=
begin
rw [finsupp.curry],
transitivity,
{ exact sum_sum_index (assume a, sum_zero_index)
(assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) },
congr, funext p c,
transitivity,
{ exact sum_single_index sum_zero_index },
exact sum_single_index (hg₀ _ _)
end
protected def uncurry [decidable_eq α] [decidable_eq β] [decidable_eq γ] [add_comm_monoid γ]
(f : α →₀ (β →₀ γ)) : (α × β) →₀ γ :=
f.sum $ λa g, g.sum $ λb c, single (a, b) c
def finsupp_prod_equiv [add_comm_monoid γ] [decidable_eq α] [decidable_eq β] [decidable_eq γ] :
((α × β) →₀ γ) ≃ (α →₀ (β →₀ γ)) :=
by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [
finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff,
forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single]
lemma filter_curry [decidable_eq α₁] [decidable_eq α₂] [add_comm_monoid β]
(f : α₁ × α₂ →₀ β) (p : α₁ → Prop) [decidable_pred p] :
(f.filter (λa:α₁×α₂, p a.1)).curry = f.curry.filter p :=
begin
rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum,
@filter_sum _ (α₂ →₀ β) _ _ _ p _ _ f.support _],
rw [support_filter, sum_filter],
refine finset.sum_congr rfl _,
rintros ⟨a₁, a₂⟩ ha,
dsimp only,
split_ifs,
{ rw [filter_apply_pos, filter_single_of_pos]; exact h },
{ rwa [filter_single_of_neg] }
end
lemma support_curry
[decidable_eq α₁] [decidable_eq α₂] [add_comm_monoid β] (f : α₁ × α₂ →₀ β) :
f.curry.support ⊆ f.support.image prod.fst :=
begin
rw ← finset.bind_singleton,
refine finset.subset.trans support_sum _,
refine finset.bind_mono (assume a _, support_single_subset)
end
end curry_uncurry
section
variables [add_monoid α] [semiring β]
-- TODO: the simplifier unfolds 0 in the instance proof!
private lemma zero_mul (f : α →₀ β) : 0 * f = 0 := by simp only [mul_def, sum_zero_index]
private lemma mul_zero (f : α →₀ β) : f * 0 = 0 := by simp only [mul_def, sum_zero_index, sum_zero]
private lemma left_distrib (a b c : α →₀ β) : a * (b + c) = a * b + a * c :=
by simp only [mul_def, sum_add_index, mul_add, _root_.mul_zero, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_add]
private lemma right_distrib (a b c : α →₀ β) : (a + b) * c = a * c + b * c :=
by simp only [mul_def, sum_add_index, add_mul, _root_.mul_zero, _root_.zero_mul, single_zero, single_add,
eq_self_iff_true, forall_true_iff, forall_3_true_iff, sum_zero, sum_add]
def to_semiring : semiring (α →₀ β) :=
{ one := 1,
mul := (*),
one_mul := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.zero_mul, single_zero, sum_zero,
zero_add, one_mul, sum_single],
mul_one := assume f, by simp only [mul_def, one_def, sum_single_index, _root_.mul_zero, single_zero, sum_zero,
add_zero, mul_one, sum_single],
zero_mul := zero_mul,
mul_zero := mul_zero,
mul_assoc := assume f g h, by simp only [mul_def, sum_sum_index, sum_zero_index, sum_add_index, sum_single_index,
single_zero, single_add, eq_self_iff_true, forall_true_iff, forall_3_true_iff,
add_mul, mul_add, add_assoc, mul_assoc, _root_.zero_mul, _root_.mul_zero, sum_zero, sum_add],
left_distrib := left_distrib,
right_distrib := right_distrib,
.. finsupp.add_comm_monoid }
end
local attribute [instance] to_semiring
def to_comm_semiring [add_comm_monoid α] [comm_semiring β] : comm_semiring (α →₀ β) :=
{ mul_comm := assume f g,
begin
simp only [mul_def, finsupp.sum, mul_comm],
rw [finset.sum_comm],
simp only [add_comm]
end,
.. finsupp.to_semiring }
local attribute [instance] to_comm_semiring
def to_ring [add_monoid α] [ring β] : ring (α →₀ β) :=
{ neg := has_neg.neg,
add_left_neg := add_left_neg,
.. finsupp.to_semiring }
def to_comm_ring [add_comm_monoid α] [comm_ring β] : comm_ring (α →₀ β) :=
{ mul_comm := mul_comm, .. finsupp.to_ring}
lemma single_mul_single [has_add α] [semiring β] {a₁ a₂ : α} {b₁ b₂ : β}:
single a₁ b₁ * single a₂ b₂ = single (a₁ + a₂) (b₁ * b₂) :=
(sum_single_index (by simp only [_root_.zero_mul, single_zero, sum_zero])).trans
(sum_single_index (by rw [_root_.mul_zero, single_zero]))
lemma prod_single [decidable_eq ι] [add_comm_monoid α] [comm_semiring β]
{s : finset ι} {a : ι → α} {b : ι → β} :
s.prod (λi, single (a i) (b i)) = single (s.sum a) (s.prod b) :=
finset.induction_on s rfl $ λ a s has ih, by rw [prod_insert has, ih,
single_mul_single, sum_insert has, prod_insert has]
section
variables (α β)
def to_has_scalar' [R:semiring γ] [add_comm_monoid β] [semimodule γ β] : has_scalar γ (α →₀ β) := ⟨λa v, v.map_range ((•) a) (smul_zero _)⟩
local attribute [instance] to_has_scalar'
@[simp] lemma smul_apply' {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {a : α} {b : γ} {v : α →₀ β} :
(b • v) a = b • (v a) := rfl
def to_semimodule {R:semiring γ} [add_comm_monoid β] [semimodule γ β] : semimodule γ (α →₀ β) :=
{ smul := (•),
smul_add := λ a x y, finsupp.ext $ λ _, smul_add _ _ _,
add_smul := λ a x y, finsupp.ext $ λ _, add_smul _ _ _,
one_smul := λ x, finsupp.ext $ λ _, one_smul _ _,
mul_smul := λ r s x, finsupp.ext $ λ _, mul_smul _ _ _,
zero_smul := λ x, finsupp.ext $ λ _, zero_smul _ _,
smul_zero := λ x, finsupp.ext $ λ _, smul_zero _ }
def to_module {R:ring γ} [add_comm_group β] [module γ β] : module γ (α →₀ β) :=
{ ..to_semimodule α β }
variables {α β}
lemma support_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {g : α →₀ β} :
(b • g).support ⊆ g.support :=
λ a, by simp; exact mt (λ h, h.symm ▸ smul_zero _)
section
variables {α' : Type*} [has_zero δ] {p : α → Prop} [decidable_pred p]
@[simp] lemma filter_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β]
{b : γ} {v : α →₀ β} : (b • v).filter p = b • v.filter p :=
ext $ λ a, by by_cases p a; simp [h]
end
lemma map_domain_smul {α'} [decidable_eq α'] {R:semiring γ} [add_comm_monoid β] [semimodule γ β]
{f : α → α'} (b : γ) (v : α →₀ β) : map_domain f (b • v) = b • map_domain f v :=
begin
change map_domain f (map_range _ _ _) = map_range _ _ _,
apply finsupp.induction v, {simp},
intros a b v' hv₁ hv₂ IH,
rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add,
map_range_single, map_domain_single, map_domain_single, map_range_single];
apply smul_add
end
@[simp] lemma smul_single {R:semiring γ} [add_comm_monoid β] [semimodule γ β]
(c : γ) (a : α) (b : β) : c • finsupp.single a b = finsupp.single a (c • b) :=
ext $ λ a', by by_cases a = a'; [{subst h, simp}, simp [h]]
end
def to_has_scalar [ring β] : has_scalar β (α →₀ β) := to_has_scalar' α β
local attribute [instance] to_has_scalar
@[simp] lemma smul_apply [ring β] {a : α} {b : β} {v : α →₀ β} :
(b • v) a = b • (v a) := rfl
lemma sum_smul_index [ring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ}
(h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) :=
finsupp.sum_map_range_index h0
end decidable
section
variables [semiring β] [semiring γ]
lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} :
(s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) :=
by simp only [finsupp.sum, finset.sum_mul]
lemma mul_sum (b : γ) (s : α →₀ β) {f : α → β → γ} :
b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) :=
by simp only [finsupp.sum, finset.mul_sum]
end
def restrict_support_equiv [decidable_eq α] [decidable_eq β] [add_comm_monoid β]
(s : set α) [decidable_pred (λx, x ∈ s)] :
{f : α →₀ β // ↑f.support ⊆ s } ≃ (s →₀ β):=
begin
refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩,
{ refine set.subset.trans (finset.coe_subset.2 map_domain_support) _,
rw [finset.coe_image, set.image_subset_iff],
exact assume x hx, x.2 },
{ rintros ⟨f, hf⟩,
apply subtype.eq,
ext a,
dsimp only,
refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _),
{ rcases h with ⟨x, rfl⟩,
rw [map_domain_apply subtype.val_injective, subtype_domain_apply] },
{ convert map_domain_notin_range _ _ h,
rw [← not_mem_support_iff],
refine mt _ h,
exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } },
{ assume f,
ext ⟨a, ha⟩,
dsimp only,
rw [subtype_domain_apply, map_domain_apply subtype.val_injective] }
end
protected def dom_congr [decidable_eq α₁] [decidable_eq α₂] [decidable_eq β] [add_comm_monoid β]
(e : α₁ ≃ α₂) : (α₁ →₀ β) ≃ (α₂ →₀ β) :=
⟨map_domain e, map_domain e.symm,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply],
exact map_domain_id
end,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply],
exact map_domain_id
end⟩
end finsupp
|
4f9796159d79050202d8291022db2c9356e073c9 | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/algebra/order/hom/basic.lean | b36d1b7a0876037d2e4c6a4efccf9836eae7881c | [
"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 | 2,476 | lean | /-
Copyright (c) 2022 Yaël Dillies. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yaël Dillies
-/
import algebra.hom.group
import algebra.order.with_zero
import order.hom.basic
/-!
# Algebraic order homomorphism classes
This file defines hom classes for common properties at the intersection of order theory and algebra.
## Typeclasses
* `nonneg_hom_class`: Homs are nonnegative: `∀ f a, 0 ≤ f a`
* `subadditive_hom_class`: Homs are subadditive: `∀ f a b, f (a + b) ≤ f a + f b`
* `submultiplicative_hom_class`: Homs are submultiplicative: `∀ f a b, f (a * b) ≤ f a * f b`
* `mul_le_add_hom_class`: `∀ f a b, f (a * b) ≤ f a + f b`
-/
set_option old_structure_cmd true
open function
variables {F α β γ δ : Type*}
/-- `nonneg_hom_class F α β` states that `F` is a type of nonnegative morphisms. -/
class nonneg_hom_class (F : Type*) (α β : out_param $ Type*) [has_zero β] [has_le β]
extends fun_like F α (λ _, β) :=
(map_nonneg (f : F) : ∀ a, 0 ≤ f a)
/-- `subadditive_hom_class F α β` states that `F` is a type of subadditive morphisms. -/
class subadditive_hom_class (F : Type*) (α β : out_param $ Type*) [has_add α] [has_add β] [has_le β]
extends fun_like F α (λ _, β) :=
(map_add_le_add (f : F) : ∀ a b, f (a + b) ≤ f a + f b)
/-- `submultiplicative_hom_class F α β` states that `F` is a type of submultiplicative morphisms. -/
@[to_additive subadditive_hom_class]
class submultiplicative_hom_class (F : Type*) (α β : out_param $ Type*) [has_mul α] [has_mul β]
[has_le β] extends fun_like F α (λ _, β) :=
(map_mul_le_mul (f : F) : ∀ a b, f (a * b) ≤ f a * f b)
/-- `map_add_le_class F α β` states that `F` is a type of subadditive morphisms. -/
@[to_additive subadditive_hom_class]
class mul_le_add_hom_class (F : Type*) (α β : out_param $ Type*) [has_mul α] [has_add β] [has_le β]
extends fun_like F α (λ _, β) :=
(map_mul_le_add (f : F) : ∀ a b, f (a * b) ≤ f a + f b)
export nonneg_hom_class (map_nonneg)
export subadditive_hom_class (map_add_le_add)
export submultiplicative_hom_class (map_mul_le_mul)
export mul_le_add_hom_class (map_mul_le_add)
attribute [simp] map_nonneg
@[to_additive] lemma le_map_add_map_div [group α] [add_comm_semigroup β] [has_le β]
[mul_le_add_hom_class F α β] (f : F) (a b : α) : f a ≤ f b + f (a / b) :=
by simpa only [add_comm, div_mul_cancel'] using map_mul_le_add f (a / b) b
|
fee3feac822b89b03b325eade2b0cdce379cc061 | e030b0259b777fedcdf73dd966f3f1556d392178 | /tests/lean/run/apply4.lean | a5d27f44e848302a4fe211dab97a898d0cca8830 | [
"Apache-2.0"
] | permissive | fgdorais/lean | 17b46a095b70b21fa0790ce74876658dc5faca06 | c3b7c54d7cca7aaa25328f0a5660b6b75fe26055 | refs/heads/master | 1,611,523,590,686 | 1,484,412,902,000 | 1,484,412,902,000 | 38,489,734 | 0 | 0 | null | 1,435,923,380,000 | 1,435,923,379,000 | null | UTF-8 | Lean | false | false | 1,000 | lean | open tactic bool
universe variables u
constant foo {A : Type u} [inhabited A] (a b : A) : a = default A → a = b
example (a b : nat) : a = 0 → a = b :=
by do
intro `H,
apply (expr.const `foo [level.of_nat 1]),
trace_state,
assumption
definition ex : inhabited (nat × nat × bool) :=
by apply_instance
set_option pp.all true
print ex
set_option pp.all false
example (a b : nat) : a = 0 → a = b :=
by do
intro `H,
apply_core semireducible tt ff (expr.const `foo [level.of_nat 1]),
trace_state,
a ← get_local `a,
trace_state,
mk_app `inhabited.mk [a] >>= exact,
trace "--------",
trace_state,
reflexivity
print "----------------"
set_option pp.all true
example (a b : nat) : a = 0 → a = b :=
by do
intro `H,
foo ← mk_const `foo,
trace foo,
apply foo,
trace_state,
assumption
example (a b : nat) : a = 0 → a = b :=
by do
`[intro],
apply_core semireducible tt ff (expr.const `foo [level.of_nat 1]),
`[exact inhabited.mk a],
reflexivity
|
f8358f8604e7a58b0c2928205cf3508137e6086d | 05b503addd423dd68145d68b8cde5cd595d74365 | /src/data/finsupp.lean | acd3c1f30e6f8ffe24aa229d6ecea70be4132e7d | [
"Apache-2.0"
] | permissive | aestriplex/mathlib | 77513ff2b176d74a3bec114f33b519069788811d | e2fa8b2b1b732d7c25119229e3cdfba8370cb00f | refs/heads/master | 1,621,969,960,692 | 1,586,279,279,000 | 1,586,279,279,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 66,449 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Scott Morrison
-/
import data.finset data.set.finite algebra.big_operators algebra.module
/-!
# Type of functions with finite support
For any type `α` and a type `β` with zero, we define the type `finsupp α β` of finitely supported
functions from `α` to `β`, i.e. the functions which are zero everywhere on `α` except on a finite
set. We write this in infix notation as `α →₀ β`.
Functions with finite support provide the basis for the following concrete instances:
* `ℕ →₀ α`: Polynomials (where `α` is a ring)
* `(σ →₀ ℕ) →₀ α`: Multivariate Polynomials (again `α` is a ring, and `σ` are variable names)
* `α →₀ ℕ`: Multisets
* `α →₀ ℤ`: Abelian groups freely generated by `α`
* `β →₀ α`: Linear combinations over `β` where `α` is the scalar ring
Most of the theory assumes that the range is a commutative monoid. This gives us the big sum
operator as a powerful way to construct `finsupp` elements.
A general piece of advice is to not use `α →₀ β` directly, as the type class setup might not be a
good fit. Defining a copy and selecting the instances that are best suited for the application works
better.
## Implementation notes
This file is a `noncomputable theory` and uses classical logic throughout.
## Notation
This file defines `α →₀ β` as notation for `finsupp α β`.
-/
noncomputable theory
open_locale classical
open finset
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Type*}
{α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*}
/-- `finsupp α β`, denoted `α →₀ β`, is the type of functions `f : α → β` such that
`f x = 0` for all but finitely many `x`. -/
structure finsupp (α : Type*) (β : Type*) [has_zero β] :=
(support : finset α)
(to_fun : α → β)
(mem_support_to_fun : ∀a, a ∈ support ↔ to_fun a ≠ 0)
infixr ` →₀ `:25 := finsupp
namespace finsupp
/-! ### Basic declarations about `finsupp` -/
section basic
variable [has_zero β]
instance : has_coe_to_fun (α →₀ β) := ⟨λ_, α → β, to_fun⟩
instance : has_zero (α →₀ β) := ⟨⟨∅, (λ_, 0), λ _, ⟨false.elim, λ H, H rfl⟩⟩⟩
@[simp] lemma zero_apply {a : α} : (0 : α →₀ β) a = 0 :=
rfl
@[simp] lemma support_zero : (0 : α →₀ β).support = ∅ :=
rfl
instance : inhabited (α →₀ β) := ⟨0⟩
@[simp] lemma mem_support_iff {f : α →₀ β} : ∀{a:α}, a ∈ f.support ↔ f a ≠ 0 :=
f.mem_support_to_fun
lemma not_mem_support_iff {f : α →₀ β} {a} : a ∉ f.support ↔ f a = 0 :=
not_iff_comm.1 mem_support_iff.symm
@[ext]
lemma ext : ∀{f g : α →₀ β}, (∀a, f a = g a) → f = g
| ⟨s, f, hf⟩ ⟨t, g, hg⟩ h :=
begin
have : f = g, { funext a, exact h a },
subst this,
have : s = t, { ext a, exact (hf a).trans (hg a).symm },
subst this
end
lemma ext_iff {f g : α →₀ β} : f = g ↔ (∀a:α, f a = g a) :=
⟨by rintros rfl a; refl, ext⟩
@[simp] lemma support_eq_empty {f : α →₀ β} : f.support = ∅ ↔ f = 0 :=
⟨assume h, ext $ assume a, by_contradiction $ λ H, (finset.ext.1 h a).1 $
mem_support_iff.2 H, by rintro rfl; refl⟩
instance finsupp.decidable_eq [decidable_eq α] [decidable_eq β] : decidable_eq (α →₀ β) :=
assume f g, decidable_of_iff (f.support = g.support ∧ (∀a∈f.support, f a = g a))
⟨assume ⟨h₁, h₂⟩, ext $ assume a,
if h : a ∈ f.support then h₂ a h else
have hf : f a = 0, by rwa [mem_support_iff, not_not] at h,
have hg : g a = 0, by rwa [h₁, mem_support_iff, not_not] at h,
by rw [hf, hg],
by rintro rfl; exact ⟨rfl, λ _ _, rfl⟩⟩
lemma finite_supp (f : α →₀ β) : set.finite {a | f a ≠ 0} :=
⟨fintype.of_finset f.support (λ _, mem_support_iff)⟩
lemma support_subset_iff {s : set α} {f : α →₀ β} :
↑f.support ⊆ s ↔ (∀a∉s, f a = 0) :=
by simp only [set.subset_def, mem_coe, mem_support_iff];
exact forall_congr (assume a, @not_imp_comm _ _ (classical.dec _) (classical.dec _))
/-- Given `fintype α`, `equiv_fun_on_fintype` is the `equiv` between `α →₀ β` and `α → β`.
(All functions on a finite type are finitely supported.) -/
def equiv_fun_on_fintype [fintype α] : (α →₀ β) ≃ (α → β) :=
⟨λf a, f a, λf, mk (finset.univ.filter $ λa, f a ≠ 0) f (by simp only [true_and, finset.mem_univ,
iff_self, finset.mem_filter, finset.filter_congr_decidable, forall_true_iff]),
begin intro f, ext a, refl end,
begin intro f, ext a, refl end⟩
end basic
/-! ### Declarations about `single` -/
section single
variables [has_zero β] {a a' : α} {b : β}
/-- `single a b` is the finitely supported function which has
value `b` at `a` and zero otherwise. -/
def single (a : α) (b : β) : α →₀ β :=
⟨if b = 0 then ∅ else finset.singleton a, λ a', if a = a' then b else 0, λ a', begin
by_cases hb : b = 0; by_cases a = a';
simp only [hb, h, if_pos, if_false, mem_singleton],
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨false.elim, λ H, H rfl⟩ },
{ exact ⟨λ _, hb, λ _, rfl⟩ },
{ exact ⟨λ H _, h H.symm, λ H, (H rfl).elim⟩ }
end⟩
lemma single_apply : (single a b : α →₀ β) a' = if a = a' then b else 0 :=
rfl
@[simp] lemma single_eq_same : (single a b : α →₀ β) a = b :=
if_pos rfl
@[simp] lemma single_eq_of_ne (h : a ≠ a') : (single a b : α →₀ β) a' = 0 :=
if_neg h
@[simp] lemma single_zero : (single a 0 : α →₀ β) = 0 :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, single_eq_same, zero_apply] },
{ rw [single_eq_of_ne h, zero_apply] }
end
lemma support_single_ne_zero (hb : b ≠ 0) : (single a b).support = {a} :=
if_neg hb
lemma support_single_subset : (single a b).support ⊆ {a} :=
show ite _ _ _ ⊆ _, by split_ifs; [exact empty_subset _, exact subset.refl _]
lemma injective_single (a : α) : function.injective (single a : β → α →₀ β) :=
assume b₁ b₂ eq,
have (single a b₁ : α →₀ β) a = (single a b₂ : α →₀ β) a, by rw eq,
by rwa [single_eq_same, single_eq_same] at this
lemma single_eq_single_iff (a₁ a₂ : α) (b₁ b₂ : β) :
single a₁ b₁ = single a₂ b₂ ↔ ((a₁ = a₂ ∧ b₁ = b₂) ∨ (b₁ = 0 ∧ b₂ = 0)) :=
begin
split,
{ assume eq,
by_cases a₁ = a₂,
{ refine or.inl ⟨h, _⟩,
rwa [h, (injective_single a₂).eq_iff] at eq },
{ rw [ext_iff] at eq,
have h₁ := eq a₁,
have h₂ := eq a₂,
simp only [single_eq_same, single_eq_of_ne h, single_eq_of_ne (ne.symm h)] at h₁ h₂,
exact or.inr ⟨h₁, h₂.symm⟩ } },
{ rintros (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩),
{ refl },
{ rw [single_zero, single_zero] } }
end
lemma single_right_inj (h : b ≠ 0) :
single a b = single a' b ↔ a = a' :=
⟨λ H, by simpa only [h, single_eq_single_iff,
and_false, or_false, eq_self_iff_true, and_true] using H,
λ H, by rw [H]⟩
lemma single_eq_zero : single a b = 0 ↔ b = 0 :=
⟨λ h, by { rw ext_iff at h, simpa only [single_eq_same, zero_apply] using h a },
λ h, by rw [h, single_zero]⟩
lemma single_swap {α β : Type*} [has_zero β] (a₁ a₂ : α) (b : β) :
(single a₁ b : α → β) a₂ = (single a₂ b : α → β) a₁ :=
by simp only [single_apply]; ac_refl
lemma unique_single [unique α] (x : α →₀ β) : x = single (default α) (x (default α)) :=
by ext i; simp only [unique.eq_default i, single_eq_same]
@[simp] lemma unique_single_eq_iff [unique α] {b' : β} :
single a b = single a' b' ↔ b = b' :=
begin
rw [single_eq_single_iff],
split,
{ rintros (⟨_, rfl⟩ | ⟨rfl, rfl⟩); refl },
{ intro h, left, exact ⟨subsingleton.elim _ _, h⟩ }
end
end single
/-! ### Declarations about `on_finset` -/
section on_finset
variables [has_zero β]
/-- `on_finset s f hf` is the finsupp function representing `f` restricted to the finset `s`.
The function needs to be `0` outside of `s`. Use this when the set needs to be filtered anyways,
otherwise a better set representation is often available. -/
def on_finset (s : finset α) (f : α → β) (hf : ∀a, f a ≠ 0 → a ∈ s) : α →₀ β :=
⟨s.filter (λa, f a ≠ 0), f,
assume a, classical.by_cases
(assume h : f a = 0, by rw mem_filter; exact ⟨and.right, λ H, (H h).elim⟩)
(assume h : f a ≠ 0, by rw mem_filter; simp only [iff_true_intro h, hf a h, true_and])⟩
@[simp] lemma on_finset_apply {s : finset α} {f : α → β} {hf a} :
(on_finset s f hf : α →₀ β) a = f a :=
rfl
@[simp] lemma support_on_finset_subset {s : finset α} {f : α → β} {hf} :
(on_finset s f hf).support ⊆ s :=
filter_subset _
end on_finset
/-! ### Declarations about `map_range` -/
section map_range
variables [has_zero β₁] [has_zero β₂]
/-- The composition of `f : β₁ → β₂` and `g : α →₀ β₁` is
`map_range f hf g : α →₀ β₂`, well-defined when `f 0 = 0`. -/
def map_range (f : β₁ → β₂) (hf : f 0 = 0) (g : α →₀ β₁) : α →₀ β₂ :=
on_finset g.support (f ∘ g) $
assume a, by rw [mem_support_iff, not_imp_not]; exact λ H, (congr_arg f H).trans hf
@[simp] lemma map_range_apply {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {a : α} :
map_range f hf g a = f (g a) :=
rfl
@[simp] lemma map_range_zero {f : β₁ → β₂} {hf : f 0 = 0} : map_range f hf (0 : α →₀ β₁) = 0 :=
ext $ λ a, by simp only [hf, zero_apply, map_range_apply]
lemma support_map_range {f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} :
(map_range f hf g).support ⊆ g.support :=
support_on_finset_subset
@[simp] lemma map_range_single {f : β₁ → β₂} {hf : f 0 = 0} {a : α} {b : β₁} :
map_range f hf (single a b) = single a (f b) :=
ext $ λ a', show f (ite _ _ _) = ite _ _ _, by split_ifs; [refl, exact hf]
end map_range
/-! ### Declarations about `emb_domain` -/
section emb_domain
variables [has_zero β]
/-- Given `f : α₁ ↪ α₂` and `v : α₁ →₀ β`, `emb_domain f v : α₂ →₀ β`
is the finitely supported function whose value at `f a : α₂` is `v a`.
For a `b : α₂` outside the range of `f`, it is zero. -/
def emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
begin
refine ⟨v.support.map f, λa₂,
if h : a₂ ∈ v.support.map f then v (v.support.choose (λa₁, f a₁ = a₂) _) else 0, _⟩,
{ rcases finset.mem_map.1 h with ⟨a, ha, rfl⟩,
exact exists_unique.intro a ⟨ha, rfl⟩ (assume b ⟨_, hb⟩, f.inj hb) },
{ assume a₂,
split_ifs,
{ simp only [h, true_iff, ne.def],
rw [← not_mem_support_iff, not_not],
apply finset.choose_mem },
{ simp only [h, ne.def, ne_self_iff_false] } }
end
lemma support_emb_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
(emb_domain f v).support = v.support.map f :=
rfl
lemma emb_domain_zero (f : α₁ ↪ α₂) : (emb_domain f 0 : α₂ →₀ β) = 0 :=
rfl
lemma emb_domain_apply (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₁) :
emb_domain f v (f a) = v a :=
begin
change dite _ _ _ = _,
split_ifs; rw [finset.mem_map' f] at h,
{ refine congr_arg (v : α₁ → β) (f.inj' _),
exact finset.choose_property (λa₁, f a₁ = f a) _ _ },
{ exact (not_mem_support_iff.1 h).symm }
end
lemma emb_domain_notin_range (f : α₁ ↪ α₂) (v : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
emb_domain f v a = 0 :=
begin
refine dif_neg (mt (assume h, _) h),
rcases finset.mem_map.1 h with ⟨a, h, rfl⟩,
exact set.mem_range_self a
end
lemma emb_domain_inj {f : α₁ ↪ α₂} {l₁ l₂ : α₁ →₀ β} :
emb_domain f l₁ = emb_domain f l₂ ↔ l₁ = l₂ :=
⟨λ h, ext $ λ a, by simpa only [emb_domain_apply] using ext_iff.1 h (f a),
λ h, by rw h⟩
lemma emb_domain_map_range
{β₁ β₂ : Type*} [has_zero β₁] [has_zero β₂]
(f : α₁ ↪ α₂) (g : β₁ → β₂) (p : α₁ →₀ β₁) (hg : g 0 = 0) :
emb_domain f (map_range g hg p) = map_range g hg (emb_domain f p) :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a', rfl⟩,
rw [map_range_apply, emb_domain_apply, emb_domain_apply, map_range_apply] },
{ rw [map_range_apply, emb_domain_notin_range, emb_domain_notin_range, ← hg]; assumption }
end
lemma single_of_emb_domain_single
(l : α₁ →₀ β) (f : α₁ ↪ α₂) (a : α₂) (b : β) (hb : b ≠ 0)
(h : l.emb_domain f = single a b) :
∃ x, l = single x b ∧ f x = a :=
begin
have h_map_support : finset.map f (l.support) = finset.singleton a,
by rw [←support_emb_domain, h, support_single_ne_zero hb]; refl,
have ha : a ∈ finset.map f (l.support),
by simp only [h_map_support, finset.mem_singleton],
rcases finset.mem_map.1 ha with ⟨c, hc₁, hc₂⟩,
use c,
split,
{ ext d,
rw [← emb_domain_apply f l, h],
by_cases h_cases : c = d,
{ simp only [eq.symm h_cases, hc₂, single_eq_same] },
{ rw [single_apply, single_apply, if_neg, if_neg h_cases],
by_contra hfd,
exact h_cases (f.inj (hc₂.trans hfd)) } },
{ exact hc₂ }
end
end emb_domain
/-! ### Declarations about `zip_with` -/
section zip_with
variables [has_zero β] [has_zero β₁] [has_zero β₂]
/-- `zip_with f hf g₁ g₂` is the finitely supported function satisfying
`zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a)`, and it is well-defined when `f 0 0 = 0`. -/
def zip_with (f : β₁ → β₂ → β) (hf : f 0 0 = 0) (g₁ : α →₀ β₁) (g₂ : α →₀ β₂) : (α →₀ β) :=
on_finset (g₁.support ∪ g₂.support) (λa, f (g₁ a) (g₂ a)) $ λ a H,
begin
simp only [mem_union, mem_support_iff, ne], rw [← not_and_distrib],
rintro ⟨h₁, h₂⟩, rw [h₁, h₂] at H, exact H hf
end
@[simp] lemma zip_with_apply
{f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} {a : α} :
zip_with f hf g₁ g₂ a = f (g₁ a) (g₂ a) :=
rfl
lemma support_zip_with {f : β₁ → β₂ → β} {hf : f 0 0 = 0} {g₁ : α →₀ β₁} {g₂ : α →₀ β₂} :
(zip_with f hf g₁ g₂).support ⊆ g₁.support ∪ g₂.support :=
support_on_finset_subset
end zip_with
/-! ### Declarations about `erase` -/
section erase
/-- `erase a f` is the finitely supported function equal to `f` except at `a` where it is equal to
`0`. -/
def erase [has_zero β] (a : α) (f : α →₀ β) : α →₀ β :=
⟨f.support.erase a, (λa', if a' = a then 0 else f a'),
assume a', by rw [mem_erase, mem_support_iff]; split_ifs;
[exact ⟨λ H _, H.1 h, λ H, (H rfl).elim⟩,
exact and_iff_right h]⟩
@[simp] lemma support_erase [has_zero β] {a : α} {f : α →₀ β} :
(f.erase a).support = f.support.erase a :=
rfl
@[simp] lemma erase_same [has_zero β] {a : α} {f : α →₀ β} : (f.erase a) a = 0 :=
if_pos rfl
@[simp] lemma erase_ne [has_zero β] {a a' : α} {f : α →₀ β} (h : a' ≠ a) : (f.erase a) a' = f a' :=
if_neg h
@[simp] lemma erase_single [has_zero β] {a : α} {b : β} : (erase a (single a b)) = 0 := begin
ext s, by_cases hs : s = a,
{ rw [hs, erase_same], refl },
{ rw [erase_ne hs], exact single_eq_of_ne (ne.symm hs) }
end
lemma erase_single_ne [has_zero β] {a a' : α} {b : β} (h : a ≠ a') : (erase a (single a' b)) = single a' b :=
begin
ext s, by_cases hs : s = a,
{ rw [hs, erase_same, single_eq_of_ne (h.symm)] },
{ rw [erase_ne hs] }
end
end erase
/-!
### Declarations about `sum` and `prod`
In most of this section, the domain `β` is assumed to be an `add_monoid`.
-/
-- [to_additive sum] for finsupp.prod doesn't work, the equation lemmas are not generated
/-- `sum f g` is the sum of `g a (f a)` over the support of `f`. -/
def sum [has_zero β] [add_comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
f.support.sum (λa, g a (f a))
/-- `prod f g` is the product of `g a (f a)` over the support of `f`. -/
@[to_additive]
def prod [has_zero β] [comm_monoid γ] (f : α →₀ β) (g : α → β → γ) : γ :=
f.support.prod (λa, g a (f a))
@[to_additive]
lemma prod_map_range_index [has_zero β₁] [has_zero β₂] [comm_monoid γ]
{f : β₁ → β₂} {hf : f 0 = 0} {g : α →₀ β₁} {h : α → β₂ → γ} (h0 : ∀a, h a 0 = 1) :
(map_range f hf g).prod h = g.prod (λa b, h a (f b)) :=
finset.prod_subset support_map_range $ λ _ _ H,
by rw [not_mem_support_iff.1 H, h0]
@[to_additive]
lemma prod_zero_index [add_comm_monoid β] [comm_monoid γ] {h : α → β → γ} :
(0 : α →₀ β).prod h = 1 :=
rfl
@[to_additive]
lemma prod_comm {α' : Type*} [has_zero β] {β' : Type*} [has_zero β'] (f : α →₀ β) (g : α' →₀ β') [comm_monoid γ] (h : α → β → α' → β' → γ) :
f.prod (λ x v, g.prod (λ x' v', h x v x' v')) = g.prod (λ x' v', f.prod (λ x v, h x v x' v')) :=
begin
dsimp [finsupp.prod],
rw finset.prod_comm,
end
@[simp, to_additive]
lemma prod_ite_eq [has_zero β] [comm_monoid γ] (f : α →₀ β) (a : α) (b : α → β → γ) :
f.prod (λ x v, ite (a = x) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 :=
by { dsimp [finsupp.prod], rw f.support.prod_ite_eq, }
/-- A restatement of `prod_ite_eq` with the equality test reversed. -/
@[simp, to_additive "A restatement of `sum_ite_eq` with the equality test reversed."]
lemma prod_ite_eq' [has_zero β] [comm_monoid γ] (f : α →₀ β) (a : α) (b : α → β → γ) :
f.prod (λ x v, ite (x = a) (b x v) 1) = ite (a ∈ f.support) (b a (f a)) 1 :=
by { dsimp [finsupp.prod], rw f.support.prod_ite_eq', }
section add_monoid
variables [add_monoid β]
@[to_additive]
lemma prod_single_index [comm_monoid γ] {a : α} {b : β} {h : α → β → γ} (h_zero : h a 0 = 1) :
(single a b).prod h = h a b :=
begin
by_cases h : b = 0,
{ simp only [h, h_zero, single_zero]; refl },
{ simp only [finsupp.prod, support_single_ne_zero h, insert_empty_eq_singleton,
prod_singleton, single_eq_same] }
end
instance : has_add (α →₀ β) := ⟨zip_with (+) (add_zero 0)⟩
@[simp] lemma add_apply {g₁ g₂ : α →₀ β} {a : α} : (g₁ + g₂) a = g₁ a + g₂ a :=
rfl
lemma support_add {g₁ g₂ : α →₀ β} : (g₁ + g₂).support ⊆ g₁.support ∪ g₂.support :=
support_zip_with
lemma support_add_eq {g₁ g₂ : α →₀ β} (h : disjoint g₁.support g₂.support) :
(g₁ + g₂).support = g₁.support ∪ g₂.support :=
le_antisymm support_zip_with $ assume a ha,
(finset.mem_union.1 ha).elim
(assume ha, have a ∉ g₂.support, from disjoint_left.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, add_zero])
(assume ha, have a ∉ g₁.support, from disjoint_right.1 h ha,
by simp only [mem_support_iff, not_not] at *;
simpa only [add_apply, this, zero_add])
@[simp] lemma single_add {a : α} {b₁ b₂ : β} : single a (b₁ + b₂) = single a b₁ + single a b₂ :=
ext $ assume a',
begin
by_cases h : a = a',
{ rw [h, add_apply, single_eq_same, single_eq_same, single_eq_same] },
{ rw [add_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h, zero_add] }
end
instance : add_monoid (α →₀ β) :=
{ add_monoid .
zero := 0,
add := (+),
add_assoc := assume ⟨s, f, hf⟩ ⟨t, g, hg⟩ ⟨u, h, hh⟩, ext $ assume a, add_assoc _ _ _,
zero_add := assume ⟨s, f, hf⟩, ext $ assume a, zero_add _,
add_zero := assume ⟨s, f, hf⟩, ext $ assume a, add_zero _ }
instance (a : α) : is_add_monoid_hom (λ g : α →₀ β, g a) :=
{ map_add := λ _ _, add_apply, map_zero := zero_apply }
lemma single_add_erase {a : α} {f : α →₀ β} : single a (f a) + f.erase a = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, add_zero]
else by simp only [add_apply, single_eq_of_ne h, zero_add, erase_ne (ne.symm h)]
lemma erase_add_single {a : α} {f : α →₀ β} : f.erase a + single a (f a) = f :=
ext $ λ a',
if h : a = a' then by subst h; simp only [add_apply, single_eq_same, erase_same, zero_add]
else by simp only [add_apply, single_eq_of_ne h, add_zero, erase_ne (ne.symm h)]
@[simp] lemma erase_add (a : α) (f f' : α →₀ β) : erase a (f + f') = erase a f + erase a f' :=
begin
ext s, by_cases hs : s = a,
{ rw [hs, add_apply, erase_same, erase_same, erase_same, add_zero] },
rw [add_apply, erase_ne hs, erase_ne hs, erase_ne hs, add_apply],
end
@[elab_as_eliminator]
protected theorem induction {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (single a b + f)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (single a (f a) + f.erase a), by rwa [single_add_erase] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma induction₂ {p : (α →₀ β) → Prop} (f : α →₀ β)
(h0 : p 0) (ha : ∀a b (f : α →₀ β), a ∉ f.support → b ≠ 0 → p f → p (f + single a b)) :
p f :=
suffices ∀s (f : α →₀ β), f.support = s → p f, from this _ _ rfl,
assume s, finset.induction_on s (λ f hf, by rwa [support_eq_empty.1 hf]) $
assume a s has ih f hf,
suffices p (f.erase a + single a (f a)), by rwa [erase_add_single] at this,
begin
apply ha,
{ rw [support_erase, mem_erase], exact λ H, H.1 rfl },
{ rw [← mem_support_iff, hf], exact mem_insert_self _ _ },
{ apply ih _ _,
rw [support_erase, hf, finset.erase_insert has] }
end
lemma map_range_add [add_monoid β₁] [add_monoid β₂]
{f : β₁ → β₂} {hf : f 0 = 0} (hf' : ∀ x y, f (x + y) = f x + f y) (v₁ v₂ : α →₀ β₁) :
map_range f hf (v₁ + v₂) = map_range f hf v₁ + map_range f hf v₂ :=
ext $ λ a, by simp only [hf', add_apply, map_range_apply]
end add_monoid
section nat_sub
instance nat_sub : has_sub (α →₀ ℕ) := ⟨zip_with (λ m n, m - n) (nat.sub_zero 0)⟩
@[simp] lemma nat_sub_apply {g₁ g₂ : α →₀ ℕ} {a : α} :
(g₁ - g₂) a = g₁ a - g₂ a :=
rfl
@[simp] lemma single_sub {a : α} {n₁ n₂ : ℕ} : single a (n₁ - n₂) = single a n₁ - single a n₂ :=
begin
ext f,
by_cases h : (a = f),
{ rw [h, nat_sub_apply, single_eq_same, single_eq_same, single_eq_same] },
rw [nat_sub_apply, single_eq_of_ne h, single_eq_of_ne h, single_eq_of_ne h]
end
-- These next two lemmas are used in developing
-- the partial derivative on `mv_polynomial`.
lemma sub_single_one_add {a : α} {u u' : α →₀ ℕ} (h : u a ≠ 0) :
u - single a 1 + u' = u + u' - single a 1 :=
begin
ext b,
rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply],
by_cases h : a = b,
{ rw [←h, single_eq_same], cases (u a), { contradiction }, { simp }, },
{ simp [h], }
end
lemma add_sub_single_one {a : α} {u u' : α →₀ ℕ} (h : u' a ≠ 0) :
u + (u' - single a 1) = u + u' - single a 1 :=
begin
ext b,
rw [add_apply, nat_sub_apply, nat_sub_apply, add_apply],
by_cases h : a = b,
{ rw [←h, single_eq_same], cases (u' a), { contradiction }, { simp }, },
{ simp [h], }
end
end nat_sub
instance [add_comm_monoid β] : add_comm_monoid (α →₀ β) :=
{ add_comm := assume ⟨s, f, _⟩ ⟨t, g, _⟩, ext $ assume a, add_comm _ _,
.. finsupp.add_monoid }
instance [add_group β] : add_group (α →₀ β) :=
{ neg := map_range (has_neg.neg) neg_zero,
add_left_neg := assume ⟨s, f, _⟩, ext $ assume x, add_left_neg _,
.. finsupp.add_monoid }
lemma single_multiset_sum [add_comm_monoid β] (s : multiset β) (a : α) :
single a s.sum = (s.map (single a)).sum :=
multiset.induction_on s single_zero $ λ a s ih,
by rw [multiset.sum_cons, single_add, ih, multiset.map_cons, multiset.sum_cons]
lemma single_finset_sum [add_comm_monoid β] (s : finset γ) (f : γ → β) (a : α) :
single a (s.sum f) = s.sum (λb, single a (f b)) :=
begin
transitivity,
apply single_multiset_sum,
rw [multiset.map_map],
refl
end
lemma single_sum [has_zero γ] [add_comm_monoid β] (s : δ →₀ γ) (f : δ → γ → β) (a : α) :
single a (s.sum f) = s.sum (λd c, single a (f d c)) :=
single_finset_sum _ _ _
@[to_additive]
lemma prod_neg_index [add_group β] [comm_monoid γ]
{g : α →₀ β} {h : α → β → γ} (h0 : ∀a, h a 0 = 1) :
(-g).prod h = g.prod (λa b, h a (- b)) :=
prod_map_range_index h0
@[simp] lemma neg_apply [add_group β] {g : α →₀ β} {a : α} : (- g) a = - g a :=
rfl
@[simp] lemma sub_apply [add_group β] {g₁ g₂ : α →₀ β} {a : α} : (g₁ - g₂) a = g₁ a - g₂ a :=
rfl
@[simp] lemma support_neg [add_group β] {f : α →₀ β} : support (-f) = support f :=
finset.subset.antisymm
support_map_range
(calc support f = support (- (- f)) : congr_arg support (neg_neg _).symm
... ⊆ support (- f) : support_map_range)
instance [add_comm_group β] : add_comm_group (α →₀ β) :=
{ add_comm := add_comm, ..finsupp.add_group }
@[simp] lemma sum_apply [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β} {a₂ : α} :
(f.sum g) a₂ = f.sum (λa₁ b, g a₁ b a₂) :=
(f.support.sum_hom (λf : α →₀ β, f a₂)).symm
lemma support_sum [has_zero β₁] [add_comm_monoid β]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → (α →₀ β)} :
(f.sum g).support ⊆ f.support.bind (λa, (g a (f a)).support) :=
have ∀a₁ : α, f.sum (λ (a : α₁) (b : β₁), (g a b) a₁) ≠ 0 →
(∃ (a : α₁), f a ≠ 0 ∧ ¬ (g a (f a)) a₁ = 0),
from assume a₁ h,
let ⟨a, ha, ne⟩ := finset.exists_ne_zero_of_sum_ne_zero h in
⟨a, mem_support_iff.mp ha, ne⟩,
by simpa only [finset.subset_iff, mem_support_iff, finset.mem_bind, sum_apply, exists_prop]
using this
@[simp] lemma sum_zero [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β} :
f.sum (λa b, (0 : γ)) = 0 :=
finset.sum_const_zero
@[simp] lemma sum_add [add_comm_monoid β] [add_comm_monoid γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b + h₂ a b) = f.sum h₁ + f.sum h₂ :=
finset.sum_add_distrib
@[simp] lemma sum_neg [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h : α → β → γ} : f.sum (λa b, - h a b) = - f.sum h :=
f.support.sum_hom (@has_neg.neg γ _)
@[simp] lemma sum_sub [add_comm_monoid β] [add_comm_group γ] {f : α →₀ β}
{h₁ h₂ : α → β → γ} :
f.sum (λa b, h₁ a b - h₂ a b) = f.sum h₁ - f.sum h₂ :=
by rw [sub_eq_add_neg, ←sum_neg, ←sum_add]; refl
@[simp] lemma sum_single [add_comm_monoid β] (f : α →₀ β) :
f.sum single = f :=
have ∀a:α, f.sum (λa' b, ite (a' = a) b 0) =
({a} : finset α).sum (λa', ite (a' = a) (f a') 0),
begin
intro a,
by_cases h : a ∈ f.support,
{ have : (finset.singleton a : finset α) ⊆ f.support,
{ simpa only [finset.subset_iff, mem_singleton, forall_eq] },
refine (finset.sum_subset this (λ _ _ H, _)).symm,
exact if_neg (mt mem_singleton.2 H) },
{ transitivity (f.support.sum (λa, (0 : β))),
{ refine (finset.sum_congr rfl $ λ a' ha', if_neg _),
rintro rfl, exact h ha' },
{ rw [sum_const_zero, insert_empty_eq_singleton, sum_singleton,
if_pos rfl, not_mem_support_iff.1 h] } }
end,
ext $ assume a, by simp only [sum_apply, single_apply, this,
insert_empty_eq_singleton, sum_singleton, if_pos]
@[to_additive]
lemma prod_add_index [add_comm_monoid β] [comm_monoid γ] {f g : α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f + g).prod h = f.prod h * g.prod h :=
have f_eq : (f.support ∪ g.support).prod (λa, h a (f a)) = f.prod h,
from (finset.prod_subset (finset.subset_union_left _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
have g_eq : (f.support ∪ g.support).prod (λa, h a (g a)) = g.prod h,
from (finset.prod_subset (finset.subset_union_right _ _) $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]).symm,
calc (f + g).support.prod (λa, h a ((f + g) a)) =
(f.support ∪ g.support).prod (λa, h a ((f + g) a)) :
finset.prod_subset support_add $
by intros _ _ H; rw [not_mem_support_iff.1 H, h_zero]
... = (f.support ∪ g.support).prod (λa, h a (f a)) *
(f.support ∪ g.support).prod (λa, h a (g a)) :
by simp only [add_apply, h_add, finset.prod_mul_distrib]
... = _ : by rw [f_eq, g_eq]
lemma sum_sub_index [add_comm_group β] [add_comm_group γ] {f g : α →₀ β}
{h : α → β → γ} (h_sub : ∀a b₁ b₂, h a (b₁ - b₂) = h a b₁ - h a b₂) :
(f - g).sum h = f.sum h - g.sum h :=
have h_zero : ∀a, h a 0 = 0,
from assume a,
have h a (0 - 0) = h a 0 - h a 0, from h_sub a 0 0,
by simpa only [sub_self] using this,
have h_neg : ∀a b, h a (- b) = - h a b,
from assume a b,
have h a (0 - b) = h a 0 - h a b, from h_sub a 0 b,
by simpa only [h_zero, zero_sub] using this,
have h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ + h a b₂,
from assume a b₁ b₂,
have h a (b₁ - (- b₂)) = h a b₁ - h a (- b₂), from h_sub a b₁ (-b₂),
by simpa only [h_neg, sub_neg_eq_add] using this,
calc (f - g).sum h = (f + - g).sum h : rfl
... = f.sum h + - g.sum h : by simp only [sum_add_index h_zero h_add, sum_neg_index h_zero,
h_neg, sum_neg]
... = f.sum h - g.sum h : rfl
@[to_additive]
lemma prod_finset_sum_index [add_comm_monoid β] [comm_monoid γ]
{s : finset ι} {g : ι → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
s.prod (λi, (g i).prod h) = (s.sum g).prod h :=
finset.induction_on s rfl $ λ a s has ih,
by rw [prod_insert has, ih, sum_insert has, prod_add_index h_zero h_add]
@[to_additive]
lemma prod_sum_index
[add_comm_monoid β₁] [add_comm_monoid β] [comm_monoid γ]
{f : α₁ →₀ β₁} {g : α₁ → β₁ → α →₀ β}
{h : α → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(f.sum g).prod h = f.prod (λa b, (g a b).prod h) :=
(prod_finset_sum_index h_zero h_add).symm
lemma multiset_sum_sum_index
[add_comm_monoid β] [add_comm_monoid γ]
(f : multiset (α →₀ β)) (h : α → β → γ)
(h₀ : ∀a, h a 0 = 0) (h₁ : ∀ (a : α) (b₁ b₂ : β), h a (b₁ + b₂) = h a b₁ + h a b₂) :
(f.sum.sum h) = (f.map $ λg:α →₀ β, g.sum h).sum :=
multiset.induction_on f rfl $ assume a s ih,
by rw [multiset.sum_cons, multiset.map_cons, multiset.sum_cons, sum_add_index h₀ h₁, ih]
lemma multiset_map_sum [has_zero β] {f : α →₀ β} {m : γ → δ} {h : α → β → multiset γ} :
multiset.map m (f.sum h) = f.sum (λa b, (h a b).map m) :=
(f.support.sum_hom _).symm
lemma multiset_sum_sum [has_zero β] [add_comm_monoid γ] {f : α →₀ β} {h : α → β → multiset γ} :
multiset.sum (f.sum h) = f.sum (λa b, multiset.sum (h a b)) :=
(f.support.sum_hom multiset.sum).symm
section map_range
variables
[add_comm_monoid β₁] [add_comm_monoid β₂]
(f : β₁ → β₂) [hf : is_add_monoid_hom f]
instance is_add_monoid_hom_map_range :
is_add_monoid_hom (map_range f hf.map_zero : (α →₀ β₁) → (α →₀ β₂)) :=
{ map_zero := map_range_zero, map_add := λ a b, map_range_add hf.map_add _ _ }
lemma map_range_multiset_sum (m : multiset (α →₀ β₁)) :
map_range f hf.map_zero m.sum = (m.map $ λx, map_range f hf.map_zero x).sum :=
(m.sum_hom (map_range f hf.map_zero)).symm
lemma map_range_finset_sum {ι : Type*} (s : finset ι) (g : ι → (α →₀ β₁)) :
map_range f hf.map_zero (s.sum g) = s.sum (λx, map_range f hf.map_zero (g x)) :=
by rw [finset.sum.equations._eqn_1, map_range_multiset_sum, multiset.map_map]; refl
end map_range
/-! ### Declarations about `map_domain` -/
section map_domain
variables [add_comm_monoid β] {v v₁ v₂ : α →₀ β}
/-- Given `f : α₁ → α₂` and `v : α₁ →₀ β`, `map_domain f v : α₂ →₀ β`
is the finitely supported function whose value at `a : α₂` is the sum
of `v x` over all `x` such that `f x = a`. -/
def map_domain (f : α₁ → α₂) (v : α₁ →₀ β) : α₂ →₀ β :=
v.sum $ λa, single (f a)
lemma map_domain_apply {f : α₁ → α₂} (hf : function.injective f) (x : α₁ →₀ β) (a : α₁) :
map_domain f x (f a) = x a :=
begin
rw [map_domain, sum_apply, sum, finset.sum_eq_single a, single_eq_same],
{ assume b _ hba, exact single_eq_of_ne (hf.ne hba) },
{ simp only [(∉), (≠), not_not, mem_support_iff],
assume h,
rw [h, single_zero],
refl }
end
lemma map_domain_notin_range {f : α₁ → α₂} (x : α₁ →₀ β) (a : α₂) (h : a ∉ set.range f) :
map_domain f x a = 0 :=
begin
rw [map_domain, sum_apply, sum],
exact finset.sum_eq_zero
(assume a' h', single_eq_of_ne $ assume eq, h $ eq ▸ set.mem_range_self _)
end
lemma map_domain_id : map_domain id v = v :=
sum_single _
lemma map_domain_comp {f : α → α₁} {g : α₁ → α₂} :
map_domain (g ∘ f) v = map_domain g (map_domain f v) :=
begin
refine ((sum_sum_index _ _).trans _).symm,
{ intros, exact single_zero },
{ intros, exact single_add },
refine sum_congr rfl (λ _ _, sum_single_index _),
{ exact single_zero }
end
lemma map_domain_single {f : α → α₁} {a : α} {b : β} : map_domain f (single a b) = single (f a) b :=
sum_single_index single_zero
@[simp] lemma map_domain_zero {f : α → α₂} : map_domain f 0 = (0 : α₂ →₀ β) :=
sum_zero_index
lemma map_domain_congr {f g : α → α₂} (h : ∀x∈v.support, f x = g x) :
v.map_domain f = v.map_domain g :=
finset.sum_congr rfl $ λ _ H, by simp only [h _ H]
lemma map_domain_add {f : α → α₂} : map_domain f (v₁ + v₂) = map_domain f v₁ + map_domain f v₂ :=
sum_add_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_finset_sum {f : α → α₂} {s : finset ι} {v : ι → α →₀ β} :
map_domain f (s.sum v) = s.sum (λi, map_domain f (v i)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_sum [has_zero β₁] {f : α → α₂} {s : α →₀ β₁} {v : α → β₁ → α →₀ β} :
map_domain f (s.sum v) = s.sum (λa b, map_domain f (v a b)) :=
eq.symm $ sum_finset_sum_index (λ _, single_zero) (λ _ _ _, single_add)
lemma map_domain_support {f : α → α₂} {s : α →₀ β} :
(s.map_domain f).support ⊆ s.support.image f :=
finset.subset.trans support_sum $
finset.subset.trans (finset.bind_mono $ assume a ha, support_single_subset) $
by rw [finset.bind_singleton]; exact subset.refl _
@[to_additive]
lemma prod_map_domain_index [comm_monoid γ] {f : α → α₂} {s : α →₀ β}
{h : α₂ → β → γ} (h_zero : ∀a, h a 0 = 1) (h_add : ∀a b₁ b₂, h a (b₁ + b₂) = h a b₁ * h a b₂) :
(s.map_domain f).prod h = s.prod (λa b, h (f a) b) :=
(prod_sum_index h_zero h_add).trans $ prod_congr rfl $ λ _ _, prod_single_index (h_zero _)
lemma emb_domain_eq_map_domain (f : α₁ ↪ α₂) (v : α₁ →₀ β) :
emb_domain f v = map_domain f v :=
begin
ext a,
by_cases a ∈ set.range f,
{ rcases h with ⟨a, rfl⟩,
rw [map_domain_apply (function.embedding.inj' _), emb_domain_apply] },
{ rw [map_domain_notin_range, emb_domain_notin_range]; assumption }
end
lemma injective_map_domain {f : α₁ → α₂} (hf : function.injective f) :
function.injective (map_domain f : (α₁ →₀ β) → (α₂ →₀ β)) :=
begin
assume v₁ v₂ eq, ext a,
have : map_domain f v₁ (f a) = map_domain f v₂ (f a), { rw eq },
rwa [map_domain_apply hf, map_domain_apply hf] at this,
end
end map_domain
/-! ### Declarations about `comap_domain` -/
section comap_domain
/-- Given `f : α₁ → α₂`, `l : α₂ →₀ γ` and a proof `hf` that `f` is injective on
the preimage of `l.support`, `comap_domain f l hf` is the finitely supported function
from `α₁` to `γ` given by composing `l` with `f`. -/
def comap_domain {α₁ α₂ γ : Type*} [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) : α₁ →₀ γ :=
{ support := l.support.preimage hf,
to_fun := (λ a, l (f a)),
mem_support_to_fun :=
begin
intros a,
simp only [finset.mem_def.symm, finset.mem_preimage],
exact l.mem_support_to_fun (f a),
end }
lemma comap_domain_apply {α₁ α₂ γ : Type*} [has_zero γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.inj_on f (f ⁻¹' l.support.to_set)) (a : α₁) :
comap_domain f l hf a = l (f a) :=
rfl
lemma sum_comap_domain {α₁ α₂ β γ : Type*} [has_zero β] [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ β) (g : α₂ → β → γ)
(hf : set.bij_on f (f ⁻¹' l.support.to_set) l.support.to_set) :
(comap_domain f l hf.inj_on).sum (g ∘ f) = l.sum g :=
begin
unfold sum,
simp only [comap_domain, comap_domain_apply, finset.sum_preimage f _ _ (λ (x : α₂), g x (l x))],
end
lemma eq_zero_of_comap_domain_eq_zero {α₁ α₂ γ : Type*} [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ γ) (hf : set.bij_on f (f ⁻¹' l.support.to_set) l.support.to_set) :
comap_domain f l hf.inj_on = 0 → l = 0 :=
begin
rw [← support_eq_empty, ← support_eq_empty, comap_domain],
simp only [finset.ext, finset.not_mem_empty, iff_false, mem_preimage],
assume h a ha,
cases hf.2.2 ha with b hb,
exact h b (hb.2.symm ▸ ha)
end
lemma map_domain_comap_domain {α₁ α₂ γ : Type*} [add_comm_monoid γ]
(f : α₁ → α₂) (l : α₂ →₀ γ)
(hf : function.injective f) (hl : ↑l.support ⊆ set.range f):
map_domain f (comap_domain f l (hf.inj_on _)) = l :=
begin
ext a,
by_cases h_cases: a ∈ set.range f,
{ rcases set.mem_range.1 h_cases with ⟨b, hb⟩,
rw [hb.symm, map_domain_apply hf, comap_domain_apply] },
{ rw map_domain_notin_range _ _ h_cases,
by_contra h_contr,
apply h_cases (hl $ finset.mem_coe.2 $ mem_support_iff.2 $ λ h, h_contr h.symm) }
end
end comap_domain
/-! ### Declarations about `filter` -/
section filter
section has_zero
variables [has_zero β] (p : α → Prop) (f : α →₀ β)
/-- `filter p f` is the function which is `f a` if `p a` is true and 0 otherwise. -/
def filter (p : α → Prop) (f : α →₀ β) : α →₀ β :=
on_finset f.support (λa, if p a then f a else 0) $ λ a H,
mem_support_iff.2 $ λ h, by rw [h, if_t_t] at H; exact H rfl
@[simp] lemma filter_apply_pos {a : α} (h : p a) : f.filter p a = f a :=
if_pos h
@[simp] lemma filter_apply_neg {a : α} (h : ¬ p a) : f.filter p a = 0 :=
if_neg h
@[simp] lemma support_filter : (f.filter p).support = f.support.filter p :=
finset.ext.mpr $ assume a, if H : p a
then by simp only [mem_support_iff, filter_apply_pos _ _ H, mem_filter, H, and_true]
else by simp only [mem_support_iff, filter_apply_neg _ _ H, mem_filter, H, and_false, ne.def,
ne_self_iff_false]
lemma filter_zero : (0 : α →₀ β).filter p = 0 :=
by rw [← support_eq_empty, support_filter, support_zero, finset.filter_empty]
@[simp] lemma filter_single_of_pos
{a : α} {b : β} (h : p a) : (single a b).filter p = single a b :=
ext $ λ x, begin
by_cases h' : p x,
{ simp only [h', filter_apply_pos] },
{ simp only [h', filter_apply_neg, not_false_iff],
rw single_eq_of_ne, rintro rfl, exact h' h }
end
@[simp] lemma filter_single_of_neg
{a : α} {b : β} (h : ¬ p a) : (single a b).filter p = 0 :=
ext $ λ x, begin
by_cases h' : p x,
{ simp only [h', filter_apply_pos, zero_apply], rw single_eq_of_ne, rintro rfl, exact h h' },
{ simp only [h', finsupp.zero_apply, not_false_iff, filter_apply_neg] }
end
end has_zero
lemma filter_pos_add_filter_neg [add_monoid β] (f : α →₀ β) (p : α → Prop) :
f.filter p + f.filter (λa, ¬ p a) = f :=
ext $ assume a, if H : p a
then by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_not, add_zero]
else by simp only [add_apply, filter_apply_pos, filter_apply_neg, H, not_false_iff, zero_add]
end filter
/-! ### Declarations about `frange` -/
section frange
variables [has_zero β]
/-- `frange f` is the image of `f` on the support of `f`. -/
def frange (f : α →₀ β) : finset β := finset.image f f.support
theorem mem_frange {f : α →₀ β} {y : β} :
y ∈ f.frange ↔ y ≠ 0 ∧ ∃ x, f x = y :=
finset.mem_image.trans
⟨λ ⟨x, hx1, hx2⟩, ⟨hx2 ▸ mem_support_iff.1 hx1, x, hx2⟩,
λ ⟨hy, x, hx⟩, ⟨x, mem_support_iff.2 (hx.symm ▸ hy), hx⟩⟩
theorem zero_not_mem_frange {f : α →₀ β} : (0:β) ∉ f.frange :=
λ H, (mem_frange.1 H).1 rfl
theorem frange_single {x : α} {y : β} : frange (single x y) ⊆ {y} :=
λ r hr, let ⟨t, ht1, ht2⟩ := mem_frange.1 hr in ht2 ▸
(by rw single_apply at ht2 ⊢; split_ifs at ht2 ⊢; [exact finset.mem_singleton_self _, cc])
end frange
/-! ### Declarations about `subtype_domain` -/
section subtype_domain
variables {α' : Type*} [has_zero δ] {p : α → Prop}
section zero
variables [has_zero β] {v v' : α' →₀ β}
/-- `subtype_domain p f` is the restriction of the finitely supported function
`f` to the subtype `p`. -/
def subtype_domain (p : α → Prop) (f : α →₀ β) : (subtype p →₀ β) :=
⟨f.support.subtype p, f ∘ subtype.val, λ a, by simp only [mem_subtype, mem_support_iff]⟩
@[simp] lemma support_subtype_domain {f : α →₀ β} :
(subtype_domain p f).support = f.support.subtype p :=
rfl
@[simp] lemma subtype_domain_apply {a : subtype p} {v : α →₀ β} :
(subtype_domain p v) a = v (a.val) :=
rfl
@[simp] lemma subtype_domain_zero : subtype_domain p (0 : α →₀ β) = 0 :=
rfl
@[to_additive]
lemma prod_subtype_domain_index [comm_monoid γ] {v : α →₀ β}
{h : α → β → γ} (hp : ∀x∈v.support, p x) :
(v.subtype_domain p).prod (λa b, h a.1 b) = v.prod h :=
prod_bij (λp _, p.val)
(λ _, mem_subtype.1)
(λ _ _, rfl)
(λ _ _ _ _, subtype.eq)
(λ b hb, ⟨⟨b, hp b hb⟩, mem_subtype.2 hb, rfl⟩)
end zero
section monoid
variables [add_monoid β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_add {v v' : α →₀ β} :
(v + v').subtype_domain p = v.subtype_domain p + v'.subtype_domain p :=
ext $ λ _, rfl
instance subtype_domain.is_add_monoid_hom :
is_add_monoid_hom (subtype_domain p : (α →₀ β) → subtype p →₀ β) :=
{ map_add := λ _ _, subtype_domain_add, map_zero := subtype_domain_zero }
@[simp] lemma filter_add {v v' : α →₀ β} :
(v + v').filter p = v.filter p + v'.filter p :=
ext $ λ a, begin
by_cases p a,
{ simp only [h, filter_apply_pos, add_apply] },
{ simp only [h, add_zero, add_apply, not_false_iff, filter_apply_neg] }
end
instance filter.is_add_monoid_hom (p : α → Prop) :
is_add_monoid_hom (filter p : (α →₀ β) → (α →₀ β)) :=
{ map_zero := filter_zero p, map_add := λ x y, filter_add }
end monoid
section comm_monoid
variables [add_comm_monoid β]
lemma subtype_domain_sum {s : finset γ} {h : γ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc, (h c).subtype_domain p) :=
eq.symm (s.sum_hom _)
lemma subtype_domain_finsupp_sum {s : γ →₀ δ} {h : γ → δ → α →₀ β} :
(s.sum h).subtype_domain p = s.sum (λc d, (h c d).subtype_domain p) :=
subtype_domain_sum
lemma filter_sum (s : finset γ) (f : γ → α →₀ β) :
(s.sum f).filter p = s.sum (λa, filter p (f a)) :=
(s.sum_hom (filter p)).symm
end comm_monoid
section group
variables [add_group β] {v v' : α' →₀ β}
@[simp] lemma subtype_domain_neg {v : α →₀ β} :
(- v).subtype_domain p = - v.subtype_domain p :=
ext $ λ _, rfl
@[simp] lemma subtype_domain_sub {v v' : α →₀ β} :
(v - v').subtype_domain p = v.subtype_domain p - v'.subtype_domain p :=
ext $ λ _, rfl
end group
end subtype_domain
/-! ### Declarations relating `finsupp` to `multiset` -/
section multiset
/-- Given `f : α →₀ ℕ`, `f.to_multiset` is the multiset with multiplicities given by the values of
`f` on the elements of `α`. -/
def to_multiset (f : α →₀ ℕ) : multiset α :=
f.sum (λa n, add_monoid.smul n {a})
lemma to_multiset_zero : (0 : α →₀ ℕ).to_multiset = 0 :=
rfl
lemma to_multiset_add (m n : α →₀ ℕ) :
(m + n).to_multiset = m.to_multiset + n.to_multiset :=
sum_add_index (assume a, add_monoid.zero_smul _) (assume a b₁ b₂, add_monoid.add_smul _ _ _)
lemma to_multiset_single (a : α) (n : ℕ) : to_multiset (single a n) = add_monoid.smul n {a} :=
by rw [to_multiset, sum_single_index]; apply add_monoid.zero_smul
instance is_add_monoid_hom.to_multiset : is_add_monoid_hom (to_multiset : _ → multiset α) :=
{ map_zero := to_multiset_zero, map_add := to_multiset_add }
lemma card_to_multiset (f : α →₀ ℕ) : f.to_multiset.card = f.sum (λa, id) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.card_zero, sum_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.card_add, ih, sum_add_index, to_multiset_single,
sum_single_index, multiset.card_smul, multiset.singleton_eq_singleton,
multiset.card_singleton, mul_one]; intros; refl }
end
lemma to_multiset_map (f : α →₀ ℕ) (g : α → β) :
f.to_multiset.map g = (f.map_domain g).to_multiset :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.map_zero, map_domain_zero, to_multiset_zero] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.map_add, ih, map_domain_add, map_domain_single,
to_multiset_single, to_multiset_add, to_multiset_single,
is_add_monoid_hom.map_smul (multiset.map g)],
refl }
end
lemma prod_to_multiset [comm_monoid α] (f : α →₀ ℕ) :
f.to_multiset.prod = f.prod (λa n, a ^ n) :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.prod_zero, finsupp.prod_zero_index] },
{ assume a n f _ _ ih,
rw [to_multiset_add, multiset.prod_add, ih, to_multiset_single, finsupp.prod_add_index,
finsupp.prod_single_index, multiset.prod_smul, multiset.singleton_eq_singleton,
multiset.prod_singleton],
{ exact pow_zero a },
{ exact pow_zero },
{ exact pow_add } }
end
lemma to_finset_to_multiset (f : α →₀ ℕ) : f.to_multiset.to_finset = f.support :=
begin
refine f.induction _ _,
{ rw [to_multiset_zero, multiset.to_finset_zero, support_zero] },
{ assume a n f ha hn ih,
rw [to_multiset_add, multiset.to_finset_add, ih, to_multiset_single, support_add_eq,
support_single_ne_zero hn, multiset.to_finset_smul _ _ hn,
multiset.singleton_eq_singleton, multiset.to_finset_cons, multiset.to_finset_zero],
refl,
refine disjoint.mono_left support_single_subset _,
rwa [finset.singleton_eq_singleton, finset.singleton_disjoint] }
end
@[simp] lemma count_to_multiset (f : α →₀ ℕ) (a : α) :
f.to_multiset.count a = f a :=
calc f.to_multiset.count a = f.sum (λx n, (add_monoid.smul n {x} : multiset α).count a) :
(f.support.sum_hom $ multiset.count a).symm
... = f.sum (λx n, n * ({x} : multiset α).count a) : by simp only [multiset.count_smul]
... = f.sum (λx n, n * (x :: 0 : multiset α).count a) : rfl
... = f a * (a :: 0 : multiset α).count a : sum_eq_single _
(λ a' _ H, by simp only [multiset.count_cons_of_ne (ne.symm H), multiset.count_zero, mul_zero])
(λ H, by simp only [not_mem_support_iff.1 H, zero_mul])
... = f a : by simp only [multiset.count_singleton, mul_one]
/-- Given `m : multiset α`, `of_multiset m` is the finitely supported function from `α` to `ℕ`
given by the multiplicities of the elements of `α` in `m`. -/
def of_multiset (m : multiset α) : α →₀ ℕ :=
on_finset m.to_finset (λa, m.count a) $ λ a H, multiset.mem_to_finset.2 $
by_contradiction (mt multiset.count_eq_zero.2 H)
@[simp] lemma of_multiset_apply (m : multiset α) (a : α) :
of_multiset m a = m.count a :=
rfl
/-- `equiv_multiset` defines an `equiv` between finitely supported functions
from `α` to `ℕ` and multisets on `α`. -/
def equiv_multiset : (α →₀ ℕ) ≃ (multiset α) :=
⟨ to_multiset, of_multiset,
assume f, finsupp.ext $ λ a, by rw [of_multiset_apply, count_to_multiset],
assume m, multiset.ext.2 $ λ a, by rw [count_to_multiset, of_multiset_apply] ⟩
lemma mem_support_multiset_sum [add_comm_monoid β]
{s : multiset (α →₀ β)} (a : α) :
a ∈ s.sum.support → ∃f∈s, a ∈ (f : α →₀ β).support :=
multiset.induction_on s false.elim
begin
assume f s ih ha,
by_cases a ∈ f.support,
{ exact ⟨f, multiset.mem_cons_self _ _, h⟩ },
{ simp only [multiset.sum_cons, mem_support_iff, add_apply,
not_mem_support_iff.1 h, zero_add] at ha,
rcases ih (mem_support_iff.2 ha) with ⟨f', h₀, h₁⟩,
exact ⟨f', multiset.mem_cons_of_mem h₀, h₁⟩ }
end
lemma mem_support_finset_sum [add_comm_monoid β]
{s : finset γ} {h : γ → α →₀ β} (a : α) (ha : a ∈ (s.sum h).support) : ∃c∈s, a ∈ (h c).support :=
let ⟨f, hf, hfa⟩ := mem_support_multiset_sum a ha in
let ⟨c, hc, eq⟩ := multiset.mem_map.1 hf in
⟨c, hc, eq.symm ▸ hfa⟩
lemma mem_support_single [has_zero β] (a a' : α) (b : β) :
a ∈ (single a' b).support ↔ a = a' ∧ b ≠ 0 :=
⟨λ H : (a ∈ ite _ _ _), if h : b = 0
then by rw if_pos h at H; exact H.elim
else ⟨by rw if_neg h at H; exact mem_singleton.1 H, h⟩,
λ ⟨h1, h2⟩, show a ∈ ite _ _ _, by rw [if_neg h2]; exact mem_singleton.2 h1⟩
end multiset
/-! ### Declarations about `curry` and `uncurry` -/
section curry_uncurry
/-- Given a finitely supported function `f` from a product type `α × β` to `γ`,
`curry f` is the "curried" finitely supported function from `α` to the type of
finitely supported functions from `β` to `γ`. -/
protected def curry [add_comm_monoid γ]
(f : (α × β) →₀ γ) : α →₀ (β →₀ γ) :=
f.sum $ λp c, single p.1 (single p.2 c)
lemma sum_curry_index
[add_comm_monoid γ] [add_comm_monoid δ]
(f : (α × β) →₀ γ) (g : α → β → γ → δ)
(hg₀ : ∀ a b, g a b 0 = 0) (hg₁ : ∀a b c₀ c₁, g a b (c₀ + c₁) = g a b c₀ + g a b c₁) :
f.curry.sum (λa f, f.sum (g a)) = f.sum (λp c, g p.1 p.2 c) :=
begin
rw [finsupp.curry],
transitivity,
{ exact sum_sum_index (assume a, sum_zero_index)
(assume a b₀ b₁, sum_add_index (assume a, hg₀ _ _) (assume c d₀ d₁, hg₁ _ _ _ _)) },
congr, funext p c,
transitivity,
{ exact sum_single_index sum_zero_index },
exact sum_single_index (hg₀ _ _)
end
/-- Given a finitely supported function `f` from `α` to the type of
finitely supported functions from `β` to `γ`,
`uncurry f` is the "uncurried" finitely supported function from `α × β` to `γ`. -/
protected def uncurry [add_comm_monoid γ] (f : α →₀ (β →₀ γ)) : (α × β) →₀ γ :=
f.sum $ λa g, g.sum $ λb c, single (a, b) c
/-- `finsupp_prod_equiv` defines the `equiv` between `((α × β) →₀ γ)` and `(α →₀ (β →₀ γ))` given by
currying and uncurrying. -/
def finsupp_prod_equiv [add_comm_monoid γ] : ((α × β) →₀ γ) ≃ (α →₀ (β →₀ γ)) :=
by refine ⟨finsupp.curry, finsupp.uncurry, λ f, _, λ f, _⟩; simp only [
finsupp.curry, finsupp.uncurry, sum_sum_index, sum_zero_index, sum_add_index,
sum_single_index, single_zero, single_add, eq_self_iff_true, forall_true_iff,
forall_3_true_iff, prod.mk.eta, (single_sum _ _ _).symm, sum_single]
lemma filter_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) (p : α₁ → Prop) :
(f.filter (λa:α₁×α₂, p a.1)).curry = f.curry.filter p :=
begin
rw [finsupp.curry, finsupp.curry, finsupp.sum, finsupp.sum,
@filter_sum _ (α₂ →₀ β) _ p _ f.support _],
rw [support_filter, sum_filter],
refine finset.sum_congr rfl _,
rintros ⟨a₁, a₂⟩ ha,
dsimp only,
split_ifs,
{ rw [filter_apply_pos, filter_single_of_pos]; exact h },
{ rwa [filter_single_of_neg] }
end
lemma support_curry [add_comm_monoid β] (f : α₁ × α₂ →₀ β) :
f.curry.support ⊆ f.support.image prod.fst :=
begin
rw ← finset.bind_singleton,
refine finset.subset.trans support_sum _,
refine finset.bind_mono (assume a _, support_single_subset)
end
end curry_uncurry
section
instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : has_scalar γ (α →₀ β) :=
⟨λa v, v.map_range ((•) a) (smul_zero _)⟩
variables (α β)
@[simp] lemma smul_apply' {R:semiring γ} [add_comm_monoid β] [semimodule γ β]
{a : α} {b : γ} {v : α →₀ β} : (b • v) a = b • (v a) :=
rfl
instance [semiring γ] [add_comm_monoid β] [semimodule γ β] : semimodule γ (α →₀ β) :=
{ smul := (•),
smul_add := λ a x y, ext $ λ _, smul_add _ _ _,
add_smul := λ a x y, ext $ λ _, add_smul _ _ _,
one_smul := λ x, ext $ λ _, one_smul _ _,
mul_smul := λ r s x, ext $ λ _, mul_smul _ _ _,
zero_smul := λ x, ext $ λ _, zero_smul _ _,
smul_zero := λ x, ext $ λ _, smul_zero _ }
instance [ring γ] [add_comm_group β] [module γ β] : module γ (α →₀ β) :=
{ ..finsupp.semimodule α β }
instance [field γ] [add_comm_group β] [vector_space γ β] : vector_space γ (α →₀ β) :=
{ ..finsupp.module α β }
variables {α β}
lemma support_smul {R:semiring γ} [add_comm_monoid β] [semimodule γ β] {b : γ} {g : α →₀ β} :
(b • g).support ⊆ g.support :=
λ a, by simp only [smul_apply', mem_support_iff, ne.def]; exact mt (λ h, h.symm ▸ smul_zero _)
section
variables {α' : Type*} [has_zero δ] {p : α → Prop}
@[simp] lemma filter_smul {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
{b : γ} {v : α →₀ β} : (b • v).filter p = b • v.filter p :=
ext $ λ a, begin
by_cases p a,
{ simp only [h, smul_apply', filter_apply_pos] },
{ simp only [h, smul_apply', not_false_iff, filter_apply_neg, smul_zero] }
end
end
lemma map_domain_smul {α'} {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
{f : α → α'} (b : γ) (v : α →₀ β) : map_domain f (b • v) = b • map_domain f v :=
begin
change map_domain f (map_range _ _ _) = map_range _ _ _,
apply finsupp.induction v, { simp only [map_domain_zero, map_range_zero] },
intros a b v' hv₁ hv₂ IH,
rw [map_range_add, map_domain_add, IH, map_domain_add, map_range_add,
map_range_single, map_domain_single, map_domain_single, map_range_single];
apply smul_add
end
@[simp] lemma smul_single {R : semiring γ} [add_comm_monoid β] [semimodule γ β]
(c : γ) (a : α) (b : β) : c • finsupp.single a b = finsupp.single a (c • b) :=
ext $ λ a', by by_cases a = a';
[{ subst h, simp only [smul_apply', single_eq_same] },
simp only [h, smul_apply', ne.def, not_false_iff, single_eq_of_ne, smul_zero]]
end
@[simp] lemma smul_apply [semiring β] {a : α} {b : β} {v : α →₀ β} :
(b • v) a = b • (v a) :=
rfl
lemma sum_smul_index [ring β] [add_comm_monoid γ] {g : α →₀ β} {b : β} {h : α → β → γ}
(h0 : ∀i, h i 0 = 0) : (b • g).sum h = g.sum (λi a, h i (b * a)) :=
finsupp.sum_map_range_index h0
section
variables [semiring β] [semiring γ]
lemma sum_mul (b : γ) (s : α →₀ β) {f : α → β → γ} :
(s.sum f) * b = s.sum (λ a c, (f a (s a)) * b) :=
by simp only [finsupp.sum, finset.sum_mul]
lemma mul_sum (b : γ) (s : α →₀ β) {f : α → β → γ} :
b * (s.sum f) = s.sum (λ a c, b * (f a (s a))) :=
by simp only [finsupp.sum, finset.mul_sum]
protected lemma eq_zero_of_zero_eq_one
(zero_eq_one : (0 : β) = 1) (l : α →₀ β) : l = 0 :=
by ext i; simp only [eq_zero_of_zero_eq_one β zero_eq_one (l i), finsupp.zero_apply]
end
/-- Given an `add_comm_monoid β` and `s : set α`, `restrict_support_equiv` is the `equiv`
between the subtype of finitely supported functions with support contained in `s` and
the type of finitely supported functions from `s`. -/
def restrict_support_equiv [add_comm_monoid β] (s : set α) :
{f : α →₀ β // ↑f.support ⊆ s } ≃ (s →₀ β):=
begin
refine ⟨λf, subtype_domain (λx, x ∈ s) f.1, λ f, ⟨f.map_domain subtype.val, _⟩, _, _⟩,
{ refine set.subset.trans (finset.coe_subset.2 map_domain_support) _,
rw [finset.coe_image, set.image_subset_iff],
exact assume x hx, x.2 },
{ rintros ⟨f, hf⟩,
apply subtype.eq,
ext a,
dsimp only,
refine classical.by_cases (assume h : a ∈ set.range (subtype.val : s → α), _) (assume h, _),
{ rcases h with ⟨x, rfl⟩,
rw [map_domain_apply subtype.val_injective, subtype_domain_apply] },
{ convert map_domain_notin_range _ _ h,
rw [← not_mem_support_iff],
refine mt _ h,
exact assume ha, ⟨⟨a, hf ha⟩, rfl⟩ } },
{ assume f,
ext ⟨a, ha⟩,
dsimp only,
rw [subtype_domain_apply, map_domain_apply subtype.val_injective] }
end
/-- Given `add_comm_monoid β` and `e : α₁ ≃ α₂`, `dom_congr e` is the corresponding `equiv` between
`α₁ →₀ β` and `α₂ →₀ β`. -/
protected def dom_congr [add_comm_monoid β] (e : α₁ ≃ α₂) : (α₁ →₀ β) ≃ (α₂ →₀ β) :=
⟨map_domain e, map_domain e.symm,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.symm_apply_apply],
exact map_domain_id
end,
begin
assume v,
simp only [map_domain_comp.symm, (∘), equiv.apply_symm_apply],
exact map_domain_id
end⟩
/-! ### Declarations about sigma types -/
section sigma
variables {αs : ι → Type*} [has_zero β] (l : (Σ i, αs i) →₀ β)
/-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β` and
an index element `i : ι`, `split l i` is the `i`th component of `l`,
a finitely supported function from `as i` to `β`. -/
def split (i : ι) : αs i →₀ β :=
l.comap_domain (sigma.mk i) (λ x1 x2 _ _ hx, heq_iff_eq.1 (sigma.mk.inj hx).2)
lemma split_apply (i : ι) (x : αs i) : split l i x = l ⟨i, x⟩ :=
begin
dunfold split,
rw comap_domain_apply
end
/-- Given `l`, a finitely supported function from the sigma type `Σ (i : ι), αs i` to `β`,
`split_support l` is the finset of indices in `ι` that appear in the support of `l`. -/
def split_support : finset ι := l.support.image sigma.fst
lemma mem_split_support_iff_nonzero (i : ι) :
i ∈ split_support l ↔ split l i ≠ 0 :=
begin
rw [split_support, mem_image, ne.def, ← support_eq_empty, ← ne.def,
← finset.nonempty_iff_ne_empty, split, comap_domain, finset.nonempty],
simp only [exists_prop, finset.mem_preimage, exists_and_distrib_right, exists_eq_right,
mem_support_iff, sigma.exists, ne.def]
end
/-- Given `l`, a finitely supported function from the sigma type `Σ i, αs i` to `β` and
an `ι`-indexed family `g` of functions from `(αs i →₀ β)` to `γ`, `split_comp` defines a
finitely supported function from the index type `ι` to `γ` given by composing `g i` with
`split l i`. -/
def split_comp [has_zero γ] (g : Π i, (αs i →₀ β) → γ)
(hg : ∀ i x, x = 0 ↔ g i x = 0) : ι →₀ γ :=
{ support := split_support l,
to_fun := λ i, g i (split l i),
mem_support_to_fun :=
begin
intros i,
rw [mem_split_support_iff_nonzero, not_iff_not, hg],
end }
lemma sigma_support : l.support = l.split_support.sigma (λ i, (l.split i).support) :=
by simp only [finset.ext, split_support, split, comap_domain, mem_image,
mem_preimage, sigma.forall, mem_sigma]; tauto
lemma sigma_sum [add_comm_monoid γ] (f : (Σ (i : ι), αs i) → β → γ) :
l.sum f = (split_support l).sum (λ (i : ι), (split l i).sum (λ (a : αs i) b, f ⟨i, a⟩ b)) :=
by simp only [sum, sigma_support, sum_sigma, split_apply]
end sigma
end finsupp
/-! ### Declarations relating `multiset` to `finsupp` -/
namespace multiset
/-- Given a multiset `s`, `s.to_finsupp` returns the finitely supported function on `ℕ` given by
the multiplicities of the elements of `s`. -/
def to_finsupp (s : multiset α) : α →₀ ℕ :=
{ support := s.to_finset,
to_fun := λ a, s.count a,
mem_support_to_fun := λ a,
begin
rw mem_to_finset,
convert not_iff_not_of_iff (count_eq_zero.symm),
rw not_not
end }
@[simp] lemma to_finsupp_support (s : multiset α) :
s.to_finsupp.support = s.to_finset :=
rfl
@[simp] lemma to_finsupp_apply (s : multiset α) (a : α) :
s.to_finsupp a = s.count a :=
rfl
@[simp] lemma to_finsupp_zero :
to_finsupp (0 : multiset α) = 0 :=
finsupp.ext $ λ a, count_zero a
@[simp] lemma to_finsupp_add (s t : multiset α) :
to_finsupp (s + t) = to_finsupp s + to_finsupp t :=
finsupp.ext $ λ a, count_add a s t
lemma to_finsupp_singleton (a : α) :
to_finsupp {a} = finsupp.single a 1 :=
finsupp.ext $ λ b,
if h : a = b then by rw [to_finsupp_apply, finsupp.single_apply, h, if_pos rfl,
singleton_eq_singleton, count_singleton] else
begin
rw [to_finsupp_apply, finsupp.single_apply, if_neg h, count_eq_zero,
singleton_eq_singleton, mem_singleton],
rintro rfl, exact h rfl
end
namespace to_finsupp
instance : is_add_monoid_hom (to_finsupp : multiset α → α →₀ ℕ) :=
{ map_zero := to_finsupp_zero,
map_add := to_finsupp_add }
end to_finsupp
@[simp] lemma to_finsupp_to_multiset (s : multiset α) :
s.to_finsupp.to_multiset = s :=
ext.2 $ λ a, by rw [finsupp.count_to_multiset, to_finsupp_apply]
end multiset
/-! ### Declarations about order(ed) instances on `finsupp` -/
namespace finsupp
variables {σ : Type*}
instance [preorder α] [has_zero α] : preorder (σ →₀ α) :=
{ le := λ f g, ∀ s, f s ≤ g s,
le_refl := λ f s, le_refl _,
le_trans := λ f g h Hfg Hgh s, le_trans (Hfg s) (Hgh s) }
instance [partial_order α] [has_zero α] : partial_order (σ →₀ α) :=
{ le_antisymm := λ f g hfg hgf, ext $ λ s, le_antisymm (hfg s) (hgf s),
.. finsupp.preorder }
instance [ordered_cancel_comm_monoid α] :
add_left_cancel_semigroup (σ →₀ α) :=
{ add_left_cancel := λ a b c h, ext $ λ s,
by { rw ext_iff at h, exact add_left_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_comm_monoid α] :
add_right_cancel_semigroup (σ →₀ α) :=
{ add_right_cancel := λ a b c h, ext $ λ s,
by { rw ext_iff at h, exact add_right_cancel (h s) },
.. finsupp.add_monoid }
instance [ordered_cancel_comm_monoid α] :
ordered_cancel_comm_monoid (σ →₀ α) :=
{ add_le_add_left := λ a b h c s, add_le_add_left (h s) (c s),
le_of_add_le_add_left := λ a b c h s, le_of_add_le_add_left (h s),
.. finsupp.add_comm_monoid, .. finsupp.partial_order,
.. finsupp.add_left_cancel_semigroup, .. finsupp.add_right_cancel_semigroup }
lemma le_iff [canonically_ordered_monoid α] (f g : σ →₀ α) :
f ≤ g ↔ ∀ s ∈ f.support, f s ≤ g s :=
⟨λ h s hs, h s,
λ h s, if H : s ∈ f.support then h s H else (not_mem_support_iff.1 H).symm ▸ zero_le (g s)⟩
@[simp] lemma add_eq_zero_iff [canonically_ordered_monoid α] (f g : σ →₀ α) :
f + g = 0 ↔ f = 0 ∧ g = 0 :=
begin
split,
{ assume h,
split,
all_goals
{ ext s,
suffices H : f s + g s = 0,
{ rw add_eq_zero_iff at H, cases H, assumption },
show (f + g) s = 0,
rw h, refl } },
{ rintro ⟨rfl, rfl⟩, rw add_zero }
end
attribute [simp] to_multiset_zero to_multiset_add
@[simp] lemma to_multiset_to_finsupp (f : σ →₀ ℕ) :
f.to_multiset.to_finsupp = f :=
ext $ λ s, by rw [multiset.to_finsupp_apply, count_to_multiset]
lemma to_multiset_strict_mono : strict_mono (@to_multiset σ) :=
λ m n h,
begin
rw lt_iff_le_and_ne at h ⊢, cases h with h₁ h₂,
split,
{ rw multiset.le_iff_count, intro s, erw [count_to_multiset m s, count_to_multiset], exact h₁ s },
{ intro H, apply h₂, replace H := congr_arg multiset.to_finsupp H,
simpa only [to_multiset_to_finsupp] using H }
end
lemma sum_id_lt_of_lt (m n : σ →₀ ℕ) (h : m < n) :
m.sum (λ _, id) < n.sum (λ _, id) :=
begin
rw [← card_to_multiset, ← card_to_multiset],
apply multiset.card_lt_of_lt,
exact to_multiset_strict_mono h
end
variable (σ)
/-- The order on `σ →₀ ℕ` is well-founded.-/
lemma lt_wf : well_founded (@has_lt.lt (σ →₀ ℕ) _) :=
subrelation.wf (sum_id_lt_of_lt) $ inv_image.wf _ nat.lt_wf
instance decidable_le : decidable_rel (@has_le.le (σ →₀ ℕ) _) :=
λ m n, by rw le_iff; apply_instance
variable {σ}
/-- The `finsupp` counterpart of `multiset.antidiagonal`: the antidiagonal of
`s : σ →₀ ℕ` consists of all pairs `(t₁, t₂) : (σ →₀ ℕ) × (σ →₀ ℕ)` such that `t₁ + t₂ = s`.
The finitely supported function `antidiagonal s` is equal to the multiplicities of these pairs. -/
def antidiagonal (f : σ →₀ ℕ) : ((σ →₀ ℕ) × (σ →₀ ℕ)) →₀ ℕ :=
(f.to_multiset.antidiagonal.map (prod.map multiset.to_finsupp multiset.to_finsupp)).to_finsupp
lemma mem_antidiagonal_support {f : σ →₀ ℕ} {p : (σ →₀ ℕ) × (σ →₀ ℕ)} :
p ∈ (antidiagonal f).support ↔ p.1 + p.2 = f :=
begin
erw [multiset.mem_to_finset, multiset.mem_map],
split,
{ rintros ⟨⟨a, b⟩, h, rfl⟩,
rw multiset.mem_antidiagonal at h,
simpa only [to_multiset_to_finsupp, multiset.to_finsupp_add]
using congr_arg multiset.to_finsupp h},
{ intro h,
refine ⟨⟨p.1.to_multiset, p.2.to_multiset⟩, _, _⟩,
{ simpa only [multiset.mem_antidiagonal, to_multiset_add]
using congr_arg to_multiset h},
{ rw [prod.map, to_multiset_to_finsupp, to_multiset_to_finsupp, prod.mk.eta] } }
end
@[simp] lemma antidiagonal_zero : antidiagonal (0 : σ →₀ ℕ) = single (0,0) 1 :=
by rw [← multiset.to_finsupp_singleton]; refl
lemma swap_mem_antidiagonal_support {n : σ →₀ ℕ} {f} (hf : f ∈ (antidiagonal n).support) :
f.swap ∈ (antidiagonal n).support :=
by simpa only [mem_antidiagonal_support, add_comm, prod.swap] using hf
end finsupp
|
d0d452c3e190e9d509f19315bc9e3efbfdefb354 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/order/filter/pointwise.lean | 886f3e75e2ec2a155eff6df55fd50dbd64bfb370 | [
"Apache-2.0"
] | permissive | urkud/mathlib | eab80095e1b9f1513bfb7f25b4fa82fa4fd02989 | 6379d39e6b5b279df9715f8011369a301b634e41 | refs/heads/master | 1,658,425,342,662 | 1,658,078,703,000 | 1,658,078,703,000 | 186,910,338 | 0 | 0 | Apache-2.0 | 1,568,512,083,000 | 1,557,958,709,000 | Lean | UTF-8 | Lean | false | false | 35,566 | lean | /-
Copyright (c) 2019 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Yaël Dillies
-/
import data.set.pointwise
import order.filter.n_ary
import order.filter.ultrafilter
/-!
# Pointwise operations on filters
This file defines pointwise operations on filters. This is useful because usual algebraic operations
distribute over pointwise operations. For example,
* `(f₁ * f₂).map m = f₁.map m * f₂.map m`
* `𝓝 (x * y) = 𝓝 x * 𝓝 y`
## Main declarations
* `0` (`filter.has_zero`): Pure filter at `0 : α`, or alternatively principal filter at `0 : set α`.
* `1` (`filter.has_one`): Pure filter at `1 : α`, or alternatively principal filter at `1 : set α`.
* `f + g` (`filter.has_add`): Addition, filter generated by all `s + t` where `s ∈ f` and `t ∈ g`.
* `f * g` (`filter.has_mul`): Multiplication, filter generated by all `s * t` where `s ∈ f` and
`t ∈ g`.
* `-f` (`filter.has_neg`): Negation, filter of all `-s` where `s ∈ f`.
* `f⁻¹` (`filter.has_inv`): Inversion, filter of all `s⁻¹` where `s ∈ f`.
* `f - g` (`filter.has_sub`): Subtraction, filter generated by all `s - t` where `s ∈ f` and
`t ∈ g`.
* `f / g` (`filter.has_div`): Division, filter generated by all `s / t` where `s ∈ f` and `t ∈ g`.
* `f +ᵥ g` (`filter.has_vadd`): Scalar addition, filter generated by all `s +ᵥ t` where `s ∈ f` and
`t ∈ g`.
* `f -ᵥ g` (`filter.has_vsub`): Scalar subtraction, filter generated by all `s -ᵥ t` where `s ∈ f`
and `t ∈ g`.
* `f • g` (`filter.has_smul`): Scalar multiplication, filter generated by all `s • t` where
`s ∈ f` and `t ∈ g`.
* `a +ᵥ f` (`filter.has_vadd_filter`): Translation, filter of all `a +ᵥ s` where `s ∈ f`.
* `a • f` (`filter.has_smul_filter`): Scaling, filter of all `a • s` where `s ∈ f`.
For `α` a semigroup/monoid, `filter α` is a semigroup/monoid.
As an unfortunate side effect, this means that `n • f`, where `n : ℕ`, is ambiguous between
pointwise scaling and repeated pointwise addition. See note [pointwise nat action].
## Implementation notes
We put all instances in the locale `pointwise`, so that these instances are not available by
default. Note that we do not mark them as reducible (as argued by note [reducible non-instances])
since we expect the locale to be open whenever the instances are actually used (and making the
instances reducible changes the behavior of `simp`.
## Tags
filter multiplication, filter addition, pointwise addition, pointwise multiplication,
-/
open function set
open_locale filter pointwise
variables {F α β γ δ ε : Type*}
namespace filter
/-! ### `0`/`1` as filters -/
section has_one
variables [has_one α] {f : filter α} {s : set α}
/-- `1 : filter α` is defined as the filter of sets containing `1 : α` in locale `pointwise`. -/
@[to_additive "`0 : filter α` is defined as the filter of sets containing `0 : α` in locale
`pointwise`."]
protected def has_one : has_one (filter α) := ⟨pure 1⟩
localized "attribute [instance] filter.has_one filter.has_zero" in pointwise
@[simp, to_additive] lemma mem_one : s ∈ (1 : filter α) ↔ (1 : α) ∈ s := mem_pure
@[to_additive] lemma one_mem_one : (1 : set α) ∈ (1 : filter α) := mem_pure.2 one_mem_one
@[simp, to_additive] lemma pure_one : pure 1 = (1 : filter α) := rfl
@[simp, to_additive] lemma principal_one : 𝓟 1 = (1 : filter α) := principal_singleton _
@[to_additive] lemma one_ne_bot : (1 : filter α).ne_bot := filter.pure_ne_bot
@[simp, to_additive] protected lemma map_one' (f : α → β) : (1 : filter α).map f = pure (f 1) := rfl
@[simp, to_additive] lemma le_one_iff : f ≤ 1 ↔ (1 : set α) ∈ f := le_pure_iff
@[to_additive] protected lemma ne_bot.le_one_iff (h : f.ne_bot) : f ≤ 1 ↔ f = 1 := h.le_pure_iff
@[simp, to_additive] lemma eventually_one {p : α → Prop} : (∀ᶠ x in 1, p x) ↔ p 1 := eventually_pure
@[simp, to_additive] lemma tendsto_one {a : filter β} {f : β → α} :
tendsto f a 1 ↔ ∀ᶠ x in a, f x = 1 :=
tendsto_pure
/-- `pure` as a `one_hom`. -/
@[to_additive "`pure` as a `zero_hom`."]
def pure_one_hom : one_hom α (filter α) := ⟨pure, pure_one⟩
@[simp, to_additive] lemma coe_pure_one_hom : (pure_one_hom : α → filter α) = pure := rfl
@[simp, to_additive] lemma pure_one_hom_apply (a : α) : pure_one_hom a = pure a := rfl
variables [has_one β]
@[simp, to_additive]
protected lemma map_one [one_hom_class F α β] (φ : F) : map φ 1 = 1 :=
by rw [filter.map_one', map_one, pure_one]
end has_one
/-! ### Filter negation/inversion -/
section has_inv
variables [has_inv α] {f g : filter α} {s : set α} {a : α}
/-- The inverse of a filter is the pointwise preimage under `⁻¹` of its sets. -/
@[to_additive "The negation of a filter is the pointwise preimage under `-` of its sets."]
instance : has_inv (filter α) := ⟨map has_inv.inv⟩
@[simp, to_additive] protected lemma map_inv : f.map has_inv.inv = f⁻¹ := rfl
@[to_additive] lemma mem_inv : s ∈ f⁻¹ ↔ has_inv.inv ⁻¹' s ∈ f := iff.rfl
@[to_additive] protected lemma inv_le_inv (hf : f ≤ g) : f⁻¹ ≤ g⁻¹ := map_mono hf
@[simp, to_additive] lemma inv_pure : (pure a : filter α)⁻¹ = pure a⁻¹ := rfl
@[simp, to_additive] lemma inv_eq_bot_iff : f⁻¹ = ⊥ ↔ f = ⊥ := map_eq_bot_iff
@[simp, to_additive] lemma ne_bot_inv_iff : f⁻¹.ne_bot ↔ ne_bot f := map_ne_bot_iff _
@[to_additive] lemma ne_bot.inv : f.ne_bot → f⁻¹.ne_bot := λ h, h.map _
end has_inv
section has_involutive_inv
variables [has_involutive_inv α] {f : filter α} {s : set α}
@[to_additive] lemma inv_mem_inv (hs : s ∈ f) : s⁻¹ ∈ f⁻¹ := by rwa [mem_inv, inv_preimage, inv_inv]
/-- Inversion is involutive on `filter α` if it is on `α`. -/
@[to_additive "Negation is involutive on `filter α` if it is on `α`."]
protected def has_involutive_inv : has_involutive_inv (filter α) :=
{ inv_inv := λ f, map_map.trans $ by rw [inv_involutive.comp_self, map_id],
..filter.has_inv }
end has_involutive_inv
/-! ### Filter addition/multiplication -/
section has_mul
variables [has_mul α] [has_mul β] {f f₁ f₂ g g₁ g₂ h : filter α} {s t : set α} {a b : α}
/-- The filter `f * g` is generated by `{s * t | s ∈ f, t ∈ g}` in locale `pointwise`. -/
@[to_additive "The filter `f + g` is generated by `{s + t | s ∈ f, t ∈ g}` in locale `pointwise`."]
protected def has_mul : has_mul (filter α) :=
/- This is defeq to `map₂ (*) f g`, but the hypothesis unfolds to `t₁ * t₂ ⊆ s` rather than all the
way to `set.image2 (*) t₁ t₂ ⊆ s`. -/
⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ * t₂ ⊆ s}, ..map₂ (*) f g }⟩
localized "attribute [instance] filter.has_mul filter.has_add" in pointwise
@[simp, to_additive] lemma map₂_mul : map₂ (*) f g = f * g := rfl
@[to_additive] lemma mem_mul : s ∈ f * g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ * t₂ ⊆ s := iff.rfl
@[to_additive] lemma mul_mem_mul : s ∈ f → t ∈ g → s * t ∈ f * g := image2_mem_map₂
@[simp, to_additive] lemma bot_mul : ⊥ * g = ⊥ := map₂_bot_left
@[simp, to_additive] lemma mul_bot : f * ⊥ = ⊥ := map₂_bot_right
@[simp, to_additive] lemma mul_eq_bot_iff : f * g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff
@[simp, to_additive] lemma mul_ne_bot_iff : (f * g).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff
@[to_additive] lemma ne_bot.mul : ne_bot f → ne_bot g → ne_bot (f * g) := ne_bot.map₂
@[to_additive] lemma ne_bot.of_mul_left : (f * g).ne_bot → f.ne_bot := ne_bot.of_map₂_left
@[to_additive] lemma ne_bot.of_mul_right : (f * g).ne_bot → g.ne_bot := ne_bot.of_map₂_right
@[simp, to_additive] lemma pure_mul : pure a * g = g.map ((*) a) := map₂_pure_left
@[simp, to_additive] lemma mul_pure : f * pure b = f.map (* b) := map₂_pure_right
@[simp, to_additive] lemma pure_mul_pure : (pure a : filter α) * pure b = pure (a * b) := map₂_pure
@[simp, to_additive] lemma le_mul_iff : h ≤ f * g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s * t ∈ h :=
le_map₂_iff
@[to_additive] instance covariant_mul : covariant_class (filter α) (filter α) (*) (≤) :=
⟨λ f g h, map₂_mono_left⟩
@[to_additive] instance covariant_swap_mul : covariant_class (filter α) (filter α) (swap (*)) (≤) :=
⟨λ f g h, map₂_mono_right⟩
@[to_additive]
protected lemma map_mul [mul_hom_class F α β] (m : F) : (f₁ * f₂).map m = f₁.map m * f₂.map m :=
map_map₂_distrib $ map_mul m
/-- `pure` operation as a `mul_hom`. -/
@[to_additive "The singleton operation as an `add_hom`."]
def pure_mul_hom : α →ₙ* filter α := ⟨pure, λ a b, pure_mul_pure.symm⟩
@[simp, to_additive] lemma coe_pure_mul_hom : (pure_mul_hom : α → filter α) = pure := rfl
@[simp, to_additive] lemma pure_mul_hom_apply (a : α) : pure_mul_hom a = pure a := rfl
end has_mul
/-! ### Filter subtraction/division -/
section div
variables [has_div α] {f f₁ f₂ g g₁ g₂ h : filter α} {s t : set α} {a b : α}
/-- The filter `f / g` is generated by `{s / t | s ∈ f, t ∈ g}` in locale `pointwise`. -/
@[to_additive "The filter `f - g` is generated by `{s - t | s ∈ f, t ∈ g}` in locale `pointwise`."]
protected def has_div : has_div (filter α) :=
/- This is defeq to `map₂ (/) f g`, but the hypothesis unfolds to `t₁ / t₂ ⊆ s` rather than all the
way to `set.image2 (/) t₁ t₂ ⊆ s`. -/
⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ / t₂ ⊆ s}, ..map₂ (/) f g }⟩
localized "attribute [instance] filter.has_div filter.has_sub" in pointwise
@[simp, to_additive] lemma map₂_div : map₂ (/) f g = f / g := rfl
@[to_additive] lemma mem_div : s ∈ f / g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ / t₂ ⊆ s := iff.rfl
@[to_additive] lemma div_mem_div : s ∈ f → t ∈ g → s / t ∈ f / g := image2_mem_map₂
@[simp, to_additive] lemma bot_div : ⊥ / g = ⊥ := map₂_bot_left
@[simp, to_additive] lemma div_bot : f / ⊥ = ⊥ := map₂_bot_right
@[simp, to_additive] lemma div_eq_bot_iff : f / g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff
@[simp, to_additive] lemma div_ne_bot_iff : (f / g).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff
@[to_additive] lemma ne_bot.div : ne_bot f → ne_bot g → ne_bot (f / g) := ne_bot.map₂
@[to_additive] lemma ne_bot.of_div_left : (f / g).ne_bot → f.ne_bot := ne_bot.of_map₂_left
@[to_additive] lemma ne_bot.of_div_right : (f / g).ne_bot → g.ne_bot := ne_bot.of_map₂_right
@[simp, to_additive] lemma pure_div : pure a / g = g.map ((/) a) := map₂_pure_left
@[simp, to_additive] lemma div_pure : f / pure b = f.map (/ b) := map₂_pure_right
@[simp, to_additive] lemma pure_div_pure : (pure a : filter α) / pure b = pure (a / b) := map₂_pure
@[to_additive] protected lemma div_le_div : f₁ ≤ f₂ → g₁ ≤ g₂ → f₁ / g₁ ≤ f₂ / g₂ := map₂_mono
@[to_additive] protected lemma div_le_div_left : g₁ ≤ g₂ → f / g₁ ≤ f / g₂ := map₂_mono_left
@[to_additive] protected lemma div_le_div_right : f₁ ≤ f₂ → f₁ / g ≤ f₂ / g := map₂_mono_right
@[simp, to_additive] protected lemma le_div_iff :
h ≤ f / g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s / t ∈ h :=
le_map₂_iff
@[to_additive] instance covariant_div : covariant_class (filter α) (filter α) (/) (≤) :=
⟨λ f g h, map₂_mono_left⟩
@[to_additive] instance covariant_swap_div : covariant_class (filter α) (filter α) (swap (/)) (≤) :=
⟨λ f g h, map₂_mono_right⟩
end div
open_locale pointwise
/-- Repeated pointwise addition (not the same as pointwise repeated addition!) of a `filter`. See
Note [pointwise nat action].-/
protected def has_nsmul [has_zero α] [has_add α] : has_smul ℕ (filter α) := ⟨nsmul_rec⟩
/-- Repeated pointwise multiplication (not the same as pointwise repeated multiplication!) of a
`filter`. See Note [pointwise nat action]. -/
@[to_additive]
protected def has_npow [has_one α] [has_mul α] : has_pow (filter α) ℕ := ⟨λ s n, npow_rec n s⟩
/-- Repeated pointwise addition/subtraction (not the same as pointwise repeated
addition/subtraction!) of a `filter`. See Note [pointwise nat action]. -/
protected def has_zsmul [has_zero α] [has_add α] [has_neg α] : has_smul ℤ (filter α) :=
⟨zsmul_rec⟩
/-- Repeated pointwise multiplication/division (not the same as pointwise repeated
multiplication/division!) of a `filter`. See Note [pointwise nat action]. -/
@[to_additive] protected def has_zpow [has_one α] [has_mul α] [has_inv α] : has_pow (filter α) ℤ :=
⟨λ s n, zpow_rec n s⟩
localized "attribute [instance] filter.has_nsmul filter.has_npow filter.has_zsmul filter.has_zpow"
in pointwise
/-- `filter α` is a `semigroup` under pointwise operations if `α` is.-/
@[to_additive "`filter α` is an `add_semigroup` under pointwise operations if `α` is."]
protected def semigroup [semigroup α] : semigroup (filter α) :=
{ mul := (*),
mul_assoc := λ f g h, map₂_assoc mul_assoc }
/-- `filter α` is a `comm_semigroup` under pointwise operations if `α` is. -/
@[to_additive "`filter α` is an `add_comm_semigroup` under pointwise operations if `α` is."]
protected def comm_semigroup [comm_semigroup α] : comm_semigroup (filter α) :=
{ mul_comm := λ f g, map₂_comm mul_comm,
..filter.semigroup }
section mul_one_class
variables [mul_one_class α] [mul_one_class β]
/-- `filter α` is a `mul_one_class` under pointwise operations if `α` is. -/
@[to_additive "`filter α` is an `add_zero_class` under pointwise operations if `α` is."]
protected def mul_one_class : mul_one_class (filter α) :=
{ one := 1,
mul := (*),
one_mul := λ f, by simp only [←pure_one, ←map₂_mul, map₂_pure_left, one_mul, map_id'],
mul_one := λ f, by simp only [←pure_one, ←map₂_mul, map₂_pure_right, mul_one, map_id'] }
localized "attribute [instance] filter.semigroup filter.add_semigroup filter.comm_semigroup
filter.add_comm_semigroup filter.mul_one_class filter.add_zero_class" in pointwise
/-- If `φ : α →* β` then `map_monoid_hom φ` is the monoid homomorphism
`filter α →* filter β` induced by `map φ`. -/
@[to_additive "If `φ : α →+ β` then `map_add_monoid_hom φ` is the monoid homomorphism
`filter α →+ filter β` induced by `map φ`."]
def map_monoid_hom [monoid_hom_class F α β] (φ : F) : filter α →* filter β :=
{ to_fun := map φ,
map_one' := filter.map_one φ,
map_mul' := λ _ _, filter.map_mul φ }
-- The other direction does not hold in general
@[to_additive]
lemma comap_mul_comap_le [mul_hom_class F α β] (m : F) {f g : filter β} :
f.comap m * g.comap m ≤ (f * g).comap m :=
λ s ⟨t, ⟨t₁, t₂, ht₁, ht₂, t₁t₂⟩, mt⟩,
⟨m ⁻¹' t₁, m ⁻¹' t₂, ⟨t₁, ht₁, subset.rfl⟩, ⟨t₂, ht₂, subset.rfl⟩,
(preimage_mul_preimage_subset _).trans $ (preimage_mono t₁t₂).trans mt⟩
@[to_additive]
lemma tendsto.mul_mul [mul_hom_class F α β] (m : F) {f₁ g₁ : filter α} {f₂ g₂ : filter β} :
tendsto m f₁ f₂ → tendsto m g₁ g₂ → tendsto m (f₁ * g₁) (f₂ * g₂) :=
λ hf hg, (filter.map_mul m).trans_le $ mul_le_mul' hf hg
/-- `pure` as a `monoid_hom`. -/
@[to_additive "`pure` as an `add_monoid_hom`."]
def pure_monoid_hom : α →* filter α := { ..pure_mul_hom, ..pure_one_hom }
@[simp, to_additive] lemma coe_pure_monoid_hom : (pure_monoid_hom : α → filter α) = pure := rfl
@[simp, to_additive] lemma pure_monoid_hom_apply (a : α) : pure_monoid_hom a = pure a := rfl
end mul_one_class
section monoid
variables [monoid α] {f g : filter α} {s : set α} {a : α} {m n : ℕ}
/-- `filter α` is a `monoid` under pointwise operations if `α` is. -/
@[to_additive "`filter α` is an `add_monoid` under pointwise operations if `α` is."]
protected def monoid : monoid (filter α) :=
{ ..filter.mul_one_class, ..filter.semigroup, ..filter.has_npow }
localized "attribute [instance] filter.monoid filter.add_monoid" in pointwise
@[to_additive] lemma pow_mem_pow (hs : s ∈ f) : ∀ n : ℕ, s ^ n ∈ f ^ n
| 0 := by { rw pow_zero, exact one_mem_one }
| (n + 1) := by { rw pow_succ, exact mul_mem_mul hs (pow_mem_pow _) }
@[simp, to_additive nsmul_bot] lemma bot_pow {n : ℕ} (hn : n ≠ 0) : (⊥ : filter α) ^ n = ⊥ :=
by rw [←tsub_add_cancel_of_le (nat.succ_le_of_lt $ nat.pos_of_ne_zero hn), pow_succ, bot_mul]
@[to_additive] lemma mul_top_of_one_le (hf : 1 ≤ f) : f * ⊤ = ⊤ :=
begin
refine top_le_iff.1 (λ s, _),
simp only [mem_mul, mem_top, exists_and_distrib_left, exists_eq_left],
rintro ⟨t, ht, hs⟩,
rwa [mul_univ_of_one_mem (mem_one.1 $ hf ht), univ_subset_iff] at hs,
end
@[to_additive] lemma top_mul_of_one_le (hf : 1 ≤ f) : ⊤ * f = ⊤ :=
begin
refine top_le_iff.1 (λ s, _),
simp only [mem_mul, mem_top, exists_and_distrib_left, exists_eq_left],
rintro ⟨t, ht, hs⟩,
rwa [univ_mul_of_one_mem (mem_one.1 $ hf ht), univ_subset_iff] at hs,
end
@[simp, to_additive] lemma top_mul_top : (⊤ : filter α) * ⊤ = ⊤ := mul_top_of_one_le le_top
--TODO: `to_additive` trips up on the `1 : ℕ` used in the pattern-matching.
lemma nsmul_top {α : Type*} [add_monoid α] : ∀ {n : ℕ}, n ≠ 0 → n • (⊤ : filter α) = ⊤
| 0 := λ h, (h rfl).elim
| 1 := λ _, one_nsmul _
| (n + 2) := λ _, by { rw [succ_nsmul, nsmul_top n.succ_ne_zero, top_add_top] }
@[to_additive nsmul_top] lemma top_pow : ∀ {n : ℕ}, n ≠ 0 → (⊤ : filter α) ^ n = ⊤
| 0 := λ h, (h rfl).elim
| 1 := λ _, pow_one _
| (n + 2) := λ _, by { rw [pow_succ, top_pow n.succ_ne_zero, top_mul_top] }
@[to_additive] protected lemma _root_.is_unit.filter : is_unit a → is_unit (pure a : filter α) :=
is_unit.map (pure_monoid_hom : α →* filter α)
end monoid
/-- `filter α` is a `comm_monoid` under pointwise operations if `α` is. -/
@[to_additive "`filter α` is an `add_comm_monoid` under pointwise operations if `α` is."]
protected def comm_monoid [comm_monoid α] : comm_monoid (filter α) :=
{ ..filter.mul_one_class, ..filter.comm_semigroup }
open_locale pointwise
section division_monoid
variables [division_monoid α] {f g : filter α}
@[to_additive]
protected lemma mul_eq_one_iff : f * g = 1 ↔ ∃ a b, f = pure a ∧ g = pure b ∧ a * b = 1 :=
begin
refine ⟨λ hfg, _, _⟩,
{ obtain ⟨t₁, t₂, h₁, h₂, h⟩ : (1 : set α) ∈ f * g := hfg.symm.subst one_mem_one,
have hfg : (f * g).ne_bot := hfg.symm.subst one_ne_bot,
rw [(hfg.nonempty_of_mem $ mul_mem_mul h₁ h₂).subset_one_iff, set.mul_eq_one_iff] at h,
obtain ⟨a, b, rfl, rfl, h⟩ := h,
refine ⟨a, b, _, _, h⟩,
{ rwa [←hfg.of_mul_left.le_pure_iff, le_pure_iff] },
{ rwa [←hfg.of_mul_right.le_pure_iff, le_pure_iff] } },
{ rintro ⟨a, b, rfl, rfl, h⟩,
rw [pure_mul_pure, h, pure_one] }
end
/-- `filter α` is a division monoid under pointwise operations if `α` is. -/
@[to_additive subtraction_monoid "`filter α` is a subtraction monoid under pointwise
operations if `α` is."]
protected def division_monoid : division_monoid (filter α) :=
{ mul_inv_rev := λ s t, map_map₂_antidistrib mul_inv_rev,
inv_eq_of_mul := λ s t h, begin
obtain ⟨a, b, rfl, rfl, hab⟩ := filter.mul_eq_one_iff.1 h,
rw [inv_pure, inv_eq_of_mul_eq_one_right hab],
end,
div_eq_mul_inv := λ f g, map_map₂_distrib_right div_eq_mul_inv,
..filter.monoid, ..filter.has_involutive_inv, ..filter.has_div, ..filter.has_zpow }
@[to_additive] lemma is_unit_iff : is_unit f ↔ ∃ a, f = pure a ∧ is_unit a :=
begin
split,
{ rintro ⟨u, rfl⟩,
obtain ⟨a, b, ha, hb, h⟩ := filter.mul_eq_one_iff.1 u.mul_inv,
refine ⟨a, ha, ⟨a, b, h, pure_injective _⟩, rfl⟩,
rw [←pure_mul_pure, ←ha, ←hb],
exact u.inv_mul },
{ rintro ⟨a, rfl, ha⟩,
exact ha.filter }
end
end division_monoid
/-- `filter α` is a commutative division monoid under pointwise operations if `α` is. -/
@[to_additive subtraction_comm_monoid "`filter α` is a commutative subtraction monoid under
pointwise operations if `α` is."]
protected def division_comm_monoid [division_comm_monoid α] : division_comm_monoid (filter α) :=
{ ..filter.division_monoid, ..filter.comm_semigroup }
/-- `filter α` has distributive negation if `α` has. -/
protected def has_distrib_neg [has_mul α] [has_distrib_neg α] : has_distrib_neg (filter α) :=
{ neg_mul := λ _ _, map₂_map_left_comm neg_mul,
mul_neg := λ _ _, map_map₂_right_comm mul_neg,
..filter.has_involutive_neg }
localized "attribute [instance] filter.comm_monoid filter.add_comm_monoid filter.division_monoid
filter.subtraction_monoid filter.division_comm_monoid filter.subtraction_comm_monoid
filter.has_distrib_neg" in pointwise
section distrib
variables [distrib α] {f g h : filter α}
/-!
Note that `filter α` is not a `distrib` because `f * g + f * h` has cross terms that `f * (g + h)`
lacks.
-/
lemma mul_add_subset : f * (g + h) ≤ f * g + f * h := map₂_distrib_le_left mul_add
lemma add_mul_subset : (f + g) * h ≤ f * h + g * h := map₂_distrib_le_right add_mul
end distrib
section mul_zero_class
variables [mul_zero_class α] {f g : filter α}
/-! Note that `filter` is not a `mul_zero_class` because `0 * ⊥ ≠ 0`. -/
lemma ne_bot.mul_zero_nonneg (hf : f.ne_bot) : 0 ≤ f * 0 :=
le_mul_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨a, ha⟩ := hf.nonempty_of_mem h₁ in ⟨_, _, ha, h₂, mul_zero _⟩
lemma ne_bot.zero_mul_nonneg (hg : g.ne_bot) : 0 ≤ 0 * g :=
le_mul_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨b, hb⟩ := hg.nonempty_of_mem h₂ in ⟨_, _, h₁, hb, zero_mul _⟩
end mul_zero_class
section group
variables [group α] [division_monoid β] [monoid_hom_class F α β] (m : F) {f g f₁ g₁ : filter α}
{f₂ g₂ : filter β}
/-! Note that `filter α` is not a group because `f / f ≠ 1` in general -/
@[simp, to_additive] protected lemma one_le_div_iff : 1 ≤ f / g ↔ ¬ disjoint f g :=
begin
refine ⟨λ h hfg, _, _⟩,
{ obtain ⟨s, hs, t, ht, hst⟩ := hfg (mem_bot : ∅ ∈ ⊥),
exact set.one_mem_div_iff.1 (h $ div_mem_div hs ht) (disjoint_iff.2 hst.symm) },
{ rintro h s ⟨t₁, t₂, h₁, h₂, hs⟩,
exact hs (set.one_mem_div_iff.2 $ λ ht, h $ disjoint_of_disjoint_of_mem ht h₁ h₂) }
end
@[to_additive] lemma not_one_le_div_iff : ¬ 1 ≤ f / g ↔ disjoint f g :=
filter.one_le_div_iff.not_left
@[to_additive] lemma ne_bot.one_le_div (h : f.ne_bot) : 1 ≤ f / f :=
begin
rintro s ⟨t₁, t₂, h₁, h₂, hs⟩,
obtain ⟨a, ha₁, ha₂⟩ := set.not_disjoint_iff.1 (h.not_disjoint h₁ h₂),
rw [mem_one, ←div_self' a],
exact hs (set.div_mem_div ha₁ ha₂),
end
@[to_additive] lemma is_unit_pure (a : α) : is_unit (pure a : filter α) := (group.is_unit a).filter
@[simp] lemma is_unit_iff_singleton : is_unit f ↔ ∃ a, f = pure a :=
by simp only [is_unit_iff, group.is_unit, and_true]
include β
@[to_additive] lemma map_inv' : f⁻¹.map m = (f.map m)⁻¹ := semiconj.filter_map (map_inv m) f
@[to_additive] lemma tendsto.inv_inv : tendsto m f₁ f₂ → tendsto m f₁⁻¹ f₂⁻¹ :=
λ hf, (filter.map_inv' m).trans_le $ filter.inv_le_inv hf
@[to_additive] protected lemma map_div : (f / g).map m = f.map m / g.map m :=
map_map₂_distrib $ map_div m
@[to_additive]
lemma tendsto.div_div : tendsto m f₁ f₂ → tendsto m g₁ g₂ → tendsto m (f₁ / g₁) (f₂ / g₂) :=
λ hf hg, (filter.map_div m).trans_le $ filter.div_le_div hf hg
end group
open_locale pointwise
section group_with_zero
variables [group_with_zero α] {f g : filter α}
lemma ne_bot.div_zero_nonneg (hf : f.ne_bot) : 0 ≤ f / 0 :=
filter.le_div_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨a, ha⟩ := hf.nonempty_of_mem h₁ in
⟨_, _, ha, h₂, div_zero _⟩
lemma ne_bot.zero_div_nonneg (hg : g.ne_bot) : 0 ≤ 0 / g :=
filter.le_div_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨b, hb⟩ := hg.nonempty_of_mem h₂ in
⟨_, _, h₁, hb, zero_div _⟩
end group_with_zero
/-! ### Scalar addition/multiplication of filters -/
section smul
variables [has_smul α β] {f f₁ f₂ : filter α} {g g₁ g₂ h : filter β} {s : set α} {t : set β}
{a : α} {b : β}
/-- The filter `f • g` is generated by `{s • t | s ∈ f, t ∈ g}` in locale `pointwise`. -/
@[to_additive filter.has_vadd
"The filter `f +ᵥ g` is generated by `{s +ᵥ t | s ∈ f, t ∈ g}` in locale `pointwise`."]
protected def has_smul : has_smul (filter α) (filter β) :=
/- This is defeq to `map₂ (•) f g`, but the hypothesis unfolds to `t₁ • t₂ ⊆ s` rather than all the
way to `set.image2 (•) t₁ t₂ ⊆ s`. -/
⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ • t₂ ⊆ s}, ..map₂ (•) f g }⟩
localized "attribute [instance] filter.has_smul filter.has_vadd" in pointwise
@[simp, to_additive] lemma map₂_smul : map₂ (•) f g = f • g := rfl
@[to_additive] lemma mem_smul : t ∈ f • g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ • t₂ ⊆ t := iff.rfl
@[to_additive] lemma smul_mem_smul : s ∈ f → t ∈ g → s • t ∈ f • g := image2_mem_map₂
@[simp, to_additive] lemma bot_smul : (⊥ : filter α) • g = ⊥ := map₂_bot_left
@[simp, to_additive] lemma smul_bot : f • (⊥ : filter β) = ⊥ := map₂_bot_right
@[simp, to_additive] lemma smul_eq_bot_iff : f • g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff
@[simp, to_additive] lemma smul_ne_bot_iff : (f • g).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff
@[to_additive] lemma ne_bot.smul : ne_bot f → ne_bot g → ne_bot (f • g) := ne_bot.map₂
@[to_additive] lemma ne_bot.of_smul_left : (f • g).ne_bot → f.ne_bot := ne_bot.of_map₂_left
@[to_additive] lemma ne_bot.of_smul_right : (f • g).ne_bot → g.ne_bot := ne_bot.of_map₂_right
@[simp, to_additive] lemma pure_smul : (pure a : filter α) • g = g.map ((•) a) := map₂_pure_left
@[simp, to_additive] lemma smul_pure : f • pure b = f.map (• b) := map₂_pure_right
@[simp, to_additive] lemma pure_smul_pure :
(pure a : filter α) • (pure b : filter β) = pure (a • b) := map₂_pure
@[to_additive] lemma smul_le_smul : f₁ ≤ f₂ → g₁ ≤ g₂ → f₁ • g₁ ≤ f₂ • g₂ := map₂_mono
@[to_additive] lemma smul_le_smul_left : g₁ ≤ g₂ → f • g₁ ≤ f • g₂ := map₂_mono_left
@[to_additive] lemma smul_le_smul_right : f₁ ≤ f₂ → f₁ • g ≤ f₂ • g := map₂_mono_right
@[simp, to_additive] lemma le_smul_iff : h ≤ f • g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s • t ∈ h :=
le_map₂_iff
@[to_additive] instance covariant_smul : covariant_class (filter α) (filter β) (•) (≤) :=
⟨λ f g h, map₂_mono_left⟩
end smul
/-! ### Scalar subtraction of filters -/
section vsub
variables [has_vsub α β] {f f₁ f₂ g g₁ g₂ : filter β} {h : filter α} {s t : set β} {a b : β}
include α
/-- The filter `f -ᵥ g` is generated by `{s -ᵥ t | s ∈ f, t ∈ g}` in locale `pointwise`. -/
protected def has_vsub : has_vsub (filter α) (filter β) :=
/- This is defeq to `map₂ (-ᵥ) f g`, but the hypothesis unfolds to `t₁ -ᵥ t₂ ⊆ s` rather than all
the way to `set.image2 (-ᵥ) t₁ t₂ ⊆ s`. -/
⟨λ f g, { sets := {s | ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ -ᵥ t₂ ⊆ s}, ..map₂ (-ᵥ) f g }⟩
localized "attribute [instance] filter.has_vsub" in pointwise
@[simp] lemma map₂_vsub : map₂ (-ᵥ) f g = f -ᵥ g := rfl
lemma mem_vsub {s : set α} : s ∈ f -ᵥ g ↔ ∃ t₁ t₂, t₁ ∈ f ∧ t₂ ∈ g ∧ t₁ -ᵥ t₂ ⊆ s := iff.rfl
lemma vsub_mem_vsub : s ∈ f → t ∈ g → s -ᵥ t ∈ f -ᵥ g := image2_mem_map₂
@[simp] lemma bot_vsub : (⊥ : filter β) -ᵥ g = ⊥ := map₂_bot_left
@[simp] lemma vsub_bot : f -ᵥ (⊥ : filter β) = ⊥ := map₂_bot_right
@[simp] lemma vsub_eq_bot_iff : f -ᵥ g = ⊥ ↔ f = ⊥ ∨ g = ⊥ := map₂_eq_bot_iff
@[simp] lemma vsub_ne_bot_iff : (f -ᵥ g : filter α).ne_bot ↔ f.ne_bot ∧ g.ne_bot := map₂_ne_bot_iff
lemma ne_bot.vsub : ne_bot f → ne_bot g → ne_bot (f -ᵥ g) := ne_bot.map₂
lemma ne_bot.of_vsub_left : (f -ᵥ g : filter α).ne_bot → f.ne_bot := ne_bot.of_map₂_left
lemma ne_bot.of_vsub_right : (f -ᵥ g : filter α).ne_bot → g.ne_bot := ne_bot.of_map₂_right
@[simp] lemma pure_vsub : (pure a : filter β) -ᵥ g = g.map ((-ᵥ) a) := map₂_pure_left
@[simp] lemma vsub_pure : f -ᵥ pure b = f.map (-ᵥ b) := map₂_pure_right
@[simp] lemma pure_vsub_pure : (pure a : filter β) -ᵥ pure b = (pure (a -ᵥ b) : filter α) :=
map₂_pure
lemma vsub_le_vsub : f₁ ≤ f₂ → g₁ ≤ g₂ → f₁ -ᵥ g₁ ≤ f₂ -ᵥ g₂ := map₂_mono
lemma vsub_le_vsub_left : g₁ ≤ g₂ → f -ᵥ g₁ ≤ f -ᵥ g₂ := map₂_mono_left
lemma vsub_le_vsub_right : f₁ ≤ f₂ → f₁ -ᵥ g ≤ f₂ -ᵥ g := map₂_mono_right
@[simp] lemma le_vsub_iff : h ≤ f -ᵥ g ↔ ∀ ⦃s⦄, s ∈ f → ∀ ⦃t⦄, t ∈ g → s -ᵥ t ∈ h := le_map₂_iff
end vsub
/-! ### Translation/scaling of filters -/
section smul
variables [has_smul α β] {f f₁ f₂ : filter β} {s : set β} {a : α}
/-- `a • f` is the map of `f` under `a •` in locale `pointwise`. -/
@[to_additive filter.has_vadd_filter
"`a +ᵥ f` is the map of `f` under `a +ᵥ` in locale `pointwise`."]
protected def has_smul_filter : has_smul α (filter β) := ⟨λ a, map ((•) a)⟩
localized "attribute [instance] filter.has_smul_filter filter.has_vadd_filter" in pointwise
@[simp, to_additive] lemma map_smul : map (λ b, a • b) f = a • f := rfl
@[to_additive] lemma mem_smul_filter : s ∈ a • f ↔ (•) a ⁻¹' s ∈ f := iff.rfl
@[to_additive] lemma smul_set_mem_smul_filter : s ∈ f → a • s ∈ a • f := image_mem_map
@[simp, to_additive] lemma smul_filter_bot : a • (⊥ : filter β) = ⊥ := map_bot
@[simp, to_additive] lemma smul_filter_eq_bot_iff : a • f = ⊥ ↔ f = ⊥ := map_eq_bot_iff
@[simp, to_additive] lemma smul_filter_ne_bot_iff : (a • f).ne_bot ↔ f.ne_bot := map_ne_bot_iff _
@[to_additive] lemma ne_bot.smul_filter : f.ne_bot → (a • f).ne_bot := λ h, h.map _
@[to_additive] lemma ne_bot.of_smul_filter : (a • f).ne_bot → f.ne_bot := ne_bot.of_map
@[to_additive] lemma smul_filter_le_smul_filter (hf : f₁ ≤ f₂) : a • f₁ ≤ a • f₂ :=
map_mono hf
@[to_additive] instance covariant_smul_filter : covariant_class α (filter β) (•) (≤) :=
⟨λ f, map_mono⟩
end smul
open_locale pointwise
@[to_additive]
instance smul_comm_class_filter [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] :
smul_comm_class α β (filter γ) :=
⟨λ _ _ _, map_comm (funext $ smul_comm _ _) _⟩
@[to_additive]
instance smul_comm_class_filter' [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] :
smul_comm_class α (filter β) (filter γ) :=
⟨λ a f g, map_map₂_distrib_right $ smul_comm a⟩
@[to_additive]
instance smul_comm_class_filter'' [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] :
smul_comm_class (filter α) β (filter γ) :=
by haveI := smul_comm_class.symm α β γ; exact smul_comm_class.symm _ _ _
@[to_additive]
instance smul_comm_class [has_smul α γ] [has_smul β γ] [smul_comm_class α β γ] :
smul_comm_class (filter α) (filter β) (filter γ) :=
⟨λ f g h, map₂_left_comm smul_comm⟩
instance is_scalar_tower [has_smul α β] [has_smul α γ] [has_smul β γ]
[is_scalar_tower α β γ] :
is_scalar_tower α β (filter γ) :=
⟨λ a b f, by simp only [←map_smul, map_map, smul_assoc]⟩
instance is_scalar_tower' [has_smul α β] [has_smul α γ] [has_smul β γ]
[is_scalar_tower α β γ] :
is_scalar_tower α (filter β) (filter γ) :=
⟨λ a f g, by { refine (map_map₂_distrib_left $ λ _ _, _).symm, exact (smul_assoc a _ _).symm }⟩
instance is_scalar_tower'' [has_smul α β] [has_smul α γ] [has_smul β γ]
[is_scalar_tower α β γ] :
is_scalar_tower (filter α) (filter β) (filter γ) :=
⟨λ f g h, map₂_assoc smul_assoc⟩
instance is_central_scalar [has_smul α β] [has_smul αᵐᵒᵖ β] [is_central_scalar α β] :
is_central_scalar α (filter β) :=
⟨λ a f, congr_arg (λ m, map m f) $ by exact funext (λ _, op_smul_eq_smul _ _)⟩
/-- A multiplicative action of a monoid `α` on a type `β` gives a multiplicative action of
`filter α` on `filter β`. -/
@[to_additive "An additive action of an additive monoid `α` on a type `β` gives an additive action
of `filter α` on `filter β`"]
protected def mul_action [monoid α] [mul_action α β] : mul_action (filter α) (filter β) :=
{ one_smul := λ f, map₂_pure_left.trans $ by simp_rw [one_smul, map_id'],
mul_smul := λ f g h, map₂_assoc mul_smul }
/-- A multiplicative action of a monoid on a type `β` gives a multiplicative action on `filter β`.
-/
@[to_additive "An additive action of an additive monoid on a type `β` gives an additive action on
`filter β`."]
protected def mul_action_filter [monoid α] [mul_action α β] : mul_action α (filter β) :=
{ mul_smul := λ a b f, by simp only [←map_smul, map_map, function.comp, ←mul_smul],
one_smul := λ f, by simp only [←map_smul, one_smul, map_id'] }
localized "attribute [instance] filter.mul_action filter.add_action filter.mul_action_filter
filter.add_action_filter" in pointwise
/-- A distributive multiplicative action of a monoid on an additive monoid `β` gives a distributive
multiplicative action on `filter β`. -/
protected def distrib_mul_action_filter [monoid α] [add_monoid β] [distrib_mul_action α β] :
distrib_mul_action α (filter β) :=
{ smul_add := λ _ _ _, map_map₂_distrib $ smul_add _,
smul_zero := λ _, (map_pure _ _).trans $ by rw [smul_zero, pure_zero] }
/-- A multiplicative action of a monoid on a monoid `β` gives a multiplicative action on `set β`. -/
protected def mul_distrib_mul_action_filter [monoid α] [monoid β] [mul_distrib_mul_action α β] :
mul_distrib_mul_action α (set β) :=
{ smul_mul := λ _ _ _, image_image2_distrib $ smul_mul' _,
smul_one := λ _, image_singleton.trans $ by rw [smul_one, singleton_one] }
localized "attribute [instance] filter.distrib_mul_action_filter
filter.mul_distrib_mul_action_filter" in pointwise
section smul_with_zero
variables [has_zero α] [has_zero β] [smul_with_zero α β] {f : filter α} {g : filter β}
/-!
Note that we have neither `smul_with_zero α (filter β)` nor `smul_with_zero (filter α) (filter β)`
because `0 * ⊥ ≠ 0`.
-/
lemma ne_bot.smul_zero_nonneg (hf : f.ne_bot) : 0 ≤ f • (0 : filter β) :=
le_smul_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨a, ha⟩ := hf.nonempty_of_mem h₁ in
⟨_, _, ha, h₂, smul_zero' _ _⟩
lemma ne_bot.zero_smul_nonneg (hg : g.ne_bot) : 0 ≤ (0 : filter α) • g :=
le_smul_iff.2 $ λ t₁ h₁ t₂ h₂, let ⟨b, hb⟩ := hg.nonempty_of_mem h₂ in ⟨_, _, h₁, hb, zero_smul _ _⟩
lemma zero_smul_filter_nonpos : (0 : α) • g ≤ 0 :=
begin
refine λ s hs, mem_smul_filter.2 _,
convert univ_mem,
refine eq_univ_iff_forall.2 (λ a, _),
rwa [mem_preimage, zero_smul],
end
lemma zero_smul_filter (hg : g.ne_bot) : (0 : α) • g = 0 :=
zero_smul_filter_nonpos.antisymm $ le_map_iff.2 $ λ s hs, begin
simp_rw [set.image_eta, zero_smul, (hg.nonempty_of_mem hs).image_const],
exact zero_mem_zero,
end
end smul_with_zero
end filter
|
114e4aaa4a74c7e9cacc067d97a4d2abf83d2e72 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/bad_pattern2.lean | c3488d3251504fcc8e1c5d597b46ed5d0703cb12 | [
"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 | 50 | lean | definition foo : nat → nat
| bla.boo := bla.boo
|
6cc84f7d183297f4094216bc953a53f2adea91cf | 56e5b79a7ab4f2c52e6eb94f76d8100a25273cf3 | /src/backends/greedy/baseline.lean | f9b60e5af69a31db881ef2482c3012ad7eec4495 | [
"Apache-2.0"
] | permissive | DyeKuu/lean-tpe-public | 3a9968f286ca182723ef7e7d97e155d8cb6b1e70 | 750ade767ab28037e80b7a80360d213a875038f8 | refs/heads/master | 1,682,842,633,115 | 1,621,330,793,000 | 1,621,330,793,000 | 368,475,816 | 0 | 0 | Apache-2.0 | 1,621,330,745,000 | 1,621,330,744,000 | null | UTF-8 | Lean | false | false | 2,058 | lean | import tactic.tidy
import evaluation
namespace baseline
section tidy_proof_search
meta def tidy_default_tactics : list string := [
"refl"
, "exact dec_trivial"
, "assumption"
, "tactic.intros1"
, "tactic.auto_cases"
, "apply_auto_param"
, "dsimp at *"
, "simp at *"
, "ext1"
, "fsplit"
, "injections_and_clear"
, "solve_by_elim"
, "norm_cast"
]
meta def tidy_api : ModelAPI := -- simulates logic of tidy, baseline (deterministic) model
let fn : json → io json := λ msg, do {
pure $ json.array $ json.of_string <$> tidy_default_tactics
} in ⟨fn⟩
meta def tidy_greedy_proof_search_core
(fuel : ℕ := 1000)
(verbose := ff)
: state_t GreedyProofSearchState tactic unit :=
greedy_proof_search_core
tidy_api
(λ _, pure json.null)
(λ msg n, run_best_beam_candidate (unwrap_lm_response $ some "[tidy_greedy_proof_search]") msg n)
fuel
-- TODO(jesse): run against `tidy` test suite to confirm reproduction of `tidy` logic
meta def tidy_greedy_proof_search
(fuel : ℕ := 1000)
(verbose := ff)
: tactic unit :=
greedy_proof_search
tidy_api
(λ _, pure json.null)
(λ msg n, run_best_beam_candidate (unwrap_lm_response $ some "[tidy_greedy_proof_search]") msg n)
fuel
verbose
end tidy_proof_search
section playground
-- example : true :=
-- begin
-- tidy_greedy_proof_search 5 tt,
-- end
-- open nat
-- universe u
-- example : ∀ {α : Type u} {s₁ s₂ t₁ t₂ : list α},
-- s₁ ++ t₁ = s₂ ++ t₂ → s₁.length = s₂.length → s₁ = s₂ ∧ t₁ = t₂ :=
-- begin
-- intros, -- tidy_greedy_proof_search
-- end
-- open nat
-- example {p q r : Prop} (h₁ : p) (h₂ : q) : p ∧ q :=
-- begin
-- tidy_greedy_proof_search 3 tt
-- end
-- run_cmd do {set_show_eval_trace tt *> do env ← tactic.get_env, tactic.set_env_core env}
-- example {p q r : Prop} (h₁ : p) (h₂ : q) : p ∧ q :=
-- begin
-- tidy_greedy_proof_search 2 ff -- should only try one iteration before halting
end playground
end baseline
|
c0136e6949ad22819a7ed734b526a2028ecbb5df | d1bbf1801b3dcb214451d48214589f511061da63 | /src/ring_theory/power_basis.lean | d211d5d10ea7aa53debe2bf1cf5a40305555c6c8 | [
"Apache-2.0"
] | permissive | cheraghchi/mathlib | 5c366f8c4f8e66973b60c37881889da8390cab86 | f29d1c3038422168fbbdb2526abf7c0ff13e86db | refs/heads/master | 1,676,577,831,283 | 1,610,894,638,000 | 1,610,894,638,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 22,754 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import field_theory.adjoin
import field_theory.minpoly
import ring_theory.adjoin
import ring_theory.adjoin_root
import ring_theory.algebraic
/-!
# Power basis
This file defines a structure `power_basis R S`, giving a basis of the
`R`-algebra `S` as a finite list of powers `1, x, ..., x^n`.
There are also constructors for `power_basis` when adjoining an algebraic
element to a ring/field.
## Definitions
* `power_basis R A`: a structure containing an `x` and an `n` such that
`1, x, ..., x^n` is a basis for the `R`-algebra `A` (viewed as an `R`-module).
* `findim (hf : f ≠ 0) : finite_dimensional.findim K (adjoin_root f) = f.nat_degree`,
the dimension of `adjoin_root f` equals the degree of `f`
* `power_basis.lift (pb : power_basis R S)`: if `y : S'` satisfies the same
equations as `pb.gen`, this is the map `S →ₐ[R] S'` sending `pb.gen` to `y`
* `power_basis.equiv`: if two power bases satisfy the same equations, they are
equivalent as algebras
## Implementation notes
Throughout this file, `R`, `S`, ... are `comm_ring`s, `A`, `B`, ... are
`integral_domain`s and `K`, `L`, ... are `field`s.
`S` is an `R`-algebra, `B` is an `A`-algebra, `L` is a `K`-algebra.
## Tags
power basis, powerbasis
-/
open polynomial
variables {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T]
variables [algebra R S] [algebra S T] [algebra R T] [is_scalar_tower R S T]
variables {A B : Type*} [integral_domain A] [integral_domain B] [algebra A B]
variables {K L : Type*} [field K] [field L] [algebra K L]
/-- `pb : power_basis R S` states that `1, pb.gen, ..., pb.gen ^ (pb.dim - 1)`
is a basis for the `R`-algebra `S` (viewed as `R`-module).
This is a structure, not a class, since the same algebra can have many power bases.
For the common case where `S` is defined by adjoining an integral element to `R`,
the canonical power basis is given by `{algebra,intermediate_field}.adjoin.power_basis`.
-/
@[nolint has_inhabited_instance]
structure power_basis (R S : Type*) [comm_ring R] [ring S] [algebra R S] :=
(gen : S)
(dim : ℕ)
(is_basis : is_basis R (λ (i : fin dim), gen ^ (i : ℕ)))
namespace power_basis
/-- Cannot be an instance because `power_basis` cannot be a class. -/
lemma finite_dimensional [algebra K S] (pb : power_basis K S) : finite_dimensional K S :=
finite_dimensional.of_fintype_basis pb.is_basis
lemma findim [algebra K S] (pb : power_basis K S) : finite_dimensional.findim K S = pb.dim :=
by rw [finite_dimensional.findim_eq_card_basis pb.is_basis, fintype.card_fin]
/-- TODO: this mixes `polynomial` and `finsupp`, we should hide this behind a
new function `polynomial.of_finsupp`. -/
lemma polynomial.mem_supported_range {f : polynomial R} {d : ℕ} :
(f : finsupp ℕ R) ∈ finsupp.supported R R (↑(finset.range d) : set ℕ) ↔ f.degree < d :=
by { simp_rw [finsupp.mem_supported', finset.mem_coe, finset.mem_range, not_lt,
degree_lt_iff_coeff_zero],
refl }
lemma mem_span_pow' {x y : S} {d : ℕ} :
y ∈ submodule.span R (set.range (λ (i : fin d), x ^ (i : ℕ))) ↔
∃ f : polynomial R, f.degree < d ∧ y = aeval x f :=
begin
have : set.range (λ (i : fin d), x ^ (i : ℕ)) = (λ (i : ℕ), x ^ i) '' ↑(finset.range d),
{ ext n,
simp_rw [set.mem_range, set.mem_image, finset.mem_coe, finset.mem_range],
exact ⟨λ ⟨⟨i, hi⟩, hy⟩, ⟨i, hi, hy⟩, λ ⟨i, hi, hy⟩, ⟨⟨i, hi⟩, hy⟩⟩ },
rw [this, finsupp.mem_span_iff_total],
-- In the next line we use that `polynomial R := finsupp ℕ R`.
-- It would be nice to have a function `polynomial.of_finsupp`.
apply exists_congr,
rintro (f : polynomial R),
simp only [exists_prop, polynomial.mem_supported_range, eq_comm],
apply and_congr iff.rfl,
split;
{ rintro rfl;
rw [finsupp.total_apply, aeval_def, eval₂_eq_sum, eq_comm],
apply finset.sum_congr rfl,
rintro i -,
simp only [algebra.smul_def] }
end
lemma mem_span_pow {x y : S} {d : ℕ} (hd : d ≠ 0) :
y ∈ submodule.span R (set.range (λ (i : fin d), x ^ (i : ℕ))) ↔
∃ f : polynomial R, f.nat_degree < d ∧ y = aeval x f :=
begin
rw mem_span_pow',
split;
{ rintros ⟨f, h, hy⟩,
refine ⟨f, _, hy⟩,
by_cases hf : f = 0,
{ simp only [hf, nat_degree_zero, degree_zero] at h ⊢,
exact lt_of_le_of_ne (nat.zero_le d) hd.symm <|> exact with_bot.bot_lt_some d },
simpa only [degree_eq_nat_degree hf, with_bot.coe_lt_coe] using h },
end
lemma dim_ne_zero [nontrivial S] (pb : power_basis R S) : pb.dim ≠ 0 :=
λ h, one_ne_zero $
show (1 : S) = 0,
by { rw [← pb.is_basis.total_repr 1, finsupp.total_apply, finsupp.sum_fintype],
{ refine finset.sum_eq_zero (λ x hx, _),
cases x with x x_lt,
rw h at x_lt,
cases x_lt },
{ simp } }
lemma exists_eq_aeval [nontrivial S] (pb : power_basis R S) (y : S) :
∃ f : polynomial R, f.nat_degree < pb.dim ∧ y = aeval pb.gen f :=
(mem_span_pow pb.dim_ne_zero).mp (pb.is_basis.mem_span y)
section minpoly
open_locale big_operators
variable [algebra A S]
/-- `pb.minpoly_gen` is a minimal polynomial for `pb.gen`.
If `A` is not a field, it might not necessarily be *the* minimal polynomial,
however `nat_degree_minpoly` shows its degree is indeed minimal.
-/
noncomputable def minpoly_gen (pb : power_basis A S) : polynomial A :=
X ^ pb.dim -
∑ (i : fin pb.dim), C (pb.is_basis.repr (pb.gen ^ pb.dim) i) * X ^ (i : ℕ)
@[simp]
lemma nat_degree_minpoly_gen (pb : power_basis A S) :
nat_degree (minpoly_gen pb) = pb.dim :=
begin
unfold minpoly_gen,
apply nat_degree_eq_of_degree_eq_some,
rw degree_sub_eq_left_of_degree_lt; rw degree_X_pow,
apply degree_sum_fin_lt
end
lemma minpoly_gen_monic (pb : power_basis A S) : monic (minpoly_gen pb) :=
begin
apply monic_sub_of_left (monic_pow (monic_X) _),
rw degree_X_pow,
exact degree_sum_fin_lt _
end
@[simp]
lemma aeval_minpoly_gen (pb : power_basis A S) : aeval pb.gen (minpoly_gen pb) = 0 :=
begin
simp_rw [minpoly_gen, alg_hom.map_sub, alg_hom.map_sum, alg_hom.map_mul, alg_hom.map_pow,
aeval_C, ← algebra.smul_def, aeval_X],
refine sub_eq_zero.mpr ((pb.is_basis.total_repr (pb.gen ^ pb.dim)).symm.trans _),
rw [finsupp.total_apply, finsupp.sum_fintype],
intro i, rw zero_smul
end
lemma is_integral_gen (pb : power_basis A S) : is_integral A pb.gen :=
⟨minpoly_gen pb, minpoly_gen_monic pb, aeval_minpoly_gen pb⟩
lemma dim_le_nat_degree_of_root (h : power_basis A S) {p : polynomial A}
(ne_zero : p ≠ 0) (root : aeval h.gen p = 0) :
h.dim ≤ p.nat_degree :=
begin
refine le_of_not_lt (λ hlt, ne_zero _),
let p_coeff : fin (h.dim) → A := λ i, p.coeff i,
suffices : ∀ i, p_coeff i = 0,
{ ext i,
by_cases hi : i < h.dim,
{ exact this ⟨i, hi⟩ },
exact coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le hlt (le_of_not_gt hi)) },
intro i,
refine linear_independent_iff'.mp h.is_basis.1 finset.univ _ _ i (finset.mem_univ _),
rw aeval_eq_sum_range' hlt at root,
rw finset.sum_fin_eq_sum_range,
convert root,
ext i,
split_ifs with hi,
{ refl },
{ rw [coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le hlt (le_of_not_gt hi)),
zero_smul] }
end
@[simp]
lemma nat_degree_minpoly (pb : power_basis A S) :
(minpoly pb.is_integral_gen).nat_degree = pb.dim :=
begin
refine le_antisymm _
(dim_le_nat_degree_of_root pb (minpoly.ne_zero _) (minpoly.aeval _)),
rw ← nat_degree_minpoly_gen,
apply nat_degree_le_of_degree_le,
rw ← degree_eq_nat_degree (minpoly_gen_monic pb).ne_zero,
exact minpoly.min _ (minpoly_gen_monic pb) (aeval_minpoly_gen pb)
end
end minpoly
section equiv
variables [algebra A S] {S' : Type*} [comm_ring S'] [algebra A S']
lemma nat_degree_lt_nat_degree {p q : polynomial R} (hp : p ≠ 0) (hpq : p.degree < q.degree) :
p.nat_degree < q.nat_degree :=
begin
by_cases hq : q = 0, { rw [hq, degree_zero] at hpq, have := not_lt_bot hpq, contradiction },
rwa [degree_eq_nat_degree hp, degree_eq_nat_degree hq, with_bot.coe_lt_coe] at hpq
end
lemma constr_pow_aeval (pb : power_basis A S) {y : S'}
(hy : aeval y (minpoly pb.is_integral_gen) = 0) (f : polynomial A) :
pb.is_basis.constr (λ i, y ^ (i : ℕ)) (aeval pb.gen f) = aeval y f :=
begin
rw [← aeval_mod_by_monic_eq_self_of_root
(minpoly.monic pb.is_integral_gen)
(minpoly.aeval _),
← @aeval_mod_by_monic_eq_self_of_root _ _ _ _ _ f _
(minpoly.monic pb.is_integral_gen) y hy],
by_cases hf : f %ₘ minpoly (pb.is_integral_gen) = 0,
{ simp only [hf, alg_hom.map_zero, linear_map.map_zero] },
have : (f %ₘ minpoly _).nat_degree < pb.dim,
{ rw ← pb.nat_degree_minpoly,
apply nat_degree_lt_nat_degree hf,
exact degree_mod_by_monic_lt _ (minpoly.monic _) (minpoly.ne_zero _) },
rw [aeval_eq_sum_range' this, aeval_eq_sum_range' this, linear_map.map_sum],
refine finset.sum_congr rfl (λ i (hi : i ∈ finset.range pb.dim), _),
rw finset.mem_range at hi,
rw linear_map.map_smul,
congr,
exact @constr_basis _ _ _ _ _ _ _ _ _ _ _ (⟨i, hi⟩ : fin pb.dim) pb.is_basis,
end
lemma constr_pow_gen (pb : power_basis A S) {y : S'}
(hy : aeval y (minpoly pb.is_integral_gen) = 0) :
pb.is_basis.constr (λ i, y ^ (i : ℕ)) pb.gen = y :=
by { convert pb.constr_pow_aeval hy X; rw aeval_X }
lemma constr_pow_algebra_map (pb : power_basis A S) {y : S'}
(hy : aeval y (minpoly pb.is_integral_gen) = 0) (x : A) :
pb.is_basis.constr (λ i, y ^ (i : ℕ)) (algebra_map A S x) = algebra_map A S' x :=
by { convert pb.constr_pow_aeval hy (C x); rw aeval_C }
lemma constr_pow_mul [nontrivial S] (pb : power_basis A S) {y : S'}
(hy : aeval y (minpoly pb.is_integral_gen) = 0) (x x' : S) :
pb.is_basis.constr (λ i, y ^ (i : ℕ)) (x * x') =
pb.is_basis.constr (λ i, y ^ (i : ℕ)) x * pb.is_basis.constr (λ i, y ^ (i : ℕ)) x' :=
begin
obtain ⟨f, hf, rfl⟩ := pb.exists_eq_aeval x,
obtain ⟨g, hg, rfl⟩ := pb.exists_eq_aeval x',
simp only [← aeval_mul, pb.constr_pow_aeval hy]
end
/-- `pb.lift y hy` is the algebra map sending `pb.gen` to `y`,
where `hy` states the higher powers of `y` are the same as the higher powers of `pb.gen`. -/
noncomputable def lift [nontrivial S] (pb : power_basis A S) (y : S')
(hy : aeval y (minpoly pb.is_integral_gen) = 0) :
S →ₐ[A] S' :=
{ map_one' := by { convert pb.constr_pow_algebra_map hy 1 using 2; rw ring_hom.map_one },
map_zero' := by { convert pb.constr_pow_algebra_map hy 0 using 2; rw ring_hom.map_zero },
map_mul' := pb.constr_pow_mul hy,
commutes' := pb.constr_pow_algebra_map hy,
.. pb.is_basis.constr (λ i, y ^ (i : ℕ)) }
@[simp] lemma lift_gen [nontrivial S] (pb : power_basis A S) (y : S')
(hy : aeval y (minpoly pb.is_integral_gen) = 0) :
pb.lift y hy pb.gen = y :=
pb.constr_pow_gen hy
@[simp] lemma lift_aeval [nontrivial S] (pb : power_basis A S) (y : S')
(hy : aeval y (minpoly pb.is_integral_gen) = 0) (f : polynomial A) :
pb.lift y hy (aeval pb.gen f) = aeval y f :=
pb.constr_pow_aeval hy f
/-- `pb.equiv pb' h` is an equivalence of algebras with the same power basis. -/
noncomputable def equiv [nontrivial S] [nontrivial S']
(pb : power_basis A S) (pb' : power_basis A S')
(h : minpoly pb.is_integral_gen = minpoly pb'.is_integral_gen) :
S ≃ₐ[A] S' :=
alg_equiv.of_alg_hom
(pb.lift pb'.gen (h.symm ▸ minpoly.aeval pb'.is_integral_gen))
(pb'.lift pb.gen (h ▸ minpoly.aeval pb.is_integral_gen))
(by { ext x, obtain ⟨f, hf, rfl⟩ := pb'.exists_eq_aeval x, simp })
(by { ext x, obtain ⟨f, hf, rfl⟩ := pb.exists_eq_aeval x, simp })
@[simp]
lemma equiv_aeval [nontrivial S] [nontrivial S']
(pb : power_basis A S) (pb' : power_basis A S')
(h : minpoly pb.is_integral_gen = minpoly pb'.is_integral_gen)
(f : polynomial A) :
pb.equiv pb' h (aeval pb.gen f) = aeval pb'.gen f :=
pb.lift_aeval _ (h.symm ▸ minpoly.aeval _) _
@[simp]
lemma equiv_gen [nontrivial S] [nontrivial S']
(pb : power_basis A S) (pb' : power_basis A S')
(h : minpoly pb.is_integral_gen = minpoly pb'.is_integral_gen) :
pb.equiv pb' h pb.gen = pb'.gen :=
pb.lift_gen _ (h.symm ▸ minpoly.aeval _)
local attribute [irreducible] power_basis.lift
@[simp]
lemma equiv_symm [nontrivial S] [nontrivial S']
(pb : power_basis A S) (pb' : power_basis A S')
(h : minpoly pb.is_integral_gen = minpoly pb'.is_integral_gen) :
(pb.equiv pb' h).symm = pb'.equiv pb h.symm :=
rfl
end equiv
end power_basis
lemma is_integral_algebra_map_iff {x : S} (hST : function.injective (algebra_map S T)) :
is_integral R (algebra_map S T x) ↔ is_integral R x :=
begin
split; rintros ⟨f, hf, hx⟩; use [f, hf],
{ exact is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero R S T hST hx },
{ rw [is_scalar_tower.algebra_map_eq R S T, ← hom_eval₂, hx, ring_hom.map_zero] }
end
/-- If `y` is the image of `x` in an extension, their minimal polynomials coincide.
We take `h : y = algebra_map L T x` as an argument because `rw h` typically fails
since `is_integral R y` depends on y.
-/
lemma minpoly.eq_of_algebra_map_eq [algebra K S] [algebra K T]
[is_scalar_tower K S T] (hST : function.injective (algebra_map S T))
{x : S} {y : T} (hx : is_integral K x) (hy : is_integral K y)
(h : y = algebra_map S T x) : minpoly hx = minpoly hy :=
minpoly.unique hy (minpoly.monic hx)
(by rw [h, ← is_scalar_tower.algebra_map_aeval, minpoly.aeval hx, ring_hom.map_zero])
(λ q q_monic root_q, minpoly.min _ q_monic
(is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero K S T hST
(h ▸ root_q : aeval (algebra_map S T x) q = 0)))
namespace algebra
open power_basis
lemma mem_span_power_basis [nontrivial R] {x y : S} (hx : _root_.is_integral R x)
(hy : ∃ f : polynomial R, y = aeval x f) :
y ∈ submodule.span R (set.range (λ (i : fin (minpoly hx).nat_degree),
x ^ (i : ℕ))) :=
begin
obtain ⟨f, rfl⟩ := hy,
rw mem_span_pow',
have := minpoly.monic hx,
refine ⟨f.mod_by_monic (minpoly hx),
lt_of_lt_of_le (degree_mod_by_monic_lt _ this (ne_zero_of_monic this)) degree_le_nat_degree,
_⟩,
conv_lhs { rw ← mod_by_monic_add_div f this },
simp only [add_zero, zero_mul, minpoly.aeval, aeval_add, alg_hom.map_mul]
end
lemma linear_independent_power_basis [algebra K S] {x : S} (hx : _root_.is_integral K x) :
linear_independent K (λ (i : fin (minpoly hx).nat_degree), x ^ (i : ℕ)) :=
begin
rw linear_independent_iff,
intros p hp,
let f : polynomial K := p.sum (λ i, monomial i),
have f_def : ∀ (i : fin _), f.coeff i = p i,
{ intro i,
-- TODO: how can we avoid unfolding here?
change (p.sum (λ i pi, finsupp.single i pi) : ℕ →₀ K) i = p i,
simp_rw [finsupp.sum_apply, finsupp.single_apply, finsupp.sum],
rw [finset.sum_eq_single, if_pos rfl],
{ intros b _ hb,
rw if_neg (mt (λ h, _) hb),
exact fin.coe_injective h },
{ intro hi,
split_ifs; { exact finsupp.not_mem_support_iff.mp hi } } },
have f_def' : ∀ i, f.coeff i = if hi : i < _ then p ⟨i, hi⟩ else 0,
{ intro i,
split_ifs with hi,
{ exact f_def ⟨i, hi⟩ },
-- TODO: how can we avoid unfolding here?
change (p.sum (λ i pi, finsupp.single i pi) : ℕ →₀ K) i = 0,
simp_rw [finsupp.sum_apply, finsupp.single_apply, finsupp.sum],
apply finset.sum_eq_zero,
rintro ⟨j, hj⟩ -,
apply if_neg (mt _ hi),
rintro rfl,
exact hj },
suffices : f = 0,
{ ext i, rw [← f_def, this, coeff_zero, finsupp.zero_apply] },
contrapose hp with hf,
intro h,
have : (minpoly hx).degree ≤ f.degree,
{ apply minpoly.degree_le_of_ne_zero hx hf,
convert h,
rw [finsupp.total_apply, aeval_def, eval₂_eq_sum, finsupp.sum_sum_index],
{ apply finset.sum_congr rfl,
rintro i -,
simp only [algebra.smul_def, monomial, finsupp.lsingle_apply, zero_mul, ring_hom.map_zero,
finsupp.sum_single_index] },
{ intro, simp only [ring_hom.map_zero, zero_mul] },
{ intros, simp only [ring_hom.map_add, add_mul] } },
have : ¬ (minpoly hx).degree ≤ f.degree,
{ apply not_le_of_lt,
rw [degree_eq_nat_degree (minpoly.ne_zero hx), degree_lt_iff_coeff_zero],
intros i hi,
rw [f_def' i, dif_neg],
exact not_lt_of_ge hi },
contradiction
end
lemma power_basis_is_basis [algebra K S] {x : S} (hx : _root_.is_integral K x) :
is_basis K (λ (i : fin (minpoly hx).nat_degree),
(⟨x, subset_adjoin (set.mem_singleton x)⟩ ^ (i : ℕ) : adjoin K ({x} : set S))) :=
begin
have hST : function.injective (algebra_map (adjoin K ({x} : set S)) S) := subtype.coe_injective,
have hx' : _root_.is_integral K
(show adjoin K ({x} : set S), from ⟨x, subset_adjoin (set.mem_singleton x)⟩),
{ apply (is_integral_algebra_map_iff hST).mp,
convert hx,
apply_instance },
have minpoly_eq := minpoly.eq_of_algebra_map_eq hST hx' hx,
refine ⟨_, _root_.eq_top_iff.mpr _⟩,
{ have := linear_independent_power_basis hx',
rwa minpoly_eq at this,
refl },
{ rintros ⟨y, hy⟩ _,
have := mem_span_power_basis hx',
rw minpoly_eq at this,
apply this,
{ rw [adjoin_singleton_eq_range] at hy,
obtain ⟨f, rfl⟩ := (aeval x).mem_range.mp hy,
use f,
ext,
exact (is_scalar_tower.algebra_map_aeval K (adjoin K {x}) S ⟨x, _⟩ _).symm },
{ refl } }
end
/-- The power basis `1, x, ..., x ^ (d - 1)` for `K[x]`,
where `d` is the degree of the minimal polynomial of `x`. -/
noncomputable def adjoin.power_basis [algebra K S] {x : S} (hx : _root_.is_integral K x) :
power_basis K (adjoin K ({x} : set S)) :=
{ gen := ⟨x, subset_adjoin (set.mem_singleton x)⟩,
dim := (minpoly hx).nat_degree,
is_basis := power_basis_is_basis hx }
end algebra
namespace adjoin_root
variables {f : polynomial K}
lemma power_basis_is_basis (hf : f ≠ 0) : is_basis K (λ (i : fin f.nat_degree), (root f ^ i.val)) :=
begin
set f' := f * C (f.leading_coeff⁻¹) with f'_def,
have deg_f' : f'.nat_degree = f.nat_degree,
{ rw [nat_degree_mul hf, nat_degree_C, add_zero],
{ rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] } },
have f'_monic : monic f' := monic_mul_leading_coeff_inv hf,
have aeval_f' : aeval (root f) f' = 0,
{ rw [f'_def, alg_hom.map_mul, aeval_eq, mk_self, zero_mul] },
have hx : is_integral K (root f) := ⟨f', f'_monic, aeval_f'⟩,
have minpoly_eq : f' = minpoly hx,
{ apply minpoly.unique hx f'_monic aeval_f',
intros q q_monic q_aeval,
have commutes : (lift (algebra_map K (adjoin_root f)) (root f) q_aeval).comp (mk q) = mk f,
{ ext,
{ simp only [ring_hom.comp_apply, mk_C, lift_of], refl },
{ simp only [ring_hom.comp_apply, mk_X, lift_root] } },
rw [degree_eq_nat_degree f'_monic.ne_zero, degree_eq_nat_degree q_monic.ne_zero,
with_bot.coe_le_coe, deg_f'],
apply nat_degree_le_of_dvd,
{ rw [←ideal.mem_span_singleton, ←ideal.quotient.eq_zero_iff_mem],
change mk f q = 0,
rw [←commutes, ring_hom.comp_apply, mk_self, ring_hom.map_zero] },
{ exact q_monic.ne_zero } },
refine ⟨_, eq_top_iff.mpr _⟩,
{ rw [←deg_f', minpoly_eq],
exact algebra.linear_independent_power_basis hx, },
{ rintros y -,
rw [←deg_f', minpoly_eq],
apply algebra.mem_span_power_basis hx,
obtain ⟨g⟩ := y,
use g,
rw aeval_eq,
refl }
end
/-- The power basis `1, root f, ..., root f ^ (d - 1)` for `adjoin_root f`,
where `f` is an irreducible polynomial over a field of degree `d`. -/
noncomputable def power_basis (hf : f ≠ 0) :
power_basis K (adjoin_root f) :=
{ gen := root f,
dim := f.nat_degree,
is_basis := power_basis_is_basis hf }
end adjoin_root
namespace intermediate_field
lemma power_basis_is_basis {x : L} (hx : is_integral K x) :
is_basis K (λ (i : fin (minpoly hx).nat_degree), (adjoin_simple.gen K x ^ (i : ℕ))) :=
begin
let ϕ := (adjoin_root_equiv_adjoin K hx).to_linear_equiv,
have key : ϕ (adjoin_root.root (minpoly hx)) = adjoin_simple.gen K x,
{ exact intermediate_field.adjoin_root_equiv_adjoin_apply_root K hx },
suffices : ϕ ∘ (λ (i : fin (minpoly hx).nat_degree),
adjoin_root.root (minpoly hx) ^ (i.val)) =
(λ (i : fin (minpoly hx).nat_degree),
(adjoin_simple.gen K x) ^ ↑i),
{ rw ← this, exact linear_equiv.is_basis
(adjoin_root.power_basis_is_basis (minpoly.ne_zero hx)) ϕ },
ext y,
rw [function.comp_app, fin.val_eq_coe, alg_equiv.to_linear_equiv_apply, alg_equiv.map_pow],
rw intermediate_field.adjoin_root_equiv_adjoin_apply_root K hx,
end
/-- The power basis `1, x, ..., x ^ (d - 1)` for `K⟮x⟯`,
where `d` is the degree of the minimal polynomial of `x`. -/
noncomputable def adjoin.power_basis {x : L} (hx : is_integral K x) :
power_basis K K⟮x⟯ :=
{ gen := adjoin_simple.gen K x,
dim := (minpoly hx).nat_degree,
is_basis := power_basis_is_basis hx }
@[simp] lemma adjoin.power_basis.gen_eq {x : L} (hx : is_integral K x) :
(adjoin.power_basis hx).gen = adjoin_simple.gen K x := rfl
lemma adjoin.finite_dimensional {x : L} (hx : is_integral K x) : finite_dimensional K K⟮x⟯ :=
power_basis.finite_dimensional (adjoin.power_basis hx)
lemma adjoin.findim {x : L} (hx : is_integral K x) :
finite_dimensional.findim K K⟮x⟯ = (minpoly hx).nat_degree :=
begin
rw power_basis.findim (adjoin.power_basis hx),
refl,
end
end intermediate_field
namespace power_basis
open intermediate_field
/-- `pb.equiv_adjoin_simple` is the equivalence between `K⟮pb.gen⟯` and `L` itself. -/
noncomputable def equiv_adjoin_simple (pb : power_basis K L) :
K⟮pb.gen⟯ ≃ₐ[K] L :=
(adjoin.power_basis pb.is_integral_gen).equiv pb
(minpoly.eq_of_algebra_map_eq (algebra_map K⟮pb.gen⟯ L).injective _ _
(by rw [adjoin.power_basis.gen_eq, adjoin_simple.algebra_map_gen]))
@[simp]
lemma equiv_adjoin_simple_aeval (pb : power_basis K L) (f : polynomial K) :
pb.equiv_adjoin_simple (aeval (adjoin_simple.gen K pb.gen) f) = aeval pb.gen f :=
equiv_aeval _ pb _ f
@[simp]
lemma equiv_adjoin_simple_gen (pb : power_basis K L) :
pb.equiv_adjoin_simple (adjoin_simple.gen K pb.gen) = pb.gen :=
equiv_gen _ pb _
@[simp]
lemma equiv_adjoin_simple_symm_aeval (pb : power_basis K L) (f : polynomial K) :
pb.equiv_adjoin_simple.symm (aeval pb.gen f) = aeval (adjoin_simple.gen K pb.gen) f :=
by rw [equiv_adjoin_simple, equiv_symm, equiv_aeval, adjoin.power_basis.gen_eq]
@[simp]
lemma equiv_adjoin_simple_symm_gen (pb : power_basis K L) :
pb.equiv_adjoin_simple.symm pb.gen = (adjoin_simple.gen K pb.gen) :=
by rw [equiv_adjoin_simple, equiv_symm, equiv_gen, adjoin.power_basis.gen_eq]
end power_basis
|
8eccb8ce434b66e9a54d5e55593609eb232563cf | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/number_theory/lucas_lehmer.lean | f65dd787e416d111d4f3e3019e4273ba025f5af8 | [] | 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 | 11,329 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro, Scott Morrison, Ainsley Pahljina
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.ring_exp
import Mathlib.tactic.interval_cases
import Mathlib.data.nat.parity
import Mathlib.data.zmod.basic
import Mathlib.group_theory.order_of_element
import Mathlib.ring_theory.fintype
import Mathlib.PostPort
namespace Mathlib
/-!
# The Lucas-Lehmer test for Mersenne primes.
We define `lucas_lehmer_residue : Π p : ℕ, zmod (2^p - 1)`, and
prove `lucas_lehmer_residue p = 0 → prime (mersenne p)`.
We construct a tactic `lucas_lehmer.run_test`, which iteratively certifies the arithmetic
required to calculate the residue, and enables us to prove
```
example : prime (mersenne 127) :=
lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test)
```
## TODO
- Show reverse implication.
- Speed up the calculations using `n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]`.
- Find some bigger primes!
## History
This development began as a student project by Ainsley Pahljina,
and was then cleaned up for mathlib by Scott Morrison.
The tactic for certified computation of Lucas-Lehmer residues was provided by Mario Carneiro.
-/
/-- The Mersenne numbers, 2^p - 1. -/
def mersenne (p : ℕ) : ℕ :=
bit0 1 ^ p - 1
theorem mersenne_pos {p : ℕ} (h : 0 < p) : 0 < mersenne p := sorry
@[simp] theorem succ_mersenne (k : ℕ) : mersenne k + 1 = bit0 1 ^ k := sorry
namespace lucas_lehmer
/-!
We now define three(!) different versions of the recurrence
`s (i+1) = (s i)^2 - 2`.
These versions take values either in `ℤ`, in `zmod (2^p - 1)`, or
in `ℤ` but applying `% (2^p - 1)` at each step.
They are each useful at different points in the proof,
so we take a moment setting up the lemmas relating them.
-/
/-- The recurrence `s (i+1) = (s i)^2 - 2` in `ℤ`. -/
def s : ℕ → ℤ :=
sorry
/-- The recurrence `s (i+1) = (s i)^2 - 2` in `zmod (2^p - 1)`. -/
def s_zmod (p : ℕ) : ℕ → zmod (bit0 1 ^ p - 1) :=
sorry
/-- The recurrence `s (i+1) = ((s i)^2 - 2) % (2^p - 1)` in `ℤ`. -/
def s_mod (p : ℕ) : ℕ → ℤ :=
sorry
theorem mersenne_int_ne_zero (p : ℕ) (w : 0 < p) : bit0 1 ^ p - 1 ≠ 0 := sorry
theorem s_mod_nonneg (p : ℕ) (w : 0 < p) (i : ℕ) : 0 ≤ s_mod p i :=
nat.cases_on i (id (iff.mp sup_eq_left rfl))
fun (i : ℕ) => id (int.mod_nonneg (s_mod p i ^ bit0 1 - bit0 1) (mersenne_int_ne_zero p w))
theorem s_mod_mod (p : ℕ) (i : ℕ) : s_mod p i % (bit0 1 ^ p - 1) = s_mod p i := sorry
theorem s_mod_lt (p : ℕ) (w : 0 < p) (i : ℕ) : s_mod p i < bit0 1 ^ p - 1 := sorry
theorem s_zmod_eq_s (p' : ℕ) (i : ℕ) : s_zmod (p' + bit0 1) i = ↑(s i) := sorry
-- These next two don't make good `norm_cast` lemmas.
theorem int.coe_nat_pow_pred (b : ℕ) (p : ℕ) (w : 0 < b) : ↑(b ^ p - 1) = ↑b ^ p - 1 := sorry
theorem int.coe_nat_two_pow_pred (p : ℕ) : ↑(bit0 1 ^ p - 1) = bit0 1 ^ p - 1 :=
int.coe_nat_pow_pred (bit0 1) p (of_as_true trivial)
theorem s_zmod_eq_s_mod (p : ℕ) (i : ℕ) : s_zmod p i = ↑(s_mod p i) := sorry
/-- The Lucas-Lehmer residue is `s p (p-2)` in `zmod (2^p - 1)`. -/
def lucas_lehmer_residue (p : ℕ) : zmod (bit0 1 ^ p - 1) :=
s_zmod p (p - bit0 1)
theorem residue_eq_zero_iff_s_mod_eq_zero (p : ℕ) (w : 1 < p) : lucas_lehmer_residue p = 0 ↔ s_mod p (p - bit0 1) = 0 := sorry
/--
A Mersenne number `2^p-1` is prime if and only if
the Lucas-Lehmer residue `s p (p-2) % (2^p - 1)` is zero.
-/
def lucas_lehmer_test (p : ℕ) :=
lucas_lehmer_residue p = 0
/-- `q` is defined as the minimum factor of `mersenne p`, bundled as an `ℕ+`. -/
def q (p : ℕ) : ℕ+ :=
{ val := nat.min_fac (mersenne p), property := sorry }
protected instance fact_pnat_pos (q : ℕ+) : fact (0 < ↑q) :=
subtype.property q
/-- We construct the ring `X q` as ℤ/qℤ + √3 ℤ/qℤ. -/
-- It would be nice to define this as (ℤ/qℤ)[x] / (x^2 - 3),
-- obtaining the ring structure for free,
-- but that seems to be more trouble than it's worth;
-- if it were easy to make the definition,
-- cardinality calculations would be somewhat more involved, too.
def X (q : ℕ+) :=
zmod ↑q × zmod ↑q
namespace X
theorem ext {q : ℕ+} {x : X q} {y : X q} (h₁ : prod.fst x = prod.fst y) (h₂ : prod.snd x = prod.snd y) : x = y := sorry
@[simp] theorem add_fst {q : ℕ+} (x : X q) (y : X q) : prod.fst (x + y) = prod.fst x + prod.fst y :=
rfl
@[simp] theorem add_snd {q : ℕ+} (x : X q) (y : X q) : prod.snd (x + y) = prod.snd x + prod.snd y :=
rfl
@[simp] theorem neg_fst {q : ℕ+} (x : X q) : prod.fst (-x) = -prod.fst x :=
rfl
@[simp] theorem neg_snd {q : ℕ+} (x : X q) : prod.snd (-x) = -prod.snd x :=
rfl
protected instance has_mul {q : ℕ+} : Mul (X q) :=
{ mul :=
fun (x y : X q) =>
(prod.fst x * prod.fst y + bit1 1 * prod.snd x * prod.snd y, prod.fst x * prod.snd y + prod.snd x * prod.fst y) }
@[simp] theorem mul_fst {q : ℕ+} (x : X q) (y : X q) : prod.fst (x * y) = prod.fst x * prod.fst y + bit1 1 * prod.snd x * prod.snd y :=
rfl
@[simp] theorem mul_snd {q : ℕ+} (x : X q) (y : X q) : prod.snd (x * y) = prod.fst x * prod.snd y + prod.snd x * prod.fst y :=
rfl
protected instance has_one {q : ℕ+} : HasOne (X q) :=
{ one := (1, 0) }
@[simp] theorem one_fst {q : ℕ+} : prod.fst 1 = 1 :=
rfl
@[simp] theorem one_snd {q : ℕ+} : prod.snd 1 = 0 :=
rfl
@[simp] theorem bit0_fst {q : ℕ+} (x : X q) : prod.fst (bit0 x) = bit0 (prod.fst x) :=
rfl
@[simp] theorem bit0_snd {q : ℕ+} (x : X q) : prod.snd (bit0 x) = bit0 (prod.snd x) :=
rfl
@[simp] theorem bit1_fst {q : ℕ+} (x : X q) : prod.fst (bit1 x) = bit1 (prod.fst x) :=
rfl
@[simp] theorem bit1_snd {q : ℕ+} (x : X q) : prod.snd (bit1 x) = bit0 (prod.snd x) := sorry
protected instance monoid {q : ℕ+} : monoid (X q) :=
monoid.mk Mul.mul sorry (1, 0) sorry sorry
theorem left_distrib {q : ℕ+} (x : X q) (y : X q) (z : X q) : x * (y + z) = x * y + x * z := sorry
theorem right_distrib {q : ℕ+} (x : X q) (y : X q) (z : X q) : (x + y) * z = x * z + y * z := sorry
protected instance ring {q : ℕ+} : ring (X q) :=
ring.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry
monoid.mul sorry monoid.one sorry sorry left_distrib right_distrib
protected instance comm_ring {q : ℕ+} : comm_ring (X q) :=
comm_ring.mk ring.add sorry ring.zero sorry sorry ring.neg ring.sub sorry sorry ring.mul sorry ring.one sorry sorry
sorry sorry sorry
protected instance nontrivial {q : ℕ+} [fact (1 < ↑q)] : nontrivial (X q) :=
nontrivial.mk
(Exists.intro 0
(Exists.intro 1 fun (h : 0 = 1) => prod.mk.inj_arrow h fun (h1 : 0 = 1) (ᾰ : 0 = 0) => zero_ne_one h1))
@[simp] theorem nat_coe_fst {q : ℕ+} (n : ℕ) : prod.fst ↑n = ↑n :=
Nat.rec (Eq.refl (prod.fst ↑0))
(fun (n_n : ℕ) (n_ih : prod.fst ↑n_n = ↑n_n) => id (eq.mpr (id (propext (add_left_inj 1))) n_ih)) n
@[simp] theorem nat_coe_snd {q : ℕ+} (n : ℕ) : prod.snd ↑n = 0 := sorry
@[simp] theorem int_coe_fst {q : ℕ+} (n : ℤ) : prod.fst ↑n = ↑n := sorry
@[simp] theorem int_coe_snd {q : ℕ+} (n : ℤ) : prod.snd ↑n = 0 := sorry
theorem coe_mul {q : ℕ+} (n : ℤ) (m : ℤ) : ↑(n * m) = ↑n * ↑m := sorry
theorem coe_nat {q : ℕ+} (n : ℕ) : ↑↑n = ↑n := sorry
/-- The cardinality of `X` is `q^2`. -/
theorem X_card {q : ℕ+} : fintype.card (X q) = ↑q ^ bit0 1 := sorry
/-- There are strictly fewer than `q^2` units, since `0` is not a unit. -/
theorem units_card {q : ℕ+} (w : 1 < q) : fintype.card (units (X q)) < ↑q ^ bit0 1 := sorry
/-- We define `ω = 2 + √3`. -/
/-- We define `ωb = 2 - √3`, which is the inverse of `ω`. -/
def ω {q : ℕ+} : X q :=
(bit0 1, 1)
def ωb {q : ℕ+} : X q :=
(bit0 1, -1)
theorem ω_mul_ωb (q : ℕ+) : ω * ωb = 1 := sorry
theorem ωb_mul_ω (q : ℕ+) : ωb * ω = 1 := sorry
/-- A closed form for the recurrence relation. -/
theorem closed_form {q : ℕ+} (i : ℕ) : ↑(s i) = ω ^ bit0 1 ^ i + ωb ^ bit0 1 ^ i := sorry
end X
/-!
Here and below, we introduce `p' = p - 2`, in order to avoid using subtraction in `ℕ`.
-/
/-- If `1 < p`, then `q p`, the smallest prime factor of `mersenne p`, is more than 2. -/
theorem two_lt_q (p' : ℕ) : bit0 1 < q (p' + bit0 1) := sorry
theorem ω_pow_formula (p' : ℕ) (h : lucas_lehmer_residue (p' + bit0 1) = 0) : ∃ (k : ℤ), X.ω ^ bit0 1 ^ (p' + 1) = ↑k * ↑(mersenne (p' + bit0 1)) * X.ω ^ bit0 1 ^ p' - 1 := sorry
/-- `q` is the minimum factor of `mersenne p`, so `M p = 0` in `X q`. -/
theorem mersenne_coe_X (p : ℕ) : ↑(mersenne p) = 0 := sorry
theorem ω_pow_eq_neg_one (p' : ℕ) (h : lucas_lehmer_residue (p' + bit0 1) = 0) : X.ω ^ bit0 1 ^ (p' + 1) = -1 := sorry
theorem ω_pow_eq_one (p' : ℕ) (h : lucas_lehmer_residue (p' + bit0 1) = 0) : X.ω ^ bit0 1 ^ (p' + bit0 1) = 1 := sorry
/-- `ω` as an element of the group of units. -/
def ω_unit (p : ℕ) : units (X (q p)) :=
units.mk X.ω X.ωb sorry sorry
@[simp] theorem ω_unit_coe (p : ℕ) : ↑(ω_unit p) = X.ω :=
rfl
/-- The order of `ω` in the unit group is exactly `2^p`. -/
theorem order_ω (p' : ℕ) (h : lucas_lehmer_residue (p' + bit0 1) = 0) : order_of (ω_unit (p' + bit0 1)) = bit0 1 ^ (p' + bit0 1) := sorry
theorem order_ineq (p' : ℕ) (h : lucas_lehmer_residue (p' + bit0 1) = 0) : bit0 1 ^ (p' + bit0 1) < ↑(q (p' + bit0 1)) ^ bit0 1 :=
lt_of_le_of_lt (trans_rel_right LessEq (Eq.symm (order_ω p' h)) order_of_le_card_univ)
(X.units_card (nat.lt_of_succ_lt (two_lt_q p')))
end lucas_lehmer
theorem lucas_lehmer_sufficiency (p : ℕ) (w : 1 < p) : lucas_lehmer_test p → nat.prime (mersenne p) := sorry
-- Here we calculate the residue, very inefficiently, using `dec_trivial`. We can do much better.
-- Next we use `norm_num` to calculate each `s p i`.
namespace lucas_lehmer
theorem s_mod_succ {p : ℕ} {a : ℤ} {i : ℕ} {b : ℤ} {c : ℤ} (h1 : bit0 1 ^ p - 1 = a) (h2 : s_mod p i = b) (h3 : (b * b - bit0 1) % a = c) : s_mod p (i + 1) = c := sorry
/--
Given a goal of the form `lucas_lehmer_test p`,
attempt to do the calculation using `norm_num` to certify each step.
-/
end lucas_lehmer
/-- We verify that the tactic works to prove `127.prime`. -/
/-!
This implementation works successfully to prove `(2^127 - 1).prime`,
and all the Mersenne primes up to this point appear in [archive/examples/mersenne_primes.lean].
`(2^127 - 1).prime` takes about 5 minutes to run (depending on your CPU!),
and unfortunately the next Mersenne prime `(2^521 - 1)`,
which was the first "computer era" prime,
is out of reach with the current implementation.
There's still low hanging fruit available to do faster computations
based on the formula
n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]
and the fact that `% 2^p` and `/ 2^p` can be very efficient on the binary representation.
Someone should do this, too!
-/
-- See https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/help.20finding.20a.20lemma/near/177698446
theorem modeq_mersenne (n : ℕ) (k : ℕ) : nat.modeq (bit0 1 ^ n - 1) k (k / bit0 1 ^ n + k % bit0 1 ^ n) := sorry
|
69240670606a3f89968da94ff62e4dbe91dc1103 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/integral/set_integral.lean | a4ef51091adbbbc7bebabcf177996fa4208c25fe | [
"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 | 63,019 | lean | /-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Yury Kudryashov
-/
import measure_theory.integral.integrable_on
import measure_theory.integral.bochner
import measure_theory.function.locally_integrable
import order.filter.indicator_function
import topology.metric_space.thickened_indicator
import topology.continuous_function.compact
/-!
# Set integral
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file we prove some properties of `∫ x in s, f x ∂μ`. Recall that this notation
is defined as `∫ x, f x ∂(μ.restrict s)`. In `integral_indicator` we prove that for a measurable
function `f` and a measurable set `s` this definition coincides with another natural definition:
`∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ`, where `indicator s f x` is equal to `f x` for `x ∈ s`
and is zero otherwise.
Since `∫ x in s, f x ∂μ` is a notation, one can rewrite or apply any theorem about `∫ x, f x ∂μ`
directly. In this file we prove some theorems about dependence of `∫ x in s, f x ∂μ` on `s`, e.g.
`integral_union`, `integral_empty`, `integral_univ`.
We use the property `integrable_on f s μ := integrable f (μ.restrict s)`, defined in
`measure_theory.integrable_on`. We also defined in that same file a predicate
`integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at
some set `s ∈ l`.
Finally, we prove a version of the
[Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus)
for set integral, see `filter.tendsto.integral_sub_linear_is_o_ae` and its corollaries.
Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and
a function `f` that has a finite limit `c` at `l ⊓ μ.ae`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)`
as `s` tends to `l.small_sets`, i.e. for any `ε>0` there exists `t ∈ l` such that
`‖∫ x in s, f x ∂μ - μ s • c‖ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this
theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`.
## Notation
We provide the following notations for expressing the integral of a function on a set :
* `∫ a in s, f a ∂μ` is `measure_theory.integral (μ.restrict s) f`
* `∫ a in s, f a` is `∫ a in s, f a ∂volume`
Note that the set notations are defined in the file `measure_theory/integral/bochner`,
but we reference them here because all theorems about set integrals are in this file.
-/
assert_not_exists inner_product_space
noncomputable theory
open set filter topological_space measure_theory function
open_locale classical topology interval big_operators filter ennreal nnreal measure_theory
variables {α β E F : Type*} [measurable_space α]
namespace measure_theory
section normed_add_comm_group
variables [normed_add_comm_group E] {f g : α → E} {s t : set α} {μ ν : measure α}
{l l' : filter α}
variables [complete_space E] [normed_space ℝ E]
lemma set_integral_congr_ae₀ (hs : null_measurable_set s μ) (h : ∀ᵐ x ∂μ, x ∈ s → f x = g x) :
∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ :=
integral_congr_ae ((ae_restrict_iff'₀ hs).2 h)
lemma set_integral_congr_ae (hs : measurable_set s) (h : ∀ᵐ x ∂μ, x ∈ s → f x = g x) :
∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ :=
integral_congr_ae ((ae_restrict_iff' hs).2 h)
lemma set_integral_congr₀ (hs : null_measurable_set s μ) (h : eq_on f g s) :
∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ :=
set_integral_congr_ae₀ hs $ eventually_of_forall h
lemma set_integral_congr (hs : measurable_set s) (h : eq_on f g s) :
∫ x in s, f x ∂μ = ∫ x in s, g x ∂μ :=
set_integral_congr_ae hs $ eventually_of_forall h
lemma set_integral_congr_set_ae (hst : s =ᵐ[μ] t) :
∫ x in s, f x ∂μ = ∫ x in t, f x ∂μ :=
by rw measure.restrict_congr_set hst
lemma integral_union_ae (hst : ae_disjoint μ s t) (ht : null_measurable_set t μ)
(hfs : integrable_on f s μ) (hft : integrable_on f t μ) :
∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ :=
by simp only [integrable_on, measure.restrict_union₀ hst ht, integral_add_measure hfs hft]
lemma integral_union (hst : disjoint s t) (ht : measurable_set t)
(hfs : integrable_on f s μ) (hft : integrable_on f t μ) :
∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ :=
integral_union_ae hst.ae_disjoint ht.null_measurable_set hfs hft
lemma integral_diff (ht : measurable_set t) (hfs : integrable_on f s μ) (hts : t ⊆ s) :
∫ x in s \ t, f x ∂μ = ∫ x in s, f x ∂μ - ∫ x in t, f x ∂μ :=
begin
rw [eq_sub_iff_add_eq, ← integral_union, diff_union_of_subset hts],
exacts [disjoint_sdiff_self_left, ht, hfs.mono_set (diff_subset _ _), hfs.mono_set hts]
end
lemma integral_inter_add_diff₀ (ht : null_measurable_set t μ) (hfs : integrable_on f s μ) :
∫ x in s ∩ t, f x ∂μ + ∫ x in s \ t, f x ∂μ = ∫ x in s, f x ∂μ :=
begin
rw [← measure.restrict_inter_add_diff₀ s ht, integral_add_measure],
{ exact integrable.mono_measure hfs (measure.restrict_mono (inter_subset_left _ _) le_rfl) },
{ exact integrable.mono_measure hfs (measure.restrict_mono (diff_subset _ _) le_rfl) }
end
lemma integral_inter_add_diff (ht : measurable_set t) (hfs : integrable_on f s μ) :
∫ x in s ∩ t, f x ∂μ + ∫ x in s \ t, f x ∂μ = ∫ x in s, f x ∂μ :=
integral_inter_add_diff₀ ht.null_measurable_set hfs
lemma integral_finset_bUnion {ι : Type*} (t : finset ι) {s : ι → set α}
(hs : ∀ i ∈ t, measurable_set (s i)) (h's : set.pairwise ↑t (disjoint on s))
(hf : ∀ i ∈ t, integrable_on f (s i) μ) :
∫ x in (⋃ i ∈ t, s i), f x ∂ μ = ∑ i in t, ∫ x in s i, f x ∂ μ :=
begin
induction t using finset.induction_on with a t hat IH hs h's,
{ simp },
{ simp only [finset.coe_insert, finset.forall_mem_insert, set.pairwise_insert,
finset.set_bUnion_insert] at hs hf h's ⊢,
rw [integral_union _ _ hf.1 (integrable_on_finset_Union.2 hf.2)],
{ rw [finset.sum_insert hat, IH hs.2 h's.1 hf.2] },
{ simp only [disjoint_Union_right],
exact (λ i hi, (h's.2 i hi (ne_of_mem_of_not_mem hi hat).symm).1) },
{ exact finset.measurable_set_bUnion _ hs.2 } }
end
lemma integral_fintype_Union {ι : Type*} [fintype ι] {s : ι → set α}
(hs : ∀ i, measurable_set (s i)) (h's : pairwise (disjoint on s))
(hf : ∀ i, integrable_on f (s i) μ) :
∫ x in (⋃ i, s i), f x ∂ μ = ∑ i, ∫ x in s i, f x ∂ μ :=
begin
convert integral_finset_bUnion finset.univ (λ i hi, hs i) _ (λ i _, hf i),
{ simp },
{ simp [pairwise_univ, h's] }
end
lemma integral_empty : ∫ x in ∅, f x ∂μ = 0 := by rw [measure.restrict_empty, integral_zero_measure]
lemma integral_univ : ∫ x in univ, f x ∂μ = ∫ x, f x ∂μ := by rw [measure.restrict_univ]
lemma integral_add_compl₀ (hs : null_measurable_set s μ) (hfi : integrable f μ) :
∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ :=
by rw [← integral_union_ae (@disjoint_compl_right (set α) _ _).ae_disjoint hs.compl
hfi.integrable_on hfi.integrable_on, union_compl_self, integral_univ]
lemma integral_add_compl (hs : measurable_set s) (hfi : integrable f μ) :
∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ :=
integral_add_compl₀ hs.null_measurable_set hfi
/-- For a function `f` and a measurable set `s`, the integral of `indicator s f`
over the whole space is equal to `∫ x in s, f x ∂μ` defined as `∫ x, f x ∂(μ.restrict s)`. -/
lemma integral_indicator (hs : measurable_set s) :
∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ :=
begin
by_cases hfi : integrable_on f s μ, swap,
{ rwa [integral_undef, integral_undef],
rwa integrable_indicator_iff hs },
calc ∫ x, indicator s f x ∂μ = ∫ x in s, indicator s f x ∂μ + ∫ x in sᶜ, indicator s f x ∂μ :
(integral_add_compl hs (hfi.integrable_indicator hs)).symm
... = ∫ x in s, f x ∂μ + ∫ x in sᶜ, 0 ∂μ :
congr_arg2 (+) (integral_congr_ae (indicator_ae_eq_restrict hs))
(integral_congr_ae (indicator_ae_eq_restrict_compl hs))
... = ∫ x in s, f x ∂μ : by simp
end
lemma set_integral_indicator (ht : measurable_set t) :
∫ x in s, t.indicator f x ∂μ = ∫ x in s ∩ t, f x ∂μ :=
by rw [integral_indicator ht, measure.restrict_restrict ht, set.inter_comm]
lemma of_real_set_integral_one_of_measure_ne_top {α : Type*} {m : measurable_space α}
{μ : measure α} {s : set α} (hs : μ s ≠ ∞) :
ennreal.of_real (∫ x in s, (1 : ℝ) ∂μ) = μ s :=
calc
ennreal.of_real (∫ x in s, (1 : ℝ) ∂μ)
= ennreal.of_real (∫ x in s, ‖(1 : ℝ)‖ ∂μ) : by simp only [norm_one]
... = ∫⁻ x in s, 1 ∂μ :
begin
rw of_real_integral_norm_eq_lintegral_nnnorm (integrable_on_const.2 (or.inr hs.lt_top)),
simp only [nnnorm_one, ennreal.coe_one],
end
... = μ s : set_lintegral_one _
lemma of_real_set_integral_one {α : Type*} {m : measurable_space α} (μ : measure α)
[is_finite_measure μ] (s : set α) :
ennreal.of_real (∫ x in s, (1 : ℝ) ∂μ) = μ s :=
of_real_set_integral_one_of_measure_ne_top (measure_ne_top μ s)
lemma integral_piecewise [decidable_pred (∈ s)] (hs : measurable_set s)
(hf : integrable_on f s μ) (hg : integrable_on g sᶜ μ) :
∫ x, s.piecewise f g x ∂μ = ∫ x in s, f x ∂μ + ∫ x in sᶜ, g x ∂μ :=
by rw [← set.indicator_add_compl_eq_piecewise,
integral_add' (hf.integrable_indicator hs) (hg.integrable_indicator hs.compl),
integral_indicator hs, integral_indicator hs.compl]
lemma tendsto_set_integral_of_monotone {ι : Type*} [countable ι] [semilattice_sup ι]
{s : ι → set α} (hsm : ∀ i, measurable_set (s i))
(h_mono : monotone s) (hfi : integrable_on f (⋃ n, s n) μ) :
tendsto (λ i, ∫ a in s i, f a ∂μ) at_top (𝓝 (∫ a in (⋃ n, s n), f a ∂μ)) :=
begin
have hfi' : ∫⁻ x in ⋃ n, s n, ‖f x‖₊ ∂μ < ∞ := hfi.2,
set S := ⋃ i, s i,
have hSm : measurable_set S := measurable_set.Union hsm,
have hsub : ∀ {i}, s i ⊆ S, from subset_Union s,
rw [← with_density_apply _ hSm] at hfi',
set ν := μ.with_density (λ x, ‖f x‖₊) with hν,
refine metric.nhds_basis_closed_ball.tendsto_right_iff.2 (λ ε ε0, _),
lift ε to ℝ≥0 using ε0.le,
have : ∀ᶠ i in at_top, ν (s i) ∈ Icc (ν S - ε) (ν S + ε),
from tendsto_measure_Union h_mono (ennreal.Icc_mem_nhds hfi'.ne (ennreal.coe_pos.2 ε0).ne'),
refine this.mono (λ i hi, _),
rw [mem_closed_ball_iff_norm', ← integral_diff (hsm i) hfi hsub,
← coe_nnnorm, nnreal.coe_le_coe, ← ennreal.coe_le_coe],
refine (ennnorm_integral_le_lintegral_ennnorm _).trans _,
rw [← with_density_apply _ (hSm.diff (hsm _)), ← hν, measure_diff hsub (hsm _)],
exacts [tsub_le_iff_tsub_le.mp hi.1,
(hi.2.trans_lt $ ennreal.add_lt_top.2 ⟨hfi', ennreal.coe_lt_top⟩).ne]
end
lemma has_sum_integral_Union_ae {ι : Type*} [countable ι] {s : ι → set α}
(hm : ∀ i, null_measurable_set (s i) μ) (hd : pairwise (ae_disjoint μ on s))
(hfi : integrable_on f (⋃ i, s i) μ) :
has_sum (λ n, ∫ a in s n, f a ∂ μ) (∫ a in ⋃ n, s n, f a ∂μ) :=
begin
simp only [integrable_on, measure.restrict_Union_ae hd hm] at hfi ⊢,
exact has_sum_integral_measure hfi
end
lemma has_sum_integral_Union {ι : Type*} [countable ι] {s : ι → set α}
(hm : ∀ i, measurable_set (s i)) (hd : pairwise (disjoint on s))
(hfi : integrable_on f (⋃ i, s i) μ) :
has_sum (λ n, ∫ a in s n, f a ∂ μ) (∫ a in ⋃ n, s n, f a ∂μ) :=
has_sum_integral_Union_ae (λ i, (hm i).null_measurable_set) (hd.mono (λ i j h, h.ae_disjoint)) hfi
lemma integral_Union {ι : Type*} [countable ι] {s : ι → set α}
(hm : ∀ i, measurable_set (s i)) (hd : pairwise (disjoint on s))
(hfi : integrable_on f (⋃ i, s i) μ) :
(∫ a in (⋃ n, s n), f a ∂μ) = ∑' n, ∫ a in s n, f a ∂ μ :=
(has_sum.tsum_eq (has_sum_integral_Union hm hd hfi)).symm
lemma integral_Union_ae {ι : Type*} [countable ι] {s : ι → set α}
(hm : ∀ i, null_measurable_set (s i) μ) (hd : pairwise (ae_disjoint μ on s))
(hfi : integrable_on f (⋃ i, s i) μ) :
(∫ a in (⋃ n, s n), f a ∂μ) = ∑' n, ∫ a in s n, f a ∂ μ :=
(has_sum.tsum_eq (has_sum_integral_Union_ae hm hd hfi)).symm
lemma set_integral_eq_zero_of_ae_eq_zero (ht_eq : ∀ᵐ x ∂μ, x ∈ t → f x = 0) :
∫ x in t, f x ∂μ = 0 :=
begin
by_cases hf : ae_strongly_measurable f (μ.restrict t), swap,
{ rw integral_undef,
contrapose! hf,
exact hf.1 },
have : ∫ x in t, hf.mk f x ∂μ = 0,
{ refine integral_eq_zero_of_ae _,
rw [eventually_eq, ae_restrict_iff
(hf.strongly_measurable_mk.measurable_set_eq_fun strongly_measurable_zero)],
filter_upwards [ae_imp_of_ae_restrict hf.ae_eq_mk, ht_eq] with x hx h'x h''x,
rw ← hx h''x,
exact h'x h''x },
rw ← this,
exact integral_congr_ae hf.ae_eq_mk,
end
lemma set_integral_eq_zero_of_forall_eq_zero (ht_eq : ∀ x ∈ t, f x = 0) :
∫ x in t, f x ∂μ = 0 :=
set_integral_eq_zero_of_ae_eq_zero (eventually_of_forall ht_eq)
lemma integral_union_eq_left_of_ae_aux (ht_eq : ∀ᵐ x ∂(μ.restrict t), f x = 0)
(haux : strongly_measurable f) (H : integrable_on f (s ∪ t) μ) :
∫ x in (s ∪ t), f x ∂μ = ∫ x in s, f x ∂μ :=
begin
let k := f ⁻¹' {0},
have hk : measurable_set k,
{ borelize E, exact haux.measurable (measurable_set_singleton _) },
have h's : integrable_on f s μ := H.mono (subset_union_left _ _) le_rfl,
have A : ∀ (u : set α), ∫ x in u ∩ k, f x ∂μ = 0 :=
λ u, set_integral_eq_zero_of_forall_eq_zero (λ x hx, hx.2),
rw [← integral_inter_add_diff hk h's, ← integral_inter_add_diff hk H, A, A, zero_add, zero_add,
union_diff_distrib, union_comm],
apply set_integral_congr_set_ae,
rw union_ae_eq_right,
apply measure_mono_null (diff_subset _ _),
rw measure_zero_iff_ae_nmem,
filter_upwards [ae_imp_of_ae_restrict ht_eq] with x hx h'x using h'x.2 (hx h'x.1),
end
lemma integral_union_eq_left_of_ae (ht_eq : ∀ᵐ x ∂(μ.restrict t), f x = 0) :
∫ x in (s ∪ t), f x ∂μ = ∫ x in s, f x ∂μ :=
begin
have ht : integrable_on f t μ,
{ apply integrable_on_zero.congr_fun_ae, symmetry, exact ht_eq },
by_cases H : integrable_on f (s ∪ t) μ, swap,
{ rw [integral_undef H, integral_undef], simpa [integrable_on_union, ht] using H },
let f' := H.1.mk f,
calc ∫ (x : α) in s ∪ t, f x ∂μ
= ∫ (x : α) in s ∪ t, f' x ∂μ : integral_congr_ae H.1.ae_eq_mk
... = ∫ x in s, f' x ∂μ :
begin
apply integral_union_eq_left_of_ae_aux _ H.1.strongly_measurable_mk
(H.congr_fun_ae H.1.ae_eq_mk),
filter_upwards [ht_eq, ae_mono (measure.restrict_mono (subset_union_right s t) le_rfl)
H.1.ae_eq_mk] with x hx h'x,
rw [← h'x, hx]
end
... = ∫ x in s, f x ∂μ : integral_congr_ae
(ae_mono (measure.restrict_mono (subset_union_left s t) le_rfl) H.1.ae_eq_mk.symm)
end
lemma integral_union_eq_left_of_forall₀ {f : α → E}
(ht : null_measurable_set t μ) (ht_eq : ∀ x ∈ t, f x = 0) :
∫ x in (s ∪ t), f x ∂μ = ∫ x in s, f x ∂μ :=
integral_union_eq_left_of_ae ((ae_restrict_iff'₀ ht).2 (eventually_of_forall ht_eq))
lemma integral_union_eq_left_of_forall {f : α → E}
(ht : measurable_set t) (ht_eq : ∀ x ∈ t, f x = 0) :
∫ x in (s ∪ t), f x ∂μ = ∫ x in s, f x ∂μ :=
integral_union_eq_left_of_forall₀ ht.null_measurable_set ht_eq
lemma set_integral_eq_of_subset_of_ae_diff_eq_zero_aux
(hts : s ⊆ t) (h't : ∀ᵐ x ∂μ, x ∈ t \ s → f x = 0)
(haux : strongly_measurable f) (h'aux : integrable_on f t μ) :
∫ x in t, f x ∂μ = ∫ x in s, f x ∂μ :=
begin
let k := f ⁻¹' {0},
have hk : measurable_set k,
{ borelize E, exact haux.measurable (measurable_set_singleton _) },
calc
∫ x in t, f x ∂μ
= ∫ x in t ∩ k, f x ∂μ + ∫ x in t \ k, f x ∂μ :
by rw integral_inter_add_diff hk h'aux
... = ∫ x in t \ k, f x ∂μ :
by { rw [set_integral_eq_zero_of_forall_eq_zero (λ x hx, _), zero_add], exact hx.2 }
... = ∫ x in s \ k, f x ∂μ :
begin
apply set_integral_congr_set_ae,
filter_upwards [h't] with x hx,
change (x ∈ t \ k) = (x ∈ s \ k),
simp only [mem_preimage, mem_singleton_iff, eq_iff_iff, and.congr_left_iff, mem_diff],
assume h'x,
by_cases xs : x ∈ s,
{ simp only [xs, hts xs] },
{ simp only [xs, iff_false],
assume xt,
exact h'x (hx ⟨xt, xs⟩) }
end
... = ∫ x in s ∩ k, f x ∂μ + ∫ x in s \ k, f x ∂μ :
begin
have : ∀ x ∈ s ∩ k, f x = 0 := λ x hx, hx.2,
rw [set_integral_eq_zero_of_forall_eq_zero this, zero_add],
end
... = ∫ x in s, f x ∂μ : by rw integral_inter_add_diff hk (h'aux.mono hts le_rfl)
end
/-- If a function vanishes almost everywhere on `t \ s` with `s ⊆ t`, then its integrals on `s`
and `t` coincide if `t` is null-measurable. -/
lemma set_integral_eq_of_subset_of_ae_diff_eq_zero
(ht : null_measurable_set t μ) (hts : s ⊆ t) (h't : ∀ᵐ x ∂μ, x ∈ t \ s → f x = 0) :
∫ x in t, f x ∂μ = ∫ x in s, f x ∂μ :=
begin
by_cases h : integrable_on f t μ, swap,
{ have : ¬(integrable_on f s μ) := λ H, h (H.of_ae_diff_eq_zero ht h't),
rw [integral_undef h, integral_undef this] },
let f' := h.1.mk f,
calc ∫ x in t, f x ∂μ
= ∫ x in t, f' x ∂μ : integral_congr_ae h.1.ae_eq_mk
... = ∫ x in s, f' x ∂μ :
begin
apply set_integral_eq_of_subset_of_ae_diff_eq_zero_aux hts _ h.1.strongly_measurable_mk
(h.congr h.1.ae_eq_mk),
filter_upwards [h't, ae_imp_of_ae_restrict h.1.ae_eq_mk] with x hx h'x h''x,
rw [← h'x h''x.1, hx h''x]
end
... = ∫ x in s, f x ∂μ :
begin
apply integral_congr_ae,
apply ae_restrict_of_ae_restrict_of_subset hts,
exact h.1.ae_eq_mk.symm
end
end
/-- If a function vanishes on `t \ s` with `s ⊆ t`, then its integrals on `s`
and `t` coincide if `t` is measurable. -/
lemma set_integral_eq_of_subset_of_forall_diff_eq_zero
(ht : measurable_set t) (hts : s ⊆ t) (h't : ∀ x ∈ t \ s, f x = 0) :
∫ x in t, f x ∂μ = ∫ x in s, f x ∂μ :=
set_integral_eq_of_subset_of_ae_diff_eq_zero ht.null_measurable_set hts
(eventually_of_forall (λ x hx, h't x hx))
/-- If a function vanishes almost everywhere on `sᶜ`, then its integral on `s`
coincides with its integral on the whole space. -/
lemma set_integral_eq_integral_of_ae_compl_eq_zero
(h : ∀ᵐ x ∂μ, x ∉ s → f x = 0) : ∫ x in s, f x ∂μ = ∫ x, f x ∂μ :=
begin
conv_rhs { rw ← integral_univ },
symmetry,
apply set_integral_eq_of_subset_of_ae_diff_eq_zero null_measurable_set_univ (subset_univ _),
filter_upwards [h] with x hx h'x using hx h'x.2,
end
/-- If a function vanishes on `sᶜ`, then its integral on `s` coincides with its integral on the
whole space. -/
lemma set_integral_eq_integral_of_forall_compl_eq_zero
(h : ∀ x, x ∉ s → f x = 0) : ∫ x in s, f x ∂μ = ∫ x, f x ∂μ :=
set_integral_eq_integral_of_ae_compl_eq_zero (eventually_of_forall h)
lemma set_integral_neg_eq_set_integral_nonpos [linear_order E]
{f : α → E} (hf : ae_strongly_measurable f μ) :
∫ x in {x | f x < 0}, f x ∂μ = ∫ x in {x | f x ≤ 0}, f x ∂μ :=
begin
have h_union : {x | f x ≤ 0} = {x | f x < 0} ∪ {x | f x = 0},
by { ext, simp_rw [set.mem_union, set.mem_set_of_eq], exact le_iff_lt_or_eq, },
rw h_union,
have B : null_measurable_set {x | f x = 0} μ,
from hf.null_measurable_set_eq_fun ae_strongly_measurable_zero,
symmetry,
refine integral_union_eq_left_of_ae _,
filter_upwards [ae_restrict_mem₀ B] with x hx using hx,
end
lemma integral_norm_eq_pos_sub_neg {f : α → ℝ} (hfi : integrable f μ) :
∫ x, ‖f x‖ ∂μ = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | f x ≤ 0}, f x ∂μ :=
have h_meas : null_measurable_set {x | 0 ≤ f x} μ,
from ae_strongly_measurable_const.null_measurable_set_le hfi.1,
calc ∫ x, ‖f x‖ ∂μ = ∫ x in {x | 0 ≤ f x}, ‖f x‖ ∂μ + ∫ x in {x | 0 ≤ f x}ᶜ, ‖f x‖ ∂μ :
by rw ← integral_add_compl₀ h_meas hfi.norm
... = ∫ x in {x | 0 ≤ f x}, f x ∂μ + ∫ x in {x | 0 ≤ f x}ᶜ, ‖f x‖ ∂μ :
begin
congr' 1,
refine set_integral_congr₀ h_meas (λ x hx, _),
dsimp only,
rw [real.norm_eq_abs, abs_eq_self.mpr _],
exact hx,
end
... = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | 0 ≤ f x}ᶜ, f x ∂μ :
begin
congr' 1,
rw ← integral_neg,
refine set_integral_congr₀ h_meas.compl (λ x hx, _),
dsimp only,
rw [real.norm_eq_abs, abs_eq_neg_self.mpr _],
rw [set.mem_compl_iff, set.nmem_set_of_iff] at hx,
linarith,
end
... = ∫ x in {x | 0 ≤ f x}, f x ∂μ - ∫ x in {x | f x ≤ 0}, f x ∂μ :
by { rw ← set_integral_neg_eq_set_integral_nonpos hfi.1, congr, ext1 x, simp, }
lemma set_integral_const (c : E) : ∫ x in s, c ∂μ = (μ s).to_real • c :=
by rw [integral_const, measure.restrict_apply_univ]
@[simp]
lemma integral_indicator_const (e : E) ⦃s : set α⦄ (s_meas : measurable_set s) :
∫ (a : α), s.indicator (λ (x : α), e) a ∂μ = (μ s).to_real • e :=
by rw [integral_indicator s_meas, ← set_integral_const]
@[simp]
lemma integral_indicator_one ⦃s : set α⦄ (hs : measurable_set s) :
∫ a, s.indicator 1 a ∂μ = (μ s).to_real :=
(integral_indicator_const 1 hs).trans ((smul_eq_mul _).trans (mul_one _))
lemma set_integral_indicator_const_Lp {p : ℝ≥0∞} (hs : measurable_set s) (ht : measurable_set t)
(hμt : μ t ≠ ∞) (x : E) :
∫ a in s, indicator_const_Lp p ht hμt x a ∂μ = (μ (t ∩ s)).to_real • x :=
calc ∫ a in s, indicator_const_Lp p ht hμt x a ∂μ
= (∫ a in s, t.indicator (λ _, x) a ∂μ) :
by rw set_integral_congr_ae hs (indicator_const_Lp_coe_fn.mono (λ x hx hxs, hx))
... = (μ (t ∩ s)).to_real • x : by rw [integral_indicator_const _ ht, measure.restrict_apply ht]
lemma integral_indicator_const_Lp {p : ℝ≥0∞} (ht : measurable_set t) (hμt : μ t ≠ ∞) (x : E) :
∫ a, indicator_const_Lp p ht hμt x a ∂μ = (μ t).to_real • x :=
calc ∫ a, indicator_const_Lp p ht hμt x a ∂μ
= ∫ a in univ, indicator_const_Lp p ht hμt x a ∂μ : by rw integral_univ
... = (μ (t ∩ univ)).to_real • x : set_integral_indicator_const_Lp measurable_set.univ ht hμt x
... = (μ t).to_real • x : by rw inter_univ
lemma set_integral_map {β} [measurable_space β] {g : α → β} {f : β → E} {s : set β}
(hs : measurable_set s)
(hf : ae_strongly_measurable f (measure.map g μ)) (hg : ae_measurable g μ) :
∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ :=
begin
rw [measure.restrict_map_of_ae_measurable hg hs,
integral_map (hg.mono_measure measure.restrict_le_self) (hf.mono_measure _)],
exact measure.map_mono_of_ae_measurable measure.restrict_le_self hg
end
lemma _root_.measurable_embedding.set_integral_map {β} {_ : measurable_space β} {f : α → β}
(hf : measurable_embedding f) (g : β → E) (s : set β) :
∫ y in s, g y ∂(measure.map f μ) = ∫ x in f ⁻¹' s, g (f x) ∂μ :=
by rw [hf.restrict_map, hf.integral_map]
lemma _root_.closed_embedding.set_integral_map [topological_space α] [borel_space α]
{β} [measurable_space β] [topological_space β] [borel_space β]
{g : α → β} {f : β → E} (s : set β) (hg : closed_embedding g) :
∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ :=
hg.measurable_embedding.set_integral_map _ _
lemma measure_preserving.set_integral_preimage_emb {β} {_ : measurable_space β} {f : α → β} {ν}
(h₁ : measure_preserving f μ ν) (h₂ : measurable_embedding f) (g : β → E) (s : set β) :
∫ x in f ⁻¹' s, g (f x) ∂μ = ∫ y in s, g y ∂ν :=
(h₁.restrict_preimage_emb h₂ s).integral_comp h₂ _
lemma measure_preserving.set_integral_image_emb {β} {_ : measurable_space β} {f : α → β} {ν}
(h₁ : measure_preserving f μ ν) (h₂ : measurable_embedding f) (g : β → E) (s : set α) :
∫ y in f '' s, g y ∂ν = ∫ x in s, g (f x) ∂μ :=
eq.symm $ (h₁.restrict_image_emb h₂ s).integral_comp h₂ _
lemma set_integral_map_equiv {β} [measurable_space β] (e : α ≃ᵐ β) (f : β → E) (s : set β) :
∫ y in s, f y ∂(measure.map e μ) = ∫ x in e ⁻¹' s, f (e x) ∂μ :=
e.measurable_embedding.set_integral_map f s
lemma norm_set_integral_le_of_norm_le_const_ae {C : ℝ} (hs : μ s < ∞)
(hC : ∀ᵐ x ∂μ.restrict s, ‖f x‖ ≤ C) :
‖∫ x in s, f x ∂μ‖ ≤ C * (μ s).to_real :=
begin
rw ← measure.restrict_apply_univ at *,
haveI : is_finite_measure (μ.restrict s) := ⟨‹_›⟩,
exact norm_integral_le_of_norm_le_const hC
end
lemma norm_set_integral_le_of_norm_le_const_ae' {C : ℝ} (hs : μ s < ∞)
(hC : ∀ᵐ x ∂μ, x ∈ s → ‖f x‖ ≤ C) (hfm : ae_strongly_measurable f (μ.restrict s)) :
‖∫ x in s, f x ∂μ‖ ≤ C * (μ s).to_real :=
begin
apply norm_set_integral_le_of_norm_le_const_ae hs,
have A : ∀ᵐ (x : α) ∂μ, x ∈ s → ‖ae_strongly_measurable.mk f hfm x‖ ≤ C,
{ filter_upwards [hC, hfm.ae_mem_imp_eq_mk] with _ h1 h2 h3,
rw [← h2 h3],
exact h1 h3 },
have B : measurable_set {x | ‖(hfm.mk f) x‖ ≤ C} :=
hfm.strongly_measurable_mk.norm.measurable measurable_set_Iic,
filter_upwards [hfm.ae_eq_mk, (ae_restrict_iff B).2 A] with _ h1 _,
rwa h1,
end
lemma norm_set_integral_le_of_norm_le_const_ae'' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s)
(hC : ∀ᵐ x ∂μ, x ∈ s → ‖f x‖ ≤ C) :
‖∫ x in s, f x ∂μ‖ ≤ C * (μ s).to_real :=
norm_set_integral_le_of_norm_le_const_ae hs $ by rwa [ae_restrict_eq hsm, eventually_inf_principal]
lemma norm_set_integral_le_of_norm_le_const {C : ℝ} (hs : μ s < ∞)
(hC : ∀ x ∈ s, ‖f x‖ ≤ C) (hfm : ae_strongly_measurable f (μ.restrict s)) :
‖∫ x in s, f x ∂μ‖ ≤ C * (μ s).to_real :=
norm_set_integral_le_of_norm_le_const_ae' hs (eventually_of_forall hC) hfm
lemma norm_set_integral_le_of_norm_le_const' {C : ℝ} (hs : μ s < ∞) (hsm : measurable_set s)
(hC : ∀ x ∈ s, ‖f x‖ ≤ C) :
‖∫ x in s, f x ∂μ‖ ≤ C * (μ s).to_real :=
norm_set_integral_le_of_norm_le_const_ae'' hs hsm $ eventually_of_forall hC
lemma set_integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f)
(hfi : integrable_on f s μ) :
∫ x in s, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict s] 0 :=
integral_eq_zero_iff_of_nonneg_ae hf hfi
lemma set_integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f)
(hfi : integrable_on f s μ) :
0 < ∫ x in s, f x ∂μ ↔ 0 < μ (support f ∩ s) :=
begin
rw [integral_pos_iff_support_of_nonneg_ae hf hfi, measure.restrict_apply₀],
rw support_eq_preimage,
exact hfi.ae_strongly_measurable.ae_measurable.null_measurable (measurable_set_singleton 0).compl
end
lemma set_integral_gt_gt {R : ℝ} {f : α → ℝ} (hR : 0 ≤ R) (hfm : measurable f)
(hfint : integrable_on f {x | ↑R < f x} μ) (hμ : μ {x | ↑R < f x} ≠ 0):
(μ {x | ↑R < f x}).to_real * R < ∫ x in {x | ↑R < f x}, f x ∂μ :=
begin
have : integrable_on (λ x, R) {x | ↑R < f x} μ,
{ refine ⟨ae_strongly_measurable_const, lt_of_le_of_lt _ hfint.2⟩,
refine set_lintegral_mono (measurable.nnnorm _).coe_nnreal_ennreal
hfm.nnnorm.coe_nnreal_ennreal (λ x hx, _),
{ exact measurable_const },
{ simp only [ennreal.coe_le_coe, real.nnnorm_of_nonneg hR,
real.nnnorm_of_nonneg (hR.trans $ le_of_lt hx), subtype.mk_le_mk],
exact le_of_lt hx } },
rw [← sub_pos, ← smul_eq_mul, ← set_integral_const, ← integral_sub hfint this,
set_integral_pos_iff_support_of_nonneg_ae],
{ rw ← zero_lt_iff at hμ,
rwa set.inter_eq_self_of_subset_right,
exact λ x hx, ne.symm (ne_of_lt $ sub_pos.2 hx) },
{ change ∀ᵐ x ∂(μ.restrict _), _,
rw ae_restrict_iff,
{ exact eventually_of_forall (λ x hx, sub_nonneg.2 $ le_of_lt hx) },
{ exact measurable_set_le measurable_zero (hfm.sub measurable_const) } },
{ exact integrable.sub hfint this },
end
lemma set_integral_trim {α} {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) {f : α → E}
(hf_meas : strongly_measurable[m] f) {s : set α} (hs : measurable_set[m] s) :
∫ x in s, f x ∂μ = ∫ x in s, f x ∂(μ.trim hm) :=
by rwa [integral_trim hm hf_meas, restrict_trim hm μ]
/-! ### Lemmas about adding and removing interval boundaries
The primed lemmas take explicit arguments about the endpoint having zero measure, while the
unprimed ones use `[has_no_atoms μ]`.
-/
section partial_order
variables [partial_order α] {a b : α}
lemma integral_Icc_eq_integral_Ioc' (ha : μ {a} = 0) :
∫ t in Icc a b, f t ∂μ = ∫ t in Ioc a b, f t ∂μ :=
set_integral_congr_set_ae (Ioc_ae_eq_Icc' ha).symm
lemma integral_Icc_eq_integral_Ico' (hb : μ {b} = 0) :
∫ t in Icc a b, f t ∂μ = ∫ t in Ico a b, f t ∂μ :=
set_integral_congr_set_ae (Ico_ae_eq_Icc' hb).symm
lemma integral_Ioc_eq_integral_Ioo' (hb : μ {b} = 0) :
∫ t in Ioc a b, f t ∂μ = ∫ t in Ioo a b, f t ∂μ :=
set_integral_congr_set_ae (Ioo_ae_eq_Ioc' hb).symm
lemma integral_Ico_eq_integral_Ioo' (ha : μ {a} = 0) :
∫ t in Ico a b, f t ∂μ = ∫ t in Ioo a b, f t ∂μ :=
set_integral_congr_set_ae (Ioo_ae_eq_Ico' ha).symm
lemma integral_Icc_eq_integral_Ioo' (ha : μ {a} = 0) (hb : μ {b} = 0) :
∫ t in Icc a b, f t ∂μ = ∫ t in Ioo a b, f t ∂μ :=
set_integral_congr_set_ae (Ioo_ae_eq_Icc' ha hb).symm
lemma integral_Iic_eq_integral_Iio' (ha : μ {a} = 0) :
∫ t in Iic a, f t ∂μ = ∫ t in Iio a, f t ∂μ :=
set_integral_congr_set_ae (Iio_ae_eq_Iic' ha).symm
lemma integral_Ici_eq_integral_Ioi' (ha : μ {a} = 0) :
∫ t in Ici a, f t ∂μ = ∫ t in Ioi a, f t ∂μ :=
set_integral_congr_set_ae (Ioi_ae_eq_Ici' ha).symm
variable [has_no_atoms μ]
lemma integral_Icc_eq_integral_Ioc : ∫ t in Icc a b, f t ∂μ = ∫ t in Ioc a b, f t ∂μ :=
integral_Icc_eq_integral_Ioc' $ measure_singleton a
lemma integral_Icc_eq_integral_Ico : ∫ t in Icc a b, f t ∂μ = ∫ t in Ico a b, f t ∂μ :=
integral_Icc_eq_integral_Ico' $ measure_singleton b
lemma integral_Ioc_eq_integral_Ioo : ∫ t in Ioc a b, f t ∂μ = ∫ t in Ioo a b, f t ∂μ :=
integral_Ioc_eq_integral_Ioo' $ measure_singleton b
lemma integral_Ico_eq_integral_Ioo : ∫ t in Ico a b, f t ∂μ = ∫ t in Ioo a b, f t ∂μ :=
integral_Ico_eq_integral_Ioo' $ measure_singleton a
lemma integral_Icc_eq_integral_Ioo : ∫ t in Icc a b, f t ∂μ = ∫ t in Ico a b, f t ∂μ :=
by rw [integral_Icc_eq_integral_Ico, integral_Ico_eq_integral_Ioo]
lemma integral_Iic_eq_integral_Iio : ∫ t in Iic a, f t ∂μ = ∫ t in Iio a, f t ∂μ :=
integral_Iic_eq_integral_Iio' $ measure_singleton a
lemma integral_Ici_eq_integral_Ioi : ∫ t in Ici a, f t ∂μ = ∫ t in Ioi a, f t ∂μ :=
integral_Ici_eq_integral_Ioi' $ measure_singleton a
end partial_order
end normed_add_comm_group
section mono
variables {μ : measure α} {f g : α → ℝ} {s t : set α}
(hf : integrable_on f s μ) (hg : integrable_on g s μ)
lemma set_integral_mono_ae_restrict (h : f ≤ᵐ[μ.restrict s] g) :
∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ :=
integral_mono_ae hf hg h
lemma set_integral_mono_ae (h : f ≤ᵐ[μ] g) :
∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ :=
set_integral_mono_ae_restrict hf hg (ae_restrict_of_ae h)
lemma set_integral_mono_on (hs : measurable_set s) (h : ∀ x ∈ s, f x ≤ g x) :
∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ :=
set_integral_mono_ae_restrict hf hg
(by simp [hs, eventually_le, eventually_inf_principal, ae_of_all _ h])
include hf hg -- why do I need this include, but we don't need it in other lemmas?
lemma set_integral_mono_on_ae (hs : measurable_set s) (h : ∀ᵐ x ∂μ, x ∈ s → f x ≤ g x) :
∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ :=
by { refine set_integral_mono_ae_restrict hf hg _, rwa [eventually_le, ae_restrict_iff' hs], }
omit hf hg
lemma set_integral_mono (h : f ≤ g) :
∫ a in s, f a ∂μ ≤ ∫ a in s, g a ∂μ :=
integral_mono hf hg h
lemma set_integral_mono_set (hfi : integrable_on f t μ) (hf : 0 ≤ᵐ[μ.restrict t] f)
(hst : s ≤ᵐ[μ] t) :
∫ x in s, f x ∂μ ≤ ∫ x in t, f x ∂μ :=
integral_mono_measure (measure.restrict_mono_ae hst) hf hfi
lemma set_integral_ge_of_const_le {c : ℝ} (hs : measurable_set s) (hμs : μ s ≠ ∞)
(hf : ∀ x ∈ s, c ≤ f x) (hfint : integrable_on (λ (x : α), f x) s μ) :
c * (μ s).to_real ≤ ∫ x in s, f x ∂μ :=
begin
rw [mul_comm, ← smul_eq_mul, ← set_integral_const c],
exact set_integral_mono_on (integrable_on_const.2 (or.inr hμs.lt_top)) hfint hs hf,
end
end mono
section nonneg
variables {μ : measure α} {f : α → ℝ} {s : set α}
lemma set_integral_nonneg_of_ae_restrict (hf : 0 ≤ᵐ[μ.restrict s] f) :
0 ≤ ∫ a in s, f a ∂μ :=
integral_nonneg_of_ae hf
lemma set_integral_nonneg_of_ae (hf : 0 ≤ᵐ[μ] f) : 0 ≤ ∫ a in s, f a ∂μ :=
set_integral_nonneg_of_ae_restrict (ae_restrict_of_ae hf)
lemma set_integral_nonneg (hs : measurable_set s) (hf : ∀ a, a ∈ s → 0 ≤ f a) :
0 ≤ ∫ a in s, f a ∂μ :=
set_integral_nonneg_of_ae_restrict ((ae_restrict_iff' hs).mpr (ae_of_all μ hf))
lemma set_integral_nonneg_ae (hs : measurable_set s) (hf : ∀ᵐ a ∂μ, a ∈ s → 0 ≤ f a) :
0 ≤ ∫ a in s, f a ∂μ :=
set_integral_nonneg_of_ae_restrict $ by rwa [eventually_le, ae_restrict_iff' hs]
lemma set_integral_le_nonneg {s : set α} (hs : measurable_set s) (hf : strongly_measurable f)
(hfi : integrable f μ) :
∫ x in s, f x ∂μ ≤ ∫ x in {y | 0 ≤ f y}, f x ∂μ :=
begin
rw [← integral_indicator hs,
← integral_indicator (strongly_measurable_const.measurable_set_le hf)],
exact integral_mono (hfi.indicator hs)
(hfi.indicator (strongly_measurable_const.measurable_set_le hf))
(indicator_le_indicator_nonneg s f),
end
lemma set_integral_nonpos_of_ae_restrict (hf : f ≤ᵐ[μ.restrict s] 0) :
∫ a in s, f a ∂μ ≤ 0 :=
integral_nonpos_of_ae hf
lemma set_integral_nonpos_of_ae (hf : f ≤ᵐ[μ] 0) : ∫ a in s, f a ∂μ ≤ 0 :=
set_integral_nonpos_of_ae_restrict (ae_restrict_of_ae hf)
lemma set_integral_nonpos (hs : measurable_set s) (hf : ∀ a, a ∈ s → f a ≤ 0) :
∫ a in s, f a ∂μ ≤ 0 :=
set_integral_nonpos_of_ae_restrict ((ae_restrict_iff' hs).mpr (ae_of_all μ hf))
lemma set_integral_nonpos_ae (hs : measurable_set s) (hf : ∀ᵐ a ∂μ, a ∈ s → f a ≤ 0) :
∫ a in s, f a ∂μ ≤ 0 :=
set_integral_nonpos_of_ae_restrict $ by rwa [eventually_le, ae_restrict_iff' hs]
lemma set_integral_nonpos_le {s : set α} (hs : measurable_set s) (hf : strongly_measurable f)
(hfi : integrable f μ) :
∫ x in {y | f y ≤ 0}, f x ∂μ ≤ ∫ x in s, f x ∂μ :=
begin
rw [← integral_indicator hs,
← integral_indicator (hf.measurable_set_le strongly_measurable_const)],
exact integral_mono (hfi.indicator (hf.measurable_set_le strongly_measurable_const))
(hfi.indicator hs) (indicator_nonpos_le_indicator s f),
end
end nonneg
section integrable_Union
variables {μ : measure α} [normed_add_comm_group E] [countable β]
lemma integrable_on_Union_of_summable_integral_norm {f : α → E} {s : β → set α}
(hs : ∀ (b : β), measurable_set (s b)) (hi : ∀ (b : β), integrable_on f (s b) μ)
(h : summable (λ (b : β), ∫ (a : α) in s b, ‖f a‖ ∂μ)) :
integrable_on f (Union s) μ :=
begin
refine ⟨ae_strongly_measurable.Union (λ i, (hi i).1), (lintegral_Union_le _ _).trans_lt _⟩,
have B := λ (b : β), lintegral_coe_eq_integral (λ (a : α), ‖f a‖₊) (hi b).norm,
rw tsum_congr B,
have S' : summable (λ (b : β), (⟨∫ (a : α) in s b, ‖f a‖₊ ∂μ,
set_integral_nonneg (hs b) (λ a ha, nnreal.coe_nonneg _)⟩ : nnreal)),
{ rw ←nnreal.summable_coe, exact h },
have S'' := ennreal.tsum_coe_eq S'.has_sum,
simp_rw [ennreal.coe_nnreal_eq, nnreal.coe_mk, coe_nnnorm] at S'',
convert ennreal.of_real_lt_top,
end
variables [topological_space α] [borel_space α] [metrizable_space α] [is_locally_finite_measure μ]
/-- If `s` is a countable family of compact sets, `f` is a continuous function, and the sequence
`‖f.restrict (s i)‖ * μ (s i)` is summable, then `f` is integrable on the union of the `s i`. -/
lemma integrable_on_Union_of_summable_norm_restrict {f : C(α, E)} {s : β → compacts α}
(hf : summable (λ i : β, ‖f.restrict (s i)‖ * ennreal.to_real (μ $ s i))) :
integrable_on f (⋃ i : β, s i) μ :=
begin
refine integrable_on_Union_of_summable_integral_norm
(λ i, (s i).is_compact.is_closed.measurable_set)
(λ i, (map_continuous f).continuous_on.integrable_on_compact (s i).is_compact)
(summable_of_nonneg_of_le (λ ι, integral_nonneg (λ x, norm_nonneg _)) (λ i, _) hf),
rw ←(real.norm_of_nonneg (integral_nonneg (λ a, norm_nonneg _)) : ‖_‖ = ∫ x in s i, ‖f x‖ ∂μ),
exact norm_set_integral_le_of_norm_le_const' (s i).is_compact.measure_lt_top
(s i).is_compact.is_closed.measurable_set
(λ x hx, (norm_norm (f x)).symm ▸ (f.restrict ↑(s i)).norm_coe_le_norm ⟨x, hx⟩)
end
/-- If `s` is a countable family of compact sets covering `α`, `f` is a continuous function, and
the sequence `‖f.restrict (s i)‖ * μ (s i)` is summable, then `f` is integrable. -/
lemma integrable_of_summable_norm_restrict {f : C(α, E)} {s : β → compacts α}
(hf : summable (λ i : β, ‖f.restrict (s i)‖ * ennreal.to_real (μ $ s i)))
(hs : (⋃ i : β, ↑(s i)) = (univ : set α)) :
integrable f μ :=
by simpa only [hs, integrable_on_univ] using integrable_on_Union_of_summable_norm_restrict hf
end integrable_Union
section tendsto_mono
variables {μ : measure α} [normed_add_comm_group E] [complete_space E] [normed_space ℝ E]
{s : ℕ → set α} {f : α → E}
lemma _root_.antitone.tendsto_set_integral (hsm : ∀ i, measurable_set (s i))
(h_anti : antitone s) (hfi : integrable_on f (s 0) μ) :
tendsto (λi, ∫ a in s i, f a ∂μ) at_top (𝓝 (∫ a in (⋂ n, s n), f a ∂μ)) :=
begin
let bound : α → ℝ := indicator (s 0) (λ a, ‖f a‖),
have h_int_eq : (λ i, ∫ a in s i, f a ∂μ) = (λ i, ∫ a, (s i).indicator f a ∂μ),
from funext (λ i, (integral_indicator (hsm i)).symm),
rw h_int_eq,
rw ← integral_indicator (measurable_set.Inter hsm),
refine tendsto_integral_of_dominated_convergence bound _ _ _ _,
{ intro n,
rw ae_strongly_measurable_indicator_iff (hsm n),
exact (integrable_on.mono_set hfi (h_anti (zero_le n))).1 },
{ rw integrable_indicator_iff (hsm 0),
exact hfi.norm, },
{ simp_rw norm_indicator_eq_indicator_norm,
refine λ n, eventually_of_forall (λ x, _),
exact indicator_le_indicator_of_subset (h_anti (zero_le n)) (λ a, norm_nonneg _) _ },
{ filter_upwards with a using le_trans (h_anti.tendsto_indicator _ _ _) (pure_le_nhds _), },
end
end tendsto_mono
/-! ### Continuity of the set integral
We prove that for any set `s`, the function `λ f : α →₁[μ] E, ∫ x in s, f x ∂μ` is continuous. -/
section continuous_set_integral
variables [normed_add_comm_group E] {𝕜 : Type*} [normed_field 𝕜] [normed_add_comm_group F]
[normed_space 𝕜 F] {p : ℝ≥0∞} {μ : measure α}
/-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by
`(Lp.mem_ℒp f).restrict s).to_Lp f`. This map is additive. -/
lemma Lp_to_Lp_restrict_add (f g : Lp E p μ) (s : set α) :
((Lp.mem_ℒp (f + g)).restrict s).to_Lp ⇑(f + g)
= ((Lp.mem_ℒp f).restrict s).to_Lp f + ((Lp.mem_ℒp g).restrict s).to_Lp g :=
begin
ext1,
refine (ae_restrict_of_ae (Lp.coe_fn_add f g)).mp _,
refine (Lp.coe_fn_add (mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s))
(mem_ℒp.to_Lp g ((Lp.mem_ℒp g).restrict s))).mp _,
refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s)).mp _,
refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp g).restrict s)).mp _,
refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp (f+g)).restrict s)).mono (λ x hx1 hx2 hx3 hx4 hx5, _),
rw [hx4, hx1, pi.add_apply, hx2, hx3, hx5, pi.add_apply],
end
/-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by
`(Lp.mem_ℒp f).restrict s).to_Lp f`. This map commutes with scalar multiplication. -/
lemma Lp_to_Lp_restrict_smul (c : 𝕜) (f : Lp F p μ) (s : set α) :
((Lp.mem_ℒp (c • f)).restrict s).to_Lp ⇑(c • f) = c • (((Lp.mem_ℒp f).restrict s).to_Lp f) :=
begin
ext1,
refine (ae_restrict_of_ae (Lp.coe_fn_smul c f)).mp _,
refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s)).mp _,
refine (mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp (c • f)).restrict s)).mp _,
refine (Lp.coe_fn_smul c (mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s))).mono
(λ x hx1 hx2 hx3 hx4, _),
rw [hx2, hx1, pi.smul_apply, hx3, hx4, pi.smul_apply],
end
/-- For `f : Lp E p μ`, we can define an element of `Lp E p (μ.restrict s)` by
`(Lp.mem_ℒp f).restrict s).to_Lp f`. This map is non-expansive. -/
lemma norm_Lp_to_Lp_restrict_le (s : set α) (f : Lp E p μ) :
‖((Lp.mem_ℒp f).restrict s).to_Lp f‖ ≤ ‖f‖ :=
begin
rw [Lp.norm_def, Lp.norm_def, ennreal.to_real_le_to_real (Lp.snorm_ne_top _) (Lp.snorm_ne_top _)],
refine (le_of_eq _).trans (snorm_mono_measure _ measure.restrict_le_self),
{ exact s, },
exact snorm_congr_ae (mem_ℒp.coe_fn_to_Lp _),
end
variables (α F 𝕜)
/-- Continuous linear map sending a function of `Lp F p μ` to the same function in
`Lp F p (μ.restrict s)`. -/
def Lp_to_Lp_restrict_clm (μ : measure α) (p : ℝ≥0∞) [hp : fact (1 ≤ p)] (s : set α) :
Lp F p μ →L[𝕜] Lp F p (μ.restrict s) :=
@linear_map.mk_continuous 𝕜 𝕜 (Lp F p μ) (Lp F p (μ.restrict s)) _ _ _ _ _ _ (ring_hom.id 𝕜)
⟨λ f, mem_ℒp.to_Lp f ((Lp.mem_ℒp f).restrict s), λ f g, Lp_to_Lp_restrict_add f g s,
λ c f, Lp_to_Lp_restrict_smul c f s⟩
1 (by { intro f, rw one_mul, exact norm_Lp_to_Lp_restrict_le s f, })
variables {α F 𝕜}
variables (𝕜)
lemma Lp_to_Lp_restrict_clm_coe_fn [hp : fact (1 ≤ p)] (s : set α) (f : Lp F p μ) :
Lp_to_Lp_restrict_clm α F 𝕜 μ p s f =ᵐ[μ.restrict s] f :=
mem_ℒp.coe_fn_to_Lp ((Lp.mem_ℒp f).restrict s)
variables {𝕜}
@[continuity]
lemma continuous_set_integral [normed_space ℝ E] [complete_space E] (s : set α) :
continuous (λ f : α →₁[μ] E, ∫ x in s, f x ∂μ) :=
begin
haveI : fact ((1 : ℝ≥0∞) ≤ 1) := ⟨le_rfl⟩,
have h_comp : (λ f : α →₁[μ] E, ∫ x in s, f x ∂μ)
= (integral (μ.restrict s)) ∘ (λ f, Lp_to_Lp_restrict_clm α E ℝ μ 1 s f),
{ ext1 f,
rw [function.comp_apply, integral_congr_ae (Lp_to_Lp_restrict_clm_coe_fn ℝ s f)], },
rw h_comp,
exact continuous_integral.comp (Lp_to_Lp_restrict_clm α E ℝ μ 1 s).continuous,
end
end continuous_set_integral
end measure_theory
open measure_theory asymptotics metric
variables {ι : Type*} [normed_add_comm_group E]
/-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite at a
filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ μ.ae`, then `∫ x in
s i, f x ∂μ = μ (s i) • b + o(μ (s i))` at a filter `li` provided that `s i` tends to `l.small_sets`
along `li`. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement.
Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional
argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these
arguments, `m i = (μ (s i)).to_real` is used in the output. -/
lemma filter.tendsto.integral_sub_linear_is_o_ae
[normed_space ℝ E] [complete_space E]
{μ : measure α} {l : filter α} [l.is_measurably_generated]
{f : α → E} {b : E} (h : tendsto f (l ⊓ μ.ae) (𝓝 b))
(hfm : strongly_measurable_at_filter f l μ) (hμ : μ.finite_at_filter l)
{s : ι → set α} {li : filter ι} (hs : tendsto s li l.small_sets)
(m : ι → ℝ := λ i, (μ (s i)).to_real)
(hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) :
(λ i, ∫ x in s i, f x ∂μ - m i • b) =o[li] m :=
begin
suffices : (λ s, ∫ x in s, f x ∂μ - (μ s).to_real • b) =o[l.small_sets] (λ s, (μ s).to_real),
from (this.comp_tendsto hs).congr' (hsμ.mono $ λ a ha, ha ▸ rfl) hsμ,
refine is_o_iff.2 (λ ε ε₀, _),
have : ∀ᶠ s in l.small_sets, ∀ᶠ x in μ.ae, x ∈ s → f x ∈ closed_ball b ε :=
eventually_small_sets_eventually.2 (h.eventually $ closed_ball_mem_nhds _ ε₀),
filter_upwards [hμ.eventually, (hμ.integrable_at_filter_of_tendsto_ae hfm h).eventually,
hfm.eventually, this],
simp only [mem_closed_ball, dist_eq_norm],
intros s hμs h_integrable hfm h_norm,
rw [← set_integral_const, ← integral_sub h_integrable (integrable_on_const.2 $ or.inr hμs),
real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg],
exact norm_set_integral_le_of_norm_le_const_ae' hμs h_norm (hfm.sub ae_strongly_measurable_const)
end
/-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally
finite measure and `f` is an almost everywhere measurable function that is continuous at a point `a`
within a measurable set `t`, then `∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at a filter `li`
provided that `s i` tends to `(𝓝[t] a).small_sets` along `li`. Since `μ (s i)` is an `ℝ≥0∞`
number, we use `(μ (s i)).to_real` in the actual statement.
Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional
argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these
arguments, `m i = (μ (s i)).to_real` is used in the output. -/
lemma continuous_within_at.integral_sub_linear_is_o_ae
[topological_space α] [opens_measurable_space α]
[normed_space ℝ E] [complete_space E]
{μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α}
{f : α → E} (ha : continuous_within_at f t a) (ht : measurable_set t)
(hfm : strongly_measurable_at_filter f (𝓝[t] a) μ)
{s : ι → set α} {li : filter ι} (hs : tendsto s li (𝓝[t] a).small_sets)
(m : ι → ℝ := λ i, (μ (s i)).to_real)
(hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) :
(λ i, ∫ x in s i, f x ∂μ - m i • f a) =o[li] m :=
by haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _;
exact (ha.mono_left inf_le_left).integral_sub_linear_is_o_ae
hfm (μ.finite_at_nhds_within a t) hs m hsμ
/-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite
measure and `f` is an almost everywhere measurable function that is continuous at a point `a`, then
`∫ x in s i, f x ∂μ = μ (s i) • f a + o(μ (s i))` at `li` provided that `s` tends to
`(𝓝 a).small_sets` along `li. Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in
the actual statement.
Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional
argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these
arguments, `m i = (μ (s i)).to_real` is used in the output. -/
lemma continuous_at.integral_sub_linear_is_o_ae
[topological_space α] [opens_measurable_space α]
[normed_space ℝ E] [complete_space E]
{μ : measure α} [is_locally_finite_measure μ] {a : α}
{f : α → E} (ha : continuous_at f a) (hfm : strongly_measurable_at_filter f (𝓝 a) μ)
{s : ι → set α} {li : filter ι} (hs : tendsto s li (𝓝 a).small_sets)
(m : ι → ℝ := λ i, (μ (s i)).to_real)
(hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) :
(λ i, ∫ x in s i, f x ∂μ - m i • f a) =o[li] m :=
(ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds a) hs m hsμ
/-- Fundamental theorem of calculus for set integrals, `nhds_within` version: if `μ` is a locally
finite measure, `f` is continuous on a measurable set `t`, and `a ∈ t`, then `∫ x in (s i), f x ∂μ =
μ (s i) • f a + o(μ (s i))` at `li` provided that `s i` tends to `(𝓝[t] a).small_sets` along `li`.
Since `μ (s i)` is an `ℝ≥0∞` number, we use `(μ (s i)).to_real` in the actual statement.
Often there is a good formula for `(μ (s i)).to_real`, so the formalization can take an optional
argument `m` with this formula and a proof `of `(λ i, (μ (s i)).to_real) =ᶠ[li] m`. Without these
arguments, `m i = (μ (s i)).to_real` is used in the output. -/
lemma continuous_on.integral_sub_linear_is_o_ae
[topological_space α] [opens_measurable_space α]
[normed_space ℝ E] [complete_space E] [second_countable_topology_either α E]
{μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α}
{f : α → E} (hft : continuous_on f t) (ha : a ∈ t) (ht : measurable_set t)
{s : ι → set α} {li : filter ι} (hs : tendsto s li (𝓝[t] a).small_sets)
(m : ι → ℝ := λ i, (μ (s i)).to_real)
(hsμ : (λ i, (μ (s i)).to_real) =ᶠ[li] m . tactic.interactive.refl) :
(λ i, ∫ x in s i, f x ∂μ - m i • f a) =o[li] m :=
(hft a ha).integral_sub_linear_is_o_ae ht
⟨t, self_mem_nhds_within, hft.ae_strongly_measurable ht⟩ hs m hsμ
section
/-! ### Continuous linear maps composed with integration
The goal of this section is to prove that integration commutes with continuous linear maps.
This holds for simple functions. The general result follows from the continuity of all involved
operations on the space `L¹`. Note that composition by a continuous linear map on `L¹` is not just
the composition, as we are dealing with classes of functions, but it has already been defined
as `continuous_linear_map.comp_Lp`. We take advantage of this construction here.
-/
open_locale complex_conjugate
variables {μ : measure α} {𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E]
[normed_add_comm_group F] [normed_space 𝕜 F]
{p : ennreal}
namespace continuous_linear_map
variables [complete_space F] [normed_space ℝ F]
lemma integral_comp_Lp (L : E →L[𝕜] F) (φ : Lp E p μ) :
∫ a, (L.comp_Lp φ) a ∂μ = ∫ a, L (φ a) ∂μ :=
integral_congr_ae $ coe_fn_comp_Lp _ _
lemma set_integral_comp_Lp (L : E →L[𝕜] F) (φ : Lp E p μ) {s : set α} (hs : measurable_set s) :
∫ a in s, (L.comp_Lp φ) a ∂μ = ∫ a in s, L (φ a) ∂μ :=
set_integral_congr_ae hs ((L.coe_fn_comp_Lp φ).mono (λ x hx hx2, hx))
lemma continuous_integral_comp_L1 (L : E →L[𝕜] F) :
continuous (λ (φ : α →₁[μ] E), ∫ (a : α), L (φ a) ∂μ) :=
by { rw ← funext L.integral_comp_Lp, exact continuous_integral.comp (L.comp_LpL 1 μ).continuous, }
variables [complete_space E] [normed_space ℝ E]
lemma integral_comp_comm (L : E →L[𝕜] F) {φ : α → E} (φ_int : integrable φ μ) :
∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) :=
begin
apply integrable.induction (λ φ, ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ)),
{ intros e s s_meas s_finite,
rw [integral_indicator_const e s_meas, ← @smul_one_smul E ℝ 𝕜 _ _ _ _ _ (μ s).to_real e,
continuous_linear_map.map_smul, @smul_one_smul F ℝ 𝕜 _ _ _ _ _ (μ s).to_real (L e),
← integral_indicator_const (L e) s_meas],
congr' 1 with a,
rw set.indicator_comp_of_zero L.map_zero },
{ intros f g H f_int g_int hf hg,
simp [L.map_add, integral_add f_int g_int,
integral_add (L.integrable_comp f_int) (L.integrable_comp g_int), hf, hg] },
{ exact is_closed_eq L.continuous_integral_comp_L1 (L.continuous.comp continuous_integral) },
{ intros f g hfg f_int hf,
convert hf using 1 ; clear hf,
{ exact integral_congr_ae (hfg.fun_comp L).symm },
{ rw integral_congr_ae hfg.symm } },
all_goals { assumption }
end
lemma integral_apply {H : Type*} [normed_add_comm_group H] [normed_space 𝕜 H]
{φ : α → H →L[𝕜] E} (φ_int : integrable φ μ) (v : H) :
(∫ a, φ a ∂μ) v = ∫ a, φ a v ∂μ :=
((continuous_linear_map.apply 𝕜 E v).integral_comp_comm φ_int).symm
lemma integral_comp_comm' (L : E →L[𝕜] F) {K} (hL : antilipschitz_with K L) (φ : α → E) :
∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) :=
begin
by_cases h : integrable φ μ,
{ exact integral_comp_comm L h },
have : ¬ (integrable (L ∘ φ) μ),
by rwa lipschitz_with.integrable_comp_iff_of_antilipschitz L.lipschitz hL (L.map_zero),
simp [integral_undef, h, this]
end
lemma integral_comp_L1_comm (L : E →L[𝕜] F) (φ : α →₁[μ] E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) :=
L.integral_comp_comm (L1.integrable_coe_fn φ)
end continuous_linear_map
namespace linear_isometry
variables [complete_space F] [normed_space ℝ F] [complete_space E] [normed_space ℝ E]
lemma integral_comp_comm (L : E →ₗᵢ[𝕜] F) (φ : α → E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) :=
L.to_continuous_linear_map.integral_comp_comm' L.antilipschitz _
end linear_isometry
namespace continuous_linear_equiv
variables [complete_space F] [normed_space ℝ F] [complete_space E] [normed_space ℝ E]
lemma integral_comp_comm (L : E ≃L[𝕜] F) (φ : α → E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) :=
L.to_continuous_linear_map.integral_comp_comm' L.antilipschitz _
end continuous_linear_equiv
variables [complete_space E] [normed_space ℝ E] [complete_space F] [normed_space ℝ F]
@[norm_cast] lemma integral_of_real {f : α → ℝ} : ∫ a, (f a : 𝕜) ∂μ = ↑∫ a, f a ∂μ :=
(@is_R_or_C.of_real_li 𝕜 _).integral_comp_comm f
lemma integral_re {f : α → 𝕜} (hf : integrable f μ) :
∫ a, is_R_or_C.re (f a) ∂μ = is_R_or_C.re ∫ a, f a ∂μ :=
(@is_R_or_C.re_clm 𝕜 _).integral_comp_comm hf
lemma integral_im {f : α → 𝕜} (hf : integrable f μ) :
∫ a, is_R_or_C.im (f a) ∂μ = is_R_or_C.im ∫ a, f a ∂μ :=
(@is_R_or_C.im_clm 𝕜 _).integral_comp_comm hf
lemma integral_conj {f : α → 𝕜} : ∫ a, conj (f a) ∂μ = conj ∫ a, f a ∂μ :=
(@is_R_or_C.conj_lie 𝕜 _).to_linear_isometry.integral_comp_comm f
lemma integral_coe_re_add_coe_im {f : α → 𝕜} (hf : integrable f μ) :
∫ x, (is_R_or_C.re (f x) : 𝕜) ∂μ + ∫ x, is_R_or_C.im (f x) ∂μ * is_R_or_C.I = ∫ x, f x ∂μ :=
begin
rw [mul_comm, ← smul_eq_mul, ← integral_smul, ← integral_add],
{ congr,
ext1 x,
rw [smul_eq_mul, mul_comm, is_R_or_C.re_add_im] },
{ exact hf.re.of_real },
{ exact hf.im.of_real.smul is_R_or_C.I }
end
lemma integral_re_add_im {f : α → 𝕜} (hf : integrable f μ) :
((∫ x, is_R_or_C.re (f x) ∂μ : ℝ) : 𝕜) + (∫ x, is_R_or_C.im (f x) ∂μ : ℝ) * is_R_or_C.I =
∫ x, f x ∂μ :=
by { rw [← integral_of_real, ← integral_of_real, integral_coe_re_add_coe_im hf] }
lemma set_integral_re_add_im {f : α → 𝕜} {i : set α} (hf : integrable_on f i μ) :
((∫ x in i, is_R_or_C.re (f x) ∂μ : ℝ) : 𝕜) +
(∫ x in i, is_R_or_C.im (f x) ∂μ : ℝ) * is_R_or_C.I = ∫ x in i, f x ∂μ :=
integral_re_add_im hf
lemma fst_integral {f : α → E × F} (hf : integrable f μ) :
(∫ x, f x ∂μ).1 = ∫ x, (f x).1 ∂μ :=
((continuous_linear_map.fst ℝ E F).integral_comp_comm hf).symm
lemma snd_integral {f : α → E × F} (hf : integrable f μ) :
(∫ x, f x ∂μ).2 = ∫ x, (f x).2 ∂μ :=
((continuous_linear_map.snd ℝ E F).integral_comp_comm hf).symm
lemma integral_pair {f : α → E} {g : α → F} (hf : integrable f μ) (hg : integrable g μ) :
∫ x, (f x, g x) ∂μ = (∫ x, f x ∂μ, ∫ x, g x ∂μ) :=
have _ := hf.prod_mk hg, prod.ext (fst_integral this) (snd_integral this)
lemma integral_smul_const {𝕜 : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] (f : α → 𝕜) (c : E) :
∫ x, f x • c ∂μ = (∫ x, f x ∂μ) • c :=
begin
by_cases hf : integrable f μ,
{ exact ((1 : 𝕜 →L[𝕜] 𝕜).smul_right c).integral_comp_comm hf },
{ by_cases hc : c = 0,
{ simp only [hc, integral_zero, smul_zero] },
rw [integral_undef hf, integral_undef, zero_smul],
simp_rw [integrable_smul_const hc, hf, not_false_iff] }
end
lemma integral_with_density_eq_integral_smul
{f : α → ℝ≥0} (f_meas : measurable f) (g : α → E) :
∫ a, g a ∂(μ.with_density (λ x, f x)) = ∫ a, f a • g a ∂μ :=
begin
by_cases hg : integrable g (μ.with_density (λ x, f x)), swap,
{ rw [integral_undef hg, integral_undef],
rwa [← integrable_with_density_iff_integrable_smul f_meas];
apply_instance },
refine integrable.induction _ _ _ _ _ hg,
{ assume c s s_meas hs,
rw integral_indicator s_meas,
simp_rw [← indicator_smul_apply, integral_indicator s_meas],
simp only [s_meas, integral_const, measure.restrict_apply', univ_inter, with_density_apply],
rw [lintegral_coe_eq_integral, ennreal.to_real_of_real, ← integral_smul_const],
{ refl },
{ exact integral_nonneg (λ x, nnreal.coe_nonneg _) },
{ refine ⟨(f_meas.coe_nnreal_real).ae_measurable.ae_strongly_measurable, _⟩,
rw with_density_apply _ s_meas at hs,
rw has_finite_integral,
convert hs,
ext1 x,
simp only [nnreal.nnnorm_eq] } },
{ assume u u' h_disj u_int u'_int h h',
change ∫ (a : α), (u a + u' a) ∂μ.with_density (λ (x : α), ↑(f x)) =
∫ (a : α), f a • (u a + u' a) ∂μ,
simp_rw [smul_add],
rw [integral_add u_int u'_int, h, h', integral_add],
{ exact (integrable_with_density_iff_integrable_smul f_meas).1 u_int },
{ exact (integrable_with_density_iff_integrable_smul f_meas).1 u'_int } },
{ have C1 : continuous (λ (u : Lp E 1 (μ.with_density (λ x, f x))),
∫ x, u x ∂(μ.with_density (λ x, f x))) := continuous_integral,
have C2 : continuous (λ (u : Lp E 1 (μ.with_density (λ x, f x))),
∫ x, f x • u x ∂μ),
{ have : continuous ((λ (u : Lp E 1 μ), ∫ x, u x ∂μ) ∘ (with_density_smul_li μ f_meas)) :=
continuous_integral.comp (with_density_smul_li μ f_meas).continuous,
convert this,
ext1 u,
simp only [function.comp_app, with_density_smul_li_apply],
exact integral_congr_ae (mem_ℒ1_smul_of_L1_with_density f_meas u).coe_fn_to_Lp.symm },
exact is_closed_eq C1 C2 },
{ assume u v huv u_int hu,
rw [← integral_congr_ae huv, hu],
apply integral_congr_ae,
filter_upwards [(ae_with_density_iff f_meas.coe_nnreal_ennreal).1 huv] with x hx,
rcases eq_or_ne (f x) 0 with h'x|h'x,
{ simp only [h'x, zero_smul]},
{ rw [hx _],
simpa only [ne.def, ennreal.coe_eq_zero] using h'x } }
end
lemma integral_with_density_eq_integral_smul₀
{f : α → ℝ≥0} (hf : ae_measurable f μ) (g : α → E) :
∫ a, g a ∂(μ.with_density (λ x, f x)) = ∫ a, f a • g a ∂μ :=
begin
let f' := hf.mk _,
calc ∫ a, g a ∂(μ.with_density (λ x, f x))
= ∫ a, g a ∂(μ.with_density (λ x, f' x)) :
begin
congr' 1,
apply with_density_congr_ae,
filter_upwards [hf.ae_eq_mk] with x hx,
rw hx,
end
... = ∫ a, f' a • g a ∂μ : integral_with_density_eq_integral_smul hf.measurable_mk _
... = ∫ a, f a • g a ∂μ :
begin
apply integral_congr_ae,
filter_upwards [hf.ae_eq_mk] with x hx,
rw hx,
end
end
lemma set_integral_with_density_eq_set_integral_smul
{f : α → ℝ≥0} (f_meas : measurable f) (g : α → E) {s : set α} (hs : measurable_set s) :
∫ a in s, g a ∂(μ.with_density (λ x, f x)) = ∫ a in s, f a • g a ∂μ :=
by rw [restrict_with_density hs, integral_with_density_eq_integral_smul f_meas]
lemma set_integral_with_density_eq_set_integral_smul₀ {f : α → ℝ≥0} {s : set α}
(hf : ae_measurable f (μ.restrict s)) (g : α → E) (hs : measurable_set s) :
∫ a in s, g a ∂(μ.with_density (λ x, f x)) = ∫ a in s, f a • g a ∂μ :=
by rw [restrict_with_density hs, integral_with_density_eq_integral_smul₀ hf]
end
section thickened_indicator
variables [pseudo_emetric_space α]
lemma measure_le_lintegral_thickened_indicator_aux
(μ : measure α) {E : set α} (E_mble : measurable_set E) (δ : ℝ) :
μ E ≤ ∫⁻ a, (thickened_indicator_aux δ E a : ℝ≥0∞) ∂μ :=
begin
convert_to lintegral μ (E.indicator (λ _, (1 : ℝ≥0∞)))
≤ lintegral μ (thickened_indicator_aux δ E),
{ rw [lintegral_indicator _ E_mble],
simp only [lintegral_one, measure.restrict_apply, measurable_set.univ, univ_inter], },
{ apply lintegral_mono,
apply indicator_le_thickened_indicator_aux, },
end
lemma measure_le_lintegral_thickened_indicator
(μ : measure α) {E : set α} (E_mble : measurable_set E) {δ : ℝ} (δ_pos : 0 < δ) :
μ E ≤ ∫⁻ a, (thickened_indicator δ_pos E a : ℝ≥0∞) ∂μ :=
begin
convert measure_le_lintegral_thickened_indicator_aux μ E_mble δ,
dsimp,
simp only [thickened_indicator_aux_lt_top.ne, ennreal.coe_to_nnreal, ne.def, not_false_iff],
end
end thickened_indicator
section bilinear_map
namespace measure_theory
variables {f : β → ℝ} {m m0 : measurable_space β} {μ : measure β}
lemma integrable.simple_func_mul (g : simple_func β ℝ) (hf : integrable f μ) :
integrable (g * f) μ :=
begin
refine simple_func.induction (λ c s hs, _) (λ g₁ g₂ h_disj h_int₁ h_int₂,
(h_int₁.add h_int₂).congr (by rw [simple_func.coe_add, add_mul])) g,
simp only [simple_func.const_zero, simple_func.coe_piecewise, simple_func.coe_const,
simple_func.coe_zero, set.piecewise_eq_indicator],
have : set.indicator s (function.const β c) * f = s.indicator (c • f),
{ ext1 x,
by_cases hx : x ∈ s,
{ simp only [hx, pi.mul_apply, set.indicator_of_mem, pi.smul_apply, algebra.id.smul_eq_mul] },
{ simp only [hx, pi.mul_apply, set.indicator_of_not_mem, not_false_iff, zero_mul], }, },
rw [this, integrable_indicator_iff hs],
exact (hf.smul c).integrable_on,
end
lemma integrable.simple_func_mul' (hm : m ≤ m0) (g : @simple_func β m ℝ) (hf : integrable f μ) :
integrable (g * f) μ :=
by { rw ← simple_func.coe_to_larger_space_eq hm g, exact hf.simple_func_mul (g.to_larger_space hm) }
end measure_theory
end bilinear_map
|
f61b5f4b84c43d8482d7dd61713b0a2d782ca06b | 6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf | /src/game/world10/level17.lean | 7966ea0642833980df998889bea25a65b021c3ec | [
"Apache-2.0"
] | permissive | arolihas/natural_number_game | 4f0c93feefec93b8824b2b96adff8b702b8b43ce | 8e4f7b4b42888a3b77429f90cce16292bd288138 | refs/heads/master | 1,621,872,426,808 | 1,586,270,467,000 | 1,586,270,467,000 | 253,648,466 | 0 | 0 | null | 1,586,219,694,000 | 1,586,219,694,000 | null | UTF-8 | Lean | false | false | 1,336 | lean | import game.world10.level16 -- hide
namespace mynat -- hide
/-
# Inequality world.
## Level 17: definition of `<`
OK so we are going to *define* `a < b` by `a ≤ b ∧ ¬ (b ≤ a)`,
and given `lt_aux_one a b` and `lt_aux_two a b` it should now just
be a few lines to prove `a < b ↔ succ(a) ≤ b`.
-/
definition lt (a b : mynat) := a ≤ b ∧ ¬ (b ≤ a)
-- incantation so that we can use `<` notation:
instance : has_lt mynat := ⟨lt⟩
/- Lemma :
For all naturals $a$ and $b$,
$$a<b\iff\operatorname{succ}(a)\le b.$$
-/
lemma lt_iff_succ_le (a b : mynat) : a < b ↔ succ a ≤ b :=
begin [nat_num_game]
end
/-
For now -- that's it. In the next version of the natural number game we will go on and make
the natural numbers into an `ordered_cancel_comm_monoid`, which is the most
exotic of all the structures defined on the natural numbers in Lean 3.4.2.
Interested in playing levels involving other kinds of mathematics?
Look <a href="https://github.com/ImperialCollegeLondon/natural_number_game/blob/master/WHATS_NEXT.md"
target="blank">here</a> for more ideas about what to do next.
Interested in learning more? Join us on the
<a href="https://leanprover.zulipchat.com/" target="blank">Zulip Lean chat</a>
and ask questions in the `#new members` stream. Real names preferred. Be nice.
-/
end mynat -- hide
|
12f6acf73a8516f99cebf04b8f6e414b6d84bcfe | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/category_theory/limits/exact_functor.lean | 3446a771c886d371d976148146b46820e0439131 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 5,628 | lean | /-
Copyright (c) 2022 Markus Himmel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Markus Himmel
-/
import category_theory.limits.preserves.finite
/-!
# Bundled exact functors
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We say that a functor `F` is left exact if it preserves finite limits, it is right exact if it
preserves finite colimits, and it is exact if it is both left exact and right exact.
In this file, we define the categories of bundled left exact, right exact and exact functors.
-/
universes v₁ v₂ u₁ u₂
open category_theory.limits
namespace category_theory
variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D]
section
variables (C) (D)
/-- Bundled left-exact functors. -/
@[derive category, nolint has_nonempty_instance]
def LeftExactFunctor :=
full_subcategory (λ F : C ⥤ D, nonempty (preserves_finite_limits F))
infixr ` ⥤ₗ `:26 := LeftExactFunctor
/-- A left exact functor is in particular a functor. -/
@[derive full, derive faithful]
def LeftExactFunctor.forget : (C ⥤ₗ D) ⥤ (C ⥤ D) :=
full_subcategory_inclusion _
/-- Bundled right-exact functors. -/
@[derive category, nolint has_nonempty_instance]
def RightExactFunctor :=
full_subcategory (λ F : C ⥤ D, nonempty (preserves_finite_colimits F))
infixr ` ⥤ᵣ `:26 := RightExactFunctor
/-- A right exact functor is in particular a functor. -/
@[derive full, derive faithful]
def RightExactFunctor.forget : (C ⥤ᵣ D) ⥤ (C ⥤ D) :=
full_subcategory_inclusion _
/-- Bundled exact functors. -/
@[derive category, nolint has_nonempty_instance]
def ExactFunctor := full_subcategory
(λ F : C ⥤ D, nonempty (preserves_finite_limits F) ∧ nonempty (preserves_finite_colimits F))
infixr ` ⥤ₑ `:26 := ExactFunctor
/-- An exact functor is in particular a functor. -/
@[derive full, derive faithful]
def ExactFunctor.forget : (C ⥤ₑ D) ⥤ (C ⥤ D) :=
full_subcategory_inclusion _
/-- Turn an exact functor into a left exact functor. -/
@[derive full, derive faithful]
def LeftExactFunctor.of_exact : (C ⥤ₑ D) ⥤ (C ⥤ₗ D) :=
full_subcategory.map (λ X, and.left)
/-- Turn an exact functor into a left exact functor. -/
@[derive full, derive faithful]
def RightExactFunctor.of_exact : (C ⥤ₑ D) ⥤ (C ⥤ᵣ D) :=
full_subcategory.map (λ X, and.right)
variables {C D}
@[simp] lemma LeftExactFunctor.of_exact_obj (F : C ⥤ₑ D) :
(LeftExactFunctor.of_exact C D).obj F = ⟨F.1, F.2.1⟩ := rfl
@[simp] lemma RightExactFunctor.of_exact_obj (F : C ⥤ₑ D) :
(RightExactFunctor.of_exact C D).obj F = ⟨F.1, F.2.2⟩ := rfl
@[simp] lemma LeftExactFunctor.of_exact_map {F G : C ⥤ₑ D} (α : F ⟶ G) :
(LeftExactFunctor.of_exact C D).map α = α := rfl
@[simp] lemma RightExactFunctor.of_exact_map {F G : C ⥤ₑ D} (α : F ⟶ G) :
(RightExactFunctor.of_exact C D).map α = α := rfl
@[simp] lemma LeftExactFunctor.forget_obj (F : C ⥤ₗ D) :
(LeftExactFunctor.forget C D).obj F = F.1 := rfl
@[simp] lemma RightExactFunctor.forget_obj (F : C ⥤ᵣ D) :
(RightExactFunctor.forget C D).obj F = F.1 := rfl
@[simp] lemma ExactFunctor.forget_obj (F : C ⥤ₑ D) :
(ExactFunctor.forget C D).obj F = F.1 := rfl
@[simp] lemma LeftExactFunctor.forget_map {F G : C ⥤ₗ D} (α : F ⟶ G) :
(LeftExactFunctor.forget C D).map α = α := rfl
@[simp] lemma RightExactFunctor.forget_map {F G : C ⥤ᵣ D} (α : F ⟶ G) :
(RightExactFunctor.forget C D).map α = α := rfl
@[simp] lemma ExactFunctor.forget_map {F G : C ⥤ₑ D} (α : F ⟶ G) :
(ExactFunctor.forget C D).map α = α := rfl
/-- Turn a left exact functor into an object of the category `LeftExactFunctor C D`. -/
def LeftExactFunctor.of (F : C ⥤ D) [preserves_finite_limits F] : C ⥤ₗ D := ⟨F, ⟨infer_instance⟩⟩
/-- Turn a right exact functor into an object of the category `RightExactFunctor C D`. -/
def RightExactFunctor.of (F : C ⥤ D) [preserves_finite_colimits F] : C ⥤ᵣ D :=
⟨F, ⟨infer_instance⟩⟩
/-- Turn an exact functor into an object of the category `ExactFunctor C D`. -/
def ExactFunctor.of (F : C ⥤ D) [preserves_finite_limits F] [preserves_finite_colimits F] :
C ⥤ₑ D := ⟨F, ⟨⟨infer_instance⟩, ⟨infer_instance⟩⟩⟩
@[simp] lemma LeftExactFunctor.of_fst (F : C ⥤ D) [preserves_finite_limits F] :
(LeftExactFunctor.of F).obj = F := rfl
@[simp] lemma RightExactFunctor.of_fst (F : C ⥤ D) [preserves_finite_colimits F] :
(RightExactFunctor.of F).obj = F := rfl
@[simp] lemma ExactFunctor.of_fst (F : C ⥤ D) [preserves_finite_limits F]
[preserves_finite_colimits F] : (ExactFunctor.of F).obj = F := rfl
lemma LeftExactFunctor.forget_obj_of (F : C ⥤ D) [preserves_finite_limits F] :
(LeftExactFunctor.forget C D).obj (LeftExactFunctor.of F) = F := rfl
lemma RightExactFunctor.forget_obj_of (F : C ⥤ D) [preserves_finite_colimits F] :
(RightExactFunctor.forget C D).obj (RightExactFunctor.of F) = F := rfl
lemma ExactFunctor.forget_obj_of (F : C ⥤ D) [preserves_finite_limits F]
[preserves_finite_colimits F] : (ExactFunctor.forget C D).obj (ExactFunctor.of F) = F := rfl
noncomputable instance (F : C ⥤ₗ D) : preserves_finite_limits F.obj := F.property.some
noncomputable instance (F : C ⥤ᵣ D) : preserves_finite_colimits F.obj := F.property.some
noncomputable instance (F : C ⥤ₑ D) : preserves_finite_limits F.obj := F.property.1.some
noncomputable instance (F : C ⥤ₑ D) : preserves_finite_colimits F.obj := F.property.2.some
end
end category_theory
|
45e11aaf8155a142ab021b7d80d7ecf09986dc14 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/complex/re_im_topology.lean | 08072675acf4994844cf470841e4d1e0db484933 | [
"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 | 7,969 | 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 analysis.complex.basic
import topology.fiber_bundle
/-!
# Closure, interior, and frontier of preimages under `re` and `im`
In this fact we use the fact that `ℂ` is naturally homeomorphic to `ℝ × ℝ` to deduce some
topological properties of `complex.re` and `complex.im`.
## Main statements
Each statement about `complex.re` listed below has a counterpart about `complex.im`.
* `complex.is_trivial_topological_fiber_bundle_re`: `complex.re` turns `ℂ` into a trivial
topological fiber bundle over `ℝ`;
* `complex.is_open_map_re`, `complex.quotient_map_re`: in particular, `complex.re` is an open map
and is a quotient map;
* `complex.interior_preimage_re`, `complex.closure_preimage_re`, `complex.frontier_preimage_re`:
formulas for `interior (complex.re ⁻¹' s)` etc;
* `complex.interior_set_of_re_le` etc: particular cases of the above formulas in the cases when `s`
is one of the infinite intervals `set.Ioi a`, `set.Ici a`, `set.Iio a`, and `set.Iic a`,
formulated as `interior {z : ℂ | z.re ≤ a} = {z | z.re < a}` etc.
## Tags
complex, real part, imaginary part, closure, interior, frontier
-/
open topological_fiber_bundle set
noncomputable theory
namespace complex
/-- `complex.re` turns `ℂ` into a trivial topological fiber bundle over `ℝ`. -/
lemma is_trivial_topological_fiber_bundle_re : is_trivial_topological_fiber_bundle ℝ re :=
⟨equiv_real_prodₗ.to_homeomorph, λ z, rfl⟩
/-- `complex.im` turns `ℂ` into a trivial topological fiber bundle over `ℝ`. -/
lemma is_trivial_topological_fiber_bundle_im : is_trivial_topological_fiber_bundle ℝ im :=
⟨equiv_real_prodₗ.to_homeomorph.trans (homeomorph.prod_comm ℝ ℝ), λ z, rfl⟩
lemma is_topological_fiber_bundle_re : is_topological_fiber_bundle ℝ re :=
is_trivial_topological_fiber_bundle_re.is_topological_fiber_bundle
lemma is_topological_fiber_bundle_im : is_topological_fiber_bundle ℝ im :=
is_trivial_topological_fiber_bundle_im.is_topological_fiber_bundle
lemma is_open_map_re : is_open_map re := is_topological_fiber_bundle_re.is_open_map_proj
lemma is_open_map_im : is_open_map im := is_topological_fiber_bundle_im.is_open_map_proj
lemma quotient_map_re : quotient_map re := is_topological_fiber_bundle_re.quotient_map_proj
lemma quotient_map_im : quotient_map im := is_topological_fiber_bundle_im.quotient_map_proj
lemma interior_preimage_re (s : set ℝ) : interior (re ⁻¹' s) = re ⁻¹' (interior s) :=
(is_open_map_re.preimage_interior_eq_interior_preimage continuous_re _).symm
lemma interior_preimage_im (s : set ℝ) : interior (im ⁻¹' s) = im ⁻¹' (interior s) :=
(is_open_map_im.preimage_interior_eq_interior_preimage continuous_im _).symm
lemma closure_preimage_re (s : set ℝ) : closure (re ⁻¹' s) = re ⁻¹' (closure s) :=
(is_open_map_re.preimage_closure_eq_closure_preimage continuous_re _).symm
lemma closure_preimage_im (s : set ℝ) : closure (im ⁻¹' s) = im ⁻¹' (closure s) :=
(is_open_map_im.preimage_closure_eq_closure_preimage continuous_im _).symm
lemma frontier_preimage_re (s : set ℝ) : frontier (re ⁻¹' s) = re ⁻¹' (frontier s) :=
(is_open_map_re.preimage_frontier_eq_frontier_preimage continuous_re _).symm
lemma frontier_preimage_im (s : set ℝ) : frontier (im ⁻¹' s) = im ⁻¹' (frontier s) :=
(is_open_map_im.preimage_frontier_eq_frontier_preimage continuous_im _).symm
@[simp] lemma interior_set_of_re_le (a : ℝ) : interior {z : ℂ | z.re ≤ a} = {z | z.re < a} :=
by simpa only [interior_Iic] using interior_preimage_re (Iic a)
@[simp] lemma interior_set_of_im_le (a : ℝ) : interior {z : ℂ | z.im ≤ a} = {z | z.im < a} :=
by simpa only [interior_Iic] using interior_preimage_im (Iic a)
@[simp] lemma interior_set_of_le_re (a : ℝ) : interior {z : ℂ | a ≤ z.re} = {z | a < z.re} :=
by simpa only [interior_Ici] using interior_preimage_re (Ici a)
@[simp] lemma interior_set_of_le_im (a : ℝ) : interior {z : ℂ | a ≤ z.im} = {z | a < z.im} :=
by simpa only [interior_Ici] using interior_preimage_im (Ici a)
@[simp] lemma closure_set_of_re_lt (a : ℝ) : closure {z : ℂ | z.re < a} = {z | z.re ≤ a} :=
by simpa only [closure_Iio] using closure_preimage_re (Iio a)
@[simp] lemma closure_set_of_im_lt (a : ℝ) : closure {z : ℂ | z.im < a} = {z | z.im ≤ a} :=
by simpa only [closure_Iio] using closure_preimage_im (Iio a)
@[simp] lemma closure_set_of_lt_re (a : ℝ) : closure {z : ℂ | a < z.re} = {z | a ≤ z.re} :=
by simpa only [closure_Ioi] using closure_preimage_re (Ioi a)
@[simp] lemma closure_set_of_lt_im (a : ℝ) : closure {z : ℂ | a < z.im} = {z | a ≤ z.im} :=
by simpa only [closure_Ioi] using closure_preimage_im (Ioi a)
@[simp] lemma frontier_set_of_re_le (a : ℝ) : frontier {z : ℂ | z.re ≤ a} = {z | z.re = a} :=
by simpa only [frontier_Iic] using frontier_preimage_re (Iic a)
@[simp] lemma frontier_set_of_im_le (a : ℝ) : frontier {z : ℂ | z.im ≤ a} = {z | z.im = a} :=
by simpa only [frontier_Iic] using frontier_preimage_im (Iic a)
@[simp] lemma frontier_set_of_le_re (a : ℝ) : frontier {z : ℂ | a ≤ z.re} = {z | z.re = a} :=
by simpa only [frontier_Ici] using frontier_preimage_re (Ici a)
@[simp] lemma frontier_set_of_le_im (a : ℝ) : frontier {z : ℂ | a ≤ z.im} = {z | z.im = a} :=
by simpa only [frontier_Ici] using frontier_preimage_im (Ici a)
@[simp] lemma frontier_set_of_re_lt (a : ℝ) : frontier {z : ℂ | z.re < a} = {z | z.re = a} :=
by simpa only [frontier_Iio] using frontier_preimage_re (Iio a)
@[simp] lemma frontier_set_of_im_lt (a : ℝ) : frontier {z : ℂ | z.im < a} = {z | z.im = a} :=
by simpa only [frontier_Iio] using frontier_preimage_im (Iio a)
@[simp] lemma frontier_set_of_lt_re (a : ℝ) : frontier {z : ℂ | a < z.re} = {z | z.re = a} :=
by simpa only [frontier_Ioi] using frontier_preimage_re (Ioi a)
@[simp] lemma frontier_set_of_lt_im (a : ℝ) : frontier {z : ℂ | a < z.im} = {z | z.im = a} :=
by simpa only [frontier_Ioi] using frontier_preimage_im (Ioi a)
lemma closure_re_prod_im (s t : set ℝ) : closure (s ×ℂ t) = closure s ×ℂ closure t :=
by simpa only [← preimage_eq_preimage equiv_real_prodₗ.symm.to_homeomorph.surjective,
equiv_real_prodₗ.symm.to_homeomorph.preimage_closure]
using @closure_prod_eq _ _ _ _ s t
lemma interior_re_prod_im (s t : set ℝ) : interior (s ×ℂ t) = interior s ×ℂ interior t :=
by rw [re_prod_im, re_prod_im, interior_inter, interior_preimage_re, interior_preimage_im]
lemma frontier_re_prod_im (s t : set ℝ) :
frontier (s ×ℂ t) = (closure s ×ℂ frontier t) ∪ (frontier s ×ℂ closure t) :=
by simpa only [← preimage_eq_preimage equiv_real_prodₗ.symm.to_homeomorph.surjective,
equiv_real_prodₗ.symm.to_homeomorph.preimage_frontier]
using frontier_prod_eq s t
lemma frontier_set_of_le_re_and_le_im (a b : ℝ) :
frontier {z | a ≤ re z ∧ b ≤ im z} = {z | a ≤ re z ∧ im z = b ∨ re z = a ∧ b ≤ im z} :=
by simpa only [closure_Ici, frontier_Ici] using frontier_re_prod_im (Ici a) (Ici b)
lemma frontier_set_of_le_re_and_im_le (a b : ℝ) :
frontier {z | a ≤ re z ∧ im z ≤ b} = {z | a ≤ re z ∧ im z = b ∨ re z = a ∧ im z ≤ b} :=
by simpa only [closure_Ici, closure_Iic, frontier_Ici, frontier_Iic]
using frontier_re_prod_im (Ici a) (Iic b)
end complex
open complex metric
variables {s t : set ℝ}
lemma is_open.re_prod_im (hs : is_open s) (ht : is_open t) : is_open (s ×ℂ t) :=
(hs.preimage continuous_re).inter (ht.preimage continuous_im)
lemma is_closed.re_prod_im (hs : is_closed s) (ht : is_closed t) : is_closed (s ×ℂ t) :=
(hs.preimage continuous_re).inter (ht.preimage continuous_im)
lemma metric.bounded.re_prod_im (hs : bounded s) (ht : bounded t) : bounded (s ×ℂ t) :=
equiv_real_prodₗ.antilipschitz.bounded_preimage (hs.prod ht)
|
f6bfe93de7e32dfd4e34c424990045170606d5d3 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/control/functor/multivariate.lean | 9274109ee08a8c237d3f302c766108f0fae28636 | [
"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 | 6,718 | lean | /-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Mario Carneiro, Simon Hudon
-/
import data.fin.fin2
import data.typevec
import logic.function.basic
import tactic.basic
/-!
Functors between the category of tuples of types, and the category Type
Features:
`mvfunctor n` : the type class of multivariate functors
`f <$$> x` : notation for map
-/
universes u v w
open_locale mvfunctor
/-- multivariate functors, i.e. functor between the category of type vectors
and the category of Type -/
class mvfunctor {n : ℕ} (F : typevec n → Type*) :=
(map : Π {α β : typevec n}, (α ⟹ β) → (F α → F β))
localized "infixr ` <$$> `:100 := mvfunctor.map" in mvfunctor
variables {n : ℕ}
namespace mvfunctor
variables {α β γ : typevec.{u} n} {F : typevec.{u} n → Type v} [mvfunctor F]
/-- predicate lifting over multivariate functors -/
def liftp {α : typevec n} (p : Π i, α i → Prop) (x : F α) : Prop :=
∃ u : F (λ i, subtype (p i)), (λ i, @subtype.val _ (p i)) <$$> u = x
/-- relational lifting over multivariate functors -/
def liftr {α : typevec n} (r : Π {i}, α i → α i → Prop) (x y : F α) : Prop :=
∃ u : F (λ i, {p : α i × α i // r p.fst p.snd}),
(λ i (t : {p : α i × α i // r p.fst p.snd}), t.val.fst) <$$> u = x ∧
(λ i (t : {p : α i × α i // r p.fst p.snd}), t.val.snd) <$$> u = y
/-- given `x : F α` and a projection `i` of type vector `α`, `supp x i` is the set
of `α.i` contained in `x` -/
def supp {α : typevec n} (x : F α) (i : fin2 n) : set (α i) :=
{ y : α i | ∀ ⦃p⦄, liftp p x → p i y }
theorem of_mem_supp {α : typevec n} {x : F α} {p : Π ⦃i⦄, α i → Prop} (h : liftp p x) (i : fin2 n):
∀ y ∈ supp x i, p y :=
λ y hy, hy h
end mvfunctor
/-- laws for `mvfunctor` -/
class is_lawful_mvfunctor {n : ℕ} (F : typevec n → Type*) [mvfunctor F] : Prop :=
(id_map : ∀ {α : typevec n} (x : F α), typevec.id <$$> x = x)
(comp_map : ∀ {α β γ : typevec n} (g : α ⟹ β) (h : β ⟹ γ) (x : F α),
(h ⊚ g) <$$> x = h <$$> g <$$> x)
open nat typevec
namespace mvfunctor
export is_lawful_mvfunctor (comp_map)
open is_lawful_mvfunctor
variables {α β γ : typevec.{u} n}
variables {F : typevec.{u} n → Type v} [mvfunctor F]
variables (p : α ⟹ repeat n Prop) (r : α ⊗ α ⟹ repeat n Prop)
/-- adapt `mvfunctor.liftp` to accept predicates as arrows -/
def liftp' : F α → Prop :=
mvfunctor.liftp $ λ i x, of_repeat $ p i x
/-- adapt `mvfunctor.liftp` to accept relations as arrows -/
def liftr' : F α → F α → Prop :=
mvfunctor.liftr $ λ i x y, of_repeat $ r i $ typevec.prod.mk _ x y
variables [is_lawful_mvfunctor F]
@[simp]
lemma id_map (x : F α) :
typevec.id <$$> x = x :=
id_map x
@[simp]
lemma id_map' (x : F α) :
(λ i a, a) <$$> x = x :=
id_map x
lemma map_map (g : α ⟹ β) (h : β ⟹ γ) (x : F α) :
h <$$> g <$$> x = (h ⊚ g) <$$> x :=
eq.symm $ comp_map _ _ _
section liftp'
variables (F)
lemma exists_iff_exists_of_mono {p : F α → Prop} {q : F β → Prop} (f : α ⟹ β) (g : β ⟹ α)
(h₀ : f ⊚ g = id)
(h₁ : ∀ u : F α, p u ↔ q (f <$$> u)) :
(∃ u : F α, p u) ↔ (∃ u : F β, q u) :=
begin
split; rintro ⟨u,h₂⟩; [ use f <$$> u, use g <$$> u ],
{ apply (h₁ u).mp h₂ },
{ apply (h₁ _).mpr _,
simp only [mvfunctor.map_map,h₀,is_lawful_mvfunctor.id_map,h₂] },
end
variables {F}
lemma liftp_def (x : F α) : liftp' p x ↔ ∃ u : F (subtype_ p), subtype_val p <$$> u = x :=
exists_iff_exists_of_mono F _ _ (to_subtype_of_subtype p) (by simp [mvfunctor.map_map])
lemma liftr_def (x y : F α) :
liftr' r x y ↔
∃ u : F (subtype_ r), (typevec.prod.fst ⊚ subtype_val r) <$$> u = x ∧
(typevec.prod.snd ⊚ subtype_val r) <$$> u = y :=
exists_iff_exists_of_mono _ _ _ (to_subtype'_of_subtype' r)
(by simp only [map_map, comp_assoc, subtype_val_to_subtype']; simp [comp])
end liftp'
end mvfunctor
open nat
namespace mvfunctor
open typevec
section liftp_last_pred_iff
variables {F : typevec.{u} (n+1) → Type*} [mvfunctor F] [is_lawful_mvfunctor F]
{α : typevec.{u} n}
variables (p : α ⟹ repeat n Prop)
(r : α ⊗ α ⟹ repeat n Prop)
open mvfunctor
variables {β : Type u}
variables (pp : β → Prop)
private def f : Π (n α), (λ (i : fin2 (n + 1)), {p_1 // of_repeat (pred_last' α pp i p_1)}) ⟹
λ (i : fin2 (n + 1)), {p_1 : (α ::: β) i // pred_last α pp p_1}
| _ α (fin2.fs i) x := ⟨ x.val, cast (by simp only [pred_last]; erw const_iff_true) x.property ⟩
| _ α fin2.fz x := ⟨ x.val, x.property ⟩
private def g : Π (n α), (λ (i : fin2 (n + 1)), {p_1 : (α ::: β) i // pred_last α pp p_1}) ⟹
(λ (i : fin2 (n + 1)), {p_1 // of_repeat (pred_last' α pp i p_1)})
| _ α (fin2.fs i) x := ⟨ x.val, cast (by simp only [pred_last]; erw const_iff_true) x.property ⟩
| _ α fin2.fz x := ⟨ x.val, x.property ⟩
lemma liftp_last_pred_iff {β} (p : β → Prop) (x : F (α ::: β)) :
liftp' (pred_last' _ p) x ↔ liftp (pred_last _ p) x :=
begin
dsimp only [liftp,liftp'],
apply exists_iff_exists_of_mono F (f _ n α) (g _ n α),
{ clear x _inst_2 _inst_1 F, ext i ⟨x,_⟩, cases i; refl },
{ intros, rw [mvfunctor.map_map,(⊚)],
congr'; ext i ⟨x,_⟩; cases i; refl }
end
open function
variables (rr : β → β → Prop)
private def f :
Π (n α),
(λ (i : fin2 (n + 1)),
{p_1 : _ × _ // of_repeat (rel_last' α rr i (typevec.prod.mk _ p_1.fst p_1.snd))}) ⟹
λ (i : fin2 (n + 1)), {p_1 : (α ::: β) i × _ // rel_last α rr (p_1.fst) (p_1.snd)}
| _ α (fin2.fs i) x := ⟨ x.val, cast (by simp only [rel_last]; erw repeat_eq_iff_eq) x.property ⟩
| _ α fin2.fz x := ⟨ x.val, x.property ⟩
private def g :
Π (n α), (λ (i : fin2 (n + 1)), {p_1 : (α ::: β) i × _ // rel_last α rr (p_1.fst) (p_1.snd)}) ⟹
(λ (i : fin2 (n + 1)),
{p_1 : _ × _ // of_repeat (rel_last' α rr i (typevec.prod.mk _ p_1.1 p_1.2))})
| _ α (fin2.fs i) x := ⟨ x.val, cast (by simp only [rel_last]; erw repeat_eq_iff_eq) x.property ⟩
| _ α fin2.fz x := ⟨ x.val, x.property ⟩
lemma liftr_last_rel_iff (x y : F (α ::: β)) :
liftr' (rel_last' _ rr) x y ↔ liftr (rel_last _ rr) x y :=
begin
dsimp only [liftr,liftr'],
apply exists_iff_exists_of_mono F (f rr _ _) (g rr _ _),
{ clear x y _inst_2 _inst_1 F, ext i ⟨x,_⟩ : 2, cases i; refl, },
{ intros, rw [mvfunctor.map_map,mvfunctor.map_map,(⊚),(⊚)],
congr'; ext i ⟨x,_⟩; cases i; refl }
end
end liftp_last_pred_iff
end mvfunctor
|
3f61246463a573479b54b79ed437086b370747c6 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/data/equiv/local_equiv.lean | 5b5c7f74dbf497fb0a2a0b2fd9fc66927ebd139f | [
"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 | 24,819 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import data.equiv.basic
/-!
# Local equivalences
This files defines equivalences between subsets of given types.
An element `e` of `local_equiv α β` is made of two maps `e.to_fun` and `e.inv_fun` respectively
from α to β and from β to α (just like equivs), which are inverse to each other on the subsets
`e.source` and `e.target` of respectively α and β.
They are designed in particular to define charts on manifolds.
The main functionality is `e.trans f`, which composes the two local equivalences by restricting
the source and target to the maximal set where the composition makes sense.
As for equivs, we register a coercion to functions and use it in our simp normal form: we write
`e x` and `e.symm y` instead of `e.to_fun x` and `e.inv_fun y`.
## Main definitions
`equiv.to_local_equiv`: associating a local equiv to an equiv, with source = target = univ
`local_equiv.symm` : the inverse of a local equiv
`local_equiv.trans` : the composition of two local equivs
`local_equiv.refl` : the identity local equiv
`local_equiv.of_set` : the identity on a set `s`
`eq_on_source` : equivalence relation describing the "right" notion of equality for local
equivs (see below in implementation notes)
## Implementation notes
There are at least three possible implementations of local equivalences:
* equivs on subtypes
* pairs of functions taking values in `option α` and `option β`, equal to none where the local
equivalence is not defined
* pairs of functions defined everywhere, keeping the source and target as additional data
Each of these implementations has pros and cons.
* When dealing with subtypes, one still need to define additional API for composition and
restriction of domains. Checking that one always belongs to the right subtype makes things very
tedious, and leads quickly to DTT hell (as the subtype `u ∩ v` is not the "same" as `v ∩ u`, for
instance).
* With option-valued functions, the composition is very neat (it is just the usual composition, and
the domain is restricted automatically). These are implemented in `pequiv.lean`. For manifolds,
where one wants to discuss thoroughly the smoothness of the maps, this creates however a lot of
overhead as one would need to extend all classes of smoothness to option-valued maps.
* The local_equiv version as explained above is easier to use for manifolds. The drawback is that
there is extra useless data (the values of `to_fun` and `inv_fun` outside of `source` and `target`).
In particular, the equality notion between local equivs is not "the right one", i.e., coinciding
source and target and equality there. Moreover, there are no local equivs in this sense between
an empty type and a nonempty type. Since empty types are not that useful, and since one almost never
needs to talk about equal local equivs, this is not an issue in practice.
Still, we introduce an equivalence relation `eq_on_source` that captures this right notion of
equality, and show that many properties are invariant under this equivalence relation.
-/
mk_simp_attribute mfld_simps "The simpset `mfld_simps` records several simp lemmas that are
especially useful in manifolds. It is a subset of the whole set of simp lemmas, but it makes it
possible to have quicker proofs (when used with `squeeze_simp` or `simp only`) while retaining
readability.
The typical use case is the following, in a file on manifolds:
If `simp [foo, bar]` is slow, replace it with `squeeze_simp [foo, bar] with mfld_simps` and paste
its output. The list of lemmas should be reasonable (contrary to the output of
`squeeze_simp [foo, bar]` which might contain tens of lemmas), and the outcome should be quick
enough.
"
-- register in the simpset `mfld_simps` several lemmas that are often useful when dealing
-- with manifolds
attribute [mfld_simps] id.def function.comp.left_id set.mem_set_of_eq set.image_eq_empty
set.univ_inter set.preimage_univ set.prod_mk_mem_set_prod_eq and_true set.mem_univ
set.mem_image_of_mem true_and set.mem_inter_eq set.mem_preimage function.comp_app
set.inter_subset_left set.mem_prod set.range_id and_self set.mem_range_self
eq_self_iff_true forall_const forall_true_iff set.inter_univ set.preimage_id function.comp.right_id
not_false_iff and_imp set.prod_inter_prod set.univ_prod_univ true_or or_true prod.map_mk
set.preimage_inter heq_iff_eq equiv.sigma_equiv_prod_apply equiv.sigma_equiv_prod_symm_apply
subtype.coe_mk equiv.to_fun_as_coe equiv.inv_fun_as_coe
namespace tactic.interactive
/-- A very basic tactic to show that sets showing up in manifolds coincide or are included in
one another. -/
meta def mfld_set_tac : tactic unit := do
goal ← tactic.target,
match goal with
| `(%%e₁ = %%e₂) :=
`[ext my_y,
split;
{ assume h_my_y,
try { simp only [*, -h_my_y] with mfld_simps at h_my_y },
simp only [*] with mfld_simps }]
| `(%%e₁ ⊆ %%e₂) :=
`[assume my_y h_my_y,
try { simp only [*, -h_my_y] with mfld_simps at h_my_y },
simp only [*] with mfld_simps]
| _ := tactic.fail "goal should be an equality or an inclusion"
end
end tactic.interactive
open function set
variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*}
/-- Local equivalence between subsets `source` and `target` of α and β respectively. The (global)
maps `to_fun : α → β` and `inv_fun : β → α` map `source` to `target` and conversely, and are inverse
to each other there. The values of `to_fun` outside of `source` and of `inv_fun` outside of `target`
are irrelevant. -/
@[nolint has_inhabited_instance]
structure local_equiv (α : Type*) (β : Type*) :=
(to_fun : α → β)
(inv_fun : β → α)
(source : set α)
(target : set β)
(map_source' : ∀{x}, x ∈ source → to_fun x ∈ target)
(map_target' : ∀{x}, x ∈ target → inv_fun x ∈ source)
(left_inv' : ∀{x}, x ∈ source → inv_fun (to_fun x) = x)
(right_inv' : ∀{x}, x ∈ target → to_fun (inv_fun x) = x)
/-- Associating a local_equiv to an equiv-/
def equiv.to_local_equiv (e : equiv α β) : local_equiv α β :=
{ to_fun := e.to_fun,
inv_fun := e.inv_fun,
source := univ,
target := univ,
map_source' := λx hx, mem_univ _,
map_target' := λy hy, mem_univ _,
left_inv' := λx hx, e.left_inv x,
right_inv' := λx hx, e.right_inv x }
namespace local_equiv
variables (e : local_equiv α β) (e' : local_equiv β γ)
/-- The inverse of a local equiv -/
protected def symm : local_equiv β α :=
{ to_fun := e.inv_fun,
inv_fun := e.to_fun,
source := e.target,
target := e.source,
map_source' := e.map_target',
map_target' := e.map_source',
left_inv' := e.right_inv',
right_inv' := e.left_inv' }
instance : has_coe_to_fun (local_equiv α β) := ⟨_, local_equiv.to_fun⟩
@[simp, mfld_simps] theorem coe_mk (f : α → β) (g s t ml mr il ir) :
(local_equiv.mk f g s t ml mr il ir : α → β) = f := rfl
@[simp, mfld_simps] theorem coe_symm_mk (f : α → β) (g s t ml mr il ir) :
((local_equiv.mk f g s t ml mr il ir).symm : β → α) = g := rfl
@[simp, mfld_simps] lemma to_fun_as_coe : e.to_fun = e := rfl
@[simp, mfld_simps] lemma inv_fun_as_coe : e.inv_fun = e.symm := rfl
@[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target :=
e.map_source' h
@[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source :=
e.map_target' h
@[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x :=
e.left_inv' h
@[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x :=
e.right_inv' h
protected lemma maps_to : maps_to e e.source e.target := λ x, e.map_source
lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to
protected lemma left_inv_on : left_inv_on e.symm e e.source := λ x, e.left_inv
protected lemma right_inv_on : right_inv_on e.symm e e.target := λ x, e.right_inv
protected lemma inv_on : inv_on e.symm e e.source e.target := ⟨e.left_inv_on, e.right_inv_on⟩
protected lemma inj_on : inj_on e e.source := e.left_inv_on.inj_on
protected lemma bij_on : bij_on e e.source e.target := e.inv_on.bij_on e.maps_to e.symm_maps_to
protected lemma surj_on : surj_on e e.source e.target := e.bij_on.surj_on
/-- Associating to a local_equiv an equiv between the source and the target -/
protected def to_equiv : equiv (e.source) (e.target) :=
{ to_fun := λ x, ⟨e x, e.map_source x.mem⟩,
inv_fun := λ y, ⟨e.symm y, e.map_target y.mem⟩,
left_inv := λ⟨x, hx⟩, subtype.eq $ e.left_inv hx,
right_inv := λ⟨y, hy⟩, subtype.eq $ e.right_inv hy }
@[simp, mfld_simps] lemma symm_source : e.symm.source = e.target := rfl
@[simp, mfld_simps] lemma symm_target : e.symm.target = e.source := rfl
@[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := by { cases e, refl }
lemma image_source_eq_target : e '' e.source = e.target := e.bij_on.image_eq
lemma image_inter_source_eq' (s : set α) :
e '' (s ∩ e.source) = e.target ∩ e.symm ⁻¹' s :=
by rw [e.left_inv_on.image_inter', image_source_eq_target, inter_comm]
lemma image_inter_source_eq (s : set α) :
e '' (s ∩ e.source) = e.target ∩ e.symm ⁻¹' (s ∩ e.source) :=
by rw [e.left_inv_on.image_inter, image_source_eq_target, inter_comm]
lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) :
e '' s = e.target ∩ e.symm ⁻¹' s :=
by rw [← e.image_inter_source_eq', inter_eq_self_of_subset_left h]
lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) :
e.symm '' s = e.source ∩ e ⁻¹' s :=
e.symm.image_eq_target_inter_inv_preimage h
lemma symm_image_inter_target_eq (s : set β) :
e.symm '' (s ∩ e.target) = e.source ∩ e ⁻¹' (s ∩ e.target) :=
e.symm.image_inter_source_eq _
lemma symm_image_inter_target_eq' (s : set β) :
e.symm '' (s ∩ e.target) = e.source ∩ e ⁻¹' s :=
e.symm.image_inter_source_eq' _
lemma source_inter_preimage_inv_preimage (s : set α) :
e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s :=
begin
ext x, split,
{ rintros ⟨hx, xs⟩,
simp only [mem_preimage, hx, e.left_inv, mem_preimage] at xs,
exact ⟨hx, xs⟩ },
{ rintros ⟨hx, xs⟩,
simp [hx, xs] }
end
lemma target_inter_inv_preimage_preimage (s : set β) :
e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s :=
e.symm.source_inter_preimage_inv_preimage _
lemma source_subset_preimage_target : e.source ⊆ e ⁻¹' e.target :=
λx hx, e.map_source hx
lemma symm_image_target_eq_source : e.symm '' e.target = e.source :=
e.symm.image_source_eq_target
lemma target_subset_preimage_source : e.target ⊆ e.symm ⁻¹' e.source :=
λx hx, e.map_target hx
/-- Two local equivs that have the same `source`, same `to_fun` and same `inv_fun`, coincide. -/
@[ext]
protected lemma ext {e e' : local_equiv α β} (h : ∀x, e x = e' x)
(hsymm : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' :=
begin
have A : (e : α → β) = e', by { ext x, exact h x },
have B : (e.symm : β → α) = e'.symm, by { ext x, exact hsymm x },
have I : e '' e.source = e.target := e.image_source_eq_target,
have I' : e' '' e'.source = e'.target := e'.image_source_eq_target,
rw [A, hs, I'] at I,
cases e; cases e',
simp * at *
end
/-- Restricting a local equivalence to e.source ∩ s -/
protected def restr (s : set α) : local_equiv α β :=
{ to_fun := e,
inv_fun := e.symm,
source := e.source ∩ s,
target := e.target ∩ e.symm⁻¹' s,
map_source' := λx hx, begin
simp only with mfld_simps at hx,
simp only [hx] with mfld_simps,
end,
map_target' := λy hy, begin
simp only with mfld_simps at hy,
simp only [hy] with mfld_simps,
end,
left_inv' := λx hx, e.left_inv hx.1,
right_inv' := λy hy, e.right_inv hy.1 }
@[simp, mfld_simps] lemma restr_coe (s : set α) : (e.restr s : α → β) = e := rfl
@[simp, mfld_simps] lemma restr_coe_symm (s : set α) : ((e.restr s).symm : β → α) = e.symm := rfl
@[simp, mfld_simps] lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ s := rfl
@[simp, mfld_simps] lemma restr_target (s : set α) :
(e.restr s).target = e.target ∩ e.symm ⁻¹' s := rfl
lemma restr_eq_of_source_subset {e : local_equiv α β} {s : set α} (h : e.source ⊆ s) :
e.restr s = e :=
local_equiv.ext (λ_, rfl) (λ_, rfl) (by simp [inter_eq_self_of_subset_left h])
@[simp, mfld_simps] lemma restr_univ {e : local_equiv α β} : e.restr univ = e :=
restr_eq_of_source_subset (subset_univ _)
/-- The identity local equiv -/
protected def refl (α : Type*) : local_equiv α α := (equiv.refl α).to_local_equiv
@[simp, mfld_simps] lemma refl_source : (local_equiv.refl α).source = univ := rfl
@[simp, mfld_simps] lemma refl_target : (local_equiv.refl α).target = univ := rfl
@[simp, mfld_simps] lemma refl_coe : (local_equiv.refl α : α → α) = id := rfl
@[simp, mfld_simps] lemma refl_symm : (local_equiv.refl α).symm = local_equiv.refl α := rfl
@[simp, mfld_simps] lemma refl_restr_source (s : set α) :
((local_equiv.refl α).restr s).source = s :=
by simp
@[simp, mfld_simps] lemma refl_restr_target (s : set α) :
((local_equiv.refl α).restr s).target = s :=
by { change univ ∩ id⁻¹' s = s, simp }
/-- The identity local equiv on a set `s` -/
def of_set (s : set α) : local_equiv α α :=
{ to_fun := id,
inv_fun := id,
source := s,
target := s,
map_source' := λx hx, hx,
map_target' := λx hx, hx,
left_inv' := λx hx, rfl,
right_inv' := λx hx, rfl }
@[simp, mfld_simps] lemma of_set_source (s : set α) : (local_equiv.of_set s).source = s := rfl
@[simp, mfld_simps] lemma of_set_target (s : set α) : (local_equiv.of_set s).target = s := rfl
@[simp, mfld_simps] lemma of_set_coe (s : set α) : (local_equiv.of_set s : α → α) = id := rfl
@[simp, mfld_simps] lemma of_set_symm (s : set α) :
(local_equiv.of_set s).symm = local_equiv.of_set s := rfl
/-- Composing two local equivs if the target of the first coincides with the source of the
second. -/
protected def trans' (e' : local_equiv β γ) (h : e.target = e'.source) :
local_equiv α γ :=
{ to_fun := e' ∘ e,
inv_fun := e.symm ∘ e'.symm,
source := e.source,
target := e'.target,
map_source' := λx hx, by simp [h.symm, hx],
map_target' := λy hy, by simp [h, hy],
left_inv' := λx hx, by simp [hx, h.symm],
right_inv' := λy hy, by simp [hy, h] }
/-- Composing two local equivs, by restricting to the maximal domain where their composition
is well defined. -/
protected def trans : local_equiv α γ :=
local_equiv.trans' (e.symm.restr (e'.source)).symm (e'.restr (e.target)) (inter_comm _ _)
@[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl
@[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl
lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm :=
by cases e; cases e'; refl
@[simp, mfld_simps] lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := rfl
lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) :=
by mfld_set_tac
lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) :=
by rw [e.trans_source', inter_comm e.target, e.symm_image_inter_target_eq]
lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source :=
image_source_eq_target (local_equiv.symm (local_equiv.restr (local_equiv.symm e) (e'.source)))
@[simp, mfld_simps] lemma trans_target :
(e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl
lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) :=
trans_source' e'.symm e.symm
lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) :=
trans_source'' e'.symm e.symm
lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target :=
image_trans_source e'.symm e.symm
lemma trans_assoc (e'' : local_equiv γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') :=
local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, @preimage_comp α β γ, inter_assoc])
@[simp, mfld_simps] lemma trans_refl : e.trans (local_equiv.refl β) = e :=
local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source])
@[simp, mfld_simps] lemma refl_trans : (local_equiv.refl α).trans e = e :=
local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, preimage_id])
lemma trans_refl_restr (s : set β) :
e.trans ((local_equiv.refl β).restr s) = e.restr (e ⁻¹' s) :=
local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source])
lemma trans_refl_restr' (s : set β) :
e.trans ((local_equiv.refl β).restr s) = e.restr (e.source ∩ e ⁻¹' s) :=
local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source], rw [← inter_assoc, inter_self] }
lemma restr_trans (s : set α) :
(e.restr s).trans e' = (e.trans e').restr s :=
local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source, inter_comm], rwa inter_assoc }
/-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. Then `e`
and `e'` should really be considered the same local equiv. -/
def eq_on_source (e e' : local_equiv α β) : Prop :=
e.source = e'.source ∧ (e.source.eq_on e e')
/-- `eq_on_source` is an equivalence relation -/
instance eq_on_source_setoid : setoid (local_equiv α β) :=
{ r := eq_on_source,
iseqv := ⟨
λe, by simp [eq_on_source],
λe e' h, by { simp [eq_on_source, h.1.symm], exact λx hx, (h.2 hx).symm },
λe e' e'' h h', ⟨by rwa [← h'.1, ← h.1], λx hx, by { rw [← h'.2, h.2 hx], rwa ← h.1 }⟩⟩ }
lemma eq_on_source_refl : e ≈ e := setoid.refl _
/-- Two equivalent local equivs have the same source -/
lemma eq_on_source.source_eq {e e' : local_equiv α β} (h : e ≈ e') : e.source = e'.source :=
h.1
/-- Two equivalent local equivs coincide on the source -/
lemma eq_on_source.eq_on {e e' : local_equiv α β} (h : e ≈ e') : e.source.eq_on e e' :=
h.2
/-- Two equivalent local equivs have the same target -/
lemma eq_on_source.target_eq {e e' : local_equiv α β} (h : e ≈ e') : e.target = e'.target :=
by simp only [← image_source_eq_target, ← h.source_eq, h.2.image_eq]
/-- If two local equivs are equivalent, so are their inverses. -/
lemma eq_on_source.symm' {e e' : local_equiv α β} (h : e ≈ e') : e.symm ≈ e'.symm :=
begin
refine ⟨h.target_eq, eq_on_of_left_inv_on_of_right_inv_on e.left_inv_on _ _⟩;
simp only [symm_source, h.target_eq, h.source_eq, e'.symm_maps_to],
exact e'.right_inv_on.congr_right e'.symm_maps_to (h.source_eq ▸ h.eq_on.symm),
end
/-- Two equivalent local equivs have coinciding inverses on the target -/
lemma eq_on_source.symm_eq_on {e e' : local_equiv α β} (h : e ≈ e') :
eq_on e.symm e'.symm e.target :=
h.symm'.eq_on
/-- Composition of local equivs respects equivalence -/
lemma eq_on_source.trans' {e e' : local_equiv α β} {f f' : local_equiv β γ}
(he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' :=
begin
split,
{ rw [trans_source'', trans_source'', ← he.target_eq, ← hf.1],
exact (he.symm'.eq_on.mono $ inter_subset_left _ _).image_eq },
{ assume x hx,
rw trans_source at hx,
simp [(he.2 hx.1).symm, hf.2 hx.2] }
end
/-- Restriction of local equivs respects equivalence -/
lemma eq_on_source.restr {e e' : local_equiv α β} (he : e ≈ e') (s : set α) :
e.restr s ≈ e'.restr s :=
begin
split,
{ simp [he.1] },
{ assume x hx,
simp only [mem_inter_eq, restr_source] at hx,
exact he.2 hx.1 }
end
/-- Preimages are respected by equivalence -/
lemma eq_on_source.source_inter_preimage_eq {e e' : local_equiv α β} (he : e ≈ e') (s : set β) :
e.source ∩ e ⁻¹' s = e'.source ∩ e' ⁻¹' s :=
begin
ext x,
simp only [mem_inter_eq, mem_preimage],
split,
{ assume hx,
rwa [← he.2 hx.1, ← he.source_eq] },
{ assume hx,
rwa [← (setoid.symm he).2 hx.1, he.source_eq] }
end
/-- Composition of a local equiv and its inverse is equivalent to the restriction of the identity
to the source -/
lemma trans_self_symm :
e.trans e.symm ≈ local_equiv.of_set e.source :=
begin
have A : (e.trans e.symm).source = e.source, by mfld_set_tac,
refine ⟨by simp [A], λx hx, _⟩,
rw A at hx,
simp only [hx] with mfld_simps
end
/-- Composition of the inverse of a local equiv and this local equiv is equivalent to the
restriction of the identity to the target -/
lemma trans_symm_self :
e.symm.trans e ≈ local_equiv.of_set e.target :=
trans_self_symm (e.symm)
/-- Two equivalent local equivs are equal when the source and target are univ -/
lemma eq_of_eq_on_source_univ (e e' : local_equiv α β) (h : e ≈ e')
(s : e.source = univ) (t : e.target = univ) : e = e' :=
begin
apply local_equiv.ext (λx, _) (λx, _) h.1,
{ apply h.2,
rw s,
exact mem_univ _ },
{ apply h.symm'.2,
rw [symm_source, t],
exact mem_univ _ }
end
section prod
/-- The product of two local equivs, as a local equiv on the product. -/
def prod (e : local_equiv α β) (e' : local_equiv γ δ) : local_equiv (α × γ) (β × δ) :=
{ source := set.prod e.source e'.source,
target := set.prod e.target e'.target,
to_fun := λp, (e p.1, e' p.2),
inv_fun := λp, (e.symm p.1, e'.symm p.2),
map_source' := λp hp, by { simp at hp, simp [hp] },
map_target' := λp hp, by { simp at hp, simp [map_target, hp] },
left_inv' := λp hp, by { simp at hp, simp [hp] },
right_inv' := λp hp, by { simp at hp, simp [hp] } }
@[simp, mfld_simps] lemma prod_source (e : local_equiv α β) (e' : local_equiv γ δ) :
(e.prod e').source = set.prod e.source e'.source := rfl
@[simp, mfld_simps] lemma prod_target (e : local_equiv α β) (e' : local_equiv γ δ) :
(e.prod e').target = set.prod e.target e'.target := rfl
@[simp, mfld_simps] lemma prod_coe (e : local_equiv α β) (e' : local_equiv γ δ) :
((e.prod e') : α × γ → β × δ) = (λp, (e p.1, e' p.2)) := rfl
lemma prod_coe_symm (e : local_equiv α β) (e' : local_equiv γ δ) :
((e.prod e').symm : β × δ → α × γ) = (λp, (e.symm p.1, e'.symm p.2)) := rfl
@[simp, mfld_simps] lemma prod_symm (e : local_equiv α β) (e' : local_equiv γ δ) :
(e.prod e').symm = (e.symm.prod e'.symm) :=
by ext x; simp [prod_coe_symm]
@[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*}
(e : local_equiv α β) (f : local_equiv β γ) (e' : local_equiv δ η) (f' : local_equiv η ε) :
(e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') :=
by ext x; simp [ext_iff]; tauto
end prod
end local_equiv
namespace set
-- All arguments are explicit to avoid missing information in the pretty printer output
/-- A bijection between two sets `s : set α` and `t : set β` provides a local equivalence
between `α` and `β`. -/
@[simps] noncomputable def bij_on.to_local_equiv [nonempty α] (f : α → β) (s : set α) (t : set β)
(hf : bij_on f s t) :
local_equiv α β :=
{ to_fun := f,
inv_fun := inv_fun_on f s,
source := s,
target := t,
map_source' := hf.maps_to,
map_target' := hf.surj_on.maps_to_inv_fun_on,
left_inv' := hf.inv_on_inv_fun_on.1,
right_inv' := hf.inv_on_inv_fun_on.2 }
/-- A map injective on a subset of its domain provides a local equivalence. -/
@[simp, mfld_simps] noncomputable def inj_on.to_local_equiv [nonempty α] (f : α → β) (s : set α)
(hf : inj_on f s) :
local_equiv α β :=
hf.bij_on_image.to_local_equiv f s (f '' s)
end set
namespace equiv
/- equivs give rise to local_equiv. We set up simp lemmas to reduce most properties of the local
equiv to that of the equiv. -/
variables (e : equiv α β) (e' : equiv β γ)
@[simp, mfld_simps] lemma to_local_equiv_coe : (e.to_local_equiv : α → β) = e := rfl
@[simp, mfld_simps] lemma to_local_equiv_symm_coe : (e.to_local_equiv.symm : β → α) = e.symm := rfl
@[simp, mfld_simps] lemma to_local_equiv_source : e.to_local_equiv.source = univ := rfl
@[simp, mfld_simps] lemma to_local_equiv_target : e.to_local_equiv.target = univ := rfl
@[simp, mfld_simps] lemma refl_to_local_equiv :
(equiv.refl α).to_local_equiv = local_equiv.refl α := rfl
@[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl
@[simp, mfld_simps] lemma trans_to_local_equiv :
(e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv :=
local_equiv.ext (λx, rfl) (λx, rfl) (by simp [local_equiv.trans_source, equiv.to_local_equiv])
end equiv
|
9f8a6e03c1f145db7cf8fcfac431219a08f2bcea | a45212b1526d532e6e83c44ddca6a05795113ddc | /src/data/vector2.lean | 868044013a5334d60421441d92da7756ad4eeeb1 | [
"Apache-2.0"
] | permissive | fpvandoorn/mathlib | b21ab4068db079cbb8590b58fda9cc4bc1f35df4 | b3433a51ea8bc07c4159c1073838fc0ee9b8f227 | refs/heads/master | 1,624,791,089,608 | 1,556,715,231,000 | 1,556,715,231,000 | 165,722,980 | 5 | 0 | Apache-2.0 | 1,552,657,455,000 | 1,547,494,646,000 | Lean | UTF-8 | Lean | false | false | 8,319 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
Additional theorems about the `vector` type.
-/
import data.vector data.list.basic category.traversable.basic data.set.basic
universes u
variables {n : ℕ}
namespace vector
variables {α : Type*}
attribute [simp] head_cons tail_cons
instance [inhabited α] : inhabited (vector α n) :=
⟨of_fn (λ _, default α)⟩
theorem to_list_injective : function.injective (@to_list α n) :=
subtype.val_injective
@[simp] theorem to_list_of_fn : ∀ {n} (f : fin n → α), to_list (of_fn f) = list.of_fn f
| 0 f := rfl
| (n+1) f := by rw [of_fn, list.of_fn_succ, to_list_cons, to_list_of_fn]
@[simp] theorem mk_to_list :
∀ (v : vector α n) h, (⟨to_list v, h⟩ : vector α n) = v
| ⟨l, h₁⟩ h₂ := rfl
theorem nth_eq_nth_le : ∀ (v : vector α n) (i),
nth v i = v.to_list.nth_le i.1 (by rw to_list_length; exact i.2)
| ⟨l, h⟩ i := rfl
@[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = f i :=
by rw [nth_eq_nth_le, ← list.nth_le_of_fn f];
congr; apply to_list_of_fn
@[simp] theorem of_fn_nth (v : vector α n) : of_fn (nth v) = v :=
begin
rcases v with ⟨l, rfl⟩,
apply to_list_injective,
change nth ⟨l, eq.refl _⟩ with λ i, nth ⟨l, rfl⟩ i,
simp [nth, list.of_fn_nth_le]
end
@[simp] theorem nth_tail : ∀ (v : vector α n.succ) (i : fin n),
nth (tail v) i = nth v i.succ
| ⟨a::l, e⟩ ⟨i, h⟩ := by simp [nth_eq_nth_le]; refl
@[simp] theorem tail_of_fn {n : ℕ} (f : fin n.succ → α) :
tail (of_fn f) = of_fn (λ i, f i.succ) :=
(of_fn_nth _).symm.trans $ by congr; funext i; simp
theorem head'_to_list : ∀ (v : vector α n.succ),
(to_list v).head' = some (head v)
| ⟨a::l, e⟩ := rfl
def reverse (v : vector α n) : vector α n :=
⟨v.to_list.reverse, by simp⟩
@[simp] theorem nth_zero : ∀ (v : vector α n.succ), nth v 0 = head v
| ⟨a::l, e⟩ := rfl
@[simp] theorem head_of_fn
{n : ℕ} (f : fin n.succ → α) : head (of_fn f) = f 0 :=
by rw [← nth_zero, nth_of_fn]
@[simp] theorem nth_cons_zero
(a : α) (v : vector α n) : nth (a :: v) 0 = a :=
by simp [nth_zero]
@[simp] theorem nth_cons_succ
(a : α) (v : vector α n) (i : fin n) : nth (a :: v) i.succ = nth v i :=
by rw [← nth_tail, tail_cons]
def m_of_fn {m} [monad m] {α : Type u} : ∀ {n}, (fin n → m α) → m (vector α n)
| 0 f := pure nil
| (n+1) f := do a ← f 0, v ← m_of_fn (λi, f i.succ), pure (a :: v)
theorem m_of_fn_pure {m} [monad m] [is_lawful_monad m] {α} :
∀ {n} (f : fin n → α), @m_of_fn m _ _ _ (λ i, pure (f i)) = pure (of_fn f)
| 0 f := rfl
| (n+1) f := by simp [m_of_fn, @m_of_fn_pure n, of_fn]
def mmap {m} [monad m] {α} {β : Type u} (f : α → m β) :
∀ {n}, vector α n → m (vector β n)
| _ ⟨[], rfl⟩ := pure nil
| _ ⟨a::l, rfl⟩ := do h' ← f a, t' ← mmap ⟨l, rfl⟩, pure (h' :: t')
@[simp] theorem mmap_nil {m} [monad m] {α β} (f : α → m β) :
mmap f nil = pure nil := rfl
@[simp] theorem mmap_cons {m} [monad m] {α β} (f : α → m β) (a) :
∀ {n} (v : vector α n), mmap f (a::v) =
do h' ← f a, t' ← mmap f v, pure (h' :: t')
| _ ⟨l, rfl⟩ := rfl
@[extensionality] theorem ext : ∀ {v w : vector α n}
(h : ∀ m : fin n, vector.nth v m = vector.nth w m), v = w
| ⟨v, hv⟩ ⟨w, hw⟩ h := subtype.eq (list.ext_le (by rw [hv, hw])
(λ m hm hn, h ⟨m, hv ▸ hm⟩))
instance zero_subsingleton : subsingleton (vector α 0) :=
⟨λ _ _, vector.ext (λ m, fin.elim0 m)⟩
def to_array : vector α n → array n α
| ⟨xs, h⟩ := cast (by rw h) xs.to_array
section insert_nth
variable {a : α}
def insert_nth (a : α) (i : fin (n+1)) (v : vector α n) : vector α (n+1) :=
⟨v.1.insert_nth i.1 a,
begin
rw [list.length_insert_nth, v.2],
rw [v.2, ← nat.succ_le_succ_iff],
exact i.2
end⟩
lemma insert_nth_val {i : fin (n+1)} {v : vector α n} :
(v.insert_nth a i).val = v.val.insert_nth i.1 a :=
rfl
@[simp] lemma remove_nth_val {i : fin n} :
∀{v : vector α n}, (remove_nth i v).val = v.val.remove_nth i.1
| ⟨l, hl⟩ := rfl
lemma remove_nth_insert_nth {v : vector α n} {i : fin (n+1)} : remove_nth i (insert_nth a i v) = v :=
subtype.eq $ list.remove_nth_insert_nth i.1 v.1
lemma remove_nth_insert_nth_ne {v : vector α (n+1)} :
∀{i j : fin (n+2)} (h : i ≠ j),
remove_nth i (insert_nth a j v) = insert_nth a (i.pred_above j h.symm) (remove_nth (j.pred_above i h) v)
| ⟨i, hi⟩ ⟨j, hj⟩ ne :=
begin
have : i ≠ j := fin.vne_of_ne ne,
refine subtype.eq _,
dsimp [insert_nth, remove_nth, fin.pred_above, fin.cast_lt],
rcases lt_trichotomy i j with h | h | h,
{ have h_nji : ¬ j < i := lt_asymm h,
have j_pos : 0 < j := lt_of_le_of_lt (zero_le i) h,
simp [h, h_nji, fin.lt_iff_val_lt_val],
rw [show j.pred = j - 1, from rfl, list.insert_nth_remove_nth_of_ge, nat.sub_add_cancel j_pos],
{ rw [v.2], exact lt_of_lt_of_le h (nat.le_of_succ_le_succ hj) },
{ exact nat.le_sub_right_of_add_le h } },
{ exact (this h).elim },
{ have h_nij : ¬ i < j := lt_asymm h,
have i_pos : 0 < i := lt_of_le_of_lt (zero_le j) h,
simp [h, h_nij, fin.lt_iff_val_lt_val],
rw [show i.pred = i - 1, from rfl, list.insert_nth_remove_nth_of_le, nat.sub_add_cancel i_pos],
{ show i - 1 + 1 ≤ v.val.length,
rw [v.2, nat.sub_add_cancel i_pos],
exact nat.le_of_lt_succ hi },
{ exact nat.le_sub_right_of_add_le h } }
end
lemma insert_nth_comm (a b : α) (i j : fin (n+1)) (h : i ≤ j) :
∀(v : vector α n), (v.insert_nth a i).insert_nth b j.succ = (v.insert_nth b j).insert_nth a i.cast_succ
| ⟨l, hl⟩ :=
begin
refine subtype.eq _,
simp [insert_nth_val, fin.succ_val, fin.cast_succ],
apply list.insert_nth_comm,
{ assumption },
{ rw hl, exact nat.le_of_succ_le_succ j.2 }
end
end insert_nth
end vector
namespace vector
section traverse
variables {F G : Type u → Type u}
variables [applicative F] [applicative G]
open applicative functor
open list (cons) nat
private def traverse_aux {α β : Type u} (f : α → F β) :
Π (x : list α), F (vector β x.length)
| [] := pure vector.nil
| (x::xs) := vector.cons <$> f x <*> traverse_aux xs
protected def traverse {α β : Type u} (f : α → F β) : vector α n → F (vector β n)
| ⟨v, Hv⟩ := cast (by rw Hv) $ traverse_aux f v
variables [is_lawful_applicative F] [is_lawful_applicative G]
variables {α β γ : Type u}
@[simp] protected lemma traverse_def
(f : α → F β) (x : α) : ∀ (xs : vector α n),
(x :: xs).traverse f = cons <$> f x <*> xs.traverse f :=
by rintro ⟨xs, rfl⟩; refl
protected lemma id_traverse : ∀ (x : vector α n), x.traverse id.mk = x :=
begin
rintro ⟨x, rfl⟩, dsimp [vector.traverse, cast],
induction x with x xs IH, {refl},
simp! [IH], refl
end
open function
protected lemma comp_traverse (f : β → F γ) (g : α → G β) : ∀ (x : vector α n),
vector.traverse (comp.mk ∘ functor.map f ∘ g) x =
comp.mk (vector.traverse f <$> vector.traverse g x) :=
by rintro ⟨x, rfl⟩; dsimp [vector.traverse, cast];
induction x with x xs; simp! [cast, *] with functor_norm;
[refl, simp [(∘)]]
protected lemma traverse_eq_map_id {α β} (f : α → β) : ∀ (x : vector α n),
x.traverse (id.mk ∘ f) = id.mk (map f x) :=
by rintro ⟨x, rfl⟩; simp!;
induction x; simp! * with functor_norm; refl
variable (η : applicative_transformation F G)
protected lemma naturality {α β : Type*}
(f : α → F β) : ∀ (x : vector α n),
η (x.traverse f) = x.traverse (@η _ ∘ f) :=
by rintro ⟨x, rfl⟩; simp! [cast];
induction x with x xs IH; simp! * with functor_norm
end traverse
instance : traversable.{u} (flip vector n) :=
{ traverse := @vector.traverse n,
map := λ α β, @vector.map.{u u} α β n }
instance : is_lawful_traversable.{u} (flip vector n) :=
{ id_traverse := @vector.id_traverse n,
comp_traverse := @vector.comp_traverse n,
traverse_eq_map_id := @vector.traverse_eq_map_id n,
naturality := @vector.naturality n,
id_map := by intros; cases x; simp! [(<$>)],
comp_map := by intros; cases x; simp! [(<$>)] }
end vector
|
eef0934fd4fb957dfe5f490e6a99ffc1c799c4aa | 618003631150032a5676f229d13a079ac875ff77 | /src/topology/metric_space/emetric_space.lean | 13b45ae746fed09df75d50bf21a5d5a25b47e35e | [
"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 | 40,235 | lean | /-
Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel
-/
import data.real.ennreal
import topology.uniform_space.uniform_embedding
import topology.uniform_space.pi
import topology.uniform_space.uniform_convergence
/-!
# Extended metric spaces
This file is devoted to the definition and study of `emetric_spaces`, i.e., metric
spaces in which the distance is allowed to take the value ∞. This extended distance is
called `edist`, and takes values in `ennreal`.
Many definitions and theorems expected on emetric spaces are already introduced on uniform spaces and
topological spaces. For example:
open and closed sets, compactness, completeness, continuity and uniform continuity
The class `emetric_space` therefore extends `uniform_space` (and `topological_space`).
-/
open set filter classical
noncomputable theory
open_locale uniformity topological_space
universes u v w
variables {α : Type u} {β : Type v} {γ : Type w}
/-- Characterizing uniformities associated to a (generalized) distance function `D`
in terms of the elements of the uniformity. -/
theorem uniformity_dist_of_mem_uniformity [linear_order β] {U : filter (α × α)} (z : β) (D : α → α → β)
(H : ∀ s, s ∈ U ↔ ∃ε>z, ∀{a b:α}, D a b < ε → (a, b) ∈ s) :
U = ⨅ ε>z, principal {p:α×α | D p.1 p.2 < ε} :=
le_antisymm
(le_infi $ λ ε, le_infi $ λ ε0, le_principal_iff.2 $ (H _).2 ⟨ε, ε0, λ a b, id⟩)
(λ r ur, let ⟨ε, ε0, h⟩ := (H _).1 ur in
mem_infi_sets ε $ mem_infi_sets ε0 $ mem_principal_sets.2 $ λ ⟨a, b⟩, h)
class has_edist (α : Type*) := (edist : α → α → ennreal)
export has_edist (edist)
/- Design note: one could define an `emetric_space` just by giving `edist`, and then
derive an instance of `uniform_space` by taking the natural uniform structure
associated to the distance. This creates diamonds problem for products, as the
uniform structure on the product of two emetric spaces could be obtained first
by obtaining two uniform spaces and then taking their products, or by taking
the product of the emetric spaces and then the associated uniform structure.
The two uniform structure we have just described are equal, but not defeq, which
creates a lot of problem.
The idea is to add, in the very definition of an `emetric_space`, a uniform structure
with a uniformity which equal to the one given by the distance, but maybe not defeq.
And the instance from `emetric_space` to `uniform_space` uses this uniformity.
In this way, when we create the product of emetric spaces, we put in the product
the uniformity corresponding to the product of the uniformities. There is one more
proof obligation, that this product uniformity is equal to the uniformity corresponding
to the product metric. But the diamond problem disappears.
The same trick is used in the definition of a metric space, where one stores as well
a uniform structure and an edistance. -/
/-- Creating a uniform space from an extended distance. -/
def uniform_space_of_edist
(edist : α → α → ennreal)
(edist_self : ∀ x : α, edist x x = 0)
(edist_comm : ∀ x y : α, edist x y = edist y x)
(edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z) : uniform_space α :=
uniform_space.of_core {
uniformity := (⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε}),
refl := le_infi $ assume ε, le_infi $
by simp [set.subset_def, id_rel, edist_self, (>)] {contextual := tt},
comp :=
le_infi $ assume ε, le_infi $ assume h,
have (2 : ennreal) = (2 : ℕ) := by simp,
have A : 0 < ε / 2 := ennreal.div_pos_iff.2
⟨ne_of_gt h, by { convert ennreal.nat_ne_top 2 }⟩,
lift'_le
(mem_infi_sets (ε / 2) $ mem_infi_sets A (subset.refl _)) $
have ∀ (a b c : α), edist a c < ε / 2 → edist c b < ε / 2 → edist a b < ε,
from assume a b c hac hcb,
calc edist a b ≤ edist a c + edist c b : edist_triangle _ _ _
... < ε / 2 + ε / 2 : ennreal.add_lt_add hac hcb
... = ε : by rw [ennreal.add_halves],
by simpa [comp_rel],
symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h,
tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [edist_comm] }
section prio
set_option default_priority 100 -- see Note [default priority]
/-- Extended metric spaces, with an extended distance `edist` possibly taking the
value ∞
Each emetric space induces a canonical `uniform_space` and hence a canonical `topological_space`.
This is enforced in the type class definition, by extending the `uniform_space` structure. When
instantiating an `emetric_space` structure, the uniformity fields are not necessary, they will be
filled in by default. There is a default value for the uniformity, that can be substituted
in cases of interest, for instance when instantiating an `emetric_space` structure
on a product.
Continuity of `edist` is finally proving in `topology.instances.ennreal`
-/
class emetric_space (α : Type u) extends has_edist α : Type u :=
(edist_self : ∀ x : α, edist x x = 0)
(eq_of_edist_eq_zero : ∀ {x y : α}, edist x y = 0 → x = y)
(edist_comm : ∀ x y : α, edist x y = edist y x)
(edist_triangle : ∀ x y z : α, edist x z ≤ edist x y + edist y z)
(to_uniform_space : uniform_space α := uniform_space_of_edist edist edist_self edist_comm edist_triangle)
(uniformity_edist : 𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} . control_laws_tac)
end prio
/- emetric spaces are less common than metric spaces. Therefore, we work in a dedicated
namespace, while notions associated to metric spaces are mostly in the root namespace. -/
variables [emetric_space α]
@[priority 100] -- see Note [lower instance priority]
instance emetric_space.to_uniform_space' : uniform_space α :=
emetric_space.to_uniform_space
export emetric_space (edist_self eq_of_edist_eq_zero edist_comm edist_triangle)
attribute [simp] edist_self
/-- Characterize the equality of points by the vanishing of their extended distance -/
@[simp] theorem edist_eq_zero {x y : α} : edist x y = 0 ↔ x = y :=
iff.intro eq_of_edist_eq_zero (assume : x = y, this ▸ edist_self _)
@[simp] theorem zero_eq_edist {x y : α} : 0 = edist x y ↔ x = y :=
iff.intro (assume h, eq_of_edist_eq_zero (h.symm))
(assume : x = y, this ▸ (edist_self _).symm)
theorem edist_le_zero {x y : α} : (edist x y ≤ 0) ↔ x = y :=
le_zero_iff_eq.trans edist_eq_zero
/-- Triangle inequality for the extended distance -/
theorem edist_triangle_left (x y z : α) : edist x y ≤ edist z x + edist z y :=
by rw edist_comm z; apply edist_triangle
theorem edist_triangle_right (x y z : α) : edist x y ≤ edist x z + edist y z :=
by rw edist_comm y; apply edist_triangle
lemma edist_triangle4 (x y z t : α) :
edist x t ≤ edist x y + edist y z + edist z t :=
calc
edist x t ≤ edist x z + edist z t : edist_triangle x z t
... ≤ (edist x y + edist y z) + edist z t : add_le_add_right' (edist_triangle x y z)
/-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/
lemma edist_le_Ico_sum_edist (f : ℕ → α) {m n} (h : m ≤ n) :
edist (f m) (f n) ≤ (finset.Ico m n).sum (λ i, edist (f i) (f (i + 1))) :=
begin
revert n,
refine nat.le_induction _ _,
{ simp only [finset.sum_empty, finset.Ico.self_eq_empty, edist_self],
-- TODO: Why doesn't Lean close this goal automatically? `apply le_refl` fails too.
exact le_refl (0:ennreal) },
{ assume n hn hrec,
calc edist (f m) (f (n+1)) ≤ edist (f m) (f n) + edist (f n) (f (n+1)) : edist_triangle _ _ _
... ≤ (finset.Ico m n).sum _ + _ : add_le_add' hrec (le_refl _)
... = (finset.Ico m (n+1)).sum _ :
by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp }
end
/-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/
lemma edist_le_range_sum_edist (f : ℕ → α) (n : ℕ) :
edist (f 0) (f n) ≤ (finset.range n).sum (λ i, edist (f i) (f (i + 1))) :=
finset.Ico.zero_bot n ▸ edist_le_Ico_sum_edist f (nat.zero_le n)
/-- A version of `edist_le_Ico_sum_edist` with each intermediate distance replaced
with an upper estimate. -/
lemma edist_le_Ico_sum_of_edist_le {f : ℕ → α} {m n} (hmn : m ≤ n)
{d : ℕ → ennreal} (hd : ∀ {k}, m ≤ k → k < n → edist (f k) (f (k + 1)) ≤ d k) :
edist (f m) (f n) ≤ (finset.Ico m n).sum d :=
le_trans (edist_le_Ico_sum_edist f hmn) $
finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2
/-- A version of `edist_le_range_sum_edist` with each intermediate distance replaced
with an upper estimate. -/
lemma edist_le_range_sum_of_edist_le {f : ℕ → α} (n : ℕ)
{d : ℕ → ennreal} (hd : ∀ {k}, k < n → edist (f k) (f (k + 1)) ≤ d k) :
edist (f 0) (f n) ≤ (finset.range n).sum d :=
finset.Ico.zero_bot n ▸ edist_le_Ico_sum_of_edist_le (zero_le n) (λ _ _, hd)
/-- Two points coincide if their distance is `< ε` for all positive ε -/
theorem eq_of_forall_edist_le {x y : α} (h : ∀ε, ε > 0 → edist x y ≤ ε) : x = y :=
eq_of_edist_eq_zero (eq_of_le_of_forall_le_of_dense bot_le h)
/-- Reformulation of the uniform structure in terms of the extended distance -/
theorem uniformity_edist :
𝓤 α = ⨅ ε>0, principal {p:α×α | edist p.1 p.2 < ε} :=
emetric_space.uniformity_edist
theorem uniformity_basis_edist :
(𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) :=
(@uniformity_edist α _).symm ▸ has_basis_binfi_principal
(λ r hr p hp, ⟨min r p, lt_min hr hp,
λ x hx, lt_of_lt_of_le hx (min_le_left _ _),
λ x hx, lt_of_lt_of_le hx (min_le_right _ _)⟩)
⟨1, ennreal.zero_lt_one⟩
/-- Characterization of the elements of the uniformity in terms of the extended distance -/
theorem mem_uniformity_edist {s : set (α×α)} :
s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, edist a b < ε → (a, b) ∈ s) :=
uniformity_basis_edist.mem_uniformity_iff
/-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`.
For specific bases see `uniformity_basis_edist`, `uniformity_basis_edist'`,
`uniformity_basis_edist_nnreal`, and `uniformity_basis_edist_inv_nat`. -/
protected theorem emetric.mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ennreal}
(hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) :
(𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 < f x}) :=
begin
refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
rcases hf ε ε₀ with ⟨i, hi, H⟩,
exact ⟨i, hi, λ x hx, hε $ lt_of_lt_of_le hx H⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ }
end
/-- Given `f : β → ennreal`, if `f` sends `{i | p i}` to a set of positive numbers
accumulating to zero, then closed `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`.
For specific bases see `uniformity_basis_edist_le` and `uniformity_basis_edist_le'`. -/
protected theorem emetric.mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ennreal}
(hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) :
(𝓤 α).has_basis p (λ x, {p:α×α | edist p.1 p.2 ≤ f x}) :=
begin
refine ⟨λ s, uniformity_basis_edist.mem_iff.trans _⟩,
split,
{ rintros ⟨ε, ε₀, hε⟩,
rcases dense ε₀ with ⟨ε', hε'⟩,
rcases hf ε' hε'.1 with ⟨i, hi, H⟩,
exact ⟨i, hi, λ x hx, hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ },
{ exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x hx, H (le_of_lt hx)⟩ }
end
theorem uniformity_basis_edist_le :
(𝓤 α).has_basis (λ ε : ennreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) :=
emetric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩)
theorem uniformity_basis_edist' (ε' : ennreal) (hε' : 0 < ε') :
(𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 < ε}) :=
emetric.mk_uniformity_basis (λ _, and.left)
(λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in
⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩)
theorem uniformity_basis_edist_le' (ε' : ennreal) (hε' : 0 < ε') :
(𝓤 α).has_basis (λ ε : ennreal, ε ∈ Ioo 0 ε') (λ ε, {p:α×α | edist p.1 p.2 ≤ ε}) :=
emetric.mk_uniformity_basis_le (λ _, and.left)
(λ ε ε₀, let ⟨δ, hδ⟩ := dense hε' in
⟨min ε δ, ⟨lt_min ε₀ hδ.1, lt_of_le_of_lt (min_le_right _ _) hδ.2⟩, min_le_left _ _⟩)
theorem uniformity_basis_edist_nnreal :
(𝓤 α).has_basis (λ ε : nnreal, 0 < ε) (λ ε, {p:α×α | edist p.1 p.2 < ε}) :=
emetric.mk_uniformity_basis (λ _, ennreal.coe_pos.2)
(λ ε ε₀, let ⟨δ, hδ⟩ := ennreal.lt_iff_exists_nnreal_btwn.1 ε₀ in
⟨δ, ennreal.coe_pos.1 hδ.1, le_of_lt hδ.2⟩)
theorem uniformity_basis_edist_inv_nat :
(𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | edist p.1 p.2 < (↑n)⁻¹}) :=
emetric.mk_uniformity_basis
(λ n _, ennreal.inv_pos.2 $ ennreal.nat_ne_top n)
(λ ε ε₀, let ⟨n, hn⟩ := ennreal.exists_inv_nat_lt (ne_of_gt ε₀) in ⟨n, trivial, le_of_lt hn⟩)
/-- Fixed size neighborhoods of the diagonal belong to the uniform structure -/
theorem edist_mem_uniformity {ε:ennreal} (ε0 : 0 < ε) :
{p:α×α | edist p.1 p.2 < ε} ∈ 𝓤 α :=
mem_uniformity_edist.2 ⟨ε, ε0, λ a b, id⟩
namespace emetric
theorem uniformity_has_countable_basis : is_countably_generated (𝓤 α) :=
is_countably_generated_of_seq ⟨_, uniformity_basis_edist_inv_nat.eq_infi⟩
/-- ε-δ characterization of uniform continuity on emetric spaces -/
theorem uniform_continuous_iff [emetric_space β] {f : α → β} :
uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0,
∀{a b:α}, edist a b < δ → edist (f a) (f b) < ε :=
uniformity_basis_edist.uniform_continuous_iff uniformity_basis_edist
/-- ε-δ characterization of uniform embeddings on emetric spaces -/
theorem uniform_embedding_iff [emetric_space β] {f : α → β} :
uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧
∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ :=
uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl
⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (edist_mem_uniformity δ0),
⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 tu in
⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩,
λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_edist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in
⟨_, edist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩
/-- A map between emetric spaces is a uniform embedding if and only if the edistance between `f x`
and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/
theorem uniform_embedding_iff' [emetric_space β] {f : α → β} :
uniform_embedding f ↔
(∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, edist a b < δ → edist (f a) (f b) < ε) ∧
(∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, edist (f a) (f b) < ε → edist a b < δ) :=
begin
split,
{ assume h,
exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1,
(uniform_embedding_iff.1 h).2.2⟩ },
{ rintros ⟨h₁, h₂⟩,
refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩,
assume x y hxy,
have : edist x y ≤ 0,
{ refine le_of_forall_lt' (λδ δpos, _),
rcases h₂ δ δpos with ⟨ε, εpos, hε⟩,
have : edist (f x) (f y) < ε, by simpa [hxy],
exact hε this },
simpa using this }
end
/-- ε-δ characterization of Cauchy sequences on emetric spaces -/
protected lemma cauchy_iff {f : filter α} :
cauchy f ↔ f ≠ ⊥ ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, edist x y < ε :=
uniformity_basis_edist.cauchy_iff
/-- A very useful criterion to show that a space is complete is to show that all sequences
which satisfy a bound of the form `edist (u n) (u m) < B N` for all `n m ≥ N` are
converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to
`0`, which makes it possible to use arguments of converging series, while this is impossible
to do in general for arbitrary Cauchy sequences. -/
theorem complete_of_convergent_controlled_sequences (B : ℕ → ennreal) (hB : ∀n, 0 < B n)
(H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → edist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) :
complete_space α :=
uniform_space.complete_of_convergent_controlled_sequences
uniformity_has_countable_basis
(λ n, {p:α×α | edist p.1 p.2 < B n}) (λ n, edist_mem_uniformity $ hB n) H
/-- A sequentially complete emetric space is complete. -/
theorem complete_of_cauchy_seq_tendsto :
(∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α :=
uniform_space.complete_of_cauchy_seq_tendsto uniformity_has_countable_basis
/-- Expressing locally uniform convergence on a set using `edist`. -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_locally_uniformly_on F f p s ↔
∀ ε > 0, ∀ x ∈ s, ∃ t ∈ nhds_within x s, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε :=
begin
refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu x hx, _⟩,
rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩,
rcases H ε εpos x hx with ⟨t, ht, Ht⟩,
exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩
end
/-- Expressing uniform convergence on a set using `edist`. -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma tendsto_uniformly_on_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} :
tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, edist (f x) (F n x) < ε :=
begin
refine ⟨λ H ε hε, H _ (edist_mem_uniformity hε), λ H u hu, _⟩,
rcases mem_uniformity_edist.1 hu with ⟨ε, εpos, hε⟩,
exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx))
end
/-- Expressing locally uniform convergence using `edist`. -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β]
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_locally_uniformly F f p ↔
∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, edist (f y) (F n y) < ε :=
by simp [← nhds_within_univ, ← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff]
/-- Expressing uniform convergence using `edist`. -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma tendsto_uniformly_iff {ι : Type*}
{F : ι → β → α} {f : β → α} {p : filter ι} :
tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, edist (f x) (F n x) < ε :=
by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp }
end emetric
open emetric
/-- An emetric space is separated -/
@[priority 100] -- see Note [lower instance priority]
instance to_separated : separated α :=
separated_def.2 $ λ x y h, eq_of_forall_edist_le $
λ ε ε0, le_of_lt (h _ (edist_mem_uniformity ε0))
/-- Auxiliary function to replace the uniformity on an emetric space with
a uniformity which is equal to the original one, but maybe not defeq.
This is useful if one wants to construct an emetric space with a
specified uniformity. -/
def emetric_space.replace_uniformity {α} [U : uniform_space α] (m : emetric_space α)
(H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space) :
emetric_space α :=
{ edist := @edist _ m.to_has_edist,
edist_self := edist_self,
eq_of_edist_eq_zero := @eq_of_edist_eq_zero _ _,
edist_comm := edist_comm,
edist_triangle := edist_triangle,
to_uniform_space := U,
uniformity_edist := H.trans (@emetric_space.uniformity_edist α _) }
/-- The extended metric induced by an injective function taking values in an emetric space. -/
def emetric_space.induced {α β} (f : α → β) (hf : function.injective f)
(m : emetric_space β) : emetric_space α :=
{ edist := λ x y, edist (f x) (f y),
edist_self := λ x, edist_self _,
eq_of_edist_eq_zero := λ x y h, hf (edist_eq_zero.1 h),
edist_comm := λ x y, edist_comm _ _,
edist_triangle := λ x y z, edist_triangle _ _ _,
to_uniform_space := uniform_space.comap f m.to_uniform_space,
uniformity_edist := begin
apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, edist (f x) (f y)),
refine λ s, mem_comap_sets.trans _,
split; intro H,
{ rcases H with ⟨r, ru, rs⟩,
rcases mem_uniformity_edist.1 ru with ⟨ε, ε0, hε⟩,
refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h },
{ rcases H with ⟨ε, ε0, hε⟩,
exact ⟨_, edist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ }
end }
/-- Emetric space instance on subsets of emetric spaces -/
instance {α : Type*} {p : α → Prop} [t : emetric_space α] : emetric_space (subtype p) :=
t.induced coe (λ x y, subtype.coe_ext.2)
/-- The extended distance on a subset of an emetric space is the restriction of
the original distance, by definition -/
theorem subtype.edist_eq {p : α → Prop} (x y : subtype p) : edist x y = edist (x : α) y := rfl
/-- The product of two emetric spaces, with the max distance, is an extended
metric spaces. We make sure that the uniform structure thus constructed is the one
corresponding to the product of uniform spaces, to avoid diamond problems. -/
instance prod.emetric_space_max [emetric_space β] : emetric_space (α × β) :=
{ edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2),
edist_self := λ x, by simp,
eq_of_edist_eq_zero := λ x y h, begin
cases max_le_iff.1 (le_of_eq h) with h₁ h₂,
have A : x.fst = y.fst := edist_le_zero.1 h₁,
have B : x.snd = y.snd := edist_le_zero.1 h₂,
exact prod.ext_iff.2 ⟨A, B⟩
end,
edist_comm := λ x y, by simp [edist_comm],
edist_triangle := λ x y z, max_le
(le_trans (edist_triangle _ _ _) (add_le_add' (le_max_left _ _) (le_max_left _ _)))
(le_trans (edist_triangle _ _ _) (add_le_add' (le_max_right _ _) (le_max_right _ _))),
uniformity_edist := begin
refine uniformity_prod.trans _,
simp [emetric_space.uniformity_edist, comap_infi],
rw ← infi_inf_eq, congr, funext,
rw ← infi_inf_eq, congr, funext,
simp [inf_principal, ext_iff, max_lt_iff]
end,
to_uniform_space := prod.uniform_space }
lemma prod.edist_eq [emetric_space β] (x y : α × β) :
edist x y = max (edist x.1 y.1) (edist x.2 y.2) :=
rfl
section pi
open finset
variables {π : β → Type*} [fintype β]
/-- The product of a finite number of emetric spaces, with the max distance, is still
an emetric space.
This construction would also work for infinite products, but it would not give rise
to the product topology. Hence, we only formalize it in the good situation of finitely many
spaces. -/
instance emetric_space_pi [∀b, emetric_space (π b)] : emetric_space (Πb, π b) :=
{ edist := λ f g, finset.sup univ (λb, edist (f b) (g b)),
edist_self := assume f, bot_unique $ finset.sup_le $ by simp,
edist_comm := assume f g, by unfold edist; congr; funext a; exact edist_comm _ _,
edist_triangle := assume f g h,
begin
simp only [finset.sup_le_iff],
assume b hb,
exact le_trans (edist_triangle _ (g b) _) (add_le_add' (le_sup hb) (le_sup hb))
end,
eq_of_edist_eq_zero := assume f g eq0,
begin
have eq1 : sup univ (λ (b : β), edist (f b) (g b)) ≤ 0 := le_of_eq eq0,
simp only [finset.sup_le_iff] at eq1,
exact (funext $ assume b, edist_le_zero.1 $ eq1 b $ mem_univ b),
end,
to_uniform_space := Pi.uniform_space _,
uniformity_edist := begin
simp only [Pi.uniformity, emetric_space.uniformity_edist, comap_infi, gt_iff_lt, preimage_set_of_eq,
comap_principal],
rw infi_comm, congr, funext ε,
rw infi_comm, congr, funext εpos,
change 0 < ε at εpos,
simp [ext_iff, εpos]
end }
end pi
namespace emetric
variables {x y z : α} {ε ε₁ ε₂ : ennreal} {s : set α}
/-- `emetric.ball x ε` is the set of all points `y` with `edist y x < ε` -/
def ball (x : α) (ε : ennreal) : set α := {y | edist y x < ε}
@[simp] theorem mem_ball : y ∈ ball x ε ↔ edist y x < ε := iff.rfl
theorem mem_ball' : y ∈ ball x ε ↔ edist x y < ε := by rw edist_comm; refl
/-- `emetric.closed_ball x ε` is the set of all points `y` with `edist y x ≤ ε` -/
def closed_ball (x : α) (ε : ennreal) := {y | edist y x ≤ ε}
@[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ edist y x ≤ ε := iff.rfl
theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε :=
assume y, by simp; intros h; apply le_of_lt h
theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε :=
lt_of_le_of_lt (zero_le _) hy
theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε :=
show edist x x < ε, by rw edist_self; assumption
theorem mem_closed_ball_self : x ∈ closed_ball x ε :=
show edist x x ≤ ε, by rw edist_self; exact bot_le
theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε :=
by simp [edist_comm]
theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ :=
λ y (yx : _ < ε₁), lt_of_lt_of_le yx h
theorem closed_ball_subset_closed_ball (h : ε₁ ≤ ε₂) :
closed_ball x ε₁ ⊆ closed_ball x ε₂ :=
λ y (yx : _ ≤ ε₁), le_trans yx h
theorem ball_disjoint (h : ε₁ + ε₂ ≤ edist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ :=
eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩,
not_lt_of_le (edist_triangle_left x y z)
(lt_of_lt_of_le (ennreal.add_lt_add h₁ h₂) h)
theorem ball_subset (h : edist x y + ε₁ ≤ ε₂) (h' : edist x y < ⊤) : ball x ε₁ ⊆ ball y ε₂ :=
λ z zx, calc
edist z y ≤ edist z x + edist x y : edist_triangle _ _ _
... = edist x y + edist z x : add_comm _ _
... < edist x y + ε₁ : (ennreal.add_lt_add_iff_left h').2 zx
... ≤ ε₂ : h
theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε :=
begin
have : 0 < ε - edist y x := by simpa using h,
refine ⟨ε - edist y x, this, ball_subset _ _⟩,
{ rw ennreal.add_sub_cancel_of_le (le_of_lt h), apply le_refl _},
{ have : edist y x ≠ ⊤ := ne_top_of_lt h, apply lt_top_iff_ne_top.2 this }
end
theorem ball_eq_empty_iff : ball x ε = ∅ ↔ ε = 0 :=
eq_empty_iff_forall_not_mem.trans
⟨λh, le_bot_iff.1 (le_of_not_gt (λ ε0, h _ (mem_ball_self ε0))),
λε0 y h, not_lt_of_le (le_of_eq ε0) (pos_of_mem_ball h)⟩
/-- Relation “two points are at a finite edistance” is an equivalence relation. -/
def edist_lt_top_setoid : setoid α :=
{ r := λ x y, edist x y < ⊤,
iseqv := ⟨λ x, by { rw edist_self, exact ennreal.coe_lt_top },
λ x y h, by rwa edist_comm,
λ x y z hxy hyz, lt_of_le_of_lt (edist_triangle x y z) (ennreal.add_lt_top.2 ⟨hxy, hyz⟩)⟩ }
@[simp] lemma ball_zero : ball x 0 = ∅ :=
by rw [emetric.ball_eq_empty_iff]
theorem nhds_basis_eball : (𝓝 x).has_basis (λ ε:ennreal, 0 < ε) (ball x) :=
nhds_basis_uniformity uniformity_basis_edist
theorem nhds_eq : 𝓝 x = (⨅ε>0, principal (ball x ε)) :=
nhds_basis_eball.eq_binfi
theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_eball.mem_iff
theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s :=
by simp [is_open_iff_nhds, mem_nhds_iff]
theorem is_open_ball : is_open (ball x ε) :=
is_open_iff.2 $ λ y, exists_ball_subset_ball
theorem is_closed_ball_top : is_closed (ball x ⊤) :=
is_open_iff.2 $ λ y hy, ⟨⊤, ennreal.coe_lt_top, subset_compl_iff_disjoint.2 $
ball_disjoint $ by { rw ennreal.top_add, exact le_of_not_lt hy }⟩
theorem ball_mem_nhds (x : α) {ε : ennreal} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x :=
mem_nhds_sets is_open_ball (mem_ball_self ε0)
/-- ε-characterization of the closure in emetric spaces -/
@[nolint ge_or_gt] -- see Note [nolint_ge]
theorem mem_closure_iff :
x ∈ closure s ↔ ∀ε>0, ∃y ∈ s, edist x y < ε :=
(mem_closure_iff_nhds_basis nhds_basis_eball).trans $
by simp only [mem_ball, edist_comm x]
theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} :
tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, edist (u x) a < ε :=
nhds_basis_eball.tendsto_right_iff
theorem tendsto_at_top [nonempty β] [semilattice_sup β] (u : β → α) {a : α} :
tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, edist (u n) a < ε :=
(at_top_basis.tendsto_iff nhds_basis_eball).trans $
by simp only [exists_prop, true_and, mem_Ici, mem_ball]
/-- In an emetric space, Cauchy sequences are characterized by the fact that, eventually,
the edistance between its elements is arbitrarily small -/
theorem cauchy_seq_iff [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, edist (u m) (u n) < ε :=
uniformity_basis_edist.cauchy_seq_iff
/-- A variation around the emetric characterization of Cauchy sequences -/
theorem cauchy_seq_iff' [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ ∀ε>(0 : ennreal), ∃N, ∀n≥N, edist (u n) (u N) < ε :=
uniformity_basis_edist.cauchy_seq_iff'
/-- A variation of the emetric characterization of Cauchy sequences that deals with
`nnreal` upper bounds. -/
theorem cauchy_seq_iff_nnreal [nonempty β] [semilattice_sup β] {u : β → α} :
cauchy_seq u ↔ ∀ ε : nnreal, 0 < ε → ∃ N, ∀ n, N ≤ n → edist (u n) (u N) < ε :=
uniformity_basis_edist_nnreal.cauchy_seq_iff'
theorem totally_bounded_iff {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, H _ (edist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru,
⟨t, ft, h⟩ := H ε ε0 in
⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩
theorem totally_bounded_iff' {s : set α} :
totally_bounded s ↔ ∀ ε > 0, ∃t⊆s, finite t ∧ s ⊆ ⋃y∈t, ball y ε :=
⟨λ H ε ε0, (totally_bounded_iff_subset.1 H) _ (edist_mem_uniformity ε0),
λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_edist.1 ru,
⟨t, _, ft, h⟩ := H ε ε0 in
⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩
section compact
/-- A compact set in an emetric space is separable, i.e., it is the closure of a countable set -/
lemma countable_closure_of_compact {α : Type u} [emetric_space α] {s : set α} (hs : compact s) :
∃ t ⊆ s, (countable t ∧ s = closure t) :=
begin
have A : ∀ (e:ennreal), e > 0 → ∃ t ⊆ s, (finite t ∧ s ⊆ (⋃x∈t, ball x e)) :=
totally_bounded_iff'.1 (compact_iff_totally_bounded_complete.1 hs).1,
-- assume e, finite_cover_balls_of_compact hs,
have B : ∀ (e:ennreal), ∃ t ⊆ s, finite t ∧ (e > 0 → s ⊆ (⋃x∈t, ball x e)),
{ intro e,
cases le_or_gt e 0 with h,
{ exact ⟨∅, by finish⟩ },
{ rcases A e h with ⟨s, ⟨finite_s, closure_s⟩⟩, existsi s, finish }},
/-The desired countable set is obtained by taking for each `n` the centers of a finite cover
by balls of radius `1/n`, and then the union over `n`. -/
choose T T_in_s finite_T using B,
let t := ⋃n:ℕ, T n⁻¹,
have T₁ : t ⊆ s := begin apply Union_subset, assume n, apply T_in_s end,
have T₂ : countable t := by finish [countable_Union, finite.countable],
have T₃ : s ⊆ closure t,
{ intros x x_in_s,
apply mem_closure_iff.2,
intros ε εpos,
rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 εpos) with ⟨n, hn⟩,
have inv_n_pos : (0 : ennreal) < (n : ℕ)⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot],
have C : x ∈ (⋃y∈ T (n : ℕ)⁻¹, ball y (n : ℕ)⁻¹) :=
mem_of_mem_of_subset x_in_s ((finite_T (n : ℕ)⁻¹).2 inv_n_pos),
rcases mem_Union.1 C with ⟨y, _, ⟨y_in_T, rfl⟩, Dxy⟩,
simp at Dxy, -- Dxy : edist x y < 1 / ↑n
have : y ∈ t := mem_of_mem_of_subset y_in_T (by apply subset_Union (λ (n:ℕ), T (n : ℕ)⁻¹)),
have : edist x y < ε := lt_trans Dxy hn,
exact ⟨y, ‹y ∈ t›, ‹edist x y < ε›⟩ },
have T₄ : closure t ⊆ s := calc
closure t ⊆ closure s : closure_mono T₁
... = s : closure_eq_of_is_closed (closed_of_compact _ hs),
exact ⟨t, ⟨T₁, T₂, subset.antisymm T₃ T₄⟩⟩
end
end compact
section first_countable
@[priority 100] -- see Note [lower instance priority]
instance (α : Type u) [emetric_space α] :
topological_space.first_countable_topology α :=
uniform_space.first_countable_topology uniformity_has_countable_basis
end first_countable
section second_countable
open topological_space
/-- A separable emetric space is second countable: one obtains a countable basis by taking
the balls centered at points in a dense subset, and with rational radii. We do not register
this as an instance, as there is already an instance going in the other direction
from second countable spaces to separable spaces, and we want to avoid loops. -/
lemma second_countable_of_separable (α : Type u) [emetric_space α] [separable_space α] :
second_countable_topology α :=
let ⟨S, ⟨S_countable, S_dense⟩⟩ := separable_space.exists_countable_closure_eq_univ in
⟨⟨⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)},
⟨show countable ⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)},
{ apply S_countable.bUnion,
intros a aS,
apply countable_Union,
simp },
show uniform_space.to_topological_space = generate_from (⋃x ∈ S, ⋃ (n : nat), {ball x (n⁻¹)}),
{ have A : ∀ (u : set α), (u ∈ ⋃x ∈ S, ⋃ (n : nat), ({ball x ((n : ennreal)⁻¹)} : set (set α))) → is_open u,
{ simp only [and_imp, exists_prop, set.mem_Union, set.mem_singleton_iff, exists_imp_distrib],
intros u x hx i u_ball,
rw [u_ball],
exact is_open_ball },
have B : is_topological_basis (⋃x ∈ S, ⋃ (n : nat), ({ball x (n⁻¹)} : set (set α))),
{ refine is_topological_basis_of_open_of_nhds A (λa u au open_u, _),
rcases is_open_iff.1 open_u a au with ⟨ε, εpos, εball⟩,
have : ε / 2 > 0 := ennreal.half_pos εpos,
/- The ball `ball a ε` is included in `u`. We need to find one of our balls `ball x (n⁻¹)`
containing `a` and contained in `ball a ε`. For this, we take `n` larger than `2/ε`, and
then `x` in `S` at distance at most `n⁻¹` of `a` -/
rcases ennreal.exists_inv_nat_lt (bot_lt_iff_ne_bot.1 (ennreal.half_pos εpos)) with ⟨n, εn⟩,
have : (0 : ennreal) < n⁻¹ := by simp [ennreal.bot_lt_iff_ne_bot],
have : (a : α) ∈ closure (S : set α) := by rw [S_dense]; simp,
rcases mem_closure_iff.1 this _ ‹(0 : ennreal) < n⁻¹› with ⟨x, xS, xdist⟩,
existsi ball x (↑n)⁻¹,
have I : ball x (n⁻¹) ⊆ ball a ε := λy ydist, calc
edist y a = edist a y : edist_comm _ _
... ≤ edist a x + edist y x : edist_triangle_right _ _ _
... < n⁻¹ + n⁻¹ : ennreal.add_lt_add xdist ydist
... < ε/2 + ε/2 : ennreal.add_lt_add εn εn
... = ε : ennreal.add_halves _,
simp only [emetric.mem_ball, exists_prop, set.mem_Union, set.mem_singleton_iff],
exact ⟨⟨x, ⟨xS, ⟨n, rfl⟩⟩⟩, ⟨by simpa, subset.trans I εball⟩⟩ },
exact B.2.2 }⟩⟩⟩
end second_countable
section diam
/-- The diameter of a set in an emetric space, named `emetric.diam` -/
def diam (s : set α) := ⨆ (x ∈ s) (y ∈ s), edist x y
lemma diam_le_iff_forall_edist_le {d : ennreal} :
diam s ≤ d ↔ ∀ (x ∈ s) (y ∈ s), edist x y ≤ d :=
by simp only [diam, supr_le_iff]
/-- If two points belong to some set, their edistance is bounded by the diameter of the set -/
lemma edist_le_diam_of_mem (hx : x ∈ s) (hy : y ∈ s) : edist x y ≤ diam s :=
diam_le_iff_forall_edist_le.1 (le_refl _) x hx y hy
/-- If the distance between any two points in a set is bounded by some constant, this constant
bounds the diameter. -/
lemma diam_le_of_forall_edist_le {d : ennreal} (h : ∀ (x ∈ s) (y ∈ s), edist x y ≤ d) :
diam s ≤ d :=
diam_le_iff_forall_edist_le.2 h
/-- The diameter of a subsingleton vanishes. -/
lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 :=
le_zero_iff_eq.1 $ diam_le_of_forall_edist_le $
λ x hx y hy, (hs hx hy).symm ▸ edist_self y ▸ le_refl _
/-- The diameter of the empty set vanishes -/
@[simp] lemma diam_empty : diam (∅ : set α) = 0 :=
diam_subsingleton subsingleton_empty
/-- The diameter of a singleton vanishes -/
@[simp] lemma diam_singleton : diam ({x} : set α) = 0 :=
diam_subsingleton subsingleton_singleton
lemma diam_eq_zero_iff : diam s = 0 ↔ s.subsingleton :=
⟨λ h x hx y hy, edist_le_zero.1 $ h ▸ edist_le_diam_of_mem hx hy, diam_subsingleton⟩
lemma diam_pos_iff : 0 < diam s ↔ ∃ (x ∈ s) (y ∈ s), x ≠ y :=
begin
have := not_congr (@diam_eq_zero_iff _ _ s),
dunfold set.subsingleton at this,
push_neg at this,
simpa only [zero_lt_iff_ne_zero, exists_prop] using this
end
lemma diam_insert : diam (insert x s) = max (⨆ y ∈ s, edist x y) (diam s) :=
eq_of_forall_ge_iff $ λ d, by simp only [diam_le_iff_forall_edist_le, ball_insert_iff,
edist_self, edist_comm x, max_le_iff, supr_le_iff, zero_le, true_and,
forall_and_distrib, and_self, ← and_assoc]
lemma diam_pair : diam ({x, y} : set α) = edist x y :=
by simp only [supr_singleton, diam_insert, diam_singleton, ennreal.max_zero_right]
lemma diam_triple :
diam ({x, y, z} : set α) = max (max (edist x y) (edist x z)) (edist y z) :=
by simp only [diam_insert, supr_insert, supr_singleton, diam_singleton,
ennreal.max_zero_right, ennreal.sup_eq_max]
/-- The diameter is monotonous with respect to inclusion -/
lemma diam_mono {s t : set α} (h : s ⊆ t) : diam s ≤ diam t :=
diam_le_of_forall_edist_le $ λ x hx y hy, edist_le_diam_of_mem (h hx) (h hy)
/-- The diameter of a union is controlled by the diameter of the sets, and the edistance
between two points in the sets. -/
lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + edist x y + diam t :=
begin
have A : ∀a ∈ s, ∀b ∈ t, edist a b ≤ diam s + edist x y + diam t := λa ha b hb, calc
edist a b ≤ edist a x + edist x y + edist y b : edist_triangle4 _ _ _ _
... ≤ diam s + edist x y + diam t :
add_le_add' (add_le_add' (edist_le_diam_of_mem ha xs) (le_refl _)) (edist_le_diam_of_mem yt hb),
refine diam_le_of_forall_edist_le (λa ha b hb, _),
cases (mem_union _ _ _).1 ha with h'a h'a; cases (mem_union _ _ _).1 hb with h'b h'b,
{ calc edist a b ≤ diam s : edist_le_diam_of_mem h'a h'b
... ≤ diam s + (edist x y + diam t) : le_add_right (le_refl _)
... = diam s + edist x y + diam t : by simp only [add_comm, eq_self_iff_true, add_left_comm] },
{ exact A a h'a b h'b },
{ have Z := A b h'b a h'a, rwa [edist_comm] at Z },
{ calc edist a b ≤ diam t : edist_le_diam_of_mem h'a h'b
... ≤ (diam s + edist x y) + diam t : le_add_left (le_refl _) }
end
lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t :=
let ⟨x, ⟨xs, xt⟩⟩ := h in by simpa using diam_union xs xt
lemma diam_closed_ball {r : ennreal} : diam (closed_ball x r) ≤ 2 * r :=
diam_le_of_forall_edist_le $ λa ha b hb, calc
edist a b ≤ edist a x + edist b x : edist_triangle_right _ _ _
... ≤ r + r : add_le_add' ha hb
... = 2 * r : by simp [mul_two, mul_comm]
lemma diam_ball {r : ennreal} : diam (ball x r) ≤ 2 * r :=
le_trans (diam_mono ball_subset_closed_ball) diam_closed_ball
end diam
end emetric --namespace
|
8c6242569e2f63efae817211ff55865d76b81c80 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/group_with_zero/power.lean | a1019d3ab18a593670021275bd3adac2ae03eef8 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 11,445 | 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 algebra.group_power.lemmas
/-!
# Powers of elements of groups with an adjoined zero element
In this file we define integer power functions for groups with an adjoined zero element.
This generalises the integer power function on a division ring.
-/
section zero
variables {M : Type*} [monoid_with_zero M]
@[simp] lemma zero_pow' : ∀ n : ℕ, n ≠ 0 → (0 : M) ^ n = 0
| 0 h := absurd rfl h
| (k+1) h := by { rw [pow_succ], exact zero_mul _ }
lemma ne_zero_pow {a : M} {n : ℕ} (hn : n ≠ 0) : a ^ n ≠ 0 → a ≠ 0 :=
by { contrapose!, rintro rfl, exact zero_pow' n hn }
@[simp] lemma zero_pow_eq_zero [nontrivial M] {n : ℕ} : (0 : M) ^ n = 0 ↔ 0 < n :=
begin
split; intro h,
{ rw [pos_iff_ne_zero], rintro rfl, simpa using h },
{ exact zero_pow' n h.ne.symm }
end
lemma ring.inverse_pow (r : M) : ∀ (n : ℕ), ring.inverse r ^ n = ring.inverse (r ^ n)
| 0 := by rw [pow_zero, pow_zero, ring.inverse_one]
| (n + 1) := by rw [pow_succ, pow_succ', ring.mul_inverse_rev' ((commute.refl r).pow_left n),
ring.inverse_pow]
end zero
section group_with_zero
variables {G₀ : Type*} [group_with_zero G₀] {a : G₀} {m n : ℕ}
section nat_pow
@[simp, field_simps] theorem inv_pow₀ (a : G₀) (n : ℕ) : (a⁻¹) ^ n = (a ^ n)⁻¹ :=
begin
induction n with n ih,
{ rw [pow_zero, pow_zero], exact inv_one.symm },
{ rw [pow_succ', pow_succ, ih, mul_inv_rev₀] }
end
theorem pow_sub₀ (a : G₀) {m n : ℕ} (ha : a ≠ 0) (h : n ≤ m) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ :=
have h1 : m - n + n = m, from tsub_add_cancel_of_le h,
have h2 : a ^ (m - n) * a ^ n = a ^ m, by rw [←pow_add, h1],
by simpa only [div_eq_mul_inv] using eq_div_of_mul_eq (pow_ne_zero _ ha) h2
lemma pow_sub_of_lt (a : G₀) {m n : ℕ} (h : n < m) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ :=
begin
obtain rfl | ha := eq_or_ne a 0,
{ rw [zero_pow (tsub_pos_of_lt h), zero_pow (n.zero_le.trans_lt h), zero_mul] },
{ exact pow_sub₀ _ ha h.le }
end
theorem pow_inv_comm₀ (a : G₀) (m n : ℕ) : (a⁻¹) ^ m * a ^ n = a ^ n * (a⁻¹) ^ m :=
(commute.refl a).inv_left₀.pow_pow m n
lemma inv_pow_sub₀ (ha : a ≠ 0) (h : n ≤ m) : a⁻¹ ^ (m - n) = (a ^ m)⁻¹ * a ^ n :=
by rw [pow_sub₀ _ (inv_ne_zero ha) h, inv_pow₀, inv_pow₀, inv_inv₀]
lemma inv_pow_sub_of_lt (a : G₀) (h : n < m) : a⁻¹ ^ (m - n) = (a ^ m)⁻¹ * a ^ n :=
by rw [pow_sub_of_lt a⁻¹ h, inv_pow₀, inv_pow₀, inv_inv₀]
end nat_pow
end group_with_zero
section zpow
open int
variables {G₀ : Type*} [group_with_zero G₀]
local attribute [ematch] le_of_lt
@[simp] theorem one_zpow₀ : ∀ (n : ℤ), (1 : G₀) ^ n = 1
| (n : ℕ) := by rw [zpow_coe_nat, one_pow]
| -[1+ n] := by rw [zpow_neg_succ_of_nat, one_pow, inv_one]
lemma zero_zpow : ∀ z : ℤ, z ≠ 0 → (0 : G₀) ^ z = 0
| (n : ℕ) h := by { rw [zpow_coe_nat, zero_pow'], simpa using h }
| -[1+n] h := by simp
lemma zero_zpow_eq (n : ℤ) : (0 : G₀) ^ n = if n = 0 then 1 else 0 :=
begin
split_ifs with h,
{ rw [h, zpow_zero] },
{ rw [zero_zpow _ h] }
end
@[simp] theorem zpow_neg₀ (a : G₀) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹
| (n+1:ℕ) := div_inv_monoid.zpow_neg' _ _
| 0 := by { change a ^ (0 : ℤ) = (a ^ (0 : ℤ))⁻¹, simp }
| -[1+ n] := by { rw [zpow_neg_succ_of_nat, inv_inv₀, ← zpow_coe_nat], refl }
lemma mul_zpow_neg_one₀ (a b : G₀) : (a * b) ^ (-1 : ℤ) = b ^ (-1 : ℤ) * a ^ (-1 : ℤ) :=
by simp only [mul_inv_rev₀, zpow_one, zpow_neg₀]
lemma zpow_neg_one₀ (x : G₀) : x ^ (-1 : ℤ) = x⁻¹ :=
by { rw [← congr_arg has_inv.inv (pow_one x), zpow_neg₀, ← zpow_coe_nat], refl }
theorem inv_zpow₀ (a : G₀) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹
| (n : ℕ) := by rw [zpow_coe_nat, zpow_coe_nat, inv_pow₀]
| -[1+ n] := by rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, inv_pow₀]
lemma zpow_add_one₀ {a : G₀} (ha : a ≠ 0) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a
| (n : ℕ) := by simp [← int.coe_nat_succ, pow_succ']
| -[1+0] := by simp [int.neg_succ_of_nat_eq, ha]
| -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, zpow_neg₀, neg_add, neg_add_cancel_right, zpow_neg₀,
← int.coe_nat_succ, zpow_coe_nat, zpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev₀, mul_assoc,
inv_mul_cancel ha, mul_one]
lemma zpow_sub_one₀ {a : G₀} (ha : a ≠ 0) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ :=
calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : by rw [mul_assoc, mul_inv_cancel ha, mul_one]
... = a^n * a⁻¹ : by rw [← zpow_add_one₀ ha, sub_add_cancel]
lemma zpow_add₀ {a : G₀} (ha : a ≠ 0) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n :=
begin
induction n using int.induction_on with n ihn n ihn,
case hz : { simp },
{ simp only [← add_assoc, zpow_add_one₀ ha, ihn, mul_assoc] },
{ rw [zpow_sub_one₀ ha, ← mul_assoc, ← ihn, ← zpow_sub_one₀ ha, add_sub_assoc] }
end
lemma zpow_add' {a : G₀} {m n : ℤ} (h : a ≠ 0 ∨ m + n ≠ 0 ∨ m = 0 ∧ n = 0) :
a ^ (m + n) = a ^ m * a ^ n :=
begin
by_cases hm : m = 0, { simp [hm] },
by_cases hn : n = 0, { simp [hn] },
by_cases ha : a = 0,
{ subst a,
simp only [false_or, eq_self_iff_true, not_true, ne.def, hm, hn, false_and, or_false] at h,
rw [zero_zpow _ h, zero_zpow _ hm, zero_mul] },
{ exact zpow_add₀ ha m n }
end
theorem zpow_one_add₀ {a : G₀} (h : a ≠ 0) (i : ℤ) : a ^ (1 + i) = a * a ^ i :=
by rw [zpow_add₀ h, zpow_one]
theorem semiconj_by.zpow_right₀ {a x y : G₀} (h : semiconj_by a x y) :
∀ m : ℤ, semiconj_by a (x^m) (y^m)
| (n : ℕ) := by simp [h.pow_right n]
| -[1+n] := by simp [(h.pow_right (n + 1)).inv_right₀]
theorem commute.zpow_right₀ {a b : G₀} (h : commute a b) : ∀ m : ℤ, commute a (b^m) :=
h.zpow_right₀
theorem commute.zpow_left₀ {a b : G₀} (h : commute a b) (m : ℤ) : commute (a^m) b :=
(h.symm.zpow_right₀ m).symm
theorem commute.zpow_zpow₀ {a b : G₀} (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) :=
(h.zpow_left₀ m).zpow_right₀ n
theorem commute.zpow_self₀ (a : G₀) (n : ℤ) : commute (a^n) a := (commute.refl a).zpow_left₀ n
theorem commute.self_zpow₀ (a : G₀) (n : ℤ) : commute a (a^n) := (commute.refl a).zpow_right₀ n
theorem commute.zpow_zpow_self₀ (a : G₀) (m n : ℤ) : commute (a^m) (a^n) :=
(commute.refl a).zpow_zpow₀ m n
theorem zpow_bit0₀ (a : G₀) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n :=
begin
apply zpow_add', right,
by_cases hn : n = 0,
{ simp [hn] },
{ simp [← two_mul, hn, two_ne_zero] }
end
theorem zpow_bit1₀ (a : G₀) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a :=
begin
rw [← zpow_bit0₀, bit1, zpow_add', zpow_one],
right, left,
apply bit1_ne_zero
end
theorem zpow_mul₀ (a : G₀) : ∀ m n : ℤ, a ^ (m * n) = (a ^ m) ^ n
| (m : ℕ) (n : ℕ) := by { rw [zpow_coe_nat, zpow_coe_nat, ← pow_mul, ← zpow_coe_nat], refl }
| (m : ℕ) -[1+ n] := by { rw [zpow_coe_nat, zpow_neg_succ_of_nat, ← pow_mul, coe_nat_mul_neg_succ,
zpow_neg₀, inv_inj₀, ← zpow_coe_nat], refl }
| -[1+ m] (n : ℕ) := by { rw [zpow_coe_nat, zpow_neg_succ_of_nat, ← inv_pow₀, ← pow_mul,
neg_succ_mul_coe_nat, zpow_neg₀, inv_pow₀, inv_inj₀, ← zpow_coe_nat], refl }
| -[1+ m] -[1+ n] := by { rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, neg_succ_mul_neg_succ,
inv_pow₀, inv_inv₀, ← pow_mul, ← zpow_coe_nat], refl }
theorem zpow_mul₀' (a : G₀) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m :=
by rw [mul_comm, zpow_mul₀]
@[simp, norm_cast] lemma units.coe_zpow₀ (u : G₀ˣ) :
∀ (n : ℤ), ((u ^ n : G₀ˣ) : G₀) = u ^ n
| (n : ℕ) := by { rw [zpow_coe_nat, zpow_coe_nat], exact u.coe_pow n }
| -[1+k] := by rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat, units.coe_inv', u.coe_pow]
lemma zpow_ne_zero_of_ne_zero {a : G₀} (ha : a ≠ 0) : ∀ (z : ℤ), a ^ z ≠ 0
| (n : ℕ) := by { rw zpow_coe_nat, exact pow_ne_zero _ ha }
| -[1+n] := by { rw zpow_neg_succ_of_nat, exact inv_ne_zero (pow_ne_zero _ ha) }
lemma zpow_sub₀ {a : G₀} (ha : a ≠ 0) (z1 z2 : ℤ) : a ^ (z1 - z2) = a ^ z1 / a ^ z2 :=
by rw [sub_eq_add_neg, zpow_add₀ ha, zpow_neg₀, div_eq_mul_inv]
lemma commute.mul_zpow₀ {a b : G₀} (h : commute a b) :
∀ (i : ℤ), (a * b) ^ i = (a ^ i) * (b ^ i)
| (n : ℕ) := by simp [h.mul_pow n]
| -[1+n] := by simp [h.mul_pow, (h.pow_pow _ _).eq, mul_inv_rev₀]
theorem zpow_bit0' (a : G₀) (n : ℤ) : a ^ bit0 n = (a * a) ^ n :=
(zpow_bit0₀ a n).trans ((commute.refl a).mul_zpow₀ n).symm
theorem zpow_bit1' (a : G₀) (n : ℤ) : a ^ bit1 n = (a * a) ^ n * a :=
by rw [zpow_bit1₀, (commute.refl a).mul_zpow₀]
lemma zpow_eq_zero {x : G₀} {n : ℤ} (h : x ^ n = 0) : x = 0 :=
classical.by_contradiction $ λ hx, zpow_ne_zero_of_ne_zero hx n h
lemma zpow_ne_zero {x : G₀} (n : ℤ) : x ≠ 0 → x ^ n ≠ 0 :=
mt zpow_eq_zero
theorem zpow_neg_mul_zpow_self (n : ℤ) {x : G₀} (h : x ≠ 0) :
x ^ (-n) * x ^ n = 1 :=
begin
rw [zpow_neg₀],
exact inv_mul_cancel (zpow_ne_zero n h)
end
theorem one_div_pow {a : G₀} (n : ℕ) :
(1 / a) ^ n = 1 / a ^ n :=
by simp only [one_div, inv_pow₀]
theorem one_div_zpow {a : G₀} (n : ℤ) :
(1 / a) ^ n = 1 / a ^ n :=
by simp only [one_div, inv_zpow₀]
@[simp] lemma inv_zpow' {a : G₀} (n : ℤ) :
(a ⁻¹) ^ n = a ^ (-n) :=
by { rw [inv_zpow₀, ← zpow_neg_one, ← zpow_mul₀], simp }
end zpow
section
variables {G₀ : Type*} [comm_group_with_zero G₀]
@[simp] theorem div_pow (a b : G₀) (n : ℕ) :
(a / b) ^ n = a ^ n / b ^ n :=
by simp only [div_eq_mul_inv, mul_pow, inv_pow₀]
lemma mul_zpow₀ (a b : G₀) (m : ℤ) : (a * b) ^ m = (a ^ m) * (b ^ m) :=
(commute.all a b).mul_zpow₀ m
@[simp] theorem div_zpow₀ (a : G₀) {b : G₀} (n : ℤ) :
(a / b) ^ n = a ^ n / b ^ n :=
by simp only [div_eq_mul_inv, mul_zpow₀, inv_zpow₀]
lemma div_sq_cancel (a b : G₀) : a ^ 2 * b / a = a * b :=
begin
by_cases ha : a = 0,
{ simp [ha] },
rw [sq, mul_assoc, mul_div_cancel_left _ ha]
end
/-- The `n`-th power map (`n` an integer) on a commutative group with zero, considered as a group
homomorphism. -/
def zpow_group_hom₀ (n : ℤ) : G₀ →* G₀ :=
{ to_fun := (^ n),
map_one' := one_zpow₀ n,
map_mul' := λ a b, mul_zpow₀ a b n }
end
/-- If a monoid homomorphism `f` between two `group_with_zero`s maps `0` to `0`, then it maps `x^n`,
`n : ℤ`, to `(f x)^n`. -/
lemma monoid_with_zero_hom.map_zpow {G₀ G₀' : Type*} [group_with_zero G₀] [group_with_zero G₀']
(f : G₀ →*₀ G₀') (x : G₀) :
∀ n : ℤ, f (x ^ n) = f x ^ n
| (n : ℕ) := by { rw [zpow_coe_nat, zpow_coe_nat], exact f.to_monoid_hom.map_pow x n }
| -[1+n] := begin
rw [zpow_neg_succ_of_nat, zpow_neg_succ_of_nat],
exact ((f.map_inv _).trans $ congr_arg _ $ f.to_monoid_hom.map_pow x _)
end
-- I haven't been able to find a better home for this:
-- it belongs with other lemmas on `linear_ordered_field`, but
-- we need to wait until `zpow` has been defined in this file.
section
variables {R : Type*} [linear_ordered_field R] {a : R}
lemma pow_minus_two_nonneg : 0 ≤ a^(-2 : ℤ) :=
begin
simp only [inv_nonneg, zpow_neg₀],
change 0 ≤ a ^ ((2 : ℕ) : ℤ),
rw zpow_coe_nat,
apply sq_nonneg,
end
end
|
76f3733b1e70931a2552a7f18b7760e05e434557 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/logic/basic.lean | 2e3e3fa1a13f74f8fa2c461cef3ac9e3d21b2ab9 | [] | 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 | 63,573 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.doc_commands
import Mathlib.tactic.reserved_notation
import Mathlib.PostPort
universes u_1 u_2 u_3 u_4 u l w v
namespace Mathlib
/-!
# Basic logic properties
This file is one of the earliest imports in mathlib.
## Implementation notes
Theorems that require decidability hypotheses are in the namespace "decidable".
Classical versions are in the namespace "classical".
In the presence of automation, this whole file may be unnecessary. On the other hand,
maybe it is useful for writing automation.
-/
/- We add the `inline` attribute to optimize VM computation using these declarations. For example,
`if p ∧ q then ... else ...` will not evaluate the decidability of `q` if `p` is false. -/
/-- An identity function with its main argument implicit. This will be printed as `hidden` even
if it is applied to a large term, so it can be used for elision,
as done in the `elide` and `unelide` tactics. -/
def hidden {α : Sort u_1} {a : α} : α :=
a
/-- Ex falso, the nondependent eliminator for the `empty` type. -/
def empty.elim {C : Sort u_1} : empty → C :=
sorry
protected instance empty.subsingleton : subsingleton empty :=
subsingleton.intro fun (a : empty) => empty.elim a
protected instance subsingleton.prod {α : Type u_1} {β : Type u_2} [subsingleton α] [subsingleton β] : subsingleton (α × β) :=
subsingleton.intro
fun (a b : α × β) =>
prod.cases_on a
fun (a_fst : α) (a_snd : β) =>
prod.cases_on b
fun (b_fst : α) (b_snd : β) =>
(fun (fst fst_1 : α) (snd snd_1 : β) =>
Eq.trans ((fun (fst : α) (snd : β) => Eq.refl (fst, snd)) fst snd)
(congr (congr (Eq.refl Prod.mk) (subsingleton.elim fst fst_1)) (subsingleton.elim snd snd_1)))
a_fst b_fst a_snd b_snd
protected instance empty.decidable_eq : DecidableEq empty :=
fun (a : empty) => empty.elim a
protected instance sort.inhabited : Inhabited (Sort u_1) :=
{ default := PUnit }
protected instance sort.inhabited' : Inhabited Inhabited.default :=
{ default := PUnit.unit }
protected instance psum.inhabited_left {α : Sort u_1} {β : Sort u_2} [Inhabited α] : Inhabited (psum α β) :=
{ default := psum.inl Inhabited.default }
protected instance psum.inhabited_right {α : Sort u_1} {β : Sort u_2} [Inhabited β] : Inhabited (psum α β) :=
{ default := psum.inr Inhabited.default }
protected instance decidable_eq_of_subsingleton {α : Sort u_1} [subsingleton α] : DecidableEq α :=
sorry
@[simp] theorem eq_iff_true_of_subsingleton {α : Type u_1} [subsingleton α] (x : α) (y : α) : x = y ↔ True :=
of_eq_true (Eq.trans (iff_eq_of_eq_true_right (Eq.refl True)) (eq_true_intro (Eq.symm (subsingleton.elim y x))))
/-- Add an instance to "undo" coercion transitivity into a chain of coercions, because
most simp lemmas are stated with respect to simple coercions and will not match when
part of a chain. -/
@[simp] theorem coe_coe {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} [has_coe α β] [has_coe_t β γ] (a : α) : ↑a = ↑↑a :=
rfl
theorem coe_fn_coe_trans {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_fun γ] (x : α) : ⇑x = ⇑↑x :=
rfl
@[simp] theorem coe_fn_coe_base {α : Sort u_1} {β : Sort u_2} [has_coe α β] [has_coe_to_fun β] (x : α) : ⇑x = ⇑↑x :=
rfl
theorem coe_sort_coe_trans {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} [has_coe α β] [has_coe_t_aux β γ] [has_coe_to_sort γ] (x : α) : ↥x = ↥↑x :=
rfl
/--
Many structures such as bundled morphisms coerce to functions so that you can
transparently apply them to arguments. For example, if `e : α ≃ β` and `a : α`
then you can write `e a` and this is elaborated as `⇑e a`. This type of
coercion is implemented using the `has_coe_to_fun` type class. There is one
important consideration:
If a type coerces to another type which in turn coerces to a function,
then it **must** implement `has_coe_to_fun` directly:
```lean
structure sparkling_equiv (α β) extends α ≃ β
-- if we add a `has_coe` instance,
-- if we add a `has_coe` instance,
instance {α β} : has_coe (sparkling_equiv α β) (α ≃ β) :=
⟨sparkling_equiv.to_equiv⟩
-- then a `has_coe_to_fun` instance **must** be added as well:
-- then a `has_coe_to_fun` instance **must** be added as well:
instance {α β} : has_coe_to_fun (sparkling_equiv α β) :=
⟨λ _, α → β, λ f, f.to_equiv.to_fun⟩
```
(Rationale: if we do not declare the direct coercion, then `⇑e a` is not in
simp-normal form. The lemma `coe_fn_coe_base` will unfold it to `⇑↑e a`. This
often causes loops in the simplifier.)
-/
@[simp] theorem coe_sort_coe_base {α : Sort u_1} {β : Sort u_2} [has_coe α β] [has_coe_to_sort β] (x : α) : ↥x = ↥↑x :=
rfl
/-- `pempty` is the universe-polymorphic analogue of `empty`. -/
inductive pempty
where
/-- Ex falso, the nondependent eliminator for the `pempty` type. -/
def pempty.elim {C : Sort u_1} : pempty → C :=
sorry
protected instance subsingleton_pempty : subsingleton pempty :=
subsingleton.intro fun (a : pempty) => pempty.elim a
@[simp] theorem not_nonempty_pempty : ¬Nonempty pempty :=
fun (_x : Nonempty pempty) =>
(fun (_a : Nonempty pempty) => nonempty.dcases_on _a fun (val : pempty) => idRhs False (pempty.elim val)) _x
@[simp] theorem forall_pempty {P : pempty → Prop} : (∀ (x : pempty), P x) ↔ True :=
{ mp := fun (h : ∀ (x : pempty), P x) => trivial,
mpr := fun (h : True) (x : pempty) => pempty.cases_on (fun (x : pempty) => P x) x }
@[simp] theorem exists_pempty {P : pempty → Prop} : (∃ (x : pempty), P x) ↔ False := sorry
theorem congr_arg_heq {α : Sort u_1} {β : α → Sort u_2} (f : (a : α) → β a) {a₁ : α} {a₂ : α} : a₁ = a₂ → f a₁ == f a₂ := sorry
theorem plift.down_inj {α : Sort u_1} (a : plift α) (b : plift α) : plift.down a = plift.down b → a = b := sorry
-- missing [symm] attribute for ne in core.
theorem ne_comm {α : Sort u_1} {a : α} {b : α} : a ≠ b ↔ b ≠ a :=
{ mp := ne.symm, mpr := ne.symm }
@[simp] theorem eq_iff_eq_cancel_left {α : Type u_1} {b : α} {c : α} : (∀ {a : α}, a = b ↔ a = c) ↔ b = c :=
{ mp :=
fun (h : ∀ {a : α}, a = b ↔ a = c) => eq.mpr (id (Eq._oldrec (Eq.refl (b = c)) (Eq.symm (propext h)))) (Eq.refl b),
mpr := fun (h : b = c) (a : α) => eq.mpr (id (Eq._oldrec (Eq.refl (a = b ↔ a = c)) h)) (iff.refl (a = c)) }
@[simp] theorem eq_iff_eq_cancel_right {α : Type u_1} {a : α} {b : α} : (∀ {c : α}, a = c ↔ b = c) ↔ a = b :=
{ mp := fun (h : ∀ {c : α}, a = c ↔ b = c) => eq.mpr (id (Eq._oldrec (Eq.refl (a = b)) (propext h))) (Eq.refl b),
mpr := fun (h : a = b) (a_1 : α) => eq.mpr (id (Eq._oldrec (Eq.refl (a = a_1 ↔ b = a_1)) h)) (iff.refl (b = a_1)) }
/-- Wrapper for adding elementary propositions to the type class systems.
Warning: this can easily be abused. See the rest of this docstring for details.
Certain propositions should not be treated as a class globally,
but sometimes it is very convenient to be able to use the type class system
in specific circumstances.
For example, `zmod p` is a field if and only if `p` is a prime number.
In order to be able to find this field instance automatically by type class search,
we have to turn `p.prime` into an instance implicit assumption.
On the other hand, making `nat.prime` a class would require a major refactoring of the library,
and it is questionable whether making `nat.prime` a class is desirable at all.
The compromise is to add the assumption `[fact p.prime]` to `zmod.field`.
In particular, this class is not intended for turning the type class system
into an automated theorem prover for first order logic. -/
def fact (p : Prop) :=
p
theorem fact.elim {p : Prop} (h : fact p) : p :=
h
/-!
### Declarations about propositional connectives
-/
theorem false_ne_true : False ≠ True :=
fun (ᾰ : False = True) => idRhs ((fun (_x : Prop) => _x) False) (Eq.symm ᾰ ▸ trivial)
/-! ### Declarations about `implies` -/
theorem iff_of_eq {a : Prop} {b : Prop} (e : a = b) : a ↔ b :=
e ▸ iff.rfl
theorem iff_iff_eq {a : Prop} {b : Prop} : a ↔ b ↔ a = b :=
{ mp := propext, mpr := iff_of_eq }
@[simp] theorem eq_iff_iff {p : Prop} {q : Prop} : p = q ↔ (p ↔ q) :=
iff.symm iff_iff_eq
@[simp] theorem imp_self {a : Prop} : a → a ↔ True :=
iff_true_intro id
theorem imp_intro {α : Prop} {β : Prop} (h : α) : β → α :=
fun (_x : β) => h
theorem imp_false {a : Prop} : a → False ↔ ¬a :=
iff.rfl
theorem imp_and_distrib {b : Prop} {c : Prop} {α : Sort u_1} : α → b ∧ c ↔ (α → b) ∧ (α → c) :=
{ mp := fun (h : α → b ∧ c) => { left := fun (ha : α) => and.left (h ha), right := fun (ha : α) => and.right (h ha) },
mpr := fun (h : (α → b) ∧ (α → c)) (ha : α) => { left := and.left h ha, right := and.right h ha } }
@[simp] theorem and_imp {a : Prop} {b : Prop} {c : Prop} : a ∧ b → c ↔ a → b → c := sorry
theorem iff_def {a : Prop} {b : Prop} : a ↔ b ↔ (a → b) ∧ (b → a) :=
iff_iff_implies_and_implies a b
theorem iff_def' {a : Prop} {b : Prop} : a ↔ b ↔ (b → a) ∧ (a → b) :=
iff.trans iff_def and.comm
theorem imp_true_iff {α : Sort u_1} : α → True ↔ True :=
iff_true_intro fun (_x : α) => trivial
@[simp] theorem imp_iff_right {a : Prop} {b : Prop} (ha : a) : a → b ↔ b :=
{ mp := fun (f : a → b) => f ha, mpr := imp_intro }
/-! ### Declarations about `not` -/
/-- Ex falso for negation. From `¬ a` and `a` anything follows. This is the same as `absurd` with
the arguments flipped, but it is in the `not` namespace so that projection notation can be used. -/
def not.elim {a : Prop} {α : Sort u_1} (H1 : ¬a) (H2 : a) : α :=
absurd H2 H1
theorem not.imp {a : Prop} {b : Prop} (H2 : ¬b) (H1 : a → b) : ¬a :=
mt H1 H2
theorem not_not_of_not_imp {a : Prop} {b : Prop} : ¬(a → b) → ¬¬a :=
mt not.elim
theorem not_of_not_imp {b : Prop} {a : Prop} : ¬(a → b) → ¬b :=
mt imp_intro
theorem dec_em (p : Prop) [Decidable p] : p ∨ ¬p :=
decidable.em p
theorem em (p : Prop) : p ∨ ¬p :=
classical.em p
theorem or_not {p : Prop} : p ∨ ¬p :=
em p
theorem by_contradiction {p : Prop} : (¬p → False) → p :=
decidable.by_contradiction
-- alias by_contradiction ← by_contra
theorem by_contra {p : Prop} : (¬p → False) → p :=
decidable.by_contradiction
/--
In most of mathlib, we use the law of excluded middle (LEM) and the axiom of choice (AC) freely.
The `decidable` namespace contains versions of lemmas from the root namespace that explicitly
attempt to avoid the axiom of choice, usually by adding decidability assumptions on the inputs.
You can check if a lemma uses the axiom of choice by using `#print axioms foo` and seeing if
`classical.choice` appears in the list.
-/
-- See Note [decidable namespace]
protected theorem decidable.not_not {a : Prop} [Decidable a] : ¬¬a ↔ a :=
{ mp := decidable.by_contradiction, mpr := not_not_intro }
/-- The Double Negation Theorem: `¬ ¬ P` is equivalent to `P`.
The left-to-right direction, double negation elimination (DNE),
is classically true but not constructively. -/
@[simp] theorem not_not {a : Prop} : ¬¬a ↔ a :=
decidable.not_not
theorem of_not_not {a : Prop} : ¬¬a → a :=
by_contra
-- See Note [decidable namespace]
protected theorem decidable.of_not_imp {a : Prop} {b : Prop} [Decidable a] (h : ¬(a → b)) : a :=
decidable.by_contradiction (not_not_of_not_imp h)
theorem of_not_imp {a : Prop} {b : Prop} : ¬(a → b) → a :=
decidable.of_not_imp
-- See Note [decidable namespace]
protected theorem decidable.not_imp_symm {a : Prop} {b : Prop} [Decidable a] (h : ¬a → b) (hb : ¬b) : a :=
decidable.by_contradiction (hb ∘ h)
theorem not.decidable_imp_symm {a : Prop} {b : Prop} [Decidable a] : (¬a → b) → ¬b → a :=
decidable.not_imp_symm
theorem not.imp_symm {a : Prop} {b : Prop} : (¬a → b) → ¬b → a :=
not.decidable_imp_symm
-- See Note [decidable namespace]
protected theorem decidable.not_imp_comm {a : Prop} {b : Prop} [Decidable a] [Decidable b] : ¬a → b ↔ ¬b → a :=
{ mp := not.decidable_imp_symm, mpr := not.decidable_imp_symm }
theorem not_imp_comm {a : Prop} {b : Prop} : ¬a → b ↔ ¬b → a :=
decidable.not_imp_comm
@[simp] theorem imp_not_self {a : Prop} : a → ¬a ↔ ¬a :=
{ mp := fun (h : a → ¬a) (ha : a) => h ha ha, mpr := fun (h : ¬a) (_x : a) => h }
theorem decidable.not_imp_self {a : Prop} [Decidable a] : ¬a → a ↔ a :=
eq.mp (Eq._oldrec (Eq.refl (¬a → ¬¬a ↔ ¬¬a)) (propext decidable.not_not)) imp_not_self
@[simp] theorem not_imp_self {a : Prop} : ¬a → a ↔ a :=
decidable.not_imp_self
theorem imp.swap {a : Prop} {b : Prop} {c : Prop} : a → b → c ↔ b → a → c :=
{ mp := function.swap, mpr := function.swap }
theorem imp_not_comm {a : Prop} {b : Prop} : a → ¬b ↔ b → ¬a :=
imp.swap
/-! ### Declarations about `and` -/
theorem and_congr_left {a : Prop} {b : Prop} {c : Prop} (h : c → (a ↔ b)) : a ∧ c ↔ b ∧ c :=
iff.trans and.comm (iff.trans (and_congr_right h) and.comm)
theorem and_congr_left' {a : Prop} {b : Prop} {c : Prop} (h : a ↔ b) : a ∧ c ↔ b ∧ c :=
and_congr h iff.rfl
theorem and_congr_right' {a : Prop} {b : Prop} {c : Prop} (h : b ↔ c) : a ∧ b ↔ a ∧ c :=
and_congr iff.rfl h
theorem not_and_of_not_left {a : Prop} (b : Prop) : ¬a → ¬(a ∧ b) :=
mt and.left
theorem not_and_of_not_right (a : Prop) {b : Prop} : ¬b → ¬(a ∧ b) :=
mt and.right
theorem and.imp_left {a : Prop} {b : Prop} {c : Prop} (h : a → b) : a ∧ c → b ∧ c :=
and.imp h id
theorem and.imp_right {a : Prop} {b : Prop} {c : Prop} (h : a → b) : c ∧ a → c ∧ b :=
and.imp id h
theorem and.right_comm {a : Prop} {b : Prop} {c : Prop} : (a ∧ b) ∧ c ↔ (a ∧ c) ∧ b := sorry
theorem and.rotate {a : Prop} {b : Prop} {c : Prop} : a ∧ b ∧ c ↔ b ∧ c ∧ a := sorry
theorem and_not_self_iff (a : Prop) : a ∧ ¬a ↔ False :=
{ mp := fun (h : a ∧ ¬a) => and.right h (and.left h), mpr := fun (h : False) => false.elim h }
theorem not_and_self_iff (a : Prop) : ¬a ∧ a ↔ False := sorry
theorem and_iff_left_of_imp {a : Prop} {b : Prop} (h : a → b) : a ∧ b ↔ a :=
{ mp := and.left, mpr := fun (ha : a) => { left := ha, right := h ha } }
theorem and_iff_right_of_imp {a : Prop} {b : Prop} (h : b → a) : a ∧ b ↔ b :=
{ mp := and.right, mpr := fun (hb : b) => { left := h hb, right := hb } }
@[simp] theorem and_iff_left_iff_imp {a : Prop} {b : Prop} : a ∧ b ↔ a ↔ a → b :=
{ mp := fun (h : a ∧ b ↔ a) (ha : a) => and.right (iff.mpr h ha), mpr := and_iff_left_of_imp }
@[simp] theorem and_iff_right_iff_imp {a : Prop} {b : Prop} : a ∧ b ↔ b ↔ b → a :=
{ mp := fun (h : a ∧ b ↔ b) (ha : b) => and.left (iff.mpr h ha), mpr := and_iff_right_of_imp }
@[simp] theorem and.congr_right_iff {a : Prop} {b : Prop} {c : Prop} : a ∧ b ↔ a ∧ c ↔ a → (b ↔ c) := sorry
@[simp] theorem and.congr_left_iff {a : Prop} {b : Prop} {c : Prop} : a ∧ c ↔ b ∧ c ↔ c → (a ↔ b) := sorry
@[simp] theorem and_self_left {a : Prop} {b : Prop} : a ∧ a ∧ b ↔ a ∧ b :=
{ mp := fun (h : a ∧ a ∧ b) => { left := and.left h, right := and.right (and.right h) },
mpr := fun (h : a ∧ b) => { left := and.left h, right := { left := and.left h, right := and.right h } } }
@[simp] theorem and_self_right {a : Prop} {b : Prop} : (a ∧ b) ∧ b ↔ a ∧ b :=
{ mp := fun (h : (a ∧ b) ∧ b) => { left := and.left (and.left h), right := and.right h },
mpr := fun (h : a ∧ b) => { left := { left := and.left h, right := and.right h }, right := and.right h } }
/-! ### Declarations about `or` -/
theorem or_congr_left {a : Prop} {b : Prop} {c : Prop} (h : a ↔ b) : a ∨ c ↔ b ∨ c :=
or_congr h iff.rfl
theorem or_congr_right {a : Prop} {b : Prop} {c : Prop} (h : b ↔ c) : a ∨ b ↔ a ∨ c :=
or_congr iff.rfl h
theorem or.right_comm {a : Prop} {b : Prop} {c : Prop} : (a ∨ b) ∨ c ↔ (a ∨ c) ∨ b :=
eq.mpr (id (Eq._oldrec (Eq.refl ((a ∨ b) ∨ c ↔ (a ∨ c) ∨ b)) (propext (or_assoc a b))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ∨ c ↔ (a ∨ c) ∨ b)) (propext (or_assoc a c))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ∨ c ↔ a ∨ c ∨ b)) (propext (or_comm b c)))) (iff.refl (a ∨ c ∨ b))))
theorem or_of_or_of_imp_of_imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → d) : c ∨ d :=
or.imp h₂ h₃ h₁
theorem or_of_or_of_imp_left {a : Prop} {b : Prop} {c : Prop} (h₁ : a ∨ c) (h : a → b) : b ∨ c :=
or.imp_left h h₁
theorem or_of_or_of_imp_right {a : Prop} {b : Prop} {c : Prop} (h₁ : c ∨ a) (h : a → b) : c ∨ b :=
or.imp_right h h₁
theorem or.elim3 {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h : a ∨ b ∨ c) (ha : a → d) (hb : b → d) (hc : c → d) : d :=
or.elim h ha fun (h₂ : b ∨ c) => or.elim h₂ hb hc
theorem or_imp_distrib {a : Prop} {b : Prop} {c : Prop} : a ∨ b → c ↔ (a → c) ∧ (b → c) := sorry
-- See Note [decidable namespace]
protected theorem decidable.or_iff_not_imp_left {a : Prop} {b : Prop} [Decidable a] : a ∨ b ↔ ¬a → b :=
{ mp := or.resolve_left, mpr := fun (h : ¬a → b) => dite a Or.inl (Or.inr ∘ h) }
theorem or_iff_not_imp_left {a : Prop} {b : Prop} : a ∨ b ↔ ¬a → b :=
decidable.or_iff_not_imp_left
-- See Note [decidable namespace]
protected theorem decidable.or_iff_not_imp_right {a : Prop} {b : Prop} [Decidable b] : a ∨ b ↔ ¬b → a :=
iff.trans or.comm decidable.or_iff_not_imp_left
theorem or_iff_not_imp_right {a : Prop} {b : Prop} : a ∨ b ↔ ¬b → a :=
decidable.or_iff_not_imp_right
-- See Note [decidable namespace]
protected theorem decidable.not_imp_not {a : Prop} {b : Prop} [Decidable a] : ¬a → ¬b ↔ b → a :=
{ mp := fun (h : ¬a → ¬b) (hb : b) => decidable.by_contradiction fun (na : ¬a) => h na hb, mpr := mt }
theorem not_imp_not {a : Prop} {b : Prop} : ¬a → ¬b ↔ b → a :=
decidable.not_imp_not
@[simp] theorem or_iff_left_iff_imp {a : Prop} {b : Prop} : a ∨ b ↔ a ↔ b → a :=
{ mp := fun (h : a ∨ b ↔ a) (hb : b) => iff.mp h (Or.inr hb), mpr := or_iff_left_of_imp }
@[simp] theorem or_iff_right_iff_imp {a : Prop} {b : Prop} : a ∨ b ↔ b ↔ a → b :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ↔ b ↔ a → b)) (propext (or_comm a b))))
(eq.mpr (id (Eq._oldrec (Eq.refl (b ∨ a ↔ b ↔ a → b)) (propext or_iff_left_iff_imp))) (iff.refl (a → b)))
/-! ### Declarations about distributivity -/
/-- `∧` distributes over `∨` (on the left). -/
theorem and_or_distrib_left {a : Prop} {b : Prop} {c : Prop} : a ∧ (b ∨ c) ↔ a ∧ b ∨ a ∧ c := sorry
/-- `∧` distributes over `∨` (on the right). -/
theorem or_and_distrib_right {a : Prop} {b : Prop} {c : Prop} : (a ∨ b) ∧ c ↔ a ∧ c ∨ b ∧ c :=
iff.trans (iff.trans and.comm and_or_distrib_left) (or_congr and.comm and.comm)
/-- `∨` distributes over `∧` (on the left). -/
theorem or_and_distrib_left {a : Prop} {b : Prop} {c : Prop} : a ∨ b ∧ c ↔ (a ∨ b) ∧ (a ∨ c) :=
{ mp := Or._oldrec (fun (ha : a) => { left := Or.inl ha, right := Or.inl ha }) (and.imp Or.inr Or.inr),
mpr := And._oldrec (Or._oldrec (imp_intro ∘ Or.inl) (or.imp_right ∘ And.intro)) }
/-- `∨` distributes over `∧` (on the right). -/
theorem and_or_distrib_right {a : Prop} {b : Prop} {c : Prop} : a ∧ b ∨ c ↔ (a ∨ c) ∧ (b ∨ c) :=
iff.trans (iff.trans or.comm or_and_distrib_left) (and_congr or.comm or.comm)
@[simp] theorem or_self_left {a : Prop} {b : Prop} : a ∨ a ∨ b ↔ a ∨ b :=
{ mp := fun (h : a ∨ a ∨ b) => or.elim h Or.inl id, mpr := fun (h : a ∨ b) => or.elim h Or.inl (Or.inr ∘ Or.inr) }
@[simp] theorem or_self_right {a : Prop} {b : Prop} : (a ∨ b) ∨ b ↔ a ∨ b :=
{ mp := fun (h : (a ∨ b) ∨ b) => or.elim h id Or.inr, mpr := fun (h : a ∨ b) => or.elim h (Or.inl ∘ Or.inl) Or.inr }
/-! Declarations about `iff` -/
theorem iff_of_true {a : Prop} {b : Prop} (ha : a) (hb : b) : a ↔ b :=
{ mp := fun (_x : a) => hb, mpr := fun (_x : b) => ha }
theorem iff_of_false {a : Prop} {b : Prop} (ha : ¬a) (hb : ¬b) : a ↔ b :=
{ mp := not.elim ha, mpr := not.elim hb }
theorem iff_true_left {a : Prop} {b : Prop} (ha : a) : a ↔ b ↔ b :=
{ mp := fun (h : a ↔ b) => iff.mp h ha, mpr := iff_of_true ha }
theorem iff_true_right {a : Prop} {b : Prop} (ha : a) : b ↔ a ↔ b :=
iff.trans iff.comm (iff_true_left ha)
theorem iff_false_left {a : Prop} {b : Prop} (ha : ¬a) : a ↔ b ↔ ¬b :=
{ mp := fun (h : a ↔ b) => mt (iff.mpr h) ha, mpr := iff_of_false ha }
theorem iff_false_right {a : Prop} {b : Prop} (ha : ¬a) : b ↔ a ↔ ¬b :=
iff.trans iff.comm (iff_false_left ha)
-- See Note [decidable namespace]
protected theorem decidable.not_or_of_imp {a : Prop} {b : Prop} [Decidable a] (h : a → b) : ¬a ∨ b :=
dite a (fun (ha : a) => Or.inr (h ha)) fun (ha : ¬a) => Or.inl ha
theorem not_or_of_imp {a : Prop} {b : Prop} : (a → b) → ¬a ∨ b :=
decidable.not_or_of_imp
-- See Note [decidable namespace]
protected theorem decidable.imp_iff_not_or {a : Prop} {b : Prop} [Decidable a] : a → b ↔ ¬a ∨ b :=
{ mp := decidable.not_or_of_imp, mpr := or.neg_resolve_left }
theorem imp_iff_not_or {a : Prop} {b : Prop} : a → b ↔ ¬a ∨ b :=
decidable.imp_iff_not_or
-- See Note [decidable namespace]
protected theorem decidable.imp_or_distrib {a : Prop} {b : Prop} {c : Prop} [Decidable a] : a → b ∨ c ↔ (a → b) ∨ (a → c) := sorry
theorem imp_or_distrib {a : Prop} {b : Prop} {c : Prop} : a → b ∨ c ↔ (a → b) ∨ (a → c) :=
decidable.imp_or_distrib
-- See Note [decidable namespace]
protected theorem decidable.imp_or_distrib' {a : Prop} {b : Prop} {c : Prop} [Decidable b] : a → b ∨ c ↔ (a → b) ∨ (a → c) := sorry
theorem imp_or_distrib' {a : Prop} {b : Prop} {c : Prop} : a → b ∨ c ↔ (a → b) ∨ (a → c) :=
decidable.imp_or_distrib'
theorem not_imp_of_and_not {a : Prop} {b : Prop} : a ∧ ¬b → ¬(a → b) :=
fun (ᾰ : a ∧ ¬b) (ᾰ_1 : a → b) => and.dcases_on ᾰ fun (ᾰ_left : a) (ᾰ_right : ¬b) => idRhs False (ᾰ_right (ᾰ_1 ᾰ_left))
-- See Note [decidable namespace]
protected theorem decidable.not_imp {a : Prop} {b : Prop} [Decidable a] : ¬(a → b) ↔ a ∧ ¬b :=
{ mp := fun (h : ¬(a → b)) => { left := decidable.of_not_imp h, right := not_of_not_imp h }, mpr := not_imp_of_and_not }
theorem not_imp {a : Prop} {b : Prop} : ¬(a → b) ↔ a ∧ ¬b :=
decidable.not_imp
-- for monotonicity
theorem imp_imp_imp {a : Prop} {b : Prop} {c : Prop} {d : Prop} (h₀ : c → a) (h₁ : b → d) : (a → b) → c → d :=
fun (h₂ : a → b) => h₁ ∘ h₂ ∘ h₀
-- See Note [decidable namespace]
protected theorem decidable.peirce (a : Prop) (b : Prop) [Decidable a] : ((a → b) → a) → a :=
dite a (fun (ha : a) (h : (a → b) → a) => ha) fun (ha : ¬a) (h : (a → b) → a) => h (not.elim ha)
theorem peirce (a : Prop) (b : Prop) : ((a → b) → a) → a :=
decidable.peirce a b
theorem peirce' {a : Prop} (H : ∀ (b : Prop), (a → b) → a) : a :=
H a id
-- See Note [decidable namespace]
protected theorem decidable.not_iff_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] : ¬a ↔ ¬b ↔ (a ↔ b) :=
eq.mpr (id (Eq._oldrec (Eq.refl (¬a ↔ ¬b ↔ (a ↔ b))) (propext iff_def)))
(eq.mpr (id (Eq._oldrec (Eq.refl ((¬a → ¬b) ∧ (¬b → ¬a) ↔ (a ↔ b))) (propext iff_def')))
(and_congr decidable.not_imp_not decidable.not_imp_not))
theorem not_iff_not {a : Prop} {b : Prop} : ¬a ↔ ¬b ↔ (a ↔ b) :=
decidable.not_iff_not
-- See Note [decidable namespace]
protected theorem decidable.not_iff_comm {a : Prop} {b : Prop} [Decidable a] [Decidable b] : ¬a ↔ b ↔ (¬b ↔ a) :=
eq.mpr (id (Eq._oldrec (Eq.refl (¬a ↔ b ↔ (¬b ↔ a))) (propext iff_def)))
(eq.mpr (id (Eq._oldrec (Eq.refl ((¬a → b) ∧ (b → ¬a) ↔ (¬b ↔ a))) (propext iff_def)))
(and_congr decidable.not_imp_comm imp_not_comm))
theorem not_iff_comm {a : Prop} {b : Prop} : ¬a ↔ b ↔ (¬b ↔ a) :=
decidable.not_iff_comm
-- See Note [decidable namespace]
protected theorem decidable.not_iff {a : Prop} {b : Prop} [Decidable b] : ¬(a ↔ b) ↔ (¬a ↔ b) := sorry
theorem not_iff {a : Prop} {b : Prop} : ¬(a ↔ b) ↔ (¬a ↔ b) :=
decidable.not_iff
-- See Note [decidable namespace]
protected theorem decidable.iff_not_comm {a : Prop} {b : Prop} [Decidable a] [Decidable b] : a ↔ ¬b ↔ (b ↔ ¬a) :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ↔ ¬b ↔ (b ↔ ¬a))) (propext iff_def)))
(eq.mpr (id (Eq._oldrec (Eq.refl ((a → ¬b) ∧ (¬b → a) ↔ (b ↔ ¬a))) (propext iff_def)))
(and_congr imp_not_comm decidable.not_imp_comm))
theorem iff_not_comm {a : Prop} {b : Prop} : a ↔ ¬b ↔ (b ↔ ¬a) :=
decidable.iff_not_comm
-- See Note [decidable namespace]
protected theorem decidable.iff_iff_and_or_not_and_not {a : Prop} {b : Prop} [Decidable b] : a ↔ b ↔ a ∧ b ∨ ¬a ∧ ¬b := sorry
theorem iff_iff_and_or_not_and_not {a : Prop} {b : Prop} : a ↔ b ↔ a ∧ b ∨ ¬a ∧ ¬b :=
decidable.iff_iff_and_or_not_and_not
theorem decidable.iff_iff_not_or_and_or_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] : a ↔ b ↔ (¬a ∨ b) ∧ (a ∨ ¬b) := sorry
theorem iff_iff_not_or_and_or_not {a : Prop} {b : Prop} : a ↔ b ↔ (¬a ∨ b) ∧ (a ∨ ¬b) :=
decidable.iff_iff_not_or_and_or_not
-- See Note [decidable namespace]
protected theorem decidable.not_and_not_right {a : Prop} {b : Prop} [Decidable b] : ¬(a ∧ ¬b) ↔ a → b := sorry
theorem not_and_not_right {a : Prop} {b : Prop} : ¬(a ∧ ¬b) ↔ a → b :=
decidable.not_and_not_right
/-- Transfer decidability of `a` to decidability of `b`, if the propositions are equivalent.
**Important**: this function should be used instead of `rw` on `decidable b`, because the
kernel will get stuck reducing the usage of `propext` otherwise,
and `dec_trivial` will not work. -/
def decidable_of_iff {b : Prop} (a : Prop) (h : a ↔ b) [D : Decidable a] : Decidable b :=
decidable_of_decidable_of_iff D h
/-- Transfer decidability of `b` to decidability of `a`, if the propositions are equivalent.
This is the same as `decidable_of_iff` but the iff is flipped. -/
def decidable_of_iff' {a : Prop} (b : Prop) (h : a ↔ b) [D : Decidable b] : Decidable a :=
decidable_of_decidable_of_iff D (iff.symm h)
/-- Prove that `a` is decidable by constructing a boolean `b` and a proof that `b ↔ a`.
(This is sometimes taken as an alternate definition of decidability.) -/
def decidable_of_bool {a : Prop} (b : Bool) (h : ↥b ↔ a) : Decidable a :=
sorry
/-! ### De Morgan's laws -/
theorem not_and_of_not_or_not {a : Prop} {b : Prop} (h : ¬a ∨ ¬b) : ¬(a ∧ b) :=
fun (ᾰ : a ∧ b) =>
and.dcases_on ᾰ fun (ᾰ_left : a) (ᾰ_right : b) => idRhs False (or.elim h (absurd ᾰ_left) (absurd ᾰ_right))
-- See Note [decidable namespace]
protected theorem decidable.not_and_distrib {a : Prop} {b : Prop} [Decidable a] : ¬(a ∧ b) ↔ ¬a ∨ ¬b := sorry
-- See Note [decidable namespace]
protected theorem decidable.not_and_distrib' {a : Prop} {b : Prop} [Decidable b] : ¬(a ∧ b) ↔ ¬a ∨ ¬b := sorry
/-- One of de Morgan's laws: the negation of a conjunction is logically equivalent to the
disjunction of the negations. -/
theorem not_and_distrib {a : Prop} {b : Prop} : ¬(a ∧ b) ↔ ¬a ∨ ¬b :=
decidable.not_and_distrib
@[simp] theorem not_and {a : Prop} {b : Prop} : ¬(a ∧ b) ↔ a → ¬b :=
and_imp
theorem not_and' {a : Prop} {b : Prop} : ¬(a ∧ b) ↔ b → ¬a :=
iff.trans not_and imp_not_comm
/-- One of de Morgan's laws: the negation of a disjunction is logically equivalent to the
conjunction of the negations. -/
theorem not_or_distrib {a : Prop} {b : Prop} : ¬(a ∨ b) ↔ ¬a ∧ ¬b := sorry
-- See Note [decidable namespace]
protected theorem decidable.or_iff_not_and_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] : a ∨ b ↔ ¬(¬a ∧ ¬b) :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ↔ ¬(¬a ∧ ¬b))) (Eq.symm (propext not_or_distrib))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ∨ b ↔ ¬¬(a ∨ b))) (propext decidable.not_not))) (iff.refl (a ∨ b)))
theorem or_iff_not_and_not {a : Prop} {b : Prop} : a ∨ b ↔ ¬(¬a ∧ ¬b) :=
decidable.or_iff_not_and_not
-- See Note [decidable namespace]
protected theorem decidable.and_iff_not_or_not {a : Prop} {b : Prop} [Decidable a] [Decidable b] : a ∧ b ↔ ¬(¬a ∨ ¬b) :=
eq.mpr (id (Eq._oldrec (Eq.refl (a ∧ b ↔ ¬(¬a ∨ ¬b))) (Eq.symm (propext decidable.not_and_distrib))))
(eq.mpr (id (Eq._oldrec (Eq.refl (a ∧ b ↔ ¬¬(a ∧ b))) (propext decidable.not_not))) (iff.refl (a ∧ b)))
theorem and_iff_not_or_not {a : Prop} {b : Prop} : a ∧ b ↔ ¬(¬a ∨ ¬b) :=
decidable.and_iff_not_or_not
/-! ### Declarations about equality -/
@[simp] theorem heq_iff_eq {α : Sort u_1} {a : α} {b : α} : a == b ↔ a = b :=
{ mp := eq_of_heq, mpr := heq_of_eq }
theorem proof_irrel_heq {p : Prop} {q : Prop} (hp : p) (hq : q) : hp == hq :=
(fun (this : p = q) => Eq._oldrec (fun (hq : p) => HEq.refl hp) this hq)
(propext { mp := fun (_x : p) => hq, mpr := fun (_x : q) => hp })
theorem ne_of_mem_of_not_mem {α : outParam (Type u_1)} {β : Type u_2} [has_mem α β] {s : β} {a : α} {b : α} (h : a ∈ s) : ¬b ∈ s → a ≠ b :=
mt fun (e : a = b) => e ▸ h
theorem eq_equivalence {α : Sort u_1} : equivalence Eq :=
{ left := Eq.refl, right := { left := Eq.symm, right := Eq.trans } }
/-- Transport through trivial families is the identity. -/
@[simp] theorem eq_rec_constant {α : Sort u_1} {a : α} {a' : α} {β : Sort u_2} (y : β) (h : a = a') : Eq._oldrec y h = y := sorry
@[simp] theorem eq_mp_rfl {α : Sort u_1} {a : α} : eq.mp (Eq.refl α) a = a :=
rfl
@[simp] theorem eq_mpr_rfl {α : Sort u_1} {a : α} : eq.mpr (Eq.refl α) a = a :=
rfl
theorem heq_of_eq_mp {α : Sort u_1} {β : Sort u_1} {a : α} {a' : β} (e : α = β) (h₂ : eq.mp e a = a') : a == a' := sorry
theorem rec_heq_of_heq {α : Sort u_1} {a : α} {b : α} {β : Sort u_2} {C : α → Sort u_2} {x : C a} {y : β} (eq : a = b) (h : x == y) : Eq._oldrec x eq == y :=
eq.drec h eq
@[simp] theorem eq_mpr_heq {α : Sort u} {β : Sort u} (h : β = α) (x : α) : eq.mpr h x == x :=
eq.drec (fun (x : β) => HEq.refl (eq.mpr (Eq.refl β) x)) h x
protected theorem eq.congr {α : Sort u_1} {x₁ : α} {x₂ : α} {y₁ : α} {y₂ : α} (h₁ : x₁ = y₁) (h₂ : x₂ = y₂) : x₁ = x₂ ↔ y₁ = y₂ :=
Eq._oldrec (Eq._oldrec (iff.refl (x₁ = x₂)) h₂) h₁
theorem eq.congr_left {α : Sort u_1} {x : α} {y : α} {z : α} (h : x = y) : x = z ↔ y = z :=
eq.mpr (id (Eq._oldrec (Eq.refl (x = z ↔ y = z)) h)) (iff.refl (y = z))
theorem eq.congr_right {α : Sort u_1} {x : α} {y : α} {z : α} (h : x = y) : z = x ↔ z = y :=
eq.mpr (id (Eq._oldrec (Eq.refl (z = x ↔ z = y)) h)) (iff.refl (z = y))
theorem congr_arg2 {α : Type u_1} {β : Type u_2} {γ : Type u_3} (f : α → β → γ) {x : α} {x' : α} {y : β} {y' : β} (hx : x = x') (hy : y = y') : f x y = f x' y' :=
Eq._oldrec (Eq._oldrec (Eq.refl (f x y)) hy) hx
/-! ### Declarations about quantifiers -/
theorem forall_imp {α : Sort u_1} {p : α → Prop} {q : α → Prop} (h : ∀ (a : α), p a → q a) : (∀ (a : α), p a) → ∀ (a : α), q a :=
fun (h' : ∀ (a : α), p a) (a : α) => h a (h' a)
theorem forall₂_congr {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} {q : α → β → Prop} (h : ∀ (a : α) (b : β), p a b ↔ q a b) : (∀ (a : α) (b : β), p a b) ↔ ∀ (a : α) (b : β), q a b :=
forall_congr fun (a : α) => forall_congr (h a)
theorem forall₃_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {p : α → β → γ → Prop} {q : α → β → γ → Prop} (h : ∀ (a : α) (b : β) (c : γ), p a b c ↔ q a b c) : (∀ (a : α) (b : β) (c : γ), p a b c) ↔ ∀ (a : α) (b : β) (c : γ), q a b c :=
forall_congr fun (a : α) => forall₂_congr (h a)
theorem forall₄_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {δ : Sort u_4} {p : α → β → γ → δ → Prop} {q : α → β → γ → δ → Prop} (h : ∀ (a : α) (b : β) (c : γ) (d : δ), p a b c d ↔ q a b c d) : (∀ (a : α) (b : β) (c : γ) (d : δ), p a b c d) ↔ ∀ (a : α) (b : β) (c : γ) (d : δ), q a b c d :=
forall_congr fun (a : α) => forall₃_congr (h a)
theorem Exists.imp {α : Sort u_1} {q : α → Prop} {p : α → Prop} (h : ∀ (a : α), p a → q a) : (∃ (a : α), p a) → ∃ (a : α), q a :=
fun (p_1 : ∃ (a : α), p a) => exists_imp_exists h p_1
theorem exists_imp_exists' {α : Sort u_1} {β : Sort u_2} {p : α → Prop} {q : β → Prop} (f : α → β) (hpq : ∀ (a : α), p a → q (f a)) (hp : ∃ (a : α), p a) : ∃ (b : β), q b :=
exists.elim hp fun (a : α) (hp' : p a) => Exists.intro (f a) (hpq a hp')
theorem exists₂_congr {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} {q : α → β → Prop} (h : ∀ (a : α) (b : β), p a b ↔ q a b) : (∃ (a : α), ∃ (b : β), p a b) ↔ ∃ (a : α), ∃ (b : β), q a b :=
exists_congr fun (a : α) => exists_congr (h a)
theorem exists₃_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {p : α → β → γ → Prop} {q : α → β → γ → Prop} (h : ∀ (a : α) (b : β) (c : γ), p a b c ↔ q a b c) : (∃ (a : α), ∃ (b : β), ∃ (c : γ), p a b c) ↔ ∃ (a : α), ∃ (b : β), ∃ (c : γ), q a b c :=
exists_congr fun (a : α) => exists₂_congr (h a)
theorem exists₄_congr {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} {δ : Sort u_4} {p : α → β → γ → δ → Prop} {q : α → β → γ → δ → Prop} (h : ∀ (a : α) (b : β) (c : γ) (d : δ), p a b c d ↔ q a b c d) : (∃ (a : α), ∃ (b : β), ∃ (c : γ), ∃ (d : δ), p a b c d) ↔ ∃ (a : α), ∃ (b : β), ∃ (c : γ), ∃ (d : δ), q a b c d :=
exists_congr fun (a : α) => exists₃_congr (h a)
theorem forall_swap {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} : (∀ (x : α) (y : β), p x y) ↔ ∀ (y : β) (x : α), p x y :=
{ mp := function.swap, mpr := function.swap }
theorem exists_swap {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} : (∃ (x : α), ∃ (y : β), p x y) ↔ ∃ (y : β), ∃ (x : α), p x y := sorry
@[simp] theorem exists_imp_distrib {α : Sort u_1} {p : α → Prop} {b : Prop} : (∃ (x : α), p x) → b ↔ ∀ (x : α), p x → b := sorry
/--
Extract an element from a existential statement, using `classical.some`.
-/
-- This enables projection notation.
def Exists.some {α : Sort u_1} {p : α → Prop} (P : ∃ (a : α), p a) : α :=
classical.some P
/--
Show that an element extracted from `P : ∃ a, p a` using `P.some` satisfies `p`.
-/
theorem Exists.some_spec {α : Sort u_1} {p : α → Prop} (P : ∃ (a : α), p a) : p (Exists.some P) :=
classical.some_spec P
--theorem forall_not_of_not_exists (h : ¬ ∃ x, p x) : ∀ x, ¬ p x :=
--forall_imp_of_exists_imp h
theorem not_exists_of_forall_not {α : Sort u_1} {p : α → Prop} (h : ∀ (x : α), ¬p x) : ¬∃ (x : α), p x :=
iff.mpr exists_imp_distrib h
@[simp] theorem not_exists {α : Sort u_1} {p : α → Prop} : (¬∃ (x : α), p x) ↔ ∀ (x : α), ¬p x :=
exists_imp_distrib
theorem not_forall_of_exists_not {α : Sort u_1} {p : α → Prop} : (∃ (x : α), ¬p x) → ¬∀ (x : α), p x :=
fun (ᾰ : ∃ (x : α), ¬p x) (ᾰ_1 : ∀ (x : α), p x) =>
Exists.dcases_on ᾰ fun (ᾰ_w : α) (ᾰ_h : ¬p ᾰ_w) => idRhs False (ᾰ_h (ᾰ_1 ᾰ_w))
-- See Note [decidable namespace]
protected theorem decidable.not_forall {α : Sort u_1} {p : α → Prop} [Decidable (∃ (x : α), ¬p x)] [(x : α) → Decidable (p x)] : (¬∀ (x : α), p x) ↔ ∃ (x : α), ¬p x := sorry
@[simp] theorem not_forall {α : Sort u_1} {p : α → Prop} : (¬∀ (x : α), p x) ↔ ∃ (x : α), ¬p x :=
decidable.not_forall
-- See Note [decidable namespace]
protected theorem decidable.not_forall_not {α : Sort u_1} {p : α → Prop} [Decidable (∃ (x : α), p x)] : (¬∀ (x : α), ¬p x) ↔ ∃ (x : α), p x :=
iff.mp decidable.not_iff_comm not_exists
theorem not_forall_not {α : Sort u_1} {p : α → Prop} : (¬∀ (x : α), ¬p x) ↔ ∃ (x : α), p x :=
decidable.not_forall_not
-- See Note [decidable namespace]
protected theorem decidable.not_exists_not {α : Sort u_1} {p : α → Prop} [(x : α) → Decidable (p x)] : (¬∃ (x : α), ¬p x) ↔ ∀ (x : α), p x := sorry
@[simp] theorem not_exists_not {α : Sort u_1} {p : α → Prop} : (¬∃ (x : α), ¬p x) ↔ ∀ (x : α), p x :=
decidable.not_exists_not
@[simp] theorem forall_true_iff {α : Sort u_1} : α → True ↔ True :=
iff_true_intro fun (_x : α) => trivial
-- Unfortunately this causes simp to loop sometimes, so we
-- add the 2 and 3 cases as simp lemmas instead
theorem forall_true_iff' {α : Sort u_1} {p : α → Prop} (h : ∀ (a : α), p a ↔ True) : (∀ (a : α), p a) ↔ True :=
iff_true_intro fun (_x : α) => of_iff_true (h _x)
@[simp] theorem forall_2_true_iff {α : Sort u_1} {β : α → Sort u_2} : (∀ (a : α), β a → True) ↔ True :=
forall_true_iff' fun (_x : α) => forall_true_iff
@[simp] theorem forall_3_true_iff {α : Sort u_1} {β : α → Sort u_2} {γ : (a : α) → β a → Sort u_3} : (∀ (a : α) (b : β a), γ a b → True) ↔ True :=
forall_true_iff' fun (_x : α) => forall_2_true_iff
@[simp] theorem forall_const {b : Prop} (α : Sort u_1) [i : Nonempty α] : α → b ↔ b :=
{ mp := nonempty.elim i, mpr := fun (hb : b) (x : α) => hb }
@[simp] theorem exists_const {b : Prop} (α : Sort u_1) [i : Nonempty α] : (∃ (x : α), b) ↔ b :=
{ mp := fun (_x : ∃ (x : α), b) => (fun (_a : ∃ (x : α), b) => Exists.dcases_on _a fun (w : α) (h : b) => idRhs b h) _x,
mpr := nonempty.elim i exists.intro }
theorem forall_and_distrib {α : Sort u_1} {p : α → Prop} {q : α → Prop} : (∀ (x : α), p x ∧ q x) ↔ (∀ (x : α), p x) ∧ ∀ (x : α), q x := sorry
theorem exists_or_distrib {α : Sort u_1} {p : α → Prop} {q : α → Prop} : (∃ (x : α), p x ∨ q x) ↔ (∃ (x : α), p x) ∨ ∃ (x : α), q x := sorry
@[simp] theorem exists_and_distrib_left {α : Sort u_1} {q : Prop} {p : α → Prop} : (∃ (x : α), q ∧ p x) ↔ q ∧ ∃ (x : α), p x := sorry
@[simp] theorem exists_and_distrib_right {α : Sort u_1} {q : Prop} {p : α → Prop} : (∃ (x : α), p x ∧ q) ↔ (∃ (x : α), p x) ∧ q := sorry
@[simp] theorem forall_eq {α : Sort u_1} {p : α → Prop} {a' : α} : (∀ (a : α), a = a' → p a) ↔ p a' :=
{ mp := fun (h : ∀ (a : α), a = a' → p a) => h a' rfl, mpr := fun (h : p a') (a : α) (e : a = a') => Eq.symm e ▸ h }
@[simp] theorem forall_eq' {α : Sort u_1} {p : α → Prop} {a' : α} : (∀ (a : α), a' = a → p a) ↔ p a' := sorry
-- this lemma is needed to simplify the output of `list.mem_cons_iff`
@[simp] theorem forall_eq_or_imp {α : Sort u_1} {p : α → Prop} {q : α → Prop} {a' : α} : (∀ (a : α), a = a' ∨ q a → p a) ↔ p a' ∧ ∀ (a : α), q a → p a := sorry
@[simp] theorem exists_eq {α : Sort u_1} {a' : α} : ∃ (a : α), a = a' :=
Exists.intro a' rfl
@[simp] theorem exists_eq' {α : Sort u_1} {a' : α} : ∃ (a : α), a' = a :=
Exists.intro a' rfl
@[simp] theorem exists_eq_left {α : Sort u_1} {p : α → Prop} {a' : α} : (∃ (a : α), a = a' ∧ p a) ↔ p a' := sorry
@[simp] theorem exists_eq_right {α : Sort u_1} {p : α → Prop} {a' : α} : (∃ (a : α), p a ∧ a = a') ↔ p a' :=
iff.trans (exists_congr fun (a : α) => and.comm) exists_eq_left
@[simp] theorem exists_eq_right_right {α : Sort u_1} {p : α → Prop} {b : Prop} {a' : α} : (∃ (a : α), p a ∧ b ∧ a = a') ↔ p a' ∧ b := sorry
@[simp] theorem exists_eq_right_right' {α : Sort u_1} {p : α → Prop} {b : Prop} {a' : α} : (∃ (a : α), p a ∧ b ∧ a' = a) ↔ p a' ∧ b := sorry
@[simp] theorem exists_apply_eq_apply {α : Type u_1} {β : Type u_2} (f : α → β) (a' : α) : ∃ (a : α), f a = f a' :=
Exists.intro a' rfl
@[simp] theorem exists_apply_eq_apply' {α : Type u_1} {β : Type u_2} (f : α → β) (a' : α) : ∃ (a : α), f a' = f a :=
Exists.intro a' rfl
@[simp] theorem exists_exists_and_eq_and {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : α → Prop} {q : β → Prop} : (∃ (b : β), (∃ (a : α), p a ∧ f a = b) ∧ q b) ↔ ∃ (a : α), p a ∧ q (f a) := sorry
@[simp] theorem exists_exists_eq_and {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∃ (b : β), (∃ (a : α), f a = b) ∧ p b) ↔ ∃ (a : α), p (f a) := sorry
@[simp] theorem forall_apply_eq_imp_iff {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∀ (a : α) (b : β), f a = b → p b) ↔ ∀ (a : α), p (f a) :=
{ mp := fun (h : ∀ (a : α) (b : β), f a = b → p b) (a : α) => h a (f a) rfl,
mpr := fun (h : ∀ (a : α), p (f a)) (a : α) (b : β) (hab : f a = b) => hab ▸ h a }
@[simp] theorem forall_apply_eq_imp_iff' {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∀ (b : β) (a : α), f a = b → p b) ↔ ∀ (a : α), p (f a) := sorry
@[simp] theorem forall_eq_apply_imp_iff {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∀ (a : α) (b : β), b = f a → p b) ↔ ∀ (a : α), p (f a) := sorry
@[simp] theorem forall_eq_apply_imp_iff' {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : β → Prop} : (∀ (b : β) (a : α), b = f a → p b) ↔ ∀ (a : α), p (f a) := sorry
@[simp] theorem forall_apply_eq_imp_iff₂ {α : Sort u_1} {β : Sort u_2} {f : α → β} {p : α → Prop} {q : β → Prop} : (∀ (b : β) (a : α), p a → f a = b → q b) ↔ ∀ (a : α), p a → q (f a) :=
{ mp := fun (h : ∀ (b : β) (a : α), p a → f a = b → q b) (a : α) (ha : p a) => h (f a) a ha rfl,
mpr := fun (h : ∀ (a : α), p a → q (f a)) (b : β) (a : α) (ha : p a) (hb : f a = b) => hb ▸ h a ha }
@[simp] theorem exists_eq_left' {α : Sort u_1} {p : α → Prop} {a' : α} : (∃ (a : α), a' = a ∧ p a) ↔ p a' := sorry
@[simp] theorem exists_eq_right' {α : Sort u_1} {p : α → Prop} {a' : α} : (∃ (a : α), p a ∧ a' = a) ↔ p a' := sorry
theorem exists_comm {α : Sort u_1} {β : Sort u_2} {p : α → β → Prop} : (∃ (a : α), ∃ (b : β), p a b) ↔ ∃ (b : β), ∃ (a : α), p a b := sorry
theorem forall_or_of_or_forall {α : Sort u_1} {p : α → Prop} {b : Prop} (h : b ∨ ∀ (x : α), p x) (x : α) : b ∨ p x :=
or.imp_right (fun (h₂ : ∀ (x : α), p x) => h₂ x) h
-- See Note [decidable namespace]
protected theorem decidable.forall_or_distrib_left {α : Sort u_1} {q : Prop} {p : α → Prop} [Decidable q] : (∀ (x : α), q ∨ p x) ↔ q ∨ ∀ (x : α), p x := sorry
theorem forall_or_distrib_left {α : Sort u_1} {q : Prop} {p : α → Prop} : (∀ (x : α), q ∨ p x) ↔ q ∨ ∀ (x : α), p x :=
decidable.forall_or_distrib_left
-- See Note [decidable namespace]
protected theorem decidable.forall_or_distrib_right {α : Sort u_1} {q : Prop} {p : α → Prop} [Decidable q] : (∀ (x : α), p x ∨ q) ↔ (∀ (x : α), p x) ∨ q := sorry
theorem forall_or_distrib_right {α : Sort u_1} {q : Prop} {p : α → Prop} : (∀ (x : α), p x ∨ q) ↔ (∀ (x : α), p x) ∨ q :=
decidable.forall_or_distrib_right
/-- A predicate holds everywhere on the image of a surjective functions iff
it holds everywhere. -/
theorem forall_iff_forall_surj {α : Type u_1} {β : Type u_2} {f : α → β} (h : function.surjective f) {P : β → Prop} : (∀ (a : α), P (f a)) ↔ ∀ (b : β), P b := sorry
@[simp] theorem exists_prop {p : Prop} {q : Prop} : (∃ (h : p), q) ↔ p ∧ q := sorry
@[simp] theorem exists_false {α : Sort u_1} : ¬∃ (a : α), False :=
fun (_x : ∃ (a : α), False) =>
(fun (_a : ∃ (a : α), False) => Exists.dcases_on _a fun (w : α) (h : False) => idRhs False h) _x
@[simp] theorem exists_unique_false {α : Sort u_1} : ¬exists_unique fun (a : α) => False := sorry
theorem Exists.fst {b : Prop} {p : b → Prop} : Exists p → b :=
fun (ᾰ : Exists p) => Exists.dcases_on ᾰ fun (ᾰ_w : b) (ᾰ_h : p ᾰ_w) => idRhs b ᾰ_w
theorem Exists.snd {b : Prop} {p : b → Prop} (h : Exists p) : p (Exists.fst h) :=
Exists.dcases_on h fun (h_w : b) (h_h : p h_w) => idRhs (p h_w) h_h
@[simp] theorem forall_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∀ (h' : p), q h') ↔ q h :=
forall_const p
@[simp] theorem exists_prop_of_true {p : Prop} {q : p → Prop} (h : p) : (∃ (h' : p), q h') ↔ q h :=
exists_const p
@[simp] theorem forall_prop_of_false {p : Prop} {q : p → Prop} (hn : ¬p) : (∀ (h' : p), q h') ↔ True :=
iff_true_intro fun (h : p) => not.elim hn h
@[simp] theorem exists_prop_of_false {p : Prop} {q : p → Prop} : ¬p → ¬∃ (h' : p), q h' :=
mt Exists.fst
theorem exists_unique.exists {α : Sort u_1} {p : α → Prop} (h : exists_unique fun (x : α) => p x) : ∃ (x : α), p x :=
exists.elim h fun (x : α) (hx : (fun (x : α) => p x) x ∧ ∀ (y : α), p y → y = x) => Exists.intro x (and.left hx)
theorem exists_unique.unique {α : Sort u_1} {p : α → Prop} (h : exists_unique fun (x : α) => p x) {y₁ : α} {y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ :=
unique_of_exists_unique h py₁ py₂
@[simp] theorem exists_unique_iff_exists {α : Sort u_1} [subsingleton α] {p : α → Prop} : (exists_unique fun (x : α) => p x) ↔ ∃ (x : α), p x :=
{ mp := fun (h : exists_unique fun (x : α) => p x) => exists_unique.exists h,
mpr := Exists.imp fun (x : α) (hx : p x) => { left := hx, right := fun (y : α) (_x : p y) => subsingleton.elim y x } }
theorem exists_unique.elim2 {α : Sort u_1} {p : α → Sort u_2} [∀ (x : α), subsingleton (p x)] {q : (x : α) → p x → Prop} {b : Prop} (h₂ : exists_unique fun (x : α) => exists_unique fun (h : p x) => q x h) (h₁ : ∀ (x : α) (h : p x), q x h → (∀ (y : α) (hy : p y), q y hy → y = x) → b) : b := sorry
theorem exists_unique.intro2 {α : Sort u_1} {p : α → Sort u_2} [∀ (x : α), subsingleton (p x)] {q : (x : α) → p x → Prop} (w : α) (hp : p w) (hq : q w hp) (H : ∀ (y : α) (hy : p y), q y hy → y = w) : exists_unique fun (x : α) => exists_unique fun (hx : p x) => q x hx := sorry
theorem exists_unique.exists2 {α : Sort u_1} {p : α → Sort u_2} {q : (x : α) → p x → Prop} (h : exists_unique fun (x : α) => exists_unique fun (hx : p x) => q x hx) : ∃ (x : α), ∃ (hx : p x), q x hx :=
Exists.imp (fun (x : α) (hx : exists_unique fun (hx : p x) => q x hx) => exists_unique.exists hx)
(exists_unique.exists h)
theorem exists_unique.unique2 {α : Sort u_1} {p : α → Sort u_2} [∀ (x : α), subsingleton (p x)] {q : (x : α) → p x → Prop} (h : exists_unique fun (x : α) => exists_unique fun (hx : p x) => q x hx) {y₁ : α} {y₂ : α} (hpy₁ : p y₁) (hqy₁ : q y₁ hpy₁) (hpy₂ : p y₂) (hqy₂ : q y₂ hpy₂) : y₁ = y₂ := sorry
/-! ### Classical lemmas -/
namespace classical
theorem cases {p : Prop → Prop} (h1 : p True) (h2 : p False) (a : Prop) : p a :=
cases_on a h1 h2
/- use shortened names to avoid conflict when classical namespace is open. -/
theorem dec (p : Prop) : Decidable p :=
prop_decidable p
theorem dec_pred {α : Sort u_1} (p : α → Prop) : decidable_pred p :=
fun (a : α) => prop_decidable (p a)
theorem dec_rel {α : Sort u_1} (p : α → α → Prop) : DecidableRel p :=
fun (a b : α) => prop_decidable (p a b)
theorem dec_eq (α : Sort u_1) : DecidableEq α :=
fun (a b : α) => prop_decidable (a = b)
/--
We make decidability results that depends on `classical.choice` noncomputable lemmas.
* We have to mark them as noncomputable, because otherwise Lean will try to generate bytecode
for them, and fail because it depends on `classical.choice`.
* We make them lemmas, and not definitions, because otherwise later definitions will raise
\"failed to generate bytecode\" errors when writing something like
`letI := classical.dec_eq _`.
Cf. <https://leanprover-community.github.io/archive/113488general/08268noncomputabletheorem.html>
-/
/-- Construct a function from a default value `H0`, and a function to use if there exists a value
satisfying the predicate. -/
def exists_cases {α : Sort u_1} {p : α → Prop} {C : Sort u} (H0 : C) (H : (a : α) → p a → C) : C :=
dite (∃ (a : α), p a) (fun (h : ∃ (a : α), p a) => H (some h) sorry) fun (h : ¬∃ (a : α), p a) => H0
theorem some_spec2 {α : Sort u_1} {p : α → Prop} {h : ∃ (a : α), p a} (q : α → Prop) (hpq : ∀ (a : α), p a → q a) : q (some h) :=
hpq (some h) (some_spec h)
/-- A version of classical.indefinite_description which is definitionally equal to a pair -/
def subtype_of_exists {α : Type u_1} {P : α → Prop} (h : ∃ (x : α), P x) : Subtype fun (x : α) => P x :=
{ val := some h, property := sorry }
end classical
/-- This function has the same type as `exists.rec_on`, and can be used to case on an equality,
but `exists.rec_on` can only eliminate into Prop, while this version eliminates into any universe
using the axiom of choice. -/
def exists.classical_rec_on {α : Sort u_1} {p : α → Prop} (h : ∃ (a : α), p a) {C : Sort u} (H : (a : α) → p a → C) : C :=
H (classical.some h) sorry
/-! ### Declarations about bounded quantifiers -/
theorem bex_def {α : Sort u_1} {p : α → Prop} {q : α → Prop} : (∃ (x : α), ∃ (h : p x), q x) ↔ ∃ (x : α), p x ∧ q x := sorry
theorem bex.elim {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {b : Prop} : (∃ (x : α), ∃ (h : p x), P x h) → (∀ (a : α) (h : p a), P a h → b) → b := sorry
theorem bex.intro {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} (a : α) (h₁ : p a) (h₂ : P a h₁) : ∃ (x : α), ∃ (h : p x), P x h :=
Exists.intro a (Exists.intro h₁ h₂)
theorem ball_congr {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h ↔ Q x h) : (∀ (x : α) (h : p x), P x h) ↔ ∀ (x : α) (h : p x), Q x h :=
forall_congr fun (x : α) => forall_congr (H x)
theorem bex_congr {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h ↔ Q x h) : (∃ (x : α), ∃ (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), Q x h :=
exists_congr fun (x : α) => exists_congr (H x)
theorem bex_eq_left {α : Sort u_1} {p : α → Prop} {a : α} : (∃ (x : α), ∃ (_x : x = a), p x) ↔ p a := sorry
theorem ball.imp_right {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h → Q x h) (h₁ : ∀ (x : α) (h : p x), P x h) (x : α) (h : p x) : Q x h :=
H x h (h₁ x h)
theorem bex.imp_right {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} (H : ∀ (x : α) (h : p x), P x h → Q x h) : (∃ (x : α), ∃ (h : p x), P x h) → ∃ (x : α), ∃ (h : p x), Q x h := sorry
theorem ball.imp_left {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x → q x) (h₁ : ∀ (x : α), q x → r x) (x : α) (h : p x) : r x :=
h₁ x (H x h)
theorem bex.imp_left {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x → q x) : (∃ (x : α), ∃ (_x : p x), r x) → ∃ (x : α), ∃ (_x : q x), r x := sorry
theorem ball_of_forall {α : Sort u_1} {p : α → Prop} (h : ∀ (x : α), p x) (x : α) : p x :=
h x
theorem forall_of_ball {α : Sort u_1} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x) (h : ∀ (x : α), p x → q x) (x : α) : q x :=
h x (H x)
theorem bex_of_exists {α : Sort u_1} {p : α → Prop} {q : α → Prop} (H : ∀ (x : α), p x) : (∃ (x : α), q x) → ∃ (x : α), ∃ (_x : p x), q x :=
fun (ᾰ : ∃ (x : α), q x) =>
Exists.dcases_on ᾰ
fun (ᾰ_w : α) (ᾰ_h : q ᾰ_w) => idRhs (∃ (x : α), ∃ (_x : p x), q x) (Exists.intro ᾰ_w (Exists.intro (H ᾰ_w) ᾰ_h))
theorem exists_of_bex {α : Sort u_1} {p : α → Prop} {q : α → Prop} : (∃ (x : α), ∃ (_x : p x), q x) → ∃ (x : α), q x := sorry
@[simp] theorem bex_imp_distrib {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {b : Prop} : (∃ (x : α), ∃ (h : p x), P x h) → b ↔ ∀ (x : α) (h : p x), P x h → b := sorry
theorem not_bex {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} : (¬∃ (x : α), ∃ (h : p x), P x h) ↔ ∀ (x : α) (h : p x), ¬P x h :=
bex_imp_distrib
theorem not_ball_of_bex_not {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} : (∃ (x : α), ∃ (h : p x), ¬P x h) → ¬∀ (x : α) (h : p x), P x h := sorry
-- See Note [decidable namespace]
protected theorem decidable.not_ball {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} [Decidable (∃ (x : α), ∃ (h : p x), ¬P x h)] [(x : α) → (h : p x) → Decidable (P x h)] : (¬∀ (x : α) (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), ¬P x h := sorry
theorem not_ball {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} : (¬∀ (x : α) (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), ¬P x h :=
decidable.not_ball
theorem ball_true_iff {α : Sort u_1} (p : α → Prop) : (∀ (x : α), p x → True) ↔ True :=
iff_true_intro fun (h : α) (hrx : p h) => trivial
theorem ball_and_distrib {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} : (∀ (x : α) (h : p x), P x h ∧ Q x h) ↔ (∀ (x : α) (h : p x), P x h) ∧ ∀ (x : α) (h : p x), Q x h :=
iff.trans (forall_congr fun (x : α) => forall_and_distrib) forall_and_distrib
theorem bex_or_distrib {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} {Q : (x : α) → p x → Prop} : (∃ (x : α), ∃ (h : p x), P x h ∨ Q x h) ↔ (∃ (x : α), ∃ (h : p x), P x h) ∨ ∃ (x : α), ∃ (h : p x), Q x h :=
iff.trans (exists_congr fun (x : α) => exists_or_distrib) exists_or_distrib
theorem ball_or_left_distrib {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} : (∀ (x : α), p x ∨ q x → r x) ↔ (∀ (x : α), p x → r x) ∧ ∀ (x : α), q x → r x :=
iff.trans (forall_congr fun (x : α) => or_imp_distrib) forall_and_distrib
theorem bex_or_left_distrib {α : Sort u_1} {r : α → Prop} {p : α → Prop} {q : α → Prop} : (∃ (x : α), ∃ (_x : p x ∨ q x), r x) ↔ (∃ (x : α), ∃ (_x : p x), r x) ∨ ∃ (x : α), ∃ (_x : q x), r x := sorry
namespace classical
theorem not_ball {α : Sort u_1} {p : α → Prop} {P : (x : α) → p x → Prop} : (¬∀ (x : α) (h : p x), P x h) ↔ ∃ (x : α), ∃ (h : p x), ¬P x h :=
not_ball
end classical
theorem ite_eq_iff {α : Sort u_1} {p : Prop} [Decidable p] {a : α} {b : α} {c : α} : ite p a b = c ↔ p ∧ a = c ∨ ¬p ∧ b = c := sorry
@[simp] theorem ite_eq_left_iff {α : Sort u_1} {p : Prop} [Decidable p] {a : α} {b : α} : ite p a b = a ↔ ¬p → b = a := sorry
@[simp] theorem ite_eq_right_iff {α : Sort u_1} {p : Prop} [Decidable p] {a : α} {b : α} : ite p a b = b ↔ p → a = b := sorry
/-! ### Declarations about `nonempty` -/
protected instance has_zero.nonempty {α : Type u} [HasZero α] : Nonempty α :=
Nonempty.intro 0
protected instance has_one.nonempty {α : Type u} [HasOne α] : Nonempty α :=
Nonempty.intro 1
theorem exists_true_iff_nonempty {α : Sort u_1} : (∃ (a : α), True) ↔ Nonempty α := sorry
@[simp] theorem nonempty_Prop {p : Prop} : Nonempty p ↔ p :=
{ mp := fun (_x : Nonempty p) => (fun (_a : Nonempty p) => nonempty.dcases_on _a fun (val : p) => idRhs p val) _x,
mpr := fun (h : p) => Nonempty.intro h }
theorem not_nonempty_iff_imp_false {α : Type u} : ¬Nonempty α ↔ α → False := sorry
@[simp] theorem nonempty_sigma {α : Type u} {γ : α → Type w} : Nonempty (sigma fun (a : α) => γ a) ↔ ∃ (a : α), Nonempty (γ a) := sorry
@[simp] theorem nonempty_subtype {α : Sort u} {p : α → Prop} : Nonempty (Subtype p) ↔ ∃ (a : α), p a := sorry
@[simp] theorem nonempty_prod {α : Type u} {β : Type v} : Nonempty (α × β) ↔ Nonempty α ∧ Nonempty β := sorry
@[simp] theorem nonempty_pprod {α : Sort u} {β : Sort v} : Nonempty (PProd α β) ↔ Nonempty α ∧ Nonempty β := sorry
@[simp] theorem nonempty_sum {α : Type u} {β : Type v} : Nonempty (α ⊕ β) ↔ Nonempty α ∨ Nonempty β := sorry
@[simp] theorem nonempty_psum {α : Sort u} {β : Sort v} : Nonempty (psum α β) ↔ Nonempty α ∨ Nonempty β := sorry
@[simp] theorem nonempty_psigma {α : Sort u} {β : α → Sort v} : Nonempty (psigma β) ↔ ∃ (a : α), Nonempty (β a) := sorry
@[simp] theorem nonempty_empty : ¬Nonempty empty :=
fun (_x : Nonempty empty) =>
(fun (_a : Nonempty empty) => nonempty.dcases_on _a fun (val : empty) => idRhs False (empty.elim val)) _x
@[simp] theorem nonempty_ulift {α : Type u} : Nonempty (ulift α) ↔ Nonempty α := sorry
@[simp] theorem nonempty_plift {α : Sort u} : Nonempty (plift α) ↔ Nonempty α := sorry
@[simp] theorem nonempty.forall {α : Sort u} {p : Nonempty α → Prop} : (∀ (h : Nonempty α), p h) ↔ ∀ (a : α), p (Nonempty.intro a) := sorry
@[simp] theorem nonempty.exists {α : Sort u} {p : Nonempty α → Prop} : (∃ (h : Nonempty α), p h) ↔ ∃ (a : α), p (Nonempty.intro a) := sorry
theorem classical.nonempty_pi {α : Sort u} {β : α → Sort v} : Nonempty ((a : α) → β a) ↔ ∀ (a : α), Nonempty (β a) := sorry
/-- Using `classical.choice`, lifts a (`Prop`-valued) `nonempty` instance to a (`Type`-valued)
`inhabited` instance. `classical.inhabited_of_nonempty` already exists, in
`core/init/classical.lean`, but the assumption is not a type class argument,
which makes it unsuitable for some applications. -/
def classical.inhabited_of_nonempty' {α : Sort u} [h : Nonempty α] : Inhabited α :=
{ default := Classical.choice h }
/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/
protected def nonempty.some {α : Sort u} (h : Nonempty α) : α :=
Classical.choice h
/-- Using `classical.choice`, extracts a term from a `nonempty` type. -/
protected def classical.arbitrary (α : Sort u) [h : Nonempty α] : α :=
Classical.choice h
/-- Given `f : α → β`, if `α` is nonempty then `β` is also nonempty.
`nonempty` cannot be a `functor`, because `functor` is restricted to `Type`. -/
theorem nonempty.map {α : Sort u} {β : Sort v} (f : α → β) : Nonempty α → Nonempty β :=
fun (ᾰ : Nonempty α) => nonempty.dcases_on ᾰ fun (ᾰ : α) => idRhs (Nonempty β) (Nonempty.intro (f ᾰ))
protected theorem nonempty.map2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) : Nonempty α → Nonempty β → Nonempty γ :=
fun (ᾰ : Nonempty α) (ᾰ_1 : Nonempty β) =>
nonempty.dcases_on ᾰ
fun (ᾰ_1_1 : α) => nonempty.dcases_on ᾰ_1 fun (ᾰ : β) => idRhs (Nonempty γ) (Nonempty.intro (f ᾰ_1_1 ᾰ))
protected theorem nonempty.congr {α : Sort u} {β : Sort v} (f : α → β) (g : β → α) : Nonempty α ↔ Nonempty β :=
{ mp := nonempty.map f, mpr := nonempty.map g }
theorem nonempty.elim_to_inhabited {α : Sort u_1} [h : Nonempty α] {p : Prop} (f : Inhabited α → p) : p :=
nonempty.elim h (f ∘ Inhabited.mk)
protected instance prod.nonempty {α : Type u_1} {β : Type u_2} [h : Nonempty α] [h2 : Nonempty β] : Nonempty (α × β) :=
nonempty.elim h fun (g : α) => nonempty.elim h2 fun (g2 : β) => Nonempty.intro (g, g2)
/-- A function applied to a `dite` is a `dite` of that function applied to each of the branches. -/
theorem apply_dite {α : Sort u_1} {β : Sort u_2} (f : α → β) (P : Prop) [Decidable P] (x : P → α) (y : ¬P → α) : f (dite P x y) = dite P (fun (h : P) => f (x h)) fun (h : ¬P) => f (y h) := sorry
/-- A function applied to a `ite` is a `ite` of that function applied to each of the branches. -/
theorem apply_ite {α : Sort u_1} {β : Sort u_2} (f : α → β) (P : Prop) [Decidable P] (x : α) (y : α) : f (ite P x y) = ite P (f x) (f y) :=
apply_dite f P (fun (_x : P) => x) fun (_x : ¬P) => y
/-- A two-argument function applied to two `dite`s is a `dite` of that two-argument function
applied to each of the branches. -/
theorem apply_dite2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) (P : Prop) [Decidable P] (a : P → α) (b : ¬P → α) (c : P → β) (d : ¬P → β) : f (dite P a b) (dite P c d) = dite P (fun (h : P) => f (a h) (c h)) fun (h : ¬P) => f (b h) (d h) := sorry
/-- A two-argument function applied to two `ite`s is a `ite` of that two-argument function
applied to each of the branches. -/
theorem apply_ite2 {α : Sort u_1} {β : Sort u_2} {γ : Sort u_3} (f : α → β → γ) (P : Prop) [Decidable P] (a : α) (b : α) (c : β) (d : β) : f (ite P a b) (ite P c d) = ite P (f a c) (f b d) :=
apply_dite2 f P (fun (_x : P) => a) (fun (_x : ¬P) => b) (fun (_x : P) => c) fun (_x : ¬P) => d
/-- A 'dite' producing a `Pi` type `Π a, β a`, applied to a value `x : α`
is a `dite` that applies either branch to `x`. -/
theorem dite_apply {α : Sort u_1} {β : α → Sort u_2} (P : Prop) [Decidable P] (f : P → (a : α) → β a) (g : ¬P → (a : α) → β a) (x : α) : dite P f g x = dite P (fun (h : P) => f h x) fun (h : ¬P) => g h x := sorry
/-- A 'ite' producing a `Pi` type `Π a, β a`, applied to a value `x : α`
is a `ite` that applies either branch to `x` -/
theorem ite_apply {α : Sort u_1} {β : α → Sort u_2} (P : Prop) [Decidable P] (f : (a : α) → β a) (g : (a : α) → β a) (x : α) : ite P f g x = ite P (f x) (g x) :=
dite_apply P (fun (_x : P) => f) (fun (_x : ¬P) => g) x
/-- Negation of the condition `P : Prop` in a `dite` is the same as swapping the branches. -/
@[simp] theorem dite_not {α : Sort u_1} (P : Prop) [Decidable P] (x : ¬P → α) (y : ¬¬P → α) : dite (¬P) x y = dite P (fun (h : P) => y (not_not_intro h)) x := sorry
/-- Negation of the condition `P : Prop` in a `ite` is the same as swapping the branches. -/
@[simp] theorem ite_not {α : Sort u_1} (P : Prop) [Decidable P] (x : α) (y : α) : ite (¬P) x y = ite P y x :=
dite_not P (fun (_x : ¬P) => x) fun (_x : ¬¬P) => y
theorem ite_and {α : Sort u_1} {p : Prop} {q : Prop} [Decidable p] [Decidable q] {x : α} {y : α} : ite (p ∧ q) x y = ite p (ite q x y) y := sorry
|
c9ba294c5712d52c631dbe948dc487270bc43600 | efa51dd2edbbbbd6c34bd0ce436415eb405832e7 | /20160406_UW/ex1.lean | fa974d6d14d0bde8f929a4f33859cf76d77a586b | [
"Apache-2.0"
] | permissive | leanprover/presentations | dd031a05bcb12c8855676c77e52ed84246bd889a | 3ce2d132d299409f1de269fa8e95afa1333d644e | refs/heads/master | 1,688,703,388,796 | 1,686,838,383,000 | 1,687,465,742,000 | 29,750,158 | 12 | 9 | Apache-2.0 | 1,540,211,670,000 | 1,422,042,683,000 | Lean | UTF-8 | Lean | false | false | 305 | lean | import data.vector theories.number_theory.primes
open bool nat list vector
check nat
check list
check fact 3
eval fact 5
check λ x, x + 1
check λ (n : nat) (v : vector nat n), 0::v
check add
print prime
eval is_true (prime 7)
eval is_true (prime 4)
set_option pp.universes true
check Type.{5}
|
036a7b497d6e6fb64cdb2e3d25af651b08dafcfd | b9d8165d695e844c92d9d4cdcac7b5ab9efe09f7 | /src/analysis/complex/exponential.lean | 1f6351359f29079bcac13702fdfef75bdd068cdb | [
"Apache-2.0"
] | permissive | spapinistarkware/mathlib | e917d9c44bf85ef51db18e7a11615959f714efc5 | 0a9a1ff463a1f26e27d7c391eb7f6334f0d90383 | refs/heads/master | 1,606,808,129,547 | 1,577,478,369,000 | 1,577,478,369,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 82,752 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne
-/
import tactic.linarith data.complex.exponential analysis.specific_limits
group_theory.quotient_group analysis.complex.basic
/-!
# Exponential
## Main definitions
This file contains the following definitions:
* π, arcsin, arccos, arctan
* argument of a complex number
* logarithm on real and complex numbers
* complex and real power function
## Main statements
The following functions are shown to be continuous:
* complex and real exponential function
* sin, cos, tan, sinh, cosh
* logarithm on real numbers
* real power function
* square root function
The following functions are shown to be differentiable, and their derivatives are computed:
* complex and real exponential function
* sin, cos, sinh, cosh
## Tags
exp, log, sin, cos, tan, arcsin, arccos, arctan, angle, argument, power, square root,
-/
noncomputable theory
open finset filter metric asymptotics
open_locale topological_space
namespace complex
/-- The complex exponential is everywhere differentiable, with the derivative `exp x`. -/
lemma has_deriv_at_exp (x : ℂ) : has_deriv_at exp (exp x) x :=
begin
rw has_deriv_at_iff_is_o_nhds_zero,
have : (1 : ℕ) < 2 := by norm_num,
refine is_O.trans_is_o (is_O_iff.2 ⟨∥exp x∥, _⟩) (is_o_pow_id this),
have : metric.ball (0 : ℂ) 1 ∈ nhds (0 : ℂ) :=
mem_nhds_sets metric.is_open_ball (by simp [zero_lt_one]),
apply filter.mem_sets_of_superset this (λz hz, _),
simp only [metric.mem_ball, dist_zero_right] at hz,
simp only [exp_zero, mul_one, one_mul, add_comm, normed_field.norm_pow,
zero_add, set.mem_set_of_eq],
calc ∥exp (x + z) - exp x - z * exp x∥
= ∥exp x * (exp z - 1 - z)∥ : by { congr, rw [exp_add], ring }
... = ∥exp x∥ * ∥exp z - 1 - z∥ : normed_field.norm_mul _ _
... ≤ ∥exp x∥ * ∥z∥^2 :
mul_le_mul_of_nonneg_left (abs_exp_sub_one_sub_id_le (le_of_lt hz)) (norm_nonneg _)
end
lemma differentiable_exp : differentiable ℂ exp :=
λx, (has_deriv_at_exp x).differentiable_at
@[simp] lemma deriv_exp : deriv exp = exp :=
funext $ λ x, (has_deriv_at_exp x).deriv
@[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp
| 0 := rfl
| (n+1) := by rw [nat.iterate_succ, deriv_exp, iter_deriv_exp n]
lemma continuous_exp : continuous exp :=
differentiable_exp.continuous
/-- The complex sine function is everywhere differentiable, with the derivative `cos x`. -/
lemma has_deriv_at_sin (x : ℂ) : has_deriv_at sin (cos x) x :=
begin
have A : has_deriv_at (λ(z:ℂ), exp (z * I)) (I * exp (x * I)) x,
{ convert (has_deriv_at_exp _).comp x ((has_deriv_at_id x).mul (has_deriv_at_const x I)),
simp },
have B : has_deriv_at (λ(z:ℂ), exp (-z * I)) (-I * exp (-x * I)) x,
{ convert (has_deriv_at_exp _).comp x ((has_deriv_at_id x).neg.mul (has_deriv_at_const x I)),
simp },
have C : has_deriv_at (λ(z:ℂ), exp (-z * I) - exp (z * I)) (-I * (exp (x * I) + exp (-x * I))) x,
by { convert has_deriv_at.sub B A, ring },
convert has_deriv_at.mul C (has_deriv_at_const x (I/(2:ℂ))),
{ ext z, simp [sin, mul_div_assoc] },
{ simp only [cos, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm, zero_add, sub_eq_add_neg, mul_zero],
rw [← mul_assoc, ← mul_div_right_comm, I_mul_I, div_eq_mul_inv, div_eq_mul_inv],
generalize : (2 : ℂ)⁻¹ = u,
ring }
end
lemma differentiable_sin : differentiable ℂ sin :=
λx, (has_deriv_at_sin x).differentiable_at
@[simp] lemma deriv_sin : deriv sin = cos :=
funext $ λ x, (has_deriv_at_sin x).deriv
lemma continuous_sin : continuous sin :=
differentiable_sin.continuous
/-- The complex cosine function is everywhere differentiable, with the derivative `-sin x`. -/
lemma has_deriv_at_cos (x : ℂ) : has_deriv_at cos (-sin x) x :=
begin
have A : has_deriv_at (λ(z:ℂ), exp (z * I)) (I * exp (x * I)) x,
{ convert (has_deriv_at_exp _).comp x ((has_deriv_at_id x).mul (has_deriv_at_const x I)),
simp },
have B : has_deriv_at (λ(z:ℂ), exp (-z * I)) (-I * exp (-x * I)) x,
{ convert (has_deriv_at_exp _).comp x ((has_deriv_at_id x).neg.mul (has_deriv_at_const x I)),
simp },
have C : has_deriv_at (λ(z:ℂ), exp (z * I) + exp (-z * I)) (I * (exp (x * I) - exp (-x * I))) x,
by { convert has_deriv_at.add A B, ring },
convert has_deriv_at.mul C (has_deriv_at_const x (1/(2:ℂ))),
{ ext z, simp [cos, mul_div_assoc], refl },
{ simp only [sin, div_eq_mul_inv, neg_mul_eq_neg_mul_symm, one_mul, zero_add, sub_eq_add_neg, mul_zero],
generalize : (2 : ℂ)⁻¹ = u,
ring }
end
lemma differentiable_cos : differentiable ℂ cos :=
λx, (has_deriv_at_cos x).differentiable_at
lemma deriv_cos {x : ℂ} : deriv cos x = -sin x :=
(has_deriv_at_cos x).deriv
@[simp] lemma deriv_cos' : deriv cos = (λ x, -sin x) :=
funext $ λ x, deriv_cos
lemma continuous_cos : continuous cos :=
differentiable_cos.continuous
lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) :=
(continuous_sin.comp continuous_subtype_val).mul
(continuous.inv subtype.property (continuous_cos.comp continuous_subtype_val))
/-- The complex hyperbolic sine function is everywhere differentiable, with the derivative `sinh x`. -/
lemma has_deriv_at_sinh (x : ℂ) : has_deriv_at sinh (cosh x) x :=
begin
have C : has_deriv_at (λ(z:ℂ), exp z - exp(-z)) (exp x + exp (-x)) x,
{ convert (has_deriv_at_exp x).sub ((has_deriv_at_exp _).comp x (has_deriv_at_id x).neg),
simp },
convert has_deriv_at.mul C (has_deriv_at_const x (1/(2:ℂ))),
{ ext z, simp [sinh, div_eq_mul_inv] },
{ simp [cosh, div_eq_mul_inv, mul_comm] }
end
lemma differentiable_sinh : differentiable ℂ sinh :=
λx, (has_deriv_at_sinh x).differentiable_at
@[simp] lemma deriv_sinh : deriv sinh = cosh :=
funext $ λ x, (has_deriv_at_sinh x).deriv
lemma continuous_sinh : continuous sinh :=
differentiable_sinh.continuous
/-- The complex hyperbolic cosine function is everywhere differentiable, with the derivative `cosh x`. -/
lemma has_deriv_at_cosh (x : ℂ) : has_deriv_at cosh (sinh x) x :=
begin
have C : has_deriv_at (λ(z:ℂ), exp z + exp(-z)) (exp x - exp (-x)) x,
{ convert (has_deriv_at_exp x).add ((has_deriv_at_exp _).comp x (has_deriv_at_id x).neg),
simp },
convert has_deriv_at.mul C (has_deriv_at_const x (1/(2:ℂ))),
{ ext z, simp [cosh, div_eq_mul_inv] },
{ simp [sinh, div_eq_mul_inv, mul_comm] }
end
lemma differentiable_cosh : differentiable ℂ cosh :=
λx, (has_deriv_at_cosh x).differentiable_at
@[simp] lemma deriv_cosh : deriv cosh = sinh :=
funext $ λ x, (has_deriv_at_cosh x).deriv
lemma continuous_cosh : continuous cosh :=
differentiable_cosh.continuous
end complex
namespace real
variables {x y z : ℝ}
lemma has_deriv_at_exp (x : ℝ) : has_deriv_at exp (exp x) x :=
has_deriv_at_real_of_complex (complex.has_deriv_at_exp x)
lemma differentiable_exp : differentiable ℝ exp :=
λx, (has_deriv_at_exp x).differentiable_at
@[simp] lemma deriv_exp : deriv exp = exp :=
funext $ λ x, (has_deriv_at_exp x).deriv
@[simp] lemma iter_deriv_exp : ∀ n : ℕ, (deriv^[n] exp) = exp
| 0 := rfl
| (n+1) := by rw [nat.iterate_succ, deriv_exp, iter_deriv_exp n]
lemma continuous_exp : continuous exp :=
differentiable_exp.continuous
lemma has_deriv_at_sin (x : ℝ) : has_deriv_at sin (cos x) x :=
has_deriv_at_real_of_complex (complex.has_deriv_at_sin x)
lemma differentiable_sin : differentiable ℝ sin :=
λx, (has_deriv_at_sin x).differentiable_at
@[simp] lemma deriv_sin : deriv sin = cos :=
funext $ λ x, (has_deriv_at_sin x).deriv
lemma continuous_sin : continuous sin :=
differentiable_sin.continuous
lemma has_deriv_at_cos (x : ℝ) : has_deriv_at cos (-sin x) x :=
(has_deriv_at_real_of_complex (complex.has_deriv_at_cos x) : _)
lemma differentiable_cos : differentiable ℝ cos :=
λx, (has_deriv_at_cos x).differentiable_at
lemma deriv_cos : deriv cos x = - sin x :=
(has_deriv_at_cos x).deriv
@[simp] lemma deriv_cos' : deriv cos = (λ x, - sin x) :=
funext $ λ _, deriv_cos
lemma continuous_cos : continuous cos :=
differentiable_cos.continuous
lemma continuous_tan : continuous (λ x : {x // cos x ≠ 0}, tan x) :=
by simp only [tan_eq_sin_div_cos]; exact
(continuous_sin.comp continuous_subtype_val).mul
(continuous.inv subtype.property
(continuous_cos.comp continuous_subtype_val))
lemma has_deriv_at_sinh (x : ℝ) : has_deriv_at sinh (cosh x) x :=
has_deriv_at_real_of_complex (complex.has_deriv_at_sinh x)
lemma differentiable_sinh : differentiable ℝ sinh :=
λx, (has_deriv_at_sinh x).differentiable_at
@[simp] lemma deriv_sinh : deriv sinh = cosh :=
funext $ λ x, (has_deriv_at_sinh x).deriv
lemma continuous_sinh : continuous sinh :=
differentiable_sinh.continuous
lemma has_deriv_at_cosh (x : ℝ) : has_deriv_at cosh (sinh x) x :=
has_deriv_at_real_of_complex (complex.has_deriv_at_cosh x)
lemma differentiable_cosh : differentiable ℝ cosh :=
λx, (has_deriv_at_cosh x).differentiable_at
@[simp] lemma deriv_cosh : deriv cosh = sinh :=
funext $ λ x, (has_deriv_at_cosh x).deriv
lemma continuous_cosh : continuous cosh :=
differentiable_cosh.continuous
lemma exists_exp_eq_of_pos {x : ℝ} (hx : 0 < x) : ∃ y, exp y = x :=
have ∀ {z:ℝ}, 1 ≤ z → z ∈ set.range exp,
from λ z hz, intermediate_value_univ 0 (z - 1) continuous_exp
⟨by simpa, by simpa using add_one_le_exp_of_nonneg (sub_nonneg.2 hz)⟩,
match le_total x 1 with
| (or.inl hx1) := let ⟨y, hy⟩ := this (one_le_inv hx hx1) in
⟨-y, by rw [exp_neg, hy, inv_inv']⟩
| (or.inr hx1) := this hx1
end
/-- The real logarithm function, equal to `0` for `x ≤ 0` and to the inverse of the exponential
for `x > 0`. -/
noncomputable def log (x : ℝ) : ℝ :=
if hx : 0 < x then classical.some (exists_exp_eq_of_pos hx) else 0
lemma exp_log {x : ℝ} (hx : 0 < x) : exp (log x) = x :=
by rw [log, dif_pos hx]; exact classical.some_spec (exists_exp_eq_of_pos hx)
@[simp] lemma log_exp (x : ℝ) : log (exp x) = x :=
exp_injective $ exp_log (exp_pos x)
@[simp] lemma log_zero : log 0 = 0 :=
by simp [log, lt_irrefl]
@[simp] lemma log_one : log 1 = 0 :=
exp_injective $ by rw [exp_log zero_lt_one, exp_zero]
lemma log_mul {x y : ℝ} (hx : 0 < x) (hy : 0 < y) : log (x * y) = log x + log y :=
exp_injective $ by rw [exp_log (mul_pos hx hy), exp_add, exp_log hx, exp_log hy]
lemma log_le_log {x y : ℝ} (h : 0 < x) (h₁ : 0 < y) : real.log x ≤ real.log y ↔ x ≤ y :=
⟨λ h₂, by rwa [←real.exp_le_exp, real.exp_log h, real.exp_log h₁] at h₂, λ h₂,
(real.exp_le_exp).1 $ by rwa [real.exp_log h₁, real.exp_log h]⟩
lemma log_lt_log (hx : 0 < x) : x < y → log x < log y :=
by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] }
lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y :=
by { rw [← exp_lt_exp, exp_log hx, exp_log hy] }
lemma log_pos_iff (x : ℝ) : 0 < log x ↔ 1 < x :=
begin
by_cases h : 0 < x,
{ rw ← log_one, exact log_lt_log_iff (by norm_num) h },
{ rw [log, dif_neg], split, repeat {intro, linarith} }
end
lemma log_pos : 1 < x → 0 < log x := (log_pos_iff x).2
lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 :=
by { rw ← log_one, exact log_lt_log_iff h (by norm_num) }
lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1
lemma log_nonneg : 1 ≤ x → 0 ≤ log x :=
by { intro, rwa [← log_one, log_le_log], norm_num, linarith }
lemma log_nonpos : x ≤ 1 → log x ≤ 0 :=
begin
intro, by_cases hx : 0 < x,
{ rwa [← log_one, log_le_log], exact hx, norm_num },
{ simp [log, dif_neg hx] }
end
section prove_log_is_continuous
lemma tendsto_log_one_zero : tendsto log (𝓝 1) (𝓝 0) :=
begin
rw tendsto_nhds_nhds, assume ε ε0,
let δ := min (exp ε - 1) (1 - exp (-ε)),
have : 0 < δ,
refine lt_min (sub_pos_of_lt (by rwa one_lt_exp_iff)) (sub_pos_of_lt _),
by { rw exp_lt_one_iff, linarith },
use [δ, this], assume x h,
cases le_total 1 x with hx hx,
{ have h : x < exp ε,
rw [dist_eq, abs_of_nonneg (sub_nonneg_of_le hx)] at h,
linarith [(min_le_left _ _ : δ ≤ exp ε - 1)],
calc abs (log x - 0) = abs (log x) : by simp
... = log x : abs_of_nonneg $ log_nonneg hx
... < ε : by { rwa [← exp_lt_exp, exp_log], linarith }},
{ have h : exp (-ε) < x,
rw [dist_eq, abs_of_nonpos (sub_nonpos_of_le hx)] at h,
linarith [(min_le_right _ _ : δ ≤ 1 - exp (-ε))],
have : 0 < x := lt_trans (exp_pos _) h,
calc abs (log x - 0) = abs (log x) : by simp
... = -log x : abs_of_nonpos $ log_nonpos hx
... < ε : by { rw [neg_lt, ← exp_lt_exp, exp_log], assumption' } }
end
lemma continuous_log' : continuous (λx : {x:ℝ // 0 < x}, log x.val) :=
continuous_iff_continuous_at.2 $ λ x,
begin
rw continuous_at,
let f₁ := λ h:{h:ℝ // 0 < h}, log (x.1 * h.1),
let f₂ := λ y:{y:ℝ // 0 < y}, subtype.mk (x.1 ⁻¹ * y.1) (mul_pos (inv_pos x.2) y.2),
have H1 : tendsto f₁ (𝓝 ⟨1, zero_lt_one⟩) (𝓝 (log (x.1*1))),
have : f₁ = λ h:{h:ℝ // 0 < h}, log x.1 + log h.1,
ext h, rw ← log_mul x.2 h.2,
simp only [this, log_mul x.2 zero_lt_one, log_one],
exact tendsto_const_nhds.add (tendsto.comp tendsto_log_one_zero continuous_at_subtype_val),
have H2 : tendsto f₂ (𝓝 x) (𝓝 ⟨x.1⁻¹ * x.1, mul_pos (inv_pos x.2) x.2⟩),
rw tendsto_subtype_rng, exact tendsto_const_nhds.mul continuous_at_subtype_val,
suffices h : tendsto (f₁ ∘ f₂) (𝓝 x) (𝓝 (log x.1)),
begin
convert h, ext y,
have : x.val * (x.val⁻¹ * y.val) = y.val,
rw [← mul_assoc, mul_inv_cancel (ne_of_gt x.2), one_mul],
show log (y.val) = log (x.val * (x.val⁻¹ * y.val)), rw this
end,
exact tendsto.comp (by rwa mul_one at H1)
(by { simp only [inv_mul_cancel (ne_of_gt x.2)] at H2, assumption })
end
lemma continuous_at_log (hx : 0 < x) : continuous_at log x :=
continuous_within_at.continuous_at (continuous_on_iff_continuous_restrict.2 continuous_log' _ hx)
(mem_nhds_sets (is_open_lt' _) hx)
/--
Three forms of the continuity of `real.log` is provided.
For the other two forms, see `real.continuous_log'` and `real.continuous_at_log`
-/
lemma continuous_log {α : Type*} [topological_space α] {f : α → ℝ} (h : ∀a, 0 < f a)
(hf : continuous f) : continuous (λa, log (f a)) :=
show continuous ((log ∘ @subtype.val ℝ (λr, 0 < r)) ∘ λa, ⟨f a, h a⟩),
from continuous_log'.comp (continuous_subtype_mk _ hf)
end prove_log_is_continuous
lemma exists_cos_eq_zero : 0 ∈ cos '' set.Icc (1:ℝ) 2 :=
intermediate_value_Icc' (by norm_num) continuous_cos.continuous_on
⟨le_of_lt cos_two_neg, le_of_lt cos_one_pos⟩
/-- The number π = 3.14159265... Defined here using choice as twice a zero of cos in [1,2], from
which one can derive all its properties. For explicit bounds on π, see `data.real.pi`. -/
noncomputable def pi : ℝ := 2 * classical.some exists_cos_eq_zero
localized "notation `π` := real.pi" in real
@[simp] lemma cos_pi_div_two : cos (π / 2) = 0 :=
by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)];
exact (classical.some_spec exists_cos_eq_zero).2
lemma one_le_pi_div_two : (1 : ℝ) ≤ π / 2 :=
by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)];
exact (classical.some_spec exists_cos_eq_zero).1.1
lemma pi_div_two_le_two : π / 2 ≤ 2 :=
by rw [pi, mul_div_cancel_left _ (@two_ne_zero' ℝ _ _ _)];
exact (classical.some_spec exists_cos_eq_zero).1.2
lemma two_le_pi : (2 : ℝ) ≤ π :=
(div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1
(by rw div_self (@two_ne_zero' ℝ _ _ _); exact one_le_pi_div_two)
lemma pi_le_four : π ≤ 4 :=
(div_le_div_right (show (0 : ℝ) < 2, by norm_num)).1
(calc π / 2 ≤ 2 : pi_div_two_le_two
... = 4 / 2 : by norm_num)
lemma pi_pos : 0 < π :=
lt_of_lt_of_le (by norm_num) two_le_pi
lemma pi_div_two_pos : 0 < π / 2 :=
half_pos pi_pos
lemma two_pi_pos : 0 < 2 * π :=
by linarith [pi_pos]
@[simp] lemma sin_pi : sin π = 0 :=
by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), two_mul, add_div,
sin_add, cos_pi_div_two]; simp
@[simp] lemma cos_pi : cos π = -1 :=
by rw [← mul_div_cancel_left pi (@two_ne_zero ℝ _), mul_div_assoc,
cos_two_mul, cos_pi_div_two];
simp [bit0, pow_add]
@[simp] lemma sin_two_pi : sin (2 * π) = 0 :=
by simp [two_mul, sin_add]
@[simp] lemma cos_two_pi : cos (2 * π) = 1 :=
by simp [two_mul, cos_add]
lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x :=
by simp [sin_add]
lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x :=
by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi]
lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x :=
by simp [cos_add, cos_two_pi, sin_two_pi]
lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x :=
by simp [sin_add]
lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x :=
by simp [cos_add]
lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x :=
by simp [cos_add]
lemma sin_pos_of_pos_of_lt_pi {x : ℝ} (h0x : 0 < x) (hxp : x < π) : 0 < sin x :=
if hx2 : x ≤ 2 then sin_pos_of_pos_of_le_two h0x hx2
else
have (2 : ℝ) + 2 = 4, from rfl,
have π - x ≤ 2, from sub_le_iff_le_add.2
(le_trans pi_le_four (this ▸ add_le_add_left (le_of_not_ge hx2) _)),
sin_pi_sub x ▸ sin_pos_of_pos_of_le_two (sub_pos.2 hxp) this
lemma sin_nonneg_of_nonneg_of_le_pi {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π) : 0 ≤ sin x :=
match lt_or_eq_of_le h0x with
| or.inl h0x := (lt_or_eq_of_le hxp).elim
(le_of_lt ∘ sin_pos_of_pos_of_lt_pi h0x)
(λ hpx, by simp [hpx])
| or.inr h0x := by simp [h0x.symm]
end
lemma sin_neg_of_neg_of_neg_pi_lt {x : ℝ} (hx0 : x < 0) (hpx : -π < x) : sin x < 0 :=
neg_pos.1 $ sin_neg x ▸ sin_pos_of_pos_of_lt_pi (neg_pos.2 hx0) (neg_lt.1 hpx)
lemma sin_nonpos_of_nonnpos_of_neg_pi_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -π ≤ x) : sin x ≤ 0 :=
neg_nonneg.1 $ sin_neg x ▸ sin_nonneg_of_nonneg_of_le_pi (neg_nonneg.2 hx0) (neg_le.1 hpx)
@[simp] lemma sin_pi_div_two : sin (π / 2) = 1 :=
have sin (π / 2) = 1 ∨ sin (π / 2) = -1 :=
by simpa [pow_two, mul_self_eq_one_iff] using sin_sq_add_cos_sq (π / 2),
this.resolve_right
(λ h, (show ¬(0 : ℝ) < -1, by norm_num) $
h ▸ sin_pos_of_pos_of_lt_pi pi_div_two_pos (half_lt_self pi_pos))
lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x :=
by simp [sin_add]
lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x :=
by simp [sin_add]
lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x :=
by simp [sin_add]
lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x :=
by simp [cos_add]
lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x :=
by simp [cos_add]
lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x :=
by rw [← cos_neg, neg_sub, cos_sub_pi_div_two]
lemma cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two
{x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : 0 < cos x :=
sin_add_pi_div_two x ▸ sin_pos_of_pos_of_lt_pi (by linarith) (by linarith)
lemma cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two
{x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : 0 ≤ cos x :=
match lt_or_eq_of_le hx₁, lt_or_eq_of_le hx₂ with
| or.inl hx₁, or.inl hx₂ := le_of_lt (cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two hx₁ hx₂)
| or.inl hx₁, or.inr hx₂ := by simp [hx₂]
| or.inr hx₁, _ := by simp [hx₁.symm]
end
lemma cos_neg_of_pi_div_two_lt_of_lt {x : ℝ} (hx₁ : π / 2 < x) (hx₂ : x < π + π / 2) : cos x < 0 :=
neg_pos.1 $ cos_pi_sub x ▸
cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) (by linarith)
lemma cos_nonpos_of_pi_div_two_le_of_le {x : ℝ} (hx₁ : π / 2 ≤ x) (hx₂ : x ≤ π + π / 2) : cos x ≤ 0 :=
neg_nonneg.1 $ cos_pi_sub x ▸
cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two (by linarith) (by linarith)
lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 :=
by induction n; simp [add_mul, sin_add, *]
lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 :=
by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi]
lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 :=
by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi]
lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 :=
by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe,
int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg,
(neg_mul_eq_neg_mul _ _).symm, cos_neg]
lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 :=
by simp [cos_add, sin_add, cos_int_mul_two_pi]
lemma sin_eq_zero_iff_of_lt_of_lt {x : ℝ} (hx₁ : -π < x) (hx₂ : x < π) :
sin x = 0 ↔ x = 0 :=
⟨λ h, le_antisymm
(le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $
calc 0 < sin x : sin_pos_of_pos_of_lt_pi h0 hx₂
... = 0 : h))
(le_of_not_gt (λ h0, lt_irrefl (0 : ℝ) $
calc 0 = sin x : h.symm
... < 0 : sin_neg_of_neg_of_neg_pi_lt h0 hx₁)),
λ h, by simp [h]⟩
lemma sin_eq_zero_iff {x : ℝ} : sin x = 0 ↔ ∃ n : ℤ, (n : ℝ) * π = x :=
⟨λ h, ⟨⌊x / π⌋, le_antisymm (sub_nonneg.1 (sub_floor_div_mul_nonneg _ pi_pos))
(sub_nonpos.1 $ le_of_not_gt $ λ h₃, ne_of_lt (sin_pos_of_pos_of_lt_pi h₃ (sub_floor_div_mul_lt _ pi_pos))
(by simp [sin_add, h, sin_int_mul_pi]))⟩,
λ ⟨n, hn⟩, hn ▸ sin_int_mul_pi _⟩
lemma sin_eq_zero_iff_cos_eq {x : ℝ} : sin x = 0 ↔ cos x = 1 ∨ cos x = -1 :=
by rw [← mul_self_eq_one_iff (cos x), ← sin_sq_add_cos_sq x,
pow_two, pow_two, ← sub_eq_iff_eq_add, sub_self];
exact ⟨λ h, by rw [h, mul_zero], eq_zero_of_mul_self_eq_zero ∘ eq.symm⟩
theorem sin_sub_sin (θ ψ : ℝ) : sin θ - sin ψ = 2 * sin((θ - ψ)/2) * cos((θ + ψ)/2) :=
begin
have s1 := sin_add ((θ + ψ) / 2) ((θ - ψ) / 2),
have s2 := sin_sub ((θ + ψ) / 2) ((θ - ψ) / 2),
rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, add_self_div_two] at s1,
rw [div_sub_div_same, ←sub_add, add_sub_cancel', add_self_div_two] at s2,
rw [s1, s2, ←sub_add, add_sub_cancel', ← two_mul, ← mul_assoc, mul_right_comm]
end
lemma cos_eq_one_iff (x : ℝ) : cos x = 1 ↔ ∃ n : ℤ, (n : ℝ) * (2 * π) = x :=
⟨λ h, let ⟨n, hn⟩ := sin_eq_zero_iff.1 (sin_eq_zero_iff_cos_eq.2 (or.inl h)) in
⟨n / 2, (int.mod_two_eq_zero_or_one n).elim
(λ hn0, by rwa [← mul_assoc, ← @int.cast_two ℝ, ← int.cast_mul, int.div_mul_cancel
((int.dvd_iff_mod_eq_zero _ _).2 hn0)])
(λ hn1, by rw [← int.mod_add_div n 2, hn1, int.cast_add, int.cast_one, add_mul,
one_mul, add_comm, mul_comm (2 : ℤ), int.cast_mul, mul_assoc, int.cast_two] at hn;
rw [← hn, cos_int_mul_two_pi_add_pi] at h;
exact absurd h (by norm_num))⟩,
λ ⟨n, hn⟩, hn ▸ cos_int_mul_two_pi _⟩
theorem cos_eq_zero_iff {θ : ℝ} : cos θ = 0 ↔ ∃ k : ℤ, θ = (2 * k + 1) * pi / 2 :=
begin
rw [←real.sin_pi_div_two_sub, sin_eq_zero_iff],
split,
{ rintro ⟨n, hn⟩, existsi -n,
rw [int.cast_neg, add_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero,
one_mul, ←neg_mul_eq_neg_mul, hn, neg_sub, sub_add_cancel] },
{ rintro ⟨n, hn⟩, existsi -n,
rw [hn, add_mul, one_mul, add_div, mul_assoc, mul_div_cancel_left _ two_ne_zero,
sub_add_eq_sub_sub_swap, sub_self, zero_sub, neg_mul_eq_neg_mul, int.cast_neg] }
end
lemma cos_eq_one_iff_of_lt_of_lt {x : ℝ} (hx₁ : -(2 * π) < x) (hx₂ : x < 2 * π) : cos x = 1 ↔ x = 0 :=
⟨λ h, let ⟨n, hn⟩ := (cos_eq_one_iff x).1 h in
begin
clear _let_match,
subst hn,
rw [mul_lt_iff_lt_one_left two_pi_pos, ← int.cast_one, int.cast_lt, ← int.le_sub_one_iff, sub_self] at hx₂,
rw [neg_lt, neg_mul_eq_neg_mul, mul_lt_iff_lt_one_left two_pi_pos, neg_lt,
← int.cast_one, ← int.cast_neg, int.cast_lt, ← int.add_one_le_iff, neg_add_self] at hx₁,
exact mul_eq_zero.2 (or.inl (int.cast_eq_zero.2 (le_antisymm hx₂ hx₁))),
end,
λ h, by simp [h]⟩
theorem cos_sub_cos (θ ψ : ℝ) : cos θ - cos ψ = -2 * sin((θ + ψ)/2) * sin((θ - ψ)/2) :=
by rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub, sin_sub_sin, sub_sub_sub_cancel_left,
add_sub, sub_add_eq_add_sub, add_halves, sub_sub, sub_div π, cos_pi_div_two_sub,
← neg_sub, neg_div, sin_neg, ← neg_mul_eq_mul_neg, neg_mul_eq_neg_mul, mul_right_comm]
lemma cos_lt_cos_of_nonneg_of_le_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π / 2)
(hy₁ : 0 ≤ y) (hy₂ : y ≤ π / 2) (hxy : x < y) : cos y < cos x :=
calc cos y = cos x * cos (y - x) - sin x * sin (y - x) :
by rw [← cos_add, add_sub_cancel'_right]
... < (cos x * 1) - sin x * sin (y - x) :
sub_lt_sub_right ((mul_lt_mul_left
(cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (lt_of_lt_of_le (neg_neg_of_pos pi_div_two_pos) hx₁)
(lt_of_lt_of_le hxy hy₂))).2
(lt_of_le_of_ne (cos_le_one _) (mt (cos_eq_one_iff_of_lt_of_lt
(show -(2 * π) < y - x, by linarith) (show y - x < 2 * π, by linarith)).1
(sub_ne_zero.2 (ne_of_lt hxy).symm)))) _
... ≤ _ : by rw mul_one;
exact sub_le_self _ (mul_nonneg (sin_nonneg_of_nonneg_of_le_pi hx₁ (by linarith))
(sin_nonneg_of_nonneg_of_le_pi (by linarith) (by linarith)))
lemma cos_lt_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π)
(hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x < y) : cos y < cos x :=
match (le_total x (π / 2) : x ≤ π / 2 ∨ π / 2 ≤ x), le_total y (π / 2) with
| or.inl hx, or.inl hy := cos_lt_cos_of_nonneg_of_le_pi_div_two hx₁ hx hy₁ hy hxy
| or.inl hx, or.inr hy := (lt_or_eq_of_le hx).elim
(λ hx, calc cos y ≤ 0 : cos_nonpos_of_pi_div_two_le_of_le hy (by linarith [pi_pos])
... < cos x : cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hx)
(λ hx, calc cos y < 0 : cos_neg_of_pi_div_two_lt_of_lt (by linarith) (by linarith [pi_pos])
... = cos x : by rw [hx, cos_pi_div_two])
| or.inr hx, or.inl hy := by linarith
| or.inr hx, or.inr hy := neg_lt_neg_iff.1 (by rw [← cos_pi_sub, ← cos_pi_sub];
apply cos_lt_cos_of_nonneg_of_le_pi_div_two; linarith)
end
lemma cos_le_cos_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π)
(hy₁ : 0 ≤ y) (hy₂ : y ≤ π) (hxy : x ≤ y) : cos y ≤ cos x :=
(lt_or_eq_of_le hxy).elim
(le_of_lt ∘ cos_lt_cos_of_nonneg_of_le_pi hx₁ hx₂ hy₁ hy₂)
(λ h, h ▸ le_refl _)
lemma sin_lt_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y)
(hy₂ : y ≤ π / 2) (hxy : x < y) : sin x < sin y :=
by rw [← cos_sub_pi_div_two, ← cos_sub_pi_div_two, ← cos_neg (x - _), ← cos_neg (y - _)];
apply cos_lt_cos_of_nonneg_of_le_pi; linarith
lemma sin_le_sin_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y)
(hy₂ : y ≤ π / 2) (hxy : x ≤ y) : sin x ≤ sin y :=
(lt_or_eq_of_le hxy).elim
(le_of_lt ∘ sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂)
(λ h, h ▸ le_refl _)
lemma sin_inj_of_le_of_le_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) (hy₁ : -(π / 2) ≤ y)
(hy₂ : y ≤ π / 2) (hxy : sin x = sin y) : x = y :=
match lt_trichotomy x y with
| or.inl h := absurd (sin_lt_sin_of_le_of_le_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _)
| or.inr (or.inl h) := h
| or.inr (or.inr h) := absurd (sin_lt_sin_of_le_of_le_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _)
end
lemma cos_inj_of_nonneg_of_le_pi {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) (hy₁ : 0 ≤ y) (hy₂ : y ≤ π)
(hxy : cos x = cos y) : x = y :=
begin
rw [← sin_pi_div_two_sub, ← sin_pi_div_two_sub] at hxy,
refine (sub_left_inj).1 (sin_inj_of_le_of_le_pi_div_two _ _ _ _ hxy);
linarith
end
lemma exists_sin_eq : set.Icc (-1:ℝ) 1 ⊆ sin '' set.Icc (-(π / 2)) (π / 2) :=
by convert intermediate_value_Icc
(le_trans (neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos))
continuous_sin.continuous_on; simp only [sin_neg, sin_pi_div_two]
lemma sin_lt {x : ℝ} (h : 0 < x) : sin x < x :=
begin
cases le_or_gt x 1 with h' h',
{ have hx : abs x = x := abs_of_nonneg (le_of_lt h),
have : abs x ≤ 1, rwa [hx],
have := sin_bound this, rw [abs_le] at this,
have := this.2, rw [sub_le_iff_le_add', hx] at this,
apply lt_of_le_of_lt this, rw [sub_add], apply lt_of_lt_of_le _ (le_of_eq (sub_zero x)),
apply sub_lt_sub_left, rw sub_pos, apply mul_lt_mul',
{ rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)),
rw mul_le_mul_right, exact h', apply pow_pos h },
norm_num, norm_num, apply pow_pos h },
exact lt_of_le_of_lt (sin_le_one x) h'
end
/- note 1: this inequality is not tight, the tighter inequality is sin x > x - x ^ 3 / 6.
note 2: this is also true for x > 1, but it's nontrivial for x just above 1. -/
lemma sin_gt_sub_cube {x : ℝ} (h : 0 < x) (h' : x ≤ 1) : x - x ^ 3 / 4 < sin x :=
begin
have hx : abs x = x := abs_of_nonneg (le_of_lt h),
have : abs x ≤ 1, rwa [hx],
have := sin_bound this, rw [abs_le] at this,
have := this.1, rw [le_sub_iff_add_le, hx] at this,
refine lt_of_lt_of_le _ this,
rw [add_comm, sub_add, sub_neg_eq_add], apply sub_lt_sub_left,
apply add_lt_of_lt_sub_left,
rw (show x ^ 3 / 4 - x ^ 3 / 6 = x ^ 3 / 12,
by simp [div_eq_mul_inv, (mul_sub _ _ _).symm, -sub_eq_add_neg]; congr; norm_num),
apply mul_lt_mul',
{ rw [pow_succ x 3], refine le_trans _ (le_of_eq (one_mul _)),
rw mul_le_mul_right, exact h', apply pow_pos h },
norm_num, norm_num, apply pow_pos h
end
/-- The type of angles -/
def angle : Type :=
quotient_add_group.quotient (gmultiples (2 * π))
namespace angle
instance angle.add_comm_group : add_comm_group angle :=
quotient_add_group.add_comm_group _
instance angle.has_coe : has_coe ℝ angle :=
⟨quotient.mk'⟩
instance angle.is_add_group_hom : is_add_group_hom (coe : ℝ → angle) :=
@quotient_add_group.is_add_group_hom _ _ _ (normal_add_subgroup_of_add_comm_group _)
@[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl
@[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl
@[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl
@[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl
@[simp] lemma coe_gsmul (x : ℝ) (n : ℤ) : ↑(gsmul n x : ℝ) = gsmul n (↑x : angle) := is_add_group_hom.map_gsmul _ _ _
@[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) :=
quotient.sound' ⟨-1, by dsimp only; rw [neg_one_gsmul, add_zero]⟩
lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k :=
by simp only [quotient_add_group.eq, gmultiples, set.mem_range, gsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm]
theorem cos_eq_iff_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ :=
begin
split,
{ intro Hcos,
rw [←sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro two_ne_zero,
false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos,
rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩,
{ right,
rw [eq_div_iff_mul_eq _ _ two_ne_zero, ← sub_eq_iff_eq_add] at hn,
rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc,
← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero] },
{ left,
rw [eq_div_iff_mul_eq _ _ two_ne_zero, eq_sub_iff_add_eq] at hn,
rw [← hn, coe_add, mul_assoc,
← gsmul_eq_mul, coe_gsmul, mul_comm, coe_two_pi, gsmul_zero, zero_add] } },
{ rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub],
rintro (⟨k, H⟩ | ⟨k, H⟩),
rw [← sub_eq_zero_iff_eq, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero,
mul_comm π _, sin_int_mul_pi, mul_zero],
rw [←sub_eq_zero_iff_eq, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k,
mul_div_cancel_left _ two_ne_zero, mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] }
end
theorem sin_eq_iff_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π :=
begin
split,
{ intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin,
cases cos_eq_iff_eq_or_eq_neg.mp Hsin with h h,
{ left, rw coe_sub at h, exact sub_left_inj.1 h },
right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub,
sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h,
exact h.symm },
{ rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub],
rintro (⟨k, H⟩ | ⟨k, H⟩),
rw [← sub_eq_zero_iff_eq, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ two_ne_zero,
mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul],
have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add,
mul_assoc, mul_comm π _, ←mul_assoc] at H,
rw [← sub_eq_zero_iff_eq, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ two_ne_zero,
cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] }
end
theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ :=
begin
cases cos_eq_iff_eq_or_eq_neg.mp Hcos with hc hc, { exact hc },
cases sin_eq_iff_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs },
rw [eq_neg_iff_add_eq_zero, hs] at hc,
cases quotient.exact' hc with n hn, dsimp only at hn,
rw [← neg_one_mul, add_zero, ← sub_eq_zero_iff_eq, gsmul_eq_mul, ← mul_assoc, ← sub_mul,
mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add,
← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn,
have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn,
rw [add_comm, int.add_mul_mod_self] at this,
exact absurd this one_ne_zero
end
end angle
/-- Inverse of the `sin` function, returns values in the range `-π / 2 ≤ arcsin x` and `arcsin x ≤ π / 2`.
If the argument is not between `-1` and `1` it defaults to `0` -/
noncomputable def arcsin (x : ℝ) : ℝ :=
if hx : -1 ≤ x ∧ x ≤ 1 then classical.some (exists_sin_eq hx) else 0
lemma arcsin_le_pi_div_two (x : ℝ) : arcsin x ≤ π / 2 :=
if hx : -1 ≤ x ∧ x ≤ 1
then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.2
else by rw [arcsin, dif_neg hx]; exact le_of_lt pi_div_two_pos
lemma neg_pi_div_two_le_arcsin (x : ℝ) : -(π / 2) ≤ arcsin x :=
if hx : -1 ≤ x ∧ x ≤ 1
then by rw [arcsin, dif_pos hx]; exact (classical.some_spec (exists_sin_eq hx)).1.1
else by rw [arcsin, dif_neg hx]; exact neg_nonpos.2 (le_of_lt pi_div_two_pos)
lemma sin_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arcsin x) = x :=
by rw [arcsin, dif_pos (and.intro hx₁ hx₂)];
exact (classical.some_spec (exists_sin_eq ⟨hx₁, hx₂⟩)).2
lemma arcsin_sin {x : ℝ} (hx₁ : -(π / 2) ≤ x) (hx₂ : x ≤ π / 2) : arcsin (sin x) = x :=
sin_inj_of_le_of_le_pi_div_two (neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _) hx₁ hx₂
(by rw sin_arcsin (neg_one_le_sin _) (sin_le_one _))
lemma arcsin_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1)
(hxy : arcsin x = arcsin y) : x = y :=
by rw [← sin_arcsin hx₁ hx₂, ← sin_arcsin hy₁ hy₂, hxy]
@[simp] lemma arcsin_zero : arcsin 0 = 0 :=
sin_inj_of_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _)
(arcsin_le_pi_div_two _)
(neg_nonpos.2 (le_of_lt pi_div_two_pos))
(le_of_lt pi_div_two_pos)
(by rw [sin_arcsin, sin_zero]; norm_num)
@[simp] lemma arcsin_one : arcsin 1 = π / 2 :=
sin_inj_of_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _)
(arcsin_le_pi_div_two _)
(by linarith [pi_pos])
(le_refl _)
(by rw [sin_arcsin, sin_pi_div_two]; norm_num)
@[simp] lemma arcsin_neg (x : ℝ) : arcsin (-x) = -arcsin x :=
if h : -1 ≤ x ∧ x ≤ 1 then
have -1 ≤ -x ∧ -x ≤ 1, by rwa [neg_le_neg_iff, neg_le, and.comm],
sin_inj_of_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _)
(arcsin_le_pi_div_two _)
(neg_le_neg (arcsin_le_pi_div_two _))
(neg_le.1 (neg_pi_div_two_le_arcsin _))
(by rw [sin_arcsin this.1 this.2, sin_neg, sin_arcsin h.1 h.2])
else
have ¬(-1 ≤ -x ∧ -x ≤ 1) := by rwa [neg_le_neg_iff, neg_le, and.comm],
by rw [arcsin, arcsin, dif_neg h, dif_neg this, neg_zero]
@[simp] lemma arcsin_neg_one : arcsin (-1) = -(π / 2) := by simp
lemma arcsin_nonneg {x : ℝ} (hx : 0 ≤ x) : 0 ≤ arcsin x :=
if hx₁ : x ≤ 1 then
not_lt.1 (λ h, not_lt.2 hx begin
have := sin_lt_sin_of_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _)
(neg_nonpos.2 (le_of_lt pi_div_two_pos)) (le_of_lt pi_div_two_pos) h,
rw [real.sin_arcsin, sin_zero] at this; linarith
end)
else by rw [arcsin, dif_neg]; simp [hx₁]
lemma arcsin_eq_zero_iff {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : arcsin x = 0 ↔ x = 0 :=
⟨λ h, have sin (arcsin x) = 0, by simp [h],
by rwa [sin_arcsin hx₁ hx₂] at this,
λ h, by simp [h]⟩
lemma arcsin_pos {x : ℝ} (hx₁ : 0 < x) (hx₂ : x ≤ 1) : 0 < arcsin x :=
lt_of_le_of_ne (arcsin_nonneg (le_of_lt hx₁))
(ne.symm (mt (arcsin_eq_zero_iff (by linarith) hx₂).1 (ne_of_lt hx₁).symm))
lemma arcsin_nonpos {x : ℝ} (hx : x ≤ 0) : arcsin x ≤ 0 :=
neg_nonneg.1 (arcsin_neg x ▸ arcsin_nonneg (neg_nonneg.2 hx))
/-- Inverse of the `cos` function, returns values in the range `0 ≤ arccos x` and `arccos x ≤ π`.
If the argument is not between `-1` and `1` it defaults to `π / 2` -/
noncomputable def arccos (x : ℝ) : ℝ :=
π / 2 - arcsin x
lemma arccos_eq_pi_div_two_sub_arcsin (x : ℝ) : arccos x = π / 2 - arcsin x := rfl
lemma arcsin_eq_pi_div_two_sub_arccos (x : ℝ) : arcsin x = π / 2 - arccos x := by simp [arccos]
lemma arccos_le_pi (x : ℝ) : arccos x ≤ π :=
by unfold arccos; linarith [neg_pi_div_two_le_arcsin x]
lemma arccos_nonneg (x : ℝ) : 0 ≤ arccos x :=
by unfold arccos; linarith [arcsin_le_pi_div_two x]
lemma cos_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arccos x) = x :=
by rw [arccos, cos_pi_div_two_sub, sin_arcsin hx₁ hx₂]
lemma arccos_cos {x : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x ≤ π) : arccos (cos x) = x :=
by rw [arccos, ← sin_pi_div_two_sub, arcsin_sin]; simp; linarith
lemma arccos_inj {x y : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) (hy₁ : -1 ≤ y) (hy₂ : y ≤ 1)
(hxy : arccos x = arccos y) : x = y :=
arcsin_inj hx₁ hx₂ hy₁ hy₂ $ by simp [arccos, *] at *
@[simp] lemma arccos_zero : arccos 0 = π / 2 := by simp [arccos]
@[simp] lemma arccos_one : arccos 1 = 0 := by simp [arccos]
@[simp] lemma arccos_neg_one : arccos (-1) = π := by simp [arccos, add_halves]
lemma arccos_neg (x : ℝ) : arccos (-x) = π - arccos x :=
by rw [← add_halves π, arccos, arcsin_neg, arccos, add_sub_assoc, sub_sub_self]; simp
lemma cos_arcsin_nonneg (x : ℝ) : 0 ≤ cos (arcsin x) :=
cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two
(neg_pi_div_two_le_arcsin _) (arcsin_le_pi_div_two _)
lemma cos_arcsin {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : cos (arcsin x) = sqrt (1 - x ^ 2) :=
have sin (arcsin x) ^ 2 + cos (arcsin x) ^ 2 = 1 := sin_sq_add_cos_sq (arcsin x),
begin
rw [← eq_sub_iff_add_eq', ← sqrt_inj (pow_two_nonneg _) (sub_nonneg.2 (sin_sq_le_one (arcsin x))),
pow_two, sqrt_mul_self (cos_arcsin_nonneg _)] at this,
rw [this, sin_arcsin hx₁ hx₂],
end
lemma sin_arccos {x : ℝ} (hx₁ : -1 ≤ x) (hx₂ : x ≤ 1) : sin (arccos x) = sqrt (1 - x ^ 2) :=
by rw [arccos_eq_pi_div_two_sub_arcsin, sin_pi_div_two_sub, cos_arcsin hx₁ hx₂]
lemma abs_div_sqrt_one_add_lt (x : ℝ) : abs (x / sqrt (1 + x ^ 2)) < 1 :=
have h₁ : 0 < 1 + x ^ 2, from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _),
have h₂ : 0 < sqrt (1 + x ^ 2), from sqrt_pos.2 h₁,
by rw [abs_div, div_lt_iff (abs_pos_of_pos h₂), one_mul,
mul_self_lt_mul_self_iff (abs_nonneg x) (abs_nonneg _),
← abs_mul, ← abs_mul, mul_self_sqrt (add_nonneg zero_le_one (pow_two_nonneg _)),
abs_of_nonneg (mul_self_nonneg x), abs_of_nonneg (le_of_lt h₁), pow_two, add_comm];
exact lt_add_one _
lemma div_sqrt_one_add_lt_one (x : ℝ) : x / sqrt (1 + x ^ 2) < 1 :=
(abs_lt.1 (abs_div_sqrt_one_add_lt _)).2
lemma neg_one_lt_div_sqrt_one_add (x : ℝ) : -1 < x / sqrt (1 + x ^ 2) :=
(abs_lt.1 (abs_div_sqrt_one_add_lt _)).1
lemma tan_pos_of_pos_of_lt_pi_div_two {x : ℝ} (h0x : 0 < x) (hxp : x < π / 2) : 0 < tan x :=
by rw tan_eq_sin_div_cos; exact div_pos (sin_pos_of_pos_of_lt_pi h0x (by linarith))
(cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hxp)
lemma tan_nonneg_of_nonneg_of_le_pi_div_two {x : ℝ} (h0x : 0 ≤ x) (hxp : x ≤ π / 2) : 0 ≤ tan x :=
match lt_or_eq_of_le h0x, lt_or_eq_of_le hxp with
| or.inl hx0, or.inl hxp := le_of_lt (tan_pos_of_pos_of_lt_pi_div_two hx0 hxp)
| or.inl hx0, or.inr hxp := by simp [hxp, tan_eq_sin_div_cos]
| or.inr hx0, _ := by simp [hx0.symm]
end
lemma tan_neg_of_neg_of_pi_div_two_lt {x : ℝ} (hx0 : x < 0) (hpx : -(π / 2) < x) : tan x < 0 :=
neg_pos.1 (tan_neg x ▸ tan_pos_of_pos_of_lt_pi_div_two (by linarith) (by linarith [pi_pos]))
lemma tan_nonpos_of_nonpos_of_neg_pi_div_two_le {x : ℝ} (hx0 : x ≤ 0) (hpx : -(π / 2) ≤ x) : tan x ≤ 0 :=
neg_nonneg.1 (tan_neg x ▸ tan_nonneg_of_nonneg_of_le_pi_div_two (by linarith) (by linarith [pi_pos]))
lemma tan_lt_tan_of_nonneg_of_lt_pi_div_two {x y : ℝ} (hx₁ : 0 ≤ x) (hx₂ : x < π / 2) (hy₁ : 0 ≤ y)
(hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y :=
begin
rw [tan_eq_sin_div_cos, tan_eq_sin_div_cos],
exact div_lt_div
(sin_lt_sin_of_le_of_le_pi_div_two (by linarith) (le_of_lt hx₂)
(by linarith) (le_of_lt hy₂) hxy)
(cos_le_cos_of_nonneg_of_le_pi hx₁ (by linarith) hy₁ (by linarith) (le_of_lt hxy))
(sin_nonneg_of_nonneg_of_le_pi hy₁ (by linarith))
(cos_pos_of_neg_pi_div_two_lt_of_lt_pi_div_two (by linarith) hy₂)
end
lemma tan_lt_tan_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2)
(hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : x < y) : tan x < tan y :=
match le_total x 0, le_total y 0 with
| or.inl hx0, or.inl hy0 := neg_lt_neg_iff.1 $ by rw [← tan_neg, ← tan_neg]; exact
tan_lt_tan_of_nonneg_of_lt_pi_div_two (neg_nonneg.2 hy0) (neg_lt.2 hy₁)
(neg_nonneg.2 hx0) (neg_lt.2 hx₁) (neg_lt_neg hxy)
| or.inl hx0, or.inr hy0 := (lt_or_eq_of_le hy0).elim
(λ hy0, calc tan x ≤ 0 : tan_nonpos_of_nonpos_of_neg_pi_div_two_le hx0 (le_of_lt hx₁)
... < tan y : tan_pos_of_pos_of_lt_pi_div_two hy0 hy₂)
(λ hy0, by rw [← hy0, tan_zero]; exact
tan_neg_of_neg_of_pi_div_two_lt (hy0.symm ▸ hxy) hx₁)
| or.inr hx0, or.inl hy0 := by linarith
| or.inr hx0, or.inr hy0 := tan_lt_tan_of_nonneg_of_lt_pi_div_two hx0 hx₂ hy0 hy₂ hxy
end
lemma tan_inj_of_lt_of_lt_pi_div_two {x y : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2)
(hy₁ : -(π / 2) < y) (hy₂ : y < π / 2) (hxy : tan x = tan y) : x = y :=
match lt_trichotomy x y with
| or.inl h := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hx₁ hx₂ hy₁ hy₂ h) (by rw hxy; exact lt_irrefl _)
| or.inr (or.inl h) := h
| or.inr (or.inr h) := absurd (tan_lt_tan_of_lt_of_lt_pi_div_two hy₁ hy₂ hx₁ hx₂ h) (by rw hxy; exact lt_irrefl _)
end
/-- Inverse of the `tan` function, returns values in the range `-π / 2 < arctan x` and `arctan x < π / 2` -/
noncomputable def arctan (x : ℝ) : ℝ :=
arcsin (x / sqrt (1 + x ^ 2))
lemma sin_arctan (x : ℝ) : sin (arctan x) = x / sqrt (1 + x ^ 2) :=
sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _))
lemma cos_arctan (x : ℝ) : cos (arctan x) = 1 / sqrt (1 + x ^ 2) :=
have h₁ : (0 : ℝ) < 1 + x ^ 2,
from add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg _),
have h₂ : (x / sqrt (1 + x ^ 2)) ^ 2 < 1,
by rw [pow_two, ← abs_mul_self, _root_.abs_mul];
exact mul_lt_one_of_nonneg_of_lt_one_left (abs_nonneg _)
(abs_div_sqrt_one_add_lt _) (le_of_lt (abs_div_sqrt_one_add_lt _)),
by rw [arctan, cos_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _)) (le_of_lt (div_sqrt_one_add_lt_one _)),
one_div_eq_inv, ← sqrt_inv, sqrt_inj (sub_nonneg.2 (le_of_lt h₂)) (inv_nonneg.2 (le_of_lt h₁)),
div_pow _ (mt sqrt_eq_zero'.1 (not_le.2 h₁)), pow_two (sqrt _), mul_self_sqrt (le_of_lt h₁),
← domain.mul_left_inj (ne.symm (ne_of_lt h₁)), mul_sub,
mul_div_cancel' _ (ne.symm (ne_of_lt h₁)), mul_inv_cancel (ne.symm (ne_of_lt h₁))];
simp
lemma tan_arctan (x : ℝ) : tan (arctan x) = x :=
by rw [tan_eq_sin_div_cos, sin_arctan, cos_arctan, div_div_div_div_eq, mul_one,
mul_div_assoc,
div_self (mt sqrt_eq_zero'.1 (not_le_of_gt (add_pos_of_pos_of_nonneg zero_lt_one (pow_two_nonneg x)))),
mul_one]
lemma arctan_lt_pi_div_two (x : ℝ) : arctan x < π / 2 :=
lt_of_le_of_ne (arcsin_le_pi_div_two _)
(λ h, ne_of_lt (div_sqrt_one_add_lt_one x) $
by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _))
(le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, h, sin_pi_div_two])
lemma neg_pi_div_two_lt_arctan (x : ℝ) : -(π / 2) < arctan x :=
lt_of_le_of_ne (neg_pi_div_two_le_arcsin _)
(λ h, ne_of_lt (neg_one_lt_div_sqrt_one_add x) $
by rw [← sin_arcsin (le_of_lt (neg_one_lt_div_sqrt_one_add _))
(le_of_lt (div_sqrt_one_add_lt_one _)), ← arctan, ← h, sin_neg, sin_pi_div_two])
lemma tan_surjective : function.surjective tan :=
function.surjective_of_has_right_inverse ⟨_, tan_arctan⟩
lemma arctan_tan {x : ℝ} (hx₁ : -(π / 2) < x) (hx₂ : x < π / 2) : arctan (tan x) = x :=
tan_inj_of_lt_of_lt_pi_div_two (neg_pi_div_two_lt_arctan _)
(arctan_lt_pi_div_two _) hx₁ hx₂ (by rw tan_arctan)
@[simp] lemma arctan_zero : arctan 0 = 0 :=
by simp [arctan]
@[simp] lemma arctan_neg (x : ℝ) : arctan (-x) = - arctan x :=
by simp [arctan, neg_div]
end real
namespace complex
open_locale real
/-- `arg` returns values in the range (-π, π], such that for `x ≠ 0`,
`sin (arg x) = x.im / x.abs` and `cos (arg x) = x.re / x.abs`,
`arg 0` defaults to `0` -/
noncomputable def arg (x : ℂ) : ℝ :=
if 0 ≤ x.re
then real.arcsin (x.im / x.abs)
else if 0 ≤ x.im
then real.arcsin ((-x).im / x.abs) + π
else real.arcsin ((-x).im / x.abs) - π
lemma arg_le_pi (x : ℂ) : arg x ≤ π :=
if hx₁ : 0 ≤ x.re
then by rw [arg, if_pos hx₁];
exact le_trans (real.arcsin_le_pi_div_two _) (le_of_lt (half_lt_self real.pi_pos))
else
have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁,
if hx₂ : 0 ≤ x.im
then by rw [arg, if_neg hx₁, if_pos hx₂];
exact le_sub_iff_add_le.1 (by rw sub_self;
exact real.arcsin_nonpos (by rw [neg_im, neg_div, neg_nonpos]; exact div_nonneg hx₂ (abs_pos.2 hx)))
else by rw [arg, if_neg hx₁, if_neg hx₂];
exact sub_le_iff_le_add.2 (le_trans (real.arcsin_le_pi_div_two _)
(by linarith [real.pi_pos]))
lemma neg_pi_lt_arg (x : ℂ) : -π < arg x :=
if hx₁ : 0 ≤ x.re
then by rw [arg, if_pos hx₁];
exact lt_of_lt_of_le (neg_lt_neg (half_lt_self real.pi_pos)) (real.neg_pi_div_two_le_arcsin _)
else
have hx : x ≠ 0, from λ h, by simpa [h, lt_irrefl] using hx₁,
if hx₂ : 0 ≤ x.im
then by rw [arg, if_neg hx₁, if_pos hx₂];
exact sub_lt_iff_lt_add.1
(lt_of_lt_of_le (by linarith [real.pi_pos]) (real.neg_pi_div_two_le_arcsin _))
else by rw [arg, if_neg hx₁, if_neg hx₂];
exact lt_sub_iff_add_lt.2 (by rw neg_add_self;
exact real.arcsin_pos (by rw [neg_im]; exact div_pos (neg_pos.2 (lt_of_not_ge hx₂))
(abs_pos.2 hx)) (by rw [← abs_neg x]; exact (abs_le.1 (abs_im_div_abs_le_one _)).2))
lemma arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : 0 ≤ x.im) :
arg x = arg (-x) + π :=
have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos],
by rw [arg, arg, if_neg (not_le.2 hxr), if_pos this, if_pos hxi, abs_neg]
lemma arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg {x : ℂ} (hxr : x.re < 0) (hxi : x.im < 0) :
arg x = arg (-x) - π :=
have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos],
by rw [arg, arg, if_neg (not_le.2 hxr), if_neg (not_le.2 hxi), if_pos this, abs_neg]
@[simp] lemma arg_zero : arg 0 = 0 :=
by simp [arg, le_refl]
@[simp] lemma arg_one : arg 1 = 0 :=
by simp [arg, zero_le_one]
@[simp] lemma arg_neg_one : arg (-1) = π :=
by simp [arg, le_refl, not_le.2 (@zero_lt_one ℝ _)]
@[simp] lemma arg_I : arg I = π / 2 :=
by simp [arg, le_refl]
@[simp] lemma arg_neg_I : arg (-I) = -(π / 2) :=
by simp [arg, le_refl]
lemma sin_arg (x : ℂ) : real.sin (arg x) = x.im / x.abs :=
by unfold arg; split_ifs;
simp [arg, real.sin_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1
(abs_le.1 (abs_im_div_abs_le_one x)).2, real.sin_add, neg_div, real.arcsin_neg,
real.sin_neg]
private lemma cos_arg_of_re_nonneg {x : ℂ} (hx : x ≠ 0) (hxr : 0 ≤ x.re) : real.cos (arg x) = x.re / x.abs :=
have 0 ≤ 1 - (x.im / abs x) ^ 2,
from sub_nonneg.2 $ by rw [pow_two, ← _root_.abs_mul_self, _root_.abs_mul, ← pow_two];
exact pow_le_one _ (_root_.abs_nonneg _) (abs_im_div_abs_le_one _),
by rw [eq_div_iff_mul_eq _ _ (mt abs_eq_zero.1 hx), ← real.mul_self_sqrt (abs_nonneg x),
arg, if_pos hxr, real.cos_arcsin (abs_le.1 (abs_im_div_abs_le_one x)).1
(abs_le.1 (abs_im_div_abs_le_one x)).2, ← real.sqrt_mul (abs_nonneg _), ← real.sqrt_mul this,
sub_mul, div_pow _ (mt abs_eq_zero.1 hx), ← pow_two, div_mul_cancel _ (pow_ne_zero 2 (mt abs_eq_zero.1 hx)),
one_mul, pow_two, mul_self_abs, norm_sq, pow_two, add_sub_cancel, real.sqrt_mul_self hxr]
lemma cos_arg {x : ℂ} (hx : x ≠ 0) : real.cos (arg x) = x.re / x.abs :=
if hxr : 0 ≤ x.re then cos_arg_of_re_nonneg hx hxr
else
have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr,
if hxi : 0 ≤ x.im
then have 0 ≤ (-x).re, from le_of_lt $ by simpa [neg_pos] using hxr,
by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg (not_le.1 hxr) hxi, real.cos_add_pi,
cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this];
simp [neg_div]
else by rw [arg_eq_arg_neg_sub_pi_of_im_neg_of_re_neg (not_le.1 hxr) (not_le.1 hxi)];
simp [real.cos_add, neg_div, cos_arg_of_re_nonneg (neg_ne_zero.2 hx) this]
lemma tan_arg {x : ℂ} : real.tan (arg x) = x.im / x.re :=
if hx : x = 0 then by simp [hx]
else by rw [real.tan_eq_sin_div_cos, sin_arg, cos_arg hx,
div_div_div_cancel_right _ _ (mt abs_eq_zero.1 hx)]
lemma arg_cos_add_sin_mul_I {x : ℝ} (hx₁ : -π < x) (hx₂ : x ≤ π) :
arg (cos x + sin x * I) = x :=
if hx₃ : -(π / 2) ≤ x ∧ x ≤ π / 2
then
have hx₄ : 0 ≤ (cos x + sin x * I).re,
by simp; exact real.cos_nonneg_of_neg_pi_div_two_le_of_le_pi_div_two hx₃.1 hx₃.2,
by rw [arg, if_pos hx₄];
simp [abs_cos_add_sin_mul_I, sin_of_real_re, real.arcsin_sin hx₃.1 hx₃.2]
else if hx₄ : x < -(π / 2)
then
have hx₅ : ¬0 ≤ (cos x + sin x * I).re :=
suffices ¬ 0 ≤ real.cos x, by simpa,
not_le.2 $ by rw ← real.cos_neg;
apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith,
have hx₆ : ¬0 ≤ (cos ↑x + sin ↑x * I).im :=
suffices real.sin x < 0, by simpa,
by apply real.sin_neg_of_neg_of_neg_pi_lt; linarith,
suffices -π + -real.arcsin (real.sin x) = x,
by rw [arg, if_neg hx₅, if_neg hx₆];
simpa [abs_cos_add_sin_mul_I, sin_of_real_re],
by rw [← real.arcsin_neg, ← real.sin_add_pi, real.arcsin_sin]; simp; linarith
else
have hx₅ : π / 2 < x, by cases not_and_distrib.1 hx₃; linarith,
have hx₆ : ¬0 ≤ (cos x + sin x * I).re :=
suffices ¬0 ≤ real.cos x, by simpa,
not_le.2 $ by apply real.cos_neg_of_pi_div_two_lt_of_lt; linarith,
have hx₇ : 0 ≤ (cos x + sin x * I).im :=
suffices 0 ≤ real.sin x, by simpa,
by apply real.sin_nonneg_of_nonneg_of_le_pi; linarith,
suffices π - real.arcsin (real.sin x) = x,
by rw [arg, if_neg hx₆, if_pos hx₇];
simpa [abs_cos_add_sin_mul_I, sin_of_real_re],
by rw [← real.sin_pi_sub, real.arcsin_sin]; simp; linarith
lemma arg_eq_arg_iff {x y : ℂ} (hx : x ≠ 0) (hy : y ≠ 0) :
arg x = arg y ↔ (abs y / abs x : ℂ) * x = y :=
have hax : abs x ≠ 0, from (mt abs_eq_zero.1 hx),
have hay : abs y ≠ 0, from (mt abs_eq_zero.1 hy),
⟨λ h,
begin
have hcos := congr_arg real.cos h,
rw [cos_arg hx, cos_arg hy, div_eq_div_iff hax hay] at hcos,
have hsin := congr_arg real.sin h,
rw [sin_arg, sin_arg, div_eq_div_iff hax hay] at hsin,
apply complex.ext,
{ rw [mul_re, ← of_real_div, of_real_re, of_real_im, zero_mul, sub_zero, mul_comm,
← mul_div_assoc, hcos, mul_div_cancel _ hax] },
{ rw [mul_im, ← of_real_div, of_real_re, of_real_im, zero_mul, add_zero,
mul_comm, ← mul_div_assoc, hsin, mul_div_cancel _ hax] }
end,
λ h,
have hre : abs (y / x) * x.re = y.re,
by rw ← of_real_div at h;
simpa [-of_real_div] using congr_arg re h,
have hre' : abs (x / y) * y.re = x.re,
by rw [← hre, abs_div, abs_div, ← mul_assoc, div_mul_div,
mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul],
have him : abs (y / x) * x.im = y.im,
by rw ← of_real_div at h;
simpa [-of_real_div] using congr_arg im h,
have him' : abs (x / y) * y.im = x.im,
by rw [← him, abs_div, abs_div, ← mul_assoc, div_mul_div,
mul_comm (abs _), div_self (mul_ne_zero hay hax), one_mul],
have hxya : x.im / abs x = y.im / abs y,
by rw [← him, abs_div, mul_comm, ← mul_div_comm, mul_div_cancel_left _ hay],
have hnxya : (-x).im / abs x = (-y).im / abs y,
by rw [neg_im, neg_im, neg_div, neg_div, hxya],
if hxr : 0 ≤ x.re
then
have hyr : 0 ≤ y.re, from hre ▸ mul_nonneg (abs_nonneg _) hxr,
by simp [arg, *] at *
else
have hyr : ¬ 0 ≤ y.re, from λ hyr, hxr $ hre' ▸ mul_nonneg (abs_nonneg _) hyr,
if hxi : 0 ≤ x.im
then
have hyi : 0 ≤ y.im, from him ▸ mul_nonneg (abs_nonneg _) hxi,
by simp [arg, *] at *
else
have hyi : ¬ 0 ≤ y.im, from λ hyi, hxi $ him' ▸ mul_nonneg (abs_nonneg _) hyi,
by simp [arg, *] at *⟩
lemma arg_real_mul (x : ℂ) {r : ℝ} (hr : 0 < r) : arg (r * x) = arg x :=
if hx : x = 0 then by simp [hx]
else (arg_eq_arg_iff (mul_ne_zero (of_real_ne_zero.2 (ne_of_lt hr).symm) hx) hx).2 $
by rw [abs_mul, abs_of_nonneg (le_of_lt hr), ← mul_assoc,
of_real_mul, mul_comm (r : ℂ), ← div_div_eq_div_mul,
div_mul_cancel _ (of_real_ne_zero.2 (ne_of_lt hr).symm),
div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), one_mul]
lemma ext_abs_arg {x y : ℂ} (h₁ : x.abs = y.abs) (h₂ : x.arg = y.arg) : x = y :=
if hy : y = 0 then by simp * at *
else have hx : x ≠ 0, from λ hx, by simp [*, eq_comm] at *,
by rwa [arg_eq_arg_iff hx hy, h₁, div_self (of_real_ne_zero.2 (mt abs_eq_zero.1 hy)), one_mul] at h₂
lemma arg_of_real_of_nonneg {x : ℝ} (hx : 0 ≤ x) : arg x = 0 :=
by simp [arg, hx]
lemma arg_of_real_of_neg {x : ℝ} (hx : x < 0) : arg x = π :=
by rw [arg_eq_arg_neg_add_pi_of_im_nonneg_of_re_neg, ← of_real_neg, arg_of_real_of_nonneg];
simp [*, le_iff_eq_or_lt, lt_neg]
/-- Inverse of the `exp` function. Returns values such that `(log x).im > - π` and `(log x).im ≤ π`.
`log 0 = 0`-/
noncomputable def log (x : ℂ) : ℂ := x.abs.log + arg x * I
lemma log_re (x : ℂ) : x.log.re = x.abs.log := by simp [log]
lemma log_im (x : ℂ) : x.log.im = x.arg := by simp [log]
lemma exp_log {x : ℂ} (hx : x ≠ 0) : exp (log x) = x :=
by rw [log, exp_add_mul_I, ← of_real_sin, sin_arg, ← of_real_cos, cos_arg hx,
← of_real_exp, real.exp_log (abs_pos.2 hx), mul_add, of_real_div, of_real_div,
mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), ← mul_assoc,
mul_div_cancel' _ (of_real_ne_zero.2 (mt abs_eq_zero.1 hx)), re_add_im]
lemma exp_inj_of_neg_pi_lt_of_le_pi {x y : ℂ} (hx₁ : -π < x.im) (hx₂ : x.im ≤ π)
(hy₁ : - π < y.im) (hy₂ : y.im ≤ π) (hxy : exp x = exp y) : x = y :=
by rw [exp_eq_exp_re_mul_sin_add_cos, exp_eq_exp_re_mul_sin_add_cos y] at hxy;
exact complex.ext
(real.exp_injective $
by simpa [abs_mul, abs_cos_add_sin_mul_I] using congr_arg complex.abs hxy)
(by simpa [(of_real_exp _).symm, - of_real_exp, arg_real_mul _ (real.exp_pos _),
arg_cos_add_sin_mul_I hx₁ hx₂, arg_cos_add_sin_mul_I hy₁ hy₂] using congr_arg arg hxy)
lemma log_exp {x : ℂ} (hx₁ : -π < x.im) (hx₂: x.im ≤ π) : log (exp x) = x :=
exp_inj_of_neg_pi_lt_of_le_pi
(by rw log_im; exact neg_pi_lt_arg _)
(by rw log_im; exact arg_le_pi _)
hx₁ hx₂ (by rw [exp_log (exp_ne_zero _)])
lemma of_real_log {x : ℝ} (hx : 0 ≤ x) : (x.log : ℂ) = log x :=
complex.ext
(by rw [log_re, of_real_re, abs_of_nonneg hx])
(by rw [of_real_im, log_im, arg_of_real_of_nonneg hx])
@[simp] lemma log_zero : log 0 = 0 := by simp [log]
@[simp] lemma log_one : log 1 = 0 := by simp [log]
lemma log_neg_one : log (-1) = π * I := by simp [log]
lemma log_I : log I = π / 2 * I := by simp [log]
lemma log_neg_I : log (-I) = -(π / 2) * I := by simp [log]
lemma exp_eq_one_iff {x : ℂ} : exp x = 1 ↔ ∃ n : ℤ, x = n * ((2 * π) * I) :=
have real.exp (x.re) * real.cos (x.im) = 1 → real.cos x.im ≠ -1,
from λ h₁ h₂, begin
rw [h₂, mul_neg_eq_neg_mul_symm, mul_one, neg_eq_iff_neg_eq] at h₁,
have := real.exp_pos x.re,
rw ← h₁ at this,
exact absurd this (by norm_num)
end,
calc exp x = 1 ↔ (exp x).re = 1 ∧ (exp x).im = 0 : by simp [complex.ext_iff]
... ↔ real.cos x.im = 1 ∧ real.sin x.im = 0 ∧ x.re = 0 :
begin
rw exp_eq_exp_re_mul_sin_add_cos,
simp [complex.ext_iff, cos_of_real_re, sin_of_real_re, exp_of_real_re,
real.exp_ne_zero],
split; finish [real.sin_eq_zero_iff_cos_eq]
end
... ↔ (∃ n : ℤ, ↑n * (2 * π) = x.im) ∧ (∃ n : ℤ, ↑n * π = x.im) ∧ x.re = 0 :
by rw [real.sin_eq_zero_iff, real.cos_eq_one_iff]
... ↔ ∃ n : ℤ, x = n * ((2 * π) * I) :
⟨λ ⟨⟨n, hn⟩, ⟨m, hm⟩, h⟩, ⟨n, by simp [complex.ext_iff, hn.symm, h]⟩,
λ ⟨n, hn⟩, ⟨⟨n, by simp [hn]⟩, ⟨2 * n, by simp [hn, mul_comm, mul_assoc, mul_left_comm]⟩,
by simp [hn]⟩⟩
lemma exp_eq_exp_iff_exp_sub_eq_one {x y : ℂ} : exp x = exp y ↔ exp (x - y) = 1 :=
by rw [exp_sub, div_eq_one_iff_eq _ (exp_ne_zero _)]
lemma exp_eq_exp_iff_exists_int {x y : ℂ} : exp x = exp y ↔ ∃ n : ℤ, x = y + n * ((2 * π) * I) :=
by simp only [exp_eq_exp_iff_exp_sub_eq_one, exp_eq_one_iff, sub_eq_iff_eq_add']
@[simp] lemma cos_pi_div_two : cos (π / 2) = 0 :=
calc cos (π / 2) = real.cos (π / 2) : by rw [of_real_cos]; simp
... = 0 : by simp
@[simp] lemma sin_pi_div_two : sin (π / 2) = 1 :=
calc sin (π / 2) = real.sin (π / 2) : by rw [of_real_sin]; simp
... = 1 : by simp
@[simp] lemma sin_pi : sin π = 0 :=
by rw [← of_real_sin, real.sin_pi]; simp
@[simp] lemma cos_pi : cos π = -1 :=
by rw [← of_real_cos, real.cos_pi]; simp
@[simp] lemma sin_two_pi : sin (2 * π) = 0 :=
by simp [two_mul, sin_add]
@[simp] lemma cos_two_pi : cos (2 * π) = 1 :=
by simp [two_mul, cos_add]
lemma sin_add_pi (x : ℝ) : sin (x + π) = -sin x :=
by simp [sin_add]
lemma sin_add_two_pi (x : ℝ) : sin (x + 2 * π) = sin x :=
by simp [sin_add_pi, sin_add, sin_two_pi, cos_two_pi]
lemma cos_add_two_pi (x : ℝ) : cos (x + 2 * π) = cos x :=
by simp [cos_add, cos_two_pi, sin_two_pi]
lemma sin_pi_sub (x : ℝ) : sin (π - x) = sin x :=
by simp [sin_add]
lemma cos_add_pi (x : ℝ) : cos (x + π) = -cos x :=
by simp [cos_add]
lemma cos_pi_sub (x : ℝ) : cos (π - x) = -cos x :=
by simp [cos_add]
lemma sin_add_pi_div_two (x : ℝ) : sin (x + π / 2) = cos x :=
by simp [sin_add]
lemma sin_sub_pi_div_two (x : ℝ) : sin (x - π / 2) = -cos x :=
by simp [sin_add]
lemma sin_pi_div_two_sub (x : ℝ) : sin (π / 2 - x) = cos x :=
by simp [sin_add]
lemma cos_add_pi_div_two (x : ℝ) : cos (x + π / 2) = -sin x :=
by simp [cos_add]
lemma cos_sub_pi_div_two (x : ℝ) : cos (x - π / 2) = sin x :=
by simp [cos_add]
lemma cos_pi_div_two_sub (x : ℝ) : cos (π / 2 - x) = sin x :=
by rw [← cos_neg, neg_sub, cos_sub_pi_div_two]
lemma sin_nat_mul_pi (n : ℕ) : sin (n * π) = 0 :=
by induction n; simp [add_mul, sin_add, *]
lemma sin_int_mul_pi (n : ℤ) : sin (n * π) = 0 :=
by cases n; simp [add_mul, sin_add, *, sin_nat_mul_pi]
lemma cos_nat_mul_two_pi (n : ℕ) : cos (n * (2 * π)) = 1 :=
by induction n; simp [*, mul_add, cos_add, add_mul, cos_two_pi, sin_two_pi]
lemma cos_int_mul_two_pi (n : ℤ) : cos (n * (2 * π)) = 1 :=
by cases n; simp only [cos_nat_mul_two_pi, int.of_nat_eq_coe,
int.neg_succ_of_nat_coe, int.cast_coe_nat, int.cast_neg,
(neg_mul_eq_neg_mul _ _).symm, cos_neg]
lemma cos_int_mul_two_pi_add_pi (n : ℤ) : cos (n * (2 * π) + π) = -1 :=
by simp [cos_add, sin_add, cos_int_mul_two_pi]
section pow
/-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal
determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for
`y ≠ 0`. -/
noncomputable def cpow (x y : ℂ) : ℂ :=
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y)
noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩
lemma cpow_def (x y : ℂ) : x ^ y =
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y) := rfl
@[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def]
@[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 :=
by simp [cpow_def, *]
@[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x :=
if hx : x = 0 then by simp [hx, cpow_def]
else by rw [cpow_def, if_neg (@one_ne_zero ℂ _), if_neg hx, mul_one, exp_log hx]
@[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 :=
by rw cpow_def; split_ifs; simp [one_ne_zero, *] at *
lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z :=
by simp [cpow_def]; split_ifs; simp [*, exp_add, mul_add] at *
lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) :
x ^ (y * z) = (x ^ y) ^ z :=
begin
simp [cpow_def],
split_ifs;
simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at *
end
lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ :=
by simp [cpow_def]; split_ifs; simp [exp_neg]
@[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n
| 0 := by simp
| (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ,
complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul]
else by simp [cpow_def, hx, mul_add, exp_add, pow_succ, (cpow_nat_cast n).symm, exp_log hx]
@[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n
| (n : ℕ) := by simp; refl
| -[1+ n] := by rw fpow_neg_succ_of_nat;
simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div,
int.cast_coe_nat, cpow_nat_cast]
lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x :=
have (log x * (↑n)⁻¹).im = (log x).im / n,
by rw [div_eq_mul_inv, ← of_real_nat_cast, ← of_real_inv, mul_im,
of_real_re, of_real_im]; simp,
have h : -π < (log x * (↑n)⁻¹).im ∧ (log x * (↑n)⁻¹).im ≤ π,
from (le_total (log x).im 0).elim
(λ h, ⟨calc -π < (log x).im : by simp [log, neg_pi_lt_arg]
... ≤ ((log x).im * 1) / n : le_div_of_mul_le (nat.cast_pos.2 hn)
(mul_le_mul_of_nonpos_left (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h)
... = (log x * (↑n)⁻¹).im : by simp [this],
this.symm ▸ le_trans (div_nonpos_of_nonpos_of_pos h (nat.cast_pos.2 hn))
(le_of_lt real.pi_pos)⟩)
(λ h, ⟨this.symm ▸ lt_of_lt_of_le (neg_neg_of_pos real.pi_pos)
(div_nonneg h (nat.cast_pos.2 hn)),
calc (log x * (↑n)⁻¹).im = (1 * (log x).im) / n : by simp [this]
... ≤ (log x).im : (div_le_of_le_mul (nat.cast_pos.2 hn)
(mul_le_mul_of_nonneg_right (by rw ← nat.cast_one; exact nat.cast_le.2 hn) h))
... ≤ _ : by simp [log, arg_le_pi]⟩),
by rw [← cpow_nat_cast, ← cpow_mul _ h.1 h.2,
inv_mul_cancel (show (n : ℂ) ≠ 0, from nat.cast_ne_zero.2 (nat.pos_iff_ne_zero.1 hn)),
cpow_one]
end pow
end complex
namespace real
/-- The real power function `x^y`, defined as the real part of the complex power function.
For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`.
For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex
determination of the logarithm. With our conventions, it is equal to `exp (y log (-x)) cos (πy)`. -/
noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re
noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩
lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl
lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y =
if x = 0
then if y = 0
then 1
else 0
else exp (log x * y) :=
by simp only [rpow_def, complex.cpow_def];
split_ifs;
simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul,
(complex.of_real_mul _ _).symm, complex.exp_of_real_re] at *
lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) :=
by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)]
open_locale real
lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log (-x) * y) * cos (y * π) :=
begin
rw [rpow_def, complex.cpow_def, if_neg],
have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I,
simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx,
complex.abs_of_real, complex.of_real_mul], ring,
{ rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos,
← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul,
complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im], ring },
{ rw complex.of_real_eq_zero, exact ne_of_lt hx }
end
lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y =
if x = 0
then if y = 0
then 1
else 0
else exp (log (-x) * y) * cos (y * π) :=
by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _
lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y :=
by rw rpow_def_of_pos hx; apply exp_pos
lemma abs_rpow_le_abs_rpow (x y : ℝ) : abs (x ^ y) ≤ abs (x) ^ y :=
abs_le_of_le_of_neg_le
begin
cases lt_trichotomy 0 x, { rw abs_of_pos h },
cases h, { simp [h.symm] },
rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h],
calc exp (log (-x) * y) * cos (y * π) ≤ exp (log (-x) * y) * 1 :
mul_le_mul_of_nonneg_left (cos_le_one _) (le_of_lt $ exp_pos _)
... = _ : mul_one _
end
begin
cases lt_trichotomy 0 x, { rw abs_of_pos h, have : 0 < x^y := rpow_pos_of_pos h _, linarith },
cases h, { simp only [h.symm, abs_zero, rpow_def_of_nonneg], split_ifs, repeat {norm_num}},
rw [rpow_def_of_neg h, rpow_def_of_pos (abs_pos_of_neg h), abs_of_neg h],
calc -(exp (log (-x) * y) * cos (y * π)) = exp (log (-x) * y) * (-cos (y * π)) : by ring
... ≤ exp (log (-x) * y) * 1 :
mul_le_mul_of_nonneg_left (neg_le.2 $ neg_one_le_cos _) (le_of_lt $ exp_pos _)
... = exp (log (-x) * y) : mul_one _
end
end real
namespace complex
lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) :=
by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx]
@[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y :=
begin
rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def],
split_ifs;
simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add,
add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I,
(complex.of_real_mul _ _).symm, -complex.of_real_mul] at *
end
@[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) :=
by rw ← abs_cpow_real; simp [-abs_cpow_real]
end complex
namespace real
open_locale real
variables {x y z : ℝ}
@[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def]
@[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 :=
by simp [rpow_def, *]
@[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def]
@[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def]
lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y :=
by rw [rpow_def_of_nonneg hx];
split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)]
lemma rpow_add {x : ℝ} (y z : ℝ) (hx : 0 < x) : x ^ (y + z) = x ^ y * x ^ z :=
by simp only [rpow_def_of_pos hx, mul_add, exp_add]
lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z :=
by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _),
complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx];
simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm,
complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos]
lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ :=
by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at *
@[simp] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n :=
by simp only [rpow_def, (complex.of_real_pow _ _).symm, complex.cpow_nat_cast,
complex.of_real_nat_cast, complex.of_real_re]
@[simp] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n :=
by simp only [rpow_def, (complex.of_real_fpow _ _).symm, complex.cpow_int_cast,
complex.of_real_int_cast, complex.of_real_re]
lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z :=
begin
iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *,
{ have hx : 0 < x, cases lt_or_eq_of_le h with h₂ h₂, exact h₂, exfalso, apply h_2, exact eq.symm h₂,
have hy : 0 < y, cases lt_or_eq_of_le h₁ with h₂ h₂, exact h₂, exfalso, apply h_3, exact eq.symm h₂,
rw [log_mul hx hy, add_mul, exp_add]},
{ exact h₁},
{ exact h},
{ exact mul_nonneg h h₁},
end
lemma one_le_rpow {x z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z :=
begin
rw real.rpow_def_of_nonneg, split_ifs with h₂ h₃,
{ refl},
{ simp [*, not_le_of_gt zero_lt_one] at *},
{ have hx : 0 < x, exact lt_of_lt_of_le zero_lt_one h,
rw [←log_le_log zero_lt_one hx, log_one] at h,
have pos : 0 ≤ log x * z, exact mul_nonneg h h₁,
rwa [←exp_le_exp, exp_zero] at pos},
{ exact le_trans zero_le_one h},
end
lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z :=
begin
rw le_iff_eq_or_lt at h h₂, cases h₂,
{ rw [←h₂, rpow_zero, rpow_zero]},
{ cases h,
{ rw [←h, zero_rpow], rw real.rpow_def_of_nonneg, split_ifs,
{ exact zero_le_one},
{ refl},
{ exact le_of_lt (exp_pos (log y * z))},
{ rwa ←h at h₁},
{ exact ne.symm (ne_of_lt h₂)}},
{ have one_le : 1 ≤ y / x, rw one_le_div_iff_le h, exact h₁,
have one_le_pow : 1 ≤ (y / x)^z, exact one_le_rpow one_le (le_of_lt h₂),
rw [←mul_div_cancel y (ne.symm (ne_of_lt h)), mul_comm, mul_div_assoc],
rw [mul_rpow (le_of_lt h) (le_trans zero_le_one one_le), mul_comm],
exact (le_mul_of_ge_one_left (rpow_nonneg_of_nonneg (le_of_lt h) z) one_le_pow) } }
end
lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z :=
begin
rw le_iff_eq_or_lt at hx, cases hx,
{ rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ },
rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp],
exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz
end
lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z :=
begin
repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]},
rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx),
end
lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z :=
begin
repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]},
rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx),
end
lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) :
x^y < x^z :=
begin
repeat {rw [rpow_def_of_pos hx0]},
rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1),
end
lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) :
x^y ≤ x^z :=
begin
repeat {rw [rpow_def_of_pos hx0]},
rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos hx1),
end
lemma rpow_le_one {x e : ℝ} (he : 0 ≤ e) (hx : 0 ≤ x) (hx2 : x ≤ 1) : x^e ≤ 1 :=
by rw ←one_rpow e; apply rpow_le_rpow; assumption
lemma one_lt_rpow (hx : 1 < x) (hz : 0 < z) : 1 < x^z :=
by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz }
lemma rpow_lt_one (hx : 0 < x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 :=
by { rw ← one_rpow z, exact rpow_lt_rpow (le_of_lt hx) hx1 hz }
lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) :
(x ^ n) ^ (n⁻¹ : ℝ) = x :=
have hn0 : (n : ℝ) ≠ 0, by simpa [nat.pos_iff_ne_zero] using hn,
by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one]
section prove_rpow_is_continuous
lemma continuous_rpow_aux1 : continuous (λp : {p:ℝ×ℝ // 0 < p.1}, p.val.1 ^ p.val.2) :=
suffices h : continuous (λ p : {p:ℝ×ℝ // 0 < p.1 }, exp (log p.val.1 * p.val.2)),
by { convert h, ext p, rw rpow_def_of_pos p.2 },
continuous_exp.comp $
(show continuous ((λp:{p:ℝ//0 < p}, log (p.val)) ∘ (λp:{p:ℝ×ℝ//0<p.fst}, ⟨p.val.1, p.2⟩)), from
continuous_log'.comp $ continuous_subtype_mk _ $ continuous_fst.comp continuous_subtype_val).mul
(continuous_snd.comp $ continuous_subtype_val.comp continuous_id)
lemma continuous_rpow_aux2 : continuous (λ p : {p:ℝ×ℝ // p.1 < 0}, p.val.1 ^ p.val.2) :=
suffices h : continuous (λp:{p:ℝ×ℝ // p.1 < 0}, exp (log (-p.val.1) * p.val.2) * cos (p.val.2 * π)),
by { convert h, ext p, rw [rpow_def_of_neg p.2] },
(continuous_exp.comp $
(show continuous $ (λp:{p:ℝ//0<p},
log (p.val))∘(λp:{p:ℝ×ℝ//p.1<0}, ⟨-p.val.1, neg_pos_of_neg p.2⟩),
from continuous_log'.comp $ continuous_subtype_mk _ $ continuous_neg.comp $
continuous_fst.comp continuous_subtype_val).mul
(continuous_snd.comp $ continuous_subtype_val.comp continuous_id)).mul
(continuous_cos.comp $
(continuous_snd.comp $ continuous_subtype_val.comp continuous_id).mul continuous_const)
lemma continuous_at_rpow_of_ne_zero (hx : x ≠ 0) (y : ℝ) :
continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) :=
begin
cases lt_trichotomy 0 x,
exact continuous_within_at.continuous_at
(continuous_on_iff_continuous_restrict.2 continuous_rpow_aux1 _ h)
(mem_nhds_sets (by { convert is_open_prod (is_open_lt' (0:ℝ)) is_open_univ, ext, finish }) h),
cases h,
{ exact absurd h.symm hx },
exact continuous_within_at.continuous_at
(continuous_on_iff_continuous_restrict.2 continuous_rpow_aux2 _ h)
(mem_nhds_sets (by { convert is_open_prod (is_open_gt' (0:ℝ)) is_open_univ, ext, finish }) h)
end
lemma continuous_rpow_aux3 : continuous (λ p : {p:ℝ×ℝ // 0 < p.2}, p.val.1 ^ p.val.2) :=
continuous_iff_continuous_at.2 $ λ ⟨(x₀, y₀), hy₀⟩,
begin
by_cases hx₀ : x₀ = 0,
{ simp only [continuous_at, hx₀, zero_rpow (ne_of_gt hy₀), tendsto_nhds_nhds], assume ε ε0,
rcases exists_pos_rat_lt (half_pos hy₀) with ⟨q, q_pos, q_lt⟩,
let q := (q:ℝ), replace q_pos : 0 < q := rat.cast_pos.2 q_pos,
let δ := min (min q (ε ^ (1 / q))) (1/2),
have δ0 : 0 < δ := lt_min (lt_min q_pos (rpow_pos_of_pos ε0 _)) (by norm_num),
have : δ ≤ q := le_trans (min_le_left _ _) (min_le_left _ _),
have : δ ≤ ε ^ (1 / q) := le_trans (min_le_left _ _) (min_le_right _ _),
have : δ < 1 := lt_of_le_of_lt (min_le_right _ _) (by norm_num),
use δ, use δ0, rintros ⟨⟨x, y⟩, hy⟩,
simp only [subtype.dist_eq, real.dist_eq, prod.dist_eq, sub_zero],
assume h, rw max_lt_iff at h, cases h with xδ yy₀,
have qy : q < y, calc q < y₀ / 2 : q_lt
... = y₀ - y₀ / 2 : (sub_half _).symm
... ≤ y₀ - δ : by linarith
... < y : sub_lt_of_abs_sub_lt_left yy₀,
calc abs(x^y) ≤ abs(x)^y : abs_rpow_le_abs_rpow _ _
... < δ ^ y : rpow_lt_rpow (abs_nonneg _) xδ hy
... < δ ^ q : by { refine rpow_lt_rpow_of_exponent_gt _ _ _, repeat {linarith} }
... ≤ (ε ^ (1 / q)) ^ q : by { refine rpow_le_rpow _ _ _, repeat {linarith} }
... = ε : by { rw [← rpow_mul, div_mul_cancel, rpow_one], exact ne_of_gt q_pos, linarith }},
{ exact (continuous_within_at_iff_continuous_at_restrict (λp:ℝ×ℝ, p.1^p.2) _).1
(continuous_at_rpow_of_ne_zero hx₀ _).continuous_within_at }
end
lemma continuous_at_rpow_of_pos (hy : 0 < y) (x : ℝ) :
continuous_at (λp:ℝ×ℝ, p.1^p.2) (x, y) :=
continuous_within_at.continuous_at
(continuous_on_iff_continuous_restrict.2 continuous_rpow_aux3 _ hy)
(mem_nhds_sets (by { convert is_open_prod is_open_univ (is_open_lt' (0:ℝ)), ext, finish }) hy)
variables {α : Type*} [topological_space α] {f g : α → ℝ}
/--
`real.rpow` is continuous at all points except for the lower half of the y-axis.
In other words, the function `λp:ℝ×ℝ, p.1^p.2` is continuous at `(x, y)` if `x ≠ 0` or `y > 0`.
Multiple forms of the claim is provided in the current section.
-/
lemma continuous_rpow (h : ∀a, f a ≠ 0 ∨ 0 < g a) (hf : continuous f) (hg : continuous g):
continuous (λa:α, (f a) ^ (g a)) :=
continuous_iff_continuous_at.2 $ λ a,
begin
show continuous_at ((λp:ℝ×ℝ, p.1^p.2) ∘ (λa, (f a, g a))) a,
refine continuous_at.comp _ (continuous_iff_continuous_at.1 (hf.prod_mk hg) _),
{ replace h := h a, cases h,
{ exact continuous_at_rpow_of_ne_zero h _ },
{ exact continuous_at_rpow_of_pos h _ }},
end
lemma continuous_rpow_of_ne_zero (h : ∀a, f a ≠ 0) (hf : continuous f) (hg : continuous g):
continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inl $ h a) hf hg
lemma continuous_rpow_of_pos (h : ∀a, 0 < g a) (hf : continuous f) (hg : continuous g):
continuous (λa:α, (f a) ^ (g a)) := continuous_rpow (λa, or.inr $ h a) hf hg
end prove_rpow_is_continuous
section sqrt
lemma sqrt_eq_rpow : sqrt = λx:ℝ, x ^ (1/(2:ℝ)) :=
begin
funext, by_cases h : 0 ≤ x,
{ rw [← mul_self_inj_of_nonneg, mul_self_sqrt h, ← pow_two, ← rpow_nat_cast, ← rpow_mul h],
norm_num, exact sqrt_nonneg _, exact rpow_nonneg_of_nonneg h _ },
{ replace h : x < 0 := lt_of_not_ge h,
have : 1 / (2:ℝ) * π = π / (2:ℝ), ring,
rw [sqrt_eq_zero_of_nonpos (le_of_lt h), rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] }
end
lemma continuous_sqrt : continuous sqrt :=
by rw sqrt_eq_rpow; exact continuous_rpow_of_pos (λa, by norm_num) continuous_id continuous_const
end sqrt
section exp
/-- The real exponential function tends to +infinity at +infinity -/
lemma tendsto_exp_at_top : tendsto exp at_top at_top :=
begin
have A : tendsto (λx:ℝ, x + 1) at_top at_top :=
tendsto_at_top_add_const_right at_top 1 tendsto_id,
have B : {x : ℝ | x + 1 ≤ exp x} ∈ at_top,
{ have : {x : ℝ | 0 ≤ x} ∈ at_top := mem_at_top 0,
filter_upwards [this],
exact λx hx, add_one_le_exp_of_nonneg hx },
exact tendsto_at_top_mono' at_top B A
end
/-- The real exponential function tends to 0 at -infinity or, equivalently, `exp(-x)` tends to `0`
at +infinity -/
lemma tendsto_exp_neg_at_top_nhds_0 : tendsto (λx, exp (-x)) at_top (𝓝 0) :=
(tendsto.comp tendsto_inverse_at_top_nhds_0 (tendsto_exp_at_top)).congr (λx, (exp_neg x).symm)
/-- The function `exp(x)/x^n` tends to +infinity at +infinity, for any natural number `n` -/
lemma tendsto_exp_div_pow_at_top (n : ℕ) : tendsto (λx, exp x / x^n) at_top at_top :=
begin
have n_pos : (0 : ℝ) < n + 1 := nat.cast_add_one_pos n,
have n_ne_zero : (n : ℝ) + 1 ≠ 0 := ne_of_gt n_pos,
have A : ∀x:ℝ, 0 < x → exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n,
{ assume x hx,
let y := x / (n+1),
have y_pos : 0 < y := div_pos hx n_pos,
have : exp (x / (n+1)) ≤ (n+1)^n * (exp x / x^n), from calc
exp y = exp y * 1 : by simp
... ≤ exp y * (exp y / y)^n : begin
apply mul_le_mul_of_nonneg_left (one_le_pow_of_one_le _ n) (le_of_lt (exp_pos _)),
apply one_le_div_of_le _ y_pos,
apply le_trans _ (add_one_le_exp_of_nonneg (le_of_lt y_pos)),
exact le_add_of_le_of_nonneg (le_refl _) (zero_le_one)
end
... = exp y * exp (n * y) / y^n :
by rw [div_pow _ (ne_of_gt y_pos), exp_nat_mul, mul_div_assoc]
... = exp ((n + 1) * y) / y^n :
by rw [← exp_add, add_mul, one_mul, add_comm]
... = exp x / (x / (n+1))^n :
by { dsimp [y], rw mul_div_cancel' _ n_ne_zero }
... = (n+1)^n * (exp x / x^n) :
by rw [← mul_div_assoc, div_pow _ n_ne_zero, div_div_eq_mul_div, mul_comm],
rwa div_le_iff' (pow_pos n_pos n) },
have B : {x : ℝ | exp (x / (n+1)) / (n+1)^n ≤ exp x / x^n} ∈ at_top :=
mem_at_top_sets.2 ⟨1, λx hx, A _ (lt_of_lt_of_le zero_lt_one hx)⟩,
have C : tendsto (λx, exp (x / (n+1)) / (n+1)^n) at_top at_top :=
tendsto_at_top_div (pow_pos n_pos n)
(tendsto_exp_at_top.comp (tendsto_at_top_div (nat.cast_add_one_pos n) tendsto_id)),
exact tendsto_at_top_mono' at_top B C
end
/-- The function `x^n * exp(-x)` tends to `0` at +infinity, for any natural number `n`. -/
lemma tendsto_pow_mul_exp_neg_at_top_nhds_0 (n : ℕ) : tendsto (λx, x^n * exp (-x)) at_top (𝓝 0) :=
(tendsto_inverse_at_top_nhds_0.comp (tendsto_exp_div_pow_at_top n)).congr $ λx,
by rw [function.comp_app, inv_eq_one_div, div_div_eq_mul_div, one_mul, div_eq_mul_inv, exp_neg]
end exp
end real
|
296914ac408b09e7b3ab1460c4386ecac6bdebce | 7cdf3413c097e5d36492d12cdd07030eb991d394 | /src/solutions/world3_le.lean | 4faa20b6c8d2de70c253c5033095a52400fc2f57 | [] | no_license | alreadydone/natural_number_game | 3135b9385a9f43e74cfbf79513fc37e69b99e0b3 | 1a39e693df4f4e871eb449890d3c7715a25c2ec9 | refs/heads/master | 1,599,387,390,105 | 1,573,200,587,000 | 1,573,200,691,000 | 220,397,084 | 0 | 0 | null | 1,573,192,734,000 | 1,573,192,733,000 | null | UTF-8 | Lean | false | false | 8,504 | lean | import mynat.le
import solutions.world2_multiplication
import tactic.interactive
-- #check tactic.interactive.rintro
meta def less_leaky.interactive.rintro := tactic.interactive.rintro
namespace mynat
-- example
theorem le_refl (a : mynat) : a ≤ a :=
begin
use 0,
rw add_zero,
end
example : one ≤ one := le_refl one
-- ignore this; it's making the "refl" tactic work with goals of the form a ≤ a
attribute [_refl_lemma] le_refl
theorem le_succ {a b : mynat} (h : a ≤ b) : a ≤ (succ b) :=
begin
cases h with c h,
use succ c,
rw add_succ, rw h,
end
lemma zero_le (a : mynat) : 0 ≤ a :=
begin
use a, rw zero_add,
end
lemma le_zero {a : mynat} : a ≤ 0 → a = 0 :=
begin
intro h,
cases h with b h,
apply add_right_eq_zero,
exact eq.symm h,
/-
intro h,
cases h with b h,
cases a with a,
refl,
rw succ_add at h,
apply absurd (eq.symm h),
apply succ_ne_zero,
-/
end
theorem le_trans ⦃a b c : mynat⦄ (hab : a ≤ b) (hbc : b ≤ c) : a ≤ c :=
begin
cases hab with d hab,
cases hbc with e hbc,
use d+e,
rw hab at hbc,
rw hbc,
apply add_assoc,
end
instance : preorder mynat := by structure_helper
-- ignore this, it's the definition.
theorem lt_iff_le_not_le {a b : mynat} : a < b ↔ a ≤ b ∧ ¬ b ≤ a := iff.rfl
theorem le_antisymm : ∀ {{a b : mynat}}, a ≤ b → b ≤ a → a = b :=
begin
intros a b hab hba,
cases hab with c hab,
cases hba with d hba,
rw hba at hab,
rw add_assoc at hab,
rw add_right_eq_zero (eq_zero_of_add_right_eq_self (eq.symm hab)) at hba,
rw add_zero at hba, exact hba,
end
instance : partial_order mynat := by structure_helper
theorem lt_iff_le_and_ne ⦃a b : mynat⦄ : a < b ↔ a ≤ b ∧ a ≠ b :=
begin
split,
intro h,
cases h with h1 h2,
split,
exact h1,
intro h,
rw h at h2,
exact h2 (le_refl b),
intro h,
split,
cases h with h _, exact h,
cases h with h1 h2,
intro h,
exact h2 (le_antisymm h1 h),
end
lemma succ_le_succ {a b : mynat} (h : a ≤ b) : succ a ≤ succ b :=
begin
cases h with c h,
use c, rw succ_add, rw h,
end
theorem le_total (a b : mynat) : a ≤ b ∨ b ≤ a :=
begin
revert a,
induction b with b h,
intro a, right, apply zero_le,
intro a, cases a with a,
left, apply zero_le,
cases h a with h1 h2,
left, exact succ_le_succ h1,
right, exact succ_le_succ h2,
end
instance : linear_order mynat := by structure_helper
theorem add_le_add_right (a b : mynat) : a ≤ b → ∀ t, (a + t) ≤ (b + t) :=
begin
intros h t,
cases h with c h,
use c,
rw h,
rw add_right_comm,
end
theorem le_succ_self (a : mynat) : a ≤ succ a :=
begin
use 1, rw succ_eq_add_one,
end
theorem le_of_succ_le_succ {a b : mynat} : succ a ≤ succ b → a ≤ b :=
begin
intro h,
cases h with c h,
use c,
rw succ_add at h,
exact succ_inj h,
/-
repeat {rw succ_eq_add_one at h},
rw add_right_comm at h,
exact (add_right_cancel h),
-/
end
theorem not_succ_le_self {{d : mynat}} (h : succ d ≤ d) : false :=
begin
cases h with c h,
rw succ_add at h,
rw ← add_succ at h,
apply zero_ne_succ,
symmetry,
exact eq_zero_of_add_right_eq_self (eq.symm h),
end
theorem add_le_add_left : ∀ (a b : mynat), a ≤ b → ∀ (c : mynat), c + a ≤ c + b :=
begin
intros a b h c,
rw add_comm c a,
rw add_comm c b,
apply add_le_add_right,
exact h,
end
def succ_le_succ_iff (a b : mynat) : succ a ≤ succ b ↔ a ≤ b :=
begin
split,
exact le_of_succ_le_succ,
exact succ_le_succ,
end
-- convenient lemma
def lt_iff_succ_le (a b : mynat) : a < b ↔ succ a ≤ b :=
begin
split,
intro h,
cases h with h1 h2,
cases h1 with c h1,
cases c with c,
rw mynat_zero_eq_zero at h1,
rw add_zero at h1,
rw h1 at h2,
apply absurd (le_refl a) h2,
use c,
rw succ_add, rw ← add_succ, exact h1,
intro h,
split,
cases h with c h,
use (succ c),
rw add_succ, rw ← succ_add, exact h,
intro h1,
exact not_succ_le_self (le_trans h h1),
end
def succ_lt_succ_iff (a b : mynat) : succ a < succ b ↔ a < b :=
begin
repeat {rw lt_iff_succ_le},
exact succ_le_succ_iff (succ a) b,
/-
split,
intro h,
cases h with h1 h2,
split,
apply le_of_succ_le_succ h1,
intro h, exact h2 (succ_le_succ h),
intro h,
cases h with h1 h2,
split,
apply succ_le_succ h1,
intro h, exact h2 (le_of_succ_le_succ h),
-/
end
theorem le_of_add_le_add_left ⦃ a b c : mynat⦄ : a + b ≤ a + c → b ≤ c :=
begin
intro h,
cases h with d h,
use d,
rw add_assoc at h,
exact add_left_cancel h,
end
theorem lt_of_add_lt_add_left : ∀ {{a b c : mynat}}, a + b < a + c → b < c :=
begin
intros a b c,
repeat {rw lt_iff_succ_le},
rw ← add_succ,
intro h,
exact le_of_add_le_add_left h,
end
theorem le_iff_exists_add : ∀ (a b : mynat), a ≤ b ↔ ∃ (c : mynat), b = a + c :=
begin
exact le_def,
end
theorem zero_ne_one : (0 : mynat) ≠ 1 :=
begin
exact zero_ne_succ 0,
end
instance : ordered_comm_monoid mynat := by structure_helper
instance : ordered_cancel_comm_monoid mynat := by structure_helper
-- removed redundant condition 0 ≤ c
theorem mul_le_mul_of_nonneg_left ⦃a b c : mynat⦄ : a ≤ b → c * a ≤ c * b :=
begin
intros h,
cases h with d h,
rw h, rw mul_add,
use c*d,
end
theorem mul_le_mul_of_nonneg_right ⦃a b c : mynat⦄ : a ≤ b → a * c ≤ b * c :=
begin
rw mul_comm a c, rw mul_comm b c,
apply mul_le_mul_of_nonneg_left,
end
theorem ne_zero_of_pos ⦃a : mynat⦄ : 0 < a → a ≠ 0 :=
begin
rw lt_iff_le_and_ne,
intros h,
cases h with _ h,
symmetry, exact h,
end
theorem mul_lt_mul_of_pos_left ⦃a b c : mynat⦄ : a < b → 0 < c → c * a < c * b :=
begin
intros h hc,
rw lt_iff_succ_le at h hc ⊢, rw succ_eq_add_one,
apply le_trans (add_le_add_left 1 c hc (c*a)),
rw ← mul_succ,
exact mul_le_mul_of_nonneg_left h,
end
theorem mul_lt_mul_of_pos_right ⦃a b c : mynat⦄ : a < b → 0 < c → a * c < b * c :=
begin
rw mul_comm a c, rw mul_comm b c,
apply mul_lt_mul_of_pos_left,
end
instance : ordered_semiring mynat := by structure_helper
lemma lt_irrefl (a : mynat) : ¬ (a < a) :=
begin
intro h,
cases h with h1 h2,
exact h2 h1,
end
theorem not_lt_zero ⦃a : mynat⦄ : ¬(a < 0) :=
begin
intro h,
rw lt_iff_succ_le at h,
exact not_succ_le_self (le_trans h (zero_le a)),
end
theorem lt_succ_self (n : mynat) : n < succ n :=
begin
rw lt_iff_succ_le,
end
theorem lt_succ_iff (m n : mynat) : m < succ n ↔ m ≤ n :=
begin
rw lt_iff_succ_le,
exact succ_le_succ_iff m n,
end
-- lemma necessary for the second approach to strong_induction below
theorem le_if_eq_or_lt (m n : mynat) : m ≤ n ↔ m < n ∨ m = n :=
begin
split,
intro h,
cases h with c h,
cases c with c,
right, rw [mynat_zero_eq_zero, add_zero] at h, symmetry, exact h,
left, rw [add_succ, ← succ_add] at h, rw lt_iff_succ_le, use c, exact h,
intro h, cases h,
rw lt_iff_le_not_le at h, cases h with h _, exact h,
rw h,
end
theorem strong_induction (P : mynat → Prop)
(IH : ∀ m : mynat, (∀ d : mynat, d < m → P d) → P m) :
∀ n, P n :=
begin [less_leaky]
intro n,
apply IH,
induction n with n h,
intros d ltz, exfalso, exact not_lt_zero ltz,
{
intros d h1,
rw lt_succ_iff at h1,
apply IH,
intros e h2,
apply h,
rw lt_iff_succ_le at h2 ⊢,
exact le_trans h2 h1,
-- without appeal to lt_of_lt_of_le (external reference)
/-
rw [lt_succ_iff, le_if_eq_or_lt] at h1,
cases h1,
exact h d h1,
rw h1,
exact IH n h,
-/
}
end
end mynat
/-
instance : canonically_ordered_comm_semiring mynat :=
{ add := (+),
add_assoc := add_assoc,
zero := 0,
zero_add := zero_add,
add_zero := add_zero,
add_comm := add_comm,
le := (≤),
le_refl := le_refl,
le_trans := le_trans,
le_antisymm := le_antisymm,
add_le_add_left := add_le_add_left,
lt_of_add_lt_add_left := lt_of_add_lt_add_left,
bot := 0,
bot_le := zero_le,
le_iff_exists_add := le_iff_exists_add,
mul := (*),
mul_assoc := mul_assoc,
one := 1,
one_mul := one_mul,
mul_one := mul_one,
left_distrib := left_distrib,
right_distrib := right_distrib,
zero_mul := zero_mul,
mul_zero := mul_zero,
mul_comm := mul_comm,
zero_ne_one := zero_ne_one,
mul_eq_zero_iff := mul_eq_zero_iff }
-/
|
4de9288b7e4fe5aae5669c9a7cdc2f819a2dfbad | 453dcd7c0d1ef170b0843a81d7d8caedc9741dce | /algebra/pi_instances.lean | aadfa2b60f5bb5259b8984efd5342167bc45a187 | [
"Apache-2.0"
] | permissive | amswerdlow/mathlib | 9af77a1f08486d8fa059448ae2d97795bd12ec0c | 27f96e30b9c9bf518341705c99d641c38638dfd0 | refs/heads/master | 1,585,200,953,598 | 1,534,275,532,000 | 1,534,275,532,000 | 144,564,700 | 0 | 0 | null | 1,534,156,197,000 | 1,534,156,197,000 | null | UTF-8 | Lean | false | false | 3,830 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
Pi instances for algebraic structures.
-/
import algebra.module order.basic tactic.pi_instances
namespace pi
universes u v
variable {I : Type u} -- The indexing type
variable {f : I → Type v} -- The family of types already equiped with instances
variables (x y : Π i, f i) (i : I)
instance has_zero [∀ i, has_zero $ f i] : has_zero (Π i : I, f i) := ⟨λ i, 0⟩
@[simp] lemma zero_apply [∀ i, has_zero $ f i] : (0 : Π i, f i) i = 0 := rfl
instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ i, 1⟩
@[simp] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl
instance has_add [∀ i, has_add $ f i] : has_add (Π i : I, f i) := ⟨λ x y, λ i, x i + y i⟩
@[simp] lemma add_apply [∀ i, has_add $ f i] : (x + y) i = x i + y i := rfl
instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ x y, λ i, x i * y i⟩
@[simp] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl
instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ x, λ i, (x i)⁻¹⟩
@[simp] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl
instance has_neg [∀ i, has_neg $ f i] : has_neg (Π i : I, f i) := ⟨λ x, λ i, -(x i)⟩
@[simp] lemma neg_apply [∀ i, has_neg $ f i] : (-x) i = -x i := rfl
instance has_scalar {α : Type*} [∀ i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩
@[simp] lemma smul_apply {α : Type*} [∀ i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl
instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by pi_instance
instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by pi_instance
instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by pi_instance
instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by pi_instance
instance add_comm_monoid [∀ i, add_comm_monoid $ f i] : add_comm_monoid (Π i : I, f i) := by pi_instance
instance group [∀ i, group $ f i] : group (Π i : I, f i) := by pi_instance
instance add_semigroup [∀ i, add_semigroup $ f i] : add_semigroup (Π i : I, f i) := by pi_instance
instance add_group [∀ i, add_group $ f i] : add_group (Π i : I, f i) := by pi_instance
instance add_comm_group [∀ i, add_comm_group $ f i] : add_comm_group (Π i : I, f i) := by pi_instance
instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by pi_instance
instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by pi_instance
instance module {α} [ring α] [∀ i, module α $ f i] : module α (Π i : I, f i) := by pi_instance
instance vector_space (α) [field α] [∀ i, vector_space α $ f i] : vector_space α (Π i : I, f i) :=
{ ..pi.module }
instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance add_left_cancel_semigroup [∀ i, add_left_cancel_semigroup $ f i] : add_left_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance add_right_cancel_semigroup [∀ i, add_right_cancel_semigroup $ f i] : add_right_cancel_semigroup (Π i : I, f i) :=
by pi_instance
instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) :=
by pi_instance
end pi
|
fe053ec6609f472ec3ede5bd0b1bdb60d15fc5d7 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Lean/Elab/PreDefinition/Basic.lean | e802b549203a4e5acd1351e0de1d33ce8aa3e4a2 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 7,667 | 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.Util.SCC
import Lean.Meta.AbstractNestedProofs
import Lean.Meta.Transform
import Lean.Elab.Term
import Lean.Elab.RecAppSyntax
import Lean.Elab.DefView
import Lean.Elab.PreDefinition.MkInhabitant
namespace Lean.Elab
open Meta
open Term
/--
A (potentially recursive) definition.
The elaborator converts it into Kernel definitions using many different strategies.
-/
structure PreDefinition where
ref : Syntax
kind : DefKind
levelParams : List Name
modifiers : Modifiers
declName : Name
type : Expr
value : Expr
deriving Inhabited
def instantiateMVarsAtPreDecls (preDefs : Array PreDefinition) : TermElabM (Array PreDefinition) :=
preDefs.mapM fun preDef => do
pure { preDef with type := (← instantiateMVars preDef.type), value := (← instantiateMVars preDef.value) }
private def levelMVarToParamPreDeclsAux (preDefs : Array PreDefinition) : StateRefT Nat TermElabM (Array PreDefinition) :=
preDefs.mapM fun preDef => do
pure { preDef with type := (← levelMVarToParam' preDef.type), value := (← levelMVarToParam' preDef.value) }
def levelMVarToParamPreDecls (preDefs : Array PreDefinition) : TermElabM (Array PreDefinition) :=
(levelMVarToParamPreDeclsAux preDefs).run' 1
private def getLevelParamsPreDecls (preDefs : Array PreDefinition) (scopeLevelNames allUserLevelNames : List Name) : TermElabM (List Name) := do
let mut s : CollectLevelParams.State := {}
for preDef in preDefs do
s := collectLevelParams s preDef.type
s := collectLevelParams s preDef.value
match sortDeclLevelParams scopeLevelNames allUserLevelNames s.params with
| Except.error msg => throwError msg
| Except.ok levelParams => pure levelParams
def fixLevelParams (preDefs : Array PreDefinition) (scopeLevelNames allUserLevelNames : List Name) : TermElabM (Array PreDefinition) := do
-- We used to use `shareCommon` here, but is was a bottleneck
let levelParams ← getLevelParamsPreDecls preDefs scopeLevelNames allUserLevelNames
let us := levelParams.map mkLevelParam
let fixExpr (e : Expr) : Expr :=
e.replace fun c => match c with
| Expr.const declName _ _ => if preDefs.any fun preDef => preDef.declName == declName then some $ Lean.mkConst declName us else none
| _ => none
pure $ preDefs.map fun preDef =>
{ preDef with
type := fixExpr preDef.type,
value := fixExpr preDef.value,
levelParams := levelParams }
def applyAttributesOf (preDefs : Array PreDefinition) (applicationTime : AttributeApplicationTime) : TermElabM Unit := do
for preDef in preDefs do
applyAttributesAt preDef.declName preDef.modifiers.attrs applicationTime
def abstractNestedProofs (preDef : PreDefinition) : MetaM PreDefinition :=
if preDef.kind.isTheorem || preDef.kind.isExample then
pure preDef
else do
let value ← Meta.abstractNestedProofs preDef.declName preDef.value
pure { preDef with value := value }
/- Auxiliary method for (temporarily) adding pre definition as an axiom -/
def addAsAxiom (preDef : PreDefinition) : MetaM Unit := do
withRef preDef.ref do
addDecl <| Declaration.axiomDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, isUnsafe := preDef.modifiers.isUnsafe }
private def shouldGenCodeFor (preDef : PreDefinition) : Bool :=
!preDef.kind.isTheorem && !preDef.modifiers.isNoncomputable
private def compileDecl (decl : Declaration) : TermElabM Bool := do
try
Lean.compileDecl decl
catch ex =>
if (← read).isNoncomputableSection then
return false
else
throw ex
return true
private def addNonRecAux (preDef : PreDefinition) (compile : Bool) : TermElabM Unit :=
withRef preDef.ref do
let preDef ← abstractNestedProofs preDef
let env ← getEnv
let decl :=
match preDef.kind with
| DefKind.«theorem» =>
Declaration.thmDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, value := preDef.value }
| DefKind.«opaque» =>
Declaration.opaqueDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, value := preDef.value,
isUnsafe := preDef.modifiers.isUnsafe }
| DefKind.«abbrev» =>
Declaration.defnDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, value := preDef.value,
hints := ReducibilityHints.«abbrev»,
safety := if preDef.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe }
| _ => -- definitions and examples
Declaration.defnDecl { name := preDef.declName, levelParams := preDef.levelParams, type := preDef.type, value := preDef.value,
hints := ReducibilityHints.regular (getMaxHeight env preDef.value + 1),
safety := if preDef.modifiers.isUnsafe then DefinitionSafety.unsafe else DefinitionSafety.safe }
addDecl decl
withSaveInfoContext do -- save new env
addTermInfo preDef.ref (← mkConstWithLevelParams preDef.declName) (isBinder := true)
applyAttributesOf #[preDef] AttributeApplicationTime.afterTypeChecking
if compile && shouldGenCodeFor preDef then
unless (← compileDecl decl) do
return ()
applyAttributesOf #[preDef] AttributeApplicationTime.afterCompilation
def addAndCompileNonRec (preDef : PreDefinition) : TermElabM Unit := do
addNonRecAux preDef true
def addNonRec (preDef : PreDefinition) : TermElabM Unit := do
addNonRecAux preDef false
/--
Eliminate recursive application annotations containing syntax. These annotations are used by the well-founded recursion module
to produce better error messages. -/
def eraseRecAppSyntax (e : Expr) : CoreM Expr :=
Core.transform e (post := fun e => TransformStep.done <| if (getRecAppSyntax? e).isSome then e.mdataExpr! else e)
def addAndCompileUnsafe (preDefs : Array PreDefinition) (safety := DefinitionSafety.unsafe) : TermElabM Unit :=
withRef preDefs[0].ref do
let decl := Declaration.mutualDefnDecl <| ← preDefs.toList.mapM fun preDef => return {
name := preDef.declName
levelParams := preDef.levelParams
type := preDef.type
value := (← eraseRecAppSyntax preDef.value)
safety := safety
hints := ReducibilityHints.opaque
}
addDecl decl
withSaveInfoContext do -- save new env
for preDef in preDefs do
addTermInfo preDef.ref (← mkConstWithLevelParams preDef.declName) (isBinder := true)
applyAttributesOf preDefs AttributeApplicationTime.afterTypeChecking
unless (← compileDecl decl) do
return ()
applyAttributesOf preDefs AttributeApplicationTime.afterCompilation
return ()
def addAndCompilePartialRec (preDefs : Array PreDefinition) : TermElabM Unit := do
if preDefs.all shouldGenCodeFor then
addAndCompileUnsafe (safety := DefinitionSafety.partial) <| preDefs.map fun preDef =>
{ preDef with
declName := Compiler.mkUnsafeRecName preDef.declName,
value := preDef.value.replace fun e => match e with
| Expr.const declName us _ =>
if preDefs.any fun preDef => preDef.declName == declName then
some $ mkConst (Compiler.mkUnsafeRecName declName) us
else
none
| _ => none,
modifiers := {} }
end Lean.Elab
|
b32e0755023bd38b91921454f7343479ebffcddf | 01f6b345a06ece970e589d4bbc68ee8b9b2cf58a | /src/normed_space.lean | 98f3f22f75563e5bebe3d247f74b3567310e0b11 | [] | no_license | mariainesdff/norm_extensions_journal_submission | 6077acb98a7200de4553e653d81d54fb5d2314c8 | d396130660935464fbc683f9aaf37fff8a890baa | refs/heads/master | 1,686,685,693,347 | 1,684,065,115,000 | 1,684,065,115,000 | 603,823,641 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 17,569 | lean | /-
Copyright (c) 2023 María Inés de Frutos-Fernández. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: María Inés de Frutos-Fernández
-/
import analysis.normed_space.bounded_linear_maps
import seminorm_from_bounded
import smoothing_seminorm
/-!
# Basis.norm
In this file, we prove [BGR, Lemma 3.2.1./3]: if `K` is a normed field with a nonarchimedean
power-multiplicative norm and `L/K` is a finite extension, then there exists at least one
power-multiplicative `K`-algebra norm on `L` extending the norm on `K`.
## Main Definitions
* `basis.norm` : the function sending an element `x : L` to the maximum of the norms of its
coefficients with respect to the `K`-basis `B` of `L`.
## Main Results
* `finite_extension_pow_mul_seminorm` : the proof of [BGR, Lemma 3.2.1./3].
## References
* [S. Bosch, U. Güntzer, R. Remmert, *Non-Archimedean Analysis*][bosch-guntzer-remmert]
## Tags
basis.norm, nonarchimedean
-/
noncomputable theory
open finset
open_locale big_operators
section continuous
/-- A continuous linear map between normed spaces. -/
structure is_continuous_linear_map (𝕜 : Type*) [normed_field 𝕜]
{E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E]
{F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] (f : E → F)
extends is_linear_map 𝕜 f : Prop :=
(cont : continuous f . tactic.interactive.continuity')
/-- A linear map between normed spaces is continuous if and only if it is bounded,-/
lemma is_continuous_linear_map_iff_is_bounded_linear_map {K : Type*} [nontrivially_normed_field K]
{M : Type*} [normed_add_comm_group M] [normed_space K M] {N : Type*} [normed_add_comm_group N]
[normed_space K N] (f : M → N) : is_continuous_linear_map K f ↔ is_bounded_linear_map K f :=
begin
refine ⟨λ h_cont, _, λ h_bdd, ⟨h_bdd.to_is_linear_map, h_bdd.continuous⟩⟩,
{ set F : M →L[K] N :=
by use [f, is_linear_map.map_add h_cont.1, is_linear_map.map_smul h_cont.1, h_cont.2],
exact continuous_linear_map.is_bounded_linear_map F, },
end
end continuous
section finsum
/-- Given a function `f : α → M` and a linear equivalence `g : M ≃ₛₗ[σ] N`, we have
`g ∑ᶠ f i = ∑ᶠ g(f i)`. -/
theorem linear_equiv.map_finsum {R S : Type*} {α : Sort*} [semiring R] [semiring S] (σ : R →+* S)
{σ' : S →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] (M N : Type*) [add_comm_monoid M]
[add_comm_monoid N] [module R M] [module S N] (g : M ≃ₛₗ[σ] N) (f : α → M) :
g (finsum (λ (i : α), f i)) = finsum (λ (i : α), g (f i)) :=
add_equiv.map_finsum g.to_add_equiv f
/-- Given a fintype `α`, a function `f : α → M` and a linear equivalence `g : M ≃ₛₗ[σ] N`, we have
`g (∑ (i : α), f i) = ∑ (i : α), g (f i)`. -/
theorem linear_equiv.map_finset_sum {R S : Type*} {α : Sort*} [fintype α] [semiring R] [semiring S]
(σ : R →+* S) {σ' : S →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] (M N : Type*)
[add_comm_monoid M] [add_comm_monoid N] [module R M] [module S N] (g : M ≃ₛₗ[σ] N)
(f : α → M) : g (∑ (i : α), f i) = ∑ (i : α), g (f i) :=
by simp only [← finsum_eq_sum_of_fintype, linear_equiv.map_finsum]
theorem finsum_apply {α : Type*} {β : α → Type*} {γ : Type*} [finite γ]
[Π (a : α), add_comm_monoid (β a)] (a : α) (g : γ → Π (a : α), β a) :
finsum (λ (c : γ), g c) a = finsum (λ (c : γ), g c a) :=
begin
casesI nonempty_fintype γ,
simp only [finsum_eq_sum_of_fintype, sum_apply]
end
/-- If `∑ i, f i • v i = ∑ i, g i • v i`, then for all `i`, `f i = g i`. -/
lemma linear_independent.eq_coords_of_eq {R : Type*} [ring R] {M : Type*} [add_comm_group M]
[module R M] {ι : Type*} [fintype ι] {v : ι → M} (hv : linear_independent R v) {f : ι → R}
{g : ι → R} (heq : ∑ i, f i • v i = ∑ i, g i • v i) (i : ι) : f i = g i :=
begin
rw [← sub_eq_zero, ← sum_sub_distrib] at heq,
simp_rw ← sub_smul at heq,
rw linear_independent_iff' at hv,
exact sub_eq_zero.mp (hv univ (λ i, (f i - g i)) heq i (mem_univ i)),
end
end finsum
variables {K : Type*} [normed_field K] {L : Type*} [field L] [algebra K L]
/-- If `B` is a basis of the `K`-vector space `L` such that `B i = 1` for some index `i`, then
each `k:K` gets represented as `k • B i` as an element of `L`. -/
lemma basis_one {ι : Type*} [fintype ι] [decidable_eq ι] {B : basis ι K L} {i : ι}
(hBi : B i = (1 : L)) (k : K) :
B.equiv_fun ((algebra_map K L) k) = λ (j : ι), if (j = i) then k else 0 :=
begin
ext j,
apply linear_independent.eq_coords_of_eq B.linear_independent,
rw basis.sum_equiv_fun B (algebra_map K L k),
have h_sum : ∑ (j : ι), ite (j = i) k 0 • B j = ∑ (j : ι), ite (j = i) (k • B j) 0,
{ apply sum_congr (eq.refl _),
{ rintros h -,
split_ifs,
exacts [rfl, zero_smul _ _] }},
rw [h_sum, algebra.algebra_map_eq_smul_one, sum_ite_eq' univ (i : ι) (λ j : ι, k • B j)],
simp only [mem_univ, if_true, hBi],
end
namespace basis
/-- The function sending an element `x : L` to the maximum of the norms of its coefficients
with respect to the `K`-basis `B` of `L`.-/
def norm {ι : Type*} [fintype ι] [nonempty ι] (B : basis ι K L) : L → ℝ :=
λ x, ‖B.equiv_fun x (classical.some (finite.exists_max (λ i : ι, ‖B.equiv_fun x i‖ )))‖
/-- The norm of a coefficient `x_i` is less than or equal to the norm of `x`. -/
lemma le_norm {ι : Type*} [fintype ι] [nonempty ι] (B : basis ι K L) (x : L) (i : ι) :
‖B.equiv_fun x i‖ ≤ B.norm x :=
classical.some_spec (finite.exists_max (λ i : ι, ‖B.equiv_fun x i‖)) i
/-- For any `K`-basis of `L`, we have `B.norm 0 = 0`. -/
lemma norm_zero' {ι : Type*} [fintype ι] [nonempty ι] (B : basis ι K L) : B.norm 0 = 0 :=
by simp only [norm, map_zero, pi.zero_apply, norm_zero]
/-- For any `K`-basis of `L`, and any `x : L`, we have `B.norm (-x) = B.norm x`. -/
lemma norm_neg {ι : Type*} [fintype ι] [nonempty ι] (B : basis ι K L) (x : L) :
B.norm (-x) = B.norm x :=
begin
simp only [norm, map_neg],
convert norm_neg _,
ext x, simp only [pi.neg_apply, norm_neg]
end
/-- For any `K`-basis of `L`, `B.norm` extends the norm on `K`. -/
lemma norm_extends {ι : Type*} [fintype ι] [nonempty ι] {B : basis ι K L}
{i : ι} (hBi : B i = (1 : L)) :
function_extends (λ x : K, ‖x‖) B.norm :=
begin
classical,
intro k,
{ by_cases hk : k = 0,
{ simp only [hk, map_zero, norm_zero, norm_zero'] },
{ simp only [norm, basis_one hBi],
have h_max : (classical.some (finite.exists_max (λ j : ι,
‖(λ (n : ι), if (n = i) then k else 0) j ‖))) = i,
{ by_contradiction h,
have h_max := classical.some_spec (finite.exists_max (λ j : ι,
‖(λ (n : ι), if (n = i) then k else 0) j ‖)),
simp only [if_neg h] at h_max,
specialize h_max i,
rw [if_pos rfl, norm_zero, norm_le_zero_iff] at h_max,
exact hk h_max },
rw if_pos h_max }}
end
/-- For any `K`-basis of `L`, if the norm on `K` is nonarchimedean, then so is `B.norm`. -/
lemma norm_is_nonarchimedean {ι : Type*} [fintype ι] [nonempty ι] {B : basis ι K L}
(hna : is_nonarchimedean (has_norm.norm : K → ℝ)) : is_nonarchimedean B.norm :=
begin
classical,
intros x y,
simp only [basis.norm],
set ixy := classical.some (finite.exists_max (λ i : ι, ‖B.equiv_fun (x + y) i‖)) with hixy_def,
have hxy : ‖B.equiv_fun (x + y) ixy‖ ≤ max (‖B.equiv_fun x ixy‖) (‖B.equiv_fun y ixy‖),
{ rw [linear_equiv.map_add, pi.add_apply], exact hna _ _ },
have hix := classical.some_spec (finite.exists_max (λ i : ι, ‖B.equiv_fun x i‖)),
have hiy := classical.some_spec (finite.exists_max (λ i : ι, ‖B.equiv_fun y i‖)),
cases le_max_iff.mp hxy with hx hy,
{ apply le_max_of_le_left (le_trans hx (hix ixy)) },
{ apply le_max_of_le_right (le_trans hy (hiy ixy)) },
end
/-- For any `K`-basis of `L`, `B.norm` is bounded with respect to multiplication. That is,
`∃ (c : ℝ), c > 0` such that ` ∀ (x y : L), B.norm (x * y) ≤ c * B.norm x * B.norm y`. -/
lemma norm_is_bdd {ι : Type*} [fintype ι] [nonempty ι] {B : basis ι K L} {i : ι}
(hBi : B i = (1 : L)) (hna : is_nonarchimedean (has_norm.norm : K → ℝ)) :
∃ (c : ℝ) (hc : 0 < c), ∀ (x y : L), B.norm (x * y) ≤ c * B.norm x * B.norm y :=
begin
classical,
-- The bounding constant `c` will be the maximum of the products `B.norm (B i * B j)`.
set c := classical.some (finite.exists_max (λ (i : ι × ι), B.norm (B i.1 * B i.2))) with hc_def,
have hc := classical.some_spec (finite.exists_max (λ (i : ι × ι), B.norm (B i.1 * B i.2))),
use B.norm (B c.1 * B c.2),
split,
-- `B c.1 * B c.2` is positive
{ have h_pos : (0 : ℝ) < B.norm (B i * B i),
{ have h1 : (1 : L) = (algebra_map K L) 1 := by rw map_one,
rw [hBi, mul_one, h1, basis.norm_extends hBi],
simp only [norm_one, zero_lt_one] },
exact lt_of_lt_of_le h_pos (hc (i, i)) },
-- ∀ (x y : L), B.norm (x * y) ≤ B.norm (⇑B c.fst * ⇑B c.snd) * B.norm x * B.norm y
{ intros x y,
-- `ixy` is an index for which `‖B.equiv_fun (x*y) i‖` is maximum.
set ixy := classical.some (finite.exists_max (λ i : ι, ‖B.equiv_fun (x*y) i‖)) with hixy_def,
-- We rewrite the LHS using `ixy`.
conv_lhs{ simp only [basis.norm],
rw [← hixy_def, ← basis.sum_equiv_fun B x, ← basis.sum_equiv_fun B y] },
rw [sum_mul, linear_equiv.map_finset_sum, sum_apply],
simp_rw [smul_mul_assoc, linear_equiv.map_smul, mul_sum,
linear_equiv.map_finset_sum, mul_smul_comm, linear_equiv.map_smul],
/- Since the norm is nonarchimidean, the norm of a finite sum is bounded by the maximum of the
norms of the summands. -/
have hna' : is_nonarchimedean (normed_field.to_mul_ring_norm K) := hna,
have hk : ∃ (k : ι) (hk : univ.nonempty → k ∈ univ),
‖∑ (i : ι),
(B.equiv_fun x i • ∑ (i_1 : ι), B.equiv_fun y i_1 • B.equiv_fun (B i * B i_1)) ixy‖ ≤
‖ (B.equiv_fun x k • ∑ (j : ι), B.equiv_fun y j • B.equiv_fun (B k * B j)) ixy‖ :=
is_nonarchimedean_finset_image_add hna'
(λ i, (B.equiv_fun x i • ∑ (i_1 : ι), B.equiv_fun y i_1 • B.equiv_fun (B i * B i_1)) ixy)
(univ : finset ι),
obtain ⟨k, -, hk⟩ := hk,
apply le_trans hk,
-- We use the above property again.
have hk' : ∃ (k' : ι) (hk' : univ.nonempty → k' ∈ univ),
‖∑ (j : ι), B.equiv_fun y j • B.equiv_fun (B k * B j) ixy‖ ≤
‖B.equiv_fun y k' • B.equiv_fun (B k * B k') ixy‖ :=
is_nonarchimedean_finset_image_add hna'
(λ i, B.equiv_fun y i • B.equiv_fun (B k * B i) ixy) (univ : finset ι),
obtain ⟨k', -, hk'⟩ := hk',
rw [pi.smul_apply, norm_smul, sum_apply],
apply le_trans (mul_le_mul_of_nonneg_left hk' (norm_nonneg _)),
-- Now an easy computation leads to the desired conclusion.
rw [norm_smul, mul_assoc, mul_comm (B.norm (B c.fst * B c.snd)), ← mul_assoc],
exact mul_le_mul (mul_le_mul (B.le_norm _ _) (B.le_norm _ _) (norm_nonneg _) (norm_nonneg _))
(le_trans (B.le_norm _ _) (hc (k, k'))) (norm_nonneg _)
(mul_nonneg (norm_nonneg _) (norm_nonneg _)) }
end
/-- For any `k : K`, `y : L`, we have
`B.equiv_fun ((algebra_map K L k) * y) i = k * (B.equiv_fun y i) `. -/
lemma repr_smul {ι : Type*} [fintype ι] (B : basis ι K L) (i : ι) (k : K) (y : L) :
B.equiv_fun ((algebra_map K L k) * y) i = k * (B.equiv_fun y i) :=
by rw [← smul_eq_mul, algebra_map_smul, linear_equiv.map_smul]; refl
/-- For any `k : K`, `y : L`, we have
`B.norm ((algebra_map K L) k * y) = B.norm ((algebra_map K L) k) * B.norm y`. -/
lemma norm_smul {ι : Type*} [fintype ι] [nonempty ι] {B : basis ι K L}
{i : ι} (hBi : B i = (1 : L)) (k : K) (y : L) :
B.norm ((algebra_map K L) k * y) = B.norm ((algebra_map K L) k) * B.norm y :=
begin
classical,
by_cases hk : k = 0,
{ rw [hk, map_zero, zero_mul, B.norm_zero', zero_mul],},
{ rw norm_extends hBi,
simp only [norm],
set i := classical.some (finite.exists_max (λ i : ι, ‖B.equiv_fun y i‖)) with hi_def,
have hi := classical.some_spec (finite.exists_max (λ i : ι, ‖B.equiv_fun y i‖)),
set j := classical.some (finite.exists_max (λ i : ι, ‖B.equiv_fun ((algebra_map K L) k * y) i‖))
with hj_def,
have hj := classical.some_spec
(finite.exists_max (λ i : ι, ‖B.equiv_fun ((algebra_map K L) k * y) i‖)),
have hij : ‖B.equiv_fun y i‖ = ‖B.equiv_fun y j‖,
{ refine le_antisymm _ (hi j),
{ specialize hj i,
rw ← hj_def at hj,
simp only [repr_smul, norm_mul] at hj,
exact (mul_le_mul_left (lt_of_le_of_ne (norm_nonneg _)
(ne.symm (norm_ne_zero_iff.mpr hk)))).mp hj }},
rw [repr_smul, norm_mul, ← hi_def, ← hj_def, hij] },
end
end basis
/-- If `K` is a nonarchimedean normed field `L/K` is a finite extension, then there exists a
power-multiplicative nonarchimedean `K`-algebra norm on `L` extending the norm on `K`. -/
lemma finite_extension_pow_mul_seminorm (hfd : finite_dimensional K L)
(hna : is_nonarchimedean (norm : K → ℝ)) :
∃ (f : algebra_norm K L), is_pow_mul f ∧ function_extends (norm : K → ℝ) f ∧
is_nonarchimedean f :=
begin
-- Choose a basis B = {1, e2,..., en} of the K-vector space L
classical,
set h1 : linear_independent K (λ (x : ({1} : set L)), (x : L)) :=
linear_independent_singleton one_ne_zero,
set ι := {x // x ∈ (h1.extend (set.subset_univ ({1} : set L)))} with hι,
set B : basis ι K L := basis.extend h1 with hB,
letI hfin : fintype ι := finite_dimensional.fintype_basis_index B,
haveI hem : nonempty ι := B.index_nonempty,
have h1L : (1 : L) ∈ h1.extend _ := basis.subset_extend _ (set.mem_singleton (1 : L)),
have hB1 : B ⟨1, h1L⟩ = (1 : L),
{ rw [basis.coe_extend, subtype.coe_mk] },
-- For every k ∈ K, k = k • 1 + 0 • e2 + ... + 0 • en
have h_k : ∀ (k : K), B.equiv_fun ((algebra_map K L) k) = λ (i : ι),
if (i = ⟨(1 : L), h1L⟩) then k else 0 := basis_one hB1,
-- Define a function g : L → ℝ by setting g (∑ki • ei) = maxᵢ ‖ ki ‖
set g : L → ℝ := B.norm with hg,
-- g 0 = 0
have hg0 : g 0 = 0 := B.norm_zero',
-- g takes nonnegative values
have hg_nonneg : ∀ (x : L), 0 ≤ g x := λ x, norm_nonneg _,
-- g extends the norm on K
have hg_ext : function_extends (norm : K → ℝ) g := basis.norm_extends hB1,
-- g is nonarchimedean
have hg_na : is_nonarchimedean g := basis.norm_is_nonarchimedean hna,
-- g satisfies the triangle inequality
have hg_add : ∀ (a b : L), g (a + b) ≤ g a + g b,
{ exact add_le_of_is_nonarchimedean hg_nonneg hg_na },
-- g (-a) = g a
have hg_neg : ∀ (a : L), g (-a) = g a := B.norm_neg,
-- g is multiplicatively bounded
have hg_bdd : ∃ (c : ℝ) (hc : 0 < c), ∀ (x y : L), g (x * y) ≤ c * g x * g y,
{ exact basis.norm_is_bdd hB1 hna },
-- g is a K-module norm
have hg_mul : ∀ (k : K) (y : L), g ((algebra_map K L) k * y) = g ((algebra_map K L) k) * g y :=
λ k y, basis.norm_smul hB1 k y,
-- Using BGR Prop. 1.2.1/2, we can smooth g to a ring norm f on L that extends the norm on K.
set f := seminorm_from_bounded hg0 hg_nonneg hg_bdd hg_add hg_neg with hf,
have hf_na : is_nonarchimedean f :=
seminorm_from_bounded_is_nonarchimedean hg_nonneg hg_bdd hg_na,
have hf_1 : f 1 ≤ 1 := seminorm_from_bounded_is_norm_le_one_class hg_nonneg hg_bdd,
have hf_ext : function_extends (norm : K → ℝ) f,
{ intro k,
rw ← hg_ext,
exact seminorm_from_bounded_of_mul_apply hg_nonneg hg_bdd (hg_mul k) },
-- Using BGR Prop. 1.3.2/1, we obtain from f a power multiplicative K-algebra norm on L
-- extending the norm on K.
set F' := smoothing_seminorm f hf_1 hf_na with hF',
have hF'_ext : ∀ k : K, F' ((algebra_map K L) k) = ‖k‖,
{ intro k,
rw ← hf_ext _,
exact smoothing_seminorm_apply_of_is_mul f hf_1 hf_na
(seminorm_from_bounded_of_mul_is_mul hg_nonneg hg_bdd (hg_mul k)) },
have hF'_1 : F' 1 = 1,
{ have h1 : (1 : L) = (algebra_map K L) 1 := by rw map_one,
simp only [h1, hF'_ext (1 : K), norm_one], },
have hF'_0 : F' ≠ 0 := fun_like.ne_iff.mpr ⟨(1 : L), by {rw hF'_1, exact one_ne_zero}⟩,
set F : algebra_norm K L :=
{ smul' := λ k y,
begin
simp only [ring_norm.to_fun_eq_coe],
have hk : ∀ y : L, f ((algebra_map K L k) * y) = f (algebra_map K L k) * f y,
{ exact seminorm_from_bounded_of_mul_is_mul hg_nonneg hg_bdd (hg_mul k), },
have hfk : ‖k‖ = (smoothing_seminorm f hf_1 hf_na)((algebra_map K L) k),
{ rw [← hf_ext k, eq_comm, smoothing_seminorm_apply_of_is_mul f hf_1 hf_na hk] },
simp only [hfk, hF'],
erw [← smoothing_seminorm_of_mul f hf_1 hf_na hk y, algebra.smul_def],
refl,
end,
..(ring_seminorm.to_ring_norm F' hF'_0) },
have hF_ext : ∀ k : K, F ((algebra_map K L) k) = ‖k‖,
{ intro k,
rw ← hf_ext _,
exact smoothing_seminorm_apply_of_is_mul f hf_1 hf_na
(seminorm_from_bounded_of_mul_is_mul hg_nonneg hg_bdd (hg_mul k)) },
have hF_1 : F 1 = 1,
{ have h1 : (1 : L) = (algebra_map K L) 1 := by rw map_one,
simp only [h1, hF_ext (1 : K), norm_one], },
exact ⟨F, smoothing_seminorm_is_pow_mul f hf_1, hF_ext,
smoothing_seminorm_is_nonarchimedean f hf_1 hf_na⟩,
end |
a6140f43a2d50319a29e0c6119cfe07ab8b6d6ff | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/control/id_auto.lean | cf5532e5c7287e59257301d625a56db6ae745f7a | [] | 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 | 502 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sebastian Ullrich
The identity monad.
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.control.lift
universes u u_1
namespace Mathlib
def id_bind {α : Type u} {β : Type u} (x : α) (f : α → id β) : id β := f x
protected instance id.monad : Monad id := sorry
protected instance id.monad_run : monad_run id id := monad_run.mk id
end Mathlib |
810e964400d35ead754393d7e4a2352685e70dac | d1a52c3f208fa42c41df8278c3d280f075eb020c | /tests/lean/run/whnfDelayedMVarIssue.lean | 76efdb0389cb21d8205d6092ba837bb44ee8937a | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 224 | lean | def Nat.isZero (n : Nat) :=
n == 0
def test (preDefs : Array (Array Nat)) : IO Unit := do
for preDefs in preDefs do
let preDef := preDefs[0]
if preDef.isZero then
pure ()
else
IO.println "error"
|
12e2899e1b5a612292d7514fe4896d7398459f2e | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Elab/Syntax.lean | 843924c043c66e1eedaa956470a22a7282e178ca | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 15,786 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Elab.Command
import Lean.Parser.Syntax
import Lean.Elab.Util
namespace Lean.Elab.Term
/-
Expand `optional «precedence»` where
«precedence» := leading_parser " : " >> precedenceParser -/
def expandOptPrecedence (stx : Syntax) : MacroM (Option Nat) :=
if stx.isNone then
return none
else
return some (← evalPrec stx[0][1])
private def mkParserSeq (ds : Array Syntax) : TermElabM Syntax := do
if ds.size == 0 then
throwUnsupportedSyntax
else if ds.size == 1 then
pure ds[0]
else
let mut r := ds[0]
for d in ds[1:ds.size] do
r ← `(ParserDescr.binary `andthen $r $d)
return r
structure ToParserDescrContext where
catName : Name
first : Bool
leftRec : Bool -- true iff left recursion is allowed
/- See comment at `Parser.ParserCategory`. -/
behavior : Parser.LeadingIdentBehavior
abbrev ToParserDescrM := ReaderT ToParserDescrContext (StateRefT (Option Nat) TermElabM)
private def markAsTrailingParser (lhsPrec : Nat) : ToParserDescrM Unit := set (some lhsPrec)
@[inline] private def withNotFirst {α} (x : ToParserDescrM α) : ToParserDescrM α :=
withReader (fun ctx => { ctx with first := false }) x
@[inline] private def withNestedParser {α} (x : ToParserDescrM α) : ToParserDescrM α :=
withReader (fun ctx => { ctx with leftRec := false, first := false }) x
def checkLeftRec (stx : Syntax) : ToParserDescrM Bool := do
let ctx ← read
unless ctx.first && stx.getKind == ``Lean.Parser.Syntax.cat do
return false
let cat := stx[0].getId.eraseMacroScopes
unless cat == ctx.catName do
return false
let prec? ← liftMacroM <| expandOptPrecedence stx[1]
unless ctx.leftRec do
throwErrorAt stx[3] "invalid occurrence of '{cat}', parser algorithm does not allow this form of left recursion"
markAsTrailingParser (prec?.getD 0)
return true
/--
Given a `stx` of category `syntax`, return a pair `(newStx, lhsPrec?)`,
where `newStx` is of category `term`. After elaboration, `newStx` should have type
`TrailingParserDescr` if `lhsPrec?.isSome`, and `ParserDescr` otherwise. -/
partial def toParserDescr (stx : Syntax) (catName : Name) : TermElabM (Syntax × Option Nat) := do
let env ← getEnv
let behavior := Parser.leadingIdentBehavior env catName
(process stx { catName := catName, first := true, leftRec := true, behavior := behavior }).run none
where
process (stx : Syntax) : ToParserDescrM Syntax := withRef stx do
let kind := stx.getKind
if kind == nullKind then
processSeq stx
else if kind == choiceKind then
process stx[0]
else if kind == ``Lean.Parser.Syntax.paren then
process stx[1]
else if kind == ``Lean.Parser.Syntax.cat then
processNullaryOrCat stx
else if kind == ``Lean.Parser.Syntax.unary then
processUnary stx
else if kind == ``Lean.Parser.Syntax.binary then
processBinary stx
else if kind == ``Lean.Parser.Syntax.sepBy then
processSepBy stx
else if kind == ``Lean.Parser.Syntax.sepBy1 then
processSepBy1 stx
else if kind == ``Lean.Parser.Syntax.atom then
processAtom stx
else if kind == ``Lean.Parser.Syntax.nonReserved then
processNonReserved stx
else
let stxNew? ← liftM (liftMacroM (expandMacro? stx) : TermElabM _)
match stxNew? with
| some stxNew => process stxNew
| none => throwErrorAt stx "unexpected syntax kind of category `syntax`: {kind}"
/- Sequence (aka NullNode) -/
processSeq (stx : Syntax) := do
let args := stx.getArgs
if (← checkLeftRec stx[0]) then
if args.size == 1 then throwErrorAt stx "invalid atomic left recursive syntax"
let args := args.eraseIdx 0
let args ← args.mapM fun arg => withNestedParser do process arg
mkParserSeq args
else
let args ← args.mapIdxM fun i arg => withReader (fun ctx => { ctx with first := ctx.first && i.val == 0 }) do process arg
mkParserSeq args
/- Resolve the given parser name and return a list of candidates.
Each candidate is a pair `(resolvedParserName, isDescr)`.
`isDescr == true` if the type of `resolvedParserName` is a `ParserDescr`. -/
resolveParserName (parserName : Syntax) : ToParserDescrM (List (Name × Bool)) := do
try
let candidates ← resolveGlobalConstWithInfos parserName
/- Convert `candidates` in a list of pairs `(c, isDescr)`, where `c` is the parser name,
and `isDescr` is true iff `c` has type `Lean.ParserDescr` or `Lean.TrailingParser` -/
let env ← getEnv
candidates.filterMap fun c =>
match env.find? c with
| none => none
| some info =>
match info.type with
| Expr.const ``Lean.Parser.TrailingParser _ _ => (c, false)
| Expr.const ``Lean.Parser.Parser _ _ => (c, false)
| Expr.const ``Lean.ParserDescr _ _ => (c, true)
| Expr.const ``Lean.TrailingParserDescr _ _ => (c, true)
| _ => none
catch _ => return []
ensureNoPrec (stx : Syntax) :=
unless stx[1].isNone do
throwErrorAt stx[1] "unexpected precedence"
processParserCategory (stx : Syntax) := do
let catName := stx[0].getId.eraseMacroScopes
if (← read).first && catName == (← read).catName then
throwErrorAt stx "invalid atomic left recursive syntax"
let prec? ← liftMacroM <| expandOptPrecedence stx[1]
let prec := prec?.getD 0
`(ParserDescr.cat $(quote catName) $(quote prec))
processNullaryOrCat (stx : Syntax) := do
match (← resolveParserName stx[0]) with
| [(c, true)] => ensureNoPrec stx; return mkIdentFrom stx c
| [(c, false)] => ensureNoPrec stx; `(ParserDescr.parser $(quote c))
| cs@(_ :: _ :: _) => throwError "ambiguous parser declaration {cs.map (·.1)}"
| [] =>
let id := stx[0].getId.eraseMacroScopes
if Parser.isParserCategory (← getEnv) id then
processParserCategory stx
else if (← Parser.isParserAlias id) then
ensureNoPrec stx
Parser.ensureConstantParserAlias id
`(ParserDescr.const $(quote id))
else
throwError "unknown parser declaration/category/alias '{id}'"
processUnary (stx : Syntax) := do
let aliasName := (stx[0].getId).eraseMacroScopes
Parser.ensureUnaryParserAlias aliasName
let d ← withNestedParser do process stx[2]
`(ParserDescr.unary $(quote aliasName) $d)
processBinary (stx : Syntax) := do
let aliasName := (stx[0].getId).eraseMacroScopes
Parser.ensureBinaryParserAlias aliasName
let d₁ ← withNestedParser do process stx[2]
let d₂ ← withNestedParser do process stx[4]
`(ParserDescr.binary $(quote aliasName) $d₁ $d₂)
processSepBy (stx : Syntax) := do
let p ← withNestedParser $ process stx[1]
let sep := stx[3]
let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else process stx[4][1]
let allowTrailingSep := !stx[5].isNone
`(ParserDescr.sepBy $p $sep $psep $(quote allowTrailingSep))
processSepBy1 (stx : Syntax) := do
let p ← withNestedParser do process stx[1]
let sep := stx[3]
let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else process stx[4][1]
let allowTrailingSep := !stx[5].isNone
`(ParserDescr.sepBy1 $p $sep $psep $(quote allowTrailingSep))
isValidAtom (s : String) : Bool :=
!s.isEmpty &&
s[0] != '\'' &&
s[0] != '\"' &&
!(s[0] == '`' && (s.bsize == 1 || isIdFirst s[1] || isIdBeginEscape s[1])) &&
!s[0].isDigit
processAtom (stx : Syntax) := do
match stx[0].isStrLit? with
| some atom =>
unless isValidAtom atom do
throwErrorAt stx "invalid atom"
/- For syntax categories where initialized with `LeadingIdentBehavior` different from default (e.g., `tactic`), we automatically mark
the first symbol as nonReserved. -/
if (← read).behavior != Parser.LeadingIdentBehavior.default && (← read).first then
`(ParserDescr.nonReservedSymbol $(quote atom) false)
else
`(ParserDescr.symbol $(quote atom))
| none => throwUnsupportedSyntax
processNonReserved (stx : Syntax) := do
match stx[1].isStrLit? with
| some atom => `(ParserDescr.nonReservedSymbol $(quote atom) false)
| none => throwUnsupportedSyntax
end Term
namespace Command
open Lean.Syntax
open Lean.Parser.Term hiding macroArg
open Lean.Parser.Command
private def declareSyntaxCatQuotParser (catName : Name) : CommandElabM Unit := do
if let Name.str _ suffix _ := catName then
let quotSymbol := "`(" ++ suffix ++ "|"
let name := catName ++ `quot
-- TODO(Sebastian): this might confuse the pretty printer, but it lets us reuse the elaborator
let kind := ``Lean.Parser.Term.quot
let cmd ← `(
@[termParser] def $(mkIdent name) : Lean.ParserDescr :=
Lean.ParserDescr.node $(quote kind) $(quote Lean.Parser.maxPrec)
(Lean.ParserDescr.binary `andthen (Lean.ParserDescr.symbol $(quote quotSymbol))
(Lean.ParserDescr.binary `andthen
(Lean.ParserDescr.unary `incQuotDepth (Lean.ParserDescr.cat $(quote catName) 0))
(Lean.ParserDescr.symbol ")"))))
elabCommand cmd
@[builtinCommandElab syntaxCat] def elabDeclareSyntaxCat : CommandElab := fun stx => do
let catName := stx[1].getId
let catBehavior :=
if stx[2].isNone then
Parser.LeadingIdentBehavior.default
else if stx[2][3].getKind == ``Parser.Command.catBehaviorBoth then
Parser.LeadingIdentBehavior.both
else
Parser.LeadingIdentBehavior.symbol
let attrName := catName.appendAfter "Parser"
let env ← getEnv
let env ← Parser.registerParserCategory env attrName catName catBehavior
setEnv env
declareSyntaxCatQuotParser catName
/--
Auxiliary function for creating declaration names from parser descriptions.
Example:
Given
```
syntax term "+" term : term
syntax "[" sepBy(term, ", ") "]" : term
```
It generates the names `term_+_` and `term[_,]`
-/
partial def mkNameFromParserSyntax (catName : Name) (stx : Syntax) : MacroM Name := do
mkUnusedBaseName <| Name.mkSimple <| appendCatName <| visit stx ""
where
visit (stx : Syntax) (acc : String) : String :=
match stx.isStrLit? with
| some val => acc ++ (val.trim.map fun c => if c.isWhitespace then '_' else c).capitalize
| none =>
match stx with
| Syntax.node _ k args =>
if k == ``Lean.Parser.Syntax.cat then
acc ++ "_"
else
args.foldl (init := acc) fun acc arg => visit arg acc
| Syntax.ident .. => acc
| Syntax.atom .. => acc
| Syntax.missing => acc
appendCatName (str : String) :=
match catName with
| Name.str _ s _ => s ++ str
| _ => str
/- We assume a new syntax can be treated as an atom when it starts and ends with a token.
Here are examples of atom-like syntax.
```
syntax "(" term ")" : term
syntax "[" (sepBy term ",") "]" : term
syntax "foo" : term
```
-/
private partial def isAtomLikeSyntax (stx : Syntax) : Bool :=
let kind := stx.getKind
if kind == nullKind then
isAtomLikeSyntax stx[0] && isAtomLikeSyntax stx[stx.getNumArgs - 1]
else if kind == choiceKind then
isAtomLikeSyntax stx[0] -- see toParserDescr
else if kind == ``Lean.Parser.Syntax.paren then
isAtomLikeSyntax stx[1]
else
kind == ``Lean.Parser.Syntax.atom
def resolveSyntaxKind (k : Name) : CommandElabM Name := do
checkSyntaxNodeKindAtNamespaces k (← getCurrNamespace)
<|>
throwError "invalid syntax node kind '{k}'"
@[builtinCommandElab «syntax»] def elabSyntax : CommandElab := fun stx => do
let `($[$doc?:docComment]? $attrKind:attrKind syntax $[: $prec? ]? $[(name := $name?)]? $[(priority := $prio?)]? $[$ps:stx]* : $catStx) ← pure stx
| throwUnsupportedSyntax
let cat := catStx.getId.eraseMacroScopes
unless (Parser.isParserCategory (← getEnv) cat) do
throwErrorAt catStx "unknown category '{cat}'"
let syntaxParser := mkNullNode ps
-- If the user did not provide an explicit precedence, we assign `maxPrec` to atom-like syntax and `leadPrec` otherwise.
let precDefault := if isAtomLikeSyntax syntaxParser then Parser.maxPrec else Parser.leadPrec
let prec ← match prec? with
| some prec => liftMacroM <| evalPrec prec
| none => precDefault
let name ← match name? with
| some name => pure name.getId
| none => liftMacroM <| mkNameFromParserSyntax cat syntaxParser
let prio ← liftMacroM <| evalOptPrio prio?
let stxNodeKind := (← getCurrNamespace) ++ name
let catParserId := mkIdentFrom stx (cat.appendAfter "Parser")
let (val, lhsPrec?) ← runTermElabM none fun _ => Term.toParserDescr syntaxParser cat
let declName := mkIdentFrom stx name
let d ←
if let some lhsPrec := lhsPrec? then
`($[$doc?:docComment]? @[$attrKind:attrKind $catParserId:ident $(quote prio):numLit] def $declName:ident : Lean.TrailingParserDescr :=
ParserDescr.trailingNode $(quote stxNodeKind) $(quote prec) $(quote lhsPrec) $val)
else
`($[$doc?:docComment]? @[$attrKind:attrKind $catParserId:ident $(quote prio):numLit] def $declName:ident : Lean.ParserDescr :=
ParserDescr.node $(quote stxNodeKind) $(quote prec) $val)
trace `Elab fun _ => d
withMacroExpansion stx d <| elabCommand d
@[builtinCommandElab «syntaxAbbrev»] def elabSyntaxAbbrev : CommandElab := fun stx => do
let `($[$doc?:docComment]? syntax $declName:ident := $[$ps:stx]*) ← pure stx | throwUnsupportedSyntax
-- TODO: nonatomic names
let (val, _) ← runTermElabM none $ fun _ => Term.toParserDescr (mkNullNode ps) Name.anonymous
let stxNodeKind := (← getCurrNamespace) ++ declName.getId
let stx' ← `($[$doc?:docComment]? def $declName:ident : Lean.ParserDescr := ParserDescr.nodeWithAntiquot $(quote (toString declName.getId)) $(quote stxNodeKind) $val)
withMacroExpansion stx stx' $ elabCommand stx'
def checkRuleKind (given expected : SyntaxNodeKind) : Bool :=
given == expected || given == expected ++ `antiquot
def inferMacroRulesAltKind : Syntax → CommandElabM SyntaxNodeKind
| `(matchAltExpr| | $pat:term => $rhs) => do
if !pat.isQuot then
throwUnsupportedSyntax
let quoted := getQuotContent pat
pure quoted.getKind
| _ => throwUnsupportedSyntax
/--
Infer syntax kind `k` from first pattern, put alternatives of same kind into new `macro/elab_rules (kind := k)` via `mkCmd (some k)`,
leave remaining alternatives (via `mkCmd none`) to be recursively expanded. -/
def expandNoKindMacroRulesAux (alts : Array Syntax) (cmdName : String) (mkCmd : Option Name → Array Syntax → CommandElabM Syntax) : CommandElabM Syntax := do
let mut k ← inferMacroRulesAltKind alts[0]
if k.isStr && k.getString! == "antiquot" then
k := k.getPrefix
if k == choiceKind then
throwErrorAt alts[0]
"invalid {cmdName} alternative, multiple interpretations for pattern (solution: specify node kind using `{cmdName} (kind := ...) ...`)"
else
let altsK ← alts.filterM fun alt => return checkRuleKind (← inferMacroRulesAltKind alt) k
let altsNotK ← alts.filterM fun alt => return !checkRuleKind (← inferMacroRulesAltKind alt) k
if altsNotK.isEmpty then
mkCmd k altsK
else
mkNullNode #[← mkCmd k altsK, ← mkCmd none altsNotK]
def strLitToPattern (stx: Syntax) : MacroM Syntax :=
match stx.isStrLit? with
| some str => pure $ mkAtomFrom stx str
| none => Macro.throwUnsupported
builtin_initialize
registerTraceClass `Elab.syntax
end Lean.Elab.Command
|
9ac69a7253e4c511142f2489d770b2d4396010e9 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/data/list/cycle.lean | 36d6cde41b0b6dabf76f86369550f1682299be12 | [
"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 | 22,705 | lean | /-
Copyright (c) 2021 Yakov Pechersky. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yakov Pechersky
-/
import data.list.rotate
import data.finset.basic
import data.fintype.list
/-!
# Cycles of a list
Lists have an equivalence relation of whether they are rotational permutations of one another.
This relation is defined as `is_rotated`.
Based on this, we define the quotient of lists by the rotation relation, called `cycle`.
-/
namespace list
variables {α : Type*} [decidable_eq α]
/-- Return the `z` such that `x :: z :: _` appears in `xs`, or `default` if there is no such `z`. -/
def next_or : Π (xs : list α) (x default : α), α
| [] x default := default
| [y] x default := default -- Handles the not-found and the wraparound case
| (y :: z :: xs) x default := if x = y then z else next_or (z :: xs) x default
@[simp] lemma next_or_nil (x d : α) : next_or [] x d = d := rfl
@[simp] lemma next_or_singleton (x y d : α) : next_or [y] x d = d := rfl
@[simp] lemma next_or_self_cons_cons (xs : list α) (x y d : α) :
next_or (x :: y :: xs) x d = y :=
if_pos rfl
lemma next_or_cons_of_ne (xs : list α) (y x d : α) (h : x ≠ y) :
next_or (y :: xs) x d = next_or xs x d :=
begin
cases xs with z zs,
{ refl },
{ exact if_neg h }
end
/-- `next_or` does not depend on the default value, if the next value appears. -/
lemma next_or_eq_next_or_of_mem_of_ne (xs : list α) (x d d' : α)
(x_mem : x ∈ xs) (x_ne : x ≠ xs.last (ne_nil_of_mem x_mem)) :
next_or xs x d = next_or xs x d' :=
begin
induction xs with y ys IH,
{ cases x_mem },
cases ys with z zs,
{ simp at x_mem x_ne, contradiction },
by_cases h : x = y,
{ rw [h, next_or_self_cons_cons, next_or_self_cons_cons] },
{ rw [next_or, next_or, IH];
simpa [h] using x_mem }
end
lemma mem_of_next_or_ne {xs : list α} {x d : α} (h : next_or xs x d ≠ d) :
x ∈ xs :=
begin
induction xs with y ys IH,
{ simpa using h },
cases ys with z zs,
{ simpa using h },
{ by_cases hx : x = y,
{ simp [hx] },
{ rw [next_or_cons_of_ne _ _ _ _ hx] at h,
simpa [hx] using IH h } }
end
lemma next_or_concat {xs : list α} {x : α} (d : α) (h : x ∉ xs) :
next_or (xs ++ [x]) x d = d :=
begin
induction xs with z zs IH,
{ simp },
{ obtain ⟨hz, hzs⟩ := not_or_distrib.mp (mt (mem_cons_iff _ _ _).mp h),
rw [cons_append, next_or_cons_of_ne _ _ _ _ hz, IH hzs] }
end
lemma next_or_mem {xs : list α} {x d : α} (hd : d ∈ xs) :
next_or xs x d ∈ xs :=
begin
revert hd,
suffices : ∀ (xs' : list α) (h : ∀ x ∈ xs, x ∈ xs') (hd : d ∈ xs'), next_or xs x d ∈ xs',
{ exact this xs (λ _, id) },
intros xs' hxs' hd,
induction xs with y ys ih,
{ exact hd },
cases ys with z zs,
{ exact hd },
rw next_or,
split_ifs with h,
{ exact hxs' _ (mem_cons_of_mem _ (mem_cons_self _ _)) },
{ exact ih (λ _ h, hxs' _ (mem_cons_of_mem _ h)) },
end
/--
Given an element `x : α` of `l : list α` such that `x ∈ l`, get the next
element of `l`. This works from head to tail, (including a check for last element)
so it will match on first hit, ignoring later duplicates.
For example:
* `next [1, 2, 3] 2 _ = 3`
* `next [1, 2, 3] 3 _ = 1`
* `next [1, 2, 3, 2, 4] 2 _ = 3`
* `next [1, 2, 3, 2] 2 _ = 3`
* `next [1, 1, 2, 3, 2] 1 _ = 1`
-/
def next (l : list α) (x : α) (h : x ∈ l) : α :=
next_or l x (l.nth_le 0 (length_pos_of_mem h))
/--
Given an element `x : α` of `l : list α` such that `x ∈ l`, get the previous
element of `l`. This works from head to tail, (including a check for last element)
so it will match on first hit, ignoring later duplicates.
* `prev [1, 2, 3] 2 _ = 1`
* `prev [1, 2, 3] 1 _ = 3`
* `prev [1, 2, 3, 2, 4] 2 _ = 1`
* `prev [1, 2, 3, 4, 2] 2 _ = 1`
* `prev [1, 1, 2] 1 _ = 2`
-/
def prev : Π (l : list α) (x : α) (h : x ∈ l), α
| [] _ h := by simpa using h
| [y] _ _ := y
| (y :: z :: xs) x h := if hx : x = y then (last (z :: xs) (cons_ne_nil _ _)) else
if x = z then y else prev (z :: xs) x (by simpa [hx] using h)
variables (l : list α) (x : α) (h : x ∈ l)
@[simp] lemma next_singleton (x y : α) (h : x ∈ [y]) :
next [y] x h = y := rfl
@[simp] lemma prev_singleton (x y : α) (h : x ∈ [y]) :
prev [y] x h = y := rfl
lemma next_cons_cons_eq' (y z : α) (h : x ∈ (y :: z :: l)) (hx : x = y) :
next (y :: z :: l) x h = z :=
by rw [next, next_or, if_pos hx]
@[simp] lemma next_cons_cons_eq (z : α) (h : x ∈ (x :: z :: l)) :
next (x :: z :: l) x h = z :=
next_cons_cons_eq' l x x z h rfl
lemma next_ne_head_ne_last (y : α) (h : x ∈ (y :: l)) (hy : x ≠ y)
(hx : x ≠ last (y :: l) (cons_ne_nil _ _)) :
next (y :: l) x h = next l x (by simpa [hy] using h) :=
begin
rw [next, next, next_or_cons_of_ne _ _ _ _ hy, next_or_eq_next_or_of_mem_of_ne],
{ rwa last_cons at hx },
{ simpa [hy] using h }
end
lemma next_cons_concat (y : α) (hy : x ≠ y) (hx : x ∉ l)
(h : x ∈ y :: l ++ [x] := mem_append_right _ (mem_singleton_self x)) :
next (y :: l ++ [x]) x h = y :=
begin
rw [next, next_or_concat],
{ refl },
{ simp [hy, hx] }
end
lemma next_last_cons (y : α) (h : x ∈ (y :: l)) (hy : x ≠ y)
(hx : x = last (y :: l) (cons_ne_nil _ _)) (hl : nodup l) :
next (y :: l) x h = y :=
begin
rw [next, nth_le, ←init_append_last (cons_ne_nil y l), hx, next_or_concat],
subst hx,
intro H,
obtain ⟨_ | k, hk, hk'⟩ := nth_le_of_mem H,
{ simpa [init_eq_take, nth_le_take', hy.symm] using hk' },
suffices : k.succ = l.length,
{ simpa [this] using hk },
cases l with hd tl,
{ simpa using hk },
{ rw nodup_iff_nth_le_inj at hl,
rw [length, nat.succ_inj'],
apply hl,
simpa [init_eq_take, nth_le_take', last_eq_nth_le] using hk' }
end
lemma prev_last_cons' (y : α) (h : x ∈ (y :: l)) (hx : x = y) :
prev (y :: l) x h = last (y :: l) (cons_ne_nil _ _) :=
begin
cases l;
simp [prev, hx]
end
@[simp] lemma prev_last_cons (h : x ∈ (x :: l)) :
prev (x :: l) x h = last (x :: l) (cons_ne_nil _ _) :=
prev_last_cons' l x x h rfl
lemma prev_cons_cons_eq' (y z : α) (h : x ∈ (y :: z :: l)) (hx : x = y) :
prev (y :: z :: l) x h = last (z :: l) (cons_ne_nil _ _) :=
by rw [prev, dif_pos hx]
@[simp] lemma prev_cons_cons_eq (z : α) (h : x ∈ (x :: z :: l)) :
prev (x :: z :: l) x h = last (z :: l) (cons_ne_nil _ _) :=
prev_cons_cons_eq' l x x z h rfl
lemma prev_cons_cons_of_ne' (y z : α) (h : x ∈ (y :: z :: l)) (hy : x ≠ y) (hz : x = z) :
prev (y :: z :: l) x h = y :=
begin
cases l,
{ simp [prev, hy, hz] },
{ rw [prev, dif_neg hy, if_pos hz] }
end
lemma prev_cons_cons_of_ne (y : α) (h : x ∈ (y :: x :: l)) (hy : x ≠ y) :
prev (y :: x :: l) x h = y :=
prev_cons_cons_of_ne' _ _ _ _ _ hy rfl
lemma prev_ne_cons_cons (y z : α) (h : x ∈ (y :: z :: l)) (hy : x ≠ y) (hz : x ≠ z) :
prev (y :: z :: l) x h = prev (z :: l) x (by simpa [hy] using h) :=
begin
cases l,
{ simpa [hy, hz] using h },
{ rw [prev, dif_neg hy, if_neg hz] }
end
include h
lemma next_mem : l.next x h ∈ l :=
next_or_mem (nth_le_mem _ _ _)
lemma prev_mem : l.prev x h ∈ l :=
begin
cases l with hd tl,
{ simpa using h },
induction tl with hd' tl hl generalizing hd,
{ simp },
{ by_cases hx : x = hd,
{ simp only [hx, prev_cons_cons_eq],
exact mem_cons_of_mem _ (last_mem _) },
{ rw [prev, dif_neg hx],
split_ifs with hm,
{ exact mem_cons_self _ _ },
{ exact mem_cons_of_mem _ (hl _ _) } } }
end
lemma next_nth_le (l : list α) (h : nodup l) (n : ℕ) (hn : n < l.length) :
next l (l.nth_le n hn) (nth_le_mem _ _ _) = l.nth_le ((n + 1) % l.length)
(nat.mod_lt _ (n.zero_le.trans_lt hn)) :=
begin
cases l with x l,
{ simpa using hn },
induction l with y l hl generalizing x n,
{ simp },
{ cases n,
{ simp },
{ have hn' : n.succ ≤ l.length.succ,
{ refine nat.succ_le_of_lt _,
simpa [nat.succ_lt_succ_iff] using hn },
have hx': (x :: y :: l).nth_le n.succ hn ≠ x,
{ intro H,
suffices : n.succ = 0,
{ simpa },
rw nodup_iff_nth_le_inj at h,
refine h _ _ hn nat.succ_pos' _,
simpa using H },
rcases hn'.eq_or_lt with hn''|hn'',
{ rw [next_last_cons],
{ simp [hn''] },
{ exact hx' },
{ simp [last_eq_nth_le, hn''] },
{ exact nodup_of_nodup_cons h } },
{ have : n < l.length := by simpa [nat.succ_lt_succ_iff] using hn'' ,
rw [next_ne_head_ne_last _ _ _ _ hx'],
{ simp [nat.mod_eq_of_lt (nat.succ_lt_succ (nat.succ_lt_succ this)),
hl _ _ (nodup_of_nodup_cons h), nat.mod_eq_of_lt (nat.succ_lt_succ this)] },
{ rw last_eq_nth_le,
intro H,
suffices : n.succ = l.length.succ,
{ exact absurd hn'' this.ge.not_lt },
rw nodup_iff_nth_le_inj at h,
refine h _ _ hn _ _,
{ simp },
{ simpa using H } } } } }
end
lemma prev_nth_le (l : list α) (h : nodup l) (n : ℕ) (hn : n < l.length) :
prev l (l.nth_le n hn) (nth_le_mem _ _ _) = l.nth_le ((n + (l.length - 1)) % l.length)
(nat.mod_lt _ (n.zero_le.trans_lt hn)) :=
begin
cases l with x l,
{ simpa using hn },
induction l with y l hl generalizing n x,
{ simp },
{ rcases n with _|_|n,
{ simpa [last_eq_nth_le, nat.mod_eq_of_lt (nat.succ_lt_succ l.length.lt_succ_self)] },
{ simp only [mem_cons_iff, nodup_cons] at h,
push_neg at h,
simp [add_comm, prev_cons_cons_of_ne, h.left.left.symm] },
{ rw [prev_ne_cons_cons],
{ convert hl _ _ (nodup_of_nodup_cons h) _ using 1,
have : ∀ k hk, (y :: l).nth_le k hk = (x :: y :: l).nth_le (k + 1) (nat.succ_lt_succ hk),
{ intros,
simpa },
rw [this],
congr,
simp only [nat.add_succ_sub_one, add_zero, length],
simp only [length, nat.succ_lt_succ_iff] at hn,
set k := l.length,
rw [nat.succ_add, ←nat.add_succ, nat.add_mod_right, nat.succ_add, ←nat.add_succ _ k,
nat.add_mod_right, nat.mod_eq_of_lt, nat.mod_eq_of_lt],
{ exact nat.lt_succ_of_lt hn },
{ exact nat.succ_lt_succ (nat.lt_succ_of_lt hn) } },
{ intro H,
suffices : n.succ.succ = 0,
{ simpa },
rw nodup_iff_nth_le_inj at h,
refine h _ _ hn nat.succ_pos' _,
simpa using H },
{ intro H,
suffices : n.succ.succ = 1,
{ simpa },
rw nodup_iff_nth_le_inj at h,
refine h _ _ hn (nat.succ_lt_succ nat.succ_pos') _,
simpa using H } } }
end
lemma pmap_next_eq_rotate_one (h : nodup l) :
l.pmap l.next (λ _ h, h) = l.rotate 1 :=
begin
apply list.ext_le,
{ simp },
{ intros,
rw [nth_le_pmap, nth_le_rotate, next_nth_le _ h] }
end
lemma pmap_prev_eq_rotate_length_sub_one (h : nodup l) :
l.pmap l.prev (λ _ h, h) = l.rotate (l.length - 1) :=
begin
apply list.ext_le,
{ simp },
{ intros n hn hn',
rw [nth_le_rotate, nth_le_pmap, prev_nth_le _ h] }
end
lemma prev_next (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) :
prev l (next l x hx) (next_mem _ _ _) = x :=
begin
obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx,
simp only [next_nth_le, prev_nth_le, h, nat.mod_add_mod],
cases l with hd tl,
{ simp },
{ have : n < 1 + tl.length := by simpa [add_comm] using hn,
simp [add_left_comm, add_comm, add_assoc, nat.mod_eq_of_lt this] }
end
lemma next_prev (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) :
next l (prev l x hx) (prev_mem _ _ _) = x :=
begin
obtain ⟨n, hn, rfl⟩ := nth_le_of_mem hx,
simp only [next_nth_le, prev_nth_le, h, nat.mod_add_mod],
cases l with hd tl,
{ simp },
{ have : n < 1 + tl.length := by simpa [add_comm] using hn,
simp [add_left_comm, add_comm, add_assoc, nat.mod_eq_of_lt this] }
end
lemma prev_reverse_eq_next (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) :
prev l.reverse x (mem_reverse.mpr hx) = next l x hx :=
begin
obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx,
have lpos : 0 < l.length := k.zero_le.trans_lt hk,
have key : l.length - 1 - k < l.length :=
(nat.sub_le _ _).trans_lt (nat.sub_lt_self lpos nat.succ_pos'),
rw ←nth_le_pmap l.next (λ _ h, h) (by simpa using hk),
simp_rw [←nth_le_reverse l k (key.trans_le (by simp)), pmap_next_eq_rotate_one _ h],
rw ←nth_le_pmap l.reverse.prev (λ _ h, h),
{ simp_rw [pmap_prev_eq_rotate_length_sub_one _ (nodup_reverse.mpr h), rotate_reverse,
length_reverse, nat.mod_eq_of_lt (nat.sub_lt_self lpos nat.succ_pos'),
nat.sub_sub_self (nat.succ_le_of_lt lpos)],
rw ←nth_le_reverse,
{ simp [nat.sub_sub_self (nat.le_pred_of_lt hk)] },
{ simpa using (nat.sub_le _ _).trans_lt (nat.sub_lt_self lpos nat.succ_pos') } },
{ simpa using (nat.sub_le _ _).trans_lt (nat.sub_lt_self lpos nat.succ_pos') }
end
lemma next_reverse_eq_prev (l : list α) (h : nodup l) (x : α) (hx : x ∈ l) :
next l.reverse x (mem_reverse.mpr hx) = prev l x hx :=
begin
convert (prev_reverse_eq_next l.reverse (nodup_reverse.mpr h) x (mem_reverse.mpr hx)).symm,
exact (reverse_reverse l).symm
end
lemma is_rotated_next_eq {l l' : list α} (h : l ~r l') (hn : nodup l) {x : α} (hx : x ∈ l) :
l.next x hx = l'.next x (h.mem_iff.mp hx) :=
begin
obtain ⟨k, hk, rfl⟩ := nth_le_of_mem hx,
obtain ⟨n, rfl⟩ := id h,
rw [next_nth_le _ hn],
simp_rw ←nth_le_rotate' _ n k,
rw [next_nth_le _ (h.nodup_iff.mp hn), ←nth_le_rotate' _ n],
simp [add_assoc]
end
lemma is_rotated_prev_eq {l l' : list α} (h : l ~r l') (hn : nodup l) {x : α} (hx : x ∈ l) :
l.prev x hx = l'.prev x (h.mem_iff.mp hx) :=
begin
rw [←next_reverse_eq_prev _ hn, ←next_reverse_eq_prev _ (h.nodup_iff.mp hn)],
exact is_rotated_next_eq h.reverse (nodup_reverse.mpr hn) _
end
end list
open list
/--
`cycle α` is the quotient of `list α` by cyclic permutation.
Duplicates are allowed.
-/
def cycle (α : Type*) : Type* := quotient (is_rotated.setoid α)
namespace cycle
variables {α : Type*}
instance : has_coe (list α) (cycle α) := ⟨quot.mk _⟩
@[simp] lemma coe_eq_coe {l₁ l₂ : list α} : (l₁ : cycle α) = l₂ ↔ (l₁ ~r l₂) :=
@quotient.eq _ (is_rotated.setoid _) _ _
@[simp] lemma mk_eq_coe (l : list α) :
quot.mk _ l = (l : cycle α) := rfl
@[simp] lemma mk'_eq_coe (l : list α) :
quotient.mk' l = (l : cycle α) := rfl
instance : inhabited (cycle α) := ⟨(([] : list α) : cycle α)⟩
/--
For `x : α`, `s : cycle α`, `x ∈ s` indicates that `x` occurs at least once in `s`.
-/
def mem (a : α) (s : cycle α) : Prop :=
quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~r l₂), propext $ e.mem_iff)
instance : has_mem α (cycle α) := ⟨mem⟩
@[simp] lemma mem_coe_iff {a : α} {l : list α} :
a ∈ (l : cycle α) ↔ a ∈ l := iff.rfl
instance [decidable_eq α] : decidable_eq (cycle α) :=
λ s₁ s₂, quotient.rec_on_subsingleton₂' s₁ s₂ (λ l₁ l₂,
decidable_of_iff' _ quotient.eq')
instance [decidable_eq α] (x : α) (s : cycle α) : decidable (x ∈ s) :=
quotient.rec_on_subsingleton' s (λ l, list.decidable_mem x l)
/--
Reverse a `s : cycle α` by reversing the underlying `list`.
-/
def reverse (s : cycle α) : cycle α :=
quot.map reverse (λ l₁ l₂ (e : l₁ ~r l₂), e.reverse) s
@[simp] lemma reverse_coe (l : list α) :
(l : cycle α).reverse = l.reverse := rfl
@[simp] lemma mem_reverse_iff {a : α} {s : cycle α} :
a ∈ s.reverse ↔ a ∈ s :=
quot.induction_on s (λ _, mem_reverse)
@[simp] lemma reverse_reverse (s : cycle α) :
s.reverse.reverse = s :=
quot.induction_on s (λ _, by simp)
/--
The length of the `s : cycle α`, which is the number of elements, counting duplicates.
-/
def length (s : cycle α) : ℕ :=
quot.lift_on s length (λ l₁ l₂ (e : l₁ ~r l₂), e.perm.length_eq)
@[simp] lemma length_coe (l : list α) :
length (l : cycle α) = l.length := rfl
@[simp] lemma length_reverse (s : cycle α) :
s.reverse.length = s.length :=
quot.induction_on s length_reverse
/--
A `s : cycle α` that is at most one element.
-/
def subsingleton (s : cycle α) : Prop :=
s.length ≤ 1
lemma length_subsingleton_iff {s : cycle α} :
subsingleton s ↔ length s ≤ 1 := iff.rfl
@[simp] lemma subsingleton_reverse_iff {s : cycle α} :
s.reverse.subsingleton ↔ s.subsingleton :=
by simp [length_subsingleton_iff]
lemma subsingleton.congr {s : cycle α} (h : subsingleton s) :
∀ ⦃x⦄ (hx : x ∈ s) ⦃y⦄ (hy : y ∈ s), x = y :=
begin
induction s using quot.induction_on with l,
simp only [length_subsingleton_iff, length_coe, mk_eq_coe, le_iff_lt_or_eq, nat.lt_add_one_iff,
length_eq_zero, length_eq_one, nat.not_lt_zero, false_or] at h,
rcases h with rfl|⟨z, rfl⟩;
simp
end
/--
A `s : cycle α` that is made up of at least two unique elements.
-/
def nontrivial (s : cycle α) : Prop := ∃ (x y : α) (h : x ≠ y), x ∈ s ∧ y ∈ s
@[simp] lemma nontrivial_coe_nodup_iff {l : list α} (hl : l.nodup) :
nontrivial (l : cycle α) ↔ 2 ≤ l.length :=
begin
rw nontrivial,
rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩),
{ simp },
{ simp },
{ simp only [mem_cons_iff, exists_prop, mem_coe_iff, list.length, ne.def, nat.succ_le_succ_iff,
zero_le, iff_true],
refine ⟨hd, hd', _, by simp⟩,
simp only [not_or_distrib, mem_cons_iff, nodup_cons] at hl,
exact hl.left.left }
end
@[simp] lemma nontrivial_reverse_iff {s : cycle α} :
s.reverse.nontrivial ↔ s.nontrivial :=
by simp [nontrivial]
lemma length_nontrivial {s : cycle α} (h : nontrivial s) :
2 ≤ length s :=
begin
obtain ⟨x, y, hxy, hx, hy⟩ := h,
induction s using quot.induction_on with l,
rcases l with (_ | ⟨hd, _ | ⟨hd', tl⟩⟩),
{ simpa using hx },
{ simp only [mem_coe_iff, mk_eq_coe, mem_singleton] at hx hy,
simpa [hx, hy] using hxy },
{ simp [bit0] }
end
/--
The `s : cycle α` contains no duplicates.
-/
def nodup (s : cycle α) : Prop :=
quot.lift_on s nodup (λ l₁ l₂ (e : l₁ ~r l₂), propext $ e.nodup_iff)
@[simp] lemma nodup_coe_iff {l : list α} :
nodup (l : cycle α) ↔ l.nodup := iff.rfl
@[simp] lemma nodup_reverse_iff {s : cycle α} :
s.reverse.nodup ↔ s.nodup :=
quot.induction_on s (λ _, nodup_reverse)
lemma subsingleton.nodup {s : cycle α} (h : subsingleton s) :
nodup s :=
begin
induction s using quot.induction_on with l,
cases l with hd tl,
{ simp },
{ have : tl = [] := by simpa [subsingleton, length_eq_zero] using h,
simp [this] }
end
lemma nodup.nontrivial_iff {s : cycle α} (h : nodup s) :
nontrivial s ↔ ¬ subsingleton s :=
begin
rw length_subsingleton_iff,
induction s using quotient.induction_on',
simp only [mk'_eq_coe, nodup_coe_iff] at h,
simp [h, nat.succ_le_iff]
end
/--
The `s : cycle α` as a `multiset α`.
-/
def to_multiset (s : cycle α) : multiset α :=
quotient.lift_on' s (λ l, (l : multiset α)) (λ l₁ l₂ (h : l₁ ~r l₂), multiset.coe_eq_coe.mpr h.perm)
section decidable
variable [decidable_eq α]
/--
Auxiliary decidability algorithm for lists that contain at least two unique elements.
-/
def decidable_nontrivial_coe : Π (l : list α), decidable (nontrivial (l : cycle α))
| [] := is_false (by simp [nontrivial])
| [x] := is_false (by simp [nontrivial])
| (x :: y :: l) := if h : x = y
then @decidable_of_iff' _ (nontrivial ((x :: l) : cycle α))
(by simp [h, nontrivial])
(decidable_nontrivial_coe (x :: l))
else is_true ⟨x, y, h, by simp, by simp⟩
instance {s : cycle α} : decidable (nontrivial s) :=
quot.rec_on_subsingleton s decidable_nontrivial_coe
instance {s : cycle α} : decidable (nodup s) :=
quot.rec_on_subsingleton s (λ (l : list α), list.nodup_decidable l)
instance fintype_nodup_cycle [fintype α] : fintype {s : cycle α // s.nodup} :=
fintype.of_surjective (λ (l : {l : list α // l.nodup}), ⟨l.val, by simpa using l.prop⟩) (λ ⟨s, hs⟩,
begin
induction s using quotient.induction_on',
exact ⟨⟨s, hs⟩, by simp⟩
end)
instance fintype_nodup_nontrivial_cycle [fintype α] :
fintype {s : cycle α // s.nodup ∧ s.nontrivial} :=
fintype.subtype (((finset.univ : finset {s : cycle α // s.nodup}).map
(function.embedding.subtype _)).filter cycle.nontrivial)
(by simp)
/--
The `s : cycle α` as a `finset α`.
-/
def to_finset (s : cycle α) : finset α :=
s.to_multiset.to_finset
/-- Given a `s : cycle α` such that `nodup s`, retrieve the next element after `x ∈ s`. -/
def next : Π (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s), α :=
λ s, quot.hrec_on s (λ l hn x hx, next l x hx)
(λ l₁ l₂ (h : l₁ ~r l₂),
function.hfunext (propext h.nodup_iff) (λ h₁ h₂ he, function.hfunext rfl
(λ x y hxy, function.hfunext (propext (by simpa [eq_of_heq hxy] using h.mem_iff))
(λ hm hm' he', heq_of_eq (by simpa [eq_of_heq hxy] using is_rotated_next_eq h h₁ _)))))
/-- Given a `s : cycle α` such that `nodup s`, retrieve the previous element before `x ∈ s`. -/
def prev : Π (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s), α :=
λ s, quot.hrec_on s (λ l hn x hx, prev l x hx)
(λ l₁ l₂ (h : l₁ ~r l₂),
function.hfunext (propext h.nodup_iff) (λ h₁ h₂ he, function.hfunext rfl
(λ x y hxy, function.hfunext (propext (by simpa [eq_of_heq hxy] using h.mem_iff))
(λ hm hm' he', heq_of_eq (by simpa [eq_of_heq hxy] using is_rotated_prev_eq h h₁ _)))))
@[simp] lemma prev_reverse_eq_next (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) :
s.reverse.prev (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.next hs x hx :=
(quotient.induction_on' s prev_reverse_eq_next) hs x hx
@[simp] lemma next_reverse_eq_prev (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) :
s.reverse.next (nodup_reverse_iff.mpr hs) x (mem_reverse_iff.mpr hx) = s.prev hs x hx :=
by simp [←prev_reverse_eq_next]
@[simp] lemma next_mem (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) :
s.next hs x hx ∈ s :=
begin
induction s using quot.induction_on,
exact next_mem _ _ _
end
lemma prev_mem (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) :
s.prev hs x hx ∈ s :=
by { rw [←next_reverse_eq_prev, ←mem_reverse_iff], exact next_mem _ _ _ _ }
@[simp] lemma prev_next (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) :
s.prev hs (s.next hs x hx) (next_mem s hs x hx) = x :=
(quotient.induction_on' s prev_next) hs x hx
@[simp] lemma next_prev (s : cycle α) (hs : nodup s) (x : α) (hx : x ∈ s) :
s.next hs (s.prev hs x hx) (prev_mem s hs x hx) = x :=
(quotient.induction_on' s next_prev) hs x hx
end decidable
end cycle
|
f04ae3de73bd6e1b50a9644ab1207b09cd3e6ccf | 37da0369b6c03e380e057bf680d81e6c9fdf9219 | /hott/homotopy/cylinder.hlean | ac8778209049f459e80b7fcb79e486d62c6eb09c | [
"Apache-2.0"
] | permissive | kodyvajjha/lean2 | 72b120d95c3a1d77f54433fa90c9810e14a931a4 | 227fcad22ab2bc27bb7471be7911075d101ba3f9 | refs/heads/master | 1,627,157,512,295 | 1,501,855,676,000 | 1,504,809,427,000 | 109,317,326 | 0 | 0 | null | 1,509,839,253,000 | 1,509,655,713,000 | C++ | UTF-8 | Lean | false | false | 4,787 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn
Declaration of mapping cylinders
-/
import hit.quotient types.fiber
open quotient eq sum equiv fiber
namespace cylinder
section
parameters {A B : Type} (f : A → B)
local abbreviation C := B + A
inductive cylinder_rel : C → C → Type :=
| Rmk : Π(a : A), cylinder_rel (inl (f a)) (inr a)
open cylinder_rel
local abbreviation R := cylinder_rel
definition cylinder := quotient cylinder_rel -- TODO: define this in root namespace
parameter {f}
definition base (b : B) : cylinder :=
class_of R (inl b)
definition top (a : A) : cylinder :=
class_of R (inr a)
definition seg (a : A) : base (f a) = top a :=
eq_of_rel cylinder_rel (Rmk f a)
protected definition rec {P : cylinder → Type}
(Pbase : Π(b : B), P (base b)) (Ptop : Π(a : A), P (top a))
(Pseg : Π(a : A), Pbase (f a) =[seg a] Ptop a) (x : cylinder) : P x :=
begin
induction x,
{ cases a,
apply Pbase,
apply Ptop},
{ cases H, apply Pseg}
end
protected definition rec_on [reducible] {P : cylinder → Type} (x : cylinder)
(Pbase : Π(b : B), P (base b)) (Ptop : Π(a : A), P (top a))
(Pseg : Π(a : A), Pbase (f a) =[seg a] Ptop a) : P x :=
rec Pbase Ptop Pseg x
theorem rec_seg {P : cylinder → Type}
(Pbase : Π(b : B), P (base b)) (Ptop : Π(a : A), P (top a))
(Pseg : Π(a : A), Pbase (f a) =[seg a] Ptop a)
(a : A) : apd (rec Pbase Ptop Pseg) (seg a) = Pseg a :=
!rec_eq_of_rel
protected definition elim {P : Type} (Pbase : B → P) (Ptop : A → P)
(Pseg : Π(a : A), Pbase (f a) = Ptop a) (x : cylinder) : P :=
rec Pbase Ptop (λa, pathover_of_eq _ (Pseg a)) x
protected definition elim_on [reducible] {P : Type} (x : cylinder) (Pbase : B → P) (Ptop : A → P)
(Pseg : Π(a : A), Pbase (f a) = Ptop a) : P :=
elim Pbase Ptop Pseg x
theorem elim_seg {P : Type} (Pbase : B → P) (Ptop : A → P)
(Pseg : Π(a : A), Pbase (f a) = Ptop a)
(a : A) : ap (elim Pbase Ptop Pseg) (seg a) = Pseg a :=
begin
apply eq_of_fn_eq_fn_inv !(pathover_constant (seg a)),
rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑elim,rec_seg],
end
protected definition elim_type (Pbase : B → Type) (Ptop : A → Type)
(Pseg : Π(a : A), Pbase (f a) ≃ Ptop a) (x : cylinder) : Type :=
elim Pbase Ptop (λa, ua (Pseg a)) x
protected definition elim_type_on [reducible] (x : cylinder) (Pbase : B → Type) (Ptop : A → Type)
(Pseg : Π(a : A), Pbase (f a) ≃ Ptop a) : Type :=
elim_type Pbase Ptop Pseg x
theorem elim_type_seg (Pbase : B → Type) (Ptop : A → Type)
(Pseg : Π(a : A), Pbase (f a) ≃ Ptop a)
(a : A) : transport (elim_type Pbase Ptop Pseg) (seg a) = Pseg a :=
by rewrite [tr_eq_cast_ap_fn,↑elim_type,elim_seg];apply cast_ua_fn
end
end cylinder
attribute cylinder.base cylinder.top [constructor]
attribute cylinder.rec cylinder.elim [unfold 8] [recursor 8]
attribute cylinder.elim_type [unfold 7]
attribute cylinder.rec_on cylinder.elim_on [unfold 5]
attribute cylinder.elim_type_on [unfold 4]
namespace cylinder
open sigma sigma.ops
variables {A B : Type} (f : A → B)
/- cylinder as a dependent family -/
definition pr1 [unfold 4] : cylinder f → B :=
cylinder.elim id f (λa, idp)
definition fcylinder : B → Type := fiber (pr1 f)
definition cylinder_equiv_sigma_fcylinder [constructor] : cylinder f ≃ Σb, fcylinder f b :=
!sigma_fiber_equiv⁻¹ᵉ
variable {f}
definition fbase (b : B) : fcylinder f b :=
fiber.mk (base b) idp
definition ftop (a : A) : fcylinder f (f a) :=
fiber.mk (top a) idp
definition fseg (a : A) : fbase (f a) = ftop a :=
fiber_eq (seg a) !elim_seg⁻¹
-- TODO: define the induction principle for "fcylinder"
-- set_option pp.notation false
-- -- The induction principle for the dependent mapping cylinder (TODO)
-- protected definition frec {P : Π(b), fcylinder f b → Type}
-- (Pbase : Π(b : B), P _ (fbase b)) (Ptop : Π(a : A), P _ (ftop a))
-- (Pseg : Π(a : A), Pbase (f a) =[fseg a] Ptop a) {b : B} (x : fcylinder f b) : P _ x :=
-- begin
-- cases x with x p, induction p,
-- induction x: esimp,
-- { apply Pbase},
-- { apply Ptop},
-- { esimp, --fapply fiber_pathover,
-- --refine pathover_of_pathover_ap P (λx, fiber.mk x idp),
-- exact sorry}
-- end
-- theorem frec_fseg {P : Π(b), fcylinder f b → Type}
-- (Pbase : Π(b : B), P _ (fbase b)) (Ptop : Π(a : A), P _ (ftop a))
-- (Pseg : Π(a : A), Pbase (f a) =[fseg a] Ptop a) (a : A)
-- : apd (cylinder.frec Pbase Ptop Pseg) (fseg a) = Pseg a :=
-- sorry
end cylinder
|
580619fde02037d1630f5975a828cfb75ed3eeaa | acc85b4be2c618b11fc7cb3005521ae6858a8d07 | /analysis/measure_theory/measure_space.lean | d114387d3c9ca1a2ba056fdd71ff3275647d9250 | [
"Apache-2.0"
] | permissive | linpingchuan/mathlib | d49990b236574df2a45d9919ba43c923f693d341 | 5ad8020f67eb13896a41cc7691d072c9331b1f76 | refs/heads/master | 1,626,019,377,808 | 1,508,048,784,000 | 1,508,048,784,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 18,655 | 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
Measure spaces -- measures
Measures are restricted to a measurable space (associated by the type class `measurable_space`).
This allows us to prove equalities between measures by restricting to a generating set of the
measurable space.
On the other hand, the `μ.measure s` projection (i.e. the measure of `s` on the measure space `μ`)
is the _outer_ measure generated by `μ`. This gives us a unrestricted monotonicity rule and it is
somehow well-behaved on non-measurable sets.
This allows us for the `lebesgue` measure space to have the `borel` measurable space, but still be
a complete measure.
-/
import data.set order.galois_connection analysis.ennreal
analysis.measure_theory.outer_measure
noncomputable theory
open classical set lattice filter finset function
local attribute [instance] decidable_inhabited prop_decidable
universes u v w x
namespace measure_theory
structure measure_space (α : Type*) [m : measurable_space α] :=
(measure_of : Π(s : set α), is_measurable s → ennreal)
(measure_of_empty : measure_of ∅ is_measurable_empty = 0)
(measure_of_Union :
∀{f:ℕ → set α}, ∀h : ∀i, is_measurable (f i), pairwise (disjoint on f) →
measure_of (⋃i, f i) (is_measurable_Union h) = (∑i, measure_of (f i) (h i)))
namespace measure_space
variables {α : Type*} [measurable_space α] (μ : measure_space α) {s s₁ s₂ : set α}
/-- Measure projection which is ∞ for non-measurable sets.
`measure'` is mainly used to derive the outer measure, for the main `measure` projection. -/
protected def measure' (s : set α) : ennreal := ⨅ h : is_measurable s, μ.measure_of s h
protected lemma measure'_eq (h : is_measurable s) : μ.measure' s = μ.measure_of s h :=
by simp [measure_space.measure', h]
protected lemma measure'_empty : μ.measure' ∅ = 0 :=
by simp [μ.measure'_eq, measure_space.measure_of_empty, is_measurable_empty]
protected lemma measure'_Union {f : ℕ → set α}
(hd : pairwise (disjoint on f)) (hm : ∀i, is_measurable (f i)) :
μ.measure' (⋃i, f i) = (∑i, μ.measure' (f i)) :=
by simp [μ.measure'_eq, hm, is_measurable_Union hm] {contextual := tt};
from μ.measure_of_Union _ hd
protected lemma measure'_union {s₁ s₂ : set α}
(hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
μ.measure' (s₁ ∪ s₂) = μ.measure' s₁ + μ.measure' s₂ :=
let s := λn:ℕ, ([s₁, s₂].nth n).get_or_else ∅ in
have s0 : s 0 = s₁, from rfl,
have s1 : s 1 = s₂, from rfl,
have hd : pairwise (disjoint on s),
from assume i j h,
match i, j, h with
| 0, 0, h := (h rfl).elim
| 0, (nat.succ 0), h := hd
| (nat.succ 0), 0, h := show s₂ ⊓ s₁ = ⊥, by rw [inf_comm]; assumption
| (nat.succ 0), (nat.succ 0), h := (h rfl).elim
| (nat.succ (nat.succ i)), j, h :=
begin simp [s, disjoint, (on), option.get_or_else]; exact set.empty_inter _ end
| i, (nat.succ (nat.succ j)), h :=
begin simp [s, disjoint, (on), option.get_or_else]; exact set.inter_empty _ end
end,
have Un_s : (⋃n, s n) = s₁ ∪ s₂,
from subset.antisymm
(Union_subset $ assume n, match n with
| 0 := subset_union_left _ _
| 1 := subset_union_right _ _
| (nat.succ (nat.succ i)) := empty_subset _
end)
(union_subset (subset_Union s 0) (subset_Union s 1)),
have hms : ∀n, is_measurable (s n),
from assume n, match n with
| 0 := h₁
| 1 := h₂
| (nat.succ (nat.succ i)) := is_measurable_empty
end,
calc μ.measure' (s₁ ∪ s₂) = μ.measure' (⋃n, s n) : by rw [Un_s]
... = (∑n, μ.measure' (s n)) :
measure_space.measure'_Union μ hd hms
... = (range (nat.succ (nat.succ 0))).sum (λn, μ.measure' (s n)) :
tsum_eq_sum $ assume n hn,
match n, hn with
| 0, h := by simp at h; contradiction
| nat.succ 0, h := by simp at h; contradiction
| nat.succ (nat.succ n), h := μ.measure'_empty
end
... = μ.measure' s₁ + μ.measure' s₂ :
by simp [sum_insert, s0, s1]
protected lemma measure'_mono (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) (hs : s₁ ⊆ s₂) :
μ.measure' s₁ ≤ μ.measure' s₂ :=
have hd : s₁ ∩ (s₂ \ s₁) = ∅, from set.ext $ by simp [mem_sdiff_iff] {contextual:=tt},
have hu : s₁ ∪ (s₂ \ s₁) = s₂,
from set.ext $ assume x, by by_cases x ∈ s₁; simp [mem_sdiff_iff, h, @hs x] {contextual:=tt},
calc μ.measure' s₁ ≤ μ.measure' s₁ + μ.measure' (s₂ \ s₁) :
le_add_of_nonneg_right' ennreal.zero_le
... = μ.measure' (s₁ ∪ (s₂ \ s₁)) :
(μ.measure'_union hd h₁ (is_measurable_sdiff h₂ h₁)).symm
... = μ.measure' s₂ :
by simp [hu]
protected lemma measure'_Union_le_tsum_nat {s : ℕ → set α} (h : ∀i, is_measurable (s i)) :
μ.measure' (⋃i, s i) ≤ (∑i, μ.measure' (s i)) :=
calc μ.measure' (⋃i, s i) = μ.measure' (⋃i, disjointed s i) :
by simp [disjointed_Union]
... = ∑i, μ.measure' (disjointed s i) :
μ.measure'_Union disjoint_disjointed $ assume i, is_measurable_disjointed h
... ≤ ∑i, μ.measure' (s i) :
ennreal.tsum_le_tsum $ assume i,
μ.measure'_mono (is_measurable_disjointed h) (h i) (inter_subset_left _ _)
/-- outer measure of a measure -/
protected def to_outer_measure : outer_measure α :=
outer_measure.of_function μ.measure' μ.measure'_empty
/-- Measure projections for a measure space.
For measurable sets this returns the measure assigned by the `measure_of` field in `measure_space`.
But we can extend this to _all_ sets, but using the outer measure. This gives us monotonicity and
subadditivity for all sets.
-/
protected def measure (s : set α) : ennreal := μ.to_outer_measure.measure_of s
protected lemma measure_eq (hs : is_measurable s) : μ.measure s = μ.measure_of s hs :=
le_antisymm
(infi_le_of_le (λn, ⋃h : n = 0, s) $
infi_le_of_le begin simp [subset_def] end $
calc (∑i, ⨅ h : is_measurable (⋃ h : i = 0, s), μ.measure_of _ h) =
({0}:finset ℕ).sum (λi, ⨅ h : is_measurable (⋃ h : i = 0, s), μ.measure_of _ h) :
tsum_eq_sum $ assume b,
begin
simp,
intro hb,
rw [set.Union_neg hb, infi_pos is_measurable_empty, measure_space.measure_of_empty]
end
... ≤ μ.measure_of s hs : by simp [hs])
(le_infi $ assume f, le_infi $ assume hf,
classical.by_cases
(assume : ∀i, is_measurable (f i),
calc μ.measure_of s hs = μ.measure' s : by rw [μ.measure'_eq]
... ≤ μ.measure' (⋃i, f i) : μ.measure'_mono hs (is_measurable_Union this) hf
... ≤ ∑ (i : ℕ), μ.measure' (f i) : μ.measure'_Union_le_tsum_nat this)
(assume : ¬ ∀i, is_measurable (f i),
have ∃i, ¬ is_measurable (f i), by rwa [classical.not_forall] at this,
let ⟨i, hi⟩ := this in
calc μ.measure_of s hs ≤ μ.measure' (f i) : le_infi $ assume hi', by contradiction
... ≤ ∑ (i : ℕ), μ.measure' (f i) : ennreal.le_tsum))
protected lemma measure_eq_measure' (hs : is_measurable s) : μ.measure s = μ.measure' s :=
by rwa [μ.measure_eq, μ.measure'_eq]
end measure_space
section
variables {α : Type*} {β : Type*} [measurable_space α] {μ μ₁ μ₂ : measure_space α} {s s₁ s₂ : set α}
lemma measure_space_eq_of : ∀{μ₁ μ₂ : measure_space α},
(∀s, ∀h:is_measurable s, μ₁.measure_of s h = μ₂.measure_of s h) → μ₁ = μ₂
| ⟨m₁, e₁, u₁⟩ ⟨m₂, e₂, u₂⟩ h :=
have m₁ = m₂, from funext $ assume s, funext $ assume hs, h s hs,
by simp [this]
lemma measure_space_eq (h : ∀s, is_measurable s → μ₁.measure s = μ₂.measure s) : μ₁ = μ₂ :=
measure_space_eq_of $ assume s hs,
have μ₁.measure s = μ₂.measure s, from h s hs,
by simp [measure_space.measure_eq, hs] at this; assumption
@[simp] lemma measure_empty : μ.measure ∅ = 0 := μ.to_outer_measure.empty
lemma measure_mono (h : s₁ ⊆ s₂) : μ.measure s₁ ≤ μ.measure s₂ := μ.to_outer_measure.mono h
lemma measure_Union_le_tsum_nat {s : ℕ → set α} : μ.measure (⋃i, s i) ≤ (∑i, μ.measure (s i)) :=
@outer_measure.Union_nat α μ.to_outer_measure s
lemma measure_union (hd : disjoint s₁ s₂) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂) :
μ.measure (s₁ ∪ s₂) = μ.measure s₁ + μ.measure s₂ :=
by simp only [μ.measure_eq_measure', h₁, h₂, is_measurable_union];
from μ.measure'_union hd h₁ h₂
lemma measure_Union_nat {f : ℕ → set α}
(hn : pairwise (disjoint on f)) (h : ∀i, is_measurable (f i)) :
μ.measure (⋃i, f i) = (∑i, μ.measure (f i)) :=
by simp [measure_space.measure_eq, h, is_measurable_Union h, μ.measure_of_Union h hn]
lemma measure_bUnion {i : set β} {s : β → set α} (hi : countable i)
(hd : pairwise_on i (disjoint on s)) (h : ∀b∈i, is_measurable (s b)) :
μ.measure (⋃b∈i, s b) = ∑p:{b // b ∈ i}, μ.measure (s p.val) :=
let ⟨f, hf⟩ := hi in
let g : ℕ → set α := λn, ⋃b (h : b ∈ i) (h : f b = n), s b in
have h_gf : ∀b∈i, g (f b) = s b,
from assume b hb, le_antisymm
(supr_le $ assume b', supr_le $ assume hb', supr_le $ assume hbn,
have f b = f b', by simp [hbn],
have b = b', from hf _ hb _ hb' this,
by simp [this]; exact le_refl _)
(le_supr_of_le b $ le_supr_of_le hb $ le_supr_of_le rfl $ le_refl _),
have eq₁ : (⋃b∈i, s b) = (⋃i, g i),
from le_antisymm
(bUnion_subset $ assume b hb, show s b ≤ ⨆n (b:β) (h : b ∈ i) (h : f b = n), s b,
from le_supr_of_le (f b) $ le_supr_of_le b $ le_supr_of_le hb $ le_supr_of_le rfl $ le_refl (s b))
(supr_le $ assume n, supr_le $ assume b, supr_le $ assume hb, supr_le $ assume hnb,
subset_bUnion_of_mem hb),
have hd : pairwise (disjoint on g),
from assume n m h,
set.eq_empty_of_subset_empty $ calc g n ∩ g m =
(⋃b (h : b ∈ i) (h : f b = n) b' (h : b' ∈ i) (h : f b' = m), s b ∩ s b') :
by simp [g, inter_distrib_Union_left, inter_distrib_Union_right]
... ⊆ ∅ :
bUnion_subset $ assume b hb, Union_subset $ assume hbn,
bUnion_subset $ assume b' hb', Union_subset $ assume hbm,
have b ≠ b',
from assume h_eq,
have f b = f b', from congr_arg f h_eq,
by simp [hbm, hbn, h] at this; assumption,
have s b ∩ s b' = ∅,
from hd b hb b' hb' this,
by rw [this]; exact subset.refl _,
have hm : ∀n, is_measurable (g n),
from assume n,
by_cases
(assume : ∃b∈i, f b = n, let ⟨b, hb, h_eq⟩ := this in
have s b = g n, from h_eq ▸ (h_gf b hb).symm,
this ▸ h b hb)
(assume : ¬ ∃b∈i, f b = n,
have g n = ∅, from set.eq_empty_of_subset_empty $
bUnion_subset $ assume b hb, Union_subset $ assume h_eq, (this ⟨b, hb, h_eq⟩).elim,
this.symm ▸ is_measurable_empty),
calc μ.measure (⋃b∈i, s b) = μ.measure (⋃i, g i) : by rw [eq₁]
... = (∑i, μ.measure (g i)) : measure_Union_nat hd hm
... = (∑p:{b // b ∈ i}, μ.measure (s p.val)) : tsum_eq_tsum_of_ne_zero_bij
(λb h, f b.val)
(assume ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ _ _ h, subtype.eq $ show b₁ = b₂, from hf b₁ hb₁ b₂ hb₂ h)
(assume n hn,
have g n ≠ ∅, from assume h, by simp [h] at hn; assumption,
have ∃b∈i, f b = n,
from let ⟨x, hx⟩ := set.exists_mem_of_ne_empty this in
by simp at hx; exact let ⟨b, h_eq, hb, _⟩ := hx in ⟨b, hb, h_eq⟩,
let ⟨b, hb, h_eq⟩ := this in
have g n = s b,
from h_eq ▸ h_gf b hb,
⟨⟨b, hb⟩, by simp [this] at hn; assumption, h_eq⟩)
(assume ⟨b, hb⟩, by simp [hb, h_gf])
lemma measure_sUnion [encodable β] {s : β → set α}
(hd : pairwise (disjoint on s)) (h : ∀b, is_measurable (s b)) :
μ.measure (⋃b, s b) = ∑b, μ.measure (s b) :=
calc μ.measure (⋃b, s b) = μ.measure (⋃b∈(univ:set β), s b) :
congr_arg μ.measure $ set.ext $ by simp
... = ∑p:{b:β // true}, μ.measure (s p.val) :
measure_bUnion countable_encodable (assume i _ j _, hd i j) (assume b _, h b)
... = ∑b, μ.measure (s b) : @tsum_eq_tsum_of_iso _ _ _ _ _ _ _ (λb, μ.measure (s b)) subtype.val
(λb, ⟨b, trivial⟩ : β → {b:β // true}) (λ⟨b, hb⟩, rfl) (λb, rfl)
lemma measure_sdiff {s₁ s₂ : set α} (h : s₂ ⊆ s₁) (h₁ : is_measurable s₁) (h₂ : is_measurable s₂)
(h_fin : μ.measure s₁ < ⊤) : μ.measure (s₁ \ s₂) = μ.measure s₁ - μ.measure s₂ :=
have hd : disjoint (s₁ \ s₂) s₂, from sdiff_inter_same,
have μ.measure s₂ < ⊤, from lt_of_le_of_lt (measure_mono h) h_fin,
calc μ.measure (s₁ \ s₂) = (μ.measure (s₁ \ s₂) + μ.measure s₂) - μ.measure s₂ :
by rw [ennreal.add_sub_self this]
... = μ.measure (s₁ \ s₂ ∪ s₂) - μ.measure s₂ :
by rw [measure_union hd]; simp [is_measurable_sdiff, h₁, h₂]
... = _ : by rw [sdiff_union_same, union_of_subset_right h]
lemma measure_Union_eq_supr_nat {s : ℕ → set α} (h : ∀i, is_measurable (s i)) (hs : monotone s) :
μ.measure (⋃i, s i) = (⨆i, μ.measure (s i)) :=
-- TODO: generalize and extract from this proof
have ∀i, (range (i + 1)).sum (λi, μ.measure (disjointed s i)) = μ.measure (s i),
begin
intro i, induction i,
case nat.zero { simp [disjointed, nat.not_lt_zero, univ_inter] },
case nat.succ i ih {
rw [range_succ, sum_insert, ih, ←measure_union],
{ show μ.measure (disjointed s (i + 1) ∪ s i) = μ.measure (s (i + 1)),
rw [disjointed_of_mono hs, sdiff_union_same, union_of_subset_right],
exact hs (nat.le_succ _) },
{ show disjoint (disjointed s (i + 1)) (s i),
simp [disjoint, disjointed_of_mono hs],
exact sdiff_inter_same },
{ exact is_measurable_disjointed h },
{ exact h _ },
{ exact not_mem_range_self } }
end,
calc μ.measure (⋃i, s i) = μ.measure (⋃i, disjointed s i) :
by rw [disjointed_Union]
... = (∑i, μ.measure (disjointed s i)) :
measure_Union_nat (disjoint_disjointed) (assume i, is_measurable_disjointed h)
... = (⨆i, (finset.range i).sum (λi, μ.measure (disjointed s i))) :
by rw [ennreal.tsum_eq_supr_nat]
... = (⨆i, (range (i + 1)).sum (λi, μ.measure (disjointed s i))) :
le_antisymm
(supr_le begin intro i, cases i with j, simp, exact le_supr_of_le j (le_refl _) end)
(supr_le $ assume i, le_supr_of_le (i + 1) $ le_refl _)
... = (⨆i, μ.measure (s i)) :
congr_arg _ $ funext $ this
lemma measure_Inter_eq_infi_nat {s : ℕ → set α}
(h : ∀i, is_measurable (s i)) (hs : ∀i j, i ≤ j → s j ⊆ s i) (hfin : μ.measure (s 0) < ⊤) :
μ.measure (⋂i, s i) = (⨅i, μ.measure (s i)) :=
have eq₁ : (⋂i, s i) = (s 0 \ (⋃i, s 0 \ s i)),
from set.ext $ begin simp [iff_def], simp [imp_false] {contextual := tt} end,
have sub : (⋃i, s 0 \ s i) ⊆ s 0,
from Union_subset $ assume i, assume x, by simp {contextual := tt},
have hd : ∀i, is_measurable (s 0 \ s i), from assume i, is_measurable_sdiff (h 0) (h i),
have hu : is_measurable (⋃i, s 0 \ s i), from is_measurable_Union hd,
have hm : monotone (λ (i : ℕ), s 0 \ s i),
from assume i j h, sdiff_subset_sdiff (subset.refl _) (hs i j h),
have eq₂ : ∀i, μ.measure (s 0) - (μ.measure (s 0) - μ.measure (s i)) = μ.measure (s i),
from assume i,
have μ.measure (s i) ≤ μ.measure (s 0), from measure_mono (hs _ _ $ nat.zero_le _),
let ⟨r, hr, eqr, _⟩ := ennreal.lt_iff_exists_of_real.mp hfin in
let ⟨p, hp, eqp, _⟩ := ennreal.lt_iff_exists_of_real.mp (lt_of_le_of_lt this hfin) in
have 0 ≤ r - p,
by rw [le_sub_iff_add_le, zero_add, ←ennreal.of_real_le_of_real_iff hp hr, ←eqp, ←eqr];
from this,
by simp [eqr, eqp, hp, hr, this, -sub_eq_add_neg, sub_sub_self],
calc μ.measure (⋂i, s i) = μ.measure (s 0 \ (⋃i, s 0 \ s i)) :
congr_arg _ eq₁
... = μ.measure (s 0) - μ.measure (⋃i, s 0 \ s i) :
by rw [measure_sdiff sub (h 0) hu hfin]
... = μ.measure (s 0) - (⨆i, μ.measure (s 0 \ s i)) :
by rw [measure_Union_eq_supr_nat hd hm]
... = (⨅i, μ.measure (s 0) - μ.measure (s 0 \ s i)) :
ennreal.sub_supr hfin
... = (⨅i, μ.measure (s i)) :
congr_arg _ $ funext $ assume i,
by rw [measure_sdiff (hs _ _ (nat.zero_le _)) (h 0) (h i) hfin, eq₂]
end
def outer_measure.to_measure
{α : Type*} (m : outer_measure α) [ms : measurable_space α] (h : ms ≤ m.caratheodory) :
measure_space α :=
{ measure_of := λs hs, m.measure_of s,
measure_of_empty := m.empty,
measure_of_Union := assume s hs hf, m.Union_eq_of_caratheodory (assume i, h _ $ hs i) hf }
section constructions
variables {α : Type u} [measurable_space α]
def count : measure_space α :=
{ measure_of := λs hs, ∑x, if x ∈ s then 1 else 0,
measure_of_empty := by simp,
measure_of_Union := assume f _ hd,
begin
rw [ennreal.tsum_comm],
congr, apply funext, intro,
by_cases ∃i, x ∈ f i,
{ have h' : (∑(i : ℕ), ite (x ∈ f i) 1 0 : ennreal) = 1,
from let ⟨i, hi⟩ := h in
calc (∑(i : ℕ), ite (x ∈ f i) 1 0 : ennreal) =
finset.sum {i} (λi, ite (x ∈ f i) 1 0) :
tsum_eq_sum (assume j hj,
have j ≠ i, by simp at hj; assumption,
have f j ∩ f i = ∅, from hd j i this,
have x ∉ f j,
from assume hj,
have hx : x ∈ f j ∩ f i, from ⟨hj, hi⟩,
by rwa [this] at hx,
by simp [this])
... = (1 : ennreal) : by simp [hi],
simp [h, h'] },
{ have h₁ : x ∉ ⋃ (i : ℕ), f i, by simp [h],
have h₂ : ∀i, x ∉ f i, from assume i hi, h ⟨i, hi⟩,
simp [h₁, h₂] }
end }
instance : has_zero (measure_space α) :=
⟨{ measure_of := λs hs, 0, measure_of_empty := rfl, measure_of_Union := by simp }⟩
instance : partial_order (measure_space α) :=
{ partial_order .
le := λm₁ m₂, ∀s (hs : is_measurable s), m₁.measure_of s hs ≤ m₂.measure_of s hs,
le_refl := assume m s hs, le_refl _,
le_trans := assume m₁ m₂ m₃ h₁ h₂ s hs, le_trans (h₁ s hs) (h₂ s hs),
le_antisymm := assume m₁ m₂ h₁ h₂, measure_space_eq_of $
assume s hs, le_antisymm (h₁ s hs) (h₂ s hs) }
end constructions
end measure_theory
|
416fc3d9836935a66b0aba7443d02262b74d250c | 80746c6dba6a866de5431094bf9f8f841b043d77 | /src/meta/expr.lean | 1768c4b144823d7759e1230e7f42b7d71271fa7d | [
"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 | 4,037 | lean | /-
Copyright (c) 2019 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek, Robert Y. Lewis
Additional non-tactic operations on expr and related types
-/
namespace name
meta def deinternalize_field : name → name
| (name.mk_string s name.anonymous) :=
let i := s.mk_iterator in
if i.curr = '_' then i.next.next_to_string else s
| n := n
meta def get_nth_prefix : name → ℕ → name
| nm 0 := nm
| nm (n + 1) := get_nth_prefix nm.get_prefix n
private meta def pop_nth_prefix_aux : name → ℕ → name × ℕ
| anonymous n := (anonymous, 1)
| nm n := let (pfx, height) := pop_nth_prefix_aux nm.get_prefix n in
if height ≤ n then (anonymous, height + 1)
else (nm.update_prefix pfx, height + 1)
-- Pops the top `n` prefixes from the given name.
meta def pop_nth_prefix (nm : name) (n : ℕ) : name :=
prod.fst $ pop_nth_prefix_aux nm n
meta def pop_prefix (n : name) : name :=
pop_nth_prefix n 1
-- `name`s can contain numeral pieces, which are not legal names
-- when typed/passed directly to the parser. We turn an arbitrary
-- name into a legal identifier name.
meta def sanitize_name : name → name
| name.anonymous := name.anonymous
| (name.mk_string s p) := name.mk_string s $ sanitize_name p
| (name.mk_numeral s p) := name.mk_string sformat!"n{s}" $ sanitize_name p
end name
namespace expr
open tactic
protected meta def to_pos_nat : expr → option ℕ
| `(has_one.one _) := some 1
| `(bit0 %%e) := bit0 <$> e.to_pos_nat
| `(bit1 %%e) := bit1 <$> e.to_pos_nat
| _ := none
protected meta def to_nat : expr → option ℕ
| `(has_zero.zero _) := some 0
| e := e.to_pos_nat
protected meta def to_int : expr → option ℤ
| `(has_neg.neg %%e) := do n ← e.to_nat, some (-n)
| e := coe <$> e.to_nat
meta def is_meta_var : expr → bool
| (mvar _ _ _) := tt
| e := ff
meta def is_sort : expr → bool
| (sort _) := tt
| e := ff
meta def list_local_consts (e : expr) : list expr :=
e.fold [] (λ e' _ es, if e'.is_local_constant then insert e' es else es)
meta def list_constant (e : expr) : name_set :=
e.fold mk_name_set (λ e' _ es, if e'.is_constant then es.insert e'.const_name else es)
meta def list_meta_vars (e : expr) : list expr :=
e.fold [] (λ e' _ es, if e'.is_meta_var then insert e' es else es)
meta def list_names_with_prefix (pre : name) (e : expr) : name_set :=
e.fold mk_name_set $ λ e' _ l,
match e' with
| expr.const n _ := if n.get_prefix = pre then l.insert n else l
| _ := l
end
meta def is_mvar : expr → bool
| (mvar _ _ _) := tt
| _ := ff
/--
is_num_eq n1 n2 returns true if n1 and n2 are both numerals with the same numeral structure,
ignoring differences in type and type class arguments.
-/
meta def is_num_eq : expr → expr → bool
| `(@has_zero.zero _ _) `(@has_zero.zero _ _) := tt
| `(@has_one.one _ _) `(@has_one.one _ _) := tt
| `(bit0 %%a) `(bit0 %%b) := a.is_num_eq b
| `(bit1 %%a) `(bit1 %%b) := a.is_num_eq b
| `(-%%a) `(-%%b) := a.is_num_eq b
| `(%%a/%%a') `(%%b/%%b') := a.is_num_eq b
| _ _ := ff
end expr
namespace environment
meta def in_current_file' (env : environment) (n : name) : bool :=
env.in_current_file n && (n ∉ [``quot, ``quot.mk, ``quot.lift, ``quot.ind])
meta def is_structure_like (env : environment) (n : name) : option (nat × name) :=
do guardb (env.is_inductive n),
d ← (env.get n).to_option,
[intro] ← pure (env.constructors_of n) | none,
guard (env.inductive_num_indices n = 0),
some (env.inductive_num_params n, intro)
meta def is_structure (env : environment) (n : name) : bool :=
option.is_some $ do
(nparams, intro) ← env.is_structure_like n,
di ← (env.get intro).to_option,
expr.pi x _ _ _ ← nparams.iterate
(λ e : option expr, do expr.pi _ _ _ body ← e | none, some body)
(some di.type) | none,
env.is_projection (n ++ x.deinternalize_field)
end environment
|
ece6e90d3b68c67ef0b8755e1f5b9a3ca5828910 | 205f0fc16279a69ea36e9fd158e3a97b06834ce2 | /EXAMS/exam2.lean | fd98d077d815d0c4f020c5a2364836f79ff11475 | [] | 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 | 3,171 | lean | /-
This exam focuses on assessing your
ability to write and prove propositions
in predicate logic, with an emphasis on
predicates, disjunctions, and existentially
quantified propositions. There are three
parts:
A: Predicates [20 points in 4 parts]
B: Disjuctions [40 points in 2 parts]
C. Existentials [40 point in 2 parts]
-/
/- ******************************** -/
/- *** A. PREDICATES [20 points] ***-/
/- ******************************** -/
/-
1a. Define a function called isOdd that
takes an argument, n : ℕ, and returns a
proposition that asserts that n is odd.
The function will thus be a predicate on
values of type ℕ. Hint: a number is odd
if it's one more than an even number.
-/
/-
1b. To test your predicate, use "example"
to write and prove isOdd(15).
-/
/-
1c. Define isSmall : ℕ → Prop, to be a
predicate that is true exactly when the
argument, n, is such that n = 0 ∨ n = 1
∨ n = 2 ∨ n = 3 ∨ n = 4 ∨ n = 5. (Don't
try to rewrite this proposition as an
inequality; just use it as is.)
-/
/-
1d. Define a predicate, isBoth(n:ℕ) that
is true exacly when n satisfies both the
isOdd and isSmall predicates. Use isOdd
and isSmall in your answer.
-/
/- ******************* -/
/- *** DISJUNCTIONS ***-/
/- ******************* -/
/-
2. [20 Points]
Jane walks to school or she carries
her lunch. In either case, she uses
a bag. If she walks, she uses a bag for
her books. If she carries her lunch, she
uses a bag to carry her food. So if she
walks, she uses a bag, and if she carries
her lunch, she uses a bag. From the fact
that she walks or carries her lunch, and
from the added facts that in either case
she uses a bag, we can conclude that she
uses a bag.
Using Walks, Carries, and Bag as names
of propositions, write a Lean example
that asserts the following proposition;
then prove it.
If Walks, Carries, and Bag are
propositions, then if (Walks ∨ Carries)
is true, and then if (Walks implies Bag)
is true, and then if (Carries implies Bag)
is true, then Bag is true.
Here's a start.
example : ∀ (Walks Carries Bag : Prop), ...
-/
/-
3. [20 Points]
Prove the following proposition.
-/
example :
∀ (P Q R : Prop),
(P ∧ Q) → (Q ∨ R) → (P ∨ R) :=
begin
_
end
/- *********************** -/
/- *** C. EXISTENTIALS ***-/
/- *********************** -/
/-
4. [20 points]
Referring to the isBoth predicate you
defined in question #1, state and prove
the proposition that there *exists* a
number, n, that satisfies isBoth. Remember
that you can use the unfold tactic to
expand the name of a predicate in a goal.
Use "example" to state the proposition.
-/
/-
5. [20 points]
Suppose that Heavy and Round are
predicates on values of any type, T.
Prove the proposition that if every
t : T is Heavy (satisfies the Heavy
predicate) and if there exists some
t : T that is Round (satisfies the
Round predicate) then there exists
some t : T is both Heavy and Round
(satisfies the conjunction of the
two properties).
-/
example :
∀ T : Type, ∀ (Heavy Round : T → Prop),
(∀ t, Heavy t) → (∃ t, Round t) →
(∃ t, Heavy t ∧ Round t) :=
begin
_
end
|
85fa3c5b9cc37088cc427c6743a785d82a8912ed | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/linear_algebra/multilinear/basic.lean | 7e7f5a18107305d24488e133ff6ee2a89d63e9fd | [
"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 | 51,653 | lean | /-
Copyright (c) 2020 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import linear_algebra.basic
import algebra.algebra.basic
import algebra.big_operators.order
import algebra.big_operators.ring
import data.fintype.card
import data.fintype.sort
/-!
# Multilinear maps
We define multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are linear in each
coordinate. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type
(although some statements will require it to be a fintype). This space, denoted by
`multilinear_map R M₁ M₂`, inherits a module structure by pointwise addition and multiplication.
## Main definitions
* `multilinear_map R M₁ M₂` is the space of multilinear maps from `Π(i : ι), M₁ i` to `M₂`.
* `f.map_smul` is the multiplicativity of the multilinear map `f` along each coordinate.
* `f.map_add` is the additivity of the multilinear map `f` along each coordinate.
* `f.map_smul_univ` expresses the multiplicativity of `f` over all coordinates at the same time,
writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`.
* `f.map_add_univ` expresses the additivity of `f` over all coordinates at the same time, writing
`f (m + m')` as the sum over all subsets `s` of `ι` of `f (s.piecewise m m')`.
* `f.map_sum` expresses `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` as the sum of
`f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all possible functions.
We also register isomorphisms corresponding to currying or uncurrying variables, transforming a
multilinear function `f` on `n+1` variables into a linear function taking values in multilinear
functions in `n` variables, and into a multilinear function in `n` variables taking values in linear
functions. These operations are called `f.curry_left` and `f.curry_right` respectively
(with inverses `f.uncurry_left` and `f.uncurry_right`). These operations induce linear equivalences
between spaces of multilinear functions in `n+1` variables and spaces of linear functions into
multilinear functions in `n` variables (resp. multilinear functions in `n` variables taking values
in linear functions), called respectively `multilinear_curry_left_equiv` and
`multilinear_curry_right_equiv`.
## Implementation notes
Expressing that a map is linear along the `i`-th coordinate when all other coordinates are fixed
can be done in two (equivalent) different ways:
* fixing a vector `m : Π(j : ι - i), M₁ j.val`, and then choosing separately the `i`-th coordinate
* fixing a vector `m : Πj, M₁ j`, and then modifying its `i`-th coordinate
The second way is more artificial as the value of `m` at `i` is not relevant, but it has the
advantage of avoiding subtype inclusion issues. This is the definition we use, based on
`function.update` that allows to change the value of `m` at `i`.
-/
open function fin set
open_locale big_operators
universes u v v' v₁ v₂ v₃ w u'
variables {R : Type u} {ι : Type u'} {n : ℕ}
{M : fin n.succ → Type v} {M₁ : ι → Type v₁} {M₂ : Type v₂} {M₃ : Type v₃} {M' : Type v'}
[decidable_eq ι]
/-- Multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules
over `R`. -/
structure multilinear_map (R : Type u) {ι : Type u'} (M₁ : ι → Type v) (M₂ : Type w)
[decidable_eq ι] [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂]
[∀i, module R (M₁ i)] [module R M₂] :=
(to_fun : (Πi, M₁ i) → M₂)
(map_add' : ∀(m : Πi, M₁ i) (i : ι) (x y : M₁ i),
to_fun (update m i (x + y)) = to_fun (update m i x) + to_fun (update m i y))
(map_smul' : ∀(m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i),
to_fun (update m i (c • x)) = c • to_fun (update m i x))
namespace multilinear_map
section semiring
variables [semiring R]
[∀i, add_comm_monoid (M i)] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃]
[add_comm_monoid M']
[∀i, module R (M i)] [∀i, module R (M₁ i)] [module R M₂] [module R M₃]
[module R M']
(f f' : multilinear_map R M₁ M₂)
instance : has_coe_to_fun (multilinear_map R M₁ M₂) := ⟨_, to_fun⟩
initialize_simps_projections multilinear_map (to_fun → apply)
@[simp] lemma to_fun_eq_coe : f.to_fun = f := rfl
@[simp] lemma coe_mk (f : (Π i, M₁ i) → M₂) (h₁ h₂ ) :
⇑(⟨f, h₁, h₂⟩ : multilinear_map R M₁ M₂) = f := rfl
theorem congr_fun {f g : multilinear_map R M₁ M₂} (h : f = g) (x : Π i, M₁ i) : f x = g x :=
congr_arg (λ h : multilinear_map R M₁ M₂, h x) h
theorem congr_arg (f : multilinear_map R M₁ M₂) {x y : Π i, M₁ i} (h : x = y) : f x = f y :=
congr_arg (λ x : Π i, M₁ i, f x) h
theorem coe_inj ⦃f g : multilinear_map R M₁ M₂⦄ (h : ⇑f = g) : f = g :=
by cases f; cases g; cases h; refl
@[ext] theorem ext {f f' : multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' :=
coe_inj (funext H)
theorem ext_iff {f g : multilinear_map R M₁ M₂} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, ext h⟩
@[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) :
f (update m i (x + y)) = f (update m i x) + f (update m i y) :=
f.map_add' m i x y
@[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) :
f (update m i (c • x)) = c • f (update m i x) :=
f.map_smul' m i c x
lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 :=
begin
have : (0 : R) • (0 : M₁ i) = 0, by simp,
rw [← update_eq_self i m, h, ← this, f.map_smul, zero_smul]
end
@[simp] lemma map_update_zero (m : Πi, M₁ i) (i : ι) : f (update m i 0) = 0 :=
f.map_coord_zero i (update_same i 0 m)
@[simp] lemma map_zero [nonempty ι] : f 0 = 0 :=
begin
obtain ⟨i, _⟩ : ∃i:ι, i ∈ set.univ := set.exists_mem_of_nonempty ι,
exact map_coord_zero f i rfl
end
instance : has_add (multilinear_map R M₁ M₂) :=
⟨λf f', ⟨λx, f x + f' x, λm i x y, by simp [add_left_comm, add_assoc],
λm i c x, by simp [smul_add]⟩⟩
@[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl
instance : has_zero (multilinear_map R M₁ M₂) :=
⟨⟨λ _, 0, λm i x y, by simp, λm i c x, by simp⟩⟩
instance : inhabited (multilinear_map R M₁ M₂) := ⟨0⟩
@[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : multilinear_map R M₁ M₂) m = 0 := rfl
instance : add_comm_monoid (multilinear_map R M₁ M₂) :=
{ zero := (0 : multilinear_map R M₁ M₂),
add := (+),
add_assoc := by intros; ext; simp [add_comm, add_left_comm],
zero_add := by intros; ext; simp [add_comm, add_left_comm],
add_zero := by intros; ext; simp [add_comm, add_left_comm],
add_comm := by intros; ext; simp [add_comm, add_left_comm],
nsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩,
nsmul_zero' := λ f, by { ext, simp },
nsmul_succ' := λ n f, by { ext, simp [add_smul, nat.succ_eq_one_add] } }
@[simp] lemma sum_apply {α : Type*} (f : α → multilinear_map R M₁ M₂)
(m : Πi, M₁ i) : ∀ {s : finset α}, (∑ a in s, f a) m = ∑ a in s, f a m :=
begin
classical,
apply finset.induction,
{ rw finset.sum_empty, simp },
{ assume a s has H, rw finset.sum_insert has, simp [H, has] }
end
/-- If `f` is a multilinear map, then `f.to_linear_map m i` is the linear map obtained by fixing all
coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/
def to_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →ₗ[R] M₂ :=
{ to_fun := λx, f (update m i x),
map_add' := λx y, by simp,
map_smul' := λc x, by simp }
/-- The cartesian product of two multilinear maps, as a multilinear map. -/
def prod (f : multilinear_map R M₁ M₂) (g : multilinear_map R M₁ M₃) :
multilinear_map R M₁ (M₂ × M₃) :=
{ to_fun := λ m, (f m, g m),
map_add' := λ m i x y, by simp,
map_smul' := λ m i c x, by simp }
/-- Combine a family of multilinear maps with the same domain and codomains `M' i` into a
multilinear map taking values in the space of functions `Π i, M' i`. -/
@[simps] def pi {ι' : Type*} {M' : ι' → Type*} [Π i, add_comm_monoid (M' i)]
[Π i, module R (M' i)] (f : Π i, multilinear_map R M₁ (M' i)) :
multilinear_map R M₁ (Π i, M' i) :=
{ to_fun := λ m i, f i m,
map_add' := λ m i x y, funext $ λ j, (f j).map_add _ _ _ _,
map_smul' := λ m i c x, funext $ λ j, (f j).map_smul _ _ _ _ }
section
variables (R M₂)
/-- The evaluation map from `ι → M₂` to `M₂` is multilinear at a given `i` when `ι` is subsingleton.
-/
@[simps]
def of_subsingleton [subsingleton ι] (i' : ι) : multilinear_map R (λ _ : ι, M₂) M₂ :=
{ to_fun := function.eval i',
map_add' := λ m i x y, by {
rw subsingleton.elim i i', simp only [function.eval, function.update_same], },
map_smul' := λ m i r x, by {
rw subsingleton.elim i i', simp only [function.eval, function.update_same], } }
end
/-- Given a multilinear map `f` on `n` variables (parameterized by `fin n`) and a subset `s` of `k`
of these variables, one gets a new multilinear map on `fin k` by varying these variables, and fixing
the other ones equal to a given value `z`. It is denoted by `f.restr s hk z`, where `hk` is a
proof that the cardinality of `s` is `k`. The implicit identification between `fin k` and `s` that
we use is the canonical (increasing) bijection. -/
def restr {k n : ℕ} (f : multilinear_map R (λ i : fin n, M') M₂) (s : finset (fin n))
(hk : s.card = k) (z : M') :
multilinear_map R (λ i : fin k, M') M₂ :=
{ to_fun := λ v, f (λ j, if h : j ∈ s then v ((s.order_iso_of_fin hk).symm ⟨j, h⟩) else z),
map_add' := λ v i x y,
by { erw [dite_comp_equiv_update, dite_comp_equiv_update, dite_comp_equiv_update], simp },
map_smul' := λ v i c x, by { erw [dite_comp_equiv_update, dite_comp_equiv_update], simp } }
variable {R}
/-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build
an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a
multilinear map along the first variable. -/
lemma cons_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) :
f (cons (x+y) m) = f (cons x m) + f (cons y m) :=
by rw [← update_cons_zero x m (x+y), f.map_add, update_cons_zero, update_cons_zero]
/-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build
an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity
of a multilinear map along the first variable. -/
lemma cons_smul (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) :
f (cons (c • x) m) = c • f (cons x m) :=
by rw [← update_cons_zero x m (c • x), f.map_smul, update_cons_zero]
/-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build
an element of `Π(i : fin (n+1)), M i` using `snoc`, one can express directly the additivity of a
multilinear map along the first variable. -/
lemma snoc_add (f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x y : M (last n)) :
f (snoc m (x+y)) = f (snoc m x) + f (snoc m y) :=
by rw [← update_snoc_last x m (x+y), f.map_add, update_snoc_last, update_snoc_last]
/-- In the specific case of multilinear maps on spaces indexed by `fin (n+1)`, where one can build
an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity
of a multilinear map along the first variable. -/
lemma snoc_smul (f : multilinear_map R M M₂)
(m : Π(i : fin n), M i.cast_succ) (c : R) (x : M (last n)) :
f (snoc m (c • x)) = c • f (snoc m x) :=
by rw [← update_snoc_last x m (c • x), f.map_smul, update_snoc_last]
section
variables {M₁' : ι → Type*} [Π i, add_comm_monoid (M₁' i)] [Π i, module R (M₁' i)]
/-- If `g` is a multilinear map and `f` is a collection of linear maps,
then `g (f₁ m₁, ..., fₙ mₙ)` is again a multilinear map, that we call
`g.comp_linear_map f`. -/
def comp_linear_map (g : multilinear_map R M₁' M₂) (f : Π i, M₁ i →ₗ[R] M₁' i) :
multilinear_map R M₁ M₂ :=
{ to_fun := λ m, g $ λ i, f i (m i),
map_add' := λ m i x y,
have ∀ j z, f j (update m i z j) = update (λ k, f k (m k)) i (f i z) j :=
λ j z, function.apply_update (λ k, f k) _ _ _ _,
by simp [this],
map_smul' := λ m i c x,
have ∀ j z, f j (update m i z j) = update (λ k, f k (m k)) i (f i z) j :=
λ j z, function.apply_update (λ k, f k) _ _ _ _,
by simp [this] }
@[simp] lemma comp_linear_map_apply (g : multilinear_map R M₁' M₂) (f : Π i, M₁ i →ₗ[R] M₁' i)
(m : Π i, M₁ i) :
g.comp_linear_map f m = g (λ i, f i (m i)) :=
rfl
end
/-- If one adds to a vector `m'` another vector `m`, but only for coordinates in a finset `t`, then
the image under a multilinear map `f` is the sum of `f (s.piecewise m m')` along all subsets `s` of
`t`. This is mainly an auxiliary statement to prove the result when `t = univ`, given in
`map_add_univ`, although it can be useful in its own right as it does not require the index set `ι`
to be finite.-/
lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) :
f (t.piecewise (m + m') m') = ∑ s in t.powerset, f (s.piecewise m m') :=
begin
revert m',
refine finset.induction_on t (by simp) _,
assume i t hit Hrec m',
have A : (insert i t).piecewise (m + m') m' = update (t.piecewise (m + m') m') i (m i + m' i) :=
t.piecewise_insert _ _ _,
have B : update (t.piecewise (m + m') m') i (m' i) = t.piecewise (m + m') m',
{ ext j,
by_cases h : j = i,
{ rw h, simp [hit] },
{ simp [h] } },
let m'' := update m' i (m i),
have C : update (t.piecewise (m + m') m') i (m i) = t.piecewise (m + m'') m'',
{ ext j,
by_cases h : j = i,
{ rw h, simp [m'', hit] },
{ by_cases h' : j ∈ t; simp [h, hit, m'', h'] } },
rw [A, f.map_add, B, C, finset.sum_powerset_insert hit, Hrec, Hrec, add_comm],
congr' 1,
apply finset.sum_congr rfl (λs hs, _),
have : (insert i s).piecewise m m' = s.piecewise m m'',
{ ext j,
by_cases h : j = i,
{ rw h, simp [m'', finset.not_mem_of_mem_powerset_of_not_mem hs hit] },
{ by_cases h' : j ∈ s; simp [h, m'', h'] } },
rw this
end
/-- Additivity of a multilinear map along all coordinates at the same time,
writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/
lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) :
f (m + m') = ∑ s : finset ι, f (s.piecewise m m') :=
by simpa using f.map_piecewise_add m m' finset.univ
section apply_sum
variables {α : ι → Type*} (g : Π i, α i → M₁ i) (A : Π i, finset (α i))
open_locale classical
open fintype finset
/-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of
`f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ...,
`r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each
coordinate. Here, we give an auxiliary statement tailored for an inductive proof. Use instead
`map_sum_finset`. -/
lemma map_sum_finset_aux [fintype ι] {n : ℕ} (h : ∑ i, (A i).card = n) :
f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) :=
begin
induction n using nat.strong_induction_on with n IH generalizing A,
-- If one of the sets is empty, then all the sums are zero
by_cases Ai_empty : ∃ i, A i = ∅,
{ rcases Ai_empty with ⟨i, hi⟩,
have : ∑ j in A i, g i j = 0, by convert sum_empty,
rw f.map_coord_zero i this,
have : pi_finset A = ∅,
{ apply finset.eq_empty_of_forall_not_mem (λ r hr, _),
have : r i ∈ A i := mem_pi_finset.mp hr i,
rwa hi at this },
convert sum_empty.symm },
push_neg at Ai_empty,
-- Otherwise, if all sets are at most singletons, then they are exactly singletons and the result
-- is again straightforward
by_cases Ai_singleton : ∀ i, (A i).card ≤ 1,
{ have Ai_card : ∀ i, (A i).card = 1,
{ assume i,
have pos : finset.card (A i) ≠ 0, by simp [finset.card_eq_zero, Ai_empty i],
have : finset.card (A i) ≤ 1 := Ai_singleton i,
exact le_antisymm this (nat.succ_le_of_lt (_root_.pos_iff_ne_zero.mpr pos)) },
have : ∀ (r : Π i, α i), r ∈ pi_finset A → f (λ i, g i (r i)) = f (λ i, ∑ j in A i, g i j),
{ assume r hr,
unfold_coes,
congr' with i,
have : ∀ j ∈ A i, g i j = g i (r i),
{ assume j hj,
congr,
apply finset.card_le_one_iff.1 (Ai_singleton i) hj,
exact mem_pi_finset.mp hr i },
simp only [finset.sum_congr rfl this, finset.mem_univ, finset.sum_const, Ai_card i,
one_nsmul] },
simp only [sum_congr rfl this, Ai_card, card_pi_finset, prod_const_one, one_nsmul,
finset.sum_const] },
-- Remains the interesting case where one of the `A i`, say `A i₀`, has cardinality at least 2.
-- We will split into two parts `B i₀` and `C i₀` of smaller cardinality, let `B i = C i = A i`
-- for `i ≠ i₀`, apply the inductive assumption to `B` and `C`, and add up the corresponding
-- parts to get the sum for `A`.
push_neg at Ai_singleton,
obtain ⟨i₀, hi₀⟩ : ∃ i, 1 < (A i).card := Ai_singleton,
obtain ⟨j₁, j₂, hj₁, hj₂, j₁_ne_j₂⟩ : ∃ j₁ j₂, (j₁ ∈ A i₀) ∧ (j₂ ∈ A i₀) ∧ j₁ ≠ j₂ :=
finset.one_lt_card_iff.1 hi₀,
let B := function.update A i₀ (A i₀ \ {j₂}),
let C := function.update A i₀ {j₂},
have B_subset_A : ∀ i, B i ⊆ A i,
{ assume i,
by_cases hi : i = i₀,
{ rw hi, simp only [B, sdiff_subset, update_same]},
{ simp only [hi, B, update_noteq, ne.def, not_false_iff, finset.subset.refl] } },
have C_subset_A : ∀ i, C i ⊆ A i,
{ assume i,
by_cases hi : i = i₀,
{ rw hi, simp only [C, hj₂, finset.singleton_subset_iff, update_same] },
{ simp only [hi, C, update_noteq, ne.def, not_false_iff, finset.subset.refl] } },
-- split the sum at `i₀` as the sum over `B i₀` plus the sum over `C i₀`, to use additivity.
have A_eq_BC : (λ i, ∑ j in A i, g i j) =
function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j + ∑ j in C i₀, g i₀ j),
{ ext i,
by_cases hi : i = i₀,
{ rw [hi],
simp only [function.update_same],
have : A i₀ = B i₀ ∪ C i₀,
{ simp only [B, C, function.update_same, finset.sdiff_union_self_eq_union],
symmetry,
simp only [hj₂, finset.singleton_subset_iff, finset.union_eq_left_iff_subset] },
rw this,
apply finset.sum_union,
apply finset.disjoint_right.2 (λ j hj, _),
have : j = j₂, by { dsimp [C] at hj, simpa using hj },
rw this,
dsimp [B],
simp only [mem_sdiff, eq_self_iff_true, not_true, not_false_iff, finset.mem_singleton,
update_same, and_false] },
{ simp [hi] } },
have Beq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in B i₀, g i₀ j) =
(λ i, ∑ j in B i, g i j),
{ ext i,
by_cases hi : i = i₀,
{ rw hi, simp only [update_same] },
{ simp only [hi, B, update_noteq, ne.def, not_false_iff] } },
have Ceq : function.update (λ i, ∑ j in A i, g i j) i₀ (∑ j in C i₀, g i₀ j) =
(λ i, ∑ j in C i, g i j),
{ ext i,
by_cases hi : i = i₀,
{ rw hi, simp only [update_same] },
{ simp only [hi, C, update_noteq, ne.def, not_false_iff] } },
-- Express the inductive assumption for `B`
have Brec : f (λ i, ∑ j in B i, g i j) = ∑ r in pi_finset B, f (λ i, g i (r i)),
{ have : ∑ i, finset.card (B i) < ∑ i, finset.card (A i),
{ refine finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (B_subset_A i))
⟨i₀, finset.mem_univ _, _⟩,
have : {j₂} ⊆ A i₀, by simp [hj₂],
simp only [B, finset.card_sdiff this, function.update_same, finset.card_singleton],
exact nat.pred_lt (ne_of_gt (lt_trans nat.zero_lt_one hi₀)) },
rw h at this,
exact IH _ this B rfl },
-- Express the inductive assumption for `C`
have Crec : f (λ i, ∑ j in C i, g i j) = ∑ r in pi_finset C, f (λ i, g i (r i)),
{ have : ∑ i, finset.card (C i) < ∑ i, finset.card (A i) :=
finset.sum_lt_sum (λ i hi, finset.card_le_of_subset (C_subset_A i))
⟨i₀, finset.mem_univ _, by simp [C, hi₀]⟩,
rw h at this,
exact IH _ this C rfl },
have D : disjoint (pi_finset B) (pi_finset C),
{ have : disjoint (B i₀) (C i₀), by simp [B, C],
exact pi_finset_disjoint_of_disjoint B C this },
have pi_BC : pi_finset A = pi_finset B ∪ pi_finset C,
{ apply finset.subset.antisymm,
{ assume r hr,
by_cases hri₀ : r i₀ = j₂,
{ apply finset.mem_union_right,
apply mem_pi_finset.2 (λ i, _),
by_cases hi : i = i₀,
{ have : r i₀ ∈ C i₀, by simp [C, hri₀],
convert this },
{ simp [C, hi, mem_pi_finset.1 hr i] } },
{ apply finset.mem_union_left,
apply mem_pi_finset.2 (λ i, _),
by_cases hi : i = i₀,
{ have : r i₀ ∈ B i₀,
by simp [B, hri₀, mem_pi_finset.1 hr i₀],
convert this },
{ simp [B, hi, mem_pi_finset.1 hr i] } } },
{ exact finset.union_subset (pi_finset_subset _ _ (λ i, B_subset_A i))
(pi_finset_subset _ _ (λ i, C_subset_A i)) } },
rw A_eq_BC,
simp only [multilinear_map.map_add, Beq, Ceq, Brec, Crec, pi_BC],
rw ← finset.sum_union D,
end
/-- If `f` is multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of
`f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ...,
`r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each
coordinate. -/
lemma map_sum_finset [fintype ι] :
f (λ i, ∑ j in A i, g i j) = ∑ r in pi_finset A, f (λ i, g i (r i)) :=
f.map_sum_finset_aux _ _ rfl
/-- If `f` is multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of
`f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from
multilinearity by expanding successively with respect to each coordinate. -/
lemma map_sum [fintype ι] [∀ i, fintype (α i)] :
f (λ i, ∑ j, g i j) = ∑ r : Π i, α i, f (λ i, g i (r i)) :=
f.map_sum_finset g (λ i, finset.univ)
lemma map_update_sum {α : Type*} (t : finset α) (i : ι) (g : α → M₁ i) (m : Π i, M₁ i):
f (update m i (∑ a in t, g a)) = ∑ a in t, f (update m i (g a)) :=
begin
induction t using finset.induction with a t has ih h,
{ simp },
{ simp [finset.sum_insert has, ih] }
end
end apply_sum
section restrict_scalar
variables (R) {A : Type*} [semiring A] [has_scalar R A] [Π (i : ι), module A (M₁ i)]
[module A M₂] [∀ i, is_scalar_tower R A (M₁ i)] [is_scalar_tower R A M₂]
/-- Reinterpret an `A`-multilinear map as an `R`-multilinear map, if `A` is an algebra over `R`
and their actions on all involved modules agree with the action of `R` on `A`. -/
def restrict_scalars (f : multilinear_map A M₁ M₂) : multilinear_map R M₁ M₂ :=
{ to_fun := f,
map_add' := f.map_add,
map_smul' := λ m i, (f.to_linear_map m i).map_smul_of_tower }
@[simp] lemma coe_restrict_scalars (f : multilinear_map A M₁ M₂) :
⇑(f.restrict_scalars R) = f := rfl
end restrict_scalar
section
variables {ι₁ ι₂ ι₃ : Type*} [decidable_eq ι₁] [decidable_eq ι₂] [decidable_eq ι₃]
/-- Transfer the arguments to a map along an equivalence between argument indices.
The naming is derived from `finsupp.dom_congr`, noting that here the permutation applies to the
domain of the domain. -/
@[simps apply]
def dom_dom_congr (σ : ι₁ ≃ ι₂) (m : multilinear_map R (λ i : ι₁, M₂) M₃) :
multilinear_map R (λ i : ι₂, M₂) M₃ :=
{ to_fun := λ v, m (λ i, v (σ i)),
map_add' := λ v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_add, },
map_smul' := λ v i a b, by { simp_rw function.update_apply_equiv_apply v, rw m.map_smul, }, }
lemma dom_dom_congr_trans (σ₁ : ι₁ ≃ ι₂) (σ₂ : ι₂ ≃ ι₃) (m : multilinear_map R (λ i : ι₁, M₂) M₃) :
m.dom_dom_congr (σ₁.trans σ₂) = (m.dom_dom_congr σ₁).dom_dom_congr σ₂ := rfl
lemma dom_dom_congr_mul (σ₁ : equiv.perm ι₁) (σ₂ : equiv.perm ι₁)
(m : multilinear_map R (λ i : ι₁, M₂) M₃) :
m.dom_dom_congr (σ₂ * σ₁) = (m.dom_dom_congr σ₁).dom_dom_congr σ₂ := rfl
/-- `multilinear_map.dom_dom_congr` as an equivalence.
This is declared separately because it does not work with dot notation. -/
@[simps apply symm_apply]
def dom_dom_congr_equiv (σ : ι₁ ≃ ι₂) :
multilinear_map R (λ i : ι₁, M₂) M₃ ≃+ multilinear_map R (λ i : ι₂, M₂) M₃ :=
{ to_fun := dom_dom_congr σ,
inv_fun := dom_dom_congr σ.symm,
left_inv := λ m, by {ext, simp},
right_inv := λ m, by {ext, simp},
map_add' := λ a b, by {ext, simp} }
end
end semiring
end multilinear_map
namespace linear_map
variables [semiring R]
[Πi, add_comm_monoid (M₁ i)] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M']
[∀i, module R (M₁ i)] [module R M₂] [module R M₃] [module R M']
/-- Composing a multilinear map with a linear map gives again a multilinear map. -/
def comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) :
multilinear_map R M₁ M₃ :=
{ to_fun := g ∘ f,
map_add' := λ m i x y, by simp,
map_smul' := λ m i c x, by simp }
@[simp] lemma coe_comp_multilinear_map (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) :
⇑(g.comp_multilinear_map f) = g ∘ f := rfl
lemma comp_multilinear_map_apply (g : M₂ →ₗ[R] M₃) (f : multilinear_map R M₁ M₂) (m : Π i, M₁ i) :
g.comp_multilinear_map f m = g (f m) := rfl
variables {ι₁ ι₂ : Type*} [decidable_eq ι₁] [decidable_eq ι₂]
@[simp] lemma comp_multilinear_map_dom_dom_congr (σ : ι₁ ≃ ι₂) (g : M₂ →ₗ[R] M₃)
(f : multilinear_map R (λ i : ι₁, M') M₂) :
(g.comp_multilinear_map f).dom_dom_congr σ = g.comp_multilinear_map (f.dom_dom_congr σ) :=
by { ext, simp }
end linear_map
namespace multilinear_map
section comm_semiring
variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [∀i, add_comm_monoid (M i)]
[add_comm_monoid M₂] [∀i, module R (M i)] [∀i, module R (M₁ i)] [module R M₂]
(f f' : multilinear_map R M₁ M₂)
/-- If one multiplies by `c i` the coordinates in a finset `s`, then the image under a multilinear
map is multiplied by `∏ i in s, c i`. This is mainly an auxiliary statement to prove the result when
`s = univ`, given in `map_smul_univ`, although it can be useful in its own right as it does not
require the index set `ι` to be finite. -/
lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) :
f (s.piecewise (λi, c i • m i) m) = (∏ i in s, c i) • f m :=
begin
refine s.induction_on (by simp) _,
assume j s j_not_mem_s Hrec,
have A : function.update (s.piecewise (λi, c i • m i) m) j (m j) =
s.piecewise (λi, c i • m i) m,
{ ext i,
by_cases h : i = j,
{ rw h, simp [j_not_mem_s] },
{ simp [h] } },
rw [s.piecewise_insert, f.map_smul, A, Hrec],
simp [j_not_mem_s, mul_smul]
end
/-- Multiplicativity of a multilinear map along all coordinates at the same time,
writing `f (λi, c i • m i)` as `(∏ i, c i) • f m`. -/
lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) :
f (λi, c i • m i) = (∏ i, c i) • f m :=
by simpa using map_piecewise_smul f c m finset.univ
section distrib_mul_action
variables {R' A : Type*} [monoid R'] [semiring A]
[Π i, module A (M₁ i)] [distrib_mul_action R' M₂] [module A M₂] [smul_comm_class A R' M₂]
instance : has_scalar R' (multilinear_map A M₁ M₂) := ⟨λ c f,
⟨λ m, c • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x c] ⟩⟩
@[simp] lemma smul_apply (f : multilinear_map A M₁ M₂) (c : R') (m : Πi, M₁ i) :
(c • f) m = c • f m := rfl
instance : distrib_mul_action R' (multilinear_map A M₁ M₂) :=
{ one_smul := λ f, ext $ λ x, one_smul _ _,
mul_smul := λ c₁ c₂ f, ext $ λ x, mul_smul _ _ _,
smul_zero := λ r, ext $ λ x, smul_zero _,
smul_add := λ r f₁ f₂, ext $ λ x, smul_add _ _ _ }
end distrib_mul_action
section module
variables {R' A : Type*} [semiring R'] [semiring A]
[Π i, module A (M₁ i)] [module A M₂]
[add_comm_monoid M₃] [module R' M₃] [module A M₃] [smul_comm_class A R' M₃]
/-- The space of multilinear maps over an algebra over `R` is a module over `R`, for the pointwise
addition and scalar multiplication. -/
instance [module R' M₂] [smul_comm_class A R' M₂] : module R' (multilinear_map A M₁ M₂) :=
{ add_smul := λ r₁ r₂ f, ext $ λ x, add_smul _ _ _,
zero_smul := λ f, ext $ λ x, zero_smul _ _ }
variables (M₂ M₃ R' A)
/-- `multilinear_map.dom_dom_congr` as a `linear_equiv`. -/
@[simps apply symm_apply]
def dom_dom_congr_linear_equiv {ι₁ ι₂} [decidable_eq ι₁] [decidable_eq ι₂] (σ : ι₁ ≃ ι₂) :
multilinear_map A (λ i : ι₁, M₂) M₃ ≃ₗ[R'] multilinear_map A (λ i : ι₂, M₂) M₃ :=
{ map_smul' := λ c f, by { ext, simp },
.. (dom_dom_congr_equiv σ : multilinear_map A (λ i : ι₁, M₂) M₃ ≃+
multilinear_map A (λ i : ι₂, M₂) M₃) }
end module
section
variables (R ι) (A : Type*) [comm_semiring A] [algebra R A] [fintype ι]
/-- Given an `R`-algebra `A`, `mk_pi_algebra` is the multilinear map on `A^ι` associating
to `m` the product of all the `m i`.
See also `multilinear_map.mk_pi_algebra_fin` for a version that works with a non-commutative
algebra `A` but requires `ι = fin n`. -/
protected def mk_pi_algebra : multilinear_map R (λ i : ι, A) A :=
{ to_fun := λ m, ∏ i, m i,
map_add' := λ m i x y, by simp [finset.prod_update_of_mem, add_mul],
map_smul' := λ m i c x, by simp [finset.prod_update_of_mem] }
variables {R A ι}
@[simp] lemma mk_pi_algebra_apply (m : ι → A) :
multilinear_map.mk_pi_algebra R ι A m = ∏ i, m i :=
rfl
end
section
variables (R n) (A : Type*) [semiring A] [algebra R A]
/-- Given an `R`-algebra `A`, `mk_pi_algebra_fin` is the multilinear map on `A^n` associating
to `m` the product of all the `m i`.
See also `multilinear_map.mk_pi_algebra` for a version that assumes `[comm_semiring A]` but works
for `A^ι` with any finite type `ι`. -/
protected def mk_pi_algebra_fin : multilinear_map R (λ i : fin n, A) A :=
{ to_fun := λ m, (list.of_fn m).prod,
map_add' :=
begin
intros m i x y,
have : (list.fin_range n).index_of i < n,
by simpa using list.index_of_lt_length.2 (list.mem_fin_range i),
simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, add_mul,
this, mul_add, add_mul]
end,
map_smul' :=
begin
intros m i c x,
have : (list.fin_range n).index_of i < n,
by simpa using list.index_of_lt_length.2 (list.mem_fin_range i),
simp [list.of_fn_eq_map, (list.nodup_fin_range n).map_update, list.prod_update_nth, this]
end }
variables {R A n}
@[simp] lemma mk_pi_algebra_fin_apply (m : fin n → A) :
multilinear_map.mk_pi_algebra_fin R n A m = (list.of_fn m).prod :=
rfl
lemma mk_pi_algebra_fin_apply_const (a : A) :
multilinear_map.mk_pi_algebra_fin R n A (λ _, a) = a ^ n :=
by simp
end
/-- Given an `R`-multilinear map `f` taking values in `R`, `f.smul_right z` is the map
sending `m` to `f m • z`. -/
def smul_right (f : multilinear_map R M₁ R) (z : M₂) : multilinear_map R M₁ M₂ :=
(linear_map.smul_right linear_map.id z).comp_multilinear_map f
@[simp] lemma smul_right_apply (f : multilinear_map R M₁ R) (z : M₂) (m : Π i, M₁ i) :
f.smul_right z m = f m • z :=
rfl
variables (R ι)
/-- The canonical multilinear map on `R^ι` when `ι` is finite, associating to `m` the product of
all the `m i` (multiplied by a fixed reference element `z` in the target module). See also
`mk_pi_algebra` for a more general version. -/
protected def mk_pi_ring [fintype ι] (z : M₂) : multilinear_map R (λ(i : ι), R) M₂ :=
(multilinear_map.mk_pi_algebra R ι R).smul_right z
variables {R ι}
@[simp] lemma mk_pi_ring_apply [fintype ι] (z : M₂) (m : ι → R) :
(multilinear_map.mk_pi_ring R ι z : (ι → R) → M₂) m = (∏ i, m i) • z := rfl
lemma mk_pi_ring_apply_one_eq_self [fintype ι] (f : multilinear_map R (λ(i : ι), R) M₂) :
multilinear_map.mk_pi_ring R ι (f (λi, 1)) = f :=
begin
ext m,
have : m = (λi, m i • 1), by { ext j, simp },
conv_rhs { rw [this, f.map_smul_univ] },
refl
end
end comm_semiring
section range_add_comm_group
variables [semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_group M₂]
[∀i, module R (M₁ i)] [module R M₂]
(f g : multilinear_map R M₁ M₂)
instance : has_neg (multilinear_map R M₁ M₂) :=
⟨λ f, ⟨λ m, - f m, λm i x y, by simp [add_comm], λm i c x, by simp⟩⟩
@[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl
instance : has_sub (multilinear_map R M₁ M₂) :=
⟨λ f g,
⟨λ m, f m - g m,
λ m i x y, by { simp only [map_add, sub_eq_add_neg, neg_add], cc },
λ m i c x, by { simp only [map_smul, smul_sub] }⟩⟩
@[simp] lemma sub_apply (m : Πi, M₁ i) : (f - g) m = f m - g m := rfl
instance : add_comm_group (multilinear_map R M₁ M₂) :=
by refine
{ zero := (0 : multilinear_map R M₁ M₂),
add := (+),
neg := has_neg.neg,
sub := has_sub.sub,
sub_eq_add_neg := _,
nsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩,
gsmul := λ n f, ⟨λ m, n • f m, λm i x y, by simp [smul_add], λl i x d, by simp [←smul_comm x n] ⟩,
gsmul_zero' := _,
gsmul_succ' := _,
gsmul_neg' := _,
.. multilinear_map.add_comm_monoid, .. };
intros; ext; simp [add_comm, add_left_comm, sub_eq_add_neg, add_smul, nat.succ_eq_add_one]
end range_add_comm_group
section add_comm_group
variables [semiring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂]
[∀i, module R (M₁ i)] [module R M₂]
(f : multilinear_map R M₁ M₂)
@[simp] lemma map_neg (m : Πi, M₁ i) (i : ι) (x : M₁ i) :
f (update m i (-x)) = -f (update m i x) :=
eq_neg_of_add_eq_zero $ by rw [←map_add, add_left_neg, f.map_coord_zero i (update_same i 0 m)]
@[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) :
f (update m i (x - y)) = f (update m i x) - f (update m i y) :=
by rw [sub_eq_add_neg, sub_eq_add_neg, map_add, map_neg]
end add_comm_group
section comm_semiring
variables [comm_semiring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M₂]
[∀i, module R (M₁ i)] [module R M₂]
/-- When `ι` is finite, multilinear maps on `R^ι` with values in `M₂` are in bijection with `M₂`,
as such a multilinear map is completely determined by its value on the constant vector made of ones.
We register this bijection as a linear equivalence in `multilinear_map.pi_ring_equiv`. -/
protected def pi_ring_equiv [fintype ι] : M₂ ≃ₗ[R] (multilinear_map R (λ(i : ι), R) M₂) :=
{ to_fun := λ z, multilinear_map.mk_pi_ring R ι z,
inv_fun := λ f, f (λi, 1),
map_add' := λ z z', by { ext m, simp [smul_add] },
map_smul' := λ c z, by { ext m, simp [smul_smul, mul_comm] },
left_inv := λ z, by simp,
right_inv := λ f, f.mk_pi_ring_apply_one_eq_self }
end comm_semiring
end multilinear_map
section currying
/-!
### Currying
We associate to a multilinear map in `n+1` variables (i.e., based on `fin n.succ`) two
curried functions, named `f.curry_left` (which is a linear map on `E 0` taking values
in multilinear maps in `n` variables) and `f.curry_right` (wich is a multilinear map in `n`
variables taking values in linear maps on `E 0`). In both constructions, the variable that is
singled out is `0`, to take advantage of the operations `cons` and `tail` on `fin n`.
The inverse operations are called `uncurry_left` and `uncurry_right`.
We also register linear equiv versions of these correspondences, in
`multilinear_curry_left_equiv` and `multilinear_curry_right_equiv`.
-/
open multilinear_map
variables {R M M₂}
[comm_semiring R] [∀i, add_comm_monoid (M i)] [add_comm_monoid M'] [add_comm_monoid M₂]
[∀i, module R (M i)] [module R M'] [module R M₂]
/-! #### Left currying -/
/-- Given a linear map `f` from `M 0` to multilinear maps on `n` variables,
construct the corresponding multilinear map on `n+1` variables obtained by concatenating
the variables, given by `m ↦ f (m 0) (tail m)`-/
def linear_map.uncurry_left
(f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) :
multilinear_map R M M₂ :=
{ to_fun := λm, f (m 0) (tail m),
map_add' := λm i x y, begin
by_cases h : i = 0,
{ subst i,
rw [update_same, update_same, update_same, f.map_add, add_apply,
tail_update_zero, tail_update_zero, tail_update_zero] },
{ rw [update_noteq (ne.symm h), update_noteq (ne.symm h), update_noteq (ne.symm h)],
revert x y,
rw ← succ_pred i h,
assume x y,
rw [tail_update_succ, map_add, tail_update_succ, tail_update_succ] }
end,
map_smul' := λm i c x, begin
by_cases h : i = 0,
{ subst i,
rw [update_same, update_same, tail_update_zero, tail_update_zero,
← smul_apply, f.map_smul] },
{ rw [update_noteq (ne.symm h), update_noteq (ne.symm h)],
revert x,
rw ← succ_pred i h,
assume x,
rw [tail_update_succ, tail_update_succ, map_smul] }
end }
@[simp] lemma linear_map.uncurry_left_apply
(f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) (m : Πi, M i) :
f.uncurry_left m = f (m 0) (tail m) := rfl
/-- Given a multilinear map `f` in `n+1` variables, split the first variable to obtain
a linear map into multilinear maps in `n` variables, given by `x ↦ (m ↦ f (cons x m))`. -/
def multilinear_map.curry_left
(f : multilinear_map R M M₂) :
M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂) :=
{ to_fun := λx,
{ to_fun := λm, f (cons x m),
map_add' := λm i y y', by simp,
map_smul' := λm i y c, by simp },
map_add' := λx y, by { ext m, exact cons_add f m x y },
map_smul' := λc x, by { ext m, exact cons_smul f m c x } }
@[simp] lemma multilinear_map.curry_left_apply
(f : multilinear_map R M M₂) (x : M 0) (m : Π(i : fin n), M i.succ) :
f.curry_left x m = f (cons x m) := rfl
@[simp] lemma linear_map.curry_uncurry_left
(f : M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) :
f.uncurry_left.curry_left = f :=
begin
ext m x,
simp only [tail_cons, linear_map.uncurry_left_apply, multilinear_map.curry_left_apply],
rw cons_zero
end
@[simp] lemma multilinear_map.uncurry_curry_left
(f : multilinear_map R M M₂) :
f.curry_left.uncurry_left = f :=
by { ext m, simp, }
variables (R M M₂)
/-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to
the space of linear maps from `M 0` to the space of multilinear maps on
`Π(i : fin n), M i.succ `, by separating the first variable. We register this isomorphism as a
linear isomorphism in `multilinear_curry_left_equiv R M M₂`.
The direct and inverse maps are given by `f.uncurry_left` and `f.curry_left`. Use these
unless you need the full framework of linear equivs. -/
def multilinear_curry_left_equiv :
(M 0 →ₗ[R] (multilinear_map R (λ(i : fin n), M i.succ) M₂)) ≃ₗ[R] (multilinear_map R M M₂) :=
{ to_fun := linear_map.uncurry_left,
map_add' := λf₁ f₂, by { ext m, refl },
map_smul' := λc f, by { ext m, refl },
inv_fun := multilinear_map.curry_left,
left_inv := linear_map.curry_uncurry_left,
right_inv := multilinear_map.uncurry_curry_left }
variables {R M M₂}
/-! #### Right currying -/
/-- Given a multilinear map `f` in `n` variables to the space of linear maps from `M (last n)` to
`M₂`, construct the corresponding multilinear map on `n+1` variables obtained by concatenating
the variables, given by `m ↦ f (init m) (m (last n))`-/
def multilinear_map.uncurry_right
(f : (multilinear_map R (λ(i : fin n), M i.cast_succ) (M (last n) →ₗ[R] M₂))) :
multilinear_map R M M₂ :=
{ to_fun := λm, f (init m) (m (last n)),
map_add' := λm i x y, begin
by_cases h : i.val < n,
{ have : last n ≠ i := ne.symm (ne_of_lt h),
rw [update_noteq this, update_noteq this, update_noteq this],
revert x y,
rw [(cast_succ_cast_lt i h).symm],
assume x y,
rw [init_update_cast_succ, map_add, init_update_cast_succ, init_update_cast_succ,
linear_map.add_apply] },
{ revert x y,
rw eq_last_of_not_lt h,
assume x y,
rw [init_update_last, init_update_last, init_update_last,
update_same, update_same, update_same, linear_map.map_add] }
end,
map_smul' := λm i c x, begin
by_cases h : i.val < n,
{ have : last n ≠ i := ne.symm (ne_of_lt h),
rw [update_noteq this, update_noteq this],
revert x,
rw [(cast_succ_cast_lt i h).symm],
assume x,
rw [init_update_cast_succ, init_update_cast_succ, map_smul, linear_map.smul_apply] },
{ revert x,
rw eq_last_of_not_lt h,
assume x,
rw [update_same, update_same, init_update_last, init_update_last,
linear_map.map_smul] }
end }
@[simp] lemma multilinear_map.uncurry_right_apply
(f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) (m : Πi, M i) :
f.uncurry_right m = f (init m) (m (last n)) := rfl
/-- Given a multilinear map `f` in `n+1` variables, split the last variable to obtain
a multilinear map in `n` variables taking values in linear maps from `M (last n)` to `M₂`, given by
`m ↦ (x ↦ f (snoc m x))`. -/
def multilinear_map.curry_right (f : multilinear_map R M M₂) :
multilinear_map R (λ(i : fin n), M (fin.cast_succ i)) ((M (last n)) →ₗ[R] M₂) :=
{ to_fun := λm,
{ to_fun := λx, f (snoc m x),
map_add' := λx y, by rw f.snoc_add,
map_smul' := λc x, by simp only [f.snoc_smul, ring_hom.id_apply] },
map_add' := λm i x y, begin
ext z,
change f (snoc (update m i (x + y)) z)
= f (snoc (update m i x) z) + f (snoc (update m i y) z),
rw [snoc_update, snoc_update, snoc_update, f.map_add]
end,
map_smul' := λm i c x, begin
ext z,
change f (snoc (update m i (c • x)) z) = c • f (snoc (update m i x) z),
rw [snoc_update, snoc_update, f.map_smul]
end }
@[simp] lemma multilinear_map.curry_right_apply
(f : multilinear_map R M M₂) (m : Π(i : fin n), M i.cast_succ) (x : M (last n)) :
f.curry_right m x = f (snoc m x) := rfl
@[simp] lemma multilinear_map.curry_uncurry_right
(f : (multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))) :
f.uncurry_right.curry_right = f :=
begin
ext m x,
simp only [snoc_last, multilinear_map.curry_right_apply, multilinear_map.uncurry_right_apply],
rw init_snoc
end
@[simp] lemma multilinear_map.uncurry_curry_right
(f : multilinear_map R M M₂) : f.curry_right.uncurry_right = f :=
by { ext m, simp }
variables (R M M₂)
/-- The space of multilinear maps on `Π(i : fin (n+1)), M i` is canonically isomorphic to
the space of linear maps from the space of multilinear maps on `Π(i : fin n), M i.cast_succ` to the
space of linear maps on `M (last n)`, by separating the last variable. We register this isomorphism
as a linear isomorphism in `multilinear_curry_right_equiv R M M₂`.
The direct and inverse maps are given by `f.uncurry_right` and `f.curry_right`. Use these
unless you need the full framework of linear equivs. -/
def multilinear_curry_right_equiv :
(multilinear_map R (λ(i : fin n), M i.cast_succ) ((M (last n)) →ₗ[R] M₂))
≃ₗ[R] (multilinear_map R M M₂) :=
{ to_fun := multilinear_map.uncurry_right,
map_add' := λf₁ f₂, by { ext m, refl },
map_smul' := λc f, by { ext m, rw [smul_apply], refl },
inv_fun := multilinear_map.curry_right,
left_inv := multilinear_map.curry_uncurry_right,
right_inv := multilinear_map.uncurry_curry_right }
namespace multilinear_map
variables {ι' : Type*} [decidable_eq ι'] [decidable_eq (ι ⊕ ι')] {R M₂}
/-- A multilinear map on `Π i : ι ⊕ ι', M'` defines a multilinear map on `Π i : ι, M'`
taking values in the space of multilinear maps on `Π i : ι', M'`. -/
def curry_sum (f : multilinear_map R (λ x : ι ⊕ ι', M') M₂) :
multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂) :=
{ to_fun := λ u,
{ to_fun := λ v, f (sum.elim u v),
map_add' := λ v i x y, by simp only [← sum.update_elim_inr, f.map_add],
map_smul' := λ v i c x, by simp only [← sum.update_elim_inr, f.map_smul] },
map_add' := λ u i x y, ext $ λ v,
by simp only [multilinear_map.coe_mk, add_apply, ← sum.update_elim_inl, f.map_add],
map_smul' := λ u i c x, ext $ λ v,
by simp only [multilinear_map.coe_mk, smul_apply, ← sum.update_elim_inl, f.map_smul] }
@[simp] lemma curry_sum_apply (f : multilinear_map R (λ x : ι ⊕ ι', M') M₂)
(u : ι → M') (v : ι' → M') :
f.curry_sum u v = f (sum.elim u v) :=
rfl
/-- A multilinear map on `Π i : ι, M'` taking values in the space of multilinear maps
on `Π i : ι', M'` defines a multilinear map on `Π i : ι ⊕ ι', M'`. -/
def uncurry_sum (f : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂)) :
multilinear_map R (λ x : ι ⊕ ι', M') M₂ :=
{ to_fun := λ u, f (u ∘ sum.inl) (u ∘ sum.inr),
map_add' := λ u i x y, by cases i;
simp only [map_add, add_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr,
sum.update_inr_comp_inl, sum.update_inr_comp_inr],
map_smul' := λ u i c x, by cases i;
simp only [map_smul, smul_apply, sum.update_inl_comp_inl, sum.update_inl_comp_inr,
sum.update_inr_comp_inl, sum.update_inr_comp_inr] }
@[simp] lemma uncurry_sum_aux_apply
(f : multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂)) (u : ι ⊕ ι' → M') :
f.uncurry_sum u = f (u ∘ sum.inl) (u ∘ sum.inr) :=
rfl
variables (ι ι' R M₂ M')
/-- Linear equivalence between the space of multilinear maps on `Π i : ι ⊕ ι', M'` and the space
of multilinear maps on `Π i : ι, M'` taking values in the space of multilinear maps
on `Π i : ι', M'`. -/
def curry_sum_equiv : multilinear_map R (λ x : ι ⊕ ι', M') M₂ ≃ₗ[R]
multilinear_map R (λ x : ι, M') (multilinear_map R (λ x : ι', M') M₂) :=
{ to_fun := curry_sum,
inv_fun := uncurry_sum,
left_inv := λ f, ext $ λ u, by simp,
right_inv := λ f, by { ext, simp },
map_add' := λ f g, by { ext, refl },
map_smul' := λ c f, by { ext, refl } }
variables {ι ι' R M₂ M'}
@[simp] lemma coe_curry_sum_equiv : ⇑(curry_sum_equiv R ι M₂ M' ι') = curry_sum := rfl
@[simp] lemma coe_curr_sum_equiv_symm : ⇑(curry_sum_equiv R ι M₂ M' ι').symm = uncurry_sum := rfl
variables (R M₂ M')
/-- If `s : finset (fin n)` is a finite set of cardinality `k` and its complement has cardinality
`l`, then the space of multilinear maps on `λ i : fin n, M'` is isomorphic to the space of
multilinear maps on `λ i : fin k, M'` taking values in the space of multilinear maps
on `λ i : fin l, M'`. -/
def curry_fin_finset {k l n : ℕ} {s : finset (fin n)}
(hk : s.card = k) (hl : sᶜ.card = l) :
multilinear_map R (λ x : fin n, M') M₂ ≃ₗ[R]
multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂) :=
(dom_dom_congr_linear_equiv M' M₂ R R (fin_sum_equiv_of_finset hk hl).symm).trans
(curry_sum_equiv R (fin k) M₂ M' (fin l))
variables {R M₂ M'}
@[simp]
lemma curry_fin_finset_apply {k l n : ℕ} {s : finset (fin n)}
(hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin n, M') M₂)
(mk : fin k → M') (ml : fin l → M') :
curry_fin_finset R M₂ M' hk hl f mk ml =
f (λ i, sum.elim mk ml ((fin_sum_equiv_of_finset hk hl).symm i)) :=
rfl
@[simp] lemma curry_fin_finset_symm_apply {k l n : ℕ} {s : finset (fin n)}
(hk : s.card = k) (hl : sᶜ.card = l)
(f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂))
(m : fin n → M') :
(curry_fin_finset R M₂ M' hk hl).symm f m =
f (λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inl i))
(λ i, m $ fin_sum_equiv_of_finset hk hl (sum.inr i)) :=
rfl
@[simp] lemma curry_fin_finset_symm_apply_piecewise_const {k l n : ℕ} {s : finset (fin n)}
(hk : s.card = k) (hl : sᶜ.card = l)
(f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (x y : M') :
(curry_fin_finset R M₂ M' hk hl).symm f (s.piecewise (λ _, x) (λ _, y)) = f (λ _, x) (λ _, y) :=
begin
rw curry_fin_finset_symm_apply, congr,
{ ext i, rw [fin_sum_equiv_of_finset_inl, finset.piecewise_eq_of_mem],
apply finset.order_emb_of_fin_mem },
{ ext i, rw [fin_sum_equiv_of_finset_inr, finset.piecewise_eq_of_not_mem],
exact finset.mem_compl.1 (finset.order_emb_of_fin_mem _ _ _) }
end
@[simp] lemma curry_fin_finset_symm_apply_const {k l n : ℕ} {s : finset (fin n)}
(hk : s.card = k) (hl : sᶜ.card = l)
(f : multilinear_map R (λ x : fin k, M') (multilinear_map R (λ x : fin l, M') M₂)) (x : M') :
(curry_fin_finset R M₂ M' hk hl).symm f (λ _, x) = f (λ _, x) (λ _, x) :=
rfl
@[simp] lemma curry_fin_finset_apply_const {k l n : ℕ} {s : finset (fin n)}
(hk : s.card = k) (hl : sᶜ.card = l) (f : multilinear_map R (λ x : fin n, M') M₂) (x y : M') :
curry_fin_finset R M₂ M' hk hl f (λ _, x) (λ _, y) = f (s.piecewise (λ _, x) (λ _, y)) :=
begin
refine (curry_fin_finset_symm_apply_piecewise_const hk hl _ _ _).symm.trans _, -- `rw` fails
rw linear_equiv.symm_apply_apply
end
end multilinear_map
end currying
section submodule
variables {R M M₂}
[ring R] [∀i, add_comm_monoid (M₁ i)] [add_comm_monoid M'] [add_comm_monoid M₂]
[∀i, module R (M₁ i)] [module R M'] [module R M₂]
namespace multilinear_map
/-- The pushforward of an indexed collection of submodule `p i ⊆ M₁ i` by `f : M₁ → M₂`.
Note that this is not a submodule - it is not closed under addition. -/
def map [nonempty ι] (f : multilinear_map R M₁ M₂) (p : Π i, submodule R (M₁ i)) :
sub_mul_action R M₂ :=
{ carrier := f '' { v | ∀ i, v i ∈ p i},
smul_mem' := λ c _ ⟨x, hx, hf⟩, let ⟨i⟩ := ‹nonempty ι› in by {
refine ⟨update x i (c • x i), λ j, if hij : j = i then _ else _, hf ▸ _⟩,
{ rw [hij, update_same], exact (p i).smul_mem _ (hx i) },
{ rw [update_noteq hij], exact hx j },
{ rw [f.map_smul, update_eq_self] } } }
/-- The map is always nonempty. This lemma is needed to apply `sub_mul_action.zero_mem`. -/
lemma map_nonempty [nonempty ι] (f : multilinear_map R M₁ M₂) (p : Π i, submodule R (M₁ i)) :
(map f p : set M₂).nonempty :=
⟨f 0, 0, λ i, (p i).zero_mem, rfl⟩
/-- The range of a multilinear map, closed under scalar multiplication. -/
def range [nonempty ι] (f : multilinear_map R M₁ M₂) : sub_mul_action R M₂ :=
f.map (λ i, ⊤)
end multilinear_map
end submodule
|
3c50b4173b0a6975410ef29e6f062ed48ab6b362 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/data/rat/basic.lean | 48caa5250d0dbe5080f130012a333b3c204f1806 | [
"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 | 31,728 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import data.equiv.encodable.basic
import algebra.euclidean_domain
import data.nat.gcd
import data.int.cast
/-!
# Basics for the Rational Numbers
## Summary
We define a rational number `q` as a structure `{ num, denom, pos, cop }`, where
- `num` is the numerator of `q`,
- `denom` is the denominator of `q`,
- `pos` is a proof that `denom > 0`, and
- `cop` is a proof `num` and `denom` are coprime.
We then define the expected (discrete) field structure on `ℚ` and prove basic lemmas about it.
Moreoever, we provide the expected casts from `ℕ` and `ℤ` into `ℚ`, i.e. `(↑n : ℚ) = n / 1`.
## Main Definitions
- `rat` is the structure encoding `ℚ`.
- `rat.mk n d` constructs a rational number `q = n / d` from `n d : ℤ`.
## Notations
- `/.` is infix notation for `rat.mk`.
## Tags
rat, rationals, field, ℚ, numerator, denominator, num, denom
-/
/-- `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 : 0 < denom)
(cop : num.nat_abs.coprime denom)
notation `ℚ` := rat
namespace rat
/-- String representation of a rational numbers, used in `has_repr`, `has_to_string`, and
`has_to_format` instances. -/
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 : ℕ // 0 < d ∧ 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⟩
lemma ext_iff {p q : ℚ} : p = q ↔ p.num = q.num ∧ p.denom = q.denom :=
by { cases p, cases q, simp }
@[ext] lemma ext {p q : ℚ} (hn : p.num = q.num) (hd : p.denom = q.denom) : p = q :=
rat.ext_iff.mpr ⟨hn, hd⟩
/-- 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 (d : ℕ) := mk_nat n d
| n -[1+ d] := mk_pnat (-n) d.succ_pnat
localized "infix ` /. `:70 := rat.mk" in rat
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_injective, 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_injective; 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_injective; simpa [left_distrib, eq_comm] using h },
{ change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ,
simp [left_distrib, sub_eq_add_neg], cc }
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 (dv.mul_left _) 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 (dv.mul_left _) 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 mul_right_cancel₀ 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
@[simp] theorem num_denom : ∀ {a : ℚ}, a.num /. a.denom = a
| ⟨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.symm
theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom'
/-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with rational
numbers of the form `n /. d` with `0 < d` and coprime `n`, `d`. -/
@[elab_as_eliminator] def {u} num_denom_cases_on {C : ℚ → Sort u}
: ∀ (a : ℚ) (H : ∀ n d, 0 < d → (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
/-- Define a (dependent) function or prove `∀ r : ℚ, p r` by dealing with rational
numbers of the form `n /. d` with `d ≠ 0`. -/
@[elab_as_eliminator] def {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 h.ne'
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
/-- Addition of rational numbers. Use `(+)` instead. -/
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
/-- Negation of rational numbers. Use `-r` instead. -/
protected def neg (r : ℚ) : ℚ :=
⟨-r.num, r.denom, r.pos, by simp [r.cop]⟩
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
@[simp] lemma mk_neg_denom (n d : ℤ) : n /. -d = -n /. d :=
begin
by_cases hd : d = 0;
simp [rat.mk_eq, hd]
end
/-- Multiplication of rational numbers. Use `(*)` instead. -/
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
/-- Inverse rational number. Use `r⁻¹` instead. -/
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₂]; cc
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, add_assoc]
protected theorem add_left_neg : -a + a = 0 :=
num_denom_cases_on' a $ λ n d h,
by simp [h]
@[simp] lemma mk_zero_one : 0 /. 1 = 0 :=
show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl }
@[simp] lemma mk_one_one : 1 /. 1 = 1 :=
show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl }
@[simp] lemma mk_neg_one_one : (-1) /. 1 = -1 :=
show mk_pnat _ _ = _, by { rw mk_pnat, simp, refl }
protected theorem mul_one : a * 1 = a :=
num_denom_cases_on' a $ λ n d h,
by { rw ← mk_one_one, simp [h, -mk_one_one] }
protected theorem one_mul : 1 * a = a :=
num_denom_cases_on' a $ λ n d h,
by { rw ← mk_one_one, simp [h, -mk_one_one] }
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:ℚ) :=
suffices (1:ℚ) = 0 → false, by cc,
by { rw [← mk_one_one, mk_eq_zero one_ne_zero], exact 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 simpa [h, n0, mul_comm] using @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 : 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,
exists_pair_ne := ⟨0, 1, rat.zero_ne_one⟩,
mul_inv_cancel := rat.mul_inv_cancel,
inv_zero := rfl }
/- Extra instances to short-circuit type class resolution -/
instance : division_ring ℚ := by apply_instance
instance : is_domain ℚ := by apply_instance
-- TODO(Mario): this instance slows down data.real.basic
instance : nontrivial ℚ := 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, sub_eq_add_neg]
@[simp] lemma denom_neg_eq_denom (q : ℚ) : (-q).denom = q.denom := rfl
@[simp] lemma num_neg_eq_neg_num (q : ℚ) : (-q).num = -(q.num) := rfl
@[simp] lemma num_zero : rat.num 0 = 0 := rfl
@[simp] lemma denom_zero : rat.denom 0 = 1 := rfl
lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 :=
have q = q.num /. q.denom, from num_denom.symm,
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
@[simp] lemma num_one : (1 : ℚ).num = 1 := rfl
@[simp] lemma denom_one : (1 : ℚ).denom = 1 := rfl
lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 :=
ne_of_gt q.pos
lemma eq_iff_mul_eq_mul {p q : ℚ} : p = q ↔ p.num * q.denom = q.num * p.denom :=
begin
conv_lhs { rw [←(@num_denom p), ←(@num_denom q)] },
apply rat.mk_eq,
{ exact_mod_cast p.denom_ne_zero },
{ exact_mod_cast q.denom_ne_zero }
end
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 simpa using this,
by simp [mul_def hq' hr', -num_denom]
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 r
... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by simp
... = (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 [num_denom],
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 },
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
lemma num_mk (n d : ℤ) :
(n /. d).num = d.sign * n / n.gcd d :=
begin
rcases d with ((_ | _) | _),
{ simp },
{ simpa [←int.coe_nat_succ, int.sign_coe_nat_of_nonzero] },
{ rw rat.mk,
simpa [rat.mk_pnat_num, int.neg_succ_of_nat_eq, ←int.coe_nat_succ,
int.sign_coe_nat_of_nonzero] }
end
lemma denom_mk (n d : ℤ) :
(n /. d).denom = if d = 0 then 1 else d.nat_abs / n.gcd d :=
begin
rcases d with ((_ | _) | _),
{ simp },
{ simpa [←int.coe_nat_succ, int.sign_coe_nat_of_nonzero] },
{ rw rat.mk,
simpa [rat.mk_pnat_denom, int.neg_succ_of_nat_eq, ←int.coe_nat_succ,
int.sign_coe_nat_of_nonzero] }
end
theorem mk_pnat_denom_dvd (n : ℤ) (d : ℕ+) :
(mk_pnat n d).denom ∣ d.1 :=
begin
rw mk_pnat_denom,
apply nat.div_dvd_of_dvd,
apply nat.gcd_dvd_right
end
theorem add_denom_dvd (q₁ q₂ : ℚ) : (q₁ + q₂).denom ∣ q₁.denom * q₂.denom :=
by { cases q₁, cases q₂, apply mk_pnat_denom_dvd }
theorem mul_denom_dvd (q₁ q₂ : ℚ) : (q₁ * q₂).denom ∣ q₁.denom * q₂.denom :=
by { cases q₁, cases q₂, apply mk_pnat_denom_dvd }
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)
lemma add_num_denom (q r : ℚ) : q + r =
((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ) :=
have hqd : (q.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 q.3,
have hrd : (r.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 r.3,
by conv_lhs { rw [←@num_denom q, ←@num_denom r, rat.add_def hqd hrd] };
simp [mul_comm]
section casts
protected lemma add_mk (a b c : ℤ) : (a + b) /. c = a /. c + b /. c :=
if h : c = 0 then by simp [h] else
by { rw [add_def h h, mk_eq h (mul_ne_zero h h)], simp [add_mul, mul_assoc] }
theorem coe_int_eq_mk : ∀ (z : ℤ), ↑z = z /. 1
| (n : ℕ) := show (n:ℚ) = n /. 1,
by induction n with n IH n; simp [*, rat.add_mk]
| -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin
induction n with n IH, { rw ← of_int_eq_mk, simp, refl },
show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1,
rw [neg_add, IH, ← mk_neg_one_one],
simp [-mk_neg_one_one]
end
theorem mk_eq_div (n d : ℤ) : n /. d = ((n : ℚ) / d) :=
begin
by_cases d0 : d = 0, {simp [d0, div_zero]},
simp [division_def, coe_int_eq_mk, mul_def one_ne_zero d0]
end
@[simp]
theorem num_div_denom (r : ℚ) : (r.num / r.denom : ℚ) = r :=
by rw [← int.cast_coe_nat, ← mk_eq_div, num_denom]
lemma exists_eq_mul_div_num_and_eq_mul_div_denom {n d : ℤ} (n_ne_zero : n ≠ 0)
(d_ne_zero : d ≠ 0) :
∃ (c : ℤ), n = c * ((n : ℚ) / d).num ∧ (d : ℤ) = c * ((n : ℚ) / d).denom :=
begin
have : ((n : ℚ) / d) = rat.mk n d, by rw [←rat.mk_eq_div],
exact rat.num_denom_mk n_ne_zero d_ne_zero this
end
theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z :=
(coe_int_eq_mk z).trans (of_int_eq_mk z).symm
@[simp, norm_cast] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n :=
by rw coe_int_eq_of_int; refl
@[simp, norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 :=
by rw coe_int_eq_of_int; refl
lemma coe_int_num_of_denom_eq_one {q : ℚ} (hq : q.denom = 1) : ↑(q.num) = q :=
by { conv_rhs { rw [←(@num_denom q), hq] }, rw [coe_int_eq_mk], refl }
lemma denom_eq_one_iff (r : ℚ) : r.denom = 1 ↔ ↑r.num = r :=
⟨rat.coe_int_num_of_denom_eq_one, λ h, h ▸ rat.coe_int_denom r.num⟩
instance : can_lift ℚ ℤ :=
⟨coe, λ q, q.denom = 1, λ q hq, ⟨q.num, coe_int_num_of_denom_eq_one hq⟩⟩
theorem coe_nat_eq_mk (n : ℕ) : ↑n = n /. 1 :=
by rw [← int.cast_coe_nat, coe_int_eq_mk]
@[simp, norm_cast] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n :=
by rw [← int.cast_coe_nat, coe_int_num]
@[simp, norm_cast] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 :=
by rw [← int.cast_coe_nat, coe_int_denom]
-- Will be subsumed by `int.coe_inj` after we have defined
-- `linear_ordered_field ℚ` (which implies characteristic zero).
lemma coe_int_inj (m n : ℤ) : (m : ℚ) = n ↔ m = n :=
⟨λ h, by simpa using congr_arg num h, congr_arg _⟩
end casts
lemma inv_def' {q : ℚ} : q⁻¹ = (q.denom : ℚ) / q.num :=
by { conv_lhs { rw ←(@num_denom q) }, cases q, simp [div_num_denom] }
@[simp] lemma mul_denom_eq_num {q : ℚ} : q * q.denom = q.num :=
begin
suffices : mk (q.num) ↑(q.denom) * mk ↑(q.denom) 1 = mk (q.num) 1, by
{ conv { for q [1] { rw ←(@num_denom q) }}, rwa [coe_int_eq_mk, coe_nat_eq_mk] },
have : (q.denom : ℤ) ≠ 0, from ne_of_gt (by exact_mod_cast q.pos),
rw [(rat.mul_def this one_ne_zero), (mul_comm (q.denom : ℤ) 1), (div_mk_div_cancel_left this)]
end
lemma denom_div_cast_eq_one_iff (m n : ℤ) (hn : n ≠ 0) :
((m : ℚ) / n).denom = 1 ↔ n ∣ m :=
begin
replace hn : (n:ℚ) ≠ 0, by rwa [ne.def, ← int.cast_zero, coe_int_inj],
split,
{ intro h,
lift ((m : ℚ) / n) to ℤ using h with k hk,
use k,
rwa [eq_div_iff_mul_eq hn, ← int.cast_mul, mul_comm, eq_comm, coe_int_inj] at hk },
{ rintros ⟨d, rfl⟩,
rw [int.cast_mul, mul_comm, mul_div_cancel _ hn, rat.coe_int_denom] }
end
lemma num_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) :
(a / b : ℚ).num = a :=
begin
lift b to ℕ using le_of_lt hb0,
norm_cast at hb0 h,
rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_num, pnat.mk_coe, h.gcd_eq_one,
int.coe_nat_one, int.div_one]
end
lemma denom_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) :
((a / b : ℚ).denom : ℤ) = b :=
begin
lift b to ℕ using le_of_lt hb0,
norm_cast at hb0 h,
rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_denom, pnat.mk_coe, h.gcd_eq_one,
nat.div_one]
end
lemma div_int_inj {a b c d : ℤ} (hb0 : 0 < b) (hd0 : 0 < d)
(h1 : nat.coprime a.nat_abs b.nat_abs) (h2 : nat.coprime c.nat_abs d.nat_abs)
(h : (a : ℚ) / b = (c : ℚ) / d) : a = c ∧ b = d :=
begin
apply and.intro,
{ rw [← (num_div_eq_of_coprime hb0 h1), h, num_div_eq_of_coprime hd0 h2] },
{ rw [← (denom_div_eq_of_coprime hb0 h1), h, denom_div_eq_of_coprime hd0 h2] }
end
@[norm_cast] lemma coe_int_div_self (n : ℤ) : ((n / n : ℤ) : ℚ) = n / n :=
begin
by_cases hn : n = 0,
{ subst hn, simp only [int.cast_zero, euclidean_domain.zero_div] },
{ have : (n : ℚ) ≠ 0, { rwa ← coe_int_inj at hn },
simp only [int.div_self hn, int.cast_one, ne.def, not_false_iff, div_self this] }
end
@[norm_cast] lemma coe_nat_div_self (n : ℕ) : ((n / n : ℕ) : ℚ) = n / n :=
coe_int_div_self n
lemma coe_int_div (a b : ℤ) (h : b ∣ a) : ((a / b : ℤ) : ℚ) = a / b :=
begin
rcases h with ⟨c, rfl⟩,
simp only [mul_comm b, int.mul_div_assoc c (dvd_refl b), int.cast_mul, mul_div_assoc,
coe_int_div_self]
end
lemma coe_nat_div (a b : ℕ) (h : b ∣ a) : ((a / b : ℕ) : ℚ) = a / b :=
begin
rcases h with ⟨c, rfl⟩,
simp only [mul_comm b, nat.mul_div_assoc c (dvd_refl b), nat.cast_mul, mul_div_assoc,
coe_nat_div_self]
end
lemma inv_coe_int_num {a : ℤ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 :=
begin
rw [rat.inv_def', rat.coe_int_num, rat.coe_int_denom, nat.cast_one, ←int.cast_one],
apply num_div_eq_of_coprime ha0,
rw int.nat_abs_one,
exact nat.coprime_one_left _,
end
lemma inv_coe_nat_num {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.num = 1 :=
inv_coe_int_num (by exact_mod_cast ha0 : 0 < (a : ℤ))
lemma inv_coe_int_denom {a : ℤ} (ha0 : 0 < a) : ((a : ℚ)⁻¹.denom : ℤ) = a :=
begin
rw [rat.inv_def', rat.coe_int_num, rat.coe_int_denom, nat.cast_one, ←int.cast_one],
apply denom_div_eq_of_coprime ha0,
rw int.nat_abs_one,
exact nat.coprime_one_left _,
end
lemma inv_coe_nat_denom {a : ℕ} (ha0 : 0 < a) : (a : ℚ)⁻¹.denom = a :=
by exact_mod_cast inv_coe_int_denom (by exact_mod_cast ha0 : 0 < (a : ℤ))
protected lemma «forall» {p : ℚ → Prop} : (∀ r, p r) ↔ ∀ a b : ℤ, p (a / b) :=
⟨λ h _ _, h _,
λ h q, (show q = q.num / q.denom, from by simp [rat.div_num_denom]).symm ▸ (h q.1 q.2)⟩
protected lemma «exists» {p : ℚ → Prop} : (∃ r, p r) ↔ ∃ a b : ℤ, p (a / b) :=
⟨λ ⟨r, hr⟩, ⟨r.num, r.denom, by rwa [← mk_eq_div, num_denom]⟩, λ ⟨a, b, h⟩, ⟨_, h⟩⟩
end rat
|
034058576a8f9b3650b9f940f408fb56f4e105dc | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/conv1.lean | b733c7000e4d04ec5a5465f40a409437e6cae3a4 | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | leanprover/lean4 | 4bdf9790294964627eb9be79f5e8f6157780b4cc | f1f9dc0f2f531af3312398999d8b8303fa5f096b | refs/heads/master | 1,693,360,665,786 | 1,693,350,868,000 | 1,693,350,868,000 | 129,571,436 | 2,827 | 311 | Apache-2.0 | 1,694,716,156,000 | 1,523,760,560,000 | Lean | UTF-8 | Lean | false | false | 5,026 | lean | import Lean
set_option pp.analyze false
def p (x y : Nat) := x = y
example (x y : Nat) : p (x + y) (y + x + 0) := by
conv =>
trace_state
whnf
tactic' => trace_state
trace_state
congr
next => rfl
any_goals whnf; rfl
conv' =>
trace_state
apply id ?x
conv =>
fail_if_success case x => whnf
trace_state
rw [Nat.add_comm]
rfl
def foo (x y : Nat) : Nat := x + y
example : foo (0 + a) (b + 0) = a + b := by
conv =>
apply id
lhs
trace_state
congr
trace_state
case x =>
simp
trace_state
fail_if_success case x => skip
case' y => skip
case y => skip
done
example : foo (0 + a) (b + 0) = a + b := by
conv =>
lhs
conv =>
congr
trace_state
focus
trace_state
tactic => simp
trace_state
all_goals dsimp (config := {}) []
simp [foo]
trace_state
example : foo (0 + a) (b + 0) = a + b := by
conv =>
lhs
congr <;> simp
fail_if_success lhs
try lhs
trace_state
example (x y : Nat) : p (x + y) (y + x + 0) := by
conv =>
whnf
rhs
whnf
trace_state
rw [Nat.add_comm]
rfl
example (x y : Nat) : p (x + y) (y + x + 0) := by
conv =>
whnf
lhs
whnf
conv =>
rhs
whnf
trace_state
apply Nat.add_comm x y
def f (x y z : Nat) : Nat :=
y
example (x y : Nat) : f x (x + y + 0) y = y + x := by
conv =>
lhs
arg 2
whnf
trace_state
simp [f]
apply Nat.add_comm
example (x y : Nat) : f x (x + y + 0) y = y + x := by
conv =>
lhs
arg 2
change x + y
trace_state
rw [Nat.add_comm]
example : id (fun x y => 0 + x + y) = Nat.add := by
conv =>
lhs
arg 1
ext a b
trace_state
rw [Nat.zero_add]
trace_state
example : id (fun x y => 0 + x + y) = Nat.add := by
conv =>
lhs
arg 1
intro a b
rw [Nat.zero_add]
example : id (fun x y => 0 + x + y) = Nat.add := by
conv =>
enter [1, 1, a, b]
trace_state
rw [Nat.zero_add]
example (p : Nat → Prop) (h : ∀ a, p a) : ∀ a, p (id (0 + a)) := by
conv =>
intro x
trace_state
arg 1
trace_state
simp only [id]
trace_state
rw [Nat.zero_add]
exact h
example (p : Prop) (x : Nat) : (x = x → p) → p := by
conv =>
congr
. trace_state
congr
. simp
trace_state
conv =>
lhs
simp
intros
assumption
example : (fun x => 0 + x) = id := by
conv =>
lhs
tactic => funext x
trace_state
rw [Nat.zero_add]
example (p : Prop) (x : Nat) : (x = x → p) → p := by
conv =>
apply implies_congr
. apply implies_congr
simp
trace_state
conv =>
lhs
simp
intros; assumption
example (x y : Nat) (f : Nat → Nat → Nat) (g : Nat → Nat) (h₁ : ∀ z, f z z = z) (h₂ : ∀ x y, f (g x) (g y) = y) : f (g (0 + y)) (f (g x) (g (0 + x))) = x := by
conv =>
pattern _ + _
apply Nat.zero_add
trace_state
conv =>
pattern 0 + _
apply Nat.zero_add
trace_state
simp [h₁, h₂]
example (x y : Nat) (h : y = 0) : x + ((y + x) + x) = x + (x + x) := by
conv =>
lhs
rhs
lhs
trace_state
rw [h, Nat.zero_add]
example (p : Nat → Prop) (x y : Nat) (h1 : y = 0) (h2 : p x) : p (y + x) := by
conv =>
rhs
trace_state
rw [h1]
apply Nat.zero_add
exact h2
example (p : (n : Nat) → Fin n → Prop) (i : Fin 5) (hp : p 5 i) (hi : j = i) : p 5 j := by
conv =>
arg 2
trace_state
rw [hi]
exact hp
example (p : {_ : Nat} → Nat → Prop) (x y : Nat) (h1 : y = 0) (h2 : @p x x) : @p (y + x) (y + x) := by
conv =>
enter [@1, 1]
trace_state
rw [h1]
conv =>
enter [@2, 1]
trace_state
rw [h1]
rw [Nat.zero_add]
exact h2
example (p : Nat → Prop) (x y : Nat) (h : y = 0) : p (y + x) := by
conv => lhs
example (p : Nat → Prop) (x y : Nat) (h : y = 0) : p (y + x) := by
conv => arg 2
example (p : Prop) : p := by
conv => rhs
example (p : (n : Nat) → Fin n → Prop) (i : Fin 5) (hp : p 5 i) : p 5 j := by
conv => arg 1
-- repeated `zeta`
example : let a := 0; let b := a; b = 0 := by
intros
conv =>
zeta
trace_state
example : ((x + y) + z : Nat) = x + (y + z) := by
conv in _ + _ => trace_state
conv in (occs := *) _ + _ => trace_state
conv in (occs := 1 3) _ + _ => trace_state
conv in (occs := 3 1) _ + _ => trace_state
conv in (occs := 2 3) _ + _ => trace_state
conv in (occs := 2 4) _ + _ => trace_state
apply Nat.add_assoc
example : ((x + y) + z : Nat) = x + (y + z) := by conv => pattern (occs := 5) _ + _
example : ((x + y) + z : Nat) = x + (y + z) := by conv => pattern (occs := 2 5) _ + _
example : ((x + y) + z : Nat) = x + (y + z) := by conv => pattern (occs := 1 5) _ + _
example : ((x + y) + z : Nat) = x + (y + z) := by conv => pattern (occs := 1 2 5) _ + _
macro "bla" : term => `(?a)
example : 1 = 1 := by conv => apply bla; congr
example (h : a = a') (H : a + a' = 0) : a + a = 0 := by
conv in (occs := 2) a => rw [h]
apply H
|
15a17aa855c2fa30a8b9171d365b8bbe9ac1973f | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/data/array/lemmas.lean | f8b896c8c4e79d0f699a98c0402a3fe2f419fd7b | [
"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 | 9,828 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Mario Carneiro
-/
import control.traversable.equiv
import data.vector.basic
universes u v w
namespace d_array
variables {n : ℕ} {α : fin n → Type u}
instance [∀ i, inhabited (α i)] : inhabited (d_array n α) :=
⟨⟨λ _, default _⟩⟩
end d_array
namespace array
instance {n α} [inhabited α] : inhabited (array n α) :=
d_array.inhabited
theorem to_list_of_heq {n₁ n₂ α} {a₁ : array n₁ α} {a₂ : array n₂ α}
(hn : n₁ = n₂) (ha : a₁ == a₂) : a₁.to_list = a₂.to_list :=
by congr; assumption
/- rev_list -/
section rev_list
variables {n : ℕ} {α : Type u} {a : array n α}
theorem rev_list_reverse_aux : ∀ i (h : i ≤ n) (t : list α),
(a.iterate_aux (λ _, (::)) i h []).reverse_core t = a.rev_iterate_aux (λ _, (::)) i h t
| 0 h t := rfl
| (i+1) h t := rev_list_reverse_aux i _ _
@[simp] theorem rev_list_reverse : a.rev_list.reverse = a.to_list :=
rev_list_reverse_aux _ _ _
@[simp] theorem to_list_reverse : a.to_list.reverse = a.rev_list :=
by rw [←rev_list_reverse, list.reverse_reverse]
end rev_list
/- mem -/
section mem
variables {n : ℕ} {α : Type u} {v : α} {a : array n α}
theorem mem.def : v ∈ a ↔ ∃ i, a.read i = v :=
iff.rfl
theorem mem_rev_list_aux : ∀ {i} (h : i ≤ n),
(∃ (j : fin n), (j : ℕ) < i ∧ read a j = v) ↔ v ∈ a.iterate_aux (λ _, (::)) i h []
| 0 _ := ⟨λ ⟨i, n, _⟩, absurd n i.val.not_lt_zero, false.elim⟩
| (i+1) h := let IH := mem_rev_list_aux (le_of_lt h) in
⟨λ ⟨j, ji1, e⟩, or.elim (lt_or_eq_of_le $ nat.le_of_succ_le_succ ji1)
(λ ji, list.mem_cons_of_mem _ $ IH.1 ⟨j, ji, e⟩)
(λ je, by simp [d_array.iterate_aux]; apply or.inl; unfold read at e;
have H : j = ⟨i, h⟩ := fin.eq_of_veq je; rwa [←H, e]),
λ m, begin
simp [d_array.iterate_aux, list.mem] at m,
cases m with e m',
exact ⟨⟨i, h⟩, nat.lt_succ_self _, eq.symm e⟩,
exact let ⟨j, ji, e⟩ := IH.2 m' in
⟨j, nat.le_succ_of_le ji, e⟩
end⟩
@[simp] theorem mem_rev_list : v ∈ a.rev_list ↔ v ∈ a :=
iff.symm $ iff.trans
(exists_congr $ λ j, iff.symm $
show j.1 < n ∧ read a j = v ↔ read a j = v,
from and_iff_right j.2)
(mem_rev_list_aux _)
@[simp] theorem mem_to_list : v ∈ a.to_list ↔ v ∈ a :=
by rw ←rev_list_reverse; exact list.mem_reverse.trans mem_rev_list
end mem
/- foldr -/
section foldr
variables {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : α → β → β} {a : array n α}
theorem rev_list_foldr_aux : ∀ {i} (h : i ≤ n),
(d_array.iterate_aux a (λ _, (::)) i h []).foldr f b = d_array.iterate_aux a (λ _, f) i h b
| 0 h := rfl
| (j+1) h := congr_arg (f (read a ⟨j, h⟩)) (rev_list_foldr_aux _)
theorem rev_list_foldr : a.rev_list.foldr f b = a.foldl b f :=
rev_list_foldr_aux _
end foldr
/- foldl -/
section foldl
variables {n : ℕ} {α : Type u} {β : Type w} {b : β} {f : β → α → β} {a : array n α}
theorem to_list_foldl : a.to_list.foldl f b = a.foldl b (function.swap f) :=
by rw [←rev_list_reverse, list.foldl_reverse, rev_list_foldr]
end foldl
/- length -/
section length
variables {n : ℕ} {α : Type u}
theorem rev_list_length_aux (a : array n α) (i h) :
(a.iterate_aux (λ _, (::)) i h []).length = i :=
by induction i; simp [*, d_array.iterate_aux]
@[simp] theorem rev_list_length (a : array n α) : a.rev_list.length = n :=
rev_list_length_aux a _ _
@[simp] theorem to_list_length (a : array n α) : a.to_list.length = n :=
by rw[←rev_list_reverse, list.length_reverse, rev_list_length]
end length
/- nth -/
section nth
variables {n : ℕ} {α : Type u} {a : array n α}
theorem to_list_nth_le_aux (i : ℕ) (ih : i < n) : ∀ j {jh t h'},
(∀ k tl, j + k = i → list.nth_le t k tl = a.read ⟨i, ih⟩) →
(a.rev_iterate_aux (λ _, (::)) j jh t).nth_le i h' = a.read ⟨i, ih⟩
| 0 _ _ _ al := al i _ $ zero_add _
| (j+1) jh t h' al := to_list_nth_le_aux j $ λ k tl hjk,
show list.nth_le (a.read ⟨j, jh⟩ :: t) k tl = a.read ⟨i, ih⟩, from
match k, hjk, tl with
| 0, e, tl := match i, e, ih with ._, rfl, _ := rfl end
| k'+1, _, tl := by simp[list.nth_le]; exact al _ _ (by simp [add_comm, add_assoc, *]; cc)
end
theorem to_list_nth_le (i : ℕ) (h h') : list.nth_le a.to_list i h' = a.read ⟨i, h⟩ :=
to_list_nth_le_aux _ _ _ (λ k tl, absurd tl k.not_lt_zero)
@[simp] theorem to_list_nth_le' (a : array n α) (i : fin n) (h') :
list.nth_le a.to_list i h' = a.read i :=
by cases i; apply to_list_nth_le
theorem to_list_nth {i v} : list.nth a.to_list i = some v ↔ ∃ h, a.read ⟨i, h⟩ = v :=
begin
rw list.nth_eq_some,
have ll := to_list_length a,
split; intro h; cases h with h e; subst v,
{ exact ⟨ll ▸ h, (to_list_nth_le _ _ _).symm⟩ },
{ exact ⟨ll.symm ▸ h, to_list_nth_le _ _ _⟩ }
end
theorem write_to_list {i v} : (a.write i v).to_list = a.to_list.update_nth i v :=
list.ext_le (by simp) $ λ j h₁ h₂, begin
have h₃ : j < n, {simpa using h₁},
rw [to_list_nth_le _ h₃],
refine let ⟨_, e⟩ := list.nth_eq_some.1 _ in e.symm,
by_cases ij : (i : ℕ) = j,
{ subst j, rw [show (⟨(i : ℕ), h₃⟩ : fin _) = i, from fin.eq_of_veq rfl,
array.read_write, list.nth_update_nth_of_lt],
simp [h₃] },
{ rw [list.nth_update_nth_ne _ _ ij, a.read_write_of_ne,
to_list_nth.2 ⟨h₃, rfl⟩],
exact fin.ne_of_vne ij }
end
end nth
/- enum -/
section enum
variables {n : ℕ} {α : Type u} {a : array n α}
theorem mem_to_list_enum {i v} : (i, v) ∈ a.to_list.enum ↔ ∃ h, a.read ⟨i, h⟩ = v :=
by simp [list.mem_iff_nth, to_list_nth, and.comm, and.assoc, and.left_comm]
end enum
/- to_array -/
section to_array
variables {n : ℕ} {α : Type u}
@[simp] theorem to_list_to_array (a : array n α) : a.to_list.to_array == a :=
heq_of_heq_of_eq
(@@eq.drec_on (λ m (e : a.to_list.length = m), (d_array.mk (λ v, a.to_list.nth_le v.1 v.2)) ==
(@d_array.mk m (λ _, α) $ λ v, a.to_list.nth_le v.1 $ e.symm ▸ v.2)) a.to_list_length heq.rfl) $
d_array.ext $ λ ⟨i, h⟩, to_list_nth_le i h _
@[simp] theorem to_array_to_list (l : list α) : l.to_array.to_list = l :=
list.ext_le (to_list_length _) $ λ n h1 h2, to_list_nth_le _ h2 _
end to_array
/- push_back -/
section push_back
variables {n : ℕ} {α : Type u} {v : α} {a : array n α}
lemma push_back_rev_list_aux : ∀ i h h',
d_array.iterate_aux (a.push_back v) (λ _, (::)) i h [] = d_array.iterate_aux a (λ _, (::)) i h' []
| 0 h h' := rfl
| (i+1) h h' := begin
simp [d_array.iterate_aux],
refine ⟨_, push_back_rev_list_aux _ _ _⟩,
dsimp [read, d_array.read, push_back],
rw [dif_neg], refl,
exact ne_of_lt h',
end
@[simp] theorem push_back_rev_list : (a.push_back v).rev_list = v :: a.rev_list :=
begin
unfold push_back rev_list foldl iterate d_array.iterate,
dsimp [d_array.iterate_aux, read, d_array.read, push_back],
rw [dif_pos (eq.refl n)],
apply congr_arg,
apply push_back_rev_list_aux
end
@[simp] theorem push_back_to_list : (a.push_back v).to_list = a.to_list ++ [v] :=
by rw [←rev_list_reverse, ←rev_list_reverse, push_back_rev_list, list.reverse_cons]
@[simp] lemma read_push_back_left (i : fin n) : (a.push_back v).read i.cast_succ = a.read i :=
begin
cases i with i hi,
have : ¬ i = n := ne_of_lt hi,
simp [push_back, this, fin.cast_succ, fin.cast_add, fin.cast_le, fin.cast_lt, read, d_array.read]
end
@[simp] lemma read_push_back_right : (a.push_back v).read (fin.last _) = v :=
begin
cases hn : fin.last n with k hk,
have : k = n := by simpa [fin.eq_iff_veq ] using hn.symm,
simp [push_back, this, fin.cast_succ, fin.cast_add, fin.cast_le, fin.cast_lt, read, d_array.read]
end
end push_back
/- foreach -/
section foreach
variables {n : ℕ} {α : Type u} {β : Type v} {i : fin n} {f : fin n → α → β} {a : array n α}
@[simp] theorem read_foreach : (foreach a f).read i = f i (a.read i) :=
rfl
end foreach
/- map -/
section map
variables {n : ℕ} {α : Type u} {β : Type v} {i : fin n} {f : α → β} {a : array n α}
theorem read_map : (a.map f).read i = f (a.read i) :=
read_foreach
end map
/- map₂ -/
section map₂
variables {n : ℕ} {α : Type u} {i : fin n} {f : α → α → α} {a₁ a₂ : array n α}
@[simp] theorem read_map₂ : (map₂ f a₁ a₂).read i = f (a₁.read i) (a₂.read i) :=
read_foreach
end map₂
end array
namespace equiv
/-- The natural equivalence between length-`n` heterogeneous arrays
and dependent functions from `fin n`. -/
def d_array_equiv_fin {n : ℕ} (α : fin n → Type*) : d_array n α ≃ (Π i, α i) :=
⟨d_array.read, d_array.mk, λ ⟨f⟩, rfl, λ f, rfl⟩
/-- The natural equivalence between length-`n` arrays and functions from `fin n`. -/
def array_equiv_fin (n : ℕ) (α : Type*) : array n α ≃ (fin n → α) :=
d_array_equiv_fin _
/-- The natural equivalence between length-`n` vectors and functions from `fin n`. -/
def vector_equiv_fin (α : Type*) (n : ℕ) : vector α n ≃ (fin n → α) :=
⟨vector.nth, vector.of_fn, vector.of_fn_nth, λ f, funext $ vector.nth_of_fn f⟩
/-- The natural equivalence between length-`n` vectors and length-`n` arrays. -/
def vector_equiv_array (α : Type*) (n : ℕ) : vector α n ≃ array n α :=
(vector_equiv_fin _ _).trans (array_equiv_fin _ _).symm
end equiv
namespace array
open function
variable {n : ℕ}
instance : traversable (array n) :=
@equiv.traversable (flip vector n) _ (λ α, equiv.vector_equiv_array α n) _
instance : is_lawful_traversable (array n) :=
@equiv.is_lawful_traversable (flip vector n) _ (λ α, equiv.vector_equiv_array α n) _ _
end array
|
51b66e3b864b47e038834c4ef92d880810e5260b | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/limits/shapes/finite_limits.lean | c2059ea5ba5b4126083c4341708dd0db4d5e181a | [
"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 | 8,573 | 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.fin_category
import category_theory.limits.shapes.binary_products
import category_theory.limits.shapes.equalizers
import category_theory.limits.shapes.wide_pullbacks
import category_theory.limits.shapes.pullbacks
import data.fintype.basic
/-!
# Categories with finite limits.
A typeclass for categories with all finite (co)limits.
-/
universes w' w v' u' v u
noncomputable theory
open category_theory
namespace category_theory.limits
variables (C : Type u) [category.{v} C]
/--
A category has all finite limits if every functor `J ⥤ C` with a `fin_category J`
instance and `J : Type` has a limit.
This is often called 'finitely complete'.
-/
-- We can't just made this an `abbreviation`
-- because of https://github.com/leanprover-community/lean/issues/429
class has_finite_limits : Prop :=
(out (J : Type) [𝒥 : small_category J] [@fin_category J 𝒥] : @has_limits_of_shape J 𝒥 C _)
@[priority 100]
instance has_limits_of_shape_of_has_finite_limits
(J : Type w) [small_category J] [fin_category J] [has_finite_limits C] :
has_limits_of_shape J C :=
begin
apply has_limits_of_shape_of_equivalence (fin_category.equiv_as_type J),
apply has_finite_limits.out
end
@[priority 100]
instance has_finite_limits_of_has_limits_of_size [has_limits_of_size.{v' u'} C] :
has_finite_limits C :=
⟨λ J hJ hJ', by { haveI := has_limits_of_size_shrink.{0 0} C,
exact has_limits_of_shape_of_equivalence (fin_category.equiv_as_type J) }⟩
/-- If `C` has all limits, it has finite limits. -/
@[priority 100]
instance has_finite_limits_of_has_limits [has_limits C] : has_finite_limits C :=
infer_instance
/-- We can always derive `has_finite_limits C` by providing limits at an
arbitrary universe. -/
lemma has_finite_limits_of_has_finite_limits_of_size
(h : ∀ (J : Type w) {𝒥 : small_category J} (hJ : @fin_category J 𝒥),
by { resetI, exact has_limits_of_shape J C }) :
has_finite_limits C :=
⟨λ J hJ hhJ,
begin
resetI,
letI : category.{w w} (ulift_hom.{w} (ulift.{w 0} J)),
{ apply ulift_hom.category.{0}, exact category_theory.ulift_category J },
haveI := h (ulift_hom.{w} (ulift.{w} J)) category_theory.fin_category_ulift,
exact has_limits_of_shape_of_equivalence (ulift_hom_ulift_category.equiv.{w w} J).symm
end ⟩
/--
A category has all finite colimits if every functor `J ⥤ C` with a `fin_category J`
instance and `J : Type` has a colimit.
This is often called 'finitely cocomplete'.
-/
class has_finite_colimits : Prop :=
(out (J : Type) [𝒥 : small_category J] [@fin_category J 𝒥] : @has_colimits_of_shape J 𝒥 C _)
@[priority 100]
instance has_colimits_of_shape_of_has_finite_colimits
(J : Type w) [small_category J] [fin_category J] [has_finite_colimits C] :
has_colimits_of_shape J C :=
begin
apply has_colimits_of_shape_of_equivalence (fin_category.equiv_as_type J),
apply has_finite_colimits.out
end
@[priority 100]
instance has_finite_colimits_of_has_colimits_of_size [has_colimits_of_size.{v' u'} C] :
has_finite_colimits C :=
⟨λ J hJ hJ', by { haveI := has_colimits_of_size_shrink.{0 0} C,
exact has_colimits_of_shape_of_equivalence (fin_category.equiv_as_type J) }⟩
/-- We can always derive `has_finite_colimits C` by providing colimits at an
arbitrary universe. -/
lemma has_finite_colimits_of_has_finite_colimits_of_size
(h : ∀ (J : Type w) {𝒥 : small_category J} (hJ : @fin_category J 𝒥),
by { resetI, exact has_colimits_of_shape J C }) :
has_finite_colimits C :=
⟨λ J hJ hhJ,
begin
resetI,
letI : category.{w w} (ulift_hom.{w} (ulift.{w 0} J)),
{ apply ulift_hom.category.{0}, exact category_theory.ulift_category J },
haveI := h (ulift_hom.{w} (ulift.{w} J)) category_theory.fin_category_ulift,
exact has_colimits_of_shape_of_equivalence (ulift_hom_ulift_category.equiv.{w w} J).symm
end ⟩
section
open walking_parallel_pair walking_parallel_pair_hom
instance fintype_walking_parallel_pair : fintype walking_parallel_pair :=
{ elems := [walking_parallel_pair.zero, walking_parallel_pair.one].to_finset,
complete := λ x, by { cases x; simp } }
local attribute [tidy] tactic.case_bash
instance (j j' : walking_parallel_pair) : fintype (walking_parallel_pair_hom j j') :=
{ elems := walking_parallel_pair.rec_on j
(walking_parallel_pair.rec_on j' [walking_parallel_pair_hom.id zero].to_finset
[left, right].to_finset)
(walking_parallel_pair.rec_on j' ∅ [walking_parallel_pair_hom.id one].to_finset),
complete := by tidy }
end
instance : fin_category walking_parallel_pair := { }
/-- Equalizers are finite limits, so if `C` has all finite limits, it also has all equalizers -/
example [has_finite_limits C] : has_equalizers C := by apply_instance
/-- Coequalizers are finite colimits, of if `C` has all finite colimits, it also has all
coequalizers -/
example [has_finite_colimits C] : has_coequalizers C := by apply_instance
variables {J : Type v}
local attribute [tidy] tactic.case_bash
namespace wide_pullback_shape
instance fintype_obj [fintype J] : fintype (wide_pullback_shape J) :=
by { rw wide_pullback_shape, apply_instance }
instance fintype_hom (j j' : wide_pullback_shape J) : fintype (j ⟶ j') :=
{ elems :=
begin
cases j',
{ cases j,
{ exact {hom.id none} },
{ exact {hom.term j} } },
{ by_cases some j' = j,
{ rw h,
exact {hom.id j} },
{ exact ∅ } }
end,
complete := by tidy }
end wide_pullback_shape
namespace wide_pushout_shape
instance fintype_obj [fintype J] : fintype (wide_pushout_shape J) :=
by { rw wide_pushout_shape, apply_instance }
instance fintype_hom (j j' : wide_pushout_shape J) : fintype (j ⟶ j') :=
{ elems :=
begin
cases j,
{ cases j',
{ exact {hom.id none} },
{ exact {hom.init j'} } },
{ by_cases some j = j',
{ rw h,
exact {hom.id j'} },
{ exact ∅ } }
end,
complete := by tidy }
end wide_pushout_shape
instance fin_category_wide_pullback [fintype J] : fin_category (wide_pullback_shape J) :=
{ fintype_hom := wide_pullback_shape.fintype_hom }
instance fin_category_wide_pushout [fintype J] :
fin_category (wide_pushout_shape J) :=
{ fintype_hom := wide_pushout_shape.fintype_hom }
/--
`has_finite_wide_pullbacks` represents a choice of wide pullback
for every finite collection of morphisms
-/
-- We can't just made this an `abbreviation`
-- because of https://github.com/leanprover-community/lean/issues/429
class has_finite_wide_pullbacks : Prop :=
(out (J : Type) [fintype J] : has_limits_of_shape (wide_pullback_shape J) C)
instance has_limits_of_shape_wide_pullback_shape
(J : Type) [finite J] [has_finite_wide_pullbacks C] :
has_limits_of_shape (wide_pullback_shape J) C :=
by { casesI nonempty_fintype J, haveI := @has_finite_wide_pullbacks.out C _ _ J, apply_instance }
/--
`has_finite_wide_pushouts` represents a choice of wide pushout
for every finite collection of morphisms
-/
class has_finite_wide_pushouts : Prop :=
(out (J : Type) [fintype J] : has_colimits_of_shape (wide_pushout_shape J) C)
instance has_colimits_of_shape_wide_pushout_shape
(J : Type) [finite J] [has_finite_wide_pushouts C] :
has_colimits_of_shape (wide_pushout_shape J) C :=
by { casesI nonempty_fintype J, haveI := @has_finite_wide_pushouts.out C _ _ J, apply_instance }
/--
Finite wide pullbacks are finite limits, so if `C` has all finite limits,
it also has finite wide pullbacks
-/
lemma has_finite_wide_pullbacks_of_has_finite_limits [has_finite_limits C] :
has_finite_wide_pullbacks C :=
⟨λ J _, by exactI has_finite_limits.out _⟩
/--
Finite wide pushouts are finite colimits, so if `C` has all finite colimits,
it also has finite wide pushouts
-/
lemma has_finite_wide_pushouts_of_has_finite_limits [has_finite_colimits C] :
has_finite_wide_pushouts C :=
⟨λ J _, by exactI has_finite_colimits.out _⟩
instance fintype_walking_pair : fintype walking_pair :=
{ elems := {walking_pair.left, walking_pair.right},
complete := λ x, by { cases x; simp } }
/-- Pullbacks are finite limits, so if `C` has all finite limits, it also has all pullbacks -/
example [has_finite_wide_pullbacks C] : has_pullbacks C := by apply_instance
/-- Pushouts are finite colimits, so if `C` has all finite colimits, it also has all pushouts -/
example [has_finite_wide_pushouts C] : has_pushouts C := by apply_instance
end category_theory.limits
|
e75a95ffde79c9e32f8c9c74c7cf004d6c6be523 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/compiler/StackOverflowTask.lean | 87e7ab9ddeeb37db746fc47b6e982e39b888b40f | [
"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 | 136 | lean | partial def foo : Nat → Nat | n => foo n + 1
@[never_extract]
def main : IO Unit := IO.println $ Task.get $ Task.spawn fun _ => foo 0
|
06abbf936cd9a92b0edf1054bdb1db0e3953c293 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/inner_product_space/pi_L2.lean | 1ed855d2f4947ab309a2fd85643e9777cac0c70e | [
"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 | 36,838 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Sébastien Gouëzel, Heather Macbeth
-/
import analysis.inner_product_space.projection
import analysis.normed_space.pi_Lp
import linear_algebra.finite_dimensional
import linear_algebra.unitary_group
/-!
# `L²` inner product space structure on finite products of inner product spaces
The `L²` norm on a finite product of inner product spaces is compatible with an inner product
$$
\langle x, y\rangle = \sum \langle x_i, y_i \rangle.
$$
This is recorded in this file as an inner product space instance on `pi_Lp 2`.
This file develops the notion of a finite dimensional Hilbert space over `𝕜 = ℂ, ℝ`, referred to as
`E`. We define an `orthonormal_basis 𝕜 ι E` as a linear isometric equivalence
between `E` and `euclidean_space 𝕜 ι`. Then `std_orthonormal_basis` shows that such an equivalence
always exists if `E` is finite dimensional. We provide language for converting between a basis
that is orthonormal and an orthonormal basis (e.g. `basis.to_orthonormal_basis`). We show that
orthonormal bases for each summand in a direct sum of spaces can be combined into an orthonormal
basis for the the whole sum in `direct_sum.submodule_is_internal.subordinate_orthonormal_basis`. In
the last section, various properties of matrices are explored.
## Main definitions
- `euclidean_space 𝕜 n`: defined to be `pi_Lp 2 (n → 𝕜)` for any `fintype n`, i.e., the space
from functions to `n` to `𝕜` with the `L²` norm. We register several instances on it (notably
that it is a finite-dimensional inner product space).
- `orthonormal_basis 𝕜 ι`: defined to be an isometry to Euclidean space from a given
finite-dimensional innner product space, `E ≃ₗᵢ[𝕜] euclidean_space 𝕜 ι`.
- `basis.to_orthonormal_basis`: constructs an `orthonormal_basis` for a finite-dimensional
Euclidean space from a `basis` which is `orthonormal`.
- `orthonormal.exists_orthonormal_basis_extension`: provides an existential result of an
`orthonormal_basis` extending a given orthonormal set
- `exists_orthonormal_basis`: provides an orthonormal basis on a finite dimensional vector space
- `std_orthonormal_basis`: provides an arbitrarily-chosen `orthonormal_basis` of a given finite
dimensional inner product space
For consequences in infinite dimension (Hilbert bases, etc.), see the file
`analysis.inner_product_space.l2_space`.
-/
open real set filter is_R_or_C submodule function
open_locale big_operators uniformity topological_space nnreal ennreal complex_conjugate direct_sum
noncomputable theory
variables {ι : Type*} {ι' : Type*}
variables {𝕜 : Type*} [is_R_or_C 𝕜] {E : Type*} [inner_product_space 𝕜 E]
variables {E' : Type*} [inner_product_space 𝕜 E']
variables {F : Type*} [inner_product_space ℝ F]
variables {F' : Type*} [inner_product_space ℝ F']
local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y
/-
If `ι` is a finite type and each space `f i`, `i : ι`, is an inner product space,
then `Π i, f i` is an inner product space as well. Since `Π i, f i` is endowed with the sup norm,
we use instead `pi_Lp 2 f` for the product space, which is endowed with the `L^2` norm.
-/
instance pi_Lp.inner_product_space {ι : Type*} [fintype ι] (f : ι → Type*)
[Π i, inner_product_space 𝕜 (f i)] : inner_product_space 𝕜 (pi_Lp 2 f) :=
{ to_normed_add_comm_group := infer_instance,
inner := λ x y, ∑ i, inner (x i) (y i),
norm_sq_eq_inner := λ x,
by simp only [pi_Lp.norm_sq_eq_of_L2, add_monoid_hom.map_sum, ← norm_sq_eq_inner, one_div],
conj_sym :=
begin
intros x y,
unfold inner,
rw ring_hom.map_sum,
apply finset.sum_congr rfl,
rintros z -,
apply inner_conj_sym,
end,
add_left := λ x y z,
show ∑ i, inner (x i + y i) (z i) = ∑ i, inner (x i) (z i) + ∑ i, inner (y i) (z i),
by simp only [inner_add_left, finset.sum_add_distrib],
smul_left := λ x y r,
show ∑ (i : ι), inner (r • x i) (y i) = (conj r) * ∑ i, inner (x i) (y i),
by simp only [finset.mul_sum, inner_smul_left] }
@[simp] lemma pi_Lp.inner_apply {ι : Type*} [fintype ι] {f : ι → Type*}
[Π i, inner_product_space 𝕜 (f i)] (x y : pi_Lp 2 f) :
⟪x, y⟫ = ∑ i, ⟪x i, y i⟫ :=
rfl
/-- The standard real/complex Euclidean space, functions on a finite type. For an `n`-dimensional
space use `euclidean_space 𝕜 (fin n)`. -/
@[reducible, nolint unused_arguments]
def euclidean_space (𝕜 : Type*) [is_R_or_C 𝕜]
(n : Type*) [fintype n] : Type* := pi_Lp 2 (λ (i : n), 𝕜)
lemma euclidean_space.nnnorm_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n]
(x : euclidean_space 𝕜 n) : ‖x‖₊ = nnreal.sqrt (∑ i, ‖x i‖₊ ^ 2) :=
pi_Lp.nnnorm_eq_of_L2 x
lemma euclidean_space.norm_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n]
(x : euclidean_space 𝕜 n) : ‖x‖ = real.sqrt (∑ i, ‖x i‖ ^ 2) :=
by simpa only [real.coe_sqrt, nnreal.coe_sum] using congr_arg (coe : ℝ≥0 → ℝ) x.nnnorm_eq
lemma euclidean_space.dist_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n]
(x y : euclidean_space 𝕜 n) : dist x y = (∑ i, dist (x i) (y i) ^ 2).sqrt :=
(pi_Lp.dist_eq_of_L2 x y : _)
lemma euclidean_space.nndist_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n]
(x y : euclidean_space 𝕜 n) : nndist x y = (∑ i, nndist (x i) (y i) ^ 2).sqrt :=
(pi_Lp.nndist_eq_of_L2 x y : _)
lemma euclidean_space.edist_eq {𝕜 : Type*} [is_R_or_C 𝕜] {n : Type*} [fintype n]
(x y : euclidean_space 𝕜 n) : edist x y = (∑ i, edist (x i) (y i) ^ 2) ^ (1 / 2 : ℝ) :=
(pi_Lp.edist_eq_of_L2 x y : _)
variables [fintype ι]
section
local attribute [reducible] pi_Lp
instance : finite_dimensional 𝕜 (euclidean_space 𝕜 ι) := by apply_instance
instance : inner_product_space 𝕜 (euclidean_space 𝕜 ι) := by apply_instance
@[simp] lemma finrank_euclidean_space :
finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 ι) = fintype.card ι := by simp
lemma finrank_euclidean_space_fin {n : ℕ} :
finite_dimensional.finrank 𝕜 (euclidean_space 𝕜 (fin n)) = n := by simp
lemma euclidean_space.inner_eq_star_dot_product (x y : euclidean_space 𝕜 ι) :
⟪x, y⟫ = matrix.dot_product (star $ pi_Lp.equiv _ _ x) (pi_Lp.equiv _ _ y) := rfl
/-- A finite, mutually orthogonal family of subspaces of `E`, which span `E`, induce an isometry
from `E` to `pi_Lp 2` of the subspaces equipped with the `L2` inner product. -/
def direct_sum.is_internal.isometry_L2_of_orthogonal_family
[decidable_eq ι] {V : ι → submodule 𝕜 E} (hV : direct_sum.is_internal V)
(hV' : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) :
E ≃ₗᵢ[𝕜] pi_Lp 2 (λ i, V i) :=
begin
let e₁ := direct_sum.linear_equiv_fun_on_fintype 𝕜 ι (λ i, V i),
let e₂ := linear_equiv.of_bijective (direct_sum.coe_linear_map V) hV.injective hV.surjective,
refine (e₂.symm.trans e₁).isometry_of_inner _,
suffices : ∀ v w, ⟪v, w⟫ = ⟪e₂ (e₁.symm v), e₂ (e₁.symm w)⟫,
{ intros v₀ w₀,
convert this (e₁ (e₂.symm v₀)) (e₁ (e₂.symm w₀));
simp only [linear_equiv.symm_apply_apply, linear_equiv.apply_symm_apply] },
intros v w,
transitivity ⟪(∑ i, (V i).subtypeₗᵢ (v i)), ∑ i, (V i).subtypeₗᵢ (w i)⟫,
{ simp only [sum_inner, hV'.inner_right_fintype, pi_Lp.inner_apply] },
{ congr; simp }
end
@[simp] lemma direct_sum.is_internal.isometry_L2_of_orthogonal_family_symm_apply
[decidable_eq ι] {V : ι → submodule 𝕜 E} (hV : direct_sum.is_internal V)
(hV' : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ))
(w : pi_Lp 2 (λ i, V i)) :
(hV.isometry_L2_of_orthogonal_family hV').symm w = ∑ i, (w i : E) :=
begin
classical,
let e₁ := direct_sum.linear_equiv_fun_on_fintype 𝕜 ι (λ i, V i),
let e₂ := linear_equiv.of_bijective (direct_sum.coe_linear_map V) hV.injective hV.surjective,
suffices : ∀ v : ⨁ i, V i, e₂ v = ∑ i, e₁ v i,
{ exact this (e₁.symm w) },
intros v,
simp [e₂, direct_sum.coe_linear_map, direct_sum.to_module, dfinsupp.sum_add_hom_apply]
end
end
variables (ι 𝕜)
-- TODO : This should be generalized to `pi_Lp` with finite dimensional factors.
/-- `pi_Lp.linear_equiv` upgraded to a continuous linear map between `euclidean_space 𝕜 ι`
and `ι → 𝕜`. -/
@[simps] def euclidean_space.equiv :
euclidean_space 𝕜 ι ≃L[𝕜] (ι → 𝕜) :=
(pi_Lp.linear_equiv 2 𝕜 (λ i : ι, 𝕜)).to_continuous_linear_equiv
variables {ι 𝕜}
-- TODO : This should be generalized to `pi_Lp`.
/-- The projection on the `i`-th coordinate of `euclidean_space 𝕜 ι`, as a linear map. -/
@[simps] def euclidean_space.projₗ (i : ι) :
euclidean_space 𝕜 ι →ₗ[𝕜] 𝕜 :=
(linear_map.proj i).comp (pi_Lp.linear_equiv 2 𝕜 (λ i : ι, 𝕜) : euclidean_space 𝕜 ι →ₗ[𝕜] ι → 𝕜)
-- TODO : This should be generalized to `pi_Lp`.
/-- The projection on the `i`-th coordinate of `euclidean_space 𝕜 ι`,
as a continuous linear map. -/
@[simps] def euclidean_space.proj (i : ι) :
euclidean_space 𝕜 ι →L[𝕜] 𝕜 :=
⟨euclidean_space.projₗ i, continuous_apply i⟩
-- TODO : This should be generalized to `pi_Lp`.
/-- The vector given in euclidean space by being `1 : 𝕜` at coordinate `i : ι` and `0 : 𝕜` at
all other coordinates. -/
def euclidean_space.single [decidable_eq ι] (i : ι) (a : 𝕜) :
euclidean_space 𝕜 ι :=
(pi_Lp.equiv _ _).symm (pi.single i a)
@[simp] lemma pi_Lp.equiv_single [decidable_eq ι] (i : ι) (a : 𝕜) :
pi_Lp.equiv _ _ (euclidean_space.single i a) = pi.single i a := rfl
@[simp] lemma pi_Lp.equiv_symm_single [decidable_eq ι] (i : ι) (a : 𝕜) :
(pi_Lp.equiv _ _).symm (pi.single i a) = euclidean_space.single i a := rfl
@[simp] theorem euclidean_space.single_apply [decidable_eq ι] (i : ι) (a : 𝕜) (j : ι) :
(euclidean_space.single i a) j = ite (j = i) a 0 :=
by { rw [euclidean_space.single, pi_Lp.equiv_symm_apply, ← pi.single_apply i a j] }
lemma euclidean_space.inner_single_left [decidable_eq ι] (i : ι) (a : 𝕜) (v : euclidean_space 𝕜 ι) :
⟪euclidean_space.single i (a : 𝕜), v⟫ = conj a * (v i) :=
by simp [apply_ite conj]
lemma euclidean_space.inner_single_right [decidable_eq ι] (i : ι) (a : 𝕜)
(v : euclidean_space 𝕜 ι) :
⟪v, euclidean_space.single i (a : 𝕜)⟫ = a * conj (v i) :=
by simp [apply_ite conj, mul_comm]
lemma euclidean_space.pi_Lp_congr_left_single [decidable_eq ι] {ι' : Type*} [fintype ι']
[decidable_eq ι'] (e : ι' ≃ ι) (i' : ι') :
linear_isometry_equiv.pi_Lp_congr_left 2 𝕜 𝕜 e (euclidean_space.single i' (1:𝕜)) =
euclidean_space.single (e i') (1:𝕜) :=
begin
ext i,
simpa using if_congr e.symm_apply_eq rfl rfl
end
variables (ι 𝕜 E)
/-- An orthonormal basis on E is an identification of `E` with its dimensional-matching
`euclidean_space 𝕜 ι`. -/
structure orthonormal_basis := of_repr :: (repr : E ≃ₗᵢ[𝕜] euclidean_space 𝕜 ι)
variables {ι 𝕜 E}
namespace orthonormal_basis
instance : inhabited (orthonormal_basis ι 𝕜 (euclidean_space 𝕜 ι)) :=
⟨of_repr (linear_isometry_equiv.refl 𝕜 (euclidean_space 𝕜 ι))⟩
/-- `b i` is the `i`th basis vector. -/
instance : has_coe_to_fun (orthonormal_basis ι 𝕜 E) (λ _, ι → E) :=
{ coe := λ b i, by classical; exact b.repr.symm (euclidean_space.single i (1 : 𝕜)) }
@[simp] lemma coe_of_repr [decidable_eq ι] (e : E ≃ₗᵢ[𝕜] euclidean_space 𝕜 ι) :
⇑(orthonormal_basis.of_repr e) = λ i, e.symm (euclidean_space.single i (1 : 𝕜)) :=
begin
rw coe_fn,
unfold has_coe_to_fun.coe,
funext,
congr,
simp only [eq_iff_true_of_subsingleton],
end
@[simp] protected lemma repr_symm_single [decidable_eq ι] (b : orthonormal_basis ι 𝕜 E) (i : ι) :
b.repr.symm (euclidean_space.single i (1:𝕜)) = b i :=
by { classical, congr, simp, }
@[simp] protected lemma repr_self [decidable_eq ι] (b : orthonormal_basis ι 𝕜 E) (i : ι) :
b.repr (b i) = euclidean_space.single i (1:𝕜) :=
by rw [← b.repr_symm_single i, linear_isometry_equiv.apply_symm_apply]
protected lemma repr_apply_apply (b : orthonormal_basis ι 𝕜 E) (v : E) (i : ι) :
b.repr v i = ⟪b i, v⟫ :=
begin
classical,
rw [← b.repr.inner_map_map (b i) v, b.repr_self i, euclidean_space.inner_single_left],
simp only [one_mul, eq_self_iff_true, map_one],
end
@[simp]
protected lemma orthonormal (b : orthonormal_basis ι 𝕜 E) : orthonormal 𝕜 b :=
begin
classical,
rw orthonormal_iff_ite,
intros i j,
rw [← b.repr.inner_map_map (b i) (b j), b.repr_self i, b.repr_self j,
euclidean_space.inner_single_left, euclidean_space.single_apply, map_one, one_mul],
end
/-- The `basis ι 𝕜 E` underlying the `orthonormal_basis` -/
protected def to_basis (b : orthonormal_basis ι 𝕜 E) : basis ι 𝕜 E :=
basis.of_equiv_fun b.repr.to_linear_equiv
@[simp] protected lemma coe_to_basis (b : orthonormal_basis ι 𝕜 E) :
(⇑b.to_basis : ι → E) = ⇑b :=
begin
change ⇑(basis.of_equiv_fun b.repr.to_linear_equiv) = b,
ext j,
rw basis.coe_of_equiv_fun,
congr,
end
@[simp] protected lemma coe_to_basis_repr (b : orthonormal_basis ι 𝕜 E) :
b.to_basis.equiv_fun = b.repr.to_linear_equiv :=
begin
change (basis.of_equiv_fun b.repr.to_linear_equiv).equiv_fun = b.repr.to_linear_equiv,
ext x j,
simp only [basis.of_equiv_fun_repr_apply, linear_isometry_equiv.coe_to_linear_equiv,
basis.equiv_fun_apply],
end
@[simp] protected lemma coe_to_basis_repr_apply (b : orthonormal_basis ι 𝕜 E) (x : E) (i : ι) :
b.to_basis.repr x i = b.repr x i :=
by {rw [← basis.equiv_fun_apply, orthonormal_basis.coe_to_basis_repr,
linear_isometry_equiv.coe_to_linear_equiv]}
protected lemma sum_repr (b : orthonormal_basis ι 𝕜 E) (x : E) :
∑ i, b.repr x i • b i = x :=
by { simp_rw [← b.coe_to_basis_repr_apply, ← b.coe_to_basis], exact b.to_basis.sum_repr x }
protected lemma sum_repr_symm (b : orthonormal_basis ι 𝕜 E) (v : euclidean_space 𝕜 ι) :
∑ i , v i • b i = (b.repr.symm v) :=
by { simpa using (b.to_basis.equiv_fun_symm_apply v).symm }
protected lemma sum_inner_mul_inner (b : orthonormal_basis ι 𝕜 E) (x y : E) :
∑ i, ⟪x, b i⟫ * ⟪b i, y⟫ = ⟪x, y⟫ :=
begin
have := congr_arg (@innerSL 𝕜 _ _ _ x) (b.sum_repr y),
rw map_sum at this,
convert this,
ext i,
rw [smul_hom_class.map_smul, b.repr_apply_apply, mul_comm],
refl,
end
protected lemma orthogonal_projection_eq_sum {U : submodule 𝕜 E} [complete_space U]
(b : orthonormal_basis ι 𝕜 U) (x : E) :
orthogonal_projection U x = ∑ i, ⟪(b i : E), x⟫ • b i :=
by simpa only [b.repr_apply_apply, inner_orthogonal_projection_eq_of_mem_left]
using (b.sum_repr (orthogonal_projection U x)).symm
/-- Mapping an orthonormal basis along a `linear_isometry_equiv`. -/
protected def map {G : Type*} [inner_product_space 𝕜 G] (b : orthonormal_basis ι 𝕜 E)
(L : E ≃ₗᵢ[𝕜] G) :
orthonormal_basis ι 𝕜 G :=
{ repr := L.symm.trans b.repr }
@[simp] protected lemma map_apply {G : Type*} [inner_product_space 𝕜 G]
(b : orthonormal_basis ι 𝕜 E) (L : E ≃ₗᵢ[𝕜] G) (i : ι) :
b.map L i = L (b i) := rfl
@[simp] protected lemma to_basis_map {G : Type*} [inner_product_space 𝕜 G]
(b : orthonormal_basis ι 𝕜 E) (L : E ≃ₗᵢ[𝕜] G) :
(b.map L).to_basis = b.to_basis.map L.to_linear_equiv :=
rfl
/-- A basis that is orthonormal is an orthonormal basis. -/
def _root_.basis.to_orthonormal_basis (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) :
orthonormal_basis ι 𝕜 E :=
orthonormal_basis.of_repr $
linear_equiv.isometry_of_inner v.equiv_fun
begin
intros x y,
let p : euclidean_space 𝕜 ι := v.equiv_fun x,
let q : euclidean_space 𝕜 ι := v.equiv_fun y,
have key : ⟪p, q⟫ = ⟪∑ i, p i • v i, ∑ i, q i • v i⟫,
{ simp [sum_inner, inner_smul_left, hv.inner_right_fintype] },
convert key,
{ rw [← v.equiv_fun.symm_apply_apply x, v.equiv_fun_symm_apply] },
{ rw [← v.equiv_fun.symm_apply_apply y, v.equiv_fun_symm_apply] }
end
@[simp] lemma _root_.basis.coe_to_orthonormal_basis_repr (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) :
((v.to_orthonormal_basis hv).repr : E → euclidean_space 𝕜 ι) = v.equiv_fun :=
rfl
@[simp] lemma _root_.basis.coe_to_orthonormal_basis_repr_symm
(v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) :
((v.to_orthonormal_basis hv).repr.symm : euclidean_space 𝕜 ι → E) = v.equiv_fun.symm :=
rfl
@[simp] lemma _root_.basis.to_basis_to_orthonormal_basis (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) :
(v.to_orthonormal_basis hv).to_basis = v :=
by simp [basis.to_orthonormal_basis, orthonormal_basis.to_basis]
@[simp] lemma _root_.basis.coe_to_orthonormal_basis (v : basis ι 𝕜 E) (hv : orthonormal 𝕜 v) :
(v.to_orthonormal_basis hv : ι → E) = (v : ι → E) :=
calc (v.to_orthonormal_basis hv : ι → E) = ((v.to_orthonormal_basis hv).to_basis : ι → E) :
by { classical, rw orthonormal_basis.coe_to_basis }
... = (v : ι → E) : by simp
variable {v : ι → E}
/-- A finite orthonormal set that spans is an orthonormal basis -/
protected def mk (hon : orthonormal 𝕜 v) (hsp: ⊤ ≤ submodule.span 𝕜 (set.range v)):
orthonormal_basis ι 𝕜 E :=
(basis.mk (orthonormal.linear_independent hon) hsp).to_orthonormal_basis (by rwa basis.coe_mk)
@[simp]
protected lemma coe_mk (hon : orthonormal 𝕜 v) (hsp: ⊤ ≤ submodule.span 𝕜 (set.range v)) :
⇑(orthonormal_basis.mk hon hsp) = v :=
by classical; rw [orthonormal_basis.mk, _root_.basis.coe_to_orthonormal_basis, basis.coe_mk]
/-- Any finite subset of a orthonormal family is an `orthonormal_basis` for its span. -/
protected def span {v' : ι' → E} (h : orthonormal 𝕜 v') (s : finset ι') :
orthonormal_basis s 𝕜 (span 𝕜 (s.image v' : set E)) :=
let
e₀' : basis s 𝕜 _ := basis.span (h.linear_independent.comp (coe : s → ι') subtype.coe_injective),
e₀ : orthonormal_basis s 𝕜 _ := orthonormal_basis.mk
begin
convert orthonormal_span (h.comp (coe : s → ι') subtype.coe_injective),
ext,
simp [e₀', basis.span_apply],
end e₀'.span_eq.ge,
φ : span 𝕜 (s.image v' : set E) ≃ₗᵢ[𝕜] span 𝕜 (range (v' ∘ (coe : s → ι'))) :=
linear_isometry_equiv.of_eq _ _
begin
rw [finset.coe_image, image_eq_range],
refl
end
in
e₀.map φ.symm
@[simp] protected lemma span_apply {v' : ι' → E} (h : orthonormal 𝕜 v') (s : finset ι') (i : s) :
(orthonormal_basis.span h s i : E) = v' i :=
by simp only [orthonormal_basis.span, basis.span_apply, linear_isometry_equiv.of_eq_symm,
orthonormal_basis.map_apply, orthonormal_basis.coe_mk,
linear_isometry_equiv.coe_of_eq_apply]
open submodule
/-- A finite orthonormal family of vectors whose span has trivial orthogonal complement is an
orthonormal basis. -/
protected def mk_of_orthogonal_eq_bot (hon : orthonormal 𝕜 v) (hsp : (span 𝕜 (set.range v))ᗮ = ⊥) :
orthonormal_basis ι 𝕜 E :=
orthonormal_basis.mk hon
begin
refine eq.ge _,
haveI : finite_dimensional 𝕜 (span 𝕜 (range v)) :=
finite_dimensional.span_of_finite 𝕜 (finite_range v),
haveI : complete_space (span 𝕜 (range v)) := finite_dimensional.complete 𝕜 _,
rwa orthogonal_eq_bot_iff at hsp,
end
@[simp] protected lemma coe_of_orthogonal_eq_bot_mk (hon : orthonormal 𝕜 v)
(hsp : (span 𝕜 (set.range v))ᗮ = ⊥) :
⇑(orthonormal_basis.mk_of_orthogonal_eq_bot hon hsp) = v :=
orthonormal_basis.coe_mk hon _
variables [fintype ι']
/-- `b.reindex (e : ι ≃ ι')` is an `orthonormal_basis` indexed by `ι'` -/
def reindex (b : orthonormal_basis ι 𝕜 E) (e : ι ≃ ι') : orthonormal_basis ι' 𝕜 E :=
orthonormal_basis.of_repr (b.repr.trans (linear_isometry_equiv.pi_Lp_congr_left 2 𝕜 𝕜 e))
protected lemma reindex_apply (b : orthonormal_basis ι 𝕜 E) (e : ι ≃ ι') (i' : ι') :
(b.reindex e) i' = b (e.symm i') :=
begin
classical,
dsimp [reindex, orthonormal_basis.has_coe_to_fun],
rw coe_of_repr,
dsimp,
rw [← b.repr_symm_single, linear_isometry_equiv.pi_Lp_congr_left_symm,
euclidean_space.pi_Lp_congr_left_single],
end
@[simp] protected lemma coe_reindex (b : orthonormal_basis ι 𝕜 E) (e : ι ≃ ι') :
⇑(b.reindex e) = ⇑b ∘ ⇑(e.symm) :=
funext (b.reindex_apply e)
@[simp] protected lemma reindex_repr
(b : orthonormal_basis ι 𝕜 E) (e : ι ≃ ι') (x : E) (i' : ι') :
((b.reindex e).repr x) i' = (b.repr x) (e.symm i') :=
by { classical,
rw [orthonormal_basis.repr_apply_apply, b.repr_apply_apply, orthonormal_basis.coe_reindex] }
end orthonormal_basis
/-- `![1, I]` is an orthonormal basis for `ℂ` considered as a real inner product space. -/
def complex.orthonormal_basis_one_I : orthonormal_basis (fin 2) ℝ ℂ :=
(complex.basis_one_I.to_orthonormal_basis
begin
rw orthonormal_iff_ite,
intros i, fin_cases i;
intros j; fin_cases j;
simp [real_inner_eq_re_inner]
end)
@[simp] lemma complex.orthonormal_basis_one_I_repr_apply (z : ℂ) :
complex.orthonormal_basis_one_I.repr z = ![z.re, z.im] :=
rfl
@[simp] lemma complex.orthonormal_basis_one_I_repr_symm_apply (x : euclidean_space ℝ (fin 2)) :
complex.orthonormal_basis_one_I.repr.symm x = (x 0) + (x 1) * I :=
rfl
@[simp] lemma complex.to_basis_orthonormal_basis_one_I :
complex.orthonormal_basis_one_I.to_basis = complex.basis_one_I :=
basis.to_basis_to_orthonormal_basis _ _
@[simp] lemma complex.coe_orthonormal_basis_one_I :
(complex.orthonormal_basis_one_I : (fin 2) → ℂ) = ![1, I] :=
by simp [complex.orthonormal_basis_one_I]
/-- The isometry between `ℂ` and a two-dimensional real inner product space given by a basis. -/
def complex.isometry_of_orthonormal (v : orthonormal_basis (fin 2) ℝ F) : ℂ ≃ₗᵢ[ℝ] F :=
complex.orthonormal_basis_one_I.repr.trans v.repr.symm
@[simp] lemma complex.map_isometry_of_orthonormal (v : orthonormal_basis (fin 2) ℝ F)
(f : F ≃ₗᵢ[ℝ] F') :
complex.isometry_of_orthonormal (v.map f) =
(complex.isometry_of_orthonormal v).trans f :=
by simp [complex.isometry_of_orthonormal, linear_isometry_equiv.trans_assoc, orthonormal_basis.map]
lemma complex.isometry_of_orthonormal_symm_apply
(v : orthonormal_basis (fin 2) ℝ F) (f : F) :
(complex.isometry_of_orthonormal v).symm f
= (v.to_basis.coord 0 f : ℂ) + (v.to_basis.coord 1 f : ℂ) * I :=
by simp [complex.isometry_of_orthonormal]
lemma complex.isometry_of_orthonormal_apply
(v : orthonormal_basis (fin 2) ℝ F) (z : ℂ) :
complex.isometry_of_orthonormal v z = z.re • v 0 + z.im • v 1 :=
by simp [complex.isometry_of_orthonormal, ← v.sum_repr_symm]
open finite_dimensional
/-! ### Matrix representation of an orthonormal basis with respect to another -/
section to_matrix
variables [decidable_eq ι]
section
variables (a b : orthonormal_basis ι 𝕜 E)
/-- The change-of-basis matrix between two orthonormal bases `a`, `b` is a unitary matrix. -/
lemma orthonormal_basis.to_matrix_orthonormal_basis_mem_unitary :
a.to_basis.to_matrix b ∈ matrix.unitary_group ι 𝕜 :=
begin
rw matrix.mem_unitary_group_iff',
ext i j,
convert a.repr.inner_map_map (b i) (b j),
rw orthonormal_iff_ite.mp b.orthonormal i j,
refl,
end
/-- The determinant of the change-of-basis matrix between two orthonormal bases `a`, `b` has
unit length. -/
@[simp] lemma orthonormal_basis.det_to_matrix_orthonormal_basis :
‖a.to_basis.det b‖ = 1 :=
begin
have : (norm_sq (a.to_basis.det b) : 𝕜) = 1,
{ simpa [is_R_or_C.mul_conj]
using (matrix.det_of_mem_unitary (a.to_matrix_orthonormal_basis_mem_unitary b)).2 },
norm_cast at this,
rwa [← sqrt_norm_sq_eq_norm, sqrt_eq_one],
end
end
section real
variables (a b : orthonormal_basis ι ℝ F)
/-- The change-of-basis matrix between two orthonormal bases `a`, `b` is an orthogonal matrix. -/
lemma orthonormal_basis.to_matrix_orthonormal_basis_mem_orthogonal :
a.to_basis.to_matrix b ∈ matrix.orthogonal_group ι ℝ :=
a.to_matrix_orthonormal_basis_mem_unitary b
/-- The determinant of the change-of-basis matrix between two orthonormal bases `a`, `b` is ±1. -/
lemma orthonormal_basis.det_to_matrix_orthonormal_basis_real :
a.to_basis.det b = 1 ∨ a.to_basis.det b = -1 :=
begin
rw ← sq_eq_one_iff,
simpa [unitary, sq] using matrix.det_of_mem_unitary (a.to_matrix_orthonormal_basis_mem_unitary b)
end
end real
end to_matrix
/-! ### Existence of orthonormal basis, etc. -/
section finite_dimensional
variables {v : set E}
variables {A : ι → submodule 𝕜 E}
/-- Given an internal direct sum decomposition of a module `M`, and an orthonormal basis for each
of the components of the direct sum, the disjoint union of these orthonormal bases is an
orthonormal basis for `M`. -/
noncomputable def direct_sum.is_internal.collected_orthonormal_basis
(hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, A i) _ (λ i, (A i).subtypeₗᵢ))
[decidable_eq ι] (hV_sum : direct_sum.is_internal (λ i, A i)) {α : ι → Type*}
[Π i, fintype (α i)] (v_family : Π i, orthonormal_basis (α i) 𝕜 (A i)) :
orthonormal_basis (Σ i, α i) 𝕜 E :=
(hV_sum.collected_basis (λ i, (v_family i).to_basis)).to_orthonormal_basis $
by simpa using hV.orthonormal_sigma_orthonormal
(show (∀ i, orthonormal 𝕜 (v_family i).to_basis), by simp)
lemma direct_sum.is_internal.collected_orthonormal_basis_mem [decidable_eq ι]
(h : direct_sum.is_internal A) {α : ι → Type*}
[Π i, fintype (α i)] (hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, A i) _ (λ i, (A i).subtypeₗᵢ))
(v : Π i, orthonormal_basis (α i) 𝕜 (A i)) (a : Σ i, α i) :
h.collected_orthonormal_basis hV v a ∈ A a.1 :=
by simp [direct_sum.is_internal.collected_orthonormal_basis]
variables [finite_dimensional 𝕜 E]
/-- In a finite-dimensional `inner_product_space`, any orthonormal subset can be extended to an
orthonormal basis. -/
lemma _root_.orthonormal.exists_orthonormal_basis_extension (hv : orthonormal 𝕜 (coe : v → E)) :
∃ {u : finset E} (b : orthonormal_basis u 𝕜 E), v ⊆ u ∧ ⇑b = coe :=
begin
obtain ⟨u₀, hu₀s, hu₀, hu₀_max⟩ := exists_maximal_orthonormal hv,
rw maximal_orthonormal_iff_orthogonal_complement_eq_bot hu₀ at hu₀_max,
have hu₀_finite : u₀.finite := hu₀.linear_independent.finite,
let u : finset E := hu₀_finite.to_finset,
let fu : ↥u ≃ ↥u₀ := equiv.cast (congr_arg coe_sort hu₀_finite.coe_to_finset),
have hfu : (coe : u → E) = (coe : u₀ → E) ∘ fu := by { ext, simp },
have hu : orthonormal 𝕜 (coe : u → E) := by simpa [hfu] using hu₀.comp _ fu.injective,
refine ⟨u, orthonormal_basis.mk_of_orthogonal_eq_bot hu _, _, _⟩,
{ simpa using hu₀_max },
{ simpa using hu₀s },
{ simp },
end
lemma _root_.orthonormal.exists_orthonormal_basis_extension_of_card_eq
{ι : Type*} [fintype ι] (card_ι : finrank 𝕜 E = fintype.card ι) {v : ι → E} {s : set ι}
(hv : orthonormal 𝕜 (s.restrict v)) :
∃ b : orthonormal_basis ι 𝕜 E, ∀ i ∈ s, b i = v i :=
begin
have hsv : injective (s.restrict v) := hv.linear_independent.injective,
have hX : orthonormal 𝕜 (coe : set.range (s.restrict v) → E),
{ rwa orthonormal_subtype_range hsv },
obtain ⟨Y, b₀, hX, hb₀⟩ := hX.exists_orthonormal_basis_extension,
have hιY : fintype.card ι = Y.card,
{ refine (card_ι.symm.trans _),
exact finite_dimensional.finrank_eq_card_finset_basis b₀.to_basis },
have hvsY : s.maps_to v Y := (s.maps_to_image v).mono_right (by rwa ← range_restrict),
have hsv' : set.inj_on v s,
{ rw set.inj_on_iff_injective,
exact hsv },
obtain ⟨g, hg⟩ := hvsY.exists_equiv_extend_of_card_eq hιY hsv',
use b₀.reindex g.symm,
intros i hi,
{ simp [hb₀, hg i hi] },
end
variables (𝕜 E)
/-- A finite-dimensional inner product space admits an orthonormal basis. -/
lemma _root_.exists_orthonormal_basis :
∃ (w : finset E) (b : orthonormal_basis w 𝕜 E), ⇑b = (coe : w → E) :=
let ⟨w, hw, hw', hw''⟩ := (orthonormal_empty 𝕜 E).exists_orthonormal_basis_extension in
⟨w, hw, hw''⟩
/-- A finite-dimensional `inner_product_space` has an orthonormal basis. -/
def std_orthonormal_basis : orthonormal_basis (fin (finrank 𝕜 E)) 𝕜 E :=
begin
let b := classical.some (classical.some_spec $ exists_orthonormal_basis 𝕜 E),
rw [finrank_eq_card_basis b.to_basis],
exact b.reindex (fintype.equiv_fin_of_card_eq rfl),
end
variables {𝕜 E}
section subordinate_orthonormal_basis
open direct_sum
variables {n : ℕ} (hn : finrank 𝕜 E = n) [decidable_eq ι]
{V : ι → submodule 𝕜 E} (hV : is_internal V)
/-- Exhibit a bijection between `fin n` and the index set of a certain basis of an `n`-dimensional
inner product space `E`. This should not be accessed directly, but only via the subsequent API. -/
@[irreducible] def direct_sum.is_internal.sigma_orthonormal_basis_index_equiv
(hV' : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) :
(Σ i, fin (finrank 𝕜 (V i))) ≃ fin n :=
let b := hV.collected_orthonormal_basis hV' (λ i, (std_orthonormal_basis 𝕜 (V i))) in
fintype.equiv_fin_of_card_eq $ (finite_dimensional.finrank_eq_card_basis b.to_basis).symm.trans hn
/-- An `n`-dimensional `inner_product_space` equipped with a decomposition as an internal direct
sum has an orthonormal basis indexed by `fin n` and subordinate to that direct sum. -/
@[irreducible] def direct_sum.is_internal.subordinate_orthonormal_basis
(hV' : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) :
orthonormal_basis (fin n) 𝕜 E :=
((hV.collected_orthonormal_basis hV' (λ i, (std_orthonormal_basis 𝕜 (V i)))).reindex
(hV.sigma_orthonormal_basis_index_equiv hn hV'))
/-- An `n`-dimensional `inner_product_space` equipped with a decomposition as an internal direct
sum has an orthonormal basis indexed by `fin n` and subordinate to that direct sum. This function
provides the mapping by which it is subordinate. -/
def direct_sum.is_internal.subordinate_orthonormal_basis_index
(a : fin n) (hV' : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) : ι :=
((hV.sigma_orthonormal_basis_index_equiv hn hV').symm a).1
/-- The basis constructed in `orthogonal_family.subordinate_orthonormal_basis` is subordinate to
the `orthogonal_family` in question. -/
lemma direct_sum.is_internal.subordinate_orthonormal_basis_subordinate
(a : fin n) (hV' : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) :
(hV.subordinate_orthonormal_basis hn hV' a) ∈
V (hV.subordinate_orthonormal_basis_index hn a hV') :=
by simpa only [direct_sum.is_internal.subordinate_orthonormal_basis,
orthonormal_basis.coe_reindex]
using hV.collected_orthonormal_basis_mem hV' (λ i, (std_orthonormal_basis 𝕜 (V i)))
((hV.sigma_orthonormal_basis_index_equiv hn hV').symm a)
attribute [irreducible] direct_sum.is_internal.subordinate_orthonormal_basis_index
end subordinate_orthonormal_basis
end finite_dimensional
local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ
/-- Given a natural number `n` one less than the `finrank` of a finite-dimensional inner product
space, there exists an isometry from the orthogonal complement of a nonzero singleton to
`euclidean_space 𝕜 (fin n)`. -/
def orthonormal_basis.from_orthogonal_span_singleton
(n : ℕ) [fact (finrank 𝕜 E = n + 1)] {v : E} (hv : v ≠ 0) :
orthonormal_basis (fin n) 𝕜 (𝕜 ∙ v)ᗮ :=
(std_orthonormal_basis _ _).reindex $ fin_congr $ finrank_orthogonal_span_singleton hv
section linear_isometry
variables {V : Type*} [inner_product_space 𝕜 V] [finite_dimensional 𝕜 V]
variables {S : submodule 𝕜 V} {L : S →ₗᵢ[𝕜] V}
open finite_dimensional
/-- Let `S` be a subspace of a finite-dimensional complex inner product space `V`. A linear
isometry mapping `S` into `V` can be extended to a full isometry of `V`.
TODO: The case when `S` is a finite-dimensional subspace of an infinite-dimensional `V`.-/
noncomputable def linear_isometry.extend (L : S →ₗᵢ[𝕜] V): V →ₗᵢ[𝕜] V :=
begin
-- Build an isometry from Sᗮ to L(S)ᗮ through euclidean_space
let d := finrank 𝕜 Sᗮ,
have dim_S_perp : finrank 𝕜 Sᗮ = d := rfl,
let LS := L.to_linear_map.range,
have E : Sᗮ ≃ₗᵢ[𝕜] LSᗮ,
{ have dim_LS_perp : finrank 𝕜 LSᗮ = d,
calc finrank 𝕜 LSᗮ = finrank 𝕜 V - finrank 𝕜 LS : by simp only
[← LS.finrank_add_finrank_orthogonal, add_tsub_cancel_left]
... = finrank 𝕜 V - finrank 𝕜 S : by simp only
[linear_map.finrank_range_of_inj L.injective]
... = finrank 𝕜 Sᗮ : by simp only
[← S.finrank_add_finrank_orthogonal, add_tsub_cancel_left],
exact (std_orthonormal_basis 𝕜 Sᗮ).repr.trans
((std_orthonormal_basis 𝕜 LSᗮ).reindex $ fin_congr dim_LS_perp).repr.symm },
let L3 := (LS)ᗮ.subtypeₗᵢ.comp E.to_linear_isometry,
-- Project onto S and Sᗮ
haveI : complete_space S := finite_dimensional.complete 𝕜 S,
haveI : complete_space V := finite_dimensional.complete 𝕜 V,
let p1 := (orthogonal_projection S).to_linear_map,
let p2 := (orthogonal_projection Sᗮ).to_linear_map,
-- Build a linear map from the isometries on S and Sᗮ
let M := L.to_linear_map.comp p1 + L3.to_linear_map.comp p2,
-- Prove that M is an isometry
have M_norm_map : ∀ (x : V), ‖M x‖ = ‖x‖,
{ intro x,
-- Apply M to the orthogonal decomposition of x
have Mx_decomp : M x = L (p1 x) + L3 (p2 x),
{ simp only [linear_map.add_apply, linear_map.comp_apply, linear_map.comp_apply,
linear_isometry.coe_to_linear_map]},
-- Mx_decomp is the orthogonal decomposition of M x
have Mx_orth : ⟪ L (p1 x), L3 (p2 x) ⟫ = 0,
{ have Lp1x : L (p1 x) ∈ L.to_linear_map.range :=
linear_map.mem_range_self L.to_linear_map (p1 x),
have Lp2x : L3 (p2 x) ∈ (L.to_linear_map.range)ᗮ,
{ simp only [L3, linear_isometry.coe_comp, function.comp_app, submodule.coe_subtypeₗᵢ,
← submodule.range_subtype (LSᗮ)],
apply linear_map.mem_range_self},
apply submodule.inner_right_of_mem_orthogonal Lp1x Lp2x},
-- Apply the Pythagorean theorem and simplify
rw [← sq_eq_sq (norm_nonneg _) (norm_nonneg _), norm_sq_eq_add_norm_sq_projection x S],
simp only [sq, Mx_decomp],
rw norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (L (p1 x)) (L3 (p2 x)) Mx_orth,
simp only [linear_isometry.norm_map, p1, p2, continuous_linear_map.to_linear_map_eq_coe,
add_left_inj, mul_eq_mul_left_iff, norm_eq_zero, true_or, eq_self_iff_true,
continuous_linear_map.coe_coe, submodule.coe_norm, submodule.coe_eq_zero] },
exact { to_linear_map := M, norm_map' := M_norm_map },
end
lemma linear_isometry.extend_apply (L : S →ₗᵢ[𝕜] V) (s : S):
L.extend s = L s :=
begin
haveI : complete_space S := finite_dimensional.complete 𝕜 S,
simp only [linear_isometry.extend, continuous_linear_map.to_linear_map_eq_coe,
←linear_isometry.coe_to_linear_map],
simp only [add_right_eq_self, linear_isometry.coe_to_linear_map,
linear_isometry_equiv.coe_to_linear_isometry, linear_isometry.coe_comp, function.comp_app,
orthogonal_projection_mem_subspace_eq_self, linear_map.coe_comp, continuous_linear_map.coe_coe,
submodule.coe_subtype, linear_map.add_apply, submodule.coe_eq_zero,
linear_isometry_equiv.map_eq_zero_iff, submodule.coe_subtypeₗᵢ,
orthogonal_projection_mem_subspace_orthogonal_complement_eq_zero,
submodule.orthogonal_orthogonal, submodule.coe_mem],
end
end linear_isometry
section matrix
open_locale matrix
variables {n m : ℕ}
local notation `⟪`x`, `y`⟫ₘ` := @inner 𝕜 (euclidean_space 𝕜 (fin m)) _ x y
local notation `⟪`x`, `y`⟫ₙ` := @inner 𝕜 (euclidean_space 𝕜 (fin n)) _ x y
/-- The inner product of a row of A and a row of B is an entry of B ⬝ Aᴴ. -/
lemma inner_matrix_row_row (A B : matrix (fin n) (fin m) 𝕜) (i j : (fin n)) :
⟪A i, B j⟫ₘ = (B ⬝ Aᴴ) j i := by {simp only [inner, matrix.mul_apply, star_ring_end_apply,
matrix.conj_transpose_apply,mul_comm]}
/-- The inner product of a column of A and a column of B is an entry of Aᴴ ⬝ B -/
lemma inner_matrix_col_col (A B : matrix (fin n) (fin m) 𝕜) (i j : (fin m)) :
⟪Aᵀ i, Bᵀ j⟫ₙ = (Aᴴ ⬝ B) i j := rfl
end matrix
|
feecdc68e0da5a6c92a4ca72506e5ab65717c8b0 | 367134ba5a65885e863bdc4507601606690974c1 | /src/category_theory/closed/cartesian.lean | e8d4c9a85fa3c733907adc2accead908484cfadd | [
"Apache-2.0"
] | permissive | kodyvajjha/mathlib | 9bead00e90f68269a313f45f5561766cfd8d5cad | b98af5dd79e13a38d84438b850a2e8858ec21284 | refs/heads/master | 1,624,350,366,310 | 1,615,563,062,000 | 1,615,563,062,000 | 162,666,963 | 0 | 0 | Apache-2.0 | 1,545,367,651,000 | 1,545,367,651,000 | null | UTF-8 | Lean | false | false | 14,517 | lean | /-
Copyright (c) 2020 Bhavik Mehta, Edward Ayers, Thomas Read. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Edward Ayers, Thomas Read
-/
import category_theory.limits.shapes.finite_products
import category_theory.limits.preserves.shapes.binary_products
import category_theory.closed.monoidal
import category_theory.monoidal.of_has_finite_products
import category_theory.adjunction
import category_theory.adjunction.mates
import category_theory.epi_mono
/-!
# Cartesian closed categories
Given a category with finite products, the cartesian monoidal structure is provided by the local
instance `monoidal_of_has_finite_products`.
We define exponentiable objects to be closed objects with respect to this monoidal structure,
i.e. `(X × -)` is a left adjoint.
We say a category is cartesian closed if every object is exponentiable
(equivalently, that the category equipped with the cartesian monoidal structure is closed monoidal).
Show that exponential forms a difunctor and define the exponential comparison morphisms.
## TODO
Some of the results here are true more generally for closed objects and
for closed monoidal categories, and these could be generalised.
-/
universes v u u₂
noncomputable theory
namespace category_theory
open category_theory category_theory.category category_theory.limits
local attribute [instance] monoidal_of_has_finite_products
/--
An object `X` is *exponentiable* if `(X × -)` is a left adjoint.
We define this as being `closed` in the cartesian monoidal structure.
-/
abbreviation exponentiable {C : Type u} [category.{v} C] [has_finite_products C] (X : C) :=
closed X
/--
If `X` and `Y` are exponentiable then `X ⨯ Y` is.
This isn't an instance because it's not usually how we want to construct exponentials, we'll usually
prove all objects are exponential uniformly.
-/
def binary_product_exponentiable {C : Type u} [category.{v} C] [has_finite_products C] {X Y : C}
(hX : exponentiable X) (hY : exponentiable Y) : exponentiable (X ⨯ Y) :=
{ is_adj :=
begin
haveI := hX.is_adj,
haveI := hY.is_adj,
exact adjunction.left_adjoint_of_nat_iso (monoidal_category.tensor_left_tensor _ _).symm
end }
/--
The terminal object is always exponentiable.
This isn't an instance because most of the time we'll prove cartesian closed for all objects
at once, rather than just for this one.
-/
def terminal_exponentiable {C : Type u} [category.{v} C] [has_finite_products C] :
exponentiable ⊤_C :=
unit_closed
/--
A category `C` is cartesian closed if it has finite products and every object is exponentiable.
We define this as `monoidal_closed` with respect to the cartesian monoidal structure.
-/
abbreviation cartesian_closed (C : Type u) [category.{v} C] [has_finite_products C] :=
monoidal_closed C
variables {C : Type u} [category.{v} C] (A B : C) {X X' Y Y' Z : C}
section exp
variables [has_finite_products C] [exponentiable A]
/-- This is (-)^A. -/
def exp : C ⥤ C :=
(@closed.is_adj _ _ _ A _).right
/-- The adjunction between A ⨯ - and (-)^A. -/
def exp.adjunction : prod.functor.obj A ⊣ exp A :=
closed.is_adj.adj
/-- The evaluation natural transformation. -/
def ev : exp A ⋙ prod.functor.obj A ⟶ 𝟭 C :=
closed.is_adj.adj.counit
/-- The coevaluation natural transformation. -/
def coev : 𝟭 C ⟶ prod.functor.obj A ⋙ exp A :=
closed.is_adj.adj.unit
@[simp] lemma exp_adjunction_counit : (exp.adjunction A).counit = ev A := rfl
@[simp] lemma exp_adjunction_unit : (exp.adjunction A).unit = coev A := rfl
@[simp, reassoc]
lemma ev_naturality {X Y : C} (f : X ⟶ Y) :
limits.prod.map (𝟙 A) ((exp A).map f) ≫ (ev A).app Y = (ev A).app X ≫ f :=
(ev A).naturality f
@[simp, reassoc]
lemma coev_naturality {X Y : C} (f : X ⟶ Y) :
f ≫ (coev A).app Y = (coev A).app X ≫ (exp A).map (limits.prod.map (𝟙 A) f) :=
(coev A).naturality f
notation A ` ⟹ `:20 B:20 := (exp A).obj B
notation B ` ^^ `:30 A:30 := (exp A).obj B
@[simp, reassoc] lemma ev_coev :
limits.prod.map (𝟙 A) ((coev A).app B) ≫ (ev A).app (A ⨯ B) = 𝟙 (A ⨯ B) :=
adjunction.left_triangle_components (exp.adjunction A)
@[simp, reassoc] lemma coev_ev : (coev A).app (A⟹B) ≫ (exp A).map ((ev A).app B) = 𝟙 (A⟹B) :=
adjunction.right_triangle_components (exp.adjunction A)
instance : preserves_colimits (prod.functor.obj A) :=
(exp.adjunction A).left_adjoint_preserves_colimits
end exp
variables {A}
-- Wrap these in a namespace so we don't clash with the core versions.
namespace cartesian_closed
variables [has_finite_products C] [exponentiable A]
/-- Currying in a cartesian closed category. -/
def curry : (A ⨯ Y ⟶ X) → (Y ⟶ A ⟹ X) :=
(closed.is_adj.adj.hom_equiv _ _).to_fun
/-- Uncurrying in a cartesian closed category. -/
def uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X) :=
(closed.is_adj.adj.hom_equiv _ _).inv_fun
end cartesian_closed
open cartesian_closed
variables [has_finite_products C] [exponentiable A]
@[reassoc]
lemma curry_natural_left (f : X ⟶ X') (g : A ⨯ X' ⟶ Y) :
curry (limits.prod.map (𝟙 _) f ≫ g) = f ≫ curry g :=
adjunction.hom_equiv_naturality_left _ _ _
@[reassoc]
lemma curry_natural_right (f : A ⨯ X ⟶ Y) (g : Y ⟶ Y') :
curry (f ≫ g) = curry f ≫ (exp _).map g :=
adjunction.hom_equiv_naturality_right _ _ _
@[reassoc]
lemma uncurry_natural_right (f : X ⟶ A⟹Y) (g : Y ⟶ Y') :
uncurry (f ≫ (exp _).map g) = uncurry f ≫ g :=
adjunction.hom_equiv_naturality_right_symm _ _ _
@[reassoc]
lemma uncurry_natural_left (f : X ⟶ X') (g : X' ⟶ A⟹Y) :
uncurry (f ≫ g) = limits.prod.map (𝟙 _) f ≫ uncurry g :=
adjunction.hom_equiv_naturality_left_symm _ _ _
@[simp]
lemma uncurry_curry (f : A ⨯ X ⟶ Y) : uncurry (curry f) = f :=
(closed.is_adj.adj.hom_equiv _ _).left_inv f
@[simp]
lemma curry_uncurry (f : X ⟶ A⟹Y) : curry (uncurry f) = f :=
(closed.is_adj.adj.hom_equiv _ _).right_inv f
lemma curry_eq_iff (f : A ⨯ Y ⟶ X) (g : Y ⟶ A ⟹ X) :
curry f = g ↔ f = uncurry g :=
adjunction.hom_equiv_apply_eq _ f g
lemma eq_curry_iff (f : A ⨯ Y ⟶ X) (g : Y ⟶ A ⟹ X) :
g = curry f ↔ uncurry g = f :=
adjunction.eq_hom_equiv_apply _ f g
-- I don't think these two should be simp.
lemma uncurry_eq (g : Y ⟶ A ⟹ X) : uncurry g = limits.prod.map (𝟙 A) g ≫ (ev A).app X :=
adjunction.hom_equiv_counit _
lemma curry_eq (g : A ⨯ Y ⟶ X) : curry g = (coev A).app Y ≫ (exp A).map g :=
adjunction.hom_equiv_unit _
lemma uncurry_id_eq_ev (A X : C) [exponentiable A] : uncurry (𝟙 (A ⟹ X)) = (ev A).app X :=
by rw [uncurry_eq, prod.map_id_id, id_comp]
lemma curry_id_eq_coev (A X : C) [exponentiable A] : curry (𝟙 _) = (coev A).app X :=
by { rw [curry_eq, (exp A).map_id (A ⨯ _)], apply comp_id }
lemma curry_injective : function.injective (curry : (A ⨯ Y ⟶ X) → (Y ⟶ A ⟹ X)) :=
(closed.is_adj.adj.hom_equiv _ _).injective
lemma uncurry_injective : function.injective (uncurry : (Y ⟶ A ⟹ X) → (A ⨯ Y ⟶ X)) :=
(closed.is_adj.adj.hom_equiv _ _).symm.injective
/--
Show that the exponential of the terminal object is isomorphic to itself, i.e. `X^1 ≅ X`.
The typeclass argument is explicit: any instance can be used.
-/
def exp_terminal_iso_self [exponentiable ⊤_C] : (⊤_C ⟹ X) ≅ X :=
yoneda.ext (⊤_ C ⟹ X) X
(λ Y f, (prod.left_unitor Y).inv ≫ uncurry f)
(λ Y f, curry ((prod.left_unitor Y).hom ≫ f))
(λ Z g, by rw [curry_eq_iff, iso.hom_inv_id_assoc] )
(λ Z g, by simp)
(λ Z W f g, by rw [uncurry_natural_left, prod.left_unitor_inv_naturality_assoc f] )
/-- The internal element which points at the given morphism. -/
def internalize_hom (f : A ⟶ Y) : ⊤_C ⟶ (A ⟹ Y) :=
curry (limits.prod.fst ≫ f)
section pre
variables {B}
/-- Pre-compose an internal hom with an external hom. -/
def pre (f : B ⟶ A) [exponentiable B] : exp A ⟶ exp B :=
transfer_nat_trans_self (exp.adjunction _) (exp.adjunction _) (prod.functor.map f)
lemma prod_map_pre_app_comp_ev (f : B ⟶ A) [exponentiable B] (X : C) :
limits.prod.map (𝟙 B) ((pre f).app X) ≫ (ev B).app X =
limits.prod.map f (𝟙 (A ⟹ X)) ≫ (ev A).app X :=
transfer_nat_trans_self_counit _ _ (prod.functor.map f) X
lemma uncurry_pre (f : B ⟶ A) [exponentiable B] (X : C) :
uncurry ((pre f).app X) = limits.prod.map f (𝟙 _) ≫ (ev A).app X :=
begin
rw [uncurry_eq, prod_map_pre_app_comp_ev]
end
lemma coev_app_comp_pre_app (f : B ⟶ A) [exponentiable B] :
(coev A).app X ≫ (pre f).app (A ⨯ X) = (coev B).app X ≫ (exp B).map (limits.prod.map f (𝟙 _)) :=
unit_transfer_nat_trans_self _ _ (prod.functor.map f) X
@[simp]
lemma pre_id (A : C) [exponentiable A] : pre (𝟙 A) = 𝟙 _ :=
by simp [pre]
@[simp]
lemma pre_map {A₁ A₂ A₃ : C} [exponentiable A₁] [exponentiable A₂] [exponentiable A₃]
(f : A₁ ⟶ A₂) (g : A₂ ⟶ A₃) :
pre (f ≫ g) = pre g ≫ pre f :=
by rw [pre, pre, pre, transfer_nat_trans_self_comp, prod.functor.map_comp]
end pre
/-- The internal hom functor given by the cartesian closed structure. -/
def internal_hom [cartesian_closed C] : Cᵒᵖ ⥤ C ⥤ C :=
{ obj := λ X, exp X.unop,
map := λ X Y f, pre f.unop }
/-- If an initial object `I` exists in a CCC, then `A ⨯ I ≅ I`. -/
@[simps]
def zero_mul {I : C} (t : is_initial I) : A ⨯ I ≅ I :=
{ hom := limits.prod.snd,
inv := t.to _,
hom_inv_id' :=
begin
have: (limits.prod.snd : A ⨯ I ⟶ I) = uncurry (t.to _),
rw ← curry_eq_iff,
apply t.hom_ext,
rw [this, ← uncurry_natural_right, ← eq_curry_iff],
apply t.hom_ext,
end,
inv_hom_id' := t.hom_ext _ _ }
/-- If an initial object `0` exists in a CCC, then `0 ⨯ A ≅ 0`. -/
def mul_zero {I : C} (t : is_initial I) : I ⨯ A ≅ I :=
limits.prod.braiding _ _ ≪≫ zero_mul t
/-- If an initial object `0` exists in a CCC then `0^B ≅ 1` for any `B`. -/
def pow_zero {I : C} (t : is_initial I) [cartesian_closed C] : I ⟹ B ≅ ⊤_ C :=
{ hom := default _,
inv := curry ((mul_zero t).hom ≫ t.to _),
hom_inv_id' :=
begin
rw [← curry_natural_left, curry_eq_iff, ← cancel_epi (mul_zero t).inv],
{ apply t.hom_ext },
{ apply_instance },
{ apply_instance }
end }
-- TODO: Generalise the below to its commutated variants.
-- TODO: Define a distributive category, so that zero_mul and friends can be derived from this.
/-- In a CCC with binary coproducts, the distribution morphism is an isomorphism. -/
def prod_coprod_distrib [has_binary_coproducts C] [cartesian_closed C] (X Y Z : C) :
(Z ⨯ X) ⨿ (Z ⨯ Y) ≅ Z ⨯ (X ⨿ Y) :=
{ hom := coprod.desc (limits.prod.map (𝟙 _) coprod.inl) (limits.prod.map (𝟙 _) coprod.inr),
inv := uncurry (coprod.desc (curry coprod.inl) (curry coprod.inr)),
hom_inv_id' :=
begin
apply coprod.hom_ext,
rw [coprod.inl_desc_assoc, comp_id, ←uncurry_natural_left, coprod.inl_desc, uncurry_curry],
rw [coprod.inr_desc_assoc, comp_id, ←uncurry_natural_left, coprod.inr_desc, uncurry_curry],
end,
inv_hom_id' :=
begin
rw [← uncurry_natural_right, ←eq_curry_iff],
apply coprod.hom_ext,
rw [coprod.inl_desc_assoc, ←curry_natural_right, coprod.inl_desc, ←curry_natural_left, comp_id],
rw [coprod.inr_desc_assoc, ←curry_natural_right, coprod.inr_desc, ←curry_natural_left, comp_id],
end }
/--
If an initial object `I` exists in a CCC then it is a strict initial object,
i.e. any morphism to `I` is an iso.
This actually shows a slightly stronger version: any morphism to an initial object from an
exponentiable object is an isomorphism.
-/
def strict_initial {I : C} (t : is_initial I) (f : A ⟶ I) : is_iso f :=
begin
haveI : mono (limits.prod.lift (𝟙 A) f ≫ (zero_mul t).hom) := mono_comp _ _,
rw [zero_mul_hom, prod.lift_snd] at _inst,
haveI: split_epi f := ⟨t.to _, t.hom_ext _ _⟩,
apply is_iso_of_mono_of_split_epi
end
instance to_initial_is_iso [has_initial C] (f : A ⟶ ⊥_ C) : is_iso f :=
strict_initial initial_is_initial _
/-- If an initial object `0` exists in a CCC then every morphism from it is monic. -/
lemma initial_mono {I : C} (B : C) (t : is_initial I) [cartesian_closed C] : mono (t.to B) :=
⟨λ B g h _,
begin
haveI := strict_initial t g,
haveI := strict_initial t h,
exact eq_of_inv_eq_inv (t.hom_ext _ _)
end⟩
instance initial.mono_to [has_initial C] (B : C) [cartesian_closed C] : mono (initial.to B) :=
initial_mono B initial_is_initial
variables {D : Type u₂} [category.{v} D]
section functor
variables [has_finite_products D]
/--
Transport the property of being cartesian closed across an equivalence of categories.
Note we didn't require any coherence between the choice of finite products here, since we transport
along the `prod_comparison` isomorphism.
-/
def cartesian_closed_of_equiv (e : C ≌ D) [h : cartesian_closed C] : cartesian_closed D :=
{ closed := λ X,
{ is_adj :=
begin
haveI q : exponentiable (e.inverse.obj X) := infer_instance,
have : is_left_adjoint (prod.functor.obj (e.inverse.obj X)) := q.is_adj,
have : e.functor ⋙ prod.functor.obj X ⋙ e.inverse ≅ prod.functor.obj (e.inverse.obj X),
apply nat_iso.of_components _ _,
intro Y,
{ apply as_iso (prod_comparison e.inverse X (e.functor.obj Y)) ≪≫ _,
apply prod.map_iso (iso.refl _) (e.unit_iso.app Y).symm },
{ intros Y Z g,
dsimp [prod_comparison],
simp [prod.comp_lift, ← e.inverse.map_comp, ← e.inverse.map_comp_assoc],
-- I wonder if it would be a good idea to make `map_comp` a simp lemma the other way round
dsimp, simp -- See note [dsimp, simp]
},
{ have : is_left_adjoint (e.functor ⋙ prod.functor.obj X ⋙ e.inverse) :=
by exactI adjunction.left_adjoint_of_nat_iso this.symm,
have : is_left_adjoint (e.inverse ⋙ e.functor ⋙ prod.functor.obj X ⋙ e.inverse) :=
by exactI adjunction.left_adjoint_of_comp e.inverse _,
have : (e.inverse ⋙ e.functor ⋙ prod.functor.obj X ⋙ e.inverse) ⋙ e.functor ≅
prod.functor.obj X,
{ apply iso_whisker_right e.counit_iso (prod.functor.obj X ⋙ e.inverse ⋙ e.functor) ≪≫ _,
change prod.functor.obj X ⋙ e.inverse ⋙ e.functor ≅ prod.functor.obj X,
apply iso_whisker_left (prod.functor.obj X) e.counit_iso, },
resetI,
apply adjunction.left_adjoint_of_nat_iso this },
end } }
end functor
end category_theory
|
847a2be455f1badf1d3eaa2ac1c240a1554fff05 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/lazy_list/basic.lean | 4b6762f43bc7088add7bba2fb2ffdca86d36a8b2 | [
"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 | 7,818 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import control.traversable.equiv
import control.traversable.instances
import data.lazy_list
/-!
## Definitions on lazy lists
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file contains various definitions and proofs on lazy lists.
TODO: move the `lazy_list.lean` file from core to mathlib.
-/
universes u
namespace thunk
/-- Creates a thunk with a (non-lazy) constant value. -/
def mk {α} (x : α) : thunk α := λ _, x
instance {α : Type u} [decidable_eq α] : decidable_eq (thunk α) | a b :=
have a = b ↔ a () = b (), from ⟨by cc, by intro; ext x; cases x; assumption⟩,
by rw this; apply_instance
end thunk
namespace lazy_list
open function
/-- Isomorphism between strict and lazy lists. -/
def list_equiv_lazy_list (α : Type*) : list α ≃ lazy_list α :=
{ to_fun := lazy_list.of_list,
inv_fun := lazy_list.to_list,
right_inv := by { intro, induction x, refl, simp! [*],
ext, cases x, refl },
left_inv := by { intro, induction x, refl, simp! [*] } }
instance {α : Type u} [decidable_eq α] : decidable_eq (lazy_list α)
| nil nil := is_true rfl
| (cons x xs) (cons y ys) :=
if h : x = y then
match decidable_eq (xs ()) (ys ()) with
| is_false h2 := is_false (by intro; cc)
| is_true h2 :=
have xs = ys, by ext u; cases u; assumption,
is_true (by cc)
end
else
is_false (by intro; cc)
| nil (cons _ _) := is_false (by cc)
| (cons _ _) nil := is_false (by cc)
/-- Traversal of lazy lists using an applicative effect. -/
protected def traverse {m : Type u → Type u} [applicative m] {α β : Type u}
(f : α → m β) : lazy_list α → m (lazy_list β)
| lazy_list.nil := pure lazy_list.nil
| (lazy_list.cons x xs) := lazy_list.cons <$> f x <*> (thunk.mk <$> traverse (xs ()))
instance : traversable lazy_list :=
{ map := @lazy_list.traverse id _,
traverse := @lazy_list.traverse }
instance : is_lawful_traversable lazy_list :=
begin
apply equiv.is_lawful_traversable' list_equiv_lazy_list;
intros ; resetI; ext,
{ induction x, refl,
simp! [equiv.map,functor.map] at *,
simp [*], refl, },
{ induction x, refl,
simp! [equiv.map,functor.map_const] at *,
simp [*], refl, },
{ induction x,
{ simp! [traversable.traverse,equiv.traverse] with functor_norm, refl },
simp! [equiv.map,functor.map_const,traversable.traverse] at *, rw x_ih,
dsimp [list_equiv_lazy_list,equiv.traverse,to_list,traversable.traverse,list.traverse],
simp! with functor_norm, refl },
end
/-- `init xs`, if `xs` non-empty, drops the last element of the list.
Otherwise, return the empty list. -/
def init {α} : lazy_list α → lazy_list α
| lazy_list.nil := lazy_list.nil
| (lazy_list.cons x xs) :=
let xs' := xs () in
match xs' with
| lazy_list.nil := lazy_list.nil
| (lazy_list.cons _ _) := lazy_list.cons x (init xs')
end
/-- Return the first object contained in the list that satisfies
predicate `p` -/
def find {α} (p : α → Prop) [decidable_pred p] : lazy_list α → option α
| nil := none
| (cons h t) := if p h then some h else find (t ())
/-- `interleave xs ys` creates a list where elements of `xs` and `ys` alternate. -/
def interleave {α} : lazy_list α → lazy_list α → lazy_list α
| lazy_list.nil xs := xs
| a@(lazy_list.cons x xs) lazy_list.nil := a
| (lazy_list.cons x xs) (lazy_list.cons y ys) :=
lazy_list.cons x (lazy_list.cons y (interleave (xs ()) (ys ())))
/-- `interleave_all (xs::ys::zs::xss)` creates a list where elements of `xs`, `ys`
and `zs` and the rest alternate. Every other element of the resulting list is taken from
`xs`, every fourth is taken from `ys`, every eighth is taken from `zs` and so on. -/
def interleave_all {α} : list (lazy_list α) → lazy_list α
| [] := lazy_list.nil
| (x :: xs) := interleave x (interleave_all xs)
/-- Monadic bind operation for `lazy_list`. -/
protected def bind {α β} : lazy_list α → (α → lazy_list β) → lazy_list β
| lazy_list.nil _ := lazy_list.nil
| (lazy_list.cons x xs) f := lazy_list.append (f x) (bind (xs ()) f)
/-- Reverse the order of a `lazy_list`.
It is done by converting to a `list` first because reversal involves evaluating all
the list and if the list is all evaluated, `list` is a better representation for
it than a series of thunks. -/
def reverse {α} (xs : lazy_list α) : lazy_list α :=
of_list xs.to_list.reverse
instance : monad lazy_list :=
{ pure := @lazy_list.singleton,
bind := @lazy_list.bind }
lemma append_nil {α} (xs : lazy_list α) : xs.append lazy_list.nil = xs :=
begin
induction xs, refl,
simp [lazy_list.append, xs_ih],
ext, congr,
end
lemma append_assoc {α} (xs ys zs : lazy_list α) :
(xs.append ys).append zs = xs.append (ys.append zs) :=
by induction xs; simp [append, *]
lemma append_bind {α β} (xs : lazy_list α) (ys : thunk (lazy_list α)) (f : α → lazy_list β) :
(@lazy_list.append _ xs ys).bind f = (xs.bind f).append ((ys ()).bind f) :=
by induction xs; simp [lazy_list.bind, append, *, append_assoc, append, lazy_list.bind]
instance : is_lawful_monad lazy_list :=
{ pure_bind := by { intros, apply append_nil },
bind_assoc := by { intros, dsimp [(>>=)], induction x; simp [lazy_list.bind, append_bind, *], },
id_map :=
begin
intros,
simp [(<$>)],
induction x; simp [lazy_list.bind, *, singleton, append],
ext ⟨ ⟩, refl,
end }
/-- Try applying function `f` to every element of a `lazy_list` and
return the result of the first attempt that succeeds. -/
def mfirst {m} [alternative m] {α β} (f : α → m β) : lazy_list α → m β
| nil := failure
| (cons x xs) :=
f x <|> mfirst (xs ())
/-- Membership in lazy lists -/
protected def mem {α} (x : α) : lazy_list α → Prop
| lazy_list.nil := false
| (lazy_list.cons y ys) := x = y ∨ mem (ys ())
instance {α} : has_mem α (lazy_list α) :=
⟨ lazy_list.mem ⟩
instance mem.decidable {α} [decidable_eq α] (x : α) : Π xs : lazy_list α, decidable (x ∈ xs)
| lazy_list.nil := decidable.false
| (lazy_list.cons y ys) :=
if h : x = y
then decidable.is_true (or.inl h)
else decidable_of_decidable_of_iff (mem.decidable (ys ())) (by simp [*, (∈), lazy_list.mem])
@[simp]
lemma mem_nil {α} (x : α) : x ∈ @lazy_list.nil α ↔ false := iff.rfl
@[simp]
lemma mem_cons {α} (x y : α) (ys : thunk (lazy_list α)) :
x ∈ @lazy_list.cons α y ys ↔ x = y ∨ x ∈ ys () := iff.rfl
theorem forall_mem_cons {α} {p : α → Prop} {a : α} {l : thunk (lazy_list α)} :
(∀ x ∈ @lazy_list.cons _ a l, p x) ↔ p a ∧ ∀ x ∈ l (), p x :=
by simp only [has_mem.mem, lazy_list.mem, or_imp_distrib, forall_and_distrib, forall_eq]
/-! ### map for partial functions -/
/-- Partial map. If `f : Π a, p a → β` is a partial function defined on
`a : α` satisfying `p`, then `pmap f l h` is essentially the same as `map f l`
but is defined only when all members of `l` satisfy `p`, using the proof
to apply `f`. -/
@[simp] def pmap {α β} {p : α → Prop} (f : Π a, p a → β) :
Π l : lazy_list α, (∀ a ∈ l, p a) → lazy_list β
| lazy_list.nil H := lazy_list.nil
| (lazy_list.cons x xs) H := lazy_list.cons (f x (forall_mem_cons.1 H).1)
(pmap (xs ()) (forall_mem_cons.1 H).2)
/-- "Attach" the proof that the elements of `l` are in `l` to produce a new `lazy_list`
with the same elements but in the type `{x // x ∈ l}`. -/
def attach {α} (l : lazy_list α) : lazy_list {x // x ∈ l} := pmap subtype.mk l (λ a, id)
instance {α} [has_repr α] : has_repr (lazy_list α) :=
⟨ λ xs, repr xs.to_list ⟩
end lazy_list
|
6dff50d81fedf6ee946047e0568c68b4eab54d62 | 649957717d58c43b5d8d200da34bf374293fe739 | /src/algebra/ordered_field.lean | 4d6217c7eb360d8c0368ed6041d9701de1c374a9 | [
"Apache-2.0"
] | permissive | Vtec234/mathlib | b50c7b21edea438df7497e5ed6a45f61527f0370 | fb1848bbbfce46152f58e219dc0712f3289d2b20 | refs/heads/master | 1,592,463,095,113 | 1,562,737,749,000 | 1,562,737,749,000 | 196,202,858 | 0 | 0 | Apache-2.0 | 1,562,762,338,000 | 1,562,762,337,000 | null | UTF-8 | Lean | false | false | 9,124 | 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 algebra.ordered_ring algebra.field
section linear_ordered_field
variables {α : Type*} [linear_ordered_field α] {a b c d : α}
def div_pos := @div_pos_of_pos_of_pos
lemma inv_pos {a : α} : 0 < a → 0 < a⁻¹ :=
by rw [inv_eq_one_div]; exact div_pos zero_lt_one
lemma inv_lt_zero {a : α} : a < 0 → a⁻¹ < 0 :=
by rw [inv_eq_one_div]; exact div_neg_of_pos_of_neg zero_lt_one
lemma one_le_div_iff_le (hb : 0 < b) : 1 ≤ a / b ↔ b ≤ a :=
⟨le_of_one_le_div a hb, one_le_div_of_le a hb⟩
lemma one_lt_div_iff_lt (hb : 0 < b) : 1 < a / b ↔ b < a :=
⟨lt_of_one_lt_div a hb, one_lt_div_of_lt a hb⟩
lemma div_le_one_iff_le (hb : 0 < b) : a / b ≤ 1 ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (one_lt_div_iff_lt hb)
lemma div_lt_one_iff_lt (hb : 0 < b) : a / b < 1 ↔ a < b :=
lt_iff_lt_of_le_iff_le (one_le_div_iff_le hb)
lemma le_div_iff (hc : 0 < c) : a ≤ b / c ↔ a * c ≤ b :=
⟨mul_le_of_le_div hc, le_div_of_mul_le hc⟩
lemma le_div_iff' (hc : 0 < c) : a ≤ b / c ↔ c * a ≤ b :=
by rw [mul_comm, le_div_iff hc]
lemma div_le_iff (hb : 0 < b) : a / b ≤ c ↔ a ≤ c * b :=
⟨le_mul_of_div_le hb, by rw [mul_comm]; exact div_le_of_le_mul hb⟩
lemma div_le_iff' (hb : 0 < b) : a / b ≤ c ↔ a ≤ b * c :=
by rw [mul_comm, div_le_iff hb]
lemma lt_div_iff (hc : 0 < c) : a < b / c ↔ a * c < b :=
⟨mul_lt_of_lt_div hc, lt_div_of_mul_lt hc⟩
lemma lt_div_iff' (hc : 0 < c) : a < b / c ↔ c * a < b :=
by rw [mul_comm, lt_div_iff hc]
lemma div_le_iff_of_neg (hc : c < 0) : b / c ≤ a ↔ a * c ≤ b :=
⟨mul_le_of_div_le_of_neg hc, div_le_of_mul_le_of_neg hc⟩
lemma div_lt_iff (hc : 0 < c) : b / c < a ↔ b < a * c :=
lt_iff_lt_of_le_iff_le (le_div_iff hc)
lemma div_lt_iff' (hc : 0 < c) : b / c < a ↔ b < c * a :=
by rw [mul_comm, div_lt_iff hc]
lemma div_lt_iff_of_neg (hc : c < 0) : b / c < a ↔ a * c < b :=
⟨mul_lt_of_gt_div_of_neg hc, div_lt_of_mul_gt_of_neg hc⟩
lemma inv_le_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b⁻¹ ↔ b ≤ a :=
by rw [inv_eq_one_div, div_le_iff ha,
← div_eq_inv_mul, one_le_div_iff_le hb]
lemma inv_le (ha : 0 < a) (hb : 0 < b) : a⁻¹ ≤ b ↔ b⁻¹ ≤ a :=
by rw [← inv_le_inv hb (inv_pos ha), division_ring.inv_inv (ne_of_gt ha)]
lemma le_inv (ha : 0 < a) (hb : 0 < b) : a ≤ b⁻¹ ↔ b ≤ a⁻¹ :=
by rw [← inv_le_inv (inv_pos hb) ha, division_ring.inv_inv (ne_of_gt hb)]
lemma one_div_le_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a ≤ 1 / b ↔ b ≤ a :=
by simpa [one_div_eq_inv] using inv_le_inv ha hb
lemma inv_lt_inv (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b⁻¹ ↔ b < a :=
lt_iff_lt_of_le_iff_le (inv_le_inv hb ha)
lemma inv_lt (ha : 0 < a) (hb : 0 < b) : a⁻¹ < b ↔ b⁻¹ < a :=
lt_iff_lt_of_le_iff_le (le_inv hb ha)
lemma lt_inv (ha : 0 < a) (hb : 0 < b) : a < b⁻¹ ↔ b < a⁻¹ :=
lt_iff_lt_of_le_iff_le (inv_le hb ha)
lemma one_div_lt_one_div (ha : 0 < a) (hb : 0 < b) : 1 / a < 1 / b ↔ b < a :=
lt_iff_lt_of_le_iff_le (one_div_le_one_div hb ha)
def div_nonneg := @div_nonneg_of_nonneg_of_pos
lemma div_lt_div_right (hc : 0 < c) : a / c < b / c ↔ a < b :=
⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_pos h hc),
λ h, div_lt_div_of_lt_of_pos h hc⟩
lemma div_le_div_right (hc : 0 < c) : a / c ≤ b / c ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right hc)
lemma div_lt_div_right_of_neg (hc : c < 0) : a / c < b / c ↔ b < a :=
⟨lt_imp_lt_of_le_imp_le (λ h, div_le_div_of_le_of_neg h hc),
λ h, div_lt_div_of_lt_of_neg h hc⟩
lemma div_le_div_right_of_neg (hc : c < 0) : a / c ≤ b / c ↔ b ≤ a :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_right_of_neg hc)
lemma div_lt_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b < a / c ↔ c < b :=
(mul_lt_mul_left ha).trans (inv_lt_inv hb hc)
lemma div_le_div_left (ha : 0 < a) (hb : 0 < b) (hc : 0 < c) : a / b ≤ a / c ↔ c ≤ b :=
le_iff_le_iff_lt_iff_lt.2 (div_lt_div_left ha hc hb)
lemma div_lt_div_iff (b0 : 0 < b) (d0 : 0 < d) :
a / b < c / d ↔ a * d < c * b :=
by rw [lt_div_iff d0, div_mul_eq_mul_div, div_lt_iff b0]
lemma div_lt_div (hac : a < c) (hbd : d ≤ b) (c0 : 0 ≤ c) (d0 : 0 < d) :
a / b < c / d :=
(div_lt_div_iff (lt_of_lt_of_le d0 hbd) d0).2 (mul_lt_mul hac hbd d0 c0)
lemma div_lt_div' (hac : a ≤ c) (hbd : d < b) (c0 : 0 < c) (d0 : 0 < d) :
a / b < c / d :=
(div_lt_div_iff (lt_trans d0 hbd) d0).2 (mul_lt_mul' hac hbd (le_of_lt d0) c0)
lemma half_pos {a : α} (h : 0 < a) : 0 < a / 2 := div_pos h two_pos
lemma one_half_pos : (0:α) < 1 / 2 := half_pos zero_lt_one
def half_lt_self := @div_two_lt_of_pos
lemma one_half_lt_one : (1 / 2 : α) < 1 := half_lt_self zero_lt_one
lemma ivl_translate : (λx, x + c) '' {r:α | a ≤ r ∧ r ≤ b } = {r:α | a + c ≤ r ∧ r ≤ b + c} :=
calc (λx, x + c) '' {r | a ≤ r ∧ r ≤ b } = (λx, x - c) ⁻¹' {r | a ≤ r ∧ r ≤ b } :
congr_fun (set.image_eq_preimage_of_inverse
(assume a, add_sub_cancel a c) (assume b, sub_add_cancel b c)) _
... = {r | a + c ≤ r ∧ r ≤ b + c} :
set.ext $ by simp [-sub_eq_add_neg, le_sub_iff_add_le, sub_le_iff_le_add]
lemma ivl_stretch (hc : 0 < c) : (λx, x * c) '' {r | a ≤ r ∧ r ≤ b } = {r | a * c ≤ r ∧ r ≤ b * c} :=
calc (λx, x * c) '' {r | a ≤ r ∧ r ≤ b } = (λx, x / c) ⁻¹' {r | a ≤ r ∧ r ≤ b } :
congr_fun (set.image_eq_preimage_of_inverse
(assume a, mul_div_cancel _ $ ne_of_gt hc) (assume b, div_mul_cancel _ $ ne_of_gt hc)) _
... = {r | a * c ≤ r ∧ r ≤ b * c} :
set.ext $ by simp [le_div_iff, div_le_iff, hc]
instance linear_ordered_field.to_densely_ordered [linear_ordered_field α] : densely_ordered α :=
{ dense := assume a₁ a₂ h, ⟨(a₁ + a₂) / 2,
calc a₁ = (a₁ + a₁) / 2 : (add_self_div_two a₁).symm
... < (a₁ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_left h _) two_pos,
calc (a₁ + a₂) / 2 < (a₂ + a₂) / 2 : div_lt_div_of_lt_of_pos (add_lt_add_right h _) two_pos
... = a₂ : add_self_div_two a₂⟩ }
instance linear_ordered_field.to_no_top_order [linear_ordered_field α] : no_top_order α :=
{ no_top := assume a, ⟨a + 1, lt_add_of_le_of_pos (le_refl a) zero_lt_one ⟩ }
instance linear_ordered_field.to_no_bot_order [linear_ordered_field α] : no_bot_order α :=
{ no_bot := assume a, ⟨a + -1,
add_lt_of_le_of_neg (le_refl _) (neg_lt_of_neg_lt $ by simp [zero_lt_one]) ⟩ }
lemma inv_lt_one {a : α} (ha : 1 < a) : a⁻¹ < 1 :=
by rw [inv_eq_one_div]; exact div_lt_of_mul_lt_of_pos (lt_trans zero_lt_one ha) (by simp *)
lemma one_lt_inv (h₁ : 0 < a) (h₂ : a < 1) : 1 < a⁻¹ :=
by rw [inv_eq_one_div, lt_div_iff h₁]; simp [h₂]
lemma inv_le_one {a : α} (ha : 1 ≤ a) : a⁻¹ ≤ 1 :=
by rw [inv_eq_one_div]; exact div_le_of_le_mul (lt_of_lt_of_le zero_lt_one ha) (by simp *)
lemma one_le_inv {x : α} (hx0 : 0 < x) (hx : x ≤ 1) : 1 ≤ x⁻¹ :=
le_of_mul_le_mul_left (by simpa [mul_inv_cancel (ne.symm (ne_of_lt hx0))]) hx0
lemma mul_self_inj_of_nonneg {a b : α} (a0 : 0 ≤ a) (b0 : 0 ≤ b) : a * a = b * b ↔ a = b :=
(mul_self_eq_mul_self_iff a b).trans $ or_iff_left_of_imp $
λ h, by subst a; rw [le_antisymm (neg_nonneg.1 a0) b0, neg_zero]
lemma div_le_div_of_le_left {a b c : α} (ha : 0 ≤ a) (hb : 0 < b) (hc : 0 < c) (h : c ≤ b) :
a / b ≤ a / c :=
by haveI := classical.dec_eq α; exact
if ha0 : a = 0 then by simp [ha0]
else (div_le_div_left (lt_of_le_of_ne ha (ne.symm ha0)) hb hc).2 h
end linear_ordered_field
namespace nat
variables {α : Type*} [linear_ordered_field α]
lemma inv_pos_of_nat [linear_ordered_field α] {n : ℕ} : 0 < ((n : α) + 1)⁻¹ :=
inv_pos $ add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one
lemma one_div_pos_of_nat [linear_ordered_field α] {n : ℕ} : 0 < 1 / ((n : α) + 1) :=
by { rw one_div_eq_inv, exact inv_pos_of_nat }
end nat
section
variables {α : Type*} [discrete_linear_ordered_field α] (a b c : α)
lemma inv_pos' {a : α} : 0 < a⁻¹ ↔ 0 < a :=
⟨by rw [inv_eq_one_div]; exact pos_of_one_div_pos, inv_pos⟩
lemma inv_neg' {a : α} : a⁻¹ < 0 ↔ a < 0 :=
⟨by rw [inv_eq_one_div]; exact neg_of_one_div_neg, inv_lt_zero⟩
lemma inv_nonneg {a : α} : 0 ≤ a⁻¹ ↔ 0 ≤ a :=
le_iff_le_iff_lt_iff_lt.2 inv_neg'
lemma inv_nonpos {a : α} : a⁻¹ ≤ 0 ↔ a ≤ 0 :=
le_iff_le_iff_lt_iff_lt.2 inv_pos'
lemma abs_inv : abs a⁻¹ = (abs a)⁻¹ :=
have h : abs (1 / a) = 1 / abs a,
begin rw [abs_div, abs_of_nonneg], exact zero_le_one end,
by simp [*] at *
lemma inv_neg : (-a)⁻¹ = -(a⁻¹) :=
if h : a = 0
then by simp [h, inv_zero]
else by rwa [inv_eq_one_div, inv_eq_one_div, div_neg_eq_neg_div]
lemma inv_le_inv_of_le {a b : α} (hb : 0 < b) (h : b ≤ a) : a⁻¹ ≤ b⁻¹ :=
begin
rw [inv_eq_one_div, inv_eq_one_div],
exact one_div_le_one_div_of_le hb h
end
lemma div_nonneg' {a b : α} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a / b :=
(lt_or_eq_of_le hb).elim (div_nonneg ha) (λ h, by simp [h.symm])
end
|
544572ffbef5cded2cab6a65b848ab3d1df1f218 | a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91 | /tests/lean/run/set.lean | 56de4e71bca43b6bb24a410dd39767dee68a23b0 | [
"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 | 159 | lean | open bool nat
definition set (T : Type) := T → bool
definition mem {A : Type} (x : A) (s : set A) := s x
infix ` ∈ ` := mem
check 1 ∈ (λ x : nat, tt)
|
e08b8a847f4ebb5ab94b4e075e5dedd85fbe530c | c9e78e68dc955b2325401aec3a6d3240cd8b83f4 | /src/myLTS.lean | 5de03df76ebda86e2fd9e2747a270dba8185aaa1 | [] | no_license | loganrjmurphy/lean-strategies | 4b8dd54771bb421c929a8bcb93a528ce6c1a70f1 | 832ea28077701b977b4fc59ed9a8ce6911654e59 | refs/heads/master | 1,682,732,168,860 | 1,621,444,295,000 | 1,621,444,295,000 | 278,458,841 | 3 | 0 | null | 1,613,755,728,000 | 1,594,324,763,000 | Lean | UTF-8 | Lean | false | false | 734 | lean | import LTS
inductive S
| pay | select | beer
| soda| serve
open S
inductive A
| insert_coin
| choose_b | choose_s
| get_soda | get_beer | restart open A
def TR : set (S × A × S) :=
{ (pay,insert_coin, select), (select, choose_b, beer),
(select, choose_s, soda), (soda, get_soda, serve),
(beer, get_beer, serve), (serve, restart, pay) }
def myLTS : LTS := LTS.mk S A TR
@[instance] def S_to_myLTSS : has_coe S (myLTS.S) :=⟨id⟩
@[instance] def S_to_form : has_coe myLTS.S (formula myLTS) :=
⟨λ s, formula.state s⟩
@[instance] def S_to_form' : has_coe S (formula myLTS) :=
⟨λ s, formula.state s⟩
@[instance] def Act_to_form : has_coe A (formula myLTS) :=
⟨λ a, formula.act a⟩
|
d430829119822b070cd7b840b049c27edc6bdd4d | aa2345b30d710f7e75f13157a35845ee6d48c017 | /data/finset.lean | 6d674d299538d4a728cff6a845e0b3c055351bbf | [
"Apache-2.0"
] | permissive | CohenCyril/mathlib | 5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe | a12d5a192f5923016752f638d19fc1a51610f163 | refs/heads/master | 1,586,031,957,957 | 1,541,432,824,000 | 1,541,432,824,000 | 156,246,337 | 0 | 0 | Apache-2.0 | 1,541,434,514,000 | 1,541,434,513,000 | null | UTF-8 | Lean | false | false | 70,640 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura, Jeremy Avigad, Minchao Wu, Mario Carneiro
Finite sets.
-/
import logic.embedding order.boolean_algebra algebra.order_functions
data.multiset data.sigma.basic data.set.lattice
open multiset subtype nat lattice
variables {α : Type*} {β : Type*} {γ : Type*}
/-- `finset α` is the type of finite sets of elements of `α`. It is implemented
as a multiset (a list up to permutation) which has no duplicate elements. -/
structure finset (α : Type*) :=
(val : multiset α)
(nodup : nodup val)
namespace finset
theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t
| ⟨s, _⟩ ⟨t, _⟩ rfl := rfl
@[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t :=
⟨eq_of_veq, congr_arg _⟩
@[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 :=
erase_dup_eq_self.2 s.2
instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α)
| s₁ s₂ := decidable_of_iff _ val_inj
/- membership -/
instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩
theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl
@[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl
instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) :=
multiset.decidable_mem _ _
/- set coercion -/
/-- Convert a finset to a set in the natural way. -/
def to_set (s : finset α) : set α := {x | x ∈ s}
instance : has_lift (finset α) (set α) := ⟨to_set⟩
@[simp] lemma mem_coe {a : α} {s : finset α} : a ∈ (↑s : set α) ↔ a ∈ s := iff.rfl
@[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = ↑s := rfl
/- extensionality -/
theorem ext {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ :=
val_inj.symm.trans $ nodup_ext s₁.2 s₂.2
@[extensionality]
theorem ext' {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ :=
ext.2
@[simp] theorem coe_inj {s₁ s₂ : finset α} : (↑s₁ : set α) = ↑s₂ ↔ s₁ = s₂ :=
(set.ext_iff _ _).trans ext.symm
/- subset -/
instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩
theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl
@[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _
theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans
theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset
theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ :=
ext.2 $ λ a, ⟨@H₁ a, @H₂ a⟩
theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl
@[simp] theorem coe_subset {s₁ s₂ : finset α} :
(↑s₁ : set α) ⊆ ↑s₂ ↔ s₁ ⊆ s₂ := iff.rfl
@[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2
instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩
instance : partial_order (finset α) :=
{ le := (⊆),
lt := (⊂),
le_refl := subset.refl,
le_trans := @subset.trans _,
le_antisymm := @subset.antisymm _ }
theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ :=
le_antisymm_iff
@[simp] theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl
@[simp] theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl
@[simp] lemma coe_ssubset {s₁ s₂ : finset α} : (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊂ s₂ :=
show (↑s₁ : set α) ⊂ ↑s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁,
by simp only [set.ssubset_iff_subset_not_subset, finset.coe_subset]
@[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ :=
and_congr val_le_iff $ not_congr val_le_iff
/- empty -/
protected def empty : finset α := ⟨0, nodup_zero⟩
instance : has_emptyc (finset α) := ⟨finset.empty⟩
instance : inhabited (finset α) := ⟨∅⟩
@[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl
@[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id
@[simp] theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅
| e := not_mem_empty a $ e ▸ h
@[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _
theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ :=
eq_of_veq (eq_zero_of_forall_not_mem H)
lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s :=
⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩
@[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅
theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero
theorem exists_mem_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a : α, a ∈ s :=
exists_mem_of_ne_zero (mt val_eq_zero.1 h)
@[simp] lemma coe_empty : ↑(∅ : finset α) = (∅ : set α) := rfl
/-- `singleton a` is the set `{a}` containing `a` and nothing else. -/
def singleton (a : α) : finset α := ⟨_, nodup_singleton a⟩
local prefix `ι`:90 := singleton
@[simp] theorem singleton_val (a : α) : (ι a).1 = a :: 0 := rfl
@[simp] theorem mem_singleton {a b : α} : b ∈ ι a ↔ b = a := mem_singleton
theorem not_mem_singleton {a b : α} : a ∉ ι b ↔ a ≠ b := not_iff_not_of_iff mem_singleton
theorem mem_singleton_self (a : α) : a ∈ ι a := or.inl rfl
theorem singleton_inj {a b : α} : ι a = ι b ↔ a = b :=
⟨λ h, mem_singleton.1 (h ▸ mem_singleton_self _), congr_arg _⟩
@[simp] theorem singleton_ne_empty (a : α) : ι a ≠ ∅ := ne_empty_of_mem (mem_singleton_self _)
@[simp] lemma coe_singleton (a : α) : ↑(ι a) = ({a} : set α) := rfl
/- insert -/
section decidable_eq
variables [decidable_eq α]
/-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/
instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩
@[simp] theorem has_insert_eq_insert (a : α) (s : finset α) : has_insert.insert a s = insert a s := rfl
theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl
@[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl
theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a :: s.1) :=
by rw [erase_dup_cons, erase_dup_eq_self]; refl
theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a :: s.1 :=
by rw [insert_val, ndinsert_of_not_mem h]
@[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert
theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1
theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h
theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s :=
(mem_insert.1 h).resolve_left
@[simp] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a ↑s : set α) :=
set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff]
@[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s :=
eq_of_veq $ ndinsert_of_mem h
@[simp] theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) :=
ext.2 $ λ x, by simp only [finset.mem_insert, or.left_comm]
@[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s :=
ext.2 $ λ x, by simp only [finset.mem_insert, or.assoc.symm, or_self]
@[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ :=
ne_empty_of_mem (mem_insert_self a s)
theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t :=
by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib]
theorem subset_insert [h : decidable_eq α] (a : α) (s : finset α) : s ⊆ insert a s :=
λ b, mem_insert_of_mem
theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t :=
insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩
lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a, a ∉ s ∧ insert a s ⊆ t) :=
iff.intro
(assume ⟨h₁, h₂⟩,
have ∃a ∈ t, a ∉ s, by simpa only [finset.subset_iff, classical.not_forall] using h₂,
let ⟨a, hat, has⟩ := this in ⟨a, has, insert_subset.mpr ⟨hat, h₁⟩⟩)
(assume ⟨a, hat, has⟩,
let ⟨h₁, h₂⟩ := insert_subset.mp has in
⟨h₂, assume h, hat $ h h₁⟩)
lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s :=
ssubset_iff.mpr ⟨a, h, subset.refl _⟩
@[recursor 6] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α]
(h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s
| ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin
cases nodup_cons.1 nd with m nd',
rw [← (eq_of_veq _ : insert a (finset.mk s _) = ⟨a::s, nd⟩)],
{ exact h₂ (by exact m) (IH nd') },
{ rw [insert_val, ndinsert_of_not_mem m] }
end) nd
@[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α]
(s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s :=
finset.induction h₁ h₂ s
@[simp] theorem singleton_eq_singleton (a : α) : _root_.singleton a = ι a := rfl
@[simp] theorem insert_empty_eq_singleton (a : α) : {a} = ι a := rfl
@[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = ι a :=
insert_eq_of_mem $ mem_singleton_self _
/- union -/
/-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/
instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩
theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl
@[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 :=
ndunion_eq_union s₁.2
@[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion
theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h
theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h
theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ :=
by rw [mem_union, not_or_distrib]
@[simp] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (↑s₁ ∪ ↑s₂ : set α) := set.ext $ λ x, mem_union
theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ :=
val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩)
theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _
theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _
@[simp] theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ :=
ext.2 $ λ x, by simp only [mem_union, or_comm]
instance : is_commutative (finset α) (∪) := ⟨union_comm⟩
@[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) :=
ext.2 $ λ x, by simp only [mem_union, or_assoc]
instance : is_associative (finset α) (∪) := ⟨union_assoc⟩
@[simp] theorem union_idempotent (s : finset α) : s ∪ s = s :=
ext.2 $ λ _, mem_union.trans $ or_self _
instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩
theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) :=
ext.2 $ λ _, by simp only [mem_union, or.left_comm]
theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ :=
ext.2 $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)]
@[simp] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s
@[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s :=
ext.2 $ λ x, mem_union.trans $ or_false _
@[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s :=
ext.2 $ λ x, mem_union.trans $ false_or _
theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl
@[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) :=
by simp only [insert_eq, union_assoc]
@[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) :=
by simp only [insert_eq, union_left_comm]
theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t :=
by simp only [insert_union, union_insert, insert_idem]
/- inter -/
/-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/
instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩
theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl
@[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 :=
ndinter_eq_inter s₁.2
@[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter
theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1
theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2
theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ :=
and_imp.1 mem_inter.2
theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left
theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right
theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ :=
by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial
@[simp] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (↑s₁ ∩ ↑s₂ : set α) := set.ext $ λ _, mem_inter
@[simp] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ :=
ext.2 $ λ _, by simp only [mem_inter, and_comm]
@[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) :=
ext.2 $ λ _, by simp only [mem_inter, and_assoc]
@[simp] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) :=
ext.2 $ λ _, by simp only [mem_inter, and.left_comm]
@[simp] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ :=
ext.2 $ λ _, by simp only [mem_inter, and.right_comm]
@[simp] theorem inter_self (s : finset α) : s ∩ s = s :=
ext.2 $ λ _, mem_inter.trans $ and_self _
@[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ :=
ext.2 $ λ _, mem_inter.trans $ and_false _
@[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ :=
ext.2 $ λ _, mem_inter.trans $ false_and _
@[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) :
insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) :=
ext.2 $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h,
by simp only [mem_inter, mem_insert, or_and_distrib_left, this]
@[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) :
s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) :=
by rw [inter_comm, insert_inter_of_mem h, inter_comm]
@[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) :
insert a s₁ ∩ s₂ = s₁ ∩ s₂ :=
ext.2 $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H,
by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or]
@[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) :
s₁ ∩ insert a s₂ = s₁ ∩ s₂ :=
by rw [inter_comm, insert_inter_of_not_mem h, inter_comm]
@[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : ι a ∩ s = ι a :=
show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter]
@[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : ι a ∩ s = ∅ :=
eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h
@[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ ι a = ι a :=
by rw [inter_comm, singleton_inter_of_mem h]
@[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ ι a = ∅ :=
by rw [inter_comm, singleton_inter_of_not_mem h]
/- lattice laws -/
instance : lattice (finset α) :=
{ sup := (∪),
sup_le := assume a b c, union_subset,
le_sup_left := subset_union_left,
le_sup_right := subset_union_right,
inf := (∩),
le_inf := assume a b c, subset_inter,
inf_le_left := inter_subset_left,
inf_le_right := inter_subset_right,
..finset.partial_order }
@[simp] theorem sup_eq_union (s t : finset α) : s ⊔ t = s ∪ t := rfl
@[simp] theorem inf_eq_inter (s t : finset α) : s ⊓ t = s ∩ t := rfl
instance : semilattice_inf_bot (finset α) :=
{ bot := ∅, bot_le := empty_subset, ..finset.lattice.lattice }
instance : distrib_lattice (finset α) :=
{ le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c,
by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt};
simp only [true_or, imp_true_iff, true_and, or_true],
..finset.lattice.lattice }
theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left
theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right
theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left
theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right
/- erase -/
/-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are
not equal to `a`. -/
def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩
@[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl
@[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s :=
mem_erase_iff_of_nodup s.2
theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2
@[simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl
theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a :=
by simp only [mem_erase]; exact and.left
theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase
theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b :=
by simp only [mem_erase]; exact and.intro
theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s :=
ext.2 $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or];
apply and_iff_right_of_imp; rintro H rfl; exact h H
theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s :=
ext.2 $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and];
apply or_iff_right_of_imp; rintro rfl; exact h
theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a :=
val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h
theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _
@[simp] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (↑s \ {a} : set α) :=
set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl
lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s :=
calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _
... = _ : insert_erase h
theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s :=
eq_of_veq $ erase_of_not_mem h
theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t :=
by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp];
exact forall_congr (λ x, forall_swap)
theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s :=
subset_insert_iff.1 $ subset.refl _
theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) :=
subset_insert_iff.2 $ subset.refl _
/- sdiff -/
/-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/
instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le (sub_le_self _ _) s₁.2⟩⟩
@[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} :
a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2
@[simp] theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ :=
ext.2 $ λ a, by simpa only [mem_sdiff, mem_union, or_comm,
or_and_distrib_left, dec_em, and_true] using or_iff_right_of_imp (@h a)
@[simp] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ :=
(union_comm _ _).trans (sdiff_union_of_subset h)
@[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ :=
eq_empty_of_forall_not_mem $
by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h
@[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ :=
(inter_comm _ _).trans (inter_sdiff_self _ _)
theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ :=
by simpa only [subset_iff, mem_sdiff, and_imp] using λ a m₁ m₂, and.intro (h₁ m₁) (mt (@h₂ _) m₂)
@[simp] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (↑s₁ \ ↑s₂ : set α) :=
set.ext $ λ _, mem_sdiff
end decidable_eq
/- attach -/
/-- `attach s` takes the elements of `s` and forms a new set of elements of the
subtype `{x // x ∈ s}`. -/
def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩
@[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl
@[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _
@[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl
section decidable_pi_exists
variables {s : finset α}
instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] :
decidable (∀a (h : a ∈ s), p a h) :=
multiset.decidable_dforall_multiset
/-- decidable equality for functions whose domain is bounded by finsets -/
instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] :
decidable_eq (Πa∈s, β a) :=
multiset.decidable_eq_pi_multiset
instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] :
decidable (∃a (h : a ∈ s), p a h) :=
multiset.decidable_dexists_multiset
end decidable_pi_exists
/- filter -/
section filter
variables {p q : α → Prop} [decidable_pred p] [decidable_pred q]
/-- `filter p s` is the set of elements of `s` that satisfy `p`. -/
def filter (p : α → Prop) [decidable_pred p] (s : finset α) : finset α :=
⟨_, nodup_filter p s.2⟩
@[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl
@[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter
@[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _
theorem filter_filter (s : finset α) :
(s.filter p).filter q = s.filter (λa, p a ∧ q a) :=
ext.2 $ assume a, by simp only [mem_filter, and_comm, and.left_comm]
@[simp] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] :
@finset.filter α (λ _, true) h s = s :=
by ext; simp
@[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ :=
ext.2 $ assume a, by simp only [mem_filter, and_false]; refl
lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s :=
eq_of_veq $ filter_congr H
variable [decidable_eq α]
theorem filter_union (s₁ s₂ : finset α) :
(s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p :=
ext.2 $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right]
theorem filter_or (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q :=
ext.2 $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left]
theorem filter_and (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q :=
ext.2 $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self]
theorem filter_not (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p :=
ext.2 $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $
λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm
theorem sdiff_eq_filter (s₁ s₂ : finset α) :
s₁ \ s₂ = filter (∉ s₂) s₁ := ext.2 $ λ _, by simp only [mem_sdiff, mem_filter]
theorem filter_union_filter_neg_eq (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s :=
by simp only [filter_not, union_sdiff_of_subset (filter_subset s)]
theorem filter_inter_filter_neg_eq (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ :=
by simp only [filter_not, inter_sdiff_self]
@[simp] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) :=
set.ext $ λ _, mem_filter
end filter
/- range -/
section range
variables {n m l : ℕ}
/-- `range n` is the set of integers less than `n`. -/
def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩
@[simp] theorem range_val (n : ℕ) : (range n).1 = multiset.range n := rfl
@[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range
@[simp] theorem range_zero : range 0 = ∅ := rfl
@[simp] theorem range_succ : range (succ n) = insert n (range n) :=
eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm
@[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self
@[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset
theorem exists_nat_subset_range (s : finset ℕ) : ∃n : ℕ, s ⊆ range n :=
finset.induction_on s ⟨0, empty_subset _⟩ $ λ a s ha ⟨n, hn⟩,
⟨max (a + 1) n, insert_subset.2
⟨by simpa only [mem_range] using le_max_left (a+1) n,
subset.trans hn (by simpa only [range_subset] using le_max_right (a+1) n)⟩⟩
end range
/- useful rules for calculations with quantifiers -/
theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false :=
by simp only [not_mem_empty, false_and, exists_false]
theorem exists_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) :=
by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left]
theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true :=
iff_true_intro $ λ _, false.elim
theorem forall_mem_insert [d : decidable_eq α]
(a : α) (s : finset α) (p : α → Prop) :
(∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) :=
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
end finset
namespace option
/-- Construct an empty or singleton finset from an `option` -/
def to_finset (o : option α) : finset α :=
match o with
| none := ∅
| some a := finset.singleton a
end
@[simp] theorem to_finset_none : none.to_finset = (∅ : finset α) := rfl
@[simp] theorem to_finset_some {a : α} : (some a).to_finset = finset.singleton a := rfl
@[simp] theorem mem_to_finset {a : α} {o : option α} : a ∈ o.to_finset ↔ a ∈ o :=
by cases o; simp only [to_finset, finset.mem_singleton, option.mem_def, eq_comm]; refl
end option
/- erase_dup on list and multiset -/
namespace multiset
variable [decidable_eq α]
/-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/
def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩
@[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl
theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset :=
finset.val_inj.1 (erase_dup_eq_self.2 n).symm
@[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s :=
mem_erase_dup
@[simp] lemma to_finset_cons (a : α) (s : multiset α) :
to_finset (a :: s) = insert a (to_finset s) :=
finset.eq_of_veq erase_dup_cons
end multiset
namespace list
variable [decidable_eq α]
/-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/
def to_finset (l : list α) : finset α := multiset.to_finset l
@[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl
theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset :=
multiset.to_finset_eq n
@[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l :=
mem_erase_dup
@[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ :=
rfl
@[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) :=
finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h]
end list
namespace finset
section map
open function
def map (f : α ↪ β) (s : finset α) : finset β :=
⟨s.1.map f, nodup_map f.2 s.2⟩
@[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl
@[simp] theorem map_empty (f : α ↪ β) (s : finset α) : (∅ : finset α).map f = ∅ := rfl
variables {f : α ↪ β} {s : finset α}
@[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b :=
mem_map.trans $ by simp only [exists_prop]; refl
theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s :=
mem_map_of_inj f.2
@[simp] theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f :=
(mem_map' _).2
theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} :
s.to_finset.map f = (s.map f).to_finset :=
ext.2 $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset]
theorem map_refl : s.map (embedding.refl _) = s :=
ext.2 $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right
theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) :=
eq_of_veq $ by simp only [map_val, multiset.map_map]; refl
theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ :=
⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs,
λ h, by simp [subset_def, map_subset_map h]⟩
theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ :=
by simp only [subset.antisymm_iff, map_subset_map]
def map_embedding (f : α ↪ β) : finset α ↪ finset β := ⟨map f, λ s₁ s₂, map_inj.1⟩
@[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl
theorem map_filter {p : β → Prop} [decidable_pred p] :
(s.map f).filter p = (s.filter (p ∘ f)).map f :=
ext.2 $ λ b, by simp only [mem_filter, mem_map, exists_prop, and_assoc]; exact
⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, h1, h2, rfl⟩,
by rintro ⟨x, h1, h2, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩
theorem map_union [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f :=
ext.2 $ λ _, by simp only [mem_map, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib]
theorem map_inter [decidable_eq α] [decidable_eq β]
{f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f :=
ext.2 $ λ b, by simp only [mem_map, mem_inter, exists_prop]; exact
⟨by rintro ⟨a, ⟨m₁, m₂⟩, rfl⟩; exact ⟨⟨a, m₁, rfl⟩, ⟨a, m₂, rfl⟩⟩,
by rintro ⟨⟨a, m₁, e⟩, ⟨a', m₂, rfl⟩⟩; cases f.2 e; exact ⟨_, ⟨m₁, m₂⟩, rfl⟩⟩
@[simp] theorem map_singleton (f : α ↪ β) (a : α) : (singleton a).map f = singleton (f a) :=
ext.2 $ λ _, by simp only [mem_map, mem_singleton, exists_prop, exists_eq_left]; exact eq_comm
@[simp] theorem map_insert [decidable_eq α] [decidable_eq β]
(f : α ↪ β) (a : α) (s : finset α) :
(insert a s).map f = insert (f a) (s.map f) :=
by simp only [insert_eq, insert_empty_eq_singleton, map_union, map_singleton]
@[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s :=
eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _
end map
section image
variables [decidable_eq β]
/-- `image f s` is the forward image of `s` under `f`. -/
def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset
@[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl
@[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl
variables {f : α → β} {s : finset α}
@[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b :=
by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop]
@[simp] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f :=
mem_image.2 ⟨_, h, rfl⟩
@[simp] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s :=
set.ext $ λ _, mem_image.trans $ by simp only [exists_prop]; refl
theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset :=
ext.2 $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map]
@[simp] theorem image_val_of_inj_on (H : ∀x∈s, ∀y∈s, f x = f y → x = y) : (image f s).1 = s.1.map f :=
multiset.erase_dup_eq_self.2 (nodup_map_on H s.2)
theorem image_id [decidable_eq α] : s.image id = s :=
ext.2 $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right]
theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) :=
eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map]
theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f :=
by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h]
theorem image_filter {p : β → Prop} [decidable_pred p] :
(s.image f).filter p = (s.filter (p ∘ f)).image f :=
ext.2 $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact
⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩,
by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩
theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f :=
ext.2 $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib]
theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f :=
ext.2 $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b,
⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩,
λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩.
@[simp] theorem image_singleton [decidable_eq α] (f : α → β) (a : α) : (singleton a).image f = singleton (f a) :=
ext.2 $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm
@[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) :
(insert a s).image f = insert (f a) (s.image f) :=
by simp only [insert_eq, insert_empty_eq_singleton, image_singleton, image_union]
@[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ :=
⟨λ h, eq_empty_of_forall_not_mem $
λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩
lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s :=
eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self]
@[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} :
attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s})
((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) :=
ext.2 $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx)
(assume h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h)
(assume h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩),
λ _, finset.mem_attach _ _⟩
theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f :=
eq_of_veq $ (multiset.erase_dup_eq_self.2 (s.map f).2).symm
lemma image_const [decidable_eq β] {s : finset α} (h : s ≠ ∅) (b : β) : s.image (λa, b) = singleton b :=
ext.2 $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right,
exists_mem_of_ne_empty h, true_and, mem_singleton, eq_comm]
end image
/- card -/
section card
/-- `card s` is the cardinality (number of elements) of `s`. -/
def card (s : finset α) : nat := s.1.card
theorem card_def (s : finset α) : s.card = s.1.card := rfl
@[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl
@[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ :=
card_eq_zero.trans val_eq_zero
theorem card_pos {s : finset α} : 0 < card s ↔ s ≠ ∅ :=
pos_iff_ne_zero.trans $ not_congr card_eq_zero
@[simp] theorem card_insert_of_not_mem [decidable_eq α]
{a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 :=
by simpa only [card_cons, card, insert_val] using
congr_arg multiset.card (ndinsert_of_not_mem h)
theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 :=
by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right},
rw [card_insert_of_not_mem h]]
@[simp] theorem card_singleton (a : α) : card (singleton a) = 1 := card_singleton _
theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem
@[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n
@[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach
theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α}
(H : ∀x∈s, ∀y∈s, f x = f y → x = y) : card (image f s) = card s :=
by simp only [card, image_val_of_inj_on H, card_map]
theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α)
(H : function.injective f) : card (image f s) = card s :=
card_image_of_inj_on $ λ x _ y _ h, H h
lemma card_eq_of_bijective [decidable_eq α] {s : finset α} {n : ℕ}
(f : ∀i, i < n → α)
(hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s)
(f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) :
card s = n :=
have ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a,
from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩,
assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩,
have s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)),
by simpa only [ext, mem_image, exists_prop, subtype.exists, mem_attach, true_and],
calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) :
by rw [this]
... = card ((range n).attach) :
card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq,
subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq
... = card (range n) : card_attach
... = n : card_range n
lemma card_eq_succ [decidable_eq α] {s : finset α} {a : α} {n : ℕ} :
s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) :=
iff.intro
(assume eq,
have card s > 0, from eq.symm ▸ nat.zero_lt_succ _,
let ⟨a, has⟩ := finset.exists_mem_of_ne_empty $ card_pos.mp this in
⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩)
(assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat)
theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t :=
multiset.card_le_of_le ∘ val_le_iff.mpr
theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t :=
eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂
lemma card_lt_card [decidable_eq α] {s t : finset α} (h : s ⊂ t) : s.card < t.card :=
card_lt_of_lt (val_lt_iff.2 h)
lemma card_le_card_of_inj_on [decidable_eq α] [decidable_eq β] {s : finset α} {t : finset β}
(f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) :
card s ≤ card t :=
calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj]
... ≤ card t : card_le_of_subset $
assume x hx, match x, finset.mem_image.1 hx with _, ⟨a, ha, rfl⟩ := hf a ha end
lemma card_le_of_inj_on [decidable_eq α] {n} {s : finset α}
(f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀i j, i<n → j<n → f i = f j → i = j) : n ≤ card s :=
calc n = card (range n) : (card_range n).symm
... ≤ card s : card_le_card_of_inj_on f
(by simpa only [mem_range])
(by simp only [mem_range]; exact assume a₁ h₁ a₂ h₂, f_inj a₁ a₂ h₁ h₂)
@[elab_as_eliminator] lemma strong_induction_on {p : finset α → Sort*} :
∀ (s : finset α), (∀s, (∀t ⊂ s, p t) → p s) → p s
| ⟨s, nd⟩ ih := multiset.strong_induction_on s
(λ s IH nd, ih ⟨s, nd⟩ (λ ⟨t, nd'⟩ ss, IH t (val_lt_iff.2 ss) nd')) nd
@[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop}
(s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀t ⊆ s, p t) → p (insert a s)) : p s :=
finset.strong_induction_on s $ λ s,
finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $
λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _)
lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β)
(h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b)
(h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card :=
by haveI := classical.prop_decidable; exact
calc s.card = s.attach.card : card_attach.symm
... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card :
eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h)))
... = t.card : congr_arg card (finset.ext.2 $ λ b,
⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _,
λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩)
lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) :
(s ∪ t).card + (s ∩ t).card = s.card + t.card :=
finset.induction_on t (by simp) (λ a, by by_cases a ∈ s; simp * {contextual := tt})
lemma card_union_le [decidable_eq α] (s t : finset α) :
(s ∪ t).card ≤ s.card + t.card :=
card_union_add_card_inter s t ▸ le_add_right _ _
lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β}
(f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t)
(hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂)
(hst : card t ≤ card s) :
(∀ b ∈ t, ∃ a ha, b = f a ha) :=
by haveI := classical.dec_eq β; exact
λ b hb,
have h : card (image (λ (a : {a // a ∈ s}), f (a.val) a.2) (attach s)) = card s,
from @card_attach _ s ▸ card_image_of_injective _
(λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h),
have h₁ : image (λ a : {a // a ∈ s}, f a.1 a.2) s.attach = t :=
eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in
ha₂ ▸ hf _ _) (by simp [hst, h]),
begin
rw ← h₁ at hb,
rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩,
exact ⟨a, a.2, ha₂.symm⟩,
end
end card
section bind
variables [decidable_eq β] {s : finset α} {t : α → finset β}
/-- `bind s t` is the union of `t x` over `x ∈ s` -/
protected def bind (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset
@[simp] theorem bind_val (s : finset α) (t : α → finset β) :
(s.bind t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl
@[simp] theorem bind_empty : finset.bind ∅ t = ∅ := rfl
@[simp] theorem mem_bind {b : β} : b ∈ s.bind t ↔ ∃a∈s, b ∈ t a :=
by simp only [mem_def, bind_val, mem_erase_dup, mem_bind, exists_prop]
@[simp] theorem bind_insert [decidable_eq α] {a : α} : (insert a s).bind t = t a ∪ s.bind t :=
ext.2 $ λ x, by simp only [mem_bind, exists_prop, mem_union, mem_insert,
or_and_distrib_right, exists_or_distrib, exists_eq_left]
-- ext.2 $ λ x, by simp [or_and_distrib_right, exists_or_distrib]
@[simp] lemma singleton_bind [decidable_eq α] {a : α} : (singleton a).bind t = t a :=
show (insert a ∅ : finset α).bind t = t a, from bind_insert.trans $ union_empty _
theorem image_bind [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} :
(s.image f).bind t = s.bind (λa, t (f a)) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [image_insert, bind_insert, ih])
theorem bind_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} :
(s.bind t).image f = s.bind (λa, (t a).image f) :=
by haveI := classical.dec_eq α; exact
finset.induction_on s rfl (λ a s has ih,
by simp only [bind_insert, image_union, ih])
theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) :
(s.bind t).to_finset = s.to_finset.bind (λa, (t a).to_finset) :=
ext.2 $ λ x, by simp only [multiset.mem_to_finset, mem_bind, multiset.mem_bind, exists_prop]
lemma bind_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bind t₁ ⊆ s.bind t₂ :=
have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a),
from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩,
by simpa only [subset_iff, mem_bind, exists_imp_distrib, and_imp, exists_prop]
lemma bind_singleton {f : α → β} : s.bind (λa, {f a}) = s.image f :=
ext.2 $ λ x, by simp only [mem_bind, mem_image, insert_empty_eq_singleton, mem_singleton, eq_comm]
lemma image_bind_filter_eq [decidable_eq α] (s : finset β) (g : β → α) :
(s.image g).bind (λa, s.filter $ (λc, g c = a)) = s :=
begin
ext b,
simp,
split,
{ rintros ⟨a, ⟨b', _, _⟩, hb, _⟩, exact hb },
{ rintros hb, exact ⟨g b, ⟨b, hb, rfl⟩, hb, rfl⟩ }
end
end bind
section prod
variables {s : finset α} {t : finset β}
/-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/
protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩
@[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl
@[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product
theorem product_eq_bind [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) :
s.product t = s.bind (λa, t.image $ λb, (a, b)) :=
ext.2 $ λ ⟨x, y⟩, by simp only [mem_product, mem_bind, mem_image, exists_prop, prod.mk.inj_iff,
and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left]
@[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t :=
multiset.card_product _ _
end prod
section sigma
variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)}
/-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/
protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) :=
⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩
@[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma
theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)}
(H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ :=
λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩
theorem sigma_eq_bind [decidable_eq α] [∀a, decidable_eq (σ a)] (s : finset α) (t : Πa, finset (σ a)) :
s.sigma t = s.bind (λa, (t a).image $ λb, ⟨a, b⟩) :=
ext.2 $ λ ⟨x, y⟩, by simp only [mem_sigma, mem_bind, mem_image, exists_prop,
and.left_comm, exists_and_distrib_left, exists_eq_left, heq_iff_eq, exists_eq_right]
end sigma
section pi
variables {δ : α → Type*} [decidable_eq α]
def pi (s : finset α) (t : Πa, finset (δ a)) : finset (Πa∈s, δ a) :=
⟨s.1.pi (λ a, (t a).1), nodup_pi s.2 (λ a _, (t a).2)⟩
@[simp] lemma pi_val (s : finset α) (t : Πa, finset (δ a)) :
(s.pi t).1 = s.1.pi (λ a, (t a).1) := rfl
@[simp] lemma mem_pi {s : finset α} {t : Πa, finset (δ a)} {f : Πa∈s, δ a} :
f ∈ s.pi t ↔ (∀a (h : a ∈ s), f a h ∈ t a) :=
mem_pi _ _ _
def pi.empty (β : α → Sort*) [decidable_eq α] (a : α) (h : a ∈ (∅ : finset α)) : β a :=
multiset.pi.empty β a h
def pi.cons (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) : δ a' :=
multiset.pi.cons s.1 a b f _ (multiset.mem_cons.2 $ mem_insert.symm.2 h)
@[simp] lemma pi.cons_same (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (h : a ∈ insert a s) :
pi.cons s a b f a h = b :=
multiset.pi.cons_same _
lemma pi.cons_ne {s : finset α} {a a' : α} {b : δ a} {f : Πa, a ∈ s → δ a} {h : a' ∈ insert a s} (ha : a ≠ a') :
pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) :=
multiset.pi.cons_ne _ _
lemma injective_pi_cons {a : α} {b : δ a} {s : finset α} (hs : a ∉ s) :
function.injective (pi.cons s a b) :=
assume e₁ e₂ eq,
@multiset.injective_pi_cons α _ δ a b s.1 hs _ _ $
funext $ assume e, funext $ assume h,
have pi.cons s a b e₁ e (by simpa only [mem_cons, mem_insert] using h) = pi.cons s a b e₂ e (by simpa only [mem_cons, mem_insert] using h),
by rw [eq],
this
@[simp] lemma pi_empty {t : Πa:α, finset (δ a)} :
pi (∅ : finset α) t = singleton (pi.empty δ) := rfl
@[simp] lemma pi_insert [∀a, decidable_eq (δ a)]
{s : finset α} {t : Πa:α, finset (δ a)} {a : α} (ha : a ∉ s) :
pi (insert a s) t = (t a).bind (λb, (pi s t).image (pi.cons s a b)) :=
begin
apply eq_of_veq,
rw ← multiset.erase_dup_eq_self.2 (pi (insert a s) t).2,
refine (λ s' (h : s' = a :: s.1), (_ : erase_dup (multiset.pi s' (λ a, (t a).1)) =
erase_dup ((t a).1.bind $ λ b,
erase_dup $ (multiset.pi s.1 (λ (a : α), (t a).val)).map $
λ f a' h', multiset.pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha),
subst s', rw pi_cons,
congr, funext b,
rw multiset.erase_dup_eq_self.2,
exact multiset.nodup_map (multiset.injective_pi_cons ha) (pi s t).2,
end
end pi
section powerset
def powerset (s : finset α) : finset (finset α) :=
⟨s.1.powerset.pmap finset.mk
(λ t h, nodup_of_le (mem_powerset.1 h) s.2),
nodup_pmap (λ a ha b hb, congr_arg finset.val)
(nodup_powerset.2 s.2)⟩
@[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t :=
by cases s; simp only [powerset, mem_mk, mem_pmap, mem_powerset, exists_prop, exists_eq_right]; rw ← val_le_iff
@[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s :=
mem_powerset.2 (empty_subset _)
@[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s :=
mem_powerset.2 (subset.refl _)
@[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t :=
⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _),
λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩
@[simp] theorem card_powerset (s : finset α) :
card (powerset s) = 2 ^ card s :=
(card_pmap _ _ _).trans (card_powerset s.1)
end powerset
section subtype
variables [decidable_eq α]
protected def subtype (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) :=
(s.filter p).attach.image $ λ⟨a, ha⟩, ⟨a, (mem_filter.1 ha).2⟩
@[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} :
∀{a : subtype p}, a ∈ s.subtype p ↔ a.val ∈ s
| ⟨a, ha⟩ := by simp only [finset.subtype, mem_image, exists_prop,
mem_attach, true_and, subtype.exists, exists_eq_right, mem_filter, ha, and_true]
end subtype
section fold
variables (op : β → β → β) [hc : is_commutative β op] [ha : is_associative β op]
local notation a * b := op a b
include hc ha
/-- `fold op b f s` folds the commutative associative operation `op` over the
`f`-image of `s`, i.e. `fold (+) b f {1,2,3} = `f 1 + f 2 + f 3 + b`. -/
def fold (b : β) (f : α → β) (s : finset α) : β := (s.1.map f).fold op b
variables {op} {f : α → β} {b : β} {s : finset α} {a : α}
@[simp] theorem fold_empty : (∅ : finset α).fold op b f = b := rfl
@[simp] theorem fold_insert [decidable_eq α] (h : a ∉ s) : (insert a s).fold op b f = f a * s.fold op b f :=
by unfold fold; rw [insert_val, ndinsert_of_not_mem h, map_cons, fold_cons_left]
@[simp] theorem fold_singleton : (singleton a).fold op b f = f a * b := rfl
@[simp] theorem fold_image [decidable_eq α] {g : γ → α} {s : finset γ}
(H : ∀ (x ∈ s) (y ∈ s), g x = g y → x = y) : (s.image g).fold op b f = s.fold op b (f ∘ g) :=
by simp only [fold, image_val_of_inj_on H, multiset.map_map]
@[congr] theorem fold_congr {g : α → β} (H : ∀ x ∈ s, f x = g x) : s.fold op b f = s.fold op b g :=
by rw [fold, fold, map_congr H]
theorem fold_op_distrib {f g : α → β} {b₁ b₂ : β} :
s.fold op (b₁ * b₂) (λx, f x * g x) = s.fold op b₁ f * s.fold op b₂ g :=
by simp only [fold, fold_distrib]
theorem fold_hom {op' : γ → γ → γ} [is_commutative γ op'] [is_associative γ op']
{m : β → γ} (hm : ∀x y, m (op x y) = op' (m x) (m y)) :
s.fold op' (m b) (λx, m (f x)) = m (s.fold op b f) :=
by rw [fold, fold, ← fold_hom op hm, multiset.map_map]
theorem fold_union_inter [decidable_eq α] {s₁ s₂ : finset α} {b₁ b₂ : β} :
(s₁ ∪ s₂).fold op b₁ f * (s₁ ∩ s₂).fold op b₂ f = s₁.fold op b₂ f * s₂.fold op b₁ f :=
by unfold fold; rw [← fold_add op, ← map_add, union_val,
inter_val, union_add_inter, map_add, hc.comm, fold_add]
@[simp] theorem fold_insert_idem [decidable_eq α] [hi : is_idempotent β op] :
(insert a s).fold op b f = f a * s.fold op b f :=
by haveI := classical.prop_decidable;
rw [fold, insert_val', ← fold_erase_dup_idem op, erase_dup_map_erase_dup_eq,
fold_erase_dup_idem op]; simp only [map_cons, fold_cons_left, fold]
end fold
section sup
variables [semilattice_sup_bot α]
/-- Supremum of a finite set: `sup {a, b, c} f = f a ⊔ f b ⊔ f c` -/
def sup (s : finset β) (f : β → α) : α := s.fold (⊔) ⊥ f
variables {s s₁ s₂ : finset β} {f : β → α}
lemma sup_val : s.sup f = (s.1.map f).sup := rfl
@[simp] lemma sup_empty : (∅ : finset β).sup f = ⊥ :=
fold_empty
@[simp] lemma sup_insert [decidable_eq β] {b : β} : (insert b s : finset β).sup f = f b ⊔ s.sup f :=
fold_insert_idem
@[simp] lemma sup_singleton [decidable_eq β] {b : β} : ({b} : finset β).sup f = f b :=
calc _ = f b ⊔ (∅:finset β).sup f : sup_insert
... = f b : sup_bot_eq
lemma sup_union [decidable_eq β] : (s₁ ∪ s₂).sup f = s₁.sup f ⊔ s₂.sup f :=
finset.induction_on s₁ (by rw [empty_union, sup_empty, bot_sup_eq]) $ λ a s has ih,
by rw [insert_union, sup_insert, sup_insert, ih, sup_assoc]
lemma sup_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.sup f ≤ s.sup g :=
by letI := classical.dec_eq β; from
finset.induction_on s (λ _, le_refl _) (λ a s has ih H,
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H;
simp only [sup_insert]; exact sup_le_sup H.1 (ih H.2))
lemma le_sup {b : β} (hb : b ∈ s) : f b ≤ s.sup f :=
by letI := classical.dec_eq β; from
calc f b ≤ f b ⊔ s.sup f : le_sup_left
... = (insert b s).sup f : sup_insert.symm
... = s.sup f : by rw [insert_eq_of_mem hb]
lemma sup_le {a : α} : (∀b ∈ s, f b ≤ a) → s.sup f ≤ a :=
by letI := classical.dec_eq β; from
finset.induction_on s (λ _, bot_le) (λ n s hns ih H,
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H;
simp only [sup_insert]; exact sup_le H.1 (ih H.2))
lemma sup_le_iff {a : α} : s.sup f ≤ a ↔ (∀b ∈ s, f b ≤ a) :=
iff.intro (assume h b hb, le_trans (le_sup hb) h) sup_le
lemma sup_mono (h : s₁ ⊆ s₂) : s₁.sup f ≤ s₂.sup f :=
sup_le $ assume b hb, le_sup (h hb)
end sup
lemma sup_eq_supr [complete_lattice β] (s : finset α) (f : α → β) : s.sup f = (⨆a∈s, f a) :=
le_antisymm
(finset.sup_le $ assume a ha, le_supr_of_le a $ le_supr _ ha)
(supr_le $ assume a, supr_le $ assume ha, le_sup ha)
section inf
variables [semilattice_inf_top α]
/-- Infimum of a finite set: `inf {a, b, c} f = f a ⊓ f b ⊓ f c` -/
def inf (s : finset β) (f : β → α) : α := s.fold (⊓) ⊤ f
variables {s s₁ s₂ : finset β} {f : β → α}
lemma inf_val : s.inf f = (s.1.map f).inf := rfl
@[simp] lemma inf_empty : (∅ : finset β).inf f = ⊤ :=
fold_empty
@[simp] lemma inf_insert [decidable_eq β] {b : β} : (insert b s : finset β).inf f = f b ⊓ s.inf f :=
fold_insert_idem
@[simp] lemma inf_singleton [decidable_eq β] {b : β} : ({b} : finset β).inf f = f b :=
calc _ = f b ⊓ (∅:finset β).inf f : inf_insert
... = f b : inf_top_eq
lemma inf_union [decidable_eq β] : (s₁ ∪ s₂).inf f = s₁.inf f ⊓ s₂.inf f :=
finset.induction_on s₁ (by rw [empty_union, inf_empty, top_inf_eq]) $ λ a s has ih,
by rw [insert_union, inf_insert, inf_insert, ih, inf_assoc]
lemma inf_mono_fun {g : β → α} : (∀b∈s, f b ≤ g b) → s.inf f ≤ s.inf g :=
by letI := classical.dec_eq β; from
finset.induction_on s (λ _, le_refl _) (λ a s has ih H,
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H;
simp only [inf_insert]; exact inf_le_inf H.1 (ih H.2))
lemma inf_le {b : β} (hb : b ∈ s) : s.inf f ≤ f b :=
by letI := classical.dec_eq β; from
calc f b ≥ f b ⊓ s.inf f : inf_le_left
... = (insert b s).inf f : inf_insert.symm
... = s.inf f : by rw [insert_eq_of_mem hb]
lemma le_inf {a : α} : (∀b ∈ s, a ≤ f b) → a ≤ s.inf f :=
by letI := classical.dec_eq β; from
finset.induction_on s (λ _, le_top) (λ n s hns ih H,
by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] at H;
simp only [inf_insert]; exact le_inf H.1 (ih H.2))
lemma le_inf_iff {a : α} : a ≤ s.inf f ↔ (∀b ∈ s, a ≤ f b) :=
iff.intro (assume h b hb, le_trans h (inf_le hb)) le_inf
lemma inf_mono (h : s₁ ⊆ s₂) : s₂.inf f ≤ s₁.inf f :=
le_inf $ assume b hb, inf_le (h hb)
end inf
lemma inf_eq_infi [complete_lattice β] (s : finset α) (f : α → β) : s.inf f = (⨅a∈s, f a) :=
le_antisymm
(le_infi $ assume a, le_infi $ assume ha, inf_le ha)
(finset.le_inf $ assume a ha, infi_le_of_le a $ infi_le _ ha)
/- max and min of finite sets -/
section max_min
variables [decidable_linear_order α]
protected def max : finset α → option α :=
fold (option.lift_or_get max) none some
theorem max_eq_sup_with_bot (s : finset α) :
s.max = @sup (with_bot α) α _ s some := rfl
@[simp] theorem max_empty : (∅ : finset α).max = none := rfl
@[simp] theorem max_insert {a : α} {s : finset α} :
(insert a s).max = option.lift_or_get max (some a) s.max := fold_insert_idem
@[simp] theorem max_singleton {a : α} : finset.max {a} = some a := max_insert
@[simp] theorem max_singleton' {a : α} : finset.max (singleton a) = some a := max_singleton
theorem max_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.max :=
(@le_sup (with_bot α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst
theorem max_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.max :=
let ⟨a, ha⟩ := exists_mem_of_ne_empty h in max_of_mem ha
theorem max_eq_none {s : finset α} : s.max = none ↔ s = ∅ :=
⟨λ h, by_contradiction $
λ hs, let ⟨a, ha⟩ := max_of_ne_empty hs in by rw [h] at ha; cases ha,
λ h, h.symm ▸ max_empty⟩
theorem mem_of_max {s : finset α} : ∀ {a : α}, a ∈ s.max → a ∈ s :=
finset.induction_on s (λ _ H, by cases H)
(λ b s _ (ih : ∀ {a}, a ∈ s.max → a ∈ s) a (h : a ∈ (insert b s).max),
begin
by_cases p : b = a,
{ induction p, exact mem_insert_self b s },
{ cases option.lift_or_get_choice max_choice (some b) s.max with q q;
rw [max_insert, q] at h,
{ cases h, cases p rfl },
{ exact mem_insert_of_mem (ih h) } }
end)
theorem le_max_of_mem {s : finset α} {a b : α} (h₁ : a ∈ s) (h₂ : b ∈ s.max) : a ≤ b :=
by rcases @le_sup (with_bot α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩;
cases h₂.symm.trans hb; assumption
protected def min : finset α → option α :=
fold (option.lift_or_get min) none some
theorem min_eq_inf_with_top (s : finset α) :
s.min = @inf (with_top α) α _ s some := rfl
@[simp] theorem min_empty : (∅ : finset α).min = none := rfl
@[simp] theorem min_insert {a : α} {s : finset α} :
(insert a s).min = option.lift_or_get min (some a) s.min :=
fold_insert_idem
@[simp] theorem min_singleton {a : α} : finset.min {a} = some a := min_insert
theorem min_of_mem {s : finset α} {a : α} (h : a ∈ s) : ∃ b, b ∈ s.min :=
(@inf_le (with_top α) _ _ _ _ _ h _ rfl).imp $ λ b, Exists.fst
theorem min_of_ne_empty {s : finset α} (h : s ≠ ∅) : ∃ a, a ∈ s.min :=
let ⟨a, ha⟩ := exists_mem_of_ne_empty h in min_of_mem ha
theorem min_eq_none {s : finset α} : s.min = none ↔ s = ∅ :=
⟨λ h, by_contradiction $
λ hs, let ⟨a, ha⟩ := min_of_ne_empty hs in by rw [h] at ha; cases ha,
λ h, h.symm ▸ min_empty⟩
theorem mem_of_min {s : finset α} : ∀ {a : α}, a ∈ s.min → a ∈ s :=
finset.induction_on s (λ _ H, by cases H) $
λ b s _ (ih : ∀ {a}, a ∈ s.min → a ∈ s) a (h : a ∈ (insert b s).min),
begin
by_cases p : b = a,
{ induction p, exact mem_insert_self b s },
{ cases option.lift_or_get_choice min_choice (some b) s.min with q q;
rw [min_insert, q] at h,
{ cases h, cases p rfl },
{ exact mem_insert_of_mem (ih h) } }
end
theorem le_min_of_mem {s : finset α} {a b : α} (h₁ : b ∈ s) (h₂ : a ∈ s.min) : a ≤ b :=
by rcases @inf_le (with_top α) _ _ _ _ _ h₁ _ rfl with ⟨b', hb, ab⟩;
cases h₂.symm.trans hb; assumption
end max_min
section sort
variables (r : α → α → Prop) [decidable_rel r]
[is_trans α r] [is_antisymm α r] [is_total α r]
/-- `sort s` constructs a sorted list from the unordered set `s`.
(Uses merge sort algorithm.) -/
def sort (s : finset α) : list α := sort r s.1
@[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) :=
sort_sorted _ _
@[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 :=
sort_eq _ _
@[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup :=
(by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s))
@[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s :=
list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s)
@[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s :=
multiset.mem_sort _
end sort
section disjoint
variable [decidable_eq α]
theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t :=
by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl
theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 :=
disjoint_left
theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ :=
disjoint_iff
theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s :=
by rw [disjoint.comm, disjoint_left]
theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b :=
by simp only [disjoint_left, imp_not_comm, forall_eq']
theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t :=
disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁))
theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t :=
disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁))
@[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left
@[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right
@[simp] theorem singleton_disjoint {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s :=
by simp only [disjoint_left, mem_singleton, forall_eq]
@[simp] theorem disjoint_singleton {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s :=
disjoint.comm.trans singleton_disjoint
@[simp] theorem disjoint_insert_left {a : α} {s t : finset α} :
disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t :=
by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq]
@[simp] theorem disjoint_insert_right {a : α} {s t : finset α} :
disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t :=
disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm]
@[simp] theorem disjoint_union_left {s t u : finset α} :
disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u :=
by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right {s t u : finset α} :
disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u :=
by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib]
@[simp] theorem card_disjoint_union {s t : finset α} :
disjoint s t → card (s ∪ t) = card s + card t :=
finset.induction_on s (λ _, by simp only [empty_union, card_empty, zero_add]) $ λ a s ha ih H,
have h1 : a ∉ s ∪ t, from λ h, or.elim (mem_union.1 h) ha (disjoint_insert_left.1 H).1,
by rw [insert_union, card_insert_of_not_mem h1, card_insert_of_not_mem ha, ih (disjoint_insert_left.1 H).2, add_right_comm]
end disjoint
theorem sort_sorted_lt [decidable_linear_order α] (s : finset α) :
list.sorted (<) (sort (≤) s) :=
(sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _)
instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩
def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) :=
⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.mk.inj) s.2⟩
@[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} :
a ∈ s.attach_fin h ↔ a.1 ∈ s :=
⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁,
λ h, multiset.mem_pmap.2 ⟨a.1, h, fin.eta _ _⟩⟩
@[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) :
(s.attach_fin h).card = s.card := multiset.card_pmap _ _ _
theorem lt_wf {α} [decidable_eq α] : well_founded (@has_lt.lt (finset α) _) :=
have H : subrelation (@has_lt.lt (finset α) _)
(inv_image (<) card),
from λ x y hxy, card_lt_card hxy,
subrelation.wf H $ inv_image.wf _ $ nat.lt_wf
section decidable_linear_order
variables {α} [decidable_linear_order α]
def min' (S : finset α) (H : S ≠ ∅) : α :=
@option.get _ S.min $
let ⟨k, hk⟩ := exists_mem_of_ne_empty H in
let ⟨b, hb⟩ := min_of_mem hk in by simp at hb; simp [hb]
def max' (S : finset α) (H : S ≠ ∅) : α :=
@option.get _ S.max $
let ⟨k, hk⟩ := exists_mem_of_ne_empty H in
let ⟨b, hb⟩ := max_of_mem hk in by simp at hb; simp [hb]
variables (S : finset α) (H : S ≠ ∅)
theorem min'_mem : S.min' H ∈ S := mem_of_min $ by simp [min']
theorem min'_le (x) (H2 : x ∈ S) : S.min' H ≤ x := le_min_of_mem H2 $ option.get_mem _
theorem le_min' (x) (H2 : ∀ y ∈ S, x ≤ y) : x ≤ S.min' H := H2 _ $ min'_mem _ _
theorem max'_mem : S.max' H ∈ S := mem_of_max $ by simp [max']
theorem le_max' (x) (H2 : x ∈ S) : x ≤ S.max' H := le_max_of_mem H2 $ option.get_mem _
theorem max'_le (x) (H2 : ∀ y ∈ S, y ≤ x) : S.max' H ≤ x := H2 _ $ max'_mem _ _
theorem min'_lt_max' {i j} (H1 : i ∈ S) (H2 : j ∈ S) (H3 : i ≠ j) : S.min' H < S.max' H :=
begin
rcases lt_trichotomy i j with H4 | H4 | H4,
{ have H5 := min'_le S H i H1,
have H6 := le_max' S H j H2,
apply lt_of_le_of_lt H5,
apply lt_of_lt_of_le H4 H6 },
{ cc },
{ have H5 := min'_le S H j H2,
have H6 := le_max' S H i H1,
apply lt_of_le_of_lt H5,
apply lt_of_lt_of_le H4 H6 }
end
end decidable_linear_order
end finset
namespace list
variable [decidable_eq α]
theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length :=
congr_arg card $ (@multiset.erase_dup_eq_self α _ l).2 h
end list
|
4b3dfaf445f6439dbf0a3f04ddef47943f589bd4 | 64874bd1010548c7f5a6e3e8902efa63baaff785 | /hott/init/tactic.hlean | 27be9158842bde7385343ac6c819cb4adc640590 | [
"Apache-2.0"
] | permissive | tjiaqi/lean | 4634d729795c164664d10d093f3545287c76628f | d0ce4cf62f4246b0600c07e074d86e51f2195e30 | refs/heads/master | 1,622,323,796,480 | 1,422,643,069,000 | 1,422,643,069,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,676 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
This is just a trick to embed the 'tactic language' as a Lean
expression. We should view 'tactic' as automation that when execute
produces a term. tactic.builtin is just a "dummy" for creating the
definitions that are actually implemented in C++
-/
prelude
import init.datatypes init.reserved_notation
inductive tactic :
Type := builtin : tactic
namespace tactic
-- Remark the following names are not arbitrary, the tactic module
-- uses them when converting Lean expressions into actual tactic objects.
-- The bultin 'by' construct triggers the process of converting a
-- a term of type 'tactic' into a tactic that sythesizes a term
opaque definition and_then (t1 t2 : tactic) : tactic := builtin
opaque definition or_else (t1 t2 : tactic) : tactic := builtin
opaque definition append (t1 t2 : tactic) : tactic := builtin
opaque definition interleave (t1 t2 : tactic) : tactic := builtin
opaque definition par (t1 t2 : tactic) : tactic := builtin
opaque definition fixpoint (f : tactic → tactic) : tactic := builtin
opaque definition repeat (t : tactic) : tactic := builtin
opaque definition at_most (t : tactic) (k : num) : tactic := builtin
opaque definition discard (t : tactic) (k : num) : tactic := builtin
opaque definition focus_at (t : tactic) (i : num) : tactic := builtin
opaque definition try_for (t : tactic) (ms : num) : tactic := builtin
opaque definition now : tactic := builtin
opaque definition assumption : tactic := builtin
opaque definition eassumption : tactic := builtin
opaque definition state : tactic := builtin
opaque definition fail : tactic := builtin
opaque definition id : tactic := builtin
opaque definition beta : tactic := builtin
opaque definition info : tactic := builtin
opaque definition whnf : tactic := builtin
opaque definition rotate_left (k : num) := builtin
opaque definition rotate_right (k : num) := builtin
definition rotate (k : num) := rotate_left k
-- This is just a trick to embed expressions into tactics.
-- The nested expressions are "raw". They tactic should
-- elaborate them when it is executed.
inductive expr : Type :=
builtin : expr
opaque definition apply (e : expr) : tactic := builtin
opaque definition rapply (e : expr) : tactic := builtin
opaque definition fapply (e : expr) : tactic := builtin
opaque definition rename (a b : expr) : tactic := builtin
opaque definition intro (e : expr) : tactic := builtin
opaque definition generalize (e : expr) : tactic := builtin
opaque definition clear (e : expr) : tactic := builtin
opaque definition revert (e : expr) : tactic := builtin
opaque definition unfold (e : expr) : tactic := builtin
opaque definition exact (e : expr) : tactic := builtin
opaque definition trace (s : string) : tactic := builtin
opaque definition inversion (id : expr) : tactic := builtin
notation a `↦` b:max := rename a b
inductive expr_list : Type :=
nil : expr_list,
cons : expr → expr_list → expr_list
opaque definition inversion_with (id : expr) (ids : expr_list) : tactic := builtin
notation `cases` a:max := inversion a
notation `cases` a:max `with` `(` l:(foldr `,` (h t, expr_list.cons h t) expr_list.nil) `)` := inversion_with a l
opaque definition intro_lst (ids : expr_list) : tactic := builtin
notation `intros` := intro_lst expr_list.nil
notation `intros` `(` l:(foldr `,` (h t, expr_list.cons h t) expr_list.nil) `)` := intro_lst l
opaque definition generalize_lst (es : expr_list) : tactic := builtin
notation `generalizes` `(` l:(foldr `,` (h t, expr_list.cons h t) expr_list.nil) `)` := generalize_lst l
opaque definition clear_lst (ids : expr_list) : tactic := builtin
notation `clears` `(` l:(foldr `,` (h t, expr_list.cons h t) expr_list.nil) `)` := clear_lst l
opaque definition revert_lst (ids : expr_list) : tactic := builtin
notation `reverts` `(` l:(foldr `,` (h t, expr_list.cons h t) expr_list.nil) `)` := revert_lst l
opaque definition assert_hypothesis (id : expr) (e : expr) : tactic := builtin
notation `assert` `(` id `:` ty `)` := assert_hypothesis id ty
infixl `;`:15 := and_then
notation `[` h:10 `|`:10 r:(foldl:10 `|` (e r, or_else r e) h) `]` := r
definition try (t : tactic) : tactic := [t | id]
definition repeat1 (t : tactic) : tactic := t ; repeat t
definition focus (t : tactic) : tactic := focus_at t 0
definition determ (t : tactic) : tactic := at_most t 1
end tactic
|
9f697c07eab1e01c725882c33930e7a020d105bc | b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77 | /src/ring_theory/derivation.lean | 9c0b661ac975417dce2f7112c19ba7be108195c5 | [
"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 | 8,147 | lean | /-
Copyright © 2020 Nicolò Cavalleri. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Nicolò Cavalleri.
-/
import algebra.lie.basic
import ring_theory.algebra_tower
/-!
# Derivations
This file defines derivation. A derivation `D` from the `R`-algebra `A` to the `A`-module `M` is an
`R`-linear map that satisfy the Leibniz rule `D (a * b) = a * D b + D a * b`.
## Notation
The notation `⁅D1, D2⁆` is used for the commutator of two derivations.
TODO: this file is just a stub to go on with some PRs in the geometry section. It only
implements the definition of derivations in commutative algebra. This will soon change: as soon
as bimodules will be there in mathlib I will change this file to take into account the
non-commutative case. Any development on the theory of derivations is discouraged until the
definitive definition of derivation will be implemented.
-/
open algebra ring_hom
/-- `D : derivation R A M` is an `R`-linear map from `A` to `M` that satisfies the `leibniz`
equality.
TODO: update this when bimodules are defined. -/
@[protect_proj]
structure derivation (R : Type*) (A : Type*) [comm_semiring R] [comm_semiring A]
[algebra R A] (M : Type*) [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M]
[is_scalar_tower R A M]
extends A →ₗ[R] M :=
(leibniz' (a b : A) : to_fun (a * b) = a • to_fun b + b • to_fun a)
namespace derivation
section
variables {R : Type*} [comm_semiring R]
variables {A : Type*} [comm_semiring A] [algebra R A]
variables {M : Type*} [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M]
variables [is_scalar_tower R A M]
variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A)
instance : has_coe_to_fun (derivation R A M) := ⟨_, λ D, D.to_linear_map.to_fun⟩
instance has_coe_to_linear_map : has_coe (derivation R A M) (A →ₗ[R] M) :=
⟨λ D, D.to_linear_map⟩
@[simp] lemma to_fun_eq_coe : D.to_fun = ⇑D := rfl
@[simp, norm_cast]
lemma coe_fn_coe (f : derivation R A M) :
⇑(f : A →ₗ[R] M) = f := rfl
lemma coe_injective (H : ⇑D1 = D2) : D1 = D2 :=
by { cases D1, cases D2, congr', exact linear_map.coe_injective H }
@[ext] theorem ext (H : ∀ a, D1 a = D2 a) : D1 = D2 :=
coe_injective $ funext H
@[simp] lemma map_add : D (a + b) = D a + D b := is_add_hom.map_add D a b
@[simp] lemma map_zero : D 0 = 0 := is_add_monoid_hom.map_zero D
@[simp] lemma map_smul : D (r • a) = r • D a := linear_map.map_smul D r a
@[simp] lemma leibniz : D (a * b) = a • D b + b • D a := D.leibniz' _ _
@[simp] lemma map_one_eq_zero : D 1 = 0 :=
begin
have h : D 1 = D (1 * 1) := by rw mul_one,
rw [leibniz D 1 1, one_smul] at h,
exact eq_zero_of_left_cancel_add_self h,
end
@[simp] lemma map_algebra_map : D (algebra_map R A r) = 0 :=
by rw [←mul_one r, ring_hom.map_mul, map_one, ←smul_def, map_smul, map_one_eq_zero, smul_zero]
instance : has_zero (derivation R A M) :=
⟨⟨(0 : A →ₗ[R] M), λ a b, by simp only [add_zero, linear_map.zero_apply,
linear_map.to_fun_eq_coe, smul_zero]⟩⟩
instance : inhabited (derivation R A M) := ⟨0⟩
instance : add_comm_monoid (derivation R A M) :=
{ add := λ D1 D2, ⟨D1 + D2, λ a b, by { simp only [leibniz, linear_map.add_apply,
linear_map.to_fun_eq_coe, coe_fn_coe, smul_add], cc }⟩,
add_assoc := λ D E F, ext $ λ a, add_assoc _ _ _,
zero_add := λ D, ext $ λ a, zero_add _,
add_zero := λ D, ext $ λ a, add_zero _,
add_comm := λ D E, ext $ λ a, add_comm _ _,
..derivation.has_zero }
@[simp] lemma add_apply : (D1 + D2) a = D1 a + D2 a := rfl
@[priority 100]
instance derivation.Rsemimodule : semimodule R (derivation R A M) :=
{ smul := λ r D, ⟨r • D, λ a b, by simp only [linear_map.smul_apply, leibniz,
linear_map.to_fun_eq_coe, smul_algebra_smul_comm, coe_fn_coe, smul_add, add_comm],⟩,
mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _,
one_smul := λ D, ext $ λ b, one_smul _ _,
smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _,
smul_zero := λ a, ext $ λ b, smul_zero _,
add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _,
zero_smul := λ D, ext $ λ b, zero_smul _ _ }
@[simp] lemma smul_to_linear_map_coe : ↑(r • D) = (r • D : A →ₗ[R] M) := rfl
@[simp] lemma Rsmul_apply : (r • D) a = r • D a := rfl
instance : semimodule A (derivation R A M) :=
{ smul := λ a D, ⟨a • D, λ b c, by { dsimp, simp only [smul_add, leibniz, smul_comm a, add_comm] }⟩,
mul_smul := λ a1 a2 D, ext $ λ b, mul_smul _ _ _,
one_smul := λ D, ext $ λ b, one_smul A _,
smul_add := λ a D1 D2, ext $ λ b, smul_add _ _ _,
smul_zero := λ a, ext $ λ b, smul_zero _,
add_smul := λ a1 a2 D, ext $ λ b, add_smul _ _ _,
zero_smul := λ D, ext $ λ b, zero_smul A _ }
@[simp] lemma smul_apply : (a • D) b = a • D b := rfl
instance : is_scalar_tower R A (derivation R A M) :=
⟨λ x y z, ext (λ a, smul_assoc _ _ _)⟩
end
section
variables {R : Type*} [comm_ring R]
variables {A : Type*} [comm_ring A] [algebra R A]
section
variables {M : Type*} [add_comm_group M] [module A M] [module R M] [is_scalar_tower R A M]
variables (D : derivation R A M) {D1 D2 : derivation R A M} (r : R) (a b : A)
@[simp] lemma map_neg : D (-a) = -D a := linear_map.map_neg D a
@[simp] lemma map_sub : D (a - b) = D a - D b := linear_map.map_sub D a b
instance : add_comm_group (derivation R A M) :=
{ neg := λ D, ⟨-D, λ a b, by simp only [linear_map.neg_apply, smul_neg, neg_add_rev, leibniz,
linear_map.to_fun_eq_coe, coe_fn_coe, add_comm]⟩,
add_left_neg := λ D, ext $ λ a, add_left_neg _,
..derivation.add_comm_monoid }
@[simp] lemma sub_apply : (D1 - D2) a = D1 a - D2 a := rfl
end
section lie_structures
/-! # Lie structures -/
variables (D : derivation R A A) {D1 D2 : derivation R A A} (r : R) (a b : A)
open ring_commutator
/-- The commutator of derivations is again a derivation. -/
def commutator (D1 D2 : derivation R A A) : derivation R A A :=
{ leibniz' := λ a b, by
{ simp only [commutator, map_add, id.smul_eq_mul, linear_map.mul_app, leibniz,
linear_map.to_fun_eq_coe, coe_fn_coe, linear_map.sub_apply], ring, },
..⁅(D1 : module.End R A), (D2 : module.End R A)⁆, }
instance : has_bracket (derivation R A A) (derivation R A A) := ⟨derivation.commutator⟩
@[simp] lemma commutator_coe_linear_map :
↑⁅D1, D2⁆ = ⁅(D1 : module.End R A), (D2 : module.End R A)⁆ := rfl
lemma commutator_apply : ⁅D1, D2⁆ a = D1 (D2 a) - D2 (D1 a) := rfl
instance : lie_ring (derivation R A A) :=
{ add_lie := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, },
lie_add := λ d e f, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, },
lie_self := λ d, by { ext a, simp only [commutator_apply, add_apply, map_add], ring, },
leibniz_lie := λ d e f,
by { ext a, simp only [commutator_apply, add_apply, sub_apply, map_sub], ring, } }
instance : lie_algebra R (derivation R A A) :=
{ lie_smul := λ r d e, by { ext a, simp only [commutator_apply, map_smul, smul_sub, Rsmul_apply]},
..derivation.Rsemimodule }
end lie_structures
end
end derivation
section comp_der
namespace linear_map
variables {R : Type*} [comm_semiring R]
variables {A : Type*} [comm_semiring A] [algebra R A]
variables {M : Type*} [add_cancel_comm_monoid M] [semimodule A M] [semimodule R M]
variables {N : Type*} [add_cancel_comm_monoid N] [semimodule A N] [semimodule R N]
variables [is_scalar_tower R A M] [is_scalar_tower R A N]
/-- The composition of a linear map and a derivation is a derivation. -/
def comp_der (f : M →ₗ[A] N) (D : derivation R A M) : derivation R A N :=
{ to_fun := λ a, f (D a),
map_add' := λ a1 a2, by rw [D.map_add, f.map_add],
map_smul' := λ r a, by rw [derivation.map_smul, map_smul_of_tower],
leibniz' := λ a b, by simp only [derivation.leibniz, linear_map.map_smul, linear_map.map_add, add_comm] }
@[simp] lemma comp_der_apply (f : M →ₗ[A] N) (D : derivation R A M) (a : A) :
f.comp_der D a = f (D a) := rfl
end linear_map
end comp_der
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.