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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4d30b980649fd68bd1cd8975cd1633c0f56efa49 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/omega/int/main.lean | 8c1e5412e8376fe83ecaa0291e9cb0c80ea7ad1f | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 6,289 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Seul Baek
-/
/-
Main procedure for linear integer arithmetic.
-/
import tactic.omega.prove_unsats
import tactic.omega.int.dnf
open tactic
namespace omega
namespace int
open_locale omega.int
run_cmd mk_simp_attr `sugar
attribute [sugar]
ne not_le not_lt
int.lt_iff_add_one_le
or_false false_or
and_true true_and
ge gt mul_add add_mul
one_mul mul_one
mul_comm sub_eq_add_neg
imp_iff_not_or
iff_iff_not_or_and_or_not
meta def desugar := `[try {simp only with sugar}]
lemma univ_close_of_unsat_clausify (m : nat) (p : preform) :
clauses.unsat (dnf (Β¬* p)) β univ_close p (Ξ» x, 0) m | h1 :=
begin
apply univ_close_of_valid,
apply valid_of_unsat_not,
apply unsat_of_clauses_unsat,
exact h1
end
/-- Given a (p : preform), return the expr of a (t : univ_close m p) -/
meta def prove_univ_close (m : nat) (p : preform) : tactic expr :=
do x β prove_unsats (dnf (Β¬*p)),
return `(univ_close_of_unsat_clausify %%`(m) %%`(p) %%x)
/-- Reification to imtermediate shadow syntax that retains exprs -/
meta def to_exprterm : expr β tactic exprterm
| `(- %%x) := --return (exprterm.exp (-1 : int) x)
( do z β eval_expr' int x,
return (exprterm.cst (-z : int)) ) <|>
( return $ exprterm.exp (-1 : int) x )
| `(%%mx * %%zx) :=
do z β eval_expr' int zx,
return (exprterm.exp z mx)
| `(%%t1x + %%t2x) :=
do t1 β to_exprterm t1x,
t2 β to_exprterm t2x,
return (exprterm.add t1 t2)
| x :=
( do z β eval_expr' int x,
return (exprterm.cst z) ) <|>
( return $ exprterm.exp 1 x )
/-- Reification to imtermediate shadow syntax that retains exprs -/
meta def to_exprform : expr β tactic exprform
| `(%%tx1 = %%tx2) :=
do t1 β to_exprterm tx1,
t2 β to_exprterm tx2,
return (exprform.eq t1 t2)
| `(%%tx1 β€ %%tx2) :=
do t1 β to_exprterm tx1,
t2 β to_exprterm tx2,
return (exprform.le t1 t2)
| `(Β¬ %%px) := do p β to_exprform px, return (exprform.not p)
| `(%%px β¨ %%qx) :=
do p β to_exprform px,
q β to_exprform qx,
return (exprform.or p q)
| `(%%px β§ %%qx) :=
do p β to_exprform px,
q β to_exprform qx,
return (exprform.and p q)
| `(_ β %%px) := to_exprform px
| x := trace "Cannot reify expr : " >> trace x >> failed
/-- List of all unreified exprs -/
meta def exprterm.exprs : exprterm β list expr
| (exprterm.cst _) := []
| (exprterm.exp _ x) := [x]
| (exprterm.add t s) := list.union t.exprs s.exprs
/-- List of all unreified exprs -/
meta def exprform.exprs : exprform β list expr
| (exprform.eq t s) := list.union t.exprs s.exprs
| (exprform.le t s) := list.union t.exprs s.exprs
| (exprform.not p) := p.exprs
| (exprform.or p q) := list.union p.exprs q.exprs
| (exprform.and p q) := list.union p.exprs q.exprs
/-- Reification to an intermediate shadow syntax which eliminates exprs,
but still includes non-canonical terms -/
meta def exprterm.to_preterm (xs : list expr) : exprterm β tactic preterm
| (exprterm.cst k) := return & k
| (exprterm.exp k x) :=
let m := xs.index_of x in
if m < xs.length
then return (k ** m)
else failed
| (exprterm.add xa xb) :=
do a β xa.to_preterm,
b β xb.to_preterm,
return (a +* b)
/-- Reification to an intermediate shadow syntax which eliminates exprs,
but still includes non-canonical terms -/
meta def exprform.to_preform (xs : list expr) : exprform β tactic preform
| (exprform.eq xa xb) :=
do a β xa.to_preterm xs,
b β xb.to_preterm xs,
return (a =* b)
| (exprform.le xa xb) :=
do a β xa.to_preterm xs,
b β xb.to_preterm xs,
return (a β€* b)
| (exprform.not xp) :=
do p β xp.to_preform,
return Β¬* p
| (exprform.or xp xq) :=
do p β xp.to_preform,
q β xq.to_preform,
return (p β¨* q)
| (exprform.and xp xq) :=
do p β xp.to_preform,
q β xq.to_preform,
return (p β§* q)
/-- Reification to an intermediate shadow syntax which eliminates exprs,
but still includes non-canonical terms. -/
meta def to_preform (x : expr) : tactic (preform Γ nat) :=
do xf β to_exprform x,
let xs := xf.exprs,
f β xf.to_preform xs,
return (f, xs.length)
/-- Return expr of proof of current LIA goal -/
meta def prove : tactic expr :=
do (p,m) β target >>= to_preform,
trace_if_enabled `omega p,
prove_univ_close m p
/-- Succeed iff argument is the expr of β€ -/
meta def eq_int (x : expr) : tactic unit :=
if x = `(int) then skip else failed
/-- Check whether argument is expr of a well-formed formula of LIA-/
meta def wff : expr β tactic unit
| `(Β¬ %%px) := wff px
| `(%%px β¨ %%qx) := wff px >> wff qx
| `(%%px β§ %%qx) := wff px >> wff qx
| `(%%px β %%qx) := wff px >> wff qx
| `(%%(expr.pi _ _ px qx)) :=
monad.cond
(if expr.has_var px then return tt else is_prop px)
(wff px >> wff qx)
(eq_int px >> wff qx)
| `(@has_lt.lt %%dx %%h _ _) := eq_int dx
| `(@has_le.le %%dx %%h _ _) := eq_int dx
| `(@eq %%dx _ _) := eq_int dx
| `(@ge %%dx %%h _ _) := eq_int dx
| `(@gt %%dx %%h _ _) := eq_int dx
| `(@ne %%dx _ _) := eq_int dx
| `(true) := skip
| `(false) := skip
| _ := failed
/-- Succeed iff argument is expr of term whose type is wff -/
meta def wfx (x : expr) : tactic unit :=
infer_type x >>= wff
/-- Intro all universal quantifiers over β€ -/
meta def intro_ints_core : tactic unit :=
do x β target,
match x with
| (expr.pi _ _ `(int) _) := intro_fresh >> intro_ints_core
| _ := skip
end
meta def intro_ints : tactic unit :=
do (expr.pi _ _ `(int) _) β target,
intro_ints_core
/-- If the goal has universal quantifiers over integers, introduce all of them.
Otherwise, revert all hypotheses that are formulas of linear integer arithmetic. -/
meta def preprocess : tactic unit :=
intro_ints <|> (revert_cond_all wfx >> desugar)
end int
end omega
open omega.int
/-- The core omega tactic for integers. -/
meta def omega_int (is_manual : bool) : tactic unit :=
desugar ; (if is_manual then skip else preprocess) ; prove >>= apply >> skip
|
31dc8778aa490d03ca79120eeec2568a890e5b4f | 859855170b866e395d328ebb28c4e060aa5559e8 | /src/solutions/06_sub_sequences.lean | 3931d8aed1666e63d3980efc8764b79ae973e4ac | [
"Apache-2.0"
] | permissive | bradheintz/tutorials | 1be40c9e97a484441f268ea8504c3d74534162cf | 02f15b400478de7278f4baa08935befd0f3986ef | refs/heads/master | 1,688,028,802,367 | 1,627,863,284,000 | 1,627,863,284,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,803 | lean | import tuto_lib
/-
This file continues the elementary study of limits of sequences.
It can be skipped if the previous file was too easy, it won't introduce
any new tactic or trick.
Remember useful lemmas:
abs_le (x y : β) : |x| β€ y β -y β€ x β§ x β€ y
abs_add (x y : β) : |x + y| β€ |x| + |y|
abs_sub_comm (x y : β) : |x - y| = |y - x|
ge_max_iff (p q r) : r β₯ max p q β r β₯ p β§ r β₯ q
le_max_left p q : p β€ max p q
le_max_right p q : q β€ max p q
and the definition:
def seq_limit (u : β β β) (l : β) : Prop :=
β Ξ΅ > 0, β N, β n β₯ N, |u n - l| β€ Ξ΅
You can also use a property proved in the previous file:
unique_limit : seq_limit u l β seq_limit u l' β l = l'
def extraction (Ο : β β β) := β n m, n < m β Ο n < Ο m
-/
variable { Ο : β β β}
/-
The next lemma is proved by an easy induction, but we haven't seen induction
in this tutorial. If you did the natural number game then you can delete
the proof below and try to reconstruct it.
-/
/-- An extraction is greater than id -/
lemma id_le_extraction' : extraction Ο β β n, n β€ Ο n :=
begin
intros hyp n,
induction n with n hn,
{ exact nat.zero_le _ },
{ exact nat.succ_le_of_lt (by linarith [hyp n (n+1) (by linarith)]) },
end
/-- Extractions take arbitrarily large values for arbitrarily large
inputs. -/
-- 0039
lemma extraction_ge : extraction Ο β β N N', β n β₯ N', Ο n β₯ N :=
begin
-- sorry
intros h N N',
use max N N',
split,
apply le_max_right,
calc
N β€ max N N' : by apply le_max_left
... β€ Ο (max N N') : by apply id_le_extraction' h
-- sorry
end
/-- A real number `a` is a cluster point of a sequence `u`
if `u` has a subsequence converging to `a`.
def cluster_point (u : β β β) (a : β) :=
β Ο, extraction Ο β§ seq_limit (u β Ο) a
-/
variables {u : β β β} {a l : β}
/-
In the exercise, we use `β n β₯ N, ...` which is the abbreviation of
`β n, n β₯ N β§ ...`.
Lean can read this abbreviation, but displays it as the confusing:
`β (n : β) (H : n β₯ N)`
One gets used to it. Alternatively, one can get rid of it using the lemma
exists_prop {p q : Prop} : (β (h : p), q) β p β§ q
-/
/-- If `a` is a cluster point of `u` then there are values of
`u` arbitrarily close to `a` for arbitrarily large input. -/
-- 0040
lemma near_cluster :
cluster_point u a β β Ξ΅ > 0, β N, β n β₯ N, |u n - a| β€ Ξ΅ :=
begin
-- sorry
intros hyp Ξ΅ Ξ΅_pos N,
rcases hyp with β¨Ο, Ο_extr, hΟβ©,
cases hΟ Ξ΅ Ξ΅_pos with N' hN',
rcases extraction_ge Ο_extr N N' with β¨q, hq, hq'β©,
exact β¨Ο q, hq', hN' _ hqβ©,
-- sorry
end
/-
The above exercice can be done in five lines.
Hint: you can use the anonymous constructor syntax when proving
existential statements.
-/
/-- If `u` tends to `l` then its subsequences tend to `l`. -/
-- 0041
lemma subseq_tendsto_of_tendsto' (h : seq_limit u l) (hΟ : extraction Ο) :
seq_limit (u β Ο) l :=
begin
-- sorry
intros Ξ΅ Ξ΅_pos,
cases h Ξ΅ Ξ΅_pos with N hN,
use N,
intros n hn,
apply hN,
calc N β€ n : hn
... β€ Ο n : id_le_extraction' hΟ n,
-- sorry
end
/-- If `u` tends to `l` all its cluster points are equal to `l`. -/
-- 0042
lemma cluster_limit (hl : seq_limit u l) (ha : cluster_point u a) : a = l :=
begin
-- sorry
rcases ha with β¨Ο, Ο_extr, lim_u_Οβ©,
have lim_u_Ο' : seq_limit (u β Ο) l,
from subseq_tendsto_of_tendsto' hl Ο_extr,
exact unique_limit lim_u_Ο lim_u_Ο',
-- sorry
end
/-- Cauchy_sequence sequence -/
def cauchy_sequence (u : β β β) := β Ξ΅ > 0, β N, β p q, p β₯ N β q β₯ N β |u p - u q| β€ Ξ΅
-- 0043
example : (β l, seq_limit u l) β cauchy_sequence u :=
begin
-- sorry
intro hyp,
cases hyp with l hl,
intros Ξ΅ Ξ΅_pos,
cases hl (Ξ΅/2) (by linarith) with N hN,
use N,
intros p q hp hq,
calc |u p - u q| = |(u p - l) + (l - u q)| : by ring_nf
... β€ |u p - l| + |l - u q| : by apply abs_add
... = |u p - l| + |u q - l| : by rw abs_sub_comm (u q) l
... β€ Ξ΅ : by linarith [hN p hp, hN q hq],
-- sorry
end
/-
In the next exercise, you can reuse
near_cluster : cluster_point u a β β Ξ΅ > 0, β N, β n β₯ N, |u n - a| β€ Ξ΅
-/
-- 0044
example (hu : cauchy_sequence u) (hl : cluster_point u l) : seq_limit u l :=
begin
-- sorry
intros Ξ΅ Ξ΅_pos,
cases hu (Ξ΅/2) (by linarith) with N hN,
use N,
have clef : β N' β₯ N, |u N' - l| β€ Ξ΅/2,
apply near_cluster hl (Ξ΅/2) (by linarith),
cases clef with N' h,
cases h with hNN' hN',
intros n hn,
calc |u n - l| = |(u n - u N') + (u N' - l)| : by ring
... β€ |u n - u N'| + |u N' - l| : by apply abs_add
... β€ Ξ΅ : by linarith [hN n N' (by linarith) hNN'],
-- sorry
end
|
418d600b991a54af361680ecf3556322b71ecc99 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/tactic/nth_rewrite/congr.lean | 81b48cc3508fe8d7c32821566d30ffb7790cacb2 | [] | 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 | 651 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Keeley Hoek, Scott Morrison
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.tactic.nth_rewrite.basic
import Mathlib.tactic.core
import Mathlib.data.mllist
import Mathlib.PostPort
namespace Mathlib
namespace tactic
namespace nth_rewrite.congr
/-- Helper function which just tries to rewrite `e` using the equality `r` without assigning any
metavariables in the tactic state, and without creating any metavariables which cannot be
discharged by `cfg.discharger` in the process. -/
|
02be97905b6f45a78c6f5ff841bcf48b376a9531 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/set_theory/game/pgame.lean | b6a9580b9cbb2ea047de298450d579c576ca1849 | [
"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 | 59,543 | lean | /-
Copyright (c) 2019 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Mario Carneiro, Isabel Longbottom, Scott Morrison
-/
import data.fin.basic
import data.list.basic
import logic.relation
import logic.small.basic
import order.game_add
/-!
# Combinatorial (pre-)games.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
The basic theory of combinatorial games, following Conway's book `On Numbers and Games`. We
construct "pregames", define an ordering and arithmetic operations on them, then show that the
operations descend to "games", defined via the equivalence relation `p β q β p β€ q β§ q β€ p`.
The surreal numbers will be built as a quotient of a subtype of pregames.
A pregame (`pgame` below) is axiomatised via an inductive type, whose sole constructor takes two
types (thought of as indexing the possible moves for the players Left and Right), and a pair of
functions out of these types to `pgame` (thought of as describing the resulting game after making a
move).
Combinatorial games themselves, as a quotient of pregames, are constructed in `game.lean`.
## Conway induction
By construction, the induction principle for pregames is exactly "Conway induction". That is, to
prove some predicate `pgame β Prop` holds for all pregames, it suffices to prove that for every
pregame `g`, if the predicate holds for every game resulting from making a move, then it also holds
for `g`.
While it is often convenient to work "by induction" on pregames, in some situations this becomes
awkward, so we also define accessor functions `pgame.left_moves`, `pgame.right_moves`,
`pgame.move_left` and `pgame.move_right`. There is a relation `pgame.subsequent p q`, saying that
`p` can be reached by playing some non-empty sequence of moves starting from `q`, an instance
`well_founded subsequent`, and a local tactic `pgame_wf_tac` which is helpful for discharging proof
obligations in inductive proofs relying on this relation.
## Order properties
Pregames have both a `β€` and a `<` relation, satisfying the usual properties of a `preorder`. The
relation `0 < x` means that `x` can always be won by Left, while `0 β€ x` means that `x` can be won
by Left as the second player.
It turns out to be quite convenient to define various relations on top of these. We define the "less
or fuzzy" relation `x β§ y` as `Β¬ y β€ x`, the equivalence relation `x β y` as `x β€ y β§ y β€ x`, and
the fuzzy relation `x β y` as `x β§ y β§ y β§ x`. If `0 β§ x`, then `x` can be won by Left as the
first player. If `x β 0`, then `x` can be won by the second player. If `x β 0`, then `x` can be won
by the first player.
Statements like `zero_le_lf`, `zero_lf_le`, etc. unfold these definitions. The theorems `le_def` and
`lf_def` give a recursive characterisation of each relation in terms of themselves two moves later.
The theorems `zero_le`, `zero_lf`, etc. also take into account that `0` has no moves.
Later, games will be defined as the quotient by the `β` relation; that is to say, the
`antisymmetrization` of `pgame`.
## Algebraic structures
We next turn to defining the operations necessary to make games into a commutative additive group.
Addition is defined for $x = \{xL | xR\}$ and $y = \{yL | yR\}$ by $x + y = \{xL + y, x + yL | xR +
y, x + yR\}$. Negation is defined by $\{xL | xR\} = \{-xR | -xL\}$.
The order structures interact in the expected way with addition, so we have
```
theorem le_iff_sub_nonneg {x y : pgame} : x β€ y β 0 β€ y - x := sorry
theorem lt_iff_sub_pos {x y : pgame} : x < y β 0 < y - x := sorry
```
We show that these operations respect the equivalence relation, and hence descend to games. At the
level of games, these operations satisfy all the laws of a commutative group. To prove the necessary
equivalence relations at the level of pregames, we introduce the notion of a `relabelling` of a
game, and show, for example, that there is a relabelling between `x + (y + z)` and `(x + y) + z`.
## Future work
* The theory of dominated and reversible positions, and unique normal form for short games.
* Analysis of basic domineering positions.
* Hex.
* Temperature.
* The development of surreal numbers, based on this development of combinatorial games, is still
quite incomplete.
## References
The material here is all drawn from
* [Conway, *On numbers and games*][conway2001]
An interested reader may like to formalise some of the material from
* [Andreas Blass, *A game semantics for linear logic*][MR1167694]
* [AndrΓ© Joyal, *Remarques sur la thΓ©orie des jeux Γ deux personnes*][joyal1997]
-/
open function relation
universes u
/-! ### Pre-game moves -/
/-- The type of pre-games, before we have quotiented
by equivalence (`pgame.setoid`). In ZFC, a combinatorial game is constructed from
two sets of combinatorial games that have been constructed at an earlier
stage. To do this in type theory, we say that a pre-game is built
inductively from two families of pre-games indexed over any type
in Type u. The resulting type `pgame.{u}` lives in `Type (u+1)`,
reflecting that it is a proper class in ZFC. -/
inductive pgame : Type (u+1)
| mk : β Ξ± Ξ² : Type u, (Ξ± β pgame) β (Ξ² β pgame) β pgame
namespace pgame
/-- The indexing type for allowable moves by Left. -/
def left_moves : pgame β Type u
| (mk l _ _ _) := l
/-- The indexing type for allowable moves by Right. -/
def right_moves : pgame β Type u
| (mk _ r _ _) := r
/-- The new game after Left makes an allowed move. -/
def move_left : Ξ (g : pgame), left_moves g β pgame
| (mk l _ L _) := L
/-- The new game after Right makes an allowed move. -/
def move_right : Ξ (g : pgame), right_moves g β pgame
| (mk _ r _ R) := R
@[simp] lemma left_moves_mk {xl xr xL xR} : (β¨xl, xr, xL, xRβ© : pgame).left_moves = xl := rfl
@[simp] lemma move_left_mk {xl xr xL xR} : (β¨xl, xr, xL, xRβ© : pgame).move_left = xL := rfl
@[simp] lemma right_moves_mk {xl xr xL xR} : (β¨xl, xr, xL, xRβ© : pgame).right_moves = xr := rfl
@[simp] lemma move_right_mk {xl xr xL xR} : (β¨xl, xr, xL, xRβ© : pgame).move_right = xR := rfl
/--
Construct a pre-game from list of pre-games describing the available moves for Left and Right.
-/
-- TODO define this at the level of games, as well, and perhaps also for finsets of games.
def of_lists (L R : list pgame.{u}) : pgame.{u} :=
mk (ulift (fin L.length)) (ulift (fin R.length))
(Ξ» i, L.nth_le i.down i.down.is_lt) (Ξ» j, R.nth_le j.down j.down.prop)
lemma left_moves_of_lists (L R : list pgame) : (of_lists L R).left_moves = ulift (fin L.length) :=
rfl
lemma right_moves_of_lists (L R : list pgame) : (of_lists L R).right_moves = ulift (fin R.length) :=
rfl
/-- Converts a number into a left move for `of_lists`. -/
def to_of_lists_left_moves {L R : list pgame} : fin L.length β (of_lists L R).left_moves :=
((equiv.cast (left_moves_of_lists L R).symm).trans equiv.ulift).symm
/-- Converts a number into a right move for `of_lists`. -/
def to_of_lists_right_moves {L R : list pgame} : fin R.length β (of_lists L R).right_moves :=
((equiv.cast (right_moves_of_lists L R).symm).trans equiv.ulift).symm
theorem of_lists_move_left {L R : list pgame} (i : fin L.length) :
(of_lists L R).move_left (to_of_lists_left_moves i) = L.nth_le i i.is_lt :=
rfl
@[simp] theorem of_lists_move_left' {L R : list pgame} (i : (of_lists L R).left_moves) :
(of_lists L R).move_left i =
L.nth_le (to_of_lists_left_moves.symm i) (to_of_lists_left_moves.symm i).is_lt :=
rfl
theorem of_lists_move_right {L R : list pgame} (i : fin R.length) :
(of_lists L R).move_right (to_of_lists_right_moves i) = R.nth_le i i.is_lt :=
rfl
@[simp] theorem of_lists_move_right' {L R : list pgame} (i : (of_lists L R).right_moves) :
(of_lists L R).move_right i =
R.nth_le (to_of_lists_right_moves.symm i) (to_of_lists_right_moves.symm i).is_lt :=
rfl
/-- A variant of `pgame.rec_on` expressed in terms of `pgame.move_left` and `pgame.move_right`.
Both this and `pgame.rec_on` describe Conway induction on games. -/
@[elab_as_eliminator] def move_rec_on {C : pgame β Sort*} (x : pgame)
(IH : β (y : pgame), (β i, C (y.move_left i)) β (β j, C (y.move_right j)) β C y) : C x :=
x.rec_on $ Ξ» yl yr yL yR, IH (mk yl yr yL yR)
/-- `is_option x y` means that `x` is either a left or right option for `y`. -/
@[mk_iff] inductive is_option : pgame β pgame β Prop
| move_left {x : pgame} (i : x.left_moves) : is_option (x.move_left i) x
| move_right {x : pgame} (i : x.right_moves) : is_option (x.move_right i) x
theorem is_option.mk_left {xl xr : Type u} (xL : xl β pgame) (xR : xr β pgame) (i : xl) :
(xL i).is_option (mk xl xr xL xR) :=
@is_option.move_left (mk _ _ _ _) i
theorem is_option.mk_right {xl xr : Type u} (xL : xl β pgame) (xR : xr β pgame) (i : xr) :
(xR i).is_option (mk xl xr xL xR) :=
@is_option.move_right (mk _ _ _ _) i
theorem wf_is_option : well_founded is_option :=
β¨Ξ» x, move_rec_on x $ Ξ» x IHl IHr, acc.intro x $ Ξ» y h, begin
induction h with _ i _ j,
{ exact IHl i },
{ exact IHr j }
endβ©
/-- `subsequent x y` says that `x` can be obtained by playing some nonempty sequence of moves from
`y`. It is the transitive closure of `is_option`. -/
def subsequent : pgame β pgame β Prop :=
trans_gen is_option
instance : is_trans _ subsequent := trans_gen.is_trans
@[trans] theorem subsequent.trans {x y z} : subsequent x y β subsequent y z β subsequent x z :=
trans_gen.trans
theorem wf_subsequent : well_founded subsequent := wf_is_option.trans_gen
instance : has_well_founded pgame := β¨_, wf_subsequentβ©
lemma subsequent.move_left {x : pgame} (i : x.left_moves) : subsequent (x.move_left i) x :=
trans_gen.single (is_option.move_left i)
lemma subsequent.move_right {x : pgame} (j : x.right_moves) : subsequent (x.move_right j) x :=
trans_gen.single (is_option.move_right j)
lemma subsequent.mk_left {xl xr} (xL : xl β pgame) (xR : xr β pgame) (i : xl) :
subsequent (xL i) (mk xl xr xL xR) :=
@subsequent.move_left (mk _ _ _ _) i
lemma subsequent.mk_right {xl xr} (xL : xl β pgame) (xR : xr β pgame) (j : xr) :
subsequent (xR j) (mk xl xr xL xR) :=
@subsequent.move_right (mk _ _ _ _) j
/-- A local tactic for proving well-foundedness of recursive definitions involving pregames. -/
meta def pgame_wf_tac :=
`[solve_by_elim
[psigma.lex.left, psigma.lex.right, subsequent.move_left, subsequent.move_right,
subsequent.mk_left, subsequent.mk_right, subsequent.trans]
{ max_depth := 6 }]
/-! ### Basic pre-games -/
/-- The pre-game `zero` is defined by `0 = { | }`. -/
instance : has_zero pgame := β¨β¨pempty, pempty, pempty.elim, pempty.elimβ©β©
@[simp] lemma zero_left_moves : left_moves 0 = pempty := rfl
@[simp] lemma zero_right_moves : right_moves 0 = pempty := rfl
instance is_empty_zero_left_moves : is_empty (left_moves 0) := pempty.is_empty
instance is_empty_zero_right_moves : is_empty (right_moves 0) := pempty.is_empty
instance : inhabited pgame := β¨0β©
/-- The pre-game `one` is defined by `1 = { 0 | }`. -/
instance : has_one pgame := β¨β¨punit, pempty, Ξ» _, 0, pempty.elimβ©β©
@[simp] lemma one_left_moves : left_moves 1 = punit := rfl
@[simp] lemma one_move_left (x) : move_left 1 x = 0 := rfl
@[simp] lemma one_right_moves : right_moves 1 = pempty := rfl
instance unique_one_left_moves : unique (left_moves 1) := punit.unique
instance is_empty_one_right_moves : is_empty (right_moves 1) := pempty.is_empty
/-! ### Pre-game order relations -/
/-- The less or equal relation on pre-games.
If `0 β€ x`, then Left can win `x` as the second player. -/
instance : has_le pgame :=
β¨sym2.game_add.fix wf_is_option $ Ξ» x y le,
(β i, Β¬ le y (x.move_left i) (sym2.game_add.snd_fst $ is_option.move_left i)) β§
(β j, Β¬ le (y.move_right j) x (sym2.game_add.fst_snd $ is_option.move_right j))β©
/-- The less or fuzzy relation on pre-games.
If `0 β§ x`, then Left can win `x` as the first player. -/
def lf (x y : pgame) : Prop := Β¬ y β€ x
localized "infix (name := pgame.lf) ` β§ `:50 := pgame.lf" in pgame
@[simp] protected theorem not_le {x y : pgame} : Β¬ x β€ y β y β§ x := iff.rfl
@[simp] theorem not_lf {x y : pgame} : Β¬ x β§ y β y β€ x := not_not
theorem _root_.has_le.le.not_gf {x y : pgame} : x β€ y β Β¬ y β§ x := not_lf.2
theorem lf.not_ge {x y : pgame} : x β§ y β Β¬ y β€ x := id
/-- Definition of `x β€ y` on pre-games, in terms of `β§`.
The ordering here is chosen so that `and.left` refer to moves by Left, and `and.right` refer to
moves by Right. -/
theorem le_iff_forall_lf {x y : pgame} :
x β€ y β (β i, x.move_left i β§ y) β§ β j, x β§ y.move_right j :=
by { unfold has_le.le, rw sym2.game_add.fix_eq, refl }
/-- Definition of `x β€ y` on pre-games built using the constructor. -/
@[simp] theorem mk_le_mk {xl xr xL xR yl yr yL yR} :
mk xl xr xL xR β€ mk yl yr yL yR β
(β i, xL i β§ mk yl yr yL yR) β§ β j, mk xl xr xL xR β§ yR j :=
le_iff_forall_lf
theorem le_of_forall_lf {x y : pgame} (hβ : β i, x.move_left i β§ y) (hβ : β j, x β§ y.move_right j) :
x β€ y :=
le_iff_forall_lf.2 β¨hβ, hββ©
/-- Definition of `x β§ y` on pre-games, in terms of `β€`.
The ordering here is chosen so that `or.inl` refer to moves by Left, and `or.inr` refer to
moves by Right. -/
theorem lf_iff_exists_le {x y : pgame} :
x β§ y β (β i, x β€ y.move_left i) β¨ β j, x.move_right j β€ y :=
by { rw [lf, le_iff_forall_lf, not_and_distrib], simp }
/-- Definition of `x β§ y` on pre-games built using the constructor. -/
@[simp] theorem mk_lf_mk {xl xr xL xR yl yr yL yR} :
mk xl xr xL xR β§ mk yl yr yL yR β
(β i, mk xl xr xL xR β€ yL i) β¨ β j, xR j β€ mk yl yr yL yR :=
lf_iff_exists_le
theorem le_or_gf (x y : pgame) : x β€ y β¨ y β§ x :=
by { rw βpgame.not_le, apply em }
theorem move_left_lf_of_le {x y : pgame} (h : x β€ y) (i) : x.move_left i β§ y :=
(le_iff_forall_lf.1 h).1 i
alias move_left_lf_of_le β _root_.has_le.le.move_left_lf
theorem lf_move_right_of_le {x y : pgame} (h : x β€ y) (j) : x β§ y.move_right j :=
(le_iff_forall_lf.1 h).2 j
alias lf_move_right_of_le β _root_.has_le.le.lf_move_right
theorem lf_of_move_right_le {x y : pgame} {j} (h : x.move_right j β€ y) : x β§ y :=
lf_iff_exists_le.2 $ or.inr β¨j, hβ©
theorem lf_of_le_move_left {x y : pgame} {i} (h : x β€ y.move_left i) : x β§ y :=
lf_iff_exists_le.2 $ or.inl β¨i, hβ©
theorem lf_of_le_mk {xl xr xL xR y} : mk xl xr xL xR β€ y β β i, xL i β§ y :=
move_left_lf_of_le
theorem lf_of_mk_le {x yl yr yL yR} : x β€ mk yl yr yL yR β β j, x β§ yR j :=
lf_move_right_of_le
theorem mk_lf_of_le {xl xr y j} (xL) {xR : xr β pgame} : xR j β€ y β mk xl xr xL xR β§ y :=
@lf_of_move_right_le (mk _ _ _ _) y j
theorem lf_mk_of_le {x yl yr} {yL : yl β pgame} (yR) {i} : x β€ yL i β x β§ mk yl yr yL yR :=
@lf_of_le_move_left x (mk _ _ _ _) i
/- We prove that `x β€ y β y β€ z β x β€ z` inductively, by also simultaneously proving its cyclic
reorderings. This auxiliary lemma is used during said induction. -/
private theorem le_trans_aux {x y z : pgame}
(hβ : β {i}, y β€ z β z β€ x.move_left i β y β€ x.move_left i)
(hβ : β {j}, z.move_right j β€ x β x β€ y β z.move_right j β€ y)
(hxy : x β€ y) (hyz : y β€ z) : x β€ z :=
le_of_forall_lf
(Ξ» i, pgame.not_le.1 $ Ξ» h, (hβ hyz h).not_gf $ hxy.move_left_lf i)
(Ξ» j, pgame.not_le.1 $ Ξ» h, (hβ h hxy).not_gf $ hyz.lf_move_right j)
instance : preorder pgame :=
{ le_refl := Ξ» x, begin
induction x with _ _ _ _ IHl IHr,
exact le_of_forall_lf (Ξ» i, lf_of_le_move_left (IHl i)) (Ξ» i, lf_of_move_right_le (IHr i))
end,
le_trans := begin
suffices : β {x y z : pgame},
(x β€ y β y β€ z β x β€ z) β§ (y β€ z β z β€ x β y β€ x) β§ (z β€ x β x β€ y β z β€ y),
from Ξ» x y z, this.1,
intros x y z,
induction x with xl xr xL xR IHxl IHxr generalizing y z,
induction y with yl yr yL yR IHyl IHyr generalizing z,
induction z with zl zr zL zR IHzl IHzr,
exact β¨le_trans_aux (Ξ» i, (IHxl i).2.1) (Ξ» j, (IHzr j).2.2),
le_trans_aux (Ξ» i, (IHyl i).2.2) (Ξ» j, (IHxr j).1),
le_trans_aux (Ξ» i, (IHzl i).1) (Ξ» j, (IHyr j).2.1)β©
end,
lt := Ξ» x y, x β€ y β§ x β§ y,
..pgame.has_le, }
theorem lt_iff_le_and_lf {x y : pgame} : x < y β x β€ y β§ x β§ y := iff.rfl
theorem lt_of_le_of_lf {x y : pgame} (hβ : x β€ y) (hβ : x β§ y) : x < y := β¨hβ, hββ©
theorem lf_of_lt {x y : pgame} (h : x < y) : x β§ y := h.2
alias lf_of_lt β _root_.has_lt.lt.lf
theorem lf_irrefl (x : pgame) : Β¬ x β§ x := le_rfl.not_gf
instance : is_irrefl _ (β§) := β¨lf_irreflβ©
@[trans] theorem lf_of_le_of_lf {x y z : pgame} (hβ : x β€ y) (hβ : y β§ z) : x β§ z :=
by { rw βpgame.not_le at hβ β’, exact Ξ» hβ, hβ (hβ.trans hβ) }
@[trans] theorem lf_of_lf_of_le {x y z : pgame} (hβ : x β§ y) (hβ : y β€ z) : x β§ z :=
by { rw βpgame.not_le at hβ β’, exact Ξ» hβ, hβ (hβ.trans hβ) }
alias lf_of_le_of_lf β _root_.has_le.le.trans_lf
alias lf_of_lf_of_le β lf.trans_le
@[trans] theorem lf_of_lt_of_lf {x y z : pgame} (hβ : x < y) (hβ : y β§ z) : x β§ z :=
hβ.le.trans_lf hβ
@[trans] theorem lf_of_lf_of_lt {x y z : pgame} (hβ : x β§ y) (hβ : y < z) : x β§ z :=
hβ.trans_le hβ.le
alias lf_of_lt_of_lf β _root_.has_lt.lt.trans_lf
alias lf_of_lf_of_lt β lf.trans_lt
theorem move_left_lf {x : pgame} : β i, x.move_left i β§ x :=
le_rfl.move_left_lf
theorem lf_move_right {x : pgame} : β j, x β§ x.move_right j :=
le_rfl.lf_move_right
theorem lf_mk {xl xr} (xL : xl β pgame) (xR : xr β pgame) (i) : xL i β§ mk xl xr xL xR :=
@move_left_lf (mk _ _ _ _) i
theorem mk_lf {xl xr} (xL : xl β pgame) (xR : xr β pgame) (j) : mk xl xr xL xR β§ xR j :=
@lf_move_right (mk _ _ _ _) j
/-- This special case of `pgame.le_of_forall_lf` is useful when dealing with surreals, where `<` is
preferred over `β§`. -/
theorem le_of_forall_lt {x y : pgame} (hβ : β i, x.move_left i < y) (hβ : β j, x < y.move_right j) :
x β€ y :=
le_of_forall_lf (Ξ» i, (hβ i).lf) (Ξ» i, (hβ i).lf)
/-- The definition of `x β€ y` on pre-games, in terms of `β€` two moves later. -/
theorem le_def {x y : pgame} : x β€ y β
(β i, (β i', x.move_left i β€ y.move_left i') β¨ β j, (x.move_left i).move_right j β€ y) β§
β j, (β i, x β€ (y.move_right j).move_left i) β¨ β j', x.move_right j' β€ y.move_right j :=
by { rw le_iff_forall_lf, conv { to_lhs, simp only [lf_iff_exists_le] } }
/-- The definition of `x β§ y` on pre-games, in terms of `β§` two moves later. -/
theorem lf_def {x y : pgame} : x β§ y β
(β i, (β i', x.move_left i' β§ y.move_left i) β§ β j, x β§ (y.move_left i).move_right j) β¨
β j, (β i, (x.move_right j).move_left i β§ y) β§ β j', x.move_right j β§ y.move_right j' :=
by { rw lf_iff_exists_le, conv { to_lhs, simp only [le_iff_forall_lf] } }
/-- The definition of `0 β€ x` on pre-games, in terms of `0 β§`. -/
theorem zero_le_lf {x : pgame} : 0 β€ x β β j, 0 β§ x.move_right j :=
by { rw le_iff_forall_lf, simp }
/-- The definition of `x β€ 0` on pre-games, in terms of `β§ 0`. -/
theorem le_zero_lf {x : pgame} : x β€ 0 β β i, x.move_left i β§ 0 :=
by { rw le_iff_forall_lf, simp }
/-- The definition of `0 β§ x` on pre-games, in terms of `0 β€`. -/
theorem zero_lf_le {x : pgame} : 0 β§ x β β i, 0 β€ x.move_left i :=
by { rw lf_iff_exists_le, simp }
/-- The definition of `x β§ 0` on pre-games, in terms of `β€ 0`. -/
theorem lf_zero_le {x : pgame} : x β§ 0 β β j, x.move_right j β€ 0 :=
by { rw lf_iff_exists_le, simp }
/-- The definition of `0 β€ x` on pre-games, in terms of `0 β€` two moves later. -/
theorem zero_le {x : pgame} : 0 β€ x β β j, β i, 0 β€ (x.move_right j).move_left i :=
by { rw le_def, simp }
/-- The definition of `x β€ 0` on pre-games, in terms of `β€ 0` two moves later. -/
theorem le_zero {x : pgame} : x β€ 0 β β i, β j, (x.move_left i).move_right j β€ 0 :=
by { rw le_def, simp }
/-- The definition of `0 β§ x` on pre-games, in terms of `0 β§` two moves later. -/
theorem zero_lf {x : pgame} : 0 β§ x β β i, β j, 0 β§ (x.move_left i).move_right j :=
by { rw lf_def, simp }
/-- The definition of `x β§ 0` on pre-games, in terms of `β§ 0` two moves later. -/
theorem lf_zero {x : pgame} : x β§ 0 β β j, β i, (x.move_right j).move_left i β§ 0 :=
by { rw lf_def, simp }
@[simp] theorem zero_le_of_is_empty_right_moves (x : pgame) [is_empty x.right_moves] : 0 β€ x :=
zero_le.2 is_empty_elim
@[simp] theorem le_zero_of_is_empty_left_moves (x : pgame) [is_empty x.left_moves] : x β€ 0 :=
le_zero.2 is_empty_elim
/-- Given a game won by the right player when they play second, provide a response to any move by
left. -/
noncomputable def right_response {x : pgame} (h : x β€ 0) (i : x.left_moves) :
(x.move_left i).right_moves :=
classical.some $ (le_zero.1 h) i
/-- Show that the response for right provided by `right_response` preserves the right-player-wins
condition. -/
lemma right_response_spec {x : pgame} (h : x β€ 0) (i : x.left_moves) :
(x.move_left i).move_right (right_response h i) β€ 0 :=
classical.some_spec $ (le_zero.1 h) i
/-- Given a game won by the left player when they play second, provide a response to any move by
right. -/
noncomputable def left_response {x : pgame} (h : 0 β€ x) (j : x.right_moves) :
(x.move_right j).left_moves :=
classical.some $ (zero_le.1 h) j
/-- Show that the response for left provided by `left_response` preserves the left-player-wins
condition. -/
lemma left_response_spec {x : pgame} (h : 0 β€ x) (j : x.right_moves) :
0 β€ (x.move_right j).move_left (left_response h j) :=
classical.some_spec $ (zero_le.1 h) j
/-- An explicit upper bound for a family of pre-games, whose left moves are the union of the left
moves of all the pre-games in the family. -/
def upper_bound {ΞΉ : Type u} (f : ΞΉ β pgame.{u}) : pgame :=
β¨Ξ£ i, (f i).left_moves, pempty, Ξ» x, move_left _ x.2, pempty.elimβ©
instance upper_bound_right_moves_empty {ΞΉ : Type u} (f : ΞΉ β pgame.{u}) :
is_empty (upper_bound f).right_moves :=
pempty.is_empty
theorem le_upper_bound {ΞΉ : Type u} (f : ΞΉ β pgame.{u}) (i : ΞΉ) : f i β€ upper_bound f :=
begin
rw [upper_bound, le_iff_forall_lf],
dsimp,
simp only [and_true, is_empty.forall_iff],
exact Ξ» j, @move_left_lf (upper_bound f) β¨i, jβ©
end
lemma upper_bound_mem_upper_bounds (s : set pgame.{u}) [small.{u} s] :
upper_bound (subtype.val β (equiv_shrink s).symm) β upper_bounds s :=
Ξ» i hi, by simpa using
le_upper_bound (subtype.val β (equiv_shrink s).symm) (equiv_shrink s β¨i, hiβ©)
/-- A small set `s` of pre-games is bounded above. -/
lemma bdd_above_of_small (s : set pgame.{u}) [small.{u} s] : bdd_above s :=
β¨_, upper_bound_mem_upper_bounds sβ©
/-- An explicit lower bound for a family of pre-games, whose right moves are the union of the right
moves of all the pre-games in the family. -/
def lower_bound {ΞΉ : Type u} (f : ΞΉ β pgame.{u}) : pgame :=
β¨pempty, Ξ£ i, (f i).right_moves, pempty.elim, Ξ» x, move_right _ x.2β©
instance lower_bound_left_moves_empty {ΞΉ : Type u} (f : ΞΉ β pgame.{u}) :
is_empty (lower_bound f).left_moves :=
pempty.is_empty
theorem lower_bound_le {ΞΉ : Type u} (f : ΞΉ β pgame.{u}) (i : ΞΉ) : lower_bound f β€ f i :=
begin
rw [lower_bound, le_iff_forall_lf],
dsimp,
simp only [is_empty.forall_iff, true_and],
exact Ξ» j, @lf_move_right (lower_bound f) β¨i, jβ©
end
lemma lower_bound_mem_lower_bounds (s : set pgame.{u}) [small.{u} s] :
lower_bound (subtype.val β (equiv_shrink s).symm) β lower_bounds s :=
Ξ» i hi, by simpa using
lower_bound_le (subtype.val β (equiv_shrink s).symm) (equiv_shrink s β¨i, hiβ©)
/-- A small set `s` of pre-games is bounded below. -/
lemma bdd_below_of_small (s : set pgame.{u}) [small.{u} s] : bdd_below s :=
β¨_, lower_bound_mem_lower_bounds sβ©
/-- The equivalence relation on pre-games. Two pre-games `x`, `y` are equivalent if `x β€ y` and
`y β€ x`.
If `x β 0`, then the second player can always win `x`. -/
def equiv (x y : pgame) : Prop := x β€ y β§ y β€ x
localized "infix (name := pgame.equiv) ` β ` := pgame.equiv" in pgame
instance : is_equiv _ (β) :=
{ refl := Ξ» x, β¨le_rfl, le_rflβ©,
trans := Ξ» x y z β¨xy, yxβ© β¨yz, zyβ©, β¨xy.trans yz, zy.trans yxβ©,
symm := Ξ» x y, and.symm }
theorem equiv.le {x y : pgame} (h : x β y) : x β€ y := h.1
theorem equiv.ge {x y : pgame} (h : x β y) : y β€ x := h.2
@[refl, simp] theorem equiv_rfl {x} : x β x := refl x
theorem equiv_refl (x) : x β x := refl x
@[symm] protected theorem equiv.symm {x y} : x β y β y β x := symm
@[trans] protected theorem equiv.trans {x y z} : x β y β y β z β x β z := trans
protected theorem equiv_comm {x y} : x β y β y β x := comm
theorem equiv_of_eq {x y} (h : x = y) : x β y := by subst h
@[trans] theorem le_of_le_of_equiv {x y z} (hβ : x β€ y) (hβ : y β z) : x β€ z := hβ.trans hβ.1
@[trans] theorem le_of_equiv_of_le {x y z} (hβ : x β y) : y β€ z β x β€ z := hβ.1.trans
theorem lf.not_equiv {x y} (h : x β§ y) : Β¬ x β y := Ξ» h', h.not_ge h'.2
theorem lf.not_equiv' {x y} (h : x β§ y) : Β¬ y β x := Ξ» h', h.not_ge h'.1
theorem lf.not_gt {x y} (h : x β§ y) : Β¬ y < x := Ξ» h', h.not_ge h'.le
theorem le_congr_imp {xβ yβ xβ yβ} (hx : xβ β xβ) (hy : yβ β yβ) (h : xβ β€ yβ) : xβ β€ yβ :=
hx.2.trans (h.trans hy.1)
theorem le_congr {xβ yβ xβ yβ} (hx : xβ β xβ) (hy : yβ β yβ) : xβ β€ yβ β xβ β€ yβ :=
β¨le_congr_imp hx hy, le_congr_imp hx.symm hy.symmβ©
theorem le_congr_left {xβ xβ y} (hx : xβ β xβ) : xβ β€ y β xβ β€ y :=
le_congr hx equiv_rfl
theorem le_congr_right {x yβ yβ} (hy : yβ β yβ) : x β€ yβ β x β€ yβ :=
le_congr equiv_rfl hy
theorem lf_congr {xβ yβ xβ yβ} (hx : xβ β xβ) (hy : yβ β yβ) : xβ β§ yβ β xβ β§ yβ :=
pgame.not_le.symm.trans $ (not_congr (le_congr hy hx)).trans pgame.not_le
theorem lf_congr_imp {xβ yβ xβ yβ} (hx : xβ β xβ) (hy : yβ β yβ) : xβ β§ yβ β xβ β§ yβ :=
(lf_congr hx hy).1
theorem lf_congr_left {xβ xβ y} (hx : xβ β xβ) : xβ β§ y β xβ β§ y :=
lf_congr hx equiv_rfl
theorem lf_congr_right {x yβ yβ} (hy : yβ β yβ) : x β§ yβ β x β§ yβ :=
lf_congr equiv_rfl hy
@[trans] theorem lf_of_lf_of_equiv {x y z} (hβ : x β§ y) (hβ : y β z) : x β§ z :=
lf_congr_imp equiv_rfl hβ hβ
@[trans] theorem lf_of_equiv_of_lf {x y z} (hβ : x β y) : y β§ z β x β§ z :=
lf_congr_imp hβ.symm equiv_rfl
@[trans] theorem lt_of_lt_of_equiv {x y z} (hβ : x < y) (hβ : y β z) : x < z := hβ.trans_le hβ.1
@[trans] theorem lt_of_equiv_of_lt {x y z} (hβ : x β y) : y < z β x < z := hβ.1.trans_lt
theorem lt_congr_imp {xβ yβ xβ yβ} (hx : xβ β xβ) (hy : yβ β yβ) (h : xβ < yβ) : xβ < yβ :=
hx.2.trans_lt (h.trans_le hy.1)
theorem lt_congr {xβ yβ xβ yβ} (hx : xβ β xβ) (hy : yβ β yβ) : xβ < yβ β xβ < yβ :=
β¨lt_congr_imp hx hy, lt_congr_imp hx.symm hy.symmβ©
theorem lt_congr_left {xβ xβ y} (hx : xβ β xβ) : xβ < y β xβ < y :=
lt_congr hx equiv_rfl
theorem lt_congr_right {x yβ yβ} (hy : yβ β yβ) : x < yβ β x < yβ :=
lt_congr equiv_rfl hy
theorem lt_or_equiv_of_le {x y : pgame} (h : x β€ y) : x < y β¨ x β y :=
and_or_distrib_left.mp β¨h, (em $ y β€ x).swap.imp_left pgame.not_le.1β©
theorem lf_or_equiv_or_gf (x y : pgame) : x β§ y β¨ x β y β¨ y β§ x :=
begin
by_cases h : x β§ y,
{ exact or.inl h },
{ right,
cases (lt_or_equiv_of_le (pgame.not_lf.1 h)) with h' h',
{ exact or.inr h'.lf },
{ exact or.inl h'.symm } }
end
theorem equiv_congr_left {yβ yβ} : yβ β yβ β β xβ, xβ β yβ β xβ β yβ :=
β¨Ξ» h xβ, β¨Ξ» h', h'.trans h, Ξ» h', h'.trans h.symmβ©,
Ξ» h, (h yβ).1 $ equiv_rflβ©
theorem equiv_congr_right {xβ xβ} : xβ β xβ β β yβ, xβ β yβ β xβ β yβ :=
β¨Ξ» h yβ, β¨Ξ» h', h.symm.trans h', Ξ» h', h.trans h'β©,
Ξ» h, (h xβ).2 $ equiv_rflβ©
theorem equiv_of_mk_equiv {x y : pgame}
(L : x.left_moves β y.left_moves) (R : x.right_moves β y.right_moves)
(hl : β i, x.move_left i β y.move_left (L i))
(hr : β j, x.move_right j β y.move_right (R j)) : x β y :=
begin
fsplit; rw le_def,
{ exact β¨Ξ» i, or.inl β¨_, (hl i).1β©, Ξ» j, or.inr β¨_, by simpa using (hr (R.symm j)).1β©β© },
{ exact β¨Ξ» i, or.inl β¨_, by simpa using (hl (L.symm i)).2β©, Ξ» j, or.inr β¨_, (hr j).2β©β© }
end
/-- The fuzzy, confused, or incomparable relation on pre-games.
If `x β 0`, then the first player can always win `x`. -/
def fuzzy (x y : pgame) : Prop := x β§ y β§ y β§ x
localized "infix (name := pgame.fuzzy) ` β `:50 := pgame.fuzzy" in pgame
@[symm] theorem fuzzy.swap {x y : pgame} : x β y β y β x := and.swap
instance : is_symm _ (β) := β¨Ξ» x y, fuzzy.swapβ©
theorem fuzzy.swap_iff {x y : pgame} : x β y β y β x := β¨fuzzy.swap, fuzzy.swapβ©
theorem fuzzy_irrefl (x : pgame) : Β¬ x β x := Ξ» h, lf_irrefl x h.1
instance : is_irrefl _ (β) := β¨fuzzy_irreflβ©
theorem lf_iff_lt_or_fuzzy {x y : pgame} : x β§ y β x < y β¨ x β y :=
by { simp only [lt_iff_le_and_lf, fuzzy, βpgame.not_le], tauto! }
theorem lf_of_fuzzy {x y : pgame} (h : x β y) : x β§ y := lf_iff_lt_or_fuzzy.2 (or.inr h)
alias lf_of_fuzzy β fuzzy.lf
theorem lt_or_fuzzy_of_lf {x y : pgame} : x β§ y β x < y β¨ x β y :=
lf_iff_lt_or_fuzzy.1
theorem fuzzy.not_equiv {x y : pgame} (h : x β y) : Β¬ x β y :=
Ξ» h', h'.1.not_gf h.2
theorem fuzzy.not_equiv' {x y : pgame} (h : x β y) : Β¬ y β x :=
Ξ» h', h'.2.not_gf h.2
theorem not_fuzzy_of_le {x y : pgame} (h : x β€ y) : Β¬ x β y :=
Ξ» h', h'.2.not_ge h
theorem not_fuzzy_of_ge {x y : pgame} (h : y β€ x) : Β¬ x β y :=
Ξ» h', h'.1.not_ge h
theorem equiv.not_fuzzy {x y : pgame} (h : x β y) : Β¬ x β y :=
not_fuzzy_of_le h.1
theorem equiv.not_fuzzy' {x y : pgame} (h : x β y) : Β¬ y β x :=
not_fuzzy_of_le h.2
theorem fuzzy_congr {xβ yβ xβ yβ : pgame} (hx : xβ β xβ) (hy : yβ β yβ) : xβ β yβ β xβ β yβ :=
show _ β§ _ β _ β§ _, by rw [lf_congr hx hy, lf_congr hy hx]
theorem fuzzy_congr_imp {xβ yβ xβ yβ : pgame} (hx : xβ β xβ) (hy : yβ β yβ) : xβ β yβ β xβ β yβ :=
(fuzzy_congr hx hy).1
theorem fuzzy_congr_left {xβ xβ y} (hx : xβ β xβ) : xβ β y β xβ β y :=
fuzzy_congr hx equiv_rfl
theorem fuzzy_congr_right {x yβ yβ} (hy : yβ β yβ) : x β yβ β x β yβ :=
fuzzy_congr equiv_rfl hy
@[trans] theorem fuzzy_of_fuzzy_of_equiv {x y z} (hβ : x β y) (hβ : y β z) : x β z :=
(fuzzy_congr_right hβ).1 hβ
@[trans] theorem fuzzy_of_equiv_of_fuzzy {x y z} (hβ : x β y) (hβ : y β z) : x β z :=
(fuzzy_congr_left hβ).2 hβ
/-- Exactly one of the following is true (although we don't prove this here). -/
theorem lt_or_equiv_or_gt_or_fuzzy (x y : pgame) : x < y β¨ x β y β¨ y < x β¨ x β y :=
begin
cases le_or_gf x y with hβ hβ;
cases le_or_gf y x with hβ hβ,
{ right, left, exact β¨hβ, hββ© },
{ left, exact β¨hβ, hββ© },
{ right, right, left, exact β¨hβ, hββ© },
{ right, right, right, exact β¨hβ, hββ© }
end
theorem lt_or_equiv_or_gf (x y : pgame) : x < y β¨ x β y β¨ y β§ x :=
begin
rw [lf_iff_lt_or_fuzzy, fuzzy.swap_iff],
exact lt_or_equiv_or_gt_or_fuzzy x y
end
/-! ### Relabellings -/
/--
`relabelling x y` says that `x` and `y` are really the same game, just dressed up differently.
Specifically, there is a bijection between the moves for Left in `x` and in `y`, and similarly
for Right, and under these bijections we inductively have `relabelling`s for the consequent games.
-/
inductive relabelling : pgame.{u} β pgame.{u} β Type (u+1)
| mk : Ξ {x y : pgame} (L : x.left_moves β y.left_moves) (R : x.right_moves β y.right_moves),
(β i, relabelling (x.move_left i) (y.move_left (L i))) β
(β j, relabelling (x.move_right j) (y.move_right (R j))) β
relabelling x y
localized "infix (name := pgame.relabelling) ` β‘r `:50 := pgame.relabelling" in pgame
namespace relabelling
variables {x y : pgame.{u}}
/-- A constructor for relabellings swapping the equivalences. -/
def mk' (L : y.left_moves β x.left_moves) (R : y.right_moves β x.right_moves)
(hL : β i, x.move_left (L i) β‘r y.move_left i)
(hR : β j, x.move_right (R j) β‘r y.move_right j) : x β‘r y :=
β¨L.symm, R.symm, Ξ» i, by simpa using hL (L.symm i), Ξ» j, by simpa using hR (R.symm j)β©
/-- The equivalence between left moves of `x` and `y` given by the relabelling. -/
def left_moves_equiv : Ξ (r : x β‘r y), x.left_moves β y.left_moves
| β¨L, R, hL, hRβ© := L
@[simp] theorem mk_left_moves_equiv {x y L R hL hR} :
(@relabelling.mk x y L R hL hR).left_moves_equiv = L := rfl
@[simp] theorem mk'_left_moves_equiv {x y L R hL hR} :
(@relabelling.mk' x y L R hL hR).left_moves_equiv = L.symm := rfl
/-- The equivalence between right moves of `x` and `y` given by the relabelling. -/
def right_moves_equiv : Ξ (r : x β‘r y), x.right_moves β y.right_moves
| β¨L, R, hL, hRβ© := R
@[simp] theorem mk_right_moves_equiv {x y L R hL hR} :
(@relabelling.mk x y L R hL hR).right_moves_equiv = R := rfl
@[simp] theorem mk'_right_moves_equiv {x y L R hL hR} :
(@relabelling.mk' x y L R hL hR).right_moves_equiv = R.symm := rfl
/-- A left move of `x` is a relabelling of a left move of `y`. -/
def move_left : β (r : x β‘r y) (i : x.left_moves),
x.move_left i β‘r y.move_left (r.left_moves_equiv i)
| β¨L, R, hL, hRβ© := hL
/-- A left move of `y` is a relabelling of a left move of `x`. -/
def move_left_symm : β (r : x β‘r y) (i : y.left_moves),
x.move_left (r.left_moves_equiv.symm i) β‘r y.move_left i
| β¨L, R, hL, hRβ© i := by simpa using hL (L.symm i)
/-- A right move of `x` is a relabelling of a right move of `y`. -/
def move_right : β (r : x β‘r y) (i : x.right_moves),
x.move_right i β‘r y.move_right (r.right_moves_equiv i)
| β¨L, R, hL, hRβ© := hR
/-- A right move of `y` is a relabelling of a right move of `x`. -/
def move_right_symm : β (r : x β‘r y) (i : y.right_moves),
x.move_right (r.right_moves_equiv.symm i) β‘r y.move_right i
| β¨L, R, hL, hRβ© i := by simpa using hR (R.symm i)
/-- The identity relabelling. -/
@[refl] def refl : Ξ (x : pgame), x β‘r x
| x := β¨equiv.refl _, equiv.refl _, Ξ» i, refl _, Ξ» j, refl _β©
using_well_founded { dec_tac := pgame_wf_tac }
instance (x : pgame) : inhabited (x β‘r x) := β¨refl _β©
/-- Flip a relabelling. -/
@[symm] def symm : Ξ {x y : pgame}, x β‘r y β y β‘r x
| x y β¨L, R, hL, hRβ© := mk' L R (Ξ» i, (hL i).symm) (Ξ» j, (hR j).symm)
theorem le : β {x y : pgame} (r : x β‘r y), x β€ y
| x y r := le_def.2 β¨Ξ» i, or.inl β¨_, (r.move_left i).leβ©, Ξ» j, or.inr β¨_, (r.move_right_symm j).leβ©β©
using_well_founded { dec_tac := pgame_wf_tac }
theorem ge {x y : pgame} (r : x β‘r y) : y β€ x := r.symm.le
/-- A relabelling lets us prove equivalence of games. -/
theorem equiv (r : x β‘r y) : x β y := β¨r.le, r.geβ©
/-- Transitivity of relabelling. -/
@[trans] def trans : Ξ {x y z : pgame}, x β‘r y β y β‘r z β x β‘r z
| x y z β¨Lβ, Rβ, hLβ, hRββ© β¨Lβ, Rβ, hLβ, hRββ© :=
β¨Lβ.trans Lβ, Rβ.trans Rβ, Ξ» i, (hLβ i).trans (hLβ _), Ξ» j, (hRβ j).trans (hRβ _)β©
/-- Any game without left or right moves is a relabelling of 0. -/
def is_empty (x : pgame) [is_empty x.left_moves] [is_empty x.right_moves] : x β‘r 0 :=
β¨equiv.equiv_pempty _, equiv.equiv_of_is_empty _ _, is_empty_elim, is_empty_elimβ©
end relabelling
theorem equiv.is_empty (x : pgame) [is_empty x.left_moves] [is_empty x.right_moves] : x β 0 :=
(relabelling.is_empty x).equiv
instance {x y : pgame} : has_coe (x β‘r y) (x β y) := β¨relabelling.equivβ©
/-- Replace the types indexing the next moves for Left and Right by equivalent types. -/
def relabel {x : pgame} {xl' xr'} (el : xl' β x.left_moves) (er : xr' β x.right_moves) : pgame :=
β¨xl', xr', x.move_left β el, x.move_right β erβ©
@[simp] lemma relabel_move_left' {x : pgame} {xl' xr'}
(el : xl' β x.left_moves) (er : xr' β x.right_moves) (i : xl') :
move_left (relabel el er) i = x.move_left (el i) :=
rfl
@[simp] lemma relabel_move_left {x : pgame} {xl' xr'}
(el : xl' β x.left_moves) (er : xr' β x.right_moves) (i : x.left_moves) :
move_left (relabel el er) (el.symm i) = x.move_left i :=
by simp
@[simp] lemma relabel_move_right' {x : pgame} {xl' xr'}
(el : xl' β x.left_moves) (er : xr' β x.right_moves) (j : xr') :
move_right (relabel el er) j = x.move_right (er j) :=
rfl
@[simp] lemma relabel_move_right {x : pgame} {xl' xr'}
(el : xl' β x.left_moves) (er : xr' β x.right_moves) (j : x.right_moves) :
move_right (relabel el er) (er.symm j) = x.move_right j :=
by simp
/-- The game obtained by relabelling the next moves is a relabelling of the original game. -/
def relabel_relabelling {x : pgame} {xl' xr'} (el : xl' β x.left_moves) (er : xr' β x.right_moves) :
x β‘r relabel el er :=
relabelling.mk' el er (Ξ» i, by simp) (Ξ» j, by simp)
/-! ### Negation -/
/-- The negation of `{L | R}` is `{-R | -L}`. -/
def neg : pgame β pgame
| β¨l, r, L, Rβ© := β¨r, l, Ξ» i, neg (R i), Ξ» i, neg (L i)β©
instance : has_neg pgame := β¨negβ©
@[simp] lemma neg_def {xl xr xL xR} : -(mk xl xr xL xR) = mk xr xl (Ξ» j, -(xR j)) (Ξ» i, -(xL i)) :=
rfl
instance : has_involutive_neg pgame :=
{ neg_neg := Ξ» x, begin
induction x with xl xr xL xR ihL ihR,
simp_rw [neg_def, ihL, ihR],
exact β¨rfl, rfl, heq.rfl, heq.rflβ©,
end,
..pgame.has_neg }
instance : neg_zero_class pgame :=
{ neg_zero :=
begin
dsimp [has_zero.zero, has_neg.neg, neg],
congr; funext i; cases i
end,
..pgame.has_zero,
..pgame.has_neg }
@[simp] lemma neg_of_lists (L R : list pgame) :
-of_lists L R = of_lists (R.map (Ξ» x, -x)) (L.map (Ξ» x, -x)) :=
begin
simp only [of_lists, neg_def, list.length_map, list.nth_le_map', eq_self_iff_true, true_and],
split, all_goals
{ apply hfunext,
{ simp },
{ intros a a' ha,
congr' 2,
have : β {m n} (hβ : m = n) {b : ulift (fin m)} {c : ulift (fin n)} (hβ : b == c),
(b.down : β) = βc.down,
{ rintros m n rfl b c rfl, refl },
exact this (list.length_map _ _).symm ha } }
end
theorem is_option_neg {x y : pgame} : is_option x (-y) β is_option (-x) y :=
begin
rw [is_option_iff, is_option_iff, or_comm],
cases y, apply or_congr;
{ apply exists_congr, intro, rw neg_eq_iff_eq_neg, refl },
end
@[simp] theorem is_option_neg_neg {x y : pgame} : is_option (-x) (-y) β is_option x y :=
by rw [is_option_neg, neg_neg]
theorem left_moves_neg : β x : pgame, (-x).left_moves = x.right_moves
| β¨_, _, _, _β© := rfl
theorem right_moves_neg : β x : pgame, (-x).right_moves = x.left_moves
| β¨_, _, _, _β© := rfl
/-- Turns a right move for `x` into a left move for `-x` and vice versa.
Even though these types are the same (not definitionally so), this is the preferred way to convert
between them. -/
def to_left_moves_neg {x : pgame} : x.right_moves β (-x).left_moves :=
equiv.cast (left_moves_neg x).symm
/-- Turns a left move for `x` into a right move for `-x` and vice versa.
Even though these types are the same (not definitionally so), this is the preferred way to convert
between them. -/
def to_right_moves_neg {x : pgame} : x.left_moves β (-x).right_moves :=
equiv.cast (right_moves_neg x).symm
lemma move_left_neg {x : pgame} (i) :
(-x).move_left (to_left_moves_neg i) = -x.move_right i :=
by { cases x, refl }
@[simp] lemma move_left_neg' {x : pgame} (i) :
(-x).move_left i = -x.move_right (to_left_moves_neg.symm i) :=
by { cases x, refl }
lemma move_right_neg {x : pgame} (i) :
(-x).move_right (to_right_moves_neg i) = -(x.move_left i) :=
by { cases x, refl }
@[simp] lemma move_right_neg' {x : pgame} (i) :
(-x).move_right i = -x.move_left (to_right_moves_neg.symm i) :=
by { cases x, refl }
lemma move_left_neg_symm {x : pgame} (i) :
x.move_left (to_right_moves_neg.symm i) = -(-x).move_right i :=
by simp
lemma move_left_neg_symm' {x : pgame} (i) :
x.move_left i = -(-x).move_right (to_right_moves_neg i) :=
by simp
lemma move_right_neg_symm {x : pgame} (i) :
x.move_right (to_left_moves_neg.symm i) = -(-x).move_left i :=
by simp
lemma move_right_neg_symm' {x : pgame} (i) :
x.move_right i = -(-x).move_left (to_left_moves_neg i) :=
by simp
/-- If `x` has the same moves as `y`, then `-x` has the sames moves as `-y`. -/
def relabelling.neg_congr : β {x y : pgame}, x β‘r y β -x β‘r -y
| β¨xl, xr, xL, xRβ© β¨yl, yr, yL, yRβ© β¨L, R, hL, hRβ© :=
β¨R, L, Ξ» j, (hR j).neg_congr, Ξ» i, (hL i).neg_congrβ©
private theorem neg_le_lf_neg_iff :
Ξ {x y : pgame.{u}}, (-y β€ -x β x β€ y) β§ (-y β§ -x β x β§ y)
| (mk xl xr xL xR) (mk yl yr yL yR) :=
begin
simp_rw [neg_def, mk_le_mk, mk_lf_mk, β neg_def],
split,
{ rw and_comm, apply and_congr; exact forall_congr (Ξ» _, neg_le_lf_neg_iff.2) },
{ rw or_comm, apply or_congr; exact exists_congr (Ξ» _, neg_le_lf_neg_iff.1) },
end
using_well_founded { dec_tac := pgame_wf_tac }
@[simp] theorem neg_le_neg_iff {x y : pgame} : -y β€ -x β x β€ y := neg_le_lf_neg_iff.1
@[simp] theorem neg_lf_neg_iff {x y : pgame} : -y β§ -x β x β§ y := neg_le_lf_neg_iff.2
@[simp] theorem neg_lt_neg_iff {x y : pgame} : -y < -x β x < y :=
by rw [lt_iff_le_and_lf, lt_iff_le_and_lf, neg_le_neg_iff, neg_lf_neg_iff]
@[simp] theorem neg_equiv_neg_iff {x y : pgame} : -x β -y β x β y :=
by rw [equiv, equiv, neg_le_neg_iff, neg_le_neg_iff, and.comm]
@[simp] theorem neg_fuzzy_neg_iff {x y : pgame} : -x β -y β x β y :=
by rw [fuzzy, fuzzy, neg_lf_neg_iff, neg_lf_neg_iff, and.comm]
theorem neg_le_iff {x y : pgame} : -y β€ x β -x β€ y :=
by rw [βneg_neg x, neg_le_neg_iff, neg_neg]
theorem neg_lf_iff {x y : pgame} : -y β§ x β -x β§ y :=
by rw [βneg_neg x, neg_lf_neg_iff, neg_neg]
theorem neg_lt_iff {x y : pgame} : -y < x β -x < y :=
by rw [βneg_neg x, neg_lt_neg_iff, neg_neg]
theorem neg_equiv_iff {x y : pgame} : -x β y β x β -y :=
by rw [βneg_neg y, neg_equiv_neg_iff, neg_neg]
theorem neg_fuzzy_iff {x y : pgame} : -x β y β x β -y :=
by rw [βneg_neg y, neg_fuzzy_neg_iff, neg_neg]
theorem le_neg_iff {x y : pgame} : y β€ -x β x β€ -y :=
by rw [βneg_neg x, neg_le_neg_iff, neg_neg]
theorem lf_neg_iff {x y : pgame} : y β§ -x β x β§ -y :=
by rw [βneg_neg x, neg_lf_neg_iff, neg_neg]
theorem lt_neg_iff {x y : pgame} : y < -x β x < -y :=
by rw [βneg_neg x, neg_lt_neg_iff, neg_neg]
@[simp] theorem neg_le_zero_iff {x : pgame} : -x β€ 0 β 0 β€ x :=
by rw [neg_le_iff, neg_zero]
@[simp] theorem zero_le_neg_iff {x : pgame} : 0 β€ -x β x β€ 0 :=
by rw [le_neg_iff, neg_zero]
@[simp] theorem neg_lf_zero_iff {x : pgame} : -x β§ 0 β 0 β§ x :=
by rw [neg_lf_iff, neg_zero]
@[simp] theorem zero_lf_neg_iff {x : pgame} : 0 β§ -x β x β§ 0 :=
by rw [lf_neg_iff, neg_zero]
@[simp] theorem neg_lt_zero_iff {x : pgame} : -x < 0 β 0 < x :=
by rw [neg_lt_iff, neg_zero]
@[simp] theorem zero_lt_neg_iff {x : pgame} : 0 < -x β x < 0 :=
by rw [lt_neg_iff, neg_zero]
@[simp] theorem neg_equiv_zero_iff {x : pgame} : -x β 0 β x β 0 :=
by rw [neg_equiv_iff, neg_zero]
@[simp] theorem neg_fuzzy_zero_iff {x : pgame} : -x β 0 β x β 0 :=
by rw [neg_fuzzy_iff, neg_zero]
@[simp] theorem zero_equiv_neg_iff {x : pgame} : 0 β -x β 0 β x :=
by rw [βneg_equiv_iff, neg_zero]
@[simp] theorem zero_fuzzy_neg_iff {x : pgame} : 0 β -x β 0 β x :=
by rw [βneg_fuzzy_iff, neg_zero]
/-! ### Addition and subtraction -/
/-- The sum of `x = {xL | xR}` and `y = {yL | yR}` is `{xL + y, x + yL | xR + y, x + yR}`. -/
instance : has_add pgame.{u} := β¨Ξ» x y, begin
induction x with xl xr xL xR IHxl IHxr generalizing y,
induction y with yl yr yL yR IHyl IHyr,
have y := mk yl yr yL yR,
refine β¨xl β yl, xr β yr, sum.rec _ _, sum.rec _ _β©,
{ exact Ξ» i, IHxl i y },
{ exact IHyl },
{ exact Ξ» i, IHxr i y },
{ exact IHyr }
endβ©
/-- The pre-game `((0+1)+β―)+1`. -/
instance : has_nat_cast pgame := β¨nat.unary_castβ©
@[simp] protected theorem nat_succ (n : β) : ((n + 1 : β) : pgame) = n + 1 := rfl
instance is_empty_left_moves_add (x y : pgame.{u})
[is_empty x.left_moves] [is_empty y.left_moves] : is_empty (x + y).left_moves :=
begin
unfreezingI { cases x, cases y },
apply is_empty_sum.2 β¨_, _β©,
assumption'
end
instance is_empty_right_moves_add (x y : pgame.{u})
[is_empty x.right_moves] [is_empty y.right_moves] : is_empty (x + y).right_moves :=
begin
unfreezingI { cases x, cases y },
apply is_empty_sum.2 β¨_, _β©,
assumption'
end
/-- `x + 0` has exactly the same moves as `x`. -/
def add_zero_relabelling : Ξ (x : pgame.{u}), x + 0 β‘r x
| β¨xl, xr, xL, xRβ© :=
begin
refine β¨equiv.sum_empty xl pempty, equiv.sum_empty xr pempty, _, _β©;
rintro (β¨iβ©|β¨β¨β©β©);
apply add_zero_relabelling
end
/-- `x + 0` is equivalent to `x`. -/
lemma add_zero_equiv (x : pgame.{u}) : x + 0 β x :=
(add_zero_relabelling x).equiv
/-- `0 + x` has exactly the same moves as `x`. -/
def zero_add_relabelling : Ξ (x : pgame.{u}), 0 + x β‘r x
| β¨xl, xr, xL, xRβ© :=
begin
refine β¨equiv.empty_sum pempty xl, equiv.empty_sum pempty xr, _, _β©;
rintro (β¨β¨β©β©|β¨iβ©);
apply zero_add_relabelling
end
/-- `0 + x` is equivalent to `x`. -/
lemma zero_add_equiv (x : pgame.{u}) : 0 + x β x :=
(zero_add_relabelling x).equiv
theorem left_moves_add : β (x y : pgame.{u}),
(x + y).left_moves = (x.left_moves β y.left_moves)
| β¨_, _, _, _β© β¨_, _, _, _β© := rfl
theorem right_moves_add : β (x y : pgame.{u}),
(x + y).right_moves = (x.right_moves β y.right_moves)
| β¨_, _, _, _β© β¨_, _, _, _β© := rfl
/-- Converts a left move for `x` or `y` into a left move for `x + y` and vice versa.
Even though these types are the same (not definitionally so), this is the preferred way to convert
between them. -/
def to_left_moves_add {x y : pgame} :
x.left_moves β y.left_moves β (x + y).left_moves :=
equiv.cast (left_moves_add x y).symm
/-- Converts a right move for `x` or `y` into a right move for `x + y` and vice versa.
Even though these types are the same (not definitionally so), this is the preferred way to convert
between them. -/
def to_right_moves_add {x y : pgame} :
x.right_moves β y.right_moves β (x + y).right_moves :=
equiv.cast (right_moves_add x y).symm
@[simp] lemma mk_add_move_left_inl {xl xr yl yr} {xL xR yL yR} {i} :
(mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inl i) =
(mk xl xr xL xR).move_left i + (mk yl yr yL yR) :=
rfl
@[simp] lemma add_move_left_inl {x : pgame} (y : pgame) (i) :
(x + y).move_left (to_left_moves_add (sum.inl i)) = x.move_left i + y :=
by { cases x, cases y, refl }
@[simp] lemma mk_add_move_right_inl {xl xr yl yr} {xL xR yL yR} {i} :
(mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inl i) =
(mk xl xr xL xR).move_right i + (mk yl yr yL yR) :=
rfl
@[simp] lemma add_move_right_inl {x : pgame} (y : pgame) (i) :
(x + y).move_right (to_right_moves_add (sum.inl i)) = x.move_right i + y :=
by { cases x, cases y, refl }
@[simp] lemma mk_add_move_left_inr {xl xr yl yr} {xL xR yL yR} {i} :
(mk xl xr xL xR + mk yl yr yL yR).move_left (sum.inr i) =
(mk xl xr xL xR) + (mk yl yr yL yR).move_left i :=
rfl
@[simp] lemma add_move_left_inr (x : pgame) {y : pgame} (i) :
(x + y).move_left (to_left_moves_add (sum.inr i)) = x + y.move_left i :=
by { cases x, cases y, refl }
@[simp] lemma mk_add_move_right_inr {xl xr yl yr} {xL xR yL yR} {i} :
(mk xl xr xL xR + mk yl yr yL yR).move_right (sum.inr i) =
(mk xl xr xL xR) + (mk yl yr yL yR).move_right i :=
rfl
@[simp] lemma add_move_right_inr (x : pgame) {y : pgame} (i) :
(x + y).move_right (to_right_moves_add (sum.inr i)) = x + y.move_right i :=
by { cases x, cases y, refl }
lemma left_moves_add_cases {x y : pgame} (k) {P : (x + y).left_moves β Prop}
(hl : β i, P $ to_left_moves_add (sum.inl i))
(hr : β i, P $ to_left_moves_add (sum.inr i)) : P k :=
begin
rw βto_left_moves_add.apply_symm_apply k,
cases to_left_moves_add.symm k with i i,
{ exact hl i },
{ exact hr i }
end
lemma right_moves_add_cases {x y : pgame} (k) {P : (x + y).right_moves β Prop}
(hl : β j, P $ to_right_moves_add (sum.inl j))
(hr : β j, P $ to_right_moves_add (sum.inr j)) : P k :=
begin
rw βto_right_moves_add.apply_symm_apply k,
cases to_right_moves_add.symm k with i i,
{ exact hl i },
{ exact hr i }
end
instance is_empty_nat_right_moves : β n : β, is_empty (right_moves n)
| 0 := pempty.is_empty
| (n + 1) := begin
haveI := is_empty_nat_right_moves n,
rw [pgame.nat_succ, right_moves_add],
apply_instance
end
/-- If `w` has the same moves as `x` and `y` has the same moves as `z`,
then `w + y` has the same moves as `x + z`. -/
def relabelling.add_congr : β {w x y z : pgame.{u}}, w β‘r x β y β‘r z β w + y β‘r x + z
| β¨wl, wr, wL, wRβ© β¨xl, xr, xL, xRβ© β¨yl, yr, yL, yRβ© β¨zl, zr, zL, zRβ©
β¨Lβ, Rβ, hLβ, hRββ© β¨Lβ, Rβ, hLβ, hRββ© :=
begin
let Hwx : β¨wl, wr, wL, wRβ© β‘r β¨xl, xr, xL, xRβ© := β¨Lβ, Rβ, hLβ, hRββ©,
let Hyz : β¨yl, yr, yL, yRβ© β‘r β¨zl, zr, zL, zRβ© := β¨Lβ, Rβ, hLβ, hRββ©,
refine β¨equiv.sum_congr Lβ Lβ, equiv.sum_congr Rβ Rβ, _, _β©;
rintro (i|j),
{ exact (hLβ i).add_congr Hyz },
{ exact Hwx.add_congr (hLβ j) },
{ exact (hRβ i).add_congr Hyz },
{ exact Hwx.add_congr (hRβ j) }
end
using_well_founded { dec_tac := pgame_wf_tac }
instance : has_sub pgame := β¨Ξ» x y, x + -yβ©
@[simp] theorem sub_zero (x : pgame) : x - 0 = x + 0 :=
show x + -0 = x + 0, by rw neg_zero
/-- If `w` has the same moves as `x` and `y` has the same moves as `z`,
then `w - y` has the same moves as `x - z`. -/
def relabelling.sub_congr {w x y z : pgame} (hβ : w β‘r x) (hβ : y β‘r z) : w - y β‘r x - z :=
hβ.add_congr hβ.neg_congr
/-- `-(x + y)` has exactly the same moves as `-x + -y`. -/
def neg_add_relabelling : Ξ (x y : pgame), -(x + y) β‘r -x + -y
| β¨xl, xr, xL, xRβ© β¨yl, yr, yL, yRβ© :=
begin
refine β¨equiv.refl _, equiv.refl _, _, _β©,
all_goals {
exact Ξ» j, sum.cases_on j
(Ξ» j, neg_add_relabelling _ _)
(Ξ» j, neg_add_relabelling β¨xl, xr, xL, xRβ© _) }
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem neg_add_le {x y : pgame} : -(x + y) β€ -x + -y :=
(neg_add_relabelling x y).le
/-- `x + y` has exactly the same moves as `y + x`. -/
def add_comm_relabelling : Ξ (x y : pgame.{u}), x + y β‘r y + x
| (mk xl xr xL xR) (mk yl yr yL yR) :=
begin
refine β¨equiv.sum_comm _ _, equiv.sum_comm _ _, _, _β©;
rintros (_|_);
{ dsimp [left_moves_add, right_moves_add], apply add_comm_relabelling }
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem add_comm_le {x y : pgame} : x + y β€ y + x :=
(add_comm_relabelling x y).le
theorem add_comm_equiv {x y : pgame} : x + y β y + x :=
(add_comm_relabelling x y).equiv
/-- `(x + y) + z` has exactly the same moves as `x + (y + z)`. -/
def add_assoc_relabelling : Ξ (x y z : pgame.{u}), x + y + z β‘r x + (y + z)
| β¨xl, xr, xL, xRβ© β¨yl, yr, yL, yRβ© β¨zl, zr, zL, zRβ© :=
begin
refine β¨equiv.sum_assoc _ _ _, equiv.sum_assoc _ _ _, _, _β©,
all_goals
{ rintro (β¨i|iβ©|i) <|> rintro (j|β¨j|jβ©),
{ apply add_assoc_relabelling },
{ apply add_assoc_relabelling β¨xl, xr, xL, xRβ© },
{ apply add_assoc_relabelling β¨xl, xr, xL, xRβ© β¨yl, yr, yL, yRβ© } }
end
using_well_founded { dec_tac := pgame_wf_tac }
theorem add_assoc_equiv {x y z : pgame} : (x + y) + z β x + (y + z) :=
(add_assoc_relabelling x y z).equiv
theorem add_left_neg_le_zero : β (x : pgame), -x + x β€ 0
| β¨xl, xr, xL, xRβ© :=
le_zero.2 $ Ξ» i, begin
cases i,
{ -- If Left played in -x, Right responds with the same move in x.
refine β¨@to_right_moves_add _ β¨_, _, _, _β© (sum.inr i), _β©,
convert @add_left_neg_le_zero (xR i),
apply add_move_right_inr },
{ -- If Left in x, Right responds with the same move in -x.
dsimp,
refine β¨@to_right_moves_add β¨_, _, _, _β© _ (sum.inl i), _β©,
convert @add_left_neg_le_zero (xL i),
apply add_move_right_inl }
end
theorem zero_le_add_left_neg (x : pgame) : 0 β€ -x + x :=
begin
rw [βneg_le_neg_iff, neg_zero],
exact neg_add_le.trans (add_left_neg_le_zero _)
end
theorem add_left_neg_equiv (x : pgame) : -x + x β 0 :=
β¨add_left_neg_le_zero x, zero_le_add_left_neg xβ©
theorem add_right_neg_le_zero (x : pgame) : x + -x β€ 0 :=
add_comm_le.trans (add_left_neg_le_zero x)
theorem zero_le_add_right_neg (x : pgame) : 0 β€ x + -x :=
(zero_le_add_left_neg x).trans add_comm_le
theorem add_right_neg_equiv (x : pgame) : x + -x β 0 :=
β¨add_right_neg_le_zero x, zero_le_add_right_neg xβ©
theorem sub_self_equiv : β x, x - x β 0 :=
add_right_neg_equiv
private lemma add_le_add_right' : β {x y z : pgame} (h : x β€ y), x + z β€ y + z
| (mk xl xr xL xR) (mk yl yr yL yR) (mk zl zr zL zR) :=
Ξ» h, begin
refine le_def.2 β¨Ξ» i, _, Ξ» i, _β©;
cases i,
{ rw le_def at h,
cases h,
rcases h_left i with β¨i', ihβ© | β¨j, jhβ©,
{ exact or.inl β¨to_left_moves_add (sum.inl i'), add_le_add_right' ihβ© },
{ refine or.inr β¨to_right_moves_add (sum.inl j), _β©,
convert add_le_add_right' jh,
apply add_move_right_inl } },
{ exact or.inl β¨@to_left_moves_add _ β¨_, _, _, _β© (sum.inr i), add_le_add_right' hβ© },
{ rw le_def at h,
cases h,
rcases h_right i with β¨i, ihβ© | β¨j', jhβ©,
{ refine or.inl β¨to_left_moves_add (sum.inl i), _β©,
convert add_le_add_right' ih,
apply add_move_left_inl },
{ exact or.inr β¨to_right_moves_add (sum.inl j'), add_le_add_right' jhβ© } },
{ exact or.inr β¨@to_right_moves_add _ β¨_, _, _, _β© (sum.inr i), add_le_add_right' hβ© }
end
using_well_founded { dec_tac := pgame_wf_tac }
instance covariant_class_swap_add_le : covariant_class pgame pgame (swap (+)) (β€) :=
β¨Ξ» x y z, add_le_add_right'β©
instance covariant_class_add_le : covariant_class pgame pgame (+) (β€) :=
β¨Ξ» x y z h, (add_comm_le.trans (add_le_add_right h x)).trans add_comm_leβ©
theorem add_lf_add_right {y z : pgame} (h : y β§ z) (x) : y + x β§ z + x :=
suffices z + x β€ y + x β z β€ y, by { rw βpgame.not_le at β’ h, exact mt this h }, Ξ» w,
calc z β€ z + 0 : (add_zero_relabelling _).symm.le
... β€ z + (x + -x) : add_le_add_left (zero_le_add_right_neg x) _
... β€ z + x + -x : (add_assoc_relabelling _ _ _).symm.le
... β€ y + x + -x : add_le_add_right w _
... β€ y + (x + -x) : (add_assoc_relabelling _ _ _).le
... β€ y + 0 : add_le_add_left (add_right_neg_le_zero x) _
... β€ y : (add_zero_relabelling _).le
theorem add_lf_add_left {y z : pgame} (h : y β§ z) (x) : x + y β§ x + z :=
by { rw lf_congr add_comm_equiv add_comm_equiv, apply add_lf_add_right h }
instance covariant_class_swap_add_lt : covariant_class pgame pgame (swap (+)) (<) :=
β¨Ξ» x y z h, β¨add_le_add_right h.1 x, add_lf_add_right h.2 xβ©β©
instance covariant_class_add_lt : covariant_class pgame pgame (+) (<) :=
β¨Ξ» x y z h, β¨add_le_add_left h.1 x, add_lf_add_left h.2 xβ©β©
theorem add_lf_add_of_lf_of_le {w x y z : pgame} (hwx : w β§ x) (hyz : y β€ z) : w + y β§ x + z :=
lf_of_lf_of_le (add_lf_add_right hwx y) (add_le_add_left hyz x)
theorem add_lf_add_of_le_of_lf {w x y z : pgame} (hwx : w β€ x) (hyz : y β§ z) : w + y β§ x + z :=
lf_of_le_of_lf (add_le_add_right hwx y) (add_lf_add_left hyz x)
theorem add_congr {w x y z : pgame} (hβ : w β x) (hβ : y β z) : w + y β x + z :=
β¨(add_le_add_left hβ.1 w).trans (add_le_add_right hβ.1 z),
(add_le_add_left hβ.2 x).trans (add_le_add_right hβ.2 y)β©
theorem add_congr_left {x y z : pgame} (h : x β y) : x + z β y + z :=
add_congr h equiv_rfl
theorem add_congr_right {x y z : pgame} : y β z β x + y β x + z :=
add_congr equiv_rfl
theorem sub_congr {w x y z : pgame} (hβ : w β x) (hβ : y β z) : w - y β x - z :=
add_congr hβ (neg_equiv_neg_iff.2 hβ)
theorem sub_congr_left {x y z : pgame} (h : x β y) : x - z β y - z :=
sub_congr h equiv_rfl
theorem sub_congr_right {x y z : pgame} : y β z β x - y β x - z :=
sub_congr equiv_rfl
theorem le_iff_sub_nonneg {x y : pgame} : x β€ y β 0 β€ y - x :=
β¨Ξ» h, (zero_le_add_right_neg x).trans (add_le_add_right h _),
Ξ» h,
calc x β€ 0 + x : (zero_add_relabelling x).symm.le
... β€ y - x + x : add_le_add_right h _
... β€ y + (-x + x) : (add_assoc_relabelling _ _ _).le
... β€ y + 0 : add_le_add_left (add_left_neg_le_zero x) _
... β€ y : (add_zero_relabelling y).leβ©
theorem lf_iff_sub_zero_lf {x y : pgame} : x β§ y β 0 β§ y - x :=
β¨Ξ» h, (zero_le_add_right_neg x).trans_lf (add_lf_add_right h _),
Ξ» h,
calc x β€ 0 + x : (zero_add_relabelling x).symm.le
... β§ y - x + x : add_lf_add_right h _
... β€ y + (-x + x) : (add_assoc_relabelling _ _ _).le
... β€ y + 0 : add_le_add_left (add_left_neg_le_zero x) _
... β€ y : (add_zero_relabelling y).leβ©
theorem lt_iff_sub_pos {x y : pgame} : x < y β 0 < y - x :=
β¨Ξ» h, lt_of_le_of_lt (zero_le_add_right_neg x) (add_lt_add_right h _),
Ξ» h,
calc x β€ 0 + x : (zero_add_relabelling x).symm.le
... < y - x + x : add_lt_add_right h _
... β€ y + (-x + x) : (add_assoc_relabelling _ _ _).le
... β€ y + 0 : add_le_add_left (add_left_neg_le_zero x) _
... β€ y : (add_zero_relabelling y).leβ©
/-! ### Special pre-games -/
/-- The pre-game `star`, which is fuzzy with zero. -/
def star : pgame.{u} := β¨punit, punit, Ξ» _, 0, Ξ» _, 0β©
@[simp] theorem star_left_moves : star.left_moves = punit := rfl
@[simp] theorem star_right_moves : star.right_moves = punit := rfl
@[simp] theorem star_move_left (x) : star.move_left x = 0 := rfl
@[simp] theorem star_move_right (x) : star.move_right x = 0 := rfl
instance unique_star_left_moves : unique star.left_moves := punit.unique
instance unique_star_right_moves : unique star.right_moves := punit.unique
theorem star_fuzzy_zero : star β 0 :=
β¨by { rw lf_zero, use default, rintros β¨β© }, by { rw zero_lf, use default, rintros β¨β© }β©
@[simp] theorem neg_star : -star = star :=
by simp [star]
@[simp] protected theorem zero_lt_one : (0 : pgame) < 1 :=
lt_of_le_of_lf (zero_le_of_is_empty_right_moves 1) (zero_lf_le.2 β¨default, le_rflβ©)
instance : zero_le_one_class pgame := β¨pgame.zero_lt_one.leβ©
@[simp] theorem zero_lf_one : (0 : pgame) β§ 1 :=
pgame.zero_lt_one.lf
end pgame
|
c4b941e5e947991c4b0da0ce3a92e5d4f06da9fe | 5b273b8c05e2f73fb74340ce100ce261900a98cd | /disjoint_finset.lean | f969ffb0c640767458ee86b442670dde0cdc5663 | [] | no_license | ChrisHughes24/leanstuff1 | 2eba44bc48da6e544e07495b41e1703f81dc1c24 | cbcd788b8b1d07b20b2fff4482c870077a13d1c0 | refs/heads/master | 1,631,670,333,297 | 1,527,093,981,000 | 1,527,093,981,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,793 | lean | import data.finset
namespace finset
variable {Ξ± : Type*}
def disjoint (s t : finset Ξ±) : Prop := β β¦aβ¦, a β s β a β t β false
theorem disjoint.symm {s t : finset Ξ±} (d : disjoint s t) : disjoint t s
| a iβ iβ := d iβ iβ
@[simp] theorem disjoint_comm {s t : finset Ξ±} : disjoint s t β disjoint t s :=
β¨disjoint.symm, disjoint.symmβ©
theorem disjoint_left {s t : finset Ξ±} : disjoint s t β β {a}, a β s β a β t := iff.rfl
theorem disjoint_right {s t : finset Ξ±} : disjoint s t β β {a}, a β t β a β s :=
disjoint_comm
theorem disjoint_iff_ne {s t : finset Ξ±} : disjoint s t β β a β s, β b β t, a β b :=
by simp [disjoint_left, imp_not_comm]
theorem disjoint_of_subset_left {s t u : finset Ξ±} (h : s β u) (d : disjoint u t) : disjoint s t
| x mβ := d (h mβ)
theorem disjoint_of_subset_right {s t u : finset Ξ±} (h : t β u) (d : disjoint s u) : disjoint s t
| x m mβ := d m (h mβ)
@[simp] theorem empty_disjoint (l : finset Ξ±) : disjoint β
l
| a := (not_mem_empty a).elim
@[simp] theorem singleton_disjoint [decidable_eq Ξ±] {l : finset Ξ±} {a : Ξ±} : disjoint (singleton a) l β a β l :=
by simp [disjoint]; refl
@[simp] theorem disjoint_singleton [decidable_eq Ξ±] {l : finset Ξ±} {a : Ξ±} : disjoint l (singleton a) β a β l :=
by rw disjoint_comm; simp
@[simp] theorem disjoint_insert_left [decidable_eq Ξ±] {a : Ξ±} {s t : finset Ξ±} :
disjoint (insert a s) t β a β t β§ disjoint s t :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]; refl
@[simp] theorem disjoint_insert_right [decidable_eq Ξ±] {a : Ξ±} {s t : finset Ξ±} :
disjoint s (insert a t) β a β s β§ disjoint s t :=
disjoint_comm.trans $ by simp [disjoint_insert_left]
theorem inter_eq_empty_iff_disjoint [decidable_eq Ξ±] {s t : finset Ξ±} : s β© t = β
β disjoint s t :=
by simp [ext, mem_inter]; refl
theorem inter_eq_zero_iff_disjoint [decidable_eq Ξ±] {s t : finset Ξ±} : s β© t = β
β disjoint s t :=
by rw β subset_empty; simp [subset_iff, disjoint]
@[simp] theorem disjoint_union_left [decidable_eq Ξ±] {s t u : finset Ξ±} :
disjoint (s βͺ t) u β disjoint s u β§ disjoint t u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_union_right [decidable_eq Ξ±] {s t u : finset Ξ±} :
disjoint s (t βͺ u) β disjoint s t β§ disjoint s u :=
by simp [disjoint, or_imp_distrib, forall_and_distrib]
@[simp] theorem disjoint_val {s t : finset Ξ±} : multiset.disjoint s.1 t.1 β disjoint s t :=
by simp [disjoint, multiset.disjoint, mem_def]
@[simp] theorem card_disjoint_union [decidable_eq Ξ±] {s t : finset Ξ±} :
disjoint s t β card (s βͺ t) = card s + card t :=
finset.induction_on s (by simp) $ begin simp {contextual := tt} end
end finset
|
2b0203d93d224709956b728868cb7e44a08ef01c | 6329dd15b8fd567a4737f2dacd02bd0e8c4b3ae4 | /src/game/world1/level1.lean | 489c394c84218cd5fbce620ff85698c8caf82495 | [
"Apache-2.0"
] | permissive | agusakov/mathematics_in_lean_game | 76e455a688a8826b05160c16c0490b9e3d39f071 | ad45fd42148f2203b973537adec7e8a48677ba2a | refs/heads/master | 1,666,147,402,274 | 1,592,119,137,000 | 1,592,119,137,000 | 272,111,226 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,845 | lean | import data.real.basic --imports the real numbers
import tactic.maths_in_lean_game -- hide
namespace calculating -- hide
/- Axiom : mul_comm (a b : β) :
a * b = b * a
-/
/- Axiom : mul_assoc (a b c : β) :
(a * b) * c = a * (b * c)
-/
/-
#Calculating
## Level 1: The `rw` tactic.
We generally learn to carry out mathematical calculations
without thinking of them as proofs.
But when we justify each step in a calculation,
as Lean requires us to do,
the net result is a proof that the left-hand side of the calculation
is equal to the right-hand side.
In Lean, stating a theorem is tantamount to stating a goal,
namely, the goal of proving the theorem.
Lean provides the `rewrite` tactic, abbreviated `rw`,
to replace the left-hand side of an identity by the right-hand side
in the goal. If `a`, `b`, and `c` are real numbers,
`mul_assoc a b c` is the identity `a * b * c = a * (b * c)`
and `mul_comm a b` is the identity `a * b = b * a`.
In Lean, multiplication associates to the left,
so the left-hand side of `mul_assoc` could also be written `(a * b) * c`.
However, it is generally good style to be mindful of Lean's
notational conventions and leave out parentheses when Lean does as well.
Let's try out `rw`.
First we use `rw mul_comm a b,` to swap $a$ with $b$,
and then `rw mul_assoc b a c` to do associativity stuff.
-/
/- Lemma : no-side-bar
-/
lemma example1 (a b c : β) : (a * b) * c = b * (a * c) :=
begin [maths_in_lean_game]
rw mul_comm a b,
rw mul_assoc b a c
end
/-
As you move your cursor past each step of the proof,
you can see the goal of the proof change.
The `import` line at the beginning of the example
imports the theory of the real numbers from `mathlib`.
For the sake of brevity,
we generally suppress information like this when it
is repeated from example to example.
-/
end calculating -- hide |
902962e14589540053f0644bd8d675e87daa4b71 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/geometry/euclidean/triangle.lean | dbfad34a93f32df2e9eb832b945169b0c8a276ef | [
"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 | 19,223 | lean | /-
Copyright (c) 2020 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers, Manuel Candales
-/
import geometry.euclidean.basic
import tactic.interval_cases
/-!
# Triangles
This file proves basic geometrical results about distances and angles
in (possibly degenerate) triangles in real inner product spaces and
Euclidean affine spaces. More specialized results, and results
developed for simplices in general rather than just for triangles, are
in separate files. Definitions and results that make sense in more
general affine spaces rather than just in the Euclidean case go under
`linear_algebra.affine_space`.
## Implementation notes
Results in this file are generally given in a form with only those
non-degeneracy conditions needed for the particular result, rather
than requiring affine independence of the points of a triangle
unnecessarily.
## References
* https://en.wikipedia.org/wiki/Pythagorean_theorem
* https://en.wikipedia.org/wiki/Law_of_cosines
* https://en.wikipedia.org/wiki/Pons_asinorum
* https://en.wikipedia.org/wiki/Sum_of_angles_of_a_triangle
-/
noncomputable theory
open_locale big_operators
open_locale classical
open_locale real
open_locale real_inner_product_space
namespace inner_product_geometry
/-!
### Geometrical results on triangles in real inner product spaces
This section develops some results on (possibly degenerate) triangles
in real inner product spaces, where those definitions and results can
most conveniently be developed in terms of vectors and then used to
deduce corresponding results for Euclidean affine spaces.
-/
variables {V : Type*} [inner_product_space β V]
/-- Pythagorean theorem, if-and-only-if vector angle form. -/
lemma norm_add_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two (x y : V) :
β₯x + yβ₯ * β₯x + yβ₯ = β₯xβ₯ * β₯xβ₯ + β₯yβ₯ * β₯yβ₯ β angle x y = Ο / 2 :=
begin
rw norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero,
exact inner_eq_zero_iff_angle_eq_pi_div_two x y
end
/-- Pythagorean theorem, vector angle form. -/
lemma norm_add_sq_eq_norm_sq_add_norm_sq' (x y : V) (h : angle x y = Ο / 2) :
β₯x + yβ₯ * β₯x + yβ₯ = β₯xβ₯ * β₯xβ₯ + β₯yβ₯ * β₯yβ₯ :=
(norm_add_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two x y).2 h
/-- Pythagorean theorem, subtracting vectors, if-and-only-if vector angle form. -/
lemma norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two (x y : V) :
β₯x - yβ₯ * β₯x - yβ₯ = β₯xβ₯ * β₯xβ₯ + β₯yβ₯ * β₯yβ₯ β angle x y = Ο / 2 :=
begin
rw norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero,
exact inner_eq_zero_iff_angle_eq_pi_div_two x y
end
/-- Pythagorean theorem, subtracting vectors, vector angle form. -/
lemma norm_sub_sq_eq_norm_sq_add_norm_sq' (x y : V) (h : angle x y = Ο / 2) :
β₯x - yβ₯ * β₯x - yβ₯ = β₯xβ₯ * β₯xβ₯ + β₯yβ₯ * β₯yβ₯ :=
(norm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two x y).2 h
/-- Law of cosines (cosine rule), vector angle form. -/
lemma norm_sub_sq_eq_norm_sq_add_norm_sq_sub_two_mul_norm_mul_norm_mul_cos_angle
(x y : V) :
β₯x - yβ₯ * β₯x - yβ₯ = β₯xβ₯ * β₯xβ₯ + β₯yβ₯ * β₯yβ₯ - 2 * β₯xβ₯ * β₯yβ₯ * real.cos (angle x y) :=
by rw [(show 2 * β₯xβ₯ * β₯yβ₯ * real.cos (angle x y) =
2 * (real.cos (angle x y) * (β₯xβ₯ * β₯yβ₯)), by ring),
cos_angle_mul_norm_mul_norm, βreal_inner_self_eq_norm_sq,
βreal_inner_self_eq_norm_sq, βreal_inner_self_eq_norm_sq, real_inner_sub_sub_self,
sub_add_eq_add_sub]
/-- Pons asinorum, vector angle form. -/
lemma angle_sub_eq_angle_sub_rev_of_norm_eq {x y : V} (h : β₯xβ₯ = β₯yβ₯) :
angle x (x - y) = angle y (y - x) :=
begin
refine real.inj_on_cos β¨angle_nonneg _ _, angle_le_pi _ _β© β¨angle_nonneg _ _, angle_le_pi _ _β© _,
rw [cos_angle, cos_angle, h, βneg_sub, norm_neg, neg_sub,
inner_sub_right, inner_sub_right, real_inner_self_eq_norm_sq,
real_inner_self_eq_norm_sq, h, real_inner_comm x y]
end
/-- Converse of pons asinorum, vector angle form. -/
lemma norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi {x y : V}
(h : angle x (x - y) = angle y (y - x)) (hpi : angle x y β Ο) : β₯xβ₯ = β₯yβ₯ :=
begin
replace h := real.arccos_inj_on
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x (x - y)))
(abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one y (y - x))) h,
by_cases hxy : x = y,
{ rw hxy },
{ rw [βnorm_neg (y - x), neg_sub, mul_comm, mul_comm β₯yβ₯, div_eq_mul_inv, div_eq_mul_inv,
mul_inv_rev', mul_inv_rev', βmul_assoc, βmul_assoc] at h,
replace h :=
mul_right_cancel' (inv_ne_zero (Ξ» hz, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 hz)))) h,
rw [inner_sub_right, inner_sub_right, real_inner_comm x y, real_inner_self_eq_norm_sq,
real_inner_self_eq_norm_sq, mul_sub_right_distrib, mul_sub_right_distrib,
mul_self_mul_inv, mul_self_mul_inv, sub_eq_sub_iff_sub_eq_sub,
βmul_sub_left_distrib] at h,
by_cases hx0 : x = 0,
{ rw [hx0, norm_zero, inner_zero_left, zero_mul, zero_sub, neg_eq_zero] at h,
rw [hx0, norm_zero, h] },
{ by_cases hy0 : y = 0,
{ rw [hy0, norm_zero, inner_zero_right, zero_mul, sub_zero] at h,
rw [hy0, norm_zero, h] },
{ rw [inv_sub_inv (Ξ» hz, hx0 (norm_eq_zero.1 hz)) (Ξ» hz, hy0 (norm_eq_zero.1 hz)),
βneg_sub, βmul_div_assoc, mul_comm, mul_div_assoc, βmul_neg_one] at h,
symmetry,
by_contradiction hyx,
replace h := (mul_left_cancel' (sub_ne_zero_of_ne hyx) h).symm,
rw [real_inner_div_norm_mul_norm_eq_neg_one_iff, βangle_eq_pi_iff] at h,
exact hpi h } } }
end
/-- The cosine of the sum of two angles in a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle {x y : V} (hx : x β 0) (hy : y β 0) :
real.cos (angle x (x - y) + angle y (y - x)) = -real.cos (angle x y) :=
begin
by_cases hxy : x = y,
{ rw [hxy, angle_self hy],
simp },
{ rw [real.cos_add, cos_angle, cos_angle, cos_angle],
have hxn : β₯xβ₯ β 0 := (Ξ» h, hx (norm_eq_zero.1 h)),
have hyn : β₯yβ₯ β 0 := (Ξ» h, hy (norm_eq_zero.1 h)),
have hxyn : β₯x - yβ₯ β 0 := (Ξ» h, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 h))),
apply mul_right_cancel' hxn,
apply mul_right_cancel' hyn,
apply mul_right_cancel' hxyn,
apply mul_right_cancel' hxyn,
have H1 : real.sin (angle x (x - y)) * real.sin (angle y (y - x)) *
β₯xβ₯ * β₯yβ₯ * β₯x - yβ₯ * β₯x - yβ₯ =
(real.sin (angle x (x - y)) * (β₯xβ₯ * β₯x - yβ₯)) *
(real.sin (angle y (y - x)) * (β₯yβ₯ * β₯x - yβ₯)), { ring },
have H2 : βͺx, xβ« * (inner x x - inner x y - (inner x y - inner y y)) -
(inner x x - inner x y) * (inner x x - inner x y) =
inner x x * inner y y - inner x y * inner x y, { ring },
have H3 : βͺy, yβ« * (inner y y - inner x y - (inner x y - inner x x)) -
(inner y y - inner x y) * (inner y y - inner x y) =
inner x x * inner y y - inner x y * inner x y, { ring },
rw [mul_sub_right_distrib, mul_sub_right_distrib, mul_sub_right_distrib,
mul_sub_right_distrib, H1, sin_angle_mul_norm_mul_norm, norm_sub_rev x y,
sin_angle_mul_norm_mul_norm, norm_sub_rev y x, inner_sub_left, inner_sub_left,
inner_sub_right, inner_sub_right, inner_sub_right, inner_sub_right, real_inner_comm x y, H2,
H3, real.mul_self_sqrt (sub_nonneg_of_le (real_inner_mul_inner_self_le x y)),
real_inner_self_eq_norm_sq, real_inner_self_eq_norm_sq,
real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two],
field_simp [hxn, hyn, hxyn],
ring }
end
/-- The sine of the sum of two angles in a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma sin_angle_sub_add_angle_sub_rev_eq_sin_angle {x y : V} (hx : x β 0) (hy : y β 0) :
real.sin (angle x (x - y) + angle y (y - x)) = real.sin (angle x y) :=
begin
by_cases hxy : x = y,
{ rw [hxy, angle_self hy],
simp },
{ rw [real.sin_add, cos_angle, cos_angle],
have hxn : β₯xβ₯ β 0 := (Ξ» h, hx (norm_eq_zero.1 h)),
have hyn : β₯yβ₯ β 0 := (Ξ» h, hy (norm_eq_zero.1 h)),
have hxyn : β₯x - yβ₯ β 0 := (Ξ» h, hxy (eq_of_sub_eq_zero (norm_eq_zero.1 h))),
apply mul_right_cancel' hxn,
apply mul_right_cancel' hyn,
apply mul_right_cancel' hxyn,
apply mul_right_cancel' hxyn,
have H1 : real.sin (angle x (x - y)) * (βͺy, y - xβ« / (β₯yβ₯ * β₯y - xβ₯)) * β₯xβ₯ * β₯yβ₯ * β₯x - yβ₯ =
real.sin (angle x (x - y)) * (β₯xβ₯ * β₯x - yβ₯) *
(βͺy, y - xβ« / (β₯yβ₯ * β₯y - xβ₯)) * β₯yβ₯, { ring },
have H2 : βͺx, x - yβ« / (β₯xβ₯ * β₯y - xβ₯) * real.sin (angle y (y - x)) * β₯xβ₯ * β₯yβ₯ * β₯y - xβ₯ =
βͺx, x - yβ« / (β₯xβ₯ * β₯y - xβ₯) *
(real.sin (angle y (y - x)) * (β₯yβ₯ * β₯y - xβ₯)) * β₯xβ₯, { ring },
have H3 : βͺx, xβ« * (βͺx, xβ« - βͺx, yβ« - (βͺx, yβ« - βͺy, yβ«)) -
(βͺx, xβ« - βͺx, yβ«) * (βͺx, xβ« - βͺx, yβ«) =
βͺx, xβ« * βͺy, yβ« - βͺx, yβ« * βͺx, yβ«, { ring },
have H4 : βͺy, yβ« * (βͺy, yβ« - βͺx, yβ« - (βͺx, yβ« - βͺx, xβ«)) -
(βͺy, yβ« - βͺx, yβ«) * (βͺy, yβ« - βͺx, yβ«) =
βͺx, xβ« * βͺy, yβ« - βͺx, yβ« * βͺx, yβ«, { ring },
rw [right_distrib, right_distrib, right_distrib, right_distrib, H1,
sin_angle_mul_norm_mul_norm, norm_sub_rev x y, H2, sin_angle_mul_norm_mul_norm,
norm_sub_rev y x, mul_assoc (real.sin (angle x y)), sin_angle_mul_norm_mul_norm,
inner_sub_left, inner_sub_left, inner_sub_right, inner_sub_right, inner_sub_right,
inner_sub_right, real_inner_comm x y, H3, H4, real_inner_self_eq_norm_sq,
real_inner_self_eq_norm_sq,
real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two],
field_simp [hxn, hyn, hxyn],
ring }
end
/-- The cosine of the sum of the angles of a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma cos_angle_add_angle_sub_add_angle_sub_eq_neg_one {x y : V} (hx : x β 0) (hy : y β 0) :
real.cos (angle x y + angle x (x - y) + angle y (y - x)) = -1 :=
by rw [add_assoc, real.cos_add, cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle hx hy,
sin_angle_sub_add_angle_sub_rev_eq_sin_angle hx hy, βneg_mul_eq_mul_neg, βneg_add',
add_comm, βsq, βsq, real.sin_sq_add_cos_sq]
/-- The sine of the sum of the angles of a possibly degenerate
triangle (where two given sides are nonzero), vector angle form. -/
lemma sin_angle_add_angle_sub_add_angle_sub_eq_zero {x y : V} (hx : x β 0) (hy : y β 0) :
real.sin (angle x y + angle x (x - y) + angle y (y - x)) = 0 :=
begin
rw [add_assoc, real.sin_add, cos_angle_sub_add_angle_sub_rev_eq_neg_cos_angle hx hy,
sin_angle_sub_add_angle_sub_rev_eq_sin_angle hx hy],
ring
end
/-- The sum of the angles of a possibly degenerate triangle (where the
two given sides are nonzero), vector angle form. -/
lemma angle_add_angle_sub_add_angle_sub_eq_pi {x y : V} (hx : x β 0) (hy : y β 0) :
angle x y + angle x (x - y) + angle y (y - x) = Ο :=
begin
have hcos := cos_angle_add_angle_sub_add_angle_sub_eq_neg_one hx hy,
have hsin := sin_angle_add_angle_sub_add_angle_sub_eq_zero hx hy,
rw real.sin_eq_zero_iff at hsin,
cases hsin with n hn,
symmetry' at hn,
have h0 : 0 β€ angle x y + angle x (x - y) + angle y (y - x) :=
add_nonneg (add_nonneg (angle_nonneg _ _) (angle_nonneg _ _)) (angle_nonneg _ _),
have h3 : angle x y + angle x (x - y) + angle y (y - x) β€ Ο + Ο + Ο :=
add_le_add (add_le_add (angle_le_pi _ _) (angle_le_pi _ _)) (angle_le_pi _ _),
have h3lt : angle x y + angle x (x - y) + angle y (y - x) < Ο + Ο + Ο,
{ by_contradiction hnlt,
have hxy : angle x y = Ο,
{ by_contradiction hxy,
exact hnlt (add_lt_add_of_lt_of_le (add_lt_add_of_lt_of_le
(lt_of_le_of_ne (angle_le_pi _ _) hxy)
(angle_le_pi _ _)) (angle_le_pi _ _)) },
rw hxy at hnlt,
rw angle_eq_pi_iff at hxy,
rcases hxy with β¨hx, β¨r, β¨hr, hxrβ©β©β©,
rw [hxr, βone_smul β x, βmul_smul, mul_one, βsub_smul, one_smul, sub_eq_add_neg,
angle_smul_right_of_pos _ _ (add_pos zero_lt_one (neg_pos_of_neg hr)), angle_self hx,
add_zero] at hnlt,
apply hnlt,
rw add_assoc,
exact add_lt_add_left (lt_of_le_of_lt (angle_le_pi _ _)
(lt_add_of_pos_right Ο real.pi_pos)) _ },
have hn0 : 0 β€ n,
{ rw [hn, mul_nonneg_iff_right_nonneg_of_pos real.pi_pos] at h0,
norm_cast at h0,
exact h0 },
have hn3 : n < 3,
{ rw [hn, (show Ο + Ο + Ο = 3 * Ο, by ring)] at h3lt,
replace h3lt := lt_of_mul_lt_mul_right h3lt (le_of_lt real.pi_pos),
norm_cast at h3lt,
exact h3lt },
interval_cases n,
{ rw hn at hcos,
simp at hcos,
norm_num at hcos },
{ rw hn,
norm_num },
{ rw hn at hcos,
simp at hcos,
norm_num at hcos },
end
end inner_product_geometry
namespace euclidean_geometry
/-!
### Geometrical results on triangles in Euclidean affine spaces
This section develops some geometrical definitions and results on
(possible degenerate) triangles in Euclidean affine spaces.
-/
open inner_product_geometry
open_locale euclidean_geometry
variables {V : Type*} {P : Type*} [inner_product_space β V] [metric_space P]
[normed_add_torsor V P]
include V
/-- Pythagorean theorem, if-and-only-if angle-at-point form. -/
lemma dist_sq_eq_dist_sq_add_dist_sq_iff_angle_eq_pi_div_two (p1 p2 p3 : P) :
dist p1 p3 * dist p1 p3 = dist p1 p2 * dist p1 p2 + dist p3 p2 * dist p3 p2 β
β p1 p2 p3 = Ο / 2 :=
by erw [pseudo_metric_space.dist_comm p3 p2, dist_eq_norm_vsub V p1 p3, dist_eq_norm_vsub V p1 p2,
dist_eq_norm_vsub V p2 p3,
βnorm_sub_sq_eq_norm_sq_add_norm_sq_iff_angle_eq_pi_div_two,
vsub_sub_vsub_cancel_right p1, βneg_vsub_eq_vsub_rev p2 p3, norm_neg]
/-- Law of cosines (cosine rule), angle-at-point form. -/
lemma dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle
(p1 p2 p3 : P) :
dist p1 p3 * dist p1 p3 =
dist p1 p2 * dist p1 p2 + dist p3 p2 * dist p3 p2 -
2 * dist p1 p2 * dist p3 p2 * real.cos (β p1 p2 p3) :=
begin
rw [dist_eq_norm_vsub V p1 p3, dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p3 p2],
unfold angle,
convert norm_sub_sq_eq_norm_sq_add_norm_sq_sub_two_mul_norm_mul_norm_mul_cos_angle
(p1 -α΅₯ p2 : V) (p3 -α΅₯ p2 : V),
{ exact (vsub_sub_vsub_cancel_right p1 p3 p2).symm },
{ exact (vsub_sub_vsub_cancel_right p1 p3 p2).symm }
end
alias dist_sq_eq_dist_sq_add_dist_sq_sub_two_mul_dist_mul_dist_mul_cos_angle β law_cos
/-- Pons asinorum, angle-at-point form. -/
lemma angle_eq_angle_of_dist_eq {p1 p2 p3 : P} (h : dist p1 p2 = dist p1 p3) :
β p1 p2 p3 = β p1 p3 p2 :=
begin
rw [dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p1 p3] at h,
unfold angle,
convert angle_sub_eq_angle_sub_rev_of_norm_eq h,
{ exact (vsub_sub_vsub_cancel_left p3 p2 p1).symm },
{ exact (vsub_sub_vsub_cancel_left p2 p3 p1).symm }
end
/-- Converse of pons asinorum, angle-at-point form. -/
lemma dist_eq_of_angle_eq_angle_of_angle_ne_pi {p1 p2 p3 : P} (h : β p1 p2 p3 = β p1 p3 p2)
(hpi : β p2 p1 p3 β Ο) : dist p1 p2 = dist p1 p3 :=
begin
unfold angle at h hpi,
rw [dist_eq_norm_vsub V p1 p2, dist_eq_norm_vsub V p1 p3],
rw [βangle_neg_neg, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev] at hpi,
rw [βvsub_sub_vsub_cancel_left p3 p2 p1, βvsub_sub_vsub_cancel_left p2 p3 p1] at h,
exact norm_eq_of_angle_sub_eq_angle_sub_rev_of_angle_ne_pi h hpi
end
/-- The sum of the angles of a possibly degenerate triangle (where the
given vertex is distinct from the others), angle-at-point. -/
lemma angle_add_angle_add_angle_eq_pi {p1 p2 p3 : P} (h2 : p2 β p1) (h3 : p3 β p1) :
β p1 p2 p3 + β p2 p3 p1 + β p3 p1 p2 = Ο :=
begin
rw [add_assoc, add_comm, add_comm (β p2 p3 p1), angle_comm p2 p3 p1],
unfold angle,
rw [βangle_neg_neg (p1 -α΅₯ p3), βangle_neg_neg (p1 -α΅₯ p2), neg_vsub_eq_vsub_rev,
neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev, neg_vsub_eq_vsub_rev,
βvsub_sub_vsub_cancel_right p3 p2 p1, βvsub_sub_vsub_cancel_right p2 p3 p1],
exact angle_add_angle_sub_add_angle_sub_eq_pi (Ξ» he, h3 (vsub_eq_zero_iff_eq.1 he))
(Ξ» he, h2 (vsub_eq_zero_iff_eq.1 he))
end
/-- Stewart's Theorem. -/
theorem dist_sq_mul_dist_add_dist_sq_mul_dist (a b c p : P) (h : β b p c = Ο) :
dist a b ^ 2 * dist c p + dist a c ^ 2 * dist b p =
dist b c * (dist a p ^ 2 + dist b p * dist c p) :=
begin
rw [pow_two, pow_two, law_cos a p b, law_cos a p c,
eq_sub_of_add_eq (angle_add_angle_eq_pi_of_angle_eq_pi a h), real.cos_pi_sub,
dist_eq_add_dist_of_angle_eq_pi h],
ring,
end
/-- Apollonius's Theorem. -/
theorem dist_sq_add_dist_sq_eq_two_mul_dist_midpoint_sq_add_half_dist_sq (a b c : P) :
dist a b ^ 2 + dist a c ^ 2 = 2 * (dist a (midpoint β b c) ^ 2 + (dist b c / 2) ^ 2) :=
begin
by_cases hbc : b = c,
{ simp [hbc, midpoint_self, dist_self, two_mul] },
{ let m := midpoint β b c,
have : dist b c β 0 := (dist_pos.mpr hbc).ne',
have hm := dist_sq_mul_dist_add_dist_sq_mul_dist a b c m (angle_midpoint_eq_pi b c hbc),
simp only [dist_left_midpoint, dist_right_midpoint, real.norm_two] at hm,
calc dist a b ^ 2 + dist a c ^ 2
= 2 / dist b c * (dist a b ^ 2 * (2β»ΒΉ * dist b c) + dist a c ^ 2 * (2β»ΒΉ * dist b c)) :
by { field_simp, ring }
... = 2 * (dist a (midpoint β b c) ^ 2 + (dist b c / 2) ^ 2) :
by { rw hm, field_simp, ring } },
end
lemma dist_mul_of_eq_angle_of_dist_mul (a b c a' b' c' : P) (r : β) (h : β a' b' c' = β a b c)
(hab : dist a' b' = r * dist a b) (hcb : dist c' b' = r * dist c b) :
dist a' c' = r * dist a c :=
begin
have h' : dist a' c' ^ 2 = (r * dist a c) ^ 2,
calc dist a' c' ^ 2
= dist a' b' ^ 2 + dist c' b' ^ 2 - 2 * dist a' b' * dist c' b' * real.cos (β a' b' c') :
by { simp [pow_two, law_cos a' b' c'] }
... = r ^ 2 * (dist a b ^ 2 + dist c b ^ 2 - 2 * dist a b * dist c b * real.cos (β a b c)) :
by { rw [h, hab, hcb], ring }
... = (r * dist a c) ^ 2 : by simp [pow_two, β law_cos a b c, mul_pow],
by_cases habβ : a = b,
{ have hab'β : a' = b', { rw [β dist_eq_zero, hab, dist_eq_zero.mpr habβ, mul_zero r] },
rw [habβ, hab'β, dist_comm b' c', dist_comm b c, hcb] },
{ have h1 : 0 β€ r * dist a b, { rw β hab, exact dist_nonneg },
have h2 : 0 β€ r := nonneg_of_mul_nonneg_right h1 (dist_pos.mpr habβ),
exact (eq_of_sq_eq_sq dist_nonneg (mul_nonneg h2 dist_nonneg)).mp h' },
end
end euclidean_geometry
|
cf766947312df35a31d104d2e58b8fee325f1274 | 9d2e3d5a2e2342a283affd97eead310c3b528a24 | /src/hints/thursday/afternoon/category_theory/exercise1/hint2.lean | 787902bde4159453a2f7ceea4222cdd89f56a7a7 | [] | permissive | Vtec234/lftcm2020 | ad2610ab614beefe44acc5622bb4a7fff9a5ea46 | bbbd4c8162f8c2ef602300ab8fdeca231886375d | refs/heads/master | 1,668,808,098,623 | 1,594,989,081,000 | 1,594,990,079,000 | 280,423,039 | 0 | 0 | MIT | 1,594,990,209,000 | 1,594,990,209,000 | null | UTF-8 | Lean | false | false | 851 | lean | import category_theory.isomorphism
import category_theory.yoneda
open category_theory
open opposite
variables {C : Type*} [category C]
def iso_of_hom_iso_attempt (X Y : C) (h : yoneda.obj X β
yoneda.obj Y) : X β
Y :=
{ hom :=
begin
-- We need to construct a morphism `X βΆ Y`.
-- Recall that the components `h.app Z` of our hypothesis are isomorphisms.
-- We can check exactly what they are (if we've forgotten how `yoneda` works), like this:
have := h.app,
dsimp at this,
-- This says that for any `Z : Cα΅α΅`, we get an isomorphism from
-- the morphism space `unop Z βΆ Z` to the morphism space `unop Z βΆ Y`.
-- This suggests we want to use `h.app (op X)`, and apply the forward direction of that
-- to some element of `unop (op X) βΆ X` that we have available.
sorry
end,
inv := sorry, }
|
8753de0c113598183dc0941f9e76d0c48ae320e5 | 367134ba5a65885e863bdc4507601606690974c1 | /src/data/zsqrtd/basic.lean | ed665d670673418d7495294dfb9269191300bffb | [
"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 | 28,608 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import algebra.associated
import tactic.ring
/-- The ring of integers adjoined with a square root of `d`.
These have the form `a + b βd` where `a b : β€`. The components
are called `re` and `im` by analogy to the negative `d` case,
but of course both parts are real here since `d` is nonnegative. -/
structure zsqrtd (d : β€) :=
(re : β€)
(im : β€)
prefix `β€β`:100 := zsqrtd
namespace zsqrtd
section
parameters {d : β€}
instance : decidable_eq β€βd :=
by tactic.mk_dec_eq_instance
theorem ext : β {z w : β€βd}, z = w β z.re = w.re β§ z.im = w.im
| β¨x, yβ© β¨x', y'β© := β¨Ξ» h, by injection h; split; assumption,
Ξ» β¨hβ, hββ©, by congr; assumptionβ©
/-- Convert an integer to a `β€βd` -/
def of_int (n : β€) : β€βd := β¨n, 0β©
theorem of_int_re (n : β€) : (of_int n).re = n := rfl
theorem of_int_im (n : β€) : (of_int n).im = 0 := rfl
/-- The zero of the ring -/
def zero : β€βd := of_int 0
instance : has_zero β€βd := β¨zsqrtd.zeroβ©
@[simp] theorem zero_re : (0 : β€βd).re = 0 := rfl
@[simp] theorem zero_im : (0 : β€βd).im = 0 := rfl
instance : inhabited β€βd := β¨0β©
/-- The one of the ring -/
def one : β€βd := of_int 1
instance : has_one β€βd := β¨zsqrtd.oneβ©
@[simp] theorem one_re : (1 : β€βd).re = 1 := rfl
@[simp] theorem one_im : (1 : β€βd).im = 0 := rfl
/-- The representative of `βd` in the ring -/
def sqrtd : β€βd := β¨0, 1β©
@[simp] theorem sqrtd_re : (sqrtd : β€βd).re = 0 := rfl
@[simp] theorem sqrtd_im : (sqrtd : β€βd).im = 1 := rfl
/-- Addition of elements of `β€βd` -/
def add : β€βd β β€βd β β€βd
| β¨x, yβ© β¨x', y'β© := β¨x + x', y + y'β©
instance : has_add β€βd := β¨zsqrtd.addβ©
@[simp] theorem add_def (x y x' y' : β€) :
(β¨x, yβ© + β¨x', y'β© : β€βd) = β¨x + x', y + y'β© := rfl
@[simp] theorem add_re : β z w : β€βd, (z + w).re = z.re + w.re
| β¨x, yβ© β¨x', y'β© := rfl
@[simp] theorem add_im : β z w : β€βd, (z + w).im = z.im + w.im
| β¨x, yβ© β¨x', y'β© := rfl
@[simp] theorem bit0_re (z) : (bit0 z : β€βd).re = bit0 z.re := add_re _ _
@[simp] theorem bit0_im (z) : (bit0 z : β€βd).im = bit0 z.im := add_im _ _
@[simp] theorem bit1_re (z) : (bit1 z : β€βd).re = bit1 z.re := by simp [bit1]
@[simp] theorem bit1_im (z) : (bit1 z : β€βd).im = bit0 z.im := by simp [bit1]
/-- Negation in `β€βd` -/
def neg : β€βd β β€βd
| β¨x, yβ© := β¨-x, -yβ©
instance : has_neg β€βd := β¨zsqrtd.negβ©
@[simp] theorem neg_re : β z : β€βd, (-z).re = -z.re
| β¨x, yβ© := rfl
@[simp] theorem neg_im : β z : β€βd, (-z).im = -z.im
| β¨x, yβ© := rfl
/-- Conjugation in `β€βd`. The conjugate of `a + b βd` is `a - b βd`. -/
def conj : β€βd β β€βd
| β¨x, yβ© := β¨x, -yβ©
@[simp] theorem conj_re : β z : β€βd, (conj z).re = z.re
| β¨x, yβ© := rfl
@[simp] theorem conj_im : β z : β€βd, (conj z).im = -z.im
| β¨x, yβ© := rfl
/-- Multiplication in `β€βd` -/
def mul : β€βd β β€βd β β€βd
| β¨x, yβ© β¨x', y'β© := β¨x * x' + d * y * y', x * y' + y * x'β©
instance : has_mul β€βd := β¨zsqrtd.mulβ©
@[simp] theorem mul_re : β z w : β€βd, (z * w).re = z.re * w.re + d * z.im * w.im
| β¨x, yβ© β¨x', y'β© := rfl
@[simp] theorem mul_im : β z w : β€βd, (z * w).im = z.re * w.im + z.im * w.re
| β¨x, yβ© β¨x', y'β© := rfl
instance : comm_ring β€βd := by refine
{ add := (+),
zero := 0,
neg := has_neg.neg,
mul := (*),
sub := Ξ» a b, a + -b,
one := 1, ..};
{ intros, simp [ext, add_mul, mul_add, add_comm, add_left_comm, mul_comm, mul_left_comm] }
instance : add_comm_monoid β€βd := by apply_instance
instance : add_monoid β€βd := by apply_instance
instance : monoid β€βd := by apply_instance
instance : comm_monoid β€βd := by apply_instance
instance : comm_semigroup β€βd := by apply_instance
instance : semigroup β€βd := by apply_instance
instance : add_comm_semigroup β€βd := by apply_instance
instance : add_semigroup β€βd := by apply_instance
instance : comm_semiring β€βd := by apply_instance
instance : semiring β€βd := by apply_instance
instance : ring β€βd := by apply_instance
instance : distrib β€βd := by apply_instance
instance : nontrivial β€βd :=
β¨β¨0, 1, dec_trivialβ©β©
@[simp] theorem coe_nat_re (n : β) : (n : β€βd).re = n :=
by induction n; simp *
@[simp] theorem coe_nat_im (n : β) : (n : β€βd).im = 0 :=
by induction n; simp *
theorem coe_nat_val (n : β) : (n : β€βd) = β¨n, 0β© :=
by simp [ext]
@[simp] theorem coe_int_re (n : β€) : (n : β€βd).re = n :=
by cases n; simp [*, int.of_nat_eq_coe, int.neg_succ_of_nat_eq]
@[simp] theorem coe_int_im (n : β€) : (n : β€βd).im = 0 :=
by cases n; simp *
theorem coe_int_val (n : β€) : (n : β€βd) = β¨n, 0β© :=
by simp [ext]
instance : char_zero β€βd :=
{ cast_injective := Ξ» m n, by simp [ext] }
@[simp] theorem of_int_eq_coe (n : β€) : (of_int n : β€βd) = n :=
by simp [ext, of_int_re, of_int_im]
@[simp] theorem smul_val (n x y : β€) : (n : β€βd) * β¨x, yβ© = β¨n * x, n * yβ© :=
by simp [ext]
@[simp] theorem muld_val (x y : β€) : sqrtd * β¨x, yβ© = β¨d * y, xβ© :=
by simp [ext]
@[simp] theorem dmuld : sqrtd * sqrtd = d :=
by simp [ext]
@[simp] theorem smuld_val (n x y : β€) : sqrtd * (n : β€βd) * β¨x, yβ© = β¨d * n * y, n * xβ© :=
by simp [ext]
theorem decompose {x y : β€} : (β¨x, yβ© : β€βd) = x + sqrtd * y :=
by simp [ext]
theorem mul_conj {x y : β€} : (β¨x, yβ© * conj β¨x, yβ© : β€βd) = x * x - d * y * y :=
by simp [ext, sub_eq_add_neg, mul_comm]
theorem conj_mul {a b : β€βd} : conj (a * b) = conj a * conj b :=
by { simp [ext], ring }
protected lemma coe_int_add (m n : β€) : (β(m + n) : β€βd) = βm + βn :=
(int.cast_ring_hom _).map_add _ _
protected lemma coe_int_sub (m n : β€) : (β(m - n) : β€βd) = βm - βn :=
(int.cast_ring_hom _).map_sub _ _
protected lemma coe_int_mul (m n : β€) : (β(m * n) : β€βd) = βm * βn :=
(int.cast_ring_hom _).map_mul _ _
protected lemma coe_int_inj {m n : β€} (h : (βm : β€βd) = βn) : m = n :=
by simpa using congr_arg re h
/-- Read `sq_le a c b d` as `a βc β€ b βd` -/
def sq_le (a c b d : β) : Prop := c*a*a β€ d*b*b
theorem sq_le_of_le {c d x y z w : β} (xz : z β€ x) (yw : y β€ w) (xy : sq_le x c y d) :
sq_le z c w d :=
le_trans (mul_le_mul (nat.mul_le_mul_left _ xz) xz (nat.zero_le _) (nat.zero_le _)) $
le_trans xy (mul_le_mul (nat.mul_le_mul_left _ yw) yw (nat.zero_le _) (nat.zero_le _))
theorem sq_le_add_mixed {c d x y z w : β} (xy : sq_le x c y d) (zw : sq_le z c w d) :
c * (x * z) β€ d * (y * w) :=
nat.mul_self_le_mul_self_iff.2 $
by simpa [mul_comm, mul_left_comm] using
mul_le_mul xy zw (nat.zero_le _) (nat.zero_le _)
theorem sq_le_add {c d x y z w : β} (xy : sq_le x c y d) (zw : sq_le z c w d) :
sq_le (x + z) c (y + w) d :=
begin
have xz := sq_le_add_mixed xy zw,
simp [sq_le, mul_assoc] at xy zw,
simp [sq_le, mul_add, mul_comm, mul_left_comm, add_le_add, *]
end
theorem sq_le_cancel {c d x y z w : β} (zw : sq_le y d x c) (h : sq_le (x + z) c (y + w) d) :
sq_le z c w d :=
begin
apply le_of_not_gt,
intro l,
refine not_le_of_gt _ h,
simp [sq_le, mul_add, mul_comm, mul_left_comm, add_assoc],
have hm := sq_le_add_mixed zw (le_of_lt l),
simp [sq_le, mul_assoc] at l zw,
exact lt_of_le_of_lt (add_le_add_right zw _)
(add_lt_add_left (add_lt_add_of_le_of_lt hm (add_lt_add_of_le_of_lt hm l)) _)
end
theorem sq_le_smul {c d x y : β} (n : β) (xy : sq_le x c y d) : sq_le (n * x) c (n * y) d :=
by simpa [sq_le, mul_left_comm, mul_assoc] using
nat.mul_le_mul_left (n * n) xy
theorem sq_le_mul {d x y z w : β} :
(sq_le x 1 y d β sq_le z 1 w d β sq_le (x * w + y * z) d (x * z + d * y * w) 1) β§
(sq_le x 1 y d β sq_le w d z 1 β sq_le (x * z + d * y * w) 1 (x * w + y * z) d) β§
(sq_le y d x 1 β sq_le z 1 w d β sq_le (x * z + d * y * w) 1 (x * w + y * z) d) β§
(sq_le y d x 1 β sq_le w d z 1 β sq_le (x * w + y * z) d (x * z + d * y * w) 1) :=
by refine β¨_, _, _, _β©; {
intros xy zw,
have := int.mul_nonneg (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le xy))
(sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le zw)),
refine int.le_of_coe_nat_le_coe_nat (le_of_sub_nonneg _),
convert this,
simp only [one_mul, int.coe_nat_add, int.coe_nat_mul],
ring }
/-- "Generalized" `nonneg`. `nonnegg c d x y` means `a βc + b βd β₯ 0`;
we are interested in the case `c = 1` but this is more symmetric -/
def nonnegg (c d : β) : β€ β β€ β Prop
| (a : β) (b : β) := true
| (a : β) -[1+ b] := sq_le (b+1) c a d
| -[1+ a] (b : β) := sq_le (a+1) d b c
| -[1+ a] -[1+ b] := false
theorem nonnegg_comm {c d : β} {x y : β€} : nonnegg c d x y = nonnegg d c y x :=
by induction x; induction y; refl
theorem nonnegg_neg_pos {c d} : Ξ {a b : β}, nonnegg c d (-a) b β sq_le a d b c
| 0 b := β¨by simp [sq_le, nat.zero_le], Ξ»a, trivialβ©
| (a+1) b := by rw β int.neg_succ_of_nat_coe; refl
theorem nonnegg_pos_neg {c d} {a b : β} : nonnegg c d a (-b) β sq_le b c a d :=
by rw nonnegg_comm; exact nonnegg_neg_pos
theorem nonnegg_cases_right {c d} {a : β} :
Ξ {b : β€}, (Ξ x : β, b = -x β sq_le x c a d) β nonnegg c d a b
| (b:nat) h := trivial
| -[1+ b] h := h (b+1) rfl
theorem nonnegg_cases_left {c d} {b : β} {a : β€} (h : Ξ x : β, a = -x β sq_le x d b c) :
nonnegg c d a b :=
cast nonnegg_comm (nonnegg_cases_right h)
section norm
def norm (n : β€βd) : β€ := n.re * n.re - d * n.im * n.im
@[simp] lemma norm_zero : norm 0 = 0 := by simp [norm]
@[simp] lemma norm_one : norm 1 = 1 := by simp [norm]
@[simp] lemma norm_int_cast (n : β€) : norm n = n * n := by simp [norm]
@[simp] lemma norm_nat_cast (n : β) : norm n = n * n := norm_int_cast n
@[simp] lemma norm_mul (n m : β€βd) : norm (n * m) = norm n * norm m :=
by { simp only [norm, mul_im, mul_re], ring }
lemma norm_eq_mul_conj (n : β€βd) : (norm n : β€βd) = n * n.conj :=
by cases n; simp [norm, conj, zsqrtd.ext, mul_comm, sub_eq_add_neg]
instance : is_monoid_hom norm :=
{ map_one := norm_one, map_mul := norm_mul }
lemma norm_nonneg (hd : d β€ 0) (n : β€βd) : 0 β€ n.norm :=
add_nonneg (mul_self_nonneg _)
(by rw [mul_assoc, neg_mul_eq_neg_mul];
exact (mul_nonneg (neg_nonneg.2 hd) (mul_self_nonneg _)))
lemma norm_eq_one_iff {x : β€βd} : x.norm.nat_abs = 1 β is_unit x :=
β¨Ξ» h, is_unit_iff_dvd_one.2 $
(le_total 0 (norm x)).cases_on
(Ξ» hx, show x β£ 1, from β¨x.conj,
by rwa [β int.coe_nat_inj', int.nat_abs_of_nonneg hx,
β @int.cast_inj (β€βd) _ _, norm_eq_mul_conj, eq_comm] at hβ©)
(Ξ» hx, show x β£ 1, from β¨- x.conj,
by rwa [β int.coe_nat_inj', int.of_nat_nat_abs_of_nonpos hx,
β @int.cast_inj (β€βd) _ _, int.cast_neg, norm_eq_mul_conj, neg_mul_eq_mul_neg,
eq_comm] at hβ©),
Ξ» h, let β¨y, hyβ© := is_unit_iff_dvd_one.1 h in begin
have := congr_arg (int.nat_abs β norm) hy,
rw [function.comp_app, function.comp_app, norm_mul, int.nat_abs_mul,
norm_one, int.nat_abs_one, eq_comm, nat.mul_eq_one_iff] at this,
exact this.1
endβ©
end norm
end
section
parameter {d : β}
/-- Nonnegativity of an element of `β€βd`. -/
def nonneg : β€βd β Prop | β¨a, bβ© := nonnegg d 1 a b
protected def le (a b : β€βd) : Prop := nonneg (b - a)
instance : has_le β€βd := β¨zsqrtd.leβ©
protected def lt (a b : β€βd) : Prop := Β¬(b β€ a)
instance : has_lt β€βd := β¨zsqrtd.ltβ©
instance decidable_nonnegg (c d a b) : decidable (nonnegg c d a b) :=
by cases a; cases b; repeat {rw int.of_nat_eq_coe}; unfold nonnegg sq_le; apply_instance
instance decidable_nonneg : Ξ (a : β€βd), decidable (nonneg a)
| β¨a, bβ© := zsqrtd.decidable_nonnegg _ _ _ _
instance decidable_le (a b : β€βd) : decidable (a β€ b) := decidable_nonneg _
theorem nonneg_cases : Ξ {a : β€βd}, nonneg a β β x y : β, a = β¨x, yβ© β¨ a = β¨x, -yβ© β¨ a = β¨-x, yβ©
| β¨(x : β), (y : β)β© h := β¨x, y, or.inl rflβ©
| β¨(x : β), -[1+ y]β© h := β¨x, y+1, or.inr $ or.inl rflβ©
| β¨-[1+ x], (y : β)β© h := β¨x+1, y, or.inr $ or.inr rflβ©
| β¨-[1+ x], -[1+ y]β© h := false.elim h
lemma nonneg_add_lem {x y z w : β} (xy : nonneg β¨x, -yβ©) (zw : nonneg β¨-z, wβ©) :
nonneg (β¨x, -yβ© + β¨-z, wβ©) :=
have nonneg β¨int.sub_nat_nat x z, int.sub_nat_nat w yβ©, from int.sub_nat_nat_elim x z
(Ξ»m n i, sq_le y d m 1 β sq_le n 1 w d β nonneg β¨i, int.sub_nat_nat w yβ©)
(Ξ»j k, int.sub_nat_nat_elim w y
(Ξ»m n i, sq_le n d (k + j) 1 β sq_le k 1 m d β nonneg β¨int.of_nat j, iβ©)
(Ξ»m n xy zw, trivial)
(Ξ»m n xy zw, sq_le_cancel zw xy))
(Ξ»j k, int.sub_nat_nat_elim w y
(Ξ»m n i, sq_le n d k 1 β sq_le (k + j + 1) 1 m d β nonneg β¨-[1+ j], iβ©)
(Ξ»m n xy zw, sq_le_cancel xy zw)
(Ξ»m n xy zw, let t := nat.le_trans zw (sq_le_of_le (nat.le_add_right n (m+1)) (le_refl _) xy) in
have k + j + 1 β€ k, from nat.mul_self_le_mul_self_iff.2 (by repeat{rw one_mul at t}; exact t),
absurd this (not_le_of_gt $ nat.succ_le_succ $ nat.le_add_right _ _))) (nonnegg_pos_neg.1 xy)
(nonnegg_neg_pos.1 zw),
show nonneg β¨_, _β©, by rw [neg_add_eq_sub];
rwa [int.sub_nat_nat_eq_coe,int.sub_nat_nat_eq_coe] at this
theorem nonneg_add {a b : β€βd} (ha : nonneg a) (hb : nonneg b) : nonneg (a + b) :=
begin
rcases nonneg_cases ha with β¨x, y, rfl|rfl|rflβ©;
rcases nonneg_cases hb with β¨z, w, rfl|rfl|rflβ©; dsimp [add, nonneg] at ha hb β’,
{ trivial },
{ refine nonnegg_cases_right (Ξ»i h, sq_le_of_le _ _ (nonnegg_pos_neg.1 hb)),
{ exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ y (by simp [add_comm, *]))) },
{ apply nat.le_add_left } },
{ refine nonnegg_cases_left (Ξ»i h, sq_le_of_le _ _ (nonnegg_neg_pos.1 hb)),
{ exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ x (by simp [add_comm, *]))) },
{ apply nat.le_add_left } },
{ refine nonnegg_cases_right (Ξ»i h, sq_le_of_le _ _ (nonnegg_pos_neg.1 ha)),
{ exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ w (by simp *))) },
{ apply nat.le_add_right } },
{ simpa [add_comm] using
nonnegg_pos_neg.2 (sq_le_add (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) },
{ exact nonneg_add_lem ha hb },
{ refine nonnegg_cases_left (Ξ»i h, sq_le_of_le _ _ (nonnegg_neg_pos.1 ha)),
{ exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ z (by simp *))) },
{ apply nat.le_add_right } },
{ rw [add_comm, add_comm βy], exact nonneg_add_lem hb ha },
{ simpa [add_comm] using
nonnegg_neg_pos.2 (sq_le_add (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) },
end
theorem le_refl (a : β€βd) : a β€ a := show nonneg (a - a), by simp
protected theorem le_trans {a b c : β€βd} (ab : a β€ b) (bc : b β€ c) : a β€ c :=
have nonneg (b - a + (c - b)), from nonneg_add ab bc,
by simpa [sub_add_sub_cancel']
theorem nonneg_iff_zero_le {a : β€βd} : nonneg a β 0 β€ a := show _ β nonneg _, by simp
theorem le_of_le_le {x y z w : β€} (xz : x β€ z) (yw : y β€ w) : (β¨x, yβ© : β€βd) β€ β¨z, wβ© :=
show nonneg β¨z - x, w - yβ©, from
match z - x, w - y, int.le.dest_sub xz, int.le.dest_sub yw with ._, ._, β¨a, rflβ©, β¨b, rflβ© :=
trivial end
theorem le_arch (a : β€βd) : βn : β, a β€ n :=
let β¨x, y, (h : a β€ β¨x, yβ©)β© := show βx y : β, nonneg (β¨x, yβ© + -a), from match -a with
| β¨int.of_nat x, int.of_nat yβ© := β¨0, 0, trivialβ©
| β¨int.of_nat x, -[1+ y]β© := β¨0, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]β©
| β¨-[1+ x], int.of_nat yβ© := β¨x+1, 0, by simp [int.neg_succ_of_nat_coe, add_assoc]β©
| β¨-[1+ x], -[1+ y]β© := β¨x+1, y+1, by simp [int.neg_succ_of_nat_coe, add_assoc]β©
end in begin
refine β¨x + d*y, zsqrtd.le_trans h _β©,
rw [β int.cast_coe_nat, β of_int_eq_coe],
change nonneg β¨(βx + d*y) - βx, 0-βyβ©,
cases y with y,
{ simp },
have h : βy, sq_le y d (d * y) 1 := Ξ» y,
by simpa [sq_le, mul_comm, mul_left_comm] using
nat.mul_le_mul_right (y * y) (nat.le_mul_self d),
rw [show (x:β€) + d * nat.succ y - x = d * nat.succ y, by simp],
exact h (y+1)
end
protected theorem nonneg_total : Ξ (a : β€βd), nonneg a β¨ nonneg (-a)
| β¨(x : β), (y : β)β© := or.inl trivial
| β¨-[1+ x], -[1+ y]β© := or.inr trivial
| β¨0, -[1+ y]β© := or.inr trivial
| β¨-[1+ x], 0β© := or.inr trivial
| β¨(x+1:β), -[1+ y]β© := nat.le_total
| β¨-[1+ x], (y+1:β)β© := nat.le_total
protected theorem le_total (a b : β€βd) : a β€ b β¨ b β€ a :=
let t := nonneg_total (b - a) in by rw [show -(b-a) = a-b, from neg_sub b a] at t; exact t
instance : preorder β€βd :=
{ le := zsqrtd.le,
le_refl := zsqrtd.le_refl,
le_trans := @zsqrtd.le_trans,
lt := zsqrtd.lt,
lt_iff_le_not_le := Ξ» a b,
(and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm }
protected theorem add_le_add_left (a b : β€βd) (ab : a β€ b) (c : β€βd) : c + a β€ c + b :=
show nonneg _, by rw add_sub_add_left_eq_sub; exact ab
protected theorem le_of_add_le_add_left (a b c : β€βd) (h : c + a β€ c + b) : a β€ b :=
by simpa using zsqrtd.add_le_add_left _ _ h (-c)
protected theorem add_lt_add_left (a b : β€βd) (h : a < b) (c) : c + a < c + b :=
Ξ» h', h (zsqrtd.le_of_add_le_add_left _ _ _ h')
theorem nonneg_smul {a : β€βd} {n : β} (ha : nonneg a) : nonneg (n * a) :=
by rw β int.cast_coe_nat; exact match a, nonneg_cases ha, ha with
| ._, β¨x, y, or.inl rflβ©, ha := by rw smul_val; trivial
| ._, β¨x, y, or.inr $ or.inl rflβ©, ha := by rw smul_val; simpa using
nonnegg_pos_neg.2 (sq_le_smul n $ nonnegg_pos_neg.1 ha)
| ._, β¨x, y, or.inr $ or.inr rflβ©, ha := by rw smul_val; simpa using
nonnegg_neg_pos.2 (sq_le_smul n $ nonnegg_neg_pos.1 ha)
end
theorem nonneg_muld {a : β€βd} (ha : nonneg a) : nonneg (sqrtd * a) :=
by refine match a, nonneg_cases ha, ha with
| ._, β¨x, y, or.inl rflβ©, ha := trivial
| ._, β¨x, y, or.inr $ or.inl rflβ©, ha := by simp; apply nonnegg_neg_pos.2;
simpa [sq_le, mul_comm, mul_left_comm] using
nat.mul_le_mul_left d (nonnegg_pos_neg.1 ha)
| ._, β¨x, y, or.inr $ or.inr rflβ©, ha := by simp; apply nonnegg_pos_neg.2;
simpa [sq_le, mul_comm, mul_left_comm] using
nat.mul_le_mul_left d (nonnegg_neg_pos.1 ha)
end
theorem nonneg_mul_lem {x y : β} {a : β€βd} (ha : nonneg a) : nonneg (β¨x, yβ© * a) :=
have (β¨x, yβ© * a : β€βd) = x * a + sqrtd * (y * a), by rw [decompose, right_distrib, mul_assoc];
refl,
by rw this; exact nonneg_add (nonneg_smul ha) (nonneg_muld $ nonneg_smul ha)
theorem nonneg_mul {a b : β€βd} (ha : nonneg a) (hb : nonneg b) : nonneg (a * b) :=
match a, b, nonneg_cases ha, nonneg_cases hb, ha, hb with
| ._, ._, β¨x, y, or.inl rflβ©, β¨z, w, or.inl rflβ©, ha, hb := trivial
| ._, ._, β¨x, y, or.inl rflβ©, β¨z, w, or.inr $ or.inr rflβ©, ha, hb := nonneg_mul_lem hb
| ._, ._, β¨x, y, or.inl rflβ©, β¨z, w, or.inr $ or.inl rflβ©, ha, hb := nonneg_mul_lem hb
| ._, ._, β¨x, y, or.inr $ or.inr rflβ©, β¨z, w, or.inl rflβ©, ha, hb :=
by rw mul_comm; exact nonneg_mul_lem ha
| ._, ._, β¨x, y, or.inr $ or.inl rflβ©, β¨z, w, or.inl rflβ©, ha, hb :=
by rw mul_comm; exact nonneg_mul_lem ha
| ._, ._, β¨x, y, or.inr $ or.inr rflβ©, β¨z, w, or.inr $ or.inr rflβ©, ha, hb :=
by rw [calc (β¨-x, yβ© * β¨-z, wβ© : β€βd) = β¨_, _β© : rfl
... = β¨x * z + d * y * w, -(x * w + y * z)β© : by simp [add_comm]]; exact
nonnegg_pos_neg.2 (sq_le_mul.left (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb))
| ._, ._, β¨x, y, or.inr $ or.inr rflβ©, β¨z, w, or.inr $ or.inl rflβ©, ha, hb :=
by rw [calc (β¨-x, yβ© * β¨z, -wβ© : β€βd) = β¨_, _β© : rfl
... = β¨-(x * z + d * y * w), x * w + y * zβ© : by simp [add_comm]]; exact
nonnegg_neg_pos.2 (sq_le_mul.right.left (nonnegg_neg_pos.1 ha) (nonnegg_pos_neg.1 hb))
| ._, ._, β¨x, y, or.inr $ or.inl rflβ©, β¨z, w, or.inr $ or.inr rflβ©, ha, hb :=
by rw [calc (β¨x, -yβ© * β¨-z, wβ© : β€βd) = β¨_, _β© : rfl
... = β¨-(x * z + d * y * w), x * w + y * zβ© : by simp [add_comm]]; exact
nonnegg_neg_pos.2 (sq_le_mul.right.right.left (nonnegg_pos_neg.1 ha) (nonnegg_neg_pos.1 hb))
| ._, ._, β¨x, y, or.inr $ or.inl rflβ©, β¨z, w, or.inr $ or.inl rflβ©, ha, hb :=
by rw [calc (β¨x, -yβ© * β¨z, -wβ© : β€βd) = β¨_, _β© : rfl
... = β¨x * z + d * y * w, -(x * w + y * z)β© : by simp [add_comm]]; exact
nonnegg_pos_neg.2 (sq_le_mul.right.right.right (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb))
end
protected theorem mul_nonneg (a b : β€βd) : 0 β€ a β 0 β€ b β 0 β€ a * b :=
by repeat {rw β nonneg_iff_zero_le}; exact nonneg_mul
theorem not_sq_le_succ (c d y) (h : 0 < c) : Β¬sq_le (y + 1) c 0 d :=
not_le_of_gt $ mul_pos (mul_pos h $ nat.succ_pos _) $ nat.succ_pos _
/-- A nonsquare is a natural number that is not equal to the square of an
integer. This is implemented as a typeclass because it's a necessary condition
for much of the Pell equation theory. -/
class nonsquare (x : β) : Prop := (ns [] : βn : β, x β n*n)
parameter [dnsq : nonsquare d]
include dnsq
theorem d_pos : 0 < d := lt_of_le_of_ne (nat.zero_le _) $ ne.symm $ (nonsquare.ns d 0)
theorem divides_sq_eq_zero {x y} (h : x * x = d * y * y) : x = 0 β§ y = 0 :=
let g := x.gcd y in or.elim g.eq_zero_or_pos
(Ξ»H, β¨nat.eq_zero_of_gcd_eq_zero_left H, nat.eq_zero_of_gcd_eq_zero_right Hβ©)
(Ξ»gpos, false.elim $
let β¨m, n, co, (hx : x = m * g), (hy : y = n * g)β© := nat.exists_coprime gpos in
begin
rw [hx, hy] at h,
have : m * m = d * (n * n) := nat.eq_of_mul_eq_mul_left (mul_pos gpos gpos)
(by simpa [mul_comm, mul_left_comm] using h),
have co2 := let co1 := co.mul_right co in co1.mul co1,
exact nonsquare.ns d m (nat.dvd_antisymm (by rw this; apply dvd_mul_right) $
co2.dvd_of_dvd_mul_right $ by simp [this])
end)
theorem divides_sq_eq_zero_z {x y : β€} (h : x * x = d * y * y) : x = 0 β§ y = 0 :=
by rw [mul_assoc, β int.nat_abs_mul_self, β int.nat_abs_mul_self, β int.coe_nat_mul, β mul_assoc]
at h;
exact let β¨h1, h2β© := divides_sq_eq_zero (int.coe_nat_inj h) in
β¨int.eq_zero_of_nat_abs_eq_zero h1, int.eq_zero_of_nat_abs_eq_zero h2β©
theorem not_divides_square (x y) : (x + 1) * (x + 1) β d * (y + 1) * (y + 1) :=
Ξ»e, by have t := (divides_sq_eq_zero e).left; contradiction
theorem nonneg_antisymm : Ξ {a : β€βd}, nonneg a β nonneg (-a) β a = 0
| β¨0, 0β© xy yx := rfl
| β¨-[1+ x], -[1+ y]β© xy yx := false.elim xy
| β¨(x+1:nat), (y+1:nat)β© xy yx := false.elim yx
| β¨-[1+ x], 0β© xy yx := absurd xy (not_sq_le_succ _ _ _ dec_trivial)
| β¨(x+1:nat), 0β© xy yx := absurd yx (not_sq_le_succ _ _ _ dec_trivial)
| β¨0, -[1+ y]β© xy yx := absurd xy (not_sq_le_succ _ _ _ d_pos)
| β¨0, (y+1:nat)β© _ yx := absurd yx (not_sq_le_succ _ _ _ d_pos)
| β¨(x+1:nat), -[1+ y]β© (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) :=
let t := le_antisymm yx xy in by rw[one_mul] at t; exact absurd t (not_divides_square _ _)
| β¨-[1+ x], (y+1:nat)β© (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) :=
let t := le_antisymm xy yx in by rw[one_mul] at t; exact absurd t (not_divides_square _ _)
theorem le_antisymm {a b : β€βd} (ab : a β€ b) (ba : b β€ a) : a = b :=
eq_of_sub_eq_zero $ nonneg_antisymm ba (by rw neg_sub; exact ab)
instance : linear_order β€βd :=
{ le_antisymm := @zsqrtd.le_antisymm,
le_total := zsqrtd.le_total,
decidable_le := zsqrtd.decidable_le,
..zsqrtd.preorder }
protected theorem eq_zero_or_eq_zero_of_mul_eq_zero : Ξ {a b : β€βd}, a * b = 0 β a = 0 β¨ b = 0
| β¨x, yβ© β¨z, wβ© h := by injection h with h1 h2; exact
have h1 : x*z = -(d*y*w), from eq_neg_of_add_eq_zero h1,
have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero h2,
have fin : x*x = d*y*y β (β¨x, yβ©:β€βd) = 0, from
Ξ»e, match x, y, divides_sq_eq_zero_z e with ._, ._, β¨rfl, rflβ© := rfl end,
if z0 : z = 0 then if w0 : w = 0 then
or.inr (match z, w, z0, w0 with ._, ._, rfl, rfl := rfl end)
else
or.inl $ fin $ mul_right_cancel' w0 $ calc
x * x * w = -y * (x * z) : by simp [h2, mul_assoc, mul_left_comm]
... = d * y * y * w : by simp [h1, mul_assoc, mul_left_comm]
else
or.inl $ fin $ mul_right_cancel' z0 $ calc
x * x * z = d * -y * (x * w) : by simp [h1, mul_assoc, mul_left_comm]
... = d * y * y * z : by simp [h2, mul_assoc, mul_left_comm]
instance : integral_domain β€βd :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := @zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero,
.. zsqrtd.comm_ring, .. zsqrtd.nontrivial }
protected theorem mul_pos (a b : β€βd) (a0 : 0 < a) (b0 : 0 < b) : 0 < a * b := Ξ»ab,
or.elim (eq_zero_or_eq_zero_of_mul_eq_zero
(le_antisymm ab (mul_nonneg _ _ (le_of_lt a0) (le_of_lt b0))))
(Ξ»e, ne_of_gt a0 e)
(Ξ»e, ne_of_gt b0 e)
instance : linear_ordered_comm_ring β€βd :=
{ add_le_add_left := @zsqrtd.add_le_add_left,
mul_pos := @zsqrtd.mul_pos,
zero_le_one := dec_trivial,
.. zsqrtd.comm_ring, .. zsqrtd.linear_order, .. zsqrtd.nontrivial }
instance : linear_ordered_semiring β€βd := by apply_instance
instance : ordered_semiring β€βd := by apply_instance
end
lemma norm_eq_zero {d : β€} (h_nonsquare : β n : β€, d β n*n) (a : β€βd) :
norm a = 0 β a = 0 :=
begin
refine β¨Ξ» ha, ext.mpr _, Ξ» h, by rw [h, norm_zero]β©,
delta norm at ha,
rw sub_eq_zero at ha,
by_cases h : 0 β€ d,
{ obtain β¨d', rflβ© := int.eq_coe_of_zero_le h,
haveI : nonsquare d' := β¨Ξ» n h, h_nonsquare n $ by exact_mod_cast hβ©,
exact divides_sq_eq_zero_z ha, },
{ push_neg at h,
suffices : a.re * a.re = 0,
{ rw eq_zero_of_mul_self_eq_zero this at ha β’,
simpa only [true_and, or_self_right, zero_re, zero_im, eq_self_iff_true,
zero_eq_mul, mul_zero, mul_eq_zero, h.ne, false_or, or_self] using ha },
apply _root_.le_antisymm _ (mul_self_nonneg _),
rw [ha, mul_assoc],
exact mul_nonpos_of_nonpos_of_nonneg h.le (mul_self_nonneg _) }
end
variables {R : Type} [comm_ring R]
@[ext] lemma hom_ext {d : β€} (f g : β€βd β+* R) (h : f sqrtd = g sqrtd) : f = g :=
begin
ext β¨x_re, x_imβ©,
simp [decompose, h],
end
/-- The unique `ring_hom` from `β€βd` to a ring `R`, constructed by replacing `βd` with the provided
root. Conversely, this associates to every mapping `β€βd β+* R` a value of `βd` in `R`. -/
@[simps]
def lift {d : β€} : {r : R // r * r = βd} β (β€βd β+* R) :=
{ to_fun := Ξ» r,
{ to_fun := Ξ» a, a.1 + a.2*(r : R),
map_zero' := by simp,
map_add' := Ξ» a b, by { simp, ring, },
map_one' := by simp,
map_mul' := Ξ» a b, by {
have : (a.re + a.im * r : R) * (b.re + b.im * r) =
a.re * b.re + (a.re * b.im + a.im * b.re) * r + a.im * b.im * (r * r) := by ring,
simp [this, r.prop],
ring, } },
inv_fun := Ξ» f, β¨f sqrtd, by rw [βf.map_mul, dmuld, ring_hom.map_int_cast]β©,
left_inv := Ξ» r, by { ext, simp },
right_inv := Ξ» f, by { ext, simp } }
/-- `lift r` is injective if `d` is non-square, and R has characteristic zero (that is, the map from
`β€` into `R` is injective). -/
lemma lift_injective [char_zero R] {d : β€} (r : {r : R // r * r = βd}) (hd : β n : β€, d β n*n) :
function.injective (lift r) :=
(lift r).injective_iff.mpr $ Ξ» a ha,
begin
have h_inj : function.injective (coe : β€ β R) := int.cast_injective,
suffices : lift r a.norm = 0,
{ simp only [coe_int_re, add_zero, lift_apply_apply, coe_int_im, int.cast_zero, zero_mul] at this,
rwa [β int.cast_zero, h_inj.eq_iff, norm_eq_zero hd] at this },
rw [norm_eq_mul_conj, ring_hom.map_mul, ha, zero_mul]
end
end zsqrtd
|
99333fbae78c79ed048d8b57275fa767d1712730 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/Init/Data/Option/Basic.lean | 21359e6dfaaf16d9f6c1ec81bcb6c1fecb79598d | [
"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,274 | 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
-/
prelude
import Init.Core
import Init.Control.Basic
import Init.Coe
namespace Option
def toMonad [Monad m] [Alternative m] : Option Ξ± β m Ξ±
| none => failure
| some a => pure a
@[inline] def toBool : Option Ξ± β Bool
| some _ => true
| none => false
@[inline] def isSome : Option Ξ± β Bool
| some _ => true
| none => false
@[inline] def isNone : Option Ξ± β Bool
| some _ => false
| none => true
@[inline] def isEqSome [BEq Ξ±] : Option Ξ± β Ξ± β Bool
| some a, b => a == b
| none, _ => false
@[inline] protected def bind : Option Ξ± β (Ξ± β Option Ξ²) β Option Ξ²
| none, _ => none
| some a, b => b a
@[inline] protected def mapM [Monad m] (f : Ξ± β m Ξ²) (o : Option Ξ±) : m (Option Ξ²) := do
if let some a := o then
return some (β f a)
else
return none
theorem map_id : (Option.map id : Option Ξ± β Option Ξ±) = id :=
funext (fun o => match o with | none => rfl | some _ => rfl)
@[always_inline, inline] protected def filter (p : Ξ± β Bool) : Option Ξ± β Option Ξ±
| some a => if p a then some a else none
| none => none
@[always_inline, inline] protected def all (p : Ξ± β Bool) : Option Ξ± β Bool
| some a => p a
| none => true
@[always_inline, inline] protected def any (p : Ξ± β Bool) : Option Ξ± β Bool
| some a => p a
| none => false
@[always_inline, macro_inline] protected def orElse : Option Ξ± β (Unit β Option Ξ±) β Option Ξ±
| some a, _ => some a
| none, b => b ()
instance : OrElse (Option Ξ±) where
orElse := Option.orElse
@[inline] protected def lt (r : Ξ± β Ξ± β Prop) : Option Ξ± β Option Ξ± β Prop
| none, some _ => True
| some x, some y => r x y
| _, _ => False
instance (r : Ξ± β Ξ± β Prop) [s : DecidableRel r] : DecidableRel (Option.lt r)
| none, some _ => isTrue trivial
| some x, some y => s x y
| some _, none => isFalse not_false
| none, none => isFalse not_false
/-- Take a pair of options and if they are both `some`, apply the given fn to produce an output.
Otherwise act like `orElse`. -/
def merge (fn : Ξ± β Ξ± β Ξ±) : Option Ξ± β Option Ξ± β Option Ξ±
| none , none => none
| some x, none => some x
| none , some y => some y
| some x, some y => some <| fn x y
end Option
deriving instance DecidableEq for Option
deriving instance BEq for Option
instance [LT Ξ±] : LT (Option Ξ±) where
lt := Option.lt (Β· < Β·)
@[always_inline]
instance : Functor Option where
map := Option.map
@[always_inline]
instance : Monad Option where
pure := Option.some
bind := Option.bind
@[always_inline]
instance : Alternative Option where
failure := Option.none
orElse := Option.orElse
def liftOption [Alternative m] : Option Ξ± β m Ξ±
| some a => pure a
| none => failure
@[always_inline, inline] protected def Option.tryCatch (x : Option Ξ±) (handle : Unit β Option Ξ±) : Option Ξ± :=
match x with
| some _ => x
| none => handle ()
instance : MonadExceptOf Unit Option where
throw := fun _ => Option.none
tryCatch := Option.tryCatch
|
3bca43aa7886ed055d2f9a302de2b79db2e45cfb | 94e33a31faa76775069b071adea97e86e218a8ee | /src/ring_theory/nullstellensatz.lean | 2384031ea8136b64ade84ab7a40bc938c3bab0a8 | [
"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 | 8,179 | lean | /-
Copyright (c) 2021 Devon Tuma. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Devon Tuma
-/
import ring_theory.jacobson
import field_theory.is_alg_closed.basic
import field_theory.mv_polynomial
import algebraic_geometry.prime_spectrum.basic
/-!
# Nullstellensatz
This file establishes a version of Hilbert's classical Nullstellensatz for `mv_polynomial`s.
The main statement of the theorem is `vanishing_ideal_zero_locus_eq_radical`.
The statement is in terms of new definitions `vanishing_ideal` and `zero_locus`.
Mathlib already has versions of these in terms of the prime spectrum of a ring,
but those are not well-suited for expressing this result.
Suggestions for better ways to state this theorem or organize things are welcome.
The machinery around `vanishing_ideal` and `zero_locus` is also minimal, I only added lemmas
directly needed in this proof, since I'm not sure if they are the right approach.
-/
open ideal
noncomputable theory
namespace mv_polynomial
open mv_polynomial
variables {k : Type*} [field k]
variables {Ο : Type*}
/-- Set of points that are zeroes of all polynomials in an ideal -/
def zero_locus (I : ideal (mv_polynomial Ο k)) : set (Ο β k) :=
{x : Ο β k | β p β I, eval x p = 0}
@[simp] lemma mem_zero_locus_iff {I : ideal (mv_polynomial Ο k)} {x : Ο β k} :
x β zero_locus I β β p β I, eval x p = 0 := iff.rfl
lemma zero_locus_anti_mono {I J : ideal (mv_polynomial Ο k)} (h : I β€ J) :
zero_locus J β€ zero_locus I :=
Ξ» x hx p hp, hx p $ h hp
lemma zero_locus_bot : zero_locus (β₯ : ideal (mv_polynomial Ο k)) = β€ :=
eq_top_iff.2 (Ξ» x hx p hp, trans (congr_arg (eval x) (mem_bot.1 hp)) (eval x).map_zero)
lemma zero_locus_top : zero_locus (β€ : ideal (mv_polynomial Ο k)) = β₯ :=
eq_bot_iff.2 $ Ξ» x hx, one_ne_zero ((eval x).map_one βΈ (hx 1 submodule.mem_top) : (1 : k) = 0)
/-- Ideal of polynomials with common zeroes at all elements of a set -/
def vanishing_ideal (V : set (Ο β k)) : ideal (mv_polynomial Ο k) :=
{ carrier := {p | β x β V, eval x p = 0},
zero_mem' := Ξ» x hx, ring_hom.map_zero _,
add_mem' := Ξ» p q hp hq x hx, by simp only [hq x hx, hp x hx, add_zero, ring_hom.map_add],
smul_mem' := Ξ» p q hq x hx,
by simp only [hq x hx, algebra.id.smul_eq_mul, mul_zero, ring_hom.map_mul] }
@[simp] lemma mem_vanishing_ideal_iff {V : set (Ο β k)} {p : mv_polynomial Ο k} :
p β vanishing_ideal V β β x β V, eval x p = 0 := iff.rfl
lemma vanishing_ideal_anti_mono {A B : set (Ο β k)} (h : A β€ B) :
vanishing_ideal B β€ vanishing_ideal A :=
Ξ» p hp x hx, hp x $ h hx
lemma vanishing_ideal_empty : vanishing_ideal (β
: set (Ο β k)) = β€ :=
le_antisymm le_top (Ξ» p hp x hx, absurd hx (set.not_mem_empty x))
lemma le_vanishing_ideal_zero_locus (I : ideal (mv_polynomial Ο k)) :
I β€ vanishing_ideal (zero_locus I) :=
Ξ» p hp x hx, hx p hp
lemma zero_locus_vanishing_ideal_le (V : set (Ο β k)) :
V β€ zero_locus (vanishing_ideal V) :=
Ξ» V hV p hp, hp V hV
theorem zero_locus_vanishing_ideal_galois_connection :
@galois_connection (ideal (mv_polynomial Ο k)) (set (Ο β k))α΅α΅ _ _
zero_locus vanishing_ideal :=
Ξ» I V, β¨Ξ» h, le_trans (le_vanishing_ideal_zero_locus I) (vanishing_ideal_anti_mono h),
Ξ» h, le_trans (zero_locus_anti_mono h) (zero_locus_vanishing_ideal_le V)β©
lemma mem_vanishing_ideal_singleton_iff (x : Ο β k) (p : mv_polynomial Ο k) :
p β (vanishing_ideal {x} : ideal (mv_polynomial Ο k)) β (eval x p = 0) :=
β¨Ξ» h, h x rfl, Ξ» hpx y hy, hy.symm βΈ hpxβ©
instance vanishing_ideal_singleton_is_maximal {x : Ο β k} :
(vanishing_ideal {x} : ideal (mv_polynomial Ο k)).is_maximal :=
begin
have : mv_polynomial Ο k β§Έ vanishing_ideal {x} β+* k := ring_equiv.of_bijective
(ideal.quotient.lift _ (eval x) (Ξ» p h, (mem_vanishing_ideal_singleton_iff x p).mp h))
begin
refine β¨(injective_iff_map_eq_zero _).mpr (Ξ» p hp, _), Ξ» z,
β¨(ideal.quotient.mk (vanishing_ideal {x} : ideal (mv_polynomial Ο k))) (C z), by simpβ©β©,
obtain β¨q, rflβ© := quotient.mk_surjective p,
rwa [ideal.quotient.lift_mk, β mem_vanishing_ideal_singleton_iff,
β quotient.eq_zero_iff_mem] at hp,
end,
rw [β bot_quotient_is_maximal_iff, ring_equiv.bot_maximal_iff this],
exact bot_is_maximal,
end
lemma radical_le_vanishing_ideal_zero_locus (I : ideal (mv_polynomial Ο k)) :
I.radical β€ vanishing_ideal (zero_locus I) :=
begin
intros p hp x hx,
rw β mem_vanishing_ideal_singleton_iff,
rw radical_eq_Inf at hp,
refine (mem_Inf.mp hp) β¨le_trans (le_vanishing_ideal_zero_locus I)
(vanishing_ideal_anti_mono (Ξ» y hy, hy.symm βΈ hx)), is_maximal.is_prime' _β©,
end
/-- The point in the prime spectrum assosiated to a given point -/
def point_to_point (x : Ο β k) : prime_spectrum (mv_polynomial Ο k) :=
β¨(vanishing_ideal {x} : ideal (mv_polynomial Ο k)), by apply_instanceβ©
@[simp] lemma vanishing_ideal_point_to_point (V : set (Ο β k)) :
prime_spectrum.vanishing_ideal (point_to_point '' V) = mv_polynomial.vanishing_ideal V :=
le_antisymm
(Ξ» p hp x hx, (((prime_spectrum.mem_vanishing_ideal _ _).1 hp)
β¨vanishing_ideal {x}, by apply_instanceβ© β¨x, β¨hx, rflβ©β©) x rfl)
(Ξ» p hp, (prime_spectrum.mem_vanishing_ideal _ _).2
(Ξ» I hI, let β¨x, hxβ© := hI in hx.2 βΈ Ξ» x' hx', (set.mem_singleton_iff.1 hx').symm βΈ hp x hx.1))
lemma point_to_point_zero_locus_le (I : ideal (mv_polynomial Ο k)) :
point_to_point '' (mv_polynomial.zero_locus I) β€ prime_spectrum.zero_locus βI :=
Ξ» J hJ, let β¨x, hxβ© := hJ in (le_trans (le_vanishing_ideal_zero_locus I)
(hx.2 βΈ vanishing_ideal_anti_mono (set.singleton_subset_iff.2 hx.1)) : I β€ J.as_ideal)
variables [is_alg_closed k] [fintype Ο]
lemma is_maximal_iff_eq_vanishing_ideal_singleton (I : ideal (mv_polynomial Ο k)) :
I.is_maximal β β (x : Ο β k), I = vanishing_ideal {x} :=
begin
refine β¨Ξ» hI, _, Ξ» h, let β¨x, hxβ© := h in
hx.symm βΈ (mv_polynomial.vanishing_ideal_singleton_is_maximal)β©,
letI : I.is_maximal := hI,
letI : field (mv_polynomial Ο k β§Έ I) := quotient.field I,
let Ο : k β+* mv_polynomial Ο k β§Έ I := (ideal.quotient.mk I).comp C,
have hΟ : function.bijective Ο := β¨quotient_mk_comp_C_injective _ _ I hI.ne_top,
is_alg_closed.algebra_map_surjective_of_is_integral' Ο
(mv_polynomial.comp_C_integral_of_surjective_of_jacobson _ quotient.mk_surjective)β©,
obtain β¨Ο, hΟβ© := function.surjective.has_right_inverse hΟ.2,
let x : Ο β k := Ξ» s, Ο ((ideal.quotient.mk I) (X s)),
have hx : β s : Ο, Ο (x s) = (ideal.quotient.mk I) (X s) := Ξ» s, hΟ ((ideal.quotient.mk I) (X s)),
refine β¨x, (is_maximal.eq_of_le (by apply_instance) hI.ne_top _).symmβ©,
intros p hp,
rw [β quotient.eq_zero_iff_mem, map_mv_polynomial_eq_evalβ (ideal.quotient.mk I) p, evalβ_eq'],
rw [mem_vanishing_ideal_singleton_iff, eval_eq'] at hp,
simpa only [Ο.map_sum, Ο.map_mul, Ο.map_prod, Ο.map_pow, Ο.map_zero, hx] using congr_arg Ο hp,
end
/-- Main statement of the Nullstellensatz -/
@[simp] theorem vanishing_ideal_zero_locus_eq_radical (I : ideal (mv_polynomial Ο k)) :
vanishing_ideal (zero_locus I) = I.radical :=
begin
rw I.radical_eq_jacobson,
refine le_antisymm (le_Inf _) (Ξ» p hp x hx, _),
{ rintros J β¨hJI, hJβ©,
obtain β¨x, hxβ© := (is_maximal_iff_eq_vanishing_ideal_singleton J).1 hJ,
refine hx.symm βΈ vanishing_ideal_anti_mono (Ξ» y hy p hp, _),
rw [β mem_vanishing_ideal_singleton_iff, set.mem_singleton_iff.1 hy, β hx],
refine hJI hp },
{ rw β mem_vanishing_ideal_singleton_iff x p,
refine (mem_Inf.mp hp) β¨le_trans (le_vanishing_ideal_zero_locus I)
(vanishing_ideal_anti_mono (Ξ» y hy, hy.symm βΈ hx)),
mv_polynomial.vanishing_ideal_singleton_is_maximalβ© },
end
@[simp] lemma is_prime.vanishing_ideal_zero_locus (P : ideal (mv_polynomial Ο k)) [h : P.is_prime] :
vanishing_ideal (zero_locus P) = P :=
trans (vanishing_ideal_zero_locus_eq_radical P) h.radical
end mv_polynomial
|
87258492f999bf41f27ae557fc27948c2867d736 | 82e44445c70db0f03e30d7be725775f122d72f3e | /src/analysis/calculus/local_extr.lean | 203a1ac4ccf605bd6635a6ca98dd038b72e1dfd8 | [
"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 | 18,183 | lean | /-
Copyright (c) 2019 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import analysis.calculus.deriv
import topology.algebra.ordered.extend_from
import topology.algebra.polynomial
import topology.local_extr
/-!
# Local extrema of smooth functions
## Main definitions
In a real normed space `E` we define `pos_tangent_cone_at (s : set E) (x : E)`.
This would be the same as `tangent_cone_at ββ₯0 s x` if we had a theory of normed semifields.
This set is used in the proof of Fermat's Theorem (see below), and can be used to formalize
[Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) and/or
[KarushβKuhnβTucker conditions](https://en.wikipedia.org/wiki/KarushβKuhnβTucker_conditions).
## Main statements
For each theorem name listed below,
we also prove similar theorems for `min`, `extr` (if applicable)`,
and `(f)deriv` instead of `has_fderiv`.
* `is_local_max_on.has_fderiv_within_at_nonpos` : `f' y β€ 0` whenever `a` is a local maximum
of `f` on `s`, `f` has derivative `f'` at `a` within `s`, and `y` belongs to the positive tangent
cone of `s` at `a`.
* `is_local_max_on.has_fderiv_within_at_eq_zero` : In the settings of the previous theorem, if both
`y` and `-y` belong to the positive tangent cone, then `f' y = 0`.
* `is_local_max.has_fderiv_at_eq_zero` :
[Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)),
the derivative of a differentiable function at a local extremum point equals zero.
* `exists_has_deriv_at_eq_zero` :
[Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem): given a function `f` continuous
on `[a, b]` and differentiable on `(a, b)`, there exists `c β (a, b)` such that `f' c = 0`.
## Implementation notes
For each mathematical fact we prove several versions of its formalization:
* for maxima and minima;
* using `has_fderiv*`/`has_deriv*` or `fderiv*`/`deriv*`.
For the `fderiv*`/`deriv*` versions we omit the differentiability condition whenever it is possible
due to the fact that `fderiv` and `deriv` are defined to be zero for non-differentiable functions.
## References
* [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points));
* [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem);
* [Tangent cone](https://en.wikipedia.org/wiki/Tangent_cone);
## Tags
local extremum, Fermat's Theorem, Rolle's Theorem
-/
universes u v
open filter set
open_locale topological_space classical
section module
variables {E : Type u} [normed_group E] [normed_space β E] {f : E β β} {a : E}
{f' : E βL[β] β}
/-- "Positive" tangent cone to `s` at `x`; the only difference from `tangent_cone_at`
is that we require `c n β β` instead of `β₯c nβ₯ β β`. One can think about `pos_tangent_cone_at`
as `tangent_cone_at nnreal` but we have no theory of normed semifields yet. -/
def pos_tangent_cone_at (s : set E) (x : E) : set E :=
{y : E | β(c : β β β) (d : β β E), (βαΆ n in at_top, x + d n β s) β§
(tendsto c at_top at_top) β§ (tendsto (Ξ»n, c n β’ d n) at_top (π y))}
lemma pos_tangent_cone_at_mono : monotone (Ξ» s, pos_tangent_cone_at s a) :=
begin
rintros s t hst y β¨c, d, hd, hc, hcdβ©,
exact β¨c, d, mem_sets_of_superset hd $ Ξ» h hn, hst hn, hc, hcdβ©
end
lemma mem_pos_tangent_cone_at_of_segment_subset {s : set E} {x y : E} (h : segment x y β s) :
y - x β pos_tangent_cone_at s x :=
begin
let c := Ξ»n:β, (2:β)^n,
let d := Ξ»n:β, (c n)β»ΒΉ β’ (y-x),
refine β¨c, d, filter.univ_mem_sets' (Ξ»n, h _),
tendsto_pow_at_top_at_top_of_one_lt one_lt_two, _β©,
show x + d n β segment x y,
{ rw segment_eq_image',
refine β¨(c n)β»ΒΉ, β¨_, _β©, rflβ©,
exacts [inv_nonneg.2 (pow_nonneg zero_le_two _),
inv_le_one (one_le_pow_of_one_le one_le_two _)] },
show tendsto (Ξ» n, c n β’ d n) at_top (π (y - x)),
{ convert tendsto_const_nhds, ext n,
simp only [d, smul_smul],
rw [mul_inv_cancel, one_smul],
exact pow_ne_zero _ two_ne_zero }
end
lemma mem_pos_tangent_cone_at_of_segment_subset' {s : set E} {x y : E} (h : segment x (x + y) β s) :
y β pos_tangent_cone_at s x :=
by simpa only [add_sub_cancel'] using mem_pos_tangent_cone_at_of_segment_subset h
lemma pos_tangent_cone_at_univ : pos_tangent_cone_at univ a = univ :=
eq_univ_of_forall $ Ξ» x, mem_pos_tangent_cone_at_of_segment_subset' (subset_univ _)
/-- If `f` has a local max on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and
`y` belongs to the positive tangent cone of `s` at `a`, then `f' y β€ 0`. -/
lemma is_local_max_on.has_fderiv_within_at_nonpos {s : set E} (h : is_local_max_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y β pos_tangent_cone_at s a) :
f' y β€ 0 :=
begin
rcases hy with β¨c, d, hd, hc, hcdβ©,
have hc' : tendsto (Ξ» n, β₯c nβ₯) at_top at_top,
from tendsto_at_top_mono (Ξ» n, le_abs_self _) hc,
refine le_of_tendsto (hf.lim at_top hd hc' hcd) _,
replace hd : tendsto (Ξ» n, a + d n) at_top (π[s] (a + 0)),
from tendsto_inf.2 β¨tendsto_const_nhds.add (tangent_cone_at.lim_zero _ hc' hcd),
by rwa tendsto_principalβ©,
rw [add_zero] at hd,
replace h : βαΆ n in at_top, f (a + d n) β€ f a, from mem_map.1 (hd h),
replace hc : βαΆ n in at_top, 0 β€ c n, from mem_map.1 (hc (mem_at_top (0:β))),
filter_upwards [h, hc],
simp only [smul_eq_mul, mem_preimage, subset_def],
assume n hnf hn,
exact mul_nonpos_of_nonneg_of_nonpos hn (sub_nonpos.2 hnf)
end
/-- If `f` has a local max on `s` at `a` and `y` belongs to the positive tangent cone
of `s` at `a`, then `f' y β€ 0`. -/
lemma is_local_max_on.fderiv_within_nonpos {s : set E} (h : is_local_max_on f s a)
{y} (hy : y β pos_tangent_cone_at s a) :
(fderiv_within β f s a : E β β) y β€ 0 :=
if hf : differentiable_within_at β f s a
then h.has_fderiv_within_at_nonpos hf.has_fderiv_within_at hy
else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl }
/-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and
both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y β€ 0`. -/
lemma is_local_max_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_max_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y β pos_tangent_cone_at s a)
(hy' : -y β pos_tangent_cone_at s a) :
f' y = 0 :=
le_antisymm (h.has_fderiv_within_at_nonpos hf hy) $
by simpa using h.has_fderiv_within_at_nonpos hf hy'
/-- If `f` has a local max on `s` at `a` and both `y` and `-y` belong to the positive tangent cone
of `s` at `a`, then `f' y = 0`. -/
lemma is_local_max_on.fderiv_within_eq_zero {s : set E} (h : is_local_max_on f s a)
{y} (hy : y β pos_tangent_cone_at s a) (hy' : -y β pos_tangent_cone_at s a) :
(fderiv_within β f s a : E β β) y = 0 :=
if hf : differentiable_within_at β f s a
then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy'
else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl }
/-- If `f` has a local min on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and
`y` belongs to the positive tangent cone of `s` at `a`, then `0 β€ f' y`. -/
lemma is_local_min_on.has_fderiv_within_at_nonneg {s : set E} (h : is_local_min_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y β pos_tangent_cone_at s a) :
0 β€ f' y :=
by simpa using h.neg.has_fderiv_within_at_nonpos hf.neg hy
/-- If `f` has a local min on `s` at `a` and `y` belongs to the positive tangent cone
of `s` at `a`, then `0 β€ f' y`. -/
lemma is_local_min_on.fderiv_within_nonneg {s : set E} (h : is_local_min_on f s a)
{y} (hy : y β pos_tangent_cone_at s a) :
(0:β) β€ (fderiv_within β f s a : E β β) y :=
if hf : differentiable_within_at β f s a
then h.has_fderiv_within_at_nonneg hf.has_fderiv_within_at hy
else by { rw [fderiv_within_zero_of_not_differentiable_within_at hf], refl }
/-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and
both `y` and `-y` belong to the positive tangent cone of `s` at `a`, then `f' y β€ 0`. -/
lemma is_local_min_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_min_on f s a)
(hf : has_fderiv_within_at f f' s a) {y} (hy : y β pos_tangent_cone_at s a)
(hy' : -y β pos_tangent_cone_at s a) :
f' y = 0 :=
by simpa using h.neg.has_fderiv_within_at_eq_zero hf.neg hy hy'
/-- If `f` has a local min on `s` at `a` and both `y` and `-y` belong to the positive tangent cone
of `s` at `a`, then `f' y = 0`. -/
lemma is_local_min_on.fderiv_within_eq_zero {s : set E} (h : is_local_min_on f s a)
{y} (hy : y β pos_tangent_cone_at s a) (hy' : -y β pos_tangent_cone_at s a) :
(fderiv_within β f s a : E β β) y = 0 :=
if hf : differentiable_within_at β f s a
then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy'
else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl }
/-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.has_fderiv_at_eq_zero (h : is_local_min f a) (hf : has_fderiv_at f f' a) :
f' = 0 :=
begin
ext y,
apply (h.on univ).has_fderiv_within_at_eq_zero hf.has_fderiv_within_at;
rw pos_tangent_cone_at_univ; apply mem_univ
end
/-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.fderiv_eq_zero (h : is_local_min f a) : fderiv β f a = 0 :=
if hf : differentiable_at β f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at
else fderiv_zero_of_not_differentiable_at hf
/-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.has_fderiv_at_eq_zero (h : is_local_max f a) (hf : has_fderiv_at f f' a) :
f' = 0 :=
neg_eq_zero.1 $ h.neg.has_fderiv_at_eq_zero hf.neg
/-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.fderiv_eq_zero (h : is_local_max f a) : fderiv β f a = 0 :=
if hf : differentiable_at β f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at
else fderiv_zero_of_not_differentiable_at hf
/-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.has_fderiv_at_eq_zero (h : is_local_extr f a) :
has_fderiv_at f f' a β f' = 0 :=
h.elim is_local_min.has_fderiv_at_eq_zero is_local_max.has_fderiv_at_eq_zero
/-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.fderiv_eq_zero (h : is_local_extr f a) : fderiv β f a = 0 :=
h.elim is_local_min.fderiv_eq_zero is_local_max.fderiv_eq_zero
end module
section real
variables {f : β β β} {f' : β} {a b : β}
/-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.has_deriv_at_eq_zero (h : is_local_min f a) (hf : has_deriv_at f f' a) :
f' = 0 :=
by simpa using continuous_linear_map.ext_iff.1
(h.has_fderiv_at_eq_zero (has_deriv_at_iff_has_fderiv_at.1 hf)) 1
/-- **Fermat's Theorem**: the derivative of a function at a local minimum equals zero. -/
lemma is_local_min.deriv_eq_zero (h : is_local_min f a) : deriv f a = 0 :=
if hf : differentiable_at β f a then h.has_deriv_at_eq_zero hf.has_deriv_at
else deriv_zero_of_not_differentiable_at hf
/-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.has_deriv_at_eq_zero (h : is_local_max f a) (hf : has_deriv_at f f' a) :
f' = 0 :=
neg_eq_zero.1 $ h.neg.has_deriv_at_eq_zero hf.neg
/-- **Fermat's Theorem**: the derivative of a function at a local maximum equals zero. -/
lemma is_local_max.deriv_eq_zero (h : is_local_max f a) : deriv f a = 0 :=
if hf : differentiable_at β f a then h.has_deriv_at_eq_zero hf.has_deriv_at
else deriv_zero_of_not_differentiable_at hf
/-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.has_deriv_at_eq_zero (h : is_local_extr f a) :
has_deriv_at f f' a β f' = 0 :=
h.elim is_local_min.has_deriv_at_eq_zero is_local_max.has_deriv_at_eq_zero
/-- **Fermat's Theorem**: the derivative of a function at a local extremum equals zero. -/
lemma is_local_extr.deriv_eq_zero (h : is_local_extr f a) : deriv f a = 0 :=
h.elim is_local_min.deriv_eq_zero is_local_max.deriv_eq_zero
end real
section Rolle
variables (f f' : β β β) {a b : β}
/-- A continuous function on a closed interval with `f a = f b` takes either its maximum
or its minimum value at a point in the interior of the interval. -/
lemma exists_Ioo_extr_on_Icc (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) :
β c β Ioo a b, is_extr_on f (Icc a b) c :=
begin
have ne : (Icc a b).nonempty, from nonempty_Icc.2 (le_of_lt hab),
-- Consider absolute min and max points
obtain β¨c, cmem, cleβ© : β c β Icc a b, β x β Icc a b, f c β€ f x,
from is_compact_Icc.exists_forall_le ne hfc,
obtain β¨C, Cmem, Cgeβ© : β C β Icc a b, β x β Icc a b, f x β€ f C,
from is_compact_Icc.exists_forall_ge ne hfc,
by_cases hc : f c = f a,
{ by_cases hC : f C = f a,
{ have : β x β Icc a b, f x = f a,
from Ξ» x hx, le_antisymm (hC βΈ Cge x hx) (hc βΈ cle x hx),
-- `f` is a constant, so we can take any point in `Ioo a b`
rcases exists_between hab with β¨c', hc'β©,
refine β¨c', hc', or.inl _β©,
assume x hx,
rw [mem_set_of_eq, this x hx, β hC],
exact Cge c' β¨le_of_lt hc'.1, le_of_lt hc'.2β© },
{ refine β¨C, β¨lt_of_le_of_ne Cmem.1 $ mt _ hC, lt_of_le_of_ne Cmem.2 $ mt _ hCβ©, or.inr Cgeβ©,
exacts [Ξ» h, by rw h, Ξ» h, by rw [h, hfI]] } },
{ refine β¨c, β¨lt_of_le_of_ne cmem.1 $ mt _ hc, lt_of_le_of_ne cmem.2 $ mt _ hcβ©, or.inl cleβ©,
exacts [Ξ» h, by rw h, Ξ» h, by rw [h, hfI]] }
end
/-- A continuous function on a closed interval with `f a = f b` has a local extremum at some
point of the corresponding open interval. -/
lemma exists_local_extr_Ioo (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) :
β c β Ioo a b, is_local_extr f c :=
let β¨c, cmem, hcβ© := exists_Ioo_extr_on_Icc f hab hfc hfI
in β¨c, cmem, hc.is_local_extr $ Icc_mem_nhds cmem.1 cmem.2β©
/-- **Rolle's Theorem** `has_deriv_at` version -/
lemma exists_has_deriv_at_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b)
(hff' : β x β Ioo a b, has_deriv_at f (f' x) x) :
β c β Ioo a b, f' c = 0 :=
let β¨c, cmem, hcβ© := exists_local_extr_Ioo f hab hfc hfI in
β¨c, cmem, hc.has_deriv_at_eq_zero $ hff' c cmemβ©
/-- **Rolle's Theorem** `deriv` version -/
lemma exists_deriv_eq_zero (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) :
β c β Ioo a b, deriv f c = 0 :=
let β¨c, cmem, hcβ© := exists_local_extr_Ioo f hab hfc hfI in
β¨c, cmem, hc.deriv_eq_zeroβ©
variables {f f'} {l : β}
/-- **Rolle's Theorem**, a version for a function on an open interval: if `f` has derivative `f'`
on `(a, b)` and has the same limit `l` at `π[Ioi a] a` and `π[Iio b] b`, then `f' c = 0`
for some `c β (a, b)`. -/
lemma exists_has_deriv_at_eq_zero' (hab : a < b)
(hfa : tendsto f (π[Ioi a] a) (π l)) (hfb : tendsto f (π[Iio b] b) (π l))
(hff' : β x β Ioo a b, has_deriv_at f (f' x) x) :
β c β Ioo a b, f' c = 0 :=
begin
have : continuous_on f (Ioo a b) := Ξ» x hx, (hff' x hx).continuous_at.continuous_within_at,
have hcont := continuous_on_Icc_extend_from_Ioo hab this hfa hfb,
obtain β¨c, hc, hcextrβ© : β c β Ioo a b, is_local_extr (extend_from (Ioo a b) f) c,
{ apply exists_local_extr_Ioo _ hab hcont,
rw eq_lim_at_right_extend_from_Ioo hab hfb,
exact eq_lim_at_left_extend_from_Ioo hab hfa },
use [c, hc],
apply (hcextr.congr _).has_deriv_at_eq_zero (hff' c hc),
rw eventually_eq_iff_exists_mem,
exact β¨Ioo a b, Ioo_mem_nhds hc.1 hc.2, extend_from_extends thisβ©
end
/-- **Rolle's Theorem**, a version for a function on an open interval: if `f` has the same limit
`l` at `π[Ioi a] a` and `π[Iio b] b`, then `deriv f c = 0` for some `c β (a, b)`. This version
does not require differentiability of `f` because we define `deriv f c = 0` whenever `f` is not
differentiable at `c`. -/
lemma exists_deriv_eq_zero' (hab : a < b)
(hfa : tendsto f (π[Ioi a] a) (π l)) (hfb : tendsto f (π[Iio b] b) (π l)) :
β c β Ioo a b, deriv f c = 0 :=
classical.by_cases
(assume h : β x β Ioo a b, differentiable_at β f x,
show β c β Ioo a b, deriv f c = 0,
from exists_has_deriv_at_eq_zero' hab hfa hfb (Ξ» x hx, (h x hx).has_deriv_at))
(assume h : Β¬β x β Ioo a b, differentiable_at β f x,
have h : β x, x β Ioo a b β§ Β¬differentiable_at β f x, by { push_neg at h, exact h },
let β¨c, hc, hcdiffβ© := h in β¨c, hc, deriv_zero_of_not_differentiable_at hcdiffβ©)
end Rolle
namespace polynomial
lemma card_root_set_le_derivative {F : Type*} [field F] [algebra F β] (p : polynomial F) :
fintype.card (p.root_set β) β€ fintype.card (p.derivative.root_set β) + 1 :=
begin
haveI : char_zero F :=
(ring_hom.char_zero_iff (algebra_map F β).injective).mpr (by apply_instance),
by_cases hp : p = 0,
{ simp_rw [hp, derivative_zero, root_set_zero, set.empty_card', zero_le_one] },
by_cases hp' : p.derivative = 0,
{ rw eq_C_of_nat_degree_eq_zero (nat_degree_eq_zero_of_derivative_eq_zero hp'),
simp_rw [root_set_C, set.empty_card', zero_le] },
simp_rw [root_set_def, finset.coe_sort_coe, fintype.card_coe],
refine finset.card_le_of_interleaved (Ξ» x y hx hy hxy, _),
rw [βfinset.mem_coe, βroot_set_def, mem_root_set hp] at hx hy,
obtain β¨z, hz1, hz2β© := exists_deriv_eq_zero (Ξ» x : β, aeval x p) hxy
p.continuous_aeval.continuous_on (hx.trans hy.symm),
refine β¨z, _, hz1β©,
rw [βfinset.mem_coe, βroot_set_def, mem_root_set hp', βhz2],
simp_rw [aeval_def, βeval_map, polynomial.deriv, derivative_map],
end
end polynomial
|
83d970fd3e5759df2bc63a389fc02d4f8f443677 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/unique_factorization_domain.lean | a14c36192d98af5f31e5eb23c3782f27d3a27ea2 | [
"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 | 67,990 | lean | /-
Copyright (c) 2018 Johannes HΓΆlzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes HΓΆlzl, Jens Wagemaker, Aaron Anderson
-/
import algebra.big_operators.associated
import algebra.gcd_monoid.basic
import data.finsupp.multiset
import ring_theory.noetherian
import ring_theory.multiplicity
/-!
# Unique factorization
## Main Definitions
* `wf_dvd_monoid` holds for `monoid`s for which a strict divisibility relation is
well-founded.
* `unique_factorization_monoid` holds for `wf_dvd_monoid`s where
`irreducible` is equivalent to `prime`
## To do
* set up the complete lattice structure on `factor_set`.
-/
variables {Ξ± : Type*}
local infix ` ~α΅€ ` : 50 := associated
/-- Well-foundedness of the strict version of |, which is equivalent to the descending chain
condition on divisibility and to the ascending chain condition on
principal ideals in an integral domain.
-/
class wf_dvd_monoid (Ξ± : Type*) [comm_monoid_with_zero Ξ±] : Prop :=
(well_founded_dvd_not_unit : well_founded (@dvd_not_unit Ξ± _))
export wf_dvd_monoid (well_founded_dvd_not_unit)
@[priority 100] -- see Note [lower instance priority]
instance is_noetherian_ring.wf_dvd_monoid [comm_ring Ξ±] [is_domain Ξ±] [is_noetherian_ring Ξ±] :
wf_dvd_monoid Ξ± :=
β¨by { convert inv_image.wf (Ξ» a, ideal.span ({a} : set Ξ±)) (well_founded_submodule_gt _ _),
ext,
exact ideal.span_singleton_lt_span_singleton.symm }β©
namespace wf_dvd_monoid
variables [comm_monoid_with_zero Ξ±]
open associates nat
theorem of_wf_dvd_monoid_associates (h : wf_dvd_monoid (associates Ξ±)): wf_dvd_monoid Ξ± :=
β¨begin
haveI := h,
refine (surjective.well_founded_iff mk_surjective _).2 well_founded_dvd_not_unit,
intros, rw mk_dvd_not_unit_mk_iff
endβ©
variables [wf_dvd_monoid Ξ±]
instance wf_dvd_monoid_associates : wf_dvd_monoid (associates Ξ±) :=
β¨begin
refine (surjective.well_founded_iff mk_surjective _).1 well_founded_dvd_not_unit,
intros, rw mk_dvd_not_unit_mk_iff
endβ©
theorem well_founded_associates : well_founded ((<) : associates Ξ± β associates Ξ± β Prop) :=
subrelation.wf (Ξ» x y, dvd_not_unit_of_lt) well_founded_dvd_not_unit
local attribute [elab_as_eliminator] well_founded.fix
lemma exists_irreducible_factor {a : Ξ±} (ha : Β¬ is_unit a) (ha0 : a β 0) :
β i, irreducible i β§ i β£ a :=
(irreducible_or_factor a ha).elim (Ξ» hai, β¨a, hai, dvd_rflβ©)
(well_founded.fix
well_founded_dvd_not_unit
(Ξ» a ih ha ha0 β¨x, y, hx, hy, hxyβ©,
have hx0 : x β 0, from Ξ» hx0, ha0 (by rw [β hxy, hx0, zero_mul]),
(irreducible_or_factor x hx).elim
(Ξ» hxi, β¨x, hxi, hxy βΈ by simpβ©)
(Ξ» hxf, let β¨i, hiβ© := ih x β¨hx0, y, hy, hxy.symmβ© hx hx0 hxf in
β¨i, hi.1, hi.2.trans (hxy βΈ by simp)β©)) a ha ha0)
@[elab_as_eliminator] lemma induction_on_irreducible {P : Ξ± β Prop} (a : Ξ±)
(h0 : P 0) (hu : β u : Ξ±, is_unit u β P u)
(hi : β a i : Ξ±, a β 0 β irreducible i β P a β P (i * a)) :
P a :=
by haveI := classical.dec; exact
well_founded.fix well_founded_dvd_not_unit
(Ξ» a ih, if ha0 : a = 0 then ha0.symm βΈ h0
else if hau : is_unit a then hu a hau
else let β¨i, hii, β¨b, hbβ©β© := exists_irreducible_factor hau ha0 in
have hb0 : b β 0, from Ξ» hb0, by simp * at *,
hb.symm βΈ hi _ _ hb0 hii (ih _ β¨hb0, i,
hii.1, by rw [hb, mul_comm]β©))
a
lemma exists_factors (a : Ξ±) : a β 0 β
β f : multiset Ξ±, (β b β f, irreducible b) β§ associated f.prod a :=
induction_on_irreducible a
(Ξ» h, (h rfl).elim)
(Ξ» u hu _, β¨0, β¨by simp [hu], associated.symm (by simp [hu, associated_one_iff_is_unit])β©β©)
(Ξ» a i ha0 hii ih hia0,
let β¨s, hsβ© := ih ha0 in
β¨i ::β s, β¨by clear _let_match;
{ intros b H, cases (multiset.mem_cons.mp H), { convert hii }, { exact hs.1 b h } },
by { rw multiset.prod_cons,
exact hs.2.mul_left _ }β©β©)
lemma not_unit_iff_exists_factors_eq (a : Ξ±) (hn0 : a β 0) :
Β¬ is_unit a β β f : multiset Ξ±, (β b β f, irreducible b) β§ f.prod = a β§ f β β
:=
β¨Ξ» hnu, begin
obtain β¨f, hi, u, rflβ© := exists_factors a hn0,
obtain β¨b, hβ© := multiset.exists_mem_of_ne_zero (Ξ» h : f = 0, hnu $ by simp [h]),
classical, refine β¨(f.erase b).cons (b * u), Ξ» a ha, _, _, multiset.cons_ne_zeroβ©,
{ obtain (rfl|ha) := multiset.mem_cons.1 ha,
exacts [associated.irreducible β¨u,rflβ© (hi b h), hi a (multiset.mem_of_mem_erase ha)] },
{ rw [multiset.prod_cons, mul_comm b, mul_assoc, multiset.prod_erase h, mul_comm] },
end,
Ξ» β¨f,hi,he,hneβ©, let β¨b, hβ© := multiset.exists_mem_of_ne_zero hne in
not_is_unit_of_not_is_unit_dvd (hi b h).not_unit (he.subst $ multiset.dvd_prod h)β©
end wf_dvd_monoid
theorem wf_dvd_monoid.of_well_founded_associates [cancel_comm_monoid_with_zero Ξ±]
(h : well_founded ((<) : associates Ξ± β associates Ξ± β Prop)) : wf_dvd_monoid Ξ± :=
wf_dvd_monoid.of_wf_dvd_monoid_associates
β¨by { convert h, ext, exact associates.dvd_not_unit_iff_lt }β©
theorem wf_dvd_monoid.iff_well_founded_associates [cancel_comm_monoid_with_zero Ξ±] :
wf_dvd_monoid Ξ± β well_founded ((<) : associates Ξ± β associates Ξ± β Prop) :=
β¨by apply wf_dvd_monoid.well_founded_associates, wf_dvd_monoid.of_well_founded_associatesβ©
section prio
set_option default_priority 100 -- see Note [default priority]
/-- unique factorization monoids.
These are defined as `cancel_comm_monoid_with_zero`s with well-founded strict divisibility
relations, but this is equivalent to more familiar definitions:
Each element (except zero) is uniquely represented as a multiset of irreducible factors.
Uniqueness is only up to associated elements.
Each element (except zero) is non-uniquely represented as a multiset
of prime factors.
To define a UFD using the definition in terms of multisets
of irreducible factors, use the definition `of_exists_unique_irreducible_factors`
To define a UFD using the definition in terms of multisets
of prime factors, use the definition `of_exists_prime_factors`
-/
class unique_factorization_monoid (Ξ± : Type*) [cancel_comm_monoid_with_zero Ξ±]
extends wf_dvd_monoid Ξ± : Prop :=
(irreducible_iff_prime : β {a : Ξ±}, irreducible a β prime a)
/-- Can't be an instance because it would cause a loop `ufm β wf_dvd_monoid β ufm β ...`. -/
@[reducible] lemma ufm_of_gcd_of_wf_dvd_monoid [cancel_comm_monoid_with_zero Ξ±]
[wf_dvd_monoid Ξ±] [gcd_monoid Ξ±] : unique_factorization_monoid Ξ± :=
{ irreducible_iff_prime := Ξ» _, gcd_monoid.irreducible_iff_prime
.. βΉwf_dvd_monoid Ξ±βΊ }
instance associates.ufm [cancel_comm_monoid_with_zero Ξ±]
[unique_factorization_monoid Ξ±] : unique_factorization_monoid (associates Ξ±) :=
{ irreducible_iff_prime := by { rw β associates.irreducible_iff_prime_iff,
apply unique_factorization_monoid.irreducible_iff_prime, }
.. (wf_dvd_monoid.wf_dvd_monoid_associates : wf_dvd_monoid (associates Ξ±)) }
end prio
namespace unique_factorization_monoid
variables [cancel_comm_monoid_with_zero Ξ±] [unique_factorization_monoid Ξ±]
theorem exists_prime_factors (a : Ξ±) : a β 0 β
β f : multiset Ξ±, (βb β f, prime b) β§ f.prod ~α΅€ a :=
by { simp_rw β unique_factorization_monoid.irreducible_iff_prime,
apply wf_dvd_monoid.exists_factors a }
@[elab_as_eliminator] lemma induction_on_prime {P : Ξ± β Prop}
(a : Ξ±) (hβ : P 0) (hβ : β x : Ξ±, is_unit x β P x)
(hβ : β a p : Ξ±, a β 0 β prime p β P a β P (p * a)) : P a :=
begin
simp_rw β unique_factorization_monoid.irreducible_iff_prime at hβ,
exact wf_dvd_monoid.induction_on_irreducible a hβ hβ hβ,
end
lemma factors_unique : β{f g : multiset Ξ±},
(βxβf, irreducible x) β (βxβg, irreducible x) β f.prod ~α΅€ g.prod β
multiset.rel associated f g :=
by haveI := classical.dec_eq Ξ±; exact
Ξ» f, multiset.induction_on f
(Ξ» g _ hg h,
multiset.rel_zero_left.2 $
multiset.eq_zero_of_forall_not_mem (Ξ» x hx,
have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm,
(hg x hx).not_unit (is_unit_iff_dvd_one.2 ((multiset.dvd_prod hx).trans
(is_unit_iff_dvd_one.1 this)))))
(Ξ» p f ih g hf hg hfg,
let β¨b, hbg, hbβ© := exists_associated_mem_of_dvd_prod
(irreducible_iff_prime.1 (hf p (by simp)))
(Ξ» q hq, irreducible_iff_prime.1 (hg _ hq)) $
hfg.dvd_iff_dvd_right.1
(show p β£ (p ::β f).prod, by simp) in
begin
rw β multiset.cons_erase hbg,
exact multiset.rel.cons hb (ih (Ξ» q hq, hf _ (by simp [hq]))
(Ξ» q (hq : q β g.erase b), hg q (multiset.mem_of_mem_erase hq))
(associated.of_mul_left
(by rwa [β multiset.prod_cons, β multiset.prod_cons, multiset.cons_erase hbg]) hb
(hf p (by simp)).ne_zero))
end)
end unique_factorization_monoid
lemma prime_factors_unique [cancel_comm_monoid_with_zero Ξ±] : β {f g : multiset Ξ±},
(β x β f, prime x) β (β x β g, prime x) β f.prod ~α΅€ g.prod β
multiset.rel associated f g :=
by haveI := classical.dec_eq Ξ±; exact
Ξ» f, multiset.induction_on f
(Ξ» g _ hg h,
multiset.rel_zero_left.2 $
multiset.eq_zero_of_forall_not_mem $ Ξ» x hx,
have is_unit g.prod, by simpa [associated_one_iff_is_unit] using h.symm,
(hg x hx).not_unit $ is_unit_iff_dvd_one.2 $
(multiset.dvd_prod hx).trans (is_unit_iff_dvd_one.1 this))
(Ξ» p f ih g hf hg hfg,
let β¨b, hbg, hbβ© := exists_associated_mem_of_dvd_prod
(hf p (by simp)) (Ξ» q hq, hg _ hq) $
hfg.dvd_iff_dvd_right.1
(show p β£ (p ::β f).prod, by simp) in
begin
rw β multiset.cons_erase hbg,
exact multiset.rel.cons hb (ih (Ξ» q hq, hf _ (by simp [hq]))
(Ξ» q (hq : q β g.erase b), hg q (multiset.mem_of_mem_erase hq))
(associated.of_mul_left
(by rwa [β multiset.prod_cons, β multiset.prod_cons, multiset.cons_erase hbg]) hb
(hf p (by simp)).ne_zero)),
end)
/-- If an irreducible has a prime factorization,
then it is an associate of one of its prime factors. -/
lemma prime_factors_irreducible [cancel_comm_monoid_with_zero Ξ±] {a : Ξ±} {f : multiset Ξ±}
(ha : irreducible a) (pfa : (β b β f, prime b) β§ f.prod ~α΅€ a) :
β p, a ~α΅€ p β§ f = {p} :=
begin
haveI := classical.dec_eq Ξ±,
refine multiset.induction_on f (Ξ» h, (ha.not_unit
(associated_one_iff_is_unit.1 (associated.symm h))).elim) _ pfa.2 pfa.1,
rintros p s _ β¨u, huβ© hs,
use p,
have hs0 : s = 0,
{ by_contra hs0,
obtain β¨q, hqβ© := multiset.exists_mem_of_ne_zero hs0,
apply (hs q (by simp [hq])).2.1,
refine (ha.is_unit_or_is_unit (_ : _ = ((p * βu) * (s.erase q).prod) * _)).resolve_left _,
{ rw [mul_right_comm _ _ q, mul_assoc, β multiset.prod_cons, multiset.cons_erase hq, β hu,
mul_comm, mul_comm p _, mul_assoc],
simp, },
apply mt is_unit_of_mul_is_unit_left (mt is_unit_of_mul_is_unit_left _),
apply (hs p (multiset.mem_cons_self _ _)).2.1 },
simp only [mul_one, multiset.prod_cons, multiset.prod_zero, hs0] at *,
exact β¨associated.symm β¨u, huβ©, rflβ©,
end
section exists_prime_factors
variables [cancel_comm_monoid_with_zero Ξ±]
variables (pf : β (a : Ξ±), a β 0 β β f : multiset Ξ±, (βb β f, prime b) β§ f.prod ~α΅€ a)
include pf
lemma wf_dvd_monoid.of_exists_prime_factors : wf_dvd_monoid Ξ± :=
β¨begin
classical,
refine rel_hom_class.well_founded
(rel_hom.mk _ _ : (dvd_not_unit : Ξ± β Ξ± β Prop) βr ((<) : with_top β β with_top β β Prop))
(with_top.well_founded_lt nat.lt_wf),
{ intro a,
by_cases h : a = 0, { exact β€ },
exact (classical.some (pf a h)).card },
rintros a b β¨ane0, β¨c, hc, b_eqβ©β©,
rw dif_neg ane0,
by_cases h : b = 0, { simp [h, lt_top_iff_ne_top] },
rw [dif_neg h, with_top.coe_lt_coe],
have cne0 : c β 0, { refine mt (Ξ» con, _) h, rw [b_eq, con, mul_zero] },
calc multiset.card (classical.some (pf a ane0))
< _ + multiset.card (classical.some (pf c cne0)) :
lt_add_of_pos_right _ (multiset.card_pos.mpr (Ξ» con, hc (associated_one_iff_is_unit.mp _)))
... = multiset.card (classical.some (pf a ane0) + classical.some (pf c cne0)) :
(multiset.card_add _ _).symm
... = multiset.card (classical.some (pf b h)) :
multiset.card_eq_card_of_rel (prime_factors_unique _ (classical.some_spec (pf _ h)).1 _),
{ convert (classical.some_spec (pf c cne0)).2.symm,
rw [con, multiset.prod_zero] },
{ intros x hadd,
rw multiset.mem_add at hadd,
cases hadd; apply (classical.some_spec (pf _ _)).1 _ hadd },
{ rw multiset.prod_add,
transitivity a * c,
{ apply associated.mul_mul; apply (classical.some_spec (pf _ _)).2 },
{ rw β b_eq,
apply (classical.some_spec (pf _ _)).2.symm, } }
endβ©
lemma irreducible_iff_prime_of_exists_prime_factors {p : Ξ±} : irreducible p β prime p :=
begin
by_cases hp0 : p = 0,
{ simp [hp0] },
refine β¨Ξ» h, _, prime.irreducibleβ©,
obtain β¨f, hfβ© := pf p hp0,
obtain β¨q, hq, rflβ© := prime_factors_irreducible h hf,
rw hq.prime_iff,
exact hf.1 q (multiset.mem_singleton_self _)
end
theorem unique_factorization_monoid.of_exists_prime_factors :
unique_factorization_monoid Ξ± :=
{ irreducible_iff_prime := Ξ» _, irreducible_iff_prime_of_exists_prime_factors pf,
.. wf_dvd_monoid.of_exists_prime_factors pf }
end exists_prime_factors
theorem unique_factorization_monoid.iff_exists_prime_factors [cancel_comm_monoid_with_zero Ξ±] :
unique_factorization_monoid Ξ± β
(β (a : Ξ±), a β 0 β β f : multiset Ξ±, (βb β f, prime b) β§ f.prod ~α΅€ a) :=
β¨Ξ» h, @unique_factorization_monoid.exists_prime_factors _ _ h,
unique_factorization_monoid.of_exists_prime_factorsβ©
section
variables {Ξ² : Type*} [cancel_comm_monoid_with_zero Ξ±] [cancel_comm_monoid_with_zero Ξ²]
lemma mul_equiv.unique_factorization_monoid (e : Ξ± β* Ξ²)
(hΞ± : unique_factorization_monoid Ξ±) : unique_factorization_monoid Ξ² :=
begin
rw unique_factorization_monoid.iff_exists_prime_factors at hΞ± β’, intros a ha,
obtain β¨w,hp,u,hβ© := hΞ± (e.symm a) (Ξ» h, ha $ by { convert β map_zero e, simp [β h] }),
exact β¨ w.map e,
Ξ» b hb, let β¨c,hc,heβ© := multiset.mem_map.1 hb in he βΈ e.prime_iff.1 (hp c hc),
units.map e.to_monoid_hom u,
by { erw [multiset.prod_hom, β e.map_mul, h], simp } β©,
end
lemma mul_equiv.unique_factorization_monoid_iff (e : Ξ± β* Ξ²) :
unique_factorization_monoid Ξ± β unique_factorization_monoid Ξ² :=
β¨ e.unique_factorization_monoid, e.symm.unique_factorization_monoid β©
end
theorem irreducible_iff_prime_of_exists_unique_irreducible_factors [cancel_comm_monoid_with_zero Ξ±]
(eif : β (a : Ξ±), a β 0 β β f : multiset Ξ±, (βb β f, irreducible b) β§ f.prod ~α΅€ a)
(uif : β (f g : multiset Ξ±),
(β x β f, irreducible x) β (β x β g, irreducible x) β f.prod ~α΅€ g.prod β
multiset.rel associated f g)
(p : Ξ±) : irreducible p β prime p :=
β¨by letI := classical.dec_eq Ξ±; exact Ξ» hpi,
β¨hpi.ne_zero, hpi.1,
Ξ» a b β¨x, hxβ©,
if hab0 : a * b = 0
then (eq_zero_or_eq_zero_of_mul_eq_zero hab0).elim
(Ξ» ha0, by simp [ha0])
(Ξ» hb0, by simp [hb0])
else
have hx0 : x β 0, from Ξ» hx0, by simp * at *,
have ha0 : a β 0, from left_ne_zero_of_mul hab0,
have hb0 : b β 0, from right_ne_zero_of_mul hab0,
begin
cases eif x hx0 with fx hfx,
cases eif a ha0 with fa hfa,
cases eif b hb0 with fb hfb,
have h : multiset.rel associated (p ::β fx) (fa + fb),
{ apply uif,
{ exact Ξ» i hi, (multiset.mem_cons.1 hi).elim (Ξ» hip, hip.symm βΈ hpi) (hfx.1 _), },
{ exact Ξ» i hi, (multiset.mem_add.1 hi).elim (hfa.1 _) (hfb.1 _), },
calc multiset.prod (p ::β fx)
~α΅€ a * b : by rw [hx, multiset.prod_cons];
exact hfx.2.mul_left _
... ~α΅€ (fa).prod * (fb).prod :
hfa.2.symm.mul_mul hfb.2.symm
... = _ : by rw multiset.prod_add, },
exact let β¨q, hqf, hqβ© := multiset.exists_mem_of_rel_of_mem h
(multiset.mem_cons_self p _) in
(multiset.mem_add.1 hqf).elim
(Ξ» hqa, or.inl $ hq.dvd_iff_dvd_left.2 $
hfa.2.dvd_iff_dvd_right.1
(multiset.dvd_prod hqa))
(Ξ» hqb, or.inr $ hq.dvd_iff_dvd_left.2 $
hfb.2.dvd_iff_dvd_right.1
(multiset.dvd_prod hqb))
endβ©, prime.irreducibleβ©
theorem unique_factorization_monoid.of_exists_unique_irreducible_factors
[cancel_comm_monoid_with_zero Ξ±]
(eif : β (a : Ξ±), a β 0 β β f : multiset Ξ±, (βb β f, irreducible b) β§ f.prod ~α΅€ a)
(uif : β (f g : multiset Ξ±),
(β x β f, irreducible x) β (β x β g, irreducible x) β f.prod ~α΅€ g.prod β
multiset.rel associated f g) :
unique_factorization_monoid Ξ± :=
unique_factorization_monoid.of_exists_prime_factors (by
{ convert eif,
simp_rw irreducible_iff_prime_of_exists_unique_irreducible_factors eif uif })
namespace unique_factorization_monoid
variables [cancel_comm_monoid_with_zero Ξ±] [decidable_eq Ξ±]
variables [unique_factorization_monoid Ξ±]
/-- Noncomputably determines the multiset of prime factors. -/
noncomputable def factors (a : Ξ±) : multiset Ξ± := if h : a = 0 then 0 else
classical.some (unique_factorization_monoid.exists_prime_factors a h)
theorem factors_prod {a : Ξ±} (ane0 : a β 0) : associated (factors a).prod a :=
begin
rw [factors, dif_neg ane0],
exact (classical.some_spec (exists_prime_factors a ane0)).2
end
theorem prime_of_factor {a : Ξ±} : β (x : Ξ±), x β factors a β prime x :=
begin
rw [factors],
split_ifs with ane0, { simp only [multiset.not_mem_zero, forall_false_left, forall_const] },
intros x hx,
exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 x hx,
end
theorem irreducible_of_factor {a : Ξ±} : β (x : Ξ±), x β factors a β irreducible x :=
Ξ» x h, (prime_of_factor x h).irreducible
lemma exists_mem_factors_of_dvd {a p : Ξ±} (ha0 : a β 0) (hp : irreducible p) : p β£ a β
β q β factors a, p ~α΅€ q :=
Ξ» β¨b, hbβ©,
have hb0 : b β 0, from Ξ» hb0, by simp * at *,
have multiset.rel associated (p ::β factors b) (factors a),
from factors_unique
(Ξ» x hx, (multiset.mem_cons.1 hx).elim (Ξ» h, h.symm βΈ hp) (irreducible_of_factor _))
irreducible_of_factor
(associated.symm $ calc multiset.prod (factors a) ~α΅€ a : factors_prod ha0
... = p * b : hb
... ~α΅€ multiset.prod (p ::β factors b) :
by rw multiset.prod_cons; exact (factors_prod hb0).symm.mul_left _),
multiset.exists_mem_of_rel_of_mem this (by simp)
end unique_factorization_monoid
namespace unique_factorization_monoid
variables [cancel_comm_monoid_with_zero Ξ±] [decidable_eq Ξ±] [normalization_monoid Ξ±]
variables [unique_factorization_monoid Ξ±]
/-- Noncomputably determines the multiset of prime factors. -/
noncomputable def normalized_factors (a : Ξ±) : multiset Ξ± :=
multiset.map normalize $ factors a
/-- An arbitrary choice of factors of `x : M` is exactly the (unique) normalized set of factors,
if `M` has a trivial group of units. -/
@[simp] lemma factors_eq_normalized_factors {M : Type*} [cancel_comm_monoid_with_zero M]
[decidable_eq M] [unique_factorization_monoid M] [unique (MΛ£)] (x : M) :
factors x = normalized_factors x :=
begin
unfold normalized_factors,
convert (multiset.map_id (factors x)).symm,
ext p,
exact normalize_eq p
end
theorem normalized_factors_prod {a : Ξ±} (ane0 : a β 0) : associated (normalized_factors a).prod a :=
begin
rw [normalized_factors, factors, dif_neg ane0],
refine associated.trans _ (classical.some_spec (exists_prime_factors a ane0)).2,
rw [β associates.mk_eq_mk_iff_associated, β associates.prod_mk, β associates.prod_mk,
multiset.map_map],
congr' 2,
ext,
rw [function.comp_apply, associates.mk_normalize],
end
theorem prime_of_normalized_factor {a : Ξ±} : β (x : Ξ±), x β normalized_factors a β prime x :=
begin
rw [normalized_factors, factors],
split_ifs with ane0, { simp },
intros x hx, rcases multiset.mem_map.1 hx with β¨y, β¨hy, rflβ©β©,
rw (normalize_associated _).prime_iff,
exact (classical.some_spec (unique_factorization_monoid.exists_prime_factors a ane0)).1 y hy,
end
theorem irreducible_of_normalized_factor {a : Ξ±} :
β (x : Ξ±), x β normalized_factors a β irreducible x :=
Ξ» x h, (prime_of_normalized_factor x h).irreducible
theorem normalize_normalized_factor {a : Ξ±} :
β (x : Ξ±), x β normalized_factors a β normalize x = x :=
begin
rw [normalized_factors, factors],
split_ifs with h, { simp },
intros x hx,
obtain β¨y, hy, rflβ© := multiset.mem_map.1 hx,
apply normalize_idem
end
lemma normalized_factors_irreducible {a : Ξ±} (ha : irreducible a) :
normalized_factors a = {normalize a} :=
begin
obtain β¨p, a_assoc, hpβ© := prime_factors_irreducible ha
β¨prime_of_normalized_factor, normalized_factors_prod ha.ne_zeroβ©,
have p_mem : p β normalized_factors a,
{ rw hp, exact multiset.mem_singleton_self _ },
convert hp,
rwa [β normalize_normalized_factor p p_mem, normalize_eq_normalize_iff, dvd_dvd_iff_associated]
end
lemma exists_mem_normalized_factors_of_dvd {a p : Ξ±} (ha0 : a β 0) (hp : irreducible p) : p β£ a β
β q β normalized_factors a, p ~α΅€ q :=
Ξ» β¨b, hbβ©,
have hb0 : b β 0, from Ξ» hb0, by simp * at *,
have multiset.rel associated (p ::β normalized_factors b) (normalized_factors a),
from factors_unique
(Ξ» x hx, (multiset.mem_cons.1 hx).elim (Ξ» h, h.symm βΈ hp)
(irreducible_of_normalized_factor _))
irreducible_of_normalized_factor
(associated.symm $ calc multiset.prod (normalized_factors a) ~α΅€ a : normalized_factors_prod ha0
... = p * b : hb
... ~α΅€ multiset.prod (p ::β normalized_factors b) :
by rw multiset.prod_cons; exact (normalized_factors_prod hb0).symm.mul_left _),
multiset.exists_mem_of_rel_of_mem this (by simp)
@[simp] lemma normalized_factors_zero : normalized_factors (0 : Ξ±) = 0 :=
by simp [normalized_factors, factors]
@[simp] lemma normalized_factors_one : normalized_factors (1 : Ξ±) = 0 :=
begin
nontriviality Ξ± using [normalized_factors, factors],
rw β multiset.rel_zero_right,
apply factors_unique irreducible_of_normalized_factor,
{ intros x hx,
exfalso,
apply multiset.not_mem_zero x hx },
{ simp [normalized_factors_prod (@one_ne_zero Ξ± _ _)] },
apply_instance
end
@[simp] lemma normalized_factors_mul {x y : Ξ±} (hx : x β 0) (hy : y β 0) :
normalized_factors (x * y) = normalized_factors x + normalized_factors y :=
begin
have h : (normalize : Ξ± β Ξ±) = associates.out β associates.mk,
{ ext, rw [function.comp_apply, associates.out_mk], },
rw [β multiset.map_id' (normalized_factors (x * y)), β multiset.map_id' (normalized_factors x),
β multiset.map_id' (normalized_factors y), β multiset.map_congr rfl normalize_normalized_factor,
β multiset.map_congr rfl normalize_normalized_factor,
β multiset.map_congr rfl normalize_normalized_factor,
β multiset.map_add, h, β multiset.map_map associates.out, eq_comm,
β multiset.map_map associates.out],
refine congr rfl _,
apply multiset.map_mk_eq_map_mk_of_rel,
apply factors_unique,
{ intros x hx,
rcases multiset.mem_add.1 hx with hx | hx;
exact irreducible_of_normalized_factor x hx },
{ exact irreducible_of_normalized_factor },
{ rw multiset.prod_add,
exact ((normalized_factors_prod hx).mul_mul (normalized_factors_prod hy)).trans
(normalized_factors_prod (mul_ne_zero hx hy)).symm }
end
@[simp] lemma normalized_factors_pow {x : Ξ±} (n : β) :
normalized_factors (x ^ n) = n β’ normalized_factors x :=
begin
induction n with n ih,
{ simp },
by_cases h0 : x = 0,
{ simp [h0, zero_pow n.succ_pos, smul_zero] },
rw [pow_succ, succ_nsmul, normalized_factors_mul h0 (pow_ne_zero _ h0), ih],
end
theorem _root_.irreducible.normalized_factors_pow {p : Ξ±} (hp : irreducible p) (k : β) :
normalized_factors (p ^ k) = multiset.repeat (normalize p) k :=
by rw [normalized_factors_pow, normalized_factors_irreducible hp, multiset.nsmul_singleton]
lemma dvd_iff_normalized_factors_le_normalized_factors {x y : Ξ±} (hx : x β 0) (hy : y β 0) :
x β£ y β normalized_factors x β€ normalized_factors y :=
begin
split,
{ rintro β¨c, rflβ©,
simp [hx, right_ne_zero_of_mul hy] },
{ rw [β (normalized_factors_prod hx).dvd_iff_dvd_left,
β (normalized_factors_prod hy).dvd_iff_dvd_right],
apply multiset.prod_dvd_prod_of_le }
end
theorem normalized_factors_of_irreducible_pow {p : Ξ±} (hp : irreducible p) (k : β) :
normalized_factors (p ^ k) = multiset.repeat (normalize p) k :=
by rw [normalized_factors_pow, normalized_factors_irreducible hp, multiset.nsmul_singleton]
lemma zero_not_mem_normalized_factors (x : Ξ±) : (0 : Ξ±) β normalized_factors x :=
Ξ» h, prime.ne_zero (prime_of_normalized_factor _ h) rfl
lemma dvd_of_mem_normalized_factors {a p : Ξ±} (H : p β normalized_factors a) : p β£ a :=
begin
by_cases hcases : a = 0,
{ rw hcases,
exact dvd_zero p },
{ exact dvd_trans (multiset.dvd_prod H) (associated.dvd (normalized_factors_prod hcases)) },
end
lemma exists_associated_prime_pow_of_unique_normalized_factor {p r : Ξ±}
(h : β {m}, m β normalized_factors r β m = p) (hr : r β 0) : β (i : β), associated (p ^ i) r :=
begin
use (normalized_factors r).card,
have := unique_factorization_monoid.normalized_factors_prod hr,
rwa [multiset.eq_repeat_of_mem (Ξ» b, h), multiset.prod_repeat] at this
end
end unique_factorization_monoid
namespace unique_factorization_monoid
open_locale classical
open multiset associates
noncomputable theory
variables [cancel_comm_monoid_with_zero Ξ±] [nontrivial Ξ±] [unique_factorization_monoid Ξ±]
/-- Noncomputably defines a `normalization_monoid` structure on a `unique_factorization_monoid`. -/
protected def normalization_monoid : normalization_monoid Ξ± :=
normalization_monoid_of_monoid_hom_right_inverse
{ to_fun := Ξ» a : associates Ξ±, if a = 0 then 0 else ((normalized_factors a).map
(classical.some mk_surjective.has_right_inverse : associates Ξ± β Ξ±)).prod,
map_one' := by simp,
map_mul' := Ξ» x y, by
{ by_cases hx : x = 0, { simp [hx] },
by_cases hy : y = 0, { simp [hy] },
simp [hx, hy] } } begin
intro x,
dsimp,
by_cases hx : x = 0, { simp [hx] },
have h : associates.mk_monoid_hom β (classical.some mk_surjective.has_right_inverse) =
(id : associates Ξ± β associates Ξ±),
{ ext x,
rw [function.comp_apply, mk_monoid_hom_apply,
classical.some_spec mk_surjective.has_right_inverse x],
refl },
rw [if_neg hx, β mk_monoid_hom_apply, monoid_hom.map_multiset_prod, map_map, h, map_id,
β associated_iff_eq],
apply normalized_factors_prod hx
end
instance : inhabited (normalization_monoid Ξ±) := β¨unique_factorization_monoid.normalization_monoidβ©
end unique_factorization_monoid
namespace unique_factorization_monoid
variables {R : Type*} [cancel_comm_monoid_with_zero R] [unique_factorization_monoid R]
lemma no_factors_of_no_prime_factors {a b : R} (ha : a β 0)
(h : (β {d}, d β£ a β d β£ b β Β¬ prime d)) : β {d}, d β£ a β d β£ b β is_unit d :=
Ξ» d, induction_on_prime d
(by { simp only [zero_dvd_iff], intros, contradiction })
(Ξ» x hx _ _, hx)
(Ξ» d q hp hq ih dvd_a dvd_b,
absurd hq (h (dvd_of_mul_right_dvd dvd_a) (dvd_of_mul_right_dvd dvd_b)))
/-- Euclid's lemma: if `a β£ b * c` and `a` and `c` have no common prime factors, `a β£ b`.
Compare `is_coprime.dvd_of_dvd_mul_left`. -/
lemma dvd_of_dvd_mul_left_of_no_prime_factors {a b c : R} (ha : a β 0) :
(β {d}, d β£ a β d β£ c β Β¬ prime d) β a β£ b * c β a β£ b :=
begin
refine induction_on_prime c _ _ _,
{ intro no_factors,
simp only [dvd_zero, mul_zero, forall_prop_of_true],
haveI := classical.prop_decidable,
exact is_unit_iff_forall_dvd.mp
(no_factors_of_no_prime_factors ha @no_factors (dvd_refl a) (dvd_zero a)) _ },
{ rintros _ β¨x, rflβ© _ a_dvd_bx,
apply units.dvd_mul_right.mp a_dvd_bx },
{ intros c p hc hp ih no_factors a_dvd_bpc,
apply ih (Ξ» q dvd_a dvd_c hq, no_factors dvd_a (dvd_c.mul_left _) hq),
rw mul_left_comm at a_dvd_bpc,
refine or.resolve_left (hp.left_dvd_or_dvd_right_of_dvd_mul a_dvd_bpc) (Ξ» h, _),
exact no_factors h (dvd_mul_right p c) hp }
end
/-- Euclid's lemma: if `a β£ b * c` and `a` and `b` have no common prime factors, `a β£ c`.
Compare `is_coprime.dvd_of_dvd_mul_right`. -/
lemma dvd_of_dvd_mul_right_of_no_prime_factors {a b c : R} (ha : a β 0)
(no_factors : β {d}, d β£ a β d β£ b β Β¬ prime d) : a β£ b * c β a β£ c :=
by simpa [mul_comm b c] using dvd_of_dvd_mul_left_of_no_prime_factors ha @no_factors
/-- If `a β 0, b` are elements of a unique factorization domain, then dividing
out their common factor `c'` gives `a'` and `b'` with no factors in common. -/
lemma exists_reduced_factors : β (a β (0 : R)) b,
β a' b' c', (β {d}, d β£ a' β d β£ b' β is_unit d) β§ c' * a' = a β§ c' * b' = b :=
begin
haveI := classical.prop_decidable,
intros a,
refine induction_on_prime a _ _ _,
{ intros, contradiction },
{ intros a a_unit a_ne_zero b,
use [a, b, 1],
split,
{ intros p p_dvd_a _,
exact is_unit_of_dvd_unit p_dvd_a a_unit },
{ simp } },
{ intros a p a_ne_zero p_prime ih_a pa_ne_zero b,
by_cases p β£ b,
{ rcases h with β¨b, rflβ©,
obtain β¨a', b', c', no_factor, ha', hb'β© := ih_a a_ne_zero b,
refine β¨a', b', p * c', @no_factor, _, _β©,
{ rw [mul_assoc, ha'] },
{ rw [mul_assoc, hb'] } },
{ obtain β¨a', b', c', coprime, rfl, rflβ© := ih_a a_ne_zero b,
refine β¨p * a', b', c', _, mul_left_comm _ _ _, rflβ©,
intros q q_dvd_pa' q_dvd_b',
cases p_prime.left_dvd_or_dvd_right_of_dvd_mul q_dvd_pa' with p_dvd_q q_dvd_a',
{ have : p β£ c' * b' := dvd_mul_of_dvd_right (p_dvd_q.trans q_dvd_b') _,
contradiction },
exact coprime q_dvd_a' q_dvd_b' } }
end
lemma exists_reduced_factors' (a b : R) (hb : b β 0) :
β a' b' c', (β {d}, d β£ a' β d β£ b' β is_unit d) β§ c' * a' = a β§ c' * b' = b :=
let β¨b', a', c', no_factor, hb, haβ© := exists_reduced_factors b hb a
in β¨a', b', c', Ξ» _ hpb hpa, no_factor hpa hpb, ha, hbβ©
section multiplicity
variables [nontrivial R] [normalization_monoid R] [decidable_eq R]
variables [dec_dvd : decidable_rel (has_dvd.dvd : R β R β Prop)]
open multiplicity multiset
include dec_dvd
lemma le_multiplicity_iff_repeat_le_normalized_factors {a b : R} {n : β}
(ha : irreducible a) (hb : b β 0) :
βn β€ multiplicity a b β repeat (normalize a) n β€ normalized_factors b :=
begin
rw β pow_dvd_iff_le_multiplicity,
revert b,
induction n with n ih, { simp },
intros b hb,
split,
{ rintro β¨c, rflβ©,
rw [ne.def, pow_succ, mul_assoc, mul_eq_zero, decidable.not_or_iff_and_not] at hb,
rw [pow_succ, mul_assoc, normalized_factors_mul hb.1 hb.2, repeat_succ,
normalized_factors_irreducible ha, singleton_add, cons_le_cons_iff, β ih hb.2],
apply dvd.intro _ rfl },
{ rw [multiset.le_iff_exists_add],
rintro β¨u, huβ©,
rw [β (normalized_factors_prod hb).dvd_iff_dvd_right, hu, prod_add, prod_repeat],
exact (associated.pow_pow $ associated_normalize a).dvd.trans (dvd.intro u.prod rfl) }
end
/-- The multiplicity of an irreducible factor of a nonzero element is exactly the number of times
the normalized factor occurs in the `normalized_factors`.
See also `count_normalized_factors_eq` which expands the definition of `multiplicity`
to produce a specification for `count (normalized_factors _) _`..
-/
lemma multiplicity_eq_count_normalized_factors {a b : R} (ha : irreducible a) (hb : b β 0) :
multiplicity a b = (normalized_factors b).count (normalize a) :=
begin
apply le_antisymm,
{ apply enat.le_of_lt_add_one,
rw [β nat.cast_one, β nat.cast_add, lt_iff_not_ge, ge_iff_le,
le_multiplicity_iff_repeat_le_normalized_factors ha hb, β le_count_iff_repeat_le],
simp },
rw [le_multiplicity_iff_repeat_le_normalized_factors ha hb, β le_count_iff_repeat_le],
end
omit dec_dvd
/-- The number of times an irreducible factor `p` appears in `normalized_factors x` is defined by
the number of times it divides `x`.
See also `multiplicity_eq_count_normalized_factors` if `n` is given by `multiplicity p x`.
-/
lemma count_normalized_factors_eq {p x : R} (hp : irreducible p) (hnorm : normalize p = p) {n : β}
(hle : p^n β£ x) (hlt : Β¬ (p^(n+1) β£ x)) :
(normalized_factors x).count p = n :=
begin
letI : decidable_rel ((β£) : R β R β Prop) := Ξ» _ _, classical.prop_decidable _,
by_cases hx0 : x = 0,
{ simp [hx0] at hlt, contradiction },
rw [β enat.coe_inj],
convert (multiplicity_eq_count_normalized_factors hp hx0).symm,
{ exact hnorm.symm },
exact (multiplicity.eq_coe_iff.mpr β¨hle, hltβ©).symm
end
end multiplicity
end unique_factorization_monoid
namespace associates
open unique_factorization_monoid associated multiset
variables [cancel_comm_monoid_with_zero Ξ±]
/-- `factor_set Ξ±` representation elements of unique factorization domain as multisets.
`multiset Ξ±` produced by `normalized_factors` are only unique up to associated elements, while the
multisets in `factor_set Ξ±` are unique by equality and restricted to irreducible elements. This
gives us a representation of each element as a unique multisets (or the added β€ for 0), which has a
complete lattice struture. Infimum is the greatest common divisor and supremum is the least common
multiple.
-/
@[reducible] def {u} factor_set (Ξ± : Type u) [cancel_comm_monoid_with_zero Ξ±] :
Type u :=
with_top (multiset { a : associates Ξ± // irreducible a })
local attribute [instance] associated.setoid
theorem factor_set.coe_add {a b : multiset { a : associates Ξ± // irreducible a }} :
(β(a + b) : factor_set Ξ±) = a + b :=
by norm_cast
lemma factor_set.sup_add_inf_eq_add [decidable_eq (associates Ξ±)] :
β(a b : factor_set Ξ±), a β b + a β b = a + b
| none b := show β€ β b + β€ β b = β€ + b, by simp
| a none := show a β β€ + a β β€ = a + β€, by simp
| (some a) (some b) := show (a : factor_set Ξ±) β b + a β b = a + b, from
begin
rw [β with_top.coe_sup, β with_top.coe_inf, β with_top.coe_add, β with_top.coe_add,
with_top.coe_eq_coe],
exact multiset.union_add_inter _ _
end
/-- Evaluates the product of a `factor_set` to be the product of the corresponding multiset,
or `0` if there is none. -/
def factor_set.prod : factor_set Ξ± β associates Ξ±
| none := 0
| (some s) := (s.map coe).prod
@[simp] theorem prod_top : (β€ : factor_set Ξ±).prod = 0 := rfl
@[simp] theorem prod_coe {s : multiset { a : associates Ξ± // irreducible a }} :
(s : factor_set Ξ±).prod = (s.map coe).prod :=
rfl
@[simp] theorem prod_add : β(a b : factor_set Ξ±), (a + b).prod = a.prod * b.prod
| none b := show (β€ + b).prod = (β€:factor_set Ξ±).prod * b.prod, by simp
| a none := show (a + β€).prod = a.prod * (β€:factor_set Ξ±).prod, by simp
| (some a) (some b) :=
show (βa + βb:factor_set Ξ±).prod = (βa:factor_set Ξ±).prod * (βb:factor_set Ξ±).prod,
by rw [β factor_set.coe_add, prod_coe, prod_coe, prod_coe, multiset.map_add, multiset.prod_add]
theorem prod_mono : β{a b : factor_set Ξ±}, a β€ b β a.prod β€ b.prod
| none b h := have b = β€, from top_unique h, by rw [this, prod_top]; exact le_rfl
| a none h := show a.prod β€ (β€ : factor_set Ξ±).prod, by simp; exact le_top
| (some a) (some b) h := prod_le_prod $ multiset.map_le_map $ with_top.coe_le_coe.1 $ h
theorem factor_set.prod_eq_zero_iff [nontrivial Ξ±] (p : factor_set Ξ±) :
p.prod = 0 β p = β€ :=
begin
induction p using with_top.rec_top_coe,
{ simp only [iff_self, eq_self_iff_true, associates.prod_top] },
simp only [prod_coe, with_top.coe_ne_top, iff_false, prod_eq_zero_iff, multiset.mem_map],
rintro β¨β¨a, haβ©, -, eqβ©,
rw [subtype.coe_mk] at eq,
exact ha.ne_zero eq,
end
/-- `bcount p s` is the multiplicity of `p` in the factor_set `s` (with bundled `p`)-/
def bcount [decidable_eq (associates Ξ±)] (p : {a : associates Ξ± // irreducible a}) :
factor_set Ξ± β β
| none := 0
| (some s) := s.count p
variables [dec_irr : Ξ (p : associates Ξ±), decidable (irreducible p)]
include dec_irr
/-- `count p s` is the multiplicity of the irreducible `p` in the factor_set `s`.
If `p` is not irreducible, `count p s` is defined to be `0`. -/
def count [decidable_eq (associates Ξ±)] (p : associates Ξ±) :
factor_set Ξ± β β :=
if hp : irreducible p then bcount β¨p, hpβ© else 0
@[simp] lemma count_some [decidable_eq (associates Ξ±)] {p : associates Ξ±} (hp : irreducible p)
(s : multiset _) : count p (some s) = s.count β¨p, hpβ©:=
by { dunfold count, split_ifs, refl }
@[simp] lemma count_zero [decidable_eq (associates Ξ±)] {p : associates Ξ±} (hp : irreducible p) :
count p (0 : factor_set Ξ±) = 0 :=
by { dunfold count, split_ifs, refl }
lemma count_reducible [decidable_eq (associates Ξ±)] {p : associates Ξ±} (hp : Β¬ irreducible p) :
count p = 0 := dif_neg hp
omit dec_irr
/-- membership in a factor_set (bundled version) -/
def bfactor_set_mem : {a : associates Ξ± // irreducible a} β (factor_set Ξ±) β Prop
| _ β€ := true
| p (some l) := p β l
include dec_irr
/-- `factor_set_mem p s` is the predicate that the irreducible `p` is a member of
`s : factor_set Ξ±`.
If `p` is not irreducible, `p` is not a member of any `factor_set`. -/
def factor_set_mem (p : associates Ξ±) (s : factor_set Ξ±) : Prop :=
if hp : irreducible p then bfactor_set_mem β¨p, hpβ© s else false
instance : has_mem (associates Ξ±) (factor_set Ξ±) := β¨factor_set_memβ©
@[simp] lemma factor_set_mem_eq_mem (p : associates Ξ±) (s : factor_set Ξ±) :
factor_set_mem p s = (p β s) := rfl
lemma mem_factor_set_top {p : associates Ξ±} {hp : irreducible p} :
p β (β€ : factor_set Ξ±) :=
begin
dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, exact trivial
end
lemma mem_factor_set_some {p : associates Ξ±} {hp : irreducible p}
{l : multiset {a : associates Ξ± // irreducible a }} :
p β (l : factor_set Ξ±) β subtype.mk p hp β l :=
begin
dunfold has_mem.mem, dunfold factor_set_mem, split_ifs, refl
end
lemma reducible_not_mem_factor_set {p : associates Ξ±} (hp : Β¬ irreducible p)
(s : factor_set Ξ±) : Β¬ p β s :=
Ξ» (h : if hp : irreducible p then bfactor_set_mem β¨p, hpβ© s else false),
by rwa [dif_neg hp] at h
omit dec_irr
variable [unique_factorization_monoid Ξ±]
theorem unique' {p q : multiset (associates Ξ±)} :
(βaβp, irreducible a) β (βaβq, irreducible a) β p.prod = q.prod β p = q :=
begin
apply multiset.induction_on_multiset_quot p,
apply multiset.induction_on_multiset_quot q,
assume s t hs ht eq,
refine multiset.map_mk_eq_map_mk_of_rel (unique_factorization_monoid.factors_unique _ _ _),
{ exact assume a ha, ((irreducible_mk _).1 $ hs _ $ multiset.mem_map_of_mem _ ha) },
{ exact assume a ha, ((irreducible_mk _).1 $ ht _ $ multiset.mem_map_of_mem _ ha) },
simpa [quot_mk_eq_mk, prod_mk, mk_eq_mk_iff_associated] using eq
end
theorem factor_set.unique [nontrivial Ξ±] {p q : factor_set Ξ±} (h : p.prod = q.prod) : p = q :=
begin
induction p using with_top.rec_top_coe;
induction q using with_top.rec_top_coe,
{ refl },
{ rw [eq_comm, βfactor_set.prod_eq_zero_iff, βh, associates.prod_top] },
{ rw [βfactor_set.prod_eq_zero_iff, h, associates.prod_top] },
{ congr' 1,
rw βmultiset.map_eq_map subtype.coe_injective,
apply unique' _ _ h;
{ intros a ha,
obtain β¨β¨a', irredβ©, -, rflβ© := multiset.mem_map.mp ha,
rwa [subtype.coe_mk] } },
end
theorem prod_le_prod_iff_le [nontrivial Ξ±] {p q : multiset (associates Ξ±)}
(hp : βaβp, irreducible a) (hq : βaβq, irreducible a) :
p.prod β€ q.prod β p β€ q :=
iff.intro
begin
classical,
rintros β¨c, eqcβ©,
refine multiset.le_iff_exists_add.2 β¨factors c, unique' hq (Ξ» x hx, _) _β©,
{ obtain h|h := multiset.mem_add.1 hx,
{ exact hp x h },
{ exact irreducible_of_factor _ h } },
{ rw [eqc, multiset.prod_add],
congr,
refine associated_iff_eq.mp (factors_prod (Ξ» hc, _)).symm,
refine not_irreducible_zero (hq _ _),
rw [βprod_eq_zero_iff, eqc, hc, mul_zero] }
end
prod_le_prod
variables [dec : decidable_eq Ξ±] [dec' : decidable_eq (associates Ξ±)]
include dec
/-- This returns the multiset of irreducible factors as a `factor_set`,
a multiset of irreducible associates `with_top`. -/
noncomputable def factors' (a : Ξ±) :
multiset { a : associates Ξ± // irreducible a } :=
(factors a).pmap (Ξ»a ha, β¨associates.mk a, (irreducible_mk _).2 haβ©)
(irreducible_of_factor)
@[simp] theorem map_subtype_coe_factors' {a : Ξ±} :
(factors' a).map coe = (factors a).map associates.mk :=
by simp [factors', multiset.map_pmap, multiset.pmap_eq_map]
theorem factors'_cong {a b : Ξ±} (h : a ~α΅€ b) :
factors' a = factors' b :=
begin
obtain rfl|hb := eq_or_ne b 0,
{ rw associated_zero_iff_eq_zero at h, rw h },
have ha : a β 0,
{ contrapose! hb with ha,
rw [βassociated_zero_iff_eq_zero, βha],
exact h.symm },
rw [βmultiset.map_eq_map subtype.coe_injective, map_subtype_coe_factors',
map_subtype_coe_factors', βrel_associated_iff_map_eq_map],
exact factors_unique irreducible_of_factor irreducible_of_factor
((factors_prod ha).trans $ h.trans $ (factors_prod hb).symm),
end
include dec'
/-- This returns the multiset of irreducible factors of an associate as a `factor_set`,
a multiset of irreducible associates `with_top`. -/
noncomputable def factors (a : associates Ξ±) :
factor_set Ξ± :=
begin
refine (if h : a = 0 then β€ else
quotient.hrec_on a (Ξ»x h, some $ factors' x) _ h),
assume a b hab,
apply function.hfunext,
{ have : a ~α΅€ 0 β b ~α΅€ 0, from
iff.intro (assume ha0, hab.symm.trans ha0) (assume hb0, hab.trans hb0),
simp only [associated_zero_iff_eq_zero] at this,
simp only [quotient_mk_eq_mk, this, mk_eq_zero] },
exact (assume ha hb eq, heq_of_eq $ congr_arg some $ factors'_cong hab)
end
@[simp] theorem factors_0 : (0 : associates Ξ±).factors = β€ :=
dif_pos rfl
@[simp] theorem factors_mk (a : Ξ±) (h : a β 0) :
(associates.mk a).factors = factors' a :=
by { classical, apply dif_neg, apply (mt mk_eq_zero.1 h) }
@[simp]
theorem factors_prod (a : associates Ξ±) : a.factors.prod = a :=
quotient.induction_on a $ assume a, decidable.by_cases
(assume : associates.mk a = 0, by simp [quotient_mk_eq_mk, this])
(assume : associates.mk a β 0,
have a β 0, by simp * at *,
by simp [this, quotient_mk_eq_mk, prod_mk,
mk_eq_mk_iff_associated.2 (factors_prod this)])
theorem prod_factors [nontrivial Ξ±] (s : factor_set Ξ±) : s.prod.factors = s :=
factor_set.unique $ factors_prod _
@[nontriviality] lemma factors_subsingleton [subsingleton Ξ±] {a : associates Ξ±} :
a.factors = option.none :=
by { convert factors_0; apply_instance }
lemma factors_eq_none_iff_zero {a : associates Ξ±} :
a.factors = option.none β a = 0 :=
begin
nontriviality Ξ±,
exact β¨Ξ» h, by rwa [β factors_prod a, factor_set.prod_eq_zero_iff], Ξ» h, h.symm βΈ factors_0β©
end
lemma factors_eq_some_iff_ne_zero {a : associates Ξ±} :
(β (s : multiset {p : associates Ξ± // irreducible p}), a.factors = some s) β a β 0 :=
by rw [β option.is_some_iff_exists, β option.ne_none_iff_is_some, ne.def, ne.def,
factors_eq_none_iff_zero]
theorem eq_of_factors_eq_factors {a b : associates Ξ±} (h : a.factors = b.factors) : a = b :=
have a.factors.prod = b.factors.prod, by rw h,
by rwa [factors_prod, factors_prod] at this
omit dec dec'
theorem eq_of_prod_eq_prod [nontrivial Ξ±] {a b : factor_set Ξ±} (h : a.prod = b.prod) : a = b :=
begin
classical,
have : a.prod.factors = b.prod.factors, by rw h,
rwa [prod_factors, prod_factors] at this
end
include dec dec' dec_irr
theorem eq_factors_of_eq_counts {a b : associates Ξ±} (ha : a β 0) (hb : b β 0)
(h : β (p : associates Ξ±) (hp : irreducible p), p.count a.factors = p.count b.factors) :
a.factors = b.factors :=
begin
obtain β¨sa, h_saβ© := factors_eq_some_iff_ne_zero.mpr ha,
obtain β¨sb, h_sbβ© := factors_eq_some_iff_ne_zero.mpr hb,
rw [h_sa, h_sb] at h β’,
rw option.some_inj,
have h_count : β (p : associates Ξ±) (hp : irreducible p), sa.count β¨p, hpβ© = sb.count β¨p, hpβ©,
{ intros p hp, rw [β count_some, β count_some, h p hp] },
apply multiset.to_finsupp.injective,
ext β¨p, hpβ©,
rw [multiset.to_finsupp_apply, multiset.to_finsupp_apply, h_count p hp]
end
theorem eq_of_eq_counts {a b : associates Ξ±} (ha : a β 0) (hb : b β 0)
(h : β (p : associates Ξ±), irreducible p β p.count a.factors = p.count b.factors) : a = b :=
eq_of_factors_eq_factors (eq_factors_of_eq_counts ha hb h)
lemma count_le_count_of_factors_le {a b p : associates Ξ±} (hb : b β 0)
(hp : irreducible p) (h : a.factors β€ b.factors) : p.count a.factors β€ p.count b.factors :=
begin
by_cases ha : a = 0,
{ simp [*] at *, },
obtain β¨sa, h_saβ© := factors_eq_some_iff_ne_zero.mpr ha,
obtain β¨sb, h_sbβ© := factors_eq_some_iff_ne_zero.mpr hb,
rw [h_sa, h_sb] at h β’,
rw [count_some hp, count_some hp], rw with_top.some_le_some at h,
exact multiset.count_le_of_le _ h
end
omit dec_irr
@[simp] theorem factors_mul (a b : associates Ξ±) :
(a * b).factors = a.factors + b.factors :=
begin
casesI subsingleton_or_nontrivial Ξ±,
{ simp [subsingleton.elim a 0], },
refine (eq_of_prod_eq_prod (eq_of_factors_eq_factors _)),
rw [prod_add, factors_prod, factors_prod, factors_prod],
end
theorem factors_mono : β{a b : associates Ξ±}, a β€ b β a.factors β€ b.factors
| s t β¨d, rflβ© := by rw [factors_mul] ; exact le_add_of_nonneg_right bot_le
theorem factors_le {a b : associates Ξ±} : a.factors β€ b.factors β a β€ b :=
iff.intro
(assume h, have a.factors.prod β€ b.factors.prod, from prod_mono h,
by rwa [factors_prod, factors_prod] at this)
factors_mono
include dec_irr
lemma count_le_count_of_le {a b p : associates Ξ±} (hb : b β 0)
(hp : irreducible p) (h : a β€ b) : p.count a.factors β€ p.count b.factors :=
count_le_count_of_factors_le hb hp $ factors_mono h
omit dec dec' dec_irr
theorem prod_le [nontrivial Ξ±] {a b : factor_set Ξ±} : a.prod β€ b.prod β a β€ b :=
begin
classical,
exact iff.intro
(assume h, have a.prod.factors β€ b.prod.factors, from factors_mono h,
by rwa [prod_factors, prod_factors] at this)
prod_mono
end
include dec dec'
noncomputable instance : has_sup (associates Ξ±) := β¨Ξ»a b, (a.factors β b.factors).prodβ©
noncomputable instance : has_inf (associates Ξ±) := β¨Ξ»a b, (a.factors β b.factors).prodβ©
noncomputable instance : lattice (associates Ξ±) :=
{ sup := (β),
inf := (β),
sup_le :=
assume a b c hac hbc, factors_prod c βΈ prod_mono (sup_le (factors_mono hac) (factors_mono hbc)),
le_sup_left := assume a b,
le_trans (le_of_eq (factors_prod a).symm) $ prod_mono $ le_sup_left,
le_sup_right := assume a b,
le_trans (le_of_eq (factors_prod b).symm) $ prod_mono $ le_sup_right,
le_inf :=
assume a b c hac hbc, factors_prod a βΈ prod_mono (le_inf (factors_mono hac) (factors_mono hbc)),
inf_le_left := assume a b,
le_trans (prod_mono inf_le_left) (le_of_eq (factors_prod a)),
inf_le_right := assume a b,
le_trans (prod_mono inf_le_right) (le_of_eq (factors_prod b)),
.. associates.partial_order }
lemma sup_mul_inf (a b : associates Ξ±) : (a β b) * (a β b) = a * b :=
show (a.factors β b.factors).prod * (a.factors β b.factors).prod = a * b,
begin
nontriviality Ξ±,
refine eq_of_factors_eq_factors _,
rw [β prod_add, prod_factors, factors_mul, factor_set.sup_add_inf_eq_add]
end
include dec_irr
lemma dvd_of_mem_factors {a p : associates Ξ±} {hp : irreducible p}
(hm : p β factors a) : p β£ a :=
begin
by_cases ha0 : a = 0, { rw ha0, exact dvd_zero p },
obtain β¨a0, nza, ha'β© := exists_non_zero_rep ha0,
rw [β associates.factors_prod a],
rw [β ha', factors_mk a0 nza] at hm β’,
erw prod_coe,
apply multiset.dvd_prod, apply multiset.mem_map.mpr,
exact β¨β¨p, hpβ©, mem_factor_set_some.mp hm, rflβ©
end
omit dec'
lemma dvd_of_mem_factors' {a : Ξ±} {p : associates Ξ±} {hp : irreducible p} {hz : a β 0}
(h_mem : subtype.mk p hp β factors' a) : p β£ associates.mk a :=
by { haveI := classical.dec_eq (associates Ξ±),
apply @dvd_of_mem_factors _ _ _ _ _ _ _ _ hp,
rw factors_mk _ hz,
apply mem_factor_set_some.2 h_mem }
omit dec_irr
lemma mem_factors'_of_dvd {a p : Ξ±} (ha0 : a β 0) (hp : irreducible p) (hd : p β£ a) :
subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) β factors' a :=
begin
obtain β¨q, hq, hpqβ© := exists_mem_factors_of_dvd ha0 hp hd,
apply multiset.mem_pmap.mpr, use q, use hq,
exact subtype.eq (eq.symm (mk_eq_mk_iff_associated.mpr hpq))
end
include dec_irr
lemma mem_factors'_iff_dvd {a p : Ξ±} (ha0 : a β 0) (hp : irreducible p) :
subtype.mk (associates.mk p) ((irreducible_mk _).2 hp) β factors' a β p β£ a :=
begin
split,
{ rw β mk_dvd_mk, apply dvd_of_mem_factors', apply ha0 },
{ apply mem_factors'_of_dvd ha0 }
end
include dec'
lemma mem_factors_of_dvd {a p : Ξ±} (ha0 : a β 0) (hp : irreducible p) (hd : p β£ a) :
(associates.mk p) β factors (associates.mk a) :=
begin
rw factors_mk _ ha0, exact mem_factor_set_some.mpr (mem_factors'_of_dvd ha0 hp hd)
end
lemma mem_factors_iff_dvd {a p : Ξ±} (ha0 : a β 0) (hp : irreducible p) :
(associates.mk p) β factors (associates.mk a) β p β£ a :=
begin
split,
{ rw β mk_dvd_mk, apply dvd_of_mem_factors, exact (irreducible_mk p).mpr hp },
{ apply mem_factors_of_dvd ha0 hp }
end
lemma exists_prime_dvd_of_not_inf_one {a b : Ξ±}
(ha : a β 0) (hb : b β 0) (h : (associates.mk a) β (associates.mk b) β 1) :
β (p : Ξ±), prime p β§ p β£ a β§ p β£ b :=
begin
have hz : (factors (associates.mk a)) β (factors (associates.mk b)) β 0,
{ contrapose! h with hf,
change ((factors (associates.mk a)) β (factors (associates.mk b))).prod = 1,
rw hf,
exact multiset.prod_zero },
rw [factors_mk a ha, factors_mk b hb, β with_top.coe_inf] at hz,
obtain β¨β¨p0, p0_irrβ©, p0_memβ© := multiset.exists_mem_of_ne_zero ((mt with_top.coe_eq_coe.mpr) hz),
rw multiset.inf_eq_inter at p0_mem,
obtain β¨p, rflβ© : β p, associates.mk p = p0 := quot.exists_rep p0,
refine β¨p, _, _, _β©,
{ rw [β irreducible_iff_prime, β irreducible_mk],
exact p0_irr },
{ apply dvd_of_mk_le_mk,
apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).left,
apply ha, },
{ apply dvd_of_mk_le_mk,
apply dvd_of_mem_factors' (multiset.mem_inter.mp p0_mem).right,
apply hb }
end
theorem coprime_iff_inf_one {a b : Ξ±} (ha0 : a β 0) (hb0 : b β 0) :
(associates.mk a) β (associates.mk b) = 1 β β {d : Ξ±}, d β£ a β d β£ b β Β¬ prime d :=
begin
split,
{ intros hg p ha hb hp,
refine ((associates.prime_mk _).mpr hp).not_unit (is_unit_of_dvd_one _ _),
rw β hg,
exact le_inf (mk_le_mk_of_dvd ha) (mk_le_mk_of_dvd hb) },
{ contrapose,
intros hg hc,
obtain β¨p, hp, hpa, hpbβ© := exists_prime_dvd_of_not_inf_one ha0 hb0 hg,
exact hc hpa hpb hp }
end
omit dec_irr
theorem factors_self [nontrivial Ξ±] {p : associates Ξ±} (hp : irreducible p) :
p.factors = some ({β¨p, hpβ©}) :=
eq_of_prod_eq_prod (by rw [factors_prod, factor_set.prod, map_singleton, prod_singleton,
subtype.coe_mk])
theorem factors_prime_pow [nontrivial Ξ±] {p : associates Ξ±} (hp : irreducible p)
(k : β) : factors (p ^ k) = some (multiset.repeat β¨p, hpβ© k) :=
eq_of_prod_eq_prod (by rw [associates.factors_prod, factor_set.prod, multiset.map_repeat,
multiset.prod_repeat, subtype.coe_mk])
include dec_irr
theorem prime_pow_dvd_iff_le [nontrivial Ξ±] {m p : associates Ξ±} (hβ : m β 0)
(hβ : irreducible p) {k : β} : p ^ k β€ m β k β€ count p m.factors :=
begin
obtain β¨a, nz, rflβ© := associates.exists_non_zero_rep hβ,
rw [factors_mk _ nz, β with_top.some_eq_coe, count_some, multiset.le_count_iff_repeat_le,
β factors_le, factors_prime_pow hβ, factors_mk _ nz],
exact with_top.coe_le_coe
end
theorem le_of_count_ne_zero {m p : associates Ξ±} (h0 : m β 0)
(hp : irreducible p) : count p m.factors β 0 β p β€ m :=
begin
nontriviality Ξ±,
rw [β pos_iff_ne_zero],
intro h,
rw [β pow_one p],
apply (prime_pow_dvd_iff_le h0 hp).2,
simpa only
end
theorem count_ne_zero_iff_dvd {a p : Ξ±} (ha0 : a β 0) (hp : irreducible p) :
(associates.mk p).count (associates.mk a).factors β 0 β p β£ a :=
begin
nontriviality Ξ±,
rw β associates.mk_le_mk_iff_dvd_iff,
refine β¨Ξ» h, associates.le_of_count_ne_zero (associates.mk_ne_zero.mpr ha0)
((associates.irreducible_mk p).mpr hp) h, Ξ» h, _β©,
{ rw [β pow_one (associates.mk p), associates.prime_pow_dvd_iff_le
(associates.mk_ne_zero.mpr ha0) ((associates.irreducible_mk p).mpr hp)] at h,
exact (zero_lt_one.trans_le h).ne' }
end
theorem count_self [nontrivial Ξ±] {p : associates Ξ±} (hp : irreducible p) :
p.count p.factors = 1 :=
by simp [factors_self hp, associates.count_some hp]
lemma count_eq_zero_of_ne {p q : associates Ξ±} (hp : irreducible p) (hq : irreducible q)
(h : p β q) : p.count q.factors = 0 :=
not_ne_iff.mp $ Ξ» h', h $ associated_iff_eq.mp $ hp.associated_of_dvd hq $
by { nontriviality Ξ±, exact le_of_count_ne_zero hq.ne_zero hp h' }
theorem count_mul {a : associates Ξ±} (ha : a β 0) {b : associates Ξ±} (hb : b β 0)
{p : associates Ξ±} (hp : irreducible p) :
count p (factors (a * b)) = count p a.factors + count p b.factors :=
begin
obtain β¨a0, nza, ha'β© := exists_non_zero_rep ha,
obtain β¨b0, nzb, hb'β© := exists_non_zero_rep hb,
rw [factors_mul, β ha', β hb', factors_mk a0 nza, factors_mk b0 nzb, β factor_set.coe_add,
β with_top.some_eq_coe, β with_top.some_eq_coe, β with_top.some_eq_coe, count_some hp,
multiset.count_add, count_some hp, count_some hp]
end
theorem count_of_coprime {a : associates Ξ±} (ha : a β 0) {b : associates Ξ±}
(hb : b β 0)
(hab : β d, d β£ a β d β£ b β Β¬ prime d) {p : associates Ξ±} (hp : irreducible p) :
count p a.factors = 0 β¨ count p b.factors = 0 :=
begin
rw [or_iff_not_imp_left, β ne.def],
intro hca,
contrapose! hab with hcb,
exact β¨p, le_of_count_ne_zero ha hp hca, le_of_count_ne_zero hb hp hcb,
(irreducible_iff_prime.mp hp)β©,
end
theorem count_mul_of_coprime {a : associates Ξ±} {b : associates Ξ±}
(hb : b β 0)
{p : associates Ξ±} (hp : irreducible p) (hab : β d, d β£ a β d β£ b β Β¬ prime d) :
count p a.factors = 0 β¨ count p a.factors = count p (a * b).factors :=
begin
by_cases ha : a = 0,
{ simp [ha], },
cases count_of_coprime ha hb hab hp with hz hb0, { tauto },
apply or.intro_right,
rw [count_mul ha hb hp, hb0, add_zero]
end
theorem count_mul_of_coprime' {a b : associates Ξ±}
{p : associates Ξ±} (hp : irreducible p) (hab : β d, d β£ a β d β£ b β Β¬ prime d) :
count p (a * b).factors = count p a.factors
β¨ count p (a * b).factors = count p b.factors :=
begin
by_cases ha : a = 0, { simp [ha], },
by_cases hb : b = 0, { simp [hb], },
rw [count_mul ha hb hp],
cases count_of_coprime ha hb hab hp with ha0 hb0,
{ apply or.intro_right, rw [ha0, zero_add] },
{ apply or.intro_left, rw [hb0, add_zero] }
end
theorem dvd_count_of_dvd_count_mul {a b : associates Ξ±} (hb : b β 0)
{p : associates Ξ±} (hp : irreducible p) (hab : β d, d β£ a β d β£ b β Β¬ prime d)
{k : β} (habk : k β£ count p (a * b).factors) : k β£ count p a.factors :=
begin
by_cases ha : a = 0, { simpa [*] using habk, },
cases count_of_coprime ha hb hab hp with hz h,
{ rw hz, exact dvd_zero k },
{ rw [count_mul ha hb hp, h] at habk, exact habk }
end
omit dec_irr
@[simp] lemma factors_one [nontrivial Ξ±] : factors (1 : associates Ξ±) = 0 :=
begin
apply eq_of_prod_eq_prod,
rw associates.factors_prod,
exact multiset.prod_zero,
end
@[simp] theorem pow_factors [nontrivial Ξ±] {a : associates Ξ±} {k : β} :
(a ^ k).factors = k β’ a.factors :=
begin
induction k with n h,
{ rw [zero_nsmul, pow_zero], exact factors_one },
{ rw [pow_succ, succ_nsmul, factors_mul, h] }
end
include dec_irr
lemma count_pow [nontrivial Ξ±] {a : associates Ξ±} (ha : a β 0) {p : associates Ξ±}
(hp : irreducible p)
(k : β) : count p (a ^ k).factors = k * count p a.factors :=
begin
induction k with n h,
{ rw [pow_zero, factors_one, zero_mul, count_zero hp] },
{ rw [pow_succ, count_mul ha (pow_ne_zero _ ha) hp, h, nat.succ_eq_add_one], ring }
end
theorem dvd_count_pow [nontrivial Ξ±] {a : associates Ξ±} (ha : a β 0) {p : associates Ξ±}
(hp : irreducible p)
(k : β) : k β£ count p (a ^ k).factors := by { rw count_pow ha hp, apply dvd_mul_right }
theorem is_pow_of_dvd_count [nontrivial Ξ±] {a : associates Ξ±} (ha : a β 0) {k : β}
(hk : β (p : associates Ξ±) (hp : irreducible p), k β£ count p a.factors) :
β (b : associates Ξ±), a = b ^ k :=
begin
obtain β¨a0, hz, rflβ© := exists_non_zero_rep ha,
rw [factors_mk a0 hz] at hk,
have hk' : β p, p β (factors' a0) β k β£ (factors' a0).count p,
{ rintros p -,
have pp : p = β¨p.val, p.2β©, { simp only [subtype.coe_eta, subtype.val_eq_coe] },
rw [pp, β count_some p.2], exact hk p.val p.2 },
obtain β¨u, huβ© := multiset.exists_smul_of_dvd_count _ hk',
use (u : factor_set Ξ±).prod,
apply eq_of_factors_eq_factors,
rw [pow_factors, prod_factors, factors_mk a0 hz, β with_top.some_eq_coe, hu],
exact with_bot.coe_nsmul u k
end
/-- The only divisors of prime powers are prime powers. See `eq_pow_find_of_dvd_irreducible_pow`
for an explicit expression as a p-power (without using `count`). -/
theorem eq_pow_count_factors_of_dvd_pow {p a : associates Ξ±} (hp : irreducible p)
{n : β} (h : a β£ p ^ n) : a = p ^ p.count a.factors :=
begin
nontriviality Ξ±,
have hph := pow_ne_zero n hp.ne_zero,
have ha := ne_zero_of_dvd_ne_zero hph h,
apply eq_of_eq_counts ha (pow_ne_zero _ hp.ne_zero),
have eq_zero_of_ne : β (q : associates Ξ±), irreducible q β q β p β _ = 0 :=
Ξ» q hq h', nat.eq_zero_of_le_zero $ by
{ convert count_le_count_of_le hph hq h, symmetry,
rw [count_pow hp.ne_zero hq, count_eq_zero_of_ne hq hp h', mul_zero] },
intros q hq,
rw count_pow hp.ne_zero hq,
by_cases h : q = p,
{ rw [h, count_self hp, mul_one] },
{ rw [count_eq_zero_of_ne hq hp h, mul_zero, eq_zero_of_ne q hq h] }
end
lemma count_factors_eq_find_of_dvd_pow {a p : associates Ξ±} (hp : irreducible p)
[β n : β, decidable (a β£ p ^ n)] {n : β} (h : a β£ p ^ n) : nat.find β¨n, hβ© = p.count a.factors :=
begin
apply le_antisymm,
{ refine nat.find_le β¨1, _β©, rw mul_one, symmetry, exact eq_pow_count_factors_of_dvd_pow hp h },
{ have hph := pow_ne_zero (nat.find β¨n, hβ©) hp.ne_zero,
casesI (subsingleton_or_nontrivial Ξ±) with hΞ± hΞ±,
{ simpa using hph, },
convert count_le_count_of_le hph hp (nat.find_spec β¨n, hβ©),
rw [count_pow hp.ne_zero hp, count_self hp, mul_one] }
end
omit dec
omit dec_irr
omit dec'
theorem eq_pow_of_mul_eq_pow [nontrivial Ξ±] {a b c : associates Ξ±} (ha : a β 0) (hb : b β 0)
(hab : β d, d β£ a β d β£ b β Β¬ prime d) {k : β} (h : a * b = c ^ k) :
β (d : associates Ξ±), a = d ^ k :=
begin
classical,
by_cases hk0 : k = 0,
{ use 1,
rw [hk0, pow_zero] at h β’,
apply (mul_eq_one_iff.1 h).1 },
{ refine is_pow_of_dvd_count ha _,
intros p hp,
apply dvd_count_of_dvd_count_mul hb hp hab,
rw h,
apply dvd_count_pow _ hp,
rintros rfl,
rw zero_pow' _ hk0 at h,
cases mul_eq_zero.mp h; contradiction }
end
/-- The only divisors of prime powers are prime powers. -/
theorem eq_pow_find_of_dvd_irreducible_pow {a p : associates Ξ±} (hp : irreducible p)
[β n : β, decidable (a β£ p ^ n)] {n : β} (h : a β£ p ^ n) : a = p ^ nat.find β¨n, hβ© :=
by { classical, rw [count_factors_eq_find_of_dvd_pow hp, β eq_pow_count_factors_of_dvd_pow hp h] }
end associates
section
open associates unique_factorization_monoid
lemma associates.quot_out {Ξ± : Type*} [comm_monoid Ξ±] (a : associates Ξ±):
associates.mk (quot.out (a)) = a :=
by rw [βquot_mk_eq_mk, quot.out_eq]
/-- `to_gcd_monoid` constructs a GCD monoid out of a unique factorization domain. -/
noncomputable def unique_factorization_monoid.to_gcd_monoid
(Ξ± : Type*) [cancel_comm_monoid_with_zero Ξ±] [unique_factorization_monoid Ξ±]
[decidable_eq (associates Ξ±)] [decidable_eq Ξ±] : gcd_monoid Ξ± :=
{ gcd := Ξ»a b, quot.out (associates.mk a β associates.mk b : associates Ξ±),
lcm := Ξ»a b, quot.out (associates.mk a β associates.mk b : associates Ξ±),
gcd_dvd_left := Ξ» a b, by
{ rw [βmk_dvd_mk, (associates.mk a β associates.mk b).quot_out, dvd_eq_le],
exact inf_le_left },
gcd_dvd_right := Ξ» a b, by
{ rw [βmk_dvd_mk, (associates.mk a β associates.mk b).quot_out, dvd_eq_le],
exact inf_le_right },
dvd_gcd := Ξ» a b c hac hab, by
{ rw [βmk_dvd_mk, (associates.mk c β associates.mk b).quot_out, dvd_eq_le,
le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff],
exact β¨hac, habβ© },
lcm_zero_left := Ξ» a, by
{ have : associates.mk (0 : Ξ±) = β€ := rfl,
rw [this, top_sup_eq, βthis, βassociated_zero_iff_eq_zero, βmk_eq_mk_iff_associated,
βassociated_iff_eq, associates.quot_out] },
lcm_zero_right := Ξ» a, by
{ have : associates.mk (0 : Ξ±) = β€ := rfl,
rw [this, sup_top_eq, βthis, βassociated_zero_iff_eq_zero, βmk_eq_mk_iff_associated,
βassociated_iff_eq, associates.quot_out] },
gcd_mul_lcm := Ξ» a b, by
{ rw [βmk_eq_mk_iff_associated, βassociates.mk_mul_mk, βassociated_iff_eq, associates.quot_out,
associates.quot_out, mul_comm, sup_mul_inf, associates.mk_mul_mk] } }
/-- `to_normalized_gcd_monoid` constructs a GCD monoid out of a normalization on a
unique factorization domain. -/
noncomputable def unique_factorization_monoid.to_normalized_gcd_monoid
(Ξ± : Type*) [cancel_comm_monoid_with_zero Ξ±] [unique_factorization_monoid Ξ±]
[normalization_monoid Ξ±] [decidable_eq (associates Ξ±)] [decidable_eq Ξ±] :
normalized_gcd_monoid Ξ± :=
{ gcd := Ξ»a b, (associates.mk a β associates.mk b).out,
lcm := Ξ»a b, (associates.mk a β associates.mk b).out,
gcd_dvd_left := assume a b, (out_dvd_iff a (associates.mk a β associates.mk b)).2 $ inf_le_left,
gcd_dvd_right := assume a b, (out_dvd_iff b (associates.mk a β associates.mk b)).2 $ inf_le_right,
dvd_gcd := assume a b c hac hab, show a β£ (associates.mk c β associates.mk b).out,
by rw [dvd_out_iff, le_inf_iff, mk_le_mk_iff_dvd_iff, mk_le_mk_iff_dvd_iff]; exact β¨hac, habβ©,
lcm_zero_left := assume a, show (β€ β associates.mk a).out = 0, by simp,
lcm_zero_right := assume a, show (associates.mk a β β€).out = 0, by simp,
gcd_mul_lcm := assume a b, by
{ rw [β out_mul, mul_comm, sup_mul_inf, mk_mul_mk, out_mk],
exact normalize_associated (a * b) },
normalize_gcd := assume a b, by convert normalize_out _,
normalize_lcm := assume a b, by convert normalize_out _,
.. βΉnormalization_monoid Ξ±βΊ }
end
namespace unique_factorization_monoid
/-- If `y` is a nonzero element of a unique factorization monoid with finitely
many units (e.g. `β€`, `ideal (ring_of_integers K)`), it has finitely many divisors. -/
noncomputable def fintype_subtype_dvd {M : Type*} [cancel_comm_monoid_with_zero M]
[unique_factorization_monoid M] [fintype MΛ£]
(y : M) (hy : y β 0) :
fintype {x // x β£ y} :=
begin
haveI : nontrivial M := β¨β¨y, 0, hyβ©β©,
haveI : normalization_monoid M := unique_factorization_monoid.normalization_monoid,
haveI := classical.dec_eq M,
haveI := classical.dec_eq (associates M),
-- We'll show `Ξ» (u : MΛ£) (f β factors y) β u * Ξ f` is injective
-- and has image exactly the divisors of `y`.
refine fintype.of_finset
(((normalized_factors y).powerset.to_finset.product (finset.univ : finset MΛ£)).image
(Ξ» s, (s.snd : M) * s.fst.prod))
(Ξ» x, _),
simp only [exists_prop, finset.mem_image, finset.mem_product, finset.mem_univ, and_true,
multiset.mem_to_finset, multiset.mem_powerset, exists_eq_right, multiset.mem_map],
split,
{ rintros β¨s, hs, rflβ©,
have prod_s_ne : s.fst.prod β 0,
{ intro hz,
apply hy (eq_zero_of_zero_dvd _),
have hz := (@multiset.prod_eq_zero_iff M _ _ _ s.fst).mp hz,
rw β (normalized_factors_prod hy).dvd_iff_dvd_right,
exact multiset.dvd_prod (multiset.mem_of_le hs hz) },
show (s.snd : M) * s.fst.prod β£ y,
rw [(unit_associated_one.mul_right s.fst.prod).dvd_iff_dvd_left, one_mul,
β (normalized_factors_prod hy).dvd_iff_dvd_right],
exact multiset.prod_dvd_prod_of_le hs },
{ rintro (h : x β£ y),
have hx : x β 0, { refine mt (Ξ» hx, _) hy, rwa [hx, zero_dvd_iff] at h },
obtain β¨u, huβ© := normalized_factors_prod hx,
refine β¨β¨normalized_factors x, uβ©, _, (mul_comm _ _).trans huβ©,
exact (dvd_iff_normalized_factors_le_normalized_factors hx hy).mp h }
end
end unique_factorization_monoid
section finsupp
variables [cancel_comm_monoid_with_zero Ξ±] [unique_factorization_monoid Ξ±]
variables [normalization_monoid Ξ±] [decidable_eq Ξ±]
open unique_factorization_monoid
/-- This returns the multiset of irreducible factors as a `finsupp` -/
noncomputable def factorization (n : Ξ±) : Ξ± ββ β := (normalized_factors n).to_finsupp
lemma factorization_eq_count {n p : Ξ±} :
factorization n p = multiset.count p (normalized_factors n) :=
by simp [factorization]
@[simp] lemma factorization_zero : factorization (0 : Ξ±) = 0 := by simp [factorization]
@[simp] lemma factorization_one : factorization (1 : Ξ±) = 0 := by simp [factorization]
/-- The support of `factorization n` is exactly the finset of normalized factors -/
@[simp] lemma support_factorization {n : Ξ±} :
(factorization n).support = (normalized_factors n).to_finset :=
by simp [factorization, multiset.to_finsupp_support]
/-- For nonzero `a` and `b`, the power of `p` in `a * b` is the sum of the powers in `a` and `b` -/
@[simp] lemma factorization_mul {a b : Ξ±} (ha : a β 0) (hb : b β 0) :
factorization (a * b) = factorization a + factorization b :=
by simp [factorization, normalized_factors_mul ha hb]
/-- For any `p`, the power of `p` in `x^n` is `n` times the power in `x` -/
lemma factorization_pow {x : Ξ±} {n : β} :
factorization (x^n) = n β’ factorization x :=
by { ext, simp [factorization] }
lemma associated_of_factorization_eq (a b: Ξ±) (ha: a β 0) (hb: b β 0)
(h: factorization a = factorization b) : associated a b :=
begin
simp only [factorization, add_equiv.apply_eq_iff_eq] at h,
have ha' := normalized_factors_prod ha,
rw h at ha',
exact associated.trans ha'.symm (normalized_factors_prod hb),
end
end finsupp
|
359028f59688248c614c709e487093b7ebc27faa | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/topology/uniform_space/UniformSpace.lean | 01b60488d27bce502679337efeb69a23704178eb | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 6,266 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Reid Barton, Patrick Massot, Scott Morrison
-/
import category_theory.concrete_category
import category_theory.full_subcategory
import category_theory.monad.limits
import topology.uniform_space.completion
import topology.Top.basic
/-!
# The category of uniform spaces
We construct the category of uniform spaces, show that the complete separated uniform spaces
form a reflective subcategory, and hence possess all limits that uniform spaces do.
TODO: show that uniform spaces actually have all limits!
-/
universes u
open category_theory
/-- A (bundled) uniform spaces. -/
@[reducible] def UniformSpace : Type (u+1) := bundled uniform_space
namespace UniformSpace
instance (x : UniformSpace) : uniform_space x := x.str
/-- The category instance on `UniformSpace`. -/
instance concrete_category_uniform_continuous : concrete_category @uniform_continuous :=
β¨@uniform_continuous_id, by { introsI, apply uniform_continuous.comp; assumption }β©
def of (Ξ± : Type u) [uniform_space Ξ±] : UniformSpace := β¨Ξ±β©
abbreviation forget : UniformSpace.{u} β₯€ Type u := forget
instance forget.faithful : faithful (forget) := {}
/-- The forgetful functor from uniform spaces to topological spaces. -/
def forget_to_Top : UniformSpace.{u} β₯€ Top.{u} :=
{ obj := Ξ» X, { Ξ± := X.1 },
map := Ξ» X Y f, β¨ f, uniform_continuous.continuous f.property β© }
/-- The natural isomorphism between forgetting from `UniformSpace` to `Type` via `Top`,
and forgetting directly. -/
def forget_to_Type_via_Top : forget_to_Top β Top.forget β
forget := iso.refl _
end UniformSpace
/-- A (bundled) complete separated uniform space. -/
structure CpltSepUniformSpace :=
(Ξ± : Type u)
[is_uniform_space : uniform_space Ξ±]
[is_complete_space : complete_space Ξ±]
[is_separated : separated Ξ±]
namespace CpltSepUniformSpace
instance : has_coe_to_sort CpltSepUniformSpace :=
{ S := Type u, coe := CpltSepUniformSpace.Ξ± }
attribute [instance] is_uniform_space is_complete_space is_separated
def to_UniformSpace (X : CpltSepUniformSpace) : UniformSpace :=
β¨Xβ©
instance (X : CpltSepUniformSpace) : complete_space ((to_UniformSpace X).Ξ±) := CpltSepUniformSpace.is_complete_space X
instance (X : CpltSepUniformSpace) : separated ((to_UniformSpace X).Ξ±) := CpltSepUniformSpace.is_separated X
/-- The category instance on `CpltSepUniformSpace`. -/
instance CpltSepUniformSpace_category : category CpltSepUniformSpace :=
induced_category.category to_UniformSpace
def of (X : Type u) [uniform_space X] [complete_space X] [separated X] : CpltSepUniformSpace := β¨Xβ©
def forget_to_UniformSpace : CpltSepUniformSpace β₯€ UniformSpace := induced_functor to_UniformSpace
/-- The forgetful functor from complete separated uniform spaces to `Type`. -/
def forget : CpltSepUniformSpace β₯€ Type u :=
{ obj := Ξ» R, R,
map := Ξ» R S f, f.1 }
instance forget_faithful : faithful forget := {}
instance forget_to_UniformSpace_full : full forget_to_UniformSpace :=
induced_category.full _
instance forget_to_UniformSpace_faithful : faithful forget_to_UniformSpace :=
induced_category.faithful _
/-- The natural isomorphism between forgetting from `CpltSepUniformSpace` to `Type` via `UniformSpace`,
and forgetting directly. -/
def forget_to_Type_via_UniformSpace : forget_to_UniformSpace β UniformSpace.forget β
forget := iso.refl _
end CpltSepUniformSpace
namespace UniformSpace
open uniform_space
open CpltSepUniformSpace
/-- The functor turning uniform spaces into complete separated uniform spaces. -/
noncomputable def completion_functor : UniformSpace β₯€ CpltSepUniformSpace :=
{ obj := Ξ» X, CpltSepUniformSpace.of (completion X),
map := Ξ» X Y f, β¨completion.map f.1, completion.uniform_continuous_mapβ©,
map_comp' := Ξ» X Y Z f g,
begin cases f, cases g, apply subtype.ext.2, dsimp, rw βcompletion.map_comp; assumption end }.
/-- The inclusion of any uniform spaces into its completion. -/
def completion_hom (X : UniformSpace) : X βΆ forget_to_UniformSpace.obj (completion_functor.obj X) :=
{ val := (coe : X β completion X),
property := completion.uniform_continuous_coe X }
@[simp] lemma completion_hom_val (X : UniformSpace) (x) :
(completion_hom X) x = (x : completion X) := rfl
/-- The mate of a morphism from a `UniformSpace` to a `CpltSepUniformSpace`. -/
noncomputable def extension_hom {X : UniformSpace} {Y : CpltSepUniformSpace} (f : X βΆ forget_to_UniformSpace.obj Y) :
completion_functor.obj X βΆ Y :=
{ val := completion.extension f,
property := completion.uniform_continuous_extension }
@[simp] lemma extension_hom_val {X : UniformSpace} {Y : CpltSepUniformSpace}
(f : X βΆ forget_to_UniformSpace.obj Y) (x) :
(extension_hom f) x = completion.extension f x := rfl.
@[simp] lemma extension_comp_coe {X : UniformSpace} {Y : CpltSepUniformSpace}
(f : to_UniformSpace (CpltSepUniformSpace.of (completion X)) βΆ to_UniformSpace Y) :
extension_hom (completion_hom X β« f) = f :=
by { ext x, exact congr_fun (completion.extension_comp_coe f.property) x }
/-- The completion functor is left adjoint to the forgetful functor. -/
noncomputable def adj : completion_functor β£ forget_to_UniformSpace :=
adjunction.mk_of_hom_equiv
{ hom_equiv := Ξ» X Y,
{ to_fun := Ξ» f, completion_hom X β« f,
inv_fun := Ξ» f, extension_hom f,
left_inv := Ξ» f, by { dsimp, erw extension_comp_coe },
right_inv := Ξ» f,
begin
ext1, cases f,
change completion.extension f_val _ = f_val x,
erw completion.extension_coe, assumption
end },
hom_equiv_naturality_left_symm' := Ξ» X X' Y f g,
begin
ext1, dsimp,
erw βcompletion.extension_map,
refl, exact g.property, exact f.property,
end }
noncomputable instance : is_right_adjoint forget_to_UniformSpace :=
β¨completion_functor, adjβ©
noncomputable instance : reflective forget_to_UniformSpace := {}
open category_theory.limits
-- TODO Once someone defines `has_limits UniformSpace`, turn this into an instance.
noncomputable example [has_limits.{u} UniformSpace.{u}] : has_limits.{u} CpltSepUniformSpace.{u} :=
has_limits_of_reflective forget_to_UniformSpace
end UniformSpace
|
09ba396ca15bde1196cd7782f7b76f70a4cd68d8 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/combinatorics/simple_graph/regularity/bound.lean | 0142d46464d4b8fc3f5663548aa36db2547add1b | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 10,115 | lean | /-
Copyright (c) 2022 YaΓ«l Dillies, Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: YaΓ«l Dillies, Bhavik Mehta
-/
import algebra.order.chebyshev
import analysis.special_functions.pow
import order.partition.equipartition
/-!
# Numerical bounds for SzemerΓ©di Regularity Lemma
This file gathers the numerical facts required by the proof of SzemerΓ©di's regularity lemma.
This entire file is internal to the proof of SzemerΓ©di Regularity Lemma.
## Main declarations
* `szemeredi_regularity.step_bound`: During the inductive step, a partition of size `n` is blown to
size at most `step_bound n`.
* `szemeredi_regularity.initial_bound`: The size of the partition we start the induction with.
* `szemeredi_regularity.bound`: The upper bound on the size of the partition produced by our version
of SzemerΓ©di's regularity lemma.
-/
open finset fintype function real
open_locale big_operators
namespace szemeredi_regularity
/-- Auxiliary function for SzemerΓ©di's regularity lemma. Blowing up a partition of size `n` during
the induction results in a partition of size at most `step_bound n`. -/
def step_bound (n : β) : β := n * 4 ^ n
lemma le_step_bound : id β€ step_bound := Ξ» n, nat.le_mul_of_pos_right $ pow_pos (by norm_num) n
lemma step_bound_mono : monotone step_bound :=
Ξ» a b h, nat.mul_le_mul h $ nat.pow_le_pow_of_le_right (by norm_num) h
lemma step_bound_pos_iff {n : β} : 0 < step_bound n β 0 < n := zero_lt_mul_right $ by positivity
alias step_bound_pos_iff β _ step_bound_pos
end szemeredi_regularity
open szemeredi_regularity
variables {Ξ± : Type*} [decidable_eq Ξ±] [fintype Ξ±] {P : finpartition (univ : finset Ξ±)}
{u : finset Ξ±} {Ξ΅ : β}
local notation `m` := (card Ξ±/step_bound P.parts.card : β)
local notation `a` := (card Ξ±/P.parts.card - m * 4^P.parts.card : β)
namespace tactic
open positivity
private lemma eps_pos {Ξ΅ : β} {n : β} (h : 100 β€ 4 ^ n * Ξ΅^5) : 0 < Ξ΅ :=
pow_bit1_pos_iff.1 $ pos_of_mul_pos_right (h.trans_lt' $ by norm_num) $ by positivity
private lemma m_pos [nonempty Ξ±] (hPΞ± : P.parts.card * 16^P.parts.card β€ card Ξ±) : 0 < m :=
nat.div_pos ((nat.mul_le_mul_left _ $ nat.pow_le_pow_of_le_left (by norm_num) _).trans hPΞ±) $
step_bound_pos (P.parts_nonempty $ univ_nonempty.ne_empty).card_pos
/-- Local extension for the `positivity` tactic: A few facts that are needed many times for the
proof of SzemerΓ©di's regularity lemma. -/
meta def positivity_szemeredi_regularity : expr β tactic strictness
| `(%%n / step_bound (finpartition.parts %%P).card) := do
p β to_expr
``((finpartition.parts %%P).card * 16^(finpartition.parts %%P).card β€ %%n)
>>= find_assumption,
positive <$> mk_app ``m_pos [p]
| Ξ΅ := do
typ β infer_type Ξ΅,
unify typ `(β),
p β to_expr ``(100 β€ 4 ^ _ * %%Ξ΅ ^ 5) >>= find_assumption,
positive <$> mk_app ``eps_pos [p]
end tactic
local attribute [positivity] tactic.positivity_szemeredi_regularity
namespace szemeredi_regularity
lemma m_pos [nonempty Ξ±] (hPΞ± : P.parts.card * 16^P.parts.card β€ card Ξ±) : 0 < m := by positivity
lemma coe_m_add_one_pos : 0 < (m : β) + 1 := by positivity
lemma one_le_m_coe [nonempty Ξ±] (hPΞ± : P.parts.card * 16^P.parts.card β€ card Ξ±) : (1 : β) β€ m :=
nat.one_le_cast.2 $ m_pos hPΞ±
lemma eps_pow_five_pos (hPΞ΅ : 100 β€ 4^P.parts.card * Ξ΅^5) : 0 < Ξ΅^5 :=
pos_of_mul_pos_right ((by norm_num : (0 : β) < 100).trans_le hPΞ΅) $ pow_nonneg (by norm_num) _
lemma eps_pos (hPΞ΅ : 100 β€ 4^P.parts.card * Ξ΅^5) : 0 < Ξ΅ :=
pow_bit1_pos_iff.1 $ eps_pow_five_pos hPΞ΅
lemma hundred_div_Ξ΅_pow_five_le_m [nonempty Ξ±] (hPΞ± : P.parts.card * 16^P.parts.card β€ card Ξ±)
(hPΞ΅ : 100 β€ 4^P.parts.card * Ξ΅^5) :
100 / Ξ΅^5 β€ m :=
(div_le_of_nonneg_of_le_mul (eps_pow_five_pos hPΞ΅).le (by positivity) hPΞ΅).trans
begin
norm_cast,
rwa [nat.le_div_iff_mul_le'(step_bound_pos (P.parts_nonempty $ univ_nonempty.ne_empty).card_pos),
step_bound, mul_left_comm, βmul_pow],
end
lemma hundred_le_m [nonempty Ξ±] (hPΞ± : P.parts.card * 16^P.parts.card β€ card Ξ±)
(hPΞ΅ : 100 β€ 4^P.parts.card * Ξ΅^5) (hΞ΅ : Ξ΅ β€ 1) : 100 β€ m :=
by exact_mod_cast (hundred_div_Ξ΅_pow_five_le_m hPΞ± hPΞ΅).trans'
(le_div_self (by norm_num) (by positivity) $ pow_le_one _ (by positivity) hΞ΅)
lemma a_add_one_le_four_pow_parts_card : a + 1 β€ 4^P.parts.card :=
begin
have h : 1 β€ 4^P.parts.card := one_le_pow_of_one_le (by norm_num) _,
rw [step_bound, βnat.div_div_eq_div_mul, βnat.le_sub_iff_right h, tsub_le_iff_left,
βnat.add_sub_assoc h],
exact nat.le_pred_of_lt (nat.lt_div_mul_add h),
end
lemma card_auxβ (hucard : u.card = m * 4^P.parts.card + a) :
(4^P.parts.card - a) * m + a * (m + 1) = u.card :=
by rw [hucard, mul_add, mul_one, βadd_assoc, βadd_mul, nat.sub_add_cancel
((nat.le_succ _).trans a_add_one_le_four_pow_parts_card), mul_comm]
lemma card_auxβ (hP : P.is_equipartition) (hu : u β P.parts)
(hucard : Β¬u.card = m * 4^P.parts.card + a) :
(4^P.parts.card - (a + 1)) * m + (a + 1) * (m + 1) = u.card :=
begin
have : m * 4 ^ P.parts.card β€ card Ξ± / P.parts.card,
{ rw [step_bound, βnat.div_div_eq_div_mul],
exact nat.div_mul_le_self _ _ },
rw nat.add_sub_of_le this at hucard,
rw [(hP.card_parts_eq_average hu).resolve_left hucard, mul_add, mul_one, βadd_assoc, βadd_mul,
nat.sub_add_cancel a_add_one_le_four_pow_parts_card, βadd_assoc, mul_comm,
nat.add_sub_of_le this, card_univ],
end
lemma pow_mul_m_le_card_part (hP : P.is_equipartition) (hu : u β P.parts) :
(4 : β) ^ P.parts.card * m β€ u.card :=
begin
norm_cast,
rw [step_bound, βnat.div_div_eq_div_mul],
exact (nat.mul_div_le _ _).trans (hP.average_le_card_part hu),
end
variables (P Ξ΅) (l : β)
/-- Auxiliary function for SzemerΓ©di's regularity lemma. The size of the partition by which we start
blowing. -/
noncomputable def initial_bound : β := max 7 $ max l $ βlog (100 / Ξ΅^5) / log 4ββ + 1
lemma le_initial_bound : l β€ initial_bound Ξ΅ l := (le_max_left _ _).trans $ le_max_right _ _
lemma seven_le_initial_bound : 7 β€ initial_bound Ξ΅ l := le_max_left _ _
lemma initial_bound_pos : 0 < initial_bound Ξ΅ l :=
nat.succ_pos'.trans_le $ seven_le_initial_bound _ _
lemma hundred_lt_pow_initial_bound_mul {Ξ΅ : β} (hΞ΅ : 0 < Ξ΅) (l : β) :
100 < 4^initial_bound Ξ΅ l * Ξ΅^5 :=
begin
rw [βrpow_nat_cast 4, βdiv_lt_iff (pow_pos hΞ΅ 5), lt_rpow_iff_log_lt _ zero_lt_four,
βdiv_lt_iff, initial_bound, nat.cast_max, nat.cast_max],
{ push_cast, exact lt_max_of_lt_right (lt_max_of_lt_right $ nat.lt_floor_add_one _) },
{ exact log_pos (by norm_num) },
{ exact div_pos (by norm_num) (pow_pos hΞ΅ 5) }
end
/-- An explicit bound on the size of the equipartition whose existence is given by SzemerΓ©di's
regularity lemma. -/
noncomputable def bound : β :=
(step_bound^[β4 / Ξ΅^5ββ] $ initial_bound Ξ΅ l) * 16 ^ (step_bound^[β4 / Ξ΅^5ββ] $ initial_bound Ξ΅ l)
lemma initial_bound_le_bound : initial_bound Ξ΅ l β€ bound Ξ΅ l :=
(id_le_iterate_of_id_le le_step_bound _ _).trans $ nat.le_mul_of_pos_right $ by positivity
lemma le_bound : l β€ bound Ξ΅ l := (le_initial_bound Ξ΅ l).trans $ initial_bound_le_bound Ξ΅ l
lemma bound_pos : 0 < bound Ξ΅ l := (initial_bound_pos Ξ΅ l).trans_le $ initial_bound_le_bound Ξ΅ l
variables {ΞΉ π : Type*} [linear_ordered_field π] (r : ΞΉ β ΞΉ β Prop) [decidable_rel r]
{s t : finset ΞΉ} {x : π}
lemma mul_sq_le_sum_sq (hst : s β t) (f : ΞΉ β π) (hs : x^2 β€ ((β i in s, f i) / s.card) ^ 2)
(hs' : (s.card : π) β 0) :
(s.card : π) * x ^ 2 β€ β i in t, f i ^ 2 :=
(mul_le_mul_of_nonneg_left (hs.trans sum_div_card_sq_le_sum_sq_div_card) $
nat.cast_nonneg _).trans $ (mul_div_cancel' _ hs').le.trans $ sum_le_sum_of_subset_of_nonneg hst $
Ξ» i _ _, sq_nonneg _
lemma add_div_le_sum_sq_div_card (hst : s β t) (f : ΞΉ β π) (d : π) (hx : 0 β€ x)
(hs : x β€ |(β i in s, f i)/s.card - (β i in t, f i)/t.card|)
(ht : d β€ ((β i in t, f i)/t.card)^2) :
d + s.card/t.card * x^2 β€ (β i in t, f i^2)/t.card :=
begin
obtain hscard | hscard := (s.card.cast_nonneg : (0 : π) β€ s.card).eq_or_lt,
{ simpa [βhscard] using ht.trans sum_div_card_sq_le_sum_sq_div_card },
have htcard : (0:π) < t.card := hscard.trans_le (nat.cast_le.2 (card_le_of_subset hst)),
have hβ : x^2 β€ ((β i in s, f i)/s.card - (β i in t, f i)/t.card)^2 :=
sq_le_sq.2 (by rwa [abs_of_nonneg hx]),
have hβ : x^2 β€ ((β i in s, (f i - (β j in t, f j)/t.card))/s.card)^2,
{ apply hβ.trans,
rw [sum_sub_distrib, sum_const, nsmul_eq_mul, sub_div, mul_div_cancel_left _ hscard.ne'] },
apply (add_le_add_right ht _).trans,
rw [βmul_div_right_comm, le_div_iff htcard, add_mul, div_mul_cancel _ htcard.ne'],
have hβ := mul_sq_le_sum_sq hst (Ξ» i, f i - (β j in t, f j) / t.card) hβ hscard.ne',
apply (add_le_add_left hβ _).trans,
simp [βmul_div_right_comm _ (t.card : π), sub_div' _ _ _ htcard.ne', βsum_div, βadd_div, mul_pow,
div_le_iff (sq_pos_of_ne_zero _ htcard.ne'), sub_sq, sum_add_distrib, βsum_mul, βmul_sum],
ring_nf,
end
end szemeredi_regularity
namespace tactic
open positivity szemeredi_regularity
/-- Extension for the `positivity` tactic: `szemeredi_regularity.initial_bound` and
`szemeredi_regularity.bound` are always positive. -/
@[positivity]
meta def positivity_szemeredi_regularity_bound : expr β tactic strictness
| `(szemeredi_regularity.initial_bound %%Ξ΅ %%l) := positive <$> mk_app ``initial_bound_pos [Ξ΅, l]
| `(szemeredi_regularity.bound %%Ξ΅ %%l) := positive <$> mk_app ``bound_pos [Ξ΅, l]
| e := pp e >>= fail β format.bracket "The expression `"
"` isn't of the form `szemeredi_regularity.initial_bound Ξ΅ l` nor `szemeredi_regularity.bound Ξ΅ l`"
example (Ξ΅ : β) (l : β) : 0 < szemeredi_regularity.initial_bound Ξ΅ l := by positivity
example (Ξ΅ : β) (l : β) : 0 < szemeredi_regularity.bound Ξ΅ l := by positivity
end tactic
|
351daed1fd5eeb617d636a695a104699d16a2c6d | 82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7 | /src/Lean/Server/Snapshots.lean | 1f8310f7c3c13e3b23e297511a30f06930a4ba5a | [
"Apache-2.0"
] | permissive | banksonian/lean4 | 3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc | 78da6b3aa2840693eea354a41e89fc5b212a5011 | refs/heads/master | 1,673,703,624,165 | 1,605,123,551,000 | 1,605,123,551,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,397 | lean | /-
Copyright (c) 2020 Wojciech Nawrocki. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Wojciech Nawrocki
-/
import Init.System.IO
import Lean.Elab.Import
import Lean.Elab.Command
/-! One can think of this module as being a partial reimplementation
of Lean.Elab.Frontend which also stores a snapshot of the world after
each command. Importantly, we allow (re)starting compilation from any
snapshot/position in the file for interactive editing purposes. -/
namespace Lean
namespace Server
namespace Snapshots
open Elab
/-- The data associated with a snapshot is different depending on whether
it was produced from the header or from a command. -/
inductive SnapshotData
| headerData : Environment β MessageLog β Options β SnapshotData
| cmdData : Command.State β SnapshotData
/-- What Lean knows about the world after the header and each command. -/
structure Snapshot :=
/- Where the command which produced this snapshot begins. Note that
neighbouring snapshots are *not* necessarily attached beginning-to-end,
since inputs outside the grammar advance the parser but do not produce
snapshots. -/
(beginPos : String.Pos)
(mpState : Parser.ModuleParserState)
(data : SnapshotData)
namespace Snapshot
def endPos (s : Snapshot) : String.Pos := s.mpState.pos
def env : Snapshot β Environment
| β¨_, _, SnapshotData.headerData env_ _ _β© => env_
| β¨_, _, SnapshotData.cmdData cmdStateβ© => cmdState.env
def msgLog : Snapshot β MessageLog
| β¨_, _, SnapshotData.headerData _ msgLog_ _β© => msgLog_
| β¨_, _, SnapshotData.cmdData cmdStateβ© => cmdState.messages
def toCmdState : Snapshot β Command.State
| β¨_, _, SnapshotData.headerData env msgLog optsβ© => Command.mkState env msgLog opts
| β¨_, _, SnapshotData.cmdData cmdStateβ© => cmdState
end Snapshot
-- TODO(WN): fns here should probably take inputCtx and live
-- in some SnapshotsM := ReaderT Context (EIO Empty)
def compileHeader (contents : String) (opts : Options := {}) : IO Snapshot := do
let inputCtx := Parser.mkInputContext contents "<input>"
let (headerStx, headerParserState, msgLog) β Parser.parseHeader inputCtx
let (headerEnv, msgLog) β Elab.processHeader headerStx opts msgLog inputCtx
pure { beginPos := 0,
mpState := headerParserState,
data := SnapshotData.headerData headerEnv msgLog opts
}
private def ioErrorFromEmpty (ex : Empty) : IO.Error :=
nomatch ex
/-- Compiles the next command occurring after the given snapshot.
If there is no next command (file ended), returns messages produced
through the file. -/
-- NOTE: This code is really very similar to Elab.Frontend. But generalizing it
-- over "store snapshots"/"don't store snapshots" would likely result in confusing
-- isServer? conditionals and not be worth it due to how short it is.
def compileNextCmd (contents : String) (snap : Snapshot) : IO (Sum Snapshot MessageLog) := do
let inputCtx := Parser.mkInputContext contents "<input>";
let (cmdStx, cmdParserState, msgLog) :=
Parser.parseCommand snap.env inputCtx snap.mpState snap.msgLog;
let cmdPos := cmdStx.getHeadInfo.get!.pos.get!; -- TODO(WN): always `some`?
if Parser.isEOI cmdStx || Parser.isExitCommand cmdStx then
pure $ Sum.inr msgLog
else
let cmdStateRef β IO.mkRef { snap.toCmdState with messages := msgLog }
let cmdCtx : Elab.Command.Context := {
cmdPos := snap.endPos,
fileName := inputCtx.fileName,
fileMap := inputCtx.fileMap
}
EIO.toIO ioErrorFromEmpty $
Elab.Command.catchExceptions
(Elab.Command.elabCommand cmdStx)
cmdCtx cmdStateRef
let postCmdState β cmdStateRef.get
let postCmdSnap : Snapshot := {
beginPos := cmdPos,
mpState := cmdParserState,
data := SnapshotData.cmdData postCmdState
}
pure $ Sum.inl postCmdSnap
/-- Compiles all commands after the given snapshot. Returns them as a list, together with
the final message log. -/
partial def compileCmdsAfter (contents : String) (snap : Snapshot) : IO (List Snapshot Γ MessageLog) := do
let cmdOut β compileNextCmd contents snap
match cmdOut with
| Sum.inl snap => do
let (snaps, msgLog) β compileCmdsAfter contents snap
pure $ (snap :: snaps, msgLog)
| Sum.inr msgLog => pure ([], msgLog)
end Snapshots
end Server
end Lean
|
53510d9cceb69a2fd6c0179c823a68f47c070d37 | a9fe717b93ccfa4b2e64faeb24f96dfefb390240 | /nat/reify.lean | fabb86352a3e8301699434363472f789d4d3f75f | [] | no_license | skbaek/omega | ab1f4a6daadfc8c855f14c39d9459ab841527141 | 715e384ed14e8eb177a326700066e7c98269e078 | refs/heads/master | 1,588,000,876,352 | 1,552,645,917,000 | 1,552,645,917,000 | 174,442,914 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,254 | lean | import .form ..tactic
open expr tactic
namespace nat
meta def to_preterm : expr β tactic preterm
| (expr.var k) := return (preterm.var 1 k)
| `(%%(expr.var k) * %%mx) :=
do m β eval_expr nat mx,
return (preterm.var m k)
| `(%%t1x + %%t2x) :=
do t1 β to_preterm t1x,
t2 β to_preterm t2x,
return (preterm.add t1 t2)
| `(%%t1x - %%t2x) :=
do t1 β to_preterm t1x,
t2 β to_preterm t2x,
return (preterm.sub t1 t2)
| mx :=
do m β eval_expr nat mx,
return (preterm.cst m)
meta def to_form_core : expr β tactic form
| `(%%tx1 = %%tx2) :=
do t1 β to_preterm tx1,
t2 β to_preterm tx2,
return (t1 =* t2)
| `(%%tx1 β€ %%tx2) :=
do t1 β to_preterm tx1,
t2 β to_preterm tx2,
return (t1 β€* t2)
| `(Β¬ %%px) := do p β to_form_core px, return (Β¬* p)
| `(%%px β¨ %%qx) :=
do p β to_form_core px,
q β to_form_core qx,
return (p β¨* q)
| `(%%px β§ %%qx) :=
do p β to_form_core px,
q β to_form_core qx,
return (p β§* q)
| `(_ β %%px) := to_form_core px
| _ := failed
meta def to_form : nat β expr β tactic (form Γ nat)
| m `(_ β %%px) := to_form (m+1) px
| m x := do p β to_form_core x, return (p,m)
end nat |
5378c3a6ed485d5eb4a16fb1556379d6826f55d9 | fe2016bd13274f6bcbed6792696f5f4520ac9c4b | /src/training2.lean | 30ae168a8223be1511530b99fea704361720ebdd | [] | no_license | inkytonik/lean-training | 178d6d8d42eca8b6065e85a784bb2997c1bdf6d9 | 7005c0ba8c8a87bd7ea8322926693dec26ec53ec | refs/heads/main | 1,672,144,760,431 | 1,602,561,261,000 | 1,602,561,261,000 | 301,878,072 | 0 | 1 | null | 1,602,561,263,000 | 1,602,026,587,000 | Lean | UTF-8 | Lean | false | false | 1,954 | lean | import tactic
set_option pp.generalized_field_notation false
open nat
namespace training
def powerOf2 : β β β
| 0 := 1
| (n+1) := 2 * powerOf2 n
lemma lowerBoundPowerOf2 (n : β) :
1 β€ powerOf2 n :=
begin
induction n; simp [powerOf2], linarith,
end
lemma sumSamePowerOf2 (n : β) :
powerOf2 n + powerOf2 n == 2 * powerOf2 n :=
by ring
lemma monotonicPowerOf2 :
β {n m}, n β€ m β powerOf2 n β€ powerOf2 m
| 0 m le := lowerBoundPowerOf2 m
| (n+1) 0 le := by cases le
| (n+1) (m+1) le := begin simp [powerOf2], apply monotonicPowerOf2, linarith, end
lemma addPowerOf2 (n m : β) :
powerOf2 n * powerOf2 m = powerOf2 (n + m) :=
begin
induction n; simp [powerOf2], rw [mul_assoc, n_ih, succ_add], simp [powerOf2],
end
inductive tree : Type
| leaf : tree
| node : tree β tree β tree
namespace tree
def height : tree β β
| leaf := 1
| (node l r) := max (height l) (height r) + 1
def nodeCount : tree β β
| leaf := 1
| (node l r) := nodeCount l + nodeCount r + 1
def leafCount : tree β β
| leaf := 1
| (node l r) := leafCount l + leafCount r
-- Move - 1 to LHS to avoid nat subtraction
lemma upperboundForNodeCount (root : tree) :
nodeCount root + 1 β€ powerOf2 (height root) :=
begin
induction root with l r ih_l ih_r;
simp [height, nodeCount, powerOf2],
set hl := height l,
set hr := height r,
calc
nodeCount (node l r) + 1
= nodeCount l + nodeCount r + 1 + 1 : rfl
... β€ powerOf2 hl + powerOf2 hr : by linarith
... β€ powerOf2 (max hl hr) + powerOf2 (max hl hr) :
by linarith [ monotonicPowerOf2 (le_max_left hl hr)
, monotonicPowerOf2 (le_max_right hl hr) ]
... = 2 * powerOf2 (max hl hr) : by ring
... = powerOf2 (max hl hr + 1) : rfl
... = powerOf2 (height (node l r)) : rfl
end
end tree
end training
|
44a16dc5065e9fd62d41967a9c9eafbce79cacb1 | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /stage0/src/Lean/MonadEnv.lean | e0ae9545cb70b541d4f5c19a9d932648fe82559f | [
"Apache-2.0"
] | permissive | dupuisf/lean4 | d082d13b01243e1de29ae680eefb476961221eef | 6a39c65bd28eb0e28c3870188f348c8914502718 | refs/heads/master | 1,676,948,755,391 | 1,610,665,114,000 | 1,610,665,114,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 5,324 | lean | /-
Copyright (c) 2020 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Environment
import Lean.Exception
namespace Lean
def setEnv [MonadEnv m] (env : Environment) : m Unit :=
modifyEnv fun _ => env
def isInductive [Monad m] [MonadEnv m] (declName : Name) : m Bool := do
match (β getEnv).find? declName with
| some (ConstantInfo.inductInfo ..) => return true
| _ => return false
def isRec [Monad m] [MonadEnv m] (declName : Name) : m Bool := do
match (β getEnv).find? declName with
| some (ConstantInfo.recInfo ..) => return true
| _ => return false
@[inline] def withoutModifyingEnv [Monad m] [MonadEnv m] [MonadFinally m] {Ξ± : Type} (x : m Ξ±) : m Ξ± := do
let env β getEnv
try x finally setEnv env
@[inline] def matchConst [Monad m] [MonadEnv m] (e : Expr) (failK : Unit β m Ξ±) (k : ConstantInfo β List Level β m Ξ±) : m Ξ± := do
match e with
| Expr.const constName us _ => do
match (β getEnv).find? constName with
| some cinfo => k cinfo us
| none => failK ()
| _ => failK ()
@[inline] def matchConstInduct [Monad m] [MonadEnv m] (e : Expr) (failK : Unit β m Ξ±) (k : InductiveVal β List Level β m Ξ±) : m Ξ± :=
matchConst e failK fun cinfo us =>
match cinfo with
| ConstantInfo.inductInfo val => k val us
| _ => failK ()
@[inline] def matchConstCtor [Monad m] [MonadEnv m] (e : Expr) (failK : Unit β m Ξ±) (k : ConstructorVal β List Level β m Ξ±) : m Ξ± :=
matchConst e failK fun cinfo us =>
match cinfo with
| ConstantInfo.ctorInfo val => k val us
| _ => failK ()
@[inline] def matchConstRec [Monad m] [MonadEnv m] (e : Expr) (failK : Unit β m Ξ±) (k : RecursorVal β List Level β m Ξ±) : m Ξ± :=
matchConst e failK fun cinfo us =>
match cinfo with
| ConstantInfo.recInfo val => k val us
| _ => failK ()
def hasConst [Monad m] [MonadEnv m] (constName : Name) : m Bool := do
return (β getEnv).contains constName
private partial def mkAuxNameAux (env : Environment) (base : Name) (i : Nat) : Name :=
let candidate := base.appendIndexAfter i
if env.contains candidate then
mkAuxNameAux env base (i+1)
else
candidate
def mkAuxName [Monad m] [MonadEnv m] (baseName : Name) (idx : Nat) : m Name := do
return mkAuxNameAux (β getEnv) baseName idx
def getConstInfo [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m ConstantInfo := do
match (β getEnv).find? constName with
| some info => pure info
| none => throwError! "unknown constant '{mkConst constName}'"
def getConstInfoInduct [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m InductiveVal := do
match (β getConstInfo constName) with
| ConstantInfo.inductInfo v => pure v
| _ => throwError! "'{mkConst constName}' is not a inductive type"
def getConstInfoCtor [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m ConstructorVal := do
match (β getConstInfo constName) with
| ConstantInfo.ctorInfo v => pure v
| _ => throwError! "'{mkConst constName}' is not a constructor"
def getConstInfoRec [Monad m] [MonadEnv m] [MonadError m] (constName : Name) : m RecursorVal := do
match (β getConstInfo constName) with
| ConstantInfo.recInfo v => pure v
| _ => throwError! "'{mkConst constName}' is not a recursor"
@[inline] def matchConstStruct [Monad m] [MonadEnv m] [MonadError m] (e : Expr) (failK : Unit β m Ξ±) (k : InductiveVal β List Level β ConstructorVal β m Ξ±) : m Ξ± :=
matchConstInduct e failK fun ival us => do
if ival.isRec then failK ()
else match ival.ctors with
| [ctor] =>
match (β getConstInfo ctor) with
| ConstantInfo.ctorInfo cval => k ival us cval
| _ => failK ()
| _ => failK ()
def addDecl [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (decl : Declaration) : m Unit := do
match (β getEnv).addDecl decl with
| Except.ok env => setEnv env
| Except.error ex => throwKernelException ex
def compileDecl [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (decl : Declaration) : m Unit := do
match (β getEnv).compileDecl (β getOptions) decl with
| Except.ok env => setEnv env
| Except.error ex => throwKernelException ex
def addAndCompile [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (decl : Declaration) : m Unit := do
addDecl decl;
compileDecl decl
unsafe def evalConst [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (Ξ±) (constName : Name) : m Ξ± := do
ofExcept <| (β getEnv).evalConst Ξ± (β getOptions) constName
unsafe def evalConstCheck [Monad m] [MonadEnv m] [MonadError m] [MonadOptions m] (Ξ±) (typeName : Name) (constName : Name) : m Ξ± := do
ofExcept <| (β getEnv).evalConstCheck Ξ± (β getOptions) typeName constName
def findModuleOf? [Monad m] [MonadEnv m] [MonadError m] (declName : Name) : m (Option Name) := do
discard <| getConstInfo declName -- ensure declaration exists
match (β getEnv).getModuleIdxFor? declName with
| none => return none
| some modIdx => return some ((β getEnv).allImportedModuleNames[modIdx])
end Lean
|
ab14573865c628712f79e926a59487271ccdccca | 9b9a16fa2cb737daee6b2785474678b6fa91d6d4 | /src/tactic/linarith.lean | af94c07bab10956d695bfba6e0c68ed6eb4191df | [
"Apache-2.0"
] | permissive | johoelzl/mathlib | 253f46daa30b644d011e8e119025b01ad69735c4 | 592e3c7a2dfbd5826919b4605559d35d4d75938f | refs/heads/master | 1,625,657,216,488 | 1,551,374,946,000 | 1,551,374,946,000 | 98,915,829 | 0 | 0 | Apache-2.0 | 1,522,917,267,000 | 1,501,524,499,000 | Lean | UTF-8 | Lean | false | false | 32,509 | 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
A tactic for discharging linear arithmetic goals using Fourier-Motzkin elimination.
`linarith` is (in principle) complete for β and β. It is not complete for non-dense orders, i.e. β€.
@TODO: investigate storing comparisons in a list instead of a set, for possible efficiency gains
@TODO: delay proofs of denominator normalization and nat casting until after contradiction is found
-/
import tactic.ring data.nat.gcd data.list.basic meta.rb_map
meta def nat.to_pexpr : β β pexpr
| 0 := ``(0)
| 1 := ``(1)
| n := if n % 2 = 0 then ``(bit0 %%(nat.to_pexpr (n/2))) else ``(bit1 %%(nat.to_pexpr (n/2)))
open native
namespace linarith
section lemmas
lemma int.coe_nat_bit0 (n : β) : (β(bit0 n : β) : β€) = bit0 (βn : β€) := by simp [bit0]
lemma int.coe_nat_bit1 (n : β) : (β(bit1 n : β) : β€) = bit1 (βn : β€) := by simp [bit1, bit0]
lemma int.coe_nat_bit0_mul (n : β) (x : β) : (β(bit0 n * x) : β€) = (β(bit0 n) : β€) * (βx : β€) := by simp
lemma int.coe_nat_bit1_mul (n : β) (x : β) : (β(bit1 n * x) : β€) = (β(bit1 n) : β€) * (βx : β€) := by simp
lemma int.coe_nat_one_mul (x : β) : (β(1 * x) : β€) = 1 * (βx : β€) := by simp
lemma int.coe_nat_zero_mul (x : β) : (β(0 * x) : β€) = 0 * (βx : β€) := by simp
lemma int.coe_nat_mul_bit0 (n : β) (x : β) : (β(x * bit0 n) : β€) = (βx : β€) * (β(bit0 n) : β€) := by simp
lemma int.coe_nat_mul_bit1 (n : β) (x : β) : (β(x * bit1 n) : β€) = (βx : β€) * (β(bit1 n) : β€) := by simp
lemma int.coe_nat_mul_one (x : β) : (β(x * 1) : β€) = (βx : β€) * 1 := by simp
lemma int.coe_nat_mul_zero (x : β) : (β(x * 0) : β€) = (βx : β€) * 0 := by simp
lemma nat_eq_subst {n1 n2 : β} {z1 z2 : β€} (hn : n1 = n2) (h1 : βn1 = z1) (h2 : βn2 = z2) : z1 = z2 :=
by simpa [eq.symm h1, eq.symm h2, int.coe_nat_eq_coe_nat_iff]
lemma nat_le_subst {n1 n2 : β} {z1 z2 : β€} (hn : n1 β€ n2) (h1 : βn1 = z1) (h2 : βn2 = z2) : z1 β€ z2 :=
by simpa [eq.symm h1, eq.symm h2, int.coe_nat_le]
lemma nat_lt_subst {n1 n2 : β} {z1 z2 : β€} (hn : n1 < n2) (h1 : βn1 = z1) (h2 : βn2 = z2) : z1 < z2 :=
by simpa [eq.symm h1, eq.symm h2, int.coe_nat_lt]
lemma eq_of_eq_of_eq {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (ha : a = 0) (hb : b = 0) : a + b = 0 :=
by simp *
lemma le_of_eq_of_le {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (ha : a = 0) (hb : b β€ 0) : a + b β€ 0 :=
by simp *
lemma lt_of_eq_of_lt {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (ha : a = 0) (hb : b < 0) : a + b < 0 :=
by simp *
lemma le_of_le_of_eq {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (ha : a β€ 0) (hb : b = 0) : a + b β€ 0 :=
by simp *
lemma lt_of_lt_of_eq {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (ha : a < 0) (hb : b = 0) : a + b < 0 :=
by simp *
lemma mul_neg {Ξ±} [ordered_ring Ξ±] {a b : Ξ±} (ha : a < 0) (hb : b > 0) : b * a < 0 :=
have (-b)*a > 0, from mul_pos_of_neg_of_neg (neg_neg_of_pos hb) ha,
neg_of_neg_pos (by simpa)
lemma mul_nonpos {Ξ±} [ordered_ring Ξ±] {a b : Ξ±} (ha : a β€ 0) (hb : b > 0) : b * a β€ 0 :=
have (-b)*a β₯ 0, from mul_nonneg_of_nonpos_of_nonpos (le_of_lt (neg_neg_of_pos hb)) ha,
nonpos_of_neg_nonneg (by simp at this; exact this)
lemma mul_eq {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (ha : a = 0) (hb : b > 0) : b * a = 0 :=
by simp *
lemma eq_of_not_lt_of_not_gt {Ξ±} [linear_order Ξ±] (a b : Ξ±) (h1 : Β¬ a < b) (h2 : Β¬ b < a) : a = b :=
le_antisymm (le_of_not_gt h2) (le_of_not_gt h1)
lemma add_subst {Ξ±} [ring Ξ±] {n e1 e2 t1 t2 : Ξ±} (h1 : n * e1 = t1) (h2 : n * e2 = t2) :
n * (e1 + e2) = t1 + t2 := by simp [left_distrib, *]
lemma sub_subst {Ξ±} [ring Ξ±] {n e1 e2 t1 t2 : Ξ±} (h1 : n * e1 = t1) (h2 : n * e2 = t2) :
n * (e1 - e2) = t1 - t2 := by simp [left_distrib, *]
lemma neg_subst {Ξ±} [ring Ξ±] {n e t : Ξ±} (h1 : n * e = t) : n * (-e) = -t := by simp *
private meta def apnn : tactic unit := `[norm_num]
lemma mul_subst {Ξ±} [comm_ring Ξ±] {n1 n2 k e1 e2 t1 t2 : Ξ±} (h1 : n1 * e1 = t1) (h2 : n2 * e2 = t2)
(h3 : n1*n2 = k . apnn) : k * (e1 * e2) = t1 * t2 :=
have h3 : n1 * n2 = k, from h3,
by rw [βh3, mul_comm n1, mul_assoc n2, βmul_assoc n1, h1, βmul_assoc n2, mul_comm n2, mul_assoc, h2] -- OUCH
lemma div_subst {Ξ±} [field Ξ±] {n1 n2 k e1 e2 t1 : Ξ±} (h1 : n1 * e1 = t1) (h2 : n2 / e2 = 1) (h3 : n1*n2 = k) :
k * (e1 / e2) = t1 :=
by rw [βh3, mul_assoc, mul_div_comm, h2, βmul_assoc, h1, mul_comm, one_mul]
end lemmas
section datatypes
@[derive decidable_eq]
inductive ineq
| eq | le | lt
open ineq
def ineq.max : ineq β ineq β ineq
| eq a := a
| le a := a
| lt a := lt
def ineq.is_lt : ineq β ineq β bool
| eq le := tt
| eq lt := tt
| le lt := tt
| _ _ := ff
def ineq.to_string : ineq β string
| eq := "="
| le := "β€"
| lt := "<"
instance : has_to_string ineq := β¨ineq.to_stringβ©
/--
The main datatype for FM elimination.
Variables are represented by natural numbers, each of which has an integer coefficient.
Index 0 is reserved for constants, i.e. `coeffs.find 0` is the coefficient of 1.
The represented term is coeffs.keys.sum (Ξ» i, coeffs.find i * Var[i]).
str determines the direction of the comparison -- is it < 0, β€ 0, or = 0?
-/
meta structure comp :=
(str : ineq)
(coeffs : rb_map β int)
meta instance : inhabited comp := β¨β¨ineq.eq, mk_rb_mapβ©β©
meta inductive comp_source
| assump : β β comp_source
| add : comp_source β comp_source β comp_source
| scale : β β comp_source β comp_source
meta def comp_source.flatten : comp_source β rb_map β β
| (comp_source.assump n) := mk_rb_map.insert n 1
| (comp_source.add c1 c2) := (comp_source.flatten c1).add (comp_source.flatten c2)
| (comp_source.scale n c) := (comp_source.flatten c).map (Ξ» v, v * n)
meta def comp_source.to_string : comp_source β string
| (comp_source.assump e) := to_string e
| (comp_source.add c1 c2) := comp_source.to_string c1 ++ " + " ++ comp_source.to_string c2
| (comp_source.scale n c) := to_string n ++ " * " ++ comp_source.to_string c
meta instance comp_source.has_to_format : has_to_format comp_source :=
β¨Ξ» a, comp_source.to_string aβ©
meta structure pcomp :=
(c : comp)
(src : comp_source)
meta def map_lt (m1 m2 : rb_map β int) : bool :=
list.lex (prod.lex (<) (<)) m1.to_list m2.to_list
-- make more efficient
meta def comp.lt (c1 c2 : comp) : bool :=
(c1.str.is_lt c2.str) || (c1.str = c2.str) && map_lt c1.coeffs c2.coeffs
meta instance comp.has_lt : has_lt comp := β¨Ξ» a b, comp.lt a bβ©
meta instance pcomp.has_lt : has_lt pcomp := β¨Ξ» p1 p2, p1.c < p2.cβ©
meta instance pcomp.has_lt_dec : decidable_rel ((<) : pcomp β pcomp β Prop) := by apply_instance
meta def comp.coeff_of (c : comp) (a : β) : β€ :=
c.coeffs.zfind a
meta def comp.scale (c : comp) (n : β) : comp :=
{ c with coeffs := c.coeffs.map ((*) (n : β€)) }
meta def comp.add (c1 c2 : comp) : comp :=
β¨c1.str.max c2.str, c1.coeffs.add c2.coeffsβ©
meta def pcomp.scale (c : pcomp) (n : β) : pcomp :=
β¨c.c.scale n, comp_source.scale n c.srcβ©
meta def pcomp.add (c1 c2 : pcomp) : pcomp :=
β¨c1.c.add c2.c, comp_source.add c1.src c2.srcβ©
meta instance pcomp.to_format : has_to_format pcomp :=
β¨Ξ» p, to_fmt p.c.coeffs ++ to_string p.c.str ++ "0"β©
meta instance comp.to_format : has_to_format comp :=
β¨Ξ» p, to_fmt p.coeffsβ©
end datatypes
section fm_elim
/-- If c1 and c2 both contain variable a with opposite coefficients,
produces v1, v2, and c such that a has been cancelled in c := v1*c1 + v2*c2 -/
meta def elim_var (c1 c2 : comp) (a : β) : option (β Γ β Γ comp) :=
let v1 := c1.coeff_of a,
v2 := c2.coeff_of a in
if v1 * v2 < 0 then
let vlcm := nat.lcm v1.nat_abs v2.nat_abs,
v1' := vlcm / v1.nat_abs,
v2' := vlcm / v2.nat_abs in
some β¨v1', v2', comp.add (c1.scale v1') (c2.scale v2')β©
else none
meta def pelim_var (p1 p2 : pcomp) (a : β) : option pcomp :=
do (n1, n2, c) β elim_var p1.c p2.c a,
return β¨c, comp_source.add (p1.src.scale n1) (p2.src.scale n2)β©
meta def comp.is_contr (c : comp) : bool := c.coeffs.empty β§ c.str = ineq.lt
meta def pcomp.is_contr (p : pcomp) : bool := p.c.is_contr
meta def elim_with_set (a : β) (p : pcomp) (comps : rb_set pcomp) : rb_set pcomp :=
if Β¬ p.c.coeffs.contains a then mk_rb_set.insert p else
comps.fold mk_rb_set $ Ξ» pc s,
match pelim_var p pc a with
| some pc := s.insert pc
| none := s
end
/--
The state for the elimination monad.
vars: the set of variables present in comps
comps: a set of comparisons
inputs: a set of pairs of exprs (t, pf), where t is a term and pf is a proof that t {<, β€, =} 0,
indexed by β.
has_false: stores a pcomp of 0 < 0 if one has been found
TODO: is it more efficient to store comps as a list, to avoid comparisons?
-/
meta structure linarith_structure :=
(vars : rb_set β)
(comps : rb_set pcomp)
@[reducible] meta def linarith_monad :=
state_t linarith_structure (except_t pcomp id)
meta instance : monad linarith_monad := state_t.monad
meta instance : monad_except pcomp linarith_monad :=
state_t.monad_except pcomp
meta def get_vars : linarith_monad (rb_set β) :=
linarith_structure.vars <$> get
meta def get_var_list : linarith_monad (list β) :=
rb_set.to_list <$> get_vars
meta def get_comps : linarith_monad (rb_set pcomp) :=
linarith_structure.comps <$> get
meta def validate : linarith_monad unit :=
do β¨_, compsβ© β get,
match comps.to_list.find (Ξ» p : pcomp, p.is_contr) with
| none := return ()
| some c := throw c
end
meta def update (vars : rb_set β) (comps : rb_set pcomp) : linarith_monad unit :=
state_t.put β¨vars, compsβ© >> validate
meta def monad.elim_var (a : β) : linarith_monad unit :=
do vs β get_vars,
when (vs.contains a) $
do comps β get_comps,
let cs' := comps.fold mk_rb_set (Ξ» p s, s.union (elim_with_set a p comps)),
update (vs.erase a) cs'
meta def elim_all_vars : linarith_monad unit :=
get_var_list >>= list.mmap' monad.elim_var
end fm_elim
section parse
open ineq tactic
meta def map_of_expr_mul_aux (c1 c2 : rb_map β β€) : option (rb_map β β€) :=
match c1.keys, c2.keys with
| [0], _ := some $ c2.scale (c1.zfind 0)
| _, [0] := some $ c1.scale (c2.zfind 0)
| _, _ := none
end
/--
Turns an expression into a map from β to β€, for use in a comp object.
The expr_map β argument identifies which expressions have already been assigned numbers.
Returns a new map.
-/
meta def map_of_expr : expr_map β β expr β option (expr_map β Γ rb_map β β€)
| m e@`(%%e1 * %%e2) :=
(do (m', comp1) β map_of_expr m e1,
(m', comp2) β map_of_expr m' e2,
mp β map_of_expr_mul_aux comp1 comp2,
return (m', mp)) <|>
(match m.find e with
| some k := return (m, mk_rb_map.insert k 1)
| none := let n := m.size + 1 in return (m.insert e n, mk_rb_map.insert n 1)
end)
| m `(%%e1 + %%e2) :=
do (m', comp1) β map_of_expr m e1,
(m', comp2) β map_of_expr m' e2,
return (m', comp1.add comp2)
| m `(%%e1 - %%e2) :=
do (m', comp1) β map_of_expr m e1,
(m', comp2) β map_of_expr m' e2,
return (m', comp1.add (comp2.scale (-1)))
| m `(-%%e) := do (m', comp) β map_of_expr m e, return (m', comp.scale (-1))
| m e :=
match e.to_int, m.find e with
| some 0, _ := return β¨m, mk_rb_mapβ©
| some z, _ := return β¨m, mk_rb_map.insert 0 zβ©
| none, some k := return (m, mk_rb_map.insert k 1)
| none, none := let n := m.size + 1 in
return (m.insert e n, mk_rb_map.insert n 1)
end
meta def parse_into_comp_and_expr : expr β option (ineq Γ expr)
| `(%%e < 0) := (ineq.lt, e)
| `(%%e β€ 0) := (ineq.le, e)
| `(%%e = 0) := (ineq.eq, e)
| _ := none
meta def to_comp (e : expr) (m : expr_map β) : option (comp Γ expr_map β) :=
do (iq, e) β parse_into_comp_and_expr e,
(m', comp') β map_of_expr m e,
return β¨β¨iq, comp'β©, m'β©
meta def to_comp_fold : expr_map β β list expr β
(list (option comp) Γ expr_map β)
| m [] := ([], m)
| m (h::t) :=
match to_comp h m with
| some (c, m') := let (l, mp) := to_comp_fold m' t in (c::l, mp)
| none := let (l, mp) := to_comp_fold m t in (none::l, mp)
end
/--
Takes a list of proofs of props of the form t {<, β€, =} 0, and creates a linarith_structure.
-/
meta def mk_linarith_structure (l : list expr) : tactic (linarith_structure Γ rb_map β (expr Γ expr)) :=
do pftps β l.mmap infer_type,
let (l', map) := to_comp_fold mk_rb_map pftps,
let lz := list.enum $ ((l.zip pftps).zip l').filter_map (Ξ» β¨a, bβ©, prod.mk a <$> b),
let prmap := rb_map.of_list $ lz.map (Ξ» β¨n, xβ©, (n, x.1)),
let vars : rb_set β := rb_map.set_of_list $ list.range map.size.succ,
let pc : rb_set pcomp := rb_map.set_of_list $
lz.map (Ξ» β¨n, xβ©, β¨x.2, comp_source.assump nβ©),
return (β¨vars, pcβ©, prmap)
meta def linarith_monad.run {Ξ±} (tac : linarith_monad Ξ±) (l : list expr) : tactic ((pcomp β Ξ±) Γ rb_map β (expr Γ expr)) :=
do (struct, inputs) β mk_linarith_structure l,
match (state_t.run (validate >> tac) struct).run with
| (except.ok (a, _)) := return (sum.inr a, inputs)
| (except.error contr) := return (sum.inl contr, inputs)
end
end parse
section prove
open ineq tactic
meta def get_rel_sides : expr β tactic (expr Γ expr)
| `(%%a < %%b) := return (a, b)
| `(%%a β€ %%b) := return (a, b)
| `(%%a = %%b) := return (a, b)
| `(%%a β₯ %%b) := return (a, b)
| `(%%a > %%b) := return (a, b)
| _ := failed
meta def mul_expr (n : β) (e : expr) : pexpr :=
if n = 1 then ``(%%e) else
``(%%(nat.to_pexpr n) * %%e)
meta def add_exprs_aux : pexpr β list pexpr β pexpr
| p [] := p
| p [a] := ``(%%p + %%a)
| p (h::t) := add_exprs_aux ``(%%p + %%h) t
meta def add_exprs : list pexpr β pexpr
| [] := ``(0)
| (h::t) := add_exprs_aux h t
meta def find_contr (m : rb_set pcomp) : option pcomp :=
m.keys.find (Ξ» p, p.c.is_contr)
meta def ineq_const_mul_nm : ineq β name
| lt := ``mul_neg
| le := ``mul_nonpos
| eq := ``mul_eq
meta def ineq_const_nm : ineq β ineq β (name Γ ineq)
| eq eq := (``eq_of_eq_of_eq, eq)
| eq le := (``le_of_eq_of_le, le)
| eq lt := (``lt_of_eq_of_lt, lt)
| le eq := (``le_of_le_of_eq, le)
| le le := (`add_nonpos, le)
| le lt := (`add_neg_of_nonpos_of_neg, lt)
| lt eq := (``lt_of_lt_of_eq, lt)
| lt le := (`add_neg_of_neg_of_nonpos, lt)
| lt lt := (`add_neg, lt)
meta def mk_single_comp_zero_pf (c : β) (h : expr) : tactic (ineq Γ expr) :=
do tp β infer_type h,
some (iq, e) β return $ parse_into_comp_and_expr tp,
if c = 0 then
do e' β mk_app ``zero_mul [e], return (eq, e')
else if c = 1 then return (iq, h)
else
do nm β resolve_name (ineq_const_mul_nm iq),
tp β (prod.snd <$> (infer_type h >>= get_rel_sides)) >>= infer_type,
cpos β to_expr ``((%%c.to_pexpr : %%tp) > 0),
(_, ex) β solve_aux cpos `[norm_num, done],
-- e' β mk_app (ineq_const_mul_nm iq) [h, ex], -- this takes many seconds longer in some examples! why?
e' β to_expr ``(%%nm %%h %%ex) ff,
return (iq, e')
meta def mk_lt_zero_pf_aux (c : ineq) (pf npf : expr) (coeff : β) : tactic (ineq Γ expr) :=
do (iq, h') β mk_single_comp_zero_pf coeff npf,
let (nm, niq) := ineq_const_nm c iq,
n β resolve_name nm,
e' β to_expr ``(%%n %%pf %%h'),
return (niq, e')
/--
Takes a list of coefficients [c] and list of expressions, of equal length.
Each expression is a proof of a prop of the form t {<, β€, =} 0.
Produces a proof that the sum of (c*t) {<, β€, =} 0, where the comp is as strong as possible.
-/
meta def mk_lt_zero_pf : list β β list expr β tactic expr
| _ [] := fail "no linear hypotheses found"
| [c] [h] := prod.snd <$> mk_single_comp_zero_pf c h
| (c::ct) (h::t) :=
do (iq, h') β mk_single_comp_zero_pf c h,
prod.snd <$> (ct.zip t).mfoldl (Ξ» pr ce, mk_lt_zero_pf_aux pr.1 pr.2 ce.2 ce.1) (iq, h')
| _ _ := fail "not enough args to mk_lt_zero_pf"
meta def term_of_ineq_prf (prf : expr) : tactic expr :=
do (lhs, _) β infer_type prf >>= get_rel_sides,
return lhs
meta structure linarith_config :=
(discharger : tactic unit := `[ring])
(restrict_type : option Type := none)
(restrict_type_reflect : reflected restrict_type . apply_instance)
(exfalso : bool := tt)
meta def ineq_pf_tp (pf : expr) : tactic expr :=
do (_, z) β infer_type pf >>= get_rel_sides,
infer_type z
meta def mk_neg_one_lt_zero_pf (tp : expr) : tactic expr :=
to_expr ``((neg_neg_of_pos zero_lt_one : -1 < (0 : %%tp)))
/--
Assumes e is a proof that t = 0. Creates a proof that -t = 0.
-/
meta def mk_neg_eq_zero_pf (e : expr) : tactic expr :=
to_expr ``(neg_eq_zero.mpr %%e)
meta def add_neg_eq_pfs : list expr β tactic (list expr)
| [] := return []
| (h::t) :=
do some (iq, tp) β parse_into_comp_and_expr <$> infer_type h,
match iq with
| ineq.eq := do nep β mk_neg_eq_zero_pf h, tl β add_neg_eq_pfs t, return $ h::nep::tl
| _ := list.cons h <$> add_neg_eq_pfs t
end
/--
Takes a list of proofs of propositions of the form t {<, β€, =} 0,
and tries to prove the goal `false`.
-/
meta def prove_false_by_linarith1 (cfg : linarith_config) : list expr β tactic unit
| [] := fail "no args to linarith"
| l@(h::t) :=
do l' β add_neg_eq_pfs l,
hz β ineq_pf_tp h >>= mk_neg_one_lt_zero_pf,
(sum.inl contr, inputs) β elim_all_vars.run (hz::l')
| fail "linarith failed to find a contradiction",
let coeffs := inputs.keys.map (Ξ» k, (contr.src.flatten.ifind k)),
let pfs : list expr := inputs.keys.map (Ξ» k, (inputs.ifind k).1),
let zip := (coeffs.zip pfs).filter (Ξ» pr, pr.1 β 0),
let (coeffs, pfs) := zip.unzip,
mls β zip.mmap (Ξ» pr, do e β term_of_ineq_prf pr.2, return (mul_expr pr.1 e)),
sm β to_expr $ add_exprs mls,
tgt β to_expr ``(%%sm = 0),
(a, b) β solve_aux tgt (cfg.discharger >> done),
pf β mk_lt_zero_pf coeffs pfs,
pftp β infer_type pf,
(_, nep, _) β rewrite_core b pftp,
pf' β mk_eq_mp nep pf,
mk_app `lt_irrefl [pf'] >>= exact
end prove
section normalize
open tactic
set_option eqn_compiler.max_steps 50000
meta def rem_neg (prf : expr) : expr β tactic expr
| `(_ β€ _) := to_expr ``(lt_of_not_ge %%prf)
| `(_ < _) := to_expr ``(le_of_not_gt %%prf)
| `(_ > _) := to_expr ``(le_of_not_gt %%prf)
| `(_ β₯ _) := to_expr ``(lt_of_not_ge %%prf)
| e := failed
meta def rearr_comp : expr β expr β tactic expr
| prf `(%%a β€ 0) := return prf
| prf `(%%a < 0) := return prf
| prf `(%%a = 0) := return prf
| prf `(%%a β₯ 0) := to_expr ``(neg_nonpos.mpr %%prf)
| prf `(%%a > 0) := to_expr ``(neg_neg_of_pos %%prf)
| prf `(0 β₯ %%a) := to_expr ``(show %%a β€ 0, from %%prf)
| prf `(0 > %%a) := to_expr ``(show %%a < 0, from %%prf)
| prf `(0 = %%a) := to_expr ``(eq.symm %%prf)
| prf `(0 β€ %%a) := to_expr ``(neg_nonpos.mpr %%prf)
| prf `(0 < %%a) := to_expr ``(neg_neg_of_pos %%prf)
| prf `(%%a β€ %%b) := to_expr ``(sub_nonpos.mpr %%prf)
| prf `(%%a < %%b) := to_expr ``(sub_neg_of_lt %%prf)
| prf `(%%a = %%b) := to_expr ``(sub_eq_zero.mpr %%prf)
| prf `(%%a > %%b) := to_expr ``(sub_neg_of_lt %%prf)
| prf `(%%a β₯ %%b) := to_expr ``(sub_nonpos.mpr %%prf)
| prf `(Β¬ %%t) := do nprf β rem_neg prf t, tp β infer_type nprf, rearr_comp nprf tp
| prf _ := fail "couldn't rearrange comp"
meta def is_numeric : expr β option β
| `(%%e1 + %%e2) := (+) <$> is_numeric e1 <*> is_numeric e2
| `(%%e1 - %%e2) := has_sub.sub <$> is_numeric e1 <*> is_numeric e2
| `(%%e1 * %%e2) := (*) <$> is_numeric e1 <*> is_numeric e2
| `(%%e1 / %%e2) := (/) <$> is_numeric e1 <*> is_numeric e2
| `(-%%e) := rat.neg <$> is_numeric e
| e := e.to_rat
inductive {u} tree (Ξ± : Type u) : Type u
| nil {} : tree
| node : Ξ± β tree β tree β tree
def tree.repr {Ξ±} [has_repr Ξ±] : tree Ξ± β string
| tree.nil := "nil"
| (tree.node a t1 t2) := "tree.node " ++ repr a ++ " (" ++ tree.repr t1 ++ ") (" ++ tree.repr t2 ++ ")"
instance {Ξ±} [has_repr Ξ±] : has_repr (tree Ξ±) := β¨tree.reprβ©
meta def find_cancel_factor : expr β β Γ tree β
| `(%%e1 + %%e2) :=
let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in
(lcm, tree.node lcm t1 t2)
| `(%%e1 - %%e2) :=
let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, lcm := v1.lcm v2 in
(lcm, tree.node lcm t1 t2)
| `(%%e1 * %%e2) :=
match is_numeric e1, is_numeric e2 with
| none, none := (1, tree.node 1 tree.nil tree.nil)
| _, _ :=
let (v1, t1) := find_cancel_factor e1, (v2, t2) := find_cancel_factor e2, pd := v1*v2 in
(pd, tree.node pd t1 t2)
end
| `(%%e1 / %%e2) :=
match is_numeric e2 with
| some q := let (v1, t1) := find_cancel_factor e1, n := v1.lcm q.num.nat_abs in
(n, tree.node n t1 (tree.node q.num.nat_abs tree.nil tree.nil))
| none := (1, tree.node 1 tree.nil tree.nil)
end
| `(-%%e) := find_cancel_factor e
| _ := (1, tree.node 1 tree.nil tree.nil)
open tree
meta def mk_prod_prf : β β tree β β expr β tactic expr
| v (node _ lhs rhs) `(%%e1 + %%e2) :=
do v1 β mk_prod_prf v lhs e1, v2 β mk_prod_prf v rhs e2, mk_app ``add_subst [v1, v2]
| v (node _ lhs rhs) `(%%e1 - %%e2) :=
do v1 β mk_prod_prf v lhs e1, v2 β mk_prod_prf v rhs e2, mk_app ``sub_subst [v1, v2]
| v (node n lhs@(node ln _ _) rhs) `(%%e1 * %%e2) :=
do tp β infer_type e1, v1 β mk_prod_prf ln lhs e1, v2 β mk_prod_prf (v/ln) rhs e2,
ln' β tp.of_nat ln, vln' β tp.of_nat (v/ln), v' β tp.of_nat v,
ntp β to_expr ``(%%ln' * %%vln' = %%v'),
(_, npf) β solve_aux ntp `[norm_num, done],
mk_app ``mul_subst [v1, v2, npf]
| v (node n lhs rhs@(node rn _ _)) `(%%e1 / %%e2) :=
do tp β infer_type e1, v1 β mk_prod_prf (v/rn) lhs e1,
rn' β tp.of_nat rn, vrn' β tp.of_nat (v/rn), n' β tp.of_nat n, v' β tp.of_nat v,
ntp β to_expr ``(%%rn' / %%e2 = 1),
(_, npf) β solve_aux ntp `[norm_num, done],
ntp2 β to_expr ``(%%vrn' * %%n' = %%v'),
(_, npf2) β solve_aux ntp2 `[norm_num, done],
mk_app ``div_subst [v1, npf, npf2]
| v t `(-%%e) := do v' β mk_prod_prf v t e, mk_app ``neg_subst [v']
| v _ e :=
do tp β infer_type e,
v' β tp.of_nat v,
e' β to_expr ``(%%v' * %%e),
mk_app `eq.refl [e']
/--
e is a term with rational division. produces a natural number n and a proof that n*e = e',
where e' has no division.
-/
meta def kill_factors (e : expr) : tactic (β Γ expr) :=
let (n, t) := find_cancel_factor e in
do e' β mk_prod_prf n t e, return (n, e')
open expr
meta def expr_contains (n : name) : expr β bool
| (const nm _) := nm = n
| (lam _ _ _ bd) := expr_contains bd
| (pi _ _ _ bd) := expr_contains bd
| (app e1 e2) := expr_contains e1 || expr_contains e2
| _ := ff
lemma sub_into_lt {Ξ±} [ordered_semiring Ξ±] {a b : Ξ±} (he : a = b) (hl : a β€ 0) : b β€ 0 :=
by rwa he at hl
meta def norm_hyp_aux (h' lhs : expr) : tactic expr :=
do (v, lhs') β kill_factors lhs,
if v = 1 then return h' else do
(ih, h'') β mk_single_comp_zero_pf v h',
(_, nep, _) β infer_type h'' >>= rewrite_core lhs',
mk_eq_mp nep h''
meta def norm_hyp (h : expr) : tactic expr :=
do htp β infer_type h,
h' β rearr_comp h htp,
some (c, lhs) β parse_into_comp_and_expr <$> infer_type h',
if expr_contains `has_div.div lhs then
norm_hyp_aux h' lhs
else return h'
meta def get_contr_lemma_name : expr β option name
| `(%%a < %%b) := return `lt_of_not_ge
| `(%%a β€ %%b) := return `le_of_not_gt
| `(%%a = %%b) := return ``eq_of_not_lt_of_not_gt
| `(%%a β₯ %%b) := return `le_of_not_gt
| `(%%a > %%b) := return `lt_of_not_ge
| `(Β¬ %%a < %%b) := return `not.intro
| `(Β¬ %%a β€ %%b) := return `not.intro
| `(Β¬ %%a = %%b) := return `not.intro
| `(Β¬ %%a β₯ %%b) := return `not.intro
| `(Β¬ %%a > %%b) := return `not.intro
| _ := none
-- assumes the input t is of type β. Produces t' of type β€ such that βt = t' and a proof of equality
meta def cast_expr (e : expr) : tactic (expr Γ expr) :=
do s β [`int.coe_nat_add, `int.coe_nat_zero, `int.coe_nat_one,
``int.coe_nat_bit0_mul, ``int.coe_nat_bit1_mul, ``int.coe_nat_zero_mul, ``int.coe_nat_one_mul,
``int.coe_nat_mul_bit0, ``int.coe_nat_mul_bit1, ``int.coe_nat_mul_zero, ``int.coe_nat_mul_one,
``int.coe_nat_bit0, ``int.coe_nat_bit1].mfoldl simp_lemmas.add_simp simp_lemmas.mk,
ce β to_expr ``(β%%e : β€),
simplify s [] ce {fail_if_unchanged := ff}
meta def is_nat_int_coe : expr β option expr
| `((β(%%n : β) : β€)) := some n
| _ := none
meta def mk_coe_nat_nonneg_prf (e : expr) : tactic expr :=
mk_app `int.coe_nat_nonneg [e]
meta def get_nat_comps : expr β list expr
| `(%%a + %%b) := (get_nat_comps a).append (get_nat_comps b)
| `(%%a * %%b) := (get_nat_comps a).append (get_nat_comps b)
| e := match is_nat_int_coe e with
| some e' := [e']
| none := []
end
meta def mk_coe_nat_nonneg_prfs (e : expr) : tactic (list expr) :=
(get_nat_comps e).mmap mk_coe_nat_nonneg_prf
meta def mk_cast_eq_and_nonneg_prfs (pf a b : expr) (ln : name) : tactic (list expr) :=
do (a', prfa) β cast_expr a,
(b', prfb) β cast_expr b,
la β mk_coe_nat_nonneg_prfs a',
lb β mk_coe_nat_nonneg_prfs b',
pf' β mk_app ln [pf, prfa, prfb],
return $ pf'::(la.append lb)
meta def mk_int_pfs_of_nat_pf (pf : expr) : tactic (list expr) :=
do tp β infer_type pf,
match tp with
| `(%%a = %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_eq_subst
| `(%%a β€ %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_le_subst
| `(%%a < %%b) := mk_cast_eq_and_nonneg_prfs pf a b ``nat_lt_subst
| `(%%a β₯ %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_le_subst
| `(%%a > %%b) := mk_cast_eq_and_nonneg_prfs pf b a ``nat_lt_subst
| `(Β¬ %%a β€ %%b) := do pf' β mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_lt_subst
| `(Β¬ %%a < %%b) := do pf' β mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' b a ``nat_le_subst
| `(Β¬ %%a β₯ %%b) := do pf' β mk_app ``lt_of_not_ge [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_lt_subst
| `(Β¬ %%a > %%b) := do pf' β mk_app ``le_of_not_gt [pf], mk_cast_eq_and_nonneg_prfs pf' a b ``nat_le_subst
| _ := fail "mk_int_pfs_of_nat_pf failed: proof is not an inequality"
end
meta def mk_non_strict_int_pf_of_strict_int_pf (pf : expr) : tactic expr :=
do tp β infer_type pf,
match tp with
| `(%%a < %%b) := to_expr ``(@cast (%%a < %%b) (%%a + 1 β€ %%b) (by refl) %%pf)
| `(%%a > %%b) := to_expr ``(@cast (%%a > %%b) (%%a β₯ %%b + 1) (by refl) %%pf)
| `(Β¬ %%a β€ %%b) := to_expr ``(@cast (%%a > %%b) (%%a β₯ %%b + 1) (by refl) (lt_of_not_ge %%pf))
| `(Β¬ %%a β₯ %%b) := to_expr ``(@cast (%%a < %%b) (%%a + 1 β€ %%b) (by refl) (lt_of_not_ge %%pf))
| _ := fail "mk_non_strict_int_pf_of_strict_int_pf failed: proof is not an inequality"
end
meta def guard_is_nat_prop : expr β tactic unit
| `(%%a = _) := infer_type a >>= unify `(β)
| `(%%a β€ _) := infer_type a >>= unify `(β)
| `(%%a < _) := infer_type a >>= unify `(β)
| `(%%a β₯ _) := infer_type a >>= unify `(β)
| `(%%a > _) := infer_type a >>= unify `(β)
| `(Β¬ %%p) := guard_is_nat_prop p
| _ := failed
meta def guard_is_strict_int_prop : expr β tactic unit
| `(%%a < _) := infer_type a >>= unify `(β€)
| `(%%a > _) := infer_type a >>= unify `(β€)
| `(Β¬ %%a β€ _) := infer_type a >>= unify `(β€)
| `(Β¬ %%a β₯ _) := infer_type a >>= unify `(β€)
| _ := failed
meta def replace_nat_pfs : list expr β tactic (list expr)
| [] := return []
| (h::t) :=
(do infer_type h >>= guard_is_nat_prop,
ls β mk_int_pfs_of_nat_pf h,
list.append ls <$> replace_nat_pfs t) <|> list.cons h <$> replace_nat_pfs t
meta def replace_strict_int_pfs : list expr β tactic (list expr)
| [] := return []
| (h::t) :=
(do infer_type h >>= guard_is_strict_int_prop,
l β mk_non_strict_int_pf_of_strict_int_pf h,
list.cons l <$> replace_strict_int_pfs t) <|> list.cons h <$> replace_strict_int_pfs t
meta def partition_by_type_aux : rb_lmap expr expr β list expr β tactic (rb_lmap expr expr)
| m [] := return m
| m (h::t) := do tp β ineq_pf_tp h, partition_by_type_aux (m.insert tp h) t
meta def partition_by_type (l : list expr) : tactic (rb_lmap expr expr) :=
partition_by_type_aux mk_rb_map l
private meta def try_linarith_on_lists (cfg : linarith_config) (ls : list (list expr)) : tactic unit :=
(first $ ls.map $ prove_false_by_linarith1 cfg) <|> fail "linarith failed"
/--
Takes a list of proofs of propositions.
Filters out the proofs of linear (in)equalities,
and tries to use them to prove `false`.
If pref_type is given, starts by working over this type
-/
meta def prove_false_by_linarith (cfg : linarith_config) (pref_type : option expr) (l : list expr) : tactic unit :=
do l' β replace_nat_pfs l,
l'' β replace_strict_int_pfs l',
ls β list.reduce_option <$> l''.mmap (Ξ» h, (do s β norm_hyp h, return (some s)) <|> return none)
>>= partition_by_type,
pref_type β (unify pref_type.iget `(β) >> return (some `(β€) : option expr)) <|> return pref_type,
match cfg.restrict_type, ls.values, pref_type with
| some rtp, _, _ :=
do m β mk_mvar, unify `(some %%m : option Type) cfg.restrict_type_reflect, m β instantiate_mvars m,
prove_false_by_linarith1 cfg (ls.ifind m)
| none, [ls'], _ := prove_false_by_linarith1 cfg ls'
| none, ls', none := try_linarith_on_lists cfg ls'
| none, _, (some t) := prove_false_by_linarith1 cfg (ls.ifind t) <|> try_linarith_on_lists cfg (ls.erase t).values
end
end normalize
end linarith
section
open tactic linarith
open lean lean.parser interactive tactic interactive.types
local postfix `?`:9001 := optional
local postfix *:9001 := many
meta def linarith.interactive_aux (cfg : linarith_config) : option expr β
parse ident* β (parse (tk "using" *> pexpr_list)?) β tactic unit
| pt l (some pe) := pe.mmap (Ξ» p, i_to_expr p >>= note_anon) >> linarith.interactive_aux pt l none
| pt [] none :=
do t β target,
if t = `(false) then local_context >>= prove_false_by_linarith cfg pt
else match get_contr_lemma_name t with
| some nm := seq (applyc nm) (do t β intro1 >>= ineq_pf_tp, linarith.interactive_aux (some t) [] none)
| none := if cfg.exfalso then exfalso >> linarith.interactive_aux pt [] none
else fail "linarith failed: target type is not an inequality."
end
| pt ls none := (ls.mmap get_local) >>= prove_false_by_linarith cfg pt
/--
Tries to prove a goal of `false` by linear arithmetic on hypotheses.
If the goal is a linear (in)equality, tries to prove it by contradiction.
If the goal is not `false` or an inequality, applies `exfalso` and tries linarith on the
hypotheses.
`linarith` will use all relevant hypotheses in the local context.
`linarith h1 h2 h3` will only use hypotheses h1, h2, h3.
`linarith using [t1, t2, t3]` will add proof terms t1, t2, t3 to the local context.
Config options:
`linarith {exfalso := ff}` will fail on a goal that is neither an inequality nor `false`
`linarith {restrict_type := T}` will run only on hypotheses that are inequalities over `T`
`linarith {discharger := tac}` will use `tac` instead of `ring` for normalization.
Options: `ring2`, `ring SOP`, `simp`
-/
meta def tactic.interactive.linarith (ids : parse (many ident))
(using_hyps : parse (tk "using" *> pexpr_list)?) (cfg : linarith_config := {}) : tactic unit :=
linarith.interactive_aux cfg none ids using_hyps
end
|
32ecb83aaeb8148b3822a76ac9d3872dcac3fc71 | ce6917c5bacabee346655160b74a307b4a5ab620 | /src/ch6/ex0403.lean | 1c3d87b9af4d91e3168eaaa5bde97a7ba667dbe0 | [] | no_license | Ailrun/Theorem_Proving_in_Lean | ae6a23f3c54d62d401314d6a771e8ff8b4132db2 | 2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68 | refs/heads/master | 1,609,838,270,467 | 1,586,846,743,000 | 1,586,846,743,000 | 240,967,761 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 252 | lean | variable {Ξ± : Type*}
def is_prefix (lβ : list Ξ±) (lβ : list Ξ±) : Prop :=
β t, lβ ++ t = lβ
infix ` <+: `:50 := is_prefix
theorem list.is_prefix_refl (l : list Ξ±) : l <+: l :=
β¨[], by simpβ©
attribute [simp] list.is_prefix_refl
|
3373478b6469e15078778b0858df4aa377b70358 | dd4e652c749fea9ac77e404005cb3470e5f75469 | /src/array.lean | 1b533a856b4fc782eace1fc9ac6bbc8984587816 | [] | no_license | skbaek/cvx | e32822ad5943541539966a37dee162b0a5495f55 | c50c790c9116f9fac8dfe742903a62bdd7292c15 | refs/heads/master | 1,623,803,010,339 | 1,618,058,958,000 | 1,618,058,958,000 | 176,293,135 | 3 | 2 | null | null | null | null | UTF-8 | Lean | false | false | 1,016 | lean | import .vector
variables {Ξ± Ξ² : Type}
variables {k m n : nat}
open nat
namespace array
def cell_size [has_repr Ξ±] (as : array m Ξ±) : nat :=
as.foldl 0 (Ξ» a n, max n (repr a).length)
def sum [has_zero Ξ±] [has_add Ξ±] (v : array n Ξ±) : Ξ± := foldl v 0 (+)
def dot_prod [has_zero Ξ±] [has_add Ξ±] [has_mul Ξ±] (v w : array n Ξ±) : Ξ± :=
array.sum (mapβ (*) v w)
#check tactic.simplify
--#exit
--lemma ext'_succ (a b : array (k+1) Ξ±) :
-- β (m : nat) (h : m < k), read a β¨m, _β© = read b β¨m, _β© β
-- read a β¨k, lt_succ_self kβ© = read b β¨k, lt_succ_self kβ© β
-- a = b :=
--sorry
end array
#exit
def vector.to_array : β {k : nat}, vector Ξ± k β array k Ξ±
| 0 _ := array.nil
| (k+1) v :=
(mk_array (k+1) (v.nth β¨0, nat.zero_lt_succ _β©)).foreach
(Ξ» i _, v.nth i)
#exit
run_cmd tactic.norm_num
`(array.dot_prod
(vector.to_array (β¨([0,1,2] : list nat), rflβ© : vector nat 3))
(vector.to_array (β¨([0,1,2] : list nat), rflβ© : vector nat 3)))
|
dd94af7bed7a883ef327d054a5fbc3882c01e094 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/dynamics/fixed_points/topology_auto.lean | a5e301268b04acf8e5ef7ba05e758504de69aa21 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,356 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Johannes HΓΆlzl
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.dynamics.fixed_points.basic
import Mathlib.topology.separation
import Mathlib.PostPort
universes u_1
namespace Mathlib
/-!
# Topological properties of fixed points
Currently this file contains two lemmas:
- `is_fixed_pt_of_tendsto_iterate`: if `f^n(x) β y` and `f` is continuous at `y`, then `f y = y`;
- `is_closed_fixed_points`: the set of fixed points of a continuous map is a closed set.
## TODO
fixed points, iterates
-/
/-- If the iterates `f^[n] x` converge to `y` and `f` is continuous at `y`,
then `y` is a fixed point for `f`. -/
theorem is_fixed_pt_of_tendsto_iterate {Ξ± : Type u_1} [topological_space Ξ±] [t2_space Ξ±] {f : Ξ± β Ξ±}
{x : Ξ±} {y : Ξ±} (hy : filter.tendsto (fun (n : β) => nat.iterate f n x) filter.at_top (nhds y))
(hf : continuous_at f y) : function.is_fixed_pt f y :=
sorry
/-- The set of fixed points of a continuous map is a closed set. -/
theorem is_closed_fixed_points {Ξ± : Type u_1} [topological_space Ξ±] [t2_space Ξ±] {f : Ξ± β Ξ±}
(hf : continuous f) : is_closed (function.fixed_points f) :=
is_closed_eq hf continuous_id
end Mathlib |
5ca5bf371c8ecd2436b7cfb2a23d712c6de63993 | 97c8e5d8aca4afeebb5b335f26a492c53680efc8 | /ground_zero/HITs/simplicial.lean | 771840e7d7c0ae3d1a0515c693a6c65120713c49 | [] | no_license | jfrancese/lean | cf32f0d8d5520b6f0e9d3987deb95841c553c53c | 06e7efaecce4093d97fb5ecc75479df2ef1dbbdb | refs/heads/master | 1,587,915,151,351 | 1,551,012,140,000 | 1,551,012,140,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,540 | lean | import ground_zero.HITs.truncation
open ground_zero.types
open ground_zero.types.eq (renaming rfl -> idp)
/-
* Filled simplex.
* Simplex.
-/
hott theory
namespace ground_zero.HITs
universes u v w
def iterated_unit : β β Type
| 0 := empty
| (n + 1) := coproduct ground_zero.types.unit.{1} (iterated_unit n)
def filled_simplex (n : β) := β₯iterated_unit nβ₯
inductive simplex.core : β β Type
| base {n : β} : simplex.core (n + 1)
| lift {n : β} : simplex.core n β simplex.core (n + 1)
inductive simplex.rel : Ξ n, simplex.core n β simplex.core n β Prop
| mk {n : β} (x : simplex.core n) :
simplex.rel (n + 1) simplex.core.base (simplex.core.lift x)
def simplex (n : β) := quot (simplex.rel n)
inductive graph.rel {Ξ± : Sort u} (edges : Ξ± β Ξ± β Sort v) : Ξ± β Ξ± β Prop
| line (n m : Ξ±) : edges n m β graph.rel n m
def graph {Ξ± : Sort u} (edges : Ξ± β Ξ± β Sort v) := quot (graph.rel edges)
namespace graph
def elem {Ξ± : Sort u} {edges : Ξ± β Ξ± β Sort w} : Ξ± β graph edges :=
quot.mk (rel edges)
def line {Ξ± : Sort u} {edges : Ξ± β Ξ± β Sort w} {x y : Ξ±}
(h : edges x y) : @elem Ξ± edges x = @elem Ξ± edges y :=
ground_zero.support.inclusion (quot.sound (rel.line x y h))
def rec {Ξ± : Sort u} {Ξ² : Sort v} {edges : Ξ± β Ξ± β Sort w}
(f : Ξ± β Ξ²) (h : Ξ x y, edges x y β f x = f y) : graph edges β Ξ² := begin
fapply quot.lift, exact f,
{ intros a b, intro H, cases H,
apply ground_zero.support.truncation,
fapply h, assumption }
end
def ind {Ξ± : Sort u} {edges : Ξ± β Ξ± β Sort w} {Ξ² : graph edges β Sort v}
(f : Ξ x, Ξ² (elem x)) (h : Ξ x y (H : edges x y), f x =[line H] f y) :
Ξ x, Ξ² x := begin
intro x, fapply quot.hrec_on x,
exact f, intros a b H, cases H,
apply ground_zero.types.heq.from_pathover (line H_a),
fapply h
end
end graph
def is_connected (Ξ± : Sort u) := Ξ£' (x : Ξ±), Ξ y, β₯x = yβ₯
def is_loop {Ξ± : Sort u} {a : Ξ±} (p : a = a) := Β¬(p = idp)
def is_acyclic {Ξ± : Sort u} (edges : Ξ± β Ξ± β Sort u) :=
ground_zero.structures.K (graph edges)
def is_tree {Ξ± : Sort u} (edges : Ξ± β Ξ± β Sort u) :=
is_connected (graph edges) Γ is_acyclic edges
def is_complete {Ξ± : Sort u} (edges : Ξ± β Ξ± β Sort u) :=
ground_zero.structures.prop (graph edges)
namespace iso_example
inductive ABC
| A | B
open ABC
def Gβ : ABC β ABC β Type
| A B := π
| _ _ := π
def Gβ : ABC β ABC β Type
| A B := π
| B A := π
| _ _ := π
def GβGβ : graph Gβ β graph Gβ :=
graph.rec (graph.elem β id) (begin
intros x y, cases x; cases y; intro H,
{ cases H },
{ cases H,
{ apply graph.line, exact β
},
{ symmetry, apply graph.line, exact β
} },
{ cases H },
{ cases H }
end)
def GβGβ : graph Gβ β graph Gβ :=
graph.rec (graph.elem β id) (begin
intros x y, cases x; cases y; intro H,
{ cases H },
{ apply graph.line, exact ff },
{ symmetry, apply graph.line, exact tt },
{ cases H }
end)
end iso_example
inductive Koenigsberg
| Altstadt | Kneiphof
| Lomse | Vorstadt
namespace Koenigsberg
def edges : Koenigsberg β Koenigsberg β Type
| Kneiphof Lomse := ground_zero.types.unit
| Altstadt Lomse := ground_zero.types.unit
| Lomse Vorstadt := ground_zero.types.unit
| Altstadt Kneiphof := bool
| Altstadt Vorstadt := bool
| _ _ := empty
end Koenigsberg
end ground_zero.HITs |
ced53e101eab3b6b96933b35ba775b3d7fe56448 | f313d4982feee650661f61ed73f0cb6635326350 | /Mathlib/Algebra/Group/Defs.lean | f12ce731973a1a42c6bec7024d1fe6faf25b85c2 | [
"Apache-2.0"
] | permissive | shingtaklam1324/mathlib4 | 38c6e172eec1385944db5a70a3b5545c924980ee | 50610c343b7065e8eec056d641f859ceed608e69 | refs/heads/master | 1,683,032,333,313 | 1,621,942,699,000 | 1,621,942,699,000 | 371,130,608 | 0 | 0 | Apache-2.0 | 1,622,053,166,000 | 1,622,053,166,000 | null | UTF-8 | Lean | false | false | 11,093 | lean | import Mathlib.Data.Nat.Basic -- *only* for notation β which should be in a "prelude"
/-!
# Typeclasses for monoids and groups etc
-/
/-
## Stuff which was in core Lean 3
-- this should also be in a "prelude" -- it is not in mathlib3's algebra.group.defs
-/
class Zero (Ξ± : Type u) where
zero : Ξ±
instance [Zero Ξ±] : OfNat Ξ± (nat_lit 0) where
ofNat := Zero.zero
class One (Ξ± : Type u) where
one : Ξ±
instance [One Ξ±] : OfNat Ξ± (nat_lit 1) where
ofNat := One.one
class Inv (Ξ± : Type u) where
inv : Ξ± β Ξ±
postfix:max "β»ΒΉ" => Inv.inv
/-
## The trick for adding a natural action onto monoids
-/
section nat_action
variable {M : Type u}
-- see npow_rec comment for explanation about why not nsmul_rec n a + a
/-- The fundamental scalar multiplication in an additive monoid. `nsmul_rec n a = a+a+...+a` n
times. Use instead `n β’ a`, which has better definitional behavior. -/
def nsmul_rec [Zero M] [Add M] : β β M β M
| 0 , a => 0
| n+1, a => a + nsmul_rec n a
-- use `x * npow_rec n x` and not `npow_rec n x * x` in the definition to make sure that
-- definitional unfolding of `npow_rec` is blocked, to avoid deep recursion issues.
/-- The fundamental power operation in a monoid. `npow_rec n a = a*a*...*a` n times.
Use instead `a ^ n`, which has better definitional behavior. -/
def npow_rec [One M] [Mul M] : β β M β M
| 0 , a => 1
| n+1, a => a * npow_rec n a
end nat_action
section int_action
-- TODO -- this should be in a prelude
notation "β€" => Int
/-- The fundamental scalar multiplication in an additive group. `gsmul_rec n a = a+a+...+a` n
times, for integer `n`. Use instead `n β’ a`, which has better definitional behavior. -/
def gsmul_rec {G : Type u} [Zero G] [Add G] [Neg G]: β€ β G β G
| (Int.ofNat n) , a => nsmul_rec n a
| (Int.negSucc n), a => - (nsmul_rec n.succ a)
/-- The fundamental power operation in a group. `gpow_rec n a = a*a*...*a` n times, for integer `n`.
Use instead `a ^ n`, which has better definitional behavior. -/
def gpow_rec {G : Type u} [One G] [Mul G] [Inv G] : β€ β G β G
| (Int.ofNat n) , a => npow_rec n a
| (Int.negSucc n), a => (npow_rec n.succ a) β»ΒΉ
end int_action
/-
## Additive semigroups, monoids and groups
-/
/-
### Semigroups
-/
class AddSemigroup (A : Type u) extends Add A where
add_assoc (a b c : A) : (a + b) + c = a + (b + c)
theorem add_assoc {G : Type u} [AddSemigroup G] :
β a b c : G, (a + b) + c = a + (b + c) :=
AddSemigroup.add_assoc
class AddCommSemigroup (A : Type u) extends AddSemigroup A where
add_comm (a b : A) : a + b = b + a
theorem add_comm {A : Type u} [AddCommSemigroup A] (a b : A) : a + b = b + a :=
AddCommSemigroup.add_comm a b
/-
### Cancellative semigroups
-/
class IsAddLeftCancel (A : Type u) [Add A] where
add_left_cancel (a b c : A) : a + b = a + c β b = c
class IsAddRightCancel (A : Type u) [Add A] where
add_right_cancel (a b c : A) : b + a = c + a β b = c
section AddLeftCancel_lemmas
variable {A : Type u} [AddSemigroup A] [IsAddLeftCancel A] {a b c : A}
theorem add_left_cancel : a + b = a + c β b = c :=
IsAddLeftCancel.add_left_cancel a b c
theorem add_left_cancel_iff : a + b = a + c β b = c :=
β¨add_left_cancel, congrArg _β©
-- no `function.injective`?
--theorem add_right_injective (a : G) : function.injective (c * .) :=
--Ξ» a b => add_left_cancel
@[simp] theorem add_right_inj (a : A) {b c : A} : a + b = a + c β b = c :=
β¨add_left_cancel, congrArg _β©
--theorem add_ne_add_right (a : A) {b c : A} : a + b β a + c β b β c :=
--(add_right_injective a).ne_iff
end AddLeftCancel_lemmas
section AddRightCancel_lemmas
variable {A : Type u} [AddSemigroup A] [IsAddRightCancel A] {a b c : A}
theorem add_right_cancel : b + a = c + a β b = c :=
IsAddRightCancel.add_right_cancel a b c
theorem add_right_cancel_iff : b + a = c + a β b = c :=
β¨add_right_cancel, Ξ» h => h βΈ rflβ©
@[simp] theorem add_left_inj (a : A) {b c : A} : b + a = c + a β b = c :=
β¨add_right_cancel, Ξ» h => h βΈ rflβ©
end AddRightCancel_lemmas
/-
### Additive monoids
-/
class AddMonoid (A : Type u) extends AddSemigroup A, Zero A where
add_zero (a : A) : a + 0 = a
zero_add (a : A) : 0 + a = a
nsmul : β β A β A := nsmul_rec
nsmul_zero' : β x, nsmul 0 x = 0 -- fill in with tactic once we can do this
nsmul_succ' : β (n : β) x, nsmul n.succ x = x + nsmul n x -- fill in with tactic
section AddMonoid_lemmas
variable {A : Type u} [AddMonoid A] {a b c : A}
@[simp] theorem add_zero (a : A) : a + 0 = a :=
AddMonoid.add_zero a
@[simp] theorem zero_add (a : A) : 0 + a = a :=
AddMonoid.zero_add a
theorem left_neg_eq_right_neg (hba : b + a = 0) (hac : a + c = 0) : b = c :=
by rw [βzero_add c, βhba, add_assoc, hac, add_zero b]
end AddMonoid_lemmas
/-
### Commutative additive monoids
-/
class AddCommMonoid (A : Type u) extends AddMonoid A where
add_comm (a b : A) : a + b = b + a
instance (A : Type u) [h : AddCommMonoid A] : AddCommSemigroup A :=
{h with}
/-
### Additive groups
-/
class AddGroup (A : Type u) extends AddMonoid A, Neg A, Sub A where
add_left_neg (a : A) : -a + a = 0
sub_eq_add_neg (a b : A) : a - b = a + -b
gsmul : β€ β A β A := gsmul_rec
gpow_zero' (a : A) : gsmul 0 a = 0 -- try rfl
gpow_succ' (n : β) (a : A) : gsmul (Int.ofNat n.succ) a = a + gsmul (Int.ofNat n) a
gpow_neg' (n : β) (a : A) : gsmul (Int.negSucc n) a = -(gsmul β(n.succ) a)
section AddGroup_lemmas
variable {A : Type u} [AddGroup A] {a b c : A}
@[simp] theorem add_left_neg : β a : A, -a + a = 0 :=
AddGroup.add_left_neg
theorem neg_add_self (a : A) : -a + a = 0 := add_left_neg a
@[simp] theorem neg_add_cancel_left (a b : A) : -a + (a + b) = b :=
by rw [β add_assoc, add_left_neg, zero_add]
@[simp] theorem neg_eq_of_add_eq_zero (h : a + b = 0) : -a = b :=
left_neg_eq_right_neg (neg_add_self a) h
@[simp] theorem neg_neg (a : A) : -(-a) = a :=
neg_eq_of_add_eq_zero (add_left_neg a)
@[simp] theorem add_right_neg (a : A) : a + -a = 0 := by
rw [βadd_left_neg (-a), neg_neg]
-- synonym
theorem add_neg_self (a : A) : a + -a = 0 := add_right_neg a
@[simp] theorem add_neg_cancel_right (a b : A) : a + b + -b = a :=
by rw [add_assoc, add_right_neg, add_zero]
instance (A : Type u) [AddGroup A] : IsAddRightCancel A where
add_right_cancel a b c h := by
rw [β add_neg_cancel_right b a, h, add_neg_cancel_right]
instance (A : Type u) [AddGroup A] : IsAddLeftCancel A where
add_left_cancel a b c h := by
rw [β neg_add_cancel_left a b, h, neg_add_cancel_left]
end AddGroup_lemmas
class AddCommGroup (A : Type u) extends AddGroup A where
add_comm (a b : A) : a + b = b + a
-- the automatically generated name is something like instAddCommMonoid
-- I need to explicitly refer to this later when making Ring.toSemiring
instance AddCommGroup.toAddCommMonoid (A : Type u) [h : AddCommGroup A] :
AddCommMonoid A :=
{ h with }
/-
## Multiplicative semigroups, monoids and groups
-/
/-
## Semigroups
-/
class Semigroup (G : Type u) extends Mul G where
mul_assoc (a b c : G) : (a * b) * c = a * (b * c)
theorem mul_assoc {G : Type u} [Semigroup G] :
β a b c : G, a * b * c = a * (b * c) :=
Semigroup.mul_assoc
class CommSemigroup (G : Type u) extends Semigroup G where
mul_comm (a b : G) : a * b = b * a
theorem mul_comm {M : Type u} [CommSemigroup M] : β a b : M, a * b = b * a :=
CommSemigroup.mul_comm
/-
### Cancellative semigroups
-/
class IsMulLeftCancel (G : Type u) [Mul G] where
mul_left_cancel (a b c : G) : a * b = a * c β b = c
class IsMulRightCancel (G : Type u) [Mul G] where
mul_right_cancel (a b c : G) : b * a = c * a β b = c
section MulLeftCancel
variable {G : Type u} [Semigroup G] [IsMulLeftCancel G] {a b c : G}
theorem mul_left_cancel : a * b = a * c β b = c :=
IsMulLeftCancel.mul_left_cancel a b c
theorem mul_left_cancel_iff : a * b = a * c β b = c :=
β¨mul_left_cancel, congrArg _β©
-- no `function.injective`?
--theorem mul_right_injective (a : G) : function.injective (c * .) :=
--Ξ» a b => mul_left_cancel
@[simp] theorem mul_right_inj (a : G) {b c : G} : a * b = a * c β b = c :=
β¨mul_left_cancel, congrArg _β©
--theorem mul_ne_mul_right (a : G) {b c : G} : a * b β a * c β b β c :=
--(mul_right_injective a).ne_iff
end MulLeftCancel
section MulRightCancel
variable {G : Type u} [Semigroup G] [IsMulRightCancel G] {a b c : G}
theorem mul_right_cancel : b * a = c * a β b = c :=
IsMulRightCancel.mul_right_cancel a b c
theorem mul_right_cancel_iff : b * a = c * a β b = c :=
β¨mul_right_cancel, Ξ» h => h βΈ rflβ©
@[simp] theorem mul_left_inj (a : G) {b c : G} : b * a = c * a β b = c :=
β¨mul_right_cancel, Ξ» h => h βΈ rflβ©
end MulRightCancel
/-
### Monoids
-/
class Monoid (M : Type u) extends Semigroup M, One M where
mul_one (m : M) : m * 1 = m
one_mul (m : M) : 1 * m = m
npow : β β M β M := npow_rec
npow_zero' : β x, npow 0 x = 1 -- fill in with tactic once we can do this
npow_succ' : β (n : β) x, npow n.succ x = x * npow n x -- fill in with tactic
@[simp] theorem mul_one {M : Type u} [Monoid M] : β (m : M), m * 1 = m :=
Monoid.mul_one
@[simp] theorem one_mul {M : Type u} [Monoid M] : β (m : M), 1 * m = m :=
Monoid.one_mul
theorem left_inv_eq_right_inv {M : Type u} [Monoid M] {a b c : M}
(hba : b * a = 1) (hac : a * c = 1) : b = c :=
by rw [βone_mul c, βhba, mul_assoc, hac, mul_one b]
/-
### Commutative monoids
-/
class CommMonoid (M : Type u) extends Monoid M where
mul_comm (a b : M) : a * b = b * a
instance (M : Type u) [h : CommMonoid M] : CommSemigroup M :=
{ h with }
/-
### Groups
-/
class Group (G : Type u) extends Monoid G, Inv G, Div G where
mul_left_inv (a : G) : aβ»ΒΉ * a = 1
div_eq_mul_inv (a b : G) : a / b = a * bβ»ΒΉ
gpow : β€ β G β G := gpow_rec
gpow_zero' (a : G) : gpow 0 a = 1 -- try rfl
gpow_succ' (n : β) (a : G) : gpow (Int.ofNat n.succ) a = a * gpow (Int.ofNat n) a
gpow_neg' (n : β) (a : G) : gpow (Int.negSucc n) a = (gpow β(n.succ) a)β»ΒΉ
section Group_lemmas
variable {G : Type u} [Group G] {a b c : G}
@[simp] theorem mul_left_inv : β a : G, aβ»ΒΉ * a = 1 :=
Group.mul_left_inv
theorem inv_mul_self (a : G) : aβ»ΒΉ * a = 1 := mul_left_inv a
@[simp] theorem inv_mul_cancel_left (a b : G) : aβ»ΒΉ * (a * b) = b :=
by rw [β mul_assoc, mul_left_inv, one_mul]
@[simp] theorem inv_eq_of_mul_eq_one (h : a * b = 1) : aβ»ΒΉ = b :=
left_inv_eq_right_inv (inv_mul_self a) h
@[simp] theorem inv_inv (a : G) : (aβ»ΒΉ)β»ΒΉ = a :=
inv_eq_of_mul_eq_one (mul_left_inv a)
@[simp] theorem mul_right_inv (a : G) : a * aβ»ΒΉ = 1 := by
rw [βmul_left_inv (aβ»ΒΉ), inv_inv]
-- synonym
theorem mul_inv_self (a : G) : a * aβ»ΒΉ = 1 := mul_right_inv a
@[simp] theorem mul_inv_cancel_right (a b : G) : a * b * bβ»ΒΉ = a :=
by rw [mul_assoc, mul_right_inv, mul_one]
end Group_lemmas
class CommGroup (G : Type u) extends Group G where
mul_comm (a b : G) : a * b = b * a
instance (G : Type u) [h : CommGroup G] : CommMonoid G :=
{ h with } |
74b0fd7406c0da666e41a7327031c99f59807219 | 39c5aa4cf3be4a2dfd294cd2becd0848ff4cad97 | /src/TypeCheck.lean | 49b56fb7c35bafb4370150b206eeffb773317ce2 | [] | no_license | anfelor/coc-lean | 70d489ae1d34932d33bcf211b4ef8d1fe557e1d3 | fdd967d2b7bc349202a1deabbbce155eed4db73a | refs/heads/master | 1,617,867,588,097 | 1,587,224,804,000 | 1,587,224,804,000 | 248,754,643 | 5 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,455 | lean | import Terms
import CoC
open PTSSort
open BetaOpt
/-! The type checker. -/
/-
Since Judgements are in Prop, we have to jump through some hoops
to write nearly trivial functions. But Judgements belong to Prop
not least because the type checker would be noncomputable if they
were in type due to some hard to prove statements.
-/
inductive TypeError : Type
| TypeMismatch : Exp β Exp β TypeError
| UnboundIndex : nat β TypeError
| UnboundVar : string β TypeError
| BoxInTerm : TypeError
| WhileChecking : Exp β TypeError β TypeError
| ExpectedFunctionButGot : Exp β TypeError
| ExpectedSortButGot : Exp β TypeError
open TypeError
def type_error_repr : TypeError -> string
| (TypeMismatch e1 e2) := "Type mismatch between: " ++ repr e1 ++ " and " ++ repr e2
| (UnboundIndex n) := "Unbound index: " ++ repr n
| (UnboundVar s) := "Unbound var: " ++ repr s
| (BoxInTerm) := "Box in term."
| (WhileChecking e t) := "While checking " ++ repr e ++ " encountered\n" ++ type_error_repr t
| (ExpectedFunctionButGot e) := "Expected function but got: " ++ repr e
| (ExpectedSortButGot e) := "Expected sort but got: " ++ repr e
instance type_error_has_repr : has_repr TypeError :=
{ repr := type_error_repr }
/-- The type checker monad -/
def TC := except TypeError
open except
instance tc_has_bind : has_bind TC := { bind := Ξ» _ _, except.bind }
instance tc_has_repr {a} {h : has_repr a} : has_repr (TC a) :=
{ repr := Ξ» t, match t with
| error t := repr t
| ok a := repr a
end }
instance type_psigma_has_repr {g e} : has_repr (Ξ£' t : Exp, Judgement g e t) :=
{ repr := Ξ» s, repr s.fst }
/- This instance is necessary for #eval -/
instance type_tc_has_repr {g e} : has_repr (TC (Ξ£' t : Exp, Judgement g e t)) :=
{ repr := (@tc_has_repr _ type_psigma_has_repr).repr }
/-- Lookup a variable in a well-formed context. -/
def lookup (x : string) : Ξ (g : Context) (h : ContextWF g),
TC (Ξ£' t, Judgement g (Exp.free x) t)
| (Context.empty) h := error (UnboundVar x)
| (Context.cons y e g') h :=
match string.has_decidable_eq x y with
| (is_true p) := ok β¨e, begin simp [p], cases h,
exact Judgement.start y h_noShadowing h_a, endβ©
| (is_false p) := lookup g' (by { cases h, assumption }) >>= (begin
intro a, apply ok, cases a, apply psigma.mk, cases h,
exact Judgement.weaken y h_noShadowing a_snd h_a,
end)
end
def find_rule : Ξ (s t : PTSSort), Rule s t
| star star := Rule.vdv
| star box := Rule.tdv
| box star := Rule.vdt
| box box := Rule.tdt
inductive Classification (g : Context) (t : Exp) : Type
| kind : t = Exp.sort box β Classification
| term : Judgement g t (Exp.sort star) β Classification
| constructor : Judgement g t (Exp.sort box) β Classification
-- | See Theorem 3.2 and 3.3 in [snforcc].
-- The classification lemma will be challenging since Classification is in
-- type and not in Prop. See typing_pi_find_sort below.
axiom preservation {g e t} : Judgement g e t β Judgement g (head_reduce e) t
axiom classification : Ξ {g e t}, Judgement g e t β Classification g t
axiom beta_preserves_type : Ξ {g e t z},
Beta Red t z β Judgement g e t β Judgement g e z
def beta_reduce_terminates_type {g e t} : Judgement g e t β (beta_reduce t).dom :=
begin
intro j, cases classification j, simp [a, beta_reduce],
refine acc.intro t _, intro y, rw [a], intro b, cases b,
repeat { exact beta_reduce_terminates a },
end
inductive ContextLT : Context -> Context -> Prop
| empty {g} : ContextLT (Context.empty) g
| cons1 {x a g h} : ContextLT g h -> ContextLT g (Context.cons x a h)
| cons2 {x a g h} : ContextLT g h -> ContextLT (Context.cons x a g) (Context.cons x a h)
def context_lt_refl : Ξ g, ContextLT g g
| Context.empty := ContextLT.empty
| (Context.cons x a g) := ContextLT.cons2 (context_lt_refl g)
def context_lt_cons {x a} : Ξ g, ContextLT g (Context.cons x a g)
:= Ξ» g, ContextLT.cons1 (context_lt_refl g)
def preserves_type {g e t}
: Judgement g e t β Judgement g e (head_reduce t) :=
begin
intro j, cases classification j, rw [a, head_reduce], rw [a] at j, exact j,
exact Judgement.conv (Beta.head_reduce Eq t) (preservation a) j,
exact Judgement.conv (Beta.head_reduce Eq t) (preservation a) j,
end
-- The grammar for expressions of type box is
-- t := A | * | x -> t for A a variable and x an arbitrary expression.
lemma typing_pi_find_sort : Ξ a (g : Context) (h : ContextWF g),
Ξ£' s, β p, β h_g, ContextLT h_g g -> Judgement h_g a (Exp.sort p) -> p = s
:= sorry
lemma typing_pi : Ξ {g x a b t}, Judgement g (Exp.pi x a b) t β Ξ£' s, Judgement g a (Exp.sort s) :=
begin
intros g x a b t,
generalize e : Exp.pi x a b = y, intro h,
let z := typing_pi_find_sort a g (judgement_context_wf h),
apply psigma.mk z.fst,
induction h generalizing e; cases e,
{ apply Judgement.weaken,
exact h_noShadowing, have z2 := h_ih_a (eq.refl _),
exact eq.mp (by rw [z.snd _ h_g (context_lt_cons _) z2]) z2,
exact h_a_1, },
{ exact eq.mp (by rw [z.snd h_s1 h_g (context_lt_refl h_g) h_a]) h_a },
{ from h_ih_a_1 (eq.refl _) },
end
lemma beta_reduce_terminates_head_reduce_pi {g e t x a b} : Judgement g e t
β head_reduce t = Exp.pi x a b β (beta_reduce a).dom := begin
intros j h, cases classification j,
simp [a_1, head_reduce] at h, from false.elim h,
iterate 2 { have h2 := preservation a_1, rw [h] at h2,
cases typing_pi h2, from beta_reduce_terminates snd, }
end
inductive typecheck_rel : (Ξ£' (e : Exp) (g : Context), ContextWF g)
β (Ξ£' (e : Exp) (g : Context), ContextWF g) β Prop
| app_1 {g h a b} : typecheck_rel β¨a, g, hβ© β¨Exp.app a b, g, hβ©
| app_2 {g h a b} : typecheck_rel β¨b, g, hβ© β¨Exp.app a b, g, hβ©
| lam_1 {g h x a b} : typecheck_rel β¨a, g, hβ© β¨Exp.lam x a b, g, hβ©
| lam_2 {g h x a t s hns} {h1 : Judgement g a (Exp.sort s)} : typecheck_rel
β¨instantiate (Exp.free (fresh (context_domain g βͺ free_vars t) x)) t
, Context.cons (fresh (context_domain g βͺ free_vars t) x) a g, ContextWF.cons h hns h1β©
β¨Exp.lam x a t, g, hβ©
| check_pi {g h x a t b}
(h1 : Judgement (Context.cons (fresh (context_domain g βͺ free_vars t) x) a g)
(instantiate (Exp.free (fresh (context_domain g βͺ free_vars t) x)) t) b)
: typecheck_rel
β¨Exp.pi (fresh (context_domain g βͺ free_vars t) x) a (abstract (fresh (context_domain g βͺ free_vars t) x) b), g, hβ©
β¨Exp.lam x a t, g, hβ©
| pi_1 {g h x a b} : typecheck_rel β¨a, g, hβ© β¨Exp.pi x a b, g, hβ©
| pi_2 {g h x a t s hns} {h1 : Judgement g a (Exp.sort s)} : typecheck_rel
β¨instantiate (Exp.free (fresh (context_domain g βͺ free_vars t) x)) t
, Context.cons (fresh (context_domain g βͺ free_vars t) x) a g, ContextWF.cons h hns h1β©
β¨Exp.pi x a t, g, hβ©
set_option eqn_compiler.zeta true
def typecheck_recur : Ξ (e : Exp) (g : Context) (h : ContextWF g),
(Ξ y, typecheck_rel y β¨e, g, hβ© β TC (Ξ£' t, Judgement y.2.1 y.1 t))
β TC (Ξ£' t, Judgement g e t)
| (Exp.free x) g h IH := lookup x g h
| (Exp.bound x) g h IH := error (UnboundIndex x)
| (Exp.sort s) g h IH := match s with
| star := ok β¨Exp.sort box, ContextWF.rec_on h (Judgement.starInBox)
(Ξ» x _ _ _ _ hns a h, Judgement.weaken x hns h a)β©
| box := error BoxInTerm
end
| (Exp.app f a) g h IH :=
IH β¨f, g, hβ© (typecheck_rel.app_1) >>= Ξ» β¨e, jeβ©,
IH β¨a, g, hβ© (typecheck_rel.app_2) >>= Ξ» β¨A, jAβ©,
let β¨z1, beta1β© := (beta_reduce A).get (beta_reduce_terminates_type jA)
in begin
cases h : (head_reduce e),
case Exp.pi : x A' B begin
rename h_1 h,
let zb := (beta_reduce A').get (beta_reduce_terminates_head_reduce_pi je h),
cases exp_decidable_eq z1 zb.1,
exact error (ExpectedFunctionButGot e),
let h2 : Ξ£' s, Judgement g (Exp.pi x A' B) (Exp.sort s) := begin
cases classification (preserves_type je),
simp [a_1, head_reduce] at h, from false.elim h,
repeat { rw [h] at a_1 }, exact β¨star, a_1β©, exact β¨box, a_1β©,
end,
let h4 : Ξ£' s, Judgement g A' (Exp.sort s) := begin
cases classification (preserves_type je),
simp [a_1, head_reduce] at h, from false.elim h,
repeat { rw [h] at a_1, from typing_pi a_1, },
end,
apply ok, fapply psigma.mk, exact (instantiate a B), apply Judgement.app,
apply Judgement.conv, apply eq.mp (by simp [h]) (Beta.head_reduce Eq e),
from h2.snd, from je, apply Judgement.conv,
from (Beta.trans Red Eq Eq (eq.refl _) beta1 (eq.mp (by simp[h_1]) (Beta.symm zb.2))),
from h4.2, from jA,
end,
repeat { exact error (ExpectedFunctionButGot (head_reduce e)) }
end
| (Exp.lam x a t) g h IH :=
IH β¨a, g, hβ© (typecheck_rel.lam_1) >>= Ξ»β¨s, jaβ©,
match (beta_reduce s).get (beta_reduce_terminates_type ja), ja with
| β¨Exp.sort s, bsβ©, ja := let x' := fresh (context_domain g βͺ free_vars t) x in
IH β¨(instantiate (Exp.free x') t), (Context.cons x' a g),
(ContextWF.cons h (iff.elim_left finset.not_mem_union (fresh_not_mem)).1
(beta_preserves_type bs ja))β© (typecheck_rel.lam_2)
>>= Ξ»β¨b, jbβ©,
IH β¨(Exp.pi x' a (abstract x' b)), g, hβ© (typecheck_rel.check_pi jb) >>=
Ξ»β¨p, jpβ©, match (beta_reduce p).get (beta_reduce_terminates_type jp), jp with
| β¨Exp.sort _, bpβ©, jp :=
let h : Judgement g (Exp.lam x a t) (Exp.pi x a (abstract x' b))
:= eq.mp (by simp [fresh_avoids_capture (finset.subset_union_right _ _)])
(Judgement.abs x jb (beta_preserves_type bp jp))
in ok β¨Exp.pi x a (abstract x' b), hβ©
| _, _ := error (ExpectedSortButGot p)
end
| β¨e, _β©, _ := error (ExpectedSortButGot e)
end
| (Exp.pi x a b) g h IH :=
IH β¨a, g, hβ© (typecheck_rel.pi_1) >>= Ξ»β¨s, jsβ©,
match (beta_reduce s).get (beta_reduce_terminates_type js), js with
| β¨Exp.sort s, bsβ©, js := let x' := fresh (context_domain g βͺ free_vars b) x in
IH β¨(instantiate (Exp.free x') b), (Context.cons x' a g),
(ContextWF.cons h (iff.elim_left finset.not_mem_union (fresh_not_mem)).1
(beta_preserves_type bs js))β© (typecheck_rel.pi_2)
>>= Ξ»β¨t, jtβ©, match (beta_reduce t).get (beta_reduce_terminates_type jt), jt with
| β¨Exp.sort t, btβ©, jt :=
let h : Judgement g (Exp.pi x a b) (Exp.sort t)
:= eq.mp (by simp [fresh_avoids_capture (finset.subset_union_right _ _)])
(Judgement.product x (find_rule s t) (beta_preserves_type bs js)
(beta_preserves_type bt jt))
in ok β¨Exp.sort t, hβ©
| β¨e, _β©, _ := error (ExpectedSortButGot e)
end
| β¨e, _β©, _ := error (ExpectedSortButGot e)
end
set_option eqn_compiler.zeta false
def typecheck_roption (e : Exp) (g : Context) (h : ContextWF g) : roption (TC (Ξ£' t, Judgement g e t)) :=
begin
refine β¨acc typecheck_rel β¨e,g,hβ©, Ξ» h2, @acc.rec_on (Ξ£' (e : Exp) (g : Context), ContextWF g) _
(Ξ» y, TC (Ξ£' t, Judgement y.2.1 y.1 t)) _ h2 (Ξ» β¨e1,g1,h1β© ih IH,
typecheck_recur e1 g1 h1 IH)β©,
end
def typecheck_terminates (e : Exp) (g : Context) (h : ContextWF g) : (typecheck_roption e g h).dom
:= sorry
def typecheck (e : Exp) (g : Context) (h : ContextWF g) : TC (Ξ£' t, Judgement g e t) :=
(typecheck_roption e g h).get (typecheck_terminates e g h) |
6aca3a9921b510a7ba369ad4f80f56fb82708c30 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/locally_convex/polar.lean | 6c2d73ba3e9bee61d7914bf2cf5337f30601a04d | [
"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 | 4,695 | lean | /-
Copyright (c) 2022 Moritz Doll. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Moritz Doll, Kalle KytΓΆlΓ€
-/
import analysis.normed.normed_field
import analysis.convex.basic
import linear_algebra.sesquilinear_form
import topology.algebra.module.weak_dual
/-!
# Polar set
In this file we define the polar set. There are different notions of the polar, we will define the
*absolute polar*. The advantage over the real polar is that we can define the absolute polar for
any bilinear form `B : E ββ[π] F ββ[π] π`, where `π` is a normed commutative ring and
`E` and `F` are modules over `π`.
## Main definitions
* `linear_map.polar`: The polar of a bilinear form `B : E ββ[π] F ββ[π] π`.
## Main statements
* `linear_map.polar_eq_Inter`: The polar as an intersection.
* `linear_map.subset_bipolar`: The polar is a subset of the bipolar.
* `linear_map.polar_weak_closed`: The polar is closed in the weak topology induced by `B.flip`.
## References
* [H. H. Schaefer, *Topological Vector Spaces*][schaefer1966]
## Tags
polar
-/
variables {π E F : Type*}
namespace linear_map
section normed_ring
variables [normed_comm_ring π] [add_comm_monoid E] [add_comm_monoid F]
variables [module π E] [module π F]
variables (B : E ββ[π] F ββ[π] π)
/-- The (absolute) polar of `s : set E` is given by the set of all `y : F` such that `β₯B x yβ₯ β€ 1`
for all `x β s`.-/
def polar (s : set E) : set F :=
{y : F | β x β s, β₯B x yβ₯ β€ 1 }
lemma polar_mem_iff (s : set E) (y : F) :
y β B.polar s β β x β s, β₯B x yβ₯ β€ 1 := iff.rfl
lemma polar_mem (s : set E) (y : F) (hy : y β B.polar s) :
β x β s, β₯B x yβ₯ β€ 1 := hy
@[simp] lemma zero_mem_polar (s : set E) :
(0 : F) β B.polar s :=
Ξ» _ _, by simp only [map_zero, norm_zero, zero_le_one]
lemma polar_eq_Inter {s : set E} :
B.polar s = β x β s, {y : F | β₯B x yβ₯ β€ 1} :=
by { ext, simp only [polar_mem_iff, set.mem_Inter, set.mem_set_of_eq] }
/-- The map `B.polar : set E β set F` forms an order-reversing Galois connection with
`B.flip.polar : set F β set E`. We use `order_dual.to_dual` and `order_dual.of_dual` to express
that `polar` is order-reversing. -/
lemma polar_gc : galois_connection (order_dual.to_dual β B.polar)
(B.flip.polar β order_dual.of_dual) :=
Ξ» s t, β¨Ξ» h _ hx _ hy, h hy _ hx, Ξ» h _ hx _ hy, h hy _ hxβ©
@[simp] lemma polar_Union {ΞΉ} {s : ΞΉ β set E} : B.polar (β i, s i) = β i, B.polar (s i) :=
B.polar_gc.l_supr
@[simp] lemma polar_union {s t : set E} : B.polar (s βͺ t) = B.polar s β© B.polar t :=
B.polar_gc.l_sup
lemma polar_antitone : antitone (B.polar : set E β set F) := B.polar_gc.monotone_l
@[simp] lemma polar_empty : B.polar β
= set.univ := B.polar_gc.l_bot
@[simp] lemma polar_zero : B.polar ({0} : set E) = set.univ :=
begin
refine set.eq_univ_iff_forall.mpr (Ξ» y x hx, _),
rw [set.mem_singleton_iff.mp hx, map_zero, linear_map.zero_apply, norm_zero],
exact zero_le_one,
end
lemma subset_bipolar (s : set E) : s β B.flip.polar (B.polar s) :=
Ξ» x hx y hy, by { rw B.flip_apply, exact hy x hx }
@[simp] lemma tripolar_eq_polar (s : set E) : B.polar (B.flip.polar (B.polar s)) = B.polar s :=
begin
refine (B.polar_antitone (B.subset_bipolar s)).antisymm _,
convert subset_bipolar B.flip (B.polar s),
exact B.flip_flip.symm,
end
/-- The polar set is closed in the weak topology induced by `B.flip`. -/
lemma polar_weak_closed (s : set E) :
@is_closed _ (weak_bilin.topological_space B.flip) (B.polar s) :=
begin
rw polar_eq_Inter,
refine is_closed_Inter (Ξ» x, is_closed_Inter (Ξ» _, _)),
exact is_closed_le (weak_bilin.eval_continuous B.flip x).norm continuous_const,
end
end normed_ring
section nondiscrete_normed_field
variables [nondiscrete_normed_field π] [add_comm_monoid E] [add_comm_monoid F]
variables [module π E] [module π F]
variables (B : E ββ[π] F ββ[π] π)
lemma polar_univ (h : separating_right B) :
B.polar set.univ = {(0 : F)} :=
begin
rw set.eq_singleton_iff_unique_mem,
refine β¨by simp only [zero_mem_polar], Ξ» y hy, h _ (Ξ» x, _)β©,
refine norm_le_zero_iff.mp (le_of_forall_le_of_dense $ Ξ» Ξ΅ hΞ΅, _),
rcases normed_field.exists_norm_lt π hΞ΅ with β¨c, hc, hcΞ΅β©,
calc β₯B x yβ₯ = β₯cβ₯ * β₯B (cβ»ΒΉ β’ x) yβ₯ :
by rw [B.map_smul, linear_map.smul_apply, algebra.id.smul_eq_mul, norm_mul, norm_inv,
mul_inv_cancel_leftβ hc.ne']
... β€ Ξ΅ * 1 : mul_le_mul hcΞ΅.le (hy _ trivial) (norm_nonneg _) hΞ΅.le
... = Ξ΅ : mul_one _
end
end nondiscrete_normed_field
end linear_map
|
bada3eec3971aee9440353432c6fbb6ec43b4e4f | f2fbd9ce3f46053c664b74a5294d7d2f584e72d3 | /src/adic_space.lean | 5b0b4a98ecd845868cf8e23249bd4649e5cd4827 | [
"Apache-2.0"
] | permissive | jcommelin/lean-perfectoid-spaces | c656ae26a2338ee7a0072dab63baf577f079ca12 | d5ed816bcc116fd4cde5ce9aaf03905d00ee391c | refs/heads/master | 1,584,610,432,107 | 1,538,491,594,000 | 1,538,491,594,000 | 136,299,168 | 0 | 0 | null | 1,528,274,452,000 | 1,528,274,452,000 | null | UTF-8 | Lean | false | false | 2,298 | lean | import for_mathlib.prime
import for_mathlib.is_cover
import analysis.topology.topological_structures
import data.nat.prime
import algebra.group_power
import for_mathlib.presheaves
import for_mathlib.topology
import for_mathlib.topological_structures
import continuous_valuations
import Spa
import Huber_pair
universe u
open nat function
--definition π_X (A : Huber_pair) : presheaf_of_rings (Spa A) := sorry
-- it's a presheaf of complete topological rings on all opens (defined on rational opens
-- first and then extended to all via proj limits) -- Wedhorn p75
-- most of that would not be in the adic_space file.
--structure π₯pre :=
--(X : sorry)
--(πX : sorry)
--(v : sorry)
/-
We denote by π₯pre the category of tuples X = (X, O X , (v x ) xβX ), where
(a) X is a topological space,
(b) π_X is a presheaf of complete topological rings on X such that the stalk π_X,x of
π_X (considered as a presheaf of rings) is a local ring,
(c) v_x is an equivalence class of valuations on the stalk π_X,x such that supp(v_x) is the
maximal ideal of π_X,x .
Wedhorn p76 shows how Spa(A) gives an object of this for A a Huber pair
-/
--definition affinoid_adic_space (A : Huber_pair) : π₯pre := sorry
-- unwritten -- it's a full subcat of π₯pre
class preadic_space (X : Type) extends topological_space X
-- not logically necessary but should be easy
instance (A : Huber_pair) : preadic_space (Spa A) := sorry
-- attribute [class] _root_.is_open
instance preadic_space_restriction {X : Type} [preadic_space X] {U : opens X} :
preadic_space U := sorry
-- unwritten
class adic_space (X : Type) extends preadic_space X
-- a preadic_space_equiv is just an isom in π₯pre, or an isomorphism of preadic spaces.
-- is homeo in Lean yet?
-- unwritten
structure preadic_space_equiv (X Y : Type) [AX : preadic_space X] [AY : preadic_space Y] extends equiv X Y
definition is_preadic_space_equiv (X Y : Type) [AX : preadic_space X] [AY : preadic_space Y] :=
nonempty (preadic_space_equiv X Y)
definition preadic_space_pullback {X : Type} [preadic_space X] (U : set X) := {x : X // x β U}
instance pullback_is_preadic_space {X : Type} [preadic_space X] (U : set X) : preadic_space (preadic_space_pullback U) := sorry
-- notation `is_open` := _root_.is_open
|
77dc9bce8268cfbf871f2e9ff42ce210d5737991 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/polynomial/pochhammer.lean | 81f5de17ff7a734b62afaa0c354e6ee5deb8634e | [
"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,774 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import tactic.abel
import data.polynomial.eval
/-!
# The Pochhammer polynomials
We define and prove some basic relations about
`pochhammer S n : S[X] := X * (X + 1) * ... * (X + n - 1)`
which is also known as the rising factorial. A version of this definition
that is focused on `nat` can be found in `data.nat.factorial` as `nat.asc_factorial`.
## Implementation
As with many other families of polynomials, even though the coefficients are always in `β`,
we define the polynomial with coefficients in any `[semiring S]`.
## TODO
There is lots more in this direction:
* q-factorials, q-binomials, q-Pochhammer.
-/
universes u v
open polynomial
open_locale polynomial
section semiring
variables (S : Type u) [semiring S]
/--
`pochhammer S n` is the polynomial `X * (X+1) * ... * (X + n - 1)`,
with coefficients in the semiring `S`.
-/
noncomputable def pochhammer : β β S[X]
| 0 := 1
| (n+1) := X * (pochhammer n).comp (X + 1)
@[simp] lemma pochhammer_zero : pochhammer S 0 = 1 := rfl
@[simp] lemma pochhammer_one : pochhammer S 1 = X := by simp [pochhammer]
lemma pochhammer_succ_left (n : β) : pochhammer S (n+1) = X * (pochhammer S n).comp (X+1) :=
by rw pochhammer
section
variables {S} {T : Type v} [semiring T]
@[simp] lemma pochhammer_map (f : S β+* T) (n : β) : (pochhammer S n).map f = pochhammer T n :=
begin
induction n with n ih,
{ simp, },
{ simp [ih, pochhammer_succ_left, map_comp], },
end
end
@[simp, norm_cast] lemma pochhammer_eval_cast (n k : β) :
((pochhammer β n).eval k : S) = (pochhammer S n).eval k :=
begin
rw [βpochhammer_map (algebra_map β S), eval_map, βeq_nat_cast (algebra_map β S),
evalβ_at_nat_cast, nat.cast_id, eq_nat_cast],
end
lemma pochhammer_eval_zero {n : β} : (pochhammer S n).eval 0 = if n = 0 then 1 else 0 :=
begin
cases n,
{ simp, },
{ simp [X_mul, nat.succ_ne_zero, pochhammer_succ_left], }
end
lemma pochhammer_zero_eval_zero : (pochhammer S 0).eval 0 = 1 :=
by simp
@[simp] lemma pochhammer_ne_zero_eval_zero {n : β} (h : n β 0) : (pochhammer S n).eval 0 = 0 :=
by simp [pochhammer_eval_zero, h]
lemma pochhammer_succ_right (n : β) : pochhammer S (n+1) = pochhammer S n * (X + n) :=
begin
suffices h : pochhammer β (n+1) = pochhammer β n * (X + n),
{ apply_fun polynomial.map (algebra_map β S) at h,
simpa only [pochhammer_map, polynomial.map_mul, polynomial.map_add,
map_X, polynomial.map_nat_cast] using h },
induction n with n ih,
{ simp, },
{ conv_lhs
{ rw [pochhammer_succ_left, ih, mul_comp, βmul_assoc, βpochhammer_succ_left, add_comp, X_comp,
nat_cast_comp, add_assoc, add_comm (1 : β[X])], },
refl, },
end
lemma pochhammer_succ_eval {S : Type*} [semiring S] (n : β) (k : S) :
(pochhammer S (n + 1)).eval k = (pochhammer S n).eval k * (k + n) :=
by rw [pochhammer_succ_right, mul_add, eval_add, eval_mul_X, β nat.cast_comm, β C_eq_nat_cast,
eval_C_mul, nat.cast_comm, β mul_add]
lemma pochhammer_succ_comp_X_add_one (n : β) :
(pochhammer S (n + 1)).comp (X + 1) =
pochhammer S (n + 1) + (n + 1) β’ (pochhammer S n).comp (X + 1) :=
begin
suffices : (pochhammer β (n + 1)).comp (X + 1) =
pochhammer β (n + 1) + (n + 1) * (pochhammer β n).comp (X + 1),
{ simpa [map_comp] using congr_arg (polynomial.map (nat.cast_ring_hom S)) this },
nth_rewrite 1 pochhammer_succ_left,
rw [β add_mul, pochhammer_succ_right β n, mul_comp, mul_comm, add_comp, X_comp,
nat_cast_comp, add_comm βn, β add_assoc]
end
lemma polynomial.mul_X_add_nat_cast_comp {p q : S[X]} {n : β} :
(p * (X + n)).comp q = (p.comp q) * (q + n) :=
by rw [mul_add, add_comp, mul_X_comp, βnat.cast_comm, nat_cast_mul_comp, nat.cast_comm, mul_add]
lemma pochhammer_mul (n m : β) :
pochhammer S n * (pochhammer S m).comp (X + n) = pochhammer S (n + m) :=
begin
induction m with m ih,
{ simp, },
{ rw [pochhammer_succ_right, polynomial.mul_X_add_nat_cast_comp, βmul_assoc, ih,
nat.succ_eq_add_one, βadd_assoc, pochhammer_succ_right, nat.cast_add, add_assoc], }
end
lemma pochhammer_nat_eq_asc_factorial (n : β) :
β k, (pochhammer β k).eval (n + 1) = n.asc_factorial k
| 0 := by erw [eval_one]; refl
| (t + 1) := begin
rw [pochhammer_succ_right, eval_mul, pochhammer_nat_eq_asc_factorial t],
suffices : n.asc_factorial t * (n + 1 + t) = n.asc_factorial (t + 1), by simpa,
rw [nat.asc_factorial_succ, add_right_comm, mul_comm]
end
lemma pochhammer_nat_eq_desc_factorial (a b : β) :
(pochhammer β b).eval a = (a + b - 1).desc_factorial b :=
begin
cases b,
{ rw [nat.desc_factorial_zero, pochhammer_zero, polynomial.eval_one] },
rw [nat.add_succ, nat.succ_sub_succ, tsub_zero],
cases a,
{ rw [pochhammer_ne_zero_eval_zero _ b.succ_ne_zero, zero_add,
nat.desc_factorial_of_lt b.lt_succ_self] },
{ rw [nat.succ_add, βnat.add_succ, nat.add_desc_factorial_eq_asc_factorial,
pochhammer_nat_eq_asc_factorial] }
end
end semiring
section ordered_semiring
variables {S : Type*} [ordered_semiring S] [nontrivial S]
lemma pochhammer_pos (n : β) (s : S) (h : 0 < s) : 0 < (pochhammer S n).eval s :=
begin
induction n with n ih,
{ simp only [nat.nat_zero_eq_zero, pochhammer_zero, eval_one], exact zero_lt_one, },
{ rw [pochhammer_succ_right, mul_add, eval_add, βnat.cast_comm, eval_nat_cast_mul, eval_mul_X,
nat.cast_comm, βmul_add],
exact mul_pos ih
(lt_of_lt_of_le h ((le_add_iff_nonneg_right _).mpr (nat.cast_nonneg n))), }
end
end ordered_semiring
section factorial
open_locale nat
variables (S : Type*) [semiring S] (r n : β)
@[simp]
lemma pochhammer_eval_one (S : Type*) [semiring S] (n : β) :
(pochhammer S n).eval (1 : S) = (n! : S) :=
by rw_mod_cast [pochhammer_nat_eq_asc_factorial, nat.zero_asc_factorial]
lemma factorial_mul_pochhammer (S : Type*) [semiring S] (r n : β) :
(r! : S) * (pochhammer S n).eval (r + 1) = (r + n)! :=
by rw_mod_cast [pochhammer_nat_eq_asc_factorial, nat.factorial_mul_asc_factorial]
lemma pochhammer_nat_eval_succ (r : β) :
β n : β, n * (pochhammer β r).eval (n + 1) = (n + r) * (pochhammer β r).eval n
| 0 := begin
by_cases h : r = 0,
{ simp only [h, zero_mul, zero_add], },
{ simp only [pochhammer_eval_zero, zero_mul, if_neg h, mul_zero], }
end
| (k + 1) := by simp only [pochhammer_nat_eq_asc_factorial, nat.succ_asc_factorial, add_right_comm]
lemma pochhammer_eval_succ (r n : β) :
(n : S) * (pochhammer S r).eval (n + 1 : S) = (n + r) * (pochhammer S r).eval n :=
by exact_mod_cast congr_arg nat.cast (pochhammer_nat_eval_succ r n)
end factorial
|
f154d8efa6f52eac328b7b0bd85e8ad3104ed698 | 0845ae2ca02071debcfd4ac24be871236c01784f | /library/init/lean/parser/level.lean | b7a888a114c35d978cf13d122ee796b1affbc7f6 | [
"Apache-2.0"
] | permissive | GaloisInc/lean4 | 74c267eb0e900bfaa23df8de86039483ecbd60b7 | 228ddd5fdcd98dd4e9c009f425284e86917938aa | refs/heads/master | 1,643,131,356,301 | 1,562,715,572,000 | 1,562,715,572,000 | 192,390,898 | 0 | 0 | null | 1,560,792,750,000 | 1,560,792,749,000 | null | UTF-8 | Lean | false | false | 1,273 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
prelude
import init.lean.parser.parser
namespace Lean
namespace Parser
@[init mkBuiltinParsingTablesRef]
constant builtinLevelParsingTable : IO.Ref ParsingTables := default _
@[init] def regBuiltinLevelParserAttr : IO Unit :=
registerBuiltinParserAttribute `builtinLevelParser `Lean.Parser.builtinLevelParsingTable
def levelParserFn {k : ParserKind} (rbp : Nat) : ParserFn k :=
fun _ => runBuiltinParser "universe level" builtinLevelParsingTable rbp
@[inline] def levelParser {k : ParserKind} (rbp : Nat := 0) : Parser k :=
{ fn := levelParserFn rbp }
namespace Level
@[builtinLevelParser] def paren := parser! symbol "(" appPrec >> levelParser >> ")"
@[builtinLevelParser] def max := parser! "max" >> many1 (levelParser appPrec)
@[builtinLevelParser] def imax := parser! "imax" >> many1 (levelParser appPrec)
@[builtinLevelParser] def hole := parser! "_"
@[builtinLevelParser] def num : Parser := numLit
@[builtinLevelParser] def ident : Parser := ident
@[builtinLevelParser] def addLit := tparser! pushLeading >> symbol "+" (65:Nat) >> numLit
end Level
end Parser
end Lean
|
1c8b1bf3c79ec4736a3b91409c6c346de483b783 | bdb33f8b7ea65f7705fc342a178508e2722eb851 | /algebra/euclidean_domain.lean | ed8b93a2a547742d2149e85876100ff72852ca54 | [
"Apache-2.0"
] | permissive | rwbarton/mathlib | 939ae09bf8d6eb1331fc2f7e067d39567e10e33d | c13c5ea701bb1eec057e0a242d9f480a079105e9 | refs/heads/master | 1,584,015,335,862 | 1,524,142,167,000 | 1,524,142,167,000 | 130,614,171 | 0 | 0 | Apache-2.0 | 1,548,902,667,000 | 1,524,437,371,000 | Lean | UTF-8 | Lean | false | false | 7,197 | lean | /-
Copyright (c) 2018 Louis Carlin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Louis Carlin
Euclidean domains and Euclidean algorithm (extended to come)
A lot is based on pre-existing code in mathlib for natural number gcds
-/
import tactic.ring
universe u
class euclidean_domain (Ξ± : Type u) [decidable_eq Ξ±] extends integral_domain Ξ± :=
(quotient : Ξ± β Ξ± β Ξ±)
(remainder : Ξ± β Ξ± β Ξ±)
(quotient_mul_add_remainder_eq : β a b, (quotient a b) * b + (remainder a b) = a) -- This could be changed to the same order as int.mod_add_div. We normally write qb+r rather than r + qb though.
(valuation : Ξ± β β)
(valuation_remainder_lt : β a b, b β 0 β valuation (remainder a b) < valuation b)
(le_valuation_mul : β a b, b β 0 β valuation a β€ valuation (a*b))
/-
le_valuation_mul is often not a required in definitions of a euclidean domain since given the other properties we can show there is a (noncomputable) euclidean domain Ξ± with the property le_valuation_mul.
So potentially this definition could be split into two different ones (euclidean_domain_weak and euclidean_domain_strong) with a noncomputable function from weak to strong.
I've currently divided the lemmas into strong and weak depending on whether they require le_valuation_mul or not.
-/
namespace euclidean_domain
variable {Ξ± : Type u}
variables [decidable_eq Ξ±] [euclidean_domain Ξ±]
instance : has_div Ξ± := β¨quotientβ©
instance : has_mod Ξ± := β¨remainderβ©
instance : has_sizeof Ξ± := β¨valuationβ©
lemma gcd_decreasing (a b : Ξ±) (w : a β 0) : has_well_founded.r (b % a) a := valuation_remainder_lt b a w
def gcd : Ξ± β Ξ± β Ξ±
| a b := if a_zero : a = 0 then b
else have h : has_well_founded.r (b % a) a := gcd_decreasing a b a_zero,
gcd (b%a) a
/- weak lemmas -/
@[simp] lemma mod_zero (a : Ξ±) : a % 0 = a := by simpa using
quotient_mul_add_remainder_eq a 0
lemma dvd_mod_self (a : Ξ±) : a β£ a % a :=
begin
let d := (a/a)*a, -- ring tactic can't solve things without this
have : a%a = a - (a/a)*a, from
calc
a%a = d + a%a - d : by ring
... = (a/a)*a + a%a - (a/a)*a : by dsimp [d]; refl
... = a - (a/a)*a : by simp [(%), (/), quotient_mul_add_remainder_eq a a],
rw this,
exact dvd_sub (dvd_refl a) (dvd_mul_left a (a/a)),
end
lemma mod_lt : β (a : Ξ±) {b : Ξ±}, valuation b > valuation (0:Ξ±) β valuation (a%b) < valuation b :=
begin
intros a b h,
by_cases b_zero : (b=0),
{ rw b_zero at h,
have := lt_irrefl (valuation (0:Ξ±)),
contradiction },
{ exact valuation_remainder_lt a b b_zero }
end
lemma neq_zero_lt_mod_lt (a b : Ξ±) : b β 0 β valuation (a%b) < valuation b
| hnb := valuation_remainder_lt a b hnb
lemma dvd_mod {a b c : Ξ±} : c β£ a β c β£ b β c β£ a % b :=
begin
intros dvd_a dvd_b,
have : remainder a b = a - quotient a b * b, from
calc
a%b = quotient a b * b + a%b - quotient a b * b : by ring
... = a - quotient a b * b : by {dsimp[(%)]; rw (quotient_mul_add_remainder_eq a b)},
dsimp [(%)],
rw this,
exact dvd_sub dvd_a (dvd_mul_of_dvd_right dvd_b (a/b)),
end
/- strong lemmas -/
lemma val_lt_one (a : Ξ±) : valuation a < valuation (1:Ξ±) β a = 0 :=
begin
intro a_lt,
by_cases a = 0,
{ exact h },
{ have := le_valuation_mul (1:Ξ±) a h,
simp at this,
have := not_le_of_lt a_lt,
contradiction }
end
lemma val_dvd_le : β a b : Ξ±, b β£ a β a β 0 β valuation b β€ valuation a
| _ b β¨d, rflβ© ha :=
begin
by_cases d = 0,
{ simp[h] at ha,
contradiction },
{ exact le_valuation_mul b d h }
end
@[simp] lemma mod_one (a : Ξ±) : a % 1 = 0 :=
val_lt_one _ (valuation_remainder_lt a 1 one_ne_zero)
@[simp] lemma zero_mod (b : Ξ±) : 0 % b = 0 :=
begin
have h : remainder 0 b = b * (-quotient 0 b ), from
calc
remainder 0 b = quotient 0 b * b + remainder 0 b + b * (-quotient 0 b ) : by ring
... = b * (-quotient 0 b ) : by rw [quotient_mul_add_remainder_eq 0 b, zero_add],
by_cases quotient_zero : (-quotient 0 b) = 0,
{ simp[quotient_zero] at h,
exact h },
{ by_cases h'' : b = 0,
{ rw h'',
simp },
{ have := not_le_of_lt (valuation_remainder_lt 0 b h''),
rw h at this,
have := le_valuation_mul b (-quotient 0 b) quotient_zero,
contradiction }}
end
@[simp] lemma zero_div (b : Ξ±) (hnb : b β 0) : 0 / b = 0 :=
begin
have h1 : remainder 0 b = 0, from zero_mod b,
have h2 := quotient_mul_add_remainder_eq 0 b,
simp[h1] at h2,
cases eq_zero_or_eq_zero_of_mul_eq_zero h2,
{ exact h },
{ contradiction }
end
@[simp] lemma mod_self (a : Ξ±) : a % a = 0 :=
let β¨m, a_mulβ© := dvd_mod_self a in
begin
by_cases m = 0,
{ rw [h, mul_zero] at a_mul,
exact a_mul },
{ by_cases a_zero : a = 0,
{ rw a_zero,
simp },
{ have := le_valuation_mul a m h,
rw βa_mul at this,
have := not_le_of_lt (valuation_remainder_lt a a a_zero),
contradiction}}
end
lemma div_self (a : Ξ±) : a β 0 β a / a = (1:Ξ±) :=
begin
intro hna,
have wit_aa := quotient_mul_add_remainder_eq a a,
have a_mod_a := mod_self a,
dsimp [(%)] at a_mod_a,
simp [a_mod_a] at wit_aa,
have h1 : 1 * a = a, from one_mul a,
conv at wit_aa {for a [4] {rw βh1}},
exact eq_of_mul_eq_mul_right hna wit_aa
end
/- weak gcd lemmas -/
@[simp] theorem gcd_zero_left (a : Ξ±) : gcd 0 a = a :=
begin
rw gcd,
simp,
end
@[elab_as_eliminator]
theorem gcd.induction {P : Ξ± β Ξ± β Prop}
(a b : Ξ±)
(H0 : β x, P 0 x)
(H1 : β a b, a β 0 β P (b%a) a β P a b) :
P a b :=
@well_founded.induction _ _ (has_well_founded.wf Ξ±) (Ξ»a, βb, P a b) a
begin
intros c IH,
by_cases c = 0,
{ rw h,
exact H0 },
{ intro b,
exact H1 c b (h) (IH (b%c) (neq_zero_lt_mod_lt b c h) c) }
end
b
theorem gcd_dvd (a b : Ξ±) : (gcd a b β£ a) β§ (gcd a b β£ b) :=
gcd.induction a b
(Ξ» b, by simp)
begin
intros a b aneq h_dvd,
rw gcd,
simp [aneq],
induction h_dvd,
split,
{ exact h_dvd_right },
{ conv {for b [2] {rw β(quotient_mul_add_remainder_eq b a)}},
have h_dvd_right_a:= dvd_mul_of_dvd_right h_dvd_right (b/a),
exact dvd_add h_dvd_right_a h_dvd_left }
end
theorem gcd_dvd_left (a b : Ξ±) : gcd a b β£ a := (gcd_dvd a b).left
theorem gcd_dvd_right (a b : Ξ±) : gcd a b β£ b := (gcd_dvd a b).right
theorem dvd_gcd {a b c : Ξ±} : c β£ a β c β£ b β c β£ gcd a b :=
gcd.induction a b
begin
intros b dvd_0 dvd_b,
simp,
exact dvd_b
end
begin
intros a b hna d dvd_a dvd_b,
rw gcd,
simp [hna],
exact d (dvd_mod dvd_b dvd_a) dvd_a,
end
/- strong gcd lemmas -/
@[simp] theorem gcd_zero_right (a : Ξ±) : gcd a 0 = a :=
begin
by_cases (a=0),
{ simp[h] },
{ rw gcd,
simp [h] }
end
@[simp] theorem gcd_one_left (a : Ξ±) : gcd 1 a = 1 :=
begin
rw [gcd],
simp,
end
theorem gcd_next (a b : Ξ±) : gcd a b = gcd (b % a) a :=
begin
by_cases (a=0),
{ simp [h] },
{ rw gcd,
simp [h] }
end
@[simp] theorem gcd_self (a : Ξ±) : gcd a a = a :=
by rw [gcd_next a a, mod_self a, gcd_zero_left]
end euclidean_domain |
7e83e84ea188a916ad56712681cc8eae45c6a82e | 94e33a31faa76775069b071adea97e86e218a8ee | /src/analysis/analytic/inverse.lean | 7b8f71305b137ce23f59511056312b596cf24891 | [
"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 | 27,251 | lean | /-
Copyright (c) 2021 SΓ©bastien GouΓ«zel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: SΓ©bastien GouΓ«zel
-/
import analysis.analytic.composition
import tactic.congrm
/-!
# Inverse of analytic functions
We construct the left and right inverse of a formal multilinear series with invertible linear term,
we prove that they coincide and study their properties (notably convergence).
## Main statements
* `p.left_inv i`: the formal left inverse of the formal multilinear series `p`,
for `i : E βL[π] F` which coincides with `pβ`.
* `p.right_inv i`: the formal right inverse of the formal multilinear series `p`,
for `i : E βL[π] F` which coincides with `pβ`.
* `p.left_inv_comp` says that `p.left_inv i` is indeed a left inverse to `p` when `pβ = i`.
* `p.right_inv_comp` says that `p.right_inv i` is indeed a right inverse to `p` when `pβ = i`.
* `p.left_inv_eq_right_inv`: the two inverses coincide.
* `p.radius_right_inv_pos_of_radius_pos`: if a power series has a positive radius of convergence,
then so does its inverse.
-/
open_locale big_operators classical topological_space
open finset filter
namespace formal_multilinear_series
variables {π : Type*} [nondiscrete_normed_field π]
{E : Type*} [normed_group E] [normed_space π E]
{F : Type*} [normed_group F] [normed_space π F]
/-! ### The left inverse of a formal multilinear series -/
/-- The left inverse of a formal multilinear series, where the `n`-th term is defined inductively
in terms of the previous ones to make sure that `(left_inv p i) β p = id`. For this, the linear term
`pβ` in `p` should be invertible. In the definition, `i` is a linear isomorphism that should
coincide with `pβ`, so that one can use its inverse in the construction. The definition does not
use that `i = pβ`, but proofs that the definition is well-behaved do.
The `n`-th term in `q β p` is `β qβ (p_{jβ}, ..., p_{jβ})` over `jβ + ... + jβ = n`. In this
expression, `qβ` appears only once, in `qβ (pβ, ..., pβ)`. We adjust the definition so that this
term compensates the rest of the sum, using `iβ»ΒΉ` as an inverse to `pβ`.
These formulas only make sense when the constant term `pβ` vanishes. The definition we give is
general, but it ignores the value of `pβ`.
-/
noncomputable def left_inv (p : formal_multilinear_series π E F) (i : E βL[π] F) :
formal_multilinear_series π F E
| 0 := 0
| 1 := (continuous_multilinear_curry_fin1 π F E).symm i.symm
| (n+2) := - β c : {c : composition (n+2) // c.length < n + 2},
have (c : composition (n+2)).length < n+2 := c.2,
(left_inv (c : composition (n+2)).length).comp_along_composition
(p.comp_continuous_linear_map i.symm) c
@[simp] lemma left_inv_coeff_zero (p : formal_multilinear_series π E F) (i : E βL[π] F) :
p.left_inv i 0 = 0 := by rw left_inv
@[simp] lemma left_inv_coeff_one (p : formal_multilinear_series π E F) (i : E βL[π] F) :
p.left_inv i 1 = (continuous_multilinear_curry_fin1 π F E).symm i.symm := by rw left_inv
/-- The left inverse does not depend on the zeroth coefficient of a formal multilinear
series. -/
lemma left_inv_remove_zero (p : formal_multilinear_series π E F) (i : E βL[π] F) :
p.remove_zero.left_inv i = p.left_inv i :=
begin
ext1 n,
induction n using nat.strong_rec' with n IH,
cases n, { simp }, -- if one replaces `simp` with `refl`, the proof times out in the kernel.
cases n, { simp }, -- TODO: why?
simp only [left_inv, neg_inj],
refine finset.sum_congr rfl (Ξ» c cuniv, _),
rcases c with β¨c, hcβ©,
ext v,
dsimp,
simp [IH _ hc],
end
/-- The left inverse to a formal multilinear series is indeed a left inverse, provided its linear
term is invertible. -/
lemma left_inv_comp (p : formal_multilinear_series π E F) (i : E βL[π] F)
(h : p 1 = (continuous_multilinear_curry_fin1 π E F).symm i) :
(left_inv p i).comp p = id π E :=
begin
ext n v,
cases n,
{ simp only [left_inv, continuous_multilinear_map.zero_apply, id_apply_ne_one, ne.def,
not_false_iff, zero_ne_one, comp_coeff_zero']},
cases n,
{ simp only [left_inv, comp_coeff_one, h, id_apply_one, continuous_linear_equiv.coe_apply,
continuous_linear_equiv.symm_apply_apply, continuous_multilinear_curry_fin1_symm_apply] },
have A : (finset.univ : finset (composition (n+2)))
= {c | composition.length c < n + 2}.to_finset βͺ {composition.ones (n+2)},
{ refine subset.antisymm (Ξ» c hc, _) (subset_univ _),
by_cases h : c.length < n + 2,
{ simp [h] },
{ simp [composition.eq_ones_iff_le_length.2 (not_lt.1 h)] } },
have B : disjoint ({c | composition.length c < n + 2} : set (composition (n + 2))).to_finset
{composition.ones (n+2)}, by simp,
have C : (p.left_inv i (composition.ones (n + 2)).length)
(Ξ» (j : fin (composition.ones n.succ.succ).length), p 1 (Ξ» k,
v ((fin.cast_le (composition.length_le _)) j)))
= p.left_inv i (n+2) (Ξ» (j : fin (n+2)), p 1 (Ξ» k, v j)),
{ apply formal_multilinear_series.congr _ (composition.ones_length _) (Ξ» j hj1 hj2, _),
exact formal_multilinear_series.congr _ rfl (Ξ» k hk1 hk2, by congr) },
have D : p.left_inv i (n+2) (Ξ» (j : fin (n+2)), p 1 (Ξ» k, v j)) =
- β (c : composition (n + 2)) in {c : composition (n + 2) | c.length < n + 2}.to_finset,
(p.left_inv i c.length) (p.apply_composition c v),
{ simp only [left_inv, continuous_multilinear_map.neg_apply, neg_inj,
continuous_multilinear_map.sum_apply],
convert (sum_to_finset_eq_subtype (Ξ» (c : composition (n+2)), c.length < n+2)
(Ξ» (c : composition (n+2)), (continuous_multilinear_map.comp_along_composition
(p.comp_continuous_linear_map β(i.symm)) c (p.left_inv i c.length))
(Ξ» (j : fin (n + 2)), p 1 (Ξ» (k : fin 1), v j)))).symm.trans _,
simp only [comp_continuous_linear_map_apply_composition,
continuous_multilinear_map.comp_along_composition_apply],
congr,
ext c,
congr,
ext k,
simp [h] },
simp [formal_multilinear_series.comp, show n + 2 β 1, by dec_trivial, A, finset.sum_union B,
apply_composition_ones, C, D],
end
/-! ### The right inverse of a formal multilinear series -/
/-- The right inverse of a formal multilinear series, where the `n`-th term is defined inductively
in terms of the previous ones to make sure that `p β (right_inv p i) = id`. For this, the linear
term `pβ` in `p` should be invertible. In the definition, `i` is a linear isomorphism that should
coincide with `pβ`, so that one can use its inverse in the construction. The definition does not
use that `i = pβ`, but proofs that the definition is well-behaved do.
The `n`-th term in `p β q` is `β pβ (q_{jβ}, ..., q_{jβ})` over `jβ + ... + jβ = n`. In this
expression, `qβ` appears only once, in `pβ (qβ)`. We adjust the definition of `qβ` so that this
term compensates the rest of the sum, using `iβ»ΒΉ` as an inverse to `pβ`.
These formulas only make sense when the constant term `pβ` vanishes. The definition we give is
general, but it ignores the value of `pβ`.
-/
noncomputable def right_inv (p : formal_multilinear_series π E F) (i : E βL[π] F) :
formal_multilinear_series π F E
| 0 := 0
| 1 := (continuous_multilinear_curry_fin1 π F E).symm i.symm
| (n+2) :=
let q : formal_multilinear_series π F E := Ξ» k, if h : k < n + 2 then right_inv k else 0 in
- (i.symm : F βL[π] E).comp_continuous_multilinear_map ((p.comp q) (n+2))
@[simp] lemma right_inv_coeff_zero (p : formal_multilinear_series π E F) (i : E βL[π] F) :
p.right_inv i 0 = 0 := by rw right_inv
@[simp] lemma right_inv_coeff_one (p : formal_multilinear_series π E F) (i : E βL[π] F) :
p.right_inv i 1 = (continuous_multilinear_curry_fin1 π F E).symm i.symm := by rw right_inv
/-- The right inverse does not depend on the zeroth coefficient of a formal multilinear
series. -/
lemma right_inv_remove_zero (p : formal_multilinear_series π E F) (i : E βL[π] F) :
p.remove_zero.right_inv i = p.right_inv i :=
begin
ext1 n,
induction n using nat.strong_rec' with n IH,
rcases n with _|_|n,
{ simp only [right_inv_coeff_zero] },
{ simp only [right_inv_coeff_one] },
simp only [right_inv, neg_inj],
rw remove_zero_comp_of_pos _ _ (add_pos_of_nonneg_of_pos (n.zero_le) zero_lt_two),
congrm i.symm.to_continuous_linear_map.comp_continuous_multilinear_map (p.comp (Ξ» k, _) _),
by_cases hk : k < n+2; simp [hk, IH]
end
lemma comp_right_inv_aux1 {n : β} (hn : 0 < n)
(p : formal_multilinear_series π E F) (q : formal_multilinear_series π F E) (v : fin n β F) :
p.comp q n v =
(β (c : composition n) in {c : composition n | 1 < c.length}.to_finset,
p c.length (q.apply_composition c v)) + p 1 (Ξ» i, q n v) :=
begin
have A : (finset.univ : finset (composition n))
= {c | 1 < composition.length c}.to_finset βͺ {composition.single n hn},
{ refine subset.antisymm (Ξ» c hc, _) (subset_univ _),
by_cases h : 1 < c.length,
{ simp [h] },
{ have : c.length = 1,
by { refine (eq_iff_le_not_lt.2 β¨ _, hβ©).symm, exact c.length_pos_of_pos hn },
rw β composition.eq_single_iff_length hn at this,
simp [this] } },
have B : disjoint ({c | 1 < composition.length c} : set (composition n)).to_finset
{composition.single n hn}, by simp,
have C : p (composition.single n hn).length
(q.apply_composition (composition.single n hn) v)
= p 1 (Ξ» (i : fin 1), q n v),
{ apply p.congr (composition.single_length hn) (Ξ» j hj1 hj2, _),
simp [apply_composition_single] },
simp [formal_multilinear_series.comp, A, finset.sum_union B, C],
end
lemma comp_right_inv_aux2
(p : formal_multilinear_series π E F) (i : E βL[π] F) (n : β) (v : fin (n + 2) β F) :
β (c : composition (n + 2)) in {c : composition (n + 2) | 1 < c.length}.to_finset,
p c.length (apply_composition (Ξ» (k : β), ite (k < n + 2) (p.right_inv i k) 0) c v) =
β (c : composition (n + 2)) in {c : composition (n + 2) | 1 < c.length}.to_finset,
p c.length ((p.right_inv i).apply_composition c v) :=
begin
have N : 0 < n + 2, by dec_trivial,
refine sum_congr rfl (Ξ» c hc, p.congr rfl (Ξ» j hj1 hj2, _)),
have : β k, c.blocks_fun k < n + 2,
{ simp only [set.mem_to_finset, set.mem_set_of_eq] at hc,
simp [β composition.ne_single_iff N, composition.eq_single_iff_length, ne_of_gt hc] },
simp [apply_composition, this],
end
/-- The right inverse to a formal multilinear series is indeed a right inverse, provided its linear
term is invertible and its constant term vanishes. -/
lemma comp_right_inv (p : formal_multilinear_series π E F) (i : E βL[π] F)
(h : p 1 = (continuous_multilinear_curry_fin1 π E F).symm i) (h0 : p 0 = 0) :
p.comp (right_inv p i) = id π F :=
begin
ext n v,
cases n,
{ simp only [h0, continuous_multilinear_map.zero_apply, id_apply_ne_one, ne.def, not_false_iff,
zero_ne_one, comp_coeff_zero']},
cases n,
{ simp only [comp_coeff_one, h, right_inv, continuous_linear_equiv.apply_symm_apply, id_apply_one,
continuous_linear_equiv.coe_apply, continuous_multilinear_curry_fin1_symm_apply] },
have N : 0 < n+2, by dec_trivial,
simp [comp_right_inv_aux1 N, h, right_inv, lt_irrefl n, show n + 2 β 1, by dec_trivial,
β sub_eq_add_neg, sub_eq_zero, comp_right_inv_aux2],
end
lemma right_inv_coeff (p : formal_multilinear_series π E F) (i : E βL[π] F) (n : β) (hn : 2 β€ n) :
p.right_inv i n = - (i.symm : F βL[π] E).comp_continuous_multilinear_map
(β c in ({c | 1 < composition.length c}.to_finset : finset (composition n)),
p.comp_along_composition (p.right_inv i) c) :=
begin
cases n, { exact false.elim (zero_lt_two.not_le hn) },
cases n, { exact false.elim (one_lt_two.not_le hn) },
simp only [right_inv, neg_inj],
congr' 1,
ext v,
have N : 0 < n + 2, by dec_trivial,
have : (p 1) (Ξ» (i : fin 1), 0) = 0 := continuous_multilinear_map.map_zero _,
simp [comp_right_inv_aux1 N, lt_irrefl n, this, comp_right_inv_aux2]
end
/-! ### Coincidence of the left and the right inverse -/
private lemma left_inv_eq_right_inv_aux (p : formal_multilinear_series π E F) (i : E βL[π] F)
(h : p 1 = (continuous_multilinear_curry_fin1 π E F).symm i) (h0 : p 0 = 0) :
left_inv p i = right_inv p i := calc
left_inv p i = (left_inv p i).comp (id π F) : by simp
... = (left_inv p i).comp (p.comp (right_inv p i)) : by rw comp_right_inv p i h h0
... = ((left_inv p i).comp p).comp (right_inv p i) : by rw comp_assoc
... = (id π E).comp (right_inv p i) : by rw left_inv_comp p i h
... = right_inv p i : by simp
/-- The left inverse and the right inverse of a formal multilinear series coincide. This is not at
all obvious from their definition, but it follows from uniqueness of inverses (which comes from the
fact that composition is associative on formal multilinear series). -/
theorem left_inv_eq_right_inv (p : formal_multilinear_series π E F) (i : E βL[π] F)
(h : p 1 = (continuous_multilinear_curry_fin1 π E F).symm i) :
left_inv p i = right_inv p i := calc
left_inv p i = left_inv p.remove_zero i : by rw left_inv_remove_zero
... = right_inv p.remove_zero i : by { apply left_inv_eq_right_inv_aux; simp [h] }
... = right_inv p i : by rw right_inv_remove_zero
/-!
### Convergence of the inverse of a power series
Assume that `p` is a convergent multilinear series, and let `q` be its (left or right) inverse.
Using the left-inverse formula gives
$$
q_n = - (p_1)^{-n} \sum_{k=0}^{n-1} \sum_{i_1 + \dotsc + i_k = n} q_k (p_{i_1}, \dotsc, p_{i_k}).
$$
Assume for simplicity that we are in dimension `1` and `pβ = 1`. In the formula for `qβ`, the term
`q_{n-1}` appears with a multiplicity of `n-1` (choosing the index `i_j` for which `i_j = 2` while
all the other indices are equal to `1`), which indicates that `qβ` might grow like `n!`. This is
bad for summability properties.
It turns out that the right-inverse formula is better behaved, and should instead be used for this
kind of estimate. It reads
$$
q_n = - (p_1)^{-1} \sum_{k=2}^n \sum_{i_1 + \dotsc + i_k = n} p_k (q_{i_1}, \dotsc, q_{i_k}).
$$
Here, `q_{n-1}` can only appear in the term with `k = 2`, and it only appears twice, so there is
hope this formula can lead to an at most geometric behavior.
Let `Qβ = β₯qββ₯`. Bounding `β₯pββ₯` with `C r^k` gives an inequality
$$
Q_n β€ C' \sum_{k=2}^n r^k \sum_{i_1 + \dotsc + i_k = n} Q_{i_1} \dotsm Q_{i_k}.
$$
This formula is not enough to prove by naive induction on `n` a bound of the form `Qβ β€ D R^n`.
However, assuming that the inequality above were an equality, one could get a formula for the
generating series of the `Qβ`:
$$
\begin{align}
Q(z) & := \sum Q_n z^n = Q_1 z + C' \sum_{2 \leq k \leq n} \sum_{i_1 + \dotsc + i_k = n}
(r z^{i_1} Q_{i_1}) \dotsm (r z^{i_k} Q_{i_k})
\\ & = Q_1 z + C' \sum_{k = 2}^\infty (\sum_{i_1 \geq 1} r z^{i_1} Q_{i_1})
\dotsm (\sum_{i_k \geq 1} r z^{i_k} Q_{i_k})
\\ & = Q_1 z + C' \sum_{k = 2}^\infty (r Q(z))^k
= Q_1 z + C' (r Q(z))^2 / (1 - r Q(z)).
\end{align}
$$
One can solve this formula explicitly. The solution is analytic in a neighborhood of `0` in `β`,
hence its coefficients grow at most geometrically (by a contour integral argument), and therefore
the original `Qβ`, which are bounded by these ones, are also at most geometric.
This classical argument is not really satisfactory, as it requires an a priori bound on a complex
analytic function. Another option would be to compute explicitly its terms (with binomial
coefficients) to obtain an explicit geometric bound, but this would be very painful.
Instead, we will use the above intuition, but in a slightly different form, with finite sums and an
induction. I learnt this trick in [pΓΆschel2017siegelsternberg]. Let
$S_n = \sum_{k=1}^n Q_k a^k$ (where `a` is a positive real parameter to be chosen suitably small).
The above computation but with finite sums shows that
$$
S_n \leq Q_1 a + C' \sum_{k=2}^n (r S_{n-1})^k.
$$
In particular, $S_n \leq Q_1 a + C' (r S_{n-1})^2 / (1- r S_{n-1})$.
Assume that $S_{n-1} \leq K a$, where `K > Qβ` is fixed and `a` is small enough so that
`r K a β€ 1/2` (to control the denominator). Then this equation gives a bound
$S_n \leq Q_1 a + 2 C' r^2 K^2 a^2$.
If `a` is small enough, this is bounded by `K a` as the second term is quadratic in `a`, and
therefore negligible.
By induction, we deduce `Sβ β€ K a` for all `n`, which gives in particular the fact that `aβΏ Qβ`
remains bounded.
-/
/-- First technical lemma to control the growth of coefficients of the inverse. Bound the explicit
expression for `β_{k<n+1} aα΅ Qβ` in terms of a sum of powers of the same sum one step before,
in a general abstract setup. -/
lemma radius_right_inv_pos_of_radius_pos_aux1
(n : β) (p : β β β) (hp : β k, 0 β€ p k) {r a : β} (hr : 0 β€ r) (ha : 0 β€ a) :
β k in Ico 2 (n + 1), a ^ k *
(β c in ({c | 1 < composition.length c}.to_finset : finset (composition k)),
r ^ c.length * β j, p (c.blocks_fun j))
β€ β j in Ico 2 (n + 1), r ^ j * (β k in Ico 1 n, a ^ k * p k) ^ j :=
calc
β k in Ico 2 (n + 1), a ^ k *
(β c in ({c | 1 < composition.length c}.to_finset : finset (composition k)),
r ^ c.length * β j, p (c.blocks_fun j))
= β k in Ico 2 (n + 1),
(β c in ({c | 1 < composition.length c}.to_finset : finset (composition k)),
β j, r * (a ^ (c.blocks_fun j) * p (c.blocks_fun j))) :
begin
simp_rw [mul_sum],
apply sum_congr rfl (Ξ» k hk, _),
apply sum_congr rfl (Ξ» c hc, _),
rw [prod_mul_distrib, prod_mul_distrib, prod_pow_eq_pow_sum, composition.sum_blocks_fun,
prod_const, card_fin],
ring,
end
... β€ β d in comp_partial_sum_target 2 (n + 1) n,
β (j : fin d.2.length), r * (a ^ d.2.blocks_fun j * p (d.2.blocks_fun j)) :
begin
rw sum_sigma',
refine sum_le_sum_of_subset_of_nonneg _ (Ξ» x hx1 hx2,
prod_nonneg (Ξ» j hj, mul_nonneg hr (mul_nonneg (pow_nonneg ha _) (hp _)))),
rintros β¨k, cβ© hd,
simp only [set.mem_to_finset, mem_Ico, mem_sigma, set.mem_set_of_eq] at hd,
simp only [mem_comp_partial_sum_target_iff],
refine β¨hd.2, c.length_le.trans_lt hd.1.2, Ξ» j, _β©,
have : c β composition.single k (zero_lt_two.trans_le hd.1.1),
by simp [composition.eq_single_iff_length, ne_of_gt hd.2],
rw composition.ne_single_iff at this,
exact (this j).trans_le (nat.lt_succ_iff.mp hd.1.2)
end
... = β e in comp_partial_sum_source 2 (n+1) n, β (j : fin e.1), r * (a ^ e.2 j * p (e.2 j)) :
begin
symmetry,
apply comp_change_of_variables_sum,
rintros β¨k, blocks_funβ© H,
have K : (comp_change_of_variables 2 (n + 1) n β¨k, blocks_funβ© H).snd.length = k, by simp,
congr' 2; try { rw K },
rw fin.heq_fun_iff K.symm,
assume j,
rw comp_change_of_variables_blocks_fun,
end
... = β j in Ico 2 (n+1), r ^ j * (β k in Ico 1 n, a ^ k * p k) ^ j :
begin
rw [comp_partial_sum_source, β sum_sigma' (Ico 2 (n + 1))
(Ξ» (k : β), (fintype.pi_finset (Ξ» (i : fin k), Ico 1 n) : finset (fin k β β)))
(Ξ» n e, β (j : fin n), r * (a ^ e j * p (e j)))],
apply sum_congr rfl (Ξ» j hj, _),
simp only [β @multilinear_map.mk_pi_algebra_apply β (fin j) _ _ β],
simp only [β multilinear_map.map_sum_finset (multilinear_map.mk_pi_algebra β (fin j) β)
(Ξ» k (m : β), r * (a ^ m * p m))],
simp only [multilinear_map.mk_pi_algebra_apply],
dsimp,
simp [prod_const, β mul_sum, mul_pow],
end
/-- Second technical lemma to control the growth of coefficients of the inverse. Bound the explicit
expression for `β_{k<n+1} aα΅ Qβ` in terms of a sum of powers of the same sum one step before,
in the specific setup we are interesting in, by reducing to the general bound in
`radius_right_inv_pos_of_radius_pos_aux1`. -/
lemma radius_right_inv_pos_of_radius_pos_aux2
{n : β} (hn : 2 β€ n + 1) (p : formal_multilinear_series π E F) (i : E βL[π] F)
{r a C : β} (hr : 0 β€ r) (ha : 0 β€ a) (hC : 0 β€ C) (hp : β n, β₯p nβ₯ β€ C * r ^ n) :
(β k in Ico 1 (n + 1), a ^ k * β₯p.right_inv i kβ₯) β€
β₯(i.symm : F βL[π] E)β₯ * a + β₯(i.symm : F βL[π] E)β₯ * C * β k in Ico 2 (n + 1),
(r * ((β j in Ico 1 n, a ^ j * β₯p.right_inv i jβ₯))) ^ k :=
let I := β₯(i.symm : F βL[π] E)β₯ in calc
β k in Ico 1 (n + 1), a ^ k * β₯p.right_inv i kβ₯
= a * I + β k in Ico 2 (n + 1), a ^ k * β₯p.right_inv i kβ₯ :
by simp only [linear_isometry_equiv.norm_map, pow_one, right_inv_coeff_one,
nat.Ico_succ_singleton, sum_singleton, β sum_Ico_consecutive _ one_le_two hn]
... = a * I + β k in Ico 2 (n + 1), a ^ k *
β₯(i.symm : F βL[π] E).comp_continuous_multilinear_map
(β c in ({c | 1 < composition.length c}.to_finset : finset (composition k)),
p.comp_along_composition (p.right_inv i) c)β₯ :
begin
congr' 1,
apply sum_congr rfl (Ξ» j hj, _),
rw [right_inv_coeff _ _ _ (mem_Ico.1 hj).1, norm_neg],
end
... β€ a * β₯(i.symm : F βL[π] E)β₯ + β k in Ico 2 (n + 1), a ^ k * (I *
(β c in ({c | 1 < composition.length c}.to_finset : finset (composition k)),
C * r ^ c.length * β j, β₯p.right_inv i (c.blocks_fun j)β₯)) :
begin
apply_rules [add_le_add, le_refl, sum_le_sum (Ξ» j hj, _), mul_le_mul_of_nonneg_left,
pow_nonneg, ha],
apply (continuous_linear_map.norm_comp_continuous_multilinear_map_le _ _).trans,
apply mul_le_mul_of_nonneg_left _ (norm_nonneg _),
apply (norm_sum_le _ _).trans,
apply sum_le_sum (Ξ» c hc, _),
apply (comp_along_composition_norm _ _ _).trans,
apply mul_le_mul_of_nonneg_right (hp _),
exact prod_nonneg (Ξ» j hj, norm_nonneg _),
end
... = I * a + I * C * β k in Ico 2 (n + 1), a ^ k *
(β c in ({c | 1 < composition.length c}.to_finset : finset (composition k)),
r ^ c.length * β j, β₯p.right_inv i (c.blocks_fun j)β₯) :
begin
simp_rw [mul_assoc C, β mul_sum, β mul_assoc, mul_comm _ (β₯βi.symmβ₯), mul_assoc, β mul_sum,
β mul_assoc, mul_comm _ C, mul_assoc, β mul_sum],
ring,
end
... β€ I * a + I * C * β k in Ico 2 (n+1), (r * ((β j in Ico 1 n, a ^ j * β₯p.right_inv i jβ₯))) ^ k :
begin
apply_rules [add_le_add, le_refl, mul_le_mul_of_nonneg_left, norm_nonneg, hC, mul_nonneg],
simp_rw [mul_pow],
apply radius_right_inv_pos_of_radius_pos_aux1 n (Ξ» k, β₯p.right_inv i kβ₯)
(Ξ» k, norm_nonneg _) hr ha,
end
/-- If a a formal multilinear series has a positive radius of convergence, then its right inverse
also has a positive radius of convergence. -/
theorem radius_right_inv_pos_of_radius_pos (p : formal_multilinear_series π E F) (i : E βL[π] F)
(hp : 0 < p.radius) : 0 < (p.right_inv i).radius :=
begin
obtain β¨C, r, Cpos, rpos, pleβ© : β C r (hC : 0 < C) (hr : 0 < r), β (n : β), β₯p nβ₯ β€ C * r ^ n :=
le_mul_pow_of_radius_pos p hp,
let I := β₯(i.symm : F βL[π] E)β₯,
-- choose `a` small enough to make sure that `β_{k β€ n} aα΅ Qβ` will be controllable by
-- induction
obtain β¨a, apos, ha1, ha2β© : β a (apos : 0 < a),
(2 * I * C * r^2 * (I + 1) ^ 2 * a β€ 1) β§ (r * (I + 1) * a β€ 1/2),
{ have : tendsto (Ξ» a, 2 * I * C * r^2 * (I + 1) ^ 2 * a) (π 0)
(π (2 * I * C * r^2 * (I + 1) ^ 2 * 0)) := tendsto_const_nhds.mul tendsto_id,
have A : βαΆ a in π 0, 2 * I * C * r^2 * (I + 1) ^ 2 * a < 1,
by { apply (tendsto_order.1 this).2, simp [zero_lt_one] },
have : tendsto (Ξ» a, r * (I + 1) * a) (π 0)
(π (r * (I + 1) * 0)) := tendsto_const_nhds.mul tendsto_id,
have B : βαΆ a in π 0, r * (I + 1) * a < 1/2,
by { apply (tendsto_order.1 this).2, simp [zero_lt_one] },
have C : βαΆ a in π[>] (0 : β), (0 : β) < a,
by { filter_upwards [self_mem_nhds_within] with _ ha using ha },
rcases (C.and ((A.and B).filter_mono inf_le_left)).exists with β¨a, haβ©,
exact β¨a, ha.1, ha.2.1.le, ha.2.2.leβ© },
-- check by induction that the partial sums are suitably bounded, using the choice of `a` and the
-- inductive control from Lemma `radius_right_inv_pos_of_radius_pos_aux2`.
let S := Ξ» n, β k in Ico 1 n, a ^ k * β₯p.right_inv i kβ₯,
have IRec : β n, 1 β€ n β S n β€ (I + 1) * a,
{ apply nat.le_induction,
{ simp only [S],
rw [Ico_eq_empty_of_le (le_refl 1), sum_empty],
exact mul_nonneg (add_nonneg (norm_nonneg _) zero_le_one) apos.le },
{ assume n one_le_n hn,
have In : 2 β€ n + 1, by linarith,
have Snonneg : 0 β€ S n :=
sum_nonneg (Ξ» x hx, mul_nonneg (pow_nonneg apos.le _) (norm_nonneg _)),
have rSn : r * S n β€ 1/2 := calc
r * S n β€ r * ((I+1) * a) : mul_le_mul_of_nonneg_left hn rpos.le
... β€ 1/2 : by rwa [β mul_assoc],
calc S (n + 1) β€ I * a + I * C * β k in Ico 2 (n + 1), (r * S n)^k :
radius_right_inv_pos_of_radius_pos_aux2 In p i rpos.le apos.le Cpos.le ple
... = I * a + I * C * (((r * S n) ^ 2 - (r * S n) ^ (n + 1)) / (1 - r * S n)) :
by { rw geom_sum_Ico' _ In, exact ne_of_lt (rSn.trans_lt (by norm_num)) }
... β€ I * a + I * C * ((r * S n) ^ 2 / (1/2)) :
begin
apply_rules [add_le_add, le_refl, mul_le_mul_of_nonneg_left, mul_nonneg, norm_nonneg,
Cpos.le],
refine div_le_div (sq_nonneg _) _ (by norm_num) (by linarith),
simp only [sub_le_self_iff],
apply pow_nonneg (mul_nonneg rpos.le Snonneg),
end
... = I * a + 2 * I * C * (r * S n) ^ 2 : by ring
... β€ I * a + 2 * I * C * (r * ((I + 1) * a)) ^ 2 :
by apply_rules [add_le_add, le_refl, mul_le_mul_of_nonneg_left, mul_nonneg, norm_nonneg,
Cpos.le, zero_le_two, pow_le_pow_of_le_left, rpos.le]
... = (I + 2 * I * C * r^2 * (I + 1) ^ 2 * a) * a : by ring
... β€ (I + 1) * a :
by apply_rules [mul_le_mul_of_nonneg_right, apos.le, add_le_add, le_refl] } },
-- conclude that all coefficients satisfy `aβΏ Qβ β€ (I + 1) a`.
let a' : nnreal := β¨a, apos.leβ©,
suffices H : (a' : ennreal) β€ (p.right_inv i).radius,
by { apply lt_of_lt_of_le _ H, exact_mod_cast apos },
apply le_radius_of_bound _ ((I + 1) * a) (Ξ» n, _),
by_cases hn : n = 0,
{ have : β₯p.right_inv i nβ₯ = β₯p.right_inv i 0β₯, by congr; try { rw hn },
simp only [this, norm_zero, zero_mul, right_inv_coeff_zero],
apply_rules [mul_nonneg, add_nonneg, norm_nonneg, zero_le_one, apos.le] },
{ have one_le_n : 1 β€ n := bot_lt_iff_ne_bot.2 hn,
calc β₯p.right_inv i nβ₯ * βa' ^ n = a ^ n * β₯p.right_inv i nβ₯ : mul_comm _ _
... β€ β k in Ico 1 (n + 1), a ^ k * β₯p.right_inv i kβ₯ :
begin
have : β k β Ico 1 (n + 1), 0 β€ a ^ k * β₯p.right_inv i kβ₯ :=
Ξ» k hk, mul_nonneg (pow_nonneg apos.le _) (norm_nonneg _),
exact single_le_sum this (by simp [one_le_n]),
end
... β€ (I + 1) * a : IRec (n + 1) (by dec_trivial) }
end
end formal_multilinear_series
|
1fc2667a93ae4080683d7a953b9677cce3dd4986 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/assert_tac2.lean | 9ca6c3257eea35bc5610874564d3f11a01339139 | [
"Apache-2.0"
] | permissive | soonhokong/lean | cb8aa01055ffe2af0fb99a16b4cda8463b882cd1 | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | refs/heads/master | 1,611,187,284,081 | 1,450,766,737,000 | 1,476,122,547,000 | 11,513,992 | 2 | 0 | null | 1,401,763,102,000 | 1,374,182,235,000 | C++ | UTF-8 | Lean | false | false | 1,307 | lean | import data.nat
open nat eq.ops algebra
theorem lcm_dvd {m n k : nat} (H1 : m β£ k) (H2 : (n β£ k)) : (lcm m n β£ k) :=
match eq_zero_or_pos k with
| @or.inl _ _ kzero :=
begin
rewrite kzero,
apply dvd_zero
end
| @or.inr _ _ kpos :=
obtain (p : nat) (km : k = m * p), from exists_eq_mul_right_of_dvd H1,
obtain (q : nat) (kn : k = n * q), from exists_eq_mul_right_of_dvd H2,
begin
have mpos : m > 0, from pos_of_dvd_of_pos H1 kpos,
have npos : n > 0, from pos_of_dvd_of_pos H2 kpos,
have gcd_pos : gcd m n > 0, from gcd_pos_of_pos_left n mpos,
have ppos : p > 0,
begin
apply pos_of_mul_pos_left,
apply (eq.rec_on km),
exact kpos
end,
have qpos : q > 0, from pos_of_mul_pos_left (kn βΈ kpos),
have H3 : p * q * (m * n * gcd p q) = p * q * (gcd m n * k),
begin
apply sorry
end,
have H4 : m * n * gcd p q = gcd m n * k, from
!eq_of_mul_eq_mul_left (mul_pos ppos qpos) H3,
have H5 : gcd m n * (lcm m n * gcd p q) = gcd m n * k,
begin
rewrite [-mul.assoc, gcd_mul_lcm],
exact H4
end,
have H6 : lcm m n * gcd p q = k, from
!eq_of_mul_eq_mul_left gcd_pos H5,
exact (dvd.intro H6)
end
end
|
011937e4cf9103b4df106b3fdcd6ac0552e74e70 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/category_theory/limits/shapes/wide_pullbacks_auto.lean | e64a2c411b2ea3c3260fbdf84c07a6b6dbaa6733 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,999 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.category_theory.limits.limits
import Mathlib.category_theory.thin
import Mathlib.PostPort
universes v l u
namespace Mathlib
/-!
# Wide pullbacks
We define the category `wide_pullback_shape`, (resp. `wide_pushout_shape`) which is the category
obtained from a discrete category of type `J` by adjoining a terminal (resp. initial) element.
Limits of this shape are wide pullbacks (pushouts).
The convenience method `wide_cospan` (`wide_span`) constructs a functor from this category, hitting
the given morphisms.
We use `wide_pullback_shape` to define ordinary pullbacks (pushouts) by using `J := walking_pair`,
which allows easy proofs of some related lemmas.
Furthermore, wide pullbacks are used to show the existence of limits in the slice category.
Namely, if `C` has wide pullbacks then `C/B` has limits for any object `B` in `C`.
Typeclasses `has_wide_pullbacks` and `has_finite_wide_pullbacks` assert the existence of wide
pullbacks and finite wide pullbacks.
-/
namespace category_theory.limits
/-- A wide pullback shape for any type `J` can be written simply as `option J`. -/
def wide_pullback_shape (J : Type v) := Option J
/-- A wide pushout shape for any type `J` can be written simply as `option J`. -/
def wide_pushout_shape (J : Type v) := Option J
namespace wide_pullback_shape
/-- The type of arrows for the shape indexing a wide pullback. -/
inductive hom {J : Type v} : wide_pullback_shape J β wide_pullback_shape J β Type v where
| id : (X : wide_pullback_shape J) β hom X X
| term : (j : J) β hom (some j) none
protected instance struct {J : Type v} : category_struct (wide_pullback_shape J) := sorry
protected instance hom.inhabited {J : Type v} : Inhabited (hom none none) :=
{ default := hom.id none }
protected instance subsingleton_hom {J : Type v} (j : wide_pullback_shape J)
(j' : wide_pullback_shape J) : subsingleton (j βΆ j') :=
sorry
protected instance category {J : Type v} : small_category (wide_pullback_shape J) := thin_category
@[simp] theorem hom_id {J : Type v} (X : wide_pullback_shape J) : hom.id X = π := rfl
/--
Construct a functor out of the wide pullback shape given a J-indexed collection of arrows to a
fixed object.
-/
@[simp] theorem wide_cospan_map {J : Type v} {C : Type u} [category C] (B : C) (objs : J β C)
(arrows : (j : J) β objs j βΆ B) (X : wide_pullback_shape J) (Y : wide_pullback_shape J)
(f : X βΆ Y) :
functor.map (wide_cospan B objs arrows) f =
hom.cases_on f
(fun (f_1 : wide_pullback_shape J) (H_1 : X = f_1) =>
Eq._oldrec
(fun (H_2 : Y = X) =>
Eq._oldrec
(fun (f : X βΆ X) (H_3 : f == hom.id X) =>
Eq._oldrec π (wide_cospan._proof_1 X f H_3))
(wide_cospan._proof_2 X Y H_2) f)
H_1)
(fun (j : J) (H_1 : X = some j) =>
Eq._oldrec
(fun (f : some j βΆ Y) (H_2 : Y = none) =>
Eq._oldrec
(fun (f : some j βΆ none) (H_3 : f == hom.term j) =>
Eq._oldrec (arrows j) (wide_cospan._proof_3 j f H_3))
(wide_cospan._proof_4 Y H_2) f)
(wide_cospan._proof_5 X j H_1) f)
(wide_cospan._proof_6 X) (wide_cospan._proof_7 Y) (wide_cospan._proof_8 X Y f) :=
Eq.refl (functor.map (wide_cospan B objs arrows) f)
/-- Every diagram is naturally isomorphic (actually, equal) to a `wide_cospan` -/
def diagram_iso_wide_cospan {J : Type v} {C : Type u} [category C] (F : wide_pullback_shape J β₯€ C) :
F β
wide_cospan (functor.obj F none) (fun (j : J) => functor.obj F (some j))
fun (j : J) => functor.map F (hom.term j) :=
nat_iso.of_components (fun (j : wide_pullback_shape J) => eq_to_iso sorry) sorry
end wide_pullback_shape
namespace wide_pushout_shape
/-- The type of arrows for the shape indexing a wide psuhout. -/
inductive hom {J : Type v} : wide_pushout_shape J β wide_pushout_shape J β Type v where
| id : (X : wide_pushout_shape J) β hom X X
| init : (j : J) β hom none (some j)
protected instance struct {J : Type v} : category_struct (wide_pushout_shape J) := sorry
protected instance hom.inhabited {J : Type v} : Inhabited (hom none none) :=
{ default := hom.id none }
protected instance subsingleton_hom {J : Type v} (j : wide_pushout_shape J)
(j' : wide_pushout_shape J) : subsingleton (j βΆ j') :=
sorry
protected instance category {J : Type v} : small_category (wide_pushout_shape J) := thin_category
@[simp] theorem hom_id {J : Type v} (X : wide_pushout_shape J) : hom.id X = π := rfl
/--
Construct a functor out of the wide pushout shape given a J-indexed collection of arrows from a
fixed object.
-/
@[simp] theorem wide_span_map {J : Type v} {C : Type u} [category C] (B : C) (objs : J β C)
(arrows : (j : J) β B βΆ objs j) (X : wide_pushout_shape J) (Y : wide_pushout_shape J)
(f : X βΆ Y) :
functor.map (wide_span B objs arrows) f =
hom.cases_on f
(fun (f_1 : wide_pushout_shape J) (H_1 : X = f_1) =>
Eq._oldrec
(fun (H_2 : Y = X) =>
Eq._oldrec
(fun (f : X βΆ X) (H_3 : f == hom.id X) =>
Eq._oldrec π (wide_span._proof_1 X f H_3))
(wide_span._proof_2 X Y H_2) f)
H_1)
(fun (j : J) (H_1 : X = none) =>
Eq._oldrec
(fun (f : none βΆ Y) (H_2 : Y = some j) =>
Eq._oldrec
(fun (f : none βΆ some j) (H_3 : f == hom.init j) =>
Eq._oldrec (arrows j) (wide_span._proof_3 j f H_3))
(wide_span._proof_4 Y j H_2) f)
(wide_span._proof_5 X H_1) f)
(wide_span._proof_6 X) (wide_span._proof_7 Y) (wide_span._proof_8 X Y f) :=
Eq.refl (functor.map (wide_span B objs arrows) f)
/-- Every diagram is naturally isomorphic (actually, equal) to a `wide_span` -/
def diagram_iso_wide_span {J : Type v} {C : Type u} [category C] (F : wide_pushout_shape J β₯€ C) :
F β
wide_span (functor.obj F none) (fun (j : J) => functor.obj F (some j))
fun (j : J) => functor.map F (hom.init j) :=
nat_iso.of_components (fun (j : wide_pushout_shape J) => eq_to_iso sorry) sorry
end wide_pushout_shape
/-- `has_wide_pullbacks` represents a choice of wide pullback for every collection of morphisms -/
def has_wide_pullbacks (C : Type u) [category C] :=
β (J : Type v), has_limits_of_shape (wide_pullback_shape J) C
/-- `has_wide_pushouts` represents a choice of wide pushout for every collection of morphisms -/
def has_wide_pushouts (C : Type u) [category C] :=
β (J : Type v), has_colimits_of_shape (wide_pushout_shape J) C
end Mathlib |
4460033b20965805092532025f0b5b6928177dd6 | 63abd62053d479eae5abf4951554e1064a4c45b4 | /src/analysis/convex/basic.lean | 9a99772b0b0d4af0908d6728f5398611c21156c4 | [
"Apache-2.0"
] | permissive | Lix0120/mathlib | 0020745240315ed0e517cbf32e738d8f9811dd80 | e14c37827456fc6707f31b4d1d16f1f3a3205e91 | refs/heads/master | 1,673,102,855,024 | 1,604,151,044,000 | 1,604,151,044,000 | 308,930,245 | 0 | 0 | Apache-2.0 | 1,604,164,710,000 | 1,604,163,547,000 | null | UTF-8 | Lean | false | false | 58,022 | lean | /-
Copyright (c) 2019 Alexander Bentkamp. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Alexander Bentkamp, Yury Kudriashov
-/
import data.set.intervals.ord_connected
import data.set.intervals.image_preimage
import data.complex.module
import linear_algebra.affine_space.affine_map
import algebra.module.ordered
/-!
# Convex sets and functions on real vector spaces
In a real vector space, we define the following objects and properties.
* `segment x y` is the closed segment joining `x` and `y`.
* A set `s` is `convex` if for any two points `x y β s` it includes `segment x y`;
* A function `f : E β Ξ²` is `convex_on` a set `s` if `s` is itself a convex set, and for any two
points `x y β s` the segment joining `(x, f x)` to `(y, f y)` is (non-strictly) above the graph
of `f`; equivalently, `convex_on f s` means that the epigraph
`{p : E Γ Ξ² | p.1 β s β§ f p.1 β€ p.2}` is a convex set;
* Center mass of a finite set of points with prescribed weights.
* Convex hull of a set `s` is the minimal convex set that includes `s`.
* Standard simplex `std_simplex ΞΉ [fintype ΞΉ]` is the intersection of the positive quadrant with
the hyperplane `s.sum = 1` in the space `ΞΉ β β`.
We also provide various equivalent versions of the definitions above, prove that some specific sets
are convex, and prove Jensen's inequality.
Note: To define convexity for functions `f : E β Ξ²`, we need `Ξ²` to be an ordered vector space,
defined using the instance `ordered_semimodule β Ξ²`.
## Notations
We use the following local notations:
* `I = Icc (0:β) 1`;
* `[x, y] = segment x y`.
They are defined using `local notation`, so they are not available outside of this file.
-/
universes u' u v v' w x
variables {E : Type u} {F : Type v} {ΞΉ : Type w} {ΞΉ' : Type x} {Ξ± : Type v'}
[add_comm_group E] [vector_space β E] [add_comm_group F] [vector_space β F]
[linear_ordered_field Ξ±]
{s : set E}
open set linear_map
open_locale classical big_operators
local notation `I` := (Icc 0 1 : set β)
section sets
/-! ### Segment -/
/-- Segments in a vector space -/
def segment (x y : E) : set E :=
{z : E | β (a b : β) (ha : 0 β€ a) (hb : 0 β€ b) (hab : a + b = 1), a β’ x + b β’ y = z}
local notation `[`x `, ` y `]` := segment x y
lemma segment_symm (x y : E) : [x, y] = [y, x] :=
set.ext $ Ξ» z,
β¨Ξ» β¨a, b, ha, hb, hab, Hβ©, β¨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans Hβ©,
Ξ» β¨a, b, ha, hb, hab, Hβ©, β¨b, a, hb, ha, (add_comm _ _).trans hab, (add_comm _ _).trans Hβ©β©
lemma left_mem_segment (x y : E) : x β [x, y] :=
β¨1, 0, zero_le_one, le_refl 0, add_zero 1, by rw [zero_smul, one_smul, add_zero]β©
lemma right_mem_segment (x y : E) : y β [x, y] :=
segment_symm y x βΈ left_mem_segment y x
lemma segment_same (x : E) : [x, x] = {x} :=
set.ext $ Ξ» z, β¨Ξ» β¨a, b, ha, hb, hab, hzβ©,
by simpa only [(add_smul _ _ _).symm, mem_singleton_iff, hab, one_smul, eq_comm] using hz,
Ξ» h, mem_singleton_iff.1 h βΈ left_mem_segment z zβ©
lemma segment_eq_image (x y : E) : segment x y = (Ξ» (ΞΈ : β), (1 - ΞΈ) β’ x + ΞΈ β’ y) '' I :=
set.ext $ Ξ» z,
β¨Ξ» β¨a, b, ha, hb, hab, hzβ©,
β¨b, β¨hb, hab βΈ le_add_of_nonneg_left haβ©, hab βΈ hz βΈ by simp only [add_sub_cancel]β©,
Ξ» β¨ΞΈ, β¨hΞΈβ, hΞΈββ©, hzβ©, β¨1-ΞΈ, ΞΈ, sub_nonneg.2 hΞΈβ, hΞΈβ, sub_add_cancel _ _, hzβ©β©
lemma segment_eq_image' (x y : E) : segment x y = (Ξ» (ΞΈ : β), x + ΞΈ β’ (y - x)) '' I :=
by { convert segment_eq_image x y, ext ΞΈ, simp only [smul_sub, sub_smul, one_smul], abel }
lemma segment_eq_imageβ (x y : E) :
segment x y = (Ξ» p:βΓβ, p.1 β’ x + p.2 β’ y) '' {p | 0 β€ p.1 β§ 0 β€ p.2 β§ p.1 + p.2 = 1} :=
by simp only [segment, image, prod.exists, mem_set_of_eq, exists_prop, and_assoc]
lemma segment_eq_Icc {a b : β} (h : a β€ b) : [a, b] = Icc a b :=
begin
rw [segment_eq_image'],
show (((+) a) β (Ξ» t, t * (b - a))) '' Icc 0 1 = Icc a b,
rw [image_comp, image_mul_right_Icc (@zero_le_one β _) (sub_nonneg.2 h), image_const_add_Icc],
simp
end
lemma segment_eq_Icc' (a b : β) : [a, b] = Icc (min a b) (max a b) :=
by cases le_total a b; [skip, rw segment_symm]; simp [segment_eq_Icc, *]
lemma segment_eq_interval (a b : β) : segment a b = interval a b :=
segment_eq_Icc' _ _
lemma mem_segment_translate (a : E) {x b c} : a + x β [a + b, a + c] β x β [b, c] :=
begin
rw [segment_eq_image', segment_eq_image'],
refine exists_congr (Ξ» ΞΈ, and_congr iff.rfl _),
simp only [add_sub_add_left_eq_sub, add_assoc, add_right_inj]
end
lemma segment_translate_preimage (a b c : E) : (Ξ» x, a + x) β»ΒΉ' [a + b, a + c] = [b, c] :=
set.ext $ Ξ» x, mem_segment_translate a
lemma segment_translate_image (a b c: E) : (Ξ»x, a + x) '' [b, c] = [a + b, a + c] :=
segment_translate_preimage a b c βΈ image_preimage_eq $ add_left_surjective a
/-! ### Convexity of sets -/
/-- Convexity of sets -/
def convex (s : set E) :=
β β¦x y : Eβ¦, x β s β y β s β β β¦a b : ββ¦, 0 β€ a β 0 β€ b β a + b = 1 β
a β’ x + b β’ y β s
lemma convex_iff_forall_pos :
convex s β β β¦x yβ¦, x β s β y β s β β β¦a b : ββ¦, 0 < a β 0 < b β a + b = 1 β a β’ x + b β’ y β s :=
begin
refine β¨Ξ» h x y hx hy a b ha hb hab, h hx hy (le_of_lt ha) (le_of_lt hb) hab, _β©,
intros h x y hx hy a b ha hb hab,
cases eq_or_lt_of_le ha with ha ha,
{ subst a, rw [zero_add] at hab, simp [hab, hy] },
cases eq_or_lt_of_le hb with hb hb,
{ subst b, rw [add_zero] at hab, simp [hab, hx] },
exact h hx hy ha hb hab
end
lemma convex_iff_segment_subset : convex s β β β¦x yβ¦, x β s β y β s β [x, y] β s :=
by simp only [convex, segment_eq_imageβ, subset_def, ball_image_iff, prod.forall,
mem_set_of_eq, and_imp]
lemma convex.segment_subset (h : convex s) {x y:E} (hx : x β s) (hy : y β s) : [x, y] β s :=
convex_iff_segment_subset.1 h hx hy
/-- Alternative definition of set convexity, in terms of pointwise set operations. -/
lemma convex_iff_pointwise_add_subset:
convex s β β β¦a b : ββ¦, 0 β€ a β 0 β€ b β a + b = 1 β a β’ s + b β’ s β s :=
iff.intro
begin
rintros hA a b ha hb hab w β¨au, bv, β¨u, hu, rflβ©, β¨v, hv, rflβ©, rflβ©,
exact hA hu hv ha hb hab
end
(Ξ» h x y hx hy a b ha hb hab,
(h ha hb hab) (set.add_mem_add β¨_, hx, rflβ© β¨_, hy, rflβ©))
/-- Alternative definition of set convexity, using division -/
lemma convex_iff_div:
convex s β β β¦x y : Eβ¦, x β s β y β s β β β¦a b : ββ¦,
0 β€ a β 0 β€ b β 0 < a + b β (a/(a+b)) β’ x + (b/(a+b)) β’ y β s :=
β¨begin
assume h x y hx hy a b ha hb hab,
apply h hx hy,
have ha', from mul_le_mul_of_nonneg_left ha (le_of_lt (inv_pos.2 hab)),
rwa [mul_zero, βdiv_eq_inv_mul] at ha',
have hb', from mul_le_mul_of_nonneg_left hb (le_of_lt (inv_pos.2 hab)),
rwa [mul_zero, βdiv_eq_inv_mul] at hb',
rw [βadd_div],
exact div_self (ne_of_lt hab).symm
end,
begin
assume h x y hx hy a b ha hb hab,
have h', from h hx hy ha hb,
rw [hab, div_one, div_one] at h',
exact h' zero_lt_one
endβ©
/-! ### Examples of convex sets -/
lemma convex_empty : convex (β
: set E) := by finish
lemma convex_singleton (c : E) : convex ({c} : set E) :=
begin
intros x y hx hy a b ha hb hab,
rw [set.eq_of_mem_singleton hx, set.eq_of_mem_singleton hy, βadd_smul, hab, one_smul],
exact mem_singleton c
end
lemma convex_univ : convex (set.univ : set E) := Ξ» _ _ _ _ _ _ _ _ _, trivial
lemma convex.inter {t : set E} (hs: convex s) (ht: convex t) : convex (s β© t) :=
Ξ» x y (hx : x β s β© t) (hy : y β s β© t) a b (ha : 0 β€ a) (hb : 0 β€ b) (hab : a + b = 1),
β¨hs hx.left hy.left ha hb hab, ht hx.right hy.right ha hb habβ©
lemma convex_sInter {S : set (set E)} (h : β s β S, convex s) : convex (ββ S) :=
assume x y hx hy a b ha hb hab s hs,
h s hs (hx s hs) (hy s hs) ha hb hab
lemma convex_Inter {ΞΉ : Sort*} {s: ΞΉ β set E} (h: β i : ΞΉ, convex (s i)) : convex (β i, s i) :=
(sInter_range s) βΈ convex_sInter $ forall_range_iff.2 h
lemma convex.prod {s : set E} {t : set F} (hs : convex s) (ht : convex t) :
convex (s.prod t) :=
begin
intros x y hx hy a b ha hb hab,
apply mem_prod.2,
exact β¨hs (mem_prod.1 hx).1 (mem_prod.1 hy).1 ha hb hab,
ht (mem_prod.1 hx).2 (mem_prod.1 hy).2 ha hb habβ©
end
lemma convex.combo_to_vadd {a b : β} {x y : E} (h : a + b = 1) :
a β’ x + b β’ y = b β’ (y - x) + x :=
eq.symm (calc
b β’ (y - x) + x = b β’ (y - x) + (1 : β) β’ x : by rw [one_smul]
... = b β’ (y - x) + (a + b) β’ x : by rw [h]
... = (b β’ y - b β’ x) + (a β’ x + b β’ x) : by rw [add_smul, smul_sub]
... = a β’ x + b β’ y : by abel )
/--
Applying an affine map to an affine combination of two points yields
an affine combination of the images.
-/
lemma convex.combo_affine_apply {a b : β} {x y : E} {f : E βα΅[β] F} (h : a + b = 1) :
f (a β’ x + b β’ y) = a β’ f x + b β’ f y :=
begin
simp only [convex.combo_to_vadd h, β vsub_eq_sub],
exact f.apply_line_map _ _ _,
end
/-- The preimage of a convex set under an affine map is convex. -/
lemma convex.affine_preimage (f : E βα΅[β] F) {s : set F} (hs : convex s) :
convex (f β»ΒΉ' s) :=
begin
intros x y xs ys a b ha hb hab,
rw [mem_preimage, convex.combo_affine_apply hab],
exact hs xs ys ha hb hab,
end
/-- The image of a convex set under an affine map is convex. -/
lemma convex.affine_image (f : E βα΅[β] F) {s : set E} (hs : convex s) :
convex (f '' s) :=
begin
rintros x y β¨x', β¨hx', hx'fβ©β© β¨y', β¨hy', hy'fβ©β© a b ha hb hab,
refine β¨a β’ x' + b β’ y', β¨hs hx' hy' ha hb hab, _β©β©,
rw [convex.combo_affine_apply hab, hx'f, hy'f]
end
lemma convex.linear_image (hs : convex s) (f : E ββ[β] F) : convex (image f s) :=
hs.affine_image f.to_affine_map
lemma convex.is_linear_image (hs : convex s) {f : E β F} (hf : is_linear_map β f) :
convex (f '' s) :=
hs.linear_image $ hf.mk' f
lemma convex.linear_preimage {s : set F} (hs : convex s) (f : E ββ[β] F) :
convex (preimage f s) :=
hs.affine_preimage f.to_affine_map
lemma convex.is_linear_preimage {s : set F} (hs : convex s) {f : E β F} (hf : is_linear_map β f) :
convex (preimage f s) :=
hs.linear_preimage $ hf.mk' f
lemma convex.neg (hs : convex s) : convex ((Ξ» z, -z) '' s) :=
hs.is_linear_image is_linear_map.is_linear_map_neg
lemma convex.neg_preimage (hs : convex s) : convex ((Ξ» z, -z) β»ΒΉ' s) :=
hs.is_linear_preimage is_linear_map.is_linear_map_neg
lemma convex.smul (c : β) (hs : convex s) : convex (c β’ s) :=
hs.linear_image (linear_map.lsmul _ _ c)
lemma convex.smul_preimage (c : β) (hs : convex s) : convex ((Ξ» z, c β’ z) β»ΒΉ' s) :=
hs.linear_preimage (linear_map.lsmul _ _ c)
lemma convex.add {t : set E} (hs : convex s) (ht : convex t) : convex (s + t) :=
by { rw β add_image_prod, exact (hs.prod ht).is_linear_image is_linear_map.is_linear_map_add }
lemma convex.sub {t : set E} (hs : convex s) (ht : convex t) :
convex ((Ξ»x : E Γ E, x.1 - x.2) '' (s.prod t)) :=
(hs.prod ht).is_linear_image is_linear_map.is_linear_map_sub
lemma convex.translate (hs : convex s) (z : E) : convex ((Ξ»x, z + x) '' s) :=
hs.affine_image $ affine_map.const β E z +α΅₯ affine_map.id β E
/-- The translation of a convex set is also convex -/
lemma convex.translate_preimage_right (hs : convex s) (a : E) : convex ((Ξ» z, a + z) β»ΒΉ' s) :=
hs.affine_preimage $ affine_map.const β E a +α΅₯ affine_map.id β E
/-- The translation of a convex set is also convex -/
lemma convex.translate_preimage_left (hs : convex s) (a : E) : convex ((Ξ» z, z + a) β»ΒΉ' s) :=
by simpa only [add_comm] using hs.translate_preimage_right a
lemma convex.affinity (hs : convex s) (z : E) (c : β) : convex ((Ξ»x, z + c β’ x) '' s) :=
hs.affine_image $ affine_map.const β E z +α΅₯ c β’ affine_map.id β E
lemma real.convex_iff_ord_connected {s : set β} : convex s β ord_connected s :=
begin
simp only [convex_iff_segment_subset, segment_eq_interval, ord_connected_iff_interval_subset],
exact forall_congr (Ξ» x, forall_swap)
end
alias real.convex_iff_ord_connected β convex.ord_connected set.ord_connected.convex
lemma convex_Iio (r : β) : convex (Iio r) := ord_connected_Iio.convex
lemma convex_Ioi (r : β) : convex (Ioi r) := ord_connected_Ioi.convex
lemma convex_Iic (r : β) : convex (Iic r) := ord_connected_Iic.convex
lemma convex_Ici (r : β) : convex (Ici r) := ord_connected_Ici.convex
lemma convex_Ioo (r s : β) : convex (Ioo r s) := ord_connected_Ioo.convex
lemma convex_Ico (r s : β) : convex (Ico r s) := ord_connected_Ico.convex
lemma convex_Ioc (r : β) (s : β) : convex (Ioc r s) := ord_connected_Ioc.convex
lemma convex_Icc (r : β) (s : β) : convex (Icc r s) := ord_connected_Icc.convex
lemma convex_interval (r : β) (s : β) : convex (interval r s) := ord_connected_interval.convex
lemma convex_segment (a b : E) : convex [a, b] :=
begin
have : (Ξ» (t : β), a + t β’ (b - a)) = (Ξ»z : E, a + z) β (Ξ»t:β, t β’ (b - a)) := rfl,
rw [segment_eq_image', this, image_comp],
refine ((convex_Icc _ _).is_linear_image _).translate _,
exact is_linear_map.is_linear_map_smul' _
end
lemma convex_halfspace_lt {f : E β β} (h : is_linear_map β f) (r : β) :
convex {w | f w < r} :=
(convex_Iio r).is_linear_preimage h
lemma convex_halfspace_le {f : E β β} (h : is_linear_map β f) (r : β) :
convex {w | f w β€ r} :=
(convex_Iic r).is_linear_preimage h
lemma convex_halfspace_gt {f : E β β} (h : is_linear_map β f) (r : β) :
convex {w | r < f w} :=
(convex_Ioi r).is_linear_preimage h
lemma convex_halfspace_ge {f : E β β} (h : is_linear_map β f) (r : β) :
convex {w | r β€ f w} :=
(convex_Ici r).is_linear_preimage h
lemma convex_hyperplane {f : E β β} (h : is_linear_map β f) (r : β) :
convex {w | f w = r} :=
begin
show convex (f β»ΒΉ' {p | p = r}),
rw set_of_eq_eq_singleton,
exact (convex_singleton r).is_linear_preimage h
end
lemma convex_halfspace_re_lt (r : β) : convex {c : β | c.re < r} :=
convex_halfspace_lt (is_linear_map.mk complex.add_re complex.smul_re) _
lemma convex_halfspace_re_le (r : β) : convex {c : β | c.re β€ r} :=
convex_halfspace_le (is_linear_map.mk complex.add_re complex.smul_re) _
lemma convex_halfspace_re_gt (r : β) : convex {c : β | r < c.re } :=
convex_halfspace_gt (is_linear_map.mk complex.add_re complex.smul_re) _
lemma convex_halfspace_re_lge (r : β) : convex {c : β | r β€ c.re} :=
convex_halfspace_ge (is_linear_map.mk complex.add_re complex.smul_re) _
lemma convex_halfspace_im_lt (r : β) : convex {c : β | c.im < r} :=
convex_halfspace_lt (is_linear_map.mk complex.add_im complex.smul_im) _
lemma convex_halfspace_im_le (r : β) : convex {c : β | c.im β€ r} :=
convex_halfspace_le (is_linear_map.mk complex.add_im complex.smul_im) _
lemma convex_halfspace_im_gt (r : β) : convex {c : β | r < c.im } :=
convex_halfspace_gt (is_linear_map.mk complex.add_im complex.smul_im) _
lemma convex_halfspace_im_lge (r : β) : convex {c : β | r β€ c.im} :=
convex_halfspace_ge (is_linear_map.mk complex.add_im complex.smul_im) _
/- Convex combinations in intervals -/
lemma convex.combo_self (a : Ξ±) {x y : Ξ±} (h : x + y = 1) : a = x * a + y * a :=
calc
a = 1 * a : by rw [one_mul]
... = (x + y) * a : by rw [h]
... = x * a + y * a : by rw [add_mul]
/--
If x is in an Ioo, it can be expressed as a convex combination of the endpoints.
-/
lemma convex.mem_Ioo {a b x : Ξ±} (h : a < b) :
x β Ioo a b β β (x_a x_b : Ξ±), 0 < x_a β§ 0 < x_b β§ x_a + x_b = 1 β§ x_a * a + x_b * b = x :=
begin
split,
{ rintros β¨h_ax, h_bxβ©,
by_cases hab : Β¬a < b,
{ exfalso; exact hab h },
{ refine β¨(b-x) / (b-a), (x-a) / (b-a), _β©,
refine β¨div_pos (by linarith) (by linarith), div_pos (by linarith) (by linarith),_,_β©;
{ field_simp [show b - a β 0, by linarith], ring } } },
{ rw [mem_Ioo],
rintros β¨xa, xb, β¨hxa, hxb, hxaxb, hββ©β©,
rw [βhβ],
exact β¨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]β© }
end
/-- If x is in an Ioc, it can be expressed as a convex combination of the endpoints. -/
lemma convex.mem_Ioc {a b x : Ξ±} (h : a < b) :
x β Ioc a b β β (x_a x_b : Ξ±), 0 β€ x_a β§ 0 < x_b β§ x_a + x_b = 1 β§ x_a * a + x_b * b = x :=
begin
split,
{ rintros β¨h_ax, h_bxβ©,
by_cases h_x : x = b,
{ exact β¨0, 1, by linarith, by linarith, by ring, by {rw [h_x], ring}β© },
{ rcases (convex.mem_Ioo h).mp β¨h_ax, lt_of_le_of_ne h_bx h_xβ© with β¨x_a, x_b, Ioo_caseβ©,
exact β¨x_a, x_b, by linarith, Ioo_case.2β© } },
{ rw [mem_Ioc],
rintros β¨xa, xb, β¨hxa, hxb, hxaxb, hββ©β©,
rw [βhβ],
exact β¨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]β© }
end
/-- If x is in an Ico, it can be expressed as a convex combination of the endpoints. -/
lemma convex.mem_Ico {a b x : Ξ±} (h : a < b) :
x β Ico a b β β (x_a x_b : Ξ±), 0 < x_a β§ 0 β€ x_b β§ x_a + x_b = 1 β§ x_a * a + x_b * b = x :=
begin
split,
{ rintros β¨h_ax, h_bxβ©,
by_cases h_x : x = a,
{ exact β¨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}β© },
{ rcases (convex.mem_Ioo h).mp β¨lt_of_le_of_ne h_ax (ne.symm h_x), h_bxβ©
with β¨x_a, x_b, Ioo_caseβ©,
exact β¨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2β© } },
{ rw [mem_Ico],
rintros β¨xa, xb, β¨hxa, hxb, hxaxb, hββ©β©,
rw [βhβ],
exact β¨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]β© }
end
/-- If x is in an Icc, it can be expressed as a convex combination of the endpoints. -/
lemma convex.mem_Icc {a b x : Ξ±} (h : a β€ b):
x β Icc a b β β (x_a x_b : Ξ±), 0 β€ x_a β§ 0 β€ x_b β§ x_a + x_b = 1 β§ x_a * a + x_b * b = x :=
begin
split,
{ intro x_in_I,
rw [Icc, mem_set_of_eq] at x_in_I,
rcases x_in_I with β¨h_ax, h_bxβ©,
by_cases hab' : a = b,
{ exact β¨0, 1, le_refl 0, by linarith, by ring, by linarithβ© },
change a β b at hab',
replace h : a < b, exact lt_of_le_of_ne h hab',
by_cases h_x : x = a,
{ exact β¨1, 0, by linarith, by linarith, by ring, by {rw [h_x], ring}β© },
{ rcases (convex.mem_Ioc h).mp β¨lt_of_le_of_ne h_ax (ne.symm h_x), h_bxβ©
with β¨x_a, x_b, Ioo_caseβ©,
exact β¨x_a, x_b, Ioo_case.1, by linarith, (Ioo_case.2).2β© } },
{ rw [mem_Icc],
rintros β¨xa, xb, β¨hxa, hxb, hxaxb, hββ©β©,
rw [βhβ],
exact β¨by nlinarith [convex.combo_self a hxaxb], by nlinarith [convex.combo_self b hxaxb]β© }
end
section submodule
open submodule
lemma submodule.convex (K : submodule β E) : convex (βK : set E) :=
by { repeat {intro}, refine add_mem _ (smul_mem _ _ _) (smul_mem _ _ _); assumption }
lemma subspace.convex (K : subspace β E) : convex (βK : set E) := K.convex
end submodule
end sets
section functions
variables {Ξ² : Type*} [ordered_add_comm_monoid Ξ²] [semimodule β Ξ²]
local notation `[`x `, ` y `]` := segment x y
/-! ### Convex functions -/
/-- Convexity of functions -/
def convex_on (s : set E) (f : E β Ξ²) : Prop :=
convex s β§
β β¦x y : Eβ¦, x β s β y β s β β β¦a b : ββ¦, 0 β€ a β 0 β€ b β a + b = 1 β
f (a β’ x + b β’ y) β€ a β’ f x + b β’ f y
/-- Concavity of functions -/
def concave_on (s : set E) (f : E β Ξ²) : Prop :=
convex s β§
β β¦x y : Eβ¦, x β s β y β s β β β¦a b : ββ¦, 0 β€ a β 0 β€ b β a + b = 1 β
a β’ f x + b β’ f y β€ f (a β’ x + b β’ y)
/-- A function f is concave iff -f is convex -/
@[simp] lemma neg_convex_on_iff {Ξ³ : Type*} [ordered_add_comm_group Ξ³] [semimodule β Ξ³]
(s : set E) (f : E β Ξ³) : convex_on s (-f) β concave_on s f :=
begin
split,
{ rintros β¨hconv, hβ©,
refine β¨hconv, _β©,
intros x y xs ys a b ha hb hab,
specialize h xs ys ha hb hab,
simp [neg_apply, neg_le, add_comm] at h,
exact h },
{ rintros β¨hconv, hβ©,
refine β¨hconv, _β©,
intros x y xs ys a b ha hb hab,
specialize h xs ys ha hb hab,
simp [neg_apply, neg_le, add_comm, h] }
end
/-- A function f is concave iff -f is convex -/
@[simp] lemma neg_concave_on_iff {Ξ³ : Type*} [ordered_add_comm_group Ξ³] [semimodule β Ξ³]
(s : set E) (f : E β Ξ³) : concave_on s (-f) β convex_on s f:=
by rw [β neg_convex_on_iff s (-f), neg_neg f]
lemma convex_on_id {s : set β} (hs : convex s) : convex_on s id := β¨hs, by { intros, refl }β©
lemma concave_on_id {s : set β} (hs : convex s) : concave_on s id := β¨hs, by { intros, refl }β©
lemma convex_on_const (c : Ξ²) (hs : convex s) : convex_on s (Ξ» x:E, c) :=
β¨hs, by { intros, simp only [β add_smul, *, one_smul] }β©
lemma concave_on_const (c : Ξ²) (hs : convex s) : concave_on s (Ξ» x:E, c) :=
@convex_on_const _ _ _ _ (order_dual Ξ²) _ _ c hs
variables {t : set E}
lemma convex_on_iff_div {f : E β Ξ²} :
convex_on s f β convex s β§ β β¦x y : Eβ¦, x β s β y β s β β β¦a b : ββ¦, 0 β€ a β 0 β€ b β 0 < a + b β
f ((a/(a+b)) β’ x + (b/(a+b)) β’ y) β€ (a/(a+b)) β’ f x + (b/(a+b)) β’ f y :=
and_congr iff.rfl
β¨begin
intros h x y hx hy a b ha hb hab,
apply h hx hy (div_nonneg ha $ le_of_lt hab) (div_nonneg hb $ le_of_lt hab),
rw [βadd_div],
exact div_self (ne_of_gt hab)
end,
begin
intros h x y hx hy a b ha hb hab,
simpa [hab, zero_lt_one] using h hx hy ha hb,
endβ©
lemma concave_on_iff_div {f : E β Ξ²} :
concave_on s f β convex s β§ β β¦x y : Eβ¦, x β s β y β s β β β¦a b : ββ¦, 0 β€ a β 0 β€ b β 0 < a + b β
(a/(a+b)) β’ f x + (b/(a+b)) β’ f y β€ f ((a/(a+b)) β’ x + (b/(a+b)) β’ y) :=
@convex_on_iff_div _ _ _ _ (order_dual Ξ²) _ _ _
/-- For a function on a convex set in a linear ordered space, in order to prove that it is convex
it suffices to verify the inequality `f (a β’ x + b β’ y) β€ a β’ f x + b β’ f y` only for `x < y`
and positive `a`, `b`. The main use case is `E = β` however one can apply it, e.g., to `β^n` with
lexicographic order. -/
lemma linear_order.convex_on_of_lt {f : E β Ξ²} [linear_order E] (hs : convex s)
(hf : β β¦x y : Eβ¦, x β s β y β s β x < y β β β¦a b : ββ¦, 0 < a β 0 < b β a + b = 1 β
f (a β’ x + b β’ y) β€ a β’ f x + b β’ f y) : convex_on s f :=
begin
use hs,
intros x y hx hy a b ha hb hab,
wlog hxy : x<=y using [x y a b, y x b a],
{ exact le_total _ _ },
{ cases eq_or_lt_of_le hxy with hxy hxy,
by { subst y, rw [β add_smul, β add_smul, hab, one_smul, one_smul] },
cases eq_or_lt_of_le ha with ha ha,
by { subst a, rw [zero_add] at hab, subst b, simp },
cases eq_or_lt_of_le hb with hb hb,
by { subst b, rw [add_zero] at hab, subst a, simp },
exact hf hx hy hxy ha hb hab }
end
/-- For a function on a convex set in a linear ordered space, in order to prove that it is concave
it suffices to verify the inequality `a β’ f x + b β’ f y β€ f (a β’ x + b β’ y)` only for `x < y`
and positive `a`, `b`. The main use case is `E = β` however one can apply it, e.g., to `β^n` with
lexicographic order. -/
lemma linear_order.concave_on_of_lt {f : E β Ξ²} [linear_order E] (hs : convex s)
(hf : β β¦x y : Eβ¦, x β s β y β s β x < y β β β¦a b : ββ¦, 0 < a β 0 < b β a + b = 1 β
a β’ f x + b β’ f y β€ f (a β’ x + b β’ y)) : concave_on s f :=
@linear_order.convex_on_of_lt _ _ _ _ (order_dual Ξ²) _ _ f _ hs hf
/-- For a function `f` defined on a convex subset `D` of `β`, if for any three points `x<y<z`
the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope
of the secant line of `f` on `[x, z]`, then `f` is convex on `D`. This way of proving convexity
of a function is used in the proof of convexity of a function with a monotone derivative. -/
lemma convex_on_real_of_slope_mono_adjacent {s : set β} (hs : convex s) {f : β β β}
(hf : β {x y z : β}, x β s β z β s β x < y β y < z β
(f y - f x) / (y - x) β€ (f z - f y) / (z - y)) :
convex_on s f :=
linear_order.convex_on_of_lt hs
begin
assume x z hx hz hxz a b ha hb hab,
let y := a * x + b * z,
have hxy : x < y,
{ rw [β one_mul x, β hab, add_mul],
exact add_lt_add_left ((mul_lt_mul_left hb).2 hxz) _ },
have hyz : y < z,
{ rw [β one_mul z, β hab, add_mul],
exact add_lt_add_right ((mul_lt_mul_left ha).2 hxz) _ },
have : (f y - f x) * (z - y) β€ (f z - f y) * (y - x),
from (div_le_div_iff (sub_pos.2 hxy) (sub_pos.2 hyz)).1 (hf hx hz hxy hyz),
have A : z - y + (y - x) = z - x, by abel,
have B : 0 < z - x, from sub_pos.2 (lt_trans hxy hyz),
rw [sub_mul, sub_mul, sub_le_iff_le_add', β add_sub_assoc, le_sub_iff_add_le, β mul_add, A,
β le_div_iff B, add_div, mul_div_assoc, mul_div_assoc,
mul_comm (f x), mul_comm (f z)] at this,
rw [eq_comm, β sub_eq_iff_eq_add] at hab; subst a,
convert this; symmetry; simp only [div_eq_iff (ne_of_gt B), y]; ring
end
/-- For a function `f` defined on a subset `D` of `β`, if `f` is convex on `D`, then for any three
points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope
of the secant line of `f` on `[x, z]`. -/
lemma convex_on.slope_mono_adjacent {s : set β} {f : β β β} (hf : convex_on s f)
{x y z : β} (hx : x β s) (hz : z β s) (hxy : x < y) (hyz : y < z) :
(f y - f x) / (y - x) β€ (f z - f y) / (z - y) :=
begin
have hβ : 0 < y - x := by linarith,
have hβ : 0 < z - y := by linarith,
have hβ : 0 < z - x := by linarith,
suffices : f y / (y - x) + f y / (z - y) β€ f x / (y - x) + f z / (z - y),
by { ring at this β’, linarith },
set a := (z - y) / (z - x),
set b := (y - x) / (z - x),
have heqz : a β’ x + b β’ z = y, by { field_simp, rw div_eq_iff; [ring, linarith], },
have key, from
hf.2 hx hz
(show 0 β€ a, by apply div_nonneg; linarith)
(show 0 β€ b, by apply div_nonneg; linarith)
(show a + b = 1, by { field_simp, rw div_eq_iff; [ring, linarith], }),
rw heqz at key,
replace key := mul_le_mul_of_nonneg_left key (le_of_lt hβ),
field_simp [ne_of_gt hβ, ne_of_gt hβ, ne_of_gt hβ, mul_comm (z - x) _] at key β’,
rw div_le_div_right,
{ linarith, },
{ nlinarith, },
end
/-- For a function `f` defined on a convex subset `D` of `β`, `f` is convex on `D` iff for any three
points `x<y<z` the slope of the secant line of `f` on `[x, y]` is less than or equal to the slope
of the secant line of `f` on `[x, z]`. -/
lemma convex_on_real_iff_slope_mono_adjacent {s : set β} (hs : convex s) {f : β β β} :
convex_on s f β
(β {x y z : β}, x β s β z β s β x < y β y < z β
(f y - f x) / (y - x) β€ (f z - f y) / (z - y)) :=
β¨convex_on.slope_mono_adjacent, convex_on_real_of_slope_mono_adjacent hsβ©
/-- For a function `f` defined on a convex subset `D` of `β`, if for any three points `x<y<z`
the slope of the secant line of `f` on `[x, y]` is greater than or equal to the slope
of the secant line of `f` on `[x, z]`, then `f` is concave on `D`. -/
lemma concave_on_real_of_slope_mono_adjacent {s : set β} (hs : convex s) {f : β β β}
(hf : β {x y z : β}, x β s β z β s β x < y β y < z β
(f z - f y) / (z - y) β€ (f y - f x) / (y - x)) : concave_on s f :=
begin
rw [βneg_convex_on_iff],
apply convex_on_real_of_slope_mono_adjacent hs,
intros x y z xs zs xy yz,
rw [βneg_le_neg_iff, βneg_div, βneg_div, neg_sub, neg_sub],
simp only [hf xs zs xy yz, neg_sub_neg, pi.neg_apply],
end
/-- For a function `f` defined on a subset `D` of `β`, if `f` is concave on `D`, then for any three
points `x<y<z`, the slope of the secant line of `f` on `[x, y]` is greater than or equal to the
slope of the secant line of `f` on `[x, z]`. -/
lemma concave_on.slope_mono_adjacent {s : set β} {f : β β β} (hf : concave_on s f)
{x y z : β} (hx : x β s) (hz : z β s) (hxy : x < y) (hyz : y < z) :
(f z - f y) / (z - y) β€ (f y - f x) / (y - x) :=
begin
rw [βneg_le_neg_iff, βneg_div, βneg_div, neg_sub, neg_sub],
rw [βneg_sub_neg (f y), βneg_sub_neg (f z)],
simp_rw [βpi.neg_apply],
rw [βneg_convex_on_iff] at hf,
apply convex_on.slope_mono_adjacent hf; assumption,
end
/-- For a function `f` defined on a convex subset `D` of `β`, `f` is concave on `D` iff for any
three points `x<y<z` the slope of the secant line of `f` on `[x, y]` is greater than or equal to
the slope of the secant line of `f` on `[x, z]`. -/
lemma concave_on_real_iff_slope_mono_adjacent {s : set β} (hs : convex s) {f : β β β} :
concave_on s f β
(β {x y z : β}, x β s β z β s β x < y β y < z β
(f z - f y) / (z - y) β€ (f y - f x) / (y - x)) :=
β¨concave_on.slope_mono_adjacent, concave_on_real_of_slope_mono_adjacent hsβ©
lemma convex_on.subset {f : E β Ξ²} (h_convex_on : convex_on t f)
(h_subset : s β t) (h_convex : convex s) : convex_on s f :=
begin
apply and.intro h_convex,
intros x y hx hy,
exact h_convex_on.2 (h_subset hx) (h_subset hy),
end
lemma concave_on.subset {f : E β Ξ²}
(h_concave_on : concave_on t f) (h_subset : s β t) (h_convex : convex s) : concave_on s f :=
@convex_on.subset _ _ _ _ (order_dual Ξ²) _ _ t f h_concave_on h_subset h_convex
lemma convex_on.add {f g : E β Ξ²} (hf : convex_on s f) (hg : convex_on s g) :
convex_on s (Ξ»x, f x + g x) :=
begin
apply and.intro hf.1,
intros x y hx hy a b ha hb hab,
calc
f (a β’ x + b β’ y) + g (a β’ x + b β’ y) β€ (a β’ f x + b β’ f y) + (a β’ g x + b β’ g y)
: add_le_add (hf.2 hx hy ha hb hab) (hg.2 hx hy ha hb hab)
... = a β’ f x + a β’ g x + b β’ f y + b β’ g y : by abel
... = a β’ (f x + g x) + b β’ (f y + g y) : by simp [smul_add, add_assoc]
end
lemma concave_on.add {f g : E β Ξ²} (hf : concave_on s f) (hg : concave_on s g) :
concave_on s (Ξ»x, f x + g x) :=
@convex_on.add _ _ _ _ (order_dual Ξ²) _ _ f g hf hg
lemma convex_on.smul [ordered_semimodule β Ξ²] {f : E β Ξ²} {c : β} (hc : 0 β€ c)
(hf : convex_on s f) : convex_on s (Ξ»x, c β’ f x) :=
begin
apply and.intro hf.1,
intros x y hx hy a b ha hb hab,
calc
c β’ f (a β’ x + b β’ y) β€ c β’ (a β’ f x + b β’ f y)
: smul_le_smul_of_nonneg (hf.2 hx hy ha hb hab) hc
... = a β’ (c β’ f x) + b β’ (c β’ f y) : by simp only [smul_add, smul_comm]
end
lemma concave_on.smul [ordered_semimodule β Ξ²] {f : E β Ξ²} {c : β} (hc : 0 β€ c)
(hf : concave_on s f) : concave_on s (Ξ»x, c β’ f x) :=
@convex_on.smul _ _ _ _ (order_dual Ξ²) _ _ _ f c hc hf
/-- A convex function on a segment is upper-bounded by the max of its endpoints. -/
lemma convex_on.le_on_segment' {Ξ³ : Type*}
[linear_ordered_add_comm_group Ξ³] [semimodule β Ξ³] [ordered_semimodule β Ξ³]
{f : E β Ξ³} {x y : E} {a b : β}
(hf : convex_on s f) (hx : x β s) (hy : y β s) (ha : 0 β€ a) (hb : 0 β€ b) (hab : a + b = 1) :
f (a β’ x + b β’ y) β€ max (f x) (f y) :=
calc
f (a β’ x + b β’ y) β€ a β’ f x + b β’ f y : hf.2 hx hy ha hb hab
... β€ a β’ max (f x) (f y) + b β’ max (f x) (f y) :
add_le_add (smul_le_smul_of_nonneg (le_max_left _ _) ha) (smul_le_smul_of_nonneg (le_max_right _ _) hb)
... β€ max (f x) (f y) : by rw [βadd_smul, hab, one_smul]
/-- A concave function on a segment is lower-bounded by the min of its endpoints. -/
lemma concave_on.le_on_segment' {Ξ³ : Type*}
[linear_ordered_add_comm_group Ξ³] [semimodule β Ξ³] [ordered_semimodule β Ξ³]
{f : E β Ξ³} {x y : E} {a b : β}
(hf : concave_on s f) (hx : x β s) (hy : y β s) (ha : 0 β€ a) (hb : 0 β€ b) (hab : a + b = 1) :
min (f x) (f y) β€ f (a β’ x + b β’ y) :=
@convex_on.le_on_segment' _ _ _ _ (order_dual Ξ³) _ _ _ f x y a b hf hx hy ha hb hab
/-- A convex function on a segment is upper-bounded by the max of its endpoints. -/
lemma convex_on.le_on_segment {Ξ³ : Type*}
[linear_ordered_add_comm_group Ξ³] [semimodule β Ξ³] [ordered_semimodule β Ξ³]
{f : E β Ξ³} (hf : convex_on s f) {x y z : E}
(hx : x β s) (hy : y β s) (hz : z β [x, y]) :
f z β€ max (f x) (f y) :=
let β¨a, b, ha, hb, hab, hzβ© := hz in hz βΈ hf.le_on_segment' hx hy ha hb hab
/-- A concave function on a segment is lower-bounded by the min of its endpoints. -/
lemma concave_on.le_on_segment {Ξ³ : Type*}
[linear_ordered_add_comm_group Ξ³] [semimodule β Ξ³] [ordered_semimodule β Ξ³]
{f : E β Ξ³} (hf : concave_on s f) {x y z : E}
(hx : x β s) (hy : y β s) (hz : z β [x, y]) :
min (f x) (f y) β€ f z :=
@convex_on.le_on_segment _ _ _ _ (order_dual Ξ³) _ _ _ f hf x y z hx hy hz
lemma convex_on.convex_le [ordered_semimodule β Ξ²] {f : E β Ξ²} (hf : convex_on s f) (r : Ξ²) :
convex {x β s | f x β€ r} :=
convex_iff_segment_subset.2 $ Ξ» x y hx hy z hz,
begin
refine β¨hf.1.segment_subset hx.1 hy.1 hz,_β©,
rcases hz with β¨za,zb,hza,hzb,hzazb,Hβ©,
rw βH,
calc
f (za β’ x + zb β’ y) β€ za β’ (f x) + zb β’ (f y) : hf.2 hx.1 hy.1 hza hzb hzazb
... β€ za β’ r + zb β’ r
: add_le_add (smul_le_smul_of_nonneg hx.2 hza)
(smul_le_smul_of_nonneg hy.2 hzb)
... β€ r : by simp [βadd_smul, hzazb]
end
lemma concave_on.concave_le [ordered_semimodule β Ξ²] {f : E β Ξ²} (hf : concave_on s f) (r : Ξ²) :
convex {x β s | r β€ f x} :=
@convex_on.convex_le _ _ _ _ (order_dual Ξ²) _ _ _ f hf r
lemma convex_on.convex_lt {Ξ³ : Type*} [ordered_cancel_add_comm_monoid Ξ³]
[semimodule β Ξ³] [ordered_semimodule β Ξ³]
{f : E β Ξ³} (hf : convex_on s f) (r : Ξ³) : convex {x β s | f x < r} :=
begin
intros a b as bs xa xb hxa hxb hxaxb,
refine β¨hf.1 as.1 bs.1 hxa hxb hxaxb,_β©,
dsimp,
by_cases H : xa = 0,
{ have H' : xb = 1 := by rwa [H, zero_add] at hxaxb,
rw [H, H', zero_smul, one_smul, zero_add],
exact bs.2 },
{ calc
f (xa β’ a + xb β’ b) β€ xa β’ (f a) + xb β’ (f b) : hf.2 as.1 bs.1 hxa hxb hxaxb
... < xa β’ r + xb β’ (f b)
: (add_lt_add_iff_right (xb β’ (f b))).mpr
(smul_lt_smul_of_pos as.2
(lt_of_le_of_ne hxa (ne.symm H)))
... β€ xa β’ r + xb β’ r
: (add_le_add_iff_left (xa β’ r)).mpr
(smul_le_smul_of_nonneg (le_of_lt bs.2) hxb)
... = r
: by simp only [βadd_smul, hxaxb, one_smul] }
end
lemma concave_on.convex_lt {Ξ³ : Type*} [ordered_cancel_add_comm_monoid Ξ³]
[semimodule β Ξ³] [ordered_semimodule β Ξ³]
{f : E β Ξ³} (hf : concave_on s f) (r : Ξ³) : convex {x β s | r < f x} :=
@convex_on.convex_lt _ _ _ _ (order_dual Ξ³) _ _ _ f hf r
lemma convex_on.convex_epigraph {Ξ³ : Type*} [ordered_add_comm_group Ξ³]
[semimodule β Ξ³] [ordered_semimodule β Ξ³]
{f : E β Ξ³} (hf : convex_on s f) :
convex {p : E Γ Ξ³ | p.1 β s β§ f p.1 β€ p.2} :=
begin
rintros β¨x, rβ© β¨y, tβ© β¨hx, hrβ© β¨hy, htβ© a b ha hb hab,
refine β¨hf.1 hx hy ha hb hab, _β©,
calc f (a β’ x + b β’ y) β€ a β’ f x + b β’ f y : hf.2 hx hy ha hb hab
... β€ a β’ r + b β’ t : add_le_add (smul_le_smul_of_nonneg hr ha)
(smul_le_smul_of_nonneg ht hb)
end
lemma concave_on.convex_hypograph {Ξ³ : Type*} [ordered_add_comm_group Ξ³]
[semimodule β Ξ³] [ordered_semimodule β Ξ³]
{f : E β Ξ³} (hf : concave_on s f) :
convex {p : E Γ Ξ³ | p.1 β s β§ p.2 β€ f p.1} :=
@convex_on.convex_epigraph _ _ _ _ (order_dual Ξ³) _ _ _ f hf
lemma convex_on_iff_convex_epigraph {Ξ³ : Type*} [ordered_add_comm_group Ξ³]
[semimodule β Ξ³] [ordered_semimodule β Ξ³]
{f : E β Ξ³} :
convex_on s f β convex {p : E Γ Ξ³ | p.1 β s β§ f p.1 β€ p.2} :=
begin
refine β¨convex_on.convex_epigraph, Ξ» h, β¨_, _β©β©,
{ assume x y hx hy a b ha hb hab,
exact (@h (x, f x) (y, f y) β¨hx, le_refl _β© β¨hy, le_refl _β© a b ha hb hab).1 },
{ assume x y hx hy a b ha hb hab,
exact (@h (x, f x) (y, f y) β¨hx, le_refl _β© β¨hy, le_refl _β© a b ha hb hab).2 }
end
lemma concave_on_iff_convex_hypograph {Ξ³ : Type*} [ordered_add_comm_group Ξ³]
[semimodule β Ξ³] [ordered_semimodule β Ξ³]
{f : E β Ξ³} :
concave_on s f β convex {p : E Γ Ξ³ | p.1 β s β§ p.2 β€ f p.1} :=
@convex_on_iff_convex_epigraph _ _ _ _ (order_dual Ξ³) _ _ _ f
/-- If a function is convex on s, it remains convex when precomposed by an affine map -/
lemma convex_on.comp_affine_map {f : F β Ξ²} (g : E βα΅[β] F) {s : set F}
(hf : convex_on s f) : convex_on (g β»ΒΉ' s) (f β g) :=
begin
refine β¨hf.1.affine_preimage _,_β©,
intros x y xs ys a b ha hb hab,
calc
(f β g) (a β’ x + b β’ y) = f (g (a β’ x + b β’ y)) : rfl
... = f (a β’ (g x) + b β’ (g y)) : by rw [convex.combo_affine_apply hab]
... β€ a β’ f (g x) + b β’ f (g y) : hf.2 xs ys ha hb hab
... = a β’ (f β g) x + b β’ (f β g) y : rfl
end
/-- If a function is concave on s, it remains concave when precomposed by an affine map -/
lemma concave_on.comp_affine_map {f : F β Ξ²} (g : E βα΅[β] F) {s : set F}
(hf : concave_on s f) : concave_on (g β»ΒΉ' s) (f β g) :=
@convex_on.comp_affine_map _ _ _ _ _ _ (order_dual Ξ²) _ _ f g s hf
/-- If g is convex on s, so is (g β f) on f β»ΒΉ' s for a linear f. -/
lemma convex_on.comp_linear_map {g : F β Ξ²} {s : set F} (hg : convex_on s g) (f : E ββ[β] F) :
convex_on (f β»ΒΉ' s) (g β f) :=
hg.comp_affine_map f.to_affine_map
/-- If g is concave on s, so is (g β f) on f β»ΒΉ' s for a linear f. -/
lemma concave_on.comp_linear_map {g : F β Ξ²} {s : set F} (hg : concave_on s g) (f : E ββ[β] F) :
concave_on (f β»ΒΉ' s) (g β f) :=
hg.comp_affine_map f.to_affine_map
/-- If a function is convex on s, it remains convex after a translation. -/
lemma convex_on.translate_right {f : E β Ξ²} {s : set E} {a : E} (hf : convex_on s f) :
convex_on ((Ξ» z, a + z) β»ΒΉ' s) (f β (Ξ» z, a + z)) :=
hf.comp_affine_map $ affine_map.const β E a +α΅₯ affine_map.id β E
/-- If a function is concave on s, it remains concave after a translation. -/
lemma concave_on.translate_right {f : E β Ξ²} {s : set E} {a : E} (hf : concave_on s f) :
concave_on ((Ξ» z, a + z) β»ΒΉ' s) (f β (Ξ» z, a + z)) :=
hf.comp_affine_map $ affine_map.const β E a +α΅₯ affine_map.id β E
/-- If a function is convex on s, it remains convex after a translation. -/
lemma convex_on.translate_left {f : E β Ξ²} {s : set E} {a : E} (hf : convex_on s f) :
convex_on ((Ξ» z, a + z) β»ΒΉ' s) (f β (Ξ» z, z + a)) :=
by simpa only [add_comm] using hf.translate_right
/-- If a function is concave on s, it remains concave after a translation. -/
lemma concave_on.translate_left {f : E β Ξ²} {s : set E} {a : E} (hf : concave_on s f) :
concave_on ((Ξ» z, a + z) β»ΒΉ' s) (f β (Ξ» z, z + a)) :=
by simpa only [add_comm] using hf.translate_right
end functions
section center_mass
/-- Center mass of a finite collection of points with prescribed weights.
Note that we require neither `0 β€ w i` nor `β w = 1`. -/
noncomputable def finset.center_mass (t : finset ΞΉ) (w : ΞΉ β β) (z : ΞΉ β E) : E :=
(β i in t, w i)β»ΒΉ β’ (β i in t, w i β’ z i)
variables (i j : ΞΉ) (c : β) (t : finset ΞΉ) (w : ΞΉ β β) (z : ΞΉ β E)
open finset
lemma finset.center_mass_empty : (β
: finset ΞΉ).center_mass w z = 0 :=
by simp only [center_mass, sum_empty, smul_zero]
lemma finset.center_mass_pair (hne : i β j) :
({i, j} : finset ΞΉ).center_mass w z = (w i / (w i + w j)) β’ z i + (w j / (w i + w j)) β’ z j :=
by simp only [center_mass, sum_pair hne, smul_add, (mul_smul _ _ _).symm, div_eq_inv_mul]
variable {w}
lemma finset.center_mass_insert (ha : i β t) (hw : β j in t, w j β 0) :
(insert i t).center_mass w z = (w i / (w i + β j in t, w j)) β’ z i +
((β j in t, w j) / (w i + β j in t, w j)) β’ t.center_mass w z :=
begin
simp only [center_mass, sum_insert ha, smul_add, (mul_smul _ _ _).symm],
congr' 2,
{ apply mul_comm },
{ rw [div_mul_eq_mul_div, mul_inv_cancel hw, one_div] }
end
lemma finset.center_mass_singleton (hw : w i β 0) : ({i} : finset ΞΉ).center_mass w z = z i :=
by rw [center_mass, sum_singleton, sum_singleton, β mul_smul, inv_mul_cancel hw, one_smul]
lemma finset.center_mass_eq_of_sum_1 (hw : β i in t, w i = 1) :
t.center_mass w z = β i in t, w i β’ z i :=
by simp only [finset.center_mass, hw, inv_one, one_smul]
lemma finset.center_mass_smul : t.center_mass w (Ξ» i, c β’ z i) = c β’ t.center_mass w z :=
by simp only [finset.center_mass, finset.smul_sum, (mul_smul _ _ _).symm, mul_comm c, mul_assoc]
/-- A convex combination of two centers of mass is a center of mass as well. This version
deals with two different index types. -/
lemma finset.center_mass_segment'
(s : finset ΞΉ) (t : finset ΞΉ') (ws : ΞΉ β β) (zs : ΞΉ β E) (wt : ΞΉ' β β) (zt : ΞΉ' β E)
(hws : β i in s, ws i = 1) (hwt : β i in t, wt i = 1) (a b : β) (hab : a + b = 1):
a β’ s.center_mass ws zs + b β’ t.center_mass wt zt =
(s.image sum.inl βͺ t.image sum.inr).center_mass
(sum.elim (Ξ» i, a * ws i) (Ξ» j, b * wt j))
(sum.elim zs zt) :=
begin
rw [s.center_mass_eq_of_sum_1 _ hws, t.center_mass_eq_of_sum_1 _ hwt,
smul_sum, smul_sum, β finset.sum_sum_elim, finset.center_mass_eq_of_sum_1],
{ congr' with β¨β©; simp only [sum.elim_inl, sum.elim_inr, mul_smul] },
{ rw [sum_sum_elim, β mul_sum, β mul_sum, hws, hwt, mul_one, mul_one, hab] }
end
/-- A convex combination of two centers of mass is a center of mass as well. This version
works if two centers of mass share the set of original points. -/
lemma finset.center_mass_segment
(s : finset ΞΉ) (wβ wβ : ΞΉ β β) (z : ΞΉ β E)
(hwβ : β i in s, wβ i = 1) (hwβ : β i in s, wβ i = 1) (a b : β) (hab : a + b = 1):
a β’ s.center_mass wβ z + b β’ s.center_mass wβ z =
s.center_mass (Ξ» i, a * wβ i + b * wβ i) z :=
have hw : β i in s, (a * wβ i + b * wβ i) = 1,
by simp only [mul_sum.symm, sum_add_distrib, mul_one, *],
by simp only [finset.center_mass_eq_of_sum_1, smul_sum, sum_add_distrib, add_smul, mul_smul, *]
lemma finset.center_mass_ite_eq (hi : i β t) :
t.center_mass (Ξ» j, if (i = j) then 1 else 0) z = z i :=
begin
rw [finset.center_mass_eq_of_sum_1],
transitivity β j in t, if (i = j) then z i else 0,
{ congr' with i, split_ifs, exacts [h βΈ one_smul _ _, zero_smul _ _] },
{ rw [sum_ite_eq, if_pos hi] },
{ rw [sum_ite_eq, if_pos hi] }
end
variables {t w}
lemma finset.center_mass_subset {t' : finset ΞΉ} (ht : t β t')
(h : β i β t', i β t β w i = 0) :
t.center_mass w z = t'.center_mass w z :=
begin
rw [center_mass, sum_subset ht h, smul_sum, center_mass, smul_sum],
apply sum_subset ht,
assume i hit' hit,
rw [h i hit' hit, zero_smul, smul_zero]
end
lemma finset.center_mass_filter_ne_zero :
(t.filter (Ξ» i, w i β 0)).center_mass w z = t.center_mass w z :=
finset.center_mass_subset z (filter_subset _) $ Ξ» i hit hit',
by simpa only [hit, mem_filter, true_and, ne.def, not_not] using hit'
variable {z}
/-- Center mass of a finite subset of a convex set belongs to the set
provided that all weights are non-negative, and the total weight is positive. -/
lemma convex.center_mass_mem (hs : convex s) :
(β i β t, 0 β€ w i) β (0 < β i in t, w i) β (β i β t, z i β s) β t.center_mass w z β s :=
begin
induction t using finset.induction with i t hi ht, { simp [lt_irrefl] },
intros hβ hpos hmem,
have zi : z i β s, from hmem _ (mem_insert_self _ _),
have hsβ : β j β t, 0 β€ w j, from Ξ» j hj, hβ j $ mem_insert_of_mem hj,
rw [sum_insert hi] at hpos,
by_cases hsum_t : β j in t, w j = 0,
{ have ws : β j β t, w j = 0, from (sum_eq_zero_iff_of_nonneg hsβ).1 hsum_t,
have wz : β j in t, w j β’ z j = 0, from sum_eq_zero (Ξ» i hi, by simp [ws i hi]),
simp only [center_mass, sum_insert hi, wz, hsum_t, add_zero],
simp only [hsum_t, add_zero] at hpos,
rw [β mul_smul, inv_mul_cancel (ne_of_gt hpos), one_smul],
exact zi },
{ rw [finset.center_mass_insert _ _ _ hi hsum_t],
refine convex_iff_div.1 hs zi (ht hsβ _ _) _ (sum_nonneg hsβ) hpos,
{ exact lt_of_le_of_ne (sum_nonneg hsβ) (ne.symm hsum_t) },
{ intros j hj, exact hmem j (mem_insert_of_mem hj) },
{ exact hβ _ (mem_insert_self _ _) } }
end
lemma convex.sum_mem (hs : convex s) (hβ : β i β t, 0 β€ w i) (hβ : β i in t, w i = 1)
(hz : β i β t, z i β s) :
β i in t, w i β’ z i β s :=
by simpa only [hβ, center_mass, inv_one, one_smul] using
hs.center_mass_mem hβ (hβ.symm βΈ zero_lt_one) hz
lemma convex_iff_sum_mem :
convex s β
(β (t : finset E) (w : E β β),
(β i β t, 0 β€ w i) β β i in t, w i = 1 β (β x β t, x β s) β β x in t, w x β’ x β s ) :=
begin
refine β¨Ξ» hs t w hwβ hwβ hts, hs.sum_mem hwβ hwβ hts, _β©,
intros h x y hx hy a b ha hb hab,
by_cases h_cases: x = y,
{ rw [h_cases, βadd_smul, hab, one_smul], exact hy },
{ convert h {x, y} (Ξ» z, if z = y then b else a) _ _ _,
{ simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl] },
{ simp_intros i hi,
cases hi; subst i; simp [ha, hb, if_neg h_cases] },
{ simp only [sum_pair h_cases, if_neg h_cases, if_pos rfl, hab] },
{ simp_intros i hi,
cases hi; subst i; simp [hx, hy, if_neg h_cases] } }
end
/-- Jensen's inequality, `finset.center_mass` version. -/
lemma convex_on.map_center_mass_le {f : E β β} (hf : convex_on s f)
(hβ : β i β t, 0 β€ w i) (hpos : 0 < β i in t, w i)
(hmem : β i β t, z i β s) : f (t.center_mass w z) β€ t.center_mass w (f β z) :=
begin
have hmem' : β i β t, (z i, (f β z) i) β {p : E Γ β | p.1 β s β§ f p.1 β€ p.2},
from Ξ» i hi, β¨hmem i hi, le_refl _β©,
convert (hf.convex_epigraph.center_mass_mem hβ hpos hmem').2;
simp only [center_mass, function.comp, prod.smul_fst, prod.fst_sum, prod.smul_snd, prod.snd_sum]
end
/-- Jensen's inequality, `finset.sum` version. -/
lemma convex_on.map_sum_le {f : E β β} (hf : convex_on s f)
(hβ : β i β t, 0 β€ w i) (hβ : β i in t, w i = 1)
(hmem : β i β t, z i β s) : f (β i in t, w i β’ z i) β€ β i in t, w i * (f (z i)) :=
by simpa only [center_mass, hβ, inv_one, one_smul]
using hf.map_center_mass_le hβ (hβ.symm βΈ zero_lt_one) hmem
/-- If a function `f` is convex on `s` takes value `y` at the center mass of some points
`z i β s`, then for some `i` we have `y β€ f (z i)`. -/
lemma convex_on.exists_ge_of_center_mass {f : E β β} (h : convex_on s f)
(hwβ : β i β t, 0 β€ w i) (hws : 0 < β i in t, w i) (hz : β i β t, z i β s) :
β i β t, f (t.center_mass w z) β€ f (z i) :=
begin
set y := t.center_mass w z,
have : f y β€ t.center_mass w (f β z) := h.map_center_mass_le hwβ hws hz,
rw β sum_filter_ne_zero at hws,
rw [β finset.center_mass_filter_ne_zero (f β z), center_mass, smul_eq_mul,
β div_eq_inv_mul, le_div_iff hws, mul_sum] at this,
replace : β i β t.filter (Ξ» i, w i β 0), f y * w i β€ w i β’ (f β z) i :=
exists_le_of_sum_le (nonempty_of_sum_ne_zero (ne_of_gt hws)) this,
rcases this with β¨i, hi, Hβ©,
rw [mem_filter] at hi,
use [i, hi.1],
simp only [smul_eq_mul, mul_comm (w i)] at H,
refine (mul_le_mul_right _).1 H,
exact lt_of_le_of_ne (hwβ i hi.1) hi.2.symm
end
end center_mass
section convex_hull
variable {t : set E}
/-- Convex hull of a set `s` is the minimal convex set that includes `s` -/
def convex_hull (s : set E) : set E :=
β (t : set E) (hst : s β t) (ht : convex t), t
variable (s)
lemma subset_convex_hull : s β convex_hull s :=
set.subset_Inter $ Ξ» t, set.subset_Inter $ Ξ» hst, set.subset_Inter $ Ξ» ht, hst
lemma convex_convex_hull : convex (convex_hull s) :=
convex_Inter $ Ξ» t, convex_Inter $ Ξ» ht, convex_Inter id
variable {s}
lemma convex_hull_min (hst : s β t) (ht : convex t) : convex_hull s β t :=
set.Inter_subset_of_subset t $ set.Inter_subset_of_subset hst $ set.Inter_subset _ ht
lemma convex_hull_mono (hst : s β t) : convex_hull s β convex_hull t :=
convex_hull_min (set.subset.trans hst $ subset_convex_hull t) (convex_convex_hull t)
lemma convex.convex_hull_eq {s : set E} (hs : convex s) : convex_hull s = s :=
set.subset.antisymm (convex_hull_min (set.subset.refl _) hs) (subset_convex_hull s)
@[simp]
lemma convex_hull_singleton {x : E} : convex_hull ({x} : set E) = {x} :=
(convex_singleton x).convex_hull_eq
lemma is_linear_map.image_convex_hull {f : E β F} (hf : is_linear_map β f) :
f '' (convex_hull s) = convex_hull (f '' s) :=
begin
refine set.subset.antisymm _ _,
{ rw [set.image_subset_iff],
exact convex_hull_min (set.image_subset_iff.1 $ subset_convex_hull $ f '' s)
((convex_convex_hull (f '' s)).is_linear_preimage hf) },
{ exact convex_hull_min (set.image_subset _ $ subset_convex_hull s)
((convex_convex_hull s).is_linear_image hf) }
end
lemma linear_map.image_convex_hull (f : E ββ[β] F) :
f '' (convex_hull s) = convex_hull (f '' s) :=
f.is_linear.image_convex_hull
lemma finset.center_mass_mem_convex_hull (t : finset ΞΉ) {w : ΞΉ β β} (hwβ : β i β t, 0 β€ w i)
(hws : 0 < β i in t, w i) {z : ΞΉ β E} (hz : β i β t, z i β s) :
t.center_mass w z β convex_hull s :=
(convex_convex_hull s).center_mass_mem hwβ hws (Ξ» i hi, subset_convex_hull s $ hz i hi)
-- TODO : Do we need other versions of the next lemma?
/-- Convex hull of `s` is equal to the set of all centers of masses of `finset`s `t`, `z '' t β s`.
This version allows finsets in any type in any universe. -/
lemma convex_hull_eq (s : set E) :
convex_hull s = {x : E | β (ΞΉ : Type u') (t : finset ΞΉ) (w : ΞΉ β β) (z : ΞΉ β E)
(hwβ : β i β t, 0 β€ w i) (hwβ : β i in t, w i = 1) (hz : β i β t, z i β s) , t.center_mass w z = x} :=
begin
refine subset.antisymm (convex_hull_min _ _) _,
{ intros x hx,
use [punit, {punit.star}, Ξ» _, 1, Ξ» _, x, Ξ» _ _, zero_le_one,
finset.sum_singleton, Ξ» _ _, hx],
simp only [finset.center_mass, finset.sum_singleton, inv_one, one_smul] },
{ rintros x y β¨ΞΉ, sx, wx, zx, hwxβ, hwxβ, hzx, rflβ© β¨ΞΉ', sy, wy, zy, hwyβ, hwyβ, hzy, rflβ©
a b ha hb hab,
rw [finset.center_mass_segment' _ _ _ _ _ _ hwxβ hwyβ _ _ hab],
refine β¨_, _, _, _, _, _, _, rflβ©,
{ rintros i hi,
rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi,
rcases hi with β¨j, hj, rflβ©|β¨j, hj, rflβ©;
simp only [sum.elim_inl, sum.elim_inr];
apply_rules [mul_nonneg, hwxβ, hwyβ] },
{ simp [finset.sum_sum_elim, finset.mul_sum.symm, *] },
{ intros i hi,
rw [finset.mem_union, finset.mem_image, finset.mem_image] at hi,
rcases hi with β¨j, hj, rflβ©|β¨j, hj, rflβ©;
simp only [sum.elim_inl, sum.elim_inr]; apply_rules [hzx, hzy] } },
{ rintros _ β¨ΞΉ, t, w, z, hwβ, hwβ, hz, rflβ©,
exact t.center_mass_mem_convex_hull hwβ (hwβ.symm βΈ zero_lt_one) hz }
end
/-- Maximum principle for convex functions. If a function `f` is convex on the convex hull of `s`,
then `f` can't have a maximum on `convex_hull s` outside of `s`. -/
lemma convex_on.exists_ge_of_mem_convex_hull {f : E β β} (hf : convex_on (convex_hull s) f)
{x} (hx : x β convex_hull s) : β y β s, f x β€ f y :=
begin
rw convex_hull_eq at hx,
rcases hx with β¨Ξ±, t, w, z, hwβ, hwβ, hz, rflβ©,
rcases hf.exists_ge_of_center_mass hwβ (hwβ.symm βΈ zero_lt_one)
(Ξ» i hi, subset_convex_hull s (hz i hi)) with β¨i, hit, Hiβ©,
exact β¨z i, hz i hit, Hiβ©
end
lemma finset.convex_hull_eq (s : finset E) :
convex_hull βs = {x : E | β (w : E β β) (hwβ : β y β s, 0 β€ w y) (hwβ : β y in s, w y = 1),
s.center_mass w id = x} :=
begin
refine subset.antisymm (convex_hull_min _ _) _,
{ intros x hx,
rw [finset.mem_coe] at hx,
refine β¨_, _, _, finset.center_mass_ite_eq _ _ _ hxβ©,
{ intros, split_ifs, exacts [zero_le_one, le_refl 0] },
{ rw [finset.sum_ite_eq, if_pos hx] } },
{ rintros x y β¨wx, hwxβ, hwxβ, rflβ© β¨wy, hwyβ, hwyβ, rflβ©
a b ha hb hab,
rw [finset.center_mass_segment _ _ _ _ hwxβ hwyβ _ _ hab],
refine β¨_, _, _, rflβ©,
{ rintros i hi,
apply_rules [add_nonneg, mul_nonneg, hwxβ, hwyβ], },
{ simp only [finset.sum_add_distrib, finset.mul_sum.symm, mul_one, *] } },
{ rintros _ β¨w, hwβ, hwβ, rflβ©,
exact s.center_mass_mem_convex_hull (Ξ» x hx, hwβ _ hx)
(hwβ.symm βΈ zero_lt_one) (Ξ» x hx, hx) }
end
lemma set.finite.convex_hull_eq {s : set E} (hs : finite s) :
convex_hull s = {x : E | β (w : E β β) (hwβ : β y β s, 0 β€ w y) (hwβ : β y in hs.to_finset, w y = 1),
hs.to_finset.center_mass w id = x} :=
by simpa only [set.finite.coe_to_finset, set.finite.mem_to_finset, exists_prop]
using hs.to_finset.convex_hull_eq
lemma convex_hull_eq_union_convex_hull_finite_subsets (s : set E) :
convex_hull s = β (t : finset E) (w : βt β s), convex_hull βt :=
begin
refine subset.antisymm _ _,
{ rw [convex_hull_eq.{u}],
rintros x β¨ΞΉ, t, w, z, hwβ, hwβ, hz, rflβ©,
simp only [mem_Union],
refine β¨t.image z, _, _β©,
{ rw [finset.coe_image, image_subset_iff],
exact hz },
{ apply t.center_mass_mem_convex_hull hwβ,
{ simp only [hwβ, zero_lt_one] },
{ exact Ξ» i hi, finset.mem_coe.2 (finset.mem_image_of_mem _ hi) } } },
{ exact Union_subset (Ξ» i, Union_subset convex_hull_mono), },
end
lemma is_linear_map.convex_hull_image {f : E β F} (hf : is_linear_map β f) (s : set E) :
convex_hull (f '' s) = f '' convex_hull s :=
set.subset.antisymm (convex_hull_min (image_subset _ (subset_convex_hull s)) $
(convex_convex_hull s).is_linear_image hf)
(image_subset_iff.2 $ convex_hull_min
(image_subset_iff.1 $ subset_convex_hull _)
((convex_convex_hull _).is_linear_preimage hf))
lemma linear_map.convex_hull_image (f : E ββ[β] F) (s : set E) :
convex_hull (f '' s) = f '' convex_hull s :=
f.is_linear.convex_hull_image s
end convex_hull
/-! ### Simplex -/
section simplex
variables (ΞΉ) [fintype ΞΉ] {f : ΞΉ β β}
/-- Standard simplex in the space of functions `ΞΉ β β` is the set
of vectors with non-negative coordinates with total sum `1`. -/
def std_simplex (ΞΉ : Type*) [fintype ΞΉ] : set (ΞΉ β β) :=
{ f | (β x, 0 β€ f x) β§ β x, f x = 1 }
lemma std_simplex_eq_inter :
std_simplex ΞΉ = (β x, {f | 0 β€ f x}) β© {f | β x, f x = 1} :=
by { ext f, simp only [std_simplex, set.mem_inter_eq, set.mem_Inter, set.mem_set_of_eq] }
lemma convex_std_simplex : convex (std_simplex ΞΉ) :=
begin
refine Ξ» f g hf hg a b ha hb hab, β¨Ξ» x, _, _β©,
{ apply_rules [add_nonneg, mul_nonneg, hf.1, hg.1] },
{ erw [finset.sum_add_distrib, β finset.smul_sum, β finset.smul_sum, hf.2, hg.2,
smul_eq_mul, smul_eq_mul, mul_one, mul_one],
exact hab }
end
variable {ΞΉ}
lemma ite_eq_mem_std_simplex (i : ΞΉ) : (Ξ» j, ite (i = j) (1:β) 0) β std_simplex ΞΉ :=
β¨Ξ» j, by simp only; split_ifs; norm_num, by rw [finset.sum_ite_eq, if_pos (finset.mem_univ _)] β©
/-- `std_simplex ΞΉ` is the convex hull of the canonical basis in `ΞΉ β β`. -/
lemma convex_hull_basis_eq_std_simplex :
convex_hull (range $ Ξ»(i j:ΞΉ), if i = j then (1:β) else 0) = std_simplex ΞΉ :=
begin
refine subset.antisymm (convex_hull_min _ (convex_std_simplex ΞΉ)) _,
{ rintros _ β¨i, rflβ©,
exact ite_eq_mem_std_simplex i },
{ rintros w β¨hwβ, hwββ©,
rw [pi_eq_sum_univ w, β finset.univ.center_mass_eq_of_sum_1 _ hwβ],
exact finset.univ.center_mass_mem_convex_hull (Ξ» i hi, hwβ i)
(hwβ.symm βΈ zero_lt_one) (Ξ» i hi, mem_range_self i) }
end
variable {ΞΉ}
/-- Convex hull of a finite set is the image of the standard simplex in `s β β`
under the linear map sending each function `w` to `β x in s, w x β’ x`.
Since we have no sums over finite sets, we use sum over `@finset.univ _ hs.fintype`.
The map is defined in terms of operations on `(s β β) ββ[β] β` so that later we will not need
to prove that this map is linear. -/
lemma set.finite.convex_hull_eq_image {s : set E} (hs : finite s) :
convex_hull s = by haveI := hs.fintype; exact
(β(β x : s, (@linear_map.proj β s _ (Ξ» i, β) _ _ x).smul_right x.1)) '' (std_simplex s) :=
begin
rw [β convex_hull_basis_eq_std_simplex, β linear_map.convex_hull_image, β set.range_comp, (β)],
apply congr_arg,
convert subtype.range_coe.symm,
ext x,
simp [linear_map.sum_apply, ite_smul, finset.filter_eq]
end
/-- All values of a function `f β std_simplex ΞΉ` belong to `[0, 1]`. -/
lemma mem_Icc_of_mem_std_simplex (hf : f β std_simplex ΞΉ) (x) :
f x β I :=
β¨hf.1 x, hf.2 βΈ finset.single_le_sum (Ξ» y hy, hf.1 y) (finset.mem_univ x)β©
end simplex
|
9287040de8c43470ef4d65f46de09843cf1acca7 | 097294e9b80f0d9893ac160b9c7219aa135b51b9 | /instructor/today.lean | f505580f2bf848a826f2cd9c23d222dc2ece8f7d | [] | no_license | AbigailCastro17/CS2102-Discrete-Math | cf296251be9418ce90206f5e66bde9163e21abf9 | d741e4d2d6a9b2e0c8380e51706218b8f608cee4 | refs/heads/main | 1,682,891,087,358 | 1,621,401,341,000 | 1,621,401,341,000 | 368,749,959 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 99 | lean | /-
- polynorphic functions and implicit arguments
- Lean's "structure" syntax for "record" types
-/ |
fe24aae1ebc85a8f4520e53c5f2dfcc8b964fce0 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/bicategory/coherence.lean | c0b364e1e9122b65a157b5204f50db5e20665318 | [
"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 | 8,725 | lean | /-
Copyright (c) 2022 Yuma Mizuno. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yuma Mizuno, Junyan Xu
-/
import category_theory.path_category
import category_theory.functor.fully_faithful
import category_theory.bicategory.free
import category_theory.bicategory.locally_discrete
/-!
# The coherence theorem for bicategories
In this file, we prove the coherence theorem for bicategories, stated in the following form: the
free bicategory over any quiver is locally thin.
The proof is almost the same as the proof of the coherence theorem for monoidal categories that
has been previously formalized in mathlib, which is based on the proof described by Ilya Beylin
and Peter Dybjer. The idea is to view a path on a quiver as a normal form of a 1-morphism in the
free bicategory on the same quiver. A normalization procedure is then described by
`normalize : pseudofunctor (free_bicategory B) (locally_discrete (paths B))`, which is a
pseudofunctor from the free bicategory to the locally discrete bicategory on the path category.
It turns out that this pseudofunctor is locally an equivalence of categories, and the coherence
theorem follows immediately from this fact.
## Main statements
* `locally_thin` : the free bicategory is locally thin, that is, there is at most one
2-morphism between two fixed 1-morphisms.
## References
* [Ilya Beylin and Peter Dybjer, Extracting a proof of coherence for monoidal categories from a
proof of normalization for monoids][beylin1996]
-/
open quiver (path) quiver.path
namespace category_theory
open bicategory category
open_locale bicategory
universes v u
namespace free_bicategory
variables {B : Type u} [quiver.{v+1} B]
/-- Auxiliary definition for `inclusion_path`. -/
@[simp]
def inclusion_path_aux {a : B} : β {b : B}, path a b β hom a b
| _ nil := hom.id a
| _ (cons p f) := (inclusion_path_aux p).comp (hom.of f)
/--
The discrete category on the paths includes into the category of 1-morphisms in the free
bicategory.
-/
def inclusion_path (a b : B) : discrete (path.{v+1} a b) β₯€ hom a b :=
{ obj := inclusion_path_aux,
map := Ξ» f g Ξ·, eq_to_hom (congr_arg inclusion_path_aux (discrete.eq_of_hom Ξ·)) }
/--
The inclusion from the locally discrete bicategory on the path category into the free bicategory
as a prelax functor. This will be promoted to a pseudofunctor after proving the coherence theorem.
See `inclusion`.
-/
def preinclusion (B : Type u) [quiver.{v+1} B] :
prelax_functor (locally_discrete (paths B)) (free_bicategory B) :=
{ obj := id,
map := Ξ» a b, (inclusion_path a b).obj,
mapβ := Ξ» a b, (inclusion_path a b).map }
@[simp]
lemma preinclusion_obj (a : B) :
(preinclusion B).obj a = a :=
rfl
/--
The normalization of the composition of `p : path a b` and `f : hom b c`.
`p` will eventually be taken to be `nil` and we then get the normalization
of `f` alone, but the auxiliary `p` is necessary for Lean to accept the definition of
`normalize_iso` and the `whisker_left` case of `normalize_aux_congr` and `normalize_naturality`.
-/
@[simp]
def normalize_aux {a : B} : β {b c : B}, path a b β hom b c β path a c
| _ _ p (hom.of f) := p.cons f
| _ _ p (hom.id b) := p
| _ _ p (hom.comp f g) := normalize_aux (normalize_aux p f) g
/-
We may define
```
def normalize_aux' : β {a b : B}, hom a b β path a b
| _ _ (hom.of f) := f.to_path
| _ _ (hom.id b) := nil
| _ _ (hom.comp f g) := (normalize_aux' f).comp (normalize_aux' g)
```
and define `normalize_aux p f` to be `p.comp (normalize_aux' f)` and this will be
equal to the above definition, but the equality proof requires `comp_assoc`, and it
thus lacks the correct definitional property to make the definition of `normalize_iso`
typecheck.
```
example {a b c : B} (p : path a b) (f : hom b c) :
normalize_aux p f = p.comp (normalize_aux' f) :=
by { induction f, refl, refl,
case comp : _ _ _ _ _ ihf ihg { rw [normalize_aux, ihf, ihg], apply comp_assoc } }
```
-/
/--
A 2-isomorphism between a partially-normalized 1-morphism in the free bicategory to the
fully-normalized 1-morphism.
-/
@[simp]
def normalize_iso {a : B} : β {b c : B} (p : path a b) (f : hom b c),
(preinclusion B).map p β« f β
(preinclusion B).map (normalize_aux p f)
| _ _ p (hom.of f) := iso.refl _
| _ _ p (hom.id b) := Ο_ _
| _ _ p (hom.comp f g) := (Ξ±_ _ _ _).symm βͺβ«
whisker_right_iso (normalize_iso p f) g βͺβ« normalize_iso (normalize_aux p f) g
/--
Given a 2-morphism between `f` and `g` in the free bicategory, we have the equality
`normalize_aux p f = normalize_aux p g`.
-/
lemma normalize_aux_congr {a b c : B} (p : path a b) {f g : hom b c} (Ξ· : f βΆ g) :
normalize_aux p f = normalize_aux p g :=
begin
rcases Ξ·,
apply @congr_fun _ _ (Ξ» p, normalize_aux p f),
clear p,
induction Ξ·,
case vcomp { apply eq.trans; assumption },
/- p β nil required! See the docstring of `normalize_aux`. -/
case whisker_left : _ _ _ _ _ _ _ ih { funext, apply congr_fun ih },
case whisker_right : _ _ _ _ _ _ _ ih { funext, apply congr_arg2 _ (congr_fun ih p) rfl },
all_goals { funext, refl }
end
/-- The 2-isomorphism `normalize_iso p f` is natural in `f`. -/
lemma normalize_naturality {a b c : B} (p : path a b) {f g : hom b c} (Ξ· : f βΆ g) :
(preinclusion B).map p β Ξ· β« (normalize_iso p g).hom =
(normalize_iso p f).hom β« eq_to_hom (congr_arg _ (normalize_aux_congr p Ξ·)) :=
begin
rcases Ξ·, induction Ξ·,
case id : { simp },
case vcomp : _ _ _ _ _ _ _ ihf ihg
{ rw [mk_vcomp, bicategory.whisker_left_comp],
slice_lhs 2 3 { rw ihg },
slice_lhs 1 2 { rw ihf },
simp },
case whisker_left : _ _ _ _ _ _ _ ih
/- p β nil required! See the docstring of `normalize_aux`. -/
{ dsimp, simp_rw [associator_inv_naturality_right_assoc, whisker_exchange_assoc, ih, assoc] },
case whisker_right : _ _ _ _ _ h Ξ· ih
{ dsimp,
rw [associator_inv_naturality_middle_assoc, βcomp_whisker_right_assoc, ih, comp_whisker_right],
have := dcongr_arg (Ξ» x, (normalize_iso x h).hom) (normalize_aux_congr p (quot.mk _ Ξ·)),
dsimp at this, simp [this] },
all_goals { dsimp, dsimp [id_def, comp_def], simp }
end
@[simp]
lemma normalize_aux_nil_comp {a b c : B} (f : hom a b) (g : hom b c) :
normalize_aux nil (f.comp g) = (normalize_aux nil f).comp (normalize_aux nil g) :=
begin
induction g generalizing a,
case id { refl },
case of { refl },
case comp : _ _ _ g _ ihf ihg { erw [ihg (f.comp g), ihf f, ihg g, comp_assoc] }
end
/-- The normalization pseudofunctor for the free bicategory on a quiver `B`. -/
def normalize (B : Type u) [quiver.{v+1} B] :
pseudofunctor (free_bicategory B) (locally_discrete (paths B)) :=
{ obj := id,
map := Ξ» a b, normalize_aux nil,
mapβ := Ξ» a b f g Ξ·, eq_to_hom (normalize_aux_congr nil Ξ·),
map_id := Ξ» a, iso.refl nil,
map_comp := Ξ» a b c f g, eq_to_iso (normalize_aux_nil_comp f g) }
/-- Auxiliary definition for `normalize_equiv`. -/
def normalize_unit_iso (a b : free_bicategory B) :
π (a βΆ b) β
(normalize B).map_functor a b β inclusion_path a b :=
nat_iso.of_components (Ξ» f, (Ξ»_ f).symm βͺβ« normalize_iso nil f)
begin
intros f g Ξ·,
erw [left_unitor_inv_naturality_assoc, assoc],
congr' 1,
exact normalize_naturality nil Ξ·
end
/-- Normalization as an equivalence of categories. -/
def normalize_equiv (a b : B) : hom a b β discrete (path.{v+1} a b) :=
equivalence.mk ((normalize _).map_functor a b) (inclusion_path a b)
(normalize_unit_iso a b)
(discrete.nat_iso (Ξ» f, eq_to_iso (by { induction f; tidy })))
/-- The coherence theorem for bicategories. -/
instance locally_thin {a b : free_bicategory B} (f g : a βΆ b) : subsingleton (f βΆ g) :=
β¨Ξ» Ξ· ΞΈ, (normalize_equiv a b).functor.map_injective (subsingleton.elim _ _)β©
/-- Auxiliary definition for `inclusion`. -/
def inclusion_map_comp_aux {a b : B} : β {c : B} (f : path a b) (g : path b c),
(preinclusion _).map (f β« g) β
(preinclusion _).map f β« (preinclusion _).map g
| _ f nil := (Ο_ ((preinclusion _).map f)).symm
| _ f (cons gβ gβ) := whisker_right_iso (inclusion_map_comp_aux f gβ) (hom.of gβ) βͺβ« Ξ±_ _ _ _
/--
The inclusion pseudofunctor from the locally discrete bicategory on the path category into the
free bicategory.
-/
def inclusion (B : Type u) [quiver.{v+1} B] :
pseudofunctor (locally_discrete (paths B)) (free_bicategory B) :=
{ map_id := Ξ» a, iso.refl (π a),
map_comp := Ξ» a b c f g, inclusion_map_comp_aux f g,
-- All the conditions for 2-morphisms are trivial thanks to the coherence theorem!
.. preinclusion B }
end free_bicategory
end category_theory
|
862ac4ad8a23d7197b17a65a3072e82c6efea3c9 | 2eab05920d6eeb06665e1a6df77b3157354316ad | /src/tactic/lint/frontend.lean | 6aac5f3cf669a55c7b0027b52ba57e9e9db29185 | [
"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 | 13,927 | lean | /-
Copyright (c) 2020 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Robert Y. Lewis, Gabriel Ebner
-/
import tactic.lint.basic
/-!
# Linter frontend and commands
This file defines the linter commands which spot common mistakes in the code.
* `#lint`: check all declarations in the current file
* `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects,
and also excluding the current file)
* `#lint_all`: check all declarations in the environment (the current file and all
imported files)
For a list of default / non-default linters, see the "Linting Commands" user command doc entry.
The command `#list_linters` prints a list of the names of all available linters.
You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4).
You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint
that suppresses the output if all checks pass.
A silent lint will fail if any test fails.
You can append a `+` to any command (e.g. `#lint_mathlib+`) to run a verbose lint
that reports the result of each linter, including the successes.
You can append a sequence of linter names to any command to run extra tests, in addition to the
default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`.
You can append `only name1 name2 ...` to any command to run a subset of linters, e.g.
`#lint only unused_arguments`
You can add custom linters by defining a term of type `linter` in the `linter` namespace.
A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check`
or `lint only my_new_check`.
If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default.
Adding the attribute `@[nolint doc_blame unused_arguments]` to a declaration
omits it from only the specified linter checks.
## Tags
sanity check, lint, cleanup, command, tactic
-/
open tactic expr native
setup_tactic_parser
/--
Verbosity for the linter output.
* `low`: only print failing checks, print nothing on success.
* `medium`: only print failing checks, print confirmation on success.
* `high`: print output of every check.
-/
@[derive [decidable_eq, inhabited]]
inductive lint_verbosity | low | medium | high
/-- `get_checks slow extra use_only` produces a list of linters.
`extras` is a list of names that should resolve to declarations with type `linter`.
If `use_only` is true, it only uses the linters in `extra`.
Otherwise, it uses all linters in the environment tagged with `@[linter]`.
If `slow` is false, it only uses the fast default tests. -/
meta def get_checks (slow : bool) (extra : list name) (use_only : bool) :
tactic (list (name Γ linter)) := do
default β if use_only then return [] else attribute.get_instances `linter >>= get_linters,
let default := if slow then default else default.filter (Ξ» l, l.2.is_fast),
list.append default <$> get_linters extra
/--
`lint_core all_decls non_auto_decls checks` applies the linters `checks` to the list of
declarations.
If `auto_decls` is false for a linter (default) the linter is applied to `non_auto_decls`.
If `auto_decls` is true, then it is applied to `all_decls`.
The resulting list has one element for each linter, containing the linter as
well as a map from declaration name to warning.
-/
meta def lint_core (all_decls non_auto_decls : list declaration) (checks : list (name Γ linter)) :
tactic (list (name Γ linter Γ rb_map name string)) := do
checks.mmap $ Ξ» β¨linter_name, linterβ©, do
let test_decls := if linter.auto_decls then all_decls else non_auto_decls,
test_decls β test_decls.mfilter (Ξ» decl, should_be_linted linter_name decl.to_name),
s β read,
let results := test_decls.map_async_chunked $ Ξ» decl, prod.mk decl.to_name $
match linter.test decl s with
| result.success w _ := w
| result.exception msg _ _ :=
some $ "LINTER FAILED:\n" ++ msg.elim "(no message)" (Ξ» msg, to_string $ msg ())
end,
let results := results.foldl (Ξ» (results : rb_map name string) warning,
match warning with
| (decl_name, some w) := results.insert decl_name w
| (_, none) := results
end) mk_rb_map,
pure (linter_name, linter, results)
/-- Sorts a map with declaration keys as names by line number. -/
meta def sort_results {Ξ±} (e : environment) (results : rb_map name Ξ±) : list (name Γ Ξ±) :=
list.reverse $ rb_lmap.values $ rb_lmap.of_list $
results.fold [] $ Ξ» decl linter_warning results,
(((e.decl_pos decl).get_or_else β¨0,0β©).line, (decl, linter_warning)) :: results
/-- Formats a linter warning as `#print` command with comment. -/
meta def print_warning (decl_name : name) (warning : string) : format :=
"#check @" ++ to_fmt decl_name ++ " /- " ++ warning ++ " -/"
/-- Formats a map of linter warnings using `print_warning`, sorted by line number. -/
meta def print_warnings (env : environment) (results : rb_map name string) : format :=
format.intercalate format.line $ (sort_results env results).map $
Ξ» β¨decl_name, warningβ©, print_warning decl_name warning
/--
Formats a map of linter warnings grouped by filename with `-- filename` comments.
The first `drop_fn_chars` characters are stripped from the filename.
-/
meta def grouped_by_filename (e : environment) (results : rb_map name string) (drop_fn_chars := 0)
(formatter: rb_map name string β format) : format :=
let results := results.fold (rb_map.mk string (rb_map name string)) $
Ξ» decl_name linter_warning results,
let fn := (e.decl_olean decl_name).get_or_else "" in
results.insert fn (((results.find fn).get_or_else mk_rb_map).insert
decl_name linter_warning) in
let l := results.to_list.reverse.map (Ξ» β¨fn, resultsβ©,
("-- " ++ fn.popn drop_fn_chars ++ "\n" ++ formatter results : format)) in
format.intercalate "\n\n" l ++ "\n"
/--
Formats the linter results as Lean code with comments and `#print` commands.
-/
meta def format_linter_results
(env : environment)
(results : list (name Γ linter Γ rb_map name string))
(decls non_auto_decls : list declaration)
(group_by_filename : option β)
(where_desc : string) (slow : bool) (verbose : lint_verbosity) (num_linters : β) :
format := do
let formatted_results := results.map $ Ξ» β¨linter_name, linter, resultsβ©,
let report_str : format := to_fmt "/- The `" ++ to_fmt linter_name ++ "` linter reports: -/\n" in
if Β¬ results.empty then
let warnings := match group_by_filename with
| none := print_warnings env results
| some dropped := grouped_by_filename env results dropped (print_warnings env)
end in
report_str ++ "/- " ++ linter.errors_found ++ " -/\n" ++ warnings ++ "\n"
else if verbose = lint_verbosity.high then
"/- OK: " ++ linter.no_errors_found ++ " -/"
else format.nil,
let s := format.intercalate "\n" (formatted_results.filter (Ξ» f, Β¬ f.is_nil)),
let s := if verbose = lint_verbosity.low then s else
format!("/- Checking {non_auto_decls.length} declarations (plus " ++
"{decls.length - non_auto_decls.length} automatically generated ones) {where_desc} " ++
"with {num_linters} linters -/\n\n") ++ s,
let s := if slow then s else s ++ "/- (slow tests skipped) -/\n",
s
/-- The common denominator of `#lint[|mathlib|all]`.
The different commands have different configurations for `l`,
`group_by_filename` and `where_desc`.
If `slow` is false, doesn't do the checks that take a lot of time.
If `verbose` is false, it will suppress messages from passing checks.
By setting `checks` you can customize which checks are performed.
Returns a `name_set` containing the names of all declarations that fail any check in `check`,
and a `format` object describing the failures. -/
meta def lint_aux (decls : list declaration) (group_by_filename : option β)
(where_desc : string) (slow : bool) (verbose : lint_verbosity) (checks : list (name Γ linter)) :
tactic (name_set Γ format) := do
e β get_env,
let non_auto_decls := decls.filter (Ξ» d, Β¬ d.is_auto_or_internal e),
results β lint_core decls non_auto_decls checks,
let s := format_linter_results e results decls non_auto_decls
group_by_filename where_desc slow verbose checks.length,
let ns := name_set.of_list (do (_,_,rs) β results, rs.keys),
pure (ns, s)
/-- Return the message printed by `#lint` and a `name_set` containing all declarations that fail. -/
meta def lint (slow : bool := tt) (verbose : lint_verbosity := lint_verbosity.medium)
(extra : list name := []) (use_only : bool := ff) : tactic (name_set Γ format) := do
checks β get_checks slow extra use_only,
e β get_env,
let l := e.filter (Ξ» d, e.in_current_file d.to_name),
lint_aux l none "in the current file" slow verbose checks
/-- Returns the declarations considered by the mathlib linter. -/
meta def lint_mathlib_decls : tactic (list declaration) := do
e β get_env,
ml β get_mathlib_dir,
pure $ e.filter $ Ξ» d, e.is_prefix_of_file ml d.to_name
/-- Return the message printed by `#lint_mathlib` and a `name_set` containing all declarations
that fail. -/
meta def lint_mathlib (slow : bool := tt) (verbose : lint_verbosity := lint_verbosity.medium)
(extra : list name := []) (use_only : bool := ff) : tactic (name_set Γ format) := do
checks β get_checks slow extra use_only,
decls β lint_mathlib_decls,
mathlib_path_len β string.length <$> get_mathlib_dir,
lint_aux decls mathlib_path_len "in mathlib (only in imported files)" slow verbose checks
/-- Return the message printed by `#lint_all` and a `name_set` containing all declarations
that fail. -/
meta def lint_all (slow : bool := tt) (verbose : lint_verbosity := lint_verbosity.medium)
(extra : list name := []) (use_only : bool := ff) : tactic (name_set Γ format) := do
checks β get_checks slow extra use_only,
e β get_env,
let l := e.get_decls,
lint_aux l (some 0) "in all imported files (including this one)" slow verbose checks
/-- Parses an optional `only`, followed by a sequence of zero or more identifiers.
Prepends `linter.` to each of these identifiers. -/
private meta def parse_lint_additions : parser (bool Γ list name) :=
prod.mk <$> only_flag <*> (list.map (name.append `linter) <$> ident*)
/--
Parses a "-" or "+", returning `lint_verbosity.low` or `lint_verbosity.high` respectively,
or returns `none`.
-/
private meta def parse_verbosity : parser (option lint_verbosity) :=
tk "-" >> return lint_verbosity.low <|>
tk "+" >> return lint_verbosity.high <|>
return none
/-- The common denominator of `lint_cmd`, `lint_mathlib_cmd`, `lint_all_cmd` -/
private meta def lint_cmd_aux
(scope : bool β lint_verbosity β list name β bool β tactic (name_set Γ format)) :
parser unit :=
do verbosity β parse_verbosity,
fast_only β optional (tk "*"),
-- allow either order of *-
verbosity β if verbosity.is_some then return verbosity else parse_verbosity,
let verbosity := verbosity.get_or_else lint_verbosity.medium,
(use_only, extra) β parse_lint_additions,
(failed, s) β scope fast_only.is_none verbosity extra use_only,
when (Β¬ s.is_nil) $ trace s,
when (verbosity = lint_verbosity.low β§ Β¬ failed.empty) $
fail "Linting did not succeed",
when (verbosity = lint_verbosity.medium β§ failed.empty) $
trace "/- All linting checks passed! -/"
/-- The command `#lint` at the bottom of a file will warn you about some common mistakes
in that file. Usage: `#lint`, `#lint linter_1 linter_2`, `#lint only linter_1 linter_2`.
`#lint-` will suppress the output if all checks pass.
`#lint+` will enable verbose output.
Use the command `#list_linters` to see all available linters. -/
@[user_command] meta def lint_cmd (_ : parse $ tk "#lint") : parser unit :=
lint_cmd_aux @lint
/-- The command `#lint_mathlib` checks all of mathlib for certain mistakes.
Usage: `#lint_mathlib`, `#lint_mathlib linter_1 linter_2`, `#lint_mathlib only linter_1 linter_2`.
`#lint_mathlib-` will suppress the output if all checks pass.
`lint_mathlib+` will enable verbose output.
Use the command `#list_linters` to see all available linters. -/
@[user_command] meta def lint_mathlib_cmd (_ : parse $ tk "#lint_mathlib") : parser unit :=
lint_cmd_aux @lint_mathlib
/-- The command `#lint_all` checks all imported files for certain mistakes.
Usage: `#lint_all`, `#lint_all linter_1 linter_2`, `#lint_all only linter_1 linter_2`.
`#lint_all-` will suppress the output if all checks pass.
`lint_all+` will enable verbose output.
Use the command `#list_linters` to see all available linters. -/
@[user_command] meta def lint_all_cmd (_ : parse $ tk "#lint_all") : parser unit :=
lint_cmd_aux @lint_all
/-- The command `#list_linters` prints a list of all available linters. -/
@[user_command] meta def list_linters (_ : parse $ tk "#list_linters") : parser unit :=
do env β get_env,
let ns := env.decl_filter_map $ Ξ» dcl,
if (dcl.to_name.get_prefix = `linter) && (dcl.type = `(linter)) then some dcl.to_name else none,
trace "Available linters:\n linters marked with (*) are in the default lint set\n",
ns.mmap' $ Ξ» n, do
b β has_attribute' `linter n,
trace $ n.pop_prefix.to_string ++ if b then " (*)" else ""
/--
Invoking the hole command `lint` ("Find common mistakes in current file") will print text that
indicates mistakes made in the file above the command. It is equivalent to copying and pasting the
output of `#lint`. On large files, it may take some time before the output appears.
-/
@[hole_command] meta def lint_hole_cmd : hole_command :=
{ name := "Lint",
descr := "Lint: Find common mistakes in current file.",
action := Ξ» es, do (_, s) β lint, return [(s.to_string,"")] }
add_tactic_doc
{ name := "Lint",
category := doc_category.hole_cmd,
decl_names := [`lint_hole_cmd],
tags := ["linting"] }
|
8afcdd18b320a29166cb2072a317f058afd93fdf | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/geometry/manifold/metrizable.lean | 432c3b5b1dae06a39fc279a2b84f647b6964852a | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 1,205 | 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 geometry.manifold.smooth_manifold_with_corners
import topology.paracompact
import topology.metric_space.metrizable
/-!
# Metrizability of a Ο-compact manifold
In this file we show that a Ο-compact Hausdorff topological manifold over a finite dimensional real
vector space is metrizable.
-/
open topological_space
/-- A Ο-compact Hausdorff topological manifold over a finite dimensional real vector space is
metrizable. -/
lemma manifold_with_corners.metrizable_space
{E : Type*} [normed_add_comm_group E] [normed_space β E] [finite_dimensional β E]
{H : Type*} [topological_space H] (I : model_with_corners β E H)
(M : Type*) [topological_space M] [charted_space H M]
[sigma_compact_space M] [t2_space M] : metrizable_space M :=
begin
haveI := I.locally_compact, haveI := charted_space.locally_compact H M,
haveI : normal_space M := normal_of_paracompact_t2,
haveI := I.second_countable_topology,
haveI := charted_space.second_countable_of_sigma_compact H M,
exact metrizable_space_of_t3_second_countable M
end
|
749fc7e1c33786750c5294f528a92e6f6d165096 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/category_theory/idempotents/simplicial_object.lean | 0432a50a0e2ab86b1d80f50e83610b9da3125ffc | [
"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 | 867 | lean | /-
Copyright (c) 2022 JoΓ«l Riou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: JoΓ«l Riou
-/
import algebraic_topology.simplicial_object
import category_theory.idempotents.functor_categories
/-!
# Idempotent completeness of categories of simplicial objects
In this file, we provide an instance expressing that `simplicial_object C`
and `cosimplicial_object C` are idempotent complete categories when the
category `C` is.
-/
namespace category_theory
namespace idempotents
variables {C : Type*} [category C] [is_idempotent_complete C]
instance : is_idempotent_complete (simplicial_object C) :=
idempotents.functor_category_is_idempotent_complete _ _
instance : is_idempotent_complete (cosimplicial_object C) :=
idempotents.functor_category_is_idempotent_complete _ _
end idempotents
end category_theory
|
542657b6659b84e7bac23515c1159dc5ba1e6671 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /stage0/src/Init/System.lean | 0585f2c7ffb051bf7c2e26d9333de3c7cc3c6ae0 | [
"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 | 222 | 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.System.IO
import Init.System.Platform
|
2fbf931912081958a39713ea5eee0df376abd023 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/data/fin.lean | 90a30445b839e6d63517149080ba190b249ad44a | [] | 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 | 47,420 | lean | /-
Copyright (c) 2017 Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Robert Y. Lewis, Keeley Hoek
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.data.nat.cast
import Mathlib.tactic.localized
import Mathlib.order.rel_iso
import Mathlib.PostPort
universes u u_1 u_2 v
namespace Mathlib
/-!
# The finite type with `n` elements
`fin n` is the type whose elements are natural numbers smaller than `n`.
This file expands on the development in the core library.
## Main definitions
### Induction principles
* `fin_zero_elim` : Elimination principle for the empty set `fin 0`, generalizes `fin.elim0`.
* `fin.succ_rec` : Define `C n i` by induction on `i : fin n` interpreted
as `(0 : fin (n - i)).succ.succβ¦`. This function has two arguments: `H0 n` defines
`0`-th element `C (n+1) 0` of an `(n+1)`-tuple, and `Hs n i` defines `(i+1)`-st element
of `(n+1)`-tuple based on `n`, `i`, and `i`-th element of `n`-tuple.
* `fin.succ_rec_on` : same as `fin.succ_rec` but `i : fin n` is the first argument;
* `fin.induction` : Define `C i` by induction on `i : fin (n + 1)`, separating into the
`nat`-like base cases of `C 0` and `C (i.succ)`.
* `fin.induction_on` : same as `fin.induction` but with `i : fin (n + 1)` as the first argument.
### Casts
* `cast_lt i h` : embed `i` into a `fin` where `h` proves it belongs into;
* `cast_le h` : embed `fin n` into `fin m`, `h : n β€ m`;
* `cast eq` : embed `fin n` into `fin m`, `eq : n = m`;
* `cast_add m` : embed `fin n` into `fin (n+m)`;
* `cast_succ` : embed `fin n` into `fin (n+1)`;
* `succ_above p` : embed `fin n` into `fin (n + 1)` with a hole around `p`;
* `pred_above p i h` : embed `i : fin (n+1)` into `fin n` by ignoring `p`;
* `sub_nat i h` : subtract `m` from `i β₯ m`, generalizes `fin.pred`;
* `add_nat i h` : add `m` on `i` on the right, generalizes `fin.succ`;
* `nat_add i h` adds `n` on `i` on the left;
* `clamp n m` : `min n m` as an element of `fin (m + 1)`;
### Operation on tuples
We interpret maps `Ξ i : fin n, Ξ± i` as tuples `(Ξ± 0, β¦, Ξ± (n-1))`.
If `Ξ± i` is a constant map, then tuples are isomorphic (but not definitionally equal)
to `vector`s.
We define the following operations:
* `tail` : the tail of an `n+1` tuple, i.e., its last `n` entries;
* `cons` : adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple;
* `init` : the beginning of an `n+1` tuple, i.e., its first `n` entries;
* `snoc` : adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc`
comes from `cons` (i.e., adding an element to the left of a tuple) read in reverse order.
* `insert_nth` : insert an element to a tuple at a given position.
* `find p` : returns the first index `n` where `p n` is satisfied, and `none` if it is never
satisfied.
### Misc definitions
* `fin.last n` : The greatest value of `fin (n+1)`.
-/
/-- Elimination principle for the empty set `fin 0`, dependent version. -/
def fin_zero_elim {Ξ± : fin 0 β Sort u} (x : fin 0) : Ξ± x :=
fin.elim0 x
theorem fact.succ.pos {n : β} : fact (0 < Nat.succ n) :=
nat.zero_lt_succ n
theorem fact.bit0.pos {n : β} [h : fact (0 < n)] : fact (0 < bit0 n) :=
nat.zero_lt_bit0 (ne_of_gt h)
theorem fact.bit1.pos {n : β} : fact (0 < bit1 n) :=
nat.zero_lt_bit1 n
theorem fact.pow.pos {p : β} {n : β} [h : fact (0 < p)] : fact (0 < p ^ n) :=
pow_pos h n
namespace fin
protected instance fin_to_nat (n : β) : has_coe (fin n) β :=
has_coe.mk subtype.val
theorem is_lt {n : β} (i : fin n) : βi < n :=
subtype.property i
/-- convert a `β` to `fin n`, provided `n` is positive -/
def of_nat' {n : β} [h : fact (0 < n)] (i : β) : fin n :=
{ val := i % n, property := nat.mod_lt i h }
@[simp] protected theorem eta {n : β} (a : fin n) (h : βa < n) : { val := βa, property := h } = a := sorry
theorem ext {n : β} {a : fin n} {b : fin n} (h : βa = βb) : a = b :=
eq_of_veq h
theorem ext_iff {n : β} (a : fin n) (b : fin n) : a = b β βa = βb :=
{ mp := congr_arg fun (a : fin n) => βa, mpr := eq_of_veq }
theorem coe_injective {n : β} : function.injective coe :=
subtype.coe_injective
theorem eq_iff_veq {n : β} (a : fin n) (b : fin n) : a = b β subtype.val a = subtype.val b :=
{ mp := veq_of_eq, mpr := eq_of_veq }
theorem ne_iff_vne {n : β} (a : fin n) (b : fin n) : a β b β subtype.val a β subtype.val b :=
{ mp := vne_of_ne, mpr := ne_of_vne }
@[simp] theorem mk_eq_subtype_mk {n : β} (a : β) (h : a < n) : mk a h = { val := a, property := h } :=
rfl
protected theorem mk.inj_iff {n : β} {a : β} {b : β} {ha : a < n} {hb : b < n} : { val := a, property := ha } = { val := b, property := hb } β a = b :=
subtype.mk_eq_mk
theorem mk_val {m : β} {n : β} (h : m < n) : subtype.val { val := m, property := h } = m :=
rfl
theorem eq_mk_iff_coe_eq {n : β} {a : fin n} {k : β} {hk : k < n} : a = { val := k, property := hk } β βa = k :=
eq_iff_veq a { val := k, property := hk }
@[simp] theorem coe_mk {m : β} {n : β} (h : m < n) : β{ val := m, property := h } = m :=
rfl
theorem mk_coe {n : β} (i : fin n) : { val := βi, property := is_lt i } = i :=
fin.eta i (is_lt i)
theorem coe_eq_val {n : β} (a : fin n) : βa = subtype.val a :=
rfl
@[simp] theorem val_eq_coe {n : β} (a : fin n) : subtype.val a = βa :=
rfl
@[simp] theorem val_one {n : β} : subtype.val 1 = 1 :=
rfl
@[simp] theorem val_two {n : β} : subtype.val (bit0 1) = bit0 1 :=
rfl
@[simp] theorem coe_zero {n : β} : β0 = 0 :=
rfl
@[simp] theorem coe_one {n : β} : β1 = 1 :=
rfl
@[simp] theorem coe_two {n : β} : β(bit0 1) = bit0 1 :=
rfl
/-- `a < b` as natural numbers if and only if `a < b` in `fin n`. -/
@[simp] theorem coe_fin_lt {n : β} {a : fin n} {b : fin n} : βa < βb β a < b :=
iff.rfl
/-- `a β€ b` as natural numbers if and only if `a β€ b` in `fin n`. -/
@[simp] theorem coe_fin_le {n : β} {a : fin n} {b : fin n} : βa β€ βb β a β€ b :=
iff.rfl
theorem val_add {n : β} (a : fin n) (b : fin n) : subtype.val (a + b) = (subtype.val a + subtype.val b) % n := sorry
theorem coe_add {n : β} (a : fin n) (b : fin n) : β(a + b) = (βa + βb) % n := sorry
theorem val_mul {n : β} (a : fin n) (b : fin n) : subtype.val (a * b) = subtype.val a * subtype.val b % n := sorry
theorem coe_mul {n : β} (a : fin n) (b : fin n) : β(a * b) = βa * βb % n := sorry
theorem one_val {n : β} : subtype.val 1 = 1 % (n + 1) :=
rfl
theorem coe_one' {n : β} : β1 = 1 % (n + 1) :=
rfl
@[simp] theorem val_zero' (n : β) : subtype.val 0 = 0 :=
rfl
@[simp] theorem mk_zero {n : β} : { val := 0, property := nat.succ_pos' } = 0 :=
rfl
@[simp] theorem mk_one {n : β} : { val := 1, property := nat.succ_lt_succ (nat.succ_pos n) } = 1 :=
rfl
@[simp] theorem mk_bit0 {m : β} {n : β} (h : bit0 m < n) : { val := bit0 m, property := h } = bit0 { val := m, property := has_le.le.trans_lt (nat.le_add_right m m) h } :=
eq_of_veq (Eq.symm (nat.mod_eq_of_lt h))
@[simp] theorem mk_bit1 {m : β} {n : β} (h : bit1 m < n + 1) : { val := bit1 m, property := h } =
bit1
{ val := m, property := has_le.le.trans_lt (nat.le_add_right m m) (has_lt.lt.trans (nat.lt_succ_self (m + m)) h) } := sorry
@[simp] theorem of_nat_eq_coe (n : β) (a : β) : of_nat a = βa := sorry
/-- Converting an in-range number to `fin (n + 1)` produces a result
whose value is the original number. -/
theorem coe_val_of_lt {n : β} {a : β} (h : a < n + 1) : subtype.val βa = a :=
eq.mpr (id (Eq._oldrec (Eq.refl (subtype.val βa = a)) (Eq.symm (of_nat_eq_coe n a)))) (nat.mod_eq_of_lt h)
/-- Converting the value of a `fin (n + 1)` to `fin (n + 1)` results
in the same value. -/
theorem coe_val_eq_self {n : β} (a : fin (n + 1)) : β(subtype.val a) = a :=
eq.mpr (id (Eq._oldrec (Eq.refl (β(subtype.val a) = a)) (propext (eq_iff_veq (β(subtype.val a)) a))))
(coe_val_of_lt (subtype.property a))
/-- Coercing an in-range number to `fin (n + 1)`, and converting back
to `β`, results in that number. -/
theorem coe_coe_of_lt {n : β} {a : β} (h : a < n + 1) : ββa = a :=
coe_val_of_lt h
/-- Converting a `fin (n + 1)` to `β` and back results in the same
value. -/
@[simp] theorem coe_coe_eq_self {n : β} (a : fin (n + 1)) : ββa = a :=
coe_val_eq_self a
/-- Assume `k = l`. If two functions defined on `fin k` and `fin l` are equal on each element,
then they coincide (in the heq sense). -/
protected theorem heq_fun_iff {Ξ± : Type u_1} {k : β} {l : β} (h : k = l) {f : fin k β Ξ±} {g : fin l β Ξ±} : f == g β β (i : fin k), f i = g { val := βi, property := h βΈ subtype.property i } := sorry
protected theorem heq_ext_iff {k : β} {l : β} (h : k = l) {i : fin k} {j : fin l} : i == j β βi = βj := sorry
protected instance nontrivial {n : β} : nontrivial (fin (n + bit0 1)) :=
nontrivial.mk (Exists.intro 0 (Exists.intro 1 (of_as_true trivial)))
protected instance linear_order {n : β} : linear_order (fin n) :=
linear_order.mk LessEq Less sorry sorry sorry sorry fin.decidable_le (fin.decidable_eq n) fin.decidable_lt
theorem exists_iff {n : β} {p : fin n β Prop} : (β (i : fin n), p i) β β (i : β), β (h : i < n), p { val := i, property := h } := sorry
theorem forall_iff {n : β} {p : fin n β Prop} : (β (i : fin n), p i) β β (i : β) (h : i < n), p { val := i, property := h } := sorry
theorem lt_iff_coe_lt_coe {n : β} {a : fin n} {b : fin n} : a < b β βa < βb :=
iff.rfl
theorem le_iff_coe_le_coe {n : β} {a : fin n} {b : fin n} : a β€ b β βa β€ βb :=
iff.rfl
theorem mk_lt_of_lt_coe {n : β} {b : fin n} {a : β} (h : a < βb) : { val := a, property := has_lt.lt.trans h (is_lt b) } < b :=
h
theorem mk_le_of_le_coe {n : β} {b : fin n} {a : β} (h : a β€ βb) : { val := a, property := has_le.le.trans_lt h (is_lt b) } β€ b :=
h
theorem zero_le {n : β} (a : fin (n + 1)) : 0 β€ a :=
nat.zero_le (subtype.val a)
@[simp] theorem coe_succ {n : β} (j : fin n) : β(fin.succ j) = βj + 1 := sorry
theorem succ_pos {n : β} (a : fin n) : 0 < fin.succ a := sorry
/-- The greatest value of `fin (n+1)` -/
def last (n : β) : fin (n + 1) :=
{ val := n, property := nat.lt_succ_self n }
@[simp] theorem coe_last (n : β) : β(last n) = n :=
rfl
theorem last_val (n : β) : subtype.val (last n) = n :=
rfl
theorem le_last {n : β} (i : fin (n + 1)) : i β€ last n :=
nat.le_of_lt_succ (is_lt i)
protected instance bounded_lattice {n : β} : bounded_lattice (fin (n + 1)) :=
bounded_lattice.mk lattice.sup linear_order.le linear_order.lt sorry sorry sorry sorry sorry sorry lattice.inf sorry
sorry sorry (last n) le_last 0 zero_le
/-- `fin.succ` as an `order_embedding` -/
def succ_embedding (n : β) : fin n βͺo fin (n + 1) :=
order_embedding.of_strict_mono fin.succ sorry
@[simp] theorem coe_succ_embedding {n : β} : β(succ_embedding n) = fin.succ :=
rfl
@[simp] theorem succ_le_succ_iff {n : β} {a : fin n} {b : fin n} : fin.succ a β€ fin.succ b β a β€ b :=
order_embedding.le_iff_le (succ_embedding n)
@[simp] theorem succ_lt_succ_iff {n : β} {a : fin n} {b : fin n} : fin.succ a < fin.succ b β a < b :=
order_embedding.lt_iff_lt (succ_embedding n)
theorem succ_injective (n : β) : function.injective fin.succ :=
rel_embedding.injective (succ_embedding n)
@[simp] theorem succ_inj {n : β} {a : fin n} {b : fin n} : fin.succ a = fin.succ b β a = b :=
function.injective.eq_iff (succ_injective n)
theorem succ_ne_zero {n : β} (k : fin n) : fin.succ k β 0 := sorry
@[simp] theorem succ_zero_eq_one {n : β} : fin.succ 0 = 1 :=
rfl
theorem mk_succ_pos {n : β} (i : β) (h : i < n) : 0 < { val := Nat.succ i, property := add_lt_add_right h 1 } := sorry
theorem one_lt_succ_succ {n : β} (a : fin n) : 1 < fin.succ (fin.succ a) := sorry
theorem succ_succ_ne_one {n : β} (a : fin n) : fin.succ (fin.succ a) β 1 :=
ne_of_gt (one_lt_succ_succ a)
@[simp] theorem coe_pred {n : β} (j : fin (n + 1)) (h : j β 0) : β(pred j h) = βj - 1 := sorry
@[simp] theorem succ_pred {n : β} (i : fin (n + 1)) (h : i β 0) : fin.succ (pred i h) = i := sorry
@[simp] theorem pred_succ {n : β} (i : fin n) {h : fin.succ i β 0} : pred (fin.succ i) h = i := sorry
@[simp] theorem pred_mk_succ {n : β} (i : β) (h : i < n + 1) : pred { val := i + 1, property := add_lt_add_right h 1 } (ne_of_vne (ne_of_gt (mk_succ_pos i h))) =
{ val := i, property := h } := sorry
@[simp] theorem pred_le_pred_iff {n : β} {a : fin (Nat.succ n)} {b : fin (Nat.succ n)} {ha : a β 0} {hb : b β 0} : pred a ha β€ pred b hb β a β€ b :=
eq.mpr (id (Eq._oldrec (Eq.refl (pred a ha β€ pred b hb β a β€ b)) (Eq.symm (propext succ_le_succ_iff))))
(eq.mpr (id (Eq._oldrec (Eq.refl (fin.succ (pred a ha) β€ fin.succ (pred b hb) β a β€ b)) (succ_pred a ha)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a β€ fin.succ (pred b hb) β a β€ b)) (succ_pred b hb))) (iff.refl (a β€ b))))
@[simp] theorem pred_lt_pred_iff {n : β} {a : fin (Nat.succ n)} {b : fin (Nat.succ n)} {ha : a β 0} {hb : b β 0} : pred a ha < pred b hb β a < b :=
eq.mpr (id (Eq._oldrec (Eq.refl (pred a ha < pred b hb β a < b)) (Eq.symm (propext succ_lt_succ_iff))))
(eq.mpr (id (Eq._oldrec (Eq.refl (fin.succ (pred a ha) < fin.succ (pred b hb) β a < b)) (succ_pred a ha)))
(eq.mpr (id (Eq._oldrec (Eq.refl (a < fin.succ (pred b hb) β a < b)) (succ_pred b hb))) (iff.refl (a < b))))
@[simp] theorem pred_inj {n : β} {a : fin (n + 1)} {b : fin (n + 1)} {ha : a β 0} {hb : b β 0} : pred a ha = pred b hb β a = b := sorry
/-- The inclusion map `fin n β β` is a relation embedding. -/
def coe_embedding (n : β) : fin n βͺo β :=
rel_embedding.mk (function.embedding.mk coe eq_of_veq) sorry
/-- The ordering on `fin n` is a well order. -/
protected instance fin.lt.is_well_order (n : β) : is_well_order (fin n) Less :=
order_embedding.is_well_order (coe_embedding n)
/-- `cast_lt i h` embeds `i` into a `fin` where `h` proves it belongs into. -/
def cast_lt {n : β} {m : β} (i : fin m) (h : subtype.val i < n) : fin n :=
{ val := subtype.val i, property := h }
@[simp] theorem coe_cast_lt {n : β} {m : β} (i : fin m) (h : subtype.val i < n) : β(cast_lt i h) = βi :=
rfl
/-- `cast_le h i` embeds `i` into a larger `fin` type. -/
def cast_le {n : β} {m : β} (h : n β€ m) : fin n βͺo fin m :=
order_embedding.of_strict_mono (fun (a : fin n) => cast_lt a sorry) sorry
@[simp] theorem coe_cast_le {n : β} {m : β} (h : n β€ m) (i : fin n) : β(coe_fn (cast_le h) i) = βi :=
rfl
/-- `cast eq i` embeds `i` into a equal `fin` type. -/
def cast {n : β} {m : β} (eq : n = m) : fin n βo fin m :=
rel_iso.mk (equiv.mk β(cast_le sorry) β(cast_le sorry) sorry sorry) sorry
@[simp] theorem symm_cast {n : β} {m : β} (h : n = m) : order_iso.symm (cast h) = cast (Eq.symm h) :=
rfl
theorem coe_cast {n : β} {m : β} (h : n = m) (i : fin n) : β(coe_fn (cast h) i) = βi :=
rfl
@[simp] theorem cast_trans {n : β} {m : β} {k : β} (h : n = m) (h' : m = k) {i : fin n} : coe_fn (cast h') (coe_fn (cast h) i) = coe_fn (cast (Eq.trans h h')) i :=
rfl
@[simp] theorem cast_refl {n : β} {i : fin n} : coe_fn (cast rfl) i = i :=
ext (Eq.refl β(coe_fn (cast rfl) i))
/-- `cast_add m i` embeds `i : fin n` in `fin (n+m)`. -/
def cast_add {n : β} (m : β) : fin n βͺo fin (n + m) :=
cast_le (nat.le_add_right n m)
@[simp] theorem coe_cast_add {n : β} (m : β) (i : fin n) : β(coe_fn (cast_add m) i) = βi :=
rfl
/-- `cast_succ i` embeds `i : fin n` in `fin (n+1)`. -/
def cast_succ {n : β} : fin n βͺo fin (n + 1) :=
cast_add 1
@[simp] theorem coe_cast_succ {n : β} (i : fin n) : β(coe_fn cast_succ i) = βi :=
rfl
theorem cast_succ_lt_succ {n : β} (i : fin n) : coe_fn cast_succ i < fin.succ i := sorry
theorem succ_above_aux {n : β} (p : fin (n + 1)) : strict_mono fun (i : fin n) => ite (coe_fn cast_succ i < p) (coe_fn cast_succ i) (fin.succ i) := sorry
/-- `succ_above p i` embeds `fin n` into `fin (n + 1)` with a hole around `p`. -/
def succ_above {n : β} (p : fin (n + 1)) : fin n βͺo fin (n + 1) :=
order_embedding.of_strict_mono
(fun (a : fin n) => (fun (i : fin n) => ite (coe_fn cast_succ i < p) (coe_fn cast_succ i) (fin.succ i)) a)
(succ_above_aux p)
/-- `pred_above p i h` embeds `i : fin (n+1)` into `fin n` by ignoring `p`. -/
def pred_above {n : β} (p : fin (n + 1)) (i : fin (n + 1)) (hi : i β p) : fin n :=
dite (i < p) (fun (h : i < p) => cast_lt i sorry) fun (h : Β¬i < p) => pred i sorry
/-- `sub_nat i h` subtracts `m` from `i`, generalizes `fin.pred`. -/
def sub_nat {n : β} (m : β) (i : fin (n + m)) (h : m β€ βi) : fin n :=
{ val := βi - m, property := sorry }
@[simp] theorem coe_sub_nat {n : β} {m : β} (i : fin (n + m)) (h : m β€ βi) : β(sub_nat m i h) = βi - m :=
rfl
/-- `add_nat i h` adds `m` to `i`, generalizes `fin.succ`. -/
def add_nat {n : β} (m : β) : fin n βͺo fin (n + m) :=
order_embedding.of_strict_mono (fun (i : fin n) => { val := βi + m, property := sorry }) sorry
@[simp] theorem coe_add_nat {n : β} (m : β) (i : fin n) : β(coe_fn (add_nat m) i) = βi + m :=
rfl
/-- `nat_add i h` adds `n` to `i` "on the left". -/
def nat_add (n : β) {m : β} : fin m βͺo fin (n + m) :=
order_embedding.of_strict_mono (fun (i : fin m) => { val := n + βi, property := sorry }) sorry
@[simp] theorem coe_nat_add (n : β) {m : β} (i : fin m) : β(coe_fn (nat_add n) i) = n + βi :=
rfl
/-- If `e` is an `order_iso` between `fin n` and `fin m`, then `n = m` and `e` is the identity
map. In this lemma we state that for each `i : fin n` we have `(e i : β) = (i : β)`. -/
@[simp] theorem coe_order_iso_apply {n : β} {m : β} (e : fin n βo fin m) (i : fin n) : β(coe_fn e i) = βi := sorry
protected instance order_iso_subsingleton {n : β} {Ξ± : Type u_1} [preorder Ξ±] : subsingleton (fin n βo Ξ±) := sorry
protected instance order_iso_subsingleton' {n : β} {Ξ± : Type u_1} [preorder Ξ±] : subsingleton (Ξ± βo fin n) :=
function.injective.subsingleton order_iso.symm_injective
protected instance order_iso_unique {n : β} : unique (fin n βo fin n) :=
unique.mk' (fin n βo fin n)
/-- Two strictly monotone functions from `fin n` are equal provided that their ranges
are equal. -/
theorem strict_mono_unique {n : β} {Ξ± : Type u_1} [preorder Ξ±] {f : fin n β Ξ±} {g : fin n β Ξ±} (hf : strict_mono f) (hg : strict_mono g) (h : set.range f = set.range g) : f = g := sorry
/-- Two order embeddings of `fin n` are equal provided that their ranges are equal. -/
theorem order_embedding_eq {n : β} {Ξ± : Type u_1} [preorder Ξ±] {f : fin n βͺo Ξ±} {g : fin n βͺo Ξ±} (h : set.range βf = set.range βg) : f = g :=
rel_embedding.ext
(iff.mp function.funext_iff (strict_mono_unique (order_embedding.strict_mono f) (order_embedding.strict_mono g) h))
@[simp] theorem succ_last (n : β) : fin.succ (last n) = last (Nat.succ n) :=
rfl
@[simp] theorem cast_succ_cast_lt {n : β} (i : fin (n + 1)) (h : βi < n) : coe_fn cast_succ (cast_lt i h) = i :=
eq_of_veq rfl
@[simp] theorem cast_lt_cast_succ {n : β} (a : fin n) (h : βa < n) : cast_lt (coe_fn cast_succ a) h = a := sorry
theorem cast_succ_injective (n : β) : function.injective βcast_succ :=
rel_embedding.injective cast_succ
theorem cast_succ_inj {n : β} {a : fin n} {b : fin n} : coe_fn cast_succ a = coe_fn cast_succ b β a = b :=
function.injective.eq_iff (cast_succ_injective n)
theorem cast_succ_lt_last {n : β} (a : fin n) : coe_fn cast_succ a < last n :=
iff.mpr lt_iff_coe_lt_coe (is_lt a)
@[simp] theorem cast_succ_zero {n : β} : coe_fn cast_succ 0 = 0 :=
rfl
/-- `cast_succ i` is positive when `i` is positive -/
theorem cast_succ_pos {n : β} (i : fin (n + 1)) (h : 0 < i) : 0 < coe_fn cast_succ i := sorry
theorem last_pos {n : β} : 0 < last (n + 1) := sorry
theorem coe_nat_eq_last (n : β) : βn = last n := sorry
theorem le_coe_last {n : β} (i : fin (n + 1)) : i β€ βn :=
eq.mpr (id (Eq._oldrec (Eq.refl (i β€ βn)) (coe_nat_eq_last n))) (le_last i)
theorem eq_last_of_not_lt {n : β} {i : fin (n + 1)} (h : Β¬βi < n) : i = last n :=
le_antisymm (le_last i) (iff.mp not_lt h)
theorem add_one_pos {n : β} (i : fin (n + 1)) (h : i < last n) : 0 < i + 1 := sorry
theorem one_pos {n : β} : 0 < 1 :=
succ_pos 0
theorem zero_ne_one {n : β} : 0 β 1 :=
ne_of_lt one_pos
@[simp] theorem zero_eq_one_iff {n : β} : 0 = 1 β n = 0 :=
{ mp := nat.cases_on n (fun (h : 0 = 1) => Eq.refl 0) fun (n : β) (h : 0 = 1) => absurd h zero_ne_one,
mpr := fun (αΎ° : n = 0) => Eq._oldrec (Eq.refl 0) (Eq.symm αΎ°) }
@[simp] theorem one_eq_zero_iff {n : β} : 1 = 0 β n = 0 :=
eq.mpr (id (Eq._oldrec (Eq.refl (1 = 0 β n = 0)) (propext eq_comm)))
(eq.mpr (id (Eq._oldrec (Eq.refl (0 = 1 β n = 0)) (propext zero_eq_one_iff))) (iff.refl (n = 0)))
theorem cast_succ_fin_succ (n : β) (j : fin n) : coe_fn cast_succ (fin.succ j) = fin.succ (coe_fn cast_succ j) := sorry
@[simp] theorem coe_eq_cast_succ {n : β} {a : fin n} : βa = coe_fn cast_succ a :=
ext (coe_val_of_lt (nat.lt.step (is_lt a)))
@[simp] theorem coe_succ_eq_succ {n : β} {a : fin n} : coe_fn cast_succ a + 1 = fin.succ a := sorry
theorem lt_succ {n : β} {a : fin n} : coe_fn cast_succ a < fin.succ a := sorry
@[simp] theorem pred_one {n : β} : pred 1 (ne.symm (ne_of_lt one_pos)) = 0 :=
rfl
theorem pred_add_one {n : β} (i : fin (n + bit0 1)) (h : βi < n + 1) : pred (i + 1) (ne_of_gt (add_one_pos i (iff.mpr lt_iff_coe_lt_coe h))) = cast_lt i h := sorry
theorem nat_add_zero {n : β} : nat_add 0 = rel_iso.to_rel_embedding (cast (Eq.symm (zero_add n))) :=
rel_embedding.ext fun (x : fin n) => ext (zero_add βx)
/-- `min n m` as an element of `fin (m + 1)` -/
def clamp (n : β) (m : β) : fin (m + 1) :=
of_nat (min n m)
@[simp] theorem coe_clamp (n : β) (m : β) : β(clamp n m) = min n m :=
nat.mod_eq_of_lt (iff.mpr nat.lt_succ_iff (min_le_right n m))
/-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)`
embeds `i` by `cast_succ` when the resulting `i.cast_succ < p`. -/
theorem succ_above_below {n : β} (p : fin (n + 1)) (i : fin n) (h : coe_fn cast_succ i < p) : coe_fn (succ_above p) i = coe_fn cast_succ i :=
eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (succ_above p) i = coe_fn cast_succ i)) (succ_above.equations._eqn_1 p)))
(if_pos h)
/-- Embedding `fin n` into `fin (n + 1)` with a hole around zero embeds by `succ`. -/
@[simp] theorem succ_above_zero {n : β} : β(succ_above 0) = fin.succ :=
rfl
/-- Embedding `fin n` into `fin (n + 1)` with a hole around `last n` embeds by `cast_succ`. -/
@[simp] theorem succ_above_last {n : β} : succ_above (last n) = cast_succ := sorry
theorem succ_above_last_apply {n : β} (i : fin n) : coe_fn (succ_above (last n)) i = coe_fn cast_succ i :=
eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (succ_above (last n)) i = coe_fn cast_succ i)) succ_above_last))
(Eq.refl (coe_fn cast_succ i))
/-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)`
embeds `i` by `succ` when the resulting `p < i.succ`. -/
theorem succ_above_above {n : β} (p : fin (n + 1)) (i : fin n) (h : p β€ coe_fn cast_succ i) : coe_fn (succ_above p) i = fin.succ i := sorry
/-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/
theorem succ_above_lt_ge {n : β} (p : fin (n + 1)) (i : fin n) : coe_fn cast_succ i < p β¨ p β€ coe_fn cast_succ i :=
lt_or_ge (coe_fn cast_succ i) p
/-- Embedding `i : fin n` into `fin (n + 1)` is always about some hole `p`. -/
theorem succ_above_lt_gt {n : β} (p : fin (n + 1)) (i : fin n) : coe_fn cast_succ i < p β¨ p < fin.succ i :=
or.cases_on (succ_above_lt_ge p i) (fun (h : coe_fn cast_succ i < p) => Or.inl h)
fun (h : p β€ coe_fn cast_succ i) => Or.inr (lt_of_le_of_lt h (cast_succ_lt_succ i))
/-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is greater
results in a value that is less than `p`. -/
@[simp] theorem succ_above_lt_iff {n : β} (p : fin (n + 1)) (i : fin n) : coe_fn (succ_above p) i < p β coe_fn cast_succ i < p := sorry
/-- Embedding `i : fin n` into `fin (n + 1)` using a pivot `p` that is lesser
results in a value that is greater than `p`. -/
theorem lt_succ_above_iff {n : β} (p : fin (n + 1)) (i : fin n) : p < coe_fn (succ_above p) i β p β€ coe_fn cast_succ i := sorry
/-- Embedding `i : fin n` into `fin (n + 1)` with a hole around `p : fin (n + 1)`
never results in `p` itself -/
theorem succ_above_ne {n : β} (p : fin (n + 1)) (i : fin n) : coe_fn (succ_above p) i β p := sorry
/-- Embedding a positive `fin n` results in a positive fin (n + 1)` -/
theorem succ_above_pos {n : β} (p : fin (n + bit0 1)) (i : fin (n + 1)) (h : 0 < i) : 0 < coe_fn (succ_above p) i := sorry
/-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/
theorem succ_above_right_injective {n : β} {x : fin (n + 1)} : function.injective β(succ_above x) :=
rel_embedding.injective (succ_above x)
/-- Given a fixed pivot `x : fin (n + 1)`, `x.succ_above` is injective -/
theorem succ_above_right_inj {n : β} {a : fin n} {b : fin n} {x : fin (n + 1)} : coe_fn (succ_above x) a = coe_fn (succ_above x) b β a = b :=
function.injective.eq_iff succ_above_right_injective
/-- Embedding a `fin (n + 1)` into `fin n` and embedding it back around the same hole
gives the starting `fin (n + 1)` -/
@[simp] theorem succ_above_pred_above {n : β} (p : fin (n + 1)) (i : fin (n + 1)) (h : i β p) : coe_fn (succ_above p) (pred_above p i h) = i := sorry
/-- Embedding a `fin n` into `fin (n + 1)` and embedding it back around the same hole
gives the starting `fin n` -/
@[simp] theorem pred_above_succ_above {n : β} (p : fin (n + 1)) (i : fin n) : pred_above p (coe_fn (succ_above p) i) (succ_above_ne p i) = i := sorry
@[simp] theorem pred_above_zero {n : β} {i : fin (n + 1)} (hi : i β 0) : pred_above 0 i hi = pred i hi :=
rfl
theorem forall_iff_succ_above {n : β} {p : fin (n + 1) β Prop} (i : fin (n + 1)) : (β (j : fin (n + 1)), p j) β p i β§ β (j : fin n), p (coe_fn (succ_above i) j) := sorry
/-- `succ_above` is injective at the pivot -/
theorem succ_above_left_injective {n : β} : function.injective succ_above := sorry
/-- `succ_above` is injective at the pivot -/
theorem succ_above_left_inj {n : β} {x : fin (n + 1)} {y : fin (n + 1)} : succ_above x = succ_above y β x = y :=
function.injective.eq_iff succ_above_left_injective
/-- A function `f` on `fin n` is strictly monotone if and only if `f i < f (i+1)` for all `i`. -/
theorem strict_mono_iff_lt_succ {n : β} {Ξ± : Type u_1} [preorder Ξ±] {f : fin n β Ξ±} : strict_mono f β
β (i : β) (h : i + 1 < n),
f { val := i, property := lt_of_le_of_lt (nat.le_succ i) h } < f { val := i + 1, property := h } := sorry
/-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succβ¦`.
This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple,
and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element
of `n`-tuple. -/
def succ_rec {C : (n : β) β fin n β Sort u_1} (H0 : (n : β) β C (Nat.succ n) 0) (Hs : (n : β) β (i : fin n) β C n i β C (Nat.succ n) (fin.succ i)) {n : β} (i : fin n) : C n i :=
sorry
/-- Define `C n i` by induction on `i : fin n` interpreted as `(0 : fin (n - i)).succ.succβ¦`.
This function has two arguments: `H0 n` defines `0`-th element `C (n+1) 0` of an `(n+1)`-tuple,
and `Hs n i` defines `(i+1)`-st element of `(n+1)`-tuple based on `n`, `i`, and `i`-th element
of `n`-tuple.
A version of `fin.succ_rec` taking `i : fin n` as the first argument. -/
def succ_rec_on {n : β} (i : fin n) {C : (n : β) β fin n β Sort u_1} (H0 : (n : β) β C (Nat.succ n) 0) (Hs : (n : β) β (i : fin n) β C n i β C (Nat.succ n) (fin.succ i)) : C n i :=
succ_rec H0 Hs i
@[simp] theorem succ_rec_on_zero {C : (n : β) β fin n β Sort u_1} {H0 : (n : β) β C (Nat.succ n) 0} {Hs : (n : β) β (i : fin n) β C n i β C (Nat.succ n) (fin.succ i)} (n : β) : succ_rec_on 0 H0 Hs = H0 n :=
rfl
@[simp] theorem succ_rec_on_succ {C : (n : β) β fin n β Sort u_1} {H0 : (n : β) β C (Nat.succ n) 0} {Hs : (n : β) β (i : fin n) β C n i β C (Nat.succ n) (fin.succ i)} {n : β} (i : fin n) : succ_rec_on (fin.succ i) H0 Hs = Hs n i (succ_rec_on i H0 Hs) :=
subtype.cases_on i
fun (i_val : β) (i_property : i_val < n) =>
Eq.refl (succ_rec_on (fin.succ { val := i_val, property := i_property }) H0 Hs)
/--
Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value.
This function has two arguments: `h0` handles the base case on `C 0`,
and `hs` defines the inductive step using `C i.cast_succ`.
-/
def induction {n : β} {C : fin (n + 1) β Sort u_1} (h0 : C 0) (hs : (i : fin n) β C (coe_fn cast_succ i) β C (fin.succ i)) (i : fin (n + 1)) : C i :=
subtype.cases_on i
fun (i : β) (hi : i < n + 1) =>
Nat.rec (fun (hi : 0 < n + 1) => eq.mpr sorry h0)
(fun (i : β) (IH : (hi : i < n + 1) β C { val := i, property := hi }) (hi : Nat.succ i < n + 1) =>
hs { val := i, property := nat.lt_of_succ_lt_succ hi } (IH sorry))
i hi
/--
Define `C i` by induction on `i : fin (n + 1)` via induction on the underlying `nat` value.
This function has two arguments: `h0` handles the base case on `C 0`,
and `hs` defines the inductive step using `C i.cast_succ`.
A version of `fin.induction` taking `i : fin (n + 1)` as the first argument.
-/
def induction_on {n : β} (i : fin (n + 1)) {C : fin (n + 1) β Sort u_1} (h0 : C 0) (hs : (i : fin n) β C (coe_fn cast_succ i) β C (fin.succ i)) : C i :=
induction h0 hs i
/-- Define `f : Ξ i : fin n.succ, C i` by separately handling the cases `i = 0` and
`i = j.succ`, `j : fin n`. -/
def cases {n : β} {C : fin (Nat.succ n) β Sort u_1} (H0 : C 0) (Hs : (i : fin n) β C (fin.succ i)) (i : fin (Nat.succ n)) : C i :=
induction H0 fun (i : fin n) (_x : C (coe_fn cast_succ i)) => Hs i
@[simp] theorem cases_zero {n : β} {C : fin (Nat.succ n) β Sort u_1} {H0 : C 0} {Hs : (i : fin n) β C (fin.succ i)} : cases H0 Hs 0 = H0 :=
rfl
@[simp] theorem cases_succ {n : β} {C : fin (Nat.succ n) β Sort u_1} {H0 : C 0} {Hs : (i : fin n) β C (fin.succ i)} (i : fin n) : cases H0 Hs (fin.succ i) = Hs i :=
subtype.cases_on i
fun (i_val : β) (i_property : i_val < n) => Eq.refl (cases H0 Hs (fin.succ { val := i_val, property := i_property }))
@[simp] theorem cases_succ' {n : β} {C : fin (Nat.succ n) β Sort u_1} {H0 : C 0} {Hs : (i : fin n) β C (fin.succ i)} {i : β} (h : i + 1 < n + 1) : cases H0 Hs { val := Nat.succ i, property := h } = Hs { val := i, property := nat.lt_of_succ_lt_succ h } :=
nat.cases_on i (fun (h : 0 + 1 < n + 1) => Eq.refl (cases H0 Hs { val := 1, property := h }))
(fun (i : β) (h : Nat.succ i + 1 < n + 1) => Eq.refl (cases H0 Hs { val := Nat.succ (Nat.succ i), property := h })) h
theorem forall_fin_succ {n : β} {P : fin (n + 1) β Prop} : (β (i : fin (n + 1)), P i) β P 0 β§ β (i : fin n), P (fin.succ i) := sorry
theorem exists_fin_succ {n : β} {P : fin (n + 1) β Prop} : (β (i : fin (n + 1)), P i) β P 0 β¨ β (i : fin n), P (fin.succ i) := sorry
/-!
### Tuples
We can think of the type `Ξ (i : fin n), Ξ± i` as `n`-tuples of elements of possibly varying type
`Ξ± i`. A particular case is `fin n β Ξ±` of elements with all the same type. Here are some relevant
operations, first about adding or removing elements at the beginning of a tuple.
-/
/-- There is exactly one tuple of size zero. -/
protected instance tuple0_unique (Ξ± : fin 0 β Type u) : unique ((i : fin 0) β Ξ± i) :=
unique.mk { default := fin_zero_elim } sorry
@[simp] theorem tuple0_le {Ξ± : fin 0 β Type u_1} [(i : fin 0) β preorder (Ξ± i)] (f : (i : fin 0) β Ξ± i) (g : (i : fin 0) β Ξ± i) : f β€ g :=
fin_zero_elim
/-- The tail of an `n+1` tuple, i.e., its last `n` entries. -/
def tail {n : β} {Ξ± : fin (n + 1) β Type u} (q : (i : fin (n + 1)) β Ξ± i) (i : fin n) : Ξ± (fin.succ i) :=
q (fin.succ i)
/-- Adding an element at the beginning of an `n`-tuple, to get an `n+1`-tuple. -/
def cons {n : β} {Ξ± : fin (n + 1) β Type u} (x : Ξ± 0) (p : (i : fin n) β Ξ± (fin.succ i)) (i : fin (n + 1)) : Ξ± i :=
cases x p j
@[simp] theorem tail_cons {n : β} {Ξ± : fin (n + 1) β Type u} (x : Ξ± 0) (p : (i : fin n) β Ξ± (fin.succ i)) : tail (cons x p) = p := sorry
@[simp] theorem cons_succ {n : β} {Ξ± : fin (n + 1) β Type u} (x : Ξ± 0) (p : (i : fin n) β Ξ± (fin.succ i)) (i : fin n) : cons x p (fin.succ i) = p i := sorry
@[simp] theorem cons_zero {n : β} {Ξ± : fin (n + 1) β Type u} (x : Ξ± 0) (p : (i : fin n) β Ξ± (fin.succ i)) : cons x p 0 = x := sorry
/-- Updating a tuple and adding an element at the beginning commute. -/
@[simp] theorem cons_update {n : β} {Ξ± : fin (n + 1) β Type u} (x : Ξ± 0) (p : (i : fin n) β Ξ± (fin.succ i)) (i : fin n) (y : Ξ± (fin.succ i)) : cons x (function.update p i y) = function.update (cons x p) (fin.succ i) y := sorry
/-- Adding an element at the beginning of a tuple and then updating it amounts to adding it
directly. -/
theorem update_cons_zero {n : β} {Ξ± : fin (n + 1) β Type u} (x : Ξ± 0) (p : (i : fin n) β Ξ± (fin.succ i)) (z : Ξ± 0) : function.update (cons x p) 0 z = cons z p := sorry
/-- Concatenating the first element of a tuple with its tail gives back the original tuple -/
@[simp] theorem cons_self_tail {n : β} {Ξ± : fin (n + 1) β Type u} (q : (i : fin (n + 1)) β Ξ± i) : cons (q 0) (tail q) = q := sorry
/-- Updating the first element of a tuple does not change the tail. -/
@[simp] theorem tail_update_zero {n : β} {Ξ± : fin (n + 1) β Type u} (q : (i : fin (n + 1)) β Ξ± i) (z : Ξ± 0) : tail (function.update q 0 z) = tail q := sorry
/-- Updating a nonzero element and taking the tail commute. -/
@[simp] theorem tail_update_succ {n : β} {Ξ± : fin (n + 1) β Type u} (q : (i : fin (n + 1)) β Ξ± i) (i : fin n) (y : Ξ± (fin.succ i)) : tail (function.update q (fin.succ i) y) = function.update (tail q) i y := sorry
theorem comp_cons {n : β} {Ξ± : Type u_1} {Ξ² : Type u_2} (g : Ξ± β Ξ²) (y : Ξ±) (q : fin n β Ξ±) : g β cons y q = cons (g y) (g β q) := sorry
theorem comp_tail {n : β} {Ξ± : Type u_1} {Ξ² : Type u_2} (g : Ξ± β Ξ²) (q : fin (Nat.succ n) β Ξ±) : g β tail q = tail (g β q) := sorry
theorem le_cons {n : β} {Ξ± : fin (n + 1) β Type u} [(i : fin (n + 1)) β preorder (Ξ± i)] {x : Ξ± 0} {q : (i : fin (n + 1)) β Ξ± i} {p : (i : fin n) β Ξ± (fin.succ i)} : q β€ cons x p β q 0 β€ x β§ tail q β€ p := sorry
theorem cons_le {n : β} {Ξ± : fin (n + 1) β Type u} [(i : fin (n + 1)) β preorder (Ξ± i)] {x : Ξ± 0} {q : (i : fin (n + 1)) β Ξ± i} {p : (i : fin n) β Ξ± (fin.succ i)} : cons x p β€ q β x β€ q 0 β§ p β€ tail q :=
le_cons
/-- `fin.append ho u v` appends two vectors of lengths `m` and `n` to produce
one of length `o = m + n`. `ho` provides control of definitional equality
for the vector length. -/
def append {n : β} {m : β} {Ξ± : Type u_1} {o : β} (ho : o = m + n) (u : fin m β Ξ±) (v : fin n β Ξ±) : fin o β Ξ± :=
fun (i : fin o) =>
dite (βi < m) (fun (h : βi < m) => u { val := βi, property := h })
fun (h : Β¬βi < m) => v { val := βi - m, property := sorry }
@[simp] theorem fin_append_apply_zero {n : β} {m : β} {Ξ± : Type u_1} {o : β} (ho : o + 1 = m + 1 + n) (u : fin (m + 1) β Ξ±) (v : fin n β Ξ±) : append ho u v 0 = u 0 :=
rfl
/-! In the previous section, we have discussed inserting or removing elements on the left of a
tuple. In this section, we do the same on the right. A difference is that `fin (n+1)` is constructed
inductively from `fin n` starting from the left, not from the right. This implies that Lean needs
more help to realize that elements belong to the right types, i.e., we need to insert casts at
several places. -/
/-- The beginning of an `n+1` tuple, i.e., its first `n` entries -/
def init {n : β} {Ξ± : fin (n + 1) β Type u} (q : (i : fin (n + 1)) β Ξ± i) (i : fin n) : Ξ± (coe_fn cast_succ i) :=
q (coe_fn cast_succ i)
/-- Adding an element at the end of an `n`-tuple, to get an `n+1`-tuple. The name `snoc` comes from
`cons` (i.e., adding an element to the left of a tuple) read in reverse order. -/
def snoc {n : β} {Ξ± : fin (n + 1) β Type u} (p : (i : fin n) β Ξ± (coe_fn cast_succ i)) (x : Ξ± (last n)) (i : fin (n + 1)) : Ξ± i :=
dite (subtype.val i < n) (fun (h : subtype.val i < n) => cast sorry (p (cast_lt i h)))
fun (h : Β¬subtype.val i < n) => cast sorry x
@[simp] theorem init_snoc {n : β} {Ξ± : fin (n + 1) β Type u} (x : Ξ± (last n)) (p : (i : fin n) β Ξ± (coe_fn cast_succ i)) : init (snoc p x) = p := sorry
@[simp] theorem snoc_cast_succ {n : β} {Ξ± : fin (n + 1) β Type u} (x : Ξ± (last n)) (p : (i : fin n) β Ξ± (coe_fn cast_succ i)) (i : fin n) : snoc p x (coe_fn cast_succ i) = p i := sorry
@[simp] theorem snoc_last {n : β} {Ξ± : fin (n + 1) β Type u} (x : Ξ± (last n)) (p : (i : fin n) β Ξ± (coe_fn cast_succ i)) : snoc p x (last n) = x := sorry
/-- Updating a tuple and adding an element at the end commute. -/
@[simp] theorem snoc_update {n : β} {Ξ± : fin (n + 1) β Type u} (x : Ξ± (last n)) (p : (i : fin n) β Ξ± (coe_fn cast_succ i)) (i : fin n) (y : Ξ± (coe_fn cast_succ i)) : snoc (function.update p i y) x = function.update (snoc p x) (coe_fn cast_succ i) y := sorry
/-- Adding an element at the beginning of a tuple and then updating it amounts to adding it
directly. -/
theorem update_snoc_last {n : β} {Ξ± : fin (n + 1) β Type u} (x : Ξ± (last n)) (p : (i : fin n) β Ξ± (coe_fn cast_succ i)) (z : Ξ± (last n)) : function.update (snoc p x) (last n) z = snoc p z := sorry
/-- Concatenating the first element of a tuple with its tail gives back the original tuple -/
@[simp] theorem snoc_init_self {n : β} {Ξ± : fin (n + 1) β Type u} (q : (i : fin (n + 1)) β Ξ± i) : snoc (init q) (q (last n)) = q := sorry
/-- Updating the last element of a tuple does not change the beginning. -/
@[simp] theorem init_update_last {n : β} {Ξ± : fin (n + 1) β Type u} (q : (i : fin (n + 1)) β Ξ± i) (z : Ξ± (last n)) : init (function.update q (last n) z) = init q := sorry
/-- Updating an element and taking the beginning commute. -/
@[simp] theorem init_update_cast_succ {n : β} {Ξ± : fin (n + 1) β Type u} (q : (i : fin (n + 1)) β Ξ± i) (i : fin n) (y : Ξ± (coe_fn cast_succ i)) : init (function.update q (coe_fn cast_succ i) y) = function.update (init q) i y := sorry
/-- `tail` and `init` commute. We state this lemma in a non-dependent setting, as otherwise it
would involve a cast to convince Lean that the two types are equal, making it harder to use. -/
theorem tail_init_eq_init_tail {n : β} {Ξ² : Type u_1} (q : fin (n + bit0 1) β Ξ²) : tail (init q) = init (tail q) := sorry
/-- `cons` and `snoc` commute. We state this lemma in a non-dependent setting, as otherwise it
would involve a cast to convince Lean that the two types are equal, making it harder to use. -/
theorem cons_snoc_eq_snoc_cons {n : β} {Ξ² : Type u_1} (a : Ξ²) (q : fin n β Ξ²) (b : Ξ²) : cons a (snoc q b) = snoc (cons a q) b := sorry
theorem comp_snoc {n : β} {Ξ± : Type u_1} {Ξ² : Type u_2} (g : Ξ± β Ξ²) (q : fin n β Ξ±) (y : Ξ±) : g β snoc q y = snoc (g β q) (g y) := sorry
theorem comp_init {n : β} {Ξ± : Type u_1} {Ξ² : Type u_2} (g : Ξ± β Ξ²) (q : fin (Nat.succ n) β Ξ±) : g β init q = init (g β q) := sorry
/-- Insert an element into a tuple at a given position. For `i = 0` see `fin.cons`,
for `i = fin.last n` see `fin.snoc`. -/
def insert_nth {n : β} {Ξ± : fin (n + 1) β Type u} (i : fin (n + 1)) (x : Ξ± i) (p : (j : fin n) β Ξ± (coe_fn (succ_above i) j)) (j : fin (n + 1)) : Ξ± j :=
dite (j = i) (fun (h : j = i) => cast sorry x) fun (h : Β¬j = i) => cast sorry (p (pred_above i j h))
@[simp] theorem insert_nth_apply_same {n : β} {Ξ± : fin (n + 1) β Type u} (i : fin (n + 1)) (x : Ξ± i) (p : (j : fin n) β Ξ± (coe_fn (succ_above i) j)) : insert_nth i x p i = x := sorry
@[simp] theorem insert_nth_apply_succ_above {n : β} {Ξ± : fin (n + 1) β Type u} (i : fin (n + 1)) (x : Ξ± i) (p : (j : fin n) β Ξ± (coe_fn (succ_above i) j)) (j : fin n) : insert_nth i x p (coe_fn (succ_above i) j) = p j := sorry
@[simp] theorem insert_nth_comp_succ_above {n : β} {Ξ² : Type v} (i : fin (n + 1)) (x : Ξ²) (p : fin n β Ξ²) : insert_nth i x p β β(succ_above i) = p :=
funext (insert_nth_apply_succ_above i x p)
theorem insert_nth_eq_iff {n : β} {Ξ± : fin (n + 1) β Type u} {i : fin (n + 1)} {x : Ξ± i} {p : (j : fin n) β Ξ± (coe_fn (succ_above i) j)} {q : (j : fin (n + 1)) β Ξ± j} : insert_nth i x p = q β q i = x β§ p = fun (j : fin n) => q (coe_fn (succ_above i) j) := sorry
theorem eq_insert_nth_iff {n : β} {Ξ± : fin (n + 1) β Type u} {i : fin (n + 1)} {x : Ξ± i} {p : (j : fin n) β Ξ± (coe_fn (succ_above i) j)} {q : (j : fin (n + 1)) β Ξ± j} : q = insert_nth i x p β q i = x β§ p = fun (j : fin n) => q (coe_fn (succ_above i) j) :=
iff.trans eq_comm insert_nth_eq_iff
theorem insert_nth_zero {n : β} {Ξ± : fin (n + 1) β Type u} (x : Ξ± 0) (p : (j : fin n) β Ξ± (coe_fn (succ_above 0) j)) : insert_nth 0 x p = cons x fun (j : fin n) => cast (congr_arg Ξ± (congr_fun succ_above_zero j)) (p j) := sorry
@[simp] theorem insert_nth_zero' {n : β} {Ξ² : Type v} (x : Ξ²) (p : fin n β Ξ²) : insert_nth 0 x p = cons x p := sorry
theorem insert_nth_last {n : β} {Ξ± : fin (n + 1) β Type u} (x : Ξ± (last n)) (p : (j : fin n) β Ξ± (coe_fn (succ_above (last n)) j)) : insert_nth (last n) x p = snoc (fun (j : fin n) => cast (congr_arg Ξ± (succ_above_last_apply j)) (p j)) x := sorry
@[simp] theorem insert_nth_last' {n : β} {Ξ² : Type v} (x : Ξ²) (p : fin n β Ξ²) : insert_nth (last n) x p = snoc p x := sorry
theorem insert_nth_le_iff {n : β} {Ξ± : fin (n + 1) β Type u} [(i : fin (n + 1)) β preorder (Ξ± i)] {i : fin (n + 1)} {x : Ξ± i} {p : (j : fin n) β Ξ± (coe_fn (succ_above i) j)} {q : (j : fin (n + 1)) β Ξ± j} : insert_nth i x p β€ q β x β€ q i β§ p β€ fun (j : fin n) => q (coe_fn (succ_above i) j) := sorry
theorem le_insert_nth_iff {n : β} {Ξ± : fin (n + 1) β Type u} [(i : fin (n + 1)) β preorder (Ξ± i)] {i : fin (n + 1)} {x : Ξ± i} {p : (j : fin n) β Ξ± (coe_fn (succ_above i) j)} {q : (j : fin (n + 1)) β Ξ± j} : q β€ insert_nth i x p β q i β€ x β§ (fun (j : fin n) => q (coe_fn (succ_above i) j)) β€ p := sorry
theorem insert_nth_mem_Icc {n : β} {Ξ± : fin (n + 1) β Type u} [(i : fin (n + 1)) β preorder (Ξ± i)] {i : fin (n + 1)} {x : Ξ± i} {p : (j : fin n) β Ξ± (coe_fn (succ_above i) j)} {qβ : (j : fin (n + 1)) β Ξ± j} {qβ : (j : fin (n + 1)) β Ξ± j} : insert_nth i x p β set.Icc qβ qβ β
x β set.Icc (qβ i) (qβ i) β§
p β set.Icc (fun (j : fin n) => qβ (coe_fn (succ_above i) j)) fun (j : fin n) => qβ (coe_fn (succ_above i) j) := sorry
theorem preimage_insert_nth_Icc_of_mem {n : β} {Ξ± : fin (n + 1) β Type u} [(i : fin (n + 1)) β preorder (Ξ± i)] {i : fin (n + 1)} {x : Ξ± i} {qβ : (j : fin (n + 1)) β Ξ± j} {qβ : (j : fin (n + 1)) β Ξ± j} (hx : x β set.Icc (qβ i) (qβ i)) : insert_nth i x β»ΒΉ' set.Icc qβ qβ =
set.Icc (fun (j : fin n) => qβ (coe_fn (succ_above i) j)) fun (j : fin n) => qβ (coe_fn (succ_above i) j) := sorry
theorem preimage_insert_nth_Icc_of_not_mem {n : β} {Ξ± : fin (n + 1) β Type u} [(i : fin (n + 1)) β preorder (Ξ± i)] {i : fin (n + 1)} {x : Ξ± i} {qβ : (j : fin (n + 1)) β Ξ± j} {qβ : (j : fin (n + 1)) β Ξ± j} (hx : Β¬x β set.Icc (qβ i) (qβ i)) : insert_nth i x β»ΒΉ' set.Icc qβ qβ = β
:= sorry
/-- `find p` returns the first index `n` where `p n` is satisfied, and `none` if it is never
satisfied. -/
def find {n : β} (p : fin n β Prop) [decidable_pred p] : Option (fin n) :=
sorry
/-- If `find p = some i`, then `p i` holds -/
theorem find_spec {n : β} (p : fin n β Prop) [decidable_pred p] {i : fin n} (hi : i β find p) : p i := sorry
/-- `find p` does not return `none` if and only if `p i` holds at some index `i`. -/
theorem is_some_find_iff {n : β} {p : fin n β Prop} [decidable_pred p] : β₯(option.is_some (find p)) β β (i : fin n), p i := sorry
/-- `find p` returns `none` if and only if `p i` never holds. -/
theorem find_eq_none_iff {n : β} {p : fin n β Prop} [decidable_pred p] : find p = none β β (i : fin n), Β¬p i := sorry
/-- If `find p` returns `some i`, then `p j` does not hold for `j < i`, i.e., `i` is minimal among
the indices where `p` holds. -/
theorem find_min {n : β} {p : fin n β Prop} [decidable_pred p] {i : fin n} (hi : i β find p) {j : fin n} (hj : j < i) : Β¬p j := sorry
theorem find_min' {n : β} {p : fin n β Prop} [decidable_pred p] {i : fin n} (h : i β find p) {j : fin n} (hj : p j) : i β€ j :=
le_of_not_gt fun (hij : i > j) => find_min h hij hj
theorem nat_find_mem_find {n : β} {p : fin n β Prop} [decidable_pred p] (h : β (i : β), β (hin : i < n), p { val := i, property := hin }) : { val := nat.find h, property := Exists.fst (nat.find_spec h) } β find p := sorry
theorem mem_find_iff {n : β} {p : fin n β Prop} [decidable_pred p] {i : fin n} : i β find p β p i β§ β (j : fin n), p j β i β€ j := sorry
theorem find_eq_some_iff {n : β} {p : fin n β Prop} [decidable_pred p] {i : fin n} : find p = some i β p i β§ β (j : fin n), p j β i β€ j :=
mem_find_iff
theorem mem_find_of_unique {n : β} {p : fin n β Prop} [decidable_pred p] (h : β (i j : fin n), p i β p j β i = j) {i : fin n} (hi : p i) : i β find p :=
iff.mpr mem_find_iff { left := hi, right := fun (j : fin n) (hj : p j) => le_of_eq (h i j hi hj) }
@[simp] theorem coe_of_nat_eq_mod (m : β) (n : β) : ββn = n % Nat.succ m :=
eq.mpr (id (Eq._oldrec (Eq.refl (ββn = n % Nat.succ m)) (Eq.symm (of_nat_eq_coe m n)))) (Eq.refl β(of_nat n))
@[simp] theorem coe_of_nat_eq_mod' (m : β) (n : β) [I : fact (0 < m)] : β(of_nat' n) = n % m :=
rfl
@[simp] protected theorem add_zero {n : β} (k : fin (n + 1)) : k + 0 = k := sorry
@[simp] protected theorem zero_add {n : β} (k : fin (n + 1)) : 0 + k = k := sorry
@[simp] protected theorem mul_one {n : β} (k : fin (n + 1)) : k * 1 = k := sorry
@[simp] protected theorem one_mul {n : β} (k : fin (n + 1)) : 1 * k = k := sorry
@[simp] protected theorem mul_zero {n : β} (k : fin (n + 1)) : k * 0 = 0 := sorry
@[simp] protected theorem zero_mul {n : β} (k : fin (n + 1)) : 0 * k = 0 := sorry
protected instance add_comm_monoid (n : β) : add_comm_monoid (fin (n + 1)) :=
add_comm_monoid.mk Add.add sorry 0 fin.zero_add fin.add_zero sorry
|
22f3112e66c0f2f4a829859a10b2621baca14049 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/tactic_error_pos.lean | ffbd369c65678bea8204fa300cf121b6e77f1980 | [
"Apache-2.0"
] | permissive | leanprover-community/lean | 12b87f69d92e614daea8bcc9d4de9a9ace089d0e | cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0 | refs/heads/master | 1,687,508,156,644 | 1,684,951,104,000 | 1,684,951,104,000 | 169,960,991 | 457 | 107 | Apache-2.0 | 1,686,744,372,000 | 1,549,790,268,000 | C++ | UTF-8 | Lean | false | false | 1,145 | lean | example (p q : Prop) (h1 : p) (h2 : q) : p β§ q :=
begin
exact (or.inl _)
--^ type mismatch here (OK)
end
example (p q : Prop) (h1 : p) (h2 : q) : p β§ q :=
begin
exact (and.intro _ h2)
--^ don't know how to synthesize placeholder here (OK)
end
example (p q : Prop) (h1 : p) (h2 : q) : p β§ q :=
begin
abstract {exact (and.intro _ h2)}
--^ don't know how to synthesize placeholder here (OK)
end
example (p q : Prop) (h1 : p) (h2 : q) : p β§ q :=
begin
{exact (and.intro _ h2) } <|> apply and.intro
--^ should not show error here (BUG)
end
example (p q : Prop) (h1 : p) (h2 : q) : p β§ q :=
begin
try {exact (and.intro _ h2) }
--^ should not show error here (BUG)
end
example (p q : Prop) (h1 : p) (h2 : q) : p β§ q :=
begin
repeat {exact (and.intro _ h2) }
--^ should not show error here (BUG)
end
open tactic
meta def mytac : tactic unit :=
`[apply (or.inl _)]
example (p q : Prop) (h1 : p) (h2 : q) : p β§ q :=
begin
mytac
--^ failed to unify error here, it shoult *not* be at mytac or.inl (OK)
end
|
493361e105b7401cb61729979a9b1329c9331f8f | b2fe74b11b57d362c13326bc5651244f111fa6f4 | /src/algebra/category/Group/limits.lean | 23d70ed325335d61871db608f5e7ca1eaaf2c4dc | [
"Apache-2.0"
] | permissive | midfield/mathlib | c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7 | 775edc615ecec631d65b6180dbcc7bc26c3abc26 | refs/heads/master | 1,675,330,551,921 | 1,608,304,514,000 | 1,608,304,514,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,772 | 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.category.Mon.limits
import algebra.category.Group.preadditive
import category_theory.over
import category_theory.limits.concrete_category
import category_theory.limits.shapes.concrete_category
import group_theory.subgroup
/-!
# The category of (commutative) (additive) groups has all limits
Further, these limits are preserved by the forgetful functor --- that is,
the underlying types are just the limits in the category of types.
-/
open category_theory
open category_theory.limits
universe u
noncomputable theory
variables {J : Type u} [small_category J]
namespace Group
@[to_additive]
instance group_obj (F : J β₯€ Group) (j) :
group ((F β forget Group).obj j) :=
by { change group (F.obj j), apply_instance }
/--
The flat sections of a functor into `Group` form a subgroup of all sections.
-/
@[to_additive
"The flat sections of a functor into `AddGroup` form an additive subgroup of all sections."]
def sections_subgroup (F : J β₯€ Group) :
subgroup (Ξ j, F.obj j) :=
{ carrier := (F β forget Group).sections,
inv_mem' := Ξ» a ah j j' f,
begin
simp only [forget_map_eq_coe, functor.comp_map, pi.inv_apply, monoid_hom.map_inv, inv_inj],
dsimp [functor.sections] at ah,
rw ah f,
end,
..(Mon.sections_submonoid (F β forgetβ Group Mon)) }
@[to_additive]
instance limit_group (F : J β₯€ Group) :
group (types.limit_cone (F β forget Group.{u})).X :=
begin
change group (sections_subgroup F),
apply_instance,
end
/--
We show that the forgetful functor `Group β₯€ Mon` creates limits.
All we need to do is notice that the limit point has a `group` instance available,
and then reuse the existing limit.
-/
@[to_additive]
instance (F : J β₯€ Group) : creates_limit F (forgetβ Group Mon.{u}) :=
creates_limit_of_reflects_iso (Ξ» c' t,
{ lifted_cone :=
{ X := Group.of (types.limit_cone (F β forget Group)).X,
Ο :=
{ app := Mon.limit_Ο_monoid_hom (F β forgetβ Group Mon.{u}),
naturality' := (Mon.has_limits.limit_cone (F β forgetβ _ _)).Ο.naturality, } },
valid_lift := is_limit.unique_up_to_iso (Mon.has_limits.limit_cone_is_limit _) t,
makes_limit := is_limit.of_faithful (forgetβ Group Mon.{u}) (Mon.has_limits.limit_cone_is_limit _)
(Ξ» s, _) (Ξ» s, rfl) })
/--
A choice of limit cone for a functor into `Group`.
(Generally, you'll just want to use `limit F`.)
-/
@[to_additive "A choice of limit cone for a functor into `Group`. (Generally, you'll just want to use `limit F`.)"]
def limit_cone (F : J β₯€ Group) : cone F :=
lift_limit (limit.is_limit (F β (forgetβ Group Mon.{u})))
/--
The chosen cone is a limit cone.
(Generally, you'll just want to use `limit.cone F`.)
-/
@[to_additive "The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.)"]
def limit_cone_is_limit (F : J β₯€ Group) : is_limit (limit_cone F) :=
lifted_limit_is_limit _
/-- The category of groups has all limits. -/
@[to_additive]
instance has_limits : has_limits Group :=
{ has_limits_of_shape := Ξ» J π₯, by exactI
{ has_limit := Ξ» F, has_limit_of_created F (forgetβ Group Mon) } } -- TODO use the above instead?
/--
The forgetful functor from groups to monoids preserves all limits.
(That is, the underlying monoid could have been computed instead as limits in the category of monoids.)
-/
@[to_additive AddGroup.forgetβ_AddMon_preserves_limits]
instance forgetβ_Mon_preserves_limits : preserves_limits (forgetβ Group Mon) :=
{ preserves_limits_of_shape := Ξ» J π₯,
{ preserves_limit := Ξ» F, by apply_instance } }
/--
The forgetful functor from groups to types preserves all limits. (That is, the underlying
types could have been computed instead as limits in the category of types.)
-/
@[to_additive]
instance forget_preserves_limits : preserves_limits (forget Group) :=
{ preserves_limits_of_shape := Ξ» J π₯, by exactI
{ preserves_limit := Ξ» F, limits.comp_preserves_limit (forgetβ Group Mon) (forget Mon) } }
end Group
namespace CommGroup
@[to_additive]
instance comm_group_obj (F : J β₯€ CommGroup) (j) :
comm_group ((F β forget CommGroup).obj j) :=
by { change comm_group (F.obj j), apply_instance }
@[to_additive]
instance limit_comm_group (F : J β₯€ CommGroup) :
comm_group (types.limit_cone (F β forget CommGroup.{u})).X :=
@subgroup.to_comm_group (Ξ j, F.obj j) _
(Group.sections_subgroup (F β forgetβ CommGroup Group.{u}))
/--
We show that the forgetful functor `CommGroup β₯€ Group` creates limits.
All we need to do is notice that the limit point has a `comm_group` instance available,
and then reuse the existing limit.
-/
@[to_additive]
instance (F : J β₯€ CommGroup) : creates_limit F (forgetβ CommGroup Group.{u}) :=
creates_limit_of_reflects_iso (Ξ» c' t,
{ lifted_cone :=
{ X := CommGroup.of (types.limit_cone (F β forget CommGroup)).X,
Ο :=
{ app := Mon.limit_Ο_monoid_hom (F β forgetβ CommGroup Group.{u} β forgetβ Group Mon),
naturality' := (Mon.has_limits.limit_cone _).Ο.naturality, } },
valid_lift := is_limit.unique_up_to_iso (Group.limit_cone_is_limit _) t,
makes_limit := is_limit.of_faithful (forgetβ _ Group.{u} β forgetβ _ Mon.{u}) (Mon.has_limits.limit_cone_is_limit _)
(Ξ» s, _) (Ξ» s, rfl) })
/--
A choice of limit cone for a functor into `CommGroup`.
(Generally, you'll just want to use `limit F`.)
-/
@[to_additive "A choice of limit cone for a functor into `CommGroup`. (Generally, you'll just want to use `limit F`.)"]
def limit_cone (F : J β₯€ CommGroup) : cone F :=
lift_limit (limit.is_limit (F β (forgetβ CommGroup Group.{u})))
/--
The chosen cone is a limit cone.
(Generally, you'll just want to use `limit.cone F`.)
-/
@[to_additive "The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.)"]
def limit_cone_is_limit (F : J β₯€ CommGroup) : is_limit (limit_cone F) :=
lifted_limit_is_limit _
/-- The category of commutative groups has all limits. -/
@[to_additive]
instance has_limits : has_limits CommGroup :=
{ has_limits_of_shape := Ξ» J π₯, by exactI
{ has_limit := Ξ» F, has_limit_of_created F (forgetβ CommGroup Group) } }
/--
The forgetful functor from commutative groups to groups preserves all limits.
(That is, the underlying group could have been computed instead as limits in the category of groups.)
-/
@[to_additive AddCommGroup.forgetβ_AddGroup_preserves_limits]
instance forgetβ_Group_preserves_limits : preserves_limits (forgetβ CommGroup Group) :=
{ preserves_limits_of_shape := Ξ» J π₯,
{ preserves_limit := Ξ» F, by apply_instance } }
/--
An auxiliary declaration to speed up typechecking.
-/
@[to_additive AddCommGroup.forgetβ_AddCommMon_preserves_limits_aux
"An auxiliary declaration to speed up typechecking."]
def forgetβ_CommMon_preserves_limits_aux (F : J β₯€ CommGroup) :
is_limit ((forgetβ CommGroup CommMon).map_cone (limit_cone F)) :=
CommMon.limit_cone_is_limit (F β forgetβ CommGroup CommMon)
/--
The forgetful functor from commutative groups to commutative monoids preserves all limits.
(That is, the underlying commutative monoids could have been computed instead as limits
in the category of commutative monoids.)
-/
@[to_additive AddCommGroup.forgetβ_AddCommMon_preserves_limits]
instance forgetβ_CommMon_preserves_limits : preserves_limits (forgetβ CommGroup CommMon) :=
{ preserves_limits_of_shape := Ξ» J π₯, by exactI
{ preserves_limit := Ξ» F, preserves_limit_of_preserves_limit_cone
(limit_cone_is_limit F) (forgetβ_CommMon_preserves_limits_aux F) } }
/--
The forgetful functor from commutative groups to types preserves all limits. (That is, the underlying
types could have been computed instead as limits in the category of types.)
-/
@[to_additive AddCommGroup.forget_preserves_limits]
instance forget_preserves_limits : preserves_limits (forget CommGroup) :=
{ preserves_limits_of_shape := Ξ» J π₯, by exactI
{ preserves_limit := Ξ» F, limits.comp_preserves_limit (forgetβ CommGroup Group) (forget Group) } }
end CommGroup
namespace AddCommGroup
/--
The categorical kernel of a morphism in `AddCommGroup`
agrees with the usual group-theoretical kernel.
-/
def kernel_iso_ker {G H : AddCommGroup} (f : G βΆ H) :
kernel f β
AddCommGroup.of f.ker :=
{ hom :=
{ to_fun := Ξ» g, β¨kernel.ΞΉ f g,
begin
-- TODO where is this `has_coe_t_aux.coe` coming from? can we prevent it appearing?
change (kernel.ΞΉ f) g β f.ker,
simp [add_monoid_hom.mem_ker],
endβ©,
map_zero' := by { ext, simp, },
map_add' := Ξ» g g', by { ext, simp, }, },
inv := kernel.lift f (add_subgroup.subtype f.ker) (by tidy),
hom_inv_id' := by { apply equalizer.hom_ext _, ext, simp, },
inv_hom_id' :=
begin
apply AddCommGroup.ext,
simp only [add_monoid_hom.coe_mk, coe_id, coe_comp],
rintro β¨x, memβ©,
simp,
end, }.
@[simp]
lemma kernel_iso_ker_hom_comp_subtype {G H : AddCommGroup} (f : G βΆ H) :
(kernel_iso_ker f).hom β« add_subgroup.subtype f.ker = kernel.ΞΉ f :=
begin
ext,
simp [kernel_iso_ker],
end
@[simp]
lemma kernel_iso_ker_inv_comp_ΞΉ {G H : AddCommGroup} (f : G βΆ H) :
(kernel_iso_ker f).inv β« kernel.ΞΉ f = add_subgroup.subtype f.ker :=
begin
ext,
simp [kernel_iso_ker],
end
/--
The categorical kernel inclusion for `f : G βΆ H`, as an object over `G`,
agrees with the `subtype` map.
-/
@[simps {rhs_md:=semireducible}]
def kernel_iso_ker_over {G H : AddCommGroup.{u}} (f : G βΆ H) :
over.mk (kernel.ΞΉ f) β
@over.mk _ _ G (AddCommGroup.of f.ker) (add_subgroup.subtype f.ker) :=
over.iso_mk (kernel_iso_ker f) (by simp)
end AddCommGroup
|
7b400899f3b37eb9ffab1ab33917c2f014ca5365 | 29cc89d6158dd3b90acbdbcab4d2c7eb9a7dbf0f | /31_lecture.lean | 1c864b391f9367de98c527305ed23f78b1df3b1a | [] | no_license | KjellZijlemaker/Logical_Verification_VU | ced0ba95316a30e3c94ba8eebd58ea004fa6f53b | 4578b93bf1615466996157bb333c84122b201d99 | refs/heads/master | 1,585,966,086,108 | 1,549,187,704,000 | 1,549,187,704,000 | 155,690,284 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 9,540 | lean | /- Lecture 3.1: Program Semantics β Operational Semantics -/
import .x31_library
attribute [pattern] or.intro_left or.intro_right
/- A WHILE programming language -/
section syntax
inductive program (Ο : Type) : Type
| skip {} : program
| assign : (Ο β Ο) β program
| seq : program β program β program
| ite : (Ο β Prop) β program β program β program
| while : (Ο β Prop) β program β program
end syntax
/- Big-step semantics -/
open program
section semantics
variables {Ο : Type} {c : Ο β Prop} {f : Ο β Ο} {p pβ pβ pβ : program Ο} {s sβ sβ sβ t u : Ο}
/- `big_step p s s'`: when started in `s`, program `p` terminates in `s'`. -/
inductive big_step : (program Ο Γ Ο) β Ο β Prop
| skip {s} :
big_step (skip, s) s
| assign {f s} :
big_step (assign f, s) (f s)
| seq {pβ pβ s u} (t) (hβ : big_step (pβ, s) t) (hβ : big_step (pβ, t) u) :
big_step (seq pβ pβ, s) u
| ite_true {c : Ο β Prop} {pβ pβ s t} (hs : c s) (h : big_step (pβ, s) t) :
big_step (ite c pβ pβ, s) t
| ite_false {c : Ο β Prop} {pβ pβ s t} (hs : Β¬ c s) (h : big_step (pβ, s) t) :
big_step (ite c pβ pβ, s) t
| while_true {c : Ο β Prop} {p s u} (t) (hs : c s) (hp : big_step (p, s) t)
(hw : big_step (while c p, t) u) :
big_step (while c p, s) u
| while_false {c : Ο β Prop} {p s} (hs : Β¬ c s) : big_step (while c p, s) s
/- Mixfix notation for `big_step`:
(p, s) βΉ s' := big_step (p, s) s'.
`βΉ` is entered as `\==>`. -/
infix ` βΉ `:110 := big_step
section tactics
open tactic
/- Finds two local hypotheses `hnp : Β¬ p` and `hp : p` and solves the goal by contradiction -/
meta def find_absurd : tactic unit := do
hs β local_context,
hs.mfirst $ Ξ»hn, do
`(Β¬ %%p) β infer_type hn,
(hs.mfirst $ Ξ»h, do
p' β infer_type h,
is_def_eq p p',
to_expr ``(false.elim (%%hn %%h)) >>= exact)
/- For a `ih : βx, p x β q x`, finds all matching `h : p t` and resolves `ih` with each `h` -/
meta def resolve_all : tactic unit := do
hs β local_context,
hs.mfirst $ Ξ»ih, do
([x, h'], g) β infer_type ih >>= mk_local_pis,
p β mk_pattern [] [x] h' [] [x],
l β hs.reverse.mmap $ Ξ»h, (do
([], [x']) β match_pattern p h,
tactic.note ih.local_pp_name none (ih x' h),
pure tt) <|> pure ff,
if l.bor then clear ih else skip
/- Resolves all `ih : βx, p x β q x` with all `h : p t` and substitutes all occurrences of `x = t`
or `t = x` -/
meta def tactic.interactive.resolve_subst : tactic unit :=
repeat (resolve_all >> subst_vars)
end tactics
/- The `big_step` semantics is deterministic: two terminating program executions result in the same
output -/
lemma big_step_unique (ht : (p, s) βΉ t) (hu : (p, s) βΉ u) : u = t :=
begin
induction ht generalizing u hu;
cases hu;
resolve_subst;
try { refl <|> find_absurd }
end
lemma not_cond_of_big_step_while : (while c p, s) βΉ t β Β¬ c t :=
begin
generalize eq_ps : (while c p, s) = ps,
intro h,
induction h generalizing s eq_ps;
cases eq_ps,
{ apply h_ih_hw, refl },
{ assumption }
end
/- Inversion rules for `βΉ` -/
@[simp] lemma big_step_skip_iff :
(skip, s) βΉ t β t = s :=
iff.intro
(assume h, match t, h with _, big_step.skip := by refl end)
(assume h, match t, h with _, rfl := big_step.skip end)
@[simp] lemma big_step_assign_iff :
(assign f, s) βΉ t β t = f s :=
iff.intro
(assume h, match t, h with _, big_step.assign := rfl end)
(assume h, match t, h with _, rfl := big_step.assign end)
@[simp] lemma big_step_seq_iff :
(seq pβ pβ, s) βΉ t β (βu, (pβ, s) βΉ u β§ (pβ, u) βΉ t) :=
iff.intro
(assume h, match h with big_step.seq u hβ hβ := β¨u, hβ, hββ© end)
(assume h, match h with β¨u, hβ, hββ© := big_step.seq u hβ hβ end)
@[simp] lemma big_step_ite_iff :
(ite c pβ pβ, s) βΉ t β ((c s β§ (pβ, s) βΉ t) β¨ (Β¬ c s β§ (pβ, s) βΉ t)) :=
iff.intro
(assume h, match h with
| big_step.ite_true hs h := or.intro_left _ β¨hs, hβ©
| big_step.ite_false hs h := or.intro_right _ β¨hs, hβ©
end)
(assume h, match h with
| or.intro_left _ β¨hs, hβ© := big_step.ite_true hs h
| or.intro_right _ β¨hs, hβ© := big_step.ite_false hs h
end)
lemma big_step_while_iff :
(while c p, s) βΉ t β (βu, c s β§ (p, s) βΉ u β§ (while c p, u) βΉ t) β¨ (Β¬ c s β§ t = s) :=
iff.intro
(assume h, match t, h with
| t, big_step.while_true u hs hβ hβ := or.intro_left _ β¨u, hs, hβ, hββ©
| s, big_step.while_false hs := or.intro_right _ β¨hs, rflβ©
end)
(assume h, match t, h with
| _, or.intro_left _ β¨u, hs, hβ, hββ© := big_step.while_true u hs hβ hβ
| _, or.intro_right _ β¨hs, rflβ© := big_step.while_false hs
end)
@[simp] lemma big_step_while_true_iff (hs : c s) :
(while c p, s) βΉ t β (βu, (p, s) βΉ u β§ (while c p, u) βΉ t) :=
by rw [big_step_while_iff]; simp [hs]
@[simp] lemma big_step_while_false_iff (hs : Β¬ c s) :
(while c p, s) βΉ t β t = s :=
by rw [big_step_while_iff]; simp [hs]
/- Small-step semantics -/
inductive small_step : program Ο Γ Ο β program Ο Γ Ο β Prop
| assign {f s} :
small_step (assign f, s) (skip, f s)
| seq_step {pβ pβ s s'} (p) :
small_step (pβ, s) (p, s') β small_step (seq pβ pβ, s) (seq p pβ, s')
| seq_skip {p s} :
small_step (seq skip p, s) (p, s)
| ite_true {c : Ο β Prop} {pβ pβ s} :
c s β small_step (ite c pβ pβ, s) (pβ, s)
| ite_false {c : Ο β Prop} {pβ pβ s} :
Β¬ c s β small_step (ite c pβ pβ, s) (pβ, s)
| while {c : Ο β Prop} {p s} :
small_step (while c p, s) (ite c (seq p (while c p)) skip, s)
/- Mixfix notations for `small_step`:
ps β qt := small_step ps qt
ps β* qt := refl_trans small_step ps qt -/
infixr ` β ` := small_step
infixr ` β* ` : 100 := refl_trans small_step
/- Inversion rules for `β` -/
@[simp] lemma small_step_skip : Β¬ ((skip, s) β (p, t)) :=
assume h, match h with end
lemma small_step_seq_iff {v : program Ο Γ Ο} :
(seq pβ pβ, s) β v β (βp t, (pβ, s) β (p, t) β§ v = (seq p pβ, t)) β¨ (pβ = skip β§ v = (pβ, s)) :=
iff.intro
(assume h, match pβ, v, h with
| _, (_, t), small_step.seq_step p h := or.intro_left _ β¨p, t, h, rflβ©
| _, _, small_step.seq_skip := or.intro_right _ β¨rfl, rflβ©
end)
(assume h, match pβ, v, h with
| _, _, or.intro_left _ β¨p, t, h, rflβ© := small_step.seq_step p h
| _, _, or.intro_right _ β¨rfl, rflβ© := small_step.seq_skip
end)
@[simp] lemma small_step_ite_iff {v : program Ο Γ Ο} :
(ite c pβ pβ, s) β v β (c s β§ v = (pβ, s)) β¨ (Β¬ c s β§ v = (pβ, s)) :=
iff.intro
(assume h, match v, h with
| _, small_step.ite_true h := or.intro_left _ β¨h, rflβ©
| _, small_step.ite_false h := or.intro_right _ β¨h, rflβ©
end)
(assume h, match v, h with
| _, or.intro_left _ β¨h, rflβ© := small_step.ite_true h
| _, or.intro_right _ β¨h, rflβ© := small_step.ite_false h
end)
/- Connection between `_ β* _` and `βΉ` -/
lemma refl_trans_small_step_seq (h : (pβ, s) β* (skip, u)) :
(seq pβ pβ, s) β* (seq skip pβ, u) :=
h.lift (Ξ»p:program Ο Γ Ο, (seq p.1 pβ, p.2)) $
assume β¨pβ, sβ© β¨pβ, tβ©, small_step.seq_step _
lemma big_step_imp_refl_trans_small_step (h : (p, s) βΉ t) :
(p, s) β* (skip, t) :=
begin
induction h,
case big_step.skip { refl },
case big_step.assign { exact refl_trans.single small_step.assign },
case big_step.seq : pβ pβ s t u hβ hβ ihβ ihβ {
transitivity,
exact refl_trans_small_step_seq ihβ,
exact ihβ.head small_step.seq_skip
},
case big_step.ite_true : c pβ pβ s t hs hst ih {
exact ih.head (small_step.ite_true hs)
},
case big_step.ite_false : c pβ pβ s t hs hst ih {
exact ih.head (small_step.ite_false hs)
},
case big_step.while_true : c p s t u hs hβ hβ ihβ ihβ {
exact (refl_trans.head (small_step.while) $
refl_trans.head (small_step.ite_true hs) $
(refl_trans_small_step_seq ihβ).trans $
refl_trans.head small_step.seq_skip $
ihβ)
},
case big_step.while_false : c p s hs {
exact (refl_trans.single small_step.while).tail (small_step.ite_false hs)
}
end
lemma big_step_of_small_step_of_big_step :
(pβ, sβ) β (pβ, sβ) β (pβ, sβ) βΉ sβ β (pβ, sβ) βΉ sβ :=
begin
generalize hvβ : (pβ, sβ) = vβ,
generalize hvβ : (pβ, sβ) = vβ,
intro h,
induction h generalizing pβ sβ pβ sβ sβ;
cases hvβ; clear hvβ;
cases hvβ; clear hvβ;
simp [*, big_step_while_true_iff] {contextual := tt},
{ intros u hβ hβ, exact β¨u, h_ih rfl rfl hβ, hββ© },
{ intro h, exact β¨_, rfl, hβ© }
end
lemma refl_trans_small_step_imp_big_step :
(p, s) β* (skip, t) β (p, s) βΉ t :=
begin
generalize hvβ : (p, s) = vβ,
intro h,
induction h
using refl_trans.head_induction_on
with vβ vβ h h' ih
generalizing p s;
cases hvβ;
clear hvβ,
{ exact big_step.skip },
{ cases vβ with p' s',
specialize ih rfl,
exact big_step_of_small_step_of_big_step h ih }
end
lemma big_step_iff_refl_trans_small_step :
(p, s) βΉ t β (p, s) β* (skip, t) :=
iff.intro
big_step_imp_refl_trans_small_step
refl_trans_small_step_imp_big_step
end semantics
|
0097296e4f1cca57f9481ac9dcca0234419cb931 | 19cc34575500ee2e3d4586c15544632aa07a8e66 | /src/algebra/ordered_ring.lean | edcd160a712d5c4ec4562e3c23775514f06a1c08 | [
"Apache-2.0"
] | permissive | LibertasSpZ/mathlib | b9fcd46625eb940611adb5e719a4b554138dade6 | 33f7870a49d7cc06d2f3036e22543e6ec5046e68 | refs/heads/master | 1,672,066,539,347 | 1,602,429,158,000 | 1,602,429,158,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 43,042 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro
-/
import algebra.ordered_group
set_option old_structure_cmd true
universe u
variable {Ξ± : Type u}
/-- An `ordered_semiring Ξ±` is a semiring `Ξ±` with a partial order such that
multiplication with a positive number and addition are monotone. -/
@[protect_proj]
class ordered_semiring (Ξ± : Type u) extends semiring Ξ±, ordered_cancel_add_comm_monoid Ξ± :=
(zero_lt_one : 0 < (1 : Ξ±))
(mul_lt_mul_of_pos_left : β a b c : Ξ±, a < b β 0 < c β c * a < c * b)
(mul_lt_mul_of_pos_right : β a b c : Ξ±, a < b β 0 < c β a * c < b * c)
section ordered_semiring
variables [ordered_semiring Ξ±] {a b c d : Ξ±}
lemma zero_lt_one : 0 < (1:Ξ±) :=
ordered_semiring.zero_lt_one
lemma zero_le_one : 0 β€ (1:Ξ±) :=
zero_lt_one.le
lemma zero_lt_two : 0 < (2:Ξ±) := add_pos zero_lt_one zero_lt_one
@[field_simps] lemma two_ne_zero : (2:Ξ±) β 0 :=
ne.symm (ne_of_lt zero_lt_two)
lemma one_lt_two : 1 < (2:Ξ±) :=
calc (2:Ξ±) = 1+1 : one_add_one_eq_two
... > 1+0 : add_lt_add_left zero_lt_one _
... = 1 : add_zero 1
lemma one_le_two : 1 β€ (2:Ξ±) := one_lt_two.le
lemma zero_lt_four : 0 < (4:Ξ±) := add_pos zero_lt_two zero_lt_two
lemma mul_lt_mul_of_pos_left (hβ : a < b) (hβ : 0 < c) : c * a < c * b :=
ordered_semiring.mul_lt_mul_of_pos_left a b c hβ hβ
lemma mul_lt_mul_of_pos_right (hβ : a < b) (hβ : 0 < c) : a * c < b * c :=
ordered_semiring.mul_lt_mul_of_pos_right a b c hβ hβ
lemma mul_le_mul_of_nonneg_left (hβ : a β€ b) (hβ : 0 β€ c) : c * a β€ c * b :=
begin
cases classical.em (b β€ a), { simp [h.antisymm hβ] },
cases classical.em (c β€ 0), { simp [h_1.antisymm hβ] },
exact (mul_lt_mul_of_pos_left (hβ.lt_of_not_le h) (hβ.lt_of_not_le h_1)).le,
end
lemma mul_le_mul_of_nonneg_right (hβ : a β€ b) (hβ : 0 β€ c) : a * c β€ b * c :=
begin
cases classical.em (b β€ a), { simp [h.antisymm hβ] },
cases classical.em (c β€ 0), { simp [h_1.antisymm hβ] },
exact (mul_lt_mul_of_pos_right (hβ.lt_of_not_le h) (hβ.lt_of_not_le h_1)).le,
end
-- TODO: there are four variations, depending on which variables we assume to be nonneg
lemma mul_le_mul (hac : a β€ c) (hbd : b β€ d) (nn_b : 0 β€ b) (nn_c : 0 β€ c) : a * b β€ c * d :=
calc
a * b β€ c * b : mul_le_mul_of_nonneg_right hac nn_b
... β€ c * d : mul_le_mul_of_nonneg_left hbd nn_c
lemma mul_nonneg (ha : 0 β€ a) (hb : 0 β€ b) : 0 β€ a * b :=
have h : 0 * b β€ a * b, from mul_le_mul_of_nonneg_right ha hb,
by rwa [zero_mul] at h
lemma mul_nonpos_of_nonneg_of_nonpos (ha : 0 β€ a) (hb : b β€ 0) : a * b β€ 0 :=
have h : a * b β€ a * 0, from mul_le_mul_of_nonneg_left hb ha,
by rwa mul_zero at h
lemma mul_nonpos_of_nonpos_of_nonneg (ha : a β€ 0) (hb : 0 β€ b) : a * b β€ 0 :=
have h : a * b β€ 0 * b, from mul_le_mul_of_nonneg_right ha hb,
by rwa zero_mul at h
lemma mul_lt_mul (hac : a < c) (hbd : b β€ d) (pos_b : 0 < b) (nn_c : 0 β€ c) : a * b < c * d :=
calc
a * b < c * b : mul_lt_mul_of_pos_right hac pos_b
... β€ c * d : mul_le_mul_of_nonneg_left hbd nn_c
lemma mul_lt_mul' (h1 : a β€ c) (h2 : b < d) (h3 : 0 β€ b) (h4 : 0 < c) : a * b < c * d :=
calc
a * b β€ c * b : mul_le_mul_of_nonneg_right h1 h3
... < c * d : mul_lt_mul_of_pos_left h2 h4
lemma mul_pos (ha : 0 < a) (hb : 0 < b) : 0 < a * b :=
have h : 0 * b < a * b, from mul_lt_mul_of_pos_right ha hb,
by rwa zero_mul at h
lemma mul_neg_of_pos_of_neg (ha : 0 < a) (hb : b < 0) : a * b < 0 :=
have h : a * b < a * 0, from mul_lt_mul_of_pos_left hb ha,
by rwa mul_zero at h
lemma mul_neg_of_neg_of_pos (ha : a < 0) (hb : 0 < b) : a * b < 0 :=
have h : a * b < 0 * b, from mul_lt_mul_of_pos_right ha hb,
by rwa zero_mul at h
lemma mul_self_le_mul_self (h1 : 0 β€ a) (h2 : a β€ b) : a * a β€ b * b :=
mul_le_mul h2 h2 h1 $ h1.trans h2
lemma mul_self_lt_mul_self (h1 : 0 β€ a) (h2 : a < b) : a * a < b * b :=
mul_lt_mul' h2.le h2 h1 $ h1.trans_lt h2
lemma mul_lt_mul'' (h1 : a < c) (h2 : b < d) (h3 : 0 β€ a) (h4 : 0 β€ b) : a * b < c * d :=
(lt_or_eq_of_le h4).elim
(Ξ» b0, mul_lt_mul h1 h2.le b0 $ h3.trans h1.le)
(Ξ» b0, by rw [β b0, mul_zero]; exact
mul_pos (h3.trans_lt h1) (h4.trans_lt h2))
lemma le_mul_of_one_le_right (hb : 0 β€ b) (h : 1 β€ a) : b β€ b * a :=
suffices b * 1 β€ b * a, by rwa mul_one at this,
mul_le_mul_of_nonneg_left h hb
lemma le_mul_of_one_le_left (hb : 0 β€ b) (h : 1 β€ a) : b β€ a * b :=
suffices 1 * b β€ a * b, by rwa one_mul at this,
mul_le_mul_of_nonneg_right h hb
lemma bit1_pos (h : 0 β€ a) : 0 < bit1 a :=
lt_add_of_le_of_pos (add_nonneg h h) zero_lt_one
lemma bit1_pos' (h : 0 < a) : 0 < bit1 a :=
bit1_pos h.le
lemma lt_add_one (a : Ξ±) : a < a + 1 :=
lt_add_of_le_of_pos le_rfl zero_lt_one
lemma lt_one_add (a : Ξ±) : a < 1 + a :=
by { rw [add_comm], apply lt_add_one }
lemma one_lt_mul (ha : 1 β€ a) (hb : 1 < b) : 1 < a * b :=
(one_mul (1 : Ξ±)) βΈ mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha)
lemma mul_le_one (ha : a β€ 1) (hb' : 0 β€ b) (hb : b β€ 1) : a * b β€ 1 :=
begin rw β one_mul (1 : Ξ±), apply mul_le_mul; {assumption <|> apply zero_le_one} end
lemma one_lt_mul_of_le_of_lt (ha : 1 β€ a) (hb : 1 < b) : 1 < a * b :=
calc 1 = 1 * 1 : by rw one_mul
... < a * b : mul_lt_mul' ha hb zero_le_one (zero_lt_one.trans_le ha)
lemma one_lt_mul_of_lt_of_le (ha : 1 < a) (hb : 1 β€ b) : 1 < a * b :=
calc 1 = 1 * 1 : by rw one_mul
... < a * b : mul_lt_mul ha hb zero_lt_one $ zero_le_one.trans ha.le
lemma mul_le_of_le_one_right (ha : 0 β€ a) (hb1 : b β€ 1) : a * b β€ a :=
calc a * b β€ a * 1 : mul_le_mul_of_nonneg_left hb1 ha
... = a : mul_one a
lemma mul_le_of_le_one_left (hb : 0 β€ b) (ha1 : a β€ 1) : a * b β€ b :=
calc a * b β€ 1 * b : mul_le_mul ha1 le_rfl hb zero_le_one
... = b : one_mul b
lemma mul_lt_one_of_nonneg_of_lt_one_left (ha0 : 0 β€ a) (ha : a < 1) (hb : b β€ 1) : a * b < 1 :=
calc a * b β€ a : mul_le_of_le_one_right ha0 hb
... < 1 : ha
lemma mul_lt_one_of_nonneg_of_lt_one_right (ha : a β€ 1) (hb0 : 0 β€ b) (hb : b < 1) : a * b < 1 :=
calc a * b β€ b : mul_le_of_le_one_left hb0 ha
... < 1 : hb
end ordered_semiring
/-- A `linear_ordered_semiring Ξ±` is a semiring `Ξ±` with a linear order
such that multiplication with a positive number and addition are monotone. -/
@[protect_proj]
class linear_ordered_semiring (Ξ± : Type u) extends ordered_semiring Ξ±, linear_order Ξ±
section linear_ordered_semiring
variables [linear_ordered_semiring Ξ±] {a b c d : Ξ±}
lemma lt_of_mul_lt_mul_left (h : c * a < c * b) (hc : 0 β€ c) : a < b :=
lt_of_not_ge
(assume h1 : b β€ a,
have h2 : c * b β€ c * a, from mul_le_mul_of_nonneg_left h1 hc,
h2.not_lt h)
lemma lt_of_mul_lt_mul_right (h : a * c < b * c) (hc : 0 β€ c) : a < b :=
lt_of_not_ge
(assume h1 : b β€ a,
have h2 : b * c β€ a * c, from mul_le_mul_of_nonneg_right h1 hc,
h2.not_lt h)
lemma le_of_mul_le_mul_left (h : c * a β€ c * b) (hc : 0 < c) : a β€ b :=
le_of_not_gt
(assume h1 : b < a,
have h2 : c * b < c * a, from mul_lt_mul_of_pos_left h1 hc,
h2.not_le h)
lemma le_of_mul_le_mul_right (h : a * c β€ b * c) (hc : 0 < c) : a β€ b :=
le_of_not_gt
(assume h1 : b < a,
have h2 : b * c < a * c, from mul_lt_mul_of_pos_right h1 hc,
h2.not_le h)
lemma pos_and_pos_or_neg_and_neg_of_mul_pos (hab : 0 < a * b) :
(0 < a β§ 0 < b) β¨ (a < 0 β§ b < 0) :=
begin
rcases lt_trichotomy 0 a with (ha|rfl|ha),
{ refine or.inl β¨ha, _β©,
contrapose! hab,
exact mul_nonpos_of_nonneg_of_nonpos ha.le hab },
{ rw [zero_mul] at hab, exact hab.false.elim },
{ refine or.inr β¨ha, _β©,
contrapose! hab,
exact mul_nonpos_of_nonpos_of_nonneg ha.le hab }
end
lemma nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg (hab : 0 β€ a * b) :
(0 β€ a β§ 0 β€ b) β¨ (a β€ 0 β§ b β€ 0) :=
begin
contrapose! hab,
rcases lt_trichotomy 0 a with (ha|rfl|ha),
exacts [mul_neg_of_pos_of_neg ha (hab.1 ha.le), ((hab.1 le_rfl).asymm (hab.2 le_rfl)).elim,
mul_neg_of_neg_of_pos ha (hab.2 ha.le)]
end
lemma pos_of_mul_pos_left (h : 0 < a * b) (ha : 0 β€ a) : 0 < b :=
((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ Ξ» h, h.1.not_le ha).2
lemma pos_of_mul_pos_right (h : 0 < a * b) (hb : 0 β€ b) : 0 < a :=
((pos_and_pos_or_neg_and_neg_of_mul_pos h).resolve_right $ Ξ» h, h.2.not_le hb).1
lemma nonneg_of_mul_nonneg_left (h : 0 β€ a * b) (h1 : 0 < a) : 0 β€ b :=
le_of_not_gt (assume h2 : b < 0, (mul_neg_of_pos_of_neg h1 h2).not_le h)
lemma nonneg_of_mul_nonneg_right (h : 0 β€ a * b) (h1 : 0 < b) : 0 β€ a :=
le_of_not_gt (assume h2 : a < 0, (mul_neg_of_neg_of_pos h2 h1).not_le h)
lemma neg_of_mul_neg_left (h : a * b < 0) (h1 : 0 β€ a) : b < 0 :=
lt_of_not_ge (assume h2 : b β₯ 0, (mul_nonneg h1 h2).not_lt h)
lemma neg_of_mul_neg_right (h : a * b < 0) (h1 : 0 β€ b) : a < 0 :=
lt_of_not_ge (assume h2 : a β₯ 0, (mul_nonneg h2 h1).not_lt h)
lemma nonpos_of_mul_nonpos_left (h : a * b β€ 0) (h1 : 0 < a) : b β€ 0 :=
le_of_not_gt (assume h2 : b > 0, (mul_pos h1 h2).not_le h)
lemma nonpos_of_mul_nonpos_right (h : a * b β€ 0) (h1 : 0 < b) : a β€ 0 :=
le_of_not_gt (assume h2 : a > 0, (mul_pos h2 h1).not_le h)
@[simp] lemma mul_le_mul_left (h : 0 < c) : c * a β€ c * b β a β€ b :=
β¨Ξ» h', le_of_mul_le_mul_left h' h, Ξ» h', mul_le_mul_of_nonneg_left h' h.leβ©
@[simp] lemma mul_le_mul_right (h : 0 < c) : a * c β€ b * c β a β€ b :=
β¨Ξ» h', le_of_mul_le_mul_right h' h, Ξ» h', mul_le_mul_of_nonneg_right h' h.leβ©
@[simp] lemma mul_lt_mul_left (h : 0 < c) : c * a < c * b β a < b :=
β¨lt_imp_lt_of_le_imp_le $ Ξ» h', mul_le_mul_of_nonneg_left h' h.le,
Ξ» h', mul_lt_mul_of_pos_left h' hβ©
@[simp] lemma mul_lt_mul_right (h : 0 < c) : a * c < b * c β a < b :=
β¨lt_imp_lt_of_le_imp_le $ Ξ» h', mul_le_mul_of_nonneg_right h' h.le,
Ξ» h', mul_lt_mul_of_pos_right h' hβ©
@[simp] lemma zero_le_mul_left (h : 0 < c) : 0 β€ c * b β 0 β€ b :=
by { convert mul_le_mul_left h, simp }
@[simp] lemma zero_le_mul_right (h : 0 < c) : 0 β€ b * c β 0 β€ b :=
by { convert mul_le_mul_right h, simp }
@[simp] lemma zero_lt_mul_left (h : 0 < c) : 0 < c * b β 0 < b :=
by { convert mul_lt_mul_left h, simp }
@[simp] lemma zero_lt_mul_right (h : 0 < c) : 0 < b * c β 0 < b :=
by { convert mul_lt_mul_right h, simp }
@[simp] lemma bit0_le_bit0 : bit0 a β€ bit0 b β a β€ b :=
by rw [bit0, bit0, β two_mul, β two_mul, mul_le_mul_left zero_lt_two]
@[simp] lemma bit0_lt_bit0 : bit0 a < bit0 b β a < b :=
by rw [bit0, bit0, β two_mul, β two_mul, mul_lt_mul_left zero_lt_two]
@[simp] lemma bit1_le_bit1 : bit1 a β€ bit1 b β a β€ b :=
(add_le_add_iff_right 1).trans bit0_le_bit0
@[simp] lemma bit1_lt_bit1 : bit1 a < bit1 b β a < b :=
(add_lt_add_iff_right 1).trans bit0_lt_bit0
@[simp] lemma one_le_bit1 : (1 : Ξ±) β€ bit1 a β 0 β€ a :=
by rw [bit1, le_add_iff_nonneg_left, bit0, β two_mul, zero_le_mul_left zero_lt_two]
@[simp] lemma one_lt_bit1 : (1 : Ξ±) < bit1 a β 0 < a :=
by rw [bit1, lt_add_iff_pos_left, bit0, β two_mul, zero_lt_mul_left zero_lt_two]
@[simp] lemma zero_le_bit0 : (0 : Ξ±) β€ bit0 a β 0 β€ a :=
by rw [bit0, β two_mul, zero_le_mul_left zero_lt_two]
@[simp] lemma zero_lt_bit0 : (0 : Ξ±) < bit0 a β 0 < a :=
by rw [bit0, β two_mul, zero_lt_mul_left zero_lt_two]
lemma le_mul_iff_one_le_left (hb : 0 < b) : b β€ a * b β 1 β€ a :=
suffices 1 * b β€ a * b β 1 β€ a, by rwa one_mul at this,
mul_le_mul_right hb
lemma lt_mul_iff_one_lt_left (hb : 0 < b) : b < a * b β 1 < a :=
suffices 1 * b < a * b β 1 < a, by rwa one_mul at this,
mul_lt_mul_right hb
lemma le_mul_iff_one_le_right (hb : 0 < b) : b β€ b * a β 1 β€ a :=
suffices b * 1 β€ b * a β 1 β€ a, by rwa mul_one at this,
mul_le_mul_left hb
lemma lt_mul_iff_one_lt_right (hb : 0 < b) : b < b * a β 1 < a :=
suffices b * 1 < b * a β 1 < a, by rwa mul_one at this,
mul_lt_mul_left hb
lemma lt_mul_of_one_lt_right (hb : 0 < b) : 1 < a β b < b * a :=
(lt_mul_iff_one_lt_right hb).2
theorem mul_nonneg_iff_right_nonneg_of_pos (h : 0 < a) : 0 β€ b * a β 0 β€ b :=
β¨assume : 0 β€ b * a, nonneg_of_mul_nonneg_right this h, assume : 0 β€ b, mul_nonneg this h.leβ©
lemma mul_le_iff_le_one_left (hb : 0 < b) : a * b β€ b β a β€ 1 :=
β¨ Ξ» h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).2 h.not_lt),
Ξ» h, le_of_not_lt (mt (lt_mul_iff_one_lt_left hb).1 h.not_lt) β©
lemma mul_lt_iff_lt_one_left (hb : 0 < b) : a * b < b β a < 1 :=
β¨ Ξ» h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).2 h.not_le),
Ξ» h, lt_of_not_ge (mt (le_mul_iff_one_le_left hb).1 h.not_le) β©
lemma mul_le_iff_le_one_right (hb : 0 < b) : b * a β€ b β a β€ 1 :=
β¨ Ξ» h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).2 h.not_lt),
Ξ» h, le_of_not_lt (mt (lt_mul_iff_one_lt_right hb).1 h.not_lt) β©
lemma mul_lt_iff_lt_one_right (hb : 0 < b) : b * a < b β a < 1 :=
β¨ Ξ» h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).2 h.not_le),
Ξ» h, lt_of_not_ge (mt (le_mul_iff_one_le_right hb).1 h.not_le) β©
lemma nonpos_of_mul_nonneg_left (h : 0 β€ a * b) (hb : b < 0) : a β€ 0 :=
le_of_not_gt (Ξ» ha, absurd h (mul_neg_of_pos_of_neg ha hb).not_le)
lemma nonpos_of_mul_nonneg_right (h : 0 β€ a * b) (ha : a < 0) : b β€ 0 :=
le_of_not_gt (Ξ» hb, absurd h (mul_neg_of_neg_of_pos ha hb).not_le)
lemma neg_of_mul_pos_left (h : 0 < a * b) (hb : b β€ 0) : a < 0 :=
lt_of_not_ge (Ξ» ha, absurd h (mul_nonpos_of_nonneg_of_nonpos ha hb).not_lt)
lemma neg_of_mul_pos_right (h : 0 < a * b) (ha : a β€ 0) : b < 0 :=
lt_of_not_ge (Ξ» hb, absurd h (mul_nonpos_of_nonpos_of_nonneg ha hb).not_lt)
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_semiring.to_nontrivial {Ξ± : Type*} [linear_ordered_semiring Ξ±] :
nontrivial Ξ± :=
{ exists_pair_ne := β¨0, 1, ne_of_lt zero_lt_oneβ© }
/- TODO This theorem ought to be written in the context of `nontrivial` linearly ordered (additive)
commutative monoids rather than linearly ordered rings; however, the former concept does not
currently exist in mathlib. -/
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_semiring.to_no_top_order {Ξ± : Type*} [linear_ordered_semiring Ξ±] :
no_top_order Ξ± :=
β¨assume a, β¨a + 1, lt_add_of_pos_right _ zero_lt_oneβ©β©
end linear_ordered_semiring
section mono
variables {Ξ² : Type*} [linear_ordered_semiring Ξ±] [preorder Ξ²] {f g : Ξ² β Ξ±} {a : Ξ±}
lemma monotone_mul_left_of_nonneg (ha : 0 β€ a) : monotone (Ξ» x, a*x) :=
assume b c b_le_c, mul_le_mul_of_nonneg_left b_le_c ha
lemma monotone_mul_right_of_nonneg (ha : 0 β€ a) : monotone (Ξ» x, x*a) :=
assume b c b_le_c, mul_le_mul_of_nonneg_right b_le_c ha
lemma monotone.mul_const (hf : monotone f) (ha : 0 β€ a) :
monotone (Ξ» x, (f x) * a) :=
(monotone_mul_right_of_nonneg ha).comp hf
lemma monotone.const_mul (hf : monotone f) (ha : 0 β€ a) :
monotone (Ξ» x, a * (f x)) :=
(monotone_mul_left_of_nonneg ha).comp hf
lemma monotone.mul (hf : monotone f) (hg : monotone g) (hf0 : β x, 0 β€ f x) (hg0 : β x, 0 β€ g x) :
monotone (Ξ» x, f x * g x) :=
Ξ» x y h, mul_le_mul (hf h) (hg h) (hg0 x) (hf0 y)
lemma strict_mono_mul_left_of_pos (ha : 0 < a) : strict_mono (Ξ» x, a * x) :=
assume b c b_lt_c, (mul_lt_mul_left ha).2 b_lt_c
lemma strict_mono_mul_right_of_pos (ha : 0 < a) : strict_mono (Ξ» x, x * a) :=
assume b c b_lt_c, (mul_lt_mul_right ha).2 b_lt_c
lemma strict_mono.mul_const (hf : strict_mono f) (ha : 0 < a) :
strict_mono (Ξ» x, (f x) * a) :=
(strict_mono_mul_right_of_pos ha).comp hf
lemma strict_mono.const_mul (hf : strict_mono f) (ha : 0 < a) :
strict_mono (Ξ» x, a * (f x)) :=
(strict_mono_mul_left_of_pos ha).comp hf
lemma strict_mono.mul_monotone (hf : strict_mono f) (hg : monotone g) (hf0 : β x, 0 β€ f x)
(hg0 : β x, 0 < g x) :
strict_mono (Ξ» x, f x * g x) :=
Ξ» x y h, mul_lt_mul (hf h) (hg h.le) (hg0 x) (hf0 y)
lemma monotone.mul_strict_mono (hf : monotone f) (hg : strict_mono g) (hf0 : β x, 0 < f x)
(hg0 : β x, 0 β€ g x) :
strict_mono (Ξ» x, f x * g x) :=
Ξ» x y h, mul_lt_mul' (hf h.le) (hg h) (hg0 x) (hf0 y)
lemma strict_mono.mul (hf : strict_mono f) (hg : strict_mono g) (hf0 : β x, 0 β€ f x)
(hg0 : β x, 0 β€ g x) :
strict_mono (Ξ» x, f x * g x) :=
Ξ» x y h, mul_lt_mul'' (hf h) (hg h) (hf0 x) (hg0 x)
end mono
/-- A `decidable_linear_ordered_semiring Ξ±` is a semiring `Ξ±` with a decidable linear order
such that multiplication with a positive number and addition are monotone. -/
@[protect_proj] class decidable_linear_ordered_semiring (Ξ± : Type u)
extends linear_ordered_semiring Ξ±, decidable_linear_order Ξ±
section decidable_linear_ordered_semiring
variables [decidable_linear_ordered_semiring Ξ±] {a b c : Ξ±}
@[simp] lemma decidable.mul_le_mul_left (h : 0 < c) : c * a β€ c * b β a β€ b :=
decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_left h
@[simp] lemma decidable.mul_le_mul_right (h : 0 < c) : a * c β€ b * c β a β€ b :=
decidable.le_iff_le_iff_lt_iff_lt.2 $ mul_lt_mul_right h
end decidable_linear_ordered_semiring
/-- An `ordered_ring Ξ±` is a ring `Ξ±` with a partial order such that
multiplication with a positive number and addition are monotone. -/
@[protect_proj]
class ordered_ring (Ξ± : Type u) extends ring Ξ±, ordered_add_comm_group Ξ±, nontrivial Ξ± :=
(zero_lt_one : zero < one)
(mul_pos : β a b : Ξ±, 0 < a β 0 < b β 0 < a * b)
section ordered_ring
variables [ordered_ring Ξ±] {a b c : Ξ±}
lemma ordered_ring.mul_nonneg (a b : Ξ±) (hβ : 0 β€ a) (hβ : 0 β€ b) : 0 β€ a * b :=
begin
cases classical.em (a β€ 0), { simp [le_antisymm h hβ] },
cases classical.em (b β€ 0), { simp [le_antisymm h_1 hβ] },
exact (le_not_le_of_lt (ordered_ring.mul_pos a b (hβ.lt_of_not_le h) (hβ.lt_of_not_le h_1))).left,
end
lemma ordered_ring.mul_le_mul_of_nonneg_left (hβ : a β€ b) (hβ : 0 β€ c) : c * a β€ c * b :=
have 0 β€ b - a, from sub_nonneg_of_le hβ,
have 0 β€ c * (b - a), from ordered_ring.mul_nonneg c (b - a) hβ this,
begin
rw mul_sub_left_distrib at this,
apply le_of_sub_nonneg this
end
lemma ordered_ring.mul_le_mul_of_nonneg_right (hβ : a β€ b) (hβ : 0 β€ c) : a * c β€ b * c :=
have 0 β€ b - a, from sub_nonneg_of_le hβ,
have 0 β€ (b - a) * c, from ordered_ring.mul_nonneg (b - a) c this hβ,
begin
rw mul_sub_right_distrib at this,
apply le_of_sub_nonneg this
end
lemma ordered_ring.mul_lt_mul_of_pos_left (hβ : a < b) (hβ : 0 < c) : c * a < c * b :=
have 0 < b - a, from sub_pos_of_lt hβ,
have 0 < c * (b - a), from ordered_ring.mul_pos c (b - a) hβ this,
begin
rw mul_sub_left_distrib at this,
apply lt_of_sub_pos this
end
lemma ordered_ring.mul_lt_mul_of_pos_right (hβ : a < b) (hβ : 0 < c) : a * c < b * c :=
have 0 < b - a, from sub_pos_of_lt hβ,
have 0 < (b - a) * c, from ordered_ring.mul_pos (b - a) c this hβ,
begin
rw mul_sub_right_distrib at this,
apply lt_of_sub_pos this
end
@[priority 100] -- see Note [lower instance priority]
instance ordered_ring.to_ordered_semiring : ordered_semiring Ξ± :=
{ mul_zero := mul_zero,
zero_mul := zero_mul,
add_left_cancel := @add_left_cancel Ξ± _,
add_right_cancel := @add_right_cancel Ξ± _,
le_of_add_le_add_left := @le_of_add_le_add_left Ξ± _,
mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left Ξ± _,
mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right Ξ± _,
..βΉordered_ring Ξ±βΊ }
lemma mul_le_mul_of_nonpos_left {a b c : Ξ±} (h : b β€ a) (hc : c β€ 0) : c * a β€ c * b :=
have -c β₯ 0, from neg_nonneg_of_nonpos hc,
have -c * b β€ -c * a, from mul_le_mul_of_nonneg_left h this,
have -(c * b) β€ -(c * a), by rwa [β neg_mul_eq_neg_mul, β neg_mul_eq_neg_mul] at this,
le_of_neg_le_neg this
lemma mul_le_mul_of_nonpos_right {a b c : Ξ±} (h : b β€ a) (hc : c β€ 0) : a * c β€ b * c :=
have -c β₯ 0, from neg_nonneg_of_nonpos hc,
have b * -c β€ a * -c, from mul_le_mul_of_nonneg_right h this,
have -(b * c) β€ -(a * c), by rwa [β neg_mul_eq_mul_neg, β neg_mul_eq_mul_neg] at this,
le_of_neg_le_neg this
lemma mul_nonneg_of_nonpos_of_nonpos {a b : Ξ±} (ha : a β€ 0) (hb : b β€ 0) : 0 β€ a * b :=
have 0 * b β€ a * b, from mul_le_mul_of_nonpos_right ha hb,
by rwa zero_mul at this
lemma mul_lt_mul_of_neg_left {a b c : Ξ±} (h : b < a) (hc : c < 0) : c * a < c * b :=
have -c > 0, from neg_pos_of_neg hc,
have -c * b < -c * a, from mul_lt_mul_of_pos_left h this,
have -(c * b) < -(c * a), by rwa [β neg_mul_eq_neg_mul, β neg_mul_eq_neg_mul] at this,
lt_of_neg_lt_neg this
lemma mul_lt_mul_of_neg_right {a b c : Ξ±} (h : b < a) (hc : c < 0) : a * c < b * c :=
have -c > 0, from neg_pos_of_neg hc,
have b * -c < a * -c, from mul_lt_mul_of_pos_right h this,
have -(b * c) < -(a * c), by rwa [β neg_mul_eq_mul_neg, β neg_mul_eq_mul_neg] at this,
lt_of_neg_lt_neg this
lemma mul_pos_of_neg_of_neg {a b : Ξ±} (ha : a < 0) (hb : b < 0) : 0 < a * b :=
have 0 * b < a * b, from mul_lt_mul_of_neg_right ha hb,
by rwa zero_mul at this
end ordered_ring
/-- A `linear_ordered_ring Ξ±` is a ring `Ξ±` with a linear order such that
multiplication with a positive number and addition are monotone. -/
@[protect_proj] class linear_ordered_ring (Ξ± : Type u) extends ordered_ring Ξ±, linear_order Ξ±
section linear_ordered_ring
variables [linear_ordered_ring Ξ±] {a b c : Ξ±}
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_ring.to_linear_ordered_semiring : linear_ordered_semiring Ξ± :=
{ mul_zero := mul_zero,
zero_mul := zero_mul,
add_left_cancel := @add_left_cancel Ξ± _,
add_right_cancel := @add_right_cancel Ξ± _,
le_of_add_le_add_left := @le_of_add_le_add_left Ξ± _,
mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left Ξ± _,
mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right Ξ± _,
le_total := linear_ordered_ring.le_total,
..βΉlinear_ordered_ring Ξ±βΊ }
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_ring.to_domain : domain Ξ± :=
{ eq_zero_or_eq_zero_of_mul_eq_zero :=
begin
intros a b hab,
contrapose! hab,
cases (lt_or_gt_of_ne hab.1) with ha ha; cases (lt_or_gt_of_ne hab.2) with hb hb,
exacts [(mul_pos_of_neg_of_neg ha hb).ne.symm, (mul_neg_of_neg_of_pos ha hb).ne,
(mul_neg_of_pos_of_neg ha hb).ne, (mul_pos ha hb).ne.symm]
end,
.. βΉlinear_ordered_ring Ξ±βΊ }
lemma mul_pos_iff : 0 < a * b β 0 < a β§ 0 < b β¨ a < 0 β§ b < 0 :=
β¨pos_and_pos_or_neg_and_neg_of_mul_pos,
Ξ» h, h.elim (and_imp.2 mul_pos) (and_imp.2 mul_pos_of_neg_of_neg)β©
lemma mul_neg_iff : a * b < 0 β 0 < a β§ b < 0 β¨ a < 0 β§ 0 < b :=
by rw [β neg_pos, neg_mul_eq_mul_neg, mul_pos_iff, neg_pos, neg_lt_zero]
lemma mul_nonneg_iff : 0 β€ a * b β 0 β€ a β§ 0 β€ b β¨ a β€ 0 β§ b β€ 0 :=
β¨nonneg_and_nonneg_or_nonpos_and_nonpos_of_mul_nnonneg,
Ξ» h, h.elim (and_imp.2 mul_nonneg) (and_imp.2 mul_nonneg_of_nonpos_of_nonpos)β©
lemma mul_nonpos_iff : a * b β€ 0 β 0 β€ a β§ b β€ 0 β¨ a β€ 0 β§ 0 β€ b :=
by rw [β neg_nonneg, neg_mul_eq_mul_neg, mul_nonneg_iff, neg_nonneg, neg_nonpos]
lemma mul_self_nonneg (a : Ξ±) : 0 β€ a * a :=
or.elim (le_total 0 a)
(assume h : a β₯ 0, mul_nonneg h h)
(assume h : a β€ 0, mul_nonneg_of_nonpos_of_nonpos h h)
lemma gt_of_mul_lt_mul_neg_left (h : c * a < c * b) (hc : c β€ 0) : b < a :=
have nhc : 0 β€ -c, from neg_nonneg_of_nonpos hc,
have h2 : -(c * b) < -(c * a), from neg_lt_neg h,
have h3 : (-c) * b < (-c) * a, from calc
(-c) * b = - (c * b) : by rewrite neg_mul_eq_neg_mul
... < -(c * a) : h2
... = (-c) * a : by rewrite neg_mul_eq_neg_mul,
lt_of_mul_lt_mul_left h3 nhc
lemma neg_one_lt_zero : -1 < (0:Ξ±) :=
begin
have this := neg_lt_neg (@zero_lt_one Ξ± _),
rwa neg_zero at this
end
lemma le_of_mul_le_of_one_le {a b c : Ξ±} (h : a * c β€ b) (hb : 0 β€ b) (hc : 1 β€ c) : a β€ b :=
have h' : a * c β€ b * c, from calc
a * c β€ b : h
... = b * 1 : by rewrite mul_one
... β€ b * c : mul_le_mul_of_nonneg_left hc hb,
le_of_mul_le_mul_right h' (zero_lt_one.trans_le hc)
lemma nonneg_le_nonneg_of_squares_le {a b : Ξ±} (hb : 0 β€ b) (h : a * a β€ b * b) : a β€ b :=
le_of_not_gt (Ξ»hab, (mul_self_lt_mul_self hb hab).not_le h)
lemma mul_self_le_mul_self_iff {a b : Ξ±} (h1 : 0 β€ a) (h2 : 0 β€ b) : a β€ b β a * a β€ b * b :=
β¨mul_self_le_mul_self h1, nonneg_le_nonneg_of_squares_le h2β©
lemma mul_self_lt_mul_self_iff {a b : Ξ±} (h1 : 0 β€ a) (h2 : 0 β€ b) : a < b β a * a < b * b :=
iff.trans (lt_iff_not_ge _ _) $ iff.trans (not_iff_not_of_iff $ mul_self_le_mul_self_iff h2 h1) $
iff.symm (lt_iff_not_ge _ _)
/- TODO This theorem ought to be written in the context of `nontrivial` linearly ordered (additive)
commutative groups rather than linearly ordered rings; however, the former concept does not
currently exist in mathlib. -/
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_ring.to_no_bot_order : no_bot_order Ξ± :=
β¨assume a, β¨a - 1, sub_lt_iff_lt_add.mpr $ lt_add_of_pos_right _ zero_lt_oneβ©β©
@[simp] lemma mul_le_mul_left_of_neg {a b c : Ξ±} (h : c < 0) : c * a β€ c * b β b β€ a :=
β¨le_imp_le_of_lt_imp_lt $ Ξ» h', mul_lt_mul_of_neg_left h' h,
Ξ» h', mul_le_mul_of_nonpos_left h' h.leβ©
@[simp] lemma mul_le_mul_right_of_neg {a b c : Ξ±} (h : c < 0) : a * c β€ b * c β b β€ a :=
β¨le_imp_le_of_lt_imp_lt $ Ξ» h', mul_lt_mul_of_neg_right h' h,
Ξ» h', mul_le_mul_of_nonpos_right h' h.leβ©
@[simp] lemma mul_lt_mul_left_of_neg {a b c : Ξ±} (h : c < 0) : c * a < c * b β b < a :=
lt_iff_lt_of_le_iff_le (mul_le_mul_left_of_neg h)
@[simp] lemma mul_lt_mul_right_of_neg {a b c : Ξ±} (h : c < 0) : a * c < b * c β b < a :=
lt_iff_lt_of_le_iff_le (mul_le_mul_right_of_neg h)
lemma sub_one_lt (a : Ξ±) : a - 1 < a :=
sub_lt_iff_lt_add.2 (lt_add_one a)
lemma mul_self_pos {a : Ξ±} (ha : a β 0) : 0 < a * a :=
by rcases lt_trichotomy a 0 with h|h|h;
[exact mul_pos_of_neg_of_neg h h, exact (ha h).elim, exact mul_pos h h]
lemma mul_self_le_mul_self_of_le_of_neg_le {x y : Ξ±} (hβ : x β€ y) (hβ : -x β€ y) : x * x β€ y * y :=
begin
cases le_total 0 x,
{ exact mul_self_le_mul_self h hβ },
{ rw β neg_mul_neg, exact mul_self_le_mul_self (neg_nonneg_of_nonpos h) hβ }
end
lemma nonneg_of_mul_nonpos_left {a b : Ξ±} (h : a * b β€ 0) (hb : b < 0) : 0 β€ a :=
le_of_not_gt (Ξ» ha, absurd h (mul_pos_of_neg_of_neg ha hb).not_le)
lemma nonneg_of_mul_nonpos_right {a b : Ξ±} (h : a * b β€ 0) (ha : a < 0) : 0 β€ b :=
le_of_not_gt (Ξ» hb, absurd h (mul_pos_of_neg_of_neg ha hb).not_le)
lemma pos_of_mul_neg_left {a b : Ξ±} (h : a * b < 0) (hb : b β€ 0) : 0 < a :=
lt_of_not_ge (Ξ» ha, absurd h (mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt)
lemma pos_of_mul_neg_right {a b : Ξ±} (h : a * b < 0) (ha : a β€ 0) : 0 < b :=
lt_of_not_ge (Ξ» hb, absurd h (mul_nonneg_of_nonpos_of_nonpos ha hb).not_lt)
/- The sum of two squares is zero iff both elements are zero. -/
lemma mul_self_add_mul_self_eq_zero {x y : Ξ±} : x * x + y * y = 0 β x = 0 β§ y = 0 :=
begin
split; intro h, swap, { rcases h with β¨rfl, rflβ©, simp },
have : y * y β€ 0, { rw [β h], apply le_add_of_nonneg_left (mul_self_nonneg x) },
have : y * y = 0 := le_antisymm this (mul_self_nonneg y),
have hx : x = 0, { rwa [this, add_zero, mul_self_eq_zero] at h },
rw mul_self_eq_zero at this, split; assumption
end
end linear_ordered_ring
/-- A `linear_ordered_comm_ring Ξ±` is a commutative ring `Ξ±` with a linear order
such that multiplication with a positive number and addition are monotone. -/
@[protect_proj]
class linear_ordered_comm_ring (Ξ± : Type u) extends linear_ordered_ring Ξ±, comm_monoid Ξ±
@[priority 100] -- see Note [lower instance priority]
instance linear_ordered_comm_ring.to_integral_domain [s: linear_ordered_comm_ring Ξ±] :
integral_domain Ξ± :=
{ ..s, .. linear_ordered_ring.to_domain }
/-- A `decidable_linear_ordered_comm_ring Ξ±` is a commutative ring `Ξ±` with a
decidable linear order such that multiplication with a positive number and
addition are monotone. -/
@[protect_proj] class decidable_linear_ordered_comm_ring (Ξ± : Type u) extends linear_ordered_comm_ring Ξ±,
decidable_linear_ordered_add_comm_group Ξ±
@[priority 100] -- see Note [lower instance priority]
instance decidable_linear_ordered_comm_ring.to_decidable_linear_ordered_semiring [d : decidable_linear_ordered_comm_ring Ξ±] :
decidable_linear_ordered_semiring Ξ± :=
let s : linear_ordered_semiring Ξ± := @linear_ordered_ring.to_linear_ordered_semiring Ξ± _ in
{ zero_mul := @linear_ordered_semiring.zero_mul Ξ± s,
mul_zero := @linear_ordered_semiring.mul_zero Ξ± s,
add_left_cancel := @linear_ordered_semiring.add_left_cancel Ξ± s,
add_right_cancel := @linear_ordered_semiring.add_right_cancel Ξ± s,
le_of_add_le_add_left := @linear_ordered_semiring.le_of_add_le_add_left Ξ± s,
mul_lt_mul_of_pos_left := @linear_ordered_semiring.mul_lt_mul_of_pos_left Ξ± s,
mul_lt_mul_of_pos_right := @linear_ordered_semiring.mul_lt_mul_of_pos_right Ξ± s,
..d }
section decidable_linear_ordered_comm_ring
variables [decidable_linear_ordered_comm_ring Ξ±] {a b c : Ξ±}
lemma abs_mul (a b : Ξ±) : abs (a * b) = abs a * abs b :=
or.elim (le_total 0 a)
(assume h1 : 0 β€ a,
or.elim (le_total 0 b)
(assume h2 : 0 β€ b,
calc
abs (a * b) = a * b : abs_of_nonneg (mul_nonneg h1 h2)
... = abs a * b : by rw (abs_of_nonneg h1)
... = abs a * abs b : by rw (abs_of_nonneg h2))
(assume h2 : b β€ 0,
calc
abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos h1 h2)
... = a * -b : by rw neg_mul_eq_mul_neg
... = abs a * -b : by rw (abs_of_nonneg h1)
... = abs a * abs b : by rw (abs_of_nonpos h2)))
(assume h1 : a β€ 0,
or.elim (le_total 0 b)
(assume h2 : 0 β€ b,
calc
abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg h1 h2)
... = -a * b : by rw neg_mul_eq_neg_mul
... = abs a * b : by rw (abs_of_nonpos h1)
... = abs a * abs b : by rw (abs_of_nonneg h2))
(assume h2 : b β€ 0,
calc
abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos h1 h2)
... = -a * -b : by rw neg_mul_neg
... = abs a * -b : by rw (abs_of_nonpos h1)
... = abs a * abs b : by rw (abs_of_nonpos h2)))
lemma abs_mul_abs_self (a : Ξ±) : abs a * abs a = a * a :=
abs_by_cases (Ξ» x, x * x = a * a) rfl (neg_mul_neg a a)
lemma abs_mul_self (a : Ξ±) : abs (a * a) = a * a :=
by rw [abs_mul, abs_mul_abs_self]
lemma sub_le_of_abs_sub_le_left (h : abs (a - b) β€ c) : b - c β€ a :=
if hz : 0 β€ a - b then
(calc
a β₯ b : le_of_sub_nonneg hz
... β₯ b - c : sub_le_self _ $ (abs_nonneg _).trans h)
else
have habs : b - a β€ c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h,
have habs' : b β€ c + a, from le_add_of_sub_right_le habs,
sub_left_le_of_le_add habs'
lemma sub_le_of_abs_sub_le_right (h : abs (a - b) β€ c) : a - c β€ b :=
sub_le_of_abs_sub_le_left (abs_sub a b βΈ h)
lemma sub_lt_of_abs_sub_lt_left (h : abs (a - b) < c) : b - c < a :=
if hz : 0 β€ a - b then
(calc
a β₯ b : le_of_sub_nonneg hz
... > b - c : sub_lt_self _ ((abs_nonneg _).trans_lt h))
else
have habs : b - a < c, by rwa [abs_of_neg (lt_of_not_ge hz), neg_sub] at h,
have habs' : b < c + a, from lt_add_of_sub_right_lt habs,
sub_left_lt_of_lt_add habs'
lemma sub_lt_of_abs_sub_lt_right (h : abs (a - b) < c) : a - c < b :=
sub_lt_of_abs_sub_lt_left (abs_sub a b βΈ h)
lemma abs_sub_square (a b : Ξ±) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b :=
begin
rw abs_mul_abs_self,
simp [left_distrib, right_distrib, add_assoc, add_comm, add_left_comm, mul_comm, sub_eq_add_neg]
end
lemma eq_zero_of_mul_self_add_mul_self_eq_zero (h : a * a + b * b = 0) : a = 0 :=
have a * a β€ (0 : Ξ±), from calc
a * a β€ a * a + b * b : le_add_of_nonneg_right (mul_self_nonneg b)
... = 0 : h,
eq_zero_of_mul_self_eq_zero (le_antisymm this (mul_self_nonneg a))
lemma abs_abs_sub_abs_le_abs_sub (a b : Ξ±) : abs (abs a - abs b) β€ abs (a - b) :=
begin
apply nonneg_le_nonneg_of_squares_le,
apply abs_nonneg,
iterate {rw abs_sub_square},
iterate {rw abs_mul_abs_self},
apply sub_le_sub_left,
iterate {rw mul_assoc},
apply mul_le_mul_of_nonneg_left,
{ rw [β abs_mul],
apply le_abs_self },
{ exact (add_pos (@zero_lt_one Ξ± _) zero_lt_one).le }
end
-- The proof doesn't need commutativity but we have no `decidable_linear_ordered_ring`
@[simp] lemma abs_two : abs (2:Ξ±) = 2 :=
abs_of_pos zero_lt_two
end decidable_linear_ordered_comm_ring
/-- Extend `nonneg_add_comm_group` to support ordered rings
specified by their nonnegative elements -/
class nonneg_ring (Ξ± : Type*) extends ring Ξ±, nonneg_add_comm_group Ξ±, nontrivial Ξ± :=
(one_pos : pos 1)
(mul_nonneg : β {a b}, nonneg a β nonneg b β nonneg (a * b))
(mul_pos : β {a b}, pos a β pos b β pos (a * b))
/-- Extend `nonneg_add_comm_group` to support linearly ordered rings
specified by their nonnegative elements -/
class linear_nonneg_ring (Ξ± : Type*) extends domain Ξ±, nonneg_add_comm_group Ξ± :=
(one_pos : pos 1)
(mul_nonneg : β {a b}, nonneg a β nonneg b β nonneg (a * b))
(nonneg_total : β a, nonneg a β¨ nonneg (-a))
namespace nonneg_ring
open nonneg_add_comm_group
variable [nonneg_ring Ξ±]
@[priority 100] -- see Note [lower instance priority]
instance to_ordered_ring : ordered_ring Ξ± :=
{ zero_lt_one := begin dsimp [(<), preorder.lt, partial_order.lt], convert one_pos, exact sub_zero _, end,
mul_pos := Ξ» a b, by simp [pos_def.symm]; exact mul_pos,
..βΉnonneg_ring Ξ±βΊ, ..(infer_instance : ordered_add_comm_group Ξ±) }
/-- `to_linear_nonneg_ring` shows that a `nonneg_ring` with a total order is a `domain`,
hence a `linear_nonneg_ring`. -/
def to_linear_nonneg_ring
(nonneg_total : β a : Ξ±, nonneg a β¨ nonneg (-a))
: linear_nonneg_ring Ξ± :=
{ nonneg_total := nonneg_total,
eq_zero_or_eq_zero_of_mul_eq_zero :=
suffices β {a} b : Ξ±, nonneg a β a * b = 0 β a = 0 β¨ b = 0,
from Ξ» a b, (nonneg_total a).elim (this b)
(Ξ» na, by simpa using this b na),
suffices β {a b : Ξ±}, nonneg a β nonneg b β a * b = 0 β a = 0 β¨ b = 0,
from Ξ» a b na, (nonneg_total b).elim (this na)
(Ξ» nb, by simpa using this na nb),
Ξ» a b na nb z, classical.by_cases
(Ξ» nna : nonneg (-a), or.inl (nonneg_antisymm na nna))
(Ξ» pa, classical.by_cases
(Ξ» nnb : nonneg (-b), or.inr (nonneg_antisymm nb nnb))
(Ξ» pb, absurd z $ ne_of_gt $ pos_def.1 $ mul_pos
((pos_iff _).2 β¨na, paβ©)
((pos_iff _).2 β¨nb, pbβ©))),
..βΉnonneg_ring Ξ±βΊ }
end nonneg_ring
namespace linear_nonneg_ring
open nonneg_add_comm_group
variable [linear_nonneg_ring Ξ±]
@[priority 100] -- see Note [lower instance priority]
instance to_nonneg_ring : nonneg_ring Ξ± :=
{ mul_pos := Ξ» a b pa pb,
let β¨a1, a2β© := (pos_iff a).1 pa,
β¨b1, b2β© := (pos_iff b).1 pb in
have ab : nonneg (a * b), from mul_nonneg a1 b1,
(pos_iff _).2 β¨ab, Ξ» hn,
have a * b = 0, from nonneg_antisymm ab hn,
(eq_zero_or_eq_zero_of_mul_eq_zero _ _ this).elim
(ne_of_gt (pos_def.1 pa))
(ne_of_gt (pos_def.1 pb))β©,
..βΉlinear_nonneg_ring Ξ±βΊ }
@[priority 100] -- see Note [lower instance priority]
instance to_linear_order : linear_order Ξ± :=
{ le_total := nonneg_total_iff.1 nonneg_total,
..βΉlinear_nonneg_ring Ξ±βΊ, ..(infer_instance : ordered_add_comm_group Ξ±) }
@[priority 100] -- see Note [lower instance priority]
instance to_linear_ordered_ring : linear_ordered_ring Ξ± :=
{ mul_pos := by simp [pos_def.symm]; exact @nonneg_ring.mul_pos _ _,
zero_lt_one := lt_of_not_ge $ Ξ» (h : nonneg (0 - 1)), begin
rw [zero_sub] at h,
have := mul_nonneg h h, simp at this,
exact zero_ne_one (nonneg_antisymm this h).symm
end,
..βΉlinear_nonneg_ring Ξ±βΊ, ..(infer_instance : ordered_add_comm_group Ξ±),
..(infer_instance : linear_order Ξ±) }
/-- Convert a `linear_nonneg_ring` with a commutative multiplication and
decidable non-negativity into a `decidable_linear_ordered_comm_ring` -/
def to_decidable_linear_ordered_comm_ring
[decidable_pred (@nonneg Ξ± _)]
[comm : @is_commutative Ξ± (*)]
: decidable_linear_ordered_comm_ring Ξ± :=
{ decidable_le := by apply_instance,
decidable_lt := by apply_instance,
mul_comm := is_commutative.comm,
..@linear_nonneg_ring.to_linear_ordered_ring _ _ }
end linear_nonneg_ring
/-- A canonically ordered commutative semiring is an ordered, commutative semiring
in which `a β€ b` iff there exists `c` with `b = a + c`. This is satisfied by the
natural numbers, for example, but not the integers or other ordered groups. -/
class canonically_ordered_comm_semiring (Ξ± : Type*) extends
canonically_ordered_add_monoid Ξ±, comm_semiring Ξ±, nontrivial Ξ± :=
(eq_zero_or_eq_zero_of_mul_eq_zero : β a b : Ξ±, a * b = 0 β a = 0 β¨ b = 0)
namespace canonically_ordered_semiring
variables [canonically_ordered_comm_semiring Ξ±] {a b : Ξ±}
open canonically_ordered_add_monoid (le_iff_exists_add)
@[priority 100] -- see Note [lower instance priority]
instance canonically_ordered_comm_semiring.to_no_zero_divisors :
no_zero_divisors Ξ± :=
β¨canonically_ordered_comm_semiring.eq_zero_or_eq_zero_of_mul_eq_zeroβ©
lemma mul_le_mul {a b c d : Ξ±} (hab : a β€ b) (hcd : c β€ d) : a * c β€ b * d :=
begin
rcases (le_iff_exists_add _ _).1 hab with β¨b, rflβ©,
rcases (le_iff_exists_add _ _).1 hcd with β¨d, rflβ©,
suffices : a * c β€ a * c + (a * d + b * c + b * d), by simpa [mul_add, add_mul, _root_.add_assoc],
exact (le_iff_exists_add _ _).2 β¨_, rflβ©
end
lemma mul_le_mul_left' {b c : Ξ±} (h : b β€ c) (a : Ξ±) : a * b β€ a * c :=
mul_le_mul (le_refl a) h
lemma mul_le_mul_right' {b c : Ξ±} (h : b β€ c) (a : Ξ±) : b * a β€ c * a :=
mul_le_mul h (le_refl a)
/-- A version of `zero_lt_one : 0 < 1` for a `canonically_ordered_comm_semiring`. -/
lemma zero_lt_one : (0:Ξ±) < 1 := (zero_le 1).lt_of_ne zero_ne_one
lemma mul_pos : 0 < a * b β (0 < a) β§ (0 < b) :=
by simp only [zero_lt_iff_ne_zero, ne.def, mul_eq_zero, not_or_distrib]
end canonically_ordered_semiring
namespace with_top
instance [nonempty Ξ±] : nontrivial (with_top Ξ±) :=
option.nontrivial
variable [decidable_eq Ξ±]
section has_mul
variables [has_zero Ξ±] [has_mul Ξ±]
instance : mul_zero_class (with_top Ξ±) :=
{ zero := 0,
mul := Ξ»m n, if m = 0 β¨ n = 0 then 0 else m.bind (Ξ»a, n.bind $ Ξ»b, β(a * b)),
zero_mul := assume a, if_pos $ or.inl rfl,
mul_zero := assume a, if_pos $ or.inr rfl }
lemma mul_def {a b : with_top Ξ±} :
a * b = if a = 0 β¨ b = 0 then 0 else a.bind (Ξ»a, b.bind $ Ξ»b, β(a * b)) := rfl
@[simp] lemma mul_top {a : with_top Ξ±} (h : a β 0) : a * β€ = β€ :=
by cases a; simp [mul_def, h]; refl
@[simp] lemma top_mul {a : with_top Ξ±} (h : a β 0) : β€ * a = β€ :=
by cases a; simp [mul_def, h]; refl
@[simp] lemma top_mul_top : (β€ * β€ : with_top Ξ±) = β€ :=
top_mul top_ne_zero
end has_mul
section mul_zero_class
variables [mul_zero_class Ξ±]
@[norm_cast] lemma coe_mul {a b : Ξ±} : (β(a * b) : with_top Ξ±) = a * b :=
decidable.by_cases (assume : a = 0, by simp [this]) $ assume ha,
decidable.by_cases (assume : b = 0, by simp [this]) $ assume hb,
by { simp [*, mul_def], refl }
lemma mul_coe {b : Ξ±} (hb : b β 0) : β{a : with_top Ξ±}, a * b = a.bind (Ξ»a:Ξ±, β(a * b))
| none := show (if (β€:with_top Ξ±) = 0 β¨ (b:with_top Ξ±) = 0 then 0 else β€ : with_top Ξ±) = β€,
by simp [hb]
| (some a) := show βa * βb = β(a * b), from coe_mul.symm
@[simp] lemma mul_eq_top_iff {a b : with_top Ξ±} : a * b = β€ β (a β 0 β§ b = β€) β¨ (a = β€ β§ b β 0) :=
begin
cases a; cases b; simp only [none_eq_top, some_eq_coe],
{ simp [β coe_mul] },
{ suffices : β€ * (b : with_top Ξ±) = β€ β b β 0, by simpa,
by_cases hb : b = 0; simp [hb] },
{ suffices : (a : with_top Ξ±) * β€ = β€ β a β 0, by simpa,
by_cases ha : a = 0; simp [ha] },
{ simp [β coe_mul] }
end
end mul_zero_class
section no_zero_divisors
variables [mul_zero_class Ξ±] [no_zero_divisors Ξ±]
instance : no_zero_divisors (with_top Ξ±) :=
β¨Ξ» a b, by cases a; cases b; dsimp [mul_def]; split_ifs;
simp [*, none_eq_top, some_eq_coe, mul_eq_zero] at *β©
end no_zero_divisors
variables [canonically_ordered_comm_semiring Ξ±]
private lemma comm (a b : with_top Ξ±) : a * b = b * a :=
begin
by_cases ha : a = 0, { simp [ha] },
by_cases hb : b = 0, { simp [hb] },
simp [ha, hb, mul_def, option.bind_comm a b, mul_comm]
end
private lemma distrib' (a b c : with_top Ξ±) : (a + b) * c = a * c + b * c :=
begin
cases c,
{ show (a + b) * β€ = a * β€ + b * β€,
by_cases ha : a = 0; simp [ha] },
{ show (a + b) * c = a * c + b * c,
by_cases hc : c = 0, { simp [hc] },
simp [mul_coe hc], cases a; cases b,
repeat { refl <|> exact congr_arg some (add_mul _ _ _) } }
end
private lemma assoc (a b c : with_top Ξ±) : (a * b) * c = a * (b * c) :=
begin
cases a,
{ by_cases hb : b = 0; by_cases hc : c = 0;
simp [*, none_eq_top] },
cases b,
{ by_cases ha : a = 0; by_cases hc : c = 0;
simp [*, none_eq_top, some_eq_coe] },
cases c,
{ by_cases ha : a = 0; by_cases hb : b = 0;
simp [*, none_eq_top, some_eq_coe] },
simp [some_eq_coe, coe_mul.symm, mul_assoc]
end
private lemma one_mul' : βa : with_top Ξ±, 1 * a = a
| none := show ((1:Ξ±) : with_top Ξ±) * β€ = β€, by simp [-with_top.coe_one]
| (some a) := show ((1:Ξ±) : with_top Ξ±) * a = a, by simp [coe_mul.symm, -with_top.coe_one]
instance : canonically_ordered_comm_semiring (with_top Ξ±) :=
{ one := (1 : Ξ±),
right_distrib := distrib',
left_distrib := assume a b c, by rw [comm, distrib', comm b, comm c]; refl,
mul_assoc := assoc,
mul_comm := comm,
one_mul := one_mul',
mul_one := assume a, by rw [comm, one_mul'],
.. with_top.add_comm_monoid, .. with_top.mul_zero_class, .. with_top.canonically_ordered_add_monoid,
.. with_top.no_zero_divisors, .. with_top.nontrivial }
end with_top
|
d089d8fc7c3cf1c498a2de7bc344560c71765445 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/calc_heq_symm.lean | 00483999fd4e8051057a1a31d03e49bc4a284046 | [
"Apache-2.0"
] | permissive | soonhokong/lean | cb8aa01055ffe2af0fb99a16b4cda8463b882cd1 | 38607e3eb57f57f77c0ac114ad169e9e4262e24f | refs/heads/master | 1,611,187,284,081 | 1,450,766,737,000 | 1,476,122,547,000 | 11,513,992 | 2 | 0 | null | 1,401,763,102,000 | 1,374,182,235,000 | C++ | UTF-8 | Lean | false | false | 303 | lean | import logic
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 : Hβ
... == b : Hβ
... == aβ : Hβ
... = aβ : Hβ
reveal tst
print definition tst
|
828b3cd9f608cc9ec2fb95aea30dda12b7926b7c | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/category_theory/limits/shapes/images.lean | b295301cc6ec70780125915fc164a7767ecff732 | [
"Apache-2.0"
] | permissive | dupuisf/mathlib | 62de4ec6544bf3b79086afd27b6529acfaf2c1bb | 8582b06b0a5d06c33ee07d0bdf7c646cae22cf36 | refs/heads/master | 1,669,494,854,016 | 1,595,692,409,000 | 1,595,692,409,000 | 272,046,630 | 0 | 0 | Apache-2.0 | 1,592,066,143,000 | 1,592,066,142,000 | null | UTF-8 | Lean | false | false | 19,728 | lean | /-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Markus Himmel
-/
import category_theory.limits.shapes.equalizers
import category_theory.limits.shapes.strong_epi
/-!
# Categorical images
We define the categorical image of `f` as a factorisation `f = e β« m` through a monomorphism `m`,
so that `m` factors through the `m'` in any other such factorisation.
## Main definitions
* A `mono_factorisation` is a factorisation `f = e β« m`, where `m` is a monomorphism
* `is_image F` means that a given mono factorisation `F` has the universal property of the image.
* `has_image f` means that we have chosen an image for the morphism `f : X βΆ Y`.
* In this case, `image f` is the image object, `image.ΞΉ f : image f βΆ Y` is the monomorphism `m`
of the factorisation and `factor_thru_image f : X βΆ image f` is the morphism `e`.
* `has_images C` means that every morphism in `C` has an image.
* Let `f : X βΆ Y` and `g : P βΆ Q` be morphisms in `C`, which we will represent as objects of the
arrow category `arrow C`. Then `sq : f βΆ g` is a commutative square in `C`. If `f` and `g` have
images, then `has_image_map sq` represents the fact that there is a morphism
`i : image f βΆ image g` making the diagram
X ----β image f ----β Y
| | |
| | |
β β β
P ----β image g ----β Q
commute, where the top row is the image factorisation of `f`, the bottom row is the image
factorisation of `g`, and the outer rectangle is the commutative square `sq`.
* If a category `has_images`, then `has_image_maps` means that every commutative square admits an
image map.
* If a category `has_images`, then `has_strong_epi_images` means that the morphism to the image is
always a strong epimorphism.
## Main statements
* When `C` has equalizers, the morphism `e` appearing in an image factorisation is an epimorphism.
* When `C` has strong epi images, then these images admit image maps.
## Future work
* TODO: coimages, and abelian categories.
* TODO: connect this with existing working in the group theory and ring theory libraries.
-/
universes v u
open category_theory
open category_theory.limits.walking_parallel_pair
namespace category_theory.limits
variables {C : Type u} [category.{v} C]
variables {X Y : C} (f : X βΆ Y)
/-- A factorisation of a morphism `f = e β« m`, with `m` monic. -/
structure mono_factorisation (f : X βΆ Y) :=
(I : C)
(m : I βΆ Y)
[m_mono : mono m]
(e : X βΆ I)
(fac' : e β« m = f . obviously)
restate_axiom mono_factorisation.fac'
attribute [simp, reassoc] mono_factorisation.fac
attribute [instance] mono_factorisation.m_mono
attribute [instance] mono_factorisation.m_mono
namespace mono_factorisation
/-- The obvious factorisation of a monomorphism through itself. -/
def self [mono f] : mono_factorisation f :=
{ I := X,
m := f,
e := π X }
-- I'm not sure we really need this, but the linter says that an inhabited instance ought to exist...
instance [mono f] : inhabited (mono_factorisation f) := β¨self fβ©
/-- The morphism `m` in a factorisation `f = e β« m` through a monomorphism is uniquely determined. -/
@[ext]
lemma ext
{F F' : mono_factorisation f} (hI : F.I = F'.I) (hm : F.m = (eq_to_hom hI) β« F'.m) : F = F' :=
begin
cases F, cases F',
cases hI,
simp at hm,
dsimp at F_fac' F'_fac',
congr,
{ assumption },
{ resetI, apply (cancel_mono F_m).1,
rw [F_fac', hm, F'_fac'], }
end
end mono_factorisation
variable {f}
/-- Data exhibiting that a given factorisation through a mono is initial. -/
structure is_image (F : mono_factorisation f) :=
(lift : Ξ (F' : mono_factorisation f), F.I βΆ F'.I)
(lift_fac' : Ξ (F' : mono_factorisation f), lift F' β« F'.m = F.m . obviously)
restate_axiom is_image.lift_fac'
attribute [simp, reassoc] is_image.lift_fac
@[simp, reassoc] lemma is_image.fac_lift {F : mono_factorisation f} (hF : is_image F)
(F' : mono_factorisation f) : F.e β« hF.lift F' = F'.e :=
(cancel_mono F'.m).1 $ by simp
variable (f)
namespace is_image
/-- The trivial factorisation of a monomorphism satisfies the universal property. -/
@[simps]
def self [mono f] : is_image (mono_factorisation.self f) :=
{ lift := Ξ» F', F'.e }
instance [mono f] : inhabited (is_image (mono_factorisation.self f)) :=
β¨self fβ©
variable {f}
/-- Two factorisations through monomorphisms satisfying the universal property
must factor through isomorphic objects. -/
-- TODO this is another good candidate for a future `unique_up_to_canonical_iso`.
@[simps]
def iso_ext {F F' : mono_factorisation f} (hF : is_image F) (hF' : is_image F') : F.I β
F'.I :=
{ hom := hF.lift F',
inv := hF'.lift F,
hom_inv_id' := (cancel_mono F.m).1 (by simp),
inv_hom_id' := (cancel_mono F'.m).1 (by simp) }
end is_image
/-- Data exhibiting that a morphism `f` has an image. -/
class has_image (f : X βΆ Y) :=
(F : mono_factorisation f)
(is_image : is_image F)
section
variable [has_image f]
/-- The chosen factorisation of `f` through a monomorphism. -/
def image.mono_factorisation : mono_factorisation f := has_image.F
/-- The witness of the universal property for the chosen factorisation of `f` through a monomorphism. -/
def image.is_image : is_image (image.mono_factorisation f) := has_image.is_image
/-- The categorical image of a morphism. -/
def image : C := (image.mono_factorisation f).I
/-- The inclusion of the image of a morphism into the target. -/
def image.ΞΉ : image f βΆ Y := (image.mono_factorisation f).m
@[simp] lemma image.as_ΞΉ : (image.mono_factorisation f).m = image.ΞΉ f := rfl
instance : mono (image.ΞΉ f) := (image.mono_factorisation f).m_mono
/-- The map from the source to the image of a morphism. -/
def factor_thru_image : X βΆ image f := (image.mono_factorisation f).e
/-- Rewrite in terms of the `factor_thru_image` interface. -/
@[simp]
lemma as_factor_thru_image : (image.mono_factorisation f).e = factor_thru_image f := rfl
@[simp, reassoc]
lemma image.fac : factor_thru_image f β« image.ΞΉ f = f := (image.mono_factorisation f).fac'
variable {f}
/-- Any other factorisation of the morphism `f` through a monomorphism receives a map from the image. -/
def image.lift (F' : mono_factorisation f) : image f βΆ F'.I := (image.is_image f).lift F'
@[simp, reassoc]
lemma image.lift_fac (F' : mono_factorisation f) : image.lift F' β« F'.m = image.ΞΉ f :=
(image.is_image f).lift_fac' F'
@[simp, reassoc]
lemma image.fac_lift (F' : mono_factorisation f) : factor_thru_image f β« image.lift F' = F'.e :=
(image.is_image f).fac_lift F'
-- TODO we could put a category structure on `mono_factorisation f`,
-- with the morphisms being `g : I βΆ I'` commuting with the `m`s
-- (they then automatically commute with the `e`s)
-- and show that an `image_of f` gives an initial object there
-- (uniqueness of the lift comes for free).
instance lift_mono (F' : mono_factorisation f) : mono (image.lift F') :=
begin
split, intros Z a b w,
have w' : a β« image.ΞΉ f = b β« image.ΞΉ f :=
calc a β« image.ΞΉ f = a β« (image.lift F' β« F'.m) : by simp
... = (a β« image.lift F') β« F'.m : by rw [category.assoc]
... = (b β« image.lift F') β« F'.m : by rw w
... = b β« (image.lift F' β« F'.m) : by rw [βcategory.assoc]
... = b β« image.ΞΉ f : by simp,
exact (cancel_mono (image.ΞΉ f)).1 w',
end
lemma has_image.uniq
(F' : mono_factorisation f) (l : image f βΆ F'.I) (w : l β« F'.m = image.ΞΉ f) :
l = image.lift F' :=
(cancel_mono F'.m).1 (by simp [w])
end
section
variables (C)
/-- `has_images` represents a choice of image for every morphism -/
class has_images :=
(has_image : Ξ {X Y : C} (f : X βΆ Y), has_image f)
attribute [instance, priority 100] has_images.has_image
end
section
variables (f) [has_image f]
/-- The image of a monomorphism is isomorphic to the source. -/
def image_mono_iso_source [mono f] : image f β
X :=
is_image.iso_ext (image.is_image f) (is_image.self f)
@[simp, reassoc]
lemma image_mono_iso_source_inv_ΞΉ [mono f] : (image_mono_iso_source f).inv β« image.ΞΉ f = f :=
by simp [image_mono_iso_source]
@[simp, reassoc]
lemma image_mono_iso_source_hom_self [mono f] : (image_mono_iso_source f).hom β« f = image.ΞΉ f :=
begin
conv { to_lhs, congr, skip, rw βimage_mono_iso_source_inv_ΞΉ f, },
rw [βcategory.assoc, iso.hom_inv_id, category.id_comp],
end
-- This is the proof that `factor_thru_image f` is an epimorphism
-- from https://en.wikipedia.org/wiki/Image_(category_theory), which is in turn taken from:
-- Mitchell, Barry (1965), Theory of categories, MR 0202787, p.12, Proposition 10.1
@[ext]
lemma image.ext {W : C} {g h : image f βΆ W} [has_limit (parallel_pair g h)]
(w : factor_thru_image f β« g = factor_thru_image f β« h) :
g = h :=
begin
let q := equalizer.ΞΉ g h,
let e' := equalizer.lift _ w,
let F' : mono_factorisation f :=
{ I := equalizer g h,
m := q β« image.ΞΉ f,
m_mono := by apply mono_comp,
e := e' },
let v := image.lift F',
have tβ : v β« q β« image.ΞΉ f = image.ΞΉ f := image.lift_fac F',
have t : v β« q = π (image f) :=
(cancel_mono_id (image.ΞΉ f)).1 (by { convert tβ using 1, rw category.assoc }),
-- The proof from wikipedia next proves `q β« v = π _`,
-- and concludes that `equalizer g h β
image f`,
-- but this isn't necessary.
calc g = π (image f) β« g : by rw [category.id_comp]
... = v β« q β« g : by rw [βt, category.assoc]
... = v β« q β« h : by rw [equalizer.condition g h]
... = π (image f) β« h : by rw [βcategory.assoc, t]
... = h : by rw [category.id_comp]
end
instance [Ξ {Z : C} (g h : image f βΆ Z), has_limit (parallel_pair g h)] :
epi (factor_thru_image f) :=
β¨Ξ» Z g h w, image.ext f wβ©
lemma epi_image_of_epi {X Y : C} (f : X βΆ Y) [has_image f] [E : epi f] : epi (image.ΞΉ f) :=
begin
rw βimage.fac f at E,
resetI,
exact epi_of_epi (factor_thru_image f) (image.ΞΉ f),
end
lemma epi_of_epi_image {X Y : C} (f : X βΆ Y) [has_image f]
[epi (image.ΞΉ f)] [epi (factor_thru_image f)] : epi f :=
by { rw [βimage.fac f], apply epi_comp, }
end
section
variables {f} {f' : X βΆ Y} [has_image f] [has_image f']
/--
An equation between morphisms gives a comparison map between the images
(which momentarily we prove is an iso).
-/
def image.eq_to_hom (h : f = f') : image f βΆ image f' :=
image.lift
{ I := image f',
m := image.ΞΉ f',
e := factor_thru_image f', }.
instance (h : f = f') : is_iso (image.eq_to_hom h) :=
{ inv := image.eq_to_hom h.symm,
hom_inv_id' := (cancel_mono (image.ΞΉ f)).1 (by simp [image.eq_to_hom]),
inv_hom_id' := (cancel_mono (image.ΞΉ f')).1 (by simp [image.eq_to_hom]), }
/-- An equation between morphisms gives an isomorphism between the images. -/
def image.eq_to_iso (h : f = f') : image f β
image f' := as_iso (image.eq_to_hom h)
/--
As long as the category has equalizers,
the image inclusion maps commute with `image.eq_to_iso`.
-/
lemma image.eq_fac [has_equalizers C] (h : f = f') :
image.ΞΉ f = (image.eq_to_iso h).hom β« image.ΞΉ f' :=
by { ext, simp [image.eq_to_iso, image.eq_to_hom], }
end
section
variables {Z : C} (g : Y βΆ Z)
/-- The comparison map `image (f β« g) βΆ image g`. -/
def image.pre_comp [has_image g] [has_image (f β« g)] : image (f β« g) βΆ image g :=
image.lift
{ I := image g,
m := image.ΞΉ g,
e := f β« factor_thru_image g }
/--
The two step comparison map
`image (f β« (g β« h)) βΆ image (g β« h) βΆ image h`
agrees with the one step comparison map
`image (f β« (g β« h)) β
image ((f β« g) β« h) βΆ image h`.
-/
lemma image.pre_comp_comp {W : C} (h : Z βΆ W)
[has_image (g β« h)] [has_image (f β« g β« h)]
[has_image h] [has_image ((f β« g) β« h)] :
image.pre_comp f (g β« h) β« image.pre_comp g h =
image.eq_to_hom (category.assoc f g h).symm β« (image.pre_comp (f β« g) h) :=
begin
apply (cancel_mono (image.ΞΉ h)).1,
simp [image.pre_comp, image.eq_to_hom],
end
-- Note that in general we don't have the other comparison map you might expect
-- `image f βΆ image (f β« g)`.
end
end category_theory.limits
namespace category_theory.limits
variables {C : Type u} [category.{v} C]
section
instance {X Y : C} (f : X βΆ Y) [has_image f] : has_image (arrow.mk f).hom :=
show has_image f, by apply_instance
end
section has_image_map
/-- An image map is a morphism `image f β image g` fitting into a commutative square and satisfying
the obvious commutativity conditions. -/
class has_image_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f βΆ g) :=
(map : image f.hom βΆ image g.hom)
(map_ΞΉ' : map β« image.ΞΉ g.hom = image.ΞΉ f.hom β« sq.right . obviously)
restate_axiom has_image_map.map_ΞΉ'
attribute [simp, reassoc] has_image_map.map_ΞΉ
@[simp, reassoc]
lemma has_image_map.factor_map {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f βΆ g)
[has_image_map sq] :
factor_thru_image f.hom β« has_image_map.map sq = sq.left β« factor_thru_image g.hom :=
(cancel_mono (image.ΞΉ g.hom)).1 $ by simp [arrow.w]
variables {f g : arrow C} [has_image f.hom] [has_image g.hom] (sq : f βΆ g)
section
local attribute [ext] has_image_map
instance : subsingleton (has_image_map sq) :=
subsingleton.intro $ Ξ» a b, has_image_map.ext a b $ (cancel_mono (image.ΞΉ g.hom)).1 $
by simp only [has_image_map.map_ΞΉ]
end
variable [has_image_map sq]
/-- The map on images induced by a commutative square. -/
abbreviation image.map : image f.hom βΆ image g.hom := has_image_map.map sq
lemma image.factor_map :
factor_thru_image f.hom β« image.map sq = sq.left β« factor_thru_image g.hom :=
by simp
lemma image.map_ΞΉ : image.map sq β« image.ΞΉ g.hom = image.ΞΉ f.hom β« sq.right :=
by simp
lemma image.map_hom_mk'_ΞΉ {X Y P Q : C} {k : X βΆ Y} [has_image k] {l : P βΆ Q} [has_image l]
{m : X βΆ P} {n : Y βΆ Q} (w : m β« l = k β« n) [has_image_map (arrow.hom_mk' w)] :
image.map (arrow.hom_mk' w) β« image.ΞΉ l = image.ΞΉ k β« n :=
image.map_ΞΉ _
section
variables {h : arrow C} [has_image h.hom] (sq' : g βΆ h)
variables [has_image_map sq']
/-- Image maps for composable commutative squares induce an image map in the composite square. -/
def has_image_map_comp : has_image_map (sq β« sq') :=
{ map := image.map sq β« image.map sq' }
@[simp]
lemma image.map_comp [has_image_map (sq β« sq')] :
image.map (sq β« sq') = image.map sq β« image.map sq' :=
show (has_image_map.map (sq β« sq')) = (has_image_map_comp sq sq').map, by congr
end
section
variables (f)
/-- The identity `image f βΆ image f` fits into the commutative square represented by the identity
morphism `π f` in the arrow category. -/
def has_image_map_id : has_image_map (π f) :=
{ map := π (image f.hom) }
@[simp]
lemma image.map_id [has_image_map (π f)] : image.map (π f) = π (image f.hom) :=
show (image.map (π f)) = (has_image_map_id f).map, by congr
end
end has_image_map
section
variables (C) [has_images C]
/-- If a category `has_image_maps`, then all commutative squares induce morphisms on images. -/
class has_image_maps :=
(has_image_map : Ξ {f g : arrow C} (st : f βΆ g), has_image_map st)
attribute [instance, priority 100] has_image_maps.has_image_map
end
section has_image_maps
variables [has_images C] [has_image_maps C]
/-- The functor from the arrow category of `C` to `C` itself that maps a morphism to its image
and a commutative square to the induced morphism on images. -/
@[simps]
def im : arrow C β₯€ C :=
{ obj := Ξ» f, image f.hom,
map := Ξ» _ _ st, image.map st }
end has_image_maps
section strong_epi_mono_factorisation
/-- A strong epi-mono factorisation is a decomposition `f = e β« m` with `e` a strong epimorphism
and `m` a monomorphism. -/
structure strong_epi_mono_factorisation {X Y : C} (f : X βΆ Y) extends mono_factorisation f :=
[e_strong_epi : strong_epi e]
attribute [instance] strong_epi_mono_factorisation.e_strong_epi
/-- Satisfying the inhabited linter -/
instance strong_epi_mono_factorisation_inhabited {X Y : C} (f : X βΆ Y) [strong_epi f] :
inhabited (strong_epi_mono_factorisation f) :=
β¨β¨β¨Y, π Y, f, by simpβ©β©β©
/-- A mono factorisation coming from a strong epi-mono factorisation always has the universal
property of the image. -/
def strong_epi_mono_factorisation.to_mono_is_image {X Y : C} {f : X βΆ Y}
(F : strong_epi_mono_factorisation f) : is_image F.to_mono_factorisation :=
{ lift := Ξ» G, arrow.lift $ arrow.hom_mk' $
show G.e β« G.m = F.e β« F.m, by rw [F.to_mono_factorisation.fac, G.fac] }
variable (C)
/-- A category has strong epi-mono factorisations if every morphism admits a strong epi-mono
factorisation. -/
class has_strong_epi_mono_factorisations :=
(has_fac : Ξ {X Y : C} (f : X βΆ Y), strong_epi_mono_factorisation f)
@[priority 100]
instance has_images_of_has_strong_epi_mono_factorisations
[has_strong_epi_mono_factorisations C] : has_images C :=
{ has_image := Ξ» X Y f,
let F' := has_strong_epi_mono_factorisations.has_fac f in
{ F := F'.to_mono_factorisation,
is_image := F'.to_mono_is_image } }
end strong_epi_mono_factorisation
section has_strong_epi_images
variables (C) [has_images C]
/-- A category has strong epi images if it has all images and `factor_thru_image f` is a strong
epimorphism for all `f`. -/
class has_strong_epi_images :=
(strong_factor_thru_image : Ξ {X Y : C} (f : X βΆ Y), strong_epi (factor_thru_image f))
attribute [instance] has_strong_epi_images.strong_factor_thru_image
end has_strong_epi_images
section has_strong_epi_images
/-- If we constructed our images from strong epi-mono factorisations, then these images are
strong epi images. -/
@[priority 100]
instance has_strong_epi_images_of_has_strong_epi_mono_factorisations
[has_strong_epi_mono_factorisations C] : has_strong_epi_images C :=
{ strong_factor_thru_image := Ξ» X Y f,
(has_strong_epi_mono_factorisations.has_fac f).e_strong_epi }
end has_strong_epi_images
section has_strong_epi_images
variables [has_images C]
/-- A category with strong epi images has image maps. The construction is taken from Borceux,
Handbook of Categorical Algebra 1, Proposition 4.4.5. -/
@[priority 100]
instance has_image_maps_of_has_strong_epi_images [has_strong_epi_images C] :
has_image_maps C :=
{ has_image_map := Ξ» f g st,
let I := image (image.ΞΉ f.hom β« st.right) in
let I' := image (st.left β« factor_thru_image g.hom) in
let upper : strong_epi_mono_factorisation (f.hom β« st.right) :=
{ I := I,
e := factor_thru_image f.hom β« factor_thru_image (image.ΞΉ f.hom β« st.right),
m := image.ΞΉ (image.ΞΉ f.hom β« st.right),
e_strong_epi := strong_epi_comp _ _,
m_mono := by apply_instance } in
let lower : strong_epi_mono_factorisation (f.hom β« st.right) :=
{ I := I',
e := factor_thru_image (st.left β« factor_thru_image g.hom),
m := image.ΞΉ (st.left β« factor_thru_image g.hom) β« image.ΞΉ g.hom,
fac' := by simp [arrow.w],
e_strong_epi := by apply_instance,
m_mono := mono_comp _ _ } in
let s : I βΆ I' := is_image.lift upper.to_mono_is_image lower.to_mono_factorisation in
{ map := factor_thru_image (image.ΞΉ f.hom β« st.right) β« s β«
image.ΞΉ (st.left β« factor_thru_image g.hom),
map_ΞΉ' := by rw [category.assoc, category.assoc,
is_image.lift_fac upper.to_mono_is_image lower.to_mono_factorisation, image.fac] } }
end has_strong_epi_images
end category_theory.limits
|
157f69e438f1d8c890edfcbde07e8bd125aeac3e | 432d948a4d3d242fdfb44b81c9e1b1baacd58617 | /src/category_theory/limits/shapes/zero.lean | 0cc7edcdc1c256cbad41c0a15d0e5734dc717913 | [
"Apache-2.0"
] | permissive | JLimperg/aesop3 | 306cc6570c556568897ed2e508c8869667252e8a | a4a116f650cc7403428e72bd2e2c4cda300fe03f | refs/heads/master | 1,682,884,916,368 | 1,620,320,033,000 | 1,620,320,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,129 | 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.limits.shapes.terminal
import category_theory.limits.shapes.binary_products
import category_theory.limits.shapes.products
import category_theory.limits.shapes.images
import category_theory.isomorphism_classes
/-!
# Zero morphisms and zero objects
A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space,
and compositions of zero morphisms with anything give the zero morphism. (Notice this is extra
structure, not merely a property.)
A category "has a zero object" if it has an object which is both initial and terminal. Having a
zero object provides zero morphisms, as the unique morphisms factoring through the zero object.
## References
* https://en.wikipedia.org/wiki/Zero_morphism
* [F. Borceux, *Handbook of Categorical Algebra 2*][borceux-vol2]
-/
noncomputable theory
universes v u
open category_theory
open category_theory.category
namespace category_theory.limits
variables (C : Type u) [category.{v} C]
/-- A category "has zero morphisms" if there is a designated "zero morphism" in each morphism space,
and compositions of zero morphisms with anything give the zero morphism. -/
class has_zero_morphisms :=
[has_zero : Ξ X Y : C, has_zero (X βΆ Y)]
(comp_zero' : β {X Y : C} (f : X βΆ Y) (Z : C), f β« (0 : Y βΆ Z) = (0 : X βΆ Z) . obviously)
(zero_comp' : β (X : C) {Y Z : C} (f : Y βΆ Z), (0 : X βΆ Y) β« f = (0 : X βΆ Z) . obviously)
attribute [instance] has_zero_morphisms.has_zero
restate_axiom has_zero_morphisms.comp_zero'
restate_axiom has_zero_morphisms.zero_comp'
variables {C}
@[simp] lemma comp_zero [has_zero_morphisms C] {X Y : C} {f : X βΆ Y} {Z : C} :
f β« (0 : Y βΆ Z) = (0 : X βΆ Z) := has_zero_morphisms.comp_zero f Z
@[simp] lemma zero_comp [has_zero_morphisms C] {X : C} {Y Z : C} {f : Y βΆ Z} :
(0 : X βΆ Y) β« f = (0 : X βΆ Z) := has_zero_morphisms.zero_comp X f
instance has_zero_morphisms_pempty : has_zero_morphisms (discrete pempty) :=
{ has_zero := by tidy }
instance has_zero_morphisms_punit : has_zero_morphisms (discrete punit) :=
{ has_zero := by tidy }
namespace has_zero_morphisms
variables {C}
/-- This lemma will be immediately superseded by `ext`, below. -/
private lemma ext_aux (I J : has_zero_morphisms C)
(w : β X Y : C, (@has_zero_morphisms.has_zero _ _ I X Y).zero =
(@has_zero_morphisms.has_zero _ _ J X Y).zero) : I = J :=
begin
casesI I, casesI J,
congr,
{ ext X Y,
exact w X Y },
{ apply proof_irrel_heq, },
{ apply proof_irrel_heq, }
end
/--
If you're tempted to use this lemma "in the wild", you should probably
carefully consider whether you've made a mistake in allowing two
instances of `has_zero_morphisms` to exist at all.
See, particularly, the note on `zero_morphisms_of_zero_object` below.
-/
lemma ext (I J : has_zero_morphisms C) : I = J :=
begin
apply ext_aux,
intros X Y,
rw β@has_zero_morphisms.comp_zero _ _ I X X (@has_zero_morphisms.has_zero _ _ J X X).zero,
rw @has_zero_morphisms.zero_comp _ _ J,
end
instance : subsingleton (has_zero_morphisms C) :=
β¨extβ©
end has_zero_morphisms
open has_zero_morphisms
section
variables {C} [has_zero_morphisms C]
lemma zero_of_comp_mono {X Y Z : C} {f : X βΆ Y} (g : Y βΆ Z) [mono g] (h : f β« g = 0) : f = 0 :=
by { rw [βzero_comp, cancel_mono] at h, exact h }
lemma zero_of_epi_comp {X Y Z : C} (f : X βΆ Y) {g : Y βΆ Z} [epi f] (h : f β« g = 0) : g = 0 :=
by { rw [βcomp_zero, cancel_epi] at h, exact h }
lemma eq_zero_of_image_eq_zero {X Y : C} {f : X βΆ Y} [has_image f] (w : image.ΞΉ f = 0) : f = 0 :=
by rw [βimage.fac f, w, has_zero_morphisms.comp_zero]
lemma nonzero_image_of_nonzero {X Y : C} {f : X βΆ Y} [has_image f] (w : f β 0) : image.ΞΉ f β 0 :=
Ξ» h, w (eq_zero_of_image_eq_zero h)
end
section
universes v' u'
variables (D : Type u') [category.{v'} D]
variables [has_zero_morphisms D]
instance : has_zero_morphisms (C β₯€ D) :=
{ has_zero := Ξ» F G, β¨{ app := Ξ» X, 0, }β© }
@[simp] lemma zero_app (F G : C β₯€ D) (j : C) : (0 : F βΆ G).app j = 0 := rfl
variables [has_zero_morphisms C]
lemma equivalence_preserves_zero_morphisms (F : C β D) (X Y : C) :
F.functor.map (0 : X βΆ Y) = (0 : F.functor.obj X βΆ F.functor.obj Y) :=
begin
have t : F.functor.map (0 : X βΆ Y) =
F.functor.map (0 : X βΆ Y) β« (0 : F.functor.obj Y βΆ F.functor.obj Y),
{ apply faithful.map_injective (F.inverse),
rw [functor.map_comp, equivalence.inv_fun_map],
dsimp,
rw [zero_comp, comp_zero, zero_comp], },
exact t.trans (by simp)
end
@[simp] lemma is_equivalence_preserves_zero_morphisms (F : C β₯€ D) [is_equivalence F] (X Y : C) :
F.map (0 : X βΆ Y) = 0 :=
by rw [βfunctor.as_equivalence_functor F, equivalence_preserves_zero_morphisms]
end
variables (C)
/-- A category "has a zero object" if it has an object which is both initial and terminal. -/
class has_zero_object :=
(zero : C)
(unique_to : Ξ X : C, unique (zero βΆ X))
(unique_from : Ξ X : C, unique (X βΆ zero))
instance has_zero_object_punit : has_zero_object (discrete punit) :=
{ zero := punit.star,
unique_to := by tidy,
unique_from := by tidy, }
variables {C}
namespace has_zero_object
variables [has_zero_object C]
/--
Construct a `has_zero C` for a category with a zero object.
This can not be a global instance as it will trigger for every `has_zero C` typeclass search.
-/
protected def has_zero : has_zero C :=
{ zero := has_zero_object.zero }
local attribute [instance] has_zero_object.has_zero
local attribute [instance] has_zero_object.unique_to has_zero_object.unique_from
@[ext]
lemma to_zero_ext {X : C} (f g : X βΆ 0) : f = g :=
by rw [(has_zero_object.unique_from X).uniq f, (has_zero_object.unique_from X).uniq g]
@[ext]
lemma from_zero_ext {X : C} (f g : 0 βΆ X) : f = g :=
by rw [(has_zero_object.unique_to X).uniq f, (has_zero_object.unique_to X).uniq g]
instance (X : C) : subsingleton (X β
0) := by tidy
instance {X : C} (f : 0 βΆ X) : mono f :=
{ right_cancellation := Ξ» Z g h w, by ext, }
instance {X : C} (f : X βΆ 0) : epi f :=
{ left_cancellation := Ξ» Z g h w, by ext, }
/-- A category with a zero object has zero morphisms.
It is rarely a good idea to use this. Many categories that have a zero object have zero
morphisms for some other reason, for example from additivity. Library code that uses
`zero_morphisms_of_zero_object` will then be incompatible with these categories because
the `has_zero_morphisms` instances will not be definitionally equal. For this reason library
code should generally ask for an instance of `has_zero_morphisms` separately, even if it already
asks for an instance of `has_zero_objects`. -/
def zero_morphisms_of_zero_object : has_zero_morphisms C :=
{ has_zero := Ξ» X Y,
{ zero := inhabited.default (X βΆ 0) β« inhabited.default (0 βΆ Y) },
zero_comp' := Ξ» X Y Z f, by { dunfold has_zero.zero, rw category.assoc, congr, },
comp_zero' := Ξ» X Y Z f, by { dunfold has_zero.zero, rw βcategory.assoc, congr, }}
/-- A zero object is in particular initial. -/
lemma has_initial : has_initial C :=
has_initial_of_unique 0
/-- A zero object is in particular terminal. -/
lemma has_terminal : has_terminal C :=
has_terminal_of_unique 0
end has_zero_object
section
variables [has_zero_object C] [has_zero_morphisms C]
local attribute [instance] has_zero_object.has_zero
@[simp]
lemma id_zero : π (0 : C) = (0 : 0 βΆ 0) :=
by ext
/-- An arrow ending in the zero object is zero -/
-- This can't be a `simp` lemma because the left hand side would be a metavariable.
lemma zero_of_to_zero {X : C} (f : X βΆ 0) : f = 0 :=
by ext
lemma zero_of_target_iso_zero {X Y : C} (f : X βΆ Y) (i : Y β
0) : f = 0 :=
begin
have h : f = f β« i.hom β« π 0 β« i.inv := by simp only [iso.hom_inv_id, id_comp, comp_id],
simpa using h,
end
/-- An arrow starting at the zero object is zero -/
lemma zero_of_from_zero {X : C} (f : 0 βΆ X) : f = 0 :=
by ext
lemma zero_of_source_iso_zero {X Y : C} (f : X βΆ Y) (i : X β
0) : f = 0 :=
begin
have h : f = i.hom β« π 0 β« i.inv β« f := by simp only [iso.hom_inv_id_assoc, id_comp, comp_id],
simpa using h,
end
lemma zero_of_source_iso_zero' {X Y : C} (f : X βΆ Y) (i : is_isomorphic X 0) : f = 0 :=
zero_of_source_iso_zero f (nonempty.some i)
lemma zero_of_target_iso_zero' {X Y : C} (f : X βΆ Y) (i : is_isomorphic Y 0) : f = 0 :=
zero_of_target_iso_zero f (nonempty.some i)
lemma mono_of_source_iso_zero {X Y : C} (f : X βΆ Y) (i : X β
0) : mono f :=
β¨Ξ» Z g h w, by rw [zero_of_target_iso_zero g i, zero_of_target_iso_zero h i]β©
lemma epi_of_target_iso_zero {X Y : C} (f : X βΆ Y) (i : Y β
0) : epi f :=
β¨Ξ» Z g h w, by rw [zero_of_source_iso_zero g i, zero_of_source_iso_zero h i]β©
/--
An object `X` has `π X = 0` if and only if it is isomorphic to the zero object.
Because `X β
0` contains data (even if a subsingleton), we express this `β` as an `β`.
-/
def id_zero_equiv_iso_zero (X : C) : (π X = 0) β (X β
0) :=
{ to_fun := Ξ» h, { hom := 0, inv := 0, },
inv_fun := Ξ» i, zero_of_target_iso_zero (π X) i,
left_inv := by tidy,
right_inv := by tidy, }
@[simp]
lemma id_zero_equiv_iso_zero_apply_hom (X : C) (h : π X = 0) :
((id_zero_equiv_iso_zero X) h).hom = 0 := rfl
@[simp]
lemma id_zero_equiv_iso_zero_apply_inv (X : C) (h : π X = 0) :
((id_zero_equiv_iso_zero X) h).inv = 0 := rfl
/-- If an object `X` is isomorphic to 0, there's no need to use choice to construct
an explicit isomorphism: the zero morphism suffices. -/
def iso_of_is_isomorphic_zero {X : C} (P : is_isomorphic X 0) : X β
0 :=
{ hom := 0,
inv := 0,
hom_inv_id' :=
begin
casesI P,
rw βP.hom_inv_id,
rw βcategory.id_comp P.inv,
simp,
end,
inv_hom_id' := by simp, }
end
section is_iso
variables [has_zero_morphisms C]
/--
A zero morphism `0 : X βΆ Y` is an isomorphism if and only if
the identities on both `X` and `Y` are zero.
-/
@[simps]
def is_iso_zero_equiv (X Y : C) : is_iso (0 : X βΆ Y) β (π X = 0 β§ π Y = 0) :=
{ to_fun := by { introsI i, rw βis_iso.hom_inv_id (0 : X βΆ Y),
rw βis_iso.inv_hom_id (0 : X βΆ Y), simp },
inv_fun := Ξ» h, β¨β¨(0 : Y βΆ X), by tidyβ©β©,
left_inv := by tidy,
right_inv := by tidy, }
/--
A zero morphism `0 : X βΆ X` is an isomorphism if and only if
the identity on `X` is zero.
-/
def is_iso_zero_self_equiv (X : C) : is_iso (0 : X βΆ X) β (π X = 0) :=
by simpa using is_iso_zero_equiv X X
variables [has_zero_object C]
local attribute [instance] has_zero_object.has_zero
/--
A zero morphism `0 : X βΆ Y` is an isomorphism if and only if
`X` and `Y` are isomorphic to the zero object.
-/
def is_iso_zero_equiv_iso_zero (X Y : C) : is_iso (0 : X βΆ Y) β (X β
0) Γ (Y β
0) :=
begin
-- This is lame, because `prod` can't cope with `Prop`, so we can't use `equiv.prod_congr`.
refine (is_iso_zero_equiv X Y).trans _,
symmetry,
fsplit,
{ rintros β¨eX, eYβ©, fsplit,
exact (id_zero_equiv_iso_zero X).symm eX,
exact (id_zero_equiv_iso_zero Y).symm eY, },
{ rintros β¨hX, hYβ©, fsplit,
exact (id_zero_equiv_iso_zero X) hX,
exact (id_zero_equiv_iso_zero Y) hY, },
{ tidy, },
{ tidy, },
end
/--
A zero morphism `0 : X βΆ X` is an isomorphism if and only if
`X` is isomorphic to the zero object.
-/
def is_iso_zero_self_equiv_iso_zero (X : C) : is_iso (0 : X βΆ X) β (X β
0) :=
(is_iso_zero_equiv_iso_zero X X).trans subsingleton_prod_self_equiv
end is_iso
/-- If there are zero morphisms, any initial object is a zero object. -/
@[priority 50]
instance has_zero_object_of_has_initial_object
[has_zero_morphisms C] [has_initial C] : has_zero_object C :=
{ zero := β₯_ C,
unique_to := Ξ» X, β¨β¨0β©, by tidyβ©,
unique_from := Ξ» X, β¨β¨0β©, Ξ» f,
calc
f = f β« π _ : (category.comp_id _).symm
... = f β« 0 : by congr
... = 0 : has_zero_morphisms.comp_zero _ _
β© }
/-- If there are zero morphisms, any terminal object is a zero object. -/
@[priority 50]
instance has_zero_object_of_has_terminal_object
[has_zero_morphisms C] [has_terminal C] : has_zero_object C :=
{ zero := β€_ C,
unique_from := Ξ» X, β¨β¨0β©, by tidyβ©,
unique_to := Ξ» X, β¨β¨0β©, Ξ» f,
calc
f = π _ β« f : (category.id_comp _).symm
... = 0 β« f : by congr
... = 0 : zero_comp
β© }
section image
variable [has_zero_morphisms C]
lemma image_ΞΉ_comp_eq_zero {X Y Z : C} {f : X βΆ Y} {g : Y βΆ Z} [has_image f]
[epi (factor_thru_image f)] (h : f β« g = 0) : image.ΞΉ f β« g = 0 :=
zero_of_epi_comp (factor_thru_image f) $ by simp [h]
variables [has_zero_object C]
local attribute [instance] has_zero_object.has_zero
/--
The zero morphism has a `mono_factorisation` through the zero object.
-/
@[simps]
def mono_factorisation_zero (X Y : C) : mono_factorisation (0 : X βΆ Y) :=
{ I := 0, m := 0, e := 0, }
/--
The factorisation through the zero object is an image factorisation.
-/
def image_factorisation_zero (X Y : C) : image_factorisation (0 : X βΆ Y) :=
{ F := mono_factorisation_zero X Y,
is_image := { lift := Ξ» F', 0 } }
instance has_image_zero {X Y : C} : has_image (0 : X βΆ Y) :=
has_image.mk $ image_factorisation_zero _ _
/-- The image of a zero morphism is the zero object. -/
def image_zero {X Y : C} : image (0 : X βΆ Y) β
0 :=
is_image.iso_ext (image.is_image (0 : X βΆ Y)) (image_factorisation_zero X Y).is_image
/-- The image of a morphism which is equal to zero is the zero object. -/
def image_zero' {X Y : C} {f : X βΆ Y} (h : f = 0) [has_image f] : image f β
0 :=
image.eq_to_iso h βͺβ« image_zero
@[simp]
lemma image.ΞΉ_zero {X Y : C} [has_image (0 : X βΆ Y)] : image.ΞΉ (0 : X βΆ Y) = 0 :=
begin
rw βimage.lift_fac (mono_factorisation_zero X Y),
simp,
end
/--
If we know `f = 0`,
it requires a little work to conclude `image.ΞΉ f = 0`,
because `f = g` only implies `image f β
image g`.
-/
@[simp]
lemma image.ΞΉ_zero' [has_equalizers C] {X Y : C} {f : X βΆ Y} (h : f = 0) [has_image f] :
image.ΞΉ f = 0 :=
by { rw image.eq_fac h, simp }
end image
/-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/
instance split_mono_sigma_ΞΉ
{Ξ² : Type v} [decidable_eq Ξ²]
[has_zero_morphisms C]
(f : Ξ² β C) [has_colimit (discrete.functor f)] (b : Ξ²) : split_mono (sigma.ΞΉ f b) :=
{ retraction := sigma.desc (Ξ» b', if h : b' = b then eq_to_hom (congr_arg f h) else 0), }
/-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/
instance split_epi_pi_Ο
{Ξ² : Type v} [decidable_eq Ξ²]
[has_zero_morphisms C]
(f : Ξ² β C) [has_limit (discrete.functor f)] (b : Ξ²) : split_epi (pi.Ο f b) :=
{ section_ := pi.lift (Ξ» b', if h : b = b' then eq_to_hom (congr_arg f h) else 0), }
/-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/
instance split_mono_coprod_inl
[has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] :
split_mono (coprod.inl : X βΆ X β¨Ώ Y) :=
{ retraction := coprod.desc (π X) 0, }
/-- In the presence of zero morphisms, coprojections into a coproduct are (split) monomorphisms. -/
instance split_mono_coprod_inr
[has_zero_morphisms C] {X Y : C} [has_colimit (pair X Y)] :
split_mono (coprod.inr : Y βΆ X β¨Ώ Y) :=
{ retraction := coprod.desc 0 (π Y), }
/-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/
instance split_epi_prod_fst
[has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] :
split_epi (prod.fst : X β¨― Y βΆ X) :=
{ section_ := prod.lift (π X) 0, }
/-- In the presence of zero morphisms, projections into a product are (split) epimorphisms. -/
instance split_epi_prod_snd
[has_zero_morphisms C] {X Y : C} [has_limit (pair X Y)] :
split_epi (prod.snd : X β¨― Y βΆ Y) :=
{ section_ := prod.lift 0 (π Y), }
end category_theory.limits
|
841b89dd4d4428e6cf6d37da2cc0d3cb59fbedfd | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/format_thunk1.lean | a3d083f3e57f922af278c3c031a793d66bcb0237 | [
"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 | 132 | lean | open tactic
example : true :=
by do
str β to_expr ``(string),
one β to_expr ``(1),
definev `H str one,
constructor
|
63d71a1ce8d76eb1183a9d0b749de6b6af640cc5 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/data/finsupp/pointwise.lean | bdc93a49df5d17c93e32091159252d6345aea71f | [
"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 | 2,220 | 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 data.finsupp.basic
/-!
# The pointwise product on `finsupp`.
TODO per issue #1864:
We intend to remove the convolution product on finsupp, and define
it only on a type synonym `add_monoid_algebra`. After we've done this,
it would be good to make this the default product on `finsupp`.
-/
noncomputable theory
open_locale classical
open finset
universes uβ uβ uβ uβ uβ
variables {Ξ± : Type uβ} {Ξ² : Type uβ} {Ξ³ : Type uβ} {Ξ΄ : Type uβ} {ΞΉ : Type uβ
}
namespace finsupp
/-! ### Declarations about the pointwise product on `finsupp`s -/
section
variables [mul_zero_class Ξ²]
/-- The product of `f g : Ξ± ββ Ξ²` is the finitely supported function
whose value at `a` is `f a * g a`. -/
instance : has_mul (Ξ± ββ Ξ²) := β¨zip_with (*) (mul_zero 0)β©
@[simp] lemma mul_apply {gβ gβ : Ξ± ββ Ξ²} {a : Ξ±} : (gβ * gβ) a = gβ a * gβ a :=
rfl
lemma support_mul {gβ gβ : Ξ± ββ Ξ²} : (gβ * gβ).support β gβ.support β© gβ.support :=
begin
intros a h,
simp only [mul_apply, mem_support_iff] at h,
simp only [mem_support_iff, mem_inter, ne.def],
rw βnot_or_distrib,
intro w,
apply h,
cases w; { rw w, simp },
end
instance : mul_zero_class (Ξ± ββ Ξ²) :=
{ zero := 0,
mul := (*),
mul_zero := Ξ» f, by { ext, simp only [mul_apply, zero_apply, mul_zero], },
zero_mul := Ξ» f, by { ext, simp only [mul_apply, zero_apply, zero_mul], }, }
end
instance [semiring Ξ²] : semigroup (Ξ± ββ Ξ²) :=
{ mul := (*),
mul_assoc := Ξ» f g h, by { ext, simp only [mul_apply, mul_assoc], }, }
instance [semiring Ξ²] : distrib (Ξ± ββ Ξ²) :=
{ left_distrib := Ξ» f g h, by { ext, simp only [mul_apply, add_apply, left_distrib] {proj := ff} },
right_distrib := Ξ» f g h,
by { ext, simp only [mul_apply, add_apply, right_distrib] {proj := ff} },
..(infer_instance : semigroup (Ξ± ββ Ξ²)),
..(infer_instance : add_comm_monoid (Ξ± ββ Ξ²)) }
-- If `non_unital_semiring` existed in the algebraic hierarchy, we could produce one here.
end finsupp
|
eb50ec8cf5a31ec47c507dca966e64696107a95f | 8eeb99d0fdf8125f5d39a0ce8631653f588ee817 | /src/data/complex/is_R_or_C.lean | a759eb58f331979a66f0c93cebb5022f12fb00d3 | [
"Apache-2.0"
] | permissive | jesse-michael-han/mathlib | a15c58378846011b003669354cbab7062b893cfe | fa6312e4dc971985e6b7708d99a5bc3062485c89 | refs/heads/master | 1,625,200,760,912 | 1,602,081,753,000 | 1,602,081,753,000 | 181,787,230 | 0 | 0 | null | 1,555,460,682,000 | 1,555,460,682,000 | null | UTF-8 | Lean | false | false | 25,812 | lean | /-
Copyright (c) 2020 FrΓ©dΓ©ric Dupuis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: FrΓ©dΓ©ric Dupuis
-/
import analysis.normed_space.basic
import analysis.complex.basic
/-!
# `is_R_or_C`: a typeclass for β or β
This file defines the typeclass `is_R_or_C` intended to have only two instances:
β and β. It is meant for definitions and theorems which hold for both the real and the complex case,
and in particular when the real case follows directly from the complex case by setting `re` to `id`,
`im` to zero and so on. Its API follows closely that of β.
Possible applications include defining inner products and Hilbert spaces for both the real and
complex case. One would produce the definitions and proof for an arbitrary field of this
typeclass, which basically amounts to doing the complex case, and the two cases then fall out
immediately from the two instances of the class.
-/
/--
This typeclass captures properties shared by β and β, with an API that closely matches that of β.
-/
class is_R_or_C (K : Type*) extends nondiscrete_normed_field K, normed_algebra β K, complete_space K :=
(re : K β+ β)
(im : K β+ β)
(conj : K β+* K)
(I : K) -- Meant to be set to 0 for K=β
(of_real : β β K) -- Meant to be id for K=β and the coercion from β for K=β
(I_re_ax : re I = 0)
(I_mul_I_ax : I = 0 β¨ I * I = -1)
(re_add_im_ax : β (z : K), of_real (re z) + of_real (im z) * I = z)
(smul_coe_mul_ax : β (z : K) (r : β), r β’ z = of_real r * z)
(of_real_re_ax : β r : β, re (of_real r) = r)
(of_real_im_ax : β r : β, im (of_real r) = 0)
(mul_re_ax : β z w : K, re (z * w) = re z * re w - im z * im w)
(mul_im_ax : β z w : K, im (z * w) = re z * im w + im z * re w)
(conj_re_ax : β z : K, re (conj z) = re z)
(conj_im_ax : β z : K, im (conj z) = -(im z))
(conj_I_ax : conj I = -I)
(norm_sq_eq_def_ax : β (z : K), β₯zβ₯^2 = (re z) * (re z) + (im z) * (im z))
(mul_im_I_ax : β (z : K), (im z) * im I = im z)
(inv_def_ax : β (z : K), zβ»ΒΉ = conj z * of_real ((β₯zβ₯^2)β»ΒΉ))
(div_I_ax : β (z : K), z / I = -(z * I))
namespace is_R_or_C
variables {K : Type*} [is_R_or_C K]
local notation `π` := @is_R_or_C.of_real K _
local postfix `β `:100 := @is_R_or_C.conj K _
lemma of_real_alg : β x : β, π x = x β’ (1 : K) :=
Ξ» x, by rw [βmul_one (π x), smul_coe_mul_ax]
@[simp] lemma re_add_im (z : K) : π (re z) + π (im z) * I = z := is_R_or_C.re_add_im_ax z
@[simp] lemma of_real_re : β r : β, re (π r) = r := is_R_or_C.of_real_re_ax
@[simp] lemma of_real_im : β r : β, im (π r) = 0 := is_R_or_C.of_real_im_ax
@[simp] lemma mul_re : β z w : K, re (z * w) = re z * re w - im z * im w :=
is_R_or_C.mul_re_ax
@[simp] lemma mul_im : β z w : K, im (z * w) = re z * im w + im z * re w :=
is_R_or_C.mul_im_ax
lemma inv_def {z : K} : zβ»ΒΉ = conj z * of_real ((β₯zβ₯^2)β»ΒΉ) := is_R_or_C.inv_def_ax z
theorem ext_iff : β {z w : K}, z = w β re z = re w β§ im z = im w :=
Ξ» z w, { mp := by { rintro rfl, cc },
mpr := by { rintro β¨hβ,hββ©, rw [βre_add_im z, βre_add_im w, hβ, hβ] } }
theorem ext : β {z w : K}, re z = re w β im z = im w β z = w :=
by { simp_rw ext_iff, cc }
@[simp] lemma zero_re : re (π 0) = (0 : β) := by simp only [of_real_re]
@[simp] lemma zero_im : im (π 0) = 0 := by rw [of_real_im]
lemma of_real_zero : π 0 = 0 := by rw [of_real_alg, zero_smul]
@[simp] lemma zero_re' : re (0 : K) = (0 : β) :=
by simp only [add_monoid_hom.map_zero]
@[simp] lemma of_real_one : π 1 = 1 := by rw [of_real_alg, one_smul]
@[simp] lemma one_re : re (1 : K) = 1 := by rw [βof_real_one, of_real_re]
@[simp] lemma one_im : im (1 : K) = 0 := by rw [βof_real_one, of_real_im]
@[simp] theorem of_real_inj {z w : β} : π z = π w β z = w :=
{ mp := Ξ» h, by { convert congr_arg re h; simp only [of_real_re] },
mpr := Ξ» h, by rw h }
@[simp] lemma bit0_re (z : K) : re (bit0 z) = bit0 (re z) := by simp [bit0]
@[simp] lemma bit1_re (z : K) : re (bit1 z) = bit1 (re z) :=
by simp only [bit1, add_monoid_hom.map_add, bit0_re, add_right_inj, one_re]
@[simp] lemma bit0_im (z : K) : im (bit0 z) = bit0 (im z) := by simp [bit0]
@[simp] lemma bit1_im (z : K) : im (bit1 z) = bit0 (im z) :=
by simp only [bit1, add_right_eq_self, add_monoid_hom.map_add, bit0_im, one_im]
@[simp] theorem of_real_eq_zero {z : β} : π z = 0 β z = 0 :=
by rw [βof_real_zero]; exact of_real_inj
@[simp] lemma of_real_add β¦r s : ββ¦ : π (r + s) = π r + π s :=
by apply (@is_R_or_C.ext_iff K _ (π (r + s)) (π r + π s)).mpr; simp
@[simp] lemma of_real_bit0 (r : β) : π (bit0 r : β) = bit0 (π r) :=
ext_iff.2 $ by simp [bit0]
@[simp] lemma of_real_bit1 (r : β) : π (bit1 r : β) = bit1 (π r) :=
ext_iff.2 $ by simp [bit1]
/- Note: This can be proven by `norm_num` once K is proven to be of characteristic zero below. -/
lemma two_ne_zero : (2 : K) β 0 :=
begin
intro h, rw [(show (2 : K) = π 2, by norm_num), βof_real_zero, of_real_inj] at h,
linarith,
end
@[simp] lemma of_real_neg (r : β) : π (-r) = -(π r) := ext_iff.2 $ by simp
@[simp] lemma of_real_mul (r s : β) : π (r * s) = (π r) * (π s) := ext_iff.2 $ by simp
lemma of_real_mul_re (r : β) (z : K) : re ((π r) * z) = r * re z :=
by simp only [mul_re, of_real_im, zero_mul, of_real_re, sub_zero]
lemma smul_re (r : β) (z : K) : re ((π r) * z) = r * (re z) :=
by simp only [of_real_im, zero_mul, of_real_re, sub_zero, mul_re]
lemma smul_im (r : β) (z : K) : im ((π r) * z) = r * (im z) :=
by simp only [add_zero, of_real_im, zero_mul, of_real_re, mul_im]
lemma smul_re' : β (r : β) (z : K), re (r β’ z) = r * (re z) :=
Ξ» r z, by { rw [smul_coe_mul_ax], apply smul_re }
lemma smul_im' : β (r : β) (z : K), im (r β’ z) = r * (im z) :=
Ξ» r z, by { rw [smul_coe_mul_ax], apply smul_im }
/-! ### The imaginary unit, `I` -/
/-- The imaginary unit. -/
@[simp] lemma I_re : re (I : K) = 0 := I_re_ax
@[simp] lemma I_im (z : K) : im z * im (I : K) = im z := mul_im_I_ax z
@[simp] lemma I_im' (z : K) : im (I : K) * im z = im z :=
by rw [mul_comm, I_im _]
lemma I_mul_I : (I : K) = 0 β¨ (I : K) * I = -1 := I_mul_I_ax
@[simp] lemma conj_re (z : K) : re (conj z) = re z := is_R_or_C.conj_re_ax z
@[simp] lemma conj_im (z : K) : im (conj z) = -(im z) := is_R_or_C.conj_im_ax z
@[simp] lemma conj_of_real (r : β) : conj (π r) = (π r) :=
by { rw ext_iff, simp only [of_real_im, conj_im, eq_self_iff_true, conj_re, and_self, neg_zero] }
@[simp] lemma conj_bit0 (z : K) : conj (bit0 z) = bit0 (conj z) := by simp [bit0, ext_iff]
@[simp] lemma conj_bit1 (z : K) : conj (bit1 z) = bit1 (conj z) := by simp [bit0, ext_iff]
@[simp] lemma conj_neg_I : conj (-I) = (I : K) := by simp [ext_iff]
@[simp] lemma conj_conj (z : K) : conj (conj z) = z := by simp [ext_iff]
lemma conj_involutive : @function.involutive K is_R_or_C.conj := conj_conj
lemma conj_bijective : @function.bijective K K is_R_or_C.conj := conj_involutive.bijective
lemma conj_inj (z w : K) : conj z = conj w β z = w := conj_bijective.1.eq_iff
@[simp] lemma conj_eq_zero {z : K} : conj z = 0 β z = 0 :=
by simpa using @conj_inj K _ z 0
lemma eq_conj_iff_real {z : K} : conj z = z β β r : β, z = (π r) :=
begin
split,
{ intro h,
suffices : im z = 0,
{ use (re z),
rw β add_zero (of_real _),
convert (re_add_im z).symm, simp [this] },
contrapose! h,
rw β re_add_im z,
simp only [conj_of_real, ring_hom.map_add, ring_hom.map_mul, conj_I_ax],
rw [add_left_cancel_iff, ext_iff],
simpa [neg_eq_iff_add_eq_zero, add_self_eq_zero] },
{ rintros β¨r, rflβ©, apply conj_of_real }
end
/-- Conjugation as a ring equivalence. This is used to convert the inner product into a
sesquilinear product. -/
def conj_to_ring_equiv : K β+* Kα΅α΅ :=
{ to_fun := opposite.op β conj,
inv_fun := conj β opposite.unop,
left_inv := Ξ» x, by simp only [conj_conj, function.comp_app, opposite.unop_op],
right_inv := Ξ» x, by simp only [conj_conj, opposite.op_unop, function.comp_app],
map_mul' := Ξ» x y, by simp [mul_comm],
map_add' := Ξ» x y, by simp }
lemma eq_conj_iff_re {z : K} : conj z = z β π (re z) = z :=
eq_conj_iff_real.trans β¨by rintro β¨r, rflβ©; simp, Ξ» h, β¨_, h.symmβ©β©
/-- The norm squared function. -/
def norm_sq (z : K) : β := re z * re z + im z * im z
lemma norm_sq_eq_def {z : K} : β₯zβ₯^2 = (re z) * (re z) + (im z) * (im z) := norm_sq_eq_def_ax z
lemma norm_sq_eq_def' (z : K) : norm_sq z = β₯zβ₯^2 := by rw [norm_sq_eq_def, norm_sq]
@[simp] lemma norm_sq_of_real (r : β) : β₯π rβ₯^2 = r * r :=
by simp [norm_sq_eq_def]
@[simp] lemma norm_sq_zero : norm_sq (0 : K) = 0 := by simp [norm_sq, pow_two]
@[simp] lemma norm_sq_one : norm_sq (1 : K) = 1 := by simp [norm_sq]
lemma norm_sq_nonneg (z : K) : 0 β€ norm_sq z :=
add_nonneg (mul_self_nonneg _) (mul_self_nonneg _)
@[simp] lemma norm_sq_eq_zero {z : K} : norm_sq z = 0 β z = 0 :=
by { rw [norm_sq, βnorm_sq_eq_def], simp [pow_two] }
@[simp] lemma norm_sq_pos {z : K} : 0 < norm_sq z β z β 0 :=
by rw [lt_iff_le_and_ne, ne, eq_comm]; simp [norm_sq_nonneg]
@[simp] lemma norm_sq_neg (z : K) : norm_sq (-z) = norm_sq z :=
by simp [norm_sq]
@[simp] lemma norm_sq_conj (z : K) : norm_sq (conj z) = norm_sq z := by simp [norm_sq]
@[simp] lemma norm_sq_mul (z w : K) : norm_sq (z * w) = norm_sq z * norm_sq w :=
by simp [norm_sq, pow_two]; ring
lemma norm_sq_add (z w : K) :
norm_sq (z + w) = norm_sq z + norm_sq w + 2 * (re (z * conj w)) :=
by simp [norm_sq, pow_two]; ring
lemma re_sq_le_norm_sq (z : K) : re z * re z β€ norm_sq z :=
le_add_of_nonneg_right (mul_self_nonneg _)
lemma im_sq_le_norm_sq (z : K) : im z * im z β€ norm_sq z :=
le_add_of_nonneg_left (mul_self_nonneg _)
theorem mul_conj (z : K) : z * conj z = π (norm_sq z) :=
by simp [ext_iff, norm_sq, mul_comm, sub_eq_neg_add, add_comm]
theorem add_conj (z : K) : z + conj z = π (2 * re z) :=
by simp [ext_iff, two_mul]
/-- The pseudo-coercion `of_real` as a `ring_hom`. -/
def of_real_hom : β β+* K := β¨of_real, of_real_one, of_real_mul, of_real_zero, of_real_addβ©
@[simp] lemma of_real_sub (r s : β) : π (r - s : β) = π r - π s := ext_iff.2 $ by simp
@[simp] lemma of_real_pow (r : β) (n : β) : π (r ^ n : β) = (π r) ^ n :=
by induction n; simp [*, of_real_mul, pow_succ]
theorem sub_conj (z : K) : z - conj z = π (2 * im z) * I :=
by simp [ext_iff, two_mul, sub_eq_add_neg, add_mul, mul_im_I_ax]
lemma norm_sq_sub (z w : K) : norm_sq (z - w) =
norm_sq z + norm_sq w - 2 * re (z * conj w) :=
by simp [-mul_re, norm_sq_add, add_comm, add_left_comm, sub_eq_add_neg]
lemma sqrt_norm_sq_eq_norm {z : K} : real.sqrt (norm_sq z) = β₯zβ₯ :=
begin
have hβ : (norm_sq z) = β₯zβ₯^2 := by rw [norm_sq_eq_def, norm_sq],
have hβ : β₯zβ₯ = real.sqrt (β₯zβ₯^2) := eq_comm.mp (real.sqrt_sqr (norm_nonneg z)),
rw [hβ],
exact congr_arg real.sqrt hβ
end
/-! ### Inversion -/
@[simp] lemma inv_re (z : K) : re (zβ»ΒΉ) = re z / norm_sq z :=
by simp [inv_def, norm_sq_eq_def, norm_sq, division_def]
@[simp] lemma inv_im (z : K) : im (zβ»ΒΉ) = im (-z) / norm_sq z :=
by simp [inv_def, norm_sq_eq_def, norm_sq, division_def]
@[simp] lemma of_real_inv (r : β) : π (rβ»ΒΉ) = (π r)β»ΒΉ :=
begin
rw ext_iff, by_cases r = 0, { simp [h] },
{ simp; field_simp [h, norm_sq] },
end
protected lemma inv_zero : (0β»ΒΉ : K) = 0 :=
by rw [β of_real_zero, β of_real_inv, inv_zero]
protected theorem mul_inv_cancel {z : K} (h : z β 0) : z * zβ»ΒΉ = 1 :=
by rw [inv_def, βmul_assoc, mul_conj, βof_real_mul, βnorm_sq_eq_def',
mul_inv_cancel (mt norm_sq_eq_zero.1 h), of_real_one]
lemma div_re (z w : K) : re (z / w) = re z * re w / norm_sq w + im z * im w / norm_sq w :=
by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg]
lemma div_im (z w : K) : im (z / w) = im z * re w / norm_sq w - re z * im w / norm_sq w :=
by simp [div_eq_mul_inv, mul_assoc, sub_eq_add_neg, add_comm]
@[simp] lemma of_real_div (r s : β) : π (r / s : β) = π r / π s :=
(@is_R_or_C.of_real_hom K _).map_div r s
lemma div_re_of_real {z : K} {r : β} : re (z / (π r)) = re z / r :=
begin
by_cases h : r = 0,
{ simp [h, of_real_zero] },
{ change r β 0 at h,
rw [div_eq_mul_inv, βof_real_inv, div_eq_mul_inv],
simp [norm_sq, norm_sq_of_real, div_mul_eq_div_mul_one_div, div_self h] }
end
@[simp] lemma of_real_fpow (r : β) (n : β€) : π (r ^ n) = (π r) ^ n :=
(@is_R_or_C.of_real_hom K _).map_fpow r n
lemma I_mul_I_of_nonzero : (I : K) β 0 β (I : K) * I = -1 :=
by { have := I_mul_I_ax, tauto }
@[simp] lemma div_I (z : K) : z / I = -(z * I) :=
begin
by_cases h : (I : K) = 0,
{ simp [h] },
{ field_simp [h], simp [mul_assoc, I_mul_I_of_nonzero h] }
end
@[simp] lemma inv_I : (I : K)β»ΒΉ = -I :=
by { by_cases h : (I : K) = 0; field_simp [h] }
@[simp] lemma norm_sq_inv (z : K) : norm_sq zβ»ΒΉ = (norm_sq z)β»ΒΉ :=
begin
by_cases z = 0,
{ simp [h] },
{ refine mul_right_cancel' (mt norm_sq_eq_zero.1 h) _,
simp [h, βnorm_sq_mul], }
end
@[simp] lemma norm_sq_div (z w : K) : norm_sq (z / w) = norm_sq z / norm_sq w :=
by { rw [division_def, norm_sq_mul, norm_sq_inv], refl }
lemma norm_conj {z : K} : β₯conj zβ₯ = β₯zβ₯ :=
by simp only [βsqrt_norm_sq_eq_norm, norm_sq_conj]
lemma conj_inv {z : K} : conj (zβ»ΒΉ) = (conj z)β»ΒΉ :=
by simp only [inv_def, norm_conj, ring_hom.map_mul, conj_of_real]
lemma conj_div {z w : K} : conj (z / w) = (conj z) / (conj w) :=
by rw [div_eq_inv_mul, div_eq_inv_mul, ring_hom.map_mul]; simp only [conj_inv]
/-! ### Cast lemmas -/
@[simp] theorem of_real_nat_cast (n : β) : π (n : β) = n :=
of_real_hom.map_nat_cast n
@[simp] lemma nat_cast_re (n : β) : re (n : K) = n :=
by rw [β of_real_nat_cast, of_real_re]
@[simp] lemma nat_cast_im (n : β) : im (n : K) = 0 :=
by rw [β of_real_nat_cast, of_real_im]
@[simp] theorem of_real_int_cast (n : β€) : π (n : β) = n :=
of_real_hom.map_int_cast n
@[simp] lemma int_cast_re (n : β€) : re (n : K) = n :=
by rw [β of_real_int_cast, of_real_re]
@[simp] lemma int_cast_im (n : β€) : im (n : K) = 0 :=
by rw [β of_real_int_cast, of_real_im]
@[simp] theorem of_real_rat_cast (n : β) : π (n : β) = n :=
(@is_R_or_C.of_real_hom K _).map_rat_cast n
@[simp] lemma rat_cast_re (q : β) : re (q : K) = q :=
by rw [β of_real_rat_cast, of_real_re]
@[simp] lemma rat_cast_im (q : β) : im (q : K) = 0 :=
by rw [β of_real_rat_cast, of_real_im]
/-! ### Characteristic zero -/
/--
β and β are both of characteristic zero.
Note: This is not registered as an instance to avoid having multiple instances on β and β.
-/
lemma char_zero_R_or_C : char_zero K :=
add_group.char_zero_of_inj_zero $ Ξ» n h,
by rwa [β of_real_nat_cast, of_real_eq_zero, nat.cast_eq_zero] at h
theorem re_eq_add_conj (z : K) : π (re z) = (z + conj z) / 2 :=
by rw [add_conj]; simp; rw [mul_div_cancel_left (π (re z)) two_ne_zero]
/-! ### Absolute value -/
/-- The complex absolute value function, defined as the square root of the norm squared. -/
@[pp_nodot] noncomputable def abs (z : K) : β := (norm_sq z).sqrt
local notation `abs'` := _root_.abs
local notation `absK` := @abs K _
@[simp] lemma abs_of_real (r : β) : absK (π r) = abs' r :=
by simp [abs, norm_sq, norm_sq_of_real, real.sqrt_mul_self_eq_abs]
lemma abs_of_nonneg {r : β} (h : 0 β€ r) : absK (π r) = r :=
(abs_of_real _).trans (abs_of_nonneg h)
lemma abs_of_nat (n : β) : absK n = n :=
by { rw [β of_real_nat_cast], exact abs_of_nonneg (nat.cast_nonneg n) }
lemma mul_self_abs (z : K) : abs z * abs z = norm_sq z :=
real.mul_self_sqrt (norm_sq_nonneg _)
@[simp] lemma abs_zero : absK 0 = 0 := by simp [abs]
@[simp] lemma abs_one : absK 1 = 1 := by simp [abs]
@[simp] lemma abs_two : absK 2 = 2 :=
calc absK 2 = absK (π 2) : by rw [of_real_bit0, of_real_one]
... = (2 : β) : abs_of_nonneg (by norm_num)
lemma abs_nonneg (z : K) : 0 β€ absK z :=
real.sqrt_nonneg _
@[simp] lemma abs_eq_zero {z : K} : absK z = 0 β z = 0 :=
(real.sqrt_eq_zero $ norm_sq_nonneg _).trans norm_sq_eq_zero
lemma abs_ne_zero {z : K} : abs z β 0 β z β 0 :=
not_congr abs_eq_zero
@[simp] lemma abs_conj (z : K) : abs (conj z) = abs z :=
by simp [abs]
@[simp] lemma abs_mul (z w : K) : abs (z * w) = abs z * abs w :=
by rw [abs, norm_sq_mul, real.sqrt_mul (norm_sq_nonneg _)]; refl
lemma abs_re_le_abs (z : K) : abs' (re z) β€ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (re z)) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply re_sq_le_norm_sq
lemma abs_im_le_abs (z : K) : abs' (im z) β€ abs z :=
by rw [mul_self_le_mul_self_iff (_root_.abs_nonneg (im z)) (abs_nonneg _),
abs_mul_abs_self, mul_self_abs];
apply im_sq_le_norm_sq
lemma re_le_abs (z : K) : re z β€ abs z :=
(abs_le.1 (abs_re_le_abs _)).2
lemma im_le_abs (z : K) : im z β€ abs z :=
(abs_le.1 (abs_im_le_abs _)).2
lemma abs_add (z w : K) : abs (z + w) β€ abs z + abs w :=
(mul_self_le_mul_self_iff (abs_nonneg _)
(add_nonneg (abs_nonneg _) (abs_nonneg _))).2 $
begin
rw [mul_self_abs, add_mul_self_eq, mul_self_abs, mul_self_abs,
add_right_comm, norm_sq_add, add_le_add_iff_left,
mul_assoc, mul_le_mul_left (@zero_lt_two β _)],
simpa [-mul_re] using re_le_abs (z * conj w)
end
instance : is_absolute_value absK :=
{ abv_nonneg := abs_nonneg,
abv_eq_zero := Ξ» _, abs_eq_zero,
abv_add := abs_add,
abv_mul := abs_mul }
open is_absolute_value
@[simp] lemma abs_abs (z : K) : abs' (abs z) = abs z :=
_root_.abs_of_nonneg (abs_nonneg _)
@[simp] lemma abs_pos {z : K} : 0 < abs z β z β 0 := abv_pos abs
@[simp] lemma abs_neg : β z : K, abs (-z) = abs z := abv_neg abs
lemma abs_sub : β z w : K, abs (z - w) = abs (w - z) := abv_sub abs
lemma abs_sub_le : β a b c : K, abs (a - c) β€ abs (a - b) + abs (b - c) := abv_sub_le abs
@[simp] theorem abs_inv : β z : K, abs zβ»ΒΉ = (abs z)β»ΒΉ := abv_inv abs
@[simp] theorem abs_div : β z w : K, abs (z / w) = abs z / abs w := abv_div abs
lemma abs_abs_sub_le_abs_sub : β z w : K, abs' (abs z - abs w) β€ abs (z - w) :=
abs_abv_sub_le_abv_sub abs
lemma abs_re_div_abs_le_one (z : K) : abs' (re z / abs z) β€ 1 :=
begin
by_cases hz : z = 0,
{ simp [hz, zero_le_one] },
{ simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_re_le_abs] }
end
lemma abs_im_div_abs_le_one (z : K) : abs' (im z / abs z) β€ 1 :=
begin
by_cases hz : z = 0,
{ simp [hz, zero_le_one] },
{ simp_rw [_root_.abs_div, abs_abs, div_le_iff (abs_pos.2 hz), one_mul, abs_im_le_abs] }
end
@[simp] lemma abs_cast_nat (n : β) : abs (n : K) = n :=
by rw [β of_real_nat_cast, abs_of_nonneg (nat.cast_nonneg n)]
lemma norm_sq_eq_abs (x : K) : norm_sq x = abs x ^ 2 :=
by rw [abs, pow_two, real.mul_self_sqrt (norm_sq_nonneg _)]
lemma re_eq_abs_of_mul_conj (x : K) : re (x * (conj x)) = abs (x * (conj x)) :=
by rw [mul_conj, of_real_re, abs_of_real, norm_sq_eq_abs, pow_two, _root_.abs_mul, abs_abs]
lemma abs_sqr_re_add_conj (x : K) : (abs (x + xβ ))^2 = (re (x + xβ ))^2 :=
by simp [pow_two, βnorm_sq_eq_abs, norm_sq]
lemma abs_sqr_re_add_conj' (x : K) : (abs (xβ + x))^2 = (re (xβ + x))^2 :=
by simp [pow_two, βnorm_sq_eq_abs, norm_sq]
lemma conj_mul_eq_norm_sq_left (x : K) : xβ * x = π (norm_sq x) :=
begin
rw ext_iff,
refine β¨by simp [of_real_re, mul_re, conj_re, conj_im, norm_sq],_β©,
simp [of_real_im, mul_im, conj_im, conj_re, mul_comm],
end
/-! ### Cauchy sequences -/
theorem is_cau_seq_re (f : cau_seq K abs) : is_cau_seq abs' (Ξ» n, re (f n)) :=
Ξ» Ξ΅ Ξ΅0, (f.cauchy Ξ΅0).imp $ Ξ» i H j ij,
lt_of_le_of_lt (by simpa using abs_re_le_abs (f j - f i)) (H _ ij)
theorem is_cau_seq_im (f : cau_seq K abs) : is_cau_seq abs' (Ξ» n, im (f n)) :=
Ξ» Ξ΅ Ξ΅0, (f.cauchy Ξ΅0).imp $ Ξ» i H j ij,
lt_of_le_of_lt (by simpa using abs_im_le_abs (f j - f i)) (H _ ij)
/-- The real part of a K Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_re (f : cau_seq K abs) : cau_seq β abs' :=
β¨_, is_cau_seq_re fβ©
/-- The imaginary part of a K Cauchy sequence, as a real Cauchy sequence. -/
noncomputable def cau_seq_im (f : cau_seq K abs) : cau_seq β abs' :=
β¨_, is_cau_seq_im fβ©
lemma is_cau_seq_abs {f : β β K} (hf : is_cau_seq abs f) :
is_cau_seq abs' (abs β f) :=
Ξ» Ξ΅ Ξ΅0, let β¨i, hiβ© := hf Ξ΅ Ξ΅0 in
β¨i, Ξ» j hj, lt_of_le_of_lt (abs_abs_sub_le_abs_sub _ _) (hi j hj)β©
end is_R_or_C
section instances
noncomputable instance real.is_R_or_C : is_R_or_C β :=
{ re := add_monoid_hom.id β,
im := 0,
conj := ring_hom.id β,
I := 0,
of_real := id,
I_re_ax := by simp only [add_monoid_hom.map_zero],
I_mul_I_ax := or.intro_left _ rfl,
re_add_im_ax := Ξ» z, by unfold_coes; simp [add_zero, id.def, mul_zero],
smul_coe_mul_ax := Ξ» z r, by simp only [algebra.id.smul_eq_mul, id.def],
of_real_re_ax := Ξ» r, by simp only [id.def, add_monoid_hom.id_apply],
of_real_im_ax := Ξ» r, by simp only [add_monoid_hom.zero_apply],
mul_re_ax := Ξ» z w, by simp only [sub_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply],
mul_im_ax := Ξ» z w, by simp only [add_zero, zero_mul, mul_zero, add_monoid_hom.zero_apply],
conj_re_ax := Ξ» z, by simp only [ring_hom.id_apply],
conj_im_ax := Ξ» z, by simp only [neg_zero, add_monoid_hom.zero_apply],
conj_I_ax := by simp only [ring_hom.map_zero, neg_zero],
norm_sq_eq_def_ax := Ξ» z, by simp only [pow_two, norm, βabs_mul, abs_mul_self z, add_zero, mul_zero, add_monoid_hom.zero_apply, add_monoid_hom.id_apply],
mul_im_I_ax := Ξ» z, by simp only [mul_zero, add_monoid_hom.zero_apply],
inv_def_ax :=
begin
intro z,
unfold_coes,
have H : z β 0 β 1 / z = z / (z * z) := Ξ» h,
calc
1 / z = 1 * (1 / z) : (one_mul (1 / z)).symm
... = (z / z) * (1 / z) : congr_arg (Ξ» x, x * (1 / z)) (div_self h).symm
... = z / (z * z) : by field_simp,
rcases lt_trichotomy z 0 with hlt|heq|hgt,
{ field_simp [norm, abs, max_eq_right_of_lt (show z < -z, by linarith), pow_two, mul_inv', βH (ne_of_lt hlt)] },
{ simp [heq] },
{ field_simp [norm, abs, max_eq_left_of_lt (show -z < z, by linarith), pow_two, mul_inv', βH (ne_of_gt hgt)] },
end,
div_I_ax := Ξ» z, by simp only [div_zero, mul_zero, neg_zero]}
noncomputable instance complex.is_R_or_C : is_R_or_C β :=
{ re := β¨complex.re, complex.zero_re, complex.add_reβ©,
im := β¨complex.im, complex.zero_im, complex.add_imβ©,
conj := complex.conj,
I := complex.I,
of_real := coe,
I_re_ax := by simp only [add_monoid_hom.coe_mk, complex.I_re],
I_mul_I_ax := by simp only [complex.I_mul_I, eq_self_iff_true, or_true],
re_add_im_ax := by simp only [forall_const, add_monoid_hom.coe_mk, complex.re_add_im, eq_self_iff_true],
smul_coe_mul_ax := Ξ» z r, rfl,
of_real_re_ax := Ξ» r, by simp only [add_monoid_hom.coe_mk, complex.of_real_re],
of_real_im_ax := Ξ» r, by simp only [add_monoid_hom.coe_mk, complex.of_real_im],
mul_re_ax := Ξ» z w, by simp only [complex.mul_re, add_monoid_hom.coe_mk],
mul_im_ax := Ξ» z w, by simp only [add_monoid_hom.coe_mk, complex.mul_im],
conj_re_ax := Ξ» z, by simp only [ring_hom.coe_mk, add_monoid_hom.coe_mk, complex.conj_re],
conj_im_ax := Ξ» z, by simp only [ring_hom.coe_mk, complex.conj_im, add_monoid_hom.coe_mk],
conj_I_ax := by simp only [complex.conj_I, ring_hom.coe_mk],
norm_sq_eq_def_ax := Ξ» z, by simp only [βcomplex.norm_sq_eq_abs, βcomplex.norm_sq, add_monoid_hom.coe_mk, complex.norm_eq_abs],
mul_im_I_ax := Ξ» z, by simp only [mul_one, add_monoid_hom.coe_mk, complex.I_im],
inv_def_ax := Ξ» z, by convert complex.inv_def z; exact (complex.norm_sq_eq_abs z).symm,
div_I_ax := complex.div_I }
end instances
namespace is_R_or_C
section cleanup_lemmas
local notation `reR` := @is_R_or_C.re β _
local notation `imR` := @is_R_or_C.im β _
local notation `conjR` := @is_R_or_C.conj β _
local notation `IR` := @is_R_or_C.I β _
local notation `of_realR` := @is_R_or_C.of_real β _
local notation `absR` := @is_R_or_C.abs β _
local notation `norm_sqR` := @is_R_or_C.norm_sq β _
local notation `reC` := @is_R_or_C.re β _
local notation `imC` := @is_R_or_C.im β _
local notation `conjC` := @is_R_or_C.conj β _
local notation `IC` := @is_R_or_C.I β _
local notation `of_realC` := @is_R_or_C.of_real β _
local notation `absC` := @is_R_or_C.abs β _
local notation `norm_sqC` := @is_R_or_C.norm_sq β _
@[simp] lemma re_to_real {x : β} : reR x = x := rfl
@[simp] lemma im_to_real {x : β} : imR x = 0 := rfl
@[simp] lemma conj_to_real {x : β} : conjR x = x := rfl
@[simp] lemma I_to_real : IR = 0 := rfl
@[simp] lemma of_real_to_real {x : β} : of_realR x = x := rfl
@[simp] lemma norm_sq_to_real {x : β} : norm_sqR x = x*x := by simp [is_R_or_C.norm_sq]
@[simp] lemma abs_to_real {x : β} : absR x = _root_.abs x :=
by simp [is_R_or_C.abs, abs, real.sqrt_mul_self_eq_abs]
@[simp] lemma re_to_complex {x : β} : reC x = x.re := rfl
@[simp] lemma im_to_complex {x : β} : imC x = x.im := rfl
@[simp] lemma conj_to_complex {x : β} : conjC x = x.conj := rfl
@[simp] lemma I_to_complex : IC = complex.I := rfl
@[simp] lemma of_real_to_complex {x : β} : of_realC x = x := rfl
@[simp] lemma norm_sq_to_complex {x : β} : norm_sqC x = complex.norm_sq x :=
by simp [is_R_or_C.norm_sq, complex.norm_sq]
@[simp] lemma abs_to_complex {x : β} : absC x = complex.abs x :=
by simp [is_R_or_C.abs, complex.abs]
end cleanup_lemmas
end is_R_or_C
|
61b8b9601cdbc6e69612d73595f20c850b1d845f | 5756a081670ba9c1d1d3fca7bd47cb4e31beae66 | /Mathport/Syntax/AST3.lean | ebe66b4bdb9fb26c02975f79196aa724e8bcc950 | [
"Apache-2.0"
] | permissive | leanprover-community/mathport | 2c9bdc8292168febf59799efdc5451dbf0450d4a | 13051f68064f7638970d39a8fecaede68ffbf9e1 | refs/heads/master | 1,693,841,364,079 | 1,693,813,111,000 | 1,693,813,111,000 | 379,357,010 | 27 | 10 | Apache-2.0 | 1,691,309,132,000 | 1,624,384,521,000 | Lean | UTF-8 | Lean | false | false | 46,724 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Daniel Selsam
-/
import Mathport.Util.Misc
def Lean.BinderInfo.bracket (paren : Bool) : BinderInfo β Format β Format
| BinderInfo.default, f => if paren then f.paren else f.group
| BinderInfo.implicit, f => f.bracket "{" "}"
| BinderInfo.strictImplicit, f => f.bracket "{{" "}}"
| BinderInfo.instImplicit, f => f.sbracket
namespace Mathport
open Lean (Position Name BinderInfo)
open Std (Format)
namespace Lean3
inductive Proj
| nat : Nat β Proj
| ident : Name β Proj
deriving Inhabited
instance : Repr Proj where
reprPrec
| Proj.nat n, _ => repr n
| Proj.ident n, _ => n.toString
open Lean (Level)
inductive Annotation
| no_univ
| do_failure_eq
| infix_fn
| begin_hole
| end_hole
| anonymous_constructor
| Β«calcΒ»
| no_info
| frozen_name
| Β«haveΒ»
| Β«showΒ»
| Β«sufficesΒ»
| checkpoint
| Β«@Β»
| Β«@@Β»
| as_atomic
| as_is
| antiquote
| expr_quote_pre
| comp_irrel
| inaccessible
| Β«byΒ»
| pattern_hint
| th_proof
deriving Repr
structure EquationsHeader :=
(num_fns : Nat) (fn_names fn_actual_names : Array Name)
(is_private is_noncomputable is_meta is_lemma gen_code aux_lemmas : Bool)
deriving Repr
instance : Repr Level.Data := β¨fun _ _ => "Β·"β©
deriving instance Repr for Level
mutual
inductive Expr where
| var : Nat β Expr
| sort : Level β Expr
| const : Name β Array Level β Expr
| mvar (name pp : Name) (type : Expr)
| Β«localΒ» (name pp : Name) (bi : BinderInfo) (type : Expr)
| app : Expr β Expr β Expr
| lam (name : Name) (bi : BinderInfo) (dom body : Expr)
| Pi (name : Name) (bi : BinderInfo) (dom body : Expr)
| Β«letΒ» (name : Name) (type value body : Expr)
| annotation : Annotation β Expr β Expr
| field : Expr β Proj β Expr
| typed_expr (ty val : Expr)
| structinst (struct : Name) (catchall : Bool) (fields : Array (Name Γ Expr)) (sources : Array Expr)
| prenum (value : Nat)
| nat (value : Nat)
| quote (value : Expr) (expr : Bool)
| choice (args : Array Expr)
| string (value : String)
| no_equation
| equation (lhs rhs : Expr) (ignore_if_unused : Bool)
| equations (h : EquationsHeader) (eqns : Array LambdaEquation) (wf : Option Expr)
| equations_result (args : Array Expr)
| as_pattern (lhs rhs : Expr)
| delayed_abstraction : Expr β Array (Name Γ Expr) β Expr
| Β«sorryΒ» (synthetic : Bool) (ty : Expr)
| rec_fn (name : Name) (ty : Expr)
| proj (I constr proj : Name) (idx : Nat) (params : Array Name) (ty val arg : Expr)
| ac_app (args : Array Expr) (op : Expr)
| perm_ac (assoc comm e1 e2 : Expr)
| cc_proof (e1 e2 : Expr)
deriving Inhabited, Repr
inductive LambdaEquation where
| no_equation
| equation (lhs rhs : Expr) (ignore_if_unused : Bool)
| lam (name : Name) (bi : BinderInfo) (dom : Expr) : LambdaEquation β LambdaEquation
deriving Inhabited, Repr
end
partial def Expr.toLambdaEqn : Expr β Option LambdaEquation
| Expr.no_equation => LambdaEquation.no_equation
| Expr.equation lhs rhs iu => LambdaEquation.equation lhs rhs iu
| Expr.lam n pp bi e => LambdaEquation.lam n pp bi <$> e.toLambdaEqn
| _ => none
end Lean3
structure Meta where
id : Nat
start : Position
end_ : Position
deriving Inhabited
structure Spanned (Ξ± : Type u) where
meta : Option Meta
kind : Ξ±
deriving Inhabited
instance [Repr Ξ±] : Repr (Spanned Ξ±) := β¨fun n p => reprPrec n.kind pβ©
def Spanned.map (f : Ξ± β Ξ²) : Spanned Ξ± β Spanned Ξ²
| β¨m, aβ© => β¨m, f aβ©
def Spanned.dummy (a : Ξ±) : Spanned Ξ± := β¨none, aβ©
local prefix:max "#" => Spanned
namespace AST3
open Lean3 (Proj)
inductive BinderName
| ident : Name β BinderName
| Β«_Β» : BinderName
instance : Repr BinderName where
reprPrec
| BinderName.ident n, _ => n.toString
| BinderName.Β«_Β», _ => "_"
inductive VariableKind | Β«variableΒ» | Β«parameterΒ»
deriving Inhabited
instance : Repr VariableKind where
reprPrec
| VariableKind.Β«variableΒ», _ => "variable"
| VariableKind.Β«parameterΒ», _ => "parameter"
inductive AxiomKind | Β«axiomΒ» | Β«constantΒ»
deriving Inhabited
instance : Repr AxiomKind where
reprPrec
| AxiomKind.Β«axiomΒ», _ => "axiom"
| AxiomKind.Β«constantΒ», _ => "constant"
inductive DeclKind | Β«defΒ» | Β«theoremΒ» | Β«abbrevΒ» | Β«exampleΒ» | Β«instanceΒ»
deriving Inhabited
instance : Repr DeclKind where
reprPrec
| DeclKind.def, _ => "def"
| DeclKind.theorem, _ => "theorem"
| DeclKind.abbrev, _ => "abbreviation"
| DeclKind.example, _ => "example"
| DeclKind.instance, _ => "instance"
def LocalReserve := Bool Γ Bool
instance : Repr LocalReserve := β¨fun β¨loc, resβ© _ =>
((if loc then "local " else "") ++ (if res then "reserve " else "") : String)β©
inductive MixfixKind | Β«infixΒ» | Β«infixlΒ» | Β«infixrΒ» | Β«postfixΒ» | Β«prefixΒ»
deriving Inhabited, BEq, Hashable
instance : Repr MixfixKind where
reprPrec
| MixfixKind.infix, _ => "infix"
| MixfixKind.infixl, _ => "infixl"
| MixfixKind.infixr, _ => "infixr"
| MixfixKind.postfix, _ => "postfix"
| MixfixKind.prefix, _ => "prefix"
instance : ToString MixfixKind where
toString m := toString (repr m)
inductive InferKind | implicit | relaxedImplicit | none
instance : Inhabited InferKind := β¨InferKind.relaxedImplicitβ©
instance : ToString InferKind where
toString
| InferKind.implicit => "[]"
| InferKind.relaxedImplicit => "{}"
| InferKind.none => "( )"
instance : Repr InferKind where
reprPrec ik _ := toString ik
def InferKind.optRepr : Option InferKind β Format
| Option.none => ""
| some ik => " " ++ repr ik
inductive Symbol
| quoted : String β Symbol
| ident : String β Symbol
deriving Inhabited
instance : Repr Symbol where
reprPrec
| Symbol.quoted s, _ => ("`" ++ s ++ "`" : String)
| Symbol.ident n, _ => n
def Symbol.trim : Symbol β String
| Symbol.ident s => s
| Symbol.quoted s => s.trim
def Symbol.toString : Symbol β String
| Symbol.ident s => s
| Symbol.quoted s => s
inductive Choice
| one : Name β Choice
| many : Array Name β Choice
deriving Inhabited
def Choice.name : Choice β Name
| Choice.one n => n
| Choice.many #[n] => n
| _ => default
instance : Repr Choice where
reprPrec
| Choice.one n, _ => n.toString
| Choice.many ns, _ => (Format.joinSep (ns.toList.map (Β·.toString)) "/").sbracket
inductive OptionVal
| bool : Bool β OptionVal
| str : String β OptionVal
| nat : Nat β OptionVal
| decimal : Nat β Nat β OptionVal
instance : Repr OptionVal where
reprPrec
| OptionVal.bool n, _ => repr n
| OptionVal.nat n, _ => repr n
| OptionVal.str n, _ => repr n
| OptionVal.decimal n d, _ => repr n ++ "/" ++ repr d
inductive Level
| Β«_Β» : Level
| nat : Nat β Level
| add : #Level β #Nat β Level
| max : Array #Level β Level
| imax : Array #Level β Level
| param : Name β Level
| paren : #Level β Level
deriving Inhabited
def Levels := Option (Array #Level)
def LevelDecl := Option (Array #Name)
instance : Inhabited Levels := β¨noneβ©
instance : Inhabited LevelDecl := β¨noneβ©
-- These are used to break up the huge mutual recursion below
abbrev NotationId := Nat
abbrev CommandId := Nat
section
set_option hygiene false
local notation "Binders" => Array #Binder
mutual
inductive Default
| Β«:=Β» : #Expr β Default
| Β«.Β» : #Name β Default
inductive Binder
| Β«notationΒ» : NotationId β Binder
| binder : BinderInfo β Option (Array #BinderName) β
Binders β Option #Expr β Option Default β Binder
| collection : BinderInfo β Array #BinderName β
(nota : Name) β (rhs : #Expr) β Binder
deriving Inhabited
inductive LambdaBinder
| reg : Binder β LambdaBinder
| Β«β¨β©Β» : Array #Expr β LambdaBinder
deriving Inhabited
inductive LetDecl
| Β«notationΒ» : NotationId β LetDecl
| var : #BinderName β Binders β Option #Expr β #Expr β LetDecl
| pat : #Expr β #Expr β LetDecl
deriving Inhabited
inductive Arg
| expr : Expr β Arg
| exprs : Array #Expr β Arg
| binder : Binder β Arg
| binders : Binders β Arg
deriving Inhabited
inductive Expr
| Β«...Β» : Expr
| Β«sorryΒ» : Expr
| Β«_Β» : Expr
| Β«()Β» : Expr
| Β«{}Β» : Expr
| ident : Name β Expr
| const : #Name β Levels β Array Name β Expr
| nat : Nat β Expr
| decimal : Nat β Nat β Expr
| string : String β Expr
| char : Char β Expr
| paren : #Expr β Expr
| sort (isType isStar : Bool) : Option #Level β Expr
| app : #Expr β #Expr β Expr
| Β«funΒ» (isAssume : Bool) : Array #LambdaBinder β #Expr β Expr
| Β«βΒ» : #Expr β #Expr β Expr
| Pi : Binders β #Expr β Expr
| Β«showΒ» : #Expr β #Proof β Expr
| Β«haveΒ» (suff : Bool) : Option #Name β #Expr β #Proof β #Expr β Expr
| Β«.Β» (compact : Bool) : #Expr β #Proj β Expr
| Β«ifΒ» : Option #Name β #Expr β #Expr β #Expr β Expr
| Β«calcΒ» : Array (#Expr Γ #Expr) β Expr
| Β«@Β» (Β«partialΒ» : Bool) : #Expr β Expr
| pattern : #Expr β Expr
| Β«`()Β» (lazy expr : Bool) : #Expr β Expr
| Β«%%Β» : #Expr β Expr
| Β«`[]Β» : Array #Tactic β Expr
| Β«`Β» (resolve : Bool) : Name β Expr
| Β«β¨β©Β» : Array #Expr β Expr
| infix_fn : Choice β Option #Expr β Expr
| Β«(,)Β» : Array #Expr β Expr
| Β«:Β» : #Expr β #Expr β Expr
| hole : Array #Expr β Expr
| Β«#[]Β» : Array #Expr β Expr
| Β«byΒ» : #Tactic β Expr
| begin : Block β Expr
| Β«letΒ» : Array #LetDecl β #Expr β Expr
| Β«matchΒ» : Array #Expr β Option #Expr β Array Arm β Expr
| Β«doΒ» (braces : Bool) : Array #DoElem β Expr
| Β«{,}Β» : Array #Expr β Expr
| subtype (setOf : Bool) : #Name β Option #Expr β #Expr β Expr
| sep : #Name β #Expr β #Expr β Expr
| setReplacement : #Expr β Binders β Expr
| structInst (ty : Option #Name) (src : Option #Expr)
(fields : Array (#Name Γ #Expr)) (srcs : Array #Expr) (catchall : Bool) : Expr
| atPat : #Name β #Expr β Expr
| Β«.()Β» : #Expr β Expr
| Β«notationΒ» (n : Choice) : Array #Arg β Expr
| userNotation (n : Name) : Array #Param β Expr
deriving Inhabited
inductive Arm
| mk (lhs : Array #Expr) (rhs : #Expr) : Arm
deriving Inhabited
inductive DoElem
| Β«letΒ» : #LetDecl β DoElem
| Β«βΒ» : #Expr β Option #Expr β #Expr β Option #Expr β DoElem
| eval : #Expr β DoElem
deriving Inhabited
inductive Proof
| Β«fromΒ» (Β«:=Β» : Bool) : #Expr β Proof
| block : Block β Proof
| Β«byΒ» : #Tactic β Proof
deriving Inhabited
inductive Tactic
| Β«;Β» : Array #Tactic β Tactic
| Β«<|>Β» : Array #Tactic β Tactic
| Β«[]Β» : Array #Tactic β Tactic
| block : Block β Tactic
| Β«byΒ» : #Tactic β Tactic
| exact_shortcut : #Expr β Tactic
| expr : #Expr β Tactic
| interactive (n : Name) : Array #Param β Tactic
deriving Inhabited
inductive Block
| mk (curly : Bool) (tacClass : Option #Name)
(cfg : Option #Expr) (tacs : Array #Tactic) : Block
deriving Inhabited
inductive Param
| parse : Lean3.Expr β Array #VMCall β Param
| expr : #Expr β Param
| block : Block β Param
deriving Inhabited
inductive VMCall
| ident : Name β VMCall
| nat : Nat β VMCall
| token : String β VMCall
| pat : Expr β VMCall
| expr : Expr β VMCall
| binders : Binders β VMCall
| block : Block β VMCall
| Β«inductiveΒ» : CommandId β VMCall
| command : Option CommandId β VMCall
| withInput : Array #VMCall β (bytesParsed : Nat) β VMCall
deriving Inhabited
end
end
def Binders := Array #Binder
instance : Inhabited Binders := β¨#[]β©
partial def Expr.unparen : Expr β Expr
| Expr.paren e => e.kind.unparen
| e => e
inductive AttrArg
| eager : AttrArg
| indices : Array #Nat β AttrArg
| keyValue : #String β #String β AttrArg
| vmOverride : #Name β Option #Name β AttrArg
| user : Lean3.Expr β Array #VMCall β AttrArg
deriving Inhabited
inductive Attribute
| priority : #Expr β Attribute
| del (name : Name) : Attribute
| add (name : Name) (arg : Option #AttrArg) : Attribute
deriving Inhabited
def Attributes := Array #Attribute
instance : Inhabited Attributes := β¨#[]β©
inductive Precedence
| nat : Nat β Precedence
| expr : #Expr β Precedence
deriving Inhabited
def PrecSymbol := #Symbol Γ Option #Precedence
instance : Inhabited PrecSymbol := inferInstanceAs (Inhabited (_Γ_))
inductive Action
| prec : Precedence β Action
| prev : Action
| Β«scopedΒ» : Option #Precedence β Option (#Name Γ #Expr) β Action
| fold (right : Bool)
(prec : Option #Precedence) (sep : PrecSymbol)
(Β«recΒ» : #Name Γ #Name Γ #Expr) (ini : Option #Expr)
(term : Option PrecSymbol) : Action
deriving Inhabited
inductive Literal
| nat : Nat β Literal
| var : #Name β Option #Action β Literal
| sym : PrecSymbol β Literal
| binder : Option #Precedence β Literal
| binders : Option #Precedence β Literal
deriving Inhabited
inductive Notation
| Β«notationΒ» : Option #Name β Array #Literal β Option #Expr β Notation
| mixfix : MixfixKind β Option #Name β PrecSymbol β Option #Expr β Notation
deriving Inhabited
inductive Modifier
| Β«privateΒ» : Modifier
| Β«protectedΒ» : Modifier
| Β«noncomputableΒ» : Modifier
| meta : Modifier
| Β«mutualΒ» : Modifier
| doc : String β Modifier
| attr (Β«localΒ» compact : Bool) : Attributes β Modifier
deriving Inhabited
def Modifiers := Array #Modifier
instance : Inhabited Modifiers := β¨#[]β©
inductive DeclVal
| expr : Expr β DeclVal
| eqns : Array Arm β DeclVal
deriving Inhabited
structure Mutual (Ξ± : Type) := (attrs : Attributes) (name : #Name) (ty : #Expr) (vals : Array Ξ±)
deriving Inhabited
structure MutualHeader (Ξ± : Type) where
(mods : Modifiers) (lvls : LevelDecl) (bis : Binders) (vals : Array (Mutual Ξ±))
deriving Inhabited
structure Intro where
(doc : Option String) (name : #Name) (ik : Option InferKind) (bis : Binders) (ty : Option #Expr)
structure Rename := (Β«fromΒ» to : #Name)
structure Parent where
(Β«privateΒ» : Bool) (name : Option #Name) (expr : #Expr) (renames : Array Rename)
structure Mk := (name : #Name) (ik : Option InferKind)
inductive Field
| binder : BinderInfo β Array #Name β Option InferKind β
Binders β Option #Expr β Option Default β Field
| Β«notationΒ» : Notation β Field
inductive OpenClause
| explicit : Array #Name β OpenClause
| Β«renamingΒ» : Array Rename β OpenClause
| Β«hidingΒ» : Array #Name β OpenClause
structure Open :=
(tgt : #Name) (as : Option #Name) (clauses : Array #OpenClause)
inductive HelpCmd
| options : HelpCmd
| commands : HelpCmd
inductive PrintAttrCmd
| recursor : PrintAttrCmd
| unify : PrintAttrCmd
| simp : PrintAttrCmd
| congr : PrintAttrCmd
| attr : Name β PrintAttrCmd
def PrintAttrCmd.toName : PrintAttrCmd β Name
| recursor => `recursor
| unify => `unify
| simp => `simp
| congr => `congr
| attr n => n
inductive PrintCmd
| str : String β PrintCmd
| raw : #Expr β PrintCmd
| options : PrintCmd
| trust : PrintCmd
| keyEquivalences : PrintCmd
| Β«defΒ» : #Name β PrintCmd
| instances : #Name β PrintCmd
| classes : PrintCmd
| attributes : PrintCmd
| Β«prefixΒ» : #Name β PrintCmd
| aliases : PrintCmd
| Β«axiomsΒ» : Option #Name β PrintCmd
| fields : #Name β PrintCmd
| Β«notationΒ» : Array #Name β PrintCmd
| Β«inductiveΒ» : #Name β PrintCmd
| attr : #PrintAttrCmd β PrintCmd
| token : #Name β PrintCmd
| ident : #Name β PrintCmd
inductive InductiveCmd
| reg (Β«classΒ» : Bool) : Modifiers β #Name β LevelDecl β Binders β
(ty : Option #Expr) β Option Notation β Array #Intro β InductiveCmd
| Β«mutualΒ» (Β«classΒ» : Bool) : Modifiers β LevelDecl β Binders β
Option Notation β Array (Mutual #Intro) β InductiveCmd
inductive Command
| initQuotient : Command
| mdoc : String β Command
| Β«universeΒ» (var plural : Bool) : Array #Name β Command
| Β«namespaceΒ» : #Name β Command
| Β«sectionΒ» : Option #Name β Command
| Β«endΒ» : Option #Name β Command
| Β«variableΒ» : VariableKind β (plural : Bool) β Modifiers β Binders β Command
| Β«axiomΒ» : AxiomKind β Modifiers β #Name β LevelDecl β Binders β #Expr β Command
| Β«axiomsΒ» : AxiomKind β Modifiers β Binders β Command
| decl : DeclKind β Modifiers β Option #Name β
LevelDecl β Binders β (ty : Option #Expr) β #DeclVal β (uwf : Option #Expr) β Command
| mutualDecl : DeclKind β Modifiers β LevelDecl β Binders β Array (Mutual Arm) β
(uwf : Option #Expr) β Command
| Β«inductiveΒ» : InductiveCmd β Command
| Β«structureΒ» (Β«classΒ» : Bool) :
Modifiers β #Name β LevelDecl β Binders β Array #Parent β (ty : Option #Expr) β
Option #Mk β Array #Field β Command
| Β«attributeΒ» (Β«localΒ» : Bool) : Modifiers β Attributes β Array #Name β Command
| Β«precedenceΒ» : #Symbol β #Precedence β Command
| Β«notationΒ» : LocalReserve β Attributes β Notation β Command
| Β«openΒ» (Β«exportΒ» : Bool) : Array Open β Command
| Β«includeΒ» (pos : Bool) : Array #Name β Command
| Β«hideΒ» : Array #Name β Command
| Β«theoryΒ» : Modifiers β Command
| setOption : #Name β #OptionVal β Command
| declareTrace : #Name β Command
| addKeyEquivalence : #Name β #Name β Command
| runCmd : #Expr β Command
| check : #Expr β Command
| reduce (whnf : Bool) : #Expr β Command
| eval : #Expr β Command
| unify : #Expr β #Expr β Command
| compile : #Name β Command
| help : HelpCmd β Command
| print : PrintCmd β Command
| userCommand (n : Name) : Modifiers β Array #Param β Command
deriving Inhabited
def spaced (f : Ξ± β Format) (mods : Array Ξ±) : Format :=
(Format.joinSep (mods.toList.map f) Format.line).fill
def spacedBefore (f : Ξ± β Format) (mods : Array Ξ±) : Format :=
(Format.join (mods.toList.map fun m => Format.line ++ f m)).fill
def spacedAfter (f : Ξ± β Format) (mods : Array Ξ±) : Format :=
(Format.join (mods.toList.map fun m => f m ++ Format.line)).fill
def suffix (pl : Bool) := if pl then "s " else " "
partial def Level_repr : Level β (prec : _ := 0) β Format
| Level.Β«_Β», _ => "_"
| Level.nat n, _ => repr n
| Level.add l n, p => Format.parenPrec 10 p $
Level_repr l.kind 10 ++ "+" ++ repr n
| Level.imax ls, p => Format.parenPrec max_prec p $
"imax" ++ Format.join (ls.toList.map fun l => " " ++ Level_repr l.kind max_prec)
| Level.max ls, p => Format.parenPrec max_prec p $
"max" ++ Format.join (ls.toList.map fun l => " " ++ Level_repr l.kind max_prec)
| Level.param u, _ => u.toString
| Level.paren l, _ => Level_repr l.kind
instance : Repr Level := β¨@Level_reprβ©
instance : Repr Levels where
reprPrec
| none, _ => ""
| some us, _ => (Format.joinSep (us.toList.map repr) ", ").bracket ".{" "}"
instance : Repr LevelDecl where
reprPrec
| none, _ => ""
| some us, _ => (Format.joinSep (us.toList.map fun u => u.kind.toString) ", ").bracket ".{" "}"
mutual
partial def Precedence_repr : Precedence β Format
| Precedence.nat n => repr n
| Precedence.expr e => Expr_repr e.kind max_prec
partial def optTy : Option #Expr β Format
| none => ""
| some e => " :" ++ Format.line ++ Expr_repr e.kind
partial def Default_repr : Option Default β Format
| none => ""
| some (Default.Β«:=Β» e) => " :=" ++ Format.line ++ Expr_repr e.kind
| some (Default.Β«.Β» n) => " ." ++ Format.line ++ (n.kind.toString : Format)
partial def Binder_repr : Binder β (paren :_:= true) β Format
| Binder.binder bi none _ e dflt, paren => bi.bracket paren $
(match e with | none => "β¬" | some e => Expr_repr e.kind) ++
Default_repr dflt
| Binder.binder bi (some vars) bis ty dflt, paren => bi.bracket paren $
spaced repr vars ++ Binders_repr bis ++ optTy ty ++ Default_repr dflt
| Binder.collection bi vars n rhs, paren => bi.bracket paren $
spaced repr vars ++ " " ++ n.toString ++ " " ++ Expr_repr rhs.kind
| Binder.notation n, _ => Format.paren s!"notation <{show Nat from n}>"
partial def Binders_repr (bis : Binders) (paren := true) : Format :=
let paren := paren || bis.size β 1
spacedBefore (fun m => Binder_repr m.kind paren) bis
partial def LambdaBinder_repr : LambdaBinder β (paren :_:= true) β Format
| LambdaBinder.reg bi, paren => Binder_repr bi paren
| LambdaBinder.Β«β¨β©Β» args, _ =>
(Format.joinSep (args.toList.map fun e => Expr_repr e.kind) ", ").bracket "β¨" "β©"
partial def LambdaBinders_repr (bis : Array #LambdaBinder) (paren := true) : Format :=
let paren := paren || bis.size β 1
spacedBefore (fun m => LambdaBinder_repr m.kind paren) bis
partial def LetDecl_repr : LetDecl β Format
| LetDecl.var v bis ty val =>
repr v ++ Binders_repr bis ++ optTy ty ++ " := " ++ Expr_repr val.kind
| LetDecl.pat pat val => Expr_repr pat.kind ++ " := " ++ Expr_repr val.kind
| LetDecl.notation n => s!"notation <{show Nat from n}>"
partial def Expr_repr : Expr β (prec : _ := 0) β Format
| Expr.Β«...Β», _ => "..."
| Expr.sorry, _ => "sorry"
| Expr.Β«_Β», _ => "_"
| Expr.Β«()Β», _ => "()"
| Expr.Β«{}Β», _ => "{}"
| Expr.ident n, _ => n.toString
| Expr.const n l cs, _ => n.kind.toString ++ cs.toList.toString ++ repr l
| Expr.nat n, _ => repr n
| Expr.decimal n d, _ => repr n ++ "/" ++ repr d
| Expr.string s, _ => repr s
| Expr.char c, _ => repr c
| Expr.paren e, p => Expr_repr e.kind p
| Expr.sort ty st u, p => Format.parenPrec max_prec p $
(if ty then "Type" else "Sort") ++
if st then ("*" : Format) else match u with | none => "" | some u => " " ++ Level_repr u.kind max_prec
| Expr.Β«βΒ» lhs rhs, p => Format.parenPrec 25 p $
Expr_repr lhs.kind 25 ++ " β " ++ Expr_repr rhs.kind 24
| Expr.fun as bis e, p => Format.parenPrec max_prec p $
((if as then "assume" else "Ξ»" : Format) ++
(match as, bis with
| true, #[β¨_, .reg (.binder _ none _ (some ty) _)β©] => ": " ++ Expr_repr ty.kind
| _, _ => LambdaBinders_repr bis false) ++
",").group ++ Format.line ++ Expr_repr e.kind
| Expr.Pi bis e, p => Format.parenPrec max_prec p $ ("β" ++
Binders_repr bis false ++ ",").group ++ Format.line ++ Expr_repr e.kind
| Expr.app f x, p => Format.parenPrec max_prec p $
(Expr_repr f.kind 1023 ++ Format.line ++ Expr_repr x.kind max_prec).fill
| Expr.show t pr, p => Format.parenPrec 1000 p $
"show " ++ Expr_repr t.kind ++ Proof_repr' pr.kind
| Expr.have suff h t pr e, p => Format.parenPrec 1000 p $
(if suff then "suffices " else "have ") ++
(match h with | none => "" | some h => h.kind.toString ++ " : ") ++
Expr_repr t.kind ++ Proof_repr' pr.kind ++
"," ++ Format.line ++ Expr_repr e.kind
| Expr.Β«.Β» compact e pr, _ =>
Expr_repr e.kind max_prec ++ (if compact then "." else "^.") ++ repr pr.kind
| Expr.if h c t e, p => Format.parenPrec 1000 p $ "if " ++
(match h with | none => "" | some h => h.kind.toString ++ " : ") ++
Expr_repr c.kind ++ " then " ++ Expr_repr t.kind ++ " else " ++ Expr_repr e.kind
| Expr.calc args, p => Format.parenPrec 1000 p $ "calc" ++
(Format.join $ args.toList.map fun (lhs, rhs) =>
Format.line ++ Expr_repr lhs.kind ++ " : " ++ Expr_repr rhs.kind).nest 2
| Expr.Β«@Β» part e, _ => (if part then "@@" else "@") ++ Expr_repr e.kind max_prec
| Expr.pattern e, p => Format.parenPrec 1000 p $ "(: " ++ Expr_repr e.kind ++ " :)"
| Expr.Β«`()Β» lazy expr e, p => Format.parenPrec 1000 p $
(if expr then "`(" else if lazy then "```(" else "``(") ++
(match e.kind with
| Expr.Β«:Β» e ty => Expr_repr e.kind ++ " : " ++ Expr_repr ty.kind
| _ => Expr_repr e.kind : Format) ++ ")"
| Expr.Β«%%Β» e, p => Format.parenPrec 1000 p $ "%%" ++ Expr_repr e.kind
| Expr.Β«`[]Β» tacs, p => Format.parenPrec 1000 p $
(Format.joinSep (tacs.toList.map fun t => Tactic_repr t.kind) ", ").bracket "`[" "]"
| Expr.Β«`Β» res n, p => Format.parenPrec 1000 p $
(if res then "``" else "`" : Format) ++ n.toString
| Expr.Β«β¨β©Β» es, _ =>
(Format.joinSep (es.toList.map fun e => Expr_repr e.kind) ", ").bracket "β¨" "β©"
| Expr.infix_fn c e, p => Format.parenPrec 1000 p $
"(" ++ repr c ++ (match e with | none => "" | some e => " " ++ Expr_repr e.kind) ++ ")"
| Expr.Β«(,)Β» es, _ =>
(Format.joinSep (es.toList.map fun e => Expr_repr e.kind) ", ").paren
| Expr.Β«.()Β» e, _ => "." ++ Expr_repr e.kind max_prec
| Expr.Β«:Β» e ty, _ => "(" ++ Expr_repr e.kind ++ " : " ++ Expr_repr ty.kind ++ ")"
| Expr.hole es, p => Format.parenPrec 1000 p $
(Format.joinSep (es.toList.map fun e => Expr_repr e.kind) ", ").bracket "{! " " !}"
| Expr.Β«#[]Β» es, p => Format.parenPrec 1000 p $
(Format.joinSep (es.toList.map fun e => Expr_repr e.kind) ", ").bracket "#[" "]"
| Expr.by tac, p => Format.parenPrec 1000 p $ "by " ++ Tactic_repr tac.kind
| Expr.begin tacs, p => Format.parenPrec 1000 p $ Block_repr tacs
| Expr.let bis e, p => Format.parenPrec 1000 p $
("let " ++ (("," ++ Format.line).joinSep
(bis.toList.map fun bi => LetDecl_repr bi.kind)).nest 4 ++ " in").group ++
Format.line ++ Expr_repr e.kind
| Expr.match xs ty eqns, _ => "match " ++
Format.joinSep (xs.toList.map fun x => Expr_repr x.kind) ", " ++ optTy ty ++ " with" ++
(if eqns.isEmpty then " end" else Arms_repr eqns ++ Format.line ++ "end" : Format)
| Expr.do braces els, p => Format.parenPrec 1000 p $
let s := Format.line ++ (("," ++ Format.line).joinSep
(els.toList.map fun el => DoElem_repr el.kind)).nest 2
if braces then "do" ++ s else "do {" ++ s ++ " }"
| Expr.Β«{,}Β» es, _ => (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) ", ").bracket "{" "}"
| Expr.subtype setOf x ty p, _ =>
"{" ++ x.kind.toString ++ optTy ty ++
(if setOf then " | " else " // ") ++ Expr_repr p.kind ++ "}"
| Expr.sep x ty p, _ =>
"{" ++ x.kind.toString ++ " β " ++ Expr_repr ty.kind ++ " | " ++ Expr_repr p.kind ++ "}"
| Expr.setReplacement e bis, _ =>
"{(" ++ Expr_repr e.kind ++ ") |" ++ Binders_repr bis false ++ "}"
| Expr.structInst S src flds srcs catchall, _ => Format.nest 2 $ Format.group $ "{ " ++
(match S with | none => "" | some S => S.kind.toString ++ " ." ++ Format.line : Format) ++
(match src with | none => "" | some s => Expr_repr s.kind ++ " with" ++ Format.line : Format) ++
(("," ++ Format.line).joinSep $
flds.toList.map (fun (i, s) => i.kind.toString ++ " := " ++ Expr_repr s.kind) ++
srcs.toList.map (fun s => ".." ++ Expr_repr s.kind) ++
if catchall then [(".." : Format)] else []) ++ " }"
| Expr.atPat lhs rhs, p => Format.parenPrec 1000 p $
lhs.kind.toString ++ "@" ++ Expr_repr rhs.kind max_prec
| Expr.notation n args, _ => repr n ++
(Format.joinSep (args.toList.map fun e => Arg_repr e.kind) ("," ++ Format.line)).paren
| Expr.userNotation n args, p => Format.parenPrec 1000 p $ n.toString ++
Format.join (args.toList.map fun a => " " ++ Param_repr a.kind)
partial def Arg_repr : Arg β Format
| Arg.expr e => Expr_repr e
| Arg.exprs es => (Format.joinSep (es.toList.map fun e => Expr_repr e.kind) ", ").sbracket
| Arg.binder bi => Binder_repr bi
| Arg.binders bis => spaced (fun m => Binder_repr m.kind) bis
partial def Arm_repr : Arm β Format
| β¨lhs, rhsβ© =>
"\n| " ++ Format.joinSep (lhs.toList.map fun e => Expr_repr e.kind) ", " ++
" := " ++ Expr_repr rhs.kind
partial def DoElem_repr : DoElem β Format
| DoElem.let bi => "let " ++ LetDecl_repr bi.kind
| DoElem.Β«βΒ» lhs ty rhs els =>
Expr_repr lhs.kind ++ optTy ty ++ " β " ++ Expr_repr rhs.kind ++
match els with | none => "" | some e => " | " ++ Expr_repr e.kind
| DoElem.eval e => Expr_repr e.kind
partial def Arms_repr (arms : Array Arm) : Format :=
if arms.isEmpty then "." else Format.join $ arms.toList.map Arm_repr
partial def Proof_repr' : Proof β Format
| Proof.from true e => " := " ++ Expr_repr e.kind
| p => ", " ++ Proof_repr p
partial def Proof_repr : Proof β Format
| Proof.from _ e => "from " ++ Expr_repr e.kind
| Proof.block tacs => Block_repr tacs
| Proof.by tac => "by " ++ Tactic_repr tac.kind
partial def Tactic_repr : Tactic β Format
| Tactic.Β«;Β» tacs =>
Format.joinSep (tacs.toList.map fun t => Tactic_repr t.kind) "; "
| Tactic.Β«<|>Β» tacs =>
Format.joinSep (tacs.toList.map fun t => Tactic_repr t.kind) " <|> "
| Tactic.Β«[]Β» tacs =>
(Format.joinSep (tacs.toList.map fun t => Tactic_repr t.kind) ", ").sbracket
| Tactic.block tacs => Block_repr tacs
| Tactic.by tac => "by " ++ Tactic_repr tac.kind
| Tactic.exact_shortcut e => Expr_repr e.kind
| Tactic.expr tac => Expr_repr tac.kind
| Tactic.interactive n args => n.toString ++
Format.join (args.toList.map fun a => " " ++ Param_repr a.kind)
partial def Block_repr : Block β Format
| β¨curly, cl, cfg, tacsβ© =>
let sβ := match cl with | none => "" | some cl => " [" ++ cl.kind.toString ++ "]"
let sβ : Format := match cfg with | none => "" | some e => " with " ++ Expr_repr e.kind ++ ","
let sβ := ("," ++ Format.line).joinSep (tacs.toList.map fun t => Tactic_repr t.kind)
if curly then
("{" ++ sβ ++ sβ ++ (if cl.isSome || cfg.isSome then Format.line else " ") ++ sβ ++ " }").nest 2
else
("begin" ++ sβ ++ sβ ++ Format.line ++ sβ).nest 2 ++ Format.line ++ "end"
partial def Param_repr : Param β Format
| Param.parse _ calls => Format.sbracket $
(", ":Format).joinSep $ calls.toList.map fun c => VMCall_repr c.kind
| Param.expr e => Expr_repr e.kind
| Param.block e => Block_repr e
partial def VMCall_repr : VMCall β Format
| VMCall.ident n => "ident " ++ (n.toString:Format)
| VMCall.nat n => repr n
| VMCall.token tk => repr tk
| VMCall.pat e => "pat " ++ Expr_repr e
| VMCall.expr e => "expr " ++ Expr_repr e
| VMCall.binders bis => "binders" ++ Binders_repr bis
| VMCall.block bl => Block_repr bl
| VMCall.inductive c => s!"inductive <{show Nat from c}>"
| VMCall.command c => s!"command <{repr $ show Option Nat from c}>"
| VMCall.withInput calls _ => Format.sbracket $
(", ":Format).joinSep $ calls.toList.map fun c => VMCall_repr c.kind
partial def optPrec_repr : Option #Precedence β Format
| none => ""
| some p => ":" ++ Precedence_repr p.kind
partial def PrecSymbol_repr : PrecSymbol β Format
| (sym, prec) => repr sym ++ optPrec_repr prec
partial def Action_repr : Action β Format
| Action.prec p => Precedence_repr p
| Action.prev => "prev"
| Action.scoped p none => "scoped" ++ optPrec_repr p
| Action.scoped p (some (x, e)) =>
"(scoped" ++ optPrec_repr p ++ " " ++ x.kind.toString ++ ", " ++ Expr_repr e.kind ++ ")"
| Action.fold r p sep (x, y, Β«recΒ») ini term =>
"(fold" ++ (if r then "r" else "l") ++ optPrec_repr p ++ " " ++
PrecSymbol_repr sep ++
" (" ++ x.kind.toString ++ " " ++ y.kind.toString ++ ", " ++ Expr_repr rec.kind ++ ")" ++
(match ini with | none => "" | some ini => " " ++ Expr_repr ini.kind) ++
(match term with | none => "" | some term => " " ++ PrecSymbol_repr term) ++ ")"
partial def Literal_repr : Literal β Format
| Literal.nat n => repr n
| Literal.sym sym => PrecSymbol_repr sym
| Literal.binder prec => "binder" ++ optPrec_repr prec
| Literal.binders prec => "binders" ++ optPrec_repr prec
| Literal.var v a => (v.kind.toString : Format) ++
match a with | none => "" | some a => ":" ++ Action_repr a.kind
end
instance : Repr Precedence := β¨fun n _ => Precedence_repr nβ©
instance : Repr Binder := β¨fun n _ => Binder_repr nβ©
instance : Repr Binders := β¨fun n _ => Binders_repr nβ©
instance : Repr Expr := β¨fun n _ => Expr_repr nβ©
instance : Repr Arg := β¨fun n _ => Arg_repr nβ©
instance : Repr Arm := β¨fun n _ => Arm_repr nβ©
instance : Repr DoElem := β¨fun n _ => DoElem_repr nβ©
instance : Repr Proof := β¨fun n _ => Proof_repr nβ©
instance : Repr Tactic := β¨fun n _ => Tactic_repr nβ©
instance : Repr Block := β¨fun n _ => Block_repr nβ©
instance : Repr Param := β¨fun n _ => Param_repr nβ©
instance : Repr VMCall := β¨fun n _ => VMCall_repr nβ©
instance : Repr PrecSymbol := β¨fun n _ => PrecSymbol_repr nβ©
instance : Repr Action := β¨fun n _ => Action_repr nβ©
instance : Repr Literal := β¨fun n _ => Literal_repr nβ©
instance : Repr AttrArg where reprPrec
| AttrArg.eager, _ => "!"
| AttrArg.indices ns, _ => spacedBefore repr ns
| AttrArg.keyValue a b, _ => " " ++ repr a ++ " " ++ repr b
| AttrArg.vmOverride a b, _ => " " ++ repr a ++
(match b with | none => "" | some b => " " ++ repr b : Format)
| AttrArg.user _ e, _ => repr e
instance : Repr Attribute where reprPrec
| Attribute.priority e, _ => "priority " ++ Expr_repr e.kind
| Attribute.del n, _ => ("-":Format) ++ n.toString
| Attribute.add n arg, _ => n.toString ++
(match arg with | none => "" | some arg => " " ++ repr arg : Format)
instance : Repr Attributes :=
β¨fun attrs _ => (Format.joinSep (attrs.toList.map repr) ", ").sbracketβ©
def Notation_repr : Notation β (attrs : Attributes := #[]) β Format
| Notation.mixfix mk name sym val, attrs => repr mk ++
(if attrs.isEmpty then "" else " " ++ repr attrs : Format) ++
(match name with | none => "" | some n => f!" (name := {repr n})") ++
" " ++ PrecSymbol_repr sym ++
(match val with | none => "" | some e => " := " ++ Expr_repr e.kind)
| Notation.notation name lits val, attrs => "notation" ++
(if attrs.isEmpty then "" else " " ++ repr attrs : Format) ++
(match name with | none => "" | some n => f!" (name := {repr n})") ++
spacedBefore (fun n => Literal_repr n.kind) lits ++
(match val with | none => "" | some e => " := " ++ Expr_repr e.kind)
instance : Repr Notation := β¨fun n _ => Notation_repr nβ©
instance : Repr DeclVal where reprPrec
| DeclVal.expr n, _ => " :=" ++ Format.line ++ repr n
| DeclVal.eqns arms, _ => Format.join (arms.toList.map repr)
instance : Repr Modifier where reprPrec
| Modifier.private, _ => "private"
| Modifier.protected, _ => "protected"
| Modifier.noncomputable, _ => "noncomputable"
| Modifier.meta, _ => "meta"
| Modifier.mutual, _ => "mutual"
| Modifier.doc s, _ => ("/--" ++ s ++ "-/" : String)
| Modifier.attr l c attrs, _ =>
(if l then "local " else "") ++ (if c then "@" else "attribute ") ++ repr attrs
def Modifiers_repr : Modifiers β Format := spacedAfter repr
instance : Repr Modifiers := β¨fun n _ => Modifiers_repr nβ©
instance : Repr Intro where reprPrec
| β¨doc, name, ik, bis, tyβ©, _ =>
(match doc with | none => "" | some doc => "\n/--" ++ doc ++ "-/") ++
"\n| " ++ name.kind.toString ++ InferKind.optRepr ik ++ repr bis ++ optTy ty
def Intros_repr (arms : Array #Intro) : Format :=
Format.join $ arms.toList.map repr
def Mutual_repr (f : Array Ξ± β Format) : Mutual Ξ± β Format
| β¨attr, n, ty, valsβ© =>
"with " ++ repr attr ++ " " ++ n.kind.toString ++ " : " ++
Expr_repr ty.kind ++ f vals
instance : Repr Mk where reprPrec
| β¨mk, ikβ©, _ => mk.kind.toString ++ InferKind.optRepr ik
instance : Repr Rename where reprPrec
| β¨Β«fromΒ», toβ©, _ => (Β«fromΒ».kind.toString ++ "β" ++ to.kind.toString : String)
instance : Repr Parent where reprPrec
| β¨priv, n, ty, rensβ©, _ =>
(if priv then "private " else "") ++
(match n with | none => "" | some n => n.kind.toString ++ " : ") ++ repr ty ++
if rens.isEmpty then ("":Format) else "renaming" ++ spacedBefore repr rens
instance : Repr Field where reprPrec
| Field.binder bi vars ik bis ty dflt, _ => bi.bracket true $
spaced (fun v => v.kind.toString) vars ++ InferKind.optRepr ik ++
Binders_repr bis ++ optTy ty ++ Default_repr dflt
| Field.notation n, _ => (repr n).paren
instance : Repr OpenClause where reprPrec
| OpenClause.explicit ns, _ => spaced (fun n => n.kind.toString) ns
| OpenClause.renaming rens, _ => "renaming" ++ spacedBefore repr rens
| OpenClause.hiding ns, _ => "hiding" ++ spacedBefore (fun n => n.kind.toString) ns
instance : Repr Open where reprPrec
| β¨tgt, as, clsβ©, _ => tgt.kind.toString ++
(match as with | none => "" | some as => " as " ++ as.kind.toString) ++
spacedBefore (fun i => (repr i).paren) cls
instance : Repr HelpCmd where
reprPrec
| HelpCmd.options, _ => "options"
| HelpCmd.commands, _ => "commands"
instance : Repr PrintCmd where reprPrec c _ := match c with
| PrintCmd.str n => repr n
| PrintCmd.raw e => "raw " ++ (repr e).nest 2
| PrintCmd.options => "options"
| PrintCmd.trust => "trust"
| PrintCmd.keyEquivalences => "key_equivalences"
| PrintCmd.def n => "def " ++ repr n
| PrintCmd.instances n => ("instances " : Format) ++ n.kind.toString
| PrintCmd.classes => "classes"
| PrintCmd.attributes => "attributes"
| PrintCmd.prefix n => ("prefix " : Format) ++ n.kind.toString
| PrintCmd.aliases => "aliases"
| PrintCmd.axioms n => ("axioms" : Format) ++
(match n with | none => "" | some n => " " ++ n.kind.toString : String)
| PrintCmd.fields n => ("fields " : Format) ++ n.kind.toString
| PrintCmd.notation ns => ("notation" : Format) ++ spacedBefore (fun n => n.kind.toString) ns
| PrintCmd.inductive n => ("inductive " : Format) ++ n.kind.toString
| PrintCmd.attr n => (n.kind.toName.toString : Format).sbracket
| PrintCmd.token n => n.kind.toString
| PrintCmd.ident n => n.kind.toString
instance : Repr InductiveCmd where reprPrec c _ := match c with
| InductiveCmd.reg cl mods n us bis ty nota intros =>
repr mods ++ (if cl then "class " else "") ++ "inductive " ++
n.kind.toString ++ repr us ++ repr bis ++ optTy ty ++
(match nota with | none => "" | some n => "\n" ++ repr n) ++
Intros_repr intros
| InductiveCmd.mutual cl mods us bis nota inds =>
repr mods ++ (if cl then "class " else "") ++ "inductive " ++ repr us ++
Format.joinSep (inds.toList.map fun m => m.name.kind.toString) ", " ++ repr bis ++
(match nota with | none => "" | some n => "\n" ++ repr n) ++
Format.join (inds.toList.map (Mutual_repr Intros_repr))
instance : Repr Command where reprPrec c _ := match c with
| Command.initQuotient => "init_quotient"
| Command.mdoc s => ("/-!" ++ s ++ "-/" : String)
| Command.Β«universeΒ» var pl ns =>
"universe" ++ (if var then " variable" else "") ++ suffix pl ++
Format.joinSep (ns.toList.map fun a => a.kind.toString) " "
| Command.Β«namespaceΒ» n => ("namespace ":Format) ++ n.kind.toString
| Command.Β«sectionΒ» (some n) => ("section ":Format) ++ n.kind.toString
| Command.Β«sectionΒ» none => "section"
| Command.Β«endΒ» (some n) => ("end ":Format) ++ n.kind.toString
| Command.Β«endΒ» none => "end"
| Command.Β«variableΒ» vk plural mods bis =>
repr mods ++ repr vk ++ (if plural then "s" else "") ++ Binders_repr bis plural
| Command.axiom ak mods n us bis ty =>
repr mods ++ repr ak ++ " " ++ n.kind.toString ++
repr us ++ repr bis ++ optTy ty
| Command.axioms ak mods bis => repr mods ++ repr ak ++ "s" ++ repr bis
| Command.decl dk mods n us bis ty val uwf =>
repr mods ++ (repr dk ++
(match n with | none => "" | some n => " " ++ n.kind.toString : String) ++
repr us ++ repr bis ++ optTy ty).group.nest 2 ++ repr val.kind ++
(match uwf with | none => "" | some e => "\nusing_well_founded " ++ (repr e).nest 2)
| Command.mutualDecl dk mods us bis arms uwf =>
repr mods ++ repr dk ++ " " ++ repr us ++
Format.joinSep (arms.toList.map fun m => m.name.kind.toString) ", " ++
repr bis ++ Format.join (arms.toList.map (Mutual_repr Arms_repr)) ++
(match uwf with | none => "" | some e => "\nusing_well_founded " ++ (repr e).nest 2)
| Command.inductive ind => repr ind
| Command.structure cl mods n us bis exts ty mk flds =>
repr mods ++ (if cl then "class " else "structure ") ++
n.kind.toString ++ repr us ++ repr bis ++
(if exts.isEmpty then ("":Format) else "extends " ++
((", ":Format).joinSep $ exts.toList.map repr)) ++ optTy ty ++
if mk.isNone && flds.isEmpty then ("":Format) else " :=" ++
(match mk with | none => "" | some mk => " " ++ repr mk ++
if flds.isEmpty then "" else " ::" : Format) ++
((Format.join $ flds.toList.map fun f => Format.line ++ repr f).group).nest 2
| Command.attribute loc mods attrs ns =>
repr mods ++ (if loc then "local " else "") ++ "attribute" ++
(if attrs.isEmpty then "" else " " ++ repr attrs : Format) ++ spacedBefore (fun n => n.kind.toString) ns
| Command.precedence sym prec => "precedence " ++ repr sym ++ ":" ++ repr prec
| Command.notation loc attrs n => repr loc ++ Notation_repr n attrs
| Command.open exp ops => (if exp then "export" else "open") ++ spacedBefore repr ops
| Command.include pos ops => (if pos then "include" else "omit") ++
spacedBefore (fun n => n.kind.toString) ops
| Command.hide ops => "hide" ++ spacedBefore (fun n => n.kind.toString) ops
| Command.theory mods => repr mods ++ "theory"
| Command.setOption n val => "set_option " ++ n.kind.toString ++ " " ++ repr val
| Command.declareTrace n => ("declare_trace " : Format) ++ n.kind.toString
| Command.addKeyEquivalence a b => ("add_key_equivalence " : Format) ++
a.kind.toString ++ " " ++ b.kind.toString
| Command.runCmd e => "run_cmd " ++ (repr e).nest 2
| Command.check e => "#check " ++ (repr e).nest 2
| Command.reduce whnf e => "#reduce " ++ (if whnf then "[whnf] " else "") ++ (repr e).nest 2
| Command.eval e => "#eval " ++ (repr e).nest 2
| Command.unify eβ eβ => "#unify " ++ (repr eβ ++ ", " ++ repr eβ).nest 2
| Command.compile n => ("#compile ":Format) ++ n.kind.toString
| Command.help n => "#help " ++ repr n
| Command.print n => "#print " ++ repr n
| Command.userCommand n mods args => repr mods ++ n.toString ++
Format.join (args.toList.map fun a => " " ++ Param_repr a.kind)
def Notation.name (sp : Char) (f : PrecSymbol β String) (withTerm : Bool) (start : String) :
Notation β Name
| Notation.notation (some name) .. | Notation.mixfix _ (some name) .. => name.kind
| Notation.notation none lits _ => Id.run do
let mut s := start
for β¨_, litβ© in lits do
match lit with
| Literal.nat n => s := s ++ toString n
| Literal.sym tk => s := s ++ f tk
| Literal.var _ none => s := s.push sp
| Literal.var _ (some β¨_, Action.prec _β©) => s := s.push sp
| Literal.var _ (some β¨_, Action.prevβ©) => s := s.push sp
| Literal.var _ (some β¨_, Action.scoped _ _β©) => s := s.push sp
| Literal.var _ (some β¨_, Action.fold _ _ sep _ _ termβ©) =>
s := s.push sp ++ f sep
if withTerm then if let some term := term then s := s ++ f term
| Literal.binder _ => s := s.push sp
| Literal.binders _ => s := s.push sp
Name.mkSimple s
| Notation.mixfix mk none tk _ =>
Name.mkSimple <| match mk with
| MixfixKind.infix => start.push sp ++ (f tk).push sp
| MixfixKind.infixl => start.push sp ++ (f tk).push sp
| MixfixKind.infixr => start.push sp ++ (f tk).push sp
| MixfixKind.postfix => start.push sp ++ f tk
| MixfixKind.prefix => start ++ (f tk).push sp
def Notation.name3 := Notation.name ' ' (Β·.1.kind.trim) true "expr"
def Notation.name4 := Notation.name '_' (Β·.1.kind.trim) false "term"
def Attributes.hasToAdditive (attrs : Attributes) : Bool :=
attrs.any (Β· matches β¨_, .add `to_additive _β©)
def Modifiers.hasToAdditive (mods : Modifiers) : Bool :=
mods.any fun
| β¨_, .attr _ _ attrsβ© => attrs.hasToAdditive
| _ => false
structure Hyp where
name : Name
pp : Name
type : Lean3.Expr
value : Option Lean3.Expr
instance : Repr Hyp where reprPrec
| β¨_, pp, t, vβ©, _ =>
pp.toString ++ " : " ++ repr t ++
match v with | none => ("":Format) | some v => repr v
structure Goal where
hyps : Array Hyp
target : Lean3.Expr
instance : Repr Goal where reprPrec
| β¨hyps, targetβ©, _ =>
Format.join (hyps.toList.map fun hyp => repr hyp ++ "\n") ++
"β’ " ++ repr target
def Goals_repr (gs : Array Goal) : Format :=
Format.join (gs.toList.map fun g => repr g ++ "\n")
structure TacticInvocation where
declName : Name
ast : Option #Tactic
start : Array Goal
Β«endΒ» : Array Goal
success : Bool
instance : Repr TacticInvocation where reprPrec
| β¨declName, tac, start, end_, successβ©, _ =>
"in declaration " ++ toString declName ++ " " ++
"invoking " ++ repr tac ++ ":\n" ++
"before:\n" ++ Goals_repr start ++
(if success then "success" else "failed") ++ ", after:\n" ++ Goals_repr end_
structure Comment where
start : Position
Β«endΒ» : Position
text : String
deriving Repr, Inhabited
end AST3
structure AST3 where
Β«preludeΒ» : Option #Unit
Β«importΒ» : Array (Array #Name)
commands : Array (Spanned AST3.Command)
indexed_nota : Array AST3.Notation
indexed_cmds : Array AST3.Command
comments : Array AST3.Comment
instance : Repr AST3 where reprPrec
| β¨prel, imps, cmds, _, _, _β©, _ =>
(match prel with | none => "" | some _ => "prelude\n") ++
Format.join (imps.toList.map fun ns =>
"import " ++ Format.joinSep (ns.toList.map fun a => a.kind.toString) " " ++ "\n") ++
"\n" ++ Format.join (cmds.toList.map fun c => repr c ++ "\n\n")
partial def Spanned.unparen : #AST3.Expr β #AST3.Expr
| β¨_, AST3.Expr.paren eβ© => e.unparen
| e => e
end Mathport
|
44359d8e377b8cdf4dd3cda75579c5c82ff4c79d | e00ea76a720126cf9f6d732ad6216b5b824d20a7 | /src/tactic/ring.lean | 74ef9adf71e7d98914b1654f30ecd9c07cfbba0e | [
"Apache-2.0"
] | permissive | vaibhavkarve/mathlib | a574aaf68c0a431a47fa82ce0637f0f769826bfe | 17f8340912468f49bdc30acdb9a9fa02eeb0473a | refs/heads/master | 1,621,263,802,637 | 1,585,399,588,000 | 1,585,399,588,000 | 250,833,447 | 0 | 0 | Apache-2.0 | 1,585,410,341,000 | 1,585,410,341,000 | null | UTF-8 | Lean | false | false | 21,846 | 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.group_power tactic.norm_num
import tactic.converter.interactive
/-!
# `ring`
Evaluate expressions in the language of commutative (semi)rings.
Based on <http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf> .
-/
namespace tactic
namespace ring
def horner {Ξ±} [comm_semiring Ξ±] (a x : Ξ±) (n : β) (b : Ξ±) := a * x ^ n + b
meta structure cache :=
(Ξ± : expr)
(univ : level)
(comm_semiring_inst : expr)
(red : transparency)
meta def ring_m (Ξ± : Type) : Type :=
reader_t cache (state_t (buffer expr) tactic) Ξ±
meta instance : monad ring_m := by dunfold ring_m; apply_instance
meta instance : alternative ring_m := by dunfold ring_m; apply_instance
meta def get_cache : ring_m cache := reader_t.read
meta def get_atom (n : β) : ring_m expr :=
reader_t.lift $ (Ξ» es : buffer expr, es.read' n) <$> state_t.get
meta def get_transparency : ring_m transparency :=
cache.red <$> get_cache
meta def add_atom (e : expr) : ring_m β :=
do red β get_transparency,
reader_t.lift β¨Ξ» es, (do
n β es.iterate failed (Ξ» n e' t, t <|> (is_def_eq e e' red $> n)),
return (n, es)) <|> return (es.size, es.push_back e)β©
meta def lift {Ξ±} (m : tactic Ξ±) : ring_m Ξ± :=
reader_t.lift (state_t.lift m)
meta def ring_m.run (red : transparency) (e : expr) {Ξ±} (m : ring_m Ξ±) : tactic Ξ± :=
do Ξ± β infer_type e,
c β mk_app ``comm_semiring [Ξ±] >>= mk_instance,
u β mk_meta_univ,
infer_type Ξ± >>= unify (expr.sort (level.succ u)),
u β get_univ_assignment u,
prod.fst <$> state_t.run (reader_t.run m β¨Ξ±, u, c, redβ©) mk_buffer
meta def cache.cs_app (c : cache) (n : name) : list expr β expr :=
(@expr.const tt n [c.univ] c.Ξ± c.comm_semiring_inst).mk_app
meta def ring_m.mk_app (n inst : name) (l : list expr) : ring_m expr :=
do c β get_cache,
m β lift $ mk_instance ((expr.const inst [c.univ] : expr) c.Ξ±),
return $ (@expr.const tt n [c.univ] c.Ξ± m).mk_app l
meta inductive horner_expr : Type
| const (e : expr) : horner_expr
| xadd (e : expr) (a : horner_expr) (x : expr Γ β) (n : expr Γ β) (b : horner_expr) : horner_expr
meta def horner_expr.e : horner_expr β expr
| (horner_expr.const e) := e
| (horner_expr.xadd e _ _ _ _) := e
meta instance : has_coe horner_expr expr := β¨horner_expr.eβ©
meta def horner_expr.xadd' (c : cache) (a : horner_expr)
(x : expr Γ β) (n : expr Γ β) (b : horner_expr) : horner_expr :=
horner_expr.xadd (c.cs_app ``horner [a, x.1, n.1, b]) a x n b
open horner_expr
meta def horner_expr.to_string : horner_expr β string
| (const e) := to_string e
| (xadd e a x (_, n) b) :=
"(" ++ a.to_string ++ ") * (" ++ to_string x.1 ++ ")^"
++ to_string n ++ " + " ++ b.to_string
meta def horner_expr.pp : horner_expr β tactic format
| (const e) := pp e
| (xadd e a x (_, n) b) := do
pa β a.pp, pb β b.pp, px β pp x.1,
return $ "(" ++ pa ++ ") * (" ++ px ++ ")^" ++ to_string n ++ " + " ++ pb
meta instance : has_to_tactic_format horner_expr := β¨horner_expr.ppβ©
meta def horner_expr.refl_conv (e : horner_expr) : ring_m (horner_expr Γ expr) :=
do p β lift $ mk_eq_refl e, return (e, p)
theorem zero_horner {Ξ±} [comm_semiring Ξ±] (x n b) :
@horner Ξ± _ 0 x n b = b :=
by simp [horner]
theorem horner_horner {Ξ±} [comm_semiring Ξ±] (aβ x nβ nβ b n')
(h : nβ + nβ = n') :
@horner Ξ± _ (horner aβ x nβ 0) x nβ b = horner aβ x n' b :=
by simp [h.symm, horner, pow_add, mul_assoc]
meta def eval_horner : horner_expr β expr Γ β β expr Γ β β horner_expr β ring_m (horner_expr Γ expr)
| ha@(const a) x n b := do
c β get_cache,
if a.to_nat = some 0 then
return (b, c.cs_app ``zero_horner [x.1, n.1, b])
else (xadd' c ha x n b).refl_conv
| ha@(xadd a aβ xβ nβ bβ) x n b := do
c β get_cache,
if xβ.2 = x.2 β§ bβ.e.to_nat = some 0 then do
(n', h) β lift $ mk_app ``has_add.add [nβ.1, n.1] >>= norm_num,
return (xadd' c aβ x (n', nβ.2 + n.2) b,
c.cs_app ``horner_horner [aβ, x.1, nβ.1, n.1, b, n', h])
else (xadd' c ha x n b).refl_conv
theorem const_add_horner {Ξ±} [comm_semiring Ξ±] (k a x n b b') (h : k + b = b') :
k + @horner Ξ± _ a x n b = horner a x n b' :=
by simp [h.symm, horner]; cc
theorem horner_add_const {Ξ±} [comm_semiring Ξ±] (a x n b k b') (h : b + k = b') :
@horner Ξ± _ a x n b + k = horner a x n b' :=
by simp [h.symm, horner]
theorem horner_add_horner_lt {Ξ±} [comm_semiring Ξ±] (aβ x nβ bβ aβ nβ bβ k a' b')
(hβ : nβ + k = nβ) (hβ : (aβ + horner aβ x k 0 : Ξ±) = a') (hβ : bβ + bβ = b') :
@horner Ξ± _ aβ x nβ bβ + horner aβ x nβ bβ = horner a' x nβ b' :=
by simp [hβ.symm, hβ.symm, hβ.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc
theorem horner_add_horner_gt {Ξ±} [comm_semiring Ξ±] (aβ x nβ bβ aβ nβ bβ k a' b')
(hβ : nβ + k = nβ) (hβ : (horner aβ x k 0 + aβ : Ξ±) = a') (hβ : bβ + bβ = b') :
@horner Ξ± _ aβ x nβ bβ + horner aβ x nβ bβ = horner a' x nβ b' :=
by simp [hβ.symm, hβ.symm, hβ.symm, horner, pow_add, mul_add, mul_comm, mul_left_comm]; cc
-- set_option trace.class_instances true
-- set_option class.instance_max_depth 128
theorem horner_add_horner_eq {Ξ±} [comm_semiring Ξ±] (aβ x n bβ aβ bβ a' b' t)
(hβ : aβ + aβ = a') (hβ : bβ + bβ = b') (hβ : horner a' x n b' = t) :
@horner Ξ± _ aβ x n bβ + horner aβ x n bβ = t :=
by simp [hβ.symm, hβ.symm, hβ.symm, horner, add_mul, mul_comm]; cc
meta def eval_add : horner_expr β horner_expr β ring_m (horner_expr Γ expr)
| (const eβ) (const eβ) := do
(e, p) β lift $ mk_app ``has_add.add [eβ, eβ] >>= norm_num,
return (const e, p)
| heβ@(const eβ) heβ@(xadd eβ a x n b) := do
c β get_cache,
if eβ.to_nat = some 0 then do
p β lift $ mk_app ``zero_add [eβ],
return (heβ, p)
else do
(b', h) β eval_add heβ b,
return (xadd' c a x n b',
c.cs_app ``const_add_horner [eβ, a, x.1, n.1, b, b', h])
| heβ@(xadd eβ a x n b) heβ@(const eβ) := do
c β get_cache,
if eβ.to_nat = some 0 then do
p β lift $ mk_app ``add_zero [eβ],
return (heβ, p)
else do
(b', h) β eval_add b heβ,
return (xadd' c a x n b',
c.cs_app ``horner_add_const [a, x.1, n.1, b, eβ, b', h])
| heβ@(xadd eβ aβ xβ nβ bβ) heβ@(xadd eβ aβ xβ nβ bβ) := do
c β get_cache,
if xβ.2 < xβ.2 then do
(b', h) β eval_add bβ heβ,
return (xadd' c aβ xβ nβ b',
c.cs_app ``horner_add_const [aβ, xβ.1, nβ.1, bβ, eβ, b', h])
else if xβ.2 β xβ.2 then do
(b', h) β eval_add heβ bβ,
return (xadd' c aβ xβ nβ b',
c.cs_app ``const_add_horner [eβ, aβ, xβ.1, nβ.1, bβ, b', h])
else if nβ.2 < nβ.2 then do
let k := nβ.2 - nβ.2,
ek β lift $ expr.of_nat (expr.const `nat []) k,
(_, hβ) β lift $ mk_app ``has_add.add [nβ.1, ek] >>= norm_num,
Ξ±0 β lift $ expr.of_nat c.Ξ± 0,
(a', hβ) β eval_add aβ (xadd' c aβ xβ (ek, k) (const Ξ±0)),
(b', hβ) β eval_add bβ bβ,
return (xadd' c a' xβ nβ b',
c.cs_app ``horner_add_horner_lt [aβ, xβ.1, nβ.1, bβ, aβ, nβ.1, bβ, ek, a', b', hβ, hβ, hβ])
else if nβ.2 β nβ.2 then do
let k := nβ.2 - nβ.2,
ek β lift $ expr.of_nat (expr.const `nat []) k,
(_, hβ) β lift $ mk_app ``has_add.add [nβ.1, ek] >>= norm_num,
Ξ±0 β lift $ expr.of_nat c.Ξ± 0,
(a', hβ) β eval_add (xadd' c aβ xβ (ek, k) (const Ξ±0)) aβ,
(b', hβ) β eval_add bβ bβ,
return (xadd' c a' xβ nβ b',
c.cs_app ``horner_add_horner_gt [aβ, xβ.1, nβ.1, bβ, aβ, nβ.1, bβ, ek, a', b', hβ, hβ, hβ])
else do
(a', hβ) β eval_add aβ aβ,
(b', hβ) β eval_add bβ bβ,
(t, hβ) β eval_horner a' xβ nβ b',
return (t, c.cs_app ``horner_add_horner_eq
[aβ, xβ.1, nβ.1, bβ, aβ, bβ, a', b', t, hβ, hβ, hβ])
theorem horner_neg {Ξ±} [comm_ring Ξ±] (a x n b a' b')
(hβ : -a = a') (hβ : -b = b') :
-@horner Ξ± _ a x n b = horner a' x n b' :=
by simp [hβ.symm, hβ.symm, horner]; cc
meta def eval_neg : horner_expr β ring_m (horner_expr Γ expr)
| (const e) := do
(e', p) β lift $ mk_app ``has_neg.neg [e] >>= norm_num,
return (const e', p)
| (xadd e a x n b) := do
c β get_cache,
(a', hβ) β eval_neg a,
(b', hβ) β eval_neg b,
p β ring_m.mk_app ``horner_neg ``comm_ring [a, x.1, n.1, b, a', b', hβ, hβ],
return (xadd' c a' x n b', p)
theorem horner_const_mul {Ξ±} [comm_semiring Ξ±] (c a x n b a' b')
(hβ : c * a = a') (hβ : c * b = b') :
c * @horner Ξ± _ a x n b = horner a' x n b' :=
by simp [hβ.symm, hβ.symm, horner, mul_add, mul_assoc]
theorem horner_mul_const {Ξ±} [comm_semiring Ξ±] (a x n b c a' b')
(hβ : a * c = a') (hβ : b * c = b') :
@horner Ξ± _ a x n b * c = horner a' x n b' :=
by simp [hβ.symm, hβ.symm, horner, add_mul, mul_right_comm]
meta def eval_const_mul (k : expr) :
horner_expr β ring_m (horner_expr Γ expr)
| (const e) := do
(e', p) β lift $ mk_app ``has_mul.mul [k, e] >>= norm_num,
return (const e', p)
| (xadd e a x n b) := do
c β get_cache,
(a', hβ) β eval_const_mul a,
(b', hβ) β eval_const_mul b,
return (xadd' c a' x n b',
c.cs_app ``horner_const_mul [k, a, x.1, n.1, b, a', b', hβ, hβ])
theorem horner_mul_horner_zero {Ξ±} [comm_semiring Ξ±] (aβ x nβ bβ aβ nβ aa t)
(hβ : @horner Ξ± _ aβ x nβ bβ * aβ = aa)
(hβ : horner aa x nβ 0 = t) :
horner aβ x nβ bβ * horner aβ x nβ 0 = t :=
by rw [β hβ, β hβ];
simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc]
theorem horner_mul_horner {Ξ±} [comm_semiring Ξ±]
(aβ x nβ bβ aβ nβ bβ aa haa ab bb t)
(hβ : @horner Ξ± _ aβ x nβ bβ * aβ = aa)
(hβ : horner aa x nβ 0 = haa)
(hβ : aβ * bβ = ab) (hβ : bβ * bβ = bb)
(H : haa + horner ab x nβ bb = t) :
horner aβ x nβ bβ * horner aβ x nβ bβ = t :=
by rw [β H, β hβ, β hβ, β hβ, β hβ];
simp [horner, mul_add, mul_comm, mul_left_comm, mul_assoc]
meta def eval_mul : horner_expr β horner_expr β ring_m (horner_expr Γ expr)
| (const eβ) (const eβ) := do
(e', p) β lift $ mk_app ``has_mul.mul [eβ, eβ] >>= norm_num,
return (const e', p)
| (const eβ) eβ :=
match eβ.to_nat with
| (some 0) := do
c β get_cache,
Ξ±0 β lift $ expr.of_nat c.Ξ± 0,
p β lift $ mk_app ``zero_mul [eβ],
return (const Ξ±0, p)
| (some 1) := do
p β lift $ mk_app ``one_mul [eβ],
return (eβ, p)
| _ := eval_const_mul eβ eβ
end
| eβ heβ@(const eβ) := do
pβ β lift $ mk_app ``mul_comm [eβ, eβ],
(e', pβ) β eval_mul heβ eβ,
p β lift $ mk_eq_trans pβ pβ, return (e', p)
| heβ@(xadd eβ aβ xβ nβ bβ) heβ@(xadd eβ aβ xβ nβ bβ) := do
c β get_cache,
if xβ.2 < xβ.2 then do
(a', hβ) β eval_mul aβ heβ,
(b', hβ) β eval_mul bβ heβ,
return (xadd' c a' xβ nβ b',
c.cs_app ``horner_mul_const [aβ, xβ.1, nβ.1, bβ, eβ, a', b', hβ, hβ])
else if xβ.2 β xβ.2 then do
(a', hβ) β eval_mul heβ aβ,
(b', hβ) β eval_mul heβ bβ,
return (xadd' c a' xβ nβ b',
c.cs_app ``horner_const_mul [eβ, aβ, xβ.1, nβ.1, bβ, a', b', hβ, hβ])
else do
(aa, hβ) β eval_mul heβ aβ,
Ξ±0 β lift $ expr.of_nat c.Ξ± 0,
(haa, hβ) β eval_horner aa xβ nβ (const Ξ±0),
if bβ.e.to_nat = some 0 then
return (haa, c.cs_app ``horner_mul_horner_zero
[aβ, xβ.1, nβ.1, bβ, aβ, nβ.1, aa, haa, hβ, hβ])
else do
(ab, hβ) β eval_mul aβ bβ,
(bb, hβ) β eval_mul bβ bβ,
(t, H) β eval_add haa (xadd' c ab xβ nβ bb),
return (t, c.cs_app ``horner_mul_horner
[aβ, xβ.1, nβ.1, bβ, aβ, nβ.1, bβ, aa, haa, ab, bb, t, hβ, hβ, hβ, hβ, H])
theorem horner_pow {Ξ±} [comm_semiring Ξ±] (a x n m n' a')
(hβ : n * m = n') (hβ : a ^ m = a') :
@horner Ξ± _ a x n 0 ^ m = horner a' x n' 0 :=
by simp [hβ.symm, hβ.symm, horner, mul_pow, pow_mul]
meta def eval_pow : horner_expr β expr Γ β β ring_m (horner_expr Γ expr)
| e (_, 0) := do
c β get_cache,
Ξ±1 β lift $ expr.of_nat c.Ξ± 1,
p β lift $ mk_app ``pow_zero [e],
return (const Ξ±1, p)
| e (_, 1) := do
p β lift $ mk_app ``pow_one [e],
return (e, p)
| (const e) (eβ, m) := do
(e', p) β lift $ mk_app ``monoid.pow [e, eβ] >>= norm_num.derive',
return (const e', p)
| he@(xadd e a x n b) m := do
c β get_cache,
let N : expr := expr.const `nat [],
match b.e.to_nat with
| some 0 := do
(n', hβ) β lift $ mk_app ``has_mul.mul [n.1, m.1] >>= norm_num.derive',
(a', hβ) β eval_pow a m,
Ξ±0 β lift $ expr.of_nat c.Ξ± 0,
return (xadd' c a' x (n', n.2 * m.2) (const Ξ±0),
c.cs_app ``horner_pow [a, x.1, n.1, m.1, n', a', hβ, hβ])
| _ := do
eβ β lift $ expr.of_nat N (m.2-1),
l β lift $ mk_app ``monoid.pow [e, eβ],
(tl, hl) β eval_pow he (eβ, m.2-1),
(t, pβ) β eval_mul tl he,
hr β lift $ mk_eq_refl e,
pβ β ring_m.mk_app ``norm_num.subst_into_prod ``has_mul [l, e, tl, e, t, hl, hr, pβ],
pβ β lift $ mk_app ``pow_succ' [e, eβ],
p β lift $ mk_eq_trans pβ pβ,
return (t, p)
end
theorem horner_atom {Ξ±} [comm_semiring Ξ±] (x : Ξ±) : x = horner 1 x 1 0 :=
by simp [horner]
meta def eval_atom (e : expr) : ring_m (horner_expr Γ expr) :=
do c β get_cache,
i β add_atom e,
Ξ±0 β lift $ expr.of_nat c.Ξ± 0,
Ξ±1 β lift $ expr.of_nat c.Ξ± 1,
n1 β lift $ expr.of_nat (expr.const `nat []) 1,
return (xadd' c (const Ξ±1) (e, i) (n1, 1) (const Ξ±0),
c.cs_app ``horner_atom [e])
lemma subst_into_pow {Ξ±} [monoid Ξ±] (l r tl tr t)
(prl : (l : Ξ±) = tl) (prr : (r : β) = tr) (prt : tl ^ tr = t) : l ^ r = t :=
by simp [prl, prr, prt]
lemma unfold_sub {Ξ±} [add_group Ξ±] (a b c : Ξ±)
(h : a + -b = c) : a - b = c := h
lemma unfold_div {Ξ±} [division_ring Ξ±] (a b c : Ξ±)
(h : a * bβ»ΒΉ = c) : a / b = c := h
meta def eval : expr β ring_m (horner_expr Γ expr)
| `(%%eβ + %%eβ) := do
(eβ', pβ) β eval eβ,
(eβ', pβ) β eval eβ,
(e', p') β eval_add eβ' eβ',
p β ring_m.mk_app ``norm_num.subst_into_sum ``has_add [eβ, eβ, eβ', eβ', e', pβ, pβ, p'],
return (e', p)
| e@`(@has_sub.sub %%Ξ± %%P %%eβ %%eβ) :=
mcond (succeeds (lift $ mk_app ``comm_ring [Ξ±] >>= mk_instance))
(do
eβ' β lift $ mk_app ``has_neg.neg [eβ],
e β lift $ mk_app ``has_add.add [eβ, eβ'],
(e', p) β eval e,
p' β ring_m.mk_app ``unfold_sub ``add_group [eβ, eβ, e', p],
return (e', p'))
(eval_atom e)
| `(- %%e) := do
(eβ, pβ) β eval e,
(eβ, pβ) β eval_neg eβ,
p β ring_m.mk_app ``norm_num.subst_into_neg ``has_neg [e, eβ, eβ, pβ, pβ],
return (eβ, p)
| `(%%eβ * %%eβ) := do
(eβ', pβ) β eval eβ,
(eβ', pβ) β eval eβ,
(e', p') β eval_mul eβ' eβ',
p β ring_m.mk_app ``norm_num.subst_into_prod ``has_mul [eβ, eβ, eβ', eβ', e', pβ, pβ, p'],
return (e', p)
| e@`(has_inv.inv %%_) := (do
(e', p) β lift $ norm_num.derive e <|> refl_conv e,
lift $ e'.to_rat,
return (const e', p)) <|> eval_atom e
| e@`(@has_div.div _ %%inst %%eβ %%eβ) := mcond
(succeeds (do
inst' β ring_m.mk_app ``division_ring_has_div ``division_ring [],
lift $ is_def_eq inst inst'))
(do
eβ' β lift $ mk_app ``has_inv.inv [eβ],
e β lift $ mk_app ``has_mul.mul [eβ, eβ'],
(e', p) β eval e,
p' β ring_m.mk_app ``unfold_div ``division_ring [eβ, eβ, e', p],
return (e', p'))
(eval_atom e)
| e@`(@has_pow.pow _ _ %%P %%eβ %%eβ) := do
(eβ', pβ) β lift $ norm_num.derive eβ <|> refl_conv eβ,
match eβ'.to_nat, P with
| some k, `(monoid.has_pow) := do
(eβ', pβ) β eval eβ,
(e', p') β eval_pow eβ' (eβ, k),
p β ring_m.mk_app ``subst_into_pow ``monoid [eβ, eβ, eβ', eβ', e', pβ, pβ, p'],
return (e', p)
| some k, `(nat.has_pow) := do
(eβ', pβ) β eval eβ,
(e', p') β eval_pow eβ' (eβ, k),
pβ β ring_m.mk_app ``subst_into_pow ``monoid [eβ, eβ, eβ', eβ', e', pβ, pβ, p'],
pβ β lift $ mk_app ``nat.pow_eq_pow [eβ, eβ] >>= mk_eq_symm,
p β lift $ mk_eq_trans pβ pβ,
return (e', p)
| _, _ := eval_atom e
end
| e := match e.to_nat with
| some n := (const e).refl_conv
| none := eval_atom e
end
meta def eval' (red : transparency) (e : expr) : tactic (expr Γ expr) :=
ring_m.run red e $ do (e', p) β eval e, return (e', p)
theorem horner_def' {Ξ±} [comm_semiring Ξ±] (a x n b) : @horner Ξ± _ a x n b = x ^ n * a + b :=
by simp [horner, mul_comm]
theorem mul_assoc_rev {Ξ±} [semigroup Ξ±] (a b c : Ξ±) : a * (b * c) = a * b * c :=
by simp [mul_assoc]
theorem pow_add_rev {Ξ±} [monoid Ξ±] (a : Ξ±) (m n : β) : a ^ m * a ^ n = a ^ (m + n) :=
by simp [pow_add]
theorem pow_add_rev_right {Ξ±} [monoid Ξ±] (a b : Ξ±) (m n : β) : b * a ^ m * a ^ n = b * a ^ (m + n) :=
by simp [pow_add, mul_assoc]
theorem add_neg_eq_sub {Ξ±} [add_group Ξ±] (a b : Ξ±) : a + -b = a - b := rfl
@[derive has_reflect]
inductive normalize_mode | raw | SOP | horner
instance : inhabited normalize_mode := β¨normalize_mode.hornerβ©
meta def normalize (red : transparency) (mode := normalize_mode.horner) (e : expr) : tactic (expr Γ expr) := do
pow_lemma β simp_lemmas.mk.add_simp ``pow_one,
let lemmas := match mode with
| normalize_mode.SOP :=
[``horner_def', ``add_zero, ``mul_one, ``mul_add, ``mul_sub,
``mul_assoc_rev, ``pow_add_rev, ``pow_add_rev_right,
``mul_neg_eq_neg_mul_symm, ``add_neg_eq_sub]
| normalize_mode.horner :=
[``horner.equations._eqn_1, ``add_zero, ``one_mul, ``pow_one,
``neg_mul_eq_neg_mul_symm, ``add_neg_eq_sub]
| _ := []
end,
lemmas β lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk,
(_, e', pr) β ext_simplify_core () {}
simp_lemmas.mk (Ξ» _, failed) (Ξ» _ _ _ _ e, do
(new_e, pr) β match mode with
| normalize_mode.raw := eval' red
| normalize_mode.horner := trans_conv (eval' red) (simplify lemmas [])
| normalize_mode.SOP :=
trans_conv (eval' red) $
trans_conv (simplify lemmas []) $
simp_bottom_up' (Ξ» e, norm_num e <|> pow_lemma.rewrite e)
end e,
guard (Β¬ new_e =β e),
return ((), new_e, some pr, ff))
(Ξ» _ _ _ _ _, failed) `eq e,
return (e', pr)
end ring
namespace interactive
open interactive interactive.types lean.parser
open tactic.ring
local postfix `?`:9001 := optional
/-- Tactic for solving equations in the language of *commutative* (semi)rings.
This version of `ring` fails if the target is not an equality
that is provable by the axioms of commutative (semi)rings. -/
meta def ring1 (red : parse (tk "!")?) : tactic unit :=
let transp := if red.is_some then semireducible else reducible in
do `(%%eβ = %%eβ) β target,
((eβ', pβ), (eβ', pβ)) β ring_m.run transp eβ $
prod.mk <$> eval eβ <*> eval eβ,
is_def_eq eβ' eβ',
p β mk_eq_symm pβ >>= mk_eq_trans pβ,
tactic.exact p
meta def ring.mode : lean.parser ring.normalize_mode :=
with_desc "(SOP|raw|horner)?" $
do mode β ident?, match mode with
| none := return ring.normalize_mode.horner
| some `horner := return ring.normalize_mode.horner
| some `SOP := return ring.normalize_mode.SOP
| some `raw := return ring.normalize_mode.raw
| _ := failed
end
/-- Tactic for solving equations in the language of *commutative* (semi)rings.
Attempts to prove the goal outright if there is no `at`
specifier and the target is an equality, but if this
fails it falls back to rewriting all ring expressions
into a normal form. When writing a normal form,
`ring SOP` will use sum-of-products form instead of horner form.
`ring!` will use a more aggressive reducibility setting to identify atoms.
Based on [Proving Equalities in a Commutative Ring Done Right
in Coq](http://www.cs.ru.nl/~freek/courses/tt-2014/read/10.1.1.61.3041.pdf) by Benjamin GrΓ©goire
and Assia Mahboubi.
-/
meta def ring (red : parse (tk "!")?) (SOP : parse ring.mode) (loc : parse location) : tactic unit :=
match loc with
| interactive.loc.ns [none] := instantiate_mvars_in_target >> ring1 red
| _ := failed
end <|>
do ns β loc.get_locals,
let transp := if red.is_some then semireducible else reducible,
tt β tactic.replace_at (normalize transp SOP) ns loc.include_goal
| fail "ring failed to simplify",
when loc.include_goal $ try tactic.reflexivity
add_hint_tactic "ring"
add_tactic_doc
{ name := "ring",
category := doc_category.tactic,
decl_names := [`tactic.interactive.ring],
tags := ["arithmetic", "simplification", "decision procedure"] }
end interactive
end tactic
namespace conv.interactive
open conv interactive
open tactic tactic.interactive (ring.mode ring1)
open tactic.ring (normalize)
local postfix `?`:9001 := optional
meta def ring (red : parse (lean.parser.tk "!")?) (SOP : parse ring.mode) : conv unit :=
let transp := if red.is_some then semireducible else reducible in
discharge_eq_lhs (ring1 red)
<|> replace_lhs (normalize transp SOP)
<|> fail "ring failed to simplify"
end conv.interactive
|
4b0afabfd4fc6007808d3ea022cfb45ef4097b79 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/measure_theory/function/conditional_expectation/real.lean | ffdda9fc88a671d74d3a548fa1d4759b492da054 | [
"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 | 19,807 | lean | /-
Copyright (c) 2022 RΓ©my Degenne. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: RΓ©my Degenne, Kexing Ying
-/
import measure_theory.function.conditional_expectation.indicator
import measure_theory.function.uniform_integrable
import measure_theory.decomposition.radon_nikodym
/-!
# Conditional expectation of real-valued functions
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file proves some results regarding the conditional expectation of real-valued functions.
## Main results
* `measure_theory.rn_deriv_ae_eq_condexp`: the conditional expectation `ΞΌ[f | m]` is equal to the
Radon-Nikodym derivative of `fΞΌ` restricted on `m` with respect to `ΞΌ` restricted on `m`.
* `measure_theory.integrable.uniform_integrable_condexp`: the conditional expectation of a function
form a uniformly integrable class.
* `measure_theory.condexp_strongly_measurable_mul`: the pull-out property of the conditional
expectation.
-/
noncomputable theory
open topological_space measure_theory.Lp filter continuous_linear_map
open_locale nnreal ennreal topology big_operators measure_theory
namespace measure_theory
variables {Ξ± : Type*} {m m0 : measurable_space Ξ±} {ΞΌ : measure Ξ±}
lemma rn_deriv_ae_eq_condexp {hm : m β€ m0} [hΞΌm : sigma_finite (ΞΌ.trim hm)] {f : Ξ± β β}
(hf : integrable f ΞΌ) :
signed_measure.rn_deriv ((ΞΌ.with_densityα΅₯ f).trim hm) (ΞΌ.trim hm) =α΅[ΞΌ] ΞΌ[f | m] :=
begin
refine ae_eq_condexp_of_forall_set_integral_eq hm hf _ _ _,
{ exact Ξ» _ _ _, (integrable_of_integrable_trim hm (signed_measure.integrable_rn_deriv
((ΞΌ.with_densityα΅₯ f).trim hm) (ΞΌ.trim hm))).integrable_on },
{ intros s hs hlt,
conv_rhs { rw [β hf.with_densityα΅₯_trim_eq_integral hm hs,
β signed_measure.with_densityα΅₯_rn_deriv_eq ((ΞΌ.with_densityα΅₯ f).trim hm) (ΞΌ.trim hm)
(hf.with_densityα΅₯_trim_absolutely_continuous hm)], },
rw [with_densityα΅₯_apply
(signed_measure.integrable_rn_deriv ((ΞΌ.with_densityα΅₯ f).trim hm) (ΞΌ.trim hm)) hs,
β set_integral_trim hm _ hs],
exact (signed_measure.measurable_rn_deriv _ _).strongly_measurable },
{ exact strongly_measurable.ae_strongly_measurable'
(signed_measure.measurable_rn_deriv _ _).strongly_measurable },
end
-- TODO: the following couple of lemmas should be generalized and proved using Jensen's inequality
-- for the conditional expectation (not in mathlib yet) .
lemma snorm_one_condexp_le_snorm (f : Ξ± β β) :
snorm (ΞΌ[f | m]) 1 ΞΌ β€ snorm f 1 ΞΌ :=
begin
by_cases hf : integrable f ΞΌ,
swap, { rw [condexp_undef hf, snorm_zero], exact zero_le _ },
by_cases hm : m β€ m0,
swap, { rw [condexp_of_not_le hm, snorm_zero], exact zero_le _ },
by_cases hsig : sigma_finite (ΞΌ.trim hm),
swap, { rw [condexp_of_not_sigma_finite hm hsig, snorm_zero], exact zero_le _ },
calc snorm (ΞΌ[f | m]) 1 ΞΌ β€ snorm (ΞΌ[|f| | m]) 1 ΞΌ :
begin
refine snorm_mono_ae _,
filter_upwards [@condexp_mono _ m m0 _ _ _ _ _ _ _ _ hf hf.abs
(@ae_of_all _ m0 _ ΞΌ (Ξ» x, le_abs_self (f x) : β x, f x β€ |f x|)),
eventually_le.trans (condexp_neg f).symm.le
(@condexp_mono _ m m0 _ _ _ _ _ _ _ _ hf.neg hf.abs
(@ae_of_all _ m0 _ ΞΌ (Ξ» x, neg_le_abs_self (f x) : β x, -f x β€ |f x|)))] with x hxβ hxβ,
exact abs_le_abs hxβ hxβ,
end
... = snorm f 1 ΞΌ :
begin
rw [snorm_one_eq_lintegral_nnnorm, snorm_one_eq_lintegral_nnnorm,
β ennreal.to_real_eq_to_real (ne_of_lt integrable_condexp.2) (ne_of_lt hf.2),
β integral_norm_eq_lintegral_nnnorm
(strongly_measurable_condexp.mono hm).ae_strongly_measurable,
β integral_norm_eq_lintegral_nnnorm hf.1],
simp_rw [real.norm_eq_abs],
rw β @integral_condexp _ _ _ _ _ m m0 ΞΌ _ hm hsig hf.abs,
refine integral_congr_ae _,
have : 0 β€α΅[ΞΌ] ΞΌ[|f| | m],
{ rw β @condexp_zero Ξ± β _ _ _ m m0 ΞΌ,
exact condexp_mono (integrable_zero _ _ _) hf.abs
(@ae_of_all _ m0 _ ΞΌ (Ξ» x, abs_nonneg (f x) : β x, 0 β€ |f x|)) },
filter_upwards [this] with x hx,
exact abs_eq_self.2 hx
end
end
lemma integral_abs_condexp_le (f : Ξ± β β) :
β« x, |ΞΌ[f | m] x| βΞΌ β€ β« x, |f x| βΞΌ :=
begin
by_cases hm : m β€ m0,
swap,
{ simp_rw [condexp_of_not_le hm, pi.zero_apply, abs_zero, integral_zero],
exact integral_nonneg (Ξ» x, abs_nonneg _) },
by_cases hfint : integrable f ΞΌ,
swap,
{ simp only [condexp_undef hfint, pi.zero_apply, abs_zero, integral_const,
algebra.id.smul_eq_mul, mul_zero],
exact integral_nonneg (Ξ» x, abs_nonneg _) },
rw [integral_eq_lintegral_of_nonneg_ae, integral_eq_lintegral_of_nonneg_ae],
{ rw ennreal.to_real_le_to_real;
simp_rw [β real.norm_eq_abs, of_real_norm_eq_coe_nnnorm],
{ rw [β snorm_one_eq_lintegral_nnnorm, β snorm_one_eq_lintegral_nnnorm],
exact snorm_one_condexp_le_snorm _ },
{ exact ne_of_lt integrable_condexp.2 },
{ exact ne_of_lt hfint.2 } },
{ exact eventually_of_forall (Ξ» x, abs_nonneg _) },
{ simp_rw β real.norm_eq_abs,
exact hfint.1.norm },
{ exact eventually_of_forall (Ξ» x, abs_nonneg _) },
{ simp_rw β real.norm_eq_abs,
exact (strongly_measurable_condexp.mono hm).ae_strongly_measurable.norm }
end
lemma set_integral_abs_condexp_le {s : set Ξ±} (hs : measurable_set[m] s) (f : Ξ± β β) :
β« x in s, |ΞΌ[f | m] x| βΞΌ β€ β« x in s, |f x| βΞΌ :=
begin
by_cases hnm : m β€ m0,
swap,
{ simp_rw [condexp_of_not_le hnm, pi.zero_apply, abs_zero, integral_zero],
exact integral_nonneg (Ξ» x, abs_nonneg _) },
by_cases hfint : integrable f ΞΌ,
swap,
{ simp only [condexp_undef hfint, pi.zero_apply, abs_zero, integral_const,
algebra.id.smul_eq_mul, mul_zero],
exact integral_nonneg (Ξ» x, abs_nonneg _) },
have : β« x in s, |ΞΌ[f | m] x| βΞΌ = β« x, |ΞΌ[s.indicator f | m] x| βΞΌ,
{ rw β integral_indicator,
swap, { exact hnm _ hs },
refine integral_congr_ae _,
have : (Ξ» x, |ΞΌ[s.indicator f | m] x|) =α΅[ΞΌ] Ξ» x, |s.indicator (ΞΌ[f | m]) x| :=
eventually_eq.fun_comp (condexp_indicator hfint hs) _,
refine eventually_eq.trans (eventually_of_forall $ Ξ» x, _) this.symm,
rw [β real.norm_eq_abs, norm_indicator_eq_indicator_norm],
refl },
rw [this, β integral_indicator],
swap, { exact hnm _ hs },
refine (integral_abs_condexp_le _).trans (le_of_eq $ integral_congr_ae $
eventually_of_forall $ Ξ» x, _),
rw [β real.norm_eq_abs, norm_indicator_eq_indicator_norm],
refl,
end
/-- If the real valued function `f` is bounded almost everywhere by `R`, then so is its conditional
expectation. -/
lemma ae_bdd_condexp_of_ae_bdd {R : ββ₯0} {f : Ξ± β β}
(hbdd : βα΅ x βΞΌ, |f x| β€ R) :
βα΅ x βΞΌ, |ΞΌ[f | m] x| β€ R :=
begin
by_cases hnm : m β€ m0,
swap,
{ simp_rw [condexp_of_not_le hnm, pi.zero_apply, abs_zero],
refine eventually_of_forall (Ξ» x, R.coe_nonneg) },
by_cases hfint : integrable f ΞΌ,
swap,
{ simp_rw [condexp_undef hfint],
filter_upwards [hbdd] with x hx,
rw [pi.zero_apply, abs_zero],
exact (abs_nonneg _).trans hx },
by_contra h,
change ΞΌ _ β 0 at h,
simp only [β zero_lt_iff, set.compl_def, set.mem_set_of_eq, not_le] at h,
suffices : (ΞΌ {x | βR < |ΞΌ[f | m] x|}).to_real * βR < (ΞΌ {x | βR < |ΞΌ[f | m] x|}).to_real * βR,
{ exact this.ne rfl },
refine lt_of_lt_of_le (set_integral_gt_gt R.coe_nonneg _ _ h.ne.symm) _,
{ simp_rw [β real.norm_eq_abs],
exact (strongly_measurable_condexp.mono hnm).measurable.norm },
{ exact integrable_condexp.abs.integrable_on },
refine (set_integral_abs_condexp_le _ _).trans _,
{ simp_rw [β real.norm_eq_abs],
exact @measurable_set_lt _ _ _ _ _ m _ _ _ _ _ measurable_const
strongly_measurable_condexp.norm.measurable },
simp only [β smul_eq_mul, β set_integral_const, nnreal.val_eq_coe,
is_R_or_C.coe_real_eq_id, id.def],
refine set_integral_mono_ae hfint.abs.integrable_on _ _,
{ refine β¨ae_strongly_measurable_const, lt_of_le_of_lt _
(integrable_condexp.integrable_on : integrable_on (ΞΌ[f | m]) {x | βR < |ΞΌ[f | m] x|} ΞΌ).2β©,
refine set_lintegral_mono (measurable.nnnorm _).coe_nnreal_ennreal
(strongly_measurable_condexp.mono hnm).measurable.nnnorm.coe_nnreal_ennreal (Ξ» x hx, _),
{ exact measurable_const },
{ rw [ennreal.coe_le_coe, real.nnnorm_of_nonneg R.coe_nonneg],
exact subtype.mk_le_mk.2 (le_of_lt hx) } },
{ exact hbdd },
end
/-- Given a integrable function `g`, the conditional expectations of `g` with respect to
a sequence of sub-Ο-algebras is uniformly integrable. -/
lemma integrable.uniform_integrable_condexp {ΞΉ : Type*} [is_finite_measure ΞΌ]
{g : Ξ± β β} (hint : integrable g ΞΌ) {β± : ΞΉ β measurable_space Ξ±} (hβ± : β i, β± i β€ m0) :
uniform_integrable (Ξ» i, ΞΌ[g | β± i]) 1 ΞΌ :=
begin
have hmeas : β n, β C, measurable_set {x | C β€ βΞΌ[g | β± n] xββ} :=
Ξ» n C, measurable_set_le measurable_const
(strongly_measurable_condexp.mono (hβ± n)).measurable.nnnorm,
have hg : mem_βp g 1 ΞΌ := mem_βp_one_iff_integrable.2 hint,
refine uniform_integrable_of le_rfl ennreal.one_ne_top
(Ξ» n, (strongly_measurable_condexp.mono (hβ± n)).ae_strongly_measurable) (Ξ» Ξ΅ hΞ΅, _),
by_cases hne : snorm g 1 ΞΌ = 0,
{ rw snorm_eq_zero_iff hg.1 one_ne_zero at hne,
refine β¨0, Ξ» n, (le_of_eq $ (snorm_eq_zero_iff
((strongly_measurable_condexp.mono (hβ± n)).ae_strongly_measurable.indicator (hmeas n 0))
one_ne_zero).2 _).trans (zero_le _)β©,
filter_upwards [@condexp_congr_ae _ _ _ _ _ (β± n) m0 ΞΌ _ _ hne] with x hx,
simp only [zero_le', set.set_of_true, set.indicator_univ, pi.zero_apply, hx, condexp_zero] },
obtain β¨Ξ΄, hΞ΄, hβ© := hg.snorm_indicator_le ΞΌ le_rfl ennreal.one_ne_top hΞ΅,
set C : ββ₯0 := β¨Ξ΄, hΞ΄.leβ©β»ΒΉ * (snorm g 1 ΞΌ).to_nnreal with hC,
have hCpos : 0 < C :=
mul_pos (inv_pos.2 hΞ΄) (ennreal.to_nnreal_pos hne hg.snorm_lt_top.ne),
have : β n, ΞΌ {x : Ξ± | C β€ βΞΌ[g | β± n] xββ} β€ ennreal.of_real Ξ΄,
{ intro n,
have := mul_meas_ge_le_pow_snorm' ΞΌ one_ne_zero ennreal.one_ne_top
((@strongly_measurable_condexp _ _ _ _ _ (β± n) _ ΞΌ g).mono
(hβ± n)).ae_strongly_measurable C,
rw [ennreal.one_to_real, ennreal.rpow_one, ennreal.rpow_one, mul_comm,
β ennreal.le_div_iff_mul_le (or.inl (ennreal.coe_ne_zero.2 hCpos.ne.symm))
(or.inl ennreal.coe_lt_top.ne)] at this,
simp_rw [ennreal.coe_le_coe] at this,
refine this.trans _,
rw [ennreal.div_le_iff_le_mul (or.inl (ennreal.coe_ne_zero.2 hCpos.ne.symm))
(or.inl ennreal.coe_lt_top.ne), hC, nonneg.inv_mk, ennreal.coe_mul,
ennreal.coe_to_nnreal hg.snorm_lt_top.ne, β mul_assoc, β ennreal.of_real_eq_coe_nnreal,
β ennreal.of_real_mul hΞ΄.le, mul_inv_cancel hΞ΄.ne.symm, ennreal.of_real_one, one_mul],
exact snorm_one_condexp_le_snorm _ },
refine β¨C, Ξ» n, le_trans _ (h {x : Ξ± | C β€ βΞΌ[g | β± n] xββ} (hmeas n C) (this n))β©,
have hmeasβ± : measurable_set[β± n] {x : Ξ± | C β€ βΞΌ[g | β± n] xββ} :=
@measurable_set_le _ _ _ _ _ (β± n) _ _ _ _ _ measurable_const
(@measurable.nnnorm _ _ _ _ _ (β± n) _ strongly_measurable_condexp.measurable),
rw β snorm_congr_ae (condexp_indicator hint hmeasβ±),
exact snorm_one_condexp_le_snorm _,
end
section pull_out
-- TODO: this section could be generalized beyond multiplication, to any bounded bilinear map.
/-- Auxiliary lemma for `condexp_measurable_mul`. -/
lemma condexp_strongly_measurable_simple_func_mul (hm : m β€ m0)
(f : @simple_func Ξ± m β) {g : Ξ± β β} (hg : integrable g ΞΌ) :
ΞΌ[f * g | m] =α΅[ΞΌ] f * ΞΌ[g | m] :=
begin
have : β s c (f : Ξ± β β), set.indicator s (function.const Ξ± c) * f = s.indicator (c β’ f),
{ intros s 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], }, },
refine @simple_func.induction _ _ m _ _ (Ξ» c s hs, _) (Ξ» gβ gβ h_disj h_eqβ h_eqβ, _) f,
{ simp only [simple_func.const_zero, simple_func.coe_piecewise, simple_func.coe_const,
simple_func.coe_zero, set.piecewise_eq_indicator],
rw [this, this],
refine (condexp_indicator (hg.smul c) hs).trans _,
filter_upwards [@condexp_smul Ξ± β β _ _ _ _ _ m m0 ΞΌ c g] with x hx,
classical,
simp_rw [set.indicator_apply, hx], },
{ have h_add := @simple_func.coe_add _ _ m _ gβ gβ,
calc ΞΌ[β(gβ + gβ) * g|m] =α΅[ΞΌ] ΞΌ[(βgβ + βgβ) * g|m] :
by { refine condexp_congr_ae (eventually_eq.mul _ eventually_eq.rfl), rw h_add, }
... =α΅[ΞΌ] ΞΌ[βgβ * g|m] + ΞΌ[βgβ * g|m] :
by { rw add_mul, exact condexp_add (hg.simple_func_mul' hm _) (hg.simple_func_mul' hm _), }
... =α΅[ΞΌ] βgβ * ΞΌ[g|m] + βgβ * ΞΌ[g|m] : eventually_eq.add h_eqβ h_eqβ
... =α΅[ΞΌ] β(gβ + gβ) * ΞΌ[g|m] : by rw [h_add, add_mul], },
end
lemma condexp_strongly_measurable_mul_of_bound (hm : m β€ m0) [is_finite_measure ΞΌ]
{f g : Ξ± β β} (hf : strongly_measurable[m] f) (hg : integrable g ΞΌ) (c : β)
(hf_bound : βα΅ x βΞΌ, βf xβ β€ c) :
ΞΌ[f * g | m] =α΅[ΞΌ] f * ΞΌ[g | m] :=
begin
let fs := hf.approx_bounded c,
have hfs_tendsto : βα΅ x βΞΌ, tendsto (Ξ» n, fs n x) at_top (π (f x)),
from hf.tendsto_approx_bounded_ae hf_bound,
by_cases hΞΌ : ΞΌ = 0,
{ simp only [hΞΌ, ae_zero], },
haveI : ΞΌ.ae.ne_bot, by simp only [hΞΌ, ae_ne_bot, ne.def, not_false_iff],
have hc : 0 β€ c,
{ have h_exists : β x, βf xβ β€ c := eventually.exists hf_bound,
exact (norm_nonneg _).trans h_exists.some_spec, },
have hfs_bound : β n x, βfs n xβ β€ c := hf.norm_approx_bounded_le hc,
have hn_eq : β n, ΞΌ[fs n * g | m] =α΅[ΞΌ] fs n * ΞΌ[g | m],
from Ξ» n, condexp_strongly_measurable_simple_func_mul hm _ hg,
have : ΞΌ[f * ΞΌ[g|m]|m] = f * ΞΌ[g|m],
{ refine condexp_of_strongly_measurable hm (hf.mul strongly_measurable_condexp) _,
exact integrable_condexp.bdd_mul' ((hf.mono hm).ae_strongly_measurable) hf_bound, },
rw β this,
refine tendsto_condexp_unique (Ξ» n x, fs n x * g x) (Ξ» n x, fs n x * ΞΌ[g|m] x) (f * g)
(f * ΞΌ[g|m]) _ _ _ _ (Ξ» x, c * βg xβ) _ (Ξ» x, c * βΞΌ[g|m] xβ) _ _ _ _,
{ exact Ξ» n, hg.bdd_mul'
((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable
(eventually_of_forall (hfs_bound n)), },
{ exact Ξ» n, integrable_condexp.bdd_mul'
((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable
(eventually_of_forall (hfs_bound n)), },
{ filter_upwards [hfs_tendsto] with x hx,
rw pi.mul_apply,
exact tendsto.mul hx tendsto_const_nhds, },
{ filter_upwards [hfs_tendsto] with x hx,
rw pi.mul_apply,
exact tendsto.mul hx tendsto_const_nhds, },
{ exact hg.norm.const_mul c, },
{ exact integrable_condexp.norm.const_mul c, },
{ refine Ξ» n, eventually_of_forall (Ξ» x, _),
exact (norm_mul_le _ _).trans (mul_le_mul_of_nonneg_right (hfs_bound n x) (norm_nonneg _)), },
{ refine Ξ» n, eventually_of_forall (Ξ» x, _),
exact (norm_mul_le _ _).trans (mul_le_mul_of_nonneg_right (hfs_bound n x) (norm_nonneg _)), },
{ intros n,
simp_rw β pi.mul_apply,
refine (condexp_strongly_measurable_simple_func_mul hm _ hg).trans _,
rw condexp_of_strongly_measurable hm
((simple_func.strongly_measurable _).mul strongly_measurable_condexp) _,
{ apply_instance, },
{ apply_instance, },
exact integrable_condexp.bdd_mul'
((simple_func.strongly_measurable (fs n)).mono hm).ae_strongly_measurable
(eventually_of_forall (hfs_bound n)), },
end
lemma condexp_strongly_measurable_mul_of_boundβ (hm : m β€ m0) [is_finite_measure ΞΌ]
{f g : Ξ± β β} (hf : ae_strongly_measurable' m f ΞΌ) (hg : integrable g ΞΌ) (c : β)
(hf_bound : βα΅ x βΞΌ, βf xβ β€ c) :
ΞΌ[f * g | m] =α΅[ΞΌ] f * ΞΌ[g | m] :=
begin
have : ΞΌ[f * g | m] =α΅[ΞΌ] ΞΌ[hf.mk f * g | m],
from condexp_congr_ae (eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl),
refine this.trans _,
have : f * ΞΌ[g | m] =α΅[ΞΌ] hf.mk f * ΞΌ[g | m] := eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl,
refine eventually_eq.trans _ this.symm,
refine condexp_strongly_measurable_mul_of_bound hm hf.strongly_measurable_mk hg c _,
filter_upwards [hf_bound, hf.ae_eq_mk] with x hxc hx_eq,
rw β hx_eq,
exact hxc,
end
/-- Pull-out property of the conditional expectation. -/
lemma condexp_strongly_measurable_mul {f g : Ξ± β β} (hf : strongly_measurable[m] f)
(hfg : integrable (f * g) ΞΌ) (hg : integrable g ΞΌ) :
ΞΌ[f * g | m] =α΅[ΞΌ] f * ΞΌ[g | m] :=
begin
by_cases hm : m β€ m0, swap, { simp_rw condexp_of_not_le hm, rw mul_zero, },
by_cases hΞΌm : sigma_finite (ΞΌ.trim hm),
swap, { simp_rw condexp_of_not_sigma_finite hm hΞΌm, rw mul_zero, },
haveI : sigma_finite (ΞΌ.trim hm) := hΞΌm,
obtain β¨sets, sets_prop, h_univβ© := hf.exists_spanning_measurable_set_norm_le hm ΞΌ,
simp_rw forall_and_distrib at sets_prop,
obtain β¨h_meas, h_finite, h_normβ© := sets_prop,
suffices : β n, βα΅ x βΞΌ, x β sets n β ΞΌ[f * g|m] x = f x * ΞΌ[g|m] x,
{ rw β ae_all_iff at this,
filter_upwards [this] with x hx,
rw pi.mul_apply,
obtain β¨i, hiβ© : β i, x β sets i,
{ have h_mem : x β β i, sets i,
{ rw h_univ, exact set.mem_univ _, },
simpa using h_mem, },
exact hx i hi, },
refine Ξ» n, ae_imp_of_ae_restrict _,
suffices : (ΞΌ.restrict (sets n))[f * g | m]
=α΅[ΞΌ.restrict (sets n)] f * (ΞΌ.restrict (sets n))[g | m],
{ simp_rw β pi.mul_apply,
refine (condexp_restrict_ae_eq_restrict hm (h_meas n) hfg).symm.trans _,
exact this.trans (eventually_eq.rfl.mul (condexp_restrict_ae_eq_restrict hm (h_meas n) hg)), },
suffices : (ΞΌ.restrict (sets n))[((sets n).indicator f) * g | m]
=α΅[ΞΌ.restrict (sets n)] ((sets n).indicator f) * (ΞΌ.restrict (sets n))[g | m],
{ refine eventually_eq.trans _ (this.trans _),
{ exact condexp_congr_ae
((indicator_ae_eq_restrict (hm _ (h_meas n))).symm.mul eventually_eq.rfl), },
{ exact (indicator_ae_eq_restrict (hm _ (h_meas n))).mul eventually_eq.rfl, }, },
haveI : is_finite_measure (ΞΌ.restrict (sets n)),
{ constructor,
rw measure.restrict_apply_univ,
exact h_finite n, },
refine condexp_strongly_measurable_mul_of_bound hm (hf.indicator (h_meas n)) hg.integrable_on n _,
refine eventually_of_forall (Ξ» x, _),
by_cases hxs : x β sets n,
{ simp only [hxs, set.indicator_of_mem],
exact h_norm n x hxs, },
{ simp only [hxs, set.indicator_of_not_mem, not_false_iff, _root_.norm_zero, nat.cast_nonneg], },
end
/-- Pull-out property of the conditional expectation. -/
lemma condexp_strongly_measurable_mulβ {f g : Ξ± β β} (hf : ae_strongly_measurable' m f ΞΌ)
(hfg : integrable (f * g) ΞΌ) (hg : integrable g ΞΌ) :
ΞΌ[f * g | m] =α΅[ΞΌ] f * ΞΌ[g | m] :=
begin
have : ΞΌ[f * g | m] =α΅[ΞΌ] ΞΌ[hf.mk f * g | m],
from condexp_congr_ae (eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl),
refine this.trans _,
have : f * ΞΌ[g | m] =α΅[ΞΌ] hf.mk f * ΞΌ[g | m] := eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl,
refine eventually_eq.trans _ this.symm,
refine condexp_strongly_measurable_mul hf.strongly_measurable_mk _ hg,
refine (integrable_congr _).mp hfg,
exact eventually_eq.mul hf.ae_eq_mk eventually_eq.rfl,
end
end pull_out
end measure_theory
|
a867007d3d7f0047863418c852e072ba43c889e5 | 263b858cfdc89a2f9d3a4b5f400694bf81ab855d | /mm0-lean/x86/lemmas.lean | 1d2544af83639c857ea92d72b42ae39207814177 | [
"CC0-1.0"
] | permissive | jcommelin/mm0 | 97d89e6935cdf21523a6f29904bd0a2a042335cc | 7482b84b3518cae5c730ba07d91e23ae978dafd9 | refs/heads/master | 1,617,826,105,860 | 1,583,734,867,000 | 1,583,735,028,000 | 248,705,227 | 0 | 0 | CC0-1.0 | 1,584,693,150,000 | 1,584,693,150,000 | null | UTF-8 | Lean | false | false | 62,601 | lean | import x86.x86 data.list.basic data.zmod.basic
theorem bool.coe_bool_iff : β {a b : bool}, (a β b) β a = b := dec_trivial
namespace bitvec
theorem of_nat_zero (n) : bitvec.of_nat n 0 = 0 :=
by induction n; [refl, exact congr_arg (vector.cons ff) n_ih]
theorem of_nat_one (n) : bitvec.of_nat n 1 = 1 :=
by cases n; [refl, exact congr_arg (vector.cons tt) (of_nat_zero _)]
theorem from_bits_fill_eq : β {n b l} (e : list.length l = n),
from_bits_fill b l = β¨l, eβ©
| 0 b [] e := rfl
| (n+1) b (a :: l) e :=
by rw [from_bits_fill, from_bits_fill_eq (nat.succ_inj e)]; refl
theorem bits_to_nat_zero (n) : bits_to_nat (list.repeat ff n) = 0 :=
by simp [bits_to_nat]; induction n; simp *
@[simp] theorem bits_to_nat_cons (a l) :
bits_to_nat (a :: l) = nat.bit a (bits_to_nat l) := rfl
@[simp] theorem to_nat_nil : to_nat vector.nil = 0 := rfl
@[simp] theorem to_nat_zero (n) : to_nat (0 : bitvec n) = 0 :=
bits_to_nat_zero _
@[simp] theorem to_nat_cons (b) {n} (v : bitvec n) :
to_nat (b :: v) = nat.bit b (to_nat v) :=
by cases v; refl
@[simp] theorem of_nat_succ (n i : β) :
bitvec.of_nat n.succ i = i.bodd :: bitvec.of_nat n i.div2 :=
by rw [bitvec.of_nat, nat.bodd_div2_eq, bitvec.of_nat]
@[simp] theorem of_nat_bit (n : β) (b i) :
bitvec.of_nat n.succ (nat.bit b i) = b :: bitvec.of_nat n i :=
by rw [of_nat_succ, nat.div2_bit, nat.bodd_bit]
theorem of_nat_bits_to_nat {n} (l : list bool) :
bitvec.of_nat n (bits_to_nat l) = from_bits_fill ff l :=
begin
rw bits_to_nat,
induction l generalizing n, exact of_nat_zero _,
cases n, refl,
simp [*, bits_to_nat, from_bits_fill,
bitvec.of_nat, nat.bodd_bit, nat.div2_bit]
end
theorem of_nat_bits_to_nat_eq {n} (l : list bool) (e : l.length = n) :
bitvec.of_nat n (bits_to_nat l) = β¨l, eβ© :=
begin
induction n generalizing l; cases l; injection e, refl,
simp [bits_to_nat, nat.div2_bit, nat.bodd_bit],
exact congr_arg (vector.cons l_hd) (n_ih _ h_1)
end
@[simp] theorem of_nat_to_nat : β {n} (v : bitvec n),
bitvec.of_nat n (to_nat v) = v
| n β¨l, eβ© := of_nat_bits_to_nat_eq l e
theorem to_nat_of_nat_aux (m n b) :
nat.bit b (n % 2 ^ m) = nat.bit b n % 2 ^ nat.succ m :=
begin
have := nat.mod_add_div (n.bit b) (2^m * 2),
conv at this { to_rhs, rw [nat.bit_val, β nat.mod_add_div n (2^m),
mul_add, add_right_comm, β nat.bit_val, mul_left_comm,
β mul_assoc] },
rw [nat.pow_succ],
refine add_right_cancel (this.symm.trans _), congr' 2,
rw [mul_comm, β nat.div_div_eq_div_mul, β nat.div2_val, nat.div2_bit]
end
theorem to_nat_of_nat (m n) : to_nat (bitvec.of_nat m n) = n % 2 ^ m :=
begin
induction m generalizing n,
{ simp [bitvec.of_nat, to_nat], refl },
simp [bitvec.of_nat, m_ih],
conv { to_rhs, rw β nat.bit_decomp n },
apply to_nat_of_nat_aux
end
theorem to_nat_lt_pow2 {n} (v : bitvec n) : to_nat v < 2 ^ n :=
begin
rw [β of_nat_to_nat v, to_nat_of_nat],
exact nat.mod_lt _ (nat.pow_pos dec_trivial _),
end
def pow2 (n : β) : β+ := β¨2^n, nat.pow_pos dec_trivial _β©
def to_zmod {n} (v : bitvec n) : zmod (pow2 n) := bitvec.to_nat v
def of_zmod {n} (i : zmod (pow2 n)) : bitvec n := bitvec.of_nat _ i.1
theorem to_zmod_of_zmod {n} (i : zmod (pow2 n)) : to_zmod (of_zmod i) = i :=
((zmod.eq_iff_modeq_nat' _).2
(by convert nat.modeq.mod_modeq _ _; apply to_nat_of_nat)).trans (zmod.cast_val _)
theorem of_zmod_to_zmod {n} (v : bitvec n) : of_zmod (to_zmod v) = v :=
by unfold of_zmod to_zmod; convert of_nat_to_nat v; exact
zmod.val_cast_of_lt (to_nat_lt_pow2 _)
theorem of_nat_eq_iff_modeq {m nβ nβ} :
bitvec.of_nat m nβ = bitvec.of_nat m nβ β nβ β‘ nβ [MOD 2 ^ m] :=
begin
dunfold nat.modeq, split; intro h,
{ rw [β to_nat_of_nat, h, to_nat_of_nat] },
{ rw [β of_nat_to_nat (bitvec.of_nat m nβ),
to_nat_of_nat, h, β to_nat_of_nat, of_nat_to_nat] },
end
theorem of_nat_eq_of_zmod (m n) :
bitvec.of_nat m n = bitvec.of_zmod n :=
eq.symm $ of_nat_eq_iff_modeq.2 $
by convert nat.modeq.mod_modeq _ _; apply zmod.val_cast_nat
theorem to_zmod_zero (n) : to_zmod (0 : bitvec n) = 0 :=
by rw [to_zmod, to_nat_zero]; refl
theorem of_zmod_zero (n) : (of_zmod 0 : bitvec n) = 0 :=
by rw [β to_zmod_zero, of_zmod_to_zmod]
theorem of_zmod_one (n) : (of_zmod 1 : bitvec n) = 1 :=
begin
cases n, {refl},
change bitvec.of_nat _ (1 % 2 ^ _) = _,
rw [nat.mod_eq_of_lt, of_nat_one],
exact @nat.pow_lt_pow_of_lt_right _ dec_trivial 0 _ (nat.succ_pos _)
end
theorem to_zmod_one (n) : to_zmod (1 : bitvec n) = 1 :=
by rw [β of_zmod_one, to_zmod_of_zmod]
theorem to_zmod_add {n} (a b : bitvec n) : to_zmod (a + b) = to_zmod a + to_zmod b :=
show to_zmod (bitvec.of_nat _ _) = _,
by rw [of_nat_eq_of_zmod, to_zmod_of_zmod, to_zmod, to_zmod, nat.cast_add]
theorem to_zmod_mul {n} (a b : bitvec n) : to_zmod (a * b) = to_zmod a * to_zmod b :=
show to_zmod (bitvec.of_nat _ _) = _,
by rw [of_nat_eq_of_zmod, to_zmod_of_zmod, to_zmod, to_zmod, nat.cast_mul]
theorem to_zmod_neg {n} (a : bitvec n) : to_zmod (-a) = -to_zmod a :=
show to_zmod (bitvec.of_nat _ _) = _,
begin
rw [of_nat_eq_of_zmod, to_zmod_of_zmod, eq_neg_iff_add_eq_zero, to_zmod,
β nat.cast_add, nat.sub_add_cancel (le_of_lt (to_nat_lt_pow2 _))],
exact zmod.cast_self_eq_zero,
end
theorem of_zmod_add {n} (a b : zmod (pow2 n)) : of_zmod (a + b) = of_zmod a + of_zmod b :=
by conv_lhs {rw [β to_zmod_of_zmod a, β to_zmod_of_zmod b]};
rw [β to_zmod_add, of_zmod_to_zmod]
theorem of_zmod_mul {n} (a b : zmod (pow2 n)) : of_zmod (a * b) = of_zmod a * of_zmod b :=
by conv_lhs {rw [β to_zmod_of_zmod a, β to_zmod_of_zmod b]};
rw [β to_zmod_mul, of_zmod_to_zmod]
theorem of_zmod_neg {n} (a : zmod (pow2 n)) : of_zmod (-a) = -of_zmod a :=
by conv_lhs {rw [β to_zmod_of_zmod a]}; rw [β to_zmod_neg, of_zmod_to_zmod]
instance (n : β) : add_comm_semigroup (bitvec n) :=
{ add_assoc := Ξ» a b c, by rw [β of_zmod_to_zmod a, β of_zmod_to_zmod b, β of_zmod_to_zmod c,
β of_zmod_add, β of_zmod_add, add_assoc, of_zmod_add, of_zmod_add],
add_comm := Ξ» a b, by rw [β of_zmod_to_zmod a, β of_zmod_to_zmod b,
β of_zmod_add, add_comm, of_zmod_add],
..bitvec.has_add }
instance (n : β) : comm_semigroup (bitvec n) :=
{ mul_assoc := Ξ» a b c, by rw [β of_zmod_to_zmod a, β of_zmod_to_zmod b, β of_zmod_to_zmod c,
β of_zmod_mul, β of_zmod_mul, mul_assoc, of_zmod_mul, of_zmod_mul],
mul_comm := Ξ» a b, by rw [β of_zmod_to_zmod a, β of_zmod_to_zmod b,
β of_zmod_mul, mul_comm, of_zmod_mul],
..bitvec.has_mul }
instance (n : β) : comm_ring (bitvec n) :=
{ zero_add := Ξ» a, by rw [β of_zmod_to_zmod a, β of_zmod_zero, β of_zmod_add, zero_add],
add_zero := Ξ» a, by rw [β of_zmod_to_zmod a, β of_zmod_zero, β of_zmod_add, add_zero],
add_left_neg := Ξ» a, by rw [β of_zmod_to_zmod a,
β of_zmod_neg, β of_zmod_add, add_left_neg, β of_zmod_zero],
one_mul := Ξ» a, by rw [β of_zmod_to_zmod a, β of_zmod_one, β of_zmod_mul, one_mul],
mul_one := Ξ» a, by rw [β of_zmod_to_zmod a, β of_zmod_one, β of_zmod_mul, mul_one],
left_distrib := Ξ» a b c, by rw [β of_zmod_to_zmod a, β of_zmod_to_zmod b, β of_zmod_to_zmod c,
β of_zmod_add, β of_zmod_mul, left_distrib, of_zmod_add, of_zmod_mul, of_zmod_mul]; refl,
right_distrib := Ξ» a b c, by rw [β of_zmod_to_zmod a, β of_zmod_to_zmod b, β of_zmod_to_zmod c,
β of_zmod_add, β of_zmod_mul, right_distrib, of_zmod_add, of_zmod_mul, of_zmod_mul]; refl,
..bitvec.has_zero,
..bitvec.has_one,
..bitvec.has_neg,
..bitvec.add_comm_semigroup n,
..bitvec.comm_semigroup n }
theorem to_nat_nth {n} (i j) :
(bitvec.of_nat n i).nth j = i.test_bit j.1 :=
begin
generalize e : bitvec.of_nat n i = v, cases v with l e',
cases j with j h,
rw [vector.nth], dsimp only,
induction n generalizing i l j, cases h,
cases l; injection e',
simp [bitvec.of_nat] at e,
generalize_hyp eβ : bitvec.of_nat n_n i.div2 = v at e, cases v with l eβ',
injection e, cases h_2,
cases j; simp, refl,
rw [β nat.bit_decomp i, nat.test_bit_succ],
exact n_ih _ _ _ _ eβ (nat.lt_of_succ_lt_succ h)
end
theorem of_nat_from_bits_fill (n m i) (h : n β€ m) :
bitvec.of_nat n i = from_bits_fill ff (bitvec.of_nat m i).1 :=
begin
generalize e : bitvec.of_nat m i = v, cases v with l h, simp,
induction n generalizing m i l e, exact (vector.eq_nil _).trans (vector.eq_nil _).symm,
rw [of_nat_succ],
cases m, cases h,
rw [of_nat_succ] at e,
generalize e' : bitvec.of_nat m i.div2 = v, cases v with l' h',
rw e' at e, injection e, subst l,
rw [n_ih _ _ (nat.le_of_succ_le_succ h) _ _ e', from_bits_fill],
end
theorem of_nat_bit0_aux {n} (j : bitvec (nat.succ n)) :
bit0 j = ff :: from_bits_fill ff (j.val) :=
begin
change bitvec.of_nat n.succ (bit0 (to_nat j)) = _,
rw [of_nat_succ,
nat.bodd_bit0, nat.div2_bit0, to_nat, of_nat_bits_to_nat]
end
theorem of_nat_bit0 (n i) : bitvec.of_nat n (bit0 i) = bit0 (bitvec.of_nat n i) :=
begin
induction n generalizing i, refl,
rw [of_nat_succ,
nat.bodd_bit0, nat.div2_bit0],
rw [of_nat_from_bits_fill _ _ _ (nat.le_succ _)],
generalize : bitvec.of_nat n_n.succ i = j,
rw of_nat_bit0_aux,
end
theorem of_nat_bit1 (n i) : bitvec.of_nat n (bit1 i) = bit1 (bitvec.of_nat n i) :=
begin
induction n generalizing i, refl,
rw [of_nat_succ,
nat.bodd_bit1, nat.div2_bit1],
rw [of_nat_from_bits_fill _ _ _ (nat.le_succ _)],
generalize : bitvec.of_nat n_n.succ i = j,
change _ = bitvec.of_nat _ (to_nat (bit0 j) + bit0 (@to_nat n_n 0) + 1),
rw [to_nat_zero],
change _ = bitvec.of_nat _ (to_nat (bit0 j) + 1),
rw [of_nat_bit0_aux, to_nat_cons],
change _ = bitvec.of_nat _ (nat.bit tt _),
rw [of_nat_bit, of_nat_to_nat],
end
theorem add_nat_assoc {n} (v : bitvec n) (a b : β) :
v + a + b = v + (a + b : β) :=
by rw [nat.cast_add, add_assoc]
theorem of_nat_add {n} (a b : β) : bitvec.of_nat n (a + b) = bitvec.of_nat n a + bitvec.of_nat n b :=
by simp [of_nat_eq_of_zmod, of_zmod_add]
theorem of_nat_succ' {n} (a : β) : bitvec.of_nat n a.succ = bitvec.of_nat n a + 1 :=
(of_nat_add a 1).trans $ by simp [of_nat_one]
theorem of_nat_mul {n} (a b : β) : bitvec.of_nat n (a * b) = bitvec.of_nat n a * bitvec.of_nat n b :=
by simp [of_nat_eq_of_zmod, of_zmod_mul]
theorem coe_eq_of_nat {n} (a : β) :
(a : bitvec n) = bitvec.of_nat n a :=
begin
induction a, exact (bitvec.of_nat_zero _).symm,
rw [of_nat_succ', β a_ih], refl,
end
theorem coe_to_nat {n} (v : bitvec n) : (to_nat v : bitvec n) = v :=
by rw [coe_eq_of_nat, of_nat_to_nat]
theorem bits_to_nat_inj : β {lβ lβ},
bits_to_nat lβ = bits_to_nat lβ β lβ.length = lβ.length β lβ = lβ
| [] [] _ _ := rfl
| (a :: lβ) (b :: lβ) e e' := begin
rw [bits_to_nat_cons, bits_to_nat_cons] at e,
rw [β nat.bodd_bit a (bits_to_nat lβ), e, nat.bodd_bit,
@bits_to_nat_inj lβ lβ _ (nat.succ_inj e')],
rw [β nat.div2_bit a (bits_to_nat lβ), e, nat.div2_bit]
end
theorem to_nat_inj {n vβ vβ}
(h : @bitvec.to_nat n vβ = bitvec.to_nat vβ) : vβ = vβ :=
subtype.eq $ bits_to_nat_inj h (vβ.2.trans vβ.2.symm)
theorem coe_shl {n} (a b) : (nat.shiftl a b : bitvec n) = bitvec.shl a b :=
begin
rw [shl, coe_eq_of_nat, nat.shiftl_eq_mul_pow, nat.shiftl_eq_mul_pow],
refine of_nat_eq_iff_modeq.2 (nat.modeq.modeq_mul_right _ _),
rw [β of_nat_eq_iff_modeq, of_nat_to_nat, coe_eq_of_nat],
end
theorem sign_iff_neg {n v} : @bitvec.sign n v β bitvec.to_int v < 0 :=
begin
unfold bitvec.to_int, cases sign v; simp,
apply sub_lt_zero.2, norm_cast,
exact to_nat_lt_pow2 _
end
theorem to_int_inj {n vβ vβ}
(h : @bitvec.to_int n vβ = bitvec.to_int vβ) : vβ = vβ :=
begin
have : sign vβ = sign vβ,
{ apply bool.coe_bool_iff.1,
rw [sign_iff_neg, sign_iff_neg, h] },
revert h,
unfold bitvec.to_int,
rw this, cases sign vβ; simp; exact to_nat_inj
end
theorem pow2_eq_zero {n} : (2 ^ n : bitvec n) = 0 :=
begin
suffices : ((2 ^ n : β) : bitvec n) = 0, {exact_mod_cast this},
have := to_nat_of_nat n (2^n),
apply to_nat_inj,
rw [coe_eq_of_nat, to_nat_of_nat, nat.mod_self, to_nat_zero],
end
theorem coe_to_int {n} (v : bitvec n) : (to_int v : bitvec n) = v :=
by unfold to_int; cases sign v; simp [coe_to_nat, pow2_eq_zero]
@[class] def reify {n} (v : bitvec n) (l : out_param (list bool)) : Prop :=
from_bits_fill ff l = v
theorem reify.mk {n} (v) {l} [h : @reify n v l] :
from_bits_fill ff l = v := h
theorem reify_eq {n v l l'} [@reify n v l] (h : l' = v.1) :
l' = (@from_bits_fill ff l n).1 := by rwa reify.mk v
theorem reify_eq' {n v l l'} [@reify n v l] (h : l' = v) :
l' = @from_bits_fill ff l n := by rwa reify.mk v
theorem reify_eqβ {n vβ lβ vβ lβ}
[@reify n vβ lβ] [@reify n vβ lβ] (h : vβ = vβ) :
@from_bits_fill ff lβ n = from_bits_fill ff lβ :=
by rwa [reify.mk vβ, reify.mk vβ]
theorem reify_iff {n v l} : @reify n v l β bitvec.of_nat n (bits_to_nat l) = v :=
iff_of_eq $ congr_arg (= v) (of_nat_bits_to_nat _).symm
instance reify_0 {n} : @reify n 0 [] := rfl
instance reify_1 {n} : @reify n 1 [tt] :=
by cases n; exact rfl
instance reify_bit0 {n} (v l) [h : @reify n v l] :
reify (bit0 v) (ff :: l) :=
reify_iff.2 $
by have := of_nat_bit0 n (bits_to_nat l);
rwa [reify_iff.1 h] at this
instance reify_bit1 {n} (v l) [h : @reify n v l] :
reify (bit1 v) (tt :: l) :=
reify_iff.2 $
by have := of_nat_bit1 n (bits_to_nat l);
rwa [reify_iff.1 h] at this
end bitvec
namespace x86
def split_bits_spec : list (Ξ£ n, bitvec n) β list bool β Prop
| [] l := list.all l bnot
| (β¨n, vβ© :: s) l := let β¨lβ, lββ© := l.split_at n in
(@bitvec.from_bits_fill ff lβ n).1 = v.1 β§ split_bits_spec s lβ
theorem split_bits_ok {l s} : split_bits (bitvec.bits_to_nat l) s β split_bits_spec s l :=
begin
generalize eβ : bitvec.bits_to_nat l = n,
induction s generalizing l n, rintro β¨β©,
{ induction l, constructor,
cases l_hd,
{ exact bool.band_intro rfl (l_ih (not_imp_not.1 (nat.bit_ne_zero _) eβ)) },
{ cases nat.bit1_ne_zero _ eβ } },
{ rcases s_hd with β¨i, l', eββ©,
unfold split_bits_spec,
generalize eβ : l.split_at i = p, cases p with lβ lβ,
dsimp [split_bits_spec],
induction i with i generalizing l' lβ lβ eβ l n; cases l'; injection eβ,
{ cases h_2, cases eβ, exact β¨rfl, s_ih _ eβ h_2_aβ© },
{ generalize_hyp eβ : (β¨l'_hd :: l'_tl, eββ© : bitvec _) = f at h_2,
cases h_2, cases h_2_bs with _ pr, injection eβ, cases h_3,
generalize eβ
: l.tail.split_at i = p, cases p with lβ' lβ',
have : bitvec.bits_to_nat l.tail = nat.div2 n,
{ subst eβ, cases l, refl, exact (nat.div2_bit _ _).symm },
rcases i_ih _ _ _ h_1 _ this eβ
h_2_a with β¨eβ, h'β©,
replace eβ : bitvec.from_bits_fill ff lβ' = β¨l'_tl, prβ© := subtype.eq eβ,
cases l,
{ cases eβ,
have : (lβ', lβ') = ([], []), {cases i; cases eβ
; refl}, cases this,
simp [bitvec.from_bits_fill, h', vector.repeat] at eβ β’,
cases eβ, exact β¨rfl, eββ© },
{ rw [list.split_at, show l_tl.split_at i = (lβ', lβ'), from eβ
] at eβ,
cases eβ, rw [bitvec.from_bits_fill, β eβ, eβ],
refine β¨_, h'β©, simp [vector.cons], exact (nat.bodd_bit _ _).symm } } }
end
theorem split_bits.determ_l {nβ nβ l} (hβ : split_bits nβ l) (hβ : split_bits nβ l) : nβ = nβ :=
begin
induction l generalizing nβ nβ, {cases hβ, cases hβ, refl},
rcases l_hd with β¨_, l', rflβ©,
induction l' generalizing nβ nβ,
{ cases hβ, cases hβ, exact l_ih hβ_a hβ_a },
{ have : β {n l'},
split_bits n l' β
l' = β¨_, l'_hd :: l'_tl, rflβ© :: l_tl β
l'_hd = nat.bodd n β§
split_bits (nat.div2 n) (β¨_, l'_tl, rflβ© :: l_tl),
{ intros, cases a; try {cases a_1},
rcases a_bs with β¨lβ, rflβ©,
injection a_1, cases h_2,
cases congr_arg (Ξ» v : Ξ£ n, bitvec n, v.2.1) h_1,
exact β¨rfl, a_aβ© },
rcases this hβ rfl with β¨rfl, hβ'β©,
rcases this hβ rfl with β¨e, hβ'β©,
rw [β nat.bit_decomp nβ, e, l'_ih hβ' hβ', nat.bit_decomp] }
end
theorem split_bits.determ {n lβ lβ} (hβ : split_bits n lβ) (hβ : split_bits n lβ)
(h : lβ.map sigma.fst = lβ.map sigma.fst) : lβ = lβ :=
begin
induction lβ generalizing n lβ; cases lβ; injection h, refl,
cases lβ_hd with i vβ, cases lβ_hd with _ vβ, cases h_1,
clear h h_1, induction i with i generalizing vβ vβ n,
{ cases hβ, cases hβ, rw lβ_ih hβ_a hβ_a h_2 },
{ cases hβ, cases hβ, cases i_ih _ _ hβ_a hβ_a, refl }
end
theorem bits_to_byte.determ_l {n m w1 w2 l} :
@bits_to_byte n m w1 l β @bits_to_byte n m w2 l β w1 = w2
| β¨eβ, hββ© β¨_, hββ© := bitvec.to_nat_inj $ split_bits.determ_l hβ hβ
theorem bits_to_byte.determ_l_aux {n m w1 w2 l l'} :
@bits_to_byte n m w1 l β @bits_to_byte n m w2 (l ++ l') β (w1, l') = (w2, [])
| β¨eβ, hββ© β¨eβ, hββ© := begin
simp, suffices, refine β¨_, thisβ©, swap,
{ apply list.length_eq_zero.1,
apply @eq_of_add_eq_add_left _ _ l.length,
rw [add_zero, β list.length_append, eβ, eβ] },
clear bits_to_byte.determ_l_aux, subst this,
rw list.append_nil at hβ,
exact bitvec.to_nat_inj (split_bits.determ_l hβ hβ)
end
theorem bits_to_byte.determ {n m w l1 l2} :
@bits_to_byte n m w l1 β @bits_to_byte n m w l2 β l1 = l2
| β¨eβ, hββ© β¨eβ, hββ© := list.injective_map_iff.2
(by rintro x y β¨β©; refl)
(split_bits.determ hβ hβ
(by rw [list.map_map, list.map_map, (_ : _β_ = _),
list.map_const _ 8, eβ, list.map_const, eβ]; refl))
theorem read_prefixes.determ {rβ rβ l} : read_prefixes rβ l β read_prefixes rβ l β rβ = rβ :=
begin
intros hβ hβ, cases hβ; cases hβ; congr,
cases split_bits.determ hβ_a hβ_a rfl, refl,
end
@[elab_as_eliminator] theorem byte_split {C : byte β Sort*}
: β b : byte, (β b0 b1 b2 b3 b4 b5 b6 b7,
C β¨[b0, b1, b2, b3, b4, b5, b6, b7], rflβ©) β C b
| β¨[b0, b1, b2, b3, b4, b5, b6, b7], rflβ© H := H _ _ _ _ _ _ _ _
def binop.from_bits : β (b0 b1 b2 b3 : bool), binop
| ff ff ff ff := binop.add
| tt ff ff ff := binop.or
| ff tt ff ff := binop.adc
| tt tt ff ff := binop.sbb
| ff ff tt ff := binop.and
| tt ff tt ff := binop.sub
| ff tt tt ff := binop.xor
| tt tt tt ff := binop.cmp
| ff ff ff tt := binop.rol
| tt ff ff tt := binop.ror
| ff tt ff tt := binop.rcl
| tt tt ff tt := binop.rcr
| ff ff tt tt := binop.shl
| tt ff tt tt := binop.shr
| ff tt tt tt := binop.tst
| tt tt tt tt := binop.sar
theorem binop.bits_eq {b0 b1 b2 b3 e op} :
binop.bits op β¨[b0, b1, b2, b3], eβ© β op = binop.from_bits b0 b1 b2 b3 :=
begin
generalize e' : (β¨[b0, b1, b2, b3], eβ© : bitvec 4) = v,
intro h, induction h;
{ cases bitvec.reify_eq (congr_arg subtype.val e'), refl }
end
theorem binop.bits.determ : β {op1 op2 v},
binop.bits op1 v β binop.bits op2 v β op1 = op2
| op1 op2 β¨[b0, b1, b2, b3], _β© h1 h2 :=
(binop.bits_eq h1).trans (binop.bits_eq h2).symm
def basic_cond.from_bits : β (b0 b1 b2 : bool), option basic_cond
| ff ff ff := some basic_cond.o
| tt ff ff := some basic_cond.b
| ff tt ff := some basic_cond.e
| tt tt ff := some basic_cond.na
| ff ff tt := some basic_cond.s
| tt ff tt := none
| ff tt tt := some basic_cond.l
| tt tt tt := some basic_cond.ng
theorem basic_cond.bits_eq {b0 b1 b2 e c} :
basic_cond.bits c β¨[b0, b1, b2], eβ© β basic_cond.from_bits b0 b1 b2 = some c :=
begin
generalize e' : (β¨[b0, b1, b2], eβ© : bitvec 3) = v,
intro h, induction h;
{ cases bitvec.reify_eq (congr_arg subtype.val e'), refl }
end
def cond_code.from_bits (b0 b1 b2 b3 : bool) : option cond_code :=
option.map (cond_code.mk b0) (basic_cond.from_bits b1 b2 b3)
theorem cond_code.bits_eq {b0 b1 b2 b3 e c} :
cond_code.bits c β¨[b0, b1, b2, b3], eβ© β cond_code.from_bits b0 b1 b2 b3 = some c :=
begin
rintro β¨β©,
rcases split_bits_ok a_a with β¨β¨β©, hβ, _β©,
cases subtype.eq hβ,
rw [cond_code.from_bits, basic_cond.bits_eq a_a_1], refl
end
theorem cond_code.bits.determ : β {c1 c2 v},
cond_code.bits c1 v β cond_code.bits c2 v β c1 = c2
| c1 c2 β¨[b0, b1, b2, b3], _β© h1 h2 := option.some_inj.1 $
(cond_code.bits_eq h1).symm.trans (cond_code.bits_eq h2)
theorem read_displacement_ne_3 {mod disp l} :
read_displacement mod disp l β mod β 3 :=
by rintro β¨β© β¨β©
theorem read_displacement.determ_aux {mod disp1 disp2 l l'}
(hβ : read_displacement mod disp1 l)
(hβ : read_displacement mod disp2 (l ++ l')) : (disp1, l') = (disp2, []) :=
begin
cases hβ; cases hβ; try {refl},
cases bits_to_byte.determ_l_aux hβ_a hβ_a, refl
end
theorem read_displacement.determ {mod disp1 disp2 l}
(hβ : read_displacement mod disp1 l)
(hβ : read_displacement mod disp2 l) : disp1 = disp2 :=
by cases read_displacement.determ_aux hβ
(by rw list.append_nil; exact hβ); refl
theorem read_sib_displacement_ne_3 {mod bbase w Base l} :
read_sib_displacement mod bbase w Base l β mod β 3 :=
by rw [read_sib_displacement]; split_ifs; [
{rcases h with β¨_, rflβ©; rintro _ β¨β©},
exact Ξ» h, read_displacement_ne_3 h.1]
theorem read_sib_displacement.determ_aux {mod bbase w1 w2 Base1 Base2 l l'}
(hβ : read_sib_displacement mod bbase w1 Base1 l)
(hβ : read_sib_displacement mod bbase w2 Base2 (l ++ l')) : (w1, Base1, l') = (w2, Base2, []) :=
begin
rw read_sib_displacement at hβ hβ, split_ifs at hβ hβ,
{ rcases hβ with β¨b, rfl, rfl, rflβ©,
rcases hβ with β¨_, rfl, rfl, β¨β©β©, refl },
{ rcases hβ with β¨h1, rflβ©,
rcases hβ with β¨h2, rflβ©,
cases read_displacement.determ_aux h1 h2, refl },
end
theorem read_sib_displacement.determ {mod bbase w1 w2 Base1 Base2 l}
(hβ : read_sib_displacement mod bbase w1 Base1 l)
(hβ : read_sib_displacement mod bbase w2 Base2 l) : (w1, Base1) = (w2, Base2) :=
by cases read_sib_displacement.determ_aux hβ
(by rw list.append_nil; exact hβ); refl
theorem read_SIB_ne_3 {rex mod rm l} :
read_SIB rex mod rm l β mod β 3 :=
by rintro β¨β©; exact read_sib_displacement_ne_3 a_a_1
theorem read_SIB.determ_aux {rex mod rm1 rm2 l l'}
(hβ : read_SIB rex mod rm1 l)
(hβ : read_SIB rex mod rm2 (l ++ l')) : (rm1, l') = (rm2, []) :=
begin
cases hβ, cases hβ,
cases split_bits.determ hβ_a hβ_a rfl,
cases read_sib_displacement.determ_aux hβ_a_1 hβ_a_1, refl
end
theorem read_SIB.determ {rex mod rm1 rm2 l}
(hβ : read_SIB rex mod rm1 l)
(hβ : read_SIB rex mod rm2 l) : rm1 = rm2 :=
by cases read_SIB.determ_aux hβ
(by rw list.append_nil; exact hβ); refl
theorem read_ModRM_nil {rex reg r} : Β¬ read_ModRM rex reg r [] :=
by rintro β¨β©
def read_ModRM' (rex : REX) (r : RM)
(rm : bitvec 3) (mod : bitvec 2) (l : list byte) : Prop :=
if mod = 3 then
r = RM.reg (rex_reg rex.B rm) β§
l = []
else if rm = 4 then
read_SIB rex mod r l
else if rm = 5 β§ mod = 0 then β i : word,
i.to_list_byte l β§
r = RM.mem none base.rip (EXTS i)
else β disp,
read_displacement mod disp l β§
r = RM.mem none (base.reg (rex_reg rex.B rm)) disp
theorem read_ModRM_ModRM' {rex : REX} {reg : regnum} {r : RM}
{rm reg_opc : bitvec 3} {mod : bitvec 2} {b : byte} {l : list byte}
(hβ : split_bits b.to_nat [β¨3, rmβ©, β¨3, reg_opcβ©, β¨2, modβ©])
(hβ : read_ModRM rex reg r (b :: l)) :
reg = rex_reg rex.R reg_opc β§ read_ModRM' rex r rm mod l :=
begin
generalize_hyp e : list.cons b l = l' at hβ,
induction hβ; cases e;
cases split_bits.determ hβ hβ_a rfl;
refine β¨rfl, _β©,
{ rw [read_ModRM', if_neg, if_neg, if_pos],
exact β¨_, hβ_a_1, rflβ©,
all_goals {exact dec_trivial} },
{ rw [read_ModRM', if_pos],
exact β¨rfl, rflβ©, exact dec_trivial },
{ rw [read_ModRM', if_neg (read_SIB_ne_3 hβ_a_1), if_pos],
exact hβ_a_1, refl },
{ rw [read_ModRM', if_neg (read_displacement_ne_3 hβ_a_3),
if_neg hβ_a_1, if_neg hβ_a_2],
exact β¨_, hβ_a_3, rflβ© },
end
theorem read_ModRM_split {rex reg r b l}
(h : read_ModRM rex reg r (b :: l)) :
β rm reg_opc mod,
split_bits b.to_nat [β¨3, rmβ©, β¨3, reg_opcβ©, β¨2, modβ©] :=
by cases h; exact β¨_, _, _, by assumptionβ©
theorem read_ModRM.determ_aux {rex reg1 r1 reg2 r2 l l'}
(hβ : read_ModRM rex reg1 r1 l)
(hβ : read_ModRM rex reg2 r2 (l ++ l')) :
(reg1, r1, l') = (reg2, r2, []) :=
begin
simp,
cases l with b l, {cases read_ModRM_nil hβ},
rcases read_ModRM_split hβ with β¨rm, reg_opc, r, sβ©,
rcases read_ModRM_ModRM' s hβ with β¨rfl, hβ'β©,
rcases read_ModRM_ModRM' s hβ with β¨rfl, hβ'β©,
refine β¨rfl, _β©,
clear hβ hβ s, unfold read_ModRM' at hβ' hβ',
split_ifs at hβ' hβ',
{ rw hβ'.2 at hβ', exact β¨hβ'.1.trans hβ'.1.symm, hβ'.2β© },
{ cases read_SIB.determ_aux hβ' hβ', exact β¨rfl, rflβ© },
{ rcases hβ' with β¨i1, h11, h12β©,
rcases hβ' with β¨i2, h21, h22β©,
cases bits_to_byte.determ_l_aux h11 h21,
exact β¨h12.trans h22.symm, rflβ© },
{ rcases hβ' with β¨i1, h11, h12β©,
rcases hβ' with β¨i2, h21, h22β©,
cases read_displacement.determ_aux h11 h21,
exact β¨h12.trans h22.symm, rflβ© },
end
theorem read_ModRM.determ {rex reg1 r1 reg2 r2 l}
(hβ : read_ModRM rex reg1 r1 l)
(hβ : read_ModRM rex reg2 r2 l) : (reg1, r1) = (reg2, r2) :=
by cases read_ModRM.determ_aux hβ
(by rw list.append_nil; exact hβ); refl
theorem read_ModRM.determβ {rex reg1 r1 reg2 r2 l1 l2 l1' l2'}
(hβ : read_ModRM rex reg1 r1 l1)
(hβ : read_ModRM rex reg2 r2 l2)
(e : l1 ++ l1' = l2 ++ l2') : (reg1, r1, l1, l1') = (reg2, r2, l2, l2') :=
begin
have : β {reg1 r1 reg2 r2 l1 l2 l1' l2'}
(hβ : read_ModRM rex reg1 r1 l1)
(hβ : read_ModRM rex reg2 r2 l2)
(e : β a', l2 = l1 ++ a' β§ l1' = a' ++ l2'),
(l1, l1') = (l2, l2'),
{ intros, rcases e_1 with β¨l3, rfl, rflβ©,
cases read_ModRM.determ_aux hβ_1 hβ_1, simp },
cases (list.append_eq_append_iff.1 e).elim
(Ξ» h, this hβ hβ h)
(Ξ» h, (this hβ hβ h).symm),
cases read_ModRM.determ hβ hβ, refl,
end
theorem read_opcode_ModRM.determ_aux {rex v1 r1 v2 r2 l l'}
(hβ : read_opcode_ModRM rex v1 r1 l)
(hβ : read_opcode_ModRM rex v2 r2 (l ++ l')) : (v1, r1, l') = (v2, r2, []) :=
begin
cases hβ, cases hβ,
cases read_ModRM.determ_aux hβ_a hβ_a,
cases split_bits.determ hβ_a_1 hβ_a_1 rfl, refl,
end
theorem read_opcode_ModRM.determ {rex v1 r1 v2 r2 l}
(hβ : read_opcode_ModRM rex v1 r1 l)
(hβ : read_opcode_ModRM rex v2 r2 l) : (v1, r1) = (v2, r2) :=
by cases read_opcode_ModRM.determ_aux hβ
(by rw list.append_nil; exact hβ); refl
theorem read_opcode_ModRM.determβ_aux {rex v1 r1 v2 r2 l1 l2 l1' l2' l'}
(hβ : read_opcode_ModRM rex v1 r1 l1)
(hβ : read_opcode_ModRM rex v2 r2 l2)
(e : l1 ++ l1' ++ l' = l2 ++ l2') : (v1, r1, l1, l1' ++ l') = (v2, r2, l2, l2') :=
begin
cases hβ, cases hβ,
rw [list.append_assoc, list.append_eq_append_iff] at e,
rcases e with β¨x, rfl, eβ© | β¨x, rfl, rflβ©,
{ cases read_ModRM.determ_aux hβ_a hβ_a, cases e,
cases split_bits.determ hβ_a_1 hβ_a_1 rfl,
rw list.append_nil, refl },
{ cases read_ModRM.determ_aux hβ_a hβ_a,
cases split_bits.determ hβ_a_1 hβ_a_1 rfl,
rw list.append_nil, refl },
end
theorem read_opcode_ModRM.determβ {rex v1 r1 v2 r2 l1 l2 l1' l2'}
(hβ : read_opcode_ModRM rex v1 r1 l1)
(hβ : read_opcode_ModRM rex v2 r2 l2) :
l1 ++ l1' = l2 ++ l2' β (v1, r1, l1, l1') = (v2, r2, l2, l2') :=
by simpa using @read_opcode_ModRM.determβ_aux _ _ _ _ _ _ _ l1' l2' [] hβ hβ
theorem read_imm8.determ_aux {w1 w2 l l'}
(hβ : read_imm8 w1 l) (hβ : read_imm8 w2 (l ++ l')) : (w1, l') = (w2, []) :=
by cases hβ; cases hβ; refl
theorem read_imm16.determ_aux {w1 w2 l l'}
(hβ : read_imm16 w1 l) (hβ : read_imm16 w2 (l ++ l')) : (w1, l') = (w2, []) :=
by cases hβ; cases hβ; cases bits_to_byte.determ_l_aux hβ_a hβ_a; refl
theorem read_imm32.determ_aux {w1 w2 l l'}
(hβ : read_imm32 w1 l) (hβ : read_imm32 w2 (l ++ l')) : (w1, l') = (w2, []) :=
by cases hβ; cases hβ; cases bits_to_byte.determ_l_aux hβ_a hβ_a; refl
theorem read_imm8.determ {w1 w2 l}
(hβ : read_imm8 w1 l) (hβ : read_imm8 w2 l) : w1 = w2 :=
by cases hβ; cases hβ; refl
theorem read_imm16.determ {w1 w2 l}
(hβ : read_imm16 w1 l) (hβ : read_imm16 w2 l) : w1 = w2 :=
by cases hβ; cases hβ; cases bits_to_byte.determ_l hβ_a hβ_a; refl
theorem read_imm32.determ {w1 w2 l}
(hβ : read_imm32 w1 l) (hβ : read_imm32 w2 l) : w1 = w2 :=
by cases hβ; cases hβ; cases bits_to_byte.determ_l hβ_a hβ_a; refl
theorem read_imm.determ_aux : β {sz w1 w2 l l'},
read_imm sz w1 l β read_imm sz w2 (l ++ l') β (w1, l') = (w2, [])
| (wsize.Sz8 _) _ _ _ _ := read_imm8.determ_aux
| wsize.Sz16 _ _ _ _ := read_imm16.determ_aux
| wsize.Sz32 _ _ _ _ := read_imm32.determ_aux
| wsize.Sz64 _ _ _ _ := false.elim
theorem read_full_imm.determ_aux : β {sz w1 w2 l l'},
read_full_imm sz w1 l β read_full_imm sz w2 (l ++ l') β (w1, l') = (w2, [])
| (wsize.Sz8 _) _ _ _ _ := read_imm8.determ_aux
| wsize.Sz16 _ _ _ _ := read_imm16.determ_aux
| wsize.Sz32 _ _ _ _ := read_imm32.determ_aux
| wsize.Sz64 _ _ _ _ := bits_to_byte.determ_l_aux
theorem read_imm.determ {sz w1 w2 l}
(hβ : read_imm sz w1 l) (hβ : read_imm sz w2 l) : w1 = w2 :=
by cases read_imm.determ_aux hβ
(by rw list.append_nil; exact hβ); refl
theorem read_full_imm.determ {sz w1 w2 l}
(hβ : read_full_imm sz w1 l) (hβ : read_full_imm sz w2 l) : w1 = w2 :=
by cases read_full_imm.determ_aux hβ
(by rw list.append_nil; exact hβ); refl
def decode_two' (rex : REX) (a : ast) (b0 b1 b2 b3 b4 b5 b6 b7 : bool) (l : list byte) : Prop :=
cond b7
(cond b6
( -- xadd
[b1, b2, b3, b4, b5] = [ff, ff, ff, ff, ff] β§
let v := b0, sz := op_size_W rex v in
β reg r,
read_ModRM rex reg r l β§
a = ast.xadd sz r reg)
(cond b5
(cond b2
( -- movsx
[b1, b4] = [tt, tt] β§
let sz2 := op_size_W rex tt,
sz := if b0 then wsize.Sz16 else wsize.Sz8 rex.is_some in
β reg r,
read_ModRM rex reg r l β§
a = (if b3 then ast.movsx else ast.movzx) sz (dest_src.R_rm reg r) sz2)
( -- cmpxchg
[b1, b4] = [ff, tt] β§
let v := b0, sz := op_size_W rex v in
β reg r,
read_ModRM rex reg r l β§
a = ast.cmpxchg sz r reg))
(cond b4
( -- setcc
β reg r code,
read_ModRM rex reg r l β§
cond_code.from_bits b0 b1 b2 b3 = some code β§
a = ast.setcc code rex.is_some r)
( -- jcc
β imm code,
read_imm32 imm l β§
cond_code.from_bits b0 b1 b2 b3 = some code β§
a = ast.jcc code imm))))
(cond b6
( -- cmov
[b4, b5] = [ff, ff] β§
let sz := op_size tt rex.W tt in
β reg r code,
read_ModRM rex reg r l β§
cond_code.from_bits b0 b1 b2 b3 = some code β§
a = ast.cmov code sz (dest_src.R_rm reg r))
( -- syscall
[b0, b1, b2, b3, b4, b5] = [tt, ff, tt, ff, ff, ff] β§
a = ast.syscall β§
l = []))
theorem decode_two_two' {rex a b0 b1 b2 b3 b4 b5 b6 b7 l} :
decode_two rex a (β¨[b0, b1, b2, b3, b4, b5, b6, b7], rflβ© :: l) β
decode_two' rex a b0 b1 b2 b3 b4 b5 b6 b7 l :=
begin
generalize e : (β¨[b0, b1, b2, b3, b4, b5, b6, b7], rflβ© :: l : list byte) = l',
intro a, cases a,
{ cases e, rcases split_bits_ok a_a with β¨hβ, hβ, _β©,
cases subtype.eq hβ,
cases bitvec.reify_eq hβ,
exact β¨rfl, _, _, _, a_a_1, cond_code.bits_eq a_a_2, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨hβ, hβ, _β©,
cases subtype.eq hβ,
cases bitvec.reify_eq hβ,
exact β¨_, _, a_a_1, cond_code.bits_eq a_a_2, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨hβ, hβ, _β©,
cases subtype.eq hβ,
cases bitvec.reify_eq hβ,
exact β¨_, _, _, a_a_1, cond_code.bits_eq a_a_2, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
exact β¨rfl, _, _, a_a_1, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, hβ, β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
cases bitvec.reify_eq hβ,
exact β¨rfl, _, _, a_a_1, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
exact β¨rfl, _, _, a_a_1, rflβ© },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact β¨rfl, rfl, rflβ© },
end
theorem decode_two_nil {rex a} : Β¬ decode_two rex a [].
theorem decode_two.determ_aux {rex aβ aβ l l'} :
decode_two rex aβ l β decode_two rex aβ (l ++ l') β (aβ, l') = (aβ, []) :=
begin
cases l with b l, {exact decode_two_nil.elim},
apply byte_split b, introv h1 h2,
replace h1 := decode_two_two' h1,
replace h2 := decode_two_two' h2,
unfold decode_two' at h1 h2,
repeat { do
`(cond %%e _ _) β tactic.get_local `h1 >>= tactic.infer_type,
tactic.cases e $> (); `[dsimp only [cond] at h1 h2] },
{ rcases h1.2 with β¨rfl, rflβ©,
rcases h2.2 with β¨rfl, β¨β©β©, refl },
{ rcases h1.2 with β¨reg1, r1, h11, h12, h13, rflβ©,
rcases h2.2 with β¨reg2, r2, h21, h22, h23, rflβ©,
cases read_ModRM.determ_aux h12 h22,
cases h13.symm.trans h23, refl },
{ rcases h1 with β¨imm1, code1, h11, h12, rflβ©,
rcases h2 with β¨imm2, code2, h21, h22, rflβ©,
cases read_imm32.determ_aux h11 h21,
cases h12.symm.trans h22, refl },
{ rcases h1 with β¨reg1, r1, code1, h11, h12, rflβ©,
rcases h2 with β¨reg2, r2, code2, h21, h22, rflβ©,
cases read_ModRM.determ_aux h11 h21,
cases h12.symm.trans h22, refl },
{ rcases h1 with β¨reg1, r1, code1, h11, h12, rflβ©,
rcases h2 with β¨reg2, r2, code2, h21, h22, rflβ©,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1.2 with β¨reg1, r1, h11, rflβ©,
rcases h2.2 with β¨reg2, r2, h21, rflβ©,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1.2 with β¨reg1, r1, h11, rflβ©,
rcases h2.2 with β¨reg2, r2, h21, rflβ©,
cases read_ModRM.determ_aux h11 h21, refl },
end
theorem decode_two.determ {rex aβ aβ l}
(hβ : decode_two rex aβ l) (hβ : decode_two rex aβ l) : aβ = aβ :=
by cases decode_two.determ_aux hβ
(by rw list.append_nil; exact hβ); refl
def decode_hi' (v : bool) (sz : wsize) (r : RM) :
β (b0 b1 b2 x : bool), ast β list byte β Prop
| ff ff ff ff a l := β imm,
read_imm sz imm l β§
a = ast.binop binop.tst sz (dest_src.Rm_i r imm)
| ff tt ff ff a l := a = ast.unop unop.not sz r β§ l = []
| tt tt ff ff a l := a = ast.unop unop.neg sz r β§ l = []
| ff ff tt ff a l := a = ast.mul sz r β§ l = []
| ff tt tt ff a l := a = ast.div sz r β§ l = []
| ff ff ff tt a l := a = ast.unop unop.inc sz r β§ l = []
| tt ff ff tt a l := a = ast.unop unop.dec sz r β§ l = []
| ff tt ff tt a l := a = ast.call (imm_rm.rm r) β§ l = []
| ff ff tt tt a l := a = ast.jump r β§ l = []
| ff tt tt tt a l := a = ast.push (imm_rm.rm r) β§ l = []
| _ _ _ _ a l := false
theorem decode_hi_hi' {v sz r x b0 b1 b2 a l}
(h : decode_hi v sz r x β¨[b0, b1, b2], rflβ© a l) : decode_hi' v sz r b0 b1 b2 x a l :=
begin
generalize_hyp e : (β¨[b0, b1, b2], rflβ© : bitvec 3) = opc at h,
induction h; cases congr_arg subtype.val (bitvec.reify_eq' e),
exact β¨_, h_a, rflβ©, all_goals { exact β¨rfl, rflβ© }
end
theorem decode_hi.determ_aux {v sz r x aβ aβ l l'} : β {opc},
decode_hi v sz r x opc aβ l β decode_hi v sz r x opc aβ (l ++ l') β (aβ, l') = (aβ, [])
| β¨[b0, b1, b2], _β© h1 h2 := begin
replace h1 := decode_hi_hi' h1,
replace h2 := decode_hi_hi' h2, clear decode_hi.determ_aux,
cases b0; cases b1; cases b2; cases x; cases h1; cases h2,
{ cases read_imm.determ_aux h1_h.1 h2_h.1,
cases h1_h.2.trans h2_h.2.symm, refl },
all_goals {
rw [h1_left, β h2_left],
cases h1_right, cases h2_right, refl }
end
theorem decode_hi.determ {v sz r x opc aβ aβ l}
(hβ : decode_hi v sz r x opc aβ l) (hβ : decode_hi v sz r x opc aβ l) : aβ = aβ :=
by cases decode_hi.determ_aux hβ
(by rw list.append_nil; exact hβ); refl
def decode_aux' (rex : REX) (a : ast) (b0 b1 b2 b3 b4 b5 b6 b7 : bool) (l : list byte) : Prop :=
cond b7
(cond b6
(cond b5
(cond b4
(cond b2
(cond b1
( -- hi
let v := b0, sz := op_size_W rex v in
β opc r l1 l2,
read_opcode_ModRM rex opc r l1 β§
decode_hi v sz r b3 opc a l2 β§
l = l1 ++ l2)
( -- cmc
b0 = tt β§
a = ast.cmc β§
l = []))
( -- clc, stc
[b1, b3] = [ff, tt] β§
a = cond b0 ast.stc ast.clc β§
l = []))
(cond b0
( -- jump
[b2, b3] = [ff, tt] β§
β imm,
(if b1 then read_imm8 imm l else read_imm32 imm l) β§
a = ast.jcc cond_code.always imm)
( -- call
[b2, b3] = [ff, tt] β§
β imm,
read_imm32 imm l β§
a = ast.call (imm_rm.imm imm))))
( let v := b0, sz := op_size_W rex v in
cond b4
( -- binop_hi_reg
[b2, b3] = [ff, ff] β§
β opc r op,
read_opcode_ModRM rex opc r l β§ opc β 6 β§
binop.bits op (rex_reg tt opc) β§
let src_dst := if b1 then dest_src.Rm_r r RCX else dest_src.Rm_i r 1 in
a = ast.binop op sz src_dst)
(cond b3
( -- leave
[b0, b1, b2] = [tt, ff, ff] β§
a = ast.leave β§
l = [])
(cond b2
( -- mov_imm
b1 = tt β§
β opc r imm l1 l2,
read_opcode_ModRM rex opc r l1 β§
read_imm sz imm l2 β§
a = ast.mov sz (dest_src.Rm_i r imm) β§
l = l1 ++ l2)
(cond b1
( -- ret
β imm,
(if v then imm = 0 β§ l = [] else read_imm16 imm l) β§
a = ast.ret imm)
( -- binop_hi
β opc r imm op l1 l2,
read_opcode_ModRM rex opc r l1 β§ opc β 6 β§
binop.bits op (rex_reg tt opc) β§
read_imm8 imm l2 β§
a = ast.binop op sz (dest_src.Rm_i r imm) β§
l = l1 ++ l2))))))
(cond b5
(cond b4
( -- mov64
let v := b3, sz := op_size_W rex v in
β imm,
read_full_imm sz imm l β§
a = ast.mov sz (dest_src.Rm_i (RM.reg β¨[b0, b1, b2, rex.B], rflβ©) imm))
( -- test_rax
[b1, b2, b3] = [ff, ff, tt] β§
let v := b0, sz := op_size tt rex.W v in
β imm,
read_imm sz imm l β§
a = ast.binop binop.tst sz (dest_src.Rm_i (RM.reg RAX) imm)))
(cond b4
( -- xchg_rax
b3 = ff β§
let sz := op_size tt rex.W tt in
a = ast.xchg sz (RM.reg RAX) β¨[b0, b1, b2, rex.B], rflβ© β§
l = [])
(cond b3
(cond b2
(cond b1
( -- pop_rm
b0 = tt β§
β r,
read_opcode_ModRM rex 0 r l β§
a = ast.pop r)
( -- lea
b0 = tt β§
β reg r,
let sz := op_size tt rex.W tt in
read_ModRM rex reg r l β§ RM.is_mem r β§
a = ast.lea sz (dest_src.R_rm reg r)))
( -- mov
let v := b0, sz := op_size_W rex v in
β reg r,
read_ModRM rex reg r l β§
let src_dst := if b1 then dest_src.R_rm reg r else dest_src.Rm_r r reg in
a = ast.mov sz src_dst))
(cond b2
( let v := b0, sz := op_size_W rex v in
-- xchg, test
β reg r,
read_ModRM rex reg r l β§
a = cond b1 (ast.xchg sz r reg)
(ast.binop binop.tst sz (dest_src.Rm_r r reg)))
( -- binop_imm, binop_imm8
let sz := op_size_W rex (cond b1 tt b0) in
β opc r l1 imm l2 op,
read_opcode_ModRM rex opc r l1 β§
binop.bits op (EXTZ opc) β§
cond b1 (read_imm8 imm l2) (read_imm sz imm l2) β§
a = ast.binop op sz (dest_src.Rm_i r imm) β§
l = l1 ++ l2))))))
(cond b6
(cond b5
(cond b4
( -- jcc8
β code imm,
cond_code.from_bits b0 b1 b2 b3 = some code β§
read_imm8 imm l β§
a = ast.jcc code imm)
(cond b3
( -- push_imm
[b0, b2] = [ff, ff] β§
β imm,
read_imm (if b1 then wsize.Sz8 ff else wsize.Sz32) imm l β§
a = ast.push (imm_rm.imm imm))
( -- movsx
[b0, b1, b2] = [tt, tt, ff] β§
β reg r,
read_ModRM rex reg r l β§
a = ast.movsx wsize.Sz32 (dest_src.R_rm reg r) wsize.Sz64)))
(cond b4
( -- pop, push_rm
let reg := RM.reg β¨[b0, b1, b2, rex.B], rflβ© in
a = cond b3 (ast.pop reg) (ast.push (imm_rm.rm reg)) β§
l = [])
( -- prefix byte
false)))
(cond b2
(cond b1
( -- decode_two
[b0, b3, b4, b5] = [tt, tt, ff, ff] β§
decode_two rex a l)
( -- binop_imm_rax
let v := b0, sz := op_size_W rex v,
op := binop.from_bits b3 b4 b5 ff in
β imm, read_imm sz imm l β§
a = ast.binop op sz (dest_src.Rm_i (RM.reg RAX) imm)))
( -- binop1
let v := b0, d := b1, sz := op_size_W rex v,
op := binop.from_bits b3 b4 b5 ff in
β reg r, read_ModRM rex reg r l β§
let src_dst := if d then dest_src.R_rm reg r else dest_src.Rm_r r reg in
a = ast.binop op sz src_dst)))
theorem decode_aux_aux' {rex a b0 b1 b2 b3 b4 b5 b6 b7 l} :
decode_aux rex a (β¨[b0, b1, b2, b3, b4, b5, b6, b7], rflβ© :: l) β
decode_aux' rex a b0 b1 b2 b3 b4 b5 b6 b7 l :=
begin
generalize e : (β¨[b0, b1, b2, b3, b4, b5, b6, b7], rflβ© :: l : list byte) = l',
intro a, cases a,
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, β¨β©, β¨β©, hβ, hβ, _β©,
cases subtype.eq hβ,
cases bitvec.reify_eq hβ,
cases binop.bits_eq a_a_2,
exact β¨_, _, a_a_1, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, hβ, hβ, hβ, _β©,
cases bitvec.reify_eq hβ,
cases subtype.eq hβ,
cases bitvec.reify_eq hβ,
cases binop.bits_eq a_a_1,
exact β¨_, a_a_2, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
exact β¨_, _, _, _, _, _, a_a_1, a_a_3, a_a_2, rfl, rflβ© },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
exact β¨_, _, _, _, _, _, a_a, a_a_1, a_a_2, rfl, h_2β© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
exact β¨_, _, _, _, _, _, a_a_1, a_a_2, a_a_3, a_a_4, rfl, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
exact β¨rfl, _, _, _, a_a_1, a_a_2, a_a_3, rflβ© },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact β¨rfl, a_a_1β© },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact β¨rfl, _, _, a_a, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
exact β¨_, _, a_a_1, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨hβ, β¨β©, hβ, _β©,
cases subtype.eq hβ,
cases bitvec.reify_eq hβ,
exact β¨_, a_a_1, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
exact β¨rfl, _, _, _, _, _, a_a_1, a_a_2, rfl, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
exact β¨_, _, a_a_1, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨hβ, hβ, _β©,
cases subtype.eq hβ,
cases bitvec.reify_eq hβ,
exact β¨rfl, rfl, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
exact β¨rfl, _, a_a_1, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨hβ, hβ, _β©,
cases subtype.eq hβ,
cases bitvec.reify_eq hβ,
exact β¨rfl, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨hβ, hβ, _β©,
cases subtype.eq hβ,
cases bitvec.reify_eq hβ,
exact β¨rfl, rflβ© },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact β¨rfl, _, a_a, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
exact β¨rfl, _, a_a_1, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨hβ, hβ, _β©,
cases subtype.eq hβ,
cases bitvec.reify_eq hβ,
exact β¨_, _, cond_code.bits_eq a_a_1, a_a_2, rflβ© },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact β¨rfl, _, a_a, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
exact β¨_, a_a_1, rflβ© },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact β¨rfl, rfl, rflβ© },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact β¨rfl, _, _, a_a, a_a_1, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
exact β¨_, _, a_a_1, rflβ© },
{ cases e, rcases split_bits_ok a_a with β¨β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
exact β¨rfl, _, a_a_1, rflβ© },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact β¨rfl, rfl, rflβ© },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact β¨rfl, rfl, rflβ© },
{ injection e, cases congr_arg subtype.val (bitvec.reify_eq' h_1),
cases h_2, exact β¨rfl, rfl, rflβ© },
{ cases e, rcases split_bits_ok a_a_1 with β¨β¨β©, hβ, β¨β©, hβ, _β©,
cases bitvec.reify_eq hβ,
cases bitvec.reify_eq hβ,
exact β¨_, _, _, _, a_a_2, a_a_3, rflβ© },
end
theorem decode_aux_nil {rex a} : Β¬ decode_aux rex a [].
theorem decode_aux.determ_aux {rex aβ aβ l l'} :
decode_aux rex aβ l β decode_aux rex aβ (l ++ l') β (aβ, l') = (aβ, []) :=
begin
cases l with b l, {exact decode_aux_nil.elim},
apply byte_split b, introv h1 h2,
replace h1 := decode_aux_aux' h1,
replace h2 := decode_aux_aux' h2,
unfold decode_aux' at h1 h2,
repeat { do
`(cond %%e _ _) β tactic.get_local `h1 >>= tactic.infer_type,
tactic.cases e $> (); `[dsimp only [cond] at h1 h2] },
{ rcases h1 with β¨reg1, r1, h11, rflβ©,
rcases h2 with β¨reg2, r2, h21, rflβ©,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1 with β¨imm1, h11, rflβ©,
rcases h2 with β¨imm2, h21, rflβ©,
cases read_imm.determ_aux h11 h21, refl },
{ exact decode_two.determ_aux h1.2 h2.2 },
{ cases h2 },
{ rcases h1 with β¨rfl, rflβ©,
rcases h2 with β¨rfl, β¨β©β©, refl },
{ rcases h1.2 with β¨reg1, r1, h11, rflβ©,
rcases h2.2 with β¨reg2, r2, h21, rflβ©,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1.2 with β¨imm1, h11, rflβ©,
rcases h2.2 with β¨imm2, h21, rflβ©,
cases read_imm.determ_aux h11 h21, refl },
{ rcases h1 with β¨code1, imm1, h11, h12, rflβ©,
rcases h2 with β¨code2, imm2, h21, h22, rflβ©,
cases h11.symm.trans h21,
cases read_imm8.determ_aux h12 h22, refl },
{ rcases h1 with β¨opc1, r1, l11, imm1, l12, op1, h11, h12, h13, rfl, rflβ©,
rcases h2 with β¨opc2, r2, l21, imm2, l22, op2, h21, h22, h23, rfl, eβ©,
cases read_opcode_ModRM.determβ_aux h11 h21 e,
cases binop.bits.determ h12 h22,
cases b1,
{ cases read_imm.determ_aux h13 h23, refl },
{ cases read_imm8.determ_aux h13 h23, refl } },
{ rcases h1 with β¨reg1, r1, h11, rflβ©,
rcases h2 with β¨reg2, r2, h21, rflβ©,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1 with β¨reg1, r1, h11, rflβ©,
rcases h2 with β¨reg2, r2, h21, rflβ©,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1.2 with β¨reg1, r1, h11, h12, rflβ©,
rcases h2.2 with β¨reg2, r2, h21, h22, rflβ©,
cases read_ModRM.determ_aux h11 h21, refl },
{ rcases h1.2 with β¨r1, h11, h12, rflβ©,
rcases h2.2 with β¨r2, h21, h22, rflβ©,
cases read_opcode_ModRM.determ_aux h11 h21, refl },
{ rcases h1.2 with β¨rfl, rflβ©,
rcases h2.2 with β¨rfl, β¨β©β©, refl },
{ rcases h1.2 with β¨imm1, h11, rflβ©,
rcases h2.2 with β¨imm2, h21, rflβ©,
cases read_imm.determ_aux h11 h21, refl },
{ rcases h1 with β¨imm1, h11, rflβ©,
rcases h2 with β¨imm2, h21, rflβ©,
cases read_full_imm.determ_aux h11 h21, refl },
{ rcases h1 with β¨opc1, r1, imm1, op1, l11, l12, h11, _, h12, h13, rfl, rflβ©,
rcases h2 with β¨opc2, r2, imm2, op2, l21, l22, h21, _, h22, h23, rfl, eβ©,
cases read_opcode_ModRM.determβ_aux h11 h21 e,
cases binop.bits.determ h12 h22,
cases read_imm8.determ_aux h13 h23, refl },
{ rcases h1 with β¨imm1, h11, rflβ©,
rcases h2 with β¨imm2, h21, rflβ©,
split_ifs at h11 h21,
{ rcases h11 with β¨rfl, rflβ©,
rcases h21 with β¨rfl, β¨β©β©, refl },
{ cases read_imm16.determ_aux h11 h21, refl } },
{ rcases h1 with β¨opc1, r1, imm1, op1, l11, l12, h11, h12, rfl, rflβ©,
rcases h2 with β¨opc2, r2, imm2, op2, l21, l22, h21, h22, rfl, eβ©,
cases read_opcode_ModRM.determβ_aux h11 h21 e,
cases read_imm.determ_aux h12 h22, refl },
{ rcases h1.2 with β¨rfl, rflβ©,
rcases h2.2 with β¨rfl, β¨β©β©, refl },
{ rcases h1.2 with β¨opc1, r1, op1, h11, _, h12, rflβ©,
rcases h2.2 with β¨opc2, r2, op2, h21, _, h22, rflβ©,
cases read_opcode_ModRM.determ_aux h11 h21,
cases binop.bits.determ h12 h22, refl },
{ rcases h1.2 with β¨imm1, h11, rflβ©,
rcases h2.2 with β¨imm2, h21, rflβ©,
cases read_imm32.determ_aux h11 h21, refl },
{ rcases h1.2 with β¨imm1, h11, rflβ©,
rcases h2.2 with β¨imm2, h21, rflβ©,
split_ifs at h11 h21,
{ cases read_imm8.determ_aux h11 h21, refl },
{ cases read_imm32.determ_aux h11 h21, refl } },
{ rcases h1.2 with β¨rfl, rflβ©,
rcases h2.2 with β¨rfl, β¨β©β©, refl },
{ rcases h1.2 with β¨rfl, rflβ©,
rcases h2.2 with β¨rfl, β¨β©β©, refl },
{ rcases h1 with β¨opc1, r1, l11, l12, h11, h12, rflβ©,
rcases h2 with β¨opc2, r2, l21, l22, h21, h22, eβ©,
cases read_opcode_ModRM.determβ_aux h11 h21 e,
exact decode_hi.determ_aux h12 h22 },
end
theorem decode_aux.determ {rex aβ aβ l}
(hβ : decode_aux rex aβ l) (hβ : decode_aux rex aβ l) : aβ = aβ :=
by cases decode_aux.determ_aux hβ
(by rw list.append_nil; exact hβ); refl
theorem decode.no_prefix {rex rex' a l b l'} :
read_prefixes rex l β b β l β Β¬ decode_aux rex' a (b :: l') :=
begin
rintro β¨β© (rfl|β¨β¨β©β©),
-- generalize e : b :: l' = lβ,
revert a_1_a, apply byte_split b, intros,
rcases split_bits_ok a_1_a with β¨_, β¨β©, _β©,
exact decode_aux_aux'
end
theorem decode_nil {a} : Β¬ decode a [] :=
begin
generalize e : [] = l, rintro β¨β©,
cases a_1_l1; cases e,
exact decode_aux_nil a_1_a_2
end
theorem decode.determ_aux {aβ aβ l l'}
(hβ : decode aβ l) (hβ : decode aβ (l ++ l')) : (aβ, l') = (aβ, []) :=
begin
generalize_hyp e : l ++ l' = x at hβ,
induction hβ, induction hβ,
rw [list.append_assoc, list.append_eq_append_iff] at e,
rcases e with β¨_|β¨b, xβ©, rfl, eβ© | β¨_|β¨b, xβ©, rfl, rflβ©,
{ rw list.append_nil at hβ_a_1, cases e,
cases read_prefixes.determ hβ_a_1 hβ_a_1,
exact decode_aux.determ_aux hβ_a_2 hβ_a_2 },
{ cases hβ_l2 with b' l2, cases decode_aux_nil hβ_a_2,
injection e, subst b',
cases decode.no_prefix hβ_a_1 (list.mem_append_right _ (or.inl rfl)) hβ_a_2 },
{ rw list.append_nil at hβ_a_1,
cases read_prefixes.determ hβ_a_1 hβ_a_1,
exact decode_aux.determ_aux hβ_a_2 hβ_a_2 },
{ cases decode.no_prefix hβ_a_1 (list.mem_append_right _ (or.inl rfl)) hβ_a_2 },
end
theorem decode.determ {aβ aβ l}
(hβ : decode aβ l) (hβ : decode aβ l) : aβ = aβ :=
by cases decode.determ_aux hβ
(by rw list.append_nil; exact hβ); refl
instance : add_comm_monoid perm :=
{ zero := β¨ff, ff, ffβ©,
add_assoc := Ξ» a b c,
show perm.mk (_||_||_) (_||_||_) (_||_||_) = _,
by repeat {rw bool.bor_assoc}; refl,
zero_add := Ξ» β¨r, w, xβ©,
show perm.mk (ff||_) (ff||_) (ff||_) = _,
by repeat {rw ff_bor},
add_zero := Ξ» β¨r, w, xβ©,
show perm.mk (_||ff) (_||ff) (_||ff) = _,
by repeat {rw bor_ff},
add_comm := Ξ» a b,
show perm.mk (_||_) (_||_) (_||_) = _,
by rw [bool.bor_comm, bool.bor_comm a.isW, bool.bor_comm a.isX]; refl,
..perm.has_add }
theorem perm.add_self : β p : perm, p + p = p
| β¨r, w, xβ© :=
show perm.mk (r||r) (w||w) (x||x) = _,
by repeat {rw bor_self}
instance : partial_order perm :=
{ le_refl := perm.add_self,
le_trans := Ξ» a b c (hβ : a + b = b) (hβ : b + c = c),
show a + c = c, by rw [β hβ, β add_assoc, hβ],
le_antisymm := Ξ» a b (hβ : a + b = b) (hβ : b + a = a),
by rw [β hβ, add_comm, hβ],
..perm.has_le }
theorem perm.le_add_left {pβ pβ : perm} : pβ β€ pβ + pβ :=
show _=_, by rw [β add_assoc, perm.add_self]
theorem mem.read1.determ {p1 p2 m a b1 b2} :
mem.read1 p1 m a b1 β mem.read1 p2 m a b2 β b1 = b2 :=
by rintro β¨_, rfl, _β© β¨_, rfl, _β©; refl
theorem mem.read'.determ_aux {p1 p2 m a l1 l2}
(hβ : mem.read' p1 m a l1) (hβ : mem.read' p2 m a l2) :
l1 <+: l2 β¨ l2 <+: l1 :=
begin
induction hβ generalizing l2,
{ exact or.inl (list.nil_prefix _) },
cases hβ,
{ exact or.inr (list.nil_prefix _) },
cases hβ_a.determ hβ_a,
rw [list.prefix_cons_inj, list.prefix_cons_inj],
exact hβ_ih hβ_a_1,
end
theorem mem.read'.determ_len {p1 p2 m a l1 l2}
(hβ : mem.read' p1 m a l1) (hβ : mem.read' p2 m a l2)
(h : l1.length = l2.length) : l1 = l2 :=
(mem.read'.determ_aux hβ hβ).elim
(Ξ» h', list.eq_of_prefix_of_length_eq h' h)
(Ξ» h', (list.eq_of_prefix_of_length_eq h' h.symm).symm)
theorem mem_decode.determ {p1 p2 m a l1 l2 ast1 ast2}
(mβ : mem.read' p1 m a l1) (hβ : decode ast1 l1)
(mβ : mem.read' p2 m a l2) (hβ : decode ast2 l2) :
(ast1, l1) = (ast2, l2) :=
begin
rcases mem.read'.determ_aux mβ mβ with β¨x, rflβ© | β¨x, rflβ©,
{ cases decode.determ_aux hβ hβ, simp },
{ cases decode.determ_aux hβ hβ, simp },
end
theorem config.step_noIO {k kβ kβ} :
config.step k kβ β Β¬ config.isIO k kβ :=
Ξ» hβ hβ, begin
cases hβ, cases hβ,
cases mem_decode.determ hβ_a_1 hβ_a_2 hβ_a hβ_a_1,
rcases hβ_a_3 with β¨_, sβ, _, β¨β©, _β©
end
theorem mem.write1.determ {m a b mβ mβ}
(hβ : mem.write1 m a b mβ)
(hβ : mem.write1 m a b mβ) : mβ = mβ :=
by cases hβ; cases hβ; refl
theorem mem.write.determ {m a l mβ mβ}
(hβ : mem.write m a l mβ)
(hβ : mem.write m a l mβ) : mβ = mβ :=
begin
induction hβ generalizing mβ; cases hβ, refl,
cases mem.write1.determ hβ_a hβ_a,
cases hβ_ih hβ_a_1, refl
end
theorem config.write_mem.determ {k a l kβ kβ}
(hβ : config.write_mem k a l kβ)
(hβ : config.write_mem k a l kβ) : kβ = kβ :=
by cases hβ; cases hβ; cases mem.write.determ hβ_a_1 hβ_a_1; refl
theorem EA.write.determ {k ea sz v kβ kβ}
(hβ : EA.write k ea sz v kβ)
(hβ : EA.write k ea sz v kβ) : kβ = kβ :=
begin
cases hβ; cases hβ, refl,
cases bits_to_byte.determ hβ_a_1 hβ_a_1,
exact config.write_mem.determ hβ_a_2 hβ_a_2
end
theorem config.isIO.determ {k kβ kβ} :
config.isIO k kβ β config.isIO k kβ β
β k' vβ vβ,
kβ = config.set_reg k' 11 vβ β§
kβ = config.set_reg k' 11 vβ :=
begin
rintro β¨lβ, _, mβ, dβ, _, _, β¨β©, β¨β©, k', aβ, qβ, _, β¨β¨β©, rflβ©, hββ©
β¨lβ, _, mβ, dβ, _, _, β¨β©, β¨β©, k'', aβ, qβ, _, β¨β¨β©, rflβ©, hββ©,
cases mem_decode.determ mβ dβ mβ dβ,
cases EA.write.determ aβ aβ,
cases hβ, cases hβ,
exact β¨_, _, _, rfl, rflβ©
end
theorem config.step.no_exit {k kβ r} :
config.step k kβ β Β¬ config.exit k r :=
Ξ» h β¨k', h', _β©, config.step_noIO h h'
theorem set_reg_ne {k r r' q} (h : r' β r) :
(config.set_reg k r q).regs r' = k.regs r' :=
if_neg h
theorem config.set_reg_11_exec_exit {k v r} :
exec_exit (config.set_reg k 11 v) r β exec_exit k r :=
begin
split; rintro β¨eβ©; split,
{ rwa set_reg_ne at e, rintro β¨β© },
{ rwa set_reg_ne, rintro β¨β© },
end
theorem config.isIO.determ_exec {k kβ kβ r}
(hβ : config.isIO k kβ) (hβ : config.isIO k kβ) :
exec_exit kβ r β exec_exit kβ r :=
begin
rcases hβ.determ hβ with β¨k', vβ, vβ, rfl, rflβ©,
simp [config.set_reg_11_exec_exit],
end
theorem exec_io.no_exit {i o k i' o' k' ret r} :
exec_io i o k (k.regs RAX) i' o' k' ret β Β¬ exec_exit k r :=
begin
rintro h β¨eβ©, rw e at h,
rcases h with β¨_, _, _, _, eβ© | β¨_, _, _, _, _, _, _, eβ©;
cases bitvec.reify_eqβ e,
end
theorem read_from_fd.io_part {fd i H_dat i'}
(H : read_from_fd fd i H_dat i') : i' <:+ i :=
begin
cases H, apply list.suffix_refl,
exact β¨_, rflβ©
end
theorem exec_read.io_part {i k fd count i' k' ret}
(H : exec_read i k fd count i' k' ret) : i' <:+ i :=
begin
cases H, apply list.suffix_refl,
exact read_from_fd.io_part H_a_2
end
theorem exec_io.io_part {kβ iβ oβ kβ iβ oβ call ret}
(H : exec_io iβ oβ kβ call iβ oβ kβ ret) :
iβ <:+ iβ β§ oβ <+: oβ :=
begin
induction H, exact β¨list.suffix_refl _, list.prefix_refl _β©,
exact β¨exec_read.io_part H_a_2, list.prefix_refl _β©,
end
theorem kcfg.step.no_exit {k k' r} :
kcfg.step k k' β Β¬ config.exit k.k r :=
begin
rintro (β¨_, _, _, _, hβ© | β¨_, _, kβ, kβ, _, _, _, _, hβ, hβ©),
{ exact h.no_exit },
{ rintro β¨kβ, hβ, eβ©,
exact h.no_exit ((hβ.determ_exec hβ).2 e) },
end
theorem kcfg.step.io_part {kβ iβ oβ kβ iβ oβ}
(H : kcfg.step β¨iβ, oβ, kββ© β¨iβ, oβ, kββ©) :
iβ <:+ iβ β§ oβ <+: oβ :=
begin
cases H, exact β¨list.suffix_refl _, list.prefix_refl _β©,
exact exec_io.io_part H_a_1
end
@[simp] theorem EXTZ_id {n} (w : bitvec n) : EXTZ w = w :=
begin
suffices : β l n, list.length l = n β (@EXTZ_aux l n).to_list = l,
{ exact subtype.eq (this w.1 _ w.2) },
intro l, induction l; intros n e; cases e, {refl},
unfold EXTZ_aux, rw [vector.to_list_cons, l_ih _ rfl],
end
@[simp] theorem EXTS_id {n} (w : bitvec n) : EXTS w = w :=
begin
suffices : β l a n, list.length l = n β (@EXTS_aux l a n).to_list = l,
{ exact subtype.eq (this w.1 _ _ w.2) },
intro l, induction l; intros n a e; cases e, {refl},
unfold EXTS_aux, rw [vector.to_list_cons, l_ih _ _ rfl],
end
theorem EA.read_reg_64 {r k q} :
(EA.r r).read k wsize.Sz64 q β q = k.regs r :=
by simp [EA.read]
theorem EA.readq_reg_64 {r k q} :
(EA.r r).readq k wsize.Sz64 q β q = k.regs r :=
by simp [EA.readq, EA.read_reg_64]
theorem EA.write_reg_64 {r k q k'} :
(EA.r r).write k wsize.Sz64 q k' β k' = k.set_reg r q :=
by split; [{rintro β¨β©, refl}, {rintro rfl, constructor}]
theorem EA.writeq_reg_64 {r k q k'} :
(EA.r r).writeq k wsize.Sz64 q k' β k' = k.set_reg r q :=
by simp [EA.writeq, EA.write_reg_64]
theorem mem.set.read'_exists {p m q w b v}
(h1 : mem.read' p m q v) : β v', mem.read' p (m.set w b) q v' :=
begin
induction h1, {exact β¨_, mem.read'.nil _ _ _β©},
cases h1_ih with v1 ih,
rcases h1_a with β¨_, rfl, h1β©,
exact β¨_, mem.read'.cons β¨_, rfl, h1β© ihβ©,
end
theorem mem.write.read'_exists {p m q a v v2 m'}
(h1 : mem.read' p m q v) (h2 : mem.write m a v2 m') :
β v', mem.read' p m' q v' :=
begin
induction h2 generalizing v, {exact β¨_, h1β©},
cases h2_a with h3 h4,
cases mem.set.read'_exists h1 with v1 h1,
exact h2_ih h1,
end
theorem EA.read.determ {k ea sz w1 w2}
(h1 : EA.read k ea sz w1) (h2 : EA.read k ea sz w2) : w1 = w2 :=
begin
cases ea,
{ exact h1.trans h2.symm },
{ cases sz, cases sz, all_goals {exact h1.trans h2.symm} },
{ rcases h1 with β¨_, a1, b1β©,
rcases h2 with β¨_, a2, b2β©,
cases a1.determ_len a2 (b1.1.trans b2.1.symm),
exact bits_to_byte.determ_l b1 b2 },
end
theorem EA.readq.determ {k ea sz q1 q2} :
EA.readq k ea sz q1 β EA.readq k ea sz q2 β q1 = q2
| β¨a1, b1, e1β© β¨a2, b2, e2β© :=
by cases b1.determ b2; exact e1.trans e2.symm
theorem hoare_p.bind {P P' : kcfg β Prop}
(H : β {{k}}, P k β hoare_p P' k) {k} : hoare_p P k β hoare_p P' k :=
begin
intro h, induction h,
exact H h_a,
exact hoare_p.step h_a (Ξ» k', h_ih _),
by_cases h_ret = 0,
{ cases H (h_a_1 h),
{ exact hoare_p.zero a },
{ cases a with k' h, cases h.no_exit h_a },
{ exact hoare_p.exit _ _ a a_1 } },
{ exact hoare_p.exit _ _ h_a h.elim },
end
theorem hoare_p.mono {P P' : kcfg β Prop}
(H : β {{k}}, P k β P' k) {k} : hoare_p P k β hoare_p P' k :=
hoare_p.bind (Ξ» k h, hoare_p.zero (H h))
end x86 |
34d13a414b027c5b765f99142c53cb69f31db959 | 88fb7558b0636ec6b181f2a548ac11ad3919f8a5 | /tests/lean/run/1562.lean | db95359906bc656fe994629b0aedf7f0f570186b | [
"Apache-2.0"
] | permissive | moritayasuaki/lean | 9f666c323cb6fa1f31ac597d777914aed41e3b7a | ae96ebf6ee953088c235ff7ae0e8c95066ba8001 | refs/heads/master | 1,611,135,440,814 | 1,493,852,869,000 | 1,493,852,869,000 | 90,269,903 | 0 | 0 | null | 1,493,906,291,000 | 1,493,906,291,000 | null | UTF-8 | Lean | false | false | 494 | lean | meta constant term : Type
meta constant smt2.builder.int_const : int -> term
meta constant smt2_state : Type
@[reducible] meta def smt2_m (Ξ± : Type) :=
state_t smt2_state tactic Ξ±
meta instance tactic_to_smt2_m (Ξ± : Type) : has_coe (tactic Ξ±) (smt2_m Ξ±) :=
β¨ fun tc, fun s, do res β tc, return (res, s) β©
meta def reflect_arith_formula : expr β smt2_m term
| ```(has_zero.zero) := smt2.builder.int_const <$> tactic.eval_expr int ```(has_zero.zero int)
| a := tactic.fail "foo"
|
ee5c4afacade4f49b96a2f8a48e2dc517de794b9 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/Lean3Lib/init/meta/float_auto.lean | 8688c8426ff850c9dfe00fe607dbbd13baa99008 | [] | 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 | 158 | lean | /- Authors: E.W.Ayers -/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.data.default
namespace Mathlib
namespace native
namespace float
end Mathlib |
80f8c40302ab981c93ce29bd38246aabe9e4d2f9 | 5ae26df177f810c5006841e9c73dc56e01b978d7 | /src/algebra/Mon/basic.lean | 4bbd2e16de0d6a9d0150e820a8b09d6ce535bdcc | [
"Apache-2.0"
] | permissive | ChrisHughes24/mathlib | 98322577c460bc6b1fe5c21f42ce33ad1c3e5558 | a2a867e827c2a6702beb9efc2b9282bd801d5f9a | refs/heads/master | 1,583,848,251,477 | 1,565,164,247,000 | 1,565,164,247,000 | 129,409,993 | 0 | 1 | Apache-2.0 | 1,565,164,817,000 | 1,523,628,059,000 | Lean | UTF-8 | Lean | false | false | 1,823 | lean | /- Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
Introduce Mon -- the category of monoids.
Currently only the basic setup.
-/
import category_theory.concrete_category algebra.group
universes u v
open category_theory
/-- The category of monoids and monoid morphisms. -/
@[reducible] def Mon : Type (u+1) := bundled monoid
/-- The category of commutative monoids and monoid morphisms. -/
@[reducible] def CommMon : Type (u+1) := bundled comm_monoid
namespace Mon
instance (x : Mon) : monoid x := x.str
instance concrete_is_monoid_hom : concrete_category @is_monoid_hom :=
β¨by introsI Ξ± ia; apply_instance,
by introsI Ξ± Ξ² Ξ³ ia ib ic f g hf hg; apply_instanceβ©
def of (X : Type u) [monoid X] : Mon := β¨Xβ©
abbreviation forget : Mon.{u} β₯€ Type u := forget
instance hom_is_monoid_hom {R S : Mon} (f : R βΆ S) : is_monoid_hom (f : R β S) := f.2
end Mon
namespace CommMon
instance (x : CommMon) : comm_monoid x := x.str
@[reducible] def is_comm_monoid_hom {Ξ± Ξ²} [comm_monoid Ξ±] [comm_monoid Ξ²] (f : Ξ± β Ξ²) : Prop :=
is_monoid_hom f
instance concrete_is_comm_monoid_hom : concrete_category @is_comm_monoid_hom :=
β¨by introsI Ξ± ia; apply_instance,
by introsI Ξ± Ξ² Ξ³ ia ib ic f g hf hg; apply_instanceβ©
def of (X : Type u) [comm_monoid X] : CommMon := β¨Xβ©
abbreviation forget : CommMon.{u} β₯€ Type u := forget
instance hom_is_comm_monoid_hom {R S : CommMon} (f : R βΆ S) :
is_comm_monoid_hom (f : R β S) := f.2
/-- The forgetful functor from commutative monoids to monoids. -/
def forget_to_Mon : CommMon β₯€ Mon :=
concrete_functor
(by intros _ c; exact { ..c })
(by introsI _ _ _ _ f i; exact { ..i })
instance : faithful (forget_to_Mon) := {}
end CommMon
|
ec072efc529512e8d85c616271d6a798b85a1385 | f3849be5d845a1cb97680f0bbbe03b85518312f0 | /library/init/data/to_string.lean | 7f4766e87329b62d5b255f25afcf62c30b25f8a8 | [
"Apache-2.0"
] | permissive | bjoeris/lean | 0ed95125d762b17bfcb54dad1f9721f953f92eeb | 4e496b78d5e73545fa4f9a807155113d8e6b0561 | refs/heads/master | 1,611,251,218,281 | 1,495,337,658,000 | 1,495,337,658,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,587 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.data.string.basic init.data.bool.basic init.data.subtype.basic
import init.data.unsigned.basic init.data.prod init.data.sum.basic init.data.nat.div
open sum subtype nat
universes u v
class has_to_string (Ξ± : Type u) :=
(to_string : Ξ± β string)
def to_string {Ξ± : Type u} [has_to_string Ξ±] : Ξ± β string :=
has_to_string.to_string
instance : has_to_string bool :=
β¨Ξ» b, cond b "tt" "ff"β©
instance {p : Prop} : has_to_string (decidable p) :=
-- Remark: type class inference will not consider local instance `b` in the new elaborator
β¨Ξ» b : decidable p, @ite p b _ "tt" "ff"β©
protected def list.to_string_aux {Ξ± : Type u} [has_to_string Ξ±] : bool β list Ξ± β string
| b [] := ""
| tt (x::xs) := to_string x ++ list.to_string_aux ff xs
| ff (x::xs) := ", " ++ to_string x ++ list.to_string_aux ff xs
protected def list.to_string {Ξ± : Type u} [has_to_string Ξ±] : list Ξ± β string
| [] := "[]"
| (x::xs) := "[" ++ list.to_string_aux tt (x::xs) ++ "]"
instance {Ξ± : Type u} [has_to_string Ξ±] : has_to_string (list Ξ±) :=
β¨list.to_stringβ©
instance : has_to_string unit :=
β¨Ξ» u, "star"β©
instance {Ξ± : Type u} [has_to_string Ξ±] : has_to_string (option Ξ±) :=
β¨Ξ» o, match o with | none := "none" | (some a) := "(some " ++ to_string a ++ ")" endβ©
instance {Ξ± : Type u} {Ξ² : Type v} [has_to_string Ξ±] [has_to_string Ξ²] : has_to_string (Ξ± β Ξ²) :=
β¨Ξ» s, match s with | (inl a) := "(inl " ++ to_string a ++ ")" | (inr b) := "(inr " ++ to_string b ++ ")" endβ©
instance {Ξ± : Type u} {Ξ² : Type v} [has_to_string Ξ±] [has_to_string Ξ²] : has_to_string (Ξ± Γ Ξ²) :=
β¨Ξ» β¨a, bβ©, "(" ++ to_string a ++ ", " ++ to_string b ++ ")"β©
instance {Ξ± : Type u} {Ξ² : Ξ± β Type v} [has_to_string Ξ±] [s : β x, has_to_string (Ξ² x)] : has_to_string (sigma Ξ²) :=
β¨Ξ» β¨a, bβ©, "β¨" ++ to_string a ++ ", " ++ to_string b ++ "β©"β©
instance {Ξ± : Type u} {p : Ξ± β Prop} [has_to_string Ξ±] : has_to_string (subtype p) :=
β¨Ξ» s, to_string (val s)β©
/- Remark: the code generator replaces this definition with one that display natural numbers in decimal notation -/
protected def nat.to_string : nat β string
| 0 := "zero"
| (succ a) := "(succ " ++ nat.to_string a ++ ")"
instance : has_to_string nat :=
β¨nat.to_stringβ©
def hex_digit_to_string (n : nat) : string :=
if n β€ 9 then to_string n
else if n = 10 then "a"
else if n = 11 then "b"
else if n = 12 then "c"
else if n = 13 then "d"
else if n = 14 then "e"
else "f"
def char_to_hex (c : char) : string :=
let n := char.to_nat c,
d2 := n / 16,
d1 := n % 16
in hex_digit_to_string d2 ++ hex_digit_to_string d1
def char.quote_core (c : char) : string :=
if c = '\n' then "\\n"
else if c = '\t' then "\\t"
else if c = '\\' then "\\\\"
else if c = '\"' then "\\\""
else if char.to_nat c <= 31 then "\\x" ++ char_to_hex c
else [c]
instance : has_to_string char :=
β¨Ξ» c, "'" ++ char.quote_core c ++ "'"β©
def string.quote_aux : string β string
| [] := ""
| (x::xs) := string.quote_aux xs ++ char.quote_core x
def string.quote : string β string
| [] := "\"\""
| (x::xs) := "\"" ++ string.quote_aux (x::xs) ++ "\""
instance : has_to_string string :=
β¨string.quoteβ©
instance (n : nat) : has_to_string (fin n) :=
β¨Ξ» f, to_string (fin.val f)β©
instance : has_to_string unsigned :=
β¨Ξ» n, to_string (fin.val n)β©
|
e91945045ec7c4f26a611daca9e0a6e95d75a9d2 | 6dc0c8ce7a76229dd81e73ed4474f15f88a9e294 | /src/Lean/Data/Position.lean | a35dc0a8f3d82bc4a7359c12a73524af00d83aca | [
"Apache-2.0"
] | permissive | williamdemeo/lean4 | 72161c58fe65c3ad955d6a3050bb7d37c04c0d54 | 6d00fcf1d6d873e195f9220c668ef9c58e9c4a35 | refs/heads/master | 1,678,305,356,877 | 1,614,708,995,000 | 1,614,708,995,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,239 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
import Lean.Data.Format
namespace Lean
structure Position where
line : Nat
column : Nat
deriving Inhabited, DecidableEq, Repr
namespace Position
protected def lt : Position β Position β Bool
| β¨lβ, cββ©, β¨lβ, cββ© => (lβ, cβ) < (lβ, cβ)
instance : ToFormat Position :=
β¨fun β¨l, cβ© => "β¨" ++ fmt l ++ ", " ++ fmt c ++ "β©"β©
instance : ToString Position :=
β¨fun β¨l, cβ© => "β¨" ++ toString l ++ ", " ++ toString c ++ "β©"β©
end Position
structure FileMap where
source : String
positions : Array String.Pos
lines : Array Nat
deriving Inhabited
namespace FileMap
partial def ofString (s : String) : FileMap :=
let rec loop (i : String.Pos) (line : Nat) (ps : Array String.Pos) (lines : Array Nat) : FileMap :=
if s.atEnd i then { source := s, positions := ps.push i, lines := lines.push line }
else
let c := s.get i;
let i := s.next i;
if c == '\n' then loop i (line+1) (ps.push i) (lines.push (line+1))
else loop i line ps lines
loop 0 1 (#[0]) (#[1])
partial def toPosition (fmap : FileMap) (pos : String.Pos) : Position :=
match fmap with
| { source := str, positions := ps, lines := lines } =>
if ps.size >= 2 && pos <= ps.back then
let rec toColumn (i : String.Pos) (c : Nat) : Nat :=
if i == pos || str.atEnd i then c
else toColumn (str.next i) (c+1)
let rec loop (b e : Nat) :=
let posB := ps[b]
if e == b + 1 then { line := lines.get! b, column := toColumn posB 0 }
else
let m := (b + e) / 2;
let posM := ps.get! m;
if pos == posM then { line := lines.get! m, column := 0 }
else if pos > posM then loop m e
else loop b m
loop 0 (ps.size -1)
else
-- Some systems like the delaborator use synthetic positions without an input file,
-- which would violate `toPositionAux`'s invariant
β¨1, posβ©
end FileMap
end Lean
def String.toFileMap (s : String) : Lean.FileMap :=
Lean.FileMap.ofString s
|
a9332e39dc51dba196f88e3b503aee6e293623c7 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /tests/lean/run/simpStar.lean | 7ef9d42a1e183dcce534176e18781caa5e5f888e | [
"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 | 490 | lean | opaque f (x y : Nat) : Nat
opaque g (x : Nat) : Nat
theorem ex1 (x : Nat) (hβ : f x x = g x) (hβ : g x = x) : f x (f x x) = x := by
simp
simp [*]
theorem ex2 (x : Nat) (hβ : f x x = g x) (hβ : g x = x) : f x (f x x) = x := by
simp [*]
axiom g_ax (x : Nat) : g x = 0
theorem ex3 (x y : Nat) (hβ : f x x = g x) (hβ : f x x < 5) : f x x + f x x = 0 := by
simp [*] at *
trace_state
have auxβ : f x x = g x := hβ
have auxβ : g x < 5 := hβ
simp [g_ax]
|
75f92982d4a649923e413a73bebe40847a6a1fa6 | ea80d7bb31b9673a3a06d5148363b44b66c53796 | /thys/move.lean | 1086ae568afb335e671602da0160b9204780e8ea | [] | no_license | gitter-badger/electrolysis | 2a59d6e0fe1b6629a14a1202e31b1a8ff1c93ced | 4f63846e817cb52bdac4ae65ef3d17634e6ffc36 | refs/heads/master | 1,608,825,996,259 | 1,467,154,609,000 | 1,467,154,609,000 | 62,184,345 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,209 | lean | /- things that may or may not belong in the stdlib -/
import data.list
import data.list.sorted
open eq.ops
open list
open nat
open option
lemma generalize_with_eq {A : Type} {P : A β Prop} (x : A) (H : βy, x = y β P y) : P x := H x rfl
namespace nat
open int
definition of_int : β€ β β
| (int.of_nat n) := n
| _ := 0
lemma of_int_one : of_int 1 = 1 := rfl
end nat
namespace option
variables {A B : Type}
protected definition any [unfold 3] (P : A β Prop) : option A β Prop
| (some x) := P x
| none := false
protected theorem any.elim {x : option A} {P : A β Prop} (H : option.any P x) : βy, x = some y β§ P y :=
begin
cases x with y,
{ contradiction },
{ apply exists.intro y (and.intro rfl H) }
end
theorem ex_some_of_neq_none {x : option A} (H : x β none) : βy, x = some y :=
begin
cases x with y,
{ exfalso, apply H rfl },
{ existsi y, apply rfl }
end
protected definition bind [unfold 4] {A B : Type} (f : A β option B) : option A β option B
| (some x) := f x
| none := none
theorem bind_some_eq_id {x : option A} : option.bind some x = x :=
by cases x; esimp; esimp
theorem bind_neq_none {f : A β option B} {x} (Hx : x β none) (Hf : βx', f x' β none) : option.bind f x β none :=
obtain x' Hβ, from ex_some_of_neq_none Hx,
obtain x'' Hβ, from ex_some_of_neq_none (Hf x'),
by rewrite [Hβ, βΈ*, Hβ]; contradiction
end option
namespace list
section
parameter {A : Type}
variable xs : list A
-- first without [inhabited], last without predicate
definition first' [unfold 2] : option A := nth xs 0
definition last' : list A β option A
| [] := none
| [x] := some x
| (x::xs) := last' xs
theorem last'_cons_eq_last' : Ξ {x : A} {xs : list A}, xs β nil β last' (x::xs) = last' xs
| x [] H := false.elim (H rfl)
| x (x'::xs) H := by esimp
theorem firstn_sub : Ξ (n : β) (xs : list A), firstn n xs β xs
| 0 xs := nil_sub _
| (succ n) [] := sub.refl _
| (succ n) (x::xs) := cons_sub_cons x (firstn_sub n xs)
theorem dropn_nil (n : β) : dropn n (nil : list A) = nil :=
nat.cases_on n rfl (Ξ»n, rfl)
theorem mem_of_mem_dropn (x : A) : Ξ (n : β) (xs : list A), x β dropn n xs β x β xs
| 0 xs H := H
| (n+1) [] H := by contradiction
| (succ n) (y::xs) H := by esimp at H; apply mem_cons_of_mem y (mem_of_mem_dropn n xs H)
theorem dropn_sub_dropn_cons : Ξ (n : β) (x : A) (xs : list A), dropn n xs β dropn n (x::xs)
| 0 x xs := sub_cons x xs
| (succ n) x [] := nil_sub _
| (succ n) x (x'::xs) := by esimp; apply dropn_sub_dropn_cons n x' xs
theorem dropn_sub : Ξ (n : β) (xs : list A), dropn n xs β xs
| 0 xs := sub.refl _
| (succ n) [] := sub.refl _
| (succ n) (x::xs) := by esimp; apply sub.trans (dropn_sub_dropn_cons n x xs) (dropn_sub n (x::xs))
theorem dropn_dropn (n : β) : Ξ (m : β) (xs : list A), dropn n (dropn m xs) = dropn (n+m) xs
| 0 xs := by esimp
| (succ m) [] := by rewrite +dropn_nil
| (succ m) (x::xs) := by rewrite [nat.add_succ, βdropn at {1,3}]; apply dropn_dropn m xs
theorem last'_dropn_of_last' : Ξ (n : β) (xs : list A) (H : n < length xs), last' (dropn n xs) = last' xs
| 0 xs H := rfl
| (succ n) [] H := by rewrite length_nil at H
| (succ n) (x::xs) H := begin
have H' : n < length xs, from lt_of_succ_lt_succ (!length_cons βΈ H),
have xs β nil, begin
intro Hcontr,
rewrite [Hcontr at H', length_nil at H'],
apply not_succ_le_zero n H',
end,
rewrite [βdropn, last'_cons_eq_last' this],
apply last'_dropn_of_last' n xs H'
end
theorem nth_eq_first'_dropn : Ξ (n : β) (xs : list A), nth xs n = first' (dropn n xs)
| 0 xs := rfl
| (succ n) [] := by esimp
| (succ n) (x::xs) := by rewrite [βdropn, βnth]; apply nth_eq_first'_dropn n xs
theorem firstn_app_dropn_eq_self : Ξ (n : β) (xs : list A), firstn n xs ++ dropn n xs = xs
| 0 xs := rfl
| (succ n) [] := rfl
| (succ n) (x::xs) := by rewrite [βfirstn, βdropn, βΈ*, append_cons, firstn_app_dropn_eq_self]
theorem mem_of_nth : Ξ {i : β} {xs : list A} {y : A}, nth xs i = some y β y β xs
| _ [] _ H := by contradiction
| 0 (x::xs) y H := by injection H with Hxy; apply Hxy βΈ !mem_cons
| (succ i) (x::xs) y H := by rewrite [βnth at H]; apply mem_cons_of_mem x (mem_of_nth H)
theorem nth_of_mem : Ξ {xs : list A} {y : A}, y β xs β βi, nth xs i = some y
| [] y H := by contradiction
| (x::xs) y H := or.rec_on (eq_or_mem_of_mem_cons H)
(suppose y = x, exists.intro 0 (this βΈ rfl))
(suppose y β xs,
obtain i Hnth, from nth_of_mem this,
exists.intro (i+1) (!nth_succ β¬ Hnth))
theorem lt_length_of_mem : Ξ {xs : list A} {i : β} {y : A}, nth xs i = some y β i < length xs
| [] i y H := by contradiction
| (x::xs) 0 y H := !zero_lt_succ
| (x::xs) (succ i) y H := by unfold nth at H; apply succ_lt_succ (lt_length_of_mem H)
definition insert_at : list A β β β A β list A
| [] n y := [y]
| xs 0 y := y::xs
| (x::xs) (succ n) y := x::insert_at xs n y
end
inductive prefixeq {A : Type} : list A β list A β Prop :=
infix ` ββ `:50 := prefixeq
| nil : Ξ ys, [] ββ ys
| cons : Ξ x {xs ys}, xs ββ ys β x::xs ββ x::ys
namespace prefixeq
section
parameter {A : Type}
infix ` ββ `:50 := prefixeq
protected theorem refl [refl] : Ξ (xs : list A), xs ββ xs
| [] := !nil
| (x::xs) := cons x (refl xs)
protected theorem trans [trans] : Ξ {xs ys zs : list A}, xs ββ ys β ys ββ zs β xs ββ zs
| [] ys zs _ _ := !nil
| (x::xs) (x::ys) (x::zs) (cons x Hβ) (cons x Hβ) :=
cons x (trans Hβ Hβ)
protected theorem antisymm : Ξ {xs ys : list A}, xs ββ ys β ys ββ xs β xs = ys
| [] [] _ _ := rfl
| (x::xs) (x::ys) (cons x Hβ) (cons x Hβ) := antisymm Hβ Hβ βΈ rfl
definition weak_order [instance] : weak_order (list A) := β¦weak_order,
le := prefixeq, le_refl := refl, le_trans := @trans, le_antisymm := @antisymm
β¦
theorem nth_of_nth_prefixeq {i : β} {xs ys : list A} {z : A} (Hxs : nth xs i = some z) (Hprefix : xs ββ ys) : nth ys i = some z :=
begin
revert i Hxs,
induction Hprefix with x z' xs ys Hprefix ih,
all_goals intro i Hxs,
{ contradiction },
{ cases i with i,
{ apply Hxs },
{ apply ih i Hxs }
}
end
theorem firstn_prefixeq : Ξ (n : β) (xs : list A), firstn n xs ββ xs
| 0 xs := !nil
| (succ n) [] := !nil
| (succ n) (x::xs) := cons x (firstn_prefixeq n xs)
theorem dropn_prefixeq_dropn_of_prefixeq : Ξ (n : β) {xs ys : list A} (H : xs ββ ys),
dropn n xs ββ dropn n ys
| 0 xs ys H := H
| n [] ys H := by rewrite dropn_nil; apply !prefixeq.nil
| (succ n) (x::xs) (x::ys) (cons x H) := by unfold dropn; apply dropn_prefixeq_dropn_of_prefixeq n H
end
end prefixeq
namespace sorted
section
parameter {A : Type}
parameter [decidable_linear_order A]
definition insert_pos : list A β A β β
| [] y := 0
| (x::xs) y := if y β€ x
then 0
else succ (insert_pos xs y)
theorem insert_pos_le_length : Ξ (xs : list A) (y : A), insert_pos xs y β€ length xs
| [] y := zero_le _
| (x::xs) y := begin
unfold insert_pos, cases (_ : decidable (y β€ x)),
{ apply zero_le },
{ apply succ_le_succ (insert_pos_le_length xs y) }
end
section
variable {xs : list A}
variable (Hsorted : sorted le xs)
theorem first_le {x x' : A} (Hsorted : sorted le (x::xs)) (Hx'_mem : x' β x::xs) : x β€ x' :=
or.rec_on (eq_or_mem_of_mem_cons Hx'_mem)
(assume H : x' = x, H βΈ le.refl x')
(assume H : x' β xs, of_mem_of_all H (sorted_extends (@le.trans _ _) Hsorted))
include Hsorted
theorem le_of_nth_le_nth {xβ xβ : A} : Ξ {i j : β}, nth xs i = some xβ β nth xs j = some xβ β i β€ j β xβ β€ xβ :=
begin
induction Hsorted using sorted.rec with y ys Hhd_rel Hsorted ih,
{ contradiction },
{ intro i j Hi Hj Hle,
cases i with i',
{ injection Hi with H, subst H,
apply first_le (sorted.step Hhd_rel Hsorted) (mem_of_nth Hj) },
{ cases j with j',
{ exfalso, apply !not_succ_le_zero Hle },
{ unfold nth at Hi, unfold nth at Hj, apply ih Hi Hj (le_of_succ_le_succ Hle) }
}
}
end
theorem insert_pos_gt {y xi : A} {i : β} (Hyxi : y > xi) (Hnth : nth xs i = some xi) :
insert_pos xs y > i :=
begin
revert i Hnth,
induction Hsorted using sorted.rec with x xs Hhd_rel Hsorted ih,
{ contradiction },
{ unfold insert_pos, cases (_ : decidable (y β€ x)) with Hyx Hyx,
{ intro i Hnth, exfalso,
exact lt.irrefl _ (
calc x β€ xi : first_le (sorted.step Hhd_rel Hsorted) (mem_of_nth Hnth)
... < y : Hyxi
... β€ x : Hyx)
},
{ intro i Hnth, cases i with i,
{ apply zero_lt_succ },
{ apply succ_lt_succ (ih i Hnth) }
}
}
end
theorem insert_pos_le {y xi : A} {i : β} (Hyxi : y < xi) (Hnth : nth xs i = some xi) :
insert_pos xs y β€ i :=
begin
revert i Hnth,
induction Hsorted using sorted.rec with x xs Hhd_rel Hsorted ih,
{ contradiction },
{ unfold insert_pos, cases (_ : decidable (y β€ x)) with Hyx Hyx,
{ intros, apply zero_le },
{ intro i Hnth, cases i with i,
{ injection Hnth with Hx_eq_xi,
exfalso, apply Hyx (le_of_lt (Hx_eq_xiβ»ΒΉ βΈ Hyxi)) },
{ apply succ_le_succ (ih i Hnth) }
}
}
end
theorem sorted_insert_at_insert_pos (y : A) :
sorted le (insert_at xs (insert_pos xs y) y) :=
begin
note Hlsorted := locally_sorted_of_sorted Hsorted,
clear Hsorted,
apply sorted_of_locally_sorted,
induction xs with x xs ih,
{ apply locally_sorted.base },
{ unfold insert_pos,
exact decidable.rec_on _
(suppose y β€ x, locally_sorted.step this Hlsorted)
(suppose Hyx : Β¬y β€ x, begin
cases xs with x' xs,
{ exact locally_sorted.step (le_of_not_ge Hyx) !locally_sorted.base },
{ cases Hlsorted with _ _ _ _ Hxx' Hlsorted',
rewrite [βite, βinsert_at],
revert ih, rewrite [βinsert_pos],
exact decidable.rec_on _
(suppose y β€ x', assume ih, locally_sorted.step (le_of_not_ge Hyx) (locally_sorted.step this Hlsorted'))
(suppose Β¬y β€ x', assume ih, locally_sorted.step Hxx' (ih Hlsorted'))
}
end)
}
end
theorem sorted_dropn_of_sorted : Ξ (n : β), sorted le (dropn n xs) :=
begin
induction Hsorted using sorted.rec with x xs Hhd_rel Hsorted ih,
{ intro n, rewrite dropn_nil, apply sorted.base },
{ intro n, cases n,
{ apply sorted.step Hhd_rel Hsorted },
{ unfold dropn, apply ih }
}
end
omit Hsorted
theorem hd_rel_of_prefix_of_hd_rel {x : A} {ys : list A} (Hprefix : prefixeq xs ys) (Hhd_rel : hd_rel le x ys) :
hd_rel le x xs :=
begin
cases Hhd_rel with y ys' Hxy,
{ cases Hprefix, apply hd_rel.base },
{ cases Hprefix,
{ apply hd_rel.base },
{ exact hd_rel.step _ Hxy }
}
end
theorem sorted_of_prefix_of_sorted {ys : list A} (Hprefix : prefixeq xs ys) (Hsorted : sorted le ys) :
sorted le xs :=
begin
revert xs Hprefix,
induction Hsorted using sorted.rec with y ys Hhd_rel Hsorted ih,
all_goals intro xs Hprefix,
{ cases Hprefix, apply sorted.base },
{ cases Hprefix with _ _ xs' _ Hprefix',
{ apply sorted.base },
{ apply sorted.step (!hd_rel_of_prefix_of_hd_rel Hprefix' Hhd_rel) (ih xs' Hprefix') }
}
end
end
end
end sorted
end list
namespace partial
infixr ` β `:25 := Ξ»A B, A β option B
section
parameters {A B : Type} {R : B β B β Prop}
parameters (f : A β B)
definition R' [unfold 3] : option B β option B β Prop
| (some y) (some x) := R y x
| _ _ := false
private definition R'.wf (H : well_founded R) : well_founded R' :=
begin
apply well_founded.intro,
intro x, cases x with x',
{ apply acc.intro,
intro y,
cases y; repeat contradiction },
{ induction (well_founded.apply H x') with x' _ ih,
apply acc.intro,
intro y HR', cases y with y',
{ contradiction },
{ apply ih _ HR' }
}
end
parameter (R)
definition inv_image (f : A β B) : A β A β Prop := inv_image R' f
parameter {R}
lemma inv_image.wf (H : well_founded R) : well_founded (inv_image f) :=
inv_image.wf f (R'.wf H)
end
end partial
namespace sum
definition inl_opt [unfold 3] {A B : Type} : A + B β option A
| (inl a) := some a
| (inr _) := none
definition inr_opt [unfold 3] {A B : Type} : A + B β option B
| (inl _) := none
| (inr b) := some b
end sum
-- generalized nat.le_lt_antisymm
theorem le_lt_antisymm {T : Type} [order_pair T] {n m : T} (H1 : n β€ m) (H2 : m < n) : false :=
!lt.irrefl (lt_of_le_of_lt H1 H2)
namespace classical
theorem dite_else_false {c : Prop} {t : c β Prop} (Hdite : if H : c then t H else false) : c :=
if H : c then H
else false.elim (dif_neg H βΈ Hdite)
end classical
attribute dite [unfold 2]
attribute ite [unfold 2]
-- H as implicit instead of instance implicit for rewriting
theorem if_pos' {c : Prop} {H : decidable c} (Hc : c) {A : Type} {t e : A} : (ite c t e) = t :=
decidable.rec
(Ξ» Hc : c, eq.refl (@ite c (decidable.inl Hc) A t e))
(Ξ» Hnc : Β¬c, absurd Hc Hnc)
H
theorem if_neg' {c : Prop} {H : decidable c} (Hnc : Β¬c) {A : Type} {t e : A} : (ite c t e) = e :=
decidable.rec
(Ξ» Hc : c, absurd Hc Hnc)
(Ξ» Hnc : Β¬c, eq.refl (@ite c (decidable.inr Hnc) A t e))
H
|
d76dd5dff1401702443ca8a3fc1ee5c92fc06ce6 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/data/finset/sort.lean | 0e3d62639b3d41c6a263dc9a111d7373c052004f | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 10,475 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
-/
import data.finset.lattice
import data.multiset.sort
/-!
# Construct a sorted list from a finset.
-/
namespace finset
open multiset nat
variables {Ξ± Ξ² : Type*}
/-! ### sort -/
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 _
@[simp] theorem length_sort {s : finset Ξ±} : (sort r s).length = s.card :=
multiset.length_sort _
end sort
section sort_linear_order
variables [decidable_linear_order Ξ±]
theorem sort_sorted_lt (s : finset Ξ±) :
list.sorted (<) (sort (β€) s) :=
(sort_sorted _ _).impβ (@lt_of_le_of_ne _ _) (sort_nodup _ _)
lemma sorted_zero_eq_min'_aux (s : finset Ξ±) (h : 0 < (s.sort (β€)).length) (H : s.nonempty) :
(s.sort (β€)).nth_le 0 h = s.min' H :=
begin
let l := s.sort (β€),
apply le_antisymm,
{ have : s.min' H β l := (finset.mem_sort (β€)).mpr (s.min'_mem H),
obtain β¨i, i_lt, hiβ© : β i (hi : i < l.length), l.nth_le i hi = s.min' H :=
list.mem_iff_nth_le.1 this,
rw β hi,
exact list.nth_le_of_sorted_of_le (s.sort_sorted (β€)) (nat.zero_le i) },
{ have : l.nth_le 0 h β s := (finset.mem_sort (β€)).1 (list.nth_le_mem l 0 h),
exact s.min'_le _ this }
end
lemma sorted_zero_eq_min' {s : finset Ξ±} {h : 0 < (s.sort (β€)).length} :
(s.sort (β€)).nth_le 0 h = s.min' (card_pos.1 $ by rwa length_sort at h) :=
sorted_zero_eq_min'_aux _ _ _
lemma min'_eq_sorted_zero {s : finset Ξ±} {h : s.nonempty} :
s.min' h = (s.sort (β€)).nth_le 0 (by { rw length_sort, exact card_pos.2 h }) :=
(sorted_zero_eq_min'_aux _ _ _).symm
lemma sorted_last_eq_max'_aux (s : finset Ξ±) (h : (s.sort (β€)).length - 1 < (s.sort (β€)).length)
(H : s.nonempty) : (s.sort (β€)).nth_le ((s.sort (β€)).length - 1) h = s.max' H :=
begin
let l := s.sort (β€),
apply le_antisymm,
{ have : l.nth_le ((s.sort (β€)).length - 1) h β s :=
(finset.mem_sort (β€)).1 (list.nth_le_mem l _ h),
exact s.le_max' _ this },
{ have : s.max' H β l := (finset.mem_sort (β€)).mpr (s.max'_mem H),
obtain β¨i, i_lt, hiβ© : β i (hi : i < l.length), l.nth_le i hi = s.max' H :=
list.mem_iff_nth_le.1 this,
rw β hi,
have : i β€ l.length - 1 := nat.le_pred_of_lt i_lt,
exact list.nth_le_of_sorted_of_le (s.sort_sorted (β€)) (nat.le_pred_of_lt i_lt) },
end
lemma sorted_last_eq_max' {s : finset Ξ±} {h : (s.sort (β€)).length - 1 < (s.sort (β€)).length} :
(s.sort (β€)).nth_le ((s.sort (β€)).length - 1) h =
s.max' (by { rw length_sort at h, exact card_pos.1 (lt_of_le_of_lt bot_le h) }) :=
sorted_last_eq_max'_aux _ _ _
lemma max'_eq_sorted_last {s : finset Ξ±} {h : s.nonempty} :
s.max' h = (s.sort (β€)).nth_le ((s.sort (β€)).length - 1)
(by simpa using sub_lt (card_pos.mpr h) zero_lt_one) :=
(sorted_last_eq_max'_aux _ _ _).symm
/-- Given a finset `s` of cardinal `k` in a linear order `Ξ±`, the map `mono_of_fin s h`
is the increasing bijection between `fin k` and `s` as an `Ξ±`-valued map. Here, `h` is a proof that
the cardinality of `s` is `k`. We use this instead of a map `fin s.card β Ξ±` to avoid
casting issues in further uses of this function. -/
def mono_of_fin (s : finset Ξ±) {k : β} (h : s.card = k) (i : fin k) : Ξ± :=
have A : (i : β) < (s.sort (β€)).length, by simpa [h] using i.2,
(s.sort (β€)).nth_le i A
lemma mono_of_fin_strict_mono (s : finset Ξ±) {k : β} (h : s.card = k) :
strict_mono (s.mono_of_fin h) :=
begin
assume i j hij,
exact list.pairwise_iff_nth_le.1 s.sort_sorted_lt _ _ _ hij
end
lemma mono_of_fin_bij_on (s : finset Ξ±) {k : β} (h : s.card = k) :
set.bij_on (s.mono_of_fin h) set.univ βs :=
begin
have A : β j, j β s β j β (s.sort (β€)) := Ξ» j, by simp,
apply set.bij_on.mk,
{ assume i hi,
simp only [mono_of_fin, set.mem_preimage, mem_coe, list.nth_le, A],
exact list.nth_le_mem _ _ _ },
{ exact ((mono_of_fin_strict_mono s h).injective).inj_on _ },
{ assume x hx,
simp only [mem_coe, A] at hx,
obtain β¨i, il, hiβ© : β (i : β) (h : i < (s.sort (β€)).length), (s.sort (β€)).nth_le i h = x :=
list.nth_le_of_mem hx,
simp [h] at il,
exact β¨β¨i, ilβ©, set.mem_univ _, hiβ© }
end
lemma mono_of_fin_injective (s : finset Ξ±) {k : β} (h : s.card = k) :
function.injective (s.mono_of_fin h) :=
set.injective_iff_inj_on_univ.mpr (s.mono_of_fin_bij_on h).inj_on
/-- The bijection `mono_of_fin s h` sends `0` to the minimum of `s`. -/
lemma mono_of_fin_zero {s : finset Ξ±} {k : β} (h : s.card = k) (hz : 0 < k) :
mono_of_fin s h β¨0, hzβ© = s.min' (card_pos.mp (h.symm βΈ hz)) :=
begin
apply le_antisymm,
{ have : min' s _ β s := min'_mem s _,
rcases (mono_of_fin_bij_on s h).surj_on this with β¨a, _, haβ©,
rw β ha,
apply (mono_of_fin_strict_mono s h).monotone,
exact zero_le a.val },
{ have : mono_of_fin s h β¨0, hzβ© β s := (mono_of_fin_bij_on s h).maps_to (set.mem_univ _),
exact min'_le s _ this }
end
/-- The bijection `mono_of_fin s h` sends `k-1` to the maximum of `s`. -/
lemma mono_of_fin_last {s : finset Ξ±} {k : β} (h : s.card = k) (hz : 0 < k) :
mono_of_fin s h β¨k-1, buffer.lt_aux_2 hzβ© = s.max' (card_pos.mp (h.symm βΈ hz)) :=
begin
have h'' : k - 1 < k := buffer.lt_aux_2 hz,
apply le_antisymm,
{ have : mono_of_fin s h β¨k-1, h''β© β s := (mono_of_fin_bij_on s h).maps_to (set.mem_univ _),
exact le_max' s _ this },
{ have : max' s _ β s := max'_mem s _,
rcases (mono_of_fin_bij_on s h).surj_on this with β¨a, _, haβ©,
rw β ha,
apply (mono_of_fin_strict_mono s h).monotone,
exact le_pred_of_lt a.2},
end
/-- `mono_of_fin {a} h` sends any argument to `a`. -/
@[simp] lemma mono_of_fin_singleton (a : Ξ±) (i : fin 1) {h} :
mono_of_fin {a} h i = a :=
by rw [subsingleton.elim i β¨0, zero_lt_oneβ©,
mono_of_fin_zero h zero_lt_one, min'_singleton]
/-- The range of `mono_of_fin`. -/
@[simp] lemma range_mono_of_fin {s : finset Ξ±} {k : β} (h : s.card = k) :
set.range (s.mono_of_fin h) = βs :=
begin
rw βset.image_univ,
exact (mono_of_fin_bij_on s h).image_eq
end
/-- Any increasing bijection between `fin k` and a finset of cardinality `k` has to coincide with
the increasing bijection `mono_of_fin s h`. For a statement assuming only that `f` maps `univ` to
`s`, see `mono_of_fin_unique'`.-/
lemma mono_of_fin_unique {s : finset Ξ±} {k : β} (h : s.card = k) {f : fin k β Ξ±}
(hbij : set.bij_on f set.univ βs) (hmono : strict_mono f) : f = s.mono_of_fin h :=
begin
ext β¨i, hiβ©,
induction i using nat.strong_induction_on with i IH,
rcases lt_trichotomy (f β¨i, hiβ©) (mono_of_fin s h β¨i, hiβ©) with H|H|H,
{ have A : f β¨i, hiβ© β βs := hbij.maps_to (set.mem_univ _),
rcases (mono_of_fin_bij_on s h).surj_on A with β¨j, _, hjβ©,
rw β hj at H,
have ji : j < β¨i, hiβ© := (mono_of_fin_strict_mono s h).lt_iff_lt.1 H,
have : f j = mono_of_fin s h j,
by { convert IH j ji (lt_trans ji hi), rw [fin.ext_iff, fin.coe_mk] },
rw β this at hj,
exact (ne_of_lt (hmono ji) hj).elim },
{ exact H },
{ have A : mono_of_fin s h β¨i, hiβ© β βs := (mono_of_fin_bij_on s h).maps_to (set.mem_univ _),
rcases hbij.surj_on A with β¨j, _, hjβ©,
rw β hj at H,
have ji : j < β¨i, hiβ© := hmono.lt_iff_lt.1 H,
have : f j = mono_of_fin s h j,
by { convert IH j ji (lt_trans ji hi), rw [fin.ext_iff, fin.coe_mk] },
rw this at hj,
exact (ne_of_lt (mono_of_fin_strict_mono s h ji) hj).elim }
end
/-- Any increasing map between `fin k` and a finset of cardinality `k` has to coincide with
the increasing bijection `mono_of_fin s h`. -/
lemma mono_of_fin_unique' {s : finset Ξ±} {k : β} (h : s.card = k)
{f : fin k β Ξ±} (fmap : set.maps_to f set.univ βs) (hmono : strict_mono f) :
f = s.mono_of_fin h :=
begin
have finj : set.inj_on f set.univ := hmono.injective.inj_on _,
apply mono_of_fin_unique h (set.bij_on.mk fmap finj (Ξ» y hy, _)) hmono,
simp only [set.image_univ, set.mem_range],
rcases surj_on_of_inj_on_of_card_le (Ξ» i (hi : i β finset.fin_range k), f i)
(Ξ» i hi, fmap (set.mem_univ i)) (Ξ» i j hi hj hij, finj (set.mem_univ i) (set.mem_univ j) hij)
(by simp [h]) y hy with β¨x, _, hxβ©,
exact β¨x, hx.symmβ©
end
/-- Two parametrizations `mono_of_fin` of the same set take the same value on `i` and `j` if and
only if `i = j`. Since they can be defined on a priori not defeq types `fin k` and `fin l` (although
necessarily `k = l`), the conclusion is rather written `(i : β) = (j : β)`. -/
@[simp] lemma mono_of_fin_eq_mono_of_fin_iff
{k l : β} {s : finset Ξ±} {i : fin k} {j : fin l} {h : s.card = k} {h' : s.card = l} :
s.mono_of_fin h i = s.mono_of_fin h' j β (i : β) = (j : β) :=
begin
have A : k = l, by rw [β h', β h],
have : s.mono_of_fin h = (s.mono_of_fin h') β (Ξ» j : (fin k), β¨j, A βΈ j.is_ltβ©) := rfl,
rw [this, function.comp_app, (s.mono_of_fin_injective h').eq_iff, fin.ext_iff, fin.coe_mk]
end
/-- Given a finset `s` of cardinal `k` in a linear order `Ξ±`, the equiv `mono_equiv_of_fin s h`
is the increasing bijection between `fin k` and `s` as an `s`-valued map. Here, `h` is a proof that
the cardinality of `s` is `k`. We use this instead of a map `fin s.card β Ξ±` to avoid
casting issues in further uses of this function. -/
noncomputable def mono_equiv_of_fin (s : finset Ξ±) {k : β} (h : s.card = k) :
fin k β {x // x β s} :=
(s.mono_of_fin_bij_on h).equiv _
end sort_linear_order
instance [has_repr Ξ±] : has_repr (finset Ξ±) := β¨Ξ» s, repr s.1β©
end finset
|
143d356141f12480a96dbbc1f3d1fb5e25cd18d6 | ac1c2a2f522b0fdf854095ba00f882ca849669e7 | /library/init/data/to_string.lean | 4e8ae12c6303e68389ac765b34bb59a37c5b949a | [
"Apache-2.0"
] | permissive | abliss/lean | b8b336abc8d50dbb0726dcff9dd16793c23bfbe1 | fb24cc99573c153f97a1951ee94bbbdda300b6be | refs/heads/master | 1,611,536,584,520 | 1,497,811,981,000 | 1,497,811,981,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,670 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
-/
prelude
import init.data.string.basic init.data.bool.basic init.data.subtype.basic
import init.data.unsigned.basic init.data.prod init.data.sum.basic init.data.nat.div
open sum subtype nat
universes u v
class has_to_string (Ξ± : Type u) :=
(to_string : Ξ± β string)
def to_string {Ξ± : Type u} [has_to_string Ξ±] : Ξ± β string :=
has_to_string.to_string
instance : has_to_string bool :=
β¨Ξ» b, cond b "tt" "ff"β©
instance {p : Prop} : has_to_string (decidable p) :=
-- Remark: type class inference will not consider local instance `b` in the new elaborator
β¨Ξ» b : decidable p, @ite p b _ "tt" "ff"β©
protected def list.to_string_aux {Ξ± : Type u} [has_to_string Ξ±] : bool β list Ξ± β string
| b [] := ""
| tt (x::xs) := to_string x ++ list.to_string_aux ff xs
| ff (x::xs) := ", " ++ to_string x ++ list.to_string_aux ff xs
protected def list.to_string {Ξ± : Type u} [has_to_string Ξ±] : list Ξ± β string
| [] := "[]"
| (x::xs) := "[" ++ list.to_string_aux tt (x::xs) ++ "]"
instance {Ξ± : Type u} [has_to_string Ξ±] : has_to_string (list Ξ±) :=
β¨list.to_stringβ©
instance : has_to_string unit :=
β¨Ξ» u, "star"β©
instance {Ξ± : Type u} [has_to_string Ξ±] : has_to_string (option Ξ±) :=
β¨Ξ» o, match o with | none := "none" | (some a) := "(some " ++ to_string a ++ ")" endβ©
instance {Ξ± : Type u} {Ξ² : Type v} [has_to_string Ξ±] [has_to_string Ξ²] : has_to_string (Ξ± β Ξ²) :=
β¨Ξ» s, match s with | (inl a) := "(inl " ++ to_string a ++ ")" | (inr b) := "(inr " ++ to_string b ++ ")" endβ©
instance {Ξ± : Type u} {Ξ² : Type v} [has_to_string Ξ±] [has_to_string Ξ²] : has_to_string (Ξ± Γ Ξ²) :=
β¨Ξ» β¨a, bβ©, "(" ++ to_string a ++ ", " ++ to_string b ++ ")"β©
instance {Ξ± : Type u} {Ξ² : Ξ± β Type v} [has_to_string Ξ±] [s : β x, has_to_string (Ξ² x)] : has_to_string (sigma Ξ²) :=
β¨Ξ» β¨a, bβ©, "β¨" ++ to_string a ++ ", " ++ to_string b ++ "β©"β©
instance {Ξ± : Type u} {p : Ξ± β Prop} [has_to_string Ξ±] : has_to_string (subtype p) :=
β¨Ξ» s, to_string (val s)β©
/- Remark: the code generator replaces this definition with one that display natural numbers in decimal notation -/
protected def nat.to_string : nat β string
| 0 := "zero"
| (succ a) := "(succ " ++ nat.to_string a ++ ")"
instance : has_to_string nat :=
β¨nat.to_stringβ©
def hex_digit_to_string (n : nat) : string :=
if n β€ 9 then to_string n
else if n = 10 then "a"
else if n = 11 then "b"
else if n = 12 then "c"
else if n = 13 then "d"
else if n = 14 then "e"
else "f"
def char_to_hex (c : char) : string :=
let n := char.to_nat c,
d2 := n / 16,
d1 := n % 16
in hex_digit_to_string d2 ++ hex_digit_to_string d1
def char.quote_core (c : char) : string :=
if c = '\n' then "\\n"
else if c = '\t' then "\\t"
else if c = '\\' then "\\\\"
else if c = '\"' then "\\\""
else if char.to_nat c <= 31 then "\\x" ++ char_to_hex c
else string.singleton c
instance : has_to_string char :=
β¨Ξ» c, "'" ++ char.quote_core c ++ "'"β©
def string.quote_aux : list char β string
| [] := ""
| (x::xs) := char.quote_core x ++ string.quote_aux xs
def string.quote (s : string) : string :=
if s.is_empty = tt then "\"\""
else "\"" ++ string.quote_aux s.to_list ++ "\""
instance : has_to_string string :=
β¨string.quoteβ©
instance (n : nat) : has_to_string (fin n) :=
β¨Ξ» f, to_string (fin.val f)β©
instance : has_to_string unsigned :=
β¨Ξ» n, to_string (fin.val n)β©
def char.to_string (c : char) : string :=
to_string c
|
58e63007a6d0fc0316ae0602350ee252685ea2b2 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/algebra/monoid.lean | ee3b1845b415330c461261e9fd6c02007a0bca18 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,071 | 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.topology.continuous_on
import Mathlib.group_theory.submonoid.basic
import Mathlib.algebra.group.prod
import Mathlib.algebra.pointwise
import Mathlib.PostPort
universes u_5 l u_3 u_1 u_4 u_2
namespace Mathlib
/-!
# Theory of topological monoids
In this file we define mixin classes `has_continuous_mul` and `has_continuous_add`. While in many
applications the underlying type is a monoid (multiplicative or additive), we do not require this in
the definitions.
-/
/-- Basic hypothesis to talk about a topological additive monoid or a topological additive
semigroup. A topological additive monoid over `Ξ±`, for example, is obtained by requiring both the
instances `add_monoid Ξ±` and `has_continuous_add Ξ±`. -/
class has_continuous_add (M : Type u_5) [topological_space M] [Add M]
where
continuous_add : continuous fun (p : M Γ M) => prod.fst p + prod.snd p
/-- Basic hypothesis to talk about a topological monoid or a topological semigroup.
A topological monoid over `Ξ±`, for example, is obtained by requiring both the instances `monoid Ξ±`
and `has_continuous_mul Ξ±`. -/
class has_continuous_mul (M : Type u_5) [topological_space M] [Mul M]
where
continuous_mul : continuous fun (p : M Γ M) => prod.fst p * prod.snd p
theorem continuous_add {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] : continuous fun (p : M Γ M) => prod.fst p + prod.snd p :=
has_continuous_add.continuous_add
theorem continuous.mul {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Mul M] [has_continuous_mul M] [topological_space Ξ±] {f : Ξ± β M} {g : Ξ± β M} (hf : continuous f) (hg : continuous g) : continuous fun (x : Ξ±) => f x * g x :=
continuous.comp continuous_mul (continuous.prod_mk hf hg)
-- should `to_additive` be doing this?
theorem continuous_add_left {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] (a : M) : continuous fun (b : M) => a + b :=
continuous.add continuous_const continuous_id
theorem continuous_add_right {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] (a : M) : continuous fun (b : M) => b + a :=
continuous.add continuous_id continuous_const
theorem continuous_on.add {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] [topological_space Ξ±] {f : Ξ± β M} {g : Ξ± β M} {s : set Ξ±} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (fun (x : Ξ±) => f x + g x) s :=
continuous.comp_continuous_on continuous_add (continuous_on.prod hf hg)
theorem tendsto_add {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] {a : M} {b : M} : filter.tendsto (fun (p : M Γ M) => prod.fst p + prod.snd p) (nhds (a, b)) (nhds (a + b)) :=
iff.mp continuous_iff_continuous_at has_continuous_add.continuous_add (a, b)
theorem filter.tendsto.add {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] {f : Ξ± β M} {g : Ξ± β M} {x : filter Ξ±} {a : M} {b : M} (hf : filter.tendsto f x (nhds a)) (hg : filter.tendsto g x (nhds b)) : filter.tendsto (fun (x : Ξ±) => f x + g x) x (nhds (a + b)) :=
filter.tendsto.comp tendsto_add (filter.tendsto.prod_mk_nhds hf hg)
theorem tendsto.const_mul {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Mul M] [has_continuous_mul M] (b : M) {c : M} {f : Ξ± β M} {l : filter Ξ±} (h : filter.tendsto (fun (k : Ξ±) => f k) l (nhds c)) : filter.tendsto (fun (k : Ξ±) => b * f k) l (nhds (b * c)) :=
filter.tendsto.mul tendsto_const_nhds h
theorem tendsto.add_const {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] (b : M) {c : M} {f : Ξ± β M} {l : filter Ξ±} (h : filter.tendsto (fun (k : Ξ±) => f k) l (nhds c)) : filter.tendsto (fun (k : Ξ±) => f k + b) l (nhds (c + b)) :=
filter.tendsto.add h tendsto_const_nhds
theorem continuous_at.add {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] [topological_space Ξ±] {f : Ξ± β M} {g : Ξ± β M} {x : Ξ±} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (fun (x : Ξ±) => f x + g x) x :=
filter.tendsto.add hf hg
theorem continuous_within_at.add {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [Add M] [has_continuous_add M] [topological_space Ξ±] {f : Ξ± β M} {g : Ξ± β M} {s : set Ξ±} {x : Ξ±} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (fun (x : Ξ±) => f x + g x) s x :=
filter.tendsto.add hf hg
protected instance prod.has_continuous_mul {M : Type u_3} {N : Type u_4} [topological_space M] [Mul M] [has_continuous_mul M] [topological_space N] [Mul N] [has_continuous_mul N] : has_continuous_mul (M Γ N) :=
has_continuous_mul.mk
(continuous.prod_mk
(continuous.mul (continuous.comp continuous_fst continuous_fst) (continuous.comp continuous_fst continuous_snd))
(continuous.mul (continuous.comp continuous_snd continuous_fst) (continuous.comp continuous_snd continuous_snd)))
protected instance has_continuous_mul_of_discrete_topology {N : Type u_4} [topological_space N] [Mul N] [discrete_topology N] : has_continuous_mul N :=
has_continuous_mul.mk continuous_of_discrete_topology
theorem has_continuous_mul.of_nhds_one {M : Type (max u_1 u_2)} [monoid M] [topological_space M] (hmul : filter.tendsto (function.uncurry Mul.mul) (filter.prod (nhds 1) (nhds 1)) (nhds 1)) (hleft : β (xβ : M), nhds xβ = filter.map (fun (x : M) => xβ * x) (nhds 1)) (hright : β (xβ : M), nhds xβ = filter.map (fun (x : M) => x * xβ) (nhds 1)) : has_continuous_mul M := sorry
theorem has_continuous_mul_of_comm_of_nhds_one (M : Type (max u_1 u_2)) [comm_monoid M] [topological_space M] (hmul : filter.tendsto (function.uncurry Mul.mul) (filter.prod (nhds 1) (nhds 1)) (nhds 1)) (hleft : β (xβ : M), nhds xβ = filter.map (fun (x : M) => xβ * x) (nhds 1)) : has_continuous_mul M := sorry
theorem add_submonoid.top_closure_add_self_subset {M : Type u_3} [topological_space M] [add_monoid M] [has_continuous_add M] (s : add_submonoid M) : closure βs + closure βs β closure βs := sorry
theorem submonoid.top_closure_mul_self_eq {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] (s : submonoid M) : closure βs * closure βs = closure βs := sorry
/-- The (topological-space) closure of a submonoid of a space `M` with `has_continuous_mul` is
itself a submonoid. -/
def add_submonoid.topological_closure {M : Type u_3} [topological_space M] [add_monoid M] [has_continuous_add M] (s : add_submonoid M) : add_submonoid M :=
add_submonoid.mk (closure βs) sorry sorry
theorem submonoid.submonoid_topological_closure {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] (s : submonoid M) : s β€ submonoid.topological_closure s :=
subset_closure
theorem submonoid.is_closed_topological_closure {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] (s : submonoid M) : is_closed β(submonoid.topological_closure s) := sorry
theorem submonoid.topological_closure_minimal {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] (s : submonoid M) {t : submonoid M} (h : s β€ t) (ht : is_closed βt) : submonoid.topological_closure s β€ t :=
closure_minimal h ht
theorem exists_open_nhds_zero_half {M : Type u_3} [topological_space M] [add_monoid M] [has_continuous_add M] {s : set M} (hs : s β nhds 0) : β (V : set M), is_open V β§ 0 β V β§ β (v : M), v β V β β (w : M), w β V β v + w β s := sorry
theorem exists_nhds_zero_half {M : Type u_3} [topological_space M] [add_monoid M] [has_continuous_add M] {s : set M} (hs : s β nhds 0) : β (V : set M), β (H : V β nhds 0), β (v : M), v β V β β (w : M), w β V β v + w β s := sorry
theorem exists_nhds_one_split4 {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] {u : set M} (hu : u β nhds 1) : β (V : set M), β (H : V β nhds 1), β {v w s t : M}, v β V β w β V β s β V β t β V β v * w * s * t β u := sorry
/-- Given a neighborhood `U` of `1` there is an open neighborhood `V` of `1`
such that `VV β U`. -/
theorem exists_open_nhds_one_mul_subset {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] {U : set M} (hU : U β nhds 1) : β (V : set M), is_open V β§ 1 β V β§ V * V β U := sorry
theorem tendsto_list_sum {Ξ± : Type u_1} {Ξ² : Type u_2} {M : Type u_3} [topological_space M] [add_monoid M] [has_continuous_add M] {f : Ξ² β Ξ± β M} {x : filter Ξ±} {a : Ξ² β M} (l : List Ξ²) : (β (c : Ξ²), c β l β filter.tendsto (f c) x (nhds (a c))) β
filter.tendsto (fun (b : Ξ±) => list.sum (list.map (fun (c : Ξ²) => f c b) l)) x (nhds (list.sum (list.map a l))) := sorry
theorem continuous_list_sum {Ξ± : Type u_1} {Ξ² : Type u_2} {M : Type u_3} [topological_space M] [add_monoid M] [has_continuous_add M] [topological_space Ξ±] {f : Ξ² β Ξ± β M} (l : List Ξ²) (h : β (c : Ξ²), c β l β continuous (f c)) : continuous fun (a : Ξ±) => list.sum (list.map (fun (c : Ξ²) => f c a) l) :=
iff.mpr continuous_iff_continuous_at
fun (x : Ξ±) => tendsto_list_sum l fun (c : Ξ²) (hc : c β l) => iff.mp continuous_iff_continuous_at (h c hc) x
-- @[to_additive continuous_smul]
theorem continuous_pow {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] (n : β) : continuous fun (a : M) => a ^ n := sorry
theorem continuous.pow {Ξ± : Type u_1} {M : Type u_3} [topological_space M] [monoid M] [has_continuous_mul M] {f : Ξ± β M} [topological_space Ξ±] (h : continuous f) (n : β) : continuous fun (b : Ξ±) => f b ^ n :=
continuous.comp (continuous_pow n) h
theorem submonoid.mem_nhds_one {M : Type u_3} [topological_space M] [comm_monoid M] (S : submonoid M) (oS : is_open βS) : βS β nhds 1 :=
mem_nhds_sets oS (submonoid.one_mem S)
theorem tendsto_multiset_prod {Ξ± : Type u_1} {Ξ² : Type u_2} {M : Type u_3} [topological_space M] [comm_monoid M] [has_continuous_mul M] {f : Ξ² β Ξ± β M} {x : filter Ξ±} {a : Ξ² β M} (s : multiset Ξ²) : (β (c : Ξ²), c β s β filter.tendsto (f c) x (nhds (a c))) β
filter.tendsto (fun (b : Ξ±) => multiset.prod (multiset.map (fun (c : Ξ²) => f c b) s)) x
(nhds (multiset.prod (multiset.map a s))) := sorry
theorem tendsto_finset_sum {Ξ± : Type u_1} {Ξ² : Type u_2} {M : Type u_3} [topological_space M] [add_comm_monoid M] [has_continuous_add M] {f : Ξ² β Ξ± β M} {x : filter Ξ±} {a : Ξ² β M} (s : finset Ξ²) : (β (c : Ξ²), c β s β filter.tendsto (f c) x (nhds (a c))) β
filter.tendsto (fun (b : Ξ±) => finset.sum s fun (c : Ξ²) => f c b) x (nhds (finset.sum s fun (c : Ξ²) => a c)) :=
tendsto_multiset_sum (finset.val s)
theorem continuous_multiset_prod {Ξ± : Type u_1} {Ξ² : Type u_2} {M : Type u_3} [topological_space M] [comm_monoid M] [has_continuous_mul M] [topological_space Ξ±] {f : Ξ² β Ξ± β M} (s : multiset Ξ²) : (β (c : Ξ²), c β s β continuous (f c)) β continuous fun (a : Ξ±) => multiset.prod (multiset.map (fun (c : Ξ²) => f c a) s) := sorry
theorem continuous_finset_prod {Ξ± : Type u_1} {Ξ² : Type u_2} {M : Type u_3} [topological_space M] [comm_monoid M] [has_continuous_mul M] [topological_space Ξ±] {f : Ξ² β Ξ± β M} (s : finset Ξ²) : (β (c : Ξ²), c β s β continuous (f c)) β continuous fun (a : Ξ±) => finset.prod s fun (c : Ξ²) => f c a :=
continuous_multiset_prod (finset.val s)
-- should `to_additive` be doing this?
protected instance additive.has_continuous_add {M : Type u_1} [h : topological_space M] [Mul M] [has_continuous_mul M] : has_continuous_add (additive M) :=
has_continuous_add.mk continuous_mul
protected instance multiplicative.has_continuous_mul {M : Type u_1} [h : topological_space M] [Add M] [has_continuous_add M] : has_continuous_mul (multiplicative M) :=
has_continuous_mul.mk continuous_add
|
0c7a995643d8ec49001f49794af1af54ee484c06 | 80cc5bf14c8ea85ff340d1d747a127dcadeb966f | /src/measure_theory/lebesgue_measure.lean | fb7863c2d6bdeeef31c93f92123a6ac949118ce0 | [
"Apache-2.0"
] | permissive | lacker/mathlib | f2439c743c4f8eb413ec589430c82d0f73b2d539 | ddf7563ac69d42cfa4a1bfe41db1fed521bd795f | refs/heads/master | 1,671,948,326,773 | 1,601,479,268,000 | 1,601,479,268,000 | 298,686,743 | 0 | 0 | Apache-2.0 | 1,601,070,794,000 | 1,601,070,794,000 | null | UTF-8 | Lean | false | false | 13,724 | lean | /-
Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes HΓΆlzl
-/
import measure_theory.measure_space
import measure_theory.borel_space
/-!
# Lebesgue measure on the real line
-/
noncomputable theory
open classical set filter
open ennreal (of_real)
open_locale big_operators
namespace measure_theory
/-- Length of an interval. This is the largest monotonic function which correctly
measures all intervals. -/
def lebesgue_length (s : set β) : ennreal := β¨
a b (h : s β Ico a b), of_real (b - a)
@[simp] lemma lebesgue_length_empty : lebesgue_length β
= 0 :=
le_zero_iff_eq.1 $ infi_le_of_le 0 $ infi_le_of_le 0 $ by simp
@[simp] lemma lebesgue_length_Ico (a b : β) :
lebesgue_length (Ico a b) = of_real (b - a) :=
begin
refine le_antisymm (infi_le_of_le a $ binfi_le b (subset.refl _))
(le_infi $ Ξ» a', le_infi $ Ξ» b', le_infi $ Ξ» h, ennreal.coe_le_coe.2 _),
cases le_or_lt b a with ab ab,
{ rw nnreal.of_real_of_nonpos (sub_nonpos.2 ab), apply zero_le },
cases (Ico_subset_Ico_iff ab).1 h with hβ hβ,
exact nnreal.of_real_le_of_real (sub_le_sub hβ hβ)
end
lemma lebesgue_length_mono {sβ sβ : set β} (h : sβ β sβ) :
lebesgue_length sβ β€ lebesgue_length sβ :=
infi_le_infi $ Ξ» a, infi_le_infi $ Ξ» b, infi_le_infi2 $ Ξ» h', β¨subset.trans h h', le_refl _β©
lemma lebesgue_length_eq_infi_Ioo (s) :
lebesgue_length s = β¨
a b (h : s β Ioo a b), of_real (b - a) :=
begin
refine le_antisymm
(infi_le_infi $ Ξ» a, infi_le_infi $ Ξ» b, infi_le_infi2 $ Ξ» h,
β¨subset.trans h Ioo_subset_Ico_self, le_refl _β©) _,
refine le_infi (Ξ» a, le_infi $ Ξ» b, le_infi $ Ξ» h, _),
refine ennreal.le_of_forall_epsilon_le (Ξ» Ξ΅ Ξ΅0 _, _),
refine infi_le_of_le (a - Ξ΅) (infi_le_of_le b $ infi_le_of_le
(subset.trans h $ Ico_subset_Ioo_left $ (sub_lt_self_iff _).2 Ξ΅0) _),
rw β sub_add,
refine le_trans ennreal.of_real_add_le (add_le_add_left _ _),
simp only [ennreal.of_real_coe_nnreal, le_refl]
end
@[simp] lemma lebesgue_length_Ioo (a b : β) :
lebesgue_length (Ioo a b) = of_real (b - a) :=
begin
rw β lebesgue_length_Ico,
refine le_antisymm (lebesgue_length_mono Ioo_subset_Ico_self) _,
rw lebesgue_length_eq_infi_Ioo (Ioo a b),
refine (le_infi $ Ξ» a', le_infi $ Ξ» b', le_infi $ Ξ» h, _),
cases le_or_lt b a with ab ab, {simp [ab]},
cases (Ioo_subset_Ioo_iff ab).1 h with hβ hβ,
rw [lebesgue_length_Ico],
exact ennreal.of_real_le_of_real (sub_le_sub hβ hβ)
end
lemma lebesgue_length_eq_infi_Icc (s) :
lebesgue_length s = β¨
a b (h : s β Icc a b), of_real (b - a) :=
begin
refine le_antisymm _
(infi_le_infi $ Ξ» a, infi_le_infi $ Ξ» b, infi_le_infi2 $ Ξ» h,
β¨subset.trans h Ico_subset_Icc_self, le_refl _β©),
refine le_infi (Ξ» a, le_infi $ Ξ» b, le_infi $ Ξ» h, _),
refine ennreal.le_of_forall_epsilon_le (Ξ» Ξ΅ Ξ΅0 _, _),
refine infi_le_of_le a (infi_le_of_le (b + Ξ΅) $ infi_le_of_le
(subset.trans h $ Icc_subset_Ico_right $ (lt_add_iff_pos_right _).2 Ξ΅0) _),
rw [β sub_add_eq_add_sub],
refine le_trans ennreal.of_real_add_le (add_le_add_left _ _),
simp only [ennreal.of_real_coe_nnreal, le_refl]
end
@[simp] lemma lebesgue_length_Icc (a b : β) :
lebesgue_length (Icc a b) = of_real (b - a) :=
begin
rw β lebesgue_length_Ico,
refine le_antisymm _ (lebesgue_length_mono Ico_subset_Icc_self),
rw lebesgue_length_eq_infi_Icc (Icc a b),
exact infi_le_of_le a (infi_le_of_le b $ infi_le_of_le (by refl) (by simp [le_refl]))
end
/-- The Lebesgue outer measure, as an outer measure of β. -/
def lebesgue_outer : outer_measure β :=
outer_measure.of_function lebesgue_length lebesgue_length_empty
lemma lebesgue_outer_le_length (s : set β) : lebesgue_outer s β€ lebesgue_length s :=
outer_measure.of_function_le _
lemma lebesgue_length_subadditive {a b : β} {c d : β β β}
(ss : Icc a b β βi, Ioo (c i) (d i)) :
(of_real (b - a) : ennreal) β€ β' i, of_real (d i - c i) :=
begin
suffices : β (s:finset β) b
(cv : Icc a b β β i β (βs:set β), Ioo (c i) (d i)),
(of_real (b - a) : ennreal) β€ β i in s, of_real (d i - c i),
{ rcases compact_Icc.elim_finite_subcover_image (Ξ» (i : β) (_ : i β univ),
@is_open_Ioo _ _ _ _ (c i) (d i)) (by simpa using ss) with β¨s, su, hf, hsβ©,
have e : (β i β (βhf.to_finset:set β),
Ioo (c i) (d i)) = (β i β s, Ioo (c i) (d i)), {simp [set.ext_iff]},
rw ennreal.tsum_eq_supr_sum,
refine le_trans _ (le_supr _ hf.to_finset),
exact this hf.to_finset _ (by simpa [e]) },
clear ss b,
refine Ξ» s, finset.strong_induction_on s (Ξ» s IH b cv, _),
cases le_total b a with ab ab,
{ rw ennreal.of_real_eq_zero.2 (sub_nonpos.2 ab), exact zero_le _ },
have := cv β¨ab, le_refl _β©, simp at this,
rcases this with β¨i, is, cb, bdβ©,
rw [β finset.insert_erase is] at cv β’,
rw [finset.coe_insert, bUnion_insert] at cv,
rw [finset.sum_insert (finset.not_mem_erase _ _)],
refine le_trans _ (add_le_add_left (IH _ (finset.erase_ssubset is) (c i) _) _),
{ refine le_trans (ennreal.of_real_le_of_real _) ennreal.of_real_add_le,
rw sub_add_sub_cancel,
exact sub_le_sub_right (le_of_lt bd) _ },
{ rintro x β¨hβ, hββ©,
refine (cv β¨hβ, le_trans hβ (le_of_lt cb)β©).resolve_left
(mt and.left (not_lt_of_le hβ)) }
end
@[simp] lemma lebesgue_outer_Icc (a b : β) :
lebesgue_outer (Icc a b) = of_real (b - a) :=
begin
refine le_antisymm (by rw β lebesgue_length_Icc; apply lebesgue_outer_le_length)
(le_binfi $ Ξ» f hf, ennreal.le_of_forall_epsilon_le $ Ξ» Ξ΅ Ξ΅0 h, _),
rcases ennreal.exists_pos_sum_of_encodable
(ennreal.zero_lt_coe_iff.2 Ξ΅0) β with β¨Ξ΅', Ξ΅'0, hΞ΅β©,
refine le_trans _ (add_le_add_left (le_of_lt hΞ΅) _),
rw β ennreal.tsum_add,
choose g hg using show
β i, β p:βΓβ, f i β Ioo p.1 p.2 β§ (of_real (p.2 - p.1) : ennreal) < lebesgue_length (f i) + Ξ΅' i,
{ intro i,
have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h)
(ennreal.zero_lt_coe_iff.2 (Ξ΅'0 i))),
conv at this {to_lhs, rw lebesgue_length_eq_infi_Ioo},
simpa [infi_lt_iff] },
refine le_trans _ (ennreal.tsum_le_tsum $ Ξ» i, le_of_lt (hg i).2),
exact lebesgue_length_subadditive (subset.trans hf $
Union_subset_Union $ Ξ» i, (hg i).1)
end
@[simp] lemma lebesgue_outer_singleton (a : β) : lebesgue_outer {a} = 0 :=
by simpa using lebesgue_outer_Icc a a
@[simp] lemma lebesgue_outer_Ico (a b : β) :
lebesgue_outer (Ico a b) = of_real (b - a) :=
by rw [β Icc_diff_right, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _),
lebesgue_outer_Icc]
@[simp] lemma lebesgue_outer_Ioo (a b : β) :
lebesgue_outer (Ioo a b) = of_real (b - a) :=
by rw [β Ico_diff_left, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _), lebesgue_outer_Ico]
@[simp] lemma lebesgue_outer_Ioc (a b : β) :
lebesgue_outer (Ioc a b) = of_real (b - a) :=
by rw [β Icc_diff_left, lebesgue_outer.diff_null _ (lebesgue_outer_singleton _), lebesgue_outer_Icc]
lemma is_lebesgue_measurable_Iio {c : β} :
lebesgue_outer.caratheodory.is_measurable' (Iio c) :=
outer_measure.of_function_caratheodory $ Ξ» t,
le_infi $ Ξ» a, le_infi $ Ξ» b, le_infi $ Ξ» h, begin
refine le_trans (add_le_add
(lebesgue_length_mono $ inter_subset_inter_left _ h)
(lebesgue_length_mono $ diff_subset_diff_left h)) _,
cases le_total a c with hac hca; cases le_total b c with hbc hcb;
simp [*, -sub_eq_add_neg, sub_add_sub_cancel', le_refl],
{ simp [*, β ennreal.of_real_add, -sub_eq_add_neg, sub_add_sub_cancel', le_refl] },
{ simp only [ennreal.of_real_eq_zero.2 (sub_nonpos.2 (le_trans hbc hca)), zero_add, le_refl] }
end
theorem lebesgue_outer_trim : lebesgue_outer.trim = lebesgue_outer :=
begin
refine le_antisymm (Ξ» s, _) (outer_measure.le_trim _),
rw outer_measure.trim_eq_infi,
refine le_infi (Ξ» f, le_infi $ Ξ» hf,
ennreal.le_of_forall_epsilon_le $ Ξ» Ξ΅ Ξ΅0 h, _),
rcases ennreal.exists_pos_sum_of_encodable
(ennreal.zero_lt_coe_iff.2 Ξ΅0) β with β¨Ξ΅', Ξ΅'0, hΞ΅β©,
refine le_trans _ (add_le_add_left (le_of_lt hΞ΅) _),
rw β ennreal.tsum_add,
choose g hg using show
β i, β s, f i β s β§ is_measurable s β§ lebesgue_outer s β€ lebesgue_length (f i) + of_real (Ξ΅' i),
{ intro i,
have := (ennreal.lt_add_right (lt_of_le_of_lt (ennreal.le_tsum i) h)
(ennreal.zero_lt_coe_iff.2 (Ξ΅'0 i))),
conv at this {to_lhs, rw lebesgue_length},
simp only [infi_lt_iff] at this,
rcases this with β¨a, b, hβ, hββ©,
rw β lebesgue_outer_Ico at hβ,
exact β¨_, hβ, is_measurable_Ico, le_of_lt $ by simpa using hββ© },
simp at hg,
apply infi_le_of_le (Union g) _,
apply infi_le_of_le (subset.trans hf $ Union_subset_Union (Ξ» i, (hg i).1)) _,
apply infi_le_of_le (is_measurable.Union (Ξ» i, (hg i).2.1)) _,
exact le_trans (lebesgue_outer.Union _) (ennreal.tsum_le_tsum $ Ξ» i, (hg i).2.2)
end
lemma borel_le_lebesgue_measurable : borel β β€ lebesgue_outer.caratheodory :=
begin
rw real.borel_eq_generate_from_Iio_rat,
refine measurable_space.generate_from_le _,
simp [is_lebesgue_measurable_Iio] { contextual := tt }
end
/-- Lebesgue measure on the Borel sets
The outer Lebesgue measure is the completion of this measure. (TODO: proof this)
-/
instance real.measure_space : measure_space β :=
β¨{to_outer_measure := lebesgue_outer,
m_Union := Ξ» f hf, lebesgue_outer.Union_eq_of_caratheodory $
Ξ» i, borel_le_lebesgue_measurable _ (hf i),
trimmed := lebesgue_outer_trim }β©
@[simp] theorem lebesgue_to_outer_measure :
(volume : measure β).to_outer_measure = lebesgue_outer := rfl
end measure_theory
open measure_theory
namespace real
open_locale topological_space
theorem volume_val (s) : volume s = lebesgue_outer s := rfl
instance has_no_atoms_volume : has_no_atoms (volume : measure β) :=
β¨lebesgue_outer_singletonβ©
@[simp] lemma volume_Ico {a b : β} : volume (Ico a b) = of_real (b - a) := lebesgue_outer_Ico a b
@[simp] lemma volume_Icc {a b : β} : volume (Icc a b) = of_real (b - a) := lebesgue_outer_Icc a b
@[simp] lemma volume_Ioo {a b : β} : volume (Ioo a b) = of_real (b - a) := lebesgue_outer_Ioo a b
@[simp] lemma volume_Ioc {a b : β} : volume (Ioc a b) = of_real (b - a) := lebesgue_outer_Ioc a b
@[simp] lemma volume_singleton {a : β} : volume ({a} : set β) = 0 := lebesgue_outer_singleton a
@[simp] lemma volume_interval {a b : β} : volume (interval a b) = of_real (abs (b - a)) :=
by rw [interval, volume_Icc, max_sub_min_eq_abs]
instance locally_finite_volume : locally_finite_measure (volume : measure β) :=
β¨Ξ» x, β¨Ioo (x - 1) (x + 1),
mem_nhds_sets is_open_Ioo β¨sub_lt_self _ zero_lt_one, lt_add_of_pos_right _ zero_lt_oneβ©,
by simp only [real.volume_Ioo, ennreal.of_real_lt_top]β©β©
lemma map_volume_add_left (a : β) : measure.map ((+) a) volume = volume :=
eq.symm $ real.measure_ext_Ioo_rat $ Ξ» p q,
by simp [measure.map_apply (measurable_add_left a) is_measurable_Ioo, sub_sub_sub_cancel_right]
lemma map_volume_add_right (a : β) : measure.map (+ a) volume = volume :=
by simpa only [add_comm] using real.map_volume_add_left a
lemma smul_map_volume_mul_left {a : β} (h : a β 0) :
ennreal.of_real (abs a) β’ measure.map ((*) a) volume = volume :=
begin
refine (real.measure_ext_Ioo_rat $ Ξ» p q, _).symm,
cases lt_or_gt_of_ne h with h h,
{ simp only [real.volume_Ioo, measure.smul_apply, β ennreal.of_real_mul (le_of_lt $ neg_pos.2 h),
measure.map_apply (measurable_mul_left a) is_measurable_Ioo, neg_sub_neg,
β neg_mul_eq_neg_mul, preimage_const_mul_Ioo_of_neg _ _ h, abs_of_neg h, mul_sub,
mul_div_cancel' _ (ne_of_lt h)] },
{ simp only [real.volume_Ioo, measure.smul_apply, β ennreal.of_real_mul (le_of_lt h),
measure.map_apply (measurable_mul_left a) is_measurable_Ioo, preimage_const_mul_Ioo _ _ h,
abs_of_pos h, mul_sub, mul_div_cancel' _ (ne_of_gt h)] }
end
lemma map_volume_mul_left {a : β} (h : a β 0) :
measure.map ((*) a) volume = ennreal.of_real (abs aβ»ΒΉ) β’ volume :=
by conv_rhs { rw [β real.smul_map_volume_mul_left h, smul_smul,
β ennreal.of_real_mul (abs_nonneg _), β abs_mul, inv_mul_cancel h, abs_one, ennreal.of_real_one,
one_smul] }
lemma smul_map_volume_mul_right {a : β} (h : a β 0) :
ennreal.of_real (abs a) β’ measure.map (* a) volume = volume :=
by simpa only [mul_comm] using real.smul_map_volume_mul_left h
lemma map_volume_mul_right {a : β} (h : a β 0) :
measure.map (* a) volume = ennreal.of_real (abs aβ»ΒΉ) β’ volume :=
by simpa only [mul_comm] using real.map_volume_mul_left h
@[simp] lemma map_volume_neg : measure.map has_neg.neg (volume : measure β) = volume :=
eq.symm $ real.measure_ext_Ioo_rat $ Ξ» p q,
by simp [measure.map_apply measurable_neg is_measurable_Ioo]
end real
/-
section vitali
def vitali_aux_h (x : β) (h : x β Icc (0:β) 1) :
β y β Icc (0:β) 1, β q:β, βq = x - y :=
β¨x, h, 0, by simpβ©
def vitali_aux (x : β) (h : x β Icc (0:β) 1) : β :=
classical.some (vitali_aux_h x h)
theorem vitali_aux_mem (x : β) (h : x β Icc (0:β) 1) : vitali_aux x h β Icc (0:β) 1 :=
Exists.fst (classical.some_spec (vitali_aux_h x h):_)
theorem vitali_aux_rel (x : β) (h : x β Icc (0:β) 1) :
β q:β, βq = x - vitali_aux x h :=
Exists.snd (classical.some_spec (vitali_aux_h x h):_)
def vitali : set β := {x | β h, x = vitali_aux x h}
theorem vitali_nonmeasurable : Β¬ is_null_measurable measure_space.ΞΌ vitali :=
sorry
end vitali
-/
|
e689daedf503cbe0f7c3c463474b67e5d8c0998c | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /hott/types/sum.hlean | b163158b9c9c430d16ef2aed5f0421108fb37aef | [
"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 | 15,428 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Floris van Doorn
Theorems about sums/coproducts/disjoint unions
-/
import .pi .equiv logic
open lift eq is_equiv equiv equiv.ops prod prod.ops is_trunc sigma bool
namespace sum
universe variables u v u' v'
variables {A : Type.{u}} {B : Type.{v}} (z z' : A + B) {P : A β Type.{u'}} {Q : A β Type.{v'}}
protected definition eta : sum.rec inl inr z = z :=
by induction z; all_goals reflexivity
protected definition code [unfold 3 4] : A + B β A + B β Type.{max u v}
| code (inl a) (inl a') := lift (a = a')
| code (inr b) (inr b') := lift (b = b')
| code _ _ := lift empty
protected definition decode [unfold 3 4] : Ξ (z z' : A + B), sum.code z z' β z = z'
| decode (inl a) (inl a') := Ξ»c, ap inl (down c)
| decode (inl a) (inr b') := Ξ»c, empty.elim (down c) _
| decode (inr b) (inl a') := Ξ»c, empty.elim (down c) _
| decode (inr b) (inr b') := Ξ»c, ap inr (down c)
protected definition mem_cases : (Ξ£ a, z = inl a) + (Ξ£ b, z = inr b) :=
by cases z with a b; exact inl β¨a, idpβ©; exact inr β¨b, idpβ©
protected definition eqrec {A B : Type} {C : A + B β Type}
(x : A + B) (cl : Ξ a, x = inl a β C (inl a)) (cr : Ξ b, x = inr b β C (inr b)) : C x :=
by cases x with a b; exact cl a idp; exact cr b idp
variables {z z'}
protected definition encode [unfold 3 4 5] (p : z = z') : sum.code z z' :=
by induction p; induction z; all_goals exact up idp
variables (z z')
definition sum_eq_equiv [constructor] : (z = z') β sum.code z z' :=
equiv.MK sum.encode
!sum.decode
abstract begin
intro c, induction z with a b, all_goals induction z' with a' b',
all_goals (esimp at *; induction c with c),
all_goals induction c, -- c either has type empty or a path
all_goals reflexivity
end end
abstract begin
intro p, induction p, induction z, all_goals reflexivity
end end
section
variables {a a' : A} {b b' : B}
definition eq_of_inl_eq_inl [unfold 5] (p : inl a = inl a' :> A + B) : a = a' :=
down (sum.encode p)
definition eq_of_inr_eq_inr [unfold 5] (p : inr b = inr b' :> A + B) : b = b' :=
down (sum.encode p)
definition empty_of_inl_eq_inr (p : inl a = inr b) : empty := down (sum.encode p)
definition empty_of_inr_eq_inl (p : inr b = inl a) : empty := down (sum.encode p)
/- Transport -/
definition sum_transport (p : a = a') (z : P a + Q a)
: p βΈ z = sum.rec (Ξ»a, inl (p βΈ a)) (Ξ»b, inr (p βΈ b)) z :=
by induction p; induction z; all_goals reflexivity
/- Pathovers -/
definition etao (p : a = a') (z : P a + Q a)
: z =[p] sum.rec (Ξ»a, inl (p βΈ a)) (Ξ»b, inr (p βΈ b)) z :=
by induction p; induction z; all_goals constructor
protected definition codeo (p : a = a') : P a + Q a β P a' + Q a' β Type.{max u' v'}
| codeo (inl x) (inl x') := lift.{u' v'} (x =[p] x')
| codeo (inr y) (inr y') := lift.{v' u'} (y =[p] y')
| codeo _ _ := lift empty
protected definition decodeo (p : a = a') : Ξ (z : P a + Q a) (z' : P a' + Q a'),
sum.codeo p z z' β z =[p] z'
| decodeo (inl x) (inl x') := Ξ»c, apo (Ξ»a, inl) (down c)
| decodeo (inl x) (inr y') := Ξ»c, empty.elim (down c) _
| decodeo (inr y) (inl x') := Ξ»c, empty.elim (down c) _
| decodeo (inr y) (inr y') := Ξ»c, apo (Ξ»a, inr) (down c)
variables {z z'}
protected definition encodeo {p : a = a'} {z : P a + Q a} {z' : P a' + Q a'} (q : z =[p] z')
: sum.codeo p z z' :=
by induction q; induction z; all_goals exact up idpo
variables (z z')
definition sum_pathover_equiv [constructor] (p : a = a') (z : P a + Q a) (z' : P a' + Q a')
: (z =[p] z') β sum.codeo p z z' :=
equiv.MK sum.encodeo
!sum.decodeo
abstract begin
intro c, induction z with a b, all_goals induction z' with a' b',
all_goals (esimp at *; induction c with c),
all_goals induction c, -- c either has type empty or a pathover
all_goals reflexivity
end end
abstract begin
intro q, induction q, induction z, all_goals reflexivity
end end
end
/- Functorial action -/
variables {A' B' : Type} (f : A β A') (g : B β B')
definition sum_functor [unfold 7] : A + B β A' + B'
| sum_functor (inl a) := inl (f a)
| sum_functor (inr b) := inr (g b)
/- Equivalences -/
definition is_equiv_sum_functor [constructor] [Hf : is_equiv f] [Hg : is_equiv g]
: is_equiv (sum_functor f g) :=
adjointify (sum_functor f g)
(sum_functor fβ»ΒΉ gβ»ΒΉ)
abstract begin
intro z, induction z,
all_goals (esimp; (apply ap inl | apply ap inr); apply right_inv)
end end
abstract begin
intro z, induction z,
all_goals (esimp; (apply ap inl | apply ap inr); apply right_inv)
end end
definition sum_equiv_sum_of_is_equiv [constructor] [Hf : is_equiv f] [Hg : is_equiv g]
: A + B β A' + B' :=
equiv.mk _ (is_equiv_sum_functor f g)
definition sum_equiv_sum [constructor] (f : A β A') (g : B β B') : A + B β A' + B' :=
equiv.mk _ (is_equiv_sum_functor f g)
definition sum_equiv_sum_left [constructor] (g : B β B') : A + B β A + B' :=
sum_equiv_sum equiv.refl g
definition sum_equiv_sum_right [constructor] (f : A β A') : A + B β A' + B :=
sum_equiv_sum f equiv.refl
definition flip [unfold 3] : A + B β B + A
| flip (inl a) := inr a
| flip (inr b) := inl b
definition sum_comm_equiv [constructor] (A B : Type) : A + B β B + A :=
begin
fapply equiv.MK,
exact flip,
exact flip,
all_goals (intro z; induction z; all_goals reflexivity)
end
definition sum_assoc_equiv [constructor] (A B C : Type) : A + (B + C) β (A + B) + C :=
begin
fapply equiv.MK,
all_goals try (intro z; induction z with u v;
all_goals try induction u; all_goals try induction v),
all_goals try (repeat append (append (apply inl) (apply inr)) assumption; now),
all_goals reflexivity
end
definition sum_empty_equiv [constructor] (A : Type) : A + empty β A :=
begin
fapply equiv.MK,
{ intro z, induction z, assumption, contradiction},
{ exact inl},
{ intro a, reflexivity},
{ intro z, induction z, reflexivity, contradiction}
end
definition empty_sum_equiv (A : Type) : empty + A β A :=
!sum_comm_equiv β¬e !sum_empty_equiv
definition bool_equiv_unit_sum_unit : bool β unit + unit :=
begin
fapply equiv.MK,
{ intro b, cases b, exact inl unit.star, exact inr unit.star },
{ intro s, cases s, exact bool.ff, exact bool.tt },
{ intro s, cases s, do 2 (cases a; reflexivity) },
{ intro b, cases b, do 2 reflexivity },
end
definition sum_prod_right_distrib [constructor] (A B C : Type) :
(A + B) Γ C β (A Γ C) + (B Γ C) :=
begin
fapply equiv.MK,
{ intro x, cases x with ab c, cases ab with a b, exact inl (a, c), exact inr (b, c) },
{ intro x, cases x with ac bc, cases ac with a c, exact (inl a, c),
cases bc with b c, exact (inr b, c) },
{ intro x, cases x with ac bc, cases ac with a c, reflexivity, cases bc, reflexivity },
{ intro x, cases x with ab c, cases ab with a b, do 2 reflexivity }
end
definition sum_prod_left_distrib [constructor] (A B C : Type) :
A Γ (B + C) β (A Γ B) + (A Γ C) :=
calc A Γ (B + C) β (B + C) Γ A : prod_comm_equiv
... β (B Γ A) + (C Γ A) : sum_prod_right_distrib
... β (A Γ B) + (C Γ A) : prod_comm_equiv
... β (A Γ B) + (A Γ C) : prod_comm_equiv
section
variables (H : unit + A β unit + B)
include H
open unit decidable sigma.ops
definition unit_sum_equiv_cancel_map : A β B :=
begin
intro a, cases sum.mem_cases (H (inr a)) with u b, rotate 1, exact b.1,
cases u with u Hu, cases sum.mem_cases (H (inl β)) with u' b, rotate 1, exact b.1,
cases u' with u' Hu', exfalso, apply empty_of_inl_eq_inr,
calc inl β = Hβ»ΒΉ (H (inl β)) : (to_left_inv H (inl β))β»ΒΉ
... = Hβ»ΒΉ (inl u') : {Hu'}
... = Hβ»ΒΉ (inl u) : is_hprop.elim
... = Hβ»ΒΉ (H (inr a)) : {Huβ»ΒΉ}
... = inr a : to_left_inv H (inr a)
end
definition unit_sum_equiv_cancel_inv (b : B) :
unit_sum_equiv_cancel_map H (unit_sum_equiv_cancel_map Hβ»ΒΉ b) = b :=
begin
assert HH : to_fun Hβ»ΒΉ = (to_fun H)β»ΒΉ, cases H, reflexivity,
esimp[unit_sum_equiv_cancel_map], apply sum.rec,
{ intro x, cases x with u Hu, esimp, apply sum.rec,
{ intro x, exfalso, cases x with u' Hu', apply empty_of_inl_eq_inr,
calc inl β = Hβ»ΒΉ (H (inl β)) : (to_left_inv H (inl β))β»ΒΉ
... = Hβ»ΒΉ (inl u') : ap Hβ»ΒΉ Hu'
... = Hβ»ΒΉ (inl u) : {!is_hprop.elim}
... = Hβ»ΒΉ (H (inr _)) : {Huβ»ΒΉ}
... = inr _ : to_left_inv H },
{ intro x, cases x with b' Hb', esimp, cases sum.mem_cases (Hβ»ΒΉ (inr b)) with x x,
{ cases x with u' Hu', cases u', apply eq_of_inr_eq_inr, rewrite -HH at Hu',
calc inr b' = H (inl β) : Hb'β»ΒΉ
... = H (Hβ»ΒΉ (inr b)) : {(ap (to_fun H) Hu')β»ΒΉ}
... = inr b : to_right_inv H (inr b) },
{ exfalso, cases x with a Ha, rewrite -HH at Ha, apply empty_of_inl_eq_inr,
cases u, apply concat, apply Huβ»ΒΉ, apply concat, rotate 1, apply !(to_right_inv H),
apply ap (to_fun H), krewrite -HH,
apply concat, rotate 1, apply Haβ»ΒΉ, apply ap inr, esimp,
apply sum.rec, intro x, exfalso, apply empty_of_inl_eq_inr,
apply concat, exact x.2β»ΒΉ, apply Ha,
intro x, cases x with a' Ha', esimp, apply eq_of_inr_eq_inr, apply Ha'β»ΒΉ β¬ Ha } } },
{ intro x, cases x with b' Hb', esimp, apply eq_of_inr_eq_inr, refine Hb'β»ΒΉ β¬ _,
cases sum.mem_cases (to_fun Hβ»ΒΉ (inr b)) with x x,
{ cases x with u Hu, esimp, cases sum.mem_cases (to_fun Hβ»ΒΉ (inl β)) with x x,
{ cases x with u' Hu', exfalso, apply empty_of_inl_eq_inr,
calc inl β = H (Hβ»ΒΉ (inl β)) : (to_right_inv H (inl β))β»ΒΉ
... = H (inl u') : {ap H Hu'}
... = H (inl u) : {!is_hprop.elim}
... = H (Hβ»ΒΉ (inr b)) : {ap H Huβ»ΒΉ}
... = inr b : to_right_inv H (inr b) },
{ cases x with a Ha, exfalso, apply empty_of_inl_eq_inr,
apply concat, rotate 1, exact Hb', krewrite HH at Ha,
assert Ha' : inl β = H (inr a), apply !(to_right_inv H)β»ΒΉ β¬ ap H Ha,
apply concat Ha', apply ap H, apply ap inr, apply sum.rec,
intro x, cases x with u' Hu', esimp, apply sum.rec,
intro x, cases x with u'' Hu'', esimp, apply empty.rec,
intro x, cases x with a'' Ha'', esimp, krewrite Ha' at Ha'', apply eq_of_inr_eq_inr,
apply !(to_left_inv H)β»ΒΉ β¬ Ha'',
intro x, exfalso, cases x with a'' Ha'', apply empty_of_inl_eq_inr,
apply Huβ»ΒΉ β¬ Ha'', } },
{ cases x with a' Ha', esimp, refine _ β¬ !(to_right_inv H), apply ap H,
rewrite -HH, apply Ha'β»ΒΉ } }
end
definition unit_sum_equiv_cancel : A β B :=
begin
fapply equiv.MK, apply unit_sum_equiv_cancel_map H,
apply unit_sum_equiv_cancel_map Hβ»ΒΉ,
intro b, apply unit_sum_equiv_cancel_inv,
{ intro a, have H = (Hβ»ΒΉ)β»ΒΉ, from !equiv.symm_symmβ»ΒΉ, rewrite this at {2},
apply unit_sum_equiv_cancel_inv }
end
end
/- universal property -/
definition sum_rec_unc [unfold 5] {P : A + B β Type} (fg : (Ξ a, P (inl a)) Γ (Ξ b, P (inr b)))
: Ξ z, P z :=
sum.rec fg.1 fg.2
definition is_equiv_sum_rec [constructor] (P : A + B β Type)
: is_equiv (sum_rec_unc : (Ξ a, P (inl a)) Γ (Ξ b, P (inr b)) β Ξ z, P z) :=
begin
apply adjointify sum_rec_unc (Ξ»f, (Ξ»a, f (inl a), Ξ»b, f (inr b))),
intro f, apply eq_of_homotopy, intro z, focus (induction z; all_goals reflexivity),
intro h, induction h with f g, reflexivity
end
definition equiv_sum_rec [constructor] (P : A + B β Type)
: (Ξ a, P (inl a)) Γ (Ξ b, P (inr b)) β Ξ z, P z :=
equiv.mk _ !is_equiv_sum_rec
definition imp_prod_imp_equiv_sum_imp [constructor] (A B C : Type)
: (A β C) Γ (B β C) β (A + B β C) :=
!equiv_sum_rec
/- truncatedness -/
variables (A B)
theorem is_trunc_sum (n : trunc_index) [HA : is_trunc (n.+2) A] [HB : is_trunc (n.+2) B]
: is_trunc (n.+2) (A + B) :=
begin
apply is_trunc_succ_intro, intro z z',
apply is_trunc_equiv_closed_rev, apply sum_eq_equiv,
induction z with a b, all_goals induction z' with a' b', all_goals esimp,
all_goals exact _,
end
theorem is_trunc_sum_excluded (n : trunc_index) [HA : is_trunc n A] [HB : is_trunc n B]
(H : A β B β empty) : is_trunc n (A + B) :=
begin
induction n with n IH,
{ exfalso, exact H !center !center},
{ clear IH, induction n with n IH,
{ apply is_hprop.mk, intros x y,
induction x, all_goals induction y, all_goals esimp,
all_goals try (exfalso;apply H;assumption;assumption), all_goals apply ap _ !is_hprop.elim},
{ apply is_trunc_sum}}
end
variable {B}
definition is_contr_sum_left [HA : is_contr A] (H : Β¬B) : is_contr (A + B) :=
is_contr.mk (inl !center)
(Ξ»x, sum.rec_on x (Ξ»a, ap inl !center_eq) (Ξ»b, empty.elim (H b)))
/-
Sums are equivalent to dependent sigmas where the first component is a bool.
The current construction only works for A and B in the same universe.
If we need it for A and B in different universes, we need to insert some lifts.
-/
definition sum_of_sigma_bool {A B : Type.{u}} (v : Ξ£(b : bool), bool.rec A B b) : A + B :=
by induction v with b x; induction b; exact inl x; exact inr x
definition sigma_bool_of_sum {A B : Type.{u}} (z : A + B) : Ξ£(b : bool), bool.rec A B b :=
by induction z with a b; exact β¨ff, aβ©; exact β¨tt, bβ©
definition sum_equiv_sigma_bool [constructor] (A B : Type.{u})
: A + B β Ξ£(b : bool), bool.rec A B b :=
equiv.MK sigma_bool_of_sum
sum_of_sigma_bool
begin intro v, induction v with b x, induction b, all_goals reflexivity end
begin intro z, induction z with a b, all_goals reflexivity end
end sum
open sum pi
namespace decidable
definition decidable_equiv [constructor] (A : Type) : decidable A β A + Β¬A :=
begin
fapply equiv.MK:intro a;induction a:try (constructor;assumption;now),
all_goals reflexivity
end
definition is_trunc_decidable [constructor] (A : Type) (n : trunc_index) [H : is_trunc n A] :
is_trunc n (decidable A) :=
begin
apply is_trunc_equiv_closed_rev,
apply decidable_equiv,
induction n with n IH,
{ apply is_contr_sum_left, exact Ξ»na, na !center},
{ apply is_trunc_sum_excluded, exact Ξ»a na, na a}
end
end decidable
attribute sum.is_trunc_sum [instance] [priority 1480]
definition tsum [constructor] {n : trunc_index} (A B : (n.+2)-Type) : (n.+2)-Type :=
trunctype.mk (A + B) _
infixr `+t`:25 := tsum
|
b755ecfdff105a5e5ab2ee6c9d2af1581d81c42b | 367134ba5a65885e863bdc4507601606690974c1 | /src/tactic/apply.lean | 6d62b92d1b10a74c591fc93dcb8ac943004e4d59 | [
"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 | 7,911 | lean | /-
Copyright (c) 2019 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author(s): Simon Hudon
-/
import tactic.core
/-!
This file provides an alternative implementation for `apply` to fix the so-called "apply bug".
The issue arises when the goals is a Ξ -type -- whether it is visible or hidden behind a definition.
For instance, consider the following proof:
```
example {Ξ± Ξ²} (x y z : Ξ± β Ξ²) (hβ : x β€ y) (hβ : y β€ z) : x β€ z :=
begin
apply le_trans,
end
```
Because `x β€ z` is definitionally equal to `β i, x i β€ z i`, `apply` will fail. The alternative
definition, `apply'` fixes this. When `apply` would work, `apply` is used and otherwise,
a different strategy is deployed
-/
namespace tactic
/-- With `gs` a list of proof goals, `reorder_goals gs new_g` will use the `new_goals` policy
`new_g` to rearrange the dependent goals to either drop them, push them to the end of the list
or leave them in place. The `bool` values in `gs` indicates whether the goal is dependent or not. -/
def reorder_goals {Ξ±} (gs : list (bool Γ Ξ±)) : new_goals β list Ξ±
| new_goals.non_dep_first :=
let β¨dep,non_depβ© := gs.partition (coe β prod.fst) in
non_dep.map prod.snd ++ dep.map prod.snd
| new_goals.non_dep_only := (gs.filter (coe β bnot β prod.fst)).map prod.snd
| new_goals.all := gs.map prod.snd
private meta def has_opt_auto_param_inst_for_apply (ms : list (name Γ expr)) : tactic bool :=
ms.mfoldl
(Ξ» r m, do type β infer_type m.2,
b β is_class type,
return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2 || b)
ff
private meta def try_apply_opt_auto_param_instance_for_apply (cfg : apply_cfg)
(ms : list (name Γ expr)) : tactic unit :=
mwhen (has_opt_auto_param_inst_for_apply ms) $ do
gs β get_goals,
ms.mmap' (Ξ» m, mwhen (bnot <$> (is_assigned m.2)) $
set_goals [m.2] >>
try apply_instance >>
when cfg.opt_param (try apply_opt_param) >>
when cfg.auto_param (try apply_auto_param)),
set_goals gs
private meta def retry_apply_aux :
Ξ (e : expr) (cfg : apply_cfg), list (bool Γ name Γ expr) β tactic (list (name Γ expr))
| e cfg gs :=
focus1 (do {
tgt : expr β target, t β infer_type e,
unify t tgt,
exact e,
gs' β get_goals,
let r := reorder_goals gs.reverse cfg.new_goals,
set_goals (gs' ++ r.map prod.snd),
return r }) <|>
do (expr.pi n bi d b) β infer_type e >>= whnf | apply_core e cfg,
v β mk_meta_var d,
let b := b.has_var,
e β head_beta $ e v,
retry_apply_aux e cfg ((b, n, v) :: gs)
private meta def retry_apply (e : expr) (cfg : apply_cfg) : tactic (list (name Γ expr)) :=
apply_core e cfg <|> retry_apply_aux e cfg []
/-- `apply'` mimics the behavior of `apply_core`. When
`apply_core` fails, it is retried by providing the term with meta
variables as additional arguments. The meta variables can then
become new goals depending on the `cfg.new_goals` policy.
`apply'` also finds instances and applies opt_params and auto_params. -/
meta def apply' (e : expr) (cfg : apply_cfg := {}) : tactic (list (name Γ expr)) :=
do r β retry_apply e cfg,
try_apply_opt_auto_param_instance_for_apply cfg r,
return r
/-- Same as `apply'` but __all__ arguments that weren't inferred are added to goal list. -/
meta def fapply' (e : expr) : tactic (list (name Γ expr)) :=
apply' e {new_goals := new_goals.all}
/-- Same as `apply'` but only goals that don't depend on other goals are added to goal list. -/
meta def eapply' (e : expr) : tactic (list (name Γ expr)) :=
apply' e {new_goals := new_goals.non_dep_only}
/-- `relation_tactic` finds a proof rule for the relation found in the goal and uses `apply'`
to make one proof step. -/
private meta def relation_tactic (md : transparency) (op_for : environment β name β option name)
(tac_name : string) : tactic unit :=
do tgt β target >>= instantiate_mvars,
env β get_env,
let r := expr.get_app_fn tgt,
match op_for env (expr.const_name r) with
| (some refl) := do r β mk_const refl,
retry_apply r {md := md, new_goals := new_goals.non_dep_only },
return ()
| none := fail $ tac_name ++
" tactic failed, target is not a relation application with the expected property."
end
/-- Similar to `reflexivity` with the difference that `apply'` is used instead of `apply` -/
meta def reflexivity' (md := semireducible) : tactic unit :=
relation_tactic md environment.refl_for "reflexivity"
/-- Similar to `symmetry` with the difference that `apply'` is used instead of `apply` -/
meta def symmetry' (md := semireducible) : tactic unit :=
relation_tactic md environment.symm_for "symmetry"
/-- Similar to `transitivity` with the difference that `apply'` is used instead of `apply` -/
meta def transitivity' (md := semireducible) : tactic unit :=
relation_tactic md environment.trans_for "transitivity"
namespace interactive
setup_tactic_parser
/--
Similarly to `apply`, the `apply'` tactic tries to match the current goal against the conclusion
of the type of term.
It differs from `apply` in that it does not unfold definition in order to find out what the
assumptions of the provided term is. It is especially useful when defining relations on function
spaces (e.g. `β€`) so that rules like transitivity on `le : (Ξ± β Ξ²) β (Ξ± β Ξ²) β (Ξ± β Ξ²)` will be
considered to have three parameters and two assumptions (i.e. `f g h : Ξ± β Ξ²`, `Hβ : f β€ g`,
`Hβ : g β€ h`) instead of three parameters, two assumptions and then one more parameter
(i.e. `f g h : Ξ± β Ξ²`, `Hβ : f β€ g`, `Hβ : g β€ h`, `x : Ξ±`). Whereas `apply` would expect the goal
`f x β€ h x`, `apply'` will work with the goal `f β€ h`.
-/
meta def apply' (q : parse texpr) : tactic unit :=
concat_tags (do h β i_to_expr_for_apply q, tactic.apply' h)
/--
Similar to the `apply'` tactic, but does not reorder goals.
-/
meta def fapply' (q : parse texpr) : tactic unit :=
concat_tags (i_to_expr_for_apply q >>= tactic.fapply')
/--
Similar to the `apply'` tactic, but only creates subgoals for non-dependent premises that have not
been fixed by type inference or type class resolution.
-/
meta def eapply' (q : parse texpr) : tactic unit :=
concat_tags (i_to_expr_for_apply q >>= tactic.eapply')
/--
Similar to the `apply'` tactic, but allows the user to provide a `apply_cfg` configuration object.
-/
meta def apply_with' (q : parse parser.pexpr) (cfg : apply_cfg) : tactic unit :=
concat_tags (do e β i_to_expr_for_apply q, tactic.apply' e cfg)
/--
Similar to the `apply'` tactic, but uses matching instead of unification.
`mapply' t` is equivalent to `apply_with' t {unify := ff}`
-/
meta def mapply' (q : parse texpr) : tactic unit :=
concat_tags (do e β i_to_expr_for_apply q, tactic.apply' e {unify := ff})
/--
Similar to `reflexivity` with the difference that `apply'` is used instead of `apply`.
-/
meta def reflexivity' : tactic unit :=
tactic.reflexivity'
/--
Shorter name for the tactic `reflexivity'`.
-/
meta def refl' : tactic unit :=
tactic.reflexivity'
/--
`symmetry'` behaves like `symmetry` but also offers the option `symmetry' at h` to apply symmetry
to assumption `h`
-/
meta def symmetry' : parse location β tactic unit
| l@loc.wildcard := l.try_apply symmetry_hyp tactic.symmetry'
| (loc.ns hs) := (loc.ns hs.reverse).apply symmetry_hyp tactic.symmetry'
/--
Similar to `transitivity` with the difference that `apply'` is used instead of `apply`.
-/
meta def transitivity' (q : parse texpr?) : tactic unit :=
tactic.transitivity' >> match q with
| none := skip
| some q :=
do (r, lhs, rhs) β target_lhs_rhs,
t β infer_type lhs,
i_to_expr ``(%%q : %%t) >>= unify rhs
end
end interactive
end tactic
|
27d60a527afde5417c6a4b7e08790094fbfeffd3 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/tfae.lean | 43c494df03ad1d3aabe686c9156b0c63882cbbed | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 4,923 | lean | /-
Copyright (c) 2018 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Reid Barton, Simon Hudon
-/
import data.list.tfae
import tactic.scc
/-!
# The Following Are Equivalent (TFAE)
This file provides the tactics `tfae_have` and `tfae_finish` for proving the pairwise equivalence of
propositions in a set using various implications between them.
-/
namespace tactic
export list (tfae)
namespace tfae
@[derive has_reflect, derive inhabited]
inductive arrow : Type
| right : arrow
| left_right : arrow
| left : arrow
meta def mk_implication : Ξ (re : arrow) (eβ eβ : expr), pexpr
| arrow.right eβ eβ := ``(%%eβ β %%eβ)
| arrow.left_right eβ eβ := ``(%%eβ β %%eβ)
| arrow.left eβ eβ := ``(%%eβ β %%eβ)
meta def mk_name : Ξ (re : arrow) (iβ iβ : nat), name
| arrow.right iβ iβ := ("tfae_" ++ to_string iβ ++ "_to_" ++ to_string iβ : string)
| arrow.left_right iβ iβ := ("tfae_" ++ to_string iβ ++ "_iff_" ++ to_string iβ : string)
| arrow.left iβ iβ := ("tfae_" ++ to_string iβ ++ "_to_" ++ to_string iβ : string)
end tfae
namespace interactive
setup_tactic_parser
open tactic.tfae list
meta def parse_list : expr β option (list expr)
| `([]) := pure []
| `(%%e :: %%es) := (::) e <$> parse_list es
| _ := none
/-- In a goal of the form `tfae [aβ, aβ, aβ]`,
`tfae_have : i β j` creates the assertion `aα΅’ β aβ±Ό`. The other possible
notations are `tfae_have : i β j` and `tfae_have : i β j`. The user can
also provide a label for the assertion, as with `have`: `tfae_have h : i β j`.
-/
meta def tfae_have
(h : parse $ optional ident <* tk ":")
(iβ : parse (with_desc "i" small_nat))
(re : parse (((tk "β" <|> tk "->") *> return arrow.right) <|>
((tk "β" <|> tk "<->") *> return arrow.left_right) <|>
((tk "β" <|> tk "<-") *> return arrow.left)))
(iβ : parse (with_desc "j" small_nat)) :
tactic unit := do
`(tfae %%l) <- target,
l β parse_list l,
eβ β list.nth l (iβ - 1) <|> fail format!"index {iβ} is not between 1 and {l.length}",
eβ β list.nth l (iβ - 1) <|> fail format!"index {iβ} is not between 1 and {l.length}",
type β to_expr (tfae.mk_implication re eβ eβ),
let h := h.get_or_else (mk_name re iβ iβ),
tactic.assert h type,
return ()
/-- Finds all implications and equivalences in the context
to prove a goal of the form `tfae [...]`.
-/
meta def tfae_finish : tactic unit :=
applyc ``tfae_nil <|>
closure.with_new_closure (Ξ» cl,
do impl_graph.mk_scc cl,
`(tfae %%l) β target,
l β parse_list l,
(_,r,_) β cl.root l.head,
refine ``(tfae_of_forall %%r _ _),
thm β mk_const ``forall_mem_cons,
l.mmap' (Ξ» e,
do rewrite_target thm, split,
(_,r',p) β cl.root e,
tactic.exact p ),
applyc ``forall_mem_nil,
pure ())
end interactive
end tactic
/--
The `tfae` tactic suite is a set of tactics that help with proving that certain
propositions are equivalent.
In `data/list/basic.lean` there is a section devoted to propositions of the
form
```lean
tfae [p1, p2, ..., pn]
```
where `p1`, `p2`, through, `pn` are terms of type `Prop`.
This proposition asserts that all the `pi` are pairwise equivalent.
There are results that allow to extract the equivalence
of two propositions `pi` and `pj`.
To prove a goal of the form `tfae [p1, p2, ..., pn]`, there are two
tactics. The first tactic is `tfae_have`. As an argument it takes an
expression of the form `i arrow j`, where `i` and `j` are two positive
natural numbers, and `arrow` is an arrow such as `β`, `->`, `β`, `<-`,
`β`, or `<->`. The tactic `tfae_have : i arrow j` sets up a subgoal in
which the user has to prove the equivalence (or implication) of `pi` and `pj`.
The remaining tactic, `tfae_finish`, is a finishing tactic. It
collects all implications and equivalences from the local context and
computes their transitive closure to close the
main goal.
`tfae_have` and `tfae_finish` can be used together in a proof as
follows:
```lean
example (a b c d : Prop) : tfae [a,b,c,d] :=
begin
tfae_have : 3 β 1,
{ /- prove c β a -/ },
tfae_have : 2 β 3,
{ /- prove b β c -/ },
tfae_have : 2 β 1,
{ /- prove a β b -/ },
tfae_have : 4 β 2,
{ /- prove d β b -/ },
-- a b c d : Prop,
-- tfae_3_to_1 : c β a,
-- tfae_2_to_3 : b β c,
-- tfae_1_to_2 : a β b,
-- tfae_4_iff_2 : d β b
-- β’ tfae [a, b, c, d]
tfae_finish,
end
```
-/
add_tactic_doc
{ name := "tfae",
category := doc_category.tactic,
decl_names := [`tactic.interactive.tfae_have, `tactic.interactive.tfae_finish],
tags := ["logic"],
inherit_description_from := `tactic.interactive.tfae_finish }
|
4edef9e7012e6ff583d15cff48bbeaaf78d834e0 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/quaternion.lean | 3e3000dc5c7fa96f6f52126cd722c7560252120e | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 3,451 | lean | /-
Copyright (c) 2020 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import algebra.quaternion
import analysis.inner_product_space.basic
/-!
# Quaternions as a normed algebra
In this file we define the following structures on the space `β := β[β]` of quaternions:
* inner product space;
* normed ring;
* normed space over `β`.
## Notation
The following notation is available with `open_locale quaternion`:
* `β` : quaternions
## Tags
quaternion, normed ring, normed space, normed algebra
-/
localized "notation (name := quaternion.real) `β` := quaternion β" in quaternion
open_locale real_inner_product_space
noncomputable theory
namespace quaternion
instance : has_inner β β := β¨Ξ» a b, (a * b.conj).reβ©
lemma inner_self (a : β) : βͺa, aβ« = norm_sq a := rfl
lemma inner_def (a b : β) : βͺa, bβ« = (a * b.conj).re := rfl
instance : inner_product_space β β :=
inner_product_space.of_core
{ inner := has_inner.inner,
conj_sym := Ξ» x y, by simp [inner_def, mul_comm],
nonneg_re := Ξ» x, norm_sq_nonneg,
definite := Ξ» x, norm_sq_eq_zero.1,
add_left := Ξ» x y z, by simp only [inner_def, add_mul, add_re],
smul_left := Ξ» x y r, by simp [inner_def] }
lemma norm_sq_eq_norm_sq (a : β) : norm_sq a = βaβ * βaβ :=
by rw [β inner_self, real_inner_self_eq_norm_mul_norm]
instance : norm_one_class β :=
β¨by rw [norm_eq_sqrt_real_inner, inner_self, norm_sq.map_one, real.sqrt_one]β©
@[simp, norm_cast] lemma norm_coe (a : β) : β(a : β)β = βaβ :=
by rw [norm_eq_sqrt_real_inner, inner_self, norm_sq_coe, real.sqrt_sq_eq_abs, real.norm_eq_abs]
@[simp, norm_cast] lemma nnnorm_coe (a : β) : β(a : β)ββ = βaββ :=
subtype.ext $ norm_coe a
noncomputable instance : normed_division_ring β :=
{ dist_eq := Ξ» _ _, rfl,
norm_mul' := Ξ» a b, by { simp only [norm_eq_sqrt_real_inner, inner_self, norm_sq.map_mul],
exact real.sqrt_mul norm_sq_nonneg _ } }
noncomputable instance : normed_algebra β β :=
{ norm_smul_le := Ξ» a x, (norm_smul a x).le,
to_algebra := quaternion.algebra }
instance : has_coe β β := β¨Ξ» z, β¨z.re, z.im, 0, 0β©β©
@[simp, norm_cast] lemma coe_complex_re (z : β) : (z : β).re = z.re := rfl
@[simp, norm_cast] lemma coe_complex_im_i (z : β) : (z : β).im_i = z.im := rfl
@[simp, norm_cast] lemma coe_complex_im_j (z : β) : (z : β).im_j = 0 := rfl
@[simp, norm_cast] lemma coe_complex_im_k (z : β) : (z : β).im_k = 0 := rfl
@[simp, norm_cast] lemma coe_complex_add (z w : β) : β(z + w) = (z + w : β) := by ext; simp
@[simp, norm_cast] lemma coe_complex_mul (z w : β) : β(z * w) = (z * w : β) := by ext; simp
@[simp, norm_cast] lemma coe_complex_zero : ((0 : β) : β) = 0 := rfl
@[simp, norm_cast] lemma coe_complex_one : ((1 : β) : β) = 1 := rfl
@[simp, norm_cast] lemma coe_real_complex_mul (r : β) (z : β) : (r β’ z : β) = βr * βz :=
by ext; simp
@[simp, norm_cast] lemma coe_complex_coe (r : β) : ((r : β) : β) = r := rfl
/-- Coercion `β ββ[β] β` as an algebra homomorphism. -/
def of_complex : β ββ[β] β :=
{ to_fun := coe,
map_one' := rfl,
map_zero' := rfl,
map_add' := coe_complex_add,
map_mul' := coe_complex_mul,
commutes' := Ξ» x, rfl }
@[simp] lemma coe_of_complex : βof_complex = coe := rfl
end quaternion
|
5cda4ecec26ba3542e6c3b9e8332e15124c6d3fd | abd677583c7e4d55daf9487b82da11b7c5498d8d | /src/print.lean | e8d404ec8dfd87ee3a90431610a930f0bb5f0caa | [
"Apache-2.0"
] | permissive | jesse-michael-han/embed | e9c346918ad58e03933bdaa057a571c0cc4a7641 | c2fc188328e871e18e0dcb8258c6d0462c70a8c9 | refs/heads/master | 1,584,677,705,005 | 1,528,451,877,000 | 1,528,451,877,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 183 | lean | import .exp
variable {Ξ± : Type}
open expr tactic
def sqt2str (exp2str : exp Ξ± β string) (Ξ Ξ : list (exp Ξ±)) : string :=
lst2str exp2str Ξ ++ " β’ " ++ lst2str exp2str Ξ |
dd38ddb7e83b2d9d4378543884f909e4b861f9dd | c777c32c8e484e195053731103c5e52af26a25d1 | /src/logic/equiv/array.lean | 5e1f98c7d71cfd6aa1dbbac6825ea519b4770e0a | [
"Apache-2.0"
] | permissive | kbuzzard/mathlib | 2ff9e85dfe2a46f4b291927f983afec17e946eb8 | 58537299e922f9c77df76cb613910914a479c1f7 | refs/heads/master | 1,685,313,702,744 | 1,683,974,212,000 | 1,683,974,212,000 | 128,185,277 | 1 | 0 | null | 1,522,920,600,000 | 1,522,920,600,000 | null | UTF-8 | Lean | false | false | 1,766 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.vector.basic
import logic.equiv.list
import control.traversable.equiv
/-!
# Equivalences involving `array`
We keep this separate from the file containing `list`-like equivalences as those have no future
in mathlib4.
-/
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 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
/-- If `Ξ±` is encodable, then so is `array n Ξ±`. -/
instance _root_.array.encodable {Ξ±} [encodable Ξ±] {n} : encodable (array n Ξ±) :=
encodable.of_equiv _ (equiv.array_equiv_fin _ _)
/-- If `Ξ±` is countable, then so is `array n Ξ±`. -/
instance _root_.array.countable {Ξ±} [countable Ξ±] {n} : countable (array n Ξ±) :=
countable.of_equiv _ (equiv.vector_equiv_array _ _)
|
7f5e8db2f79af29913708e2f186b7bb59ab15ba5 | 4efff1f47634ff19e2f786deadd394270a59ecd2 | /src/set_theory/cardinal.lean | b7479b4ef8e0f0f33ead869675e7cf51cac67d2f | [
"Apache-2.0"
] | permissive | agjftucker/mathlib | d634cd0d5256b6325e3c55bb7fb2403548371707 | 87fe50de17b00af533f72a102d0adefe4a2285e8 | refs/heads/master | 1,625,378,131,941 | 1,599,166,526,000 | 1,599,166,526,000 | 160,748,509 | 0 | 0 | Apache-2.0 | 1,544,141,789,000 | 1,544,141,789,000 | null | UTF-8 | Lean | false | false | 46,208 | lean | /-
Copyright (c) 2017 Johannes HΓΆlzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Johannes HΓΆlzl, Mario Carneiro
-/
import data.set.countable
import set_theory.schroeder_bernstein
import data.fintype.card
/-!
# Cardinal Numbers
We define cardinal numbers as a quotient of types under the equivalence relation of equinumerity.
We define the order on cardinal numbers, define omega, and do basic cardinal arithmetic:
addition, multiplication, power, cardinal successor, minimum, supremum,
infinitary sums and products
The fact that the cardinality of `Ξ± Γ Ξ±` coincides with that of `Ξ±` when `Ξ±` is infinite is not
proved in this file, as it relies on facts on well-orders. Instead, it is in
`cardinal_ordinal.lean` (together with many other facts on cardinals, for instance the
cardinality of `list Ξ±`).
## Implementation notes
* There is a type of cardinal numbers in every universe level: `cardinal.{u} : Type (u + 1)`
is the quotient of types in `Type u`.
There is a lift operation lifting cardinal numbers to a higher level.
* Cardinal arithmetic specifically for infinite cardinals (like `ΞΊ * ΞΊ = ΞΊ`) is in the file
`set_theory/ordinal.lean`, because concepts from that file are used in the proof.
## References
* <https://en.wikipedia.org/wiki/Cardinal_number>
## Tags
cardinal number, cardinal arithmetic, cardinal exponentiation, omega
-/
open function set
open_locale classical
universes u v w x
variables {Ξ± Ξ² : Type u}
/-- The equivalence relation on types given by equivalence (bijective correspondence) of types.
Quotienting by this equivalence relation gives the cardinal numbers.
-/
instance cardinal.is_equivalent : setoid (Type u) :=
{ r := λα Ξ², nonempty (Ξ± β Ξ²),
iseqv := β¨Ξ»Ξ±,
β¨equiv.refl Ξ±β©,
λα Ξ² β¨eβ©, β¨e.symmβ©,
λα Ξ² Ξ³ β¨eββ© β¨eββ©, β¨eβ.trans eββ©β© }
/-- `cardinal.{u}` is the type of cardinal numbers in `Type u`,
defined as the quotient of `Type u` by existence of an equivalence
(a bijection with explicit inverse). -/
def cardinal : Type (u + 1) := quotient cardinal.is_equivalent
namespace cardinal
/-- The cardinal number of a type -/
def mk : Type u β cardinal := quotient.mk
localized "notation `#` := cardinal.mk" in cardinal
protected lemma eq : mk Ξ± = mk Ξ² β nonempty (Ξ± β Ξ²) := quotient.eq
@[simp] theorem mk_def (Ξ± : Type u) : @eq cardinal β¦Ξ±β§ (mk Ξ±) := rfl
@[simp] theorem mk_out (c : cardinal) : mk (c.out) = c := quotient.out_eq _
/-- We define the order on cardinal numbers by `mk Ξ± β€ mk Ξ²` if and only if
there exists an embedding (injective function) from Ξ± to Ξ². -/
instance : has_le cardinal.{u} :=
β¨Ξ»qβ qβ, quotient.lift_onβ qβ qβ (λα Ξ², nonempty $ Ξ± βͺ Ξ²) $
assume Ξ± Ξ² Ξ³ Ξ΄ β¨eββ© β¨eββ©,
propext β¨assume β¨eβ©, β¨e.congr eβ eββ©, assume β¨eβ©, β¨e.congr eβ.symm eβ.symmβ©β©β©
theorem mk_le_of_injective {Ξ± Ξ² : Type u} {f : Ξ± β Ξ²} (hf : injective f) : mk Ξ± β€ mk Ξ² :=
β¨β¨f, hfβ©β©
theorem mk_le_of_surjective {Ξ± Ξ² : Type u} {f : Ξ± β Ξ²} (hf : surjective f) : mk Ξ² β€ mk Ξ± :=
β¨embedding.of_surjective f hfβ©
theorem le_mk_iff_exists_set {c : cardinal} {Ξ± : Type u} :
c β€ mk Ξ± β β p : set Ξ±, mk p = c :=
β¨quotient.induction_on c $ Ξ» Ξ² β¨β¨f, hfβ©β©,
β¨set.range f, eq.symm $ quot.sound β¨equiv.set.range f hfβ©β©,
Ξ» β¨p, eβ©, e βΈ β¨β¨subtype.val, Ξ» a b, subtype.eqβ©β©β©
theorem out_embedding {c c' : cardinal} : c β€ c' β nonempty (c.out βͺ c'.out) :=
by { transitivity _, rw [βquotient.out_eq c, βquotient.out_eq c'], refl }
instance : linear_order cardinal.{u} :=
{ le := (β€),
le_refl := by rintros β¨Ξ±β©; exact β¨embedding.refl _β©,
le_trans := by rintros β¨Ξ±β© β¨Ξ²β© β¨Ξ³β© β¨eββ© β¨eββ©; exact β¨eβ.trans eββ©,
le_antisymm := by rintros β¨Ξ±β© β¨Ξ²β© β¨eββ© β¨eββ©; exact quotient.sound (eβ.antisymm eβ),
le_total := by rintros β¨Ξ±β© β¨Ξ²β©; exact embedding.total }
noncomputable instance : decidable_linear_order cardinal.{u} := classical.DLO _
noncomputable instance : distrib_lattice cardinal.{u} := by apply_instance -- short-circuit type class inference
instance : has_zero cardinal.{u} := β¨β¦pemptyβ§β©
instance : inhabited cardinal.{u} := β¨0β©
theorem ne_zero_iff_nonempty {Ξ± : Type u} : mk Ξ± β 0 β nonempty Ξ± :=
not_iff_comm.1
β¨Ξ» h, quotient.sound β¨(equiv.empty_of_not_nonempty h).trans equiv.empty_equiv_pemptyβ©,
Ξ» e, let β¨hβ© := quotient.exact e in Ξ» β¨aβ©, (h a).elimβ©
instance : has_one cardinal.{u} := β¨β¦punitβ§β©
instance : nontrivial cardinal.{u} :=
β¨β¨1, 0, ne_zero_iff_nonempty.2 β¨punit.starβ©β©β©
theorem le_one_iff_subsingleton {Ξ± : Type u} : mk Ξ± β€ 1 β subsingleton Ξ± :=
β¨Ξ» β¨fβ©, β¨Ξ» a b, f.injective (subsingleton.elim _ _)β©,
Ξ» β¨hβ©, β¨β¨Ξ» a, punit.star, Ξ» a b _, h _ _β©β©β©
theorem one_lt_iff_nontrivial {Ξ± : Type u} : 1 < mk Ξ± β nontrivial Ξ± :=
by { rw [β not_iff_not, not_nontrivial_iff_subsingleton, β le_one_iff_subsingleton], simp }
instance : has_add cardinal.{u} :=
β¨Ξ»qβ qβ, quotient.lift_onβ qβ qβ (λα Ξ², mk (Ξ± β Ξ²)) $ assume Ξ± Ξ² Ξ³ Ξ΄ β¨eββ© β¨eββ©,
quotient.sound β¨equiv.sum_congr eβ eββ©β©
@[simp] theorem add_def (Ξ± Ξ²) : mk Ξ± + mk Ξ² = mk (Ξ± β Ξ²) := rfl
instance : has_mul cardinal.{u} :=
β¨Ξ»qβ qβ, quotient.lift_onβ qβ qβ (λα Ξ², mk (Ξ± Γ Ξ²)) $ assume Ξ± Ξ² Ξ³ Ξ΄ β¨eββ© β¨eββ©,
quotient.sound β¨equiv.prod_congr eβ eββ©β©
@[simp] theorem mul_def (Ξ± Ξ² : Type u) : mk Ξ± * mk Ξ² = mk (Ξ± Γ Ξ²) := rfl
private theorem add_comm (a b : cardinal.{u}) : a + b = b + a :=
quotient.induction_onβ a b $ assume Ξ± Ξ², quotient.sound β¨equiv.sum_comm Ξ± Ξ²β©
private theorem mul_comm (a b : cardinal.{u}) : a * b = b * a :=
quotient.induction_onβ a b $ assume Ξ± Ξ², quotient.sound β¨equiv.prod_comm Ξ± Ξ²β©
private theorem zero_add (a : cardinal.{u}) : 0 + a = a :=
quotient.induction_on a $ assume Ξ±, quotient.sound β¨equiv.pempty_sum Ξ±β©
private theorem zero_mul (a : cardinal.{u}) : 0 * a = 0 :=
quotient.induction_on a $ assume Ξ±, quotient.sound β¨equiv.pempty_prod Ξ±β©
private theorem one_mul (a : cardinal.{u}) : 1 * a = a :=
quotient.induction_on a $ assume Ξ±, quotient.sound β¨equiv.punit_prod Ξ±β©
private theorem left_distrib (a b c : cardinal.{u}) : a * (b + c) = a * b + a * c :=
quotient.induction_onβ a b c $ assume Ξ± Ξ² Ξ³, quotient.sound β¨equiv.prod_sum_distrib Ξ± Ξ² Ξ³β©
instance : comm_semiring cardinal.{u} :=
{ zero := 0,
one := 1,
add := (+),
mul := (*),
zero_add := zero_add,
add_zero := assume a, by rw [add_comm a 0, zero_add a],
add_assoc := Ξ»a b c, quotient.induction_onβ a b c $ assume Ξ± Ξ² Ξ³,
quotient.sound β¨equiv.sum_assoc Ξ± Ξ² Ξ³β©,
add_comm := add_comm,
zero_mul := zero_mul,
mul_zero := assume a, by rw [mul_comm a 0, zero_mul a],
one_mul := one_mul,
mul_one := assume a, by rw [mul_comm a 1, one_mul a],
mul_assoc := Ξ»a b c, quotient.induction_onβ a b c $ assume Ξ± Ξ² Ξ³,
quotient.sound β¨equiv.prod_assoc Ξ± Ξ² Ξ³β©,
mul_comm := mul_comm,
left_distrib := left_distrib,
right_distrib := assume a b c,
by rw [mul_comm (a + b) c, left_distrib c a b, mul_comm c a, mul_comm c b] }
/-- The cardinal exponential. `mk Ξ± ^ mk Ξ²` is the cardinal of `Ξ² β Ξ±`. -/
protected def power (a b : cardinal.{u}) : cardinal.{u} :=
quotient.lift_onβ a b (λα Ξ², mk (Ξ² β Ξ±)) $ assume Ξ±β Ξ±β Ξ²β Ξ²β β¨eββ© β¨eββ©,
quotient.sound β¨equiv.arrow_congr eβ eββ©
instance : has_pow cardinal cardinal := β¨cardinal.powerβ©
local infixr ^ := @has_pow.pow cardinal cardinal cardinal.has_pow
@[simp] theorem power_def (Ξ± Ξ²) : mk Ξ± ^ mk Ξ² = mk (Ξ² β Ξ±) := rfl
@[simp] theorem power_zero {a : cardinal} : a ^ 0 = 1 :=
quotient.induction_on a $ assume Ξ±, quotient.sound
β¨equiv.pempty_arrow_equiv_punit Ξ±β©
@[simp] theorem power_one {a : cardinal} : a ^ 1 = a :=
quotient.induction_on a $ assume Ξ±, quotient.sound
β¨equiv.punit_arrow_equiv Ξ±β©
@[simp] theorem one_power {a : cardinal} : 1 ^ a = 1 :=
quotient.induction_on a $ assume Ξ±, quotient.sound
β¨equiv.arrow_punit_equiv_punit Ξ±β©
@[simp] theorem prop_eq_two : mk (ulift Prop) = 2 :=
quot.sound β¨equiv.ulift.trans $ equiv.Prop_equiv_bool.trans equiv.bool_equiv_punit_sum_punitβ©
@[simp] theorem zero_power {a : cardinal} : a β 0 β 0 ^ a = 0 :=
quotient.induction_on a $ assume Ξ± heq,
nonempty.rec_on (ne_zero_iff_nonempty.1 heq) $ assume a,
quotient.sound β¨equiv.equiv_pempty $ assume f, pempty.rec (Ξ» _, false) (f a)β©
theorem power_ne_zero {a : cardinal} (b) : a β 0 β a ^ b β 0 :=
quotient.induction_onβ a b $ Ξ» Ξ± Ξ² h,
let β¨aβ© := ne_zero_iff_nonempty.1 h in
ne_zero_iff_nonempty.2 β¨Ξ» _, aβ©
theorem mul_power {a b c : cardinal} : (a * b) ^ c = a ^ c * b ^ c :=
quotient.induction_onβ a b c $ assume Ξ± Ξ² Ξ³,
quotient.sound β¨equiv.arrow_prod_equiv_prod_arrow Ξ± Ξ² Ξ³β©
theorem power_add {a b c : cardinal} : a ^ (b + c) = a ^ b * a ^ c :=
quotient.induction_onβ a b c $ assume Ξ± Ξ² Ξ³,
quotient.sound β¨equiv.sum_arrow_equiv_prod_arrow Ξ² Ξ³ Ξ±β©
theorem power_mul {a b c : cardinal} : (a ^ b) ^ c = a ^ (b * c) :=
by rw [_root_.mul_comm b c];
from (quotient.induction_onβ a b c $ assume Ξ± Ξ² Ξ³,
quotient.sound β¨equiv.arrow_arrow_equiv_prod_arrow Ξ³ Ξ² Ξ±β©)
@[simp] lemma pow_cast_right (ΞΊ : cardinal.{u}) :
β n : β, (ΞΊ ^ (βn : cardinal.{u})) = @has_pow.pow _ _ monoid.has_pow ΞΊ n
| 0 := by simp
| (_+1) := by rw [nat.cast_succ, power_add, power_one, _root_.mul_comm, pow_succ, pow_cast_right]
section order_properties
open sum
theorem zero_le : β(a : cardinal), 0 β€ a :=
by rintro β¨Ξ±β©; exact β¨embedding.of_not_nonempty $ Ξ» β¨aβ©, a.elimβ©
theorem le_zero (a : cardinal) : a β€ 0 β a = 0 :=
by simp [le_antisymm_iff, zero_le]
theorem pos_iff_ne_zero {o : cardinal} : 0 < o β o β 0 :=
by simp [lt_iff_le_and_ne, eq_comm, zero_le]
@[simp] theorem zero_lt_one : (0 : cardinal) < 1 :=
lt_of_le_of_ne (zero_le _) zero_ne_one
lemma zero_power_le (c : cardinal.{u}) : (0 : cardinal.{u}) ^ c β€ 1 :=
by { by_cases h : c = 0, rw [h, power_zero], rw [zero_power h], apply zero_le }
theorem add_le_add : β{a b c d : cardinal}, a β€ b β c β€ d β a + c β€ b + d :=
by rintros β¨Ξ±β© β¨Ξ²β© β¨Ξ³β© β¨Ξ΄β© β¨eββ© β¨eββ©; exact β¨eβ.sum_map eββ©
theorem add_le_add_left (a) {b c : cardinal} : b β€ c β a + b β€ a + c :=
add_le_add (le_refl _)
theorem add_le_add_right {a b : cardinal} (c) (h : a β€ b) : a + c β€ b + c :=
add_le_add h (le_refl _)
theorem le_add_right (a b : cardinal) : a β€ a + b :=
by simpa using add_le_add_left a (zero_le b)
theorem le_add_left (a b : cardinal) : a β€ b + a :=
by simpa using add_le_add_right a (zero_le b)
theorem mul_le_mul : β{a b c d : cardinal}, a β€ b β c β€ d β a * c β€ b * d :=
by rintros β¨Ξ±β© β¨Ξ²β© β¨Ξ³β© β¨Ξ΄β© β¨eββ© β¨eββ©; exact β¨eβ.prod_map eββ©
theorem mul_le_mul_left (a) {b c : cardinal} : b β€ c β a * b β€ a * c :=
mul_le_mul (le_refl _)
theorem mul_le_mul_right {a b : cardinal} (c) (h : a β€ b) : a * c β€ b * c :=
mul_le_mul h (le_refl _)
theorem power_le_power_left : β{a b c : cardinal}, a β 0 β b β€ c β a ^ b β€ a ^ c :=
by rintros β¨Ξ±β© β¨Ξ²β© β¨Ξ³β© hΞ± β¨eβ©; exact
let β¨aβ© := ne_zero_iff_nonempty.1 hΞ± in
β¨@embedding.arrow_congr_right _ _ _ β¨aβ© eβ©
theorem power_le_max_power_one {a b c : cardinal} (h : b β€ c) : a ^ b β€ max (a ^ c) 1 :=
begin
by_cases ha : a = 0,
simp [ha, zero_power_le],
exact le_trans (power_le_power_left ha h) (le_max_left _ _)
end
theorem power_le_power_right {a b c : cardinal} : a β€ b β a ^ c β€ b ^ c :=
quotient.induction_onβ a b c $ assume Ξ± Ξ² Ξ³ β¨eβ©, β¨embedding.arrow_congr_left eβ©
theorem le_iff_exists_add {a b : cardinal} : a β€ b β β c, b = a + c :=
β¨quotient.induction_onβ a b $ Ξ» Ξ± Ξ² β¨β¨f, hfβ©β©,
have (Ξ± β ((range f)αΆ : set Ξ²)) β Ξ², from
(equiv.sum_congr (equiv.set.range f hf) (equiv.refl _)).trans $
(equiv.set.sum_compl (range f)),
β¨β¦β₯(range f)αΆβ§, quotient.sound β¨this.symmβ©β©,
Ξ» β¨c, eβ©, add_zero a βΈ e.symm βΈ add_le_add_left _ (zero_le _)β©
end order_properties
instance : order_bot cardinal.{u} :=
{ bot := 0, bot_le := zero_le, ..cardinal.linear_order }
instance : canonically_ordered_add_monoid cardinal.{u} :=
{ add_le_add_left := Ξ» a b h c, add_le_add_left _ h,
lt_of_add_lt_add_left := Ξ» a b c, lt_imp_lt_of_le_imp_le (add_le_add_left _),
le_iff_exists_add := @le_iff_exists_add,
..cardinal.order_bot,
..cardinal.comm_semiring, ..cardinal.linear_order }
theorem cantor : β(a : cardinal.{u}), a < 2 ^ a :=
by rw β prop_eq_two; rintros β¨aβ©; exact β¨
β¨β¨Ξ» a b, β¨a = bβ©, Ξ» a b h, cast (ulift.up.inj (@congr_fun _ _ _ _ h b)).symm rflβ©β©,
Ξ» β¨β¨f, hfβ©β©, cantor_injective (Ξ» s, f (Ξ» a, β¨s aβ©)) $
Ξ» s t h, by funext a; injection congr_fun (hf h) aβ©
instance : no_top_order cardinal.{u} :=
{ no_top := Ξ» a, β¨_, cantor aβ©, ..cardinal.linear_order }
/-- The minimum cardinal in a family of cardinals (the existence
of which is provided by `injective_min`). -/
noncomputable def min {ΞΉ} (I : nonempty ΞΉ) (f : ΞΉ β cardinal) : cardinal :=
f $ classical.some $
@embedding.min_injective _ (Ξ» i, (f i).out) I
theorem min_eq {ΞΉ} (I) (f : ΞΉ β cardinal) : β i, min I f = f i :=
β¨_, rflβ©
theorem min_le {ΞΉ I} (f : ΞΉ β cardinal) (i) : min I f β€ f i :=
by rw [β mk_out (min I f), β mk_out (f i)]; exact
let β¨gβ© := classical.some_spec
(@embedding.min_injective _ (Ξ» i, (f i).out) I) in
β¨g iβ©
theorem le_min {ΞΉ I} {f : ΞΉ β cardinal} {a} : a β€ min I f β β i, a β€ f i :=
β¨Ξ» h i, le_trans h (min_le _ _),
Ξ» h, let β¨i, eβ© := min_eq I f in e.symm βΈ h iβ©
protected theorem wf : @well_founded cardinal.{u} (<) :=
β¨Ξ» a, classical.by_contradiction $ Ξ» h,
let ΞΉ := {c :cardinal // Β¬ acc (<) c},
f : ΞΉ β cardinal := subtype.val,
β¨β¨c, hcβ©, hiβ© := @min_eq ΞΉ β¨β¨_, hβ©β© f in
hc (acc.intro _ (Ξ» j β¨_, h'β©,
classical.by_contradiction $ Ξ» hj, h' $
by have := min_le f β¨j, hjβ©; rwa hi at this))β©
instance has_wf : @has_well_founded cardinal.{u} := β¨(<), cardinal.wfβ©
instance wo : @is_well_order cardinal.{u} (<) := β¨cardinal.wfβ©
/-- The successor cardinal - the smallest cardinal greater than
`c`. This is not the same as `c + 1` except in the case of finite `c`. -/
noncomputable def succ (c : cardinal) : cardinal :=
@min {c' // c < c'} β¨β¨_, cantor _β©β© subtype.val
theorem lt_succ_self (c : cardinal) : c < succ c :=
by cases min_eq _ _ with s e; rw [succ, e]; exact s.2
theorem succ_le {a b : cardinal} : succ a β€ b β a < b :=
β¨lt_of_lt_of_le (lt_succ_self _), Ξ» h,
by exact min_le _ (subtype.mk b h)β©
theorem lt_succ {a b : cardinal} : a < succ b β a β€ b :=
by rw [β not_le, succ_le, not_lt]
theorem add_one_le_succ (c : cardinal) : c + 1 β€ succ c :=
begin
refine quot.induction_on c (Ξ» Ξ±, _) (lt_succ_self c),
refine quot.induction_on (succ (quot.mk setoid.r Ξ±)) (Ξ» Ξ² h, _),
cases h.left with f,
have : Β¬ surjective f := Ξ» hn,
ne_of_lt h (quotient.sound β¨equiv.of_bijective f β¨f.injective, hnβ©β©),
cases not_forall.1 this with b nex,
refine β¨β¨sum.rec (by exact f) _, _β©β©,
{ exact Ξ» _, b },
{ intros a b h, rcases a with a|β¨β¨β¨β©β©β©; rcases b with b|β¨β¨β¨β©β©β©,
{ rw f.injective h },
{ exact nex.elim β¨_, hβ© },
{ exact nex.elim β¨_, h.symmβ© },
{ refl } }
end
lemma succ_ne_zero (c : cardinal) : succ c β 0 :=
by { rw [βpos_iff_ne_zero, lt_succ], apply zero_le }
/-- The indexed sum of cardinals is the cardinality of the
indexed disjoint union, i.e. sigma type. -/
def sum {ΞΉ} (f : ΞΉ β cardinal) : cardinal := mk Ξ£ i, (f i).out
theorem le_sum {ΞΉ} (f : ΞΉ β cardinal) (i) : f i β€ sum f :=
by rw β quotient.out_eq (f i); exact
β¨β¨Ξ» a, β¨i, aβ©, Ξ» a b h, eq_of_heq $ by injection hβ©β©
@[simp] theorem sum_mk {ΞΉ} (f : ΞΉ β Type*) : sum (Ξ» i, mk (f i)) = mk (Ξ£ i, f i) :=
quot.sound β¨equiv.sigma_congr_right $ Ξ» i,
classical.choice $ quotient.exact $ quot.out_eq $ mk (f i)β©
theorem sum_const (ΞΉ : Type u) (a : cardinal.{u}) : sum (Ξ» _:ΞΉ, a) = mk ΞΉ * a :=
quotient.induction_on a $ Ξ» Ξ±, by simp; exact
quotient.sound β¨equiv.sigma_equiv_prod _ _β©
theorem sum_le_sum {ΞΉ} (f g : ΞΉ β cardinal) (H : β i, f i β€ g i) : sum f β€ sum g :=
β¨(embedding.refl _).sigma_map $ Ξ» i, classical.choice $
by have := H i; rwa [β quot.out_eq (f i), β quot.out_eq (g i)] at thisβ©
/-- The indexed supremum of cardinals is the smallest cardinal above
everything in the family. -/
noncomputable def sup {ΞΉ} (f : ΞΉ β cardinal) : cardinal :=
@min {c // β i, f i β€ c} β¨β¨sum f, le_sum fβ©β© (Ξ» a, a.1)
theorem le_sup {ΞΉ} (f : ΞΉ β cardinal) (i) : f i β€ sup f :=
by dsimp [sup]; cases min_eq _ _ with c hc; rw hc; exact c.2 i
theorem sup_le {ΞΉ} {f : ΞΉ β cardinal} {a} : sup f β€ a β β i, f i β€ a :=
β¨Ξ» h i, le_trans (le_sup _ _) h,
Ξ» h, by dsimp [sup]; change a with (β¨a, hβ©:subtype _).1; apply min_leβ©
theorem sup_le_sup {ΞΉ} (f g : ΞΉ β cardinal) (H : β i, f i β€ g i) : sup f β€ sup g :=
sup_le.2 $ Ξ» i, le_trans (H i) (le_sup _ _)
theorem sup_le_sum {ΞΉ} (f : ΞΉ β cardinal) : sup f β€ sum f :=
sup_le.2 $ le_sum _
theorem sum_le_sup {ΞΉ : Type u} (f : ΞΉ β cardinal.{u}) : sum f β€ mk ΞΉ * sup.{u u} f :=
by rw β sum_const; exact sum_le_sum _ _ (le_sup _)
theorem sup_eq_zero {ΞΉ} {f : ΞΉ β cardinal} (h : ΞΉ β false) : sup f = 0 :=
by { rw [βle_zero, sup_le], intro x, exfalso, exact h x }
/-- The indexed product of cardinals is the cardinality of the Pi type
(dependent product). -/
def prod {ΞΉ : Type u} (f : ΞΉ β cardinal) : cardinal := mk (Ξ i, (f i).out)
@[simp] theorem prod_mk {ΞΉ} (f : ΞΉ β Type*) : prod (Ξ» i, mk (f i)) = mk (Ξ i, f i) :=
quot.sound β¨equiv.Pi_congr_right $ Ξ» i,
classical.choice $ quotient.exact $ mk_out $ mk (f i)β©
theorem prod_const (ΞΉ : Type u) (a : cardinal.{u}) : prod (Ξ» _:ΞΉ, a) = a ^ mk ΞΉ :=
quotient.induction_on a $ by simp
theorem prod_le_prod {ΞΉ} (f g : ΞΉ β cardinal) (H : β i, f i β€ g i) : prod f β€ prod g :=
β¨embedding.Pi_congr_right $ Ξ» i, classical.choice $
by have := H i; rwa [β mk_out (f i), β mk_out (g i)] at thisβ©
theorem prod_ne_zero {ΞΉ} (f : ΞΉ β cardinal) : prod f β 0 β β i, f i β 0 :=
begin
conv in (f _) {rw β mk_out (f i)},
simp [prod, ne_zero_iff_nonempty, -mk_out, -ne.def],
exact β¨Ξ» β¨Fβ© i, β¨F iβ©, Ξ» h, β¨Ξ» i, classical.choice (h i)β©β©,
end
theorem prod_eq_zero {ΞΉ} (f : ΞΉ β cardinal) : prod f = 0 β β i, f i = 0 :=
not_iff_not.1 $ by simpa using prod_ne_zero f
/-- The universe lift operation on cardinals. You can specify the universes explicitly with
`lift.{u v} : cardinal.{u} β cardinal.{max u v}` -/
def lift (c : cardinal.{u}) : cardinal.{max u v} :=
quotient.lift_on c (Ξ» Ξ±, β¦ulift Ξ±β§) $ Ξ» Ξ± Ξ² β¨eβ©,
quotient.sound β¨equiv.ulift.trans $ e.trans equiv.ulift.symmβ©
theorem lift_mk (Ξ±) : lift.{u v} (mk Ξ±) = mk (ulift.{v u} Ξ±) := rfl
theorem lift_umax : lift.{u (max u v)} = lift.{u v} :=
funext $ Ξ» a, quot.induction_on a $ Ξ» Ξ±,
quotient.sound β¨equiv.ulift.trans equiv.ulift.symmβ©
theorem lift_id' (a : cardinal) : lift a = a :=
quot.induction_on a $ Ξ» Ξ±, quot.sound β¨equiv.uliftβ©
@[simp] theorem lift_id : β a, lift.{u u} a = a := lift_id'.{u u}
@[simp] theorem lift_lift (a : cardinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a :=
quot.induction_on a $ Ξ» Ξ±,
quotient.sound β¨equiv.ulift.trans $ equiv.ulift.trans equiv.ulift.symmβ©
theorem lift_mk_le {Ξ± : Type u} {Ξ² : Type v} :
lift.{u (max v w)} (mk Ξ±) β€ lift.{v (max u w)} (mk Ξ²) β nonempty (Ξ± βͺ Ξ²) :=
β¨Ξ» β¨fβ©, β¨embedding.congr equiv.ulift equiv.ulift fβ©,
Ξ» β¨fβ©, β¨embedding.congr equiv.ulift.symm equiv.ulift.symm fβ©β©
theorem lift_mk_eq {Ξ± : Type u} {Ξ² : Type v} :
lift.{u (max v w)} (mk Ξ±) = lift.{v (max u w)} (mk Ξ²) β nonempty (Ξ± β Ξ²) :=
quotient.eq.trans
β¨Ξ» β¨fβ©, β¨equiv.ulift.symm.trans $ f.trans equiv.uliftβ©,
Ξ» β¨fβ©, β¨equiv.ulift.trans $ f.trans equiv.ulift.symmβ©β©
@[simp] theorem lift_le {a b : cardinal} : lift a β€ lift b β a β€ b :=
quotient.induction_onβ a b $ Ξ» Ξ± Ξ²,
by rw β lift_umax; exact lift_mk_le
@[simp] theorem lift_inj {a b : cardinal} : lift a = lift b β a = b :=
by simp [le_antisymm_iff]
@[simp] theorem lift_lt {a b : cardinal} : lift a < lift b β a < b :=
by simp [lt_iff_le_not_le, -not_le]
@[simp] theorem lift_zero : lift 0 = 0 :=
quotient.sound β¨equiv.ulift.trans equiv.pempty_equiv_pemptyβ©
@[simp] theorem lift_one : lift 1 = 1 :=
quotient.sound β¨equiv.ulift.trans equiv.punit_equiv_punitβ©
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_onβ a b $ Ξ» Ξ± Ξ²,
quotient.sound β¨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symmβ©
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_onβ a b $ Ξ» Ξ± Ξ²,
quotient.sound β¨equiv.ulift.trans (equiv.prod_congr equiv.ulift equiv.ulift).symmβ©
@[simp] theorem lift_power (a b) : lift (a ^ b) = lift a ^ lift b :=
quotient.induction_onβ a b $ Ξ» Ξ± Ξ²,
quotient.sound β¨equiv.ulift.trans (equiv.arrow_congr equiv.ulift equiv.ulift).symmβ©
@[simp] theorem lift_two_power (a) : lift (2 ^ a) = 2 ^ lift a :=
by simp [bit0]
@[simp] theorem lift_min {ΞΉ I} (f : ΞΉ β cardinal) : lift (min I f) = min I (lift β f) :=
le_antisymm (le_min.2 $ Ξ» a, lift_le.2 $ min_le _ a) $
let β¨i, eβ© := min_eq I (lift β f) in
by rw e; exact lift_le.2 (le_min.2 $ Ξ» j, lift_le.1 $
by have := min_le (lift β f) j; rwa e at this)
theorem lift_down {a : cardinal.{u}} {b : cardinal.{max u v}} :
b β€ lift a β β a', lift a' = b :=
quotient.induction_onβ a b $ Ξ» Ξ± Ξ²,
by dsimp; rw [β lift_id (mk Ξ²), β lift_umax, β lift_umax.{u v}, lift_mk_le]; exact
Ξ» β¨fβ©, β¨mk (set.range f), eq.symm $ lift_mk_eq.2
β¨embedding.equiv_of_surjective
(embedding.cod_restrict _ f set.mem_range_self)
$ Ξ» β¨a, β¨b, eβ©β©, β¨b, subtype.eq eβ©β©β©
theorem le_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b β€ lift a β β a', lift a' = b β§ a' β€ a :=
β¨Ξ» h, let β¨a', eβ© := lift_down h in β¨a', e, lift_le.1 $ e.symm βΈ hβ©,
Ξ» β¨a', e, hβ©, e βΈ lift_le.2 hβ©
theorem lt_lift_iff {a : cardinal.{u}} {b : cardinal.{max u v}} :
b < lift a β β a', lift a' = b β§ a' < a :=
β¨Ξ» h, let β¨a', eβ© := lift_down (le_of_lt h) in
β¨a', e, lift_lt.1 $ e.symm βΈ hβ©,
Ξ» β¨a', e, hβ©, e βΈ lift_lt.2 hβ©
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
le_antisymm
(le_of_not_gt $ Ξ» h, begin
rcases lt_lift_iff.1 h with β¨b, e, hβ©,
rw [lt_succ, β lift_le, e] at h,
exact not_lt_of_le h (lt_succ_self _)
end)
(succ_le.2 $ lift_lt.2 $ lt_succ_self _)
@[simp] theorem lift_max {a : cardinal.{u}} {b : cardinal.{v}} :
lift.{u (max v w)} a = lift.{v (max u w)} b β lift.{u v} a = lift.{v u} b :=
calc lift.{u (max v w)} a = lift.{v (max u w)} b
β lift.{(max u v) w} (lift.{u v} a)
= lift.{(max u v) w} (lift.{v u} b) : by simp
... β lift.{u v} a = lift.{v u} b : lift_inj
theorem mk_prod {Ξ± : Type u} {Ξ² : Type v} :
mk (Ξ± Γ Ξ²) = lift.{u v} (mk Ξ±) * lift.{v u} (mk Ξ²) :=
quotient.sound β¨equiv.prod_congr (equiv.ulift).symm (equiv.ulift).symmβ©
theorem sum_const_eq_lift_mul (ΞΉ : Type u) (a : cardinal.{v}) :
sum (Ξ» _:ΞΉ, a) = lift.{u v} (mk ΞΉ) * lift.{v u} a :=
begin
apply quotient.induction_on a,
intro Ξ±,
simp only [cardinal.mk_def, cardinal.sum_mk, cardinal.lift_id],
convert mk_prod using 1,
exact quotient.sound β¨equiv.sigma_equiv_prod ΞΉ Ξ±β©,
end
/-- `Ο` is the smallest infinite cardinal, also known as β΅β. -/
def omega : cardinal.{u} := lift (mk β)
lemma mk_nat : mk nat = omega := (lift_id _).symm
theorem omega_ne_zero : omega β 0 :=
ne_zero_iff_nonempty.2 β¨β¨0β©β©
theorem omega_pos : 0 < omega :=
pos_iff_ne_zero.2 omega_ne_zero
@[simp] theorem lift_omega : lift omega = omega := lift_lift _
/- properties about the cast from nat -/
@[simp] theorem mk_fin : β (n : β), mk (fin n) = n
| 0 := quotient.sound β¨(equiv.pempty_of_not_nonempty $ Ξ» β¨hβ©, h.elim0)β©
| (n+1) := by rw [nat.cast_succ, β mk_fin]; exact
quotient.sound (fintype.card_eq.1 $ by simp)
@[simp] theorem lift_nat_cast (n : β) : lift n = n :=
by induction n; simp *
lemma lift_eq_nat_iff {a : cardinal.{u}} {n : β} : lift.{u v} a = n β a = n :=
by rw [β lift_nat_cast.{u v} n, lift_inj]
lemma nat_eq_lift_eq_iff {n : β} {a : cardinal.{u}} :
(n : cardinal) = lift.{u v} a β (n : cardinal) = a :=
by rw [β lift_nat_cast.{u v} n, lift_inj]
theorem lift_mk_fin (n : β) : lift (mk (fin n)) = n := by simp
theorem fintype_card (Ξ± : Type u) [fintype Ξ±] : mk Ξ± = fintype.card Ξ± :=
by rw [β lift_mk_fin.{u}, β lift_id (mk Ξ±), lift_mk_eq.{u 0 u}];
exact fintype.card_eq.1 (by simp)
theorem card_le_of_finset {Ξ±} (s : finset Ξ±) :
(s.card : cardinal) β€ cardinal.mk Ξ± :=
begin
rw (_ : (s.card : cardinal) = cardinal.mk (βs : set Ξ±)),
{ exact β¨function.embedding.subtype _β© },
rw [cardinal.fintype_card, fintype.card_coe]
end
@[simp, norm_cast] theorem nat_cast_pow {m n : β} : (β(pow m n) : cardinal) = m ^ n :=
by induction n; simp [nat.pow_succ, -_root_.add_comm, power_add, *]
@[simp, norm_cast] theorem nat_cast_le {m n : β} : (m : cardinal) β€ n β m β€ n :=
by rw [β lift_mk_fin, β lift_mk_fin, lift_le]; exact
β¨Ξ» β¨β¨f, hfβ©β©, begin
have : _ = fintype.card _ := finset.card_image_of_injective finset.univ hf,
simp at this,
rw [β fintype.card_fin n, β this],
exact finset.card_le_of_subset (finset.subset_univ _)
end,
Ξ» h, β¨β¨Ξ» i, β¨i.1, lt_of_lt_of_le i.2 hβ©, Ξ» a b h,
have _, from fin.veq_of_eq h, fin.eq_of_veq thisβ©β©β©
@[simp, norm_cast] theorem nat_cast_lt {m n : β} : (m : cardinal) < n β m < n :=
by simp [lt_iff_le_not_le, -not_le]
@[simp, norm_cast] theorem nat_cast_inj {m n : β} : (m : cardinal) = n β m = n :=
by simp [le_antisymm_iff]
@[simp, norm_cast, priority 900] theorem nat_succ (n : β) : (n.succ : cardinal) = succ n :=
le_antisymm (add_one_le_succ _) (succ_le.2 $ nat_cast_lt.2 $ nat.lt_succ_self _)
@[simp] theorem succ_zero : succ 0 = 1 :=
by norm_cast
theorem cantor' (a) {b : cardinal} (hb : 1 < b) : a < b ^ a :=
by rw [β succ_le, (by norm_cast : succ 1 = 2)] at hb;
exact lt_of_lt_of_le (cantor _) (power_le_power_right hb)
theorem one_le_iff_pos {c : cardinal} : 1 β€ c β 0 < c :=
by rw [β succ_zero, succ_le]
theorem one_le_iff_ne_zero {c : cardinal} : 1 β€ c β c β 0 :=
by rw [one_le_iff_pos, pos_iff_ne_zero]
theorem nat_lt_omega (n : β) : (n : cardinal.{u}) < omega :=
succ_le.1 $ by rw [β nat_succ, β lift_mk_fin, omega, lift_mk_le.{0 0 u}]; exact
β¨β¨coe, Ξ» a b, fin.extβ©β©
@[simp] theorem one_lt_omega : 1 < omega :=
by simpa using nat_lt_omega 1
theorem lt_omega {c : cardinal.{u}} : c < omega β β n : β, c = n :=
β¨Ξ» h, begin
rcases lt_lift_iff.1 h with β¨c, rfl, h'β©,
rcases le_mk_iff_exists_set.1 h'.1 with β¨S, rflβ©,
suffices : finite S,
{ cases this, resetI,
existsi fintype.card S,
rw [β lift_nat_cast.{0 u}, lift_inj, fintype_card S] },
by_contra nf,
have P : β (n : β) (IH : β i<n, S), β a : S, Β¬ β y h, IH y h = a :=
Ξ» n IH,
let g : {i | i < n} β S := Ξ» β¨i, hβ©, IH i h in
not_forall.1 (Ξ» h, nf
β¨fintype.of_surjective g (Ξ» a, subtype.exists.2 (h a))β©),
let F : β β S := nat.lt_wf.fix (Ξ» n IH, classical.some (P n IH)),
refine not_le_of_lt h' β¨β¨F, _β©β©,
suffices : β (n : β) (m < n), F m β F n,
{ refine Ξ» m n, not_imp_not.1 (Ξ» ne, _),
rcases lt_trichotomy m n with h|h|h,
{ exact this n m h },
{ contradiction },
{ exact (this m n h).symm } },
intros n m h,
have := classical.some_spec (P n (Ξ» y _, F y)),
rw [β show F n = classical.some (P n (Ξ» y _, F y)),
from nat.lt_wf.fix_eq (Ξ» n IH, classical.some (P n IH)) n] at this,
exact Ξ» e, this β¨m, h, eβ©,
end, Ξ» β¨n, eβ©, e.symm βΈ nat_lt_omega _β©
theorem omega_le {c : cardinal.{u}} : omega β€ c β β n : β, (n:cardinal) β€ c :=
β¨Ξ» h n, le_trans (le_of_lt (nat_lt_omega _)) h,
Ξ» h, le_of_not_lt $ Ξ» hn, begin
rcases lt_omega.1 hn with β¨n, rflβ©,
exact not_le_of_lt (nat.lt_succ_self _) (nat_cast_le.1 (h (n+1)))
endβ©
theorem lt_omega_iff_fintype {Ξ± : Type u} : mk Ξ± < omega β nonempty (fintype Ξ±) :=
lt_omega.trans β¨Ξ» β¨n, eβ©, begin
rw [β lift_mk_fin n] at e,
cases quotient.exact e with f,
exact β¨fintype.of_equiv _ f.symmβ©
end, Ξ» β¨_β©, by exactI β¨_, fintype_card _β©β©
theorem lt_omega_iff_finite {Ξ±} {S : set Ξ±} : mk S < omega β finite S :=
lt_omega_iff_fintype
instance can_lift_cardinal_nat : can_lift cardinal β :=
β¨ coe, Ξ» x, x < omega, Ξ» x hx, let β¨n, hnβ© := lt_omega.mp hx in β¨n, hn.symmβ©β©
theorem add_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a + b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, β¨m, rflβ©, β¨n, rflβ© := by rw [β nat.cast_add]; apply nat_lt_omega
end
lemma add_lt_omega_iff {a b : cardinal} : a + b < omega β a < omega β§ b < omega :=
β¨Ξ» h, β¨lt_of_le_of_lt (le_add_right _ _) h, lt_of_le_of_lt (le_add_left _ _) hβ©,
Ξ»β¨h1, h2β©, add_lt_omega h1 h2β©
theorem mul_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a * b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, β¨m, rflβ©, β¨n, rflβ© := by rw [β nat.cast_mul]; apply nat_lt_omega
end
lemma mul_lt_omega_iff {a b : cardinal} : a * b < omega β a = 0 β¨ b = 0 β¨ a < omega β§ b < omega :=
begin
split,
{ intro h, by_cases ha : a = 0, { left, exact ha },
right, by_cases hb : b = 0, { left, exact hb },
right, rw [β ne, β one_le_iff_ne_zero] at ha hb, split,
{ rw [β mul_one a], refine lt_of_le_of_lt (mul_le_mul (le_refl a) hb) h },
{ rw [β _root_.one_mul b], refine lt_of_le_of_lt (mul_le_mul ha (le_refl b)) h }},
rintro (rfl|rfl|β¨ha,hbβ©); simp only [*, mul_lt_omega, omega_pos, _root_.zero_mul, mul_zero]
end
lemma mul_lt_omega_iff_of_ne_zero {a b : cardinal} (ha : a β 0) (hb : b β 0) :
a * b < omega β a < omega β§ b < omega :=
by simp [mul_lt_omega_iff, ha, hb]
theorem power_lt_omega {a b : cardinal} (ha : a < omega) (hb : b < omega) : a ^ b < omega :=
match a, b, lt_omega.1 ha, lt_omega.1 hb with
| _, _, β¨m, rflβ©, β¨n, rflβ© := by rw [β nat_cast_pow]; apply nat_lt_omega
end
lemma eq_one_iff_subsingleton_and_nonempty {Ξ± : Type*} :
mk Ξ± = 1 β (subsingleton Ξ± β§ nonempty Ξ±) :=
calc mk Ξ± = 1 β mk Ξ± β€ 1 β§ Β¬mk Ξ± < 1 : eq_iff_le_not_lt
... β subsingleton Ξ± β§ nonempty Ξ± :
begin
apply and_congr le_one_iff_subsingleton,
push_neg,
rw [one_le_iff_ne_zero, ne_zero_iff_nonempty]
end
theorem infinite_iff {Ξ± : Type u} : infinite Ξ± β omega β€ mk Ξ± :=
by rw [βnot_lt, lt_omega_iff_fintype, not_nonempty_fintype]
lemma countable_iff (s : set Ξ±) : countable s β mk s β€ omega :=
begin
rw [countable_iff_exists_injective], split,
rintro β¨f, hfβ©, exact β¨embedding.trans β¨f, hfβ© equiv.ulift.symm.to_embeddingβ©,
rintro β¨f'β©, cases embedding.trans f' equiv.ulift.to_embedding with f hf, exact β¨f, hfβ©
end
lemma denumerable_iff {Ξ± : Type u} : nonempty (denumerable Ξ±) β mk Ξ± = omega :=
β¨Ξ»β¨hβ©, quotient.sound $ by exactI β¨ (denumerable.eqv Ξ±).trans equiv.ulift.symm β©,
Ξ» h, by { cases quotient.exact h with f, exact β¨denumerable.mk' $ f.trans equiv.uliftβ© }β©
lemma mk_int : mk β€ = omega :=
denumerable_iff.mp β¨by apply_instanceβ©
lemma mk_pnat : mk β+ = omega :=
denumerable_iff.mp β¨by apply_instanceβ©
lemma two_le_iff : (2 : cardinal) β€ mk Ξ± β βx y : Ξ±, x β y :=
begin
split,
{ rintro β¨fβ©, refine β¨f $ sum.inl β¨β©, f $ sum.inr β¨β©, _β©, intro h, cases f.2 h },
{ rintro β¨x, y, hβ©, by_contra h',
rw [not_le, βnat.cast_two, nat_succ, lt_succ, nat.cast_one, le_one_iff_subsingleton] at h',
apply h, exactI subsingleton.elim _ _ }
end
lemma two_le_iff' (x : Ξ±) : (2 : cardinal) β€ mk Ξ± β βy : Ξ±, x β y :=
begin
rw [two_le_iff],
split,
{ rintro β¨y, z, hβ©, refine classical.by_cases (Ξ»(h' : x = y), _) (Ξ» h', β¨y, h'β©),
rw [βh'] at h, exact β¨z, hβ© },
{ rintro β¨y, hβ©, exact β¨x, y, hβ© }
end
/-- KΓΆnig's theorem -/
theorem sum_lt_prod {ΞΉ} (f g : ΞΉ β cardinal) (H : β i, f i < g i) : sum f < prod g :=
lt_of_not_ge $ Ξ» β¨Fβ©, begin
have : inhabited (Ξ (i : ΞΉ), (g i).out),
{ refine β¨Ξ» i, classical.choice $ ne_zero_iff_nonempty.1 _β©,
rw mk_out,
exact ne_of_gt (lt_of_le_of_lt (zero_le _) (H i)) }, resetI,
let G := inv_fun F,
have sG : surjective G := inv_fun_surjective F.2,
choose C hc using show β i, β b, β a, G β¨i, aβ© i β b,
{ assume i,
simp only [- not_exists, not_exists.symm, not_forall.symm],
refine Ξ» h, not_le_of_lt (H i) _,
rw [β mk_out (f i), β mk_out (g i)],
exact β¨embedding.of_surjective _ hβ© },
exact (let β¨β¨i, aβ©, hβ© := sG C in hc i a (congr_fun h _))
end
@[simp] theorem mk_empty : mk empty = 0 :=
fintype_card empty
@[simp] theorem mk_pempty : mk pempty = 0 :=
fintype_card pempty
@[simp] theorem mk_plift_of_false {p : Prop} (h : Β¬ p) : mk (plift p) = 0 :=
quotient.sound β¨equiv.plift.trans $ equiv.equiv_pempty hβ©
theorem mk_unit : mk unit = 1 :=
(fintype_card unit).trans nat.cast_one
@[simp] theorem mk_punit : mk punit = 1 :=
(fintype_card punit).trans nat.cast_one
@[simp] theorem mk_singleton {Ξ± : Type u} (x : Ξ±) : mk ({x} : set Ξ±) = 1 :=
quotient.sound β¨equiv.set.singleton xβ©
@[simp] theorem mk_plift_of_true {p : Prop} (h : p) : mk (plift p) = 1 :=
quotient.sound β¨equiv.plift.trans $ equiv.prop_equiv_punit hβ©
@[simp] theorem mk_bool : mk bool = 2 :=
quotient.sound β¨equiv.bool_equiv_punit_sum_punitβ©
@[simp] theorem mk_Prop : mk Prop = 2 :=
(quotient.sound β¨equiv.Prop_equiv_boolβ© : mk Prop = mk bool).trans mk_bool
@[simp] theorem mk_option {Ξ± : Type u} : mk (option Ξ±) = mk Ξ± + 1 :=
quotient.sound β¨equiv.option_equiv_sum_punit Ξ±β©
theorem mk_list_eq_sum_pow (Ξ± : Type u) : mk (list Ξ±) = sum (Ξ» n : β, (mk Ξ±)^(n:cardinal.{u})) :=
calc mk (list Ξ±)
= mk (Ξ£ n, vector Ξ± n) : quotient.sound β¨(equiv.sigma_preimage_equiv list.length).symmβ©
... = mk (Ξ£ n, fin n β Ξ±) : quotient.sound β¨equiv.sigma_congr_right $ Ξ» n,
β¨vector.nth, vector.of_fn, vector.of_fn_nth, Ξ» f, funext $ vector.nth_of_fn fβ©β©
... = mk (Ξ£ n : β, ulift.{u} (fin n) β Ξ±) : quotient.sound β¨equiv.sigma_congr_right $ Ξ» n,
equiv.arrow_congr equiv.ulift.symm (equiv.refl Ξ±)β©
... = sum (Ξ» n : β, (mk Ξ±)^(n:cardinal.{u})) : by simp only [(lift_mk_fin _).symm, lift_mk, power_def, sum_mk]
theorem mk_quot_le {Ξ± : Type u} {r : Ξ± β Ξ± β Prop} : mk (quot r) β€ mk Ξ± :=
mk_le_of_surjective quot.exists_rep
theorem mk_quotient_le {Ξ± : Type u} {s : setoid Ξ±} : mk (quotient s) β€ mk Ξ± :=
mk_quot_le
theorem mk_subtype_le {Ξ± : Type u} (p : Ξ± β Prop) : mk (subtype p) β€ mk Ξ± :=
β¨embedding.subtype pβ©
theorem mk_subtype_le_of_subset {Ξ± : Type u} {p q : Ξ± β Prop} (h : β β¦xβ¦, p x β q x) :
mk (subtype p) β€ mk (subtype q) :=
β¨embedding.subtype_map (embedding.refl Ξ±) hβ©
@[simp] theorem mk_emptyc (Ξ± : Type u) : mk (β
: set Ξ±) = 0 :=
quotient.sound β¨equiv.set.pempty Ξ±β©
lemma mk_emptyc_iff {Ξ± : Type u} {s : set Ξ±} : mk s = 0 β s = β
:=
begin
split,
{ intro h,
have h2 : cardinal.mk s = cardinal.mk pempty, by simp [h],
refine set.eq_empty_iff_forall_not_mem.mpr (Ξ» _ hx, _),
rcases cardinal.eq.mp h2 with β¨f, _β©,
cases f β¨_, hxβ© },
{ intro, convert mk_emptyc _ }
end
theorem mk_univ {Ξ± : Type u} : mk (@univ Ξ±) = mk Ξ± :=
quotient.sound β¨equiv.set.univ Ξ±β©
theorem mk_image_le {Ξ± Ξ² : Type u} {f : Ξ± β Ξ²} {s : set Ξ±} : mk (f '' s) β€ mk s :=
mk_le_of_surjective surjective_onto_image
theorem mk_image_le_lift {Ξ± : Type u} {Ξ² : Type v} {f : Ξ± β Ξ²} {s : set Ξ±} :
lift.{v u} (mk (f '' s)) β€ lift.{u v} (mk s) :=
lift_mk_le.{v u 0}.mpr β¨embedding.of_surjective _ surjective_onto_imageβ©
theorem mk_range_le {Ξ± Ξ² : Type u} {f : Ξ± β Ξ²} : mk (range f) β€ mk Ξ± :=
mk_le_of_surjective surjective_onto_range
lemma mk_range_eq (f : Ξ± β Ξ²) (h : injective f) : mk (range f) = mk Ξ± :=
quotient.sound β¨(equiv.set.range f h).symmβ©
lemma mk_range_eq_of_injective {Ξ± : Type u} {Ξ² : Type v} {f : Ξ± β Ξ²} (hf : injective f) :
lift.{v u} (mk (range f)) = lift.{u v} (mk Ξ±) :=
begin
have := (@lift_mk_eq.{v u max u v} (range f) Ξ±).2 β¨(equiv.set.range f hf).symmβ©,
simp only [lift_umax.{u v}, lift_umax.{v u}] at this,
exact this
end
lemma mk_range_eq_lift {Ξ± : Type u} {Ξ² : Type v} {f : Ξ± β Ξ²} (hf : injective f) :
lift.{v (max u w)} (# (range f)) = lift.{u (max v w)} (# Ξ±) :=
lift_mk_eq.mpr β¨(equiv.set.range f hf).symmβ©
theorem mk_image_eq {Ξ± Ξ² : Type u} {f : Ξ± β Ξ²} {s : set Ξ±} (hf : injective f) :
mk (f '' s) = mk s :=
quotient.sound β¨(equiv.set.image f s hf).symmβ©
theorem mk_Union_le_sum_mk {Ξ± ΞΉ : Type u} {f : ΞΉ β set Ξ±} : mk (β i, f i) β€ sum (Ξ» i, mk (f i)) :=
calc mk (β i, f i) β€ mk (Ξ£ i, f i) : mk_le_of_surjective (set.sigma_to_Union_surjective f)
... = sum (Ξ» i, mk (f i)) : (sum_mk _).symm
theorem mk_Union_eq_sum_mk {Ξ± ΞΉ : Type u} {f : ΞΉ β set Ξ±} (h : βi j, i β j β disjoint (f i) (f j)) :
mk (β i, f i) = sum (Ξ» i, mk (f i)) :=
calc mk (β i, f i) = mk (Ξ£i, f i) : quot.sound β¨set.Union_eq_sigma_of_disjoint hβ©
... = sum (Ξ»i, mk (f i)) : (sum_mk _).symm
lemma mk_Union_le {Ξ± ΞΉ : Type u} (f : ΞΉ β set Ξ±) :
mk (β i, f i) β€ mk ΞΉ * cardinal.sup.{u u} (Ξ» i, mk (f i)) :=
le_trans mk_Union_le_sum_mk (sum_le_sup _)
lemma mk_sUnion_le {Ξ± : Type u} (A : set (set Ξ±)) :
mk (ββ A) β€ mk A * cardinal.sup.{u u} (Ξ» s : A, mk s) :=
by { rw [sUnion_eq_Union], apply mk_Union_le }
lemma mk_bUnion_le {ΞΉ Ξ± : Type u} (A : ΞΉ β set Ξ±) (s : set ΞΉ) :
mk (β(x β s), A x) β€ mk s * cardinal.sup.{u u} (Ξ» x : s, mk (A x.1)) :=
by { rw [bUnion_eq_Union], apply mk_Union_le }
@[simp] lemma finset_card {Ξ± : Type u} {s : finset Ξ±} : β(finset.card s) = mk (βs : set Ξ±) :=
by rw [fintype_card, nat_cast_inj, fintype.card_coe]
lemma finset_card_lt_omega (s : finset Ξ±) : mk (βs : set Ξ±) < omega :=
by { rw [lt_omega_iff_fintype], exact β¨finset.subtype.fintype sβ© }
theorem mk_union_add_mk_inter {Ξ± : Type u} {S T : set Ξ±} :
mk (S βͺ T : set Ξ±) + mk (S β© T : set Ξ±) = mk S + mk T :=
quot.sound β¨equiv.set.union_sum_inter S Tβ©
/-- The cardinality of a union is at most the sum of the cardinalities
of the two sets. -/
lemma mk_union_le {Ξ± : Type u} (S T : set Ξ±) : mk (S βͺ T : set Ξ±) β€ mk S + mk T :=
@mk_union_add_mk_inter Ξ± S T βΈ le_add_right (mk (S βͺ T : set Ξ±)) (mk (S β© T : set Ξ±))
theorem mk_union_of_disjoint {Ξ± : Type u} {S T : set Ξ±} (H : disjoint S T) :
mk (S βͺ T : set Ξ±) = mk S + mk T :=
quot.sound β¨equiv.set.union Hβ©
lemma mk_sum_compl {Ξ±} (s : set Ξ±) : #s + #(sαΆ : set Ξ±) = #Ξ± :=
quotient.sound β¨equiv.set.sum_compl sβ©
lemma mk_le_mk_of_subset {Ξ±} {s t : set Ξ±} (h : s β t) : mk s β€ mk t :=
β¨set.embedding_of_subset s t hβ©
lemma mk_subtype_mono {p q : Ξ± β Prop} (h : βx, p x β q x) : mk {x // p x} β€ mk {x // q x} :=
β¨embedding_of_subset _ _ hβ©
lemma mk_set_le (s : set Ξ±) : mk s β€ mk Ξ± :=
mk_subtype_le s
lemma mk_image_eq_lift {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β Ξ²) (s : set Ξ±) (h : injective f) :
lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr β¨(equiv.set.image f s h).symmβ©
lemma mk_image_eq_of_inj_on_lift {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β Ξ²) (s : set Ξ±)
(h : inj_on f s) : lift.{v u} (mk (f '' s)) = lift.{u v} (mk s) :=
lift_mk_eq.{v u 0}.mpr β¨(equiv.set.image_of_inj_on f s h).symmβ©
lemma mk_image_eq_of_inj_on {Ξ± Ξ² : Type u} (f : Ξ± β Ξ²) (s : set Ξ±) (h : inj_on f s) :
mk (f '' s) = mk s :=
quotient.sound β¨(equiv.set.image_of_inj_on f s h).symmβ©
lemma mk_subtype_of_equiv {Ξ± Ξ² : Type u} (p : Ξ² β Prop) (e : Ξ± β Ξ²) :
mk {a : Ξ± // p (e a)} = mk {b : Ξ² // p b} :=
quotient.sound β¨equiv.subtype_equiv_of_subtype eβ©
lemma mk_sep (s : set Ξ±) (t : Ξ± β Prop) : mk ({ x β s | t x } : set Ξ±) = mk { x : s | t x.1 } :=
quotient.sound β¨equiv.set.sep s tβ©
lemma mk_preimage_of_injective_lift {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β Ξ²) (s : set Ξ²)
(h : injective f) : lift.{u v} (mk (f β»ΒΉ' s)) β€ lift.{v u} (mk s) :=
begin
rw lift_mk_le.{u v 0}, use subtype.coind (Ξ» x, f x.1) (Ξ» x, x.2),
apply subtype.coind_injective, exact h.comp subtype.val_injective
end
lemma mk_preimage_of_subset_range_lift {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β Ξ²) (s : set Ξ²)
(h : s β range f) : lift.{v u} (mk s) β€ lift.{u v} (mk (f β»ΒΉ' s)) :=
begin
rw lift_mk_le.{v u 0},
refine β¨β¨_, _β©β©,
{ rintro β¨y, hyβ©, rcases classical.subtype_of_exists (h hy) with β¨x, rflβ©, exact β¨x, hyβ© },
rintro β¨y, hyβ© β¨y', hy'β©, dsimp,
rcases classical.subtype_of_exists (h hy) with β¨x, rflβ©,
rcases classical.subtype_of_exists (h hy') with β¨x', rflβ©,
simp, intro hxx', rw hxx'
end
lemma mk_preimage_of_injective_of_subset_range_lift {Ξ² : Type v} (f : Ξ± β Ξ²) (s : set Ξ²)
(h : injective f) (h2 : s β range f) : lift.{u v} (mk (f β»ΒΉ' s)) = lift.{v u} (mk s) :=
le_antisymm (mk_preimage_of_injective_lift f s h) (mk_preimage_of_subset_range_lift f s h2)
lemma mk_preimage_of_injective (f : Ξ± β Ξ²) (s : set Ξ²) (h : injective f) :
mk (f β»ΒΉ' s) β€ mk s :=
by { convert mk_preimage_of_injective_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_subset_range (f : Ξ± β Ξ²) (s : set Ξ²)
(h : s β range f) : mk s β€ mk (f β»ΒΉ' s) :=
by { convert mk_preimage_of_subset_range_lift.{u u} f s h using 1; rw [lift_id] }
lemma mk_preimage_of_injective_of_subset_range (f : Ξ± β Ξ²) (s : set Ξ²)
(h : injective f) (h2 : s β range f) : mk (f β»ΒΉ' s) = mk s :=
by { convert mk_preimage_of_injective_of_subset_range_lift.{u u} f s h h2 using 1; rw [lift_id] }
lemma mk_subset_ge_of_subset_image_lift {Ξ± : Type u} {Ξ² : Type v} (f : Ξ± β Ξ²) {s : set Ξ±}
{t : set Ξ²} (h : t β f '' s) :
lift.{v u} (mk t) β€ lift.{u v} (mk ({ x β s | f x β t } : set Ξ±)) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range_lift _ _ h using 1, rw [mk_sep], refl }
lemma mk_subset_ge_of_subset_image (f : Ξ± β Ξ²) {s : set Ξ±} {t : set Ξ²} (h : t β f '' s) :
mk t β€ mk ({ x β s | f x β t } : set Ξ±) :=
by { rw [image_eq_range] at h, convert mk_preimage_of_subset_range _ _ h using 1, rw [mk_sep], refl }
theorem le_mk_iff_exists_subset {c : cardinal} {Ξ± : Type u} {s : set Ξ±} :
c β€ mk s β β p : set Ξ±, p β s β§ mk p = c :=
begin
rw [le_mk_iff_exists_set, βsubtype.exists_set_subtype],
apply exists_congr, intro t, rw [mk_image_eq], apply subtype.val_injective
end
/-- The function Ξ±^{<Ξ²}, defined to be sup_{Ξ³ < Ξ²} Ξ±^Ξ³.
We index over {s : set Ξ².out // mk s < Ξ² } instead of {Ξ³ // Ξ³ < Ξ²}, because the latter lives in a
higher universe -/
noncomputable def powerlt (Ξ± Ξ² : cardinal.{u}) : cardinal.{u} :=
sup.{u u} (Ξ»(s : {s : set Ξ².out // mk s < Ξ²}), Ξ± ^ mk.{u} s)
infix ` ^< `:80 := powerlt
theorem powerlt_aux {c c' : cardinal} (h : c < c') :
β(s : {s : set c'.out // mk s < c'}), mk s = c :=
begin
cases out_embedding.mp (le_of_lt h) with f,
have : mk β₯(range βf) = c, { rwa [mk_range_eq, mk, quotient.out_eq c], exact f.2 },
exact β¨β¨range f, by convert hβ©, thisβ©
end
lemma le_powerlt {cβ cβ cβ : cardinal} (h : cβ < cβ) : cβ ^ cβ β€ cβ ^< cβ :=
by { rcases powerlt_aux h with β¨s, rflβ©, apply le_sup _ s }
lemma powerlt_le {cβ cβ cβ : cardinal} : cβ ^< cβ β€ cβ β β(cβ < cβ), cβ ^ cβ β€ cβ :=
begin
rw [powerlt, sup_le],
split,
{ intros h cβ hcβ, rcases powerlt_aux hcβ with β¨s, rflβ©, exact h s },
intros h s, exact h _ s.2
end
lemma powerlt_le_powerlt_left {a b c : cardinal} (h : b β€ c) : a ^< b β€ a ^< c :=
by { rw [powerlt, sup_le], rintro β¨s, hsβ©, apply le_powerlt, exact lt_of_lt_of_le hs h }
lemma powerlt_succ {cβ cβ : cardinal} (h : cβ β 0) : cβ ^< cβ.succ = cβ ^ cβ :=
begin
apply le_antisymm,
{ rw powerlt_le, intros cβ h2, apply power_le_power_left h, rwa [βlt_succ] },
{ apply le_powerlt, apply lt_succ_self }
end
lemma powerlt_max {cβ cβ cβ : cardinal} : cβ ^< max cβ cβ = max (cβ ^< cβ) (cβ ^< cβ) :=
by { cases le_total cβ cβ; simp only [max_eq_left, max_eq_right, h, powerlt_le_powerlt_left] }
lemma zero_powerlt {a : cardinal} (h : a β 0) : 0 ^< a = 1 :=
begin
apply le_antisymm,
{ rw [powerlt_le], intros c hc, apply zero_power_le },
convert le_powerlt (pos_iff_ne_zero.2 h), rw [power_zero]
end
lemma powerlt_zero {a : cardinal} : a ^< 0 = 0 :=
by { apply sup_eq_zero, rintro β¨x, hxβ©, rw [βnot_le] at hx, apply hx, apply zero_le }
end cardinal
|
102e8c73e36dc4a0a96d03b37c25611c7e42a1b5 | e94d3f31e48d06d252ee7307fe71efe1d500f274 | /hott/init/equiv.hlean | cd5174045d46b75a6792d5d4a72b5ee132309b9e | [
"Apache-2.0"
] | permissive | GallagherCommaJack/lean | e4471240a069d82f97cb361d2bf1a029de3f4256 | 226f8bafeb9baaa5a2ac58000c83d6beb29991e2 | refs/heads/master | 1,610,725,100,482 | 1,459,194,829,000 | 1,459,195,377,000 | 55,377,224 | 0 | 0 | null | 1,459,731,701,000 | 1,459,731,700,000 | null | UTF-8 | Lean | false | false | 17,140 | hlean | /-
Copyright (c) 2014 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Jeremy Avigad, Jakob von Raumer, Floris van Doorn
Ported from Coq HoTT
-/
prelude
import .path .function
open eq function lift
/- Equivalences -/
-- This is our definition of equivalence. In the HoTT-book it's called
-- ihae (half-adjoint equivalence).
structure is_equiv [class] {A B : Type} (f : A β B) :=
mk' ::
(inv : B β A)
(right_inv : Ξ b, f (inv b) = b)
(left_inv : Ξ a, inv (f a) = a)
(adj : Ξ x, right_inv (f x) = ap f (left_inv x))
attribute is_equiv.inv [reducible]
-- A more bundled version of equivalence
structure equiv (A B : Type) :=
(to_fun : A β B)
(to_is_equiv : is_equiv to_fun)
namespace is_equiv
/- Some instances and closure properties of equivalences -/
postfix β»ΒΉ := inv
/- a second notation for the inverse, which is not overloaded -/
postfix [parsing_only] `β»ΒΉαΆ `:std.prec.max_plus := inv
section
variables {A B C : Type} (f : A β B) (g : B β C) {f' : A β B}
-- The variant of mk' where f is explicit.
protected abbreviation mk [constructor] := @is_equiv.mk' A B f
-- The identity function is an equivalence.
definition is_equiv_id [instance] [constructor] (A : Type) : (is_equiv (id : A β A)) :=
is_equiv.mk id id (Ξ»a, idp) (Ξ»a, idp) (Ξ»a, idp)
-- The composition of two equivalences is, again, an equivalence.
definition is_equiv_compose [constructor] [Hf : is_equiv f] [Hg : is_equiv g]
: is_equiv (g β f) :=
is_equiv.mk (g β f) (fβ»ΒΉ β gβ»ΒΉ)
abstract (Ξ»c, ap g (right_inv f (gβ»ΒΉ c)) β¬ right_inv g c) end
abstract (Ξ»a, ap (inv f) (left_inv g (f a)) β¬ left_inv f a) end
abstract (Ξ»a, (whisker_left _ (adj g (f a))) β¬
(ap_con g _ _)β»ΒΉ β¬
ap02 g ((ap_con_eq_con (right_inv f) (left_inv g (f a)))β»ΒΉ β¬
(ap_compose f (inv f) _ βΎ adj f a) β¬
(ap_con f _ _)β»ΒΉ
) β¬
(ap_compose g f _)β»ΒΉ) end
-- Any function equal to an equivalence is an equivlance as well.
variable {f}
definition is_equiv_eq_closed [Hf : is_equiv f] (Heq : f = f') : is_equiv f' :=
eq.rec_on Heq Hf
end
section
parameters {A B : Type} (f : A β B) (g : B β A)
(ret : Ξ b, f (g b) = b) (sec : Ξ a, g (f a) = a)
private definition adjointify_left_inv' (a : A) : g (f a) = a :=
ap g (ap f (inverse (sec a))) β¬ ap g (ret (f a)) β¬ sec a
private theorem adjointify_adj' (a : A) : ret (f a) = ap f (adjointify_left_inv' a) :=
let fgretrfa := ap f (ap g (ret (f a))) in
let fgfinvsect := ap f (ap g (ap f (sec a)β»ΒΉ)) in
let fgfa := f (g (f a)) in
let retrfa := ret (f a) in
have eq1 : ap f (sec a) = _,
from calc ap f (sec a)
= idp β¬ ap f (sec a) : by rewrite idp_con
... = (ret (f a) β¬ (ret (f a))β»ΒΉ) β¬ ap f (sec a) : by rewrite con.right_inv
... = ((ret fgfa)β»ΒΉ β¬ ap (f β g) (ret (f a))) β¬ ap f (sec a) : by rewrite con_ap_eq_con
... = ((ret fgfa)β»ΒΉ β¬ fgretrfa) β¬ ap f (sec a) : by rewrite ap_compose
... = (ret fgfa)β»ΒΉ β¬ (fgretrfa β¬ ap f (sec a)) : by rewrite con.assoc,
have eq2 : ap f (sec a) β¬ idp = (ret fgfa)β»ΒΉ β¬ (fgretrfa β¬ ap f (sec a)),
from !con_idp β¬ eq1,
have eq3 : idp = _,
from calc idp
= (ap f (sec a))β»ΒΉ β¬ ((ret fgfa)β»ΒΉ β¬ (fgretrfa β¬ ap f (sec a))) : eq_inv_con_of_con_eq eq2
... = ((ap f (sec a))β»ΒΉ β¬ (ret fgfa)β»ΒΉ) β¬ (fgretrfa β¬ ap f (sec a)) : by rewrite con.assoc'
... = (ap f (sec a)β»ΒΉ β¬ (ret fgfa)β»ΒΉ) β¬ (fgretrfa β¬ ap f (sec a)) : by rewrite ap_inv
... = ((ap f (sec a)β»ΒΉ β¬ (ret fgfa)β»ΒΉ) β¬ fgretrfa) β¬ ap f (sec a) : by rewrite con.assoc'
... = ((retrfaβ»ΒΉ β¬ ap (f β g) (ap f (sec a)β»ΒΉ)) β¬ fgretrfa) β¬ ap f (sec a) : by rewrite con_ap_eq_con
... = ((retrfaβ»ΒΉ β¬ fgfinvsect) β¬ fgretrfa) β¬ ap f (sec a) : by rewrite ap_compose
... = (retrfaβ»ΒΉ β¬ (fgfinvsect β¬ fgretrfa)) β¬ ap f (sec a) : by rewrite con.assoc'
... = retrfaβ»ΒΉ β¬ ap f (ap g (ap f (sec a)β»ΒΉ) β¬ ap g (ret (f a))) β¬ ap f (sec a) : by rewrite ap_con
... = retrfaβ»ΒΉ β¬ (ap f (ap g (ap f (sec a)β»ΒΉ) β¬ ap g (ret (f a))) β¬ ap f (sec a)) : by rewrite con.assoc'
... = retrfaβ»ΒΉ β¬ ap f ((ap g (ap f (sec a)β»ΒΉ) β¬ ap g (ret (f a))) β¬ sec a) : by rewrite -ap_con,
show ret (f a) = ap f ((ap g (ap f (sec a)β»ΒΉ) β¬ ap g (ret (f a))) β¬ sec a),
from eq_of_idp_eq_inv_con eq3
definition adjointify [constructor] : is_equiv f :=
is_equiv.mk f g ret adjointify_left_inv' adjointify_adj'
end
-- Any function pointwise equal to an equivalence is an equivalence as well.
definition homotopy_closed [constructor] {A B : Type} (f : A β B) {f' : A β B} [Hf : is_equiv f]
(Hty : f ~ f') : is_equiv f' :=
adjointify f'
(inv f)
(Ξ» b, (Hty (inv f b))β»ΒΉ β¬ right_inv f b)
(Ξ» a, (ap (inv f) (Hty a))β»ΒΉ β¬ left_inv f a)
definition inv_homotopy_closed [constructor] {A B : Type} {f : A β B} {f' : B β A}
[Hf : is_equiv f] (Hty : fβ»ΒΉ ~ f') : is_equiv f :=
adjointify f
f'
(Ξ» b, ap f !Htyβ»ΒΉ β¬ right_inv f b)
(Ξ» a, !Htyβ»ΒΉ β¬ left_inv f a)
definition is_equiv_up [instance] [constructor] (A : Type)
: is_equiv (up : A β lift A) :=
adjointify up down (Ξ»a, by induction a;reflexivity) (Ξ»a, idp)
section
variables {A B C : Type} (f : A β B) {f' : A β B} [Hf : is_equiv f] (g : B β C)
include Hf
--The inverse of an equivalence is, again, an equivalence.
definition is_equiv_inv [instance] [constructor] : is_equiv fβ»ΒΉ :=
adjointify fβ»ΒΉ f (left_inv f) (right_inv f)
definition cancel_right (g : B β C) [Hgf : is_equiv (g β f)] : (is_equiv g) :=
have Hfinv : is_equiv fβ»ΒΉ, from is_equiv_inv f,
@homotopy_closed _ _ _ _ (is_equiv_compose fβ»ΒΉ (g β f)) (Ξ»b, ap g (@right_inv _ _ f _ b))
definition cancel_left (g : C β A) [Hgf : is_equiv (f β g)] : (is_equiv g) :=
have Hfinv : is_equiv fβ»ΒΉ, from is_equiv_inv f,
@homotopy_closed _ _ _ _ (is_equiv_compose (f β g) fβ»ΒΉ) (Ξ»a, left_inv f (g a))
definition eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : x = y :=
(left_inv f x)β»ΒΉ β¬ ap fβ»ΒΉ q β¬ left_inv f y
theorem ap_eq_of_fn_eq_fn' {x y : A} (q : f x = f y) : ap f (eq_of_fn_eq_fn' f q) = q :=
begin
rewrite [βeq_of_fn_eq_fn',+ap_con,ap_inv,-+adj,-ap_compose,con.assoc,
ap_con_eq_con_ap (right_inv f) q,inv_con_cancel_left,ap_id],
end
definition is_equiv_ap [instance] (x y : A) : is_equiv (ap f : x = y β f x = f y) :=
adjointify
(ap f)
(eq_of_fn_eq_fn' f)
abstract (Ξ»q, !ap_con
β¬ whisker_right !ap_con _
β¬ ((!ap_inv β¬ inverse2 (adj f _)β»ΒΉ)
βΎ (inverse (ap_compose f fβ»ΒΉ _))
βΎ (adj f _)β»ΒΉ)
β¬ con_ap_con_eq_con_con (right_inv f) _ _
β¬ whisker_right !con.left_inv _
β¬ !idp_con) end
abstract (Ξ»p, whisker_right (whisker_left _ (ap_compose fβ»ΒΉ f _)β»ΒΉ) _
β¬ con_ap_con_eq_con_con (left_inv f) _ _
β¬ whisker_right !con.left_inv _
β¬ !idp_con) end
-- The function equiv_rect says that given an equivalence f : A β B,
-- and a hypothesis from B, one may always assume that the hypothesis
-- is in the image of e.
-- In fibrational terms, if we have a fibration over B which has a section
-- once pulled back along an equivalence f : A β B, then it has a section
-- over all of B.
definition is_equiv_rect (P : B β Type) (g : Ξ a, P (f a)) (b : B) : P b :=
right_inv f b βΈ g (fβ»ΒΉ b)
definition is_equiv_rect' (P : A β B β Type) (g : Ξ b, P (fβ»ΒΉ b) b) (a : A) : P a (f a) :=
left_inv f a βΈ g (f a)
definition is_equiv_rect_comp (P : B β Type)
(df : Ξ (x : A), P (f x)) (x : A) : is_equiv_rect f P df (f x) = df x :=
calc
is_equiv_rect f P df (f x)
= right_inv f (f x) βΈ df (fβ»ΒΉ (f x)) : by esimp
... = ap f (left_inv f x) βΈ df (fβ»ΒΉ (f x)) : by rewrite -adj
... = left_inv f x βΈ df (fβ»ΒΉ (f x)) : by rewrite -tr_compose
... = df x : by rewrite (apd df (left_inv f x))
theorem adj_inv (b : B) : left_inv f (fβ»ΒΉ b) = ap fβ»ΒΉ (right_inv f b) :=
is_equiv_rect f _
(Ξ»a, eq.cancel_right (left_inv f (id a))
(whisker_left _ !ap_idβ»ΒΉ β¬ (ap_con_eq_con_ap (left_inv f) (left_inv f a))β»ΒΉ) β¬
!ap_compose β¬ ap02 fβ»ΒΉ (adj f a)β»ΒΉ)
b
end
section
variables {A B C : Type} {f : A β B} [Hf : is_equiv f]
include Hf
section rewrite_rules
variables {a : A} {b : B}
definition eq_of_eq_inv (p : a = fβ»ΒΉ b) : f a = b :=
ap f p β¬ right_inv f b
definition eq_of_inv_eq (p : fβ»ΒΉ b = a) : b = f a :=
(eq_of_eq_inv pβ»ΒΉ)β»ΒΉ
definition inv_eq_of_eq (p : b = f a) : fβ»ΒΉ b = a :=
ap fβ»ΒΉ p β¬ left_inv f a
definition eq_inv_of_eq (p : f a = b) : a = fβ»ΒΉ b :=
(inv_eq_of_eq pβ»ΒΉ)β»ΒΉ
end rewrite_rules
variable (f)
section pre_compose
variables (Ξ± : A β C) (Ξ² : B β C)
definition homotopy_of_homotopy_inv_pre (p : Ξ² ~ Ξ± β fβ»ΒΉ) : Ξ² β f ~ Ξ± :=
Ξ» a, p (f a) β¬ ap Ξ± (left_inv f a)
definition homotopy_of_inv_homotopy_pre (p : Ξ± β fβ»ΒΉ ~ Ξ²) : Ξ± ~ Ξ² β f :=
Ξ» a, (ap Ξ± (left_inv f a))β»ΒΉ β¬ p (f a)
definition inv_homotopy_of_homotopy_pre (p : Ξ± ~ Ξ² β f) : Ξ± β fβ»ΒΉ ~ Ξ² :=
Ξ» b, p (fβ»ΒΉ b) β¬ ap Ξ² (right_inv f b)
definition homotopy_inv_of_homotopy_pre (p : Ξ² β f ~ Ξ±) : Ξ² ~ Ξ± β fβ»ΒΉ :=
Ξ» b, (ap Ξ² (right_inv f b))β»ΒΉ β¬ p (fβ»ΒΉ b)
end pre_compose
section post_compose
variables (Ξ± : C β A) (Ξ² : C β B)
definition homotopy_of_homotopy_inv_post (p : Ξ± ~ fβ»ΒΉ β Ξ²) : f β Ξ± ~ Ξ² :=
Ξ» c, ap f (p c) β¬ (right_inv f (Ξ² c))
definition homotopy_of_inv_homotopy_post (p : fβ»ΒΉ β Ξ² ~ Ξ±) : Ξ² ~ f β Ξ± :=
Ξ» c, (right_inv f (Ξ² c))β»ΒΉ β¬ ap f (p c)
definition inv_homotopy_of_homotopy_post (p : Ξ² ~ f β Ξ±) : fβ»ΒΉ β Ξ² ~ Ξ± :=
Ξ» c, ap fβ»ΒΉ (p c) β¬ (left_inv f (Ξ± c))
definition homotopy_inv_of_homotopy_post (p : f β Ξ± ~ Ξ²) : Ξ± ~ fβ»ΒΉ β Ξ² :=
Ξ» c, (left_inv f (Ξ± c))β»ΒΉ β¬ ap fβ»ΒΉ (p c)
end post_compose
end
--Transporting is an equivalence
definition is_equiv_tr [constructor] {A : Type} (P : A β Type) {x y : A}
(p : x = y) : (is_equiv (transport P p)) :=
is_equiv.mk _ (transport P pβ»ΒΉ) (tr_inv_tr p) (inv_tr_tr p) (tr_inv_tr_lemma p)
section
variables {A : Type} {B C : A β Type} (f : Ξ {a}, B a β C a) [H : Ξ a, is_equiv (@f a)]
{g : A β A} {g' : A β A} (h : Ξ {a}, B (g' a) β B (g a)) (h' : Ξ {a}, C (g' a) β C (g a))
include H
definition inv_commute' (p : Ξ β¦a : Aβ¦ (b : B (g' a)), f (h b) = h' (f b)) {a : A}
(c : C (g' a)) : fβ»ΒΉ (h' c) = h (fβ»ΒΉ c) :=
eq_of_fn_eq_fn' f (right_inv f (h' c) β¬ ap h' (right_inv f c)β»ΒΉ β¬ (p (fβ»ΒΉ c))β»ΒΉ)
definition fun_commute_of_inv_commute' (p : Ξ β¦a : Aβ¦ (c : C (g' a)), fβ»ΒΉ (h' c) = h (fβ»ΒΉ c))
{a : A} (b : B (g' a)) : f (h b) = h' (f b) :=
eq_of_fn_eq_fn' fβ»ΒΉ (left_inv f (h b) β¬ ap h (left_inv f b)β»ΒΉ β¬ (p (f b))β»ΒΉ)
definition ap_inv_commute' (p : Ξ β¦a : Aβ¦ (b : B (g' a)), f (h b) = h' (f b)) {a : A}
(c : C (g' a)) : ap f (inv_commute' @f @h @h' p c)
= right_inv f (h' c) β¬ ap h' (right_inv f c)β»ΒΉ β¬ (p (fβ»ΒΉ c))β»ΒΉ :=
!ap_eq_of_fn_eq_fn'
end
end is_equiv
open is_equiv
namespace eq
local attribute is_equiv_tr [instance]
definition tr_inv_fn {A : Type} {B : A β Type} {a a' : A} (p : a = a') :
transport B pβ»ΒΉ = (transport B p)β»ΒΉ := idp
definition tr_inv {A : Type} {B : A β Type} {a a' : A} (p : a = a') (b : B a') :
pβ»ΒΉ βΈ b = (transport B p)β»ΒΉ b := idp
definition cast_inv_fn {A B : Type} (p : A = B) : cast pβ»ΒΉ = (cast p)β»ΒΉ := idp
definition cast_inv {A B : Type} (p : A = B) (b : B) : cast pβ»ΒΉ b = (cast p)β»ΒΉ b := idp
end eq
infix ` β `:25 := equiv
attribute equiv.to_is_equiv [instance]
namespace equiv
attribute to_fun [coercion]
section
variables {A B C : Type}
protected definition MK [reducible] [constructor] (f : A β B) (g : B β A)
(right_inv : Ξ b, f (g b) = b) (left_inv : Ξ a, g (f a) = a) : A β B :=
equiv.mk f (adjointify f g right_inv left_inv)
definition to_inv [reducible] [unfold 3] (f : A β B) : B β A := fβ»ΒΉ
definition to_right_inv [reducible] [unfold 3] (f : A β B) (b : B) : f (fβ»ΒΉ b) = b :=
right_inv f b
definition to_left_inv [reducible] [unfold 3] (f : A β B) (a : A) : fβ»ΒΉ (f a) = a :=
left_inv f a
protected definition refl [refl] [constructor] : A β A :=
equiv.mk id !is_equiv_id
protected definition symm [symm] (f : A β B) : B β A :=
equiv.mk fβ»ΒΉ !is_equiv_inv
protected definition trans [trans] (f : A β B) (g : B β C) : A β C :=
equiv.mk (g β f) !is_equiv_compose
infixl ` β¬e `:75 := equiv.trans
postfix `β»ΒΉα΅`:(max + 1) := equiv.symm
-- notation for inverse which is not overloaded
abbreviation erfl [constructor] := @equiv.refl
definition to_inv_trans [reducible] [unfold_full] (f : A β B) (g : B β C)
: to_inv (f β¬e g) = to_fun (gβ»ΒΉα΅ β¬e fβ»ΒΉα΅) :=
idp
definition equiv_change_fun [constructor] (f : A β B) {f' : A β B} (Heq : f ~ f') : A β B :=
equiv.mk f' (is_equiv.homotopy_closed f Heq)
definition equiv_change_inv [constructor] (f : A β B) {f' : B β A} (Heq : fβ»ΒΉ ~ f')
: A β B :=
equiv.mk f (inv_homotopy_closed Heq)
--rename: eq_equiv_fn_eq_of_is_equiv
definition eq_equiv_fn_eq [constructor] (f : A β B) [H : is_equiv f] (a b : A) : (a = b) β (f a = f b) :=
equiv.mk (ap f) !is_equiv_ap
--rename: eq_equiv_fn_eq
definition eq_equiv_fn_eq_of_equiv [constructor] (f : A β B) (a b : A) : (a = b) β (f a = f b) :=
equiv.mk (ap f) !is_equiv_ap
definition equiv_ap [constructor] (P : A β Type) {a b : A} (p : a = b) : P a β P b :=
equiv.mk (transport P p) !is_equiv_tr
definition equiv_of_eq [constructor] {A B : Type} (p : A = B) : A β B :=
equiv.mk (cast p) !is_equiv_tr
definition eq_of_fn_eq_fn (f : A β B) {x y : A} (q : f x = f y) : x = y :=
(left_inv f x)β»ΒΉ β¬ ap fβ»ΒΉ q β¬ left_inv f y
definition eq_of_fn_eq_fn_inv (f : A β B) {x y : B} (q : fβ»ΒΉ x = fβ»ΒΉ y) : x = y :=
(right_inv f x)β»ΒΉ β¬ ap f q β¬ right_inv f y
--we need this theorem for the funext_of_ua proof
theorem inv_eq {A B : Type} (eqf eqg : A β B) (p : eqf = eqg) : (to_fun eqf)β»ΒΉ = (to_fun eqg)β»ΒΉ :=
eq.rec_on p idp
definition equiv_of_equiv_of_eq [trans] {A B C : Type} (p : A = B) (q : B β C) : A β C :=
equiv_of_eq p β¬e q
definition equiv_of_eq_of_equiv [trans] {A B C : Type} (p : A β B) (q : B = C) : A β C :=
p β¬e equiv_of_eq q
definition equiv_lift [constructor] (A : Type) : A β lift A := equiv.mk up _
definition equiv_rect (f : A β B) (P : B β Type) (g : Ξ a, P (f a)) (b : B) : P b :=
right_inv f b βΈ g (fβ»ΒΉ b)
definition equiv_rect' (f : A β B) (P : A β B β Type) (g : Ξ b, P (fβ»ΒΉ b) b) (a : A) : P a (f a) :=
left_inv f a βΈ g (f a)
definition equiv_rect_comp (f : A β B) (P : B β Type)
(df : Ξ (x : A), P (f x)) (x : A) : equiv_rect f P df (f x) = df x :=
calc
equiv_rect f P df (f x)
= right_inv f (f x) βΈ df (fβ»ΒΉ (f x)) : by esimp
... = ap f (left_inv f x) βΈ df (fβ»ΒΉ (f x)) : by rewrite -adj
... = left_inv f x βΈ df (fβ»ΒΉ (f x)) : by rewrite -tr_compose
... = df x : by rewrite (apd df (left_inv f x))
end
section
variables {A : Type} {B C : A β Type} (f : Ξ {a}, B a β C a)
{g : A β A} {g' : A β A} (h : Ξ {a}, B (g' a) β B (g a)) (h' : Ξ {a}, C (g' a) β C (g a))
definition inv_commute (p : Ξ β¦a : Aβ¦ (b : B (g' a)), f (h b) = h' (f b)) {a : A}
(c : C (g' a)) : fβ»ΒΉ (h' c) = h (fβ»ΒΉ c) :=
inv_commute' @f @h @h' p c
definition fun_commute_of_inv_commute (p : Ξ β¦a : Aβ¦ (c : C (g' a)), fβ»ΒΉ (h' c) = h (fβ»ΒΉ c))
{a : A} (b : B (g' a)) : f (h b) = h' (f b) :=
fun_commute_of_inv_commute' @f @h @h' p b
end
infixl ` β¬pe `:75 := equiv_of_equiv_of_eq
infixl ` β¬ep `:75 := equiv_of_eq_of_equiv
end equiv
open equiv
namespace is_equiv
definition is_equiv_of_equiv_of_homotopy [constructor] {A B : Type} (f : A β B)
{f' : A β B} (Hty : f ~ f') : is_equiv f' :=
homotopy_closed f Hty
end is_equiv
export [unfold] equiv
export [unfold] is_equiv
|
ccd6564ccaf41deb756f544879a1b40ba4dfe3d2 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/data/set/intervals/image_preimage.lean | b81dd58a02b6061dbd9a3a405127551a5662e8aa | [
"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 | 20,068 | 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, Patrick Massot
-/
import data.set.intervals.basic
import data.equiv.mul_add
import algebra.pointwise
/-!
# (Pre)images of intervals
In this file we prove a bunch of trivial lemmas like βif we add `a` to all points of `[b, c]`,
then we get `[a + b, a + c]`β. For the functions `x β¦ x Β± a`, `x β¦ a Β± x`, and `x β¦ -x` we prove
lemmas about preimages and images of all intervals. We also prove a few lemmas about images under
`x β¦ a * x`, `x β¦ x * a` and `x β¦ xβ»ΒΉ`.
-/
universe u
namespace set
section has_exists_add_of_le
/-!
The lemmas in this section state that addition maps intervals bijectively. The typeclass
`has_exists_add_of_le` is defined specifically to make them work when combined with
`ordered_cancel_add_comm_monoid`; the lemmas below therefore apply to all
`ordered_add_comm_group`, but also to `β` and `ββ₯0`, which are not groups.
TODO : move as much as possible in this file to the setting of this weaker typeclass.
-/
variables {Ξ± : Type u} [ordered_cancel_add_comm_monoid Ξ±] [has_exists_add_of_le Ξ±] (a b d : Ξ±)
lemma Icc_add_bij : bij_on (+d) (Icc a b) (Icc (a + d) (b + d)) :=
begin
refine β¨Ξ» _ h, β¨add_le_add_right h.1 _, add_le_add_right h.2 _β©,
Ξ» _ _ _ _ h, add_right_cancel h,
Ξ» _ h, _β©,
obtain β¨c, rflβ© := exists_add_of_le h.1,
rw [mem_Icc, add_right_comm, add_le_add_iff_right, add_le_add_iff_right] at h,
exact β¨a + c, h, by rw add_right_commβ©,
end
lemma Ioo_add_bij : bij_on (+d) (Ioo a b) (Ioo (a + d) (b + d)) :=
begin
refine β¨Ξ» _ h, β¨add_lt_add_right h.1 _, add_lt_add_right h.2 _β©,
Ξ» _ _ _ _ h, add_right_cancel h,
Ξ» _ h, _β©,
obtain β¨c, rflβ© := exists_add_of_le h.1.le,
rw [mem_Ioo, add_right_comm, add_lt_add_iff_right, add_lt_add_iff_right] at h,
exact β¨a + c, h, by rw add_right_commβ©,
end
lemma Ioc_add_bij : bij_on (+d) (Ioc a b) (Ioc (a + d) (b + d)) :=
begin
refine β¨Ξ» _ h, β¨add_lt_add_right h.1 _, add_le_add_right h.2 _β©,
Ξ» _ _ _ _ h, add_right_cancel h,
Ξ» _ h, _β©,
obtain β¨c, rflβ© := exists_add_of_le h.1.le,
rw [mem_Ioc, add_right_comm, add_lt_add_iff_right, add_le_add_iff_right] at h,
exact β¨a + c, h, by rw add_right_commβ©,
end
lemma Ico_add_bij : bij_on (+d) (Ico a b) (Ico (a + d) (b + d)) :=
begin
refine β¨Ξ» _ h, β¨add_le_add_right h.1 _, add_lt_add_right h.2 _β©,
Ξ» _ _ _ _ h, add_right_cancel h,
Ξ» _ h, _β©,
obtain β¨c, rflβ© := exists_add_of_le h.1,
rw [mem_Ico, add_right_comm, add_le_add_iff_right, add_lt_add_iff_right] at h,
exact β¨a + c, h, by rw add_right_commβ©,
end
lemma Ici_add_bij : bij_on (+d) (Ici a) (Ici (a + d)) :=
begin
refine β¨Ξ» x h, add_le_add_right (mem_Ici.mp h) _, Ξ» _ _ _ _ h, add_right_cancel h, Ξ» _ h, _β©,
obtain β¨c, rflβ© := exists_add_of_le (mem_Ici.mp h),
rw [mem_Ici, add_right_comm, add_le_add_iff_right] at h,
exact β¨a + c, h, by rw add_right_commβ©,
end
lemma Ioi_add_bij : bij_on (+d) (Ioi a) (Ioi (a + d)) :=
begin
refine β¨Ξ» x h, add_lt_add_right (mem_Ioi.mp h) _, Ξ» _ _ _ _ h, add_right_cancel h, Ξ» _ h, _β©,
obtain β¨c, rflβ© := exists_add_of_le (mem_Ioi.mp h).le,
rw [mem_Ioi, add_right_comm, add_lt_add_iff_right] at h,
exact β¨a + c, h, by rw add_right_commβ©,
end
end has_exists_add_of_le
section ordered_add_comm_group
variables {G : Type u} [ordered_add_comm_group G] (a b c : G)
/-!
### Preimages under `x β¦ a + x`
-/
@[simp] lemma preimage_const_add_Ici : (Ξ» x, a + x) β»ΒΉ' (Ici b) = Ici (b - a) :=
ext $ Ξ» x, sub_le_iff_le_add'.symm
@[simp] lemma preimage_const_add_Ioi : (Ξ» x, a + x) β»ΒΉ' (Ioi b) = Ioi (b - a) :=
ext $ Ξ» x, sub_lt_iff_lt_add'.symm
@[simp] lemma preimage_const_add_Iic : (Ξ» x, a + x) β»ΒΉ' (Iic b) = Iic (b - a) :=
ext $ Ξ» x, le_sub_iff_add_le'.symm
@[simp] lemma preimage_const_add_Iio : (Ξ» x, a + x) β»ΒΉ' (Iio b) = Iio (b - a) :=
ext $ Ξ» x, lt_sub_iff_add_lt'.symm
@[simp] lemma preimage_const_add_Icc : (Ξ» x, a + x) β»ΒΉ' (Icc b c) = Icc (b - a) (c - a) :=
by simp [β Ici_inter_Iic]
@[simp] lemma preimage_const_add_Ico : (Ξ» x, a + x) β»ΒΉ' (Ico b c) = Ico (b - a) (c - a) :=
by simp [β Ici_inter_Iio]
@[simp] lemma preimage_const_add_Ioc : (Ξ» x, a + x) β»ΒΉ' (Ioc b c) = Ioc (b - a) (c - a) :=
by simp [β Ioi_inter_Iic]
@[simp] lemma preimage_const_add_Ioo : (Ξ» x, a + x) β»ΒΉ' (Ioo b c) = Ioo (b - a) (c - a) :=
by simp [β Ioi_inter_Iio]
/-!
### Preimages under `x β¦ x + a`
-/
@[simp] lemma preimage_add_const_Ici : (Ξ» x, x + a) β»ΒΉ' (Ici b) = Ici (b - a) :=
ext $ Ξ» x, sub_le_iff_le_add.symm
@[simp] lemma preimage_add_const_Ioi : (Ξ» x, x + a) β»ΒΉ' (Ioi b) = Ioi (b - a) :=
ext $ Ξ» x, sub_lt_iff_lt_add.symm
@[simp] lemma preimage_add_const_Iic : (Ξ» x, x + a) β»ΒΉ' (Iic b) = Iic (b - a) :=
ext $ Ξ» x, le_sub_iff_add_le.symm
@[simp] lemma preimage_add_const_Iio : (Ξ» x, x + a) β»ΒΉ' (Iio b) = Iio (b - a) :=
ext $ Ξ» x, lt_sub_iff_add_lt.symm
@[simp] lemma preimage_add_const_Icc : (Ξ» x, x + a) β»ΒΉ' (Icc b c) = Icc (b - a) (c - a) :=
by simp [β Ici_inter_Iic]
@[simp] lemma preimage_add_const_Ico : (Ξ» x, x + a) β»ΒΉ' (Ico b c) = Ico (b - a) (c - a) :=
by simp [β Ici_inter_Iio]
@[simp] lemma preimage_add_const_Ioc : (Ξ» x, x + a) β»ΒΉ' (Ioc b c) = Ioc (b - a) (c - a) :=
by simp [β Ioi_inter_Iic]
@[simp] lemma preimage_add_const_Ioo : (Ξ» x, x + a) β»ΒΉ' (Ioo b c) = Ioo (b - a) (c - a) :=
by simp [β Ioi_inter_Iio]
/-!
### Preimages under `x β¦ -x`
-/
@[simp] lemma preimage_neg_Ici : - Ici a = Iic (-a) := ext $ Ξ» x, le_neg
@[simp] lemma preimage_neg_Iic : - Iic a = Ici (-a) := ext $ Ξ» x, neg_le
@[simp] lemma preimage_neg_Ioi : - Ioi a = Iio (-a) := ext $ Ξ» x, lt_neg
@[simp] lemma preimage_neg_Iio : - Iio a = Ioi (-a) := ext $ Ξ» x, neg_lt
@[simp] lemma preimage_neg_Icc : - Icc a b = Icc (-b) (-a) :=
by simp [β Ici_inter_Iic, inter_comm]
@[simp] lemma preimage_neg_Ico : - Ico a b = Ioc (-b) (-a) :=
by simp [β Ici_inter_Iio, β Ioi_inter_Iic, inter_comm]
@[simp] lemma preimage_neg_Ioc : - Ioc a b = Ico (-b) (-a) :=
by simp [β Ioi_inter_Iic, β Ici_inter_Iio, inter_comm]
@[simp] lemma preimage_neg_Ioo : - Ioo a b = Ioo (-b) (-a) :=
by simp [β Ioi_inter_Iio, inter_comm]
/-!
### Preimages under `x β¦ x - a`
-/
@[simp] lemma preimage_sub_const_Ici : (Ξ» x, x - a) β»ΒΉ' (Ici b) = Ici (b + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Ioi : (Ξ» x, x - a) β»ΒΉ' (Ioi b) = Ioi (b + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Iic : (Ξ» x, x - a) β»ΒΉ' (Iic b) = Iic (b + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Iio : (Ξ» x, x - a) β»ΒΉ' (Iio b) = Iio (b + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Icc : (Ξ» x, x - a) β»ΒΉ' (Icc b c) = Icc (b + a) (c + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Ico : (Ξ» x, x - a) β»ΒΉ' (Ico b c) = Ico (b + a) (c + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Ioc : (Ξ» x, x - a) β»ΒΉ' (Ioc b c) = Ioc (b + a) (c + a) :=
by simp [sub_eq_add_neg]
@[simp] lemma preimage_sub_const_Ioo : (Ξ» x, x - a) β»ΒΉ' (Ioo b c) = Ioo (b + a) (c + a) :=
by simp [sub_eq_add_neg]
/-!
### Preimages under `x β¦ a - x`
-/
@[simp] lemma preimage_const_sub_Ici : (Ξ» x, a - x) β»ΒΉ' (Ici b) = Iic (a - b) :=
ext $ Ξ» x, le_sub
@[simp] lemma preimage_const_sub_Iic : (Ξ» x, a - x) β»ΒΉ' (Iic b) = Ici (a - b) :=
ext $ Ξ» x, sub_le
@[simp] lemma preimage_const_sub_Ioi : (Ξ» x, a - x) β»ΒΉ' (Ioi b) = Iio (a - b) :=
ext $ Ξ» x, lt_sub
@[simp] lemma preimage_const_sub_Iio : (Ξ» x, a - x) β»ΒΉ' (Iio b) = Ioi (a - b) :=
ext $ Ξ» x, sub_lt
@[simp] lemma preimage_const_sub_Icc : (Ξ» x, a - x) β»ΒΉ' (Icc b c) = Icc (a - c) (a - b) :=
by simp [β Ici_inter_Iic, inter_comm]
@[simp] lemma preimage_const_sub_Ico : (Ξ» x, a - x) β»ΒΉ' (Ico b c) = Ioc (a - c) (a - b) :=
by simp [β Ioi_inter_Iic, β Ici_inter_Iio, inter_comm]
@[simp] lemma preimage_const_sub_Ioc : (Ξ» x, a - x) β»ΒΉ' (Ioc b c) = Ico (a - c) (a - b) :=
by simp [β Ioi_inter_Iic, β Ici_inter_Iio, inter_comm]
@[simp] lemma preimage_const_sub_Ioo : (Ξ» x, a - x) β»ΒΉ' (Ioo b c) = Ioo (a - c) (a - b) :=
by simp [β Ioi_inter_Iio, inter_comm]
/-!
### Images under `x β¦ a + x`
-/
@[simp] lemma image_const_add_Ici : (Ξ» x, a + x) '' Ici b = Ici (a + b) :=
by simp [add_comm]
@[simp] lemma image_const_add_Iic : (Ξ» x, a + x) '' Iic b = Iic (a + b) :=
by simp [add_comm]
@[simp] lemma image_const_add_Iio : (Ξ» x, a + x) '' Iio b = Iio (a + b) :=
by simp [add_comm]
@[simp] lemma image_const_add_Ioi : (Ξ» x, a + x) '' Ioi b = Ioi (a + b) :=
by simp [add_comm]
@[simp] lemma image_const_add_Icc : (Ξ» x, a + x) '' Icc b c = Icc (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_const_add_Ico : (Ξ» x, a + x) '' Ico b c = Ico (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_const_add_Ioc : (Ξ» x, a + x) '' Ioc b c = Ioc (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_const_add_Ioo : (Ξ» x, a + x) '' Ioo b c = Ioo (a + b) (a + c) :=
by simp [add_comm]
/-!
### Images under `x β¦ x + a`
-/
@[simp] lemma image_add_const_Ici : (Ξ» x, x + a) '' Ici b = Ici (a + b) := by simp [add_comm]
@[simp] lemma image_add_const_Iic : (Ξ» x, x + a) '' Iic b = Iic (a + b) := by simp [add_comm]
@[simp] lemma image_add_const_Iio : (Ξ» x, x + a) '' Iio b = Iio (a + b) := by simp [add_comm]
@[simp] lemma image_add_const_Ioi : (Ξ» x, x + a) '' Ioi b = Ioi (a + b) := by simp [add_comm]
@[simp] lemma image_add_const_Icc : (Ξ» x, x + a) '' Icc b c = Icc (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_add_const_Ico : (Ξ» x, x + a) '' Ico b c = Ico (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_add_const_Ioc : (Ξ» x, x + a) '' Ioc b c = Ioc (a + b) (a + c) :=
by simp [add_comm]
@[simp] lemma image_add_const_Ioo : (Ξ» x, x + a) '' Ioo b c = Ioo (a + b) (a + c) :=
by simp [add_comm]
/-!
### Images under `x β¦ -x`
-/
lemma image_neg_Ici : has_neg.neg '' (Ici a) = Iic (-a) := by simp
lemma image_neg_Iic : has_neg.neg '' (Iic a) = Ici (-a) := by simp
lemma image_neg_Ioi : has_neg.neg '' (Ioi a) = Iio (-a) := by simp
lemma image_neg_Iio : has_neg.neg '' (Iio a) = Ioi (-a) := by simp
lemma image_neg_Icc : has_neg.neg '' (Icc a b) = Icc (-b) (-a) := by simp
lemma image_neg_Ico : has_neg.neg '' (Ico a b) = Ioc (-b) (-a) := by simp
lemma image_neg_Ioc : has_neg.neg '' (Ioc a b) = Ico (-b) (-a) := by simp
lemma image_neg_Ioo : has_neg.neg '' (Ioo a b) = Ioo (-b) (-a) := by simp
/-!
### Images under `x β¦ a - x`
-/
@[simp] lemma image_const_sub_Ici : (Ξ» x, a - x) '' Ici b = Iic (a - b) :=
by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)]
@[simp] lemma image_const_sub_Iic : (Ξ» x, a - x) '' Iic b = Ici (a - b) :=
by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)]
@[simp] lemma image_const_sub_Ioi : (Ξ» x, a - x) '' Ioi b = Iio (a - b) :=
by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)]
@[simp] lemma image_const_sub_Iio : (Ξ» x, a - x) '' Iio b = Ioi (a - b) :=
by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)]
@[simp] lemma image_const_sub_Icc : (Ξ» x, a - x) '' Icc b c = Icc (a - c) (a - b) :=
by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)]
@[simp] lemma image_const_sub_Ico : (Ξ» x, a - x) '' Ico b c = Ioc (a - c) (a - b) :=
by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)]
@[simp] lemma image_const_sub_Ioc : (Ξ» x, a - x) '' Ioc b c = Ico (a - c) (a - b) :=
by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)]
@[simp] lemma image_const_sub_Ioo : (Ξ» x, a - x) '' Ioo b c = Ioo (a - c) (a - b) :=
by simp [sub_eq_add_neg, image_comp (Ξ» x, a + x) (Ξ» x, -x)]
/-!
### Images under `x β¦ x - a`
-/
@[simp] lemma image_sub_const_Ici : (Ξ» x, x - a) '' Ici b = Ici (b - a) := by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Iic : (Ξ» x, x - a) '' Iic b = Iic (b - a) := by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Ioi : (Ξ» x, x - a) '' Ioi b = Ioi (b - a) := by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Iio : (Ξ» x, x - a) '' Iio b = Iio (b - a) := by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Icc : (Ξ» x, x - a) '' Icc b c = Icc (b - a) (c - a) :=
by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Ico : (Ξ» x, x - a) '' Ico b c = Ico (b - a) (c - a) :=
by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Ioc : (Ξ» x, x - a) '' Ioc b c = Ioc (b - a) (c - a) :=
by simp [sub_eq_neg_add]
@[simp] lemma image_sub_const_Ioo : (Ξ» x, x - a) '' Ioo b c = Ioo (b - a) (c - a) :=
by simp [sub_eq_neg_add]
/-!
### Bijections
-/
lemma Iic_add_bij : bij_on (+a) (Iic b) (Iic (b + a)) :=
begin
refine β¨Ξ» x h, add_le_add_right (mem_Iic.mp h) _, Ξ» _ _ _ _ h, add_right_cancel h, Ξ» _ h, _β©,
simpa [add_comm a] using h,
end
lemma Iio_add_bij : bij_on (+a) (Iio b) (Iio (b + a)) :=
begin
refine β¨Ξ» x h, add_lt_add_right (mem_Iio.mp h) _, Ξ» _ _ _ _ h, add_right_cancel h, Ξ» _ h, _β©,
simpa [add_comm a] using h,
end
end ordered_add_comm_group
/-!
### Multiplication and inverse in a field
-/
section linear_ordered_field
variables {k : Type u} [linear_ordered_field k]
@[simp] lemma preimage_mul_const_Iio (a : k) {c : k} (h : 0 < c) :
(Ξ» x, x * c) β»ΒΉ' (Iio a) = Iio (a / c) :=
ext $ Ξ» x, (lt_div_iff h).symm
@[simp] lemma preimage_mul_const_Ioi (a : k) {c : k} (h : 0 < c) :
(Ξ» x, x * c) β»ΒΉ' (Ioi a) = Ioi (a / c) :=
ext $ Ξ» x, (div_lt_iff h).symm
@[simp] lemma preimage_mul_const_Iic (a : k) {c : k} (h : 0 < c) :
(Ξ» x, x * c) β»ΒΉ' (Iic a) = Iic (a / c) :=
ext $ Ξ» x, (le_div_iff h).symm
@[simp] lemma preimage_mul_const_Ici (a : k) {c : k} (h : 0 < c) :
(Ξ» x, x * c) β»ΒΉ' (Ici a) = Ici (a / c) :=
ext $ Ξ» x, (div_le_iff h).symm
@[simp] lemma preimage_mul_const_Ioo (a b : k) {c : k} (h : 0 < c) :
(Ξ» x, x * c) β»ΒΉ' (Ioo a b) = Ioo (a / c) (b / c) :=
by simp [β Ioi_inter_Iio, h]
@[simp] lemma preimage_mul_const_Ioc (a b : k) {c : k} (h : 0 < c) :
(Ξ» x, x * c) β»ΒΉ' (Ioc a b) = Ioc (a / c) (b / c) :=
by simp [β Ioi_inter_Iic, h]
@[simp] lemma preimage_mul_const_Ico (a b : k) {c : k} (h : 0 < c) :
(Ξ» x, x * c) β»ΒΉ' (Ico a b) = Ico (a / c) (b / c) :=
by simp [β Ici_inter_Iio, h]
@[simp] lemma preimage_mul_const_Icc (a b : k) {c : k} (h : 0 < c) :
(Ξ» x, x * c) β»ΒΉ' (Icc a b) = Icc (a / c) (b / c) :=
by simp [β Ici_inter_Iic, h]
@[simp] lemma preimage_mul_const_Iio_of_neg (a : k) {c : k} (h : c < 0) :
(Ξ» x, x * c) β»ΒΉ' (Iio a) = Ioi (a / c) :=
ext $ Ξ» x, (div_lt_iff_of_neg h).symm
@[simp] lemma preimage_mul_const_Ioi_of_neg (a : k) {c : k} (h : c < 0) :
(Ξ» x, x * c) β»ΒΉ' (Ioi a) = Iio (a / c) :=
ext $ Ξ» x, (lt_div_iff_of_neg h).symm
@[simp] lemma preimage_mul_const_Iic_of_neg (a : k) {c : k} (h : c < 0) :
(Ξ» x, x * c) β»ΒΉ' (Iic a) = Ici (a / c) :=
ext $ Ξ» x, (div_le_iff_of_neg h).symm
@[simp] lemma preimage_mul_const_Ici_of_neg (a : k) {c : k} (h : c < 0) :
(Ξ» x, x * c) β»ΒΉ' (Ici a) = Iic (a / c) :=
ext $ Ξ» x, (le_div_iff_of_neg h).symm
@[simp] lemma preimage_mul_const_Ioo_of_neg (a b : k) {c : k} (h : c < 0) :
(Ξ» x, x * c) β»ΒΉ' (Ioo a b) = Ioo (b / c) (a / c) :=
by simp [β Ioi_inter_Iio, h, inter_comm]
@[simp] lemma preimage_mul_const_Ioc_of_neg (a b : k) {c : k} (h : c < 0) :
(Ξ» x, x * c) β»ΒΉ' (Ioc a b) = Ico (b / c) (a / c) :=
by simp [β Ioi_inter_Iic, β Ici_inter_Iio, h, inter_comm]
@[simp] lemma preimage_mul_const_Ico_of_neg (a b : k) {c : k} (h : c < 0) :
(Ξ» x, x * c) β»ΒΉ' (Ico a b) = Ioc (b / c) (a / c) :=
by simp [β Ici_inter_Iio, β Ioi_inter_Iic, h, inter_comm]
@[simp] lemma preimage_mul_const_Icc_of_neg (a b : k) {c : k} (h : c < 0) :
(Ξ» x, x * c) β»ΒΉ' (Icc a b) = Icc (b / c) (a / c) :=
by simp [β Ici_inter_Iic, h, inter_comm]
@[simp] lemma preimage_const_mul_Iio (a : k) {c : k} (h : 0 < c) :
((*) c) β»ΒΉ' (Iio a) = Iio (a / c) :=
ext $ Ξ» x, (lt_div_iff' h).symm
@[simp] lemma preimage_const_mul_Ioi (a : k) {c : k} (h : 0 < c) :
((*) c) β»ΒΉ' (Ioi a) = Ioi (a / c) :=
ext $ Ξ» x, (div_lt_iff' h).symm
@[simp] lemma preimage_const_mul_Iic (a : k) {c : k} (h : 0 < c) :
((*) c) β»ΒΉ' (Iic a) = Iic (a / c) :=
ext $ Ξ» x, (le_div_iff' h).symm
@[simp] lemma preimage_const_mul_Ici (a : k) {c : k} (h : 0 < c) :
((*) c) β»ΒΉ' (Ici a) = Ici (a / c) :=
ext $ Ξ» x, (div_le_iff' h).symm
@[simp] lemma preimage_const_mul_Ioo (a b : k) {c : k} (h : 0 < c) :
((*) c) β»ΒΉ' (Ioo a b) = Ioo (a / c) (b / c) :=
by simp [β Ioi_inter_Iio, h]
@[simp] lemma preimage_const_mul_Ioc (a b : k) {c : k} (h : 0 < c) :
((*) c) β»ΒΉ' (Ioc a b) = Ioc (a / c) (b / c) :=
by simp [β Ioi_inter_Iic, h]
@[simp] lemma preimage_const_mul_Ico (a b : k) {c : k} (h : 0 < c) :
((*) c) β»ΒΉ' (Ico a b) = Ico (a / c) (b / c) :=
by simp [β Ici_inter_Iio, h]
@[simp] lemma preimage_const_mul_Icc (a b : k) {c : k} (h : 0 < c) :
((*) c) β»ΒΉ' (Icc a b) = Icc (a / c) (b / c) :=
by simp [β Ici_inter_Iic, h]
@[simp] lemma preimage_const_mul_Iio_of_neg (a : k) {c : k} (h : c < 0) :
((*) c) β»ΒΉ' (Iio a) = Ioi (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Iio_of_neg a h
@[simp] lemma preimage_const_mul_Ioi_of_neg (a : k) {c : k} (h : c < 0) :
((*) c) β»ΒΉ' (Ioi a) = Iio (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ioi_of_neg a h
@[simp] lemma preimage_const_mul_Iic_of_neg (a : k) {c : k} (h : c < 0) :
((*) c) β»ΒΉ' (Iic a) = Ici (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Iic_of_neg a h
@[simp] lemma preimage_const_mul_Ici_of_neg (a : k) {c : k} (h : c < 0) :
((*) c) β»ΒΉ' (Ici a) = Iic (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ici_of_neg a h
@[simp] lemma preimage_const_mul_Ioo_of_neg (a b : k) {c : k} (h : c < 0) :
((*) c) β»ΒΉ' (Ioo a b) = Ioo (b / c) (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ioo_of_neg a b h
@[simp] lemma preimage_const_mul_Ioc_of_neg (a b : k) {c : k} (h : c < 0) :
((*) c) β»ΒΉ' (Ioc a b) = Ico (b / c) (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ioc_of_neg a b h
@[simp] lemma preimage_const_mul_Ico_of_neg (a b : k) {c : k} (h : c < 0) :
((*) c) β»ΒΉ' (Ico a b) = Ioc (b / c) (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Ico_of_neg a b h
@[simp] lemma preimage_const_mul_Icc_of_neg (a b : k) {c : k} (h : c < 0) :
((*) c) β»ΒΉ' (Icc a b) = Icc (b / c) (a / c) :=
by simpa only [mul_comm] using preimage_mul_const_Icc_of_neg a b h
lemma image_mul_right_Icc' (a b : k) {c : k} (h : 0 < c) :
(Ξ» x, x * c) '' Icc a b = Icc (a * c) (b * c) :=
begin
refine ((units.mk0 c (ne_of_gt h)).mul_right.image_eq_preimage _).trans _,
simp [h, division_def]
end
lemma image_mul_right_Icc {a b c : k} (hab : a β€ b) (hc : 0 β€ c) :
(Ξ» x, x * c) '' Icc a b = Icc (a * c) (b * c) :=
begin
cases eq_or_lt_of_le hc,
{ subst c,
simp [(nonempty_Icc.2 hab).image_const] },
exact image_mul_right_Icc' a b βΉ0 < cβΊ
end
lemma image_mul_left_Icc' {a : k} (h : 0 < a) (b c : k) :
((*) a) '' Icc b c = Icc (a * b) (a * c) :=
by { convert image_mul_right_Icc' b c h using 1; simp only [mul_comm _ a] }
lemma image_mul_left_Icc {a b c : k} (ha : 0 β€ a) (hbc : b β€ c) :
((*) a) '' Icc b c = Icc (a * b) (a * c) :=
by { convert image_mul_right_Icc hbc ha using 1; simp only [mul_comm _ a] }
/-- The image under `inv` of `Ioo 0 a` is `Ioi aβ»ΒΉ`. -/
lemma image_inv_Ioo_0_left {a : k} (ha : 0 < a) : has_inv.inv '' Ioo 0 a = Ioi aβ»ΒΉ :=
begin
ext x,
split,
{ rintros β¨y, β¨hy0, hyaβ©, hyxβ©,
exact hyx βΈ (inv_lt_inv ha hy0).2 hya },
{ exact Ξ» h, β¨xβ»ΒΉ, β¨inv_pos.2 (lt_trans (inv_pos.2 ha) h),
(inv_lt ha (lt_trans (inv_pos.2 ha) h)).1 hβ©,
inv_inv' xβ© }
end
end linear_ordered_field
end set
|
1c659ffdee1bccfd1ec088b83054de288dfdec29 | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /09_Type_Classes.org.9.lean | 319e5770e79f5e938c921dd0bf2bbdd5d2abf201 | [] | 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 | 809 | lean | import standard
import data.prod
namespace hide
inductive inhabited [class] (A : Type) : Type :=
mk : A β inhabited A
definition Prop.is_inhabited [instance] : inhabited Prop :=
inhabited.mk true
definition bool.is_inhabited [instance] : inhabited bool :=
inhabited.mk bool.tt
definition nat.is_inhabited [instance] : inhabited nat :=
inhabited.mk nat.zero
definition unit.is_inhabited [instance] : inhabited unit :=
inhabited.mk unit.star
definition default (A : Type) [H : inhabited A] : A :=
inhabited.rec (Ξ» a, a) H
definition arbitrary [irreducible] (A : Type) [H : inhabited A] : A :=
inhabited.rec (Ξ» a, a) H
-- BEGIN
definition prod.is_inhabited [instance] {A B : Type} [H1 : inhabited A]
[H2 : inhabited B] : inhabited (prod A B) :=
inhabited.mk ((default A, default B))
-- END
end hide
|
a34b6743abf37f6a4c9cfc4b7d8f45a4fda3253a | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/run/obtain.lean | 4f5565439dedacc93cacdc553edf21b4f5b1cb93 | [
"Apache-2.0"
] | permissive | shyamalschandra/lean4 | 27044812be8698f0c79147615b1d5090b9f4b037 | 6e7a883b21eaf62831e8111b251dc9b18f40e604 | refs/heads/master | 1,671,417,126,371 | 1,601,859,995,000 | 1,601,860,020,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 680 | lean | new_frontend
macro "obtain " p:term " from " d:term "; " body:term : term =>
`(match $d:term with | $p:term => $body:term)
theorem tst1 {p q r} (h : p β§ q β§ r) : q β§ p β§ r :=
match h with
| β¨hβ, β¨hβ, hββ©β© => β¨hβ, β¨hβ, hββ©β©
theorem tst2 {p q r} (h : p β§ q β§ r) : q β§ p β§ r :=
obtain β¨hβ, β¨hβ, hββ©β© from h;
β¨hβ, β¨hβ, hββ©β©
macro "obtain " p:term " from " d:term : tactic =>
`(tactic| match $d:term with | $p:term => ?hole)
theorem tst3 {p q r} (h : p β§ q β§ r) : q β§ p β§ r := by
obtain β¨hβ, β¨hβ, hββ©β© from h
apply And.intro
assumption
apply And.intro
assumption
assumption
|
743f09abddd8db037cae7c564dc8883fe322c0f1 | 49bd2218ae088932d847f9030c8dbff1c5607bb7 | /src/topology/basic.lean | be5a4e66154505c69838d954f39aac8494d2d6ce | [
"Apache-2.0"
] | permissive | FredericLeRoux/mathlib | e8f696421dd3e4edc8c7edb3369421c8463d7bac | 3645bf8fb426757e0a20af110d1fdded281d286e | refs/heads/master | 1,607,062,870,732 | 1,578,513,186,000 | 1,578,513,186,000 | 231,653,181 | 0 | 0 | Apache-2.0 | 1,578,080,327,000 | 1,578,080,326,000 | null | UTF-8 | Lean | false | false | 35,497 | 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, Jeremy Avigad
-/
import order.filter
/-!
# Basic theory of topological spaces.
The main definition is the type class `topological space Ξ±` which endows a type `Ξ±` with a topology.
Then `set Ξ±` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and
`frontier`. Each point `x` of `Ξ±` gets a neighborhood filter `π x`.
This file also defines locally finite families of subsets of `Ξ±`.
For topological spaces `Ξ±` and `Ξ²`, a function `f : Ξ± β Ξ²` and a point `a : Ξ±`,
`continuous_at f a` means `f` is continuous at `a`, and global continuity is
`continuous f`. There is also a version of continuity `pcontinuous` for
partially defined functions.
## Implementation notes
Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in
`docs/theories/topology.md`.
## References
* [N. Bourbaki, *General Topology*][bourbaki1966]
* [I. M. James, *Topologies and Uniformities*][james1999]
## Tags
topological space, interior, closure, frontier, neighborhood, continuity, continuous function
-/
open set filter lattice classical
open_locale classical
universes u v w
/-- A topology on `Ξ±`. -/
structure topological_space (Ξ± : Type u) :=
(is_open : set Ξ± β Prop)
(is_open_univ : is_open univ)
(is_open_inter : βs t, is_open s β is_open t β is_open (s β© t))
(is_open_sUnion : βs, (βtβs, is_open t) β is_open (ββ s))
attribute [class] topological_space
section topological_space
variables {Ξ± : Type u} {Ξ² : Type v} {ΞΉ : Sort w} {a : Ξ±} {s sβ sβ : set Ξ±} {p pβ pβ : Ξ± β Prop}
@[ext]
lemma topological_space_eq : β {f g : topological_space Ξ±}, f.is_open = g.is_open β f = g
| β¨a, _, _, _β© β¨b, _, _, _β© rfl := rfl
section
variables [t : topological_space Ξ±]
include t
/-- `is_open s` means that `s` is open in the ambient topological space on `Ξ±` -/
def is_open (s : set Ξ±) : Prop := topological_space.is_open t s
@[simp]
lemma is_open_univ : is_open (univ : set Ξ±) := topological_space.is_open_univ t
lemma is_open_inter (hβ : is_open sβ) (hβ : is_open sβ) : is_open (sβ β© sβ) :=
topological_space.is_open_inter t sβ sβ hβ hβ
lemma is_open_sUnion {s : set (set Ξ±)} (h : βt β s, is_open t) : is_open (ββ s) :=
topological_space.is_open_sUnion t s h
end
lemma is_open_fold {s : set Ξ±} {t : topological_space Ξ±} : t.is_open s = @is_open Ξ± t s :=
rfl
variables [topological_space Ξ±]
lemma is_open_Union {f : ΞΉ β set Ξ±} (h : βi, is_open (f i)) : is_open (βi, f i) :=
is_open_sUnion $ by rintro _ β¨i, rflβ©; exact h i
lemma is_open_bUnion {s : set Ξ²} {f : Ξ² β set Ξ±} (h : βiβs, is_open (f i)) :
is_open (βiβs, f i) :=
is_open_Union $ assume i, is_open_Union $ assume hi, h i hi
lemma is_open_union (hβ : is_open sβ) (hβ : is_open sβ) : is_open (sβ βͺ sβ) :=
by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 β¨hβ, hββ©)
@[simp] lemma is_open_empty : is_open (β
: set Ξ±) :=
by rw β sUnion_empty; exact is_open_sUnion (assume a, false.elim)
lemma is_open_sInter {s : set (set Ξ±)} (hs : finite s) : (βt β s, is_open t) β is_open (ββ s) :=
finite.induction_on hs (Ξ» _, by rw sInter_empty; exact is_open_univ) $
Ξ» a s has hs ih h, by rw sInter_insert; exact
is_open_inter (h _ $ mem_insert _ _) (ih $ Ξ» t, h t β mem_insert_of_mem _)
lemma is_open_bInter {s : set Ξ²} {f : Ξ² β set Ξ±} (hs : finite s) :
(βiβs, is_open (f i)) β is_open (βiβs, f i) :=
finite.induction_on hs
(Ξ» _, by rw bInter_empty; exact is_open_univ)
(Ξ» a s has hs ih h, by rw bInter_insert; exact
is_open_inter (h a (mem_insert _ _)) (ih (Ξ» i hi, h i (mem_insert_of_mem _ hi))))
lemma is_open_Inter [fintype Ξ²] {s : Ξ² β set Ξ±}
(h : β i, is_open (s i)) : is_open (β i, s i) :=
suffices is_open (β (i : Ξ²) (hi : i β @univ Ξ²), s i), by simpa,
is_open_bInter finite_univ (Ξ» i _, h i)
lemma is_open_Inter_prop {p : Prop} {s : p β set Ξ±}
(h : β h : p, is_open (s h)) : is_open (Inter s) :=
by by_cases p; simp *
lemma is_open_const {p : Prop} : is_open {a : Ξ± | p} :=
by_cases
(assume : p, begin simp only [this]; exact is_open_univ end)
(assume : Β¬ p, begin simp only [this]; exact is_open_empty end)
lemma is_open_and : is_open {a | pβ a} β is_open {a | pβ a} β is_open {a | pβ a β§ pβ a} :=
is_open_inter
/-- A set is closed if its complement is open -/
def is_closed (s : set Ξ±) : Prop := is_open (-s)
@[simp] lemma is_closed_empty : is_closed (β
: set Ξ±) :=
by unfold is_closed; rw compl_empty; exact is_open_univ
@[simp] lemma is_closed_univ : is_closed (univ : set Ξ±) :=
by unfold is_closed; rw compl_univ; exact is_open_empty
lemma is_closed_union : is_closed sβ β is_closed sβ β is_closed (sβ βͺ sβ) :=
Ξ» hβ hβ, by unfold is_closed; rw compl_union; exact is_open_inter hβ hβ
lemma is_closed_sInter {s : set (set Ξ±)} : (βt β s, is_closed t) β is_closed (ββ s) :=
by simp only [is_closed, compl_sInter, sUnion_image]; exact assume h, is_open_Union $ assume t, is_open_Union $ assume ht, h t ht
lemma is_closed_Inter {f : ΞΉ β set Ξ±} (h : βi, is_closed (f i)) : is_closed (βi, f i ) :=
is_closed_sInter $ assume t β¨i, (heq : f i = t)β©, heq βΈ h i
@[simp] lemma is_open_compl_iff {s : set Ξ±} : is_open (-s) β is_closed s := iff.rfl
@[simp] lemma is_closed_compl_iff {s : set Ξ±} : is_closed (-s) β is_open s :=
by rw [βis_open_compl_iff, compl_compl]
lemma is_open_diff {s t : set Ξ±} (hβ : is_open s) (hβ : is_closed t) : is_open (s \ t) :=
is_open_inter hβ $ is_open_compl_iff.mpr hβ
lemma is_closed_inter (hβ : is_closed sβ) (hβ : is_closed sβ) : is_closed (sβ β© sβ) :=
by rw [is_closed, compl_inter]; exact is_open_union hβ hβ
lemma is_closed_bUnion {s : set Ξ²} {f : Ξ² β set Ξ±} (hs : finite s) :
(βiβs, is_closed (f i)) β is_closed (βiβs, f i) :=
finite.induction_on hs
(Ξ» _, by rw bUnion_empty; exact is_closed_empty)
(Ξ» a s has hs ih h, by rw bUnion_insert; exact
is_closed_union (h a (mem_insert _ _)) (ih (Ξ» i hi, h i (mem_insert_of_mem _ hi))))
lemma is_closed_Union [fintype Ξ²] {s : Ξ² β set Ξ±}
(h : β i, is_closed (s i)) : is_closed (Union s) :=
suffices is_closed (β (i : Ξ²) (hi : i β @univ Ξ²), s i),
by convert this; simp [set.ext_iff],
is_closed_bUnion finite_univ (Ξ» i _, h i)
lemma is_closed_Union_prop {p : Prop} {s : p β set Ξ±}
(h : β h : p, is_closed (s h)) : is_closed (Union s) :=
by by_cases p; simp *
lemma is_closed_imp {p q : Ξ± β Prop} (hp : is_open {x | p x})
(hq : is_closed {x | q x}) : is_closed {x | p x β q x} :=
have {x | p x β q x} = (- {x | p x}) βͺ {x | q x}, from set.ext $ Ξ» x, imp_iff_not_or,
by rw [this]; exact is_closed_union (is_closed_compl_iff.mpr hp) hq
lemma is_open_neg : is_closed {a | p a} β is_open {a | Β¬ p a} :=
is_open_compl_iff.mpr
/-- The interior of a set `s` is the largest open subset of `s`. -/
def interior (s : set Ξ±) : set Ξ± := ββ {t | is_open t β§ t β s}
lemma mem_interior {s : set Ξ±} {x : Ξ±} :
x β interior s β β t β s, is_open t β§ x β t :=
by simp only [interior, mem_set_of_eq, exists_prop, and_assoc, and.left_comm]
@[simp] lemma is_open_interior {s : set Ξ±} : is_open (interior s) :=
is_open_sUnion $ assume t β¨hβ, hββ©, hβ
lemma interior_subset {s : set Ξ±} : interior s β s :=
sUnion_subset $ assume t β¨hβ, hββ©, hβ
lemma interior_maximal {s t : set Ξ±} (hβ : t β s) (hβ : is_open t) : t β interior s :=
subset_sUnion_of_mem β¨hβ, hββ©
lemma interior_eq_of_open {s : set Ξ±} (h : is_open s) : interior s = s :=
subset.antisymm interior_subset (interior_maximal (subset.refl s) h)
lemma interior_eq_iff_open {s : set Ξ±} : interior s = s β is_open s :=
β¨assume h, h βΈ is_open_interior, interior_eq_of_openβ©
lemma subset_interior_iff_open {s : set Ξ±} : s β interior s β is_open s :=
by simp only [interior_eq_iff_open.symm, subset.antisymm_iff, interior_subset, true_and]
lemma subset_interior_iff_subset_of_open {s t : set Ξ±} (hβ : is_open s) :
s β interior t β s β t :=
β¨assume h, subset.trans h interior_subset, assume hβ, interior_maximal hβ hββ©
lemma interior_mono {s t : set Ξ±} (h : s β t) : interior s β interior t :=
interior_maximal (subset.trans interior_subset h) is_open_interior
@[simp] lemma interior_empty : interior (β
: set Ξ±) = β
:=
interior_eq_of_open is_open_empty
@[simp] lemma interior_univ : interior (univ : set Ξ±) = univ :=
interior_eq_of_open is_open_univ
@[simp] lemma interior_interior {s : set Ξ±} : interior (interior s) = interior s :=
interior_eq_of_open is_open_interior
@[simp] lemma interior_inter {s t : set Ξ±} : interior (s β© t) = interior s β© interior t :=
subset.antisymm
(subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t))
(interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open_inter is_open_interior is_open_interior)
lemma interior_union_is_closed_of_interior_empty {s t : set Ξ±} (hβ : is_closed s) (hβ : interior t = β
) :
interior (s βͺ t) = interior s :=
have interior (s βͺ t) β s, from
assume x β¨u, β¨(huβ : is_open u), (huβ : u β s βͺ t)β©, (hxβ : x β u)β©,
classical.by_contradiction $ assume hxβ : x β s,
have u \ s β t,
from assume x β¨hβ, hββ©, or.resolve_left (huβ hβ) hβ,
have u \ s β interior t,
by rwa subset_interior_iff_subset_of_open (is_open_diff huβ hβ),
have u \ s β β
,
by rwa hβ at this,
this β¨hxβ, hxββ©,
subset.antisymm
(interior_maximal this is_open_interior)
(interior_mono $ subset_union_left _ _)
lemma is_open_iff_forall_mem_open : is_open s β β x β s, β t β s, is_open t β§ x β t :=
by rw β subset_interior_iff_open; simp only [subset_def, mem_interior]
/-- The closure of `s` is the smallest closed set containing `s`. -/
def closure (s : set Ξ±) : set Ξ± := ββ {t | is_closed t β§ s β t}
@[simp] lemma is_closed_closure {s : set Ξ±} : is_closed (closure s) :=
is_closed_sInter $ assume t β¨hβ, hββ©, hβ
lemma subset_closure {s : set Ξ±} : s β closure s :=
subset_sInter $ assume t β¨hβ, hββ©, hβ
lemma closure_minimal {s t : set Ξ±} (hβ : s β t) (hβ : is_closed t) : closure s β t :=
sInter_subset_of_mem β¨hβ, hββ©
lemma closure_eq_of_is_closed {s : set Ξ±} (h : is_closed s) : closure s = s :=
subset.antisymm (closure_minimal (subset.refl s) h) subset_closure
lemma closure_eq_iff_is_closed {s : set Ξ±} : closure s = s β is_closed s :=
β¨assume h, h βΈ is_closed_closure, closure_eq_of_is_closedβ©
lemma closure_subset_iff_subset_of_is_closed {s t : set Ξ±} (hβ : is_closed t) :
closure s β t β s β t :=
β¨subset.trans subset_closure, assume h, closure_minimal h hββ©
lemma closure_mono {s t : set Ξ±} (h : s β t) : closure s β closure t :=
closure_minimal (subset.trans h subset_closure) is_closed_closure
lemma monotone_closure (Ξ± : Type*) [topological_space Ξ±] : monotone (@closure Ξ± _) :=
Ξ» _ _, closure_mono
lemma closure_inter_subset_inter_closure (s t : set Ξ±) :
closure (s β© t) β closure s β© closure t :=
(monotone_closure Ξ±).map_inf_le s t
lemma is_closed_of_closure_subset {s : set Ξ±} (h : closure s β s) : is_closed s :=
by rw subset.antisymm subset_closure h; exact is_closed_closure
@[simp] lemma closure_empty : closure (β
: set Ξ±) = β
:=
closure_eq_of_is_closed is_closed_empty
lemma closure_empty_iff (s : set Ξ±) : closure s = β
β s = β
:=
begin
split; intro h,
{ rw set.eq_empty_iff_forall_not_mem,
intros x H,
simpa only [h] using subset_closure H },
{ exact (eq.symm h) βΈ closure_empty },
end
@[simp] lemma closure_univ : closure (univ : set Ξ±) = univ :=
closure_eq_of_is_closed is_closed_univ
@[simp] lemma closure_closure {s : set Ξ±} : closure (closure s) = closure s :=
closure_eq_of_is_closed is_closed_closure
@[simp] lemma closure_union {s t : set Ξ±} : closure (s βͺ t) = closure s βͺ closure t :=
subset.antisymm
(closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed_union is_closed_closure is_closed_closure)
((monotone_closure Ξ±).le_map_sup s t)
lemma interior_subset_closure {s : set Ξ±} : interior s β closure s :=
subset.trans interior_subset subset_closure
lemma closure_eq_compl_interior_compl {s : set Ξ±} : closure s = - interior (- s) :=
begin
unfold interior closure is_closed,
rw [compl_sUnion, compl_image_set_of],
simp only [compl_subset_compl]
end
@[simp] lemma interior_compl {s : set Ξ±} : interior (- s) = - closure s :=
by simp [closure_eq_compl_interior_compl]
@[simp] lemma closure_compl {s : set Ξ±} : closure (- s) = - interior s :=
by simp [closure_eq_compl_interior_compl]
theorem mem_closure_iff {s : set Ξ±} {a : Ξ±} : a β closure s β β o, is_open o β a β o β o β© s β β
:=
β¨Ξ» h o oo ao os,
have s β -o, from Ξ» x xs xo, @ne_empty_of_mem Ξ± (oβ©s) x β¨xo, xsβ© os,
closure_minimal this (is_closed_compl_iff.2 oo) h ao,
Ξ» H c β¨hβ, hββ©, classical.by_contradiction $ Ξ» nc,
let β¨x, hc, hsβ© := exists_mem_of_ne_empty (H _ hβ nc) in hc (hβ hs)β©
lemma dense_iff_inter_open {s : set Ξ±} : closure s = univ β β U, is_open U β U β β
β U β© s β β
:=
begin
split ; intro h,
{ intros U U_op U_ne,
cases exists_mem_of_ne_empty U_ne with x x_in,
exact mem_closure_iff.1 (by simp only [h]) U U_op x_in },
{ apply eq_univ_of_forall, intro x,
rw mem_closure_iff,
intros U U_op x_in,
exact h U U_op (ne_empty_of_mem x_in) },
end
lemma dense_of_subset_dense {sβ sβ : set Ξ±} (h : sβ β sβ) (hd : closure sβ = univ) :
closure sβ = univ :=
by { rw [β univ_subset_iff, β hd], exact closure_mono h }
/-- The frontier of a set is the set of points between the closure and interior. -/
def frontier (s : set Ξ±) : set Ξ± := closure s \ interior s
lemma frontier_eq_closure_inter_closure {s : set Ξ±} :
frontier s = closure s β© closure (- s) :=
by rw [closure_compl, frontier, diff_eq]
/-- The complement of a set has the same frontier as the original set. -/
@[simp] lemma frontier_compl (s : set Ξ±) : frontier (-s) = frontier s :=
by simp only [frontier_eq_closure_inter_closure, lattice.neg_neg, inter_comm]
lemma frontier_inter_subset (s t : set Ξ±) :
frontier (s β© t) β (frontier s β© closure t) βͺ (closure s β© frontier t) :=
begin
simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union],
convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t),
simp only [inter_distrib_left, inter_distrib_right, inter_assoc],
congr' 2,
apply inter_comm
end
lemma frontier_union_subset (s t : set Ξ±) :
frontier (s βͺ t) β (frontier s β© closure (-t)) βͺ (closure (-s) β© frontier t) :=
by simpa only [frontier_compl, (compl_union _ _).symm]
using frontier_inter_subset (-s) (-t)
lemma is_closed.frontier_eq {s : set Ξ±} (hs : is_closed s) : frontier s = s \ interior s :=
by rw [frontier, closure_eq_of_is_closed hs]
lemma is_open.frontier_eq {s : set Ξ±} (hs : is_open s) : frontier s = closure s \ s :=
by rw [frontier, interior_eq_of_open hs]
/-- The frontier of a set is closed. -/
lemma is_closed_frontier {s : set Ξ±} : is_closed (frontier s) :=
by rw frontier_eq_closure_inter_closure; exact is_closed_inter is_closed_closure is_closed_closure
/-- The frontier of a set has no interior point. -/
lemma interior_frontier {s : set Ξ±} (h : is_closed s) : interior (frontier s) = β
:=
begin
have A : frontier s = s \ interior s, from h.frontier_eq,
have B : interior (frontier s) β interior s, by rw A; exact interior_mono (diff_subset _ _),
have C : interior (frontier s) β frontier s := interior_subset,
have : interior (frontier s) β (interior s) β© (s \ interior s) :=
subset_inter B (by simpa [A] using C),
rwa [inter_diff_self, subset_empty_iff] at this,
end
/-- neighbourhood filter -/
def nhds (a : Ξ±) : filter Ξ± := (β¨
s β {s : set Ξ± | a β s β§ is_open s}, principal s)
localized "notation `π` := nhds" in topological_space
lemma nhds_def (a : Ξ±) : π a = (β¨
s β {s : set Ξ± | a β s β§ is_open s}, principal s) := rfl
lemma le_nhds_iff {f a} : f β€ π a β β s : set Ξ±, a β s β is_open s β s β f :=
by simp [nhds_def]
lemma nhds_le_of_le {f a} {s : set Ξ±} (h : a β s) (o : is_open s) (sf : principal s β€ f) : π a β€ f :=
by rw nhds_def; exact infi_le_of_le s (infi_le_of_le β¨h, oβ© sf)
lemma nhds_sets {a : Ξ±} : (π a).sets = {s | βtβs, is_open t β§ a β t} :=
calc (π a).sets = (βsβ{s : set Ξ±| a β s β§ is_open s}, (principal s).sets) : binfi_sets_eq
(assume x β¨hxβ, hxββ© y β¨hyβ, hyββ©,
β¨x β© y, β¨β¨hxβ, hyββ©, is_open_inter hxβ hyββ©,
le_principal_iff.2 (inter_subset_left _ _),
le_principal_iff.2 (inter_subset_right _ _)β©)
β¨univ, mem_univ _, is_open_univβ©
... = {s | βtβs, is_open t β§ a β t} :
le_antisymm
(supr_le $ assume i, supr_le $ assume β¨hiβ, hiββ© t ht, β¨i, ht, hiβ, hiββ©)
(assume t β¨i, hiβ, hiβ, hiββ©, mem_Union.2 β¨i, mem_Union.2 β¨β¨hiβ, hiββ©, hiββ©β©)
lemma map_nhds {a : Ξ±} {f : Ξ± β Ξ²} :
map f (π a) = (β¨
s β {s : set Ξ± | a β s β§ is_open s}, principal (image f s)) :=
calc map f (π a) = (β¨
s β {s : set Ξ± | a β s β§ is_open s}, map f (principal s)) :
map_binfi_eq
(assume x β¨hxβ, hxββ© y β¨hyβ, hyββ©,
β¨x β© y, β¨β¨hxβ, hyββ©, is_open_inter hxβ hyββ©,
le_principal_iff.2 (inter_subset_left _ _),
le_principal_iff.2 (inter_subset_right _ _)β©)
β¨univ, mem_univ _, is_open_univβ©
... = _ : by simp only [map_principal]
attribute [irreducible] nhds
lemma mem_nhds_sets_iff {a : Ξ±} {s : set Ξ±} :
s β π a β βtβs, is_open t β§ a β t :=
by simp only [nhds_sets, mem_set_of_eq, exists_prop]
lemma mem_of_nhds {a : Ξ±} {s : set Ξ±} : s β π a β a β s :=
Ξ» H, let β¨t, ht, _, hsβ© := mem_nhds_sets_iff.1 H in ht hs
lemma mem_nhds_sets {a : Ξ±} {s : set Ξ±} (hs : is_open s) (ha : a β s) :
s β π a :=
mem_nhds_sets_iff.2 β¨s, subset.refl _, hs, haβ©
theorem all_mem_nhds (x : Ξ±) (P : set Ξ± β Prop) (hP : β s t, s β t β P s β P t) :
(β s β π x, P s) β (β s, is_open s β x β s β P s) :=
iff.intro
(Ξ» h s os xs, h s (mem_nhds_sets os xs))
(Ξ» h t,
begin
change t β (π x).sets β P t,
rw nhds_sets,
rintros β¨s, hs, opens, xsβ©,
exact hP _ _ hs (h s opens xs),
end)
theorem all_mem_nhds_filter (x : Ξ±) (f : set Ξ± β set Ξ²) (hf : β s t, s β t β f s β f t)
(l : filter Ξ²) :
(β s β π x, f s β l) β (β s, is_open s β x β s β f s β l) :=
all_mem_nhds _ _ (Ξ» s t ssubt h, mem_sets_of_superset h (hf s t ssubt))
theorem rtendsto_nhds {r : rel Ξ² Ξ±} {l : filter Ξ²} {a : Ξ±} :
rtendsto r l (π a) β (β s, is_open s β a β s β r.core s β l) :=
all_mem_nhds_filter _ _ (Ξ» s t, id) _
theorem rtendsto'_nhds {r : rel Ξ² Ξ±} {l : filter Ξ²} {a : Ξ±} :
rtendsto' r l (π a) β (β s, is_open s β a β s β r.preimage s β l) :=
by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono }
theorem ptendsto_nhds {f : Ξ² β. Ξ±} {l : filter Ξ²} {a : Ξ±} :
ptendsto f l (π a) β (β s, is_open s β a β s β f.core s β l) :=
rtendsto_nhds
theorem ptendsto'_nhds {f : Ξ² β. Ξ±} {l : filter Ξ²} {a : Ξ±} :
ptendsto' f l (π a) β (β s, is_open s β a β s β f.preimage s β l) :=
rtendsto'_nhds
theorem tendsto_nhds {f : Ξ² β Ξ±} {l : filter Ξ²} {a : Ξ±} :
tendsto f l (π a) β (β s, is_open s β a β s β f β»ΒΉ' s β l) :=
all_mem_nhds_filter _ _ (Ξ» s t h, preimage_mono h) _
lemma tendsto_const_nhds {a : Ξ±} {f : filter Ξ²} : tendsto (Ξ»b:Ξ², a) f (π a) :=
tendsto_nhds.mpr $ assume s hs ha, univ_mem_sets' $ assume _, ha
lemma pure_le_nhds : pure β€ (π : Ξ± β filter Ξ±) :=
assume a, by rw nhds_def; exact le_infi
(assume s, le_infi $ assume β¨hβ, _β©, principal_mono.mpr $
singleton_subset_iff.2 hβ)
lemma tendsto_pure_nhds {Ξ± : Type*} [topological_space Ξ²] (f : Ξ± β Ξ²) (a : Ξ±) :
tendsto f (pure a) (π (f a)) :=
begin
rw [tendsto, filter.map_pure],
exact pure_le_nhds (f a)
end
@[simp] lemma nhds_neq_bot {a : Ξ±} : π a β β₯ :=
assume : π a = β₯,
have pure a = (β₯ : filter Ξ±),
from lattice.bot_unique $ this βΈ pure_le_nhds a,
pure_neq_bot this
lemma interior_eq_nhds {s : set Ξ±} : interior s = {a | π a β€ principal s} :=
set.ext $ Ξ» x, by simp only [mem_interior, le_principal_iff, mem_nhds_sets_iff]; refl
lemma mem_interior_iff_mem_nhds {s : set Ξ±} {a : Ξ±} :
a β interior s β s β π a :=
by simp only [interior_eq_nhds, le_principal_iff]; refl
lemma is_open_iff_nhds {s : set Ξ±} : is_open s β βaβs, π a β€ principal s :=
calc is_open s β s β interior s : subset_interior_iff_open.symm
... β (βaβs, π a β€ principal s) : by rw [interior_eq_nhds]; refl
lemma is_open_iff_mem_nhds {s : set Ξ±} : is_open s β βaβs, s β π a :=
is_open_iff_nhds.trans $ forall_congr $ Ξ» _, imp_congr_right $ Ξ» _, le_principal_iff
lemma closure_eq_nhds {s : set Ξ±} : closure s = {a | π a β principal s β β₯} :=
calc closure s = - interior (- s) : closure_eq_compl_interior_compl
... = {a | Β¬ π a β€ principal (-s)} : by rw [interior_eq_nhds]; refl
... = {a | π a β principal s β β₯} : set.ext $ assume a, not_congr
(inf_eq_bot_iff_le_compl
(show principal s β principal (-s) = β€, by simp only [sup_principal, union_compl_self, principal_univ])
(by simp only [inf_principal, inter_compl_self, principal_empty])).symm
theorem mem_closure_iff_nhds {s : set Ξ±} {a : Ξ±} : a β closure s β β t β π a, t β© s β β
:=
mem_closure_iff.trans
β¨Ξ» H t ht, subset_ne_empty
(inter_subset_inter_left _ interior_subset)
(H _ is_open_interior (mem_interior_iff_mem_nhds.2 ht)),
Ξ» H o oo ao, H _ (mem_nhds_sets oo ao)β©
/-- `x` belongs to the closure of `s` if and only if some ultrafilter
supported on `s` converges to `x`. -/
lemma mem_closure_iff_ultrafilter {s : set Ξ±} {x : Ξ±} :
x β closure s β β (u : ultrafilter Ξ±), s β u.val β§ u.val β€ π x :=
begin
rw closure_eq_nhds, change π x β principal s β β₯ β _, symmetry,
convert exists_ultrafilter_iff _, ext u,
rw [βle_principal_iff, inf_comm, le_inf_iff]
end
lemma is_closed_iff_nhds {s : set Ξ±} : is_closed s β βa, π a β principal s β β₯ β a β s :=
calc is_closed s β closure s = s : by rw [closure_eq_iff_is_closed]
... β closure s β s : β¨assume h, by rw h, assume h, subset.antisymm h subset_closureβ©
... β (βa, π a β principal s β β₯ β a β s) : by rw [closure_eq_nhds]; refl
lemma closure_inter_open {s t : set Ξ±} (h : is_open s) : s β© closure t β closure (s β© t) :=
assume a β¨hs, htβ©,
have s β π a, from mem_nhds_sets h hs,
have π a β principal s = π a, from inf_of_le_left $ by rwa le_principal_iff,
have π a β principal (s β© t) β β₯,
from calc π a β principal (s β© t) = π a β (principal s β principal t) : by rw inf_principal
... = π a β principal t : by rw [βinf_assoc, this]
... β β₯ : by rw [closure_eq_nhds] at ht; assumption,
by rw [closure_eq_nhds]; assumption
lemma closure_diff {s t : set Ξ±} : closure s - closure t β closure (s - t) :=
calc closure s \ closure t = (- closure t) β© closure s : by simp only [diff_eq, inter_comm]
... β closure (- closure t β© s) : closure_inter_open $ is_open_compl_iff.mpr $ is_closed_closure
... = closure (s \ closure t) : by simp only [diff_eq, inter_comm]
... β closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure
lemma mem_of_closed_of_tendsto {f : Ξ² β Ξ±} {b : filter Ξ²} {a : Ξ±} {s : set Ξ±}
(hb : b β β₯) (hf : tendsto f b (π a)) (hs : is_closed s) (h : f β»ΒΉ' s β b) : a β s :=
have b.map f β€ π a β principal s,
from le_trans (le_inf (le_refl _) (le_principal_iff.mpr h)) (inf_le_inf hf (le_refl _)),
is_closed_iff_nhds.mp hs a $ neq_bot_of_le_neq_bot (map_ne_bot hb) this
lemma mem_of_closed_of_tendsto' {f : Ξ² β Ξ±} {x : filter Ξ²} {a : Ξ±} {s : set Ξ±}
(hf : tendsto f x (π a)) (hs : is_closed s) (h : x β principal (f β»ΒΉ' s) β β₯) : a β s :=
is_closed_iff_nhds.mp hs _ $ neq_bot_of_le_neq_bot (@map_ne_bot _ _ _ f h) $
le_inf (le_trans (map_mono $ inf_le_left) hf) $
le_trans (map_mono $ inf_le_right_of_le $ by simp only [comap_principal, le_principal_iff]; exact subset.refl _) (@map_comap_le _ _ _ f)
lemma mem_closure_of_tendsto {f : Ξ² β Ξ±} {b : filter Ξ²} {a : Ξ±} {s : set Ξ±}
(hb : b β β₯) (hf : tendsto f b (π a)) (h : f β»ΒΉ' s β b) : a β closure s :=
mem_of_closed_of_tendsto hb hf (is_closed_closure) $
filter.mem_sets_of_superset h (preimage_mono subset_closure)
/-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter.
Then `f` tends to `a` along `l` restricted to `s` if and only it tends to `a` along `l`. -/
lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : Ξ² β Ξ±} {l : filter Ξ²} {s : set Ξ²}
{a : Ξ±} (h : β x β s, f x = a) :
tendsto f (l β principal s) (π a) β tendsto f l (π a) :=
begin
rw [tendsto_iff_comap, tendsto_iff_comap],
replace h : principal (-s) β€ comap f (π a),
{ rintros U β¨t, ht, htUβ© x hx,
have : f x β t, from (h x hx).symm βΈ mem_of_nhds ht,
exact htU this },
refine β¨Ξ» h', _, le_trans inf_le_leftβ©,
have := sup_le h' h,
rw [sup_inf_right, sup_principal, union_compl_self, principal_univ,
inf_top_eq, sup_le_iff] at this,
exact this.1
end
section lim
variables [inhabited Ξ±]
/-- If `f` is a filter, then `lim f` is a limit of the filter, if it exists. -/
noncomputable def lim (f : filter Ξ±) : Ξ± := epsilon $ Ξ»a, f β€ π a
lemma lim_spec {f : filter Ξ±} (h : βa, f β€ π a) : f β€ π (lim f) := epsilon_spec h
end lim
/- locally finite family [General Topology (Bourbaki, 1995)] -/
section locally_finite
/-- A family of sets in `set Ξ±` is locally finite if at every point `x:Ξ±`,
there is a neighborhood of `x` which meets only finitely many sets in the family -/
def locally_finite (f : Ξ² β set Ξ±) :=
βx:Ξ±, βt β π x, finite {i | f i β© t β β
}
lemma locally_finite_of_finite {f : Ξ² β set Ξ±} (h : finite (univ : set Ξ²)) : locally_finite f :=
assume x, β¨univ, univ_mem_sets, finite_subset h $ subset_univ _β©
lemma locally_finite_subset
{fβ fβ : Ξ² β set Ξ±} (hfβ : locally_finite fβ) (hf : βb, fβ b β fβ b) : locally_finite fβ :=
assume a,
let β¨t, htβ, htββ© := hfβ a in
β¨t, htβ, finite_subset htβ $ assume i hi,
neq_bot_of_le_neq_bot hi $ inter_subset_inter (hf i) $ subset.refl _β©
lemma is_closed_Union_of_locally_finite {f : Ξ² β set Ξ±}
(hβ : locally_finite f) (hβ : βi, is_closed (f i)) : is_closed (βi, f i) :=
is_open_iff_nhds.mpr $ assume a, assume h : a β (βi, f i),
have βi, a β -f i,
from assume i hi, h $ mem_Union.2 β¨i, hiβ©,
have βi, - f i β (π a).sets,
by rw [nhds_sets]; exact assume i, β¨- f i, subset.refl _, hβ i, this iβ©,
let β¨t, h_sets, (h_fin : finite {i | f i β© t β β
})β© := hβ a in
calc π a β€ principal (t β© (β iβ{i | f i β© t β β
}, - f i)) :
begin
rw [le_principal_iff],
apply @filter.inter_mem_sets _ (π a) _ _ h_sets,
apply @filter.Inter_mem_sets _ (π a) _ _ _ h_fin,
exact assume i h, this i
end
... β€ principal (- βi, f i) :
begin
simp only [principal_mono, subset_def, mem_compl_eq, mem_inter_eq,
mem_Inter, mem_set_of_eq, mem_Union, and_imp, not_exists,
not_eq_empty_iff_exists, exists_imp_distrib, (β )],
exact assume x xt ht i xfi, ht i x xfi xt xfi
end
end locally_finite
end topological_space
section continuous
variables {Ξ± : Type*} {Ξ² : Type*} {Ξ³ : Type*} {Ξ΄ : Type*}
variables [topological_space Ξ±] [topological_space Ξ²] [topological_space Ξ³]
open_locale topological_space
/-- A function between topological spaces is continuous if the preimage
of every open set is open. -/
def continuous (f : Ξ± β Ξ²) := βs, is_open s β is_open (f β»ΒΉ' s)
/-- A function between topological spaces is continuous at a point `xβ`
if `f x` tends to `f xβ` when `x` tends to `xβ`. -/
def continuous_at (f : Ξ± β Ξ²) (x : Ξ±) := tendsto f (π x) (π (f x))
lemma continuous_at.preimage_mem_nhds {f : Ξ± β Ξ²} {x : Ξ±} {t : set Ξ²} (h : continuous_at f x)
(ht : t β π (f x)) : f β»ΒΉ' t β π x :=
h ht
lemma continuous_id : continuous (id : Ξ± β Ξ±) :=
assume s h, h
lemma continuous.comp {g : Ξ² β Ξ³} {f : Ξ± β Ξ²} (hg : continuous g) (hf : continuous f) :
continuous (g β f) :=
assume s h, hf _ (hg s h)
lemma continuous_at.comp {g : Ξ² β Ξ³} {f : Ξ± β Ξ²} {x : Ξ±}
(hg : continuous_at g (f x)) (hf : continuous_at f x) :
continuous_at (g β f) x :=
hg.comp hf
lemma continuous.tendsto {f : Ξ± β Ξ²} (hf : continuous f) (x) :
tendsto f (π x) (π (f x)) | s :=
show s β π (f x) β s β map f (π x),
by simp [nhds_sets]; exact
assume t t_subset t_open fx_in_t,
β¨f β»ΒΉ' t, preimage_mono t_subset, hf t t_open, fx_in_tβ©
lemma continuous.continuous_at {f : Ξ± β Ξ²} {x : Ξ±} (h : continuous f) :
continuous_at f x :=
h.tendsto x
lemma continuous_iff_continuous_at {f : Ξ± β Ξ²} : continuous f β β x, continuous_at f x :=
β¨continuous.tendsto,
assume hf : βx, tendsto f (π x) (π (f x)),
assume s, assume hs : is_open s,
have βa, f a β s β s β π (f a),
by simp [nhds_sets]; exact assume a ha, β¨s, subset.refl s, hs, haβ©,
show is_open (f β»ΒΉ' s),
by simp [is_open_iff_nhds]; exact assume a ha, hf a (this a ha)β©
lemma continuous_const {b : Ξ²} : continuous (Ξ»a:Ξ±, b) :=
continuous_iff_continuous_at.mpr $ assume a, tendsto_const_nhds
lemma continuous_at_const {x : Ξ±} {b : Ξ²} : continuous_at (Ξ» a:Ξ±, b) x :=
continuous_const.continuous_at
lemma continuous_at_id {x : Ξ±} : continuous_at id x :=
continuous_id.continuous_at
lemma continuous_iff_is_closed {f : Ξ± β Ξ²} :
continuous f β (βs, is_closed s β is_closed (f β»ΒΉ' s)) :=
β¨assume hf s hs, hf (-s) hs,
assume hf s, by rw [βis_closed_compl_iff, βis_closed_compl_iff]; exact hf _β©
lemma continuous_at_iff_ultrafilter {f : Ξ± β Ξ²} (x) : continuous_at f x β
β g, is_ultrafilter g β g β€ π x β g.map f β€ π (f x) :=
tendsto_iff_ultrafilter f (π x) (π (f x))
lemma continuous_iff_ultrafilter {f : Ξ± β Ξ²} :
continuous f β β x g, is_ultrafilter g β g β€ π x β g.map f β€ π (f x) :=
by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter]
/-- A piecewise defined function `if p then f else g` is continuous, if both `f` and `g`
are continuous, and they coincide on the frontier (boundary) of the set `{a | p a}`. -/
lemma continuous_if {p : Ξ± β Prop} {f g : Ξ± β Ξ²} {h : βa, decidable (p a)}
(hp : βaβfrontier {a | p a}, f a = g a) (hf : continuous f) (hg : continuous g) :
continuous (Ξ»a, @ite (p a) (h a) Ξ² (f a) (g a)) :=
continuous_iff_is_closed.mpr $
assume s hs,
have (Ξ»a, ite (p a) (f a) (g a)) β»ΒΉ' s =
(closure {a | p a} β© f β»ΒΉ' s) βͺ (closure {a | Β¬ p a} β© g β»ΒΉ' s),
from set.ext $ assume a,
classical.by_cases
(assume : a β frontier {a | p a},
have hac : a β closure {a | p a}, from this.left,
have hai : a β closure {a | Β¬ p a},
from have a β - interior {a | p a}, from this.right, by rwa [βclosure_compl] at this,
by by_cases p a; simp [h, hp a this, hac, hai, iff_def] {contextual := tt})
(assume hf : a β - frontier {a | p a},
classical.by_cases
(assume : p a,
have hc : a β closure {a | p a}, from subset_closure this,
have hnc : a β closure {a | Β¬ p a},
by show a β closure (- {a | p a}); rw [closure_compl]; simpa [frontier, hc] using hf,
by simp [this, hc, hnc])
(assume : Β¬ p a,
have hc : a β closure {a | Β¬ p a}, from subset_closure this,
have hnc : a β closure {a | p a},
begin
have hc : a β closure (- {a | p a}), from hc,
simp [closure_compl] at hc,
simpa [frontier, hc] using hf
end,
by simp [this, hc, hnc])),
by rw [this]; exact is_closed_union
(is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hf s hs)
(is_closed_inter is_closed_closure $ continuous_iff_is_closed.mp hg s hs)
/- Continuity and partial functions -/
/-- Continuity of a partial function -/
def pcontinuous (f : Ξ± β. Ξ²) := β s, is_open s β is_open (f.preimage s)
lemma open_dom_of_pcontinuous {f : Ξ± β. Ξ²} (h : pcontinuous f) : is_open f.dom :=
by rw [βpfun.preimage_univ]; exact h _ is_open_univ
lemma pcontinuous_iff' {f : Ξ± β. Ξ²} :
pcontinuous f β β {x y} (h : y β f x), ptendsto' f (π x) (π y) :=
begin
split,
{ intros h x y h',
rw [ptendsto'_def],
change β (s : set Ξ²), s β (π y).sets β pfun.preimage f s β (π x).sets,
rw [nhds_sets, nhds_sets],
rintros s β¨t, tsubs, opent, ytβ©,
exact β¨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, β¨y, yt, h'β©β©
},
intros hf s os,
rw is_open_iff_nhds,
rintros x β¨y, ys, fxyβ© t,
rw [mem_principal_sets],
assume h : f.preimage s β t,
change t β π x,
apply mem_sets_of_superset _ h,
have h' : β s β π y, f.preimage s β π x,
{ intros s hs,
have : ptendsto' f (π x) (π y) := hf fxy,
rw ptendsto'_def at this,
exact this s hs },
show f.preimage s β π x,
apply h', rw mem_nhds_sets_iff, exact β¨s, set.subset.refl _, os, ysβ©
end
lemma image_closure_subset_closure_image {f : Ξ± β Ξ²} {s : set Ξ±} (h : continuous f) :
f '' closure s β closure (f '' s) :=
have β (a : Ξ±), π a β principal s β β₯ β π (f a) β principal (f '' s) β β₯,
from assume a ha,
have hβ : Β¬ map f (π a β principal s) = β₯,
by rwa[map_eq_bot_iff],
have hβ : map f (π a β principal s) β€ π (f a) β principal (f '' s),
from le_inf
(le_trans (map_mono inf_le_left) $ by rw [continuous_iff_continuous_at] at h; exact h a)
(le_trans (map_mono inf_le_right) $ by simp; exact subset.refl _),
neq_bot_of_le_neq_bot hβ hβ,
by simp [image_subset_iff, closure_eq_nhds]; assumption
lemma mem_closure {s : set Ξ±} {t : set Ξ²} {f : Ξ± β Ξ²} {a : Ξ±}
(hf : continuous f) (ha : a β closure s) (ht : βaβs, f a β t) : f a β closure t :=
subset.trans (image_closure_subset_closure_image hf) (closure_mono $ image_subset_iff.2 ht) $
(mem_image_of_mem f ha)
end continuous
|
d86cc4b4914b854231943b6ffd652eeff50d23c6 | 0e175f34f8dca5ea099671777e8d7446d7d74227 | /library/data/bitvec.lean | a5c5d1d8f536b97527f04cca46c9b838db1effc3 | [
"Apache-2.0"
] | permissive | utensil-contrib/lean | b31266738071c654d96dac8b35d9ccffc8172fda | a28b9c8f78d982a4e82b1e4f7ce7988d87183ae8 | refs/heads/master | 1,670,045,564,075 | 1,597,397,599,000 | 1,597,397,599,000 | 287,528,503 | 0 | 0 | Apache-2.0 | 1,597,408,338,000 | 1,597,408,337,000 | null | UTF-8 | Lean | false | false | 6,797 | lean | /-
Copyright (c) 2015 Joe Hendrix. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joe Hendrix, Sebastian Ullrich
Basic operations on bitvectors.
This is a work-in-progress, and contains additions to other theories.
-/
import data.vector
@[reducible] def bitvec (n : β) := vector bool n
namespace bitvec
open nat
open vector
local infix `++β`:65 := vector.append
-- Create a zero bitvector
@[reducible] protected def zero (n : β) : bitvec n := repeat ff n
-- Create a bitvector with the constant one.
@[reducible] protected def one : Ξ (n : β), bitvec n
| 0 := nil
| (succ n) := repeat ff n ++β tt::nil
protected def cong {a b : β} (h : a = b) : bitvec a β bitvec b
| β¨x, pβ© := β¨x, h βΈ pβ©
-- bitvec specific version of vector.append
def append {m n} : bitvec m β bitvec n β bitvec (m + n) := vector.append
section shift
variable {n : β}
def shl (x : bitvec n) (i : β) : bitvec n :=
bitvec.cong (by simp) $
drop i x ++β repeat ff (min n i)
def fill_shr (x : bitvec n) (i : β) (fill : bool) : bitvec n :=
bitvec.cong
begin
by_cases (i β€ n),
{ have hβ := sub_le n i,
rw [min_eq_right h], rw [min_eq_left hβ, β nat.add_sub_assoc h, nat.add_comm, nat.add_sub_cancel] },
{ have hβ := le_of_not_ge h,
rw [min_eq_left hβ, sub_eq_zero_of_le hβ, zero_min, nat.add_zero] }
end $
repeat fill (min n i) ++β take (n-i) x
-- unsigned shift right
def ushr (x : bitvec n) (i : β) : bitvec n :=
fill_shr x i ff
-- signed shift right
def sshr : Ξ {m : β}, bitvec m β β β bitvec m
| 0 _ _ := nil
| (succ m) x i := head x :: fill_shr (tail x) i (head x)
end shift
section bitwise
variable {n : β}
def not : bitvec n β bitvec n := map bnot
def and : bitvec n β bitvec n β bitvec n := mapβ band
def or : bitvec n β bitvec n β bitvec n := mapβ bor
def xor : bitvec n β bitvec n β bitvec n := mapβ bxor
end bitwise
section arith
variable {n : β}
protected def xor3 (x y c : bool) := bxor (bxor x y) c
protected def carry (x y c : bool) :=
x && y || x && c || y && c
protected def neg (x : bitvec n) : bitvec n :=
let f := Ξ» y c, (y || c, bxor y c) in
prod.snd (map_accumr f x ff)
-- Add with carry (no overflow)
def adc (x y : bitvec n) (c : bool) : bitvec (n+1) :=
let f := Ξ» x y c, (bitvec.carry x y c, bitvec.xor3 x y c) in
let β¨c, zβ© := vector.map_accumrβ f x y c in
c :: z
protected def add (x y : bitvec n) : bitvec n := tail (adc x y ff)
-- Subtract with borrow
def sbb (x y : bitvec n) (b : bool) : bool Γ bitvec n :=
let f := Ξ» x y c, (bitvec.carry (bnot x) y c, bitvec.xor3 x y c) in
vector.map_accumrβ f x y b
protected def sub (x y : bitvec n) : bitvec n := prod.snd (sbb x y ff)
instance : has_zero (bitvec n) := β¨bitvec.zero nβ©
instance : has_one (bitvec n) := β¨bitvec.one nβ©
instance : has_add (bitvec n) := β¨bitvec.addβ©
instance : has_sub (bitvec n) := β¨bitvec.subβ©
instance : has_neg (bitvec n) := β¨bitvec.negβ©
protected def mul (x y : bitvec n) : bitvec n :=
let f := Ξ» r b, cond b (r + r + y) (r + r) in
(to_list x).foldl f 0
instance : has_mul (bitvec n) := β¨bitvec.mulβ©
end arith
section comparison
variable {n : β}
def uborrow (x y : bitvec n) : bool := prod.fst (sbb x y ff)
def ult (x y : bitvec n) : Prop := uborrow x y
def ugt (x y : bitvec n) : Prop := ult y x
def ule (x y : bitvec n) : Prop := Β¬ (ult y x)
def uge (x y : bitvec n) : Prop := ule y x
def sborrow : Ξ {n : β}, bitvec n β bitvec n β bool
| 0 _ _ := ff
| (succ n) x y :=
match (head x, head y) with
| (tt, ff) := tt
| (ff, tt) := ff
| _ := uborrow (tail x) (tail y)
end
def slt (x y : bitvec n) : Prop := sborrow x y
def sgt (x y : bitvec n) : Prop := slt y x
def sle (x y : bitvec n) : Prop := Β¬ (slt y x)
def sge (x y : bitvec n) : Prop := sle y x
end comparison
section conversion
variable {Ξ± : Type}
protected def of_nat : Ξ (n : β), nat β bitvec n
| 0 x := nil
| (succ n) x := of_nat n (x / 2) ++β to_bool (x % 2 = 1) :: nil
protected def of_int : Ξ (n : β), int β bitvec (succ n)
| n (int.of_nat m) := ff :: bitvec.of_nat n m
| n (int.neg_succ_of_nat m) := tt :: not (bitvec.of_nat n m)
def add_lsb (r : β) (b : bool) := r + r + cond b 1 0
def bits_to_nat (v : list bool) : nat :=
v.foldl add_lsb 0
protected def to_nat {n : nat} (v : bitvec n) : nat :=
bits_to_nat (to_list v)
theorem bits_to_nat_to_list {n : β} (x : bitvec n)
: bitvec.to_nat x = bits_to_nat (vector.to_list x) := rfl
local attribute [simp] nat.add_comm nat.add_assoc nat.add_left_comm nat.mul_comm nat.mul_assoc
local attribute [simp] nat.zero_add nat.add_zero nat.one_mul nat.mul_one nat.zero_mul nat.mul_zero
-- mul_left_comm
theorem to_nat_append {m : β} (xs : bitvec m) (b : bool)
: bitvec.to_nat (xs ++β b::nil) = bitvec.to_nat xs * 2 + bitvec.to_nat (b::nil) :=
begin
cases xs with xs P,
simp [bits_to_nat_to_list], clear P,
unfold bits_to_nat list.foldl,
-- generalize the accumulator of foldl
generalize h : 0 = x, conv in (add_lsb x b) { rw βh }, clear h,
simp,
induction xs with x xs generalizing x,
{ simp, unfold list.foldl add_lsb, simp [nat.mul_succ] },
{ simp, apply xs_ih }
end
theorem bits_to_nat_to_bool (n : β)
: bitvec.to_nat (to_bool (n % 2 = 1) :: nil) = n % 2 :=
begin
simp [bits_to_nat_to_list],
unfold bits_to_nat add_lsb list.foldl cond,
simp [cond_to_bool_mod_two],
end
theorem of_nat_succ {k n : β}
: bitvec.of_nat (succ k) n = bitvec.of_nat k (n / 2) ++β to_bool (n % 2 = 1) :: nil :=
rfl
theorem to_nat_of_nat {k n : β}
: bitvec.to_nat (bitvec.of_nat k n) = n % 2^k :=
begin
induction k with k ih generalizing n,
{ unfold pow nat.pow, simp [nat.mod_one], refl },
{ have h : 0 < 2, { apply le_succ },
rw [of_nat_succ, to_nat_append, ih, bits_to_nat_to_bool, mod_pow_succ h, nat.mul_comm] }
end
protected def to_int : Ξ {n : nat}, bitvec n β int
| 0 _ := 0
| (succ n) v :=
cond (head v)
(int.neg_succ_of_nat $ bitvec.to_nat $ not $ tail v)
(int.of_nat $ bitvec.to_nat $ tail v)
end conversion
private def repr {n : nat} : bitvec n β string
| β¨bs, pβ© :=
"0b" ++ (bs.map (Ξ» b : bool, if b then '1' else '0')).as_string
instance (n : nat) : has_repr (bitvec n) :=
β¨reprβ©
end bitvec
instance {n} {x y : bitvec n} : decidable (bitvec.ult x y) := bool.decidable_eq _ _
instance {n} {x y : bitvec n} : decidable (bitvec.ugt x y) := bool.decidable_eq _ _
|
bec17396df68325c067994b4312b58878ebbe819 | bdc51328652176125c43c2c9f2d3e4398f127ccb | /src/regular_languages.lean | 549f39c1a153f0b17a653b24548aece6e5e5ec7b | [] | no_license | atarnoam/lean-automata | d6ca17387b8e0ac6d7c21f12e78d26c237a57cd2 | 46c69ddaa142913b1f43ef57f700f2481cdfba76 | refs/heads/main | 1,678,898,675,345 | 1,614,977,921,000 | 1,614,977,921,000 | 344,927,186 | 6 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 5,774 | lean | import DFA
import data.fintype.basic
import order.boolean_algebra
import data.quot
universes u v
def is_regular {Ξ± : Type u} [fintype Ξ±] (l : language Ξ±) : Prop :=
β (Ο : Type v) [fintype Ο] (A : DFA Ξ± Ο), A.accepts = l
lemma is_regular_def {Ξ± : Type u} [fintype Ξ±] {l : language Ξ±} :
(is_regular.{u v}) l β (β (Ο : Type v) [fintype Ο] (A : DFA Ξ± Ο), A.accepts = l) :=
iff.refl _
namespace regular_language
open DFA
section basic
/--
Here we prove basic things on regular languages, such as the they form a boolean algebra
-/
variables {Ξ± : Type u} [fintype Ξ±]
variables {l l' : language Ξ±}
lemma inf_regular : (is_regular.{u v} l) β (is_regular.{u v} l') β is_regular.{u v} (l β l') :=
begin
rintros β¨Ο, hΟ, A, hAβ©,
rintros β¨Ο, hΟ, B, hBβ©,
resetI,
refine β¨Ο Γ Ο, infer_instance, inter A B, _β©,
rw [inter_accepts, hA, hB],
end
lemma compl_regular : (is_regular.{u v} l) β (is_regular.{u v} lαΆ) :=
begin
rintros β¨Q, hQ, A, hAβ©,
refine β¨Q, hQ, A.compl, _β©,
rw [compl_accepts, hA]
end
lemma compl_regular_iff : (is_regular.{u v} lαΆ) β (is_regular.{u v} l) :=
begin
split,
{
intro h,
rw β compl_compl l,
exact compl_regular h
},
{ exact compl_regular },
end
lemma sup_regular : (is_regular.{u v} l) β (is_regular.{u v} l') β is_regular.{u v} (l β l') :=
begin
intros hl hl',
rw [βcompl_compl (l β l'), compl_sup, compl_regular_iff],
exact inf_regular (compl_regular hl) (compl_regular hl'),
end
end basic
section relation
/-!
### Myhill-Nerode theorem
Given `l`, we define an equivalence relation on `list Ξ±`.
The main theorem is that `l` is regular iff the number of
equivalence classes of this relation is finite.
-/
parameters {Ξ± : Type u} [fintype Ξ±]
section basic
parameters (l : language Ξ±)
/--
A relation on `list Ξ±`, identifying `x, y` if for all
`z : list Ξ±`, `(x ++ z β l) β (y ++ z β l)`.
-/
def rel : list Ξ± β list Ξ± β Prop :=
Ξ» x y, β (z : list Ξ±), (x ++ z β l) β (y ++ z β l)
parameter {l}
lemma iff_mem_language_of_equiv {x y : list Ξ±} (Rxy : rel x y) : x β l β y β l :=
begin
specialize Rxy [],
repeat {rwa list.append_nil at Rxy},
end
parameter (l)
lemma rel_refl : reflexive (rel) := Ξ» _ _, by refl
lemma rel_symm : symmetric (rel) := Ξ» _ _ hxy z, iff.symm (hxy z)
lemma rel_trans : transitive (rel) := Ξ» _ _ _ hxy hyz z, iff.trans (hxy z) (hyz z)
lemma rel_equiv : equivalence (rel) := β¨rel_refl, rel_symm, rel_transβ©
instance space.setoid : setoid (list Ξ±) := setoid.mk rel rel_equiv
definition space := quotient space.setoid
parameter {l}
definition mk (x : list Ξ±) : space := @quotient.mk _ space.setoid x
@[simp] lemma mk_def (x : list Ξ±) : mk x = @quotient.mk _ space.setoid x := rfl
end basic
section finite_class_space
/-!
### Myhill-Nerode, first direction
We build an automaton accepting `l` whose states are `space l`.
As a consequence, if `space l` is finite, then `l` is regular.
-/
parameters (l : language Ξ±)
def to_DFA : DFA Ξ± (space l) :=
{
step := begin
apply quot.lift (Ξ» (z : list Ξ±) (Ο : Ξ±), (mk (z ++ [Ο]) : space l)),
intros x y r,
ext Ο,
simp only [regular_language.mk_def, quotient.eq],
intro z,
simp [r (Ο :: z)],
end,
start := mk [],
accept := begin
apply quot.lift (β l),
intros x y r,
simp [iff_mem_language_of_equiv r],
end
}
@[simp] lemma to_DFA_step (w : list Ξ±) (Ο : Ξ±) : to_DFA.step (mk w) Ο = mk (w ++ [Ο]) := rfl
@[simp] lemma to_DFA_start : to_DFA.start = mk [] := rfl
@[simp] lemma to_DFA_accept (w : list Ξ±) : (mk w) β to_DFA.accept β w β l := by refl
@[simp] lemma to_DFA_eval_from (x y : list Ξ±) : eval_from to_DFA (mk x) y = mk (x ++ y) :=
begin
induction y with Ο y generalizing x,
{
simp,
exact rel_refl l _,
},
{
specialize y_ih (x ++ [Ο]),
simp at *,
exact y_ih,
}
end
lemma to_DFA_accepts : accepts to_DFA = l :=
begin
ext,
rw [mem_accepts, to_DFA_start, to_DFA_eval_from, list.nil_append, to_DFA_accept],
end
theorem regular_of_fintype_language_space [fintype (space l)] : is_regular.{u u} l :=
β¨space l, infer_instance, to_DFA, to_DFA_acceptsβ©
end finite_class_space
section regular
/-!
### Myhill-Nerode, the other direction.
Now we wish to prove that if `l` is regular then `space l` is finite.
We prove this using the canonical functions `Q β© DFA_space β space l`,
the first of which we constructed in DFA.relation.
-/
parameters {Q : Type u} (A : DFA Ξ± Q)
private def l := A.accepts
@[simp] private lemma l_def : l = A.accepts := rfl
lemma language_rel_of_DFA_rel (x y : list Ξ±) : A.rel x y β rel l x y :=
begin
intros r z,
rw rel_def at r,
rw [l_def, mem_accepts, mem_accepts, eval_from_of_append, eval_from_of_append,
β eval_def, β eval_def, r],
end
definition language_space_of_DFA_space : A.space β space l :=
by exact quot.map id (language_rel_of_DFA_rel _)
@[simp] lemma language_space_of_DFA_space_def (w : list Ξ±) :
language_space_of_DFA_space (DFA.space.mk w) = mk w := rfl
lemma language_space_of_DFA_space_surjective : function.surjective language_space_of_DFA_space :=
begin
apply quotient.ind,
intro w,
use DFA.space.mk w,
rw language_space_of_DFA_space_def,
refl
end
open classical
local attribute [instance] prop_decidable
noncomputable instance fintype_language_space_of_regular (l : language Ξ±) (r : is_regular l) :
fintype (space l) :=
begin
choose Q fQ A hA using r,
rw β hA,
resetI,
haveI : fintype A.space := DFA.fintype_space_of_fintype_states _,
exact fintype.of_surjective _ (language_space_of_DFA_space_surjective _),
end
end regular
end relation
end regular_language
variable (Ξ± : Type u)
|
e1cd29cb3ea82f29412c6c5544888f5e91eee133 | 4da0c8e61fcd6ec3f3be47ee14a038850c03d0c3 | /src/context.lean | f7286bd3d955ad63efeb2649edecd6ae0ece899e | [
"Apache-2.0"
] | permissive | bbentzen/mpl | fcbea60204bc8fd64667e0f76a5cebf4b67fb6ca | bb5066ec51fa11a4b66f440c4f6c9a3d8fb2e0de | refs/heads/master | 1,625,175,849,308 | 1,624,207,634,000 | 1,624,207,634,000 | 142,774,375 | 9 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 303 | lean | /-
Copyright (c) 2018 Bruno Bentzen. All rights reserved.
Released under the Apache License 2.0 (see "License");
Author: Bruno Bentzen
-/
import .language
/- context -/
@[reducible]
def ctx (Ο : nat) : Type := set (form Ο)
notation `Β·` := {}
notation Ξ ` βΈ΄ ` p := set.insert p Ξ |
92dbf4f66bad71711507d16a5498f8752bedb7ac | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/number_theory/liouville/residual.lean | 2b987bd5167d4fa03714010dffb72d85acfb429f | [
"Apache-2.0"
] | permissive | AntoineChambert-Loir/mathlib | 64aabb896129885f12296a799818061bc90da1ff | 07be904260ab6e36a5769680b6012f03a4727134 | refs/heads/master | 1,693,187,631,771 | 1,636,719,886,000 | 1,636,719,886,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 2,916 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import number_theory.liouville.basic
import topology.metric_space.baire
import topology.instances.irrational
/-!
# Density of Liouville numbers
In this file we prove that the set of Liouville numbers form a dense `GΞ΄` set. We also prove a
similar statement about irrational numbers.
-/
open_locale filter
open filter set metric
lemma set_of_liouville_eq_Inter_Union :
{x | liouville x} =
β n : β, β (a b : β€) (hb : 1 < b), ball (a / b) (1 / b ^ n) \ {a / b} :=
begin
ext x,
simp only [mem_Inter, mem_Union, liouville, mem_set_of_eq, exists_prop, mem_diff,
mem_singleton_iff, mem_ball, real.dist_eq, and_comm]
end
lemma is_GΞ΄_set_of_liouville : is_GΞ΄ {x | liouville x} :=
begin
rw set_of_liouville_eq_Inter_Union,
refine is_GΞ΄_Inter (Ξ» n, is_open.is_GΞ΄ _),
refine is_open_Union (Ξ» a, is_open_Union $ Ξ» b, is_open_Union $ Ξ» hb, _),
exact is_open_ball.inter is_closed_singleton.is_open_compl
end
lemma set_of_liouville_eq_irrational_inter_Inter_Union :
{x | liouville x} =
{x | irrational x} β© β n : β, β (a b : β€) (hb : 1 < b), ball (a / b) (1 / b ^ n) :=
begin
refine subset.antisymm _ _,
{ refine subset_inter (Ξ» x hx, hx.irrational) _,
rw set_of_liouville_eq_Inter_Union,
exact Inter_subset_Inter (Ξ» n, Union_subset_Union $ Ξ» a, Union_subset_Union $
Ξ» b, Union_subset_Union $ Ξ» hb, diff_subset _ _) },
{ simp only [inter_Inter, inter_Union, set_of_liouville_eq_Inter_Union],
refine Inter_subset_Inter (Ξ» n, Union_subset_Union $ Ξ» a, Union_subset_Union $
Ξ» b, Union_subset_Union $ Ξ» hb, _),
rw [inter_comm],
refine diff_subset_diff subset.rfl (singleton_subset_iff.2 β¨a / b, _β©),
norm_cast }
end
/-- The set of Liouville numbers is a residual set. -/
lemma eventually_residual_liouville : βαΆ x in residual β, liouville x :=
begin
rw [filter.eventually, set_of_liouville_eq_irrational_inter_Inter_Union],
refine eventually_residual_irrational.and _,
refine eventually_residual.2 β¨_, _, rat.dense_embedding_coe_real.dense.mono _, subset.rflβ©,
{ exact is_GΞ΄_Inter (Ξ» n, is_open.is_GΞ΄ $ is_open_Union $ Ξ» a, is_open_Union $
Ξ» b, is_open_Union $ Ξ» hb, is_open_ball) },
{ rintro _ β¨r, rflβ©,
simp only [mem_Inter, mem_Union],
refine Ξ» n, β¨r.num * 2, r.denom * 2, _, _β©,
{ have := int.coe_nat_le.2 r.pos, rw int.coe_nat_one at this, linarith },
{ convert mem_ball_self _ using 2,
{ norm_cast, field_simp },
{ refine one_div_pos.2 (pow_pos (int.cast_pos.2 _) _),
exact mul_pos (int.coe_nat_pos.2 r.pos) zero_lt_two } } }
end
/-- The set of Liouville numbers in dense. -/
lemma dense_liouville : dense {x | liouville x} :=
dense_of_mem_residual eventually_residual_liouville
|
039951c7f23112e427e7c89ec22211b9439181e7 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/qpf/multivariate/basic.lean | 6b47237bf5943eb05f409592168177a7e92e39cd | [
"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 | 8,756 | lean | /-
Copyright (c) 2018 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad, Simon Hudon
-/
import data.pfunctor.multivariate.basic
/-!
# Multivariate quotients of polynomial functors.
Basic definition of multivariate QPF. QPFs form a compositional framework
for defining inductive and coinductive types, their quotients and nesting.
The idea is based on building ever larger functors. For instance, we can define
a list using a shape functor:
```lean
inductive list_shape (a b : Type)
| nil : list_shape
| cons : a -> b -> list_shape
```
This shape can itself be decomposed as a sum of product which are themselves
QPFs. It follows that the shape is a QPF and we can take its fixed point
and create the list itself:
```lean
def list (a : Type) := fix list_shape a -- not the actual notation
```
We can continue and define the quotient on permutation of lists and create
the multiset type:
```lean
def multiset (a : Type) := qpf.quot list.perm list a -- not the actual notion
```
And `multiset` is also a QPF. We can then create a novel data type (for Lean):
```lean
inductive tree (a : Type)
| node : a -> multiset tree -> tree
```
An unordered tree. This is currently not supported by Lean because it nests
an inductive type inside of a quotient. We can go further and define
unordered, possibly infinite trees:
```lean
coinductive tree' (a : Type)
| node : a -> multiset tree' -> tree'
```
by using the `cofix` construct. Those options can all be mixed and
matched because they preserve the properties of QPF. The latter example,
`tree'`, combines fixed point, co-fixed point and quotients.
## Related modules
* constructions
* fix
* cofix
* quot
* comp
* sigma / pi
* prj
* const
each proves that some operations on functors preserves the QPF structure
## Reference
* [Jeremy Avigad, Mario M. Carneiro and Simon Hudon, *Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019]
-/
universe u
open_locale mvfunctor
/--
Multivariate quotients of polynomial functors.
-/
class mvqpf {n : β} (F : typevec.{u} n β Type*) [mvfunctor F] :=
(P : mvpfunctor.{u} n)
(abs : Ξ {Ξ±}, P.obj Ξ± β F Ξ±)
(repr : Ξ {Ξ±}, F Ξ± β P.obj Ξ±)
(abs_repr : β {Ξ±} (x : F Ξ±), abs (repr x) = x)
(abs_map : β {Ξ± Ξ²} (f : Ξ± βΉ Ξ²) (p : P.obj Ξ±), abs (f <$$> p) = f <$$> abs p)
namespace mvqpf
variables {n : β} {F : typevec.{u} n β Type*} [mvfunctor F] [q : mvqpf F]
include q
open mvfunctor (liftp liftr)
/-!
### Show that every mvqpf is a lawful mvfunctor.
-/
protected theorem id_map {Ξ± : typevec n} (x : F Ξ±) : typevec.id <$$> x = x :=
by { rw βabs_repr x, cases repr x with a f, rw [βabs_map], reflexivity }
@[simp] theorem comp_map {Ξ± Ξ² Ξ³ : typevec n} (f : Ξ± βΉ Ξ²) (g : Ξ² βΉ Ξ³) (x : F Ξ±) :
(g β f) <$$> x = g <$$> f <$$> x :=
by { rw βabs_repr x, cases repr x with a f, rw [βabs_map, βabs_map, βabs_map], reflexivity }
@[priority 100]
instance is_lawful_mvfunctor : is_lawful_mvfunctor F :=
{ id_map := @mvqpf.id_map n F _ _,
comp_map := @comp_map n F _ _ }
/- Lifting predicates and relations -/
theorem liftp_iff {Ξ± : typevec n} (p : Ξ β¦iβ¦, Ξ± i β Prop) (x : F Ξ±) :
liftp p x β β a f, x = abs β¨a, fβ© β§ β i j, p (f i j) :=
begin
split,
{ rintros β¨y, hyβ©, cases h : repr y with a f,
use [a, Ξ» i j, (f i j).val], split,
{ rw [βhy, βabs_repr y, h, βabs_map], reflexivity },
intros i j, apply (f i j).property },
rintros β¨a, f, hβ, hββ©, dsimp at *,
use abs (β¨a, Ξ» i j, β¨f i j, hβ i jβ©β©),
rw [βabs_map, hβ], reflexivity
end
theorem liftr_iff {Ξ± : typevec n} (r : Ξ β¦iβ¦, Ξ± i β Ξ± i β Prop) (x y : F Ξ±) :
liftr r x y β β a fβ fβ, x = abs β¨a, fββ© β§ y = abs β¨a, fββ© β§ β i j, r (fβ i j) (fβ i j) :=
begin
split,
{ rintros β¨u, xeq, yeqβ©, cases h : repr u with a f,
use [a, Ξ» i j, (f i j).val.fst, Ξ» i j, (f i j).val.snd],
split, { rw [βxeq, βabs_repr u, h, βabs_map], refl },
split, { rw [βyeq, βabs_repr u, h, βabs_map], refl },
intros i j, exact (f i j).property },
rintros β¨a, fβ, fβ, xeq, yeq, hβ©,
use abs β¨a, Ξ» i j, β¨(fβ i j, fβ i j), h i jβ©β©,
dsimp, split,
{ rw [xeq, βabs_map], refl },
rw [yeq, βabs_map], refl
end
open set
open mvfunctor
theorem mem_supp {Ξ± : typevec n} (x : F Ξ±) (i) (u : Ξ± i) :
u β supp x i β β a f, abs β¨a, fβ© = x β u β f i '' univ :=
begin
rw [supp], dsimp, split,
{ intros h a f haf,
have : liftp (Ξ» i u, u β f i '' univ) x,
{ rw liftp_iff, refine β¨a, f, haf.symm, _β©,
intros i u, exact mem_image_of_mem _ (mem_univ _) },
exact h this },
intros h p, rw liftp_iff,
rintros β¨a, f, xeq, h'β©,
rcases h a f xeq.symm with β¨i, _, hiβ©,
rw βhi, apply h'
end
theorem supp_eq {Ξ± : typevec n} {i} (x : F Ξ±) :
supp x i = { u | β a f, abs β¨a, fβ© = x β u β f i '' univ } :=
by ext; apply mem_supp
theorem has_good_supp_iff {Ξ± : typevec n} (x : F Ξ±) :
(β p, liftp p x β β i (u β supp x i), p i u) β
β a f, abs β¨a, fβ© = x β§ β i a' f', abs β¨a', f'β© = x β f i '' univ β f' i '' univ :=
begin
split,
{ intros h,
have : liftp (supp x) x, by { rw h, introv, exact id, },
rw liftp_iff at this, rcases this with β¨a, f, xeq, h'β©,
refine β¨a, f, xeq.symm, _β©,
intros a' f' h'',
rintros hu u β¨j, hβ, hfiβ©,
have hh : u β supp x a', by rw βhfi; apply h',
refine (mem_supp x _ u).mp hh _ _ hu, },
rintros β¨a, f, xeq, hβ© p, rw liftp_iff, split,
{ rintros β¨a', f', xeq', h'β© i u usuppx,
rcases (mem_supp x _ u).mp @usuppx a' f' xeq'.symm with β¨i, _, f'ieqβ©,
rw βf'ieq, apply h' },
intro h',
refine β¨a, f, xeq.symm, _β©, intros j y,
apply h', rw mem_supp,
intros a' f' xeq',
apply h _ a' f' xeq',
apply mem_image_of_mem _ (mem_univ _)
end
variable (q)
/-- A qpf is said to be uniform if every polynomial functor
representing a single value all have the same range. -/
def is_uniform : Prop := β β¦Ξ± : typevec nβ¦ (a a' : q.P.A)
(f : q.P.B a βΉ Ξ±) (f' : q.P.B a' βΉ Ξ±),
abs β¨a, fβ© = abs β¨a', f'β© β β i, f i '' univ = f' i '' univ
/-- does `abs` preserve `liftp`? -/
def liftp_preservation : Prop :=
β β¦Ξ± : typevec nβ¦ (p : Ξ β¦iβ¦, Ξ± i β Prop) (x : q.P.obj Ξ±), liftp p (abs x) β liftp p x
/-- does `abs` preserve `supp`? -/
def supp_preservation : Prop :=
β β¦Ξ±β¦ (x : q.P.obj Ξ±), supp (abs x) = supp x
variable [q]
theorem supp_eq_of_is_uniform (h : q.is_uniform) {Ξ± : typevec n} (a : q.P.A) (f : q.P.B a βΉ Ξ±) :
β i, supp (abs β¨a, fβ©) i = f i '' univ :=
begin
intro, ext u, rw [mem_supp], split,
{ intro h', apply h' _ _ rfl },
intros h' a' f' e,
rw [βh _ _ _ _ e.symm], apply h'
end
theorem liftp_iff_of_is_uniform (h : q.is_uniform) {Ξ± : typevec n} (x : F Ξ±) (p : Ξ i, Ξ± i β Prop) :
liftp p x β β i (u β supp x i), p i u :=
begin
rw [liftp_iff, βabs_repr x],
cases repr x with a f, split,
{ rintros β¨a', f', abseq, hfβ© u,
rw [supp_eq_of_is_uniform h, h _ _ _ _ abseq],
rintros b β¨i, _, hiβ©, rw βhi, apply hf },
intro h',
refine β¨a, f, rfl, Ξ» _ i, h' _ _ _β©,
rw supp_eq_of_is_uniform h,
exact β¨i, mem_univ i, rflβ©
end
theorem supp_map (h : q.is_uniform) {Ξ± Ξ² : typevec n} (g : Ξ± βΉ Ξ²) (x : F Ξ±) (i) :
supp (g <$$> x) i = g i '' supp x i :=
begin
rw βabs_repr x, cases repr x with a f, rw [βabs_map, mvpfunctor.map_eq],
rw [supp_eq_of_is_uniform h, supp_eq_of_is_uniform h, β image_comp],
refl,
end
theorem supp_preservation_iff_uniform :
q.supp_preservation β q.is_uniform :=
begin
split,
{ intros h Ξ± a a' f f' h' i,
rw [β mvpfunctor.supp_eq,β mvpfunctor.supp_eq,β h,h',h] },
{ rintros h Ξ± β¨a,fβ©, ext, rwa [supp_eq_of_is_uniform,mvpfunctor.supp_eq], }
end
theorem supp_preservation_iff_liftp_preservation :
q.supp_preservation β q.liftp_preservation :=
begin
split; intro h,
{ rintros Ξ± p β¨a,fβ©,
have h' := h, rw supp_preservation_iff_uniform at h',
dsimp only [supp_preservation,supp] at h,
simp only [liftp_iff_of_is_uniform, supp_eq_of_is_uniform, mvpfunctor.liftp_iff', h',
image_univ, mem_range, exists_imp_distrib],
split; intros; subst_vars; solve_by_elim },
{ rintros Ξ± β¨a,fβ©,
simp only [liftp_preservation] at h,
ext, simp [supp,h] }
end
theorem liftp_preservation_iff_uniform :
q.liftp_preservation β q.is_uniform :=
by rw [β supp_preservation_iff_liftp_preservation, supp_preservation_iff_uniform]
end mvqpf
|
d1a724d3ecb80c41d25b71a6c866e94707c24b06 | e9dbaaae490bc072444e3021634bf73664003760 | /src/Problems/2013/IMO_2013_P4.lean | f6818bc96952b37a599288111b31f0915f431041 | [
"Apache-2.0"
] | permissive | liaofei1128/geometry | 566d8bfe095ce0c0113d36df90635306c60e975b | 3dd128e4eec8008764bb94e18b932f9ffd66e6b3 | refs/heads/master | 1,678,996,510,399 | 1,581,454,543,000 | 1,583,337,839,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 474 | lean | import Geo.Geo.Core
namespace Geo
open Circle Seg Triangle
def IMO_2013_P4 : Prop :=
β (A B C W : Point),
acute β¨A, B, Cβ© β
let H := orthocenter β¨A, B, Cβ©;
strictlyBtw W B C β
let M := foot B (Line.mk A C);
let N := foot C (Line.mk A B);
β (X Y : Point),
let Οβ := Triangle.circumcircle β¨B, W, Nβ©;
on X Οβ β
isDiameter W X Οβ β
let Οβ := Triangle.circumcircle β¨C, W, Mβ©;
on Y Οβ β
isDiameter W Y Οβ β
coll X Y H
end Geo
|
130a9d43fbb93c4b56807e09ff01591240c57987 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/topology/algebra/module.lean | cb27c1f3cb3e50295e374028e57f41e9e2b3ed14 | [] | 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 | 95,148 | lean | /-
Copyright (c) 2019 SΓ©bastien GouΓ«zel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jan-David Salchow, SΓ©bastien GouΓ«zel, Jean Lo, Yury Kudryashov
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.topology.algebra.ring
import Mathlib.topology.uniform_space.uniform_embedding
import Mathlib.algebra.algebra.basic
import Mathlib.linear_algebra.projection
import Mathlib.PostPort
universes u v l u_1 u_2 u_3 u_4 u_5
namespace Mathlib
/-!
# Theory of topological modules and continuous linear maps.
We define classes `topological_semimodule`, `topological_module` and `topological_vector_spaces`,
as extensions of the corresponding algebraic classes where the algebraic operations are continuous.
We also define continuous linear maps, as linear maps between topological modules which are
continuous. The set of continuous linear maps between the topological `R`-modules `M` and `Mβ` is
denoted by `M βL[R] Mβ`.
Continuous linear equivalences are denoted by `M βL[R] Mβ`.
## Implementation notes
Topological vector spaces are defined as an `abbreviation` for topological modules,
if the base ring is a field. This has as advantage that topological vector spaces are completely
transparent for type class inference, which means that all instances for topological modules
are immediately picked up for vector spaces as well.
A cosmetic disadvantage is that one can not extend topological vector spaces.
The solution is to extend `topological_module` instead.
-/
/-- A topological semimodule, over a semiring which is also a topological space, is a
semimodule in which scalar multiplication is continuous. In applications, R will be a topological
semiring and M a topological additive semigroup, but this is not needed for the definition -/
class topological_semimodule (R : Type u) (M : Type v) [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M]
where
continuous_smul : continuous fun (p : R Γ M) => prod.fst p β’ prod.snd p
theorem continuous_smul {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] : continuous fun (p : R Γ M) => prod.fst p β’ prod.snd p :=
topological_semimodule.continuous_smul
theorem continuous.smul {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] {Ξ± : Type u_1} [topological_space Ξ±] {f : Ξ± β R} {g : Ξ± β M} (hf : continuous f) (hg : continuous g) : continuous fun (p : Ξ±) => f p β’ g p :=
continuous.comp continuous_smul (continuous.prod_mk hf hg)
theorem tendsto_smul {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] {c : R} {x : M} : filter.tendsto (fun (p : R Γ M) => prod.fst p β’ prod.snd p) (nhds (c, x)) (nhds (c β’ x)) :=
continuous.tendsto continuous_smul (c, x)
theorem filter.tendsto.smul {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] {Ξ± : Type u_1} {l : filter Ξ±} {f : Ξ± β R} {g : Ξ± β M} {c : R} {x : M} (hf : filter.tendsto f l (nhds c)) (hg : filter.tendsto g l (nhds x)) : filter.tendsto (fun (a : Ξ±) => f a β’ g a) l (nhds (c β’ x)) :=
filter.tendsto.comp tendsto_smul (filter.tendsto.prod_mk_nhds hf hg)
protected instance topological_semiring.to_semimodule {R : Type u_1} [topological_space R] [semiring R] [topological_semiring R] : topological_semimodule R R :=
topological_semimodule.mk continuous_mul
/-- A topological module, over a ring which is also a topological space, is a module in which
scalar multiplication is continuous. In applications, `R` will be a topological ring and `M` a
topological additive group, but this is not needed for the definition -/
def topological_module (R : Type u) (M : Type v) [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] :=
topological_semimodule R M
/-- A topological vector space is a topological module over a field. -/
def topological_vector_space (R : Type u) (M : Type v) [field R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] :=
topological_module R M
/-- Scalar multiplication by a unit is a homeomorphism from a
topological module onto itself. -/
protected def homeomorph.smul_of_unit {R : Type u_1} {M : Type u_2} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] (a : units R) : M ββ M :=
homeomorph.mk (equiv.mk (fun (x : M) => βa β’ x) (fun (x : M) => β(aβ»ΒΉ) β’ x) sorry sorry)
theorem is_open_map_smul_of_unit {R : Type u_1} {M : Type u_2} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] (a : units R) : is_open_map fun (x : M) => βa β’ x :=
homeomorph.is_open_map (homeomorph.smul_of_unit a)
theorem is_closed_map_smul_of_unit {R : Type u_1} {M : Type u_2} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] (a : units R) : is_closed_map fun (x : M) => βa β’ x :=
homeomorph.is_closed_map (homeomorph.smul_of_unit a)
/-- If `M` is a topological module over `R` and `0` is a limit of invertible elements of `R`, then
`β€` is the only submodule of `M` with a nonempty interior.
This is the case, e.g., if `R` is a nondiscrete normed field. -/
theorem submodule.eq_top_of_nonempty_interior' {R : Type u_1} {M : Type u_2} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] [has_continuous_add M] [filter.ne_bot (nhds_within 0 (set_of fun (x : R) => is_unit x))] (s : submodule R M) (hs : set.nonempty (interior βs)) : s = β€ := sorry
theorem submodule.closure_smul_self_subset {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] (s : submodule R M) : (fun (p : R Γ M) => prod.fst p β’ prod.snd p) '' set.prod set.univ (closure βs) β closure βs := sorry
theorem submodule.closure_smul_self_eq {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] (s : submodule R M) : (fun (p : R Γ M) => prod.fst p β’ prod.snd p) '' set.prod set.univ (closure βs) = closure βs := sorry
/-- The (topological-space) closure of a submodle of a topological `R`-semimodule `M` is itself
a submodule. -/
def submodule.topological_closure {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] [has_continuous_add M] (s : submodule R M) : submodule R M :=
submodule.mk (closure βs) sorry sorry sorry
theorem submodule.submodule_topological_closure {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] [has_continuous_add M] (s : submodule R M) : s β€ submodule.topological_closure s :=
subset_closure
theorem submodule.is_closed_topological_closure {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] [has_continuous_add M] (s : submodule R M) : is_closed β(submodule.topological_closure s) := sorry
theorem submodule.topological_closure_minimal {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] [has_continuous_add M] (s : submodule R M) {t : submodule R M} (h : s β€ t) (ht : is_closed βt) : submodule.topological_closure s β€ t :=
closure_minimal h ht
/-- Scalar multiplication by a non-zero field element is a
homeomorphism from a topological vector space onto itself. -/
protected def homeomorph.smul_of_ne_zero {R : Type u_1} {M : Type u_2} {a : R} [field R] [topological_space R] [topological_space M] [add_comm_group M] [vector_space R M] [topological_vector_space R M] (ha : a β 0) : M ββ M :=
homeomorph.mk (homeomorph.to_equiv (homeomorph.smul_of_unit (units.mk0 a ha)))
theorem is_open_map_smul_of_ne_zero {R : Type u_1} {M : Type u_2} {a : R} [field R] [topological_space R] [topological_space M] [add_comm_group M] [vector_space R M] [topological_vector_space R M] (ha : a β 0) : is_open_map fun (x : M) => a β’ x :=
homeomorph.is_open_map (homeomorph.smul_of_ne_zero ha)
/-- `smul` is a closed map in the second argument.
The lemma that `smul` is a closed map in the first argument (for a normed space over a complete
normed field) is `is_closed_map_smul_left` in `analysis.normed_space.finite_dimension`. -/
theorem is_closed_map_smul_of_ne_zero {R : Type u_1} {M : Type u_2} {a : R} [field R] [topological_space R] [topological_space M] [add_comm_group M] [vector_space R M] [topological_vector_space R M] (ha : a β 0) : is_closed_map fun (x : M) => a β’ x :=
homeomorph.is_closed_map (homeomorph.smul_of_ne_zero ha)
/-- Continuous linear maps between modules. We only put the type classes that are necessary for the
definition, although in applications `M` and `Mβ` will be topological modules over the topological
ring `R`. -/
structure continuous_linear_map (R : Type u_1) [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] (Mβ : Type u_3) [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ]
extends linear_map R M Mβ
where
cont : autoParam (continuous (linear_map.to_fun _to_linear_map))
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.continuity'")
(Lean.Name.mkStr
(Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive")
"continuity'")
[])
/-- Continuous linear equivalences between modules. We only put the type classes that are necessary
for the definition, although in applications `M` and `Mβ` will be topological modules over the
topological ring `R`. -/
structure continuous_linear_equiv (R : Type u_1) [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] (Mβ : Type u_3) [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ]
extends linear_equiv R M Mβ
where
continuous_to_fun : autoParam (continuous (linear_equiv.to_fun _to_linear_equiv))
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.continuity'")
(Lean.Name.mkStr
(Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive")
"continuity'")
[])
continuous_inv_fun : autoParam (continuous (linear_equiv.inv_fun _to_linear_equiv))
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.continuity'")
(Lean.Name.mkStr
(Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive")
"continuity'")
[])
namespace continuous_linear_map
/-!
### Properties that hold for non-necessarily commutative semirings.
-/
/-- Coerce continuous linear maps to linear maps. -/
protected instance linear_map.has_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : has_coe (continuous_linear_map R M Mβ) (linear_map R M Mβ) :=
has_coe.mk to_linear_map
/-- Coerce continuous linear maps to functions. -/
-- see Note [function coercion]
protected instance to_fun {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : has_coe_to_fun (continuous_linear_map R M Mβ) :=
has_coe_to_fun.mk (fun (_x : continuous_linear_map R M Mβ) => M β Mβ) fun (f : continuous_linear_map R M Mβ) => βf
@[simp] theorem coe_mk {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : linear_map R M Mβ) (h : autoParam (continuous (linear_map.to_fun f))
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.continuity'")
(Lean.Name.mkStr
(Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive")
"continuity'")
[])) : β(mk f) = f :=
rfl
@[simp] theorem coe_mk' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : linear_map R M Mβ) (h : autoParam (continuous (linear_map.to_fun f))
(Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.tactic.interactive.continuity'")
(Lean.Name.mkStr
(Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "tactic") "interactive")
"continuity'")
[])) : β(mk f) = βf :=
rfl
protected theorem continuous {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) : continuous βf :=
cont f
theorem coe_injective {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : function.injective coe := sorry
theorem injective_coe_fn {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : function.injective fun (f : continuous_linear_map R M Mβ) => (fun (this : M β Mβ) => this) βf :=
function.injective.comp linear_map.coe_injective coe_injective
theorem ext {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] {f : continuous_linear_map R M Mβ} {g : continuous_linear_map R M Mβ} (h : β (x : M), coe_fn f x = coe_fn g x) : f = g :=
injective_coe_fn (funext h)
theorem ext_iff {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] {f : continuous_linear_map R M Mβ} {g : continuous_linear_map R M Mβ} : f = g β β (x : M), coe_fn f x = coe_fn g x :=
{ mp :=
fun (h : f = g) (x : M) => eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn f x = coe_fn g x)) h)) (Eq.refl (coe_fn g x)),
mpr := ext }
-- make some straightforward lemmas available to `simp`.
@[simp] theorem map_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) : coe_fn f 0 = 0 :=
linear_map.map_zero (to_linear_map f)
@[simp] theorem map_add {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (x : M) (y : M) : coe_fn f (x + y) = coe_fn f x + coe_fn f y :=
linear_map.map_add (to_linear_map f) x y
@[simp] theorem map_smul {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (c : R) (f : continuous_linear_map R M Mβ) (x : M) : coe_fn f (c β’ x) = c β’ coe_fn f x :=
linear_map.map_smul (to_linear_map f) c x
theorem map_sum {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) {ΞΉ : Type u_4} (s : finset ΞΉ) (g : ΞΉ β M) : coe_fn f (finset.sum s fun (i : ΞΉ) => g i) = finset.sum s fun (i : ΞΉ) => coe_fn f (g i) :=
linear_map.map_sum (to_linear_map f)
@[simp] theorem coe_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) : ββf = βf :=
rfl
/-- If two continuous linear maps are equal on a set `s`, then they are equal on the closure
of the `submodule.span` of this set. -/
theorem eq_on_closure_span {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [t2_space Mβ] {s : set M} {f : continuous_linear_map R M Mβ} {g : continuous_linear_map R M Mβ} (h : set.eq_on (βf) (βg) s) : set.eq_on (βf) (βg) (closure β(submodule.span R s)) :=
set.eq_on.closure (linear_map.eq_on_span' h) (continuous_linear_map.continuous f) (continuous_linear_map.continuous g)
/-- If the submodule generated by a set `s` is dense in the ambient semimodule, then two continuous
linear maps equal on `s` are equal. -/
theorem ext_on {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [t2_space Mβ] {s : set M} (hs : dense β(submodule.span R s)) {f : continuous_linear_map R M Mβ} {g : continuous_linear_map R M Mβ} (h : set.eq_on (βf) (βg) s) : f = g :=
ext fun (x : M) => eq_on_closure_span h (hs x)
/-- The continuous map that is constantly zero. -/
protected instance has_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : HasZero (continuous_linear_map R M Mβ) :=
{ zero := mk 0 }
protected instance inhabited {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : Inhabited (continuous_linear_map R M Mβ) :=
{ default := 0 }
@[simp] theorem default_def {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : Inhabited.default = 0 :=
rfl
@[simp] theorem zero_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (x : M) : coe_fn 0 x = 0 :=
rfl
/- no simp attribute on the next line as simp does not always simplify `0 x` to `0`
@[simp] theorem coe_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : β0 = 0 :=
rfl
when `0` is the zero function, while it does for the zero continuous linear map,
and this is the most important property we care about. -/
theorem coe_zero' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : β0 = 0 :=
rfl
protected instance unique_of_left {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [subsingleton M] : unique (continuous_linear_map R M Mβ) :=
function.injective.unique coe_injective
protected instance unique_of_right {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [subsingleton Mβ] : unique (continuous_linear_map R M Mβ) :=
function.injective.unique coe_injective
/-- the identity map as a continuous linear map. -/
def id (R : Type u_1) [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] [semimodule R M] : continuous_linear_map R M M :=
mk linear_map.id
protected instance has_one {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : HasOne (continuous_linear_map R M M) :=
{ one := id R M }
theorem one_def {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : 1 = id R M :=
rfl
theorem id_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (x : M) : coe_fn (id R M) x = x :=
rfl
@[simp] theorem coe_id {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : β(id R M) = linear_map.id :=
rfl
@[simp] theorem coe_id' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : β(id R M) = id :=
rfl
@[simp] theorem one_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (x : M) : coe_fn 1 x = x :=
rfl
protected instance has_add {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [has_continuous_add Mβ] : Add (continuous_linear_map R M Mβ) :=
{ add := fun (f g : continuous_linear_map R M Mβ) => mk (βf + βg) }
@[simp] theorem add_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (g : continuous_linear_map R M Mβ) (x : M) [has_continuous_add Mβ] : coe_fn (f + g) x = coe_fn f x + coe_fn g x :=
rfl
@[simp] theorem coe_add {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (g : continuous_linear_map R M Mβ) [has_continuous_add Mβ] : β(f + g) = βf + βg :=
rfl
theorem coe_add' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (g : continuous_linear_map R M Mβ) [has_continuous_add Mβ] : β(f + g) = βf + βg :=
rfl
protected instance add_comm_monoid {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [has_continuous_add Mβ] : add_comm_monoid (continuous_linear_map R M Mβ) :=
add_comm_monoid.mk Add.add sorry 0 sorry sorry sorry
theorem sum_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [has_continuous_add Mβ] {ΞΉ : Type u_4} (t : finset ΞΉ) (f : ΞΉ β continuous_linear_map R M Mβ) (b : M) : coe_fn (finset.sum t fun (d : ΞΉ) => f d) b = finset.sum t fun (d : ΞΉ) => coe_fn (f d) b :=
Eq.symm (finset.sum_hom t fun (g : continuous_linear_map R M Mβ) => coe_fn g b)
/-- Composition of bounded linear maps. -/
def comp {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (g : continuous_linear_map R Mβ Mβ) (f : continuous_linear_map R M Mβ) : continuous_linear_map R M Mβ :=
mk (linear_map.comp (to_linear_map g) (to_linear_map f))
@[simp] theorem coe_comp {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (h : continuous_linear_map R Mβ Mβ) : β(comp h f) = linear_map.comp βh βf :=
rfl
@[simp] theorem coe_comp' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (h : continuous_linear_map R Mβ Mβ) : β(comp h f) = βh β βf :=
rfl
@[simp] theorem comp_id {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) : comp f (id R M) = f :=
ext fun (x : M) => rfl
@[simp] theorem id_comp {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) : comp (id R Mβ) f = f :=
ext fun (x : M) => rfl
@[simp] theorem comp_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) : comp f 0 = 0 := sorry
@[simp] theorem zero_comp {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) : comp 0 f = 0 := sorry
@[simp] theorem comp_add {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [has_continuous_add Mβ] [has_continuous_add Mβ] (g : continuous_linear_map R Mβ Mβ) (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R M Mβ) : comp g (fβ + fβ) = comp g fβ + comp g fβ := sorry
@[simp] theorem add_comp {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [has_continuous_add Mβ] (gβ : continuous_linear_map R Mβ Mβ) (gβ : continuous_linear_map R Mβ Mβ) (f : continuous_linear_map R M Mβ) : comp (gβ + gβ) f = comp gβ f + comp gβ f := sorry
theorem comp_assoc {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_5} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [semimodule R Mβ] (h : continuous_linear_map R Mβ Mβ) (g : continuous_linear_map R Mβ Mβ) (f : continuous_linear_map R M Mβ) : comp (comp h g) f = comp h (comp g f) :=
rfl
protected instance has_mul {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : Mul (continuous_linear_map R M M) :=
{ mul := comp }
theorem mul_def {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (f : continuous_linear_map R M M) (g : continuous_linear_map R M M) : f * g = comp f g :=
rfl
@[simp] theorem coe_mul {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (f : continuous_linear_map R M M) (g : continuous_linear_map R M M) : β(f * g) = βf β βg :=
rfl
theorem mul_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (f : continuous_linear_map R M M) (g : continuous_linear_map R M M) (x : M) : coe_fn (f * g) x = coe_fn f (coe_fn g x) :=
rfl
/-- The cartesian product of two bounded linear maps, as a bounded linear map. -/
protected def prod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R M Mβ) : continuous_linear_map R M (Mβ Γ Mβ) :=
mk (linear_map.mk (linear_map.to_fun (linear_map.prod (to_linear_map fβ) (to_linear_map fβ))) sorry sorry)
@[simp] theorem coe_prod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R M Mβ) : β(continuous_linear_map.prod fβ fβ) = linear_map.prod βfβ βfβ :=
rfl
@[simp] theorem prod_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R M Mβ) (x : M) : coe_fn (continuous_linear_map.prod fβ fβ) x = (coe_fn fβ x, coe_fn fβ x) :=
rfl
/-- Kernel of a continuous linear map. -/
def ker {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) : submodule R M :=
linear_map.ker βf
theorem ker_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) : linear_map.ker βf = ker f :=
rfl
@[simp] theorem mem_ker {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] {f : continuous_linear_map R M Mβ} {x : M} : x β ker f β coe_fn f x = 0 :=
linear_map.mem_ker
theorem is_closed_ker {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) [t1_space Mβ] : is_closed β(ker f) :=
iff.mp continuous_iff_is_closed (cont f) (ββ₯) is_closed_singleton
@[simp] theorem apply_ker {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (x : β₯(ker f)) : coe_fn f βx = 0 :=
iff.mp mem_ker (subtype.property x)
theorem is_complete_ker {R : Type u_1} [semiring R] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R Mβ] {M' : Type u_2} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [semimodule R M'] [t1_space Mβ] (f : continuous_linear_map R M' Mβ) : is_complete β(ker f) :=
is_closed.is_complete (is_closed_ker f)
protected instance complete_space_ker {R : Type u_1} [semiring R] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R Mβ] {M' : Type u_2} [uniform_space M'] [complete_space M'] [add_comm_monoid M'] [semimodule R M'] [t1_space Mβ] (f : continuous_linear_map R M' Mβ) : complete_space β₯(ker f) :=
is_closed.complete_space_coe (is_closed_ker f)
@[simp] theorem ker_prod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (g : continuous_linear_map R M Mβ) : ker (continuous_linear_map.prod f g) = ker f β ker g :=
linear_map.ker_prod βf βg
/-- Range of a continuous linear map. -/
def range {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) : submodule R Mβ :=
linear_map.range βf
theorem range_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) : β(range f) = set.range βf :=
linear_map.range_coe βf
theorem mem_range {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] {f : continuous_linear_map R M Mβ} {y : Mβ} : y β range f β β (x : M), coe_fn f x = y :=
linear_map.mem_range
theorem range_prod_le {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (g : continuous_linear_map R M Mβ) : range (continuous_linear_map.prod f g) β€ submodule.prod (range f) (range g) :=
linear_map.range_prod_le βf βg
/-- Restrict codomain of a continuous linear map. -/
def cod_restrict {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (p : submodule R Mβ) (h : β (x : M), coe_fn f x β p) : continuous_linear_map R M β₯p :=
mk (linear_map.cod_restrict p (βf) h)
theorem coe_cod_restrict {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (p : submodule R Mβ) (h : β (x : M), coe_fn f x β p) : β(cod_restrict f p h) = linear_map.cod_restrict p (βf) h :=
rfl
@[simp] theorem coe_cod_restrict_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (p : submodule R Mβ) (h : β (x : M), coe_fn f x β p) (x : M) : β(coe_fn (cod_restrict f p h) x) = coe_fn f x :=
rfl
@[simp] theorem ker_cod_restrict {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (p : submodule R Mβ) (h : β (x : M), coe_fn f x β p) : ker (cod_restrict f p h) = ker f :=
linear_map.ker_cod_restrict p (βf) h
/-- Embedding of a submodule into the ambient space as a continuous linear map. -/
def subtype_val {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (p : submodule R M) : continuous_linear_map R (β₯p) M :=
mk (submodule.subtype p)
@[simp] theorem coe_subtype_val {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (p : submodule R M) : β(subtype_val p) = submodule.subtype p :=
rfl
@[simp] theorem subtype_val_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] (p : submodule R M) (x : β₯p) : coe_fn (subtype_val p) x = βx :=
rfl
/-- `prod.fst` as a `continuous_linear_map`. -/
def fst (R : Type u_1) [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] (Mβ : Type u_3) [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : continuous_linear_map R (M Γ Mβ) M :=
mk (linear_map.fst R M Mβ)
/-- `prod.snd` as a `continuous_linear_map`. -/
def snd (R : Type u_1) [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] (Mβ : Type u_3) [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : continuous_linear_map R (M Γ Mβ) Mβ :=
mk (linear_map.snd R M Mβ)
@[simp] theorem coe_fst {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : β(fst R M Mβ) = linear_map.fst R M Mβ :=
rfl
@[simp] theorem coe_fst' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : β(fst R M Mβ) = prod.fst :=
rfl
@[simp] theorem coe_snd {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : β(snd R M Mβ) = linear_map.snd R M Mβ :=
rfl
@[simp] theorem coe_snd' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : β(snd R M Mβ) = prod.snd :=
rfl
@[simp] theorem fst_prod_snd {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : continuous_linear_map.prod (fst R M Mβ) (snd R M Mβ) = id R (M Γ Mβ) := sorry
/-- `prod.map` of two continuous linear maps. -/
def prod_map {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_5} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [semimodule R Mβ] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ Mβ) : continuous_linear_map R (M Γ Mβ) (Mβ Γ Mβ) :=
continuous_linear_map.prod (comp fβ (fst R M Mβ)) (comp fβ (snd R M Mβ))
@[simp] theorem coe_prod_map {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_5} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [semimodule R Mβ] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ Mβ) : β(prod_map fβ fβ) = linear_map.prod_map βfβ βfβ :=
rfl
@[simp] theorem coe_prod_map' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_5} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [semimodule R Mβ] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ Mβ) : β(prod_map fβ fβ) = prod.map βfβ βfβ :=
rfl
/-- The continuous linear map given by `(x, y) β¦ fβ x + fβ y`. -/
def coprod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [has_continuous_add Mβ] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ Mβ) : continuous_linear_map R (M Γ Mβ) Mβ :=
mk (linear_map.coprod βfβ βfβ)
@[simp] theorem coe_coprod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [has_continuous_add Mβ] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ Mβ) : β(coprod fβ fβ) = linear_map.coprod βfβ βfβ :=
rfl
@[simp] theorem coprod_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [has_continuous_add Mβ] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ Mβ) (x : M Γ Mβ) : coe_fn (coprod fβ fβ) x = coe_fn fβ (prod.fst x) + coe_fn fβ (prod.snd x) :=
rfl
/-- The linear map `Ξ» x, c x β’ f`. Associates to a scalar-valued linear map and an element of
`Mβ` the `Mβ`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `Mβ`).
See also `continuous_linear_map.smul_rightβ` and `continuous_linear_map.smul_rightL`. -/
def smul_right {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [topological_space R] [topological_semimodule R Mβ] (c : continuous_linear_map R M R) (f : Mβ) : continuous_linear_map R M Mβ :=
mk (linear_map.mk (linear_map.to_fun (linear_map.smul_right (to_linear_map c) f)) sorry sorry)
@[simp] theorem smul_right_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [topological_space R] [topological_semimodule R Mβ] {c : continuous_linear_map R M R} {f : Mβ} {x : M} : coe_fn (smul_right c f) x = coe_fn c x β’ f :=
rfl
@[simp] theorem smul_right_one_one {R : Type u_1} [semiring R] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R Mβ] [topological_space R] [topological_semimodule R Mβ] (c : continuous_linear_map R R Mβ) : smul_right 1 (coe_fn c 1) = c := sorry
@[simp] theorem smul_right_one_eq_iff {R : Type u_1} [semiring R] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R Mβ] [topological_space R] [topological_semimodule R Mβ] {f : Mβ} {f' : Mβ} : smul_right 1 f = smul_right 1 f' β f = f' := sorry
theorem smul_right_comp {R : Type u_1} [semiring R] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R Mβ] [topological_space R] [topological_semimodule R Mβ] [topological_semimodule R R] {x : Mβ} {c : R} : comp (smul_right 1 x) (smul_right 1 c) = smul_right 1 (c β’ x) := sorry
/-- `pi` construction for continuous linear functions. From a family of continuous linear functions
it produces a continuous linear function into a family of topological modules. -/
def pi {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] {ΞΉ : Type u_4} {Ο : ΞΉ β Type u_5} [(i : ΞΉ) β topological_space (Ο i)] [(i : ΞΉ) β add_comm_monoid (Ο i)] [(i : ΞΉ) β semimodule R (Ο i)] (f : (i : ΞΉ) β continuous_linear_map R M (Ο i)) : continuous_linear_map R M ((i : ΞΉ) β Ο i) :=
mk (linear_map.pi fun (i : ΞΉ) => β(f i))
@[simp] theorem pi_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] {ΞΉ : Type u_4} {Ο : ΞΉ β Type u_5} [(i : ΞΉ) β topological_space (Ο i)] [(i : ΞΉ) β add_comm_monoid (Ο i)] [(i : ΞΉ) β semimodule R (Ο i)] (f : (i : ΞΉ) β continuous_linear_map R M (Ο i)) (c : M) (i : ΞΉ) : coe_fn (pi f) c i = coe_fn (f i) c :=
rfl
theorem pi_eq_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] {ΞΉ : Type u_4} {Ο : ΞΉ β Type u_5} [(i : ΞΉ) β topological_space (Ο i)] [(i : ΞΉ) β add_comm_monoid (Ο i)] [(i : ΞΉ) β semimodule R (Ο i)] (f : (i : ΞΉ) β continuous_linear_map R M (Ο i)) : pi f = 0 β β (i : ΞΉ), f i = 0 := sorry
theorem pi_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] {ΞΉ : Type u_4} {Ο : ΞΉ β Type u_5} [(i : ΞΉ) β topological_space (Ο i)] [(i : ΞΉ) β add_comm_monoid (Ο i)] [(i : ΞΉ) β semimodule R (Ο i)] : (pi fun (i : ΞΉ) => 0) = 0 :=
ext fun (x : M) => funext fun (x_1 : ΞΉ) => Eq.refl (coe_fn (pi fun (i : ΞΉ) => 0) x x_1)
theorem pi_comp {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R Mβ] {ΞΉ : Type u_4} {Ο : ΞΉ β Type u_5} [(i : ΞΉ) β topological_space (Ο i)] [(i : ΞΉ) β add_comm_monoid (Ο i)] [(i : ΞΉ) β semimodule R (Ο i)] (f : (i : ΞΉ) β continuous_linear_map R M (Ο i)) (g : continuous_linear_map R Mβ M) : comp (pi f) g = pi fun (i : ΞΉ) => comp (f i) g :=
rfl
/-- The projections from a family of topological modules are continuous linear maps. -/
def proj {R : Type u_1} [semiring R] {ΞΉ : Type u_4} {Ο : ΞΉ β Type u_5} [(i : ΞΉ) β topological_space (Ο i)] [(i : ΞΉ) β add_comm_monoid (Ο i)] [(i : ΞΉ) β semimodule R (Ο i)] (i : ΞΉ) : continuous_linear_map R ((i : ΞΉ) β Ο i) (Ο i) :=
mk (linear_map.proj i)
@[simp] theorem proj_apply {R : Type u_1} [semiring R] {ΞΉ : Type u_4} {Ο : ΞΉ β Type u_5} [(i : ΞΉ) β topological_space (Ο i)] [(i : ΞΉ) β add_comm_monoid (Ο i)] [(i : ΞΉ) β semimodule R (Ο i)] (i : ΞΉ) (b : (i : ΞΉ) β Ο i) : coe_fn (proj i) b = b i :=
rfl
theorem proj_pi {R : Type u_1} [semiring R] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R Mβ] {ΞΉ : Type u_4} {Ο : ΞΉ β Type u_5} [(i : ΞΉ) β topological_space (Ο i)] [(i : ΞΉ) β add_comm_monoid (Ο i)] [(i : ΞΉ) β semimodule R (Ο i)] (f : (i : ΞΉ) β continuous_linear_map R Mβ (Ο i)) (i : ΞΉ) : comp (proj i) (pi f) = f i :=
ext fun (c : Mβ) => rfl
theorem infi_ker_proj {R : Type u_1} [semiring R] {ΞΉ : Type u_4} {Ο : ΞΉ β Type u_5} [(i : ΞΉ) β topological_space (Ο i)] [(i : ΞΉ) β add_comm_monoid (Ο i)] [(i : ΞΉ) β semimodule R (Ο i)] : (infi fun (i : ΞΉ) => ker (proj i)) = β₯ :=
linear_map.infi_ker_proj
/-- If `I` and `J` are complementary index sets, the product of the kernels of the `J`th projections of
`Ο` is linearly equivalent to the product over `I`. -/
def infi_ker_proj_equiv (R : Type u_1) [semiring R] {ΞΉ : Type u_4} (Ο : ΞΉ β Type u_5) [(i : ΞΉ) β topological_space (Ο i)] [(i : ΞΉ) β add_comm_monoid (Ο i)] [(i : ΞΉ) β semimodule R (Ο i)] {I : set ΞΉ} {J : set ΞΉ} [decidable_pred fun (i : ΞΉ) => i β I] (hd : disjoint I J) (hu : set.univ β I βͺ J) : continuous_linear_equiv R (β₯(infi fun (i : ΞΉ) => infi fun (H : i β J) => ker (proj i))) ((i : β₯I) β Ο βi) :=
continuous_linear_equiv.mk (linear_map.infi_ker_proj_equiv R Ο hd hu)
@[simp] theorem map_neg {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (x : M) : coe_fn f (-x) = -coe_fn f x :=
linear_map.map_neg (to_linear_map f) x
@[simp] theorem map_sub {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (x : M) (y : M) : coe_fn f (x - y) = coe_fn f x - coe_fn f y :=
linear_map.map_sub (to_linear_map f) x y
@[simp] theorem sub_apply' {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (g : continuous_linear_map R M Mβ) (x : M) : coe_fn (βf - βg) x = coe_fn f x - coe_fn g x :=
rfl
theorem range_prod_eq {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] {f : continuous_linear_map R M Mβ} {g : continuous_linear_map R M Mβ} (h : ker f β ker g = β€) : range (continuous_linear_map.prod f g) = submodule.prod (range f) (range g) :=
linear_map.range_prod_eq h
protected instance has_neg {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] [topological_add_group Mβ] : Neg (continuous_linear_map R M Mβ) :=
{ neg := fun (f : continuous_linear_map R M Mβ) => mk (-βf) }
@[simp] theorem neg_apply {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (x : M) [topological_add_group Mβ] : coe_fn (-f) x = -coe_fn f x :=
rfl
@[simp] theorem coe_neg {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) [topological_add_group Mβ] : β(-f) = -βf :=
rfl
theorem coe_neg' {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) [topological_add_group Mβ] : β(-f) = -βf :=
rfl
protected instance has_sub {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] [topological_add_group Mβ] : Sub (continuous_linear_map R M Mβ) :=
{ sub := fun (f g : continuous_linear_map R M Mβ) => mk (βf - βg) }
protected instance add_comm_group {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] [topological_add_group Mβ] : add_comm_group (continuous_linear_map R M Mβ) :=
add_comm_group.mk Add.add sorry 0 sorry sorry Neg.neg Sub.sub sorry sorry
theorem sub_apply {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (g : continuous_linear_map R M Mβ) [topological_add_group Mβ] (x : M) : coe_fn (f - g) x = coe_fn f x - coe_fn g x :=
rfl
@[simp] theorem coe_sub {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (g : continuous_linear_map R M Mβ) [topological_add_group Mβ] : β(f - g) = βf - βg :=
rfl
@[simp] theorem coe_sub' {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_map R M Mβ) (g : continuous_linear_map R M Mβ) [topological_add_group Mβ] : β(f - g) = βf - βg :=
rfl
protected instance ring {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] [topological_add_group M] : ring (continuous_linear_map R M M) :=
ring.mk add_comm_group.add sorry add_comm_group.zero sorry sorry add_comm_group.neg add_comm_group.sub sorry sorry
Mul.mul sorry 1 sorry sorry sorry sorry
theorem smul_right_one_pow {R : Type u_1} [ring R] [topological_space R] [topological_add_group R] [topological_semimodule R R] (c : R) (n : β) : smul_right 1 c ^ n = smul_right 1 (c ^ n) := sorry
/-- Given a right inverse `fβ : Mβ βL[R] M` to `fβ : M βL[R] Mβ`,
`proj_ker_of_right_inverse fβ fβ h` is the projection `M βL[R] fβ.ker` along `fβ.range`. -/
def proj_ker_of_right_inverse {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] [topological_add_group M] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ M) (h : function.right_inverse βfβ βfβ) : continuous_linear_map R M β₯(ker fβ) :=
cod_restrict (id R M - comp fβ fβ) (ker fβ) sorry
@[simp] theorem coe_proj_ker_of_right_inverse_apply {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] [topological_add_group M] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ M) (h : function.right_inverse βfβ βfβ) (x : M) : β(coe_fn (proj_ker_of_right_inverse fβ fβ h) x) = x - coe_fn fβ (coe_fn fβ x) :=
rfl
@[simp] theorem proj_ker_of_right_inverse_apply_idem {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] [topological_add_group M] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ M) (h : function.right_inverse βfβ βfβ) (x : β₯(ker fβ)) : coe_fn (proj_ker_of_right_inverse fβ fβ h) βx = x := sorry
@[simp] theorem proj_ker_of_right_inverse_comp_inv {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] [topological_add_group M] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ M) (h : function.right_inverse βfβ βfβ) (y : Mβ) : coe_fn (proj_ker_of_right_inverse fβ fβ h) (coe_fn fβ y) = 0 := sorry
protected instance has_scalar {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_4} [topological_space Mβ] [add_comm_group Mβ] [module R M] [module R Mβ] [topological_module R Mβ] : has_scalar R (continuous_linear_map R M Mβ) :=
has_scalar.mk fun (c : R) (f : continuous_linear_map R M Mβ) => mk (c β’ βf)
@[simp] theorem smul_comp {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_group Mβ] [module R M] [module R Mβ] [module R Mβ] [topological_module R Mβ] (c : R) (h : continuous_linear_map R Mβ Mβ) (f : continuous_linear_map R M Mβ) : comp (c β’ h) f = c β’ comp h f :=
rfl
@[simp] theorem smul_apply {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [module R M] [module R Mβ] (c : R) (f : continuous_linear_map R M Mβ) (x : M) [topological_module R Mβ] : coe_fn (c β’ f) x = c β’ coe_fn f x :=
rfl
@[simp] theorem coe_apply {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [module R M] [module R Mβ] (c : R) (f : continuous_linear_map R M Mβ) [topological_module R Mβ] : β(c β’ f) = c β’ βf :=
rfl
theorem coe_apply' {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [module R M] [module R Mβ] (c : R) (f : continuous_linear_map R M Mβ) [topological_module R Mβ] : β(c β’ f) = c β’ βf :=
rfl
@[simp] theorem comp_smul {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_group Mβ] [module R M] [module R Mβ] [module R Mβ] [topological_module R Mβ] (c : R) (h : continuous_linear_map R Mβ Mβ) (f : continuous_linear_map R M Mβ) [topological_module R Mβ] : comp h (c β’ f) = c β’ comp h f := sorry
protected instance module {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [module R M] [module R Mβ] [topological_module R Mβ] [topological_add_group Mβ] : module R (continuous_linear_map R M Mβ) :=
semimodule.mk sorry sorry
protected instance algebra {R : Type u_1} [comm_ring R] [topological_space R] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [module R Mβ] [topological_module R Mβ] [topological_add_group Mβ] : algebra R (continuous_linear_map R Mβ Mβ) :=
algebra.of_semimodule' sorry sorry
/-- Given `c : E βL[π] π`, `c.smul_rightβ` is the linear map from `F` to `E βL[π] F`
sending `f` to `Ξ» e, c e β’ f`. See also `continuous_linear_map.smul_rightL`. -/
def smul_rightβ {R : Type u_1} [comm_ring R] [topological_space R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [module R M] [module R Mβ] [topological_module R Mβ] [topological_add_group Mβ] (c : continuous_linear_map R M R) : linear_map R Mβ (continuous_linear_map R M Mβ) :=
linear_map.mk (smul_right c) sorry sorry
end continuous_linear_map
namespace continuous_linear_equiv
/-- A continuous linear equivalence induces a continuous linear map. -/
def to_continuous_linear_map {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : continuous_linear_map R M Mβ :=
continuous_linear_map.mk
(linear_map.mk (linear_map.to_fun (linear_equiv.to_linear_map (to_linear_equiv e))) sorry sorry)
/-- Coerce continuous linear equivs to continuous linear maps. -/
protected instance continuous_linear_map.has_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : has_coe (continuous_linear_equiv R M Mβ) (continuous_linear_map R M Mβ) :=
has_coe.mk to_continuous_linear_map
/-- Coerce continuous linear equivs to maps. -/
-- see Note [function coercion]
protected instance has_coe_to_fun {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] : has_coe_to_fun (continuous_linear_equiv R M Mβ) :=
has_coe_to_fun.mk (fun (_x : continuous_linear_equiv R M Mβ) => M β Mβ) fun (f : continuous_linear_equiv R M Mβ) => βf
@[simp] theorem coe_def_rev {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : to_continuous_linear_map e = βe :=
rfl
@[simp] theorem coe_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) (b : M) : coe_fn (βe) b = coe_fn e b :=
rfl
@[simp] theorem coe_to_linear_equiv {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (f : continuous_linear_equiv R M Mβ) : β(to_linear_equiv f) = βf :=
rfl
theorem coe_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : ββe = βe :=
rfl
theorem ext {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] {f : continuous_linear_equiv R M Mβ} {g : continuous_linear_equiv R M Mβ} (h : βf = βg) : f = g := sorry
/-- A continuous linear equivalence induces a homeomorphism. -/
def to_homeomorph {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : M ββ Mβ :=
homeomorph.mk
(equiv.mk (linear_equiv.to_fun (to_linear_equiv e)) (linear_equiv.inv_fun (to_linear_equiv e)) sorry sorry)
-- Make some straightforward lemmas available to `simp`.
@[simp] theorem map_zero {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : coe_fn e 0 = 0 :=
continuous_linear_map.map_zero βe
@[simp] theorem map_add {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) (x : M) (y : M) : coe_fn e (x + y) = coe_fn e x + coe_fn e y :=
continuous_linear_map.map_add (βe) x y
@[simp] theorem map_smul {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) (c : R) (x : M) : coe_fn e (c β’ x) = c β’ coe_fn e x :=
continuous_linear_map.map_smul c (βe) x
@[simp] theorem map_eq_zero_iff {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) {x : M} : coe_fn e x = 0 β x = 0 :=
linear_equiv.map_eq_zero_iff (to_linear_equiv e)
protected theorem continuous {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : continuous βe :=
continuous_to_fun e
protected theorem continuous_on {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) {s : set M} : continuous_on (βe) s :=
continuous.continuous_on (continuous_linear_equiv.continuous e)
protected theorem continuous_at {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) {x : M} : continuous_at (βe) x :=
continuous.continuous_at (continuous_linear_equiv.continuous e)
protected theorem continuous_within_at {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) {s : set M} {x : M} : continuous_within_at (βe) s x :=
continuous.continuous_within_at (continuous_linear_equiv.continuous e)
theorem comp_continuous_on_iff {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] {Ξ± : Type u_4} [topological_space Ξ±] (e : continuous_linear_equiv R M Mβ) {f : Ξ± β M} {s : set Ξ±} : continuous_on (βe β f) s β continuous_on f s :=
homeomorph.comp_continuous_on_iff (to_homeomorph e) f s
theorem comp_continuous_iff {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] {Ξ± : Type u_4} [topological_space Ξ±] (e : continuous_linear_equiv R M Mβ) {f : Ξ± β M} : continuous (βe β f) β continuous f :=
homeomorph.comp_continuous_iff (to_homeomorph e)
/-- An extensionality lemma for `R βL[R] M`. -/
theorem extβ {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_space R] {f : continuous_linear_equiv R R M} {g : continuous_linear_equiv R R M} (h : coe_fn f 1 = coe_fn g 1) : f = g := sorry
/-- The identity map as a continuous linear equivalence. -/
protected def refl (R : Type u_1) [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] [semimodule R M] : continuous_linear_equiv R M M :=
mk
(linear_equiv.mk (linear_equiv.to_fun (linear_equiv.refl R M)) sorry sorry
(linear_equiv.inv_fun (linear_equiv.refl R M)) sorry sorry)
@[simp] theorem coe_refl {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : β(continuous_linear_equiv.refl R M) = continuous_linear_map.id R M :=
rfl
@[simp] theorem coe_refl' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : β(continuous_linear_equiv.refl R M) = id :=
rfl
/-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/
protected def symm {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : continuous_linear_equiv R Mβ M :=
mk
(linear_equiv.mk (linear_equiv.to_fun (linear_equiv.symm (to_linear_equiv e))) sorry sorry
(linear_equiv.inv_fun (linear_equiv.symm (to_linear_equiv e))) sorry sorry)
@[simp] theorem symm_to_linear_equiv {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : to_linear_equiv (continuous_linear_equiv.symm e) = linear_equiv.symm (to_linear_equiv e) :=
linear_equiv.ext fun (x : Mβ) => Eq.refl (coe_fn (to_linear_equiv (continuous_linear_equiv.symm e)) x)
/-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/
protected def trans {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (eβ : continuous_linear_equiv R M Mβ) (eβ : continuous_linear_equiv R Mβ Mβ) : continuous_linear_equiv R M Mβ :=
mk
(linear_equiv.mk (linear_equiv.to_fun (linear_equiv.trans (to_linear_equiv eβ) (to_linear_equiv eβ))) sorry sorry
(linear_equiv.inv_fun (linear_equiv.trans (to_linear_equiv eβ) (to_linear_equiv eβ))) sorry sorry)
@[simp] theorem trans_to_linear_equiv {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (eβ : continuous_linear_equiv R M Mβ) (eβ : continuous_linear_equiv R Mβ Mβ) : to_linear_equiv (continuous_linear_equiv.trans eβ eβ) = linear_equiv.trans (to_linear_equiv eβ) (to_linear_equiv eβ) :=
linear_equiv.ext fun (x : M) => Eq.refl (coe_fn (to_linear_equiv (continuous_linear_equiv.trans eβ eβ)) x)
/-- Product of two continuous linear equivalences. The map comes from `equiv.prod_congr`. -/
def prod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_5} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) (e' : continuous_linear_equiv R Mβ Mβ) : continuous_linear_equiv R (M Γ Mβ) (Mβ Γ Mβ) :=
mk
(linear_equiv.mk (linear_equiv.to_fun (linear_equiv.prod (to_linear_equiv e) (to_linear_equiv e'))) sorry sorry
(linear_equiv.inv_fun (linear_equiv.prod (to_linear_equiv e) (to_linear_equiv e'))) sorry sorry)
@[simp] theorem prod_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_5} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) (e' : continuous_linear_equiv R Mβ Mβ) (x : M Γ Mβ) : coe_fn (prod e e') x = (coe_fn e (prod.fst x), coe_fn e' (prod.snd x)) :=
rfl
@[simp] theorem coe_prod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_5} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) (e' : continuous_linear_equiv R Mβ Mβ) : β(prod e e') = continuous_linear_map.prod_map βe βe' :=
rfl
theorem bijective {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : function.bijective βe :=
equiv.bijective (linear_equiv.to_equiv (to_linear_equiv e))
theorem injective {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : function.injective βe :=
equiv.injective (linear_equiv.to_equiv (to_linear_equiv e))
theorem surjective {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : function.surjective βe :=
equiv.surjective (linear_equiv.to_equiv (to_linear_equiv e))
@[simp] theorem trans_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (eβ : continuous_linear_equiv R M Mβ) (eβ : continuous_linear_equiv R Mβ Mβ) (c : M) : coe_fn (continuous_linear_equiv.trans eβ eβ) c = coe_fn eβ (coe_fn eβ c) :=
rfl
@[simp] theorem apply_symm_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) (c : Mβ) : coe_fn e (coe_fn (continuous_linear_equiv.symm e) c) = c :=
linear_equiv.right_inv (to_linear_equiv e) c
@[simp] theorem symm_apply_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) (b : M) : coe_fn (continuous_linear_equiv.symm e) (coe_fn e b) = b :=
linear_equiv.left_inv (to_linear_equiv e) b
@[simp] theorem symm_trans_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (eβ : continuous_linear_equiv R Mβ M) (eβ : continuous_linear_equiv R Mβ Mβ) (c : M) : coe_fn (continuous_linear_equiv.symm (continuous_linear_equiv.trans eβ eβ)) c =
coe_fn (continuous_linear_equiv.symm eβ) (coe_fn (continuous_linear_equiv.symm eβ) c) :=
rfl
@[simp] theorem comp_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] (f : continuous_linear_equiv R M Mβ) (f' : continuous_linear_equiv R Mβ Mβ) : continuous_linear_map.comp βf' βf = β(continuous_linear_equiv.trans f f') :=
rfl
@[simp] theorem coe_comp_coe_symm {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : continuous_linear_map.comp βe β(continuous_linear_equiv.symm e) = continuous_linear_map.id R Mβ :=
continuous_linear_map.ext (apply_symm_apply e)
@[simp] theorem coe_symm_comp_coe {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : continuous_linear_map.comp β(continuous_linear_equiv.symm e) βe = continuous_linear_map.id R M :=
continuous_linear_map.ext (symm_apply_apply e)
theorem symm_comp_self {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : β(continuous_linear_equiv.symm e) β βe = id :=
funext fun (x : M) => symm_apply_apply e x
theorem self_comp_symm {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : βe β β(continuous_linear_equiv.symm e) = id :=
funext fun (x : Mβ) => apply_symm_apply e x
@[simp] theorem symm_comp_self' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : ββ(continuous_linear_equiv.symm e) β ββe = id :=
symm_comp_self e
@[simp] theorem self_comp_symm' {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : ββe β ββ(continuous_linear_equiv.symm e) = id :=
self_comp_symm e
@[simp] theorem symm_symm {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) : continuous_linear_equiv.symm (continuous_linear_equiv.symm e) = e :=
ext (funext fun (x : M) => Eq.refl (coe_fn (continuous_linear_equiv.symm (continuous_linear_equiv.symm e)) x))
@[simp] theorem refl_symm {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] [semimodule R M] : continuous_linear_equiv.symm (continuous_linear_equiv.refl R M) = continuous_linear_equiv.refl R M :=
rfl
theorem symm_symm_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) (x : M) : coe_fn (continuous_linear_equiv.symm (continuous_linear_equiv.symm e)) x = coe_fn e x :=
rfl
theorem symm_apply_eq {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) {x : Mβ} {y : M} : coe_fn (continuous_linear_equiv.symm e) x = y β x = coe_fn e y :=
linear_equiv.symm_apply_eq (to_linear_equiv e)
theorem eq_symm_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) {x : Mβ} {y : M} : y = coe_fn (continuous_linear_equiv.symm e) x β coe_fn e y = x :=
linear_equiv.eq_symm_apply (to_linear_equiv e)
/-- Create a `continuous_linear_equiv` from two `continuous_linear_map`s that are
inverse of each other. -/
def equiv_of_inverse {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ M) (hβ : function.left_inverse βfβ βfβ) (hβ : function.right_inverse βfβ βfβ) : continuous_linear_equiv R M Mβ :=
mk (linear_equiv.mk βfβ sorry sorry (βfβ) hβ hβ)
@[simp] theorem equiv_of_inverse_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ M) (hβ : function.left_inverse βfβ βfβ) (hβ : function.right_inverse βfβ βfβ) (x : M) : coe_fn (equiv_of_inverse fβ fβ hβ hβ) x = coe_fn fβ x :=
rfl
@[simp] theorem symm_equiv_of_inverse {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_monoid M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_monoid Mβ] [semimodule R M] [semimodule R Mβ] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ M) (hβ : function.left_inverse βfβ βfβ) (hβ : function.right_inverse βfβ βfβ) : continuous_linear_equiv.symm (equiv_of_inverse fβ fβ hβ hβ) = equiv_of_inverse fβ fβ hβ hβ :=
rfl
/-- The continuous linear equivalences from `M` to itself form a group under composition. -/
protected instance automorphism_group {R : Type u_1} [semiring R] (M : Type u_2) [topological_space M] [add_comm_monoid M] [semimodule R M] : group (continuous_linear_equiv R M M) :=
group.mk (fun (f g : continuous_linear_equiv R M M) => continuous_linear_equiv.trans g f) sorry
(continuous_linear_equiv.refl R M) sorry sorry
(fun (f : continuous_linear_equiv R M M) => continuous_linear_equiv.symm f)
(div_inv_monoid.div._default (fun (f g : continuous_linear_equiv R M M) => continuous_linear_equiv.trans g f) sorry
(continuous_linear_equiv.refl R M) sorry sorry
fun (f : continuous_linear_equiv R M M) => continuous_linear_equiv.symm f)
sorry
/-- Equivalence given by a block lower diagonal matrix. `e` and `e'` are diagonal square blocks,
and `f` is a rectangular block below the diagonal. -/
def skew_prod {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_group Mβ] {Mβ : Type u_5} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [semimodule R Mβ] [topological_add_group Mβ] (e : continuous_linear_equiv R M Mβ) (e' : continuous_linear_equiv R Mβ Mβ) (f : continuous_linear_map R M Mβ) : continuous_linear_equiv R (M Γ Mβ) (Mβ Γ Mβ) :=
mk
(linear_equiv.mk (linear_equiv.to_fun (linear_equiv.skew_prod (to_linear_equiv e) (to_linear_equiv e') βf)) sorry
sorry (linear_equiv.inv_fun (linear_equiv.skew_prod (to_linear_equiv e) (to_linear_equiv e') βf)) sorry sorry)
@[simp] theorem skew_prod_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_group Mβ] {Mβ : Type u_5} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [semimodule R Mβ] [topological_add_group Mβ] (e : continuous_linear_equiv R M Mβ) (e' : continuous_linear_equiv R Mβ Mβ) (f : continuous_linear_map R M Mβ) (x : M Γ Mβ) : coe_fn (skew_prod e e' f) x = (coe_fn e (prod.fst x), coe_fn e' (prod.snd x) + coe_fn f (prod.fst x)) :=
rfl
@[simp] theorem skew_prod_symm_apply {R : Type u_1} [semiring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] {Mβ : Type u_4} [topological_space Mβ] [add_comm_group Mβ] {Mβ : Type u_5} [topological_space Mβ] [add_comm_group Mβ] [semimodule R M] [semimodule R Mβ] [semimodule R Mβ] [semimodule R Mβ] [topological_add_group Mβ] (e : continuous_linear_equiv R M Mβ) (e' : continuous_linear_equiv R Mβ Mβ) (f : continuous_linear_map R M Mβ) (x : Mβ Γ Mβ) : coe_fn (continuous_linear_equiv.symm (skew_prod e e' f)) x =
(coe_fn (continuous_linear_equiv.symm e) (prod.fst x),
coe_fn (continuous_linear_equiv.symm e')
(prod.snd x - coe_fn f (coe_fn (continuous_linear_equiv.symm e) (prod.fst x)))) :=
rfl
@[simp] theorem map_sub {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) (x : M) (y : M) : coe_fn e (x - y) = coe_fn e x - coe_fn e y :=
continuous_linear_map.map_sub (βe) x y
@[simp] theorem map_neg {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R Mβ] (e : continuous_linear_equiv R M Mβ) (x : M) : coe_fn e (-x) = -coe_fn e x :=
continuous_linear_map.map_neg (βe) x
/-! The next theorems cover the identification between `M βL[π] M`and the group of units of the ring
`M βL[R] M`. -/
/-- An invertible continuous linear map `f` determines a continuous equivalence from `M` to itself.
-/
def of_unit {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] [topological_add_group M] (f : units (continuous_linear_map R M M)) : continuous_linear_equiv R M M :=
mk (linear_equiv.mk β(units.val f) sorry sorry β(units.inv f) sorry sorry)
/-- A continuous equivalence from `M` to itself determines an invertible continuous linear map. -/
def to_unit {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] [topological_add_group M] (f : continuous_linear_equiv R M M) : units (continuous_linear_map R M M) :=
units.mk βf β(continuous_linear_equiv.symm f) sorry sorry
/-- The units of the algebra of continuous `R`-linear endomorphisms of `M` is multiplicatively
equivalent to the type of continuous linear equivalences between `M` and itself. -/
def units_equiv (R : Type u_1) [ring R] (M : Type u_2) [topological_space M] [add_comm_group M] [semimodule R M] [topological_add_group M] : units (continuous_linear_map R M M) β* continuous_linear_equiv R M M :=
mul_equiv.mk of_unit to_unit sorry sorry sorry
@[simp] theorem units_equiv_apply (R : Type u_1) [ring R] (M : Type u_2) [topological_space M] [add_comm_group M] [semimodule R M] [topological_add_group M] (f : units (continuous_linear_map R M M)) (x : M) : coe_fn (coe_fn (units_equiv R M) f) x = coe_fn f x :=
rfl
/-- Continuous linear equivalences `R βL[R] R` are enumerated by `units R`. -/
def units_equiv_aut (R : Type u_1) [ring R] [topological_space R] [topological_module R R] : units R β continuous_linear_equiv R R R :=
equiv.mk
(fun (u : units R) =>
equiv_of_inverse (continuous_linear_map.smul_right 1 βu) (continuous_linear_map.smul_right 1 β(uβ»ΒΉ)) sorry sorry)
(fun (e : continuous_linear_equiv R R R) =>
units.mk (coe_fn e 1) (coe_fn (continuous_linear_equiv.symm e) 1) sorry sorry)
sorry sorry
@[simp] theorem units_equiv_aut_apply {R : Type u_1} [ring R] [topological_space R] [topological_module R R] (u : units R) (x : R) : coe_fn (coe_fn (units_equiv_aut R) u) x = x * βu :=
rfl
@[simp] theorem units_equiv_aut_apply_symm {R : Type u_1} [ring R] [topological_space R] [topological_module R R] (u : units R) (x : R) : coe_fn (continuous_linear_equiv.symm (coe_fn (units_equiv_aut R) u)) x = x * β(uβ»ΒΉ) :=
rfl
@[simp] theorem units_equiv_aut_symm_apply {R : Type u_1} [ring R] [topological_space R] [topological_module R R] (e : continuous_linear_equiv R R R) : β(coe_fn (equiv.symm (units_equiv_aut R)) e) = coe_fn e 1 :=
rfl
/-- A pair of continuous linear maps such that `fβ β fβ = id` generates a continuous
linear equivalence `e` between `M` and `Mβ Γ fβ.ker` such that `(e x).2 = x` for `x β fβ.ker`,
`(e x).1 = fβ x`, and `(e (fβ y)).2 = 0`. The map is given by `e x = (fβ x, x - fβ (fβ x))`. -/
def equiv_of_right_inverse {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R Mβ] [topological_add_group M] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ M) (h : function.right_inverse βfβ βfβ) : continuous_linear_equiv R M (Mβ Γ β₯(continuous_linear_map.ker fβ)) :=
equiv_of_inverse (continuous_linear_map.prod fβ (continuous_linear_map.proj_ker_of_right_inverse fβ fβ h))
(continuous_linear_map.coprod fβ (continuous_linear_map.subtype_val (continuous_linear_map.ker fβ))) sorry sorry
@[simp] theorem fst_equiv_of_right_inverse {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R Mβ] [topological_add_group M] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ M) (h : function.right_inverse βfβ βfβ) (x : M) : prod.fst (coe_fn (equiv_of_right_inverse fβ fβ h) x) = coe_fn fβ x :=
rfl
@[simp] theorem snd_equiv_of_right_inverse {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R Mβ] [topological_add_group M] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ M) (h : function.right_inverse βfβ βfβ) (x : M) : β(prod.snd (coe_fn (equiv_of_right_inverse fβ fβ h) x)) = x - coe_fn fβ (coe_fn fβ x) :=
rfl
@[simp] theorem equiv_of_right_inverse_symm_apply {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [semimodule R M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [semimodule R Mβ] [topological_add_group M] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ M) (h : function.right_inverse βfβ βfβ) (y : Mβ Γ β₯(continuous_linear_map.ker fβ)) : coe_fn (continuous_linear_equiv.symm (equiv_of_right_inverse fβ fβ h)) y = coe_fn fβ (prod.fst y) + β(prod.snd y) :=
rfl
end continuous_linear_equiv
namespace continuous_linear_map
/-- Introduce a function `inverse` from `M βL[R] Mβ` to `Mβ βL[R] M`, which sends `f` to `f.symm` if
`f` is a continuous linear equivalence and to `0` otherwise. This definition is somewhat ad hoc,
but one needs a fully (rather than partially) defined inverse function for some purposes, including
for calculus. -/
def inverse {R : Type u_1} {M : Type u_2} {Mβ : Type u_3} [topological_space M] [topological_space Mβ] [semiring R] [add_comm_monoid Mβ] [semimodule R Mβ] [add_comm_monoid M] [semimodule R M] : continuous_linear_map R M Mβ β continuous_linear_map R Mβ M :=
fun (f : continuous_linear_map R M Mβ) =>
dite (β (e : continuous_linear_equiv R M Mβ), βe = f)
(fun (h : β (e : continuous_linear_equiv R M Mβ), βe = f) => β(continuous_linear_equiv.symm (classical.some h)))
fun (h : Β¬β (e : continuous_linear_equiv R M Mβ), βe = f) => 0
/-- By definition, if `f` is invertible then `inverse f = f.symm`. -/
@[simp] theorem inverse_equiv {R : Type u_1} {M : Type u_2} {Mβ : Type u_3} [topological_space M] [topological_space Mβ] [semiring R] [add_comm_monoid Mβ] [semimodule R Mβ] [add_comm_monoid M] [semimodule R M] (e : continuous_linear_equiv R M Mβ) : inverse βe = β(continuous_linear_equiv.symm e) := sorry
/-- By definition, if `f` is not invertible then `inverse f = 0`. -/
@[simp] theorem inverse_non_equiv {R : Type u_1} {M : Type u_2} {Mβ : Type u_3} [topological_space M] [topological_space Mβ] [semiring R] [add_comm_monoid Mβ] [semimodule R Mβ] [add_comm_monoid M] [semimodule R M] (f : continuous_linear_map R M Mβ) (h : Β¬β (e' : continuous_linear_equiv R M Mβ), βe' = f) : inverse f = 0 :=
dif_neg h
@[simp] theorem ring_inverse_equiv {R : Type u_1} {M : Type u_2} [topological_space M] [ring R] [add_comm_group M] [topological_add_group M] [module R M] (e : continuous_linear_equiv R M M) : ring.inverse βe = inverse βe := sorry
/-- The function `continuous_linear_equiv.inverse` can be written in terms of `ring.inverse` for the
ring of self-maps of the domain. -/
theorem to_ring_inverse {R : Type u_1} {M : Type u_2} {Mβ : Type u_3} [topological_space M] [topological_space Mβ] [ring R] [add_comm_group M] [topological_add_group M] [module R M] [add_comm_group Mβ] [module R Mβ] (e : continuous_linear_equiv R M Mβ) (f : continuous_linear_map R M Mβ) : inverse f = comp (ring.inverse (comp (β(continuous_linear_equiv.symm e)) f)) β(continuous_linear_equiv.symm e) := sorry
theorem ring_inverse_eq_map_inverse {R : Type u_1} {M : Type u_2} [topological_space M] [ring R] [add_comm_group M] [topological_add_group M] [module R M] : ring.inverse = inverse := sorry
end continuous_linear_map
namespace submodule
/-- A submodule `p` is called *complemented* if there exists a continuous projection `M ββ[R] p`. -/
def closed_complemented {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [module R M] (p : submodule R M) :=
β (f : continuous_linear_map R M β₯p), β (x : β₯p), coe_fn f βx = x
theorem closed_complemented.has_closed_complement {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [module R M] {p : submodule R M} [t1_space β₯p] (h : closed_complemented p) : β (q : submodule R M), β (hq : is_closed βq), is_compl p q := sorry
protected theorem closed_complemented.is_closed {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [module R M] [topological_add_group M] [t1_space M] {p : submodule R M} (h : closed_complemented p) : is_closed βp := sorry
@[simp] theorem closed_complemented_bot {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [module R M] : closed_complemented β₯ := sorry
@[simp] theorem closed_complemented_top {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] [module R M] : closed_complemented β€ := sorry
end submodule
theorem continuous_linear_map.closed_complemented_ker_of_right_inverse {R : Type u_1} [ring R] {M : Type u_2} [topological_space M] [add_comm_group M] {Mβ : Type u_3} [topological_space Mβ] [add_comm_group Mβ] [module R M] [module R Mβ] [topological_add_group M] (fβ : continuous_linear_map R M Mβ) (fβ : continuous_linear_map R Mβ M) (h : function.right_inverse βfβ βfβ) : submodule.closed_complemented (continuous_linear_map.ker fβ) :=
Exists.intro (continuous_linear_map.proj_ker_of_right_inverse fβ fβ h)
(continuous_linear_map.proj_ker_of_right_inverse_apply_idem fβ fβ h)
|
5f13aa1372284f10a49a6d711ce89ef4f15624a3 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/data/ordmap/ordset.lean | b0aacf4dd1846b0a629fdd0d38169db044018260 | [
"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 | 69,248 | lean | /-
Copyright (c) 2017 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.ordmap.ordnode
import algebra.order.ring
import data.nat.dist
import tactic.linarith
/-!
# Verification of the `ordnode Ξ±` datatype
This file proves the correctness of the operations in `data.ordmap.ordnode`.
The public facing version is the type `ordset Ξ±`, which is a wrapper around
`ordnode Ξ±` which includes the correctness invariant of the type, and it exposes
parallel operations like `insert` as functions on `ordset` that do the same
thing but bundle the correctness proofs. The advantage is that it is possible
to, for example, prove that the result of `find` on `insert` will actually find
the element, while `ordnode` cannot guarantee this if the input tree did not
satisfy the type invariants.
## Main definitions
* `ordset Ξ±`: A well formed set of values of type `Ξ±`
## Implementation notes
The majority of this file is actually in the `ordnode` namespace, because we first
have to prove the correctness of all the operations (and defining what correctness
means here is actually somewhat subtle). So all the actual `ordset` operations are
at the very end, once we have all the theorems.
An `ordnode Ξ±` is an inductive type which describes a tree which stores the `size` at
internal nodes. The correctness invariant of an `ordnode Ξ±` is:
* `ordnode.sized t`: All internal `size` fields must match the actual measured
size of the tree. (This is not hard to satisfy.)
* `ordnode.balanced t`: Unless the tree has the form `()` or `((a) b)` or `(a (b))`
(that is, nil or a single singleton subtree), the two subtrees must satisfy
`size l β€ Ξ΄ * size r` and `size r β€ Ξ΄ * size l`, where `Ξ΄ := 3` is a global
parameter of the data structure (and this property must hold recursively at subtrees).
This is why we say this is a "size balanced tree" data structure.
* `ordnode.bounded lo hi t`: The members of the tree must be in strictly increasing order,
meaning that if `a` is in the left subtree and `b` is the root, then `a β€ b` and
`Β¬ (b β€ a)`. We enforce this using `ordnode.bounded` which includes also a global
upper and lower bound.
Because the `ordnode` file was ported from Haskell, the correctness invariants of some
of the functions have not been spelled out, and some theorems like
`ordnode.valid'.balance_l_aux` show very intricate assumptions on the sizes,
which may need to be revised if it turns out some operations violate these assumptions,
because there is a decent amount of slop in the actual data structure invariants, so the
theorem will go through with multiple choices of assumption.
**Note:** This file is incomplete, in the sense that the intent is to have verified
versions and lemmas about all the definitions in `ordnode.lean`, but at the moment only
a few operations are verified (the hard part should be out of the way, but still).
Contributors are encouraged to pick this up and finish the job, if it appeals to you.
## Tags
ordered map, ordered set, data structure, verified programming
-/
variable {Ξ± : Type*}
namespace ordnode
/-! ### delta and ratio -/
theorem not_le_delta {s} (H : 1 β€ s) : Β¬ s β€ delta * 0 :=
not_le_of_gt H
theorem delta_lt_false {a b : β}
(hβ : delta * a < b) (hβ : delta * b < a) : false :=
not_le_of_lt (lt_trans ((mul_lt_mul_left dec_trivial).2 hβ) hβ) $
by simpa [mul_assoc] using nat.mul_le_mul_right a (dec_trivial : 1 β€ delta * delta)
/-! ### `singleton` -/
/-! ### `size` and `empty` -/
/-- O(n). Computes the actual number of elements in the set, ignoring the cached `size` field. -/
def real_size : ordnode Ξ± β β
| nil := 0
| (node _ l _ r) := real_size l + real_size r + 1
/-! ### `sized` -/
/-- The `sized` property asserts that all the `size` fields in nodes match the actual size of the
respective subtrees. -/
def sized : ordnode Ξ± β Prop
| nil := true
| (node s l _ r) := s = size l + size r + 1 β§ sized l β§ sized r
theorem sized.node' {l x r} (hl : @sized Ξ± l) (hr : sized r) : sized (node' l x r) :=
β¨rfl, hl, hrβ©
theorem sized.eq_node' {s l x r} (h : @sized Ξ± (node s l x r)) : node s l x r = node' l x r :=
by rw h.1; refl
theorem sized.size_eq {s l x r} (H : sized (@node Ξ± s l x r)) :
size (@node Ξ± s l x r) = size l + size r + 1 := H.1
@[elab_as_eliminator] theorem sized.induction {t} (hl : @sized Ξ± t)
{C : ordnode Ξ± β Prop} (H0 : C nil)
(H1 : β l x r, C l β C r β C (node' l x r)) : C t :=
begin
induction t, {exact H0},
rw hl.eq_node',
exact H1 _ _ _ (t_ih_l hl.2.1) (t_ih_r hl.2.2)
end
theorem size_eq_real_size : β {t : ordnode Ξ±}, sized t β size t = real_size t
| nil _ := rfl
| (node s l x r) β¨hβ, hβ, hββ© :=
by rw [size, hβ, size_eq_real_size hβ, size_eq_real_size hβ]; refl
@[simp] theorem sized.size_eq_zero {t : ordnode Ξ±} (ht : sized t) : size t = 0 β t = nil :=
by cases t; [simp, simp [ht.1]]
theorem sized.pos {s l x r} (h : sized (@node Ξ± s l x r)) : 0 < s :=
by rw h.1; apply nat.le_add_left
/-! `dual` -/
theorem dual_dual : β (t : ordnode Ξ±), dual (dual t) = t
| nil := rfl
| (node s l x r) := by rw [dual, dual, dual_dual, dual_dual]
@[simp] theorem size_dual (t : ordnode Ξ±) : size (dual t) = size t :=
by cases t; refl
/-! `balanced` -/
/-- The `balanced_sz l r` asserts that a hypothetical tree with children of sizes `l` and `r` is
balanced: either `l β€ Ξ΄ * r` and `r β€ Ξ΄ * r`, or the tree is trivial with a singleton on one side
and nothing on the other. -/
def balanced_sz (l r : β) : Prop :=
l + r β€ 1 β¨ (l β€ delta * r β§ r β€ delta * l)
instance balanced_sz.dec : decidable_rel balanced_sz := Ξ» l r, or.decidable
/-- The `balanced t` asserts that the tree `t` satisfies the balance invariants
(at every level). -/
def balanced : ordnode Ξ± β Prop
| nil := true
| (node _ l _ r) := balanced_sz (size l) (size r) β§ balanced l β§ balanced r
instance balanced.dec : decidable_pred (@balanced Ξ±) | t :=
by induction t; unfold balanced; resetI; apply_instance
theorem balanced_sz.symm {l r : β} : balanced_sz l r β balanced_sz r l :=
or.imp (by rw add_comm; exact id) and.symm
theorem balanced_sz_zero {l : β} : balanced_sz l 0 β l β€ 1 :=
by simp [balanced_sz] { contextual := tt }
theorem balanced_sz_up {l rβ rβ : β} (hβ : rβ β€ rβ)
(hβ : l + rβ β€ 1 β¨ rβ β€ delta * l)
(H : balanced_sz l rβ) : balanced_sz l rβ :=
begin
refine or_iff_not_imp_left.2 (Ξ» h, _),
refine β¨_, hβ.resolve_left hβ©,
cases H,
{ cases rβ,
{ cases h (le_trans (nat.add_le_add_left (nat.zero_le _) _) H) },
{ exact le_trans (le_trans (nat.le_add_right _ _) H) (nat.le_add_left 1 _) } },
{ exact le_trans H.1 (nat.mul_le_mul_left _ hβ) }
end
theorem balanced_sz_down {l rβ rβ : β} (hβ : rβ β€ rβ)
(hβ : l + rβ β€ 1 β¨ l β€ delta * rβ)
(H : balanced_sz l rβ) : balanced_sz l rβ :=
have l + rβ β€ 1 β balanced_sz l rβ, from
Ξ» H, or.inl (le_trans (nat.add_le_add_left hβ _) H),
or.cases_on H this (Ξ» H, or.cases_on hβ this (Ξ» hβ,
or.inr β¨hβ, le_trans hβ H.2β©))
theorem balanced.dual : β {t : ordnode Ξ±}, balanced t β balanced (dual t)
| nil h := β¨β©
| (node s l x r) β¨b, bl, brβ© :=
β¨by rw [size_dual, size_dual]; exact b.symm, br.dual, bl.dualβ©
/-! ### `rotate` and `balance` -/
/-- Build a tree from three nodes, left associated (ignores the invariants). -/
def node3_l (l : ordnode Ξ±) (x : Ξ±) (m : ordnode Ξ±) (y : Ξ±) (r : ordnode Ξ±) : ordnode Ξ± :=
node' (node' l x m) y r
/-- Build a tree from three nodes, right associated (ignores the invariants). -/
def node3_r (l : ordnode Ξ±) (x : Ξ±) (m : ordnode Ξ±) (y : Ξ±) (r : ordnode Ξ±) : ordnode Ξ± :=
node' l x (node' m y r)
/-- Build a tree from three nodes, with `a () b -> (a ()) b` and `a (b c) d -> ((a b) (c d))`. -/
def node4_l : ordnode Ξ± β Ξ± β ordnode Ξ± β Ξ± β ordnode Ξ± β ordnode Ξ±
| l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r)
| l x nil z r := node3_l l x nil z r -- should not happen
/-- Build a tree from three nodes, with `a () b -> a (() b)` and `a (b c) d -> ((a b) (c d))`. -/
def node4_r : ordnode Ξ± β Ξ± β ordnode Ξ± β Ξ± β ordnode Ξ± β ordnode Ξ±
| l x (node _ ml y mr) z r := node' (node' l x ml) y (node' mr z r)
| l x nil z r := node3_r l x nil z r -- should not happen
/-- Concatenate two nodes, performing a left rotation `x (y z) -> ((x y) z)`
if balance is upset. -/
def rotate_l : ordnode Ξ± β Ξ± β ordnode Ξ± β ordnode Ξ±
| l x (node _ m y r) :=
if size m < ratio * size r then node3_l l x m y r else node4_l l x m y r
| l x nil := node' l x nil -- should not happen
/-- Concatenate two nodes, performing a right rotation `(x y) z -> (x (y z))`
if balance is upset. -/
def rotate_r : ordnode Ξ± β Ξ± β ordnode Ξ± β ordnode Ξ±
| (node _ l x m) y r :=
if size m < ratio * size l then node3_r l x m y r else node4_r l x m y r
| nil y r := node' nil y r -- should not happen
/-- A left balance operation. This will rebalance a concatenation, assuming the original nodes are
not too far from balanced. -/
def balance_l' (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) : ordnode Ξ± :=
if size l + size r β€ 1 then node' l x r else
if size l > delta * size r then rotate_r l x r else
node' l x r
/-- A right balance operation. This will rebalance a concatenation, assuming the original nodes are
not too far from balanced. -/
def balance_r' (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) : ordnode Ξ± :=
if size l + size r β€ 1 then node' l x r else
if size r > delta * size l then rotate_l l x r else
node' l x r
/-- The full balance operation. This is the same as `balance`, but with less manual inlining.
It is somewhat easier to work with this version in proofs. -/
def balance' (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) : ordnode Ξ± :=
if size l + size r β€ 1 then node' l x r else
if size r > delta * size l then rotate_l l x r else
if size l > delta * size r then rotate_r l x r else
node' l x r
theorem dual_node' (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) :
dual (node' l x r) = node' (dual r) x (dual l) := by simp [node', add_comm]
theorem dual_node3_l (l : ordnode Ξ±) (x : Ξ±) (m : ordnode Ξ±) (y : Ξ±) (r : ordnode Ξ±) :
dual (node3_l l x m y r) = node3_r (dual r) y (dual m) x (dual l) :=
by simp [node3_l, node3_r, dual_node']
theorem dual_node3_r (l : ordnode Ξ±) (x : Ξ±) (m : ordnode Ξ±) (y : Ξ±) (r : ordnode Ξ±) :
dual (node3_r l x m y r) = node3_l (dual r) y (dual m) x (dual l) :=
by simp [node3_l, node3_r, dual_node']
theorem dual_node4_l (l : ordnode Ξ±) (x : Ξ±) (m : ordnode Ξ±) (y : Ξ±) (r : ordnode Ξ±) :
dual (node4_l l x m y r) = node4_r (dual r) y (dual m) x (dual l) :=
by cases m; simp [node4_l, node4_r, dual_node3_l, dual_node']
theorem dual_node4_r (l : ordnode Ξ±) (x : Ξ±) (m : ordnode Ξ±) (y : Ξ±) (r : ordnode Ξ±) :
dual (node4_r l x m y r) = node4_l (dual r) y (dual m) x (dual l) :=
by cases m; simp [node4_l, node4_r, dual_node3_r, dual_node']
theorem dual_rotate_l (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) :
dual (rotate_l l x r) = rotate_r (dual r) x (dual l) :=
by cases r; simp [rotate_l, rotate_r, dual_node'];
split_ifs; simp [dual_node3_l, dual_node4_l]
theorem dual_rotate_r (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) :
dual (rotate_r l x r) = rotate_l (dual r) x (dual l) :=
by rw [β dual_dual (rotate_l _ _ _), dual_rotate_l, dual_dual, dual_dual]
theorem dual_balance' (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) :
dual (balance' l x r) = balance' (dual r) x (dual l) :=
begin
simp [balance', add_comm], split_ifs; simp [dual_node', dual_rotate_l, dual_rotate_r],
cases delta_lt_false h_1 h_2
end
theorem dual_balance_l (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) :
dual (balance_l l x r) = balance_r (dual r) x (dual l) :=
begin
unfold balance_l balance_r,
cases r with rs rl rx rr,
{ cases l with ls ll lx lr, {refl},
cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr;
dsimp only [dual]; try {refl},
split_ifs; repeat {simp [h, add_comm]} },
{ cases l with ls ll lx lr, {refl},
dsimp only [dual],
split_ifs, swap, {simp [add_comm]},
cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr; try {refl},
dsimp only [dual],
split_ifs; simp [h, add_comm] },
end
theorem dual_balance_r (l : ordnode Ξ±) (x : Ξ±) (r : ordnode Ξ±) :
dual (balance_r l x r) = balance_l (dual r) x (dual l) :=
by rw [β dual_dual (balance_l _ _ _), dual_balance_l, dual_dual, dual_dual]
theorem sized.node3_l {l x m y r}
(hl : @sized Ξ± l) (hm : sized m) (hr : sized r) : sized (node3_l l x m y r) :=
(hl.node' hm).node' hr
theorem sized.node3_r {l x m y r}
(hl : @sized Ξ± l) (hm : sized m) (hr : sized r) : sized (node3_r l x m y r) :=
hl.node' (hm.node' hr)
theorem sized.node4_l {l x m y r}
(hl : @sized Ξ± l) (hm : sized m) (hr : sized r) : sized (node4_l l x m y r) :=
by cases m; [exact (hl.node' hm).node' hr,
exact (hl.node' hm.2.1).node' (hm.2.2.node' hr)]
theorem node3_l_size {l x m y r} :
size (@node3_l Ξ± l x m y r) = size l + size m + size r + 2 :=
by dsimp [node3_l, node', size]; rw add_right_comm _ 1
theorem node3_r_size {l x m y r} :
size (@node3_r Ξ± l x m y r) = size l + size m + size r + 2 :=
by dsimp [node3_r, node', size]; rw [β add_assoc, β add_assoc]
theorem node4_l_size {l x m y r} (hm : sized m) :
size (@node4_l Ξ± l x m y r) = size l + size m + size r + 2 :=
by cases m; simp [node4_l, node3_l, node', add_comm, add_left_comm]; [skip, simp [size, hm.1]];
rw [β add_assoc, β bit0]; simp [add_comm, add_left_comm]
theorem sized.dual : β {t : ordnode Ξ±} (h : sized t), sized (dual t)
| nil h := β¨β©
| (node s l x r) β¨rfl, sl, srβ© := β¨by simp [size_dual, add_comm], sized.dual sr, sized.dual slβ©
theorem sized.dual_iff {t : ordnode Ξ±} : sized (dual t) β sized t :=
β¨Ξ» h, by rw β dual_dual t; exact h.dual, sized.dualβ©
theorem sized.rotate_l {l x r} (hl : @sized Ξ± l) (hr : sized r) : sized (rotate_l l x r) :=
begin
cases r, {exact hl.node' hr},
rw rotate_l, split_ifs,
{ exact hl.node3_l hr.2.1 hr.2.2 },
{ exact hl.node4_l hr.2.1 hr.2.2 }
end
theorem sized.rotate_r {l x r} (hl : @sized Ξ± l) (hr : sized r) : sized (rotate_r l x r) :=
sized.dual_iff.1 $ by rw dual_rotate_r; exact hr.dual.rotate_l hl.dual
theorem sized.rotate_l_size {l x r} (hm : sized r) :
size (@rotate_l Ξ± l x r) = size l + size r + 1 :=
begin
cases r; simp [rotate_l],
simp [size, hm.1, add_comm, add_left_comm], rw [β add_assoc, β bit0], simp,
split_ifs; simp [node3_l_size, node4_l_size hm.2.1, add_comm, add_left_comm]
end
theorem sized.rotate_r_size {l x r} (hl : sized l) :
size (@rotate_r Ξ± l x r) = size l + size r + 1 :=
by rw [β size_dual, dual_rotate_r, hl.dual.rotate_l_size,
size_dual, size_dual, add_comm (size l)]
theorem sized.balance' {l x r} (hl : @sized Ξ± l) (hr : sized r) : sized (balance' l x r) :=
begin
unfold balance', split_ifs,
{ exact hl.node' hr },
{ exact hl.rotate_l hr },
{ exact hl.rotate_r hr },
{ exact hl.node' hr }
end
theorem size_balance' {l x r} (hl : @sized Ξ± l) (hr : sized r) :
size (@balance' Ξ± l x r) = size l + size r + 1 :=
begin
unfold balance', split_ifs,
{ refl },
{ exact hr.rotate_l_size },
{ exact hl.rotate_r_size },
{ refl }
end
/-! ## `all`, `any`, `emem`, `amem` -/
theorem all.imp {P Q : Ξ± β Prop} (H : β a, P a β Q a) : β {t}, all P t β all Q t
| nil h := β¨β©
| (node _ l x r) β¨hβ, hβ, hββ© := β¨hβ.imp, H _ hβ, hβ.impβ©
theorem any.imp {P Q : Ξ± β Prop} (H : β a, P a β Q a) : β {t}, any P t β any Q t
| nil := id
| (node _ l x r) := or.imp any.imp $ or.imp (H _) any.imp
theorem all_singleton {P : Ξ± β Prop} {x : Ξ±} : all P (singleton x) β P x :=
β¨Ξ» h, h.2.1, Ξ» h, β¨β¨β©, h, β¨β©β©β©
theorem any_singleton {P : Ξ± β Prop} {x : Ξ±} : any P (singleton x) β P x :=
β¨by rintro (β¨β¨β©β© | h | β¨β¨β©β©); exact h, Ξ» h, or.inr (or.inl h)β©
theorem all_dual {P : Ξ± β Prop} : β {t : ordnode Ξ±},
all P (dual t) β all P t
| nil := iff.rfl
| (node s l x r) :=
β¨Ξ» β¨hr, hx, hlβ©, β¨all_dual.1 hl, hx, all_dual.1 hrβ©,
Ξ» β¨hl, hx, hrβ©, β¨all_dual.2 hr, hx, all_dual.2 hlβ©β©
theorem all_iff_forall {P : Ξ± β Prop} : β {t}, all P t β β x, emem x t β P x
| nil := (iff_true_intro $ by rintro _ β¨β©).symm
| (node _ l x r) :=
by simp [all, emem, all_iff_forall, any, or_imp_distrib, forall_and_distrib]
theorem any_iff_exists {P : Ξ± β Prop} : β {t}, any P t β β x, emem x t β§ P x
| nil := β¨by rintro β¨β©, by rintro β¨_, β¨β©, _β©β©
| (node _ l x r) :=
by simp [any, emem, any_iff_exists, or_and_distrib_right, exists_or_distrib]
theorem emem_iff_all {x : Ξ±} {t} : emem x t β β P, all P t β P x :=
β¨Ξ» h P al, all_iff_forall.1 al _ h,
Ξ» H, H _ $ all_iff_forall.2 $ Ξ» _, idβ©
theorem all_node' {P l x r} :
@all Ξ± P (node' l x r) β all P l β§ P x β§ all P r := iff.rfl
theorem all_node3_l {P l x m y r} :
@all Ξ± P (node3_l l x m y r) β all P l β§ P x β§ all P m β§ P y β§ all P r :=
by simp [node3_l, all_node', and_assoc]
theorem all_node3_r {P l x m y r} :
@all Ξ± P (node3_r l x m y r) β all P l β§ P x β§ all P m β§ P y β§ all P r := iff.rfl
theorem all_node4_l {P l x m y r} :
@all Ξ± P (node4_l l x m y r) β all P l β§ P x β§ all P m β§ P y β§ all P r :=
by cases m; simp [node4_l, all_node', all, all_node3_l, and_assoc]
theorem all_node4_r {P l x m y r} :
@all Ξ± P (node4_r l x m y r) β all P l β§ P x β§ all P m β§ P y β§ all P r :=
by cases m; simp [node4_r, all_node', all, all_node3_r, and_assoc]
theorem all_rotate_l {P l x r} :
@all Ξ± P (rotate_l l x r) β all P l β§ P x β§ all P r :=
by cases r; simp [rotate_l, all_node'];
split_ifs; simp [all_node3_l, all_node4_l, all]
theorem all_rotate_r {P l x r} :
@all Ξ± P (rotate_r l x r) β all P l β§ P x β§ all P r :=
by rw [β all_dual, dual_rotate_r, all_rotate_l];
simp [all_dual, and_comm, and.left_comm]
theorem all_balance' {P l x r} :
@all Ξ± P (balance' l x r) β all P l β§ P x β§ all P r :=
by rw balance'; split_ifs; simp [all_node', all_rotate_l, all_rotate_r]
/-! ### `to_list` -/
theorem foldr_cons_eq_to_list : β (t : ordnode Ξ±) (r : list Ξ±),
t.foldr list.cons r = to_list t ++ r
| nil r := rfl
| (node _ l x r) r' := by rw [foldr, foldr_cons_eq_to_list, foldr_cons_eq_to_list,
β list.cons_append, β list.append_assoc, β foldr_cons_eq_to_list]; refl
@[simp] theorem to_list_nil : to_list (@nil Ξ±) = [] := rfl
@[simp] theorem to_list_node (s l x r) : to_list (@node Ξ± s l x r) = to_list l ++ x :: to_list r :=
by rw [to_list, foldr, foldr_cons_eq_to_list]; refl
theorem emem_iff_mem_to_list {x : Ξ±} {t} : emem x t β x β to_list t :=
by unfold emem; induction t; simp [any, *, or_assoc]
theorem length_to_list' : β t : ordnode Ξ±, (to_list t).length = t.real_size
| nil := rfl
| (node _ l _ r) := by rw [to_list_node, list.length_append, list.length_cons,
length_to_list', length_to_list']; refl
theorem length_to_list {t : ordnode Ξ±} (h : sized t) : (to_list t).length = t.size :=
by rw [length_to_list', size_eq_real_size h]
theorem equiv_iff {tβ tβ : ordnode Ξ±} (hβ : sized tβ) (hβ : sized tβ) :
equiv tβ tβ β to_list tβ = to_list tβ :=
and_iff_right_of_imp $ Ξ» h, by rw [β length_to_list hβ, h, length_to_list hβ]
/-! ### `mem` -/
theorem pos_size_of_mem [has_le Ξ±] [@decidable_rel Ξ± (β€)]
{x : Ξ±} {t : ordnode Ξ±} (h : sized t) (h_mem : x β t) : 0 < size t :=
by { cases t, { contradiction }, { simp [h.1] } }
/-! ### `(find/erase/split)_(min/max)` -/
theorem find_min'_dual : β t (x : Ξ±), find_min' (dual t) x = find_max' x t
| nil x := rfl
| (node _ l x r) _ := find_min'_dual r x
theorem find_max'_dual (t) (x : Ξ±) : find_max' x (dual t) = find_min' t x :=
by rw [β find_min'_dual, dual_dual]
theorem find_min_dual : β t : ordnode Ξ±, find_min (dual t) = find_max t
| nil := rfl
| (node _ l x r) := congr_arg some $ find_min'_dual _ _
theorem find_max_dual (t : ordnode Ξ±) : find_max (dual t) = find_min t :=
by rw [β find_min_dual, dual_dual]
theorem dual_erase_min : β t : ordnode Ξ±, dual (erase_min t) = erase_max (dual t)
| nil := rfl
| (node _ nil x r) := rfl
| (node _ l@(node _ _ _ _) x r) :=
by rw [erase_min, dual_balance_r, dual_erase_min, dual, dual, dual, erase_max]
theorem dual_erase_max (t : ordnode Ξ±) : dual (erase_max t) = erase_min (dual t) :=
by rw [β dual_dual (erase_min _), dual_erase_min, dual_dual]
theorem split_min_eq : β s l (x : Ξ±) r,
split_min' l x r = (find_min' l x, erase_min (node s l x r))
| _ nil x r := rfl
| _ (node ls ll lx lr) x r :=
by rw [split_min', split_min_eq, split_min', find_min', erase_min]
theorem split_max_eq : β s l (x : Ξ±) r,
split_max' l x r = (erase_max (node s l x r), find_max' x r)
| _ l x nil := rfl
| _ l x (node ls ll lx lr) :=
by rw [split_max', split_max_eq, split_max', find_max', erase_max]
@[elab_as_eliminator]
theorem find_min'_all {P : Ξ± β Prop} : β t (x : Ξ±), all P t β P x β P (find_min' t x)
| nil x h hx := hx
| (node _ ll lx lr) x β¨hβ, hβ, hββ© hx := find_min'_all _ _ hβ hβ
@[elab_as_eliminator]
theorem find_max'_all {P : Ξ± β Prop} : β (x : Ξ±) t, P x β all P t β P (find_max' x t)
| x nil hx h := hx
| x (node _ ll lx lr) hx β¨hβ, hβ, hββ© := find_max'_all _ _ hβ hβ
/-! ### `glue` -/
/-! ### `merge` -/
@[simp] theorem merge_nil_left (t : ordnode Ξ±) : merge t nil = t := by cases t; refl
@[simp] theorem merge_nil_right (t : ordnode Ξ±) : merge nil t = t := rfl
@[simp] theorem merge_node {ls ll lx lr rs rl rx rr} :
merge (@node Ξ± ls ll lx lr) (node rs rl rx rr) =
if delta * ls < rs then
balance_l (merge (node ls ll lx lr) rl) rx rr
else if delta * rs < ls then
balance_r ll lx (merge lr (node rs rl rx rr))
else glue (node ls ll lx lr) (node rs rl rx rr) := rfl
/-! ### `insert` -/
theorem dual_insert [preorder Ξ±] [is_total Ξ± (β€)] [@decidable_rel Ξ± (β€)] (x : Ξ±) :
β t : ordnode Ξ±, dual (ordnode.insert x t) = @ordnode.insert Ξ±α΅α΅ _ _ x (dual t)
| nil := rfl
| (node _ l y r) := begin
rw [ordnode.insert, dual, ordnode.insert, order_dual.cmp_le_flip, β cmp_le_swap x y],
cases cmp_le x y;
simp [ordering.swap, ordnode.insert, dual_balance_l, dual_balance_r, dual_insert]
end
/-! ### `balance` properties -/
theorem balance_eq_balance' {l x r}
(hl : balanced l) (hr : balanced r)
(sl : sized l) (sr : sized r) :
@balance Ξ± l x r = balance' l x r :=
begin
cases l with ls ll lx lr,
{ cases r with rs rl rx rr,
{ refl },
{ rw sr.eq_node' at hr β’,
cases rl with rls rll rlx rlr; cases rr with rrs rrl rrx rrr;
dsimp [balance, balance'],
{ refl },
{ have : size rrl = 0 β§ size rrr = 0,
{ have := balanced_sz_zero.1 hr.1.symm,
rwa [size, sr.2.2.1, nat.succ_le_succ_iff,
nat.le_zero_iff, add_eq_zero_iff] at this },
cases sr.2.2.2.1.size_eq_zero.1 this.1,
cases sr.2.2.2.2.size_eq_zero.1 this.2,
obtain rfl : rrs = 1 := sr.2.2.1,
rw [if_neg, if_pos, rotate_l, if_pos], {refl},
all_goals {exact dec_trivial} },
{ have : size rll = 0 β§ size rlr = 0,
{ have := balanced_sz_zero.1 hr.1,
rwa [size, sr.2.1.1, nat.succ_le_succ_iff,
nat.le_zero_iff, add_eq_zero_iff] at this },
cases sr.2.1.2.1.size_eq_zero.1 this.1,
cases sr.2.1.2.2.size_eq_zero.1 this.2,
obtain rfl : rls = 1 := sr.2.1.1,
rw [if_neg, if_pos, rotate_l, if_neg], {refl},
all_goals {exact dec_trivial} },
{ symmetry, rw [zero_add, if_neg, if_pos, rotate_l],
{ split_ifs,
{ simp [node3_l, node', add_comm, add_left_comm] },
{ simp [node4_l, node', sr.2.1.1, add_comm, add_left_comm] } },
{ exact dec_trivial },
{ exact not_le_of_gt (nat.succ_lt_succ
(add_pos sr.2.1.pos sr.2.2.pos)) } } } },
{ cases r with rs rl rx rr,
{ rw sl.eq_node' at hl β’,
cases ll with lls lll llx llr; cases lr with lrs lrl lrx lrr;
dsimp [balance, balance'],
{ refl },
{ have : size lrl = 0 β§ size lrr = 0,
{ have := balanced_sz_zero.1 hl.1.symm,
rwa [size, sl.2.2.1, nat.succ_le_succ_iff,
nat.le_zero_iff, add_eq_zero_iff] at this },
cases sl.2.2.2.1.size_eq_zero.1 this.1,
cases sl.2.2.2.2.size_eq_zero.1 this.2,
obtain rfl : lrs = 1 := sl.2.2.1,
rw [if_neg, if_neg, if_pos, rotate_r, if_neg], {refl},
all_goals {exact dec_trivial} },
{ have : size lll = 0 β§ size llr = 0,
{ have := balanced_sz_zero.1 hl.1,
rwa [size, sl.2.1.1, nat.succ_le_succ_iff,
nat.le_zero_iff, add_eq_zero_iff] at this },
cases sl.2.1.2.1.size_eq_zero.1 this.1,
cases sl.2.1.2.2.size_eq_zero.1 this.2,
obtain rfl : lls = 1 := sl.2.1.1,
rw [if_neg, if_neg, if_pos, rotate_r, if_pos], {refl},
all_goals {exact dec_trivial} },
{ symmetry, rw [if_neg, if_neg, if_pos, rotate_r],
{ split_ifs,
{ simp [node3_r, node', add_comm, add_left_comm] },
{ simp [node4_r, node', sl.2.2.1, add_comm, add_left_comm] } },
{ exact dec_trivial },
{ exact dec_trivial },
{ exact not_le_of_gt (nat.succ_lt_succ
(add_pos sl.2.1.pos sl.2.2.pos)) } } },
{ simp [balance, balance'],
symmetry, rw [if_neg],
{ split_ifs,
{ have rd : delta β€ size rl + size rr,
{ have := lt_of_le_of_lt (nat.mul_le_mul_left _ sl.pos) h,
rwa [sr.1, nat.lt_succ_iff] at this },
cases rl with rls rll rlx rlr,
{ rw [size, zero_add] at rd,
exact absurd (le_trans rd (balanced_sz_zero.1 hr.1.symm)) dec_trivial },
cases rr with rrs rrl rrx rrr,
{ exact absurd (le_trans rd (balanced_sz_zero.1 hr.1)) dec_trivial },
dsimp [rotate_l], split_ifs,
{ simp [node3_l, node', sr.1, add_comm, add_left_comm] },
{ simp [node4_l, node', sr.1, sr.2.1.1, add_comm, add_left_comm] } },
{ have ld : delta β€ size ll + size lr,
{ have := lt_of_le_of_lt (nat.mul_le_mul_left _ sr.pos) h_1,
rwa [sl.1, nat.lt_succ_iff] at this },
cases ll with lls lll llx llr,
{ rw [size, zero_add] at ld,
exact absurd (le_trans ld (balanced_sz_zero.1 hl.1.symm)) dec_trivial },
cases lr with lrs lrl lrx lrr,
{ exact absurd (le_trans ld (balanced_sz_zero.1 hl.1)) dec_trivial },
dsimp [rotate_r], split_ifs,
{ simp [node3_r, node', sl.1, add_comm, add_left_comm] },
{ simp [node4_r, node', sl.1, sl.2.2.1, add_comm, add_left_comm] } },
{ simp [node'] } },
{ exact not_le_of_gt (add_le_add sl.pos sr.pos : 2 β€ ls + rs) } } }
end
theorem balance_l_eq_balance {l x r}
(sl : sized l) (sr : sized r)
(H1 : size l = 0 β size r β€ 1)
(H2 : 1 β€ size l β 1 β€ size r β size r β€ delta * size l) :
@balance_l Ξ± l x r = balance l x r :=
begin
cases r with rs rl rx rr,
{ refl },
{ cases l with ls ll lx lr,
{ have : size rl = 0 β§ size rr = 0,
{ have := H1 rfl,
rwa [size, sr.1, nat.succ_le_succ_iff,
nat.le_zero_iff, add_eq_zero_iff] at this },
cases sr.2.1.size_eq_zero.1 this.1,
cases sr.2.2.size_eq_zero.1 this.2,
rw sr.eq_node', refl },
{ replace H2 : Β¬ rs > delta * ls := not_lt_of_le (H2 sl.pos sr.pos),
simp [balance_l, balance, H2]; split_ifs; simp [add_comm] } }
end
/-- `raised n m` means `m` is either equal or one up from `n`. -/
def raised (n m : β) : Prop := m = n β¨ m = n + 1
theorem raised_iff {n m} : raised n m β n β€ m β§ m β€ n + 1 :=
begin
split, rintro (rfl | rfl),
{ exact β¨le_rfl, nat.le_succ _β© },
{ exact β¨nat.le_succ _, le_rflβ© },
{ rintro β¨hβ, hββ©,
rcases eq_or_lt_of_le hβ with rfl | hβ,
{ exact or.inl rfl },
{ exact or.inr (le_antisymm hβ hβ) } }
end
theorem raised.dist_le {n m} (H : raised n m) : nat.dist n m β€ 1 :=
by cases raised_iff.1 H with H1 H2;
rwa [nat.dist_eq_sub_of_le H1, tsub_le_iff_left]
theorem raised.dist_le' {n m} (H : raised n m) : nat.dist m n β€ 1 :=
by rw nat.dist_comm; exact H.dist_le
theorem raised.add_left (k) {n m} (H : raised n m) : raised (k + n) (k + m) :=
begin
rcases H with rfl | rfl,
{ exact or.inl rfl },
{ exact or.inr rfl }
end
theorem raised.add_right (k) {n m} (H : raised n m) : raised (n + k) (m + k) :=
by rw [add_comm, add_comm m]; exact H.add_left _
theorem raised.right {l xβ xβ rβ rβ} (H : raised (size rβ) (size rβ)) :
raised (size (@node' Ξ± l xβ rβ)) (size (@node' Ξ± l xβ rβ)) :=
begin
dsimp [node', size], generalize_hyp : size rβ = m at H β’,
rcases H with rfl | rfl,
{ exact or.inl rfl },
{ exact or.inr rfl }
end
theorem balance_l_eq_balance' {l x r}
(hl : balanced l) (hr : balanced r)
(sl : sized l) (sr : sized r)
(H : (β l', raised l' (size l) β§ balanced_sz l' (size r)) β¨
(β r', raised (size r) r' β§ balanced_sz (size l) r')) :
@balance_l Ξ± l x r = balance' l x r :=
begin
rw [β balance_eq_balance' hl hr sl sr, balance_l_eq_balance sl sr],
{ intro l0, rw l0 at H,
rcases H with β¨_, β¨β¨β©β©|β¨β¨β©β©, Hβ© | β¨r', e, Hβ©,
{ exact balanced_sz_zero.1 H.symm },
exact le_trans (raised_iff.1 e).1 (balanced_sz_zero.1 H.symm) },
{ intros l1 r1,
rcases H with β¨l', e, H | β¨Hβ, Hββ©β© | β¨r', e, H | β¨Hβ, Hββ©β©,
{ exact le_trans (le_trans (nat.le_add_left _ _) H)
(mul_pos dec_trivial l1 : (0:β)<_) },
{ exact le_trans Hβ (nat.mul_le_mul_left _ (raised_iff.1 e).1) },
{ cases raised_iff.1 e, unfold delta, linarith },
{ exact le_trans (raised_iff.1 e).1 Hβ } }
end
theorem balance_sz_dual {l r}
(H : (β l', raised (@size Ξ± l) l' β§ balanced_sz l' (@size Ξ± r)) β¨
β r', raised r' (size r) β§ balanced_sz (size l) r') :
(β l', raised l' (size (dual r)) β§ balanced_sz l' (size (dual l))) β¨
β r', raised (size (dual l)) r' β§ balanced_sz (size (dual r)) r' :=
begin
rw [size_dual, size_dual],
exact H.symm.imp
(Exists.imp $ Ξ» _, and.imp_right balanced_sz.symm)
(Exists.imp $ Ξ» _, and.imp_right balanced_sz.symm)
end
theorem size_balance_l {l x r}
(hl : balanced l) (hr : balanced r)
(sl : sized l) (sr : sized r)
(H : (β l', raised l' (size l) β§ balanced_sz l' (size r)) β¨
(β r', raised (size r) r' β§ balanced_sz (size l) r')) :
size (@balance_l Ξ± l x r) = size l + size r + 1 :=
by rw [balance_l_eq_balance' hl hr sl sr H, size_balance' sl sr]
theorem all_balance_l {P l x r}
(hl : balanced l) (hr : balanced r)
(sl : sized l) (sr : sized r)
(H : (β l', raised l' (size l) β§ balanced_sz l' (size r)) β¨
(β r', raised (size r) r' β§ balanced_sz (size l) r')) :
all P (@balance_l Ξ± l x r) β all P l β§ P x β§ all P r :=
by rw [balance_l_eq_balance' hl hr sl sr H, all_balance']
theorem balance_r_eq_balance' {l x r}
(hl : balanced l) (hr : balanced r)
(sl : sized l) (sr : sized r)
(H : (β l', raised (size l) l' β§ balanced_sz l' (size r)) β¨
(β r', raised r' (size r) β§ balanced_sz (size l) r')) :
@balance_r Ξ± l x r = balance' l x r :=
by rw [β dual_dual (balance_r l x r), dual_balance_r,
balance_l_eq_balance' hr.dual hl.dual sr.dual sl.dual (balance_sz_dual H),
β dual_balance', dual_dual]
theorem size_balance_r {l x r}
(hl : balanced l) (hr : balanced r)
(sl : sized l) (sr : sized r)
(H : (β l', raised (size l) l' β§ balanced_sz l' (size r)) β¨
(β r', raised r' (size r) β§ balanced_sz (size l) r')) :
size (@balance_r Ξ± l x r) = size l + size r + 1 :=
by rw [balance_r_eq_balance' hl hr sl sr H, size_balance' sl sr]
theorem all_balance_r {P l x r}
(hl : balanced l) (hr : balanced r)
(sl : sized l) (sr : sized r)
(H : (β l', raised (size l) l' β§ balanced_sz l' (size r)) β¨
(β r', raised r' (size r) β§ balanced_sz (size l) r')) :
all P (@balance_r Ξ± l x r) β all P l β§ P x β§ all P r :=
by rw [balance_r_eq_balance' hl hr sl sr H, all_balance']
/-! ### `bounded` -/
section
variable [preorder Ξ±]
/-- `bounded t lo hi` says that every element `x β t` is in the range `lo < x < hi`, and also this
property holds recursively in subtrees, making the full tree a BST. The bounds can be set to
`lo = β₯` and `hi = β€` if we care only about the internal ordering constraints. -/
def bounded : ordnode Ξ± β with_bot Ξ± β with_top Ξ± β Prop
| nil (some a) (some b) := a < b
| nil _ _ := true
| (node _ l x r) oβ oβ := bounded l oβ βx β§ bounded r βx oβ
theorem bounded.dual : β {t : ordnode Ξ±} {oβ oβ} (h : bounded t oβ oβ),
@bounded Ξ±α΅α΅ _ (dual t) oβ oβ
| nil oβ oβ h := by cases oβ; cases oβ; try {trivial}; exact h
| (node s l x r) _ _ β¨ol, orβ© := β¨or.dual, ol.dualβ©
theorem bounded.dual_iff {t : ordnode Ξ±} {oβ oβ} :
bounded t oβ oβ β @bounded Ξ±α΅α΅ _ (dual t) oβ oβ :=
β¨bounded.dual, Ξ» h, by have := bounded.dual h;
rwa [dual_dual, order_dual.preorder.dual_dual] at thisβ©
theorem bounded.weak_left : β {t : ordnode Ξ±} {oβ oβ}, bounded t oβ oβ β bounded t β₯ oβ
| nil oβ oβ h := by cases oβ; try {trivial}; exact h
| (node s l x r) _ _ β¨ol, orβ© := β¨ol.weak_left, orβ©
theorem bounded.weak_right : β {t : ordnode Ξ±} {oβ oβ}, bounded t oβ oβ β bounded t oβ β€
| nil oβ oβ h := by cases oβ; try {trivial}; exact h
| (node s l x r) _ _ β¨ol, orβ© := β¨ol, or.weak_rightβ©
theorem bounded.weak {t : ordnode Ξ±} {oβ oβ} (h : bounded t oβ oβ) : bounded t β₯ β€ :=
h.weak_left.weak_right
theorem bounded.mono_left {x y : Ξ±} (xy : x β€ y) :
β {t : ordnode Ξ±} {o}, bounded t βy o β bounded t βx o
| nil none h := β¨β©
| nil (some z) h := lt_of_le_of_lt xy h
| (node s l z r) o β¨ol, orβ© := β¨ol.mono_left, orβ©
theorem bounded.mono_right {x y : Ξ±} (xy : x β€ y) :
β {t : ordnode Ξ±} {o}, bounded t o βx β bounded t o βy
| nil none h := β¨β©
| nil (some z) h := lt_of_lt_of_le h xy
| (node s l z r) o β¨ol, orβ© := β¨ol, or.mono_rightβ©
theorem bounded.to_lt : β {t : ordnode Ξ±} {x y : Ξ±}, bounded t x y β x < y
| nil x y h := h
| (node _ l y r) x z β¨hβ, hββ© := lt_trans hβ.to_lt hβ.to_lt
theorem bounded.to_nil {t : ordnode Ξ±} : β {oβ oβ}, bounded t oβ oβ β bounded nil oβ oβ
| none _ h := β¨β©
| (some _) none h := β¨β©
| (some x) (some y) h := h.to_lt
theorem bounded.trans_left {tβ tβ : ordnode Ξ±} {x : Ξ±} :
β {oβ oβ}, bounded tβ oβ βx β bounded tβ βx oβ β bounded tβ oβ oβ
| none oβ hβ hβ := hβ.weak_left
| (some y) oβ hβ hβ := hβ.mono_left (le_of_lt hβ.to_lt)
theorem bounded.trans_right {tβ tβ : ordnode Ξ±} {x : Ξ±} :
β {oβ oβ}, bounded tβ oβ βx β bounded tβ βx oβ β bounded tβ oβ oβ
| oβ none hβ hβ := hβ.weak_right
| oβ (some y) hβ hβ := hβ.mono_right (le_of_lt hβ.to_lt)
theorem bounded.mem_lt : β {t o} {x : Ξ±}, bounded t o βx β all (< x) t
| nil o x _ := β¨β©
| (node _ l y r) o x β¨hβ, hββ© :=
β¨hβ.mem_lt.imp (Ξ» z h, lt_trans h hβ.to_lt), hβ.to_lt, hβ.mem_ltβ©
theorem bounded.mem_gt : β {t o} {x : Ξ±}, bounded t βx o β all (> x) t
| nil o x _ := β¨β©
| (node _ l y r) o x β¨hβ, hββ© :=
β¨hβ.mem_gt, hβ.to_lt, hβ.mem_gt.imp (Ξ» z, lt_trans hβ.to_lt)β©
theorem bounded.of_lt : β {t oβ oβ} {x : Ξ±},
bounded t oβ oβ β bounded nil oβ βx β all (< x) t β bounded t oβ βx
| nil oβ oβ x _ hn _ := hn
| (node _ l y r) oβ oβ x β¨hβ, hββ© hn β¨alβ, alβ, alββ© := β¨hβ, hβ.of_lt alβ alββ©
theorem bounded.of_gt : β {t oβ oβ} {x : Ξ±},
bounded t oβ oβ β bounded nil βx oβ β all (> x) t β bounded t βx oβ
| nil oβ oβ x _ hn _ := hn
| (node _ l y r) oβ oβ x β¨hβ, hββ© hn β¨alβ, alβ, alββ© := β¨hβ.of_gt alβ alβ, hββ©
theorem bounded.to_sep {tβ tβ oβ oβ} {x : Ξ±}
(hβ : bounded tβ oβ βx) (hβ : bounded tβ βx oβ) : tβ.all (Ξ» y, tβ.all (Ξ» z : Ξ±, y < z)) :=
hβ.mem_lt.imp $ Ξ» y yx, hβ.mem_gt.imp $ Ξ» z xz, lt_trans yx xz
end
/-! ### `valid` -/
section
variable [preorder Ξ±]
/-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are
correct, the tree is balanced, and the elements of the tree are organized according to the
ordering. This version of `valid` also puts all elements in the tree in the interval `(lo, hi)`. -/
structure valid' (lo : with_bot Ξ±) (t : ordnode Ξ±) (hi : with_top Ξ±) : Prop :=
(ord : t.bounded lo hi)
(sz : t.sized)
(bal : t.balanced)
/-- The validity predicate for an `ordnode` subtree. This asserts that the `size` fields are
correct, the tree is balanced, and the elements of the tree are organized according to the
ordering. -/
def valid (t : ordnode Ξ±) : Prop := valid' β₯ t β€
theorem valid'.mono_left {x y : Ξ±} (xy : x β€ y)
{t : ordnode Ξ±} {o} (h : valid' βy t o) : valid' βx t o :=
β¨h.1.mono_left xy, h.2, h.3β©
theorem valid'.mono_right {x y : Ξ±} (xy : x β€ y)
{t : ordnode Ξ±} {o} (h : valid' o t βx) : valid' o t βy :=
β¨h.1.mono_right xy, h.2, h.3β©
theorem valid'.trans_left {tβ tβ : ordnode Ξ±} {x : Ξ±} {oβ oβ}
(h : bounded tβ oβ βx) (H : valid' βx tβ oβ) : valid' oβ tβ oβ :=
β¨h.trans_left H.1, H.2, H.3β©
theorem valid'.trans_right {tβ tβ : ordnode Ξ±} {x : Ξ±} {oβ oβ}
(H : valid' oβ tβ βx) (h : bounded tβ βx oβ) : valid' oβ tβ oβ :=
β¨H.1.trans_right h, H.2, H.3β©
theorem valid'.of_lt {t : ordnode Ξ±} {x : Ξ±} {oβ oβ}
(H : valid' oβ t oβ) (hβ : bounded nil oβ βx) (hβ : all (< x) t) : valid' oβ t βx :=
β¨H.1.of_lt hβ hβ, H.2, H.3β©
theorem valid'.of_gt {t : ordnode Ξ±} {x : Ξ±} {oβ oβ}
(H : valid' oβ t oβ) (hβ : bounded nil βx oβ) (hβ : all (> x) t) : valid' βx t oβ :=
β¨H.1.of_gt hβ hβ, H.2, H.3β©
theorem valid'.valid {t oβ oβ} (h : @valid' Ξ± _ oβ t oβ) : valid t := β¨h.1.weak, h.2, h.3β©
theorem valid'_nil {oβ oβ} (h : bounded nil oβ oβ) : valid' oβ (@nil Ξ±) oβ := β¨h, β¨β©, β¨β©β©
theorem valid_nil : valid (@nil Ξ±) := valid'_nil β¨β©
theorem valid'.node {s l x r oβ oβ}
(hl : valid' oβ l βx) (hr : valid' βx r oβ)
(H : balanced_sz (size l) (size r)) (hs : s = size l + size r + 1) :
valid' oβ (@node Ξ± s l x r) oβ :=
β¨β¨hl.1, hr.1β©, β¨hs, hl.2, hr.2β©, β¨H, hl.3, hr.3β©β©
theorem valid'.dual : β {t : ordnode Ξ±} {oβ oβ} (h : valid' oβ t oβ), @valid' Ξ±α΅α΅ _ oβ (dual t) oβ
| nil oβ oβ h := valid'_nil h.1.dual
| (node s l x r) oβ oβ β¨β¨ol, orβ©, β¨rfl, sl, srβ©, β¨b, bl, brβ©β© :=
let β¨ol', sl', bl'β© := valid'.dual β¨ol, sl, blβ©,
β¨or', sr', br'β© := valid'.dual β¨or, sr, brβ© in
β¨β¨or', ol'β©,
β¨by simp [size_dual, add_comm], sr', sl'β©,
β¨by rw [size_dual, size_dual]; exact b.symm, br', bl'β©β©
theorem valid'.dual_iff {t : ordnode Ξ±} {oβ oβ} : valid' oβ t oβ β @valid' Ξ±α΅α΅ _ oβ (dual t) oβ :=
β¨valid'.dual, Ξ» h, by have := valid'.dual h;
rwa [dual_dual, order_dual.preorder.dual_dual] at thisβ©
theorem valid.dual {t : ordnode Ξ±} : valid t β @valid Ξ±α΅α΅ _ (dual t) := valid'.dual
theorem valid.dual_iff {t : ordnode Ξ±} : valid t β @valid Ξ±α΅α΅ _ (dual t) := valid'.dual_iff
theorem valid'.left {s l x r oβ oβ} (H : valid' oβ (@node Ξ± s l x r) oβ) : valid' oβ l x :=
β¨H.1.1, H.2.2.1, H.3.2.1β©
theorem valid'.right {s l x r oβ oβ} (H : valid' oβ (@node Ξ± s l x r) oβ) : valid' βx r oβ :=
β¨H.1.2, H.2.2.2, H.3.2.2β©
theorem valid.left {s l x r} (H : valid (@node Ξ± s l x r)) : valid l := H.left.valid
theorem valid.right {s l x r} (H : valid (@node Ξ± s l x r)) : valid r := H.right.valid
theorem valid.size_eq {s l x r} (H : valid (@node Ξ± s l x r)) :
size (@node Ξ± s l x r) = size l + size r + 1 := H.2.1
theorem valid'.node' {l x r oβ oβ} (hl : valid' oβ l βx) (hr : valid' βx r oβ)
(H : balanced_sz (size l) (size r)) : valid' oβ (@node' Ξ± l x r) oβ :=
hl.node hr H rfl
theorem valid'_singleton {x : Ξ±} {oβ oβ}
(hβ : bounded nil oβ βx) (hβ : bounded nil βx oβ) : valid' oβ (singleton x : ordnode Ξ±) oβ :=
(valid'_nil hβ).node (valid'_nil hβ) (or.inl zero_le_one) rfl
theorem valid_singleton {x : Ξ±} : valid (singleton x : ordnode Ξ±) := valid'_singleton β¨β© β¨β©
theorem valid'.node3_l {l x m y r oβ oβ}
(hl : valid' oβ l βx) (hm : valid' βx m βy) (hr : valid' βy r oβ)
(H1 : balanced_sz (size l) (size m))
(H2 : balanced_sz (size l + size m + 1) (size r)) :
valid' oβ (@node3_l Ξ± l x m y r) oβ :=
(hl.node' hm H1).node' hr H2
theorem valid'.node3_r {l x m y r oβ oβ}
(hl : valid' oβ l βx) (hm : valid' βx m βy) (hr : valid' βy r oβ)
(H1 : balanced_sz (size l) (size m + size r + 1))
(H2 : balanced_sz (size m) (size r)) :
valid' oβ (@node3_r Ξ± l x m y r) oβ :=
hl.node' (hm.node' hr H2) H1
theorem valid'.node4_l_lemmaβ {a b c d : β}
(lrβ : 3 * (b + c + 1 + d) β€ 16 * a + 9)
(mrβ : b + c + 1 β€ 3 * d)
(mmβ : b β€ 3 * c) : b < 3 * a + 1 := by linarith
theorem valid'.node4_l_lemmaβ {b c d : β} (mrβ : b + c + 1 β€ 3 * d) : c β€ 3 * d := by linarith
theorem valid'.node4_l_lemmaβ {b c d : β}
(mrβ : 2 * d β€ b + c + 1)
(mmβ : b β€ 3 * c) : d β€ 3 * c := by linarith
theorem valid'.node4_l_lemmaβ {a b c d : β}
(lrβ : 3 * a β€ b + c + 1 + d)
(mrβ : b + c + 1 β€ 3 * d)
(mmβ : b β€ 3 * c) : a + b + 1 β€ 3 * (c + d + 1) := by linarith
theorem valid'.node4_l_lemmaβ
{a b c d : β}
(lrβ : 3 * (b + c + 1 + d) β€ 16 * a + 9)
(mrβ : 2 * d β€ b + c + 1)
(mmβ : c β€ 3 * b) : c + d + 1 β€ 3 * (a + b + 1) := by linarith
theorem valid'.node4_l {l x m y r oβ oβ}
(hl : valid' oβ l βx) (hm : valid' βx m βy) (hr : valid' βy r oβ)
(Hm : 0 < size m)
(H : (size l = 0 β§ size m = 1 β§ size r β€ 1) β¨
(0 < size l β§ ratio * size r β€ size m β§
delta * size l β€ size m + size r β§
3 * (size m + size r) β€ 16 * size l + 9 β§
size m β€ delta * size r)) :
valid' oβ (@node4_l Ξ± l x m y r) oβ :=
begin
cases m with s ml z mr, {cases Hm},
suffices : balanced_sz (size l) (size ml) β§
balanced_sz (size mr) (size r) β§
balanced_sz (size l + size ml + 1) (size mr + size r + 1),
from (valid'.node' (hl.node' hm.left this.1) (hm.right.node' hr this.2.1) this.2.2),
rcases H with β¨l0, m1, r0β© | β¨l0, mrβ, lrβ, lrβ, mrββ©,
{ rw [hm.2.size_eq, nat.succ_inj', add_eq_zero_iff] at m1,
rw [l0, m1.1, m1.2], rcases size r with _|_|_; exact dec_trivial },
{ cases nat.eq_zero_or_pos (size r) with r0 r0,
{ rw r0 at mrβ, cases not_le_of_lt Hm mrβ },
rw [hm.2.size_eq] at lrβ lrβ mrβ mrβ,
by_cases mm : size ml + size mr β€ 1,
{ have r1 := le_antisymm ((mul_le_mul_left dec_trivial).1
(le_trans mrβ (nat.succ_le_succ mm) : _ β€ ratio * 1)) r0,
rw [r1, add_assoc] at lrβ,
have l1 := le_antisymm ((mul_le_mul_left dec_trivial).1
(le_trans lrβ (add_le_add_right mm 2) : _ β€ delta * 1)) l0,
rw [l1, r1],
cases size ml; cases size mr,
{ exact dec_trivial },
{ rw zero_add at mm, rcases mm with _|β¨_,β¨β©β©,
exact dec_trivial },
{ rcases mm with _|β¨_,β¨β©β©, exact dec_trivial },
{ rw nat.succ_add at mm, rcases mm with _|β¨_,β¨β©β© } },
rcases hm.3.1.resolve_left mm with β¨mmβ, mmββ©,
cases nat.eq_zero_or_pos (size ml) with ml0 ml0,
{ rw [ml0, mul_zero, nat.le_zero_iff] at mmβ,
rw [ml0, mmβ] at mm, cases mm dec_trivial },
have : 2 * size l β€ size ml + size mr + 1,
{ have := nat.mul_le_mul_left _ lrβ,
rw [mul_left_comm, mul_add] at this,
have := le_trans this (add_le_add_left mrβ _),
rw [β nat.succ_mul] at this,
exact (mul_le_mul_left dec_trivial).1 this },
refine β¨or.inr β¨_, _β©, or.inr β¨_, _β©, or.inr β¨_, _β©β©,
{ refine (mul_le_mul_left dec_trivial).1 (le_trans this _),
rw [two_mul, nat.succ_le_iff],
refine add_lt_add_of_lt_of_le _ mmβ,
simpa using (mul_lt_mul_right ml0).2 (dec_trivial:1<3) },
{ exact nat.le_of_lt_succ (valid'.node4_l_lemmaβ lrβ mrβ mmβ) },
{ exact valid'.node4_l_lemmaβ mrβ },
{ exact valid'.node4_l_lemmaβ mrβ mmβ },
{ exact valid'.node4_l_lemmaβ lrβ mrβ mmβ },
{ exact valid'.node4_l_lemmaβ
lrβ mrβ mmβ } }
end
theorem valid'.rotate_l_lemmaβ {a b c : β}
(H2 : 3 * a β€ b + c) (hbβ : c β€ 3 * b) : a β€ 3 * b := by linarith
theorem valid'.rotate_l_lemmaβ {a b c : β}
(H3 : 2 * (b + c) β€ 9 * a + 3) (h : b < 2 * c) : b < 3 * a + 1 := by linarith
theorem valid'.rotate_l_lemmaβ {a b c : β}
(H2 : 3 * a β€ b + c) (h : b < 2 * c) : a + b < 3 * c := by linarith
theorem valid'.rotate_l_lemmaβ {a b : β}
(H3 : 2 * b β€ 9 * a + 3) : 3 * b β€ 16 * a + 9 := by linarith
theorem valid'.rotate_l {l x r oβ oβ} (hl : valid' oβ l βx) (hr : valid' βx r oβ)
(H1 : Β¬ size l + size r β€ 1)
(H2 : delta * size l < size r)
(H3 : 2 * size r β€ 9 * size l + 5 β¨ size r β€ 3) :
valid' oβ (@rotate_l Ξ± l x r) oβ :=
begin
cases r with rs rl rx rr, {cases H2},
rw [hr.2.size_eq, nat.lt_succ_iff] at H2,
rw [hr.2.size_eq] at H3,
replace H3 : 2 * (size rl + size rr) β€ 9 * size l + 3 β¨ size rl + size rr β€ 2 :=
H3.imp (@nat.le_of_add_le_add_right 2 _ _) nat.le_of_succ_le_succ,
have H3_0 : size l = 0 β size rl + size rr β€ 2,
{ intro l0, rw l0 at H3,
exact (or_iff_right_of_imp $ by exact Ξ» h,
(mul_le_mul_left dec_trivial).1 (le_trans h dec_trivial)).1 H3 },
have H3p : size l > 0 β 2 * (size rl + size rr) β€ 9 * size l + 3 :=
Ξ» l0 : 1 β€ size l, (or_iff_left_of_imp $ by intro; linarith).1 H3,
have ablem : β {a b : β}, 1 β€ a β a + b β€ 2 β b β€ 1, {intros, linarith},
have hlp : size l > 0 β Β¬ size rl + size rr β€ 1 := Ξ» l0 hb, absurd
(le_trans (le_trans (nat.mul_le_mul_left _ l0) H2) hb) dec_trivial,
rw rotate_l, split_ifs,
{ have rr0 : size rr > 0 := (mul_lt_mul_left dec_trivial).1
(lt_of_le_of_lt (nat.zero_le _) h : ratio * 0 < _),
suffices : balanced_sz (size l) (size rl) β§ balanced_sz (size l + size rl + 1) (size rr),
{ exact hl.node3_l hr.left hr.right this.1 this.2 },
cases nat.eq_zero_or_pos (size l) with l0 l0,
{ rw l0, replace H3 := H3_0 l0,
have := hr.3.1,
cases nat.eq_zero_or_pos (size rl) with rl0 rl0,
{ rw rl0 at this β’,
rw le_antisymm (balanced_sz_zero.1 this.symm) rr0,
exact dec_trivial },
have rr1 : size rr = 1 := le_antisymm (ablem rl0 H3) rr0,
rw add_comm at H3,
rw [rr1, show size rl = 1, from le_antisymm (ablem rr0 H3) rl0],
exact dec_trivial },
replace H3 := H3p l0,
rcases hr.3.1.resolve_left (hlp l0) with β¨hbβ, hbββ©,
refine β¨or.inr β¨_, _β©, or.inr β¨_, _β©β©,
{ exact valid'.rotate_l_lemmaβ H2 hbβ },
{ exact nat.le_of_lt_succ (valid'.rotate_l_lemmaβ H3 h) },
{ exact valid'.rotate_l_lemmaβ H2 h },
{ exact le_trans hbβ (nat.mul_le_mul_left _ $
le_trans (nat.le_add_left _ _) (nat.le_add_right _ _)) } },
{ cases nat.eq_zero_or_pos (size rl) with rl0 rl0,
{ rw [rl0, not_lt, nat.le_zero_iff, nat.mul_eq_zero] at h,
replace h := h.resolve_left dec_trivial,
rw [rl0, h, nat.le_zero_iff, nat.mul_eq_zero] at H2,
rw [hr.2.size_eq, rl0, h, H2.resolve_left dec_trivial] at H1,
cases H1 dec_trivial },
refine hl.node4_l hr.left hr.right rl0 _,
cases nat.eq_zero_or_pos (size l) with l0 l0,
{ replace H3 := H3_0 l0,
cases nat.eq_zero_or_pos (size rr) with rr0 rr0,
{ have := hr.3.1,
rw rr0 at this,
exact or.inl β¨l0,
le_antisymm (balanced_sz_zero.1 this) rl0,
rr0.symm βΈ zero_le_oneβ© },
exact or.inl β¨l0,
le_antisymm (ablem rr0 $ by rwa add_comm) rl0,
ablem rl0 H3β© },
exact or.inr β¨l0, not_lt.1 h, H2,
valid'.rotate_l_lemmaβ (H3p l0),
(hr.3.1.resolve_left (hlp l0)).1β© }
end
theorem valid'.rotate_r {l x r oβ oβ} (hl : valid' oβ l βx) (hr : valid' βx r oβ)
(H1 : Β¬ size l + size r β€ 1)
(H2 : delta * size r < size l)
(H3 : 2 * size l β€ 9 * size r + 5 β¨ size l β€ 3) :
valid' oβ (@rotate_r Ξ± l x r) oβ :=
begin
refine valid'.dual_iff.2 _,
rw dual_rotate_r,
refine hr.dual.rotate_l hl.dual _ _ _,
{ rwa [size_dual, size_dual, add_comm] },
{ rwa [size_dual, size_dual] },
{ rwa [size_dual, size_dual] }
end
theorem valid'.balance'_aux {l x r oβ oβ} (hl : valid' oβ l βx) (hr : valid' βx r oβ)
(Hβ : 2 * @size Ξ± r β€ 9 * size l + 5 β¨ size r β€ 3)
(Hβ : 2 * @size Ξ± l β€ 9 * size r + 5 β¨ size l β€ 3) :
valid' oβ (@balance' Ξ± l x r) oβ :=
begin
rw balance', split_ifs,
{ exact hl.node' hr (or.inl h) },
{ exact hl.rotate_l hr h h_1 Hβ },
{ exact hl.rotate_r hr h h_2 Hβ },
{ exact hl.node' hr (or.inr β¨not_lt.1 h_2, not_lt.1 h_1β©) }
end
theorem valid'.balance'_lemma {Ξ± l l' r r'}
(H1 : balanced_sz l' r')
(H2 : nat.dist (@size Ξ± l) l' β€ 1 β§ size r = r' β¨
nat.dist (size r) r' β€ 1 β§ size l = l') :
2 * @size Ξ± r β€ 9 * size l + 5 β¨ size r β€ 3 :=
begin
suffices : @size Ξ± r β€ 3 * (size l + 1),
{ cases nat.eq_zero_or_pos (size l) with l0 l0,
{ apply or.inr, rwa l0 at this },
change 1 β€ _ at l0, apply or.inl, linarith },
rcases H2 with β¨hl, rflβ© | β¨hr, rflβ©;
rcases H1 with h | β¨hβ, hββ©,
{ exact le_trans (nat.le_add_left _ _) (le_trans h (nat.le_add_left _ _)) },
{ exact le_trans hβ (nat.mul_le_mul_left _ $
le_trans (nat.dist_tri_right _ _) (nat.add_le_add_left hl _)) },
{ exact le_trans (nat.dist_tri_left' _ _)
(le_trans (add_le_add hr (le_trans (nat.le_add_left _ _) h)) dec_trivial) },
{ rw nat.mul_succ,
exact le_trans (nat.dist_tri_right' _ _)
(add_le_add hβ (le_trans hr dec_trivial)) },
end
theorem valid'.balance' {l x r oβ oβ} (hl : valid' oβ l βx) (hr : valid' βx r oβ)
(H : β l' r', balanced_sz l' r' β§
(nat.dist (size l) l' β€ 1 β§ size r = r' β¨
nat.dist (size r) r' β€ 1 β§ size l = l')) :
valid' oβ (@balance' Ξ± l x r) oβ :=
let β¨l', r', H1, H2β© := H in
valid'.balance'_aux hl hr (valid'.balance'_lemma H1 H2) (valid'.balance'_lemma H1.symm H2.symm)
theorem valid'.balance {l x r oβ oβ} (hl : valid' oβ l βx) (hr : valid' βx r oβ)
(H : β l' r', balanced_sz l' r' β§
(nat.dist (size l) l' β€ 1 β§ size r = r' β¨
nat.dist (size r) r' β€ 1 β§ size l = l')) :
valid' oβ (@balance Ξ± l x r) oβ :=
by rw balance_eq_balance' hl.3 hr.3 hl.2 hr.2; exact hl.balance' hr H
theorem valid'.balance_l_aux {l x r oβ oβ} (hl : valid' oβ l βx) (hr : valid' βx r oβ)
(Hβ : size l = 0 β size r β€ 1)
(Hβ : 1 β€ size l β 1 β€ size r β size r β€ delta * size l)
(Hβ : 2 * @size Ξ± l β€ 9 * size r + 5 β¨ size l β€ 3) :
valid' oβ (@balance_l Ξ± l x r) oβ :=
begin
rw [balance_l_eq_balance hl.2 hr.2 Hβ Hβ, balance_eq_balance' hl.3 hr.3 hl.2 hr.2],
refine hl.balance'_aux hr (or.inl _) Hβ,
cases nat.eq_zero_or_pos (size r) with r0 r0,
{ rw r0, exact nat.zero_le _ },
cases nat.eq_zero_or_pos (size l) with l0 l0,
{ rw l0, exact le_trans (nat.mul_le_mul_left _ (Hβ l0)) dec_trivial },
replace Hβ : _ β€ 3 * _ := Hβ l0 r0, linarith
end
theorem valid'.balance_l {l x r oβ oβ} (hl : valid' oβ l βx) (hr : valid' βx r oβ)
(H : (β l', raised l' (size l) β§ balanced_sz l' (size r)) β¨
(β r', raised (size r) r' β§ balanced_sz (size l) r')) :
valid' oβ (@balance_l Ξ± l x r) oβ :=
begin
rw balance_l_eq_balance' hl.3 hr.3 hl.2 hr.2 H,
refine hl.balance' hr _,
rcases H with β¨l', e, Hβ© | β¨r', e, Hβ©,
{ exact β¨_, _, H, or.inl β¨e.dist_le', rflβ©β© },
{ exact β¨_, _, H, or.inr β¨e.dist_le, rflβ©β© },
end
theorem valid'.balance_r_aux {l x r oβ oβ} (hl : valid' oβ l βx) (hr : valid' βx r oβ)
(Hβ : size r = 0 β size l β€ 1)
(Hβ : 1 β€ size r β 1 β€ size l β size l β€ delta * size r)
(Hβ : 2 * @size Ξ± r β€ 9 * size l + 5 β¨ size r β€ 3) :
valid' oβ (@balance_r Ξ± l x r) oβ :=
begin
rw [valid'.dual_iff, dual_balance_r],
have := hr.dual.balance_l_aux hl.dual,
rw [size_dual, size_dual] at this,
exact this Hβ Hβ Hβ
end
theorem valid'.balance_r {l x r oβ oβ} (hl : valid' oβ l βx) (hr : valid' βx r oβ)
(H : (β l', raised (size l) l' β§ balanced_sz l' (size r)) β¨
(β r', raised r' (size r) β§ balanced_sz (size l) r')) :
valid' oβ (@balance_r Ξ± l x r) oβ :=
by rw [valid'.dual_iff, dual_balance_r]; exact
hr.dual.balance_l hl.dual (balance_sz_dual H)
theorem valid'.erase_max_aux {s l x r oβ oβ}
(H : valid' oβ (node s l x r) oβ) :
valid' oβ (@erase_max Ξ± (node' l x r)) β(find_max' x r) β§
size (node' l x r) = size (erase_max (node' l x r)) + 1 :=
begin
have := H.2.eq_node', rw this at H, clear this,
induction r with rs rl rx rr IHrl IHrr generalizing l x oβ,
{ exact β¨H.left, rflβ© },
have := H.2.2.2.eq_node', rw this at H β’,
rcases IHrr H.right with β¨h, eβ©,
refine β¨valid'.balance_l H.left h (or.inr β¨_, or.inr e, H.3.1β©), _β©,
rw [erase_max, size_balance_l H.3.2.1 h.3 H.2.2.1 h.2 (or.inr β¨_, or.inr e, H.3.1β©)],
rw [size, e], refl
end
theorem valid'.erase_min_aux {s l x r oβ oβ}
(H : valid' oβ (node s l x r) oβ) :
valid' β(find_min' l x) (@erase_min Ξ± (node' l x r)) oβ β§
size (node' l x r) = size (erase_min (node' l x r)) + 1 :=
by have := H.dual.erase_max_aux;
rwa [β dual_node', size_dual, β dual_erase_min,
size_dual, β valid'.dual_iff, find_max'_dual] at this
theorem erase_min.valid : β {t} (h : @valid Ξ± _ t), valid (erase_min t)
| nil _ := valid_nil
| (node _ l x r) h := by rw h.2.eq_node'; exact h.erase_min_aux.1.valid
theorem erase_max.valid {t} (h : @valid Ξ± _ t) : valid (erase_max t) :=
by rw [valid.dual_iff, dual_erase_max]; exact erase_min.valid h.dual
theorem valid'.glue_aux {l r oβ oβ}
(hl : valid' oβ l oβ) (hr : valid' oβ r oβ)
(sep : l.all (Ξ» x, r.all (Ξ» y, x < y)))
(bal : balanced_sz (size l) (size r)) :
valid' oβ (@glue Ξ± l r) oβ β§ size (glue l r) = size l + size r :=
begin
cases l with ls ll lx lr, {exact β¨hr, (zero_add _).symmβ© },
cases r with rs rl rx rr, {exact β¨hl, rflβ© },
dsimp [glue], split_ifs,
{ rw [split_max_eq, glue],
cases valid'.erase_max_aux hl with v e,
suffices H,
refine β¨valid'.balance_r v (hr.of_gt _ _) H, _β©,
{ refine find_max'_all lx lr hl.1.2.to_nil (sep.2.2.imp _),
exact Ξ» x h, hr.1.2.to_nil.mono_left (le_of_lt h.2.1) },
{ exact @find_max'_all _ (Ξ» a, all (> a) (node rs rl rx rr)) lx lr sep.2.1 sep.2.2 },
{ rw [size_balance_r v.3 hr.3 v.2 hr.2 H, add_right_comm, β e, hl.2.1], refl },
{ refine or.inl β¨_, or.inr e, _β©,
rwa hl.2.eq_node' at bal } },
{ rw [split_min_eq, glue],
cases valid'.erase_min_aux hr with v e,
suffices H,
refine β¨valid'.balance_l (hl.of_lt _ _) v H, _β©,
{ refine @find_min'_all _ (Ξ» a, bounded nil oβ βa) rl rx (sep.2.1.1.imp _) hr.1.1.to_nil,
exact Ξ» y h, hl.1.1.to_nil.mono_right (le_of_lt h) },
{ exact @find_min'_all _ (Ξ» a, all (< a) (node ls ll lx lr)) rl rx
(all_iff_forall.2 $ Ξ» x hx, sep.imp $ Ξ» y hy, all_iff_forall.1 hy.1 _ hx)
(sep.imp $ Ξ» y hy, hy.2.1) },
{ rw [size_balance_l hl.3 v.3 hl.2 v.2 H, add_assoc, β e, hr.2.1], refl },
{ refine or.inr β¨_, or.inr e, _β©,
rwa hr.2.eq_node' at bal } },
end
theorem valid'.glue {l x r oβ oβ}
(hl : valid' oβ l β(x:Ξ±)) (hr : valid' βx r oβ) :
balanced_sz (size l) (size r) β
valid' oβ (@glue Ξ± l r) oβ β§ size (@glue Ξ± l r) = size l + size r :=
valid'.glue_aux (hl.trans_right hr.1) (hr.trans_left hl.1) (hl.1.to_sep hr.1)
theorem valid'.merge_lemma {a b c : β}
(hβ : 3 * a < b + c + 1) (hβ : b β€ 3 * c) : 2 * (a + b) β€ 9 * c + 5 :=
by linarith
theorem valid'.merge_auxβ {oβ oβ ls ll lx lr rs rl rx rr t}
(hl : valid' oβ (@node Ξ± ls ll lx lr) oβ)
(hr : valid' oβ (node rs rl rx rr) oβ)
(h : delta * ls < rs)
(v : valid' oβ t βrx)
(e : size t = ls + size rl) :
valid' oβ (balance_l t rx rr) oβ β§ size (balance_l t rx rr) = ls + rs :=
begin
rw hl.2.1 at e,
rw [hl.2.1, hr.2.1, delta] at h,
rcases hr.3.1 with H|β¨hrβ, hrββ©, {linarith},
suffices Hβ, suffices Hβ,
refine β¨valid'.balance_l_aux v hr.right Hβ Hβ _, _β©,
{ rw e, exact or.inl (valid'.merge_lemma h hrβ) },
{ rw [balance_l_eq_balance v.2 hr.2.2.2 Hβ Hβ, balance_eq_balance' v.3 hr.3.2.2 v.2 hr.2.2.2,
size_balance' v.2 hr.2.2.2, e, hl.2.1, hr.2.1], simp [add_comm, add_left_comm] },
{ rw [e, add_right_comm], rintro β¨β© },
{ intros _ hβ, rw e, unfold delta at hrβ β’, linarith }
end
theorem valid'.merge_aux {l r oβ oβ}
(hl : valid' oβ l oβ) (hr : valid' oβ r oβ)
(sep : l.all (Ξ» x, r.all (Ξ» y, x < y))) :
valid' oβ (@merge Ξ± l r) oβ β§ size (merge l r) = size l + size r :=
begin
induction l with ls ll lx lr IHll IHlr generalizing oβ oβ r,
{ exact β¨hr, (zero_add _).symmβ© },
induction r with rs rl rx rr IHrl IHrr generalizing oβ oβ,
{ exact β¨hl, rflβ© },
rw [merge_node], split_ifs,
{ cases IHrl (sep.imp $ Ξ» x h, h.1)
(hl.of_lt hr.1.1.to_nil $ sep.imp $ Ξ» x h, h.2.1) hr.left with v e,
exact valid'.merge_auxβ hl hr h v e },
{ cases IHlr hl.right (hr.of_gt hl.1.2.to_nil sep.2.1) sep.2.2 with v e,
have := valid'.merge_auxβ hr.dual hl.dual h_1 v.dual,
rw [size_dual, add_comm, size_dual,
β dual_balance_r, β valid'.dual_iff, size_dual, add_comm rs] at this,
exact this e },
{ refine valid'.glue_aux hl hr sep (or.inr β¨not_lt.1 h_1, not_lt.1 hβ©) }
end
theorem valid.merge {l r} (hl : valid l) (hr : valid r)
(sep : l.all (Ξ» x, r.all (Ξ» y, x < y))) : valid (@merge Ξ± l r) :=
(valid'.merge_aux hl hr sep).1
theorem insert_with.valid_aux [is_total Ξ± (β€)] [@decidable_rel Ξ± (β€)]
(f : Ξ± β Ξ±) (x : Ξ±) (hf : β y, x β€ y β§ y β€ x β x β€ f y β§ f y β€ x) : β {t oβ oβ},
valid' oβ t oβ β bounded nil oβ βx β bounded nil βx oβ β
valid' oβ (insert_with f x t) oβ β§
raised (size t) (size (insert_with f x t))
| nil oβ oβ _ bl br := β¨valid'_singleton bl br, or.inr rflβ©
| (node sz l y r) oβ oβ h bl br := begin
rw [insert_with, cmp_le],
split_ifs; rw [insert_with],
{ rcases h with β¨β¨lx, xrβ©, hs, hbβ©,
rcases hf _ β¨h_1, h_2β© with β¨xf, fxβ©,
refine β¨β¨β¨lx.mono_right (le_trans h_2 xf),
xr.mono_left (le_trans fx h_1)β©, hs, hbβ©, or.inl rflβ© },
{ rcases insert_with.valid_aux h.left bl (lt_of_le_not_le h_1 h_2) with β¨vl, eβ©,
suffices H,
{ refine β¨vl.balance_l h.right H, _β©,
rw [size_balance_l vl.3 h.3.2.2 vl.2 h.2.2.2 H, h.2.size_eq],
refine (e.add_right _).add_right _ },
{ exact or.inl β¨_, e, h.3.1β© } },
{ have : y < x := lt_of_le_not_le ((total_of (β€) _ _).resolve_left h_1) h_1,
rcases insert_with.valid_aux h.right this br with β¨vr, eβ©,
suffices H,
{ refine β¨h.left.balance_r vr H, _β©,
rw [size_balance_r h.3.2.1 vr.3 h.2.2.1 vr.2 H, h.2.size_eq],
refine (e.add_left _).add_right _ },
{ exact or.inr β¨_, e, h.3.1β© } },
end
theorem insert_with.valid [is_total Ξ± (β€)] [@decidable_rel Ξ± (β€)]
(f : Ξ± β Ξ±) (x : Ξ±) (hf : β y, x β€ y β§ y β€ x β x β€ f y β§ f y β€ x)
{t} (h : valid t) : valid (insert_with f x t) :=
(insert_with.valid_aux _ _ hf h β¨β© β¨β©).1
theorem insert_eq_insert_with [@decidable_rel Ξ± (β€)]
(x : Ξ±) : β t, ordnode.insert x t = insert_with (Ξ» _, x) x t
| nil := rfl
| (node _ l y r) := by unfold ordnode.insert insert_with;
cases cmp_le x y; unfold ordnode.insert insert_with; simp [insert_eq_insert_with]
theorem insert.valid [is_total Ξ± (β€)] [@decidable_rel Ξ± (β€)]
(x : Ξ±) {t} (h : valid t) : valid (ordnode.insert x t) :=
by rw insert_eq_insert_with; exact
insert_with.valid _ _ (Ξ» _ _, β¨le_rfl, le_rflβ©) h
theorem insert'_eq_insert_with [@decidable_rel Ξ± (β€)]
(x : Ξ±) : β t, insert' x t = insert_with id x t
| nil := rfl
| (node _ l y r) := by unfold insert' insert_with;
cases cmp_le x y; unfold insert' insert_with; simp [insert'_eq_insert_with]
theorem insert'.valid [is_total Ξ± (β€)] [@decidable_rel Ξ± (β€)]
(x : Ξ±) {t} (h : valid t) : valid (insert' x t) :=
by rw insert'_eq_insert_with; exact insert_with.valid _ _ (Ξ» _, id) h
theorem valid'.map_aux {Ξ²} [preorder Ξ²] {f : Ξ± β Ξ²} (f_strict_mono : strict_mono f)
{t aβ aβ} (h : valid' aβ t aβ) :
valid' (option.map f aβ) (map f t) (option.map f aβ) β§ (map f t).size = t.size :=
begin
induction t generalizing aβ aβ,
{ simp [map], apply valid'_nil,
cases aβ, { trivial },
cases aβ, { trivial },
simp [bounded],
exact f_strict_mono h.ord },
{ have t_ih_l' := t_ih_l h.left,
have t_ih_r' := t_ih_r h.right,
clear t_ih_l t_ih_r,
cases t_ih_l' with t_l_valid t_l_size,
cases t_ih_r' with t_r_valid t_r_size,
simp [map],
split,
{ exact and.intro t_l_valid.ord t_r_valid.ord },
{ repeat { split },
{ rw [t_l_size, t_r_size], exact h.sz.1 },
{ exact t_l_valid.sz },
{ exact t_r_valid.sz } },
{ repeat { split },
{ rw [t_l_size, t_r_size], exact h.bal.1 },
{ exact t_l_valid.bal },
{ exact t_r_valid.bal } } },
end
theorem map.valid {Ξ²} [preorder Ξ²] {f : Ξ± β Ξ²} (f_strict_mono : strict_mono f)
{t} (h : valid t) : valid (map f t) :=
(valid'.map_aux f_strict_mono h).1
theorem valid'.erase_aux [@decidable_rel Ξ± (β€)] (x : Ξ±) {t aβ aβ} (h : valid' aβ t aβ) :
valid' aβ (erase x t) aβ β§ raised (erase x t).size t.size :=
begin
induction t generalizing aβ aβ,
{ simp [erase, raised], exact h },
{ simp [erase],
have t_ih_l' := t_ih_l h.left,
have t_ih_r' := t_ih_r h.right,
clear t_ih_l t_ih_r,
cases t_ih_l' with t_l_valid t_l_size,
cases t_ih_r' with t_r_valid t_r_size,
cases (cmp_le x t_x);
simp [erase._match_1]; rw h.sz.1,
{ suffices h_balanceable,
split,
{ exact valid'.balance_r t_l_valid h.right h_balanceable },
{ rw size_balance_r t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz h_balanceable,
repeat { apply raised.add_right },
exact t_l_size },
{ left, existsi t_l.size, exact (and.intro t_l_size h.bal.1) } },
{ have h_glue := valid'.glue h.left h.right h.bal.1,
cases h_glue with h_glue_valid h_glue_sized,
split,
{ exact h_glue_valid },
{ right, rw h_glue_sized } },
{ suffices h_balanceable,
split,
{ exact valid'.balance_l h.left t_r_valid h_balanceable },
{ rw size_balance_l h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz h_balanceable,
apply raised.add_right,
apply raised.add_left,
exact t_r_size },
{ right, existsi t_r.size, exact (and.intro t_r_size h.bal.1) } } },
end
theorem erase.valid [@decidable_rel Ξ± (β€)] (x : Ξ±) {t} (h : valid t) : valid (erase x t) :=
(valid'.erase_aux x h).1
theorem size_erase_of_mem [@decidable_rel Ξ± (β€)]
{x : Ξ±} {t aβ aβ} (h : valid' aβ t aβ) (h_mem : x β t) :
size (erase x t) = size t - 1 :=
begin
induction t generalizing aβ aβ h h_mem,
{ contradiction },
{ have t_ih_l' := t_ih_l h.left,
have t_ih_r' := t_ih_r h.right,
clear t_ih_l t_ih_r,
unfold has_mem.mem mem at h_mem,
unfold erase,
cases (cmp_le x t_x);
simp [mem._match_1] at h_mem; simp [erase._match_1],
{ have t_ih_l := t_ih_l' h_mem,
clear t_ih_l' t_ih_r',
have t_l_h := valid'.erase_aux x h.left,
cases t_l_h with t_l_valid t_l_size,
rw size_balance_r t_l_valid.bal h.right.bal t_l_valid.sz h.right.sz
(or.inl (exists.intro t_l.size (and.intro t_l_size h.bal.1))),
rw [t_ih_l, h.sz.1],
have h_pos_t_l_size := pos_size_of_mem h.left.sz h_mem,
cases t_l.size with t_l_size, { cases h_pos_t_l_size },
simp [nat.succ_add] },
{ rw [(valid'.glue h.left h.right h.bal.1).2, h.sz.1], refl },
{ have t_ih_r := t_ih_r' h_mem,
clear t_ih_l' t_ih_r',
have t_r_h := valid'.erase_aux x h.right,
cases t_r_h with t_r_valid t_r_size,
rw size_balance_l h.left.bal t_r_valid.bal h.left.sz t_r_valid.sz
(or.inr (exists.intro t_r.size (and.intro t_r_size h.bal.1))),
rw [t_ih_r, h.sz.1],
have h_pos_t_r_size := pos_size_of_mem h.right.sz h_mem,
cases t_r.size with t_r_size, { cases h_pos_t_r_size },
simp [nat.succ_add, nat.add_succ] } },
end
end
end ordnode
/-- An `ordset Ξ±` is a finite set of values, represented as a tree. The operations on this type
maintain that the tree is balanced and correctly stores subtree sizes at each level. The
correctness property of the tree is baked into the type, so all operations on this type are correct
by construction. -/
def ordset (Ξ± : Type*) [preorder Ξ±] := {t : ordnode Ξ± // t.valid}
namespace ordset
open ordnode
variable [preorder Ξ±]
/-- O(1). The empty set. -/
def nil : ordset Ξ± := β¨nil, β¨β©, β¨β©, β¨β©β©
/-- O(1). Get the size of the set. -/
def size (s : ordset Ξ±) : β := s.1.size
/-- O(1). Construct a singleton set containing value `a`. -/
protected def singleton (a : Ξ±) : ordset Ξ± := β¨singleton a, valid_singletonβ©
instance : has_emptyc (ordset Ξ±) := β¨nilβ©
instance : inhabited (ordset Ξ±) := β¨nilβ©
instance : has_singleton Ξ± (ordset Ξ±) := β¨ordset.singletonβ©
/-- O(1). Is the set empty? -/
def empty (s : ordset Ξ±) : Prop := s = β
theorem empty_iff {s : ordset Ξ±} : s = β
β s.1.empty :=
β¨Ξ» h, by cases h; exact rfl,
Ξ» h, by cases s; cases s_val; [exact rfl, cases h]β©
instance : decidable_pred (@empty Ξ± _) :=
Ξ» s, decidable_of_iff' _ empty_iff
/-- O(log n). Insert an element into the set, preserving balance and the BST property.
If an equivalent element is already in the set, this replaces it. -/
protected def insert [is_total Ξ± (β€)] [@decidable_rel Ξ± (β€)] (x : Ξ±) (s : ordset Ξ±) : ordset Ξ± :=
β¨ordnode.insert x s.1, insert.valid _ s.2β©
instance [is_total Ξ± (β€)] [@decidable_rel Ξ± (β€)] : has_insert Ξ± (ordset Ξ±) := β¨ordset.insertβ©
/-- O(log n). Insert an element into the set, preserving balance and the BST property.
If an equivalent element is already in the set, the set is returned as is. -/
def insert' [is_total Ξ± (β€)] [@decidable_rel Ξ± (β€)] (x : Ξ±) (s : ordset Ξ±) : ordset Ξ± :=
β¨insert' x s.1, insert'.valid _ s.2β©
section
variables [@decidable_rel Ξ± (β€)]
/-- O(log n). Does the set contain the element `x`? That is,
is there an element that is equivalent to `x` in the order? -/
def mem (x : Ξ±) (s : ordset Ξ±) : bool := x β s.val
/-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order,
if it exists. -/
def find (x : Ξ±) (s : ordset Ξ±) : option Ξ± := ordnode.find x s.val
instance : has_mem Ξ± (ordset Ξ±) := β¨Ξ» x s, mem x sβ©
instance mem.decidable (x : Ξ±) (s : ordset Ξ±) : decidable (x β s) := bool.decidable_eq _ _
theorem pos_size_of_mem {x : Ξ±} {t : ordset Ξ±} (h_mem : x β t) : 0 < size t :=
begin
simp [has_mem.mem, mem] at h_mem,
apply ordnode.pos_size_of_mem t.property.sz h_mem,
end
end
/-- O(log n). Remove an element from the set equivalent to `x`. Does nothing if there
is no such element. -/
def erase [@decidable_rel Ξ± (β€)] (x : Ξ±) (s : ordset Ξ±) : ordset Ξ± :=
β¨ordnode.erase x s.val, ordnode.erase.valid x s.propertyβ©
/-- O(n). Map a function across a tree, without changing the structure. -/
def map {Ξ²} [preorder Ξ²] (f : Ξ± β Ξ²) (f_strict_mono : strict_mono f) (s : ordset Ξ±) : ordset Ξ² :=
β¨ordnode.map f s.val, ordnode.map.valid f_strict_mono s.propertyβ©
end ordset
|
21cf330d4cac412ba31d72a2b888c1e845d8df57 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/topology/algebra/module/strong_topology.lean | 78e2334d9215026448b6b378aab9f0f1e5f79d17 | [
"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 | 16,888 | lean | /-
Copyright (c) 2022 Anatole Dedecker. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anatole Dedecker
-/
import topology.algebra.uniform_convergence
/-!
# Strong topologies on the space of continuous linear maps
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
In this file, we define the strong topologies on `E βL[π] F` associated with a family
`π : set (set E)` to be the topology of uniform convergence on the elements of `π` (also called
the topology of `π`-convergence).
The lemma `uniform_on_fun.has_continuous_smul_of_image_bounded` tells us that this is a
vector space topology if the continuous linear image of any element of `π` is bounded (in the sense
of `bornology.is_vonN_bounded`).
We then declare an instance for the case where `π` is exactly the set of all bounded subsets of
`E`, giving us the so-called "topology of uniform convergence on bounded sets" (or "topology of
bounded convergence"), which coincides with the operator norm topology in the case of
`normed_space`s.
Other useful examples include the weak-* topology (when `π` is the set of finite sets or the set
of singletons) and the topology of compact convergence (when `π` is the set of relatively compact
sets).
## Main definitions
* `continuous_linear_map.strong_topology` is the topology mentioned above for an arbitrary `π`.
* `continuous_linear_map.topological_space` is the topology of bounded convergence. This is
declared as an instance.
## Main statements
* `continuous_linear_map.strong_topology.topological_add_group` and
`continuous_linear_map.strong_topology.has_continuous_smul` show that the strong topology
makes `E βL[π] F` a topological vector space, with the assumptions on `π` mentioned above.
* `continuous_linear_map.topological_add_group` and
`continuous_linear_map.has_continuous_smul` register these facts as instances for the special
case of bounded convergence.
## References
* [N. Bourbaki, *Topological Vector Spaces*][bourbaki1987]
## TODO
* add a type alias for continuous linear maps with the topology of `π`-convergence?
## Tags
uniform convergence, bounded convergence
-/
open_locale topology uniform_convergence
namespace continuous_linear_map
section general
variables {πβ πβ : Type*} [normed_field πβ] [normed_field πβ] (Ο : πβ β+* πβ)
{E E' F F' : Type*} [add_comm_group E] [module πβ E] [add_comm_group E'] [module β E']
[add_comm_group F] [module πβ F] [add_comm_group F'] [module β F']
[topological_space E] [topological_space E'] (F)
/-- Given `E` and `F` two topological vector spaces and `π : set (set E)`, then
`strong_topology Ο F π` is the "topology of uniform convergence on the elements of `π`" on
`E βL[π] F`.
If the continuous linear image of any element of `π` is bounded, this makes `E βL[π] F` a
topological vector space. -/
def strong_topology [topological_space F] [topological_add_group F]
(π : set (set E)) : topological_space (E βSL[Ο] F) :=
(@uniform_on_fun.topological_space E F
(topological_add_group.to_uniform_space F) π).induced coe_fn
/-- The uniform structure associated with `continuous_linear_map.strong_topology`. We make sure
that this has nice definitional properties. -/
def strong_uniformity [uniform_space F] [uniform_add_group F]
(π : set (set E)) : uniform_space (E βSL[Ο] F) :=
@uniform_space.replace_topology _ (strong_topology Ο F π)
((uniform_on_fun.uniform_space E F π).comap coe_fn)
(by rw [strong_topology, uniform_add_group.to_uniform_space_eq]; refl)
@[simp] lemma strong_uniformity_topology_eq [uniform_space F] [uniform_add_group F]
(π : set (set E)) :
(strong_uniformity Ο F π).to_topological_space = strong_topology Ο F π :=
rfl
lemma strong_uniformity.uniform_embedding_coe_fn [uniform_space F] [uniform_add_group F]
(π : set (set E)) :
@uniform_embedding (E βSL[Ο] F) (E βα΅€[π] F) (strong_uniformity Ο F π)
(uniform_on_fun.uniform_space E F π) coe_fn :=
begin
letI : uniform_space (E βSL[Ο] F) := strong_uniformity Ο F π,
exact β¨β¨rflβ©, fun_like.coe_injectiveβ©
end
lemma strong_topology.embedding_coe_fn [uniform_space F] [uniform_add_group F]
(π : set (set E)) :
@embedding (E βSL[Ο] F) (E βα΅€[π] F) (strong_topology Ο F π)
(uniform_on_fun.topological_space E F π)
(uniform_on_fun.of_fun π β coe_fn) :=
@uniform_embedding.embedding _ _ (_root_.id _) _ _
(strong_uniformity.uniform_embedding_coe_fn _ _ _)
lemma strong_uniformity.uniform_add_group [uniform_space F] [uniform_add_group F]
(π : set (set E)) : @uniform_add_group (E βSL[Ο] F) (strong_uniformity Ο F π) _ :=
begin
letI : uniform_space (E βSL[Ο] F) := strong_uniformity Ο F π,
rw [strong_uniformity, uniform_space.replace_topology_eq],
let Ο : (E βSL[Ο] F) β+ E βα΅€[π] F := β¨(coe_fn : (E βSL[Ο] F) β E βα΅€ F), rfl, Ξ» _ _, rflβ©,
exact uniform_add_group_comap Ο
end
lemma strong_topology.topological_add_group [topological_space F] [topological_add_group F]
(π : set (set E)) : @topological_add_group (E βSL[Ο] F) (strong_topology Ο F π) _ :=
begin
letI : uniform_space F := topological_add_group.to_uniform_space F,
haveI : uniform_add_group F := topological_add_comm_group_is_uniform,
letI : uniform_space (E βSL[Ο] F) := strong_uniformity Ο F π,
haveI : uniform_add_group (E βSL[Ο] F) := strong_uniformity.uniform_add_group Ο F π,
apply_instance
end
lemma strong_topology.t2_space [topological_space F] [topological_add_group F] [t2_space F]
(π : set (set E)) (hπ : ββ π = set.univ) : @t2_space (E βSL[Ο] F) (strong_topology Ο F π) :=
begin
letI : uniform_space F := topological_add_group.to_uniform_space F,
haveI : uniform_add_group F := topological_add_comm_group_is_uniform,
letI : topological_space (E βSL[Ο] F) := strong_topology Ο F π,
haveI : t2_space (E βα΅€[π] F) := uniform_on_fun.t2_space_of_covering hπ,
exact (strong_topology.embedding_coe_fn Ο F π).t2_space
end
lemma strong_topology.has_continuous_smul [ring_hom_surjective Ο] [ring_hom_isometric Ο]
[topological_space F] [topological_add_group F] [has_continuous_smul πβ F] (π : set (set E))
(hπβ : π.nonempty) (hπβ : directed_on (β) π) (hπβ : β S β π, bornology.is_vonN_bounded πβ S) :
@has_continuous_smul πβ (E βSL[Ο] F) _ _ (strong_topology Ο F π) :=
begin
letI : uniform_space F := topological_add_group.to_uniform_space F,
haveI : uniform_add_group F := topological_add_comm_group_is_uniform,
letI : topological_space (E βSL[Ο] F) := strong_topology Ο F π,
let Ο : (E βSL[Ο] F) ββ[πβ] E βα΅€[π] F :=
β¨(coe_fn : (E βSL[Ο] F) β E β F), Ξ» _ _, rfl, Ξ» _ _, rflβ©,
exact uniform_on_fun.has_continuous_smul_induced_of_image_bounded πβ E F (E βSL[Ο] F)
hπβ hπβ Ο β¨rflβ© (Ξ» u s hs, (hπβ s hs).image u)
end
lemma strong_topology.has_basis_nhds_zero_of_basis [topological_space F] [topological_add_group F]
{ΞΉ : Type*} (π : set (set E)) (hπβ : π.nonempty) (hπβ : directed_on (β) π) {p : ΞΉ β Prop}
{b : ΞΉ β set F} (h : (π 0 : filter F).has_basis p b) :
(@nhds (E βSL[Ο] F) (strong_topology Ο F π) 0).has_basis
(Ξ» Si : set E Γ ΞΉ, Si.1 β π β§ p Si.2)
(Ξ» Si, {f : E βSL[Ο] F | β x β Si.1, f x β b Si.2}) :=
begin
letI : uniform_space F := topological_add_group.to_uniform_space F,
haveI : uniform_add_group F := topological_add_comm_group_is_uniform,
rw nhds_induced,
exact (uniform_on_fun.has_basis_nhds_zero_of_basis π hπβ hπβ h).comap coe_fn
end
lemma strong_topology.has_basis_nhds_zero [topological_space F] [topological_add_group F]
(π : set (set E)) (hπβ : π.nonempty) (hπβ : directed_on (β) π) :
(@nhds (E βSL[Ο] F) (strong_topology Ο F π) 0).has_basis
(Ξ» SV : set E Γ set F, SV.1 β π β§ SV.2 β (π 0 : filter F))
(Ξ» SV, {f : E βSL[Ο] F | β x β SV.1, f x β SV.2}) :=
strong_topology.has_basis_nhds_zero_of_basis Ο F π hπβ hπβ (π 0).basis_sets
end general
section bounded_sets
variables {πβ πβ πβ : Type*} [normed_field πβ] [normed_field πβ] [normed_field πβ]
{Ο : πβ β+* πβ} {Ο : πβ β+* πβ} {Ο : πβ β+* πβ} [ring_hom_comp_triple Ο Ο Ο]
{E E' F F' G : Type*}
[add_comm_group E] [module πβ E] [add_comm_group E'] [module β E']
[add_comm_group F] [module πβ F] [add_comm_group F'] [module β F']
[add_comm_group G] [module πβ G]
[topological_space E]
/-- The topology of bounded convergence on `E βL[π] F`. This coincides with the topology induced by
the operator norm when `E` and `F` are normed spaces. -/
instance [topological_space F] [topological_add_group F] : topological_space (E βSL[Ο] F) :=
strong_topology Ο F {S | bornology.is_vonN_bounded πβ S}
instance [topological_space F] [topological_add_group F] : topological_add_group (E βSL[Ο] F) :=
strong_topology.topological_add_group Ο F _
instance [ring_hom_surjective Ο] [ring_hom_isometric Ο] [topological_space F]
[topological_add_group F] [has_continuous_smul πβ F] :
has_continuous_smul πβ (E βSL[Ο] F) :=
strong_topology.has_continuous_smul Ο F {S | bornology.is_vonN_bounded πβ S}
β¨β
, bornology.is_vonN_bounded_empty πβ Eβ©
(directed_on_of_sup_mem $ Ξ» _ _, bornology.is_vonN_bounded.union)
(Ξ» s hs, hs)
instance [uniform_space F] [uniform_add_group F] : uniform_space (E βSL[Ο] F) :=
strong_uniformity Ο F {S | bornology.is_vonN_bounded πβ S}
instance [uniform_space F] [uniform_add_group F] : uniform_add_group (E βSL[Ο] F) :=
strong_uniformity.uniform_add_group Ο F _
instance [topological_space F] [topological_add_group F] [has_continuous_smul πβ E] [t2_space F] :
t2_space (E βSL[Ο] F) :=
strong_topology.t2_space Ο F _ (set.eq_univ_of_forall $ Ξ» x,
set.mem_sUnion_of_mem (set.mem_singleton x) (bornology.is_vonN_bounded_singleton x))
protected lemma has_basis_nhds_zero_of_basis [topological_space F]
[topological_add_group F] {ΞΉ : Type*} {p : ΞΉ β Prop} {b : ΞΉ β set F}
(h : (π 0 : filter F).has_basis p b) :
(π (0 : E βSL[Ο] F)).has_basis
(Ξ» Si : set E Γ ΞΉ, bornology.is_vonN_bounded πβ Si.1 β§ p Si.2)
(Ξ» Si, {f : E βSL[Ο] F | β x β Si.1, f x β b Si.2}) :=
strong_topology.has_basis_nhds_zero_of_basis Ο F
{S | bornology.is_vonN_bounded πβ S} β¨β
, bornology.is_vonN_bounded_empty πβ Eβ©
(directed_on_of_sup_mem $ Ξ» _ _, bornology.is_vonN_bounded.union) h
protected lemma has_basis_nhds_zero [topological_space F]
[topological_add_group F] :
(π (0 : E βSL[Ο] F)).has_basis
(Ξ» SV : set E Γ set F, bornology.is_vonN_bounded πβ SV.1 β§ SV.2 β (π 0 : filter F))
(Ξ» SV, {f : E βSL[Ο] F | β x β SV.1, f x β SV.2}) :=
continuous_linear_map.has_basis_nhds_zero_of_basis (π 0).basis_sets
variables (G) [topological_space F] [topological_space G]
/-- Pre-composition by a *fixed* continuous linear map as a continuous linear map.
Note that in non-normed space it is not always true that composition is continuous
in both variables, so we have to fix one of them. -/
@[simps] def precomp [topological_add_group G] [has_continuous_const_smul πβ G]
[ring_hom_surjective Ο] [ring_hom_isometric Ο] (L : E βSL[Ο] F) :
(F βSL[Ο] G) βL[πβ] (E βSL[Ο] G) :=
{ to_fun := Ξ» f, f.comp L,
map_add' := Ξ» f g, add_comp f g L,
map_smul' := Ξ» a f, smul_comp a f L,
cont :=
begin
letI : uniform_space G := topological_add_group.to_uniform_space G,
haveI : uniform_add_group G := topological_add_comm_group_is_uniform,
rw (strong_topology.embedding_coe_fn _ _ _).continuous_iff,
refine (uniform_on_fun.precomp_uniform_continuous _).continuous.comp
(strong_topology.embedding_coe_fn _ _ _).continuous,
exact Ξ» S hS, hS.image L,
end }
variables (E) {G}
/-- Post-composition by a *fixed* continuous linear map as a continuous linear map.
Note that in non-normed space it is not always true that composition is continuous
in both variables, so we have to fix one of them. -/
@[simps] def postcomp [topological_add_group F] [topological_add_group G]
[has_continuous_const_smul πβ G] [has_continuous_const_smul πβ F] (L : F βSL[Ο] G) :
(E βSL[Ο] F) βSL[Ο] (E βSL[Ο] G) :=
{ to_fun := Ξ» f, L.comp f,
map_add' := comp_add L,
map_smul' := comp_smulββ L,
cont :=
begin
letI : uniform_space G := topological_add_group.to_uniform_space G,
haveI : uniform_add_group G := topological_add_comm_group_is_uniform,
letI : uniform_space F := topological_add_group.to_uniform_space F,
haveI : uniform_add_group F := topological_add_comm_group_is_uniform,
rw (strong_topology.embedding_coe_fn _ _ _).continuous_iff,
exact (uniform_on_fun.postcomp_uniform_continuous L.uniform_continuous).continuous.comp
(strong_topology.embedding_coe_fn _ _ _).continuous
end }
end bounded_sets
end continuous_linear_map
open continuous_linear_map
namespace continuous_linear_equiv
section semilinear
variables {π : Type*} {πβ : Type*} {πβ : Type*} {πβ : Type*}
{E : Type*} {F : Type*} {G : Type*} {H : Type*}
[add_comm_group E] [add_comm_group F] [add_comm_group G] [add_comm_group H]
[nontrivially_normed_field π] [nontrivially_normed_field πβ] [nontrivially_normed_field πβ]
[nontrivially_normed_field πβ]
[module π E] [module πβ F] [module πβ G] [module πβ H]
[topological_space E] [topological_space F] [topological_space G] [topological_space H]
[topological_add_group G] [topological_add_group H]
[has_continuous_const_smul πβ G] [has_continuous_const_smul πβ H]
{Οββ : π β+* πβ} {Οββ : πβ β+* π} {Οββ : πβ β+* πβ} {Οββ : π β+* πβ} {Οββ : πβ β+* πβ}
{Οββ : πβ β+* πβ} {Οββ : πβ β+* πβ} {Οββ : π β+* πβ}
[ring_hom_inv_pair Οββ Οββ] [ring_hom_inv_pair Οββ Οββ] [ring_hom_inv_pair Οββ Οββ]
[ring_hom_inv_pair Οββ Οββ]
[ring_hom_comp_triple Οββ Οββ Οββ] [ring_hom_comp_triple Οββ Οββ Οββ]
[ring_hom_comp_triple Οββ Οββ Οββ] [ring_hom_comp_triple Οββ Οββ Οββ]
[ring_hom_comp_triple Οββ Οββ Οββ] [ring_hom_comp_triple Οββ Οββ Οββ]
[ring_hom_isometric Οββ] [ring_hom_isometric Οββ]
include Οββ Οββ Οββ Οββ Οββ Οββ
/-- A pair of continuous (semi)linear equivalences generates a (semi)linear equivalence between the
spaces of continuous (semi)linear maps. -/
@[simps] def arrow_congrSL (eββ : E βSL[Οββ] F) (eββ : H βSL[Οββ] G) :
(E βSL[Οββ] H) βSL[Οββ] (F βSL[Οββ] G) :=
{ -- given explicitly to help `simps`
to_fun := Ξ» L, (eββ : H βSL[Οββ] G).comp (L.comp (eββ.symm : F βSL[Οββ] E)),
-- given explicitly to help `simps`
inv_fun := Ξ» L, (eββ.symm : G βSL[Οββ] H).comp (L.comp (eββ : E βSL[Οββ] F)),
map_add' := Ξ» f g, by rw [add_comp, comp_add],
map_smul' := Ξ» t f, by rw [smul_comp, comp_smulββ],
continuous_to_fun :=
((postcomp F eββ.to_continuous_linear_map).comp
(precomp H eββ.symm.to_continuous_linear_map)).continuous,
continuous_inv_fun :=
((precomp H eββ.to_continuous_linear_map).comp
(postcomp F eββ.symm.to_continuous_linear_map)).continuous,
.. eββ.arrow_congr_equiv eββ, }
end semilinear
section linear
variables {π : Type*} {E : Type*} {F : Type*} {G : Type*} {H : Type*}
[add_comm_group E] [add_comm_group F] [add_comm_group G] [add_comm_group H]
[nontrivially_normed_field π] [module π E] [module π F] [module π G] [module π H]
[topological_space E] [topological_space F] [topological_space G] [topological_space H]
[topological_add_group G] [topological_add_group H]
[has_continuous_const_smul π G] [has_continuous_const_smul π H]
/-- A pair of continuous linear equivalences generates an continuous linear equivalence between
the spaces of continuous linear maps. -/
def arrow_congr (eβ : E βL[π] F) (eβ : H βL[π] G) : (E βL[π] H) βL[π] (F βL[π] G) :=
eβ.arrow_congrSL eβ
end linear
end continuous_linear_equiv
|
1a0990d2f78523f3cc864979671fb2fa9c37c74d | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/category_theory/preadditive/endo_functor.lean | 8b4951081b04b74057a05efe69a114bd46651843 | [
"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 | 4,560 | lean | /-
Copyright (c) 2022 Julian Kuelshammer. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Julian Kuelshammer
-/
import category_theory.preadditive.default
import category_theory.endofunctor.algebra
import category_theory.preadditive.additive_functor
/-!
# Preadditive structure on algebras over a monad
If `C` is a preadditive categories and `F` is an additive endofunctor on `C` then `algebra F` is
also preadditive. Dually, the category `coalgebra F` is also preadditive.
-/
universes vβ uβ -- morphism levels before object levels. See note [category_theory universes].
namespace category_theory
variables (C : Type uβ) [category.{vβ} C] [preadditive C] (F : C β₯€ C)
[functor.additive (F : C β₯€ C)]
open category_theory.limits preadditive
/-- The category of algebras over an additive endofunctor on a preadditive category is preadditive.
-/
@[simps]
instance endofunctor.algebra_preadditive : preadditive (endofunctor.algebra F) :=
{ hom_group := Ξ» Aβ Aβ, { add := Ξ» Ξ± Ξ²,
{ f := Ξ±.f + Ξ².f,
h' := by simp only [functor.map_add, add_comp, endofunctor.algebra.hom.h, comp_add] },
zero :=
{ f := 0,
h' := by simp only [functor.map_zero, zero_comp, comp_zero] },
nsmul := Ξ» n Ξ±,
{ f := n β’ Ξ±.f,
h' := by rw [comp_nsmul, functor.map_nsmul, nsmul_comp, endofunctor.algebra.hom.h] },
neg := Ξ» Ξ±,
{ f := -Ξ±.f,
h' := by simp only [functor.map_neg, neg_comp, endofunctor.algebra.hom.h, comp_neg] },
sub := Ξ» Ξ± Ξ²,
{ f := Ξ±.f - Ξ².f,
h' := by simp only [functor.map_sub, sub_comp, endofunctor.algebra.hom.h, comp_sub] },
zsmul := Ξ» r Ξ±,
{ f := r β’ Ξ±.f,
h' := by rw [comp_zsmul, functor.map_zsmul, zsmul_comp, endofunctor.algebra.hom.h] },
add_assoc := by { intros, ext, apply add_assoc },
zero_add := by { intros, ext, apply zero_add },
add_zero := by { intros, ext, apply add_zero },
nsmul_zero' := by { intros, ext, apply zero_smul },
nsmul_succ' := by { intros, ext, apply succ_nsmul },
sub_eq_add_neg := by { intros, ext, apply sub_eq_add_neg },
zsmul_zero' := by { intros, ext, apply zero_smul },
zsmul_succ' := by { intros, ext, dsimp, simp only [coe_nat_zsmul, succ_nsmul], refl, },
zsmul_neg' := by { intros, ext, simp only [zsmul_neg_succ_of_nat, neg_inj,
nsmul_eq_smul_cast β€] },
add_left_neg := by { intros, ext, apply add_left_neg },
add_comm := by { intros, ext, apply add_comm } },
add_comp' := by { intros, ext, apply add_comp },
comp_add' := by { intros, ext, apply comp_add } }
instance algebra.forget_additive : (endofunctor.algebra.forget F).additive := {}
@[simps]
instance endofunctor.coalgebra_preadditive : preadditive (endofunctor.coalgebra F) :=
{ hom_group := Ξ» Aβ Aβ, { add := Ξ» Ξ± Ξ²,
{ f := Ξ±.f + Ξ².f,
h' := by simp only [functor.map_add, comp_add, endofunctor.coalgebra.hom.h, add_comp] },
zero :=
{ f := 0,
h' := by simp only [functor.map_zero, zero_comp, comp_zero] },
nsmul := Ξ» n Ξ±,
{ f := n β’ Ξ±.f,
h' := by rw [functor.map_nsmul, comp_nsmul, endofunctor.coalgebra.hom.h, nsmul_comp] },
neg := Ξ» Ξ±,
{ f := -Ξ±.f,
h' := by simp only [functor.map_neg, comp_neg, endofunctor.coalgebra.hom.h, neg_comp] },
sub := Ξ» Ξ± Ξ²,
{ f := Ξ±.f - Ξ².f,
h' := by simp only [functor.map_sub, comp_sub, endofunctor.coalgebra.hom.h, sub_comp] },
zsmul := Ξ» r Ξ±,
{ f := r β’ Ξ±.f,
h' := by rw [functor.map_zsmul, comp_zsmul, endofunctor.coalgebra.hom.h, zsmul_comp] },
add_assoc := by { intros, ext, apply add_assoc },
zero_add := by { intros, ext, apply zero_add },
add_zero := by { intros, ext, apply add_zero },
nsmul_zero' := by { intros, ext, apply zero_smul },
nsmul_succ' := by { intros, ext, apply succ_nsmul },
sub_eq_add_neg := by { intros, ext, apply sub_eq_add_neg },
zsmul_zero' := by { intros, ext, apply zero_smul },
zsmul_succ' := by { intros, ext, dsimp, simp only [coe_nat_zsmul, succ_nsmul], refl, },
zsmul_neg' := by { intros, ext, simp only [zsmul_neg_succ_of_nat, neg_inj,
nsmul_eq_smul_cast β€] },
add_left_neg := by { intros, ext, apply add_left_neg },
add_comm := by { intros, ext, apply add_comm } },
add_comp' := by { intros, ext, apply add_comp },
comp_add' := by { intros, ext, apply comp_add } }
instance coalgebra.forget_additive : (endofunctor.coalgebra.forget F).additive := {}
end category_theory
|
74faefaeb3edad44da6181a01ef6cc50e6d7b8af | 7282d49021d38dacd06c4ce45a48d09627687fe0 | /tests/lean/arith7.lean | 9a36066150ce2b57c16f76b55d73e1141fda819b | [
"Apache-2.0"
] | permissive | steveluc/lean | 5a0b4431acefaf77f15b25bbb49294c2449923ad | 92ba4e8b2d040a799eda7deb8d2a7cdd3e69c496 | refs/heads/master | 1,611,332,256,930 | 1,391,013,244,000 | 1,391,013,244,000 | 16,361,079 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 409 | lean | import Int.
eval | -2 |
-- Unfortunately, we can't write |-2|, because |- is considered a single token.
-- It is not wise to change that since the symbol |- can be used as the notation for
-- entailment relation in Lean.
eval |3|
definition x : Int := -3
eval |x + 1|
eval |x + 1| > 0
variable y : Int
eval |x + y|
print |x + y| > x
set_option pp::notation false
print |x + y| > x
print |x + y| + |y + x| > x |
3400f9637a462a43d97c1c8da31074e0308d86b0 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/test/lock/Loop.lean | ab3d0aa8287a9d3774b7e90d51dca2b0edaed959 | [
"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 | 29 | lean | #eval do repeat IO.sleep 300
|
647b01ab2962b8bde20935658b96f4549c0dfc78 | ea4aee6b11f86433e69bb5e50d0259e056d0ae61 | /src/tidy/tests/looping_and_profiling.lean | 314b105a79dfa20c6064aef6002e199aa947b128 | [] | no_license | timjb/lean-tidy | e18feff0b7f0aad08c614fb4d34aaf527bf21e20 | e767e259bf76c69edfd4ab8af1b76e6f1ed67f48 | refs/heads/master | 1,624,861,693,182 | 1,504,411,006,000 | 1,504,411,006,000 | 103,740,824 | 0 | 0 | null | 1,505,553,968,000 | 1,505,553,968,000 | null | UTF-8 | Lean | false | false | 657 | lean | -- Copyright (c) 2017 Scott Morrison. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Authors: Scott Morrison
import ..loop_detection
import ..profiling
open tactic
lemma looping_and_profiling_at_the_same_time_test_1 : true :=
begin
profiling $ (detect_looping $ triv),
end
lemma looping_and_profiling_at_the_same_time_test_2 : true :=
begin
success_if_fail { profiling $ detect_looping $ skip >> skip },
triv
end
lemma looping_and_profiling_at_the_same_time_test_3 : 1 = 1 :=
begin
success_if_fail { profiling $ detect_looping $ interactive_simp >> skip >> skip }, -- failed, with 2 invocations
simp
end
|
38266b1b78be434f62b411e40b44795ba5efa530 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Lean/Elab/Deriving/Inhabited.lean | 99f0edc1d5dc6140691e3a97c92f71fb2b5b790e | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | cipher1024/lean4 | 6e1f98bb58e7a92b28f5364eb38a14c8d0aae393 | 69114d3b50806264ef35b57394391c3e738a9822 | refs/heads/master | 1,642,227,983,603 | 1,642,011,696,000 | 1,642,011,696,000 | 228,607,691 | 0 | 0 | Apache-2.0 | 1,576,584,269,000 | 1,576,584,268,000 | null | UTF-8 | Lean | false | false | 5,445 | 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.Deriving.Basic
namespace Lean.Elab
open Command
open Meta
private abbrev IndexSet := Std.RBTree Nat compare
private abbrev LocalInst2Index := FVarIdMap Nat
private def implicitBinderF := Parser.Term.implicitBinder
private def instBinderF := Parser.Term.instBinder
private def mkInhabitedInstanceUsing (inductiveTypeName : Name) (ctorName : Name) (addHypotheses : Bool) : CommandElabM Bool := do
match (β liftTermElabM none mkInstanceCmd?) with
| some cmd =>
elabCommand cmd
return true
| none =>
return false
where
addLocalInstancesForParamsAux {Ξ±} (k : LocalInst2Index β TermElabM Ξ±) : List Expr β Nat β LocalInst2Index β TermElabM Ξ±
| [], i, map => k map
| x::xs, i, map =>
try
let instType β mkAppM `Inhabited #[x]
if (β isTypeCorrect instType) then
withLocalDeclD (β mkFreshUserName `inst) instType fun inst => do
trace[Elab.Deriving.inhabited] "adding local instance {instType}"
addLocalInstancesForParamsAux k xs (i+1) (map.insert inst.fvarId! i)
else
addLocalInstancesForParamsAux k xs (i+1) map
catch _ =>
addLocalInstancesForParamsAux k xs (i+1) map
addLocalInstancesForParams {Ξ±} (xs : Array Expr) (k : LocalInst2Index β TermElabM Ξ±) : TermElabM Ξ± := do
if addHypotheses then
addLocalInstancesForParamsAux k xs.toList 0 {}
else
k {}
collectUsedLocalsInsts (usedInstIdxs : IndexSet) (localInst2Index : LocalInst2Index) (e : Expr) : IndexSet :=
if localInst2Index.isEmpty then
usedInstIdxs
else
let visit {Ο} : StateRefT IndexSet (ST Ο) Unit :=
e.forEach fun
| Expr.fvar fvarId _ =>
match localInst2Index.find? fvarId with
| some idx => modify (Β·.insert idx)
| none => pure ()
| _ => pure ()
runST (fun _ => visit |>.run usedInstIdxs) |>.2
/- Create an `instance` command using the constructor `ctorName` with a hypothesis `Inhabited Ξ±` when `Ξ±` is one of the inductive type parameters
at position `i` and `i β assumingParamIdxs`. -/
mkInstanceCmdWith (assumingParamIdxs : IndexSet) : TermElabM Syntax := do
let indVal β getConstInfoInduct inductiveTypeName
let ctorVal β getConstInfoCtor ctorName
let mut indArgs := #[]
let mut binders := #[]
for i in [:indVal.numParams + indVal.numIndices] do
let arg := mkIdent (β mkFreshUserName `a)
indArgs := indArgs.push arg
let binder β `(implicitBinderF| { $arg:ident })
binders := binders.push binder
if assumingParamIdxs.contains i then
let binder β `(instBinderF| [ Inhabited $arg:ident ])
binders := binders.push binder
let type β `(Inhabited (@$(mkIdent inductiveTypeName):ident $indArgs:ident*))
let mut ctorArgs := #[]
for i in [:ctorVal.numParams] do
ctorArgs := ctorArgs.push (β `(_))
for i in [:ctorVal.numFields] do
ctorArgs := ctorArgs.push (β `(arbitrary))
let val β `(β¨@$(mkIdent ctorName):ident $ctorArgs:ident*β©)
`(instance $binders:explicitBinder* : $type := $val)
mkInstanceCmd? : TermElabM (Option Syntax) := do
let ctorVal β getConstInfoCtor ctorName
forallTelescopeReducing ctorVal.type fun xs _ =>
addLocalInstancesForParams xs[:ctorVal.numParams] fun localInst2Index => do
let mut usedInstIdxs := {}
let mut ok := true
for i in [ctorVal.numParams:xs.size] do
let x := xs[i]
let instType β mkAppM `Inhabited #[(β inferType x)]
trace[Elab.Deriving.inhabited] "checking {instType} for '{ctorName}'"
match (β trySynthInstance instType) with
| LOption.some e =>
usedInstIdxs β collectUsedLocalsInsts usedInstIdxs localInst2Index e
| _ =>
trace[Elab.Deriving.inhabited] "failed to generate instance using '{ctorName}' {if addHypotheses then "(assuming parameters are inhabited)" else ""} because of field with type{indentExpr (β inferType x)}"
ok := false
break
if !ok then
return none
else
trace[Elab.Deriving.inhabited] "inhabited instance using '{ctorName}' {if addHypotheses then "(assuming parameters are inhabited)" else ""} {usedInstIdxs.toList}"
let cmd β mkInstanceCmdWith usedInstIdxs
trace[Elab.Deriving.inhabited] "\n{cmd}"
return some cmd
private def mkInhabitedInstance (declName : Name) : CommandElabM Unit := do
let indVal β getConstInfoInduct declName
let doIt (addHypotheses : Bool) : CommandElabM Bool := do
for ctorName in indVal.ctors do
if (β mkInhabitedInstanceUsing declName ctorName addHypotheses) then
return true
return false
unless (β doIt false <||> doIt true) do
throwError "failed to generate 'Inhabited' instance for '{declName}'"
def mkInhabitedInstanceHandler (declNames : Array Name) : CommandElabM Bool := do
if (β declNames.allM isInductive) then
declNames.forM mkInhabitedInstance
return true
else
return false
builtin_initialize
registerBuiltinDerivingHandler `Inhabited mkInhabitedInstanceHandler
registerTraceClass `Elab.Deriving.inhabited
end Lean.Elab
|
c91d8192206d9fc37dd5c2e67346dae59196c165 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/analysis/specific_limits/floor_pow.lean | 22a9af21cf370ffc0c26fcada04d39d72365c7b7 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 17,666 | lean | /-
Copyright (c) 2022 SΓ©bastien GouΓ«zel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: SΓ©bastien GouΓ«zel
-/
import analysis.specific_limits.basic
import analysis.special_functions.pow
/-!
# Results on discretized exponentials
We state several auxiliary results pertaining to sequences of the form `βc^nββ`.
* `tendsto_div_of_monotone_of_tendsto_div_floor_pow`: If a monotone sequence `u` is such that
`u βc^nββ / βc^nββ` converges to a limit `l` for all `c > 1`, then `u n / n` tends to `l`.
* `sum_div_nat_floor_pow_sq_le_div_sq`: The sum of `1/βc^iββ^2` above a threshold `j` is comparable
to `1/j^2`, up to a multiplicative constant.
-/
open filter finset
open_locale topological_space big_operators
/-- If a monotone sequence `u` is such that `u n / n` tends to a limit `l` along subsequences with
exponential growth rate arbitrarily close to `1`, then `u n / n` tends to `l`. -/
lemma tendsto_div_of_monotone_of_exists_subseq_tendsto_div (u : β β β) (l : β) (hmono : monotone u)
(hlim : β (a : β), 1 < a β β c : β β β, (βαΆ n in at_top, (c (n+1) : β) β€ a * c n) β§
tendsto c at_top at_top β§ tendsto (Ξ» n, u (c n) / (c n)) at_top (π l)) :
tendsto (Ξ» n, u n / n) at_top (π l) :=
begin
/- To check the result up to some `Ξ΅ > 0`, we use a sequence `c` for which the ratio
`c (N+1) / c N` is bounded by `1 + Ξ΅`. Sandwiching a given `n` between two consecutive values of
`c`, say `c N` and `c (N+1)`, one can then bound `u n / n` from above by `u (c N) / c (N - 1)`
and from below by `u (c (N - 1)) / c N` (using that `u` is monotone), which are both comparable
to the limit `l` up to `1 + Ξ΅`.
We give a version of this proof by clearing out denominators first, to avoid discussing the sign
of different quantities. -/
have lnonneg : 0 β€ l,
{ rcases hlim 2 one_lt_two with β¨c, cgrowth, ctop, climβ©,
have : tendsto (Ξ» n, u 0 / (c n)) at_top (π 0) :=
tendsto_const_nhds.div_at_top (tendsto_coe_nat_at_top_iff.2 ctop),
apply le_of_tendsto_of_tendsto' this clim (Ξ» n, _),
simp_rw [div_eq_inv_mul],
exact mul_le_mul_of_nonneg_left (hmono (zero_le _)) (inv_nonneg.2 (nat.cast_nonneg _)) },
have A : β (Ξ΅ : β), 0 < Ξ΅ β βαΆ n in at_top, u n - n * l β€ (Ξ΅ * (1 + Ξ΅ + l)) * n,
{ assume Ξ΅ Ξ΅pos,
rcases hlim (1 + Ξ΅) ((lt_add_iff_pos_right _).2 Ξ΅pos) with β¨c, cgrowth, ctop, climβ©,
have L : βαΆ n in at_top, u (c n) - c n * l β€ Ξ΅ * c n,
{ rw [β tendsto_sub_nhds_zero_iff, β asymptotics.is_o_one_iff β,
asymptotics.is_o_iff] at clim,
filter_upwards [clim Ξ΅pos, ctop (Ioi_mem_at_top 0)] with n hn cnpos',
have cnpos : 0 < c n := cnpos',
calc u (c n) - c n * l
= (u (c n) / c n - l) * c n:
by simp only [cnpos.ne', ne.def, nat.cast_eq_zero, not_false_iff] with field_simps
... β€ Ξ΅ * c n :
begin
refine mul_le_mul_of_nonneg_right _ (nat.cast_nonneg _),
simp only [mul_one, real.norm_eq_abs, abs_one] at hn,
exact le_trans (le_abs_self _) hn,
end },
obtain β¨a, haβ© : β (a : β), β (b : β), a β€ b β (c (b + 1) : β) β€ (1 + Ξ΅) * c b
β§ u (c b) - c b * l β€ Ξ΅ * c b := eventually_at_top.1 (cgrowth.and L),
let M := ((finset.range (a+1)).image (Ξ» i, c i)).max' (by simp),
filter_upwards [Ici_mem_at_top M] with n hn,
have exN : β N, n < c N,
{ rcases (tendsto_at_top.1 ctop (n+1)).exists with β¨N, hNβ©,
exact β¨N, by linarith only [hN]β© },
let N := nat.find exN,
have ncN : n < c N := nat.find_spec exN,
have aN : a + 1 β€ N,
{ by_contra' h,
have cNM : c N β€ M,
{ apply le_max',
apply mem_image_of_mem,
exact mem_range.2 h },
exact lt_irrefl _ ((cNM.trans hn).trans_lt ncN) },
have Npos : 0 < N := lt_of_lt_of_le (nat.succ_pos') aN,
have cNn : c (N - 1) β€ n,
{ have : N - 1 < N := nat.pred_lt Npos.ne',
simpa only [not_lt] using nat.find_min exN this },
have IcN : (c N : β) β€ (1 + Ξ΅) * (c (N - 1)),
{ have A : a β€ N - 1, by linarith only [aN, Npos],
have B : N - 1 + 1 = N := nat.succ_pred_eq_of_pos Npos,
have := (ha _ A).1,
rwa B at this },
calc u n - n * l β€ u (c N) - c (N - 1) * l :
begin
apply sub_le_sub (hmono ncN.le),
apply mul_le_mul_of_nonneg_right (nat.cast_le.2 cNn) lnonneg,
end
... = (u (c N) - c N * l) + (c N - c (N - 1)) * l : by ring
... β€ Ξ΅ * c N + (Ξ΅ * c (N - 1)) * l :
begin
apply add_le_add,
{ apply (ha _ _).2,
exact le_trans (by simp only [le_add_iff_nonneg_right, zero_le']) aN },
{ apply mul_le_mul_of_nonneg_right _ lnonneg,
linarith only [IcN] },
end
... β€ Ξ΅ * ((1 + Ξ΅) * c (N-1)) + (Ξ΅ * c (N - 1)) * l :
add_le_add (mul_le_mul_of_nonneg_left IcN Ξ΅pos.le) le_rfl
... = (Ξ΅ * (1 + Ξ΅ + l)) * c (N - 1) : by ring
... β€ (Ξ΅ * (1 + Ξ΅ + l)) * n :
begin
refine mul_le_mul_of_nonneg_left (nat.cast_le.2 cNn) _,
apply mul_nonneg Ξ΅pos.le,
linarith only [Ξ΅pos, lnonneg]
end },
have B : β (Ξ΅ : β), 0 < Ξ΅ β βαΆ (n : β) in at_top, (n : β) * l - u n β€ (Ξ΅ * (1 + l)) * n,
{ assume Ξ΅ Ξ΅pos,
rcases hlim (1 + Ξ΅) ((lt_add_iff_pos_right _).2 Ξ΅pos) with β¨c, cgrowth, ctop, climβ©,
have L : βαΆ (n : β) in at_top, (c n : β) * l - u (c n) β€ Ξ΅ * c n,
{ rw [β tendsto_sub_nhds_zero_iff, β asymptotics.is_o_one_iff β,
asymptotics.is_o_iff] at clim,
filter_upwards [clim Ξ΅pos, ctop (Ioi_mem_at_top 0)] with n hn cnpos',
have cnpos : 0 < c n := cnpos',
calc (c n : β) * l - u (c n)
= -(u (c n) / c n - l) * c n:
by simp only [cnpos.ne', ne.def, nat.cast_eq_zero, not_false_iff, neg_sub] with field_simps
... β€ Ξ΅ * c n :
begin
refine mul_le_mul_of_nonneg_right _ (nat.cast_nonneg _),
simp only [mul_one, real.norm_eq_abs, abs_one] at hn,
exact le_trans (neg_le_abs_self _) hn,
end },
obtain β¨a, haβ© : β (a : β), β (b : β), a β€ b β (c (b + 1) : β) β€ (1 + Ξ΅) * c b
β§ (c b : β) * l - u (c b) β€ Ξ΅ * c b := eventually_at_top.1 (cgrowth.and L),
let M := ((finset.range (a+1)).image (Ξ» i, c i)).max' (by simp),
filter_upwards [Ici_mem_at_top M] with n hn,
have exN : β N, n < c N,
{ rcases (tendsto_at_top.1 ctop (n+1)).exists with β¨N, hNβ©,
exact β¨N, by linarith only [hN]β© },
let N := nat.find exN,
have ncN : n < c N := nat.find_spec exN,
have aN : a + 1 β€ N,
{ by_contra' h,
have cNM : c N β€ M,
{ apply le_max',
apply mem_image_of_mem,
exact mem_range.2 h },
exact lt_irrefl _ ((cNM.trans hn).trans_lt ncN) },
have Npos : 0 < N := lt_of_lt_of_le (nat.succ_pos') aN,
have aN' : a β€ N - 1 := by linarith only [aN, Npos],
have cNn : c (N - 1) β€ n,
{ have : N - 1 < N := nat.pred_lt Npos.ne',
simpa only [not_lt] using nat.find_min exN this },
calc (n : β) * l - u n β€ c N * l - u (c (N - 1)) :
begin
refine add_le_add (mul_le_mul_of_nonneg_right (nat.cast_le.2 ncN.le) lnonneg) _,
exact neg_le_neg (hmono cNn),
end
... β€ ((1 + Ξ΅) * c (N - 1)) * l - u (c (N - 1)) :
begin
refine add_le_add (mul_le_mul_of_nonneg_right _ lnonneg) le_rfl,
have B : N - 1 + 1 = N := nat.succ_pred_eq_of_pos Npos,
have := (ha _ aN').1,
rwa B at this,
end
... = (c (N - 1) * l - u (c (N - 1))) + Ξ΅ * c (N - 1) * l : by ring
... β€ Ξ΅ * c (N - 1) + Ξ΅ * c (N - 1) * l :
add_le_add (ha _ aN').2 le_rfl
... = (Ξ΅ * (1 + l)) * c (N - 1) : by ring
... β€ (Ξ΅ * (1 + l)) * n :
begin
refine mul_le_mul_of_nonneg_left (nat.cast_le.2 cNn) _,
exact mul_nonneg (Ξ΅pos.le) (add_nonneg zero_le_one lnonneg),
end },
refine tendsto_order.2 β¨Ξ» d hd, _, Ξ» d hd, _β©,
{ obtain β¨Ξ΅, hΞ΅, Ξ΅posβ© : β (Ξ΅ : β), d + Ξ΅ * (1 + l) < l β§ 0 < Ξ΅,
{ have L : tendsto (Ξ» Ξ΅, d + (Ξ΅ * (1 + l))) (π[>] 0) (π (d + 0 * (1 + l))),
{ apply tendsto.mono_left _ nhds_within_le_nhds,
exact tendsto_const_nhds.add (tendsto_id.mul tendsto_const_nhds) },
simp only [zero_mul, add_zero] at L,
exact (((tendsto_order.1 L).2 l hd).and (self_mem_nhds_within)).exists },
filter_upwards [B Ξ΅ Ξ΅pos, Ioi_mem_at_top 0] with n hn npos,
simp_rw [div_eq_inv_mul],
calc d < (nβ»ΒΉ * n) * (l - Ξ΅ * (1 + l)) :
begin
rw [inv_mul_cancel, one_mul],
{ linarith only [hΞ΅] },
{ exact nat.cast_ne_zero.2 (ne_of_gt npos) }
end
... = nβ»ΒΉ * (n * l - Ξ΅ * (1 + l) * n) : by ring
... β€ nβ»ΒΉ * u n :
begin
refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 (nat.cast_nonneg _)),
linarith only [hn],
end },
{ obtain β¨Ξ΅, hΞ΅, Ξ΅posβ© : β (Ξ΅ : β), l + Ξ΅ * (1 + Ξ΅ + l) < d β§ 0 < Ξ΅,
{ have L : tendsto (Ξ» Ξ΅, l + (Ξ΅ * (1 + Ξ΅ + l))) (π[>] 0) (π (l + 0 * (1 + 0 + l))),
{ apply tendsto.mono_left _ nhds_within_le_nhds,
exact tendsto_const_nhds.add
(tendsto_id.mul ((tendsto_const_nhds.add tendsto_id).add tendsto_const_nhds)) },
simp only [zero_mul, add_zero] at L,
exact (((tendsto_order.1 L).2 d hd).and (self_mem_nhds_within)).exists },
filter_upwards [A Ξ΅ Ξ΅pos, Ioi_mem_at_top 0] with n hn npos,
simp_rw [div_eq_inv_mul],
calc (n : β)β»ΒΉ * u n β€ (n : β)β»ΒΉ * (n * l + Ξ΅ * (1 + Ξ΅ + l) * n) :
begin
refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 (nat.cast_nonneg _)),
linarith only [hn],
end
... = ((n : β) β»ΒΉ * n) * (l + Ξ΅ * (1 + Ξ΅ + l)) : by ring
... < d :
begin
rwa [inv_mul_cancel, one_mul],
exact nat.cast_ne_zero.2 (ne_of_gt npos),
end }
end
/-- If a monotone sequence `u` is such that `u βc^nββ / βc^nββ` converges to a limit `l` for all
`c > 1`, then `u n / n` tends to `l`. It is even enough to have the assumption for a sequence of
`c`s converging to `1`. -/
lemma tendsto_div_of_monotone_of_tendsto_div_floor_pow
(u : β β β) (l : β) (hmono : monotone u)
(c : β β β) (cone : β k, 1 < c k) (clim : tendsto c at_top (π 1))
(hc : β k, tendsto (Ξ» (n : β), u (β(c k) ^ nββ) / β(c k)^nββ) at_top (π l)) :
tendsto (Ξ» n, u n / n) at_top (π l) :=
begin
apply tendsto_div_of_monotone_of_exists_subseq_tendsto_div u l hmono,
assume a ha,
obtain β¨k, hkβ© : β k, c k < a := ((tendsto_order.1 clim).2 a ha).exists,
refine β¨Ξ» n, β(c k)^nββ, _,
tendsto_nat_floor_at_top.comp (tendsto_pow_at_top_at_top_of_one_lt (cone k)), hc kβ©,
have H : β (n : β), (0 : β) < βc k ^ nββ,
{ assume n,
refine zero_lt_one.trans_le _,
simp only [nat.one_le_cast, nat.one_le_floor_iff, one_le_pow_of_one_le (cone k).le n] },
have A : tendsto (Ξ» (n : β), ((βc k ^ (n+1)ββ : β) / c k ^ (n+1)) * c k /
(βc k ^ nββ / c k ^ n)) at_top (π (1 * c k / 1)),
{ refine tendsto.div (tendsto.mul _ tendsto_const_nhds) _ one_ne_zero,
{ refine tendsto_nat_floor_div_at_top.comp _,
exact (tendsto_pow_at_top_at_top_of_one_lt (cone k)).comp (tendsto_add_at_top_nat 1) },
{ refine tendsto_nat_floor_div_at_top.comp _,
exact tendsto_pow_at_top_at_top_of_one_lt (cone k) } },
have B : tendsto (Ξ» (n : β), (βc k ^ (n+1)ββ : β) / βc k ^ nββ) at_top (π (c k)),
{ simp only [one_mul, div_one] at A,
convert A,
ext1 n,
simp only [(zero_lt_one.trans (cone k)).ne', ne.def, not_false_iff, (H n).ne']
with field_simps {discharger := tactic.field_simp.ne_zero},
ring_exp },
filter_upwards [(tendsto_order.1 B).2 a hk] with n hn,
exact (div_le_iff (H n)).1 hn.le
end
/-- The sum of `1/(c^i)^2` above a threshold `j` is comparable to `1/j^2`, up to a multiplicative
constant. -/
lemma sum_div_pow_sq_le_div_sq (N : β) {j : β} (hj : 0 < j) {c : β} (hc : 1 < c) :
β i in (range N).filter (Ξ» i, j < c ^ i), 1 / (c ^ i) ^ 2 β€ (c^3 * (c - 1) β»ΒΉ) / j ^ 2 :=
begin
have cpos : 0 < c := zero_lt_one.trans hc,
have A : 0 < (cβ»ΒΉ) ^ 2 := sq_pos_of_pos (inv_pos.2 cpos),
have B : c^2 * (1 - cβ»ΒΉ ^ 2) β»ΒΉ β€ c^3 * (c - 1) β»ΒΉ,
{ rw [β div_eq_mul_inv, β div_eq_mul_inv, div_le_div_iff _ (sub_pos.2 hc)], swap,
{ exact sub_pos.2 (pow_lt_one (inv_nonneg.2 cpos.le) (inv_lt_one hc) two_ne_zero) },
have : c ^ 3 = c^2 * c, by ring_exp,
simp only [mul_sub, this, mul_one, inv_pow, sub_le_sub_iff_left],
rw [mul_assoc, mul_comm c, β mul_assoc, mul_inv_cancel (sq_pos_of_pos cpos).ne', one_mul],
simpa using pow_le_pow hc.le one_le_two },
calc
β i in (range N).filter (Ξ» i, j < c ^ i), 1/ (c ^ i) ^ 2
β€ β i in Ico (βreal.log j / real.log cββ) N, 1 / (c ^ i) ^ 2 :
begin
refine sum_le_sum_of_subset_of_nonneg _ (Ξ» i hi hident, div_nonneg zero_le_one (sq_nonneg _)),
assume i hi,
simp only [mem_filter, mem_range] at hi,
simp only [hi.1, mem_Ico, and_true],
apply nat.floor_le_of_le,
apply le_of_lt,
rw [div_lt_iff (real.log_pos hc), β real.log_pow],
exact real.log_lt_log hj hi.2
end
... = β i in Ico (βreal.log j / real.log cββ) N, ((cβ»ΒΉ) ^ 2) ^ i :
begin
congr' 1 with i,
simp [β pow_mul, mul_comm],
end
... β€ ((cβ»ΒΉ) ^ 2) ^ (βreal.log j / real.log cββ) / (1 - (cβ»ΒΉ) ^ 2) :
begin
apply geom_sum_Ico_le_of_lt_one (sq_nonneg _),
rw sq_lt_one_iff (inv_nonneg.2 (zero_le_one.trans hc.le)),
exact inv_lt_one hc
end
... β€ ((cβ»ΒΉ) ^ 2) ^ (real.log j / real.log c - 1) / (1 - (cβ»ΒΉ) ^ 2) :
begin
apply div_le_div _ _ _ le_rfl,
{ apply real.rpow_nonneg_of_nonneg (sq_nonneg _) },
{ rw β real.rpow_nat_cast,
apply real.rpow_le_rpow_of_exponent_ge A,
{ exact pow_le_one _ (inv_nonneg.2 (zero_le_one.trans hc.le)) (inv_le_one hc.le) },
{ exact (nat.sub_one_lt_floor _).le } },
{ simpa only [inv_pow, sub_pos] using inv_lt_one (one_lt_pow hc two_ne_zero) }
end
... = (c^2 * (1 - cβ»ΒΉ ^ 2) β»ΒΉ) / j ^ 2 :
begin
have I : (c β»ΒΉ ^ 2) ^ (real.log j / real.log c) = 1 / j ^ 2,
{ apply real.log_inj_on_pos (real.rpow_pos_of_pos A _),
{ rw [one_div], exact inv_pos.2 (sq_pos_of_pos hj) },
rw real.log_rpow A,
simp only [one_div, real.log_inv, real.log_pow, nat.cast_bit0, nat.cast_one, mul_neg,
neg_inj],
field_simp [(real.log_pos hc).ne'],
ring },
rw [real.rpow_sub A, I],
have : c^2 - 1 β 0 := (sub_pos.2 (one_lt_pow hc two_ne_zero)).ne',
field_simp [hj.ne', (zero_lt_one.trans hc).ne'],
ring,
end
... β€ (c^3 * (c - 1) β»ΒΉ) / j ^ 2 :
begin
apply div_le_div _ B (sq_pos_of_pos hj) le_rfl,
exact mul_nonneg (pow_nonneg cpos.le _) (inv_nonneg.2 (sub_pos.2 hc).le),
end
end
lemma mul_pow_le_nat_floor_pow {c : β} (hc : 1 < c) (i : β) :
(1 - cβ»ΒΉ) * c ^ i β€ βc ^ iββ :=
begin
have cpos : 0 < c := zero_lt_one.trans hc,
rcases nat.eq_zero_or_pos i with rfl|hi,
{ simp only [pow_zero, nat.floor_one, nat.cast_one, mul_one, sub_le_self_iff, inv_nonneg,
cpos.le] },
have hident : 1 β€ i := hi,
calc (1 - cβ»ΒΉ) * c ^ i
= c ^ i - c ^ i * c β»ΒΉ : by ring
... β€ c ^ i - 1 :
by simpa only [βdiv_eq_mul_inv, sub_le_sub_iff_left, one_le_div cpos, pow_one]
using pow_le_pow hc.le hident
... β€ βc ^ iββ : (nat.sub_one_lt_floor _).le
end
/-- The sum of `1/βc^iββ^2` above a threshold `j` is comparable to `1/j^2`, up to a multiplicative
constant. -/
lemma sum_div_nat_floor_pow_sq_le_div_sq (N : β) {j : β} (hj : 0 < j) {c : β} (hc : 1 < c) :
β i in (range N).filter (Ξ» i, j < βc ^ iββ), (1 : β) / βc ^ iββ ^ 2
β€ (c ^ 5 * (c - 1) β»ΒΉ ^ 3) / j ^ 2 :=
begin
have cpos : 0 < c := zero_lt_one.trans hc,
have A : 0 < 1 - cβ»ΒΉ := sub_pos.2 (inv_lt_one hc),
calc
β i in (range N).filter (Ξ» i, j < βc ^ iββ), (1 : β) / βc ^ iββ ^ 2
β€ β i in (range N).filter (Ξ» i, j < c ^ i), (1 : β) / βc ^ iββ ^ 2 :
begin
apply sum_le_sum_of_subset_of_nonneg,
{ assume i hi,
simp only [mem_filter, mem_range] at hi,
simpa only [hi.1, mem_filter, mem_range, true_and]
using hi.2.trans_le (nat.floor_le (pow_nonneg cpos.le _)) },
{ assume i hi hident,
exact div_nonneg zero_le_one (sq_nonneg _), }
end
... β€ β i in (range N).filter (Ξ» i, j < c ^ i), ((1 - cβ»ΒΉ) β»ΒΉ) ^ 2 * (1 / (c ^ i) ^ 2) :
begin
apply sum_le_sum (Ξ» i hi, _),
rw [mul_div_assoc', mul_one, div_le_div_iff], rotate,
{ apply sq_pos_of_pos,
refine zero_lt_one.trans_le _,
simp only [nat.le_floor, one_le_pow_of_one_le, hc.le, nat.one_le_cast, nat.cast_one] },
{ exact sq_pos_of_pos (pow_pos cpos _) },
rw [one_mul, β mul_pow],
apply pow_le_pow_of_le_left (pow_nonneg cpos.le _),
rw [β div_eq_inv_mul, le_div_iff A, mul_comm],
exact mul_pow_le_nat_floor_pow hc i,
end
... β€ ((1 - cβ»ΒΉ) β»ΒΉ) ^ 2 * (c^3 * (c - 1) β»ΒΉ) / j ^ 2 :
begin
rw [β mul_sum, β mul_div_assoc'],
refine mul_le_mul_of_nonneg_left _ (sq_nonneg _),
exact sum_div_pow_sq_le_div_sq N hj hc,
end
... = (c ^ 5 * (c - 1) β»ΒΉ ^ 3) / j ^ 2 :
begin
congr' 1,
field_simp [cpos.ne', (sub_pos.2 hc).ne'],
ring,
end
end
|
07910707512590bd1405a19ac58f5325d1e4fc62 | 9be442d9ec2fcf442516ed6e9e1660aa9071b7bd | /src/Lean/Message.lean | 94e53a4c9ab4a2f4055dc89acfe2b1c5a1c29cce | [
"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 | 15,284 | lean | /-
Copyright (c) 2018 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Sebastian Ullrich, Leonardo de Moura
Message Type used by the Lean frontend
-/
import Lean.Data.Position
import Lean.Data.OpenDecl
import Lean.Syntax
import Lean.MetavarContext
import Lean.Environment
import Lean.Util.PPExt
namespace Lean
def mkErrorStringWithPos (fileName : String) (pos : Position) (msg : String) (endPos : Option Position := none) : String :=
let endPos := match endPos with
| some endPos => s!"-{endPos.line}:{endPos.column}"
| none => ""
s!"{fileName}:{pos.line}:{pos.column}{endPos}: {msg}"
inductive MessageSeverity where
| information | warning | error
deriving Inhabited, BEq
structure MessageDataContext where
env : Environment
mctx : MetavarContext
lctx : LocalContext
opts : Options
structure NamingContext where
currNamespace : Name
openDecls : List OpenDecl
/- Structure message data. We use it for reporting errors, trace messages, etc. -/
inductive MessageData where
| ofFormat : Format β MessageData
| ofSyntax : Syntax β MessageData
| ofExpr : Expr β MessageData
| ofLevel : Level β MessageData
| ofName : Name β MessageData
| ofGoal : MVarId β MessageData
/- `withContext ctx d` specifies the pretty printing context `(env, mctx, lctx, opts)` for the nested expressions in `d`. -/
| withContext : MessageDataContext β MessageData β MessageData
| withNamingContext : NamingContext β MessageData β MessageData
/- Lifted `Format.nest` -/
| nest : Nat β MessageData β MessageData
/- Lifted `Format.group` -/
| group : MessageData β MessageData
/- Lifted `Format.compose` -/
| compose : MessageData β MessageData β MessageData
/- Tagged sections. `Name` should be viewed as a "kind", and is used by `MessageData` inspector functions.
Example: an inspector that tries to find "definitional equality failures" may look for the tag "DefEqFailure". -/
| tagged : Name β MessageData β MessageData
| trace (cls : Name) (msg : MessageData) (children : Array MessageData)
(collapsed : Bool := false)
deriving Inhabited
namespace MessageData
partial def isEmpty : MessageData β Bool
| ofFormat f => f.isEmpty
| withContext _ m => m.isEmpty
| withNamingContext _ m => m.isEmpty
| nest _ m => m.isEmpty
| group m => m.isEmpty
| compose mβ mβ => mβ.isEmpty && mβ.isEmpty
| tagged _ m => m.isEmpty
| _ => false
/- Instantiate metavariables occurring in nexted `ofExpr` constructors.
It uses the surrounding `MetavarContext` at `withContext` constructors.
-/
partial def instantiateMVars (msg : MessageData) : MessageData :=
visit msg {}
where
visit (msg : MessageData) (mctx : MetavarContext) : MessageData :=
match msg with
| ofExpr e => ofExpr <| instantiateMVarsCore mctx e |>.1
| withContext ctx msg => withContext ctx <| visit msg ctx.mctx
| withNamingContext ctx msg => withNamingContext ctx <| visit msg mctx
| nest n msg => nest n <| visit msg mctx
| group msg => group <| visit msg mctx
| compose msgβ msgβ => compose (visit msgβ mctx) <| visit msgβ mctx
| tagged n msg => tagged n <| visit msg mctx
| trace cls msg msgs c => trace cls (visit msg mctx) (msgs.map (visit Β· mctx)) c
| _ => msg
variable (p : Name β Bool) in
partial def hasTag : MessageData β Bool
| withContext _ msg => hasTag msg
| withNamingContext _ msg => hasTag msg
| nest _ msg => hasTag msg
| group msg => hasTag msg
| compose msgβ msgβ => hasTag msgβ || hasTag msgβ
| tagged n msg => p n || hasTag msg
| trace cls msg msgs _ => p cls || hasTag msg || msgs.any hasTag
| _ => false
def nil : MessageData :=
ofFormat Format.nil
def isNil : MessageData β Bool
| ofFormat Format.nil => true
| _ => false
def isNest : MessageData β Bool
| nest _ _ => true
| _ => false
def mkPPContext (nCtx : NamingContext) (ctx : MessageDataContext) : PPContext := {
env := ctx.env, mctx := ctx.mctx, lctx := ctx.lctx, opts := ctx.opts,
currNamespace := nCtx.currNamespace, openDecls := nCtx.openDecls
}
partial def formatAux : NamingContext β Option MessageDataContext β MessageData β IO Format
| _, _, ofFormat fmt => return fmt
| _, _, ofLevel u => return format u
| _, _, ofName n => return format n
| nCtx, some ctx, ofSyntax s => ppTerm (mkPPContext nCtx ctx) β¨sβ© -- HACK: might not be a term
| _, none, ofSyntax s => return s.formatStx
| _, none, ofExpr e => return format (toString e)
| nCtx, some ctx, ofExpr e => ppExpr (mkPPContext nCtx ctx) e
| _, none, ofGoal mvarId => return "goal " ++ format (mkMVar mvarId)
| nCtx, some ctx, ofGoal mvarId => ppGoal (mkPPContext nCtx ctx) mvarId
| nCtx, _, withContext ctx d => formatAux nCtx ctx d
| _, ctx, withNamingContext nCtx d => formatAux nCtx ctx d
| nCtx, ctx, tagged _ d => formatAux nCtx ctx d
| nCtx, ctx, nest n d => Format.nest n <$> formatAux nCtx ctx d
| nCtx, ctx, compose dβ dβ => return (β formatAux nCtx ctx dβ) ++ (β formatAux nCtx ctx dβ)
| nCtx, ctx, group d => Format.group <$> formatAux nCtx ctx d
| nCtx, ctx, trace cls header children _ => do
let msg := f!"[{cls}] {(β formatAux nCtx ctx header).nest 2}"
let children β children.mapM (formatAux nCtx ctx)
return .nest 2 (.joinSep (msg::children.toList) "\n")
protected def format (msgData : MessageData) : IO Format :=
formatAux { currNamespace := Name.anonymous, openDecls := [] } none msgData
protected def toString (msgData : MessageData) : IO String := do
return toString (β msgData.format)
instance : Append MessageData := β¨composeβ©
instance : Coe String MessageData := β¨ofFormat β formatβ©
instance : Coe Format MessageData := β¨ofFormatβ©
instance : Coe Level MessageData := β¨ofLevelβ©
instance : Coe Expr MessageData := β¨ofExprβ©
instance : Coe Name MessageData := β¨ofNameβ©
instance : Coe Syntax MessageData := β¨ofSyntaxβ©
instance : Coe MVarId MessageData := β¨ofGoalβ©
instance : Coe (Option Expr) MessageData := β¨fun o => match o with | none => "none" | some e => ofExpr eβ©
partial def arrayExpr.toMessageData (es : Array Expr) (i : Nat) (acc : MessageData) : MessageData :=
if h : i < es.size then
let e := es.get β¨i, hβ©;
let acc := if i == 0 then acc ++ ofExpr e else acc ++ ", " ++ ofExpr e;
toMessageData es (i+1) acc
else
acc ++ "]"
instance : Coe (Array Expr) MessageData := β¨fun es => arrayExpr.toMessageData es 0 "#["β©
def bracket (l : String) (f : MessageData) (r : String) : MessageData := group (nest l.length <| l ++ f ++ r)
def paren (f : MessageData) : MessageData := bracket "(" f ")"
def sbracket (f : MessageData) : MessageData := bracket "[" f "]"
def joinSep : List MessageData β MessageData β MessageData
| [], _ => Format.nil
| [a], _ => a
| a::as, sep => a ++ sep ++ joinSep as sep
def ofList: List MessageData β MessageData
| [] => "[]"
| xs => sbracket <| joinSep xs (ofFormat "," ++ Format.line)
def ofArray (msgs : Array MessageData) : MessageData :=
ofList msgs.toList
instance : Coe (List MessageData) MessageData := β¨ofListβ©
instance : Coe (List Expr) MessageData := β¨fun es => ofList <| es.map ofExprβ©
end MessageData
structure Message where
fileName : String
pos : Position
endPos : Option Position := none
severity : MessageSeverity := MessageSeverity.error
caption : String := ""
data : MessageData
deriving Inhabited
namespace Message
protected def toString (msg : Message) (includeEndPos := false) : IO String := do
let mut str β msg.data.toString
let endPos := if includeEndPos then msg.endPos else none
unless msg.caption == "" do
str := msg.caption ++ ":\n" ++ str
match msg.severity with
| MessageSeverity.information => pure ()
| MessageSeverity.warning => str := mkErrorStringWithPos msg.fileName msg.pos (endPos := endPos) "warning: " ++ str
| MessageSeverity.error => str := mkErrorStringWithPos msg.fileName msg.pos (endPos := endPos) "error: " ++ str
if str.isEmpty || str.back != '\n' then
str := str ++ "\n"
return str
end Message
structure MessageLog where
msgs : Std.PersistentArray Message := {}
deriving Inhabited
namespace MessageLog
def empty : MessageLog := β¨{}β©
def isEmpty (log : MessageLog) : Bool :=
log.msgs.isEmpty
def add (msg : Message) (log : MessageLog) : MessageLog :=
β¨log.msgs.push msgβ©
protected def append (lβ lβ : MessageLog) : MessageLog :=
β¨lβ.msgs ++ lβ.msgsβ©
instance : Append MessageLog :=
β¨MessageLog.appendβ©
def hasErrors (log : MessageLog) : Bool :=
log.msgs.any fun m => match m.severity with
| MessageSeverity.error => true
| _ => false
def errorsToWarnings (log : MessageLog) : MessageLog :=
{ msgs := log.msgs.map (fun m => match m.severity with | MessageSeverity.error => { m with severity := MessageSeverity.warning } | _ => m) }
def getInfoMessages (log : MessageLog) : MessageLog :=
{ msgs := log.msgs.filter fun m => match m.severity with | MessageSeverity.information => true | _ => false }
def forM {m : Type β Type} [Monad m] (log : MessageLog) (f : Message β m Unit) : m Unit :=
log.msgs.forM f
def toList (log : MessageLog) : List Message :=
(log.msgs.foldl (fun acc msg => msg :: acc) []).reverse
end MessageLog
def MessageData.nestD (msg : MessageData) : MessageData :=
MessageData.nest 2 msg
def indentD (msg : MessageData) : MessageData :=
MessageData.nestD (Format.line ++ msg)
def indentExpr (e : Expr) : MessageData :=
indentD e
class AddMessageContext (m : Type β Type) where
addMessageContext : MessageData β m MessageData
export AddMessageContext (addMessageContext)
instance (m n) [MonadLift m n] [AddMessageContext m] : AddMessageContext n where
addMessageContext := fun msg => liftM (addMessageContext msg : m _)
def addMessageContextPartial {m} [Monad m] [MonadEnv m] [MonadOptions m] (msgData : MessageData) : m MessageData := do
let env β getEnv
let opts β getOptions
return MessageData.withContext { env := env, mctx := {}, lctx := {}, opts := opts } msgData
def addMessageContextFull {m} [Monad m] [MonadEnv m] [MonadMCtx m] [MonadLCtx m] [MonadOptions m] (msgData : MessageData) : m MessageData := do
let env β getEnv
let mctx β getMCtx
let lctx β getLCtx
let opts β getOptions
return MessageData.withContext { env := env, mctx := mctx, lctx := lctx, opts := opts } msgData
class ToMessageData (Ξ± : Type) where
toMessageData : Ξ± β MessageData
export ToMessageData (toMessageData)
def stringToMessageData (str : String) : MessageData :=
let lines := str.split (Β· == '\n')
let lines := lines.map (MessageData.ofFormat β format)
MessageData.joinSep lines (MessageData.ofFormat Format.line)
instance [ToFormat Ξ±] : ToMessageData Ξ± := β¨MessageData.ofFormat β formatβ©
instance : ToMessageData Expr := β¨MessageData.ofExprβ©
instance : ToMessageData Level := β¨MessageData.ofLevelβ©
instance : ToMessageData Name := β¨MessageData.ofNameβ©
instance : ToMessageData String := β¨stringToMessageDataβ©
instance : ToMessageData Syntax := β¨MessageData.ofSyntaxβ©
instance : ToMessageData (TSyntax k) := β¨(MessageData.ofSyntax Β·)β©
instance : ToMessageData Format := β¨MessageData.ofFormatβ©
instance : ToMessageData MVarId := β¨MessageData.ofGoalβ©
instance : ToMessageData MessageData := β¨idβ©
instance [ToMessageData Ξ±] : ToMessageData (List Ξ±) := β¨fun as => MessageData.ofList <| as.map toMessageDataβ©
instance [ToMessageData Ξ±] : ToMessageData (Array Ξ±) := β¨fun as => toMessageData as.toListβ©
instance [ToMessageData Ξ±] : ToMessageData (Subarray Ξ±) := β¨fun as => toMessageData as.toArray.toListβ©
instance [ToMessageData Ξ±] : ToMessageData (Option Ξ±) := β¨fun | none => "none" | some e => "some (" ++ toMessageData e ++ ")"β©
instance : ToMessageData (Option Expr) := β¨fun | none => "<not-available>" | some e => toMessageData eβ©
syntax:max "m!" interpolatedStr(term) : term
macro_rules
| `(m! $interpStr) => do interpStr.expandInterpolatedStr (β `(MessageData)) (β `(toMessageData))
def toMessageList (msgs : Array MessageData) : MessageData :=
indentD (MessageData.joinSep msgs.toList m!"\n\n")
namespace KernelException
private def mkCtx (env : Environment) (lctx : LocalContext) (opts : Options) (msg : MessageData) : MessageData :=
MessageData.withContext { env := env, mctx := {}, lctx := lctx, opts := opts } msg
def toMessageData (e : KernelException) (opts : Options) : MessageData :=
match e with
| unknownConstant env constName => mkCtx env {} opts m!"(kernel) unknown constant '{constName}'"
| alreadyDeclared env constName => mkCtx env {} opts m!"(kernel) constant has already been declared '{constName}'"
| declTypeMismatch env decl givenType =>
mkCtx env {} opts <|
let process (n : Name) (expectedType : Expr) : MessageData :=
m!"(kernel) declaration type mismatch, '{n}' has type{indentExpr givenType}\nbut it is expected to have type{indentExpr expectedType}";
match decl with
| Declaration.defnDecl { name := n, type := type, .. } => process n type
| Declaration.thmDecl { name := n, type := type, .. } => process n type
| _ => "(kernel) declaration type mismatch" -- TODO fix type checker, type mismatch for mutual decls does not have enough information
| declHasMVars env constName _ => mkCtx env {} opts m!"(kernel) declaration has metavariables '{constName}'"
| declHasFVars env constName _ => mkCtx env {} opts m!"(kernel) declaration has free variables '{constName}'"
| funExpected env lctx e => mkCtx env lctx opts m!"(kernel) function expected{indentExpr e}"
| typeExpected env lctx e => mkCtx env lctx opts m!"(kernel) type expected{indentExpr e}"
| letTypeMismatch env lctx n _ _ => mkCtx env lctx opts m!"(kernel) let-declaration type mismatch '{n}'"
| exprTypeMismatch env lctx e _ => mkCtx env lctx opts m!"(kernel) type mismatch at{indentExpr e}"
| appTypeMismatch env lctx e fnType argType =>
mkCtx env lctx opts m!"application type mismatch{indentExpr e}\nargument has type{indentExpr argType}\nbut function has type{indentExpr fnType}"
| invalidProj env lctx e => mkCtx env lctx opts m!"(kernel) invalid projection{indentExpr e}"
| other msg => m!"(kernel) {msg}"
end KernelException
end Lean
|
aacde6d70d47cc8bbd1df7c8fa8093f97e941ce6 | fe84e287c662151bb313504482b218a503b972f3 | /src/exercises/mathcomp_book/chapter_2.lean | 78a4be1079ff767d06272e3c6a8e2e097e0e415e | [] | no_license | NeilStrickland/lean_lib | 91e163f514b829c42fe75636407138b5c75cba83 | 6a9563de93748ace509d9db4302db6cd77d8f92c | refs/heads/master | 1,653,408,198,261 | 1,652,996,419,000 | 1,652,996,419,000 | 181,006,067 | 4 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 10,092 | lean | import data.nat.gcd data.nat.prime
import tactic.tauto tactic.squeeze tactic.find
/- --------------------------------------------------------------- -/
-- Section 2.1.1
#check 3 = 3
#check (ff && tt = ff)
#check (false β§ true = false)
#print notation `=`
#print eq
-- #check (3 = [3]) -- ERROR
#check 3 = 4
lemma my_first_lemma : 3 = 3 := rfl
#check my_first_lemma
/- --------------------------------------------------------------- -/
-- Section 2.1.2
lemma my_add_assoc (n m k : β) : m + (n + k) = (m + n) + k :=
(nat.add_assoc _ _ _).symm
lemma my_bor_tt (b : bool) : b || tt = tt :=
by { cases b; refl }
lemma my_bor_assoc (b1 b2 b3) : b1 || (b2 || b3) = (b1 || b2) || b3 :=
by { cases b1; cases b2; cases b3; refl, }
-- Next example skipped because bool implication is not predefined in Lean
lemma my_bnot_and (a b : bool) : bnot (a && b) = (bnot a) || (bnot b) :=
by { cases a; cases b; refl }
/- --------------------------------------------------------------- -/
-- Section 2.1.3
lemma my_zero_le (n : β) : 0 β€ n :=
begin
induction n with n ih,
exact nat.less_than_or_equal.refl,
exact nat.less_than_or_equal.step ih,
end
def odd' (n : β) : Prop := (n % 2 = 1)
lemma eq_leq (m n : β) : m = n β ((m β€ n) β§ (n β€ m)) := sorry
lemma ne_lt (m n : β) : m β n β ((m < n) β¨ (n < m)) := sorry
lemma le_zero (n : β) : n β€ 0 β n = 0 := sorry
lemma dvd_one (d : β) : (d β£ 1) β (d = 1) := sorry
lemma odd_mul (m n : β) : odd' (m * n) β (odd' n) β§ (odd' m) := sorry
/- --------------------------------------------------------------- -/
-- Section 2.1.4
lemma leq_pmull (m n : β) : (n > 0) β m β€ n * m := sorry
lemma odd_gt_zero (n : β) : odd' n β n > 0 := sorry
lemma dvd_mul (d1 d2 m1 m2 : β) : (d1 β£ m1) β (d2 β£ m2) β d1 * d2 β£ m1 * m2 := sorry
/- --------------------------------------------------------------- -/
-- Section 2.2.1
lemma my_first_lemma' : 3 = 3 := by refl
lemma my_second_lemma : 2 + 1 = 3 := rfl
lemma add_succ (m n : β) : m + (nat.succ n) = nat.succ (m + n) := rfl
lemma my_bnot_bnot (b : bool) : bnot (bnot b) = b := by {cases b; refl,}
lemma le_zero' (n : β) : n β€ 0 β n = 0 :=
by { cases n with k; simp, }
lemma my_mul_eq_zero (m n : β) : (m * n = 0) β (m = 0) β¨ (n = 0) :=
begin
cases n; cases m;
try {simp [-nat.mul_eq_zero]}
end
/- --------------------------------------------------------------- -/
-- Section 2.3.1
def is_zero : β β bool
| 0 := tt
| _ := ff
def my_le (n m : β) : bool := is_zero (n - m)
lemma le_zero'' (n m : β) : (my_le n 0) = is_zero n :=
begin
cases n; dsimp[my_le]; refl,
end
lemma list_ext (sβ sβ : list β) :
sβ.length = sβ.length β β i, sβ.nth i = sβ.nth i β sβ = sβ := sorry
lemma map_length {Ξ± Ξ² : Type} (f : Ξ± β Ξ²) (s : list Ξ±) :
list.length (list.map f s) = list.length s := sorry
def my_commutative {Ξ± Ξ² : Type} (op : Ξ± β Ξ± β Ξ²) :=
β aβ aβ : Ξ±, op aβ aβ = op aβ aβ
lemma my_add_comm : my_commutative nat.add := nat.add_comm
#print associative
#print right_distrib
#print left_distrib
#print left_identity
#print function.injective
#print function.left_inverse
/- --------------------------------------------------------------- -/
-- Section 2.3.2
section chinese
variables mβ mβ : β
variable co_n12 : nat.coprime mβ mβ
lemma chinese_remainder (x y : β) :
x % (mβ * mβ) = y % (mβ * mβ) β x % mβ = y % mβ β§ x % mβ = y % mβ := sorry
end chinese
/- --------------------------------------------------------------- -/
-- Section 2.3.3
lemma my_le_refl (n : β) : n β€ n := le_refl n
example (a b : β) : a + b β€ a + b := my_le_refl (a + b)
example (a b : β) : a + (nat.succ b) β€ nat.succ (a + b) :=
begin
apply my_le_refl,
end
attribute [simp] my_le_refl
example (a b : β) : a + (nat.succ b) β€ nat.succ (a + b) := sorry
lemma contra (c b : Prop) : (Β¬ c β Β¬ b) β (b β c) :=
begin
intros h hb,
cases classical.em c with hc hnc,
{exact hc},
{exact false.elim (h hnc hb)}
end
example (m p : β) : nat.prime p β p β£ ((nat.factorial m) + 1) β m < p :=
begin
intro prime_p,
apply contra,
intro h0,
have leq_p_m : p β€ m := le_of_not_gt h0,
rw[β (@nat.dvd_add_iff_right p (nat.factorial m) 1)],
{exact nat.prime.not_dvd_one prime_p},
{exact nat.dvd_factorial (nat.prime.pos prime_p) leq_p_m}
end
example (m p : β) : nat.prime p β p β£ ((nat.factorial m) + 1) β m < p :=
begin
intros prime_p d1,
cases lt_or_ge m p, assumption, exfalso,
rw[β (@nat.dvd_add_iff_right p (nat.factorial m) 1)] at d1,
exact nat.prime.not_dvd_one prime_p d1,
exact nat.dvd_factorial (nat.prime.pos prime_p) h,
end
/- --------------------------------------------------------------- -/
-- Section 2.3.4
#check @nat.rec
#check @list.rec
lemma my_add_zero (m : β) : m + 0 = m := rfl
lemma my_zero_add (m : β) : 0 + m = m :=
begin
induction m with m ih,refl,exact congr_arg nat.succ ih,
end
lemma last_ind (Ξ± : Type) (P : list Ξ± β Prop) :
(P list.nil) β (β s x, P s β P (s.concat x)) β β s, P s :=
begin
intros P_nil P_step,
let C : (list Ξ±) β Prop := Ξ» s,
(β (Q : list Ξ± β Prop) (Q_nil : Q list.nil)
(Q_step : β t x, Q t β Q (t.concat x)), Q s),
have h : β s : list Ξ±, C s,
{intro s,
induction s with w s ih,
{intros Q Q_nil Q_step,exact Q_nil},
{intros Q Q_nil Q_step,
let R := Ξ» t, Q (w :: t),
let R_nil : R list.nil := Q_step list.nil w Q_nil,
let R_step : β t x, R t β R (t.concat x) :=
Ξ» t x R_t, Q_step (w :: t) x R_t,
exact ih R R_nil R_step,
}
},
intro s,
exact h s P P_nil P_step,
end
lemma foldl_rev (Ξ± Ξ² : Type) (f : Ξ± β Ξ² β Ξ±) (z : Ξ±) (s : list Ξ²) :
list.foldl f z s.reverse = list.foldr (Ξ» x z, f z x) z s :=
begin
revert z,
refine last_ind Ξ² _ _ _ s,
{intro z,simp,},
{intros t x h0 z,
have h1 : list.reverse (list.concat t x) = x :: (list.reverse t) := by simp,
have h2 : t.concat x = t ++ [x] := by simp,
rw[h1,h2,list.foldl,h0 (f z x),list.foldr_append,list.foldr,list.foldr],
}
end
/- --------------------------------------------------------------- -/
-- Section 2.4
example (m p : β) : nat.prime p β p β£ ((nat.factorial m) + 1) β m < p :=
begin
intros prime_p,apply contra,intros h0 d1,
exact nat.prime.not_dvd_one prime_p
((@nat.dvd_add_iff_right p (nat.factorial m) 1 (nat.dvd_factorial (nat.prime.pos prime_p) (le_of_not_gt h0))).mpr d1),
end
/- --------------------------------------------------------------- -/
-- Section 2.5
-- #find nat.bodd
-- #find (_ β£ nat.fact _)
-- #find nat.coprime
-- #find (_ * _ = _ * _)
/- --------------------------------------------------------------- -/
-- Exercises for Chapter 2
example (b1 b2 b3 : bool) : b1 || (b2 || b3) = (b1 || b2) || b3 :=
by {cases b1; cases b2; cases b3; refl,}
-- Next example skipped as boolean implication is not predefined in Lean
example (a b : bool) : bnot (a && b) = (bnot a) || (bnot b) :=
by {cases a; cases b; refl,}
lemma nat.sub_add : β (n m k : β), n - (m + k) = (n - m) - k
| n m 0 := by {rw[add_zero,nat.sub_zero],}
| n m (nat.succ k) := by {rw[nat.add_succ,nat.sub_succ,nat.sub_add,nat.sub_succ]}
lemma nat.mul_pred (n m : β) : n * (nat.pred m) = n * m - n :=
begin
cases m,
{rw[nat.pred_zero,mul_zero,nat.zero_sub],},
{rw[nat.pred_succ,nat.mul_succ,nat.add_sub_cancel],}
end
lemma nat.pred_mul (n m : β) : (nat.pred n) * m = n * m - m :=
by { rw[nat.mul_comm,nat.mul_pred,nat.mul_comm], }
lemma nat.mul_sub : β (n m k : β), n * (m - k) = n * m - n * k
| n m 0 := by { rw[mul_zero,nat.sub_zero,nat.sub_zero],}
| n m (k + 1) :=
by {rw[nat.sub_succ,nat.mul_pred,nat.mul_sub,nat.mul_succ,nat.sub_add],}
lemma nat.sub_mul (n m k : β) : (n - m) * k = n * k - m * k :=
by {rw[nat.mul_comm,nat.mul_sub],congr' 1;apply nat.mul_comm}
example (n m : β) : m ^ 2 - n ^ 2 = (m - n) * (m + n) :=
begin
rw[pow_two,pow_two,nat.sub_mul,mul_add,mul_add,nat.mul_comm m n],
rw[nat.sub_add,nat.add_sub_cancel],
end
lemma bodd_exp (m n : β) : nat.bodd (m ^ n) = (n = 0) || nat.bodd m :=
begin
induction n with n ih,
{refl,},
{rw[to_bool_ff (nat.succ_ne_zero n),ff_bor,pow_succ,nat.bodd_mul,ih],
cases (nat.bodd m); cases (to_bool (n = 0)); refl
}
end
def flatten {Ξ± : Type} (l : list (list Ξ±)) : list Ξ± :=
list.foldr list.append list.nil l
lemma flatten_length {Ξ± : Type} : β (l : list (list Ξ±)),
(flatten l).length = list.sum (l.map list.length)
| list.nil := rfl
| (list.cons u l) := by {
erw[list.length_append,flatten_length l,list.map_cons,list.sum_cons],
}
def all_words {Ξ± : Type} : β (n : β) (alphabet : list Ξ±), list (list Ξ±)
| 0 _ := [list.nil]
| (nat.succ n) alphabet :=
flatten (list.map (Ξ» a,list.map (list.cons a) (all_words n alphabet)) alphabet)
lemma all_words_length {Ξ± : Type} (n : β) (alphabet : list Ξ±) :
(all_words n alphabet).length = alphabet.length ^ n :=
begin
induction n with n ih,
{refl,},
{erw[all_words,flatten_length],
rw[pow_succ,mul_comm],
let f : Ξ± β list (list Ξ±) :=
Ξ» a, list.map (list.cons a) (all_words n alphabet),
let g : Ξ± β β := Ξ» a, (f a).length,
let l := alphabet.map f,
let m := l.map list.length,
have h0 : β a : Ξ±, g a = alphabet.length ^ n :=
Ξ» a, (list.length_map _ _).trans ih,
have h1 : m.length = alphabet.length :=
(list.length_map list.length l).trans (list.length_map f alphabet),
have h2 : β i : β, i β m β i = alphabet.length ^ n :=
begin
intros i i_in_m,
rcases list.mem_map.mp i_in_m with β¨l0,β¨l0_in_l,l0_lengthβ©β©,
rcases list.mem_map.mp l0_in_l with β¨a,β¨a_in_alphabet,fa_eq_l0β©β©,
exact ((h0 a).symm.trans
((congr_arg list.length fa_eq_l0).trans l0_length)).symm,
end,
let h3 := (@list.eq_repeat β (alphabet.length ^ n) alphabet.length
(l.map list.length)).mpr β¨h1,h2β©,
exact ((congr_arg list.sum h3).trans
(list.sum_const_nat (alphabet.length ^ n) alphabet.length)),
}
end
|
152db41d0b03ced1d44de52fb32b206de2bd4351 | 31f556cdeb9239ffc2fad8f905e33987ff4feab9 | /stage0/src/Init/Notation.lean | a167f0f66b7c94079b5953e0f10b67da2f6ee8aa | [
"Apache-2.0",
"LLVM-exception",
"NCSA",
"LGPL-3.0-only",
"LicenseRef-scancode-inner-net-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"Spencer-94",
"LGPL-2.1-or-later",
"HPND",
"LicenseRef-scancode-pcre",
"ISC",
"LGPL-2.1-only",
"LicenseRef-scancode-other-permissive",
"SunPro",
"CMU-Mach"... | permissive | tobiasgrosser/lean4 | ce0fd9cca0feba1100656679bf41f0bffdbabb71 | ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f | refs/heads/master | 1,673,103,412,948 | 1,664,930,501,000 | 1,664,930,501,000 | 186,870,185 | 0 | 0 | Apache-2.0 | 1,665,129,237,000 | 1,557,939,901,000 | Lean | UTF-8 | Lean | false | false | 21,218 | 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, Mario Carneiro
Notation for operators defined at Prelude.lean
-/
prelude
import Init.Prelude
import Init.Coe
set_option linter.missingDocs true -- keep it documented
namespace Lean
/--
Auxiliary type used to represent syntax categories. We mainly use auxiliary
definitions with this type to attach doc strings to syntax categories.
-/
structure Parser.Category
namespace Parser.Category
/-- `command` is the syntax category for things that appear at the top level
of a lean file. For example, `def foo := 1` is a `command`, as is
`namespace Foo` and `end Foo`. Commands generally have an effect on the state of
adding something to the environment (like a new definition), as well as
commands like `variable` which modify future commands within a scope. -/
def command : Category := {}
/-- `term` is the builtin syntax category for terms. A term denotes an expression
in lean's type theory, for example `2 + 2` is a term. The difference between
`Term` and `Expr` is that the former is a kind of syntax, while the latter is
the result of elaboration. For example `by simp` is also a `Term`, but it elaborates
to different `Expr`s depending on the context. -/
def term : Category := {}
/-- `tactic` is the builtin syntax category for tactics. These appear after
`by` in proofs, and they are programs that take in the proof context
(the hypotheses in scope plus the type of the term to synthesize) and construct
a term of the expected type. For example, `simp` is a tactic, used in:
```
example : 2 + 2 = 4 := by simp
```
-/
def tactic : Category := {}
/-- `doElem` is a builtin syntax category for elements that can appear in the `do` notation.
For example, `let x β e` is a `doElem`, and a `do` block consists of a list of `doElem`s. -/
def doElem : Category := {}
/-- `level` is a builtin syntax category for universe levels.
This is the `u` in `Sort u`: it can contain `max` and `imax`, addition with
constants, and variables. -/
def level : Category := {}
/-- `attr` is a builtin syntax category for attributes.
Declarations can be annotated with attributes using the `@[...]` notation. -/
def attr : Category := {}
/-- `stx` is a builtin syntax category for syntax. This is the abbreviated
parser notation used inside `syntax` and `macro` declarations. -/
def stx : Category := {}
/-- `prio` is a builtin syntax category for priorities.
Priorities are used in many different attributes.
Higher numbers denote higher priority, and for example typeclass search will
try high priority instances before low priority.
In addition to literals like `37`, you can also use `low`, `mid`, `high`, as well as
add and subtract priorities. -/
def prio : Category := {}
/-- `prec` is a builtin syntax category for precedences. A precedence is a value
that expresses how tightly a piece of syntax binds: for example `1 + 2 * 3` is
parsed as `1 + (2 * 3)` because `*` has a higher pr0ecedence than `+`.
Higher numbers denote higher precedence.
In addition to literals like `37`, there are some special named priorities:
* `arg` for the precedence of function arguments
* `max` for the highest precedence used in term parsers (not actually the maximum possible value)
* `lead` for the precedence of terms not supposed to be used as arguments
and you can also add and subtract precedences. -/
def prec : Category := {}
end Parser.Category
namespace Parser.Syntax
/-! DSL for specifying parser precedences and priorities -/
/-- Addition of precedences. This is normally used only for offseting, e.g. `max + 1`. -/
syntax:65 (name := addPrec) prec " + " prec:66 : prec
/-- Subtraction of precedences. This is normally used only for offseting, e.g. `max - 1`. -/
syntax:65 (name := subPrec) prec " - " prec:66 : prec
/-- Addition of priorities. This is normally used only for offseting, e.g. `default + 1`. -/
syntax:65 (name := addPrio) prio " + " prio:66 : prio
/-- Subtraction of priorities. This is normally used only for offseting, e.g. `default - 1`. -/
syntax:65 (name := subPrio) prio " - " prio:66 : prio
end Parser.Syntax
instance : CoeHead (TSyntax ks) Syntax where
coe stx := stx.raw
instance : Coe SyntaxNodeKind SyntaxNodeKinds where
coe k := List.cons k List.nil
end Lean
/--
Maximum precedence used in term parsers, in particular for terms in
function position (`ident`, `paren`, ...)
-/
macro "max" : prec => `(1024)
/-- Precedence used for application arguments (`do`, `by`, ...). -/
macro "arg" : prec => `(1023)
/-- Precedence used for terms not supposed to be used as arguments (`let`, `have`, ...). -/
macro "lead" : prec => `(1022)
/-- Parentheses are used for grouping precedence expressions. -/
macro "(" p:prec ")" : prec => return p
/-- Minimum precedence used in term parsers. -/
macro "min" : prec => `(10)
/-- `(min+1)` (we can only write `min+1` after `Meta.lean`) -/
macro "min1" : prec => `(11)
/--
`max:prec` as a term. It is equivalent to `eval_prec max` for `eval_prec` defined at `Meta.lean`.
We use `max_prec` to workaround bootstrapping issues.
-/
macro "max_prec" : term => `(1024)
/-- The default priority `default = 1000`, which is used when no priority is set. -/
macro "default" : prio => `(1000)
/-- The standardized "low" priority `low = 100`, for things that should be lower than default priority. -/
macro "low" : prio => `(100)
/-- The standardized "medium" priority `med = 1000`. This is the same as `default`. -/
macro "mid" : prio => `(1000)
/-- The standardized "high" priority `high = 10000`, for things that should be higher than default priority. -/
macro "high" : prio => `(10000)
/-- Parentheses are used for grouping priority expressions. -/
macro "(" p:prio ")" : prio => return p
-- Basic notation for defining parsers
-- NOTE: precedence must be at least `arg` to be used in `macro` without parentheses
/--
`p+` is shorthand for `many1(p)`. It uses parser `p` 1 or more times, and produces a
`nullNode` containing the array of parsed results. This parser has arity 1.
If `p` has arity more than 1, it is auto-grouped in the items generated by the parser.
-/
syntax:arg stx:max "+" : stx
/--
`p*` is shorthand for `many(p)`. It uses parser `p` 0 or more times, and produces a
`nullNode` containing the array of parsed results. This parser has arity 1.
If `p` has arity more than 1, it is auto-grouped in the items generated by the parser.
-/
syntax:arg stx:max "*" : stx
/--
`(p)?` is shorthand for `optional(p)`. It uses parser `p` 0 or 1 times, and produces a
`nullNode` containing the array of parsed results. This parser has arity 1.
`p` is allowed to have arity n > 1 (in which case the node will have either 0 or n children),
but if it has arity 0 then the result will be ambiguous.
Because `?` is an identifier character, `ident?` will not work as intended.
You have to write either `ident ?` or `(ident)?` for it to parse as the `?` combinator
applied to the `ident` parser.
-/
syntax:arg stx:max "?" : stx
/--
`p1 <|> p2` is shorthand for `orelse(p1, p2)`, and parses either `p1` or `p2`.
It does not backtrack, meaning that if `p1` consumes at least one token then
`p2` will not be tried. Therefore, the parsers should all differ in their first
token. The `atomic(p)` parser combinator can be used to locally backtrack a parser.
(For full backtracking, consider using extensible syntax classes instead.)
On success, if the inner parser does not generate exactly one node, it will be
automatically wrapped in a `group` node, so the result will always be arity 1.
The `<|>` combinator does not generate a node of its own, and in particular
does not tag the inner parsers to distinguish them, which can present a problem
when reconstructing the parse. A well formed `<|>` parser should use disjoint
node kinds for `p1` and `p2`.
-/
syntax:2 stx:2 " <|> " stx:1 : stx
macro_rules
| `(stx| $p +) => `(stx| many1($p))
| `(stx| $p *) => `(stx| many($p))
| `(stx| $p ?) => `(stx| optional($p))
| `(stx| $pβ <|> $pβ) => `(stx| orelse($pβ, $pβ))
/--
`p,*` is shorthand for `sepBy(p, ",")`. It parses 0 or more occurrences of
`p` separated by `,`, that is: `empty | p | p,p | p,p,p | ...`.
It produces a `nullNode` containing a `SepArray` with the interleaved parser
results. It has arity 1, and auto-groups its component parser if needed.
-/
macro:arg x:stx:max ",*" : stx => `(stx| sepBy($x, ",", ", "))
/--
`p,+` is shorthand for `sepBy(p, ",")`. It parses 1 or more occurrences of
`p` separated by `,`, that is: `p | p,p | p,p,p | ...`.
It produces a `nullNode` containing a `SepArray` with the interleaved parser
results. It has arity 1, and auto-groups its component parser if needed.
-/
macro:arg x:stx:max ",+" : stx => `(stx| sepBy1($x, ",", ", "))
/--
`p,*,?` is shorthand for `sepBy(p, ",", allowTrailingSep)`.
It parses 0 or more occurrences of `p` separated by `,`, possibly including
a trailing `,`, that is: `empty | p | p, | p,p | p,p, | p,p,p | ...`.
It produces a `nullNode` containing a `SepArray` with the interleaved parser
results. It has arity 1, and auto-groups its component parser if needed.
-/
macro:arg x:stx:max ",*,?" : stx => `(stx| sepBy($x, ",", ", ", allowTrailingSep))
/--
`p,+,?` is shorthand for `sepBy1(p, ",", allowTrailingSep)`.
It parses 1 or more occurrences of `p` separated by `,`, possibly including
a trailing `,`, that is: `p | p, | p,p | p,p, | p,p,p | ...`.
It produces a `nullNode` containing a `SepArray` with the interleaved parser
results. It has arity 1, and auto-groups its component parser if needed.
-/
macro:arg x:stx:max ",+,?" : stx => `(stx| sepBy1($x, ",", ", ", allowTrailingSep))
/--
`!p` parses the negation of `p`. That is, it fails if `p` succeeds, and
otherwise parses nothing. It has arity 0.
-/
macro:arg "!" x:stx:max : stx => `(stx| notFollowedBy($x))
/--
The `nat_lit n` macro constructs "raw numeric literals". This corresponds to the
`Expr.lit (.natVal n)` constructor in the `Expr` data type.
Normally, when you write a numeral like `#check 37`, the parser turns this into
an application of `OfNat.ofNat` to the raw literal `37` to cast it into the
target type, even if this type is `Nat` (so the cast is the identity function).
But sometimes it is necessary to talk about the raw numeral directly,
especially when proving properties about the `ofNat` function itself.
-/
syntax (name := rawNatLit) "nat_lit " num : term
@[inheritDoc] infixr:90 " β " => Function.comp
@[inheritDoc] infixr:35 " Γ " => Prod
@[inheritDoc] infixl:55 " ||| " => HOr.hOr
@[inheritDoc] infixl:58 " ^^^ " => HXor.hXor
@[inheritDoc] infixl:60 " &&& " => HAnd.hAnd
@[inheritDoc] infixl:65 " + " => HAdd.hAdd
@[inheritDoc] infixl:65 " - " => HSub.hSub
@[inheritDoc] infixl:70 " * " => HMul.hMul
@[inheritDoc] infixl:70 " / " => HDiv.hDiv
@[inheritDoc] infixl:70 " % " => HMod.hMod
@[inheritDoc] infixl:75 " <<< " => HShiftLeft.hShiftLeft
@[inheritDoc] infixl:75 " >>> " => HShiftRight.hShiftRight
@[inheritDoc] infixr:80 " ^ " => HPow.hPow
@[inheritDoc] infixl:65 " ++ " => HAppend.hAppend
@[inheritDoc] prefix:100 "-" => Neg.neg
@[inheritDoc] prefix:100 "~~~" => Complement.complement
/-!
Remark: the infix commands above ensure a delaborator is generated for each relations.
We redefine the macros below to be able to use the auxiliary `binop%` elaboration helper for binary operators.
It addresses issue #382. -/
macro_rules | `($x ||| $y) => `(binop% HOr.hOr $x $y)
macro_rules | `($x ^^^ $y) => `(binop% HXor.hXor $x $y)
macro_rules | `($x &&& $y) => `(binop% HAnd.hAnd $x $y)
macro_rules | `($x + $y) => `(binop% HAdd.hAdd $x $y)
macro_rules | `($x - $y) => `(binop% HSub.hSub $x $y)
macro_rules | `($x * $y) => `(binop% HMul.hMul $x $y)
macro_rules | `($x / $y) => `(binop% HDiv.hDiv $x $y)
macro_rules | `($x % $y) => `(binop% HMod.hMod $x $y)
macro_rules | `($x ^ $y) => `(binop% HPow.hPow $x $y)
macro_rules | `($x ++ $y) => `(binop% HAppend.hAppend $x $y)
-- declare ASCII alternatives first so that the latter Unicode unexpander wins
@[inheritDoc] infix:50 " <= " => LE.le
@[inheritDoc] infix:50 " β€ " => LE.le
@[inheritDoc] infix:50 " < " => LT.lt
@[inheritDoc] infix:50 " >= " => GE.ge
@[inheritDoc] infix:50 " β₯ " => GE.ge
@[inheritDoc] infix:50 " > " => GT.gt
@[inheritDoc] infix:50 " = " => Eq
@[inheritDoc] infix:50 " == " => BEq.beq
/-!
Remark: the infix commands above ensure a delaborator is generated for each relations.
We redefine the macros below to be able to use the auxiliary `binrel%` elaboration helper for binary relations.
It has better support for applying coercions. For example, suppose we have `binrel% Eq n i` where `n : Nat` and
`i : Int`. The default elaborator fails because we don't have a coercion from `Int` to `Nat`, but
`binrel%` succeeds because it also tries a coercion from `Nat` to `Int` even when the nat occurs before the int. -/
macro_rules | `($x <= $y) => `(binrel% LE.le $x $y)
macro_rules | `($x β€ $y) => `(binrel% LE.le $x $y)
macro_rules | `($x < $y) => `(binrel% LT.lt $x $y)
macro_rules | `($x > $y) => `(binrel% GT.gt $x $y)
macro_rules | `($x >= $y) => `(binrel% GE.ge $x $y)
macro_rules | `($x β₯ $y) => `(binrel% GE.ge $x $y)
macro_rules | `($x = $y) => `(binrel% Eq $x $y)
macro_rules | `($x == $y) => `(binrel_no_prop% BEq.beq $x $y)
@[inheritDoc] infixr:35 " /\\ " => And
@[inheritDoc] infixr:35 " β§ " => And
@[inheritDoc] infixr:30 " \\/ " => Or
@[inheritDoc] infixr:30 " β¨ " => Or
@[inheritDoc] notation:max "Β¬" p:40 => Not p
@[inheritDoc] infixl:35 " && " => and
@[inheritDoc] infixl:30 " || " => or
@[inheritDoc] notation:max "!" b:40 => not b
@[inheritDoc] infix:50 " β " => Membership.mem
/-- `a β b` is negated elementhood. It is notation for `Β¬ (a β b)`. -/
notation:50 a:50 " β " b:50 => Β¬ (a β b)
@[inheritDoc] infixr:67 " :: " => List.cons
@[inheritDoc HOrElse.hOrElse] syntax:20 term:21 " <|> " term:20 : term
@[inheritDoc HAndThen.hAndThen] syntax:60 term:61 " >> " term:60 : term
@[inheritDoc] infixl:55 " >>= " => Bind.bind
@[inheritDoc] notation:60 a:60 " <*> " b:61 => Seq.seq a fun _ : Unit => b
@[inheritDoc] notation:60 a:60 " <* " b:61 => SeqLeft.seqLeft a fun _ : Unit => b
@[inheritDoc] notation:60 a:60 " *> " b:61 => SeqRight.seqRight a fun _ : Unit => b
@[inheritDoc] infixr:100 " <$> " => Functor.map
macro_rules | `($x <|> $y) => `(binop_lazy% HOrElse.hOrElse $x $y)
macro_rules | `($x >> $y) => `(binop_lazy% HAndThen.hAndThen $x $y)
namespace Lean
/--
`binderIdent` matches an `ident` or a `_`. It is used for identifiers in binding
position, where `_` means that the value should be left unnamed and inaccessible.
-/
syntax binderIdent := ident <|> hole
namespace Parser.Tactic
/--
A case tag argument has the form `tag xβ ... xβ`; it refers to tag `tag` and renames
the last `n` hypotheses to `xβ ... xβ`.
-/
syntax caseArg := binderIdent binderIdent*
end Parser.Tactic
end Lean
@[inheritDoc dite] syntax (name := termDepIfThenElse)
ppRealGroup(ppRealFill(ppIndent("if " Lean.binderIdent " : " term " then") ppSpace term)
ppDedent(ppSpace) ppRealFill("else " term)) : term
macro_rules
| `(if $h:ident : $c then $t else $e) => do
let mvar β Lean.withRef c `(?m)
`(let_mvar% ?m := $c; wait_if_type_mvar% ?m; dite $mvar (fun $h:ident => $t) (fun $h:ident => $e))
| `(if _%$h : $c then $t else $e) => do
let mvar β Lean.withRef c `(?m)
`(let_mvar% ?m := $c; wait_if_type_mvar% ?m; dite $mvar (fun _%$h => $t) (fun _%$h => $e))
@[inheritDoc ite] syntax (name := termIfThenElse)
ppRealGroup(ppRealFill(ppIndent("if " term " then") ppSpace term)
ppDedent(ppSpace) ppRealFill("else " term)) : term
macro_rules
| `(if $c then $t else $e) => do
let mvar β Lean.withRef c `(?m)
`(let_mvar% ?m := $c; wait_if_type_mvar% ?m; ite $mvar $t $e)
/--
`if let pat := d then t else e` is a shorthand syntax for:
```
match d with
| pat => t
| _ => e
```
It matches `d` against the pattern `pat` and the bindings are available in `t`.
If the pattern does not match, it returns `e` instead.
-/
macro "if " "let " pat:term " := " d:term " then " t:term " else " e:term : term =>
`(match $d:term with | $pat => $t | _ => $e)
@[inheritDoc cond] syntax (name := boolIfThenElse)
ppRealGroup(ppRealFill(ppIndent("bif " term " then") ppSpace term)
ppDedent(ppSpace) ppRealFill("else " term)) : term
macro_rules
| `(bif $c then $t else $e) => `(cond $c $t $e)
/--
Haskell-like pipe operator `<|`. `f <| x` means the same as the same as `f x`,
except that it parses `x` with lower precedence, which means that `f <| g <| x`
is interpreted as `f (g x)` rather than `(f g) x`.
-/
syntax:min term " <| " term:min : term
macro_rules
| `($f $args* <| $a) => `($f $args* $a)
| `($f <| $a) => `($f $a)
/--
Haskell-like pipe operator `|>`. `x |> f` means the same as the same as `f x`,
and it chains such that `x |> f |> g` is interpreted as `g (f x)`.
-/
syntax:min term " |> " term:min1 : term
macro_rules
| `($a |> $f $args*) => `($f $args* $a)
| `($a |> $f) => `($f $a)
/--
Alternative syntax for `<|`. `f $ x` means the same as the same as `f x`,
except that it parses `x` with lower precedence, which means that `f $ g $ x`
is interpreted as `f (g x)` rather than `(f g) x`.
-/
-- Note that we have a whitespace after `$` to avoid an ambiguity with antiquotations.
syntax:min term atomic(" $" ws) term:min : term
macro_rules
| `($f $args* $ $a) => `($f $args* $a)
| `($f $ $a) => `($f $a)
@[inheritDoc Subtype] syntax "{ " ident (" : " term)? " // " term " }" : term
macro_rules
| `({ $x : $type // $p }) => ``(Subtype (fun ($x:ident : $type) => $p))
| `({ $x // $p }) => ``(Subtype (fun ($x:ident : _) => $p))
/--
`without_expected_type t` instructs Lean to elaborate `t` without an expected type.
Recall that terms such as `match ... with ...` and `β¨...β©` will postpone elaboration until
expected type is known. So, `without_expected_type` is not effective in this case.
-/
macro "without_expected_type " x:term : term => `(let aux := $x; aux)
/--
The syntax `[a, b, c]` is shorthand for `a :: b :: c :: []`, or
`List.cons a (List.cons b (List.cons c List.nil))`. It allows conveniently constructing
list literals.
For lists of length at least 64, an alternative desugaring strategy is used
which uses let bindings as intermediates as in
`let left := [d, e, f]; a :: b :: c :: left` to avoid creating very deep expressions.
Note that this changes the order of evaluation, although it should not be observable
unless you use side effecting operations like `dbg_trace`.
-/
syntax "[" term,* "]" : term
/--
Auxiliary syntax for implementing `[$elem,*]` list literal syntax.
The syntax `%[a,b,c|tail]` constructs a value equivalent to `a::b::c::tail`.
It uses binary partitioning to construct a tree of intermediate let bindings as in
`let left := [d, e, f]; a :: b :: c :: left` to avoid creating very deep expressions.
-/
syntax "%[" term,* "|" term "]" : term
namespace Lean
macro_rules
| `([ $elems,* ]) => do
-- NOTE: we do not have `TSepArray.getElems` yet at this point
let rec expandListLit (i : Nat) (skip : Bool) (result : TSyntax `term) : MacroM Syntax := do
match i, skip with
| 0, _ => pure result
| i+1, true => expandListLit i false result
| i+1, false => expandListLit i true (β ``(List.cons $(β¨elems.elemsAndSeps.get! iβ©) $result))
if elems.elemsAndSeps.size < 64 then
expandListLit elems.elemsAndSeps.size false (β ``(List.nil))
else
`(%[ $elems,* | List.nil ])
-- Declare `this` as a keyword that unhygienically binds to a scope-less `this` assumption (or other binding).
-- The keyword prevents declaring a `this` binding except through metaprogramming, as is done by `have`/`show`.
/-- Special identifier introduced by "anonymous" `have : ...`, `suffices p ...` etc. -/
macro tk:"this" : term => return Syntax.ident tk.getHeadInfo "this".toSubstring `this []
/--
Category for carrying raw syntax trees between macros; any content is printed as is by the pretty printer.
The only accepted parser for this category is an antiquotation.
-/
declare_syntax_cat rawStx
instance : Coe Syntax (TSyntax `rawStx) where
coe stx := β¨stxβ©
/-- `with_annotate_term stx e` annotates the lexical range of `stx : Syntax` with term info for `e`. -/
scoped syntax (name := withAnnotateTerm) "with_annotate_term " rawStx ppSpace term : term
/--
The attribute `@[deprecated]` on a declaration indicates that the declaration
is discouraged for use in new code, and/or should be migrated away from in
existing code. It may be removed in a future version of the library.
`@[deprecated myBetterDef]` means that `myBetterDef` is the suggested replacement.
-/
syntax (name := deprecated) "deprecated " (ident)? : attr
/--
When `parent_dir` contains the current Lean file, `include_str "path" / "to" / "file"` becomes
a string literal with the contents of the file at `"parent_dir" / "path" / "to" / "file"`. If this
file cannot be read, elaboration fails.
-/
syntax (name := includeStr) "include_str" term : term
|
d425f8acb8352d3d6849ffd23d1b6cb653d85bba | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/run/exists.lean | 43a544e93fc404c8c7737c1cd7526c96707cd314 | [
"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 | 223 | lean | example : β x : Nat, x = x := by
exists 0
example : β x : Nat, β y : Nat, x > y := by
exists 1, 0
example : (x : Nat) Γ' (y : Nat) Γ' x > y := by
exists 1, 0
example : { x : Nat // x > 2 } := by
exists 3
|
30809fc948ebe4e7eff8bc0d4c37583e3e4e3184 | ba4ad8a778c69640c9cca8e5dcaeb40d4a10fa10 | /lean4/hello/Main.lean | fc5f68dd47573bebf0a4607c71b0d0e58ffe6afe | [] | no_license | tangentstorm/tangentlabs | 390ac60618bd913b567d20933dab70b84aac7151 | 137adbba6e7c35f8bb54b0786ada6c8c2ff6bc72 | refs/heads/master | 1,693,514,213,127 | 1,692,322,210,000 | 1,692,322,210,000 | 7,815,356 | 33 | 22 | null | 1,433,592,935,000 | 1,359,097,381,000 | Visual Basic | UTF-8 | Lean | false | false | 213 | lean | -- basic io demo
def chomp (s : String) := s.trimRight
def main : IO Unit := do
(β IO.getStdout).putStr "name> "
let input := chomp (β (β IO.getStdin).getLine)
IO.println s!"Hello, {input}!"
|
371fcf33782f90c721838c40a08891f762f783d6 | 6b2a480f27775cba4f3ae191b1c1387a29de586e | /group_rep_2/basic_definitions/sub_module.lean | 8e568de932353c952832f7a8809d2a2aca6a0ecc | [] | no_license | Or7ando/group_representation | a681de2e19d1930a1e1be573d6735a2f0b8356cb | 9b576984f17764ebf26c8caa2a542d248f1b50d2 | refs/heads/master | 1,662,413,107,324 | 1,590,302,389,000 | 1,590,302,389,000 | 258,130,829 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 3,764 | lean | import .group_representation
import .morphism
universe variables u v w
variables {G : Type u} {R : Type v} {M : Type w} [group G] [ring R] [add_comm_group M] [module R M]
namespace stability
variables {p : submodule R M}
/--
Technical lemma to deal with `submodule p` of `M`.
-/
lemma submodule_ext (x y : p) : (x : M) = (y : M) β x = y :=
begin
intros,rcases x,rcases y,congr, try {assumption},
end
/--
Let `Ο : G β* M ββ[R] M` a representation. A submodule `p` of `M` is `Ο-stable` when :
`β g β G, β x β p, Ο g x β p`. It induce a `sub-representation` : ` Res Ο p : G β* p ββ[R] p `
-/
class stable_submodule (Ο : group_representation G R M)(p : submodule R M) :=
(stability : β g : G, β x : M, x β p β Ο g x β p)
/--
`Trivial submodule` : `β₯` and `β€`
-/
def is_trivial (p : submodule R M) := (p = β€ β¨ p = β₯)
/--
`Irreducible Ο` : only `β₯` and `β€` for ` Ο-stable submodule`
-/
class Irreductible ( Ο : group_representation G R M) :=
(certif: β (p : submodule R M)[stable_submodule Ο p], is_trivial p)
def Trivial (Ο : group_representation G R M)(p : submodule R M) [Irreductible Ο] [stable_submodule Ο p]:=
Irreductible.certif Ο p
variables (Ο : group_representation G R M)
lemma stab [stable_submodule Ο p](g : G) {x : M} : (x β p ) β (Ο g x β p) :=
stable_submodule.stability g x
lemma map' (g : G) [stable_submodule Ο p] : submodule.map (Ο g) p β€ p := begin
rw submodule.le_def', intros x hyp, rw submodule.mem_map at hyp, rcases hyp with β¨y,hyp_y β©,
rw β hyp_y.2,
apply (stab Ο g), exact hyp_y.1, assumption,
end
lemma map (g : G) [stable_submodule Ο p] : submodule.map (Ο g) p = p :=
begin
apply le_antisymm, apply map',
rw submodule.le_def', intros x hyp_x, rw submodule.mem_map, use (Ο gβ»ΒΉ ) x, split,
apply stab Ο gβ»ΒΉ, exact hyp_x, assumption, change (Ο g β Ο gβ»ΒΉ ) x = _,
rw β map_comp, rw mul_inv_self, rw Ο.map_one, exact rfl,
end
/--
Restriction map : `res Ο : G β (p β p)`.
-/
def res [stable_submodule Ο p] : G β p β p := Ξ» g x, {
val := Ο g x,
property := stab Ο g x.property
}
variables [stable_submodule Ο p]
lemma res_add (g : G) (x y : p) : res Ο g (x+y) = res Ο g x + res Ο g y :=
begin
apply submodule_ext, change Ο _ _ = _,
erw (Ο g).map_add,
exact rfl,
end
lemma res_smul (g : G) (r : R) ( x : p) : res Ο g ( r β’ x) = r β’ res Ο g x :=
begin
apply submodule_ext, change Ο _ _ = _,
erw (Ο g).map_smul,
exact rfl,
end
/--
`res` is linear map.
-/
def res_linear [stable_submodule Ο p] (g : G) : p ββ[R]p := {
to_fun := res Ο g,
add := res_add Ο g,
smul := res_smul Ο g }
/--
` β g :G, res Ο g` has an inverse given by ` res Ο gβ»ΒΉ`.
-/
lemma res_mul (g1 g2 : G) : (res Ο (g1 * g2) : p β p) = res Ο g1 β (res Ο g2) :=
begin
ext, apply submodule_ext, change Ο (g1 * g2) x = _,
erw Ο.map_mul, exact rfl,
end
lemma res_one : (res Ο 1 : p β p) = id :=
begin
ext,apply submodule_ext, change Ο 1 x = _,
erw Ο.map_one, exact rfl,
end
/--
the restriction representation `G β* p ββ[R]p`
-/
def Res : group_representation G R p := {
to_fun := res_linear Ο ,
map_one' := begin ext,apply submodule_ext, change (Ο 1) x = _, rw Ο.map_one, exact rfl, end,
map_mul' :=
begin
intros g1 g2,
ext, apply submodule_ext,
change (Ο (g1 * g2)) x = _ , rw Ο.map_mul,
exact rfl,
end
}
def res.subtype : Res Ο βΆα΅£ Ο := {
β := submodule.subtype p,
commute := by {intros g, exact rfl}
}
end stability |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.