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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
096a1db43eb9f683c8c1c68fa21e4fd0ca894082 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /stage0/src/Lean/Meta/Offset.lean | cabaa53194d05b4a121bf50245ec61ddbf4d1b14 | [
"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,562 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Data.LBool
import Lean.Meta.InferType
import Lean.Meta.AppBuilder
namespace Lean.Meta
private abbrev withInstantiatedMVars (e : Expr) (k : Expr → OptionT MetaM α) : OptionT MetaM α := do
let eNew ← instantiateMVars e
if eNew.getAppFn.isMVar then
failure
else
k eNew
/--
Evaluate simple `Nat` expressions.
Remark: this method assumes the given expression has type `Nat`. -/
partial def evalNat : Expr → OptionT MetaM Nat
| Expr.lit (Literal.natVal n) _ => return n
| Expr.mdata _ e _ => evalNat e
| Expr.const `Nat.zero .. => return 0
| e@(Expr.app ..) => visit e
| e@(Expr.mvar ..) => visit e
| _ => failure
where
isNatProjInst (c : Name) (nargs : Nat) : Bool :=
(nargs == 4 && (c == ``Add.add || c == ``Sub.sub || c == ``Mul.mul))
|| (nargs == 6 && (c == ``HAdd.hAdd || c == ``HSub.hSub || c == ``HMul.hMul))
|| (nargs == 3 && c == ``OfNat.ofNat)
visit e := do
let f := e.getAppFn
match f with
| Expr.mvar .. => withInstantiatedMVars e evalNat
| Expr.const c _ _ =>
let nargs := e.getAppNumArgs
if c == ``Nat.succ && nargs == 1 then
let v ← evalNat (e.getArg! 0)
return v+1
else if c == ``Nat.add && nargs == 2 then
let v₁ ← evalNat (e.getArg! 0)
let v₂ ← evalNat (e.getArg! 1)
return v₁ + v₂
else if c == ``Nat.sub && nargs == 2 then
let v₁ ← evalNat (e.getArg! 0)
let v₂ ← evalNat (e.getArg! 1)
return v₁ - v₂
else if c == ``Nat.mul && nargs == 2 then
let v₁ ← evalNat (e.getArg! 0)
let v₂ ← evalNat (e.getArg! 1)
return v₁ * v₂
else if isNatProjInst c nargs then
evalNat (← unfoldProjInst? e)
else
failure
| _ => failure
/- Quick function for converting `e` into `s + k` s.t. `e` is definitionally equal to `Nat.add s k`. -/
private partial def getOffsetAux : Expr → Bool → OptionT MetaM (Expr × Nat)
| e@(Expr.app _ a _), top => do
let f := e.getAppFn
match f with
| Expr.mvar .. => withInstantiatedMVars e (getOffsetAux · top)
| Expr.const c _ _ =>
let nargs := e.getAppNumArgs
if c == ``Nat.succ && nargs == 1 then
let (s, k) ← getOffsetAux a false
pure (s, k+1)
else if c == ``Nat.add && nargs == 2 then
let v ← evalNat (e.getArg! 1)
let (s, k) ← getOffsetAux (e.getArg! 0) false
pure (s, k+v)
else if (c == ``Add.add && nargs == 4) || (c == ``HAdd.hAdd && nargs == 6) then
getOffsetAux (← unfoldProjInst? e) false
else if top then failure else pure (e, 0)
| _ => if top then failure else pure (e, 0)
| e, top => if top then failure else pure (e, 0)
private def getOffset (e : Expr) : OptionT MetaM (Expr × Nat) :=
getOffsetAux e true
private partial def isOffset : Expr → OptionT MetaM (Expr × Nat)
| e@(Expr.app _ a _) =>
let f := e.getAppFn
match f with
| Expr.mvar .. => withInstantiatedMVars e isOffset
| Expr.const c _ _ =>
let nargs := e.getAppNumArgs
if (c == ``Nat.succ && nargs == 1) || (c == ``Nat.add && nargs == 2) || (c == ``Add.add && nargs == 4) || (c == ``HAdd.hAdd && nargs == 6) then
getOffset e
else
failure
| _ => failure
| _ => failure
private def isNatZero (e : Expr) : MetaM Bool := do
match (← evalNat e) with
| some v => v == 0
| _ => false
private def mkOffset (e : Expr) (offset : Nat) : MetaM Expr := do
if offset == 0 then
return e
else if (← isNatZero e) then
return mkNatLit offset
else
mkAdd e (mkNatLit offset)
def isDefEqOffset (s t : Expr) : MetaM LBool := do
let ifNatExpr (x : MetaM LBool) : MetaM LBool := do
let type ← inferType s
-- Remark: we use `withNewMCtxDepth` to make sure we don't assing metavariables when performing the `isDefEq` test
if (← withNewMCtxDepth <| Meta.isExprDefEqAux type (mkConst ``Nat)) then
x
else
return LBool.undef
let isDefEq (s t) : MetaM LBool :=
ifNatExpr <| toLBoolM <| Meta.isExprDefEqAux s t
if !(← getConfig).offsetCnstrs then
return LBool.undef
else
match (← isOffset s) with
| some (s, k₁) =>
match (← isOffset t) with
| some (t, k₂) => -- s+k₁ =?= t+k₂
if k₁ == k₂ then
isDefEq s t
else if k₁ < k₂ then
isDefEq s (← mkOffset t (k₂ - k₁))
else
isDefEq (← mkOffset s (k₁ - k₂)) t
| none =>
match (← evalNat t) with
| some v₂ => -- s+k₁ =?= v₂
if v₂ ≥ k₁ then
isDefEq s (mkNatLit <| v₂ - k₁)
else
ifNatExpr <| return LBool.false
| none =>
return LBool.undef
| none =>
match (← evalNat s) with
| some v₁ =>
match (← isOffset t) with
| some (t, k₂) => -- v₁ =?= t+k₂
if v₁ ≥ k₂ then
isDefEq (mkNatLit <| v₁ - k₂) t
else
ifNatExpr <| return LBool.false
| none =>
match (← evalNat t) with
| some v₂ => ifNatExpr <| return (v₁ == v₂).toLBool -- v₁ =?= v₂
| none => return LBool.undef
| none => return LBool.undef
end Lean.Meta
|
4b8a043eb84f86dfe7ec9eca7d0f5a5add1be051 | 853df553b1d6ca524e3f0a79aedd32dde5d27ec3 | /src/data/rat/basic.lean | 52ef5365449a04815051c8de9bab676821798a35 | [
"Apache-2.0"
] | permissive | DanielFabian/mathlib | efc3a50b5dde303c59eeb6353ef4c35a345d7112 | f520d07eba0c852e96fe26da71d85bf6d40fcc2a | refs/heads/master | 1,668,739,922,971 | 1,595,201,756,000 | 1,595,201,756,000 | 279,469,476 | 0 | 0 | null | 1,594,696,604,000 | 1,594,696,604,000 | null | UTF-8 | Lean | false | false | 26,495 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro
-/
import data.int.sqrt
import data.equiv.encodable
import algebra.group
import algebra.euclidean_domain
import algebra.ordered_field
/-!
# Basics for the Rational Numbers
## Summary
We define a rational number `q` as a structure `{ num, denom, pos, cop }`, where
- `num` is the numerator of `q`,
- `denom` is the denominator of `q`,
- `pos` is a proof that `denom > 0`, and
- `cop` is a proof `num` and `denom` are coprime.
We then define the expected (discrete) field structure on `ℚ` and prove basic lemmas about it.
Moreoever, we provide the expected casts from `ℕ` and `ℤ` into `ℚ`, i.e. `(↑n : ℚ) = n / 1`.
## Main Definitions
- `rat` is the structure encoding `ℚ`.
- `rat.mk n d` constructs a rational number `q = n / d` from `n d : ℤ`.
## Notations
- `/.` is infix notation for `rat.mk`.
## Tags
rat, rationals, field, ℚ, numerator, denominator, num, denom
-/
/-- `rat`, or `ℚ`, is the type of rational numbers. It is defined
as the set of pairs ⟨n, d⟩ of integers such that `d` is positive and `n` and
`d` are coprime. This representation is preferred to the quotient
because without periodic reduction, the numerator and denominator can grow
exponentially (for example, adding 1/2 to itself repeatedly). -/
structure rat := mk' ::
(num : ℤ)
(denom : ℕ)
(pos : 0 < denom)
(cop : num.nat_abs.coprime denom)
notation `ℚ` := rat
namespace rat
protected def repr : ℚ → string
| ⟨n, d, _, _⟩ := if d = 1 then _root_.repr n else
_root_.repr n ++ "/" ++ _root_.repr d
instance : has_repr ℚ := ⟨rat.repr⟩
instance : has_to_string ℚ := ⟨rat.repr⟩
meta instance : has_to_format ℚ := ⟨coe ∘ rat.repr⟩
instance : encodable ℚ := encodable.of_equiv (Σ n : ℤ, {d : ℕ // 0 < d ∧ n.nat_abs.coprime d})
⟨λ ⟨a, b, c, d⟩, ⟨a, b, c, d⟩, λ⟨a, b, c, d⟩, ⟨a, b, c, d⟩,
λ ⟨a, b, c, d⟩, rfl, λ⟨a, b, c, d⟩, rfl⟩
/-- Embed an integer as a rational number -/
def of_int (n : ℤ) : ℚ :=
⟨n, 1, nat.one_pos, nat.coprime_one_right _⟩
instance : has_zero ℚ := ⟨of_int 0⟩
instance : has_one ℚ := ⟨of_int 1⟩
instance : inhabited ℚ := ⟨0⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ+` (not necessarily coprime) -/
def mk_pnat (n : ℤ) : ℕ+ → ℚ | ⟨d, dpos⟩ :=
let n' := n.nat_abs, g := n'.gcd d in
⟨n / g, d / g, begin
apply (nat.le_div_iff_mul_le _ _ (nat.gcd_pos_of_pos_right _ dpos)).2,
simp, exact nat.le_of_dvd dpos (nat.gcd_dvd_right _ _)
end, begin
have : int.nat_abs (n / ↑g) = n' / g,
{ cases int.nat_abs_eq n with e e; rw e, { refl },
rw [int.neg_div_of_dvd, int.nat_abs_neg], { refl },
exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) },
rw this,
exact nat.coprime_div_gcd_div_gcd (nat.gcd_pos_of_pos_right _ dpos)
end⟩
/-- Form the quotient `n / d` where `n:ℤ` and `d:ℕ`. In the case `d = 0`, we
define `n / 0 = 0` by convention. -/
def mk_nat (n : ℤ) (d : ℕ) : ℚ :=
if d0 : d = 0 then 0 else mk_pnat n ⟨d, nat.pos_of_ne_zero d0⟩
/-- Form the quotient `n / d` where `n d : ℤ`. -/
def mk : ℤ → ℤ → ℚ
| n (d : ℕ) := mk_nat n d
| n -[1+ d] := mk_pnat (-n) d.succ_pnat
localized "infix ` /. `:70 := rat.mk" in rat
theorem mk_pnat_eq (n d h) : mk_pnat n ⟨d, h⟩ = n /. d :=
by change n /. d with dite _ _ _; simp [ne_of_gt h]
theorem mk_nat_eq (n d) : mk_nat n d = n /. d := rfl
@[simp] theorem mk_zero (n) : n /. 0 = 0 := rfl
@[simp] theorem zero_mk_pnat (n) : mk_pnat 0 n = 0 :=
by cases n; simp [mk_pnat]; change int.nat_abs 0 with 0; simp *; refl
@[simp] theorem zero_mk_nat (n) : mk_nat 0 n = 0 :=
by by_cases n = 0; simp [*, mk_nat]
@[simp] theorem zero_mk (n) : 0 /. n = 0 :=
by cases n; simp [mk]
private lemma gcd_abs_dvd_left {a b} : (nat.gcd (int.nat_abs a) b : ℤ) ∣ a :=
int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ nat.gcd_dvd_left (int.nat_abs a) b
@[simp] theorem mk_eq_zero {a b : ℤ} (b0 : b ≠ 0) : a /. b = 0 ↔ a = 0 :=
begin
constructor; intro h; [skip, {subst a, simp}],
have : ∀ {a b}, mk_pnat a b = 0 → a = 0,
{ intros a b e, cases b with b h,
injection e with e,
apply int.eq_mul_of_div_eq_right gcd_abs_dvd_left e },
cases b with b; simp [mk, mk_nat] at h,
{ simp [mt (congr_arg int.of_nat) b0] at h,
exact this h },
{ apply neg_injective, simp [this h] }
end
theorem mk_eq : ∀ {a b c d : ℤ} (hb : b ≠ 0) (hd : d ≠ 0),
a /. b = c /. d ↔ a * d = c * b :=
suffices ∀ a b c d hb hd, mk_pnat a ⟨b, hb⟩ = mk_pnat c ⟨d, hd⟩ ↔ a * d = c * b,
begin
intros, cases b with b b; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hb],
all_goals {
cases d with d d; simp [mk, mk_nat, nat.succ_pnat],
simp [mt (congr_arg int.of_nat) hd],
all_goals { rw this, try {refl} } },
{ change a * ↑(d.succ) = -c * ↑b ↔ a * -(d.succ) = c * b,
constructor; intro h; apply neg_injective; simpa [left_distrib, neg_add_eq_iff_eq_add,
eq_neg_iff_add_eq_zero, neg_eq_iff_add_eq_zero] using h },
{ change -a * ↑d = c * b.succ ↔ a * d = c * -b.succ,
constructor; intro h; apply neg_injective; simpa [left_distrib, eq_comm] using h },
{ change -a * d.succ = -c * b.succ ↔ a * -d.succ = c * -b.succ,
simp [left_distrib, sub_eq_add_neg], cc }
end,
begin
intros, simp [mk_pnat], constructor; intro h,
{ cases h with ha hb,
have ha, {
have dv := @gcd_abs_dvd_left,
have := int.eq_mul_of_div_eq_right dv ha,
rw ← int.mul_div_assoc _ dv at this,
exact int.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm },
have hb, {
have dv := λ {a b}, nat.gcd_dvd_right (int.nat_abs a) b,
have := nat.eq_mul_of_div_eq_right dv hb,
rw ← nat.mul_div_assoc _ dv at this,
exact nat.eq_mul_of_div_eq_left (dvd_mul_of_dvd_right dv _) this.symm },
have m0 : (a.nat_abs.gcd b * c.nat_abs.gcd d : ℤ) ≠ 0, {
refine int.coe_nat_ne_zero.2 (ne_of_gt _),
apply mul_pos; apply nat.gcd_pos_of_pos_right; assumption },
apply mul_right_cancel' m0,
simpa [mul_comm, mul_left_comm] using
congr (congr_arg (*) ha.symm) (congr_arg coe hb) },
{ suffices : ∀ a c, a * d = c * b →
a / a.gcd b = c / c.gcd d ∧ b / a.gcd b = d / c.gcd d,
{ cases this a.nat_abs c.nat_abs
(by simpa [int.nat_abs_mul] using congr_arg int.nat_abs h) with h₁ h₂,
have hs := congr_arg int.sign h,
simp [int.sign_eq_one_of_pos (int.coe_nat_lt.2 hb),
int.sign_eq_one_of_pos (int.coe_nat_lt.2 hd)] at hs,
conv in a { rw ← int.sign_mul_nat_abs a },
conv in c { rw ← int.sign_mul_nat_abs c },
rw [int.mul_div_assoc, int.mul_div_assoc],
exact ⟨congr (congr_arg (*) hs) (congr_arg coe h₁), h₂⟩,
all_goals { exact int.coe_nat_dvd.2 (nat.gcd_dvd_left _ _) } },
intros a c h,
suffices bd : b / a.gcd b = d / c.gcd d,
{ refine ⟨_, bd⟩,
apply nat.eq_of_mul_eq_mul_left hb,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _), mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), bd,
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), h, mul_comm,
nat.mul_div_assoc _ (nat.gcd_dvd_left _ _)] },
suffices : ∀ {a c : ℕ} (b>0) (d>0),
a * d = c * b → b / a.gcd b ≤ d / c.gcd d,
{ exact le_antisymm (this _ hb _ hd h) (this _ hd _ hb h.symm) },
intros a c b hb d hd h,
have gb0 := nat.gcd_pos_of_pos_right a hb,
have gd0 := nat.gcd_pos_of_pos_right c hd,
apply nat.le_of_dvd,
apply (nat.le_div_iff_mul_le _ _ gd0).2,
simp, apply nat.le_of_dvd hd (nat.gcd_dvd_right _ _),
apply (nat.coprime_div_gcd_div_gcd gb0).symm.dvd_of_dvd_mul_left,
refine ⟨c / c.gcd d, _⟩,
rw [← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
← nat.mul_div_assoc _ (nat.gcd_dvd_right _ _)],
apply congr_arg (/ c.gcd d),
rw [mul_comm, ← nat.mul_div_assoc _ (nat.gcd_dvd_left _ _),
mul_comm, h, nat.mul_div_assoc _ (nat.gcd_dvd_right _ _), mul_comm] }
end
@[simp] theorem div_mk_div_cancel_left {a b c : ℤ} (c0 : c ≠ 0) :
(a * c) /. (b * c) = a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp },
apply (mk_eq (mul_ne_zero b0 c0) b0).2, simp [mul_comm, mul_assoc]
end
@[simp] theorem num_denom : ∀ {a : ℚ}, a.num /. a.denom = a
| ⟨n, d, h, (c:_=1)⟩ := show mk_nat n d = _,
by simp [mk_nat, ne_of_gt h, mk_pnat, c]
theorem num_denom' {n d h c} : (⟨n, d, h, c⟩ : ℚ) = n /. d := num_denom.symm
theorem of_int_eq_mk (z : ℤ) : of_int z = z /. 1 := num_denom'
@[elab_as_eliminator] def {u} num_denom_cases_on {C : ℚ → Sort u}
: ∀ (a : ℚ) (H : ∀ n d, 0 < d → (int.nat_abs n).coprime d → C (n /. d)), C a
| ⟨n, d, h, c⟩ H := by rw num_denom'; exact H n d h c
@[elab_as_eliminator] def {u} num_denom_cases_on' {C : ℚ → Sort u}
(a : ℚ) (H : ∀ (n:ℤ) (d:ℕ), d ≠ 0 → C (n /. d)) : C a :=
num_denom_cases_on a $ λ n d h c,
H n d $ ne_of_gt h
theorem num_dvd (a) {b : ℤ} (b0 : b ≠ 0) : (a /. b).num ∣ a :=
begin
cases e : a /. b with n d h c,
rw [rat.num_denom', rat.mk_eq b0
(ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.nat_abs_dvd.1 $ int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $
c.dvd_of_dvd_mul_right _),
have := congr_arg int.nat_abs e,
simp [int.nat_abs_mul, int.nat_abs_of_nat] at this, simp [this]
end
theorem denom_dvd (a b : ℤ) : ((a /. b).denom : ℤ) ∣ b :=
begin
by_cases b0 : b = 0, {simp [b0]},
cases e : a /. b with n d h c,
rw [num_denom', mk_eq b0 (ne_of_gt (int.coe_nat_pos.2 h))] at e,
refine (int.dvd_nat_abs.1 $ int.coe_nat_dvd.2 $ c.symm.dvd_of_dvd_mul_left _),
rw [← int.nat_abs_mul, ← int.coe_nat_dvd, int.dvd_nat_abs, ← e], simp
end
protected def add : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * d₂ + n₂ * d₁) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_add ℚ := ⟨rat.add⟩
theorem lift_binop_eq (f : ℚ → ℚ → ℚ) (f₁ : ℤ → ℤ → ℤ → ℤ → ℤ) (f₂ : ℤ → ℤ → ℤ → ℤ → ℤ)
(fv : ∀ {n₁ d₁ h₁ c₁ n₂ d₂ h₂ c₂},
f ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ = f₁ n₁ d₁ n₂ d₂ /. f₂ n₁ d₁ n₂ d₂)
(f0 : ∀ {n₁ d₁ n₂ d₂} (d₁0 : d₁ ≠ 0) (d₂0 : d₂ ≠ 0), f₂ n₁ d₁ n₂ d₂ ≠ 0)
(a b c d : ℤ) (b0 : b ≠ 0) (d0 : d ≠ 0)
(H : ∀ {n₁ d₁ n₂ d₂} (h₁ : a * d₁ = n₁ * b) (h₂ : c * d₂ = n₂ * d),
f₁ n₁ d₁ n₂ d₂ * f₂ a b c d = f₁ a b c d * f₂ n₁ d₁ n₂ d₂) :
f (a /. b) (c /. d) = f₁ a b c d /. f₂ a b c d :=
begin
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
generalize hc : c /. d = x, cases x with n₂ d₂ h₂ c₂, rw num_denom' at hc,
rw fv,
have d₁0 := ne_of_gt (int.coe_nat_lt.2 h₁),
have d₂0 := ne_of_gt (int.coe_nat_lt.2 h₂),
exact (mk_eq (f0 d₁0 d₂0) (f0 b0 d0)).2 (H ((mk_eq b0 d₁0).1 ha) ((mk_eq d0 d₂0).1 hc))
end
@[simp] theorem add_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b + c /. d = (a * d + c * b) /. (b * d) :=
begin
apply lift_binop_eq rat.add; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
calc (n₁ * d₂ + n₂ * d₁) * (b * d) =
(n₁ * b) * d₂ * d + (n₂ * d) * (d₁ * b) : by simp [mul_add, mul_comm, mul_left_comm]
... = (a * d₁) * d₂ * d + (c * d₂) * (d₁ * b) : by rw [h₁, h₂]
... = (a * d + c * b) * (d₁ * d₂) : by simp [mul_add, mul_comm, mul_left_comm]
end
protected def neg : ℚ → ℚ
| ⟨n, d, h, c⟩ := ⟨-n, d, h, by simp [c]⟩
instance : has_neg ℚ := ⟨rat.neg⟩
@[simp] theorem neg_def {a b : ℤ} : -(a /. b) = -a /. b :=
begin
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n₁ d₁ h₁ c₁, rw num_denom' at ha,
show rat.mk' _ _ _ _ = _, rw num_denom',
have d0 := ne_of_gt (int.coe_nat_lt.2 h₁),
apply (mk_eq d0 b0).2, have h₁ := (mk_eq b0 d0).1 ha,
simp only [neg_mul_eq_neg_mul_symm, congr_arg has_neg.neg h₁]
end
protected def mul : ℚ → ℚ → ℚ
| ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := mk_pnat (n₁ * n₂) ⟨d₁ * d₂, mul_pos h₁ h₂⟩
instance : has_mul ℚ := ⟨rat.mul⟩
@[simp] theorem mul_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
(a /. b) * (c /. d) = (a * c) /. (b * d) :=
begin
apply lift_binop_eq rat.mul; intros; try {assumption},
{ apply mk_pnat_eq },
{ apply mul_ne_zero d₁0 d₂0 },
cc
end
protected def inv : ℚ → ℚ
| ⟨(n+1:ℕ), d, h, c⟩ := ⟨d, n+1, n.succ_pos, c.symm⟩
| ⟨0, d, h, c⟩ := 0
| ⟨-[1+ n], d, h, c⟩ := ⟨-d, n+1, n.succ_pos, nat.coprime.symm $ by simp; exact c⟩
instance : has_inv ℚ := ⟨rat.inv⟩
@[simp] theorem inv_def {a b : ℤ} : (a /. b)⁻¹ = b /. a :=
begin
by_cases a0 : a = 0, { subst a0, simp, refl },
by_cases b0 : b = 0, { subst b0, simp, refl },
generalize ha : a /. b = x, cases x with n d h c, rw num_denom' at ha,
refine eq.trans (_ : rat.inv ⟨n, d, h, c⟩ = d /. n) _,
{ cases n with n; [cases n with n, skip],
{ refl },
{ change int.of_nat n.succ with (n+1:ℕ),
unfold rat.inv, rw num_denom' },
{ unfold rat.inv, rw num_denom', refl } },
have n0 : n ≠ 0,
{ refine mt (λ (n0 : n = 0), _) a0,
subst n0, simp at ha,
exact (mk_eq_zero b0).1 ha },
have d0 := ne_of_gt (int.coe_nat_lt.2 h),
have ha := (mk_eq b0 d0).1 ha,
apply (mk_eq n0 a0).2,
cc
end
variables (a b c : ℚ)
protected theorem add_zero : a + 0 = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem zero_add : 0 + a = a :=
num_denom_cases_on' a $ λ n d h,
by rw [← zero_mk d]; simp [h, -zero_mk]
protected theorem add_comm : a + b = b + a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂]; cc
protected theorem add_assoc : a + b + c = a + (b + c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_add, mul_comm, mul_left_comm, add_left_comm, add_assoc]
protected theorem add_left_neg : -a + a = 0 :=
num_denom_cases_on' a $ λ n d h,
by simp [h]
protected theorem mul_one : a * 1 = a :=
num_denom_cases_on' a $ λ n d h,
by change (1:ℚ) with 1 /. 1; simp [h]
protected theorem one_mul : 1 * a = a :=
num_denom_cases_on' a $ λ n d h,
by change (1:ℚ) with 1 /. 1; simp [h]
protected theorem mul_comm : a * b = b * a :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
by simp [h₁, h₂, mul_comm]
protected theorem mul_assoc : a * b * c = a * (b * c) :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero, mul_comm, mul_left_comm]
protected theorem add_mul : (a + b) * c = a * c + b * c :=
num_denom_cases_on' a $ λ n₁ d₁ h₁,
num_denom_cases_on' b $ λ n₂ d₂ h₂,
num_denom_cases_on' c $ λ n₃ d₃ h₃,
by simp [h₁, h₂, h₃, mul_ne_zero];
refine (div_mk_div_cancel_left (int.coe_nat_ne_zero.2 h₃)).symm.trans _;
simp [mul_add, mul_comm, mul_assoc, mul_left_comm]
protected theorem mul_add : a * (b + c) = a * b + a * c :=
by rw [rat.mul_comm, rat.add_mul, rat.mul_comm, rat.mul_comm c a]
protected theorem zero_ne_one : 0 ≠ (1:ℚ) :=
mt (λ (h : 0 = 1 /. 1), (mk_eq_zero one_ne_zero).1 h.symm) one_ne_zero
protected theorem mul_inv_cancel : a ≠ 0 → a * a⁻¹ = 1 :=
num_denom_cases_on' a $ λ n d h a0,
have n0 : n ≠ 0, from mt (by intro e; subst e; simp) a0,
by simp [h, n0, mul_comm]; exact
eq.trans (by simp) (@div_mk_div_cancel_left 1 1 _ n0)
protected theorem inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 :=
eq.trans (rat.mul_comm _ _) (rat.mul_inv_cancel _ h)
instance : decidable_eq ℚ := by tactic.mk_dec_eq_instance
instance : field ℚ :=
{ zero := 0,
add := rat.add,
neg := rat.neg,
one := 1,
mul := rat.mul,
inv := rat.inv,
zero_add := rat.zero_add,
add_zero := rat.add_zero,
add_comm := rat.add_comm,
add_assoc := rat.add_assoc,
add_left_neg := rat.add_left_neg,
mul_one := rat.mul_one,
one_mul := rat.one_mul,
mul_comm := rat.mul_comm,
mul_assoc := rat.mul_assoc,
left_distrib := rat.mul_add,
right_distrib := rat.add_mul,
exists_pair_ne := ⟨0, 1, rat.zero_ne_one⟩,
mul_inv_cancel := rat.mul_inv_cancel,
inv_zero := rfl }
/- Extra instances to short-circuit type class resolution -/
instance : division_ring ℚ := by apply_instance
instance : integral_domain ℚ := by apply_instance
-- TODO(Mario): this instance slows down data.real.basic
--instance : domain ℚ := by apply_instance
instance : nontrivial ℚ := by apply_instance
instance : comm_ring ℚ := by apply_instance
--instance : ring ℚ := by apply_instance
instance : comm_semiring ℚ := by apply_instance
instance : semiring ℚ := by apply_instance
instance : add_comm_group ℚ := by apply_instance
instance : add_group ℚ := by apply_instance
instance : add_comm_monoid ℚ := by apply_instance
instance : add_monoid ℚ := by apply_instance
instance : add_left_cancel_semigroup ℚ := by apply_instance
instance : add_right_cancel_semigroup ℚ := by apply_instance
instance : add_comm_semigroup ℚ := by apply_instance
instance : add_semigroup ℚ := by apply_instance
instance : comm_monoid ℚ := by apply_instance
instance : monoid ℚ := by apply_instance
instance : comm_semigroup ℚ := by apply_instance
instance : semigroup ℚ := by apply_instance
theorem sub_def {a b c d : ℤ} (b0 : b ≠ 0) (d0 : d ≠ 0) :
a /. b - c /. d = (a * d - c * b) /. (b * d) :=
by simp [b0, d0, sub_eq_add_neg]
@[simp] lemma denom_neg_eq_denom : ∀ q : ℚ, (-q).denom = q.denom
| ⟨_, d, _, _⟩ := rfl
@[simp] lemma num_neg_eq_neg_num : ∀ q : ℚ, (-q).num = -(q.num)
| ⟨n, _, _, _⟩ := rfl
@[simp] lemma num_zero : rat.num 0 = 0 := rfl
lemma zero_of_num_zero {q : ℚ} (hq : q.num = 0) : q = 0 :=
have q = q.num /. q.denom, from num_denom.symm,
by simpa [hq]
lemma zero_iff_num_zero {q : ℚ} : q = 0 ↔ q.num = 0 :=
⟨λ _, by simp *, zero_of_num_zero⟩
lemma num_ne_zero_of_ne_zero {q : ℚ} (h : q ≠ 0) : q.num ≠ 0 :=
assume : q.num = 0,
h $ zero_of_num_zero this
@[simp] lemma num_one : (1 : ℚ).num = 1 := rfl
@[simp] lemma denom_one : (1 : ℚ).denom = 1 := rfl
lemma denom_ne_zero (q : ℚ) : q.denom ≠ 0 :=
ne_of_gt q.pos
lemma eq_iff_mul_eq_mul {p q : ℚ} : p = q ↔ p.num * q.denom = q.num * p.denom :=
begin
conv_lhs { rw [←(@num_denom p), ←(@num_denom q)] },
apply rat.mk_eq,
{ exact_mod_cast p.denom_ne_zero },
{ exact_mod_cast q.denom_ne_zero }
end
lemma mk_num_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : n ≠ 0 :=
assume : n = 0,
hq $ by simpa [this] using hqnd
lemma mk_denom_ne_zero_of_ne_zero {q : ℚ} {n d : ℤ} (hq : q ≠ 0) (hqnd : q = n /. d) : d ≠ 0 :=
assume : d = 0,
hq $ by simpa [this] using hqnd
lemma mk_ne_zero_of_ne_zero {n d : ℤ} (h : n ≠ 0) (hd : d ≠ 0) : n /. d ≠ 0 :=
assume : n /. d = 0,
h $ (mk_eq_zero hd).1 this
lemma mul_num_denom (q r : ℚ) : q * r = (q.num * r.num) /. ↑(q.denom * r.denom) :=
have hq' : (↑q.denom : ℤ) ≠ 0, by have := denom_ne_zero q; simpa,
have hr' : (↑r.denom : ℤ) ≠ 0, by have := denom_ne_zero r; simpa,
suffices (q.num /. ↑q.denom) * (r.num /. ↑r.denom) = (q.num * r.num) /. ↑(q.denom * r.denom),
by simpa using this,
by simp [mul_def hq' hr', -num_denom]
lemma div_num_denom (q r : ℚ) : q / r = (q.num * r.denom) /. (q.denom * r.num) :=
if hr : r.num = 0 then
have hr' : r = 0, from zero_of_num_zero hr,
by simp *
else
calc q / r = q * r⁻¹ : div_eq_mul_inv
... = (q.num /. q.denom) * (r.num /. r.denom)⁻¹ : by simp
... = (q.num /. q.denom) * (r.denom /. r.num) : by rw inv_def
... = (q.num * r.denom) /. (q.denom * r.num) : mul_def (by simpa using denom_ne_zero q) hr
lemma num_denom_mk {q : ℚ} {n d : ℤ} (hn : n ≠ 0) (hd : d ≠ 0) (qdf : q = n /. d) :
∃ c : ℤ, n = c * q.num ∧ d = c * q.denom :=
have hq : q ≠ 0, from
assume : q = 0,
hn $ (rat.mk_eq_zero hd).1 (by cc),
have q.num /. q.denom = n /. d, by rwa [num_denom],
have q.num * d = n * ↑(q.denom), from (rat.mk_eq (by simp [rat.denom_ne_zero]) hd).1 this,
begin
existsi n / q.num,
have hqdn : q.num ∣ n, begin rw qdf, apply rat.num_dvd, assumption end,
split,
{ rw int.div_mul_cancel hqdn },
{ apply int.eq_mul_div_of_mul_eq_mul_of_dvd_left,
{ apply rat.num_ne_zero_of_ne_zero hq },
repeat { assumption } }
end
theorem mk_pnat_num (n : ℤ) (d : ℕ+) :
(mk_pnat n d).num = n / nat.gcd n.nat_abs d :=
by cases d; refl
theorem mk_pnat_denom (n : ℤ) (d : ℕ+) :
(mk_pnat n d).denom = d / nat.gcd n.nat_abs d :=
by cases d; refl
theorem mul_num (q₁ q₂ : ℚ) : (q₁ * q₂).num =
(q₁.num * q₂.num) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) :=
by cases q₁; cases q₂; refl
theorem mul_denom (q₁ q₂ : ℚ) : (q₁ * q₂).denom =
(q₁.denom * q₂.denom) / nat.gcd (q₁.num * q₂.num).nat_abs (q₁.denom * q₂.denom) :=
by cases q₁; cases q₂; refl
theorem mul_self_num (q : ℚ) : (q * q).num = q.num * q.num :=
by rw [mul_num, int.nat_abs_mul, nat.coprime.gcd_eq_one, int.coe_nat_one, int.div_one];
exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop)
theorem mul_self_denom (q : ℚ) : (q * q).denom = q.denom * q.denom :=
by rw [rat.mul_denom, int.nat_abs_mul, nat.coprime.gcd_eq_one, nat.div_one];
exact (q.cop.mul_right q.cop).mul (q.cop.mul_right q.cop)
lemma add_num_denom (q r : ℚ) : q + r =
((q.num * r.denom + q.denom * r.num : ℤ)) /. (↑q.denom * ↑r.denom : ℤ) :=
have hqd : (q.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 q.3,
have hrd : (r.denom : ℤ) ≠ 0, from int.coe_nat_ne_zero_iff_pos.2 r.3,
by conv_lhs { rw [←@num_denom q, ←@num_denom r, rat.add_def hqd hrd] };
simp [mul_comm]
section casts
theorem coe_int_eq_mk : ∀ (z : ℤ), ↑z = z /. 1
| (n : ℕ) := show (n:ℚ) = n /. 1,
by induction n with n IH n; simp [*, show (1:ℚ) = 1 /. 1, from rfl]
| -[1+ n] := show (-(n + 1) : ℚ) = -[1+ n] /. 1, begin
induction n with n IH, {refl},
show -(n + 1 + 1 : ℚ) = -[1+ n.succ] /. 1,
rw [neg_add, IH],
simpa [show -1 = (-1) /. 1, from rfl]
end
theorem mk_eq_div (n d : ℤ) : n /. d = ((n : ℚ) / d) :=
begin
by_cases d0 : d = 0, {simp [d0, div_zero]},
simp [division_def, coe_int_eq_mk, mul_def one_ne_zero d0]
end
theorem coe_int_eq_of_int (z : ℤ) : ↑z = of_int z :=
(coe_int_eq_mk z).trans (of_int_eq_mk z).symm
@[simp, norm_cast] theorem coe_int_num (n : ℤ) : (n : ℚ).num = n :=
by rw coe_int_eq_of_int; refl
@[simp, norm_cast] theorem coe_int_denom (n : ℤ) : (n : ℚ).denom = 1 :=
by rw coe_int_eq_of_int; refl
lemma coe_int_num_of_denom_eq_one {q : ℚ} (hq : q.denom = 1) : ↑(q.num) = q :=
by { conv_rhs { rw [←(@num_denom q), hq] }, rw [coe_int_eq_mk], refl }
instance : can_lift ℚ ℤ :=
⟨coe, λ q, q.denom = 1, λ q hq, ⟨q.num, coe_int_num_of_denom_eq_one hq⟩⟩
theorem coe_nat_eq_mk (n : ℕ) : ↑n = n /. 1 :=
by rw [← int.cast_coe_nat, coe_int_eq_mk]
@[simp, norm_cast] theorem coe_nat_num (n : ℕ) : (n : ℚ).num = n :=
by rw [← int.cast_coe_nat, coe_int_num]
@[simp, norm_cast] theorem coe_nat_denom (n : ℕ) : (n : ℚ).denom = 1 :=
by rw [← int.cast_coe_nat, coe_int_denom]
-- Will be subsumed by `int.coe_inj` after we have defined
-- `discrete_linear_ordered_field ℚ` (which implies characteristic zero).
lemma coe_int_inj (m n : ℤ) : (m : ℚ) = n ↔ m = n :=
⟨λ h, by simpa using congr_arg num h, congr_arg _⟩
end casts
lemma inv_def' {q : ℚ} : q⁻¹ = (q.denom : ℚ) / q.num :=
by { conv_lhs { rw ←(@num_denom q) }, cases q, simp [div_num_denom] }
@[simp] lemma mul_denom_eq_num {q : ℚ} : q * q.denom = q.num :=
begin
suffices : mk (q.num) ↑(q.denom) * mk ↑(q.denom) 1 = mk (q.num) 1, by
{ conv { for q [1] { rw ←(@num_denom q) }}, rwa [coe_int_eq_mk, coe_nat_eq_mk] },
have : (q.denom : ℤ) ≠ 0, from ne_of_gt (by exact_mod_cast q.pos),
rw [(rat.mul_def this one_ne_zero), (mul_comm (q.denom : ℤ) 1), (div_mk_div_cancel_left this)]
end
lemma denom_div_cast_eq_one_iff (m n : ℤ) (hn : n ≠ 0) :
((m : ℚ) / n).denom = 1 ↔ n ∣ m :=
begin
replace hn : (n:ℚ) ≠ 0, by rwa [ne.def, ← int.cast_zero, coe_int_inj],
split,
{ intro h,
lift ((m : ℚ) / n) to ℤ using h with k hk,
use k,
rwa [eq_div_iff_mul_eq hn, ← int.cast_mul, mul_comm, eq_comm, coe_int_inj] at hk },
{ rintros ⟨d, rfl⟩,
rw [int.cast_mul, mul_comm, mul_div_cancel _ hn, rat.coe_int_denom] }
end
lemma num_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) :
(a / b : ℚ).num = a :=
begin
lift b to ℕ using le_of_lt hb0,
norm_cast at hb0 h,
rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_num, pnat.mk_coe, h.gcd_eq_one,
int.coe_nat_one, int.div_one]
end
lemma denom_div_eq_of_coprime {a b : ℤ} (hb0 : 0 < b) (h : nat.coprime a.nat_abs b.nat_abs) :
((a / b : ℚ).denom : ℤ) = b :=
begin
lift b to ℕ using le_of_lt hb0,
norm_cast at hb0 h,
rw [← rat.mk_eq_div, ← rat.mk_pnat_eq a b hb0, rat.mk_pnat_denom, pnat.mk_coe, h.gcd_eq_one,
nat.div_one]
end
lemma div_int_inj {a b c d : ℤ} (hb0 : 0 < b) (hd0 : 0 < d)
(h1 : nat.coprime a.nat_abs b.nat_abs) (h2 : nat.coprime c.nat_abs d.nat_abs)
(h : (a : ℚ) / b = (c : ℚ) / d) : a = c ∧ b = d :=
begin
apply and.intro,
{ rw [← (num_div_eq_of_coprime hb0 h1), h, num_div_eq_of_coprime hd0 h2] },
{ rw [← (denom_div_eq_of_coprime hb0 h1), h, denom_div_eq_of_coprime hd0 h2] }
end
end rat
|
3a60651f4297aa242be4ef6b4211d76864595c43 | e5c11e5a7d990ce404047c2bd848eeafac3c0a85 | /src/primitive_element.lean | 22c1ed5d8356cc60a66c30fd43518515b138a6a3 | [
"LPPL-1.3c"
] | permissive | lean-forward/class-number | 9ec63c24845e46efc8fa8b15324d0815918292c7 | 4fccf36d5e0e16accae84c16df77a3839ad964e4 | refs/heads/main | 1,686,927,014,542 | 1,624,886,724,000 | 1,624,886,724,000 | 327,319,245 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 11,215 | lean | /-
Copyright (c) 2020 Thomas Browning and Patrick Lutz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Thomas Browning and Patrick Lutz
-/
import field_theory.adjoin
import field_theory.separable
import linear_algebra.free_module
import ring_theory.power_basis
/-!
# Primitive Element Theorem
In this file we prove the primitive element theorem.
## Main results
- `exists_primitive_element`: a finite separable extension `E / F` has a primitive element, i.e.
there is an `α : E` such that `F⟮α⟯ = (⊤ : subalgebra F E)`.
- `power_basis_of_finite_of_separable`: a finite separable extension `E / F` has a power basis
## Implementation notes
In declaration names, `primitive_element` abbreviates `adjoin_simple_eq_top`:
it stands for the statement `F⟮α⟯ = (⊤ : subalgebra F E)`. We did not add an extra
declaration `is_primitive_element F α := F⟮α⟯ = (⊤ : subalgebra F E)` because this
requires more unfolding without much obvious benefit.
## Tags
primitive element, separable field extension, separable extension, intermediate field, adjoin, exists_adjoin_simple_eq_top
-/
noncomputable theory
open_locale classical
open finite_dimensional polynomial intermediate_field
namespace field
section primitive_element_finite
variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E]
/-! ### Primitive element theorem for finite fields -/
/-- Primitive element theorem assuming E is finite. -/
lemma exists_primitive_element_of_fintype_top [fintype E] : ∃ α : E, F⟮α⟯ = ⊤ :=
begin
obtain ⟨α, hα⟩ := is_cyclic.exists_generator (units E),
use α,
apply eq_top_iff.mpr,
rintros x -,
by_cases hx : x = 0,
{ rw hx,
exact F⟮α.val⟯.zero_mem },
{ obtain ⟨n, hn⟩ := set.mem_range.mp (hα (units.mk0 x hx)),
rw (show x = α^n, by { norm_cast, rw [hn, units.coe_mk0] }),
exact pow_mem F⟮↑α⟯ (mem_adjoin_simple_self F ↑α) n, },
end
/-- Primitive element theorem for finite dimensional extension of a finite field. -/
theorem exists_primitive_element_of_fintype_bot [fintype F] [finite_dimensional F E] :
∃ α : E, F⟮α⟯ = ⊤ :=
begin
haveI : fintype E := fintype_of_fintype F E,
exact exists_primitive_element_of_fintype_top F E,
end
end primitive_element_finite
/-! ### Primitive element theorem for infinite fields -/
section primitive_element_inf
variables {F : Type*} [field F] [infinite F] {E : Type*} [field E] (ϕ : F →+* E) (α β : E)
lemma primitive_element_inf_aux_exists_c (f g : polynomial F) :
∃ c : F, ∀ (α' ∈ (f.map ϕ).roots) (β' ∈ (g.map ϕ).roots), -(α' - α)/(β' - β) ≠ ϕ c :=
begin
let sf := (f.map ϕ).roots,
let sg := (g.map ϕ).roots,
let s := (sf.bind (λ α', sg.map (λ β', -(α' - α) / (β' - β)))).to_finset,
let s' := s.preimage ϕ (λ x hx y hy h, ϕ.injective h),
obtain ⟨c, hc⟩ := infinite.exists_not_mem_finset s',
simp_rw [finset.mem_preimage, multiset.mem_to_finset, multiset.mem_bind, multiset.mem_map] at hc,
push_neg at hc,
exact ⟨c, hc⟩,
end
variables [algebra F E]
section
variables (F)
-- This is the heart of the proof of the primitive element theorem. It shows that if `F` is
-- infinite and `α` and `β` are separable over `F` then `F⟮α, β⟯` is generated by a single element.
lemma primitive_element_inf_aux [is_separable F E] :
∃ γ : E, F⟮α, β⟯ = F⟮γ⟯ :=
begin
have hα := is_separable.is_integral F α,
have hβ := is_separable.is_integral F β,
let f := minpoly F α,
let g := minpoly F β,
let ιFE := algebra_map F E,
let ιEE' := algebra_map E (splitting_field (g.map ιFE)),
obtain ⟨c, hc⟩ := primitive_element_inf_aux_exists_c (ιEE'.comp ιFE) (ιEE' α) (ιEE' β) f g,
let γ := α + c • β,
suffices β_in_Fγ : β ∈ F⟮γ⟯,
{ use γ,
apply le_antisymm,
{ rw adjoin_le_iff,
have α_in_Fγ : α ∈ F⟮γ⟯,
{ rw ← add_sub_cancel α (c • β),
exact F⟮γ⟯.sub_mem (mem_adjoin_simple_self F γ) (F⟮γ⟯.to_subalgebra.smul_mem β_in_Fγ c)},
exact λ x hx, by cases hx; cases hx; cases hx; assumption },
{ rw adjoin_le_iff,
change {γ} ⊆ _,
rw set.singleton_subset_iff,
have α_in_Fαβ : α ∈ F⟮α, β⟯ := subset_adjoin F {α, β} (set.mem_insert α {β}),
have β_in_Fαβ : β ∈ F⟮α, β⟯ := subset_adjoin F {α, β} (set.mem_insert_of_mem α rfl),
exact F⟮α,β⟯.add_mem α_in_Fαβ (F⟮α, β⟯.smul_mem β_in_Fαβ) } },
let p := euclidean_domain.gcd ((f.map (algebra_map F F⟮γ⟯)).comp
(C (adjoin_simple.gen F γ) - (C ↑c * X))) (g.map (algebra_map F F⟮γ⟯)),
let h := euclidean_domain.gcd ((f.map ιFE).comp (C γ - (C (ιFE c) * X))) (g.map ιFE),
have map_g_ne_zero : g.map ιFE ≠ 0 := map_ne_zero (minpoly.ne_zero hβ),
have h_ne_zero : h ≠ 0 := mt euclidean_domain.gcd_eq_zero_iff.mp
(not_and.mpr (λ _, map_g_ne_zero)),
suffices p_linear : p.map (algebra_map F⟮γ⟯ E) = (C h.leading_coeff) * (X - C β),
{ have finale : β = algebra_map F⟮γ⟯ E (-p.coeff 0 / p.coeff 1),
{ rw [ring_hom.map_div, ring_hom.map_neg, ←coeff_map, ←coeff_map, p_linear],
simp [mul_sub, coeff_C, mul_div_cancel_left β (mt leading_coeff_eq_zero.mp h_ne_zero)] },
rw finale,
exact subtype.mem (-p.coeff 0 / p.coeff 1) },
have h_sep : h.separable := separable_gcd_right _ (separable.map (is_separable.separable F β)),
have h_root : h.eval β = 0,
{ apply eval_gcd_eq_zero,
{ rw [eval_comp, eval_sub, eval_mul, eval_C, eval_C, eval_X, eval_map, ←aeval_def,
←algebra.smul_def, add_sub_cancel, minpoly.aeval] },
{ rw [eval_map, ←aeval_def, minpoly.aeval] } },
have h_splits : splits ιEE' h := splits_of_splits_gcd_right ιEE' map_g_ne_zero
(splitting_field.splits _),
have h_roots : ∀ x ∈ (h.map ιEE').roots, x = ιEE' β,
{ intros x hx,
rw mem_roots_map h_ne_zero at hx,
specialize hc ((ιEE' γ) - (ιEE' (ιFE c)) * x) (begin
have f_root := root_left_of_root_gcd hx,
rw [eval₂_comp, eval₂_sub, eval₂_mul,eval₂_C, eval₂_C, eval₂_X, eval₂_map] at f_root,
exact (mem_roots_map (minpoly.ne_zero hα)).mpr f_root,
end),
specialize hc x (begin
rw [mem_roots_map (minpoly.ne_zero hβ), ←eval₂_map],
exact root_right_of_root_gcd hx,
end),
by_contradiction a,
apply hc,
apply (div_eq_iff (sub_ne_zero.mpr a)).mpr,
simp only [algebra.smul_def, ring_hom.map_add, ring_hom.map_mul, ring_hom.comp_apply],
ring },
rw ← eq_X_sub_C_of_separable_of_root_eq h_ne_zero h_sep h_root h_splits h_roots,
transitivity euclidean_domain.gcd (_ : polynomial E) (_ : polynomial E),
{ dsimp only [p],
convert (gcd_map (algebra_map F⟮γ⟯ E)).symm },
{ simpa [map_comp, map_map, ←is_scalar_tower.algebra_map_eq, h] },
end
end
end primitive_element_inf
variables (F : Type*) [field F] (E : Type*) [field E] [algebra F E]
/-- Primitive element theorem: a finite separable field extension `E` of `F` has a
primitive element, i.e. there is an `α ∈ E` such that `F⟮α⟯ = (⊤ : subalgebra F E)`.-/
theorem exists_primitive_element [finite_dimensional F E] [is_separable F E] :
∃ α : E, F⟮α⟯ = ⊤ :=
begin
by_cases F_finite : nonempty (fintype F),
{ exact nonempty.elim F_finite
(λ h, by haveI := h; exact exists_primitive_element_of_fintype_bot F E) },
{ let P : intermediate_field F E → Prop := λ K, ∃ α : E, F⟮α⟯ = K,
have base : P ⊥ := ⟨0, adjoin_zero⟩,
have ih : ∀ (K : intermediate_field F E) (x : E), P K → P ↑K⟮x⟯,
{ intros K β hK,
cases hK with α hK,
rw [←hK, adjoin_simple_adjoin_simple],
haveI : infinite F := not_nonempty_fintype.mp F_finite,
cases primitive_element_inf_aux F α β with γ hγ,
exact ⟨γ, hγ.symm⟩ },
exact induction_on_adjoin P base ih ⊤ },
end
/-- An algebra equivalence induces an equivalence of power bases.
This definition is used for either direction of `power_basis.congr`.
-/
def power_basis.congr_aux {R A A' : Type*} [comm_ring R] [ring A] [ring A']
[algebra R A] [algebra R A'] (e : A ≃ₐ[R] A')
(pb : power_basis R A) : power_basis R A' :=
{ gen := e pb.gen,
dim := pb.dim,
is_basis := by { simp only [← e.map_pow],
convert linear_equiv.is_basis pb.is_basis e.to_linear_equiv } }
@[ext]
lemma power_basis.ext {R A : Type*} [integral_domain R] [ring A] [algebra R A]
{pb pb' : power_basis R A} (h : pb.gen = pb'.gen) : pb = pb' :=
begin
cases pb, cases pb', congr,
{ exact h },
convert le_antisymm
(pb'_is_basis.card_le_card_of_linear_independent pb_is_basis.1)
(pb_is_basis.card_le_card_of_linear_independent pb'_is_basis.1);
rw fintype.card_fin
end
@[ext]
lemma power_basis.ext_iff {R A : Type*} [integral_domain R] [ring A] [algebra R A]
{pb pb' : power_basis R A} : pb = pb' ↔ pb.gen = pb'.gen :=
⟨λ h, by rw h, power_basis.ext⟩
/-- An algebra equivalence induces an equivalence of power bases. -/
def power_basis.congr {R A A' : Type*} [integral_domain R] [ring A] [ring A']
[algebra R A] [algebra R A'] (e : A ≃ₐ[R] A') :
power_basis R A ≃ power_basis R A' :=
{ to_fun := power_basis.congr_aux e,
inv_fun := power_basis.congr_aux e.symm,
left_inv := λ pb, power_basis.ext (e.symm_apply_apply pb.gen),
right_inv := λ pb, power_basis.ext (e.apply_symm_apply pb.gen) }
/-- Two subalgebras with the same elements are isomorphic as `R`-algebras. -/
def subalgebra.equiv_of_eq {R A : Type*} [comm_semiring R] [semiring A] [algebra R A]
{S S' : subalgebra R A} (h : S = S') :
S ≃ₐ[R] S' :=
{ to_fun := λ x, ⟨x, h ▸ x.2⟩,
inv_fun := λ x, ⟨x, h.symm ▸ x.2⟩,
left_inv := λ x, subtype.ext rfl,
right_inv := λ x, subtype.ext rfl,
map_mul' := λ x y, subtype.ext rfl,
map_add' := λ x y, subtype.ext rfl,
commutes' := λ x, subtype.ext rfl }
/-- Two intermediate fields with the same elements are isomorphic as `R`-algebras. -/
def intermediate_field.equiv_of_eq {K L : Type*} [field K] [field L] [algebra K L]
{S S' : intermediate_field K L} (h : S = S') :
S ≃ₐ[K] S' :=
{ to_fun := λ x, ⟨x, h ▸ x.2⟩,
inv_fun := λ x, ⟨x, h.symm ▸ x.2⟩,
left_inv := λ x, subtype.ext rfl,
right_inv := λ x, subtype.ext rfl,
map_mul' := λ x y, subtype.ext rfl,
map_add' := λ x y, subtype.ext rfl,
commutes' := λ x, subtype.ext rfl }
/-- A finite separable extension `E / F` has a power basis given by the primitive element -/
def power_basis_of_finite_of_separable [finite_dimensional F E] [F_sep : is_separable F E] :
power_basis F E :=
let α := classical.some (exists_primitive_element F E) in
power_basis.congr
(show F⟮α⟯ ≃ₐ[F] E,
from (intermediate_field.equiv_of_eq
(show F⟮α⟯ = ⊤, from classical.some_spec (exists_primitive_element F E))).trans $
(subalgebra.equiv_of_eq (intermediate_field.top_to_subalgebra)).trans
algebra.top_equiv)
(intermediate_field.adjoin.power_basis ((is_algebraic_iff_is_integral _).mp
(algebra.is_algebraic_of_finite α)))
end field
|
535fd97cad15f7bf5b30025c86fb1a5d680c984c | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/computability/tm_computable.lean | 97bc8c5d7cf5ae9339a9bd6423176b96ecfc7b3d | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 11,315 | lean | /-
Copyright (c) 2020 Pim Spelier, Daan van Gent. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Pim Spelier, Daan van Gent
-/
import computability.encoding
import computability.turing_machine
import data.polynomial.basic
import data.polynomial.eval
/-!
# Computable functions
This file contains the definition of a Turing machine with some finiteness conditions
(bundling the definition of TM2 in turing_machine.lean), a definition of when a TM gives a certain
output (in a certain time), and the definition of computability (in polytime or any time function)
of a function between two types that have an encoding (as in encoding.lean).
## Main theorems
- `id_computable_in_poly_time` : a TM + a proof it computes the identity on a type in polytime.
- `id_computable` : a TM + a proof it computes the identity on a type.
## Implementation notes
To count the execution time of a Turing machine, we have decided to count the number of times the
`step` function is used. Each step executes a statement (of type stmt); this is a function, and
generally contains multiple "fundamental" steps (pushing, popping, so on). However, as functions
only contain a finite number of executions and each one is executed at most once, this execution
time is up to multiplication by a constant the amount of fundamental steps.
-/
open computability
namespace turing
/-- A bundled TM2 (an equivalent of the classical Turing machine, defined starting from
the namespace `turing.TM2` in `turing_machine.lean`), with an input and output stack,
a main function, an initial state and some finiteness guarantees. -/
structure fin_tm2 :=
{K : Type} [K_decidable_eq : decidable_eq K] [K_fin : fintype K] -- index type of stacks
(k₀ k₁ : K) -- input and output stack
(Γ : K → Type) -- type of stack elements
(Λ : Type) (main : Λ) [Λ_fin : fintype Λ] -- type of function labels
(σ : Type) (initial_state : σ) -- type of states of the machine
[σ_fin : fintype σ]
[Γk₀_fin : fintype (Γ k₀)]
(M : Λ → turing.TM2.stmt Γ Λ σ) -- the program itself, i.e. one function for every function label
namespace fin_tm2
section
variable (tm : fin_tm2)
instance : decidable_eq tm.K := tm.K_decidable_eq
instance : inhabited tm.σ := ⟨tm.initial_state⟩
/-- The type of statements (functions) corresponding to this TM. -/
@[derive inhabited]
def stmt : Type := turing.TM2.stmt tm.Γ tm.Λ tm.σ
/-- The type of configurations (functions) corresponding to this TM. -/
def cfg : Type := turing.TM2.cfg tm.Γ tm.Λ tm.σ
instance inhabited_cfg : inhabited (cfg tm) :=
turing.TM2.cfg.inhabited _ _ _
/-- The step function corresponding to this TM. -/
@[simp] def step : tm.cfg → option tm.cfg :=
turing.TM2.step tm.M
end
end fin_tm2
/-- The initial configuration corresponding to a list in the input alphabet. -/
def init_list (tm : fin_tm2) (s : list (tm.Γ tm.k₀)) : tm.cfg :=
{ l := option.some tm.main,
var := tm.initial_state,
stk := λ k, @dite (list (tm.Γ k)) (k = tm.k₀) (tm.K_decidable_eq k tm.k₀)
(λ h, begin rw h, exact s, end)
(λ _,[]) }
/-- The final configuration corresponding to a list in the output alphabet. -/
def halt_list (tm : fin_tm2) (s : list (tm.Γ tm.k₁)) : tm.cfg :=
{ l := option.none,
var := tm.initial_state,
stk := λ k, @dite (list (tm.Γ k)) (k = tm.k₁) (tm.K_decidable_eq k tm.k₁)
(λ h, begin rw h, exact s, end)
(λ _,[]) }
/-- A "proof" of the fact that f eventually reaches b when repeatedly evaluated on a,
remembering the number of steps it takes. -/
structure evals_to {σ : Type*} (f : σ → option σ) (a : σ) (b : option σ) :=
(steps : ℕ)
(evals_in_steps : ((flip bind f)^[steps] a) = b)
/-- A "proof" of the fact that `f` eventually reaches `b` in at most `m` steps when repeatedly
evaluated on `a`, remembering the number of steps it takes. -/
structure evals_to_in_time {σ : Type*} (f : σ → option σ) (a : σ) (b : option σ) (m : ℕ)
extends evals_to f a b :=
(steps_le_m : steps ≤ m)
/-- Reflexivity of `evals_to` in 0 steps. -/
@[refl] def evals_to.refl {σ : Type*} (f : σ → option σ) (a : σ) : evals_to f a a := ⟨0,rfl⟩
/-- Transitivity of `evals_to` in the sum of the numbers of steps. -/
@[trans] def evals_to.trans {σ : Type*} (f : σ → option σ) (a : σ) (b : σ) (c : option σ)
(h₁ : evals_to f a b) (h₂ : evals_to f b c) : evals_to f a c :=
⟨h₂.steps + h₁.steps,
by rw [function.iterate_add_apply,h₁.evals_in_steps,h₂.evals_in_steps]⟩
/-- Reflexivity of `evals_to_in_time` in 0 steps. -/
@[refl] def evals_to_in_time.refl {σ : Type*} (f : σ → option σ) (a : σ) :
evals_to_in_time f a a 0 :=
⟨evals_to.refl f a, le_refl 0⟩
/-- Transitivity of `evals_to_in_time` in the sum of the numbers of steps. -/
@[trans] def evals_to_in_time.trans {σ : Type*} (f : σ → option σ) (a : σ) (b : σ) (c : option σ)
(m₁ : ℕ) (m₂ : ℕ) (h₁ : evals_to_in_time f a b m₁) (h₂ : evals_to_in_time f b c m₂) :
evals_to_in_time f a c (m₂ + m₁) :=
⟨evals_to.trans f a b c h₁.to_evals_to h₂.to_evals_to, add_le_add h₂.steps_le_m h₁.steps_le_m⟩
/-- A proof of tm outputting l' when given l. -/
def tm2_outputs (tm : fin_tm2) (l : list (tm.Γ tm.k₀)) (l' : option (list (tm.Γ tm.k₁))) :=
evals_to tm.step (init_list tm l) ((option.map (halt_list tm)) l')
/-- A proof of tm outputting l' when given l in at most m steps. -/
def tm2_outputs_in_time (tm : fin_tm2) (l : list (tm.Γ tm.k₀))
(l' : option (list (tm.Γ tm.k₁))) (m : ℕ) :=
evals_to_in_time tm.step (init_list tm l) ((option.map (halt_list tm)) l') m
/-- The forgetful map, forgetting the upper bound on the number of steps. -/
def tm2_outputs_in_time.to_tm2_outputs {tm : fin_tm2} {l : list (tm.Γ tm.k₀)}
{l' : option (list (tm.Γ tm.k₁))} {m : ℕ} (h : tm2_outputs_in_time tm l l' m) :
tm2_outputs tm l l' :=
h.to_evals_to
/-- A Turing machine with input alphabet equivalent to Γ₀ and output alphabet equivalent to Γ₁. -/
structure tm2_computable_aux (Γ₀ Γ₁ : Type) :=
( tm : fin_tm2 )
( input_alphabet : tm.Γ tm.k₀ ≃ Γ₀ )
( output_alphabet : tm.Γ tm.k₁ ≃ Γ₁ )
/-- A Turing machine + a proof it outputs f. -/
structure tm2_computable {α β : Type} (ea : fin_encoding α) (eb : fin_encoding β) (f : α → β)
extends tm2_computable_aux ea.Γ eb.Γ :=
(outputs_fun : ∀ a, tm2_outputs tm (list.map input_alphabet.inv_fun (ea.encode a))
(option.some ((list.map output_alphabet.inv_fun) (eb.encode (f a)))) )
/-- A Turing machine + a time function + a proof it outputs f in at most time(len(input)) steps. -/
structure tm2_computable_in_time {α β : Type} (ea : fin_encoding α) (eb : fin_encoding β)
(f : α → β)
extends tm2_computable_aux ea.Γ eb.Γ :=
(time: ℕ → ℕ)
(outputs_fun : ∀ a, tm2_outputs_in_time tm (list.map input_alphabet.inv_fun (ea.encode a))
(option.some ((list.map output_alphabet.inv_fun) (eb.encode (f a))))
(time (ea.encode a).length))
/-- A Turing machine + a polynomial time function + a proof it outputs f in at most time(len(input))
steps. -/
structure tm2_computable_in_poly_time {α β : Type} (ea : fin_encoding α) (eb : fin_encoding β)
(f : α → β)
extends tm2_computable_aux ea.Γ eb.Γ :=
(time: polynomial ℕ)
(outputs_fun : ∀ a, tm2_outputs_in_time tm (list.map input_alphabet.inv_fun (ea.encode a))
(option.some ((list.map output_alphabet.inv_fun) (eb.encode (f a))))
(time.eval (ea.encode a).length))
/-- A forgetful map, forgetting the time bound on the number of steps. -/
def tm2_computable_in_time.to_tm2_computable {α β : Type} {ea : fin_encoding α}
{eb : fin_encoding β} {f : α → β} (h : tm2_computable_in_time ea eb f) :
tm2_computable ea eb f :=
⟨h.to_tm2_computable_aux, λ a, tm2_outputs_in_time.to_tm2_outputs (h.outputs_fun a)⟩
/-- A forgetful map, forgetting that the time function is polynomial. -/
def tm2_computable_in_poly_time.to_tm2_computable_in_time {α β : Type} {ea : fin_encoding α}
{eb : fin_encoding β} {f : α → β} (h : tm2_computable_in_poly_time ea eb f) :
tm2_computable_in_time ea eb f :=
⟨h.to_tm2_computable_aux, λ n, h.time.eval n, h.outputs_fun⟩
open turing.TM2.stmt
/-- A Turing machine computing the identity on α. -/
def id_computer {α : Type} (ea : fin_encoding α) : fin_tm2 :=
{ K := unit,
k₀ := ⟨⟩,
k₁ := ⟨⟩,
Γ := λ _, ea.Γ,
Λ := unit,
main := ⟨⟩,
σ := unit,
initial_state := ⟨⟩,
Γk₀_fin := ea.Γ_fin,
M := λ _, halt }
instance inhabited_fin_tm2 : inhabited fin_tm2 :=
⟨id_computer computability.inhabited_fin_encoding.default⟩
noncomputable theory
/-- A proof that the identity map on α is computable in polytime. -/
def id_computable_in_poly_time {α : Type} (ea : fin_encoding α) :
@tm2_computable_in_poly_time α α ea ea id :=
{ tm := id_computer ea,
input_alphabet := equiv.cast rfl,
output_alphabet := equiv.cast rfl,
time := 1,
outputs_fun := λ _, { steps := 1,
evals_in_steps := rfl,
steps_le_m := by simp only [polynomial.eval_one] } }
instance inhabited_tm2_computable_in_poly_time :
inhabited (tm2_computable_in_poly_time (default : fin_encoding bool) default id) :=
⟨id_computable_in_poly_time computability.inhabited_fin_encoding.default⟩
instance inhabited_tm2_outputs_in_time :
inhabited (tm2_outputs_in_time (id_computer fin_encoding_bool_bool)
(list.map (equiv.cast rfl).inv_fun [ff]) (some (list.map (equiv.cast rfl).inv_fun [ff])) _) :=
⟨(id_computable_in_poly_time fin_encoding_bool_bool).outputs_fun ff⟩
instance inhabited_tm2_outputs : inhabited (tm2_outputs (id_computer fin_encoding_bool_bool)
(list.map (equiv.cast rfl).inv_fun [ff]) (some (list.map (equiv.cast rfl).inv_fun [ff]))) :=
⟨tm2_outputs_in_time.to_tm2_outputs turing.inhabited_tm2_outputs_in_time.default⟩
instance inhabited_evals_to_in_time :
inhabited (evals_to_in_time (λ _ : unit, some ⟨⟩) ⟨⟩ (some ⟨⟩) 0) :=
⟨evals_to_in_time.refl _ _⟩
instance inhabited_tm2_evals_to : inhabited (evals_to (λ _ : unit, some ⟨⟩) ⟨⟩ (some ⟨⟩)) :=
⟨evals_to.refl _ _⟩
/-- A proof that the identity map on α is computable in time. -/
def id_computable_in_time {α : Type} (ea : fin_encoding α) : @tm2_computable_in_time α α ea ea id :=
tm2_computable_in_poly_time.to_tm2_computable_in_time $ id_computable_in_poly_time ea
instance inhabited_tm2_computable_in_time :
inhabited (tm2_computable_in_time fin_encoding_bool_bool fin_encoding_bool_bool id) :=
⟨id_computable_in_time computability.inhabited_fin_encoding.default⟩
/-- A proof that the identity map on α is computable. -/
def id_computable {α : Type} (ea : fin_encoding α) : @tm2_computable α α ea ea id :=
tm2_computable_in_time.to_tm2_computable $ id_computable_in_time ea
instance inhabited_tm2_computable :
inhabited (tm2_computable fin_encoding_bool_bool fin_encoding_bool_bool id) :=
⟨id_computable computability.inhabited_fin_encoding.default⟩
instance inhabited_tm2_computable_aux : inhabited (tm2_computable_aux bool bool) :=
⟨(default : tm2_computable fin_encoding_bool_bool fin_encoding_bool_bool id).to_tm2_computable_aux⟩
end turing
|
09163066d942f31a4b9f0757d4096cdd5f2777d2 | 9dd3f3912f7321eb58ee9aa8f21778ad6221f87c | /tests/lean/run/def_complete_bug.lean | 2fe87a919cd1a246238e44bd53e3a85d8294a915 | [
"Apache-2.0"
] | permissive | bre7k30/lean | de893411bcfa7b3c5572e61b9e1c52951b310aa4 | 5a924699d076dab1bd5af23a8f910b433e598d7a | refs/heads/master | 1,610,900,145,817 | 1,488,006,845,000 | 1,488,006,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 394 | lean | definition g : list nat → list nat → nat
| [] (y::ys) := y
| [] ys := 0
| (x1::x2::xs) ys := g xs ys
| (x::xs) (y::ys) := g xs ys + y
| (x::xs) [] := g xs []
print g._main.equations._eqn_1
print g._main.equations._eqn_2
print g._main.equations._eqn_3
print g._main.equations._eqn_4
print g._main.equations._eqn_5
print g._main.equations._eqn_6
|
b57617b679c448108aaa55bef26b2976c711cff0 | 69d4931b605e11ca61881fc4f66db50a0a875e39 | /src/linear_algebra/trace.lean | 06c921bf7f38544c31cc8cc5678a80ce475d99e9 | [
"Apache-2.0"
] | permissive | abentkamp/mathlib | d9a75d291ec09f4637b0f30cc3880ffb07549ee5 | 5360e476391508e092b5a1e5210bd0ed22dc0755 | refs/heads/master | 1,682,382,954,948 | 1,622,106,077,000 | 1,622,106,077,000 | 149,285,665 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 4,009 | lean | /-
Copyright (c) 2019 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Patrick Massot, Casper Putz, Anne Baanen
-/
import linear_algebra.matrix.to_lin
import linear_algebra.matrix.trace
/-!
# Trace of a matrix
This file defines the trace of a linear map.
See also `linear_algebra/matrix/trace.lean` for the trace of a matrix.
## Tags
linear_map, trace, diagonal
-/
noncomputable theory
universes u v w
namespace linear_map
open_locale big_operators
open_locale matrix
variables (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M]
variables {ι : Type w} [decidable_eq ι] [fintype ι]
variables {κ : Type*} [decidable_eq κ] [fintype κ]
variables (b : basis ι R M) (c : basis κ R M)
/-- The trace of an endomorphism given a basis. -/
def trace_aux :
(M →ₗ[R] M) →ₗ[R] R :=
(matrix.trace ι R R).comp $ linear_map.to_matrix b b
-- Can't be `simp` because it would cause a loop.
lemma trace_aux_def (b : basis ι R M) (f : M →ₗ[R] M) :
trace_aux R b f = matrix.trace ι R R (linear_map.to_matrix b b f) :=
rfl
theorem trace_aux_eq : trace_aux R b = trace_aux R c :=
linear_map.ext $ λ f,
calc matrix.trace ι R R (linear_map.to_matrix b b f)
= matrix.trace ι R R (linear_map.to_matrix b b ((linear_map.id.comp f).comp linear_map.id)) :
by rw [linear_map.id_comp, linear_map.comp_id]
... = matrix.trace ι R R (linear_map.to_matrix c b linear_map.id ⬝
linear_map.to_matrix c c f ⬝
linear_map.to_matrix b c linear_map.id) :
by rw [linear_map.to_matrix_comp _ c, linear_map.to_matrix_comp _ c]
... = matrix.trace κ R R (linear_map.to_matrix c c f ⬝
linear_map.to_matrix b c linear_map.id ⬝
linear_map.to_matrix c b linear_map.id) :
by rw [matrix.mul_assoc, matrix.trace_mul_comm]
... = matrix.trace κ R R (linear_map.to_matrix c c ((f.comp linear_map.id).comp linear_map.id)) :
by rw [linear_map.to_matrix_comp _ b, linear_map.to_matrix_comp _ c]
... = matrix.trace κ R R (linear_map.to_matrix c c f) :
by rw [linear_map.comp_id, linear_map.comp_id]
open_locale classical
theorem trace_aux_reindex_range [nontrivial R] : trace_aux R b.reindex_range = trace_aux R b :=
linear_map.ext $ λ f,
begin
change ∑ i : set.range b, _ = ∑ i : ι, _, simp_rw [matrix.diag_apply], symmetry,
convert (equiv.of_injective _ b.injective).sum_comp _, ext i,
exact (linear_map.to_matrix_reindex_range b b f i i).symm
end
variables (R) (M)
/-- Trace of an endomorphism independent of basis. -/
def trace : (M →ₗ[R] M) →ₗ[R] R :=
if H : ∃ (s : set M) (b : basis (s : set M) R M), s.finite
then @trace_aux R _ _ _ _ _ _ (classical.choice H.some_spec.some_spec) H.some_spec.some
else 0
variables (R) {M}
/-- Auxiliary lemma for `trace_eq_matrix_trace`. -/
theorem trace_eq_matrix_trace_of_finite_set {s : set M} (b : basis s R M) (hs : fintype s)
(f : M →ₗ[R] M) :
trace R M f = matrix.trace s R R (linear_map.to_matrix b b f) :=
have ∃ (s : set M) (b : basis (s : set M) R M), s.finite,
from ⟨s, b, ⟨hs⟩⟩,
by { rw [trace, dif_pos this, ← trace_aux_def], congr' 1, apply trace_aux_eq }
theorem trace_eq_matrix_trace (f : M →ₗ[R] M) :
trace R M f = matrix.trace ι R R (linear_map.to_matrix b b f) :=
if hR : nontrivial R
then by haveI := hR;
rw [trace_eq_matrix_trace_of_finite_set R b.reindex_range (set.fintype_range b),
← trace_aux_def, ← trace_aux_def, trace_aux_reindex_range]
else @subsingleton.elim _ (not_nontrivial_iff_subsingleton.mp hR) _ _
theorem trace_mul_comm (f g : M →ₗ[R] M) :
trace R M (f * g) = trace R M (g * f) :=
if H : ∃ (s : set M) (b : basis (s : set M) R M), s.finite then let ⟨s, b, hs⟩ := H in
by { haveI := classical.choice hs,
simp_rw [trace_eq_matrix_trace R b, linear_map.to_matrix_mul], apply matrix.trace_mul_comm }
else by rw [trace, dif_neg H, linear_map.zero_apply, linear_map.zero_apply]
end linear_map
|
1edf616880bcc65ced69cc9edfcd88424678dd54 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/field_theory/finite/galois_field.lean | 71e008d43a33967bc75723fec1cfaa3a8f0e3007 | [
"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,840 | lean | /-
Copyright (c) 2021 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Aaron Anderson, Alex J. Best, Johan Commelin, Eric Rodriguez, Ruben Van de Velde
-/
import algebra.char_p.algebra
import field_theory.finite.basic
import field_theory.separable
import linear_algebra.finite_dimensional
/-!
# Galois fields
If `p` is a prime number, and `n` a natural number,
then `galois_field p n` is defined as the splitting field of `X^(p^n) - X` over `zmod p`.
It is a finite field with `p ^ n` elements.
## Main definition
* `galois_field p n` is a field with `p ^ n` elements
## Main Results
- `galois_field.alg_equiv_galois_field`: Any finite field is isomorphic to some Galois field
- `finite_field.alg_equiv_of_card_eq`: Uniqueness of finite fields : algebra isomorphism
- `finite_field.ring_equiv_of_card_eq`: Uniqueness of finite fields : ring isomorphism
-/
noncomputable theory
open polynomial
open_locale polynomial
lemma galois_poly_separable {K : Type*} [field K] (p q : ℕ) [char_p K p] (h : p ∣ q) :
separable (X ^ q - X : K[X]) :=
begin
use [1, (X ^ q - X - 1)],
rw [← char_p.cast_eq_zero_iff K[X] p] at h,
rw [derivative_sub, derivative_pow, derivative_X, h],
ring,
end
/-- A finite field with `p ^ n` elements.
Every field with the same cardinality is (non-canonically)
isomorphic to this field. -/
@[derive field]
def galois_field (p : ℕ) [fact p.prime] (n : ℕ) :=
splitting_field (X^(p^n) - X : (zmod p)[X])
instance : inhabited (@galois_field 2 (fact.mk nat.prime_two) 1) :=
⟨37⟩
namespace galois_field
variables (p : ℕ) [fact p.prime] (n : ℕ)
instance : algebra (zmod p) (galois_field p n) :=
splitting_field.algebra _
instance : is_splitting_field (zmod p) (galois_field p n) (X^(p^n) - X) :=
polynomial.is_splitting_field.splitting_field _
instance : char_p (galois_field p n) p :=
(algebra.char_p_iff (zmod p) (galois_field p n) p).mp (by apply_instance)
instance : fintype (galois_field p n) := by {dsimp only [galois_field],
exact finite_dimensional.fintype_of_fintype (zmod p) (galois_field p n) }
lemma finrank {n} (h : n ≠ 0) : finite_dimensional.finrank (zmod p) (galois_field p n) = n :=
begin
set g_poly := (X^(p^n) - X : (zmod p)[X]),
have hp : 1 < p := (fact.out (nat.prime p)).one_lt,
have aux : g_poly ≠ 0 := finite_field.X_pow_card_pow_sub_X_ne_zero _ h hp,
have key : fintype.card ((g_poly).root_set (galois_field p n)) = (g_poly).nat_degree :=
card_root_set_eq_nat_degree (galois_poly_separable p _ (dvd_pow (dvd_refl p) h))
(splitting_field.splits g_poly),
have nat_degree_eq : (g_poly).nat_degree = p ^ n :=
finite_field.X_pow_card_pow_sub_X_nat_degree_eq _ h hp,
rw nat_degree_eq at key,
suffices : (g_poly).root_set (galois_field p n) = set.univ,
{ simp_rw [this, ←fintype.of_equiv_card (equiv.set.univ _)] at key,
rw [@card_eq_pow_finrank (zmod p), zmod.card] at key,
exact nat.pow_right_injective ((nat.prime.one_lt' p).out) key },
rw set.eq_univ_iff_forall,
suffices : ∀ x (hx : x ∈ (⊤ : subalgebra (zmod p) (galois_field p n))),
x ∈ (X ^ p ^ n - X : (zmod p)[X]).root_set (galois_field p n),
{ simpa, },
rw ← splitting_field.adjoin_root_set,
simp_rw algebra.mem_adjoin_iff,
intros x hx,
-- We discharge the `p = 0` separately, to avoid typeclass issues on `zmod p`.
unfreezingI { cases p, cases hp, },
apply subring.closure_induction hx; clear_dependent x; simp_rw mem_root_set aux,
{ rintros x (⟨r, rfl⟩ | hx),
{ simp only [aeval_X_pow, aeval_X, alg_hom.map_sub],
rw [← map_pow, zmod.pow_card_pow, sub_self], },
{ dsimp only [galois_field] at hx,
rwa mem_root_set aux at hx, }, },
{ dsimp only [g_poly],
rw [← coeff_zero_eq_aeval_zero'],
simp only [coeff_X_pow, coeff_X_zero, sub_zero, ring_hom.map_eq_zero, ite_eq_right_iff,
one_ne_zero, coeff_sub],
intro hn,
exact nat.not_lt_zero 1 (pow_eq_zero hn.symm ▸ hp), },
{ simp, },
{ simp only [aeval_X_pow, aeval_X, alg_hom.map_sub, add_pow_char_pow, sub_eq_zero],
intros x y hx hy,
rw [hx, hy], },
{ intros x hx,
simp only [sub_eq_zero, aeval_X_pow, aeval_X, alg_hom.map_sub, sub_neg_eq_add] at *,
rw [neg_pow, hx, char_p.neg_one_pow_char_pow],
simp, },
{ simp only [aeval_X_pow, aeval_X, alg_hom.map_sub, mul_pow, sub_eq_zero],
intros x y hx hy,
rw [hx, hy], },
end
lemma card (h : n ≠ 0) : fintype.card (galois_field p n) = p ^ n :=
begin
let b := is_noetherian.finset_basis (zmod p) (galois_field p n),
rw [module.card_fintype b, ← finite_dimensional.finrank_eq_card_basis b, zmod.card, finrank p h],
end
theorem splits_zmod_X_pow_sub_X : splits (ring_hom.id (zmod p)) (X ^ p - X) :=
begin
have hp : 1 < p := (fact.out (nat.prime p)).one_lt,
have h1 : roots (X ^ p - X : (zmod p)[X]) = finset.univ.val,
{ convert finite_field.roots_X_pow_card_sub_X _,
exact (zmod.card p).symm },
have h2 := finite_field.X_pow_card_sub_X_nat_degree_eq (zmod p) hp,
-- We discharge the `p = 0` separately, to avoid typeclass issues on `zmod p`.
unfreezingI { cases p, cases hp, },
rw [splits_iff_card_roots, h1, ←finset.card_def, finset.card_univ, h2, zmod.card],
end
/-- A Galois field with exponent 1 is equivalent to `zmod` -/
def equiv_zmod_p : galois_field p 1 ≃ₐ[zmod p] (zmod p) :=
have h : (X ^ p ^ 1 : (zmod p)[X]) = X ^ (fintype.card (zmod p)),
by rw [pow_one, zmod.card p],
have inst : is_splitting_field (zmod p) (zmod p) (X ^ p ^ 1 - X),
by { rw h, apply_instance },
by exactI (is_splitting_field.alg_equiv (zmod p) (X ^ (p ^ 1) - X : (zmod p)[X])).symm
variables {K : Type*} [field K] [fintype K] [algebra (zmod p) K]
theorem splits_X_pow_card_sub_X : splits (algebra_map (zmod p) K) (X ^ fintype.card K - X) :=
by rw [←splits_id_iff_splits, polynomial.map_sub, polynomial.map_pow, map_X, splits_iff_card_roots,
finite_field.roots_X_pow_card_sub_X, ←finset.card_def, finset.card_univ,
finite_field.X_pow_card_sub_X_nat_degree_eq]; exact fintype.one_lt_card
lemma is_splitting_field_of_card_eq (h : fintype.card K = p ^ n) :
is_splitting_field (zmod p) K (X ^ (p ^ n) - X) :=
{ splits := by { rw ← h, exact splits_X_pow_card_sub_X p },
adjoin_roots :=
begin
have hne : n ≠ 0,
{ rintro rfl, rw [pow_zero, fintype.card_eq_one_iff_nonempty_unique] at h,
cases h, resetI, exact false_of_nontrivial_of_subsingleton K },
refine algebra.eq_top_iff.mpr (λ x, algebra.subset_adjoin _),
rw [polynomial.map_sub, polynomial.map_pow, map_X, finset.mem_coe, multiset.mem_to_finset,
mem_roots, is_root.def, eval_sub, eval_pow, eval_X, ← h, finite_field.pow_card, sub_self],
exact finite_field.X_pow_card_pow_sub_X_ne_zero K hne (fact.out _)
end }
/-- Any finite field is (possibly non canonically) isomorphic to some Galois field. -/
def alg_equiv_galois_field (h : fintype.card K = p ^ n) :
K ≃ₐ[zmod p] galois_field p n :=
by haveI := is_splitting_field_of_card_eq _ _ h; exact is_splitting_field.alg_equiv _ _
end galois_field
namespace finite_field
variables {K : Type*} [field K] [fintype K] {K' : Type*} [field K'] [fintype K']
/-- Uniqueness of finite fields:
Any two finite fields of the same cardinality are (possibly non canonically) isomorphic-/
def alg_equiv_of_card_eq (p : ℕ) [fact p.prime] [algebra (zmod p) K] [algebra (zmod p) K']
(hKK' : fintype.card K = fintype.card K') :
K ≃ₐ[zmod p] K' :=
begin
haveI : char_p K p,
{ rw ← algebra.char_p_iff (zmod p) K p, exact zmod.char_p p, },
haveI : char_p K' p,
{ rw ← algebra.char_p_iff (zmod p) K' p, exact zmod.char_p p, },
choose n a hK using finite_field.card K p,
choose n' a' hK' using finite_field.card K' p,
rw [hK,hK'] at hKK',
have hGalK := galois_field.alg_equiv_galois_field p n hK,
have hK'Gal := (galois_field.alg_equiv_galois_field p n' hK').symm,
rw (nat.pow_right_injective (fact.out (nat.prime p)).one_lt hKK') at *,
use alg_equiv.trans hGalK hK'Gal,
end
/-- Uniqueness of finite fields:
Any two finite fields of the same cardinality are (possibly non canonically) isomorphic-/
def ring_equiv_of_card_eq (hKK' : fintype.card K = fintype.card K') : K ≃+* K' :=
begin
choose p _char_p_K using char_p.exists K,
choose p' _char_p'_K' using char_p.exists K',
resetI,
choose n hp hK using finite_field.card K p,
choose n' hp' hK' using finite_field.card K' p',
have hpp' : p = p', -- := eq_prime_of_eq_prime_pow
{ by_contra hne,
have h2 := nat.coprime_pow_primes n n' hp hp' hne,
rw [(eq.congr hK hK').mp hKK', nat.coprime_self, pow_eq_one_iff (pnat.ne_zero n')] at h2,
exact nat.prime.ne_one hp' h2,
all_goals {apply_instance}, },
rw ← hpp' at *,
haveI := fact_iff.2 hp,
exact alg_equiv_of_card_eq p hKK',
end
end finite_field
|
34f5ac0269f35f75bd44c928c491a25be3a30bcd | bb31430994044506fa42fd667e2d556327e18dfe | /src/dynamics/ergodic/measure_preserving.lean | 751332d237ae3f36a922317b2840c05d3fd20f01 | [
"Apache-2.0"
] | permissive | sgouezel/mathlib | 0cb4e5335a2ba189fa7af96d83a377f83270e503 | 00638177efd1b2534fc5269363ebf42a7871df9a | refs/heads/master | 1,674,527,483,042 | 1,673,665,568,000 | 1,673,665,568,000 | 119,598,202 | 0 | 0 | null | 1,517,348,647,000 | 1,517,348,646,000 | null | UTF-8 | Lean | false | false | 7,246 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov
-/
import measure_theory.measure.ae_measurable
/-!
# Measure preserving maps
We say that `f : α → β` is a measure preserving map w.r.t. measures `μ : measure α` and
`ν : measure β` if `f` is measurable and `map f μ = ν`. In this file we define the predicate
`measure_theory.measure_preserving` and prove its basic properties.
We use the term "measure preserving" because in many applications `α = β` and `μ = ν`.
## References
Partially based on
[this](https://www.isa-afp.org/browser_info/current/AFP/Ergodic_Theory/Measure_Preserving_Transformations.html)
Isabelle formalization.
## Tags
measure preserving map, measure
-/
variables {α β γ δ : Type*} [measurable_space α] [measurable_space β] [measurable_space γ]
[measurable_space δ]
namespace measure_theory
open measure function set
variables {μa : measure α} {μb : measure β} {μc : measure γ} {μd : measure δ}
/-- `f` is a measure preserving map w.r.t. measures `μa` and `μb` if `f` is measurable
and `map f μa = μb`. -/
@[protect_proj]
structure measure_preserving (f : α → β) (μa : measure α . volume_tac)
(μb : measure β . volume_tac) : Prop :=
(measurable : measurable f)
(map_eq : map f μa = μb)
protected lemma _root_.measurable.measure_preserving {f : α → β}
(h : measurable f) (μa : measure α) :
measure_preserving f μa (map f μa) :=
⟨h, rfl⟩
namespace measure_preserving
protected lemma id (μ : measure α) : measure_preserving id μ μ :=
⟨measurable_id, map_id⟩
protected lemma ae_measurable {f : α → β} (hf : measure_preserving f μa μb) :
ae_measurable f μa :=
hf.1.ae_measurable
lemma symm (e : α ≃ᵐ β) {μa : measure α} {μb : measure β} (h : measure_preserving e μa μb) :
measure_preserving e.symm μb μa :=
⟨e.symm.measurable,
by rw [← h.map_eq, map_map e.symm.measurable e.measurable, e.symm_comp_self, map_id]⟩
lemma restrict_preimage {f : α → β} (hf : measure_preserving f μa μb) {s : set β}
(hs : measurable_set s) : measure_preserving f (μa.restrict (f ⁻¹' s)) (μb.restrict s) :=
⟨hf.measurable, by rw [← hf.map_eq, restrict_map hf.measurable hs]⟩
lemma restrict_preimage_emb {f : α → β} (hf : measure_preserving f μa μb)
(h₂ : measurable_embedding f) (s : set β) :
measure_preserving f (μa.restrict (f ⁻¹' s)) (μb.restrict s) :=
⟨hf.measurable, by rw [← hf.map_eq, h₂.restrict_map]⟩
lemma restrict_image_emb {f : α → β} (hf : measure_preserving f μa μb) (h₂ : measurable_embedding f)
(s : set α) : measure_preserving f (μa.restrict s) (μb.restrict (f '' s)) :=
by simpa only [preimage_image_eq _ h₂.injective] using hf.restrict_preimage_emb h₂ (f '' s)
lemma ae_measurable_comp_iff {f : α → β} (hf : measure_preserving f μa μb)
(h₂ : measurable_embedding f) {g : β → γ} :
ae_measurable (g ∘ f) μa ↔ ae_measurable g μb :=
by rw [← hf.map_eq, h₂.ae_measurable_map_iff]
protected lemma quasi_measure_preserving {f : α → β} (hf : measure_preserving f μa μb) :
quasi_measure_preserving f μa μb :=
⟨hf.1, hf.2.absolutely_continuous⟩
protected lemma comp {g : β → γ} {f : α → β} (hg : measure_preserving g μb μc)
(hf : measure_preserving f μa μb) :
measure_preserving (g ∘ f) μa μc :=
⟨hg.1.comp hf.1, by rw [← map_map hg.1 hf.1, hf.2, hg.2]⟩
protected lemma comp_left_iff {g : α → β} {e : β ≃ᵐ γ} (h : measure_preserving e μb μc) :
measure_preserving (e ∘ g) μa μc ↔ measure_preserving g μa μb :=
begin
refine ⟨λ hg, _, λ hg, h.comp hg⟩,
convert (measure_preserving.symm e h).comp hg,
simp [← function.comp.assoc e.symm e g],
end
protected lemma comp_right_iff {g : α → β} {e : γ ≃ᵐ α} (h : measure_preserving e μc μa) :
measure_preserving (g ∘ e) μc μb ↔ measure_preserving g μa μb :=
begin
refine ⟨λ hg, _, λ hg, hg.comp h⟩,
convert hg.comp (measure_preserving.symm e h),
simp [function.comp.assoc g e e.symm],
end
protected lemma sigma_finite {f : α → β} (hf : measure_preserving f μa μb) [sigma_finite μb] :
sigma_finite μa :=
sigma_finite.of_map μa hf.ae_measurable (by rwa hf.map_eq)
lemma measure_preimage {f : α → β} (hf : measure_preserving f μa μb)
{s : set β} (hs : measurable_set s) :
μa (f ⁻¹' s) = μb s :=
by rw [← hf.map_eq, map_apply hf.1 hs]
lemma measure_preimage_emb {f : α → β} (hf : measure_preserving f μa μb)
(hfe : measurable_embedding f) (s : set β) :
μa (f ⁻¹' s) = μb s :=
by rw [← hf.map_eq, hfe.map_apply]
protected lemma iterate {f : α → α} (hf : measure_preserving f μa μa) :
∀ n, measure_preserving (f^[n]) μa μa
| 0 := measure_preserving.id μa
| (n + 1) := (iterate n).comp hf
variables {μ : measure α} {f : α → α} {s : set α}
/-- If `μ univ < n * μ s` and `f` is a map preserving measure `μ`,
then for some `x ∈ s` and `0 < m < n`, `f^[m] x ∈ s`. -/
lemma exists_mem_image_mem_of_volume_lt_mul_volume (hf : measure_preserving f μ μ)
(hs : measurable_set s) {n : ℕ} (hvol : μ (univ : set α) < n * μ s) :
∃ (x ∈ s) (m ∈ Ioo 0 n), f^[m] x ∈ s :=
begin
have A : ∀ m, measurable_set (f^[m] ⁻¹' s) := λ m, (hf.iterate m).measurable hs,
have B : ∀ m, μ (f^[m] ⁻¹' s) = μ s, from λ m, (hf.iterate m).measure_preimage hs,
have : μ (univ : set α) < (finset.range n).sum (λ m, μ (f^[m] ⁻¹' s)),
by simpa only [B, nsmul_eq_mul, finset.sum_const, finset.card_range],
rcases exists_nonempty_inter_of_measure_univ_lt_sum_measure μ (λ m hm, A m) this
with ⟨i, hi, j, hj, hij, x, hxi, hxj⟩,
-- without `tactic.skip` Lean closes the extra goal but it takes a long time; not sure why
wlog hlt : i < j := hij.lt_or_lt using [i j, j i] tactic.skip,
{ simp only [set.mem_preimage, finset.mem_range] at hi hj hxi hxj,
refine ⟨f^[i] x, hxi, j - i, ⟨tsub_pos_of_lt hlt, lt_of_le_of_lt (j.sub_le i) hj⟩, _⟩,
rwa [← iterate_add_apply, tsub_add_cancel_of_le hlt.le] },
{ exact λ hi hj hij hxi hxj, this hj hi hij.symm hxj hxi }
end
/-- A self-map preserving a finite measure is conservative: if `μ s ≠ 0`, then at least one point
`x ∈ s` comes back to `s` under iterations of `f`. Actually, a.e. point of `s` comes back to `s`
infinitely many times, see `measure_theory.measure_preserving.conservative` and theorems about
`measure_theory.conservative`. -/
lemma exists_mem_image_mem [is_finite_measure μ] (hf : measure_preserving f μ μ)
(hs : measurable_set s) (hs' : μ s ≠ 0) :
∃ (x ∈ s) (m ≠ 0), f^[m] x ∈ s :=
begin
rcases ennreal.exists_nat_mul_gt hs' (measure_ne_top μ (univ : set α)) with ⟨N, hN⟩,
rcases hf.exists_mem_image_mem_of_volume_lt_mul_volume hs hN with ⟨x, hx, m, hm, hmx⟩,
exact ⟨x, hx, m, hm.1.ne', hmx⟩
end
end measure_preserving
namespace measurable_equiv
lemma measure_preserving_symm (μ : measure α) (e : α ≃ᵐ β) :
measure_preserving e.symm (map e μ) μ :=
(e.measurable.measure_preserving μ).symm _
end measurable_equiv
end measure_theory
|
6288c4cb3c61b3e1b239f4b2f4c2c6746bf1f4b6 | c777c32c8e484e195053731103c5e52af26a25d1 | /src/data/finset/pi.lean | f5ebe2ba95aa600cad3be4c572b4744d2808b417 | [
"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 | 4,491 | lean | /-
Copyright (c) 2018 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl
-/
import data.finset.image
import data.multiset.pi
/-!
# The cartesian product of finsets
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
-/
namespace finset
open multiset
/-! ### pi -/
section pi
variables {α : Type*}
/-- The empty dependent product function, defined on the empty set. The assumption `a ∈ ∅` is never
satisfied. -/
def pi.empty (β : α → Sort*) (a : α) (h : a ∈ (∅ : finset α)) : β a :=
multiset.pi.empty β a h
variables {β : α → Type*} {δ : α → Sort*} [decidable_eq α]
/-- Given a finset `s` of `α` and for all `a : α` a finset `t a` of `δ a`, then one can define the
finset `s.pi t` of all functions defined on elements of `s` taking values in `t a` for `a ∈ s`.
Note that the elements of `s.pi t` are only partially defined, on `s`. -/
def pi (s : finset α) (t : Πa, finset (β a)) : finset (Πa∈s, β a) :=
⟨s.1.pi (λ a, (t a).1), s.nodup.pi $ λ a _, (t a).nodup⟩
@[simp] lemma pi_val (s : finset α) (t : Πa, finset (β a)) :
(s.pi t).1 = s.1.pi (λ a, (t a).1) := rfl
@[simp] lemma mem_pi {s : finset α} {t : Πa, finset (β a)} {f : Πa∈s, β a} :
f ∈ s.pi t ↔ (∀a (h : a ∈ s), f a h ∈ t a) :=
mem_pi _ _ _
/-- Given a function `f` defined on a finset `s`, define a new function on the finset `s ∪ {a}`,
equal to `f` on `s` and sending `a` to a given value `b`. This function is denoted
`s.pi.cons a b f`. If `a` already belongs to `s`, the new function takes the value `b` at `a`
anyway. -/
def pi.cons (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (a' : α) (h : a' ∈ insert a s) :
δ a' :=
multiset.pi.cons s.1 a b f _ (multiset.mem_cons.2 $ mem_insert.symm.2 h)
@[simp]
lemma pi.cons_same (s : finset α) (a : α) (b : δ a) (f : Πa, a ∈ s → δ a) (h : a ∈ insert a s) :
pi.cons s a b f a h = b :=
multiset.pi.cons_same _
lemma pi.cons_ne {s : finset α} {a a' : α} {b : δ a} {f : Πa, a ∈ s → δ a} {h : a' ∈ insert a s}
(ha : a ≠ a') :
pi.cons s a b f a' h = f a' ((mem_insert.1 h).resolve_left ha.symm) :=
multiset.pi.cons_ne _ _
lemma pi_cons_injective {a : α} {b : δ a} {s : finset α} (hs : a ∉ s) :
function.injective (pi.cons s a b) :=
assume e₁ e₂ eq,
@multiset.pi_cons_injective α _ δ a b s.1 hs _ _ $
funext $ assume e, funext $ assume h,
have pi.cons s a b e₁ e (by simpa only [multiset.mem_cons, mem_insert] using h) =
pi.cons s a b e₂ e (by simpa only [multiset.mem_cons, mem_insert] using h),
{ rw [eq] },
this
@[simp] lemma pi_empty {t : Πa:α, finset (β a)} :
pi (∅ : finset α) t = singleton (pi.empty β) := rfl
@[simp] lemma pi_insert [∀a, decidable_eq (β a)]
{s : finset α} {t : Πa:α, finset (β a)} {a : α} (ha : a ∉ s) :
pi (insert a s) t = (t a).bUnion (λb, (pi s t).image (pi.cons s a b)) :=
begin
apply eq_of_veq,
rw ← (pi (insert a s) t).2.dedup,
refine (λ s' (h : s' = a ::ₘ s.1), (_ : dedup (multiset.pi s' (λ a, (t a).1)) =
dedup ((t a).1.bind $ λ b,
dedup $ (multiset.pi s.1 (λ (a : α), (t a).val)).map $
λ f a' h', multiset.pi.cons s.1 a b f a' (h ▸ h')))) _ (insert_val_of_not_mem ha),
subst s', rw pi_cons,
congr, funext b,
refine ((pi s t).nodup.map _).dedup.symm,
exact multiset.pi_cons_injective ha,
end
lemma pi_singletons {β : Type*} (s : finset α) (f : α → β) :
s.pi (λ a, ({f a} : finset β)) = {λ a _, f a} :=
begin
rw eq_singleton_iff_unique_mem,
split,
{ simp },
intros a ha,
ext i hi,
rw [mem_pi] at ha,
simpa using ha i hi,
end
lemma pi_const_singleton {β : Type*} (s : finset α) (i : β) :
s.pi (λ _, ({i} : finset β)) = {λ _ _, i} :=
pi_singletons s (λ _, i)
lemma pi_subset {s : finset α} (t₁ t₂ : Πa, finset (β a)) (h : ∀ a ∈ s, t₁ a ⊆ t₂ a) :
s.pi t₁ ⊆ s.pi t₂ :=
λ g hg, mem_pi.2 $ λ a ha, h a ha (mem_pi.mp hg a ha)
lemma pi_disjoint_of_disjoint {δ : α → Type*}
{s : finset α} (t₁ t₂ : Πa, finset (δ a)) {a : α} (ha : a ∈ s) (h : disjoint (t₁ a) (t₂ a)) :
disjoint (s.pi t₁) (s.pi t₂) :=
disjoint_iff_ne.2 $ λ f₁ hf₁ f₂ hf₂ eq₁₂,
disjoint_iff_ne.1 h (f₁ a ha) (mem_pi.mp hf₁ a ha) (f₂ a ha) (mem_pi.mp hf₂ a ha)
$ congr_fun (congr_fun eq₁₂ a) ha
end pi
end finset
|
1d625de07f4a599a4a75b5dbcf52ff1cbbc5ba4d | 206422fb9edabf63def0ed2aa3f489150fb09ccb | /src/algebra/group/hom.lean | aabf2d36fd18adb0b3acad1cd26af40a0c48f8af | [
"Apache-2.0"
] | permissive | hamdysalah1/mathlib | b915f86b2503feeae268de369f1b16932321f097 | 95454452f6b3569bf967d35aab8d852b1ddf8017 | refs/heads/master | 1,677,154,116,545 | 1,611,797,994,000 | 1,611,797,994,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 36,229 | lean | /-
Copyright (c) 2018 Patrick Massot. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Patrick Massot, Kevin Buzzard, Scott Morrison, Johan Commelin, Chris Hughes,
Johannes Hölzl, Yury Kudryashov
-/
import algebra.group.commute
import algebra.group_with_zero.defs
/-!
# monoid and group homomorphisms
This file defines the bundled structures for monoid and group homomorphisms. Namely, we define
`monoid_hom` (resp., `add_monoid_hom`) to be bundled homomorphisms between multiplicative (resp.,
additive) monoids or groups.
We also define coercion to a function, and usual operations: composition, identity homomorphism,
pointwise multiplication and pointwise inversion.
This file also defines the lesser-used (and notation-less) homomorphism types which are used as
building blocks for other homomorphisms:
* `zero_hom`
* `one_hom`
* `add_hom`
* `mul_hom`
* `monoid_with_zero_hom`
## Notations
* `→*` for bundled monoid homs (also use for group homs)
* `→+` for bundled add_monoid homs (also use for add_group homs)
## implementation notes
There's a coercion from bundled homs to fun, and the canonical
notation is to use the bundled hom as a function via this coercion.
There is no `group_hom` -- the idea is that `monoid_hom` is used.
The constructor for `monoid_hom` needs a proof of `map_one` as well
as `map_mul`; a separate constructor `monoid_hom.mk'` will construct
group homs (i.e. monoid homs between groups) given only a proof
that multiplication is preserved,
Implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the
instances can be inferred because they are implicit arguments to the type `monoid_hom`. When they
can be inferred from the type it is faster to use this method than to use type class inference.
Historically this file also included definitions of unbundled homomorphism classes; they were
deprecated and moved to `deprecated/group`.
## Tags
monoid_hom, add_monoid_hom
-/
variables {M : Type*} {N : Type*} {P : Type*} -- monoids
{G : Type*} {H : Type*} -- groups
-- for easy multiple inheritance
set_option old_structure_cmd true
/-- Homomorphism that preserves zero -/
structure zero_hom (M : Type*) (N : Type*) [has_zero M] [has_zero N] :=
(to_fun : M → N)
(map_zero' : to_fun 0 = 0)
/-- Homomorphism that preserves addition -/
structure add_hom (M : Type*) (N : Type*) [has_add M] [has_add N] :=
(to_fun : M → N)
(map_add' : ∀ x y, to_fun (x + y) = to_fun x + to_fun y)
/-- Bundled add_monoid homomorphisms; use this for bundled add_group homomorphisms too. -/
structure add_monoid_hom (M : Type*) (N : Type*) [add_monoid M] [add_monoid N]
extends zero_hom M N, add_hom M N
attribute [nolint doc_blame] add_monoid_hom.to_add_hom
attribute [nolint doc_blame] add_monoid_hom.to_zero_hom
infixr ` →+ `:25 := add_monoid_hom
/-- Homomorphism that preserves one -/
@[to_additive]
structure one_hom (M : Type*) (N : Type*) [has_one M] [has_one N] :=
(to_fun : M → N)
(map_one' : to_fun 1 = 1)
/-- Homomorphism that preserves multiplication -/
@[to_additive]
structure mul_hom (M : Type*) (N : Type*) [has_mul M] [has_mul N] :=
(to_fun : M → N)
(map_mul' : ∀ x y, to_fun (x * y) = to_fun x * to_fun y)
/-- Bundled monoid homomorphisms; use this for bundled group homomorphisms too. -/
@[to_additive]
structure monoid_hom (M : Type*) (N : Type*) [monoid M] [monoid N] extends one_hom M N, mul_hom M N
/-- Bundled monoid with zero homomorphisms; use this for bundled group with zero homomorphisms
too. -/
structure monoid_with_zero_hom (M : Type*) (N : Type*) [monoid_with_zero M] [monoid_with_zero N]
extends zero_hom M N, monoid_hom M N
attribute [nolint doc_blame, to_additive] monoid_hom.to_mul_hom
attribute [nolint doc_blame, to_additive] monoid_hom.to_one_hom
attribute [nolint doc_blame] monoid_with_zero_hom.to_monoid_hom
attribute [nolint doc_blame] monoid_with_zero_hom.to_zero_hom
infixr ` →* `:25 := monoid_hom
-- completely uninteresting lemmas about coercion to function, that all homs need
section coes
/-! Bundled morphisms can be down-cast to weaker bundlings -/
@[to_additive]
instance monoid_hom.has_coe_to_one_hom {mM : monoid M} {mN : monoid N} :
has_coe (M →* N) (one_hom M N) := ⟨monoid_hom.to_one_hom⟩
@[to_additive]
instance monoid_hom.has_coe_to_mul_hom {mM : monoid M} {mN : monoid N} :
has_coe (M →* N) (mul_hom M N) := ⟨monoid_hom.to_mul_hom⟩
instance monoid_with_zero_hom.has_coe_to_monoid_hom
{mM : monoid_with_zero M} {mN : monoid_with_zero N} :
has_coe (monoid_with_zero_hom M N) (M →* N) := ⟨monoid_with_zero_hom.to_monoid_hom⟩
instance monoid_with_zero_hom.has_coe_to_zero_hom
{mM : monoid_with_zero M} {mN : monoid_with_zero N} :
has_coe (monoid_with_zero_hom M N) (zero_hom M N) := ⟨monoid_with_zero_hom.to_zero_hom⟩
/-! The simp-normal form of morphism coercion is `f.to_..._hom`. This choice is primarily because
this is the way things were before the above coercions were introduced. Bundled morphisms defined
elsewhere in Mathlib may choose `↑f` as their simp-normal form instead. -/
@[simp, to_additive]
lemma monoid_hom.coe_eq_to_one_hom {mM : monoid M} {mN : monoid N} (f : M →* N) :
(f : one_hom M N) = f.to_one_hom := rfl
@[simp, to_additive]
lemma monoid_hom.coe_eq_to_mul_hom {mM : monoid M} {mN : monoid N} (f : M →* N) :
(f : mul_hom M N) = f.to_mul_hom := rfl
@[simp]
lemma monoid_with_zero_hom.coe_eq_to_monoid_hom {mM : monoid_with_zero M} {mN : monoid_with_zero N}
(f : monoid_with_zero_hom M N) : (f : M →* N) = f.to_monoid_hom := rfl
@[simp]
lemma monoid_with_zero_hom.coe_eq_to_zero_hom {mM : monoid_with_zero M} {mN : monoid_with_zero N}
(f : monoid_with_zero_hom M N) : (f : zero_hom M N) = f.to_zero_hom := rfl
@[to_additive]
instance {mM : has_one M} {mN : has_one N} : has_coe_to_fun (one_hom M N) :=
⟨_, one_hom.to_fun⟩
@[to_additive]
instance {mM : has_mul M} {mN : has_mul N} : has_coe_to_fun (mul_hom M N) :=
⟨_, mul_hom.to_fun⟩
@[to_additive]
instance {mM : monoid M} {mN : monoid N} : has_coe_to_fun (M →* N) :=
⟨_, monoid_hom.to_fun⟩
instance {mM : monoid_with_zero M} {mN : monoid_with_zero N} :
has_coe_to_fun (monoid_with_zero_hom M N) :=
⟨_, monoid_with_zero_hom.to_fun⟩
-- these must come after the coe_to_fun definitions
initialize_simps_projections zero_hom (to_fun → apply)
initialize_simps_projections add_hom (to_fun → apply)
initialize_simps_projections add_monoid_hom (to_fun → apply)
initialize_simps_projections one_hom (to_fun → apply)
initialize_simps_projections mul_hom (to_fun → apply)
initialize_simps_projections monoid_hom (to_fun → apply)
initialize_simps_projections monoid_with_zero_hom (to_fun → apply)
@[simp, to_additive]
lemma one_hom.to_fun_eq_coe [has_one M] [has_one N] (f : one_hom M N) : f.to_fun = f := rfl
@[simp, to_additive]
lemma mul_hom.to_fun_eq_coe [has_mul M] [has_mul N] (f : mul_hom M N) : f.to_fun = f := rfl
@[simp, to_additive]
lemma monoid_hom.to_fun_eq_coe [monoid M] [monoid N] (f : M →* N) : f.to_fun = f := rfl
@[simp]
lemma monoid_with_zero_hom.to_fun_eq_coe [monoid_with_zero M] [monoid_with_zero N]
(f : monoid_with_zero_hom M N) : f.to_fun = f := rfl
@[simp, to_additive]
lemma one_hom.coe_mk [has_one M] [has_one N]
(f : M → N) (h1) : ⇑(one_hom.mk f h1) = f := rfl
@[simp, to_additive]
lemma mul_hom.coe_mk [has_mul M] [has_mul N]
(f : M → N) (hmul) : ⇑(mul_hom.mk f hmul) = f := rfl
@[simp, to_additive]
lemma monoid_hom.coe_mk [monoid M] [monoid N]
(f : M → N) (h1 hmul) : ⇑(monoid_hom.mk f h1 hmul) = f := rfl
@[simp]
lemma monoid_with_zero_hom.coe_mk [monoid_with_zero M] [monoid_with_zero N]
(f : M → N) (h0 h1 hmul) : ⇑(monoid_with_zero_hom.mk f h0 h1 hmul) = f := rfl
@[simp, to_additive]
lemma monoid_hom.to_one_hom_coe [monoid M] [monoid N] (f : M →* N) :
(f.to_one_hom : M → N) = f := rfl
@[simp, to_additive]
lemma monoid_hom.to_mul_hom_coe [monoid M] [monoid N] (f : M →* N) :
(f.to_mul_hom : M → N) = f := rfl
@[simp]
lemma monoid_with_zero_hom.to_zero_hom_coe [monoid_with_zero M] [monoid_with_zero N]
(f : monoid_with_zero_hom M N) :
(f.to_zero_hom : M → N) = f := rfl
@[simp]
lemma monoid_with_zero_hom.to_monoid_hom_coe [monoid_with_zero M] [monoid_with_zero N]
(f : monoid_with_zero_hom M N) :
(f.to_monoid_hom : M → N) = f := rfl
@[to_additive]
theorem one_hom.congr_fun [has_one M] [has_one N]
{f g : one_hom M N} (h : f = g) (x : M) : f x = g x :=
congr_arg (λ h : one_hom M N, h x) h
@[to_additive]
theorem mul_hom.congr_fun [has_mul M] [has_mul N]
{f g : mul_hom M N} (h : f = g) (x : M) : f x = g x :=
congr_arg (λ h : mul_hom M N, h x) h
@[to_additive]
theorem monoid_hom.congr_fun [monoid M] [monoid N]
{f g : M →* N} (h : f = g) (x : M) : f x = g x :=
congr_arg (λ h : M →* N, h x) h
theorem monoid_with_zero_hom.congr_fun [monoid_with_zero M] [monoid_with_zero N]
{f g : monoid_with_zero_hom M N} (h : f = g) (x : M) : f x = g x :=
congr_arg (λ h : monoid_with_zero_hom M N, h x) h
@[to_additive]
theorem one_hom.congr_arg [has_one M] [has_one N]
(f : one_hom M N) {x y : M} (h : x = y) : f x = f y :=
congr_arg (λ x : M, f x) h
@[to_additive]
theorem mul_hom.congr_arg [has_mul M] [has_mul N]
(f : mul_hom M N) {x y : M} (h : x = y) : f x = f y :=
congr_arg (λ x : M, f x) h
@[to_additive]
theorem monoid_hom.congr_arg [monoid M] [monoid N]
(f : M →* N) {x y : M} (h : x = y) : f x = f y :=
congr_arg (λ x : M, f x) h
theorem monoid_with_zero_hom.congr_arg [monoid_with_zero M] [monoid_with_zero N]
(f : monoid_with_zero_hom M N) {x y : M} (h : x = y) : f x = f y :=
congr_arg (λ x : M, f x) h
@[to_additive]
lemma one_hom.coe_inj [has_one M] [has_one N] ⦃f g : one_hom M N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
@[to_additive]
lemma mul_hom.coe_inj [has_mul M] [has_mul N] ⦃f g : mul_hom M N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
@[to_additive]
lemma monoid_hom.coe_inj [monoid M] [monoid N] ⦃f g : M →* N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
lemma monoid_with_zero_hom.coe_inj [monoid_with_zero M] [monoid_with_zero N]
⦃f g : monoid_with_zero_hom M N⦄ (h : (f : M → N) = g) : f = g :=
by cases f; cases g; cases h; refl
@[ext, to_additive]
lemma one_hom.ext [has_one M] [has_one N] ⦃f g : one_hom M N⦄ (h : ∀ x, f x = g x) : f = g :=
one_hom.coe_inj (funext h)
@[ext, to_additive]
lemma mul_hom.ext [has_mul M] [has_mul N] ⦃f g : mul_hom M N⦄ (h : ∀ x, f x = g x) : f = g :=
mul_hom.coe_inj (funext h)
@[ext, to_additive]
lemma monoid_hom.ext [monoid M] [monoid N] ⦃f g : M →* N⦄ (h : ∀ x, f x = g x) : f = g :=
monoid_hom.coe_inj (funext h)
@[ext]
lemma monoid_with_zero_hom.ext [monoid_with_zero M] [monoid_with_zero N]
⦃f g : monoid_with_zero_hom M N⦄ (h : ∀ x, f x = g x) : f = g :=
monoid_with_zero_hom.coe_inj (funext h)
attribute [ext] zero_hom.ext add_hom.ext add_monoid_hom.ext
@[to_additive]
lemma one_hom.ext_iff [has_one M] [has_one N] {f g : one_hom M N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, one_hom.ext h⟩
@[to_additive]
lemma mul_hom.ext_iff [has_mul M] [has_mul N] {f g : mul_hom M N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, mul_hom.ext h⟩
@[to_additive]
lemma monoid_hom.ext_iff [monoid M] [monoid N] {f g : M →* N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, monoid_hom.ext h⟩
lemma monoid_with_zero_hom.ext_iff [monoid_with_zero M] [monoid_with_zero N]
{f g : monoid_with_zero_hom M N} : f = g ↔ ∀ x, f x = g x :=
⟨λ h x, h ▸ rfl, λ h, monoid_with_zero_hom.ext h⟩
@[simp, to_additive]
lemma one_hom.mk_coe [has_one M] [has_one N]
(f : one_hom M N) (h1) : one_hom.mk f h1 = f :=
one_hom.ext $ λ _, rfl
@[simp, to_additive]
lemma mul_hom.mk_coe [has_mul M] [has_mul N]
(f : mul_hom M N) (hmul) : mul_hom.mk f hmul = f :=
mul_hom.ext $ λ _, rfl
@[simp, to_additive]
lemma monoid_hom.mk_coe [monoid M] [monoid N]
(f : M →* N) (h1 hmul) : monoid_hom.mk f h1 hmul = f :=
monoid_hom.ext $ λ _, rfl
@[simp]
lemma monoid_with_zero_hom.mk_coe [monoid_with_zero M] [monoid_with_zero N]
(f : monoid_with_zero_hom M N) (h0 h1 hmul) : monoid_with_zero_hom.mk f h0 h1 hmul = f :=
monoid_with_zero_hom.ext $ λ _, rfl
end coes
@[simp, to_additive]
lemma one_hom.map_one [has_one M] [has_one N] (f : one_hom M N) : f 1 = 1 := f.map_one'
/-- If `f` is a monoid homomorphism then `f 1 = 1`. -/
@[simp, to_additive]
lemma monoid_hom.map_one [monoid M] [monoid N] (f : M →* N) : f 1 = 1 := f.map_one'
@[simp]
lemma monoid_with_zero_hom.map_one [monoid_with_zero M] [monoid_with_zero N]
(f : monoid_with_zero_hom M N) : f 1 = 1 := f.map_one'
/-- If `f` is an additive monoid homomorphism then `f 0 = 0`. -/
add_decl_doc add_monoid_hom.map_zero
@[simp]
lemma monoid_with_zero_hom.map_zero [monoid_with_zero M] [monoid_with_zero N]
(f : monoid_with_zero_hom M N) : f 0 = 0 := f.map_zero'
@[simp, to_additive]
lemma mul_hom.map_mul [has_mul M] [has_mul N]
(f : mul_hom M N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b
/-- If `f` is a monoid homomorphism then `f (a * b) = f a * f b`. -/
@[simp, to_additive]
lemma monoid_hom.map_mul [monoid M] [monoid N]
(f : M →* N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b
@[simp]
lemma monoid_with_zero_hom.map_mul [monoid_with_zero M] [monoid_with_zero N]
(f : monoid_with_zero_hom M N) (a b : M) : f (a * b) = f a * f b := f.map_mul' a b
/-- If `f` is an additive monoid homomorphism then `f (a + b) = f a + f b`. -/
add_decl_doc add_monoid_hom.map_add
namespace monoid_hom
variables {mM : monoid M} {mN : monoid N} {mP : monoid P}
variables [group G] [comm_group H]
include mM mN
@[to_additive]
lemma map_mul_eq_one (f : M →* N) {a b : M} (h : a * b = 1) : f a * f b = 1 :=
by rw [← f.map_mul, h, f.map_one]
/-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a right inverse,
then `f x` has a right inverse too. For elements invertible on both sides see `is_unit.map`. -/
@[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has
a right inverse, then `f x` has a right inverse too."]
lemma map_exists_right_inv (f : M →* N) {x : M} (hx : ∃ y, x * y = 1) :
∃ y, f x * y = 1 :=
let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩
/-- Given a monoid homomorphism `f : M →* N` and an element `x : M`, if `x` has a left inverse,
then `f x` has a left inverse too. For elements invertible on both sides see `is_unit.map`. -/
@[to_additive "Given an add_monoid homomorphism `f : M →+ N` and an element `x : M`, if `x` has
a left inverse, then `f x` has a left inverse too. For elements invertible on both sides see
`is_add_unit.map`."]
lemma map_exists_left_inv (f : M →* N) {x : M} (hx : ∃ y, y * x = 1) :
∃ y, y * f x = 1 :=
let ⟨y, hy⟩ := hx in ⟨f y, f.map_mul_eq_one hy⟩
end monoid_hom
/-- The identity map from a type with 1 to itself. -/
@[to_additive]
def one_hom.id (M : Type*) [has_one M] : one_hom M M :=
{ to_fun := id, map_one' := rfl, }
/-- The identity map from a type with multiplication to itself. -/
@[to_additive]
def mul_hom.id (M : Type*) [has_mul M] : mul_hom M M :=
{ to_fun := id, map_mul' := λ _ _, rfl, }
/-- The identity map from a monoid to itself. -/
@[to_additive]
def monoid_hom.id (M : Type*) [monoid M] : M →* M :=
{ to_fun := id, map_one' := rfl, map_mul' := λ _ _, rfl, }
/-- The identity map from a monoid_with_zero to itself. -/
def monoid_with_zero_hom.id (M : Type*) [monoid_with_zero M] : monoid_with_zero_hom M M :=
{ to_fun := id, map_zero' := rfl, map_one' := rfl, map_mul' := λ _ _, rfl, }
/-- The identity map from an type with zero to itself. -/
add_decl_doc zero_hom.id
/-- The identity map from an type with addition to itself. -/
add_decl_doc add_hom.id
/-- The identity map from an additive monoid to itself. -/
add_decl_doc add_monoid_hom.id
@[simp, to_additive] lemma one_hom.id_apply {M : Type*} [has_one M] (x : M) :
one_hom.id M x = x := rfl
@[simp, to_additive] lemma mul_hom.id_apply {M : Type*} [has_mul M] (x : M) :
mul_hom.id M x = x := rfl
@[simp, to_additive] lemma monoid_hom.id_apply {M : Type*} [monoid M] (x : M) :
monoid_hom.id M x = x := rfl
@[simp] lemma monoid_with_zero_hom.id_apply {M : Type*} [monoid_with_zero M] (x : M) :
monoid_with_zero_hom.id M x = x := rfl
/-- Composition of `one_hom`s as a `one_hom`. -/
@[to_additive]
def one_hom.comp [has_one M] [has_one N] [has_one P]
(hnp : one_hom N P) (hmn : one_hom M N) : one_hom M P :=
{ to_fun := hnp ∘ hmn, map_one' := by simp, }
/-- Composition of `mul_hom`s as a `mul_hom`. -/
@[to_additive]
def mul_hom.comp [has_mul M] [has_mul N] [has_mul P]
(hnp : mul_hom N P) (hmn : mul_hom M N) : mul_hom M P :=
{ to_fun := hnp ∘ hmn, map_mul' := by simp, }
/-- Composition of monoid morphisms as a monoid morphism. -/
@[to_additive]
def monoid_hom.comp [monoid M] [monoid N] [monoid P] (hnp : N →* P) (hmn : M →* N) : M →* P :=
{ to_fun := hnp ∘ hmn, map_one' := by simp, map_mul' := by simp, }
/-- Composition of `monoid_with_zero_hom`s as a `monoid_with_zero_hom`. -/
def monoid_with_zero_hom.comp [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P]
(hnp : monoid_with_zero_hom N P) (hmn : monoid_with_zero_hom M N) : monoid_with_zero_hom M P :=
{ to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_mul' := by simp, }
/-- Composition of `zero_hom`s as a `zero_hom`. -/
add_decl_doc zero_hom.comp
/-- Composition of `add_hom`s as a `add_hom`. -/
add_decl_doc add_hom.comp
/-- Composition of additive monoid morphisms as an additive monoid morphism. -/
add_decl_doc add_monoid_hom.comp
@[simp, to_additive] lemma one_hom.coe_comp [has_one M] [has_one N] [has_one P]
(g : one_hom N P) (f : one_hom M N) :
⇑(g.comp f) = g ∘ f := rfl
@[simp, to_additive] lemma mul_hom.coe_comp [has_mul M] [has_mul N] [has_mul P]
(g : mul_hom N P) (f : mul_hom M N) :
⇑(g.comp f) = g ∘ f := rfl
@[simp, to_additive] lemma monoid_hom.coe_comp [monoid M] [monoid N] [monoid P]
(g : N →* P) (f : M →* N) :
⇑(g.comp f) = g ∘ f := rfl
@[simp] lemma monoid_with_zero_hom.coe_comp [monoid_with_zero M] [monoid_with_zero N]
[monoid_with_zero P]
(g : monoid_with_zero_hom N P) (f : monoid_with_zero_hom M N) :
⇑(g.comp f) = g ∘ f := rfl
@[to_additive] lemma one_hom.comp_apply [has_one M] [has_one N] [has_one P]
(g : one_hom N P) (f : one_hom M N) (x : M) :
g.comp f x = g (f x) := rfl
@[to_additive] lemma mul_hom.comp_apply [has_mul M] [has_mul N] [has_mul P]
(g : mul_hom N P) (f : mul_hom M N) (x : M) :
g.comp f x = g (f x) := rfl
@[to_additive] lemma monoid_hom.comp_apply [monoid M] [monoid N] [monoid P]
(g : N →* P) (f : M →* N) (x : M) :
g.comp f x = g (f x) := rfl
lemma monoid_with_zero_hom.comp_apply [monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P]
(g : monoid_with_zero_hom N P) (f : monoid_with_zero_hom M N) (x : M) :
g.comp f x = g (f x) := rfl
/-- Composition of monoid homomorphisms is associative. -/
@[to_additive] lemma one_hom.comp_assoc {Q : Type*} [has_one M] [has_one N] [has_one P] [has_one Q]
(f : one_hom M N) (g : one_hom N P) (h : one_hom P Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[to_additive] lemma mul_hom.comp_assoc {Q : Type*} [has_mul M] [has_mul N] [has_mul P] [has_mul Q]
(f : mul_hom M N) (g : mul_hom N P) (h : mul_hom P Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[to_additive] lemma monoid_hom.comp_assoc {Q : Type*} [monoid M] [monoid N] [monoid P] [monoid Q]
(f : M →* N) (g : N →* P) (h : P →* Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
lemma monoid_with_zero_hom.comp_assoc {Q : Type*}
[monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P] [monoid_with_zero Q]
(f : monoid_with_zero_hom M N) (g : monoid_with_zero_hom N P) (h : monoid_with_zero_hom P Q) :
(h.comp g).comp f = h.comp (g.comp f) := rfl
@[to_additive]
lemma one_hom.cancel_right [has_one M] [has_one N] [has_one P]
{g₁ g₂ : one_hom N P} {f : one_hom M N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, one_hom.ext $ (forall_iff_forall_surj hf).1 (one_hom.ext_iff.1 h), λ h, h ▸ rfl⟩
@[to_additive]
lemma mul_hom.cancel_right [has_mul M] [has_mul N] [has_mul P]
{g₁ g₂ : mul_hom N P} {f : mul_hom M N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, mul_hom.ext $ (forall_iff_forall_surj hf).1 (mul_hom.ext_iff.1 h), λ h, h ▸ rfl⟩
@[to_additive]
lemma monoid_hom.cancel_right [monoid M] [monoid N] [monoid P]
{g₁ g₂ : N →* P} {f : M →* N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, monoid_hom.ext $ (forall_iff_forall_surj hf).1 (monoid_hom.ext_iff.1 h), λ h, h ▸ rfl⟩
lemma monoid_with_zero_hom.cancel_right
[monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P]
{g₁ g₂ : monoid_with_zero_hom N P} {f : monoid_with_zero_hom M N} (hf : function.surjective f) :
g₁.comp f = g₂.comp f ↔ g₁ = g₂ :=
⟨λ h, monoid_with_zero_hom.ext $ (forall_iff_forall_surj hf).1 (monoid_with_zero_hom.ext_iff.1 h),
λ h, h ▸ rfl⟩
@[to_additive]
lemma one_hom.cancel_left [has_one M] [has_one N] [has_one P]
{g : one_hom N P} {f₁ f₂ : one_hom M N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, one_hom.ext $ λ x, hg $ by rw [← one_hom.comp_apply, h, one_hom.comp_apply],
λ h, h ▸ rfl⟩
@[to_additive]
lemma mul_hom.cancel_left [has_one M] [has_one N] [has_one P]
{g : one_hom N P} {f₁ f₂ : one_hom M N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, one_hom.ext $ λ x, hg $ by rw [← one_hom.comp_apply, h, one_hom.comp_apply],
λ h, h ▸ rfl⟩
@[to_additive]
lemma monoid_hom.cancel_left [monoid M] [monoid N] [monoid P]
{g : N →* P} {f₁ f₂ : M →* N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, monoid_hom.ext $ λ x, hg $ by rw [← monoid_hom.comp_apply, h, monoid_hom.comp_apply],
λ h, h ▸ rfl⟩
lemma monoid_with_zero_hom.cancel_left
[monoid_with_zero M] [monoid_with_zero N] [monoid_with_zero P]
{g : monoid_with_zero_hom N P} {f₁ f₂ : monoid_with_zero_hom M N} (hg : function.injective g) :
g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ :=
⟨λ h, monoid_with_zero_hom.ext $ λ x, hg $ by rw [
← monoid_with_zero_hom.comp_apply, h, monoid_with_zero_hom.comp_apply],
λ h, h ▸ rfl⟩
@[simp, to_additive] lemma one_hom.comp_id [has_one M] [has_one N]
(f : one_hom M N) : f.comp (one_hom.id M) = f := one_hom.ext $ λ x, rfl
@[simp, to_additive] lemma mul_hom.comp_id [has_mul M] [has_mul N]
(f : mul_hom M N) : f.comp (mul_hom.id M) = f := mul_hom.ext $ λ x, rfl
@[simp, to_additive] lemma monoid_hom.comp_id [monoid M] [monoid N]
(f : M →* N) : f.comp (monoid_hom.id M) = f := monoid_hom.ext $ λ x, rfl
@[simp] lemma monoid_with_zero_hom.comp_id [monoid_with_zero M] [monoid_with_zero N]
(f : monoid_with_zero_hom M N) : f.comp (monoid_with_zero_hom.id M) = f :=
monoid_with_zero_hom.ext $ λ x, rfl
@[simp, to_additive] lemma one_hom.id_comp [has_one M] [has_one N]
(f : one_hom M N) : (one_hom.id N).comp f = f := one_hom.ext $ λ x, rfl
@[simp, to_additive] lemma mul_hom.id_comp [has_mul M] [has_mul N]
(f : mul_hom M N) : (mul_hom.id N).comp f = f := mul_hom.ext $ λ x, rfl
@[simp, to_additive] lemma monoid_hom.id_comp [monoid M] [monoid N]
(f : M →* N) : (monoid_hom.id N).comp f = f := monoid_hom.ext $ λ x, rfl
@[simp] lemma monoid_with_zero_hom.id_comp [monoid_with_zero M] [monoid_with_zero N]
(f : monoid_with_zero_hom M N) : (monoid_with_zero_hom.id N).comp f = f :=
monoid_with_zero_hom.ext $ λ x, rfl
section End
namespace monoid
variables (M) [monoid M]
/-- The monoid of endomorphisms. -/
protected def End := M →* M
namespace End
instance : monoid (monoid.End M) :=
{ mul := monoid_hom.comp,
one := monoid_hom.id M,
mul_assoc := λ _ _ _, monoid_hom.comp_assoc _ _ _,
mul_one := monoid_hom.comp_id,
one_mul := monoid_hom.id_comp }
instance : inhabited (monoid.End M) := ⟨1⟩
instance : has_coe_to_fun (monoid.End M) := ⟨_, monoid_hom.to_fun⟩
end End
@[simp] lemma coe_one : ((1 : monoid.End M) : M → M) = id := rfl
@[simp] lemma coe_mul (f g) : ((f * g : monoid.End M) : M → M) = f ∘ g := rfl
end monoid
namespace add_monoid
variables (A : Type*) [add_monoid A]
/-- The monoid of endomorphisms. -/
protected def End := A →+ A
namespace End
instance : monoid (add_monoid.End A) :=
{ mul := add_monoid_hom.comp,
one := add_monoid_hom.id A,
mul_assoc := λ _ _ _, add_monoid_hom.comp_assoc _ _ _,
mul_one := add_monoid_hom.comp_id,
one_mul := add_monoid_hom.id_comp }
instance : inhabited (add_monoid.End A) := ⟨1⟩
instance : has_coe_to_fun (add_monoid.End A) := ⟨_, add_monoid_hom.to_fun⟩
end End
@[simp] lemma coe_one : ((1 : add_monoid.End A) : A → A) = id := rfl
@[simp] lemma coe_mul (f g) : ((f * g : add_monoid.End A) : A → A) = f ∘ g := rfl
end add_monoid
end End
/-- `1` is the homomorphism sending all elements to `1`. -/
@[to_additive]
instance [has_one M] [has_one N] : has_one (one_hom M N) := ⟨⟨λ _, 1, rfl⟩⟩
/-- `1` is the multiplicative homomorphism sending all elements to `1`. -/
@[to_additive]
instance [has_mul M] [monoid N] : has_one (mul_hom M N) := ⟨⟨λ _, 1, λ _ _, (one_mul 1).symm⟩⟩
/-- `1` is the monoid homomorphism sending all elements to `1`. -/
@[to_additive]
instance [monoid M] [monoid N] : has_one (M →* N) := ⟨⟨λ _, 1, rfl, λ _ _, (one_mul 1).symm⟩⟩
/-- `0` is the homomorphism sending all elements to `0`. -/
add_decl_doc zero_hom.has_zero
/-- `0` is the additive homomorphism sending all elements to `0`. -/
add_decl_doc add_hom.has_zero
/-- `0` is the additive monoid homomorphism sending all elements to `0`. -/
add_decl_doc add_monoid_hom.has_zero
@[simp, to_additive] lemma one_hom.one_apply [has_one M] [has_one N]
(x : M) : (1 : one_hom M N) x = 1 := rfl
@[simp, to_additive] lemma monoid_hom.one_apply [monoid M] [monoid N]
(x : M) : (1 : M →* N) x = 1 := rfl
@[simp, to_additive] lemma one_hom.one_comp [has_one M] [has_one N] [has_one P] (f : one_hom M N) :
(1 : one_hom N P).comp f = 1 := rfl
@[simp, to_additive] lemma one_hom.comp_one [has_one M] [has_one N] [has_one P] (f : one_hom N P) :
f.comp (1 : one_hom M N) = 1 :=
by { ext, simp only [one_hom.map_one, one_hom.coe_comp, function.comp_app, one_hom.one_apply] }
@[to_additive]
instance [has_one M] [has_one N] : inhabited (one_hom M N) := ⟨1⟩
@[to_additive]
instance [has_mul M] [monoid N] : inhabited (mul_hom M N) := ⟨1⟩
@[to_additive]
instance [monoid M] [monoid N] : inhabited (M →* N) := ⟨1⟩
-- unlike the other homs, `monoid_with_zero_hom` does not have a `1` or `0`
instance [monoid_with_zero M] : inhabited (monoid_with_zero_hom M M) := ⟨monoid_with_zero_hom.id M⟩
namespace monoid_hom
variables [mM : monoid M] [mN : monoid N] [mP : monoid P]
variables [group G] [comm_group H]
/-- Given two monoid morphisms `f`, `g` to a commutative monoid, `f * g` is the monoid morphism
sending `x` to `f x * g x`. -/
@[to_additive]
instance {M N} {mM : monoid M} [comm_monoid N] : has_mul (M →* N) :=
⟨λ f g,
{ to_fun := λ m, f m * g m,
map_one' := show f 1 * g 1 = 1, by simp,
map_mul' := begin intros, show f (x * y) * g (x * y) = f x * g x * (f y * g y),
rw [f.map_mul, g.map_mul, ←mul_assoc, ←mul_assoc, mul_right_comm (f x)], end }⟩
/-- Given two additive monoid morphisms `f`, `g` to an additive commutative monoid, `f + g` is the
additive monoid morphism sending `x` to `f x + g x`. -/
add_decl_doc add_monoid_hom.has_add
@[simp, to_additive] lemma mul_apply {M N} {mM : monoid M} {mN : comm_monoid N}
(f g : M →* N) (x : M) :
(f * g) x = f x * g x := rfl
@[simp, to_additive] lemma one_comp [monoid M] [monoid N] [monoid P] (f : M →* N) :
(1 : N →* P).comp f = 1 := rfl
@[simp, to_additive] lemma comp_one [monoid M] [monoid N] [monoid P] (f : N →* P) :
f.comp (1 : M →* N) = 1 :=
by { ext, simp only [map_one, coe_comp, function.comp_app, one_apply] }
@[to_additive] lemma mul_comp [monoid M] [comm_monoid N] [comm_monoid P]
(g₁ g₂ : N →* P) (f : M →* N) :
(g₁ * g₂).comp f = g₁.comp f * g₂.comp f := rfl
@[to_additive] lemma comp_mul [monoid M] [comm_monoid N] [comm_monoid P]
(g : N →* P) (f₁ f₂ : M →* N) :
g.comp (f₁ * f₂) = g.comp f₁ * g.comp f₂ :=
by { ext, simp only [mul_apply, function.comp_app, map_mul, coe_comp] }
/-- (M →* N) is a comm_monoid if N is commutative. -/
@[to_additive]
instance {M N} [monoid M] [comm_monoid N] : comm_monoid (M →* N) :=
{ mul := (*),
mul_assoc := by intros; ext; apply mul_assoc,
one := 1,
one_mul := by intros; ext; apply one_mul,
mul_one := by intros; ext; apply mul_one,
mul_comm := by intros; ext; apply mul_comm }
/-- `flip` arguments of `f : M →* N →* P` -/
@[to_additive "`flip` arguments of `f : M →+ N →+ P`"]
def flip {mM : monoid M} {mN : monoid N} {mP : comm_monoid P} (f : M →* N →* P) :
N →* M →* P :=
{ to_fun := λ y, ⟨λ x, f x y, by rw [f.map_one, one_apply], λ x₁ x₂, by rw [f.map_mul, mul_apply]⟩,
map_one' := ext $ λ x, (f x).map_one,
map_mul' := λ y₁ y₂, ext $ λ x, (f x).map_mul y₁ y₂ }
@[simp, to_additive] lemma flip_apply {mM : monoid M} {mN : monoid N} {mP : comm_monoid P}
(f : M →* N →* P) (x : M) (y : N) :
f.flip y x = f x y :=
rfl
/-- Evaluation of a `monoid_hom` at a point as a monoid homomorphism. See also `monoid_hom.apply`
for the evaluation of any function at a point. -/
@[to_additive "Evaluation of an `add_monoid_hom` at a point as an additive monoid homomorphism.
See also `add_monoid_hom.apply` for the evaluation of any function at a point."]
def eval [monoid M] [comm_monoid N] : M →* (M →* N) →* N := (monoid_hom.id (M →* N)).flip
@[simp, to_additive]
lemma eval_apply [monoid M] [comm_monoid N] (x : M) (f : M →* N) : eval x f = f x := rfl
/-- Composition of monoid morphisms (`monoid_hom.comp`) as a monoid morphism. -/
@[to_additive "Composition of additive monoid morphisms
(`add_monoid_hom.comp`) as an additive monoid morphism.", simps]
def comp_hom [monoid M] [comm_monoid N] [comm_monoid P] :
(N →* P) →* (M →* N) →* (M →* P) :=
{ to_fun := λ g, { to_fun := g.comp, map_one' := comp_one g, map_mul' := comp_mul g },
map_one' := by { ext1 f, exact one_comp f },
map_mul' := λ g₁ g₂, by { ext1 f, exact mul_comp g₁ g₂ f } }
/-- If two homomorphism from a group to a monoid are equal at `x`, then they are equal at `x⁻¹`. -/
@[to_additive "If two homomorphism from an additive group to an additive monoid are equal at `x`,
then they are equal at `-x`." ]
lemma eq_on_inv {G} [group G] [monoid M] {f g : G →* M} {x : G} (h : f x = g x) :
f x⁻¹ = g x⁻¹ :=
left_inv_eq_right_inv (f.map_mul_eq_one $ inv_mul_self x) $
h.symm ▸ g.map_mul_eq_one $ mul_inv_self x
/-- Group homomorphisms preserve inverse. -/
@[simp, to_additive]
theorem map_inv {G H} [group G] [group H] (f : G →* H) (g : G) : f g⁻¹ = (f g)⁻¹ :=
eq_inv_of_mul_eq_one $ f.map_mul_eq_one $ inv_mul_self g
/-- Group homomorphisms preserve division. -/
@[simp, to_additive]
theorem map_mul_inv {G H} [group G] [group H] (f : G →* H) (g h : G) :
f (g * h⁻¹) = (f g) * (f h)⁻¹ := by rw [f.map_mul, f.map_inv]
/-- A homomorphism from a group to a monoid is injective iff its kernel is trivial. -/
@[to_additive]
lemma injective_iff {G H} [group G] [monoid H] (f : G →* H) :
function.injective f ↔ (∀ a, f a = 1 → a = 1) :=
⟨λ h x hfx, h $ hfx.trans f.map_one.symm,
λ h x y hxy, mul_inv_eq_one.1 $ h _ $ by rw [f.map_mul, hxy, ← f.map_mul, mul_inv_self, f.map_one]⟩
include mM
/-- Makes a group homomorphism from a proof that the map preserves multiplication. -/
@[to_additive "Makes an additive group homomorphism from a proof that the map preserves addition."]
def mk' (f : M → G) (map_mul : ∀ a b : M, f (a * b) = f a * f b) : M →* G :=
{ to_fun := f,
map_mul' := map_mul,
map_one' := mul_self_iff_eq_one.1 $ by rw [←map_mul, mul_one] }
@[simp, to_additive]
lemma coe_mk' {f : M → G} (map_mul : ∀ a b : M, f (a * b) = f a * f b) :
⇑(mk' f map_mul) = f := rfl
omit mM
/-- Makes a group homomorphism from a proof that the map preserves right division `λ x y, x * y⁻¹`.
-/
@[to_additive "Makes an additive group homomorphism from a proof that the map preserves
the operation `λ a b, a + -b`. See also `add_monoid_hom.of_map_sub` for a version using
`λ a b, a - b`."]
def of_map_mul_inv {H : Type*} [group H] (f : G → H)
(map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) :
G →* H :=
mk' f $ λ x y,
calc f (x * y) = f x * (f $ 1 * 1⁻¹ * y⁻¹)⁻¹ : by simp only [one_mul, one_inv, ← map_div, inv_inv]
... = f x * f y : by { simp only [map_div], simp only [mul_right_inv, one_mul, inv_inv] }
@[simp, to_additive] lemma coe_of_map_mul_inv {H : Type*} [group H] (f : G → H)
(map_div : ∀ a b : G, f (a * b⁻¹) = f a * (f b)⁻¹) :
⇑(of_map_mul_inv f map_div) = f :=
rfl
/-- If `f` is a monoid homomorphism to a commutative group, then `f⁻¹` is the homomorphism sending
`x` to `(f x)⁻¹`. -/
@[to_additive]
instance {M G} [monoid M] [comm_group G] : has_inv (M →* G) :=
⟨λ f, mk' (λ g, (f g)⁻¹) $ λ a b, by rw [←mul_inv, f.map_mul]⟩
/-- If `f` is an additive monoid homomorphism to an additive commutative group, then `-f` is the
homomorphism sending `x` to `-(f x)`. -/
add_decl_doc add_monoid_hom.has_neg
@[simp, to_additive] lemma inv_apply {M G} {mM : monoid M} {gG : comm_group G}
(f : M →* G) (x : M) :
f⁻¹ x = (f x)⁻¹ := rfl
/-- If `f` and `g` are monoid homomorphisms to a commutative group, then `f / g` is the homomorphism
sending `x` to `(f x) / (g x). -/
@[to_additive]
instance {M G} [monoid M] [comm_group G] : has_div (M →* G) :=
⟨λ f g, mk' (λ x, f x / g x) $ λ a b,
by simp [div_eq_mul_inv, mul_assoc, mul_left_comm, mul_comm]⟩
/-- If `f` and `g` are monoid homomorphisms to an additive commutative group, then `f - g`
is the homomorphism sending `x` to `(f x) - (g x). -/
add_decl_doc add_monoid_hom.has_sub
@[simp, to_additive] lemma div_apply {M G} {mM : monoid M} {gG : comm_group G}
(f g : M →* G) (x : M) :
(f / g) x = f x / g x := rfl
/-- If `G` is a commutative group, then `M →* G` a commutative group too. -/
@[to_additive]
instance {M G} [monoid M] [comm_group G] : comm_group (M →* G) :=
{ inv := has_inv.inv,
div := has_div.div,
div_eq_mul_inv := by { intros, ext, apply div_eq_mul_inv },
mul_left_inv := by intros; ext; apply mul_left_inv,
..monoid_hom.comm_monoid }
/-- If `G` is an additive commutative group, then `M →+ G` an additive commutative group too. -/
add_decl_doc add_monoid_hom.add_comm_group
end monoid_hom
namespace add_monoid_hom
variables {A B : Type*} [add_monoid A] [add_comm_group B] [add_group G] [add_group H]
/-- Additive group homomorphisms preserve subtraction. -/
@[simp] theorem map_sub (f : G →+ H) (g h : G) : f (g - h) = (f g) - (f h) :=
by rw [sub_eq_add_neg, sub_eq_add_neg, f.map_add_neg g h]
/-- Define a morphism of additive groups given a map which respects difference. -/
def of_map_sub (f : G → H) (hf : ∀ x y, f (x - y) = f x - f y) : G →+ H :=
of_map_add_neg f (by simpa only [sub_eq_add_neg] using hf)
@[simp] lemma coe_of_map_sub (f : G → H) (hf : ∀ x y, f (x - y) = f x - f y) :
⇑(of_map_sub f hf) = f :=
rfl
end add_monoid_hom
section commute
variables [monoid M] [monoid N] {a x y : M}
@[simp, to_additive]
protected lemma semiconj_by.map (h : semiconj_by a x y) (f : M →* N) :
semiconj_by (f a) (f x) (f y) :=
by simpa only [semiconj_by, f.map_mul] using congr_arg f h
@[simp, to_additive]
protected lemma commute.map (h : commute x y) (f : M →* N) : commute (f x) (f y) := h.map f
end commute
|
c435d6d324f943126bf73a0ac776deb214396ae6 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebraic_geometry/Gamma_Spec_adjunction.lean | 1678717709f5fa2f53336c595dfcc730bfe1a5a4 | [
"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 | 16,159 | lean | /-
Copyright (c) 2021 Junyan Xu. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Junyan Xu
-/
import algebraic_geometry.Scheme
import category_theory.adjunction.limits
import category_theory.adjunction.reflective
/-!
# Adjunction between `Γ` and `Spec`
We define the adjunction `Γ_Spec.adjunction : Γ ⊣ Spec` by defining the unit (`to_Γ_Spec`,
in multiple steps in this file) and counit (done in Spec.lean) and checking that they satisfy
the left and right triangle identities. The constructions and proofs make use of
maps and lemmas defined and proved in structure_sheaf.lean extensively.
Notice that since the adjunction is between contravariant functors, you get to choose
one of the two categories to have arrows reversed, and it is equally valid to present
the adjunction as `Spec ⊣ Γ` (`Spec.to_LocallyRingedSpace.right_op ⊣ Γ`), in which
case the unit and the counit would switch to each other.
## Main definition
* `algebraic_geometry.identity_to_Γ_Spec` : The natural transformation `𝟭 _ ⟶ Γ ⋙ Spec`.
* `algebraic_geometry.Γ_Spec.LocallyRingedSpace_adjunction` : The adjunction `Γ ⊣ Spec` from
`CommRingᵒᵖ` to `LocallyRingedSpace`.
* `algebraic_geometry.Γ_Spec.adjunction` : The adjunction `Γ ⊣ Spec` from
`CommRingᵒᵖ` to `Scheme`.
-/
noncomputable theory
universes u
open prime_spectrum
namespace algebraic_geometry
open opposite
open category_theory
open structure_sheaf Spec (structure_sheaf)
open topological_space
open algebraic_geometry.LocallyRingedSpace
open Top.presheaf
open Top.presheaf.sheaf_condition
namespace LocallyRingedSpace
variable (X : LocallyRingedSpace.{u})
/-- The map from the global sections to a stalk. -/
def Γ_to_stalk (x : X) : Γ.obj (op X) ⟶ X.presheaf.stalk x :=
X.presheaf.germ (⟨x,trivial⟩ : (⊤ : opens X))
/-- The canonical map from the underlying set to the prime spectrum of `Γ(X)`. -/
def to_Γ_Spec_fun : X → prime_spectrum (Γ.obj (op X)) :=
λ x, comap (X.Γ_to_stalk x) (local_ring.closed_point (X.presheaf.stalk x))
lemma not_mem_prime_iff_unit_in_stalk (r : Γ.obj (op X)) (x : X) :
r ∉ (X.to_Γ_Spec_fun x).as_ideal ↔ is_unit (X.Γ_to_stalk x r) :=
by erw [local_ring.mem_maximal_ideal, not_not]
/-- The preimage of a basic open in `Spec Γ(X)` under the unit is the basic
open in `X` defined by the same element (they are equal as sets). -/
lemma to_Γ_Spec_preim_basic_open_eq (r : Γ.obj (op X)) :
X.to_Γ_Spec_fun⁻¹' (basic_open r).1 = (X.to_RingedSpace.basic_open r).1 :=
by { ext, erw X.to_RingedSpace.mem_top_basic_open, apply not_mem_prime_iff_unit_in_stalk }
/-- `to_Γ_Spec_fun` is continuous. -/
lemma to_Γ_Spec_continuous : continuous X.to_Γ_Spec_fun :=
begin
apply is_topological_basis_basic_opens.continuous,
rintro _ ⟨r, rfl⟩,
erw X.to_Γ_Spec_preim_basic_open_eq r,
exact (X.to_RingedSpace.basic_open r).2,
end
/-- The canonical (bundled) continuous map from the underlying topological
space of `X` to the prime spectrum of its global sections. -/
@[simps]
def to_Γ_Spec_base : X.to_Top ⟶ Spec.Top_obj (Γ.obj (op X)) :=
{ to_fun := X.to_Γ_Spec_fun,
continuous_to_fun := X.to_Γ_Spec_continuous }
variable (r : Γ.obj (op X))
/-- The preimage in `X` of a basic open in `Spec Γ(X)` (as an open set). -/
abbreviation to_Γ_Spec_map_basic_open : opens X :=
(opens.map X.to_Γ_Spec_base).obj (basic_open r)
/-- The preimage is the basic open in `X` defined by the same element `r`. -/
lemma to_Γ_Spec_map_basic_open_eq : X.to_Γ_Spec_map_basic_open r = X.to_RingedSpace.basic_open r :=
subtype.eq (X.to_Γ_Spec_preim_basic_open_eq r)
/-- The map from the global sections `Γ(X)` to the sections on the (preimage of) a basic open. -/
abbreviation to_to_Γ_Spec_map_basic_open :
X.presheaf.obj (op ⊤) ⟶ X.presheaf.obj (op $ X.to_Γ_Spec_map_basic_open r) :=
X.presheaf.map (X.to_Γ_Spec_map_basic_open r).le_top.op
/-- `r` is a unit as a section on the basic open defined by `r`. -/
lemma is_unit_res_to_Γ_Spec_map_basic_open :
is_unit (X.to_to_Γ_Spec_map_basic_open r r) :=
begin
convert (X.presheaf.map $ (eq_to_hom $ X.to_Γ_Spec_map_basic_open_eq r).op)
.is_unit_map (X.to_RingedSpace.is_unit_res_basic_open r),
rw ← comp_apply,
erw ← functor.map_comp,
congr
end
/-- Define the sheaf hom on individual basic opens for the unit. -/
def to_Γ_Spec_c_app :
(structure_sheaf $ Γ.obj $ op X).val.obj (op $ basic_open r) ⟶
X.presheaf.obj (op $ X.to_Γ_Spec_map_basic_open r) :=
is_localization.away.lift r (is_unit_res_to_Γ_Spec_map_basic_open _ r)
/-- Characterization of the sheaf hom on basic opens,
direction ← (next lemma) is used at various places, but → is not used in this file. -/
lemma to_Γ_Spec_c_app_iff
(f : (structure_sheaf $ Γ.obj $ op X).val.obj (op $ basic_open r) ⟶
X.presheaf.obj (op $ X.to_Γ_Spec_map_basic_open r)) :
to_open _ (basic_open r) ≫ f = X.to_to_Γ_Spec_map_basic_open r ↔ f = X.to_Γ_Spec_c_app r :=
begin
rw ← (is_localization.away.away_map.lift_comp r
(X.is_unit_res_to_Γ_Spec_map_basic_open r)),
swap 5, exact is_localization.to_basic_open _ r,
split,
{ intro h, refine is_localization.ring_hom_ext _ _,
swap 5, exact is_localization.to_basic_open _ r, exact h },
apply congr_arg,
end
lemma to_Γ_Spec_c_app_spec :
to_open _ (basic_open r) ≫ X.to_Γ_Spec_c_app r = X.to_to_Γ_Spec_map_basic_open r :=
(X.to_Γ_Spec_c_app_iff r _).2 rfl
/-- The sheaf hom on all basic opens, commuting with restrictions. -/
def to_Γ_Spec_c_basic_opens :
(induced_functor basic_open).op ⋙ (structure_sheaf (Γ.obj (op X))).1 ⟶
(induced_functor basic_open).op ⋙ ((Top.sheaf.pushforward X.to_Γ_Spec_base).obj X.𝒪).1 :=
{ app := λ r, X.to_Γ_Spec_c_app r.unop,
naturality' := λ r s f, begin
apply (structure_sheaf.to_basic_open_epi (Γ.obj (op X)) r.unop).1,
simp only [← category.assoc],
erw X.to_Γ_Spec_c_app_spec r.unop,
convert X.to_Γ_Spec_c_app_spec s.unop,
symmetry,
apply X.presheaf.map_comp
end }
/-- The canonical morphism of sheafed spaces from `X` to the spectrum of its global sections. -/
@[simps]
def to_Γ_Spec_SheafedSpace : X.to_SheafedSpace ⟶ Spec.to_SheafedSpace.obj (op (Γ.obj (op X))) :=
{ base := X.to_Γ_Spec_base,
c := Top.sheaf.restrict_hom_equiv_hom (structure_sheaf (Γ.obj (op X))).1 _
is_basis_basic_opens X.to_Γ_Spec_c_basic_opens }
lemma to_Γ_Spec_SheafedSpace_app_eq :
X.to_Γ_Spec_SheafedSpace.c.app (op (basic_open r)) = X.to_Γ_Spec_c_app r :=
Top.sheaf.extend_hom_app _ _ _ _ _
lemma to_Γ_Spec_SheafedSpace_app_spec (r : Γ.obj (op X)) :
to_open _ (basic_open r) ≫ X.to_Γ_Spec_SheafedSpace.c.app (op (basic_open r)) =
X.to_to_Γ_Spec_map_basic_open r :=
(X.to_Γ_Spec_SheafedSpace_app_eq r).symm ▸ X.to_Γ_Spec_c_app_spec r
/-- The map on stalks induced by the unit commutes with maps from `Γ(X)` to
stalks (in `Spec Γ(X)` and in `X`). -/
lemma to_stalk_stalk_map_to_Γ_Spec (x : X) : to_stalk _ _ ≫
PresheafedSpace.stalk_map X.to_Γ_Spec_SheafedSpace x = X.Γ_to_stalk x :=
begin
rw PresheafedSpace.stalk_map,
erw ← to_open_germ _ (basic_open (1 : Γ.obj (op X)))
⟨X.to_Γ_Spec_fun x, by rw basic_open_one; trivial⟩,
rw [← category.assoc, category.assoc (to_open _ _)],
erw stalk_functor_map_germ,
rw [← category.assoc (to_open _ _), X.to_Γ_Spec_SheafedSpace_app_spec 1],
unfold Γ_to_stalk,
rw ← stalk_pushforward_germ _ X.to_Γ_Spec_base X.presheaf ⊤,
congr' 1,
change (X.to_Γ_Spec_base _* X.presheaf).map le_top.hom.op ≫ _ = _,
apply germ_res,
end
/-- The canonical morphism from `X` to the spectrum of its global sections. -/
@[simps coe_base]
def to_Γ_Spec : X ⟶ Spec.LocallyRingedSpace_obj (Γ.obj (op X)) :=
{ val := X.to_Γ_Spec_SheafedSpace,
property :=
begin
intro x,
let p : prime_spectrum (Γ.obj (op X)) := X.to_Γ_Spec_fun x,
constructor, /- show stalk map is local hom ↓ -/
let S := (structure_sheaf _).val.stalk p,
rintros (t : S) ht,
obtain ⟨⟨r, s⟩, he⟩ := is_localization.surj p.as_ideal.prime_compl t,
dsimp at he,
apply is_unit_of_mul_is_unit_left,
rw he,
refine is_localization.map_units S (⟨r, _⟩ : p.as_ideal.prime_compl),
apply (not_mem_prime_iff_unit_in_stalk _ _ _).mpr,
rw [← to_stalk_stalk_map_to_Γ_Spec, comp_apply],
erw ← he,
rw ring_hom.map_mul,
exact ht.mul ((is_localization.map_units S s : _).map
(PresheafedSpace.stalk_map X.to_Γ_Spec_SheafedSpace x))
end }
lemma comp_ring_hom_ext {X : LocallyRingedSpace} {R : CommRing}
{f : R ⟶ Γ.obj (op X)} {β : X ⟶ Spec.LocallyRingedSpace_obj R}
(w : X.to_Γ_Spec.1.base ≫ (Spec.LocallyRingedSpace_map f).1.base = β.1.base)
(h : ∀ r : R,
f ≫ X.presheaf.map (hom_of_le le_top : (opens.map β.1.base).obj (basic_open r) ⟶ _).op =
to_open R (basic_open r) ≫ β.1.c.app (op (basic_open r))) :
X.to_Γ_Spec ≫ Spec.LocallyRingedSpace_map f = β :=
begin
ext1,
apply Spec.basic_open_hom_ext,
{ intros r _,
rw LocallyRingedSpace.comp_val_c_app,
erw to_open_comp_comap_assoc,
rw category.assoc,
erw [to_Γ_Spec_SheafedSpace_app_spec, ← X.presheaf.map_comp],
convert h r },
exact w,
end
/-- `to_Spec_Γ _` is an isomorphism so these are mutually two-sided inverses. -/
lemma Γ_Spec_left_triangle : to_Spec_Γ (Γ.obj (op X)) ≫ X.to_Γ_Spec.1.c.app (op ⊤) = 𝟙 _ :=
begin
unfold to_Spec_Γ,
rw ← to_open_res _ (basic_open (1 : Γ.obj (op X))) ⊤ (eq_to_hom basic_open_one.symm),
erw category.assoc,
rw [nat_trans.naturality, ← category.assoc],
erw [X.to_Γ_Spec_SheafedSpace_app_spec 1, ← functor.map_comp],
convert eq_to_hom_map X.presheaf _, refl,
end
end LocallyRingedSpace
/-- The unit as a natural transformation. -/
def identity_to_Γ_Spec : 𝟭 LocallyRingedSpace.{u} ⟶ Γ.right_op ⋙ Spec.to_LocallyRingedSpace :=
{ app := LocallyRingedSpace.to_Γ_Spec,
naturality' := λ X Y f, begin
symmetry,
apply LocallyRingedSpace.comp_ring_hom_ext,
{ ext1 x,
dsimp [Spec.Top_map, LocallyRingedSpace.to_Γ_Spec_fun],
rw [← subtype.val_eq_coe, ← local_ring.comap_closed_point (PresheafedSpace.stalk_map _ x),
← prime_spectrum.comap_comp_apply, ← prime_spectrum.comap_comp_apply],
congr' 2,
exact (PresheafedSpace.stalk_map_germ f.1 ⊤ ⟨x,trivial⟩).symm,
apply_instance },
{ intro r,
rw [LocallyRingedSpace.comp_val_c_app, ← category.assoc],
erw [Y.to_Γ_Spec_SheafedSpace_app_spec, f.1.c.naturality],
refl },
end }
namespace Γ_Spec
lemma left_triangle (X : LocallyRingedSpace) :
Spec_Γ_identity.inv.app (Γ.obj (op X)) ≫ (identity_to_Γ_Spec.app X).val.c.app (op ⊤) = 𝟙 _ :=
X.Γ_Spec_left_triangle
/-- `Spec_Γ_identity` is iso so these are mutually two-sided inverses. -/
lemma right_triangle (R : CommRing) :
identity_to_Γ_Spec.app (Spec.to_LocallyRingedSpace.obj $ op R) ≫
Spec.to_LocallyRingedSpace.map (Spec_Γ_identity.inv.app R).op = 𝟙 _ :=
begin
apply LocallyRingedSpace.comp_ring_hom_ext,
{ ext (p : prime_spectrum R) x,
erw ← is_localization.at_prime.to_map_mem_maximal_iff
((structure_sheaf R).val.stalk p) p.as_ideal x,
refl },
{ intro r, apply to_open_res },
end
-- Removing this makes the following definition time out.
local attribute [irreducible] Spec_Γ_identity identity_to_Γ_Spec Spec.to_LocallyRingedSpace
/-- The adjunction `Γ ⊣ Spec` from `CommRingᵒᵖ` to `LocallyRingedSpace`. -/
@[simps unit counit] def LocallyRingedSpace_adjunction : Γ.right_op ⊣ Spec.to_LocallyRingedSpace :=
adjunction.mk_of_unit_counit
{ unit := identity_to_Γ_Spec,
counit := (nat_iso.op Spec_Γ_identity).inv,
left_triangle' := by { ext X, erw category.id_comp,
exact congr_arg quiver.hom.op (left_triangle X) },
right_triangle' := by { ext1, ext1 R, erw category.id_comp,
exact right_triangle R.unop } }
local attribute [semireducible] Spec.to_LocallyRingedSpace
/-- The adjunction `Γ ⊣ Spec` from `CommRingᵒᵖ` to `Scheme`. -/
def adjunction : Scheme.Γ.right_op ⊣ Scheme.Spec :=
LocallyRingedSpace_adjunction.restrict_fully_faithful
Scheme.forget_to_LocallyRingedSpace (𝟭 _)
(nat_iso.of_components (λ X, iso.refl _) (λ _ _ f, by simpa))
(nat_iso.of_components (λ X, iso.refl _) (λ _ _ f, by simpa))
lemma adjunction_hom_equiv_apply {X : Scheme} {R : CommRingᵒᵖ}
(f : (op $ Scheme.Γ.obj $ op X) ⟶ R) :
Γ_Spec.adjunction.hom_equiv X R f =
LocallyRingedSpace_adjunction.hom_equiv X.1 R f :=
by { dsimp [adjunction, adjunction.restrict_fully_faithful], simp }
local attribute [irreducible] LocallyRingedSpace_adjunction Γ_Spec.adjunction
lemma adjunction_hom_equiv (X : Scheme) (R : CommRingᵒᵖ) :
Γ_Spec.adjunction.hom_equiv X R = LocallyRingedSpace_adjunction.hom_equiv X.1 R :=
equiv.ext $ λ f, adjunction_hom_equiv_apply f
lemma adjunction_hom_equiv_symm_apply {X : Scheme} {R : CommRingᵒᵖ}
(f : X ⟶ Scheme.Spec.obj R) :
(Γ_Spec.adjunction.hom_equiv X R).symm f =
(LocallyRingedSpace_adjunction.hom_equiv X.1 R).symm f :=
by { congr' 2, exact adjunction_hom_equiv _ _ }
@[simp] lemma adjunction_counit_app {R : CommRingᵒᵖ} :
Γ_Spec.adjunction.counit.app R = LocallyRingedSpace_adjunction.counit.app R :=
by { rw [← adjunction.hom_equiv_symm_id, ← adjunction.hom_equiv_symm_id,
adjunction_hom_equiv_symm_apply], refl }
@[simp] lemma adjunction_unit_app {X : Scheme} :
Γ_Spec.adjunction.unit.app X = LocallyRingedSpace_adjunction.unit.app X.1 :=
by { rw [← adjunction.hom_equiv_id, ← adjunction.hom_equiv_id, adjunction_hom_equiv_apply], refl }
local attribute [semireducible] LocallyRingedSpace_adjunction Γ_Spec.adjunction
instance is_iso_LocallyRingedSpace_adjunction_counit :
is_iso LocallyRingedSpace_adjunction.counit :=
is_iso.of_iso_inv _
instance is_iso_adjunction_counit : is_iso Γ_Spec.adjunction.counit :=
begin
apply_with nat_iso.is_iso_of_is_iso_app { instances := ff },
intro R,
rw adjunction_counit_app,
apply_instance,
end
-- This is just
-- `(Γ_Spec.adjunction.unit.app X).1.c.app (op ⊤) = Spec_Γ_identity.hom.app (X.presheaf.obj (op ⊤))`
-- But lean times out when trying to unify the types of the two sides.
lemma adjunction_unit_app_app_top (X : Scheme) :
@eq ((Scheme.Spec.obj (op $ X.presheaf.obj (op ⊤))).presheaf.obj (op ⊤) ⟶
((Γ_Spec.adjunction.unit.app X).1.base _* X.presheaf).obj (op ⊤))
((Γ_Spec.adjunction.unit.app X).val.c.app (op ⊤))
(Spec_Γ_identity.hom.app (X.presheaf.obj (op ⊤))) :=
begin
have := congr_app Γ_Spec.adjunction.left_triangle X,
dsimp at this,
rw ← is_iso.eq_comp_inv at this,
simp only [Γ_Spec.LocallyRingedSpace_adjunction_counit, nat_trans.op_app, category.id_comp,
Γ_Spec.adjunction_counit_app] at this,
rw [← op_inv, nat_iso.inv_inv_app, quiver.hom.op_inj.eq_iff] at this,
exact this
end
end Γ_Spec
/-! Immediate consequences of the adjunction. -/
/-- Spec preserves limits. -/
instance : limits.preserves_limits Spec.to_LocallyRingedSpace :=
Γ_Spec.LocallyRingedSpace_adjunction.right_adjoint_preserves_limits
instance Spec.preserves_limits : limits.preserves_limits Scheme.Spec :=
Γ_Spec.adjunction.right_adjoint_preserves_limits
/-- Spec is a full functor. -/
instance : full Spec.to_LocallyRingedSpace :=
R_full_of_counit_is_iso Γ_Spec.LocallyRingedSpace_adjunction
instance Spec.full : full Scheme.Spec :=
R_full_of_counit_is_iso Γ_Spec.adjunction
/-- Spec is a faithful functor. -/
instance : faithful Spec.to_LocallyRingedSpace :=
R_faithful_of_counit_is_iso Γ_Spec.LocallyRingedSpace_adjunction
instance Spec.faithful : faithful Scheme.Spec :=
R_faithful_of_counit_is_iso Γ_Spec.adjunction
instance : is_right_adjoint Spec.to_LocallyRingedSpace := ⟨_, Γ_Spec.LocallyRingedSpace_adjunction⟩
instance : is_right_adjoint Scheme.Spec := ⟨_, Γ_Spec.adjunction⟩
instance : reflective Spec.to_LocallyRingedSpace := ⟨⟩
instance Spec.reflective : reflective Scheme.Spec := ⟨⟩
end algebraic_geometry
|
aa1c687f42263d61fb3e7aa8805dd243dbaf834b | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /stage0/src/Lean/Elab/Deriving/Ord.lean | 77f9e0d73e08711effefa6771d6471bb0db91cc0 | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 4,408 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Dany Fabian
-/
import Lean.Meta.Transform
import Lean.Elab.Deriving.Basic
import Lean.Elab.Deriving.Util
namespace Lean.Elab.Deriving.Ord
open Lean.Parser.Term
open Meta
def mkOrdHeader (ctx : Context) (indVal : InductiveVal) : TermElabM Header := do
mkHeader ctx `Ord 2 indVal
def mkMatch (ctx : Context) (header : Header) (indVal : InductiveVal) (auxFunName : Name) : TermElabM Syntax := do
let discrs ← mkDiscrs header indVal
let alts ← mkAlts
`(match $[$discrs],* with $alts:matchAlt*)
where
mkAlts : TermElabM (Array Syntax) := do
let mut alts := #[]
for ctorName in indVal.ctors do
let ctorInfo ← getConstInfoCtor ctorName
let alt ← forallTelescopeReducing ctorInfo.type fun xs type => do
let type ← Core.betaReduce type -- we 'beta-reduce' to eliminate "artificial" dependencies
let mut indPatterns := #[]
-- add `_` pattern for indices
for i in [:indVal.numIndices] do
indPatterns := indPatterns.push (← `(_))
let mut ctorArgs1 := #[]
let mut ctorArgs2 := #[]
let mut rhs ← `(Ordering.eq)
-- add `_` for inductive parameters, they are inaccessible
for i in [:indVal.numParams] do
ctorArgs1 := ctorArgs1.push (← `(_))
ctorArgs2 := ctorArgs2.push (← `(_))
for i in [:ctorInfo.numFields] do
let x := xs[indVal.numParams + i]
if type.containsFVar x.fvarId! || (←isProp (←inferType x)) then
-- If resulting type depends on this field or is a proof, we don't need to compare
ctorArgs1 := ctorArgs1.push (← `(_))
ctorArgs2 := ctorArgs2.push (← `(_))
else
let a := mkIdent (← mkFreshUserName `a)
let b := mkIdent (← mkFreshUserName `b)
ctorArgs1 := ctorArgs1.push a
ctorArgs2 := ctorArgs2.push b
rhs ← `(match compare $a:ident $b:ident with
| Ordering.lt => Ordering.lt
| Ordering.gt => Ordering.gt
| Ordering.eq => $rhs)
let lPat ← `(@$(mkIdent ctorName):ident $ctorArgs1.reverse:term*)
let rPat ← `(@$(mkIdent ctorName):ident $ctorArgs2.reverse:term*)
let patterns := indPatterns ++ #[lPat, rPat]
let ltPatterns := indPatterns ++ #[lPat, ←`(_)]
let gtPatterns := indPatterns ++ #[←`(_), rPat]
#[←`(matchAltExpr| | $[$(patterns):term],* => $rhs:term),
←`(matchAltExpr| | $[$(ltPatterns):term],* => Ordering.lt),
←`(matchAltExpr| | $[$(gtPatterns):term],* => Ordering.gt)]
alts := alts ++ alt
return alts.pop.pop
def mkAuxFunction (ctx : Context) (i : Nat) : TermElabM Syntax := do
let auxFunName ← ctx.auxFunNames[i]
let indVal ← ctx.typeInfos[i]
let header ← mkOrdHeader ctx indVal
let mut body ← mkMatch ctx header indVal auxFunName
if ctx.usePartial || indVal.isRec then
let letDecls ← mkLocalInstanceLetDecls ctx `Ord header.argNames
body ← mkLet letDecls body
let binders := header.binders
if ctx.usePartial || indVal.isRec then
`(private partial def $(mkIdent auxFunName):ident $binders:explicitBinder* : Ordering := $body:term)
else
`(private def $(mkIdent auxFunName):ident $binders:explicitBinder* : Ordering := $body:term)
def mkMutualBlock (ctx : Context) : TermElabM Syntax := do
let mut auxDefs := #[]
for i in [:ctx.typeInfos.size] do
auxDefs := auxDefs.push (← mkAuxFunction ctx i)
`(mutual
$auxDefs:command*
end)
private def mkOrdInstanceCmds (declNames : Array Name) : TermElabM (Array Syntax) := do
let ctx ← mkContext "ord" declNames[0]
let cmds := #[← mkMutualBlock ctx] ++ (← mkInstanceCmds ctx `Ord declNames)
trace[Elab.Deriving.ord] "\n{cmds}"
return cmds
open Command
def mkOrdInstanceHandler (declNames : Array Name) : CommandElabM Bool := do
if (← declNames.allM isInductive) && declNames.size > 0 then
let cmds ← liftTermElabM none <| mkOrdInstanceCmds declNames
cmds.forM elabCommand
return true
else
return false
builtin_initialize
registerBuiltinDerivingHandler `Ord mkOrdInstanceHandler
registerTraceClass `Elab.Deriving.ord
end Lean.Elab.Deriving.Ord
|
59abebdc867802df0c11c9abd3f19ca46dea0522 | f4bff2062c030df03d65e8b69c88f79b63a359d8 | /src/game/sup_inf/lub_rationals.lean | c786a3170464af491baa26e89dcf9bdccfa6bab8 | [
"Apache-2.0"
] | permissive | adastra7470/real-number-game | 776606961f52db0eb824555ed2f8e16f92216ea3 | f9dcb7d9255a79b57e62038228a23346c2dc301b | refs/heads/master | 1,669,221,575,893 | 1,594,669,800,000 | 1,594,669,800,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 700 | lean | import game.sup_inf.supProdSets
namespace xena -- hide
/-
# Chapter 3 : Sup and Inf
## Level 11
-/
def embedded_rationals : set ℝ := {x : ℝ | ∃ y : ℚ, x = ↑y}
/- Lemma
The set of rational numbers does not have a supremum
-/
lemma not_lub_rationals : ∀ b : ℝ, ¬ (is_lub (embedded_rationals) b) :=
begin
intros b Hlub,
have Hbub : b ∈ upper_bounds embedded_rationals := Hlub.left,
have H : b < (b+1) := calc b = b+0 : (add_zero _).symm
... < b+1 : add_lt_add_left zero_lt_one _,
cases (exists_rat_btwn H) with q Hq,
have Hqin : ↑q ∈ embedded_rationals := ⟨q,rfl⟩,
have Hwrong2 := Hbub Hqin,
exact not_lt.2 Hwrong2 (Hq.left),
end
end xena -- hide
|
ef32a957d6011b9f81516c276868c7604c410184 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/logic/equiv/array.lean | cd709ecf95cbcdb8449c315f6b3be6d9d6fe9f5d | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 1,877 | 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`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
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 _ _)
|
69786f577601b79d6dc7a2c2849bc151059ae0d4 | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/algebra/big_operators/pi.lean | 6c42353b34fcc9632f6c802d8176e5b5781a5d57 | [] | no_license | AurelienSaue/Mathlib4_auto | f538cfd0980f65a6361eadea39e6fc639e9dae14 | 590df64109b08190abe22358fabc3eae000943f2 | refs/heads/master | 1,683,906,849,776 | 1,622,564,669,000 | 1,622,564,669,000 | 371,723,747 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,760 | lean | /-
Copyright (c) 2018 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Patrick Massot
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.algebra.ring.pi
import Mathlib.algebra.big_operators.basic
import Mathlib.data.fintype.basic
import Mathlib.algebra.group.prod
import Mathlib.PostPort
universes u_1 u_2 u_3
namespace Mathlib
/-!
# Big operators for Pi Types
This file contains theorems relevant to big operators in binary and arbitrary product
of monoids and groups
-/
namespace pi
theorem list_sum_apply {α : Type u_1} {β : α → Type u_2} [(a : α) → add_monoid (β a)] (a : α) (l : List ((a : α) → β a)) : list.sum l a = list.sum (list.map (fun (f : (a : α) → β a) => f a) l) :=
add_monoid_hom.map_list_sum (add_monoid_hom.apply β a) l
theorem multiset_sum_apply {α : Type u_1} {β : α → Type u_2} [(a : α) → add_comm_monoid (β a)] (a : α) (s : multiset ((a : α) → β a)) : multiset.sum s a = multiset.sum (multiset.map (fun (f : (a : α) → β a) => f a) s) :=
add_monoid_hom.map_multiset_sum (add_monoid_hom.apply β a) s
end pi
@[simp] theorem finset.sum_apply {α : Type u_1} {β : α → Type u_2} {γ : Type u_3} [(a : α) → add_comm_monoid (β a)] (a : α) (s : finset γ) (g : γ → (a : α) → β a) : finset.sum s (fun (c : γ) => g c) a = finset.sum s fun (c : γ) => g c a :=
add_monoid_hom.map_sum (add_monoid_hom.apply β a) (fun (c : γ) => g c) s
@[simp] theorem fintype.prod_apply {α : Type u_1} {β : α → Type u_2} {γ : Type u_3} [fintype γ] [(a : α) → comm_monoid (β a)] (a : α) (g : γ → (a : α) → β a) : finset.prod finset.univ (fun (c : γ) => g c) a = finset.prod finset.univ fun (c : γ) => g c a :=
finset.prod_apply a finset.univ g
theorem prod_mk_prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} [comm_monoid α] [comm_monoid β] (s : finset γ) (f : γ → α) (g : γ → β) : (finset.prod s fun (x : γ) => f x, finset.prod s fun (x : γ) => g x) = finset.prod s fun (x : γ) => (f x, g x) := sorry
-- As we only defined `single` into `add_monoid`, we only prove the `finset.sum` version here.
theorem finset.univ_sum_single {I : Type u_1} [DecidableEq I] {Z : I → Type u_2} [(i : I) → add_comm_monoid (Z i)] [fintype I] (f : (i : I) → Z i) : (finset.sum finset.univ fun (i : I) => pi.single i (f i)) = f := sorry
theorem add_monoid_hom.functions_ext {I : Type u_1} [DecidableEq I] {Z : I → Type u_2} [(i : I) → add_comm_monoid (Z i)] [fintype I] (G : Type u_3) [add_comm_monoid G] (g : ((i : I) → Z i) →+ G) (h : ((i : I) → Z i) →+ G) (w : ∀ (i : I) (x : Z i), coe_fn g (pi.single i x) = coe_fn h (pi.single i x)) : g = h := sorry
-- we need `apply`+`convert` because Lean fails to unify different `add_monoid` instances
-- on `Π i, f i`
theorem ring_hom.functions_ext {I : Type u_1} [DecidableEq I] {f : I → Type u_2} [(i : I) → semiring (f i)] [fintype I] (G : Type u_3) [semiring G] (g : ((i : I) → f i) →+* G) (h : ((i : I) → f i) →+* G) (w : ∀ (i : I) (x : f i), coe_fn g (pi.single i x) = coe_fn h (pi.single i x)) : g = h := sorry
namespace prod
theorem fst_prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} [comm_monoid α] [comm_monoid β] {s : finset γ} {f : γ → α × β} : fst (finset.prod s fun (c : γ) => f c) = finset.prod s fun (c : γ) => fst (f c) :=
monoid_hom.map_prod (monoid_hom.fst α β) f s
theorem snd_prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} [comm_monoid α] [comm_monoid β] {s : finset γ} {f : γ → α × β} : snd (finset.prod s fun (c : γ) => f c) = finset.prod s fun (c : γ) => snd (f c) :=
monoid_hom.map_prod (monoid_hom.snd α β) f s
|
ee41ab65b90316b7ccc1d67f7958d3ac06e25ae9 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/topology/algebra/mul_action.lean | 988e08cd04086bbf5a7a7dd96b093c317ca01bcb | [
"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 | 9,461 | 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 topology.algebra.monoid
import algebra.module.prod
import topology.homeomorph
/-!
# Continuous monoid action
In this file we define class `has_continuous_smul`. We say `has_continuous_smul M α` if `M` acts on
`α` and the map `(c, x) ↦ c • x` is continuous on `M × α`. We reuse this class for topological
(semi)modules, vector spaces and algebras.
## Main definitions
* `has_continuous_smul M α` : typeclass saying that the map `(c, x) ↦ c • x` is continuous
on `M × α`;
* `homeomorph.smul_of_unit`: scalar multiplication by a unit of `M` as a homeomorphism of `α`;
* `homeomorph.smul_of_ne_zero`: if a group with zero `G₀` (e.g., a field) acts on `α` and `c : G₀`
is a nonzero element of `G₀`, then scalar multiplication by `c` is a homeomorphism of `α`;
* `homeomorph.smul`: scalar multiplication by an element of a group `G` acting on `α`
is a homeomorphism of `α`.
## Main results
Besides homeomorphisms mentioned above, in this file we provide lemmas like `continuous.smul`
or `filter.tendsto.smul` that provide dot-syntax access to `continuous_smul`.
-/
open_locale topological_space
open filter
/-- Class `has_continuous_smul M α` says that the scalar multiplication `(•) : M → α → α`
is continuous in both arguments. We use the same class for all kinds of multiplicative actions,
including (semi)modules and algebras. -/
class has_continuous_smul (M α : Type*) [has_scalar M α]
[topological_space M] [topological_space α] : Prop :=
(continuous_smul : continuous (λp : M × α, p.1 • p.2))
export has_continuous_smul (continuous_smul)
variables {M α β : Type*} [topological_space M] [topological_space α]
section has_scalar
variables [has_scalar M α] [has_continuous_smul M α]
lemma filter.tendsto.smul {f : β → M} {g : β → α} {l : filter β} {c : M} {a : α}
(hf : tendsto f l (𝓝 c)) (hg : tendsto g l (𝓝 a)) :
tendsto (λ x, f x • g x) l (𝓝 $ c • a) :=
(continuous_smul.tendsto _).comp (hf.prod_mk_nhds hg)
lemma filter.tendsto.const_smul {f : β → α} {l : filter β} {a : α} (hf : tendsto f l (𝓝 a))
(c : M) :
tendsto (λ x, c • f x) l (𝓝 (c • a)) :=
tendsto_const_nhds.smul hf
variables [topological_space β] {f : β → M} {g : β → α} {b : β} {s : set β}
lemma continuous_within_at.smul (hf : continuous_within_at f s b)
(hg : continuous_within_at g s b) :
continuous_within_at (λ x, f x • g x) s b :=
hf.smul hg
lemma continuous_within_at.const_smul (hg : continuous_within_at g s b) (c : M) :
continuous_within_at (λ x, c • g x) s b :=
hg.const_smul c
lemma continuous_at.smul (hf : continuous_at f b) (hg : continuous_at g b) :
continuous_at (λ x, f x • g x) b :=
hf.smul hg
lemma continuous_at.const_smul (hg : continuous_at g b) (c : M) :
continuous_at (λ x, c • g x) b :=
hg.const_smul c
lemma continuous_on.smul (hf : continuous_on f s) (hg : continuous_on g s) :
continuous_on (λ x, f x • g x) s :=
λ x hx, (hf x hx).smul (hg x hx)
lemma continuous_on.const_smul (hg : continuous_on g s) (c : M) :
continuous_on (λ x, c • g x) s :=
λ x hx, (hg x hx).const_smul c
@[continuity]
lemma continuous.smul (hf : continuous f) (hg : continuous g) :
continuous (λ x, f x • g x) :=
continuous_smul.comp (hf.prod_mk hg)
lemma continuous.const_smul (hg : continuous g) (c : M) :
continuous (λ x, c • g x) :=
continuous_smul.comp (continuous_const.prod_mk hg)
end has_scalar
section monoid
variables [monoid M] [mul_action M α] [has_continuous_smul M α]
lemma units.tendsto_const_smul_iff {f : β → α} {l : filter β} {a : α} (u : units M) :
tendsto (λ x, (u : M) • f x) l (𝓝 $ (u : M) • a) ↔ tendsto f l (𝓝 a) :=
⟨λ h, by simpa only [u.inv_smul_smul] using h.const_smul ((u⁻¹ : units M) : M),
λ h, h.const_smul _⟩
lemma is_unit.tendsto_const_smul_iff {f : β → α} {l : filter β} {a : α} {c : M} (hc : is_unit c) :
tendsto (λ x, c • f x) l (𝓝 $ c • a) ↔ tendsto f l (𝓝 a) :=
let ⟨u, hu⟩ := hc in hu ▸ u.tendsto_const_smul_iff
variables [topological_space β] {f : β → α} {b : β} {c : M} {s : set β}
lemma is_unit.continuous_within_at_const_smul_iff (hc : is_unit c) :
continuous_within_at (λ x, c • f x) s b ↔ continuous_within_at f s b :=
hc.tendsto_const_smul_iff
lemma is_unit.continuous_on_const_smul_iff (hc : is_unit c) :
continuous_on (λ x, c • f x) s ↔ continuous_on f s :=
forall_congr $ λ b, forall_congr $ λ hb, hc.continuous_within_at_const_smul_iff
lemma is_unit.continuous_at_const_smul_iff (hc : is_unit c) :
continuous_at (λ x, c • f x) b ↔ continuous_at f b :=
hc.tendsto_const_smul_iff
lemma is_unit.continuous_const_smul_iff (hc : is_unit c) :
continuous (λ x, c • f x) ↔ continuous f :=
by simp only [continuous_iff_continuous_at, hc.continuous_at_const_smul_iff]
/-- Scalar multiplication by a unit of a monoid `M` acting on `α` is a homeomorphism from `α`
to itself. -/
protected def homeomorph.smul_of_unit (u : units M) : α ≃ₜ α :=
{ to_equiv := units.smul_perm_hom u,
continuous_to_fun := continuous_id.const_smul _,
continuous_inv_fun := continuous_id.const_smul _ }
lemma is_unit.is_open_map_smul (hc : is_unit c) : is_open_map (λ x : α, c • x) :=
let ⟨u, hu⟩ := hc in hu ▸ (homeomorph.smul_of_unit u).is_open_map
lemma is_unit.is_closed_map_smul (hc : is_unit c) : is_closed_map (λ x : α, c • x) :=
let ⟨u, hu⟩ := hc in hu ▸ (homeomorph.smul_of_unit u).is_closed_map
end monoid
section group_with_zero
variables {G₀ : Type*} [topological_space G₀] [group_with_zero G₀] [mul_action G₀ α]
[has_continuous_smul G₀ α]
lemma tendsto_const_smul_iff' {f : β → α} {l : filter β} {a : α} {c : G₀} (hc : c ≠ 0) :
tendsto (λ x, c • f x) l (𝓝 $ c • a) ↔ tendsto f l (𝓝 a) :=
(is_unit.mk0 c hc).tendsto_const_smul_iff
variables [topological_space β] {f : β → α} {b : β} {c : G₀} {s : set β}
lemma continuous_within_at_const_smul_iff' (hc : c ≠ 0) :
continuous_within_at (λ x, c • f x) s b ↔ continuous_within_at f s b :=
(is_unit.mk0 c hc).tendsto_const_smul_iff
lemma continuous_on_const_smul_iff' (hc : c ≠ 0) :
continuous_on (λ x, c • f x) s ↔ continuous_on f s :=
(is_unit.mk0 c hc).continuous_on_const_smul_iff
lemma continuous_at_const_smul_iff' (hc : c ≠ 0) :
continuous_at (λ x, c • f x) b ↔ continuous_at f b :=
(is_unit.mk0 c hc).continuous_at_const_smul_iff
lemma continuous_const_smul_iff' (hc : c ≠ 0) :
continuous (λ x, c • f x) ↔ continuous f :=
(is_unit.mk0 c hc).continuous_const_smul_iff
/-- Scalar multiplication by a non-zero element of a group with zero acting on `α` is a
homeomorphism from `α` onto itself. -/
protected def homeomorph.smul_of_ne_zero (c : G₀) (hc : c ≠ 0) : α ≃ₜ α :=
homeomorph.smul_of_unit (units.mk0 c hc)
lemma is_open_map_smul' {c : G₀} (hc : c ≠ 0) : is_open_map (λ x : α, c • x) :=
(is_unit.mk0 c hc).is_open_map_smul
/-- `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`. -/
lemma is_closed_map_smul' {c : G₀} (hc : c ≠ 0) : is_closed_map (λ x : α, c • x) :=
(is_unit.mk0 c hc).is_closed_map_smul
end group_with_zero
section group
variables {G : Type*} [topological_space G] [group G] [mul_action G α]
[has_continuous_smul G α]
lemma tendsto_const_smul_iff {f : β → α} {l : filter β} {a : α} (c : G) :
tendsto (λ x, c • f x) l (𝓝 $ c • a) ↔ tendsto f l (𝓝 a) :=
(to_units c).tendsto_const_smul_iff
variables [topological_space β] {f : β → α} {b : β} {s : set β}
lemma continuous_within_at_const_smul_iff (c : G) :
continuous_within_at (λ x, c • f x) s b ↔ continuous_within_at f s b :=
(group.is_unit c).tendsto_const_smul_iff
lemma continuous_on_const_smul_iff (c : G) :
continuous_on (λ x, c • f x) s ↔ continuous_on f s :=
(group.is_unit c).continuous_on_const_smul_iff
lemma continuous_at_const_smul_iff (c : G) :
continuous_at (λ x, c • f x) b ↔ continuous_at f b :=
(group.is_unit c).continuous_at_const_smul_iff
lemma continuous_const_smul_iff (c : G) :
continuous (λ x, c • f x) ↔ continuous f :=
(group.is_unit c).continuous_const_smul_iff
/-- Scalar multiplication by a unit of a monoid `M` acting on `α` is a homeomorphism from `α`
to itself. -/
protected def homeomorph.smul (c : G) : α ≃ₜ α :=
homeomorph.smul_of_unit (to_units c)
lemma is_open_map_smul (c : G) : is_open_map (λ x : α, c • x) :=
(homeomorph.smul c).is_open_map
lemma is_closed_map_smul (c : G) : is_closed_map (λ x : α, c • x) :=
(homeomorph.smul c).is_closed_map
end group
instance has_continuous_mul.has_continuous_smul {M : Type*} [monoid M]
[topological_space M] [has_continuous_mul M] :
has_continuous_smul M M :=
⟨continuous_mul⟩
instance [topological_space β] [has_scalar M α] [has_scalar M β] [has_continuous_smul M α]
[has_continuous_smul M β] :
has_continuous_smul M (α × β) :=
⟨(continuous_fst.smul (continuous_fst.comp continuous_snd)).prod_mk
(continuous_fst.smul (continuous_snd.comp continuous_snd))⟩
|
3a67b5ac6f9fbffe88974ee646bcad509e61ab6e | 1717bcbca047a0d25d687e7e9cd482fba00d058f | /src/measure_theory/set_integral.lean | 4ba1a01235c71d7df63abc587bd4d7587bbe0772 | [
"Apache-2.0"
] | permissive | swapnilkapoor22/mathlib | 51ad5804e6a0635ed5c7611cee73e089ab271060 | 3e7efd4ecd5d379932a89212eebd362beb01309e | refs/heads/master | 1,676,467,741,465 | 1,610,301,556,000 | 1,610,301,556,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 40,027 | lean | /-
Copyright (c) 2020 Zhouhang Zhou. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Zhouhang Zhou, Yury Kudryashov
-/
import measure_theory.bochner_integration
import analysis.normed_space.indicator_function
/-!
# Set integral
In this file we prove some properties of `∫ x in s, f x ∂μ`. Recall that this notation
is defined as `∫ x, f x ∂(μ.restrict s)`. In `integral_indicator` we prove that for a measurable
function `f` and a measurable set `s` this definition coincides with another natural definition:
`∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ`, where `indicator s f x` is equal to `f x` for `x ∈ s`
and is zero otherwise.
Since `∫ x in s, f x ∂μ` is a notation, one can rewrite or apply any theorem about `∫ x, f x ∂μ`
directly. In this file we prove some theorems about dependence of `∫ x in s, f x ∂μ` on `s`, e.g.
`integral_union`, `integral_empty`, `integral_univ`.
We also define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like
`integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`.
Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)`
saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable
at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite
at `l`.
Finally, we prove a version of the
[Fundamental theorem of calculus](https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus)
for set integral, see `filter.tendsto.integral_sub_linear_is_o_ae` and its corollaries.
Namely, consider a measurably generated filter `l`, a measure `μ` finite at this filter, and
a function `f` that has a finite limit `c` at `l ⊓ μ.ae`. Then `∫ x in s, f x ∂μ = μ s • c + o(μ s)`
as `s` tends to `l.lift' powerset`, i.e. for any `ε>0` there exists `t ∈ l` such that
`∥∫ x in s, f x ∂μ - μ s • c∥ ≤ ε * μ s` whenever `s ⊆ t`. We also formulate a version of this
theorem for a locally finite measure `μ` and a function `f` continuous at a point `a`.
## Notation
`∫ a in s, f a` is `measure_theory.integral (s.indicator f)`
## TODO
The file ends with over a hundred lines of commented out code. This is the old contents of this file
using the `indicator` approach to the definition of `∫ x in s, f x ∂μ`. This code should be
migrated to the new definition.
-/
noncomputable theory
open set filter topological_space measure_theory function
open_locale classical topological_space interval big_operators filter
variables {α β E F : Type*} [measurable_space α]
section piecewise
variables {μ : measure α} {s : set α} {f g : α → β}
lemma piecewise_ae_eq_restrict (hs : is_measurable s) : piecewise s f g =ᵐ[μ.restrict s] f :=
begin
rw [ae_restrict_eq hs],
exact (piecewise_eq_on s f g).eventually_eq.filter_mono inf_le_right
end
lemma piecewise_ae_eq_restrict_compl (hs : is_measurable s) :
piecewise s f g =ᵐ[μ.restrict sᶜ] g :=
begin
rw [ae_restrict_eq hs.compl],
exact (piecewise_eq_on_compl s f g).eventually_eq.filter_mono inf_le_right
end
end piecewise
section indicator_function
variables [has_zero β] {μ : measure α} {s : set α} {f : α → β}
lemma indicator_ae_eq_restrict (hs : is_measurable s) : indicator s f =ᵐ[μ.restrict s] f :=
piecewise_ae_eq_restrict hs
lemma indicator_ae_eq_restrict_compl (hs : is_measurable s) : indicator s f =ᵐ[μ.restrict sᶜ] 0 :=
piecewise_ae_eq_restrict_compl hs
end indicator_function
namespace measure_theory
section normed_group
lemma has_finite_integral_restrict_of_bounded [normed_group E] {f : α → E} {s : set α}
{μ : measure α} {C} (hs : μ s < ⊤) (hf : ∀ᵐ x ∂(μ.restrict s), ∥f x∥ ≤ C) :
has_finite_integral f (μ.restrict s) :=
by haveI : finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩;
exact has_finite_integral_of_bounded hf
variables [normed_group E] [measurable_space E] {f : α → E} {s t : set α} {μ ν : measure α}
/-- A function is `integrable_on` a set `s` if it is a measurable function and if the integral of
its pointwise norm over `s` is less than infinity. -/
def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop :=
integrable f (μ.restrict s)
lemma integrable_on.integrable (h : integrable_on f s μ) :
integrable f (μ.restrict s) :=
h
@[simp] lemma integrable_on_empty : integrable_on f ∅ μ :=
by simp [integrable_on, integrable_zero_measure]
@[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ :=
by rw [integrable_on, measure.restrict_univ]
lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _
lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ⊤ :=
integrable_const_iff.trans $ by rw [measure.restrict_apply_univ]
lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) :
integrable_on f s μ :=
h.mono_measure $ measure.restrict_mono hs hμ
lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) :
integrable_on f s μ :=
h.mono hst (le_refl _)
lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) :
integrable_on f s μ :=
h.mono (subset.refl _) hμ
lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) :
integrable_on f s μ :=
h.integrable.mono_measure $ restrict_mono_ae hst
lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ :=
h.mono_measure $ measure.restrict_le_self
lemma integrable.integrable_on' (h : integrable f (μ.restrict s)) : integrable_on f s μ :=
h
lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ :=
h.mono_set $ subset_union_left _ _
lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ :=
h.mono_set $ subset_union_right _ _
lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) :
integrable_on f (s ∪ t) μ :=
(hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _
@[simp] lemma integrable_on_union :
integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ :=
⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩
@[simp] lemma integrable_on_finite_union {s : set β} (hs : finite s)
{t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ :=
begin
apply hs.induction_on,
{ simp },
{ intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] }
end
@[simp] lemma integrable_on_finset_union {s : finset β} {t : β → set α} :
integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ :=
integrable_on_finite_union s.finite_to_set
lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) :
integrable_on f s (μ + ν) :=
by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν }
@[simp] lemma integrable_on_add_measure :
integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν :=
⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)),
h.mono_measure (measure.le_add_left (le_refl _))⟩,
λ h, h.1.add_measure h.2⟩
lemma ae_measurable_indicator_iff (hs : is_measurable s) :
ae_measurable f (μ.restrict s) ↔ ae_measurable (indicator s f) μ :=
begin
split,
{ assume h,
refine ⟨indicator s (h.mk f), h.measurable_mk.indicator hs, _⟩,
have A : s.indicator f =ᵐ[μ.restrict s] s.indicator (ae_measurable.mk f h) :=
(indicator_ae_eq_restrict hs).trans (h.ae_eq_mk.trans $ (indicator_ae_eq_restrict hs).symm),
have B : s.indicator f =ᵐ[μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) :=
(indicator_ae_eq_restrict_compl hs).trans (indicator_ae_eq_restrict_compl hs).symm,
have : s.indicator f =ᵐ[μ.restrict s + μ.restrict sᶜ] s.indicator (ae_measurable.mk f h) :=
ae_add_measure_iff.2 ⟨A, B⟩,
simpa only [hs, measure.restrict_add_restrict_compl] using this },
{ assume h,
exact (h.mono_measure measure.restrict_le_self).congr (indicator_ae_eq_restrict hs) }
end
lemma integrable_indicator_iff (hs : is_measurable s) :
integrable (indicator s f) μ ↔ integrable_on f s μ :=
by simp [integrable_on, integrable, has_finite_integral, nnnorm_indicator_eq_indicator_nnnorm,
ennreal.coe_indicator, lintegral_indicator _ hs, ae_measurable_indicator_iff hs]
lemma integrable_on.indicator (h : integrable_on f s μ) (hs : is_measurable s) :
integrable (indicator s f) μ :=
(integrable_indicator_iff hs).2 h
/-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some
set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.lift' powerset`. -/
def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) :=
∃ s ∈ l, integrable_on f s μ
variables {l l' : filter α}
protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) :
∀ᶠ s in l.lift' powerset, integrable_on f s μ :=
by { refine (eventually_lift'_powerset' $ λ s t hst ht, _).2 h, exact ht.mono_set hst }
lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) :
integrable_at_filter f l μ :=
let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩
lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) :
integrable_at_filter f (l ⊓ l') μ :=
hl.filter_mono inf_le_left
lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) :
integrable_at_filter f (l' ⊓ l) μ :=
hl.filter_mono inf_le_right
@[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} :
integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ :=
begin
refine ⟨_, λ h, h.filter_mono inf_le_left⟩,
rintros ⟨s, ⟨t, ht, u, hu, hs⟩, hf⟩,
refine ⟨t, ht, _⟩,
refine hf.integrable.mono_measure (λ v hv, _),
simp only [measure.restrict_apply hv],
refine measure_mono_ae (mem_sets_of_superset hu $ λ x hx, _),
exact λ ⟨hv, ht⟩, ⟨hv, hs ⟨ht, hx⟩⟩
end
alias integrable_at_filter.inf_ae_iff ↔ measure_theory.integrable_at_filter.of_inf_ae _
/-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded
above at `l`, then `f` is integrable at `l`. -/
lemma measure.finite_at_filter.integrable_at_filter (hfm : ae_measurable f μ)
{l : filter α} [is_measurably_generated l]
(hμ : μ.finite_at_filter l) (hf : l.is_bounded_under (≤) (norm ∘ f)) :
integrable_at_filter f l μ :=
begin
rcases hμ with ⟨s, hsl, hsμ⟩,
rcases hf with ⟨C, hC⟩,
simp only [eventually_map] at hC,
rcases hC.exists_measurable_mem with ⟨t, htl, htm, hC⟩,
refine ⟨t ∩ s, inter_mem_sets htl hsl, _⟩,
refine ⟨hfm.mono_measure measure.restrict_le_self, has_finite_integral_restrict_of_bounded
(lt_of_le_of_lt (measure_mono $ inter_subset_right _ _) hsμ) _⟩,
exact C,
suffices : ∀ᵐ x ∂μ.restrict t, ∥f x∥ ≤ C,
from ae_mono (measure.restrict_mono (inter_subset_left _ _) (le_refl _)) this,
rw [ae_restrict_eq htm, eventually_inf_principal],
exact eventually_of_forall hC
end
lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae (hfm : ae_measurable f μ)
{l : filter α} [is_measurably_generated l] (hμ : μ.finite_at_filter l) {b}
(hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) :
integrable_at_filter f l μ :=
(hμ.inf_of_left.integrable_at_filter hfm hf.norm.is_bounded_under_le).of_inf_ae
alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ←
filter.tendsto.integrable_at_filter_ae
lemma measure.finite_at_filter.integrable_at_filter_of_tendsto (hfm : ae_measurable f μ)
{l : filter α} [is_measurably_generated l] (hμ : μ.finite_at_filter l) {b}
(hf : tendsto f l (𝓝 b)) :
integrable_at_filter f l μ :=
hμ.integrable_at_filter hfm hf.norm.is_bounded_under_le
alias measure.finite_at_filter.integrable_at_filter_of_tendsto ← filter.tendsto.integrable_at_filter
variables [borel_space E] [second_countable_topology E]
lemma integrable_add [opens_measurable_space E] {f g : α → E}
(h : univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0}) (hf : measurable f) (hg : measurable g) :
integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ :=
begin
refine ⟨λ hfg, _, λ h, h.1.add h.2⟩,
rw [← indicator_add_eq_left h],
conv { congr, skip, rw [← indicator_add_eq_right h] },
rw [integrable_indicator_iff (hf (is_measurable_singleton 0)).compl],
rw [integrable_indicator_iff (hg (is_measurable_singleton 0)).compl],
exact ⟨hfg.integrable_on, hfg.integrable_on⟩
end
/-- To prove something for an arbitrary integrable function in a second countable
Borel normed group, it suffices to show that
* the property holds for (multiples of) characteristic functions;
* is closed under addition;
* the set of functions in the `L¹` space for which the property holds is closed.
* the property is closed under the almost-everywhere equal relation.
It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions
can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of
a simple function with a multiple of a characteristic function and that the intersection
of their images is a subset of `{0}`).
-/
@[elab_as_eliminator]
lemma integrable.induction (P : (α → E) → Prop)
(h_ind : ∀ (c : E) ⦃s⦄, is_measurable s → μ s < ⊤ → P (s.indicator (λ _, c)))
(h_sum : ∀ ⦃f g : α → E⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → integrable f μ → integrable g μ →
P f → P g → P (f + g))
(h_closed : is_closed {f : α →₁[μ] E | P f} )
(h_ae : ∀ ⦃f g⦄, f =ᵐ[μ] g → integrable f μ → P f → P g) :
∀ ⦃f : α → E⦄ (hf : integrable f μ), P f :=
begin
have : ∀ (f : simple_func α E), integrable f μ → P f,
{ refine simple_func.induction _ _,
{ intros c s hs h, dsimp only [simple_func.coe_const, simple_func.const_zero,
piecewise_eq_indicator, simple_func.coe_zero, simple_func.coe_piecewise] at h ⊢,
by_cases hc : c = 0,
{ subst hc, convert h_ind 0 is_measurable.empty (by simp) using 1, simp [const] },
apply h_ind c hs,
have : (nnnorm c : ennreal) * μ s < ⊤,
{ have := @comp_indicator _ _ _ _ (λ x : E, (nnnorm x : ennreal)) (const α c) s,
dsimp only at this,
have h' := h.has_finite_integral,
simpa [has_finite_integral, this, lintegral_indicator, hs] using h' },
exact ennreal.lt_top_of_mul_lt_top_right this (by simp [hc]) },
{ intros f g hfg hf hg int_fg,
rw [simple_func.coe_add, integrable_add hfg f.measurable g.measurable] at int_fg,
refine h_sum hfg int_fg.1 int_fg.2 (hf int_fg.1) (hg int_fg.2) } },
have : ∀ (f : α →₁ₛ[μ] E), P f,
{ intro f, exact h_ae f.to_simple_func_eq_to_fun f.integrable
(this f.to_simple_func f.integrable) },
have : ∀ (f : α →₁[μ] E), P f :=
λ f, l1.simple_func.dense_range.induction_on f h_closed this,
exact λ f hf, h_ae (l1.to_fun_of_fun f hf) (l1.integrable _) (this (l1.of_fun f hf))
end
variables [complete_space E] [normed_space ℝ E]
lemma integral_union (hst : disjoint s t) (hs : is_measurable s) (ht : is_measurable t)
(hfs : integrable_on f s μ) (hft : integrable_on f t μ) :
∫ x in s ∪ t, f x ∂μ = ∫ x in s, f x ∂μ + ∫ x in t, f x ∂μ :=
by simp only [integrable_on, measure.restrict_union hst hs ht, integral_add_measure hfs hft]
lemma integral_empty : ∫ x in ∅, f x ∂μ = 0 := by rw [measure.restrict_empty, integral_zero_measure]
lemma integral_univ : ∫ x in univ, f x ∂μ = ∫ x, f x ∂μ := by rw [measure.restrict_univ]
lemma integral_add_compl (hs : is_measurable s) (hfi : integrable f μ) :
∫ x in s, f x ∂μ + ∫ x in sᶜ, f x ∂μ = ∫ x, f x ∂μ :=
by rw [← integral_union disjoint_compl_right hs hs.compl hfi.integrable_on hfi.integrable_on,
union_compl_self, integral_univ]
/-- For a function `f` and a measurable set `s`, the integral of `indicator s f`
over the whole space is equal to `∫ x in s, f x ∂μ` defined as `∫ x, f x ∂(μ.restrict s)`. -/
lemma integral_indicator (hs : is_measurable s) :
∫ x, indicator s f x ∂μ = ∫ x in s, f x ∂μ :=
begin
by_cases hf : ae_measurable f (μ.restrict s), swap,
{ rw integral_non_ae_measurable hf,
rw [ae_measurable_indicator_iff hs] at hf,
exact integral_non_ae_measurable hf },
by_cases hfi : integrable_on f s μ, swap,
{ rwa [integral_undef, integral_undef],
rwa integrable_indicator_iff hs },
calc ∫ x, indicator s f x ∂μ = ∫ x in s, indicator s f x ∂μ + ∫ x in sᶜ, indicator s f x ∂μ :
(integral_add_compl hs (hfi.indicator hs)).symm
... = ∫ x in s, f x ∂μ + ∫ x in sᶜ, 0 ∂μ :
congr_arg2 (+) (integral_congr_ae (indicator_ae_eq_restrict hs))
(integral_congr_ae (indicator_ae_eq_restrict_compl hs))
... = ∫ x in s, f x ∂μ : by simp
end
lemma set_integral_const (c : E) : ∫ x in s, c ∂μ = (μ s).to_real • c :=
by rw [integral_const, measure.restrict_apply_univ]
@[simp]
lemma integral_indicator_const (e : E) ⦃s : set α⦄ (s_meas : is_measurable s) :
∫ (a : α), s.indicator (λ (x : α), e) a ∂μ = (μ s).to_real • e :=
by rw [integral_indicator s_meas, ← set_integral_const]
lemma set_integral_map {β} [measurable_space β] {g : α → β} {f : β → E} {s : set β}
(hs : is_measurable s) (hf : ae_measurable f (measure.map g μ)) (hg : measurable g) :
∫ y in s, f y ∂(measure.map g μ) = ∫ x in g ⁻¹' s, f (g x) ∂μ :=
begin
rw [measure.restrict_map hg hs, integral_map hg (hf.mono_measure _)],
exact measure.map_mono hg measure.restrict_le_self
end
lemma norm_set_integral_le_of_norm_le_const_ae {C : ℝ} (hs : μ s < ⊤)
(hC : ∀ᵐ x ∂μ.restrict s, ∥f x∥ ≤ C) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
begin
rw ← measure.restrict_apply_univ at *,
haveI : finite_measure (μ.restrict s) := ⟨‹_›⟩,
exact norm_integral_le_of_norm_le_const hC
end
lemma norm_set_integral_le_of_norm_le_const_ae' {C : ℝ} (hs : μ s < ⊤)
(hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) (hfm : ae_measurable f μ) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
begin
apply norm_set_integral_le_of_norm_le_const_ae hs,
have A : ∀ᵐ (x : α) ∂μ, x ∈ s → ∥ae_measurable.mk f hfm x∥ ≤ C,
{ filter_upwards [hC, hfm.ae_eq_mk],
assume a h1 h2 h3,
rw ← h2,
exact h1 h3 },
have B : is_measurable {x | ∥(hfm.mk f) x∥ ≤ C} := hfm.measurable_mk.norm is_measurable_Iic,
filter_upwards [eventually.filter_mono (ae_mono measure.restrict_le_self) hfm.ae_eq_mk,
(ae_restrict_iff B).2 A],
assume a h1 h2,
rwa h1
end
lemma norm_set_integral_le_of_norm_le_const_ae'' {C : ℝ} (hs : μ s < ⊤) (hsm : is_measurable s)
(hC : ∀ᵐ x ∂μ, x ∈ s → ∥f x∥ ≤ C) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
norm_set_integral_le_of_norm_le_const_ae hs $ by rwa [ae_restrict_eq hsm, eventually_inf_principal]
lemma norm_set_integral_le_of_norm_le_const {C : ℝ} (hs : μ s < ⊤)
(hC : ∀ x ∈ s, ∥f x∥ ≤ C) (hfm : ae_measurable f μ) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
norm_set_integral_le_of_norm_le_const_ae' hs (eventually_of_forall hC) hfm
lemma norm_set_integral_le_of_norm_le_const' {C : ℝ} (hs : μ s < ⊤) (hsm : is_measurable s)
(hC : ∀ x ∈ s, ∥f x∥ ≤ C) :
∥∫ x in s, f x ∂μ∥ ≤ C * (μ s).to_real :=
norm_set_integral_le_of_norm_le_const_ae'' hs hsm $ eventually_of_forall hC
lemma set_integral_eq_zero_iff_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f)
(hfi : integrable_on f s μ) :
∫ x in s, f x ∂μ = 0 ↔ f =ᵐ[μ.restrict s] 0 :=
integral_eq_zero_iff_of_nonneg_ae hf hfi
lemma set_integral_pos_iff_support_of_nonneg_ae {f : α → ℝ} (hf : 0 ≤ᵐ[μ.restrict s] f)
(hfi : integrable_on f s μ) :
0 < ∫ x in s, f x ∂μ ↔ 0 < μ (support f ∩ s) :=
begin
rw [integral_pos_iff_support_of_nonneg_ae hf hfi, restrict_apply_of_is_null_measurable],
exact hfi.ae_measurable.is_null_measurable (is_measurable_singleton 0).compl
end
end normed_group
end measure_theory
open measure_theory asymptotics metric
variables [measurable_space E] [normed_group E]
/-- Fundamental theorem of calculus for set integrals: if `μ` is a measure that is finite
at a filter `l` and `f` is a measurable function that has a finite limit `b` at `l ⊓ μ.ae`,
then `∫ x in s, f x ∂μ = μ s • b + o(μ s)` as `s` tends to `l.lift' powerset`. Since `μ s` is
an `ennreal` number, we use `(μ s).to_real` in the actual statement. -/
lemma filter.tendsto.integral_sub_linear_is_o_ae
[normed_space ℝ E] [second_countable_topology E] [complete_space E] [borel_space E]
{μ : measure α} {l : filter α} [l.is_measurably_generated]
{f : α → E} {b : E} (h : tendsto f (l ⊓ μ.ae) (𝓝 b)) (hfm : ae_measurable f μ)
(hμ : μ.finite_at_filter l) :
is_o (λ s : set α, ∫ x in s, f x ∂μ - (μ s).to_real • b) (λ s, (μ s).to_real)
(l.lift' powerset) :=
begin
simp only [is_o_iff],
intros ε ε₀,
have : ∀ᶠ s in l.lift' powerset, ∀ᶠ x in μ.ae, x ∈ s → f x ∈ closed_ball b ε :=
eventually_lift'_powerset_eventually.2 (h.eventually $ closed_ball_mem_nhds _ ε₀),
refine hμ.eventually.mp ((h.integrable_at_filter_ae hfm hμ).eventually.mp (this.mono _)),
simp only [mem_closed_ball, dist_eq_norm],
intros s h_norm h_integrable hμs,
rw [← set_integral_const, ← integral_sub h_integrable (integrable_on_const.2 $ or.inr hμs),
real.norm_eq_abs, abs_of_nonneg ennreal.to_real_nonneg],
exact norm_set_integral_le_of_norm_le_const_ae' hμs h_norm (hfm.sub ae_measurable_const)
end
/-- If a function is integrable at `𝓝[s] x` for each point `x` of a compact set `s`, then it is
integrable on `s`. -/
lemma is_compact.integrable_on_of_nhds_within [topological_space α] {μ : measure α} {s : set α}
(hs : is_compact s) {f : α → E} (hf : ∀ x ∈ s, integrable_at_filter f (𝓝[s] x) μ) :
integrable_on f s μ :=
is_compact.induction_on hs integrable_on_empty (λ s t hst ht, ht.mono_set hst)
(λ s t hs ht, hs.union ht) hf
/-- A function which is continuous on a set `s` is almost everywhere measurable with respect to
`μ.restrict s`. -/
lemma continuous_on.ae_measurable [topological_space α] [opens_measurable_space α] [borel_space E]
{f : α → E} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : is_measurable s) :
ae_measurable f (μ.restrict s) :=
begin
refine ⟨indicator s f, _, (indicator_ae_eq_restrict hs).symm⟩,
apply measurable_of_is_open,
assume t ht,
obtain ⟨u, u_open, hu⟩ : ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s :=
_root_.continuous_on_iff'.1 hf t ht,
rw [indicator_preimage, inter_comm, hu],
exact (u_open.is_measurable.inter hs).union (hs.compl.inter (measurable_const ht.is_measurable))
end
/-- A function `f` continuous on a compact set `s` is integrable on this set with respect to any
locally finite measure. -/
lemma continuous_on.integrable_on_compact
[topological_space α] [opens_measurable_space α] [borel_space E]
[t2_space α] {μ : measure α} [locally_finite_measure μ]
{s : set α} (hs : is_compact s) {f : α → E} (hf : continuous_on f s) :
integrable_on f s μ :=
begin
have : (μ.restrict s).restrict s = μ.restrict s, by simp [hs.is_measurable],
rw [integrable_on, ← this, ← integrable_on],
refine hs.integrable_on_of_nhds_within (λ x hx, _),
haveI := hs.is_measurable.nhds_within_is_measurably_generated,
refine (hf x hx).integrable_at_filter (hf.ae_measurable hs.is_measurable) _,
exact (μ.finite_at_nhds_within x s).measure_mono measure.restrict_le_self
end
/-- A continuous function `f` is integrable on any compact set with respect to any locally finite
measure. -/
lemma continuous.integrable_on_compact
[topological_space α] [opens_measurable_space α] [t2_space α]
[borel_space E] {μ : measure α} [locally_finite_measure μ] {s : set α}
(hs : is_compact s) {f : α → E} (hf : continuous f) :
integrable_on f s μ :=
hf.continuous_on.integrable_on_compact hs
/-- A continuous function with compact closure of the support is integrable on the whole space. -/
lemma continuous.integrable_of_compact_closure_support
[topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E]
{μ : measure α} [locally_finite_measure μ] {f : α → E} (hf : continuous f)
(hfc : is_compact (closure $ support f)) :
integrable f μ :=
begin
rw [← indicator_eq_self.2 (@subset_closure _ _ (support f)),
integrable_indicator_iff is_closed_closure.is_measurable],
{ exact hf.integrable_on_compact hfc },
{ apply_instance }
end
/-- Fundamental theorem of calculus for set integrals, `nhds` version: if `μ` is a locally finite
measure that and `f` is an almost everywhere measurable function that is continuous at a point `a`,
then `∫ x in s, f x ∂μ = μ s • f a + o(μ s)` as `s` tends to `(𝓝 a).lift' powerset`.
Since `μ s` is an `ennreal` number, we use `(μ s).to_real` in the actual statement. -/
lemma continuous_at.integral_sub_linear_is_o_ae
[topological_space α] [opens_measurable_space α]
[normed_space ℝ E] [second_countable_topology E] [complete_space E]
[borel_space E]
{μ : measure α} [locally_finite_measure μ] {a : α}
{f : α → E} (ha : continuous_at f a) (hfm : ae_measurable f μ) :
is_o (λ s, ∫ x in s, f x ∂μ - (μ s).to_real • f a) (λ s, (μ s).to_real) ((𝓝 a).lift' powerset) :=
(ha.mono_left inf_le_left).integral_sub_linear_is_o_ae hfm (μ.finite_at_nhds a)
section
/-! ### Continuous linear maps composed with integration
The goal of this section is to prove that integration commutes with continuous linear maps.
The first step is to prove that, given a function `φ : α → E` which is measurable and integrable,
and a continuous linear map `L : E →L[ℝ] F`, the function `λ a, L(φ a)` is also measurable
and integrable. Note we cannot write this as `L ∘ φ` since the type of `L` is not an actual
function type.
The next step is translate this to `l1`, replacing the function `φ` by a term with type
`α →₁[μ] E` (an equivalence class of integrable functions).
The corresponding "composition" is `L.comp_l1 φ : α →₁[μ] F`. This is then upgraded to
a linear map `L.comp_l1ₗ : (α →₁[μ] E) →ₗ[ℝ] (α →₁[μ] F)` and a continuous linear map
`L.comp_l1L : (α →₁[μ] E) →L[ℝ] (α →₁[μ] F)`.
Then we can prove the commutation result using continuity of all relevant operations
and the result on simple functions.
-/
variables {μ : measure α} [normed_space ℝ E]
variables [normed_group F] [normed_space ℝ F]
namespace continuous_linear_map
lemma norm_comp_l1_apply_le [opens_measurable_space E] [second_countable_topology E] (φ : α →₁[μ] E)
(L : E →L[ℝ] F) : ∀ᵐ a ∂μ, ∥L (φ a)∥ ≤ ∥L∥ * ∥φ a∥ :=
eventually_of_forall (λ a, L.le_op_norm (φ a))
variables [measurable_space F] [borel_space F]
lemma integrable_comp [opens_measurable_space E] {φ : α → E} (L : E →L[ℝ] F)
(φ_int : integrable φ μ) : integrable (λ (a : α), L (φ a)) μ :=
((integrable.norm φ_int).const_mul ∥L∥).mono' (L.measurable.comp_ae_measurable φ_int.ae_measurable)
(eventually_of_forall $ λ a, L.le_op_norm (φ a))
variables [borel_space E] [second_countable_topology E]
/-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`. -/
def comp_l1 [second_countable_topology F] (L : E →L[ℝ] F) (φ : α →₁[μ] E) : α →₁[μ] F :=
l1.of_fun (λ a, L (φ a)) (L.integrable_comp φ.integrable)
lemma comp_l1_apply [second_countable_topology F] (L : E →L[ℝ] F) (φ : α →₁[μ] E) :
∀ᵐ a ∂μ, (L.comp_l1 φ) a = L (φ a) :=
l1.to_fun_of_fun _ _
lemma integrable_comp_l1 (L : E →L[ℝ] F) (φ : α →₁[μ] E) : integrable (λ a, L (φ a)) μ :=
L.integrable_comp φ.integrable
lemma measurable_comp_l1 (L : E →L[ℝ] F) (φ : α →₁[μ] E) :
measurable (λ a, L (φ a)) := L.measurable.comp φ.measurable
variables [second_countable_topology F]
lemma integral_comp_l1 [complete_space F] (L : E →L[ℝ] F) (φ : α →₁[μ] E) :
∫ a, (L.comp_l1 φ) a ∂μ = ∫ a, L (φ a) ∂μ :=
by simp [comp_l1]
/-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`, seen as a `ℝ`-linear map on `α →₁[μ] E`. -/
def comp_l1ₗ (L : E →L[ℝ] F) : (α →₁[μ] E) →ₗ[ℝ] (α →₁[μ] F) :=
{ to_fun := λ φ, L.comp_l1 φ,
map_add' := begin
intros f g,
dsimp [comp_l1],
rw [← l1.of_fun_add, l1.of_fun_eq_of_fun],
apply (l1.add_to_fun f g).mono,
intros a ha,
simp only [ha, pi.add_apply, L.map_add]
end,
map_smul' := begin
intros c f,
dsimp [comp_l1],
rw [← l1.of_fun_smul, l1.of_fun_eq_of_fun],
apply (l1.smul_to_fun c f).mono,
intros a ha,
simp only [ha, pi.smul_apply, continuous_linear_map.map_smul]
end }
lemma norm_comp_l1_le (φ : α →₁[μ] E) (L : E →L[ℝ] F) : ∥L.comp_l1 φ∥ ≤ ∥L∥*∥φ∥ :=
begin
erw l1.norm_of_fun_eq_integral_norm,
calc
∫ a, ∥L (φ a)∥ ∂μ ≤ ∫ a, ∥L∥ *∥φ a∥ ∂μ : integral_mono_ae (L.integrable_comp_l1 φ).norm
(φ.integrable_norm.const_mul $ ∥L∥) (L.norm_comp_l1_apply_le φ)
... = ∥L∥ * ∥φ∥ : by rw [integral_mul_left, φ.norm_eq_integral_norm]
end
/-- Composing `φ : α →₁[μ] E` with `L : E →L[ℝ] F`, seen as a continuous `ℝ`-linear map on
`α →₁[μ] E`. -/
def comp_l1L (L : E →L[ℝ] F) : (α →₁[μ] E) →L[ℝ] (α →₁[μ] F) :=
linear_map.mk_continuous L.comp_l1ₗ (∥L∥) (λ φ, L.norm_comp_l1_le φ)
lemma norm_compl1L_le (L : E →L[ℝ] F) : ∥(L.comp_l1L : (α →₁[μ] E) →L[ℝ] (α →₁[μ] F))∥ ≤ ∥L∥ :=
op_norm_le_bound _ (norm_nonneg _) (λ φ, L.norm_comp_l1_le φ)
variables [complete_space F]
lemma continuous_integral_comp_l1 (L : E →L[ℝ] F) :
continuous (λ (φ : α →₁[μ] E), ∫ (a : α), L (φ a) ∂μ) :=
begin
rw ← funext L.integral_comp_l1,
exact continuous_integral.comp L.comp_l1L.continuous
end
variables [complete_space E]
lemma integral_comp_comm (L : E →L[ℝ] F) {φ : α → E} (φ_int : integrable φ μ) :
∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) :=
begin
apply integrable.induction (λ φ, ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ)),
{ intros e s s_meas s_finite,
rw [integral_indicator_const e s_meas, continuous_linear_map.map_smul,
← integral_indicator_const (L e) s_meas],
congr' 1 with a,
rw set.indicator_comp_of_zero L.map_zero },
{ intros f g H f_int g_int hf hg,
simp [L.map_add, integral_add f_int g_int,
integral_add (L.integrable_comp f_int) (L.integrable_comp g_int), hf, hg] },
{ exact is_closed_eq L.continuous_integral_comp_l1 (L.continuous.comp continuous_integral) },
{ intros f g hfg f_int hf,
convert hf using 1 ; clear hf,
{ exact integral_congr_ae (hfg.fun_comp L).symm },
{ rw integral_congr_ae hfg.symm } },
all_goals { assumption }
end
lemma integral_comp_l1_comm (L : E →L[ℝ] F) (φ : α →₁[μ] E) : ∫ a, L (φ a) ∂μ = L (∫ a, φ a ∂μ) :=
L.integral_comp_comm φ.integrable
end continuous_linear_map
variables [borel_space E] [second_countable_topology E] [complete_space E]
[measurable_space F] [borel_space F] [second_countable_topology F] [complete_space F]
lemma fst_integral {f : α → E × F} (hf : integrable f μ) :
(∫ x, f x ∂μ).1 = ∫ x, (f x).1 ∂μ :=
((continuous_linear_map.fst ℝ E F).integral_comp_comm hf).symm
lemma snd_integral {f : α → E × F} (hf : integrable f μ) :
(∫ x, f x ∂μ).2 = ∫ x, (f x).2 ∂μ :=
((continuous_linear_map.snd ℝ E F).integral_comp_comm hf).symm
lemma integral_pair {f : α → E} {g : α → F} (hf : integrable f μ) (hg : integrable g μ) :
∫ x, (f x, g x) ∂μ = (∫ x, f x ∂μ, ∫ x, g x ∂μ) :=
have _ := hf.prod_mk hg, prod.ext (fst_integral this) (snd_integral this)
lemma integral_smul_const (f : α → ℝ) (c : E) :
∫ x, f x • c ∂μ = (∫ x, f x ∂μ) • c :=
begin
by_cases hf : integrable f μ,
{ exact ((continuous_linear_map.id ℝ ℝ).smul_right c).integral_comp_comm hf },
{ by_cases hc : c = 0,
{ simp only [hc, integral_zero, smul_zero] },
rw [integral_undef hf, integral_undef, zero_smul],
simp_rw [integrable_smul_const hc, hf, not_false_iff] }
end
end
/-
namespace integrable
variables [measurable_space α] [measurable_space β] [normed_group E]
protected lemma measure_mono
end integrable
end measure_theory
section integral_on
variables [measurable_space α]
[normed_group β] [second_countable_topology β] [normed_space ℝ β] [complete_space β]
[measurable_space β] [borel_space β]
{s t : set α} {f g : α → β} {μ : measure α}
open set
lemma integral_on_congr (hf : measurable f) (hg : measurable g) (hs : is_measurable s)
(h : ∀ᵐ a ∂μ, a ∈ s → f a = g a) : ∫ a in s, f a ∂μ = ∫ a in s, g a ∂μ :=
integral_congr_ae hf hg $ _
lemma integral_on_congr_of_set (hsm : measurable_on s f) (htm : measurable_on t f)
(h : ∀ᵐ a, a ∈ s ↔ a ∈ t) : (∫ a in s, f a) = (∫ a in t, f a) :=
integral_congr_ae hsm htm $ indicator_congr_of_set h
lemma integral_on_add {s : set α} (hfm : measurable_on s f) (hfi : integrable_on s f)
(hgm : measurable_on s g) (hgi : integrable_on s g) :
(∫ a in s, f a + g a) = (∫ a in s, f a) + (∫ a in s, g a) :=
by { simp only [indicator_add], exact integral_add hfm hfi hgm hgi }
lemma integral_on_sub (hfm : measurable_on s f) (hfi : integrable_on s f) (hgm : measurable_on s g)
(hgi : integrable_on s g) : (∫ a in s, f a - g a) = (∫ a in s, f a) - (∫ a in s, g a) :=
by { simp only [indicator_sub], exact integral_sub hfm hfi hgm hgi }
lemma integral_on_le_integral_on_ae {f g : α → ℝ} (hfm : measurable_on s f)
(hfi : integrable_on s f) (hgm : measurable_on s g) (hgi : integrable_on s g)
(h : ∀ᵐ a, a ∈ s → f a ≤ g a) :
(∫ a in s, f a) ≤ (∫ a in s, g a) :=
begin
apply integral_le_integral_ae hfm hfi hgm hgi,
apply indicator_le_indicator_ae,
exact h
end
lemma integral_on_le_integral_on {f g : α → ℝ} (hfm : measurable_on s f) (hfi : integrable_on s f)
(hgm : measurable_on s g) (hgi : integrable_on s g) (h : ∀ a, a ∈ s → f a ≤ g a) :
(∫ a in s, f a) ≤ (∫ a in s, g a) :=
integral_on_le_integral_on_ae hfm hfi hgm hgi $ by filter_upwards [] h
lemma integral_on_union (hsm : measurable_on s f) (hsi : integrable_on s f)
(htm : measurable_on t f) (hti : integrable_on t f) (h : disjoint s t) :
(∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) :=
by { rw [indicator_union_of_disjoint h, integral_add hsm hsi htm hti] }
lemma integral_on_union_ae (hs : is_measurable s) (ht : is_measurable t) (hsm : measurable_on s f)
(hsi : integrable_on s f) (htm : measurable_on t f) (hti : integrable_on t f)
(h : ∀ᵐ a, a ∉ s ∩ t) :
(∫ a in (s ∪ t), f a) = (∫ a in s, f a) + (∫ a in t, f a) :=
begin
have := integral_congr_ae _ _ (indicator_union_ae h f),
rw [this, integral_add hsm hsi htm hti],
{ exact hsm.union hs ht htm },
{ exact measurable.add hsm htm }
end
lemma integral_on_nonneg_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) :=
integral_nonneg_of_ae $ by { filter_upwards [hf] λ a h, indicator_nonneg' h }
lemma integral_on_nonneg {f : α → ℝ} (hf : ∀ a, a ∈ s → 0 ≤ f a) : (0:ℝ) ≤ (∫ a in s, f a) :=
integral_on_nonneg_of_ae $ univ_mem_sets' hf
lemma integral_on_nonpos_of_ae {f : α → ℝ} (hf : ∀ᵐ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 :=
integral_nonpos_of_nonpos_ae $ by { filter_upwards [hf] λ a h, indicator_nonpos' h }
lemma integral_on_nonpos {f : α → ℝ} (hf : ∀ a, a ∈ s → f a ≤ 0) : (∫ a in s, f a) ≤ 0 :=
integral_on_nonpos_of_ae $ univ_mem_sets' hf
lemma tendsto_integral_on_of_monotone {s : ℕ → set α} {f : α → β} (hsm : ∀i, is_measurable (s i))
(h_mono : monotone s) (hfm : measurable_on (Union s) f) (hfi : integrable_on (Union s) f) :
tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Union s), f a)) :=
let bound : α → ℝ := indicator (Union s) (λa, ∥f a∥) in
begin
apply tendsto_integral_of_dominated_convergence,
{ assume i, exact hfm.subset (hsm i) (subset_Union _ _) },
{ assumption },
{ show integrable_on (Union s) (λa, ∥f a∥), rwa integrable_on_norm_iff },
{ assume i, apply ae_of_all,
assume a,
rw [norm_indicator_eq_indicator_norm],
exact indicator_le_indicator_of_subset (subset_Union _ _) (λa, norm_nonneg _) _ },
{ filter_upwards [] λa, le_trans (tendsto_indicator_of_monotone _ h_mono _ _) (pure_le_nhds _) }
end
lemma tendsto_integral_on_of_antimono (s : ℕ → set α) (f : α → β) (hsm : ∀i, is_measurable (s i))
(h_mono : ∀i j, i ≤ j → s j ⊆ s i) (hfm : measurable_on (s 0) f) (hfi : integrable_on (s 0) f) :
tendsto (λi, ∫ a in (s i), f a) at_top (nhds (∫ a in (Inter s), f a)) :=
let bound : α → ℝ := indicator (s 0) (λa, ∥f a∥) in
begin
apply tendsto_integral_of_dominated_convergence,
{ assume i, refine hfm.subset (hsm i) (h_mono _ _ (zero_le _)) },
{ exact hfm.subset (is_measurable.Inter hsm) (Inter_subset _ _) },
{ show integrable_on (s 0) (λa, ∥f a∥), rwa integrable_on_norm_iff },
{ assume i, apply ae_of_all,
assume a,
rw [norm_indicator_eq_indicator_norm],
refine indicator_le_indicator_of_subset (h_mono _ _ (zero_le _)) (λa, norm_nonneg _) _ },
{ filter_upwards [] λa, le_trans (tendsto_indicator_of_antimono _ h_mono _ _) (pure_le_nhds _) }
end
-- TODO : prove this for an encodable type
-- by proving an encodable version of `filter.is_countably_generated_at_top_finset_nat `
lemma integral_on_Union (s : ℕ → set α) (f : α → β) (hm : ∀i, is_measurable (s i))
(hd : ∀ i j, i ≠ j → s i ∩ s j = ∅) (hfm : measurable_on (Union s) f)
(hfi : integrable_on (Union s) f) :
(∫ a in (Union s), f a) = ∑'i, ∫ a in s i, f a :=
suffices h : tendsto (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) at_top (𝓝 $ (∫ a in (Union s), f a)),
by { rwa has_sum.tsum_eq },
begin
have : (λn:finset ℕ, ∑ i in n, ∫ a in s i, f a) = λn:finset ℕ, ∫ a in (⋃i∈n, s i), f a,
{ funext,
rw [← integral_finset_sum, indicator_finset_bUnion],
{ assume i hi j hj hij, exact hd i j hij },
{ assume i, refine hfm.subset (hm _) (subset_Union _ _) },
{ assume i, refine hfi.subset (subset_Union _ _) } },
rw this,
refine tendsto_integral_filter_of_dominated_convergence _ _ _ _ _ _ _,
{ exact indicator (Union s) (λ a, ∥f a∥) },
{ exact is_countably_generated_at_top_finset_nat },
{ refine univ_mem_sets' (λ n, _),
simp only [mem_set_of_eq],
refine hfm.subset (is_measurable.Union (λ i, is_measurable.Union_Prop (λh, hm _)))
(bUnion_subset_Union _ _), },
{ assumption },
{ refine univ_mem_sets' (λ n, univ_mem_sets' $ _),
simp only [mem_set_of_eq],
assume a,
rw ← norm_indicator_eq_indicator_norm,
refine norm_indicator_le_of_subset (bUnion_subset_Union _ _) _ _ },
{ rw [← integrable_on, integrable_on_norm_iff], assumption },
{ filter_upwards [] λa, le_trans (tendsto_indicator_bUnion_finset _ _ _) (pure_le_nhds _) }
end
end integral_on
-/
|
b9e2a2e81dec448985f552ce5b86f81e214da1f2 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/algebra/ring/order_synonym.lean | c046cb781ac5ed6b59788c351f93c50aa65a6548 | [
"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,043 | lean | /-
Copyright (c) 2021 Yury Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury Kudryashov, Yaël Dillies
-/
import algebra.ring.defs
import algebra.group.order_synonym
/-!
# Ring structure on the order type synonyms
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> https://github.com/leanprover-community/mathlib4/pull/671
> Any changes to this file require a corresponding PR to mathlib4.
Transfer algebraic instances from `α` to `αᵒᵈ` and `lex α`.
-/
variables {α : Type*}
/-! ### Order dual -/
instance [h : distrib α] : distrib αᵒᵈ := h
instance [has_mul α] [has_add α] [h : left_distrib_class α] : left_distrib_class αᵒᵈ := h
instance [has_mul α] [has_add α] [h : right_distrib_class α] : right_distrib_class αᵒᵈ := h
instance [h : non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring αᵒᵈ := h
instance [h : non_unital_semiring α] : non_unital_semiring αᵒᵈ := h
instance [h : non_assoc_semiring α] : non_assoc_semiring αᵒᵈ := h
instance [h : semiring α] : semiring αᵒᵈ := h
instance [h : non_unital_comm_semiring α] : non_unital_comm_semiring αᵒᵈ := h
instance [h : comm_semiring α] : comm_semiring αᵒᵈ := h
instance [has_mul α] [h : has_distrib_neg α] : has_distrib_neg αᵒᵈ := h
instance [h : non_unital_non_assoc_ring α] : non_unital_non_assoc_ring αᵒᵈ := h
instance [h : non_unital_ring α] : non_unital_ring αᵒᵈ := h
instance [h : non_assoc_ring α] : non_assoc_ring αᵒᵈ := h
instance [h : ring α] : ring αᵒᵈ := h
instance [h : non_unital_comm_ring α] : non_unital_comm_ring αᵒᵈ := h
instance [h : comm_ring α] : comm_ring αᵒᵈ := h
instance [ring α] [h : is_domain α] : is_domain αᵒᵈ := h
/-! ### Lexicographical order -/
instance [h : distrib α] : distrib (lex α) := h
instance [has_mul α] [has_add α] [h : left_distrib_class α] : left_distrib_class (lex α) := h
instance [has_mul α] [has_add α] [h : right_distrib_class α] : right_distrib_class (lex α) := h
instance [h : non_unital_non_assoc_semiring α] : non_unital_non_assoc_semiring (lex α) := h
instance [h : non_unital_semiring α] : non_unital_semiring (lex α) := h
instance [h : non_assoc_semiring α] : non_assoc_semiring (lex α) := h
instance [h : semiring α] : semiring (lex α) := h
instance [h : non_unital_comm_semiring α] : non_unital_comm_semiring (lex α) := h
instance [h : comm_semiring α] : comm_semiring (lex α) := h
instance [has_mul α] [h : has_distrib_neg α] : has_distrib_neg (lex α) := h
instance [h : non_unital_non_assoc_ring α] : non_unital_non_assoc_ring (lex α) := h
instance [h : non_unital_ring α] : non_unital_ring (lex α) := h
instance [h : non_assoc_ring α] : non_assoc_ring (lex α) := h
instance [h : ring α] : ring (lex α) := h
instance [h : non_unital_comm_ring α] : non_unital_comm_ring (lex α) := h
instance [h : comm_ring α] : comm_ring (lex α) := h
instance [ring α] [h : is_domain α] : is_domain (lex α) := h
|
5a863d6f1316c8d0fbfce310e71367111e32d89c | 3dd1b66af77106badae6edb1c4dea91a146ead30 | /tests/lean/run/class1.lean | aa25e295b4ecbfa1f784ad156bf0afb1c1d6aafb | [
"Apache-2.0"
] | permissive | silky/lean | 79c20c15c93feef47bb659a2cc139b26f3614642 | df8b88dca2f8da1a422cb618cd476ef5be730546 | refs/heads/master | 1,610,737,587,697 | 1,406,574,534,000 | 1,406,574,534,000 | 22,362,176 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 134 | lean | import standard
using num pair
definition H : inhabited (Prop × num × (num → num)) := _
(*
print(get_env():find("H"):value())
*) |
828e90f6dc5fc942ad5fa8e2dd08fbf915380238 | f3849be5d845a1cb97680f0bbbe03b85518312f0 | /library/init/classical.lean | f2e6688545c39090babaa504a7dc950a63267555 | [
"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 | 6,431 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
-/
prelude
import init.data.subtype.basic init.funext
namespace classical
universes u v
/- the axiom -/
axiom choice {α : Sort u} : nonempty α → α
noncomputable theorem indefinite_description {α : Sort u} (p : α → Prop) :
(∃ x, p x) → {x // p x} :=
λ h, choice (let ⟨x, px⟩ := h in ⟨⟨x, px⟩⟩)
noncomputable def some {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : α :=
(indefinite_description p h).val
theorem some_spec {α : Sort u} {p : α → Prop} (h : ∃ x, p x) : p (some h) :=
(indefinite_description p h).property
/- Diaconescu's theorem: using function extensionality and propositional extensionality,
we can get excluded middle from this. -/
section diaconescu
parameter p : Prop
private def U (x : Prop) : Prop := x = true ∨ p
private def V (x : Prop) : Prop := x = false ∨ p
private lemma exU : ∃ x, U x := ⟨true, or.inl rfl⟩
private lemma exV : ∃ x, V x := ⟨false, or.inl rfl⟩
private noncomputable def u := some exU
private noncomputable def v := some exV
private lemma u_def : U u := some_spec exU
private lemma v_def : V v := some_spec exV
private lemma not_uv_or_p : ¬(u = v) ∨ p :=
or.elim u_def
(assume hut : u = true,
or.elim v_def
(assume hvf : v = false,
have hne : ¬(u = v), from eq.symm hvf ▸ eq.symm hut ▸ true_ne_false,
or.inl hne)
(assume hp : p, or.inr hp))
(assume hp : p, or.inr hp)
private lemma p_implies_uv : p → u = v :=
assume hp : p,
have hpred : U = V, from
funext (take x : Prop,
have hl : (x = true ∨ p) → (x = false ∨ p), from
assume a, or.inr hp,
have hr : (x = false ∨ p) → (x = true ∨ p), from
assume a, or.inr hp,
show (x = true ∨ p) = (x = false ∨ p), from
propext (iff.intro hl hr)),
have h₀ : ∀ exU exV,
@some _ U exU = @some _ V exV,
from hpred ▸ λ exU exV, rfl,
show u = v, from h₀ _ _
theorem em : p ∨ ¬p :=
have h : ¬(u = v) → ¬p, from mt p_implies_uv,
or.elim not_uv_or_p
(assume hne : ¬(u = v), or.inr (h hne))
(assume hp : p, or.inl hp)
end diaconescu
theorem exists_true_of_nonempty {α : Sort u} (h : nonempty α) : ∃ x : α, true :=
nonempty.elim h (take x, ⟨x, trivial⟩)
noncomputable def inhabited_of_nonempty {α : Sort u} (h : nonempty α) : inhabited α :=
⟨(indefinite_description _ (exists_true_of_nonempty h)).val⟩
noncomputable def inhabited_of_exists {α : Sort u} {p : α → Prop} (h : ∃ x, p x) :
inhabited α :=
inhabited_of_nonempty (exists.elim h (λ w hw, ⟨w⟩))
/- all propositions are decidable -/
noncomputable def decidable_inhabited (a : Prop) : inhabited (decidable a) :=
inhabited_of_nonempty
(or.elim (em a)
(assume ha, ⟨is_true ha⟩)
(assume hna, ⟨is_false hna⟩))
local attribute [instance] decidable_inhabited
noncomputable def prop_decidable (a : Prop) : decidable a :=
arbitrary (decidable a)
local attribute [instance] prop_decidable
noncomputable def type_decidable_eq (α : Sort u) : decidable_eq α :=
λ x y, prop_decidable (x = y)
noncomputable def type_decidable (α : Sort u) : psum α (α → false) :=
match (prop_decidable (nonempty α)) with
| (is_true hp) := psum.inl (@inhabited.default _ (inhabited_of_nonempty hp))
| (is_false hn) := psum.inr (λ a, absurd (nonempty.intro a) hn)
end
noncomputable theorem strong_indefinite_description {α : Sort u} (p : α → Prop)
(h : nonempty α) : { x : α // (∃ y : α, p y) → p x} :=
match (prop_decidable (∃ x : α, p x)) with
| (is_true hp) := let xp := indefinite_description _ hp in
⟨xp.val, λ h', xp.property⟩
| (is_false hn) := ⟨@inhabited.default _ (inhabited_of_nonempty h), λ h, absurd h hn⟩
end
/- the Hilbert epsilon function -/
noncomputable def epsilon {α : Sort u} [h : nonempty α] (p : α → Prop) : α :=
(strong_indefinite_description p h).val
theorem epsilon_spec_aux {α : Sort u} (h : nonempty α) (p : α → Prop) (hex : ∃ y, p y) :
p (@epsilon α h p) :=
have aux : (∃ y, p y) → p ((strong_indefinite_description p h).val),
from (strong_indefinite_description p h).property,
aux hex
theorem epsilon_spec {α : Sort u} {p : α → Prop} (hex : ∃ y, p y) :
p (@epsilon α (nonempty_of_exists hex) p) :=
epsilon_spec_aux (nonempty_of_exists hex) p hex
theorem epsilon_singleton {α : Sort u} (x : α) : @epsilon α ⟨x⟩ (λ y, y = x) = x :=
@epsilon_spec α (λ y, y = x) ⟨x, rfl⟩
/- the axiom of choice -/
theorem axiom_of_choice {α : Sort u} {β : α → Sort v} {r : Π x, β x → Prop} (h : ∀ x, ∃ y, r x y) :
∃ (f : Π x, β x), ∀ x, r x (f x) :=
have h : ∀ x, r x (some (h x)), from take x, some_spec (h x),
⟨_, h⟩
theorem skolem {α : Sort u} {b : α → Sort v} {p : Π x, b x → Prop} :
(∀ x, ∃ y, p x y) ↔ ∃ (f : Π x, b x) , (∀ x, p x (f x)) :=
iff.intro
(assume h : (∀ x, ∃ y, p x y), axiom_of_choice h)
(assume h : (∃ (f : Π x, b x), (∀ x, p x (f x))),
take x, exists.elim h (λ (fw : ∀ x, b x) (hw : ∀ x, p x (fw x)),
⟨fw x, hw x⟩))
theorem prop_complete (a : Prop) : a = true ∨ a = false :=
or.elim (em a)
(λ t, or.inl (propext (iff.intro (λ h, trivial) (λ h, t))))
(λ f, or.inr (propext (iff.intro (λ h, absurd h f) (λ h, false.elim h))))
def eq_true_or_eq_false := prop_complete
section aux
attribute [elab_as_eliminator]
theorem cases_true_false (p : Prop → Prop) (h1 : p true) (h2 : p false) (a : Prop) : p a :=
or.elim (prop_complete a)
(assume ht : a = true, eq.symm ht ▸ h1)
(assume hf : a = false, eq.symm hf ▸ h2)
theorem cases_on (a : Prop) {p : Prop → Prop} (h1 : p true) (h2 : p false) : p a :=
cases_true_false p h1 h2 a
-- this supercedes by_cases in decidable
def by_cases {p q : Prop} (hpq : p → q) (hnpq : ¬p → q) : q :=
or.elim (em p) (assume hp, hpq hp) (assume hnp, hnpq hnp)
-- this supercedes by_contradiction in decidable
theorem by_contradiction {p : Prop} (h : ¬p → false) : p :=
by_cases
(assume h1 : p, h1)
(assume h1 : ¬p, false.rec _ (h h1))
theorem eq_false_or_eq_true (a : Prop) : a = false ∨ a = true :=
cases_true_false (λ x, x = false ∨ x = true)
(or.inr rfl)
(or.inl rfl)
a
end aux
end classical
|
25e917f39d31f57a859f589198613bd59bfc45ab | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/data/int/basic.lean | 875ee85a9249c6d95f6e61ece580905c47330417 | [
"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 | 64,817 | lean | /-
Copyright (c) 2016 Jeremy Avigad. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Jeremy Avigad
-/
import data.nat.pow
import order.min_max
import data.nat.cast
/-!
# Basic operations on the integers
This file contains:
* instances on `ℤ`. The stronger one is `int.linear_ordered_comm_ring`.
* some basic lemmas about integers
## Recursors
* `int.rec`: Sign disjunction. Something is true/defined on `ℤ` if it's true/defined for nonnegative
and for negative values.
* `int.bit_cases_on`: Parity disjunction. Something is true/defined on `ℤ` if it's true/defined for
even and for odd values.
* `int.induction_on`: Simple growing induction on positive numbers, plus simple decreasing induction
on negative numbers. Note that this recursor is currently only `Prop`-valued.
* `int.induction_on'`: Simple growing induction for numbers greater than `b`, plus simple decreasing
induction on numbers less than `b`.
-/
open nat
namespace int
instance : inhabited ℤ := ⟨int.zero⟩
instance : nontrivial ℤ :=
⟨⟨0, 1, int.zero_ne_one⟩⟩
instance : comm_ring int :=
{ add := int.add,
add_assoc := int.add_assoc,
zero := int.zero,
zero_add := int.zero_add,
add_zero := int.add_zero,
neg := int.neg,
add_left_neg := int.add_left_neg,
add_comm := int.add_comm,
mul := int.mul,
mul_assoc := int.mul_assoc,
one := int.one,
one_mul := int.one_mul,
mul_one := int.mul_one,
sub := int.sub,
left_distrib := int.distrib_left,
right_distrib := int.distrib_right,
mul_comm := int.mul_comm,
nat_cast := int.of_nat,
nat_cast_zero := rfl,
nat_cast_succ := λ n, rfl,
int_cast := λ n, n,
int_cast_of_nat := λ n, rfl,
int_cast_neg_succ_of_nat := λ n, rfl,
zsmul := (*),
zsmul_zero' := int.zero_mul,
zsmul_succ' := λ n x, by rw [succ_eq_one_add, of_nat_add, int.distrib_right, of_nat_one,
int.one_mul],
zsmul_neg' := λ n x, int.neg_mul_eq_neg_mul_symm (n.succ : ℤ) x }
/-! ### Extra instances to short-circuit type class resolution
These also prevent non-computable instances like `int.normed_comm_ring` being used to construct
these instances non-computably.
-/
-- instance : has_sub int := by apply_instance -- This is in core
instance : add_comm_monoid int := by apply_instance
instance : add_monoid int := by apply_instance
instance : monoid int := by apply_instance
instance : comm_monoid int := by apply_instance
instance : comm_semigroup int := by apply_instance
instance : semigroup int := by apply_instance
instance : add_comm_group int := by apply_instance
instance : add_group int := by apply_instance
instance : add_comm_semigroup int := by apply_instance
instance : add_semigroup int := by apply_instance
instance : comm_semiring int := by apply_instance
instance : semiring int := by apply_instance
instance : ring int := by apply_instance
instance : distrib int := by apply_instance
instance : linear_ordered_comm_ring int :=
{ add_le_add_left := @int.add_le_add_left,
mul_pos := @int.mul_pos,
zero_le_one := le_of_lt int.zero_lt_one,
.. int.comm_ring, .. int.linear_order, .. int.nontrivial }
instance : linear_ordered_add_comm_group int :=
by apply_instance
@[simp] lemma add_neg_one (i : ℤ) : i + -1 = i - 1 := rfl
theorem abs_eq_nat_abs : ∀ a : ℤ, |a| = nat_abs a
| (n : ℕ) := abs_of_nonneg $ coe_zero_le _
| -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _
theorem nat_abs_abs (a : ℤ) : nat_abs (|a|) = nat_abs a :=
by rw [abs_eq_nat_abs]; refl
theorem sign_mul_abs (a : ℤ) : sign a * |a| = a :=
by rw [abs_eq_nat_abs, sign_mul_nat_abs]
@[simp] lemma default_eq_zero : default = (0 : ℤ) := rfl
meta instance : has_to_format ℤ := ⟨λ z, to_string z⟩
section
-- Note that here we are disabling the "safety" of reflected, to allow us to reuse `int.mk_numeral`.
-- The usual way to provide the required `reflected` instance would be via rewriting to prove that
-- the expression we use here is equivalent.
local attribute [semireducible] reflected
meta instance reflect : has_reflect ℤ :=
int.mk_numeral `(ℤ) `(by apply_instance : has_zero ℤ) `(by apply_instance : has_one ℤ)
`(by apply_instance : has_add ℤ) `(by apply_instance : has_neg ℤ)
end
attribute [simp] int.bodd
@[simp] theorem add_def {a b : ℤ} : int.add a b = a + b := rfl
@[simp] theorem mul_def {a b : ℤ} : int.mul a b = a * b := rfl
@[simp] lemma neg_succ_not_nonneg (n : ℕ) : 0 ≤ -[1+ n] ↔ false :=
by { simp only [not_le, iff_false], exact int.neg_succ_lt_zero n, }
@[simp] lemma neg_succ_not_pos (n : ℕ) : 0 < -[1+ n] ↔ false :=
by simp only [not_lt, iff_false]
@[simp] lemma neg_succ_sub_one (n : ℕ) : -[1+ n] - 1 = -[1+ (n+1)] := rfl
@[simp] theorem coe_nat_mul_neg_succ (m n : ℕ) : (m : ℤ) * -[1+ n] = -(m * succ n) := rfl
@[simp] theorem neg_succ_mul_coe_nat (m n : ℕ) : -[1+ m] * n = -(succ m * n) := rfl
@[simp] theorem neg_succ_mul_neg_succ (m n : ℕ) : -[1+ m] * -[1+ n] = succ m * succ n := rfl
theorem coe_nat_le {m n : ℕ} : (↑m : ℤ) ≤ ↑n ↔ m ≤ n := coe_nat_le_coe_nat_iff m n
theorem coe_nat_lt {m n : ℕ} : (↑m : ℤ) < ↑n ↔ m < n := coe_nat_lt_coe_nat_iff m n
theorem coe_nat_inj' {m n : ℕ} : (↑m : ℤ) = ↑n ↔ m = n := int.coe_nat_eq_coe_nat_iff m n
lemma coe_nat_strict_mono : strict_mono (coe : ℕ → ℤ) := λ _ _, int.coe_nat_lt.2
@[simp] theorem coe_nat_pos {n : ℕ} : (0 : ℤ) < n ↔ 0 < n := nat.cast_pos
theorem coe_nat_eq_zero {n : ℕ} : (n : ℤ) = 0 ↔ n = 0 := nat.cast_eq_zero
theorem coe_nat_ne_zero {n : ℕ} : (n : ℤ) ≠ 0 ↔ n ≠ 0 := by simp
lemma coe_nat_nonneg (n : ℕ) : 0 ≤ (n : ℤ) := coe_nat_le.2 (nat.zero_le _)
lemma le_coe_nat_sub (m n : ℕ) :
(m - n : ℤ) ≤ ↑(m - n : ℕ) :=
begin
by_cases h: m ≥ n,
{ exact le_of_eq (int.coe_nat_sub h).symm },
{ simp [le_of_not_ge h, coe_nat_le] }
end
lemma coe_nat_ne_zero_iff_pos {n : ℕ} : (n : ℤ) ≠ 0 ↔ 0 < n :=
⟨λ h, nat.pos_of_ne_zero (coe_nat_ne_zero.1 h),
λ h, (ne_of_lt (coe_nat_lt.2 h)).symm⟩
lemma coe_nat_succ_pos (n : ℕ) : 0 < (n.succ : ℤ) := int.coe_nat_pos.2 (succ_pos n)
theorem coe_nat_abs (n : ℕ) : |(n : ℤ)| = n :=
abs_of_nonneg (coe_nat_nonneg n)
@[simp] lemma neg_of_nat_ne_zero (n : ℕ) : -[1+ n] ≠ 0 := λ h, int.no_confusion h
@[simp] lemma zero_ne_neg_of_nat (n : ℕ) : 0 ≠ -[1+ n] := λ h, int.no_confusion h
/-! ### succ and pred -/
/-- Immediate successor of an integer: `succ n = n + 1` -/
def succ (a : ℤ) := a + 1
/-- Immediate predecessor of an integer: `pred n = n - 1` -/
def pred (a : ℤ) := a - 1
theorem nat_succ_eq_int_succ (n : ℕ) : (nat.succ n : ℤ) = int.succ n := rfl
theorem pred_succ (a : ℤ) : pred (succ a) = a := add_sub_cancel _ _
theorem succ_pred (a : ℤ) : succ (pred a) = a := sub_add_cancel _ _
theorem neg_succ (a : ℤ) : -succ a = pred (-a) := neg_add _ _
theorem succ_neg_succ (a : ℤ) : succ (-succ a) = -a :=
by rw [neg_succ, succ_pred]
theorem neg_pred (a : ℤ) : -pred a = succ (-a) :=
by rw [eq_neg_of_eq_neg (neg_succ (-a)).symm, neg_neg]
theorem pred_neg_pred (a : ℤ) : pred (-pred a) = -a :=
by rw [neg_pred, pred_succ]
theorem pred_nat_succ (n : ℕ) : pred (nat.succ n) = n := pred_succ n
theorem neg_nat_succ (n : ℕ) : -(nat.succ n : ℤ) = pred (-n) := neg_succ n
theorem succ_neg_nat_succ (n : ℕ) : succ (-nat.succ n) = -n := succ_neg_succ n
theorem lt_succ_self (a : ℤ) : a < succ a :=
lt_add_of_pos_right _ zero_lt_one
theorem pred_self_lt (a : ℤ) : pred a < a :=
sub_lt_self _ zero_lt_one
theorem add_one_le_iff {a b : ℤ} : a + 1 ≤ b ↔ a < b := iff.rfl
theorem lt_add_one_iff {a b : ℤ} : a < b + 1 ↔ a ≤ b :=
add_le_add_iff_right _
@[simp] lemma succ_coe_nat_pos (n : ℕ) : 0 < (n : ℤ) + 1 :=
lt_add_one_iff.mpr (by simp)
@[norm_cast] lemma coe_pred_of_pos {n : ℕ} (h : 0 < n) : ((n - 1 : ℕ) : ℤ) = (n : ℤ) - 1 :=
by { cases n, cases h, simp, }
lemma le_add_one {a b : ℤ} (h : a ≤ b) : a ≤ b + 1 :=
le_of_lt (int.lt_add_one_iff.mpr h)
theorem sub_one_lt_iff {a b : ℤ} : a - 1 < b ↔ a ≤ b :=
sub_lt_iff_lt_add.trans lt_add_one_iff
theorem le_sub_one_iff {a b : ℤ} : a ≤ b - 1 ↔ a < b :=
le_sub_iff_add_le
@[simp] lemma abs_lt_one_iff {a : ℤ} : |a| < 1 ↔ a = 0 :=
⟨λ a0, let ⟨hn, hp⟩ := abs_lt.mp a0 in (le_of_lt_add_one (by exact hp)).antisymm hn,
λ a0, (abs_eq_zero.mpr a0).le.trans_lt zero_lt_one⟩
lemma abs_le_one_iff {a : ℤ} : |a| ≤ 1 ↔ a = 0 ∨ a = 1 ∨ a = -1 :=
by rw [le_iff_lt_or_eq, abs_lt_one_iff, abs_eq (zero_le_one' ℤ)]
lemma one_le_abs {z : ℤ} (h₀: z ≠ 0) : 1 ≤ |z| :=
add_one_le_iff.mpr (abs_pos.mpr h₀)
@[elab_as_eliminator] protected lemma induction_on {p : ℤ → Prop}
(i : ℤ) (hz : p 0) (hp : ∀ i : ℕ, p i → p (i + 1)) (hn : ∀ i : ℕ, p (-i) → p (-i - 1)) : p i :=
begin
induction i,
{ induction i,
{ exact hz },
{ exact hp _ i_ih } },
{ have : ∀ n:ℕ, p (- n),
{ intro n, induction n,
{ simp [hz] },
{ convert hn _ n_ih using 1, simp [sub_eq_neg_add] } },
exact this (i + 1) }
end
/-- Inductively define a function on `ℤ` by defining it at `b`, for the `succ` of a number greater
than `b`, and the `pred` of a number less than `b`. -/
@[elab_as_eliminator]
protected def induction_on' {C : ℤ → Sort*} (z : ℤ) (b : ℤ)
(H0 : C b) (Hs : ∀ k, b ≤ k → C k → C (k + 1)) (Hp : ∀ k ≤ b, C k → C (k - 1)) : C z :=
begin
-- Note that we use `convert` here where possible as we are constructing data, and this reduces
-- the number of times `eq.mpr` appears in the term.
rw ←sub_add_cancel z b,
induction (z - b) with n n,
{ induction n with n ih,
{ convert H0 using 1,
rw [of_nat_zero, zero_add] },
convert Hs _ (le_add_of_nonneg_left (of_nat_nonneg _)) ih using 1,
rw [of_nat_succ, add_assoc, add_comm 1 b, ←add_assoc] },
{ induction n with n ih,
{ convert Hp _ le_rfl H0 using 1,
rw [neg_succ_of_nat_eq, ←of_nat_eq_coe, of_nat_zero, zero_add, neg_add_eq_sub] },
{ convert Hp _ (le_of_lt (add_lt_of_neg_of_le (neg_succ_lt_zero _) le_rfl)) ih using 1,
rw [neg_succ_of_nat_coe', nat.succ_eq_add_one, ←neg_succ_of_nat_coe, sub_add_eq_add_sub] } }
end
/-- See `int.induction_on'` for an induction in both directions. -/
protected lemma le_induction {P : ℤ → Prop} {m : ℤ} (h0 : P m)
(h1 : ∀ (n : ℤ), m ≤ n → P n → P (n + 1)) (n : ℤ) :
m ≤ n → P n :=
begin
apply int.induction_on' n m,
{ intro _, exact h0, },
{ intros k hle hi _, exact h1 k hle (hi hle), },
{ intros _ hle _ hle',
exfalso,
exact lt_irrefl k (le_sub_one_iff.mp (hle.trans hle')), },
end
/-- See `int.induction_on'` for an induction in both directions. -/
protected lemma le_induction_down {P : ℤ → Prop} {m : ℤ} (h0 : P m)
(h1 : ∀ (n : ℤ), n ≤ m → P n → P (n - 1)) (n : ℤ) :
n ≤ m → P n :=
begin
apply int.induction_on' n m,
{ intro _, exact h0, },
{ intros _ hle _ hle',
exfalso,
exact lt_irrefl k (add_one_le_iff.mp (hle'.trans hle)), },
{ intros k hle hi _,
exact h1 k hle (hi hle), },
end
/-! ### nat abs -/
variables {a b : ℤ} {n : ℕ}
attribute [simp] nat_abs nat_abs_of_nat nat_abs_zero nat_abs_one
theorem nat_abs_add_le (a b : ℤ) : nat_abs (a + b) ≤ nat_abs a + nat_abs b :=
begin
have : ∀ (a b : ℕ), nat_abs (sub_nat_nat a (nat.succ b)) ≤ nat.succ (a + b),
{ refine (λ a b : ℕ, sub_nat_nat_elim a b.succ
(λ m n i, n = b.succ → nat_abs i ≤ (m + b).succ) _ (λ i n e, _) rfl),
{ rintro i n rfl,
rw [add_comm _ i, add_assoc],
exact nat.le_add_right i (b.succ + b).succ },
{ apply succ_le_succ,
rw [← succ.inj e, ← add_assoc, add_comm],
apply nat.le_add_right } },
cases a; cases b with b b; simp [nat_abs, nat.succ_add];
try {refl}; [skip, rw add_comm a b]; apply this
end
lemma nat_abs_sub_le (a b : ℤ) : nat_abs (a - b) ≤ nat_abs a + nat_abs b :=
by { rw [sub_eq_add_neg, ← int.nat_abs_neg b], apply nat_abs_add_le }
theorem nat_abs_neg_of_nat (n : ℕ) : nat_abs (neg_of_nat n) = n :=
by cases n; refl
theorem nat_abs_mul (a b : ℤ) : nat_abs (a * b) = (nat_abs a) * (nat_abs b) :=
by cases a; cases b;
simp only [← int.mul_def, int.mul, nat_abs_neg_of_nat, eq_self_iff_true, int.nat_abs]
lemma nat_abs_mul_nat_abs_eq {a b : ℤ} {c : ℕ} (h : a * b = (c : ℤ)) :
a.nat_abs * b.nat_abs = c :=
by rw [← nat_abs_mul, h, nat_abs_of_nat]
@[simp] lemma nat_abs_mul_self' (a : ℤ) : (nat_abs a * nat_abs a : ℤ) = a * a :=
by rw [← int.coe_nat_mul, nat_abs_mul_self]
theorem neg_succ_of_nat_eq' (m : ℕ) : -[1+ m] = -m - 1 :=
by simp [neg_succ_of_nat_eq, sub_eq_neg_add]
lemma nat_abs_ne_zero_of_ne_zero {z : ℤ} (hz : z ≠ 0) : z.nat_abs ≠ 0 :=
λ h, hz $ int.eq_zero_of_nat_abs_eq_zero h
@[simp] lemma nat_abs_eq_zero {a : ℤ} : a.nat_abs = 0 ↔ a = 0 :=
⟨int.eq_zero_of_nat_abs_eq_zero, λ h, h.symm ▸ rfl⟩
lemma nat_abs_ne_zero {a : ℤ} : a.nat_abs ≠ 0 ↔ a ≠ 0 := not_congr int.nat_abs_eq_zero
lemma nat_abs_lt_nat_abs_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) :
a.nat_abs < b.nat_abs :=
begin
lift b to ℕ using le_trans w₁ (le_of_lt w₂),
lift a to ℕ using w₁,
simpa [coe_nat_lt] using w₂,
end
lemma nat_abs_eq_nat_abs_iff {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a = b ∨ a = -b :=
begin
split; intro h,
{ cases int.nat_abs_eq a with h₁ h₁; cases int.nat_abs_eq b with h₂ h₂;
rw [h₁, h₂]; simp [h], },
{ cases h; rw h, rw int.nat_abs_neg, },
end
lemma nat_abs_eq_iff {a : ℤ} {n : ℕ} : a.nat_abs = n ↔ a = n ∨ a = -n :=
by rw [←int.nat_abs_eq_nat_abs_iff, int.nat_abs_of_nat]
lemma nat_abs_eq_iff_mul_self_eq {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a * a = b * b :=
begin
rw [← abs_eq_iff_mul_self_eq, abs_eq_nat_abs, abs_eq_nat_abs],
exact int.coe_nat_inj'.symm
end
lemma eq_nat_abs_iff_mul_eq_zero : a.nat_abs = n ↔ (a - n) * (a + n) = 0 :=
by rw [nat_abs_eq_iff, mul_eq_zero, sub_eq_zero, add_eq_zero_iff_eq_neg]
lemma nat_abs_lt_iff_mul_self_lt {a b : ℤ} : a.nat_abs < b.nat_abs ↔ a * a < b * b :=
begin
rw [← abs_lt_iff_mul_self_lt, abs_eq_nat_abs, abs_eq_nat_abs],
exact int.coe_nat_lt.symm
end
lemma nat_abs_le_iff_mul_self_le {a b : ℤ} : a.nat_abs ≤ b.nat_abs ↔ a * a ≤ b * b :=
begin
rw [← abs_le_iff_mul_self_le, abs_eq_nat_abs, abs_eq_nat_abs],
exact int.coe_nat_le.symm
end
lemma nat_abs_eq_iff_sq_eq {a b : ℤ} : a.nat_abs = b.nat_abs ↔ a ^ 2 = b ^ 2 :=
by { rw [sq, sq], exact nat_abs_eq_iff_mul_self_eq }
lemma nat_abs_lt_iff_sq_lt {a b : ℤ} : a.nat_abs < b.nat_abs ↔ a ^ 2 < b ^ 2 :=
by { rw [sq, sq], exact nat_abs_lt_iff_mul_self_lt }
lemma nat_abs_le_iff_sq_le {a b : ℤ} : a.nat_abs ≤ b.nat_abs ↔ a ^ 2 ≤ b ^ 2 :=
by { rw [sq, sq], exact nat_abs_le_iff_mul_self_le }
@[simp] lemma nat_abs_dvd_iff_dvd {a b : ℤ} : a.nat_abs ∣ b.nat_abs ↔ a ∣ b :=
begin
refine ⟨_, λ ⟨k, hk⟩, ⟨k.nat_abs, hk.symm ▸ nat_abs_mul a k⟩⟩,
rintro ⟨k, hk⟩,
rw [←nat_abs_of_nat k, ←nat_abs_mul, nat_abs_eq_nat_abs_iff, neg_mul_eq_mul_neg] at hk,
cases hk; exact ⟨_, hk⟩
end
lemma nat_abs_inj_of_nonneg_of_nonneg {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) :
nat_abs a = nat_abs b ↔ a = b :=
by rw [←sq_eq_sq ha hb, ←nat_abs_eq_iff_sq_eq]
lemma nat_abs_inj_of_nonpos_of_nonpos {a b : ℤ} (ha : a ≤ 0) (hb : b ≤ 0) :
nat_abs a = nat_abs b ↔ a = b :=
by simpa only [int.nat_abs_neg, neg_inj]
using nat_abs_inj_of_nonneg_of_nonneg
(neg_nonneg_of_nonpos ha) (neg_nonneg_of_nonpos hb)
lemma nat_abs_inj_of_nonneg_of_nonpos {a b : ℤ} (ha : 0 ≤ a) (hb : b ≤ 0) :
nat_abs a = nat_abs b ↔ a = -b :=
by simpa only [int.nat_abs_neg]
using nat_abs_inj_of_nonneg_of_nonneg ha (neg_nonneg_of_nonpos hb)
lemma nat_abs_inj_of_nonpos_of_nonneg {a b : ℤ} (ha : a ≤ 0) (hb : 0 ≤ b) :
nat_abs a = nat_abs b ↔ -a = b :=
by simpa only [int.nat_abs_neg]
using nat_abs_inj_of_nonneg_of_nonneg (neg_nonneg_of_nonpos ha) hb
section intervals
open set
lemma strict_mono_on_nat_abs : strict_mono_on nat_abs (Ici 0) :=
λ a ha b hb hab, nat_abs_lt_nat_abs_of_nonneg_of_lt ha hab
lemma strict_anti_on_nat_abs : strict_anti_on nat_abs (Iic 0) :=
λ a ha b hb hab, by simpa [int.nat_abs_neg]
using nat_abs_lt_nat_abs_of_nonneg_of_lt (right.nonneg_neg_iff.mpr hb) (neg_lt_neg_iff.mpr hab)
lemma inj_on_nat_abs_Ici : inj_on nat_abs (Ici 0) := strict_mono_on_nat_abs.inj_on
lemma inj_on_nat_abs_Iic : inj_on nat_abs (Iic 0) := strict_anti_on_nat_abs.inj_on
end intervals
/-! ### `/` -/
@[simp] theorem of_nat_div (m n : ℕ) : of_nat (m / n) = (of_nat m) / (of_nat n) := rfl
@[simp, norm_cast] theorem coe_nat_div (m n : ℕ) : ((m / n : ℕ) : ℤ) = m / n := rfl
theorem neg_succ_of_nat_div (m : ℕ) {b : ℤ} (H : 0 < b) :
-[1+m] / b = -(m / b + 1) :=
match b, eq_succ_of_zero_lt H with ._, ⟨n, rfl⟩ := rfl end
-- Will be generalized to Euclidean domains.
local attribute [simp]
protected theorem zero_div : ∀ (b : ℤ), 0 / b = 0
| (n:ℕ) := show of_nat _ = _, by simp
| -[1+ n] := show -of_nat _ = _, by simp
local attribute [simp] -- Will be generalized to Euclidean domains.
protected theorem div_zero : ∀ (a : ℤ), a / 0 = 0
| (n:ℕ) := show of_nat _ = _, by simp
| -[1+ n] := rfl
@[simp] protected theorem div_neg : ∀ (a b : ℤ), a / -b = -(a / b)
| (m : ℕ) 0 := show of_nat (m / 0) = -(m / 0 : ℕ), by rw nat.div_zero; refl
| (m : ℕ) (n+1:ℕ) := rfl
| (m : ℕ) -[1+ n] := (neg_neg _).symm
| -[1+ m] 0 := rfl
| -[1+ m] (n+1:ℕ) := rfl
| -[1+ m] -[1+ n] := rfl
theorem div_of_neg_of_pos {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b = -((-a - 1) / b + 1) :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ :=
by change (- -[1+ m] : ℤ) with (m+1 : ℤ); rw add_sub_cancel; refl
end
protected theorem div_nonneg {a b : ℤ} (Ha : 0 ≤ a) (Hb : 0 ≤ b) : 0 ≤ a / b :=
match a, b, eq_coe_of_zero_le Ha, eq_coe_of_zero_le Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := coe_zero_le _
end
protected theorem div_nonpos {a b : ℤ} (Ha : 0 ≤ a) (Hb : b ≤ 0) : a / b ≤ 0 :=
nonpos_of_neg_nonneg $ by rw [← int.div_neg]; exact int.div_nonneg Ha (neg_nonneg_of_nonpos Hb)
theorem div_neg' {a b : ℤ} (Ha : a < 0) (Hb : 0 < b) : a / b < 0 :=
match a, b, eq_neg_succ_of_lt_zero Ha, eq_succ_of_zero_lt Hb with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩ := neg_succ_lt_zero _
end
@[simp] protected theorem div_one : ∀ (a : ℤ), a / 1 = a
| (n:ℕ) := congr_arg of_nat (nat.div_one _)
| -[1+ n] := congr_arg neg_succ_of_nat (nat.div_one _)
theorem div_eq_zero_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a / b = 0 :=
match a, b, eq_coe_of_zero_le H1, eq_succ_of_zero_lt (lt_of_le_of_lt H1 H2), H2 with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 :=
congr_arg of_nat $ nat.div_eq_of_lt $ lt_of_coe_nat_lt_coe_nat H2
end
theorem div_eq_zero_of_lt_abs {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < |b|) : a / b = 0 :=
match b, |b|, abs_eq_nat_abs b, H2 with
| (n : ℕ), ._, rfl, H2 := div_eq_zero_of_lt H1 H2
| -[1+ n], ._, rfl, H2 := neg_injective $ by rw [← int.div_neg]; exact div_eq_zero_of_lt H1 H2
end
protected theorem add_mul_div_right (a b : ℤ) {c : ℤ} (H : c ≠ 0) :
(a + b * c) / c = a / c + b :=
have ∀ {k n : ℕ} {a : ℤ}, (a + n * k.succ) / k.succ = a / k.succ + n, from
λ k n a, match a with
| (m : ℕ) := congr_arg of_nat $ nat.add_mul_div_right _ _ k.succ_pos
| -[1+ m] := show ((n * k.succ:ℕ) - m.succ : ℤ) / k.succ =
n - (m / k.succ + 1 : ℕ), begin
cases lt_or_ge m (n*k.succ) with h h,
{ rw [← int.coe_nat_sub h,
← int.coe_nat_sub ((nat.div_lt_iff_lt_mul k.succ_pos).2 h)],
apply congr_arg of_nat,
rw [mul_comm, nat.mul_sub_div], rwa mul_comm },
{ change (↑(n * nat.succ k) - (m + 1) : ℤ) / ↑(nat.succ k) =
↑n - ((m / nat.succ k : ℕ) + 1),
rw [← sub_sub, ← sub_sub, ← neg_sub (m:ℤ), ← neg_sub _ (n:ℤ),
← int.coe_nat_sub h,
← int.coe_nat_sub ((nat.le_div_iff_mul_le k.succ_pos).2 h),
← neg_succ_of_nat_coe', ← neg_succ_of_nat_coe'],
{ apply congr_arg neg_succ_of_nat,
rw [mul_comm, nat.sub_mul_div], rwa mul_comm } }
end
end,
have ∀ {a b c : ℤ}, 0 < c → (a + b * c) / c = a / c + b, from
λ a b c H, match c, eq_succ_of_zero_lt H, b with
| ._, ⟨k, rfl⟩, (n : ℕ) := this
| ._, ⟨k, rfl⟩, -[1+ n] :=
show (a - n.succ * k.succ) / k.succ = (a / k.succ) - n.succ, from
eq_sub_of_add_eq $ by rw [← this, sub_add_cancel]
end,
match lt_trichotomy c 0 with
| or.inl hlt := neg_inj.1 $ by rw [← int.div_neg, neg_add, ← int.div_neg, ← neg_mul_neg];
apply this (neg_pos_of_neg hlt)
| or.inr (or.inl heq) := absurd heq H
| or.inr (or.inr hgt) := this hgt
end
protected theorem add_mul_div_left (a : ℤ) {b : ℤ} (c : ℤ) (H : b ≠ 0) :
(a + b * c) / b = a / b + c :=
by rw [mul_comm, int.add_mul_div_right _ _ H]
protected theorem add_div_of_dvd_right {a b c : ℤ} (H : c ∣ b) :
(a + b) / c = a / c + b / c :=
begin
by_cases h1 : c = 0,
{ simp [h1] },
cases H with k hk,
rw hk,
change c ≠ 0 at h1,
rw [mul_comm c k, int.add_mul_div_right _ _ h1, ←zero_add (k * c), int.add_mul_div_right _ _ h1,
int.zero_div, zero_add]
end
protected theorem add_div_of_dvd_left {a b c : ℤ} (H : c ∣ a) :
(a + b) / c = a / c + b / c :=
by rw [add_comm, int.add_div_of_dvd_right H, add_comm]
@[simp] protected theorem mul_div_cancel (a : ℤ) {b : ℤ} (H : b ≠ 0) : a * b / b = a :=
by have := int.add_mul_div_right 0 a H;
rwa [zero_add, int.zero_div, zero_add] at this
@[simp] protected theorem mul_div_cancel_left {a : ℤ} (b : ℤ) (H : a ≠ 0) : a * b / a = b :=
by rw [mul_comm, int.mul_div_cancel _ H]
@[simp] protected theorem div_self {a : ℤ} (H : a ≠ 0) : a / a = 1 :=
by have := int.mul_div_cancel 1 H; rwa one_mul at this
/-! ### mod -/
theorem of_nat_mod (m n : nat) : (m % n : ℤ) = of_nat (m % n) := rfl
@[simp, norm_cast] theorem coe_nat_mod (m n : ℕ) : (↑(m % n) : ℤ) = ↑m % ↑n := rfl
theorem neg_succ_of_nat_mod (m : ℕ) {b : ℤ} (bpos : 0 < b) :
-[1+m] % b = b - 1 - m % b :=
by rw [sub_sub, add_comm]; exact
match b, eq_succ_of_zero_lt bpos with ._, ⟨n, rfl⟩ := rfl end
@[simp] theorem mod_neg : ∀ (a b : ℤ), a % -b = a % b
| (m : ℕ) n := @congr_arg ℕ ℤ _ _ (λ i, ↑(m % i)) (nat_abs_neg _)
| -[1+ m] n := @congr_arg ℕ ℤ _ _ (λ i, sub_nat_nat i (nat.succ (m % i))) (nat_abs_neg _)
@[simp] theorem mod_abs (a b : ℤ) : a % (|b|) = a % b :=
abs_by_cases (λ i, a % i = a % b) rfl (mod_neg _ _)
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem zero_mod (b : ℤ) : 0 % b = 0 := rfl
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem mod_zero : ∀ (a : ℤ), a % 0 = a
| (m : ℕ) := congr_arg of_nat $ nat.mod_zero _
| -[1+ m] := congr_arg neg_succ_of_nat $ nat.mod_zero _
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem mod_one : ∀ (a : ℤ), a % 1 = 0
| (m : ℕ) := congr_arg of_nat $ nat.mod_one _
| -[1+ m] := show (1 - (m % 1).succ : ℤ) = 0, by rw nat.mod_one; refl
theorem mod_eq_of_lt {a b : ℤ} (H1 : 0 ≤ a) (H2 : a < b) : a % b = a :=
match a, b, eq_coe_of_zero_le H1, eq_coe_of_zero_le (le_trans H1 (le_of_lt H2)), H2 with
| ._, ._, ⟨m, rfl⟩, ⟨n, rfl⟩, H2 :=
congr_arg of_nat $ nat.mod_eq_of_lt (lt_of_coe_nat_lt_coe_nat H2)
end
theorem mod_nonneg : ∀ (a : ℤ) {b : ℤ}, b ≠ 0 → 0 ≤ a % b
| (m : ℕ) n H := coe_zero_le _
| -[1+ m] n H :=
sub_nonneg_of_le $ coe_nat_le_coe_nat_of_le $ nat.mod_lt _ (nat_abs_pos_of_ne_zero H)
theorem mod_lt_of_pos (a : ℤ) {b : ℤ} (H : 0 < b) : a % b < b :=
match a, b, eq_succ_of_zero_lt H with
| (m : ℕ), ._, ⟨n, rfl⟩ := coe_nat_lt_coe_nat_of_lt (nat.mod_lt _ (nat.succ_pos _))
| -[1+ m], ._, ⟨n, rfl⟩ := sub_lt_self _ (coe_nat_lt_coe_nat_of_lt $ nat.succ_pos _)
end
theorem mod_lt (a : ℤ) {b : ℤ} (H : b ≠ 0) : a % b < |b| :=
by rw [← mod_abs]; exact mod_lt_of_pos _ (abs_pos.2 H)
theorem mod_add_div_aux (m n : ℕ) : (n - (m % n + 1) - (n * (m / n) + n) : ℤ) = -[1+ m] :=
begin
rw [← sub_sub, neg_succ_of_nat_coe, sub_sub (n:ℤ)],
apply eq_neg_of_eq_neg,
rw [neg_sub, sub_sub_self, add_right_comm],
exact @congr_arg ℕ ℤ _ _ (λi, (i + 1 : ℤ)) (nat.mod_add_div _ _).symm
end
theorem mod_add_div : ∀ (a b : ℤ), a % b + b * (a / b) = a
| (m : ℕ) (n : ℕ) := congr_arg of_nat (nat.mod_add_div _ _)
| (m : ℕ) -[1+ n] := show (_ + -(n+1) * -((m) / (n + 1) : ℕ) : ℤ) = _,
by rw [neg_mul_neg]; exact congr_arg of_nat (nat.mod_add_div _ _)
| -[1+ m] 0 := by rw [mod_zero, int.div_zero]; refl
| -[1+ m] (n+1:ℕ) := mod_add_div_aux m n.succ
| -[1+ m] -[1+ n] := mod_add_div_aux m n.succ
theorem div_add_mod (a b : ℤ) : b * (a / b) + a % b = a :=
(add_comm _ _).trans (mod_add_div _ _)
lemma mod_add_div' (m k : ℤ) : m % k + (m / k) * k = m :=
by { rw mul_comm, exact mod_add_div _ _ }
lemma div_add_mod' (m k : ℤ) : (m / k) * k + m % k = m :=
by { rw mul_comm, exact div_add_mod _ _ }
theorem mod_def (a b : ℤ) : a % b = a - b * (a / b) :=
eq_sub_of_add_eq (mod_add_div _ _)
@[simp] theorem add_mul_mod_self {a b c : ℤ} : (a + b * c) % c = a % c :=
if cz : c = 0 then by rw [cz, mul_zero, add_zero] else
by rw [mod_def, mod_def, int.add_mul_div_right _ _ cz,
mul_add, mul_comm, add_sub_add_right_eq_sub]
@[simp] theorem add_mul_mod_self_left (a b c : ℤ) : (a + b * c) % b = a % b :=
by rw [mul_comm, add_mul_mod_self]
@[simp] theorem add_mod_self {a b : ℤ} : (a + b) % b = a % b :=
by have := add_mul_mod_self_left a b 1; rwa mul_one at this
@[simp] theorem add_mod_self_left {a b : ℤ} : (a + b) % a = b % a :=
by rw [add_comm, add_mod_self]
@[simp] theorem mod_add_mod (m n k : ℤ) : (m % n + k) % n = (m + k) % n :=
by have := (add_mul_mod_self_left (m % n + k) n (m / n)).symm;
rwa [add_right_comm, mod_add_div] at this
@[simp] theorem add_mod_mod (m n k : ℤ) : (m + n % k) % k = (m + n) % k :=
by rw [add_comm, mod_add_mod, add_comm]
lemma add_mod (a b n : ℤ) : (a + b) % n = ((a % n) + (b % n)) % n :=
by rw [add_mod_mod, mod_add_mod]
theorem add_mod_eq_add_mod_right {m n k : ℤ} (i : ℤ) (H : m % n = k % n) :
(m + i) % n = (k + i) % n :=
by rw [← mod_add_mod, ← mod_add_mod k, H]
theorem add_mod_eq_add_mod_left {m n k : ℤ} (i : ℤ) (H : m % n = k % n) :
(i + m) % n = (i + k) % n :=
by rw [add_comm, add_mod_eq_add_mod_right _ H, add_comm]
theorem mod_add_cancel_right {m n k : ℤ} (i) : (m + i) % n = (k + i) % n ↔
m % n = k % n :=
⟨λ H, by have := add_mod_eq_add_mod_right (-i) H;
rwa [add_neg_cancel_right, add_neg_cancel_right] at this,
add_mod_eq_add_mod_right _⟩
theorem mod_add_cancel_left {m n k i : ℤ} :
(i + m) % n = (i + k) % n ↔ m % n = k % n :=
by rw [add_comm, add_comm i, mod_add_cancel_right]
theorem mod_sub_cancel_right {m n k : ℤ} (i) : (m - i) % n = (k - i) % n ↔
m % n = k % n :=
mod_add_cancel_right _
theorem mod_eq_mod_iff_mod_sub_eq_zero {m n k : ℤ} : m % n = k % n ↔ (m - k) % n = 0 :=
(mod_sub_cancel_right k).symm.trans $ by simp
@[simp] theorem mul_mod_left (a b : ℤ) : (a * b) % b = 0 :=
by rw [← zero_add (a * b), add_mul_mod_self, zero_mod]
@[simp] theorem mul_mod_right (a b : ℤ) : (a * b) % a = 0 :=
by rw [mul_comm, mul_mod_left]
lemma mul_mod (a b n : ℤ) : (a * b) % n = ((a % n) * (b % n)) % n :=
begin
conv_lhs
{ rw [←mod_add_div a n, ←mod_add_div' b n, right_distrib, left_distrib, left_distrib,
mul_assoc, mul_assoc, ←left_distrib n _ _, add_mul_mod_self_left, ← mul_assoc,
add_mul_mod_self] }
end
@[simp] lemma neg_mod_two (i : ℤ) : (-i) % 2 = i % 2 :=
begin
apply int.mod_eq_mod_iff_mod_sub_eq_zero.mpr,
convert int.mul_mod_right 2 (-i),
simp only [two_mul, sub_eq_add_neg]
end
local attribute [simp] -- Will be generalized to Euclidean domains.
theorem mod_self {a : ℤ} : a % a = 0 :=
by have := mul_mod_left 1 a; rwa one_mul at this
@[simp] theorem mod_mod_of_dvd (n : ℤ) {m k : ℤ} (h : m ∣ k) : n % k % m = n % m :=
begin
conv { to_rhs, rw ←mod_add_div n k },
rcases h with ⟨t, rfl⟩, rw [mul_assoc, add_mul_mod_self_left]
end
@[simp] theorem mod_mod (a b : ℤ) : a % b % b = a % b :=
by conv {to_rhs, rw [← mod_add_div a b, add_mul_mod_self_left]}
lemma sub_mod (a b n : ℤ) : (a - b) % n = ((a % n) - (b % n)) % n :=
begin
apply (mod_add_cancel_right b).mp,
rw [sub_add_cancel, ← add_mod_mod, sub_add_cancel, mod_mod]
end
protected theorem div_mod_unique {a b r q : ℤ} (h : 0 < b) :
a / b = q ∧ a % b = r ↔ r + b * q = a ∧ 0 ≤ r ∧ r < b :=
begin
split,
{ rintro ⟨rfl, rfl⟩,
exact ⟨mod_add_div a b, mod_nonneg _ h.ne.symm, mod_lt_of_pos _ h⟩, },
{ rintro ⟨rfl, hz, hb⟩,
split,
{ rw [int.add_mul_div_left r q (ne_of_gt h), div_eq_zero_of_lt hz hb],
simp, },
{ rw [add_mul_mod_self_left, mod_eq_of_lt hz hb] } },
end
/-! ### properties of `/` and `%` -/
@[simp] theorem mul_div_mul_of_pos {a : ℤ} (b c : ℤ) (H : 0 < a) : a * b / (a * c) = b / c :=
suffices ∀ (m k : ℕ) (b : ℤ), (m.succ * b / (m.succ * k) : ℤ) = b / k, from
match a, eq_succ_of_zero_lt H, c, eq_coe_or_neg c with
| ._, ⟨m, rfl⟩, ._, ⟨k, or.inl rfl⟩ := this _ _ _
| ._, ⟨m, rfl⟩, ._, ⟨k, or.inr rfl⟩ :=
by rw [mul_neg, int.div_neg, int.div_neg];
apply congr_arg has_neg.neg; apply this
end,
λ m k b, match b, k with
| (n : ℕ), k := congr_arg of_nat (nat.mul_div_mul _ _ m.succ_pos)
| -[1+ n], 0 := by rw [int.coe_nat_zero, mul_zero, int.div_zero, int.div_zero]
| -[1+ n], k+1 := congr_arg neg_succ_of_nat $
show (m.succ * n + m) / (m.succ * k.succ) = n / k.succ, begin
apply nat.div_eq_of_lt_le,
{ refine le_trans _ (nat.le_add_right _ _),
rw [← nat.mul_div_mul _ _ m.succ_pos],
apply nat.div_mul_le_self },
{ change m.succ * n.succ ≤ _,
rw [mul_left_comm],
apply nat.mul_le_mul_left,
apply (nat.div_lt_iff_lt_mul k.succ_pos).1,
apply nat.lt_succ_self }
end
end
@[simp] theorem mul_div_mul_of_pos_left (a : ℤ) {b : ℤ} (H : 0 < b) (c : ℤ) :
a * b / (c * b) = a / c :=
by rw [mul_comm, mul_comm c, mul_div_mul_of_pos _ _ H]
@[simp] theorem mul_mod_mul_of_pos {a : ℤ} (H : 0 < a) (b c : ℤ) : a * b % (a * c) = a * (b % c) :=
by rw [mod_def, mod_def, mul_div_mul_of_pos _ _ H, mul_sub_left_distrib, mul_assoc]
theorem lt_div_add_one_mul_self (a : ℤ) {b : ℤ} (H : 0 < b) : a < (a / b + 1) * b :=
by { rw [add_mul, one_mul, mul_comm, ← sub_lt_iff_lt_add', ← mod_def],
exact mod_lt_of_pos _ H }
theorem abs_div_le_abs : ∀ (a b : ℤ), |a / b| ≤ |a| :=
suffices ∀ (a : ℤ) (n : ℕ), |a / n| ≤ |a|, from
λ a b, match b, eq_coe_or_neg b with
| ._, ⟨n, or.inl rfl⟩ := this _ _
| ._, ⟨n, or.inr rfl⟩ := by rw [int.div_neg, abs_neg]; apply this
end,
λ a n, by rw [abs_eq_nat_abs, abs_eq_nat_abs]; exact
coe_nat_le_coe_nat_of_le (match a, n with
| (m : ℕ), n := nat.div_le_self _ _
| -[1+ m], 0 := nat.zero_le _
| -[1+ m], n+1 := nat.succ_le_succ (nat.div_le_self _ _)
end)
theorem div_le_self {a : ℤ} (b : ℤ) (Ha : 0 ≤ a) : a / b ≤ a :=
by have := le_trans (le_abs_self _) (abs_div_le_abs a b);
rwa [abs_of_nonneg Ha] at this
theorem mul_div_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : b * (a / b) = a :=
by have := mod_add_div a b; rwa [H, zero_add] at this
theorem div_mul_cancel_of_mod_eq_zero {a b : ℤ} (H : a % b = 0) : a / b * b = a :=
by rw [mul_comm, mul_div_cancel_of_mod_eq_zero H]
lemma mod_two_eq_zero_or_one (n : ℤ) : n % 2 = 0 ∨ n % 2 = 1 :=
have h : n % 2 < 2 := abs_of_nonneg (show 0 ≤ (2 : ℤ), from dec_trivial) ▸ int.mod_lt _ dec_trivial,
have h₁ : 0 ≤ n % 2 := int.mod_nonneg _ dec_trivial,
match (n % 2), h, h₁ with
| (0 : ℕ) := λ _ _, or.inl rfl
| (1 : ℕ) := λ _ _, or.inr rfl
| (k + 2 : ℕ) := λ h _, absurd h dec_trivial
| -[1+ a] := λ _ h₁, absurd h₁ dec_trivial
end
/-! ### dvd -/
@[norm_cast] theorem coe_nat_dvd {m n : ℕ} : (↑m : ℤ) ∣ ↑n ↔ m ∣ n :=
⟨λ ⟨a, ae⟩, m.eq_zero_or_pos.elim
(λm0, by simp [m0] at ae; simp [ae, m0])
(λm0l, by
{ cases eq_coe_of_zero_le (@nonneg_of_mul_nonneg_right ℤ _ m a
(by simp [ae.symm]) (by simpa using m0l)) with k e,
subst a, exact ⟨k, int.coe_nat_inj ae⟩ }),
λ ⟨k, e⟩, dvd.intro k $ by rw [e, int.coe_nat_mul]⟩
theorem coe_nat_dvd_left {n : ℕ} {z : ℤ} : (↑n : ℤ) ∣ z ↔ n ∣ z.nat_abs :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem coe_nat_dvd_right {n : ℕ} {z : ℤ} : z ∣ (↑n : ℤ) ↔ z.nat_abs ∣ n :=
by rcases nat_abs_eq z with eq | eq; rw eq; simp [coe_nat_dvd]
theorem dvd_antisymm {a b : ℤ} (H1 : 0 ≤ a) (H2 : 0 ≤ b) : a ∣ b → b ∣ a → a = b :=
begin
rw [← abs_of_nonneg H1, ← abs_of_nonneg H2, abs_eq_nat_abs, abs_eq_nat_abs],
rw [coe_nat_dvd, coe_nat_dvd, coe_nat_inj'],
apply nat.dvd_antisymm
end
theorem dvd_of_mod_eq_zero {a b : ℤ} (H : b % a = 0) : a ∣ b :=
⟨b / a, (mul_div_cancel_of_mod_eq_zero H).symm⟩
theorem mod_eq_zero_of_dvd : ∀ {a b : ℤ}, a ∣ b → b % a = 0
| a ._ ⟨c, rfl⟩ := mul_mod_right _ _
theorem dvd_iff_mod_eq_zero (a b : ℤ) : a ∣ b ↔ b % a = 0 :=
⟨mod_eq_zero_of_dvd, dvd_of_mod_eq_zero⟩
/-- If `a % b = c` then `b` divides `a - c`. -/
lemma dvd_sub_of_mod_eq {a b c : ℤ} (h : a % b = c) : b ∣ a - c :=
begin
have hx : a % b % b = c % b, { rw h },
rw [mod_mod, ←mod_sub_cancel_right c, sub_self, zero_mod] at hx,
exact dvd_of_mod_eq_zero hx
end
theorem nat_abs_dvd {a b : ℤ} : (a.nat_abs : ℤ) ∣ b ↔ a ∣ b :=
(nat_abs_eq a).elim (λ e, by rw ← e) (λ e, by rw [← neg_dvd, ← e])
theorem dvd_nat_abs {a b : ℤ} : a ∣ b.nat_abs ↔ a ∣ b :=
(nat_abs_eq b).elim (λ e, by rw ← e) (λ e, by rw [← dvd_neg, ← e])
instance decidable_dvd : @decidable_rel ℤ (∣) :=
assume a n, decidable_of_decidable_of_iff (by apply_instance) (dvd_iff_mod_eq_zero _ _).symm
protected theorem div_mul_cancel {a b : ℤ} (H : b ∣ a) : a / b * b = a :=
div_mul_cancel_of_mod_eq_zero (mod_eq_zero_of_dvd H)
protected theorem mul_div_cancel' {a b : ℤ} (H : a ∣ b) : a * (b / a) = b :=
by rw [mul_comm, int.div_mul_cancel H]
protected theorem mul_div_assoc (a : ℤ) : ∀ {b c : ℤ}, c ∣ b → (a * b) / c = a * (b / c)
| ._ c ⟨d, rfl⟩ := if cz : c = 0 then by simp [cz] else
by rw [mul_left_comm, int.mul_div_cancel_left _ cz, int.mul_div_cancel_left _ cz]
protected theorem mul_div_assoc' (b : ℤ) {a c : ℤ} (h : c ∣ a) : a * b / c = a / c * b :=
by rw [mul_comm, int.mul_div_assoc _ h, mul_comm]
theorem div_dvd_div : ∀ {a b c : ℤ} (H1 : a ∣ b) (H2 : b ∣ c), b / a ∣ c / a
| a ._ ._ ⟨b, rfl⟩ ⟨c, rfl⟩ := if az : a = 0 then by simp [az] else
by rw [int.mul_div_cancel_left _ az, mul_assoc, int.mul_div_cancel_left _ az];
apply dvd_mul_right
protected theorem eq_mul_of_div_eq_right {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) :
a = b * c :=
by rw [← H2, int.mul_div_cancel' H1]
protected theorem div_eq_of_eq_mul_right {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = b * c) :
a / b = c :=
by rw [H2, int.mul_div_cancel_left _ H1]
protected theorem eq_div_of_mul_eq_right {a b c : ℤ} (H1 : a ≠ 0) (H2 : a * b = c) :
b = c / a :=
eq.symm $ int.div_eq_of_eq_mul_right H1 H2.symm
protected theorem div_eq_iff_eq_mul_right {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) :
a / b = c ↔ a = b * c :=
⟨int.eq_mul_of_div_eq_right H', int.div_eq_of_eq_mul_right H⟩
protected theorem div_eq_iff_eq_mul_left {a b c : ℤ} (H : b ≠ 0) (H' : b ∣ a) :
a / b = c ↔ a = c * b :=
by rw mul_comm; exact int.div_eq_iff_eq_mul_right H H'
protected theorem eq_mul_of_div_eq_left {a b c : ℤ} (H1 : b ∣ a) (H2 : a / b = c) :
a = c * b :=
by rw [mul_comm, int.eq_mul_of_div_eq_right H1 H2]
protected theorem div_eq_of_eq_mul_left {a b c : ℤ} (H1 : b ≠ 0) (H2 : a = c * b) :
a / b = c :=
int.div_eq_of_eq_mul_right H1 (by rw [mul_comm, H2])
protected lemma eq_zero_of_div_eq_zero {d n : ℤ} (h : d ∣ n) (H : n / d = 0) : n = 0 :=
by rw [← int.mul_div_cancel' h, H, mul_zero]
theorem neg_div_of_dvd : ∀ {a b : ℤ} (H : b ∣ a), -a / b = -(a / b)
| ._ b ⟨c, rfl⟩ := if bz : b = 0 then by simp [bz] else
by rw [neg_mul_eq_mul_neg, int.mul_div_cancel_left _ bz, int.mul_div_cancel_left _ bz]
lemma sub_div_of_dvd (a : ℤ) {b c : ℤ} (hcb : c ∣ b) : (a - b) / c = a / c - b / c :=
begin
rw [sub_eq_add_neg, sub_eq_add_neg, int.add_div_of_dvd_right ((dvd_neg c b).mpr hcb)],
congr,
exact neg_div_of_dvd hcb,
end
lemma sub_div_of_dvd_sub {a b c : ℤ} (hcab : c ∣ (a - b)) : (a - b) / c = a / c - b / c :=
by rw [eq_sub_iff_add_eq, ← int.add_div_of_dvd_left hcab, sub_add_cancel]
@[simp]
protected lemma div_left_inj {a b d : ℤ} (hda : d ∣ a) (hdb : d ∣ b) : a / d = b / d ↔ a = b :=
begin
refine ⟨λ h, _, congr_arg _⟩,
rw [←int.mul_div_cancel' hda, ←int.mul_div_cancel' hdb, h],
end
lemma nat_abs_sign (z : ℤ) :
z.sign.nat_abs = if z = 0 then 0 else 1 :=
by rcases z with (_ | _) | _; refl
lemma nat_abs_sign_of_nonzero {z : ℤ} (hz : z ≠ 0) :
z.sign.nat_abs = 1 :=
by rw [int.nat_abs_sign, if_neg hz]
lemma abs_sign_of_nonzero {z : ℤ} (hz : z ≠ 0) : |z.sign| = 1 :=
by rw [abs_eq_nat_abs, nat_abs_sign_of_nonzero hz, int.coe_nat_one]
lemma sign_coe_nat_of_nonzero {n : ℕ} (hn : n ≠ 0) :
int.sign n = 1 :=
begin
obtain ⟨n, rfl⟩ := nat.exists_eq_succ_of_ne_zero hn,
exact int.sign_of_succ n
end
@[simp] lemma sign_neg (z : ℤ) :
int.sign (-z) = -int.sign z :=
by rcases z with (_ | _)| _; refl
theorem div_sign : ∀ a b, a / sign b = a * sign b
| a (n+1:ℕ) := by unfold sign; simp
| a 0 := by simp [sign]
| a -[1+ n] := by simp [sign]
@[simp] theorem sign_mul : ∀ a b, sign (a * b) = sign a * sign b
| a 0 := by simp
| 0 b := by simp
| (m+1:ℕ) (n+1:ℕ) := rfl
| (m+1:ℕ) -[1+ n] := rfl
| -[1+ m] (n+1:ℕ) := rfl
| -[1+ m] -[1+ n] := rfl
protected theorem sign_eq_div_abs (a : ℤ) : sign a = a / |a| :=
if az : a = 0 then by simp [az] else
(int.div_eq_of_eq_mul_left (mt abs_eq_zero.1 az)
(sign_mul_abs _).symm).symm
theorem mul_sign : ∀ (i : ℤ), i * sign i = nat_abs i
| (n+1:ℕ) := mul_one _
| 0 := mul_zero _
| -[1+ n] := mul_neg_one _
@[simp]
theorem sign_pow_bit1 (k : ℕ) : ∀ n : ℤ, n.sign ^ (bit1 k) = n.sign
| (n+1:ℕ) := one_pow (bit1 k)
| 0 := zero_pow (nat.zero_lt_bit1 k)
| -[1+ n] := (neg_pow_bit1 1 k).trans (congr_arg (λ x, -x) (one_pow (bit1 k)))
theorem le_of_dvd {a b : ℤ} (bpos : 0 < b) (H : a ∣ b) : a ≤ b :=
match a, b, eq_succ_of_zero_lt bpos, H with
| (m : ℕ), ._, ⟨n, rfl⟩, H := coe_nat_le_coe_nat_of_le $
nat.le_of_dvd n.succ_pos $ coe_nat_dvd.1 H
| -[1+ m], ._, ⟨n, rfl⟩, _ :=
le_trans (le_of_lt $ neg_succ_lt_zero _) (coe_zero_le _)
end
theorem eq_one_of_dvd_one {a : ℤ} (H : 0 ≤ a) (H' : a ∣ 1) : a = 1 :=
match a, eq_coe_of_zero_le H, H' with
| ._, ⟨n, rfl⟩, H' := congr_arg coe $
nat.eq_one_of_dvd_one $ coe_nat_dvd.1 H'
end
theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : 0 ≤ a) (H' : a * b = 1) : a = 1 :=
eq_one_of_dvd_one H ⟨b, H'.symm⟩
theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : 0 ≤ b) (H' : a * b = 1) : b = 1 :=
eq_one_of_mul_eq_one_right H (by rw [mul_comm, H'])
lemma of_nat_dvd_of_dvd_nat_abs {a : ℕ} : ∀ {z : ℤ} (haz : a ∣ z.nat_abs), ↑a ∣ z
| (int.of_nat _) haz := int.coe_nat_dvd.2 haz
| -[1+k] haz :=
begin
change ↑a ∣ -(k+1 : ℤ),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
exact haz
end
lemma dvd_nat_abs_of_of_nat_dvd {a : ℕ} : ∀ {z : ℤ} (haz : ↑a ∣ z), a ∣ z.nat_abs
| (int.of_nat _) haz := int.coe_nat_dvd.1 (int.dvd_nat_abs.2 haz)
| -[1+k] haz :=
have haz' : (↑a:ℤ) ∣ (↑(k+1):ℤ), from dvd_of_dvd_neg haz,
int.coe_nat_dvd.1 haz'
lemma pow_dvd_of_le_of_pow_dvd {p m n : ℕ} {k : ℤ} (hmn : m ≤ n) (hdiv : ↑(p ^ n) ∣ k) :
↑(p ^ m) ∣ k :=
begin
induction k,
{ apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1 hdiv },
change -[1+k] with -(↑(k+1) : ℤ),
apply dvd_neg_of_dvd,
apply int.coe_nat_dvd.2,
apply pow_dvd_of_le_of_pow_dvd hmn,
apply int.coe_nat_dvd.1,
apply dvd_of_dvd_neg,
exact hdiv,
end
lemma dvd_of_pow_dvd {p k : ℕ} {m : ℤ} (hk : 1 ≤ k) (hpk : ↑(p^k) ∣ m) : ↑p ∣ m :=
by rw ←pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk
/-- If `n > 0` then `m` is not divisible by `n` iff it is between `n * k` and `n * (k + 1)`
for some `k`. -/
lemma exists_lt_and_lt_iff_not_dvd (m : ℤ) {n : ℤ} (hn : 0 < n) :
(∃ k, n * k < m ∧ m < n * (k + 1)) ↔ ¬ n ∣ m :=
begin
split,
{ rintro ⟨k, h1k, h2k⟩ ⟨l, rfl⟩, rw [mul_lt_mul_left hn] at h1k h2k,
rw [lt_add_one_iff, ← not_lt] at h2k, exact h2k h1k },
{ intro h, rw [dvd_iff_mod_eq_zero, ← ne.def] at h,
have := (mod_nonneg m hn.ne.symm).lt_of_ne h.symm,
simp only [← mod_add_div m n] {single_pass := tt},
refine ⟨m / n, lt_add_of_pos_left _ this, _⟩,
rw [add_comm _ (1 : ℤ), left_distrib, mul_one], exact add_lt_add_right (mod_lt_of_pos _ hn) _ }
end
/-! ### `/` and ordering -/
protected theorem div_mul_le (a : ℤ) {b : ℤ} (H : b ≠ 0) : a / b * b ≤ a :=
le_of_sub_nonneg $ by rw [mul_comm, ← mod_def]; apply mod_nonneg _ H
protected theorem div_le_of_le_mul {a b c : ℤ} (H : 0 < c) (H' : a ≤ b * c) : a / c ≤ b :=
le_of_mul_le_mul_right (le_trans (int.div_mul_le _ (ne_of_gt H)) H') H
protected theorem mul_lt_of_lt_div {a b c : ℤ} (H : 0 < c) (H3 : a < b / c) : a * c < b :=
lt_of_not_ge $ mt (int.div_le_of_le_mul H) (not_le_of_gt H3)
protected theorem mul_le_of_le_div {a b c : ℤ} (H1 : 0 < c) (H2 : a ≤ b / c) : a * c ≤ b :=
le_trans (decidable.mul_le_mul_of_nonneg_right H2 (le_of_lt H1)) (int.div_mul_le _ (ne_of_gt H1))
protected theorem le_div_of_mul_le {a b c : ℤ} (H1 : 0 < c) (H2 : a * c ≤ b) : a ≤ b / c :=
le_of_lt_add_one $ lt_of_mul_lt_mul_right
(lt_of_le_of_lt H2 (lt_div_add_one_mul_self _ H1)) (le_of_lt H1)
protected theorem le_div_iff_mul_le {a b c : ℤ} (H : 0 < c) : a ≤ b / c ↔ a * c ≤ b :=
⟨int.mul_le_of_le_div H, int.le_div_of_mul_le H⟩
protected theorem div_le_div {a b c : ℤ} (H : 0 < c) (H' : a ≤ b) : a / c ≤ b / c :=
int.le_div_of_mul_le H (le_trans (int.div_mul_le _ (ne_of_gt H)) H')
protected theorem div_lt_of_lt_mul {a b c : ℤ} (H : 0 < c) (H' : a < b * c) : a / c < b :=
lt_of_not_ge $ mt (int.mul_le_of_le_div H) (not_le_of_gt H')
protected theorem lt_mul_of_div_lt {a b c : ℤ} (H1 : 0 < c) (H2 : a / c < b) : a < b * c :=
lt_of_not_ge $ mt (int.le_div_of_mul_le H1) (not_le_of_gt H2)
protected theorem div_lt_iff_lt_mul {a b c : ℤ} (H : 0 < c) : a / c < b ↔ a < b * c :=
⟨int.lt_mul_of_div_lt H, int.div_lt_of_lt_mul H⟩
protected theorem le_mul_of_div_le {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ a) (H3 : a / b ≤ c) :
a ≤ c * b :=
by rw [← int.div_mul_cancel H2]; exact decidable.mul_le_mul_of_nonneg_right H3 H1
protected theorem lt_div_of_mul_lt {a b c : ℤ} (H1 : 0 ≤ b) (H2 : b ∣ c) (H3 : a * b < c) :
a < c / b :=
lt_of_not_ge $ mt (int.le_mul_of_div_le H1 H2) (not_le_of_gt H3)
protected theorem lt_div_iff_mul_lt {a b : ℤ} (c : ℤ) (H : 0 < c) (H' : c ∣ b) :
a < b / c ↔ a * c < b :=
⟨int.mul_lt_of_lt_div H, int.lt_div_of_mul_lt (le_of_lt H) H'⟩
theorem div_pos_of_pos_of_dvd {a b : ℤ} (H1 : 0 < a) (H2 : 0 ≤ b) (H3 : b ∣ a) : 0 < a / b :=
int.lt_div_of_mul_lt H2 H3 (by rwa zero_mul)
theorem div_eq_div_of_mul_eq_mul {a b c d : ℤ} (H2 : d ∣ c) (H3 : b ≠ 0)
(H4 : d ≠ 0) (H5 : a * d = b * c) :
a / b = c / d :=
int.div_eq_of_eq_mul_right H3 $
by rw [← int.mul_div_assoc _ H2]; exact
(int.div_eq_of_eq_mul_left H4 H5.symm).symm
theorem eq_mul_div_of_mul_eq_mul_of_dvd_left {a b c d : ℤ} (hb : b ≠ 0) (hbc : b ∣ c)
(h : b * a = c * d) :
a = c / b * d :=
begin
cases hbc with k hk,
subst hk,
rw [int.mul_div_cancel_left _ hb],
rw mul_assoc at h,
apply mul_left_cancel₀ hb h
end
/-- If an integer with larger absolute value divides an integer, it is
zero. -/
lemma eq_zero_of_dvd_of_nat_abs_lt_nat_abs {a b : ℤ} (w : a ∣ b) (h : nat_abs b < nat_abs a) :
b = 0 :=
begin
rw [←nat_abs_dvd, ←dvd_nat_abs, coe_nat_dvd] at w,
rw ←nat_abs_eq_zero,
exact eq_zero_of_dvd_of_lt w h
end
lemma eq_zero_of_dvd_of_nonneg_of_lt {a b : ℤ} (w₁ : 0 ≤ a) (w₂ : a < b) (h : b ∣ a) : a = 0 :=
eq_zero_of_dvd_of_nat_abs_lt_nat_abs h (nat_abs_lt_nat_abs_of_nonneg_of_lt w₁ w₂)
/-- If two integers are congruent to a sufficiently large modulus,
they are equal. -/
lemma eq_of_mod_eq_of_nat_abs_sub_lt_nat_abs {a b c : ℤ} (h1 : a % b = c)
(h2 : nat_abs (a - c) < nat_abs b) :
a = c :=
eq_of_sub_eq_zero (eq_zero_of_dvd_of_nat_abs_lt_nat_abs (dvd_sub_of_mod_eq h1) h2)
theorem of_nat_add_neg_succ_of_nat_of_lt {m n : ℕ} (h : m < n.succ) :
of_nat m + -[1+n] = -[1+ n - m] :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = (n - m).succ,
apply succ_sub,
apply le_of_lt_succ h,
simp [*, sub_nat_nat]
end
theorem of_nat_add_neg_succ_of_nat_of_ge {m n : ℕ}
(h : n.succ ≤ m) : of_nat m + -[1+n] = of_nat (m - n.succ) :=
begin
change sub_nat_nat _ _ = _,
have h' : n.succ - m = 0,
apply tsub_eq_zero_iff_le.mpr h,
simp [*, sub_nat_nat]
end
@[simp] theorem neg_add_neg (m n : ℕ) : -[1+m] + -[1+n] = -[1+nat.succ(m+n)] := rfl
lemma nat_abs_le_of_dvd_ne_zero {s t : ℤ} (hst : s ∣ t) (ht : t ≠ 0) : nat_abs s ≤ nat_abs t :=
not_lt.mp (mt (eq_zero_of_dvd_of_nat_abs_lt_nat_abs hst) ht)
lemma nat_abs_eq_of_dvd_dvd {s t : ℤ} (hst : s ∣ t) (hts : t ∣ s) : nat_abs s = nat_abs t :=
nat.dvd_antisymm (nat_abs_dvd_iff_dvd.mpr hst) (nat_abs_dvd_iff_dvd.mpr hts)
lemma div_dvd_of_dvd {s t : ℤ} (hst : s ∣ t) : (t / s) ∣ t :=
begin
rcases eq_or_ne s 0 with rfl | hs,
{ simpa using hst },
rcases hst with ⟨c, hc⟩,
simp [hc, int.mul_div_cancel_left _ hs],
end
lemma dvd_div_of_mul_dvd {a b c : ℤ} (h : a * b ∣ c) : b ∣ c / a :=
begin
rcases eq_or_ne a 0 with rfl | ha,
{ simp only [int.div_zero, dvd_zero] },
rcases h with ⟨d, rfl⟩,
refine ⟨d, _⟩,
rw [mul_assoc, int.mul_div_cancel_left _ ha],
end
/-! ### to_nat -/
theorem to_nat_eq_max : ∀ (a : ℤ), (to_nat a : ℤ) = max a 0
| (n : ℕ) := (max_eq_left (coe_zero_le n)).symm
| -[1+ n] := (max_eq_right (le_of_lt (neg_succ_lt_zero n))).symm
@[simp] lemma to_nat_zero : (0 : ℤ).to_nat = 0 := rfl
@[simp] lemma to_nat_one : (1 : ℤ).to_nat = 1 := rfl
@[simp] theorem to_nat_of_nonneg {a : ℤ} (h : 0 ≤ a) : (to_nat a : ℤ) = a :=
by rw [to_nat_eq_max, max_eq_left h]
@[simp] lemma to_nat_sub_of_le {a b : ℤ} (h : b ≤ a) : (to_nat (a - b) : ℤ) = a - b :=
int.to_nat_of_nonneg (sub_nonneg_of_le h)
@[simp] theorem to_nat_coe_nat (n : ℕ) : to_nat ↑n = n := rfl
@[simp] lemma to_nat_coe_nat_add_one {n : ℕ} : ((n : ℤ) + 1).to_nat = n + 1 := rfl
theorem le_to_nat (a : ℤ) : a ≤ to_nat a :=
by rw [to_nat_eq_max]; apply le_max_left
@[simp] theorem to_nat_le {a : ℤ} {n : ℕ} : to_nat a ≤ n ↔ a ≤ n :=
by rw [(coe_nat_le_coe_nat_iff _ _).symm, to_nat_eq_max, max_le_iff];
exact and_iff_left (coe_zero_le _)
@[simp] theorem lt_to_nat {n : ℕ} {a : ℤ} : n < to_nat a ↔ (n : ℤ) < a :=
le_iff_le_iff_lt_iff_lt.1 to_nat_le
@[simp]lemma le_to_nat_iff {n : ℕ} {z : ℤ} (h : 0 ≤ z) : n ≤ z.to_nat ↔ (n : ℤ) ≤ z :=
by rw [←int.coe_nat_le_coe_nat_iff, int.to_nat_of_nonneg h]
@[simp]
lemma coe_nat_nonpos_iff {n : ℕ} : (n : ℤ) ≤ 0 ↔ n = 0 :=
⟨ λ h, le_antisymm (int.coe_nat_le.mp (h.trans int.coe_nat_zero.le)) n.zero_le,
λ h, (coe_nat_eq_zero.mpr h).le⟩
theorem to_nat_le_to_nat {a b : ℤ} (h : a ≤ b) : to_nat a ≤ to_nat b :=
by rw to_nat_le; exact le_trans h (le_to_nat b)
theorem to_nat_lt_to_nat {a b : ℤ} (hb : 0 < b) : to_nat a < to_nat b ↔ a < b :=
⟨λ h, begin cases a, exact lt_to_nat.1 h, exact lt_trans (neg_succ_of_nat_lt_zero a) hb, end,
λ h, begin rw lt_to_nat, cases a, exact h, exact hb end⟩
theorem lt_of_to_nat_lt {a b : ℤ} (h : to_nat a < to_nat b) : a < b :=
(to_nat_lt_to_nat $ lt_to_nat.1 $ lt_of_le_of_lt (nat.zero_le _) h).1 h
lemma to_nat_add {a b : ℤ} (ha : 0 ≤ a) (hb : 0 ≤ b) :
(a + b).to_nat = a.to_nat + b.to_nat :=
begin
lift a to ℕ using ha,
lift b to ℕ using hb,
norm_cast,
end
lemma to_nat_add_nat {a : ℤ} (ha : 0 ≤ a) (n : ℕ) : (a + n).to_nat = a.to_nat + n :=
begin
lift a to ℕ using ha,
norm_cast,
end
@[simp]
lemma pred_to_nat : ∀ (i : ℤ), (i - 1).to_nat = i.to_nat - 1
| (0:ℕ) := rfl
| (n+1:ℕ) := by simp
| -[1+ n] := rfl
@[simp]
lemma to_nat_pred_coe_of_pos {i : ℤ} (h : 0 < i) : ((i.to_nat - 1 : ℕ) : ℤ) = i - 1 :=
by simp [h, le_of_lt h] with push_cast
@[simp] lemma to_nat_sub_to_nat_neg : ∀ (n : ℤ), ↑n.to_nat - ↑((-n).to_nat) = n
| (0 : ℕ) := rfl
| (n+1 : ℕ) := show ↑(n+1) - (0:ℤ) = n+1, from sub_zero _
| -[1+ n] := show 0 - (n+1 : ℤ) = _, from zero_sub _
@[simp] lemma to_nat_add_to_nat_neg_eq_nat_abs : ∀ (n : ℤ), (n.to_nat) + ((-n).to_nat) = n.nat_abs
| (0 : ℕ) := rfl
| (n+1 : ℕ) := show (n+1) + 0 = n+1, from add_zero _
| -[1+ n] := show 0 + (n+1) = n+1, from zero_add _
/-- If `n : ℕ`, then `int.to_nat' n = some n`, if `n : ℤ` is negative, then `int.to_nat' n = none`.
-/
def to_nat' : ℤ → option ℕ
| (n : ℕ) := some n
| -[1+ n] := none
theorem mem_to_nat' : ∀ (a : ℤ) (n : ℕ), n ∈ to_nat' a ↔ a = n
| (m : ℕ) n := option.some_inj.trans coe_nat_inj'.symm
| -[1+ m] n := by split; intro h; cases h
lemma to_nat_of_nonpos : ∀ {z : ℤ}, z ≤ 0 → z.to_nat = 0
| 0 _ := rfl
| (n + 1 : ℕ) h := (h.not_lt (by simp)).elim
| -[1+ n] _ := rfl
@[simp]
lemma to_nat_neg_nat : ∀ (n : ℕ), (-(n : ℤ)).to_nat = 0
| 0 := rfl
| (n + 1) := rfl
@[simp]
lemma to_nat_eq_zero : ∀ {n : ℤ}, n.to_nat = 0 ↔ n ≤ 0
| (n : ℕ) := calc _ ↔ (n = 0) : ⟨(to_nat_coe_nat n).symm.trans, (to_nat_coe_nat n).trans⟩
... ↔ _ : coe_nat_nonpos_iff.symm
| -[1+ n] := show ((-((n : ℤ) + 1)).to_nat = 0) ↔ (-(n + 1) : ℤ) ≤ 0, from
calc _ ↔ true : ⟨λ _, trivial, λ h, to_nat_neg_nat _⟩
... ↔ _ : ⟨λ h, neg_nonpos_of_nonneg (coe_zero_le _), λ _, trivial⟩
/-! ### units -/
@[simp] theorem units_nat_abs (u : ℤˣ) : nat_abs u = 1 :=
units.ext_iff.1 $ nat.units_eq_one ⟨nat_abs u, nat_abs ↑u⁻¹,
by rw [← nat_abs_mul, units.mul_inv]; refl,
by rw [← nat_abs_mul, units.inv_mul]; refl⟩
theorem units_eq_one_or (u : ℤˣ) : u = 1 ∨ u = -1 :=
by simpa only [units.ext_iff, units_nat_abs] using nat_abs_eq u
lemma is_unit_eq_one_or {a : ℤ} : is_unit a → a = 1 ∨ a = -1
| ⟨x, hx⟩ := hx ▸ (units_eq_one_or _).imp (congr_arg coe) (congr_arg coe)
lemma is_unit_iff {a : ℤ} : is_unit a ↔ a = 1 ∨ a = -1 :=
begin
refine ⟨λ h, is_unit_eq_one_or h, λ h, _⟩,
rcases h with rfl | rfl,
{ exact is_unit_one },
{ exact is_unit_one.neg }
end
lemma is_unit_eq_or_eq_neg {a b : ℤ} (ha : is_unit a) (hb : is_unit b) : a = b ∨ a = -b :=
begin
rcases is_unit_eq_one_or hb with rfl | rfl,
{ exact is_unit_eq_one_or ha },
{ rwa [or_comm, neg_neg, ←is_unit_iff] },
end
lemma eq_one_or_neg_one_of_mul_eq_one {z w : ℤ} (h : z * w = 1) : z = 1 ∨ z = -1 :=
is_unit_iff.mp (is_unit_of_mul_eq_one z w h)
lemma eq_one_or_neg_one_of_mul_eq_one' {z w : ℤ} (h : z * w = 1) :
(z = 1 ∧ w = 1) ∨ (z = -1 ∧ w = -1) :=
begin
have h' : w * z = 1 := (mul_comm z w) ▸ h,
rcases eq_one_or_neg_one_of_mul_eq_one h with rfl | rfl;
rcases eq_one_or_neg_one_of_mul_eq_one h' with rfl | rfl;
tauto,
end
theorem is_unit_iff_nat_abs_eq {n : ℤ} : is_unit n ↔ n.nat_abs = 1 :=
by simp [nat_abs_eq_iff, is_unit_iff]
alias is_unit_iff_nat_abs_eq ↔ is_unit.nat_abs_eq _
lemma is_unit_iff_abs_eq {x : ℤ} : is_unit x ↔ abs x = 1 :=
by rw [is_unit_iff_nat_abs_eq, abs_eq_nat_abs, ←int.coe_nat_one, coe_nat_inj']
@[norm_cast]
lemma of_nat_is_unit {n : ℕ} : is_unit (n : ℤ) ↔ is_unit n :=
by rw [nat.is_unit_iff, is_unit_iff_nat_abs_eq, nat_abs_of_nat]
lemma is_unit_mul_self {a : ℤ} (ha : is_unit a) : a * a = 1 :=
(is_unit_eq_one_or ha).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl)
lemma is_unit_sq {a : ℤ} (ha : is_unit a) : a ^ 2 = 1 :=
by rw [sq, is_unit_mul_self ha]
@[simp] lemma units_sq (u : ℤˣ) : u ^ 2 = 1 :=
by rw [units.ext_iff, units.coe_pow, units.coe_one, is_unit_sq u.is_unit]
@[simp] lemma units_mul_self (u : ℤˣ) : u * u = 1 :=
by rw [←sq, units_sq]
@[simp] lemma units_inv_eq_self (u : ℤˣ) : u⁻¹ = u :=
by rw [inv_eq_iff_mul_eq_one, units_mul_self]
-- `units.coe_mul` is a "wrong turn" for the simplifier, this undoes it and simplifies further
@[simp] lemma units_coe_mul_self (u : ℤˣ) : (u * u : ℤ) = 1 :=
by rw [←units.coe_mul, units_mul_self, units.coe_one]
@[simp] lemma neg_one_pow_ne_zero {n : ℕ} : (-1 : ℤ)^n ≠ 0 :=
pow_ne_zero _ (abs_pos.mp trivial)
lemma is_unit_add_is_unit_eq_is_unit_add_is_unit {a b c d : ℤ}
(ha : is_unit a) (hb : is_unit b) (hc : is_unit c) (hd : is_unit d) :
a + b = c + d ↔ a = c ∧ b = d ∨ a = d ∧ b = c :=
begin
rw is_unit_iff at ha hb hc hd,
cases ha; cases hb; cases hc; cases hd;
subst ha; subst hb; subst hc; subst hd;
tidy,
end
/-! ### bitwise ops -/
@[simp] lemma bodd_zero : bodd 0 = ff := rfl
@[simp] lemma bodd_one : bodd 1 = tt := rfl
lemma bodd_two : bodd 2 = ff := rfl
@[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl
@[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd :=
by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros;
simp; cases i.bodd; simp
@[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd :=
by cases n; simp; refl
@[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n :=
by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe]
@[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) :=
by cases m with m m; cases n with n n; unfold has_add.add;
simp [int.add, -of_nat_eq_coe, bool.bxor_comm]
@[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n :=
by cases m with m m; cases n with n n;
simp [← int.mul_def, int.mul, -of_nat_eq_coe, bool.bxor_comm]
theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n
| (n : ℕ) :=
by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ),
by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2
| -[1+ n] := begin
refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2),
dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul],
{ change -[1+ 2 * nat.div2 n] = _, rw zero_add },
{ rw [zero_add, add_comm], refl }
end
theorem div2_val : ∀ n, div2 n = n / 2
| (n : ℕ) := congr_arg of_nat n.div2_val
| -[1+ n] := congr_arg neg_succ_of_nat n.div2_val
lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm
lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _)
lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 :=
by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val }
lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n :=
(bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _
/-- Defines a function from `ℤ` conditionally, if it is defined for odd and even integers separately
using `bit`. -/
def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n :=
by rw [← bit_decomp n]; apply h
@[simp] lemma bit_zero : bit ff 0 = 0 := rfl
@[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] :=
by rw [bit_val, nat.bit_val]; cases b; refl
@[simp] lemma bodd_bit (b n) : bodd (bit b n) = b :=
by rw bit_val; simp; cases b; cases bodd n; refl
@[simp] lemma bodd_bit0 (n : ℤ) : bodd (bit0 n) = ff := bodd_bit ff n
@[simp] lemma bodd_bit1 (n : ℤ) : bodd (bit1 n) = tt := bodd_bit tt n
@[simp] lemma div2_bit (b n) : div2 (bit b n) = n :=
begin
rw [bit_val, div2_val, add_comm, int.add_mul_div_left, (_ : (_/2:ℤ) = 0), zero_add],
cases b,
{ simp },
{ show of_nat _ = _, rw nat.div_eq_zero; simp },
{ cc }
end
lemma bit0_ne_bit1 (m n : ℤ) : bit0 m ≠ bit1 n :=
mt (congr_arg bodd) $ by simp
lemma bit1_ne_bit0 (m n : ℤ) : bit1 m ≠ bit0 n :=
(bit0_ne_bit1 _ _).symm
lemma bit1_ne_zero (m : ℤ) : bit1 m ≠ 0 :=
by simpa only [bit0_zero] using bit1_ne_bit0 m 0
@[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero];
clear test_bit_zero; cases b; refl
@[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m
| (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ
| -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ]
private meta def bitwise_tac : tactic unit := `[
funext m,
funext n,
cases m with m m; cases n with n n; try {refl},
all_goals
{ apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat,
try {dsimp [nat.land, nat.ldiff, nat.lor]},
try {rw [
show nat.bitwise (λ a b, a && bnot b) n m =
nat.bitwise (λ a b, b && bnot a) m n, from
congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]},
apply congr_arg (λ f, nat.bitwise f m n),
funext a,
funext b,
cases a; cases b; refl },
all_goals {unfold nat.land nat.ldiff nat.lor}
]
theorem bitwise_or : bitwise bor = lor := by bitwise_tac
theorem bitwise_and : bitwise band = land := by bitwise_tac
theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac
theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac
@[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) :
bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) :=
begin
cases m with m m; cases n with n n;
repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ };
unfold bitwise nat_bitwise bnot;
[ induction h : f ff ff,
induction h : f ff tt,
induction h : f tt ff,
induction h : f tt tt ],
all_goals
{ unfold cond, rw nat.bitwise_bit,
repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } },
all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl }
end
@[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) :=
by rw [← bitwise_or, bitwise_bit]
@[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) :=
by rw [← bitwise_and, bitwise_bit]
@[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) :=
by rw [← bitwise_diff, bitwise_bit]
@[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) :=
by rw [← bitwise_xor, bitwise_bit]
@[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n)
| (n : ℕ) := by simp [lnot]
| -[1+ n] := by simp [lnot]
@[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) :
test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) :=
begin
induction k with k IH generalizing m n;
apply bit_cases_on m; intros a m';
apply bit_cases_on n; intros b n';
rw bitwise_bit,
{ simp [test_bit_zero] },
{ simp [test_bit_succ, IH] }
end
@[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k :=
by rw [← bitwise_or, test_bit_bitwise]
@[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k :=
by rw [← bitwise_and, test_bit_bitwise]
@[simp]
lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) :=
by rw [← bitwise_diff, test_bit_bitwise]
@[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) :=
by rw [← bitwise_xor, test_bit_bitwise]
@[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k)
| (n : ℕ) k := by simp [lnot, test_bit]
| -[1+ n] k := by simp [lnot, test_bit]
lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k
| (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _)
| -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _)
| (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k)
(λ i n, congr_arg coe $
by rw [← nat.shiftl_sub, add_tsub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg coe $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, tsub_self]; refl)
| -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ
(λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k])
(λ i n, congr_arg neg_succ_of_nat $
by rw [← nat.shiftl'_sub, add_tsub_cancel_left]; apply nat.le_add_right)
(λ i n, congr_arg neg_succ_of_nat $
by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, tsub_self]; refl)
lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k :=
shiftl_add _ _ _
@[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl
@[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg]
@[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl
@[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl
@[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl
@[simp]
lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl
lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k
| (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat,
← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add]
| -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ,
← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add]
lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n)
| (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _)
| -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _)
lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n)
| (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _)
| -[1+ m] n := begin
rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl,
exact coe_nat_lt_coe_nat_of_lt (pow_pos dec_trivial _)
end
lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) :=
congr_arg coe (nat.one_shiftl _)
@[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0
| (n : ℕ) := congr_arg coe (nat.zero_shiftl _)
| -[1+ n] := congr_arg coe (nat.zero_shiftr _)
@[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _
lemma eq_zero_of_abs_lt_dvd {m x : ℤ} (h1 : m ∣ x) (h2 : | x | < m) : x = 0 :=
begin
by_cases hm : m = 0, { subst m, exact zero_dvd_iff.mp h1, },
rcases h1 with ⟨d, rfl⟩,
apply mul_eq_zero_of_right,
rw [←abs_lt_one_iff, ←mul_lt_iff_lt_one_right (abs_pos.mpr hm), ←abs_mul],
exact lt_of_lt_of_le h2 (le_abs_self m),
end
lemma sq_eq_one_of_sq_lt_four {x : ℤ} (h1 : x ^ 2 < 4) (h2 : x ≠ 0) : x ^ 2 = 1 :=
sq_eq_one_iff.mpr ((abs_eq (zero_le_one' ℤ)).mp (le_antisymm (lt_add_one_iff.mp
(abs_lt_of_sq_lt_sq h1 zero_le_two)) (sub_one_lt_iff.mp (abs_pos.mpr h2))))
lemma sq_eq_one_of_sq_le_three {x : ℤ} (h1 : x ^ 2 ≤ 3) (h2 : x ≠ 0) : x ^ 2 = 1 :=
sq_eq_one_of_sq_lt_four (lt_of_le_of_lt h1 (lt_add_one 3)) h2
end int
attribute [irreducible] int.nonneg
|
2388d393c722af34a967b27dd47d9beb28cb1ea9 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/linear_algebra/bilinear_form.lean | a5564ba84a81f4fc67cb5db4fe54637d01fd2359 | [
"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 | 28,109 | lean | /-
Copyright (c) 2018 Andreas Swerdlow. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Andreas Swerdlow
-/
import linear_algebra.matrix
import linear_algebra.tensor_product
import linear_algebra.nonsingular_inverse
/-!
# Bilinear form
This file defines a bilinear form over a module. Basic ideas
such as orthogonality are also introduced, as well as reflexivive,
symmetric and alternating bilinear forms. Adjoints of linear maps
with respect to a bilinear form are also introduced.
A bilinear form on an R-module M, is a function from M x M to R,
that is linear in both arguments
## Notations
Given any term B of type bilin_form, due to a coercion, can use
the notation B x y to refer to the function field, ie. B x y = B.bilin x y.
## References
* <https://en.wikipedia.org/wiki/Bilinear_form>
## Tags
Bilinear form,
-/
open_locale big_operators
universes u v w
/-- A bilinear form over a module -/
structure bilin_form (R : Type u) (M : Type v) [ring R] [add_comm_group M] [module R M] :=
(bilin : M → M → R)
(bilin_add_left : ∀ (x y z : M), bilin (x + y) z = bilin x z + bilin y z)
(bilin_smul_left : ∀ (a : R) (x y : M), bilin (a • x) y = a * (bilin x y))
(bilin_add_right : ∀ (x y z : M), bilin x (y + z) = bilin x y + bilin x z)
(bilin_smul_right : ∀ (a : R) (x y : M), bilin x (a • y) = a * (bilin x y))
/-- A map with two arguments that is linear in both is a bilinear form -/
def linear_map.to_bilin {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M]
(f : M →ₗ[R] M →ₗ[R] R) : bilin_form R M :=
{ bilin := λ x y, f x y,
bilin_add_left := λ x y z, (linear_map.map_add f x y).symm ▸ linear_map.add_apply (f x) (f y) z,
bilin_smul_left := λ a x y, by {rw linear_map.map_smul, rw linear_map.smul_apply, rw smul_eq_mul},
bilin_add_right := λ x y z, linear_map.map_add (f x) y z,
bilin_smul_right := λ a x y, linear_map.map_smul (f x) a y }
namespace bilin_form
variables {R : Type u} {M : Type v} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M}
instance : has_coe_to_fun (bilin_form R M) :=
⟨_, λ B, B.bilin⟩
@[simp] lemma coe_fn_mk (f : M → M → R) (h₁ h₂ h₃ h₄) :
(bilin_form.mk f h₁ h₂ h₃ h₄ : M → M → R) = f :=
rfl
lemma coe_fn_congr : Π {x x' y y' : M}, x = x' → y = y' → B x y = B x' y'
| _ _ _ _ rfl rfl := rfl
lemma add_left (x y z : M) : B (x + y) z = B x z + B y z := bilin_add_left B x y z
lemma smul_left (a : R) (x y : M) : B (a • x) y = a * (B x y) := bilin_smul_left B a x y
lemma add_right (x y z : M) : B x (y + z) = B x y + B x z := bilin_add_right B x y z
lemma smul_right (a : R) (x y : M) : B x (a • y) = a * (B x y) := bilin_smul_right B a x y
lemma zero_left (x : M) :
B 0 x = 0 := by {rw [←@zero_smul R _ _ _ _ (0 : M), smul_left, zero_mul]}
lemma zero_right (x : M) :
B x 0 = 0 := by rw [←@zero_smul _ _ _ _ _ (0 : M), smul_right, zero_mul]
lemma neg_left (x y : M) :
B (-x) y = -(B x y) := by rw [←@neg_one_smul R _ _, smul_left, neg_one_mul]
lemma neg_right (x y : M) :
B x (-y) = -(B x y) := by rw [←@neg_one_smul R _ _, smul_right, neg_one_mul]
lemma sub_left (x y z : M) :
B (x - y) z = B x z - B y z := by rw [sub_eq_add_neg, add_left, neg_left]; refl
lemma sub_right (x y z : M) :
B x (y - z) = B x y - B x z := by rw [sub_eq_add_neg, add_right, neg_right]; refl
variable {D : bilin_form R M}
@[ext] lemma ext (H : ∀ (x y : M), B x y = D x y) : B = D := by {cases B, cases D, congr, funext, exact H _ _}
instance : add_comm_group (bilin_form R M) :=
{ add := λ B D, { bilin := λ x y, B x y + D x y,
bilin_add_left := λ x y z, by {rw add_left, rw add_left, ac_refl},
bilin_smul_left := λ a x y, by {rw [smul_left, smul_left, mul_add]},
bilin_add_right := λ x y z, by {rw add_right, rw add_right, ac_refl},
bilin_smul_right := λ a x y, by {rw [smul_right, smul_right, mul_add]} },
add_assoc := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin coe_fn has_coe_to_fun.coe bilin, rw add_assoc},
zero := { bilin := λ x y, 0,
bilin_add_left := λ x y z, (add_zero 0).symm,
bilin_smul_left := λ a x y, (mul_zero a).symm,
bilin_add_right := λ x y z, (zero_add 0).symm,
bilin_smul_right := λ a x y, (mul_zero a).symm },
zero_add := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_add},
add_zero := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_zero},
neg := λ B, { bilin := λ x y, - (B.1 x y),
bilin_add_left := λ x y z, by rw [bilin_add_left, neg_add],
bilin_smul_left := λ a x y, by rw [bilin_smul_left, mul_neg_eq_neg_mul_symm],
bilin_add_right := λ x y z, by rw [bilin_add_right, neg_add],
bilin_smul_right := λ a x y, by rw [bilin_smul_right, mul_neg_eq_neg_mul_symm] },
add_left_neg := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw neg_add_self},
add_comm := by {intros, ext, unfold coe_fn has_coe_to_fun.coe bilin, rw add_comm} }
lemma add_apply (x y : M) : (B + D) x y = B x y + D x y := rfl
lemma neg_apply (x y : M) : (-B) x y = -(B x y) := rfl
instance : inhabited (bilin_form R M) := ⟨0⟩
section
variables {R₂ : Type*} [comm_ring R₂] [module R₂ M] (F : bilin_form R₂ M) (f : M → M)
instance to_module : module R₂ (bilin_form R₂ M) :=
{ smul := λ c B,
{ bilin := λ x y, c * B x y,
bilin_add_left := λ x y z,
by {unfold coe_fn has_coe_to_fun.coe bilin, rw [bilin_add_left, left_distrib]},
bilin_smul_left := λ a x y, by {unfold coe_fn has_coe_to_fun.coe bilin,
rw [bilin_smul_left, ←mul_assoc, mul_comm c, mul_assoc]},
bilin_add_right := λ x y z, by {unfold coe_fn has_coe_to_fun.coe bilin,
rw [bilin_add_right, left_distrib]},
bilin_smul_right := λ a x y, by {unfold coe_fn has_coe_to_fun.coe bilin,
rw [bilin_smul_right, ←mul_assoc, mul_comm c, mul_assoc]} },
smul_add := λ c B D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw left_distrib},
add_smul := λ c B D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw right_distrib},
mul_smul := λ a c D, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw mul_assoc},
one_smul := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw one_mul},
zero_smul := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw zero_mul},
smul_zero := λ B, by {ext, unfold coe_fn has_coe_to_fun.coe bilin, rw mul_zero} }
lemma smul_apply (a : R₂) (x y : M) : (a • F) x y = a • (F x y) := rfl
/-- `B.to_linear_map` applies B on the left argument, then the right. -/
def to_linear_map : M →ₗ[R₂] M →ₗ[R₂] R₂ :=
linear_map.mk₂ R₂ F.1 (bilin_add_left F) (bilin_smul_left F) (bilin_add_right F) (bilin_smul_right F)
/-- Bilinear forms are equivalent to maps with two arguments that is linear in both. -/
def bilin_linear_map_equiv : (bilin_form R₂ M) ≃ₗ[R₂] (M →ₗ[R₂] M →ₗ[R₂] R₂) :=
{ to_fun := to_linear_map,
map_add' := λ B D, rfl,
map_smul' := λ a B, rfl,
inv_fun := linear_map.to_bilin,
left_inv := λ B, by {ext, refl},
right_inv := λ B, by {ext, refl} }
@[norm_cast]
lemma coe_fn_to_linear_map (x : M) : ⇑(F.to_linear_map x) = F x := rfl
lemma map_sum_left {α} (B : bilin_form R₂ M) (t : finset α) (g : α → M) (w : M) :
B (∑ i in t, g i) w = ∑ i in t, B (g i) w :=
show B.to_linear_map (∑ i in t, g i) w = ∑ i in t, B.to_linear_map (g i) w,
by rw [B.to_linear_map.map_sum, linear_map.coe_fn_sum, finset.sum_apply]
lemma map_sum_right {α} (B : bilin_form R₂ M) (t : finset α) (g : α → M) (v : M) :
B v (∑ i in t, g i) = ∑ i in t, B v (g i) :=
(B.to_linear_map v).map_sum
end
section comp
variables {N : Type w} [add_comm_group N] [module R N]
/-- Apply a linear map on the left and right argument of a bilinear form. -/
def comp (B : bilin_form R N) (l r : M →ₗ[R] N) : bilin_form R M :=
{ bilin := λ x y, B (l x) (r y),
bilin_add_left := λ x y z, by simp [add_left],
bilin_smul_left := λ x y z, by simp [smul_left],
bilin_add_right := λ x y z, by simp [add_right],
bilin_smul_right := λ x y z, by simp [smul_right] }
/-- Apply a linear map to the left argument of a bilinear form. -/
def comp_left (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M :=
B.comp f linear_map.id
/-- Apply a linear map to the right argument of a bilinear form. -/
def comp_right (B : bilin_form R M) (f : M →ₗ[R] M) : bilin_form R M :=
B.comp linear_map.id f
@[simp] lemma comp_left_comp_right (B : bilin_form R M) (l r : M →ₗ[R] M) :
(B.comp_left l).comp_right r = B.comp l r := rfl
@[simp] lemma comp_right_comp_left (B : bilin_form R M) (l r : M →ₗ[R] M) :
(B.comp_right r).comp_left l = B.comp l r := rfl
@[simp] lemma comp_apply (B : bilin_form R N) (l r : M →ₗ[R] N) (v w) :
B.comp l r v w = B (l v) (r w) := rfl
@[simp] lemma comp_left_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) :
B.comp_left f v w = B (f v) w := rfl
@[simp] lemma comp_right_apply (B : bilin_form R M) (f : M →ₗ[R] M) (v w) :
B.comp_right f v w = B v (f w) := rfl
lemma comp_injective (B₁ B₂ : bilin_form R N) (l r : M →ₗ[R] N)
(hₗ : function.surjective l) (hᵣ : function.surjective r) :
B₁.comp l r = B₂.comp l r ↔ B₁ = B₂ :=
begin
split; intros h,
{ -- B₁.comp l r = B₂.comp l r → B₁ = B₂
ext,
cases hₗ x with x' hx, subst hx,
cases hᵣ y with y' hy, subst hy,
rw [←comp_apply, ←comp_apply, h], },
{ -- B₁ = B₂ → B₁.comp l r = B₂.comp l r
subst h, },
end
end comp
section lin_mul_lin
variables {R₂ : Type*} [comm_ring R₂] [module R₂ M] {N : Type w} [add_comm_group N] [module R₂ N]
/-- `lin_mul_lin f g` is the bilinear form mapping `x` and `y` to `f x * g y` -/
def lin_mul_lin (f g : M →ₗ[R₂] R₂) : bilin_form R₂ M :=
{ bilin := λ x y, f x * g y,
bilin_add_left := λ x y z, by simp [add_mul],
bilin_smul_left := λ x y z, by simp [mul_assoc],
bilin_add_right := λ x y z, by simp [mul_add],
bilin_smul_right := λ x y z, by simp [mul_left_comm] }
variables {f g : M →ₗ[R₂] R₂}
@[simp] lemma lin_mul_lin_apply (x y) : lin_mul_lin f g x y = f x * g y := rfl
@[simp] lemma lin_mul_lin_comp (l r : N →ₗ[R₂] M) :
(lin_mul_lin f g).comp l r = lin_mul_lin (f.comp l) (g.comp r) :=
rfl
@[simp] lemma lin_mul_lin_comp_left (l : M →ₗ[R₂] M) :
(lin_mul_lin f g).comp_left l = lin_mul_lin (f.comp l) g :=
rfl
@[simp] lemma lin_mul_lin_comp_right (r : M →ₗ[R₂] M) :
(lin_mul_lin f g).comp_right r = lin_mul_lin f (g.comp r) :=
rfl
end lin_mul_lin
/-- The proposition that two elements of a bilinear form space are orthogonal -/
def is_ortho (B : bilin_form R M) (x y : M) : Prop :=
B x y = 0
lemma ortho_zero (x : M) :
is_ortho B (0 : M) x := zero_left x
section
variables {R₃ : Type*} [domain R₃] [module R₃ M] {G : bilin_form R₃ M}
theorem ortho_smul_left {x y : M} {a : R₃} (ha : a ≠ 0) :
(is_ortho G x y) ↔ (is_ortho G (a • x) y) :=
begin
dunfold is_ortho,
split; intro H,
{ rw [smul_left, H, mul_zero] },
{ rw [smul_left, mul_eq_zero] at H,
cases H,
{ trivial },
{ exact H }}
end
theorem ortho_smul_right {x y : M} {a : R₃} (ha : a ≠ 0) :
(is_ortho G x y) ↔ (is_ortho G x (a • y)) :=
begin
dunfold is_ortho,
split; intro H,
{ rw [smul_right, H, mul_zero] },
{ rw [smul_right, mul_eq_zero] at H,
cases H,
{ trivial },
{ exact H }}
end
end
end bilin_form
section matrix
variables {R : Type u} [comm_ring R]
variables {n o : Type w} [fintype n] [fintype o]
open bilin_form finset matrix
open_locale matrix
/-- The linear map from `matrix n n R` to bilinear forms on `n → R`. -/
def matrix.to_bilin_formₗ : matrix n n R →ₗ[R] bilin_form R (n → R) :=
{ to_fun := λ M,
{ bilin := λ v w, (row v ⬝ M ⬝ col w) ⟨⟩ ⟨⟩,
bilin_add_left := λ x y z, by simp [matrix.add_mul],
bilin_smul_left := λ a x y, by simp,
bilin_add_right := λ x y z, by simp [matrix.mul_add],
bilin_smul_right := λ a x y, by simp },
map_add' := λ f g, by { ext, simp [add_apply, matrix.mul_add, matrix.add_mul] },
map_smul' := λ f g, by { ext, simp [smul_apply] } }
/-- The map from `matrix n n R` to bilinear forms on `n → R`. -/
def matrix.to_bilin_form : matrix n n R → bilin_form R (n → R) :=
matrix.to_bilin_formₗ.to_fun
lemma matrix.to_bilin_form_apply (M : matrix n n R) (v w : n → R) :
(M.to_bilin_form : (n → R) → (n → R) → R) v w = (row v ⬝ M ⬝ col w) ⟨⟩ ⟨⟩ := rfl
variables [decidable_eq n] [decidable_eq o]
/-- The linear map from bilinear forms on `n → R` to `matrix n n R`. -/
def bilin_form.to_matrixₗ : bilin_form R (n → R) →ₗ[R] matrix n n R :=
{ to_fun := λ B i j, B (λ n, if n = i then 1 else 0) (λ n, if n = j then 1 else 0),
map_add' := λ f g, rfl,
map_smul' := λ f g, rfl }
/-- The map from bilinear forms on `n → R` to `matrix n n R`. -/
def bilin_form.to_matrix : bilin_form R (n → R) → matrix n n R :=
bilin_form.to_matrixₗ.to_fun
lemma bilin_form.to_matrix_apply (B : bilin_form R (n → R)) (i j : n) :
B.to_matrix i j = B (λ n, if n = i then 1 else 0) (λ n, if n = j then 1 else 0) := rfl
lemma bilin_form.to_matrix_smul (B : bilin_form R (n → R)) (x : R) :
(x • B).to_matrix = x • B.to_matrix :=
by { ext, refl }
open bilin_form
lemma bilin_form.to_matrix_comp (B : bilin_form R (n → R)) (l r : (o → R) →ₗ[R] (n → R)) :
(B.comp l r).to_matrix = l.to_matrixᵀ ⬝ B.to_matrix ⬝ r.to_matrix :=
begin
ext i j,
simp only [to_matrix_apply, comp_apply, mul_val, sum_mul],
have sum_smul_eq : Π (f : (o → R) →ₗ[R] (n → R)) (i : o),
f (λ n, ite (n = i) 1 0) = ∑ k, f.to_matrix k i • λ n, ite (n = k) (1 : R) 0,
{ intros f i,
ext j,
change f (λ n, ite (n = i) 1 0) j = (∑ k, λ n, f.to_matrix k i * ite (n = k) (1 : R) 0) j,
simp [linear_map.to_matrix, linear_map.to_matrixₗ, eq_comm] },
simp_rw [sum_smul_eq, map_sum_right, map_sum_left, smul_right, mul_comm, smul_left],
refl
end
lemma bilin_form.to_matrix_comp_left (B : bilin_form R (n → R)) (f : (n → R) →ₗ[R] (n → R)) :
(B.comp_left f).to_matrix = f.to_matrixᵀ ⬝ B.to_matrix :=
by simp [comp_left, bilin_form.to_matrix_comp]
lemma bilin_form.to_matrix_comp_right (B : bilin_form R (n → R)) (f : (n → R) →ₗ[R] (n → R)) :
(B.comp_right f).to_matrix = B.to_matrix ⬝ f.to_matrix :=
by simp [comp_right, bilin_form.to_matrix_comp]
lemma bilin_form.mul_to_matrix_mul (B : bilin_form R (n → R)) (M : matrix o n R) (N : matrix n o R) :
M ⬝ B.to_matrix ⬝ N = (B.comp (Mᵀ.to_lin) (N.to_lin)).to_matrix :=
by { ext, simp [B.to_matrix_comp (Mᵀ.to_lin) (N.to_lin), to_lin_to_matrix] }
lemma bilin_form.mul_to_matrix (B : bilin_form R (n → R)) (M : matrix n n R) :
M ⬝ B.to_matrix = (B.comp_left (Mᵀ.to_lin)).to_matrix :=
by { ext, simp [B.to_matrix_comp_left (Mᵀ.to_lin), to_lin_to_matrix] }
lemma bilin_form.to_matrix_mul (B : bilin_form R (n → R)) (M : matrix n n R) :
B.to_matrix ⬝ M = (B.comp_right (M.to_lin)).to_matrix :=
by { ext, simp [B.to_matrix_comp_right (M.to_lin), to_lin_to_matrix] }
@[simp] lemma to_matrix_to_bilin_form (B : bilin_form R (n → R)) :
B.to_matrix.to_bilin_form = B :=
begin
ext,
rw [matrix.to_bilin_form_apply, B.mul_to_matrix_mul, bilin_form.to_matrix_apply, comp_apply],
{ apply coe_fn_congr; ext; simp [mul_vec], },
{ apply_instance, },
end
@[simp] lemma to_bilin_form_to_matrix (M : matrix n n R) :
M.to_bilin_form.to_matrix = M :=
by { ext, simp [bilin_form.to_matrix_apply, matrix.to_bilin_form_apply, mul_val], }
/-- Bilinear forms are linearly equivalent to matrices. -/
def bilin_form_equiv_matrix : bilin_form R (n → R) ≃ₗ[R] matrix n n R :=
{ inv_fun := matrix.to_bilin_form,
left_inv := to_matrix_to_bilin_form,
right_inv := to_bilin_form_to_matrix,
..bilin_form.to_matrixₗ }
lemma matrix.to_bilin_form_comp {n o : Type w} [fintype n] [fintype o]
(M : matrix n n R) (P Q : matrix n o R) :
M.to_bilin_form.comp P.to_lin Q.to_lin = (Pᵀ ⬝ M ⬝ Q).to_bilin_form :=
by { classical, rw [←to_matrix_to_bilin_form (Pᵀ ⬝ M ⬝ Q).to_bilin_form,
←to_matrix_to_bilin_form (M.to_bilin_form.comp P.to_lin Q.to_lin), bilin_form.to_matrix_comp,
to_bilin_form_to_matrix, to_bilin_form_to_matrix, to_lin_to_matrix, to_lin_to_matrix], }
end matrix
namespace refl_bilin_form
open refl_bilin_form bilin_form
variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M}
/-- The proposition that a bilinear form is reflexive -/
def is_refl (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = 0 → B y x = 0
variable (H : is_refl B)
lemma eq_zero : ∀ {x y : M}, B x y = 0 → B y x = 0 := λ x y, H x y
lemma ortho_sym {x y : M} :
is_ortho B x y ↔ is_ortho B y x := ⟨eq_zero H, eq_zero H⟩
end refl_bilin_form
namespace sym_bilin_form
open sym_bilin_form bilin_form
variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M}
/-- The proposition that a bilinear form is symmetric -/
def is_sym (B : bilin_form R M) : Prop := ∀ (x y : M), B x y = B y x
variable (H : is_sym B)
lemma sym (x y : M) : B x y = B y x := H x y
lemma is_refl : refl_bilin_form.is_refl B := λ x y H1, H x y ▸ H1
lemma ortho_sym {x y : M} :
is_ortho B x y ↔ is_ortho B y x := refl_bilin_form.ortho_sym (is_refl H)
end sym_bilin_form
namespace alt_bilin_form
open alt_bilin_form bilin_form
variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] {B : bilin_form R M}
/-- The proposition that a bilinear form is alternating -/
def is_alt (B : bilin_form R M) : Prop := ∀ (x : M), B x x = 0
variable (H : is_alt B)
include H
lemma self_eq_zero (x : M) : B x x = 0 := H x
lemma neg (x y : M) :
- B x y = B y x :=
begin
have H1 : B (x + y) (x + y) = 0,
{ exact self_eq_zero H (x + y) },
rw [add_left, add_right, add_right,
self_eq_zero H, self_eq_zero H, ring.zero_add,
ring.add_zero, add_eq_zero_iff_neg_eq] at H1,
exact H1,
end
end alt_bilin_form
namespace bilin_form
section linear_adjoints
variables {R : Type u} [comm_ring R]
variables {M : Type v} [add_comm_group M] [module R M]
variables {M₂ : Type w} [add_comm_group M₂] [module R M₂]
variables (B B' : bilin_form R M) (B₂ : bilin_form R M₂)
variables (f f' : M →ₗ[R] M₂) (g g' : M₂ →ₗ[R] M)
/-- Given a pair of modules equipped with bilinear forms, this is the condition for a pair of
maps between them to be mutually adjoint. -/
def is_adjoint_pair := ∀ ⦃x y⦄, B₂ (f x) y = B x (g y)
variables {B B' B₂ f f' g g'}
lemma is_adjoint_pair.eq (h : is_adjoint_pair B B₂ f g) :
∀ {x y}, B₂ (f x) y = B x (g y) := h
lemma is_adjoint_pair_iff_comp_left_eq_comp_right (f g : module.End R M) :
is_adjoint_pair B B' f g ↔ B'.comp_left f = B.comp_right g :=
begin
split; intros h,
{ ext x y, rw [comp_left_apply, comp_right_apply], apply h, },
{ intros x y, rw [←comp_left_apply, ←comp_right_apply], rw h, },
end
lemma is_adjoint_pair_zero : is_adjoint_pair B B₂ 0 0 :=
λ x y, by simp only [bilin_form.zero_left, bilin_form.zero_right, linear_map.zero_apply]
lemma is_adjoint_pair_id : is_adjoint_pair B B 1 1 := λ x y, rfl
lemma is_adjoint_pair.add (h : is_adjoint_pair B B₂ f g) (h' : is_adjoint_pair B B₂ f' g') :
is_adjoint_pair B B₂ (f + f') (g + g') :=
λ x y, by rw [linear_map.add_apply, linear_map.add_apply, add_left, add_right, h, h']
lemma is_adjoint_pair.sub (h : is_adjoint_pair B B₂ f g) (h' : is_adjoint_pair B B₂ f' g') :
is_adjoint_pair B B₂ (f - f') (g - g') :=
λ x y, by rw [linear_map.sub_apply, linear_map.sub_apply, sub_left, sub_right, h, h']
lemma is_adjoint_pair.smul (c : R) (h : is_adjoint_pair B B₂ f g) :
is_adjoint_pair B B₂ (c • f) (c • g) :=
λ x y, by rw [linear_map.smul_apply, linear_map.smul_apply, smul_left, smul_right, h]
lemma is_adjoint_pair.comp {M₃ : Type v} [add_comm_group M₃] [module R M₃] {B₃ : bilin_form R M₃}
{f' : M₂ →ₗ[R] M₃} {g' : M₃ →ₗ[R] M₂}
(h : is_adjoint_pair B B₂ f g) (h' : is_adjoint_pair B₂ B₃ f' g') :
is_adjoint_pair B B₃ (f'.comp f) (g.comp g') :=
λ x y, by rw [linear_map.comp_apply, linear_map.comp_apply, h', h]
lemma is_adjoint_pair.mul
{f g f' g' : module.End R M} (h : is_adjoint_pair B B f g) (h' : is_adjoint_pair B B f' g') :
is_adjoint_pair B B (f * f') (g' * g) :=
λ x y, by rw [linear_map.mul_app, linear_map.mul_app, h, h']
variables (B B' B₂)
/-- The condition for an endomorphism to be "self-adjoint" with respect to a pair of bilinear forms
on the underlying module. In the case that these two forms are identical, this is the usual concept
of self adjointness. In the case that one of the forms is the negation of the other, this is the
usual concept of skew adjointness. -/
def is_pair_self_adjoint (f : module.End R M) := is_adjoint_pair B B' f f
/-- The set of pair-self-adjoint endomorphisms are a submodule of the type of all endomorphisms. -/
def is_pair_self_adjoint_submodule : submodule R (module.End R M) :=
{ carrier := { f | is_pair_self_adjoint B B' f },
zero_mem' := is_adjoint_pair_zero,
add_mem' := λ f g hf hg, hf.add hg,
smul_mem' := λ c f h, h.smul c, }
@[simp] lemma mem_is_pair_self_adjoint_submodule (f : module.End R M) :
f ∈ is_pair_self_adjoint_submodule B B' ↔ is_pair_self_adjoint B B' f :=
by refl
lemma is_pair_self_adjoint_equiv (e : M₂ ≃ₗ[R] M) (f : module.End R M) :
is_pair_self_adjoint B B' f ↔
is_pair_self_adjoint (B.comp ↑e ↑e) (B'.comp ↑e ↑e) (e.symm.conj f) :=
begin
have hₗ : (B'.comp ↑e ↑e).comp_left (e.symm.conj f) = (B'.comp_left f).comp ↑e ↑e :=
by { ext, simp [linear_equiv.symm_conj_apply], },
have hᵣ : (B.comp ↑e ↑e).comp_right (e.symm.conj f) = (B.comp_right f).comp ↑e ↑e :=
by { ext, simp [linear_equiv.conj_apply], },
have he : function.surjective (⇑(↑e : M₂ →ₗ[R] M) : M₂ → M) := e.surjective,
show bilin_form.is_adjoint_pair _ _ _ _ ↔ bilin_form.is_adjoint_pair _ _ _ _,
rw [is_adjoint_pair_iff_comp_left_eq_comp_right, is_adjoint_pair_iff_comp_left_eq_comp_right,
hᵣ, hₗ, comp_injective _ _ ↑e ↑e he he],
end
/-- An endomorphism of a module is self-adjoint with respect to a bilinear form if it serves as an
adjoint for itself. -/
def is_self_adjoint (f : module.End R M) := is_adjoint_pair B B f f
/-- An endomorphism of a module is skew-adjoint with respect to a bilinear form if its negation
serves as an adjoint. -/
def is_skew_adjoint (f : module.End R M) := is_adjoint_pair B B f (-f)
lemma is_skew_adjoint_iff_neg_self_adjoint (f : module.End R M) :
B.is_skew_adjoint f ↔ is_adjoint_pair (-B) B f f :=
show (∀ x y, B (f x) y = B x ((-f) y)) ↔ ∀ x y, B (f x) y = (-B) x (f y),
by simp only [linear_map.neg_apply, bilin_form.neg_apply, bilin_form.neg_right]
/-- The set of self-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact
it is a Jordan subalgebra.) -/
def self_adjoint_submodule := is_pair_self_adjoint_submodule B B
@[simp] lemma mem_self_adjoint_submodule (f : module.End R M) :
f ∈ B.self_adjoint_submodule ↔ B.is_self_adjoint f := iff.rfl
/-- The set of skew-adjoint endomorphisms of a module with bilinear form is a submodule. (In fact
it is a Lie subalgebra.) -/
def skew_adjoint_submodule := is_pair_self_adjoint_submodule (-B) B
@[simp] lemma mem_skew_adjoint_submodule (f : module.End R M) :
f ∈ B.skew_adjoint_submodule ↔ B.is_skew_adjoint f :=
by { rw is_skew_adjoint_iff_neg_self_adjoint, exact iff.rfl, }
end linear_adjoints
end bilin_form
section matrix_adjoints
open_locale matrix
variables {R : Type u} [comm_ring R]
variables {n : Type w} [fintype n]
variables (J J₂ A B : matrix n n R)
/-- The condition for the square matrices `A`, `B` to be an adjoint pair with respect to the square
matrices `J`, `J₂`. -/
def matrix.is_adjoint_pair := Aᵀ ⬝ J₂ = J ⬝ B
/-- The condition for a square matrix `A` to be self-adjoint with respect to the square matrix
`J`. -/
def matrix.is_self_adjoint := matrix.is_adjoint_pair J J A A
/-- The condition for a square matrix `A` to be skew-adjoint with respect to the square matrix
`J`. -/
def matrix.is_skew_adjoint := matrix.is_adjoint_pair J J A (-A)
@[simp] lemma matrix_is_adjoint_pair_bilin_form :
bilin_form.is_adjoint_pair J.to_bilin_form J₂.to_bilin_form A.to_lin B.to_lin ↔
matrix.is_adjoint_pair J J₂ A B:=
begin
classical,
rw bilin_form.is_adjoint_pair_iff_comp_left_eq_comp_right,
have h : ∀ (B B' : bilin_form R (n → R)), B = B' ↔ B.to_matrix = B'.to_matrix := λ B B', by {
split; intros h, { rw h, }, { rw [←to_matrix_to_bilin_form B, h, to_matrix_to_bilin_form B'], }, },
rw [h, J₂.to_bilin_form.to_matrix_comp_left A.to_lin, J.to_bilin_form.to_matrix_comp_right B.to_lin,
to_lin_to_matrix, to_lin_to_matrix, to_bilin_form_to_matrix, to_bilin_form_to_matrix],
refl,
end
lemma matrix.is_adjoint_pair_equiv [decidable_eq n] (P : matrix n n R) (h : is_unit P) :
(Pᵀ ⬝ J ⬝ P).is_adjoint_pair (Pᵀ ⬝ J ⬝ P) A B ↔ J.is_adjoint_pair J (P ⬝ A ⬝ P⁻¹) (P ⬝ B ⬝ P⁻¹) :=
have h' : is_unit P.det := P.is_unit_iff_is_unit_det.mp h,
begin
let u := P.nonsing_inv_unit h',
let v := Pᵀ.nonsing_inv_unit (P.is_unit_det_transpose h'),
let x := Aᵀ * Pᵀ * J,
let y := J * P * B,
suffices : x * ↑u = ↑v * y ↔ ↑v⁻¹ * x = y * ↑u⁻¹,
{ dunfold matrix.is_adjoint_pair,
repeat { rw matrix.transpose_mul, },
simp only [←matrix.mul_eq_mul, ←mul_assoc, P.transpose_nonsing_inv h'],
conv_lhs { to_rhs, rw [mul_assoc, mul_assoc], congr, skip, rw ←mul_assoc, },
conv_rhs { rw [mul_assoc, mul_assoc], conv { to_lhs, congr, skip, rw ←mul_assoc }, },
exact this, },
rw units.eq_mul_inv_iff_mul_eq, conv_rhs { rw mul_assoc, }, rw v.inv_mul_eq_iff_eq_mul,
end
variables [decidable_eq n]
/-- The submodule of pair-self-adjoint matrices with respect to bilinear forms corresponding to
given matrices `J`, `J₂`. -/
def pair_self_adjoint_matrices_submodule : submodule R (matrix n n R) :=
(bilin_form.is_pair_self_adjoint_submodule J.to_bilin_form J₂.to_bilin_form).map
(@linear_equiv_matrix' n n _ _ R _ _)
@[simp] lemma mem_pair_self_adjoint_matrices_submodule :
A ∈ (pair_self_adjoint_matrices_submodule J J₂) ↔ matrix.is_adjoint_pair J J₂ A A :=
begin
simp only [pair_self_adjoint_matrices_submodule,linear_equiv.coe_coe, linear_equiv_matrix'_apply,
submodule.mem_map, bilin_form.mem_is_pair_self_adjoint_submodule],
split,
{ rintros ⟨f, hf, hA⟩, have hf' : f = A.to_lin := by rw [←hA, to_matrix_to_lin], rw hf' at hf,
rw ←matrix_is_adjoint_pair_bilin_form, exact hf, },
{ intros h, refine ⟨A.to_lin, _, to_lin_to_matrix⟩,
exact (matrix_is_adjoint_pair_bilin_form _ _ _ _).mpr h, },
end
/-- The submodule of self-adjoint matrices with respect to the bilinear form corresponding to
the matrix `J`. -/
def self_adjoint_matrices_submodule : submodule R (matrix n n R) :=
pair_self_adjoint_matrices_submodule J J
@[simp] lemma mem_self_adjoint_matrices_submodule :
A ∈ self_adjoint_matrices_submodule J ↔ J.is_self_adjoint A :=
by { erw mem_pair_self_adjoint_matrices_submodule, refl, }
/-- The submodule of skew-adjoint matrices with respect to the bilinear form corresponding to
the matrix `J`. -/
def skew_adjoint_matrices_submodule : submodule R (matrix n n R) :=
pair_self_adjoint_matrices_submodule (-J) J
@[simp] lemma mem_skew_adjoint_matrices_submodule :
A ∈ skew_adjoint_matrices_submodule J ↔ J.is_skew_adjoint A :=
begin
erw mem_pair_self_adjoint_matrices_submodule,
simp [matrix.is_skew_adjoint, matrix.is_adjoint_pair],
end
end matrix_adjoints
|
cf444cee39306d6dbe4cb0baffecd773779fd66c | a721fe7446524f18ba361625fc01033d9c8b7a78 | /src/principia/topology/compactness.lean | 096e0c8ee93d92a7d72b4fd46ee5b354ed374bfb | [] | no_license | Sterrs/leaning | 8fd80d1f0a6117a220bb2e57ece639b9a63deadc | 3901cc953694b33adda86cb88ca30ba99594db31 | refs/heads/master | 1,627,023,822,744 | 1,616,515,221,000 | 1,616,515,221,000 | 245,512,190 | 2 | 0 | null | 1,616,429,050,000 | 1,583,527,118,000 | Lean | UTF-8 | Lean | false | false | 22,013 | lean | import .topological_space
import .continuity
namespace hidden
namespace topological_space
variables {α β γ: Type}
open classical
local attribute [instance] classical.prop_decidable
def is_open_cover (X: topological_space α) (𝒰: myset (myset α)): Prop :=
𝒰 ⊆ X.is_open ∧ ⋃₀ 𝒰 = myset.univ
def is_cover_l (X: topological_space α) (𝒰: mylist (myset α)): Prop :=
mylist.reduce_d myset.union ∅ 𝒰 = myset.univ
def is_compact (X: topological_space α): Prop :=
∀ 𝒰: myset (myset α), is_open_cover X 𝒰 →
∃ 𝒱: mylist (myset α), mylist.for_all 𝒰 𝒱 ∧ is_cover_l X 𝒱
theorem list_union (𝒰: mylist (myset α)):
mylist.reduce_d myset.union ∅ 𝒰 =
⋃₀ (λ x, 𝒰.contains x) :=
begin
apply myset.setext,
intro x,
split; assume hx, {
induction 𝒰 with U Us ih_U, {
exfalso, from hx,
}, {
cases hx with hx hx, {
existsi U,
split, {
left,
from rfl,
}, {
assumption,
},
}, {
cases ih_U hx with V hV,
cases hV with hV hxV,
existsi V,
split, {
right,
from hV,
}, {
assumption,
},
},
},
}, {
induction 𝒰 with U Us ih_U, {
cases hx with V hV,
cases hV with hV hxV,
exfalso, from hV,
}, {
cases hx with V hV,
cases hV with hV hxV,
cases hV with hV hV, {
left,
rw ←hV,
assumption,
}, {
right,
apply ih_U,
existsi V,
split, {
from hV,
}, {
assumption,
},
},
},
},
end
-- very suspicious
lemma list_intersection_iff_forall
(𝒱': mylist (myset α)) (y: α):
y ∈ mylist.reduce_d myset.intersection myset.univ 𝒱' ↔
mylist.for_all (λ V', y ∈ V') 𝒱' :=
begin
split, {
assume hyV',
induction 𝒱' with V' V's ih_V's, {
trivial,
}, {
split, {
from hyV'.left,
}, {
apply ih_V's,
from hyV'.right,
},
},
}, {
assume hyV',
induction 𝒱' with V' V's ih_V's, {
trivial,
}, {
split, {
from hyV'.left,
}, {
apply ih_V's,
from hyV'.right,
},
},
},
end
lemma list_union_iff_exists
(𝒱': mylist (myset α)) (y: α):
y ∈ mylist.reduce_d myset.union ∅ 𝒱' ↔
mylist.for_some (λ V', y ∈ V') 𝒱' :=
begin
split, {
assume hyV',
induction 𝒱' with V' V's ih_V's, {
exfalso, from hyV',
}, {
cases hyV' with hyV' hyV', {
left,
from hyV',
}, {
right,
apply ih_V's,
from hyV',
}
},
}, {
assume hyV',
induction 𝒱' with V' V's ih_V's, {
exfalso, from hyV',
}, {
cases hyV' with hyV' hyV', {
left,
from hyV',
}, {
right,
apply ih_V's,
from hyV',
}
},
},
end
-- not sure if this is optimal
-- but idk how else to construct things in the middle of a proof
private def is_raised_seq
(X: topological_space α) (Y: myset α)
(𝒰: myset (myset α)):
Π 𝒱: mylist (myset (subtype Y)),
Π (hWV: mylist.for_all ({W :
myset (subtype Y) | (X.subspace_topology Y).is_open W ∧
∃ (U : myset α), Y.subtype_restriction U = W ∧ U ∈ 𝒰}) 𝒱),
mylist (myset α) → Prop
| mylist.empty _ mylist.empty := true
| mylist.empty _ (V' :: V's) := false
| (V :: Vs) _ mylist.empty := false
| (V :: Vs) h (V' :: V's) :=
V' ∈ 𝒰 ∧
(subspace_topology X Y).is_open V ∧
myset.subtype_restriction Y V' = V ∧
is_raised_seq Vs h.right V's
private lemma raised_seq_exists
(X: topological_space α) (Y: myset α) (𝒰: myset (myset α))
(𝒱: mylist (myset (subtype Y)))
(hWV: mylist.for_all ({W :
myset (subtype Y) | (X.subspace_topology Y).is_open W ∧
∃ (U : myset α), Y.subtype_restriction U = W ∧ U ∈ 𝒰}) 𝒱)
(hVo: mylist.for_all (subspace_topology X Y).is_open 𝒱):
∃ 𝒱': mylist (myset α),
is_raised_seq X Y 𝒰 𝒱 hWV 𝒱' :=
begin
induction 𝒱 with V Vs ih_V, {
existsi mylist.empty,
trivial,
}, {
cases ih_V hWV.right hVo.right with V's hV's,
cases hWV.left with V'' hV'',
cases hV'' with V' hV',
existsi V' :: V's,
split, {
from hV'.right,
}, split, {
assumption,
}, split, {
from hV'.left,
}, {
assumption,
},
},
end
private lemma raised_seq_U
(X: topological_space α) (Y: myset α) (𝒰: myset (myset α))
(𝒱: mylist (myset (subtype Y)))
(hWV: mylist.for_all ({W :
myset (subtype Y) | (X.subspace_topology Y).is_open W ∧
∃ (U : myset α), Y.subtype_restriction U = W ∧ U ∈ 𝒰}) 𝒱)
(𝒱': mylist (myset α))
(hrV': is_raised_seq X Y 𝒰 𝒱 hWV 𝒱'):
mylist.for_all 𝒰 𝒱' :=
begin
induction 𝒱' with V' V's ih_V' generalizing 𝒱, {
trivial,
}, {
cases 𝒱 with V Vs, {
exfalso, from hrV',
}, {
split, {
from hrV'.left,
}, {
apply ih_V' _ hWV.right,
from hrV'.right.right.right,
},
},
},
end
private lemma raised_subset
(X: topological_space α) (Y: myset α) (𝒰: myset (myset α))
(𝒱: mylist (myset (subtype Y)))
(hWV: mylist.for_all ({W :
myset (subtype Y) | (X.subspace_topology Y).is_open W ∧
∃ (U : myset α), Y.subtype_restriction U = W ∧ U ∈ 𝒰}) 𝒱)
(𝒱': mylist (myset α))
(hrV': is_raised_seq X Y 𝒰 𝒱 hWV 𝒱')
(x: α) (hYx: Y x)
(hxV: (⟨x, hYx⟩: subtype Y) ∈ mylist.reduce_d myset.union ∅ 𝒱):
x ∈ mylist.reduce_d myset.union ∅ 𝒱' :=
begin
rw list_union,
rw list_union at hxV,
cases hxV with V hV,
cases hV with hV hxV,
have hWV' := hWV,
rw mylist.for_all_iff_forall at hWV,
cases (hWV V hV).right with V' hV',
sorry,
end
theorem compact_subspace_cover
(X: topological_space α) (Y: myset α)
(hYcpct: is_compact (subspace_topology X Y)):
∀ 𝒰: myset (myset α),
𝒰 ⊆ X.is_open →
Y ⊆ ⋃₀ 𝒰 →
∃ 𝒱: mylist (myset α),
mylist.for_all 𝒰 𝒱 ∧
Y ⊆ mylist.reduce_d myset.union ∅ 𝒱 :=
begin
intro 𝒰,
assume hUo,
assume hUYcov,
let 𝒲 :=
{W: myset (subtype Y) |
(subspace_topology X Y).is_open W ∧
∃ U: myset α,
Y.subtype_restriction U = W ∧
U ∈ 𝒰},
have step1 := hYcpct 𝒲,
have hWYcov: (X.subspace_topology Y).is_open_cover 𝒲, {
split, {
intro W,
assume hWW,
from hWW.left,
}, {
apply myset.setext,
intro x,
split; assume hx, {
trivial,
}, {
cases hUYcov x x.property with U hU,
cases hU with hU hxU,
existsi Y.subtype_restriction U,
split, {
split, {
existsi U,
split, {
from hUo U hU,
}, {
refl,
},
}, {
existsi U,
split, {
refl,
}, {
assumption,
},
},
}, {
from hxU,
},
},
},
},
have step2 := step1 hWYcov,
cases step2 with 𝒱 hV,
have step4: mylist.for_all (X.subspace_topology Y).is_open 𝒱, {
cases hV with hV garbage,
clear garbage,
induction 𝒱 with V Vs ih_V, {
trivial,
}, {
split, {
from hV.left.left,
}, {
apply ih_V, {
from hV.right,
},
},
},
},
have step3 := raised_seq_exists X Y 𝒰 𝒱 hV.left,
have step5 := step3 step4,
cases step5 with 𝒱' hV',
existsi 𝒱',
split, {
apply raised_seq_U X Y 𝒰 𝒱 hV.left,
from hV',
}, {
intro x,
assume hYx,
have hxV: (⟨x, hYx⟩: subtype Y) ∈ (mylist.reduce_d myset.union ∅ 𝒱), {
have := hV.right,
unfold is_cover_l at this,
rw this,
trivial,
},
from raised_subset X Y 𝒰 𝒱 hV.left 𝒱' hV' x hYx hxV,
},
end
-- could do with a bit of splitting up imho
theorem closed_in_compact
(X: topological_space α) (U: myset α)
(hXcpct: is_compact X) (hUcl: X.is_closed U):
is_compact (subspace_topology X U) :=
begin
intro 𝒰,
assume hUcov,
have step1 :=
hXcpct
((myset.singleton U.compl) ∪
{V | X.is_open V ∧
𝒰 (U.subtype_restriction V)}),
have hcovX:
X.is_open_cover
((myset.singleton U.compl) ∪
{V | X.is_open V ∧
𝒰 (U.subtype_restriction V)}), {
split, {
intro S,
assume hS,
cases hS with hS hS, {
rw myset.singleton_eq _ _ hS,
from hUcl,
}, {
from hS.left,
},
}, {
apply myset.setext,
intro x,
split; assume hx, {
trivial,
}, {
by_cases hxU: x ∈ U, {
have: (⟨x, hxU⟩: subtype U) ∈ ⋃₀ 𝒰, {
rw hUcov.right,
trivial,
},
cases this with V hV,
cases hV with hV hxV,
cases hUcov.left V hV with V' hV',
existsi V',
split, {
right,
split, {
from hV'.left,
}, {
rw hV'.right at hV,
from hV,
},
}, {
rw hV'.right at hxV,
from hxV,
},
}, {
existsi U.compl,
split, {
left,
from rfl,
}, {
from hxU,
},
},
},
},
},
have step2 := step1 hcovX,
cases step2 with 𝒱 hV,
existsi mylist.map
(myset.subtype_restriction U)
(mylist.filter (≠ U.compl) 𝒱),
split, {
cases hV with hV disaster,
clear disaster,
induction 𝒱 with V Vs ih_V, {
trivial,
}, {
by_cases hVU: V = U.compl, {
unfold mylist.filter,
have: ¬(V ≠ U.compl), {
assume h,
contradiction,
},
rw if_neg this,
apply ih_V,
from hV.right,
}, {
unfold mylist.filter,
rw if_pos hVU,
split, {
cases hV.left with hVl hVl, {
contradiction,
}, {
from hVl.right,
},
}, {
apply ih_V,
from hV.right,
},
},
},
}, {
cases hV with disaster hV,
clear disaster,
unfold is_cover_l,
rw list_union,
unfold is_cover_l at hV,
rw list_union at hV,
apply myset.setext,
intro x,
split; assume hx, {
trivial,
}, {
have: x.val ∈ (myset.univ: myset α), {
trivial,
},
rw ←hV at this,
cases this with V hxV,
cases hxV with hVV hxvV,
existsi (myset.subtype_restriction U V),
split, {
apply mylist.contains_map,
rw mylist.contains_filter,
split, {
from hVV,
}, {
assume hVUc,
rw hVUc at hxvV,
apply hxvV,
from x.property,
},
}, {
from hxvV,
},
},
},
end
private def is_corresponding_subcov
(X: topological_space α) (x: α)
(U: myset α):
Π (𝒱: mylist (myset α)),
mylist (myset α) → Prop
| mylist.empty mylist.empty := true
| (V :: Vs) mylist.empty := false
| mylist.empty (V' :: V's) := false
| (V :: Vs) (V' :: V's) :=
is_corresponding_subcov Vs V's ∧
∃ (y : α),
y ∈ U ∧ X.is_open V ∧ X.is_open V' ∧ y ∈ V ∧ x ∈ V' ∧ V ∩ V' = ∅
private lemma corresponding_subcov_forall
(X: topological_space α) (x: α)
(U: myset α)
(𝒱: mylist (myset α))
(𝒱': mylist (myset α))
(hcor: is_corresponding_subcov X x U 𝒱 𝒱'):
mylist.for_all
(λ V', ∃ (y : α),
y ∈ U ∧ X.is_open V' ∧ x ∈ V')
𝒱' :=
begin
revert 𝒱,
induction 𝒱' with V' V's ih_V's, {
intros,
trivial,
}, {
intros,
cases 𝒱 with V Vs, {
exfalso,
from hcor,
}, {
split, {
cases hcor.right with y hy,
existsi y,
repeat {split, cc},
cc,
}, {
apply ih_V's Vs hcor.left,
},
},
},
end
private lemma corresponding_subcov_forall2
(X: topological_space α) (x: α)
(U: myset α)
(𝒱: mylist (myset α))
(𝒱': mylist (myset α))
(hcor: is_corresponding_subcov X x U 𝒱 𝒱'):
mylist.for_all
(λ V', ∃ (y : α) (V: myset α), mylist.contains V 𝒱 ∧
y ∈ U ∧ X.is_open V ∧ X.is_open V' ∧ y ∈ V ∧ x ∈ V' ∧ V ∩ V' = ∅)
𝒱' :=
begin
revert 𝒱,
induction 𝒱' with V' V's ih_V's, {
intros,
trivial,
}, {
intros,
cases 𝒱 with V Vs, {
exfalso,
from hcor,
}, {
split, {
cases hcor.right with y hy,
existsi y,
existsi V,
repeat {split, cc},
split, left,
from rfl,
from hy,
}, {
have := ih_V's Vs hcor.left,
apply (mylist.for_all_iff_forall _ _).mpr,
rw mylist.for_all_iff_forall at this,
intro V'',
assume hV''Vs,
cases this V'' hV''Vs with y hy,
cases hy with W hW,
existsi y,
existsi W,
split, right,
from hW.left,
from hW.right,
-- apply ih_V's Vs hcor.left,
},
},
},
end
private lemma corresponding_subcov_forall2_symm
(X: topological_space α) (x: α)
(U: myset α)
(𝒱: mylist (myset α))
(𝒱': mylist (myset α))
(hcor: is_corresponding_subcov X x U 𝒱 𝒱'):
mylist.for_all
(λ V, ∃ (y : α) (V': myset α), mylist.contains V' 𝒱' ∧
y ∈ U ∧ X.is_open V ∧ X.is_open V' ∧ y ∈ V ∧ x ∈ V' ∧ V ∩ V' = ∅)
𝒱 :=
begin
revert 𝒱',
induction 𝒱 with V Vs ih_Vs, {
intros,
trivial,
}, {
intros,
cases 𝒱' with V' V's, {
exfalso,
from hcor,
}, {
split, {
cases hcor.right with y hy,
existsi y,
existsi V',
repeat {split, cc},
split, left,
from rfl,
from hy,
}, {
have := ih_Vs V's hcor.left,
apply (mylist.for_all_iff_forall _ _).mpr,
rw mylist.for_all_iff_forall at this,
intro V'',
assume hV''Vs,
cases this V'' hV''Vs with y hy,
cases hy with W hW,
existsi y,
existsi W,
split, right,
from hW.left,
from hW.right,
-- apply ih_V's Vs hcor.left,
},
},
},
end
private lemma exists_corresponding_subcov
(X: topological_space α) (x: α)
(U: myset α)
(𝒱: mylist (myset α))
(hVU: mylist.for_all
({V :
myset α | ∃ (y : α) (W : myset α),
y ∈ U ∧ X.is_open V ∧ X.is_open W ∧ y ∈ V ∧ x ∈ W ∧ V ∩ W = ∅}) 𝒱):
∃ 𝒱': mylist (myset α),
is_corresponding_subcov X x U 𝒱 𝒱' :=
begin
induction 𝒱 with V Vs ih_Vs, {
existsi mylist.empty,
trivial,
}, {
cases ih_Vs hVU.right with V's hV's,
cases hVU.left with y hV',
cases hV' with V' hV',
existsi V' :: V's,
split, {
from hV's,
}, {
existsi y,
from hV',
},
},
end
theorem compact_in_hausdorff
(X: topological_space α) (U: myset α)
(hUcpct: is_compact (subspace_topology X U))
(h_ausdorff: is_hausdorff X):
X.is_closed U :=
begin
unfold is_closed,
rw open_iff_neighbourhood_forall,
intro x,
assume hxUc,
let 𝒰 :=
{V: myset α | ∃ (y: α) (W: myset α),
y ∈ U ∧
X.is_open V ∧ X.is_open W ∧ y ∈ V ∧ x ∈ W ∧ V ∩ W = ∅},
have step1 := compact_subspace_cover X U hUcpct 𝒰,
have step2: 𝒰 ⊆ X.is_open, {
intro V,
assume hVU,
cases hVU with y hVU,
cases hVU with W hVU,
from hVU.right.left,
},
have step3: U ⊆ ⋃₀ 𝒰, {
intro y,
assume hUy,
cases h_ausdorff x y
begin
assume hxy,
rw hxy at hxUc,
contradiction,
end with V1 hVy,
cases hVy with V2 hVy,
existsi V2,
cases hVy,
split, {
existsi y,
existsi V1,
split, assumption,
rw myset.intersection_comm,
repeat {split},
all_goals {assumption},
}, {
assumption,
},
},
cases step1 step2 step3 with 𝒱 hV,
cases exists_corresponding_subcov X x U 𝒱 hV.left with 𝒱' hV',
have hV'fa := corresponding_subcov_forall X x U 𝒱 𝒱' hV',
existsi mylist.reduce_d myset.intersection myset.univ 𝒱',
split, {
apply finite_open_intersection_open,
rw mylist.for_all_iff_forall,
intro V',
assume hV'inV,
rw mylist.for_all_iff_forall at hV,
rw mylist.for_all_iff_forall at hV'fa,
cases hV'fa V' hV'inV with _ h,
from h.right.left,
}, {
cases hV with hV garbage,
clear garbage,
revert 𝒱,
induction 𝒱' with V' V's ih_V's, {
intros,
trivial,
}, {
intros,
split, {
cases hV'fa.left with _ h,
from h.right.right,
}, {
cases 𝒱 with V Vs, {
exfalso,
from hV',
}, {
apply ih_V's _ Vs, {
from hV'.left,
}, {
from hV.right,
}, {
from hV'fa.right,
},
},
},
},
}, {
intro y,
assume hV'y,
assume hUy,
have hV'fa2 := corresponding_subcov_forall2 X x U 𝒱 𝒱' hV',
have := (list_union_iff_exists 𝒱 y).mp (hV.right y hUy),
rw mylist.for_some_iff_exists at this,
cases this with Z hZ,
cases hZ with hZ hyZ,
unfold mylist.contains at hZ,
rw mylist.for_some_iff_exists at hZ,
cases hZ with Z' hZ,
cases hV with hVsubcovU hUsubV,
rw mylist.for_all_iff_forall at hVsubcovU,
have := hVsubcovU Z' hZ.left,
cases this with z hz,
cases hz with W hW,
have hV'fa2s := corresponding_subcov_forall2_symm X x U 𝒱 𝒱' hV',
rw mylist.for_all_iff_forall at hV'fa2s,
cases hV'fa2s Z' hZ.left with z' hz',
cases hz' with V' hzV',
have := (list_intersection_iff_forall _ _).mp hV'y,
rw mylist.for_all_iff_forall at this,
have hyV' := this V' hzV'.left,
suffices hhhhh: y ∈ Z' ∩ V', {
rw hzV'.right.right.right.right.right.right at hhhhh,
from hhhhh,
}, {
split, {
rw ←hZ.right,
assumption,
}, {
assumption,
},
},
},
end
theorem surjective_image_compact
(X: topological_space α) (Y: topological_space β)
(hXcpct: is_compact X)
(f: α → β) (hcf: is_continuous X Y f) (hsurj: function.surjective f):
is_compact Y :=
begin
intro 𝒰,
assume hUcov,
have step1 := hXcpct (myset.image (myset.inverse_image f) 𝒰),
have step2: X.is_open_cover (myset.image (myset.inverse_image f) 𝒰), {
split, {
intro V,
assume hV,
cases hV with V' hV',
rw ←hV'.right,
apply hcf,
apply hUcov.left,
from hV'.left,
}, {
apply myset.setext,
intro x,
split; assume hx, {
trivial,
}, {
have: f x ∈ ⋃₀ 𝒰, {
rw hUcov.right,
trivial,
},
cases this with U hU,
cases hU with hU hfxU,
existsi myset.inverse_image f U,
split, {
existsi U,
split, {
from hU,
}, {
refl,
},
}, {
from hfxU,
},
},
},
},
have step3 := step1 step2,
cases step3 with 𝒱' hV',
sorry,
end
theorem image_compact
(X: topological_space α) (Y: topological_space β)
(hXcpct: is_compact X)
(f: α → β) (hcf: is_continuous X Y f):
is_compact (Y.subspace_topology (myset.imageu f)) :=
begin
apply surjective_image_compact X _ hXcpct (myset.function_restrict_to_image f), {
apply continuous_to_image,
from hcf,
}, {
intro y,
cases y.property with x hx,
existsi x,
apply subtype.eq,
from hx,
},
end
-- could do with some theorems about preimages and images
-- of inverses
theorem topological_inverse_function_theorem
(X: topological_space α) (Y: topological_space β)
(hXcpct: is_compact X) (h_ausdorff: is_hausdorff Y)
(f: α → β) (g: β → α) (hcf: is_continuous X Y f)
(right_inv: f ∘ g = id)
(left_inv: g ∘ f = id):
is_continuous Y X g :=
begin
rw continuous_iff_closed_preimage,
intro U,
assume hUo,
have: myset.inverse_image g U = myset.image f U, {
apply myset.setext,
intro x,
split; assume hx, {
existsi g x,
split, {
from hx,
}, {
change (f ∘ g) x = x,
rw right_inv,
refl,
},
}, {
cases hx with y hy,
have: g x = y, {
rw ←hy.right,
change (g ∘ f) y = y,
rw left_inv,
refl,
},
rw ←this at hy,
from hy.left,
},
},
rw this, clear this,
apply compact_in_hausdorff, {
apply surjective_image_compact
(X.subspace_topology U)
(Y.subspace_topology (myset.image f U)) _
(myset.function_restrict_to_set_image f U), {
rw myset.restrict_to_set_image_composition,
apply composition_continuous
(X.subspace_topology U)
(Y.subspace_topology (myset.imageu (λ x: subtype U, f x.val)))
(Y.subspace_topology (myset.image f U)), {
apply continuous_to_image,
apply composition_continuous
_ _ _ _ _ (inclusion_continuous _ _),
from hcf,
}, {
intro U,
assume hUo,
cases hUo with V' hV',
existsi V',
split, {
from hV'.left,
}, {
rw hV'.right,
refl, -- thank the lord
},
},
}, {
intro y,
cases y.property with y' hy',
existsi (⟨y', hy'.left⟩: subtype U),
apply subtype.eq,
-- rw won't play ball >:(
transitivity (f y'), {
refl,
}, {
from hy'.right,
},
}, {
apply closed_in_compact, {
from hXcpct,
}, {
from hUo,
},
},
}, {
from h_ausdorff,
},
end
end topological_space
end hidden
|
a4bb037926925e9bae70cda94215843eb9797733 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/ring_theory/artinian.lean | 75cc0b28de795c625f8fa5cf17c849c5fa72c387 | [
"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 | 17,687 | lean | /-
Copyright (c) 2021 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes
-/
import linear_algebra.basic
import linear_algebra.prod
import linear_algebra.pi
import data.set_like.fintype
import linear_algebra.linear_independent
import tactic.linarith
import algebra.algebra.basic
import ring_theory.noetherian
import ring_theory.jacobson_ideal
import ring_theory.nilpotent
import ring_theory.nakayama
/-!
# Artinian rings and modules
A module satisfying these equivalent conditions is said to be an *Artinian* R-module
if every decreasing chain of submodules is eventually constant, or equivalently,
if the relation `<` on submodules is well founded.
A ring is an *Artinian ring* if it is Artinian as a module over itself.
(Note that we do not assume yet that our rings are commutative,
so perhaps this should be called "left Artinian".
To avoid cumbersome names once we specialize to the commutative case,
we don't make this explicit in the declaration names.)
## Main definitions
Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`.
* `is_artinian R M` is the proposition that `M` is a Artinian `R`-module. It is a class,
implemented as the predicate that the `<` relation on submodules is well founded.
## References
* [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald]
* [samuel]
## Tags
Artinian, artinian, Artinian ring, Artinian module, artinian ring, artinian module
-/
open set
open_locale big_operators pointwise
/--
`is_artinian R M` is the proposition that `M` is an Artinian `R`-module,
implemented as the well-foundedness of submodule inclusion.
-/
class is_artinian (R M) [semiring R] [add_comm_monoid M] [module R M] : Prop :=
(well_founded_submodule_lt [] : well_founded ((<) : submodule R M → submodule R M → Prop))
section
variables {R : Type*} {M : Type*} {P : Type*} {N : Type*}
variables [ring R] [add_comm_group M] [add_comm_group P] [add_comm_group N]
variables [module R M] [module R P] [module R N]
open is_artinian
include R
theorem is_artinian_of_injective (f : M →ₗ[R] P) (h : function.injective f)
[is_artinian R P] : is_artinian R M :=
⟨subrelation.wf
(λ A B hAB, show A.map f < B.map f,
from submodule.map_strict_mono_of_injective h hAB)
(inv_image.wf (submodule.map f) (is_artinian.well_founded_submodule_lt R P))⟩
instance is_artinian_submodule' [is_artinian R M] (N : submodule R M) : is_artinian R N :=
is_artinian_of_injective N.subtype subtype.val_injective
lemma is_artinian_of_le {s t : submodule R M} [ht : is_artinian R t]
(h : s ≤ t) : is_artinian R s :=
is_artinian_of_injective (submodule.of_le h) (submodule.of_le_injective h)
variable (M)
theorem is_artinian_of_surjective (f : M →ₗ[R] P) (hf : function.surjective f)
[is_artinian R M] : is_artinian R P :=
⟨subrelation.wf
(λ A B hAB, show A.comap f < B.comap f,
from submodule.comap_strict_mono_of_surjective hf hAB)
(inv_image.wf (submodule.comap f) (is_artinian.well_founded_submodule_lt _ _))⟩
variable {M}
theorem is_artinian_of_linear_equiv (f : M ≃ₗ[R] P)
[is_artinian R M] : is_artinian R P :=
is_artinian_of_surjective _ f.to_linear_map f.to_equiv.surjective
theorem is_artinian_of_range_eq_ker
[is_artinian R M] [is_artinian R P]
(f : M →ₗ[R] N) (g : N →ₗ[R] P)
(hf : function.injective f)
(hg : function.surjective g)
(h : f.range = g.ker) :
is_artinian R N :=
⟨well_founded_lt_exact_sequence
(is_artinian.well_founded_submodule_lt _ _)
(is_artinian.well_founded_submodule_lt _ _)
f.range
(submodule.map f)
(submodule.comap f)
(submodule.comap g)
(submodule.map g)
(submodule.gci_map_comap hf)
(submodule.gi_map_comap hg)
(by simp [submodule.map_comap_eq, inf_comm])
(by simp [submodule.comap_map_eq, h])⟩
instance is_artinian_prod [is_artinian R M]
[is_artinian R P] : is_artinian R (M × P) :=
is_artinian_of_range_eq_ker
(linear_map.inl R M P)
(linear_map.snd R M P)
linear_map.inl_injective
linear_map.snd_surjective
(linear_map.range_inl R M P)
@[instance, priority 100]
lemma is_artinian_of_fintype [fintype M] : is_artinian R M :=
⟨fintype.well_founded_of_trans_of_irrefl _⟩
local attribute [elab_as_eliminator] fintype.induction_empty_option
instance is_artinian_pi {R ι : Type*} [fintype ι] : Π {M : ι → Type*} [ring R]
[Π i, add_comm_group (M i)], by exactI Π [Π i, module R (M i)],
by exactI Π [∀ i, is_artinian R (M i)], is_artinian R (Π i, M i) :=
fintype.induction_empty_option
(begin
introsI α β e hα M _ _ _ _,
exact is_artinian_of_linear_equiv
(linear_equiv.Pi_congr_left R M e)
end)
(by { introsI M _ _ _ _, apply_instance })
(begin
introsI α _ ih M _ _ _ _,
exact is_artinian_of_linear_equiv
(linear_equiv.pi_option_equiv_prod R).symm,
end)
ι
/-- A version of `is_artinian_pi` for non-dependent functions. We need this instance because
sometimes Lean fails to apply the dependent version in non-dependent settings (e.g., it fails to
prove that `ι → ℝ` is finite dimensional over `ℝ`). -/
instance is_artinian_pi' {R ι M : Type*} [ring R] [add_comm_group M] [module R M] [fintype ι]
[is_artinian R M] : is_artinian R (ι → M) :=
is_artinian_pi
end
open is_artinian submodule function
section
variables {R M : Type*} [ring R] [add_comm_group M] [module R M]
theorem is_artinian_iff_well_founded :
is_artinian R M ↔ well_founded ((<) : submodule R M → submodule R M → Prop) :=
⟨λ h, h.1, is_artinian.mk⟩
variables {R M}
lemma is_artinian.finite_of_linear_independent [nontrivial R] [is_artinian R M]
{s : set M} (hs : linear_independent R (coe : s → M)) : s.finite :=
begin
refine classical.by_contradiction (λ hf, (rel_embedding.well_founded_iff_no_descending_seq.1
(well_founded_submodule_lt R M)).elim' _),
have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩,
have : ∀ n, (coe ∘ f) '' {m | n ≤ m} ⊆ s,
{ rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 },
have : ∀ a b : ℕ, a ≤ b ↔
span R ((coe ∘ f) '' {m | b ≤ m}) ≤ span R ((coe ∘ f) '' {m | a ≤ m}),
{ assume a b,
rw [span_le_span_iff hs (this b) (this a),
set.image_subset_image_iff (subtype.coe_injective.comp f.injective),
set.subset_def],
simp only [set.mem_set_of_eq],
exact ⟨λ hab x, le_trans hab, λ h, (h _ (le_refl _))⟩ },
exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | n ≤ m}),
λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩,
begin
intros a b,
conv_rhs { rw [gt, lt_iff_le_not_le, this, this, ← lt_iff_le_not_le] },
simp
end⟩
end
/-- A module is Artinian iff every nonempty set of submodules has a minimal submodule among them.
-/
theorem set_has_minimal_iff_artinian :
(∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, I ≤ M' → I = M') ↔
is_artinian R M :=
by rw [is_artinian_iff_well_founded, well_founded.well_founded_iff_has_min']
theorem is_artinian.set_has_minimal [is_artinian R M] (a : set $ submodule R M) (ha : a.nonempty) :
∃ M' ∈ a, ∀ I ∈ a, I ≤ M' → I = M' :=
set_has_minimal_iff_artinian.mpr ‹_› a ha
/-- A module is Artinian iff every decreasing chain of submodules stabilizes. -/
theorem monotone_stabilizes_iff_artinian :
(∀ (f : ℕ →ₘ order_dual (submodule R M)), ∃ n, ∀ m, n ≤ m → f n = f m)
↔ is_artinian R M :=
by rw [is_artinian_iff_well_founded];
exact (well_founded.monotone_chain_condition (order_dual (submodule R M))).symm
theorem is_artinian.monotone_stabilizes [is_artinian R M] (f : ℕ →ₘ order_dual (submodule R M)) :
∃ n, ∀ m, n ≤ m → f n = f m :=
monotone_stabilizes_iff_artinian.mpr ‹_› f
/-- If `∀ I > J, P I` implies `P J`, then `P` holds for all submodules. -/
lemma is_artinian.induction [is_artinian R M] {P : submodule R M → Prop}
(hgt : ∀ I, (∀ J < I, P J) → P I) (I : submodule R M) : P I :=
well_founded.recursion (well_founded_submodule_lt R M) I hgt
/--
For any endomorphism of a Artinian module, there is some nontrivial iterate
with disjoint kernel and range.
-/
theorem is_artinian.exists_endomorphism_iterate_ker_sup_range_eq_top
[I : is_artinian R M] (f : M →ₗ[R] M) : ∃ n : ℕ, n ≠ 0 ∧ (f ^ n).ker ⊔ (f ^ n).range = ⊤ :=
begin
obtain ⟨n, w⟩ := monotone_stabilizes_iff_artinian.mpr I
(f.iterate_range.comp ⟨λ n, n+1, λ n m w, by linarith⟩),
specialize w ((n + 1) + n) (by linarith),
dsimp at w,
refine ⟨n + 1, nat.succ_ne_zero _, _⟩,
simp_rw [eq_top_iff', mem_sup],
intro x,
have : (f^(n + 1)) x ∈ (f ^ ((n + 1) + n + 1)).range,
{ rw ← w, exact mem_range_self _ },
rcases this with ⟨y, hy⟩,
use x - (f ^ (n+1)) y,
split,
{ rw [linear_map.mem_ker, linear_map.map_sub, ← hy, sub_eq_zero, pow_add],
simp [iterate_add_apply], },
{ use (f^ (n+1)) y,
simp }
end
/-- Any injective endomorphism of an Artinian module is surjective. -/
theorem is_artinian.surjective_of_injective_endomorphism [is_artinian R M]
(f : M →ₗ[R] M) (s : injective f) : surjective f :=
begin
obtain ⟨n, ne, w⟩ := is_artinian.exists_endomorphism_iterate_ker_sup_range_eq_top f,
rw [linear_map.ker_eq_bot.mpr (linear_map.iterate_injective s n), bot_sup_eq,
linear_map.range_eq_top] at w,
exact linear_map.surjective_of_iterate_surjective ne w,
end
/-- Any injective endomorphism of an Artinian module is bijective. -/
theorem is_artinian.bijective_of_injective_endomorphism [is_artinian R M]
(f : M →ₗ[R] M) (s : injective f) : bijective f :=
⟨s, is_artinian.surjective_of_injective_endomorphism f s⟩
/--
A sequence `f` of submodules of a artinian module,
with the supremum `f (n+1)` and the infinum of `f 0`, ..., `f n` being ⊤,
is eventually ⊤.
-/
lemma is_artinian.disjoint_partial_infs_eventually_top [I : is_artinian R M]
(f : ℕ → submodule R M) (h : ∀ n, disjoint
(partial_sups (order_dual.to_dual ∘ f) n) (order_dual.to_dual (f (n+1)))) :
∃ n : ℕ, ∀ m, n ≤ m → f m = ⊤ :=
begin
-- A little off-by-one cleanup first:
suffices t : ∃ n : ℕ, ∀ m, n ≤ m → order_dual.to_dual f (m+1) = ⊤,
{ obtain ⟨n, w⟩ := t,
use n+1,
rintros (_|m) p,
{ cases p, },
{ apply w,
exact nat.succ_le_succ_iff.mp p }, },
obtain ⟨n, w⟩ := monotone_stabilizes_iff_artinian.mpr I (partial_sups (order_dual.to_dual ∘ f)),
exact ⟨n, (λ m p, eq_bot_of_disjoint_absorbs (h m)
((eq.symm (w (m + 1) (le_add_right p))).trans (w m p)))⟩
end
universe w
variables {N : Type w} [add_comm_group N] [module R N]
-- TODO: Prove this for artinian modules
-- /--
-- If `M ⊕ N` embeds into `M`, for `M` noetherian over `R`, then `N` is trivial.
-- -/
-- noncomputable def is_noetherian.equiv_punit_of_prod_injective [is_noetherian R M]
-- (f : M × N →ₗ[R] M) (i : injective f) : N ≃ₗ[R] punit.{w+1} :=
-- begin
-- apply nonempty.some,
-- obtain ⟨n, w⟩ := is_noetherian.disjoint_partial_sups_eventually_bot (f.tailing i)
-- (f.tailings_disjoint_tailing i),
-- specialize w n (le_refl n),
-- apply nonempty.intro,
-- refine (f.tailing_linear_equiv i n).symm.trans _,
-- rw w,
-- exact submodule.bot_equiv_punit,
-- end
end
/--
A ring is Artinian if it is Artinian as a module over itself.
-/
class is_artinian_ring (R) [ring R] extends is_artinian R R : Prop
theorem is_artinian_ring_iff {R} [ring R] : is_artinian_ring R ↔ is_artinian R R :=
⟨λ h, h.1, @is_artinian_ring.mk _ _⟩
theorem ring.is_artinian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_artinian_ring R :=
by haveI := subsingleton_of_zero_eq_one h01;
haveI := fintype.of_subsingleton (0:R); split;
apply_instance
theorem is_artinian_of_submodule_of_artinian (R M) [ring R] [add_comm_group M] [module R M]
(N : submodule R M) (h : is_artinian R M) : is_artinian R N :=
by apply_instance
theorem is_artinian_of_quotient_of_artinian (R) [ring R] (M) [add_comm_group M] [module R M]
(N : submodule R M) (h : is_artinian R M) : is_artinian R N.quotient :=
is_artinian_of_surjective M (submodule.mkq N) (submodule.quotient.mk_surjective N)
/-- If `M / S / R` is a scalar tower, and `M / R` is Artinian, then `M / S` is
also Artinian. -/
theorem is_artinian_of_tower (R) {S M} [comm_ring R] [ring S]
[add_comm_group M] [algebra R S] [module S M] [module R M] [is_scalar_tower R S M]
(h : is_artinian R M) : is_artinian S M :=
begin
rw is_artinian_iff_well_founded at h ⊢,
refine (submodule.restrict_scalars_embedding R S M).well_founded h
end
theorem is_artinian_of_fg_of_artinian {R M} [ring R] [add_comm_group M] [module R M]
(N : submodule R M) [is_artinian_ring R] (hN : N.fg) : is_artinian R N :=
let ⟨s, hs⟩ := hN in
begin
haveI := classical.dec_eq M,
haveI := classical.dec_eq R,
letI : is_artinian R R := by apply_instance,
have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx,
refine @@is_artinian_of_surjective ((↑s : set M) → R) _ _ _ (pi.module _ _ _)
_ _ _ is_artinian_pi,
{ fapply linear_map.mk,
{ exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ },
{ intros f g, apply subtype.eq,
change ∑ i in s.attach, (f i + g i) • _ = _,
simp only [add_smul, finset.sum_add_distrib], refl },
{ intros c f, apply subtype.eq,
change ∑ i in s.attach, (c • f i) • _ = _,
simp only [smul_eq_mul, mul_smul],
exact finset.smul_sum.symm } },
rintro ⟨n, hn⟩, change n ∈ N at hn,
rw [← hs, ← set.image_id ↑s, finsupp.mem_span_image_iff_total] at hn,
rcases hn with ⟨l, hl1, hl2⟩,
refine ⟨λ x, l x, subtype.ext _⟩,
change ∑ i in s.attach, l i • (i : M) = n,
rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2,
finsupp.total_apply, finsupp.sum, eq_comm],
refine finset.sum_subset hl1 (λ x _ hx, _),
rw [finsupp.not_mem_support_iff.1 hx, zero_smul]
end
lemma is_artinian_of_fg_of_artinian' {R M} [ring R] [add_comm_group M] [module R M]
[is_artinian_ring R] (h : (⊤ : submodule R M).fg) : is_artinian R M :=
have is_artinian R (⊤ : submodule R M), from is_artinian_of_fg_of_artinian _ h,
by exactI is_artinian_of_linear_equiv (linear_equiv.of_top (⊤ : submodule R M) rfl)
/-- In a module over a artinian ring, the submodule generated by finitely many vectors is
artinian. -/
theorem is_artinian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M]
[is_artinian_ring R] {A : set M} (hA : finite A) : is_artinian R (submodule.span R A) :=
is_artinian_of_fg_of_artinian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩)
theorem is_artinian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S]
(f : R →+* S) (hf : function.surjective f)
[H : is_artinian_ring R] : is_artinian_ring S :=
begin
rw [is_artinian_ring_iff, is_artinian_iff_well_founded] at H ⊢,
exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf) H,
end
instance is_artinian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S)
[is_artinian_ring R] : is_artinian_ring f.range :=
is_artinian_ring_of_surjective R f.range f.range_restrict
f.range_restrict_surjective
theorem is_artinian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S]
(f : R ≃+* S) [is_artinian_ring R] : is_artinian_ring S :=
is_artinian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective
namespace is_artinian_ring
open is_artinian
variables {R : Type*} [comm_ring R] [is_artinian_ring R]
lemma is_nilpotent_jacobson_bot : is_nilpotent (ideal.jacobson (⊥ : ideal R)) :=
begin
let Jac := ideal.jacobson (⊥ : ideal R),
let f : ℕ →ₘ order_dual (ideal R) := ⟨λ n, Jac ^ n, λ _ _ h, ideal.pow_le_pow h⟩,
obtain ⟨n, hn⟩ : ∃ n, ∀ m, n ≤ m → Jac ^ n = Jac ^ m := is_artinian.monotone_stabilizes f,
refine ⟨n, _⟩,
let J : ideal R := annihilator (Jac ^ n),
suffices : J = ⊤,
{ have hJ : J • Jac ^ n = ⊥ := annihilator_smul (Jac ^ n),
simpa only [this, top_smul, ideal.zero_eq_bot] using hJ },
by_contradiction hJ, change J ≠ ⊤ at hJ,
rcases is_artinian.set_has_minimal {J' : ideal R | J < J'} ⟨⊤, hJ.lt_top⟩
with ⟨J', hJJ' : J < J', hJ' : ∀ I, J < I → I ≤ J' → I = J'⟩,
rcases set_like.exists_of_lt hJJ' with ⟨x, hxJ', hxJ⟩,
obtain rfl : J ⊔ ideal.span {x} = J',
{ refine hJ' (J ⊔ ideal.span {x}) _ _,
{ rw set_like.lt_iff_le_and_exists,
exact ⟨le_sup_left, ⟨x, mem_sup_right (mem_span_singleton_self x), hxJ⟩⟩ },
{ exact (sup_le hJJ'.le (span_le.2 (singleton_subset_iff.2 hxJ'))) } },
have : J ⊔ Jac • ideal.span {x} ≤ J ⊔ ideal.span {x},
from sup_le_sup_left (smul_le.2 (λ _ _ _, submodule.smul_mem _ _)) _,
have : Jac * ideal.span {x} ≤ J, --Need version 4 of Nakayamas lemma on Stacks
{ classical, by_contradiction H,
refine H (smul_sup_le_of_le_smul_of_le_jacobson_bot
(fg_span_singleton _) le_rfl (hJ' _ _ this).ge),
exact lt_of_le_of_ne le_sup_left (λ h, H $ h.symm ▸ le_sup_right) },
have : ideal.span {x} * Jac ^ (n + 1) ≤ ⊥,
calc ideal.span {x} * Jac ^ (n + 1) = ideal.span {x} * Jac * Jac ^ n :
by rw [pow_succ, ← mul_assoc]
... ≤ J * Jac ^ n : mul_le_mul (by rwa mul_comm) (le_refl _)
... = ⊥ : by simp [J],
refine hxJ (mem_annihilator.2 (λ y hy, (mem_bot R).1 _)),
refine this (mul_mem_mul (mem_span_singleton_self x) _),
rwa [← hn (n + 1) (nat.le_succ _)]
end
end is_artinian_ring
|
45836e28040da8841f2bdcc74bb5ac81d1f89fad | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/run/prod_notation.lean | 7182963ad5aa7f9717471bb9c4707ebca61e8057 | [
"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 | 154 | lean | import data.prod data.num
open prod
definition tst1 : num × Prop × num × Prop := (1, true, 2, false)
definition tst2 : num × num × num := (1, 2, 3)
|
0a07c81825d06a3efbbe16f22f20b4727fe0f029 | 952248371e69ccae722eb20bfe6815d8641554a8 | /src/proof_reconstruction.lean | 63efda8bf0396915101155cacc74f6ea246c963f | [] | no_license | robertylewis/lean_polya | 5fd079031bf7114449d58d68ccd8c3bed9bcbc97 | 1da14d60a55ad6cd8af8017b1b64990fccb66ab7 | refs/heads/master | 1,647,212,226,179 | 1,558,108,354,000 | 1,558,108,354,000 | 89,933,264 | 1 | 2 | null | 1,560,964,118,000 | 1,493,650,551,000 | Lean | UTF-8 | Lean | false | false | 48,270 | lean | import .datatypes .additive .reconstruction_theorems tactic.norm_num
namespace polya
open expr tactic diseq_proof
--#check mk_nat_val_ne_proof use something like this below?
theorem fake_ne_zero_pf (q : ℚ) : q ≠ 0 := sorry
theorem fake_gt_zero_pf (q : ℚ) : q > 0 := sorry
theorem fake_lt_zero_pf (q : ℚ) : q < 0 := sorry
theorem fake_eq_zero_pf (q : ℚ) : q = 0 := sorry
theorem fake_ne_pf (q1 q2 : ℚ) : q1 ≠ q2 := sorry
private meta def solve_by_norm_num (e : expr) : tactic expr :=
do (_, pf) ← solve_aux e `[norm_num, tactic.done],
return pf
meta def mk_ne_zero_pf (q : ℚ) : tactic expr :=
--do qe ← to_expr ``(%%(quote q) : ℚ),
-- to_expr ``(fake_ne_zero_pf (%%qe : ℚ))
--return `(fake_ne_zero_pf q)
solve_by_norm_num `(q ≠ 0)
-- proves that q > 0, q < 0, or q = 0
meta def mk_sign_pf (q : ℚ) : tactic expr :=
/-do qe ← to_expr `(%%(quote q) : ℚ),
if q > 0 then to_expr `(fake_gt_zero_pf (%%qe : ℚ))
else if q < 0 then to_expr `(fake_lt_zero_pf (%%qe : ℚ))
else to_expr ``(fake_eq_zero_pf (%%qe : ℚ))-/
if q > 0 then --return `(fake_gt_zero_pf q)
solve_by_norm_num `(q > 0)
else if q < 0 then --return `(fake_lt_zero_pf q)
solve_by_norm_num `(q < 0)
else --return `(fake_eq_zero_pf q)
solve_by_norm_num `(q = 0)
meta def mk_ne_pf (q1 q2 : ℚ) : tactic expr :=
/-do q1e ← to_expr ``(%%(quote q1) : ℚ),
q2e ← to_expr ``(%%(quote q2) : ℚ),
to_expr `(fake_ne_pf %%q1e %%q2e)-/
--return `(fake_ne_pf q1 q2)
solve_by_norm_num `(q1 ≠ q2)
meta def mk_int_sign_pf (z : ℤ) : tactic expr :=
if z > 0 then solve_by_norm_num `(z > 0) --return `(sorry : z > 0)
else if z < 0 then solve_by_norm_num `(z < 0)--return `(sorry : z < 0)
else solve_by_norm_num `(z = 0) --return `(sorry : z = 0)
-- proves z % 2 = 0 or z % 2 = 1
meta def mk_int_mod_pf (z : ℤ) : tactic expr :=
if z % 2 = 0 then return `(sorry : z % 2 = 0)
else return `(sorry : z % 2 = 1)
namespace diseq_proof
private meta def reconstruct_hyp (lhs rhs : expr) (c : ℚ) (pf : expr) : tactic expr :=
do mvc ← mk_mvar,
pft ← infer_type pf,
to_expr ``(%%lhs ≠ %%mvc * %%rhs) >>= unify pft,
c' ← eval_expr rat mvc,
if c = c' then return pf else fail "diseq_proof.reconstruct_hyp failed"
private meta def reconstruct_sym (rc : Π {lhs rhs : expr} {c : ℚ}, diseq_proof lhs rhs c → tactic expr)
{lhs rhs c} (dp : diseq_proof lhs rhs c) : tactic expr :=
do symp ← rc dp,
cnep ← mk_ne_zero_pf c,
mk_mapp ``diseq_sym [none, none, none, cnep, symp] -- why doesn't mk_app work?
meta def reconstruct : Π {lhs rhs : expr} {c : ℚ}, diseq_proof lhs rhs c → tactic expr
| .(_) .(_) .(_) (hyp (lhs) (rhs) (c) e) := reconstruct_hyp lhs rhs c e
| .(_) .(_) .(_) (@sym lhs rhs c dp) := reconstruct_sym @reconstruct dp
end diseq_proof
namespace eq_proof
private meta def reconstruct_hyp (lhs rhs : expr) (c : ℚ) (pf : expr) : tactic expr :=
do mvc ← mk_mvar,
pft ← infer_type pf,
to_expr ``(%%lhs = %%mvc * %%rhs) >>= unify pft,
c' ← eval_expr rat mvc,
if c = c' then return pf else fail "eq_proof.reconstruct_hyp failed"
private meta def reconstruct_sym (rc : Π {lhs rhs : expr} {c : ℚ}, eq_proof lhs rhs c → tactic expr)
{lhs rhs c} (dp : eq_proof lhs rhs c) : tactic expr :=
do symp ← rc dp,
cnep ← mk_ne_zero_pf c, -- 5/1 ≠ 0
-- infer_type symp >>= trace,
-- infer_type cnep >>= trace,
mk_mapp ``eq_sym [none, none, none, cnep, symp] -- why doesn't mk_app work?
variable iepr_fn : Π {lhs rhs i}, ineq_proof lhs rhs i → tactic expr
private meta def reconstruct_of_opp_ineqs_aux {lhs rhs i} (c : ℚ) (iep : ineq_proof lhs rhs i)
(iepr : ineq_proof lhs rhs i.reverse) : tactic expr :=
do guard (bnot i.strict),
pr1 ← iepr_fn iep, pr2 ← iepr_fn iepr,
if i.to_comp.is_less then
mk_mapp ``op_ineq [none, none, none, some pr1, some pr2]
else
mk_mapp ``op_ineq [none, none, none, some pr2, some pr1]
private theorem eq_sub_of_add_eq_facs {c1 c2 e1 e2 : ℚ} (hc1 : c1 ≠ 0) (h : c1 * e1 + c2 * e2 = 0) : e1 = -(c2/c1) * e2 :=
sorry
private meta def reconstruct_of_sum_form_proof (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : expr → expr → ℚ → Π {sf},
Π (sp : sum_form_proof ⟨sf, spec_comp.eq⟩), tactic expr | lhs rhs c sf sp :=
if lhs.lt rhs then -- flipped?
reconstruct_of_sum_form_proof rhs lhs (1/c) sp
else do
guard $ (sf.contains lhs) && (sf.contains rhs),
let a := sf.get_coeff lhs in let b := sf.get_coeff rhs in do
guard $ c = -(b/a),
pf ← sfpr sp,
nez ← mk_ne_zero_pf a,
mk_app ``eq_sub_of_add_eq_facs [nez, pf]
-- fail "eq_proof.reconstruct_of_sum_proof not implemented yet"
meta def reconstruct_aux (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : Π {lhs rhs : expr} {c : ℚ}, eq_proof lhs rhs c → tactic expr
| .(_) .(_) .(_) (hyp (lhs) (rhs) (c) e) := reconstruct_hyp lhs rhs c e
| .(_) .(_) .(_) (@sym lhs rhs c dp) := reconstruct_sym @reconstruct_aux dp
| .(_) .(_) .(_) (@of_opp_ineqs lhs rhs i c iep iepr) := reconstruct_of_opp_ineqs_aux @iepr_fn c iep iepr
| .(_) .(_) .(_) (@of_sum_form_proof lhs rhs c _ sp) := reconstruct_of_sum_form_proof @sfpr lhs rhs c sp
| .(_) .(_) .(_) (adhoc _ _ _ _ t) := t
end eq_proof
namespace ineq_proof
meta def guard_is_ineq (lhs rhs : expr) (iq : ineq) (pf : expr) : tactic expr :=
do mvc ← mk_mvar, pft ← infer_type pf,
match iq.to_comp with
| comp.lt := to_expr ``(%%lhs < %%mvc * %%rhs) >>= unify pft >> return mvc
| comp.le := to_expr ``(%%lhs ≤ %%mvc * %%rhs) >>= unify pft >> return mvc
| comp.gt := to_expr ``(%%lhs > %%mvc * %%rhs) >>= unify pft >> return mvc
| comp.ge := to_expr ``(%%lhs ≥ %%mvc * %%rhs) >>= unify pft >> return mvc
end
private meta def reconstruct_hyp (lhs rhs : expr) (iq : ineq) (pf : expr) : tactic expr :=
match iq.to_slope with
| slope.horiz :=
do tp ← infer_type pf, --trace "unifying tp in reconstruct_hyp1", trace tp,
to_expr ``( %%(iq.to_comp.to_pexpr) %%rhs 0) >>= unify tp,
return pf
| slope.some c :=
do m ← guard_is_ineq lhs rhs iq pf,
m' ← eval_expr rat m,
if m' = c then return pf else fail "ineq_proof.reconstruct_hyp failed"
end
section
variable (rc : Π {lhs rhs : expr} {iq : ineq}, ineq_proof lhs rhs iq → tactic expr)
include rc
private meta def reconstruct_sym
{lhs rhs iq} (ip : ineq_proof lhs rhs iq) : tactic expr :=
match iq.to_slope with
| slope.horiz := do p ← pp (lhs, rhs), fail $ "reconstruct_sym failed on horiz slope: " ++ p.to_string
| slope.some m :=
do --trace "in reconstruct sym", trace (lhs, rhs, m),
symp ← rc ip, sgnp ← mk_sign_pf m, --trace "have proof of:", infer_type symp >>= trace,
--trace ("m", m), trace ("lhs, rhs", lhs, rhs), trace "sgnp", infer_type sgnp >>= trace, trace "symp", trace ip, infer_type symp >>= trace,
--mk_mapp (name_of_c_and_comp m iq.to_comp) [none, none, none, some sgnp, some symp]
mk_app (if m < 0 then ``sym_op_neg else ``sym_op_pos) [sgnp, symp]
end
-- x ≥ 2y and x ≠ 2y implies x > 2y
private meta def reconstruct_ineq_diseq {lhs rhs iq c} (ip : ineq_proof lhs rhs iq) (dp : diseq_proof lhs rhs c) : tactic expr :=
match iq.to_slope with
| slope.horiz := fail "reconstruct_ineq_diseq needs non-horiz slope"
| slope.some m :=
if bnot (m=c) then
fail "reconstruct_ineq_diseq found non-matching slopes"
else if iq.strict then rc ip
else do ipp ← rc ip, dpp ← dp.reconstruct,
/-if iq.to_comp.is_less then
mk_mapp ``ineq_diseq_le [none, none, none, some dpp, some ipp]
else
mk_mapp ``ineq_diseq_ge [none, none, none, some dpp, some ipp]-/
mk_app ``ineq_diseq [dpp, ipp]
end
variable (rcs : Π {e gc}, sign_proof e gc → tactic expr)
include rcs
-- x ≤ 0y and x ≠ 0 implies x < 0y
private meta def reconstruct_ineq_sign_lhs {lhs rhs iq c} (ip : ineq_proof lhs rhs iq) (sp : sign_proof lhs c) : tactic expr :=
if iq.strict || bnot (c = gen_comp.ne) then fail "reconstruct_ineq_sign_lhs assumes a weak ineq and a diseq-0" else
match iq.to_slope with
| slope.horiz := fail "reconstruct_ineq_sign_lhs assumes a 0 slope"
| slope.some m :=
if m = 0 then do
ipp ← rc ip, spp ← rcs sp,
-- mk_app (if iq.to_comp.is_less then ``ineq_diseq_sign_lhs_le else ``ineq_diseq_sign_lhs_ge) [spp, ipp]
mk_app ``ineq_diseq_sign_lhs [spp, ipp]
else fail "reconstruct_ineq_sign_lhs assumes a 0 slope"
end
-- this might be wrong: should we produce proofs of y < 0?
private meta def reconstruct_ineq_sign_rhs {lhs rhs iq c} (ip : ineq_proof lhs rhs iq) (sp : sign_proof rhs c) : tactic expr :=
if iq.strict || bnot (c = gen_comp.ne) then fail "reconstruct_ineq_sign_rhs assumes a weak ineq and a diseq-0" else
match iq.to_slope with
| slope.horiz := do ipp ← rc ip, spp ← rcs sp,
-- mk_app (if iq.to_comp.is_less then ``ineq_diseq_sign_rhs_le else ``ineq_diseq_sign_rhs_ge) [spp, ipp]
mk_app ``ineq_diseq_sign_rhs [spp, ipp]
| _ := fail "reconstruct_ineq_sign_rhs assumes a horizontal slope"
end
omit rc
-- x ≥ 0 implies x ≥ 0*y
private meta def reconstruct_zero_comp_of_sign {lhs c} (rhs : expr) (iq : ineq) (sp : sign_proof lhs c) : tactic expr :=
if bnot ((iq.to_comp.to_gen_comp = c) && (iq.is_zero_slope)) then fail $ "reconstruct_zero_comp_of_sign only produces comps with zero" ++ (to_fmt iq).to_string ++ (to_fmt iq.to_comp.to_gen_comp).to_string ++ (to_fmt c).to_string
--else do spp ← rcs sp, mk_app (zero_mul_name_of_comp iq.to_comp) [rhs, spp]
else do spp ← rcs sp, mk_mapp ``op_zero_mul [none, some rhs, none, none, some spp]
private meta def reconstruct_horiz_of_sign {rhs c} (lhs : expr) (iq : ineq) (sp : sign_proof rhs c) : tactic expr :=
if bnot ((iq.to_comp.to_gen_comp = c) && (iq.is_horiz)) then fail $ "reconstruct_horiz_of_sign failed"
else rcs sp
end
/-
private theorem eq_sub_of_add_eq_facs {c1 c2 e1 e2 : ℚ} (hc1 : c1 ≠ 0) (h : c1 * e1 + c2 * e2 = 0) : e1 = -(c2/c1) * e2 :=
sorry
private meta def reconstruct_of_sum_form_proof (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : expr → expr → ℚ → Π {sf},
Π (sp : sum_form_proof ⟨sf, spec_comp.eq⟩), tactic expr | lhs rhs c sf sp :=
if rhs.lt lhs then
reconstruct_of_sum_form_proof rhs lhs (1/c) sp
else do
guard $ (sf.contains lhs) && (sf.contains rhs),
let a := sf.get_coeff lhs in let b := sf.get_coeff rhs in do
guard $ c = -(b/a),
pf ← sfpr sp,
nez ← mk_ne_zero_pf a,
mk_app ``eq_sub_of_add_eq_facs [nez, pf]
-/
private meta def reconstruct_of_sum_form_proof (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) :
expr → expr → ineq → Π {sfc}, sum_form_proof sfc → tactic expr | lhs rhs i sfc sp :=
if lhs.lt rhs then -- flipped?
reconstruct_of_sum_form_proof rhs lhs i.reverse sp
else
(match i.to_slope with
| slope.some m := do {
guard $ (sfc.sf.contains lhs) && (sfc.sf.contains rhs),
guard $ sfc.sf.keys.length = 2,
let a := sfc.sf.get_coeff lhs in let b := sfc.sf.get_coeff rhs in do
guard $ m = -(b/a),
guard $ if a < 0 then sfc.c.to_comp = i.to_comp.reverse else sfc.c.to_comp = i.to_comp,
rhs' ← to_expr ``(%%(↑(rat.reflect m) : expr) * %%rhs), -- better way to do this?
tp ← i.to_comp.to_function lhs rhs',
sgnp ← mk_sign_pf a,
pf ← sfpr sp,
--trace "have: ", infer_type pf >>= trace, trace ("lhs: ", lhs), trace ("rhs: ", rhs),
let thnm := if a < 0 then ``op_of_sum_op_zero_neg else ``op_of_sum_op_zero_pos in
mk_app thnm [pf, sgnp]}
--to_expr ``(sorry : %%tp)
-- fail "ineq_proof.reconstruct_of_sum_proof not implemented yet"
| slope.horiz := fail "ineq_proof.reconstruct_of_sum_proof failed, cannot turn a sum into a horiz slope"
end)
meta def reconstruct_aux (rcs : Π {e gc}, sign_proof e gc → tactic expr) (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) :
Π {lhs rhs : expr} {iq : ineq}, ineq_proof lhs rhs iq → tactic expr
| _ _ _ (hyp lhs rhs iq e) := reconstruct_hyp lhs rhs iq e
| _ _ _ (sym ip) := reconstruct_sym @reconstruct_aux ip
| _ _ _ (of_ineq_proof_and_diseq ip dp) := reconstruct_ineq_diseq @reconstruct_aux ip dp
| _ _ _ (of_ineq_proof_and_sign_lhs ip sp) := reconstruct_ineq_sign_lhs @reconstruct_aux @rcs ip sp
| _ _ _ (of_ineq_proof_and_sign_rhs ip sp) := reconstruct_ineq_sign_rhs @reconstruct_aux @rcs ip sp
| _ _ _ (zero_comp_of_sign_proof rhs iq sp) := reconstruct_zero_comp_of_sign @rcs rhs iq sp
| _ _ _ (horiz_of_sign_proof lhs iq sp) := reconstruct_horiz_of_sign @rcs lhs iq sp
| _ _ _ (of_sum_form_proof lhs rhs i sp) := reconstruct_of_sum_form_proof @sfpr lhs rhs i sp
| _ _ _ (adhoc _ _ _ _ t) := t
end ineq_proof
namespace sign_proof
private meta def reconstruct_hyp (e : expr) (gc : gen_comp) (pf : expr) : tactic expr :=
let pex := match gc with
| gen_comp.ge := ``(%%e ≥ 0)
| gen_comp.gt := ``(%%e > 0)
| gen_comp.le := ``(%%e ≤ 0)
| gen_comp.lt := ``(%%e < 0)
| gen_comp.eq := ``(%%e = 0)
| gen_comp.ne := ``(%%e ≠ 0)
end in do tp ← infer_type pf, to_expr pex >>= unify tp >> return pf
private meta def reconstruct_scaled_hyp (e : expr) (gc : gen_comp) (pf : expr) (q : ℚ) : tactic expr :=
do sp ← mk_sign_pf q,
if q > 0 then
mk_mapp ``op_zero_of_mul_op_zero_of_pos [none, none, none, none, pf, sp]
else
mk_mapp ``op_zero_of_mul_op_zero_of_neg [none, none, none, none, pf, sp]
section
parameter rc : Π {e c}, sign_proof e c → tactic expr
parameter sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr
private meta def rci := @ineq_proof.reconstruct_aux @rc @sfpr
private meta def rce := @eq_proof.reconstruct_aux @rci @sfpr
-- x ≤ 0*y to x ≤ 0
private meta def reconstruct_ineq_lhs (c : gen_comp) {lhs rhs iqp} (ip : ineq_proof lhs rhs iqp) : tactic expr :=
if bnot ((iqp.to_comp.to_gen_comp = c) && (iqp.is_zero_slope)) then fail "reconstruct_ineq_lhs must take a comparison with 0"
--else do ipp ← rci ip, mk_app (zero_mul'_name_of_comp iqp.to_comp) [ipp]
else do ipp ← rci ip, mk_app ``op_zero_mul' [ipp]
private meta def reconstruct_ineq_rhs (c : gen_comp) {lhs rhs iqp} (ip : ineq_proof lhs rhs iqp) : tactic expr :=
if bnot ((iqp.to_comp.to_gen_comp = c) && (iqp.is_horiz)) then fail "reconstruct_ineq_rhs must take a horiz comp"
else rci ip
private meta def reconstruct_eq_of_two_eqs_lhs {lhs rhs eqp1 eqp2} (ep1 : eq_proof lhs rhs eqp1) (ep2 : eq_proof lhs rhs eqp2) : tactic expr :=
if h : eqp1 = eqp2 then fail "reconstruct_eq_of_two_eqs lhs cannot infer anything from the same equality twice"
else do epp1 ← rce ep1, epp2 ← rce ep2, nep ← mk_ne_pf eqp1 eqp2,
mk_app ``eq_zero_of_two_eqs_lhs [epp1, epp2, nep]
private meta def reconstruct_eq_of_two_eqs_rhs {lhs rhs eqp1 eqp2} (ep1 : eq_proof lhs rhs eqp1) (ep2 : eq_proof lhs rhs eqp2) : tactic expr :=
if h : eqp1 = eqp2 then fail "reconstruct_eq_of_two_eqs lhs cannot infer anything from the same equality twice"
else do epp1 ← rce ep1, epp2 ← rce ep2, nep ← mk_ne_pf eqp1 eqp2,
mk_app ``eq_zero_of_two_eqs_rhs [epp1, epp2, nep]
private meta def reconstruct_diseq_of_diseq_zero {lhs rhs} (dp : diseq_proof lhs rhs 0) : tactic expr :=
do dpp ← dp.reconstruct,
mk_app ``ne_zero_of_ne_mul_zero [dpp]
private meta def reconstruct_eq_of_eq_zero {lhs rhs} (ep : eq_proof lhs rhs 0) : tactic expr :=
do epp ← rce ep,
mk_app ``eq_zero_of_eq_mul_zero [epp]
/-
private meta def reconstruct_ineqs (rct : contrad → tactic expr) {lhs rhs} (ii : ineq_info lhs rhs) (id : ineq_data lhs rhs) : tactic expr := do trace "ineqs!!",
match ii with
| ineq_info.no_comps := fail "reconstruct_ineqs cannot find a contradiction with no known comps"
| ineq_info.one_comp id2 := reconstruct_two_ineq_data rct id id2
| ineq_info.equal ed := reconstruct_eq_ineq ed id
| ineq_info.two_comps id1 id2 :=
let sfid := sum_form_comp_data.of_ineq_data id,
sfid1 := sum_form_comp_data.of_ineq_data id1,
sfid2 := sum_form_comp_data.of_ineq_data id2 in
match find_contrad_in_sfcd_list [sfid, sfid1, sfid2] with
| some ctr := rct ctr
| option.none := fail "reconstruct_ineqs failed to find contr"
end
end
-/
private theorem {u} ge_of_not_lt {α : Type u} [linear_order α] {a b : α} (h : ¬ a < b) : (a ≥ b) := le_of_not_gt h
private theorem {u} gt_of_not_le {α : Type u} [linear_order α] {a b : α} (h : ¬ a ≤ b) : (a > b) := lt_of_not_ge h
private meta def neg_op_lemma_name : comp → name
| comp.lt := ``lt_of_not_ge
| comp.le := ``le_of_not_gt
| comp.ge := ``ge_of_not_lt
| comp.gt := ``gt_of_not_le
meta def reconstruct_ineq_of_eq_and_ineq_aux
-- (sfpr : Π {sf : sum_form_comp}, Π (sp : sum_form_proof sf), tactic.{0} (expr tt))
{lhs rhs iq c} (c' : gen_comp) (ep : eq_proof lhs rhs c) (ip : ineq_proof lhs rhs iq) (pvt : expr) : tactic expr :=
do negt ← c'.to_comp.to_function pvt `(0 : ℚ),
(_, notpf) ← solve_aux negt (do
applyc $ neg_op_lemma_name c'.to_comp,
hypv ← intro `h,
let sfid := sum_form_comp_data.of_ineq_data ⟨_, ip⟩ in
let sfed := sum_form_comp_data.of_eq_data ⟨_, ep⟩ in
let sfsd := sum_form_comp_data.of_sign_data ⟨c'.negate, hyp pvt _ hypv⟩ in
match find_contrad_sfcd_in_sfcd_list [sfid, sfed, sfsd] with
| none := fail "reconstruct_ineq_of_eq_and_ineq failed to find proof"
| some ⟨_, sfp, _⟩ := do ctrp ← sfpr sfp, fp ← mk_mapp ``lt_irrefl [none, none, none, ctrp], apply fp
--applyc ``lt_irrefl, trace "apply3", apply ctrp, trace "apply4"
end),
return notpf
--#check @reconstruct_ineq_of_eq_and_ineq_aux
-- these are the hard cases. Is this the right place to handle them?
private meta def reconstruct_ineq_of_eq_and_ineq_lhs {lhs rhs iq c} (c' : gen_comp) (ep : eq_proof lhs rhs c) (ip : ineq_proof lhs rhs iq) : tactic expr :=
reconstruct_ineq_of_eq_and_ineq_aux c' ep ip lhs
--fail "reconstruct_ineq_of_eq_and_ineq not implemented"
private meta def reconstruct_ineq_of_eq_and_ineq_rhs {lhs rhs iq c} (c' : gen_comp) (ep : eq_proof lhs rhs c) (ip : ineq_proof lhs rhs iq) : tactic expr :=
reconstruct_ineq_of_eq_and_ineq_aux c' ep ip rhs
/-do negt ← c'.to_comp.to_function rhs `(0 : ℚ),
(_, notpf) ← solve_aux negt (do
applyc $ neg_op_lemma_name c'.to_comp,
hypv ← intro `h,
let sfid := sum_form_comp_data.of_ineq_data ⟨_, ip⟩ in
let sfed := sum_form_comp_data.of_eq_data ⟨_, ep⟩ in
let sfsd := sum_form_comp_data.of_sign_data ⟨c', hyp rhs _ hypv⟩ in
match find_contrad_sfcd_in_sfcd_list [sfid, sfed, sfsd] with
| none := fail "reconstruct_ineq_of_eq_and_ineq_rhs failed to find proof"
| some ⟨_, sfp, _⟩ := do ctrp ← sfpr sfp, applyc ``lt_irrefl, apply ctrp
end),
return notpf-/
-- fail "reconstruct_ineq_of_eq_and_ineq not implemented"
-- TODO
private meta def reconstruct_ineq_of_ineq_and_eq_zero_rhs {lhs rhs iq} (c : gen_comp) (ip : ineq_proof lhs rhs iq) (sp : sign_proof lhs gen_comp.eq) : tactic expr :=
fail "reconstruct_ineq_of_ineq_and_eq_zero not implemented"
private meta def reconstruct_diseq_of_strict_ineq {e c} (sp : sign_proof e c) : tactic expr :=
if c.is_strict then do
spp ← rc sp,
mk_app ``ne_of_strict_op [spp]
else fail "reconstruct_diseq_of_strict_ineq failed, comp is not strict"
end
-- TODO
private meta def reconstruct_of_sum_form_proof (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) (e : expr) (c : gen_comp) {sfc}
(sp : sum_form_proof sfc) : tactic expr :=
do
pf' ← sfpr sp,
--trace "in sign_proof.reconstruct_of_sum_form_proof",
--infer_type e >>= trace,
--trace c,
let coeff := sfc.sf.get_coeff e,
if coeff = 0 then fail "sign_proof.reconstruct_of_sum_form_proof failed, zero coeff" else do
coeff_sign_pr ← mk_sign_pf coeff,
-- if coeff < 0 then
mk_mapp (if coeff < 0 then ``rev_op_zero_of_neg_mul_op_zero else ``op_zero_of_pos_mul_op_zero) [none, none, none, none, coeff_sign_pr, pf']
-- else if coeff > 0 then
-- mk_mapp ``op_zero_of_pos_mul_op_zero [none, none, none, none, coeff_sign_]
-- fail "sign_proof.reconstruct_of_sum_form_proof failed, not implemented yet"
meta def reconstruct_eq_of_le_of_ge (rct : Π {e c}, sign_proof e c → tactic expr) {e} (lep : sign_proof e gen_comp.le) (gep : sign_proof e gen_comp.ge) : tactic expr :=
do lep' ← rct lep, gep' ← rct gep,
mk_app ``le_antisymm' [lep', gep']
meta def reconstruct_aux (sfpr : Π {sf}, Π (sp : sum_form_proof sf), tactic expr) : Π {e c}, sign_proof e c → tactic expr
| .(_) .(_) (hyp e c pf) := reconstruct_hyp e c pf
| .(_) .(_) (scaled_hyp e c pf q) := reconstruct_scaled_hyp e c pf q
| .(_) .(_) (@ineq_lhs c _ _ _ ip) := reconstruct_ineq_lhs @reconstruct_aux @sfpr c ip
| .(_) .(_) (@ineq_rhs c _ _ _ ip) := reconstruct_ineq_rhs @reconstruct_aux @sfpr c ip
| .(_) .(_) (@eq_of_two_eqs_lhs _ _ _ _ ep1 ep2) := reconstruct_eq_of_two_eqs_lhs @reconstruct_aux @sfpr ep1 ep2
| .(_) .(_) (@eq_of_two_eqs_rhs _ _ _ _ ep1 ep2) := reconstruct_eq_of_two_eqs_rhs @reconstruct_aux @sfpr ep1 ep2
| .(_) .(_) (@diseq_of_diseq_zero _ _ dp) := reconstruct_diseq_of_diseq_zero dp
| .(_) .(_) (@eq_of_eq_zero _ _ ep) := reconstruct_eq_of_eq_zero @reconstruct_aux @sfpr ep
| .(_) .(_) (eq_of_le_of_ge lep gep) := reconstruct_eq_of_le_of_ge @reconstruct_aux lep gep
| .(_) .(_) (@ineq_of_eq_and_ineq_lhs _ _ _ _ c' ep ip) := reconstruct_ineq_of_eq_and_ineq_lhs @sfpr c' ep ip
| .(_) .(_) (@ineq_of_eq_and_ineq_rhs _ _ _ _ c' ep ip) := reconstruct_ineq_of_eq_and_ineq_rhs @sfpr c' ep ip
| .(_) .(_) (@ineq_of_ineq_and_eq_zero_rhs _ _ _ c ip sp) := reconstruct_ineq_of_ineq_and_eq_zero_rhs c ip sp
| .(_) .(_) (@diseq_of_strict_ineq _ _ sp) := reconstruct_diseq_of_strict_ineq @reconstruct_aux sp
| .(_) .(_) (@of_sum_form_proof e c _ sp) := reconstruct_of_sum_form_proof @sfpr e c sp
| .(_) .(_) (adhoc _ _ _ t) := t
end sign_proof
namespace sum_form_proof
section
parameter sfrc : Π {sfc}, sum_form_proof sfc → tactic expr
private meta def sprc := @sign_proof.reconstruct_aux @sfrc
private meta def iprc := @ineq_proof.reconstruct_aux @sprc @sfrc
private meta def eprc := @eq_proof.reconstruct_aux @iprc @sfrc
-- assumes lhs < rhs
private meta def reconstruct_of_ineq_proof :
Π {lhs rhs iq}, ineq_proof lhs rhs iq → tactic expr | lhs rhs iq ip :=
if expr.lt lhs rhs then reconstruct_of_ineq_proof ip.sym else
--trace "ipp is:" >> iprc ip >>= infer_type >>= trace >> trace "const is:" >> infer_type ↑`(@polya.mul_lt_of_lt) >>= trace >>
match iq.to_slope with
| slope.horiz :=
do ipp ← iprc ip,
tactic.mk_mapp (sum_form_name_of_comp_single iq.to_comp) [none, none, ipp]
| slope.some m :=
do ipp ← iprc ip,
--trace ("ipp", ip, ipp), infer_type ipp >>= trace, trace ("comp", iq.to_comp), trace ("iq", iq),
if m = 0 then
tactic.mk_mapp (sum_form_name_of_comp_single iq.to_comp) [none, none, ipp]
else
tactic.mk_mapp (sum_form_name_of_comp iq.to_comp) [none, none, none, ipp]
-- tactic.mk_mapp ((if m = 0 then sum_form_name_of_comp_single else sum_form_name_of_comp) iq.to_comp) [none, none, ipp]
end
--include sfrc
private meta def reconstruct_of_eq_proof :
Π {lhs rhs c}, eq_proof lhs rhs c → tactic expr | lhs rhs c ep :=
if expr.lt lhs rhs then reconstruct_of_eq_proof ep.sym else
do ipp ← eprc ep,
mk_app ``sub_eq_zero_of_eq [ipp]
--fail "sum_form_proof.reconstruct_of_eq_proof not implemented yet"
private meta def reconstruct_of_sign_proof :
Π {e c}, sign_proof e c → tactic expr | e c sp :=
if c.is_less then sprc sp
else do spp ← sprc sp,
--trace "spp type is", infer_type spp >>= trace,
mk_mapp ``rev_op_zero_of_op [none, none, none, some spp]
--fail "sum_form_proof.reconstruct_of_sign_proof not implemented yet"
-- sum_form_proof ⟨lhs.add_factor rhs m, spec_comp.strongest c1 c2⟩
-- wait for algebraic normalizer?
-- TODO
private theorem reconstruct_of_add_factor_aux (P : Prop) {Q R : Prop} (h : Q) (h2 : R) : P := sorry
private meta def reconstruct_of_add_factor_same_comp {lhs rhs c1 c2} (m : ℚ)
(sfpl : sum_form_proof ⟨lhs, c1⟩) (sfpr : sum_form_proof ⟨rhs, c2⟩) : tactic expr :=
let sum := lhs + rhs.scale m in
do tp ← sum_form.to_expr sum,
tp' ← (spec_comp.strongest c1 c2).to_comp.to_function tp `(0 : ℚ),
pf1 ← sfrc sfpl, pf2 ← sfrc sfpr,
mk_mapp ``reconstruct_of_add_factor_aux [some tp', none, none, some pf1, some pf2] --to_expr `(sorry : %%tp)
--fail "reconstruct_of_add_factor_same_comp failed, not implemented yet"
private theorem reconstruct_of_add_eq_factor_op_comp_aux (P : Prop) {Q R : Prop} (h : Q) (h2 : R) : P := sorry
/-
m is negative
-/
private meta def reconstruct_of_add_eq_factor_op_comp {lhs rhs c1} (m : ℚ)
(sfpl : sum_form_proof ⟨lhs, c1⟩) (sfpr : sum_form_proof ⟨rhs, spec_comp.eq⟩) : tactic expr :=
let sum := lhs + rhs.scale m in
do tp ← sum_form.to_expr sum,
tp' ← c1.to_comp.to_function tp `(0 : ℚ),
pf1 ← sfrc sfpl, pf2 ← sfrc sfpr,
mk_mapp ``reconstruct_of_add_eq_factor_op_comp_aux [some tp', none, none, some pf1, some pf2]
--fail "reconstruct_of_add_eq_factor_op_comp not implemented yet"
private theorem reconstruct_of_scale_aux (P : Prop) {Q : Prop} (h : Q) : P := sorry
private meta def reconstruct_of_scale (rct : Π {sfc}, sum_form_proof sfc → tactic expr)
{sfc} (m : ℚ) (sfp : sum_form_proof sfc) : tactic expr :=
do tp ← sum_form.to_expr (sfc.sf.scale m),
tp' ← sfc.c.to_comp.to_function tp `(0 : ℚ),
pf ← rct sfp,
mk_mapp ``reconstruct_of_scale_aux [some tp', none, some pf] -- to_expr `(sorry : %%tp')
end
-- TODO (alg norm)
theorem reconstruct_of_expr_def_aux (P : Prop) : P := sorry
private meta def reconstruct_of_expr_def (e : expr) (sf : sum_form) : tactic expr :=
do tp ← sum_form.to_expr sf,
tp' ← to_expr ``(%%tp = 0),
-- (_, pf) ← solve_aux tp' (simp >> done),
mk_app ``reconstruct_of_expr_def_aux [tp']
-- instantiate_mvars pf
--fail "reconstruct_of_expr_def failed, not implemented yet"
meta def reconstruct : Π {sfc}, sum_form_proof sfc → tactic expr
| _ (of_ineq_proof ip) := reconstruct_of_ineq_proof @reconstruct ip
| _ (of_eq_proof ep) := reconstruct_of_eq_proof @reconstruct ep
| _ (of_sign_proof sp) := reconstruct_of_sign_proof @reconstruct sp
| _ (of_add_factor_same_comp m sfpl sfpr) :=
reconstruct_of_add_factor_same_comp @reconstruct m sfpl sfpr
| _ (of_add_eq_factor_op_comp m sfpl sfpr) :=
reconstruct_of_add_eq_factor_op_comp @reconstruct m sfpl sfpr
| _ (of_scale m sfp) := reconstruct_of_scale @reconstruct m sfp
| _ (of_expr_def e sf) := reconstruct_of_expr_def e sf
| _ (fake sd) := fail "cannot reconstruct a fake proof"
/-meta def reconstruct : Π {sfc}, sum_form_proof sfc → tactic expr | sfc sfp :=
if sfc.sf.keys.length = 0 then do
ex ← sfc.c.to_comp.to_function ```(0 : ℚ) ```(0 : ℚ),
to_expr `(sorry : %%ex) else
let sfcd : sum_form_comp_data := ⟨_, sfp, mk_rb_set⟩ in
match sfcd.to_ineq_data with
| option.some ⟨lhs, rhs, id⟩ := do ex ← ineq_data.to_expr id, to_expr `(sorry : %%ex)
| none := trace sfc >> fail "fake sum_form_proof.reconstruct failed, no ineq data"
end-/
end sum_form_proof
meta def sign_proof.reconstruct := @sign_proof.reconstruct_aux @sum_form_proof.reconstruct
meta def ineq_proof.reconstruct := @ineq_proof.reconstruct_aux @sign_proof.reconstruct @sum_form_proof.reconstruct
meta def eq_proof.reconstruct := @eq_proof.reconstruct_aux @ineq_proof.reconstruct @sum_form_proof.reconstruct
meta def ineq_data.to_expr {lhs rhs} (id : ineq_data lhs rhs) : tactic expr :=
match id.inq.to_slope with
| slope.horiz := id.inq.to_comp.to_function rhs `(0 : ℚ)
| slope.some m := if m = 0 then id.inq.to_comp.to_function lhs `(0 : ℚ)
else do rhs' ← to_expr ``(%%(m.reflect : expr)*%%rhs), id.inq.to_comp.to_function lhs rhs'
end
namespace contrad
private meta def reconstruct_eq_diseq {lhs rhs} (ed : eq_data lhs rhs) (dd : diseq_data lhs rhs) : tactic expr :=
if bnot (ed.c = dd.c) then fail "reconstruct_eq_diseq failed: given different coefficients"
else do ddp ← dd.prf.reconstruct, edp ← ed.prf.reconstruct, return $ ddp.app edp
private meta def reconstruct_two_ineq_data {lhs rhs} (rct : contrad → tactic expr) (id1 id2 : ineq_data lhs rhs) : tactic expr :=
let sfid1 := sum_form_comp_data.of_ineq_data id1,
sfid2 := sum_form_comp_data.of_ineq_data id2 in
match find_contrad_in_sfcd_list [sfid1, sfid2] with
| some ctr := rct ctr
| option.none := fail "reconstruct_two_ineq_data failed to find contr"
end
private meta def reconstruct_eq_ineq {lhs rhs} (ed : eq_data lhs rhs) (id : ineq_data lhs rhs) : tactic expr :=
fail "reconstruct_eq_ineq not implemented"
-- TODO: this is the hard part. Should this be refactored into smaller pieces?
private meta def reconstruct_ineqs (rct : contrad → tactic expr) {lhs rhs} (ii : ineq_info lhs rhs) (id : ineq_data lhs rhs) : tactic expr := --do trace "ineqs!!",
match ii with
| ineq_info.no_comps := fail "reconstruct_ineqs cannot find a contradiction with no known comps"
| ineq_info.one_comp id2 := reconstruct_two_ineq_data rct id id2
| ineq_info.equal ed := reconstruct_eq_ineq ed id
| ineq_info.two_comps id1 id2 :=
let sfid := sum_form_comp_data.of_ineq_data id,
sfid1 := sum_form_comp_data.of_ineq_data id1,
sfid2 := sum_form_comp_data.of_ineq_data id2 in
match find_contrad_in_sfcd_list [sfid, sfid1, sfid2] with
| some ctr := rct ctr
| option.none := fail "reconstruct_ineqs failed to find contr"
end
end
private meta def reconstruct_sign_ne_eq {e} (nepr : sign_proof e gen_comp.ne) (eqpr : sign_proof e gen_comp.eq) : tactic expr :=
do neprp ← nepr.reconstruct, eqprp ← eqpr.reconstruct,
return $ neprp.app eqprp
private meta def reconstruct_sign_le_gt {e} (lepr : sign_proof e gen_comp.le) (gtpr : sign_proof e gen_comp.gt) : tactic expr :=
do leprp ← lepr.reconstruct, gtprp ← gtpr.reconstruct,
mk_app ``le_gt_contr [leprp, gtprp]
private meta def reconstruct_sign_ge_lt {e} (gepr : sign_proof e gen_comp.ge) (ltpr : sign_proof e gen_comp.lt) : tactic expr :=
do geprp ← gepr.reconstruct, ltprp ← ltpr.reconstruct,
mk_app ``ge_lt_contr [geprp, ltprp]
private meta def reconstruct_sign_gt_lt {e} (gtpr : sign_proof e gen_comp.gt) (ltpr : sign_proof e gen_comp.lt) : tactic expr :=
do gtprp ← gtpr.reconstruct, ltprp ← ltpr.reconstruct,
mk_app ``gt_lt_contr [gtprp, ltprp]
private meta def reconstruct_sign {e} : sign_data e → sign_data e → tactic expr
| ⟨gen_comp.ne, prf1⟩ ⟨gen_comp.eq, prf2⟩ := reconstruct_sign_ne_eq prf1 prf2
| ⟨gen_comp.eq, prf1⟩ ⟨gen_comp.ne, prf2⟩ := reconstruct_sign_ne_eq prf2 prf1
| ⟨gen_comp.le, prf1⟩ ⟨gen_comp.gt, prf2⟩ := reconstruct_sign_le_gt prf1 prf2
| ⟨gen_comp.gt, prf1⟩ ⟨gen_comp.le, prf2⟩ := reconstruct_sign_le_gt prf2 prf1
| ⟨gen_comp.lt, prf1⟩ ⟨gen_comp.ge, prf2⟩ := reconstruct_sign_ge_lt prf2 prf1
| ⟨gen_comp.ge, prf1⟩ ⟨gen_comp.lt, prf2⟩ := reconstruct_sign_ge_lt prf1 prf2
| ⟨gen_comp.gt, prf1⟩ ⟨gen_comp.lt, prf2⟩ := reconstruct_sign_gt_lt prf1 prf2
| ⟨gen_comp.lt, prf1⟩ ⟨gen_comp.gt, prf2⟩ := reconstruct_sign_gt_lt prf2 prf1
| s1 s2 := trace e >> trace s1.c >> trace s2.c >> fail "reconstruct_sign failed: given non-opposite comps"
private meta def reconstruct_strict_ineq_self {e} (id : ineq_data e e) : tactic expr :=
match id.inq.to_comp, id.inq.to_slope with
| comp.gt, slope.some m :=
if bnot (m = 1) then fail "reconstruct_strict_ineq_self failed: given non-one slope"
else do idp ← id.prf.reconstruct,
mk_app ``gt_self_contr [idp]
| comp.lt, slope.some m :=
if bnot (m = 1) then fail "reconstruct_strict_ineq_self failed: given non-one slope"
else do idp ← id.prf.reconstruct,
mk_app ``lt_self_contr [idp]
| _, _ := fail "reconstruct_strict_ineq_self failed: given non-strict comp or non-one slope"
end
meta def reconstruct_sum_form {sfc} (sfp : sum_form_proof sfc) : tactic expr :=
if sfc.is_contr then do
zltz ← sfp.reconstruct,
mk_mapp ``lt_irrefl [option.none, option.none, option.none, some zltz]
else fail "reconstruct_sum_form requires proof of 0 < 0"
meta def reconstruct : contrad → tactic expr
| none := fail "cannot reconstruct contr: no contradiction is known"
| (@eq_diseq lhs rhs ed dd) := reconstruct_eq_diseq ed dd
| (@ineqs lhs rhs ii id) := reconstruct_ineqs reconstruct ii id
| (@sign e sd1 sd2) := reconstruct_sign sd1 sd2
| (@strict_ineq_self e id) := reconstruct_strict_ineq_self id
| (@sum_form _ sfp) := reconstruct_sum_form sfp
end contrad
namespace prod_form_proof
/-private meta def mk_prod_ne_zero_prf_aux : expr → list (Σ e : expr, sign_proof e gen_comp.ne) → tactic expr
| e [] := return e
| e (⟨e', sp⟩::t) := do ene ← sp.reconstruct, pf ← mk_app ``mul_ne_zero [e, ene], mk_prod_ne_zero_prf_aux pf t
private meta def mk_prod_ne_zero_prf (c : ℚ) : list (Σ e : expr, sign_proof e gen_comp.ne) → tactic expr
| [] := if c = 0 then fail "mk_prod_ne_zero_prf failed, c = 0" else mk_app ``fake_ne_zero_pf [`(c)]
| (⟨e, sp⟩::t) :=
if c = 0 then fail "mk_prod_ne_zero_prf failed, c = 0" else
do cprf ← mk_app ``fake_ne_zero_pf [`(c)],
hpf ← sp.reconstruct,
prodprf ← mk_prod_ne_zero_prf_aux hpf t,
mk_app ``mul_ne_zero [hpf, prodprf]
-/
/-#check spec_comp_and_flipped_of_comp
-- not finished: need to orient c
private meta def reconstruct_of_ineq_proof_pos_lhs {lhs rhs iq} (id : ineq_proof lhs rhs iq)
(sp : sign_proof lhs gen_comp.gt) (nzprs : hash_map expr (λ e, sign_proof e gen_comp.ne)) : tactic expr :=
match (spec_comp_and_flipped_of_comp iq.to_comp), iq.to_slope with
| _, slope.horiz := fail "reconstruct_of_ineq_proof_pos_lhs failed, cannot make a prod_form with 0 slope"
| (c, flipped), slope.some m :=
if m = 0 then fail "reconstruct_of_ineq_proof_pos_lhs failed, cannot make a prod_form with 0 slope"
else do -- lhs c m*rhs --> 1 c m*(lhs⁻¹*rhs)
idp ← id.reconstruct,
spp ← sp.reconstruct,
opp ← mk_app ``one_op_inv_mul_of_op_of_pos [idp, spp], -- 1 r lhs⁻¹*rhs
if bnot flipped then
return opp
else do
mprf ← mk_sign_pf m,
failed
end-/
private meta def reconstruct_of_ineq_proof_aux {lhs rhs iq c1 c2} (id : ineq_proof lhs rhs iq)
(spl : sign_proof lhs c1) (spr : sign_proof rhs c2) (fail_cond : ℚ → bool)
(unflipped_name flipped_name : name) --flipped_lt_name flipped_le_name : name)
: tactic expr :=
match (spec_comp_and_flipped_of_comp iq.to_comp), iq.to_slope with
| _, slope.horiz := fail "reconstruct_of_ineq_proof_pos_pos failed, cannot make a prod_form with 0 slope"
| (c, flipped), slope.some m := --trace "okay, roipa" >> trace flipped >> trace iq >>
if fail_cond m then fail "reconstruct_of_ineq_proof_aux failed check"
else do
idp ← id.reconstruct, --trace "idp_type:", infer_type idp >>= trace,
splp ← spl.reconstruct, --trace "splp_type:", infer_type splp >>= trace, trace "c1 is:", trace c1, trace spl,
opp ← mk_app unflipped_name [idp, splp],
--trace "opp", infer_type opp >>= trace,
if bnot flipped then return opp
else do
msgn ← mk_sign_pf m,
sprp ← spr.reconstruct,
trace "HERE", infer_type opp >>= trace, infer_type splp >>= trace, infer_type sprp >>= trace, infer_type msgn >>= trace, trace unflipped_name, trace iq,
mk_app flipped_name-- (if c=spec_comp.lt then flipped_lt_name else flipped_le_name)
[opp, splp, sprp, msgn]
end
private meta def reconstruct_of_ineq_proof_pos_pos {lhs rhs iq} (id : ineq_proof lhs rhs iq)
(spl : sign_proof lhs gen_comp.gt) (spr : sign_proof rhs gen_comp.gt) : tactic expr :=
reconstruct_of_ineq_proof_aux id spl spr (λ m, m ≤ 0)
``one_op_inv_mul_of_op_of_pos ``one_op_inv_mul_of_lt_of_pos_pos_flipped' -- ``one_le_inv_mul_of_le_of_pos_pos_flipped
/-match (spec_comp_and_flipped_of_comp iq.to_comp), iq.to_slope with
| _, slope.horiz := fail "reconstruct_of_ineq_proof_pos_pos failed, cannot make a prod_form with 0 slope"
| (c, flipped), slope.some m :=
if m ≤ 0 then fail "reconstruct_of_ineq_proof_pos_pos failed, m ≤ 0"
else do
idp ← id.reconstruct,
splp ← spl.reconstruct,
opp ← mk_app ``one_op_inv_mul_of_op_of_pos [idp, splp],
if bnot flipped then return opp
else do
msgn ← mk_sign_pf m,
sprp ← spr.reconstruct,
mk_app (if c=spec_comp.lt then ``one_lt_inv_mul_of_lt_of_pos_flipped
else ``one_le_inv_mul_of_le_of_pos_flipped)
[opp, splp, sprp, msgn]
end-/
private meta def reconstruct_of_ineq_proof_pos_neg {lhs rhs iq} (id : ineq_proof lhs rhs iq)
(spl : sign_proof lhs gen_comp.gt) (spr : sign_proof rhs gen_comp.lt) : tactic expr :=
reconstruct_of_ineq_proof_aux id spl spr (λ m, m ≥ 0)
``one_op_inv_mul_of_op_of_pos ``one_op_inv_mul_of_lt_of_pos_neg_flipped -- ``one_le_inv_mul_of_le_of_pos_neg_flipped
private meta def reconstruct_of_ineq_proof_neg_pos {lhs rhs iq} (id : ineq_proof lhs rhs iq)
(spl : sign_proof lhs gen_comp.lt) (spr : sign_proof rhs gen_comp.gt) : tactic expr :=
reconstruct_of_ineq_proof_aux id spl spr (λ m, m ≥ 0)
``one_op_inv_mul_of_op_of_neg ``one_op_inv_mul_of_lt_of_neg_pos_flipped -- ``one_le_inv_mul_of_le_of_neg_flipped
private meta def reconstruct_of_ineq_proof_neg_neg {lhs rhs iq} (id : ineq_proof lhs rhs iq)
(spl : sign_proof lhs gen_comp.lt) (spr : sign_proof rhs gen_comp.lt) : tactic expr :=
reconstruct_of_ineq_proof_aux id spl spr (λ m, m ≤ 0)
``one_op_inv_mul_of_op_of_neg ``one_op_inv_mul_of_lt_of_neg_neg_flipped
/-
pos_neg
cmatch (spec_comp_and_flipped_of_comp iq.to_comp), iq.to_slope with
| _, slope.horiz := fail "reconstruct_of_ineq_proof_pos_pos failed, cannot make a prod_form with 0 slope"
| (c, flipped), slope.some m :=
if m ≥ 0 then fail "reconstruct_of_ineq_proof_pos_neg failed, m ≥ 0"
else do
idp ← id.reconstruct,
splp ← spl.reconstruct,
opp ← mk_app ``one_op_inv_mul_of_op_of_pos [idp, splp],
if bnot flipped then return opp
else do
msgn ← mk_sign_pf m,
sprp ← spr.reconstruct,
mk_app (if c=spec_comp.lt then ``one_lt_inv_mul_of_lt_of_pos_flipped
else ``one_le_inv_mul_of_le_of_pos_flipped)
[opp, splp, sprp, msgn]
end -/
private meta def reconstruct_of_ineq_proof {lhs rhs iq} (id : ineq_proof lhs rhs iq) :
Π {cl cr}, sign_proof lhs cl → sign_proof rhs cr → tactic expr
| gen_comp.gt gen_comp.gt spl spr := reconstruct_of_ineq_proof_pos_pos id spl spr
| gen_comp.gt gen_comp.lt spl spr := reconstruct_of_ineq_proof_pos_neg id spl spr
| gen_comp.lt gen_comp.gt spl spr := reconstruct_of_ineq_proof_neg_pos id spl spr
| gen_comp.lt gen_comp.lt spl spr := reconstruct_of_ineq_proof_neg_neg id spl spr
| _ _ _ _ := fail "reconstruct_of_ineq_proof failed, need to know signs of components"
/-
-- TODO
private meta def reconstruct_of_ineq_proof_neg_lhs {lhs rhs iq} (id : ineq_proof lhs rhs iq)
(sp : sign_proof lhs gen_comp.lt) (nzprs : hash_map expr (λ e, sign_proof e gen_comp.ne)) : tactic expr :=
match iq.to_slope with
| slope.horiz := fail "reconstruct_of_ineq_proof_neg_lhs failed, cannot make a prod_form with 0 slope"
| slope.some m :=
if m = 0 then fail "reconstruct_of_ineq_proof_pos_lhs failed, cannot make a prod_form with 0 slope"
else
failed
end-/
private meta def reconstruct_of_eq_proof {lhs rhs c} (id : eq_proof lhs rhs c)
(lhsne : sign_proof lhs gen_comp.ne) : tactic expr :=
if c = 0 then fail "reconstruct_of_eq_proof failed, cannot make a prod_form with 0 slope"
else do
lhsnep ← lhsne.reconstruct,
idpf ← id.reconstruct,
mk_app ``one_eq_div_of_eq [idpf, lhsnep]
theorem reconstruct_of_expr_def_aux (P : Prop) : P := sorry
/-
-- TODO
private meta def reconstruct_of_expr_def (e : expr) (sf : sum_form) : tactic expr :=
do tp ← sum_form.to_expr sf,
tp' ← to_expr ``(%%tp = 0),
-- (_, pf) ← solve_aux tp' (simp >> done),
mk_app ``reconstruct_of_expr_def_aux [tp']
-- instantiate_mvars pf
--fail "reconstruct_of_expr_def failed, not implemented yet"
-/
-- TODO (alg_nom)
private meta def reconstruct_of_expr_def (e : expr) (pf : prod_form) : tactic expr :=
do --trace "in reconstruct_of_expr_def",
tp ← prod_form.to_expr pf,
-- trace "tp:", trace tp,
tp' ← to_expr ``(1 = %%tp),
-- trace "tp':", trace tp',
-- (_, pf) ← solve_aux tp' (simp >> done),
mk_app ``reconstruct_of_expr_def_aux [tp']
section
variable (rct : Π {pfc}, prod_form_proof pfc → tactic expr)
-- Given an expr of the form e := (p1^e1)^k, produces a proof that
-- e = p1^(e1*k)
private meta def simp_pow_aux_aux (p e k : expr) : tactic expr :=
mk_app ``rat.pow_pow [p, e, k]
/-private meta def simp_pow_aux_aux : expr → tactic expr
| `(rat.pow (rat.pow %%p %%e) %%k) := mk_app ``rat.pow_pow [p, e, k]
| _ := failed
-/
-- Given an expr of the form e := (p1^e1*...*pn^en)^k, produces a proof that
-- e = (p1^(e1*k) * ... * pn^(en*k)
private meta def simp_pow_aux : expr → tactic expr | e :=
match e with
| `(rat.pow (%%a * (rat.pow %%b %%n)) %%k) :=
let prod' := `(rat.pow %%a %%k) in
do prod_pf ← simp_pow_aux prod',
pow_pf ← mk_app ``rat.mul_pow [a, `(rat.pow %%b %%n), k],
one_pow_pf ← simp_pow_aux_aux b n k,
-- trace "doing rewrite",
-- infer_type pow_pf >>= trace, trace e,
(e', pf1, []) ← rewrite pow_pf e,
(e'', pf2, []) ← rewrite one_pow_pf e',
(e''', pf3, []) ← rewrite prod_pf e'',
t1 ← mk_app ``eq.trans [pf1, pf2],
mk_app ``eq.trans [t1, pf3]
| `(rat.pow (rat.pow %%a %%n) %%k) :=
simp_pow_aux_aux a n k
| e := do f ← pp e, fail $ "simp_pow_aux failed on " ++ f.to_string
end
-- Given an expr of the form e := (c*(p1^e1*...*pn^en))^k, produces a proof that
-- e = c^k * (p1^(e1*k) * ... * pn^(en*k))
meta def simp_pow (e : expr) : tactic expr :=
--do trace "simp pow called on:", trace e,
match e with
| `(rat.pow (%%coeff * %%prod) %%k) :=
let prod' := `(rat.pow %%prod %%k) in
do prod_pf ← simp_pow_aux prod',
pow_pf ← mk_app ``rat.mul_pow [coeff, prod, k],
--trace "doing rewrite",
(e', pf1, []) ← rewrite pow_pf e,
(e'', pf2, []) ← rewrite prod_pf e',
mk_app ``eq.trans [pf1, pf2]
| _ := fail "simp_pow got malformed arg"
end
/-example (a b c : ℚ) (m n k : ℤ) : rat.pow (a * (rat.pow b m * rat.pow c n)) k = rat.pow a k * (rat.pow b (m*k) * rat.pow c (n*k)) :=
by do
(lhs, rhs) ← target >>= match_eq,
e ← simp_pow lhs,
infer_type e >>= trace,
exact e-/
private meta def simp_pow_expr (pf tgt : expr) : tactic expr :=
do sls ← (simp_lemmas.mk.add_simp ``rat.mul_pow_rev) >>= λ t, t.add pf,
--trace "target", trace tgt,
--trace "pf tp", infer_type pf >>= trace,
(do (_, npf) ← simplify sls [] tgt,-- <|> do rpr ← to_expr ``(eq.refl %%tgt), return (`(()), rpr),
--(_, npf) ← solve_aux tgt (simp_target sls >> done),
return npf) <|> to_expr ``(eq.refl %%tgt)
meta def simp_lemmas.add_simp_list : simp_lemmas → list name → tactic simp_lemmas
| s [] := return s
| s (h::t) := s.add_simp h >>= λ s', simp_lemmas.add_simp_list s' t
private meta def simp_pow_expr' (tgt : expr) : tactic expr :=
do --sls ← (simp_lemmas.mk.add_simp ``rat.mul_pow) >>= (λ s, simp_lemmas.add_simp s ``rat.pow_one) >>= (λ s, simp_lemmas.add_simp s ``rat.pow_neg_one),
sls ← simp_lemmas.add_simp_list simp_lemmas.mk [``rat.mul_pow, ``rat.pow_one, ``rat.pow_neg_one, ``rat.one_pow, ``rat.pow_pow, ``rat.one_div_pow],
--trace "target", trace tgt,
-- trace "pf tp", infer_type pf >>= trace,
-- (do (_, npf) ← simplify sls [] tgt,-- <|> do rpr ← to_expr ``(eq.refl %%tgt), return (`(()), rpr),
(_, npf) ← solve_aux tgt ( /-trace_state >>-/ simp_target sls >>/- trace "!!!" >> trace_state >>-/ reflexivity), -- `[simp [rat.mul_pow_rev, rat.pow_one], done],
return npf
section
open expr
private meta def reconstruct_of_pow_pos {pfc} (z : ℤ) (pfp : prod_form_proof pfc) : tactic expr :=
if z ≤ 0 then fail "reconstruct_of_pow_pos failed, given negative exponent" else
do zsn ← mk_int_sign_pf z,
pf1 ← rct pfp,
--trace "here", /-trace pfc,-/ trace pfp, trace z, infer_type pf1 >>= trace,
pf2 ← mk_mapp (if pfc.c = spec_comp.lt then ``lt_pos_pow' else ``le_pos_pow') [none, pf1, none, zsn],
--trace "pf2tp", infer_type pf2 >>= trace,
pf2tp ← infer_type pf2,
match pf2tp with
| (app (app (app o i) lhs) rhs) :=
do eqp ← simp_pow rhs,
(new_type, prf, []) ← rewrite eqp pf2tp,
mk_eq_mp prf pf2
-- failed
| _ := fail "reconstruct_of_pow_pos failed"
end
/-
match pf2tp with
| app (app (app o i) lhs) rhs := do tgt ← prod_form.to_expr (pfc.pf.pow z), pf ← to_expr ``(%%rhs = %%tgt) >>= simp_pow_expr',
trace "pf2tp", trace pf2tp, trace "pftp", infer_type pf >>= trace,
trace "o", trace o,
-- trace `(%%o %%lhs %%tgt),
tgt' ← return $ app (app (app o i) lhs) tgt,--to_expr ``(%%o %%lhs %%tgt),
trace "new tgt:", trace tgt',
pf1 ← to_expr ``(eq.symm %%pf),
(_, pf') ← solve_aux tgt' (rewrite_target pf1 >> apply pf2),
trace "proved", infer_type pf' >>= trace,
return pf'
| _ := failed
end
-- tgt ← prod_form.to_expr (pfc.pf.pow z),
-- simp_pow_expr pf2 tgt -/
end
/-private meta def reconstruct_of_pow_neg {pfc} (z : ℤ) (pfp : prod_form_proof pfc) : tactic expr :=
if z ≥ 0 then fail "reconstruct_of_pow_neg failed, given positive exponent" else
failed-/
private meta def reconstruct_of_pow_eq {pfc} (z : ℤ) (pfp : prod_form_proof pfc) : tactic expr :=
do --trace "pfp is:", trace pfp,
pf1 ← rct pfp, --trace "reconstructed", infer_type pf1 >>= trace,
tpf ← mk_app ``eq_pow [pf1, `(z)],
tpf' ← mk_app ``eq_pow' [tpf],
tpf_tp ← infer_type tpf',
tgt ← prod_form.to_expr (pfc.pf.pow z),
--trace "target is:", trace tgt,
tgt' ← to_expr ``(1 = %%tgt),
--trace "tgt', tpf", trace tgt', infer_type tpf >>= trace,
(_, pf') ← solve_aux tgt' (assertv `h tpf_tp tpf' >> `[simp only [rat.mul_pow, rat.pow_pow], simp only [rat.mul_pow, rat.pow_pow] at h, apply h] >> done),
return pf'
-- simp_pow_expr tpf tgt
private meta def reconstruct_of_pow {pfc} (z : ℤ) (pfp : prod_form_proof pfc) : tactic expr :=
if pfc.c = spec_comp.eq then reconstruct_of_pow_eq @rct z pfp else reconstruct_of_pow_pos @rct z pfp
private theorem reconstruct_of_mul_aux (P : Prop) {Q R : Prop} : Q → R → P := sorry
private meta def reconstruct_of_mul (rct : Π {pfc}, prod_form_proof pfc → tactic expr)
{lhs rhs c1 c2} (pfp1 : prod_form_proof ⟨lhs, c1⟩) (pfp2 : prod_form_proof ⟨rhs, c2⟩)
(sgns : list Σ e : expr, sign_proof e gen_comp.ne) : tactic expr :=
let prod := lhs * rhs in
do /-trace "in reconstruct_of_mul",
trace prod,-/
tp ← prod_form.to_expr prod,
--trace tp,
tp' ← (spec_comp.strongest c1 c2).to_comp.to_function `(1 : ℚ) tp,
--trace tp',
pf1 ← rct pfp1, pf2 ← rct pfp2,-- trace "**",
mk_mapp ``reconstruct_of_mul_aux [tp', none, none, pf1, pf2]
/-
let sum := lhs + rhs.scale m in
do tp ← sum_form.to_expr sum,
tp' ← (spec_comp.strongest c1 c2).to_comp.to_function tp `(0 : ℚ),
pf1 ← sfrc sfpl, pf2 ← sfrc sfpr,
mk_mapp ``reconstruct_of_add_factor_aux [some tp', none, none, some pf1, some pf2]
-/
end
meta def reconstruct : Π {pfc}, prod_form_proof pfc → tactic expr
--| .(_) (@of_ineq_proof_pos_lhs _ _ _ id sp nzprs) := reconstruct_of_ineq_proof_pos_lhs id sp nzprs
--| .(_) (@of_ineq_proof_neg_lhs _ _ _ id sp nzprs) := reconstruct_of_ineq_proof_neg_lhs id sp nzprs
| .(_) (@of_ineq_proof _ _ _ _ _ id spl spr) := reconstruct_of_ineq_proof id spl spr
| .(_) (@of_eq_proof _ _ _ id lhsne) := reconstruct_of_eq_proof id lhsne
| .(_) (@of_expr_def e pf) := reconstruct_of_expr_def e pf
| .(_) (@of_pow _ z pfp) := reconstruct_of_pow @reconstruct z pfp
| .(_) (@of_mul _ _ _ _ pfp1 pfp2 sgns) := reconstruct_of_mul @reconstruct pfp1 pfp2 sgns
| .(_) (adhoc _ _ t) := t
| .(_) (fake _) := fail "prod_form_proof.reconstruct failed: cannot reconstruct fake"
end prod_form_proof
end polya
|
0f7270c23bff0819dea029227b2f8ccb07a76781 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/tactic/omega/prove_unsats.lean | ca25905d42176c242d5fbe9539f4fe9f30766092 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,101 | lean | /-
Copyright (c) 2019 Seul Baek. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Seul Baek
-/
/-
A tactic which constructs exprs to discharge
goals of the form `clauses.unsat cs`.
-/
import tactic.omega.find_ees
import tactic.omega.find_scalars
import tactic.omega.lin_comb
namespace omega
open tactic
/-- Return expr of proof that given int is negative -/
meta def prove_neg : int → tactic expr
| (int.of_nat _) := failed
| -[1+ m] := return `(int.neg_succ_lt_zero %%`(m))
lemma forall_mem_replicate_zero_eq_zero (m : nat) :
(∀ x ∈ (list.replicate m (0 : int)), x = (0 : int)) :=
λ x, list.eq_of_mem_replicate
/-- Return expr of proof that elements of (replicate is.length 0) are all 0 -/
meta def prove_forall_mem_eq_zero (is : list int) : tactic expr :=
return `(forall_mem_replicate_zero_eq_zero is.length)
/-- Return expr of proof that the combination of linear constraints
represented by ks and ts is unsatisfiable -/
meta def prove_unsat_lin_comb (ks : list nat) (ts : list term) : tactic expr :=
let ⟨b,as⟩ := lin_comb ks ts in
do x1 ← prove_neg b,
x2 ← prove_forall_mem_eq_zero as,
to_expr ``(unsat_lin_comb_of %%`(ks) %%`(ts) %%x1 %%x2)
/-- Given a (([],les) : clause), return the expr of a term (t : clause.unsat ([],les)). -/
meta def prove_unsat_ef : clause → tactic expr
| ((_::_), _) := failed
| ([], les) :=
do ks ← find_scalars les,
x ← prove_unsat_lin_comb ks les,
return `(unsat_of_unsat_lin_comb %%`(ks) %%`(les) %%x)
/-- Given a (c : clause), return the expr of a term (t : clause.unsat c) -/
meta def prove_unsat (c : clause) : tactic expr :=
do ee ← find_ees c,
x ← prove_unsat_ef (eq_elim ee c),
return `(unsat_of_unsat_eq_elim %%`(ee) %%`(c) %%x)
/-- Given a (cs : list clause), return the expr of a term (t : clauses.unsat cs) -/
meta def prove_unsats : list clause → tactic expr
| [] := return `(clauses.unsat_nil)
| (p::ps) :=
do x ← prove_unsat p,
xs ← prove_unsats ps,
to_expr ``(clauses.unsat_cons %%`(p) %%`(ps) %%x %%xs)
end omega
|
e3fdad5b45f85c3850e3364b78dd2058da4a90a0 | b70031c8e2c5337b91d7e70f1e0c5f528f7b0e77 | /src/category_theory/sites/sieves.lean | 62408583b148017cd5b9b0014ab4adcfae43855b | [
"Apache-2.0"
] | permissive | molodiuc/mathlib | cae2ba3ef1601c1f42ca0b625c79b061b63fef5b | 98ebe5a6739fbe254f9ee9d401882d4388f91035 | refs/heads/master | 1,674,237,127,059 | 1,606,353,533,000 | 1,606,353,533,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,464 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, E. W. Ayers
-/
import category_theory.over
import category_theory.limits.shapes.finite_limits
import category_theory.yoneda
import order.complete_lattice
import data.set.lattice
/-!
# Theory of sieves
- For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X`
which is closed under left-composition.
- The complete lattice structure on sieves is given, as well as the Galois insertion
given by downward-closing.
- A `sieve X` (functorially) induces a presheaf on `C` together with a monomorphism to
the yoneda embedding of `X`.
## Tags
sieve, pullback
-/
universes v u
namespace category_theory
variables {C : Type u} [category.{v} C]
variables {X Y Z : C} (f : Y ⟶ X)
/-- A set of arrows all with codomain `X`. -/
@[derive complete_lattice]
def presieve (X : C) := Π ⦃Y⦄, set (Y ⟶ X)
namespace presieve
instance : inhabited (presieve X) := ⟨⊤⟩
/--
Given a set of arrows `S` all with codomain `X`, and a set of arrows with codomain `Y` for each
`f : Y ⟶ X` in `S`, produce a set of arrows with codomain `X`:
`{ g ≫ f | (f : Y ⟶ X) ∈ S, (g : Z ⟶ Y) ∈ R f }`.
-/
def bind (S : presieve X) (R : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → presieve Y) :
presieve X :=
λ Z h, ∃ (Y : C) (g : Z ⟶ Y) (f : Y ⟶ X) (H : S f), R H g ∧ g ≫ f = h
@[simp]
lemma bind_comp {S : presieve X}
{R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → presieve Y} {g : Z ⟶ Y} (h₁ : S f) (h₂ : R h₁ g) :
bind S R (g ≫ f) :=
⟨_, _, _, h₁, h₂, rfl⟩
/-- The singleton presieve. -/
-- Note we can't make this into `has_singleton` because of the out-param.
def singleton : presieve X :=
λ Z g, ∃ (H : Z = Y), eq_to_hom H ≫ f = g
@[simp] lemma singleton_eq_iff_domain (f g : Y ⟶ X) : singleton f g ↔ f = g :=
begin
split,
{ rintro ⟨_, rfl⟩,
apply (category.id_comp _).symm },
{ rintro rfl,
exact ⟨rfl, category.id_comp _⟩ },
end
lemma singleton_self : singleton f f := (singleton_eq_iff_domain _ _).2 rfl
end presieve
/--
For an object `X` of a category `C`, a `sieve X` is a set of morphisms to `X` which is closed under
left-composition.
-/
structure sieve {C : Type u} [category.{v} C] (X : C) :=
(arrows : presieve X)
(downward_closed' : ∀ {Y Z f} (hf : arrows f) (g : Z ⟶ Y), arrows (g ≫ f))
namespace sieve
instance {X : C} : has_coe_to_fun (sieve X) := ⟨_, sieve.arrows⟩
variables {S R : sieve X}
@[simp, priority 100] lemma downward_closed (S : sieve X) {f : Y ⟶ X} (hf : S f)
(g : Z ⟶ Y) : S (g ≫ f) :=
S.downward_closed' hf g
lemma arrows_ext : Π {R S : sieve X}, R.arrows = S.arrows → R = S
| ⟨Ra, _⟩ ⟨Sa, _⟩ rfl := rfl
@[ext]
protected lemma ext {R S : sieve X}
(h : ∀ ⦃Y⦄ (f : Y ⟶ X), R f ↔ S f) :
R = S :=
arrows_ext $ funext $ λ x, funext $ λ f, propext $ h f
protected lemma ext_iff {R S : sieve X} :
R = S ↔ (∀ ⦃Y⦄ (f : Y ⟶ X), R f ↔ S f) :=
⟨λ h Y f, h ▸ iff.rfl, sieve.ext⟩
open lattice
/-- The supremum of a collection of sieves: the union of them all. -/
protected def Sup (𝒮 : set (sieve X)) : (sieve X) :=
{ arrows := λ Y, {f | ∃ S ∈ 𝒮, sieve.arrows S f},
downward_closed' := λ Y Z f, by { rintro ⟨S, hS, hf⟩ g, exact ⟨S, hS, S.downward_closed hf _⟩ } }
/-- The infimum of a collection of sieves: the intersection of them all. -/
protected def Inf (𝒮 : set (sieve X)) : (sieve X) :=
{ arrows := λ Y, {f | ∀ S ∈ 𝒮, sieve.arrows S f},
downward_closed' := λ Y Z f hf g S H, S.downward_closed (hf S H) g }
/-- The union of two sieves is a sieve. -/
protected def union (S R : sieve X) : sieve X :=
{ arrows := λ Y f, S f ∨ R f,
downward_closed' := by { rintros Y Z f (h | h) g; simp [h] } }
/-- The intersection of two sieves is a sieve. -/
protected def inter (S R : sieve X) : sieve X :=
{ arrows := λ Y f, S f ∧ R f,
downward_closed' := by { rintros Y Z f ⟨h₁, h₂⟩ g, simp [h₁, h₂] } }
/--
Sieves on an object `X` form a complete lattice.
We generate this directly rather than using the galois insertion for nicer definitional properties.
-/
instance : complete_lattice (sieve X) :=
{ le := λ S R, ∀ ⦃Y⦄ (f : Y ⟶ X), S f → R f,
le_refl := λ S f q, id,
le_trans := λ S₁ S₂ S₃ S₁₂ S₂₃ Y f h, S₂₃ _ (S₁₂ _ h),
le_antisymm := λ S R p q, sieve.ext (λ Y f, ⟨p _, q _⟩),
top := { arrows := λ _, set.univ, downward_closed' := λ Y Z f g h, ⟨⟩ },
bot := { arrows := λ _, ∅, downward_closed' := λ _ _ _ p _, false.elim p },
sup := sieve.union,
inf := sieve.inter,
Sup := sieve.Sup,
Inf := sieve.Inf,
le_Sup := λ 𝒮 S hS Y f hf, ⟨S, hS, hf⟩,
Sup_le := λ ℰ S hS Y f, by { rintro ⟨R, hR, hf⟩, apply hS R hR _ hf },
Inf_le := λ _ _ hS _ _ h, h _ hS,
le_Inf := λ _ _ hS _ _ hf _ hR, hS _ hR _ hf,
le_sup_left := λ _ _ _ _, or.inl,
le_sup_right := λ _ _ _ _, or.inr,
sup_le := λ _ _ _ a b _ _ hf, hf.elim (a _) (b _),
inf_le_left := λ _ _ _ _, and.left,
inf_le_right := λ _ _ _ _, and.right,
le_inf := λ _ _ _ p q _ _ z, ⟨p _ z, q _ z⟩,
le_top := λ _ _ _ _, trivial,
bot_le := λ _ _ _, false.elim }
/-- The maximal sieve always exists. -/
instance sieve_inhabited : inhabited (sieve X) := ⟨⊤⟩
@[simp]
lemma mem_Inf {Ss : set (sieve X)} {Y} (f : Y ⟶ X) :
Inf Ss f ↔ ∀ (S : sieve X) (H : S ∈ Ss), S f :=
iff.rfl
@[simp]
lemma mem_Sup {Ss : set (sieve X)} {Y} (f : Y ⟶ X) :
Sup Ss f ↔ ∃ (S : sieve X) (H : S ∈ Ss), S f :=
iff.rfl
@[simp]
lemma mem_inter {R S : sieve X} {Y} (f : Y ⟶ X) :
(R ⊓ S) f ↔ R f ∧ S f :=
iff.rfl
@[simp]
lemma mem_union {R S : sieve X} {Y} (f : Y ⟶ X) :
(R ⊔ S) f ↔ R f ∨ S f :=
iff.rfl
@[simp]
lemma mem_top (f : Y ⟶ X) : (⊤ : sieve X) f := trivial
/-- Generate the smallest sieve containing the given set of arrows. -/
def generate (R : presieve X) : sieve X :=
{ arrows := λ Z f, ∃ Y (h : Z ⟶ Y) (g : Y ⟶ X), R g ∧ h ≫ g = f,
downward_closed' :=
begin
rintro Y Z _ ⟨W, g, f, hf, rfl⟩ h,
exact ⟨_, h ≫ g, _, hf, by simp⟩,
end }
lemma mem_generate (R : presieve X) (f : Z ⟶ X) :
generate R f ↔ ∃ (Y : C) (h : Z ⟶ Y) (g : Y ⟶ X), R g ∧ h ≫ g = f :=
iff.rfl
/-- Given a collection of arrows with fixed codomain, -/
def bind (S : presieve X) (R : Π ⦃Y⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) : sieve X :=
{ arrows := S.bind (λ Y f h, R h),
downward_closed' :=
begin
rintro Y Z f ⟨W, f, h, hh, hf, rfl⟩ g,
exact ⟨_, g ≫ f, _, hh, by simp [hf]⟩,
end }
open order lattice
lemma sets_iff_generate (R : presieve X) (S : sieve X) :
generate R ≤ S ↔ R ≤ S :=
⟨λ H Y g hg, H _ ⟨_, 𝟙 _, _, hg, category.id_comp _⟩,
λ ss Y f,
begin
rintro ⟨Z, f, g, hg, rfl⟩,
exact S.downward_closed (ss Z hg) f,
end⟩
/-- Show that there is a galois insertion (generate, set_over). -/
def gi_generate : galois_insertion (generate : presieve X → sieve X) arrows :=
{ gc := sets_iff_generate,
choice := λ 𝒢 _, generate 𝒢,
choice_eq := λ _ _, rfl,
le_l_u := λ S Y f hf, ⟨_, 𝟙 _, _, hf, category.id_comp _⟩ }
lemma le_generate (R : presieve X) : R ≤ generate R :=
gi_generate.gc.le_u_l R
/-- If the identity arrow is in a sieve, the sieve is maximal. -/
lemma id_mem_iff_eq_top : S (𝟙 X) ↔ S = ⊤ :=
⟨λ h, top_unique $ λ Y f _, by simpa using downward_closed _ h f,
λ h, h.symm ▸ trivial⟩
/-- If an arrow set contains a split epi, it generates the maximal sieve. -/
lemma generate_of_contains_split_epi {R : presieve X} (f : Y ⟶ X) [split_epi f]
(hf : R f) : generate R = ⊤ :=
begin
rw ← id_mem_iff_eq_top,
exact ⟨_, section_ f, f, hf, by simp⟩,
end
@[simp]
lemma generate_of_singleton_split_epi (f : Y ⟶ X) [split_epi f] :
generate (presieve.singleton f) = ⊤ :=
generate_of_contains_split_epi f (presieve.singleton_self _)
@[simp]
lemma generate_top : generate (⊤ : presieve X) = ⊤ :=
generate_of_contains_split_epi (𝟙 _) ⟨⟩
/-- Given a morphism `h : Y ⟶ X`, send a sieve S on X to a sieve on Y
as the inverse image of S with `_ ≫ h`.
That is, `sieve.pullback S h := (≫ h) '⁻¹ S`. -/
def pullback (h : Y ⟶ X) (S : sieve X) : sieve Y :=
{ arrows := λ Y sl, S (sl ≫ h),
downward_closed' := λ Z W f g h, by simp [g] }
@[simp] lemma mem_pullback (h : Y ⟶ X) {f : Z ⟶ Y} :
(S.pullback h) f ↔ S (f ≫ h) := iff.rfl
@[simp]
lemma pullback_id : S.pullback (𝟙 _) = S :=
by simp [sieve.ext_iff]
@[simp]
lemma pullback_top {f : Y ⟶ X} : (⊤ : sieve X).pullback f = ⊤ :=
top_unique (λ _ g, id)
lemma pullback_comp {f : Y ⟶ X} {g : Z ⟶ Y} (S : sieve X) :
S.pullback (g ≫ f) = (S.pullback f).pullback g :=
by simp [sieve.ext_iff]
@[simp]
lemma pullback_inter {f : Y ⟶ X} (S R : sieve X) :
(S ⊓ R).pullback f = S.pullback f ⊓ R.pullback f :=
by simp [sieve.ext_iff]
lemma pullback_eq_top_iff_mem (f : Y ⟶ X) : S f ↔ S.pullback f = ⊤ :=
by rw [← id_mem_iff_eq_top, mem_pullback, category.id_comp]
lemma pullback_eq_top_of_mem (S : sieve X) {f : Y ⟶ X} : S f → S.pullback f = ⊤ :=
(pullback_eq_top_iff_mem f).1
/--
Push a sieve `R` on `Y` forward along an arrow `f : Y ⟶ X`: `gf : Z ⟶ X` is in the sieve if `gf`
factors through some `g : Z ⟶ Y` which is in `R`.
-/
def pushforward (f : Y ⟶ X) (R : sieve Y) : sieve X :=
{ arrows := λ Z gf, ∃ g, g ≫ f = gf ∧ R g,
downward_closed' := λ Z₁ Z₂ g ⟨j, k, z⟩ h, ⟨h ≫ j, by simp [k], by simp [z]⟩ }
@[simp]
lemma mem_pushforward_of_comp {R : sieve Y} {Z : C} {g : Z ⟶ Y} (hg : R g) (f : Y ⟶ X) :
R.pushforward f (g ≫ f) :=
⟨g, rfl, hg⟩
lemma pushforward_comp {f : Y ⟶ X} {g : Z ⟶ Y} (R : sieve Z) :
R.pushforward (g ≫ f) = (R.pushforward g).pushforward f :=
sieve.ext (λ W h, ⟨λ ⟨f₁, hq, hf₁⟩, ⟨f₁ ≫ g, by simpa, f₁, rfl, hf₁⟩,
λ ⟨y, hy, z, hR, hz⟩, ⟨z, by rwa reassoc_of hR, hz⟩⟩)
lemma galois_connection (f : Y ⟶ X) : galois_connection (sieve.pushforward f) (sieve.pullback f) :=
λ S R, ⟨λ hR Z g hg, hR _ ⟨g, rfl, hg⟩, λ hS Z g ⟨h, hg, hh⟩, hg ▸ hS h hh⟩
lemma pullback_monotone (f : Y ⟶ X) : monotone (sieve.pullback f) :=
(galois_connection f).monotone_u
lemma pushforward_monotone (f : Y ⟶ X) : monotone (sieve.pushforward f) :=
(galois_connection f).monotone_l
lemma le_pushforward_pullback (f : Y ⟶ X) (R : sieve Y) :
R ≤ (R.pushforward f).pullback f :=
(galois_connection f).le_u_l _
lemma pullback_pushforward_le (f : Y ⟶ X) (R : sieve X) :
(R.pullback f).pushforward f ≤ R :=
(galois_connection f).l_u_le _
lemma pushforward_union {f : Y ⟶ X} (S R : sieve Y) :
(S ⊔ R).pushforward f = S.pushforward f ⊔ R.pushforward f :=
(galois_connection f).l_sup
lemma pushforward_le_bind_of_mem (S : presieve X)
(R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y) (f : Y ⟶ X) (h : S f) :
(R h).pushforward f ≤ bind S R :=
begin
rintro Z _ ⟨g, rfl, hg⟩,
exact ⟨_, g, f, h, hg, rfl⟩,
end
lemma le_pullback_bind (S : presieve X) (R : Π ⦃Y : C⦄ ⦃f : Y ⟶ X⦄, S f → sieve Y)
(f : Y ⟶ X) (h : S f) :
R h ≤ (bind S R).pullback f :=
begin
rw ← galois_connection f,
apply pushforward_le_bind_of_mem,
end
/-- If `f` is a monomorphism, the pushforward-pullback adjunction on sieves is coreflective. -/
def galois_coinsertion_of_mono (f : Y ⟶ X) [mono f] :
galois_coinsertion (sieve.pushforward f) (sieve.pullback f) :=
begin
apply (galois_connection f).to_galois_coinsertion,
rintros S Z g ⟨g₁, hf, hg₁⟩,
rw cancel_mono f at hf,
rwa ← hf,
end
/-- If `f` is a split epi, the pushforward-pullback adjunction on sieves is reflective. -/
def galois_insertion_of_split_epi (f : Y ⟶ X) [split_epi f] :
galois_insertion (sieve.pushforward f) (sieve.pullback f) :=
begin
apply (galois_connection f).to_galois_insertion,
intros S Z g hg,
refine ⟨g ≫ section_ f, by simpa⟩,
end
/-- A sieve induces a presheaf. -/
@[simps]
def functor (S : sieve X) : Cᵒᵖ ⥤ Type v :=
{ obj := λ Y, {g : Y.unop ⟶ X // S g},
map := λ Y Z f g, ⟨f.unop ≫ g.1, downward_closed _ g.2 _⟩ }
/--
If a sieve S is contained in a sieve T, then we have a morphism of presheaves on their induced
presheaves.
-/
@[simps]
def nat_trans_of_le {S T : sieve X} (h : S ≤ T) : S.functor ⟶ T.functor :=
{ app := λ Y f, ⟨f.1, h _ f.2⟩ }.
/-- The natural inclusion from the functor induced by a sieve to the yoneda embedding. -/
@[simps]
def functor_inclusion (S : sieve X) : S.functor ⟶ yoneda.obj X :=
{ app := λ Y f, f.1 }.
lemma nat_trans_of_le_comm {S T : sieve X} (h : S ≤ T) :
nat_trans_of_le h ≫ functor_inclusion _ = functor_inclusion _ :=
rfl
/-- The presheaf induced by a sieve is a subobject of the yoneda embedding. -/
instance functor_inclusion_is_mono : mono S.functor_inclusion :=
⟨λ Z f g h, by { ext Y y, apply congr_fun (nat_trans.congr_app h Y) y }⟩
/--
A natural transformation to a representable functor induces a sieve. This is the left inverse of
`functor_inclusion`, shown in `sieve_of_functor_inclusion`.
-/
-- TODO: Show that when `f` is mono, this is right inverse to `functor_inclusion` up to isomorphism.
def sieve_of_subfunctor {R} (f : R ⟶ yoneda.obj X) : sieve X :=
{ arrows := λ Y g, ∃ t, f.app (opposite.op Y) t = g,
downward_closed' := λ Y Z _,
begin
rintro ⟨t, rfl⟩ g,
refine ⟨R.map g.op t, _⟩,
rw functor_to_types.naturality _ _ f,
simp,
end }
@[simp]
lemma sieve_of_subfunctor_apply {R} (f : R ⟶ yoneda.obj X) (g : Y ⟶ X) :
sieve_of_subfunctor f g ↔ ∃ t, f.app (opposite.op Y) t = g :=
iff.rfl
lemma sieve_of_subfunctor_functor_inclusion : sieve_of_subfunctor S.functor_inclusion = S :=
begin
ext,
simp only [functor_inclusion_app, sieve_of_subfunctor_apply, subtype.val_eq_coe],
split,
{ rintro ⟨⟨f, hf⟩, rfl⟩,
exact hf },
{ intro hf,
exact ⟨⟨_, hf⟩, rfl⟩ }
end
instance functor_inclusion_top_is_iso : is_iso ((⊤ : sieve X).functor_inclusion) :=
{ inv := { app := λ Y a, ⟨a, ⟨⟩⟩ } }
end sieve
end category_theory
|
858f92aa8f86c0c871b8040d0259483ab0e91f33 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/algebraic_geometry/sheafed_space.lean | c7e77102ec00af989a5392817c0c266aaa31cd1c | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 5,901 | 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 algebraic_geometry.presheafed_space.has_colimits
import topology.sheaves.functors
/-!
# Sheafed spaces
Introduces the category of topological spaces equipped with a sheaf (taking values in an
arbitrary target category `C`.)
We further describe how to apply functors and natural transformations to the values of the
presheaves.
-/
universes v u
open category_theory
open Top
open topological_space
open opposite
open category_theory.limits
open category_theory.category category_theory.functor
variables (C : Type u) [category.{v} C] [limits.has_products C]
local attribute [tidy] tactic.op_induction'
namespace algebraic_geometry
/-- A `SheafedSpace C` is a topological space equipped with a sheaf of `C`s. -/
structure SheafedSpace extends PresheafedSpace C :=
(is_sheaf : presheaf.is_sheaf)
variables {C}
namespace SheafedSpace
instance coe_carrier : has_coe (SheafedSpace C) Top :=
{ coe := λ X, X.carrier }
/-- Extract the `sheaf C (X : Top)` from a `SheafedSpace C`. -/
def sheaf (X : SheafedSpace C) : sheaf C (X : Top.{v}) := ⟨X.presheaf, X.is_sheaf⟩
@[simp] lemma as_coe (X : SheafedSpace C) : X.carrier = (X : Top.{v}) := rfl
@[simp] lemma mk_coe (carrier) (presheaf) (h) :
(({ carrier := carrier, presheaf := presheaf, is_sheaf := h } : SheafedSpace.{v} C) :
Top.{v}) = carrier :=
rfl
instance (X : SheafedSpace.{v} C) : topological_space X := X.carrier.str
/-- The trivial `punit` valued sheaf on any topological space. -/
def punit (X : Top) : SheafedSpace (discrete punit) :=
{ is_sheaf := presheaf.is_sheaf_punit _,
..@PresheafedSpace.const (discrete punit) _ X punit.star }
instance : inhabited (SheafedSpace (discrete _root_.punit)) := ⟨punit (Top.of pempty)⟩
instance : category (SheafedSpace C) :=
show category (induced_category (PresheafedSpace C) SheafedSpace.to_PresheafedSpace),
by apply_instance
/-- Forgetting the sheaf condition is a functor from `SheafedSpace C` to `PresheafedSpace C`. -/
@[derive [full, faithful]]
def forget_to_PresheafedSpace : (SheafedSpace C) ⥤ (PresheafedSpace C) :=
induced_functor _
instance is_PresheafedSpace_iso {X Y : SheafedSpace C} (f : X ⟶ Y) [is_iso f] :
@is_iso (PresheafedSpace C) _ _ _ f :=
SheafedSpace.forget_to_PresheafedSpace.map_is_iso f
variables {C}
section
local attribute [simp] id comp
@[simp] lemma id_base (X : SheafedSpace C) :
((𝟙 X) : X ⟶ X).base = (𝟙 (X : Top.{v})) := rfl
lemma id_c (X : SheafedSpace C) :
((𝟙 X) : X ⟶ X).c = eq_to_hom (presheaf.pushforward.id_eq X.presheaf).symm := rfl
@[simp] lemma id_c_app (X : SheafedSpace C) (U) :
((𝟙 X) : X ⟶ X).c.app U = eq_to_hom (by { induction U using opposite.rec, cases U, refl }) :=
by { induction U using opposite.rec, cases U, simp only [id_c], dsimp, simp, }
@[simp] lemma comp_base {X Y Z : SheafedSpace C} (f : X ⟶ Y) (g : Y ⟶ Z) :
(f ≫ g).base = f.base ≫ g.base := rfl
@[simp] lemma comp_c_app {X Y Z : SheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z) (U) :
(α ≫ β).c.app U = (β.c).app U ≫ (α.c).app (op ((opens.map (β.base)).obj (unop U)))
:= rfl
lemma comp_c_app' {X Y Z : SheafedSpace C} (α : X ⟶ Y) (β : Y ⟶ Z) (U) :
(α ≫ β).c.app (op U) = (β.c).app (op U) ≫ (α.c).app (op ((opens.map (β.base)).obj U))
:= rfl
lemma congr_app {X Y : SheafedSpace C} {α β : X ⟶ Y} (h : α = β) (U) :
α.c.app U = β.c.app U ≫ X.presheaf.map (eq_to_hom (by subst h)) :=
PresheafedSpace.congr_app h U
variables (C)
/-- The forgetful functor from `SheafedSpace` to `Top`. -/
def forget : SheafedSpace C ⥤ Top :=
{ obj := λ X, (X : Top.{v}),
map := λ X Y f, f.base }
end
open Top.presheaf
/--
The restriction of a sheafed space along an open embedding into the space.
-/
def restrict {U : Top} (X : SheafedSpace C)
{f : U ⟶ (X : Top.{v})} (h : open_embedding f) : SheafedSpace C :=
{ is_sheaf := λ ι 𝒰, ⟨is_limit.of_iso_limit
((is_limit.postcompose_inv_equiv _ _).inv_fun (X.is_sheaf _).some)
(sheaf_condition_equalizer_products.fork.iso_of_open_embedding h 𝒰).symm⟩,
..X.to_PresheafedSpace.restrict h }
/--
The restriction of a sheafed space `X` to the top subspace is isomorphic to `X` itself.
-/
def restrict_top_iso (X : SheafedSpace C) :
X.restrict (opens.open_embedding ⊤) ≅ X :=
forget_to_PresheafedSpace.preimage_iso X.to_PresheafedSpace.restrict_top_iso
/--
The global sections, notated Gamma.
-/
def Γ : (SheafedSpace C)ᵒᵖ ⥤ C :=
forget_to_PresheafedSpace.op ⋙ PresheafedSpace.Γ
lemma Γ_def : (Γ : _ ⥤ C) = forget_to_PresheafedSpace.op ⋙ PresheafedSpace.Γ := rfl
@[simp] lemma Γ_obj (X : (SheafedSpace C)ᵒᵖ) : Γ.obj X = (unop X).presheaf.obj (op ⊤) := rfl
lemma Γ_obj_op (X : SheafedSpace C) : Γ.obj (op X) = X.presheaf.obj (op ⊤) := rfl
@[simp] lemma Γ_map {X Y : (SheafedSpace C)ᵒᵖ} (f : X ⟶ Y) :
Γ.map f = f.unop.c.app (op ⊤) := rfl
lemma Γ_map_op {X Y : SheafedSpace C} (f : X ⟶ Y) :
Γ.map f.op = f.c.app (op ⊤) := rfl
noncomputable
instance [has_limits C] : creates_colimits (forget_to_PresheafedSpace : SheafedSpace C ⥤ _) :=
⟨λ J hJ, by exactI ⟨λ K, creates_colimit_of_fully_faithful_of_iso
⟨(PresheafedSpace.colimit_cocone (K ⋙ forget_to_PresheafedSpace)).X,
limit_is_sheaf _ (λ j, sheaf.pushforward_sheaf_of_sheaf _ (K.obj (unop j)).2)⟩
(colimit.iso_colimit_cocone ⟨_, PresheafedSpace.colimit_cocone_is_colimit _⟩).symm⟩⟩
instance [has_limits C] : has_colimits (SheafedSpace C) :=
has_colimits_of_has_colimits_creates_colimits forget_to_PresheafedSpace
noncomputable instance [has_limits C] : preserves_colimits (forget C) :=
limits.comp_preserves_colimits forget_to_PresheafedSpace (PresheafedSpace.forget C)
end SheafedSpace
end algebraic_geometry
|
841a9bbc1cd0e08969d35d97eb4f2c335b2aaa5a | e61a235b8468b03aee0120bf26ec615c045005d2 | /stage0/src/Init/Lean/Compiler/IR/Basic.lean | cb280fb6a688fb1084f10a68d2a6f165ffa43b38 | [
"Apache-2.0"
] | permissive | SCKelemen/lean4 | 140dc63a80539f7c61c8e43e1c174d8500ec3230 | e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc | refs/heads/master | 1,660,973,595,917 | 1,590,278,033,000 | 1,590,278,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 25,721 | 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.Data.Array
import Init.Lean.Data.KVMap
import Init.Lean.Data.Name
import Init.Lean.Data.Format
import Init.Lean.Compiler.ExternAttr
/-
Implements (extended) λPure and λRc proposed in the article
"Counting Immutable Beans", Sebastian Ullrich and Leonardo de Moura.
The Lean to IR transformation produces λPure code, and
this part is implemented in C++. The procedures described in the paper
above are implemented in Lean.
-/
namespace Lean
namespace IR
/- Function identifier -/
abbrev FunId := Name
abbrev Index := Nat
/- Variable identifier -/
structure VarId :=
(idx : Index)
/- Join point identifier -/
structure JoinPointId :=
(idx : Index)
abbrev Index.lt (a b : Index) : Bool := a < b
namespace VarId
instance : HasBeq VarId := ⟨fun a b => a.idx == b.idx⟩
instance : HasToString VarId := ⟨fun a => "x_" ++ toString a.idx⟩
instance : HasFormat VarId := ⟨fun a => toString a⟩
instance : Hashable VarId := ⟨fun a => hash a.idx⟩
end VarId
namespace JoinPointId
instance : HasBeq JoinPointId := ⟨fun a b => a.idx == b.idx⟩
instance : HasToString JoinPointId := ⟨fun a => "block_" ++ toString a.idx⟩
instance : HasFormat JoinPointId := ⟨fun a => toString a⟩
instance : Hashable JoinPointId := ⟨fun a => hash a.idx⟩
end JoinPointId
abbrev MData := KVMap
namespace MData
abbrev empty : MData := { : KVMap }
instance : HasEmptyc MData := ⟨empty⟩
end MData
/- Low Level IR types. Most are self explanatory.
- `usize` represents the C++ `size_t` Type. We have it here
because it is 32-bit in 32-bit machines, and 64-bit in 64-bit machines,
and we want the C++ backend for our Compiler to generate platform independent code.
- `irrelevant` for Lean types, propositions and proofs.
- `object` a pointer to a value in the heap.
- `tobject` a pointer to a value in the heap or tagged pointer
(i.e., the least significant bit is 1) storing a scalar value.
- `struct` and `union` are used to return small values (e.g., `Option`, `Prod`, `Except`)
on the stack.
Remark: the RC operations for `tobject` are slightly more expensive because we
first need to test whether the `tobject` is really a pointer or not.
Remark: the Lean runtime assumes that sizeof(void*) == sizeof(sizeT).
Lean cannot be compiled on old platforms where this is not True.
Since values of type `struct` and `union` are only used to return values,
We assume they must be used/consumed "linearly". We use the term "linear" here
to mean "exactly once" in each execution. That is, given `x : S`, where `S` is a struct,
then one of the following must hold in each (execution) branch.
1- `x` occurs only at a single `ret x` instruction. That is, it is being consumed by being returned.
2- `x` occurs only at a single `ctor`. That is, it is being "consumed" by being stored into another `struct/union`.
3- We extract (aka project) every single field of `x` exactly once. That is, we are consuming `x` by consuming each
of one of its components. Minor refinement: we don't need to consume scalar fields or struct/union
fields that do not contain object fields.
-/
inductive IRType
| float | uint8 | uint16 | uint32 | uint64 | usize
| irrelevant | object | tobject
| struct (leanTypeName : Option Name) (types : Array IRType) : IRType
| union (leanTypeName : Name) (types : Array IRType) : IRType
namespace IRType
partial def beq : IRType → IRType → Bool
| float, float => true
| uint8, uint8 => true
| uint16, uint16 => true
| uint32, uint32 => true
| uint64, uint64 => true
| usize, usize => true
| irrelevant, irrelevant => true
| object, object => true
| tobject, tobject => true
| struct n₁ tys₁, struct n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq
| union n₁ tys₁, union n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq
| _, _ => false
instance HasBeq : HasBeq IRType := ⟨beq⟩
def isScalar : IRType → Bool
| float => true
| uint8 => true
| uint16 => true
| uint32 => true
| uint64 => true
| usize => true
| _ => false
def isObj : IRType → Bool
| object => true
| tobject => true
| _ => false
def isIrrelevant : IRType → Bool
| irrelevant => true
| _ => false
def isStruct : IRType → Bool
| struct _ _ => true
| _ => false
def isUnion : IRType → Bool
| union _ _ => true
| _ => false
end IRType
/- Arguments to applications, constructors, etc.
We use `irrelevant` for Lean types, propositions and proofs that have been erased.
Recall that for a Function `f`, we also generate `f._rarg` which does not take
`irrelevant` arguments. However, `f._rarg` is only safe to be used in full applications. -/
inductive Arg
| var (id : VarId)
| irrelevant
namespace Arg
protected def beq : Arg → Arg → Bool
| var x, var y => x == y
| irrelevant, irrelevant => true
| _, _ => false
instance : HasBeq Arg := ⟨Arg.beq⟩
instance : Inhabited Arg := ⟨irrelevant⟩
end Arg
@[export lean_ir_mk_var_arg] def mkVarArg (id : VarId) : Arg := Arg.var id
inductive LitVal
| num (v : Nat)
| str (v : String)
def LitVal.beq : LitVal → LitVal → Bool
| LitVal.num v₁, LitVal.num v₂ => v₁ == v₂
| LitVal.str v₁, LitVal.str v₂ => v₁ == v₂
| _, _ => false
instance LitVal.HasBeq : HasBeq LitVal := ⟨LitVal.beq⟩
/- Constructor information.
- `name` is the Name of the Constructor in Lean.
- `cidx` is the Constructor index (aka tag).
- `size` is the number of arguments of type `object/tobject`.
- `usize` is the number of arguments of type `usize`.
- `ssize` is the number of bytes used to store scalar values.
Recall that a Constructor object contains a header, then a sequence of
pointers to other Lean objects, a sequence of `USize` (i.e., `size_t`)
scalar values, and a sequence of other scalar values. -/
structure CtorInfo :=
(name : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat)
def CtorInfo.beq : CtorInfo → CtorInfo → Bool
| ⟨n₁, cidx₁, size₁, usize₁, ssize₁⟩, ⟨n₂, cidx₂, size₂, usize₂, ssize₂⟩ =>
n₁ == n₂ && cidx₁ == cidx₂ && size₁ == size₂ && usize₁ == usize₂ && ssize₁ == ssize₂
instance CtorInfo.HasBeq : HasBeq CtorInfo := ⟨CtorInfo.beq⟩
def CtorInfo.isRef (info : CtorInfo) : Bool :=
info.size > 0 || info.usize > 0 || info.ssize > 0
def CtorInfo.isScalar (info : CtorInfo) : Bool :=
!info.isRef
inductive Expr
/- We use `ctor` mainly for constructing Lean object/tobject values `lean_ctor_object` in the runtime.
This instruction is also used to creat `struct` and `union` return values.
For `union`, only `i.cidx` is relevant. For `struct`, `i` is irrelevant. -/
| ctor (i : CtorInfo) (ys : Array Arg)
| reset (n : Nat) (x : VarId)
/- `reuse x in ctor_i ys` instruction in the paper. -/
| reuse (x : VarId) (i : CtorInfo) (updtHeader : Bool) (ys : Array Arg)
/- Extract the `tobject` value at Position `sizeof(void*)*i` from `x`.
We also use `proj` for extracting fields from `struct` return values, and casting `union` return values. -/
| proj (i : Nat) (x : VarId)
/- Extract the `Usize` value at Position `sizeof(void*)*i` from `x`. -/
| uproj (i : Nat) (x : VarId)
/- Extract the scalar value at Position `sizeof(void*)*n + offset` from `x`. -/
| sproj (n : Nat) (offset : Nat) (x : VarId)
/- Full application. -/
| fap (c : FunId) (ys : Array Arg)
/- Partial application that creates a `pap` value (aka closure in our nonstandard terminology). -/
| pap (c : FunId) (ys : Array Arg)
/- Application. `x` must be a `pap` value. -/
| ap (x : VarId) (ys : Array Arg)
/- Given `x : ty` where `ty` is a scalar type, this operation returns a value of Type `tobject`.
For small scalar values, the Result is a tagged pointer, and no memory allocation is performed. -/
| box (ty : IRType) (x : VarId)
/- Given `x : [t]object`, obtain the scalar value. -/
| unbox (x : VarId)
| lit (v : LitVal)
/- Return `1 : uint8` Iff `RC(x) > 1` -/
| isShared (x : VarId)
/- Return `1 : uint8` Iff `x : tobject` is a tagged pointer (storing a scalar value). -/
| isTaggedPtr (x : VarId)
@[export lean_ir_mk_ctor_expr] def mkCtorExpr (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (ys : Array Arg) : Expr := Expr.ctor ⟨n, cidx, size, usize, ssize⟩ ys
@[export lean_ir_mk_proj_expr] def mkProjExpr (i : Nat) (x : VarId) : Expr := Expr.proj i x
@[export lean_ir_mk_uproj_expr] def mkUProjExpr (i : Nat) (x : VarId) : Expr := Expr.uproj i x
@[export lean_ir_mk_sproj_expr] def mkSProjExpr (n : Nat) (offset : Nat) (x : VarId) : Expr := Expr.sproj n offset x
@[export lean_ir_mk_fapp_expr] def mkFAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.fap c ys
@[export lean_ir_mk_papp_expr] def mkPAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.pap c ys
@[export lean_ir_mk_app_expr] def mkAppExpr (x : VarId) (ys : Array Arg) : Expr := Expr.ap x ys
@[export lean_ir_mk_num_expr] def mkNumExpr (v : Nat) : Expr := Expr.lit (LitVal.num v)
@[export lean_ir_mk_str_expr] def mkStrExpr (v : String) : Expr := Expr.lit (LitVal.str v)
structure Param :=
(x : VarId) (borrow : Bool) (ty : IRType)
instance paramInh : Inhabited Param := ⟨{ x := { idx := 0 }, borrow := false, ty := IRType.object }⟩
@[export lean_ir_mk_param] def mkParam (x : VarId) (borrow : Bool) (ty : IRType) : Param := ⟨x, borrow, ty⟩
inductive AltCore (FnBody : Type) : Type
| ctor (info : CtorInfo) (b : FnBody) : AltCore
| default (b : FnBody) : AltCore
inductive FnBody
/- `let x : ty := e; b` -/
| vdecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody)
/- Join point Declaration `block_j (xs) := e; b` -/
| jdecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody)
/- Store `y` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1.
This operation is not part of λPure is only used during optimization. -/
| set (x : VarId) (i : Nat) (y : Arg) (b : FnBody)
| setTag (x : VarId) (cidx : Nat) (b : FnBody)
/- Store `y : Usize` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. -/
| uset (x : VarId) (i : Nat) (y : VarId) (b : FnBody)
/- Store `y : ty` at Position `sizeof(void*)*i + offset` in `x`. `x` must be a Constructor object and `RC(x)` must be 1.
`ty` must not be `object`, `tobject`, `irrelevant` nor `Usize`. -/
| sset (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody)
/- RC increment for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not.
If `persistent == true` then `x` is statically known to be a persistent object. -/
| inc (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody)
/- RC decrement for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not.
If `persistent == true` then `x` is statically known to be a persistent object. -/
| dec (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody)
| del (x : VarId) (b : FnBody)
| mdata (d : MData) (b : FnBody)
| case (tid : Name) (x : VarId) (xType : IRType) (cs : Array (AltCore FnBody))
| ret (x : Arg)
/- Jump to join point `j` -/
| jmp (j : JoinPointId) (ys : Array Arg)
| unreachable
instance : Inhabited FnBody := ⟨FnBody.unreachable⟩
abbrev FnBody.nil := FnBody.unreachable
@[export lean_ir_mk_vdecl] def mkVDecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : FnBody := FnBody.vdecl x ty e b
@[export lean_ir_mk_jdecl] def mkJDecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) : FnBody := FnBody.jdecl j xs v b
@[export lean_ir_mk_uset] def mkUSet (x : VarId) (i : Nat) (y : VarId) (b : FnBody) : FnBody := FnBody.uset x i y b
@[export lean_ir_mk_sset] def mkSSet (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) : FnBody := FnBody.sset x i offset y ty b
@[export lean_ir_mk_case] def mkCase (tid : Name) (x : VarId) (cs : Array (AltCore FnBody)) : FnBody :=
-- Tyhe field `xType` is set by `explicitBoxing` compiler pass.
FnBody.case tid x IRType.object cs
@[export lean_ir_mk_ret] def mkRet (x : Arg) : FnBody := FnBody.ret x
@[export lean_ir_mk_jmp] def mkJmp (j : JoinPointId) (ys : Array Arg) : FnBody := FnBody.jmp j ys
@[export lean_ir_mk_unreachable] def mkUnreachable : Unit → FnBody := fun _ => FnBody.unreachable
abbrev Alt := AltCore FnBody
@[matchPattern] abbrev Alt.ctor := @AltCore.ctor FnBody
@[matchPattern] abbrev Alt.default := @AltCore.default FnBody
instance altInh : Inhabited Alt :=
⟨Alt.default (arbitrary _)⟩
def FnBody.isTerminal : FnBody → Bool
| FnBody.case _ _ _ _ => true
| FnBody.ret _ => true
| FnBody.jmp _ _ => true
| FnBody.unreachable => true
| _ => false
def FnBody.body : FnBody → FnBody
| FnBody.vdecl _ _ _ b => b
| FnBody.jdecl _ _ _ b => b
| FnBody.set _ _ _ b => b
| FnBody.uset _ _ _ b => b
| FnBody.sset _ _ _ _ _ b => b
| FnBody.setTag _ _ b => b
| FnBody.inc _ _ _ _ b => b
| FnBody.dec _ _ _ _ b => b
| FnBody.del _ b => b
| FnBody.mdata _ b => b
| other => other
def FnBody.setBody : FnBody → FnBody → FnBody
| FnBody.vdecl x t v _, b => FnBody.vdecl x t v b
| FnBody.jdecl j xs v _, b => FnBody.jdecl j xs v b
| FnBody.set x i y _, b => FnBody.set x i y b
| FnBody.uset x i y _, b => FnBody.uset x i y b
| FnBody.sset x i o y t _, b => FnBody.sset x i o y t b
| FnBody.setTag x i _, b => FnBody.setTag x i b
| FnBody.inc x n c p _, b => FnBody.inc x n c p b
| FnBody.dec x n c p _, b => FnBody.dec x n c p b
| FnBody.del x _, b => FnBody.del x b
| FnBody.mdata d _, b => FnBody.mdata d b
| other, b => other
@[inline] def FnBody.resetBody (b : FnBody) : FnBody :=
b.setBody FnBody.nil
/- If b is a non terminal, then return a pair `(c, b')` s.t. `b == c <;> b'`,
and c.body == FnBody.nil -/
@[inline] def FnBody.split (b : FnBody) : FnBody × FnBody :=
let b' := b.body;
let c := b.resetBody;
(c, b')
def AltCore.body : Alt → FnBody
| Alt.ctor _ b => b
| Alt.default b => b
def AltCore.setBody : Alt → FnBody → Alt
| Alt.ctor c _, b => Alt.ctor c b
| Alt.default _, b => Alt.default b
@[inline] def AltCore.modifyBody (f : FnBody → FnBody) : AltCore FnBody → Alt
| Alt.ctor c b => Alt.ctor c (f b)
| Alt.default b => Alt.default (f b)
@[inline] def AltCore.mmodifyBody {m : Type → Type} [Monad m] (f : FnBody → m FnBody) : AltCore FnBody → m Alt
| Alt.ctor c b => Alt.ctor c <$> f b
| Alt.default b => Alt.default <$> f b
def Alt.isDefault : Alt → Bool
| Alt.ctor _ _ => false
| Alt.default _ => true
def push (bs : Array FnBody) (b : FnBody) : Array FnBody :=
let b := b.resetBody;
bs.push b
partial def flattenAux : FnBody → Array FnBody → (Array FnBody) × FnBody
| b, r =>
if b.isTerminal then (r, b)
else flattenAux b.body (push r b)
def FnBody.flatten (b : FnBody) : (Array FnBody) × FnBody :=
flattenAux b #[]
partial def reshapeAux : Array FnBody → Nat → FnBody → FnBody
| a, i, b =>
if i == 0 then b
else
let i := i - 1;
let (curr, a) := a.swapAt! i (arbitrary _);
let b := curr.setBody b;
reshapeAux a i b
def reshape (bs : Array FnBody) (term : FnBody) : FnBody :=
reshapeAux bs bs.size term
@[inline] def modifyJPs (bs : Array FnBody) (f : FnBody → FnBody) : Array FnBody :=
bs.map $ fun b => match b with
| FnBody.jdecl j xs v k => FnBody.jdecl j xs (f v) k
| other => other
@[inline] def mmodifyJPs {m : Type → Type} [Monad m] (bs : Array FnBody) (f : FnBody → m FnBody) : m (Array FnBody) :=
bs.mapM $ fun b => match b with
| FnBody.jdecl j xs v k => do v ← f v; pure $ FnBody.jdecl j xs v k
| other => pure other
@[export lean_ir_mk_alt] def mkAlt (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (b : FnBody) : Alt := Alt.ctor ⟨n, cidx, size, usize, ssize⟩ b
inductive Decl
| fdecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody)
| extern (f : FunId) (xs : Array Param) (ty : IRType) (ext : ExternAttrData)
namespace Decl
instance : Inhabited Decl :=
⟨fdecl (arbitrary _) (arbitrary _) IRType.irrelevant (arbitrary _)⟩
def name : Decl → FunId
| Decl.fdecl f _ _ _ => f
| Decl.extern f _ _ _ => f
def params : Decl → Array Param
| Decl.fdecl _ xs _ _ => xs
| Decl.extern _ xs _ _ => xs
def resultType : Decl → IRType
| Decl.fdecl _ _ t _ => t
| Decl.extern _ _ t _ => t
def isExtern : Decl → Bool
| Decl.extern _ _ _ _ => true
| _ => false
end Decl
@[export lean_ir_mk_decl] def mkDecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) : Decl := Decl.fdecl f xs ty b
@[export lean_ir_mk_extern_decl] def mkExternDecl (f : FunId) (xs : Array Param) (ty : IRType) (e : ExternAttrData) : Decl :=
Decl.extern f xs ty e
/-- Set of variable and join point names -/
abbrev IndexSet := RBTree Index Index.lt
instance vsetInh : Inhabited IndexSet := ⟨{}⟩
def mkIndexSet (idx : Index) : IndexSet :=
RBTree.empty.insert idx
inductive LocalContextEntry
| param : IRType → LocalContextEntry
| localVar : IRType → Expr → LocalContextEntry
| joinPoint : Array Param → FnBody → LocalContextEntry
abbrev LocalContext := RBMap Index LocalContextEntry Index.lt
def LocalContext.addLocal (ctx : LocalContext) (x : VarId) (t : IRType) (v : Expr) : LocalContext :=
ctx.insert x.idx (LocalContextEntry.localVar t v)
def LocalContext.addJP (ctx : LocalContext) (j : JoinPointId) (xs : Array Param) (b : FnBody) : LocalContext :=
ctx.insert j.idx (LocalContextEntry.joinPoint xs b)
def LocalContext.addParam (ctx : LocalContext) (p : Param) : LocalContext :=
ctx.insert p.x.idx (LocalContextEntry.param p.ty)
def LocalContext.addParams (ctx : LocalContext) (ps : Array Param) : LocalContext :=
ps.foldl LocalContext.addParam ctx
def LocalContext.isJP (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.joinPoint _ _) => true
| other => false
def LocalContext.getJPBody (ctx : LocalContext) (j : JoinPointId) : Option FnBody :=
match ctx.find? j.idx with
| some (LocalContextEntry.joinPoint _ b) => some b
| other => none
def LocalContext.getJPParams (ctx : LocalContext) (j : JoinPointId) : Option (Array Param) :=
match ctx.find? j.idx with
| some (LocalContextEntry.joinPoint ys _) => some ys
| other => none
def LocalContext.isParam (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.param _) => true
| other => false
def LocalContext.isLocalVar (ctx : LocalContext) (idx : Index) : Bool :=
match ctx.find? idx with
| some (LocalContextEntry.localVar _ _) => true
| other => false
def LocalContext.contains (ctx : LocalContext) (idx : Index) : Bool :=
ctx.contains idx
def LocalContext.eraseJoinPointDecl (ctx : LocalContext) (j : JoinPointId) : LocalContext :=
ctx.erase j.idx
def LocalContext.getType (ctx : LocalContext) (x : VarId) : Option IRType :=
match ctx.find? x.idx with
| some (LocalContextEntry.param t) => some t
| some (LocalContextEntry.localVar t _) => some t
| other => none
def LocalContext.getValue (ctx : LocalContext) (x : VarId) : Option Expr :=
match ctx.find? x.idx with
| some (LocalContextEntry.localVar _ v) => some v
| other => none
abbrev IndexRenaming := RBMap Index Index Index.lt
class HasAlphaEqv (α : Type) :=
(aeqv : IndexRenaming → α → α → Bool)
export HasAlphaEqv (aeqv)
def VarId.alphaEqv (ρ : IndexRenaming) (v₁ v₂ : VarId) : Bool :=
match ρ.find? v₁.idx with
| some v => v == v₂.idx
| none => v₁ == v₂
instance VarId.hasAeqv : HasAlphaEqv VarId := ⟨VarId.alphaEqv⟩
def Arg.alphaEqv (ρ : IndexRenaming) : Arg → Arg → Bool
| Arg.var v₁, Arg.var v₂ => aeqv ρ v₁ v₂
| Arg.irrelevant, Arg.irrelevant => true
| _, _ => false
instance Arg.hasAeqv : HasAlphaEqv Arg := ⟨Arg.alphaEqv⟩
def args.alphaEqv (ρ : IndexRenaming) (args₁ args₂ : Array Arg) : Bool :=
Array.isEqv args₁ args₂ (fun a b => aeqv ρ a b)
instance args.hasAeqv : HasAlphaEqv (Array Arg) := ⟨args.alphaEqv⟩
def Expr.alphaEqv (ρ : IndexRenaming) : Expr → Expr → Bool
| Expr.ctor i₁ ys₁, Expr.ctor i₂ ys₂ => i₁ == i₂ && aeqv ρ ys₁ ys₂
| Expr.reset n₁ x₁, Expr.reset n₂ x₂ => n₁ == n₂ && aeqv ρ x₁ x₂
| Expr.reuse x₁ i₁ u₁ ys₁, Expr.reuse x₂ i₂ u₂ ys₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && u₁ == u₂ && aeqv ρ ys₁ ys₂
| Expr.proj i₁ x₁, Expr.proj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂
| Expr.uproj i₁ x₁, Expr.uproj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂
| Expr.sproj n₁ o₁ x₁, Expr.sproj n₂ o₂ x₂ => n₁ == n₂ && o₁ == o₂ && aeqv ρ x₁ x₂
| Expr.fap c₁ ys₁, Expr.fap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂
| Expr.pap c₁ ys₁, Expr.pap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂
| Expr.ap x₁ ys₁, Expr.ap x₂ ys₂ => aeqv ρ x₁ x₂ && aeqv ρ ys₁ ys₂
| Expr.box ty₁ x₁, Expr.box ty₂ x₂ => ty₁ == ty₂ && aeqv ρ x₁ x₂
| Expr.unbox x₁, Expr.unbox x₂ => aeqv ρ x₁ x₂
| Expr.lit v₁, Expr.lit v₂ => v₁ == v₂
| Expr.isShared x₁, Expr.isShared x₂ => aeqv ρ x₁ x₂
| Expr.isTaggedPtr x₁, Expr.isTaggedPtr x₂ => aeqv ρ x₁ x₂
| _, _ => false
instance Expr.hasAeqv : HasAlphaEqv Expr:= ⟨Expr.alphaEqv⟩
def addVarRename (ρ : IndexRenaming) (x₁ x₂ : Nat) :=
if x₁ == x₂ then ρ else ρ.insert x₁ x₂
def addParamRename (ρ : IndexRenaming) (p₁ p₂ : Param) : Option IndexRenaming :=
if p₁.ty == p₂.ty && p₁.borrow = p₂.borrow then some (addVarRename ρ p₁.x.idx p₂.x.idx)
else none
def addParamsRename (ρ : IndexRenaming) (ps₁ ps₂ : Array Param) : Option IndexRenaming :=
if ps₁.size != ps₂.size then none
else Array.foldl₂ (fun ρ p₁ p₂ => do ρ ← ρ; addParamRename ρ p₁ p₂) (some ρ) ps₁ ps₂
partial def FnBody.alphaEqv : IndexRenaming → FnBody → FnBody → Bool
| ρ, FnBody.vdecl x₁ t₁ v₁ b₁, FnBody.vdecl x₂ t₂ v₂ b₂ => t₁ == t₂ && aeqv ρ v₁ v₂ && FnBody.alphaEqv (addVarRename ρ x₁.idx x₂.idx) b₁ b₂
| ρ, FnBody.jdecl j₁ ys₁ v₁ b₁, FnBody.jdecl j₂ ys₂ v₂ b₂ => match addParamsRename ρ ys₁ ys₂ with
| some ρ' => FnBody.alphaEqv ρ' v₁ v₂ && FnBody.alphaEqv (addVarRename ρ j₁.idx j₂.idx) b₁ b₂
| none => false
| ρ, FnBody.set x₁ i₁ y₁ b₁, FnBody.set x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.uset x₁ i₁ y₁ b₁, FnBody.uset x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.sset x₁ i₁ o₁ y₁ t₁ b₁, FnBody.sset x₂ i₂ o₂ y₂ t₂ b₂ =>
aeqv ρ x₁ x₂ && i₁ = i₂ && o₁ = o₂ && aeqv ρ y₁ y₂ && t₁ == t₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.setTag x₁ i₁ b₁, FnBody.setTag x₂ i₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.inc x₁ n₁ c₁ p₁ b₁, FnBody.inc x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.dec x₁ n₁ c₁ p₁ b₁, FnBody.dec x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.del x₁ b₁, FnBody.del x₂ b₂ => aeqv ρ x₁ x₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.mdata m₁ b₁, FnBody.mdata m₂ b₂ => m₁ == m₂ && FnBody.alphaEqv ρ b₁ b₂
| ρ, FnBody.case n₁ x₁ _ alts₁, FnBody.case n₂ x₂ _ alts₂ => n₁ == n₂ && aeqv ρ x₁ x₂ && Array.isEqv alts₁ alts₂ (fun alt₁ alt₂ =>
match alt₁, alt₂ with
| Alt.ctor i₁ b₁, Alt.ctor i₂ b₂ => i₁ == i₂ && FnBody.alphaEqv ρ b₁ b₂
| Alt.default b₁, Alt.default b₂ => FnBody.alphaEqv ρ b₁ b₂
| _, _ => false)
| ρ, FnBody.jmp j₁ ys₁, FnBody.jmp j₂ ys₂ => j₁ == j₂ && aeqv ρ ys₁ ys₂
| ρ, FnBody.ret x₁, FnBody.ret x₂ => aeqv ρ x₁ x₂
| _, FnBody.unreachable, FnBody.unreachable => true
| _, _, _ => false
def FnBody.beq (b₁ b₂ : FnBody) : Bool :=
FnBody.alphaEqv ∅ b₁ b₂
instance FnBody.HasBeq : HasBeq FnBody := ⟨FnBody.beq⟩
abbrev VarIdSet := RBTree VarId (fun x y => x.idx < y.idx)
namespace VarIdSet
instance : Inhabited VarIdSet := ⟨{}⟩
end VarIdSet
def mkIf (x : VarId) (t e : FnBody) : FnBody :=
FnBody.case `Bool x IRType.uint8 #[
Alt.ctor {name := `Bool.false, cidx := 0, size := 0, usize := 0, ssize := 0} e,
Alt.ctor {name := `Bool.true, cidx := 1, size := 0, usize := 0, ssize := 0} t
]
end IR
end Lean
|
ba7c343e6c81e17c4af2e65994d4792e0f13b8c9 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /tests/lean/sanitychecks.lean | 8919ea76c50dfcf8d3de8aceeb9518392a2f6088 | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 710 | lean | theorem unsound : False := -- Error
unsound
partial theorem unsound : False := -- Error
unsound
unsafe theorem unsound : False := -- Error
unsound
constant unsound : False -- Error
axiom magic : False -- OK
partial def foo (x : Nat) : Nat := foo x -- OK
unsafe def unsound2 : False := unsound -- OK
partial def unsound3 : False := unsound3 -- Error
partial def badcast1 (x : Nat) : Bool :=
unsafeCast x -- Error: partial cannot use unsafe constant
partial def badcast2 (x : Nat) : Bool :=
if x == 0 then unsafeCast x -- Error: partial cannot use unsafe constant
else badcast2 (x + 1)
unsafe def badcast3 (x : Nat) : Bool := -- OK
if x == 0 then unsafeCast x
else badcast3 (x + 1)
|
708aedb37b41f3afe85513a28a827f7b13f70e58 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/algebra/category/CommRing/basic.lean | c2cc9069de23f6ff4f4d51e7896056cdeba113f9 | [
"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 | 7,868 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Johannes Hölzl, Yury Kudryashov
-/
import algebra.category.Group.basic
import data.equiv.ring
/-!
# Category instances for semiring, ring, comm_semiring, and comm_ring.
We introduce the bundled categories:
* `SemiRing`
* `Ring`
* `CommSemiRing`
* `CommRing`
along with the relevant forgetful functors between them.
-/
universes u v
open category_theory
/-- The category of semirings. -/
def SemiRing : Type (u+1) := bundled semiring
namespace SemiRing
/-- `ring_hom` doesn't actually assume associativity. This alias is needed to make the category
theory machinery work. We use the same trick in `category_theory.Mon.assoc_monoid_hom`. -/
abbreviation assoc_ring_hom (M N : Type*) [semiring M] [semiring N] := ring_hom M N
instance bundled_hom : bundled_hom assoc_ring_hom :=
⟨λ M N [semiring M] [semiring N], by exactI @ring_hom.to_fun M N _ _,
λ M [semiring M], by exactI @ring_hom.id M _,
λ M N P [semiring M] [semiring N] [semiring P], by exactI @ring_hom.comp M N P _ _ _,
λ M N [semiring M] [semiring N], by exactI @ring_hom.coe_inj M N _ _⟩
attribute [derive [has_coe_to_sort, large_category, concrete_category]] SemiRing
/-- Construct a bundled SemiRing from the underlying type and typeclass. -/
def of (R : Type u) [semiring R] : SemiRing := bundled.of R
instance : inhabited SemiRing := ⟨of punit⟩
instance (R : SemiRing) : semiring R := R.str
@[simp] lemma coe_of (R : Type u) [semiring R] : (SemiRing.of R : Type u) = R := rfl
instance has_forget_to_Mon : has_forget₂ SemiRing Mon :=
bundled_hom.mk_has_forget₂
(λ R hR, @monoid_with_zero.to_monoid R (@semiring.to_monoid_with_zero R hR))
(λ R₁ R₂, ring_hom.to_monoid_hom) (λ _ _ _, rfl)
instance has_forget_to_AddCommMon : has_forget₂ SemiRing AddCommMon :=
-- can't use bundled_hom.mk_has_forget₂, since AddCommMon is an induced category
{ forget₂ :=
{ obj := λ R, AddCommMon.of R,
map := λ R₁ R₂ f, ring_hom.to_add_monoid_hom f } }
end SemiRing
/-- The category of rings. -/
def Ring : Type (u+1) := bundled ring
namespace Ring
instance : bundled_hom.parent_projection @ring.to_semiring := ⟨⟩
attribute [derive [has_coe_to_sort, large_category, concrete_category]] Ring
/-- Construct a bundled Ring from the underlying type and typeclass. -/
def of (R : Type u) [ring R] : Ring := bundled.of R
instance : inhabited Ring := ⟨of punit⟩
instance (R : Ring) : ring R := R.str
@[simp] lemma coe_of (R : Type u) [ring R] : (Ring.of R : Type u) = R := rfl
instance has_forget_to_SemiRing : has_forget₂ Ring SemiRing := bundled_hom.forget₂ _ _
instance has_forget_to_AddCommGroup : has_forget₂ Ring AddCommGroup :=
-- can't use bundled_hom.mk_has_forget₂, since AddCommGroup is an induced category
{ forget₂ :=
{ obj := λ R, AddCommGroup.of R,
map := λ R₁ R₂ f, ring_hom.to_add_monoid_hom f } }
end Ring
/-- The category of commutative semirings. -/
def CommSemiRing : Type (u+1) := bundled comm_semiring
namespace CommSemiRing
instance : bundled_hom.parent_projection @comm_semiring.to_semiring := ⟨⟩
attribute [derive [has_coe_to_sort, large_category, concrete_category]] CommSemiRing
/-- Construct a bundled CommSemiRing from the underlying type and typeclass. -/
def of (R : Type u) [comm_semiring R] : CommSemiRing := bundled.of R
instance : inhabited CommSemiRing := ⟨of punit⟩
instance (R : CommSemiRing) : comm_semiring R := R.str
@[simp] lemma coe_of (R : Type u) [comm_semiring R] : (CommSemiRing.of R : Type u) = R := rfl
instance has_forget_to_SemiRing : has_forget₂ CommSemiRing SemiRing := bundled_hom.forget₂ _ _
/-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/
instance has_forget_to_CommMon : has_forget₂ CommSemiRing CommMon :=
has_forget₂.mk'
(λ R : CommSemiRing, CommMon.of R) (λ R, rfl)
(λ R₁ R₂ f, f.to_monoid_hom) (by tidy)
end CommSemiRing
/-- The category of commutative rings. -/
def CommRing : Type (u+1) := bundled comm_ring
namespace CommRing
instance : bundled_hom.parent_projection @comm_ring.to_ring := ⟨⟩
attribute [derive [has_coe_to_sort, large_category, concrete_category]] CommRing
/-- Construct a bundled CommRing from the underlying type and typeclass. -/
def of (R : Type u) [comm_ring R] : CommRing := bundled.of R
instance : inhabited CommRing := ⟨of punit⟩
instance (R : CommRing) : comm_ring R := R.str
@[simp] lemma coe_of (R : Type u) [comm_ring R] : (CommRing.of R : Type u) = R := rfl
instance has_forget_to_Ring : has_forget₂ CommRing Ring := bundled_hom.forget₂ _ _
/-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/
instance has_forget_to_CommSemiRing : has_forget₂ CommRing CommSemiRing :=
has_forget₂.mk' (λ R : CommRing, CommSemiRing.of R) (λ R, rfl) (λ R₁ R₂ f, f) (by tidy)
instance : full (forget₂ CommRing CommSemiRing) :=
{ preimage := λ X Y f, f, }
end CommRing
-- This example verifies an improvement possible in Lean 3.8.
-- Before that, to have `add_ring_hom.map_zero` usable by `simp` here,
-- we had to mark all the concrete category `has_coe_to_sort` instances reducible.
-- Now, it just works.
example {R S : CommRing} (i : R ⟶ S) (r : R) (h : r = 0) : i r = 0 :=
by simp [h]
namespace ring_equiv
variables {X Y : Type u}
/-- Build an isomorphism in the category `Ring` from a `ring_equiv` between `ring`s. -/
@[simps] def to_Ring_iso [ring X] [ring Y] (e : X ≃+* Y) : Ring.of X ≅ Ring.of Y :=
{ hom := e.to_ring_hom,
inv := e.symm.to_ring_hom }
/-- Build an isomorphism in the category `CommRing` from a `ring_equiv` between `comm_ring`s. -/
@[simps] def to_CommRing_iso [comm_ring X] [comm_ring Y] (e : X ≃+* Y) :
CommRing.of X ≅ CommRing.of Y :=
{ hom := e.to_ring_hom,
inv := e.symm.to_ring_hom }
end ring_equiv
namespace category_theory.iso
/-- Build a `ring_equiv` from an isomorphism in the category `Ring`. -/
def Ring_iso_to_ring_equiv {X Y : Ring} (i : X ≅ Y) : X ≃+* Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := by tidy,
right_inv := by tidy,
map_add' := by tidy,
map_mul' := by tidy }.
/-- Build a `ring_equiv` from an isomorphism in the category `CommRing`. -/
def CommRing_iso_to_ring_equiv {X Y : CommRing} (i : X ≅ Y) : X ≃+* Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := by tidy,
right_inv := by tidy,
map_add' := by tidy,
map_mul' := by tidy }.
end category_theory.iso
/-- Ring equivalences between `ring`s are the same as (isomorphic to) isomorphisms in `Ring`. -/
def ring_equiv_iso_Ring_iso {X Y : Type u} [ring X] [ring Y] :
(X ≃+* Y) ≅ (Ring.of X ≅ Ring.of Y) :=
{ hom := λ e, e.to_Ring_iso,
inv := λ i, i.Ring_iso_to_ring_equiv, }
/-- Ring equivalences between `comm_ring`s are the same as (isomorphic to) isomorphisms
in `CommRing`. -/
def ring_equiv_iso_CommRing_iso {X Y : Type u} [comm_ring X] [comm_ring Y] :
(X ≃+* Y) ≅ (CommRing.of X ≅ CommRing.of Y) :=
{ hom := λ e, e.to_CommRing_iso,
inv := λ i, i.CommRing_iso_to_ring_equiv, }
instance Ring.forget_reflects_isos : reflects_isomorphisms (forget Ring.{u}) :=
{ reflects := λ X Y f _,
begin
resetI,
let i := as_iso ((forget Ring).map f),
let e : X ≃+* Y := { ..f, ..i.to_equiv },
exact ⟨(is_iso.of_iso e.to_Ring_iso).1⟩,
end }
instance CommRing.forget_reflects_isos : reflects_isomorphisms (forget CommRing.{u}) :=
{ reflects := λ X Y f _,
begin
resetI,
let i := as_iso ((forget CommRing).map f),
let e : X ≃+* Y := { ..f, ..i.to_equiv },
exact ⟨(is_iso.of_iso e.to_CommRing_iso).1⟩,
end }
example : reflects_isomorphisms (forget₂ Ring AddCommGroup) := by apply_instance
|
0b166f905983cfb22c6639d6dce78ccca1ba66df | fecda8e6b848337561d6467a1e30cf23176d6ad0 | /src/data/mv_polynomial/equiv.lean | 91bab1d946351e6f5a48d48a56c7e2dce1411895 | [
"Apache-2.0"
] | permissive | spolu/mathlib | bacf18c3d2a561d00ecdc9413187729dd1f705ed | 480c92cdfe1cf3c2d083abded87e82162e8814f4 | refs/heads/master | 1,671,684,094,325 | 1,600,736,045,000 | 1,600,736,045,000 | 297,564,749 | 1 | 0 | null | 1,600,758,368,000 | 1,600,758,367,000 | null | UTF-8 | Lean | false | false | 8,683 | 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, Johan Commelin, Mario Carneiro
-/
import data.mv_polynomial.rename
import data.equiv.fin
/-!
# Equivalences between polynomial rings
This file establishes a number of equivalences between polynomial rings,
based on equivalences between the underlying types.
## Notation
As in other polynomial files we typically use the notation:
+ `σ : Type*` (indexing the variables)
+ `α : Type*` `[comm_semiring α]` (the coefficients)
+ `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set.
This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s`
+ `a : α`
+ `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians
+ `p : mv_polynomial σ α`
## Tags
equivalence, isomorphism, morphism, ring hom, hom
-/
noncomputable theory
open_locale classical big_operators
open set function finsupp add_monoid_algebra
open_locale big_operators
universes u v w x
variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x}
namespace mv_polynomial
variables {σ : Type*} {a a' a₁ a₂ : α} {e : ℕ} {n m : σ} {s : σ →₀ ℕ}
section equiv
variables (α) [comm_semiring α]
/-- The ring isomorphism between multivariable polynomials in no variables and the ground ring. -/
def pempty_ring_equiv : mv_polynomial pempty α ≃+* α :=
{ to_fun := mv_polynomial.eval₂ (ring_hom.id _) $ pempty.elim,
inv_fun := C,
left_inv := is_id (C.comp (eval₂_hom (ring_hom.id _) pempty.elim))
(assume a : α, by { dsimp, rw [eval₂_C], refl }) (assume a, a.elim),
right_inv := λ r, eval₂_C _ _ _,
map_mul' := λ _ _, eval₂_mul _ _,
map_add' := λ _ _, eval₂_add _ _ }
/--
The ring isomorphism between multivariable polynomials in a single variable and
polynomials over the ground ring.
-/
def punit_ring_equiv : mv_polynomial punit α ≃+* polynomial α :=
{ to_fun := eval₂ polynomial.C (λu:punit, polynomial.X),
inv_fun := polynomial.eval₂ mv_polynomial.C (X punit.star),
left_inv :=
begin
let f : polynomial α →+* mv_polynomial punit α :=
ring_hom.of (polynomial.eval₂ mv_polynomial.C (X punit.star)),
let g : mv_polynomial punit α →+* polynomial α :=
ring_hom.of (eval₂ polynomial.C (λu:punit, polynomial.X)),
show ∀ p, f.comp g p = p,
apply is_id,
{ assume a, dsimp, rw [eval₂_C, polynomial.eval₂_C] },
{ rintros ⟨⟩, dsimp, rw [eval₂_X, polynomial.eval₂_X] }
end,
right_inv := assume p, polynomial.induction_on p
(assume a, by rw [polynomial.eval₂_C, mv_polynomial.eval₂_C])
(assume p q hp hq, by rw [polynomial.eval₂_add, mv_polynomial.eval₂_add, hp, hq])
(assume p n hp,
by rw [polynomial.eval₂_mul, polynomial.eval₂_pow, polynomial.eval₂_X, polynomial.eval₂_C,
eval₂_mul, eval₂_C, eval₂_pow, eval₂_X]),
map_mul' := λ _ _, eval₂_mul _ _,
map_add' := λ _ _, eval₂_add _ _ }
/-- The ring isomorphism between multivariable polynomials induced by an equivalence of the variables. -/
def ring_equiv_of_equiv (e : β ≃ γ) : mv_polynomial β α ≃+* mv_polynomial γ α :=
{ to_fun := rename e,
inv_fun := rename e.symm,
left_inv := λ p, by simp only [rename_rename, (∘), e.symm_apply_apply]; exact rename_id p,
right_inv := λ p, by simp only [rename_rename, (∘), e.apply_symm_apply]; exact rename_id p,
map_mul' := (rename e).map_mul,
map_add' := (rename e).map_add }
/-- The ring isomorphism between multivariable polynomials induced by a ring isomorphism of the ground ring. -/
def ring_equiv_congr [comm_semiring γ] (e : α ≃+* γ) : mv_polynomial β α ≃+* mv_polynomial β γ :=
{ to_fun := map (e : α →+* γ),
inv_fun := map (e.symm : γ →+* α),
left_inv := assume p,
have (e.symm : γ →+* α).comp (e : α →+* γ) = ring_hom.id _,
{ ext a, exact e.symm_apply_apply a },
by simp only [map_map, this, map_id],
right_inv := assume p,
have (e : α →+* γ).comp (e.symm : γ →+* α) = ring_hom.id _,
{ ext a, exact e.apply_symm_apply a },
by simp only [map_map, this, map_id],
map_mul' := ring_hom.map_mul _,
map_add' := ring_hom.map_add _ }
section
variables (β γ δ)
/--
The function from multivariable polynomials in a sum of two types,
to multivariable polynomials in one of the types,
with coefficents in multivariable polynomials in the other type.
See `sum_ring_equiv` for the ring isomorphism.
-/
def sum_to_iter : mv_polynomial (β ⊕ γ) α →+* mv_polynomial β (mv_polynomial γ α) :=
eval₂_hom (C.comp C) (λbc, sum.rec_on bc X (C ∘ X))
instance is_semiring_hom_sum_to_iter : is_semiring_hom (sum_to_iter α β γ) :=
eval₂.is_semiring_hom _ _
lemma sum_to_iter_C (a : α) : sum_to_iter α β γ (C a) = C (C a) :=
eval₂_C _ _ a
lemma sum_to_iter_Xl (b : β) : sum_to_iter α β γ (X (sum.inl b)) = X b :=
eval₂_X _ _ (sum.inl b)
lemma sum_to_iter_Xr (c : γ) : sum_to_iter α β γ (X (sum.inr c)) = C (X c) :=
eval₂_X _ _ (sum.inr c)
/--
The function from multivariable polynomials in one type,
with coefficents in multivariable polynomials in another type,
to multivariable polynomials in the sum of the two types.
See `sum_ring_equiv` for the ring isomorphism.
-/
def iter_to_sum : mv_polynomial β (mv_polynomial γ α) →+* mv_polynomial (β ⊕ γ) α :=
eval₂_hom (ring_hom.of (eval₂ C (X ∘ sum.inr))) (X ∘ sum.inl)
lemma iter_to_sum_C_C (a : α) : iter_to_sum α β γ (C (C a)) = C a :=
eq.trans (eval₂_C _ _ (C a)) (eval₂_C _ _ _)
lemma iter_to_sum_X (b : β) : iter_to_sum α β γ (X b) = X (sum.inl b) :=
eval₂_X _ _ _
lemma iter_to_sum_C_X (c : γ) : iter_to_sum α β γ (C (X c)) = X (sum.inr c) :=
eq.trans (eval₂_C _ _ (X c)) (eval₂_X _ _ _)
/-- A helper function for `sum_ring_equiv`. -/
def mv_polynomial_equiv_mv_polynomial [comm_semiring δ]
(f : mv_polynomial β α →+* mv_polynomial γ δ)
(g : mv_polynomial γ δ →+* mv_polynomial β α)
(hfgC : ∀a, f (g (C a)) = C a)
(hfgX : ∀n, f (g (X n)) = X n)
(hgfC : ∀a, g (f (C a)) = C a)
(hgfX : ∀n, g (f (X n)) = X n) :
mv_polynomial β α ≃+* mv_polynomial γ δ :=
{ to_fun := f, inv_fun := g,
left_inv := is_id (ring_hom.comp _ _) hgfC hgfX,
right_inv := is_id (ring_hom.comp _ _) hfgC hfgX,
map_mul' := f.map_mul,
map_add' := f.map_add }
/--
The ring isomorphism between multivariable polynomials in a sum of two types,
and multivariable polynomials in one of the types,
with coefficents in multivariable polynomials in the other type.
-/
def sum_ring_equiv : mv_polynomial (β ⊕ γ) α ≃+* mv_polynomial β (mv_polynomial γ α) :=
begin
apply @mv_polynomial_equiv_mv_polynomial α (β ⊕ γ) _ _ _ _
(sum_to_iter α β γ) (iter_to_sum α β γ),
{ assume p,
convert hom_eq_hom ((sum_to_iter α β γ).comp ((iter_to_sum α β γ).comp C)) C _ _ p,
{ assume a, dsimp, rw [iter_to_sum_C_C α β γ, sum_to_iter_C α β γ] },
{ assume c, dsimp, rw [iter_to_sum_C_X α β γ, sum_to_iter_Xr α β γ] } },
{ assume b, rw [iter_to_sum_X α β γ, sum_to_iter_Xl α β γ] },
{ assume a, rw [sum_to_iter_C α β γ, iter_to_sum_C_C α β γ] },
{ assume n, cases n with b c,
{ rw [sum_to_iter_Xl, iter_to_sum_X] },
{ rw [sum_to_iter_Xr, iter_to_sum_C_X] } },
end
/--
The ring isomorphism between multivariable polynomials in `option β` and
polynomials with coefficients in `mv_polynomial β α`.
-/
def option_equiv_left : mv_polynomial (option β) α ≃+* polynomial (mv_polynomial β α) :=
(ring_equiv_of_equiv α $ (equiv.option_equiv_sum_punit β).trans (equiv.sum_comm _ _)).trans $
(sum_ring_equiv α _ _).trans $
punit_ring_equiv _
/--
The ring isomorphism between multivariable polynomials in `option β` and
multivariable polynomials with coefficients in polynomials.
-/
def option_equiv_right : mv_polynomial (option β) α ≃+* mv_polynomial β (polynomial α) :=
(ring_equiv_of_equiv α $ equiv.option_equiv_sum_punit.{0} β).trans $
(sum_ring_equiv α β unit).trans $
ring_equiv_congr (mv_polynomial unit α) (punit_ring_equiv α)
/--
The ring isomorphism between multivariable polynomials in `fin (n + 1)` and
polynomials over multivariable polynomials in `fin n`.
-/
def fin_succ_equiv (n : ℕ) :
mv_polynomial (fin (n + 1)) α ≃+* polynomial (mv_polynomial (fin n) α) :=
(ring_equiv_of_equiv α (fin_succ_equiv n)).trans
(option_equiv_left α (fin n))
end
end equiv
end mv_polynomial
|
1f9f84e1592fe05fa9abcc7248de376d7a7df895 | a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940 | /stage0/src/Lean/Elab/DeclUtil.lean | 2b599ec244d57a7c8d941584e6276716cd4856be | [
"Apache-2.0"
] | permissive | WojciechKarpiel/lean4 | 7f89706b8e3c1f942b83a2c91a3a00b05da0e65b | f6e1314fa08293dea66a329e05b6c196a0189163 | refs/heads/master | 1,686,633,402,214 | 1,625,821,189,000 | 1,625,821,258,000 | 384,640,886 | 0 | 0 | Apache-2.0 | 1,625,903,617,000 | 1,625,903,026,000 | null | UTF-8 | Lean | false | false | 3,816 | 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, Sebastian Ullrich
-/
import Lean.Meta.ExprDefEq
namespace Lean.Meta
def forallTelescopeCompatibleAux {α} (k : Array Expr → Expr → Expr → MetaM α) : Nat → Expr → Expr → Array Expr → MetaM α
| 0, type₁, type₂, xs => k xs type₁ type₂
| i+1, type₁, type₂, xs => do
let type₁ ← whnf type₁
let type₂ ← whnf type₂
match type₁, type₂ with
| Expr.forallE n₁ d₁ b₁ c₁, Expr.forallE n₂ d₂ b₂ c₂ =>
unless n₁ == n₂ do
throwError "parameter name mismatch '{n₁}', expected '{n₂}'"
unless (← isDefEq d₁ d₂) do
throwError "parameter '{n₁}' {← mkHasTypeButIsExpectedMsg d₁ d₂}"
unless c₁.binderInfo == c₂.binderInfo do
throwError "binder annotation mismatch at parameter '{n₁}'"
withLocalDecl n₁ c₁.binderInfo d₁ fun x =>
let type₁ := b₁.instantiate1 x
let type₂ := b₂.instantiate1 x
forallTelescopeCompatibleAux k i type₁ type₂ (xs.push x)
| _, _ => throwError "unexpected number of parameters"
/-- Given two forall-expressions `type₁` and `type₂`, ensure the first `numParams` parameters are compatible, and
then execute `k` with the parameters and remaining types. -/
def forallTelescopeCompatible {α m} [Monad m] [MonadControlT MetaM m] (type₁ type₂ : Expr) (numParams : Nat) (k : Array Expr → Expr → Expr → m α) : m α :=
controlAt MetaM fun runInBase =>
forallTelescopeCompatibleAux (fun xs type₁ type₂ => runInBase $ k xs type₁ type₂) numParams type₁ type₂ #[]
end Meta
namespace Elab
def expandOptDeclSig (stx : Syntax) : Syntax × Option Syntax :=
-- many Term.bracketedBinder >> Term.optType
let binders := stx[0]
let optType := stx[1] -- optional (leading_parser " : " >> termParser)
if optType.isNone then
(binders, none)
else
let typeSpec := optType[0]
(binders, some typeSpec[1])
def expandDeclSig (stx : Syntax) : Syntax × Syntax :=
-- many Term.bracketedBinder >> Term.typeSpec
let binders := stx[0]
let typeSpec := stx[1]
(binders, typeSpec[1])
def mkFreshInstanceName (env : Environment) (nextIdx : Nat) : Name :=
(env.mainModule ++ `_instance).appendIndexAfter nextIdx
def isFreshInstanceName (name : Name) : Bool :=
match name with
| Name.str _ s _ => "_instance".isPrefixOf s
| _ => false
/--
Sort the given list of `usedParams` using the following order:
- If it is an explicit level `allUserParams`, then use user given order.
- Otherwise, use lexicographical.
Remark: `scopeParams` are the universe params introduced using the `universe` command. `allUserParams` contains
the universe params introduced using the `universe` command *and* the `.{...}` notation.
Remark: this function return an exception if there is an `u` not in `usedParams`, that is in `allUserParams` but not in `scopeParams`.
Remark: `explicitParams` are in reverse declaration order. That is, the head is the last declared parameter. -/
def sortDeclLevelParams (scopeParams : List Name) (allUserParams : List Name) (usedParams : Array Name) : Except String (List Name) :=
match allUserParams.find? $ fun u => !usedParams.contains u && !scopeParams.elem u with
| some u => throw s!"unused universe parameter '{u}'"
| none =>
let result := allUserParams.foldl (fun result levelName => if usedParams.elem levelName then levelName :: result else result) []
let remaining := usedParams.filter (fun levelParam => !allUserParams.elem levelParam)
let remaining := remaining.qsort Name.lt
pure $ result ++ remaining.toList
end Lean.Elab
|
c6309eabfa73767c8359ef9585ecd2d8a56d9ba2 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/ring_theory/mv_polynomial/ideal.lean | b7ddbc120d4e0752e48a8ff78f584d0ae8f41a79 | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 2,139 | lean | /-
Copyright (c) 2023 Eric Wieser. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Eric Wieser
-/
import algebra.monoid_algebra.ideal
import data.mv_polynomial.division
/-!
# Lemmas about ideals of `mv_polynomial`
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
Notably this contains results about monomial ideals.
## Main results
* `mv_polynomial.mem_ideal_span_monomial_image`
* `mv_polynomial.mem_ideal_span_X_image`
-/
variables {σ R : Type*}
namespace mv_polynomial
variables [comm_semiring R]
/-- `x` is in a monomial ideal generated by `s` iff every element of of its support dominates one of
the generators. Note that `si ≤ xi` is analogous to saying that the monomial corresponding to `si`
divides the monomial corresponding to `xi`. -/
lemma mem_ideal_span_monomial_image
{x : mv_polynomial σ R} {s : set (σ →₀ ℕ)} :
x ∈ ideal.span ((λ s, monomial s (1 : R)) '' s) ↔ ∀ xi ∈ x.support, ∃ si ∈ s, si ≤ xi :=
begin
refine add_monoid_algebra.mem_ideal_span_of'_image.trans _,
simp_rw [le_iff_exists_add, add_comm],
refl,
end
lemma mem_ideal_span_monomial_image_iff_dvd {x : mv_polynomial σ R} {s : set (σ →₀ ℕ)} :
x ∈ ideal.span ((λ s, monomial s (1 : R)) '' s) ↔
∀ xi ∈ x.support, ∃ si ∈ s, monomial si 1 ∣ monomial xi (x.coeff xi) :=
begin
refine mem_ideal_span_monomial_image.trans (forall₂_congr $ λ xi hxi, _),
simp_rw [monomial_dvd_monomial, one_dvd, and_true, mem_support_iff.mp hxi, false_or],
end
/-- `x` is in a monomial ideal generated by variables `X` iff every element of of its support
has a component in `s`. -/
lemma mem_ideal_span_X_image {x : mv_polynomial σ R} {s : set σ} :
x ∈ ideal.span (mv_polynomial.X '' s : set (mv_polynomial σ R)) ↔
∀ m ∈ x.support, ∃ i ∈ s, (m : σ →₀ ℕ) i ≠ 0 :=
begin
have := @mem_ideal_span_monomial_image σ R _ _ ((λ i, finsupp.single i 1) '' s),
rw set.image_image at this,
refine this.trans _,
simp [nat.one_le_iff_ne_zero],
end
end mv_polynomial
|
a9a20a2a8d3f1cc1fd73c98cebd50bca0a76ccad | bde6690019e9da475b0c91d5a066e0f6681a1179 | /library/standard/int.lean | 76ade2b900cca01978073b82ee0001e314659a8c | [
"Apache-2.0"
] | permissive | leodemoura/libraries | ae67d491abc580407aa837d65736d515bec39263 | 14afd47544daa9520ea382d33ba7f6f05c949063 | refs/heads/master | 1,473,601,302,073 | 1,403,713,370,000 | 1,403,713,370,000 | 19,831,525 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 52,354 | lean | ----------------------------------------------------------------------------------------------------
-- Copyright (c) 2014 Floris van Doorn. All rights reserved.
-- Released under Apache 2.0 license as described in the file LICENSE.
-- Author: Floris van Doorn
----------------------------------------------------------------------------------------------------
-- Theory int
-- ==========
import nat quotient macros tactic
namespace int
using nat
using quot
using subtype
unary_nat
-- ## The defining equivalence relation on ℕ × ℕ
definition rel (a b : ℕ ## ℕ) : Bool := xx a + yy b = yy a + xx b
theorem rel_comp (n m k l : ℕ) : (rel (tpair n m) (tpair k l)) ↔ (n + l = m + k)
:=
have H : (xx (tpair n m) + yy (tpair k l) = yy (tpair n m) + xx (tpair k l)) = (n + l = m + k),
by simp, H
add_rewrite rel_comp --local
theorem rel_refl (a : ℕ ## ℕ) : rel a a
:= add_comm (xx a) (yy a)
theorem rel_symm {a b : ℕ ## ℕ} (H : rel a b) : rel b a
:=
calc
xx b + yy a = yy a + xx b : add_comm _ _
... = xx a + yy b : symm H
... = yy b + xx a : add_comm _ _
theorem rel_trans {a b c : ℕ ## ℕ} (H1 : rel a b) (H2 : rel b c) : rel a c
:=
have H3 : xx a + yy c + yy b = yy a + xx c + yy b, from
calc
xx a + yy c + yy b = xx a + yy b + yy c : by simp
... = yy a + xx b + yy c : {H1}
... = yy a + (xx b + yy c) : by simp
... = yy a + (yy b + xx c) : {H2}
... = yy a + xx c + yy b : by simp,
show xx a + yy c = yy a + xx c, from add_cancel_right H3
theorem rel_equiv : equivalence rel
:= equivalence_intro rel_refl @rel_symm @rel_trans
theorem rel_flip {a b : ℕ ## ℕ} (H : rel a b) : rel (flip a) (flip b)
:=
calc
xx (flip a) + yy (flip b) = yy a + xx b : by simp
... = xx a + yy b : symm H
... = yy (flip a) + xx (flip b) : by simp
-- ## The canonical representative of each equivalence class
definition proj (a : ℕ ## ℕ) : ℕ ## ℕ
:= if xx a ≥ yy a then tpair (xx a - yy a) 0 else tpair 0 (yy a - xx a)
theorem proj_ge {a : ℕ ## ℕ} (H : xx a ≥ yy a) : proj a = tpair (xx a - yy a) 0
:= imp_if_eq H _ _
theorem proj_lt {a : ℕ ## ℕ} (H : xx a < yy a) : proj a = tpair 0 (yy a - xx a)
:=
have H2 : ¬ xx a ≥ yy a, from lt_imp_not_ge H,
not_imp_if_eq H2 _ _
theorem proj_le {a : ℕ ## ℕ} (H : xx a ≤ yy a) : proj a = tpair 0 (yy a - xx a)
:=
or_elim (le_or_gt (yy a) (xx a))
(assume H2 : yy a ≤ xx a,
have H3 : xx a = yy a, from le_antisym H H2,
calc
proj a = tpair (xx a - yy a) 0 : proj_ge H2
... = tpair (xx a - yy a) (xx a - xx a) : {symm (sub_self (xx a))}
... = tpair (yy a - yy a) (yy a - xx a) : {H3}
... = tpair 0 (yy a - xx a) : {sub_self (yy a)})
(assume H2 : xx a < yy a, proj_lt H2)
theorem proj_ge_xx {a : ℕ ## ℕ} (H : xx a ≥ yy a) : xx (proj a) = xx a - yy a
:=
calc
xx (proj a) = xx (tpair (xx a - yy a) 0) : {proj_ge H}
... = xx a - yy a : tproj1_tpair (xx a - yy a) 0
theorem proj_ge_yy {a : ℕ ## ℕ} (H : xx a ≥ yy a) : yy (proj a) = 0
:=
calc
yy (proj a) = yy (tpair (xx a - yy a) 0) : {proj_ge H}
... = 0 : tproj2_tpair (xx a - yy a) 0
theorem proj_le_xx {a : ℕ ## ℕ} (H : xx a ≤ yy a) : xx (proj a) = 0
:=
calc
xx (proj a) = xx (tpair 0 (yy a - xx a)) : {proj_le H}
... = 0 : tproj1_tpair 0 (yy a - xx a)
theorem proj_le_yy {a : ℕ ## ℕ} (H : xx a ≤ yy a) : yy (proj a) = yy a - xx a
:=
calc
yy (proj a) = yy (tpair 0 (yy a - xx a)) : {proj_le H}
... = yy a - xx a : tproj2_tpair 0 (yy a - xx a)
theorem proj_flip (a : ℕ ## ℕ) : proj (flip a) = flip (proj a)
:=
have special : ∀a, yy a ≤ xx a → proj (flip a) = flip (proj a), from
take a,
assume H : yy a ≤ xx a,
have H2 : xx (flip a) ≤ yy (flip a), from P_flip H,
have H3 : xx (proj (flip a)) = xx (flip (proj a)), from
calc
xx (proj (flip a)) = 0 : proj_le_xx H2
... = yy (proj a) : symm (proj_ge_yy H)
... = xx (flip (proj a)) : symm (flip_xx (proj a)),
have H4 : yy (proj (flip a)) = yy (flip (proj a)), from
calc
yy (proj (flip a)) = yy (flip a) - xx (flip a) : proj_le_yy H2
... = xx a - xx (flip a) : {flip_yy a}
... = xx a - yy a : {flip_xx a}
... = xx (proj a) : symm (proj_ge_xx H)
... = yy (flip (proj a)) : symm (flip_yy (proj a)),
tpairext H3 H4,
or_elim (le_total (yy a) (xx a))
(assume H : yy a ≤ xx a, special a H)
(assume H : xx a ≤ yy a,
have H2 : yy (flip a) ≤ xx (flip a), from P_flip H,
calc
proj (flip a) = flip (flip (proj (flip a))) : symm (flip_flip (proj (flip a)))
... = flip (proj (flip (flip a))) : {symm (special (flip a) H2)}
... = flip (proj a) : {flip_flip a})
theorem proj_rel (a : ℕ ## ℕ) : rel a (proj a)
:=
or_elim (le_total (yy a) (xx a))
(assume H : yy a ≤ xx a,
calc
xx a + yy (proj a) = xx a + 0 : {proj_ge_yy H}
... = xx a : add_zero_right (xx a)
... = yy a + (xx a - yy a) : symm (add_sub_le H)
... = yy a + xx (proj a) : {symm (proj_ge_xx H)})
(assume H : xx a ≤ yy a,
calc
xx a + yy (proj a) = xx a + (yy a - xx a) : {proj_le_yy H}
... = yy a : add_sub_le H
... = yy a + 0 : symm (add_zero_right (yy a))
... = yy a + xx (proj a) : {symm (proj_le_xx H)})
theorem proj_congr {a b : ℕ ## ℕ} (H : rel a b) : proj a = proj b
:=
have special : ∀a b, yy a ≤ xx a → rel a b → proj a = proj b, from
take a b,
assume H2 : yy a ≤ xx a,
assume H : rel a b,
have H3 : xx a + yy b ≤ yy a + xx b, from subst (le_refl (xx a + yy b)) H,
have H4 : yy b ≤ xx b, from add_le_inv H3 H2,
have H5 : xx (proj a) = xx (proj b), from
calc
xx (proj a) = xx a - yy a : proj_ge_xx H2
... = xx a + yy b - yy b - yy a : {symm (sub_add_left (xx a) (yy b))}
... = yy a + xx b - yy b - yy a : {H}
... = yy a + xx b - yy a - yy b : {sub_comm _ _ _}
... = xx b - yy b : {sub_add_left2 (yy a) (xx b)}
... = xx (proj b) : symm (proj_ge_xx H4),
have H6 : yy (proj a) = yy (proj b), from
calc
yy (proj a) = 0 : proj_ge_yy H2
... = yy (proj b) : {symm (proj_ge_yy H4)},
tpairext H5 H6,
or_elim (le_total (yy a) (xx a))
(assume H2 : yy a ≤ xx a, special a b H2 H)
(assume H2 : xx a ≤ yy a,
have H3 : yy (flip a) ≤ xx (flip a), from P_flip H2,
have H4 : proj (flip a) = proj (flip b), from special (flip a) (flip b) H3 (rel_flip H),
have H5 : flip (proj a) = flip (proj b), from subst (subst H4 (proj_flip a)) (proj_flip b),
show proj a = proj b, from flip_inj H5)
theorem proj_inj {a b : ℕ ## ℕ} (H : proj a = proj b) : rel a b
:= representative_map_equiv_inj rel_equiv proj_rel @proj_congr H
theorem proj_zero_or (a : ℕ ## ℕ) : xx (proj a) = 0 ∨ yy (proj a) = 0
:=
or_elim (le_total (yy a) (xx a))
(assume H : yy a ≤ xx a, or_intro_right _ (proj_ge_yy H))
(assume H : xx a ≤ yy a, or_intro_left _ (proj_le_xx H))
theorem proj_idempotent (a : ℕ ## ℕ) : proj (proj a) = proj a
:= representative_map_idempotent_equiv rel proj_rel @proj_congr a
-- ## Definition of ℤ and basic theorems and definitions
definition int := image proj
alias ℤ : int
definition psub : ℕ ## ℕ → ℤ := fun_image proj
definition rep : ℤ → ℕ ## ℕ := subtype::rep
theorem quotient : is_quotient rel psub rep
:= representative_map_to_quotient_equiv rel_equiv proj_rel @proj_congr
theorem psub_rep (a : ℤ) : psub (rep a) = a
:= abs_rep quotient a
theorem destruct (a : ℤ) : ∃n m : ℕ, a = psub (tpair n m)
:=
exists_intro (xx (rep a))
(exists_intro (yy (rep a))
(calc
a = psub (rep a) : symm (psub_rep a)
... = psub (tpair (xx (rep a)) (yy (rep a))) : {symm (tpair_tproj_eq (rep a))}))
definition of_nat (n : ℕ) : ℤ := psub (tpair n 0)
coercion of_nat
theorem eq_zero_intro (n : ℕ) : psub (tpair n n) = 0
:=
have H : rel (tpair n n) (tpair 0 0), by simp,
eq_abs quotient H
-- ## absolute value
definition abs : ℤ → ℕ := rec_constant quotient (fun v, dist (xx v) (yy v))
notation | _ | : abs
---move to other library or remove
add_rewrite tpair_tproj_eq
theorem tpair_translate {A B : Type} (P : A → B → A ## B → Bool)
: (∀v, P (tproj1 v) (tproj2 v) v) ↔ (∀a b, P a b (tpair a b))
:=
iff_intro
(assume H, take a b, subst (H (tpair a b)) (by simp))
(assume H, take v, subst (H (tproj1 v) (tproj2 v)) (by simp))
theorem abs_comp (n m : ℕ) : |psub (tpair n m)| = dist n m
:=
have H : ∀v w : ℕ ## ℕ, rel v w → dist (xx v) (yy v) = dist (xx w) (yy w),
from take v w H, dist_eq_intro H,
have H2 : ∀v : ℕ ## ℕ, |psub v| = dist (xx v) (yy v),
from take v, (comp_constant quotient H (rel_refl v)),
(by simp) ◂ H2 (tpair n m)
add_rewrite abs_comp --local
--the following theorem includes abs_zero
theorem abs_of_nat (n : ℕ) : |n| = n
:=
calc
|psub (tpair n 0)| = dist n 0 : by simp
... = n : by simp
theorem of_nat_inj {n m : ℕ} (H : of_nat n = of_nat m) : n = m
:=
calc
n = |n| : symm (abs_of_nat n)
... = |m| : {H}
... = m : abs_of_nat m
theorem abs_eq_zero {a : ℤ} (H : |a| = 0) : a = 0
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
have H2 : dist xa ya = 0, from
calc
dist xa ya = |psub (tpair xa ya)| : by simp_no_assump
... = |a| : {symm Ha}
... = 0 : H,
have H3 : xa = ya, from dist_eq_zero H2,
calc
a = psub (tpair xa ya) : Ha
... = psub (tpair ya ya) : {H3}
... = 0 : eq_zero_intro ya
add_rewrite abs_of_nat
-- ## neg
definition neg : ℤ → ℤ := quotient_map quotient flip
notation 80 - _ : neg
theorem neg_comp (n m : ℕ) : -psub (tpair n m) = psub (tpair m n)
:=
have H : ∀a, -psub a = psub (flip a),
from take a, comp_quotient_map quotient @rel_flip (rel_refl _),
calc
-psub (tpair n m) = psub (flip (tpair n m)) : H (tpair n m)
... = psub (tpair m n) : by simp
add_rewrite neg_comp --local
---note: "-0" is interpreted as invalid numeral
theorem neg_zero : - 0 = 0
:= calc -psub (tpair 0 0) = psub (tpair 0 0) : neg_comp 0 0
theorem neg_neg (a : ℤ) : -(-a) = a
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
by simp
add_rewrite neg_neg neg_zero
theorem neg_inj {a b : ℤ} (H : -a = -b) : a = b
:= (by simp_no_assump) ◂ congr2 neg H
theorem neg_move {a b : ℤ} (H : -a = b) : -b = a
:= subst (neg_neg a) H
theorem abs_neg (a : ℤ) : | -a| = |a|
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
by simp
theorem pos_eq_neg {n m : ℕ} (H : n = -m) : n = 0 ∧ m = 0
:=
have H2 : ∀n : ℕ, n = psub (tpair n 0), from take n : ℕ, refl n,
have H3 : psub (tpair n 0) = psub (tpair 0 m), from (by simp) ◂ H,
have H4 : rel (tpair n 0) (tpair 0 m), from R_intro_refl quotient rel_refl H3,
have H5 : n + m = 0, from
calc
n + m = xx (tpair n 0) + yy (tpair 0 m) : by simp
... = yy (tpair n 0) + xx (tpair 0 m) : H4
... = 0 : by simp,
add_eq_zero H5
add_rewrite abs_neg
---reverse equalities
theorem cases (a : ℤ) : (∃n : ℕ, a = n) ∨ (∃n : ℕ, a = -n)
:=
have Hrep : proj (rep a) = rep a, from @idempotent_image_fix _ proj proj_idempotent a,
or_imp_or (or_flip (proj_zero_or (rep a)))
(assume H : yy (proj (rep a)) = 0,
have H2 : yy (rep a) = 0, from subst H Hrep,
exists_intro (xx (rep a))
(calc
a = psub (rep a) : symm (psub_rep a)
... = psub (tpair (xx (rep a)) (yy (rep a))) : {symm (tpair_tproj_eq (rep a))}
... = psub (tpair (xx (rep a)) 0) : {H2}
... = of_nat (xx (rep a)) : refl _))
(assume H : xx (proj (rep a)) = 0,
have H2 : xx (rep a) = 0, from subst H Hrep,
exists_intro (yy (rep a))
(calc
a = psub (rep a) : symm (psub_rep a)
... = psub (tpair (xx (rep a)) (yy (rep a))) : {symm (tpair_tproj_eq (rep a))}
... = psub (tpair 0 (yy (rep a))) : {H2}
... = -psub (tpair (yy (rep a)) 0) : by simp
... = -of_nat (yy (rep a)) : refl _))
---rename to by_cases in Lean 0.2 (for now using this to avoid name clash)
theorem int_by_cases {P : ℤ → Bool} (a : ℤ) (H1 : ∀n : ℕ, P n) (H2 : ∀n : ℕ, P (-n)) : P a
:=
or_elim (cases a)
(assume H, obtain (n : ℕ) (H3 : a = n), from H, subst (H1 n) (symm H3))
(assume H, obtain (n : ℕ) (H3 : a = -n), from H, subst (H2 n) (symm H3))
---reverse equalities, rename
theorem cases_succ (a : ℤ) : (∃n : ℕ, a = n) ∨ (∃n : ℕ, a = -succ n)
:=
or_elim (cases a)
(assume H : (∃n : ℕ, a = n), or_intro_left _ H)
(assume H,
obtain (n : ℕ) (H2 : a = -n), from H,
discriminate
(assume H3 : n = 0,
have H4 : a = 0, from
calc
a = -n : H2
... = - 0 : {H3}
... = 0 : neg_zero,
or_intro_left _ (exists_intro 0 H4))
(take k : ℕ,
assume H3 : n = succ k,
have H4 : a = -succ k, from subst H2 H3,
or_intro_right _ (exists_intro k H4)))
theorem int_by_cases_succ {P : ℤ → Bool} (a : ℤ) (H1 : ∀n : ℕ, P n) (H2 : ∀n : ℕ, P (-succ n)) : P a
:=
or_elim (cases_succ a)
(assume H, obtain (n : ℕ) (H3 : a = n), from H, subst (H1 n) (symm H3))
(assume H, obtain (n : ℕ) (H3 : a = -succ n), from H, subst (H2 n) (symm H3))
theorem of_nat_eq_neg_of_nat {n m : ℕ} (H : n = - m) : n = 0 ∧ m = 0
:=
have H2 : n = psub (tpair 0 m), from
calc
n = -m : H
... = -psub (tpair m 0) : refl (-m)
... = psub (tpair 0 m) : by simp,
have H3 : rel (tpair n 0) (tpair 0 m), from R_intro_refl quotient rel_refl H2,
have H4 : n + m = 0, from
calc
n + m = xx (tpair n 0) + yy (tpair 0 m) : by simp
... = yy (tpair n 0) + xx (tpair 0 m) : H3
... = 0 : by simp,
add_eq_zero H4
--some of these had to be transparent for theorem cases
set_opaque int true
set_opaque psub true
set_opaque proj true
-- ## add
theorem rel_add {a a' b b' : ℕ ## ℕ} (Ha : rel a a') (Hb : rel b b')
: rel (map_pair2 add a b) (map_pair2 add a' b')
:=
calc
xx (map_pair2 add a b) + yy (map_pair2 add a' b') = xx a + yy a' + (xx b + yy b') : by simp
... = yy a + xx a' + (xx b + yy b') : {Ha}
... = yy a + xx a' + (yy b + xx b') : {Hb}
... = yy (map_pair2 add a b) + xx (map_pair2 add a' b') : by simp
definition add : ℤ → ℤ → ℤ := quotient_map_binary quotient (map_pair2 nat::add)
infixl 65 + : add
theorem add_comp (n m k l : ℕ) : psub (tpair n m) + psub (tpair k l) = psub (tpair (n + k) (m + l))
:=
have H : ∀a b, psub a + psub b = psub (map_pair2 nat::add a b),
from comp_quotient_map_binary_refl rel_refl quotient @rel_add,
trans (H (tpair n m) (tpair k l)) (by simp)
add_rewrite add_comp --local
theorem add_comm (a b : ℤ) : a + b = b + a
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
obtain (xb yb : ℕ) (Hb : b = psub (tpair xb yb)), from destruct b,
by simp
theorem add_assoc (a b c : ℤ) : a + b + c = a + (b + c)
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
obtain (xb yb : ℕ) (Hb : b = psub (tpair xb yb)), from destruct b,
obtain (xc yc : ℕ) (Hc : c = psub (tpair xc yc)), from destruct c,
by simp
theorem add_left_comm (a b c : ℤ) : a + (b + c) = b + (a + c)
:= left_comm add_comm add_assoc a b c
theorem add_right_comm (a b c : ℤ) : a + b + c = a + c + b
:= right_comm add_comm add_assoc a b c
-- ### interaction of add with other functions and constants
theorem add_zero_right (a : ℤ) : a + 0 = a
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
have H0 : 0 = psub (tpair 0 0), from refl 0,
by simp
theorem add_zero_left (a : ℤ) : 0 + a = a
:= subst (add_zero_right a) (add_comm a 0)
theorem add_inverse_right (a : ℤ) : a + -a = 0
:=
have H : ∀n, psub (tpair n n) = 0, from eq_zero_intro,
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
by simp
theorem add_inverse_left (a : ℤ) : -a + a = 0
:= subst (add_inverse_right a) (add_comm a (-a))
theorem neg_add_distr (a b : ℤ) : -(a + b) = -a + -b
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
obtain (xb yb : ℕ) (Hb : b = psub (tpair xb yb)), from destruct b,
by simp
theorem triangle_inequality (a b : ℤ) : |a + b| ≤ |a| + |b| --note: ≤ is nat::≤
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
obtain (xb yb : ℕ) (Hb : b = psub (tpair xb yb)), from destruct b,
have H : dist (xa + xb) (ya + yb) ≤ dist xa ya + dist xb yb,
from dist_add_le_add_dist xa xb ya yb,
by simp
theorem add_of_nat (n m : ℕ) : of_nat n + of_nat m = n + m -- this is of_nat (n + m)
:=
have H : ∀n : ℕ, n = psub (tpair n 0), from take n : ℕ, refl n,
by simp
add_rewrite add_of_nat
theorem of_nat_succ (n : ℕ) : of_nat (succ n) = of_nat n + 1
:= by simp
-- ## sub
definition sub (a b : ℤ) : ℤ := a + -b
infixl 65 - : sub
theorem sub_def (a b : ℤ) : a - b = a + -b
:= refl (a - b)
theorem add_neg_right (a b : ℤ) : a + -b = a - b
:= refl (a - b)
theorem add_neg_left (a b : ℤ) : -a + b = b - a
:= add_comm (-a) b
theorem sub_neg_right (a b : ℤ) : a - (-b) = a + b
:= subst (refl (a - (-b))) (neg_neg b)
theorem sub_neg_neg (a b : ℤ) : -a - (-b) = b - a
:= subst (add_comm (-a) (-(-b))) (neg_neg b)
theorem sub_self (a : ℤ) : a - a = 0
:= add_inverse_right a
theorem sub_zero_right (a : ℤ) : a - 0 = a
:= substp (fun x, a + x = a) (add_zero_right a) (symm neg_zero)
---this doesn't work without explicit P
theorem sub_zero_left (a : ℤ) : 0 - a = -a
:= add_zero_left (-a)
theorem neg_sub (a b : ℤ) : -(a - b) = -a + b
:=
calc
-(a - b) = -a + -(-b) : neg_add_distr a (-b)
... = -a + b : {neg_neg b}
theorem neg_sub_flip (a b : ℤ) : -(a - b) = b - a
:=
calc
-(a - b) = -a + b : neg_sub a b
... = b - a : add_comm (-a) b
theorem sub_sub_assoc (a b c : ℤ) : a - b - c = a - (b + c)
:=
calc
a - b - c = a + (-b + -c) : add_assoc a (-b) (-c)
... = a + -(b + c) : {symm (neg_add_distr b c)}
theorem sub_add_assoc (a b c : ℤ) : a - b + c = a - (b - c)
:=
calc
a - b + c = a + (-b + c) : add_assoc a (-b) c
... = a + -(b - c) : {symm (neg_sub b c)}
theorem add_sub_assoc (a b c : ℤ) : a + b - c = a + (b - c)
:= add_assoc a b (-c)
theorem add_sub_inverse (a b : ℤ) : a + b - b = a
:=
calc
a + b - b = a + (b - b) : add_assoc a b (-b)
... = a + 0 : {sub_self b}
... = a : add_zero_right a
theorem add_sub_inverse2 (a b : ℤ) : a + b - a = b
:= subst (add_sub_inverse b a) (add_comm b a)
theorem sub_add_inverse (a b : ℤ) : a - b + b = a
:= subst (add_sub_inverse a b) (add_right_comm a b (-b))
add_rewrite add_zero_left add_zero_right
add_rewrite add_comm add_assoc add_left_comm
add_rewrite sub_def add_inverse_right add_inverse_left
add_rewrite neg_add_distr
--add_rewrite sub_sub_assoc sub_add_assoc add_sub_assoc
--add_rewrite add_neg_right add_neg_left
--add_rewrite sub_self
-- ### inversion theorems for add and sub
-- a + a = 0 -> a = 0
-- a = -a -> a = 0
theorem add_cancel_right {a b c : ℤ} (H : a + c = b + c) : a = b
:=
calc
a = a + c - c : symm (add_sub_inverse a c)
... = b + c - c : {H}
... = b : add_sub_inverse b c
theorem add_cancel_left {a b c : ℤ} (H : a + b = a + c) : b = c
:= add_cancel_right (subst (subst H (add_comm a b)) (add_comm a c))
theorem add_eq_zero_right {a b : ℤ} (H : a + b = 0) : -a = b
:=
have H2 : a + -a = a + b, from subst (symm H) (symm (add_inverse_right a)),
show -a = b, from add_cancel_left H2
theorem add_eq_zero_left {a b : ℤ} (H : a + b = 0) : -b = a
:= neg_move (add_eq_zero_right H)
theorem add_eq_self {a b : ℤ} (H : a + b = a) : b = 0
:= add_cancel_left (trans H (symm (add_zero_right a)))
theorem sub_inj_left {a b c : ℤ} (H : a - b = a - c) : b = c
:= neg_inj (add_cancel_left H)
theorem sub_inj_right {a b c : ℤ} (H : a - b = c - b) : a = c
:= add_cancel_right H
theorem sub_eq_zero {a b : ℤ} (H : a - b = 0) : a = b
:= neg_inj (add_eq_zero_right H)
theorem add_imp_sub_right {a b c : ℤ} (H : a + b = c) : c - b = a
:=
have H2 : c - b + b = a + b, from trans (sub_add_inverse c b) (symm H),
add_cancel_right H2
theorem add_imp_sub_left {a b c : ℤ} (H : a + b = c) : c - a = b
:= add_imp_sub_right (subst H (add_comm a b))
theorem sub_imp_add {a b c : ℤ} (H : a - b = c) : c + b = a
:= subst (add_imp_sub_right H) (neg_neg b)
theorem sub_imp_sub {a b c : ℤ} (H : a - b = c) : a - c = b
:= have H2 : c + b = a, from sub_imp_add H, add_imp_sub_left H2
theorem sub_add_add_right (a b c : ℤ) : a + c - (b + c) = a - b
:=
calc
a + c - (b + c) = a + (c - (b + c)) : add_sub_assoc a c (b + c)
... = a + (c - b - c) : {symm (sub_sub_assoc c b c)}
... = a + -b : {add_sub_inverse2 c (-b)}
theorem sub_add_add_left (a b c : ℤ) : c + a - (c + b) = a - b
:= subst (subst (sub_add_add_right a b c) (add_comm a c)) (add_comm b c)
theorem dist_def (n m : ℕ) : dist n m = |of_nat n - m|
:=
have H : of_nat n - m = psub (tpair n m), from
calc
psub (tpair n 0) + -psub (tpair m 0) = psub (tpair (n + 0) (0 + m)) : by simp
... = psub (tpair n m) : by simp,
calc
dist n m = |psub (tpair n m)| : by simp
... = |of_nat n - m| : {symm H}
-- ## mul
theorem rel_mul_prep {xa ya xb yb xn yn xm ym : ℕ} (H1 : xa + yb = ya + xb) (H2 : xn + ym = yn + xm)
: xa * xn + ya * yn + (xb * ym + yb * xm) = xa * yn + ya * xn + (xb * xm + yb * ym)
:=
have H3 : xa * xn + ya * yn + (xb * ym + yb * xm) + (yb * xn + xb * yn + (xb * xn + yb * yn))
= xa * yn + ya * xn + (xb * xm + yb * ym) + (yb * xn + xb * yn + (xb * xn + yb * yn)), from
calc
xa * xn + ya * yn + (xb * ym + yb * xm) + (yb * xn + xb * yn + (xb * xn + yb * yn))
= xa * xn + yb * xn + (ya * yn + xb * yn) + (xb * xn + xb * ym + (yb * yn + yb * xm)) : by simp
... = (xa + yb) * xn + (ya + xb) * yn + (xb * (xn + ym) + yb * (yn + xm)) : by simp_no_assump
... = (ya + xb) * xn + (xa + yb) * yn + (xb * (yn + xm) + yb * (xn + ym)) : by simp
... = ya * xn + xb * xn + (xa * yn + yb * yn) + (xb * yn + xb * xm + (yb*xn + yb*ym))
: by simp_no_assump
... = xa * yn + ya * xn + (xb * xm + yb * ym) + (yb * xn + xb * yn + (xb * xn + yb * yn)) : by simp,
nat::add_cancel_right H3
theorem rel_mul {u u' v v' : ℕ ## ℕ} (H1 : rel u u') (H2 : rel v v')
: rel (tpair (xx u * xx v + yy u * yy v) (xx u * yy v + yy u * xx v))
(tpair (xx u' * xx v' + yy u' * yy v') (xx u' * yy v' + yy u' * xx v'))
:=
calc
xx (tpair (xx u * xx v + yy u * yy v) (xx u * yy v + yy u * xx v))
+ yy (tpair (xx u' * xx v' + yy u' * yy v') (xx u' * yy v' + yy u' * xx v'))
= (xx u * xx v + yy u * yy v) + (xx u' * yy v' + yy u' * xx v') : by simp
... = (xx u * yy v + yy u * xx v) + (xx u' * xx v' + yy u' * yy v') : rel_mul_prep H1 H2
... = yy (tpair (xx u * xx v + yy u * yy v) (xx u * yy v + yy u * xx v))
+ xx (tpair (xx u' * xx v' + yy u' * yy v') (xx u' * yy v' + yy u' * xx v')) : by simp
definition mul : ℤ → ℤ → ℤ := quotient_map_binary quotient
(fun u v : ℕ ## ℕ, tpair (xx u * xx v + yy u * yy v) (xx u * yy v + yy u * xx v))
infixl 70 * : mul
theorem mul_comp (n m k l : ℕ)
: psub (tpair n m) * psub (tpair k l) = psub (tpair (n * k + m * l) (n * l + m * k))
:=
have H : ∀u v,
psub u * psub v = psub (tpair (xx u * xx v + yy u * yy v) (xx u * yy v + yy u * xx v)),
from comp_quotient_map_binary_refl rel_refl quotient @rel_mul,
trans (H (tpair n m) (tpair k l)) (by simp)
add_rewrite mul_comp
theorem mul_comm (a b : ℤ) : a * b = b * a
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
obtain (xb yb : ℕ) (Hb : b = psub (tpair xb yb)), from destruct b,
by simp
theorem mul_assoc (a b c : ℤ) : (a * b) * c = a * (b * c)
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
obtain (xb yb : ℕ) (Hb : b = psub (tpair xb yb)), from destruct b,
obtain (xc yc : ℕ) (Hc : c = psub (tpair xc yc)), from destruct c,
by simp
theorem mul_left_comm : ∀a b c : ℤ, a * (b * c) = b * (a * c)
:= left_comm mul_comm mul_assoc
theorem mul_right_comm : ∀a b c : ℤ, a * b * c = a * c * b
:= right_comm mul_comm mul_assoc
-- ### interaction with other objects
theorem mul_zero_right (a : ℤ) : a * 0 = 0
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
have H0 : 0 = psub (tpair 0 0), from refl 0,
by simp
theorem mul_zero_left (a : ℤ) : 0 * a = 0
:= subst (mul_zero_right a) (mul_comm a 0)
theorem mul_one_right (a : ℤ) : a * 1 = a
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
have H1 : 1 = psub (tpair 1 0), from refl 1,
by simp
theorem mul_one_left (a : ℤ) : 1 * a = a
:= subst (mul_one_right a) (mul_comm a 1)
theorem mul_neg_right (a b : ℤ) : a * -b = -(a * b)
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
obtain (xb yb : ℕ) (Hb : b = psub (tpair xb yb)), from destruct b,
by simp
theorem mul_neg_left (a b : ℤ) : -a * b = -(a * b)
:= subst (subst (mul_neg_right b a) (mul_comm b (-a))) (mul_comm b a)
add_rewrite mul_neg_right mul_neg_left
theorem mul_neg_neg (a b : ℤ) : -a * -b = a * b
:= by simp
theorem mul_distr_right (a b c : ℤ) : (a + b) * c = a * c + b * c
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
obtain (xb yb : ℕ) (Hb : b = psub (tpair xb yb)), from destruct b,
obtain (xc yc : ℕ) (Hc : c = psub (tpair xc yc)), from destruct c,
by simp
theorem mul_distr_left (a b c : ℤ) : a * (b + c) = a * b + a * c
:=
calc
a * (b + c) = (b + c) * a : mul_comm a (b + c)
... = b * a + c * a : mul_distr_right b c a
... = a * b + c * a : {mul_comm b a}
... = a * b + a * c : {mul_comm c a}
theorem mul_sub_distr_right (a b c : ℤ) : (a - b) * c = a * c - b * c
:=
calc
(a + -b) * c = a * c + -b * c : mul_distr_right a (-b) c
... = a * c + - (b * c) : {mul_neg_left b c}
theorem mul_sub_distr_left (a b c : ℤ) : a * (b - c) = a * b - a * c
:=
calc
a * (b + -c) = a * b + a * -c : mul_distr_left a b (-c)
... = a * b + - (a * c) : {mul_neg_right a c}
theorem mul_of_nat (n m : ℕ) : of_nat n * of_nat m = n * m
:=
have H : ∀n : ℕ, n = psub (tpair n 0), from take n : ℕ, refl n,
by simp
theorem mul_abs (a b : ℤ) : |a * b| = |a| * |b|
:=
obtain (xa ya : ℕ) (Ha : a = psub (tpair xa ya)), from destruct a,
obtain (xb yb : ℕ) (Hb : b = psub (tpair xb yb)), from destruct b,
have H : dist xa ya * dist xb yb = dist (xa * xb + ya * yb) (xa * yb + ya * xb),
from dist_mul_dist xa ya xb yb,
by simp
add_rewrite mul_zero_left mul_zero_right mul_one_right mul_one_left
add_rewrite mul_comm mul_assoc mul_left_comm
add_rewrite mul_distr_right mul_distr_left mul_of_nat
--mul_sub_distr_left mul_sub_distr_right
-- ---------- inversion
theorem mul_eq_zero {a b : ℤ} (H : a * b = 0) : a = 0 ∨ b = 0
:=
have H2 : |a| * |b| = 0, from
calc
|a| * |b| = |a * b| : symm (mul_abs a b)
... = |0| : {H}
... = 0 : abs_of_nat 0,
have H3 : |a| = 0 ∨ |b| = 0, from mul_eq_zero H2,
or_imp_or H3
(assume H : |a| = 0, abs_eq_zero H)
(assume H : |b| = 0, abs_eq_zero H)
theorem mul_cancel_left_or {a b c : ℤ} (H : a * b = a * c) : a = 0 ∨ b = c
:=
have H2 : a * (b - c) = 0, by simp,
have H3 : a = 0 ∨ b - c = 0, from mul_eq_zero H2,
or_imp_or_right H3 (assume H4 : b - c = 0, sub_eq_zero H4)
theorem mul_cancel_left {a b c : ℤ} (H1 : a ≠ 0) (H2 : a * b = a * c) : b = c
:= resolve_right (mul_cancel_left_or H2) H1
theorem mul_cancel_right_or {a b c : ℤ} (H : b * a = c * a) : a = 0 ∨ b = c
:= mul_cancel_left_or (subst (subst H (mul_comm b a)) (mul_comm c a))
theorem mul_cancel_right {a b c : ℤ} (H1 : c ≠ 0) (H2 : a * c = b * c) : a = b
:= resolve_right (mul_cancel_right_or H2) H1
theorem mul_ne_zero {a b : ℤ} (Ha : a ≠ 0) (Hb : b ≠ 0) : a * b ≠ 0
:=
not_intro
(assume H : a * b = 0,
or_elim (mul_eq_zero H)
(assume H2 : a = 0, absurd H2 Ha)
(assume H2 : b = 0, absurd H2 Hb))
theorem mul_ne_zero_left {a b : ℤ} (H : a * b ≠ 0) : a ≠ 0
:=
not_intro
(assume H2 : a = 0,
have H3 : a * b = 0, by simp,
absurd H3 H)
theorem mul_ne_zero_right {a b : ℤ} (H : a * b ≠ 0) : b ≠ 0
:= mul_ne_zero_left (subst H (mul_comm a b))
-- ## le
definition le (a b : ℤ) : Bool := ∃n : ℕ, a + n = b
infix 50 <= : le
infix 50 ≤ : le
-- definition le : ℤ → ℤ → Bool := rec_binary quotient (fun a b, xx a + yy b ≤ yy a + xx b)
-- theorem le_comp_alt (u v : ℕ ## ℕ) : (psub u ≤ psub v) ↔ (xx u + yy v ≤ yy u + xx v)
-- :=
-- comp_binary_refl quotient rel_refl
-- (take u u' v v' : ℕ ## ℕ,
-- assume Hu : rel u u',
-- assume Hv : rel v v',)
-- u v
-- theorem le_intro {a b : ℤ} {n : ℕ} (H : a + of_nat n = b) : a ≤ b
-- :=
-- have lemma : ∀u v, rel (map_pair2 nat::add u (tpair n 0)) v → xx u + yy v + n = yy u + xx v, from
-- take u v,
-- assume H : rel (map_pair2 nat::add u (tpair n 0)) v,
-- calc
-- xx u + yy v + n = xx u + n + yy v : nat::add_right_comm (xx u) (yy v) n
-- ... = xx (map_pair2 nat::add u (tpair n 0)) + yy v : by simp
-- ... = yy (map_pair2 nat::add u (tpair n 0)) + xx v : H
-- ... = yy u + 0 + xx v : by simp
-- ... = yy u + xx v : {nat::add_zero_right (yy u)},
-- have H2 :
theorem le_intro {a b : ℤ} {n : ℕ} (H : a + n = b) : a ≤ b
:= exists_intro n H
theorem le_elim {a b : ℤ} (H : a ≤ b) : ∃n : ℕ, a + n = b
:= H
-- ### partial order
theorem le_refl (a : ℤ) : a ≤ a
:= le_intro (add_zero_right a)
theorem le_of_nat (n m : ℕ) : (of_nat n ≤ of_nat m) ↔ (n ≤ m)
:=
iff_intro
(assume H : of_nat n ≤ of_nat m,
obtain (k : ℕ) (Hk : of_nat n + of_nat k = of_nat m), from le_elim H,
have H2 : n + k = m, from of_nat_inj (trans (symm (add_of_nat n k)) Hk),
nat::le_intro H2)
(assume H : n ≤ m,
obtain (k : ℕ) (Hk : n + k = m), from nat::le_elim H,
have H2 : of_nat n + of_nat k = of_nat m, from subst (add_of_nat n k) Hk,
le_intro H2)
theorem le_trans {a b c : ℤ} (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c
:=
obtain (n : ℕ) (Hn : a + n = b), from le_elim H1,
obtain (m : ℕ) (Hm : b + m = c), from le_elim H2,
have H3 : a + (n + m) = c, from
calc
a + (n + m) = a + (of_nat n + m) : {symm (add_of_nat n m)}
... = a + n + m : symm (add_assoc a n m)
... = b + m : {Hn}
... = c : Hm,
le_intro H3
theorem le_antisym {a b : ℤ} (H1 : a ≤ b) (H2 : b ≤ a) : a = b
:=
obtain (n : ℕ) (Hn : a + n = b), from le_elim H1,
obtain (m : ℕ) (Hm : b + m = a), from le_elim H2,
have H3 : a + (n + m) = a + 0, from
calc
a + (n + m) = a + (of_nat n + m) : {symm (add_of_nat n m)}
... = a + n + m : symm (add_assoc a n m)
... = b + m : {Hn}
... = a : Hm
... = a + 0 : symm (add_zero_right a),
have H4 : of_nat (n + m) = of_nat 0, from add_cancel_left H3,
have H5 : n + m = 0, from of_nat_inj H4,
have H6 : n = 0, from nat::add_eq_zero_left H5,
show a = b, from
calc
a = a + of_nat 0 : symm (add_zero_right a)
... = a + n : {symm H6}
... = b : Hn
-- ### interaction with add
theorem le_add_of_nat_right (a : ℤ) (n : ℕ) : a ≤ a + n
:= le_intro (refl (a + n))
theorem le_add_of_nat_left (a : ℤ) (n : ℕ) : a ≤ n + a
:= le_intro (add_comm a n)
theorem add_le_left {a b : ℤ} (H : a ≤ b) (c : ℤ) : c + a ≤ c + b
:=
obtain (n : ℕ) (Hn : a + n = b), from le_elim H,
have H2 : c + a + n = c + b, from
calc
c + a + n = c + (a + n) : add_assoc c a n
... = c + b : {Hn},
le_intro H2
theorem add_le_right {a b : ℤ} (H : a ≤ b) (c : ℤ) : a + c ≤ b + c
:= subst (subst (add_le_left H c) (add_comm c a)) (add_comm c b)
theorem add_le {a b c d : ℤ} (H1 : a ≤ b) (H2 : c ≤ d) : a + c ≤ b + d
:= le_trans (add_le_right H1 c) (add_le_left H2 b)
theorem add_le_cancel_right {a b c : ℤ} (H : a + c ≤ b + c) : a ≤ b
:=
have H2 : a + c - c ≤ b + c - c, from add_le_right H (-c),
subst (subst H2 (add_sub_inverse a c)) (add_sub_inverse b c)
theorem add_le_cancel_left {a b c : ℤ} (H : c + a ≤ c + b) : a ≤ b
:= add_le_cancel_right (subst (subst H (add_comm c a)) (add_comm c b))
theorem add_le_inv {a b c d : ℤ} (H1 : a + b ≤ c + d) (H2 : c ≤ a) : b ≤ d
:=
obtain (n : ℕ) (Hn : c + n = a), from le_elim H2,
have H3 : c + (n + b) ≤ c + d, from subst (subst H1 (symm Hn)) (add_assoc c n b),
have H4 : n + b ≤ d, from add_le_cancel_left H3,
show b ≤ d, from le_trans (le_add_of_nat_left b n) H4
theorem le_add_of_nat_right_trans {a b : ℤ} (H : a ≤ b) (n : ℕ) : a ≤ b + n
:= le_trans H (le_add_of_nat_right b n)
theorem le_imp_succ_le_or_eq {a b : ℤ} (H : a ≤ b) : a + 1 ≤ b ∨ a = b
:=
obtain (n : ℕ) (Hn : a + n = b), from le_elim H,
discriminate
(assume H2 : n = 0,
have H3 : a = b, from
calc
a = a + 0 : symm (add_zero_right a)
... = a + n : {symm H2}
... = b : Hn,
or_intro_right _ H3)
(take k : ℕ,
assume H2 : n = succ k,
have H3 : a + 1 + k = b, from
calc
a + 1 + k = a + succ k : by simp
... = a + n : by simp
... = b : Hn,
or_intro_left _ (le_intro H3))
-- ### interaction with neg and sub
theorem le_neg {a b : ℤ} (H : a ≤ b) : -b ≤ -a
:=
obtain (n : ℕ) (Hn : a + n = b), from le_elim H,
have H2 : b - n = a, from add_imp_sub_right Hn,
have H3 : -b + n = -a, from
calc
-b + n = -b + -(-n) : {symm (neg_neg n)}
... = -(b - n) : symm (neg_add_distr b (-n))
... = -a : {H2},
le_intro H3
theorem neg_le_zero {a : ℤ} (H : 0 ≤ a) : -a ≤ 0
:= subst (le_neg H) neg_zero
theorem zero_le_neg {a : ℤ} (H : a ≤ 0) : 0 ≤ -a
:= subst (le_neg H) neg_zero
theorem le_neg_inv {a b : ℤ} (H : -a ≤ -b) : b ≤ a
:= subst (subst (le_neg H) (neg_neg a)) (neg_neg b)
theorem le_sub_of_nat (a : ℤ) (n : ℕ) : a - n ≤ a
:= le_intro (sub_add_inverse a n)
theorem sub_le_right {a b : ℤ} (H : a ≤ b) (c : ℤ) : a - c ≤ b - c
:= add_le_right H (-c)
theorem sub_le_left {a b : ℤ} (H : a ≤ b) (c : ℤ) : c - b ≤ c - a
:= add_le_left (le_neg H) c
theorem sub_le {a b c d : ℤ} (H1 : a ≤ b) (H2 : d ≤ c) : a - c ≤ b - d
:= add_le H1 (le_neg H2)
theorem sub_le_right_inv {a b c : ℤ} (H : a - c ≤ b - c) : a ≤ b
:= add_le_cancel_right H
theorem sub_le_left_inv {a b c : ℤ} (H : c - a ≤ c - b) : b ≤ a
:= le_neg_inv (add_le_cancel_left H)
-- Less than, Greater than, Greater than or equal
-- ----------------------------------------------
definition lt (a b : ℤ) := a + 1 ≤ b
infix 50 < : lt
definition ge (a b : ℤ) := b ≤ a
infix 50 >= : ge
infix 50 ≥ : ge
definition gt (a b : ℤ) := b < a
infix 50 > : gt
theorem lt_def (a b : ℤ) : a < b ↔ a + 1 ≤ b
:= refl (a < b)
theorem gt_def (n m : ℕ) : n > m ↔ m < n
:= refl (n > m)
theorem ge_def (n m : ℕ) : n ≥ m ↔ m ≤ n
:= refl (n ≥ m)
add_rewrite gt_def ge_def --it might be possible to remove this in Lean 0.2
theorem lt_add_succ (a : ℤ) (n : ℕ) : a < a + succ n
:= le_intro (show a + 1 + n = a + succ n, by simp)
theorem lt_intro {a b : ℤ} {n : ℕ} (H : a + succ n = b) : a < b
:= subst (lt_add_succ a n) H
theorem lt_elim {a b : ℤ} (H : a < b) : ∃n : ℕ, a + succ n = b
:=
obtain (n : ℕ) (Hn : a + 1 + n = b), from le_elim H,
have H2 : a + succ n = b, from
calc
a + succ n = a + 1 + n : by simp_no_assump
... = b : Hn,
exists_intro n H2
-- -- ### basic facts
theorem lt_irrefl (a : ℤ) : ¬ a < a
:=
not_intro
(assume H : a < a,
obtain (n : ℕ) (Hn : a + succ n = a), from lt_elim H,
have H2 : a + succ n = a + 0, from
calc
a + succ n = a : Hn
... = a + 0 : by simp,
have H3 : succ n = 0, from add_cancel_left H2,
have H4 : succ n = 0, from of_nat_inj H3,
absurd H4 (succ_ne_zero n))
theorem lt_imp_ne {a b : ℤ} (H : a < b) : a ≠ b
:= not_intro (assume H2 : a = b, absurd (subst H H2) (lt_irrefl b))
theorem lt_of_nat (n m : ℕ) : (of_nat n < of_nat m) ↔ (n < m)
:=
calc
(of_nat n + 1 ≤ of_nat m) = (of_nat (succ n) ≤ of_nat m) : by simp
... = (succ n ≤ m) : le_of_nat (succ n) m
... = (n < m) : symm (nat::lt_def n m)
theorem gt_of_nat (n m : ℕ) : (of_nat n > of_nat m) ↔ (n > m)
:= lt_of_nat m n
-- ### interaction with le
theorem lt_imp_le_succ {a b : ℤ} (H : a < b) : a + 1 ≤ b
:= H
theorem le_succ_imp_lt {a b : ℤ} (H : a + 1 ≤ b) : a < b
:= H
theorem self_lt_succ (a : ℤ) : a < a + 1
:= le_refl (a + 1)
theorem lt_imp_le {a b : ℤ} (H : a < b) : a ≤ b
:=
obtain (n : ℕ) (Hn : a + succ n = b), from lt_elim H,
le_intro Hn
theorem le_imp_lt_or_eq {a b : ℤ} (H : a ≤ b) : a < b ∨ a = b
:= le_imp_succ_le_or_eq H
theorem le_ne_imp_lt {a b : ℤ} (H1 : a ≤ b) (H2 : a ≠ b) : a < b
:= resolve_left (le_imp_lt_or_eq H1) H2
theorem le_imp_lt_succ {a b : ℤ} (H : a ≤ b) : a < b + 1
:= add_le_right H 1
theorem lt_succ_imp_le {a b : ℤ} (H : a < b + 1) : a ≤ b
:= add_le_cancel_right H
-- ### transitivity, antisymmmetry
theorem lt_le_trans {a b c : ℤ} (H1 : a < b) (H2 : b ≤ c) : a < c
:= le_trans H1 H2
theorem le_lt_trans {a b c : ℤ} (H1 : a ≤ b) (H2 : b < c) : a < c
:= le_trans (add_le_right H1 1) H2
theorem lt_trans {a b c : ℤ} (H1 : a < b) (H2 : b < c) : a < c
:= lt_le_trans H1 (lt_imp_le H2)
theorem le_imp_not_gt {a b : ℤ} (H : a ≤ b) : ¬ a > b
:= not_intro (assume H2 : a > b, absurd (le_lt_trans H H2) (lt_irrefl a))
theorem lt_imp_not_ge {a b : ℤ} (H : a < b) : ¬ a ≥ b
:= not_intro (assume H2 : a ≥ b, absurd (lt_le_trans H H2) (lt_irrefl a))
theorem lt_antisym {a b : ℤ} (H : a < b) : ¬ b < a
:= le_imp_not_gt (lt_imp_le H)
-- ### interaction with addition
theorem add_lt_left {a b : ℤ} (H : a < b) (c : ℤ) : c + a < c + b
:= substp (fun x, x ≤ c + b) (add_le_left H c) (symm (add_assoc c a 1))
theorem add_lt_right {a b : ℤ} (H : a < b) (c : ℤ) : a + c < b + c
:= subst (subst (add_lt_left H c) (add_comm c a)) (add_comm c b)
theorem add_le_lt {a b c d : ℤ} (H1 : a ≤ c) (H2 : b < d) : a + b < c + d
:= le_lt_trans (add_le_right H1 b) (add_lt_left H2 c)
theorem add_lt_le {a b c d : ℤ} (H1 : a < c) (H2 : b ≤ d) : a + b < c + d
:= lt_le_trans (add_lt_right H1 b) (add_le_left H2 c)
theorem add_lt {a b c d : ℤ} (H1 : a < c) (H2 : b < d) : a + b < c + d
:= add_lt_le H1 (lt_imp_le H2)
theorem add_lt_cancel_left {a b c : ℤ} (H : c + a < c + b) : a < b
:= add_le_cancel_left (subst H (add_assoc c a 1))
theorem add_lt_cancel_right {a b c : ℤ} (H : a + c < b + c) : a < b
:= add_lt_cancel_left (subst (subst H (add_comm a c)) (add_comm b c))
-- ### interaction with neg and sub
theorem lt_neg {a b : ℤ} (H : a < b) : -b < -a
:=
have H2 : -(a + 1) + 1 = -a, by simp,
have H3 : -b ≤ -(a + 1), from le_neg H,
have H4 : -b + 1 ≤ -(a + 1) + 1, from add_le_right H3 1,
subst H4 H2
theorem neg_lt_zero {a : ℤ} (H : 0 < a) : -a < 0
:= subst (lt_neg H) neg_zero
theorem zero_lt_neg {a : ℤ} (H : a < 0) : 0 < -a
:= subst (lt_neg H) neg_zero
theorem lt_neg_inv {a b : ℤ} (H : -a < -b) : b < a
:= subst (subst (lt_neg H) (neg_neg a)) (neg_neg b)
theorem lt_sub_of_nat_succ (a : ℤ) (n : ℕ) : a - succ n < a
:= lt_intro (sub_add_inverse a (succ n))
theorem sub_lt_right {a b : ℤ} (H : a < b) (c : ℤ) : a - c < b - c
:= add_lt_right H (-c)
theorem sub_lt_left {a b : ℤ} (H : a < b) (c : ℤ) : c - b < c - a
:= add_lt_left (lt_neg H) c
theorem sub_lt {a b c d : ℤ} (H1 : a < b) (H2 : d < c) : a - c < b - d
:= add_lt H1 (lt_neg H2)
theorem sub_lt_right_inv {a b c : ℤ} (H : a - c < b - c) : a < b
:= add_lt_cancel_right H
theorem sub_lt_left_inv {a b c : ℤ} (H : c - a < c - b) : b < a
:= lt_neg_inv (add_lt_cancel_left H)
-- ### totality of lt and le
add_rewrite succ_pos zero_le --move some of these to nat.lean
add_rewrite le_of_nat lt_of_nat gt_of_nat --remove gt_of_nat in Lean 0.2
add_rewrite le_neg lt_neg neg_le_zero zero_le_neg zero_lt_neg neg_lt_zero
axiom sorry {P : Bool} : P
theorem neg_le_pos (n m : ℕ) : -n ≤ m
:=
have H1 : of_nat 0 ≤ of_nat m, by simp,
have H2 : -n ≤ 0, by simp,
le_trans H2 H1
theorem le_or_gt (a b : ℤ) : a ≤ b ∨ a > b
:=
int_by_cases a
(take n : ℕ,
int_by_cases_succ b
(take m : ℕ,
show of_nat n ≤ m ∨ of_nat n > m, from (by simp) ◂ (le_or_gt n m))
(take m : ℕ,
show n ≤ -succ m ∨ n > -succ m, from
have H0 : -succ m < -m, from lt_neg (subst (self_lt_succ m) (symm (of_nat_succ m))),
have H : -succ m < n, from lt_le_trans H0 (neg_le_pos m n),
or_intro_right _ H))
(take n : ℕ,
int_by_cases_succ b
(take m : ℕ,
show -n ≤ m ∨ -n > m, from
or_intro_left _ (neg_le_pos n m))
(take m : ℕ,
show -n ≤ -succ m ∨ -n > -succ m, from
or_imp_or (le_or_gt (succ m) n)
(assume H : succ m ≤ n,
le_neg (symm (le_of_nat (succ m) n) ◂ H))
(assume H : succ m > n,
lt_neg (symm (lt_of_nat n (succ m)) ◂ H))))
theorem trichotomy_alt (a b : ℤ) : (a < b ∨ a = b) ∨ a > b
:= or_imp_or_left (le_or_gt a b) (assume H : a ≤ b, le_imp_lt_or_eq H)
theorem trichotomy (a b : ℤ) : a < b ∨ a = b ∨ a > b
:= iff_elim_left (or_assoc _ _ _) (trichotomy_alt a b)
theorem le_total (a b : ℤ) : a ≤ b ∨ b ≤ a
:= or_imp_or_right (le_or_gt a b) (assume H : b < a, lt_imp_le H)
theorem not_lt_imp_le {a b : ℤ} (H : ¬ a < b) : b ≤ a
:= resolve_left (le_or_gt b a) H
theorem not_le_imp_lt {a b : ℤ} (H : ¬ a ≤ b) : b < a
:= resolve_right (le_or_gt a b) H
-- (non)positivity and (non)negativity
-- -------------------------------------
-- ### basic
-- see also "int_by_cases" and similar theorems
theorem pos_imp_exists_nat {a : ℤ} (H : a ≥ 0) : ∃n : ℕ, a = n
:=
obtain (n : ℕ) (Hn : of_nat 0 + n = a), from le_elim H,
exists_intro n (trans (symm Hn) (add_zero_left n))
theorem neg_imp_exists_nat {a : ℤ} (H : a ≤ 0) : ∃n : ℕ, a = -n
:=
have H2 : -a ≥ 0, from zero_le_neg H,
obtain (n : ℕ) (Hn : -a = n), from pos_imp_exists_nat H2,
have H3 : a = -n, from symm (neg_move Hn),
exists_intro n H3
theorem abs_pos {a : ℤ} (H : a ≥ 0) : |a| = a
:=
obtain (n : ℕ) (Hn : a = n), from pos_imp_exists_nat H,
subst (congr2 of_nat (abs_of_nat n)) (symm Hn)
--abs_neg is already taken... rename?
theorem abs_negative {a : ℤ} (H : a ≤ 0) : |a| = -a
:=
obtain (n : ℕ) (Hn : a = -n), from neg_imp_exists_nat H,
calc
|a| = | -n| : {Hn}
... = |n| : {abs_neg n}
... = n : {abs_of_nat n}
... = -a : symm (neg_move (symm Hn))
theorem abs_cases (a : ℤ) : a = |a| ∨ a = - |a|
:=
or_imp_or (le_total 0 a)
(assume H : a ≥ 0, symm (abs_pos H))
(assume H : a ≤ 0, symm (neg_move (symm (abs_negative H))))
-- ### interaction of mul with le and lt
theorem mul_le_left_nonneg {a b c : ℤ} (Ha : a ≥ 0) (H : b ≤ c) : a * b ≤ a * c
:=
obtain (n : ℕ) (Hn : b + n = c), from le_elim H,
have H2 : a * b + |a| * n = a * c, from
calc
a * b + |a| * n = a * b + |a| * of_nat n : by simp
... = a * b + a * n : {abs_pos Ha}
... = a * (b + n) : by simp_no_assump
... = a * c : by simp,
le_intro H2
theorem mul_le_right_nonneg {a b c : ℤ} (Hb : b ≥ 0) (H : a ≤ c) : a * b ≤ c * b
:= subst (subst (mul_le_left_nonneg Hb H) (mul_comm b a)) (mul_comm b c)
theorem mul_le_left_nonpos {a b c : ℤ} (Ha : a ≤ 0) (H : b ≤ c) : a * c ≤ a * b
:=
have H2 : -a * b ≤ -a * c, from mul_le_left_nonneg (zero_le_neg Ha) H,
have H3 : -(a * b) ≤ -(a * c), from subst (subst H2 (mul_neg_left a b)) (mul_neg_left a c),
le_neg_inv H3
theorem mul_le_right_nonpos {a b c : ℤ} (Hb : b ≤ 0) (H : c ≤ a) : a * b ≤ c * b
:= subst (subst (mul_le_left_nonpos Hb H) (mul_comm b a)) (mul_comm b c)
---this theorem can be made more general by replacing either Ha with 0 ≤ a or Hb with 0 ≤ d...
theorem mul_le_nonneg {a b c d : ℤ} (Ha : a ≥ 0) (Hb : b ≥ 0) (Hc : a ≤ c) (Hd : b ≤ d)
: a * b ≤ c * d
:= le_trans (mul_le_right_nonneg Hb Hc) (mul_le_left_nonneg (le_trans Ha Hc) Hd)
theorem mul_le_nonpos {a b c d : ℤ} (Ha : a ≤ 0) (Hb : b ≤ 0) (Hc : c ≤ a) (Hd : d ≤ b)
: a * b ≤ c * d
:= le_trans (mul_le_right_nonpos Hb Hc) (mul_le_left_nonpos (le_trans Hc Ha) Hd)
theorem mul_lt_left_pos {a b c : ℤ} (Ha : a > 0) (H : b < c) : a * b < a * c
:=
have H2 : a * b < a * b + a, from subst (add_lt_left Ha (a * b)) (add_zero_right (a * b)),
have H3 : a * b + a ≤ a * c, from subst (mul_le_left_nonneg (lt_imp_le Ha) H) (by simp),
lt_le_trans H2 H3
theorem mul_lt_right_pos {a b c : ℤ} (Hb : b > 0) (H : a < c) : a * b < c * b
:= subst (subst (mul_lt_left_pos Hb H) (mul_comm b a)) (mul_comm b c)
theorem mul_lt_left_neg {a b c : ℤ} (Ha : a < 0) (H : b < c) : a * c < a * b
:=
have H2 : -a * b < -a * c, from mul_lt_left_pos (zero_lt_neg Ha) H,
have H3 : -(a * b) < -(a * c), from subst (subst H2 (mul_neg_left a b)) (mul_neg_left a c),
lt_neg_inv H3
theorem mul_lt_right_neg {a b c : ℤ} (Hb : b < 0) (H : c < a) : a * b < c * b
:= subst (subst (mul_lt_left_neg Hb H) (mul_comm b a)) (mul_comm b c)
theorem mul_le_lt_pos {a b c d : ℤ} (Ha : a > 0) (Hb : b ≥ 0) (Hc : a ≤ c) (Hd : b < d)
: a * b < c * d
:= le_lt_trans (mul_le_right_nonneg Hb Hc) (mul_lt_left_pos (lt_le_trans Ha Hc) Hd)
theorem mul_lt_le_pos {a b c d : ℤ} (Ha : a ≥ 0) (Hb : b > 0) (Hc : a < c) (Hd : b ≤ d)
: a * b < c * d
:= lt_le_trans (mul_lt_right_pos Hb Hc) (mul_le_left_nonneg (le_trans Ha (lt_imp_le Hc)) Hd)
theorem mul_lt_pos {a b c d : ℤ} (Ha : a > 0) (Hb : b > 0) (Hc : a < c) (Hd : b < d)
: a * b < c * d
:= mul_lt_le_pos (lt_imp_le Ha) Hb Hc (lt_imp_le Hd)
theorem mul_lt_neg {a b c d : ℤ} (Ha : a < 0) (Hb : b < 0) (Hc : c < a) (Hd : d < b)
: a * b < c * d
:= lt_trans (mul_lt_right_neg Hb Hc) (mul_lt_left_neg (lt_trans Hc Ha) Hd)
-- theorem mul_le_lt_neg and mul_lt_le_neg?
theorem mul_lt_cancel_left_nonneg {a b c : ℤ} (Hc : c ≥ 0) (H : c * a < c * b) : a < b
:=
or_elim (le_or_gt b a)
(assume H2 : b ≤ a,
have H3 : c * b ≤ c * a, from mul_le_left_nonneg Hc H2,
absurd_elim _ H3 (lt_imp_not_ge H))
(assume H2 : a < b, H2)
theorem mul_lt_cancel_right_nonneg {a b c : ℤ} (Hc : c ≥ 0) (H : a * c < b * c) : a < b
:= mul_lt_cancel_left_nonneg Hc (subst (subst H (mul_comm a c)) (mul_comm b c))
theorem mul_lt_cancel_left_nonpos {a b c : ℤ} (Hc : c ≤ 0) (H : c * b < c * a) : a < b
:=
have H2 : -(c * a) < -(c * b), from lt_neg H,
have H3 : -c * a < -c * b,
from subst (subst H2 (symm (mul_neg_left c a))) (symm (mul_neg_left c b)),
have H4 : -c ≥ 0, from zero_le_neg Hc,
mul_lt_cancel_left_nonneg H4 H3
theorem mul_lt_cancel_right_nonpos {a b c : ℤ} (Hc : c ≤ 0) (H : b * c < a * c) : a < b
:= mul_lt_cancel_left_nonpos Hc (subst (subst H (mul_comm a c)) (mul_comm b c))
theorem mul_le_cancel_left_pos {a b c : ℤ} (Hc : c > 0) (H : c * a ≤ c * b) : a ≤ b
:=
or_elim (le_or_gt a b)
(assume H2 : a ≤ b, H2)
(assume H2 : a > b,
have H3 : c * a > c * b, from mul_lt_left_pos Hc H2,
absurd_elim _ H3 (le_imp_not_gt H))
theorem mul_le_cancel_right_pos {a b c : ℤ} (Hc : c > 0) (H : a * c ≤ b * c) : a ≤ b
:= mul_le_cancel_left_pos Hc (subst (subst H (mul_comm a c)) (mul_comm b c))
theorem mul_le_cancel_left_neg {a b c : ℤ} (Hc : c < 0) (H : c * b ≤ c * a) : a ≤ b
:=
have H2 : -(c * a) ≤ -(c * b), from le_neg H,
have H3 : -c * a ≤ -c * b,
from subst (subst H2 (symm (mul_neg_left c a))) (symm (mul_neg_left c b)),
have H4 : -c > 0, from zero_lt_neg Hc,
mul_le_cancel_left_pos H4 H3
theorem mul_le_cancel_right_neg {a b c : ℤ} (Hc : c < 0) (H : b * c ≤ a * c) : a ≤ b
:= mul_le_cancel_left_neg Hc (subst (subst H (mul_comm a c)) (mul_comm b c))
theorem mul_eq_one_left {a b : ℤ} (H : a * b = 1) : a = 1 ∨ a = - 1
:=
have H2 : |a| * |b| = 1, from
calc
|a| * |b| = |a * b| : symm (mul_abs a b)
... = |1| : {H}
... = 1 : abs_of_nat 1,
have H3 : |a| = 1, from mul_eq_one_left H2,
or_imp_or (abs_cases a)
(assume H4 : a = |a|, subst H4 H3)
(assume H4 : a = - |a|, subst H4 H3)
theorem mul_eq_one_right {a b : ℤ} (H : a * b = 1) : b = 1 ∨ b = - 1
:= mul_eq_one_left (subst H (mul_comm a b))
-- sign function
-- -------------
definition sign (a : ℤ) : ℤ := if a > 0 then 1 else (if a < 0 then - 1 else 0)
--for kernel
theorem or_elim3 {a b c d : Bool} (H : a ∨ b ∨ c) (Ha : a → d) (Hb : b → d) (Hc : c → d) : d
:= or_elim H Ha (assume H2,or_elim H2 Hb Hc)
theorem sign_pos {a : ℤ} (H : a > 0) : sign a = 1
:= imp_if_eq H _ _
theorem sign_negative {a : ℤ} (H : a < 0) : sign a = - 1
:= trans (not_imp_if_eq (lt_antisym H) _ _) (imp_if_eq H _ _)
theorem sign_zero : sign 0 = 0
:= trans (not_imp_if_eq (lt_irrefl 0) _ _) (not_imp_if_eq (lt_irrefl 0) _ _)
add_rewrite sign_negative sign_pos abs_negative abs_pos sign_zero mul_abs
theorem mul_sign_abs (a : ℤ) : sign a * |a| = a
:=
have temp1 : ∀a : ℤ, a < 0 → a ≤ 0, from take a, lt_imp_le,
have temp2 : ∀a : ℤ, a > 0 → a ≥ 0, from take a, lt_imp_le,
or_elim3 (trichotomy a 0)
(assume H : a < 0, by simp)
(assume H : a = 0, by simp)
(assume H : a > 0, by simp)
theorem sign_mul (a b : ℤ) : sign (a * b) = sign a * sign b
:=
by_cases
(assume Ha : a = 0, by simp)
(assume Ha : a ≠ 0,
by_cases
(assume Hb : b = 0, by simp)
(assume Hb : b ≠ 0,
have H : sign (a * b) * |a * b| = sign a * sign b * |a * b|, from
calc
sign (a * b) * |a * b| = a * b : mul_sign_abs (a * b)
... = sign a * |a| * b : {symm (mul_sign_abs a)}
... = sign a * |a| * (sign b * |b|) : {symm (mul_sign_abs b)}
... = sign a * sign b * |a * b| : by simp,
have H2 : |a * b| ≠ 0, from contrapos (@abs_eq_zero (a * b)) (mul_ne_zero Ha Hb),
have H3 : |a * b| ≠ of_nat 0, from contrapos of_nat_inj H2,
mul_cancel_right H3 H))
--set_option pp::coercion true
theorem sign_idempotent (a : ℤ) : sign (sign a) = sign a
:=
have temp : of_nat 1 > 0, from symm (lt_of_nat 0 1) ◂ (succ_pos 0),--this should be done with simp
or_elim3 (trichotomy a 0)
(by simp)
(by simp)
(by simp)
theorem sign_succ (n : ℕ) : sign (succ n) = 1
:= sign_pos (symm (lt_of_nat 0 (succ n)) ◂ succ_pos n) --this should be done with simp
theorem sign_neg (a : ℤ) : sign (-a) = - sign a
:=
have temp1 : a > 0 → -a < 0, from neg_lt_zero,
have temp2 : a < 0 → -a > 0, from zero_lt_neg,
or_elim3 (trichotomy a 0)
(by simp)
(by simp)
(by simp)
add_rewrite sign_neg
theorem abs_sign_ne_zero {a : ℤ} (H : a ≠ 0) : |sign a| = 1
:=
or_elim3 (trichotomy a 0)
(by simp)
(assume H2 : a = 0, absurd_elim _ H2 H)
(by simp)
theorem sign_abs (a : ℤ) : sign (abs a) = abs (sign a)
:=
have temp1 : ∀a : ℤ, a < 0 → a ≤ 0, from take a, lt_imp_le,
have temp2 : ∀a : ℤ, a > 0 → a ≥ 0, from take a, lt_imp_le,
or_elim3 (trichotomy a 0)
(by simp)
(by simp)
(by simp)
set_opaque rel true
set_opaque rep true
set_opaque of_nat true
set_opaque abs true
set_opaque neg true
set_opaque add true
set_opaque mul true
set_opaque le true
set_opaque lt true
set_opaque sign true
--transparent: sub ge gt
end -- namespace int
|
99335d9d1bbf88eb893c5633fd17bea0679ffc7f | a162e54d0534f0863de20e911278e6c41ba96e28 | /src/imo2008_q2.lean | d658db37a86b4318addd67fbafc0105c6c58b76e | [
"Apache-2.0"
] | permissive | manuelcandales/imo-lean | 0ef79d470b58064d16a94adfb83711ae3265a19a | fa54938100fc84c98fe04e1d19e20a424dd006e7 | refs/heads/master | 1,680,228,525,536 | 1,617,602,898,000 | 1,617,602,898,000 | 353,518,197 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 6,275 | lean | /-
Copyright (c) 2021 Manuel Candales. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Manuel Candales
-/
import data.real.basic
import data.set.basic
import data.set.finite
/-!
# IMO 2008 Q2
(a) Prove that
```x^2 / (x-1)^2 + y^2 / (y-1)^2 + z^2 / (z-1)^2 ≥ 1```
for all real numbers x, y, z, each different from 1, and satisfying xyz = 1.
(b) Prove that equality holds above for infinitely many triples of rational numbers x, y, z, each
different from 1, and satisfying xyz = 1.
# Solution
(a) Since xyz = 1, we can apply the substitution x = a/b, y = b/c, z = c/a.
Then we define m = c-b, n = b-a and rewrite the inequality as LHS - 1 ≥ 0
using c, m and n. We factor LHS - 1 as a square, which finishes the proof.
(b) We present a set W of rational triples. We prove that W is a subset of the
set of rational solutions to the equation, and that W is infinite.
-/
lemma subst_abc (x y z : ℝ) (h : x*y*z = 1) :
∃ a b c : ℝ, a ≠ 0 ∧ b ≠ 0 ∧ c ≠ 0 ∧ x = a/b ∧ y = b/c ∧ z = c /a :=
begin
use x, use 1, use 1/y,
have h₁ : x ≠ 0, { intro p, rw p at h, simp at h, exact h },
have h₂ : (1 : ℝ) ≠ (0 : ℝ), exact one_ne_zero,
have hy_ne_zero : y ≠ 0, { intro p, rw p at h, simp at h, exact h },
have h₃ : 1/y ≠ 0, exact one_div_ne_zero hy_ne_zero,
have h₄ : x = x / 1, exact (div_one x).symm,
have h₅ : y = 1 / (1 / y), exact (one_div_one_div y).symm,
have h₆ : z = 1 / y / x, { field_simp, linarith [h] },
exact ⟨h₁, h₂, h₃, h₄, h₅, h₆⟩,
end
theorem imo2008_q2a (x y z : ℝ) (h : x*y*z = 1) (hx : x ≠ 1) (hy : y ≠ 1) (hz : z ≠ 1) :
x^2 / (x-1)^2 + y^2 / (y-1)^2 + z^2 / (z-1)^2 ≥ 1 :=
begin
rcases (subst_abc _ _ _ h) with ⟨a, b, c, ha, hb, hc, hx₂, hy₂, hz₂⟩,
let m := c-b,
let n := b-a,
have hm_abc : m = c - b, exact rfl,
have hn_abc : n = b - a, exact rfl,
have ha_cmn : a = c - m - n, linarith,
have hb_cmn : b = c - m, linarith,
have hab_mn : (a-b)^2 = n^2, { rw [ha_cmn, hb_cmn], ring },
have hbc_mn : (b-c)^2 = m^2, rw hb_cmn, ring,
have hca_mn : (c-a)^2 = (m+n)^2, rw ha_cmn, ring,
have hm_ne_zero : m ≠ 0,
{ rw hm_abc, rw hy₂ at hy, intro p, apply hy, field_simp, linarith },
have hn_ne_zero : n ≠ 0,
{ rw hn_abc, rw hx₂ at hx, intro p, apply hx, field_simp, linarith },
have hmn_ne_zero : m + n ≠ 0,
{ rw hm_abc, rw hn_abc, rw hz₂ at hz, intro p, apply hz, field_simp, linarith },
have key : x^2 / (x-1)^2 + y^2 / (y-1)^2 + z^2 / (z-1)^2 - 1 ≥ 0,
calc x^2 / (x-1)^2 + y^2 / (y-1)^2 + z^2 / (z-1)^2 - 1
= (a/b)^2 / (a/b-1)^2 + (b/c)^2 / (b/c-1)^2 + (c/a)^2 / (c/a-1)^2 - 1 :
by rw [hx₂, hy₂, hz₂]
... = a^2/(a-b)^2 + b^2/(b-c)^2 + c^2/(c-a)^2 - 1 :
by field_simp [div_sub_one hb, div_sub_one hc, div_sub_one ha]
... = (c-m-n)^2/n^2 + (c-m)^2/m^2 + c^2/(m+n)^2 - 1 :
by rw [hab_mn, hbc_mn, hca_mn, ha_cmn, hb_cmn]
... = ( (c*(m^2+n^2+m*n) - m*(m+n)^2) / (m*n*(m+n)) )^2 :
by { ring_nf, field_simp, ring }
... ≥ 0 :
by exact pow_two_nonneg _ ,
linarith [key],
end
def rational_solutions := { s : ℚ×ℚ×ℚ | ∃ (x y z : ℚ), s = (x, y, z) ∧
x ≠ 1 ∧ y ≠ 1 ∧ z ≠ 1 ∧ x*y*z = 1 ∧ x^2/(x-1)^2 + y^2/(y-1)^2 + z^2/(z-1)^2 = 1 }
theorem imo2008_q2b : set.infinite rational_solutions :=
begin
let W := { s : ℚ×ℚ×ℚ | ∃ (x y z : ℚ), s = (x, y, z) ∧
∃ t : ℚ, t > 0 ∧ x = -(t+1)/t^2 ∧ y = t/(t+1)^2 ∧ z = -t*(t+1)},
have hW_sub_S : W ⊆ rational_solutions,
{ intros s hs_in_W,
rw rational_solutions,
simp at hs_in_W ⊢,
rcases hs_in_W with ⟨x, y, z, hs_xyz, ht⟩,
rcases ht with ⟨t, ht_gt_zero, hx_t, hy_t, hz_t⟩,
use x, use y, use z,
have ht_ne_zero : t ≠ 0, exact ne_of_gt ht_gt_zero,
have ht1_ne_zero : t+1 ≠ 0, linarith[ht_gt_zero],
have key_gt_zero : t^2 + t + 1 > 0, linarith[pow_pos ht_gt_zero 2, ht_gt_zero],
have key_ne_zero : t^2 + t + 1 ≠ 0, exact ne_of_gt key_gt_zero,
have h₂ : x ≠ 1, { rw hx_t, field_simp, linarith[key_gt_zero] },
have h₃ : y ≠ 1, { rw hy_t, field_simp, linarith[key_gt_zero] },
have h₄ : z ≠ 1, { rw hz_t, linarith[key_gt_zero] },
have h₅ : x*y*z = 1, { rw [hx_t, hy_t, hz_t], field_simp, ring },
have h₆ : x^2/(x-1)^2 + y^2/(y-1)^2 + z^2/(z-1)^2 = 1,
{ have hx1 : (x - 1)^2 = (t^2 + t + 1)^2/t^4,
{ field_simp, rw hx_t, field_simp, ring },
have hy1 : (y - 1)^2 = (t^2 + t + 1)^2/(t+1)^4,
{ field_simp, rw hy_t, field_simp, ring },
have hz1 : (z - 1)^2 = (t^2 + t + 1)^2,
{ rw hz_t, ring },
calc x^2/(x-1)^2 + y^2/(y-1)^2 + z^2/(z-1)^2
= (x^2*t^4 + y^2*(t+1)^4 + z^2)/(t^2 + t + 1)^2 :
by { rw [hx1, hy1, hz1], field_simp }
... = 1 :
by { rw [hx_t, hy_t, hz_t], field_simp, ring } },
exact ⟨hs_xyz, h₂, h₃, h₄, h₅, h₆⟩,
},
have hW_inf : set.infinite W,
{ let g : ℚ×ℚ×ℚ → ℚ := (λs, -s.2.2),
let Z := g '' W,
have hZ_not_bdd : ¬bdd_above Z,
{ rw not_bdd_above_iff,
intro q,
let t : ℚ := max (q+1) 1,
use t*(t+1),
let x : ℚ := (-1 + -t)/t^2,
let y : ℚ := t/(t+1)^2,
let z : ℚ := -t*(t+1),
have hz_def : z = -t*(t+1), exact rfl,
split,
{ simp, use x, use y, use z, split,
{ use x, use y, use z, split,
{ split, refl, split, refl, refl },
{ use t, split,
{ simp, right, exact zero_lt_one },
{ split, refl, split, refl, linarith[hz_def] } } },
{ have hg_eval : g(x, y, z) = -z, exact rfl,
rw hg_eval, linarith[hz_def] } },
{ calc q < q + 1 : by { linarith }
... ≤ t : by { exact le_max_left (q + 1) 1 }
... ≤ t+t^2 : by { linarith [pow_two_nonneg t] }
... = t*(t+1) : by { ring } },
},
have hZ_inf : set.infinite Z,
{ intro h, apply hZ_not_bdd, exact set.finite.bdd_above h },
exact set.infinite_of_infinite_image g hZ_inf,
},
exact set.infinite_mono hW_sub_S hW_inf,
end
|
bc6e4c638779fec396096eb62295efcb9a334209 | d1a52c3f208fa42c41df8278c3d280f075eb020c | /src/Lean/Meta/GetConst.lean | 7dc792ff2d46c3ac8c55c6134367a1f7791d1135 | [
"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 | 1,656 | lean | /-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Meta.GlobalInstances
namespace Lean.Meta
private def canUnfoldDefault (cfg : Config) (info : ConstantInfo) : CoreM Bool := do
match cfg.transparency with
| TransparencyMode.all => return true
| TransparencyMode.default => return true
| m =>
if (← isReducible info.name) then
return true
else if m == TransparencyMode.instances && isGlobalInstance (← getEnv) info.name then
return true
else
return false
def canUnfold (info : ConstantInfo) : MetaM Bool := do
let ctx ← read
if let some f := ctx.canUnfold? then
f ctx.config info
else
canUnfoldDefault ctx.config info
def getConst? (constName : Name) : MetaM (Option ConstantInfo) := do
let env ← getEnv
match env.find? constName with
| some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info
| some (info@(ConstantInfo.defnInfo _)) => if (← canUnfold info) then return info else return none
| some info => pure (some info)
| none => throwUnknownConstant constName
def getConstNoEx? (constName : Name) : MetaM (Option ConstantInfo) := do
let env ← getEnv
match env.find? constName with
| some (info@(ConstantInfo.thmInfo _)) => getTheoremInfo info
| some (info@(ConstantInfo.defnInfo _)) => if (← canUnfold info) then return info else return none
| some info => pure (some info)
| none => pure none
end Meta
|
ff0b9ff2ad72a9bea2bbacacb67bdd6b628e3ed1 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/analysis/calculus/mean_value.lean | bf83cd7b330ec8363519758d2875dac71b1df10d | [
"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,803 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel, Yury Kudryashov
-/
import analysis.calculus.local_extr
import analysis.convex.slope
import analysis.convex.topology
import data.complex.is_R_or_C
/-!
# The mean value inequality and equalities
In this file we prove the following facts:
* `convex.norm_image_sub_le_of_norm_deriv_le` : if `f` is differentiable on a convex set `s`
and the norm of its derivative is bounded by `C`, then `f` is Lipschitz continuous on `s` with
constant `C`; also a variant in which what is bounded by `C` is the norm of the difference of the
derivative from a fixed linear map. This lemma and its versions are formulated using `is_R_or_C`,
so they work both for real and complex derivatives.
* `image_le_of*`, `image_norm_le_of_*` : several similar lemmas deducing `f x ≤ B x` or
`∥f x∥ ≤ B x` from upper estimates on `f'` or `∥f'∥`, respectively. These lemmas differ by
their assumptions:
* `of_liminf_*` lemmas assume that limit inferior of some ratio is less than `B' x`;
* `of_deriv_right_*`, `of_norm_deriv_right_*` lemmas assume that the right derivative
or its norm is less than `B' x`;
* `of_*_lt_*` lemmas assume a strict inequality whenever `f x = B x` or `∥f x∥ = B x`;
* `of_*_le_*` lemmas assume a non-strict inequality everywhere on `[a, b)`;
* name of a lemma ends with `'` if (1) it assumes that `B` is continuous on `[a, b]`
and has a right derivative at every point of `[a, b)`, and (2) the lemma has
a counterpart assuming that `B` is differentiable everywhere on `ℝ`
* `norm_image_sub_le_*_segment` : if derivative of `f` on `[a, b]` is bounded above
by a constant `C`, then `∥f x - f a∥ ≤ C * ∥x - a∥`; several versions deal with
right derivative and derivative within `[a, b]` (`has_deriv_within_at` or `deriv_within`).
* `convex.is_const_of_fderiv_within_eq_zero` : if a function has derivative `0` on a convex set `s`,
then it is a constant on `s`.
* `exists_ratio_has_deriv_at_eq_ratio_slope` and `exists_ratio_deriv_eq_ratio_slope` :
Cauchy's Mean Value Theorem.
* `exists_has_deriv_at_eq_slope` and `exists_deriv_eq_slope` : Lagrange's Mean Value Theorem.
* `domain_mvt` : Lagrange's Mean Value Theorem, applied to a segment in a convex domain.
* `convex.image_sub_lt_mul_sub_of_deriv_lt`, `convex.mul_sub_lt_image_sub_of_lt_deriv`,
`convex.image_sub_le_mul_sub_of_deriv_le`, `convex.mul_sub_le_image_sub_of_le_deriv`,
if `∀ x, C (</≤/>/≥) (f' x)`, then `C * (y - x) (</≤/>/≥) (f y - f x)` whenever `x < y`.
* `convex.monotone_on_of_deriv_nonneg`, `convex.antitone_on_of_deriv_nonpos`,
`convex.strict_mono_of_deriv_pos`, `convex.strict_anti_of_deriv_neg` :
if the derivative of a function is non-negative/non-positive/positive/negative, then
the function is monotone/antitone/strictly monotone/strictly monotonically
decreasing.
* `convex_on_of_deriv_monotone_on`, `convex_on_of_deriv2_nonneg` : if the derivative of a function
is increasing or its second derivative is nonnegative, then the original function is convex.
* `strict_fderiv_of_cont_diff` : a C^1 function over the reals is strictly differentiable. (This
is a corollary of the mean value inequality.)
-/
variables {E : Type*} [normed_group E] [normed_space ℝ E]
{F : Type*} [normed_group F] [normed_space ℝ F]
open metric set asymptotics continuous_linear_map filter
open_locale classical topological_space nnreal
/-! ### One-dimensional fencing inequalities -/
/-- General fencing theorem for continuous functions with an estimate on the derivative.
Let `f` and `B` be continuous functions on `[a, b]` such that
* `f a ≤ B a`;
* `B` has right derivative `B'` at every point of `[a, b)`;
* for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)`
is bounded above by a function `f'`;
* we have `f' x < B' x` whenever `f x = B x`.
Then `f x ≤ B x` everywhere on `[a, b]`. -/
lemma image_le_of_liminf_slope_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ}
(hf : continuous_on f (Icc a b))
-- `hf'` actually says `liminf (f z - f x) / (z - x) ≤ f' x`
(hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[>] x, slope f x z < r)
{B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b))
(hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x)
(bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) :
∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x :=
begin
change Icc a b ⊆ {x | f x ≤ B x},
set s := {x | f x ≤ B x} ∩ Icc a b,
have A : continuous_on (λ x, (f x, B x)) (Icc a b), from hf.prod hB,
have : is_closed s,
{ simp only [s, inter_comm],
exact A.preimage_closed_of_closed is_closed_Icc order_closed_topology.is_closed_le' },
apply this.Icc_subset_of_forall_exists_gt ha,
rintros x ⟨hxB : f x ≤ B x, xab⟩ y hy,
cases hxB.lt_or_eq with hxB hxB,
{ -- If `f x < B x`, then all we need is continuity of both sides
refine nonempty_of_mem (inter_mem _ (Ioc_mem_nhds_within_Ioi ⟨le_rfl, hy⟩)),
have : ∀ᶠ x in 𝓝[Icc a b] x, f x < B x,
from A x (Ico_subset_Icc_self xab)
(is_open.mem_nhds (is_open_lt continuous_fst continuous_snd) hxB),
have : ∀ᶠ x in 𝓝[>] x, f x < B x,
from nhds_within_le_of_mem (Icc_mem_nhds_within_Ioi xab) this,
exact this.mono (λ y, le_of_lt) },
{ rcases exists_between (bound x xab hxB) with ⟨r, hfr, hrB⟩,
specialize hf' x xab r hfr,
have HB : ∀ᶠ z in 𝓝[>] x, r < slope B x z,
from (has_deriv_within_at_iff_tendsto_slope' $ lt_irrefl x).1
(hB' x xab).Ioi_of_Ici (Ioi_mem_nhds hrB),
obtain ⟨z, hfz, hzB, hz⟩ :
∃ z, slope f x z < r ∧ r < slope B x z ∧ z ∈ Ioc x y,
from (hf'.and_eventually (HB.and (Ioc_mem_nhds_within_Ioi ⟨le_rfl, hy⟩))).exists,
refine ⟨z, _, hz⟩,
have := (hfz.trans hzB).le,
rwa [slope_def_field, slope_def_field, div_le_div_right (sub_pos.2 hz.1), hxB,
sub_le_sub_iff_right] at this }
end
/-- General fencing theorem for continuous functions with an estimate on the derivative.
Let `f` and `B` be continuous functions on `[a, b]` such that
* `f a ≤ B a`;
* `B` has derivative `B'` everywhere on `ℝ`;
* for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)`
is bounded above by a function `f'`;
* we have `f' x < B' x` whenever `f x = B x`.
Then `f x ≤ B x` everywhere on `[a, b]`. -/
lemma image_le_of_liminf_slope_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ}
(hf : continuous_on f (Icc a b))
-- `hf'` actually says `liminf (f z - f x) / (z - x) ≤ f' x`
(hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r → ∃ᶠ z in 𝓝[>] x, slope f x z < r)
{B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x)
(bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) :
∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x :=
image_le_of_liminf_slope_right_lt_deriv_boundary' hf hf' ha
(λ x hx, (hB x).continuous_at.continuous_within_at)
(λ x hx, (hB x).has_deriv_within_at) bound
/-- General fencing theorem for continuous functions with an estimate on the derivative.
Let `f` and `B` be continuous functions on `[a, b]` such that
* `f a ≤ B a`;
* `B` has right derivative `B'` at every point of `[a, b)`;
* for each `x ∈ [a, b)` the right-side limit inferior of `(f z - f x) / (z - x)`
is bounded above by `B'`.
Then `f x ≤ B x` everywhere on `[a, b]`. -/
lemma image_le_of_liminf_slope_right_le_deriv_boundary {f : ℝ → ℝ} {a b : ℝ}
(hf : continuous_on f (Icc a b))
{B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b))
(hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x)
-- `bound` actually says `liminf (f z - f x) / (z - x) ≤ B' x`
(bound : ∀ x ∈ Ico a b, ∀ r, B' x < r → ∃ᶠ z in 𝓝[>] x, slope f x z < r) :
∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x :=
begin
have Hr : ∀ x ∈ Icc a b, ∀ r > 0, f x ≤ B x + r * (x - a),
{ intros x hx r hr,
apply image_le_of_liminf_slope_right_lt_deriv_boundary' hf bound,
{ rwa [sub_self, mul_zero, add_zero] },
{ exact hB.add (continuous_on_const.mul
(continuous_id.continuous_on.sub continuous_on_const)) },
{ assume x hx,
exact (hB' x hx).add (((has_deriv_within_at_id x (Ici x)).sub_const a).const_mul r) },
{ assume x hx _,
rw [mul_one],
exact (lt_add_iff_pos_right _).2 hr },
exact hx },
assume x hx,
have : continuous_within_at (λ r, B x + r * (x - a)) (Ioi 0) 0,
from continuous_within_at_const.add (continuous_within_at_id.mul continuous_within_at_const),
convert continuous_within_at_const.closure_le _ this (Hr x hx); simp
end
/-- General fencing theorem for continuous functions with an estimate on the derivative.
Let `f` and `B` be continuous functions on `[a, b]` such that
* `f a ≤ B a`;
* `B` has right derivative `B'` at every point of `[a, b)`;
* `f` has right derivative `f'` at every point of `[a, b)`;
* we have `f' x < B' x` whenever `f x = B x`.
Then `f x ≤ B x` everywhere on `[a, b]`. -/
lemma image_le_of_deriv_right_lt_deriv_boundary' {f f' : ℝ → ℝ} {a b : ℝ}
(hf : continuous_on f (Icc a b))
(hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x)
{B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b))
(hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x)
(bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) :
∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x :=
image_le_of_liminf_slope_right_lt_deriv_boundary' hf
(λ x hx r hr, (hf' x hx).liminf_right_slope_le hr) ha hB hB' bound
/-- General fencing theorem for continuous functions with an estimate on the derivative.
Let `f` and `B` be continuous functions on `[a, b]` such that
* `f a ≤ B a`;
* `B` has derivative `B'` everywhere on `ℝ`;
* `f` has right derivative `f'` at every point of `[a, b)`;
* we have `f' x < B' x` whenever `f x = B x`.
Then `f x ≤ B x` everywhere on `[a, b]`. -/
lemma image_le_of_deriv_right_lt_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ}
(hf : continuous_on f (Icc a b))
(hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x)
{B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x)
(bound : ∀ x ∈ Ico a b, f x = B x → f' x < B' x) :
∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x :=
image_le_of_deriv_right_lt_deriv_boundary' hf hf' ha
(λ x hx, (hB x).continuous_at.continuous_within_at)
(λ x hx, (hB x).has_deriv_within_at) bound
/-- General fencing theorem for continuous functions with an estimate on the derivative.
Let `f` and `B` be continuous functions on `[a, b]` such that
* `f a ≤ B a`;
* `B` has derivative `B'` everywhere on `ℝ`;
* `f` has right derivative `f'` at every point of `[a, b)`;
* we have `f' x ≤ B' x` on `[a, b)`.
Then `f x ≤ B x` everywhere on `[a, b]`. -/
lemma image_le_of_deriv_right_le_deriv_boundary {f f' : ℝ → ℝ} {a b : ℝ}
(hf : continuous_on f (Icc a b))
(hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x)
{B B' : ℝ → ℝ} (ha : f a ≤ B a) (hB : continuous_on B (Icc a b))
(hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x)
(bound : ∀ x ∈ Ico a b, f' x ≤ B' x) :
∀ ⦃x⦄, x ∈ Icc a b → f x ≤ B x :=
image_le_of_liminf_slope_right_le_deriv_boundary hf ha hB hB' $
assume x hx r hr, (hf' x hx).liminf_right_slope_le (lt_of_le_of_lt (bound x hx) hr)
/-! ### Vector-valued functions `f : ℝ → E` -/
section
variables {f : ℝ → E} {a b : ℝ}
/-- General fencing theorem for continuous functions with an estimate on the derivative.
Let `f` and `B` be continuous functions on `[a, b]` such that
* `∥f a∥ ≤ B a`;
* `B` has right derivative at every point of `[a, b)`;
* for each `x ∈ [a, b)` the right-side limit inferior of `(∥f z∥ - ∥f x∥) / (z - x)`
is bounded above by a function `f'`;
* we have `f' x < B' x` whenever `∥f x∥ = B x`.
Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. -/
lemma image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary {E : Type*} [normed_group E]
{f : ℝ → E} {f' : ℝ → ℝ} (hf : continuous_on f (Icc a b))
-- `hf'` actually says `liminf (∥f z∥ - ∥f x∥) / (z - x) ≤ f' x`
(hf' : ∀ x ∈ Ico a b, ∀ r, f' x < r →
∃ᶠ z in 𝓝[>] x, slope (norm ∘ f) x z < r)
{B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b))
(hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x)
(bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → f' x < B' x) :
∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x :=
image_le_of_liminf_slope_right_lt_deriv_boundary' (continuous_norm.comp_continuous_on hf) hf'
ha hB hB' bound
/-- General fencing theorem for continuous functions with an estimate on the norm of the derivative.
Let `f` and `B` be continuous functions on `[a, b]` such that
* `∥f a∥ ≤ B a`;
* `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`;
* the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`.
Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions
to make this theorem work for piecewise differentiable functions.
-/
lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary' {f' : ℝ → E}
(hf : continuous_on f (Icc a b))
(hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x)
{B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b))
(hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x)
(bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) :
∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x :=
image_norm_le_of_liminf_right_slope_norm_lt_deriv_boundary hf
(λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le hr) ha hB hB' bound
/-- General fencing theorem for continuous functions with an estimate on the norm of the derivative.
Let `f` and `B` be continuous functions on `[a, b]` such that
* `∥f a∥ ≤ B a`;
* `f` has right derivative `f'` at every point of `[a, b)`;
* `B` has derivative `B'` everywhere on `ℝ`;
* the norm of `f'` is strictly less than `B'` whenever `∥f x∥ = B x`.
Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions
to make this theorem work for piecewise differentiable functions.
-/
lemma image_norm_le_of_norm_deriv_right_lt_deriv_boundary {f' : ℝ → E}
(hf : continuous_on f (Icc a b))
(hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x)
{B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x)
(bound : ∀ x ∈ Ico a b, ∥f x∥ = B x → ∥f' x∥ < B' x) :
∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x :=
image_norm_le_of_norm_deriv_right_lt_deriv_boundary' hf hf' ha
(λ x hx, (hB x).continuous_at.continuous_within_at)
(λ x hx, (hB x).has_deriv_within_at) bound
/-- General fencing theorem for continuous functions with an estimate on the norm of the derivative.
Let `f` and `B` be continuous functions on `[a, b]` such that
* `∥f a∥ ≤ B a`;
* `f` and `B` have right derivatives `f'` and `B'` respectively at every point of `[a, b)`;
* we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`.
Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions
to make this theorem work for piecewise differentiable functions.
-/
lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary' {f' : ℝ → E}
(hf : continuous_on f (Icc a b))
(hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x)
{B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : continuous_on B (Icc a b))
(hB' : ∀ x ∈ Ico a b, has_deriv_within_at B (B' x) (Ici x) x)
(bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) :
∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x :=
image_le_of_liminf_slope_right_le_deriv_boundary (continuous_norm.comp_continuous_on hf) ha hB hB' $
(λ x hx r hr, (hf' x hx).liminf_right_slope_norm_le (lt_of_le_of_lt (bound x hx) hr))
/-- General fencing theorem for continuous functions with an estimate on the norm of the derivative.
Let `f` and `B` be continuous functions on `[a, b]` such that
* `∥f a∥ ≤ B a`;
* `f` has right derivative `f'` at every point of `[a, b)`;
* `B` has derivative `B'` everywhere on `ℝ`;
* we have `∥f' x∥ ≤ B x` everywhere on `[a, b)`.
Then `∥f x∥ ≤ B x` everywhere on `[a, b]`. We use one-sided derivatives in the assumptions
to make this theorem work for piecewise differentiable functions.
-/
lemma image_norm_le_of_norm_deriv_right_le_deriv_boundary {f' : ℝ → E}
(hf : continuous_on f (Icc a b))
(hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x)
{B B' : ℝ → ℝ} (ha : ∥f a∥ ≤ B a) (hB : ∀ x, has_deriv_at B (B' x) x)
(bound : ∀ x ∈ Ico a b, ∥f' x∥ ≤ B' x) :
∀ ⦃x⦄, x ∈ Icc a b → ∥f x∥ ≤ B x :=
image_norm_le_of_norm_deriv_right_le_deriv_boundary' hf hf' ha
(λ x hx, (hB x).continuous_at.continuous_within_at)
(λ x hx, (hB x).has_deriv_within_at) bound
/-- A function on `[a, b]` with the norm of the right derivative bounded by `C`
satisfies `∥f x - f a∥ ≤ C * (x - a)`. -/
theorem norm_image_sub_le_of_norm_deriv_right_le_segment {f' : ℝ → E} {C : ℝ}
(hf : continuous_on f (Icc a b))
(hf' : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x)
(bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) :
∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) :=
begin
let g := λ x, f x - f a,
have hg : continuous_on g (Icc a b), from hf.sub continuous_on_const,
have hg' : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ici x) x,
{ assume x hx,
simpa using (hf' x hx).sub (has_deriv_within_at_const _ _ _) },
let B := λ x, C * (x - a),
have hB : ∀ x, has_deriv_at B C x,
{ assume x,
simpa using (has_deriv_at_const x C).mul ((has_deriv_at_id x).sub (has_deriv_at_const x a)) },
convert image_norm_le_of_norm_deriv_right_le_deriv_boundary hg hg' _ hB bound,
simp only [g, B], rw [sub_self, norm_zero, sub_self, mul_zero]
end
/-- A function on `[a, b]` with the norm of the derivative within `[a, b]`
bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `has_deriv_within_at`
version. -/
theorem norm_image_sub_le_of_norm_deriv_le_segment' {f' : ℝ → E} {C : ℝ}
(hf : ∀ x ∈ Icc a b, has_deriv_within_at f (f' x) (Icc a b) x)
(bound : ∀x ∈ Ico a b, ∥f' x∥ ≤ C) :
∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) :=
begin
refine norm_image_sub_le_of_norm_deriv_right_le_segment
(λ x hx, (hf x hx).continuous_within_at) (λ x hx, _) bound,
exact (hf x $ Ico_subset_Icc_self hx).nhds_within (Icc_mem_nhds_within_Ici hx)
end
/-- A function on `[a, b]` with the norm of the derivative within `[a, b]`
bounded by `C` satisfies `∥f x - f a∥ ≤ C * (x - a)`, `deriv_within`
version. -/
theorem norm_image_sub_le_of_norm_deriv_le_segment {C : ℝ} (hf : differentiable_on ℝ f (Icc a b))
(bound : ∀x ∈ Ico a b, ∥deriv_within f (Icc a b) x∥ ≤ C) :
∀ x ∈ Icc a b, ∥f x - f a∥ ≤ C * (x - a) :=
begin
refine norm_image_sub_le_of_norm_deriv_le_segment' _ bound,
exact λ x hx, (hf x hx).has_deriv_within_at
end
/-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]`
bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `has_deriv_within_at`
version. -/
theorem norm_image_sub_le_of_norm_deriv_le_segment_01' {f' : ℝ → E} {C : ℝ}
(hf : ∀ x ∈ Icc (0:ℝ) 1, has_deriv_within_at f (f' x) (Icc (0:ℝ) 1) x)
(bound : ∀x ∈ Ico (0:ℝ) 1, ∥f' x∥ ≤ C) :
∥f 1 - f 0∥ ≤ C :=
by simpa only [sub_zero, mul_one]
using norm_image_sub_le_of_norm_deriv_le_segment' hf bound 1 (right_mem_Icc.2 zero_le_one)
/-- A function on `[0, 1]` with the norm of the derivative within `[0, 1]`
bounded by `C` satisfies `∥f 1 - f 0∥ ≤ C`, `deriv_within` version. -/
theorem norm_image_sub_le_of_norm_deriv_le_segment_01 {C : ℝ}
(hf : differentiable_on ℝ f (Icc (0:ℝ) 1))
(bound : ∀x ∈ Ico (0:ℝ) 1, ∥deriv_within f (Icc (0:ℝ) 1) x∥ ≤ C) :
∥f 1 - f 0∥ ≤ C :=
by simpa only [sub_zero, mul_one]
using norm_image_sub_le_of_norm_deriv_le_segment hf bound 1 (right_mem_Icc.2 zero_le_one)
theorem constant_of_has_deriv_right_zero (hcont : continuous_on f (Icc a b))
(hderiv : ∀ x ∈ Ico a b, has_deriv_within_at f 0 (Ici x) x) :
∀ x ∈ Icc a b, f x = f a :=
by simpa only [zero_mul, norm_le_zero_iff, sub_eq_zero] using
λ x hx, norm_image_sub_le_of_norm_deriv_right_le_segment
hcont hderiv (λ y hy, by rw norm_le_zero_iff) x hx
theorem constant_of_deriv_within_zero (hdiff : differentiable_on ℝ f (Icc a b))
(hderiv : ∀ x ∈ Ico a b, deriv_within f (Icc a b) x = 0) :
∀ x ∈ Icc a b, f x = f a :=
begin
have H : ∀ x ∈ Ico a b, ∥deriv_within f (Icc a b) x∥ ≤ 0 :=
by simpa only [norm_le_zero_iff] using λ x hx, hderiv x hx,
simpa only [zero_mul, norm_le_zero_iff, sub_eq_zero] using
λ x hx, norm_image_sub_le_of_norm_deriv_le_segment hdiff H x hx,
end
variables {f' g : ℝ → E}
/-- If two continuous functions on `[a, b]` have the same right derivative and are equal at `a`,
then they are equal everywhere on `[a, b]`. -/
theorem eq_of_has_deriv_right_eq
(derivf : ∀ x ∈ Ico a b, has_deriv_within_at f (f' x) (Ici x) x)
(derivg : ∀ x ∈ Ico a b, has_deriv_within_at g (f' x) (Ici x) x)
(fcont : continuous_on f (Icc a b)) (gcont : continuous_on g (Icc a b))
(hi : f a = g a) :
∀ y ∈ Icc a b, f y = g y :=
begin
simp only [← @sub_eq_zero _ _ (f _)] at hi ⊢,
exact hi ▸ constant_of_has_deriv_right_zero (fcont.sub gcont)
(λ y hy, by simpa only [sub_self] using (derivf y hy).sub (derivg y hy)),
end
/-- If two differentiable functions on `[a, b]` have the same derivative within `[a, b]` everywhere
on `[a, b)` and are equal at `a`, then they are equal everywhere on `[a, b]`. -/
theorem eq_of_deriv_within_eq (fdiff : differentiable_on ℝ f (Icc a b))
(gdiff : differentiable_on ℝ g (Icc a b))
(hderiv : eq_on (deriv_within f (Icc a b)) (deriv_within g (Icc a b)) (Ico a b))
(hi : f a = g a) :
∀ y ∈ Icc a b, f y = g y :=
begin
have A : ∀ y ∈ Ico a b, has_deriv_within_at f (deriv_within f (Icc a b) y) (Ici y) y :=
λ y hy, (fdiff y (mem_Icc_of_Ico hy)).has_deriv_within_at.nhds_within
(Icc_mem_nhds_within_Ici hy),
have B : ∀ y ∈ Ico a b, has_deriv_within_at g (deriv_within g (Icc a b) y) (Ici y) y :=
λ y hy, (gdiff y (mem_Icc_of_Ico hy)).has_deriv_within_at.nhds_within
(Icc_mem_nhds_within_Ici hy),
exact eq_of_has_deriv_right_eq A (λ y hy, (hderiv hy).symm ▸ B y hy) fdiff.continuous_on
gdiff.continuous_on hi
end
end
/-!
### Vector-valued functions `f : E → G`
Theorems in this section work both for real and complex differentiable functions. We use assumptions
`[is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 G]` to achieve this result. For the domain `E` we
also assume `[normed_space ℝ E]` to have a notion of a `convex` set. -/
section
variables {𝕜 G : Type*} [is_R_or_C 𝕜] [normed_space 𝕜 E] [normed_group G] [normed_space 𝕜 G]
namespace convex
variables {f : E → G} {C : ℝ} {s : set E} {x y : E} {f' : E → E →L[𝕜] G} {φ : E →L[𝕜] G}
/-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C`, then
the function is `C`-Lipschitz. Version with `has_fderiv_within`. -/
theorem norm_image_sub_le_of_norm_has_fderiv_within_le
(hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥ ≤ C)
(hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ :=
begin
letI : normed_space ℝ G := restrict_scalars.normed_space ℝ 𝕜 G,
/- By composition with `t ↦ x + t • (y-x)`, we reduce to a statement for functions defined
on `[0,1]`, for which it is proved in `norm_image_sub_le_of_norm_deriv_le_segment`.
We just have to check the differentiability of the composition and bounds on its derivative,
which is straightforward but tedious for lack of automation. -/
have C0 : 0 ≤ C := le_trans (norm_nonneg _) (bound x xs),
set g : ℝ → E := λ t, x + t • (y - x),
have Dg : ∀ t, has_deriv_at g (y-x) t,
{ assume t,
simpa only [one_smul] using ((has_deriv_at_id t).smul_const (y - x)).const_add x },
have segm : Icc 0 1 ⊆ g ⁻¹' s,
{ rw [← image_subset_iff, ← segment_eq_image'],
apply hs.segment_subset xs ys },
have : f x = f (g 0), by { simp only [g], rw [zero_smul, add_zero] },
rw this,
have : f y = f (g 1), by { simp only [g], rw [one_smul, add_sub_cancel'_right] },
rw this,
have D2: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g) (f' (g t) (y - x)) (Icc 0 1) t,
{ intros t ht,
have : has_fderiv_within_at f ((f' (g t)).restrict_scalars ℝ) s (g t),
from hf (g t) (segm ht),
exact this.comp_has_deriv_within_at _ (Dg t).has_deriv_within_at segm },
apply norm_image_sub_le_of_norm_deriv_le_segment_01' D2,
refine λ t ht, le_of_op_norm_le _ _ _,
exact bound (g t) (segm $ Ico_subset_Icc_self ht)
end
/-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on
`s`, then the function is `C`-Lipschitz on `s`. Version with `has_fderiv_within` and
`lipschitz_on_with`. -/
theorem lipschitz_on_with_of_nnnorm_has_fderiv_within_le {C : ℝ≥0}
(hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥₊ ≤ C)
(hs : convex ℝ s) : lipschitz_on_with C f s :=
begin
rw lipschitz_on_with_iff_norm_sub_le,
intros x x_in y y_in,
exact hs.norm_image_sub_le_of_norm_has_fderiv_within_le hf bound y_in x_in
end
/-- Let `s` be a convex set in a real normed vector space `E`, let `f : E → G` be a function
differentiable within `s` in a neighborhood of `x : E` with derivative `f'`. Suppose that `f'` is
continuous within `s` at `x`. Then for any number `K : ℝ≥0` larger than `∥f' x∥₊`, `f` is
`K`-Lipschitz on some neighborhood of `x` within `s`. See also
`convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at` for a version that claims
existence of `K` instead of an explicit estimate. -/
lemma exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt
(hs : convex ℝ s) {f : E → G} (hder : ∀ᶠ y in 𝓝[s] x, has_fderiv_within_at f (f' y) s y)
(hcont : continuous_within_at f' s x) (K : ℝ≥0) (hK : ∥f' x∥₊ < K) :
∃ t ∈ 𝓝[s] x, lipschitz_on_with K f t :=
begin
obtain ⟨ε, ε0, hε⟩ :
∃ ε > 0, ball x ε ∩ s ⊆ {y | has_fderiv_within_at f (f' y) s y ∧ ∥f' y∥₊ < K},
from mem_nhds_within_iff.1 (hder.and $ hcont.nnnorm.eventually (gt_mem_nhds hK)),
rw inter_comm at hε,
refine ⟨s ∩ ball x ε, inter_mem_nhds_within _ (ball_mem_nhds _ ε0), _⟩,
exact (hs.inter (convex_ball _ _)).lipschitz_on_with_of_nnnorm_has_fderiv_within_le
(λ y hy, (hε hy).1.mono (inter_subset_left _ _)) (λ y hy, (hε hy).2.le)
end
/-- Let `s` be a convex set in a real normed vector space `E`, let `f : E → G` be a function
differentiable within `s` in a neighborhood of `x : E` with derivative `f'`. Suppose that `f'` is
continuous within `s` at `x`. Then for any number `K : ℝ≥0` larger than `∥f' x∥₊`, `f` is Lipschitz
on some neighborhood of `x` within `s`. See also
`convex.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt` for a version
with an explicit estimate on the Lipschitz constant. -/
lemma exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at
(hs : convex ℝ s) {f : E → G} (hder : ∀ᶠ y in 𝓝[s] x, has_fderiv_within_at f (f' y) s y)
(hcont : continuous_within_at f' s x) :
∃ K (t ∈ 𝓝[s] x), lipschitz_on_with K f t :=
(exists_gt _).imp $
hs.exists_nhds_within_lipschitz_on_with_of_has_fderiv_within_at_of_nnnorm_lt hder hcont
/-- The mean value theorem on a convex set: if the derivative of a function within this set is
bounded by `C`, then the function is `C`-Lipschitz. Version with `fderiv_within`. -/
theorem norm_image_sub_le_of_norm_fderiv_within_le
(hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥fderiv_within 𝕜 f s x∥ ≤ C)
(hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ :=
hs.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at)
bound xs ys
/-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on
`s`, then the function is `C`-Lipschitz on `s`. Version with `fderiv_within` and
`lipschitz_on_with`. -/
theorem lipschitz_on_with_of_nnnorm_fderiv_within_le {C : ℝ≥0}
(hf : differentiable_on 𝕜 f s) (bound : ∀ x ∈ s, ∥fderiv_within 𝕜 f s x∥₊ ≤ C)
(hs : convex ℝ s) : lipschitz_on_with C f s:=
hs.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at) bound
/-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C`,
then the function is `C`-Lipschitz. Version with `fderiv`. -/
theorem norm_image_sub_le_of_norm_fderiv_le
(hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x∥ ≤ C)
(hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ :=
hs.norm_image_sub_le_of_norm_has_fderiv_within_le
(λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound xs ys
/-- The mean value theorem on a convex set: if the derivative of a function is bounded by `C` on
`s`, then the function is `C`-Lipschitz on `s`. Version with `fderiv` and `lipschitz_on_with`. -/
theorem lipschitz_on_with_of_nnnorm_fderiv_le {C : ℝ≥0}
(hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x∥₊ ≤ C)
(hs : convex ℝ s) : lipschitz_on_with C f s :=
hs.lipschitz_on_with_of_nnnorm_has_fderiv_within_le
(λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound
/-- Variant of the mean value inequality on a convex set, using a bound on the difference between
the derivative and a fixed linear map, rather than a bound on the derivative itself. Version with
`has_fderiv_within`. -/
theorem norm_image_sub_le_of_norm_has_fderiv_within_le'
(hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x - φ∥ ≤ C)
(hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ :=
begin
/- We subtract `φ` to define a new function `g` for which `g' = 0`, for which the previous theorem
applies, `convex.norm_image_sub_le_of_norm_has_fderiv_within_le`. Then, we just need to glue
together the pieces, expressing back `f` in terms of `g`. -/
let g := λy, f y - φ y,
have hg : ∀ x ∈ s, has_fderiv_within_at g (f' x - φ) s x :=
λ x xs, (hf x xs).sub φ.has_fderiv_within_at,
calc ∥f y - f x - φ (y - x)∥ = ∥f y - f x - (φ y - φ x)∥ : by simp
... = ∥(f y - φ y) - (f x - φ x)∥ : by abel
... = ∥g y - g x∥ : by simp
... ≤ C * ∥y - x∥ : convex.norm_image_sub_le_of_norm_has_fderiv_within_le hg bound hs xs ys,
end
/-- Variant of the mean value inequality on a convex set. Version with `fderiv_within`. -/
theorem norm_image_sub_le_of_norm_fderiv_within_le'
(hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥fderiv_within 𝕜 f s x - φ∥ ≤ C)
(hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ :=
hs.norm_image_sub_le_of_norm_has_fderiv_within_le' (λ x hx, (hf x hx).has_fderiv_within_at)
bound xs ys
/-- Variant of the mean value inequality on a convex set. Version with `fderiv`. -/
theorem norm_image_sub_le_of_norm_fderiv_le'
(hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥fderiv 𝕜 f x - φ∥ ≤ C)
(hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x - φ (y - x)∥ ≤ C * ∥y - x∥ :=
hs.norm_image_sub_le_of_norm_has_fderiv_within_le'
(λ x hx, (hf x hx).has_fderiv_at.has_fderiv_within_at) bound xs ys
/-- If a function has zero Fréchet derivative at every point of a convex set,
then it is a constant on this set. -/
theorem is_const_of_fderiv_within_eq_zero (hs : convex ℝ s) (hf : differentiable_on 𝕜 f s)
(hf' : ∀ x ∈ s, fderiv_within 𝕜 f s x = 0) (hx : x ∈ s) (hy : y ∈ s) :
f x = f y :=
have bound : ∀ x ∈ s, ∥fderiv_within 𝕜 f s x∥ ≤ 0,
from λ x hx, by simp only [hf' x hx, norm_zero],
by simpa only [(dist_eq_norm _ _).symm, zero_mul, dist_le_zero, eq_comm]
using hs.norm_image_sub_le_of_norm_fderiv_within_le hf bound hx hy
theorem _root_.is_const_of_fderiv_eq_zero (hf : differentiable 𝕜 f) (hf' : ∀ x, fderiv 𝕜 f x = 0)
(x y : E) :
f x = f y :=
convex_univ.is_const_of_fderiv_within_eq_zero hf.differentiable_on
(λ x _, by rw fderiv_within_univ; exact hf' x) trivial trivial
end convex
namespace convex
variables {f f' : 𝕜 → G} {s : set 𝕜} {x y : 𝕜}
/-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is
bounded by `C`, then the function is `C`-Lipschitz. Version with `has_deriv_within`. -/
theorem norm_image_sub_le_of_norm_has_deriv_within_le {C : ℝ}
(hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥ ≤ C)
(hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ :=
convex.norm_image_sub_le_of_norm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at)
(λ x hx, le_trans (by simp) (bound x hx)) hs xs ys
/-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is
bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`.
Version with `has_deriv_within` and `lipschitz_on_with`. -/
theorem lipschitz_on_with_of_nnnorm_has_deriv_within_le {C : ℝ≥0} (hs : convex ℝ s)
(hf : ∀ x ∈ s, has_deriv_within_at f (f' x) s x) (bound : ∀x∈s, ∥f' x∥₊ ≤ C) :
lipschitz_on_with C f s :=
convex.lipschitz_on_with_of_nnnorm_has_fderiv_within_le (λ x hx, (hf x hx).has_fderiv_within_at)
(λ x hx, le_trans (by simp) (bound x hx)) hs
/-- The mean value theorem on a convex set in dimension 1: if the derivative of a function within
this set is bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv_within` -/
theorem norm_image_sub_le_of_norm_deriv_within_le {C : ℝ}
(hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥deriv_within f s x∥ ≤ C)
(hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ :=
hs.norm_image_sub_le_of_norm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_within_at)
bound xs ys
/-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is
bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`.
Version with `deriv_within` and `lipschitz_on_with`. -/
theorem lipschitz_on_with_of_nnnorm_deriv_within_le {C : ℝ≥0} (hs : convex ℝ s)
(hf : differentiable_on 𝕜 f s) (bound : ∀x∈s, ∥deriv_within f s x∥₊ ≤ C) :
lipschitz_on_with C f s :=
hs.lipschitz_on_with_of_nnnorm_has_deriv_within_le (λ x hx, (hf x hx).has_deriv_within_at) bound
/-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is
bounded by `C`, then the function is `C`-Lipschitz. Version with `deriv`. -/
theorem norm_image_sub_le_of_norm_deriv_le {C : ℝ}
(hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥deriv f x∥ ≤ C)
(hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) : ∥f y - f x∥ ≤ C * ∥y - x∥ :=
hs.norm_image_sub_le_of_norm_has_deriv_within_le
(λ x hx, (hf x hx).has_deriv_at.has_deriv_within_at) bound xs ys
/-- The mean value theorem on a convex set in dimension 1: if the derivative of a function is
bounded by `C` on `s`, then the function is `C`-Lipschitz on `s`.
Version with `deriv` and `lipschitz_on_with`. -/
theorem lipschitz_on_with_of_nnnorm_deriv_le {C : ℝ≥0}
(hf : ∀ x ∈ s, differentiable_at 𝕜 f x) (bound : ∀x∈s, ∥deriv f x∥₊ ≤ C)
(hs : convex ℝ s) : lipschitz_on_with C f s :=
hs.lipschitz_on_with_of_nnnorm_has_deriv_within_le
(λ x hx, (hf x hx).has_deriv_at.has_deriv_within_at) bound
/-- The mean value theorem set in dimension 1: if the derivative of a function is bounded by `C`,
then the function is `C`-Lipschitz. Version with `deriv` and `lipschitz_with`. -/
theorem _root_.lipschitz_with_of_nnnorm_deriv_le {C : ℝ≥0} (hf : differentiable 𝕜 f)
(bound : ∀ x, ∥deriv f x∥₊ ≤ C) : lipschitz_with C f :=
lipschitz_on_univ.1 $ convex_univ.lipschitz_on_with_of_nnnorm_deriv_le (λ x hx, hf x)
(λ x hx, bound x)
/-- If `f : 𝕜 → G`, `𝕜 = R` or `𝕜 = ℂ`, is differentiable everywhere and its derivative equal zero,
then it is a constant function. -/
theorem _root_.is_const_of_deriv_eq_zero (hf : differentiable 𝕜 f) (hf' : ∀ x, deriv f x = 0)
(x y : 𝕜) :
f x = f y :=
is_const_of_fderiv_eq_zero hf (λ z, by { ext, simp [← deriv_fderiv, hf'] }) _ _
end convex
end
/-! ### Functions `[a, b] → ℝ`. -/
section interval
-- Declare all variables here to make sure they come in a correct order
variables (f f' : ℝ → ℝ) {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b))
(hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hfd : differentiable_on ℝ f (Ioo a b))
(g g' : ℝ → ℝ) (hgc : continuous_on g (Icc a b)) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x)
(hgd : differentiable_on ℝ g (Ioo a b))
include hab hfc hff' hgc hgg'
/-- Cauchy's **Mean Value Theorem**, `has_deriv_at` version. -/
lemma exists_ratio_has_deriv_at_eq_ratio_slope :
∃ c ∈ Ioo a b, (g b - g a) * f' c = (f b - f a) * g' c :=
begin
let h := λ x, (g b - g a) * f x - (f b - f a) * g x,
have hI : h a = h b,
{ simp only [h], ring },
let h' := λ x, (g b - g a) * f' x - (f b - f a) * g' x,
have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x,
from λ x hx, ((hff' x hx).const_mul (g b - g a)).sub ((hgg' x hx).const_mul (f b - f a)),
have hhc : continuous_on h (Icc a b),
from (continuous_on_const.mul hfc).sub (continuous_on_const.mul hgc),
rcases exists_has_deriv_at_eq_zero h h' hab hhc hI hhh' with ⟨c, cmem, hc⟩,
exact ⟨c, cmem, sub_eq_zero.1 hc⟩
end
omit hfc hgc
/-- Cauchy's **Mean Value Theorem**, extended `has_deriv_at` version. -/
lemma exists_ratio_has_deriv_at_eq_ratio_slope' {lfa lga lfb lgb : ℝ}
(hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) (hgg' : ∀ x ∈ Ioo a b, has_deriv_at g (g' x) x)
(hfa : tendsto f (𝓝[>] a) (𝓝 lfa)) (hga : tendsto g (𝓝[>] a) (𝓝 lga))
(hfb : tendsto f (𝓝[<] b) (𝓝 lfb)) (hgb : tendsto g (𝓝[<] b) (𝓝 lgb)) :
∃ c ∈ Ioo a b, (lgb - lga) * (f' c) = (lfb - lfa) * (g' c) :=
begin
let h := λ x, (lgb - lga) * f x - (lfb - lfa) * g x,
have hha : tendsto h (𝓝[>] a) (𝓝 $ lgb * lfa - lfb * lga),
{ have : tendsto h (𝓝[>] a)(𝓝 $ (lgb - lga) * lfa - (lfb - lfa) * lga) :=
(tendsto_const_nhds.mul hfa).sub (tendsto_const_nhds.mul hga),
convert this using 2,
ring },
have hhb : tendsto h (𝓝[<] b) (𝓝 $ lgb * lfa - lfb * lga),
{ have : tendsto h (𝓝[<] b)(𝓝 $ (lgb - lga) * lfb - (lfb - lfa) * lgb) :=
(tendsto_const_nhds.mul hfb).sub (tendsto_const_nhds.mul hgb),
convert this using 2,
ring },
let h' := λ x, (lgb - lga) * f' x - (lfb - lfa) * g' x,
have hhh' : ∀ x ∈ Ioo a b, has_deriv_at h (h' x) x,
{ intros x hx,
exact ((hff' x hx).const_mul _ ).sub (((hgg' x hx)).const_mul _) },
rcases exists_has_deriv_at_eq_zero' hab hha hhb hhh' with ⟨c, cmem, hc⟩,
exact ⟨c, cmem, sub_eq_zero.1 hc⟩
end
include hfc
omit hgg'
/-- Lagrange's Mean Value Theorem, `has_deriv_at` version -/
lemma exists_has_deriv_at_eq_slope : ∃ c ∈ Ioo a b, f' c = (f b - f a) / (b - a) :=
begin
rcases exists_ratio_has_deriv_at_eq_ratio_slope f f' hab hfc hff'
id 1 continuous_id.continuous_on (λ x hx, has_deriv_at_id x) with ⟨c, cmem, hc⟩,
use [c, cmem],
simp only [_root_.id, pi.one_apply, mul_one] at hc,
rw [← hc, mul_div_cancel_left],
exact ne_of_gt (sub_pos.2 hab)
end
omit hff'
/-- Cauchy's Mean Value Theorem, `deriv` version. -/
lemma exists_ratio_deriv_eq_ratio_slope :
∃ c ∈ Ioo a b, (g b - g a) * (deriv f c) = (f b - f a) * (deriv g c) :=
exists_ratio_has_deriv_at_eq_ratio_slope f (deriv f) hab hfc
(λ x hx, ((hfd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at)
g (deriv g) hgc $
λ x hx, ((hgd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at
omit hfc
/-- Cauchy's Mean Value Theorem, extended `deriv` version. -/
lemma exists_ratio_deriv_eq_ratio_slope' {lfa lga lfb lgb : ℝ}
(hdf : differentiable_on ℝ f $ Ioo a b) (hdg : differentiable_on ℝ g $ Ioo a b)
(hfa : tendsto f (𝓝[>] a) (𝓝 lfa)) (hga : tendsto g (𝓝[>] a) (𝓝 lga))
(hfb : tendsto f (𝓝[<] b) (𝓝 lfb)) (hgb : tendsto g (𝓝[<] b) (𝓝 lgb)) :
∃ c ∈ Ioo a b, (lgb - lga) * (deriv f c) = (lfb - lfa) * (deriv g c) :=
exists_ratio_has_deriv_at_eq_ratio_slope' _ _ hab _ _
(λ x hx, ((hdf x hx).differentiable_at $ Ioo_mem_nhds hx.1 hx.2).has_deriv_at)
(λ x hx, ((hdg x hx).differentiable_at $ Ioo_mem_nhds hx.1 hx.2).has_deriv_at)
hfa hga hfb hgb
/-- Lagrange's **Mean Value Theorem**, `deriv` version. -/
lemma exists_deriv_eq_slope : ∃ c ∈ Ioo a b, deriv f c = (f b - f a) / (b - a) :=
exists_has_deriv_at_eq_slope f (deriv f) hab hfc
(λ x hx, ((hfd x hx).differentiable_at $ is_open.mem_nhds is_open_Ioo hx).has_deriv_at)
end interval
/-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D`
of the real line. If `f` is differentiable on the interior of `D` and `C < f'`, then
`f` grows faster than `C * x` on `D`, i.e., `C * (y - x) < f y - f x` whenever `x, y ∈ D`,
`x < y`. -/
theorem convex.mul_sub_lt_image_sub_of_lt_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
{C} (hf'_gt : ∀ x ∈ interior D, C < deriv f x) :
∀ x y ∈ D, x < y → C * (y - x) < f y - f x :=
begin
assume x hx y hy hxy,
have hxyD : Icc x y ⊆ D, from hD.ord_connected.out hx hy,
have hxyD' : Ioo x y ⊆ interior D,
from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩,
obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x),
from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'),
have : C < (f y - f x) / (y - x), by { rw [← ha], exact hf'_gt _ (hxyD' a_mem) },
exact (lt_div_iff (sub_pos.2 hxy)).1 this
end
/-- Let `f : ℝ → ℝ` be a differentiable function. If `C < f'`, then `f` grows faster than
`C * x`, i.e., `C * (y - x) < f y - f x` whenever `x < y`. -/
theorem mul_sub_lt_image_sub_of_lt_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f)
{C} (hf'_gt : ∀ x, C < deriv f x) ⦃x y⦄ (hxy : x < y) :
C * (y - x) < f y - f x :=
convex_univ.mul_sub_lt_image_sub_of_lt_deriv hf.continuous.continuous_on hf.differentiable_on
(λ x _, hf'_gt x) x trivial y trivial hxy
/-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D`
of the real line. If `f` is differentiable on the interior of `D` and `C ≤ f'`, then
`f` grows at least as fast as `C * x` on `D`, i.e., `C * (y - x) ≤ f y - f x` whenever `x, y ∈ D`,
`x ≤ y`. -/
theorem convex.mul_sub_le_image_sub_of_le_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
{C} (hf'_ge : ∀ x ∈ interior D, C ≤ deriv f x) :
∀ x y ∈ D, x ≤ y → C * (y - x) ≤ f y - f x :=
begin
assume x hx y hy hxy,
cases eq_or_lt_of_le hxy with hxy' hxy', by rw [hxy', sub_self, sub_self, mul_zero],
have hxyD : Icc x y ⊆ D, from hD.ord_connected.out hx hy,
have hxyD' : Ioo x y ⊆ interior D,
from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩,
obtain ⟨a, a_mem, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x),
from exists_deriv_eq_slope f hxy' (hf.mono hxyD) (hf'.mono hxyD'),
have : C ≤ (f y - f x) / (y - x), by { rw [← ha], exact hf'_ge _ (hxyD' a_mem) },
exact (le_div_iff (sub_pos.2 hxy')).1 this
end
/-- Let `f : ℝ → ℝ` be a differentiable function. If `C ≤ f'`, then `f` grows at least as fast
as `C * x`, i.e., `C * (y - x) ≤ f y - f x` whenever `x ≤ y`. -/
theorem mul_sub_le_image_sub_of_le_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f)
{C} (hf'_ge : ∀ x, C ≤ deriv f x) ⦃x y⦄ (hxy : x ≤ y) :
C * (y - x) ≤ f y - f x :=
convex_univ.mul_sub_le_image_sub_of_le_deriv hf.continuous.continuous_on hf.differentiable_on
(λ x _, hf'_ge x) x trivial y trivial hxy
/-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D`
of the real line. If `f` is differentiable on the interior of `D` and `f' < C`, then
`f` grows slower than `C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x, y ∈ D`,
`x < y`. -/
theorem convex.image_sub_lt_mul_sub_of_deriv_lt {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
{C} (lt_hf' : ∀ x ∈ interior D, deriv f x < C) :
∀ x y ∈ D, x < y → f y - f x < C * (y - x) :=
begin
assume x hx y hy hxy,
have hf'_gt : ∀ x ∈ interior D, -C < deriv (λ y, -f y) x,
{ assume x hx,
rw [deriv.neg, neg_lt_neg_iff],
exact lt_hf' x hx },
simpa [-neg_lt_neg_iff]
using neg_lt_neg (hD.mul_sub_lt_image_sub_of_lt_deriv hf.neg hf'.neg hf'_gt x hx y hy hxy)
end
/-- Let `f : ℝ → ℝ` be a differentiable function. If `f' < C`, then `f` grows slower than
`C * x` on `D`, i.e., `f y - f x < C * (y - x)` whenever `x < y`. -/
theorem image_sub_lt_mul_sub_of_deriv_lt {f : ℝ → ℝ} (hf : differentiable ℝ f)
{C} (lt_hf' : ∀ x, deriv f x < C) ⦃x y⦄ (hxy : x < y) :
f y - f x < C * (y - x) :=
convex_univ.image_sub_lt_mul_sub_of_deriv_lt hf.continuous.continuous_on hf.differentiable_on
(λ x _, lt_hf' x) x trivial y trivial hxy
/-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D`
of the real line. If `f` is differentiable on the interior of `D` and `f' ≤ C`, then
`f` grows at most as fast as `C * x` on `D`, i.e., `f y - f x ≤ C * (y - x)` whenever `x, y ∈ D`,
`x ≤ y`. -/
theorem convex.image_sub_le_mul_sub_of_deriv_le {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
{C} (le_hf' : ∀ x ∈ interior D, deriv f x ≤ C) :
∀ x y ∈ D, x ≤ y → f y - f x ≤ C * (y - x) :=
begin
assume x hx y hy hxy,
have hf'_ge : ∀ x ∈ interior D, -C ≤ deriv (λ y, -f y) x,
{ assume x hx,
rw [deriv.neg, neg_le_neg_iff],
exact le_hf' x hx },
simpa [-neg_le_neg_iff]
using neg_le_neg (hD.mul_sub_le_image_sub_of_le_deriv hf.neg hf'.neg hf'_ge x hx y hy hxy)
end
/-- Let `f : ℝ → ℝ` be a differentiable function. If `f' ≤ C`, then `f` grows at most as fast
as `C * x`, i.e., `f y - f x ≤ C * (y - x)` whenever `x ≤ y`. -/
theorem image_sub_le_mul_sub_of_deriv_le {f : ℝ → ℝ} (hf : differentiable ℝ f)
{C} (le_hf' : ∀ x, deriv f x ≤ C) ⦃x y⦄ (hxy : x ≤ y) :
f y - f x ≤ C * (y - x) :=
convex_univ.image_sub_le_mul_sub_of_deriv_le hf.continuous.continuous_on hf.differentiable_on
(λ x _, le_hf' x) x trivial y trivial hxy
/-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D`
of the real line. If `f` is differentiable on the interior of `D` and `f'` is positive, then
`f` is a strictly monotone function on `D`.
Note that we don't require differentiability explicitly as it already implied by the derivative
being strictly positive. -/
theorem convex.strict_mono_on_of_deriv_pos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : ∀ x ∈ interior D, 0 < deriv f x) :
strict_mono_on f D :=
begin
rintro x hx y hy,
simpa only [zero_mul, sub_pos] using hD.mul_sub_lt_image_sub_of_lt_deriv hf _ hf' x hx y hy,
exact λ z hz, (differentiable_at_of_deriv_ne_zero (hf' z hz).ne').differentiable_within_at,
end
/-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is positive, then
`f` is a strictly monotone function.
Note that we don't require differentiability explicitly as it already implied by the derivative
being strictly positive. -/
theorem strict_mono_of_deriv_pos {f : ℝ → ℝ} (hf' : ∀ x, 0 < deriv f x) : strict_mono f :=
strict_mono_on_univ.1 $ convex_univ.strict_mono_on_of_deriv_pos
(λ z _, (differentiable_at_of_deriv_ne_zero (hf' z).ne').differentiable_within_at
.continuous_within_at)
(λ x _, hf' x)
/-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D`
of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonnegative, then
`f` is a monotone function on `D`. -/
theorem convex.monotone_on_of_deriv_nonneg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
(hf'_nonneg : ∀ x ∈ interior D, 0 ≤ deriv f x) :
monotone_on f D :=
λ x hx y hy hxy, by simpa only [zero_mul, sub_nonneg]
using hD.mul_sub_le_image_sub_of_le_deriv hf hf' hf'_nonneg x hx y hy hxy
/-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonnegative, then
`f` is a monotone function. -/
theorem monotone_of_deriv_nonneg {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, 0 ≤ deriv f x) :
monotone f :=
monotone_on_univ.1 $ convex_univ.monotone_on_of_deriv_nonneg hf.continuous.continuous_on
hf.differentiable_on (λ x _, hf' x)
/-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D`
of the real line. If `f` is differentiable on the interior of `D` and `f'` is negative, then
`f` is a strictly antitone function on `D`. -/
theorem convex.strict_anti_on_of_deriv_neg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : ∀ x ∈ interior D, deriv f x < 0) :
strict_anti_on f D :=
λ x hx y, by simpa only [zero_mul, sub_lt_zero]
using hD.image_sub_lt_mul_sub_of_deriv_lt hf
(λ z hz, (differentiable_at_of_deriv_ne_zero (hf' z hz).ne).differentiable_within_at) hf' x hx y
/-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is negative, then
`f` is a strictly antitone function.
Note that we don't require differentiability explicitly as it already implied by the derivative
being strictly negative. -/
theorem strict_anti_of_deriv_neg {f : ℝ → ℝ} (hf' : ∀ x, deriv f x < 0) :
strict_anti f :=
strict_anti_on_univ.1 $ convex_univ.strict_anti_on_of_deriv_neg
(λ z _, (differentiable_at_of_deriv_ne_zero (hf' z).ne).differentiable_within_at
.continuous_within_at)
(λ x _, hf' x)
/-- Let `f` be a function continuous on a convex (or, equivalently, connected) subset `D`
of the real line. If `f` is differentiable on the interior of `D` and `f'` is nonpositive, then
`f` is an antitone function on `D`. -/
theorem convex.antitone_on_of_deriv_nonpos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
(hf'_nonpos : ∀ x ∈ interior D, deriv f x ≤ 0) :
antitone_on f D :=
λ x hx y hy hxy, by simpa only [zero_mul, sub_nonpos]
using hD.image_sub_le_mul_sub_of_deriv_le hf hf' hf'_nonpos x hx y hy hxy
/-- Let `f : ℝ → ℝ` be a differentiable function. If `f'` is nonpositive, then
`f` is an antitone function. -/
theorem antitone_of_deriv_nonpos {f : ℝ → ℝ} (hf : differentiable ℝ f) (hf' : ∀ x, deriv f x ≤ 0) :
antitone f :=
antitone_on_univ.1 $ convex_univ.antitone_on_of_deriv_nonpos hf.continuous.continuous_on
hf.differentiable_on (λ x _, hf' x)
/-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior,
and `f'` is monotone on the interior, then `f` is convex on `D`. -/
theorem monotone_on.convex_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
(hf'_mono : monotone_on (deriv f) (interior D)) :
convex_on ℝ D f :=
convex_on_of_slope_mono_adjacent hD
begin
intros x y z hx hz hxy hyz,
-- First we prove some trivial inclusions
have hxzD : Icc x z ⊆ D, from hD.ord_connected.out hx hz,
have hxyD : Icc x y ⊆ D, from subset.trans (Icc_subset_Icc_right $ le_of_lt hyz) hxzD,
have hxyD' : Ioo x y ⊆ interior D,
from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩,
have hyzD : Icc y z ⊆ D, from subset.trans (Icc_subset_Icc_left $ le_of_lt hxy) hxzD,
have hyzD' : Ioo y z ⊆ interior D,
from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hyzD⟩,
-- Then we apply MVT to both `[x, y]` and `[y, z]`
obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x),
from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'),
obtain ⟨b, ⟨hyb, hbz⟩, hb⟩ : ∃ b ∈ Ioo y z, deriv f b = (f z - f y) / (z - y),
from exists_deriv_eq_slope f hyz (hf.mono hyzD) (hf'.mono hyzD'),
rw [← ha, ← hb],
exact hf'_mono (hxyD' ⟨hxa, hay⟩) (hyzD' ⟨hyb, hbz⟩) (hay.trans hyb).le
end
/-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior,
and `f'` is antitone on the interior, then `f` is concave on `D`. -/
theorem antitone_on.concave_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
(h_anti : antitone_on (deriv f) (interior D)) :
concave_on ℝ D f :=
begin
have : monotone_on (deriv (-f)) (interior D),
{ intros x hx y hy hxy,
convert neg_le_neg (h_anti hx hy hxy);
convert deriv.neg },
exact neg_convex_on_iff.mp (this.convex_on_of_deriv hD hf.neg hf'.neg),
end
/-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior,
and `f'` is strictly monotone on the interior, then `f` is strictly convex on `D`. -/
lemma strict_mono_on.strict_convex_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
(hf'_mono : strict_mono_on (deriv f) (interior D)) :
strict_convex_on ℝ D f :=
strict_convex_on_of_slope_strict_mono_adjacent hD
begin
intros x y z hx hz hxy hyz,
-- First we prove some trivial inclusions
have hxzD : Icc x z ⊆ D, from hD.ord_connected.out hx hz,
have hxyD : Icc x y ⊆ D, from subset.trans (Icc_subset_Icc_right $ le_of_lt hyz) hxzD,
have hxyD' : Ioo x y ⊆ interior D,
from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hxyD⟩,
have hyzD : Icc y z ⊆ D, from subset.trans (Icc_subset_Icc_left $ le_of_lt hxy) hxzD,
have hyzD' : Ioo y z ⊆ interior D,
from subset_sUnion_of_mem ⟨is_open_Ioo, subset.trans Ioo_subset_Icc_self hyzD⟩,
-- Then we apply MVT to both `[x, y]` and `[y, z]`
obtain ⟨a, ⟨hxa, hay⟩, ha⟩ : ∃ a ∈ Ioo x y, deriv f a = (f y - f x) / (y - x),
from exists_deriv_eq_slope f hxy (hf.mono hxyD) (hf'.mono hxyD'),
obtain ⟨b, ⟨hyb, hbz⟩, hb⟩ : ∃ b ∈ Ioo y z, deriv f b = (f z - f y) / (z - y),
from exists_deriv_eq_slope f hyz (hf.mono hyzD) (hf'.mono hyzD'),
rw [← ha, ← hb],
exact hf'_mono (hxyD' ⟨hxa, hay⟩) (hyzD' ⟨hyb, hbz⟩) (hay.trans hyb)
end
/-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is differentiable on its interior,
and `f'` is strictly antitone on the interior, then `f` is strictly concave on `D`. -/
lemma strict_anti_on.strict_concave_on_of_deriv {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
(h_anti : strict_anti_on (deriv f) (interior D)) :
strict_concave_on ℝ D f :=
begin
have : strict_mono_on (deriv (-f)) (interior D),
{ intros x hx y hy hxy,
convert neg_lt_neg (h_anti hx hy hxy);
convert deriv.neg },
exact neg_strict_convex_on_iff.mp (this.strict_convex_on_of_deriv hD hf.neg hf'.neg),
end
/-- If a function `f` is differentiable and `f'` is monotone on `ℝ` then `f` is convex. -/
theorem monotone.convex_on_univ_of_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f)
(hf'_mono : monotone (deriv f)) : convex_on ℝ univ f :=
(hf'_mono.monotone_on _).convex_on_of_deriv convex_univ hf.continuous.continuous_on
hf.differentiable_on
/-- If a function `f` is differentiable and `f'` is antitone on `ℝ` then `f` is concave. -/
theorem antitone.concave_on_univ_of_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f)
(hf'_anti : antitone (deriv f)) : concave_on ℝ univ f :=
(hf'_anti.antitone_on _).concave_on_of_deriv convex_univ hf.continuous.continuous_on
hf.differentiable_on
/-- If a function `f` is differentiable and `f'` is strictly monotone on `ℝ` then `f` is strictly
convex. -/
lemma strict_mono.strict_convex_on_univ_of_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f)
(hf'_mono : strict_mono (deriv f)) :
strict_convex_on ℝ univ f :=
(hf'_mono.strict_mono_on _).strict_convex_on_of_deriv convex_univ hf.continuous.continuous_on
hf.differentiable_on
/-- If a function `f` is differentiable and `f'` is strictly antitone on `ℝ` then `f` is strictly
concave. -/
lemma strict_anti.strict_concave_on_univ_of_deriv {f : ℝ → ℝ} (hf : differentiable ℝ f)
(hf'_anti : strict_anti (deriv f)) : strict_concave_on ℝ univ f :=
(hf'_anti.strict_anti_on _).strict_concave_on_of_deriv convex_univ hf.continuous.continuous_on
hf.differentiable_on
/-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its
interior, and `f''` is nonnegative on the interior, then `f` is convex on `D`. -/
theorem convex_on_of_deriv2_nonneg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
(hf'' : differentiable_on ℝ (deriv f) (interior D))
(hf''_nonneg : ∀ x ∈ interior D, 0 ≤ (deriv^[2] f x)) :
convex_on ℝ D f :=
(hD.interior.monotone_on_of_deriv_nonneg hf''.continuous_on (by rwa interior_interior)
$ by rwa interior_interior).convex_on_of_deriv hD hf hf'
/-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its
interior, and `f''` is nonpositive on the interior, then `f` is concave on `D`. -/
theorem concave_on_of_deriv2_nonpos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
(hf'' : differentiable_on ℝ (deriv f) (interior D))
(hf''_nonpos : ∀ x ∈ interior D, deriv^[2] f x ≤ 0) :
concave_on ℝ D f :=
(hD.interior.antitone_on_of_deriv_nonpos hf''.continuous_on (by rwa interior_interior)
$ by rwa interior_interior).concave_on_of_deriv hD hf hf'
/-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its
interior, and `f''` is strictly positive on the interior, then `f` is strictly convex on `D`.
Note that we don't require twice differentiability explicitly as it already implied by the second
derivative being strictly positive. -/
lemma strict_convex_on_of_deriv2_pos {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
(hf'' : ∀ x ∈ interior D, 0 < (deriv^[2] f) x) :
strict_convex_on ℝ D f :=
(hD.interior.strict_mono_on_of_deriv_pos (λ z hz,
(differentiable_at_of_deriv_ne_zero (hf'' z hz).ne').differentiable_within_at
.continuous_within_at) $ by rwa interior_interior).strict_convex_on_of_deriv hD hf hf'
/-- If a function `f` is continuous on a convex set `D ⊆ ℝ`, is twice differentiable on its
interior, and `f''` is strictly negative on the interior, then `f` is strictly concave on `D`.
Note that we don't require twice differentiability explicitly as it already implied by the second
derivative being strictly negative. -/
lemma strict_concave_on_of_deriv2_neg {D : set ℝ} (hD : convex ℝ D) {f : ℝ → ℝ}
(hf : continuous_on f D) (hf' : differentiable_on ℝ f (interior D))
(hf'' : ∀ x ∈ interior D, deriv^[2] f x < 0) :
strict_concave_on ℝ D f :=
(hD.interior.strict_anti_on_of_deriv_neg (λ z hz,
(differentiable_at_of_deriv_ne_zero (hf'' z hz).ne).differentiable_within_at
.continuous_within_at) $ by rwa interior_interior).strict_concave_on_of_deriv hD hf hf'
/-- If a function `f` is twice differentiable on a open convex set `D ⊆ ℝ` and
`f''` is nonnegative on `D`, then `f` is convex on `D`. -/
theorem convex_on_open_of_deriv2_nonneg {D : set ℝ} (hD : convex ℝ D) (hD₂ : is_open D) {f : ℝ → ℝ}
(hf' : differentiable_on ℝ f D) (hf'' : differentiable_on ℝ (deriv f) D)
(hf''_nonneg : ∀ x ∈ D, 0 ≤ (deriv^[2] f) x) : convex_on ℝ D f :=
convex_on_of_deriv2_nonneg hD hf'.continuous_on (by simpa [hD₂.interior_eq] using hf')
(by simpa [hD₂.interior_eq] using hf'') (by simpa [hD₂.interior_eq] using hf''_nonneg)
/-- If a function `f` is twice differentiable on an open convex set `D ⊆ ℝ` and
`f''` is nonpositive on `D`, then `f` is concave on `D`. -/
theorem concave_on_open_of_deriv2_nonpos {D : set ℝ} (hD : convex ℝ D) (hD₂ : is_open D) {f : ℝ → ℝ}
(hf' : differentiable_on ℝ f D) (hf'' : differentiable_on ℝ (deriv f) D)
(hf''_nonpos : ∀ x ∈ D, deriv^[2] f x ≤ 0) : concave_on ℝ D f :=
concave_on_of_deriv2_nonpos hD hf'.continuous_on (by simpa [hD₂.interior_eq] using hf')
(by simpa [hD₂.interior_eq] using hf'') (by simpa [hD₂.interior_eq] using hf''_nonpos)
/-- If a function `f` is twice differentiable on a open convex set `D ⊆ ℝ` and
`f''` is strictly positive on `D`, then `f` is strictly convex on `D`.
Note that we don't require twice differentiability explicitly as it already implied by the second
derivative being strictly positive. -/
lemma strict_convex_on_open_of_deriv2_pos {D : set ℝ} (hD : convex ℝ D) (hD₂ : is_open D)
{f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : ∀ x ∈ D, 0 < (deriv^[2] f) x) :
strict_convex_on ℝ D f :=
strict_convex_on_of_deriv2_pos hD hf'.continuous_on (by simpa [hD₂.interior_eq] using hf') $
by simpa [hD₂.interior_eq] using hf''
/-- If a function `f` is twice differentiable on an open convex set `D ⊆ ℝ` and
`f''` is strictly negative on `D`, then `f` is strictly concave on `D`.
Note that we don't require twice differentiability explicitly as it already implied by the second
derivative being strictly negative. -/
lemma strict_concave_on_open_of_deriv2_neg {D : set ℝ} (hD : convex ℝ D) (hD₂ : is_open D)
{f : ℝ → ℝ} (hf' : differentiable_on ℝ f D) (hf'' : ∀ x ∈ D, deriv^[2] f x < 0) :
strict_concave_on ℝ D f :=
strict_concave_on_of_deriv2_neg hD hf'.continuous_on (by simpa [hD₂.interior_eq] using hf') $
by simpa [hD₂.interior_eq] using hf''
/-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonnegative on `ℝ`,
then `f` is convex on `ℝ`. -/
theorem convex_on_univ_of_deriv2_nonneg {f : ℝ → ℝ} (hf' : differentiable ℝ f)
(hf'' : differentiable ℝ (deriv f)) (hf''_nonneg : ∀ x, 0 ≤ (deriv^[2] f) x) :
convex_on ℝ univ f :=
convex_on_open_of_deriv2_nonneg convex_univ is_open_univ hf'.differentiable_on
hf''.differentiable_on (λ x _, hf''_nonneg x)
/-- If a function `f` is twice differentiable on `ℝ`, and `f''` is nonpositive on `ℝ`,
then `f` is concave on `ℝ`. -/
theorem concave_on_univ_of_deriv2_nonpos {f : ℝ → ℝ} (hf' : differentiable ℝ f)
(hf'' : differentiable ℝ (deriv f)) (hf''_nonpos : ∀ x, deriv^[2] f x ≤ 0) :
concave_on ℝ univ f :=
concave_on_open_of_deriv2_nonpos convex_univ is_open_univ hf'.differentiable_on
hf''.differentiable_on (λ x _, hf''_nonpos x)
/-- If a function `f` is twice differentiable on `ℝ`, and `f''` is strictly positive on `ℝ`,
then `f` is strictly convex on `ℝ`.
Note that we don't require twice differentiability explicitly as it already implied by the second
derivative being strictly positive. -/
lemma strict_convex_on_univ_of_deriv2_pos {f : ℝ → ℝ} (hf' : differentiable ℝ f)
(hf'' : ∀ x, 0 < (deriv^[2] f) x) :
strict_convex_on ℝ univ f :=
strict_convex_on_open_of_deriv2_pos convex_univ is_open_univ hf'.differentiable_on $ λ x _, hf'' x
/-- If a function `f` is twice differentiable on `ℝ`, and `f''` is strictly negative on `ℝ`,
then `f` is strictly concave on `ℝ`.
Note that we don't require twice differentiability explicitly as it already implied by the second
derivative being strictly negative. -/
lemma strict_concave_on_univ_of_deriv2_neg {f : ℝ → ℝ} (hf' : differentiable ℝ f)
(hf'' : ∀ x, deriv^[2] f x < 0) :
strict_concave_on ℝ univ f :=
strict_concave_on_open_of_deriv2_neg convex_univ is_open_univ hf'.differentiable_on $ λ x _, hf'' x
/-! ### Functions `f : E → ℝ` -/
/-- Lagrange's Mean Value Theorem, applied to convex domains. -/
theorem domain_mvt
{f : E → ℝ} {s : set E} {x y : E} {f' : E → (E →L[ℝ] ℝ)}
(hf : ∀ x ∈ s, has_fderiv_within_at f (f' x) s x) (hs : convex ℝ s) (xs : x ∈ s) (ys : y ∈ s) :
∃ z ∈ segment ℝ x y, f y - f x = f' z (y - x) :=
begin
have hIccIoo := @Ioo_subset_Icc_self ℝ _ 0 1,
-- parametrize segment
set g : ℝ → E := λ t, x + t • (y - x),
have hseg : ∀ t ∈ Icc (0:ℝ) 1, g t ∈ segment ℝ x y,
{ rw segment_eq_image',
simp only [mem_image, and_imp, add_right_inj],
intros t ht, exact ⟨t, ht, rfl⟩ },
have hseg' : Icc 0 1 ⊆ g ⁻¹' s,
{ rw ← image_subset_iff, unfold image, change ∀ _, _,
intros z Hz, rw mem_set_of_eq at Hz, rcases Hz with ⟨t, Ht, hgt⟩,
rw ← hgt, exact hs.segment_subset xs ys (hseg t Ht) },
-- derivative of pullback of f under parametrization
have hfg: ∀ t ∈ Icc (0:ℝ) 1, has_deriv_within_at (f ∘ g)
((f' (g t) : E → ℝ) (y-x)) (Icc (0:ℝ) 1) t,
{ intros t Ht,
have hg : has_deriv_at g (y-x) t,
{ have := ((has_deriv_at_id t).smul_const (y - x)).const_add x,
rwa one_smul at this },
exact (hf (g t) $ hseg' Ht).comp_has_deriv_within_at _ hg.has_deriv_within_at hseg' },
-- apply 1-variable mean value theorem to pullback
have hMVT : ∃ (t ∈ Ioo (0:ℝ) 1), ((f' (g t) : E → ℝ) (y-x)) = (f (g 1) - f (g 0)) / (1 - 0),
{ refine exists_has_deriv_at_eq_slope (f ∘ g) _ (by norm_num) _ _,
{ exact λ t Ht, (hfg t Ht).continuous_within_at },
{ exact λ t Ht, (hfg t $ hIccIoo Ht).has_deriv_at (Icc_mem_nhds Ht.1 Ht.2) } },
-- reinterpret on domain
rcases hMVT with ⟨t, Ht, hMVT'⟩,
use g t, refine ⟨hseg t $ hIccIoo Ht, _⟩,
simp [g, hMVT'],
end
section is_R_or_C
/-!
### Vector-valued functions `f : E → F`. Strict differentiability.
A `C^1` function is strictly differentiable, when the field is `ℝ` or `ℂ`. This follows from the
mean value inequality on balls, which is a particular case of the above results after restricting
the scalars to `ℝ`. Note that it does not make sense to talk of a convex set over `ℂ`, but balls
make sense and are enough. Many formulations of the mean value inequality could be generalized to
balls over `ℝ` or `ℂ`. For now, we only include the ones that we need.
-/
variables {𝕜 : Type*} [is_R_or_C 𝕜] {G : Type*} [normed_group G] [normed_space 𝕜 G]
{H : Type*} [normed_group H] [normed_space 𝕜 H] {f : G → H} {f' : G → G →L[𝕜] H} {x : G}
/-- Over the reals or the complexes, a continuously differentiable function is strictly
differentiable. -/
lemma has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at
(hder : ∀ᶠ y in 𝓝 x, has_fderiv_at f (f' y) y) (hcont : continuous_at f' x) :
has_strict_fderiv_at f (f' x) x :=
begin
-- turn little-o definition of strict_fderiv into an epsilon-delta statement
refine is_o_iff.mpr (λ c hc, metric.eventually_nhds_iff_ball.mpr _),
-- the correct ε is the modulus of continuity of f'
rcases metric.mem_nhds_iff.mp (inter_mem hder (hcont $ ball_mem_nhds _ hc)) with ⟨ε, ε0, hε⟩,
refine ⟨ε, ε0, _⟩,
-- simplify formulas involving the product E × E
rintros ⟨a, b⟩ h,
rw [← ball_prod_same, prod_mk_mem_set_prod_eq] at h,
-- exploit the choice of ε as the modulus of continuity of f'
have hf' : ∀ x' ∈ ball x ε, ∥f' x' - f' x∥ ≤ c,
{ intros x' H', rw ← dist_eq_norm, exact le_of_lt (hε H').2 },
-- apply mean value theorem
letI : normed_space ℝ G := restrict_scalars.normed_space ℝ 𝕜 G,
refine (convex_ball _ _).norm_image_sub_le_of_norm_has_fderiv_within_le' _ hf' h.2 h.1,
exact λ y hy, (hε hy).1.has_fderiv_within_at
end
/-- Over the reals or the complexes, a continuously differentiable function is strictly
differentiable. -/
lemma has_strict_deriv_at_of_has_deriv_at_of_continuous_at {f f' : 𝕜 → G} {x : 𝕜}
(hder : ∀ᶠ y in 𝓝 x, has_deriv_at f (f' y) y) (hcont : continuous_at f' x) :
has_strict_deriv_at f (f' x) x :=
has_strict_fderiv_at_of_has_fderiv_at_of_continuous_at (hder.mono (λ y hy, hy.has_fderiv_at)) $
(smul_rightL 𝕜 𝕜 G 1).continuous.continuous_at.comp hcont
end is_R_or_C
|
6a175c86469858800c261bf256748e1e92063ae7 | abd85493667895c57a7507870867b28124b3998f | /src/data/matrix/basic.lean | 3211a382fe721dcd56114ed4b8e345a19391f2fd | [
"Apache-2.0"
] | permissive | pechersky/mathlib | d56eef16bddb0bfc8bc552b05b7270aff5944393 | f1df14c2214ee114c9738e733efd5de174deb95d | refs/heads/master | 1,666,714,392,571 | 1,591,747,567,000 | 1,591,747,567,000 | 270,557,274 | 0 | 0 | Apache-2.0 | 1,591,597,975,000 | 1,591,597,974,000 | null | UTF-8 | Lean | false | false | 19,645 | lean | /-
Copyright (c) 2018 Ellen Arlt. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Ellen Arlt, Blair Shi, Sean Leather, Mario Carneiro, Johan Commelin, Scott Morrison, Yakov Pechersky
-/
import algebra.pi_instances
/-!
# Matrices
-/
universes u v w
open_locale big_operators
@[nolint unused_arguments]
def matrix (m n : Type u) [fintype m] [fintype n] (α : Type v) : Type (max u v) :=
m → n → α
namespace matrix
variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o]
variables {α : Type v}
section ext
variables {M N : matrix m n α}
theorem ext_iff : (∀ i j, M i j = N i j) ↔ M = N :=
⟨λ h, funext $ λ i, funext $ h i, λ h, by simp [h]⟩
@[ext] theorem ext : (∀ i j, M i j = N i j) → M = N :=
ext_iff.mp
end ext
def transpose (M : matrix m n α) : matrix n m α
| x y := M y x
localized "postfix `ᵀ`:1500 := matrix.transpose" in matrix
def col (w : m → α) : matrix m punit α
| x y := w x
def row (v : n → α) : matrix punit n α
| x y := v y
instance [inhabited α] : inhabited (matrix m n α) := pi.inhabited _
instance [has_add α] : has_add (matrix m n α) := pi.has_add
instance [add_semigroup α] : add_semigroup (matrix m n α) := pi.add_semigroup
instance [add_comm_semigroup α] : add_comm_semigroup (matrix m n α) := pi.add_comm_semigroup
instance [has_zero α] : has_zero (matrix m n α) := pi.has_zero
instance [add_monoid α] : add_monoid (matrix m n α) := pi.add_monoid
instance [add_comm_monoid α] : add_comm_monoid (matrix m n α) := pi.add_comm_monoid
instance [has_neg α] : has_neg (matrix m n α) := pi.has_neg
instance [add_group α] : add_group (matrix m n α) := pi.add_group
instance [add_comm_group α] : add_comm_group (matrix m n α) := pi.add_comm_group
@[simp] theorem zero_val [has_zero α] (i j) : (0 : matrix m n α) i j = 0 := rfl
@[simp] theorem neg_val [has_neg α] (M : matrix m n α) (i j) : (- M) i j = - M i j := rfl
@[simp] theorem add_val [has_add α] (M N : matrix m n α) (i j) : (M + N) i j = M i j + N i j := rfl
section diagonal
variables [decidable_eq n]
def diagonal [has_zero α] (d : n → α) : matrix n n α := λ i j, if i = j then d i else 0
@[simp] theorem diagonal_val_eq [has_zero α] {d : n → α} (i : n) : (diagonal d) i i = d i :=
by simp [diagonal]
@[simp] theorem diagonal_val_ne [has_zero α] {d : n → α} {i j : n} (h : i ≠ j) :
(diagonal d) i j = 0 := by simp [diagonal, h]
theorem diagonal_val_ne' [has_zero α] {d : n → α} {i j : n} (h : j ≠ i) :
(diagonal d) i j = 0 := diagonal_val_ne h.symm
@[simp] theorem diagonal_zero [has_zero α] : (diagonal (λ _, 0) : matrix n n α) = 0 :=
by simp [diagonal]; refl
@[simp] lemma diagonal_transpose [has_zero α] (v : n → α) :
(diagonal v)ᵀ = diagonal v :=
begin
ext i j,
by_cases h : i = j,
{ simp [h, transpose] },
{ simp [h, transpose, diagonal_val_ne' h] }
end
section one
variables [has_zero α] [has_one α]
instance : has_one (matrix n n α) := ⟨diagonal (λ _, 1)⟩
@[simp] theorem diagonal_one : (diagonal (λ _, 1) : matrix n n α) = 1 := rfl
theorem one_val {i j} : (1 : matrix n n α) i j = if i = j then 1 else 0 := rfl
@[simp] theorem one_val_eq (i) : (1 : matrix n n α) i i = 1 := diagonal_val_eq i
@[simp] theorem one_val_ne {i j} : i ≠ j → (1 : matrix n n α) i j = 0 :=
diagonal_val_ne
theorem one_val_ne' {i j} : j ≠ i → (1 : matrix n n α) i j = 0 :=
diagonal_val_ne'
end one
end diagonal
section numeral
@[simp] lemma bit0_val [has_add α] (M : matrix n n α) (i : n) (j : n) :
(bit0 M) i j = bit0 (M i j) := rfl
variables [decidable_eq n] [add_monoid α] [has_one α]
lemma bit1_val (M : matrix n n α) (i : n) (j : n) :
(bit1 M) i j = if i = j then bit1 (M i j) else bit0 (M i j) :=
by dsimp [bit1]; by_cases i = j; simp [h]
@[simp]
lemma bit1_val_eq (M : matrix n n α) (i : n) :
(bit1 M) i i = bit1 (M i i) :=
by simp [bit1_val]
@[simp]
lemma bit1_val_ne (M : matrix n n α) {i j : n} (h : i ≠ j) :
(bit1 M) i j = bit0 (M i j) :=
by simp [bit1_val, h]
end numeral
@[simp] theorem diagonal_add [decidable_eq n] [add_monoid α] (d₁ d₂ : n → α) :
diagonal d₁ + diagonal d₂ = diagonal (λ i, d₁ i + d₂ i) :=
by ext i j; by_cases i = j; simp [h]
section dot_product
/-- `dot_product v w` is the sum of the entrywise products `v i * w i` -/
def dot_product [has_mul α] [add_comm_monoid α] (v w : m → α) : α :=
∑ i, v i * w i
lemma dot_product_assoc [semiring α] (u : m → α) (v : m → n → α) (w : n → α) :
dot_product (λ j, dot_product u (λ i, v i j)) w = dot_product u (λ i, dot_product (v i) w) :=
by simpa [dot_product, finset.mul_sum, finset.sum_mul, mul_assoc] using finset.sum_comm
lemma dot_product_comm [comm_semiring α] (v w : m → α) :
dot_product v w = dot_product w v :=
by simp_rw [dot_product, mul_comm]
@[simp] lemma dot_product_punit [add_comm_monoid α] [has_mul α] (v w : punit → α) :
dot_product v w = v ⟨⟩ * w ⟨⟩ :=
by simp [dot_product]
@[simp] lemma dot_product_zero [semiring α] (v : m → α) : dot_product v 0 = 0 :=
by simp [dot_product]
@[simp] lemma dot_product_zero' [semiring α] (v : m → α) : dot_product v (λ _, 0) = 0 :=
dot_product_zero v
@[simp] lemma zero_dot_product [semiring α] (v : m → α) : dot_product 0 v = 0 :=
by simp [dot_product]
@[simp] lemma zero_dot_product' [semiring α] (v : m → α) : dot_product (λ _, (0 : α)) v = 0 :=
zero_dot_product v
@[simp] lemma add_dot_product [semiring α] (u v w : m → α) :
dot_product (u + v) w = dot_product u w + dot_product v w :=
by simp [dot_product, add_mul, finset.sum_add_distrib]
@[simp] lemma dot_product_add [semiring α] (u v w : m → α) :
dot_product u (v + w) = dot_product u v + dot_product u w :=
by simp [dot_product, mul_add, finset.sum_add_distrib]
@[simp] lemma diagonal_dot_product [decidable_eq m] [semiring α] (v w : m → α) (i : m) :
dot_product (diagonal v i) w = v i * w i :=
have ∀ j ≠ i, diagonal v i j * w j = 0 := λ j hij, by simp [diagonal_val_ne' hij],
by convert finset.sum_eq_single i (λ j _, this j) _; simp
@[simp] lemma dot_product_diagonal [decidable_eq m] [semiring α] (v w : m → α) (i : m) :
dot_product v (diagonal w i) = v i * w i :=
have ∀ j ≠ i, v j * diagonal w i j = 0 := λ j hij, by simp [diagonal_val_ne' hij],
by convert finset.sum_eq_single i (λ j _, this j) _; simp
@[simp] lemma dot_product_diagonal' [decidable_eq m] [semiring α] (v w : m → α) (i : m) :
dot_product v (λ j, diagonal w j i) = v i * w i :=
have ∀ j ≠ i, v j * diagonal w j i = 0 := λ j hij, by simp [diagonal_val_ne hij],
by convert finset.sum_eq_single i (λ j _, this j) _; simp
@[simp] lemma neg_dot_product [ring α] (v w : m → α) : dot_product (-v) w = - dot_product v w :=
by simp [dot_product]
@[simp] lemma dot_product_neg [ring α] (v w : m → α) : dot_product v (-w) = - dot_product v w :=
by simp [dot_product]
@[simp] lemma smul_dot_product [semiring α] (x : α) (v w : m → α) :
dot_product (x • v) w = x * dot_product v w :=
by simp [dot_product, finset.mul_sum, mul_assoc]
@[simp] lemma dot_product_smul [comm_semiring α] (x : α) (v w : m → α) :
dot_product v (x • w) = x * dot_product v w :=
by simp [dot_product, finset.mul_sum, mul_assoc, mul_comm, mul_left_comm]
end dot_product
protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) :
matrix l n α :=
λ i k, dot_product (λ j, M i j) (λ j, N j k)
localized "infixl ` ⬝ `:75 := matrix.mul" in matrix
theorem mul_val [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} :
(M ⬝ N) i k = ∑ j, M i j * N j k := rfl
instance [has_mul α] [add_comm_monoid α] : has_mul (matrix n n α) := ⟨matrix.mul⟩
@[simp] theorem mul_eq_mul [has_mul α] [add_comm_monoid α] (M N : matrix n n α) :
M * N = M ⬝ N := rfl
theorem mul_val' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} :
(M ⬝ N) i k = dot_product (λ j, M i j) (λ j, N j k) := rfl
section semigroup
variables [semiring α]
protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) :
(L ⬝ M) ⬝ N = L ⬝ (M ⬝ N) :=
by { ext, apply dot_product_assoc }
instance : semigroup (matrix n n α) :=
{ mul_assoc := matrix.mul_assoc, ..matrix.has_mul }
end semigroup
@[simp] theorem diagonal_neg [decidable_eq n] [add_group α] (d : n → α) :
-diagonal d = diagonal (λ i, -d i) :=
by ext i j; by_cases i = j; simp [h]
section semiring
variables [semiring α]
@[simp] protected theorem mul_zero (M : matrix m n α) : M ⬝ (0 : matrix n o α) = 0 :=
by { ext i j, apply dot_product_zero }
@[simp] protected theorem zero_mul (M : matrix m n α) : (0 : matrix l m α) ⬝ M = 0 :=
by { ext i j, apply zero_dot_product }
protected theorem mul_add (L : matrix m n α) (M N : matrix n o α) : L ⬝ (M + N) = L ⬝ M + L ⬝ N :=
by { ext i j, apply dot_product_add }
protected theorem add_mul (L M : matrix l m α) (N : matrix m n α) : (L + M) ⬝ N = L ⬝ N + M ⬝ N :=
by { ext i j, apply add_dot_product }
@[simp] theorem diagonal_mul [decidable_eq m]
(d : m → α) (M : matrix m n α) (i j) : (diagonal d).mul M i j = d i * M i j :=
diagonal_dot_product _ _ _
@[simp] theorem mul_diagonal [decidable_eq n]
(d : n → α) (M : matrix m n α) (i j) : (M ⬝ diagonal d) i j = M i j * d j :=
by { rw ← diagonal_transpose, apply dot_product_diagonal }
@[simp] protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α) ⬝ M = M :=
by ext i j; rw [← diagonal_one, diagonal_mul, one_mul]
@[simp] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M ⬝ (1 : matrix n n α) = M :=
by ext i j; rw [← diagonal_one, mul_diagonal, mul_one]
instance [decidable_eq n] : monoid (matrix n n α) :=
{ one_mul := matrix.one_mul,
mul_one := matrix.mul_one,
..matrix.has_one, ..matrix.semigroup }
instance [decidable_eq n] : semiring (matrix n n α) :=
{ mul_zero := matrix.mul_zero,
zero_mul := matrix.zero_mul,
left_distrib := matrix.mul_add,
right_distrib := matrix.add_mul,
..matrix.add_comm_monoid,
..matrix.monoid }
@[simp] theorem diagonal_mul_diagonal [decidable_eq n] (d₁ d₂ : n → α) :
(diagonal d₁) ⬝ (diagonal d₂) = diagonal (λ i, d₁ i * d₂ i) :=
by ext i j; by_cases i = j; simp [h]
theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) :
diagonal d₁ * diagonal d₂ = diagonal (λ i, d₁ i * d₂ i) :=
diagonal_mul_diagonal _ _
lemma is_add_monoid_hom_mul_left (M : matrix l m α) :
is_add_monoid_hom (λ x : matrix m n α, M ⬝ x) :=
{ to_is_add_hom := ⟨matrix.mul_add _⟩, map_zero := matrix.mul_zero _ }
lemma is_add_monoid_hom_mul_right (M : matrix m n α) :
is_add_monoid_hom (λ x : matrix l m α, x ⬝ M) :=
{ to_is_add_hom := ⟨λ _ _, matrix.add_mul _ _ _⟩, map_zero := matrix.zero_mul _ }
protected lemma sum_mul {β : Type*} (s : finset β) (f : β → matrix l m α)
(M : matrix m n α) : s.sum f ⬝ M = s.sum (λ a, f a ⬝ M) :=
(@finset.sum_hom _ _ _ _ _ s f (λ x, x ⬝ M)
/- This line does not type-check without `id` and `: _`. Lean did not recognize that two different
`add_monoid` instances were def-eq -/
(id (@is_add_monoid_hom_mul_right l _ _ _ _ _ _ _ M) : _)).symm
protected lemma mul_sum {β : Type*} (s : finset β) (f : β → matrix m n α)
(M : matrix l m α) : M ⬝ s.sum f = s.sum (λ a, M ⬝ f a) :=
(@finset.sum_hom _ _ _ _ _ s f (λ x, M ⬝ x)
/- This line does not type-check without `id` and `: _`. Lean did not recognize that two different
`add_monoid` instances were def-eq -/
(id (@is_add_monoid_hom_mul_left _ _ n _ _ _ _ _ M) : _)).symm
@[simp]
lemma row_mul_col_val (v w : m → α) (i j) : (row v ⬝ col w) i j = dot_product v w :=
rfl
end semiring
section ring
variables [ring α]
@[simp] theorem neg_mul (M : matrix m n α) (N : matrix n o α) :
(-M) ⬝ N = -(M ⬝ N) :=
by { ext, apply neg_dot_product }
@[simp] theorem mul_neg (M : matrix m n α) (N : matrix n o α) :
M ⬝ (-N) = -(M ⬝ N) :=
by { ext, apply dot_product_neg }
end ring
instance [decidable_eq n] [ring α] : ring (matrix n n α) :=
{ ..matrix.semiring, ..matrix.add_comm_group }
instance [semiring α] : has_scalar α (matrix m n α) := pi.has_scalar
instance {β : Type w} [semiring α] [add_comm_monoid β] [semimodule α β] :
semimodule α (matrix m n β) := pi.semimodule _ _ _
@[simp] lemma smul_val [semiring α] (a : α) (A : matrix m n α) (i : m) (j : n) : (a • A) i j = a * A i j := rfl
section comm_semiring
variables [comm_semiring α]
lemma smul_eq_diagonal_mul [decidable_eq m] (M : matrix m n α) (a : α) :
a • M = diagonal (λ _, a) ⬝ M :=
by { ext, simp }
lemma smul_eq_mul_diagonal [decidable_eq n] (M : matrix m n α) (a : α) :
a • M = M ⬝ diagonal (λ _, a) :=
by { ext, simp [mul_comm] }
@[simp] lemma mul_smul (M : matrix m n α) (a : α) (N : matrix n l α) : M ⬝ (a • N) = a • M ⬝ N :=
by { ext, apply dot_product_smul }
@[simp] lemma smul_mul (M : matrix m n α) (a : α) (N : matrix n l α) : (a • M) ⬝ N = a • M ⬝ N :=
by { ext, apply smul_dot_product }
end comm_semiring
section semiring
variables [semiring α]
def vec_mul_vec (w : m → α) (v : n → α) : matrix m n α
| x y := w x * v y
def mul_vec (M : matrix m n α) (v : n → α) : m → α
| i := dot_product (λ j, M i j) v
def vec_mul (v : m → α) (M : matrix m n α) : n → α
| j := dot_product v (λ i, M i j)
instance mul_vec.is_add_monoid_hom_left (v : n → α) :
is_add_monoid_hom (λM:matrix m n α, mul_vec M v) :=
{ map_zero := by ext; simp [mul_vec]; refl,
map_add :=
begin
intros x y,
ext m,
apply add_dot_product
end }
lemma mul_vec_diagonal [decidable_eq m] (v w : m → α) (x : m) :
mul_vec (diagonal v) w x = v x * w x :=
diagonal_dot_product v w x
lemma vec_mul_diagonal [decidable_eq m] (v w : m → α) (x : m) :
vec_mul v (diagonal w) x = v x * w x :=
dot_product_diagonal' v w x
@[simp] lemma mul_vec_one [decidable_eq m] (v : m → α) : mul_vec 1 v = v :=
by { ext, rw [←diagonal_one, mul_vec_diagonal, one_mul] }
@[simp] lemma vec_mul_one [decidable_eq m] (v : m → α) : vec_mul v 1 = v :=
by { ext, rw [←diagonal_one, vec_mul_diagonal, mul_one] }
@[simp] lemma mul_vec_zero (A : matrix m n α) : mul_vec A 0 = 0 :=
by { ext, simp [mul_vec] }
@[simp] lemma vec_mul_zero (A : matrix m n α) : vec_mul 0 A = 0 :=
by { ext, simp [vec_mul] }
@[simp] lemma vec_mul_vec_mul (v : m → α) (M : matrix m n α) (N : matrix n o α) :
vec_mul (vec_mul v M) N = vec_mul v (M ⬝ N) :=
by { ext, apply dot_product_assoc }
@[simp] lemma mul_vec_mul_vec (v : o → α) (M : matrix m n α) (N : matrix n o α) :
mul_vec M (mul_vec N v) = mul_vec (M ⬝ N) v :=
by { ext, symmetry, apply dot_product_assoc }
lemma vec_mul_vec_eq (w : m → α) (v : n → α) :
vec_mul_vec w v = (col w) ⬝ (row v) :=
by { ext i j, simp [vec_mul_vec, mul_val], refl }
end semiring
section ring
variables [ring α]
lemma neg_vec_mul (v : m → α) (A : matrix m n α) : vec_mul (-v) A = - vec_mul v A :=
by { ext, apply neg_dot_product }
lemma vec_mul_neg (v : m → α) (A : matrix m n α) : vec_mul v (-A) = - vec_mul v A :=
by { ext, apply dot_product_neg }
lemma neg_mul_vec (v : n → α) (A : matrix m n α) : mul_vec (-A) v = - mul_vec A v :=
by { ext, apply neg_dot_product }
lemma mul_vec_neg (v : n → α) (A : matrix m n α) : mul_vec A (-v) = - mul_vec A v :=
by { ext, apply dot_product_neg }
end ring
section transpose
open_locale matrix
/--
Tell `simp` what the entries are in a transposed matrix.
Compare with `mul_val`, `diagonal_val_eq`, etc.
-/
@[simp] lemma transpose_val (M : matrix m n α) (i j) : M.transpose j i = M i j := rfl
@[simp] lemma transpose_transpose (M : matrix m n α) :
Mᵀᵀ = M :=
by ext; refl
@[simp] lemma transpose_zero [has_zero α] : (0 : matrix m n α)ᵀ = 0 :=
by ext i j; refl
@[simp] lemma transpose_one [decidable_eq n] [has_zero α] [has_one α] : (1 : matrix n n α)ᵀ = 1 :=
begin
ext i j,
unfold has_one.one transpose,
by_cases i = j,
{ simp only [h, diagonal_val_eq] },
{ simp only [diagonal_val_ne h, diagonal_val_ne (λ p, h (symm p))] }
end
@[simp] lemma transpose_add [has_add α] (M : matrix m n α) (N : matrix m n α) :
(M + N)ᵀ = Mᵀ + Nᵀ :=
by { ext i j, simp }
@[simp] lemma transpose_mul [comm_ring α] (M : matrix m n α) (N : matrix n l α) :
(M ⬝ N)ᵀ = Nᵀ ⬝ Mᵀ :=
begin
ext i j,
apply dot_product_comm
end
@[simp] lemma transpose_smul [comm_ring α] (c : α)(M : matrix m n α) :
(c • M)ᵀ = c • Mᵀ :=
by { ext i j, refl }
@[simp] lemma transpose_neg [comm_ring α] (M : matrix m n α) :
(- M)ᵀ = - Mᵀ :=
by ext i j; refl
end transpose
def minor (A : matrix m n α) (row : l → m) (col : o → n) : matrix l o α :=
λ i j, A (row i) (col j)
@[reducible]
def sub_left {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin l) α :=
minor A id (fin.cast_add r)
@[reducible]
def sub_right {m l r : nat} (A : matrix (fin m) (fin (l + r)) α) : matrix (fin m) (fin r) α :=
minor A id (fin.nat_add l)
@[reducible]
def sub_up {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin u) (fin n) α :=
minor A (fin.cast_add d) id
@[reducible]
def sub_down {d u n : nat} (A : matrix (fin (u + d)) (fin n) α) : matrix (fin d) (fin n) α :=
minor A (fin.nat_add u) id
@[reducible]
def sub_up_right {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin u) (fin r) α :=
sub_up (sub_right A)
@[reducible]
def sub_down_right {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin d) (fin r) α :=
sub_down (sub_right A)
@[reducible]
def sub_up_left {d u l r : nat} (A : matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin u) (fin (l)) α :=
sub_up (sub_left A)
@[reducible]
def sub_down_left {d u l r : nat} (A: matrix (fin (u + d)) (fin (l + r)) α) :
matrix (fin d) (fin (l)) α :=
sub_down (sub_left A)
section row_col
/-!
### `row_col` section
Simplification lemmas for `matrix.row` and `matrix.col`.
-/
open_locale matrix
@[simp] lemma col_add [semiring α] (v w : m → α) : col (v + w) = col v + col w := by { ext, refl }
@[simp] lemma col_smul [semiring α] (x : α) (v : m → α) : col (x • v) = x • col v := by { ext, refl }
@[simp] lemma row_add [semiring α] (v w : m → α) : row (v + w) = row v + row w := by { ext, refl }
@[simp] lemma row_smul [semiring α] (x : α) (v : m → α) : row (x • v) = x • row v := by { ext, refl }
@[simp] lemma col_val (v : m → α) (i j) : matrix.col v i j = v i := rfl
@[simp] lemma row_val (v : m → α) (i j) : matrix.row v i j = v j := rfl
@[simp]
lemma transpose_col (v : m → α) : (matrix.col v).transpose = matrix.row v := by {ext, refl}
@[simp]
lemma transpose_row (v : m → α) : (matrix.row v).transpose = matrix.col v := by {ext, refl}
lemma row_vec_mul [semiring α] (M : matrix m n α) (v : m → α) :
matrix.row (matrix.vec_mul v M) = matrix.row v ⬝ M := by {ext, refl}
lemma col_vec_mul [semiring α] (M : matrix m n α) (v : m → α) :
matrix.col (matrix.vec_mul v M) = (matrix.row v ⬝ M)ᵀ := by {ext, refl}
lemma col_mul_vec [semiring α] (M : matrix m n α) (v : n → α) :
matrix.col (matrix.mul_vec M v) = M ⬝ matrix.col v := by {ext, refl}
lemma row_mul_vec [semiring α] (M : matrix m n α) (v : n → α) :
matrix.row (matrix.mul_vec M v) = (M ⬝ matrix.col v)ᵀ := by {ext, refl}
end row_col
end matrix
|
ff70f23ebdf22364d329f6e29352245fc5be2af6 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/order/iterate.lean | bcd0164440a1a6d6e7084f7922e7defc7abfc9a8 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 8,988 | lean | /-
Copyright (c) 2020 Yury G. Kudryashov. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Yury G. Kudryashov
-/
import logic.function.iterate
import data.nat.basic
/-!
# Inequalities on iterates
In this file we prove some inequalities comparing `f^[n] x` and `g^[n] x` where `f` and `g` are
two self-maps that commute with each other.
Current selection of inequalities is motivated by formalization of the rotation number of
a circle homeomorphism.
-/
variables {α β : Type*}
open function
namespace monotone
variables [preorder α] {f : α → α} {x y : ℕ → α}
/-!
### Comparison of two sequences
If $f$ is a monotone function, then $∀ k, x_{k+1} ≤ f(x_k)$ implies that $x_k$ grows slower than
$f^k(x_0)$, and similarly for the reversed inequalities. If $x_k$ and $y_k$ are two sequences such
that $x_{k+1} ≤ f(x_k)$ and $y_{k+1} ≥ f(y_k)$ for all $k < n$, then $x_0 ≤ y_0$ implies
$x_n ≤ y_n$, see `monotone.seq_le_seq`.
If some of the inequalities in this lemma are strict, then we have $x_n < y_n$. The rest of the
lemmas in this section formalize this fact for different inequalities made strict.
-/
lemma seq_le_seq (hf : monotone f) (n : ℕ) (h₀ : x 0 ≤ y 0)
(hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) :
x n ≤ y n :=
begin
induction n with n ihn,
{ exact h₀ },
{ refine (hx _ n.lt_succ_self).trans ((hf $ ihn _ _).trans (hy _ n.lt_succ_self)),
exact λ k hk, hx _ (hk.trans n.lt_succ_self),
exact λ k hk, hy _ (hk.trans n.lt_succ_self) }
end
lemma seq_pos_lt_seq_of_lt_of_le (hf : monotone f) {n : ℕ} (hn : 0 < n) (h₀ : x 0 ≤ y 0)
(hx : ∀ k < n, x (k + 1) < f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) :
x n < y n :=
begin
induction n with n ihn, { exact hn.false.elim },
suffices : x n ≤ y n,
from (hx n n.lt_succ_self).trans_le ((hf this).trans $ hy n n.lt_succ_self),
cases n, { exact h₀ },
refine (ihn n.zero_lt_succ (λ k hk, hx _ _) (λ k hk, hy _ _)).le;
exact hk.trans n.succ.lt_succ_self
end
lemma seq_pos_lt_seq_of_le_of_lt (hf : monotone f) {n : ℕ} (hn : 0 < n) (h₀ : x 0 ≤ y 0)
(hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) < y (k + 1)) :
x n < y n :=
hf.dual.seq_pos_lt_seq_of_lt_of_le hn h₀ hy hx
lemma seq_lt_seq_of_lt_of_le (hf : monotone f) (n : ℕ) (h₀ : x 0 < y 0)
(hx : ∀ k < n, x (k + 1) < f (x k)) (hy : ∀ k < n, f (y k) ≤ y (k + 1)) :
x n < y n :=
by { cases n, exacts [h₀, hf.seq_pos_lt_seq_of_lt_of_le n.zero_lt_succ h₀.le hx hy] }
lemma seq_lt_seq_of_le_of_lt (hf : monotone f) (n : ℕ) (h₀ : x 0 < y 0)
(hx : ∀ k < n, x (k + 1) ≤ f (x k)) (hy : ∀ k < n, f (y k) < y (k + 1)) :
x n < y n :=
hf.dual.seq_lt_seq_of_lt_of_le n h₀ hy hx
/-!
### Iterates of two functions
In this section we compare the iterates of a monotone function `f : α → α` to iterates of any
function `g : β → β`. If `h : β → α` satisfies `h ∘ g ≤ f ∘ h`, then `h (g^[n] x)` grows slower
than `f^[n] (h x)`, and similarly for the reversed inequality.
Then we specialize these two lemmas to the case `β = α`, `h = id`.
-/
variables {g : β → β} {h : β → α}
open function
lemma le_iterate_comp_of_le (hf : monotone f) (H : h ∘ g ≤ f ∘ h) (n : ℕ) :
h ∘ (g^[n]) ≤ (f^[n]) ∘ h :=
λ x, by refine hf.seq_le_seq n _ (λ k hk, _) (λ k hk, _); simp [iterate_succ', H _]
lemma iterate_comp_le_of_le (hf : monotone f) (H : f ∘ h ≤ h ∘ g) (n : ℕ) :
f^[n] ∘ h ≤ h ∘ (g^[n]) :=
hf.dual.le_iterate_comp_of_le H n
/-- If `f ≤ g` and `f` is monotone, then `f^[n] ≤ g^[n]`. -/
lemma iterate_le_of_le {g : α → α} (hf : monotone f) (h : f ≤ g) (n : ℕ) :
f^[n] ≤ (g^[n]) :=
hf.iterate_comp_le_of_le h n
/-- If `f ≤ g` and `g` is monotone, then `f^[n] ≤ g^[n]`. -/
lemma le_iterate_of_le {g : α → α} (hg : monotone g) (h : f ≤ g) (n : ℕ) :
f^[n] ≤ (g^[n]) :=
hg.dual.iterate_le_of_le h n
end monotone
/-!
### Comparison of iterations and the identity function
If $f(x) ≤ x$ for all $x$ (we express this as `f ≤ id` in the code), then the same is true for
any iterate of $f$, and similarly for the reversed inequality.
-/
namespace function
section preorder
variables [preorder α] {f : α → α}
/-- If $x ≤ f x$ for all $x$ (we write this as `id ≤ f`), then the same is true for any iterate
`f^[n]` of `f`. -/
lemma id_le_iterate_of_id_le (h : id ≤ f) (n : ℕ) : id ≤ (f^[n]) :=
by simpa only [iterate_id] using monotone_id.iterate_le_of_le h n
lemma iterate_le_id_of_le_id (h : f ≤ id) (n : ℕ) : (f^[n]) ≤ id :=
@id_le_iterate_of_id_le (order_dual α) _ f h n
lemma monotone_iterate_of_id_le (h : id ≤ f) : monotone (λ m, f^[m]) :=
monotone_nat_of_le_succ $ λ n x, by { rw iterate_succ_apply', exact h _ }
lemma antitone_iterate_of_le_id (h : f ≤ id) : antitone (λ m, f^[m]) :=
λ m n hmn, @monotone_iterate_of_id_le (order_dual α) _ f h m n hmn
end preorder
/-!
### Iterates of commuting functions
If `f` and `g` are monotone and commute, then `f x ≤ g x` implies `f^[n] x ≤ g^[n] x`, see
`function.commute.iterate_le_of_map_le`. We also prove two strict inequality versions of this lemma,
as well as `iff` versions.
-/
namespace commute
section preorder
variables [preorder α] {f g : α → α}
lemma iterate_le_of_map_le (h : commute f g) (hf : monotone f) (hg : monotone g)
{x} (hx : f x ≤ g x) (n : ℕ) :
f^[n] x ≤ (g^[n]) x :=
by refine hf.seq_le_seq n _ (λ k hk, _) (λ k hk, _);
simp [iterate_succ' f, h.iterate_right _ _, hg.iterate _ hx]
lemma iterate_pos_lt_of_map_lt (h : commute f g) (hf : monotone f) (hg : strict_mono g)
{x} (hx : f x < g x) {n} (hn : 0 < n) :
f^[n] x < (g^[n]) x :=
by refine hf.seq_pos_lt_seq_of_le_of_lt hn _ (λ k hk, _) (λ k hk, _);
simp [iterate_succ' f, h.iterate_right _ _, hg.iterate _ hx]
lemma iterate_pos_lt_of_map_lt' (h : commute f g) (hf : strict_mono f) (hg : monotone g)
{x} (hx : f x < g x) {n} (hn : 0 < n) :
f^[n] x < (g^[n]) x :=
@iterate_pos_lt_of_map_lt (order_dual α) _ g f h.symm hg.dual hf.dual x hx n hn
end preorder
variables [linear_order α] {f g : α → α}
lemma iterate_pos_lt_iff_map_lt (h : commute f g) (hf : monotone f)
(hg : strict_mono g) {x n} (hn : 0 < n) :
f^[n] x < (g^[n]) x ↔ f x < g x :=
begin
rcases lt_trichotomy (f x) (g x) with H|H|H,
{ simp only [*, iterate_pos_lt_of_map_lt] },
{ simp only [*, h.iterate_eq_of_map_eq, lt_irrefl] },
{ simp only [lt_asymm H, lt_asymm (h.symm.iterate_pos_lt_of_map_lt' hg hf H hn)] }
end
lemma iterate_pos_lt_iff_map_lt' (h : commute f g) (hf : strict_mono f)
(hg : monotone g) {x n} (hn : 0 < n) :
f^[n] x < (g^[n]) x ↔ f x < g x :=
@iterate_pos_lt_iff_map_lt (order_dual α) _ _ _ h.symm hg.dual hf.dual x n hn
lemma iterate_pos_le_iff_map_le (h : commute f g) (hf : monotone f)
(hg : strict_mono g) {x n} (hn : 0 < n) :
f^[n] x ≤ (g^[n]) x ↔ f x ≤ g x :=
by simpa only [not_lt] using not_congr (h.symm.iterate_pos_lt_iff_map_lt' hg hf hn)
lemma iterate_pos_le_iff_map_le' (h : commute f g) (hf : strict_mono f)
(hg : monotone g) {x n} (hn : 0 < n) :
f^[n] x ≤ (g^[n]) x ↔ f x ≤ g x :=
by simpa only [not_lt] using not_congr (h.symm.iterate_pos_lt_iff_map_lt hg hf hn)
lemma iterate_pos_eq_iff_map_eq (h : commute f g) (hf : monotone f)
(hg : strict_mono g) {x n} (hn : 0 < n) :
f^[n] x = (g^[n]) x ↔ f x = g x :=
by simp only [le_antisymm_iff, h.iterate_pos_le_iff_map_le hf hg hn,
h.symm.iterate_pos_le_iff_map_le' hg hf hn]
end commute
end function
namespace monotone
variables [preorder α] {f : α → α} {x : α}
/-- If `f` is a monotone map and `x ≤ f x` at some point `x`, then the iterates `f^[n] x` form
a monotone sequence. -/
lemma monotone_iterate_of_le_map (hf : monotone f) (hx : x ≤ f x) : monotone (λ n, f^[n] x) :=
monotone_nat_of_le_succ $ λ n, by { rw iterate_succ_apply, exact hf.iterate n hx }
/-- If `f` is a monotone map and `f x ≤ x` at some point `x`, then the iterates `f^[n] x` form
a antitone sequence. -/
lemma antitone_iterate_of_map_le (hf : monotone f) (hx : f x ≤ x) : antitone (λ n, f^[n] x) :=
hf.dual.monotone_iterate_of_le_map hx
end monotone
namespace strict_mono
variables [preorder α] {f : α → α} {x : α}
/-- If `f` is a strictly monotone map and `x < f x` at some point `x`, then the iterates `f^[n] x`
form a strictly monotone sequence. -/
lemma strict_mono_iterate_of_lt_map (hf : strict_mono f) (hx : x < f x) :
strict_mono (λ n, f^[n] x) :=
strict_mono_nat_of_lt_succ $ λ n, by { rw iterate_succ_apply, exact hf.iterate n hx }
/-- If `f` is a strictly antitone map and `f x < x` at some point `x`, then the iterates `f^[n] x`
form a strictly antitone sequence. -/
lemma strict_anti_iterate_of_map_lt (hf : strict_mono f) (hx : f x < x) :
strict_anti (λ n, f^[n] x) :=
hf.dual.strict_mono_iterate_of_lt_map hx
end strict_mono
|
f8da816ba58cfe1f8253fee7e1f70ec8fab0b5ce | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/topology/discrete_quotient.lean | d51098ad3841cb6b540a419181a94ec4b2cae98b | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 14,204 | lean | /-
Copyright (c) 2021 Adam Topaz. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Calle Sönne, Adam Topaz
-/
import topology.separation
import topology.subset_properties
import topology.locally_constant.basic
/-!
# Discrete quotients of a topological space.
This file defines the type of discrete quotients of a topological space,
denoted `discrete_quotient X`. To avoid quantifying over types, we model such
quotients as setoids whose equivalence classes are clopen.
## Definitions
1. `discrete_quotient X` is the type of discrete quotients of `X`.
It is endowed with a coercion to `Type`, which is defined as the
quotient associated to the setoid in question, and each such quotient
is endowed with the discrete topology.
2. Given `S : discrete_quotient X`, the projection `X → S` is denoted
`S.proj`.
3. When `X` is compact and `S : discrete_quotient X`, the space `S` is
endowed with a `fintype` instance.
## Order structure
The type `discrete_quotient X` is endowed with an instance of a `semilattice_inf_top`.
The partial ordering `A ≤ B` mathematically means that `B.proj` factors through `A.proj`.
The top element `⊤` is the trivial quotient, meaning that every element of `X` is collapsed
to a point. Given `h : A ≤ B`, the map `A → B` is `discrete_quotient.of_le h`.
Whenever `X` is discrete, the type `discrete_quotient X` is also endowed with an instance of a
`semilattice_inf_bot`, where the bot element `⊥` is `X` itself.
Given `f : X → Y` and `h : continuous f`, we define a predicate `le_comap h A B` for
`A : discrete_quotient X` and `B : discrete_quotient Y`, asserting that `f` descends to `A → B`.
If `cond : le_comap h A B`, the function `A → B` is obtained by `discrete_quotient.map cond`.
## Theorems
The two main results proved in this file are:
1. `discrete_quotient.eq_of_proj_eq` which states that when `X` is compact, t2 and totally
disconnected, any two elements of `X` agree if their projections in `Q` agree for all
`Q : discrete_quotient X`.
2. `discrete_quotient.exists_of_compat` which states that when `X` is compact, then any
system of elements of `Q` as `Q : discrete_quotient X` varies, which is compatible with
respect to `discrete_quotient.of_le`, must arise from some element of `X`.
## Remarks
The constructions in this file will be used to show that any profinite space is a limit
of finite discrete spaces.
-/
variables (X : Type*) [topological_space X]
/-- The type of discrete quotients of a topological space. -/
@[ext]
structure discrete_quotient :=
(rel : X → X → Prop)
(equiv : equivalence rel)
(clopen : ∀ x, is_clopen (set_of (rel x)))
namespace discrete_quotient
variables {X} (S : discrete_quotient X)
/-- Construct a discrete quotient from a clopen set. -/
def of_clopen {A : set X} (h : is_clopen A) : discrete_quotient X :=
{ rel := λ x y, x ∈ A ∧ y ∈ A ∨ x ∉ A ∧ y ∉ A,
equiv := ⟨by tauto!, by tauto!, by tauto!⟩,
clopen := begin
intros x,
by_cases hx : x ∈ A,
{ apply is_clopen.union,
{ convert h,
ext,
exact ⟨λ i, i.2, λ i, ⟨hx,i⟩⟩ },
{ convert is_clopen_empty,
tidy } },
{ apply is_clopen.union,
{ convert is_clopen_empty,
tidy },
{ convert is_clopen.compl h,
ext,
exact ⟨λ i, i.2, λ i, ⟨hx, i⟩⟩ } },
end }
lemma refl : ∀ x : X, S.rel x x := S.equiv.1
lemma symm : ∀ x y : X, S.rel x y → S.rel y x := S.equiv.2.1
lemma trans : ∀ x y z : X, S.rel x y → S.rel y z → S.rel x z := S.equiv.2.2
/-- The setoid whose quotient yields the discrete quotient. -/
def setoid : setoid X := ⟨S.rel, S.equiv⟩
instance : has_coe_to_sort (discrete_quotient X) :=
⟨Type*, λ S, quotient S.setoid⟩
instance : topological_space S := ⊥
/-- The projection from `X` to the given discrete quotient. -/
def proj : X → S := quotient.mk'
lemma proj_surjective : function.surjective S.proj := quotient.surjective_quotient_mk'
lemma fiber_eq (x : X) : S.proj ⁻¹' {S.proj x} = set_of (S.rel x) :=
begin
ext1 y,
simp only [set.mem_preimage, set.mem_singleton_iff, quotient.eq',
discrete_quotient.proj.equations._eqn_1, set.mem_set_of_eq],
exact ⟨λ h, S.symm _ _ h, λ h, S.symm _ _ h⟩,
end
lemma proj_is_locally_constant : is_locally_constant S.proj :=
begin
rw (is_locally_constant.tfae S.proj).out 0 3,
intros x,
rcases S.proj_surjective x with ⟨x,rfl⟩,
simp [fiber_eq, (S.clopen x).1],
end
lemma proj_continuous : continuous S.proj :=
is_locally_constant.continuous $ proj_is_locally_constant _
lemma fiber_closed (A : set S) : is_closed (S.proj ⁻¹' A) :=
is_closed.preimage S.proj_continuous ⟨trivial⟩
lemma fiber_open (A : set S) : is_open (S.proj ⁻¹' A) :=
is_open.preimage S.proj_continuous trivial
lemma fiber_clopen (A : set S) : is_clopen (S.proj ⁻¹' A) := ⟨fiber_open _ _, fiber_closed _ _⟩
instance : semilattice_inf_top (discrete_quotient X) :=
{ top := ⟨λ a b, true, ⟨by tauto, by tauto, by tauto⟩, λ _, is_clopen_univ⟩,
inf := λ A B,
{ rel := λ x y, A.rel x y ∧ B.rel x y,
equiv := ⟨λ a, ⟨A.refl _,B.refl _⟩, λ a b h, ⟨A.symm _ _ h.1, B.symm _ _ h.2⟩,
λ a b c h1 h2, ⟨A.trans _ _ _ h1.1 h2.1, B.trans _ _ _ h1.2 h2.2⟩⟩,
clopen := λ x, is_clopen.inter (A.clopen _) (B.clopen _) },
le := λ A B, ∀ x y : X, A.rel x y → B.rel x y,
le_refl := λ a, by tauto,
le_trans := λ a b c h1 h2, by tauto,
le_antisymm := λ a b h1 h2, by { ext, tauto },
inf_le_left := λ a b, by tauto,
inf_le_right := λ a b, by tauto,
le_inf := λ a b c h1 h2, by tauto,
le_top := λ a, by tauto }
instance : inhabited (discrete_quotient X) := ⟨⊤⟩
section comap
variables {Y : Type*} [topological_space Y] {f : Y → X} (cont : continuous f)
/-- Comap a discrete quotient along a continuous map. -/
def comap : discrete_quotient Y :=
{ rel := λ a b, S.rel (f a) (f b),
equiv := ⟨λ a, S.refl _, λ a b h, S.symm _ _ h, λ a b c h1 h2, S.trans _ _ _ h1 h2⟩,
clopen := λ y, ⟨is_open.preimage cont (S.clopen _).1, is_closed.preimage cont (S.clopen _).2⟩ }
@[simp]
lemma comap_id : S.comap (continuous_id : continuous (id : X → X)) = S := by { ext, refl }
@[simp]
lemma comap_comp {Z : Type*} [topological_space Z] {g : Z → Y} (cont' : continuous g) :
S.comap (continuous.comp cont cont') = (S.comap cont).comap cont' := by { ext, refl }
lemma comap_mono {A B : discrete_quotient X} (h : A ≤ B) : A.comap cont ≤ B.comap cont :=
by tauto
end comap
section of_le
/-- The map induced by a refinement of a discrete quotient. -/
def of_le {A B : discrete_quotient X} (h : A ≤ B) : A → B :=
λ a, quotient.lift_on' a (λ x, B.proj x) (λ a b i, quotient.sound' (h _ _ i))
@[simp]
lemma of_le_refl {A : discrete_quotient X} : of_le (le_refl A) = id := by { ext ⟨⟩, refl }
lemma of_le_refl_apply {A : discrete_quotient X} (a : A) : of_le (le_refl A) a = a := by simp
@[simp]
lemma of_le_comp {A B C : discrete_quotient X} (h1 : A ≤ B) (h2 : B ≤ C) :
of_le (le_trans h1 h2) = of_le h2 ∘ of_le h1 := by { ext ⟨⟩, refl }
lemma of_le_comp_apply {A B C : discrete_quotient X} (h1 : A ≤ B) (h2 : B ≤ C) (a : A) :
of_le (le_trans h1 h2) a = of_le h2 (of_le h1 a) := by simp
lemma of_le_continuous {A B : discrete_quotient X} (h : A ≤ B) :
continuous (of_le h) := continuous_of_discrete_topology
@[simp]
lemma of_le_proj {A B : discrete_quotient X} (h : A ≤ B) :
of_le h ∘ A.proj = B.proj := by { ext, exact quotient.sound' (B.refl _) }
@[simp]
lemma of_le_proj_apply {A B : discrete_quotient X} (h : A ≤ B) (x : X) :
of_le h (A.proj x) = B.proj x := by { change (of_le h ∘ A.proj) x = _, simp }
end of_le
/--
When X is discrete, there is a `semilattice_inf_bot` instance on `discrete_quotient X`
-/
instance [discrete_topology X] : semilattice_inf_bot (discrete_quotient X) :=
{ bot :=
{ rel := (=),
equiv := eq_equivalence,
clopen := λ x, is_clopen_discrete _ },
bot_le := by { rintro S a b (h : a = b), rw h, exact S.refl _ },
..(infer_instance : semilattice_inf _) }
lemma proj_bot_injective [discrete_topology X] :
function.injective (⊥ : discrete_quotient X).proj := λ a b h, quotient.exact' h
lemma proj_bot_bijective [discrete_topology X] :
function.bijective (⊥ : discrete_quotient X).proj := ⟨proj_bot_injective, proj_surjective _⟩
section map
variables {Y : Type*} [topological_space Y] {f : Y → X}
(cont : continuous f) (A : discrete_quotient Y) (B : discrete_quotient X)
/--
Given `cont : continuous f`, `le_comap cont A B` is defined as `A ≤ B.comap f`.
Mathematically this means that `f` descends to a morphism `A → B`.
-/
def le_comap : Prop := A ≤ B.comap cont
variables {cont A B}
lemma le_comap_id (A : discrete_quotient X) : le_comap continuous_id A A := by tauto
lemma le_comap_comp {Z : Type*} [topological_space Z] {g : Z → Y} {cont' : continuous g}
{C : discrete_quotient Z} : le_comap cont' C A → le_comap cont A B →
le_comap (continuous.comp cont cont') C B := by tauto
lemma le_comap_trans {C : discrete_quotient X} :
le_comap cont A B → B ≤ C → le_comap cont A C := λ h1 h2, le_trans h1 $ comap_mono _ h2
/-- Map a discrete quotient along a continuous map. -/
def map (cond : le_comap cont A B) : A → B := quotient.map' f cond
lemma map_continuous (cond : le_comap cont A B) : continuous (map cond) :=
continuous_of_discrete_topology
@[simp]
lemma map_proj (cond : le_comap cont A B) : map cond ∘ A.proj = B.proj ∘ f := rfl
@[simp]
lemma map_proj_apply (cond : le_comap cont A B) (y : Y) : map cond (A.proj y) = B.proj (f y) := rfl
@[simp]
lemma map_id : map (le_comap_id A) = id := by { ext ⟨⟩, refl }
@[simp]
lemma map_comp {Z : Type*} [topological_space Z] {g : Z → Y} {cont' : continuous g}
{C : discrete_quotient Z} (h1 : le_comap cont' C A) (h2 : le_comap cont A B) :
map (le_comap_comp h1 h2) = map h2 ∘ map h1 := by { ext ⟨⟩, refl }
@[simp]
lemma of_le_map {C : discrete_quotient X} (cond : le_comap cont A B) (h : B ≤ C) :
map (le_comap_trans cond h) = of_le h ∘ map cond := by { ext ⟨⟩, refl }
@[simp]
lemma of_le_map_apply {C : discrete_quotient X} (cond : le_comap cont A B) (h : B ≤ C) (a : A) :
map (le_comap_trans cond h) a = of_le h (map cond a) := by { rcases a, refl }
@[simp]
lemma map_of_le {C : discrete_quotient Y} (cond : le_comap cont A B) (h : C ≤ A) :
map (le_trans h cond) = map cond ∘ of_le h := by { ext ⟨⟩, refl }
@[simp]
lemma map_of_le_apply {C : discrete_quotient Y} (cond : le_comap cont A B) (h : C ≤ A) (c : C) :
map (le_trans h cond) c = map cond (of_le h c) := by { rcases c, refl }
end map
lemma eq_of_proj_eq [t2_space X] [compact_space X] [disc : totally_disconnected_space X]
{x y : X} : (∀ Q : discrete_quotient X, Q.proj x = Q.proj y) → x = y :=
begin
intro h,
change x ∈ ({y} : set X),
rw totally_disconnected_space_iff_connected_component_singleton at disc,
rw [← disc y, connected_component_eq_Inter_clopen],
rintros U ⟨⟨U, hU1, hU2⟩, rfl⟩,
replace h : _ ∨ _ := quotient.exact' (h (of_clopen hU1)),
tauto,
end
lemma fiber_le_of_le {A B : discrete_quotient X} (h : A ≤ B) (a : A) :
A.proj ⁻¹' {a} ≤ B.proj ⁻¹' {of_le h a} :=
begin
induction a,
erw [fiber_eq, fiber_eq],
tidy,
end
lemma exists_of_compat [compact_space X] (Qs : Π (Q : discrete_quotient X), Q)
(compat : ∀ (A B : discrete_quotient X) (h : A ≤ B), of_le h (Qs _) = Qs _) :
∃ x : X, ∀ Q : discrete_quotient X, Q.proj x = Qs _ :=
begin
obtain ⟨x,hx⟩ := is_compact.nonempty_Inter_of_directed_nonempty_compact_closed
(λ (Q : discrete_quotient X), Q.proj ⁻¹' {Qs _}) (λ A B, _) (λ i, _)
(λ i, (fiber_closed _ _).is_compact) (λ i, fiber_closed _ _),
{ refine ⟨x, λ Q, _⟩,
specialize hx _ ⟨Q,rfl⟩,
dsimp at hx,
rcases proj_surjective _ (Qs Q) with ⟨y,hy⟩,
rw ← hy at *,
rw fiber_eq at hx,
exact quotient.sound' (Q.symm y x hx) },
{ refine ⟨A ⊓ B, λ a ha, _, λ a ha, _⟩,
{ dsimp only,
erw ← compat (A ⊓ B) A inf_le_left,
exact fiber_le_of_le _ _ ha },
{ dsimp only,
erw ← compat (A ⊓ B) B inf_le_right,
exact fiber_le_of_le _ _ ha } },
{ obtain ⟨x,hx⟩ := i.proj_surjective (Qs i),
refine ⟨x,_⟩,
dsimp only,
rw [← hx, fiber_eq],
apply i.refl },
end
noncomputable instance [compact_space X] : fintype S :=
begin
have cond : is_compact (⊤ : set X) := compact_univ,
rw is_compact_iff_finite_subcover at cond,
have h := @cond S (λ s, S.proj ⁻¹' {s}) (λ s, fiber_open _ _)
(λ x hx, ⟨S.proj ⁻¹' {S.proj x}, ⟨S.proj x, rfl⟩, rfl⟩),
let T := classical.some h,
have hT := classical.some_spec h,
refine ⟨T,λ s, _⟩,
rcases S.proj_surjective s with ⟨x,rfl⟩,
rcases hT (by tauto : x ∈ ⊤) with ⟨j, ⟨j,rfl⟩, h1, ⟨hj, rfl⟩, h2⟩,
dsimp only at h2,
suffices : S.proj x = j, by rwa this,
rcases j with ⟨j⟩,
apply quotient.sound',
erw fiber_eq at h2,
exact S.symm _ _ h2
end
end discrete_quotient
namespace locally_constant
variables {X} {α : Type*} (f : locally_constant X α)
/-- Any locally constant function induces a discrete quotient. -/
def discrete_quotient : discrete_quotient X :=
{ rel := λ a b, f b = f a,
equiv := ⟨by tauto, by tauto, λ a b c h1 h2, by rw [h2, h1]⟩,
clopen := λ x, f.is_locally_constant.is_clopen_fiber _ }
/-- The function from the discrete quotient associated to a locally constant function. -/
def lift : f.discrete_quotient → α := λ a, quotient.lift_on' a f (λ a b h, h.symm)
lemma lift_is_locally_constant : _root_.is_locally_constant f.lift := λ A, trivial
/-- A locally constant version of `locally_constant.lift`. -/
def locally_constant_lift : locally_constant f.discrete_quotient α :=
⟨f.lift, f.lift_is_locally_constant⟩
@[simp]
lemma lift_eq_coe : f.lift = f.locally_constant_lift := rfl
@[simp]
lemma factors : f.locally_constant_lift ∘ f.discrete_quotient.proj = f := by { ext, refl }
end locally_constant
|
f5136a5e1c3cbcc2bec6495171fc4b4cecc3f108 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/ring_theory/trace.lean | 31f854f1320c6834ab6ab55ee3c9344f224ebb67 | [
"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 | 22,432 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import linear_algebra.matrix.bilinear_form
import linear_algebra.matrix.charpoly.minpoly
import linear_algebra.determinant
import linear_algebra.finite_dimensional
import linear_algebra.vandermonde
import linear_algebra.trace
import field_theory.is_alg_closed.algebraic_closure
import field_theory.primitive_element
import field_theory.galois
import ring_theory.power_basis
/-!
# Trace for (finite) ring extensions.
Suppose we have an `R`-algebra `S` with a finite basis. For each `s : S`,
the trace of the linear map given by multiplying by `s` gives information about
the roots of the minimal polynomial of `s` over `R`.
## Main definitions
* `algebra.trace R S x`: the trace of an element `s` of an `R`-algebra `S`
* `algebra.trace_form R S`: bilinear form sending `x`, `y` to the trace of `x * y`
* `algebra.trace_matrix R b`: the matrix whose `(i j)`-th element is the trace of `b i * b j`.
* `algebra.embeddings_matrix A C b : matrix κ (B →ₐ[A] C) C` is the matrix whose
`(i, σ)` coefficient is `σ (b i)`.
* `algebra.embeddings_matrix_reindex A C b e : matrix κ κ C` is the matrix whose `(i, j)`
coefficient is `σⱼ (b i)`, where `σⱼ : B →ₐ[A] C` is the embedding corresponding to `j : κ`
given by a bijection `e : κ ≃ (B →ₐ[A] C)`.
## Main results
* `trace_algebra_map_of_basis`, `trace_algebra_map`: if `x : K`, then `Tr_{L/K} x = [L : K] x`
* `trace_trace_of_basis`, `trace_trace`: `Tr_{L/K} (Tr_{F/L} x) = Tr_{F/K} x`
* `trace_eq_sum_roots`: the trace of `x : K(x)` is the sum of all conjugate roots of `x`
* `trace_eq_sum_embeddings`: the trace of `x : K(x)` is the sum of all embeddings of `x` into an
algebraically closed field
* `trace_form_nondegenerate`: the trace form over a separable extension is a nondegenerate
bilinear form
## Implementation notes
Typically, the trace is defined specifically for finite field extensions.
The definition is as general as possible and the assumption that we have
fields or that the extension is finite is added to the lemmas as needed.
We only define the trace for left multiplication (`algebra.left_mul_matrix`,
i.e. `algebra.lmul_left`).
For now, the definitions assume `S` is commutative, so the choice doesn't matter anyway.
## References
* https://en.wikipedia.org/wiki/Field_trace
-/
universes u v w z
variables {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T]
variables [algebra R S] [algebra R T]
variables {K L : Type*} [field K] [field L] [algebra K L]
variables {ι κ : Type w} [fintype ι]
open finite_dimensional
open linear_map
open matrix
open_locale big_operators
open_locale matrix
namespace algebra
variables (b : basis ι R S)
variables (R S)
/-- The trace of an element `s` of an `R`-algebra is the trace of `(*) s`,
as an `R`-linear map. -/
noncomputable def trace : S →ₗ[R] R :=
(linear_map.trace R S).comp (lmul R S).to_linear_map
variables {S}
-- Not a `simp` lemma since there are more interesting ways to rewrite `trace R S x`,
-- for example `trace_trace`
lemma trace_apply (x) : trace R S x = linear_map.trace R S (lmul R S x) := rfl
lemma trace_eq_zero_of_not_exists_basis
(h : ¬ ∃ (s : finset S), nonempty (basis s R S)) : trace R S = 0 :=
by { ext s, simp [trace_apply, linear_map.trace, h] }
include b
variables {R}
-- Can't be a `simp` lemma because it depends on a choice of basis
lemma trace_eq_matrix_trace [decidable_eq ι] (b : basis ι R S) (s : S) :
trace R S s = matrix.trace (algebra.left_mul_matrix b s) :=
by rw [trace_apply, linear_map.trace_eq_matrix_trace _ b, to_matrix_lmul_eq]
/-- If `x` is in the base field `K`, then the trace is `[L : K] * x`. -/
lemma trace_algebra_map_of_basis (x : R) :
trace R S (algebra_map R S x) = fintype.card ι • x :=
begin
haveI := classical.dec_eq ι,
rw [trace_apply, linear_map.trace_eq_matrix_trace R b, matrix.trace],
convert finset.sum_const _,
ext i,
simp,
end
omit b
/-- If `x` is in the base field `K`, then the trace is `[L : K] * x`.
(If `L` is not finite-dimensional over `K`, then `trace` and `finrank` return `0`.)
-/
@[simp]
lemma trace_algebra_map (x : K) : trace K L (algebra_map K L x) = finrank K L • x :=
begin
by_cases H : ∃ (s : finset L), nonempty (basis s K L),
{ rw [trace_algebra_map_of_basis H.some_spec.some, finrank_eq_card_basis H.some_spec.some] },
{ simp [trace_eq_zero_of_not_exists_basis K H, finrank_eq_zero_of_not_exists_basis_finset H] }
end
lemma trace_trace_of_basis [algebra S T] [is_scalar_tower R S T]
{ι κ : Type*} [fintype ι] [fintype κ]
(b : basis ι R S) (c : basis κ S T) (x : T) :
trace R S (trace S T x) = trace R T x :=
begin
haveI := classical.dec_eq ι,
haveI := classical.dec_eq κ,
rw [trace_eq_matrix_trace (b.smul c), trace_eq_matrix_trace b, trace_eq_matrix_trace c,
matrix.trace, matrix.trace, matrix.trace,
← finset.univ_product_univ, finset.sum_product],
refine finset.sum_congr rfl (λ i _, _),
simp only [alg_hom.map_sum, smul_left_mul_matrix, finset.sum_apply, matrix.diag,
-- The unifier is not smart enough to apply this one by itself:
finset.sum_apply i _ (λ y, left_mul_matrix b (left_mul_matrix c x y y))]
end
lemma trace_comp_trace_of_basis [algebra S T] [is_scalar_tower R S T]
{ι κ : Type*} [fintype ι] [fintype κ]
(b : basis ι R S) (c : basis κ S T) :
(trace R S).comp ((trace S T).restrict_scalars R) = trace R T :=
by { ext, rw [linear_map.comp_apply, linear_map.restrict_scalars_apply, trace_trace_of_basis b c] }
@[simp]
lemma trace_trace [algebra K T] [algebra L T] [is_scalar_tower K L T]
[finite_dimensional K L] [finite_dimensional L T] (x : T) :
trace K L (trace L T x) = trace K T x :=
trace_trace_of_basis (basis.of_vector_space K L) (basis.of_vector_space L T) x
@[simp]
lemma trace_comp_trace [algebra K T] [algebra L T] [is_scalar_tower K L T]
[finite_dimensional K L] [finite_dimensional L T] :
(trace K L).comp ((trace L T).restrict_scalars K) = trace K T :=
by { ext, rw [linear_map.comp_apply, linear_map.restrict_scalars_apply, trace_trace] }
section trace_form
variables (R S)
/-- The `trace_form` maps `x y : S` to the trace of `x * y`.
It is a symmetric bilinear form and is nondegenerate if the extension is separable. -/
noncomputable def trace_form : bilin_form R S :=
(linear_map.compr₂ (lmul R S).to_linear_map (trace R S)).to_bilin
variables {S}
-- This is a nicer lemma than the one produced by `@[simps] def trace_form`.
@[simp] lemma trace_form_apply (x y : S) : trace_form R S x y = trace R S (x * y) := rfl
lemma trace_form_is_symm : (trace_form R S).is_symm :=
λ x y, congr_arg (trace R S) (mul_comm _ _)
lemma trace_form_to_matrix [decidable_eq ι] (i j) :
bilin_form.to_matrix b (trace_form R S) i j = trace R S (b i * b j) :=
by rw [bilin_form.to_matrix_apply, trace_form_apply]
lemma trace_form_to_matrix_power_basis (h : power_basis R S) :
bilin_form.to_matrix h.basis (trace_form R S) = of (λ i j, trace R S (h.gen ^ (↑i + ↑j : ℕ))) :=
by { ext, rw [trace_form_to_matrix, of_apply, pow_add, h.basis_eq_pow, h.basis_eq_pow] }
end trace_form
end algebra
section eq_sum_roots
open algebra polynomial
variables {F : Type*} [field F]
variables [algebra K S] [algebra K F]
/-- Given `pb : power_basis K S`, the trace of `pb.gen` is `-(minpoly K pb.gen).next_coeff`. -/
lemma power_basis.trace_gen_eq_next_coeff_minpoly [nontrivial S] (pb : power_basis K S) :
algebra.trace K S pb.gen = -(minpoly K pb.gen).next_coeff :=
begin
have d_pos : 0 < pb.dim := power_basis.dim_pos pb,
have d_pos' : 0 < (minpoly K pb.gen).nat_degree, { simpa },
haveI : nonempty (fin pb.dim) := ⟨⟨0, d_pos⟩⟩,
rw [trace_eq_matrix_trace pb.basis, trace_eq_neg_charpoly_coeff, charpoly_left_mul_matrix,
← pb.nat_degree_minpoly, fintype.card_fin, ← next_coeff_of_pos_nat_degree _ d_pos']
end
/-- Given `pb : power_basis K S`, then the trace of `pb.gen` is
`((minpoly K pb.gen).map (algebra_map K F)).roots.sum`. -/
lemma power_basis.trace_gen_eq_sum_roots [nontrivial S] (pb : power_basis K S)
(hf : (minpoly K pb.gen).splits (algebra_map K F)) :
algebra_map K F (trace K S pb.gen) =
((minpoly K pb.gen).map (algebra_map K F)).roots.sum :=
begin
rw [power_basis.trace_gen_eq_next_coeff_minpoly, ring_hom.map_neg, ← next_coeff_map
(algebra_map K F).injective, sum_roots_eq_next_coeff_of_monic_of_split
((minpoly.monic (power_basis.is_integral_gen _)).map _)
((splits_id_iff_splits _).2 hf), neg_neg]
end
namespace intermediate_field.adjoin_simple
open intermediate_field
lemma trace_gen_eq_zero {x : L} (hx : ¬ is_integral K x) :
algebra.trace K K⟮x⟯ (adjoin_simple.gen K x) = 0 :=
begin
rw [trace_eq_zero_of_not_exists_basis, linear_map.zero_apply],
contrapose! hx,
obtain ⟨s, ⟨b⟩⟩ := hx,
refine is_integral_of_mem_of_fg (K⟮x⟯).to_subalgebra _ x _,
{ exact (submodule.fg_iff_finite_dimensional _).mpr (finite_dimensional.of_finset_basis b) },
{ exact subset_adjoin K _ (set.mem_singleton x) }
end
lemma trace_gen_eq_sum_roots (x : L)
(hf : (minpoly K x).splits (algebra_map K F)) :
algebra_map K F (trace K K⟮x⟯ (adjoin_simple.gen K x)) =
((minpoly K x).map (algebra_map K F)).roots.sum :=
begin
have injKxL := (algebra_map K⟮x⟯ L).injective,
by_cases hx : is_integral K x, swap,
{ simp [minpoly.eq_zero hx, trace_gen_eq_zero hx], },
have hx' : is_integral K (adjoin_simple.gen K x),
{ rwa [← is_integral_algebra_map_iff injKxL, adjoin_simple.algebra_map_gen],
apply_instance },
rw [← adjoin.power_basis_gen hx, (adjoin.power_basis hx).trace_gen_eq_sum_roots];
rw [adjoin.power_basis_gen hx, minpoly.eq_of_algebra_map_eq injKxL hx'];
try { simp only [adjoin_simple.algebra_map_gen _ _] },
exact hf
end
end intermediate_field.adjoin_simple
open intermediate_field
variables (K)
lemma trace_eq_trace_adjoin [finite_dimensional K L] (x : L) :
algebra.trace K L x = finrank K⟮x⟯ L • trace K K⟮x⟯ (adjoin_simple.gen K x) :=
begin
rw ← @trace_trace _ _ K K⟮x⟯ _ _ _ _ _ _ _ _ x,
conv in x { rw ← intermediate_field.adjoin_simple.algebra_map_gen K x },
rw [trace_algebra_map, linear_map.map_smul_of_tower],
end
variables {K}
lemma trace_eq_sum_roots [finite_dimensional K L]
{x : L} (hF : (minpoly K x).splits (algebra_map K F)) :
algebra_map K F (algebra.trace K L x) =
finrank K⟮x⟯ L • ((minpoly K x).map (algebra_map K _)).roots.sum :=
by rw [trace_eq_trace_adjoin K x, algebra.smul_def, ring_hom.map_mul, ← algebra.smul_def,
intermediate_field.adjoin_simple.trace_gen_eq_sum_roots _ hF, is_scalar_tower.algebra_map_smul]
end eq_sum_roots
variables {F : Type*} [field F]
variables [algebra R L] [algebra L F] [algebra R F] [is_scalar_tower R L F]
open polynomial
lemma algebra.is_integral_trace [finite_dimensional L F] {x : F} (hx : _root_.is_integral R x) :
_root_.is_integral R (algebra.trace L F x) :=
begin
have hx' : _root_.is_integral L x := is_integral_of_is_scalar_tower _ hx,
rw [← is_integral_algebra_map_iff (algebra_map L (algebraic_closure F)).injective,
trace_eq_sum_roots],
{ refine (is_integral.multiset_sum _).nsmul _,
intros y hy,
rw mem_roots_map (minpoly.ne_zero hx') at hy,
use [minpoly R x, minpoly.monic hx],
rw ← aeval_def at ⊢ hy,
exact minpoly.aeval_of_is_scalar_tower R x y hy },
{ apply is_alg_closed.splits_codomain },
{ apply_instance }
end
section eq_sum_embeddings
variables [algebra K F] [is_scalar_tower K L F]
open algebra intermediate_field
variables (F) (E : Type*) [field E] [algebra K E]
lemma trace_eq_sum_embeddings_gen
(pb : power_basis K L)
(hE : (minpoly K pb.gen).splits (algebra_map K E)) (hfx : (minpoly K pb.gen).separable) :
algebra_map K E (algebra.trace K L pb.gen) =
(@@finset.univ (power_basis.alg_hom.fintype pb)).sum (λ σ, σ pb.gen) :=
begin
letI := classical.dec_eq E,
rw [pb.trace_gen_eq_sum_roots hE, fintype.sum_equiv pb.lift_equiv', finset.sum_mem_multiset,
finset.sum_eq_multiset_sum, multiset.to_finset_val,
multiset.dedup_eq_self.mpr _, multiset.map_id],
{ exact nodup_roots ((separable_map _).mpr hfx) },
{ intro x, refl },
{ intro σ, rw [power_basis.lift_equiv'_apply_coe, id.def] }
end
variables [is_alg_closed E]
lemma sum_embeddings_eq_finrank_mul [finite_dimensional K F] [is_separable K F]
(pb : power_basis K L) :
∑ σ : F →ₐ[K] E, σ (algebra_map L F pb.gen) =
finrank L F • (@@finset.univ (power_basis.alg_hom.fintype pb)).sum
(λ σ : L →ₐ[K] E, σ pb.gen) :=
begin
haveI : finite_dimensional L F := finite_dimensional.right K L F,
haveI : is_separable L F := is_separable_tower_top_of_is_separable K L F,
letI : fintype (L →ₐ[K] E) := power_basis.alg_hom.fintype pb,
letI : ∀ (f : L →ₐ[K] E), fintype (@@alg_hom L F E _ _ _ _ f.to_ring_hom.to_algebra) :=
_, -- will be solved by unification
rw [fintype.sum_equiv alg_hom_equiv_sigma (λ (σ : F →ₐ[K] E), _) (λ σ, σ.1 pb.gen),
← finset.univ_sigma_univ, finset.sum_sigma, ← finset.sum_nsmul],
refine finset.sum_congr rfl (λ σ _, _),
{ letI : algebra L E := σ.to_ring_hom.to_algebra,
simp only [finset.sum_const, finset.card_univ],
rw alg_hom.card L F E },
{ intros σ,
simp only [alg_hom_equiv_sigma, equiv.coe_fn_mk, alg_hom.restrict_domain, alg_hom.comp_apply,
is_scalar_tower.coe_to_alg_hom'] }
end
lemma trace_eq_sum_embeddings [finite_dimensional K L] [is_separable K L]
{x : L} : algebra_map K E (algebra.trace K L x) = ∑ σ : L →ₐ[K] E, σ x :=
begin
have hx := is_separable.is_integral K x,
rw [trace_eq_trace_adjoin K x, algebra.smul_def, ring_hom.map_mul, ← adjoin.power_basis_gen hx,
trace_eq_sum_embeddings_gen E (adjoin.power_basis hx) (is_alg_closed.splits_codomain _),
← algebra.smul_def, algebra_map_smul],
{ exact (sum_embeddings_eq_finrank_mul L E (adjoin.power_basis hx)).symm },
{ haveI := is_separable_tower_bot_of_is_separable K K⟮x⟯ L,
exact is_separable.separable K _ }
end
lemma trace_eq_sum_automorphisms (x : L) [finite_dimensional K L] [is_galois K L] :
algebra_map K L (algebra.trace K L x) = ∑ (σ : L ≃ₐ[K] L), σ x :=
begin
apply no_zero_smul_divisors.algebra_map_injective L (algebraic_closure L),
rw map_sum (algebra_map L (algebraic_closure L)),
rw ← fintype.sum_equiv (normal.alg_hom_equiv_aut K (algebraic_closure L) L),
{ rw ←trace_eq_sum_embeddings (algebraic_closure L),
{ simp only [algebra_map_eq_smul_one, smul_one_smul] },
{ exact is_galois.to_is_separable } },
{ intro σ,
simp only [normal.alg_hom_equiv_aut, alg_hom.restrict_normal', equiv.coe_fn_mk,
alg_equiv.coe_of_bijective, alg_hom.restrict_normal_commutes, id.map_eq_id,
ring_hom.id_apply] },
end
end eq_sum_embeddings
section det_ne_zero
namespace algebra
variables (A : Type u) {B : Type v} (C : Type z)
variables [comm_ring A] [comm_ring B] [algebra A B] [comm_ring C] [algebra A C]
open finset
/-- Given an `A`-algebra `B` and `b`, an `κ`-indexed family of elements of `B`, we define
`trace_matrix A b` as the matrix whose `(i j)`-th element is the trace of `b i * b j`. -/
@[simp] noncomputable
def trace_matrix (b : κ → B) : matrix κ κ A
| i j := trace_form A B (b i) (b j)
lemma trace_matrix_def (b : κ → B) : trace_matrix A b = of (λ i j, trace_form A B (b i) (b j)) :=
rfl
lemma trace_matrix_reindex {κ' : Type*} (b : basis κ A B) (f : κ ≃ κ') :
trace_matrix A (b.reindex f) = reindex f f (trace_matrix A b) :=
by {ext x y, simp}
variables {A}
lemma trace_matrix_of_matrix_vec_mul [fintype κ] (b : κ → B) (P : matrix κ κ A) :
trace_matrix A ((P.map (algebra_map A B)).vec_mul b) = Pᵀ ⬝ (trace_matrix A b) ⬝ P :=
begin
ext α β,
rw [trace_matrix, vec_mul, dot_product, vec_mul, dot_product, matrix.mul_apply,
bilin_form.sum_left, fintype.sum_congr _ _ (λ (i : κ), @bilin_form.sum_right _ _ _ _ _ _ _ _
(b i * P.map (algebra_map A B) i α) (λ (y : κ), b y * P.map (algebra_map A B) y β)), sum_comm],
congr, ext x,
rw [matrix.mul_apply, sum_mul],
congr, ext y,
rw [map_apply, trace_form_apply, mul_comm (b y), ← smul_def],
simp only [id.smul_eq_mul, ring_hom.id_apply, map_apply, transpose_apply, linear_map.map_smulₛₗ,
trace_form_apply, algebra.smul_mul_assoc],
rw [mul_comm (b x), ← smul_def],
ring_nf,
simp [mul_comm],
end
lemma trace_matrix_of_matrix_mul_vec [fintype κ] (b : κ → B) (P : matrix κ κ A) :
trace_matrix A ((P.map (algebra_map A B)).mul_vec b) = P ⬝ (trace_matrix A b) ⬝ Pᵀ :=
begin
refine add_equiv.injective transpose_add_equiv _,
rw [transpose_add_equiv_apply, transpose_add_equiv_apply, ← vec_mul_transpose,
← transpose_map, trace_matrix_of_matrix_vec_mul, transpose_transpose, transpose_mul,
transpose_transpose, transpose_mul]
end
lemma trace_matrix_of_basis [fintype κ] [decidable_eq κ] (b : basis κ A B) :
trace_matrix A b = bilin_form.to_matrix b (trace_form A B) :=
begin
ext i j,
rw [trace_matrix, trace_form_apply, trace_form_to_matrix]
end
lemma trace_matrix_of_basis_mul_vec (b : basis ι A B) (z : B) :
(trace_matrix A b).mul_vec (b.equiv_fun z) = (λ i, trace A B (z * (b i))) :=
begin
ext i,
rw [← col_apply ((trace_matrix A b).mul_vec (b.equiv_fun z)) i unit.star, col_mul_vec,
matrix.mul_apply, trace_matrix_def],
simp only [col_apply, trace_form_apply],
conv_lhs
{ congr, skip, funext,
rw [mul_comm _ (b.equiv_fun z _), ← smul_eq_mul, of_apply, ← linear_map.map_smul] },
rw [← linear_map.map_sum],
congr,
conv_lhs
{ congr, skip, funext,
rw [← mul_smul_comm] },
rw [← finset.mul_sum, mul_comm z],
congr,
rw [b.sum_equiv_fun ]
end
variable (A)
/-- `embeddings_matrix A C b : matrix κ (B →ₐ[A] C) C` is the matrix whose `(i, σ)` coefficient is
`σ (b i)`. It is mostly useful for fields when `fintype.card κ = finrank A B` and `C` is
algebraically closed. -/
@[simp] def embeddings_matrix (b : κ → B) : matrix κ (B →ₐ[A] C) C
| i σ := σ (b i)
/-- `embeddings_matrix_reindex A C b e : matrix κ κ C` is the matrix whose `(i, j)` coefficient
is `σⱼ (b i)`, where `σⱼ : B →ₐ[A] C` is the embedding corresponding to `j : κ` given by a
bijection `e : κ ≃ (B →ₐ[A] C)`. It is mostly useful for fields and `C` is algebraically closed.
In this case, in presence of `h : fintype.card κ = finrank A B`, one can take
`e := equiv_of_card_eq ((alg_hom.card A B C).trans h.symm)`. -/
def embeddings_matrix_reindex (b : κ → B) (e : κ ≃ (B →ₐ[A] C)) :=
reindex (equiv.refl κ) e.symm (embeddings_matrix A C b)
variable {A}
lemma embeddings_matrix_reindex_eq_vandermonde (pb : power_basis A B)
(e : fin pb.dim ≃ (B →ₐ[A] C)) :
embeddings_matrix_reindex A C pb.basis e = (vandermonde (λ i, e i pb.gen))ᵀ :=
by { ext i j, simp [embeddings_matrix_reindex, embeddings_matrix] }
section field
variables (K) {L} (E : Type z) [field E]
variables [algebra K E]
variables [module.finite K L] [is_separable K L] [is_alg_closed E]
variables (b : κ → L) (pb : power_basis K L)
lemma trace_matrix_eq_embeddings_matrix_mul_trans :
(trace_matrix K b).map (algebra_map K E) =
(embeddings_matrix K E b) ⬝ (embeddings_matrix K E b)ᵀ :=
by { ext i j, simp [trace_eq_sum_embeddings, embeddings_matrix, matrix.mul_apply] }
lemma trace_matrix_eq_embeddings_matrix_reindex_mul_trans [fintype κ]
(e : κ ≃ (L →ₐ[K] E)) : (trace_matrix K b).map (algebra_map K E) =
(embeddings_matrix_reindex K E b e) ⬝ (embeddings_matrix_reindex K E b e)ᵀ :=
by rw [trace_matrix_eq_embeddings_matrix_mul_trans, embeddings_matrix_reindex, reindex_apply,
transpose_minor, ← minor_mul_transpose_minor, ← equiv.coe_refl, equiv.refl_symm]
end field
end algebra
open algebra
variables (pb : power_basis K L)
lemma det_trace_matrix_ne_zero' [is_separable K L] :
det (trace_matrix K pb.basis) ≠ 0 :=
begin
suffices : algebra_map K (algebraic_closure L) (det (trace_matrix K pb.basis)) ≠ 0,
{ refine mt (λ ht, _) this,
rw [ht, ring_hom.map_zero] },
haveI : finite_dimensional K L := pb.finite_dimensional,
let e : fin pb.dim ≃ (L →ₐ[K] algebraic_closure L) := (fintype.equiv_fin_of_card_eq _).symm,
rw [ring_hom.map_det, ring_hom.map_matrix_apply,
trace_matrix_eq_embeddings_matrix_reindex_mul_trans K _ _ e,
embeddings_matrix_reindex_eq_vandermonde, det_mul, det_transpose],
refine mt mul_self_eq_zero.mp _,
{ simp only [det_vandermonde, finset.prod_eq_zero_iff, not_exists, sub_eq_zero],
intros i _ j hij h,
exact (finset.mem_Ioi.mp hij).ne' (e.injective $ pb.alg_hom_ext h) },
{ rw [alg_hom.card, pb.finrank] }
end
lemma det_trace_form_ne_zero [is_separable K L] [decidable_eq ι] (b : basis ι K L) :
det (bilin_form.to_matrix b (trace_form K L)) ≠ 0 :=
begin
haveI : finite_dimensional K L := finite_dimensional.of_fintype_basis b,
let pb : power_basis K L := field.power_basis_of_finite_of_separable _ _,
rw [← bilin_form.to_matrix_mul_basis_to_matrix pb.basis b,
← det_comm' (pb.basis.to_matrix_mul_to_matrix_flip b) _,
← matrix.mul_assoc, det_mul],
swap, { apply basis.to_matrix_mul_to_matrix_flip },
refine mul_ne_zero
(is_unit_of_mul_eq_one _ ((b.to_matrix pb.basis)ᵀ ⬝ b.to_matrix pb.basis).det _).ne_zero
_,
{ calc (pb.basis.to_matrix b ⬝ (pb.basis.to_matrix b)ᵀ).det *
((b.to_matrix pb.basis)ᵀ ⬝ b.to_matrix pb.basis).det
= (pb.basis.to_matrix b ⬝ (b.to_matrix pb.basis ⬝ pb.basis.to_matrix b)ᵀ ⬝
b.to_matrix pb.basis).det
: by simp only [← det_mul, matrix.mul_assoc, matrix.transpose_mul]
... = 1 : by simp only [basis.to_matrix_mul_to_matrix_flip, matrix.transpose_one,
matrix.mul_one, matrix.det_one] },
simpa only [trace_matrix_of_basis] using det_trace_matrix_ne_zero' pb
end
variables (K L)
theorem trace_form_nondegenerate [finite_dimensional K L] [is_separable K L] :
(trace_form K L).nondegenerate :=
bilin_form.nondegenerate_of_det_ne_zero (trace_form K L) _
(det_trace_form_ne_zero (finite_dimensional.fin_basis K L))
end det_ne_zero
|
ff67d3998aa8d64d0376acd267e2d196e9bb3969 | 302c785c90d40ad3d6be43d33bc6a558354cc2cf | /src/algebra/continued_fractions/computation/terminates_iff_rat.lean | 398efe7ea889ee67bc663eb0408769f6797fefaf | [
"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 | 14,602 | lean | /-
Copyright (c) 2020 Kevin Kappelmann. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kevin Kappelmann
-/
import algebra.continued_fractions.computation.approximations
import algebra.continued_fractions.computation.correctness_terminating
import data.rat
/-!
# Termination of Continued Fraction Computations (`gcf.of`)
## Summary
We show that the continued fraction for a value `v`, as defined in
`algebra.continued_fractions.computation.basic`, terminates if and only if `v` corresponds to a
rational number, that is `↑v = q` for some `q : ℚ`.
## Main Theorems
- `generalized_continued_fraction.coe_of_rat` shows that
`generalized_continued_fraction.of v = generalized_continued_fraction.of q` for `v : α` given that
`↑v = q` and `q : ℚ`.
- `generalized_continued_fraction.terminates_iff_rat` shows that
`generalized_continued_fraction.of v` terminates if and only if `↑v = q` for some `q : ℚ`.
## Tags
rational, continued fraction, termination
-/
namespace generalized_continued_fraction
open generalized_continued_fraction as gcf
variables {K : Type*} [linear_ordered_field K] [floor_ring K]
/-
We will have to constantly coerce along our structures in the following proofs using their provided
map functions.
-/
local attribute [simp] gcf.pair.map gcf.int_fract_pair.mapFr
section rat_of_terminates
/-!
### Terminating Continued Fractions Are Rational
We want to show that the computation of a continued fraction `generalized_continued_fraction.of v`
terminates if and only if `v ∈ ℚ`. In this section, we show the implication from left to right.
We first show that every finite convergent corresponds to a rational number `q` and then use the
finite correctness proof (`of_correctness_of_terminates`) of `generalized_continued_fraction.of` to
show that `v = ↑q`.
-/
variables (v : K) (n : ℕ)
lemma exists_gcf_pair_rat_eq_of_nth_conts_aux :
∃ (conts : gcf.pair ℚ), (gcf.of v).continuants_aux n = (conts.map coe : gcf.pair K) :=
nat.strong_induction_on n
begin
clear n,
let g := gcf.of v,
assume n IH,
rcases n with _|_|n,
-- n = 0
{ suffices : ∃ (gp : gcf.pair ℚ), gcf.pair.mk (1 : K) 0 = gp.map coe, by simpa [continuants_aux],
use (gcf.pair.mk 1 0),
simp },
-- n = 1
{ suffices : ∃ (conts : gcf.pair ℚ), gcf.pair.mk g.h 1 = conts.map coe, by
simpa [continuants_aux],
use (gcf.pair.mk ⌊v⌋ 1),
simp },
-- 2 ≤ n
{ cases (IH (n + 1) $ lt_add_one (n + 1)) with pred_conts pred_conts_eq, -- invoke the IH
cases s_ppred_nth_eq : (g.s.nth n) with gp_n,
-- option.none
{ use pred_conts,
have : g.continuants_aux (n + 2) = g.continuants_aux (n + 1), from
continuants_aux_stable_of_terminated (n + 1).le_succ s_ppred_nth_eq,
simp only [this, pred_conts_eq] },
-- option.some
{ -- invoke the IH a second time
cases (IH n $ lt_of_le_of_lt (n.le_succ) $ lt_add_one $ n + 1)
with ppred_conts ppred_conts_eq,
obtain ⟨a_eq_one, z, b_eq_z⟩ : gp_n.a = 1 ∧ ∃ (z : ℤ), gp_n.b = (z : K), from
of_part_num_eq_one_and_exists_int_part_denom_eq s_ppred_nth_eq,
-- finally, unfold the recurrence to obtain the required rational value.
simp only [a_eq_one, b_eq_z,
(continuants_aux_recurrence s_ppred_nth_eq ppred_conts_eq pred_conts_eq)],
use (next_continuants 1 (z : ℚ) ppred_conts pred_conts),
cases ppred_conts, cases pred_conts,
simp [next_continuants, next_numerator, next_denominator] } }
end
lemma exists_gcf_pair_rat_eq_nth_conts :
∃ (conts : gcf.pair ℚ), (gcf.of v).continuants n = (conts.map coe : gcf.pair K) :=
by { rw [nth_cont_eq_succ_nth_cont_aux], exact (exists_gcf_pair_rat_eq_of_nth_conts_aux v $ n + 1) }
lemma exists_rat_eq_nth_numerator : ∃ (q : ℚ), (gcf.of v).numerators n = (q : K) :=
begin
rcases (exists_gcf_pair_rat_eq_nth_conts v n) with ⟨⟨a, _⟩, nth_cont_eq⟩,
use a,
simp [num_eq_conts_a, nth_cont_eq],
end
lemma exists_rat_eq_nth_denominator : ∃ (q : ℚ), (gcf.of v).denominators n = (q : K) :=
begin
rcases (exists_gcf_pair_rat_eq_nth_conts v n) with ⟨⟨_, b⟩, nth_cont_eq⟩,
use b,
simp [denom_eq_conts_b, nth_cont_eq]
end
/-- Every finite convergent corresponds to a rational number. -/
lemma exists_rat_eq_nth_convergent : ∃ (q : ℚ), (gcf.of v).convergents n = (q : K) :=
begin
rcases (exists_rat_eq_nth_numerator v n) with ⟨Aₙ, nth_num_eq⟩,
rcases (exists_rat_eq_nth_denominator v n) with ⟨Bₙ, nth_denom_eq⟩,
use (Aₙ / Bₙ),
simp [nth_num_eq, nth_denom_eq, convergent_eq_num_div_denom]
end
variable {v}
/-- Every terminating continued fraction corresponds to a rational number. -/
theorem exists_rat_eq_of_terminates (terminates : (gcf.of v).terminates) : ∃ (q : ℚ), v = ↑q :=
begin
obtain ⟨n, v_eq_conv⟩ : ∃ n, v = (gcf.of v).convergents n, from
of_correctness_of_terminates terminates,
obtain ⟨q, conv_eq_q⟩ : ∃ (q : ℚ), (gcf.of v).convergents n = (↑q : K), from
exists_rat_eq_nth_convergent v n,
have : v = (↑q : K), from eq.trans v_eq_conv conv_eq_q,
use [q, this]
end
end rat_of_terminates
section rat_translation
/-!
### Technical Translation Lemmas
Before we can show that the continued fraction of a rational number terminates, we have to prove
some technical translation lemmas. More precisely, in this section, we show that, given a rational
number `q : ℚ` and value `v : K` with `v = ↑q`, the continued fraction of `q` and `v` coincide.
In particular, we show that
```lean
(↑(generalized_continued_fraction.of q : generalized_continued_fraction ℚ)
: generalized_continued_fraction K)
= generalized_continued_fraction.of v`
```
in `generalized_continued_fraction.coe_of_rat`.
To do this, we proceed bottom-up, showing the correspondence between the basic functions involved in
the computation first and then lift the results step-by-step.
-/
/- The lifting works for arbitrary linear ordered, archimedean fields with a floor function. -/
variables [archimedean K] {v : K} {q : ℚ} (v_eq_q : v = (↑q : K)) (n : ℕ)
include v_eq_q
/-! First, we show the correspondence for the very basic functions in
`generalized_continued_fraction.int_fract_pair`. -/
namespace int_fract_pair
lemma coe_of_rat_eq :
((int_fract_pair.of q).mapFr coe : int_fract_pair K) = int_fract_pair.of v :=
suffices ⌊q⌋ = ⌊(↑q : K)⌋, by simpa [int_fract_pair.of, v_eq_q, fract],
by rw [←(@rat.cast_floor K _ _ q), floor_ring_unique]
lemma coe_stream_nth_rat_eq :
((int_fract_pair.stream q n).map (mapFr coe) : option $ int_fract_pair K)
= int_fract_pair.stream v n :=
begin
induction n with n IH,
case nat.zero : { simp [int_fract_pair.stream, (coe_of_rat_eq v_eq_q)] },
case nat.succ :
{ rw v_eq_q at IH,
cases stream_q_nth_eq : (int_fract_pair.stream q n) with ifp_n,
case option.none : { simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq] },
case option.some :
{ cases ifp_n with b fr,
cases decidable.em (fr = 0) with fr_zero fr_ne_zero,
{ simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_zero] },
{ replace IH : some (int_fract_pair.mk b ↑fr) = int_fract_pair.stream ↑q n, by
rwa [stream_q_nth_eq] at IH,
have : (fr : K)⁻¹ = ((fr⁻¹ : ℚ) : K), by norm_cast,
have coe_of_fr := (coe_of_rat_eq this),
simp [int_fract_pair.stream, IH.symm, v_eq_q, stream_q_nth_eq, fr_ne_zero],
unfold_coes,
simpa [coe_of_fr] } } }
end
lemma coe_stream_rat_eq :
((int_fract_pair.stream q).map (option.map (mapFr coe)) : stream $ option $ int_fract_pair K) =
int_fract_pair.stream v :=
by { funext n, exact (int_fract_pair.coe_stream_nth_rat_eq v_eq_q n) }
end int_fract_pair
/-! Now we lift the coercion results to the continued fraction computation. -/
lemma coe_of_h_rat_eq : (↑((gcf.of q).h : ℚ) : K) = (gcf.of v).h :=
begin
unfold gcf.of int_fract_pair.seq1,
rw ←(int_fract_pair.coe_of_rat_eq v_eq_q),
simp
end
lemma coe_of_s_nth_rat_eq :
(((gcf.of q).s.nth n).map (gcf.pair.map coe) : option $ gcf.pair K) = (gcf.of v).s.nth n :=
begin
simp only [gcf.of, gcf.int_fract_pair.seq1, seq.map_nth, seq.nth_tail],
simp only [seq.nth],
rw [←(int_fract_pair.coe_stream_rat_eq v_eq_q)],
rcases succ_nth_stream_eq : (int_fract_pair.stream q (n + 1)) with _ | ⟨_, _⟩;
simp [stream.map, stream.nth, succ_nth_stream_eq]
end
lemma coe_of_s_rat_eq :
(((gcf.of q).s).map (gcf.pair.map coe) : seq $ gcf.pair K) = (gcf.of v).s :=
by { ext n, rw ←(coe_of_s_nth_rat_eq v_eq_q), refl }
/-- Given `(v : K), (q : ℚ), and v = q`, we have that `gcf.of q = gcf.of v` -/
lemma coe_of_rat_eq : (⟨(gcf.of q).h, (gcf.of q).s.map (gcf.pair.map coe)⟩ : gcf K) = gcf.of v :=
begin
cases gcf_v_eq : (gcf.of v) with h s,
have : ↑⌊↑q⌋ = h, by { rw v_eq_q at gcf_v_eq, injection gcf_v_eq },
simp [(coe_of_h_rat_eq v_eq_q), (coe_of_s_rat_eq v_eq_q), gcf_v_eq],
rwa [←(@rat.cast_floor K _ _ q), floor_ring_unique]
end
lemma of_terminates_iff_of_rat_terminates {v : K} {q : ℚ} (v_eq_q : v = (q : K)) :
(gcf.of v).terminates ↔ (gcf.of q).terminates :=
begin
split;
intro h;
cases h with n h;
use n;
simp only [seq.terminated_at, (coe_of_s_nth_rat_eq v_eq_q n).symm] at h ⊢;
cases ((gcf.of q).s.nth n);
trivial
end
end rat_translation
section terminates_of_rat
/-!
### Continued Fractions of Rationals Terminate
Finally, we show that the continued fraction of a rational number terminates.
The crucial insight is that, given any `q : ℚ` with `0 < q < 1`, the numerator of `fract q` is
smaller than the numerator of `q`. As the continued fraction computation recursively operates on
the fractional part of a value `v` and `0 ≤ fract v < 1`, we infer that the numerator of the
fractional part in the computation decreases by at least one in each step. As `0 ≤ fract v`,
this process must stop after finite number of steps, and the computation hence terminates.
-/
namespace int_fract_pair
variables {q : ℚ} {n : ℕ}
/--
Shows that for any `q : ℚ` with `0 < q < 1`, the numerator of the fractional part of
`int_fract_pair.of q⁻¹` is smaller than the numerator of `q`.
-/
lemma of_inv_fr_num_lt_num_of_pos (q_pos : 0 < q) :
(int_fract_pair.of q⁻¹).fr.num < q.num :=
rat.fract_inv_num_lt_num_of_pos q_pos
/-- Shows that the sequence of numerators of the fractional parts of the stream is strictly
monotonically decreasing. -/
lemma stream_succ_nth_fr_num_lt_nth_fr_num_rat {ifp_n ifp_succ_n : int_fract_pair ℚ}
(stream_nth_eq : int_fract_pair.stream q n = some ifp_n)
(stream_succ_nth_eq : int_fract_pair.stream q (n + 1) = some ifp_succ_n) :
ifp_succ_n.fr.num < ifp_n.fr.num :=
begin
obtain ⟨ifp_n', stream_nth_eq', ifp_n_fract_ne_zero, int_fract_pair.of_eq_ifp_succ_n⟩ :
∃ ifp_n', int_fract_pair.stream q n = some ifp_n' ∧ ifp_n'.fr ≠ 0
∧ int_fract_pair.of ifp_n'.fr⁻¹ = ifp_succ_n, from
succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq,
have : ifp_n = ifp_n', by injection (eq.trans stream_nth_eq.symm stream_nth_eq'),
cases this,
rw [←int_fract_pair.of_eq_ifp_succ_n],
cases (nth_stream_fr_nonneg_lt_one stream_nth_eq) with zero_le_ifp_n_fract ifp_n_fract_lt_one,
have : 0 < ifp_n.fr, from (lt_of_le_of_ne zero_le_ifp_n_fract $ ifp_n_fract_ne_zero.symm),
exact (of_inv_fr_num_lt_num_of_pos this)
end
lemma stream_nth_fr_num_le_fr_num_sub_n_rat : ∀ {ifp_n : int_fract_pair ℚ},
int_fract_pair.stream q n = some ifp_n → ifp_n.fr.num ≤ (int_fract_pair.of q).fr.num - n :=
begin
induction n with n IH,
case nat.zero
{ assume ifp_zero stream_zero_eq,
have : int_fract_pair.of q = ifp_zero, by injection stream_zero_eq,
simp [le_refl, this.symm] },
case nat.succ
{ assume ifp_succ_n stream_succ_nth_eq,
suffices : ifp_succ_n.fr.num + 1 ≤ (int_fract_pair.of q).fr.num - n, by
{ rw [int.coe_nat_succ, sub_add_eq_sub_sub],
solve_by_elim [le_sub_right_of_add_le] },
rcases (succ_nth_stream_eq_some_iff.elim_left stream_succ_nth_eq) with
⟨ifp_n, stream_nth_eq, -⟩,
have : ifp_succ_n.fr.num < ifp_n.fr.num, from
stream_succ_nth_fr_num_lt_nth_fr_num_rat stream_nth_eq stream_succ_nth_eq,
have : ifp_succ_n.fr.num + 1 ≤ ifp_n.fr.num, from int.add_one_le_of_lt this,
exact (le_trans this (IH stream_nth_eq)) }
end
lemma exists_nth_stream_eq_none_of_rat (q : ℚ) : ∃ (n : ℕ), int_fract_pair.stream q n = none :=
begin
let fract_q_num := (fract q).num, let n := fract_q_num.nat_abs + 1,
cases stream_nth_eq : (int_fract_pair.stream q n) with ifp,
{ use n, exact stream_nth_eq },
{ -- arrive at a contradiction since the numerator decreased num + 1 times but every fractional
-- value is nonnegative.
have ifp_fr_num_le_q_fr_num_sub_n : ifp.fr.num ≤ fract_q_num - n, from
stream_nth_fr_num_le_fr_num_sub_n_rat stream_nth_eq,
have : fract_q_num - n = -1, by
{ have : 0 ≤ fract_q_num, from rat.num_nonneg_iff_zero_le.elim_right (fract_nonneg q),
simp [(int.nat_abs_of_nonneg this), sub_add_eq_sub_sub_swap, sub_right_comm] },
have : ifp.fr.num ≤ -1, by rwa this at ifp_fr_num_le_q_fr_num_sub_n,
have : 0 ≤ ifp.fr, from (nth_stream_fr_nonneg_lt_one stream_nth_eq).left,
have : 0 ≤ ifp.fr.num, from rat.num_nonneg_iff_zero_le.elim_right this,
linarith }
end
end int_fract_pair
/-- The continued fraction of a rational number terminates. -/
theorem terminates_of_rat (q : ℚ) : (gcf.of q).terminates :=
exists.elim (int_fract_pair.exists_nth_stream_eq_none_of_rat q)
( assume n stream_nth_eq_none,
exists.intro n
( have int_fract_pair.stream q (n + 1) = none, from
int_fract_pair.stream_is_seq q stream_nth_eq_none,
(of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none.elim_right this) ) )
end terminates_of_rat
/--
The continued fraction `generalized_continued_fraction.of v` terminates if and only if `v ∈ ℚ`.
-/
theorem terminates_iff_rat [archimedean K] (v : K) :
(gcf.of v).terminates ↔ ∃ (q : ℚ), v = (q : K) :=
iff.intro
( assume terminates_v : (gcf.of v).terminates,
show ∃ (q : ℚ), v = (q : K), from exists_rat_eq_of_terminates terminates_v )
( assume exists_q_eq_v : ∃ (q : ℚ), v = (↑q : K),
exists.elim exists_q_eq_v
( assume q,
assume v_eq_q : v = ↑q,
have (gcf.of q).terminates, from terminates_of_rat q,
(of_terminates_iff_of_rat_terminates v_eq_q).elim_right this ) )
end generalized_continued_fraction
|
772b41311e7c2c442b2e2bf52b4f26590b74411c | 556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e | /src/starkware/cairo/common/cairo_secp/verification/verification/signature_recover_public_key_div_mod_n_soundness.lean | 0414a87335190db3430d3465e7c53e0ca9a290a1 | [] | permissive | starkware-libs/formal-proofs | d6b731604461bf99e6ba820e68acca62a21709e8 | f5fa4ba6a471357fd171175183203d0b437f6527 | refs/heads/master | 1,691,085,444,753 | 1,690,507,386,000 | 1,690,507,386,000 | 410,476,629 | 32 | 9 | Apache-2.0 | 1,690,506,773,000 | 1,632,639,790,000 | Lean | UTF-8 | Lean | false | false | 22,173 | lean | /-
File: signature_recover_public_key_div_mod_n_soundness.lean
Autogenerated file.
-/
import starkware.cairo.lean.semantics.soundness.hoare
import .signature_recover_public_key_code
import ..signature_recover_public_key_spec
import .signature_recover_public_key_bigint_mul_soundness
import .signature_recover_public_key_nondet_bigint3_soundness
open tactic
open starkware.cairo.common.cairo_secp.signature
open starkware.cairo.common.cairo_secp.bigint
open starkware.cairo.common.cairo_secp.constants
variables {F : Type} [field F] [decidable_eq F] [prelude_hyps F]
variable mem : F → F
variable σ : register_state F
/- starkware.cairo.common.cairo_secp.signature.div_mod_n autogenerated soundness theorem -/
theorem auto_sound_div_mod_n
-- arguments
(range_check_ptr : F) (a b : BigInt3 F)
-- code is in memory at σ.pc
(h_mem : mem_at mem code_div_mod_n σ.pc)
-- all dependencies are in memory
(h_mem_3 : mem_at mem code_bigint_mul (σ.pc - 668))
(h_mem_4 : mem_at mem code_nondet_bigint3 (σ.pc - 654))
-- input arguments on the stack
(hin_range_check_ptr : range_check_ptr = mem (σ.fp - 9))
(hin_a : a = cast_BigInt3 mem (σ.fp - 8))
(hin_b : b = cast_BigInt3 mem (σ.fp - 5))
-- conclusion
: ensures_ret mem σ (λ κ τ,
τ.ap = σ.ap + 88 ∧
∃ μ ≤ κ, rc_ensures mem (rc_bound F) μ (mem (σ.fp - 9)) (mem $ τ.ap - 4)
(spec_div_mod_n mem κ range_check_ptr a b (mem (τ.ap - 4)) (cast_BigInt3 mem (τ.ap - 3)))) :=
begin
apply ensures_of_ensuresb, intro νbound,
have h_mem_rec := h_mem,
unpack_memory code_div_mod_n at h_mem with ⟨hpc0, hpc1, hpc2, hpc3, hpc4, hpc5, hpc6, hpc7, hpc8, hpc9, hpc10, hpc11, hpc12, hpc13, hpc14, hpc15, hpc16, hpc17, hpc18, hpc19, hpc20, hpc21, hpc22, hpc23, hpc24, hpc25, hpc26, hpc27, hpc28, hpc29, hpc30, hpc31, hpc32, hpc33, hpc34, hpc35, hpc36, hpc37, hpc38, hpc39, hpc40, hpc41, hpc42, hpc43, hpc44, hpc45, hpc46, hpc47, hpc48, hpc49, hpc50, hpc51, hpc52, hpc53, hpc54, hpc55, hpc56, hpc57, hpc58, hpc59, hpc60, hpc61, hpc62, hpc63, hpc64⟩,
-- function call
step_assert_eq hpc0 with arg0,
step_sub hpc1 (auto_sound_nondet_bigint3 mem _ range_check_ptr _ _),
{ rw hpc2, norm_num2, exact h_mem_4 },
{ try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b] },
try { dsimp [cast_BigInt3] },
try { arith_simps }, try { simp only [arg0] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },
intros κ_call3 ap3 h_call3,
rcases h_call3 with ⟨h_call3_ap_offset, h_call3⟩,
rcases h_call3 with ⟨rc_m3, rc_mle3, hl_range_check_ptr₁, h_call3⟩,
generalize' hr_rev_range_check_ptr₁: mem (ap3 - 4) = range_check_ptr₁,
have htv_range_check_ptr₁ := hr_rev_range_check_ptr₁.symm, clear hr_rev_range_check_ptr₁,
generalize' hr_rev_res: cast_BigInt3 mem (ap3 - 3) = res,
simp only [hr_rev_res] at h_call3,
have htv_res := hr_rev_res.symm, clear hr_rev_res,
try { simp only [arg0] at hl_range_check_ptr₁ },
rw [←htv_range_check_ptr₁, ←hin_range_check_ptr] at hl_range_check_ptr₁,
try { simp only [arg0] at h_call3 },
rw [hin_range_check_ptr] at h_call3,
clear arg0,
-- function call
step_assert_eq hpc3 with arg0,
step_sub hpc4 (auto_sound_nondet_bigint3 mem _ range_check_ptr₁ _ _),
{ rw hpc5, norm_num2, exact h_mem_4 },
{ try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res] },
try { dsimp [cast_BigInt3] },
try { arith_simps }, try { simp only [arg0] },
try { simp only [h_call3_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },
intros κ_call6 ap6 h_call6,
rcases h_call6 with ⟨h_call6_ap_offset, h_call6⟩,
rcases h_call6 with ⟨rc_m6, rc_mle6, hl_range_check_ptr₂, h_call6⟩,
generalize' hr_rev_range_check_ptr₂: mem (ap6 - 4) = range_check_ptr₂,
have htv_range_check_ptr₂ := hr_rev_range_check_ptr₂.symm, clear hr_rev_range_check_ptr₂,
generalize' hr_rev_k: cast_BigInt3 mem (ap6 - 3) = k,
simp only [hr_rev_k] at h_call6,
have htv_k := hr_rev_k.symm, clear hr_rev_k,
try { simp only [arg0] at hl_range_check_ptr₂ },
rw [←htv_range_check_ptr₂, ←htv_range_check_ptr₁] at hl_range_check_ptr₂,
try { simp only [arg0] at h_call6 },
rw [←htv_range_check_ptr₁, hl_range_check_ptr₁, hin_range_check_ptr] at h_call6,
clear arg0,
-- function call
step_assert_eq hpc6 with arg0,
step_assert_eq hpc7 with arg1,
step_assert_eq hpc8 with arg2,
step_assert_eq hpc9 with arg3,
step_assert_eq hpc10 with arg4,
step_assert_eq hpc11 with arg5,
step_sub hpc12 (auto_sound_bigint_mul mem _ res b _ _ _),
{ rw hpc13, norm_num2, exact h_mem_3 },
{ try { ext } ; {
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k] },
try { dsimp [cast_BigInt3] },
try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },
{ try { ext } ; {
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k] },
try { dsimp [cast_BigInt3] },
try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },
intros κ_call14 ap14 h_call14,
rcases h_call14 with ⟨h_call14_ap_offset, h_call14⟩,
generalize' hr_rev_res_b: cast_UnreducedBigInt5 mem (ap14 - 5) = res_b,
simp only [hr_rev_res_b] at h_call14,
have htv_res_b := hr_rev_res_b.symm, clear hr_rev_res_b,
clear arg0 arg1 arg2 arg3 arg4 arg5,
-- let
generalize' hl_rev_n: ({
d0 := N0,
d1 := N1,
d2 := N2
} : BigInt3 F) = n,
have hl_n := hl_rev_n.symm, clear hl_rev_n,
try { dsimp at hl_n }, try { arith_simps at hl_n },
-- function call
step_assert_eq hpc14 with arg0,
step_assert_eq hpc15 with arg1,
step_assert_eq hpc16 with arg2,
step_assert_eq hpc17 hpc18 with arg3,
step_assert_eq hpc19 hpc20 with arg4,
step_assert_eq hpc21 hpc22 with arg5,
step_sub hpc23 (auto_sound_bigint_mul mem _ k n _ _ _),
{ rw hpc24, norm_num2, exact h_mem_3 },
{ try { ext } ; {
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n] },
try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },
try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },
{ try { ext } ; {
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n] },
try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },
try { arith_simps }, try { simp only [arg0, arg1, arg2, arg3, arg4, arg5] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },}, },
intros κ_call25 ap25 h_call25,
rcases h_call25 with ⟨h_call25_ap_offset, h_call25⟩,
generalize' hr_rev_k_n: cast_UnreducedBigInt5 mem (ap25 - 5) = k_n,
simp only [hr_rev_k_n] at h_call25,
have htv_k_n := hr_rev_k_n.symm, clear hr_rev_k_n,
clear arg0 arg1 arg2 arg3 arg4 arg5,
-- tempvar
step_assert_eq hpc25 with tv_carry10,
step_assert_eq hpc26 with tv_carry11,
step_assert_eq hpc27 hpc28 with tv_carry12,
generalize' hl_rev_carry1: ((res_b.d0 - k_n.d0 - a.d0) / (BASE : ℤ) : F) = carry1,
have hl_carry1 := hl_rev_carry1.symm, clear hl_rev_carry1,
have htv_carry1: carry1 = _, {
have h_δ25_c0 : ∀ x : F, x / (BASE : ℤ) = x * (-46768052394588894761721767695234645457402928824320 : ℤ),
{ intro x, apply div_eq_mul_inv', apply PRIME.int_cast_mul_eq_one, rw [PRIME], try { simp_int_casts }, norm_num1 },
apply eq.symm, apply eq.trans tv_carry12,
try { simp only [h_δ25_c0] at hl_carry1 },
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1] },
try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },
try { arith_simps }, try { simp only [(eq_sub_of_eq_add tv_carry10), (eq_sub_of_eq_add tv_carry11)] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },
clear tv_carry10 tv_carry11 tv_carry12,
try { dsimp at hl_carry1 }, try { arith_simps at hl_carry1 },
-- compound assert eq
step_assert_eq hpc29 hpc30 with temp0,
step_assert_eq hpc31 with temp1,
have a29: mem (range_check_ptr₂ + 0) = carry1 + 2 ^ 127, {
apply assert_eq_reduction temp1.symm,
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1] },
try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },
try { arith_simps }, try { simp only [temp0] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a29 }, try { arith_simps at a29 },
clear temp0 temp1,
-- tempvar
step_assert_eq hpc32 with tv_carry20,
step_assert_eq hpc33 with tv_carry21,
step_assert_eq hpc34 with tv_carry22,
step_assert_eq hpc35 hpc36 with tv_carry23,
generalize' hl_rev_carry2: ((res_b.d1 - k_n.d1 - a.d1 + carry1) / (BASE : ℤ) : F) = carry2,
have hl_carry2 := hl_rev_carry2.symm, clear hl_rev_carry2,
have htv_carry2: carry2 = _, {
have h_δ32_c0 : ∀ x : F, x / (BASE : ℤ) = x * (-46768052394588894761721767695234645457402928824320 : ℤ),
{ intro x, apply div_eq_mul_inv', apply PRIME.int_cast_mul_eq_one, rw [PRIME], try { simp_int_casts }, norm_num1 },
apply eq.symm, apply eq.trans tv_carry23,
try { simp only [h_δ32_c0] at hl_carry2 },
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2] },
try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },
try { arith_simps }, try { simp only [(eq_sub_of_eq_add tv_carry20), (eq_sub_of_eq_add tv_carry21), tv_carry22] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },
clear tv_carry20 tv_carry21 tv_carry22 tv_carry23,
try { dsimp at hl_carry2 }, try { arith_simps at hl_carry2 },
-- compound assert eq
step_assert_eq hpc37 hpc38 with temp0,
step_assert_eq hpc39 with temp1,
have a37: mem (range_check_ptr₂ + 1) = carry2 + 2 ^ 127, {
apply assert_eq_reduction temp1.symm,
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2] },
try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },
try { arith_simps }, try { simp only [temp0] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a37 }, try { arith_simps at a37 },
clear temp0 temp1,
-- tempvar
step_assert_eq hpc40 with tv_carry30,
step_assert_eq hpc41 with tv_carry31,
step_assert_eq hpc42 with tv_carry32,
step_assert_eq hpc43 hpc44 with tv_carry33,
generalize' hl_rev_carry3: ((res_b.d2 - k_n.d2 - a.d2 + carry2) / (BASE : ℤ) : F) = carry3,
have hl_carry3 := hl_rev_carry3.symm, clear hl_rev_carry3,
have htv_carry3: carry3 = _, {
have h_δ40_c0 : ∀ x : F, x / (BASE : ℤ) = x * (-46768052394588894761721767695234645457402928824320 : ℤ),
{ intro x, apply div_eq_mul_inv', apply PRIME.int_cast_mul_eq_one, rw [PRIME], try { simp_int_casts }, norm_num1 },
apply eq.symm, apply eq.trans tv_carry33,
try { simp only [h_δ40_c0] at hl_carry3 },
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2, hl_carry3] },
try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },
try { arith_simps }, try { simp only [(eq_sub_of_eq_add tv_carry30), (eq_sub_of_eq_add tv_carry31), tv_carry32] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },
clear tv_carry30 tv_carry31 tv_carry32 tv_carry33,
try { dsimp at hl_carry3 }, try { arith_simps at hl_carry3 },
-- compound assert eq
step_assert_eq hpc45 hpc46 with temp0,
step_assert_eq hpc47 with temp1,
have a45: mem (range_check_ptr₂ + 2) = carry3 + 2 ^ 127, {
apply assert_eq_reduction temp1.symm,
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2, hl_carry3, htv_carry3] },
try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },
try { arith_simps }, try { simp only [temp0] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a45 }, try { arith_simps at a45 },
clear temp0 temp1,
-- tempvar
step_assert_eq hpc48 with tv_carry40,
step_assert_eq hpc49 with tv_carry41,
step_assert_eq hpc50 hpc51 with tv_carry42,
generalize' hl_rev_carry4: ((res_b.d3 - k_n.d3 + carry3) / (BASE : ℤ) : F) = carry4,
have hl_carry4 := hl_rev_carry4.symm, clear hl_rev_carry4,
have htv_carry4: carry4 = _, {
have h_δ48_c0 : ∀ x : F, x / (BASE : ℤ) = x * (-46768052394588894761721767695234645457402928824320 : ℤ),
{ intro x, apply div_eq_mul_inv', apply PRIME.int_cast_mul_eq_one, rw [PRIME], try { simp_int_casts }, norm_num1 },
apply eq.symm, apply eq.trans tv_carry42,
try { simp only [h_δ48_c0] at hl_carry4 },
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2, hl_carry3, htv_carry3, hl_carry4] },
try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },
try { arith_simps }, try { simp only [(eq_sub_of_eq_add tv_carry40), tv_carry41] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } }, },
clear tv_carry40 tv_carry41 tv_carry42,
try { dsimp at hl_carry4 }, try { arith_simps at hl_carry4 },
-- compound assert eq
step_assert_eq hpc52 hpc53 with temp0,
step_assert_eq hpc54 with temp1,
have a52: mem (range_check_ptr₂ + 3) = carry4 + 2 ^ 127, {
apply assert_eq_reduction temp1.symm,
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2, hl_carry3, htv_carry3, hl_carry4, htv_carry4] },
try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },
try { arith_simps }, try { simp only [temp0] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a52 }, try { arith_simps at a52 },
clear temp0 temp1,
-- compound assert eq
step_assert_eq hpc55 with temp0,
step_assert_eq hpc56 hpc57 with temp1,
step_assert_eq hpc58 with temp2,
have a55: res_b.d4 - k_n.d4 + carry4 = 0, {
apply assert_eq_reduction temp2.symm,
try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2, hl_carry3, htv_carry3, hl_carry4, htv_carry4] },
try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },
try { arith_simps }, try { simp only [(eq_sub_of_eq_add temp0), temp1] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
},
try { dsimp at a55 }, try { arith_simps at a55 },
clear temp0 temp1 temp2,
-- let
generalize' hl_rev_range_check_ptr₃: (range_check_ptr₂ + 4 : F) = range_check_ptr₃,
have hl_range_check_ptr₃ := hl_rev_range_check_ptr₃.symm, clear hl_rev_range_check_ptr₃,
try { dsimp at hl_range_check_ptr₃ }, try { arith_simps at hl_range_check_ptr₃ },
-- return
step_assert_eq hpc59 hpc60 with hret0,
step_assert_eq hpc61 with hret1,
step_assert_eq hpc62 with hret2,
step_assert_eq hpc63 with hret3,
step_ret hpc64,
-- finish
step_done, use_only [rfl, rfl],
split,
{ try { simp only [h_call3_ap_offset ,h_call6_ap_offset ,h_call14_ap_offset ,h_call25_ap_offset] },
try { arith_simps }, try { refl } },
-- range check condition
use_only (rc_m3+rc_m6+4+0+0), split,
linarith [rc_mle3, rc_mle6],
split,
{ arith_simps, try { simp only [hret0 ,hret1 ,hret2 ,hret3] },
try { simp only [h_call25_ap_offset ,h_call14_ap_offset] }, try { arith_simps },
rw [←htv_range_check_ptr₂, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr],
try { arith_simps, refl <|> norm_cast }, try { refl } },
intro rc_h_range_check_ptr, repeat { rw [add_assoc] at rc_h_range_check_ptr },
have rc_h_range_check_ptr' := range_checked_add_right rc_h_range_check_ptr,
-- Final Proof
-- user-provided reduction
suffices auto_spec: auto_spec_div_mod_n mem _ range_check_ptr a b _ _,
{ apply sound_div_mod_n, apply auto_spec },
-- prove the auto generated assertion
dsimp [auto_spec_div_mod_n],
try { norm_num1 }, try { arith_simps },
use_only [κ_call3],
use_only [range_check_ptr₁],
use_only [res],
have rc_h_range_check_ptr₁ := range_checked_offset' rc_h_range_check_ptr,
have rc_h_range_check_ptr₁' := range_checked_add_right rc_h_range_check_ptr₁, try { norm_cast at rc_h_range_check_ptr₁' },
have spec3 := h_call3 rc_h_range_check_ptr',
rw [←hin_range_check_ptr, ←htv_range_check_ptr₁] at spec3,
try { dsimp at spec3, arith_simps at spec3 },
use_only [spec3],
use_only [κ_call6],
use_only [range_check_ptr₂],
use_only [k],
have rc_h_range_check_ptr₂ := range_checked_offset' rc_h_range_check_ptr₁,
have rc_h_range_check_ptr₂' := range_checked_add_right rc_h_range_check_ptr₂, try { norm_cast at rc_h_range_check_ptr₂' },
have spec6 := h_call6 rc_h_range_check_ptr₁',
rw [←hin_range_check_ptr, ←hl_range_check_ptr₁, ←htv_range_check_ptr₂] at spec6,
try { dsimp at spec6, arith_simps at spec6 },
use_only [spec6],
use_only [κ_call14],
use_only [res_b],
try { dsimp at h_call14, arith_simps at h_call14 },
try { use_only [h_call14] },
use_only [n, hl_n],
use_only [κ_call25],
use_only [k_n],
try { dsimp at h_call25, arith_simps at h_call25 },
try { use_only [h_call25] },
use_only [carry1, hl_carry1],
use_only [a29],
cases rc_h_range_check_ptr₂' (0) (by norm_num1) with n hn, arith_simps at hn,
use_only [n], { simp only [a29.symm, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },
use_only [carry2, hl_carry2],
use_only [a37],
cases rc_h_range_check_ptr₂' (1) (by norm_num1) with n hn, arith_simps at hn,
use_only [n], { simp only [a37.symm, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },
use_only [carry3, hl_carry3],
use_only [a45],
cases rc_h_range_check_ptr₂' (2) (by norm_num1) with n hn, arith_simps at hn,
use_only [n], { simp only [a45.symm, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },
use_only [carry4, hl_carry4],
use_only [a52],
cases rc_h_range_check_ptr₂' (3) (by norm_num1) with n hn, arith_simps at hn,
use_only [n], { simp only [a52.symm, hl_range_check_ptr₂, hl_range_check_ptr₁, hin_range_check_ptr], arith_simps, exact hn },
use_only [a55],
have rc_h_range_check_ptr₃ := range_checked_offset' rc_h_range_check_ptr₂,
have rc_h_range_check_ptr₃' := range_checked_add_right rc_h_range_check_ptr₃,try { norm_cast at rc_h_range_check_ptr₃' },
use_only [range_check_ptr₃, hl_range_check_ptr₃],
try { split, linarith },
try { ensures_simps; try { simp only [add_neg_eq_sub, hin_range_check_ptr, hin_a, hin_b, htv_range_check_ptr₁, htv_res, htv_range_check_ptr₂, htv_k, htv_res_b, hl_n, htv_k_n, hl_carry1, htv_carry1, hl_carry2, htv_carry2, hl_carry3, htv_carry3, hl_carry4, htv_carry4, hl_range_check_ptr₃] }, },
try { dsimp [cast_BigInt3, cast_UnreducedBigInt5] },
try { arith_simps }, try { simp only [hret0, hret1, hret2, hret3] },
try { simp only [h_call3_ap_offset, h_call6_ap_offset, h_call14_ap_offset, h_call25_ap_offset] },
try { arith_simps; try { split }; triv <|> refl <|> simp <|> abel; try { norm_num } },
end
|
f8cf0979e1ba34d0c628384063cace361db02efc | e61a235b8468b03aee0120bf26ec615c045005d2 | /src/Init/System/IO.lean | 497ca064d2a5140816e5664e039e8211d9084353 | [
"Apache-2.0"
] | permissive | SCKelemen/lean4 | 140dc63a80539f7c61c8e43e1c174d8500ec3230 | e10507e6615ddbef73d67b0b6c7f1e4cecdd82bc | refs/heads/master | 1,660,973,595,917 | 1,590,278,033,000 | 1,590,278,033,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 12,061 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Luke Nelson, Jared Roesch, Leonardo de Moura, Sebastian Ullrich
-/
prelude
import Init.Control.EState
import Init.Data.String.Basic
import Init.Data.ByteArray
import Init.System.IOError
import Init.System.FilePath
/-- Like https://hackage.haskell.org/package/ghc-Prim-0.5.2.0/docs/GHC-Prim.html#t:RealWorld.
Makes sure we never reorder `IO` operations.
TODO: mark opaque -/
def IO.RealWorld : Type := Unit
/- TODO(Leo): mark it as an opaque definition. Reason: prevent
functions defined in other modules from accessing `IO.RealWorld`.
We don't want action such as
```
def getWorld : IO (IO.RealWorld) := get
```
-/
def EIO (ε : Type) : Type → Type := EStateM ε IO.RealWorld
@[inline] def EIO.adaptExcept {α ε ε'} (f : ε → ε') (x : EIO ε α) : EIO ε' α :=
EStateM.adaptExcept f x
@[inline] def EIO.catchExceptions {α ε} (x : EIO ε α) (h : ε → EIO Empty α) : EIO Empty α :=
fun s => match x s with
| EStateM.Result.ok a s => EStateM.Result.ok a s
| EStateM.Result.error ex s => h ex s
instance (ε : Type) : Monad (EIO ε) := inferInstanceAs (Monad (EStateM ε IO.RealWorld))
instance (ε : Type) : MonadExcept ε (EIO ε) := inferInstanceAs (MonadExcept ε (EStateM ε IO.RealWorld))
instance (α ε : Type) : HasOrelse (EIO ε α) := ⟨MonadExcept.orelse⟩
instance {ε : Type} {α : Type} [Inhabited ε] : Inhabited (EIO ε α) :=
inferInstanceAs (Inhabited (EStateM ε IO.RealWorld α))
abbrev IO : Type → Type := EIO IO.Error
section
/- After we inline `EState.run'`, the closed term `((), ())` is generated, where the second `()`
represents the "initial world". We don't want to cache this closed term. So, we disable
the "extract closed terms" optimization. -/
set_option compiler.extract_closed false
@[inline] unsafe def unsafeIO {α : Type} (fn : IO α) : Except IO.Error α :=
match fn.run () with
| EStateM.Result.ok a _ => Except.ok a
| EStateM.Result.error e _ => Except.error e
end
@[extern "lean_io_timeit"]
constant timeit {α : Type} (msg : @& String) (fn : IO α) : IO α := arbitrary _
@[extern "lean_io_allocprof"]
constant allocprof {α : Type} (msg : @& String) (fn : IO α) : IO α := arbitrary _
/- Programs can execute IO actions during initialization that occurs before
the `main` function is executed. The attribute `[init <action>]` specifies
which IO action is executed to set the value of an opaque constant.
The action `initializing` returns `true` iff it is invoked during initialization. -/
@[extern "lean_io_initializing"]
constant IO.initializing : IO Bool := arbitrary _
abbrev MonadIO (m : Type → Type) := HasMonadLiftT IO m
namespace IO
def ofExcept {ε α : Type} [HasToString ε] (e : Except ε α) : IO α :=
match e with
| Except.ok a => pure a
| Except.error e => throw (IO.userError (toString e))
def lazyPure {α : Type} (fn : Unit → α) : IO α :=
pure (fn ())
inductive FS.Mode
| read | write | readWrite | append
constant FS.Handle : Type := Unit
namespace Prim
open FS
@[specialize] partial def iterate {α β : Type} : α → (α → IO (Sum α β)) → IO β
| a, f => do
v ← f a;
match v with
| Sum.inl a => iterate a f
| Sum.inr b => pure b
-- @[export lean_fopen_flags]
def fopenFlags (m : FS.Mode) (b : Bool) : String :=
let mode :=
match m with
| FS.Mode.read => "r"
| FS.Mode.write => "w"
| FS.Mode.readWrite => "r+"
| FS.Mode.append => "a" ;
let bin := if b then "b" else "t";
mode ++ bin
@[extern "lean_io_prim_put_str"]
constant putStr (s: @& String) : IO Unit := arbitrary _
@[extern "lean_io_prim_handle_mk"]
constant Handle.mk (s : @& String) (mode : @& String) : IO Handle := arbitrary _
@[extern "lean_io_prim_handle_is_eof"]
constant Handle.isEof (h : @& Handle) : IO Bool := arbitrary _
@[extern "lean_io_prim_handle_flush"]
constant Handle.flush (h : @& Handle) : IO Unit := arbitrary _
-- TODO: replace `String` with byte buffer
@[extern "lean_io_prim_handle_read"]
constant Handle.read (h : @& Handle) (bytes : USize) : IO ByteArray := arbitrary _
@[extern "lean_io_prim_handle_write"]
constant Handle.write (h : @& Handle) (buffer : @& ByteArray) : IO Unit := arbitrary _
@[extern "lean_io_prim_handle_read_byte"]
constant Handle.getByte (h : @& Handle) : IO UInt8 := arbitrary _
@[extern "lean_io_prim_handle_write_byte"]
constant Handle.putByte (h : @& Handle) (c : UInt8) : IO Unit := arbitrary _
@[extern "lean_io_prim_handle_get_line"]
constant Handle.getLine (h : @& Handle) : IO String := arbitrary _
@[extern "lean_io_prim_handle_put_str"]
constant Handle.putStr (h : @& Handle) (s : @& String) : IO Unit := arbitrary _
@[extern "lean_io_getenv"]
constant getEnv (var : @& String) : IO (Option String) := arbitrary _
@[extern "lean_io_realpath"]
constant realPath (fname : String) : IO String := arbitrary _
@[extern "lean_io_is_dir"]
constant isDir (fname : @& String) : IO Bool := arbitrary _
@[extern "lean_io_file_exists"]
constant fileExists (fname : @& String) : IO Bool := arbitrary _
@[extern "lean_io_app_dir"]
constant appPath : IO String := arbitrary _
@[extern "lean_io_current_dir"]
constant currentDir : IO String := arbitrary _
@[inline] def liftIO {m : Type → Type} {α : Type} [MonadIO m] (x : IO α) : m α :=
monadLift x
end Prim
section
variables {m : Type → Type} [Monad m] [MonadIO m]
private def putStr : String → m Unit :=
Prim.liftIO ∘ Prim.putStr
def print {α} [HasToString α] (s : α) : m Unit := putStr ∘ toString $ s
def println {α} [HasToString α] (s : α) : m Unit := print s *> putStr "\n"
def getEnv : String → m (Option String) := Prim.liftIO ∘ Prim.getEnv
def realPath : String → m String := Prim.liftIO ∘ Prim.realPath
def isDir : String → m Bool := Prim.liftIO ∘ Prim.isDir
def fileExists : String → m Bool := Prim.liftIO ∘ Prim.fileExists
def appPath : m String := Prim.liftIO Prim.appPath
def currentDir : m String := Prim.liftIO Prim.currentDir
def appDir : m String := do
p ← appPath;
realPath (System.FilePath.dirName p)
end
namespace FS
variables {m : Type → Type} [Monad m] [MonadIO m]
def Handle.mk (s : String) (Mode : Mode) (bin : Bool := false) : m Handle :=
Prim.liftIO (Prim.Handle.mk s (Prim.fopenFlags Mode bin))
@[inline]
def withFile {α} (fn : String) (m : Mode) (f : Handle → IO α) : IO α :=
Handle.mk fn m >>= f
/-- returns whether the end of the file has been reached while reading a file.
`h.isEof` returns true /after/ the first attempt at reading past the end of `h`.
Once `h.isEof` is true, the reading `h` raises `IO.Error.eof`.
-/
def Handle.isEof : Handle → m Bool := Prim.liftIO ∘ Prim.Handle.isEof
def Handle.flush : Handle → m Unit := Prim.liftIO ∘ Prim.Handle.flush
def Handle.read (h : Handle) (bytes : Nat) : m ByteArray := Prim.liftIO (Prim.Handle.read h (USize.ofNat bytes))
def Handle.write (h : Handle) (s : ByteArray) : m Unit := Prim.liftIO (Prim.Handle.write h s)
def Handle.getByte (h : Handle) : m UInt8 := Prim.liftIO (Prim.Handle.getByte h)
def Handle.putByte (h : Handle) (b : UInt8) : m Unit := Prim.liftIO (Prim.Handle.putByte h b)
def Handle.getLine : Handle → m String := Prim.liftIO ∘ Prim.Handle.getLine
def Handle.putStr (h : Handle) (s : String) : m Unit :=
Prim.liftIO $ Prim.Handle.putStr h s
def Handle.putStrLn (h : Handle) (s : String) : m Unit :=
h.putStr s *> h.putStr "\n"
-- TODO: support for binary files
partial def Handle.readToEndAux (h : Handle) : String → m String
| s => do
line ← h.getLine;
if line.length == 0 then pure s
else Handle.readToEndAux (s ++ line)
-- TODO: support for binary files
def Handle.readToEnd (h : Handle) : m String :=
Handle.readToEndAux h ""
-- TODO: support for binary files
def readFile (fname : String) : m String := do
h ← Handle.mk fname Mode.read false;
h.readToEnd
partial def linesAux (h : Handle) : Array String → m (Array String)
| lines => do
line ← h.getLine;
if line.length == 0 then
pure lines
else if line.back == '\n' then
let line := line.dropRight 1;
let line := if System.Platform.isWindows && line.back == '\x0d' then line.dropRight 1 else line;
linesAux $ lines.push line
else
pure $ lines.push line
def lines (fname : String) : m (Array String) := do
h ← Handle.mk fname Mode.read false;
linesAux h #[]
end FS
-- constant stdin : IO FS.Handle
-- constant stderr : IO FS.Handle
-- constant stdout : IO FS.Handle
/-
namespace Proc
def child : Type :=
MonadIOProcess.child ioCore
def child.stdin : child → Handle :=
MonadIOProcess.stdin
def child.stdout : child → Handle :=
MonadIOProcess.stdout
def child.stderr : child → Handle :=
MonadIOProcess.stderr
def spawn (p : IO.process.spawnArgs) : IO child :=
MonadIOProcess.spawn ioCore p
def wait (c : child) : IO Nat :=
MonadIOProcess.wait c
end Proc
-/
structure AccessRight :=
(read write execution : Bool := false)
def AccessRight.flags (acc : AccessRight) : UInt32 :=
let r : UInt32 := if acc.read then 0x4 else 0;
let w : UInt32 := if acc.write then 0x2 else 0;
let x : UInt32 := if acc.execution then 0x1 else 0;
r.lor $ w.lor x
structure FileRight :=
(user group other : AccessRight := { })
def FileRight.flags (acc : FileRight) : UInt32 :=
let u : UInt32 := acc.user.flags.shiftLeft 6;
let g : UInt32 := acc.group.flags.shiftLeft 3;
let o : UInt32 := acc.other.flags;
u.lor $ g.lor o
@[extern "lean_chmod"]
constant Prim.setAccessRights (filename : @& String) (mode : UInt32) : IO Unit :=
arbitrary _
def setAccessRights (filename : String) (mode : FileRight) : IO Unit :=
Prim.setAccessRights filename mode.flags
/- References -/
constant RefPointed (α : Type) : PointedType := arbitrary _
def Ref (α : Type) : Type := (RefPointed α).type
instance (α : Type) : Inhabited (Ref α) := ⟨(RefPointed α).val⟩
namespace Prim
@[extern "lean_io_mk_ref"]
constant mkRef {α : Type} (a : α) : IO (Ref α) := arbitrary _
@[extern "lean_io_ref_get"]
constant Ref.get {α : Type} (r : @& Ref α) : IO α := arbitrary _
@[extern "lean_io_ref_set"]
constant Ref.set {α : Type} (r : @& Ref α) (a : α) : IO Unit := arbitrary _
@[extern "lean_io_ref_swap"]
constant Ref.swap {α : Type} (r : @& Ref α) (a : α) : IO α := arbitrary _
@[extern "lean_io_ref_reset"]
constant Ref.reset {α : Type} (r : @& Ref α) : IO Unit := arbitrary _
@[extern "lean_io_ref_ptr_eq"]
constant Ref.ptrEq {α : Type} (r1 r2 : @& Ref α) : IO Bool := arbitrary _
end Prim
section
variables {m : Type → Type} [Monad m] [MonadIO m]
@[inline] def mkRef {α : Type} (a : α) : m (Ref α) := Prim.liftIO (Prim.mkRef a)
@[inline] def Ref.get {α : Type} (r : Ref α) : m α := Prim.liftIO (Prim.Ref.get r)
@[inline] def Ref.set {α : Type} (r : Ref α) (a : α) : m Unit := Prim.liftIO (Prim.Ref.set r a)
@[inline] def Ref.swap {α : Type} (r : Ref α) (a : α) : m α := Prim.liftIO (Prim.Ref.swap r a)
@[inline] def Ref.reset {α : Type} (r : Ref α) : m Unit := Prim.liftIO (Prim.Ref.reset r)
@[inline] def Ref.ptrEq {α : Type} (r1 r2 : Ref α) : m Bool := Prim.liftIO (Prim.Ref.ptrEq r1 r2)
@[inline] def Ref.modify {α : Type} (r : Ref α) (f : α → α) : m Unit := do
v ← r.get;
r.reset;
r.set (f v)
end
end IO
universe u
namespace Lean
/-- Typeclass used for presenting the output of an `#eval` command. -/
class HasEval (α : Type u) :=
-- We default `hideUnit` to `true`, but set it to `false` in the direct call from `#eval`
-- so that `()` output is hidden in chained instances such as for some `m Unit`.
(eval : α → forall (hideUnit : optParam Bool true), IO Unit)
instance HasRepr.hasEval {α : Type u} [HasRepr α] : HasEval α :=
⟨fun a _ => IO.println (repr a)⟩
instance Unit.hasEval : HasEval Unit :=
⟨fun u hideUnit => if hideUnit then pure () else IO.println (repr u)⟩
instance IO.HasEval {α : Type} [HasEval α] : HasEval (IO α) :=
⟨fun x _ => do a ← x; HasEval.eval a⟩
end Lean
|
55c16898e89e7071d70671cb68a0ea58f3f57e3d | b7b549d2cf38ac9d4e49372b7ad4d37f70449409 | /src/LeanLLVM/SimMonad.lean | 0d835fe86e5b0444111361ed2c889e5a1c1b1a02 | [
"Apache-2.0"
] | permissive | GaloisInc/lean-llvm | 7cc196172fe02ff3554edba6cc82f333c30fdc2b | 36e2ec604ae22d8ec1b1b66eca0f8887880db6c6 | refs/heads/master | 1,637,359,020,356 | 1,629,332,114,000 | 1,629,402,464,000 | 146,700,234 | 29 | 1 | Apache-2.0 | 1,631,225,695,000 | 1,535,607,191,000 | Lean | UTF-8 | Lean | false | false | 6,749 | lean | import Init.Data.Array
import Init.Data.Int
import Std.Data.RBMap
import Init.Data.String
import Galois.Data.Bitvec
import LeanLLVM.AST
import LeanLLVM.PP
import LeanLLVM.TypeContext
import LeanLLVM.Value
open Std (RBMap)
namespace LLVM
inductive trace_event : Type
| load (ptr : bitvec 64) (mt:mem_type) (val:Sim.Value)
| store (ptr : bitvec 64) (mt:mem_type) (val:Sim.Value)
| alloca (ptr : bitvec 64) (sz : Nat)
namespace trace_event
def asString : trace_event -> String
| load ptr mt val => "LOAD " ++ ptr.pp_hex ++ " " ++ val.pretty.render
| store ptr mt val => "STORE " ++ ptr.pp_hex ++ " " ++ val.pretty.render
| alloca ptr sz => "ALLOCA " ++ ptr.pp_hex ++ " " ++ toString sz
end trace_event
structure frame :=
(locals : Sim.regMap)
(func : Define)
(curr : BlockLabel)
(prev : Option BlockLabel)
(framePtr : Nat)
instance frameInh : Inhabited frame :=
⟨{ locals := Std.RBMap.empty,
func :=
{ linkage := none,
retType := PrimType.void,
name := ⟨""⟩,
args := Array.empty,
varArgs := false,
attrs := Array.empty,
sec := none,
gc := none,
body := Array.empty,
metadata := Strmap.empty,
comdat := none
},
curr := ⟨Ident.named ""⟩,
prev := none,
framePtr := 0
}⟩
structure State :=
(mem : Sim.memMap)
(mod : Module)
(dl : DataLayout)
(heapAllocPtr : Nat)
(stackPtr : Nat)
(symmap : RBMap Symbol (bitvec 64) Ord.compare)
(revsymmap : RBMap (bitvec 64) Symbol Ord.compare)
structure SimConts (z:Type) :=
(kerr : IO.Error → z) /- error continuation -/
(kret : Option Sim.Value → State → z) /- return continuation -/
(kcall : (Option Sim.Value → State → z) → Symbol → List Sim.Value → State → z)
/- call continuation -/
(kjump : BlockLabel → frame → State → z) /- jump continuation -/
(ktrace : trace_event -> z -> z ) /- trace operation -/
structure Sim (a:Type) :=
(runSim : ∀{z:Type}, SimConts z → (a → frame → State → z) → (frame → State → z))
namespace Sim
instance {a:Type} : Inhabited (Sim a) :=
⟨ ⟨λconts k f st => conts.kerr (IO.userError "black hole")⟩ ⟩
instance monad : Monad Sim :=
{ bind := λmx mf => Sim.mk (λconts k =>
mx.runSim conts (λx => (mf x).runSim conts k))
, pure := λx => Sim.mk (λ_ k => k x)
}
instance monadExcept : MonadExcept IO.Error Sim :=
{ throw := λerr => Sim.mk (λconts _k _frm _st => conts.kerr err)
, tryCatch := λm handle => Sim.mk (λconts k frm st =>
let conts' := { conts with kerr := λerr => (handle err).runSim conts k frm st };
m.runSim conts' k frm st)
}
def setFrame (frm:frame) : Sim Unit :=
Sim.mk (λ _ k _ st => k () frm st)
def getFrame : Sim frame :=
Sim.mk (λ _ k frm st => k frm frm st)
def modifyFrame (f: frame → frame) : Sim Unit :=
Sim.mk (λ _ k frm st => k () (f frm) st)
def getState : Sim State :=
Sim.mk (λ _ k frm st => k st frm st)
def setState (st:State) : Sim Unit :=
Sim.mk (λ _ k frm _ => k () frm st)
def assignReg (reg:Ident) (v:Value) : Sim Unit :=
modifyFrame (λfrm => { frm with locals := Std.RBMap.insert frm.locals reg v })
def trace (ev:trace_event) : Sim Unit :=
Sim.mk (λ conts k frm st => conts.ktrace ev (k () frm st))
def lookupReg (reg:Ident) : Sim Value := do
let frm ← getFrame
match Std.RBMap.find? frm.locals reg with
| none => throw (IO.userError ("unassigned register: " ++ reg.asString))
| some v => pure v
def returnVoid {a} : Sim a :=
Sim.mk (λ conts _k frm st => conts.kret none { st with stackPtr := frm.framePtr })
def returnValue {a} (v:Sim.Value) : Sim a :=
Sim.mk (λ conts _k frm st => conts.kret (some v) { st with stackPtr := frm.framePtr })
def jump {a} (l:BlockLabel) : Sim a :=
Sim.mk (λ conts _k frm st => conts.kjump l frm st)
def call (s:Symbol) (args:List Value) : Sim (Option Value) :=
Sim.mk (λ conts k frm st => conts.kcall (λv => k v frm) s args st)
def eval_mem_type (t:LLVMType) : Sim mem_type := do
let st ← Sim.getState
match lift_mem_type st.dl st.mod.types t with
| none => throw (IO.userError ("could not lift type: " ++ (pp t).render))
| some mt => pure mt
partial def eval : mem_type → LLVM.Value → Sim Sim.Value
| _, Value.ident i => Sim.lookupReg i
| mem_type.int w, Value.integer n => pure (Value.bv (bitvec.of_int w n))
| mem_type.int w, Value.bool true => pure (Value.bv (bitvec.of_int w 1))
| mem_type.int w, Value.bool false => pure (Value.bv (bitvec.of_int w 0))
| mem_type.int w, Value.null => pure (Value.bv (bitvec.of_int w 0))
| mem_type.int w, Value.zeroInit => pure (Value.bv (bitvec.of_int w 0))
| mem_type.int w, Value.undef => pure (Value.bv (bitvec.of_int w 0)) --???
| mem_type.ptr _, Value.symbol s => do
let st ← Sim.getState;
match st.symmap.find? s with
| some ptr => pure (Value.bv ptr)
| none => throw (IO.userError ("could not resolve symbol: " ++ s.symbol))
| mem_type.array _n eltp, LLVM.Value.array _tp vs => do
let vs' <- vs.mapM (eval eltp)
pure (Value.array eltp vs')
| _, v => throw (IO.userError ("bad Value/type in evaluation: " ++ (pp v).render))
def eval_typed (tv:Typed LLVM.Value) : Sim Sim.Value := do
let mt ← eval_mem_type tv.type
eval mt tv.value
end Sim
-- Heap allocation counts up. Find the next aligned Value and return it,
-- advancing the heap allocation pointer x bytes beyond.
def allocOnHeap (sz:Nat) (a:Alignment) (st:State) : bitvec 64 × State :=
let ptr := padToAlignment st.heapAllocPtr a;
(bitvec.of_nat 64 ptr, { st with heapAllocPtr := ptr + sz })
-- Stack allocation counts down. Find the next aligned Value that provides
-- enough space and return it, advancing the stack pointer to this point.
def allocOnStack (sz:Nat) (a:Alignment) (st:State) : bitvec 64 × State :=
let ptr := padDownToAlignment (st.stackPtr - sz) a;
( bitvec.of_nat 64 ptr, { st with stackPtr := ptr })
def allocFunctionSymbol (s:Symbol) (st:State) : State :=
let (ptr, st') := allocOnHeap 16 align16 st; -- 16 bytes with 16 byte alignment, rather arbitrarily
{ st' with symmap := st.symmap.insert s ptr,
revsymmap := st.revsymmap.insert ptr s,
}
def linkSymbol (st:State) (x:Symbol × bitvec 64) : State :=
let (s,ptr) := x;
{ st with symmap := st.symmap.insert s ptr,
revsymmap := st.revsymmap.insert ptr s
}
def initializeState (mod : Module) (dl:DataLayout) (ls:List (Symbol × bitvec 64)) : State :=
ls.foldl linkSymbol
{ mem := Std.RBMap.empty
, mod := mod
, dl := dl
, heapAllocPtr := 0
, stackPtr := 2^64
, symmap := Std.RBMap.empty
, revsymmap := Std.RBMap.empty
}
end LLVM
|
5d5b220aef9aefe9248f6900dd09445d3cdc6d68 | 55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5 | /src/data/polynomial/div.lean | 5acda6e53991b4504bfb05b3be45e895445fc6ff | [
"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 | 25,911 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker
-/
import data.polynomial.monic
import ring_theory.euclidean_domain
import ring_theory.multiplicity
/-!
# Division of univariate polynomials
The main defs are `div_by_monic` and `mod_by_monic`.
The compatibility between these is given by `mod_by_monic_add_div`.
We also define `root_multiplicity`.
-/
noncomputable theory
local attribute [instance, priority 100] classical.prop_decidable
open finset
namespace polynomial
universes u v w z
variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ}
section semiring
variables [semiring R] {p q : polynomial R}
section
/--
The coercion turning a `polynomial` into the function which reports the coefficient of a given
monomial `X^n`
-/
-- TODO we would like to completely remove this, but this requires fixing some proofs
def coeff_coe_to_fun : has_coe_to_fun (polynomial R) :=
finsupp.has_coe_to_fun
local attribute [instance] coeff_coe_to_fun
lemma apply_eq_coeff : p n = coeff p n := rfl
end
/-- `div_X p` return a polynomial `q` such that `q * X + C (p.coeff 0) = p`.
It can be used in a semiring where the usual division algorithm is not possible -/
def div_X (p : polynomial R) : polynomial R :=
{ to_fun := λ n, p.coeff (n + 1),
support := ⟨(p.support.filter (> 0)).1.map (λ n, n - 1),
multiset.nodup_map_on begin
simp only [finset.mem_def.symm, finset.mem_erase, finset.mem_filter],
assume x hx y hy hxy,
rwa [← @add_right_cancel_iff _ _ 1, nat.sub_add_cancel hx.2,
nat.sub_add_cancel hy.2] at hxy
end
(p.support.filter (> 0)).2⟩,
mem_support_to_fun := λ n,
suffices (∃ (a : ℕ), (¬coeff p a = 0 ∧ a > 0) ∧ a - 1 = n) ↔
¬coeff p (n + 1) = 0,
by simpa [finset.mem_def.symm],
⟨λ ⟨a, ha⟩, by rw [← ha.2, nat.sub_add_cancel ha.1.2]; exact ha.1.1,
λ h, ⟨n + 1, ⟨h, nat.succ_pos _⟩, nat.succ_sub_one _⟩⟩ }
lemma div_X_mul_X_add (p : polynomial R) : div_X p * X + C (p.coeff 0) = p :=
ext $ λ n,
nat.cases_on n
(by simp)
(by simp [coeff_C, nat.succ_ne_zero, coeff_mul_X, div_X])
@[simp] lemma div_X_C (a : R) : div_X (C a) = 0 :=
ext $ λ n, by cases n; simp [div_X, coeff_C]; simp [coeff]
lemma div_X_eq_zero_iff : div_X p = 0 ↔ p = C (p.coeff 0) :=
⟨λ h, by simpa [eq_comm, h] using div_X_mul_X_add p,
λ h, by rw [h, div_X_C]⟩
lemma div_X_add : div_X (p + q) = div_X p + div_X q :=
ext $ by simp [div_X]
lemma degree_div_X_lt (hp0 : p ≠ 0) : (div_X p).degree < p.degree :=
by haveI := nonzero.of_polynomial_ne hp0; exact
calc (div_X p).degree < (div_X p * X + C (p.coeff 0)).degree :
if h : degree p ≤ 0
then begin
have h' : C (p.coeff 0) ≠ 0, by rwa [← eq_C_of_degree_le_zero h],
rw [eq_C_of_degree_le_zero h, div_X_C, degree_zero, zero_mul, zero_add],
exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 $
by simp [h'])),
end
else
have hXp0 : div_X p ≠ 0,
by simpa [div_X_eq_zero_iff, -not_le, degree_le_zero_iff] using h,
have leading_coeff (div_X p) * leading_coeff X ≠ 0, by simpa,
have degree (C (p.coeff 0)) < degree (div_X p * X),
from calc degree (C (p.coeff 0)) ≤ 0 : degree_C_le
... < 1 : dec_trivial
... = degree (X : polynomial R) : degree_X.symm
... ≤ degree (div_X p * X) :
by rw [← zero_add (degree X), degree_mul' this];
exact add_le_add
(by rw [zero_le_degree_iff, ne.def, div_X_eq_zero_iff];
exact λ h0, h (h0.symm ▸ degree_C_le))
(le_refl _),
by rw [add_comm, degree_add_eq_of_degree_lt this];
exact degree_lt_degree_mul_X hXp0
... = p.degree : by rw div_X_mul_X_add
/-- An induction principle for polynomials, valued in Sort* instead of Prop. -/
@[elab_as_eliminator] noncomputable def rec_on_horner
{M : polynomial R → Sort*} : Π (p : polynomial R),
M 0 →
(Π p a, coeff p 0 = 0 → a ≠ 0 → M p → M (p + C a)) →
(Π p, p ≠ 0 → M p → M (p * X)) →
M p
| p := λ M0 MC MX,
if hp : p = 0 then eq.rec_on hp.symm M0
else
have wf : degree (div_X p) < degree p,
from degree_div_X_lt hp,
by rw [← div_X_mul_X_add p] at *;
exact
if hcp0 : coeff p 0 = 0
then by rw [hcp0, C_0, add_zero];
exact MX _ (λ h : div_X p = 0, by simpa [h, hcp0] using hp)
(rec_on_horner _ M0 MC MX)
else MC _ _ (coeff_mul_X_zero _) hcp0 (if hpX0 : div_X p = 0
then show M (div_X p * X), by rw [hpX0, zero_mul]; exact M0
else MX (div_X p) hpX0 (rec_on_horner _ M0 MC MX))
using_well_founded {dec_tac := tactic.assumption}
@[elab_as_eliminator] lemma degree_pos_induction_on
{P : polynomial R → Prop} (p : polynomial R) (h0 : 0 < degree p)
(hC : ∀ {a}, a ≠ 0 → P (C a * X))
(hX : ∀ {p}, 0 < degree p → P p → P (p * X))
(hadd : ∀ {p} {a}, 0 < degree p → P p → P (p + C a)) : P p :=
rec_on_horner p
(λ h, by rw degree_zero at h; exact absurd h dec_trivial)
(λ p a _ _ ih h0,
have 0 < degree p,
from lt_of_not_ge (λ h, (not_lt_of_ge degree_C_le) $
by rwa [eq_C_of_degree_le_zero h, ← C_add] at h0),
hadd this (ih this))
(λ p _ ih h0',
if h0 : 0 < degree p
then hX h0 (ih h0)
else by rw [eq_C_of_degree_le_zero (le_of_not_gt h0)] at *;
exact hC (λ h : coeff p 0 = 0,
by simpa [h, nat.not_lt_zero] using h0'))
h0
end semiring
section comm_semiring
variables [comm_semiring R]
theorem X_dvd_iff {α : Type u} [comm_semiring α] {f : polynomial α} : X ∣ f ↔ f.coeff 0 = 0 :=
⟨λ ⟨g, hfg⟩, by rw [hfg, mul_comm, coeff_mul_X_zero],
λ hf, ⟨f.div_X, by rw [mul_comm, ← add_zero (f.div_X * X), ← C_0, ← hf, div_X_mul_X_add]⟩⟩
end comm_semiring
section comm_semiring
variables [comm_semiring R] {p q : polynomial R}
lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p)
(hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q :=
have zn0 : (0 : R) ≠ 1, from λ h, by haveI := subsingleton_of_zero_eq_one h;
exact hq (subsingleton.elim _ _),
⟨nat_degree q, λ ⟨r, hr⟩,
have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction,
have hr0 : r ≠ 0, from λ hr0, by simp * at *,
have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1,
by simp [show _ = _, from hmp],
have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0,
from hpn1.symm ▸ zn0.symm,
have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0,
by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1,
one_pow, one_mul, ne.def, hr0]; simp,
have hpn0 : p ^ (nat_degree q + 1) ≠ 0,
from mt leading_coeff_eq_zero.2 $
by rw [leading_coeff_pow' hpn0', show _ = _, from hmp, one_pow]; exact zn0.symm,
have hnp : 0 < nat_degree p,
by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0];
exact hp,
begin
have := congr_arg nat_degree hr,
rw [nat_degree_mul' hpnr0, nat_degree_pow' hpn0', add_mul, add_assoc] at this,
exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_one_le_right' (nat.zero_le _) hnp)
(add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this
end⟩
end comm_semiring
section ring
variables [ring R] {p q : polynomial R}
lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) :
degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p :=
have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2,
have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) *
leading_coeff q ≠ 0,
by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one],
if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0
then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2))
else
have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic h.2 hq,
have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1
(by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0];
exact h.1),
degree_sub_lt
(by rw [degree_mul' hpq, degree_monomial _ hp, degree_eq_nat_degree h.2,
degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt])
h.2
(by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one])
/-- See `div_by_monic`. -/
noncomputable def div_mod_by_monic_aux : Π (p : polynomial R) {q : polynomial R},
monic q → polynomial R × polynomial R
| p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then
let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in
have wf : _ := div_wf_lemma h hq,
let dm := div_mod_by_monic_aux (p - z * q) hq in
⟨z + dm.1, dm.2⟩
else ⟨0, p⟩
using_well_founded {dec_tac := tactic.assumption}
/-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/
def div_by_monic (p q : polynomial R) : polynomial R :=
if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0
/-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/
def mod_by_monic (p q : polynomial R) : polynomial R :=
if hq : monic q then (div_mod_by_monic_aux p hq).2 else p
infixl ` /ₘ ` : 70 := div_by_monic
infixl ` %ₘ ` : 70 := mod_by_monic
lemma degree_mod_by_monic_lt : ∀ (p : polynomial R) {q : polynomial R} (hq : monic q)
(hq0 : q ≠ 0), degree (p %ₘ q) < degree q
| p := λ q hq hq0,
if h : degree q ≤ degree p ∧ p ≠ 0 then
have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq,
have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q :=
degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q)
hq hq0,
begin
unfold mod_by_monic at this ⊢,
unfold div_mod_by_monic_aux,
rw dif_pos hq at this ⊢,
rw if_pos h,
exact this
end
else
or.cases_on (not_and_distrib.1 h) begin
unfold mod_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h],
exact lt_of_not_ge,
end
begin
assume hp,
unfold mod_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h, not_not.1 hp],
exact lt_of_le_of_ne bot_le
(ne.symm (mt degree_eq_bot.1 hq0)),
end
using_well_founded {dec_tac := tactic.assumption}
@[simp] lemma zero_mod_by_monic (p : polynomial R) : 0 %ₘ p = 0 :=
begin
unfold mod_by_monic div_mod_by_monic_aux,
by_cases hp : monic p,
{ rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] },
{ rw [dif_neg hp] }
end
@[simp] lemma zero_div_by_monic (p : polynomial R) : 0 /ₘ p = 0 :=
begin
unfold div_by_monic div_mod_by_monic_aux,
by_cases hp : monic p,
{ rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] },
{ rw [dif_neg hp] }
end
@[simp] lemma mod_by_monic_zero (p : polynomial R) : p %ₘ 0 = p :=
if h : monic (0 : polynomial R) then (subsingleton_of_monic_zero h).1 _ _ else
by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h
@[simp] lemma div_by_monic_zero (p : polynomial R) : p /ₘ 0 = 0 :=
if h : monic (0 : polynomial R) then (subsingleton_of_monic_zero h).1 _ _ else
by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h
lemma div_by_monic_eq_of_not_monic (p : polynomial R) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq
lemma mod_by_monic_eq_of_not_monic (p : polynomial R) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq
lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q :=
⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0,
λ h, have ¬ degree q ≤ degree p := not_le_of_gt h,
by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩
theorem degree_mod_by_monic_le (p : polynomial R) {q : polynomial R}
(hq : monic q) : degree (p %ₘ q) ≤ degree q :=
decidable.by_cases
(assume H : q = 0, by rw [monic, H, leading_coeff_zero] at hq;
have : (0:polynomial R) = 1 := (by rw [← C_0, ← C_1, hq]);
exact le_of_eq (congr_arg _ $ eq_of_zero_eq_one this (p %ₘ q) q))
(assume H : q ≠ 0, le_of_lt $ degree_mod_by_monic_lt _ hq H)
end ring
section comm_ring
variables [comm_ring R] {p q : polynomial R}
lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial R) {q : polynomial R} (hq : monic q),
p %ₘ q = p - q * (p /ₘ q)
| p := λ q hq,
if h : degree q ≤ degree p ∧ p ≠ 0 then
have wf : _ := div_wf_lemma h hq,
have ih : _ := mod_by_monic_eq_sub_mul_div
(p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq,
begin
unfold mod_by_monic div_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_pos h],
rw [mod_by_monic, dif_pos hq] at ih,
refine ih.trans _,
unfold div_by_monic,
rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm]
end
else
begin
unfold mod_by_monic div_by_monic div_mod_by_monic_aux,
rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero]
end
using_well_founded {dec_tac := tactic.assumption}
lemma mod_by_monic_add_div (p : polynomial R) {q : polynomial R} (hq : monic q) :
p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq)
lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q :=
⟨λ h, by have := mod_by_monic_add_div p hq;
rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this,
λ h, have ¬ degree q ≤ degree p := not_le_of_gt h,
by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩
lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) :
degree q + degree (p /ₘ q) = degree p :=
if hq0 : q = 0 then
have ∀ (p : polynomial R), p = 0,
from λ p, (@subsingleton_of_monic_zero R _ (hq0 ▸ hq)).1 _ _,
by rw [this (p /ₘ q), this p, this q]; refl
else
have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt],
have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 :=
by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero],
have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) :=
calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0
... ≤ _ : by rw [degree_mul' hlc, degree_eq_nat_degree hq0,
degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe];
exact nat.le_add_right _ _,
calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul' hlc)
... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm
... = _ : congr_arg _ (mod_by_monic_add_div _ hq)
lemma degree_div_by_monic_le (p q : polynomial R) : degree (p /ₘ q) ≤ degree p :=
if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl]
else if hq : monic q then
have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq,
if h : degree q ≤ degree p
then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0,
degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))];
exact with_bot.coe_le_coe.2 (nat.le_add_left _ _)
else
by unfold div_by_monic div_mod_by_monic_aux;
simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le]
else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le
lemma degree_div_by_monic_lt (p : polynomial R) {q : polynomial R} (hq : monic q)
(hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p :=
have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq,
if hpq : degree p < degree q
then begin
rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0],
exact with_bot.bot_lt_some _
end
else begin
rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0,
degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)],
exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left
(with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q))
end
theorem nat_degree_div_by_monic {R : Type u} [comm_ring R] (f : polynomial R) {g : polynomial R}
(hg : g.monic) : nat_degree (f /ₘ g) = nat_degree f - nat_degree g :=
begin
by_cases h01 : (0 : R) = 1,
{ haveI := subsingleton_of_zero_eq_one h01,
rw [subsingleton.elim (f /ₘ g) 0, subsingleton.elim f 0, subsingleton.elim g 0,
nat_degree_zero] },
haveI : nontrivial R := ⟨⟨0, 1, h01⟩⟩,
by_cases hfg : f /ₘ g = 0,
{ rw [hfg, nat_degree_zero], rw div_by_monic_eq_zero_iff hg hg.ne_zero at hfg,
rw nat.sub_eq_zero_of_le (nat_degree_le_nat_degree $ le_of_lt hfg) },
have hgf := hfg, rw div_by_monic_eq_zero_iff hg hg.ne_zero at hgf, push_neg at hgf,
have := degree_add_div_by_monic hg hgf,
have hf : f ≠ 0, { intro hf, apply hfg, rw [hf, zero_div_by_monic] },
rw [degree_eq_nat_degree hf, degree_eq_nat_degree hg.ne_zero, degree_eq_nat_degree hfg,
← with_bot.coe_add, with_bot.coe_eq_coe] at this,
rw [← this, nat.add_sub_cancel_left]
end
lemma div_mod_by_monic_unique {f g} (q r : polynomial R) (hg : monic g)
(h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r :=
if hg0 : g = 0 then by split; exact (subsingleton_of_monic_zero
(hg0 ▸ hg : monic (0 : polynomial R))).1 _ _
else
have h₁ : r - f %ₘ g = -g * (q - f /ₘ g),
from eq_of_sub_eq_zero
(by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)];
simp [mul_add, mul_comm, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]),
have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)),
by simp [h₁],
have h₄ : degree (r - f %ₘ g) < degree g,
from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (-(f %ₘ g))) :
degree_add_le _ _
... < degree g : max_lt_iff.2 ⟨h.2, by rw degree_neg; exact degree_mod_by_monic_lt _ hg hg0⟩,
have h₅ : q - (f /ₘ g) = 0,
from by_contradiction
(λ hqf, not_le_of_gt h₄ $
calc degree g ≤ degree g + degree (q - f /ₘ g) :
by erw [degree_eq_nat_degree hg0, degree_eq_nat_degree hqf,
with_bot.coe_le_coe];
exact nat.le_add_right _ _
... = degree (r - f %ₘ g) :
by rw [h₂, degree_mul']; simpa [monic.def.1 hg]),
⟨eq.symm $ eq_of_sub_eq_zero h₅,
eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩
lemma map_mod_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) :
(p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f :=
if h01 : (0 : S) = 1 then by haveI := subsingleton_of_zero_eq_one h01;
exact ⟨subsingleton.elim _ _, subsingleton.elim _ _⟩
else
have h01R : (0 : R) ≠ 1, from mt (congr_arg f)
(by rwa [is_semiring_hom.map_one f, is_semiring_hom.map_zero f]),
have map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q),
from (div_mod_by_monic_unique ((p /ₘ q).map f) _ (monic_map f hq)
⟨eq.symm $ by rw [← map_mul, ← map_add, mod_by_monic_add_div _ hq],
calc _ ≤ degree (p %ₘ q) : degree_map_le _
... < degree q : degree_mod_by_monic_lt _ hq
$ (ne_zero_of_monic_of_zero_ne_one hq h01R)
... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _
(by rw [monic.def.1 hq, is_semiring_hom.map_one f]; exact ne.symm h01)⟩),
⟨this.1.symm, this.2.symm⟩
lemma map_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) :
(p /ₘ q).map f = p.map f /ₘ q.map f :=
(map_mod_div_by_monic f hq).1
lemma map_mod_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) :
(p %ₘ q).map f = p.map f %ₘ q.map f :=
(map_mod_div_by_monic f hq).2
lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p :=
⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add];
exact dvd_mul_right _ _,
λ h, if hq0 : q = 0 then by rw hq0 at hq;
exact (subsingleton_of_monic_zero hq).1 _ _
else
let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in
by_contradiction (λ hpq0,
have hmod : p %ₘ q = q * (r - p /ₘ q) :=
by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr],
have degree (q * (r - p /ₘ q)) < degree q :=
hmod ▸ degree_mod_by_monic_lt _ hq hq0,
have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 :=
λ h, hpq0 $ leading_coeff_eq_zero.1
(by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]),
have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 :=
by rwa [monic.def.1 hq, one_mul],
by rw [degree_mul' hlc, degree_eq_nat_degree hq0,
degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this;
exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩
theorem map_dvd_map [comm_ring S] (f : R →+* S) (hf : function.injective f) {x y : polynomial R}
(hx : x.monic) : x.map f ∣ y.map f ↔ x ∣ y :=
begin
rw [← dvd_iff_mod_by_monic_eq_zero hx, ← dvd_iff_mod_by_monic_eq_zero (monic_map f hx),
← map_mod_by_monic f hx],
exact ⟨λ H, map_injective f hf $ by rw [H, map_zero],
λ H, by rw [H, map_zero]⟩
end
@[simp] lemma mod_by_monic_one (p : polynomial R) : p %ₘ 1 = 0 :=
(dvd_iff_mod_by_monic_eq_zero (by convert monic_one)).2 (one_dvd _)
@[simp] lemma div_by_monic_one (p : polynomial R) : p /ₘ 1 = p :=
by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp
@[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial R) (a : R) :
p %ₘ (X - C a) = C (p.eval a) :=
if h0 : (0 : R) = 1 then by letI := subsingleton_of_zero_eq_one h0; exact subsingleton.elim _ _
else
by haveI : nontrivial R := nontrivial_of_ne 0 1 h0; exact
have h : (p %ₘ (X - C a)).eval a = p.eval a :=
by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul,
eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero],
have degree (p %ₘ (X - C a)) < 1 :=
degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸
ne_zero_of_monic (monic_X_sub_C _)),
have degree (p %ₘ (X - C a)) ≤ 0 :=
begin
cases (degree (p %ₘ (X - C a))),
{ exact bot_le },
{ exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) }
end,
begin
rw [eq_C_of_degree_le_zero this, eval_C] at h,
rw [eq_C_of_degree_le_zero this, h]
end
lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a :=
⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul],
λ h : p.eval a = 0,
by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)};
rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩
lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a :=
⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _),
mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h,
λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩
lemma mod_by_monic_X (p : polynomial R) : p %ₘ X = C (p.eval 0) :=
by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero]
section multiplicity
/-- An algorithm for deciding polynomial divisibility.
The algorithm is "compute `p %ₘ q` and compare to `0`". `
See `polynomial.mod_by_monic` for the algorithm that computes `%ₘ`.
-/
def decidable_dvd_monic (p : polynomial R) (hq : monic q) : decidable (q ∣ p) :=
decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq)
open_locale classical
lemma multiplicity_X_sub_C_finite (a : R) (h0 : p ≠ 0) :
multiplicity.finite (X - C a) p :=
multiplicity_finite_of_degree_pos_of_monic
(have (0 : R) ≠ 1, from (λ h, by haveI := subsingleton_of_zero_eq_one h;
exact h0 (subsingleton.elim _ _)),
by haveI : nontrivial R := ⟨⟨0, 1, this⟩⟩; rw degree_X_sub_C; exact dec_trivial)
(monic_X_sub_C _) h0
/-- The largest power of `X - C a` which divides `p`.
This is computable via the divisibility algorithm `decidable_dvd_monic`. -/
def root_multiplicity (a : R) (p : polynomial R) : ℕ :=
if h0 : p = 0 then 0
else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) :=
λ n, @not.decidable _ (decidable_dvd_monic p (monic_pow (monic_X_sub_C a) (n + 1))) in
by exactI nat.find (multiplicity_X_sub_C_finite a h0)
lemma root_multiplicity_eq_multiplicity (p : polynomial R) (a : R) :
root_multiplicity a p = if h0 : p = 0 then 0 else
(multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) :=
by simp [multiplicity, root_multiplicity, roption.dom];
congr; funext; congr
lemma pow_root_multiplicity_dvd (p : polynomial R) (a : R) :
(X - C a) ^ root_multiplicity a p ∣ p :=
if h : p = 0 then by simp [h]
else by rw [root_multiplicity_eq_multiplicity, dif_neg h];
exact multiplicity.pow_multiplicity_dvd _
lemma div_by_monic_mul_pow_root_multiplicity_eq
(p : polynomial R) (a : R) :
p /ₘ ((X - C a) ^ root_multiplicity a p) *
(X - C a) ^ root_multiplicity a p = p :=
have monic ((X - C a) ^ root_multiplicity a p),
from monic_pow (monic_X_sub_C _) _,
by conv_rhs { rw [← mod_by_monic_add_div p this,
(dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] };
simp [mul_comm]
lemma eval_div_by_monic_pow_root_multiplicity_ne_zero
{p : polynomial R} (a : R) (hp : p ≠ 0) :
(p /ₘ ((X - C a) ^ root_multiplicity a p)).eval a ≠ 0 :=
begin
haveI : nontrivial R := nonzero.of_polynomial_ne hp,
rw [ne.def, ← is_root.def, ← dvd_iff_is_root],
rintros ⟨q, hq⟩,
have := div_by_monic_mul_pow_root_multiplicity_eq p a,
rw [mul_comm, hq, ← mul_assoc, ← pow_succ',
root_multiplicity_eq_multiplicity, dif_neg hp] at this,
exact multiplicity.is_greatest'
(multiplicity_finite_of_degree_pos_of_monic
(show (0 : with_bot ℕ) < degree (X - C a),
by rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) hp)
(nat.lt_succ_self _) (dvd_of_mul_right_eq _ this)
end
end multiplicity
end comm_ring
end polynomial
|
0525cead5a29578c7c3f58155b613457dd94193d | dd0f5513e11c52db157d2fcc8456d9401a6cd9da | /10_Structures_and_Records.org.21.lean | dadbbb4ffb61cbcbb4d5125600b089aabe2f2fa9 | [] | 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 | 771 | lean | import standard
structure has_mul [class] (A : Type) :=
mk :: (mul : A → A → A)
structure has_one [class] (A : Type) :=
mk :: (one : A)
structure has_inv [class] (A : Type) :=
mk :: (inv : A → A)
infixl `*` := has_mul.mul
postfix `⁻¹` := has_inv.inv
notation 1 := has_one.one
structure semigroup [class] (A : Type) extends has_mul A :=
mk :: (assoc : ∀ a b c, mul (mul a b) c = mul a (mul b c))
structure comm_semigroup [class] (A : Type) extends semigroup A :=
mk :: (comm : ∀ a b, mul a b = mul b a)
structure monoid [class] (A : Type) extends semigroup A, has_one A :=
mk :: (right_id : ∀ a, mul a one = a) (left_id : ∀ a, mul one a = a)
structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A
print prefix comm_monoid
|
2655a742a467bff597e1bc03d165eeee81fdf581 | 4d2583807a5ac6caaffd3d7a5f646d61ca85d532 | /src/ring_theory/power_basis.lean | 4f9239e6df439794b287e2d16370929cc44c3491 | [
"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 | 20,127 | lean | /-
Copyright (c) 2020 Anne Baanen. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Anne Baanen
-/
import field_theory.minpoly
/-!
# Power basis
This file defines a structure `power_basis R S`, giving a basis of the
`R`-algebra `S` as a finite list of powers `1, x, ..., x^n`.
For example, if `x` is algebraic over a ring/field, adjoining `x`
gives a `power_basis` structure generated by `x`.
## Definitions
* `power_basis R A`: a structure containing an `x` and an `n` such that
`1, x, ..., x^n` is a basis for the `R`-algebra `A` (viewed as an `R`-module).
* `finrank (hf : f ≠ 0) : finite_dimensional.finrank K (adjoin_root f) = f.nat_degree`,
the dimension of `adjoin_root f` equals the degree of `f`
* `power_basis.lift (pb : power_basis R S)`: if `y : S'` satisfies the same
equations as `pb.gen`, this is the map `S →ₐ[R] S'` sending `pb.gen` to `y`
* `power_basis.equiv`: if two power bases satisfy the same equations, they are
equivalent as algebras
## Implementation notes
Throughout this file, `R`, `S`, ... are `comm_ring`s, `A`, `B`, ... are
`comm_ring` with `is_domain`s and `K`, `L`, ... are `field`s.
`S` is an `R`-algebra, `B` is an `A`-algebra, `L` is a `K`-algebra.
## Tags
power basis, powerbasis
-/
open polynomial
variables {R S T : Type*} [comm_ring R] [comm_ring S] [comm_ring T]
variables [algebra R S] [algebra S T] [algebra R T] [is_scalar_tower R S T]
variables {A B : Type*} [comm_ring A]
[comm_ring B] [is_domain B] [algebra A B]
variables {K L : Type*} [field K] [field L] [algebra K L]
/-- `pb : power_basis R S` states that `1, pb.gen, ..., pb.gen ^ (pb.dim - 1)`
is a basis for the `R`-algebra `S` (viewed as `R`-module).
This is a structure, not a class, since the same algebra can have many power bases.
For the common case where `S` is defined by adjoining an integral element to `R`,
the canonical power basis is given by `{algebra,intermediate_field}.adjoin.power_basis`.
-/
@[nolint has_inhabited_instance]
structure power_basis (R S : Type*) [comm_ring R] [ring S] [algebra R S] :=
(gen : S)
(dim : ℕ)
(basis : basis (fin dim) R S)
(basis_eq_pow : ∀ i, basis i = gen ^ (i : ℕ))
namespace power_basis
@[simp] lemma coe_basis (pb : power_basis R S) :
⇑pb.basis = λ (i : fin pb.dim), pb.gen ^ (i : ℕ) :=
funext pb.basis_eq_pow
/-- Cannot be an instance because `power_basis` cannot be a class. -/
lemma finite_dimensional [algebra K S] (pb : power_basis K S) : finite_dimensional K S :=
finite_dimensional.of_fintype_basis pb.basis
lemma finrank [algebra K S] (pb : power_basis K S) : finite_dimensional.finrank K S = pb.dim :=
by rw [finite_dimensional.finrank_eq_card_basis pb.basis, fintype.card_fin]
lemma mem_span_pow' {x y : S} {d : ℕ} :
y ∈ submodule.span R (set.range (λ (i : fin d), x ^ (i : ℕ))) ↔
∃ f : polynomial R, f.degree < d ∧ y = aeval x f :=
begin
have : set.range (λ (i : fin d), x ^ (i : ℕ)) = (λ (i : ℕ), x ^ i) '' ↑(finset.range d),
{ ext n,
simp_rw [set.mem_range, set.mem_image, finset.mem_coe, finset.mem_range],
exact ⟨λ ⟨⟨i, hi⟩, hy⟩, ⟨i, hi, hy⟩, λ ⟨i, hi, hy⟩, ⟨⟨i, hi⟩, hy⟩⟩ },
simp only [this, finsupp.mem_span_image_iff_total, degree_lt_iff_coeff_zero,
exists_iff_exists_finsupp, coeff, aeval, eval₂_ring_hom', eval₂_eq_sum, polynomial.sum, support,
finsupp.mem_supported', finsupp.total, finsupp.sum, algebra.smul_def, eval₂_zero, exists_prop,
linear_map.id_coe, eval₂_one, id.def, not_lt, finsupp.coe_lsum, linear_map.coe_smul_right,
finset.mem_range, alg_hom.coe_mk, finset.mem_coe],
simp_rw [@eq_comm _ y],
exact iff.rfl
end
lemma mem_span_pow {x y : S} {d : ℕ} (hd : d ≠ 0) :
y ∈ submodule.span R (set.range (λ (i : fin d), x ^ (i : ℕ))) ↔
∃ f : polynomial R, f.nat_degree < d ∧ y = aeval x f :=
begin
rw mem_span_pow',
split;
{ rintros ⟨f, h, hy⟩,
refine ⟨f, _, hy⟩,
by_cases hf : f = 0,
{ simp only [hf, nat_degree_zero, degree_zero] at h ⊢,
exact lt_of_le_of_ne (nat.zero_le d) hd.symm <|> exact with_bot.bot_lt_coe d },
simpa only [degree_eq_nat_degree hf, with_bot.coe_lt_coe] using h },
end
lemma dim_ne_zero [h : nontrivial S] (pb : power_basis R S) : pb.dim ≠ 0 :=
λ h, not_nonempty_iff.mpr (h.symm ▸ fin.is_empty : is_empty (fin pb.dim)) pb.basis.index_nonempty
lemma dim_pos [nontrivial S] (pb : power_basis R S) : 0 < pb.dim :=
nat.pos_of_ne_zero pb.dim_ne_zero
lemma exists_eq_aeval [nontrivial S] (pb : power_basis R S) (y : S) :
∃ f : polynomial R, f.nat_degree < pb.dim ∧ y = aeval pb.gen f :=
(mem_span_pow pb.dim_ne_zero).mp (by simpa using pb.basis.mem_span y)
lemma exists_eq_aeval' (pb : power_basis R S) (y : S) :
∃ f : polynomial R, y = aeval pb.gen f :=
begin
nontriviality S,
obtain ⟨f, _, hf⟩ := exists_eq_aeval pb y,
exact ⟨f, hf⟩
end
lemma alg_hom_ext {S' : Type*} [semiring S'] [algebra R S']
(pb : power_basis R S) ⦃f g : S →ₐ[R] S'⦄ (h : f pb.gen = g pb.gen) :
f = g :=
begin
ext x,
obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x,
rw [← polynomial.aeval_alg_hom_apply, ← polynomial.aeval_alg_hom_apply, h]
end
section minpoly
open_locale big_operators
variable [algebra A S]
/-- `pb.minpoly_gen` is a minimal polynomial for `pb.gen`.
If `A` is not a field, it might not necessarily be *the* minimal polynomial,
however `nat_degree_minpoly` shows its degree is indeed minimal.
-/
noncomputable def minpoly_gen (pb : power_basis A S) : polynomial A :=
X ^ pb.dim -
∑ (i : fin pb.dim), C (pb.basis.repr (pb.gen ^ pb.dim) i) * X ^ (i : ℕ)
@[simp]
lemma aeval_minpoly_gen (pb : power_basis A S) : aeval pb.gen (minpoly_gen pb) = 0 :=
begin
simp_rw [minpoly_gen, alg_hom.map_sub, alg_hom.map_sum, alg_hom.map_mul, alg_hom.map_pow,
aeval_C, ← algebra.smul_def, aeval_X],
refine sub_eq_zero.mpr ((pb.basis.total_repr (pb.gen ^ pb.dim)).symm.trans _),
rw [finsupp.total_apply, finsupp.sum_fintype];
simp only [pb.coe_basis, zero_smul, eq_self_iff_true, implies_true_iff]
end
lemma dim_le_nat_degree_of_root (h : power_basis A S) {p : polynomial A}
(ne_zero : p ≠ 0) (root : aeval h.gen p = 0) :
h.dim ≤ p.nat_degree :=
begin
refine le_of_not_lt (λ hlt, ne_zero _),
let p_coeff : fin (h.dim) → A := λ i, p.coeff i,
suffices : ∀ i, p_coeff i = 0,
{ ext i,
by_cases hi : i < h.dim,
{ exact this ⟨i, hi⟩ },
exact coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le hlt (le_of_not_gt hi)) },
intro i,
refine linear_independent_iff'.mp h.basis.linear_independent _ _ _ i (finset.mem_univ _),
rw aeval_eq_sum_range' hlt at root,
rw finset.sum_fin_eq_sum_range,
convert root,
ext i,
split_ifs with hi,
{ simp_rw [coe_basis, p_coeff, fin.coe_mk] },
{ rw [coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le hlt (le_of_not_gt hi)),
zero_smul] }
end
lemma dim_le_degree_of_root (h : power_basis A S) {p : polynomial A}
(ne_zero : p ≠ 0) (root : aeval h.gen p = 0) :
↑h.dim ≤ p.degree :=
by { rw [degree_eq_nat_degree ne_zero, with_bot.coe_le_coe],
exact h.dim_le_nat_degree_of_root ne_zero root }
variables [is_domain A]
@[simp]
lemma degree_minpoly_gen (pb : power_basis A S) :
degree (minpoly_gen pb) = pb.dim :=
begin
unfold minpoly_gen,
rw degree_sub_eq_left_of_degree_lt; rw degree_X_pow,
apply degree_sum_fin_lt
end
@[simp]
lemma nat_degree_minpoly_gen (pb : power_basis A S) :
nat_degree (minpoly_gen pb) = pb.dim :=
nat_degree_eq_of_degree_eq_some pb.degree_minpoly_gen
lemma minpoly_gen_monic (pb : power_basis A S) : monic (minpoly_gen pb) :=
begin
apply monic_sub_of_left (monic_pow (monic_X) _),
rw degree_X_pow,
exact degree_sum_fin_lt _
end
lemma is_integral_gen (pb : power_basis A S) : is_integral A pb.gen :=
⟨minpoly_gen pb, minpoly_gen_monic pb, aeval_minpoly_gen pb⟩
@[simp]
lemma nat_degree_minpoly (pb : power_basis A S) :
(minpoly A pb.gen).nat_degree = pb.dim :=
begin
refine le_antisymm _
(dim_le_nat_degree_of_root pb (minpoly.ne_zero pb.is_integral_gen) (minpoly.aeval _ _)),
rw ← nat_degree_minpoly_gen,
apply nat_degree_le_of_degree_le,
rw ← degree_eq_nat_degree (minpoly_gen_monic pb).ne_zero,
exact minpoly.min _ _ (minpoly_gen_monic pb) (aeval_minpoly_gen pb)
end
@[simp]
lemma minpoly_gen_eq [algebra K S] (pb : power_basis K S) :
pb.minpoly_gen = minpoly K pb.gen :=
minpoly.unique K pb.gen pb.minpoly_gen_monic pb.aeval_minpoly_gen (λ p p_monic p_root,
pb.degree_minpoly_gen.symm ▸ pb.dim_le_degree_of_root p_monic.ne_zero p_root)
end minpoly
section equiv
variables [algebra A S] {S' : Type*} [comm_ring S'] [algebra A S']
lemma nat_degree_lt_nat_degree {p q : polynomial R} (hp : p ≠ 0) (hpq : p.degree < q.degree) :
p.nat_degree < q.nat_degree :=
begin
by_cases hq : q = 0, { rw [hq, degree_zero] at hpq, have := not_lt_bot hpq, contradiction },
rwa [degree_eq_nat_degree hp, degree_eq_nat_degree hq, with_bot.coe_lt_coe] at hpq
end
variables [is_domain A]
lemma constr_pow_aeval (pb : power_basis A S) {y : S'}
(hy : aeval y (minpoly A pb.gen) = 0) (f : polynomial A) :
pb.basis.constr A (λ i, y ^ (i : ℕ)) (aeval pb.gen f) = aeval y f :=
begin
rw [← aeval_mod_by_monic_eq_self_of_root (minpoly.monic pb.is_integral_gen) (minpoly.aeval _ _),
← @aeval_mod_by_monic_eq_self_of_root _ _ _ _ _ f _ (minpoly.monic pb.is_integral_gen) y hy],
by_cases hf : f %ₘ minpoly A pb.gen = 0,
{ simp only [hf, alg_hom.map_zero, linear_map.map_zero] },
have : (f %ₘ minpoly A pb.gen).nat_degree < pb.dim,
{ rw ← pb.nat_degree_minpoly,
apply nat_degree_lt_nat_degree hf,
exact degree_mod_by_monic_lt _ (minpoly.monic pb.is_integral_gen) },
rw [aeval_eq_sum_range' this, aeval_eq_sum_range' this, linear_map.map_sum],
refine finset.sum_congr rfl (λ i (hi : i ∈ finset.range pb.dim), _),
rw finset.mem_range at hi,
rw linear_map.map_smul,
congr,
rw [← fin.coe_mk hi, ← pb.basis_eq_pow ⟨i, hi⟩, basis.constr_basis]
end
lemma constr_pow_gen (pb : power_basis A S) {y : S'}
(hy : aeval y (minpoly A pb.gen) = 0) :
pb.basis.constr A (λ i, y ^ (i : ℕ)) pb.gen = y :=
by { convert pb.constr_pow_aeval hy X; rw aeval_X }
lemma constr_pow_algebra_map (pb : power_basis A S) {y : S'}
(hy : aeval y (minpoly A pb.gen) = 0) (x : A) :
pb.basis.constr A (λ i, y ^ (i : ℕ)) (algebra_map A S x) = algebra_map A S' x :=
by { convert pb.constr_pow_aeval hy (C x); rw aeval_C }
lemma constr_pow_mul (pb : power_basis A S) {y : S'}
(hy : aeval y (minpoly A pb.gen) = 0) (x x' : S) :
pb.basis.constr A (λ i, y ^ (i : ℕ)) (x * x') =
pb.basis.constr A (λ i, y ^ (i : ℕ)) x * pb.basis.constr A (λ i, y ^ (i : ℕ)) x' :=
begin
obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x,
obtain ⟨g, rfl⟩ := pb.exists_eq_aeval' x',
simp only [← aeval_mul, pb.constr_pow_aeval hy]
end
/-- `pb.lift y hy` is the algebra map sending `pb.gen` to `y`,
where `hy` states the higher powers of `y` are the same as the higher powers of `pb.gen`.
See `power_basis.lift_equiv` for a bundled equiv sending `⟨y, hy⟩` to the algebra map.
-/
noncomputable def lift (pb : power_basis A S) (y : S')
(hy : aeval y (minpoly A pb.gen) = 0) :
S →ₐ[A] S' :=
{ map_one' := by { convert pb.constr_pow_algebra_map hy 1 using 2; rw ring_hom.map_one },
map_zero' := by { convert pb.constr_pow_algebra_map hy 0 using 2; rw ring_hom.map_zero },
map_mul' := pb.constr_pow_mul hy,
commutes' := pb.constr_pow_algebra_map hy,
.. pb.basis.constr A (λ i, y ^ (i : ℕ)) }
@[simp] lemma lift_gen (pb : power_basis A S) (y : S')
(hy : aeval y (minpoly A pb.gen) = 0) :
pb.lift y hy pb.gen = y :=
pb.constr_pow_gen hy
@[simp] lemma lift_aeval (pb : power_basis A S) (y : S')
(hy : aeval y (minpoly A pb.gen) = 0) (f : polynomial A) :
pb.lift y hy (aeval pb.gen f) = aeval y f :=
pb.constr_pow_aeval hy f
/-- `pb.lift_equiv` states that roots of the minimal polynomial of `pb.gen` correspond to
maps sending `pb.gen` to that root.
This is the bundled equiv version of `power_basis.lift`.
If the codomain of the `alg_hom`s is an integral domain, then the roots form a multiset,
see `lift_equiv'` for the corresponding statement.
-/
@[simps]
noncomputable def lift_equiv (pb : power_basis A S) :
(S →ₐ[A] S') ≃ {y : S' // aeval y (minpoly A pb.gen) = 0} :=
{ to_fun := λ f, ⟨f pb.gen, by rw [aeval_alg_hom_apply, minpoly.aeval, f.map_zero]⟩,
inv_fun := λ y, pb.lift y y.2,
left_inv := λ f, pb.alg_hom_ext $ lift_gen _ _ _,
right_inv := λ y, subtype.ext $ lift_gen _ _ y.prop }
/-- `pb.lift_equiv'` states that elements of the root set of the minimal
polynomial of `pb.gen` correspond to maps sending `pb.gen` to that root. -/
@[simps {fully_applied := ff}]
noncomputable def lift_equiv' (pb : power_basis A S) :
(S →ₐ[A] B) ≃ {y : B // y ∈ ((minpoly A pb.gen).map (algebra_map A B)).roots} :=
pb.lift_equiv.trans ((equiv.refl _).subtype_equiv (λ x,
begin
rw [mem_roots, is_root.def, equiv.refl_apply, ← eval₂_eq_eval_map, ← aeval_def],
exact map_monic_ne_zero (minpoly.monic pb.is_integral_gen)
end))
/-- There are finitely many algebra homomorphisms `S →ₐ[A] B` if `S` is of the form `A[x]`
and `B` is an integral domain. -/
noncomputable def alg_hom.fintype (pb : power_basis A S) :
fintype (S →ₐ[A] B) :=
by letI := classical.dec_eq B; exact
fintype.of_equiv _ pb.lift_equiv'.symm
local attribute [irreducible] power_basis.lift
/-- `pb.equiv_of_root pb' h₁ h₂` is an equivalence of algebras with the same power basis,
where "the same" means that `pb` is a root of `pb'`s minimal polynomial and vice versa.
See also `power_basis.equiv_of_minpoly` which takes the hypothesis that the
minimal polynomials are identical.
-/
noncomputable def equiv_of_root
(pb : power_basis A S) (pb' : power_basis A S')
(h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) :
S ≃ₐ[A] S' :=
alg_equiv.of_alg_hom
(pb.lift pb'.gen h₂)
(pb'.lift pb.gen h₁)
(by { ext x, obtain ⟨f, hf, rfl⟩ := pb'.exists_eq_aeval' x, simp })
(by { ext x, obtain ⟨f, hf, rfl⟩ := pb.exists_eq_aeval' x, simp })
@[simp]
lemma equiv_of_root_aeval
(pb : power_basis A S) (pb' : power_basis A S')
(h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0)
(f : polynomial A) :
pb.equiv_of_root pb' h₁ h₂ (aeval pb.gen f) = aeval pb'.gen f :=
pb.lift_aeval _ h₂ _
@[simp]
lemma equiv_of_root_gen
(pb : power_basis A S) (pb' : power_basis A S')
(h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) :
pb.equiv_of_root pb' h₁ h₂ pb.gen = pb'.gen :=
pb.lift_gen _ h₂
@[simp]
lemma equiv_of_root_symm
(pb : power_basis A S) (pb' : power_basis A S')
(h₁ : aeval pb.gen (minpoly A pb'.gen) = 0) (h₂ : aeval pb'.gen (minpoly A pb.gen) = 0) :
(pb.equiv_of_root pb' h₁ h₂).symm = pb'.equiv_of_root pb h₂ h₁ :=
rfl
/-- `pb.equiv_of_minpoly pb' h` is an equivalence of algebras with the same power basis,
where "the same" means that they have identical minimal polynomials.
See also `power_basis.equiv_of_root` which takes the hypothesis that each generator is a root of the
other basis' minimal polynomial; `power_basis.equiv_root` is more general if `A` is not a field.
-/
noncomputable def equiv_of_minpoly
(pb : power_basis A S) (pb' : power_basis A S')
(h : minpoly A pb.gen = minpoly A pb'.gen) :
S ≃ₐ[A] S' :=
pb.equiv_of_root pb' (h ▸ minpoly.aeval _ _) (h.symm ▸ minpoly.aeval _ _)
@[simp]
lemma equiv_of_minpoly_aeval
(pb : power_basis A S) (pb' : power_basis A S')
(h : minpoly A pb.gen = minpoly A pb'.gen)
(f : polynomial A) :
pb.equiv_of_minpoly pb' h (aeval pb.gen f) = aeval pb'.gen f :=
pb.equiv_of_root_aeval pb' _ _ _
@[simp]
lemma equiv_of_minpoly_gen
(pb : power_basis A S) (pb' : power_basis A S')
(h : minpoly A pb.gen = minpoly A pb'.gen) :
pb.equiv_of_minpoly pb' h pb.gen = pb'.gen :=
pb.equiv_of_root_gen pb' _ _
@[simp]
lemma equiv_of_minpoly_symm
(pb : power_basis A S) (pb' : power_basis A S')
(h : minpoly A pb.gen = minpoly A pb'.gen) :
(pb.equiv_of_minpoly pb' h).symm = pb'.equiv_of_minpoly pb h.symm :=
rfl
end equiv
end power_basis
open power_basis
/-- Useful lemma to show `x` generates a power basis:
the powers of `x` less than the degree of `x`'s minimal polynomial are linearly independent. -/
lemma is_integral.linear_independent_pow [algebra K S] {x : S} (hx : is_integral K x) :
linear_independent K (λ (i : fin (minpoly K x).nat_degree), x ^ (i : ℕ)) :=
begin
rw linear_independent_iff,
intros p hp,
set f : polynomial K := p.sum (λ i, monomial i) with hf0,
have f_def : ∀ (i : fin _), f.coeff i = p i,
{ intro i,
simp only [f, finsupp.sum, coeff_monomial, finset_sum_coeff],
rw [finset.sum_eq_single, if_pos rfl],
{ intros b _ hb,
rw if_neg (mt (λ h, _) hb),
exact fin.coe_injective h },
{ intro hi,
split_ifs; { exact finsupp.not_mem_support_iff.mp hi } } },
have f_def' : ∀ i, f.coeff i = if hi : i < _ then p ⟨i, hi⟩ else 0,
{ intro i,
split_ifs with hi,
{ exact f_def ⟨i, hi⟩ },
simp only [f, finsupp.sum, coeff_monomial, finset_sum_coeff],
apply finset.sum_eq_zero,
rintro ⟨j, hj⟩ -,
apply if_neg (mt _ hi),
rintro rfl,
exact hj },
suffices : f = 0,
{ ext i, rw [← f_def, this, coeff_zero, finsupp.zero_apply] },
contrapose hp with hf,
intro h,
have : (minpoly K x).degree ≤ f.degree,
{ apply minpoly.degree_le_of_ne_zero K x hf,
convert h,
simp_rw [finsupp.total_apply, aeval_def, hf0, finsupp.sum, eval₂_finset_sum],
apply finset.sum_congr rfl,
rintro i -,
simp only [algebra.smul_def, eval₂_monomial] },
have : ¬ (minpoly K x).degree ≤ f.degree,
{ apply not_le_of_lt,
rw [degree_eq_nat_degree (minpoly.ne_zero hx), degree_lt_iff_coeff_zero],
intros i hi,
rw [f_def' i, dif_neg],
exact hi.not_lt },
contradiction
end
lemma is_integral.mem_span_pow [nontrivial R] {x y : S} (hx : is_integral R x)
(hy : ∃ f : polynomial R, y = aeval x f) :
y ∈ submodule.span R (set.range (λ (i : fin (minpoly R x).nat_degree),
x ^ (i : ℕ))) :=
begin
obtain ⟨f, rfl⟩ := hy,
apply mem_span_pow'.mpr _,
have := minpoly.monic hx,
refine ⟨f.mod_by_monic (minpoly R x),
lt_of_lt_of_le (degree_mod_by_monic_lt _ this) degree_le_nat_degree,
_⟩,
conv_lhs { rw ← mod_by_monic_add_div f this },
simp only [add_zero, zero_mul, minpoly.aeval, aeval_add, alg_hom.map_mul]
end
namespace power_basis
section map
variables {S' : Type*} [comm_ring S'] [algebra R S']
/-- `power_basis.map pb (e : S ≃ₐ[R] S')` is the power basis for `S'` generated by `e pb.gen`. -/
@[simps]
noncomputable def map (pb : power_basis R S) (e : S ≃ₐ[R] S') : power_basis R S' :=
{ dim := pb.dim,
basis := pb.basis.map e.to_linear_equiv,
gen := e pb.gen,
basis_eq_pow :=
λ i, by rw [basis.map_apply, pb.basis_eq_pow, e.to_linear_equiv_apply, e.map_pow] }
variables [algebra A S] [algebra A S']
@[simp]
lemma minpoly_gen_map (pb : power_basis A S) (e : S ≃ₐ[A] S') :
(pb.map e).minpoly_gen = pb.minpoly_gen :=
by { dsimp only [minpoly_gen, map_dim], -- Turn `fin (pb.map e).dim` into `fin pb.dim`
simp only [linear_equiv.trans_apply, map_basis, basis.map_repr,
map_gen, alg_equiv.to_linear_equiv_apply, e.to_linear_equiv_symm, alg_equiv.map_pow,
alg_equiv.symm_apply_apply, sub_right_inj] }
variables [is_domain A]
@[simp]
lemma equiv_of_root_map (pb : power_basis A S) (e : S ≃ₐ[A] S')
(h₁ h₂) :
pb.equiv_of_root (pb.map e) h₁ h₂ = e :=
by { ext x, obtain ⟨f, rfl⟩ := pb.exists_eq_aeval' x, simp [aeval_alg_equiv] }
@[simp]
lemma equiv_of_minpoly_map (pb : power_basis A S) (e : S ≃ₐ[A] S')
(h : minpoly A pb.gen = minpoly A (pb.map e).gen) :
pb.equiv_of_minpoly (pb.map e) h = e :=
pb.equiv_of_root_map _ _ _
end map
end power_basis
|
eb12fd12c1fbb57294751275eba1806fc05cd8aa | ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5 | /tests/elabissues/zmod.lean | a3d07ca4b2357087f9a70f5f3e2ae69a02441474 | [
"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 | 1,998 | lean | class Fact (p : Prop) :=
(h : p)
class Ring (α : Type) :=
(one : α) -- dummy implementation
instance ringHasOne {α} [Ring α] : HasOne α :=
⟨Ring.one α⟩ -- dummy implementation
instance ringAdd {α} [Ring α] : Add α :=
⟨fun a b => a⟩ -- dummy implementation
instance ringMul {α} [Ring α] : Mul α :=
⟨fun a b => a⟩ -- dummy implementation
class Field (α : Type) extends Ring α :=
(otherStuff : Unit := ()) -- dummy implementation
instance fieldDiv {α} [Field α] : Div α :=
⟨fun a b => a⟩ -- dummy implementation
def IsPrime (n : Nat) : Prop :=
True -- dummy implementation
structure Zmod (n : Nat) :=
(dummy : Unit := ()) -- dummy implementation
instance zmodIsRing {n : Nat} : Ring (Zmod n) :=
{ one := {} }
/- After the instance above, Zmod already has `+`, `*` notations, but not `/` -/
set_option pp.implicit true
set_option pp.notation false
#check fun (a b : Zmod 10) => a * b -- works
#check fun (a b : Zmod 10) => a / b -- fails
instance zmodIsField {n : Nat} [Fact (IsPrime n)] : Field (Zmod n) :=
{}
#check fun (a b : Zmod 3) => a / b -- fails because local instance [Fact (IsPrime 3)] is not available
#check fun (a b : Zmod 3) (h : Fact (IsPrime 3)) => a / b -- works
axiom foo {n : Nat} (h : Fact (IsPrime n)) (a : Zmod n) : a / a = 1 -- We need hypothesis `h` to be able to write `a/a`
#check fun {n : Nat} (h : IsPrime n) (a : Zmod n) => foo ⟨h⟩ a -- need to use ⟨...⟩ to convert `IsPrime n` into `Fact (IsPrime n)`
-- We can add a coercion from `p` to `Fact p` to minimize the amount of manual wrapping
instance toFact (p : Prop) : HasCoeT p (Fact p) :=
⟨fun h => ⟨h⟩⟩
#check fun {n : Nat} (h : IsPrime n) (a : Zmod n) => @foo n h a -- coercion helps. I needed to use `@` due to a Lean3 issue that is being fixed in Lean4
/- We support cycles in the new TC. So, we can also define -/
instance ofFact (p : Prop) : HasCoeT (Fact p) p :=
⟨fun h => h.1⟩
/- So, the coercions make it easy to wrap/unwrap facts -/
|
1cae8bb9f089254dfa0ce3d8e871adb8e40f371f | 12dabd587ce2621d9a4eff9f16e354d02e206c8e | /world09/level04.lean | d14f023038353c6cd74e36b79ba05eb8762e5d1f | [] | no_license | abdelq/natural-number-game | a1b5b8f1d52625a7addcefc97c966d3f06a48263 | bbddadc6d2e78ece2e9acd40fa7702ecc2db75c2 | refs/heads/master | 1,668,606,478,691 | 1,594,175,058,000 | 1,594,175,058,000 | 278,673,209 | 0 | 1 | null | null | null | null | UTF-8 | Lean | false | false | 535 | lean | theorem mul_left_cancel (a b c : mynat) (ha : a ≠ 0) : a * b = a * c → b = c :=
begin
induction c with d hd generalizing b,
rw mul_zero,
intro h,
cases (eq_zero_or_eq_zero_of_mul_eq_zero _ _ h) with h1 h2,
exfalso,
apply ha,
exact h1,
exact h2,
intro hb,
cases b,
rw mul_zero at hb,
exfalso,
apply ha,
symmetry at hb,
cases (eq_zero_or_eq_zero_of_mul_eq_zero _ _ hb) with h1 h2,
exact h1,
exfalso,
exact succ_ne_zero _ h2,
have h : b = d,
apply hd,
rw mul_succ at hb,
rw mul_succ at hb,
exact add_right_cancel _ _ _ hb,
rwa h,
end
|
b0a68c38a9336cfab8ad891e7c40088d33ca68da | f5f7e6fae601a5fe3cac7cc3ed353ed781d62419 | /src/data/nat/prime.lean | 6319d2da98ea6e3d0ff9fb25acc50457562beb57 | [
"Apache-2.0"
] | permissive | EdAyers/mathlib | 9ecfb2f14bd6caad748b64c9c131befbff0fb4e0 | ca5d4c1f16f9c451cf7170b10105d0051db79e1b | refs/heads/master | 1,626,189,395,845 | 1,555,284,396,000 | 1,555,284,396,000 | 144,004,030 | 0 | 0 | Apache-2.0 | 1,533,727,664,000 | 1,533,727,663,000 | null | UTF-8 | Lean | false | false | 17,892 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Jeremy Avigad, Mario Carneiro
Prime numbers.
-/
import data.nat.sqrt data.nat.gcd data.list.basic data.list.perm
open bool subtype
namespace nat
open decidable
/-- `prime p` means that `p` is a prime number, that is, a natural number
at least 2 whose only divisors are `p` and `1`. -/
def prime (p : ℕ) := p ≥ 2 ∧ ∀ m ∣ p, m = 1 ∨ m = p
theorem prime.ge_two {p : ℕ} : prime p → p ≥ 2 := and.left
theorem prime.gt_one {p : ℕ} : prime p → p > 1 := prime.ge_two
lemma prime.ne_one {p : ℕ} (hp : p.prime) : p ≠ 1 :=
ne.symm $ (ne_of_lt hp.gt_one)
theorem prime_def_lt {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m < p, m ∣ p → m = 1 :=
and_congr_right $ λ p2, forall_congr $ λ m,
⟨λ h l d, (h d).resolve_right (ne_of_lt l),
λ h d, (decidable.lt_or_eq_of_le $
le_of_dvd (le_of_succ_le p2) d).imp_left (λ l, h l d)⟩
theorem prime_def_lt' {p : ℕ} : prime p ↔ p ≥ 2 ∧ ∀ m, 2 ≤ m → m < p → ¬ m ∣ p :=
prime_def_lt.trans $ and_congr_right $ λ p2, forall_congr $ λ m,
⟨λ h m2 l d, not_lt_of_ge m2 ((h l d).symm ▸ dec_trivial),
λ h l d, begin
rcases m with _|_|m,
{ rw eq_zero_of_zero_dvd d at p2, revert p2, exact dec_trivial },
{ refl },
{ exact (h dec_trivial l).elim d }
end⟩
theorem prime_def_le_sqrt {p : ℕ} : prime p ↔ p ≥ 2 ∧
∀ m, 2 ≤ m → m ≤ sqrt p → ¬ m ∣ p :=
prime_def_lt'.trans $ and_congr_right $ λ p2,
⟨λ a m m2 l, a m m2 $ lt_of_le_of_lt l $ sqrt_lt_self p2,
λ a, have ∀ {m k}, m ≤ k → 1 < m → p ≠ m * k, from
λ m k mk m1 e, a m m1
(le_sqrt.2 (e.symm ▸ mul_le_mul_left m mk)) ⟨k, e⟩,
λ m m2 l ⟨k, e⟩, begin
cases (le_total m k) with mk km,
{ exact this mk m2 e },
{ rw [mul_comm] at e,
refine this km (lt_of_mul_lt_mul_right _ (zero_le m)) e,
rwa [one_mul, ← e] }
end⟩
/--
This instance is slower than the instance `decidable_prime` defined below,
but has the advantage that it works in the kernel.
If you need to prove that a particular number is prime, in any case
you should not use `dec_trivial`, but rather `by norm_num`, which is
much faster.
-/
def decidable_prime_1 (p : ℕ) : decidable (prime p) :=
decidable_of_iff' _ prime_def_lt'
local attribute [instance] decidable_prime_1
lemma prime.ne_zero {n : ℕ} (h : prime n) : n ≠ 0 :=
assume hn : n = 0,
have h2 : ¬ prime 0, from dec_trivial,
h2 (hn ▸ h)
theorem prime.pos {p : ℕ} (pp : prime p) : p > 0 :=
lt_of_succ_lt pp.gt_one
theorem not_prime_zero : ¬ prime 0 := dec_trivial
theorem not_prime_one : ¬ prime 1 := dec_trivial
theorem prime_two : prime 2 := dec_trivial
theorem prime_three : prime 3 := dec_trivial
theorem prime.pred_pos {p : ℕ} (pp : prime p) : pred p > 0 :=
lt_pred_iff.2 pp.gt_one
theorem succ_pred_prime {p : ℕ} (pp : prime p) : succ (pred p) = p :=
succ_pred_eq_of_pos pp.pos
theorem dvd_prime {p m : ℕ} (pp : prime p) : m ∣ p ↔ m = 1 ∨ m = p :=
⟨λ d, pp.2 m d, λ h, h.elim (λ e, e.symm ▸ one_dvd _) (λ e, e.symm ▸ dvd_refl _)⟩
theorem dvd_prime_ge_two {p m : ℕ} (pp : prime p) (H : m ≥ 2) : m ∣ p ↔ m = p :=
(dvd_prime pp).trans $ or_iff_right_of_imp $ not.elim $ ne_of_gt H
theorem prime.not_dvd_one {p : ℕ} (pp : prime p) : ¬ p ∣ 1
| d := (not_le_of_gt pp.gt_one) $ le_of_dvd dec_trivial d
theorem not_prime_mul {a b : ℕ} (a1 : 1 < a) (b1 : 1 < b) : ¬ prime (a * b) :=
λ h, ne_of_lt (nat.mul_lt_mul_of_pos_left b1 (lt_of_succ_lt a1)) $
by simpa using (dvd_prime_ge_two h a1).1 (dvd_mul_right _ _)
section min_fac
private lemma min_fac_lemma (n k : ℕ) (h : ¬ k * k > n) :
sqrt n - k < sqrt n + 2 - k :=
(nat.sub_lt_sub_right_iff $ le_sqrt.2 $ le_of_not_gt h).2 $
nat.lt_add_of_pos_right dec_trivial
def min_fac_aux (n : ℕ) : ℕ → ℕ | k :=
if h : n < k * k then n else
if k ∣ n then k else
have _, from min_fac_lemma n k h,
min_fac_aux (k + 2)
using_well_founded {rel_tac :=
λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]}
/-- Returns the smallest prime factor of `n ≠ 1`. -/
def min_fac : ℕ → ℕ
| 0 := 2
| 1 := 1
| (n+2) := if 2 ∣ n then 2 else min_fac_aux (n + 2) 3
@[simp] theorem min_fac_zero : min_fac 0 = 2 := rfl
@[simp] theorem min_fac_one : min_fac 1 = 1 := rfl
theorem min_fac_eq : ∀ n, min_fac n = if 2 ∣ n then 2 else min_fac_aux n 3
| 0 := rfl
| 1 := by simp [show 2≠1, from dec_trivial]; rw min_fac_aux; refl
| (n+2) :=
have 2 ∣ n + 2 ↔ 2 ∣ n, from
(nat.dvd_add_iff_left (by refl)).symm,
by simp [min_fac, this]; congr
private def min_fac_prop (n k : ℕ) :=
k ≥ 2 ∧ k ∣ n ∧ ∀ m ≥ 2, m ∣ n → k ≤ m
theorem min_fac_aux_has_prop {n : ℕ} (n2 : n ≥ 2) (nd2 : ¬ 2 ∣ n) :
∀ k i, k = 2*i+3 → (∀ m ≥ 2, m ∣ n → k ≤ m) → min_fac_prop n (min_fac_aux n k)
| k := λ i e a, begin
rw min_fac_aux,
by_cases h : n < k*k; simp [h],
{ have pp : prime n :=
prime_def_le_sqrt.2 ⟨n2, λ m m2 l d,
not_lt_of_ge l $ lt_of_lt_of_le (sqrt_lt.2 h) (a m m2 d)⟩,
from ⟨n2, dvd_refl _, λ m m2 d, le_of_eq
((dvd_prime_ge_two pp m2).1 d).symm⟩ },
have k2 : 2 ≤ k, { subst e, exact dec_trivial },
by_cases dk : k ∣ n; simp [dk],
{ exact ⟨k2, dk, a⟩ },
{ refine have _, from min_fac_lemma n k h,
min_fac_aux_has_prop (k+2) (i+1)
(by simp [e, left_distrib]) (λ m m2 d, _),
cases nat.eq_or_lt_of_le (a m m2 d) with me ml,
{ subst me, contradiction },
apply (nat.eq_or_lt_of_le ml).resolve_left, intro me,
rw [← me, e] at d, change 2 * (i + 2) ∣ n at d,
have := dvd_of_mul_right_dvd d, contradiction }
end
using_well_founded {rel_tac :=
λ _ _, `[exact ⟨_, measure_wf (λ k, sqrt n + 2 - k)⟩]}
theorem min_fac_has_prop {n : ℕ} (n1 : n ≠ 1) :
min_fac_prop n (min_fac n) :=
begin
by_cases n0 : n = 0, {simp [n0, min_fac_prop, ge]},
have n2 : 2 ≤ n, { revert n0 n1, rcases n with _|_|_; exact dec_trivial },
simp [min_fac_eq],
by_cases d2 : 2 ∣ n; simp [d2],
{ exact ⟨le_refl _, d2, λ k k2 d, k2⟩ },
{ refine min_fac_aux_has_prop n2 d2 3 0 rfl
(λ m m2 d, (nat.eq_or_lt_of_le m2).resolve_left (mt _ d2)),
exact λ e, e.symm ▸ d }
end
theorem min_fac_dvd (n : ℕ) : min_fac n ∣ n :=
by by_cases n1 : n = 1;
[exact n1.symm ▸ dec_trivial, exact (min_fac_has_prop n1).2.1]
theorem min_fac_prime {n : ℕ} (n1 : n ≠ 1) : prime (min_fac n) :=
let ⟨f2, fd, a⟩ := min_fac_has_prop n1 in
prime_def_lt'.2 ⟨f2, λ m m2 l d, not_le_of_gt l (a m m2 (dvd_trans d fd))⟩
theorem min_fac_le_of_dvd {n : ℕ} : ∀ {m : ℕ}, m ≥ 2 → m ∣ n → min_fac n ≤ m :=
by by_cases n1 : n = 1;
[exact λ m m2 d, n1.symm ▸ le_trans dec_trivial m2,
exact (min_fac_has_prop n1).2.2]
theorem min_fac_pos (n : ℕ) : min_fac n > 0 :=
by by_cases n1 : n = 1;
[exact n1.symm ▸ dec_trivial, exact (min_fac_prime n1).pos]
theorem min_fac_le {n : ℕ} (H : n > 0) : min_fac n ≤ n :=
le_of_dvd H (min_fac_dvd n)
theorem prime_def_min_fac {p : ℕ} : prime p ↔ p ≥ 2 ∧ min_fac p = p :=
⟨λ pp, ⟨pp.ge_two,
let ⟨f2, fd, a⟩ := min_fac_has_prop $ ne_of_gt pp.gt_one in
((dvd_prime pp).1 fd).resolve_left (ne_of_gt f2)⟩,
λ ⟨p2, e⟩, e ▸ min_fac_prime (ne_of_gt p2)⟩
/--
This instance is faster in the virtual machine than `decidable_prime_1`,
but slower in the kernel.
If you need to prove that a particular number is prime, in any case
you should not use `dec_trivial`, but rather `by norm_num`, which is
much faster.
-/
instance decidable_prime (p : ℕ) : decidable (prime p) :=
decidable_of_iff' _ prime_def_min_fac
theorem not_prime_iff_min_fac_lt {n : ℕ} (n2 : n ≥ 2) : ¬ prime n ↔ min_fac n < n :=
(not_congr $ prime_def_min_fac.trans $ and_iff_right n2).trans $
(lt_iff_le_and_ne.trans $ and_iff_right $ min_fac_le $ le_of_succ_le n2).symm
end min_fac
theorem exists_dvd_of_not_prime {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) :
∃ m, m ∣ n ∧ m ≠ 1 ∧ m ≠ n :=
⟨min_fac n, min_fac_dvd _, ne_of_gt (min_fac_prime (ne_of_gt n2)).gt_one,
ne_of_lt $ (not_prime_iff_min_fac_lt n2).1 np⟩
theorem exists_dvd_of_not_prime2 {n : ℕ} (n2 : n ≥ 2) (np : ¬ prime n) :
∃ m, m ∣ n ∧ m ≥ 2 ∧ m < n :=
⟨min_fac n, min_fac_dvd _, (min_fac_prime (ne_of_gt n2)).ge_two,
(not_prime_iff_min_fac_lt n2).1 np⟩
theorem exists_prime_and_dvd {n : ℕ} (n2 : n ≥ 2) : ∃ p, prime p ∧ p ∣ n :=
⟨min_fac n, min_fac_prime (ne_of_gt n2), min_fac_dvd _⟩
theorem exists_infinite_primes (n : ℕ) : ∃ p, p ≥ n ∧ prime p :=
let p := min_fac (fact n + 1) in
have f1 : fact n + 1 ≠ 1, from ne_of_gt $ succ_lt_succ $ fact_pos _,
have pp : prime p, from min_fac_prime f1,
have np : n ≤ p, from le_of_not_ge $ λ h,
have h₁ : p ∣ fact n, from dvd_fact (min_fac_pos _) h,
have h₂ : p ∣ 1, from (nat.dvd_add_iff_right h₁).2 (min_fac_dvd _),
pp.not_dvd_one h₂,
⟨p, np, pp⟩
lemma prime.eq_two_or_odd {p : ℕ} (hp : prime p) : p = 2 ∨ p % 2 = 1 :=
(nat.mod_two_eq_zero_or_one p).elim
(λ h, or.inl ((hp.2 2 (dvd_of_mod_eq_zero h)).resolve_left dec_trivial).symm)
or.inr
theorem factors_lemma {k} : (k+2) / min_fac (k+2) < k+2 :=
div_lt_self dec_trivial (min_fac_prime dec_trivial).gt_one
/-- `factors n` is the prime factorization of `n`, listed in increasing order. -/
def factors : ℕ → list ℕ
| 0 := []
| 1 := []
| n@(k+2) :=
let m := min_fac n in have n / m < n := factors_lemma,
m :: factors (n / m)
lemma mem_factors : ∀ {n p}, p ∈ factors n → prime p
| 0 := λ p, false.elim
| 1 := λ p, false.elim
| n@(k+2) := λ p h,
let m := min_fac n in have n / m < n := factors_lemma,
have h₁ : p = m ∨ p ∈ (factors (n / m)) :=
(list.mem_cons_iff _ _ _).1 h,
or.cases_on h₁ (λ h₂, h₂.symm ▸ min_fac_prime dec_trivial)
mem_factors
lemma prod_factors : ∀ {n}, 0 < n → list.prod (factors n) = n
| 0 := (lt_irrefl _).elim
| 1 := λ h, rfl
| n@(k+2) := λ h,
let m := min_fac n in have n / m < n := factors_lemma,
show list.prod (m :: factors (n / m)) = n, from
have h₁ : 0 < n / m :=
nat.pos_of_ne_zero $ λ h,
have n = 0 * m := (nat.div_eq_iff_eq_mul_left (min_fac_pos _) (min_fac_dvd _)).1 h,
by rw zero_mul at this; exact (show k + 2 ≠ 0, from dec_trivial) this,
by rw [list.prod_cons, prod_factors h₁, nat.mul_div_cancel' (min_fac_dvd _)]
theorem prime.coprime_iff_not_dvd {p n : ℕ} (pp : prime p) : coprime p n ↔ ¬ p ∣ n :=
⟨λ co d, pp.not_dvd_one $ co.dvd_of_dvd_mul_left (by simp [d]),
λ nd, coprime_of_dvd $ λ m m2 mp, ((dvd_prime_ge_two pp m2).1 mp).symm ▸ nd⟩
theorem prime.dvd_iff_not_coprime {p n : ℕ} (pp : prime p) : p ∣ n ↔ ¬ coprime p n :=
iff_not_comm.2 pp.coprime_iff_not_dvd
theorem prime.dvd_mul {p m n : ℕ} (pp : prime p) : p ∣ m * n ↔ p ∣ m ∨ p ∣ n :=
⟨λ H, or_iff_not_imp_left.2 $ λ h,
(pp.coprime_iff_not_dvd.2 h).dvd_of_dvd_mul_left H,
or.rec (λ h, dvd_mul_of_dvd_left h _) (λ h, dvd_mul_of_dvd_right h _)⟩
theorem prime.not_dvd_mul {p m n : ℕ} (pp : prime p)
(Hm : ¬ p ∣ m) (Hn : ¬ p ∣ n) : ¬ p ∣ m * n :=
mt pp.dvd_mul.1 $ by simp [Hm, Hn]
theorem prime.dvd_of_dvd_pow {p m n : ℕ} (pp : prime p) (h : p ∣ m^n) : p ∣ m :=
by induction n with n IH;
[exact pp.not_dvd_one.elim h,
exact (pp.dvd_mul.1 h).elim IH id]
lemma prime.mul_eq_prime_pow_two_iff {x y p : ℕ} (hp : p.prime) (hx : x ≠ 1) (hy : y ≠ 1) :
x * y = p ^ 2 ↔ x = p ∧ y = p :=
⟨λ h, have pdvdxy : p ∣ x * y, by rw h; simp [nat.pow_two],
begin
wlog := hp.dvd_mul.1 pdvdxy using x y,
cases case with a ha,
have hap : a ∣ p, from ⟨y, by rwa [ha, nat.pow_two,
mul_assoc, nat.mul_left_inj hp.pos, eq_comm] at h⟩,
exact ((nat.dvd_prime hp).1 hap).elim
(λ _, by clear_aux_decl; simp [*, nat.pow_two, nat.mul_left_inj hp.pos] at *
{contextual := tt})
(λ _, by clear_aux_decl; simp [*, nat.pow_two, mul_comm, mul_assoc,
nat.mul_left_inj hp.pos, nat.mul_right_eq_self_iff hp.pos] at *
{contextual := tt})
end,
λ ⟨h₁, h₂⟩, h₁.symm ▸ h₂.symm ▸ (nat.pow_two _).symm⟩
lemma prime.dvd_fact : ∀ {n p : ℕ} (hp : prime p), p ∣ n.fact ↔ p ≤ n
| 0 p hp := iff_of_false hp.not_dvd_one (not_le_of_lt hp.pos)
| (n+1) p hp := begin
rw [fact_succ, hp.dvd_mul, prime.dvd_fact hp],
exact ⟨λ h, h.elim (le_of_dvd (succ_pos _)) le_succ_of_le,
λ h, (_root_.lt_or_eq_of_le h).elim (or.inr ∘ le_of_lt_succ)
(λ h, or.inl $ by rw h)⟩
end
theorem prime.coprime_pow_of_not_dvd {p m a : ℕ} (pp : prime p) (h : ¬ p ∣ a) : coprime a (p^m) :=
(pp.coprime_iff_not_dvd.2 h).symm.pow_right _
theorem coprime_primes {p q : ℕ} (pp : prime p) (pq : prime q) : coprime p q ↔ p ≠ q :=
pp.coprime_iff_not_dvd.trans $ not_congr $ dvd_prime_ge_two pq pp.ge_two
theorem coprime_pow_primes {p q : ℕ} (n m : ℕ) (pp : prime p) (pq : prime q) (h : p ≠ q) :
coprime (p^n) (q^m) :=
((coprime_primes pp pq).2 h).pow _ _
theorem coprime_or_dvd_of_prime {p} (pp : prime p) (i : ℕ) : coprime p i ∨ p ∣ i :=
by rw [pp.dvd_iff_not_coprime]; apply em
theorem dvd_prime_pow {p : ℕ} (pp : prime p) {m i : ℕ} : i ∣ (p^m) ↔ ∃ k ≤ m, i = p^k :=
begin
induction m with m IH generalizing i, {simp [pow_succ, le_zero_iff] at *},
by_cases p ∣ i,
{ cases h with a e, subst e,
rw [pow_succ, mul_comm (p^m) p, nat.mul_dvd_mul_iff_left pp.pos, IH],
split; intro h; rcases h with ⟨k, h, e⟩,
{ exact ⟨succ k, succ_le_succ h, by rw [mul_comm, e]; refl⟩ },
cases k with k,
{ apply pp.not_dvd_one.elim,
simp at e, rw ← e, apply dvd_mul_right },
{ refine ⟨k, le_of_succ_le_succ h, _⟩,
rwa [mul_comm, pow_succ, nat.mul_right_inj pp.pos] at e } },
{ split; intro d,
{ rw (pp.coprime_pow_of_not_dvd h).eq_one_of_dvd d,
exact ⟨0, zero_le _, rfl⟩ },
{ rcases d with ⟨k, l, e⟩,
rw e, exact pow_dvd_pow _ l } }
end
section
open list
lemma mem_list_primes_of_dvd_prod {p : ℕ} (hp : prime p) :
∀ {l : list ℕ}, (∀ p ∈ l, prime p) → p ∣ prod l → p ∈ l
| [] := λ h₁ h₂, absurd h₂ (prime.not_dvd_one hp)
| (q :: l) := λ h₁ h₂,
have h₃ : p ∣ q * prod l := @prod_cons _ _ l q ▸ h₂,
have hq : prime q := h₁ q (mem_cons_self _ _),
or.cases_on ((prime.dvd_mul hp).1 h₃)
(λ h, by rw [prime.dvd_iff_not_coprime hp, coprime_primes hp hq, ne.def, not_not] at h;
exact h ▸ mem_cons_self _ _)
(λ h, have hl : ∀ p ∈ l, prime p := λ p hlp, h₁ p ((mem_cons_iff _ _ _).2 (or.inr hlp)),
(mem_cons_iff _ _ _).2 (or.inr (mem_list_primes_of_dvd_prod hl h)))
lemma mem_factors_iff_dvd {n p : ℕ} (hn : 0 < n) (hp : prime p) : p ∈ factors n ↔ p ∣ n :=
⟨λ h, prod_factors hn ▸ list.dvd_prod h,
λ h, mem_list_primes_of_dvd_prod hp (@mem_factors n) ((prod_factors hn).symm ▸ h)⟩
lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list ℕ}, prod l₁ = prod l₂ →
(∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → l₁ ~ l₂
| [] [] _ _ _ := perm.nil
| [] (a :: l) h₁ h₂ h₃ :=
have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _,
absurd ha (prime.not_dvd_one (h₃ a (mem_cons_self _ _)))
| (a :: l) [] h₁ h₂ h₃ :=
have ha : a ∣ 1 := @prod_nil ℕ _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _,
absurd ha (prime.not_dvd_one (h₂ a (mem_cons_self _ _)))
| (a :: l₁) (b :: l₂) h hl₁ hl₂ :=
have hl₁' : ∀ p ∈ l₁, prime p := λ p hp, hl₁ p (mem_cons_of_mem _ hp),
have hl₂' : ∀ p ∈ (b :: l₂).erase a, prime p := λ p hp, hl₂ p (mem_of_mem_erase hp),
have ha : a ∈ (b :: l₂) := mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂
(h ▸ by rw prod_cons; exact dvd_mul_right _ _),
have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_erase ha,
have hl : prod l₁ = prod ((b :: l₂).erase a) :=
(nat.mul_left_inj (prime.pos (hl₁ a (mem_cons_self _ _)))).1 $
by rwa [← prod_cons, ← prod_cons, ← prod_eq_of_perm hb],
perm.trans (perm.skip _ (perm_of_prod_eq_prod hl hl₁' hl₂')) hb.symm
lemma factors_unique {n : ℕ} {l : list ℕ} (h₁ : prod l = n) (h₂ : ∀ p ∈ l, prime p) : l ~ factors n :=
have hn : 0 < n := nat.pos_of_ne_zero $ λ h, begin
rw h at *, clear h,
induction l with a l hi,
{ exact absurd h₁ dec_trivial },
{ rw prod_cons at h₁,
exact nat.mul_ne_zero (ne_of_lt (prime.pos (h₂ a (mem_cons_self _ _)))).symm
(hi (λ p hp, h₂ p (mem_cons_of_mem _ hp))) h₁ }
end,
perm_of_prod_eq_prod (by rwa prod_factors hn) h₂ (@mem_factors _)
end
lemma succ_dvd_or_succ_dvd_of_succ_sum_dvd_mul {p : ℕ} (p_prime : prime p) {m n k l : ℕ}
(hpm : p ^ k ∣ m) (hpn : p ^ l ∣ n) (hpmn : p ^ (k+l+1) ∣ m*n) :
p ^ (k+1) ∣ m ∨ p ^ (l+1) ∣ n :=
have hpd : p^(k+l) * p ∣ m*n, from hpmn,
have hpd2 : p ∣ (m*n) / p ^ (k+l), from dvd_div_of_mul_dvd hpd,
have hpd3 : p ∣ (m*n) / (p^k * p^l), by simpa [nat.pow_add] using hpd2,
have hpd4 : p ∣ (m / p^k) * (n / p^l), by simpa [nat.div_mul_div hpm hpn] using hpd3,
have hpd5 : p ∣ (m / p^k) ∨ p ∣ (n / p^l), from (prime.dvd_mul p_prime).1 hpd4,
show p^k*p ∣ m ∨ p^l*p ∣ n, from
hpd5.elim
(assume : p ∣ m / p ^ k, or.inl $ mul_dvd_of_dvd_div hpm this)
(assume : p ∣ n / p ^ l, or.inr $ mul_dvd_of_dvd_div hpn this)
end nat
|
d1728ffb08f6c9a907f56d49c3571ecb7d11e8c4 | 19cc34575500ee2e3d4586c15544632aa07a8e66 | /src/data/polynomial/ring_division.lean | 7b46e9310528fe6b020745f9774199e8f096de84 | [
"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 | 22,772 | lean | /-
Copyright (c) 2018 Chris Hughes. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker, Johan Commelin
-/
import data.polynomial.basic
import data.polynomial.div
import data.polynomial.algebra_map
import data.set.finite
/-!
# Theory of univariate polynomials
This file starts looking like the ring theory of $ R[X] $
-/
noncomputable theory
local attribute [instance, priority 100] classical.prop_decidable
open finset
namespace polynomial
universes u v w z
variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ}
section comm_ring
variables [comm_ring R] {p q : polynomial R}
variables [comm_ring S]
lemma nat_degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0)
{z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) :
0 < p.nat_degree :=
nat_degree_pos_of_eval₂_root hp (algebra_map R S) hz inj
lemma degree_pos_of_aeval_root [algebra R S] {p : polynomial R} (hp : p ≠ 0)
{z : S} (hz : aeval z p = 0) (inj : ∀ (x : R), algebra_map R S x = 0 → x = 0) :
0 < p.degree :=
nat_degree_pos_iff_degree_pos.mp (nat_degree_pos_of_aeval_root hp hz inj)
end comm_ring
section integral_domain
variables [integral_domain R] {p q : polynomial R}
instance : integral_domain (polynomial R) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin
have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b,
rw [leading_coeff_zero, eq_comm] at this,
erw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero],
exact eq_zero_or_eq_zero_of_mul_eq_zero this
end,
..polynomial.nontrivial,
..polynomial.comm_ring }
lemma nat_degree_mul (hp : p ≠ 0) (hq : q ≠ 0) : nat_degree (p * q) =
nat_degree p + nat_degree q :=
by rw [← with_bot.coe_eq_coe, ← degree_eq_nat_degree (mul_ne_zero hp hq),
with_bot.coe_add, ← degree_eq_nat_degree hp,
← degree_eq_nat_degree hq, degree_mul]
@[simp] lemma nat_degree_pow (p : polynomial R) (n : ℕ) :
nat_degree (p ^ n) = n * nat_degree p :=
if hp0 : p = 0
then if hn0 : n = 0 then by simp [hp0, hn0]
else by rw [hp0, zero_pow (nat.pos_of_ne_zero hn0)]; simp
else nat_degree_pow'
(by rw [← leading_coeff_pow, ne.def, leading_coeff_eq_zero]; exact pow_ne_zero _ hp0)
lemma root_mul : is_root (p * q) a ↔ is_root p a ∨ is_root q a :=
by simp_rw [is_root, eval_mul, mul_eq_zero]
lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a :=
root_mul.1 h
lemma degree_le_mul_left (p : polynomial R) (hq : q ≠ 0) : degree p ≤ degree (p * q) :=
if hp : p = 0 then by simp only [hp, zero_mul, le_refl]
else by rw [degree_mul, degree_eq_nat_degree hp,
degree_eq_nat_degree hq];
exact with_bot.coe_le_coe.2 (nat.le_add_right _ _)
theorem nat_degree_le_of_dvd {p q : polynomial R} (h1 : p ∣ q) (h2 : q ≠ 0) : p.nat_degree ≤ q.nat_degree :=
begin
rcases h1 with ⟨q, rfl⟩, rw mul_ne_zero_iff at h2,
rw [nat_degree_mul h2.1 h2.2], exact nat.le_add_right _ _
end
section roots
open multiset
local attribute [reducible] with_zero
lemma degree_eq_zero_of_is_unit (h : is_unit p) : degree p = 0 :=
let ⟨q, hq⟩ := is_unit_iff_dvd_one.1 h in
have hp0 : p ≠ 0, from λ hp0, by simpa [hp0] using hq,
have hq0 : q ≠ 0, from λ hp0, by simpa [hp0] using hq,
have nat_degree (1 : polynomial R) = nat_degree (p * q),
from congr_arg _ hq,
by rw [nat_degree_one, nat_degree_mul hp0 hq0, eq_comm,
_root_.add_eq_zero_iff, ← with_bot.coe_eq_coe,
← degree_eq_nat_degree hp0] at this;
exact this.1
@[simp] lemma degree_coe_units (u : units (polynomial R)) :
degree (u : polynomial R) = 0 :=
degree_eq_zero_of_is_unit ⟨u, rfl⟩
theorem prime_X_sub_C {r : R} : prime (X - C r) :=
⟨X_sub_C_ne_zero r, not_is_unit_X_sub_C,
λ _ _, by { simp_rw [dvd_iff_is_root, is_root.def, eval_mul, mul_eq_zero], exact id }⟩
theorem prime_X : prime (X : polynomial R) :=
by { convert (prime_X_sub_C : prime (X - C 0 : polynomial R)), simp }
lemma prime_of_degree_eq_one_of_monic (hp1 : degree p = 1)
(hm : monic p) : prime p :=
have p = X - C (- p.coeff 0),
by simpa [hm.leading_coeff] using eq_X_add_C_of_degree_eq_one hp1,
this.symm ▸ prime_X_sub_C
theorem irreducible_X_sub_C (r : R) : irreducible (X - C r) :=
irreducible_of_prime prime_X_sub_C
theorem irreducible_X : irreducible (X : polynomial R) :=
irreducible_of_prime prime_X
lemma irreducible_of_degree_eq_one_of_monic (hp1 : degree p = 1)
(hm : monic p) : irreducible p :=
irreducible_of_prime (prime_of_degree_eq_one_of_monic hp1 hm)
theorem eq_of_monic_of_associated (hp : p.monic) (hq : q.monic) (hpq : associated p q) : p = q :=
begin
obtain ⟨u, hu⟩ := hpq,
unfold monic at hp hq,
rw eq_C_of_degree_le_zero (le_of_eq $ degree_coe_units _) at hu,
rw [← hu, leading_coeff_mul, hp, one_mul, leading_coeff_C] at hq,
rwa [hq, C_1, mul_one] at hu
end
@[simp] lemma root_multiplicity_zero {x : R} : root_multiplicity x 0 = 0 := dif_pos rfl
lemma root_multiplicity_eq_zero {p : polynomial R} {x : R} (h : ¬ is_root p x) :
root_multiplicity x p = 0 :=
begin
rw root_multiplicity_eq_multiplicity,
split_ifs, { refl },
rw [← enat.coe_inj, enat.coe_get, multiplicity.multiplicity_eq_zero_of_not_dvd, enat.coe_zero],
intro hdvd,
exact h (dvd_iff_is_root.mp hdvd)
end
lemma root_multiplicity_pos {p : polynomial R} (hp : p ≠ 0) {x : R} :
0 < root_multiplicity x p ↔ is_root p x :=
begin
rw [← dvd_iff_is_root, root_multiplicity_eq_multiplicity, dif_neg hp,
← enat.coe_lt_coe, enat.coe_get],
exact multiplicity.dvd_iff_multiplicity_pos
end
lemma root_multiplicity_mul {p q : polynomial R} {x : R} (hpq : p * q ≠ 0) :
root_multiplicity x (p * q) = root_multiplicity x p + root_multiplicity x q :=
begin
have hp : p ≠ 0 := left_ne_zero_of_mul hpq,
have hq : q ≠ 0 := right_ne_zero_of_mul hpq,
rw [root_multiplicity_eq_multiplicity (p * q), dif_neg hpq,
root_multiplicity_eq_multiplicity p, dif_neg hp,
root_multiplicity_eq_multiplicity q, dif_neg hq,
@multiplicity.mul' _ _ _ (X - C x) _ _ prime_X_sub_C],
end
lemma root_multiplicity_X_sub_C_self {x : R} :
root_multiplicity x (X - C x) = 1 :=
by rw [root_multiplicity_eq_multiplicity, dif_neg (X_sub_C_ne_zero x),
multiplicity.get_multiplicity_self]
lemma root_multiplicity_X_sub_C {x y : R} :
root_multiplicity x (X - C y) = if x = y then 1 else 0 :=
begin
split_ifs with hxy,
{ rw hxy,
exact root_multiplicity_X_sub_C_self },
exact root_multiplicity_eq_zero (mt root_X_sub_C.mp (ne.symm hxy))
end
/-- The multiplicity of `a` as root of `(X - a) ^ n` is `n`. -/
lemma root_multiplicity_X_sub_C_pow (a : R) (n : ℕ) : root_multiplicity a ((X - C a) ^ n) = n :=
begin
induction n with n hn,
{ refine root_multiplicity_eq_zero _,
simp only [eval_one, is_root.def, not_false_iff, one_ne_zero, pow_zero] },
have hzero := (ne_zero_of_monic (monic_pow (monic_X_sub_C a) n.succ)),
rw pow_succ (X - C a) n at hzero ⊢,
simp only [root_multiplicity_mul hzero, root_multiplicity_X_sub_C_self, hn, nat.one_add]
end
/-- If `(X - a) ^ n` divides a polynomial `p` then the multiplicity of `a` as root of `p` is at
least `n`. -/
lemma root_multiplicity_of_dvd {p : polynomial R} {a : R} {n : ℕ}
(hzero : p ≠ 0) (h : (X - C a) ^ n ∣ p) : n ≤ root_multiplicity a p :=
begin
obtain ⟨q, hq⟩ := exists_eq_mul_right_of_dvd h,
rw hq at hzero,
simp only [hq, root_multiplicity_mul hzero, root_multiplicity_X_sub_C_pow,
ge_iff_le, _root_.zero_le, le_add_iff_nonneg_right],
end
/-- The multiplicity of `p + q` is at least the minimum of the multiplicities. -/
lemma root_multiplicity_add {p q : polynomial R} (a : R) (hzero : p + q ≠ 0) :
min (root_multiplicity a p) (root_multiplicity a q) ≤ root_multiplicity a (p + q) :=
begin
refine root_multiplicity_of_dvd hzero _,
have hdivp : (X - C a) ^ root_multiplicity a p ∣ p := pow_root_multiplicity_dvd p a,
have hdivq : (X - C a) ^ root_multiplicity a q ∣ q := pow_root_multiplicity_dvd q a,
exact min_pow_dvd_add hdivp hdivq
end
lemma exists_multiset_roots : ∀ {p : polynomial R} (hp : p ≠ 0),
∃ s : multiset R, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ a, s.count a = root_multiplicity a p
| p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact
if h : ∃ x, is_root p x
then
let ⟨x, hx⟩ := h in
have hpd : 0 < degree p := degree_pos_of_root hp hx,
have hd0 : p /ₘ (X - C x) ≠ 0 :=
λ h, by rw [← mul_div_by_monic_eq_iff_is_root.2 hx, h, mul_zero] at hp; exact hp rfl,
have wf : degree (p /ₘ _) < degree p :=
degree_div_by_monic_lt _ (monic_X_sub_C x) hp
((degree_X_sub_C x).symm ▸ dec_trivial),
let ⟨t, htd, htr⟩ := @exists_multiset_roots (p /ₘ (X - C x)) hd0 in
have hdeg : degree (X - C x) ≤ degree p := begin
rw [degree_X_sub_C, degree_eq_nat_degree hp],
rw degree_eq_nat_degree hp at hpd,
exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd)
end,
have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x)
(ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg,
⟨x :: t, calc (card (x :: t) : with_bot ℕ) = t.card + 1 :
by exact_mod_cast card_cons _ _
... ≤ degree p :
by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg,
degree_X_sub_C, add_comm];
exact add_le_add (le_refl (1 : with_bot ℕ)) htd,
begin
assume a,
conv_rhs { rw ← mul_div_by_monic_eq_iff_is_root.mpr hx },
rw [root_multiplicity_mul (mul_ne_zero (X_sub_C_ne_zero _) hdiv0),
root_multiplicity_X_sub_C, ← htr a],
split_ifs with ha,
{ rw [ha, count_cons_self, nat.succ_eq_add_one, add_comm] },
{ rw [count_cons_of_ne ha, zero_add] },
end⟩
else
⟨0, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _),
by { intro a, rw [count_zero, root_multiplicity_eq_zero (not_exists.mp h a)] }⟩
using_well_founded {dec_tac := tactic.assumption}
/-- `roots p` noncomputably gives a multiset containing all the roots of `p`,
including their multiplicities. -/
noncomputable def roots (p : polynomial R) : multiset R :=
if h : p = 0 then ∅ else classical.some (exists_multiset_roots h)
@[simp] lemma roots_zero : (0 : polynomial R).roots = 0 :=
dif_pos rfl
lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p :=
begin
unfold roots,
rw dif_neg hp0,
exact (classical.some_spec (exists_multiset_roots hp0)).1
end
lemma card_roots' {p : polynomial R} (hp0 : p ≠ 0) : p.roots.card ≤ nat_degree p :=
with_bot.coe_le_coe.1 (le_trans (card_roots hp0) (le_of_eq $ degree_eq_nat_degree hp0))
lemma card_roots_sub_C {p : polynomial R} {a : R} (hp0 : 0 < degree p) :
((p - C a).roots.card : with_bot ℕ) ≤ degree p :=
calc ((p - C a).roots.card : with_bot ℕ) ≤ degree (p - C a) :
card_roots $ mt sub_eq_zero.1 $ λ h, not_le_of_gt hp0 $ h.symm ▸ degree_C_le
... = degree p : by rw [sub_eq_add_neg, ← C_neg]; exact degree_add_C hp0
lemma card_roots_sub_C' {p : polynomial R} {a : R} (hp0 : 0 < degree p) :
(p - C a).roots.card ≤ nat_degree p :=
with_bot.coe_le_coe.1 (le_trans (card_roots_sub_C hp0) (le_of_eq $ degree_eq_nat_degree
(λ h, by simp [*, lt_irrefl] at *)))
@[simp] lemma count_roots (hp : p ≠ 0) : p.roots.count a = root_multiplicity a p :=
by { rw [roots, dif_neg hp], exact (classical.some_spec (exists_multiset_roots hp)).2 a }
@[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a :=
by rw [← count_pos, count_roots hp, root_multiplicity_pos hp]
lemma eq_zero_of_infinite_is_root
(p : polynomial R) (h : set.infinite {x | is_root p x}) : p = 0 :=
begin
by_contradiction hp,
apply h,
convert p.roots.to_finset.finite_to_set using 1,
ext1 r,
simp only [mem_roots hp, multiset.mem_to_finset, set.mem_set_of_eq, finset.mem_coe]
end
lemma eq_of_infinite_eval_eq {R : Type*} [integral_domain R]
(p q : polynomial R) (h : set.infinite {x | eval x p = eval x q}) : p = q :=
begin
rw [← sub_eq_zero],
apply eq_zero_of_infinite_is_root,
simpa only [is_root, eval_sub, sub_eq_zero]
end
lemma roots_mul {p q : polynomial R} (hpq : p * q ≠ 0) : (p * q).roots = p.roots + q.roots :=
multiset.ext.mpr $ λ r,
by rw [count_add, count_roots hpq, count_roots (left_ne_zero_of_mul hpq),
count_roots (right_ne_zero_of_mul hpq), root_multiplicity_mul hpq]
@[simp] lemma mem_roots_sub_C {p : polynomial R} {a x : R} (hp0 : 0 < degree p) :
x ∈ (p - C a).roots ↔ p.eval x = a :=
(mem_roots (show p - C a ≠ 0, from mt sub_eq_zero.1 $ λ h,
not_le_of_gt hp0 $ h.symm ▸ degree_C_le)).trans
(by rw [is_root.def, eval_sub, eval_C, sub_eq_zero])
@[simp] lemma roots_X_sub_C (r : R) : roots (X - C r) = r :: 0 :=
begin
ext s,
rw [count_roots (X_sub_C_ne_zero r), root_multiplicity_X_sub_C],
split_ifs with h,
{ rw [h, count_singleton] },
{ rw [count_cons_of_ne h, count_zero] }
end
@[simp] lemma roots_C (x : R) : (C x).roots = 0 :=
if H : x = 0 then by rw [H, C_0, roots_zero] else multiset.ext.mpr $ λ r,
have h : C x ≠ 0, from λ h, H $ C_inj.1 $ h.symm ▸ C_0.symm,
have not_root : ¬ is_root (C x) r := mt (λ (h : eval r (C x) = 0), trans eval_C.symm h) H,
by rw [count_roots h, count_zero, root_multiplicity_eq_zero not_root]
@[simp] lemma roots_one : (1 : polynomial R).roots = ∅ :=
roots_C 1
lemma roots_list_prod (L : list (polynomial R)) :
(∀ p ∈ L, (p : _) ≠ 0) → L.prod.roots = (L : multiset (polynomial R)).bind roots :=
list.rec_on L (λ _, roots_one) $ λ hd tl ih H,
begin
rw list.forall_mem_cons at H,
rw [list.prod_cons, roots_mul (mul_ne_zero H.1 $ list.prod_ne_zero H.2),
← multiset.cons_coe, multiset.cons_bind, ih H.2]
end
lemma roots_multiset_prod (m : multiset (polynomial R)) :
(∀ p ∈ m, (p : _) ≠ 0) → m.prod.roots = m.bind roots :=
multiset.induction_on m (λ _, roots_one) $ λ hd tl ih H,
begin
rw multiset.forall_mem_cons at H,
rw [multiset.prod_cons, roots_mul (mul_ne_zero H.1 $ multiset.prod_ne_zero H.2),
multiset.cons_bind, ih H.2]
end
lemma roots_prod {ι : Type*} (f : ι → polynomial R) (s : finset ι) :
s.prod f ≠ 0 → (s.prod f).roots = s.val.bind (λ i, roots (f i)) :=
begin
refine s.induction_on _ _,
{ intros, exact roots_one },
intros i s hi ih ne_zero,
rw prod_insert hi at ⊢ ne_zero,
rw [roots_mul ne_zero, ih (right_ne_zero_of_mul ne_zero), insert_val,
ndinsert_of_not_mem hi, cons_bind]
end
lemma roots_prod_X_sub_C (s : finset R) :
(s.prod (λ a, X - C a)).roots = s.val :=
(roots_prod (λ a, X - C a) s (prod_ne_zero_iff.mpr (λ a _, X_sub_C_ne_zero a))).trans
(by simp_rw [roots_X_sub_C, bind_cons, bind_zero, add_zero, multiset.map_id'])
lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : R) :
(roots ((X : polynomial R) ^ n - C a)).card ≤ n :=
with_bot.coe_le_coe.1 $
calc ((roots ((X : polynomial R) ^ n - C a)).card : with_bot ℕ)
≤ degree ((X : polynomial R) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a)
... = n : degree_X_pow_sub_C hn a
section nth_roots
/-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/
def nth_roots (n : ℕ) (a : R) : multiset R :=
roots ((X : polynomial R) ^ n - C a)
@[simp] lemma mem_nth_roots {n : ℕ} (hn : 0 < n) {a x : R} :
x ∈ nth_roots n a ↔ x ^ n = a :=
by rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a),
is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq]
@[simp] lemma nth_roots_zero (r : R) : nth_roots 0 r = 0 :=
by simp only [empty_eq_zero, pow_zero, nth_roots, ← C_1, ← C_sub, roots_C]
lemma card_nth_roots (n : ℕ) (a : R) :
(nth_roots n a).card ≤ n :=
if hn : n = 0
then if h : (X : polynomial R) ^ n - C a = 0
then by simp only [nat.zero_le, nth_roots, roots, h, dif_pos rfl, empty_eq_zero, card_zero]
else with_bot.coe_le_coe.1 (le_trans (card_roots h)
(by rw [hn, pow_zero, ← C_1, ← @is_ring_hom.map_sub _ _ _ _ (@C R _)];
exact degree_C_le))
else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a];
exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a)
end nth_roots
lemma coeff_comp_degree_mul_degree (hqd0 : nat_degree q ≠ 0) :
coeff (p.comp q) (nat_degree p * nat_degree q) =
leading_coeff p * leading_coeff q ^ nat_degree p :=
if hp0 : p = 0 then by simp [hp0] else
calc coeff (p.comp q) (nat_degree p * nat_degree q)
= p.sum (λ n a, coeff (C a * q ^ n) (nat_degree p * nat_degree q)) :
by rw [comp, eval₂, coeff_sum]
... = coeff (C (leading_coeff p) * q ^ nat_degree p) (nat_degree p * nat_degree q) :
finset.sum_eq_single _
begin
assume b hbs hbp,
have hq0 : q ≠ 0, from λ hq0, hqd0 (by rw [hq0, nat_degree_zero]),
have : coeff p b ≠ 0, rwa finsupp.mem_support_iff at hbs,
refine coeff_eq_zero_of_degree_lt _,
rw [degree_mul], erw degree_C this,
rw [degree_pow, zero_add, degree_eq_nat_degree hq0,
← with_bot.coe_nsmul, nsmul_eq_mul, with_bot.coe_lt_coe, nat.cast_id],
rw mul_lt_mul_right, apply lt_of_le_of_ne, assumption', swap, omega,
exact le_nat_degree_of_ne_zero this,
end
begin
intro h, contrapose! hp0,
rw finsupp.mem_support_iff at h, push_neg at h,
rwa ← leading_coeff_eq_zero,
end
... = _ :
have coeff (q ^ nat_degree p) (nat_degree p * nat_degree q) = leading_coeff (q ^ nat_degree p),
by rw [leading_coeff, nat_degree_pow],
by rw [coeff_C_mul, this, leading_coeff_pow]
lemma nat_degree_comp : nat_degree (p.comp q) = nat_degree p * nat_degree q :=
le_antisymm nat_degree_comp_le
(if hp0 : p = 0 then by rw [hp0, zero_comp, nat_degree_zero, zero_mul]
else if hqd0 : nat_degree q = 0
then have degree q ≤ 0, by rw [← with_bot.coe_zero, ← hqd0]; exact degree_le_nat_degree,
by rw [eq_C_of_degree_le_zero this]; simp
else le_nat_degree_of_ne_zero $
have hq0 : q ≠ 0, from λ hq0, hqd0 $ by rw [hq0, nat_degree_zero],
calc coeff (p.comp q) (nat_degree p * nat_degree q)
= leading_coeff p * leading_coeff q ^ nat_degree p :
coeff_comp_degree_mul_degree hqd0
... ≠ 0 : mul_ne_zero (mt leading_coeff_eq_zero.1 hp0)
(pow_ne_zero _ (mt leading_coeff_eq_zero.1 hq0)))
lemma leading_coeff_comp (hq : nat_degree q ≠ 0) : leading_coeff (p.comp q) =
leading_coeff p * leading_coeff q ^ nat_degree p :=
by rw [← coeff_comp_degree_mul_degree hq, ← nat_degree_comp]; refl
lemma units_coeff_zero_smul (c : units (polynomial R)) (p : polynomial R) :
(c : polynomial R).coeff 0 • p = c * p :=
by rw [←polynomial.C_mul', ←polynomial.eq_C_of_degree_eq_zero (degree_coe_units c)]
@[simp] lemma nat_degree_coe_units (u : units (polynomial R)) :
nat_degree (u : polynomial R) = 0 :=
nat_degree_eq_of_degree_eq_some (degree_coe_units u)
lemma zero_of_eval_zero [infinite R] (p : polynomial R) (h : ∀ x, p.eval x = 0) : p = 0 :=
by classical; by_contradiction hp; exact
infinite.not_fintype ⟨p.roots.to_finset, λ x, multiset.mem_to_finset.mpr ((mem_roots hp).mpr (h _))⟩
lemma funext [infinite R] {p q : polynomial R} (ext : ∀ r : R, p.eval r = q.eval r) : p = q :=
begin
rw ← sub_eq_zero,
apply zero_of_eval_zero,
intro x,
rw [eval_sub, sub_eq_zero, ext],
end
end roots
theorem is_unit_iff {f : polynomial R} : is_unit f ↔ ∃ r : R, is_unit r ∧ C r = f :=
⟨λ hf, ⟨f.coeff 0,
is_unit_C.1 $ eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf) ▸ hf,
(eq_C_of_degree_eq_zero (degree_eq_zero_of_is_unit hf)).symm⟩,
λ ⟨r, hr, hrf⟩, hrf ▸ is_unit_C.2 hr⟩
lemma coeff_coe_units_zero_ne_zero (u : units (polynomial R)) :
coeff (u : polynomial R) 0 ≠ 0 :=
begin
conv in (0) {rw [← nat_degree_coe_units u]},
rw [← leading_coeff, ne.def, leading_coeff_eq_zero],
exact units.ne_zero _
end
lemma degree_eq_degree_of_associated (h : associated p q) : degree p = degree q :=
let ⟨u, hu⟩ := h in by simp [hu.symm]
lemma degree_eq_one_of_irreducible_of_root (hi : irreducible p) {x : R} (hx : is_root p x) :
degree p = 1 :=
let ⟨g, hg⟩ := dvd_iff_is_root.2 hx in
have is_unit (X - C x) ∨ is_unit g, from hi.2 _ _ hg,
this.elim
(λ h, have h₁ : degree (X - C x) = 1, from degree_X_sub_C x,
have h₂ : degree (X - C x) = 0, from degree_eq_zero_of_is_unit h,
by rw h₁ at h₂; exact absurd h₂ dec_trivial)
(λ hgu, by rw [hg, degree_mul, degree_X_sub_C, degree_eq_zero_of_is_unit hgu, add_zero])
end integral_domain
section
variables [semiring R] [integral_domain S] (φ : R →+* S)
lemma is_unit_of_is_unit_leading_coeff_of_is_unit_map
(f : polynomial R) (hf : is_unit (leading_coeff f)) (H : is_unit (map φ f)) :
is_unit f :=
begin
have dz := degree_eq_zero_of_is_unit H,
rw degree_map_eq_of_leading_coeff_ne_zero at dz,
{ rw eq_C_of_degree_eq_zero dz,
apply is_unit.map',
convert hf,
rw (degree_eq_iff_nat_degree_eq _).1 dz,
rintro rfl,
simpa using H, },
{ intro h,
have u : is_unit (φ f.leading_coeff) := is_unit.map' _ hf,
rw h at u,
simpa using u, }
end
end
section
variables [integral_domain R] [integral_domain S] (φ : R →+* S)
/--
A polynomial over an integral domain `R` is irreducible if it is monic and
irreducible after mapping into an integral domain `S`.
A special case of this lemma is that a polynomial over `ℤ` is irreducible if
it is monic and irreducible over `ℤ/pℤ` for some prime `p`.
-/
lemma irreducible_of_irreducible_map (f : polynomial R)
(h_mon : monic f) (h_irr : irreducible (map φ f)) :
irreducible f :=
begin
fsplit,
{ intro h,
exact h_irr.1 (is_unit.map (monoid_hom.of (map φ)) h), },
{ intros a b h,
have q := (leading_coeff_mul a b).symm,
rw ←h at q,
dsimp [monic] at h_mon,
rw h_mon at q,
have au : is_unit a.leading_coeff := is_unit_of_mul_eq_one _ _ q,
rw mul_comm at q,
have bu : is_unit b.leading_coeff := is_unit_of_mul_eq_one _ _ q,
clear q h_mon,
have h' := congr_arg (map φ) h,
simp only [map_mul] at h',
cases h_irr.2 _ _ h' with w w,
{ left,
exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ au w, },
{ right,
exact is_unit_of_is_unit_leading_coeff_of_is_unit_map _ _ bu w, }, }
end
end
end polynomial
namespace is_integral_domain
variables {R : Type*} [comm_ring R]
/-- Lift evidence that `is_integral_domain R` to `is_integral_domain (polynomial R)`. -/
lemma polynomial (h : is_integral_domain R) : is_integral_domain (polynomial R) :=
@integral_domain.to_is_integral_domain _ (@polynomial.integral_domain _ (h.to_integral_domain _))
end is_integral_domain
|
7f7572cadc872ba96475fe05bed79676dc89cbb6 | 94e33a31faa76775069b071adea97e86e218a8ee | /src/analysis/normed_space/hahn_banach/separation.lean | c1b099a18857001b710113f483a13432c5117efd | [
"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 | 10,569 | lean | /-
Copyright (c) 2022 Bhavik Mehta All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta, Yaël Dillies
-/
import analysis.convex.cone
import analysis.convex.gauge
/-!
# Separation Hahn-Banach theorem
In this file we prove the geometric Hahn-Banach theorem. For any two disjoint convex sets, there
exists a continuous linear functional separating them, geometrically meaning that we can intercalate
a plane between them.
We provide many variations to stricten the result under more assumptions on the convex sets:
* `geometric_hahn_banach_open`: One set is open. Weak separation.
* `geometric_hahn_banach_open_point`, `geometric_hahn_banach_point_open`: One set is open, the
other is a singleton. Weak separation.
* `geometric_hahn_banach_open_open`: Both sets are open. Semistrict separation.
* `geometric_hahn_banach_compact_closed`, `geometric_hahn_banach_closed_compact`: One set is closed,
the other one is compact. Strict separation.
* `geometric_hahn_banach_point_closed`, `geometric_hahn_banach_closed_point`: One set is closed, the
other one is a singleton. Strict separation.
* `geometric_hahn_banach_point_point`: Both sets are singletons. Strict separation.
## TODO
* Eidelheit's theorem
* `convex ℝ s → interior (closure s) ⊆ s`
-/
open set
open_locale pointwise
variables {𝕜 E : Type*}
/-- Given a set `s` which is a convex neighbourhood of `0` and a point `x₀` outside of it, there is
a continuous linear functional `f` separating `x₀` and `s`, in the sense that it sends `x₀` to 1 and
all of `s` to values strictly below `1`. -/
lemma separate_convex_open_set [semi_normed_group E] [normed_space ℝ E] {s : set E}
(hs₀ : (0 : E) ∈ s) (hs₁ : convex ℝ s) (hs₂ : is_open s) {x₀ : E} (hx₀ : x₀ ∉ s) :
∃ f : E →L[ℝ] ℝ, f x₀ = 1 ∧ ∀ x ∈ s, f x < 1 :=
begin
let f : linear_pmap ℝ E ℝ :=
linear_pmap.mk_span_singleton x₀ 1 (ne_of_mem_of_not_mem hs₀ hx₀).symm,
obtain ⟨r, hr, hrs⟩ := metric.mem_nhds_iff.1
(filter.inter_mem (hs₂.mem_nhds hs₀) $ hs₂.neg.mem_nhds $ by rwa [mem_neg, neg_zero]),
obtain ⟨φ, hφ₁, hφ₂⟩ := exists_extension_of_le_sublinear f (gauge s)
(λ c hc, gauge_smul_of_nonneg hc.le)
(gauge_add_le hs₁ $ absorbent_nhds_zero $ hs₂.mem_nhds hs₀) _,
{ refine ⟨φ.mk_continuous (r⁻¹) $ λ x, _, _, _⟩,
{ rw [real.norm_eq_abs, abs_le, neg_le, ←linear_map.map_neg],
nth_rewrite 0 ←norm_neg x,
suffices : ∀ x, φ x ≤ r⁻¹ * ∥x∥,
{ exact ⟨this _, this _⟩ },
refine λ x, (hφ₂ _).trans _,
rw [←div_eq_inv_mul, ←gauge_ball hr],
exact gauge_mono (absorbent_ball_zero hr) (hrs.trans $ inter_subset_left _ _) x },
{ dsimp,
rw [←submodule.coe_mk x₀ (submodule.mem_span_singleton_self _), hφ₁,
linear_pmap.mk_span_singleton'_apply_self] },
{ exact λ x hx, (hφ₂ x).trans_lt (gauge_lt_one_of_mem_of_open hs₁ hs₀ hs₂ hx) } },
rintro ⟨x, hx⟩,
obtain ⟨y, rfl⟩ := submodule.mem_span_singleton.1 hx,
rw linear_pmap.mk_span_singleton'_apply,
simp only [mul_one, algebra.id.smul_eq_mul, submodule.coe_mk],
obtain h | h := le_or_lt y 0,
{ exact h.trans (gauge_nonneg _) },
{ rw [gauge_smul_of_nonneg h.le, smul_eq_mul, le_mul_iff_one_le_right h],
exact one_le_gauge_of_not_mem (hs₁.star_convex hs₀)
((absorbent_ball_zero hr).subset $ hrs.trans $ inter_subset_left _ _).absorbs hx₀,
apply_instance }
end
variables [normed_group E] [normed_space ℝ E] {s t : set E} {x y : E}
/-- A version of the **Hahn-Banach theorem**: given disjoint convex sets `s`, `t` where `s` is open,
there is a continuous linear functional which separates them. -/
theorem geometric_hahn_banach_open (hs₁ : convex ℝ s) (hs₂ : is_open s) (ht : convex ℝ t)
(disj : disjoint s t) :
∃ (f : E →L[ℝ] ℝ) (u : ℝ), (∀ a ∈ s, f a < u) ∧ ∀ b ∈ t, u ≤ f b :=
begin
obtain rfl | ⟨a₀, ha₀⟩ := s.eq_empty_or_nonempty,
{ exact ⟨0, 0, by simp, λ b hb, le_rfl⟩ },
obtain rfl | ⟨b₀, hb₀⟩ := t.eq_empty_or_nonempty,
{ exact ⟨0, 1, λ a ha, zero_lt_one, by simp⟩ },
let x₀ := b₀ - a₀,
let C := x₀ +ᵥ (s - t),
have : (0:E) ∈ C := ⟨a₀ - b₀, sub_mem_sub ha₀ hb₀,
by rw [vadd_eq_add, sub_add_sub_cancel', sub_self]⟩,
have : convex ℝ C := (hs₁.sub ht).vadd _,
have : x₀ ∉ C,
{ intro hx₀,
rw ←add_zero x₀ at hx₀,
exact disj.zero_not_mem_sub_set (vadd_mem_vadd_set_iff.1 hx₀) },
obtain ⟨f, hf₁, hf₂⟩ := separate_convex_open_set ‹0 ∈ C› ‹_› (hs₂.sub_right.vadd _) ‹x₀ ∉ C›,
have : f b₀ = f a₀ + 1 := by simp [←hf₁],
have forall_le : ∀ (a ∈ s) (b ∈ t), f a ≤ f b,
{ intros a ha b hb,
have := hf₂ (x₀ + (a - b)) (vadd_mem_vadd_set $ sub_mem_sub ha hb),
simp only [f.map_add, f.map_sub, hf₁] at this,
linarith },
refine ⟨f, Inf (f '' t), image_subset_iff.1 (_ : f '' s ⊆ Iio (Inf (f '' t))), λ b hb, _⟩,
{ rw ←interior_Iic,
refine interior_maximal (image_subset_iff.2 $ λ a ha, _) (f.is_open_map_of_ne_zero _ _ hs₂),
{ exact le_cInf (nonempty.image _ ⟨_, hb₀⟩) (ball_image_of_ball $ forall_le _ ha) },
{ rintro rfl,
simpa using hf₁ } },
{ exact cInf_le ⟨f a₀, ball_image_of_ball $ forall_le _ ha₀⟩ (mem_image_of_mem _ hb) }
end
theorem geometric_hahn_banach_open_point (hs₁ : convex ℝ s) (hs₂ : is_open s) (disj : x ∉ s) :
∃ f : E →L[ℝ] ℝ, ∀ a ∈ s, f a < f x :=
let ⟨f, s, hs, hx⟩ := geometric_hahn_banach_open hs₁ hs₂ (convex_singleton x)
(disjoint_singleton_right.2 disj)
in ⟨f, λ a ha, lt_of_lt_of_le (hs a ha) (hx x (mem_singleton _))⟩
theorem geometric_hahn_banach_point_open (ht₁ : convex ℝ t) (ht₂ : is_open t) (disj : x ∉ t) :
∃ f : E →L[ℝ] ℝ, ∀ b ∈ t, f x < f b :=
let ⟨f, hf⟩ := geometric_hahn_banach_open_point ht₁ ht₂ disj in ⟨-f, by simpa⟩
theorem geometric_hahn_banach_open_open (hs₁ : convex ℝ s) (hs₂ : is_open s) (ht₁ : convex ℝ t)
(ht₃ : is_open t) (disj : disjoint s t) :
∃ (f : E →L[ℝ] ℝ) (u : ℝ), (∀ a ∈ s, f a < u) ∧ ∀ b ∈ t, u < f b :=
begin
obtain (rfl | ⟨a₀, ha₀⟩) := s.eq_empty_or_nonempty,
{ exact ⟨0, -1, by simp, λ b hb, by norm_num⟩ },
obtain (rfl | ⟨b₀, hb₀⟩) := t.eq_empty_or_nonempty,
{ exact ⟨0, 1, λ a ha, by norm_num, by simp⟩ },
obtain ⟨f, s, hf₁, hf₂⟩ := geometric_hahn_banach_open hs₁ hs₂ ht₁ disj,
have hf : is_open_map f,
{ refine f.is_open_map_of_ne_zero _,
rintro rfl,
exact (hf₁ _ ha₀).not_le (hf₂ _ hb₀) },
refine ⟨f, s, hf₁, image_subset_iff.1 (_ : f '' t ⊆ Ioi s)⟩,
rw ←interior_Ici,
refine interior_maximal (image_subset_iff.2 hf₂) (f.is_open_map_of_ne_zero _ _ ht₃),
rintro rfl,
exact (hf₁ _ ha₀).not_le (hf₂ _ hb₀),
end
/-- A version of the **Hahn-Banach theorem**: given disjoint convex sets `s`, `t` where `s` is
compact and `t` is closed, there is a continuous linear functional which strongly separates them. -/
theorem geometric_hahn_banach_compact_closed (hs₁ : convex ℝ s) (hs₂ : is_compact s)
(ht₁ : convex ℝ t) (ht₂ : is_closed t) (disj : disjoint s t) :
∃ (f : E →L[ℝ] ℝ) (u v : ℝ), (∀ a ∈ s, f a < u) ∧ u < v ∧ ∀ b ∈ t, v < f b :=
begin
obtain rfl | hs := s.eq_empty_or_nonempty,
{ exact ⟨0, -2, -1, by simp, by norm_num, λ b hb, by norm_num⟩ },
unfreezingI { obtain rfl | ht := t.eq_empty_or_nonempty },
{ exact ⟨0, 1, 2, λ a ha, by norm_num, by norm_num, by simp⟩ },
obtain ⟨U, V, hU, hV, hU₁, hV₁, sU, tV, disj'⟩ := disj.exists_open_convexes hs₁ hs₂ ht₁ ht₂,
obtain ⟨f, u, hf₁, hf₂⟩ := geometric_hahn_banach_open_open hU₁ hU hV₁ hV disj',
obtain ⟨x, hx₁, hx₂⟩ := hs₂.exists_forall_ge hs f.continuous.continuous_on,
have : f x < u := hf₁ x (sU hx₁),
exact ⟨f, (f x + u)/2, u, λ a ha, by linarith [hx₂ a ha], by linarith, λ b hb, hf₂ b (tV hb)⟩,
end
/-- A version of the **Hahn-Banach theorem**: given disjoint convex sets `s`, `t` where `s` is
closed, and `t` is compact, there is a continuous linear functional which strongly separates them.
-/
theorem geometric_hahn_banach_closed_compact (hs₁ : convex ℝ s) (hs₂ : is_closed s)
(ht₁ : convex ℝ t) (ht₂ : is_compact t) (disj : disjoint s t) :
∃ (f : E →L[ℝ] ℝ) (u v : ℝ), (∀ a ∈ s, f a < u) ∧ u < v ∧ ∀ b ∈ t, v < f b :=
let ⟨f, s, t, hs, st, ht⟩ := geometric_hahn_banach_compact_closed ht₁ ht₂ hs₁ hs₂ disj.symm in
⟨-f, -t, -s, by simpa using ht, by simpa using st, by simpa using hs⟩
theorem geometric_hahn_banach_point_closed (ht₁ : convex ℝ t) (ht₂ : is_closed t) (disj : x ∉ t) :
∃ (f : E →L[ℝ] ℝ) (u : ℝ), f x < u ∧ ∀ b ∈ t, u < f b :=
let ⟨f, u, v, ha, hst, hb⟩ := geometric_hahn_banach_compact_closed (convex_singleton x)
is_compact_singleton ht₁ ht₂ (disjoint_singleton_left.2 disj)
in ⟨f, v, hst.trans' $ ha x $ mem_singleton _, hb⟩
theorem geometric_hahn_banach_closed_point (hs₁ : convex ℝ s) (hs₂ : is_closed s) (disj : x ∉ s) :
∃ (f : E →L[ℝ] ℝ) (u : ℝ), (∀ a ∈ s, f a < u) ∧ u < f x :=
let ⟨f, s, t, ha, hst, hb⟩ := geometric_hahn_banach_closed_compact hs₁ hs₂ (convex_singleton x)
is_compact_singleton (disjoint_singleton_right.2 disj)
in ⟨f, s, ha, hst.trans $ hb x $ mem_singleton _⟩
/-- Special case of `normed_space.eq_iff_forall_dual_eq`. -/
theorem geometric_hahn_banach_point_point (hxy : x ≠ y) : ∃ (f : E →L[ℝ] ℝ), f x < f y :=
begin
obtain ⟨f, s, t, hs, st, ht⟩ :=
geometric_hahn_banach_compact_closed (convex_singleton x) is_compact_singleton
(convex_singleton y) is_closed_singleton (disjoint_singleton.2 hxy),
exact ⟨f, by linarith [hs x rfl, ht y rfl]⟩,
end
/-- A closed convex set is the intersection of the halfspaces containing it. -/
lemma Inter_halfspaces_eq (hs₁ : convex ℝ s) (hs₂ : is_closed s) :
(⋂ (l : E →L[ℝ] ℝ), {x | ∃ y ∈ s, l x ≤ l y}) = s :=
begin
rw set.Inter_set_of,
refine set.subset.antisymm (λ x hx, _) (λ x hx l, ⟨x, hx, le_rfl⟩),
by_contra,
obtain ⟨l, s, hlA, hl⟩ := geometric_hahn_banach_closed_point hs₁ hs₂ h,
obtain ⟨y, hy, hxy⟩ := hx l,
exact ((hxy.trans_lt (hlA y hy)).trans hl).not_le le_rfl,
end
|
7adc57c58115a39961ae89c3d203c9e0e88488bb | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/number_theory/lucas_lehmer.lean | f05fc1a16b45892cb3955605edfe6db3355e13dd | [
"Apache-2.0"
] | permissive | leanprover-community/mathlib | 56a2cadd17ac88caf4ece0a775932fa26327ba0e | 442a83d738cb208d3600056c489be16900ba701d | refs/heads/master | 1,693,584,102,358 | 1,693,471,902,000 | 1,693,471,902,000 | 97,922,418 | 1,595 | 352 | Apache-2.0 | 1,694,693,445,000 | 1,500,624,130,000 | Lean | UTF-8 | Lean | false | false | 17,022 | lean | /-
Copyright (c) 2020 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro, Scott Morrison, Ainsley Pahljina
-/
import data.nat.parity
import data.pnat.interval
import data.zmod.basic
import group_theory.order_of_element
import ring_theory.fintype
import tactic.interval_cases
import tactic.ring_exp
/-!
# The Lucas-Lehmer test for Mersenne primes.
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
We define `lucas_lehmer_residue : Π p : ℕ, zmod (2^p - 1)`, and
prove `lucas_lehmer_residue p = 0 → prime (mersenne p)`.
We construct a tactic `lucas_lehmer.run_test`, which iteratively certifies the arithmetic
required to calculate the residue, and enables us to prove
```
example : prime (mersenne 127) :=
lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test)
```
## TODO
- Show reverse implication.
- Speed up the calculations using `n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]`.
- Find some bigger primes!
## History
This development began as a student project by Ainsley Pahljina,
and was then cleaned up for mathlib by Scott Morrison.
The tactic for certified computation of Lucas-Lehmer residues was provided by Mario Carneiro.
-/
/-- The Mersenne numbers, 2^p - 1. -/
def mersenne (p : ℕ) : ℕ := 2^p - 1
lemma mersenne_pos {p : ℕ} (h : 0 < p) : 0 < mersenne p :=
begin
dsimp [mersenne],
calc 0 < 2^1 - 1 : by norm_num
... ≤ 2^p - 1 : nat.pred_le_pred (nat.pow_le_pow_of_le_right (nat.succ_pos 1) h)
end
@[simp]
lemma succ_mersenne (k : ℕ) : mersenne k + 1 = 2 ^ k :=
begin
rw [mersenne, tsub_add_cancel_of_le],
exact one_le_pow_of_one_le (by norm_num) k
end
namespace lucas_lehmer
open nat
/-!
We now define three(!) different versions of the recurrence
`s (i+1) = (s i)^2 - 2`.
These versions take values either in `ℤ`, in `zmod (2^p - 1)`, or
in `ℤ` but applying `% (2^p - 1)` at each step.
They are each useful at different points in the proof,
so we take a moment setting up the lemmas relating them.
-/
/-- The recurrence `s (i+1) = (s i)^2 - 2` in `ℤ`. -/
def s : ℕ → ℤ
| 0 := 4
| (i+1) := (s i)^2 - 2
/-- The recurrence `s (i+1) = (s i)^2 - 2` in `zmod (2^p - 1)`. -/
def s_zmod (p : ℕ) : ℕ → zmod (2^p - 1)
| 0 := 4
| (i+1) := (s_zmod i)^2 - 2
/-- The recurrence `s (i+1) = ((s i)^2 - 2) % (2^p - 1)` in `ℤ`. -/
def s_mod (p : ℕ) : ℕ → ℤ
| 0 := 4 % (2^p - 1)
| (i+1) := ((s_mod i)^2 - 2) % (2^p - 1)
lemma mersenne_int_ne_zero (p : ℕ) (w : 0 < p) : (2^p - 1 : ℤ) ≠ 0 :=
begin
apply ne_of_gt, simp only [gt_iff_lt, sub_pos],
exact_mod_cast nat.one_lt_two_pow p w,
end
lemma s_mod_nonneg (p : ℕ) (w : 0 < p) (i : ℕ) : 0 ≤ s_mod p i :=
begin
cases i; dsimp [s_mod],
{ exact sup_eq_right.mp rfl },
{ apply int.mod_nonneg, exact mersenne_int_ne_zero p w },
end
lemma s_mod_mod (p i : ℕ) : s_mod p i % (2^p - 1) = s_mod p i :=
by cases i; simp [s_mod]
lemma s_mod_lt (p : ℕ) (w : 0 < p) (i : ℕ) : s_mod p i < 2^p - 1 :=
begin
rw ←s_mod_mod,
convert int.mod_lt _ _,
{ refine (abs_of_nonneg _).symm,
simp only [sub_nonneg, ge_iff_le],
exact_mod_cast nat.one_le_two_pow p, },
{ exact mersenne_int_ne_zero p w, },
end
lemma s_zmod_eq_s (p' : ℕ) (i : ℕ) : s_zmod (p'+2) i = (s i : zmod (2^(p'+2) - 1)):=
begin
induction i with i ih,
{ dsimp [s, s_zmod], norm_num, },
{ push_cast [s, s_zmod, ih] },
end
-- These next two don't make good `norm_cast` lemmas.
lemma int.coe_nat_pow_pred (b p : ℕ) (w : 0 < b) : ((b^p - 1 : ℕ) : ℤ) = (b^p - 1 : ℤ) :=
begin
have : 1 ≤ b^p := nat.one_le_pow p b w,
norm_cast
end
lemma int.coe_nat_two_pow_pred (p : ℕ) : ((2^p - 1 : ℕ) : ℤ) = (2^p - 1 : ℤ) :=
int.coe_nat_pow_pred 2 p dec_trivial
lemma s_zmod_eq_s_mod (p : ℕ) (i : ℕ) : s_zmod p i = (s_mod p i : zmod (2^p - 1)) :=
by induction i; push_cast [←int.coe_nat_two_pow_pred p, s_mod, s_zmod, *]
/-- The Lucas-Lehmer residue is `s p (p-2)` in `zmod (2^p - 1)`. -/
def lucas_lehmer_residue (p : ℕ) : zmod (2^p - 1) := s_zmod p (p-2)
lemma residue_eq_zero_iff_s_mod_eq_zero (p : ℕ) (w : 1 < p) :
lucas_lehmer_residue p = 0 ↔ s_mod p (p-2) = 0 :=
begin
dsimp [lucas_lehmer_residue],
rw s_zmod_eq_s_mod p,
split,
{ -- We want to use that fact that `0 ≤ s_mod p (p-2) < 2^p - 1`
-- and `lucas_lehmer_residue p = 0 → 2^p - 1 ∣ s_mod p (p-2)`.
intro h,
simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h,
apply int.eq_zero_of_dvd_of_nonneg_of_lt _ _ h; clear h,
apply s_mod_nonneg _ (nat.lt_of_succ_lt w),
exact s_mod_lt _ (nat.lt_of_succ_lt w) (p-2) },
{ intro h, rw h, simp, },
end
/--
A Mersenne number `2^p-1` is prime if and only if
the Lucas-Lehmer residue `s p (p-2) % (2^p - 1)` is zero.
-/
@[derive decidable_pred]
def lucas_lehmer_test (p : ℕ) : Prop := lucas_lehmer_residue p = 0
/-- `q` is defined as the minimum factor of `mersenne p`, bundled as an `ℕ+`. -/
def q (p : ℕ) : ℕ+ := ⟨nat.min_fac (mersenne p), nat.min_fac_pos (mersenne p)⟩
/-- We construct the ring `X q` as ℤ/qℤ + √3 ℤ/qℤ. -/
-- It would be nice to define this as (ℤ/qℤ)[x] / (x^2 - 3),
-- obtaining the ring structure for free,
-- but that seems to be more trouble than it's worth;
-- if it were easy to make the definition,
-- cardinality calculations would be somewhat more involved, too.
@[derive [add_comm_group, decidable_eq, fintype, inhabited]]
def X (q : ℕ+) : Type := (zmod q) × (zmod q)
namespace X
variable {q : ℕ+}
@[ext]
lemma ext {x y : X q} (h₁ : x.1 = y.1) (h₂ : x.2 = y.2) : x = y :=
begin
cases x, cases y,
congr; assumption
end
@[simp] lemma add_fst (x y : X q) : (x + y).1 = x.1 + y.1 := rfl
@[simp] lemma add_snd (x y : X q) : (x + y).2 = x.2 + y.2 := rfl
@[simp] lemma neg_fst (x : X q) : (-x).1 = -x.1 := rfl
@[simp] lemma neg_snd (x : X q) : (-x).2 = -x.2 := rfl
instance : has_mul (X q) :=
{ mul := λ x y, (x.1*y.1 + 3*x.2*y.2, x.1*y.2 + x.2*y.1) }
@[simp] lemma mul_fst (x y : X q) : (x * y).1 = x.1 * y.1 + 3 * x.2 * y.2 := rfl
@[simp] lemma mul_snd (x y : X q) : (x * y).2 = x.1 * y.2 + x.2 * y.1 := rfl
instance : has_one (X q) :=
{ one := ⟨1,0⟩ }
@[simp] lemma one_fst : (1 : X q).1 = 1 := rfl
@[simp] lemma one_snd : (1 : X q).2 = 0 := rfl
@[simp] lemma bit0_fst (x : X q) : (bit0 x).1 = bit0 x.1 := rfl
@[simp] lemma bit0_snd (x : X q) : (bit0 x).2 = bit0 x.2 := rfl
@[simp] lemma bit1_fst (x : X q) : (bit1 x).1 = bit1 x.1 := rfl
@[simp] lemma bit1_snd (x : X q) : (bit1 x).2 = bit0 x.2 := by { dsimp [bit1], simp, }
instance : monoid (X q) :=
{ mul_assoc := λ x y z, by { ext; { dsimp, ring }, },
one := ⟨1,0⟩,
one_mul := λ x, by { ext; simp, },
mul_one := λ x, by { ext; simp, },
..(infer_instance : has_mul (X q)) }
instance : add_group_with_one (X q) :=
{ nat_cast := λ n, ⟨n, 0⟩,
nat_cast_zero := by simp,
nat_cast_succ := by simp [nat.cast, monoid.one],
int_cast := λ n, ⟨n, 0⟩,
int_cast_of_nat := λ n, by simp; refl,
int_cast_neg_succ_of_nat := λ n, by ext; simp; refl,
.. X.monoid, .. X.add_comm_group _ }
lemma left_distrib (x y z : X q) : x * (y + z) = x * y + x * z :=
by { ext; { dsimp, ring }, }
lemma right_distrib (x y z : X q) : (x + y) * z = x * z + y * z :=
by { ext; { dsimp, ring }, }
instance : ring (X q) :=
{ left_distrib := left_distrib,
right_distrib := right_distrib,
.. X.add_group_with_one,
..(infer_instance : add_comm_group (X q)),
..(infer_instance : monoid (X q)) }
instance : comm_ring (X q) :=
{ mul_comm := λ x y, by { ext; { dsimp, ring }, },
..(infer_instance : ring (X q))}
instance [fact (1 < (q : ℕ))] : nontrivial (X q) :=
⟨⟨0, 1, λ h, by { injection h with h1 _, exact zero_ne_one h1 } ⟩⟩
@[simp] lemma nat_coe_fst (n : ℕ) : (n : X q).fst = (n : zmod q) := rfl
@[simp] lemma nat_coe_snd (n : ℕ) : (n : X q).snd = (0 : zmod q) := rfl
@[simp] lemma int_coe_fst (n : ℤ) : (n : X q).fst = (n : zmod q) := rfl
@[simp] lemma int_coe_snd (n : ℤ) : (n : X q).snd = (0 : zmod q) := rfl
@[norm_cast]
lemma coe_mul (n m : ℤ) : ((n * m : ℤ) : X q) = (n : X q) * (m : X q) :=
by { ext; simp; ring }
@[norm_cast]
lemma coe_nat (n : ℕ) : ((n : ℤ) : X q) = (n : X q) :=
by { ext; simp, }
/-- The cardinality of `X` is `q^2`. -/
lemma X_card : fintype.card (X q) = q^2 :=
begin
dsimp [X],
rw [fintype.card_prod, zmod.card q],
ring,
end
/-- There are strictly fewer than `q^2` units, since `0` is not a unit. -/
lemma units_card (w : 1 < q) : fintype.card ((X q)ˣ) < q^2 :=
begin
haveI : fact (1 < (q:ℕ)) := ⟨w⟩,
convert card_units_lt (X q),
rw X_card,
end
/-- We define `ω = 2 + √3`. -/
def ω : X q := (2, 1)
/-- We define `ωb = 2 - √3`, which is the inverse of `ω`. -/
def ωb : X q := (2, -1)
lemma ω_mul_ωb (q : ℕ+) : (ω : X q) * ωb = 1 :=
begin
dsimp [ω, ωb],
ext; simp; ring,
end
lemma ωb_mul_ω (q : ℕ+) : (ωb : X q) * ω = 1 :=
begin
dsimp [ω, ωb],
ext; simp; ring,
end
/-- A closed form for the recurrence relation. -/
lemma closed_form (i : ℕ) : (s i : X q) = (ω : X q)^(2^i) + (ωb : X q)^(2^i) :=
begin
induction i with i ih,
{ dsimp [s, ω, ωb],
ext; { simp; refl, }, },
{ calc (s (i + 1) : X q) = ((s i)^2 - 2 : ℤ) : rfl
... = ((s i : X q)^2 - 2) : by push_cast
... = (ω^(2^i) + ωb^(2^i))^2 - 2 : by rw ih
... = (ω^(2^i))^2 + (ωb^(2^i))^2 + 2*(ωb^(2^i)*ω^(2^i)) - 2 : by ring
... = (ω^(2^i))^2 + (ωb^(2^i))^2 :
by rw [←mul_pow ωb ω, ωb_mul_ω, one_pow, mul_one, add_sub_cancel]
... = ω^(2^(i+1)) + ωb^(2^(i+1)) : by rw [←pow_mul, ←pow_mul, pow_succ'] }
end
end X
open X
/-!
Here and below, we introduce `p' = p - 2`, in order to avoid using subtraction in `ℕ`.
-/
/-- If `1 < p`, then `q p`, the smallest prime factor of `mersenne p`, is more than 2. -/
lemma two_lt_q (p' : ℕ) : 2 < q (p'+2) := begin
by_contradiction H,
simp at H,
interval_cases q (p'+2), clear H,
{ -- If q = 1, we get a contradiction from 2^p = 2
dsimp [q] at h, injection h with h', clear h,
simp [mersenne] at h',
exact lt_irrefl 2
(calc 2 ≤ p'+2 : nat.le_add_left _ _
... < 2^(p'+2) : nat.lt_two_pow _
... = 2 : nat.pred_inj (nat.one_le_two_pow _) dec_trivial h'), },
{ -- If q = 2, we get a contradiction from 2 ∣ 2^p - 1
dsimp [q] at h, injection h with h', clear h,
rw [mersenne, pnat.one_coe, nat.min_fac_eq_two_iff, pow_succ] at h',
exact nat.two_not_dvd_two_mul_sub_one (nat.one_le_two_pow _) h', }
end
theorem ω_pow_formula (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
∃ (k : ℤ), (ω : X (q (p'+2)))^(2^(p'+1)) =
k * (mersenne (p'+2)) * ((ω : X (q (p'+2)))^(2^p')) - 1 :=
begin
dsimp [lucas_lehmer_residue] at h,
rw s_zmod_eq_s p' at h,
simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h,
cases h with k h,
use k,
replace h := congr_arg (λ (n : ℤ), (n : X (q (p'+2)))) h, -- coercion from ℤ to X q
dsimp at h,
rw closed_form at h,
replace h := congr_arg (λ x, ω^2^p' * x) h,
dsimp at h,
have t : 2^p' + 2^p' = 2^(p'+1) := by ring_exp,
rw [mul_add, ←pow_add ω, t, ←mul_pow ω ωb (2^p'), ω_mul_ωb, one_pow] at h,
rw [mul_comm, coe_mul] at h,
rw [mul_comm _ (k : X (q (p'+2)))] at h,
replace h := eq_sub_of_add_eq h,
have : 1 ≤ 2 ^ (p' + 2) := nat.one_le_pow _ _ dec_trivial,
exact_mod_cast h,
end
/-- `q` is the minimum factor of `mersenne p`, so `M p = 0` in `X q`. -/
theorem mersenne_coe_X (p : ℕ) : (mersenne p : X (q p)) = 0 :=
begin
ext; simp [mersenne, q, zmod.nat_coe_zmod_eq_zero_iff_dvd, -pow_pos],
apply nat.min_fac_dvd,
end
theorem ω_pow_eq_neg_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
(ω : X (q (p'+2)))^(2^(p'+1)) = -1 :=
begin
cases ω_pow_formula p' h with k w,
rw [mersenne_coe_X] at w,
simpa using w,
end
theorem ω_pow_eq_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
(ω : X (q (p'+2)))^(2^(p'+2)) = 1 :=
calc (ω : X (q (p'+2)))^2^(p'+2)
= (ω^(2^(p'+1)))^2 : by rw [←pow_mul, ←pow_succ']
... = (-1)^2 : by rw ω_pow_eq_neg_one p' h
... = 1 : by simp
/-- `ω` as an element of the group of units. -/
def ω_unit (p : ℕ) : units (X (q p)) :=
{ val := ω,
inv := ωb,
val_inv := by simp [ω_mul_ωb],
inv_val := by simp [ωb_mul_ω], }
@[simp] lemma ω_unit_coe (p : ℕ) : (ω_unit p : X (q p)) = ω := rfl
/-- The order of `ω` in the unit group is exactly `2^p`. -/
theorem order_ω (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) :
order_of (ω_unit (p'+2)) = 2^(p'+2) :=
begin
apply nat.eq_prime_pow_of_dvd_least_prime_pow, -- the order of ω divides 2^p
{ exact nat.prime_two, },
{ intro o,
have ω_pow := order_of_dvd_iff_pow_eq_one.1 o,
replace ω_pow := congr_arg (units.coe_hom (X (q (p'+2))) :
units (X (q (p'+2))) → X (q (p'+2))) ω_pow,
simp at ω_pow,
have h : (1 : zmod (q (p'+2))) = -1 :=
congr_arg (prod.fst) ((ω_pow.symm).trans (ω_pow_eq_neg_one p' h)),
haveI : fact (2 < (q (p'+2) : ℕ)) := ⟨two_lt_q _⟩,
apply zmod.neg_one_ne_one h.symm, },
{ apply order_of_dvd_iff_pow_eq_one.2,
apply units.ext,
push_cast,
exact ω_pow_eq_one p' h, }
end
lemma order_ineq (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : 2^(p'+2) < (q (p'+2) : ℕ)^2 :=
calc 2^(p'+2) = order_of (ω_unit (p'+2)) : (order_ω p' h).symm
... ≤ fintype.card ((X _)ˣ) : order_of_le_card_univ
... < (q (p'+2) : ℕ)^2 : units_card (nat.lt_of_succ_lt (two_lt_q _))
end lucas_lehmer
export lucas_lehmer (lucas_lehmer_test lucas_lehmer_residue)
open lucas_lehmer
theorem lucas_lehmer_sufficiency (p : ℕ) (w : 1 < p) : lucas_lehmer_test p → (mersenne p).prime :=
begin
let p' := p - 2,
have z : p = p' + 2 := (tsub_eq_iff_eq_add_of_le w.nat_succ_le).mp rfl,
have w : 1 < p' + 2 := (nat.lt_of_sub_eq_succ rfl),
contrapose,
intros a t,
rw z at a,
rw z at t,
have h₁ := order_ineq p' t,
have h₂ := nat.min_fac_sq_le_self (mersenne_pos (nat.lt_of_succ_lt w)) a,
have h := lt_of_lt_of_le h₁ h₂,
exact not_lt_of_ge (nat.sub_le _ _) h,
end
-- Here we calculate the residue, very inefficiently, using `dec_trivial`. We can do much better.
example : (mersenne 5).prime := lucas_lehmer_sufficiency 5 (by norm_num) dec_trivial
-- Next we use `norm_num` to calculate each `s p i`.
namespace lucas_lehmer
open tactic
lemma s_mod_succ {p a i b c}
(h1 : (2^p - 1 : ℤ) = a)
(h2 : s_mod p i = b)
(h3 : (b * b - 2) % a = c) :
s_mod p (i+1) = c :=
by { dsimp [s_mod, mersenne], rw [h1, h2, sq, h3] }
/--
Given a goal of the form `lucas_lehmer_test p`,
attempt to do the calculation using `norm_num` to certify each step.
-/
meta def run_test : tactic unit :=
do `(lucas_lehmer_test %%p) ← target,
`[dsimp [lucas_lehmer_test]],
`[rw lucas_lehmer.residue_eq_zero_iff_s_mod_eq_zero, swap, norm_num],
p ← eval_expr ℕ p,
-- Calculate the candidate Mersenne prime
let M : ℤ := 2^p - 1,
t ← to_expr ``(2^%%`(p) - 1 = %%`(M)),
v ← to_expr ``(by norm_num : 2^%%`(p) - 1 = %%`(M)),
w ← assertv `w t v,
-- base case
t ← to_expr ``(s_mod %%`(p) 0 = 4),
v ← to_expr ``(by norm_num [lucas_lehmer.s_mod] : s_mod %%`(p) 0 = 4),
h ← assertv `h t v,
-- step case, repeated p-2 times
iterate_exactly (p-2) `[replace h := lucas_lehmer.s_mod_succ w h (by { norm_num, refl })],
-- now close the goal
h ← get_local `h,
exact h
end lucas_lehmer
/-- We verify that the tactic works to prove `127.prime`. -/
example : (mersenne 7).prime := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test).
/-!
This implementation works successfully to prove `(2^127 - 1).prime`,
and all the Mersenne primes up to this point appear in [archive/examples/mersenne_primes.lean].
`(2^127 - 1).prime` takes about 5 minutes to run (depending on your CPU!),
and unfortunately the next Mersenne prime `(2^521 - 1)`,
which was the first "computer era" prime,
is out of reach with the current implementation.
There's still low hanging fruit available to do faster computations
based on the formula
```
n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]
```
and the fact that `% 2^p` and `/ 2^p` can be very efficient on the binary representation.
Someone should do this, too!
-/
lemma modeq_mersenne (n k : ℕ) : k ≡ ((k / 2^n) + (k % 2^n)) [MOD 2^n - 1] :=
-- See https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/help.20finding.20a.20lemma/near/177698446
begin
conv in k { rw ← nat.div_add_mod k (2^n) },
refine nat.modeq.add_right _ _,
conv { congr, skip, skip, rw ← one_mul (k/2^n) },
exact (nat.modeq_sub $ nat.succ_le_of_lt $ pow_pos zero_lt_two _).mul_right _,
end
-- It's hard to know what the limiting factor for large Mersenne primes would be.
-- In the purely computational world, I think it's the squaring operation in `s`.
|
7a313d0565108e70dbfefd98a2c97537f46ac642 | d98f8063520761a65549cff3a6e0b1f33c180b92 | /super/imp.lean | 7a8c94c0fdc63134bdc46dd6a84e79bbf5ff142d | [] | no_license | gebner/POPL17_tutorial | 76cb1f3164b2f62812f718538d83e3c39bcda927 | 04aaaea171736317bf20bc849b96069188d73a55 | refs/heads/master | 1,610,408,282,574 | 1,504,117,783,000 | 1,504,117,783,000 | 78,612,687 | 0 | 0 | null | 1,484,118,765,000 | 1,484,118,765,000 | null | UTF-8 | Lean | false | false | 1,080 | lean | import tools.super
namespace imp
open tactic
@[reducible] def uname := string
inductive aexp
| val : nat → aexp
| var : uname → aexp
| plus : aexp → aexp → aexp
instance : decidable_eq aexp :=
by mk_dec_eq_instance
@[reducible] def value := nat
def state := uname → value
open aexp
def aval : aexp → state → value
| (val n) s := n
| (var x) s := s x
| (plus a₁ a₂) s := aval a₁ s + aval a₂ s
def updt (s : state) (x : uname) (v : value) : state :=
λ y, if x = y then v else s y
def asimp_const : aexp → aexp
| (val n) := val n
| (var x) := var x
| (plus a₁ a₂) :=
match asimp_const a₁, asimp_const a₂ with
| val n₁, val n₂ := val (n₁ + n₂)
| b₁, b₂ := plus b₁ b₂
end
lemma aval_asimp_const (a : aexp) (s : state) : aval (asimp_const a) s = aval a s :=
begin
induction a with n x a₁ a₂ ih₁ ih₂,
repeat {reflexivity},
unfold asimp_const aval,
rewrite [-ih₁, -ih₂],
cases (asimp_const a₁),
repeat {cases (asimp_const a₂), repeat {reflexivity}}
end
end imp
|
f58766b8ffe391806bd6ae9b23b495d4082d9933 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/category_theory/sites/sheaf_of_types.lean | 55220cad13759e224aa4bee7fe09a10296688922 | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 40,779 | lean | /-
Copyright (c) 2020 Bhavik Mehta. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Bhavik Mehta
-/
import category_theory.sites.pretopology
import category_theory.limits.shapes.types
/-!
# Sheaves of types on a Grothendieck topology
Defines the notion of a sheaf of types (usually called a sheaf of sets by mathematicians)
on a category equipped with a Grothendieck topology, as well as a range of equivalent
conditions useful in different situations.
First define what it means for a presheaf `P : Cᵒᵖ ⥤ Type v` to be a sheaf *for* a particular
presieve `R` on `X`:
* A *family of elements* `x` for `P` at `R` is an element `x_f` of `P Y` for every `f : Y ⟶ X` in
`R`. See `family_of_elements`.
* The family `x` is *compatible* if, for any `f₁ : Y₁ ⟶ X` and `f₂ : Y₂ ⟶ X` both in `R`,
and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂` such that `g₁ ≫ f₁ = g₂ ≫ f₂`, the restriction of
`x_f₁` along `g₁` agrees with the restriction of `x_f₂` along `g₂`.
See `family_of_elements.compatible`.
* An *amalgamation* `t` for the family is an element of `P X` such that for every `f : Y ⟶ X` in
`R`, the restriction of `t` on `f` is `x_f`.
See `family_of_elements.is_amalgamation`.
We then say `P` is *separated* for `R` if every compatible family has at most one amalgamation,
and it is a *sheaf* for `R` if every compatible family has a unique amalgamation.
See `is_separated_for` and `is_sheaf_for`.
In the special case where `R` is a sieve, the compatibility condition can be simplified:
* The family `x` is *compatible* if, for any `f : Y ⟶ X` in `R` and `g : Z ⟶ Y`, the restriction of
`x_f` along `g` agrees with `x_(g ≫ f)` (which is well defined since `g ≫ f` is in `R`).
See `family_of_elements.sieve_compatible` and `compatible_iff_sieve_compatible`.
In the special case where `C` has pullbacks, the compatibility condition can be simplified:
* The family `x` is *compatible* if, for any `f : Y ⟶ X` and `g : Z ⟶ X` both in `R`,
the restriction of `x_f` along `π₁ : pullback f g ⟶ Y` agrees with the restriction of `x_g`
along `π₂ : pullback f g ⟶ Z`.
See `family_of_elements.pullback_compatible` and `pullback_compatible_iff`.
Now given a Grothendieck topology `J`, `P` is a sheaf if it is a sheaf for every sieve in the
topology. See `is_sheaf`.
In the case where the topology is generated by a basis, it suffices to check `P` is a sheaf for
every presieve in the pretopology. See `is_sheaf_pretopology`.
We also provide equivalent conditions to satisfy alternate definitions given in the literature.
* Stacks: In `equalizer.presieve.sheaf_condition`, the sheaf condition at a presieve is shown to be
equivalent to that of https://stacks.math.columbia.edu/tag/00VM (and combined with
`is_sheaf_pretopology`, this shows the notions of `is_sheaf` are exactly equivalent.)
The condition of https://stacks.math.columbia.edu/tag/00Z8 is virtually identical to the
statement of `yoneda_condition_iff_sheaf_condition` (since the bijection described there carries
the same information as the unique existence.)
* Maclane-Moerdijk [MM92]: Using `compatible_iff_sieve_compatible`, the definitions of `is_sheaf`
are equivalent. There are also alternate definitions given:
- Yoneda condition: Defined in `yoneda_sheaf_condition` and equivalence in
`yoneda_condition_iff_sheaf_condition`.
- Equalizer condition (Equation 3): Defined in the `equalizer.sieve` namespace, and equivalence
in `equalizer.sieve.sheaf_condition`.
- Matching family for presieves with pullback: `pullback_compatible_iff`.
- Sheaf for a pretopology (Prop 1): `is_sheaf_pretopology` combined with the previous.
- Sheaf for a pretopology as equalizer (Prop 1, bis): `equalizer.presieve.sheaf_condition`
combined with the previous.
## Implementation
The sheaf condition is given as a proposition, rather than a subsingleton in `Type (max u₁ v)`.
This doesn't seem to make a big difference, other than making a couple of definitions noncomputable,
but it means that equivalent conditions can be given as `↔` statements rather than `≃` statements,
which can be convenient.
## References
* [MM92]: *Sheaves in geometry and logic*, Saunders MacLane, and Ieke Moerdijk:
Chapter III, Section 4.
* [Elephant]: *Sketches of an Elephant*, P. T. Johnstone: C2.1.
* https://stacks.math.columbia.edu/tag/00VL (sheaves on a pretopology or site)
* https://stacks.math.columbia.edu/tag/00ZB (sheaves on a topology)
-/
universes w v₁ v₂ u₁ u₂
namespace category_theory
open opposite category_theory category limits sieve
namespace presieve
variables {C : Type u₁} [category.{v₁} C]
variables {P Q U : Cᵒᵖ ⥤ Type w}
variables {X Y : C} {S : sieve X} {R : presieve X}
variables (J J₂ : grothendieck_topology C)
/--
A family of elements for a presheaf `P` given a collection of arrows `R` with fixed codomain `X`
consists of an element of `P Y` for every `f : Y ⟶ X` in `R`.
A presheaf is a sheaf (resp, separated) if every *compatible* family of elements has exactly one
(resp, at most one) amalgamation.
This data is referred to as a `family` in [MM92], Chapter III, Section 4. It is also a concrete
version of the elements of the middle object in https://stacks.math.columbia.edu/tag/00VM which is
more useful for direct calculations. It is also used implicitly in Definition C2.1.2 in [Elephant].
-/
def family_of_elements (P : Cᵒᵖ ⥤ Type w) (R : presieve X) :=
Π ⦃Y : C⦄ (f : Y ⟶ X), R f → P.obj (op Y)
instance : inhabited (family_of_elements P (⊥ : presieve X)) := ⟨λ Y f, false.elim⟩
/--
A family of elements for a presheaf on the presieve `R₂` can be restricted to a smaller presieve
`R₁`.
-/
def family_of_elements.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂) :
family_of_elements P R₂ → family_of_elements P R₁ :=
λ x Y f hf, x f (h _ hf)
/--
A family of elements for the arrow set `R` is *compatible* if for any `f₁ : Y₁ ⟶ X` and
`f₂ : Y₂ ⟶ X` in `R`, and any `g₁ : Z ⟶ Y₁` and `g₂ : Z ⟶ Y₂`, if the square `g₁ ≫ f₁ = g₂ ≫ f₂`
commutes then the elements of `P Z` obtained by restricting the element of `P Y₁` along `g₁` and
restricting the element of `P Y₂` along `g₂` are the same.
In special cases, this condition can be simplified, see `pullback_compatible_iff` and
`compatible_iff_sieve_compatible`.
This is referred to as a "compatible family" in Definition C2.1.2 of [Elephant], and on nlab:
https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents
-/
def family_of_elements.compatible (x : family_of_elements P R) : Prop :=
∀ ⦃Y₁ Y₂ Z⦄ (g₁ : Z ⟶ Y₁) (g₂ : Z ⟶ Y₂) ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄
(h₁ : R f₁) (h₂ : R f₂), g₁ ≫ f₁ = g₂ ≫ f₂ → P.map g₁.op (x f₁ h₁) = P.map g₂.op (x f₂ h₂)
/--
If the category `C` has pullbacks, this is an alternative condition for a family of elements to be
compatible: For any `f : Y ⟶ X` and `g : Z ⟶ X` in the presieve `R`, the restriction of the
given elements for `f` and `g` to the pullback agree.
This is equivalent to being compatible (provided `C` has pullbacks), shown in
`pullback_compatible_iff`.
This is the definition for a "matching" family given in [MM92], Chapter III, Section 4,
Equation (5). Viewing the type `family_of_elements` as the middle object of the fork in
https://stacks.math.columbia.edu/tag/00VM, this condition expresses that `pr₀* (x) = pr₁* (x)`,
using the notation defined there.
-/
def family_of_elements.pullback_compatible (x : family_of_elements P R) [has_pullbacks C] : Prop :=
∀ ⦃Y₁ Y₂⦄ ⦃f₁ : Y₁ ⟶ X⦄ ⦃f₂ : Y₂ ⟶ X⦄ (h₁ : R f₁) (h₂ : R f₂),
P.map (pullback.fst : pullback f₁ f₂ ⟶ _).op (x f₁ h₁) = P.map pullback.snd.op (x f₂ h₂)
lemma pullback_compatible_iff (x : family_of_elements P R) [has_pullbacks C] :
x.compatible ↔ x.pullback_compatible :=
begin
split,
{ intros t Y₁ Y₂ f₁ f₂ hf₁ hf₂,
apply t,
apply pullback.condition },
{ intros t Y₁ Y₂ Z g₁ g₂ f₁ f₂ hf₁ hf₂ comm,
rw [←pullback.lift_fst _ _ comm, op_comp, functor_to_types.map_comp_apply, t hf₁ hf₂,
←functor_to_types.map_comp_apply, ←op_comp, pullback.lift_snd] }
end
/-- The restriction of a compatible family is compatible. -/
lemma family_of_elements.compatible.restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂)
{x : family_of_elements P R₂} : x.compatible → (x.restrict h).compatible :=
λ q Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm, q g₁ g₂ (h _ h₁) (h _ h₂) comm
/--
Extend a family of elements to the sieve generated by an arrow set.
This is the construction described as "easy" in Lemma C2.1.3 of [Elephant].
-/
noncomputable def family_of_elements.sieve_extend (x : family_of_elements P R) :
family_of_elements P (generate R) :=
λ Z f hf, P.map hf.some_spec.some.op (x _ hf.some_spec.some_spec.some_spec.1)
/-- The extension of a compatible family to the generated sieve is compatible. -/
lemma family_of_elements.compatible.sieve_extend {x : family_of_elements P R} (hx : x.compatible) :
x.sieve_extend.compatible :=
begin
intros _ _ _ _ _ _ _ h₁ h₂ comm,
iterate 2 { erw ← functor_to_types.map_comp_apply, rw ← op_comp }, apply hx,
simp [comm, h₁.some_spec.some_spec.some_spec.2, h₂.some_spec.some_spec.some_spec.2],
end
/-- The extension of a family agrees with the original family. -/
lemma extend_agrees {x : family_of_elements P R} (t : x.compatible) {f : Y ⟶ X} (hf : R f) :
x.sieve_extend f (le_generate R Y hf) = x f hf :=
begin
have h := (le_generate R Y hf).some_spec,
unfold family_of_elements.sieve_extend,
rw t h.some (𝟙 _) _ hf _,
{ simp }, { rw id_comp, exact h.some_spec.some_spec.2 },
end
/-- The restriction of an extension is the original. -/
@[simp]
lemma restrict_extend {x : family_of_elements P R} (t : x.compatible) :
x.sieve_extend.restrict (le_generate R) = x :=
begin
ext Y f hf,
exact extend_agrees t hf,
end
/--
If the arrow set for a family of elements is actually a sieve (i.e. it is downward closed) then the
consistency condition can be simplified.
This is an equivalent condition, see `compatible_iff_sieve_compatible`.
This is the notion of "matching" given for families on sieves given in [MM92], Chapter III,
Section 4, Equation 1, and nlab: https://ncatlab.org/nlab/show/matching+family.
See also the discussion before Lemma C2.1.4 of [Elephant].
-/
def family_of_elements.sieve_compatible (x : family_of_elements P S) : Prop :=
∀ ⦃Y Z⦄ (f : Y ⟶ X) (g : Z ⟶ Y) (hf), x (g ≫ f) (S.downward_closed hf g) = P.map g.op (x f hf)
lemma compatible_iff_sieve_compatible (x : family_of_elements P S) :
x.compatible ↔ x.sieve_compatible :=
begin
split,
{ intros h Y Z f g hf,
simpa using h (𝟙 _) g (S.downward_closed hf g) hf (id_comp _) },
{ intros h Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ k,
simp_rw [← h f₁ g₁ h₁, k, h f₂ g₂ h₂] }
end
lemma family_of_elements.compatible.to_sieve_compatible {x : family_of_elements P S}
(t : x.compatible) : x.sieve_compatible :=
(compatible_iff_sieve_compatible x).1 t
/--
Given a family of elements `x` for the sieve `S` generated by a presieve `R`, if `x` is restricted
to `R` and then extended back up to `S`, the resulting extension equals `x`.
-/
@[simp]
lemma extend_restrict {x : family_of_elements P (generate R)} (t : x.compatible) :
(x.restrict (le_generate R)).sieve_extend = x :=
begin
rw compatible_iff_sieve_compatible at t,
ext _ _ h, apply (t _ _ _).symm.trans, congr,
exact h.some_spec.some_spec.some_spec.2,
end
/--
Two compatible families on the sieve generated by a presieve `R` are equal if and only if they are
equal when restricted to `R`.
-/
lemma restrict_inj {x₁ x₂ : family_of_elements P (generate R)}
(t₁ : x₁.compatible) (t₂ : x₂.compatible) :
x₁.restrict (le_generate R) = x₂.restrict (le_generate R) → x₁ = x₂ :=
λ h, by { rw [←extend_restrict t₁, ←extend_restrict t₂], congr, exact h }
/-- Compatible families of elements for a presheaf of types `P` and a presieve `R`
are in 1-1 correspondence with compatible families for the same presheaf and
the sieve generated by `R`, through extension and restriction. -/
@[simps] noncomputable def compatible_equiv_generate_sieve_compatible :
{x : family_of_elements P R // x.compatible} ≃
{x : family_of_elements P (generate R) // x.compatible} :=
{ to_fun := λ x, ⟨x.1.sieve_extend, x.2.sieve_extend⟩,
inv_fun := λ x, ⟨x.1.restrict (le_generate R), x.2.restrict _⟩,
left_inv := λ x, subtype.ext (restrict_extend x.2),
right_inv := λ x, subtype.ext (extend_restrict x.2) }
lemma family_of_elements.comp_of_compatible (S : sieve X) {x : family_of_elements P S}
(t : x.compatible) {f : Y ⟶ X} (hf : S f) {Z} (g : Z ⟶ Y) :
x (g ≫ f) (S.downward_closed hf g) = P.map g.op (x f hf) :=
by simpa using t (𝟙 _) g (S.downward_closed hf g) hf (id_comp _)
section functor_pullback
variables {D : Type u₂} [category.{v₂} D] (F : D ⥤ C) {Z : D}
variables {T : presieve (F.obj Z)} {x : family_of_elements P T}
/--
Given a family of elements of a sieve `S` on `F(X)`, we can realize it as a family of elements of
`S.functor_pullback F`.
-/
def family_of_elements.functor_pullback (x : family_of_elements P T) :
family_of_elements (F.op ⋙ P) (T.functor_pullback F) := λ Y f hf, x (F.map f) hf
lemma family_of_elements.compatible.functor_pullback (h : x.compatible) :
(x.functor_pullback F).compatible :=
begin
intros Z₁ Z₂ W g₁ g₂ f₁ f₂ h₁ h₂ eq,
exact h (F.map g₁) (F.map g₂) h₁ h₂ (by simp only [← F.map_comp, eq])
end
end functor_pullback
/--
Given a family of elements of a sieve `S` on `X` whose values factors through `F`, we can
realize it as a family of elements of `S.functor_pushforward F`. Since the preimage is obtained by
choice, this is not well-defined generally.
-/
noncomputable
def family_of_elements.functor_pushforward {D : Type u₂} [category.{v₂} D] (F : D ⥤ C) {X : D}
{T : presieve X} (x : family_of_elements (F.op ⋙ P) T) :
family_of_elements P (T.functor_pushforward F) := λ Y f h,
by { obtain ⟨Z, g, h, h₁, _⟩ := get_functor_pushforward_structure h, exact P.map h.op (x g h₁) }
section pullback
/--
Given a family of elements of a sieve `S` on `X`, and a map `Y ⟶ X`, we can obtain a
family of elements of `S.pullback f` by taking the same elements.
-/
def family_of_elements.pullback (f : Y ⟶ X) (x : family_of_elements P S) :
family_of_elements P (S.pullback f) := λ _ g hg, x (g ≫ f) hg
lemma family_of_elements.compatible.pullback (f : Y ⟶ X) {x : family_of_elements P S}
(h : x.compatible) : (x.pullback f).compatible :=
begin
simp only [compatible_iff_sieve_compatible] at h ⊢,
intros W Z f₁ f₂ hf,
unfold family_of_elements.pullback,
rw ← (h (f₁ ≫ f) f₂ hf),
simp only [assoc],
end
end pullback
/--
Given a morphism of presheaves `f : P ⟶ Q`, we can take a family of elements valued in `P` to a
family of elements valued in `Q` by composing with `f`.
-/
def family_of_elements.comp_presheaf_map (f : P ⟶ Q) (x : family_of_elements P R) :
family_of_elements Q R := λ Y g hg, f.app (op Y) (x g hg)
@[simp]
lemma family_of_elements.comp_presheaf_map_id (x : family_of_elements P R) :
x.comp_presheaf_map (𝟙 P) = x := rfl
@[simp]
lemma family_of_elements.comp_prersheaf_map_comp (x : family_of_elements P R)
(f : P ⟶ Q) (g : Q ⟶ U) :
(x.comp_presheaf_map f).comp_presheaf_map g = x.comp_presheaf_map (f ≫ g) := rfl
lemma family_of_elements.compatible.comp_presheaf_map (f : P ⟶ Q) {x : family_of_elements P R}
(h : x.compatible) : (x.comp_presheaf_map f).compatible :=
begin
intros Z₁ Z₂ W g₁ g₂ f₁ f₂ h₁ h₂ eq,
unfold family_of_elements.comp_presheaf_map,
rwa [← functor_to_types.naturality, ← functor_to_types.naturality, h],
end
/--
The given element `t` of `P.obj (op X)` is an *amalgamation* for the family of elements `x` if every
restriction `P.map f.op t = x_f` for every arrow `f` in the presieve `R`.
This is the definition given in https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents,
and https://ncatlab.org/nlab/show/matching+family, as well as [MM92], Chapter III, Section 4,
equation (2).
-/
def family_of_elements.is_amalgamation (x : family_of_elements P R)
(t : P.obj (op X)) : Prop :=
∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : R f), P.map f.op t = x f h
lemma family_of_elements.is_amalgamation.comp_presheaf_map
{x : family_of_elements P R} {t} (f : P ⟶ Q) (h : x.is_amalgamation t) :
(x.comp_presheaf_map f).is_amalgamation (f.app (op X) t) :=
begin
intros Y g hg,
dsimp [family_of_elements.comp_presheaf_map],
change (f.app _ ≫ Q.map _) _ = _,
simp [← f.naturality, h g hg],
end
lemma is_compatible_of_exists_amalgamation (x : family_of_elements P R)
(h : ∃ t, x.is_amalgamation t) : x.compatible :=
begin
cases h with t ht,
intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ comm,
rw [←ht _ h₁, ←ht _ h₂, ←functor_to_types.map_comp_apply, ←op_comp, comm],
simp,
end
lemma is_amalgamation_restrict {R₁ R₂ : presieve X} (h : R₁ ≤ R₂)
(x : family_of_elements P R₂) (t : P.obj (op X)) (ht : x.is_amalgamation t) :
(x.restrict h).is_amalgamation t :=
λ Y f hf, ht f (h Y hf)
lemma is_amalgamation_sieve_extend {R : presieve X}
(x : family_of_elements P R) (t : P.obj (op X)) (ht : x.is_amalgamation t) :
x.sieve_extend.is_amalgamation t :=
begin
intros Y f hf,
dsimp [family_of_elements.sieve_extend],
rw [←ht _, ←functor_to_types.map_comp_apply, ←op_comp, hf.some_spec.some_spec.some_spec.2],
end
/-- A presheaf is separated for a presieve if there is at most one amalgamation. -/
def is_separated_for (P : Cᵒᵖ ⥤ Type w) (R : presieve X) : Prop :=
∀ (x : family_of_elements P R) (t₁ t₂),
x.is_amalgamation t₁ → x.is_amalgamation t₂ → t₁ = t₂
lemma is_separated_for.ext {R : presieve X} (hR : is_separated_for P R)
{t₁ t₂ : P.obj (op X)} (h : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄ (hf : R f), P.map f.op t₁ = P.map f.op t₂) :
t₁ = t₂ :=
hR (λ Y f hf, P.map f.op t₂) t₁ t₂ (λ Y f hf, h hf) (λ Y f hf, rfl)
lemma is_separated_for_iff_generate :
is_separated_for P R ↔ is_separated_for P (generate R) :=
begin
split,
{ intros h x t₁ t₂ ht₁ ht₂,
apply h (x.restrict (le_generate R)) t₁ t₂ _ _,
{ exact is_amalgamation_restrict _ x t₁ ht₁ },
{ exact is_amalgamation_restrict _ x t₂ ht₂ } },
{ intros h x t₁ t₂ ht₁ ht₂,
apply h (x.sieve_extend),
{ exact is_amalgamation_sieve_extend x t₁ ht₁ },
{ exact is_amalgamation_sieve_extend x t₂ ht₂ } }
end
lemma is_separated_for_top (P : Cᵒᵖ ⥤ Type w) : is_separated_for P (⊤ : presieve X) :=
λ x t₁ t₂ h₁ h₂,
begin
have q₁ := h₁ (𝟙 X) (by simp),
have q₂ := h₂ (𝟙 X) (by simp),
simp only [op_id, functor_to_types.map_id_apply] at q₁ q₂,
rw [q₁, q₂],
end
/--
We define `P` to be a sheaf for the presieve `R` if every compatible family has a unique
amalgamation.
This is the definition of a sheaf for the given presieve given in C2.1.2 of [Elephant], and
https://ncatlab.org/nlab/show/sheaf#GeneralDefinitionInComponents.
Using `compatible_iff_sieve_compatible`,
this is equivalent to the definition of a sheaf in [MM92], Chapter III, Section 4.
-/
def is_sheaf_for (P : Cᵒᵖ ⥤ Type w) (R : presieve X) : Prop :=
∀ (x : family_of_elements P R), x.compatible → ∃! t, x.is_amalgamation t
/--
This is an equivalent condition to be a sheaf, which is useful for the abstraction to local
operators on elementary toposes. However this definition is defined only for sieves, not presieves.
The equivalence between this and `is_sheaf_for` is given in `yoneda_condition_iff_sheaf_condition`.
This version is also useful to establish that being a sheaf is preserved under isomorphism of
presheaves.
See the discussion before Equation (3) of [MM92], Chapter III, Section 4. See also C2.1.4 of
[Elephant]. This is also a direct reformulation of <https://stacks.math.columbia.edu/tag/00Z8>.
-/
def yoneda_sheaf_condition (P : Cᵒᵖ ⥤ Type v₁) (S : sieve X) : Prop :=
∀ (f : S.functor ⟶ P), ∃! g, S.functor_inclusion ≫ g = f
-- TODO: We can generalize the universe parameter v₁ above by composing with
-- appropriate `ulift_functor`s.
/--
(Implementation). This is a (primarily internal) equivalence between natural transformations
and compatible families.
Cf the discussion after Lemma 7.47.10 in <https://stacks.math.columbia.edu/tag/00YW>. See also
the proof of C2.1.4 of [Elephant], and the discussion in [MM92], Chapter III, Section 4.
-/
def nat_trans_equiv_compatible_family {P : Cᵒᵖ ⥤ Type v₁} :
(S.functor ⟶ P) ≃ {x : family_of_elements P S // x.compatible} :=
{ to_fun := λ α,
begin
refine ⟨λ Y f hf, _, _⟩,
{ apply α.app (op Y) ⟨_, hf⟩ },
{ rw compatible_iff_sieve_compatible,
intros Y Z f g hf,
dsimp,
rw ← functor_to_types.naturality _ _ α g.op,
refl }
end,
inv_fun := λ t,
{ app := λ Y f, t.1 _ f.2,
naturality' := λ Y Z g,
begin
ext ⟨f, hf⟩,
apply t.2.to_sieve_compatible _,
end },
left_inv := λ α,
begin
ext X ⟨_, _⟩,
refl
end,
right_inv :=
begin
rintro ⟨x, hx⟩,
refl,
end }
/-- (Implementation). A lemma useful to prove `yoneda_condition_iff_sheaf_condition`. -/
lemma extension_iff_amalgamation {P : Cᵒᵖ ⥤ Type v₁} (x : S.functor ⟶ P) (g : yoneda.obj X ⟶ P) :
S.functor_inclusion ≫ g = x ↔
(nat_trans_equiv_compatible_family x).1.is_amalgamation (yoneda_equiv g) :=
begin
change _ ↔ ∀ ⦃Y : C⦄ (f : Y ⟶ X) (h : S f), P.map f.op (yoneda_equiv g) = x.app (op Y) ⟨f, h⟩,
split,
{ rintro rfl Y f hf,
rw yoneda_equiv_naturality,
dsimp,
simp }, -- See note [dsimp, simp].
{ intro h,
ext Y ⟨f, hf⟩,
have : _ = x.app Y _ := h f hf,
rw yoneda_equiv_naturality at this,
rw ← this,
dsimp,
simp }, -- See note [dsimp, simp].
end
/--
The yoneda version of the sheaf condition is equivalent to the sheaf condition.
C2.1.4 of [Elephant].
-/
lemma is_sheaf_for_iff_yoneda_sheaf_condition {P : Cᵒᵖ ⥤ Type v₁} :
is_sheaf_for P S ↔ yoneda_sheaf_condition P S :=
begin
rw [is_sheaf_for, yoneda_sheaf_condition],
simp_rw [extension_iff_amalgamation],
rw equiv.forall_congr_left' nat_trans_equiv_compatible_family,
rw subtype.forall,
apply ball_congr,
intros x hx,
rw equiv.exists_unique_congr_left _,
simp,
end
/--
If `P` is a sheaf for the sieve `S` on `X`, a natural transformation from `S` (viewed as a functor)
to `P` can be (uniquely) extended to all of `yoneda.obj X`.
f
S → P
↓ ↗
yX
-/
noncomputable def is_sheaf_for.extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S)
(f : S.functor ⟶ P) : yoneda.obj X ⟶ P :=
(is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists.some
/--
Show that the extension of `f : S.functor ⟶ P` to all of `yoneda.obj X` is in fact an extension, ie
that the triangle below commutes, provided `P` is a sheaf for `S`
f
S → P
↓ ↗
yX
-/
@[simp, reassoc]
lemma is_sheaf_for.functor_inclusion_comp_extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S)
(f : S.functor ⟶ P) : S.functor_inclusion ≫ h.extend f = f :=
(is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).exists.some_spec
/-- The extension of `f` to `yoneda.obj X` is unique. -/
lemma is_sheaf_for.unique_extend {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) {f : S.functor ⟶ P}
(t : yoneda.obj X ⟶ P) (ht : S.functor_inclusion ≫ t = f) :
t = h.extend f :=
((is_sheaf_for_iff_yoneda_sheaf_condition.1 h f).unique ht (h.functor_inclusion_comp_extend f))
/--
If `P` is a sheaf for the sieve `S` on `X`, then if two natural transformations from `yoneda.obj X`
to `P` agree when restricted to the subfunctor given by `S`, they are equal.
-/
lemma is_sheaf_for.hom_ext {P : Cᵒᵖ ⥤ Type v₁} (h : is_sheaf_for P S) (t₁ t₂ : yoneda.obj X ⟶ P)
(ht : S.functor_inclusion ≫ t₁ = S.functor_inclusion ≫ t₂) :
t₁ = t₂ :=
(h.unique_extend t₁ ht).trans (h.unique_extend t₂ rfl).symm
/-- `P` is a sheaf for `R` iff it is separated for `R` and there exists an amalgamation. -/
lemma is_separated_for_and_exists_is_amalgamation_iff_sheaf_for :
is_separated_for P R ∧ (∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) ↔
is_sheaf_for P R :=
begin
rw [is_separated_for, ←forall_and_distrib],
apply forall_congr,
intro x,
split,
{ intros z hx, exact exists_unique_of_exists_of_unique (z.2 hx) z.1 },
{ intros h,
refine ⟨_, (exists_of_exists_unique ∘ h)⟩,
intros t₁ t₂ ht₁ ht₂,
apply (h _).unique ht₁ ht₂,
exact is_compatible_of_exists_amalgamation x ⟨_, ht₂⟩ }
end
/--
If `P` is separated for `R` and every family has an amalgamation, then `P` is a sheaf for `R`.
-/
lemma is_separated_for.is_sheaf_for (t : is_separated_for P R) :
(∀ (x : family_of_elements P R), x.compatible → ∃ t, x.is_amalgamation t) →
is_sheaf_for P R :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
exact and.intro t,
end
/-- If `P` is a sheaf for `R`, it is separated for `R`. -/
lemma is_sheaf_for.is_separated_for : is_sheaf_for P R → is_separated_for P R :=
λ q, (is_separated_for_and_exists_is_amalgamation_iff_sheaf_for.2 q).1
/-- Get the amalgamation of the given compatible family, provided we have a sheaf. -/
noncomputable def is_sheaf_for.amalgamate
(t : is_sheaf_for P R) (x : family_of_elements P R) (hx : x.compatible) :
P.obj (op X) :=
(t x hx).exists.some
lemma is_sheaf_for.is_amalgamation
(t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) :
x.is_amalgamation (t.amalgamate x hx) :=
(t x hx).exists.some_spec
@[simp]
lemma is_sheaf_for.valid_glue
(t : is_sheaf_for P R) {x : family_of_elements P R} (hx : x.compatible) (f : Y ⟶ X) (Hf : R f) :
P.map f.op (t.amalgamate x hx) = x f Hf :=
t.is_amalgamation hx f Hf
/-- C2.1.3 in [Elephant] -/
lemma is_sheaf_for_iff_generate (R : presieve X) :
is_sheaf_for P R ↔ is_sheaf_for P (generate R) :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
rw ← is_separated_for_iff_generate,
apply and_congr (iff.refl _),
split,
{ intros q x hx,
apply exists_imp_exists _ (q _ (hx.restrict (le_generate R))),
intros t ht,
simpa [hx] using is_amalgamation_sieve_extend _ _ ht },
{ intros q x hx,
apply exists_imp_exists _ (q _ hx.sieve_extend),
intros t ht,
simpa [hx] using is_amalgamation_restrict (le_generate R) _ _ ht },
end
/--
Every presheaf is a sheaf for the family {𝟙 X}.
[Elephant] C2.1.5(i)
-/
lemma is_sheaf_for_singleton_iso (P : Cᵒᵖ ⥤ Type w) :
is_sheaf_for P (presieve.singleton (𝟙 X)) :=
begin
intros x hx,
refine ⟨x _ (presieve.singleton_self _), _, _⟩,
{ rintro _ _ ⟨rfl, rfl⟩,
simp },
{ intros t ht,
simpa using ht _ (presieve.singleton_self _) }
end
/--
Every presheaf is a sheaf for the maximal sieve.
[Elephant] C2.1.5(ii)
-/
lemma is_sheaf_for_top_sieve (P : Cᵒᵖ ⥤ Type w) :
is_sheaf_for P ((⊤ : sieve X) : presieve X) :=
begin
rw ← generate_of_singleton_is_split_epi (𝟙 X),
rw ← is_sheaf_for_iff_generate,
apply is_sheaf_for_singleton_iso,
end
/--
If `P` is a sheaf for `S`, and it is iso to `P'`, then `P'` is a sheaf for `S`. This shows that
"being a sheaf for a presieve" is a mathematical or hygenic property.
-/
lemma is_sheaf_for_iso {P' : Cᵒᵖ ⥤ Type w} (i : P ≅ P') : is_sheaf_for P R → is_sheaf_for P' R :=
begin
intros h x hx,
let x' := x.comp_presheaf_map i.inv,
have : x'.compatible := family_of_elements.compatible.comp_presheaf_map i.inv hx,
obtain ⟨t, ht1, ht2⟩ := h x' this,
use i.hom.app _ t,
fsplit,
{ convert family_of_elements.is_amalgamation.comp_presheaf_map i.hom ht1,
dsimp [x'],
simp },
{ intros y hy,
rw (show y = (i.inv.app (op X) ≫ i.hom.app (op X)) y, by simp),
simp [ ht2 (i.inv.app _ y) (family_of_elements.is_amalgamation.comp_presheaf_map i.inv hy)] }
end
/--
If a presieve `R` on `X` has a subsieve `S` such that:
* `P` is a sheaf for `S`.
* For every `f` in `R`, `P` is separated for the pullback of `S` along `f`,
then `P` is a sheaf for `R`.
This is closely related to [Elephant] C2.1.6(i).
-/
lemma is_sheaf_for_subsieve_aux (P : Cᵒᵖ ⥤ Type w) {S : sieve X} {R : presieve X}
(h : (S : presieve X) ≤ R)
(hS : is_sheaf_for P S)
(trans : ∀ ⦃Y⦄ ⦃f : Y ⟶ X⦄, R f → is_separated_for P (S.pullback f)) :
is_sheaf_for P R :=
begin
rw ← is_separated_for_and_exists_is_amalgamation_iff_sheaf_for,
split,
{ intros x t₁ t₂ ht₁ ht₂,
exact hS.is_separated_for _ _ _ (is_amalgamation_restrict h x t₁ ht₁)
(is_amalgamation_restrict h x t₂ ht₂) },
{ intros x hx,
use hS.amalgamate _ (hx.restrict h),
intros W j hj,
apply (trans hj).ext,
intros Y f hf,
rw [←functor_to_types.map_comp_apply, ←op_comp,
hS.valid_glue (hx.restrict h) _ hf, family_of_elements.restrict,
←hx (𝟙 _) f _ _ (id_comp _)],
simp },
end
/--
If `P` is a sheaf for every pullback of the sieve `S`, then `P` is a sheaf for any presieve which
contains `S`.
This is closely related to [Elephant] C2.1.6.
-/
lemma is_sheaf_for_subsieve (P : Cᵒᵖ ⥤ Type w) {S : sieve X} {R : presieve X}
(h : (S : presieve X) ≤ R)
(trans : Π ⦃Y⦄ (f : Y ⟶ X), is_sheaf_for P (S.pullback f)) :
is_sheaf_for P R :=
is_sheaf_for_subsieve_aux P h (by simpa using trans (𝟙 _)) (λ Y f hf, (trans f).is_separated_for)
/-- A presheaf is separated for a topology if it is separated for every sieve in the topology. -/
def is_separated (P : Cᵒᵖ ⥤ Type w) : Prop :=
∀ {X} (S : sieve X), S ∈ J X → is_separated_for P S
/--
A presheaf is a sheaf for a topology if it is a sheaf for every sieve in the topology.
If the given topology is given by a pretopology, `is_sheaf_for_pretopology` shows it suffices to
check the sheaf condition at presieves in the pretopology.
-/
def is_sheaf (P : Cᵒᵖ ⥤ Type w) : Prop :=
∀ ⦃X⦄ (S : sieve X), S ∈ J X → is_sheaf_for P S
lemma is_sheaf.is_sheaf_for {P : Cᵒᵖ ⥤ Type w} (hp : is_sheaf J P)
(R : presieve X) (hr : generate R ∈ J X) : is_sheaf_for P R :=
(is_sheaf_for_iff_generate R).2 $ hp _ hr
lemma is_sheaf_of_le (P : Cᵒᵖ ⥤ Type w) {J₁ J₂ : grothendieck_topology C} :
J₁ ≤ J₂ → is_sheaf J₂ P → is_sheaf J₁ P :=
λ h t X S hS, t S (h _ hS)
lemma is_separated_of_is_sheaf (P : Cᵒᵖ ⥤ Type w) (h : is_sheaf J P) : is_separated J P :=
λ X S hS, (h S hS).is_separated_for
/-- The property of being a sheaf is preserved by isomorphism. -/
lemma is_sheaf_iso {P' : Cᵒᵖ ⥤ Type w} (i : P ≅ P') (h : is_sheaf J P) : is_sheaf J P' :=
λ X S hS, is_sheaf_for_iso i (h S hS)
lemma is_sheaf_of_yoneda {P : Cᵒᵖ ⥤ Type v₁}
(h : ∀ {X} (S : sieve X), S ∈ J X → yoneda_sheaf_condition P S) : is_sheaf J P :=
λ X S hS, is_sheaf_for_iff_yoneda_sheaf_condition.2 (h _ hS)
/--
For a topology generated by a basis, it suffices to check the sheaf condition on the basis
presieves only.
-/
lemma is_sheaf_pretopology [has_pullbacks C] (K : pretopology C) :
is_sheaf (K.to_grothendieck C) P ↔ (∀ {X : C} (R : presieve X), R ∈ K X → is_sheaf_for P R) :=
begin
split,
{ intros PJ X R hR,
rw is_sheaf_for_iff_generate,
apply PJ (sieve.generate R) ⟨_, hR, le_generate R⟩ },
{ rintro PK X S ⟨R, hR, RS⟩,
have gRS : ⇑(generate R) ≤ S,
{ apply gi_generate.gc.monotone_u,
rwa sets_iff_generate },
apply is_sheaf_for_subsieve P gRS _,
intros Y f,
rw [← pullback_arrows_comm, ← is_sheaf_for_iff_generate],
exact PK (pullback_arrows f R) (K.pullbacks f R hR) }
end
/-- Any presheaf is a sheaf for the bottom (trivial) grothendieck topology. -/
lemma is_sheaf_bot : is_sheaf (⊥ : grothendieck_topology C) P :=
λ X, by simp [is_sheaf_for_top_sieve]
end presieve
namespace equalizer
variables {C : Type u₁} [category.{v₁} C] (P : Cᵒᵖ ⥤ Type (max v₁ u₁))
{X : C} (R : presieve X) (S : sieve X)
noncomputable theory
/--
The middle object of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of <https://stacks.math.columbia.edu/tag/00VM>.
-/
def first_obj : Type (max v₁ u₁) :=
∏ (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1))
/-- Show that `first_obj` is isomorphic to `family_of_elements`. -/
@[simps]
def first_obj_eq_family : first_obj P R ≅ R.family_of_elements P :=
{ hom := λ t Y f hf, pi.π (λ (f : Σ Y, {f : Y ⟶ X // R f}), P.obj (op f.1)) ⟨_, _, hf⟩ t,
inv := pi.lift (λ f x, x _ f.2.2),
hom_inv_id' :=
begin
ext ⟨Y, f, hf⟩ p,
simpa,
end,
inv_hom_id' :=
begin
ext x Y f hf,
apply limits.types.limit.lift_π_apply',
end }
instance : inhabited (first_obj P (⊥ : presieve X)) :=
((first_obj_eq_family P _).to_equiv).inhabited
/--
The left morphism of the fork diagram given in Equation (3) of [MM92], as well as the fork diagram
of <https://stacks.math.columbia.edu/tag/00VM>.
-/
def fork_map : P.obj (op X) ⟶ first_obj P R :=
pi.lift (λ f, P.map f.2.1.op)
/-!
This section establishes the equivalence between the sheaf condition of Equation (3) [MM92] and
the definition of `is_sheaf_for`.
-/
namespace sieve
/--
The rightmost object of the fork diagram of Equation (3) [MM92], which contains the data used
to check a family is compatible.
-/
def second_obj : Type (max v₁ u₁) :=
∏ (λ (f : Σ Y Z (g : Z ⟶ Y), {f' : Y ⟶ X // S f'}), P.obj (op f.2.1))
/-- The map `p` of Equations (3,4) [MM92]. -/
def first_map : first_obj P S ⟶ second_obj P S :=
pi.lift (λ fg, pi.π _ (⟨_, _, S.downward_closed fg.2.2.2.2 fg.2.2.1⟩ : Σ Y, {f : Y ⟶ X // S f}))
instance : inhabited (second_obj P (⊥ : sieve X)) := ⟨first_map _ _ default⟩
/-- The map `a` of Equations (3,4) [MM92]. -/
def second_map : first_obj P S ⟶ second_obj P S :=
pi.lift (λ fg, pi.π _ ⟨_, fg.2.2.2⟩ ≫ P.map fg.2.2.1.op)
lemma w : fork_map P S ≫ first_map P S = fork_map P S ≫ second_map P S :=
begin
apply limit.hom_ext,
rintro ⟨Y, Z, g, f, hf⟩,
simp [first_map, second_map, fork_map],
end
/--
The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map`
map it to the same point.
-/
lemma compatible_iff (x : first_obj P S) :
((first_obj_eq_family P S).hom x).compatible ↔ first_map P S x = second_map P S x :=
begin
rw presieve.compatible_iff_sieve_compatible,
split,
{ intro t,
ext ⟨Y, Z, g, f, hf⟩,
simpa [first_map, second_map] using t _ g hf },
{ intros t Y Z f g hf,
rw types.limit_ext_iff' at t,
simpa [first_map, second_map] using t ⟨⟨Y, Z, g, f, hf⟩⟩ }
end
/-- `P` is a sheaf for `S`, iff the fork given by `w` is an equalizer. -/
lemma equalizer_sheaf_condition :
presieve.is_sheaf_for P S ↔ nonempty (is_limit (fork.of_ι _ (w P S))) :=
begin
rw [types.type_equalizer_iff_unique,
← equiv.forall_congr_left (first_obj_eq_family P S).to_equiv.symm],
simp_rw ← compatible_iff,
simp only [inv_hom_id_apply, iso.to_equiv_symm_fun],
apply ball_congr,
intros x tx,
apply exists_unique_congr,
intro t,
rw ← iso.to_equiv_symm_fun,
rw equiv.eq_symm_apply,
split,
{ intros q,
ext Y f hf,
simpa [first_obj_eq_family, fork_map] using q _ _ },
{ intros q Y f hf,
rw ← q,
simp [first_obj_eq_family, fork_map] }
end
end sieve
/-!
This section establishes the equivalence between the sheaf condition of
https://stacks.math.columbia.edu/tag/00VM and the definition of `is_sheaf_for`.
-/
namespace presieve
variables [has_pullbacks C]
/--
The rightmost object of the fork diagram of https://stacks.math.columbia.edu/tag/00VM, which
contains the data used to check a family of elements for a presieve is compatible.
-/
def second_obj : Type (max v₁ u₁) :=
∏ (λ (fg : (Σ Y, {f : Y ⟶ X // R f}) × (Σ Z, {g : Z ⟶ X // R g})),
P.obj (op (pullback fg.1.2.1 fg.2.2.1)))
/-- The map `pr₀*` of <https://stacks.math.columbia.edu/tag/00VL>. -/
def first_map : first_obj P R ⟶ second_obj P R :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.fst.op)
instance : inhabited (second_obj P (⊥ : presieve X)) := ⟨first_map _ _ default⟩
/-- The map `pr₁*` of <https://stacks.math.columbia.edu/tag/00VL>. -/
def second_map : first_obj P R ⟶ second_obj P R :=
pi.lift (λ fg, pi.π _ _ ≫ P.map pullback.snd.op)
lemma w : fork_map P R ≫ first_map P R = fork_map P R ≫ second_map P R :=
begin
apply limit.hom_ext,
rintro ⟨⟨Y, f, hf⟩, ⟨Z, g, hg⟩⟩,
simp only [first_map, second_map, fork_map],
simp only [limit.lift_π, limit.lift_π_assoc, assoc, fan.mk_π_app, subtype.coe_mk,
subtype.val_eq_coe],
rw [← P.map_comp, ← op_comp, pullback.condition],
simp,
end
/--
The family of elements given by `x : first_obj P S` is compatible iff `first_map` and `second_map`
map it to the same point.
-/
lemma compatible_iff (x : first_obj P R) :
((first_obj_eq_family P R).hom x).compatible ↔ first_map P R x = second_map P R x :=
begin
rw presieve.pullback_compatible_iff,
split,
{ intro t,
ext ⟨⟨Y, f, hf⟩, Z, g, hg⟩,
simpa [first_map, second_map] using t hf hg },
{ intros t Y Z f g hf hg,
rw types.limit_ext_iff' at t,
simpa [first_map, second_map] using t ⟨⟨⟨Y, f, hf⟩, Z, g, hg⟩⟩ }
end
/--
`P` is a sheaf for `R`, iff the fork given by `w` is an equalizer.
See <https://stacks.math.columbia.edu/tag/00VM>.
-/
lemma sheaf_condition :
R.is_sheaf_for P ↔ nonempty (is_limit (fork.of_ι _ (w P R))) :=
begin
rw types.type_equalizer_iff_unique,
erw ← equiv.forall_congr_left (first_obj_eq_family P R).to_equiv.symm,
simp_rw [← compatible_iff, ← iso.to_equiv_fun, equiv.apply_symm_apply],
apply ball_congr,
intros x hx,
apply exists_unique_congr,
intros t,
rw equiv.eq_symm_apply,
split,
{ intros q,
ext Y f hf,
simpa [fork_map] using q _ _ },
{ intros q Y f hf,
rw ← q,
simp [fork_map] }
end
end presieve
end equalizer
variables {C : Type u₁} [category.{v₁} C]
variables (J : grothendieck_topology C)
/-- The category of sheaves on a grothendieck topology. -/
structure SheafOfTypes (J : grothendieck_topology C) : Type (max u₁ v₁ (w+1)) :=
(val : Cᵒᵖ ⥤ Type w)
(cond : presieve.is_sheaf J val)
namespace SheafOfTypes
variable {J}
/-- Morphisms between sheaves of types are just morphisms between the underlying presheaves. -/
@[ext]
structure hom (X Y : SheafOfTypes J) :=
(val : X.val ⟶ Y.val)
@[simps]
instance : category (SheafOfTypes J) :=
{ hom := hom,
id := λ X, ⟨𝟙 _⟩,
comp := λ X Y Z f g, ⟨f.val ≫ g.val⟩,
id_comp' := λ X Y f, hom.ext _ _ $ id_comp _,
comp_id' := λ X Y f, hom.ext _ _ $ comp_id _,
assoc' := λ X Y Z W f g h, hom.ext _ _ $ assoc _ _ _ }
-- Let's make the inhabited linter happy...
instance (X : SheafOfTypes J) : inhabited (hom X X) := ⟨𝟙 X⟩
end SheafOfTypes
/-- The inclusion functor from sheaves to presheaves. -/
@[simps]
def SheafOfTypes_to_presheaf : SheafOfTypes J ⥤ (Cᵒᵖ ⥤ Type w) :=
{ obj := SheafOfTypes.val,
map := λ X Y f, f.val,
map_id' := λ X, rfl,
map_comp' := λ X Y Z f g, rfl }
instance : full (SheafOfTypes_to_presheaf J) := { preimage := λ X Y f, ⟨f⟩ }
instance : faithful (SheafOfTypes_to_presheaf J) := {}
/--
The category of sheaves on the bottom (trivial) grothendieck topology is equivalent to the category
of presheaves.
-/
@[simps]
def SheafOfTypes_bot_equiv : SheafOfTypes (⊥ : grothendieck_topology C) ≌ (Cᵒᵖ ⥤ Type w) :=
{ functor := SheafOfTypes_to_presheaf _,
inverse :=
{ obj := λ P, ⟨P, presieve.is_sheaf_bot⟩,
map := λ P₁ P₂ f, (SheafOfTypes_to_presheaf _).preimage f },
unit_iso :=
{ hom := { app := λ _, ⟨𝟙 _⟩ },
inv := { app := λ _, ⟨𝟙 _⟩ } },
counit_iso := iso.refl _ }
instance : inhabited (SheafOfTypes (⊥ : grothendieck_topology C)) :=
⟨SheafOfTypes_bot_equiv.inverse.obj ((functor.const _).obj punit)⟩
end category_theory
|
481000968480254f0661198b06c5bb9fd096691c | cf39355caa609c0f33405126beee2739aa3cb77e | /library/init/meta/mk_inhabited_instance.lean | 0e4b135e9b5bd99cec78111b8dc105eeae0e3171 | [
"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,685 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
Helper tactic for showing that a type is inhabited.
-/
prelude
import init.meta.interactive_base
import init.meta.contradiction_tactic init.meta.constructor_tactic
import init.meta.injection_tactic init.meta.relation_tactics
namespace tactic
open expr environment list
/-- Retrieve the name of the type we are building an inhabitant instance for. -/
private meta def get_inhabited_type_name : tactic name :=
do {
(app (const n ls) t) ← target >>= whnf,
when (n ≠ `inhabited) failed,
(const I ls) ← return (get_app_fn t),
return I }
<|>
fail "mk_inhabited_instance tactic failed, target type is expected to be of the form (inhabited ...)"
/-- Try to synthesize constructor argument using type class resolution -/
private meta def mk_inhabited_arg : tactic unit :=
do tgt ← target,
inh ← mk_app `inhabited [tgt],
inst ← mk_instance inh,
mk_app `inhabited.default [inst] >>= exact
private meta def try_constructors : nat → nat → tactic unit
| 0 n := failed
| (i+1) n :=
do {constructor_idx (n - i), all_goals mk_inhabited_arg, done}
<|>
try_constructors i n
meta def mk_inhabited_instance : tactic unit :=
do
I ← get_inhabited_type_name,
env ← get_env,
let n := length (constructors_of env I),
when (n = 0) (fail format!"mk_inhabited_instance failed, type '{I}' does not have constructors"),
constructor,
(try_constructors n n)
<|>
(fail format!"mk_inhabited_instance failed, failed to build instance using all constructors of '{I}'")
end tactic
|
f04519c8718dcb914ac48e7873ae262cbdddd440 | 8c9f90127b78cbeb5bb17fd6b5db1db2ffa3cbc4 | /adam_is_hungry.lean | 8ed7ac26f80c9cac387c1610370803822b33d780 | [] | no_license | picrin/lean | 420f4d08bb3796b911d56d0938e4410e1da0e072 | 3d10c509c79704aa3a88ebfb24d08b30ce1137cc | refs/heads/master | 1,611,166,610,726 | 1,536,671,438,000 | 1,536,671,438,000 | 60,029,899 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 553 | lean | namespace hide
constant and : Prop → Prop → Prop
constant not : Prop → Prop
constant implies : Prop → Prop → Prop
constant Proof : Prop → Type
constant adam_is_hungry : Prop
constant proof_adam_hungry: Proof adam_is_hungry
constant adam_is_angry : Prop
constant when_adam_hungry_adam_angry : Proof (implies adam_is_hungry adam_is_angry)
constant modus_ponens : Π (p q : Type.{0}), Proof (implies p q) → (Proof p) → Proof q
check modus_ponens adam_is_hungry adam_is_angry when_adam_hungry_adam_angry proof_adam_hungry
end hide
|
916897b10e1f82227507962c023b6d8f3c20e1b2 | cf39355caa609c0f33405126beee2739aa3cb77e | /tests/lean/run/1813.lean | fc839d15a8e98196ff74fbf3f5fc35d4dd91c215 | [
"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 | 523 | lean | open tactic
example {A B : Type} (f : A -> B) (a b c) (h1 : f a = b) (h2 : f a = c) : false :=
begin
rw h1 at *,
guard_hyp h1 : f a = b,
guard_hyp h2 : b = c,
admit
end
example {A B : Type} (f : A -> B) (a b c) (h1 : f a = b) (h2 : f a = c) : false :=
begin
rw [id h1] at *,
guard_hyp h1 : f a = b,
guard_hyp h2 : b = c,
admit
end
example {A B : Type} (f : A -> B) (a b c) (h1 : f a = b) (h2 : f a = c) : false :=
begin
rw [id id h1] at *,
guard_hyp h1 : f a = b,
guard_hyp h2 : b = c,
admit
end
|
f86c9efe0ddf7495f135d6749f1694f9ce7ea146 | 947fa6c38e48771ae886239b4edce6db6e18d0fb | /src/data/multiset/nodup.lean | 9044e8d5c91238f3590cfb557e814fdf338ac092 | [
"Apache-2.0"
] | permissive | ramonfmir/mathlib | c5dc8b33155473fab97c38bd3aa6723dc289beaa | 14c52e990c17f5a00c0cc9e09847af16fabbed25 | refs/heads/master | 1,661,979,343,526 | 1,660,830,384,000 | 1,660,830,384,000 | 182,072,989 | 0 | 0 | null | 1,555,585,876,000 | 1,555,585,876,000 | null | UTF-8 | Lean | false | false | 9,875 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import data.multiset.bind
import data.multiset.powerset
import data.multiset.range
/-!
# The `nodup` predicate for multisets without duplicate elements.
-/
namespace multiset
open function list
variables {α β γ : Type*} {r : α → α → Prop} {s t : multiset α} {a : α}
/- nodup -/
/-- `nodup s` means that `s` has no duplicates, i.e. the multiplicity of
any element is at most 1. -/
def nodup (s : multiset α) : Prop :=
quot.lift_on s nodup (λ s t p, propext p.nodup_iff)
@[simp] theorem coe_nodup {l : list α} : @nodup α l ↔ l.nodup := iff.rfl
@[simp] theorem nodup_zero : @nodup α 0 := pairwise.nil
@[simp] theorem nodup_cons {a : α} {s : multiset α} : nodup (a ::ₘ s) ↔ a ∉ s ∧ nodup s :=
quot.induction_on s $ λ l, nodup_cons
lemma nodup.cons (m : a ∉ s) (n : nodup s) : nodup (a ::ₘ s) := nodup_cons.2 ⟨m, n⟩
theorem nodup_singleton : ∀ a : α, nodup ({a} : multiset α) := nodup_singleton
lemma nodup.of_cons (h : nodup (a ::ₘ s)) : nodup s := (nodup_cons.1 h).2
theorem nodup.not_mem (h : nodup (a ::ₘ s)) : a ∉ s := (nodup_cons.1 h).1
theorem nodup_of_le {s t : multiset α} (h : s ≤ t) : nodup t → nodup s :=
le_induction_on h $ λ l₁ l₂, nodup.sublist
theorem not_nodup_pair : ∀ a : α, ¬ nodup (a ::ₘ a ::ₘ 0) := not_nodup_pair
theorem nodup_iff_le {s : multiset α} : nodup s ↔ ∀ a : α, ¬ a ::ₘ a ::ₘ 0 ≤ s :=
quot.induction_on s $ λ l, nodup_iff_sublist.trans $ forall_congr $ λ a,
not_congr (@repeat_le_coe _ a 2 _).symm
lemma nodup_iff_ne_cons_cons {s : multiset α} : s.nodup ↔ ∀ a t, s ≠ a ::ₘ a ::ₘ t :=
nodup_iff_le.trans
⟨λ h a t s_eq, h a (s_eq.symm ▸ cons_le_cons a (cons_le_cons a (zero_le _))),
λ h a le, let ⟨t, s_eq⟩ := le_iff_exists_add.mp le in
h a t (by rwa [cons_add, cons_add, zero_add] at s_eq )⟩
theorem nodup_iff_count_le_one [decidable_eq α] {s : multiset α} : nodup s ↔ ∀ a, count a s ≤ 1 :=
quot.induction_on s $ λ l, nodup_iff_count_le_one
@[simp] theorem count_eq_one_of_mem [decidable_eq α] {a : α} {s : multiset α}
(d : nodup s) (h : a ∈ s) : count a s = 1 :=
le_antisymm (nodup_iff_count_le_one.1 d a) (count_pos.2 h)
lemma count_eq_of_nodup [decidable_eq α] {a : α} {s : multiset α}
(d : nodup s) : count a s = if a ∈ s then 1 else 0 :=
begin
split_ifs with h,
{ exact count_eq_one_of_mem d h },
{ exact count_eq_zero_of_not_mem h },
end
lemma nodup_iff_pairwise {α} {s : multiset α} : nodup s ↔ pairwise (≠) s :=
quotient.induction_on s $ λ l, (pairwise_coe_iff_pairwise (by exact λ a b, ne.symm)).symm
protected lemma nodup.pairwise : (∀ a ∈ s, ∀ b ∈ s, a ≠ b → r a b) → nodup s → pairwise r s :=
quotient.induction_on s $ assume l h hl, ⟨l, rfl, hl.imp_of_mem $ assume a b ha hb, h a ha b hb⟩
lemma pairwise.forall (H : symmetric r) (hs : pairwise r s) :
∀ ⦃a⦄, a ∈ s → ∀ ⦃b⦄, b ∈ s → a ≠ b → r a b :=
let ⟨l, hl₁, hl₂⟩ := hs in hl₁.symm ▸ hl₂.forall H
theorem nodup_add {s t : multiset α} : nodup (s + t) ↔ nodup s ∧ nodup t ∧ disjoint s t :=
quotient.induction_on₂ s t $ λ l₁ l₂, nodup_append
theorem disjoint_of_nodup_add {s t : multiset α} (d : nodup (s + t)) : disjoint s t :=
(nodup_add.1 d).2.2
lemma nodup.add_iff (d₁ : nodup s) (d₂ : nodup t) : nodup (s + t) ↔ disjoint s t :=
by simp [nodup_add, d₁, d₂]
lemma nodup.of_map (f : α → β) : nodup (map f s) → nodup s :=
quot.induction_on s $ λ l, nodup.of_map f
lemma nodup.map_on {f : α → β} : (∀ x ∈ s, ∀ y ∈ s, f x = f y → x = y) →
nodup s → nodup (map f s) :=
quot.induction_on s $ λ l, nodup.map_on
lemma nodup.map {f : α → β} {s : multiset α} (hf : injective f) : nodup s → nodup (map f s) :=
nodup.map_on (λ x _ y _ h, hf h)
theorem inj_on_of_nodup_map {f : α → β} {s : multiset α} :
nodup (map f s) → ∀ (x ∈ s) (y ∈ s), f x = f y → x = y :=
quot.induction_on s $ λ l, inj_on_of_nodup_map
theorem nodup_map_iff_inj_on {f : α → β} {s : multiset α} (d : nodup s) :
nodup (map f s) ↔ (∀ (x ∈ s) (y ∈ s), f x = f y → x = y) :=
⟨inj_on_of_nodup_map, λ h, d.map_on h⟩
lemma nodup.filter (p : α → Prop) [decidable_pred p] {s} : nodup s → nodup (filter p s) :=
quot.induction_on s $ λ l, nodup.filter p
@[simp] theorem nodup_attach {s : multiset α} : nodup (attach s) ↔ nodup s :=
quot.induction_on s $ λ l, nodup_attach
lemma nodup.pmap {p : α → Prop} {f : Π a, p a → β} {s : multiset α} {H}
(hf : ∀ a ha b hb, f a ha = f b hb → a = b) : nodup s → nodup (pmap f s H) :=
quot.induction_on s (λ l H, nodup.pmap hf) H
instance nodup_decidable [decidable_eq α] (s : multiset α) : decidable (nodup s) :=
quotient.rec_on_subsingleton s $ λ l, l.nodup_decidable
lemma nodup.erase_eq_filter [decidable_eq α] (a : α) {s} : nodup s → s.erase a = filter (≠ a) s :=
quot.induction_on s $ λ l d, congr_arg coe $ d.erase_eq_filter a
lemma nodup.erase [decidable_eq α] (a : α) {l} : nodup l → nodup (l.erase a) :=
nodup_of_le (erase_le _ _)
lemma nodup.mem_erase_iff [decidable_eq α] {a b : α} {l} (d : nodup l) :
a ∈ l.erase b ↔ a ≠ b ∧ a ∈ l :=
by rw [d.erase_eq_filter b, mem_filter, and_comm]
lemma nodup.not_mem_erase [decidable_eq α] {a : α} {s} (h : nodup s) : a ∉ s.erase a :=
λ ha, (h.mem_erase_iff.1 ha).1 rfl
protected lemma nodup.product {t : multiset β} : nodup s → nodup t → nodup (product s t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, by simp [d₁.product d₂]
protected lemma nodup.sigma {σ : α → Type*} {t : Π a, multiset (σ a)} :
nodup s → (∀ a, nodup (t a)) → nodup (s.sigma t) :=
quot.induction_on s $ assume l₁,
begin
choose f hf using assume a, quotient.exists_rep (t a),
rw show t = λ a, f a, from (eq.symm $ funext $ λ a, hf a),
simpa using nodup.sigma
end
protected lemma nodup.filter_map (f : α → option β) (H : ∀ a a' b, b ∈ f a → b ∈ f a' → a = a') :
nodup s → nodup (filter_map f s) :=
quot.induction_on s $ λ l, nodup.filter_map H
theorem nodup_range (n : ℕ) : nodup (range n) := nodup_range _
lemma nodup.inter_left [decidable_eq α] (t) : nodup s → nodup (s ∩ t) :=
nodup_of_le $ inter_le_left _ _
lemma nodup.inter_right [decidable_eq α] (s) : nodup t → nodup (s ∩ t) :=
nodup_of_le $ inter_le_right _ _
@[simp] theorem nodup_union [decidable_eq α] {s t : multiset α} :
nodup (s ∪ t) ↔ nodup s ∧ nodup t :=
⟨λ h, ⟨nodup_of_le (le_union_left _ _) h, nodup_of_le (le_union_right _ _) h⟩,
λ ⟨h₁, h₂⟩, nodup_iff_count_le_one.2 $ λ a, by rw [count_union]; exact
max_le (nodup_iff_count_le_one.1 h₁ a) (nodup_iff_count_le_one.1 h₂ a)⟩
@[simp] theorem nodup_powerset {s : multiset α} : nodup (powerset s) ↔ nodup s :=
⟨λ h, (nodup_of_le (map_single_le_powerset _) h).of_map _,
quotient.induction_on s $ λ l h,
by simp; refine (nodup_sublists'.2 h).map_on _ ; exact
λ x sx y sy e,
(h.sublist_ext (mem_sublists'.1 sx) (mem_sublists'.1 sy)).1
(quotient.exact e)⟩
alias nodup_powerset ↔ nodup.of_powerset nodup.powerset
protected lemma nodup.powerset_len {n : ℕ} (h : nodup s) : nodup (powerset_len n s) :=
nodup_of_le (powerset_len_le_powerset _ _) (nodup_powerset.2 h)
@[simp] lemma nodup_bind {s : multiset α} {t : α → multiset β} :
nodup (bind s t) ↔ ((∀a∈s, nodup (t a)) ∧ (s.pairwise (λa b, disjoint (t a) (t b)))) :=
have h₁ : ∀a, ∃l:list β, t a = l, from
assume a, quot.induction_on (t a) $ assume l, ⟨l, rfl⟩,
let ⟨t', h'⟩ := classical.axiom_of_choice h₁ in
have t = λa, t' a, from funext h',
have hd : symmetric (λa b, list.disjoint (t' a) (t' b)), from assume a b h, h.symm,
quot.induction_on s $ by simp [this, list.nodup_bind, pairwise_coe_iff_pairwise hd]
lemma nodup.ext {s t : multiset α} : nodup s → nodup t → (s = t ↔ ∀ a, a ∈ s ↔ a ∈ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d₁ d₂, quotient.eq.trans $ perm_ext d₁ d₂
theorem le_iff_subset {s t : multiset α} : nodup s → (s ≤ t ↔ s ⊆ t) :=
quotient.induction_on₂ s t $ λ l₁ l₂ d, ⟨subset_of_le, d.subperm⟩
theorem range_le {m n : ℕ} : range m ≤ range n ↔ m ≤ n :=
(le_iff_subset (nodup_range _)).trans range_subset
theorem mem_sub_of_nodup [decidable_eq α] {a : α} {s t : multiset α} (d : nodup s) :
a ∈ s - t ↔ a ∈ s ∧ a ∉ t :=
⟨λ h, ⟨mem_of_le tsub_le_self h, λ h',
by refine count_eq_zero.1 _ h; rw [count_sub a s t, tsub_eq_zero_iff_le];
exact le_trans (nodup_iff_count_le_one.1 d _) (count_pos.2 h')⟩,
λ ⟨h₁, h₂⟩, or.resolve_right (mem_add.1 $ mem_of_le le_tsub_add h₁) h₂⟩
lemma map_eq_map_of_bij_of_nodup (f : α → γ) (g : β → γ) {s : multiset α} {t : multiset β}
(hs : s.nodup) (ht : t.nodup) (i : Πa∈s, β)
(hi : ∀a ha, i a ha ∈ t) (h : ∀a ha, f a = g (i a ha))
(i_inj : ∀a₁ a₂ ha₁ ha₂, i a₁ ha₁ = i a₂ ha₂ → a₁ = a₂)
(i_surj : ∀b∈t, ∃a ha, b = i a ha) :
s.map f = t.map g :=
have t = s.attach.map (λ x, i x.1 x.2),
from (ht.ext $ (nodup_attach.2 hs).map $
show injective (λ x : {x // x ∈ s}, i x.1 x.2), from λ x y hxy,
subtype.eq $ i_inj x.1 y.1 x.2 y.2 hxy).2
(λ x, by simp only [mem_map, true_and, subtype.exists, eq_comm, mem_attach];
exact ⟨i_surj _, λ ⟨y, hy⟩, hy.snd.symm ▸ hi _ _⟩),
calc s.map f = s.pmap (λ x _, f x) (λ _, id) : by rw [pmap_eq_map]
... = s.attach.map (λ x, f x.1) : by rw [pmap_eq_map_attach]
... = t.map g : by rw [this, multiset.map_map]; exact map_congr rfl (λ x _, h _ _)
end multiset
|
c5c81f7b97dbba9ce709e26e06cc0fa605b136a8 | 2c096fdfecf64e46ea7bc6ce5521f142b5926864 | /src/Lean/Parser/Command.lean | 35af9ce35a9deab4bca007807bf31d4d3ec712d2 | [
"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 | Kha/lean4 | 1005785d2c8797ae266a303968848e5f6ce2fe87 | b99e11346948023cd6c29d248cd8f3e3fb3474cf | refs/heads/master | 1,693,355,498,027 | 1,669,080,461,000 | 1,669,113,138,000 | 184,748,176 | 0 | 0 | Apache-2.0 | 1,665,995,520,000 | 1,556,884,930,000 | Lean | UTF-8 | Lean | false | false | 15,116 | 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
-/
import Lean.Parser.Term
import Lean.Parser.Do
namespace Lean
namespace Parser
/-- Syntax quotation for terms. -/
@[builtin_term_parser] def Term.quot := leading_parser
"`(" >> withoutPosition (incQuotDepth termParser) >> ")"
@[builtin_term_parser] def Term.precheckedQuot := leading_parser
"`" >> Term.quot
namespace Command
/--
Syntax quotation for (sequences of) commands.
The identical syntax for term quotations takes priority,
so ambiguous quotations like `` `($x $y) `` will be parsed as an application,
not two commands. Use `` `($x:command $y:command) `` instead.
Multiple commands will be put in a `` `null `` node,
but a single command will not (so that you can directly
match against a quotation in a command kind's elaborator). -/
@[builtin_term_parser low] def quot := leading_parser
"`(" >> withoutPosition (incQuotDepth (many1Unbox commandParser)) >> ")"
/-
A mutual block may be broken in different cliques,
we identify them using an `ident` (an element of the clique).
We provide two kinds of hints to the termination checker:
1- A wellfounded relation (`p` is `termParser`)
2- A tactic for proving the recursive applications are "decreasing" (`p` is `tacticSeq`)
-/
def terminationHintMany (p : Parser) := leading_parser
atomic (lookahead (ident >> " => ")) >>
many1Indent (group (ppLine >> ident >> " => " >> p >> optional ";"))
def terminationHint1 (p : Parser) := leading_parser p
def terminationHint (p : Parser) := terminationHintMany p <|> terminationHint1 p
def terminationByCore := leading_parser
"termination_by' " >> terminationHint termParser
def decreasingBy := leading_parser
"decreasing_by " >> terminationHint Tactic.tacticSeq
def terminationByElement := leading_parser
ppLine >> (ident <|> Term.hole) >> many (ident <|> Term.hole) >>
" => " >> termParser >> optional ";"
def terminationBy := leading_parser
ppLine >> "termination_by " >> many1Indent terminationByElement
def terminationSuffix :=
optional (terminationBy <|> terminationByCore) >> optional decreasingBy
@[builtin_command_parser]
def moduleDoc := leading_parser ppDedent <|
"/-!" >> commentBody >> ppLine
def namedPrio := leading_parser
atomic ("(" >> nonReservedSymbol "priority") >> " := " >> withoutPosition priorityParser >> ")"
def optNamedPrio := optional (ppSpace >> namedPrio)
def «private» := leading_parser "private "
def «protected» := leading_parser "protected "
def visibility := «private» <|> «protected»
def «noncomputable» := leading_parser "noncomputable "
def «unsafe» := leading_parser "unsafe "
def «partial» := leading_parser "partial "
def «nonrec» := leading_parser "nonrec "
def declModifiers (inline : Bool) := leading_parser
optional docComment >>
optional (Term.«attributes» >> if inline then skip else ppDedent ppLine) >>
optional visibility >>
optional «noncomputable» >>
optional «unsafe» >>
optional («partial» <|> «nonrec»)
def declId := leading_parser
ident >> optional (".{" >> sepBy1 ident ", " >> "}")
def declSig := leading_parser
many (ppSpace >> (Term.binderIdent <|> Term.bracketedBinder)) >> Term.typeSpec
def optDeclSig := leading_parser
many (ppSpace >> (Term.binderIdent <|> Term.bracketedBinder)) >> Term.optType
def declValSimple := leading_parser
" :=" >> ppHardLineUnlessUngrouped >> termParser >> optional Term.whereDecls
def declValEqns := leading_parser
Term.matchAltsWhereDecls
def whereStructField := leading_parser
Term.letDecl
def whereStructInst := leading_parser
" where" >> sepByIndent (ppGroup whereStructField) "; " (allowTrailingSep := true) >>
optional Term.whereDecls
/-
Remark: we should not use `Term.whereDecls` at `declVal`
because `Term.whereDecls` is defined using `Term.letRecDecl` which may contain attributes.
Issue #753 showns an example that fails to be parsed when we used `Term.whereDecls`.
-/
def declVal :=
withAntiquot (mkAntiquot "declVal" `Lean.Parser.Command.declVal (isPseudoKind := true)) <|
declValSimple <|> declValEqns <|> whereStructInst
def «abbrev» := leading_parser
"abbrev " >> declId >> ppIndent optDeclSig >> declVal >> terminationSuffix
def optDefDeriving :=
optional (atomic ("deriving " >> notSymbol "instance") >> sepBy1 ident ", ")
def «def» := leading_parser
"def " >> declId >> ppIndent optDeclSig >> declVal >> optDefDeriving >> terminationSuffix
def «theorem» := leading_parser
"theorem " >> declId >> ppIndent declSig >> declVal >> terminationSuffix
def «opaque» := leading_parser
"opaque " >> declId >> ppIndent declSig >> optional declValSimple
/- As `declSig` starts with a space, "instance" does not need a trailing space
if we put `ppSpace` in the optional fragments. -/
def «instance» := leading_parser
Term.attrKind >> "instance" >> optNamedPrio >>
optional (ppSpace >> declId) >> ppIndent declSig >> declVal >> terminationSuffix
def «axiom» := leading_parser
"axiom " >> declId >> ppIndent declSig
/- As `declSig` starts with a space, "example" does not need a trailing space. -/
def «example» := leading_parser
"example" >> ppIndent optDeclSig >> declVal
def ctor := leading_parser
atomic (optional docComment >> "\n| ") >>
ppGroup (declModifiers true >> rawIdent >> optDeclSig)
def derivingClasses := sepBy1 (group (ident >> optional (" with " >> Term.structInst))) ", "
def optDeriving := leading_parser
optional (ppLine >> atomic ("deriving " >> notSymbol "instance") >> derivingClasses)
def computedField := leading_parser
declModifiers true >> ident >> " : " >> termParser >> Term.matchAlts
def computedFields := leading_parser
"with" >> manyIndent (ppLine >> ppGroup computedField)
/--
In Lean, every concrete type other than the universes
and every type constructor other than dependent arrows
is an instance of a general family of type constructions known as inductive types.
It is remarkable that it is possible to construct a substantial edifice of mathematics
based on nothing more than the type universes, dependent arrow types, and inductive types;
everything else follows from those.
Intuitively, an inductive type is built up from a specified list of constructor.
For example, `List α` is the list of elements of type `α`, and is defined as follows:
```
inductive List (α : Type u) where
| nil
| cons (head : α) (tail : List α)
```
A list of elements of type `α` is either the empty list, `nil`,
or an element `head : α` followed by a list `tail : List α`.
For more information about [inductive types](https://leanprover.github.io/theorem_proving_in_lean4/inductive_types.html).
-/
def «inductive» := leading_parser
"inductive " >> declId >> optDeclSig >> optional (symbol " :=" <|> " where") >>
many ctor >> optional (ppDedent ppLine >> computedFields) >> optDeriving
def classInductive := leading_parser
atomic (group (symbol "class " >> "inductive ")) >>
declId >> ppIndent optDeclSig >>
optional (symbol " :=" <|> " where") >> many ctor >> optDeriving
def structExplicitBinder := leading_parser
atomic (declModifiers true >> "(") >>
withoutPosition (many1 ident >> ppIndent optDeclSig >>
optional (Term.binderTactic <|> Term.binderDefault)) >> ")"
def structImplicitBinder := leading_parser
atomic (declModifiers true >> "{") >> withoutPosition (many1 ident >> declSig) >> "}"
def structInstBinder := leading_parser
atomic (declModifiers true >> "[") >> withoutPosition (many1 ident >> declSig) >> "]"
def structSimpleBinder := leading_parser
atomic (declModifiers true >> ident) >> optDeclSig >>
optional (Term.binderTactic <|> Term.binderDefault)
def structFields := leading_parser
manyIndent <|
ppLine >> checkColGe >> ppGroup (
structExplicitBinder <|> structImplicitBinder <|>
structInstBinder <|> structSimpleBinder)
def structCtor := leading_parser
atomic (declModifiers true >> ident >> " :: ")
def structureTk := leading_parser
"structure "
def classTk := leading_parser
"class "
def «extends» := leading_parser
" extends " >> sepBy1 termParser ", "
def «structure» := leading_parser
(structureTk <|> classTk) >>
declId >> many (ppSpace >> Term.bracketedBinder) >>
optional «extends» >> Term.optType >>
optional ((symbol " := " <|> " where ") >> optional structCtor >> structFields) >>
optDeriving
@[builtin_command_parser] def declaration := leading_parser
declModifiers false >>
(«abbrev» <|> «def» <|> «theorem» <|> «opaque» <|> «instance» <|> «axiom» <|> «example» <|>
«inductive» <|> classInductive <|> «structure»)
@[builtin_command_parser] def «deriving» := leading_parser
"deriving " >> "instance " >> derivingClasses >> " for " >> sepBy1 ident ", "
@[builtin_command_parser] def noncomputableSection := leading_parser
"noncomputable " >> "section " >> optional ident
@[builtin_command_parser] def «section» := leading_parser
"section " >> optional ident
@[builtin_command_parser] def «namespace» := leading_parser
"namespace " >> ident
@[builtin_command_parser] def «end» := leading_parser
"end " >> optional ident
@[builtin_command_parser] def «variable» := leading_parser
"variable" >> many1 (ppSpace >> Term.bracketedBinder)
@[builtin_command_parser] def «universe» := leading_parser
"universe " >> many1 ident
@[builtin_command_parser] def check := leading_parser
"#check " >> termParser
@[builtin_command_parser] def check_failure := leading_parser
"#check_failure " >> termParser -- Like `#check`, but succeeds only if term does not type check
@[builtin_command_parser] def reduce := leading_parser
"#reduce " >> termParser
@[builtin_command_parser] def eval := leading_parser
"#eval " >> termParser
@[builtin_command_parser] def synth := leading_parser
"#synth " >> termParser
@[builtin_command_parser] def exit := leading_parser
"#exit"
@[builtin_command_parser] def print := leading_parser
"#print " >> (ident <|> strLit)
@[builtin_command_parser] def printAxioms := leading_parser
"#print " >> nonReservedSymbol "axioms " >> ident
@[builtin_command_parser] def «init_quot» := leading_parser
"init_quot"
def optionValue := nonReservedSymbol "true" <|> nonReservedSymbol "false" <|> strLit <|> numLit
@[builtin_command_parser] def «set_option» := leading_parser
"set_option " >> ident >> ppSpace >> optionValue
def eraseAttr := leading_parser
"-" >> rawIdent
@[builtin_command_parser] def «attribute» := leading_parser
"attribute " >> "[" >>
withoutPosition (sepBy1 (eraseAttr <|> Term.attrInstance) ", ") >>
"] " >> many1 ident
@[builtin_command_parser] def «export» := leading_parser
"export " >> ident >> " (" >> many1 ident >> ")"
@[builtin_command_parser] def «import» := leading_parser
"import" -- not a real command, only for error messages
def openHiding := leading_parser
atomic (ident >> "hiding") >> many1 (checkColGt >> ident)
def openRenamingItem := leading_parser
ident >> unicodeSymbol " → " " -> " >> checkColGt >> ident
def openRenaming := leading_parser
atomic (ident >> "renaming") >> sepBy1 openRenamingItem ", "
def openOnly := leading_parser
atomic (ident >> " (") >> many1 ident >> ")"
def openSimple := leading_parser
many1 (checkColGt >> ident)
def openScoped := leading_parser
"scoped " >> many1 (checkColGt >> ident)
def openDecl :=
withAntiquot (mkAntiquot "openDecl" `Lean.Parser.Command.openDecl (isPseudoKind := true)) <|
openHiding <|> openRenaming <|> openOnly <|> openSimple <|> openScoped
@[builtin_command_parser] def «open» := leading_parser
withPosition ("open " >> openDecl)
@[builtin_command_parser] def «mutual» := leading_parser
"mutual " >> many1 (ppLine >> notSymbol "end" >> commandParser) >>
ppDedent (ppLine >> "end") >> terminationSuffix
def initializeKeyword := leading_parser
"initialize " <|> "builtin_initialize "
@[builtin_command_parser] def «initialize» := leading_parser
declModifiers false >> initializeKeyword >>
optional (atomic (ident >> Term.typeSpec >> Term.leftArrow)) >> Term.doSeq
@[builtin_command_parser] def «in» := trailing_parser withOpen (" in " >> commandParser)
@[builtin_command_parser] def addDocString := leading_parser
docComment >> "add_decl_doc" >> ident
/--
This is an auxiliary command for generation constructor injectivity theorems for
inductive types defined at `Prelude.lean`.
It is meant for bootstrapping purposes only. -/
@[builtin_command_parser] def genInjectiveTheorems := leading_parser
"gen_injective_theorems% " >> ident
@[run_builtin_parser_attribute_hooks] abbrev declModifiersF := declModifiers false
@[run_builtin_parser_attribute_hooks] abbrev declModifiersT := declModifiers true
builtin_initialize
register_parser_alias (kind := ``declModifiers) "declModifiers" declModifiersF
register_parser_alias (kind := ``declModifiers) "nestedDeclModifiers" declModifiersT
register_parser_alias declId
register_parser_alias declSig
register_parser_alias declVal
register_parser_alias optDeclSig
register_parser_alias openDecl
register_parser_alias docComment
end Command
namespace Term
/--
`open Foo in e` is like `open Foo` but scoped to a single term.
It makes the given namespaces available in the term `e`.
-/
@[builtin_term_parser] def «open» := leading_parser:leadPrec
"open " >> Command.openDecl >> withOpenDecl (" in " >> termParser)
/--
`set_option opt val in e` is like `set_option opt val` but scoped to a single term.
It sets the option `opt` to the value `val` in the term `e`.
-/
@[builtin_term_parser] def «set_option» := leading_parser:leadPrec
"set_option " >> ident >> ppSpace >> Command.optionValue >> " in " >> termParser
end Term
namespace Tactic
/-- `open Foo in tacs` (the tactic) acts like `open Foo` at command level,
but it opens a namespace only within the tactics `tacs`. -/
@[builtin_tactic_parser] def «open» := leading_parser:leadPrec
"open " >> Command.openDecl >> withOpenDecl (" in " >> tacticSeq)
/-- `set_option opt val in tacs` (the tactic) acts like `set_option opt val` at the command level,
but it sets the option only within the tactics `tacs`. -/
@[builtin_tactic_parser] def «set_option» := leading_parser:leadPrec
"set_option " >> ident >> ppSpace >> Command.optionValue >> " in " >> tacticSeq
end Tactic
end Parser
end Lean
|
afca9a4e75d5acd228244ce63f00d261add215b7 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /tests/lean/unknownId.lean | 769fee9fbda30da6c2b55e71383fd7f2fceb4057 | [
"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 | 170 | lean | macro "foo" : term => `(bla)
#check foo
def f (bla : Nat) : Nat :=
foo
macro "boo" x:term : term => `(fun (bla : Nat) => $x + bla)
def g : Nat → Nat :=
boo foo
|
04b1cb7f8853f815ec29cda100053ac16f01b9e8 | 8cae430f0a71442d02dbb1cbb14073b31048e4b0 | /src/data/finset/prod.lean | 278f9ac72858bdbcfbd6ffa885bf62100cc93bdf | [
"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 | 13,099 | lean | /-
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Mario Carneiro, Oliver Nash
-/
import data.finset.card
/-!
# Finsets in product types
> THIS FILE IS SYNCHRONIZED WITH MATHLIB4.
> Any changes to this file require a corresponding PR to mathlib4.
This file defines finset constructions on the product type `α × β`. Beware not to confuse with the
`finset.prod` operation which computes the multiplicative product.
## Main declarations
* `finset.product`: Turns `s : finset α`, `t : finset β` into their product in `finset (α × β)`.
* `finset.diag`: For `s : finset α`, `s.diag` is the `finset (α × α)` of pairs `(a, a)` with
`a ∈ s`.
* `finset.off_diag`: For `s : finset α`, `s.off_diag` is the `finset (α × α)` of pairs `(a, b)` with
`a, b ∈ s` and `a ≠ b`.
-/
open multiset
variables {α β γ : Type*}
namespace finset
/-! ### prod -/
section prod
variables {s s' : finset α} {t t' : finset β} {a : α} {b : β}
/-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/
protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, s.nodup.product t.nodup⟩
/- This notation binds more strongly than (pre)images, unions and intersections. -/
infixr (name := finset.product) ` ×ˢ `:82 := finset.product
@[simp] lemma product_val : (s ×ˢ t).1 = s.1 ×ˢ t.1 := rfl
@[simp] lemma mem_product {p : α × β} : p ∈ s ×ˢ t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product
lemma mk_mem_product (ha : a ∈ s) (hb : b ∈ t) : (a, b) ∈ s ×ˢ t := mem_product.2 ⟨ha, hb⟩
@[simp, norm_cast] lemma coe_product (s : finset α) (t : finset β) :
(↑(s ×ˢ t) : set (α × β)) = s ×ˢ t :=
set.ext $ λ x, finset.mem_product
lemma subset_product_image_fst [decidable_eq α] : (s ×ˢ t).image prod.fst ⊆ s :=
λ i, by simp [mem_image] {contextual := tt}
lemma subset_product_image_snd [decidable_eq β] : (s ×ˢ t).image prod.snd ⊆ t :=
λ i, by simp [mem_image] {contextual := tt}
lemma product_image_fst [decidable_eq α] (ht : t.nonempty) : (s ×ˢ t).image prod.fst = s :=
by { ext i, simp [mem_image, ht.bex] }
lemma product_image_snd [decidable_eq β] (ht : s.nonempty) : (s ×ˢ t).image prod.snd = t :=
by { ext i, simp [mem_image, ht.bex] }
lemma subset_product [decidable_eq α] [decidable_eq β] {s : finset (α × β)} :
s ⊆ s.image prod.fst ×ˢ s.image prod.snd :=
λ p hp, mem_product.2 ⟨mem_image_of_mem _ hp, mem_image_of_mem _ hp⟩
lemma product_subset_product (hs : s ⊆ s') (ht : t ⊆ t') : s ×ˢ t ⊆ s' ×ˢ t' :=
λ ⟨x,y⟩ h, mem_product.2 ⟨hs (mem_product.1 h).1, ht (mem_product.1 h).2⟩
lemma product_subset_product_left (hs : s ⊆ s') : s ×ˢ t ⊆ s' ×ˢ t :=
product_subset_product hs (subset.refl _)
lemma product_subset_product_right (ht : t ⊆ t') : s ×ˢ t ⊆ s ×ˢ t' :=
product_subset_product (subset.refl _) ht
lemma map_swap_product (s : finset α) (t : finset β) :
(t ×ˢ s).map ⟨prod.swap, prod.swap_injective⟩ = s ×ˢ t :=
coe_injective $ by { push_cast, exact set.image_swap_prod _ _ }
@[simp] lemma image_swap_product [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) :
(t ×ˢ s).image prod.swap = s ×ˢ t :=
coe_injective $ by { push_cast, exact set.image_swap_prod _ _ }
lemma product_eq_bUnion [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) :
s ×ˢ t = s.bUnion (λa, t.image $ λb, (a, b)) :=
ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff,
and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left]
lemma product_eq_bUnion_right [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) :
s ×ˢ t = t.bUnion (λ b, s.image $ λ a, (a, b)) :=
ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff,
and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left]
/-- See also `finset.sup_product_left`. -/
@[simp] lemma product_bUnion [decidable_eq γ] (s : finset α) (t : finset β) (f : α × β → finset γ) :
(s ×ˢ t).bUnion f = s.bUnion (λ a, t.bUnion (λ b, f (a, b))) :=
by { classical, simp_rw [product_eq_bUnion, bUnion_bUnion, image_bUnion] }
@[simp] lemma card_product (s : finset α) (t : finset β) : card (s ×ˢ t) = card s * card t :=
multiset.card_product _ _
lemma filter_product (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] :
(s ×ˢ t).filter (λ (x : α × β), p x.1 ∧ q x.2) = s.filter p ×ˢ t.filter q :=
by { ext ⟨a, b⟩, simp only [mem_filter, mem_product],
exact and_and_and_comm (a ∈ s) (b ∈ t) (p a) (q b) }
lemma filter_product_left (p : α → Prop) [decidable_pred p] :
(s ×ˢ t).filter (λ (x : α × β), p x.1) = s.filter p ×ˢ t :=
by simpa using filter_product p (λ _, true)
lemma filter_product_right (q : β → Prop) [decidable_pred q] :
(s ×ˢ t).filter (λ (x : α × β), q x.2) = s ×ˢ t.filter q :=
by simpa using filter_product (λ _ : α, true) q
lemma filter_product_card (s : finset α) (t : finset β)
(p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] :
((s ×ˢ t).filter (λ (x : α × β), p x.1 ↔ q x.2)).card =
(s.filter p).card * (t.filter q).card + (s.filter (not ∘ p)).card * (t.filter (not ∘ q)).card :=
begin
classical,
rw [← card_product, ← card_product, ← filter_product, ← filter_product, ← card_union_eq],
{ apply congr_arg, ext ⟨a, b⟩, simp only [filter_union_right, mem_filter, mem_product],
split; intros h; use h.1,
simp only [function.comp_app, and_self, h.2, em (q b)],
cases h.2; { try { simp at h_1 }, simp [h_1] } },
{ apply finset.disjoint_filter_filter',
exact (disjoint_compl_right.inf_left _).inf_right _ }
end
lemma empty_product (t : finset β) : (∅ : finset α) ×ˢ t = ∅ := rfl
lemma product_empty (s : finset α) : s ×ˢ (∅ : finset β) = ∅ :=
eq_empty_of_forall_not_mem (λ x h, (finset.mem_product.1 h).2)
lemma nonempty.product (hs : s.nonempty) (ht : t.nonempty) : (s ×ˢ t).nonempty :=
let ⟨x, hx⟩ := hs, ⟨y, hy⟩ := ht in ⟨(x, y), mem_product.2 ⟨hx, hy⟩⟩
lemma nonempty.fst (h : (s ×ˢ t).nonempty) : s.nonempty :=
let ⟨xy, hxy⟩ := h in ⟨xy.1, (mem_product.1 hxy).1⟩
lemma nonempty.snd (h : (s ×ˢ t).nonempty) : t.nonempty :=
let ⟨xy, hxy⟩ := h in ⟨xy.2, (mem_product.1 hxy).2⟩
@[simp] lemma nonempty_product : (s ×ˢ t).nonempty ↔ s.nonempty ∧ t.nonempty :=
⟨λ h, ⟨h.fst, h.snd⟩, λ h, h.1.product h.2⟩
@[simp] lemma product_eq_empty {s : finset α} {t : finset β} : s ×ˢ t = ∅ ↔ s = ∅ ∨ t = ∅ :=
by rw [←not_nonempty_iff_eq_empty, nonempty_product, not_and_distrib, not_nonempty_iff_eq_empty,
not_nonempty_iff_eq_empty]
@[simp] lemma singleton_product {a : α} :
({a} : finset α) ×ˢ t = t.map ⟨prod.mk a, prod.mk.inj_left _⟩ :=
by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] }
@[simp] lemma product_singleton {b : β} :
s ×ˢ {b} = s.map ⟨λ i, (i, b), prod.mk.inj_right _⟩ :=
by { ext ⟨x, y⟩, simp [and.left_comm, eq_comm] }
lemma singleton_product_singleton {a : α} {b : β} :
({a} : finset α) ×ˢ ({b} : finset β) = {(a, b)} :=
by simp only [product_singleton, function.embedding.coe_fn_mk, map_singleton]
@[simp] lemma union_product [decidable_eq α] [decidable_eq β] :
(s ∪ s') ×ˢ t = s ×ˢ t ∪ s' ×ˢ t :=
by { ext ⟨x, y⟩, simp only [or_and_distrib_right, mem_union, mem_product] }
@[simp] lemma product_union [decidable_eq α] [decidable_eq β] :
s ×ˢ (t ∪ t') = s ×ˢ t ∪ s ×ˢ t' :=
by { ext ⟨x, y⟩, simp only [and_or_distrib_left, mem_union, mem_product] }
lemma inter_product [decidable_eq α] [decidable_eq β] :
(s ∩ s') ×ˢ t = s ×ˢ t ∩ s' ×ˢ t :=
by { ext ⟨x, y⟩, simp only [←and_and_distrib_right, mem_inter, mem_product] }
lemma product_inter [decidable_eq α] [decidable_eq β] :
s ×ˢ (t ∩ t') = s ×ˢ t ∩ s ×ˢ t' :=
by { ext ⟨x, y⟩, simp only [←and_and_distrib_left, mem_inter, mem_product] }
lemma product_inter_product [decidable_eq α] [decidable_eq β] :
s ×ˢ t ∩ s' ×ˢ t' = (s ∩ s') ×ˢ (t ∩ t') :=
by { ext ⟨x, y⟩, simp only [and_assoc, and.left_comm, mem_inter, mem_product] }
lemma disjoint_product : disjoint (s ×ˢ t) (s' ×ˢ t') ↔ disjoint s s' ∨ disjoint t t' :=
by simp_rw [←disjoint_coe, coe_product, set.disjoint_prod]
@[simp] lemma disj_union_product (hs : disjoint s s') :
s.disj_union s' hs ×ˢ t = (s ×ˢ t).disj_union (s' ×ˢ t)
(disjoint_product.mpr $ or.inl hs) :=
eq_of_veq $ multiset.add_product _ _ _
@[simp] lemma product_disj_union (ht : disjoint t t') :
s ×ˢ t.disj_union t' ht = (s ×ˢ t).disj_union (s ×ˢ t')
(disjoint_product.mpr $ or.inr ht) :=
eq_of_veq $ multiset.product_add _ _ _
end prod
section diag
variables [decidable_eq α] (s t : finset α)
/-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for
`a ∈ s`. -/
def diag := (s ×ˢ s).filter (λ a : α × α, a.fst = a.snd)
/-- Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b`
for `a, b ∈ s`. -/
def off_diag := (s ×ˢ s).filter (λ (a : α × α), a.fst ≠ a.snd)
variables {s} {x : α × α}
@[simp] lemma mem_diag : x ∈ s.diag ↔ x.1 ∈ s ∧ x.1 = x.2 :=
by { simp only [diag, mem_filter, mem_product], split; intros h;
simp only [h, and_true, eq_self_iff_true, and_self], rw ←h.2, exact h.1 }
@[simp] lemma mem_off_diag : x ∈ s.off_diag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 :=
by { simp only [off_diag, mem_filter, mem_product], split; intros h;
simp only [h, ne.def, not_false_iff, and_self] }
variables (s)
@[simp, norm_cast] lemma coe_off_diag : (s.off_diag : set (α × α)) = (s : set α).off_diag :=
set.ext $ λ _, mem_off_diag
@[simp] lemma diag_card : (diag s).card = s.card :=
begin
suffices : diag s = s.image (λ a, (a, a)),
{ rw this, apply card_image_of_inj_on, exact λ x1 h1 x2 h2 h3, (prod.mk.inj h3).1 },
ext ⟨a₁, a₂⟩, rw mem_diag, split; intros h; rw finset.mem_image at *,
{ use [a₁, h.1, prod.mk.inj_iff.mpr ⟨rfl, h.2⟩] },
{ rcases h with ⟨a, h1, h2⟩, have h := prod.mk.inj h2, rw [←h.1, ←h.2], use h1 },
end
@[simp] lemma off_diag_card : (off_diag s).card = s.card * s.card - s.card :=
begin
suffices : (diag s).card + (off_diag s).card = s.card * s.card,
{ nth_rewrite 2 ← s.diag_card, simp only [diag_card] at *, rw tsub_eq_of_eq_add_rev, rw this },
rw ← card_product,
apply filter_card_add_filter_neg_card_eq_card,
end
@[mono] lemma diag_mono : monotone (diag : finset α → finset (α × α)) :=
λ s t h x hx, mem_diag.2 $ and.imp_left (@h _) $ mem_diag.1 hx
@[mono] lemma off_diag_mono : monotone (off_diag : finset α → finset (α × α)) :=
λ s t h x hx, mem_off_diag.2 $ and.imp (@h _) (and.imp_left $ @h _) $ mem_off_diag.1 hx
@[simp] lemma diag_empty : (∅ : finset α).diag = ∅ := rfl
@[simp] lemma off_diag_empty : (∅ : finset α).off_diag = ∅ := rfl
@[simp] lemma diag_union_off_diag : s.diag ∪ s.off_diag = s ×ˢ s :=
filter_union_filter_neg_eq _ _
@[simp] lemma disjoint_diag_off_diag : disjoint s.diag s.off_diag :=
disjoint_filter_filter_neg _ _ _
lemma product_sdiff_diag : s ×ˢ s \ s.diag = s.off_diag :=
by rw [←diag_union_off_diag, union_comm, union_sdiff_self,
sdiff_eq_self_of_disjoint (disjoint_diag_off_diag _).symm]
lemma product_sdiff_off_diag : s ×ˢ s \ s.off_diag = s.diag :=
by rw [←diag_union_off_diag, union_sdiff_self, sdiff_eq_self_of_disjoint (disjoint_diag_off_diag _)]
lemma diag_inter : (s ∩ t).diag = s.diag ∩ t.diag :=
ext $ λ x, by simpa only [mem_diag, mem_inter] using and_and_distrib_right _ _ _
lemma off_diag_inter : (s ∩ t).off_diag = s.off_diag ∩ t.off_diag :=
coe_injective $ by { push_cast, exact set.off_diag_inter _ _ }
lemma diag_union : (s ∪ t).diag = s.diag ∪ t.diag :=
by { ext ⟨i, j⟩, simp only [mem_diag, mem_union, or_and_distrib_right] }
variables {s t}
lemma off_diag_union (h : disjoint s t) :
(s ∪ t).off_diag = s.off_diag ∪ t.off_diag ∪ s ×ˢ t ∪ t ×ˢ s :=
coe_injective $ by { push_cast, exact set.off_diag_union (disjoint_coe.2 h) }
variables (a : α)
@[simp] lemma off_diag_singleton : ({a} : finset α).off_diag = ∅ :=
by simp [←finset.card_eq_zero]
lemma diag_singleton : ({a} : finset α).diag = {(a, a)} :=
by rw [←product_sdiff_off_diag, off_diag_singleton, sdiff_empty, singleton_product_singleton]
lemma diag_insert : (insert a s).diag = insert (a, a) s.diag :=
by rw [insert_eq, insert_eq, diag_union, diag_singleton]
lemma off_diag_insert (has : a ∉ s) :
(insert a s).off_diag = s.off_diag ∪ {a} ×ˢ s ∪ s ×ˢ {a} :=
by rw [insert_eq, union_comm, off_diag_union (disjoint_singleton_right.2 has), off_diag_singleton,
union_empty, union_right_comm]
end diag
end finset
|
3e5489da233956e8d550bd509d3b1a216fa44962 | bbecf0f1968d1fba4124103e4f6b55251d08e9c4 | /src/category_theory/category/Quiv.lean | 80c0d44b2c3eaf3d7494385dab5114ce116963e6 | [
"Apache-2.0"
] | permissive | waynemunro/mathlib | e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552 | 065a70810b5480d584033f7bbf8e0409480c2118 | refs/heads/master | 1,693,417,182,397 | 1,634,644,781,000 | 1,634,644,781,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 3,144 | lean | /-
Copyright (c) 2021 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison
-/
import category_theory.path_category
import category_theory.category.Cat
/-!
# The category of quivers
The category of (bundled) quivers, and the free/forgetful adjunction between `Cat` and `Quiv`.
-/
universes v u
namespace category_theory
/-- Category of quivers. -/
@[nolint check_univs] -- intended to be used with explicit universe parameters
def Quiv := bundled quiver.{(v+1) u}
namespace Quiv
instance : has_coe_to_sort Quiv :=
{ S := Type u,
coe := bundled.α }
instance str (C : Quiv.{v u}) : quiver.{(v+1) u} C := C.str
/-- Construct a bundled `Quiv` from the underlying type and the typeclass. -/
def of (C : Type u) [quiver.{v+1} C] : Quiv.{v u} := bundled.of C
instance : inhabited Quiv := ⟨Quiv.of (quiver.empty pempty)⟩
/-- Category structure on `Quiv` -/
instance category : large_category.{max v u} Quiv.{v u} :=
{ hom := λ C D, prefunctor C D,
id := λ C, prefunctor.id C,
comp := λ C D E F G, prefunctor.comp F G,
id_comp' := λ C D F, by cases F; refl,
comp_id' := λ C D F, by cases F; refl,
assoc' := by intros; refl }
/-- The forgetful functor from categories to quivers. -/
@[simps]
def forget : Cat.{v u} ⥤ Quiv.{v u} :=
{ obj := λ C, Quiv.of C,
map := λ C D F, F.to_prefunctor, }
end Quiv
namespace Cat
/-- The functor sending each quiver to its path category. -/
@[simps]
def free : Quiv.{v u} ⥤ Cat.{(max u v) u} :=
{ obj := λ V, Cat.of (paths V),
map := λ V W F,
{ obj := λ X, F.obj X,
map := λ X Y f, F.map_path f,
map_comp' := λ X Y Z f g, F.map_path_comp f g, },
map_id' := λ V, by { change (show paths V ⥤ _, from _) = _, ext, apply eq_conj_eq_to_hom, refl },
map_comp' := λ U V W F G,
by { change (show paths U ⥤ _, from _) = _, ext, apply eq_conj_eq_to_hom, refl } }
end Cat
namespace Quiv
/-- Any prefunctor into a category lifts to a functor from the path category. -/
@[simps]
def lift {V : Type u} [quiver.{v+1} V] {C : Type u} [category.{v} C]
(F : prefunctor V C) : paths V ⥤ C :=
{ obj := λ X, F.obj X,
map := λ X Y f, compose_path (F.map_path f), }
-- We might construct `of_lift_iso_self : paths.of ⋙ lift F ≅ F`
-- (and then show that `lift F` is initial amongst such functors)
-- but it would require lifting quite a bit of machinery to quivers!
/--
The adjunction between forming the free category on a quiver, and forgetting a category to a quiver.
-/
def adj : Cat.free ⊣ Quiv.forget :=
adjunction.mk_of_hom_equiv
{ hom_equiv := λ V C,
{ to_fun := λ F, paths.of.comp F.to_prefunctor,
inv_fun := λ F, lift F,
left_inv := λ F, by { ext, { erw (eq_conj_eq_to_hom _).symm, apply category.id_comp }, refl },
right_inv := begin
rintro ⟨obj,map⟩,
dsimp only [prefunctor.comp],
congr,
ext X Y f,
exact category.id_comp _,
end, },
hom_equiv_naturality_left_symm' := λ V W C f g,
by { change (show paths V ⥤ _, from _) = _, ext, apply eq_conj_eq_to_hom, refl } }
end Quiv
end category_theory
|
0e554517314347fd108540dc04a5ebebd0d607b1 | ac1c2a2f522b0fdf854095ba00f882ca849669e7 | /library/init/util.lean | b41b613db31a942ecf88d5f98f47bdd8a1a633d4 | [
"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 | 1,628 | lean | /-
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
prelude
import init.meta.format
universes u
/-- This function has a native implementation that tracks time. -/
def timeit {α : Type u} (s : string) (f : thunk α) : α :=
f ()
/-- This function has a native implementation that displays the given string in the regular output stream. -/
def trace {α : Type u} (s : string) (f : thunk α) : α :=
f ()
meta def trace_val {α : Type u} [has_to_format α] (f : α) : α :=
trace (to_string (to_fmt f)) f
/-- This function has a native implementation that shows the VM call stack. -/
def trace_call_stack {α : Type u} (f : thunk α) : α :=
f ()
/-- This function has a native implementation that displays in the given position all trace messages used in f.
The arguments line and col are filled by the elaborator. -/
def scope_trace {α : Type u} {line col: nat} (f : thunk α) : α :=
f ()
/--
This function has a native implementation where
the thunk is interrupted if it takes more than 'max' "heartbeats" to compute it.
The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'f ()'.
This is a deterministic way of interrupting long running tasks. -/
meta def try_for {α : Type u} (max : nat) (f : thunk α) : option α :=
some (f ())
meta constant undefined_core {α : Sort u} (message : string) : α
meta def undefined {α : Sort u} : α := undefined_core "undefined"
meta def unchecked_cast {α : Sort u} {β : Sort u} : α → β :=
cast undefined
|
993d4b1b27ab45e427f1dfe0984d932db65b56d3 | 75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2 | /tests/lean/check.lean | 3a4e6f7c92bf8eaf3d089b03168ea44544aafd04 | [
"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 | 66 | lean | import logic
check and.intro
check or.elim
check eq
check eq.rec
|
f7cb463c9efe446c73f01dde7a58bfadcf4c712e | 26ac254ecb57ffcb886ff709cf018390161a9225 | /src/order/filter/at_top_bot.lean | 0ff6a2a6aebde8ad68c5a4b20a1f9df1c79943fe | [
"Apache-2.0"
] | permissive | eric-wieser/mathlib | 42842584f584359bbe1fc8b88b3ff937c8acd72d | d0df6b81cd0920ad569158c06a3fd5abb9e63301 | refs/heads/master | 1,669,546,404,255 | 1,595,254,668,000 | 1,595,254,668,000 | 281,173,504 | 0 | 0 | Apache-2.0 | 1,595,263,582,000 | 1,595,263,581,000 | null | UTF-8 | Lean | false | false | 26,542 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov, Patrick Massot
-/
import order.filter.basic
/-!
# `at_top` and `at_bot` filters on preorded sets, monoids and groups.
In this file we define the filters
* `at_top`: corresponds to `n → +∞`;
* `at_bot`: corresponds to `n → -∞`.
Then we prove many lemmas like “if `f → +∞`, then `f ± c → +∞`”.
-/
variables {ι ι' α β γ : Type*}
open set
open_locale classical filter big_operators
namespace filter
/-- `at_top` is the filter representing the limit `→ ∞` on an ordered set.
It is generated by the collection of up-sets `{b | a ≤ b}`.
(The preorder need not have a top element for this to be well defined,
and indeed is trivial when a top element exists.) -/
def at_top [preorder α] : filter α := ⨅ a, 𝓟 {b | a ≤ b}
/-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set.
It is generated by the collection of down-sets `{b | b ≤ a}`.
(The preorder need not have a bottom element for this to be well defined,
and indeed is trivial when a bottom element exists.) -/
def at_bot [preorder α] : filter α := ⨅ a, 𝓟 {b | b ≤ a}
lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ :=
mem_infi_sets a $ subset.refl _
lemma Ioi_mem_at_top [preorder α] [no_top_order α] (x : α) : Ioi x ∈ (at_top : filter α) :=
let ⟨z, hz⟩ := no_top x in mem_sets_of_superset (mem_at_top z) $ λ y h, lt_of_lt_of_le hz h
lemma mem_at_bot [preorder α] (a : α) : {b : α | b ≤ a} ∈ @at_bot α _ :=
mem_infi_sets a $ subset.refl _
lemma Iio_mem_at_bot [preorder α] [no_bot_order α] (x : α) : Iio x ∈ (at_bot : filter α) :=
let ⟨z, hz⟩ := no_bot x in mem_sets_of_superset (mem_at_bot z) $ λ y h, lt_of_le_of_lt h hz
@[instance]
lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : ne_bot (at_top : filter α) :=
infi_ne_bot_of_directed
(assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of,
mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩)
(assume a, principal_ne_bot_iff.2 nonempty_Ici)
@[simp, nolint ge_or_gt]
lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} :
s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s :=
let ⟨a⟩ := ‹nonempty α› in
iff.intro
(assume h, infi_sets_induct h ⟨a, by simp only [forall_const, mem_univ, forall_true_iff]⟩
(assume a s₁ s₂ ha ⟨b, hb⟩, ⟨a ⊔ b,
assume c hc, ⟨ha $ le_trans le_sup_left hc, hb _ $ le_trans le_sup_right hc⟩⟩)
(assume s₁ s₂ h ⟨a, ha⟩, ⟨a, assume b hb, h $ ha _ hb⟩))
(assume ⟨a, h⟩, mem_infi_sets a $ assume x, h x)
@[simp, nolint ge_or_gt]
lemma eventually_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} :
(∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ b ≥ a, p b) :=
mem_at_top_sets
lemma eventually_ge_at_top [preorder α] (a : α) : ∀ᶠ x in at_top, a ≤ x := mem_at_top a
lemma order_top.at_top_eq (α) [order_top α] : (at_top : filter α) = pure ⊤ :=
le_antisymm (le_pure_iff.2 $ (eventually_ge_at_top ⊤).mono $ λ b, top_unique)
(le_infi $ λ b, le_principal_iff.2 le_top)
lemma tendsto_at_top_pure [order_top α] (f : α → β) :
tendsto f at_top (pure $ f ⊤) :=
(order_top.at_top_eq α).symm ▸ tendsto_pure_pure _ _
@[nolint ge_or_gt]
lemma eventually.exists_forall_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop}
(h : ∀ᶠ x in at_top, p x) : ∃ a, ∀ b ≥ a, p b :=
eventually_at_top.mp h
@[nolint ge_or_gt]
lemma frequently_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} :
(∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b ≥ a, p b) :=
by simp only [filter.frequently, eventually_at_top, not_exists, not_forall, not_not]
@[nolint ge_or_gt]
lemma frequently_at_top' [semilattice_sup α] [nonempty α] [no_top_order α] {p : α → Prop} :
(∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b > a, p b) :=
begin
rw frequently_at_top,
split ; intros h a,
{ cases no_top a with a' ha',
rcases h a' with ⟨b, hb, hb'⟩,
exact ⟨b, lt_of_lt_of_le ha' hb, hb'⟩ },
{ rcases h a with ⟨b, hb, hb'⟩,
exact ⟨b, le_of_lt hb, hb'⟩ },
end
@[nolint ge_or_gt]
lemma frequently.forall_exists_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop}
(h : ∃ᶠ x in at_top, p x) : ∀ a, ∃ b ≥ a, p b :=
frequently_at_top.mp h
lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} :
at_top.map f = (⨅a, 𝓟 $ f '' {a' | a ≤ a'}) :=
calc map f (⨅a, 𝓟 {a' | a ≤ a'}) = (⨅a, map f $ 𝓟 {a' | a ≤ a'}) :
map_infi_eq (assume a b, ⟨a ⊔ b, by simp only [ge, le_principal_iff, forall_const, set_of_subset_set_of,
mem_principal_sets, and_self, sup_le_iff, forall_true_iff] {contextual := tt}⟩)
(by apply_instance)
... = (⨅a, 𝓟 $ f '' {a' | a ≤ a'}) : by simp only [map_principal, eq_self_iff_true]
lemma tendsto_at_top [preorder β] (m : α → β) (f : filter α) :
tendsto m f at_top ↔ (∀b, ∀ᶠ a in f, b ≤ m a) :=
by simp only [at_top, tendsto_infi, tendsto_principal, mem_set_of_eq]
lemma tendsto_at_bot [preorder β] (m : α → β) (f : filter α) :
tendsto m f at_bot ↔ (∀b, ∀ᶠ a in f, m a ≤ b) :=
@tendsto_at_top α (order_dual β) _ m f
lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) :
tendsto f₁ l at_top → tendsto f₂ l at_top :=
assume h₁, (tendsto_at_top _ _).2 $ λ b, mp_sets ((tendsto_at_top _ _).1 h₁ b)
(monotone_mem_sets (λ a ha ha₁, le_trans ha₁ ha) h)
lemma tendsto_at_top_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) :
tendsto f l at_top → tendsto g l at_top :=
tendsto_at_top_mono' l $ eventually_of_forall h
/-!
### Sequences
-/
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma inf_map_at_top_ne_bot_iff [semilattice_sup α] [nonempty α] {F : filter β} {u : α → β} :
ne_bot (F ⊓ (map u at_top)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≥ N, u n ∈ U :=
by simp_rw [inf_ne_bot_iff_frequently_left, frequently_map, frequently_at_top]; refl
lemma extraction_of_frequently_at_top' {P : ℕ → Prop} (h : ∀ N, ∃ n > N, P n) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) :=
begin
choose u hu using h,
cases forall_and_distrib.mp hu with hu hu',
exact ⟨u ∘ (nat.rec 0 (λ n v, u v)), strict_mono.nat (λ n, hu _), λ n, hu' _⟩,
end
lemma extraction_of_frequently_at_top {P : ℕ → Prop} (h : ∃ᶠ n in at_top, P n) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) :=
begin
rw frequently_at_top' at h,
exact extraction_of_frequently_at_top' h,
end
lemma extraction_of_eventually_at_top {P : ℕ → Prop} (h : ∀ᶠ n in at_top, P n) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) :=
extraction_of_frequently_at_top h.frequently
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma exists_le_of_tendsto_at_top [semilattice_sup α] [preorder β] {u : α → β}
(h : tendsto u at_top at_top) : ∀ a b, ∃ a' ≥ a, b ≤ u a' :=
begin
intros a b,
have : ∀ᶠ x in at_top, a ≤ x ∧ b ≤ u x :=
(eventually_ge_at_top a).and (h.eventually $ eventually_ge_at_top b),
haveI : nonempty α := ⟨a⟩,
rcases this.exists with ⟨a', ha, hb⟩,
exact ⟨a', ha, hb⟩
end
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma exists_lt_of_tendsto_at_top [semilattice_sup α] [preorder β] [no_top_order β]
{u : α → β} (h : tendsto u at_top at_top) : ∀ a b, ∃ a' ≥ a, b < u a' :=
begin
intros a b,
cases no_top b with b' hb',
rcases exists_le_of_tendsto_at_top h a b' with ⟨a', ha', ha''⟩,
exact ⟨a', ha', lt_of_lt_of_le hb' ha''⟩
end
/--
If `u` is a sequence which is unbounded above,
then after any point, it reaches a value strictly greater than all previous values.
-/
@[nolint ge_or_gt] -- see Note [nolint_ge]
lemma high_scores [linear_order β] [no_top_order β] {u : ℕ → β}
(hu : tendsto u at_top at_top) : ∀ N, ∃ n ≥ N, ∀ k < n, u k < u n :=
begin
letI := classical.DLO β,
intros N,
let A := finset.image u (finset.range $ N+1), -- A = {u 0, ..., u N}
have Ane : A.nonempty,
from ⟨u 0, finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.zero_lt_succ _)⟩,
let M := finset.max' A Ane,
have ex : ∃ n ≥ N, M < u n,
from exists_lt_of_tendsto_at_top hu _ _,
obtain ⟨n, hnN, hnM, hn_min⟩ : ∃ n, N ≤ n ∧ M < u n ∧ ∀ k, N ≤ k → k < n → u k ≤ M,
{ use nat.find ex,
rw ← and_assoc,
split,
{ simpa using nat.find_spec ex },
{ intros k hk hk',
simpa [hk] using nat.find_min ex hk' } },
use [n, hnN],
intros k hk,
by_cases H : k ≤ N,
{ have : u k ∈ A,
from finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.lt_succ_of_le H),
have : u k ≤ M,
from finset.le_max' A Ane (u k) this,
exact lt_of_le_of_lt this hnM },
{ push_neg at H,
calc u k ≤ M : hn_min k (le_of_lt H) hk
... < u n : hnM },
end
/--
If `u` is a sequence which is unbounded above,
then it `frequently` reaches a value strictly greater than all previous values.
-/
lemma frequently_high_scores [linear_order β] [no_top_order β] {u : ℕ → β}
(hu : tendsto u at_top at_top) : ∃ᶠ n in at_top, ∀ k < n, u k < u n :=
by simpa [frequently_at_top] using high_scores hu
lemma strict_mono_subseq_of_tendsto_at_top
{β : Type*} [linear_order β] [no_top_order β]
{u : ℕ → β} (hu : tendsto u at_top at_top) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) :=
let ⟨φ, h, h'⟩ := extraction_of_frequently_at_top (frequently_high_scores hu) in
⟨φ, h, λ n m hnm, h' m _ (h hnm)⟩
lemma strict_mono_subseq_of_id_le {u : ℕ → ℕ} (hu : ∀ n, n ≤ u n) :
∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) :=
strict_mono_subseq_of_tendsto_at_top (tendsto_at_top_mono hu tendsto_id)
lemma strict_mono_tendsto_at_top {φ : ℕ → ℕ} (h : strict_mono φ) :
tendsto φ at_top at_top :=
tendsto_at_top_mono h.id_le tendsto_id
section ordered_add_comm_monoid
variables [ordered_add_comm_monoid β] {l : filter α} {f g : α → β}
lemma tendsto_at_top_add_nonneg_left' (hf : ∀ᶠ x in l, 0 ≤ f x) (hg : tendsto g l at_top) :
tendsto (λ x, f x + g x) l at_top :=
tendsto_at_top_mono' l (hf.mono (λ x, le_add_of_nonneg_left)) hg
lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) :
tendsto (λ x, f x + g x) l at_top :=
tendsto_at_top_add_nonneg_left' (eventually_of_forall hf) hg
lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, 0 ≤ g x) :
tendsto (λ x, f x + g x) l at_top :=
tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_right) hg) hf
lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) :
tendsto (λ x, f x + g x) l at_top :=
tendsto_at_top_add_nonneg_right' hf (eventually_of_forall hg)
end ordered_add_comm_monoid
section ordered_cancel_add_comm_monoid
variables [ordered_cancel_add_comm_monoid β] {l : filter α} {f g : α → β}
lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) :
tendsto f l at_top :=
(tendsto_at_top _ l).2 $ assume b,
((tendsto_at_top _ _).1 hf (C + b)).mono (λ x, le_of_add_le_add_left)
lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) :
tendsto f l at_top :=
(tendsto_at_top _ l).2 $ assume b,
((tendsto_at_top _ _).1 hf (b + C)).mono (λ x, le_of_add_le_add_right)
lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : ∀ᶠ x in l, f x ≤ C)
(h : tendsto (λ x, f x + g x) l at_top) :
tendsto g l at_top :=
tendsto_at_top_of_add_const_left C
(tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_right hx (g x))) h)
lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) :
tendsto (λ x, f x + g x) l at_top → tendsto g l at_top :=
tendsto_at_top_of_add_bdd_above_left' C (univ_mem_sets' hC)
lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : ∀ᶠ x in l, g x ≤ C)
(h : tendsto (λ x, f x + g x) l at_top) :
tendsto f l at_top :=
tendsto_at_top_of_add_const_right C
(tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_left hx (f x))) h)
lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) :
tendsto (λ x, f x + g x) l at_top → tendsto f l at_top :=
tendsto_at_top_of_add_bdd_above_right' C (univ_mem_sets' hC)
end ordered_cancel_add_comm_monoid
section ordered_group
variables [ordered_add_comm_group β] (l : filter α) {f g : α → β}
lemma tendsto_at_top_add_left_of_le' (C : β) (hf : ∀ᶠ x in l, C ≤ f x) (hg : tendsto g l at_top) :
tendsto (λ x, f x + g x) l at_top :=
@tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C)
(by simpa) (by simpa)
lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) :
tendsto (λ x, f x + g x) l at_top :=
tendsto_at_top_add_left_of_le' l C (univ_mem_sets' hf) hg
lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, C ≤ g x) :
tendsto (λ x, f x + g x) l at_top :=
@tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C)
(by simp [hg]) (by simp [hf])
lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) :
tendsto (λ x, f x + g x) l at_top :=
tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' hg)
lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) :
tendsto (λ x, C + f x) l at_top :=
tendsto_at_top_add_left_of_le' l C (univ_mem_sets' $ λ _, le_refl C) hf
lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) :
tendsto (λ x, f x + C) l at_top :=
tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' $ λ _, le_refl C)
end ordered_group
open_locale filter
@[nolint ge_or_gt]
lemma tendsto_at_top' [nonempty α] [semilattice_sup α] (f : α → β) (l : filter β) :
tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) :=
by simp only [tendsto_def, mem_at_top_sets]; refl
lemma tendsto_at_bot' [nonempty α] [semilattice_inf α] (f : α → β) (l : filter β) :
tendsto f at_bot l ↔ (∀s ∈ l, ∃a, ∀b≤a, f b ∈ s) :=
@tendsto_at_top' (order_dual α) _ _ _ _ _
@[nolint ge_or_gt]
theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} :
tendsto f at_top (𝓟 s) ↔ ∃N, ∀n≥N, f n ∈ s :=
by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl
/-- A function `f` grows to infinity independent of an order-preserving embedding `e`. -/
lemma tendsto_at_top_embedding [preorder β] [preorder γ]
{f : α → β} {e : β → γ} {l : filter α}
(hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) :
tendsto (e ∘ f) l at_top ↔ tendsto f l at_top :=
begin
rw [tendsto_at_top, tendsto_at_top],
split,
{ assume hc b,
filter_upwards [hc (e b)] assume a, (hm b (f a)).1 },
{ assume hb c,
rcases hu c with ⟨b, hc⟩,
filter_upwards [hb b] assume a ha, le_trans hc ((hm b (f a)).2 ha) }
end
lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) :
tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a :=
iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal
lemma tendsto_at_top_at_bot [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) :
tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → f a ≤ b :=
@tendsto_at_top_at_top α (order_dual β) _ _ _ f
lemma tendsto_at_bot_at_top [nonempty α] [semilattice_inf α] [preorder β] (f : α → β) :
tendsto f at_bot at_top ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → b ≤ f a :=
@tendsto_at_top_at_top (order_dual α) β _ _ _ f
lemma tendsto_at_bot_at_bot [nonempty α] [semilattice_inf α] [preorder β] (f : α → β) :
tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → f a ≤ b :=
@tendsto_at_top_at_top (order_dual α) (order_dual β) _ _ _ f
lemma tendsto_at_top_at_top_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f)
(h : ∀ b, ∃ a, b ≤ f a) :
tendsto f at_top at_top :=
tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in
mem_sets_of_superset (mem_at_top a) $ λ a' ha', le_trans ha (hf ha')
lemma tendsto_at_top_at_top_iff_of_monotone [nonempty α] [semilattice_sup α] [preorder β]
{f : α → β} (hf : monotone f) :
tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a :=
(tendsto_at_top_at_top f).trans $ forall_congr $ λ b, exists_congr $ λ a,
⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩
alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top
alias tendsto_at_top_at_top_iff_of_monotone ← monotone.tendsto_at_top_at_top_iff
lemma tendsto_finset_range : tendsto finset.range at_top at_top :=
finset.range_mono.tendsto_at_top_at_top finset.exists_nat_subset_range
/-- If `f` is a monotone sequence of `finset`s and each `x` belongs to one of `f n`, then
`tendsto f at_top at_top`. -/
lemma monotone.tendsto_at_top_finset [semilattice_sup β]
{f : β → finset α} (h : monotone f) (h' : ∀ x : α, ∃ n, x ∈ f n) :
tendsto f at_top at_top :=
begin
by_cases ne : nonempty β,
{ resetI,
apply h.tendsto_at_top_at_top,
choose N hN using h',
assume b,
rcases (b.image N).bdd_above with ⟨n, hn⟩,
refine ⟨n, λ i ib, _⟩,
have : N i ∈ b.image N := finset.mem_image_of_mem _ ib,
exact h (hn $ finset.mem_coe.2 this) (hN i) },
{ exact tendsto_of_not_nonempty ne }
end
lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : function.left_inverse j i) :
tendsto (finset.image j) at_top at_top :=
(finset.image_mono j).tendsto_at_top_at_top $ assume s,
⟨s.image i, by simp only [finset.image_image, h.comp_eq_id, finset.image_id, le_refl]⟩
lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] :
(at_top : filter β₁) ×ᶠ (at_top : filter β₂) = (at_top : filter (β₁ × β₂)) :=
begin
by_cases ne : nonempty β₁ ∧ nonempty β₂,
{ cases ne,
resetI,
inhabit β₁,
inhabit β₂,
simp [at_top, prod_infi_left (default β₁), prod_infi_right (default β₂), infi_prod],
exact infi_comm },
{ rw not_and_distrib at ne,
cases ne;
{ have : ¬ (nonempty (β₁ × β₂)), by simp [ne],
rw [at_top.filter_eq_bot_of_not_nonempty ne, at_top.filter_eq_bot_of_not_nonempty this],
simp only [bot_prod, prod_bot] } }
end
lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂]
(u₁ : β₁ → α₁) (u₂ : β₂ → α₂) :
(map u₁ at_top) ×ᶠ (map u₂ at_top) = map (prod.map u₁ u₂) at_top :=
by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def]
/-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a
Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an
insertion and a connetion above `b'`. -/
lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β)
(hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) :
map f at_top = at_top :=
begin
rw [@map_at_top_eq α _ ⟨g b'⟩],
refine le_antisymm
(le_infi $ assume b, infi_le_of_le (g (b ⊔ b')) $ principal_mono.2 $ image_subset_iff.2 _)
(le_infi $ assume a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 _),
{ assume a ha, exact (le_trans le_sup_left $ le_trans (hgi _ le_sup_right) $ hf ha) },
{ assume b hb,
have hb' : b' ≤ b := le_trans le_sup_right hb,
exact ⟨g b, (gc _ _ hb').1 (le_trans le_sup_left hb),
le_antisymm ((gc _ _ hb').2 (le_refl _)) (hgi _ hb')⟩ }
end
lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top :=
map_at_top_eq_of_gc (λa, a - k) k
(assume a b h, add_le_add_right h k)
(assume a b h, (nat.le_sub_right_iff_add_le h).symm)
(assume a h, by rw [nat.sub_add_cancel h])
lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top :=
map_at_top_eq_of_gc (λa, a + k) 0
(assume a b h, nat.sub_le_sub_right h _)
(assume a b _, nat.sub_le_right_iff_le_add)
(assume b _, by rw [nat.add_sub_cancel])
lemma tendsto_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top :=
le_of_eq (map_add_at_top_eq_nat k)
lemma tendsto_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top :=
le_of_eq (map_sub_at_top_eq_nat k)
lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) :
tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l :=
show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l,
by rw [← tendsto_map'_iff, map_add_at_top_eq_nat]
lemma map_div_at_top_eq_nat (k : ℕ) (hk : k > 0) : map (λa, a / k) at_top = at_top :=
map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1
(assume a b h, nat.div_le_div_right h)
(assume a b _,
calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff]
... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk
... ↔ _ :
begin
cases k,
exact (lt_irrefl _ hk).elim,
simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff]
end)
(assume b _,
calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk]
... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _)
/-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded
above, then `tendsto u at_top at_top`. -/
lemma tendsto_at_top_at_top_of_monotone' [preorder ι] [linear_order α]
{u : ι → α} (h : monotone u) (H : ¬bdd_above (range u)) :
tendsto u at_top at_top :=
begin
apply h.tendsto_at_top_at_top,
intro b,
rcases not_bdd_above_iff.1 H b with ⟨_, ⟨N, rfl⟩, hN⟩,
exact ⟨N, le_of_lt hN⟩,
end
lemma unbounded_of_tendsto_at_top [nonempty α] [semilattice_sup α] [preorder β] [no_top_order β]
{f : α → β} (h : tendsto f at_top at_top) :
¬ bdd_above (range f) :=
begin
rintros ⟨M, hM⟩,
cases mem_at_top_sets.mp (h $ Ioi_mem_at_top M) with a ha,
apply lt_irrefl M,
calc
M < f a : ha a (le_refl _)
... ≤ M : hM (set.mem_range_self a)
end
/-- If a monotone function `u : ι → α` tends to `at_top` along *some* non-trivial filter `l`, then
it tends to `at_top` along `at_top`. -/
lemma tendsto_at_top_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι}
{u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_top) :
tendsto u at_top at_top :=
h.tendsto_at_top_at_top $ λ b, (hu.eventually (mem_at_top b)).exists
lemma tendsto_at_top_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α}
{φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l]
(H : tendsto (u ∘ φ) l at_top) :
tendsto u at_top at_top :=
tendsto_at_top_of_monotone_of_filter h (tendsto_map' H)
lemma tendsto_neg_at_top_at_bot [ordered_add_comm_group α] :
tendsto (has_neg.neg : α → α) at_top at_bot :=
begin
simp only [tendsto_at_bot, neg_le],
exact λ b, eventually_ge_at_top _
end
lemma tendsto_neg_at_bot_at_top [ordered_add_comm_group α] :
tendsto (has_neg.neg : α → α) at_bot at_top :=
@tendsto_neg_at_top_at_bot (order_dual α) _
/-- Let `f` and `g` be two maps to the same commutative monoid. This lemma gives a sufficient
condition for comparison of the filter `at_top.map (λ s, ∏ b in s, f b)` with
`at_top.map (λ s, ∏ b in s, g b)`. This is useful to compare the set of limit points of
`Π b in s, f b` as `s → at_top` with the similar set for `g`. -/
@[to_additive]
lemma map_at_top_finset_prod_le_of_prod_eq [comm_monoid α] {f : β → α} {g : γ → α}
(h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∏ x in u', g x = ∏ b in v', f b) :
at_top.map (λs:finset β, ∏ b in s, f b) ≤ at_top.map (λs:finset γ, ∏ x in s, g x) :=
by rw [map_at_top_eq, map_at_top_eq];
from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $
by simp [set.image_subset_iff]; exact hv)
end filter
open filter finset
/-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g`
to a commutative monoid. Suppose that `f x = 1` outside of the range of `g`. Then the filters
`at_top.map (λ s, ∏ i in s, f (g i))` and `at_top.map (λ s, ∏ i in s, f i)` coincide.
The additive version of this lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under
the same assumptions.-/
@[to_additive]
lemma function.injective.map_at_top_finset_prod_eq [comm_monoid α] {g : γ → β}
(hg : function.injective g) {f : β → α} (hf : ∀ x ∉ set.range g, f x = 1) :
map (λ s, ∏ i in s, f (g i)) at_top = map (λ s, ∏ i in s, f i) at_top :=
begin
apply le_antisymm; refine map_at_top_finset_prod_le_of_prod_eq (λ s, _),
{ refine ⟨s.preimage (hg.inj_on _), λ t ht, _⟩,
refine ⟨t.image g ∪ s, finset.subset_union_right _ _, _⟩,
rw [← finset.prod_image (hg.inj_on _)],
refine (prod_subset (subset_union_left _ _) _).symm,
simp only [finset.mem_union, finset.mem_image],
refine λ y hy hyt, hf y (mt _ hyt),
rintros ⟨x, rfl⟩,
exact ⟨x, ht (finset.mem_preimage.2 $ hy.resolve_left hyt), rfl⟩ },
{ refine ⟨s.image g, λ t ht, _⟩,
simp only [← prod_preimage _ _ (hg.inj_on _) _ (λ x _, hf x)],
exact ⟨_, (image_subset_iff_subset_preimage _).1 ht, rfl⟩ }
end
/-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g`
to an additive commutative monoid. Suppose that `f x = 0` outside of the range of `g`. Then the
filters `at_top.map (λ s, ∑ i in s, f (g i))` and `at_top.map (λ s, ∑ i in s, f i)` coincide.
This lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under
the same assumptions.-/
add_decl_doc function.injective.map_at_top_finset_sum_eq
|
2cf188f83d319d701c49d5f683688d7b24b75412 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/change_tac_fail.lean | 062132a9bbaab9b4563d4e987990c8cbbd6aa278 | [
"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 | 288 | lean | import data.list
open list
variable {T : Type}
theorem append.assoc : ∀ (s t u : list T), s ++ t ++ u = s ++ (t ++ u)
| append.assoc nil t u := by esimp
| append.assoc (a :: l) t u :=
begin
change (a :: (l ++ t ++ u) = (a :: l) ++ (t ++ a)),
rewrite append.assoc
end
|
6dc778b5045d045327eee8801a32a7116678471a | d9d511f37a523cd7659d6f573f990e2a0af93c6f | /src/order/boolean_algebra.lean | 1fe449265fb6c5aaa91b490a89a1da8e9761e8df | [
"Apache-2.0"
] | permissive | hikari0108/mathlib | b7ea2b7350497ab1a0b87a09d093ecc025a50dfa | a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901 | refs/heads/master | 1,690,483,608,260 | 1,631,541,580,000 | 1,631,541,580,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 32,857 | 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, Bryan Gin-ge Chen
-/
import order.bounded_lattice
/-!
# (Generalized) Boolean algebras
A Boolean algebra is a bounded distributive lattice with a complement operator. Boolean algebras
generalize the (classical) logic of propositions and the lattice of subsets of a set.
Generalized Boolean algebras may be less familiar, but they are essentially Boolean algebras which
do not necessarily have a top element (`⊤`) (and hence not all elements may have complements). One
example in mathlib is `finset α`, the type of all finite subsets of an arbitrary
(not-necessarily-finite) type `α`.
`generalized_boolean_algebra α` is defined to be a distributive lattice with bottom (`⊥`) admitting
a *relative* complement operator, written using "set difference" notation as `x \ y` (`sdiff x y`).
For convenience, the `boolean_algebra` type class is defined to extend `generalized_boolean_algebra`
so that it is also bundled with a `\` operator.
(A terminological point: `x \ y` is the complement of `y` relative to the interval `[⊥, x]`. We do
not yet have relative complements for arbitrary intervals, as we do not even have lattice
intervals.)
## Main declarations
* `has_compl`: a type class for the complement operator
* `generalized_boolean_algebra`: a type class for generalized Boolean algebras
* `boolean_algebra.core`: a type class with the minimal assumptions for a Boolean algebras
* `boolean_algebra`: the main type class for Boolean algebras; it extends both
`generalized_boolean_algebra` and `boolean_algebra.core`. An instance of `boolean_algebra` can be
obtained from one of `boolean_algebra.core` using `boolean_algebra.of_core`.
* `Prop.boolean_algebra`: the Boolean algebra instance on `Prop`
## Implementation notes
The `sup_inf_sdiff` and `inf_inf_sdiff` axioms for the relative complement operator in
`generalized_boolean_algebra` are taken from
[Wikipedia](https://en.wikipedia.org/wiki/Boolean_algebra_(structure)#Generalizations).
[Stone's paper introducing generalized Boolean algebras][Stone1935] does not define a relative
complement operator `a \ b` for all `a`, `b`. Instead, the postulates there amount to an assumption
that for all `a, b : α` where `a ≤ b`, the equations `x ⊔ a = b` and `x ⊓ a = ⊥` have a solution
`x`. `disjoint.sdiff_unique` proves that this `x` is in fact `b \ a`.
## Notations
* `xᶜ` is notation for `compl x`
* `x \ y` is notation for `sdiff x y`.
## References
* <https://en.wikipedia.org/wiki/Boolean_algebra_(structure)#Generalizations>
* [*Postulates for Boolean Algebras and Generalized Boolean Algebras*, M.H. Stone][Stone1935]
* [*Lattice Theory: Foundation*, George Grätzer][Gratzer2011]
## Tags
generalized Boolean algebras, Boolean algebras, lattices, sdiff, compl
-/
set_option old_structure_cmd true
universes u v
variables {α : Type u} {w x y z : α}
/-!
### Generalized Boolean algebras
Some of the lemmas in this section are from:
* [*Lattice Theory: Foundation*, George Grätzer][Gratzer2011]
* <https://ncatlab.org/nlab/show/relative+complement>
* <https://people.math.gatech.edu/~mccuan/courses/4317/symmetricdifference.pdf>
-/
export has_sdiff (sdiff)
/-- A generalized Boolean algebra is a distributive lattice with `⊥` and a relative complement
operation `\` (called `sdiff`, after "set difference") satisfying `(a ⊓ b) ⊔ (a \ b) = a` and
`(a ⊓ b) ⊓ (a \ b) = b`, i.e. `a \ b` is the complement of `b` in `a`.
This is a generalization of Boolean algebras which applies to `finset α` for arbitrary
(not-necessarily-`fintype`) `α`. -/
class generalized_boolean_algebra (α : Type u) extends distrib_lattice_bot α, has_sdiff α :=
(sup_inf_sdiff : ∀a b:α, (a ⊓ b) ⊔ (a \ b) = a)
(inf_inf_sdiff : ∀a b:α, (a ⊓ b) ⊓ (a \ b) = ⊥)
-- We might want a `is_compl_of` predicate (for relative complements) generalizing `is_compl`,
-- however we'd need another type class for lattices with bot, and all the API for that.
section generalized_boolean_algebra
variables [generalized_boolean_algebra α]
@[simp] theorem sup_inf_sdiff (x y : α) : (x ⊓ y) ⊔ (x \ y) = x :=
generalized_boolean_algebra.sup_inf_sdiff _ _
@[simp] theorem inf_inf_sdiff (x y : α) : (x ⊓ y) ⊓ (x \ y) = ⊥ :=
generalized_boolean_algebra.inf_inf_sdiff _ _
@[simp] theorem sup_sdiff_inf (x y : α) : (x \ y) ⊔ (x ⊓ y) = x :=
by rw [sup_comm, sup_inf_sdiff]
@[simp] theorem inf_sdiff_inf (x y : α) : (x \ y) ⊓ (x ⊓ y) = ⊥ :=
by rw [inf_comm, inf_inf_sdiff]
theorem disjoint_inf_sdiff : disjoint (x ⊓ y) (x \ y) := (inf_inf_sdiff x y).le
-- TODO: in distributive lattices, relative complements are unique when they exist
theorem sdiff_unique (s : (x ⊓ y) ⊔ z = x) (i : (x ⊓ y) ⊓ z = ⊥) : x \ y = z :=
begin
conv_rhs at s { rw [←sup_inf_sdiff x y, sup_comm] },
rw sup_comm at s,
conv_rhs at i { rw [←inf_inf_sdiff x y, inf_comm] },
rw inf_comm at i,
exact (eq_of_inf_eq_sup_eq i s).symm,
end
theorem sdiff_symm (hy : y ≤ x) (hz : z ≤ x) (H : x \ y = z) : x \ z = y :=
have hyi : x ⊓ y = y := inf_eq_right.2 hy,
have hzi : x ⊓ z = z := inf_eq_right.2 hz,
eq_of_inf_eq_sup_eq
(begin
have ixy := inf_inf_sdiff x y,
rw [H, hyi] at ixy,
have ixz := inf_inf_sdiff x z,
rwa [hzi, inf_comm, ←ixy] at ixz,
end)
(begin
have sxz := sup_inf_sdiff x z,
rw [hzi, sup_comm] at sxz,
rw sxz,
symmetry,
have sxy := sup_inf_sdiff x y,
rwa [H, hyi] at sxy,
end)
lemma sdiff_le : x \ y ≤ x :=
calc x \ y ≤ (x ⊓ y) ⊔ (x \ y) : le_sup_right
... = x : sup_inf_sdiff x y
@[simp] lemma bot_sdiff : ⊥ \ x = ⊥ := le_bot_iff.1 sdiff_le
lemma inf_sdiff_right : x ⊓ (x \ y) = x \ y := by rw [inf_of_le_right (@sdiff_le _ x y _)]
lemma inf_sdiff_left : (x \ y) ⊓ x = x \ y := by rw [inf_comm, inf_sdiff_right]
-- cf. `is_compl_top_bot`
@[simp] lemma sdiff_self : x \ x = ⊥ :=
by rw [←inf_inf_sdiff, inf_idem, inf_of_le_right (@sdiff_le _ x x _)]
@[simp] theorem sup_sdiff_self_right : x ⊔ (y \ x) = x ⊔ y :=
calc x ⊔ (y \ x) = (x ⊔ (x ⊓ y)) ⊔ (y \ x) : by rw sup_inf_self
... = x ⊔ ((y ⊓ x) ⊔ (y \ x)) : by ac_refl
... = x ⊔ y : by rw sup_inf_sdiff
@[simp] theorem sup_sdiff_self_left : (y \ x) ⊔ x = y ⊔ x :=
by rw [sup_comm, sup_sdiff_self_right, sup_comm]
lemma sup_sdiff_symm : x ⊔ (y \ x) = y ⊔ (x \ y) :=
by rw [sup_sdiff_self_right, sup_sdiff_self_right, sup_comm]
lemma sup_sdiff_of_le (h : x ≤ y) : x ⊔ (y \ x) = y :=
by conv_rhs { rw [←sup_inf_sdiff y x, inf_eq_right.2 h] }
@[simp] lemma sup_sdiff_left : x ⊔ (x \ y) = x := by { rw sup_eq_left, exact sdiff_le }
lemma sup_sdiff_right : (x \ y) ⊔ x = x := by rw [sup_comm, sup_sdiff_left]
@[simp] lemma sdiff_inf_sdiff : x \ y ⊓ (y \ x) = ⊥ :=
eq.symm $
calc ⊥ = (x ⊓ y) ⊓ (x \ y) : by rw inf_inf_sdiff
... = (x ⊓ (y ⊓ x ⊔ y \ x)) ⊓ (x \ y) : by rw sup_inf_sdiff
... = (x ⊓ (y ⊓ x) ⊔ x ⊓ (y \ x)) ⊓ (x \ y) : by rw inf_sup_left
... = (y ⊓ (x ⊓ x) ⊔ x ⊓ (y \ x)) ⊓ (x \ y) : by ac_refl
... = (y ⊓ x ⊔ x ⊓ (y \ x)) ⊓ (x \ y) : by rw inf_idem
... = (x ⊓ y ⊓ (x \ y)) ⊔ (x ⊓ (y \ x) ⊓ (x \ y)) : by rw [inf_sup_right, @inf_comm _ _ x y]
... = x ⊓ (y \ x) ⊓ (x \ y) : by rw [inf_inf_sdiff, bot_sup_eq]
... = x ⊓ (x \ y) ⊓ (y \ x) : by ac_refl
... = (x \ y) ⊓ (y \ x) : by rw inf_sdiff_right
lemma disjoint_sdiff_sdiff : disjoint (x \ y) (y \ x) := sdiff_inf_sdiff.le
theorem le_sup_sdiff : y ≤ x ⊔ (y \ x) :=
by { rw [sup_sdiff_self_right], exact le_sup_right }
theorem le_sdiff_sup : y ≤ (y \ x) ⊔ x :=
by { rw [sup_comm], exact le_sup_sdiff }
@[simp] theorem inf_sdiff_self_right : x ⊓ (y \ x) = ⊥ :=
calc x ⊓ (y \ x) = ((x ⊓ y) ⊔ (x \ y)) ⊓ (y \ x) : by rw sup_inf_sdiff
... = (x ⊓ y) ⊓ (y \ x) ⊔ (x \ y) ⊓ (y \ x) : by rw inf_sup_right
... = ⊥ : by rw [@inf_comm _ _ x y, inf_inf_sdiff, sdiff_inf_sdiff, bot_sup_eq]
@[simp] theorem inf_sdiff_self_left : (y \ x) ⊓ x = ⊥ := by rw [inf_comm, inf_sdiff_self_right]
theorem disjoint_sdiff_self_left : disjoint (y \ x) x := inf_sdiff_self_left.le
theorem disjoint_sdiff_self_right : disjoint x (y \ x) := inf_sdiff_self_right.le
lemma disjoint.disjoint_sdiff_left (h : disjoint x y) : disjoint (x \ z) y := h.mono_left sdiff_le
lemma disjoint.disjoint_sdiff_right (h : disjoint x y) : disjoint x (y \ z) := h.mono_right sdiff_le
/- TODO: if we had a typeclass for distributive lattices with `⊥`, we could make an alternative
constructor for `generalized_boolean_algebra` using `disjoint x (y \ x)` and `x ⊔ (y \ x) = y` as
axioms. -/
theorem disjoint.sdiff_eq_of_sup_eq (hi : disjoint x z) (hs : x ⊔ z = y) : y \ x = z :=
have h : y ⊓ x = x := inf_eq_right.2 $ le_sup_left.trans hs.le,
sdiff_unique (by rw [h, hs]) (by rw [h, hi.eq_bot])
lemma disjoint.sup_sdiff_cancel_left (h : disjoint x y) : (x ⊔ y) \ x = y :=
h.sdiff_eq_of_sup_eq rfl
lemma disjoint.sup_sdiff_cancel_right (h : disjoint x y) : (x ⊔ y) \ y = x :=
h.symm.sdiff_eq_of_sup_eq sup_comm
protected theorem disjoint.sdiff_unique (hd : disjoint x z) (hz : z ≤ y) (hs : y ≤ x ⊔ z) :
y \ x = z :=
sdiff_unique
(begin
rw ←inf_eq_right at hs,
rwa [sup_inf_right, inf_sup_right, @sup_comm _ _ x, inf_sup_self, inf_comm, @sup_comm _ _ z,
hs, sup_eq_left],
end)
(by rw [inf_assoc, hd.eq_bot, inf_bot_eq])
-- cf. `is_compl.disjoint_left_iff` and `is_compl.disjoint_right_iff`
lemma disjoint_sdiff_iff_le (hz : z ≤ y) (hx : x ≤ y) : disjoint z (y \ x) ↔ z ≤ x :=
⟨λ H, le_of_inf_le_sup_le
(le_trans H bot_le)
(begin
rw sup_sdiff_of_le hx,
refine le_trans (sup_le_sup_left sdiff_le z) _,
rw sup_eq_right.2 hz,
end),
λ H, disjoint_sdiff_self_right.mono_left H⟩
-- cf. `is_compl.le_left_iff` and `is_compl.le_right_iff`
lemma le_iff_disjoint_sdiff (hz : z ≤ y) (hx : x ≤ y) : z ≤ x ↔ disjoint z (y \ x) :=
(disjoint_sdiff_iff_le hz hx).symm
-- cf. `is_compl.inf_left_eq_bot_iff` and `is_compl.inf_right_eq_bot_iff`
lemma inf_sdiff_eq_bot_iff (hz : z ≤ y) (hx : x ≤ y) : z ⊓ (y \ x) = ⊥ ↔ z ≤ x :=
by { rw ←disjoint_iff, exact disjoint_sdiff_iff_le hz hx }
-- cf. `is_compl.left_le_iff` and `is_compl.right_le_iff`
lemma le_iff_eq_sup_sdiff (hz : z ≤ y) (hx : x ≤ y) : x ≤ z ↔ y = z ⊔ (y \ x) :=
⟨λ H,
begin
apply le_antisymm,
{ conv_lhs { rw ←sup_inf_sdiff y x, },
apply sup_le_sup_right,
rwa inf_eq_right.2 hx, },
{ apply le_trans,
{ apply sup_le_sup_right hz, },
{ rw sup_sdiff_left, } }
end,
λ H,
begin
conv_lhs at H { rw ←sup_sdiff_of_le hx, },
refine le_of_inf_le_sup_le _ H.le,
rw inf_sdiff_self_right,
exact bot_le,
end⟩
-- cf. `set.union_diff_cancel'`
lemma sup_sdiff_cancel' (hx : x ≤ z) (hz : z ≤ y) : z ⊔ (y \ x) = y :=
((le_iff_eq_sup_sdiff hz (hx.trans hz)).1 hx).symm
-- cf. `is_compl.sup_inf`
lemma sdiff_sup : y \ (x ⊔ z) = (y \ x) ⊓ (y \ z) :=
sdiff_unique
(calc y ⊓ (x ⊔ z) ⊔ y \ x ⊓ (y \ z) =
(y ⊓ (x ⊔ z) ⊔ y \ x) ⊓ (y ⊓ (x ⊔ z) ⊔ (y \ z)) : by rw sup_inf_left
... = (y ⊓ x ⊔ y ⊓ z ⊔ y \ x) ⊓ (y ⊓ x ⊔ y ⊓ z ⊔ (y \ z)) : by rw @inf_sup_left _ _ y
... = (y ⊓ z ⊔ (y ⊓ x ⊔ y \ x)) ⊓ (y ⊓ x ⊔ (y ⊓ z ⊔ (y \ z))) : by ac_refl
... = (y ⊓ z ⊔ y) ⊓ (y ⊓ x ⊔ y) : by rw [sup_inf_sdiff, sup_inf_sdiff]
... = (y ⊔ y ⊓ z) ⊓ (y ⊔ y ⊓ x) : by ac_refl
... = y : by rw [sup_inf_self, sup_inf_self, inf_idem])
(calc y ⊓ (x ⊔ z) ⊓ ((y \ x) ⊓ (y \ z)) =
(y ⊓ x ⊔ y ⊓ z) ⊓ ((y \ x) ⊓ (y \ z)) : by rw inf_sup_left
... = ((y ⊓ x) ⊓ ((y \ x) ⊓ (y \ z))) ⊔ ((y ⊓ z) ⊓ ((y \ x) ⊓ (y \ z))) : by rw inf_sup_right
... = ((y ⊓ x) ⊓ (y \ x) ⊓ (y \ z)) ⊔ ((y \ x) ⊓ ((y \ z) ⊓ (y ⊓ z))) : by ac_refl
... = ⊥ : by rw [inf_inf_sdiff, bot_inf_eq, bot_sup_eq, @inf_comm _ _ (y \ z), inf_inf_sdiff,
inf_bot_eq])
-- cf. `is_compl.inf_sup`
lemma sdiff_inf : y \ (x ⊓ z) = y \ x ⊔ y \ z :=
sdiff_unique
(calc y ⊓ (x ⊓ z) ⊔ (y \ x ⊔ y \ z) =
(z ⊓ (y ⊓ x)) ⊔ (y \ x ⊔ y \ z) : by ac_refl
... = (z ⊔ (y \ x ⊔ y \ z)) ⊓ ((y ⊓ x) ⊔ (y \ x ⊔ y \ z)) : by rw sup_inf_right
... = (y \ x ⊔ (y \ z ⊔ z)) ⊓ (y ⊓ x ⊔ (y \ x ⊔ y \ z)) : by ac_refl
... = (y ⊔ z) ⊓ ((y ⊓ x) ⊔ (y \ x ⊔ y \ z)) :
by rw [sup_sdiff_self_left, ←sup_assoc, sup_sdiff_right]
... = (y ⊔ z) ⊓ y : by rw [←sup_assoc, sup_inf_sdiff, sup_sdiff_left]
... = y : by rw [inf_comm, inf_sup_self])
(calc y ⊓ (x ⊓ z) ⊓ ((y \ x) ⊔ (y \ z)) =
(y ⊓ (x ⊓ z) ⊓ (y \ x)) ⊔ (y ⊓ (x ⊓ z) ⊓ (y \ z)) : by rw inf_sup_left
... = z ⊓ (y ⊓ x ⊓ (y \ x)) ⊔ z ⊓ (y ⊓ x) ⊓ (y \ z) : by ac_refl
... = z ⊓ (y ⊓ x) ⊓ (y \ z) : by rw [inf_inf_sdiff, inf_bot_eq, bot_sup_eq]
... = x ⊓ ((y ⊓ z) ⊓ (y \ z)) : by ac_refl
... = ⊥ : by rw [inf_inf_sdiff, inf_bot_eq])
@[simp] lemma sdiff_inf_self_right : y \ (x ⊓ y) = y \ x :=
by rw [sdiff_inf, sdiff_self, sup_bot_eq]
@[simp] lemma sdiff_inf_self_left : y \ (y ⊓ x) = y \ x := by rw [inf_comm, sdiff_inf_self_right]
lemma sdiff_eq_sdiff_iff_inf_eq_inf : y \ x = y \ z ↔ y ⊓ x = y ⊓ z :=
⟨λ h, eq_of_inf_eq_sup_eq
(by rw [inf_inf_sdiff, h, inf_inf_sdiff])
(by rw [sup_inf_sdiff, h, sup_inf_sdiff]),
λ h, by rw [←sdiff_inf_self_right, ←@sdiff_inf_self_right _ z y, inf_comm, h, inf_comm]⟩
theorem disjoint.sdiff_eq_left (h : disjoint x y) : x \ y = x :=
by conv_rhs { rw [←sup_inf_sdiff x y, h.eq_bot, bot_sup_eq] }
theorem disjoint.sdiff_eq_right (h : disjoint x y) : y \ x = y := h.symm.sdiff_eq_left
-- cf. `is_compl_bot_top`
@[simp] theorem sdiff_bot : x \ ⊥ = x := disjoint_bot_right.sdiff_eq_left
theorem sdiff_eq_self_iff_disjoint : x \ y = x ↔ disjoint y x :=
calc x \ y = x ↔ x \ y = x \ ⊥ : by rw sdiff_bot
... ↔ x ⊓ y = x ⊓ ⊥ : sdiff_eq_sdiff_iff_inf_eq_inf
... ↔ disjoint y x : by rw [inf_bot_eq, inf_comm, disjoint_iff]
theorem sdiff_eq_self_iff_disjoint' : x \ y = x ↔ disjoint x y :=
by rw [sdiff_eq_self_iff_disjoint, disjoint.comm]
lemma sdiff_lt (hx : y ≤ x) (hy : y ≠ ⊥) :
x \ y < x :=
begin
refine sdiff_le.lt_of_ne (λ h, hy _),
rw [sdiff_eq_self_iff_disjoint', disjoint_iff] at h,
rw [←h, inf_eq_right.mpr hx],
end
-- cf. `is_compl.antimono`
lemma sdiff_le_sdiff_self (h : z ≤ x) : w \ x ≤ w \ z :=
le_of_inf_le_sup_le
(calc (w \ x) ⊓ (w ⊓ z) ≤ (w \ x) ⊓ (w ⊓ x) : inf_le_inf le_rfl (inf_le_inf le_rfl h)
... = ⊥ : by rw [inf_comm, inf_inf_sdiff]
... ≤ (w \ z) ⊓ (w ⊓ z) : bot_le)
(calc w \ x ⊔ (w ⊓ z) ≤ w \ x ⊔ (w ⊓ x) : sup_le_sup le_rfl (inf_le_inf le_rfl h)
... ≤ w : by rw [sup_comm, sup_inf_sdiff]
... = (w \ z) ⊔ (w ⊓ z) : by rw [sup_comm, sup_inf_sdiff])
lemma sdiff_le_iff : y \ x ≤ z ↔ y ≤ x ⊔ z :=
⟨λ h, le_of_inf_le_sup_le
(le_of_eq
(calc y ⊓ (y \ x) = y \ x : inf_sdiff_right
... = (x ⊓ (y \ x)) ⊔ (z ⊓ (y \ x)) :
by rw [inf_eq_right.2 h, inf_sdiff_self_right, bot_sup_eq]
... = (x ⊔ z) ⊓ (y \ x) : inf_sup_right.symm))
(calc y ⊔ y \ x = y : sup_sdiff_left
... ≤ y ⊔ (x ⊔ z) : le_sup_left
... = ((y \ x) ⊔ x) ⊔ z : by rw [←sup_assoc, ←@sup_sdiff_self_left _ x y]
... = x ⊔ z ⊔ y \ x : by ac_refl),
λ h, le_of_inf_le_sup_le
(calc y \ x ⊓ x = ⊥ : inf_sdiff_self_left
... ≤ z ⊓ x : bot_le)
(calc y \ x ⊔ x = y ⊔ x : sup_sdiff_self_left
... ≤ (x ⊔ z) ⊔ x : sup_le_sup_right h x
... ≤ z ⊔ x : by rw [sup_assoc, sup_comm, sup_assoc, sup_idem])⟩
lemma sdiff_eq_bot_iff : y \ x = ⊥ ↔ y ≤ x :=
by rw [←le_bot_iff, sdiff_le_iff, sup_bot_eq]
lemma sdiff_le_comm : x \ y ≤ z ↔ x \ z ≤ y :=
by rw [sdiff_le_iff, sup_comm, sdiff_le_iff]
lemma sdiff_le_self_sdiff (h : w ≤ y) : w \ x ≤ y \ x :=
le_of_inf_le_sup_le
(calc (w \ x) ⊓ (w ⊓ x) = ⊥ : by rw [inf_comm, inf_inf_sdiff]
... ≤ (y \ x) ⊓ (w ⊓ x) : bot_le)
(calc w \ x ⊔ (w ⊓ x) = w : by rw [sup_comm, sup_inf_sdiff]
... ≤ (y ⊓ (y \ x)) ⊔ w : le_sup_right
... = (y ⊓ (y \ x)) ⊔ (y ⊓ w) : by rw inf_eq_right.2 h
... = y ⊓ ((y \ x) ⊔ w) : by rw inf_sup_left
... = ((y \ x) ⊔ (y ⊓ x)) ⊓ ((y \ x) ⊔ w) :
by rw [@sup_comm _ _ (y \ x) (y ⊓ x), sup_inf_sdiff]
... = (y \ x) ⊔ ((y ⊓ x) ⊓ w) : by rw ←sup_inf_left
... = (y \ x) ⊔ ((w ⊓ y) ⊓ x) : by ac_refl
... = (y \ x) ⊔ (w ⊓ x) : by rw inf_eq_left.2 h)
theorem sdiff_le_sdiff (h₁ : w ≤ y) (h₂ : z ≤ x) : w \ x ≤ y \ z :=
calc w \ x ≤ w \ z : sdiff_le_sdiff_self h₂
... ≤ y \ z : sdiff_le_self_sdiff h₁
lemma sup_inf_inf_sdiff : (x ⊓ y) ⊓ z ⊔ (y \ z) = (x ⊓ y) ⊔ (y \ z) :=
calc (x ⊓ y) ⊓ z ⊔ (y \ z) = x ⊓ (y ⊓ z) ⊔ (y \ z) : by rw inf_assoc
... = (x ⊔ (y \ z)) ⊓ y : by rw [sup_inf_right, sup_inf_sdiff]
... = (x ⊓ y) ⊔ (y \ z) : by rw [inf_sup_right, inf_sdiff_left]
@[simp] lemma inf_sdiff_sup_left : (x \ z) ⊓ (x ⊔ y) = x \ z :=
by rw [inf_sup_left, inf_sdiff_left, sup_inf_self]
@[simp] lemma inf_sdiff_sup_right : (x \ z) ⊓ (y ⊔ x) = x \ z :=
by rw [sup_comm, inf_sdiff_sup_left]
lemma sdiff_sdiff_right : x \ (y \ z) = (x \ y) ⊔ (x ⊓ y ⊓ z) :=
begin
rw [sup_comm, inf_comm, ←inf_assoc, sup_inf_inf_sdiff],
apply sdiff_unique,
{ calc x ⊓ (y \ z) ⊔ (z ⊓ x ⊔ x \ y) =
(x ⊔ (z ⊓ x ⊔ x \ y)) ⊓ (y \ z ⊔ (z ⊓ x ⊔ x \ y)) : by rw sup_inf_right
... = (x ⊔ x ⊓ z ⊔ x \ y) ⊓ (y \ z ⊔ (x ⊓ z ⊔ x \ y)) : by ac_refl
... = x ⊓ (y \ z ⊔ x ⊓ z ⊔ x \ y) : by rw [sup_inf_self, sup_sdiff_left, ←sup_assoc]
... = x ⊓ (y \ z ⊓ (z ⊔ y) ⊔ x ⊓ (z ⊔ y) ⊔ x \ y) :
by rw [sup_inf_left, sup_sdiff_self_left, inf_sup_right, @sup_comm _ _ y]
... = x ⊓ (y \ z ⊔ (x ⊓ z ⊔ x ⊓ y) ⊔ x \ y) :
by rw [inf_sdiff_sup_right, @inf_sup_left _ _ x z y]
... = x ⊓ (y \ z ⊔ (x ⊓ z ⊔ (x ⊓ y ⊔ x \ y))) : by ac_refl
... = x ⊓ (y \ z ⊔ (x ⊔ x ⊓ z)) : by rw [sup_inf_sdiff, @sup_comm _ _ (x ⊓ z)]
... = x : by rw [sup_inf_self, sup_comm, inf_sup_self] },
{ calc x ⊓ (y \ z) ⊓ (z ⊓ x ⊔ x \ y) =
x ⊓ (y \ z) ⊓ (z ⊓ x) ⊔ x ⊓ (y \ z) ⊓ (x \ y) : by rw inf_sup_left
... = x ⊓ (y \ z ⊓ z ⊓ x) ⊔ x ⊓ (y \ z) ⊓ (x \ y) : by ac_refl
... = x ⊓ (y \ z) ⊓ (x \ y) : by rw [inf_sdiff_self_left, bot_inf_eq, inf_bot_eq, bot_sup_eq]
... = x ⊓ (y \ z ⊓ y) ⊓ (x \ y) : by conv_lhs { rw ←inf_sdiff_left }
... = x ⊓ (y \ z ⊓ (y ⊓ (x \ y))) : by ac_refl
... = ⊥ : by rw [inf_sdiff_self_right, inf_bot_eq, inf_bot_eq] }
end
lemma sdiff_sdiff_right' : x \ (y \ z) = (x \ y) ⊔ (x ⊓ z) :=
calc x \ (y \ z) = (x \ y) ⊔ (x ⊓ y ⊓ z) : sdiff_sdiff_right
... = z ⊓ x ⊓ y ⊔ (x \ y) : by ac_refl
... = (x \ y) ⊔ (x ⊓ z) : by rw [sup_inf_inf_sdiff, sup_comm, inf_comm]
@[simp] lemma sdiff_sdiff_right_self : x \ (x \ y) = x ⊓ y :=
by rw [sdiff_sdiff_right, inf_idem, sdiff_self, bot_sup_eq]
lemma sdiff_sdiff_eq_self (h : y ≤ x) : x \ (x \ y) = y :=
by rw [sdiff_sdiff_right_self, inf_of_le_right h]
lemma sdiff_sdiff_left : (x \ y) \ z = x \ (y ⊔ z) :=
begin
rw sdiff_sup,
apply sdiff_unique,
{ rw [←inf_sup_left, sup_sdiff_self_right, inf_sdiff_sup_right] },
{ rw [inf_assoc, @inf_comm _ _ z, inf_assoc, inf_sdiff_self_left, inf_bot_eq, inf_bot_eq] }
end
lemma sdiff_sdiff_left' : (x \ y) \ z = (x \ y) ⊓ (x \ z) :=
by rw [sdiff_sdiff_left, sdiff_sup]
lemma sdiff_sdiff_comm : (x \ y) \ z = (x \ z) \ y :=
by rw [sdiff_sdiff_left, sup_comm, sdiff_sdiff_left]
@[simp] lemma sdiff_idem : x \ y \ y = x \ y := by rw [sdiff_sdiff_left, sup_idem]
@[simp] lemma sdiff_sdiff_self : x \ y \ x = ⊥ := by rw [sdiff_sdiff_comm, sdiff_self, bot_sdiff]
lemma sdiff_sdiff_sup_sdiff : z \ (x \ y ⊔ y \ x) = z ⊓ (z \ x ⊔ y) ⊓ (z \ y ⊔ x) :=
calc z \ (x \ y ⊔ y \ x) = (z \ x ⊔ z ⊓ x ⊓ y) ⊓ (z \ y ⊔ z ⊓ y ⊓ x) :
by rw [sdiff_sup, sdiff_sdiff_right, sdiff_sdiff_right]
... = z ⊓ (z \ x ⊔ y) ⊓ (z \ y ⊔ z ⊓ y ⊓ x) : by rw [sup_inf_left, sup_comm, sup_inf_sdiff]
... = z ⊓ (z \ x ⊔ y) ⊓ (z ⊓ (z \ y ⊔ x)) :
by rw [sup_inf_left, @sup_comm _ _ (z \ y), sup_inf_sdiff]
... = z ⊓ z ⊓ (z \ x ⊔ y) ⊓ (z \ y ⊔ x) : by ac_refl
... = z ⊓ (z \ x ⊔ y) ⊓ (z \ y ⊔ x) : by rw inf_idem
lemma sdiff_sdiff_sup_sdiff' : z \ (x \ y ⊔ y \ x) = z ⊓ x ⊓ y ⊔ ((z \ x) ⊓ (z \ y)) :=
calc z \ (x \ y ⊔ y \ x) =
z \ (x \ y) ⊓ (z \ (y \ x)) : sdiff_sup
... = (z \ x ⊔ z ⊓ x ⊓ y) ⊓ (z \ y ⊔ z ⊓ y ⊓ x) : by rw [sdiff_sdiff_right, sdiff_sdiff_right]
... = (z \ x ⊔ z ⊓ y ⊓ x) ⊓ (z \ y ⊔ z ⊓ y ⊓ x) : by ac_refl
... = (z \ x) ⊓ (z \ y) ⊔ z ⊓ y ⊓ x : sup_inf_right.symm
... = z ⊓ x ⊓ y ⊔ ((z \ x) ⊓ (z \ y)) : by ac_refl
lemma sup_sdiff : (x ⊔ y) \ z = (x \ z) ⊔ (y \ z) :=
sdiff_unique
(calc (x ⊔ y) ⊓ z ⊔ (x \ z ⊔ y \ z) =
(x ⊓ z ⊔ y ⊓ z) ⊔ (x \ z ⊔ y \ z) : by rw inf_sup_right
... = x ⊓ z ⊔ x \ z ⊔ y \ z ⊔ y ⊓ z : by ac_refl
... = x ⊔ (y ⊓ z ⊔ y \ z) : by rw [sup_inf_sdiff, sup_assoc, @sup_comm _ _ (y \ z)]
... = x ⊔ y : by rw sup_inf_sdiff)
(calc (x ⊔ y) ⊓ z ⊓ (x \ z ⊔ y \ z) =
(x ⊓ z ⊔ y ⊓ z) ⊓ (x \ z ⊔ y \ z) : by rw inf_sup_right
... = (x ⊓ z ⊔ y ⊓ z) ⊓ (x \ z) ⊔ ((x ⊓ z ⊔ y ⊓ z) ⊓ (y \ z)) :
by rw [@inf_sup_left _ _ (x ⊓ z ⊔ y ⊓ z)]
... = (y ⊓ z ⊓ (x \ z)) ⊔ ((x ⊓ z ⊔ y ⊓ z) ⊓ (y \ z)) :
by rw [inf_sup_right, inf_inf_sdiff, bot_sup_eq]
... = (x ⊓ z ⊔ y ⊓ z) ⊓ (y \ z) : by rw [inf_assoc, inf_sdiff_self_right, inf_bot_eq, bot_sup_eq]
... = x ⊓ z ⊓ (y \ z) : by rw [inf_sup_right, inf_inf_sdiff, sup_bot_eq]
... = ⊥ : by rw [inf_assoc, inf_sdiff_self_right, inf_bot_eq])
lemma sup_sdiff_right_self : (x ⊔ y) \ y = x \ y :=
by rw [sup_sdiff, sdiff_self, sup_bot_eq]
lemma sup_sdiff_left_self : (x ⊔ y) \ x = y \ x :=
by rw [sup_comm, sup_sdiff_right_self]
lemma inf_sdiff : (x ⊓ y) \ z = (x \ z) ⊓ (y \ z) :=
sdiff_unique
(calc (x ⊓ y) ⊓ z ⊔ ((x \ z) ⊓ (y \ z)) =
((x ⊓ y) ⊓ z ⊔ (x \ z)) ⊓ ((x ⊓ y) ⊓ z ⊔ (y \ z)) : by rw [sup_inf_left]
... = (x ⊓ y ⊓ (z ⊔ x) ⊔ x \ z) ⊓ (x ⊓ y ⊓ z ⊔ y \ z) :
by rw [sup_inf_right, sup_sdiff_self_right, inf_sup_right, inf_sdiff_sup_right]
... = (y ⊓ (x ⊓ (x ⊔ z)) ⊔ x \ z) ⊓ (x ⊓ y ⊓ z ⊔ y \ z) : by ac_refl
... = ((y ⊓ x) ⊔ (x \ z)) ⊓ ((x ⊓ y) ⊔ (y \ z)) : by rw [inf_sup_self, sup_inf_inf_sdiff]
... = (x ⊓ y) ⊔ ((x \ z) ⊓ (y \ z)) : by rw [@inf_comm _ _ y, sup_inf_left]
... = x ⊓ y : sup_eq_left.2 (inf_le_inf sdiff_le sdiff_le))
(calc (x ⊓ y) ⊓ z ⊓ ((x \ z) ⊓ (y \ z)) =
x ⊓ y ⊓ (z ⊓ (x \ z)) ⊓ (y \ z) : by ac_refl
... = ⊥ : by rw [inf_sdiff_self_right, inf_bot_eq, bot_inf_eq])
lemma inf_sdiff_assoc : (x ⊓ y) \ z = x ⊓ (y \ z) :=
sdiff_unique
(calc x ⊓ y ⊓ z ⊔ x ⊓ (y \ z) = x ⊓ (y ⊓ z) ⊔ x ⊓ (y \ z) : by rw inf_assoc
... = x ⊓ ((y ⊓ z) ⊔ y \ z) : inf_sup_left.symm
... = x ⊓ y : by rw sup_inf_sdiff)
(calc x ⊓ y ⊓ z ⊓ (x ⊓ (y \ z)) = x ⊓ x ⊓ ((y ⊓ z) ⊓ (y \ z)) : by ac_refl
... = ⊥ : by rw [inf_inf_sdiff, inf_bot_eq])
lemma sup_eq_sdiff_sup_sdiff_sup_inf : x ⊔ y = (x \ y) ⊔ (y \ x) ⊔ (x ⊓ y) :=
eq.symm $
calc (x \ y) ⊔ (y \ x) ⊔ (x ⊓ y) =
((x \ y) ⊔ (y \ x) ⊔ x) ⊓ ((x \ y) ⊔ (y \ x) ⊔ y) : by rw sup_inf_left
... = ((x \ y) ⊔ x ⊔ (y \ x)) ⊓ ((x \ y) ⊔ ((y \ x) ⊔ y)) : by ac_refl
... = (x ⊔ (y \ x)) ⊓ ((x \ y) ⊔ y) : by rw [sup_sdiff_right, sup_sdiff_right]
... = x ⊔ y : by rw [sup_sdiff_self_right, sup_sdiff_self_left, inf_idem]
instance pi.generalized_boolean_algebra {α : Type u} {β : Type v} [generalized_boolean_algebra β] :
generalized_boolean_algebra (α → β) :=
by pi_instance
end generalized_boolean_algebra
/-!
### Boolean algebras
-/
/-- Set / lattice complement -/
@[notation_class] class has_compl (α : Type*) := (compl : α → α)
export has_compl (compl)
postfix `ᶜ`:(max+1) := compl
/-- This class contains the core axioms of a Boolean algebra. The `boolean_algebra` class extends
both this class and `generalized_boolean_algebra`, see Note [forgetful inheritance]. -/
class boolean_algebra.core (α : Type u) extends bounded_distrib_lattice α, has_compl α :=
(inf_compl_le_bot : ∀x:α, x ⊓ xᶜ ≤ ⊥)
(top_le_sup_compl : ∀x:α, ⊤ ≤ x ⊔ xᶜ)
section boolean_algebra_core
variables [boolean_algebra.core α]
@[simp] theorem inf_compl_eq_bot : x ⊓ xᶜ = ⊥ :=
bot_unique $ boolean_algebra.core.inf_compl_le_bot x
@[simp] theorem compl_inf_eq_bot : xᶜ ⊓ x = ⊥ :=
eq.trans inf_comm inf_compl_eq_bot
@[simp] theorem sup_compl_eq_top : x ⊔ xᶜ = ⊤ :=
top_unique $ boolean_algebra.core.top_le_sup_compl x
@[simp] theorem compl_sup_eq_top : xᶜ ⊔ x = ⊤ :=
eq.trans sup_comm sup_compl_eq_top
theorem is_compl_compl : is_compl x xᶜ :=
is_compl.of_eq inf_compl_eq_bot sup_compl_eq_top
theorem is_compl.eq_compl (h : is_compl x y) : x = yᶜ :=
h.left_unique is_compl_compl.symm
theorem is_compl.compl_eq (h : is_compl x y) : xᶜ = y :=
(h.right_unique is_compl_compl).symm
theorem eq_compl_iff_is_compl : x = yᶜ ↔ is_compl x y :=
⟨λ h, by { rw h, exact is_compl_compl.symm }, is_compl.eq_compl⟩
theorem compl_eq_iff_is_compl : xᶜ = y ↔ is_compl x y :=
⟨λ h, by { rw ←h, exact is_compl_compl }, is_compl.compl_eq⟩
theorem disjoint_compl_right : disjoint x xᶜ := is_compl_compl.disjoint
theorem disjoint_compl_left : disjoint xᶜ x := disjoint_compl_right.symm
theorem compl_unique (i : x ⊓ y = ⊥) (s : x ⊔ y = ⊤) : xᶜ = y :=
(is_compl.of_eq i s).compl_eq
@[simp] theorem compl_top : ⊤ᶜ = (⊥:α) :=
is_compl_top_bot.compl_eq
@[simp] theorem compl_bot : ⊥ᶜ = (⊤:α) :=
is_compl_bot_top.compl_eq
@[simp] theorem compl_compl (x : α) : xᶜᶜ = x :=
is_compl_compl.symm.compl_eq
@[simp] theorem compl_involutive : function.involutive (compl : α → α) := compl_compl
theorem compl_bijective : function.bijective (compl : α → α) :=
compl_involutive.bijective
theorem compl_injective : function.injective (compl : α → α) :=
compl_involutive.injective
@[simp] theorem compl_inj_iff : xᶜ = yᶜ ↔ x = y :=
compl_injective.eq_iff
theorem is_compl.compl_eq_iff (h : is_compl x y) : zᶜ = y ↔ z = x :=
h.compl_eq ▸ compl_inj_iff
@[simp] theorem compl_eq_top : xᶜ = ⊤ ↔ x = ⊥ :=
is_compl_bot_top.compl_eq_iff
@[simp] theorem compl_eq_bot : xᶜ = ⊥ ↔ x = ⊤ :=
is_compl_top_bot.compl_eq_iff
@[simp] theorem compl_inf : (x ⊓ y)ᶜ = xᶜ ⊔ yᶜ :=
(is_compl_compl.inf_sup is_compl_compl).compl_eq
@[simp] theorem compl_sup : (x ⊔ y)ᶜ = xᶜ ⊓ yᶜ :=
(is_compl_compl.sup_inf is_compl_compl).compl_eq
theorem compl_le_compl (h : y ≤ x) : xᶜ ≤ yᶜ :=
is_compl_compl.antimono is_compl_compl h
@[simp] theorem compl_le_compl_iff_le : yᶜ ≤ xᶜ ↔ x ≤ y :=
⟨assume h, by have h := compl_le_compl h; simp at h; assumption,
compl_le_compl⟩
theorem le_compl_of_le_compl (h : y ≤ xᶜ) : x ≤ yᶜ :=
by simpa only [compl_compl] using compl_le_compl h
theorem compl_le_of_compl_le (h : yᶜ ≤ x) : xᶜ ≤ y :=
by simpa only [compl_compl] using compl_le_compl h
theorem le_compl_iff_le_compl : y ≤ xᶜ ↔ x ≤ yᶜ :=
⟨le_compl_of_le_compl, le_compl_of_le_compl⟩
theorem compl_le_iff_compl_le : xᶜ ≤ y ↔ yᶜ ≤ x :=
⟨compl_le_of_compl_le, compl_le_of_compl_le⟩
namespace boolean_algebra
@[priority 100]
instance : is_complemented α := ⟨λ x, ⟨xᶜ, is_compl_compl⟩⟩
end boolean_algebra
end boolean_algebra_core
/-- A Boolean algebra is a bounded distributive lattice with
a complement operator `ᶜ` such that `x ⊓ xᶜ = ⊥` and `x ⊔ xᶜ = ⊤`.
For convenience, it must also provide a set difference operation `\`
satisfying `x \ y = x ⊓ yᶜ`.
This is a generalization of (classical) logic of propositions, or
the powerset lattice. -/
-- Lean complains about metavariables in the type if the universe is not specified
class boolean_algebra (α : Type u) extends generalized_boolean_algebra α, boolean_algebra.core α :=
(sdiff_eq : ∀x y:α, x \ y = x ⊓ yᶜ)
-- TODO: is there a way to automatically fill in the proofs of sup_inf_sdiff and inf_inf_sdiff given
-- everything in `boolean_algebra.core` and `sdiff_eq`? The following doesn't work:
-- (sup_inf_sdiff := λ a b, by rw [sdiff_eq, ←inf_sup_left, sup_compl_eq_top, inf_top_eq])
/-- Create a `boolean_algebra` instance from a `boolean_algebra.core` instance, defining `x \ y` to
be `x ⊓ yᶜ`.
For some types, it may be more convenient to create the `boolean_algebra` instance by hand in order
to have a simpler `sdiff` operation. -/
def boolean_algebra.of_core (B : boolean_algebra.core α) :
boolean_algebra α :=
{ sdiff := λ x y, x ⊓ yᶜ,
sdiff_eq := λ _ _, rfl,
sup_inf_sdiff := λ a b, by rw [←inf_sup_left, sup_compl_eq_top, inf_top_eq],
inf_inf_sdiff := λ a b, by rw [inf_left_right_swap, @inf_assoc _ _ a, compl_inf_eq_bot,
inf_bot_eq, bot_inf_eq],
..B }
section boolean_algebra
variables [boolean_algebra α]
theorem sdiff_eq : x \ y = x ⊓ yᶜ := boolean_algebra.sdiff_eq x y
theorem sdiff_compl : x \ yᶜ = x ⊓ y := by rw [sdiff_eq, compl_compl]
theorem top_sdiff : ⊤ \ x = xᶜ := by rw [sdiff_eq, top_inf_eq]
@[simp] theorem sdiff_top : x \ ⊤ = ⊥ := by rw [sdiff_eq, compl_top, inf_bot_eq]
@[simp] lemma sup_inf_inf_compl : (x ⊓ y) ⊔ (x ⊓ yᶜ) = x :=
by rw [← sdiff_eq, sup_inf_sdiff _ _]
end boolean_algebra
instance Prop.boolean_algebra : boolean_algebra Prop :=
boolean_algebra.of_core
{ compl := not,
inf_compl_le_bot := λ p ⟨Hp, Hpc⟩, Hpc Hp,
top_le_sup_compl := λ p H, classical.em p,
.. Prop.bounded_distrib_lattice }
instance pi.boolean_algebra {ι : Type u} {α : ι → Type v} [∀ i, boolean_algebra (α i)] :
boolean_algebra (Π i, α i) :=
by refine_struct { sdiff := λ x y i, x i \ y i, compl := λ x i, (x i)ᶜ, .. pi.bounded_lattice };
tactic.pi_instance_derive_field
|
55c02da2f8247083f45993ebef1a94cb288f35d8 | d406927ab5617694ec9ea7001f101b7c9e3d9702 | /src/testing/slim_check/gen.lean | eff80477cdce2b9f2bdaede4488b112a69b35e9c | [
"Apache-2.0"
] | permissive | alreadydone/mathlib | dc0be621c6c8208c581f5170a8216c5ba6721927 | c982179ec21091d3e102d8a5d9f5fe06c8fafb73 | refs/heads/master | 1,685,523,275,196 | 1,670,184,141,000 | 1,670,184,141,000 | 287,574,545 | 0 | 0 | Apache-2.0 | 1,670,290,714,000 | 1,597,421,623,000 | Lean | UTF-8 | Lean | false | false | 5,709 | lean | /-
Copyright (c) 2020 Simon Hudon. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon
-/
import control.random
import control.uliftable
import data.list.big_operators.lemmas
import data.list.perm
/-!
# `gen` Monad
This monad is used to formulate randomized computations with a parameter
to specify the desired size of the result.
This is a port of the Haskell QuickCheck library.
## Main definitions
* `gen` monad
## Local notation
* `i .. j` : `Icc i j`, the set of values between `i` and `j` inclusively;
## Tags
random testing
## References
* https://hackage.haskell.org/package/QuickCheck
-/
universes u v
namespace slim_check
/-- Monad to generate random examples to test properties with.
It has a `nat` parameter so that the caller can decide on the
size of the examples. -/
@[reducible, derive [monad, is_lawful_monad]]
def gen (α : Type u) := reader_t (ulift ℕ) rand α
variable (α : Type u)
local infix ` .. `:41 := set.Icc
/-- Execute a `gen` inside the `io` monad using `i` as the example
size and with a fresh random number generator. -/
def io.run_gen {α} (x : gen α) (i : ℕ) : io α :=
io.run_rand (x.run ⟨i⟩)
namespace gen
section rand
/-- Lift `random.random` to the `gen` monad. -/
def choose_any [random α] : gen α :=
⟨ λ _, rand.random α ⟩
variables {α} [preorder α]
/-- Lift `random.random_r` to the `gen` monad. -/
def choose [bounded_random α] (x y : α) (p : x ≤ y) : gen (x .. y) :=
⟨ λ _, rand.random_r x y p ⟩
end rand
open nat
/-- Generate a `nat` example between `x` and `y`. -/
def choose_nat (x y : ℕ) (p : x ≤ y) : gen (x .. y) :=
choose x y p
/-- Generate a `nat` example between `x` and `y`. -/
def choose_nat' (x y : ℕ) (p : x < y) : gen (set.Ico x y) :=
have ∀ i, x < i → i ≤ y → i.pred < y,
from λ i h₀ h₁,
show i.pred.succ ≤ y,
by rwa succ_pred_eq_of_pos; apply lt_of_le_of_lt (nat.zero_le _) h₀,
subtype.map pred (λ i (h : x+1 ≤ i ∧ i ≤ y), ⟨le_pred_of_lt h.1, this _ h.1 h.2⟩) <$>
choose (x+1) y p
open nat
instance : uliftable gen.{u} gen.{v} :=
reader_t.uliftable' (equiv.ulift.trans equiv.ulift.symm)
instance : has_orelse gen.{u} :=
⟨ λ α x y, do
b ← uliftable.up $ choose_any bool,
if b.down then x else y ⟩
variable {α}
/-- Get access to the size parameter of the `gen` monad. For
reasons of universe polymorphism, it is specified in
continuation passing style. -/
def sized (cmd : ℕ → gen α) : gen α :=
⟨ λ ⟨sz⟩, reader_t.run (cmd sz) ⟨sz⟩ ⟩
/-- Apply a function to the size parameter. -/
def resize (f : ℕ → ℕ) (cmd : gen α) : gen α :=
⟨ λ ⟨sz⟩, reader_t.run cmd ⟨f sz⟩ ⟩
/-- Create `n` examples using `cmd`. -/
def vector_of : ∀ (n : ℕ) (cmd : gen α), gen (vector α n)
| 0 _ := return vector.nil
| (succ n) cmd := vector.cons <$> cmd <*> vector_of n cmd
/-- Create a list of examples using `cmd`. The size is controlled
by the size parameter of `gen`. -/
def list_of (cmd : gen α) : gen (list α) :=
sized $ λ sz, do
do ⟨ n ⟩ ← uliftable.up $ choose_nat 0 (sz + 1) dec_trivial,
v ← vector_of n.val cmd,
return v.to_list
open ulift
/-- Given a list of example generators, choose one to create an example. -/
def one_of (xs : list (gen α)) (pos : 0 < xs.length) : gen α := do
⟨⟨n, h, h'⟩⟩ ← uliftable.up $ choose_nat' 0 xs.length pos,
list.nth_le xs n h'
/-- Given a list of example generators, choose one to create an example. -/
def elements (xs : list α) (pos : 0 < xs.length) : gen α := do
⟨⟨n,h₀,h₁⟩⟩ ← uliftable.up $ choose_nat' 0 xs.length pos,
pure $ list.nth_le xs n h₁
/--
`freq_aux xs i _` takes a weighted list of generator and a number meant to select one of the
generators.
If we consider `freq_aux [(1, gena), (3, genb), (5, genc)] 4 _`, we choose a generator by splitting
the interval 1-9 into 1-1, 2-4, 5-9 so that the width of each interval corresponds to one of the
number in the list of generators. Then, we check which interval 4 falls into: it selects `genb`.
-/
def freq_aux : Π (xs : list (ℕ+ × gen α)) i, i < (xs.map (subtype.val ∘ prod.fst)).sum → gen α
| [] i h := false.elim (nat.not_lt_zero _ h)
| ((i, x) :: xs) j h :=
if h' : j < i then x
else freq_aux xs (j - i)
(by { rw tsub_lt_iff_right (le_of_not_gt h'),
simpa [list.sum_cons, add_comm] using h })
/--
`freq [(1, gena), (3, genb), (5, genc)] _` will choose one of `gena`, `genb`, `genc` with
probabilities proportional to the number accompanying them. In this example, the sum of
those numbers is 9, `gena` will be chosen with probability ~1/9, `genb` with ~3/9 (i.e. 1/3)
and `genc` with probability 5/9.
-/
def freq (xs : list (ℕ+ × gen α)) (pos : 0 < xs.length) : gen α :=
let s := (xs.map (subtype.val ∘ prod.fst)).sum in
have ha : 1 ≤ s, from
(le_trans pos $
list.length_map (subtype.val ∘ prod.fst) xs ▸
(list.length_le_sum_of_one_le _ (λ i, by { simp, intros, assumption }))),
have 0 ≤ s - 1, from le_tsub_of_add_le_right ha,
uliftable.adapt_up gen.{0} gen.{u} (choose_nat 0 (s-1) this) $ λ i,
freq_aux xs i.1 (by rcases i with ⟨i,h₀,h₁⟩; rwa le_tsub_iff_right at h₁; exact ha)
/-- Generate a random permutation of a given list. -/
def permutation_of {α : Type u} : Π xs : list α, gen (subtype $ list.perm xs)
| [] := pure ⟨[], list.perm.nil ⟩
| (x :: xs) := do
⟨xs',h⟩ ← permutation_of xs,
⟨⟨n,_,h'⟩⟩ ← uliftable.up $ choose_nat 0 xs'.length dec_trivial,
pure ⟨list.insert_nth n x xs',
list.perm.trans (list.perm.cons _ h)
(list.perm_insert_nth _ _ h').symm ⟩
end gen
end slim_check
|
d77bd76a309839b9870e9a508ea74acd8d4e6487 | 7565ffb53cc64430691ce89265da0f944ee43051 | /hott/homotopy/susp.hlean | 5f25b41688cea6f1e1d25f3703c5b840fcd78e46 | [
"Apache-2.0"
] | permissive | EgbertRijke/lean2 | cacddba3d150f8b38688e044960a208bf851f90e | 519dcee739fbca5a4ab77d66db7652097b4604cd | refs/heads/master | 1,606,936,954,854 | 1,498,836,083,000 | 1,498,910,882,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 16,313 | hlean | /-
Copyright (c) 2015 Floris van Doorn. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Floris van Doorn, Ulrik Buchholtz
Declaration of suspension
-/
import hit.pushout types.pointed2 cubical.square .connectedness
open pushout unit eq equiv
definition susp (A : Type) : Type := pushout (λ(a : A), star) (λ(a : A), star)
namespace susp
variable {A : Type}
definition north {A : Type} : susp A :=
inl star
definition south {A : Type} : susp A :=
inr star
definition merid (a : A) : @north A = @south A :=
glue a
protected definition rec {P : susp A → Type} (PN : P north) (PS : P south)
(Pm : Π(a : A), PN =[merid a] PS) (x : susp A) : P x :=
begin
induction x with u u,
{ cases u, exact PN},
{ cases u, exact PS},
{ apply Pm},
end
protected definition rec_on [reducible] {P : susp A → Type} (y : susp A)
(PN : P north) (PS : P south) (Pm : Π(a : A), PN =[merid a] PS) : P y :=
susp.rec PN PS Pm y
theorem rec_merid {P : susp A → Type} (PN : P north) (PS : P south)
(Pm : Π(a : A), PN =[merid a] PS) (a : A)
: apd (susp.rec PN PS Pm) (merid a) = Pm a :=
!rec_glue
protected definition elim {P : Type} (PN : P) (PS : P) (Pm : A → PN = PS)
(x : susp A) : P :=
susp.rec PN PS (λa, pathover_of_eq _ (Pm a)) x
protected definition elim_on [reducible] {P : Type} (x : susp A)
(PN : P) (PS : P) (Pm : A → PN = PS) : P :=
susp.elim PN PS Pm x
theorem elim_merid {P : Type} {PN PS : P} (Pm : A → PN = PS) (a : A)
: ap (susp.elim PN PS Pm) (merid a) = Pm a :=
begin
apply eq_of_fn_eq_fn_inv !(pathover_constant (merid a)),
rewrite [▸*,-apd_eq_pathover_of_eq_ap,↑susp.elim,rec_merid],
end
protected definition elim_type (PN : Type) (PS : Type) (Pm : A → PN ≃ PS)
(x : susp A) : Type :=
pushout.elim_type (λx, PN) (λx, PS) Pm x
protected definition elim_type_on [reducible] (x : susp A)
(PN : Type) (PS : Type) (Pm : A → PN ≃ PS) : Type :=
susp.elim_type PN PS Pm x
theorem elim_type_merid (PN : Type) (PS : Type) (Pm : A → PN ≃ PS)
(a : A) : transport (susp.elim_type PN PS Pm) (merid a) = Pm a :=
!elim_type_glue
theorem elim_type_merid_inv {A : Type} (PN : Type) (PS : Type) (Pm : A → PN ≃ PS)
(a : A) : transport (susp.elim_type PN PS Pm) (merid a)⁻¹ = to_inv (Pm a) :=
!elim_type_glue_inv
protected definition merid_square {a a' : A} (p : a = a')
: square (merid a) (merid a') idp idp :=
by cases p; apply vrefl
end susp
attribute susp.north susp.south [constructor]
attribute susp.rec susp.elim [unfold 6] [recursor 6]
attribute susp.elim_type [unfold 5]
attribute susp.rec_on susp.elim_on [unfold 3]
attribute susp.elim_type_on [unfold 2]
namespace susp
open is_trunc is_conn trunc
-- Theorem 8.2.1
definition is_conn_susp [instance] (n : trunc_index) (A : Type)
[H : is_conn n A] : is_conn (n .+1) (susp A) :=
is_contr.mk (tr north)
begin
apply trunc.rec,
fapply susp.rec,
{ reflexivity },
{ exact (trunc.rec (λa, ap tr (merid a)) (center (trunc n A))) },
{ intro a,
generalize (center (trunc n A)),
apply trunc.rec,
intro a',
apply pathover_of_tr_eq,
rewrite [eq_transport_Fr,idp_con],
revert H, induction n with [n, IH],
{ intro H, apply is_prop.elim },
{ intros H,
change ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid a'),
generalize a',
apply is_conn_fun.elim n
(is_conn_fun_from_unit n A a)
(λx : A, trunctype.mk' n (ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid x))),
intros,
change ap (@tr n .+2 (susp A)) (merid a) = ap tr (merid a),
reflexivity
}
}
end
/- Flattening lemma -/
open prod prod.ops
section
universe variable u
parameters (A : Type) (PN PS : Type.{u}) (Pm : A → PN ≃ PS)
include Pm
local abbreviation P [unfold 5] := susp.elim_type PN PS Pm
local abbreviation F : A × PN → PN := λz, z.2
local abbreviation G : A × PN → PS := λz, Pm z.1 z.2
protected definition flattening : sigma P ≃ pushout F G :=
begin
apply equiv.trans !pushout.flattening,
fapply pushout.equiv,
{ exact sigma.equiv_prod A PN },
{ apply sigma.sigma_unit_left },
{ apply sigma.sigma_unit_left },
{ reflexivity },
{ reflexivity }
end
end
end susp
/- Functoriality and equivalence -/
namespace susp
variables {A B : Type} (f : A → B)
include f
protected definition functor [unfold 4] : susp A → susp B :=
begin
intro x, induction x with a,
{ exact north },
{ exact south },
{ exact merid (f a) }
end
variable [Hf : is_equiv f]
include Hf
open is_equiv
protected definition is_equiv_functor [instance] [constructor] : is_equiv (susp.functor f) :=
adjointify (susp.functor f) (susp.functor f⁻¹)
abstract begin
intro sb, induction sb with b, do 2 reflexivity,
apply eq_pathover,
rewrite [ap_id,ap_compose' (susp.functor f) (susp.functor f⁻¹)],
krewrite [susp.elim_merid,susp.elim_merid], apply transpose,
apply susp.merid_square (right_inv f b)
end end
abstract begin
intro sa, induction sa with a, do 2 reflexivity,
apply eq_pathover,
rewrite [ap_id,ap_compose' (susp.functor f⁻¹) (susp.functor f)],
krewrite [susp.elim_merid,susp.elim_merid], apply transpose,
apply susp.merid_square (left_inv f a)
end end
end susp
namespace susp
variables {A B : Type} (f : A ≃ B)
protected definition equiv : susp A ≃ susp B :=
equiv.mk (susp.functor f) _
end susp
namespace susp
open pointed
definition pointed_susp [instance] [constructor] (X : Type)
: pointed (susp X) :=
pointed.mk north
end susp
open susp
definition psusp [constructor] (X : Type) : Type* :=
pointed.mk' (susp X)
notation `⅀` := psusp
namespace susp
open pointed is_trunc
variables {X Y Z : Type*}
definition is_conn_psusp [instance] (n : trunc_index) (A : Type*)
[H : is_conn n A] : is_conn (n .+1) (psusp A) :=
is_conn_susp n A
definition psusp_functor [constructor] (f : X →* Y) : psusp X →* psusp Y :=
begin
fconstructor,
{ exact susp.functor f },
{ reflexivity }
end
definition is_equiv_psusp_functor [constructor] (f : X →* Y) [Hf : is_equiv f]
: is_equiv (psusp_functor f) :=
susp.is_equiv_functor f
definition psusp_pequiv [constructor] (f : X ≃* Y) : psusp X ≃* psusp Y :=
pequiv_of_equiv (susp.equiv f) idp
definition psusp_functor_pcompose (g : Y →* Z) (f : X →* Y) :
psusp_functor (g ∘* f) ~* psusp_functor g ∘* psusp_functor f :=
begin
fapply phomotopy.mk,
{ intro x, induction x,
{ reflexivity },
{ reflexivity },
{ apply eq_pathover, apply hdeg_square, esimp,
refine !elim_merid ⬝ _ ⬝ (ap_compose (psusp_functor g) _ _)⁻¹ᵖ,
refine _ ⬝ ap02 _ !elim_merid⁻¹, exact !elim_merid⁻¹ }},
{ reflexivity },
end
definition psusp_functor_phomotopy {f g : X →* Y} (p : f ~* g) :
psusp_functor f ~* psusp_functor g :=
begin
fapply phomotopy.mk,
{ intro x, induction x,
{ reflexivity },
{ reflexivity },
{ apply eq_pathover, apply hdeg_square, esimp, refine !elim_merid ⬝ _ ⬝ !elim_merid⁻¹ᵖ,
exact ap merid (p a), }},
{ reflexivity },
end
definition psusp_functor_pid (A : Type*) : psusp_functor (pid A) ~* pid (psusp A) :=
begin
fapply phomotopy.mk,
{ intro x, induction x,
{ reflexivity },
{ reflexivity },
{ apply eq_pathover_id_right, apply hdeg_square, apply elim_merid }},
{ reflexivity },
end
/- adjunction originally ported from Coq-HoTT,
but we proved some additional naturality conditions -/
definition loop_psusp_unit [constructor] (X : Type*) : X →* Ω(psusp X) :=
begin
fconstructor,
{ intro x, exact merid x ⬝ (merid pt)⁻¹ },
{ apply con.right_inv },
end
definition loop_psusp_unit_natural (f : X →* Y)
: loop_psusp_unit Y ∘* f ~* Ω→ (psusp_functor f) ∘* loop_psusp_unit X :=
begin
induction X with X x, induction Y with Y y, induction f with f pf, esimp at *, induction pf,
fapply phomotopy.mk,
{ intro x', symmetry,
exact
!ap1_gen_idp_left ⬝
(!ap_con ⬝
whisker_left _ !ap_inv) ⬝
(!elim_merid ◾ (inverse2 !elim_merid)) },
{ rewrite [▸*, idp_con (con.right_inv _)],
apply inv_con_eq_of_eq_con,
refine _ ⬝ !con.assoc',
rewrite inverse2_right_inv,
refine _ ⬝ !con.assoc',
rewrite [ap_con_right_inv],
rewrite [ap1_gen_idp_left_con],
rewrite [-ap_compose (concat idp)] },
end
definition loop_psusp_counit [constructor] (X : Type*) : psusp (Ω X) →* X :=
begin
fconstructor,
{ intro x, induction x, exact pt, exact pt, exact a },
{ reflexivity },
end
definition loop_psusp_counit_natural (f : X →* Y)
: f ∘* loop_psusp_counit X ~* loop_psusp_counit Y ∘* (psusp_functor (ap1 f)) :=
begin
induction X with X x, induction Y with Y y, induction f with f pf, esimp at *, induction pf,
fconstructor,
{ intro x', induction x' with p,
{ reflexivity },
{ reflexivity },
{ esimp, apply eq_pathover, apply hdeg_square,
xrewrite [ap_compose' f, ap_compose' (susp.elim (f x) (f x) (λ (a : f x = f x), a)),▸*],
xrewrite [+elim_merid, ap1_gen_idp_left] }},
{ reflexivity }
end
definition loop_psusp_counit_unit (X : Type*)
: ap1 (loop_psusp_counit X) ∘* loop_psusp_unit (Ω X) ~* pid (Ω X) :=
begin
induction X with X x, fconstructor,
{ intro p, esimp,
refine !ap1_gen_idp_left ⬝
(!ap_con ⬝
whisker_left _ !ap_inv) ⬝
(!elim_merid ◾ inverse2 !elim_merid) },
{ rewrite [▸*,inverse2_right_inv (elim_merid id idp)],
refine !con.assoc ⬝ _,
xrewrite [ap_con_right_inv (susp.elim x x (λa, a)) (merid idp),ap1_gen_idp_left_con,
-ap_compose] }
end
definition loop_psusp_unit_counit (X : Type*)
: loop_psusp_counit (psusp X) ∘* psusp_functor (loop_psusp_unit X) ~* pid (psusp X) :=
begin
induction X with X x, fconstructor,
{ intro x', induction x',
{ reflexivity },
{ exact merid pt },
{ apply eq_pathover,
xrewrite [▸*, ap_id, ap_compose' (susp.elim north north (λa, a)), +elim_merid,▸*],
apply square_of_eq, exact !idp_con ⬝ !inv_con_cancel_right⁻¹ }},
{ reflexivity }
end
definition psusp.elim [constructor] {X Y : Type*} (f : X →* Ω Y) : psusp X →* Y :=
loop_psusp_counit Y ∘* psusp_functor f
definition loop_psusp_intro [constructor] {X Y : Type*} (f : psusp X →* Y) : X →* Ω Y :=
ap1 f ∘* loop_psusp_unit X
definition psusp_elim_psusp_functor {A B C : Type*} (g : B →* Ω C) (f : A →* B) :
psusp.elim g ∘* psusp_functor f ~* psusp.elim (g ∘* f) :=
begin
refine !passoc ⬝* _, exact pwhisker_left _ !psusp_functor_pcompose⁻¹*
end
definition psusp_elim_phomotopy {A B : Type*} {f g : A →* Ω B} (p : f ~* g) : psusp.elim f ~* psusp.elim g :=
pwhisker_left _ (psusp_functor_phomotopy p)
definition psusp_elim_natural {X Y Z : Type*} (g : Y →* Z) (f : X →* Ω Y)
: g ∘* psusp.elim f ~* psusp.elim (Ω→ g ∘* f) :=
begin
refine _ ⬝* pwhisker_left _ !psusp_functor_pcompose⁻¹*,
refine !passoc⁻¹* ⬝* _ ⬝* !passoc,
exact pwhisker_right _ !loop_psusp_counit_natural
end
definition loop_psusp_intro_natural {X Y Z : Type*} (g : psusp Y →* Z) (f : X →* Y) :
loop_psusp_intro (g ∘* psusp_functor f) ~* loop_psusp_intro g ∘* f :=
pwhisker_right _ !ap1_pcompose ⬝* !passoc ⬝* pwhisker_left _ !loop_psusp_unit_natural⁻¹* ⬝*
!passoc⁻¹*
definition psusp_adjoint_loop_right_inv {X Y : Type*} (g : X →* Ω Y) :
loop_psusp_intro (psusp.elim g) ~* g :=
begin
refine !pwhisker_right !ap1_pcompose ⬝* _,
refine !passoc ⬝* _,
refine !pwhisker_left !loop_psusp_unit_natural⁻¹* ⬝* _,
refine !passoc⁻¹* ⬝* _,
refine !pwhisker_right !loop_psusp_counit_unit ⬝* _,
apply pid_pcompose
end
definition psusp_adjoint_loop_left_inv {X Y : Type*} (f : psusp X →* Y) :
psusp.elim (loop_psusp_intro f) ~* f :=
begin
refine !pwhisker_left !psusp_functor_pcompose ⬝* _,
refine !passoc⁻¹* ⬝* _,
refine !pwhisker_right !loop_psusp_counit_natural⁻¹* ⬝* _,
refine !passoc ⬝* _,
refine !pwhisker_left !loop_psusp_unit_counit ⬝* _,
apply pcompose_pid
end
definition psusp_adjoint_loop_unpointed [constructor] (X Y : Type*) : psusp X →* Y ≃ X →* Ω Y :=
begin
fapply equiv.MK,
{ exact loop_psusp_intro },
{ exact psusp.elim },
{ intro g, apply eq_of_phomotopy, exact psusp_adjoint_loop_right_inv g },
{ intro f, apply eq_of_phomotopy, exact psusp_adjoint_loop_left_inv f }
end
definition psusp_adjoint_loop_pconst (X Y : Type*) :
psusp_adjoint_loop_unpointed X Y (pconst (psusp X) Y) ~* pconst X (Ω Y) :=
begin
refine pwhisker_right _ !ap1_pconst ⬝* _,
apply pconst_pcompose
end
definition psusp_adjoint_loop [constructor] (X Y : Type*) : ppmap (psusp X) Y ≃* ppmap X (Ω Y) :=
begin
apply pequiv_of_equiv (psusp_adjoint_loop_unpointed X Y),
apply eq_of_phomotopy,
apply psusp_adjoint_loop_pconst
end
definition ap1_psusp_elim {A : Type*} {X : Type*} (p : A →* Ω X) :
Ω→(psusp.elim p) ∘* loop_psusp_unit A ~* p :=
psusp_adjoint_loop_right_inv p
definition psusp_adjoint_loop_nat_right (f : psusp X →* Y) (g : Y →* Z)
: psusp_adjoint_loop X Z (g ∘* f) ~* ap1 g ∘* psusp_adjoint_loop X Y f :=
begin
esimp [psusp_adjoint_loop],
refine _ ⬝* !passoc,
apply pwhisker_right,
apply ap1_pcompose
end
definition psusp_adjoint_loop_nat_left (f : Y →* Ω Z) (g : X →* Y)
: (psusp_adjoint_loop X Z)⁻¹ᵉ (f ∘* g) ~* (psusp_adjoint_loop Y Z)⁻¹ᵉ f ∘* psusp_functor g :=
begin
esimp [psusp_adjoint_loop],
refine _ ⬝* !passoc⁻¹*,
apply pwhisker_left,
apply psusp_functor_pcompose
end
/- iterated suspension -/
definition iterate_susp (n : ℕ) (A : Type) : Type := iterate susp n A
definition iterate_psusp (n : ℕ) (A : Type*) : Type* := iterate (λX, psusp X) n A
open is_conn trunc_index nat
definition iterate_susp_succ (n : ℕ) (A : Type) :
iterate_susp (succ n) A = susp (iterate_susp n A) :=
idp
definition is_conn_iterate_susp [instance] (n : ℕ₋₂) (m : ℕ) (A : Type)
[H : is_conn n A] : is_conn (n + m) (iterate_susp m A) :=
begin induction m with m IH, exact H, exact @is_conn_susp _ _ IH end
definition is_conn_iterate_psusp [instance] (n : ℕ₋₂) (m : ℕ) (A : Type*)
[H : is_conn n A] : is_conn (n + m) (iterate_psusp m A) :=
begin induction m with m IH, exact H, exact @is_conn_susp _ _ IH end
-- Separate cases for n = 0, which comes up often
definition is_conn_iterate_susp_zero [instance] (m : ℕ) (A : Type)
[H : is_conn 0 A] : is_conn m (iterate_susp m A) :=
begin induction m with m IH, exact H, exact @is_conn_susp _ _ IH end
definition is_conn_iterate_psusp_zero [instance] (m : ℕ) (A : Type*)
[H : is_conn 0 A] : is_conn m (iterate_psusp m A) :=
begin induction m with m IH, exact H, exact @is_conn_susp _ _ IH end
definition iterate_psusp_functor (n : ℕ) {A B : Type*} (f : A →* B) :
iterate_psusp n A →* iterate_psusp n B :=
begin
induction n with n g,
{ exact f },
{ exact psusp_functor g }
end
definition iterate_psusp_succ_in (n : ℕ) (A : Type*) :
iterate_psusp (succ n) A ≃* iterate_psusp n (psusp A) :=
begin
induction n with n IH,
{ reflexivity},
{ exact psusp_pequiv IH}
end
definition iterate_psusp_adjoint_loopn [constructor] (X Y : Type*) (n : ℕ) :
ppmap (iterate_psusp n X) Y ≃* ppmap X (Ω[n] Y) :=
begin
revert X Y, induction n with n IH: intro X Y,
{ reflexivity },
{ refine !psusp_adjoint_loop ⬝e* !IH ⬝e* _, apply pequiv_ppcompose_left,
symmetry, apply loopn_succ_in }
end
end susp
|
a296d4ea98298cd3a1f88be9b5330709f373dbd9 | 35677d2df3f081738fa6b08138e03ee36bc33cad | /src/algebra/pointwise.lean | ebb9d1951619655ee8e2802ec1f4f9ed3b75d332 | [
"Apache-2.0"
] | permissive | gebner/mathlib | eab0150cc4f79ec45d2016a8c21750244a2e7ff0 | cc6a6edc397c55118df62831e23bfbd6e6c6b4ab | refs/heads/master | 1,625,574,853,976 | 1,586,712,827,000 | 1,586,712,827,000 | 99,101,412 | 1 | 0 | Apache-2.0 | 1,586,716,389,000 | 1,501,667,958,000 | Lean | UTF-8 | Lean | false | false | 12,401 | lean | /-
Copyright (c) 2019 Johan Commelin. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin
-/
import data.set.finite data.set.lattice group_theory.group_action algebra.module
/-!
# Pointwise addition, multiplication, and scalar multiplication of sets.
This file defines `pointwise_mul`: for a type `α` with multiplication,
multiplication is defined on `set α` by taking `s * t` to be the set
of all `x * y` where `x ∈ s` and `y ∈ t`.
Pointwise multiplication on `set α` where `α` is a semigroup makes
`set α` into a semigroup. If `α` is additionally a (commutative)
monoid, `set α` becomes a (commutative) semiring with union as
addition. These are given by `pointwise_mul_semigroup` and
`pointwise_mul_semiring`.
Definitions and results are also transported to the additive theory
via `to_additive`.
For a type `β` with scalar multiplication by another type `α`, this
file defines `pointwise_smul`. Separately it defines `smul_set`, for
scalar multiplication of `set β` by a single term of type `α`.
## Implementation notes
Elsewhere, one should register local instances to use the definitions
in this file.
-/
namespace set
open function
variables {α : Type*} {β : Type*} (f : α → β)
@[to_additive]
def pointwise_one [has_one α] : has_one (set α) := ⟨{1}⟩
local attribute [instance] pointwise_one
@[simp, to_additive]
lemma mem_pointwise_one [has_one α] (a : α) :
a ∈ (1 : set α) ↔ a = 1 :=
mem_singleton_iff
@[to_additive]
def pointwise_mul [has_mul α] : has_mul (set α) :=
⟨λ s t, {a | ∃ x ∈ s, ∃ y ∈ t, a = x * y}⟩
local attribute [instance] pointwise_one pointwise_mul pointwise_add
@[to_additive]
lemma mem_pointwise_mul [has_mul α] {s t : set α} {a : α} :
a ∈ s * t ↔ ∃ x ∈ s, ∃ y ∈ t, a = x * y := iff.rfl
@[to_additive]
lemma mul_mem_pointwise_mul [has_mul α] {s t : set α} {a b : α} (ha : a ∈ s) (hb : b ∈ t) :
a * b ∈ s * t := ⟨_, ha, _, hb, rfl⟩
@[to_additive]
lemma pointwise_mul_eq_image [has_mul α] {s t : set α} :
s * t = (λ x : α × α, x.fst * x.snd) '' s.prod t :=
set.ext $ λ a,
⟨ by { rintros ⟨_, _, _, _, rfl⟩, exact ⟨(_, _), mem_prod.mpr ⟨‹_›, ‹_›⟩, rfl⟩ },
by { rintros ⟨_, _, rfl⟩, exact ⟨_, (mem_prod.mp ‹_›).1, _, (mem_prod.mp ‹_›).2, rfl⟩ }⟩
@[to_additive]
lemma pointwise_mul_finite [has_mul α] {s t : set α} (hs : finite s) (ht : finite t) :
finite (s * t) :=
by { rw pointwise_mul_eq_image, apply set.finite_image, exact set.finite_prod hs ht }
@[to_additive pointwise_add_add_semigroup]
def pointwise_mul_semigroup [semigroup α] : semigroup (set α) :=
{ mul_assoc := λ _ _ _, set.ext $ λ _,
begin
split,
{ rintros ⟨_, ⟨_, _, _, _, rfl⟩, _, _, rfl⟩,
exact ⟨_, ‹_›, _, ⟨_, ‹_›, _, ‹_›, rfl⟩, mul_assoc _ _ _⟩ },
{ rintros ⟨_, _, _, ⟨_, _, _, _, rfl⟩, rfl⟩,
exact ⟨_, ⟨_, ‹_›, _, ‹_›, rfl⟩, _, ‹_›, (mul_assoc _ _ _).symm⟩ }
end,
..pointwise_mul }
@[to_additive pointwise_add_add_monoid]
def pointwise_mul_monoid [monoid α] : monoid (set α) :=
{ one_mul := λ s, set.ext $ λ a,
⟨by {rintros ⟨_, _, _, _, rfl⟩, simp * at *},
λ h, ⟨1, mem_singleton 1, a, h, (one_mul a).symm⟩⟩,
mul_one := λ s, set.ext $ λ a,
⟨by {rintros ⟨_, _, _, _, rfl⟩, simp * at *},
λ h, ⟨a, h, 1, mem_singleton 1, (mul_one a).symm⟩⟩,
..pointwise_mul_semigroup,
..pointwise_one }
local attribute [instance] pointwise_mul_monoid
@[to_additive]
lemma singleton.is_mul_hom [has_mul α] : is_mul_hom (singleton : α → set α) :=
{ map_mul := λ x y, set.ext $ λ a, by simp [mem_singleton_iff, mem_pointwise_mul] }
@[to_additive is_add_monoid_hom]
lemma singleton.is_monoid_hom [monoid α] : is_monoid_hom (singleton : α → set α) :=
{ map_one := rfl, ..singleton.is_mul_hom }
@[to_additive]
def pointwise_inv [has_inv α] : has_inv (set α) :=
⟨λ s, {a | a⁻¹ ∈ s}⟩
@[simp, to_additive]
lemma pointwise_mul_empty [has_mul α] (s : set α) :
s * ∅ = ∅ :=
set.ext $ λ a, ⟨by {rintros ⟨_, _, _, _, rfl⟩, tauto}, false.elim⟩
@[simp, to_additive]
lemma empty_pointwise_mul [has_mul α] (s : set α) :
∅ * s = ∅ :=
set.ext $ λ a, ⟨by {rintros ⟨_, _, _, _, rfl⟩, tauto}, false.elim⟩
@[to_additive]
lemma pointwise_mul_subset_mul [has_mul α] {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) :
s₁ * s₂ ⊆ t₁ * t₂ :=
by {rintros _ ⟨_, _, _, _, rfl⟩, exact ⟨_, h₁ ‹_›, _, h₂ ‹_›, rfl⟩ }
@[to_additive]
lemma pointwise_mul_union [has_mul α] (s t u : set α) :
s * (t ∪ u) = (s * t) ∪ (s * u) :=
begin
ext a, split,
{ rintros ⟨_, _, _, H, rfl⟩,
cases H; [left, right]; exact ⟨_, ‹_›, _, ‹_›, rfl⟩ },
{ intro H,
cases H with H H;
{ rcases H with ⟨_, _, _, _, rfl⟩,
refine ⟨_, ‹_›, _, _, rfl⟩,
erw mem_union,
simp * } }
end
@[to_additive]
lemma union_pointwise_mul [has_mul α] (s t u : set α) :
(s ∪ t) * u = (s * u) ∪ (t * u) :=
begin
ext a, split,
{ rintros ⟨_, H, _, _, rfl⟩,
cases H; [left, right]; exact ⟨_, ‹_›, _, ‹_›, rfl⟩ },
{ intro H,
cases H with H H;
{ rcases H with ⟨_, _, _, _, rfl⟩;
refine ⟨_, _, _, ‹_›, rfl⟩;
erw mem_union;
simp * } }
end
@[to_additive]
lemma pointwise_mul_eq_Union_mul_left [has_mul α] {s t : set α} : s * t = ⋃a∈s, (λx, a * x) '' t :=
by { ext y; split; simp only [mem_Union]; rintros ⟨a, ha, x, hx, ax⟩; exact ⟨a, ha, x, hx, ax.symm⟩ }
@[to_additive]
lemma pointwise_mul_eq_Union_mul_right [has_mul α] {s t : set α} : s * t = ⋃a∈t, (λx, x * a) '' s :=
by { ext y; split; simp only [mem_Union]; rintros ⟨a, ha, x, hx, ax⟩; exact ⟨x, hx, a, ha, ax.symm⟩ }
@[to_additive]
lemma nonempty.pointwise_mul [has_mul α] {s t : set α} : s.nonempty → t.nonempty → (s * t).nonempty
| ⟨x, hx⟩ ⟨y, hy⟩ := ⟨x * y, ⟨x, hx, y, hy, rfl⟩⟩
@[simp, to_additive]
lemma univ_pointwise_mul_univ [monoid α] : (univ : set α) * univ = univ :=
begin
have : ∀x, ∃a b : α, x = a * b := λx, ⟨x, ⟨1, (mul_one x).symm⟩⟩,
show {a | ∃ x ∈ univ, ∃ y ∈ univ, a = x * y} = univ,
simpa [eq_univ_iff_forall]
end
def pointwise_mul_fintype [has_mul α] [decidable_eq α] (s t : set α) [hs : fintype s] [ht : fintype t] :
fintype (s * t : set α) := by { rw pointwise_mul_eq_image, apply set.fintype_image }
def pointwise_add_fintype [has_add α] [decidable_eq α] (s t : set α) [hs : fintype s] [ht : fintype t] :
fintype (s + t : set α) := by { rw pointwise_add_eq_image, apply set.fintype_image }
attribute [to_additive] set.pointwise_mul_fintype
/-- Pointwise scalar multiplication by a set of scalars. -/
def pointwise_smul [has_scalar α β] : has_scalar (set α) (set β) :=
⟨λ s t, { x | ∃ a ∈ s, ∃ y ∈ t, x = a • y }⟩
/-- Scaling a set: multiplying every element by a scalar. -/
def smul_set [has_scalar α β] : has_scalar α (set β) :=
⟨λ a s, { x | ∃ y ∈ s, x = a • y }⟩
local attribute [instance] pointwise_smul smul_set
lemma mem_smul_set [has_scalar α β] (a : α) (s : set β) (x : β) :
x ∈ a • s ↔ ∃ y ∈ s, x = a • y := iff.rfl
lemma smul_set_eq_image [has_scalar α β] (a : α) (s : set β) :
a • s = (λ x, a • x) '' s :=
set.ext $ λ x, iff.intro
(λ ⟨_, hy₁, hy₂⟩, ⟨_, hy₁, hy₂.symm⟩)
(λ ⟨_, hy₁, hy₂⟩, ⟨_, hy₁, hy₂.symm⟩)
lemma smul_set_eq_pointwise_smul_singleton [has_scalar α β]
(a : α) (s : set β) : a • s = ({a} : set α) • s :=
set.ext $ λ x, iff.intro
(λ ⟨_, h⟩, ⟨a, mem_singleton _, _, h⟩)
(λ ⟨_, h, y, hy, hx⟩, ⟨_, hy, by {
rw mem_singleton_iff at h; rwa h at hx }⟩)
lemma smul_mem_smul_set [has_scalar α β]
(a : α) {s : set β} {y : β} (hy : y ∈ s) : a • y ∈ a • s :=
by rw mem_smul_set; use [y, hy]
lemma smul_set_union [has_scalar α β] (a : α) (s t : set β) :
a • (s ∪ t) = a • s ∪ a • t :=
by simp only [smul_set_eq_image, image_union]
@[simp] lemma smul_set_empty [has_scalar α β] (a : α) :
a • (∅ : set β) = ∅ :=
by rw [smul_set_eq_image, image_empty]
lemma smul_set_mono [has_scalar α β]
(a : α) {s t : set β} (h : s ⊆ t) : a • s ⊆ a • t :=
by { rw [smul_set_eq_image, smul_set_eq_image], exact image_subset _ h }
section monoid
def pointwise_mul_semiring [monoid α] : semiring (set α) :=
{ add := (⊔),
zero := ∅,
add_assoc := set.union_assoc,
zero_add := set.empty_union,
add_zero := set.union_empty,
add_comm := set.union_comm,
zero_mul := empty_pointwise_mul,
mul_zero := pointwise_mul_empty,
left_distrib := pointwise_mul_union,
right_distrib := union_pointwise_mul,
..pointwise_mul_monoid }
def pointwise_mul_comm_semiring [comm_monoid α] : comm_semiring (set α) :=
{ mul_comm := λ s t, set.ext $ λ a,
by split; { rintros ⟨_, _, _, _, rfl⟩, exact ⟨_, ‹_›, _, ‹_›, mul_comm _ _⟩ },
..pointwise_mul_semiring }
local attribute [instance] pointwise_mul_semiring
def comm_monoid [comm_monoid α] : comm_monoid (set α) :=
@comm_semiring.to_comm_monoid (set α) pointwise_mul_comm_semiring
def add_comm_monoid [add_comm_monoid α] : add_comm_monoid (set α) :=
show @add_comm_monoid (additive (set (multiplicative α))),
from @additive.add_comm_monoid _ set.comm_monoid
attribute [to_additive set.add_comm_monoid] set.comm_monoid
/-- A multiplicative action of a monoid on a type β gives also a
multiplicative action on the subsets of β. -/
def smul_set_action [monoid α] [mul_action α β] :
mul_action α (set β) :=
{ smul := λ a s, a • s,
mul_smul := λ a b s, set.ext $ λ x, iff.intro
(λ ⟨_, hy, _⟩, ⟨b • _, smul_mem_smul_set _ hy, by rwa ←mul_smul⟩)
(λ ⟨_, hy, _⟩, let ⟨_, hz, h⟩ := (mem_smul_set _ _ _).2 hy in
⟨_, hz, by rwa [mul_smul, ←h]⟩),
one_smul := λ b, set.ext $ λ x, iff.intro
(λ ⟨_, _, h⟩, by { rw [one_smul] at h; rwa h })
(λ h, ⟨_, h, by rw one_smul⟩) }
section is_mul_hom
open is_mul_hom
variables [has_mul α] [has_mul β] (m : α → β) [is_mul_hom m]
@[to_additive]
lemma image_pointwise_mul (s t : set α) : m '' (s * t) = m '' s * m '' t :=
set.ext $ assume y,
begin
split,
{ rintros ⟨_, ⟨_, _, _, _, rfl⟩, rfl⟩,
refine ⟨_, mem_image_of_mem _ ‹_›, _, mem_image_of_mem _ ‹_›, map_mul _ _ _⟩ },
{ rintros ⟨_, ⟨_, _, rfl⟩, _, ⟨_, _, rfl⟩, rfl⟩,
refine ⟨_, ⟨_, ‹_›, _, ‹_›, rfl⟩, map_mul _ _ _⟩ }
end
@[to_additive]
lemma preimage_pointwise_mul_preimage_subset (s t : set β) : m ⁻¹' s * m ⁻¹' t ⊆ m ⁻¹' (s * t) :=
begin
rintros _ ⟨_, _, _, _, rfl⟩,
exact ⟨_, ‹_›, _, ‹_›, map_mul _ _ _⟩,
end
end is_mul_hom
variables [monoid α] [monoid β] [is_monoid_hom f]
lemma pointwise_mul_image_is_semiring_hom : is_semiring_hom (image f) :=
{ map_zero := image_empty _,
map_one := by erw [image_singleton, is_monoid_hom.map_one f]; refl,
map_add := image_union _,
map_mul := image_pointwise_mul _ }
end monoid
end set
section
open set
variables {α : Type*} {β : Type*}
local attribute [instance] set.smul_set
/-- A nonempty set in a semimodule is scaled by zero to the singleton
containing 0 in the semimodule. -/
lemma zero_smul_set [semiring α] [add_comm_monoid β] [semimodule α β]
{s : set β} (h : s.nonempty) : (0 : α) • s = {(0 : β)} :=
set.ext $ λ x, iff.intro
(λ ⟨_, _, hx⟩, mem_singleton_iff.mpr (by { rwa [hx, zero_smul] }))
(λ hx, let ⟨_, hs⟩ := h in
⟨_, hs, by { rw mem_singleton_iff at hx; rw [hx, zero_smul] }⟩)
lemma mem_inv_smul_set_iff [field α] [mul_action α β]
{a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a⁻¹ • A ↔ a • x ∈ A :=
iff.intro
(λ ⟨y, hy, h⟩, by rwa [h, ←mul_smul, mul_inv_cancel ha, one_smul])
(λ h, ⟨_, h, by rw [←mul_smul, inv_mul_cancel ha, one_smul]⟩)
lemma mem_smul_set_iff_inv_smul_mem [field α] [mul_action α β]
{a : α} (ha : a ≠ 0) (A : set β) (x : β) : x ∈ a • A ↔ a⁻¹ • x ∈ A :=
by conv_lhs { rw ← inv_inv'' a };
exact (mem_inv_smul_set_iff (inv_ne_zero ha) _ _)
end
|
bca4732c8e60fe0c3767617d85962c9cadf31a1e | dc253be9829b840f15d96d986e0c13520b085033 | /colimit/pointed.hlean | ddc2c4ecfbb4e91639ea9e58e13fcf0505937292 | [
"Apache-2.0"
] | permissive | cmu-phil/Spectral | 4ce68e5c1ef2a812ffda5260e9f09f41b85ae0ea | 3b078f5f1de251637decf04bd3fc8aa01930a6b3 | refs/heads/master | 1,685,119,195,535 | 1,684,169,772,000 | 1,684,169,772,000 | 46,450,197 | 42 | 13 | null | 1,505,516,767,000 | 1,447,883,921,000 | Lean | UTF-8 | Lean | false | false | 12,018 | hlean | /- pointed sequential colimits -/
-- authors: Floris van Doorn, Egbert Rijke, Stefano Piceghello
import .seq_colim types.fin homotopy.chain_complex types.pointed2
open seq_colim pointed algebra eq is_trunc nat is_equiv equiv sigma sigma.ops chain_complex fiber
namespace seq_colim
definition pseq_diagram [reducible] (A : ℕ → Type*) : Type := Πn, A n →* A (succ n)
definition pseq_colim [constructor] {X : ℕ → Type*} (f : pseq_diagram X) : Type* :=
pointed.MK (seq_colim f) (@sι _ _ 0 pt)
variables {A A' : ℕ → Type*} {f : pseq_diagram A} {f' : pseq_diagram A'}
{τ : Πn, A n →* A' n} {H : Πn, τ (n+1) ∘* f n ~* f' n ∘* τ n}
definition inclusion_pt {X : ℕ → Type*} (f : pseq_diagram X) (n : ℕ)
: inclusion f (Point (X n)) = Point (pseq_colim f) :=
begin
induction n with n p,
reflexivity,
exact (ap (sι f) (respect_pt _))⁻¹ᵖ ⬝ (!glue ⬝ p)
end
definition pinclusion [constructor] {X : ℕ → Type*} (f : pseq_diagram X) (n : ℕ)
: X n →* pseq_colim f :=
pmap.mk (inclusion f) (inclusion_pt f n)
definition pshift_equiv [constructor] {A : ℕ → Type*} (f : Πn, A n →* A (succ n)) :
pseq_colim f ≃* pseq_colim (λn, f (n+1)) :=
begin
fapply pequiv_of_equiv,
{ apply shift_equiv },
{ exact ap (ι _) (respect_pt (f 0)) }
end
definition pshift_equiv_pinclusion {A : ℕ → Type*} (f : Πn, A n →* A (succ n)) (n : ℕ) :
psquare (pinclusion f n) (pinclusion (λn, f (n+1)) n) (f n) (pshift_equiv f) :=
phomotopy.mk homotopy.rfl begin
refine !idp_con ⬝ _, esimp,
induction n with n IH,
{ esimp[inclusion_pt], esimp[shift_diag], exact !idp_con⁻¹ },
{ esimp[inclusion_pt], refine !con_inv_cancel_left ⬝ _,
rewrite ap_con, rewrite ap_con,
refine _ ⬝ whisker_right _ !con.assoc,
refine _ ⬝ (con.assoc (_ ⬝ _) _ _)⁻¹,
xrewrite [-IH],
esimp[shift_up], rewrite [elim_glue, ap_inv, ap_compose'], esimp,
rewrite [-+con.assoc], apply whisker_right,
rewrite con.assoc, apply !eq_inv_con_of_con_eq,
symmetry, exact eq_of_square !natural_square
}
end
definition pseq_colim_functor [constructor] {A A' : ℕ → Type*} {f : pseq_diagram A}
{f' : pseq_diagram A'} (g : Πn, A n →* A' n)
(p : Π⦃n⦄, g (n+1) ∘* f n ~ f' n ∘* g n) : pseq_colim f →* pseq_colim f' :=
pmap.mk (seq_colim_functor g p) (ap (ι _) (respect_pt (g _)))
definition pseq_colim_pequiv' [constructor] {A A' : ℕ → Type*} {f : pseq_diagram A}
{f' : pseq_diagram A'} (g : Πn, A n ≃* A' n)
(p : Π⦃n⦄, g (n+1) ∘* f n ~ f' n ∘* g n) : pseq_colim @f ≃* pseq_colim @f' :=
pequiv_of_equiv (seq_colim_equiv g p) (ap (ι _) (respect_pt (g _)))
definition pseq_colim_pequiv [constructor] {A A' : ℕ → Type*} {f : pseq_diagram A}
{f' : pseq_diagram A'} (g : Πn, A n ≃* A' n)
(p : Πn, g (n+1) ∘* f n ~* f' n ∘* g n) : pseq_colim @f ≃* pseq_colim @f' :=
pseq_colim_pequiv' g (λn, @p n)
-- definition seq_colim_equiv_constant [constructor] {A : ℕ → Type*} {f f' : pseq_diagram A}
-- (p : Π⦃n⦄ (a : A n), f n a = f' n a) : seq_colim f ≃ seq_colim f' :=
-- seq_colim_equiv (λn, erfl) p
definition pseq_colim_equiv_constant' [constructor] {A : ℕ → Type*} {f f' : pseq_diagram A}
(p : Π⦃n⦄, f n ~ f' n) : pseq_colim @f ≃* pseq_colim @f' :=
pseq_colim_pequiv' (λn, pequiv.rfl) p
definition pseq_colim_equiv_constant [constructor] {A : ℕ → Type*} {f f' : pseq_diagram A}
(p : Πn, f n ~* f' n) : pseq_colim @f ≃* pseq_colim @f' :=
pseq_colim_pequiv (λn, pequiv.rfl) (λn, !pid_pcompose ⬝* p n ⬝* !pcompose_pid⁻¹*)
definition pseq_colim_pequiv_pinclusion {A A' : ℕ → Type*} {f : Πn, A n →* A (n+1)}
{f' : Πn, A' n →* A' (n+1)} (g : Πn, A n ≃* A' n)
(p : Π⦃n⦄, g (n+1) ∘* f n ~* f' n ∘* g n) (n : ℕ) :
psquare (pinclusion f n) (pinclusion f' n) (g n) (pseq_colim_pequiv g p) :=
phomotopy.mk homotopy.rfl begin
esimp, refine !idp_con ⬝ _,
induction n with n IH,
{ esimp[inclusion_pt], exact !idp_con⁻¹ },
{ esimp[inclusion_pt], rewrite [+ap_con, -+ap_inv, +con.assoc, +seq_colim_functor_glue],
xrewrite[-IH],
rewrite[+ap_compose', -+con.assoc],
apply whisker_right, esimp,
rewrite[(eq_con_inv_of_con_eq (to_homotopy_pt (@p _)))],
rewrite[ap_con], esimp,
rewrite[-+con.assoc, ap_con, ap_compose', +ap_inv],
rewrite[-+con.assoc],
refine _ ⬝ whisker_right _ (whisker_right _ (whisker_right _ (whisker_right _ !con.left_inv⁻¹))),
rewrite[idp_con, +con.assoc], apply whisker_left,
rewrite[ap_con, ap_compose', con_inv, +con.assoc], apply whisker_left,
refine eq_inv_con_of_con_eq _,
symmetry, exact eq_of_square !natural_square
}
end
definition seq_colim_equiv_constant_pinclusion {A : ℕ → Type*} {f f' : pseq_diagram A}
(p : Πn, f n ~* f' n) (n : ℕ) :
pseq_colim_equiv_constant p ∘* pinclusion f n ~* pinclusion f' n :=
begin
transitivity pinclusion f' n ∘* !pid,
refine phomotopy_of_psquare !pseq_colim_pequiv_pinclusion,
exact !pcompose_pid
end
definition pseq_colim.elim' [constructor] {A : ℕ → Type*} {B : Type*} {f : pseq_diagram A}
(g : Πn, A n →* B) (p : Πn, g (n+1) ∘* f n ~ g n) : pseq_colim f →* B :=
begin
fapply pmap.mk,
{ intro x, induction x with n a n a,
{ exact g n a },
{ exact p n a }},
{ esimp, apply respect_pt }
end
definition pseq_colim.elim [constructor] {A : ℕ → Type*} {B : Type*} {f : pseq_diagram A}
(g : Πn, A n →* B) (p : Πn, g (n+1) ∘* f n ~* g n) : pseq_colim @f →* B :=
pseq_colim.elim' g p
definition pseq_colim.elim_pinclusion {A : ℕ → Type*} {B : Type*} {f : pseq_diagram A}
(g : Πn, A n →* B) (p : Πn, g (n+1) ∘* f n ~* g n) (n : ℕ) :
pseq_colim.elim g p ∘* pinclusion f n ~* g n :=
begin
refine phomotopy.mk phomotopy.rfl _,
refine !idp_con ⬝ _,
esimp,
induction n with n IH,
{ esimp, esimp[inclusion_pt], exact !idp_con⁻¹ },
{ esimp, esimp[inclusion_pt],
rewrite ap_con, rewrite ap_con,
rewrite elim_glue,
rewrite [-ap_inv],
rewrite [ap_compose'], esimp,
rewrite [(eq_con_inv_of_con_eq (!to_homotopy_pt))],
rewrite [IH],
rewrite [con_inv],
rewrite [-+con.assoc],
refine _ ⬝ whisker_right _ !con.assoc⁻¹,
rewrite [con.left_inv], esimp,
refine _ ⬝ !con.assoc⁻¹,
rewrite [con.left_inv], esimp,
rewrite [ap_inv],
rewrite [-con.assoc],
refine !idp_con⁻¹ ⬝ whisker_right _ !con.left_inv⁻¹,
}
end
definition prep0 [constructor] {A : ℕ → Type*} (f : pseq_diagram A) (k : ℕ) : A 0 →* A k :=
pmap.mk (rep0 (λn x, f n x) k)
begin induction k with k p, reflexivity, exact ap (@f k) p ⬝ !respect_pt end
definition respect_pt_prep0_succ {A : ℕ → Type*} (f : pseq_diagram A) (k : ℕ)
: respect_pt (prep0 f (succ k)) = ap (@f k) (respect_pt (prep0 f k)) ⬝ respect_pt (f k) :=
by reflexivity
theorem prep0_succ_lemma {A : ℕ → Type*} (f : pseq_diagram A) (n : ℕ)
(p : rep0 (λn x, f n x) n pt = rep0 (λn x, f n x) n pt)
(q : prep0 f n (Point (A 0)) = Point (A n))
: loop_equiv_eq_closed (ap (@f n) q ⬝ respect_pt (@f n))
(ap (@f n) p) = Ω→(@f n) (loop_equiv_eq_closed q p) :=
by rewrite [▸*, con_inv, ↑ap1_gen, +ap_con, ap_inv, +con.assoc]
-- definition succ_add_tr_rep {A : ℕ → Type} (f : seq_diagram A) {n : ℕ} (k : ℕ) (x : A n)
-- : transport A (succ_add n k) (rep f k (f x)) = rep f (succ k) x :=
-- begin
-- induction k with k p,
-- reflexivity,
-- exact tr_ap A succ (succ_add n k) _ ⬝ (fn_tr_eq_tr_fn (succ_add n k) f _)⁻¹ ⬝ ap (@f _) p,
-- end
-- definition succ_add_tr_rep_succ {A : ℕ → Type} (f : seq_diagram A) {n : ℕ} (k : ℕ) (x : A n)
-- : succ_add_tr_rep f (succ k) x = tr_ap A succ (succ_add n k) _ ⬝
-- (fn_tr_eq_tr_fn (succ_add n k) f _)⁻¹ ⬝ ap (@f _) (succ_add_tr_rep f k x) :=
-- by reflexivity
-- definition code_glue_equiv [constructor] {A : ℕ → Type} (f : seq_diagram A) {n : ℕ} (k : ℕ) (x y : A n)
-- : rep f k (f x) = rep f k (f y) ≃ rep f (succ k) x = rep f (succ k) y :=
-- begin
-- refine eq_equiv_fn_eq_of_equiv (equiv_ap A (succ_add n k)) _ _ ⬝e _,
-- apply eq_equiv_eq_closed,
-- exact succ_add_tr_rep f k x,
-- exact succ_add_tr_rep f k y
-- end
-- theorem code_glue_equiv_ap {n : ℕ} {k : ℕ} {x y : A n} (p : rep f k (f x) = rep f k (f y))
-- : code_glue_equiv f (succ k) x y (ap (@f _) p) = ap (@f _) (code_glue_equiv f k x y p) :=
-- begin
-- rewrite [▸*, +ap_con, ap_inv, +succ_add_tr_rep_succ, con_inv, inv_con_inv_right, +con.assoc],
-- apply whisker_left,
-- rewrite [- +con.assoc], apply whisker_right, rewrite [- +ap_compose'],
-- note s := (eq_top_of_square (natural_square_tr
-- (λx, fn_tr_eq_tr_fn (succ_add n k) f x ⬝ (tr_ap A succ (succ_add n k) (f x))⁻¹) p))⁻¹ᵖ,
-- rewrite [inv_con_inv_right at s, -con.assoc at s], exact s
-- end
definition pseq_colim_loop {X : ℕ → Type*} (f : Πn, X n →* X (n+1)) :
Ω (pseq_colim f) ≃* pseq_colim (λn, Ω→ (f n)) :=
begin
fapply pequiv_of_equiv,
{ refine !seq_colim_eq_equiv0 ⬝e _,
fapply seq_colim_equiv,
{ intro n, exact loop_equiv_eq_closed (respect_pt (prep0 f n)) },
{ intro n p, apply prep0_succ_lemma }},
{ reflexivity }
end
definition pseq_colim_loop_pinclusion {X : ℕ → Type*} (f : Πn, X n →* X (n+1)) (n : ℕ) :
pseq_colim_loop f ∘* Ω→ (pinclusion f n) ~* pinclusion (λn, Ω→(f n)) n :=
sorry
definition pseq_colim_loop_natural (n : ℕ) : psquare (pseq_colim_loop f) (pseq_colim_loop f')
(Ω→ (pseq_colim_functor τ H)) (pseq_colim_functor (λn, Ω→ (τ n)) (λn, ap1_psquare (H n))) :=
sorry
definition pseq_diagram_pfiber {A A' : ℕ → Type*} {f : pseq_diagram A} {f' : pseq_diagram A'}
(g : Πn, A n →* A' n) (p : Πn, g (succ n) ∘* f n ~* f' n ∘* g n) :
pseq_diagram (λk, pfiber (g k)) :=
λk, pfiber_functor (f k) (f' k) (p k)
/- Two issues when going to the pointed version of the fiber commuting with colimit:
- seq_diagram_fiber τ p a for a : A n at position k lives over (A (n + k)), so for a : A 0 you get A (0 + k), but we need A k
- in seq_diagram_fiber the fibers are taken in rep f ..., but in the pointed version over the basepoint of A n
-/
definition pfiber_pseq_colim_functor {A A' : ℕ → Type*} {f : pseq_diagram A}
{f' : pseq_diagram A'} (τ : Πn, A n →* A' n)
(p : Π⦃n⦄, τ (n+1) ∘* f n ~* f' n ∘* τ n) : pfiber (pseq_colim_functor τ p) ≃*
pseq_colim (pseq_diagram_pfiber τ p) :=
begin
fapply pequiv_of_equiv,
{ refine fiber_seq_colim_functor0 τ p pt ⬝e _, fapply seq_colim_equiv, intro n, esimp,
repeat exact sorry }, exact sorry
end
-- open succ_str
-- definition pseq_colim_succ_str_change_index' {N : succ_str} {B : N → Type*} (n : N) (m : ℕ)
-- (h : Πn, B n →* B (S n)) :
-- pseq_colim (λk, h (n +' (m + succ k))) ≃* pseq_colim (λk, h (S n +' (m + k))) :=
-- sorry
-- definition pseq_colim_succ_str_change_index {N : succ_str} {B : ℕ → N → Type*} (n : N)
-- (h : Π(k : ℕ) n, B k n →* B k (S n)) :
-- pseq_colim (λk, h k (n +' succ k)) ≃* pseq_colim (λk, h k (S n +' k)) :=
-- sorry
-- definition pseq_colim_index_eq_general {N : succ_str} (B : N → Type*) (f g : ℕ → N) (p : f ~ g)
-- (pf : Πn, S (f n) = f (n+1)) (pg : Πn, S (g n) = g (n+1)) (h : Πn, B n →* B (S n)) :
-- @pseq_colim (λn, B (f n)) (λn, ptransport B (pf n) ∘* h (f n)) ≃*
-- @pseq_colim (λn, B (g n)) (λn, ptransport B (pg n) ∘* h (g n)) :=
-- sorry
print axioms pseq_colim_loop
end seq_colim
|
e2a48ded7aac8ae7ee19bab9b00811dbd70975a9 | b7f22e51856f4989b970961f794f1c435f9b8f78 | /tests/lean/438.lean | fa093f1f1b254aba7ad0245549e902a428493e42 | [
"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 | 188 | lean | import algebra.bundled
open algebra
attribute Group.struct [coercion]
section
parameters {P₀ : Type} [P : group P₀]
include P
structure lambda_morphism := (comm : _ = _)
end
|
227c861952bf56e9297210474df8943b35c6df41 | fe84e287c662151bb313504482b218a503b972f3 | /src/data/finset_option.lean | ebfb3540aa189d2eee7b80a4a6347074cb8513a7 | [] | 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 | 2,680 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland
Suppose we have a finite type `α`, and we consider the type
`α₊ = (option α)`, which is essentially `α` with an extra
element adjoined. The power set `P(α₊)` then has an evident
bijection with `P(α) ∐ P(α)`, or equivalently with
`P(α) × bool`. Here we set up this bijection. There is
another take on essentially the same thing in
combinatorics/card_sign.lean. In both cases the amount of
work involved seems unreasonably large, but we have not
succeeded in reducing it.
-/
import data.fintype.basic algebra.big_operators.basic
import algebra.prod_equiv
import tactic.squeeze
namespace finset
open finset
variables {α : Type*} [decidable_eq α] [fintype α]
def finset_option_equiv : finset (option α) ≃ ((finset α) × bool) := {
to_fun := λ s, ⟨univ.filter (λ a, some a ∈ s),if none ∈ s then tt else ff⟩,
inv_fun := λ sb, cond sb.2 (insert none (sb.1.image some)) (sb.1.image some),
left_inv := λ s, begin
simp only [],split_ifs; rw[cond];ext x;rcases x with _ | a,
{simp[h],},
{split,
{intro ha,rcases mem_insert.mp ha with ha | ha,
{cases ha},
{rcases mem_image.mp ha with ⟨a',⟨ha,ea⟩⟩,
have ea : a' = a := by {injection ea},
exact ea ▸ (mem_filter.mp ha).right,
}
},{
intro ha,apply mem_insert_of_mem,apply mem_image.mpr,
use a,use mem_filter.mpr ⟨mem_univ a,ha⟩,
}
},{
split,
{intro h',rcases mem_image.mp h' with ⟨a,⟨_,⟨_⟩⟩⟩,},
{intro h',exact (h h').elim}
},{
split,
{intro h',rcases mem_image.mp h' with ⟨a',⟨h',ea⟩⟩,
exact ea ▸ (mem_filter.mp h').right,
},
{intro ha,apply mem_image.mpr,
use a,use mem_filter.mpr ⟨mem_univ a,ha⟩,}
}
end,
right_inv := λ ⟨s,b⟩, begin
have ne_none : ∀ a : α, some a ≠ none := λ a e, by {rcases e,},
have mem_some : ∀ a, a ∈ s ↔ some a ∈ s.image some :=
λ a, ⟨mem_image_of_mem some,
λ h, begin rcases mem_image.mp h with ⟨a',⟨h',e⟩⟩,
have e : a' = a := by { injection e }, exact e ▸ h',
end⟩,
have not_mem_some : none ∉ s.image some :=
λ e, by {rcases mem_image.mp e with ⟨_,⟨_,⟨_⟩⟩⟩,},
cases b;simp only[cond],
{rw[if_neg not_mem_some],congr,ext a,rw[mem_filter,← mem_some],
simp only[mem_univ a,true_and],
},
{rw[if_pos (mem_insert_self none (s.image some))],congr,
ext a,rw[mem_filter,mem_insert,← mem_some],
simp only[mem_univ a,ne_none a,true_and,false_or],
}
end
}
end finset
|
4c3af7a74611178c9dd4d50628280cddb4941a35 | 957a80ea22c5abb4f4670b250d55534d9db99108 | /tests/lean/case.lean | 67924b90244cbb3826814554a359780afc89be8b | [
"Apache-2.0"
] | permissive | GaloisInc/lean | aa1e64d604051e602fcf4610061314b9a37ab8cd | f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0 | refs/heads/master | 1,592,202,909,807 | 1,504,624,387,000 | 1,504,624,387,000 | 75,319,626 | 2 | 1 | Apache-2.0 | 1,539,290,164,000 | 1,480,616,104,000 | C++ | UTF-8 | Lean | false | false | 496 | lean | example (xs : list ℕ) : ℕ :=
begin
induction xs,
case list.cons {}
end
example (xs : list ℕ) : ℕ :=
begin
cases xs,
case list.cons {}
end
example (xs : list ℕ) : ℕ :=
begin
induction xs,
case list.cons x xs {
cases xs,
case list.cons x xs {}
}
end
open list
example (xs : list ℕ) : ℕ :=
begin
induction xs,
case cons {}
end
example (xs : list ℕ) : ℕ :=
begin
induction xs,
case list.cons x xs ih { apply ih },
case list.nil { apply 0 }
end
|
9a67664b23004e3b0c5da6c266bd0aadbac9c23c | c9b68131de1dfe4e7f0ea5749b11e67a774bc839 | /src/glue.lean | b00efb3f2a019d409063241be084b37dc8f6d77d | [] | no_license | congge666/formal-proofs | 2013f158f310abcfc07c156bb2a5113fb78f7831 | b5f6964d0220c8f89668357f2c08e44861128fe3 | refs/heads/master | 1,691,374,567,671 | 1,632,704,604,000 | 1,632,706,366,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 24,822 | lean | /-
This file translates the autogenerated data and constraints to the form used in the formalization.
-/
import constraints_autogen constraints
import memory range_check
open_locale classical big_operators
open_locale disable_subsingleton_simps
noncomputable theory
variables {F : Type*} [field F] [fintype F]
/- interpreting instruction constraints -/
def cpu__decode.to_instruction_constraints {c : columns F} (cd : cpu__decode c)
(j : nat) :
instruction_constraints
(c.cpu__decode__instruction (j * 16)) -- inst
(c.cpu__decode__off1 (j * 16)) -- off_op0_tilde
(c.cpu__decode__off2 (j * 16)) -- off_op1_tilde
(c.cpu__decode__off0 (j * 16)) -- off_dst_tilde
(λ k : fin 16, c.cpu__decode__opcode_rc__column (j * 16 + k)) -- f_tilde
:=
{ h_instruction :=
begin
dsimp,
have := cd.opcode_rc_input (j * 16) (by simp),
rw [eq_of_sub_eq_zero this, add_zero],
ring
end,
h_bit :=
begin
intro k, dsimp [tilde_type.to_f, column.off],
have : ↑(k.succ) = ↑k + 1, by simp,
rw [this, mul_sub, add_zero, add_zero, ←add_assoc, mul_one],
have : ¬(j * 16 + ↑k) % 16 = 15,
{ rw [add_comm, nat.add_mul_mod_self_right], apply ne_of_lt,
rw [nat.mod_eq_of_lt (lt_trans k.prop (nat.lt_succ_self _))],
apply k.prop },
have h := cd.opcode_rc__bit (j * 16 + k) this,
rw [←two_mul, column.off] at h,
exact h,
end,
h_last_value :=
begin
dsimp,
have : (j * 16 + 15) % 16 = 15,
{ rw [add_comm, nat.add_mul_mod_self_right, nat.mod_eq_of_lt (nat.lt_succ_self _)] },
exact cd.opcode_rc__zero (j * 16 + 15) this
end }
/- interpreting execution step constraints -/
def cpu__operands.to_step_constraints {c : columns F} {inp : input_data F} (ops : cpu__operands c)
(upd : cpu__update_registers c inp) (opcodes : cpu__opcodes c)
(j : ℕ) (hj : j ≠ inp.trace_length / 16 - 1) :
step_constraints
(c.cpu__decode__off1 (j * 16)) -- off_op0_tilde
(c.cpu__decode__off2 (j * 16)) -- off_op1_tilde
(c.cpu__decode__off0 (j * 16)) -- off_dst_tilde
(λ k : fin 16, c.cpu__decode__opcode_rc__column (j * 16 + k)) -- f_tilde
(c.cpu__registers__fp (j * 16)) -- fp
(c.cpu__registers__ap (j * 16)) -- ap
(c.cpu__decode__pc (j * 16)) -- pc
(c.cpu__registers__fp ((j + 1) * 16)) -- next fp
(c.cpu__registers__ap ((j + 1) * 16)) -- next ap
(c.cpu__decode__pc ((j + 1) * 16)) -- next pc
(c.cpu__operands__mem_dst__addr (j * 16)) -- dst_addr
(c.cpu__operands__mem_op0__addr (j * 16)) -- op0_addr
(c.cpu__operands__mem_op1__addr (j * 16)) -- op1_addr
(c.cpu__operands__mem_dst__value (j * 16)) -- dst
(c.cpu__operands__mem_op0__value (j * 16)) -- op0
(c.cpu__operands__mem_op1__value (j * 16)) -- op1
:=
have h0 : (j * 16 % 16 = 0), by simp,
have h1 : ¬ (j * 16 = 16 * (inp.trace_length / 16 - 1)),
by { rwa [mul_comm, mul_right_inj' _], norm_num },
{ mul := c.cpu__operands__ops_mul (j * 16),
res := c.cpu__operands__res (j * 16),
t0 := c.cpu__update_registers__update_pc__tmp0 (j * 16),
t1 := c.cpu__update_registers__update_pc__tmp1 (j * 16),
h_dst_addr :=
begin
simp [tilde_type.f_dst_reg, tilde_type.to_f, column.off, two_mul],
have h := ops.mem_dst_addr _ h0,
simp [column.off] at h,
rw [sub_eq_zero] at h,
rw ←sub_eq_iff_eq_add.mpr h.symm,
ring
end,
h_op0_addr :=
begin
simp [tilde_type.f_op0_reg, tilde_type.to_f, column.off, two_mul],
have h := ops.mem0_addr _ h0,
simp [column.off] at h,
rw [sub_eq_zero] at h,
rw ←sub_eq_iff_eq_add.mpr h.symm,
ring
end,
h_op1_addr :=
begin
have coe3 : ↑(3 : fin 15) = 3 := fin.coe_eq_val _,
have coe4 : ↑(4 : fin 15) = 4 := fin.coe_eq_val _,
simp [tilde_type.f_op1_imm, tilde_type.f_op1_ap, tilde_type.f_op1_fp,
tilde_type.to_f, column.off, two_mul, coe3, coe4],
have h := ops.mem1_addr _ h0,
simp [column.off] at h,
rw [sub_eq_zero] at h,
rw ←sub_eq_iff_eq_add.mpr h.symm,
ring,
end,
h_mul := eq_of_sub_eq_zero (ops.ops_mul _ h0),
h_res :=
begin
have coe5 : ↑(5 : fin 15) = 5 := fin.coe_eq_val _,
have coe6 : ↑(6 : fin 15) = 6 := fin.coe_eq_val _,
have coe9 : ↑(9 : fin 15) = 9 := fin.coe_eq_val _,
simp [tilde_type.f_pc_jnz, tilde_type.f_res_add, tilde_type.f_res_mul,
tilde_type.to_f, column.off, coe5, coe6, coe9, two_mul],
have h := ops.res _ h0,
rw [sub_eq_zero] at h,
transitivity,
apply h,
norm_num, ring,
end,
h_t0_eq :=
begin
simp [tilde_type.f_pc_jnz, tilde_type.to_f, column.off, two_mul],
exact eq_of_sub_eq_zero (upd.update_pc__tmp0 _ ⟨h0, h1⟩)
end,
h_t1_eq := eq_of_sub_eq_zero (upd.update_pc__tmp1 _ ⟨h0, h1⟩),
h_next_pc_eq :=
begin
have coe9 : ↑(9 : fin 15) = 9 := fin.coe_eq_val _,
dsimp,
simp only [tilde_type.f_pc_jnz, tilde_type.f_op1_imm, tilde_type.to_f, column.off, coe9,
two_mul, add_zero, fin.coe_two, fin.coe_succ, fin.coe_cast_succ, add_mul],
have h := upd.update_pc__pc_cond_positive _ ⟨h0, h1⟩,
convert h using 2,
simp [column.off], ring
end,
h_next_pc_eq' :=
begin
dsimp,
have coe7 : ↑(7 : fin 15) = 7 := fin.coe_eq_val _,
have coe8 : ↑(8 : fin 15) = 8 := fin.coe_eq_val _,
have coe9 : ↑(9 : fin 15) = 9 := fin.coe_eq_val _,
rw ←upd.update_pc__pc_cond_negative _ ⟨h0, h1⟩,
simp [tilde_type.f_pc_jnz, tilde_type.f_pc_jump_abs, tilde_type.f_pc_jump_rel,
tilde_type.f_op1_imm, tilde_type.to_f, column.off, coe7, coe8, coe9,
two_mul, add_zero, add_mul, fin.coe_two, fin.coe_succ, fin.coe_cast_succ],
ring
end,
h_opcode_call :=
begin
rw ←opcodes.call__push_fp _ h0,
dsimp,
simp only [tilde_type.f_opcode_call, tilde_type.to_f, column.off, add_zero, fin.coe_succ,
fin.coe_cast_succ, ←two_mul],
refl
end,
h_opcode_call' :=
begin
have coe12 : ↑(12 : fin 15) = 12 := fin.coe_eq_val _,
rw ←opcodes.call__push_pc _ h0,
dsimp,
simp only [tilde_type.f_opcode_call, tilde_type.f_op1_imm, tilde_type.to_f, column.off,
add_zero, fin.coe_succ, fin.coe_cast_succ, ←two_mul, coe12],
ring
end,
h_opcode_assert_eq :=
begin
have coe14 : ↑(14 : fin 15) = 14 := fin.coe_eq_val _,
rw ←opcodes.assert_eq__assert_eq _ h0,
dsimp,
simp only [tilde_type.f_opcode_assert_eq, tilde_type.to_f, column.off, add_zero, fin.coe_succ,
fin.coe_cast_succ, ←two_mul, coe14]
end,
h_next_ap :=
begin
have coe10 : ↑(10 : fin 15) = 10 := fin.coe_eq_val _,
have coe11 : ↑(11 : fin 15) = 11 := fin.coe_eq_val _,
have coe12 : ↑(12 : fin 15) = 12 := fin.coe_eq_val _,
dsimp,
simp only [add_mul, one_mul, column.off, add_zero],
transitivity,
{ exact eq_of_sub_eq_zero (upd.update_ap__ap_update _ ⟨h0, h1⟩) },
simp only [tilde_type.f_opcode_call, tilde_type.f_ap_add, tilde_type.f_ap_add1,
tilde_type.to_f, column.off, fin.coe_succ, fin.coe_cast_succ, coe10, coe11, coe12,
←two_mul],
norm_num, ring
end,
h_next_fp :=
begin
have coe12 : ↑(12 : fin 15) = 12 := fin.coe_eq_val _,
have coe13 : ↑(13 : fin 15) = 13 := fin.coe_eq_val _,
dsimp,
simp only [add_mul, one_mul, column.off, add_zero],
transitivity,
{ exact eq_of_sub_eq_zero (upd.update_fp__fp_update _ ⟨h0, h1⟩) },
simp only [tilde_type.f_opcode_call, tilde_type.f_opcode_ret,
tilde_type.to_f, column.off, fin.coe_succ, fin.coe_cast_succ,
coe12, coe13, ←two_mul],
norm_num, ring
end }
/-
interpreting range check constraints
Note: from the autogenerated constraints, we can get the stronger result with
`inp.trace_length / 16 - 1` replaced by `inp.trace_length / 16`.
-/
def rc16.to_range_check_constraints
{c : columns F}
{ci : columns_inter F}
{inp : input_data F}
{pd : public_data F}
(rc16 : rc16 inp pd c ci)
(trace_length_pos : inp.trace_length > 0)
(public_memory_prod_eq_one : pd.rc16__perm__public_memory_prod = 1)
(trace_length_le_char : inp.trace_length ≤ ring_char F) :
range_check_constraints
(inp.trace_length / 16 - 1) -- T
(λ j, c.cpu__decode__off1 (j * 16)) -- off_op0_tilde : fin T → F
(λ j, c.cpu__decode__off2 (j * 16)) -- off_op1_tilde : fin T → F
(λ j, c.cpu__decode__off0 (j * 16)) -- off_dst_tilde : fin T → F
pd.rc_min
pd.rc_max
:=
have h : ∀ j : ℕ, ∀ i : fin (inp.trace_length / 16 - 1),
j < 16 → (↑i * 16 + j) < inp.trace_length - 1 + 1,
begin
rintros j ⟨i, ilt⟩ jlt,
rw nat.sub_add_cancel trace_length_pos,
apply lt_of_lt_of_le (add_lt_add_left jlt _),
suffices : (i + 1) * 16 ≤ inp.trace_length, by rwa [add_mul] at this,
apply le_trans (nat.mul_le_mul_right _ _) (nat.div_mul_le_self _ 16),
exact lt_of_lt_of_le ilt (nat.pred_le _)
end,
{ n := inp.trace_length - 1,
a := λ i, c.rc16_pool i,
a' := λ i, c.rc16__sorted i,
p := λ i, ci.rc16__perm__cum_prod0 i,
z := pd.rc16__perm__interaction_elm,
embed_off_op0 := λ i, ⟨↑i * 16 + 8, h 8 i (by norm_num)⟩,
embed_off_op1 := λ i, ⟨↑i * 16 + 4, h 4 i (by norm_num)⟩,
embed_off_dst := λ i, ⟨↑i * 16, h 0 i (by norm_num)⟩,
h_embed_op0 := λ i, rfl,
h_embed_op1 := λ i, rfl,
h_embed_dst := λ i, rfl,
h_continuity :=
begin
intro i,
rw [←rc16.diff_is_bit _ (ne_of_lt i.is_lt), mul_sub, mul_one],
simp, refl
end,
h_initial :=
begin
rw [←sub_eq_zero, ←rc16.perm__init0 _ rfl],
simp [column.off], abel
end,
h_cumulative :=
begin
intro i,
rw [←sub_eq_zero, ←rc16.perm__step0 _ (ne_of_lt i.is_lt)],
simp [column.off]
end,
h_final := (eq_of_sub_eq_zero (rc16.perm__last _ rfl)).trans public_memory_prod_eq_one,
h_rc_min := eq_of_sub_eq_zero $ rc16.minimum _ rfl,
h_rc_max := eq_of_sub_eq_zero $ rc16.maximum _ rfl,
h_n_lt :=
begin
apply nat.lt_of_succ_le,
rw [nat.succ_eq_add_one, nat.sub_add_cancel trace_length_pos],
exact trace_length_le_char
end }
/- interpreting memory constraints -/
noncomputable def memory.to_memory_block_constraints
{inp : input_data F} {pd : public_data F} {c : columns F} {ci : columns_inter F}
(h_mem_star :
let z := pd.memory__multi_column_perm__perm__interaction_elm,
alpha := pd.memory__multi_column_perm__hash_interaction_elm0,
p := pd.memory__multi_column_perm__perm__public_memory_prod,
dom_m_star := { x // option.is_some (inp.m_star x) } in
p * ∏ a : dom_m_star, (z - (a.val + alpha * mem_val a)) = z^(fintype.card dom_m_star))
(m : memory inp pd c ci) :
memory_block_constraints
(inp.trace_length / 2 - 1) -- n
(λ i, c.mem_pool__addr (2 * i)) -- a
(λ i, c.mem_pool__value (2 * i)) -- v
inp.m_star
:=
have h0 : ∀ j : fin (inp.trace_length / 2 - 1), ↑j * 2 % 2 = 0, by intro j; simp,
have h1 : ∀ j : fin (inp.trace_length / 2 - 1), ¬ (↑j * 2 = 2 * (inp.trace_length / 2 - 1)),
begin
rintros ⟨j, jlt⟩,
have hj : j ≠ inp.trace_length / 2 - 1 := ne_of_lt jlt,
rwa [mul_comm, mul_right_inj' _], norm_num
end,
{ a' := (λ j, c.column20 (2 * j)),
v' := (λ j, c.column20 (2 * j + 1)),
p := (λ j, ci.column24_inter1 (2 * j)),
alpha := pd.memory__multi_column_perm__hash_interaction_elm0,
z := pd.memory__multi_column_perm__perm__interaction_elm,
h_continuity :=
begin
intro j,
rw [←m.diff_is_bit (↑j * 2) ⟨h0 j, h1 j⟩, mul_comm 2],
simp [column.off, add_mul, mul_comm 2], ring
end,
h_single_valued :=
begin
intro j,
apply neg_inj.mp,
rw [neg_zero, ←m.is_func (↑j * 2) ⟨h0 j, h1 j⟩],
simp [column.off, add_mul, mul_add, mul_comm 2, add_assoc], norm_num,
ring
end,
h_initial :=
begin
rw [←sub_eq_zero, ←m.multi_column_perm__perm__init0 _ rfl],
simp [column.off], ring
end,
h_cumulative :=
begin
intro j,
rw [←sub_eq_zero, ←m.multi_column_perm__perm__step0 (↑j * 2) ⟨h0 j, h1 j⟩],
simp [column.off, add_mul, mul_add, mul_comm 2, add_assoc]
end,
h_final :=
begin
apply eq.trans _ h_mem_star,
rw [←eq_of_sub_eq_zero (m.multi_column_perm__perm__last _ rfl)],
refl
end }
theorem card_dom_aux {inp : input_data F}
(h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) :
4 * fintype.card { x // option.is_some (inp.m_star x) } ≤ inp.trace_length / 2 - 1 :=
begin
apply nat.le_pred_of_lt,
apply nat.lt_of_succ_le,
rw [nat.le_div_iff_mul_le' (show 0 < 2, by norm_num), nat.succ_mul, mul_comm, ←mul_assoc],
norm_num,
exact h_card
end
def embed_mem {inp : input_data F}
(h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length)
(a : mem_dom inp.m_star) :
fin (inp.trace_length / 2 - 1 + 1) :=
let i := (fintype.equiv_fin { x // option.is_some (inp.m_star x) }).to_fun a in
⟨4 * i.val + 1,
nat.succ_lt_succ (lt_of_lt_of_le (nat.mul_lt_mul_of_pos_left i.is_lt (by norm_num))
(card_dom_aux h_card))⟩
def public_memory.to_memory_embedding_constraints
{c : columns F} {inp : input_data F}
(pm : public_memory c)
(h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) :
memory_embedding_constraints
(inp.trace_length / 16 - 1) -- T
(λ j, c.cpu__decode__pc (j * 16)) -- pc
(λ j, c.cpu__decode__instruction (j * 16)) -- inst
(λ j, c.cpu__operands__mem_dst__addr (j * 16)) -- dst_addr
(λ j, c.cpu__operands__mem_dst__value (j * 16)) -- dst
(λ j, c.cpu__operands__mem_op0__addr (j * 16)) -- op0_addr
(λ j, c.cpu__operands__mem_op0__value (j * 16)) -- op0
(λ j, c.cpu__operands__mem_op1__addr (j * 16)) -- op1_addr
(λ j, c.cpu__operands__mem_op1__value (j * 16)) -- op1
inp.m_star -- mem_star
(inp.trace_length / 2 - 1) -- n
(λ i, c.mem_pool__addr (2 * i)) -- a
(λ i, c.mem_pool__value (2 * i)) -- v
:=
have h : ∀ j : ℕ, ∀ i : fin (inp.trace_length / 16 - 1), j < 8 →
(↑i * 8 + j) < inp.trace_length / 2 - 1 + 1,
begin
rintros j ⟨i, ilt⟩ jlt,
apply nat.lt_succ_of_le,
apply nat.le_pred_of_lt,
have : i * 8 + j < (i + 1) * 8,
{ rw [add_mul, one_mul], exact add_lt_add_left jlt _ },
apply lt_of_lt_of_le this,
rw [nat.le_div_iff_mul_le' (show 0 < 2, by norm_num), mul_assoc],
norm_num,
rw [←nat.le_div_iff_mul_le' (show 0 < 16, by norm_num)],
apply nat.succ_le_of_lt,
exact lt_of_lt_of_le ilt (nat.pred_le _)
end,
have jaux : ∀ j : fin (inp.trace_length / 16 - 1), (j : ℕ) * 8 = 4 * (2 * j),
by { intro j, rw [←mul_assoc, mul_comm (4 * 2)], refl },
{ embed_inst := λ i, ⟨↑i * 8 + 0, h 0 i (by norm_num)⟩,
embed_dst := λ i, ⟨↑i * 8 + 4, h 4 i (by norm_num)⟩,
embed_op0 := λ i, ⟨↑i * 8 + 2, h 2 i (by norm_num)⟩,
embed_op1 := λ i, ⟨↑i * 8 + 6, h 6 i (by norm_num)⟩,
embed_mem := embed_mem h_card,
h_embed_pc := by { intro i, dsimp [column.off], congr' 1, ring },
h_embed_inst := by { intro i, dsimp [column.off], congr' 1, ring },
h_embed_dst_addr := by { intro i, dsimp [column.off], congr' 1, ring },
h_embed_dst := by { intro i, dsimp [column.off], congr' 1, ring },
h_embed_op0_addr := by { intro i, dsimp [column.off], congr' 1, ring },
h_embed_op0 := by { intro i, dsimp [column.off], congr' 1, ring },
h_embed_op1_addr := by { intro i, dsimp [column.off], congr' 1, ring },
h_embed_op1 := by { intro i, dsimp [column.off], congr' 1, ring },
h_embed_dom :=
begin
intro a, simp [column.off],
apply pm.memory_addr_zero, simp, rw [←mul_assoc],
exact nat.mul_mod_right _ _
end,
h_embed_val :=
begin
intro a, simp [column.off],
apply pm.memory_value_zero, simp, rw [←mul_assoc],
exact nat.mul_mod_right _ _
end,
h_embed_mem_inj :=
begin
intros a1 a2, dsimp [embed_mem],
rw [fin.eq_iff_veq, add_left_inj 1, mul_right_inj' (show 4 ≠ 0, by norm_num), ←fin.ext_iff],
apply equiv.injective
end,
h_embed_mem_disj_inst :=
begin
intros a j h',
rw [fin.eq_iff_veq] at h', dsimp at h',
have := congr_arg (λ n, n % 4) h', dsimp [embed_mem] at this,
rw [add_comm, add_comm _ 0, jaux, nat.add_mul_mod_self_left,
nat.add_mul_mod_self_left] at this,
norm_num at this
end,
h_embed_mem_disj_dst :=
begin
intros a j h',
rw [fin.eq_iff_veq] at h', dsimp [embed_mem] at h',
have := congr_arg (λ n, n % 4) h', dsimp at this,
rw [add_comm, add_comm _ 4, jaux, nat.add_mul_mod_self_left,
nat.add_mul_mod_self_left] at this,
norm_num at this
end,
h_embed_mem_disj_op0 :=
begin
intros a j h',
rw [fin.eq_iff_veq] at h', dsimp [embed_mem] at h',
have := congr_arg (λ n, n % 4) h', dsimp at this,
rw [add_comm, add_comm _ 2, jaux, nat.add_mul_mod_self_left,
nat.add_mul_mod_self_left] at this,
norm_num at this
end,
h_embed_mem_disj_op1 :=
begin
intros a j h',
rw [fin.eq_iff_veq] at h', dsimp [embed_mem] at h',
have := congr_arg (λ n, n % 4) h', dsimp at this,
rw [add_comm, add_comm _ 6, jaux, nat.add_mul_mod_self_left,
nat.add_mul_mod_self_left] at this,
norm_num at this
end }
/- putting it all together -/
def input_data.to_input_data_aux (inp : input_data F) (pd : public_data F)
(rc_max_lt : pd.rc_max < 2^16)
(rc_min_le : pd.rc_min ≤ pd.rc_max) : input_data_aux F :=
{ T := inp.trace_length / 16 - 1,
pc_I := inp.initial_pc,
pc_F := inp.final_pc,
ap_I := inp.initial_ap,
ap_F := inp.final_ap,
mem_star := inp.m_star,
rc_min := pd.rc_min,
rc_max := pd.rc_max,
h_rc_lt := rc_max_lt,
h_rc_le := rc_min_le }
def to_constraints {inp : input_data F} {pd : public_data F} {c : columns F} {ci : columns_inter F}
/- autogenerated constraints -/
(cd : cpu__decode c)
(ops : cpu__operands c)
(upd : cpu__update_registers c inp)
(opcodes : cpu__opcodes c)
(m : memory inp pd c ci)
(rc : rc16 inp pd c ci)
(pm : public_memory c)
(iandf : initial_and_final inp c)
/- extra assumptions -/
(h_mem_star :
let z := pd.memory__multi_column_perm__perm__interaction_elm,
alpha := pd.memory__multi_column_perm__hash_interaction_elm0,
p := pd.memory__multi_column_perm__perm__public_memory_prod,
dom_m_star := { x // option.is_some (inp.m_star x) } in
p * ∏ a : dom_m_star, (z - (a.val + alpha * mem_val a)) = z^(fintype.card dom_m_star))
(h_card_dom : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length)
(public_memory_prod_eq_one : pd.rc16__perm__public_memory_prod = 1)
(rc_max_lt : pd.rc_max < 2^16)
(rc_min_le : pd.rc_min ≤ pd.rc_max)
(trace_length_le_char : inp.trace_length ≤ ring_char F) :
constraints (inp.to_input_data_aux pd rc_max_lt rc_min_le) :=
have trace_length_pos : inp.trace_length > 0,
from lt_of_lt_of_le (nat.zero_lt_succ _) h_card_dom,
{ fp := λ j, c.cpu__registers__fp (j * 16),
ap := λ j, c.cpu__registers__ap (j * 16),
pc := λ j, c.cpu__decode__pc (j * 16),
inst := λ j, c.cpu__decode__instruction (j * 16),
off_op0_tilde := λ j, c.cpu__decode__off1 (j * 16),
off_op1_tilde := λ j, c.cpu__decode__off2 (j * 16),
off_dst_tilde := λ j, c.cpu__decode__off0 (j * 16),
f_tilde := λ j k, c.cpu__decode__opcode_rc__column (j * 16 + k),
dst_addr := λ j, c.cpu__operands__mem_dst__addr (j * 16),
dst := λ j, c.cpu__operands__mem_dst__value (j * 16),
op0_addr := λ j, c.cpu__operands__mem_op0__addr (j * 16),
op0 := λ j, c.cpu__operands__mem_op0__value (j * 16),
op1_addr := λ j, c.cpu__operands__mem_op1__addr (j * 16),
op1 := λ j, c.cpu__operands__mem_op1__value (j * 16),
h_pc_I := eq_of_sub_eq_zero (iandf.initial_pc _ rfl),
h_ap_I := eq_of_sub_eq_zero (iandf.initial_ap _ rfl),
h_fp_I := eq_of_sub_eq_zero (iandf.initial_fp _ rfl),
h_pc_F := by { rw mul_comm _ 16, exact eq_of_sub_eq_zero (iandf.final_pc _ rfl) },
h_ap_F := by { rw mul_comm _ 16, exact eq_of_sub_eq_zero (iandf.final_ap _ rfl) },
mc := { n := inp.trace_length / 2 - 1,
a := λ i, c.mem_pool__addr (2 * i),
v := λ i, c.mem_pool__value (2 * i),
em := pm.to_memory_embedding_constraints h_card_dom,
mb := m.to_memory_block_constraints h_mem_star,
h_n_lt :=
begin
apply lt_of_lt_of_le _ trace_length_le_char,
apply nat.lt_of_succ_le,
rw [nat.sub_one, nat.succ_pred_eq_of_pos],
{ apply nat.div_le_self },
apply nat.div_pos _ (show 0 < 2, by norm_num),
apply le_trans _ h_card_dom,
apply le_add_left (le_refl _),
end},
rc := rc.to_range_check_constraints trace_length_pos public_memory_prod_eq_one
trace_length_le_char,
ic := λ i, cd.to_instruction_constraints i,
sc := λ i, by { rw fin.coe_succ, exact ops.to_step_constraints upd opcodes i (ne_of_lt i.is_lt) }
}
/- probabilistic constraints -/
def bad1 {inp : input_data F}
(h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length)
(c19 c20 : column F) : finset F :=
bad_set_1
(real_a inp.m_star (λ i, c19 (2 * i)) (embed_mem h_card))
(real_v inp.m_star (λ i, c19 (2 * i + 1)) (embed_mem h_card))
(λ j, c20 (2 * ↑j))
(λ j, c20 (2 * ↑j + 1))
def bad2 {inp : input_data F} (pd : public_data F)
(h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length)
(c19 c20 : column F) : finset F :=
bad_set_2
(real_a inp.m_star (λ i, c19 (2 * i)) (embed_mem h_card))
(real_v inp.m_star (λ i, c19 (2 * i + 1)) (embed_mem h_card))
(λ j, c20 (2 * ↑j))
(λ j, c20 (2 * ↑j + 1))
pd.memory__multi_column_perm__hash_interaction_elm0
def bad3 (inp : input_data F) (c0 c2 : column F) : finset F :=
bad_set_3
(λ (i : fin (inp.trace_length - 1 + 1)), c0 i)
(λ (i : fin (inp.trace_length - 1 + 1)), c2 i)
lemma trace_length_div_two_pos {inp : input_data F}
(h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) :
inp.trace_length / 2 > 0 :=
begin
apply nat.div_pos _ (show 0 < 2, by norm_num),
apply le_trans _ h_card,
apply le_add_left (le_refl _)
end
theorem bad1_bound {inp : input_data F}
(h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length)
(c19 c20 : column F) :
(bad1 h_card c19 c20).card ≤ (inp.trace_length / 2)^2 :=
begin
transitivity,
apply card_bad_set_1_le,
rw [nat.sub_add_cancel, pow_two],
apply trace_length_div_two_pos h_card
end
theorem bad2_bound {inp : input_data F} (pd : public_data F)
(h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length)
(c19 c20 : column F) :
(bad2 pd h_card c19 c20).card ≤ inp.trace_length / 2 :=
begin
transitivity,
apply card_bad_set_2_le,
rw nat.sub_add_cancel,
apply trace_length_div_two_pos h_card
end
theorem bad3_bound {inp : input_data F}
(h_card : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length)
(c0 c2 : column F) :
(bad3 inp c0 c2).card ≤ inp.trace_length :=
begin
transitivity,
apply card_bad_set_3_le,
rw nat.sub_add_cancel,
exact lt_of_lt_of_le (nat.zero_lt_succ _) h_card
end
|
22089646d049f4b954e74476f6025ad937f83c0a | 9ad8d18fbe5f120c22b5e035bc240f711d2cbd7e | /src/combinatorics/binomial_sum.lean | f879e26bd76769732d8386e548c2c521eccce96c | [] | no_license | agusakov/lean_lib | c0e9cc29fc7d2518004e224376adeb5e69b5cc1a | f88d162da2f990b87c4d34f5f46bbca2bbc5948e | refs/heads/master | 1,642,141,461,087 | 1,557,395,798,000 | 1,557,395,798,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,078 | lean | /-
Copyright (c) 2019 Neil Strickland. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Neil Strickland
-/
import data.nat.choose
import tactic.squeeze
/-
Consider the identity
(choose n k) = (choose k-1 k-1) + (choose k k-1) + ... + (choose n-1 k-1)
or
(choose n+1 k+1) = (choose k k) + (choose k+1 k) + ... + (choose n k)
This can be proved algebraically by induction.
Alternatively, we can consider the set (P n k) of
subsets A of size k in {0,..,n-1}, so |(P n k)| = (choose n k).
We can split this set up according to the value of (max A),
and recover a combinatorial proof of the identity.
-/
lemma choose_sum' (k m : ℕ) :
nat.choose (k + m) (k + 1) =
(finset.range m).sum (λ i, nat.choose (k + i) k) :=
begin
induction m with m ih,
{rw[finset.range_zero,finset.sum_empty,add_zero,nat.choose_succ_self]},
{rw[finset.sum_range_succ,← ih,nat.add_succ,nat.choose],}
end
lemma choose_sum (n k : ℕ) :
nat.choose n.succ k.succ = (finset.Ico k n.succ).sum (λ i, nat.choose i k)
:= sorry |
36f61863134b714f8acbfd62022a9edb2976efae | 626e312b5c1cb2d88fca108f5933076012633192 | /src/measure_theory/constructions/borel_space.lean | 8e06b8ea41a5f902cc388831c4c569384141cff5 | [
"Apache-2.0"
] | permissive | Bioye97/mathlib | 9db2f9ee54418d29dd06996279ba9dc874fd6beb | 782a20a27ee83b523f801ff34efb1a9557085019 | refs/heads/master | 1,690,305,956,488 | 1,631,067,774,000 | 1,631,067,774,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 68,478 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johannes Hölzl, Yury Kudryashov
-/
import measure_theory.function.ae_measurable_sequence
import analysis.complex.basic
import analysis.normed_space.finite_dimension
import topology.G_delta
import measure_theory.group.arithmetic
import topology.semicontinuous
import topology.instances.ereal
/-!
# Borel (measurable) space
## Main definitions
* `borel α` : the least `σ`-algebra that contains all open sets;
* `class borel_space` : a space with `topological_space` and `measurable_space` structures
such that `‹measurable_space α› = borel α`;
* `class opens_measurable_space` : a space with `topological_space` and `measurable_space`
structures such that all open sets are measurable; equivalently, `borel α ≤ ‹measurable_space α›`.
* `borel_space` instances on `empty`, `unit`, `bool`, `nat`, `int`, `rat`;
* `measurable` and `borel_space` instances on `ℝ`, `ℝ≥0`, `ℝ≥0∞`.
## Main statements
* `is_open.measurable_set`, `is_closed.measurable_set`: open and closed sets are measurable;
* `continuous.measurable` : a continuous function is measurable;
* `continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ`
is continuous, then `λ x, op (f x, g y)` is measurable;
* `measurable.add` etc : dot notation for arithmetic operations on `measurable` predicates,
and similarly for `dist` and `edist`;
* `ae_measurable.add` : similar dot notation for almost everywhere measurable functions;
* `measurable.ennreal*` : special cases for arithmetic operations on `ℝ≥0∞`.
-/
noncomputable theory
open classical set filter measure_theory
open_locale classical big_operators topological_space nnreal ennreal
universes u v w x y
variables {α β γ γ₂ δ : Type*} {ι : Sort y} {s t u : set α}
open measurable_space topological_space
/-- `measurable_space` structure generated by `topological_space`. -/
def borel (α : Type u) [topological_space α] : measurable_space α :=
generate_from {s : set α | is_open s}
lemma borel_eq_top_of_discrete [topological_space α] [discrete_topology α] :
borel α = ⊤ :=
top_le_iff.1 $ λ s hs, generate_measurable.basic s (is_open_discrete s)
lemma borel_eq_top_of_encodable [topological_space α] [t1_space α] [encodable α] :
borel α = ⊤ :=
begin
refine (top_le_iff.1 $ λ s hs, bUnion_of_singleton s ▸ _),
apply measurable_set.bUnion s.countable_encodable,
intros x hx,
apply measurable_set.of_compl,
apply generate_measurable.basic,
exact is_closed_singleton.is_open_compl
end
lemma borel_eq_generate_from_of_subbasis {s : set (set α)}
[t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) :
borel α = generate_from s :=
le_antisymm
(generate_from_le $ assume u (hu : t.is_open u),
begin
rw [hs] at hu,
induction hu,
case generate_open.basic : u hu
{ exact generate_measurable.basic u hu },
case generate_open.univ
{ exact @measurable_set.univ α (generate_from s) },
case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂
{ exact @measurable_set.inter α (generate_from s) _ _ hs₁ hs₂ },
case generate_open.sUnion : f hf ih {
rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩,
rw ← vu,
exact @measurable_set.sUnion α (generate_from s) _ hv
(λ x xv, ih _ (vf xv)) }
end)
(generate_from_le $ assume u hu, generate_measurable.basic _ $
show t.is_open u, by rw [hs]; exact generate_open.basic _ hu)
lemma topological_space.is_topological_basis.borel_eq_generate_from [topological_space α]
[second_countable_topology α] {s : set (set α)} (hs : is_topological_basis s) :
borel α = generate_from s :=
borel_eq_generate_from_of_subbasis hs.eq_generate_from
lemma is_pi_system_is_open [topological_space α] : is_pi_system (is_open : set α → Prop) :=
λ s t hs ht hst, is_open.inter hs ht
lemma borel_eq_generate_from_is_closed [topological_space α] :
borel α = generate_from {s | is_closed s} :=
le_antisymm
(generate_from_le $ λ t ht, @measurable_set.of_compl α _ (generate_from {s | is_closed s})
(generate_measurable.basic _ $ is_closed_compl_iff.2 ht))
(generate_from_le $ λ t ht, @measurable_set.of_compl α _ (borel α)
(generate_measurable.basic _ $ is_open_compl_iff.2 ht))
section order_topology
variable (α)
variables [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α]
lemma is_pi_system_Ioo_mem {α : Type*} [linear_order α] (s t : set α) :
is_pi_system {S | ∃ (l ∈ s) (u ∈ t), l < u ∧ Ioo l u = S} :=
begin
rintro _ _ ⟨l₁, hls₁, u₁, hut₁, hlu₁, rfl⟩ ⟨l₂, hls₂, u₂, hut₂, hlu₂, rfl⟩
⟨x, ⟨hlx₁ : l₁ < x, hxu₁ : x < u₁⟩, ⟨hlx₂ : l₂ < x, hxu₂ : x < u₂⟩⟩,
refine ⟨l₁ ⊔ l₂, sup_ind l₁ l₂ hls₁ hls₂, u₁ ⊓ u₂, inf_ind u₁ u₂ hut₁ hut₂, _,
Ioo_inter_Ioo.symm⟩,
simp [hlx₂.trans hxu₁, hlx₁.trans hxu₂, *]
end
lemma is_pi_system_Ioo {α β : Type*} [linear_order β] (f : α → β) :
@is_pi_system β (⋃ l u (h : f l < f u), {Ioo (f l) (f u)}) :=
begin
convert is_pi_system_Ioo_mem (range f) (range f),
ext s,
simp [@eq_comm _ _ s]
end
lemma borel_eq_generate_Iio : borel α = generate_from (range Iio) :=
begin
refine le_antisymm _ (generate_from_le _),
{ rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _),
letI : measurable_space α := measurable_space.generate_from (range Iio),
have H : ∀ a : α, measurable_set (Iio a) := λ a, generate_measurable.basic _ ⟨_, rfl⟩,
refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H],
by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b,
{ rcases h with ⟨a', ha'⟩,
rw (_ : Ioi a = (Iio a')ᶜ), { exact (H _).compl },
simp [set.ext_iff, ha'] },
{ rcases is_open_Union_countable
(λ a' : {a' : α // a < a'}, {b | a'.1 < b})
(λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩,
simp [set.ext_iff] at vu,
have : Ioi a = ⋃ x : v, (Iio x.1.1)ᶜ,
{ simp [set.ext_iff],
refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩,
rcases (vu x).2 _ with ⟨a', h₁, h₂⟩,
{ exact ⟨a', h₁, le_of_lt h₂⟩ },
refine not_imp_comm.1 (λ h, _) h,
exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩),
lt_of_lt_of_le ax⟩⟩ },
rw this, resetI,
apply measurable_set.Union,
exact λ _, (H _).compl } },
{ rw forall_range_iff,
intro a,
exact generate_measurable.basic _ is_open_Iio }
end
lemma borel_eq_generate_Ioi : borel α = generate_from (range Ioi) :=
@borel_eq_generate_Iio (order_dual α) _ (by apply_instance : second_countable_topology α) _ _
end order_topology
lemma borel_comap {f : α → β} {t : topological_space β} :
@borel α (t.induced f) = (@borel β t).comap f :=
comap_generate_from.symm
lemma continuous.borel_measurable [topological_space α] [topological_space β]
{f : α → β} (hf : continuous f) :
@measurable α β (borel α) (borel β) f :=
measurable.of_le_map $ generate_from_le $
λ s hs, generate_measurable.basic (f ⁻¹' s) (hs.preimage hf)
/-- A space with `measurable_space` and `topological_space` structures such that
all open sets are measurable. -/
class opens_measurable_space (α : Type*) [topological_space α] [h : measurable_space α] : Prop :=
(borel_le : borel α ≤ h)
/-- A space with `measurable_space` and `topological_space` structures such that
the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/
class borel_space (α : Type*) [topological_space α] [measurable_space α] : Prop :=
(measurable_eq : ‹measurable_space α› = borel α)
/-- In a `borel_space` all open sets are measurable. -/
@[priority 100]
instance borel_space.opens_measurable {α : Type*} [topological_space α] [measurable_space α]
[borel_space α] : opens_measurable_space α :=
⟨ge_of_eq $ borel_space.measurable_eq⟩
instance subtype.borel_space {α : Type*} [topological_space α] [measurable_space α]
[hα : borel_space α] (s : set α) :
borel_space s :=
⟨by { rw [hα.1, subtype.measurable_space, ← borel_comap], refl }⟩
instance subtype.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α]
[h : opens_measurable_space α] (s : set α) :
opens_measurable_space s :=
⟨by { rw [borel_comap], exact comap_mono h.1 }⟩
section
variables [topological_space α] [measurable_space α] [opens_measurable_space α]
[topological_space β] [measurable_space β] [opens_measurable_space β]
[topological_space γ] [measurable_space γ] [borel_space γ]
[topological_space γ₂] [measurable_space γ₂] [borel_space γ₂]
[measurable_space δ]
lemma is_open.measurable_set (h : is_open s) : measurable_set s :=
opens_measurable_space.borel_le _ $ generate_measurable.basic _ h
@[measurability]
lemma measurable_set_interior : measurable_set (interior s) := is_open_interior.measurable_set
lemma is_Gδ.measurable_set (h : is_Gδ s) : measurable_set s :=
begin
rcases h with ⟨S, hSo, hSc, rfl⟩,
exact measurable_set.sInter hSc (λ t ht, (hSo t ht).measurable_set)
end
lemma measurable_set_of_continuous_at {β} [emetric_space β] (f : α → β) :
measurable_set {x | continuous_at f x} :=
(is_Gδ_set_of_continuous_at f).measurable_set
lemma is_closed.measurable_set (h : is_closed s) : measurable_set s :=
h.is_open_compl.measurable_set.of_compl
lemma is_compact.measurable_set [t2_space α] (h : is_compact s) : measurable_set s :=
h.is_closed.measurable_set
@[measurability]
lemma measurable_set_closure : measurable_set (closure s) :=
is_closed_closure.measurable_set
lemma measurable_of_is_open {f : δ → γ} (hf : ∀ s, is_open s → measurable_set (f ⁻¹' s)) :
measurable f :=
by { rw [‹borel_space γ›.measurable_eq], exact measurable_generate_from hf }
lemma measurable_of_is_closed {f : δ → γ} (hf : ∀ s, is_closed s → measurable_set (f ⁻¹' s)) :
measurable f :=
begin
apply measurable_of_is_open, intros s hs,
rw [← measurable_set.compl_iff, ← preimage_compl], apply hf, rw [is_closed_compl_iff], exact hs
end
lemma measurable_of_is_closed' {f : δ → γ}
(hf : ∀ s, is_closed s → s.nonempty → s ≠ univ → measurable_set (f ⁻¹' s)) : measurable f :=
begin
apply measurable_of_is_closed, intros s hs,
cases eq_empty_or_nonempty s with h1 h1, { simp [h1] },
by_cases h2 : s = univ, { simp [h2] },
exact hf s hs h1 h2
end
instance nhds_is_measurably_generated (a : α) : (𝓝 a).is_measurably_generated :=
begin
rw [nhds, infi_subtype'],
refine @filter.infi_is_measurably_generated _ _ _ _ (λ i, _),
exact i.2.2.measurable_set.principal_is_measurably_generated
end
/-- If `s` is a measurable set, then `𝓝[s] a` is a measurably generated filter for
each `a`. This cannot be an `instance` because it depends on a non-instance `hs : measurable_set s`.
-/
lemma measurable_set.nhds_within_is_measurably_generated {s : set α} (hs : measurable_set s)
(a : α) :
(𝓝[s] a).is_measurably_generated :=
by haveI := hs.principal_is_measurably_generated; exact filter.inf_is_measurably_generated _ _
@[priority 100] -- see Note [lower instance priority]
instance opens_measurable_space.to_measurable_singleton_class [t1_space α] :
measurable_singleton_class α :=
⟨λ x, is_closed_singleton.measurable_set⟩
instance pi.opens_measurable_space {ι : Type*} {π : ι → Type*} [fintype ι]
[t' : Π i, topological_space (π i)]
[Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)]
[∀ i, opens_measurable_space (π i)] :
opens_measurable_space (Π i, π i) :=
begin
constructor,
have : Pi.topological_space =
generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ countable_basis (π a)) ∧
t = pi ↑i s},
{ rw [funext (λ a, @eq_generate_from_countable_basis (π a) _ _), pi_generate_from_eq] },
rw [borel_eq_generate_from_of_subbasis this],
apply generate_from_le,
rintros _ ⟨s, i, hi, rfl⟩,
refine measurable_set.pi i.countable_to_set (λ a ha, is_open.measurable_set _),
rw [eq_generate_from_countable_basis (π a)],
exact generate_open.basic _ (hi a ha)
end
instance prod.opens_measurable_space [second_countable_topology α] [second_countable_topology β] :
opens_measurable_space (α × β) :=
begin
constructor,
rw [((is_basis_countable_basis α).prod (is_basis_countable_basis β)).borel_eq_generate_from],
apply generate_from_le,
rintros _ ⟨u, v, hu, hv, rfl⟩,
exact (is_open_of_mem_countable_basis hu).measurable_set.prod
(is_open_of_mem_countable_basis hv).measurable_set
end
variables {α' : Type*} [topological_space α'] [measurable_space α']
lemma meas_interior_of_null_bdry {μ : measure α'} {s : set α'}
(h_nullbdry : μ (frontier s) = 0) : μ (interior s) = μ s :=
meas_eq_meas_smaller_of_between_null_diff
interior_subset subset_closure h_nullbdry
lemma meas_closure_of_null_bdry {μ : measure α'} {s : set α'}
(h_nullbdry : μ (frontier s) = 0) : μ (closure s) = μ s :=
(meas_eq_meas_larger_of_between_null_diff
interior_subset subset_closure h_nullbdry).symm
section preorder
variables [preorder α] [order_closed_topology α] {a b : α}
@[simp, measurability]
lemma measurable_set_Ici : measurable_set (Ici a) := is_closed_Ici.measurable_set
@[simp, measurability]
lemma measurable_set_Iic : measurable_set (Iic a) := is_closed_Iic.measurable_set
@[simp, measurability]
lemma measurable_set_Icc : measurable_set (Icc a b) := is_closed_Icc.measurable_set
instance nhds_within_Ici_is_measurably_generated :
(𝓝[Ici b] a).is_measurably_generated :=
measurable_set_Ici.nhds_within_is_measurably_generated _
instance nhds_within_Iic_is_measurably_generated :
(𝓝[Iic b] a).is_measurably_generated :=
measurable_set_Iic.nhds_within_is_measurably_generated _
instance at_top_is_measurably_generated : (filter.at_top : filter α).is_measurably_generated :=
@filter.infi_is_measurably_generated _ _ _ _ $
λ a, (measurable_set_Ici : measurable_set (Ici a)).principal_is_measurably_generated
instance at_bot_is_measurably_generated : (filter.at_bot : filter α).is_measurably_generated :=
@filter.infi_is_measurably_generated _ _ _ _ $
λ a, (measurable_set_Iic : measurable_set (Iic a)).principal_is_measurably_generated
end preorder
section partial_order
variables [partial_order α] [order_closed_topology α] [second_countable_topology α]
{a b : α}
@[measurability]
lemma measurable_set_le' : measurable_set {p : α × α | p.1 ≤ p.2} :=
order_closed_topology.is_closed_le'.measurable_set
@[measurability]
lemma measurable_set_le {f g : δ → α} (hf : measurable f) (hg : measurable g) :
measurable_set {a | f a ≤ g a} :=
hf.prod_mk hg measurable_set_le'
end partial_order
section linear_order
variables [linear_order α] [order_closed_topology α] {a b : α}
@[simp, measurability]
lemma measurable_set_Iio : measurable_set (Iio a) := is_open_Iio.measurable_set
@[simp, measurability]
lemma measurable_set_Ioi : measurable_set (Ioi a) := is_open_Ioi.measurable_set
@[simp, measurability]
lemma measurable_set_Ioo : measurable_set (Ioo a b) := is_open_Ioo.measurable_set
@[simp, measurability] lemma measurable_set_Ioc : measurable_set (Ioc a b) :=
measurable_set_Ioi.inter measurable_set_Iic
@[simp, measurability] lemma measurable_set_Ico : measurable_set (Ico a b) :=
measurable_set_Ici.inter measurable_set_Iio
instance nhds_within_Ioi_is_measurably_generated :
(𝓝[Ioi b] a).is_measurably_generated :=
measurable_set_Ioi.nhds_within_is_measurably_generated _
instance nhds_within_Iio_is_measurably_generated :
(𝓝[Iio b] a).is_measurably_generated :=
measurable_set_Iio.nhds_within_is_measurably_generated _
@[measurability]
lemma measurable_set_lt' [second_countable_topology α] : measurable_set {p : α × α | p.1 < p.2} :=
(is_open_lt continuous_fst continuous_snd).measurable_set
@[measurability]
lemma measurable_set_lt [second_countable_topology α] {f g : δ → α} (hf : measurable f)
(hg : measurable g) : measurable_set {a | f a < g a} :=
hf.prod_mk hg measurable_set_lt'
lemma set.ord_connected.measurable_set (h : ord_connected s) : measurable_set s :=
begin
let u := ⋃ (x ∈ s) (y ∈ s), Ioo x y,
have huopen : is_open u := is_open_bUnion (λ x hx, is_open_bUnion (λ y hy, is_open_Ioo)),
have humeas : measurable_set u := huopen.measurable_set,
have hfinite : (s \ u).finite,
{ refine set.finite_of_forall_between_eq_endpoints (s \ u) (λ x hx y hy z hz hxy hyz, _),
by_contra h,
push_neg at h,
exact hy.2 (mem_bUnion_iff.mpr ⟨x, hx.1,
mem_bUnion_iff.mpr ⟨z, hz.1, lt_of_le_of_ne hxy h.1, lt_of_le_of_ne hyz h.2⟩⟩) },
have : u ⊆ s :=
bUnion_subset (λ x hx, bUnion_subset (λ y hy, Ioo_subset_Icc_self.trans (h.out hx hy))),
rw ← union_diff_cancel this,
exact humeas.union hfinite.measurable_set
end
lemma is_preconnected.measurable_set
(h : is_preconnected s) : measurable_set s :=
h.ord_connected.measurable_set
end linear_order
section linear_order
variables [linear_order α] [order_closed_topology α]
@[measurability]
lemma measurable_set_interval {a b : α} : measurable_set (interval a b) :=
measurable_set_Icc
variables [second_countable_topology α]
@[measurability]
lemma measurable.max {f g : δ → α} (hf : measurable f) (hg : measurable g) :
measurable (λ a, max (f a) (g a)) :=
hf.piecewise (measurable_set_le hg hf) hg
@[measurability]
lemma ae_measurable.max {f g : δ → α} {μ : measure δ}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, max (f a) (g a)) μ :=
⟨λ a, max (hf.mk f a) (hg.mk g a), hf.measurable_mk.max hg.measurable_mk,
eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩
@[measurability]
lemma measurable.min {f g : δ → α} (hf : measurable f) (hg : measurable g) :
measurable (λ a, min (f a) (g a)) :=
hf.piecewise (measurable_set_le hf hg) hg
@[measurability]
lemma ae_measurable.min {f g : δ → α} {μ : measure δ}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, min (f a) (g a)) μ :=
⟨λ a, min (hf.mk f a) (hg.mk g a), hf.measurable_mk.min hg.measurable_mk,
eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩
end linear_order
/-- A continuous function from an `opens_measurable_space` to a `borel_space`
is measurable. -/
lemma continuous.measurable {f : α → γ} (hf : continuous f) :
measurable f :=
hf.borel_measurable.mono opens_measurable_space.borel_le
(le_of_eq $ borel_space.measurable_eq)
/-- A continuous function from an `opens_measurable_space` to a `borel_space`
is ae-measurable. -/
lemma continuous.ae_measurable {f : α → γ} (h : continuous f) (μ : measure α) : ae_measurable f μ :=
h.measurable.ae_measurable
lemma closed_embedding.measurable {f : α → γ} (hf : closed_embedding f) :
measurable f :=
hf.continuous.measurable
@[priority 100, to_additive]
instance has_continuous_mul.has_measurable_mul [has_mul γ] [has_continuous_mul γ] :
has_measurable_mul γ :=
{ measurable_const_mul := λ c, (continuous_const.mul continuous_id).measurable,
measurable_mul_const := λ c, (continuous_id.mul continuous_const).measurable }
@[priority 100]
instance has_continuous_sub.has_measurable_sub [has_sub γ] [has_continuous_sub γ] :
has_measurable_sub γ :=
{ measurable_const_sub := λ c, (continuous_const.sub continuous_id).measurable,
measurable_sub_const := λ c, (continuous_id.sub continuous_const).measurable }
@[priority 100, to_additive]
instance topological_group.has_measurable_inv [group γ] [topological_group γ] :
has_measurable_inv γ :=
⟨continuous_inv.measurable⟩
@[priority 100]
instance has_continuous_smul.has_measurable_smul {M α} [topological_space M]
[topological_space α] [measurable_space M] [measurable_space α]
[opens_measurable_space M] [borel_space α] [has_scalar M α] [has_continuous_smul M α] :
has_measurable_smul M α :=
⟨λ c, (continuous_const.smul continuous_id).measurable,
λ y, (continuous_id.smul continuous_const).measurable⟩
section homeomorph
/-- A homeomorphism between two Borel spaces is a measurable equivalence.-/
def homeomorph.to_measurable_equiv (h : γ ≃ₜ γ₂) : γ ≃ᵐ γ₂ :=
{ measurable_to_fun := h.continuous_to_fun.measurable,
measurable_inv_fun := h.continuous_inv_fun.measurable,
.. h }
@[simp]
lemma homeomorph.to_measurable_equiv_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv : γ → γ₂) = h :=
rfl
@[simp] lemma homeomorph.to_measurable_equiv_symm_coe (h : γ ≃ₜ γ₂) :
(h.to_measurable_equiv.symm : γ₂ → γ) = h.symm :=
rfl
@[measurability]
lemma homeomorph.measurable (h : α ≃ₜ γ) : measurable h :=
h.continuous.measurable
end homeomorph
lemma measurable_of_continuous_on_compl_singleton [t1_space α] {f : α → γ} (a : α)
(hf : continuous_on f {a}ᶜ) :
measurable f :=
measurable_of_measurable_on_compl_singleton a
(continuous_on_iff_continuous_restrict.1 hf).measurable
lemma continuous.measurable2 [second_countable_topology α] [second_countable_topology β]
{f : δ → α} {g : δ → β} {c : α → β → γ}
(h : continuous (λ p : α × β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) :
measurable (λ a, c (f a) (g a)) :=
h.measurable.comp (hf.prod_mk hg)
lemma continuous.ae_measurable2 [second_countable_topology α] [second_countable_topology β]
{f : δ → α} {g : δ → β} {c : α → β → γ} {μ : measure δ}
(h : continuous (λ p : α × β, c p.1 p.2)) (hf : ae_measurable f μ) (hg : ae_measurable g μ) :
ae_measurable (λ a, c (f a) (g a)) μ :=
h.measurable.comp_ae_measurable (hf.prod_mk hg)
@[priority 100]
instance has_continuous_inv'.has_measurable_inv [group_with_zero γ] [t1_space γ]
[has_continuous_inv' γ] :
has_measurable_inv γ :=
⟨measurable_of_continuous_on_compl_singleton 0 continuous_on_inv'⟩
@[priority 100, to_additive]
instance has_continuous_mul.has_measurable_mul₂ [second_countable_topology γ] [has_mul γ]
[has_continuous_mul γ] : has_measurable_mul₂ γ :=
⟨continuous_mul.measurable⟩
@[priority 100]
instance has_continuous_sub.has_measurable_sub₂ [second_countable_topology γ] [has_sub γ]
[has_continuous_sub γ] : has_measurable_sub₂ γ :=
⟨continuous_sub.measurable⟩
@[priority 100]
instance has_continuous_smul.has_measurable_smul₂ {M α} [topological_space M]
[second_countable_topology M] [measurable_space M] [opens_measurable_space M]
[topological_space α] [second_countable_topology α] [measurable_space α]
[borel_space α] [has_scalar M α] [has_continuous_smul M α] :
has_measurable_smul₂ M α :=
⟨continuous_smul.measurable⟩
end
section borel_space
variables [topological_space α] [measurable_space α] [borel_space α]
[topological_space β] [measurable_space β] [borel_space β]
[topological_space γ] [measurable_space γ] [borel_space γ]
[measurable_space δ]
lemma pi_le_borel_pi {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)]
[Π i, measurable_space (π i)] [∀ i, borel_space (π i)] :
measurable_space.pi ≤ borel (Π i, π i) :=
begin
have : ‹Π i, measurable_space (π i)› = λ i, borel (π i) :=
funext (λ i, borel_space.measurable_eq),
rw [this],
exact supr_le (λ i, comap_le_iff_le_map.2 $ (continuous_apply i).borel_measurable)
end
lemma prod_le_borel_prod : prod.measurable_space ≤ borel (α × β) :=
begin
rw [‹borel_space α›.measurable_eq, ‹borel_space β›.measurable_eq],
refine sup_le _ _,
{ exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable },
{ exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable }
end
instance pi.borel_space {ι : Type*} {π : ι → Type*} [fintype ι]
[t' : Π i, topological_space (π i)]
[Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)]
[∀ i, borel_space (π i)] :
borel_space (Π i, π i) :=
⟨le_antisymm pi_le_borel_pi opens_measurable_space.borel_le⟩
instance prod.borel_space [second_countable_topology α] [second_countable_topology β] :
borel_space (α × β) :=
⟨le_antisymm prod_le_borel_prod opens_measurable_space.borel_le⟩
lemma closed_embedding.measurable_inv_fun [n : nonempty β] {g : β → γ} (hg : closed_embedding g) :
measurable (function.inv_fun g) :=
begin
refine measurable_of_is_closed (λ s hs, _),
by_cases h : classical.choice n ∈ s,
{ rw preimage_inv_fun_of_mem hg.to_embedding.inj h,
exact (hg.closed_iff_image_closed.mp hs).measurable_set.union
hg.closed_range.measurable_set.compl },
{ rw preimage_inv_fun_of_not_mem hg.to_embedding.inj h,
exact (hg.closed_iff_image_closed.mp hs).measurable_set }
end
lemma measurable_comp_iff_of_closed_embedding {f : δ → β} (g : β → γ) (hg : closed_embedding g) :
measurable (g ∘ f) ↔ measurable f :=
begin
refine ⟨λ hf, _, λ hf, hg.measurable.comp hf⟩,
apply measurable_of_is_closed, intros s hs,
convert hf (hg.is_closed_map s hs).measurable_set,
rw [@preimage_comp _ _ _ f g, preimage_image_eq _ hg.to_embedding.inj]
end
lemma ae_measurable_comp_iff_of_closed_embedding {f : δ → β} {μ : measure δ}
(g : β → γ) (hg : closed_embedding g) : ae_measurable (g ∘ f) μ ↔ ae_measurable f μ :=
begin
casesI is_empty_or_nonempty β,
{ haveI := function.is_empty f,
simp only [(measurable_of_empty (g ∘ f)).ae_measurable,
(measurable_of_empty f).ae_measurable] },
{ refine ⟨λ hf, _, λ hf, hg.measurable.comp_ae_measurable hf⟩,
convert hg.measurable_inv_fun.comp_ae_measurable hf,
ext x,
exact (function.left_inverse_inv_fun hg.to_embedding.inj (f x)).symm },
end
lemma ae_measurable_comp_right_iff_of_closed_embedding {g : α → β} {μ : measure α}
{f : β → δ} (hg : closed_embedding g) :
ae_measurable (f ∘ g) μ ↔ ae_measurable f (measure.map g μ) :=
begin
refine ⟨λ h, _, λ h, h.comp_measurable hg.measurable⟩,
casesI is_empty_or_nonempty α, { simp [μ.eq_zero_of_is_empty] },
refine ⟨(h.mk _) ∘ (function.inv_fun g), h.measurable_mk.comp hg.measurable_inv_fun, _⟩,
have : μ = measure.map (function.inv_fun g) (measure.map g μ),
by rw [measure.map_map hg.measurable_inv_fun hg.measurable,
(function.left_inverse_inv_fun hg.to_embedding.inj).comp_eq_id, measure.map_id],
rw this at h,
filter_upwards [ae_of_ae_map hg.measurable_inv_fun h.ae_eq_mk,
ae_map_mem_range g hg.closed_range.measurable_set μ],
assume x hx₁ hx₂,
convert hx₁,
exact ((function.left_inverse_inv_fun hg.to_embedding.inj).right_inv_on_range hx₂).symm,
end
section linear_order
variables [linear_order α] [order_topology α] [second_countable_topology α]
lemma measurable_of_Iio {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iio x)) : measurable f :=
begin
convert measurable_generate_from _,
exact borel_space.measurable_eq.trans (borel_eq_generate_Iio _),
rintro _ ⟨x, rfl⟩, exact hf x
end
lemma upper_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ]
{f : δ → α} (hf : upper_semicontinuous f) : measurable f :=
measurable_of_Iio (λ y, (hf.is_open_preimage y).measurable_set)
lemma measurable_of_Ioi {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ioi x)) : measurable f :=
begin
convert measurable_generate_from _,
exact borel_space.measurable_eq.trans (borel_eq_generate_Ioi _),
rintro _ ⟨x, rfl⟩, exact hf x
end
lemma lower_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ]
{f : δ → α} (hf : lower_semicontinuous f) : measurable f :=
measurable_of_Ioi (λ y, (hf.is_open_preimage y).measurable_set)
lemma measurable_of_Iic {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iic x)) : measurable f :=
begin
apply measurable_of_Ioi,
simp_rw [← compl_Iic, preimage_compl, measurable_set.compl_iff],
assumption
end
lemma measurable_of_Ici {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ici x)) : measurable f :=
begin
apply measurable_of_Iio,
simp_rw [← compl_Ici, preimage_compl, measurable_set.compl_iff],
assumption
end
lemma measurable.is_lub {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i))
(hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) :
measurable g :=
begin
change ∀ b, is_lub (range $ λ i, f i b) (g b) at hg,
rw [‹borel_space α›.measurable_eq, borel_eq_generate_Ioi α],
apply measurable_generate_from,
rintro _ ⟨a, rfl⟩,
simp_rw [set.preimage, mem_Ioi, lt_is_lub_iff (hg _), exists_range_iff, set_of_exists],
exact measurable_set.Union (λ i, hf i (is_open_lt' _).measurable_set)
end
private lemma ae_measurable.is_lub_of_nonempty {ι} (hι : nonempty ι)
{μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α}
(hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) :
ae_measurable g μ :=
begin
let p : δ → (ι → α) → Prop := λ x f', is_lub {a | ∃ i, f' i = a} (g x),
let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some,
have hg_seq : ∀ b, is_lub {a | ∃ i, ae_seq hf p i b = a} (g_seq b),
{ intro b,
haveI hα : nonempty α := nonempty.map g ⟨b⟩,
simp only [ae_seq, g_seq],
split_ifs,
{ have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a},
{ ext x,
simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], },
rw h_set_eq,
exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, },
{ have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some},
{ ext1 x,
exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, },
rw h_singleton,
exact is_lub_singleton, }, },
refine ⟨g_seq, measurable.is_lub (ae_seq.measurable hf p) hg_seq, _⟩,
exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p)
(ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm,
end
lemma ae_measurable.is_lub {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α}
(hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) :
ae_measurable g μ :=
begin
by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure },
haveI : μ.ae.ne_bot, { simpa [ne_bot_iff] },
by_cases hι : nonempty ι, { exact ae_measurable.is_lub_of_nonempty hι hf hg, },
suffices : ∃ x, g =ᵐ[μ] λ y, g x,
by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, },
have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅,
{ intro x,
ext1 y,
rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false],
exact λ hi, hι (nonempty_of_exists hi), },
simp_rw h_empty at hg,
exact ⟨hg.exists.some, hg.mono (λ y hy, is_lub.unique hy hg.exists.some_spec)⟩,
end
lemma measurable.is_glb {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i))
(hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) :
measurable g :=
begin
change ∀ b, is_glb (range $ λ i, f i b) (g b) at hg,
rw [‹borel_space α›.measurable_eq, borel_eq_generate_Iio α],
apply measurable_generate_from,
rintro _ ⟨a, rfl⟩,
simp_rw [set.preimage, mem_Iio, is_glb_lt_iff (hg _), exists_range_iff, set_of_exists],
exact measurable_set.Union (λ i, hf i (is_open_gt' _).measurable_set)
end
private lemma ae_measurable.is_glb_of_nonempty {ι} (hι : nonempty ι)
{μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α}
(hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) :
ae_measurable g μ :=
begin
let p : δ → (ι → α) → Prop := λ x f', is_glb {a | ∃ i, f' i = a} (g x),
let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some,
have hg_seq : ∀ b, is_glb {a | ∃ i, ae_seq hf p i b = a} (g_seq b),
{ intro b,
haveI hα : nonempty α := nonempty.map g ⟨b⟩,
simp only [ae_seq, g_seq],
split_ifs,
{ have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a},
{ ext x,
simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], },
rw h_set_eq,
exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, },
{ have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some},
{ ext1 x,
exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, },
rw h_singleton,
exact is_glb_singleton, }, },
refine ⟨g_seq, measurable.is_glb (ae_seq.measurable hf p) hg_seq, _⟩,
exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p)
(ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm,
end
lemma ae_measurable.is_glb {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α}
(hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) :
ae_measurable g μ :=
begin
by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure },
haveI : μ.ae.ne_bot, { simpa [ne_bot_iff] },
by_cases hι : nonempty ι, { exact ae_measurable.is_glb_of_nonempty hι hf hg, },
suffices : ∃ x, g =ᵐ[μ] λ y, g x,
by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, },
have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅,
{ intro x,
ext1 y,
rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false],
exact λ hi, hι (nonempty_of_exists hi), },
simp_rw h_empty at hg,
exact ⟨hg.exists.some, hg.mono (λ y hy, is_glb.unique hy hg.exists.some_spec)⟩,
end
lemma measurable_of_monotone [linear_order β] [order_closed_topology β] {f : β → α}
(hf : monotone f) : measurable f :=
suffices h : ∀ x, ord_connected (f ⁻¹' Ioi x),
from measurable_of_Ioi (λ x, (h x).measurable_set),
λ x, ord_connected_def.mpr (λ a ha b hb c hc, lt_of_lt_of_le ha (hf hc.1))
alias measurable_of_monotone ← monotone.measurable
lemma ae_measurable_restrict_of_monotone_on [linear_order β] [order_closed_topology β]
{μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α}
(hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → x ≤ y → f x ≤ f y) : ae_measurable f (μ.restrict s) :=
have this : monotone (f ∘ coe : s → α), from λ ⟨x, hx⟩ ⟨y, hy⟩ (hxy : x ≤ y), hf hx hy hxy,
ae_measurable_restrict_of_measurable_subtype hs this.measurable
lemma measurable_of_antimono [linear_order β] [order_closed_topology β] {f : β → α}
(hf : ∀ ⦃x y : β⦄, x ≤ y → f y ≤ f x) :
measurable f :=
@measurable_of_monotone (order_dual α) β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ hf
lemma ae_measurable_restrict_of_antimono_on [linear_order β] [order_closed_topology β]
{μ : measure β} {s : set β} (hs : measurable_set s) {f : β → α}
(hf : ∀ ⦃x y⦄, x ∈ s → y ∈ s → x ≤ y → f y ≤ f x) : ae_measurable f (μ.restrict s) :=
@ae_measurable_restrict_of_monotone_on (order_dual α) β _ _ ‹_› _ _ _ _ _ ‹_› _ _ _ _ hs _ hf
end linear_order
@[measurability]
lemma measurable.supr_Prop {α} [measurable_space α] [complete_lattice α]
(p : Prop) {f : δ → α} (hf : measurable f) :
measurable (λ b, ⨆ h : p, f b) :=
classical.by_cases
(assume h : p, begin convert hf, funext, exact supr_pos h end)
(assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end)
@[measurability]
lemma measurable.infi_Prop {α} [measurable_space α] [complete_lattice α]
(p : Prop) {f : δ → α} (hf : measurable f) :
measurable (λ b, ⨅ h : p, f b) :=
classical.by_cases
(assume h : p, begin convert hf, funext, exact infi_pos h end )
(assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end)
section complete_linear_order
variables [complete_linear_order α] [order_topology α] [second_countable_topology α]
@[measurability]
lemma measurable_supr {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) :
measurable (λ b, ⨆ i, f i b) :=
measurable.is_lub hf $ λ b, is_lub_supr
@[measurability]
lemma ae_measurable_supr {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α}
(hf : ∀ i, ae_measurable (f i) μ) :
ae_measurable (λ b, ⨆ i, f i b) μ :=
ae_measurable.is_lub hf $ (ae_of_all μ (λ b, is_lub_supr))
@[measurability]
lemma measurable_infi {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) :
measurable (λ b, ⨅ i, f i b) :=
measurable.is_glb hf $ λ b, is_glb_infi
@[measurability]
lemma ae_measurable_infi {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α}
(hf : ∀ i, ae_measurable (f i) μ) :
ae_measurable (λ b, ⨅ i, f i b) μ :=
ae_measurable.is_glb hf $ (ae_of_all μ (λ b, is_glb_infi))
lemma measurable_bsupr {ι} (s : set ι) {f : ι → δ → α} (hs : countable s)
(hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i ∈ s, f i b) :=
by { haveI : encodable s := hs.to_encodable, simp only [supr_subtype'],
exact measurable_supr (λ i, hf i) }
lemma ae_measurable_bsupr {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s)
(hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i ∈ s, f i b) μ :=
begin
haveI : encodable s := hs.to_encodable,
simp only [supr_subtype'],
exact ae_measurable_supr (λ i, hf i),
end
lemma measurable_binfi {ι} (s : set ι) {f : ι → δ → α} (hs : countable s)
(hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i ∈ s, f i b) :=
by { haveI : encodable s := hs.to_encodable, simp only [infi_subtype'],
exact measurable_infi (λ i, hf i) }
lemma ae_measurable_binfi {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s)
(hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i ∈ s, f i b) μ :=
begin
haveI : encodable s := hs.to_encodable,
simp only [infi_subtype'],
exact ae_measurable_infi (λ i, hf i),
end
/-- `liminf` over a general filter is measurable. See `measurable_liminf` for the version over `ℕ`.
-/
lemma measurable_liminf' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i))
{p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) :
measurable (λ x, liminf u (λ i, f i x)) :=
begin
simp_rw [hu.to_has_basis.liminf_eq_supr_infi],
refine measurable_bsupr _ hu.countable _,
exact λ i, measurable_binfi _ (hs i) hf
end
/-- `limsup` over a general filter is measurable. See `measurable_limsup` for the version over `ℕ`.
-/
lemma measurable_limsup' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i))
{p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) :
measurable (λ x, limsup u (λ i, f i x)) :=
begin
simp_rw [hu.to_has_basis.limsup_eq_infi_supr],
refine measurable_binfi _ hu.countable _,
exact λ i, measurable_bsupr _ (hs i) hf
end
/-- `liminf` over `ℕ` is measurable. See `measurable_liminf'` for a version with a general filter.
-/
@[measurability]
lemma measurable_liminf {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) :
measurable (λ x, liminf at_top (λ i, f i x)) :=
measurable_liminf' hf at_top_countable_basis (λ i, countable_encodable _)
/-- `limsup` over `ℕ` is measurable. See `measurable_limsup'` for a version with a general filter.
-/
@[measurability]
lemma measurable_limsup {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) :
measurable (λ x, limsup at_top (λ i, f i x)) :=
measurable_limsup' hf at_top_countable_basis (λ i, countable_encodable _)
end complete_linear_order
section conditionally_complete_linear_order
variables [conditionally_complete_linear_order α] [order_topology α] [second_countable_topology α]
lemma measurable_cSup {ι} {f : ι → δ → α} {s : set ι} (hs : s.countable)
(hf : ∀ i, measurable (f i)) (bdd : ∀ x, bdd_above ((λ i, f i x) '' s)) :
measurable (λ x, Sup ((λ i, f i x) '' s)) :=
begin
cases eq_empty_or_nonempty s with h2s h2s,
{ simp [h2s, measurable_const] },
{ apply measurable_of_Iic, intro y,
simp_rw [preimage, mem_Iic, cSup_le_iff (bdd _) (h2s.image _), ball_image_iff, set_of_forall],
exact measurable_set.bInter hs (λ i hi, measurable_set_le (hf i) measurable_const) }
end
end conditionally_complete_linear_order
/-- Convert a `homeomorph` to a `measurable_equiv`. -/
def homemorph.to_measurable_equiv (h : α ≃ₜ β) : α ≃ᵐ β :=
{ to_equiv := h.to_equiv,
measurable_to_fun := h.continuous_to_fun.measurable,
measurable_inv_fun := h.continuous_inv_fun.measurable }
end borel_space
instance empty.borel_space : borel_space empty := ⟨borel_eq_top_of_discrete.symm⟩
instance unit.borel_space : borel_space unit := ⟨borel_eq_top_of_discrete.symm⟩
instance bool.borel_space : borel_space bool := ⟨borel_eq_top_of_discrete.symm⟩
instance nat.borel_space : borel_space ℕ := ⟨borel_eq_top_of_discrete.symm⟩
instance int.borel_space : borel_space ℤ := ⟨borel_eq_top_of_discrete.symm⟩
instance rat.borel_space : borel_space ℚ := ⟨borel_eq_top_of_encodable.symm⟩
instance real.measurable_space : measurable_space ℝ := borel ℝ
instance real.borel_space : borel_space ℝ := ⟨rfl⟩
instance nnreal.measurable_space : measurable_space ℝ≥0 := subtype.measurable_space
instance nnreal.borel_space : borel_space ℝ≥0 := subtype.borel_space _
instance ennreal.measurable_space : measurable_space ℝ≥0∞ := borel ℝ≥0∞
instance ennreal.borel_space : borel_space ℝ≥0∞ := ⟨rfl⟩
instance ereal.measurable_space : measurable_space ereal := borel ereal
instance ereal.borel_space : borel_space ereal := ⟨rfl⟩
instance complex.measurable_space : measurable_space ℂ := borel ℂ
instance complex.borel_space : borel_space ℂ := ⟨rfl⟩
section metric_space
variables [metric_space α] [measurable_space α] [opens_measurable_space α]
variables [measurable_space β] {x : α} {ε : ℝ}
open metric
@[measurability]
lemma measurable_set_ball : measurable_set (metric.ball x ε) :=
metric.is_open_ball.measurable_set
@[measurability]
lemma measurable_set_closed_ball : measurable_set (metric.closed_ball x ε) :=
metric.is_closed_ball.measurable_set
@[measurability]
lemma measurable_inf_dist {s : set α} : measurable (λ x, inf_dist x s) :=
(continuous_inf_dist_pt s).measurable
@[measurability]
lemma measurable.inf_dist {f : β → α} (hf : measurable f) {s : set α} :
measurable (λ x, inf_dist (f x) s) :=
measurable_inf_dist.comp hf
@[measurability]
lemma measurable_inf_nndist {s : set α} : measurable (λ x, inf_nndist x s) :=
(continuous_inf_nndist_pt s).measurable
@[measurability]
lemma measurable.inf_nndist {f : β → α} (hf : measurable f) {s : set α} :
measurable (λ x, inf_nndist (f x) s) :=
measurable_inf_nndist.comp hf
variables [second_countable_topology α]
@[measurability]
lemma measurable_dist : measurable (λ p : α × α, dist p.1 p.2) :=
continuous_dist.measurable
@[measurability]
lemma measurable.dist {f g : β → α} (hf : measurable f) (hg : measurable g) :
measurable (λ b, dist (f b) (g b)) :=
(@continuous_dist α _).measurable2 hf hg
@[measurability]
lemma measurable_nndist : measurable (λ p : α × α, nndist p.1 p.2) :=
continuous_nndist.measurable
@[measurability]
lemma measurable.nndist {f g : β → α} (hf : measurable f) (hg : measurable g) :
measurable (λ b, nndist (f b) (g b)) :=
(@continuous_nndist α _).measurable2 hf hg
end metric_space
section emetric_space
variables [emetric_space α] [measurable_space α] [opens_measurable_space α]
variables [measurable_space β] {x : α} {ε : ℝ≥0∞}
open emetric
@[measurability]
lemma measurable_set_eball : measurable_set (emetric.ball x ε) :=
emetric.is_open_ball.measurable_set
@[measurability]
lemma measurable_edist_right : measurable (edist x) :=
(continuous_const.edist continuous_id).measurable
@[measurability]
lemma measurable_edist_left : measurable (λ y, edist y x) :=
(continuous_id.edist continuous_const).measurable
@[measurability]
lemma measurable_inf_edist {s : set α} : measurable (λ x, inf_edist x s) :=
continuous_inf_edist.measurable
@[measurability]
lemma measurable.inf_edist {f : β → α} (hf : measurable f) {s : set α} :
measurable (λ x, inf_edist (f x) s) :=
measurable_inf_edist.comp hf
variables [second_countable_topology α]
@[measurability]
lemma measurable_edist : measurable (λ p : α × α, edist p.1 p.2) :=
continuous_edist.measurable
@[measurability]
lemma measurable.edist {f g : β → α} (hf : measurable f) (hg : measurable g) :
measurable (λ b, edist (f b) (g b)) :=
(@continuous_edist α _).measurable2 hf hg
@[measurability]
lemma ae_measurable.edist {f g : β → α} {μ : measure β}
(hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, edist (f a) (g a)) μ :=
(@continuous_edist α _).ae_measurable2 hf hg
end emetric_space
namespace real
open measurable_space measure_theory
lemma borel_eq_generate_from_Ioo_rat :
borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) :=
is_topological_basis_Ioo_rat.borel_eq_generate_from
lemma is_pi_system_Ioo_rat : @is_pi_system ℝ (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) :=
by simpa using is_pi_system_Ioo (coe : ℚ → ℝ)
/-- The intervals `(-(n + 1), (n + 1))` form a finite spanning sets in the set of open intervals
with rational endpoints for a locally finite measure `μ` on `ℝ`. -/
def finite_spanning_sets_in_Ioo_rat (μ : measure ℝ) [is_locally_finite_measure μ] :
μ.finite_spanning_sets_in (⋃ (a b : ℚ) (h : a < b), {Ioo a b}) :=
{ set := λ n, Ioo (-(n + 1)) (n + 1),
set_mem := λ n,
begin
simp only [mem_Union, mem_singleton_iff],
refine ⟨-(n + 1), n + 1, _, by norm_cast⟩,
exact (neg_nonpos.2 (@nat.cast_nonneg ℚ _ (n + 1))).trans_lt n.cast_add_one_pos
end,
finite := λ n,
calc μ (Ioo _ _) ≤ μ (Icc _ _) : μ.mono Ioo_subset_Icc_self
... < ∞ : is_compact_Icc.is_finite_measure,
spanning := Union_eq_univ_iff.2 $ λ x,
⟨⌊abs x⌋₊, neg_lt.1 ((neg_le_abs_self x).trans_lt (lt_nat_floor_add_one _)),
(le_abs_self x).trans_lt (lt_nat_floor_add_one _)⟩ }
lemma measure_ext_Ioo_rat {μ ν : measure ℝ} [is_locally_finite_measure μ]
(h : ∀ a b : ℚ, μ (Ioo a b) = ν (Ioo a b)) : μ = ν :=
(finite_spanning_sets_in_Ioo_rat μ).ext borel_eq_generate_from_Ioo_rat is_pi_system_Ioo_rat $
by { simp only [mem_Union, mem_singleton_iff], rintro _ ⟨a, b, -, rfl⟩, apply h }
lemma borel_eq_generate_from_Iio_rat :
borel ℝ = generate_from (⋃ a : ℚ, {Iio a}) :=
begin
let g : measurable_space ℝ := generate_from (⋃ a : ℚ, {Iio a}),
apply le_antisymm _ (measurable_space.generate_from_le (λ t, _)),
{ rw borel_eq_generate_from_Ioo_rat,
refine generate_from_le (λ t, _),
simp only [mem_Union, mem_singleton_iff], rintro ⟨a, b, h, rfl⟩,
rw (set.ext (λ x, _) : Ioo (a : ℝ) b = (⋃c>a, (Iio c)ᶜ) ∩ Iio b),
{ have hg : ∀ q : ℚ, g.measurable_set' (Iio q) :=
λ q, generate_measurable.basic (Iio q) (by { simp, exact ⟨_, rfl⟩ }),
refine @measurable_set.inter _ g _ _ _ (hg _),
refine @measurable_set.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _),
exact @measurable_set.compl _ _ g (hg _) },
{ suffices : x < ↑b → (↑a < x ↔ ∃ (i : ℚ), a < i ∧ ↑i ≤ x), by simpa,
refine λ _, ⟨λ h, _, λ ⟨i, hai, hix⟩, (rat.cast_lt.2 hai).trans_le hix⟩,
rcases exists_rat_btwn h with ⟨c, ac, cx⟩,
exact ⟨c, rat.cast_lt.1 ac, cx.le⟩ } },
{ simp only [mem_Union, mem_singleton_iff], rintro ⟨r, rfl⟩, exact measurable_set_Iio }
end
end real
variable [measurable_space α]
@[measurability]
lemma measurable_real_to_nnreal : measurable (real.to_nnreal) :=
nnreal.continuous_of_real.measurable
@[measurability]
lemma measurable.real_to_nnreal {f : α → ℝ} (hf : measurable f) :
measurable (λ x, real.to_nnreal (f x)) :=
measurable_real_to_nnreal.comp hf
@[measurability]
lemma ae_measurable.real_to_nnreal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, real.to_nnreal (f x)) μ :=
measurable_real_to_nnreal.comp_ae_measurable hf
@[measurability]
lemma measurable_coe_nnreal_real : measurable (coe : ℝ≥0 → ℝ) :=
nnreal.continuous_coe.measurable
@[measurability]
lemma measurable.coe_nnreal_real {f : α → ℝ≥0} (hf : measurable f) :
measurable (λ x, (f x : ℝ)) :=
measurable_coe_nnreal_real.comp hf
@[measurability]
lemma ae_measurable.coe_nnreal_real {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, (f x : ℝ)) μ :=
measurable_coe_nnreal_real.comp_ae_measurable hf
@[measurability]
lemma measurable_coe_nnreal_ennreal : measurable (coe : ℝ≥0 → ℝ≥0∞) :=
ennreal.continuous_coe.measurable
@[measurability]
lemma measurable.coe_nnreal_ennreal {f : α → ℝ≥0} (hf : measurable f) :
measurable (λ x, (f x : ℝ≥0∞)) :=
ennreal.continuous_coe.measurable.comp hf
@[measurability]
lemma ae_measurable.coe_nnreal_ennreal {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, (f x : ℝ≥0∞)) μ :=
ennreal.continuous_coe.measurable.comp_ae_measurable hf
@[measurability]
lemma measurable.ennreal_of_real {f : α → ℝ} (hf : measurable f) :
measurable (λ x, ennreal.of_real (f x)) :=
ennreal.continuous_of_real.measurable.comp hf
/-- The set of finite `ℝ≥0∞` numbers is `measurable_equiv` to `ℝ≥0`. -/
def measurable_equiv.ennreal_equiv_nnreal : {r : ℝ≥0∞ | r ≠ ∞} ≃ᵐ ℝ≥0 :=
ennreal.ne_top_homeomorph_nnreal.to_measurable_equiv
namespace ennreal
lemma measurable_of_measurable_nnreal {f : ℝ≥0∞ → α}
(h : measurable (λ p : ℝ≥0, f p)) : measurable f :=
measurable_of_measurable_on_compl_singleton ∞
(measurable_equiv.ennreal_equiv_nnreal.symm.measurable_coe_iff.1 h)
/-- `ℝ≥0∞` is `measurable_equiv` to `ℝ≥0 ⊕ unit`. -/
def ennreal_equiv_sum : ℝ≥0∞ ≃ᵐ ℝ≥0 ⊕ unit :=
{ measurable_to_fun := measurable_of_measurable_nnreal measurable_inl,
measurable_inv_fun := measurable_sum measurable_coe_nnreal_ennreal
(@measurable_const ℝ≥0∞ unit _ _ ∞),
.. equiv.option_equiv_sum_punit ℝ≥0 }
open function (uncurry)
lemma measurable_of_measurable_nnreal_prod [measurable_space β] [measurable_space γ]
{f : ℝ≥0∞ × β → γ} (H₁ : measurable (λ p : ℝ≥0 × β, f (p.1, p.2)))
(H₂ : measurable (λ x, f (∞, x))) :
measurable f :=
let e : ℝ≥0∞ × β ≃ᵐ ℝ≥0 × β ⊕ unit × β :=
(ennreal_equiv_sum.prod_congr (measurable_equiv.refl β)).trans
(measurable_equiv.sum_prod_distrib _ _ _) in
e.symm.measurable_coe_iff.1 $ measurable_sum H₁ (H₂.comp measurable_id.snd)
lemma measurable_of_measurable_nnreal_nnreal [measurable_space β]
{f : ℝ≥0∞ × ℝ≥0∞ → β} (h₁ : measurable (λ p : ℝ≥0 × ℝ≥0, f (p.1, p.2)))
(h₂ : measurable (λ r : ℝ≥0, f (∞, r))) (h₃ : measurable (λ r : ℝ≥0, f (r, ∞))) :
measurable f :=
measurable_of_measurable_nnreal_prod
(measurable_swap_iff.1 $ measurable_of_measurable_nnreal_prod (h₁.comp measurable_swap) h₃)
(measurable_of_measurable_nnreal h₂)
@[measurability]
lemma measurable_of_real : measurable ennreal.of_real :=
ennreal.continuous_of_real.measurable
@[measurability]
lemma measurable_to_real : measurable ennreal.to_real :=
ennreal.measurable_of_measurable_nnreal measurable_coe_nnreal_real
@[measurability]
lemma measurable_to_nnreal : measurable ennreal.to_nnreal :=
ennreal.measurable_of_measurable_nnreal measurable_id
instance : has_measurable_mul₂ ℝ≥0∞ :=
begin
refine ⟨measurable_of_measurable_nnreal_nnreal _ _ _⟩,
{ simp only [← ennreal.coe_mul, measurable_mul.coe_nnreal_ennreal] },
{ simp only [ennreal.top_mul, ennreal.coe_eq_zero],
exact measurable_const.piecewise (measurable_set_singleton _) measurable_const },
{ simp only [ennreal.mul_top, ennreal.coe_eq_zero],
exact measurable_const.piecewise (measurable_set_singleton _) measurable_const }
end
instance : has_measurable_sub₂ ℝ≥0∞ :=
⟨by apply measurable_of_measurable_nnreal_nnreal;
simp [← ennreal.coe_sub, continuous_sub.measurable.coe_nnreal_ennreal]⟩
instance : has_measurable_inv ℝ≥0∞ := ⟨ennreal.continuous_inv.measurable⟩
end ennreal
@[measurability]
lemma measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} (hf : measurable f) :
measurable (λ x, (f x).to_nnreal) :=
ennreal.measurable_to_nnreal.comp hf
@[measurability]
lemma ae_measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, (f x).to_nnreal) μ :=
ennreal.measurable_to_nnreal.comp_ae_measurable hf
lemma measurable_coe_nnreal_ennreal_iff {f : α → ℝ≥0} :
measurable (λ x, (f x : ℝ≥0∞)) ↔ measurable f :=
⟨λ h, h.ennreal_to_nnreal, λ h, h.coe_nnreal_ennreal⟩
@[measurability]
lemma measurable.ennreal_to_real {f : α → ℝ≥0∞} (hf : measurable f) :
measurable (λ x, ennreal.to_real (f x)) :=
ennreal.measurable_to_real.comp hf
@[measurability]
lemma ae_measurable.ennreal_to_real {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, ennreal.to_real (f x)) μ :=
ennreal.measurable_to_real.comp_ae_measurable hf
/-- note: `ℝ≥0∞` can probably be generalized in a future version of this lemma. -/
@[measurability]
lemma measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) :
measurable (λ x, ∑' i, f i x) :=
by { simp_rw [ennreal.tsum_eq_supr_sum], apply measurable_supr,
exact λ s, s.measurable_sum (λ i _, h i) }
@[measurability]
lemma measurable.ennreal_tsum' {ι} [encodable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) :
measurable (∑' i, f i) :=
begin
convert measurable.ennreal_tsum h,
ext1 x,
exact tsum_apply (pi.summable.2 (λ _, ennreal.summable)),
end
@[measurability]
lemma measurable.nnreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0} (h : ∀ i, measurable (f i)) :
measurable (λ x, ∑' i, f i x) :=
begin
simp_rw [nnreal.tsum_eq_to_nnreal_tsum],
exact (measurable.ennreal_tsum (λ i, (h i).coe_nnreal_ennreal)).ennreal_to_nnreal,
end
@[measurability]
lemma ae_measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} {μ : measure α}
(h : ∀ i, ae_measurable (f i) μ) :
ae_measurable (λ x, ∑' i, f i x) μ :=
by { simp_rw [ennreal.tsum_eq_supr_sum], apply ae_measurable_supr,
exact λ s, finset.ae_measurable_sum s (λ i _, h i) }
@[measurability]
lemma measurable_coe_real_ereal : measurable (coe : ℝ → ereal) :=
continuous_coe_real_ereal.measurable
@[measurability]
lemma measurable.coe_real_ereal {f : α → ℝ} (hf : measurable f) :
measurable (λ x, (f x : ereal)) :=
measurable_coe_real_ereal.comp hf
@[measurability]
lemma ae_measurable.coe_real_ereal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, (f x : ereal)) μ :=
measurable_coe_real_ereal.comp_ae_measurable hf
/-- The set of finite `ereal` numbers is `measurable_equiv` to `ℝ`. -/
def measurable_equiv.ereal_equiv_real : ({⊥, ⊤} : set ereal).compl ≃ᵐ ℝ :=
ereal.ne_bot_top_homeomorph_real.to_measurable_equiv
lemma ereal.measurable_of_measurable_real {f : ereal → α}
(h : measurable (λ p : ℝ, f p)) : measurable f :=
measurable_of_measurable_on_compl_finite {⊥, ⊤} (by simp)
(measurable_equiv.ereal_equiv_real.symm.measurable_coe_iff.1 h)
@[measurability]
lemma measurable_ereal_to_real : measurable ereal.to_real :=
ereal.measurable_of_measurable_real (by simpa using measurable_id)
@[measurability]
lemma measurable.ereal_to_real {f : α → ereal} (hf : measurable f) :
measurable (λ x, (f x).to_real) :=
measurable_ereal_to_real.comp hf
@[measurability]
lemma ae_measurable.ereal_to_real {f : α → ereal} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, (f x).to_real) μ :=
measurable_ereal_to_real.comp_ae_measurable hf
@[measurability]
lemma measurable_coe_ennreal_ereal : measurable (coe : ℝ≥0∞ → ereal) :=
continuous_coe_ennreal_ereal.measurable
@[measurability]
lemma measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} (hf : measurable f) :
measurable (λ x, (f x : ereal)) :=
measurable_coe_ennreal_ereal.comp hf
@[measurability]
lemma ae_measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) :
ae_measurable (λ x, (f x : ereal)) μ :=
measurable_coe_ennreal_ereal.comp_ae_measurable hf
section normed_group
variables [normed_group α] [opens_measurable_space α] [measurable_space β]
@[measurability]
lemma measurable_norm : measurable (norm : α → ℝ) :=
continuous_norm.measurable
@[measurability]
lemma measurable.norm {f : β → α} (hf : measurable f) : measurable (λ a, norm (f a)) :=
measurable_norm.comp hf
@[measurability]
lemma ae_measurable.norm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) :
ae_measurable (λ a, norm (f a)) μ :=
measurable_norm.comp_ae_measurable hf
@[measurability]
lemma measurable_nnnorm : measurable (nnnorm : α → ℝ≥0) :=
continuous_nnnorm.measurable
@[measurability]
lemma measurable.nnnorm {f : β → α} (hf : measurable f) : measurable (λ a, nnnorm (f a)) :=
measurable_nnnorm.comp hf
@[measurability]
lemma ae_measurable.nnnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) :
ae_measurable (λ a, nnnorm (f a)) μ :=
measurable_nnnorm.comp_ae_measurable hf
@[measurability]
lemma measurable_ennnorm : measurable (λ x : α, (nnnorm x : ℝ≥0∞)) :=
measurable_nnnorm.coe_nnreal_ennreal
@[measurability]
lemma measurable.ennnorm {f : β → α} (hf : measurable f) :
measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) :=
hf.nnnorm.coe_nnreal_ennreal
@[measurability]
lemma ae_measurable.ennnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) :
ae_measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) μ :=
measurable_ennnorm.comp_ae_measurable hf
end normed_group
section limits
variables [measurable_space β] [metric_space β] [borel_space β]
open metric
/-- A limit (over a general filter) of measurable `ℝ≥0` valued functions is measurable.
The assumption `hs` can be dropped using `filter.is_countably_generated.has_antimono_basis`, but we
don't need that case yet. -/
lemma measurable_of_tendsto_nnreal' {ι ι'} {f : ι → α → ℝ≥0} {g : α → ℝ≥0} (u : filter ι)
[ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop}
{s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable g :=
begin
rw [tendsto_pi] at lim, rw [← measurable_coe_nnreal_ennreal_iff],
have : ∀ x, liminf u (λ n, (f n x : ℝ≥0∞)) = (g x : ℝ≥0∞) :=
λ x, ((ennreal.continuous_coe.tendsto (g x)).comp (lim x)).liminf_eq,
simp_rw [← this],
show measurable (λ x, liminf u (λ n, (f n x : ℝ≥0∞))),
exact measurable_liminf' (λ i, (hf i).coe_nnreal_ennreal) hu hs,
end
/-- A sequential limit of measurable `ℝ≥0` valued functions is measurable. -/
lemma measurable_of_tendsto_nnreal {f : ℕ → α → ℝ≥0} {g : α → ℝ≥0}
(hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g :=
measurable_of_tendsto_nnreal' at_top hf lim at_top_countable_basis (λ i, countable_encodable _)
/-- A limit (over a general filter) of measurable functions valued in a metric space is measurable.
The assumption `hs` can be dropped using `filter.is_countably_generated.has_antimono_basis`, but we
don't need that case yet. -/
lemma measurable_of_tendsto_metric' {ι ι'} {f : ι → α → β} {g : α → β}
(u : filter ι) [ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop}
{s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) :
measurable g :=
begin
apply measurable_of_is_closed', intros s h1s h2s h3s,
have : measurable (λ x, inf_nndist (g x) s),
{ refine measurable_of_tendsto_nnreal' u (λ i, (hf i).inf_nndist) _ hu hs, swap,
rw [tendsto_pi], rw [tendsto_pi] at lim, intro x,
exact ((continuous_inf_nndist_pt s).tendsto (g x)).comp (lim x) },
have h4s : g ⁻¹' s = (λ x, inf_nndist (g x) s) ⁻¹' {0},
{ ext x, simp [h1s, ← mem_iff_inf_dist_zero_of_closed h1s h2s, ← nnreal.coe_eq_zero] },
rw [h4s], exact this (measurable_set_singleton 0),
end
/-- A sequential limit of measurable functions valued in a metric space is measurable. -/
lemma measurable_of_tendsto_metric {f : ℕ → α → β} {g : α → β}
(hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) :
measurable g :=
measurable_of_tendsto_metric' at_top hf lim at_top_countable_basis (λ i, countable_encodable _)
lemma ae_measurable_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β} {g : α → β}
(hf : ∀ n, ae_measurable (f n) μ)
(h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) :
ae_measurable g μ :=
begin
let p : α → (ℕ → β) → Prop := λ x f', filter.at_top.tendsto (λ n, f' n) (𝓝 (g x)),
let hp : ∀ᵐ x ∂μ, p x (λ n, f n x), from h_ae_tendsto,
let ae_seq_lim := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨f 0 x⟩ : nonempty β).some,
refine ⟨ae_seq_lim, _, (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨f 0 x⟩ : nonempty β).some)
(ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hp)).symm⟩,
refine measurable_of_tendsto_metric (@ae_seq.measurable α β _ _ _ f μ hf p) _,
refine tendsto_pi.mpr (λ x, _),
simp_rw [ae_seq, ae_seq_lim],
split_ifs with hx,
{ simp_rw ae_seq.mk_eq_fun_of_mem_ae_seq_set hf hx,
exact @ae_seq.fun_prop_of_mem_ae_seq_set α β _ _ _ _ _ _ hf x hx, },
{ exact tendsto_const_nhds, },
end
lemma measurable_of_tendsto_metric_ae {μ : measure α} [μ.is_complete] {f : ℕ → α → β} {g : α → β}
(hf : ∀ n, measurable (f n))
(h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) :
measurable g :=
ae_measurable_iff_measurable.mp
(ae_measurable_of_tendsto_metric_ae (λ i, (hf i).ae_measurable) h_ae_tendsto)
lemma measurable_limit_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β}
(hf : ∀ n, ae_measurable (f n) μ)
(h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, filter.at_top.tendsto (λ n, f n x) (𝓝 l)) :
∃ (f_lim : α → β) (hf_lim_meas : measurable f_lim),
∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)) :=
begin
let p : α → (ℕ → β) → Prop := λ x f', ∃ l : β, filter.at_top.tendsto (λ n, f' n) (𝓝 l),
have hp_mem : ∀ x, x ∈ ae_seq_set hf p → p x (λ n, f n x),
from λ x hx, ae_seq.fun_prop_of_mem_ae_seq_set hf hx,
have hμ_compl : μ (ae_seq_set hf p)ᶜ = 0,
from ae_seq.measure_compl_ae_seq_set_eq_zero hf h_ae_tendsto,
let f_lim : α → β := λ x, dite (x ∈ ae_seq_set hf p) (λ h, (hp_mem x h).some)
(λ h, (⟨f 0 x⟩ : nonempty β).some),
have hf_lim_conv : ∀ x, x ∈ ae_seq_set hf p → filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)),
{ intros x hx_conv,
simp only [f_lim, hx_conv, dif_pos],
exact (hp_mem x hx_conv).some_spec, },
have hf_lim : ∀ x, filter.at_top.tendsto (λ n, ae_seq hf p n x) (𝓝 (f_lim x)),
{ intros x,
simp only [f_lim, ae_seq],
split_ifs,
{ rw funext (λ n, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h n),
exact (hp_mem x h).some_spec, },
{ exact tendsto_const_nhds, }, },
have h_ae_tendsto_f_lim : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)),
{ refine le_antisymm (le_of_eq (measure_mono_null _ hμ_compl)) (zero_le _),
exact set.compl_subset_compl.mpr (λ x hx, hf_lim_conv x hx), },
have h_f_lim_meas : measurable f_lim,
from measurable_of_tendsto_metric (ae_seq.measurable hf p) (tendsto_pi.mpr (λ x, hf_lim x)),
exact ⟨f_lim, h_f_lim_meas, h_ae_tendsto_f_lim⟩,
end
end limits
namespace continuous_linear_map
variables {𝕜 : Type*} [normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E]
variables [opens_measurable_space E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [measurable_space F] [borel_space F]
@[measurability]
protected lemma measurable (L : E →L[𝕜] F) : measurable L :=
L.continuous.measurable
lemma measurable_comp (L : E →L[𝕜] F) {φ : α → E} (φ_meas : measurable φ) :
measurable (λ (a : α), L (φ a)) :=
L.measurable.comp φ_meas
end continuous_linear_map
namespace continuous_linear_map
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E]
{F : Type*} [normed_group F] [normed_space 𝕜 F]
instance : measurable_space (E →L[𝕜] F) := borel _
instance : borel_space (E →L[𝕜] F) := ⟨rfl⟩
@[measurability]
lemma measurable_apply [measurable_space F] [borel_space F] (x : E) :
measurable (λ f : E →L[𝕜] F, f x) :=
(apply 𝕜 F x).continuous.measurable
@[measurability]
lemma measurable_apply' [measurable_space E] [opens_measurable_space E]
[measurable_space F] [borel_space F] :
measurable (λ (x : E) (f : E →L[𝕜] F), f x) :=
measurable_pi_lambda _ $ λ f, f.measurable
@[measurability]
lemma measurable_coe [measurable_space F] [borel_space F] :
measurable (λ (f : E →L[𝕜] F) (x : E), f x) :=
measurable_pi_lambda _ measurable_apply
end continuous_linear_map
section continuous_linear_map_nondiscrete_normed_field
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E]
variables {F : Type*} [normed_group F] [normed_space 𝕜 F]
@[measurability]
lemma measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} (hφ : measurable φ) (v : F) :
measurable (λ a, φ a v) :=
(continuous_linear_map.apply 𝕜 E v).measurable.comp hφ
@[measurability]
lemma ae_measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} {μ : measure α}
(hφ : ae_measurable φ μ) (v : F) : ae_measurable (λ a, φ a v) μ :=
(continuous_linear_map.apply 𝕜 E v).measurable.comp_ae_measurable hφ
end continuous_linear_map_nondiscrete_normed_field
section normed_space
variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜]
variables [borel_space 𝕜]
variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E]
lemma measurable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) :
measurable (λ x, f x • c) ↔ measurable f :=
measurable_comp_iff_of_closed_embedding (λ y : 𝕜, y • c) (closed_embedding_smul_left hc)
lemma ae_measurable_smul_const {f : α → 𝕜} {μ : measure α} {c : E} (hc : c ≠ 0) :
ae_measurable (λ x, f x • c) μ ↔ ae_measurable f μ :=
ae_measurable_comp_iff_of_closed_embedding (λ y : 𝕜, y • c) (closed_embedding_smul_left hc)
end normed_space
lemma is_compact.measure_lt_top_of_nhds_within [topological_space α]
{s : set α} {μ : measure α} (h : is_compact s) (hμ : ∀ x ∈ s, μ.finite_at_filter (𝓝[s] x)) :
μ s < ∞ :=
is_compact.induction_on h (by simp) (λ s t hst ht, (measure_mono hst).trans_lt ht)
(λ s t hs ht, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hs, ht⟩)) hμ
lemma is_compact.measure_lt_top [topological_space α] {s : set α} {μ : measure α}
[is_locally_finite_measure μ] (h : is_compact s) :
μ s < ∞ :=
h.measure_lt_top_of_nhds_within $ λ x hx, μ.finite_at_nhds_within _ _
|
5792ee42c4707245038b6824abfb7e7013f42541 | ea5678cc400c34ff95b661fa26d15024e27ea8cd | /primesaf.lean | 6b4c43766f60688bbc2ea634ac7c69cc34c8119f | [] | no_license | ChrisHughes24/leanstuff | dca0b5349c3ed893e8792ffbd98cbcadaff20411 | 9efa85f72efaccd1d540385952a6acc18fce8687 | refs/heads/master | 1,654,883,241,759 | 1,652,873,885,000 | 1,652,873,885,000 | 134,599,537 | 1 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 1,967 | lean | import data.nat.prime
import tactic.norm_num
import data.list.basic
import data.int.basic
open nat
open list
theorem prime_factors_unique: ∀ A B:list ℕ,prod A=prod B→(∀p:ℕ, p∈A→prime p)→(∀ p:ℕ,p∈ B→ prime p)→A~B:=begin
intro A,induction A with pA A1 Hi,
norm_num,intros,cases B with p B1,exact perm.refl nil,exfalso,revert a,norm_num,
have H:=a_1 p (list.mem_cons_self _ _),have H1:=dvd_mul_right p (prod B1),intro,rw ←a at H1,exact prime.not_dvd_one H H1,
intros,simp at a,have H:pA ∣ prod B, have:=dvd_mul_right pA (prod A1),rwa a at this,
have H1: ∀ (B:list ℕ)(p:ℕ),prime p→(∀pB, pB ∈ B → prime pB)→p ∣ prod B → p ∈ B:=begin
assume B,induction B with p1 B1 Hi,
rw prod_nil,assume p Hp H H2,exfalso,revert H2,
exact prime.not_dvd_one Hp,
assume p2 Hp2 H H1,
norm_num,rw prod_cons at H1,
have H2:=iff.elim_left (prime.dvd_mul Hp2) H1,
cases H2 with A A,left,
have H3:=H p1,
revert H3,norm_num,assume H4,
unfold prime at H4,
have H5:=and.right H4 p2 A,
have H6:¬p2=1:=begin unfold prime at Hp2,intro,rw a_3 at Hp2,simp at Hp2,revert Hp2,exact dec_trivial,end,
simp [H6] at H5,assumption,right,
have H3:(∀ (pB : ℕ), pB ∈ B1 → prime pB):=begin revert H, norm_num,end,have H2:= Hi p2 Hp2 H3 A,assumption,
end,
have HppA: prime pA:=begin apply a_1,norm_num, end,
have H9:=H1 B pA HppA a_2 H,
have H11:=prod_eq_of_perm (perm_erase H9),rw [H11,prod_cons] at a,
rw nat.mul_left_inj (gt_of_ge_of_gt (and.left HppA) (dec_trivial:2>0)) at a,
have HA1:∀ (p : ℕ), p ∈ A1 → prime p:=begin revert a_1,norm_num,end,
have HB1:∀ (p : ℕ), p ∈(list.erase B pA) → prime p:=λ p Hp,a_2 p (mem_of_mem_erase Hp),
have Hi2:= iff.elim_right (perm_cons pA) (Hi (list.erase B pA) a HA1 HB1),
exact perm.trans Hi2 (perm.symm (perm_erase H9)),
end
|
31ba0b4f702b533a6ffab4e6117c4fed1d14cd22 | 02005f45e00c7ecf2c8ca5db60251bd1e9c860b5 | /src/linear_algebra/pi.lean | 72b88b088a80c4f315cf7e4b5cd4af73899cf1e2 | [
"Apache-2.0"
] | permissive | anthony2698/mathlib | 03cd69fe5c280b0916f6df2d07c614c8e1efe890 | 407615e05814e98b24b2ff322b14e8e3eb5e5d67 | refs/heads/master | 1,678,792,774,873 | 1,614,371,563,000 | 1,614,371,563,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 7,258 | 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, Kevin Buzzard, Yury Kudryashov, Eric Wieser
-/
import linear_algebra.basic
/-!
# Pi types of semimodules
This file defines constructors for linear maps whose domains or codomains are pi types.
It contains theorems relating these to each other, as well as to `linear_map.ker`.
## Main definitions
- pi types in the codomain:
- `linear_map.pi`
- `linear_map.single`
- pi types in the domain:
- `linear_map.proj`
- `linear_map.diag`
-/
universes u v w x y z u' v' w' y'
variables {R : Type u} {K : Type u'} {M : Type v} {V : Type v'} {M₂ : Type w} {V₂ : Type w'}
variables {M₃ : Type y} {V₃ : Type y'} {M₄ : Type z} {ι : Type x}
namespace linear_map
open function submodule
open_locale big_operators
universe i
variables [semiring R] [add_comm_monoid M₂] [semimodule R M₂] [add_comm_monoid M₃] [semimodule R M₃]
{φ : ι → Type i} [∀i, add_comm_monoid (φ i)] [∀i, semimodule R (φ i)]
/-- `pi` construction for linear functions. From a family of linear functions it produces a linear
function into a family of modules. -/
def pi (f : Πi, M₂ →ₗ[R] φ i) : M₂ →ₗ[R] (Πi, φ i) :=
⟨λc i, f i c, λ c d, funext $ λ i, (f i).map_add _ _, λ c d, funext $ λ i, (f i).map_smul _ _⟩
@[simp] lemma pi_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i : ι) :
pi f c i = f i c := rfl
lemma ker_pi (f : Πi, M₂ →ₗ[R] φ i) : ker (pi f) = (⨅i:ι, ker (f i)) :=
by ext c; simp [funext_iff]; refl
lemma pi_eq_zero (f : Πi, M₂ →ₗ[R] φ i) : pi f = 0 ↔ (∀i, f i = 0) :=
by simp only [linear_map.ext_iff, pi_apply, funext_iff]; exact ⟨λh a b, h b a, λh a b, h b a⟩
lemma pi_zero : pi (λi, 0 : Πi, M₂ →ₗ[R] φ i) = 0 :=
by ext; refl
lemma pi_comp (f : Πi, M₂ →ₗ[R] φ i) (g : M₃ →ₗ[R] M₂) : (pi f).comp g = pi (λi, (f i).comp g) :=
rfl
/-- The projections from a family of modules are linear maps. -/
def proj (i : ι) : (Πi, φ i) →ₗ[R] φ i :=
⟨ λa, a i, assume f g, rfl, assume c f, rfl ⟩
@[simp] lemma proj_apply (i : ι) (b : Πi, φ i) : (proj i : (Πi, φ i) →ₗ[R] φ i) b = b i := rfl
lemma proj_pi (f : Πi, M₂ →ₗ[R] φ i) (i : ι) : (proj i).comp (pi f) = f i :=
ext $ assume c, rfl
lemma infi_ker_proj : (⨅i, ker (proj i) : submodule R (Πi, φ i)) = ⊥ :=
bot_unique $ submodule.le_def'.2 $ assume a h,
begin
simp only [mem_infi, mem_ker, proj_apply] at h,
exact (mem_bot _).2 (funext $ assume i, h i)
end
lemma apply_single [add_comm_monoid M] [semimodule R M] [decidable_eq ι]
(f : Π i, φ i →ₗ[R] M) (i j : ι) (x : φ i) :
f j (pi.single i x j) = pi.single i (f i x) j :=
pi.apply_single (λ i, f i) (λ i, (f i).map_zero) _ _ _
/-- The `linear_map` version of `add_monoid_hom.single` and `pi.single`. -/
def single [decidable_eq ι] (i : ι) : φ i →ₗ[R] (Πi, φ i) :=
{ to_fun := pi.single i,
map_smul' := pi.single_smul i,
.. add_monoid_hom.single φ i}
@[simp] lemma coe_single [decidable_eq ι] (i : ι) :
⇑(single i : φ i →ₗ[R] (Π i, φ i)) = pi.single i := rfl
/-- The linear equivalence between linear functions on a finite product of modules and
families of functions on these modules. See note [bundled maps over different rings]. -/
def lsum (S) [add_comm_monoid M] [semimodule R M] [fintype ι] [decidable_eq ι]
[semiring S] [semimodule S M] [smul_comm_class R S M] :
(Π i, φ i →ₗ[R] M) ≃ₗ[S] ((Π i, φ i) →ₗ[R] M) :=
{ to_fun := λ f, ∑ i : ι, (f i).comp (proj i),
inv_fun := λ f i, f.comp (single i),
map_add' := λ f g, by simp only [pi.add_apply, add_comp, finset.sum_add_distrib],
map_smul' := λ c f, by simp only [pi.smul_apply, smul_comp, finset.smul_sum],
left_inv := λ f, by { ext i x, simp [apply_single] },
right_inv := λ f,
begin
ext,
suffices : f (∑ j, pi.single j (x j)) = f x, by simpa [apply_single],
rw finset.univ_sum_single
end }
section ext
variables [fintype ι] [decidable_eq ι] [add_comm_monoid M] [semimodule R M]
{f g : (Π i, φ i) →ₗ[R] M}
lemma pi_ext (h : ∀ i x, f (pi.single i x) = g (pi.single i x)) :
f = g :=
to_add_monoid_hom_injective $ add_monoid_hom.functions_ext _ _ _ h
lemma pi_ext_iff : f = g ↔ ∀ i x, f (pi.single i x) = g (pi.single i x) :=
⟨λ h i x, h ▸ rfl, pi_ext⟩
/-- This is used as the ext lemma instead of `linear_map.pi_ext` for reasons explained in
note [partially-applied ext lemmas]. -/
@[ext] lemma pi_ext' (h : ∀ i, f.comp (single i) = g.comp (single i)) : f = g :=
begin
refine pi_ext (λ i x, _),
convert linear_map.congr_fun (h i) x
end
lemma pi_ext'_iff : f = g ↔ ∀ i, f.comp (single i) = g.comp (single i) :=
⟨λ h i, h ▸ rfl, pi_ext'⟩
end ext
section
variables (R φ)
/-- If `I` and `J` are disjoint 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 {I J : set ι} [decidable_pred (λi, i ∈ I)]
(hd : disjoint I J) (hu : set.univ ⊆ I ∪ J) :
(⨅i ∈ J, ker (proj i) : submodule R (Πi, φ i)) ≃ₗ[R] (Πi:I, φ i) :=
begin
refine linear_equiv.of_linear
(pi $ λi, (proj (i:ι)).comp (submodule.subtype _))
(cod_restrict _ (pi $ λi, if h : i ∈ I then proj (⟨i, h⟩ : I) else 0) _) _ _,
{ assume b,
simp only [mem_infi, mem_ker, funext_iff, proj_apply, pi_apply],
assume j hjJ,
have : j ∉ I := assume hjI, hd ⟨hjI, hjJ⟩,
rw [dif_neg this, zero_apply] },
{ simp only [pi_comp, comp_assoc, subtype_comp_cod_restrict, proj_pi, dif_pos, subtype.coe_prop],
ext b ⟨j, hj⟩, refl },
{ ext1 ⟨b, hb⟩,
apply subtype.ext,
ext j,
have hb : ∀i ∈ J, b i = 0,
{ simpa only [mem_infi, mem_ker, proj_apply] using (mem_infi _).1 hb },
simp only [comp_apply, pi_apply, id_apply, proj_apply, subtype_apply, cod_restrict_apply],
split_ifs,
{ refl },
{ exact (hb _ $ (hu trivial).resolve_left h).symm } }
end
end
section
variable [decidable_eq ι]
/-- `diag i j` is the identity map if `i = j`. Otherwise it is the constant 0 map. -/
def diag (i j : ι) : φ i →ₗ[R] φ j :=
@function.update ι (λj, φ i →ₗ[R] φ j) _ 0 i id j
lemma update_apply (f : Πi, M₂ →ₗ[R] φ i) (c : M₂) (i j : ι) (b : M₂ →ₗ[R] φ i) :
(update f i b j) c = update (λi, f i c) i (b c) j :=
begin
by_cases j = i,
{ rw [h, update_same, update_same] },
{ rw [update_noteq h, update_noteq h] }
end
end
end linear_map
namespace linear_equiv
variables [semiring R] {φ ψ : ι → Type*} [∀i, add_comm_monoid (φ i)] [∀i, semimodule R (φ i)]
[∀i, add_comm_monoid (ψ i)] [∀i, semimodule R (ψ i)]
/-- Combine a family of linear equivalences into a linear equivalence of `pi`-types. -/
@[simps] def pi (e : Π i, φ i ≃ₗ[R] ψ i) : (Π i, φ i) ≃ₗ[R] (Π i, ψ i) :=
{ to_fun := λ f i, e i (f i),
inv_fun := λ f i, (e i).symm (f i),
map_add' := λ f g, by { ext, simp },
map_smul' := λ c f, by { ext, simp },
left_inv := λ f, by { ext, simp },
right_inv := λ f, by { ext, simp } }
end linear_equiv
|
73ffe4b3422b1f12625c2f01a566f55098b438cc | 1a61aba1b67cddccce19532a9596efe44be4285f | /library/data/equiv.lean | 1523df6e94649fed604827b13d4584f0708533d4 | [
"Apache-2.0"
] | permissive | eigengrau/lean | 07986a0f2548688c13ba36231f6cdbee82abf4c6 | f8a773be1112015e2d232661ce616d23f12874d0 | refs/heads/master | 1,610,939,198,566 | 1,441,352,386,000 | 1,441,352,494,000 | 41,903,576 | 0 | 0 | null | 1,441,352,210,000 | 1,441,352,210,000 | null | UTF-8 | Lean | false | false | 16,471 | lean | /-
Copyright (c) 2015 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
In the standard library we cannot assume the univalence axiom.
We say two types are equivalent if they are isomorphic.
Two equivalent types have the same cardinality.
-/
import data.sum data.nat
open function
structure equiv [class] (A B : Type) :=
(to_fun : A → B)
(inv_fun : B → A)
(left_inv : left_inverse inv_fun to_fun)
(right_inv : right_inverse inv_fun to_fun)
namespace equiv
definition perm [reducible] (A : Type) := equiv A A
infix `≃`:50 := equiv
definition fn {A B : Type} (e : equiv A B) : A → B :=
@equiv.to_fun A B e
infixr `∙`:100 := fn
definition inv {A B : Type} [e : equiv A B] : B → A :=
@equiv.inv_fun A B e
lemma eq_of_to_fun_eq {A B : Type} : ∀ {e₁ e₂ : equiv A B}, fn e₁ = fn e₂ → e₁ = e₂
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) h :=
assert f₁ = f₂, from h,
assert g₁ = g₂, from funext (λ x,
assert f₁ (g₁ x) = f₂ (g₂ x), from eq.trans (r₁ x) (eq.symm (r₂ x)),
have f₁ (g₁ x) = f₁ (g₂ x), by rewrite [-h at this]; exact this,
show g₁ x = g₂ x, from injective_of_left_inverse l₁ this),
by congruence; repeat assumption
protected definition refl [refl] (A : Type) : A ≃ A :=
mk (@id A) (@id A) (λ x, rfl) (λ x, rfl)
protected definition symm [symm] {A B : Type} : A ≃ B → B ≃ A
| (mk f g h₁ h₂) := mk g f h₂ h₁
protected definition trans [trans] {A B C : Type} : A ≃ B → B ≃ C → A ≃ C
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) :=
mk (f₂ ∘ f₁) (g₁ ∘ g₂)
(show ∀ x, g₁ (g₂ (f₂ (f₁ x))) = x, by intros; rewrite [l₂, l₁]; reflexivity)
(show ∀ x, f₂ (f₁ (g₁ (g₂ x))) = x, by intros; rewrite [r₁, r₂]; reflexivity)
abbreviation id {A : Type} := equiv.refl A
namespace ops
postfix `⁻¹` := equiv.symm
postfix `⁻¹` := equiv.inv
notation e₁ `∘` e₂ := equiv.trans e₂ e₁
end ops
open equiv.ops
lemma id_apply {A : Type} (x : A) : id ∙ x = x :=
rfl
lemma compose_apply {A B C : Type} (g : B ≃ C) (f : A ≃ B) (x : A) : (g ∘ f) ∙ x = g ∙ f ∙ x :=
begin cases g, cases f, esimp end
lemma inverse_apply_apply {A B : Type} : ∀ (e : A ≃ B) (x : A), e⁻¹ ∙ e ∙ x = x
| (mk f₁ g₁ l₁ r₁) x := begin unfold [equiv.symm, fn], rewrite l₁ end
lemma eq_iff_eq_of_injective {A B : Type} {f : A → B} (inj : injective f) (a b : A) : f a = f b ↔ a = b :=
iff.intro
(suppose f a = f b, inj this)
(suppose a = b, by rewrite this)
lemma apply_eq_iff_eq {A B : Type} : ∀ (f : A ≃ B) (x y : A), f ∙ x = f ∙ y ↔ x = y
| (mk f₁ g₁ l₁ r₁) x y := eq_iff_eq_of_injective (injective_of_left_inverse l₁) x y
lemma apply_eq_iff_eq_inverse_apply {A B : Type} : ∀ (f : A ≃ B) (x : A) (y : B), f ∙ x = y ↔ x = f⁻¹ ∙ y
| (mk f₁ g₁ l₁ r₁) x y :=
begin
esimp, unfold [equiv.symm, fn], apply iff.intro,
suppose f₁ x = y, by subst y; rewrite l₁,
suppose x = g₁ y, by subst x; rewrite r₁
end
definition false_equiv_empty : empty ≃ false :=
mk (λ e, empty.rec _ e) (λ h, false.rec _ h) (λ e, empty.rec _ e) (λ h, false.rec _ h)
definition arrow_congr [congr] {A₁ B₁ A₂ B₂ : Type} : A₁ ≃ A₂ → B₁ ≃ B₂ → (A₁ → B₁) ≃ (A₂ → B₂)
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) :=
mk
(λ (h : A₁ → B₁) (a : A₂), f₂ (h (g₁ a)))
(λ (h : A₂ → B₂) (a : A₁), g₂ (h (f₁ a)))
(λ h, funext (λ a, by rewrite [l₁, l₂]; reflexivity))
(λ h, funext (λ a, by rewrite [r₁, r₂]; reflexivity))
section
open unit
definition arrow_unit_equiv_unit [simp] (A : Type) : (A → unit) ≃ unit :=
mk (λ f, star) (λ u, (λ f, star))
(λ f, funext (λ x, by cases (f x); reflexivity))
(λ u, by cases u; reflexivity)
definition unit_arrow_equiv [simp] (A : Type) : (unit → A) ≃ A :=
mk (λ f, f star) (λ a, (λ u, a))
(λ f, funext (λ x, by cases x; reflexivity))
(λ u, rfl)
definition empty_arrow_equiv_unit [simp] (A : Type) : (empty → A) ≃ unit :=
mk (λ f, star) (λ u, λ e, empty.rec _ e)
(λ f, funext (λ x, empty.rec _ x))
(λ u, by cases u; reflexivity)
definition false_arrow_equiv_unit [simp] (A : Type) : (false → A) ≃ unit :=
calc (false → A) ≃ (empty → A) : arrow_congr false_equiv_empty !equiv.refl
... ≃ unit : empty_arrow_equiv_unit
end
definition prod_congr [congr] {A₁ B₁ A₂ B₂ : Type} : A₁ ≃ A₂ → B₁ ≃ B₂ → (A₁ × B₁) ≃ (A₂ × B₂)
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) :=
mk
(λ p, match p with (a₁, b₁) := (f₁ a₁, f₂ b₁) end)
(λ p, match p with (a₂, b₂) := (g₁ a₂, g₂ b₂) end)
(λ p, begin cases p, esimp, rewrite [l₁, l₂], reflexivity end)
(λ p, begin cases p, esimp, rewrite [r₁, r₂], reflexivity end)
definition prod_comm [simp] (A B : Type) : (A × B) ≃ (B × A) :=
mk (λ p, match p with (a, b) := (b, a) end)
(λ p, match p with (b, a) := (a, b) end)
(λ p, begin cases p, esimp end)
(λ p, begin cases p, esimp end)
definition prod_assoc [simp] (A B C : Type) : ((A × B) × C) ≃ (A × (B × C)) :=
mk (λ t, match t with ((a, b), c) := (a, (b, c)) end)
(λ t, match t with (a, (b, c)) := ((a, b), c) end)
(λ t, begin cases t with ab c, cases ab, esimp end)
(λ t, begin cases t with a bc, cases bc, esimp end)
section
open unit prod.ops
definition prod_unit_right [simp] (A : Type) : (A × unit) ≃ A :=
mk (λ p, p.1)
(λ a, (a, star))
(λ p, begin cases p with a u, cases u, esimp end)
(λ a, rfl)
definition prod_unit_left [simp] (A : Type) : (unit × A) ≃ A :=
calc (unit × A) ≃ (A × unit) : prod_comm
... ≃ A : prod_unit_right
definition prod_empty_right [simp] (A : Type) : (A × empty) ≃ empty :=
mk (λ p, empty.rec _ p.2) (λ e, empty.rec _ e) (λ p, empty.rec _ p.2) (λ e, empty.rec _ e)
definition prod_empty_left [simp] (A : Type) : (empty × A) ≃ empty :=
calc (empty × A) ≃ (A × empty) : prod_comm
... ≃ empty : prod_empty_right
end
section
open sum
definition sum_congr [congr] {A₁ B₁ A₂ B₂ : Type} : A₁ ≃ A₂ → B₁ ≃ B₂ → (A₁ + B₁) ≃ (A₂ + B₂)
| (mk f₁ g₁ l₁ r₁) (mk f₂ g₂ l₂ r₂) :=
mk
(λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end)
(λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end)
(λ s, begin cases s, {esimp, rewrite l₁, reflexivity}, {esimp, rewrite l₂, reflexivity} end)
(λ s, begin cases s, {esimp, rewrite r₁, reflexivity}, {esimp, rewrite r₂, reflexivity} end)
open bool unit
definition bool_equiv_unit_sum_unit : bool ≃ (unit + unit) :=
mk (λ b, match b with tt := inl star | ff := inr star end)
(λ s, match s with inl star := tt | inr star := ff end)
(λ b, begin cases b, esimp, esimp end)
(λ s, begin cases s with u u, {cases u, esimp}, {cases u, esimp} end)
definition sum_comm [simp] (A B : Type) : (A + B) ≃ (B + A) :=
mk (λ s, match s with inl a := inr a | inr b := inl b end)
(λ s, match s with inl b := inr b | inr a := inl a end)
(λ s, begin cases s, esimp, esimp end)
(λ s, begin cases s, esimp, esimp end)
definition sum_assoc [simp] (A B C : Type) : ((A + B) + C) ≃ (A + (B + C)) :=
mk (λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end)
(λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end)
(λ s, begin cases s with ab c, cases ab, repeat esimp end)
(λ s, begin cases s with a bc, esimp, cases bc, repeat esimp end)
definition sum_empty_right [simp] (A : Type) : (A + empty) ≃ A :=
mk (λ s, match s with inl a := a | inr e := empty.rec _ e end)
(λ a, inl a)
(λ s, begin cases s with a e, esimp, exact empty.rec _ e end)
(λ a, rfl)
definition sum_empty_left [simp] (A : Type) : (empty + A) ≃ A :=
calc (empty + A) ≃ (A + empty) : sum_comm
... ≃ A : sum_empty_right
end
section
open prod.ops
definition arrow_prod_equiv_prod_arrow (A B C : Type) : (C → A × B) ≃ ((C → A) × (C → B)) :=
mk (λ f, (λ c, (f c).1, λ c, (f c).2))
(λ p, λ c, (p.1 c, p.2 c))
(λ f, funext (λ c, begin esimp, cases f c, esimp end))
(λ p, begin cases p, esimp end)
definition arrow_arrow_equiv_prod_arrow (A B C : Type) : (A → B → C) ≃ (A × B → C) :=
mk (λ f, λ p, f p.1 p.2)
(λ f, λ a b, f (a, b))
(λ f, rfl)
(λ f, funext (λ p, begin cases p, esimp end))
open sum
definition sum_arrow_equiv_prod_arrow (A B C : Type) : ((A + B) → C) ≃ ((A → C) × (B → C)) :=
mk (λ f, (λ a, f (inl a), λ b, f (inr b)))
(λ p, (λ s, match s with inl a := p.1 a | inr b := p.2 b end))
(λ f, funext (λ s, begin cases s, esimp, esimp end))
(λ p, begin cases p, esimp end)
definition sum_prod_distrib (A B C : Type) : ((A + B) × C) ≃ ((A × C) + (B × C)) :=
mk (λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end)
(λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end)
(λ p, begin cases p with ab c, cases ab, repeat esimp end)
(λ s, begin cases s with ac bc, cases ac, esimp, cases bc, esimp end)
definition prod_sum_distrib (A B C : Type) : (A × (B + C)) ≃ ((A × B) + (A × C)) :=
calc (A × (B + C)) ≃ ((B + C) × A) : prod_comm
... ≃ ((B × A) + (C × A)) : sum_prod_distrib
... ≃ ((A × B) + (A × C)) : sum_congr !prod_comm !prod_comm
definition bool_prod_equiv_sum (A : Type) : (bool × A) ≃ (A + A) :=
calc (bool × A) ≃ ((unit + unit) × A) : prod_congr bool_equiv_unit_sum_unit !equiv.refl
... ≃ (A × (unit + unit)) : prod_comm
... ≃ ((A × unit) + (A × unit)) : prod_sum_distrib
... ≃ (A + A) : sum_congr !prod_unit_right !prod_unit_right
end
section
open sum nat unit prod.ops
definition nat_equiv_nat_sum_unit : nat ≃ (nat + unit) :=
mk (λ n, match n with zero := inr star | succ a := inl a end)
(λ s, match s with inl n := succ n | inr star := zero end)
(λ n, begin cases n, repeat esimp end)
(λ s, begin cases s with a u, esimp, {cases u, esimp} end)
definition nat_sum_unit_equiv_nat [simp] : (nat + unit) ≃ nat :=
equiv.symm nat_equiv_nat_sum_unit
definition nat_prod_nat_equiv_nat [simp] : (nat × nat) ≃ nat :=
mk (λ p, mkpair p.1 p.2)
(λ n, unpair n)
(λ p, begin cases p, apply unpair_mkpair end)
(λ n, mkpair_unpair n)
definition nat_sum_bool_equiv_nat [simp] : (nat + bool) ≃ nat :=
calc (nat + bool) ≃ (nat + (unit + unit)) : sum_congr !equiv.refl bool_equiv_unit_sum_unit
... ≃ ((nat + unit) + unit) : sum_assoc
... ≃ (nat + unit) : sum_congr nat_sum_unit_equiv_nat !equiv.refl
... ≃ nat : nat_sum_unit_equiv_nat
open decidable
definition nat_sum_nat_equiv_nat [simp] : (nat + nat) ≃ nat :=
mk (λ s, match s with inl n := 2*n | inr n := 2*n+1 end)
(λ n, if even n then inl (n div 2) else inr ((n - 1) div 2))
(λ s, begin
have two_gt_0 : 2 > zero, from dec_trivial,
cases s,
{esimp, rewrite [if_pos (even_two_mul _), mul_div_cancel_left _ two_gt_0]},
{esimp, rewrite [if_neg (not_even_two_mul_plus_one _), add_sub_cancel, mul_div_cancel_left _ two_gt_0]}
end)
(λ n, by_cases
(λ h : even n, begin rewrite [if_pos h], esimp, rewrite [mul_div_cancel' (dvd_of_even h)] end)
(λ h : ¬ even n,
begin
rewrite [if_neg h], esimp,
cases n,
{exact absurd even_zero h},
{rewrite [-add_one, add_sub_cancel,
mul_div_cancel' (dvd_of_even (even_of_odd_succ (odd_of_not_even h)))]}
end))
definition prod_equiv_of_equiv_nat {A : Type} : A ≃ nat → (A × A) ≃ A :=
take e, calc
(A × A) ≃ (nat × nat) : prod_congr e e
... ≃ nat : nat_prod_nat_equiv_nat
... ≃ A : equiv.symm e
end
section
open decidable
definition decidable_eq_of_equiv {A B : Type} [h : decidable_eq A] : A ≃ B → decidable_eq B
| (mk f g l r) :=
take b₁ b₂, match h (g b₁) (g b₂) with
| inl he := inl (assert aux : f (g b₁) = f (g b₂), from congr_arg f he,
begin rewrite *r at aux, exact aux end)
| inr hn := inr (λ b₁eqb₂, by subst b₁eqb₂; exact absurd rfl hn)
end
end
definition inhabited_of_equiv {A B : Type} [h : inhabited A] : A ≃ B → inhabited B
| (mk f g l r) := inhabited.mk (f (inhabited.value h))
section
open subtype
definition subtype_equiv_of_subtype {A B : Type} {p : A → Prop} : A ≃ B → {a : A | p a} ≃ {b : B | p b⁻¹}
| (mk f g l r) :=
mk (λ s, match s with tag v h := tag (f v) (eq.rec_on (eq.symm (l v)) h) end)
(λ s, match s with tag v h := tag (g v) (eq.rec_on (eq.symm (r v)) h) end)
(λ s, begin cases s, esimp, congruence, rewrite l, reflexivity end)
(λ s, begin cases s, esimp, congruence, rewrite r, reflexivity end)
end
section swap
variable {A : Type}
variable [h : decidable_eq A]
include h
open decidable
definition swap_core (a b r : A) : A :=
if r = a then b
else if r = b then a
else r
lemma swap_core_swap_core (r a b : A) : swap_core a b (swap_core a b r) = r :=
by_cases
(suppose r = a, by_cases
(suppose r = b, begin unfold swap_core, rewrite [if_pos `r = a`, if_pos (eq.refl b), -`r = a`, -`r = b`, if_pos (eq.refl r)] end)
(suppose ¬ r = b,
assert b ≠ a, from assume h, begin rewrite h at this, contradiction end,
begin unfold swap_core, rewrite [*if_pos `r = a`, if_pos (eq.refl b), if_neg `b ≠ a`, `r = a`] end))
(suppose ¬ r = a, by_cases
(suppose r = b, begin unfold swap_core, rewrite [if_neg `¬ r = a`, *if_pos `r = b`, if_pos (eq.refl a), this] end)
(suppose ¬ r = b, begin unfold swap_core, rewrite [*if_neg `¬ r = a`, *if_neg `¬ r = b`, if_neg `¬ r = a`] end))
lemma swap_core_self (r a : A) : swap_core a a r = r :=
by_cases
(suppose r = a, begin unfold swap_core, rewrite [*if_pos this, this] end)
(suppose r ≠ a, begin unfold swap_core, rewrite [*if_neg this] end)
lemma swap_core_comm (r a b : A) : swap_core a b r = swap_core b a r :=
by_cases
(suppose r = a, by_cases
(suppose r = b, begin unfold swap_core, rewrite [if_pos `r = a`, if_pos `r = b`, -`r = a`, -`r = b`] end)
(suppose ¬ r = b, begin unfold swap_core, rewrite [*if_pos `r = a`, if_neg `¬ r = b`] end))
(suppose ¬ r = a, by_cases
(suppose r = b, begin unfold swap_core, rewrite [if_neg `¬ r = a`, *if_pos `r = b`] end)
(suppose ¬ r = b, begin unfold swap_core, rewrite [*if_neg `¬ r = a`, *if_neg `¬ r = b`] end))
definition swap (a b : A) : perm A :=
mk (swap_core a b)
(swap_core a b)
(λ x, abstract by rewrite swap_core_swap_core end)
(λ x, abstract by rewrite swap_core_swap_core end)
lemma swap_self (a : A) : swap a a = id :=
eq_of_to_fun_eq (funext (λ x, begin unfold [swap, fn], rewrite swap_core_self end))
lemma swap_comm (a b : A) : swap a b = swap b a :=
eq_of_to_fun_eq (funext (λ x, begin unfold [swap, fn], rewrite swap_core_comm end))
lemma swap_apply_def (a b : A) (x : A) : swap a b ∙ x = if x = a then b else if x = b then a else x :=
rfl
lemma swap_apply_left (a b : A) : swap a b ∙ a = b :=
if_pos rfl
lemma swap_apply_right (a b : A) : swap a b ∙ b = a :=
by_cases
(suppose b = a, by rewrite [swap_apply_def, this, *if_pos rfl])
(suppose b ≠ a, by rewrite [swap_apply_def, if_pos rfl, if_neg this])
lemma swap_apply_of_ne_of_ne {a b : A} {x : A} : x ≠ a → x ≠ b → swap a b ∙ x = x :=
assume h₁ h₂, by rewrite [swap_apply_def, if_neg h₁, if_neg h₂]
lemma swap_swap (a b : A) : swap a b ∘ swap a b = id :=
eq_of_to_fun_eq (funext (λ x, begin unfold [swap, fn, equiv.trans, equiv.refl], rewrite swap_core_swap_core end))
lemma swap_compose_apply (a b : A) (π : perm A) (x : A) : (swap a b ∘ π) ∙ x = if π ∙ x = a then b else if π ∙ x = b then a else π ∙ x :=
begin cases π, reflexivity end
end swap
end equiv
|
1303bebc6c694f71aff563bc9c2bf09c62852542 | 6432ea7a083ff6ba21ea17af9ee47b9c371760f7 | /src/lake/examples/deps/foo/Foo/Baz.lean | 6e098707901d334067e491f6aacf780917ffc912 | [
"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 | 33 | lean | import Foo.Foo
def baz := "baz"
|
661866addcccb5e7afe40a2c546d5b384b165ce6 | ebfc36a919e0b75a83886ec635f471d7f2dca171 | /archive/2021/AoC.lean | 4bb92678e6b65f0f4e802f2e0b711e569ecdade1 | [] | no_license | kaychaks/AoC | b933a125e2c55f632c7728eea841d827d1b5ef38 | 962cc536dda5156ac0b624f156146bf6d12ad8d2 | refs/heads/master | 1,671,715,037,914 | 1,671,632,408,000 | 1,671,632,408,000 | 160,005,656 | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 47 | lean | import AoC.Day1
import AoC.Day2
import AoC.Day3 |
873a4ad11ffeea980fa6e0c7e22bc20c62eba198 | 57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5 | /tactic/norm_num.lean | 82bc2dde527cadd6f7019ae3ee8f25cd0397e68e | [
"Apache-2.0"
] | permissive | louisanu/mathlib | 11f56f2d40dc792bc05ee2f78ea37d73e98ecbfe | 2bd5e2159d20a8f20d04fc4d382e65eea775ed39 | refs/heads/master | 1,617,706,993,439 | 1,523,163,654,000 | 1,523,163,654,000 | 124,519,997 | 0 | 0 | Apache-2.0 | 1,520,588,283,000 | 1,520,588,283,000 | null | UTF-8 | Lean | false | false | 12,173 | lean | /-
Copyright (c) 2017 Simon Hudon All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Simon Hudon, Mario Carneiro
Evaluating arithmetic expressions including *, +, -, ^, ≤
-/
import algebra.group_power data.rat tactic.interactive
universes u v w
open tactic
namespace expr
protected meta def to_pos_rat : expr → option ℚ
| `(%%e₁ / %%e₂) := do m ← e₁.to_nat, n ← e₂.to_nat, some (rat.mk m n)
| e := do n ← e.to_nat, return (rat.of_int n)
protected meta def to_rat : expr → option ℚ
| `(has_neg.neg %%e) := do q ← e.to_pos_rat, some (-q)
| e := e.to_pos_rat
protected meta def of_rat (α : expr) : ℚ → tactic expr
| ⟨(n:ℕ), d, h, c⟩ := do
e₁ ← expr.of_nat α n,
if d = 1 then return e₁ else
do e₂ ← expr.of_nat α d,
tactic.mk_app ``has_div.div [e₁, e₂]
| ⟨-[1+n], d, h, c⟩ := do
e₁ ← expr.of_nat α (n+1),
e ← (if d = 1 then return e₁ else do
e₂ ← expr.of_nat α d,
tactic.mk_app ``has_div.div [e₁, e₂]),
tactic.mk_app ``has_neg.neg [e]
end expr
namespace norm_num
variable {α : Type u}
theorem bit0_zero [add_group α] : bit0 (0 : α) = 0 := add_zero _
theorem bit1_zero [add_group α] [has_one α] : bit1 (0 : α) = 1 :=
by rw [bit1, bit0_zero, zero_add]
lemma pow_bit0_helper [monoid α] (a t : α) (b : ℕ) (h : a ^ b = t) :
a ^ bit0 b = t * t :=
by simp [pow_bit0, h]
lemma pow_bit1_helper [monoid α] (a t : α) (b : ℕ) (h : a ^ b = t) :
a ^ bit1 b = t * t * a :=
by simp [pow_bit1, h]
lemma lt_add_of_pos_helper [ordered_cancel_comm_monoid α]
(a b c : α) (h : a + b = c) (h₂ : 0 < b) : a < c :=
h ▸ (lt_add_iff_pos_right _).2 h₂
lemma nat_div_helper (a b q r : ℕ) (h : r + q * b = a) (h₂ : r < b) : a / b = q :=
by rw [← h, nat.add_mul_div_right _ _ (lt_of_le_of_lt (nat.zero_le _) h₂),
nat.div_eq_of_lt h₂, zero_add]
lemma int_div_helper (a b q r : ℤ) (h : r + q * b = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a / b = q :=
by rw [← h, int.add_mul_div_right _ _ (ne_of_gt (lt_of_le_of_lt h₁ h₂)),
int.div_eq_zero_of_lt h₁ h₂, zero_add]
lemma nat_mod_helper (a b q r : ℕ) (h : r + q * b = a) (h₂ : r < b) : a % b = r :=
by rw [← h, nat.add_mul_mod_self_right, nat.mod_eq_of_lt h₂]
lemma int_mod_helper (a b q r : ℤ) (h : r + q * b = a) (h₁ : 0 ≤ r) (h₂ : r < b) : a % b = r :=
by rw [← h, int.add_mul_mod_self, int.mod_eq_of_lt h₁ h₂]
meta def eval_pow (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr)
| `(@has_pow.pow %%α _ %%m %%e₁ %%e₂) :=
match m with
| `(nat.has_pow) :=
mk_app ``nat.pow [e₁, e₂] >>= eval_pow
| `(@monoid.has_pow %%α %%m) :=
mk_app ``monoid.pow [e₁, e₂] >>= eval_pow
| _ := failed
end
| `(monoid.pow %%e₁ 0) := do
p ← mk_app ``pow_zero [e₁],
a ← infer_type e₁,
o ← mk_app ``has_one.one [a],
return (o, p)
| `(monoid.pow %%e₁ 1) := do
p ← mk_app ``pow_one [e₁],
return (e₁, p)
| `(monoid.pow %%e₁ (bit0 %%e₂)) := do
e ← mk_app ``monoid.pow [e₁, e₂],
(e', p) ← simp e,
p' ← mk_app ``norm_num.pow_bit0_helper [e₁, e', e₂, p],
e'' ← to_expr ``(%%e' * %%e'),
return (e'', p')
| `(monoid.pow %%e₁ (bit1 %%e₂)) := do
e ← mk_app ``monoid.pow [e₁, e₂],
(e', p) ← simp e,
p' ← mk_app ``norm_num.pow_bit1_helper [e₁, e', e₂, p],
e'' ← to_expr ``(%%e' * %%e' * %%e₁),
return (e'', p')
| `(nat.pow %%e₁ %%e₂) := do
p₁ ← mk_app ``nat.pow_eq_pow [e₁, e₂],
e ← mk_app ``monoid.pow [e₁, e₂],
(e', p₂) ← simp e,
p ← mk_eq_trans p₁ p₂,
return (e', p)
| _ := failed
meta def prove_pos : instance_cache → expr → tactic (instance_cache × expr)
| c `(has_one.one _) := do (c, p) ← c.mk_app ``zero_lt_one [], return (c, p)
| c `(bit0 %%e) := do (c, p) ← prove_pos c e, (c, p) ← c.mk_app ``bit0_pos [e, p], return (c, p)
| c `(bit1 %%e) := do (c, p) ← prove_pos c e, (c, p) ← c.mk_app ``bit1_pos' [e, p], return (c, p)
| c `(%%e₁ / %%e₂) := do
(c, p₁) ← prove_pos c e₁, (c, p₂) ← prove_pos c e₂,
(c, p) ← c.mk_app ``div_pos_of_pos_of_pos [e₁, e₂, p₁, p₂],
return (c, p)
| c e := failed
meta def prove_lt (simp : expr → tactic (expr × expr)) : instance_cache → expr → expr → tactic (instance_cache × expr)
| c `(- %%e₁) `(- %%e₂) := do
(c, p) ← prove_lt c e₁ e₂,
(c, p) ← c.mk_app ``neg_lt_neg [e₁, e₂, p],
return (c, p)
| c `(- %%e₁) `(has_zero.zero _) := do
(c, p) ← prove_pos c e₁,
(c, p) ← c.mk_app ``neg_neg_of_pos [e₁, p],
return (c, p)
| c `(- %%e₁) e₂ := do
(c, p₁) ← prove_pos c e₁,
(c, me₁) ← c.mk_app ``has_neg.neg [e₁],
(c, p₁) ← c.mk_app ``neg_neg_of_pos [e₁, p₁],
(c, p₂) ← prove_pos c e₂,
(c, z) ← c.mk_app ``has_zero.zero [],
(c, p) ← c.mk_app ``lt_trans [me₁, z, e₂, p₁, p₂],
return (c, p)
| c `(has_zero.zero _) e₂ := prove_pos c e₂
| c e₁ e₂ := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
d ← expr.of_rat c.α (n₂ - n₁),
(c, e₃) ← c.mk_app ``has_add.add [e₁, d],
(e₂', p) ← norm_num e₃,
guard (e₂' =ₐ e₂),
(c, p') ← prove_pos c d,
(c, p) ← c.mk_app ``norm_num.lt_add_of_pos_helper [e₁, d, e₂, p, p'],
return (c, p)
private meta def true_intro (p : expr) : tactic (expr × expr) :=
prod.mk <$> mk_const `true <*> mk_app ``eq_true_intro [p]
private meta def false_intro (p : expr) : tactic (expr × expr) :=
prod.mk <$> mk_const `false <*> mk_app ``eq_false_intro [p]
meta def eval_ineq (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr)
| `(%%e₁ < %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ < n₂ then
do (_, p) ← prove_lt simp c e₁ e₂, true_intro p
else do
(c, p) ← if n₁ = n₂ then c.mk_app ``lt_irrefl [e₁] else
(do (c, p') ← prove_lt simp c e₂ e₁,
c.mk_app ``not_lt_of_gt [e₁, e₂, p']),
false_intro p
| `(%%e₁ ≤ %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ ≤ n₂ then do
(c, p) ← if n₁ = n₂ then c.mk_app ``le_refl [e₁] else
(do (c, p') ← prove_lt simp c e₁ e₂,
c.mk_app ``le_of_lt [e₁, e₂, p']),
true_intro p
else do
(c, p) ← prove_lt simp c e₂ e₁,
(c, p) ← c.mk_app ``not_le_of_gt [e₁, e₂, p],
false_intro p
| `(%%e₁ = %%e₂) := do
n₁ ← e₁.to_rat, n₂ ← e₂.to_rat,
c ← infer_type e₁ >>= mk_instance_cache,
if n₁ < n₂ then do
(c, p) ← prove_lt simp c e₁ e₂,
(c, p) ← c.mk_app ``ne_of_lt [e₁, e₂, p],
false_intro p
else if n₂ < n₁ then do
(c, p) ← prove_lt simp c e₂ e₁,
(c, p) ← c.mk_app ``ne_of_gt [e₁, e₂, p],
false_intro p
else mk_eq_refl e₁ >>= true_intro
| `(%%e₁ > %%e₂) := mk_app ``has_lt.lt [e₂, e₁] >>= simp
| `(%%e₁ ≥ %%e₂) := mk_app ``has_le.le [e₂, e₁] >>= simp
| `(%%e₁ ≠ %%e₂) := do e ← mk_app ``eq [e₁, e₂], mk_app ``not [e] >>= simp
| _ := failed
meta def eval_div_ext (simp : expr → tactic (expr × expr)) : expr → tactic (expr × expr)
| `(has_inv.inv %%e) := do
c ← infer_type e >>= mk_instance_cache,
(c, p₁) ← c.mk_app ``inv_eq_one_div [e],
(c, o) ← c.mk_app ``has_one.one [],
(c, e') ← c.mk_app ``has_div.div [o, e],
(do (e'', p₂) ← simp e',
p ← mk_eq_trans p₁ p₂,
return (e'', p)) <|> return (e', p₁)
| `(%%e₁ / %%e₂) := do
α ← infer_type e₁,
c ← mk_instance_cache α,
match α with
| `(nat) := do
n₁ ← e₁.to_nat, n₂ ← e₂.to_nat,
q ← expr.of_nat α (n₁ / n₂),
r ← expr.of_nat α (n₁ % n₂),
(c, e₃) ← c.mk_app ``has_mul.mul [q, e₂],
(c, e₃) ← c.mk_app ``has_add.add [r, e₃],
(e₁', p) ← norm_num e₃,
guard (e₁' =ₐ e₁),
(c, p') ← prove_lt simp c r e₂,
p ← mk_app ``norm_num.nat_div_helper [e₁, e₂, q, r, p, p'],
return (q, p)
| `(int) := match e₂ with
| `(- %%e₂') := do
(c, p₁) ← c.mk_app ``int.div_neg [e₁, e₂'],
(c, e) ← c.mk_app ``has_div.div [e₁, e₂'],
(c, e) ← c.mk_app ``has_neg.neg [e],
(e', p₂) ← simp e,
p ← mk_eq_trans p₁ p₂,
return (e', p)
| _ := do
n₁ ← e₁.to_int,
n₂ ← e₂.to_int,
q ← expr.of_rat α $ rat.of_int (n₁ / n₂),
r ← expr.of_rat α $ rat.of_int (n₁ % n₂),
(c, e₃) ← c.mk_app ``has_mul.mul [q, e₂],
(c, e₃) ← c.mk_app ``has_add.add [r, e₃],
(e₁', p) ← norm_num e₃,
guard (e₁' =ₐ e₁),
(c, r0) ← c.mk_app ``has_zero.zero [],
(c, r0) ← c.mk_app ``has_le.le [r0, r],
(_, p₁) ← simp r0,
p₁ ← mk_app ``of_eq_true [p₁],
(c, p₂) ← prove_lt simp c r e₂,
p ← mk_app ``norm_num.int_div_helper [e₁, e₂, q, r, p, p₁, p₂],
return (q, p)
end
| _ := failed
end
| `(%%e₁ % %%e₂) := do
α ← infer_type e₁,
c ← mk_instance_cache α,
match α with
| `(nat) := do
n₁ ← e₁.to_nat, n₂ ← e₂.to_nat,
q ← expr.of_nat α (n₁ / n₂),
r ← expr.of_nat α (n₁ % n₂),
(c, e₃) ← c.mk_app ``has_mul.mul [q, e₂],
(c, e₃) ← c.mk_app ``has_add.add [r, e₃],
(e₁', p) ← norm_num e₃,
guard (e₁' =ₐ e₁),
(c, p') ← prove_lt simp c r e₂,
p ← mk_app ``norm_num.nat_mod_helper [e₁, e₂, q, r, p, p'],
return (r, p)
| `(int) := match e₂ with
| `(- %%e₂') := do
(c, p₁) ← c.mk_app ``int.mod_neg [e₁, e₂'],
(c, e) ← c.mk_app ``has_mod.mod [e₁, e₂'],
(e', p₂) ← simp e,
p ← mk_eq_trans p₁ p₂,
return (e', p)
| _ := do
n₁ ← e₁.to_int,
n₂ ← e₂.to_int,
q ← expr.of_rat α $ rat.of_int (n₁ / n₂),
r ← expr.of_rat α $ rat.of_int (n₁ % n₂),
(c, e₃) ← c.mk_app ``has_mul.mul [q, e₂],
(c, e₃) ← c.mk_app ``has_add.add [r, e₃],
(e₁', p) ← norm_num e₃,
guard (e₁' =ₐ e₁),
(c, r0) ← c.mk_app ``has_zero.zero [],
(c, r0) ← c.mk_app ``has_le.le [r0, r],
(_, p₁) ← simp r0,
p₁ ← mk_app ``of_eq_true [p₁],
(c, p₂) ← prove_lt simp c r e₂,
p ← mk_app ``norm_num.int_mod_helper [e₁, e₂, q, r, p, p₁, p₂],
return (r, p)
end
| _ := failed
end
| _ := failed
meta def derive1 (simp : expr → tactic (expr × expr)) (e : expr) :
tactic (expr × expr) :=
norm_num e <|> eval_div_ext simp e <|> eval_pow simp e <|> eval_ineq simp e
meta def derive : expr → tactic (expr × expr) | e :=
do (_, e', pr) ←
ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed)
(λ _ _ _ _ e,
do (new_e, pr) ← derive1 derive e,
guard (¬ new_e =ₐ e),
return ((), new_e, some pr, tt))
`eq e,
return (e', pr)
end norm_num
namespace tactic.interactive
open norm_num interactive interactive.types
/-- Basic version of `norm_num` that does not call `simp`. -/
meta def norm_num1 (loc : parse location) : tactic unit :=
do ns ← loc.get_locals,
tt ← tactic.replace_at derive ns loc.include_goal
| fail "norm_num failed to simplify",
when loc.include_goal $ try tactic.triv,
when (¬ ns.empty) $ try tactic.contradiction
/-- Normalize numerical expressions. Supports the operations
`+` `-` `*` `/` `^` `<` `≤` over ordered fields (or other
appropriate classes), as well as `-` `/` `%` over `ℤ` and `ℕ`. -/
meta def norm_num (loc : parse location) : tactic unit :=
let t := orelse' (norm_num1 loc) $ simp_core {} failed ff [] [] loc in
t >> repeat t
meta def apply_normed (x : parse texpr) : tactic unit :=
do x₁ ← to_expr x,
(x₂,_) ← derive x₁,
tactic.exact x₂
end tactic.interactive
|
09562bb1d20493b68515739b79b9b0b2409702ab | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/ideal/operations.lean | 74202ca58f6f27d39991d1f818d67e019a75a38d | [
"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 | 81,136 | lean | /-
Copyright (c) 2018 Kenny Lau. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenny Lau
-/
import algebra.algebra.operations
import algebra.ring.equiv
import data.nat.choose.sum
import ring_theory.coprime.lemmas
import ring_theory.ideal.quotient
import ring_theory.non_zero_divisors
/-!
# More operations on modules and ideals
-/
universes u v w x
open_locale big_operators pointwise
namespace submodule
variables {R : Type u} {M : Type v}
section comm_semiring
variables [comm_semiring R] [add_comm_monoid M] [module R M]
open_locale pointwise
instance has_scalar' : has_scalar (ideal R) (submodule R M) :=
⟨submodule.map₂ (linear_map.lsmul R M)⟩
/-- This duplicates the global `smul_eq_mul`, but doesn't have to unfold anywhere near as much to
apply. -/
protected lemma _root_.ideal.smul_eq_mul (I J : ideal R) : I • J = I * J := rfl
/-- `N.annihilator` is the ideal of all elements `r : R` such that `r • N = 0`. -/
def annihilator (N : submodule R M) : ideal R :=
(linear_map.lsmul R N).ker
variables {I J : ideal R} {N P : submodule R M}
theorem mem_annihilator {r} : r ∈ N.annihilator ↔ ∀ n ∈ N, r • n = (0:M) :=
⟨λ hr n hn, congr_arg subtype.val (linear_map.ext_iff.1 (linear_map.mem_ker.1 hr) ⟨n, hn⟩),
λ h, linear_map.mem_ker.2 $ linear_map.ext $ λ n, subtype.eq $ h n.1 n.2⟩
theorem mem_annihilator' {r} : r ∈ N.annihilator ↔ N ≤ comap (r • linear_map.id) ⊥ :=
mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩
lemma mem_annihilator_span (s : set M) (r : R) :
r ∈ (submodule.span R s).annihilator ↔ ∀ n : s, r • (n : M) = 0 :=
begin
rw submodule.mem_annihilator,
split,
{ intros h n, exact h _ (submodule.subset_span n.prop) },
{ intros h n hn,
apply submodule.span_induction hn,
{ intros x hx, exact h ⟨x, hx⟩ },
{ exact smul_zero _ },
{ intros x y hx hy, rw [smul_add, hx, hy, zero_add] },
{ intros a x hx, rw [smul_comm, hx, smul_zero] } }
end
lemma mem_annihilator_span_singleton (g : M) (r : R) :
r ∈ (submodule.span R ({g} : set M)).annihilator ↔ r • g = 0 :=
by simp [mem_annihilator_span]
theorem annihilator_bot : (⊥ : submodule R M).annihilator = ⊤ :=
(ideal.eq_top_iff_one _).2 $ mem_annihilator'.2 bot_le
theorem annihilator_eq_top_iff : N.annihilator = ⊤ ↔ N = ⊥ :=
⟨λ H, eq_bot_iff.2 $ λ (n:M) hn, (mem_bot R).2 $
one_smul R n ▸ mem_annihilator.1 ((ideal.eq_top_iff_one _).1 H) n hn,
λ H, H.symm ▸ annihilator_bot⟩
theorem annihilator_mono (h : N ≤ P) : P.annihilator ≤ N.annihilator :=
λ r hrp, mem_annihilator.2 $ λ n hn, mem_annihilator.1 hrp n $ h hn
theorem annihilator_supr (ι : Sort w) (f : ι → submodule R M) :
(annihilator ⨆ i, f i) = ⨅ i, annihilator (f i) :=
le_antisymm (le_infi $ λ i, annihilator_mono $ le_supr _ _)
(λ r H, mem_annihilator'.2 $ supr_le $ λ i,
have _ := (mem_infi _).1 H i, mem_annihilator'.1 this)
theorem smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N := apply_mem_map₂ _ hr hn
theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P := map₂_le
@[elab_as_eliminator]
theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N)
(Hb : ∀ (r ∈ I) (n ∈ N), p (r • n))
(H1 : ∀ x y, p x → p y → p (x + y)) : p x :=
begin
have H0 : p 0 := by simpa only [zero_smul] using Hb 0 I.zero_mem 0 N.zero_mem,
refine submodule.supr_induction _ H _ H0 H1,
rintros ⟨i, hi⟩ m ⟨j, hj, (rfl : i • _ = m) ⟩,
exact Hb _ hi _ hj,
end
theorem mem_smul_span_singleton {I : ideal R} {m : M} {x : M} :
x ∈ I • span R ({m} : set M) ↔ ∃ y ∈ I, y • m = x :=
⟨λ hx, smul_induction_on hx
(λ r hri n hnm,
let ⟨s, hs⟩ := mem_span_singleton.1 hnm in ⟨r * s, I.mul_mem_right _ hri, hs ▸ mul_smul r s m⟩)
(λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩,
⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩),
λ ⟨y, hyi, hy⟩, hy ▸ smul_mem_smul hyi (subset_span $ set.mem_singleton m)⟩
theorem smul_le_right : I • N ≤ N :=
smul_le.2 $ λ r hr n, N.smul_mem r
theorem smul_mono (hij : I ≤ J) (hnp : N ≤ P) : I • N ≤ J • P := map₂_le_map₂ hij hnp
theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N := map₂_le_map₂_left h
theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P := map₂_le_map₂_right h
lemma map_le_smul_top (I : ideal R) (f : R →ₗ[R] M) :
submodule.map f I ≤ I • (⊤ : submodule R M) :=
begin
rintros _ ⟨y, hy, rfl⟩,
rw [← mul_one y, ← smul_eq_mul, f.map_smul],
exact smul_mem_smul hy mem_top
end
@[simp] theorem annihilator_smul (N : submodule R M) : annihilator N • N = ⊥ :=
eq_bot_iff.2 (smul_le.2 (λ r, mem_annihilator.1))
@[simp] theorem annihilator_mul (I : ideal R) : annihilator I * I = ⊥ :=
annihilator_smul I
@[simp] theorem mul_annihilator (I : ideal R) : I * annihilator I = ⊥ :=
by rw [mul_comm, annihilator_mul]
variables (I J N P)
@[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ := map₂_bot_right _ _
@[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ := map₂_bot_left _ _
@[simp] theorem top_smul : (⊤ : ideal R) • N = N :=
le_antisymm smul_le_right $ λ r hri, one_smul R r ▸ smul_mem_smul mem_top hri
theorem smul_sup : I • (N ⊔ P) = I • N ⊔ I • P := map₂_sup_right _ _ _ _
theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N := map₂_sup_left _ _ _ _
protected theorem smul_assoc : (I • J) • N = I • (J • N) :=
le_antisymm (smul_le.2 $ λ rs hrsij t htn,
smul_induction_on hrsij
(λ r hr s hs,
(@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ smul_mem_smul hr (smul_mem_smul hs htn))
(λ x y, (add_smul x y t).symm ▸ submodule.add_mem _))
(smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • linear_map.id) ((I • J) • N),
from this hsn,
smul_le.2 $ λ s hs n hn, show r • (s • n) ∈ (I • J) • N,
from mul_smul r s n ▸ smul_mem_smul (smul_mem_smul hr hs) hn)
variables (S : set R) (T : set M)
theorem span_smul_span : (ideal.span S) • (span R T) =
span R (⋃ (s ∈ S) (t ∈ T), {s • t}) :=
(map₂_span_span _ _ _ _).trans $ congr_arg _ $ set.image2_eq_Union _ _ _
lemma ideal_span_singleton_smul (r : R) (N : submodule R M) :
(ideal.span {r} : ideal R) • N = r • N :=
begin
have : span R (⋃ (t : M) (x : t ∈ N), {r • t}) = r • N,
{ convert span_eq _, exact (set.image_eq_Union _ (N : set M)).symm },
conv_lhs { rw [← span_eq N, span_smul_span] },
simpa
end
lemma span_smul_eq (r : R) (s : set M) : span R (r • s) = r • span R s :=
by rw [← ideal_span_singleton_smul, span_smul_span, ←set.image2_eq_Union,
set.image2_singleton_left, set.image_smul]
lemma mem_of_span_top_of_smul_mem (M' : submodule R M)
(s : set R) (hs : ideal.span s = ⊤) (x : M) (H : ∀ r : s, (r : R) • x ∈ M') : x ∈ M' :=
begin
suffices : (⊤ : ideal R) • (span R ({x} : set M)) ≤ M',
{ rw top_smul at this, exact this (subset_span (set.mem_singleton x)) },
rw [← hs, span_smul_span, span_le],
simpa using H
end
/-- Given `s`, a generating set of `R`, to check that an `x : M` falls in a
submodule `M'` of `x`, we only need to show that `r ^ n • x ∈ M'` for some `n` for each `r : s`. -/
lemma mem_of_span_eq_top_of_smul_pow_mem (M' : submodule R M)
(s : set R) (hs : ideal.span s = ⊤) (x : M)
(H : ∀ r : s, ∃ (n : ℕ), (r ^ n : R) • x ∈ M') : x ∈ M' :=
begin
obtain ⟨s', hs₁, hs₂⟩ := (ideal.span_eq_top_iff_finite _).mp hs,
replace H : ∀ r : s', ∃ (n : ℕ), (r ^ n : R) • x ∈ M' := λ r, H ⟨_, hs₁ r.prop⟩,
choose n₁ n₂ using H,
let N := s'.attach.sup n₁,
have hs' := ideal.span_pow_eq_top (s' : set R) hs₂ N,
apply M'.mem_of_span_top_of_smul_mem _ hs',
rintro ⟨_, r, hr, rfl⟩,
convert M'.smul_mem (r ^ (N - n₁ ⟨r, hr⟩)) (n₂ ⟨r, hr⟩) using 1,
simp only [subtype.coe_mk, smul_smul, ← pow_add],
rw tsub_add_cancel_of_le (finset.le_sup (s'.mem_attach _) : n₁ ⟨r, hr⟩ ≤ N),
end
variables {M' : Type w} [add_comm_monoid M'] [module R M']
theorem map_smul'' (f : M →ₗ[R] M') : (I • N).map f = I • N.map f :=
le_antisymm (map_le_iff_le_comap.2 $ smul_le.2 $ λ r hr n hn, show f (r • n) ∈ I • N.map f,
from (f.map_smul r n).symm ▸ smul_mem_smul hr (mem_map_of_mem hn)) $
smul_le.2 $ λ r hr n hn, let ⟨p, hp, hfp⟩ := mem_map.1 hn in
hfp ▸ f.map_smul r p ▸ mem_map_of_mem (smul_mem_smul hr hp)
variables {I}
lemma mem_smul_span {s : set M} {x : M} :
x ∈ I • submodule.span R s ↔ x ∈ submodule.span R (⋃ (a ∈ I) (b ∈ s), ({a • b} : set M)) :=
by rw [← I.span_eq, submodule.span_smul_span, I.span_eq]; refl
variables (I)
/-- If `x` is an `I`-multiple of the submodule spanned by `f '' s`,
then we can write `x` as an `I`-linear combination of the elements of `f '' s`. -/
lemma exists_sum_of_mem_ideal_smul_span {ι : Type*} (s : set ι) (f : ι → M) (x : M)
(hx : x ∈ I • span R (f '' s)) :
∃ (a : s →₀ R) (ha : ∀ i, a i ∈ I), a.sum (λ i c, c • f i) = x :=
begin
refine span_induction (mem_smul_span.mp hx) _ _ _ _,
{ simp only [set.mem_Union, set.mem_range, set.mem_singleton_iff],
rintros x ⟨y, hy, x, ⟨i, hi, rfl⟩, rfl⟩,
refine ⟨finsupp.single ⟨i, hi⟩ y, λ j, _, _⟩,
{ letI := classical.dec_eq s,
rw finsupp.single_apply, split_ifs, { assumption }, { exact I.zero_mem } },
refine @finsupp.sum_single_index s R M _ _ ⟨i, hi⟩ _ (λ i y, y • f i) _,
simp },
{ exact ⟨0, λ i, I.zero_mem, finsupp.sum_zero_index⟩ },
{ rintros x y ⟨ax, hax, rfl⟩ ⟨ay, hay, rfl⟩,
refine ⟨ax + ay, λ i, I.add_mem (hax i) (hay i), finsupp.sum_add_index _ _⟩;
intros; simp only [zero_smul, add_smul] },
{ rintros c x ⟨a, ha, rfl⟩,
refine ⟨c • a, λ i, I.mul_mem_left c (ha i), _⟩,
rw [finsupp.sum_smul_index, finsupp.smul_sum];
intros; simp only [zero_smul, mul_smul] },
end
@[simp] lemma smul_comap_le_comap_smul (f : M →ₗ[R] M') (S : submodule R M') (I : ideal R) :
I • S.comap f ≤ (I • S).comap f :=
begin
refine (submodule.smul_le.mpr (λ r hr x hx, _)),
rw [submodule.mem_comap] at ⊢ hx,
rw f.map_smul,
exact submodule.smul_mem_smul hr hx
end
end comm_semiring
section comm_ring
variables [comm_ring R] [add_comm_group M] [module R M]
variables {N N₁ N₂ P P₁ P₂ : submodule R M}
/-- `N.colon P` is the ideal of all elements `r : R` such that `r • P ⊆ N`. -/
def colon (N P : submodule R M) : ideal R :=
annihilator (P.map N.mkq)
theorem mem_colon {r} : r ∈ N.colon P ↔ ∀ p ∈ P, r • p ∈ N :=
mem_annihilator.trans ⟨λ H p hp, (quotient.mk_eq_zero N).1 (H (quotient.mk p) (mem_map_of_mem hp)),
λ H m ⟨p, hp, hpm⟩, hpm ▸ (N.mkq).map_smul r p ▸ (quotient.mk_eq_zero N).2 $ H p hp⟩
theorem mem_colon' {r} : r ∈ N.colon P ↔ P ≤ comap (r • linear_map.id) N :=
mem_colon
theorem colon_mono (hn : N₁ ≤ N₂) (hp : P₁ ≤ P₂) : N₁.colon P₂ ≤ N₂.colon P₁ :=
λ r hrnp, mem_colon.2 $ λ p₁ hp₁, hn $ mem_colon.1 hrnp p₁ $ hp hp₁
theorem infi_colon_supr (ι₁ : Sort w) (f : ι₁ → submodule R M)
(ι₂ : Sort x) (g : ι₂ → submodule R M) :
(⨅ i, f i).colon (⨆ j, g j) = ⨅ i j, (f i).colon (g j) :=
le_antisymm (le_infi $ λ i, le_infi $ λ j, colon_mono (infi_le _ _) (le_supr _ _))
(λ r H, mem_colon'.2 $ supr_le $ λ j, map_le_iff_le_comap.1 $ le_infi $ λ i,
map_le_iff_le_comap.2 $ mem_colon'.1 $ have _ := ((mem_infi _).1 H i),
have _ := ((mem_infi _).1 this j), this)
end comm_ring
end submodule
namespace ideal
section mul_and_radical
variables {R : Type u} {ι : Type*} [comm_semiring R]
variables {I J K L : ideal R}
instance : has_mul (ideal R) := ⟨(•)⟩
@[simp] lemma add_eq_sup : I + J = I ⊔ J := rfl
@[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl
@[simp] lemma one_eq_top : (1 : ideal R) = ⊤ :=
by erw [submodule.one_eq_range, linear_map.range_id]
theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J :=
submodule.smul_mem_smul hr hs
theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J :=
mul_comm r s ▸ mul_mem_mul hr hs
lemma pow_mem_pow {x : R} (hx : x ∈ I) (n : ℕ) : x ^ n ∈ I ^ n :=
begin
induction n with n ih, { simp only [pow_zero, ideal.one_eq_top], },
simpa only [pow_succ] using mul_mem_mul hx ih,
end
theorem mul_le : I * J ≤ K ↔ ∀ (r ∈ I) (s ∈ J), r * s ∈ K :=
submodule.smul_le
lemma mul_le_left : I * J ≤ J :=
ideal.mul_le.2 (λ r hr s, J.mul_mem_left _)
lemma mul_le_right : I * J ≤ I :=
ideal.mul_le.2 (λ r hr s hs, I.mul_mem_right _ hr)
@[simp] lemma sup_mul_right_self : I ⊔ (I * J) = I :=
sup_eq_left.2 ideal.mul_le_right
@[simp] lemma sup_mul_left_self : I ⊔ (J * I) = I :=
sup_eq_left.2 ideal.mul_le_left
@[simp] lemma mul_right_self_sup : (I * J) ⊔ I = I :=
sup_eq_right.2 ideal.mul_le_right
@[simp] lemma mul_left_self_sup : (J * I) ⊔ I = I :=
sup_eq_right.2 ideal.mul_le_left
variables (I J K)
protected theorem mul_comm : I * J = J * I :=
le_antisymm (mul_le.2 $ λ r hrI s hsJ, mul_mem_mul_rev hsJ hrI)
(mul_le.2 $ λ r hrJ s hsI, mul_mem_mul_rev hsI hrJ)
protected theorem mul_assoc : (I * J) * K = I * (J * K) :=
submodule.smul_assoc I J K
theorem span_mul_span (S T : set R) : span S * span T =
span ⋃ (s ∈ S) (t ∈ T), {s * t} :=
submodule.span_smul_span S T
variables {I J K}
lemma span_mul_span' (S T : set R) : span S * span T = span (S*T) :=
by { unfold span, rw submodule.span_mul_span, }
lemma span_singleton_mul_span_singleton (r s : R) :
span {r} * span {s} = (span {r * s} : ideal R) :=
by { unfold span, rw [submodule.span_mul_span, set.singleton_mul_singleton], }
lemma span_singleton_pow (s : R) (n : ℕ):
span {s} ^ n = (span {s ^ n} : ideal R) :=
begin
induction n with n ih, { simp [set.singleton_one], },
simp only [pow_succ, ih, span_singleton_mul_span_singleton],
end
lemma mem_mul_span_singleton {x y : R} {I : ideal R} :
x ∈ I * span {y} ↔ ∃ z ∈ I, z * y = x :=
submodule.mem_smul_span_singleton
lemma mem_span_singleton_mul {x y : R} {I : ideal R} :
x ∈ span {y} * I ↔ ∃ z ∈ I, y * z = x :=
by simp only [mul_comm, mem_mul_span_singleton]
lemma le_span_singleton_mul_iff {x : R} {I J : ideal R} :
I ≤ span {x} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI :=
show (∀ {zI} (hzI : zI ∈ I), zI ∈ span {x} * J) ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI,
by simp only [mem_span_singleton_mul]
lemma span_singleton_mul_le_iff {x : R} {I J : ideal R} :
span {x} * I ≤ J ↔ ∀ z ∈ I, x * z ∈ J :=
begin
simp only [mul_le, mem_span_singleton_mul, mem_span_singleton],
split,
{ intros h zI hzI,
exact h x (dvd_refl x) zI hzI },
{ rintros h _ ⟨z, rfl⟩ zI hzI,
rw [mul_comm x z, mul_assoc],
exact J.mul_mem_left _ (h zI hzI) },
end
lemma span_singleton_mul_le_span_singleton_mul {x y : R} {I J : ideal R} :
span {x} * I ≤ span {y} * J ↔ ∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ :=
by simp only [span_singleton_mul_le_iff, mem_span_singleton_mul, eq_comm]
lemma eq_span_singleton_mul {x : R} (I J : ideal R) :
I = span {x} * J ↔ ((∀ zI ∈ I, ∃ zJ ∈ J, x * zJ = zI) ∧ (∀ z ∈ J, x * z ∈ I)) :=
by simp only [le_antisymm_iff, le_span_singleton_mul_iff, span_singleton_mul_le_iff]
lemma span_singleton_mul_eq_span_singleton_mul {x y : R} (I J : ideal R) :
span {x} * I = span {y} * J ↔
((∀ zI ∈ I, ∃ zJ ∈ J, x * zI = y * zJ) ∧
(∀ zJ ∈ J, ∃ zI ∈ I, x * zI = y * zJ)) :=
by simp only [le_antisymm_iff, span_singleton_mul_le_span_singleton_mul, eq_comm]
lemma prod_span {ι : Type*} (s : finset ι) (I : ι → set R) :
(∏ i in s, ideal.span (I i)) = ideal.span (∏ i in s, I i) :=
submodule.prod_span s I
lemma prod_span_singleton {ι : Type*} (s : finset ι) (I : ι → R) :
(∏ i in s, ideal.span ({I i} : set R)) = ideal.span {∏ i in s, I i} :=
submodule.prod_span_singleton s I
lemma finset_inf_span_singleton {ι : Type*} (s : finset ι) (I : ι → R)
(hI : set.pairwise ↑s (is_coprime on I)) :
(s.inf $ λ i, ideal.span ({I i} : set R)) = ideal.span {∏ i in s, I i} :=
begin
ext x,
simp only [submodule.mem_finset_inf, ideal.mem_span_singleton],
exact ⟨finset.prod_dvd_of_coprime hI,
λ h i hi, (finset.dvd_prod_of_mem _ hi).trans h⟩
end
lemma infi_span_singleton {ι : Type*} [fintype ι] (I : ι → R)
(hI : ∀ i j (hij : i ≠ j), is_coprime (I i) (I j)):
(⨅ i, ideal.span ({I i} : set R)) = ideal.span {∏ i, I i} :=
begin
rw [← finset.inf_univ_eq_infi, finset_inf_span_singleton],
rwa [finset.coe_univ, set.pairwise_univ]
end
theorem mul_le_inf : I * J ≤ I ⊓ J :=
mul_le.2 $ λ r hri s hsj, ⟨I.mul_mem_right s hri, J.mul_mem_left r hsj⟩
theorem multiset_prod_le_inf {s : multiset (ideal R)} :
s.prod ≤ s.inf :=
begin
classical, refine s.induction_on _ _,
{ rw [multiset.inf_zero], exact le_top },
intros a s ih,
rw [multiset.prod_cons, multiset.inf_cons],
exact le_trans mul_le_inf (inf_le_inf le_rfl ih)
end
theorem prod_le_inf {s : finset ι} {f : ι → ideal R} : s.prod f ≤ s.inf f :=
multiset_prod_le_inf
theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J :=
le_antisymm mul_le_inf $ λ r ⟨hri, hrj⟩,
let ⟨s, hsi, t, htj, hst⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in
mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj)
(mul_mem_mul hri htj)
variables (I)
@[simp] theorem mul_bot : I * ⊥ = ⊥ :=
submodule.smul_bot I
@[simp] theorem bot_mul : ⊥ * I = ⊥ :=
submodule.bot_smul I
@[simp] theorem mul_top : I * ⊤ = I :=
ideal.mul_comm ⊤ I ▸ submodule.top_smul I
@[simp] theorem top_mul : ⊤ * I = I :=
submodule.top_smul I
variables {I}
theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L :=
submodule.smul_mono hik hjl
theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K :=
submodule.smul_mono_left h
theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K :=
submodule.smul_mono_right h
variables (I J K)
theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K :=
submodule.smul_sup I J K
theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K :=
submodule.sup_smul I J K
variables {I J K}
lemma pow_le_pow {m n : ℕ} (h : m ≤ n) :
I^n ≤ I^m :=
begin
cases nat.exists_eq_add_of_le h with k hk,
rw [hk, pow_add],
exact le_trans (mul_le_inf) (inf_le_left)
end
lemma pow_le_self {n : ℕ} (hn : n ≠ 0) : I^n ≤ I :=
calc I^n ≤ I ^ 1 : pow_le_pow (nat.pos_of_ne_zero hn)
... = I : pow_one _
lemma mul_eq_bot {R : Type*} [comm_ring R] [is_domain R] {I J : ideal R} :
I * J = ⊥ ↔ I = ⊥ ∨ J = ⊥ :=
⟨λ hij, or_iff_not_imp_left.mpr (λ I_ne_bot, J.eq_bot_iff.mpr (λ j hj,
let ⟨i, hi, ne0⟩ := I.ne_bot_iff.mp I_ne_bot in
or.resolve_left (mul_eq_zero.mp ((I * J).eq_bot_iff.mp hij _ (mul_mem_mul hi hj))) ne0)),
λ h, by cases h; rw [← ideal.mul_bot, h, ideal.mul_comm]⟩
instance {R : Type*} [comm_ring R] [is_domain R] : no_zero_divisors (ideal R) :=
{ eq_zero_or_eq_zero_of_mul_eq_zero := λ I J, mul_eq_bot.1 }
/-- A product of ideals in an integral domain is zero if and only if one of the terms is zero. -/
lemma prod_eq_bot {R : Type*} [comm_ring R] [is_domain R]
{s : multiset (ideal R)} : s.prod = ⊥ ↔ ∃ I ∈ s, I = ⊥ :=
prod_zero_iff_exists_zero
/-- The radical of an ideal `I` consists of the elements `r` such that `r^n ∈ I` for some `n`. -/
def radical (I : ideal R) : ideal R :=
{ carrier := { r | ∃ n : ℕ, r ^ n ∈ I },
zero_mem' := ⟨1, (pow_one (0:R)).symm ▸ I.zero_mem⟩,
add_mem' := λ x y ⟨m, hxmi⟩ ⟨n, hyni⟩, ⟨m + n,
(add_pow x y (m + n)).symm ▸ I.sum_mem $
show ∀ c ∈ finset.range (nat.succ (m + n)),
x ^ c * y ^ (m + n - c) * (nat.choose (m + n) c) ∈ I,
from λ c hc, or.cases_on (le_total c m)
(λ hcm, I.mul_mem_right _ $ I.mul_mem_left _ $ nat.add_comm n m ▸
(add_tsub_assoc_of_le hcm n).symm ▸
(pow_add y n (m-c)).symm ▸ I.mul_mem_right _ hyni)
(λ hmc, I.mul_mem_right _ $ I.mul_mem_right _ $ add_tsub_cancel_of_le hmc ▸
(pow_add x m (c-m)).symm ▸ I.mul_mem_right _ hxmi)⟩,
smul_mem' := λ r s ⟨n, hsni⟩, ⟨n, (mul_pow r s n).symm ▸ I.mul_mem_left (r^n) hsni⟩ }
theorem le_radical : I ≤ radical I :=
λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩
variables (R)
theorem radical_top : (radical ⊤ : ideal R) = ⊤ :=
(eq_top_iff_one _).2 ⟨0, submodule.mem_top⟩
variables {R}
theorem radical_mono (H : I ≤ J) : radical I ≤ radical J :=
λ r ⟨n, hrni⟩, ⟨n, H hrni⟩
variables (I)
@[simp] theorem radical_idem : radical (radical I) = radical I :=
le_antisymm (λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩) le_radical
variables {I}
theorem radical_le_radical_iff : radical I ≤ radical J ↔ I ≤ radical J :=
⟨λ h, le_trans le_radical h, λ h, radical_idem J ▸ radical_mono h⟩
theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ :=
⟨λ h, (eq_top_iff_one _).2 $ let ⟨n, hn⟩ := (eq_top_iff_one _).1 h in
@one_pow R _ n ▸ hn, λ h, h.symm ▸ radical_top R⟩
theorem is_prime.radical (H : is_prime I) : radical I = I :=
le_antisymm (λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni) le_radical
variables (I J)
theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) :=
le_antisymm (radical_mono $ sup_le_sup le_radical le_radical) $
λ r ⟨n, hrnij⟩, let ⟨s, hs, t, ht, hst⟩ := submodule.mem_sup.1 hrnij in
@radical_idem _ _ (I ⊔ J) ▸ ⟨n, hst ▸ ideal.add_mem _
(radical_mono le_sup_left hs) (radical_mono le_sup_right ht)⟩
theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J :=
le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right))
(λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right _ hrm,
(pow_add r m n).symm ▸ J.mul_mem_left _ hrn⟩)
theorem radical_mul : radical (I * J) = radical I ⊓ radical J :=
le_antisymm (radical_inf I J ▸ radical_mono $ @mul_le_inf _ _ I J)
(λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩)
variables {I J}
theorem is_prime.radical_le_iff (hj : is_prime J) :
radical I ≤ J ↔ I ≤ J :=
⟨le_trans le_radical, λ hij r ⟨n, hrni⟩, hj.mem_of_pow_mem n $ hij hrni⟩
theorem radical_eq_Inf (I : ideal R) :
radical I = Inf { J : ideal R | I ≤ J ∧ is_prime J } :=
le_antisymm (le_Inf $ λ J hJ, hJ.2.radical_le_iff.2 hJ.1) $
λ r hr, classical.by_contradiction $ λ hri,
let ⟨m, (hrm : r ∉ radical m), him, hm⟩ := zorn_nonempty_partial_order₀
{K : ideal R | r ∉ radical K}
(λ c hc hcc y hyc, ⟨Sup c, λ ⟨n, hrnc⟩, let ⟨y, hyc, hrny⟩ :=
(submodule.mem_Sup_of_directed ⟨y, hyc⟩ hcc.directed_on).1 hrnc in hc hyc ⟨n, hrny⟩,
λ z, le_Sup⟩) I hri in
have ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := λ x hxm, classical.by_contradiction $ λ hrmx, hxm $
hm (m ⊔ span {x}) hrmx le_sup_left ▸ (le_sup_right : _ ≤ m ⊔ span {x})
(subset_span $ set.mem_singleton _),
have is_prime m, from ⟨by rintro rfl; rw radical_top at hrm; exact hrm trivial,
λ x y hxym, or_iff_not_imp_left.2 $ λ hxm, classical.by_contradiction $ λ hym,
let ⟨n, hrn⟩ := this _ hxm,
⟨p, hpm, q, hq, hpqrn⟩ := submodule.mem_sup.1 hrn,
⟨c, hcxq⟩ := mem_span_singleton'.1 hq in
let ⟨k, hrk⟩ := this _ hym,
⟨f, hfm, g, hg, hfgrk⟩ := submodule.mem_sup.1 hrk,
⟨d, hdyg⟩ := mem_span_singleton'.1 hg in
hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c*x),
mul_assoc c x (d*y), mul_left_comm x, ← mul_assoc];
refine m.add_mem (m.mul_mem_right _ hpm) (m.add_mem (m.mul_mem_left _ hfm)
(m.mul_mem_left _ hxym))⟩⟩,
hrm $ this.radical.symm ▸ (Inf_le ⟨him, this⟩ : Inf {J : ideal R | I ≤ J ∧ is_prime J} ≤ m) hr
@[simp] lemma radical_bot_of_is_domain {R : Type u} [comm_ring R] [is_domain R] :
radical (⊥ : ideal R) = ⊥ :=
eq_bot_iff.2 (λ x hx, hx.rec_on (λ n hn, pow_eq_zero hn))
instance : comm_semiring (ideal R) := submodule.comm_semiring
variables (R)
theorem top_pow (n : ℕ) : (⊤ ^ n : ideal R) = ⊤ :=
nat.rec_on n one_eq_top $ λ n ih, by rw [pow_succ, ih, top_mul]
variables {R}
variables (I)
theorem radical_pow (n : ℕ) (H : n > 0) : radical (I^n) = radical I :=
nat.rec_on n (not.elim dec_trivial) (λ n ih H,
or.cases_on (lt_or_eq_of_le $ nat.le_of_lt_succ H)
(λ H, calc radical (I^(n+1))
= radical I ⊓ radical (I^n) : by { rw pow_succ, exact radical_mul _ _ }
... = radical I ⊓ radical I : by rw ih H
... = radical I : inf_idem)
(λ H, H ▸ (pow_one I).symm ▸ rfl)) H
theorem is_prime.mul_le {I J P : ideal R} (hp : is_prime P) :
I * J ≤ P ↔ I ≤ P ∨ J ≤ P :=
⟨λ h, or_iff_not_imp_left.2 $ λ hip j hj, let ⟨i, hi, hip⟩ := set.not_subset.1 hip in
(hp.mem_or_mem $ h $ mul_mem_mul hi hj).resolve_left hip,
λ h, or.cases_on h (le_trans $ le_trans mul_le_inf inf_le_left)
(le_trans $ le_trans mul_le_inf inf_le_right)⟩
theorem is_prime.inf_le {I J P : ideal R} (hp : is_prime P) :
I ⊓ J ≤ P ↔ I ≤ P ∨ J ≤ P :=
⟨λ h, hp.mul_le.1 $ le_trans mul_le_inf h,
λ h, or.cases_on h (le_trans inf_le_left) (le_trans inf_le_right)⟩
theorem is_prime.multiset_prod_le {s : multiset (ideal R)} {P : ideal R}
(hp : is_prime P) (hne : s ≠ 0) :
s.prod ≤ P ↔ ∃ I ∈ s, I ≤ P :=
suffices s.prod ≤ P → ∃ I ∈ s, I ≤ P,
from ⟨this, λ ⟨i, his, hip⟩, le_trans multiset_prod_le_inf $
le_trans (multiset.inf_le his) hip⟩,
begin
classical,
obtain ⟨b, hb⟩ : ∃ b, b ∈ s := multiset.exists_mem_of_ne_zero hne,
obtain ⟨t, rfl⟩ : ∃ t, s = b ::ₘ t,
from ⟨s.erase b, (multiset.cons_erase hb).symm⟩,
refine t.induction_on _ _,
{ simp only [exists_prop, ←multiset.singleton_eq_cons, multiset.prod_singleton,
multiset.mem_singleton, exists_eq_left, imp_self] },
intros a s ih h,
rw [multiset.cons_swap, multiset.prod_cons, hp.mul_le] at h,
rw multiset.cons_swap,
cases h,
{ exact ⟨a, multiset.mem_cons_self a _, h⟩ },
obtain ⟨I, hI, ih⟩ : ∃ I ∈ b ::ₘ s, I ≤ P := ih h,
exact ⟨I, multiset.mem_cons_of_mem hI, ih⟩
end
theorem is_prime.multiset_prod_map_le {s : multiset ι} (f : ι → ideal R) {P : ideal R}
(hp : is_prime P) (hne : s ≠ 0) :
(s.map f).prod ≤ P ↔ ∃ i ∈ s, f i ≤ P :=
begin
rw hp.multiset_prod_le (mt multiset.map_eq_zero.mp hne),
simp_rw [exists_prop, multiset.mem_map, exists_exists_and_eq_and],
end
theorem is_prime.prod_le {s : finset ι} {f : ι → ideal R} {P : ideal R}
(hp : is_prime P) (hne : s.nonempty) :
s.prod f ≤ P ↔ ∃ i ∈ s, f i ≤ P :=
hp.multiset_prod_map_le f (mt finset.val_eq_zero.mp hne.ne_empty)
theorem is_prime.inf_le' {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P)
(hsne: s.nonempty) :
s.inf f ≤ P ↔ ∃ i ∈ s, f i ≤ P :=
⟨λ h, (hp.prod_le hsne).1 $ le_trans prod_le_inf h,
λ ⟨i, his, hip⟩, le_trans (finset.inf_le his) hip⟩
theorem subset_union {R : Type u} [comm_ring R] {I J K : ideal R} :
(I : set R) ⊆ J ∪ K ↔ I ≤ J ∨ I ≤ K :=
⟨λ h, or_iff_not_imp_left.2 $ λ hij s hsi,
let ⟨r, hri, hrj⟩ := set.not_subset.1 hij in classical.by_contradiction $ λ hsk,
or.cases_on (h $ I.add_mem hri hsi)
(λ hj, hrj $ add_sub_cancel r s ▸ J.sub_mem hj ((h hsi).resolve_right hsk))
(λ hk, hsk $ add_sub_cancel' r s ▸ K.sub_mem hk ((h hri).resolve_left hrj)),
λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset_union_left J K)
(λ h, set.subset.trans h $ set.subset_union_right J K)⟩
theorem subset_union_prime' {R : Type u} [comm_ring R] {s : finset ι} {f : ι → ideal R} {a b : ι}
(hp : ∀ i ∈ s, is_prime (f i)) {I : ideal R} :
(I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) ↔ I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i :=
suffices (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) →
I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i,
from ⟨this, λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans
(set.subset_union_left _ _) (set.subset_union_left _ _)) $
λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans
(set.subset_union_right _ _) (set.subset_union_left _ _)) $
λ ⟨i, his, hi⟩, by refine (set.subset.trans hi $ set.subset.trans _ $
set.subset_union_right _ _);
exact set.subset_bUnion_of_mem (finset.mem_coe.2 his)⟩,
begin
generalize hn : s.card = n, intros h,
unfreezingI { induction n with n ih generalizing a b s },
{ clear hp,
rw finset.card_eq_zero at hn, subst hn,
rw [finset.coe_empty, set.bUnion_empty, set.union_empty, subset_union] at h,
simpa only [exists_prop, finset.not_mem_empty, false_and, exists_false, or_false] },
classical,
replace hn : ∃ (i : ι) (t : finset ι), i ∉ t ∧ insert i t = s ∧ t.card = n :=
finset.card_eq_succ.1 hn,
unfreezingI { rcases hn with ⟨i, t, hit, rfl, hn⟩ },
replace hp : is_prime (f i) ∧ ∀ x ∈ t, is_prime (f x) := (t.forall_mem_insert _ _).1 hp,
by_cases Ht : ∃ j ∈ t, f j ≤ f i,
{ obtain ⟨j, hjt, hfji⟩ : ∃ j ∈ t, f j ≤ f i := Ht,
obtain ⟨u, hju, rfl⟩ : ∃ u, j ∉ u ∧ insert j u = t,
{ exact ⟨t.erase j, t.not_mem_erase j, finset.insert_erase hjt⟩ },
have hp' : ∀ k ∈ insert i u, is_prime (f k),
{ rw finset.forall_mem_insert at hp ⊢, exact ⟨hp.1, hp.2.2⟩ },
have hiu : i ∉ u := mt finset.mem_insert_of_mem hit,
have hn' : (insert i u).card = n,
{ rwa finset.card_insert_of_not_mem at hn ⊢, exacts [hiu, hju] },
have h' : (I : set R) ⊆ f a ∪ f b ∪ (⋃ k ∈ (↑(insert i u) : set ι), f k),
{ rw finset.coe_insert at h ⊢, rw finset.coe_insert at h,
simp only [set.bUnion_insert] at h ⊢,
rw [← set.union_assoc ↑(f i)] at h,
erw [set.union_eq_self_of_subset_right hfji] at h,
exact h },
specialize @ih a b (insert i u) hp' hn' h',
refine ih.imp id (or.imp id (exists_imp_exists $ λ k, _)), simp only [exists_prop],
exact and.imp (λ hk, finset.insert_subset_insert i (finset.subset_insert j u) hk) id },
by_cases Ha : f a ≤ f i,
{ have h' : (I : set R) ⊆ f i ∪ f b ∪ (⋃ j ∈ (↑t : set ι), f j),
{ rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc,
set.union_right_comm ↑(f a)] at h,
erw [set.union_eq_self_of_subset_left Ha] at h,
exact h },
specialize @ih i b t hp.2 hn h', right,
rcases ih with ih | ih | ⟨k, hkt, ih⟩,
{ exact or.inr ⟨i, finset.mem_insert_self i t, ih⟩ },
{ exact or.inl ih },
{ exact or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } },
by_cases Hb : f b ≤ f i,
{ have h' : (I : set R) ⊆ f a ∪ f i ∪ (⋃ j ∈ (↑t : set ι), f j),
{ rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_assoc ↑(f a)] at h,
erw [set.union_eq_self_of_subset_left Hb] at h,
exact h },
specialize @ih a i t hp.2 hn h',
rcases ih with ih | ih | ⟨k, hkt, ih⟩,
{ exact or.inl ih },
{ exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, ih⟩) },
{ exact or.inr (or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩) } },
by_cases Hi : I ≤ f i,
{ exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, Hi⟩) },
have : ¬I ⊓ f a ⊓ f b ⊓ t.inf f ≤ f i,
{ rcases t.eq_empty_or_nonempty with (rfl | hsne),
{ rw [finset.inf_empty, inf_top_eq, hp.1.inf_le, hp.1.inf_le, not_or_distrib, not_or_distrib],
exact ⟨⟨Hi, Ha⟩, Hb⟩ },
simp only [hp.1.inf_le, hp.1.inf_le' hsne, not_or_distrib],
exact ⟨⟨⟨Hi, Ha⟩, Hb⟩, Ht⟩ },
rcases set.not_subset.1 this with ⟨r, ⟨⟨⟨hrI, hra⟩, hrb⟩, hr⟩, hri⟩,
by_cases HI : (I : set R) ⊆ f a ∪ f b ∪ ⋃ j ∈ (↑t : set ι), f j,
{ specialize ih hp.2 hn HI, rcases ih with ih | ih | ⟨k, hkt, ih⟩,
{ left, exact ih }, { right, left, exact ih },
{ right, right, exact ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } },
exfalso, rcases set.not_subset.1 HI with ⟨s, hsI, hs⟩,
rw [finset.coe_insert, set.bUnion_insert] at h,
have hsi : s ∈ f i := ((h hsI).resolve_left (mt or.inl hs)).resolve_right (mt or.inr hs),
rcases h (I.add_mem hrI hsI) with ⟨ha | hb⟩ | hi | ht,
{ exact hs (or.inl $ or.inl $ add_sub_cancel' r s ▸ (f a).sub_mem ha hra) },
{ exact hs (or.inl $ or.inr $ add_sub_cancel' r s ▸ (f b).sub_mem hb hrb) },
{ exact hri (add_sub_cancel r s ▸ (f i).sub_mem hi hsi) },
{ rw set.mem_Union₂ at ht, rcases ht with ⟨j, hjt, hj⟩,
simp only [finset.inf_eq_infi, set_like.mem_coe, submodule.mem_infi] at hr,
exact hs (or.inr $ set.mem_bUnion hjt $ add_sub_cancel' r s ▸ (f j).sub_mem hj $ hr j hjt) }
end
/-- Prime avoidance. Atiyah-Macdonald 1.11, Eisenbud 3.3, Stacks 00DS, Matsumura Ex.1.6. -/
theorem subset_union_prime {R : Type u} [comm_ring R] {s : finset ι} {f : ι → ideal R} (a b : ι)
(hp : ∀ i ∈ s, i ≠ a → i ≠ b → is_prime (f i)) {I : ideal R} :
(I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) ↔ ∃ i ∈ s, I ≤ f i :=
suffices (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) → ∃ i, i ∈ s ∧ I ≤ f i,
from ⟨λ h, bex_def.2 $ this h, λ ⟨i, his, hi⟩, set.subset.trans hi $ set.subset_bUnion_of_mem $
show i ∈ (↑s : set ι), from his⟩,
assume h : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i),
begin
classical,
by_cases has : a ∈ s,
{ unfreezingI { obtain ⟨t, hat, rfl⟩ : ∃ t, a ∉ t ∧ insert a t = s :=
⟨s.erase a, finset.not_mem_erase a s, finset.insert_erase has⟩ },
by_cases hbt : b ∈ t,
{ unfreezingI { obtain ⟨u, hbu, rfl⟩ : ∃ u, b ∉ u ∧ insert b u = t :=
⟨t.erase b, finset.not_mem_erase b t, finset.insert_erase hbt⟩ },
have hp' : ∀ i ∈ u, is_prime (f i),
{ intros i hiu, refine hp i (finset.mem_insert_of_mem (finset.mem_insert_of_mem hiu)) _ _;
unfreezingI { rintro rfl }; solve_by_elim only [finset.mem_insert_of_mem, *], },
rw [finset.coe_insert, finset.coe_insert, set.bUnion_insert, set.bUnion_insert,
← set.union_assoc, subset_union_prime' hp', bex_def] at h,
rwa [finset.exists_mem_insert, finset.exists_mem_insert] },
{ have hp' : ∀ j ∈ t, is_prime (f j),
{ intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _;
unfreezingI { rintro rfl }; solve_by_elim only [finset.mem_insert_of_mem, *], },
rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f a : set R),
subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h,
rwa finset.exists_mem_insert } },
{ by_cases hbs : b ∈ s,
{ unfreezingI { obtain ⟨t, hbt, rfl⟩ : ∃ t, b ∉ t ∧ insert b t = s :=
⟨s.erase b, finset.not_mem_erase b s, finset.insert_erase hbs⟩ },
have hp' : ∀ j ∈ t, is_prime (f j),
{ intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _;
unfreezingI { rintro rfl }; solve_by_elim only [finset.mem_insert_of_mem, *], },
rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f b : set R),
subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h,
rwa finset.exists_mem_insert },
cases s.eq_empty_or_nonempty with hse hsne,
{ substI hse, rw [finset.coe_empty, set.bUnion_empty, set.subset_empty_iff] at h,
have : (I : set R) ≠ ∅ := set.nonempty.ne_empty (set.nonempty_of_mem I.zero_mem),
exact absurd h this },
{ cases hsne.bex with i his,
unfreezingI { obtain ⟨t, hit, rfl⟩ : ∃ t, i ∉ t ∧ insert i t = s :=
⟨s.erase i, finset.not_mem_erase i s, finset.insert_erase his⟩ },
have hp' : ∀ j ∈ t, is_prime (f j),
{ intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _;
unfreezingI { rintro rfl }; solve_by_elim only [finset.mem_insert_of_mem, *], },
rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f i : set R),
subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h,
rwa finset.exists_mem_insert } }
end
section dvd
/-- If `I` divides `J`, then `I` contains `J`.
In a Dedekind domain, to divide and contain are equivalent, see `ideal.dvd_iff_le`.
-/
lemma le_of_dvd {I J : ideal R} : I ∣ J → J ≤ I
| ⟨K, h⟩ := h.symm ▸ le_trans mul_le_inf inf_le_left
lemma is_unit_iff {I : ideal R} :
is_unit I ↔ I = ⊤ :=
is_unit_iff_dvd_one.trans ((@one_eq_top R _).symm ▸
⟨λ h, eq_top_iff.mpr (ideal.le_of_dvd h), λ h, ⟨⊤, by rw [mul_top, h]⟩⟩)
instance unique_units : unique ((ideal R)ˣ) :=
{ default := 1,
uniq := λ u, units.ext
(show (u : ideal R) = 1, by rw [is_unit_iff.mp u.is_unit, one_eq_top]) }
end dvd
end mul_and_radical
section map_and_comap
variables {R : Type u} {S : Type v}
section semiring
variables [semiring R] [semiring S]
variables (f : R →+* S)
variables {I J : ideal R} {K L : ideal S}
/-- `I.map f` is the span of the image of the ideal `I` under `f`, which may be bigger than
the image itself. -/
def map (I : ideal R) : ideal S :=
span (f '' I)
/-- `I.comap f` is the preimage of `I` under `f`. -/
def comap (I : ideal S) : ideal R :=
{ carrier := f ⁻¹' I,
.. I.comap f.to_semilinear_map }
variables {f}
theorem map_mono (h : I ≤ J) : map f I ≤ map f J :=
span_mono $ set.image_subset _ h
theorem mem_map_of_mem (f : R →+* S) {I : ideal R} {x : R} (h : x ∈ I) : f x ∈ map f I :=
subset_span ⟨x, h, rfl⟩
lemma apply_coe_mem_map (f : R →+* S) (I : ideal R) (x : I) : f x ∈ I.map f :=
mem_map_of_mem f x.prop
theorem map_le_iff_le_comap :
map f I ≤ K ↔ I ≤ comap f K :=
span_le.trans set.image_subset_iff
@[simp] theorem mem_comap {x} : x ∈ comap f K ↔ f x ∈ K := iff.rfl
theorem comap_mono (h : K ≤ L) : comap f K ≤ comap f L :=
set.preimage_mono (λ x hx, h hx)
variables (f)
theorem comap_ne_top (hK : K ≠ ⊤) : comap f K ≠ ⊤ :=
(ne_top_iff_one _).2 $ by rw [mem_comap, f.map_one];
exact (ne_top_iff_one _).1 hK
lemma map_le_comap_of_inv_on (g : S →+* R) (I : ideal R) (hf : set.left_inv_on g f I) :
I.map f ≤ I.comap g :=
begin
refine ideal.span_le.2 _,
rintros x ⟨x, hx, rfl⟩,
rw [set_like.mem_coe, mem_comap, hf hx],
exact hx,
end
lemma comap_le_map_of_inv_on (g : S →+* R) (I : ideal S) (hf : set.left_inv_on g f (f ⁻¹' I)) :
I.comap f ≤ I.map g :=
λ x (hx : f x ∈ I), hf hx ▸ ideal.mem_map_of_mem g hx
/-- The `ideal` version of `set.image_subset_preimage_of_inverse`. -/
lemma map_le_comap_of_inverse (g : S →+* R) (I : ideal R) (h : function.left_inverse g f) :
I.map f ≤ I.comap g :=
map_le_comap_of_inv_on _ _ _ $ h.left_inv_on _
/-- The `ideal` version of `set.preimage_subset_image_of_inverse`. -/
lemma comap_le_map_of_inverse (g : S →+* R) (I : ideal S) (h : function.left_inverse g f) :
I.comap f ≤ I.map g :=
comap_le_map_of_inv_on _ _ _ $ h.left_inv_on _
instance is_prime.comap [hK : K.is_prime] : (comap f K).is_prime :=
⟨comap_ne_top _ hK.1, λ x y,
by simp only [mem_comap, f.map_mul]; apply hK.2⟩
variables (I J K L)
theorem map_top : map f ⊤ = ⊤ :=
(eq_top_iff_one _).2 $ subset_span ⟨1, trivial, f.map_one⟩
variable (f)
lemma gc_map_comap : galois_connection (ideal.map f) (ideal.comap f) :=
λ I J, ideal.map_le_iff_le_comap
@[simp] lemma comap_id : I.comap (ring_hom.id R) = I :=
ideal.ext $ λ _, iff.rfl
@[simp] lemma map_id : I.map (ring_hom.id R) = I :=
(gc_map_comap (ring_hom.id R)).l_unique galois_connection.id comap_id
lemma comap_comap {T : Type*} [semiring T] {I : ideal T} (f : R →+* S)
(g : S →+* T) : (I.comap g).comap f = I.comap (g.comp f) := rfl
lemma map_map {T : Type*} [semiring T] {I : ideal R} (f : R →+* S)
(g : S →+* T) : (I.map f).map g = I.map (g.comp f) :=
((gc_map_comap f).compose (gc_map_comap g)).l_unique
(gc_map_comap (g.comp f)) (λ _, comap_comap _ _)
lemma map_span (f : R →+* S) (s : set R) :
map f (span s) = span (f '' s) :=
symm $ submodule.span_eq_of_le _
(λ y ⟨x, hy, x_eq⟩, x_eq ▸ mem_map_of_mem f (subset_span hy))
(map_le_iff_le_comap.2 $ span_le.2 $ set.image_subset_iff.1 subset_span)
variables {f I J K L}
lemma map_le_of_le_comap : I ≤ K.comap f → I.map f ≤ K :=
(gc_map_comap f).l_le
lemma le_comap_of_map_le : I.map f ≤ K → I ≤ K.comap f :=
(gc_map_comap f).le_u
lemma le_comap_map : I ≤ (I.map f).comap f :=
(gc_map_comap f).le_u_l _
lemma map_comap_le : (K.comap f).map f ≤ K :=
(gc_map_comap f).l_u_le _
@[simp] lemma comap_top : (⊤ : ideal S).comap f = ⊤ :=
(gc_map_comap f).u_top
@[simp] lemma comap_eq_top_iff {I : ideal S} : I.comap f = ⊤ ↔ I = ⊤ :=
⟨ λ h, I.eq_top_iff_one.mpr (f.map_one ▸ mem_comap.mp ((I.comap f).eq_top_iff_one.mp h)),
λ h, by rw [h, comap_top] ⟩
@[simp] lemma map_bot : (⊥ : ideal R).map f = ⊥ :=
(gc_map_comap f).l_bot
variables (f I J K L)
@[simp] lemma map_comap_map : ((I.map f).comap f).map f = I.map f :=
(gc_map_comap f).l_u_l_eq_l I
@[simp] lemma comap_map_comap : ((K.comap f).map f).comap f = K.comap f :=
(gc_map_comap f).u_l_u_eq_u K
lemma map_sup : (I ⊔ J).map f = I.map f ⊔ J.map f :=
(gc_map_comap f).l_sup
theorem comap_inf : comap f (K ⊓ L) = comap f K ⊓ comap f L := rfl
variables {ι : Sort*}
lemma map_supr (K : ι → ideal R) : (supr K).map f = ⨆ i, (K i).map f :=
(gc_map_comap f).l_supr
lemma comap_infi (K : ι → ideal S) : (infi K).comap f = ⨅ i, (K i).comap f :=
(gc_map_comap f).u_infi
lemma map_Sup (s : set (ideal R)): (Sup s).map f = ⨆ I ∈ s, (I : ideal R).map f :=
(gc_map_comap f).l_Sup
lemma comap_Inf (s : set (ideal S)): (Inf s).comap f = ⨅ I ∈ s, (I : ideal S).comap f :=
(gc_map_comap f).u_Inf
lemma comap_Inf' (s : set (ideal S)) : (Inf s).comap f = ⨅ I ∈ (comap f '' s), I :=
trans (comap_Inf f s) (by rw infi_image)
theorem comap_is_prime [H : is_prime K] : is_prime (comap f K) :=
⟨comap_ne_top f H.ne_top,
λ x y h, H.mem_or_mem $ by rwa [mem_comap, ring_hom.map_mul] at h⟩
variables {I J K L}
theorem map_inf_le : map f (I ⊓ J) ≤ map f I ⊓ map f J :=
(gc_map_comap f).monotone_l.map_inf_le _ _
theorem le_comap_sup : comap f K ⊔ comap f L ≤ comap f (K ⊔ L) :=
(gc_map_comap f).monotone_u.le_map_sup _ _
@[simp] lemma smul_top_eq_map {R S : Type*} [comm_semiring R] [comm_semiring S] [algebra R S]
(I : ideal R) : I • (⊤ : submodule R S) = (I.map (algebra_map R S)).restrict_scalars R :=
begin
refine le_antisymm (submodule.smul_le.mpr (λ r hr y _, _) )
(λ x hx, submodule.span_induction hx _ _ _ _),
{ rw algebra.smul_def,
exact mul_mem_right _ _ (mem_map_of_mem _ hr) },
{ rintros _ ⟨x, hx, rfl⟩,
rw [← mul_one (algebra_map R S x), ← algebra.smul_def],
exact submodule.smul_mem_smul hx submodule.mem_top },
{ exact submodule.zero_mem _ },
{ intros x y, exact submodule.add_mem _ },
intros a x hx,
refine submodule.smul_induction_on hx _ _,
{ intros r hr s hs,
rw smul_comm,
exact submodule.smul_mem_smul hr submodule.mem_top },
{ intros x y hx hy,
rw smul_add, exact submodule.add_mem _ hx hy },
end
section surjective
variables (hf : function.surjective f)
include hf
open function
theorem map_comap_of_surjective (I : ideal S) :
map f (comap f I) = I :=
le_antisymm (map_le_iff_le_comap.2 le_rfl)
(λ s hsi, let ⟨r, hfrs⟩ := hf s in
hfrs ▸ (mem_map_of_mem f $ show f r ∈ I, from hfrs.symm ▸ hsi))
/-- `map` and `comap` are adjoint, and the composition `map f ∘ comap f` is the
identity -/
def gi_map_comap : galois_insertion (map f) (comap f) :=
galois_insertion.monotone_intro
((gc_map_comap f).monotone_u)
((gc_map_comap f).monotone_l)
(λ _, le_comap_map)
(map_comap_of_surjective _ hf)
lemma map_surjective_of_surjective : surjective (map f) :=
(gi_map_comap f hf).l_surjective
lemma comap_injective_of_surjective : injective (comap f) :=
(gi_map_comap f hf).u_injective
lemma map_sup_comap_of_surjective (I J : ideal S) : (I.comap f ⊔ J.comap f).map f = I ⊔ J :=
(gi_map_comap f hf).l_sup_u _ _
lemma map_supr_comap_of_surjective (K : ι → ideal S) : (⨆i, (K i).comap f).map f = supr K :=
(gi_map_comap f hf).l_supr_u _
lemma map_inf_comap_of_surjective (I J : ideal S) : (I.comap f ⊓ J.comap f).map f = I ⊓ J :=
(gi_map_comap f hf).l_inf_u _ _
lemma map_infi_comap_of_surjective (K : ι → ideal S) : (⨅i, (K i).comap f).map f = infi K :=
(gi_map_comap f hf).l_infi_u _
theorem mem_image_of_mem_map_of_surjective {I : ideal R} {y}
(H : y ∈ map f I) : y ∈ f '' I :=
submodule.span_induction H (λ _, id) ⟨0, I.zero_mem, f.map_zero⟩
(λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩,
⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ f.map_add _ _⟩)
(λ c y ⟨x, hxi, hxy⟩,
let ⟨d, hdc⟩ := hf c in ⟨d * x, I.mul_mem_left _ hxi, hdc ▸ hxy ▸ f.map_mul _ _⟩)
lemma mem_map_iff_of_surjective {I : ideal R} {y} :
y ∈ map f I ↔ ∃ x, x ∈ I ∧ f x = y :=
⟨λ h, (set.mem_image _ _ _).2 (mem_image_of_mem_map_of_surjective f hf h),
λ ⟨x, hx⟩, hx.right ▸ (mem_map_of_mem f hx.left)⟩
lemma le_map_of_comap_le_of_surjective : comap f K ≤ I → K ≤ map f I :=
λ h, (map_comap_of_surjective f hf K) ▸ map_mono h
end surjective
section injective
variables (hf : function.injective f)
include hf
lemma comap_bot_le_of_injective : comap f ⊥ ≤ I :=
begin
refine le_trans (λ x hx, _) bot_le,
rw [mem_comap, submodule.mem_bot, ← ring_hom.map_zero f] at hx,
exact eq.symm (hf hx) ▸ (submodule.zero_mem ⊥)
end
end injective
end semiring
section ring
variables [ring R] [ring S] (f : R →+* S) {I : ideal R}
section surjective
variables (hf : function.surjective f)
include hf
theorem comap_map_of_surjective (I : ideal R) : comap f (map f I) = I ⊔ comap f ⊥ :=
le_antisymm (assume r h, let ⟨s, hsi, hfsr⟩ := mem_image_of_mem_map_of_surjective f hf h in
submodule.mem_sup.2 ⟨s, hsi, r - s, (submodule.mem_bot S).2 $ by rw [f.map_sub, hfsr, sub_self],
add_sub_cancel'_right s r⟩)
(sup_le (map_le_iff_le_comap.1 le_rfl) (comap_mono bot_le))
/-- Correspondence theorem -/
def rel_iso_of_surjective : ideal S ≃o { p : ideal R // comap f ⊥ ≤ p } :=
{ to_fun := λ J, ⟨comap f J, comap_mono bot_le⟩,
inv_fun := λ I, map f I.1,
left_inv := λ J, map_comap_of_surjective f hf J,
right_inv := λ I, subtype.eq $ show comap f (map f I.1) = I.1,
from (comap_map_of_surjective f hf I).symm ▸ le_antisymm
(sup_le le_rfl I.2) le_sup_left,
map_rel_iff' := λ I1 I2, ⟨λ H, map_comap_of_surjective f hf I1 ▸
map_comap_of_surjective f hf I2 ▸ map_mono H, comap_mono⟩ }
/-- The map on ideals induced by a surjective map preserves inclusion. -/
def order_embedding_of_surjective : ideal S ↪o ideal R :=
(rel_iso_of_surjective f hf).to_rel_embedding.trans (subtype.rel_embedding _ _)
theorem map_eq_top_or_is_maximal_of_surjective {I : ideal R} (H : is_maximal I) :
(map f I) = ⊤ ∨ is_maximal (map f I) :=
begin
refine or_iff_not_imp_left.2 (λ ne_top, ⟨⟨λ h, ne_top h, λ J hJ, _⟩⟩),
{ refine (rel_iso_of_surjective f hf).injective
(subtype.ext_iff.2 (eq.trans (H.1.2 (comap f J) (lt_of_le_of_ne _ _)) comap_top.symm)),
{ exact (map_le_iff_le_comap).1 (le_of_lt hJ) },
{ exact λ h, hJ.right (le_map_of_comap_le_of_surjective f hf (le_of_eq h.symm)) } }
end
theorem comap_is_maximal_of_surjective {K : ideal S} [H : is_maximal K] : is_maximal (comap f K) :=
begin
refine ⟨⟨comap_ne_top _ H.1.1, λ J hJ, _⟩⟩,
suffices : map f J = ⊤,
{ replace this := congr_arg (comap f) this,
rw [comap_top, comap_map_of_surjective _ hf, eq_top_iff] at this,
rw eq_top_iff,
exact le_trans this (sup_le (le_of_eq rfl) (le_trans (comap_mono (bot_le)) (le_of_lt hJ))) },
refine H.1.2 (map f J) (lt_of_le_of_ne (le_map_of_comap_le_of_surjective _ hf (le_of_lt hJ))
(λ h, ne_of_lt hJ (trans (congr_arg (comap f) h) _))),
rw [comap_map_of_surjective _ hf, sup_eq_left],
exact le_trans (comap_mono bot_le) (le_of_lt hJ)
end
theorem comap_le_comap_iff_of_surjective (I J : ideal S) : comap f I ≤ comap f J ↔ I ≤ J :=
⟨λ h, (map_comap_of_surjective f hf I).symm.le.trans (map_le_of_le_comap h),
λ h, le_comap_of_map_le ((map_comap_of_surjective f hf I).le.trans h)⟩
end surjective
/-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f (map f.symm) = I`. -/
@[simp]
lemma map_of_equiv (I : ideal R) (f : R ≃+* S) : (I.map (f : R →+* S)).map (f.symm : S →+* R) = I :=
by simp [← ring_equiv.to_ring_hom_eq_coe, map_map]
/-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `comap f.symm (comap f) = I`. -/
@[simp]
lemma comap_of_equiv (I : ideal R) (f : R ≃+* S) :
(I.comap (f.symm : S →+* R)).comap (f : R →+* S) = I :=
by simp [← ring_equiv.to_ring_hom_eq_coe, comap_comap]
/-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f I = comap f.symm I`. -/
lemma map_comap_of_equiv (I : ideal R) (f : R ≃+* S) : I.map (f : R →+* S) = I.comap f.symm :=
le_antisymm (le_comap_of_map_le (map_of_equiv I f).le)
(le_map_of_comap_le_of_surjective _ f.surjective (comap_of_equiv I f).le)
section bijective
variables (hf : function.bijective f)
include hf
/-- Special case of the correspondence theorem for isomorphic rings -/
def rel_iso_of_bijective : ideal S ≃o ideal R :=
{ to_fun := comap f,
inv_fun := map f,
left_inv := (rel_iso_of_surjective f hf.right).left_inv,
right_inv := λ J, subtype.ext_iff.1
((rel_iso_of_surjective f hf.right).right_inv ⟨J, comap_bot_le_of_injective f hf.left⟩),
map_rel_iff' := (rel_iso_of_surjective f hf.right).map_rel_iff' }
lemma comap_le_iff_le_map {I : ideal R} {K : ideal S} : comap f K ≤ I ↔ K ≤ map f I :=
⟨λ h, le_map_of_comap_le_of_surjective f hf.right h,
λ h, ((rel_iso_of_bijective f hf).right_inv I) ▸ comap_mono h⟩
theorem map.is_maximal {I : ideal R} (H : is_maximal I) : is_maximal (map f I) :=
by refine or_iff_not_imp_left.1
(map_eq_top_or_is_maximal_of_surjective f hf.right H) (λ h, H.1.1 _);
calc I = comap f (map f I) : ((rel_iso_of_bijective f hf).right_inv I).symm
... = comap f ⊤ : by rw h
... = ⊤ : by rw comap_top
end bijective
lemma ring_equiv.bot_maximal_iff (e : R ≃+* S) :
(⊥ : ideal R).is_maximal ↔ (⊥ : ideal S).is_maximal :=
⟨λ h, (@map_bot _ _ _ _ e.to_ring_hom) ▸ map.is_maximal e.to_ring_hom e.bijective h,
λ h, (@map_bot _ _ _ _ e.symm.to_ring_hom) ▸ map.is_maximal e.symm.to_ring_hom e.symm.bijective h⟩
end ring
section comm_ring
variables [comm_ring R] [comm_ring S]
variables (f : R →+* S)
variables {I J : ideal R} {K L : ideal S}
variables (I J K L)
theorem map_mul : map f (I * J) = map f I * map f J :=
le_antisymm (map_le_iff_le_comap.2 $ mul_le.2 $ λ r hri s hsj,
show f (r * s) ∈ _, by rw f.map_mul;
exact mul_mem_mul (mem_map_of_mem f hri) (mem_map_of_mem f hsj))
(trans_rel_right _ (span_mul_span _ _) $ span_le.2 $
set.Union₂_subset $ λ i ⟨r, hri, hfri⟩,
set.Union₂_subset $ λ j ⟨s, hsj, hfsj⟩,
set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸
by rw [← f.map_mul];
exact mem_map_of_mem f (mul_mem_mul hri hsj))
/-- The pushforward `ideal.map` as a monoid-with-zero homomorphism. -/
@[simps]
def map_hom : ideal R →*₀ ideal S :=
{ to_fun := map f,
map_mul' := λ I J, ideal.map_mul f I J,
map_one' := by convert ideal.map_top f; exact one_eq_top,
map_zero' := ideal.map_bot }
protected theorem map_pow (n : ℕ) : map f (I^n) = (map f I)^n :=
map_pow (map_hom f) I n
theorem comap_radical : comap f (radical K) = radical (comap f K) :=
le_antisymm (λ r ⟨n, hfrnk⟩, ⟨n, show f (r ^ n) ∈ K,
from (f.map_pow r n).symm ▸ hfrnk⟩)
(λ r ⟨n, hfrnk⟩, ⟨n, f.map_pow r n ▸ hfrnk⟩)
@[simp] lemma map_quotient_self :
map (quotient.mk I) I = ⊥ :=
eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ λ x hx,
(submodule.mem_bot (R ⧸ I)).2 $ ideal.quotient.eq_zero_iff_mem.2 hx
variables {I J K L}
theorem map_radical_le : map f (radical I) ≤ radical (map f I) :=
map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, f.map_pow r n ▸ mem_map_of_mem f hrni⟩
theorem le_comap_mul : comap f K * comap f L ≤ comap f (K * L) :=
map_le_iff_le_comap.1 $ (map_mul f (comap f K) (comap f L)).symm ▸
mul_mono (map_le_iff_le_comap.2 $ le_rfl) (map_le_iff_le_comap.2 $ le_rfl)
end comm_ring
end map_and_comap
section is_primary
variables {R : Type u} [comm_semiring R]
/-- A proper ideal `I` is primary iff `xy ∈ I` implies `x ∈ I` or `y ∈ radical I`. -/
def is_primary (I : ideal R) : Prop :=
I ≠ ⊤ ∧ ∀ {x y : R}, x * y ∈ I → x ∈ I ∨ y ∈ radical I
theorem is_prime.is_primary {I : ideal R} (hi : is_prime I) : is_primary I :=
⟨hi.1, λ x y hxy, (hi.mem_or_mem hxy).imp id $ λ hyi, le_radical hyi⟩
theorem mem_radical_of_pow_mem {I : ideal R} {x : R} {m : ℕ} (hx : x ^ m ∈ radical I) :
x ∈ radical I :=
radical_idem I ▸ ⟨m, hx⟩
theorem is_prime_radical {I : ideal R} (hi : is_primary I) : is_prime (radical I) :=
⟨mt radical_eq_top.1 hi.1, λ x y ⟨m, hxy⟩, begin
rw mul_pow at hxy, cases hi.2 hxy,
{ exact or.inl ⟨m, h⟩ },
{ exact or.inr (mem_radical_of_pow_mem h) }
end⟩
theorem is_primary_inf {I J : ideal R} (hi : is_primary I) (hj : is_primary J)
(hij : radical I = radical J) : is_primary (I ⊓ J) :=
⟨ne_of_lt $ lt_of_le_of_lt inf_le_left (lt_top_iff_ne_top.2 hi.1), λ x y ⟨hxyi, hxyj⟩,
begin
rw [radical_inf, hij, inf_idem],
cases hi.2 hxyi with hxi hyi, cases hj.2 hxyj with hxj hyj,
{ exact or.inl ⟨hxi, hxj⟩ },
{ exact or.inr hyj },
{ rw hij at hyi, exact or.inr hyi }
end⟩
end is_primary
end ideal
lemma associates.mk_ne_zero' {R : Type*} [comm_ring R] {r : R} :
(associates.mk (ideal.span {r} : ideal R)) ≠ 0 ↔ (r ≠ 0):=
by rw [associates.mk_ne_zero, ideal.zero_eq_bot, ne.def, ideal.span_singleton_eq_bot]
namespace ring_hom
variables {R : Type u} {S : Type v} {T : Type v}
section semiring
variables [semiring R] [semiring S] [semiring T] (f : R →+* S) (g : T →+* S)
/-- Kernel of a ring homomorphism as an ideal of the domain. -/
def ker : ideal R := ideal.comap f ⊥
/-- An element is in the kernel if and only if it maps to zero.-/
lemma mem_ker {r} : r ∈ ker f ↔ f r = 0 :=
by rw [ker, ideal.mem_comap, submodule.mem_bot]
lemma ker_eq : ((ker f) : set R) = set.preimage f {0} := rfl
lemma ker_eq_comap_bot (f : R →+* S) : f.ker = ideal.comap f ⊥ := rfl
lemma comap_ker (f : S →+* R) : f.ker.comap g = (f.comp g).ker :=
by rw [ring_hom.ker_eq_comap_bot, ideal.comap_comap, ring_hom.ker_eq_comap_bot]
/-- If the target is not the zero ring, then one is not in the kernel.-/
lemma not_one_mem_ker [nontrivial S] (f : R →+* S) : (1:R) ∉ ker f :=
by { rw [mem_ker, f.map_one], exact one_ne_zero }
lemma ker_ne_top [nontrivial S] (f : R →+* S) : f.ker ≠ ⊤ :=
(ideal.ne_top_iff_one _).mpr $ not_one_mem_ker f
end semiring
section ring
variables [ring R] [semiring S] (f : R →+* S)
lemma injective_iff_ker_eq_bot : function.injective f ↔ ker f = ⊥ :=
by { rw [set_like.ext'_iff, ker_eq, set.ext_iff], exact injective_iff_map_eq_zero' f }
lemma ker_eq_bot_iff_eq_zero : ker f = ⊥ ↔ ∀ x, f x = 0 → x = 0 :=
by { rw [← injective_iff_map_eq_zero f, injective_iff_ker_eq_bot] }
@[simp] lemma ker_coe_equiv (f : R ≃+* S) : ker (f : R →+* S) = ⊥ :=
by simpa only [←injective_iff_ker_eq_bot] using f.injective
end ring
section comm_ring
variables [comm_ring R] [comm_ring S] (f : R →+* S)
/-- The induced map from the quotient by the kernel to the codomain.
This is an isomorphism if `f` has a right inverse (`quotient_ker_equiv_of_right_inverse`) /
is surjective (`quotient_ker_equiv_of_surjective`).
-/
def ker_lift (f : R →+* S) : R ⧸ f.ker →+* S :=
ideal.quotient.lift _ f $ λ r, f.mem_ker.mp
@[simp]
lemma ker_lift_mk (f : R →+* S) (r : R) : ker_lift f (ideal.quotient.mk f.ker r) = f r :=
ideal.quotient.lift_mk _ _ _
/-- The induced map from the quotient by the kernel is injective. -/
lemma ker_lift_injective (f : R →+* S) : function.injective (ker_lift f) :=
assume a b, quotient.induction_on₂' a b $
assume a b (h : f a = f b), ideal.quotient.eq.2 $
show a - b ∈ ker f, by rw [mem_ker, map_sub, h, sub_self]
variable {f}
/-- The **first isomorphism theorem** for commutative rings, computable version. -/
def quotient_ker_equiv_of_right_inverse
{g : S → R} (hf : function.right_inverse g f) :
R ⧸ f.ker ≃+* S :=
{ to_fun := ker_lift f,
inv_fun := (ideal.quotient.mk f.ker) ∘ g,
left_inv := begin
rintro ⟨x⟩,
apply ker_lift_injective,
simp [hf (f x)],
end,
right_inv := hf,
..ker_lift f}
@[simp]
lemma quotient_ker_equiv_of_right_inverse.apply {g : S → R} (hf : function.right_inverse g f)
(x : R ⧸ f.ker) : quotient_ker_equiv_of_right_inverse hf x = ker_lift f x := rfl
@[simp]
lemma quotient_ker_equiv_of_right_inverse.symm.apply {g : S → R} (hf : function.right_inverse g f)
(x : S) : (quotient_ker_equiv_of_right_inverse hf).symm x = ideal.quotient.mk f.ker (g x) := rfl
/-- The **first isomorphism theorem** for commutative rings. -/
noncomputable def quotient_ker_equiv_of_surjective (hf : function.surjective f) :
R ⧸ f.ker ≃+* S :=
quotient_ker_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse)
end comm_ring
/-- The kernel of a homomorphism to a domain is a prime ideal. -/
lemma ker_is_prime [ring R] [ring S] [is_domain S] (f : R →+* S) :
(ker f).is_prime :=
⟨by { rw [ne.def, ideal.eq_top_iff_one], exact not_one_mem_ker f },
λ x y, by simpa only [mem_ker, f.map_mul] using @eq_zero_or_eq_zero_of_mul_eq_zero S _ _ _ _ _⟩
/-- The kernel of a homomorphism to a field is a maximal ideal. -/
lemma ker_is_maximal_of_surjective {R K : Type*} [ring R] [field K]
(f : R →+* K) (hf : function.surjective f) :
f.ker.is_maximal :=
begin
refine ideal.is_maximal_iff.mpr
⟨λ h1, @one_ne_zero K _ _ $ f.map_one ▸ f.mem_ker.mp h1,
λ J x hJ hxf hxJ, _⟩,
obtain ⟨y, hy⟩ := hf (f x)⁻¹,
have H : 1 = y * x - (y * x - 1) := (sub_sub_cancel _ _).symm,
rw H,
refine J.sub_mem (J.mul_mem_left _ hxJ) (hJ _),
rw f.mem_ker,
simp only [hy, ring_hom.map_sub, ring_hom.map_one, ring_hom.map_mul,
inv_mul_cancel (mt f.mem_ker.mpr hxf), sub_self],
end
end ring_hom
namespace ideal
variables {R : Type*} {S : Type*}
section semiring
variables [semiring R] [semiring S]
lemma map_eq_bot_iff_le_ker {I : ideal R} (f : R →+* S) : I.map f = ⊥ ↔ I ≤ f.ker :=
by rw [ring_hom.ker, eq_bot_iff, map_le_iff_le_comap]
lemma ker_le_comap {K : ideal S} (f : R →+* S) : f.ker ≤ comap f K :=
λ x hx, mem_comap.2 (((ring_hom.mem_ker f).1 hx).symm ▸ K.zero_mem)
end semiring
section ring
variables [ring R] [ring S]
lemma map_Inf {A : set (ideal R)} {f : R →+* S} (hf : function.surjective f) :
(∀ J ∈ A, ring_hom.ker f ≤ J) → map f (Inf A) = Inf (map f '' A) :=
begin
refine λ h, le_antisymm (le_Inf _) _,
{ intros j hj y hy,
cases (mem_map_iff_of_surjective f hf).1 hy with x hx,
cases (set.mem_image _ _ _).mp hj with J hJ,
rw [← hJ.right, ← hx.right],
exact mem_map_of_mem f (Inf_le_of_le hJ.left (le_of_eq rfl) hx.left) },
{ intros y hy,
cases hf y with x hx,
refine hx ▸ (mem_map_of_mem f _),
have : ∀ I ∈ A, y ∈ map f I, by simpa using hy,
rw [submodule.mem_Inf],
intros J hJ,
rcases (mem_map_iff_of_surjective f hf).1 (this J hJ) with ⟨x', hx', rfl⟩,
have : x - x' ∈ J,
{ apply h J hJ,
rw [ring_hom.mem_ker, ring_hom.map_sub, hx, sub_self] },
simpa only [sub_add_cancel] using J.add_mem this hx' }
end
theorem map_is_prime_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R}
[H : is_prime I] (hk : ring_hom.ker f ≤ I) : is_prime (map f I) :=
begin
refine ⟨λ h, H.ne_top (eq_top_iff.2 _), λ x y, _⟩,
{ replace h := congr_arg (comap f) h,
rw [comap_map_of_surjective _ hf, comap_top] at h,
exact h ▸ sup_le (le_of_eq rfl) hk },
{ refine λ hxy, (hf x).rec_on (λ a ha, (hf y).rec_on (λ b hb, _)),
rw [← ha, ← hb, ← ring_hom.map_mul, mem_map_iff_of_surjective _ hf] at hxy,
rcases hxy with ⟨c, hc, hc'⟩,
rw [← sub_eq_zero, ← ring_hom.map_sub] at hc',
have : a * b ∈ I,
{ convert I.sub_mem hc (hk (hc' : c - a * b ∈ f.ker)),
abel },
exact (H.mem_or_mem this).imp (λ h, ha ▸ mem_map_of_mem f h) (λ h, hb ▸ mem_map_of_mem f h) }
end
theorem map_is_prime_of_equiv (f : R ≃+* S) {I : ideal R} [is_prime I] :
is_prime (map (f : R →+* S) I) :=
map_is_prime_of_surjective f.surjective $ by simp
end ring
section comm_ring
variables [comm_ring R] [comm_ring S]
@[simp] lemma mk_ker {I : ideal R} : (quotient.mk I).ker = I :=
by ext; rw [ring_hom.ker, mem_comap, submodule.mem_bot, quotient.eq_zero_iff_mem]
lemma map_mk_eq_bot_of_le {I J : ideal R} (h : I ≤ J) : I.map (J^.quotient.mk) = ⊥ :=
by { rw [map_eq_bot_iff_le_ker, mk_ker], exact h }
lemma ker_quotient_lift {S : Type v} [comm_ring S] {I : ideal R} (f : R →+* S) (H : I ≤ f.ker) :
(ideal.quotient.lift I f H).ker = (f.ker).map I^.quotient.mk :=
begin
ext x,
split,
{ intro hx,
obtain ⟨y, hy⟩ := quotient.mk_surjective x,
rw [ring_hom.mem_ker, ← hy, ideal.quotient.lift_mk, ← ring_hom.mem_ker] at hx,
rw [← hy, mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective],
exact ⟨y, hx, rfl⟩ },
{ intro hx,
rw mem_map_iff_of_surjective I^.quotient.mk quotient.mk_surjective at hx,
obtain ⟨y, hy⟩ := hx,
rw [ring_hom.mem_ker, ← hy.right, ideal.quotient.lift_mk, ← (ring_hom.mem_ker f)],
exact hy.left },
end
theorem map_eq_iff_sup_ker_eq_of_surjective {I J : ideal R} (f : R →+* S)
(hf : function.surjective f) : map f I = map f J ↔ I ⊔ f.ker = J ⊔ f.ker :=
by rw [← (comap_injective_of_surjective f hf).eq_iff, comap_map_of_surjective f hf,
comap_map_of_surjective f hf, ring_hom.ker_eq_comap_bot]
theorem map_radical_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R}
(h : ring_hom.ker f ≤ I) : map f (I.radical) = (map f I).radical :=
begin
rw [radical_eq_Inf, radical_eq_Inf],
have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_prime}, f.ker ≤ J := λ J hJ, le_trans h hJ.left,
convert map_Inf hf this,
refine funext (λ j, propext ⟨_, _⟩),
{ rintros ⟨hj, hj'⟩,
haveI : j.is_prime := hj',
exact ⟨comap f j, ⟨⟨map_le_iff_le_comap.1 hj, comap_is_prime f j⟩,
map_comap_of_surjective f hf j⟩⟩ },
{ rintro ⟨J, ⟨hJ, hJ'⟩⟩,
haveI : J.is_prime := hJ.right,
refine ⟨hJ' ▸ map_mono hJ.left, hJ' ▸ map_is_prime_of_surjective hf (le_trans h hJ.left)⟩ },
end
@[simp] lemma bot_quotient_is_maximal_iff (I : ideal R) :
(⊥ : ideal (R ⧸ I)).is_maximal ↔ I.is_maximal :=
⟨λ hI, (@mk_ker _ _ I) ▸
@comap_is_maximal_of_surjective _ _ _ _ (quotient.mk I) quotient.mk_surjective ⊥ hI,
λ hI, @bot_is_maximal _ (@field.to_division_ring _ (@quotient.field _ _ I hI)) ⟩
/-- See also `ideal.mem_quotient_iff_mem` in case `I ≤ J`. -/
@[simp]
lemma mem_quotient_iff_mem_sup {I J : ideal R} {x : R} :
quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J ⊔ I :=
by rw [← mem_comap, comap_map_of_surjective _ quotient.mk_surjective, ← ring_hom.ker_eq_comap_bot,
mk_ker]
/-- See also `ideal.mem_quotient_iff_mem_sup` if the assumption `I ≤ J` is not available. -/
lemma mem_quotient_iff_mem {I J : ideal R} (hIJ : I ≤ J) {x : R} :
quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J :=
by rw [mem_quotient_iff_mem_sup, sup_eq_left.mpr hIJ]
section quotient_algebra
variables (R₁ R₂ : Type*) {A B : Type*}
variables [comm_semiring R₁] [comm_semiring R₂] [comm_ring A] [comm_ring B]
variables [algebra R₁ A] [algebra R₂ A] [algebra R₁ B]
/-- The `R₁`-algebra structure on `A/I` for an `R₁`-algebra `A` -/
instance quotient.algebra {I : ideal A} : algebra R₁ (A ⧸ I) :=
{ to_fun := λ x, ideal.quotient.mk I (algebra_map R₁ A x),
smul := (•),
smul_def' := λ r x, quotient.induction_on' x $ λ x,
((quotient.mk I).congr_arg $ algebra.smul_def _ _).trans (ring_hom.map_mul _ _ _),
commutes' := λ _ _, mul_comm _ _,
.. ring_hom.comp (ideal.quotient.mk I) (algebra_map R₁ A) }
-- Lean can struggle to find this instance later if we don't provide this shortcut
instance quotient.is_scalar_tower [has_scalar R₁ R₂] [is_scalar_tower R₁ R₂ A] (I : ideal A) :
is_scalar_tower R₁ R₂ (A ⧸ I) :=
by apply_instance
/-- The canonical morphism `A →ₐ[R₁] A ⧸ I` as morphism of `R₁`-algebras, for `I` an ideal of
`A`, where `A` is an `R₁`-algebra. -/
def quotient.mkₐ (I : ideal A) : A →ₐ[R₁] A ⧸ I :=
⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl, λ _, rfl⟩
lemma quotient.alg_map_eq (I : ideal A) :
algebra_map R₁ (A ⧸ I) = (algebra_map A (A ⧸ I)).comp (algebra_map R₁ A) :=
rfl
lemma quotient.mkₐ_to_ring_hom (I : ideal A) :
(quotient.mkₐ R₁ I).to_ring_hom = ideal.quotient.mk I := rfl
@[simp] lemma quotient.mkₐ_eq_mk (I : ideal A) :
⇑(quotient.mkₐ R₁ I) = ideal.quotient.mk I := rfl
@[simp] lemma quotient.algebra_map_eq (I : ideal R) :
algebra_map R (R ⧸ I) = I^.quotient.mk :=
rfl
@[simp] lemma quotient.mk_comp_algebra_map (I : ideal A) :
(quotient.mk I).comp (algebra_map R₁ A) = algebra_map R₁ (A ⧸ I) :=
rfl
@[simp] lemma quotient.mk_algebra_map (I : ideal A) (x : R₁) :
quotient.mk I (algebra_map R₁ A x) = algebra_map R₁ (A ⧸ I) x :=
rfl
/-- The canonical morphism `A →ₐ[R₁] I.quotient` is surjective. -/
lemma quotient.mkₐ_surjective (I : ideal A) : function.surjective (quotient.mkₐ R₁ I) :=
surjective_quot_mk _
/-- The kernel of `A →ₐ[R₁] I.quotient` is `I`. -/
@[simp]
lemma quotient.mkₐ_ker (I : ideal A) : (quotient.mkₐ R₁ I : A →+* A ⧸ I).ker = I :=
ideal.mk_ker
variables {R₁}
lemma ker_lift.map_smul (f : A →ₐ[R₁] B) (r : R₁) (x : A ⧸ f.to_ring_hom.ker) :
f.to_ring_hom.ker_lift (r • x) = r • f.to_ring_hom.ker_lift x :=
begin
obtain ⟨a, rfl⟩ := quotient.mkₐ_surjective R₁ _ x,
rw [← alg_hom.map_smul, quotient.mkₐ_eq_mk, ring_hom.ker_lift_mk],
exact f.map_smul _ _
end
/-- The induced algebras morphism from the quotient by the kernel to the codomain.
This is an isomorphism if `f` has a right inverse (`quotient_ker_alg_equiv_of_right_inverse`) /
is surjective (`quotient_ker_alg_equiv_of_surjective`).
-/
def ker_lift_alg (f : A →ₐ[R₁] B) : (A ⧸ f.to_ring_hom.ker) →ₐ[R₁] B :=
alg_hom.mk' f.to_ring_hom.ker_lift (λ _ _, ker_lift.map_smul f _ _)
@[simp]
lemma ker_lift_alg_mk (f : A →ₐ[R₁] B) (a : A) :
ker_lift_alg f (quotient.mk f.to_ring_hom.ker a) = f a := rfl
@[simp]
lemma ker_lift_alg_to_ring_hom (f : A →ₐ[R₁] B) :
(ker_lift_alg f).to_ring_hom = ring_hom.ker_lift f := rfl
/-- The induced algebra morphism from the quotient by the kernel is injective. -/
lemma ker_lift_alg_injective (f : A →ₐ[R₁] B) : function.injective (ker_lift_alg f) :=
ring_hom.ker_lift_injective f
/-- The **first isomorphism** theorem for algebras, computable version. -/
def quotient_ker_alg_equiv_of_right_inverse
{f : A →ₐ[R₁] B} {g : B → A} (hf : function.right_inverse g f) :
(A ⧸ f.to_ring_hom.ker) ≃ₐ[R₁] B :=
{ ..ring_hom.quotient_ker_equiv_of_right_inverse (λ x, show f.to_ring_hom (g x) = x, from hf x),
..ker_lift_alg f}
@[simp]
lemma quotient_ker_alg_equiv_of_right_inverse.apply {f : A →ₐ[R₁] B} {g : B → A}
(hf : function.right_inverse g f) (x : A ⧸ f.to_ring_hom.ker) :
quotient_ker_alg_equiv_of_right_inverse hf x = ker_lift_alg f x := rfl
@[simp]
lemma quotient_ker_alg_equiv_of_right_inverse_symm.apply {f : A →ₐ[R₁] B} {g : B → A}
(hf : function.right_inverse g f) (x : B) :
(quotient_ker_alg_equiv_of_right_inverse hf).symm x = quotient.mkₐ R₁ f.to_ring_hom.ker (g x) :=
rfl
/-- The **first isomorphism theorem** for algebras. -/
noncomputable def quotient_ker_alg_equiv_of_surjective
{f : A →ₐ[R₁] B} (hf : function.surjective f) : (A ⧸ f.to_ring_hom.ker) ≃ₐ[R₁] B :=
quotient_ker_alg_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse)
/-- The ring hom `R/I →+* S/J` induced by a ring hom `f : R →+* S` with `I ≤ f⁻¹(J)` -/
def quotient_map {I : ideal R} (J : ideal S) (f : R →+* S) (hIJ : I ≤ J.comap f) :
R ⧸ I →+* S ⧸ J :=
(quotient.lift I ((quotient.mk J).comp f) (λ _ ha,
by simpa [function.comp_app, ring_hom.coe_comp, quotient.eq_zero_iff_mem] using hIJ ha))
@[simp]
lemma quotient_map_mk {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f}
{x : R} : quotient_map I f H (quotient.mk J x) = quotient.mk I (f x) :=
quotient.lift_mk J _ _
@[simp]
lemma quotient_map_algebra_map {J : ideal A} {I : ideal S} {f : A →+* S} {H : J ≤ I.comap f}
{x : R₁} :
quotient_map I f H (algebra_map R₁ (A ⧸ J) x) = quotient.mk I (f (algebra_map _ _ x)) :=
quotient.lift_mk J _ _
lemma quotient_map_comp_mk {J : ideal R} {I : ideal S} {f : R →+* S} (H : J ≤ I.comap f) :
(quotient_map I f H).comp (quotient.mk J) = (quotient.mk I).comp f :=
ring_hom.ext (λ x, by simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient_map_mk])
/-- The ring equiv `R/I ≃+* S/J` induced by a ring equiv `f : R ≃+** S`, where `J = f(I)`. -/
@[simps]
def quotient_equiv (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) :
R ⧸ I ≃+* S ⧸ J :=
{ inv_fun := quotient_map I ↑f.symm (by {rw hIJ, exact le_of_eq (map_comap_of_equiv I f)}),
left_inv := by {rintro ⟨r⟩, simp },
right_inv := by {rintro ⟨s⟩, simp },
..quotient_map J ↑f (by {rw hIJ, exact @le_comap_map _ S _ _ _ _}) }
@[simp]
lemma quotient_equiv_mk (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S))
(x : R) : quotient_equiv I J f hIJ (ideal.quotient.mk I x) = ideal.quotient.mk J (f x) := rfl
@[simp]
lemma quotient_equiv_symm_mk (I : ideal R) (J : ideal S) (f : R ≃+* S)
(hIJ : J = I.map (f : R →+* S)) (x : S) :
(quotient_equiv I J f hIJ).symm (ideal.quotient.mk J x) = ideal.quotient.mk I (f.symm x) := rfl
/-- `H` and `h` are kept as separate hypothesis since H is used in constructing the quotient map. -/
lemma quotient_map_injective' {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f}
(h : I.comap f ≤ J) : function.injective (quotient_map I f H) :=
begin
refine (injective_iff_map_eq_zero (quotient_map I f H)).2 (λ a ha, _),
obtain ⟨r, rfl⟩ := quotient.mk_surjective a,
rw [quotient_map_mk, quotient.eq_zero_iff_mem] at ha,
exact (quotient.eq_zero_iff_mem).mpr (h ha),
end
/-- If we take `J = I.comap f` then `quotient_map` is injective automatically. -/
lemma quotient_map_injective {I : ideal S} {f : R →+* S} :
function.injective (quotient_map I f le_rfl) :=
quotient_map_injective' le_rfl
lemma quotient_map_surjective {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f}
(hf : function.surjective f) : function.surjective (quotient_map I f H) :=
λ x, let ⟨x, hx⟩ := quotient.mk_surjective x in
let ⟨y, hy⟩ := hf x in ⟨(quotient.mk J) y, by simp [hx, hy]⟩
/-- Commutativity of a square is preserved when taking quotients by an ideal. -/
lemma comp_quotient_map_eq_of_comp_eq {R' S' : Type*} [comm_ring R'] [comm_ring S']
{f : R →+* S} {f' : R' →+* S'} {g : R →+* R'} {g' : S →+* S'} (hfg : f'.comp g = g'.comp f)
(I : ideal S') : (quotient_map I g' le_rfl).comp (quotient_map (I.comap g') f le_rfl) =
(quotient_map I f' le_rfl).comp (quotient_map (I.comap f') g
(le_of_eq (trans (comap_comap f g') (hfg ▸ (comap_comap g f'))))) :=
begin
refine ring_hom.ext (λ a, _),
obtain ⟨r, rfl⟩ := quotient.mk_surjective a,
simp only [ring_hom.comp_apply, quotient_map_mk],
exact congr_arg (quotient.mk I) (trans (g'.comp_apply f r).symm (hfg ▸ (f'.comp_apply g r))),
end
/-- The algebra hom `A/I →+* B/J` induced by an algebra hom `f : A →ₐ[R₁] B` with `I ≤ f⁻¹(J)`. -/
def quotient_mapₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (hIJ : I ≤ J.comap f) :
A ⧸ I →ₐ[R₁] B ⧸ J :=
{ commutes' := λ r, by simp,
..quotient_map J ↑f hIJ }
@[simp]
lemma quotient_map_mkₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (H : I ≤ J.comap f)
{x : A} : quotient_mapₐ J f H (quotient.mk I x) = quotient.mkₐ R₁ J (f x) := rfl
lemma quotient_map_comp_mkₐ {I : ideal A} (J : ideal B) (f : A →ₐ[R₁] B) (H : I ≤ J.comap f) :
(quotient_mapₐ J f H).comp (quotient.mkₐ R₁ I) = (quotient.mkₐ R₁ J).comp f :=
alg_hom.ext (λ x, by simp only [quotient_map_mkₐ, quotient.mkₐ_eq_mk, alg_hom.comp_apply])
/-- The algebra equiv `A/I ≃ₐ[R] B/J` induced by an algebra equiv `f : A ≃ₐ[R] B`,
where`J = f(I)`. -/
def quotient_equiv_alg (I : ideal A) (J : ideal B) (f : A ≃ₐ[R₁] B)
(hIJ : J = I.map (f : A →+* B)) :
(A ⧸ I) ≃ₐ[R₁] B ⧸ J :=
{ commutes' := λ r, by simp,
..quotient_equiv I J (f : A ≃+* B) hIJ }
@[priority 100]
instance quotient_algebra {I : ideal A} [algebra R A] :
algebra (R ⧸ I.comap (algebra_map R A)) (A ⧸ I) :=
(quotient_map I (algebra_map R A) (le_of_eq rfl)).to_algebra
lemma algebra_map_quotient_injective {I : ideal A} [algebra R A]:
function.injective (algebra_map (R ⧸ I.comap (algebra_map R A)) (A ⧸ I)) :=
begin
rintros ⟨a⟩ ⟨b⟩ hab,
replace hab := quotient.eq.mp hab,
rw ← ring_hom.map_sub at hab,
exact quotient.eq.mpr hab
end
end quotient_algebra
end comm_ring
end ideal
namespace submodule
variables {R : Type u} {M : Type v}
variables [comm_semiring R] [add_comm_monoid M] [module R M]
-- TODO: show `[algebra R A] : algebra (ideal R) A` too
instance module_submodule : module (ideal R) (submodule R M) :=
{ smul_add := smul_sup,
add_smul := sup_smul,
mul_smul := submodule.smul_assoc,
one_smul := by simp,
zero_smul := bot_smul,
smul_zero := smul_bot }
end submodule
namespace ring_hom
variables {A B C : Type*} [ring A] [ring B] [ring C]
variables (f : A →+* B) (f_inv : B → A)
/-- Auxiliary definition used to define `lift_of_right_inverse` -/
def lift_of_right_inverse_aux
(hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) :
B →+* C :=
{ to_fun := λ b, g (f_inv b),
map_one' :=
begin
rw [← g.map_one, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker],
apply hg,
rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_one],
exact hf 1
end,
map_mul' :=
begin
intros x y,
rw [← g.map_mul, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker],
apply hg,
rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_mul],
simp only [hf _],
end,
.. add_monoid_hom.lift_of_right_inverse f.to_add_monoid_hom f_inv hf ⟨g.to_add_monoid_hom, hg⟩ }
@[simp] lemma lift_of_right_inverse_aux_comp_apply
(hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (a : A) :
(f.lift_of_right_inverse_aux f_inv hf g hg) (f a) = g a :=
f.to_add_monoid_hom.lift_of_right_inverse_comp_apply f_inv hf ⟨g.to_add_monoid_hom, hg⟩ a
/-- `lift_of_right_inverse f hf g hg` is the unique ring homomorphism `φ`
* such that `φ.comp f = g` (`ring_hom.lift_of_right_inverse_comp`),
* where `f : A →+* B` is has a right_inverse `f_inv` (`hf`),
* and `g : B →+* C` satisfies `hg : f.ker ≤ g.ker`.
See `ring_hom.eq_lift_of_right_inverse` for the uniqueness lemma.
```
A .
| \
f | \ g
| \
v \⌟
B ----> C
∃!φ
```
-/
def lift_of_right_inverse
(hf : function.right_inverse f_inv f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) :=
{ to_fun := λ g, f.lift_of_right_inverse_aux f_inv hf g.1 g.2,
inv_fun := λ φ, ⟨φ.comp f, λ x hx, (mem_ker _).mpr $ by simp [(mem_ker _).mp hx]⟩,
left_inv := λ g, by
{ ext,
simp only [comp_apply, lift_of_right_inverse_aux_comp_apply, subtype.coe_mk,
subtype.val_eq_coe], },
right_inv := λ φ, by
{ ext b,
simp [lift_of_right_inverse_aux, hf b], } }
/-- A non-computable version of `ring_hom.lift_of_right_inverse` for when no computable right
inverse is available, that uses `function.surj_inv`. -/
@[simp]
noncomputable abbreviation lift_of_surjective
(hf : function.surjective f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) :=
f.lift_of_right_inverse (function.surj_inv hf) (function.right_inverse_surj_inv hf)
lemma lift_of_right_inverse_comp_apply
(hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) (x : A) :
(f.lift_of_right_inverse f_inv hf g) (f x) = g x :=
f.lift_of_right_inverse_aux_comp_apply f_inv hf g.1 g.2 x
lemma lift_of_right_inverse_comp (hf : function.right_inverse f_inv f)
(g : {g : A →+* C // f.ker ≤ g.ker}) :
(f.lift_of_right_inverse f_inv hf g).comp f = g :=
ring_hom.ext $ f.lift_of_right_inverse_comp_apply f_inv hf g
lemma eq_lift_of_right_inverse (hf : function.right_inverse f_inv f) (g : A →+* C)
(hg : f.ker ≤ g.ker) (h : B →+* C) (hh : h.comp f = g) :
h = (f.lift_of_right_inverse f_inv hf ⟨g, hg⟩) :=
begin
simp_rw ←hh,
exact ((f.lift_of_right_inverse f_inv hf).apply_symm_apply _).symm,
end
end ring_hom
namespace double_quot
open ideal
variables {R : Type u} [comm_ring R] (I J : ideal R)
/-- The obvious ring hom `R/I → R/(I ⊔ J)` -/
def quot_left_to_quot_sup : R ⧸ I →+* R ⧸ (I ⊔ J) :=
ideal.quotient.factor I (I ⊔ J) le_sup_left
/-- The kernel of `quot_left_to_quot_sup` -/
lemma ker_quot_left_to_quot_sup :
(quot_left_to_quot_sup I J).ker = J.map (ideal.quotient.mk I) :=
by simp only [mk_ker, sup_idem, sup_comm, quot_left_to_quot_sup, quotient.factor, ker_quotient_lift,
map_eq_iff_sup_ker_eq_of_surjective I^.quotient.mk quotient.mk_surjective, ← sup_assoc]
/-- The ring homomorphism `(R/I)/J' -> R/(I ⊔ J)` induced by `quot_left_to_quot_sup` where `J'`
is the image of `J` in `R/I`-/
def quot_quot_to_quot_sup : (R ⧸ I) ⧸ J.map (ideal.quotient.mk I) →+* R ⧸ I ⊔ J :=
ideal.quotient.lift (ideal.map (ideal.quotient.mk I) J) (quot_left_to_quot_sup I J)
(ker_quot_left_to_quot_sup I J).symm.le
/-- The composite of the maps `R → (R/I)` and `(R/I) → (R/I)/J'` -/
def quot_quot_mk : R →+* ((R ⧸ I) ⧸ J.map I^.quotient.mk) :=
((J.map I^.quotient.mk)^.quotient.mk).comp I^.quotient.mk
/-- The kernel of `quot_quot_mk` -/
lemma ker_quot_quot_mk : (quot_quot_mk I J).ker = I ⊔ J :=
by rw [ring_hom.ker_eq_comap_bot, quot_quot_mk, ← comap_comap, ← ring_hom.ker, mk_ker,
comap_map_of_surjective (ideal.quotient.mk I) (quotient.mk_surjective), ← ring_hom.ker, mk_ker,
sup_comm]
/-- The ring homomorphism `R/(I ⊔ J) → (R/I)/J' `induced by `quot_quot_mk` -/
def lift_sup_quot_quot_mk (I J : ideal R) :
R ⧸ (I ⊔ J) →+* (R ⧸ I) ⧸ J.map (ideal.quotient.mk I) :=
ideal.quotient.lift (I ⊔ J) (quot_quot_mk I J) (ker_quot_quot_mk I J).symm.le
/-- `quot_quot_to_quot_add` and `lift_sup_double_qot_mk` are inverse isomorphisms -/
def quot_quot_equiv_quot_sup : (R ⧸ I) ⧸ J.map (ideal.quotient.mk I) ≃+* R ⧸ I ⊔ J :=
ring_equiv.of_hom_inv (quot_quot_to_quot_sup I J) (lift_sup_quot_quot_mk I J)
(by { ext z, refl }) (by { ext z, refl })
@[simp]
lemma quot_quot_equiv_quot_sup_quot_quot_mk (x : R) :
quot_quot_equiv_quot_sup I J (quot_quot_mk I J x) = ideal.quotient.mk (I ⊔ J) x :=
rfl
@[simp]
lemma quot_quot_equiv_quot_sup_symm_quot_quot_mk (x : R) :
(quot_quot_equiv_quot_sup I J).symm (ideal.quotient.mk (I ⊔ J) x) = quot_quot_mk I J x :=
rfl
/-- The obvious isomorphism `(R/I)/J' → (R/J)/I' ` -/
def quot_quot_equiv_comm :
(R ⧸ I) ⧸ J.map I^.quotient.mk ≃+* (R ⧸ J) ⧸ I.map J^.quotient.mk :=
((quot_quot_equiv_quot_sup I J).trans (quot_equiv_of_eq sup_comm)).trans
(quot_quot_equiv_quot_sup J I).symm
@[simp]
lemma quot_quot_equiv_comm_quot_quot_mk (x : R) :
quot_quot_equiv_comm I J (quot_quot_mk I J x) = quot_quot_mk J I x :=
rfl
@[simp]
lemma quot_quot_equiv_comm_comp_quot_quot_mk :
ring_hom.comp ↑(quot_quot_equiv_comm I J) (quot_quot_mk I J) = quot_quot_mk J I :=
ring_hom.ext $ quot_quot_equiv_comm_quot_quot_mk I J
@[simp]
lemma quot_quot_equiv_comm_symm :
(quot_quot_equiv_comm I J).symm = quot_quot_equiv_comm J I :=
rfl
end double_quot
|
0a90fdb601cb4b5f87b55debf8ee87277cf91987 | 947b78d97130d56365ae2ec264df196ce769371a | /src/Lean/Util/ReplaceExpr.lean | 42bc6e1996e1d6879589c60d829a529d276d7b8b | [
"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 | 3,074 | 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.Expr
namespace Lean
namespace Expr
namespace ReplaceImpl
abbrev cacheSize : USize := 8192
structure State :=
(keys : Array Expr) -- Remark: our "unsafe" implementation relies on the fact that `()` is not a valid Expr
(results : Array Expr)
abbrev ReplaceM := StateM State
@[inline] unsafe def cache (i : USize) (key : Expr) (result : Expr) : ReplaceM Expr := do
modify $ fun s => { keys := s.keys.uset i key lcProof, results := s.results.uset i result lcProof };
pure result
@[specialize] unsafe def replaceUnsafeM (f? : Expr → Option Expr) (size : USize) : Expr → ReplaceM Expr
| e => do
c ← get;
let h := ptrAddrUnsafe e;
let i := h % size;
if ptrAddrUnsafe (c.keys.uget i lcProof) == h then
pure $ c.results.uget i lcProof
else match f? e with
| some eNew => cache i e eNew
| none => match e with
| Expr.forallE _ d b _ => do d ← replaceUnsafeM d; b ← replaceUnsafeM b; cache i e $ e.updateForallE! d b
| Expr.lam _ d b _ => do d ← replaceUnsafeM d; b ← replaceUnsafeM b; cache i e $ e.updateLambdaE! d b
| Expr.mdata _ b _ => do b ← replaceUnsafeM b; cache i e $ e.updateMData! b
| Expr.letE _ t v b _ => do t ← replaceUnsafeM t; v ← replaceUnsafeM v; b ← replaceUnsafeM b; cache i e $ e.updateLet! t v b
| Expr.app f a _ => do f ← replaceUnsafeM f; a ← replaceUnsafeM a; cache i e $ e.updateApp! f a
| Expr.proj _ _ b _ => do b ← replaceUnsafeM b; cache i e $ e.updateProj! b
| Expr.localE _ _ _ _ => unreachable!
| e => pure e
unsafe def initCache : State :=
{ keys := mkArray cacheSize.toNat (cast lcProof ()), -- `()` is not a valid `Expr`
results := mkArray cacheSize.toNat (arbitrary _) }
@[inline] unsafe def replaceUnsafe (f? : Expr → Option Expr) (e : Expr) : Expr :=
(replaceUnsafeM f? cacheSize e).run' initCache
end ReplaceImpl
/- TODO: use withPtrAddr, withPtrEq to avoid unsafe tricks above.
We also need an invariant at `State` and proofs for the `uget` operations. -/
@[implementedBy ReplaceImpl.replaceUnsafe]
partial def replace (f? : Expr → Option Expr) : Expr → Expr
| e =>
/- This is a reference implementation for the unsafe one above -/
match f? e with
| some eNew => eNew
| none => match e with
| Expr.forallE _ d b _ => let d := replace d; let b := replace b; e.updateForallE! d b
| Expr.lam _ d b _ => let d := replace d; let b := replace b; e.updateLambdaE! d b
| Expr.mdata _ b _ => let b := replace b; e.updateMData! b
| Expr.letE _ t v b _ => let t := replace t; let v := replace v; let b := replace b; e.updateLet! t v b
| Expr.app f a _ => let f := replace f; let a := replace a; e.updateApp! f a
| Expr.proj _ _ b _ => let b := replace b; e.updateProj! b
| e => e
end Expr
end Lean
|
f49ad3f35efbb3915ebeb0f5dcba99a417011eff | 74addaa0e41490cbaf2abd313a764c96df57b05d | /Mathlib/analysis/calculus/tangent_cone.lean | 497db319bc2dbe14fe1377dbba07eee519485801 | [] | 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 | 13,622 | lean | /-
Copyright (c) 2019 Sébastien Gouëzel. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Sébastien Gouëzel
-/
import Mathlib.PrePort
import Mathlib.Lean3Lib.init.default
import Mathlib.analysis.convex.basic
import Mathlib.analysis.normed_space.bounded_linear_maps
import Mathlib.analysis.specific_limits
import Mathlib.PostPort
universes u_1 u_2 u_3 u_4
namespace Mathlib
/-!
# Tangent cone
In this file, we define two predicates `unique_diff_within_at 𝕜 s x` and `unique_diff_on 𝕜 s`
ensuring that, if a function has two derivatives, then they have to coincide. As a direct
definition of this fact (quantifying on all target types and all functions) would depend on
universes, we use a more intrinsic definition: if all the possible tangent directions to the set
`s` at the point `x` span a dense subset of the whole subset, it is easy to check that the
derivative has to be unique.
Therefore, we introduce the set of all tangent directions, named `tangent_cone_at`,
and express `unique_diff_within_at` and `unique_diff_on` in terms of it.
One should however think of this definition as an implementation detail: the only reason to
introduce the predicates `unique_diff_within_at` and `unique_diff_on` is to ensure the uniqueness
of the derivative. This is why their names reflect their uses, and not how they are defined.
## Implementation details
Note that this file is imported by `fderiv.lean`. Hence, derivatives are not defined yet. The
property of uniqueness of the derivative is therefore proved in `fderiv.lean`, but based on the
properties of the tangent cone we prove here.
-/
/-- The set of all tangent directions to the set `s` at the point `x`. -/
def tangent_cone_at (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] (s : set E) (x : E) : set E :=
set_of
fun (y : E) =>
∃ (c : ℕ → 𝕜),
∃ (d : ℕ → E),
filter.eventually (fun (n : ℕ) => x + d n ∈ s) filter.at_top ∧
filter.tendsto (fun (n : ℕ) => norm (c n)) filter.at_top filter.at_top ∧
filter.tendsto (fun (n : ℕ) => c n • d n) filter.at_top (nhds y)
/-- A property ensuring that the tangent cone to `s` at `x` spans a dense subset of the whole space.
The main role of this property is to ensure that the differential within `s` at `x` is unique,
hence this name. The uniqueness it asserts is proved in `unique_diff_within_at.eq` in `fderiv.lean`.
To avoid pathologies in dimension 0, we also require that `x` belongs to the closure of `s` (which
is automatic when `E` is not `0`-dimensional).
-/
def unique_diff_within_at (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] (s : set E) (x : E) :=
dense ↑(submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) ∧ x ∈ closure s
/-- A property ensuring that the tangent cone to `s` at any of its points spans a dense subset of
the whole space. The main role of this property is to ensure that the differential along `s` is
unique, hence this name. The uniqueness it asserts is proved in `unique_diff_on.eq` in
`fderiv.lean`. -/
def unique_diff_on (𝕜 : Type u_1) [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] (s : set E) :=
∀ (x : E), x ∈ s → unique_diff_within_at 𝕜 s x
/- This section is devoted to the properties of the tangent cone. -/
theorem tangent_cone_univ {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} : tangent_cone_at 𝕜 set.univ x = set.univ := sorry
theorem tangent_cone_mono {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} {s : set E} {t : set E} (h : s ⊆ t) : tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x := sorry
/-- Auxiliary lemma ensuring that, under the assumptions defining the tangent cone,
the sequence `d` tends to 0 at infinity. -/
theorem tangent_cone_at.lim_zero {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {y : E} {α : Type u_3} (l : filter α) {c : α → 𝕜} {d : α → E} (hc : filter.tendsto (fun (n : α) => norm (c n)) l filter.at_top) (hd : filter.tendsto (fun (n : α) => c n • d n) l (nhds y)) : filter.tendsto d l (nhds 0) := sorry
theorem tangent_cone_mono_nhds {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} {s : set E} {t : set E} (h : nhds_within x s ≤ nhds_within x t) : tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x := sorry
/-- Tangent cone of `s` at `x` depends only on `𝓝[s] x`. -/
theorem tangent_cone_congr {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} {s : set E} {t : set E} (h : nhds_within x s = nhds_within x t) : tangent_cone_at 𝕜 s x = tangent_cone_at 𝕜 t x :=
set.subset.antisymm (tangent_cone_mono_nhds (le_of_eq h)) (tangent_cone_mono_nhds (le_of_eq (Eq.symm h)))
/-- Intersecting with a neighborhood of the point does not change the tangent cone. -/
theorem tangent_cone_inter_nhds {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} {s : set E} {t : set E} (ht : t ∈ nhds x) : tangent_cone_at 𝕜 (s ∩ t) x = tangent_cone_at 𝕜 s x :=
tangent_cone_congr (Eq.symm (nhds_within_restrict' s ht))
/-- The tangent cone of a product contains the tangent cone of its left factor. -/
theorem subset_tangent_cone_prod_left {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {x : E} {s : set E} {t : set F} {y : F} (ht : y ∈ closure t) : ⇑(linear_map.inl 𝕜 E F) '' tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) := sorry
/-- The tangent cone of a product contains the tangent cone of its right factor. -/
theorem subset_tangent_cone_prod_right {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {x : E} {s : set E} {t : set F} {y : F} (hs : x ∈ closure s) : ⇑(linear_map.inr 𝕜 E F) '' tangent_cone_at 𝕜 t y ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) := sorry
/-- If a subset of a real vector space contains a segment, then the direction of this
segment belongs to the tangent cone at its endpoints. -/
theorem mem_tangent_cone_of_segment_subset {G : Type u_4} [normed_group G] [normed_space ℝ G] {s : set G} {x : G} {y : G} (h : segment x y ⊆ s) : y - x ∈ tangent_cone_at ℝ s x := sorry
/-!
### Properties of `unique_diff_within_at` and `unique_diff_on`
This section is devoted to properties of the predicates `unique_diff_within_at` and `unique_diff_on`. -/
theorem unique_diff_on.unique_diff_within_at {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {s : set E} {x : E} (hs : unique_diff_on 𝕜 s) (h : x ∈ s) : unique_diff_within_at 𝕜 s x :=
hs x h
theorem unique_diff_within_at_univ {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} : unique_diff_within_at 𝕜 set.univ x := sorry
theorem unique_diff_on_univ {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] : unique_diff_on 𝕜 set.univ :=
fun (x : E) (hx : x ∈ set.univ) => unique_diff_within_at_univ
theorem unique_diff_on_empty {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] : unique_diff_on 𝕜 ∅ :=
fun (x : E) (hx : x ∈ ∅) => false.elim hx
theorem unique_diff_within_at.mono_nhds {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} {s : set E} {t : set E} (h : unique_diff_within_at 𝕜 s x) (st : nhds_within x s ≤ nhds_within x t) : unique_diff_within_at 𝕜 t x := sorry
theorem unique_diff_within_at.mono {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} {s : set E} {t : set E} (h : unique_diff_within_at 𝕜 s x) (st : s ⊆ t) : unique_diff_within_at 𝕜 t x :=
unique_diff_within_at.mono_nhds h (nhds_within_mono x st)
theorem unique_diff_within_at_congr {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} {s : set E} {t : set E} (st : nhds_within x s = nhds_within x t) : unique_diff_within_at 𝕜 s x ↔ unique_diff_within_at 𝕜 t x :=
{ mp := fun (h : unique_diff_within_at 𝕜 s x) => unique_diff_within_at.mono_nhds h (le_of_eq st),
mpr := fun (h : unique_diff_within_at 𝕜 t x) => unique_diff_within_at.mono_nhds h (le_of_eq (Eq.symm st)) }
theorem unique_diff_within_at_inter {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} {s : set E} {t : set E} (ht : t ∈ nhds x) : unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x :=
unique_diff_within_at_congr (Eq.symm (nhds_within_restrict' s ht))
theorem unique_diff_within_at.inter {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} {s : set E} {t : set E} (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ nhds x) : unique_diff_within_at 𝕜 (s ∩ t) x :=
iff.mpr (unique_diff_within_at_inter ht) hs
theorem unique_diff_within_at_inter' {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} {s : set E} {t : set E} (ht : t ∈ nhds_within x s) : unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x :=
unique_diff_within_at_congr (Eq.symm (nhds_within_restrict'' s ht))
theorem unique_diff_within_at.inter' {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} {s : set E} {t : set E} (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ nhds_within x s) : unique_diff_within_at 𝕜 (s ∩ t) x :=
iff.mpr (unique_diff_within_at_inter' ht) hs
theorem unique_diff_within_at_of_mem_nhds {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} {s : set E} (h : s ∈ nhds x) : unique_diff_within_at 𝕜 s x := sorry
theorem is_open.unique_diff_within_at {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {x : E} {s : set E} (hs : is_open s) (xs : x ∈ s) : unique_diff_within_at 𝕜 s x :=
unique_diff_within_at_of_mem_nhds (mem_nhds_sets hs xs)
theorem unique_diff_on.inter {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {s : set E} {t : set E} (hs : unique_diff_on 𝕜 s) (ht : is_open t) : unique_diff_on 𝕜 (s ∩ t) :=
fun (x : E) (hx : x ∈ s ∩ t) => unique_diff_within_at.inter (hs x (and.left hx)) (mem_nhds_sets ht (and.right hx))
theorem is_open.unique_diff_on {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {s : set E} (hs : is_open s) : unique_diff_on 𝕜 s :=
fun (x : E) (hx : x ∈ s) => is_open.unique_diff_within_at hs hx
/-- The product of two sets of unique differentiability at points `x` and `y` has unique
differentiability at `(x, y)`. -/
theorem unique_diff_within_at.prod {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {x : E} {s : set E} {t : set F} {y : F} (hs : unique_diff_within_at 𝕜 s x) (ht : unique_diff_within_at 𝕜 t y) : unique_diff_within_at 𝕜 (set.prod s t) (x, y) := sorry
/-- The product of two sets of unique differentiability is a set of unique differentiability. -/
theorem unique_diff_on.prod {𝕜 : Type u_1} [nondiscrete_normed_field 𝕜] {E : Type u_2} [normed_group E] [normed_space 𝕜 E] {F : Type u_3} [normed_group F] [normed_space 𝕜 F] {s : set E} {t : set F} (hs : unique_diff_on 𝕜 s) (ht : unique_diff_on 𝕜 t) : unique_diff_on 𝕜 (set.prod s t) := sorry
/-- In a real vector space, a convex set with nonempty interior is a set of unique
differentiability. -/
theorem unique_diff_on_convex {G : Type u_4} [normed_group G] [normed_space ℝ G] {s : set G} (conv : convex s) (hs : set.nonempty (interior s)) : unique_diff_on ℝ s := sorry
theorem unique_diff_on_Ici (a : ℝ) : unique_diff_on ℝ (set.Ici a) := sorry
theorem unique_diff_on_Iic (a : ℝ) : unique_diff_on ℝ (set.Iic a) := sorry
theorem unique_diff_on_Ioi (a : ℝ) : unique_diff_on ℝ (set.Ioi a) :=
is_open.unique_diff_on is_open_Ioi
theorem unique_diff_on_Iio (a : ℝ) : unique_diff_on ℝ (set.Iio a) :=
is_open.unique_diff_on is_open_Iio
theorem unique_diff_on_Icc {a : ℝ} {b : ℝ} (hab : a < b) : unique_diff_on ℝ (set.Icc a b) := sorry
theorem unique_diff_on_Ico (a : ℝ) (b : ℝ) : unique_diff_on ℝ (set.Ico a b) := sorry
theorem unique_diff_on_Ioc (a : ℝ) (b : ℝ) : unique_diff_on ℝ (set.Ioc a b) := sorry
theorem unique_diff_on_Ioo (a : ℝ) (b : ℝ) : unique_diff_on ℝ (set.Ioo a b) :=
is_open.unique_diff_on is_open_Ioo
/-- The real interval `[0, 1]` is a set of unique differentiability. -/
theorem unique_diff_on_Icc_zero_one : unique_diff_on ℝ (set.Icc 0 1) :=
unique_diff_on_Icc zero_lt_one
|
a2d953e0bb74ede27be744f6ef08be502b275a4f | 159fed64bfae88f3b6a6166836d6278f953bcbf9 | /Structure/Generic/Instances/DerivedUniverses.lean | 30a35c4e4aea19e275e2b6d288cb86dee6b51287 | [
"MIT"
] | permissive | SReichelt/lean4-experiments | 3e56830c8b2fbe3814eda071c48e3c8810d254a8 | ff55357a01a34a91bf670d712637480089085ee4 | refs/heads/main | 1,683,977,454,907 | 1,622,991,121,000 | 1,622,991,121,000 | 340,765,677 | 2 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 892 | lean | import Structure.Generic.Axioms
set_option autoBoundImplicitLocal false
--set_option pp.universes true
universes u v
structure UniverseProduct (U : Universe.{u}) (V : Universe.{v}) : Type (max 1 u v) where
(α : U)
(β : V)
def functorUniverse (U : Universe.{u}) (V : Universe.{v}) [HasExternalFunctors U V] : Universe.{max 1 u v} :=
{ α := UniverseProduct U V,
inst := ⟨λ P => P.α ⟶' P.β⟩ }
def equivalenceUniverse (U : Universe.{u}) (V : Universe.{v}) [HasExternalFunctors U V] [HasExternalFunctors V U]
[HasExternalEquivalences U V] : Universe.{max 1 u v} :=
{ α := UniverseProduct U V,
inst := ⟨λ P => P.α ⟷' P.β⟩ }
def productUniverse (U : Universe.{u}) (V : Universe.{v}) : Universe.{max 1 u v} :=
{ α := UniverseProduct U V,
inst := ⟨λ P => PProd ⌈P.α⌉ ⌈P.β⌉⟩ }
|
174f06eeb58e55eca04f1e1e60a3e70453bea7d0 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/tactic/abel.lean | 8122a4f4cec6433ba60fd39802fb9af2d65c07d6 | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 16,741 | lean | /-
Copyright (c) 2018 Mario Carneiro. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Mario Carneiro
-/
import tactic.norm_num
/-!
# The `abel` tactic
Evaluate expressions in the language of additive, commutative monoids and groups.
-/
namespace tactic
namespace abel
/-- The `context` for a call to `abel`.
Stores a few options for this call, and caches some common subexpressions
such as typeclass instances and `0 : α`.
-/
meta structure context :=
(red : transparency)
(α : expr)
(univ : level)
(α0 : expr)
(is_group : bool)
(inst : expr)
/-- Populate a `context` object for evaluating `e`, up to reducibility level `red`. -/
meta def mk_context (red : transparency) (e : expr) : tactic context :=
do α ← infer_type e,
c ← mk_app ``add_comm_monoid [α] >>= mk_instance,
cg ← try_core (mk_app ``add_comm_group [α] >>= mk_instance),
u ← mk_meta_univ,
infer_type α >>= unify (expr.sort (level.succ u)),
u ← get_univ_assignment u,
α0 ← expr.of_nat α 0,
match cg with
| (some cg) := return ⟨red, α, u, α0, tt, cg⟩
| _ := return ⟨red, α, u, α0, ff, c⟩
end
/-- Apply the function `n : ∀ {α} [inst : add_whatever α], _` to the
implicit parameters in the context, and the given list of arguments. -/
meta def context.app (c : context) (n : name) (inst : expr) : list expr → expr :=
(@expr.const tt n [c.univ] c.α inst).mk_app
/-- Apply the function `n : ∀ {α} [inst α], _` to the implicit parameters in the
context, and the given list of arguments.
Compared to `context.app`, this takes the name of the typeclass, rather than an
inferred typeclass instance.
-/
meta def context.mk_app (c : context) (n inst : name) (l : list expr) : tactic expr :=
do m ← mk_instance ((expr.const inst [c.univ] : expr) c.α), return $ c.app n m l
/-- Add the letter "g" to the end of the name, e.g. turning `term` into `termg`.
This is used to choose between declarations taking `add_comm_monoid` and those
taking `add_comm_group` instances.
-/
meta def add_g : name → name
| (name.mk_string s p) := name.mk_string (s ++ "g") p
| n := n
/-- Apply the function `n : ∀ {α} [add_comm_{monoid,group} α]` to the given
list of arguments.
Will use the `add_comm_{monoid,group}` instance that has been cached in the context.
-/
meta def context.iapp (c : context) (n : name) : list expr → expr :=
c.app (if c.is_group then add_g n else n) c.inst
def term {α} [add_comm_monoid α] (n : ℕ) (x a : α) : α := n • x + a
def termg {α} [add_comm_group α] (n : ℤ) (x a : α) : α := n • x + a
/-- Evaluate a term with coefficient `n`, atom `x` and successor terms `a`. -/
meta def context.mk_term (c : context) (n x a : expr) : expr := c.iapp ``term [n, x, a]
/-- Interpret an integer as a coefficient to a term. -/
meta def context.int_to_expr (c : context) (n : ℤ) : tactic expr :=
expr.of_int (if c.is_group then `(ℤ) else `(ℕ)) n
meta inductive normal_expr : Type
| zero (e : expr) : normal_expr
| nterm (e : expr) (n : expr × ℤ) (x : expr) (a : normal_expr) : normal_expr
meta def normal_expr.e : normal_expr → expr
| (normal_expr.zero e) := e
| (normal_expr.nterm e _ _ _) := e
meta instance : has_coe normal_expr expr := ⟨normal_expr.e⟩
meta instance : has_coe_to_fun normal_expr (λ _, expr → expr) := ⟨λ e, ⇑(e : expr)⟩
meta def normal_expr.term' (c : context) (n : expr × ℤ) (x : expr) (a : normal_expr) :
normal_expr :=
normal_expr.nterm (c.mk_term n.1 x a) n x a
meta def normal_expr.zero' (c : context) : normal_expr := normal_expr.zero c.α0
meta def normal_expr.to_list : normal_expr → list (ℤ × expr)
| (normal_expr.zero _) := []
| (normal_expr.nterm _ (_, n) x a) := (n, x) :: a.to_list
open normal_expr
meta def normal_expr.to_string (e : normal_expr) : string :=
" + ".intercalate $ (to_list e).map $
λ ⟨n, e⟩, to_string n ++ " • (" ++ to_string e ++ ")"
meta def normal_expr.pp (e : normal_expr) : tactic format :=
do l ← (to_list e).mmap (λ ⟨n, e⟩, do
pe ← pp e, return (to_fmt n ++ " • (" ++ pe ++ ")")),
return $ format.join $ l.intersperse ↑" + "
meta instance : has_to_tactic_format normal_expr := ⟨normal_expr.pp⟩
meta def normal_expr.refl_conv (e : normal_expr) : tactic (normal_expr × expr) :=
do p ← mk_eq_refl e, return (e, p)
theorem const_add_term {α} [add_comm_monoid α] (k n x a a') (h : k + a = a') :
k + @term α _ n x a = term n x a' := by simp [h.symm, term]; ac_refl
theorem const_add_termg {α} [add_comm_group α] (k n x a a') (h : k + a = a') :
k + @termg α _ n x a = termg n x a' := by simp [h.symm, termg]; ac_refl
theorem term_add_const {α} [add_comm_monoid α] (n x a k a') (h : a + k = a') :
@term α _ n x a + k = term n x a' := by simp [h.symm, term, add_assoc]
theorem term_add_constg {α} [add_comm_group α] (n x a k a') (h : a + k = a') :
@termg α _ n x a + k = termg n x a' := by simp [h.symm, termg, add_assoc]
theorem term_add_term {α} [add_comm_monoid α] (n₁ x a₁ n₂ a₂ n' a')
(h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') :
@term α _ n₁ x a₁ + @term α _ n₂ x a₂ = term n' x a' :=
by simp [h₁.symm, h₂.symm, term, add_nsmul]; ac_refl
theorem term_add_termg {α} [add_comm_group α] (n₁ x a₁ n₂ a₂ n' a')
(h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') :
@termg α _ n₁ x a₁ + @termg α _ n₂ x a₂ = termg n' x a' :=
by simp [h₁.symm, h₂.symm, termg, add_zsmul]; ac_refl
theorem zero_term {α} [add_comm_monoid α] (x a) : @term α _ 0 x a = a :=
by simp [term, zero_nsmul, one_nsmul]
theorem zero_termg {α} [add_comm_group α] (x a) : @termg α _ 0 x a = a :=
by simp [termg]
meta def eval_add (c : context) : normal_expr → normal_expr → tactic (normal_expr × expr)
| (zero _) e₂ := do
p ← mk_app ``zero_add [e₂],
return (e₂, p)
| e₁ (zero _) := do
p ← mk_app ``add_zero [e₁],
return (e₁, p)
| he₁@(nterm e₁ n₁ x₁ a₁) he₂@(nterm e₂ n₂ x₂ a₂) :=
(do
is_def_eq x₁ x₂ c.red,
(n', h₁) ← mk_app ``has_add.add [n₁.1, n₂.1] >>= norm_num.eval_field,
(a', h₂) ← eval_add a₁ a₂,
let k := n₁.2 + n₂.2,
let p₁ := c.iapp ``term_add_term [n₁.1, x₁, a₁, n₂.1, a₂, n', a', h₁, h₂],
if k = 0 then do
p ← mk_eq_trans p₁ (c.iapp ``zero_term [x₁, a']),
return (a', p)
else return (term' c (n', k) x₁ a', p₁))
<|> if expr.lex_lt x₁ x₂ then do
(a', h) ← eval_add a₁ he₂,
return (term' c n₁ x₁ a', c.iapp ``term_add_const [n₁.1, x₁, a₁, e₂, a', h])
else do
(a', h) ← eval_add he₁ a₂,
return (term' c n₂ x₂ a', c.iapp ``const_add_term [e₁, n₂.1, x₂, a₂, a', h])
theorem term_neg {α} [add_comm_group α] (n x a n' a')
(h₁ : -n = n') (h₂ : -a = a') :
-@termg α _ n x a = termg n' x a' :=
by simp [h₂.symm, h₁.symm, termg]; ac_refl
meta def eval_neg (c : context) : normal_expr → tactic (normal_expr × expr)
| (zero e) := do
p ← c.mk_app ``neg_zero ``add_group [],
return (zero' c, p)
| (nterm e n x a) := do
(n', h₁) ← mk_app ``has_neg.neg [n.1] >>= norm_num.eval_field,
(a', h₂) ← eval_neg a,
return (term' c (n', -n.2) x a',
c.app ``term_neg c.inst [n.1, x, a, n', a', h₁, h₂])
def smul {α} [add_comm_monoid α] (n : ℕ) (x : α) : α := n • x
def smulg {α} [add_comm_group α] (n : ℤ) (x : α) : α := n • x
theorem zero_smul {α} [add_comm_monoid α] (c) : smul c (0 : α) = 0 :=
by simp [smul, nsmul_zero]
theorem zero_smulg {α} [add_comm_group α] (c) : smulg c (0 : α) = 0 :=
by simp [smulg]
theorem term_smul {α} [add_comm_monoid α] (c n x a n' a')
(h₁ : c * n = n') (h₂ : smul c a = a') :
smul c (@term α _ n x a) = term n' x a' :=
by simp [h₂.symm, h₁.symm, term, smul, nsmul_add, mul_nsmul]
theorem term_smulg {α} [add_comm_group α] (c n x a n' a')
(h₁ : c * n = n') (h₂ : smulg c a = a') :
smulg c (@termg α _ n x a) = termg n' x a' :=
by simp [h₂.symm, h₁.symm, termg, smulg, zsmul_add, mul_zsmul]
meta def eval_smul (c : context) (k : expr × ℤ) :
normal_expr → tactic (normal_expr × expr)
| (zero _) := return (zero' c, c.iapp ``zero_smul [k.1])
| (nterm e n x a) := do
(n', h₁) ← mk_app ``has_mul.mul [k.1, n.1] >>= norm_num.eval_field,
(a', h₂) ← eval_smul a,
return (term' c (n', k.2 * n.2) x a',
c.iapp ``term_smul [k.1, n.1, x, a, n', a', h₁, h₂])
theorem term_atom {α} [add_comm_monoid α] (x : α) : x = term 1 x 0 :=
by simp [term]
theorem term_atomg {α} [add_comm_group α] (x : α) : x = termg 1 x 0 :=
by simp [termg]
meta def eval_atom (c : context) (e : expr) : tactic (normal_expr × expr) :=
do n1 ← c.int_to_expr 1,
return (term' c (n1, 1) e (zero' c), c.iapp ``term_atom [e])
lemma unfold_sub {α} [add_group α] (a b c : α)
(h : a + -b = c) : a - b = c :=
by rw [sub_eq_add_neg, h]
theorem unfold_smul {α} [add_comm_monoid α] (n) (x y : α)
(h : smul n x = y) : n • x = y := h
theorem unfold_smulg {α} [add_comm_group α] (n : ℕ) (x y : α)
(h : smulg (int.of_nat n) x = y) : (n : ℤ) • x = y := h
theorem unfold_zsmul {α} [add_comm_group α] (n : ℤ) (x y : α)
(h : smulg n x = y) : n • x = y := h
lemma subst_into_smul {α} [add_comm_monoid α]
(l r tl tr t) (prl : l = tl) (prr : r = tr)
(prt : @smul α _ tl tr = t) : smul l r = t :=
by simp [prl, prr, prt]
lemma subst_into_smulg {α} [add_comm_group α]
(l r tl tr t) (prl : l = tl) (prr : r = tr)
(prt : @smulg α _ tl tr = t) : smulg l r = t :=
by simp [prl, prr, prt]
lemma subst_into_smul_upcast {α} [add_comm_group α]
(l r tl zl tr t) (prl₁ : l = tl) (prl₂ : ↑tl = zl) (prr : r = tr)
(prt : @smulg α _ zl tr = t) : smul l r = t :=
by simp [← prt, prl₁, ← prl₂, prr, smul, smulg]
/-- Normalize a term `orig` of the form `smul e₁ e₂` or `smulg e₁ e₂`.
Normalized terms use `smul` for monoids and `smulg` for groups,
so there are actually four cases to handle:
* Using `smul` in a monoid just simplifies the pieces using `subst_into_smul`
* Using `smulg` in a group just simplifies the pieces using `subst_into_smulg`
* Using `smul a b` in a group requires converting `a` from a nat to an int and
then simplifying `smulg ↑a b` using `subst_into_smul_upcast`
* Using `smulg` in a monoid is impossible (or at least out of scope),
because you need a group argument to write a `smulg` term -/
meta def eval_smul' (c : context) (eval : expr → tactic (normal_expr × expr))
(is_smulg : bool) (orig e₁ e₂ : expr) : tactic (normal_expr × expr) :=
do (e₁', p₁) ← norm_num.derive e₁ <|> refl_conv e₁,
match if is_smulg then e₁'.to_int else coe <$> e₁'.to_nat with
| some n := do
(e₂', p₂) ← eval e₂,
if c.is_group = is_smulg then do
(e', p) ← eval_smul c (e₁', n) e₂',
return (e', c.iapp ``subst_into_smul [e₁, e₂, e₁', e₂', e', p₁, p₂, p])
else do
guardb c.is_group,
ic ← mk_instance_cache `(ℤ),
nc ← mk_instance_cache `(ℕ),
(ic, zl) ← ic.of_int n,
(_, _, _, p₁') ← norm_num.prove_nat_uncast ic nc zl,
(e', p) ← eval_smul c (zl, n) e₂',
return (e', c.app ``subst_into_smul_upcast c.inst [e₁, e₂, e₁', zl, e₂', e', p₁, p₁', p₂, p])
| none := eval_atom c orig
end
meta def eval (c : context) : expr → tactic (normal_expr × expr)
| `(%%e₁ + %%e₂) := do
(e₁', p₁) ← eval e₁,
(e₂', p₂) ← eval e₂,
(e', p') ← eval_add c e₁' e₂',
p ← c.mk_app ``norm_num.subst_into_add ``has_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'],
return (e', p)
| `(%%e₁ - %%e₂) := do
e₂' ← mk_app ``has_neg.neg [e₂],
e ← mk_app ``has_add.add [e₁, e₂'],
(e', p) ← eval e,
p' ← c.mk_app ``unfold_sub ``add_group [e₁, e₂, e', p],
return (e', p')
| `(- %%e) := do
(e₁, p₁) ← eval e,
(e₂, p₂) ← eval_neg c e₁,
p ← c.mk_app ``norm_num.subst_into_neg ``has_neg [e, e₁, e₂, p₁, p₂],
return (e₂, p)
| `(add_monoid.nsmul %%e₁ %%e₂) := do
n ← if c.is_group then mk_app ``int.of_nat [e₁] else return e₁,
(e', p) ← eval $ c.iapp ``smul [n, e₂],
return (e', c.iapp ``unfold_smul [e₁, e₂, e', p])
| `(sub_neg_monoid.zsmul %%e₁ %%e₂) := do
guardb c.is_group,
(e', p) ← eval $ c.iapp ``smul [e₁, e₂],
return (e', c.app ``unfold_zsmul c.inst [e₁, e₂, e', p])
| e@`(@has_scalar.smul nat _ add_monoid.has_scalar_nat %%e₁ %%e₂) :=
eval_smul' c eval ff e e₁ e₂
| e@`(@has_scalar.smul int _ sub_neg_monoid.has_scalar_int %%e₁ %%e₂) :=
eval_smul' c eval tt e e₁ e₂
| e@`(smul %%e₁ %%e₂) := eval_smul' c eval ff e e₁ e₂
| e@`(smulg %%e₁ %%e₂) := eval_smul' c eval tt e e₁ e₂
| e@`(@has_zero.zero _ _) := mcond (succeeds (is_def_eq e c.α0))
(mk_eq_refl c.α0 >>= λ p, pure (zero' c, p))
(eval_atom c e)
| e := eval_atom c e
meta def eval' (c : context) (e : expr) : tactic (expr × expr) :=
do (e', p) ← eval c e, return (e', p)
@[derive has_reflect]
inductive normalize_mode | raw | term
instance : inhabited normalize_mode := ⟨normalize_mode.term⟩
meta def normalize (red : transparency) (mode := normalize_mode.term) (e : expr) :
tactic (expr × expr) := do
pow_lemma ← simp_lemmas.mk.add_simp ``pow_one,
let lemmas := match mode with
| normalize_mode.term :=
[``term.equations._eqn_1, ``termg.equations._eqn_1, ``add_zero, ``one_nsmul, ``one_zsmul,
``zsmul_zero]
| _ := []
end,
lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk,
(_, e', pr) ← ext_simplify_core () {}
simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do
c ← mk_context red e,
(new_e, pr) ← match mode with
| normalize_mode.raw := eval' c
| normalize_mode.term := trans_conv (eval' c)
(λ e, do (e', prf, _) ← simplify lemmas [] e, return (e', prf))
end e,
guard (¬ new_e =ₐ e),
return ((), new_e, some pr, ff))
(λ _ _ _ _ _, failed) `eq e,
return (e', pr)
end abel
namespace interactive
open tactic.abel
setup_tactic_parser
/-- Tactic for solving equations in the language of
*additive*, commutative monoids and groups.
This version of `abel` fails if the target is not an equality
that is provable by the axioms of commutative monoids/groups.
`abel1!` will use a more aggressive reducibility setting to identify atoms.
This can prove goals that `abel` cannot, but is more expensive.
-/
meta def abel1 (red : parse (tk "!")?) : tactic unit :=
do `(%%e₁ = %%e₂) ← target,
c ← mk_context (if red.is_some then semireducible else reducible) e₁,
(e₁', p₁) ← eval c e₁,
(e₂', p₂) ← eval c e₂,
is_def_eq e₁' e₂',
p ← mk_eq_symm p₂ >>= mk_eq_trans p₁,
tactic.exact p
meta def abel.mode : lean.parser abel.normalize_mode :=
with_desc "(raw|term)?" $
do mode ← ident?, match mode with
| none := return abel.normalize_mode.term
| some `term := return abel.normalize_mode.term
| some `raw := return abel.normalize_mode.raw
| _ := failed
end
/--
Evaluate expressions in the language of *additive*, commutative monoids and groups.
It 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 monoid expressions into a normal form.
If there is an `at` specifier, it rewrites the given target into a normal form.
`abel!` will use a more aggressive reducibility setting to identify atoms.
This can prove goals that `abel` cannot, but is more expensive.
```lean
example {α : Type*} {a b : α} [add_comm_monoid α] : a + (b + a) = a + a + b := by abel
example {α : Type*} {a b : α} [add_comm_group α] : (a + b) - ((b + a) + a) = -a := by abel
example {α : Type*} {a b : α} [add_comm_group α] (hyp : a + a - a = b - b) : a = 0 :=
by { abel at hyp, exact hyp }
example {α : Type*} {a b : α} [add_comm_group α] : (a + b) - (id a + b) = 0 := by abel!
```
-/
meta def abel (red : parse (tk "!")?) (SOP : parse abel.mode) (loc : parse location) :
tactic unit :=
match loc with
| interactive.loc.ns [none] := abel1 red
| _ := failed
end <|>
do ns ← loc.get_locals,
let red := if red.is_some then semireducible else reducible,
tt ← tactic.replace_at (normalize red SOP) ns loc.include_goal
| fail "abel failed to simplify",
when loc.include_goal $ try tactic.reflexivity
add_tactic_doc
{ name := "abel",
category := doc_category.tactic,
decl_names := [`tactic.interactive.abel],
tags := ["arithmetic", "decision procedure"] }
end interactive
end tactic
|
611e02d905057fc3a4c36c78437715ea2d7c842c | 9dc8cecdf3c4634764a18254e94d43da07142918 | /src/analysis/inner_product_space/orientation.lean | 9195a0b66ca8bd19f3ae04f717cbe03ef08bf299 | [
"Apache-2.0"
] | permissive | jcommelin/mathlib | d8456447c36c176e14d96d9e76f39841f69d2d9b | ee8279351a2e434c2852345c51b728d22af5a156 | refs/heads/master | 1,664,782,136,488 | 1,663,638,983,000 | 1,663,638,983,000 | 132,563,656 | 0 | 0 | Apache-2.0 | 1,663,599,929,000 | 1,525,760,539,000 | Lean | UTF-8 | Lean | false | false | 2,461 | lean | /-
Copyright (c) 2022 Joseph Myers. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Joseph Myers
-/
import analysis.inner_product_space.pi_L2
import linear_algebra.orientation
/-!
# Orientations of real inner product spaces.
This file provides definitions and proves lemmas about orientations of real inner product spaces.
## Main definitions
* `orientation.fin_orthonormal_basis` is an orthonormal basis, indexed by `fin n`, with the given
orientation.
-/
noncomputable theory
variables {E : Type*} [inner_product_space ℝ E]
variables {ι : Type*} [fintype ι] [decidable_eq ι]
open finite_dimensional
/-- `basis.adjust_to_orientation`, applied to an orthonormal basis, produces an orthonormal
basis. -/
lemma orthonormal.orthonormal_adjust_to_orientation [nonempty ι] {e : basis ι ℝ E}
(h : orthonormal ℝ e) (x : orientation ℝ E ι) : orthonormal ℝ (e.adjust_to_orientation x) :=
h.orthonormal_of_forall_eq_or_eq_neg (e.adjust_to_orientation_apply_eq_or_eq_neg x)
/-- An orthonormal basis, indexed by `fin n`, with the given orientation. -/
protected def orientation.fin_orthonormal_basis {n : ℕ} (hn : 0 < n) (h : finrank ℝ E = n)
(x : orientation ℝ E (fin n)) : basis (fin n) ℝ E :=
begin
haveI := fin.pos_iff_nonempty.1 hn,
haveI := finite_dimensional_of_finrank (h.symm ▸ hn : 0 < finrank ℝ E),
exact (fin_std_orthonormal_basis h).to_basis.adjust_to_orientation x
end
/-- `orientation.fin_orthonormal_basis` is orthonormal. -/
protected lemma orientation.fin_orthonormal_basis_orthonormal {n : ℕ} (hn : 0 < n)
(h : finrank ℝ E = n) (x : orientation ℝ E (fin n)) :
orthonormal ℝ (x.fin_orthonormal_basis hn h) :=
begin
haveI := fin.pos_iff_nonempty.1 hn,
haveI := finite_dimensional_of_finrank (h.symm ▸ hn : 0 < finrank ℝ E),
exact (show orthonormal ℝ (fin_std_orthonormal_basis h).to_basis, -- Note sure how to format this
by simp only [orthonormal_basis.coe_to_basis, orthonormal_basis.orthonormal]
).orthonormal_adjust_to_orientation _
end
/-- `orientation.fin_orthonormal_basis` gives a basis with the required orientation. -/
@[simp] lemma orientation.fin_orthonormal_basis_orientation {n : ℕ} (hn : 0 < n)
(h : finrank ℝ E = n) (x : orientation ℝ E (fin n)) :
(x.fin_orthonormal_basis hn h).orientation = x :=
begin
haveI := fin.pos_iff_nonempty.1 hn,
exact basis.orientation_adjust_to_orientation _ _
end
|
95ae1d7ccd128bd4d2a06b38e92020720f420f52 | 57c233acf9386e610d99ed20ef139c5f97504ba3 | /src/algebra/category/CommRing/basic.lean | d254d6c730cbdc2c2845ca42cb74e5592247184f | [
"Apache-2.0"
] | permissive | robertylewis/mathlib | 3d16e3e6daf5ddde182473e03a1b601d2810952c | 1d13f5b932f5e40a8308e3840f96fc882fae01f0 | refs/heads/master | 1,651,379,945,369 | 1,644,276,960,000 | 1,644,276,960,000 | 98,875,504 | 0 | 0 | Apache-2.0 | 1,644,253,514,000 | 1,501,495,700,000 | Lean | UTF-8 | Lean | false | false | 9,275 | lean | /-
Copyright (c) 2018 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Johannes Hölzl, Yury Kudryashov
-/
import algebra.category.Group.basic
import category_theory.concrete_category.reflects_isomorphisms
import data.equiv.ring
/-!
# Category instances for semiring, ring, comm_semiring, and comm_ring.
We introduce the bundled categories:
* `SemiRing`
* `Ring`
* `CommSemiRing`
* `CommRing`
along with the relevant forgetful functors between them.
-/
universes u v
open category_theory
/-- The category of semirings. -/
def SemiRing : Type (u+1) := bundled semiring
namespace SemiRing
/-- `ring_hom` doesn't actually assume associativity. This alias is needed to make the category
theory machinery work. We use the same trick in `category_theory.Mon.assoc_monoid_hom`. -/
abbreviation assoc_ring_hom (M N : Type*) [semiring M] [semiring N] := ring_hom M N
instance bundled_hom : bundled_hom assoc_ring_hom :=
⟨λ M N [semiring M] [semiring N], by exactI @ring_hom.to_fun M N _ _,
λ M [semiring M], by exactI @ring_hom.id M _,
λ M N P [semiring M] [semiring N] [semiring P], by exactI @ring_hom.comp M N P _ _ _,
λ M N [semiring M] [semiring N], by exactI @ring_hom.coe_inj M N _ _⟩
attribute [derive [large_category, concrete_category]] SemiRing
instance : has_coe_to_sort SemiRing Type* := bundled.has_coe_to_sort
/-- Construct a bundled SemiRing from the underlying type and typeclass. -/
def of (R : Type u) [semiring R] : SemiRing := bundled.of R
/-- Typecheck a `ring_hom` as a morphism in `SemiRing`. -/
def of_hom {R S : Type u} [semiring R] [semiring S] (f : R →+* S) : of R ⟶ of S := f
instance : inhabited SemiRing := ⟨of punit⟩
instance (R : SemiRing) : semiring R := R.str
@[simp] lemma coe_of (R : Type u) [semiring R] : (SemiRing.of R : Type u) = R := rfl
instance has_forget_to_Mon : has_forget₂ SemiRing Mon :=
bundled_hom.mk_has_forget₂
(λ R hR, @monoid_with_zero.to_monoid R (@semiring.to_monoid_with_zero R hR))
(λ R₁ R₂, ring_hom.to_monoid_hom) (λ _ _ _, rfl)
instance has_forget_to_AddCommMon : has_forget₂ SemiRing AddCommMon :=
-- can't use bundled_hom.mk_has_forget₂, since AddCommMon is an induced category
{ forget₂ :=
{ obj := λ R, AddCommMon.of R,
map := λ R₁ R₂ f, ring_hom.to_add_monoid_hom f } }
end SemiRing
/-- The category of rings. -/
def Ring : Type (u+1) := bundled ring
namespace Ring
instance : bundled_hom.parent_projection @ring.to_semiring := ⟨⟩
attribute [derive [(λ Ring, has_coe_to_sort Ring Type*), large_category, concrete_category]] Ring
/-- Construct a bundled Ring from the underlying type and typeclass. -/
def of (R : Type u) [ring R] : Ring := bundled.of R
/-- Typecheck a `ring_hom` as a morphism in `Ring`. -/
def of_hom {R S : Type u} [ring R] [ring S] (f : R →+* S) : of R ⟶ of S := f
instance : inhabited Ring := ⟨of punit⟩
instance (R : Ring) : ring R := R.str
@[simp] lemma coe_of (R : Type u) [ring R] : (Ring.of R : Type u) = R := rfl
instance has_forget_to_SemiRing : has_forget₂ Ring SemiRing := bundled_hom.forget₂ _ _
instance has_forget_to_AddCommGroup : has_forget₂ Ring AddCommGroup :=
-- can't use bundled_hom.mk_has_forget₂, since AddCommGroup is an induced category
{ forget₂ :=
{ obj := λ R, AddCommGroup.of R,
map := λ R₁ R₂ f, ring_hom.to_add_monoid_hom f } }
end Ring
/-- The category of commutative semirings. -/
def CommSemiRing : Type (u+1) := bundled comm_semiring
namespace CommSemiRing
instance : bundled_hom.parent_projection @comm_semiring.to_semiring := ⟨⟩
attribute [derive [large_category, concrete_category]] CommSemiRing
instance : has_coe_to_sort CommSemiRing Type* := bundled.has_coe_to_sort
/-- Construct a bundled CommSemiRing from the underlying type and typeclass. -/
def of (R : Type u) [comm_semiring R] : CommSemiRing := bundled.of R
/-- Typecheck a `ring_hom` as a morphism in `CommSemiRing`. -/
def of_hom {R S : Type u} [comm_semiring R] [comm_semiring S] (f : R →+* S) : of R ⟶ of S := f
instance : inhabited CommSemiRing := ⟨of punit⟩
instance (R : CommSemiRing) : comm_semiring R := R.str
@[simp] lemma coe_of (R : Type u) [comm_semiring R] : (CommSemiRing.of R : Type u) = R := rfl
instance has_forget_to_SemiRing : has_forget₂ CommSemiRing SemiRing := bundled_hom.forget₂ _ _
/-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/
instance has_forget_to_CommMon : has_forget₂ CommSemiRing CommMon :=
has_forget₂.mk'
(λ R : CommSemiRing, CommMon.of R) (λ R, rfl)
(λ R₁ R₂ f, f.to_monoid_hom) (by tidy)
end CommSemiRing
/-- The category of commutative rings. -/
def CommRing : Type (u+1) := bundled comm_ring
namespace CommRing
instance : bundled_hom.parent_projection @comm_ring.to_ring := ⟨⟩
attribute [derive [large_category, concrete_category]] CommRing
instance : has_coe_to_sort CommRing Type* := bundled.has_coe_to_sort
/-- Construct a bundled CommRing from the underlying type and typeclass. -/
def of (R : Type u) [comm_ring R] : CommRing := bundled.of R
/-- Typecheck a `ring_hom` as a morphism in `CommRing`. -/
def of_hom {R S : Type u} [comm_ring R] [comm_ring S] (f : R →+* S) : of R ⟶ of S := f
instance : inhabited CommRing := ⟨of punit⟩
instance (R : CommRing) : comm_ring R := R.str
@[simp] lemma coe_of (R : Type u) [comm_ring R] : (CommRing.of R : Type u) = R := rfl
instance has_forget_to_Ring : has_forget₂ CommRing Ring := bundled_hom.forget₂ _ _
/-- The forgetful functor from commutative rings to (multiplicative) commutative monoids. -/
instance has_forget_to_CommSemiRing : has_forget₂ CommRing CommSemiRing :=
has_forget₂.mk' (λ R : CommRing, CommSemiRing.of R) (λ R, rfl) (λ R₁ R₂ f, f) (by tidy)
instance : full (forget₂ CommRing CommSemiRing) :=
{ preimage := λ X Y f, f, }
end CommRing
-- This example verifies an improvement possible in Lean 3.8.
-- Before that, to have `add_ring_hom.map_zero` usable by `simp` here,
-- we had to mark all the concrete category `has_coe_to_sort` instances reducible.
-- Now, it just works.
example {R S : CommRing} (i : R ⟶ S) (r : R) (h : r = 0) : i r = 0 :=
by simp [h]
namespace ring_equiv
variables {X Y : Type u}
/-- Build an isomorphism in the category `Ring` from a `ring_equiv` between `ring`s. -/
@[simps] def to_Ring_iso [ring X] [ring Y] (e : X ≃+* Y) : Ring.of X ≅ Ring.of Y :=
{ hom := e.to_ring_hom,
inv := e.symm.to_ring_hom }
/-- Build an isomorphism in the category `CommRing` from a `ring_equiv` between `comm_ring`s. -/
@[simps] def to_CommRing_iso [comm_ring X] [comm_ring Y] (e : X ≃+* Y) :
CommRing.of X ≅ CommRing.of Y :=
{ hom := e.to_ring_hom,
inv := e.symm.to_ring_hom }
end ring_equiv
namespace category_theory.iso
/-- Build a `ring_equiv` from an isomorphism in the category `Ring`. -/
def Ring_iso_to_ring_equiv {X Y : Ring} (i : X ≅ Y) : X ≃+* Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := by tidy,
right_inv := by tidy,
map_add' := by tidy,
map_mul' := by tidy }.
/-- Build a `ring_equiv` from an isomorphism in the category `CommRing`. -/
def CommRing_iso_to_ring_equiv {X Y : CommRing} (i : X ≅ Y) : X ≃+* Y :=
{ to_fun := i.hom,
inv_fun := i.inv,
left_inv := by tidy,
right_inv := by tidy,
map_add' := by tidy,
map_mul' := by tidy }.
@[simp]
lemma CommRing_iso_to_ring_equiv_to_ring_hom {X Y : CommRing} (i : X ≅ Y) :
i.CommRing_iso_to_ring_equiv.to_ring_hom = i.hom := by { ext, refl }
@[simp]
lemma CommRing_iso_to_ring_equiv_symm_to_ring_hom {X Y : CommRing} (i : X ≅ Y) :
i.CommRing_iso_to_ring_equiv.symm.to_ring_hom = i.inv := by { ext, refl }
end category_theory.iso
/-- Ring equivalences between `ring`s are the same as (isomorphic to) isomorphisms in `Ring`. -/
def ring_equiv_iso_Ring_iso {X Y : Type u} [ring X] [ring Y] :
(X ≃+* Y) ≅ (Ring.of X ≅ Ring.of Y) :=
{ hom := λ e, e.to_Ring_iso,
inv := λ i, i.Ring_iso_to_ring_equiv, }
/-- Ring equivalences between `comm_ring`s are the same as (isomorphic to) isomorphisms
in `CommRing`. -/
def ring_equiv_iso_CommRing_iso {X Y : Type u} [comm_ring X] [comm_ring Y] :
(X ≃+* Y) ≅ (CommRing.of X ≅ CommRing.of Y) :=
{ hom := λ e, e.to_CommRing_iso,
inv := λ i, i.CommRing_iso_to_ring_equiv, }
instance Ring.forget_reflects_isos : reflects_isomorphisms (forget Ring.{u}) :=
{ reflects := λ X Y f _,
begin
resetI,
let i := as_iso ((forget Ring).map f),
let e : X ≃+* Y := { ..f, ..i.to_equiv },
exact ⟨(is_iso.of_iso e.to_Ring_iso).1⟩,
end }
instance CommRing.forget_reflects_isos : reflects_isomorphisms (forget CommRing.{u}) :=
{ reflects := λ X Y f _,
begin
resetI,
let i := as_iso ((forget CommRing).map f),
let e : X ≃+* Y := { ..f, ..i.to_equiv },
exact ⟨(is_iso.of_iso e.to_CommRing_iso).1⟩,
end }
-- It would be nice if we could have the following,
-- but it requires making `reflects_isomorphisms_forget₂` an instance,
-- which can cause typeclass loops:
local attribute [priority 50,instance] reflects_isomorphisms_forget₂
example : reflects_isomorphisms (forget₂ Ring AddCommGroup) := by apply_instance
|
9cd7d4a3ac2e2837dd63bb17fea5fada840b7ad4 | b561a44b48979a98df50ade0789a21c79ee31288 | /src/Lean/Server/Completion.lean | ac8f2e298ce64f12e5211fb5dd37066c3bba6a0a | [
"Apache-2.0"
] | permissive | 3401ijk/lean4 | 97659c475ebd33a034fed515cb83a85f75ccfb06 | a5b1b8de4f4b038ff752b9e607b721f15a9a4351 | refs/heads/master | 1,693,933,007,651 | 1,636,424,845,000 | 1,636,424,845,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 13,080 | lean | /-
Copyright (c) 2021 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Environment
import Lean.Parser.Term
import Lean.Data.Lsp.LanguageFeatures
import Lean.Meta.Tactic.Apply
import Lean.Meta.Match.MatcherInfo
import Lean.Server.InfoUtils
import Lean.Parser.Extension
namespace Lean.Server.Completion
open Lsp
open Elab
open Meta
builtin_initialize completionBlackListExt : TagDeclarationExtension ← mkTagDeclarationExtension `blackListCompletion
@[export lean_completion_add_to_black_list]
def addToBlackList (env : Environment) (declName : Name) : Environment :=
completionBlackListExt.tag env declName
private def isBlackListed (declName : Name) : MetaM Bool := do
let env ← getEnv
(declName.isInternal && !isPrivateName declName)
<||> isAuxRecursor env declName
<||> isNoConfusion env declName
<||> isRec declName
<||> completionBlackListExt.isTagged env declName
<||> isMatcher declName
private partial def consumeImplicitPrefix (e : Expr) (k : Expr → MetaM α) : MetaM α := do
match e with
| Expr.forallE n d b c =>
-- We do not consume instance implicit arguments because the user probably wants be aware of this dependency
if c.binderInfo == BinderInfo.implicit then
withLocalDecl n c.binderInfo d fun arg =>
consumeImplicitPrefix (b.instantiate1 arg) k
else
k e
| _ => k e
private def isTypeApplicable (type : Expr) (expectedType? : Option Expr) : MetaM Bool :=
try
match expectedType? with
| none => return true
| some expectedType =>
let mut (numArgs, hasMVarHead) ← getExpectedNumArgsAux type
unless hasMVarHead do
let targetTypeNumArgs ← getExpectedNumArgs expectedType
numArgs := numArgs - targetTypeNumArgs
let (newMVars, _, type) ← forallMetaTelescopeReducing type (some numArgs)
-- TODO take coercions into account
-- We use `withReducible` to make sure we don't spend too much time unfolding definitions
-- Alternative: use default and small number of heartbeats
withReducible <| withoutModifyingState <| isDefEq type expectedType
catch _ =>
return false
private def sortCompletionItems (items : Array CompletionItem) : Array CompletionItem :=
items.qsort fun i1 i2 => i1.label < i2.label
private def mkCompletionItem (label : Name) (type : Expr) (docString? : Option String) : MetaM CompletionItem := do
let doc? := docString?.map fun docString => { value := docString, kind := MarkupKind.markdown : MarkupContent }
let detail ← consumeImplicitPrefix type fun type => return toString (← Meta.ppExpr type)
return { label := label.getString!, detail? := detail, documentation? := doc? }
structure State where
itemsMain : Array CompletionItem := #[]
itemsOther : Array CompletionItem := #[]
abbrev M := OptionT $ StateRefT State MetaM
private def addCompletionItem (label : Name) (type : Expr) (expectedType? : Option Expr) (declName? : Option Name) : M Unit := do
let docString? := if let some declName := declName? then findDocString? (← getEnv) declName else none
let item ← mkCompletionItem label type docString?
if (← isTypeApplicable type expectedType?) then
modify fun s => { s with itemsMain := s.itemsMain.push item }
else
modify fun s => { s with itemsOther := s.itemsOther.push item }
private def addCompletionItemForDecl (label : Name) (declName : Name) (expectedType? : Option Expr) : M Unit := do
if let some c ← (← getEnv).find? declName then
addCompletionItem label c.type expectedType? (some declName)
private def runM (ctx : ContextInfo) (lctx : LocalContext) (x : M Unit) : IO (Option CompletionList) :=
ctx.runMetaM lctx do
match (← x.run |>.run {}) with
| (none, _) => return none
| (some _, s) =>
return some { items := sortCompletionItems s.itemsMain ++ sortCompletionItems s.itemsOther, isIncomplete := true }
private def matchAtomic (id: Name) (declName : Name) : Bool :=
match id, declName with
| Name.str Name.anonymous s₁ _, Name.str Name.anonymous s₂ _ => s₁.isPrefixOf s₂
| _, _ => false
private def normPrivateName (declName : Name) : MetaM Name := do
match privateToUserName? declName with
| none => return declName
| some userName =>
if mkPrivateName (← getEnv) userName == declName then
return userName
else
return declName
/--
Return the auto-completion label if `id` can be auto completed using `declName` assuming namespace `ns` is open.
This function only succeeds with atomic labels. BTW, it seems most clients only use the last part.
Remark: `danglingDot == true` when the completion point is an identifier followed by `.`.
-/
private def matchDecl? (ns : Name) (id : Name) (danglingDot : Bool) (declName : Name) : MetaM (Option Name) := do
-- dbg_trace "{ns}, {id}, {declName}, {danglingDot}"
let declName ← normPrivateName declName
if !ns.isPrefixOf declName then
return none
else
let declName := declName.replacePrefix ns Name.anonymous
if id.isPrefixOf declName && danglingDot then
let declName := declName.replacePrefix id Name.anonymous
if declName.isAtomic && !declName.isAnonymous then
return some declName
else
return none
else if !danglingDot then
match id, declName with
| Name.str p₁ s₁ _, Name.str p₂ s₂ _ =>
if p₁ == p₂ && s₁.isPrefixOf s₂ then
return some s₂
else
return none
| _, _ => none
else
return none
private def idCompletionCore (ctx : ContextInfo) (id : Name) (danglingDot : Bool) (expectedType? : Option Expr) : M Unit := do
let id := id.eraseMacroScopes
-- dbg_trace ">> id {id} : {expectedType?}"
if id.isAtomic then
-- search for matches in the local context
for localDecl in (← getLCtx) do
if matchAtomic id localDecl.userName then
addCompletionItem localDecl.userName localDecl.type expectedType? none
-- search for matches in the environment
let env ← getEnv
env.constants.forM fun declName c => do
unless (← isBlackListed declName) do
let matchUsingNamespace (ns : Name): M Bool := do
if let some label ← matchDecl? ns id danglingDot declName then
-- dbg_trace "matched with {id}, {declName}, {label}"
addCompletionItem label c.type expectedType? declName
return true
else
return false
if (← matchUsingNamespace Name.anonymous) then
return ()
-- use current namespace
let rec visitNamespaces (ns : Name) : M Bool := do
match ns with
| Name.str p .. => matchUsingNamespace ns <||> visitNamespaces p
| _ => return false
if (← visitNamespaces ctx.currNamespace) then
return ()
-- use open decls
for openDecl in ctx.openDecls do
match openDecl with
| OpenDecl.simple ns exs =>
unless exs.contains declName do
if (← matchUsingNamespace ns) then
return ()
| _ => pure ()
-- search explicitily open `ids`
for openDecl in ctx.openDecls do
match openDecl with
| OpenDecl.explicit openedId resolvedId =>
unless (← isBlackListed resolvedId) do
if matchAtomic id openedId then
addCompletionItemForDecl openedId resolvedId expectedType?
| _ => pure ()
-- search for aliases
getAliasState env |>.forM fun alias declNames => do
if matchAtomic id alias then
declNames.forM fun declName => do
unless (← isBlackListed declName) do
addCompletionItemForDecl alias declName expectedType?
-- TODO search macros
-- TODO search namespaces
private def idCompletion (ctx : ContextInfo) (lctx : LocalContext) (id : Name) (danglingDot : Bool) (expectedType? : Option Expr) : IO (Option CompletionList) :=
runM ctx lctx do
idCompletionCore ctx id danglingDot expectedType?
private def isDotCompletionMethod (typeName : Name) (info : ConstantInfo) : MetaM Bool :=
forallTelescopeReducing info.type fun xs _ => do
for x in xs do
let localDecl ← getLocalDecl x.fvarId!
let type := localDecl.type.consumeMData
if type.getAppFn.isConstOf typeName then
return true
return false
/--
Given a type, try to extract relevant type names for dot notation field completion.
We extract the type name, parent struct names, and unfold the type.
The process mimics the dot notation elaboration procedure at `App.lean` -/
private partial def getDotCompletionTypeNames (type : Expr) : MetaM NameSet :=
return (← visit type |>.run {}).2
where
visit (type : Expr) : StateRefT NameSet MetaM Unit := do
match type.getAppFn with
| Expr.const typeName .. =>
modify fun s => s.insert typeName
if isStructure (← getEnv) typeName then
for parentName in getAllParentStructures (← getEnv) typeName do
modify fun s => s.insert parentName
let type? ← try unfoldDefinition? type catch _ => pure none
match type? with
| some type => visit type
| none => pure ()
| _ => pure ()
private def dotCompletion (ctx : ContextInfo) (info : TermInfo) (expectedType? : Option Expr) : IO (Option CompletionList) :=
runM ctx info.lctx do
let nameSet ←
try
getDotCompletionTypeNames (← instantiateMVars (← inferType info.expr))
catch _ =>
pure {}
if nameSet.isEmpty then
if info.stx.isIdent then
idCompletionCore ctx info.stx.getId (danglingDot := false) expectedType?
else if info.stx.getKind == ``Lean.Parser.Term.completion && info.stx[0].isIdent then
idCompletionCore ctx info.stx[0].getId (danglingDot := true) expectedType?
else
failure
else
(← getEnv).constants.forM fun declName c => do
let typeName := (← normPrivateName declName).getPrefix
if nameSet.contains typeName then
unless (← isBlackListed c.name) do
if (← isDotCompletionMethod typeName c) then
addCompletionItem c.name.getString! c.type expectedType? c.name
private def optionCompletion (ctx : ContextInfo) (stx : Syntax) : IO (Option CompletionList) :=
ctx.runMetaM {} do
let partialName := stx[1].getId
-- HACK(WN): unfold the type so ForIn works
let (decls : Std.RBMap _ _ _) ← getOptionDecls
let opts ← getOptions
let mut items := #[]
for ⟨name, decl⟩ in decls do
if partialName.isPrefixOf name ||
(match partialName, name with
| Name.str p₁ s₁ _, Name.str p₂ s₂ _ => p₁ == p₂ && s₁.isPrefixOf s₂
| _, _ => false) then
items := items.push
{ label := name.toString
detail? := s!"({opts.get name decl.defValue}), {decl.descr}"
documentation? := none }
return some { items := sortCompletionItems items, isIncomplete := true }
private def tacticCompletion (ctx : ContextInfo) : IO (Option CompletionList) :=
-- Just return the list of tactics for now.
ctx.runMetaM {} do
let table := Parser.getCategory (Parser.parserExtension.getState (← getEnv)).categories `tactic |>.get!.tables.leadingTable
let items : Array CompletionItem := table.fold (init := #[]) fun items tk parser =>
-- TODO pretty print tactic syntax
items.push { label := tk.toString, detail? := none, documentation? := none }
return some { items := sortCompletionItems items, isIncomplete := true }
partial def find? (fileMap : FileMap) (hoverPos : String.Pos) (infoTree : InfoTree) : IO (Option CompletionList) := do
let ⟨hoverLine, _⟩ := fileMap.toPosition hoverPos
match infoTree.foldInfo (init := none) (choose fileMap hoverLine) with
| some (ctx, Info.ofCompletionInfo info) =>
match info with
| CompletionInfo.dot info (expectedType? := expectedType?) .. => dotCompletion ctx info expectedType?
| CompletionInfo.id stx id danglingDot lctx expectedType? => idCompletion ctx lctx id danglingDot expectedType?
| CompletionInfo.option stx => optionCompletion ctx stx
| CompletionInfo.tactic .. => tacticCompletion ctx
| _ => return none
| _ =>
-- TODO try to extract id from `fileMap` and some `ContextInfo` from `InfoTree`
return none
where
choose (fileMap : FileMap) (hoverLine : Nat) (ctx : ContextInfo) (info : Info) (best? : Option (ContextInfo × Info)) : Option (ContextInfo × Info) :=
if !info.isCompletion then best?
else if let some d := info.occursBefore? hoverPos then
let pos := info.tailPos?.get!
let ⟨line, _⟩ := fileMap.toPosition pos
if line != hoverLine then best?
else match best? with
| none => return (ctx, info)
| some (_, best) =>
let dBest := best.occursBefore? hoverPos |>.get!
if d < dBest || (d == dBest && info.isSmaller best) then
return (ctx, info)
else
best?
else
best?
end Lean.Server.Completion
|
b7187d60e5fe025a8a4c9423dcc67193856599ff | 947b78d97130d56365ae2ec264df196ce769371a | /tests/lean/run/new_inductive2.lean | e08dec06cbec197975d87acca01346732090da37 | [
"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 | 356 | lean | new_frontend
universes u v
inductive arrow (α : Type u) (β : Type v)
| mk : (α → β) → arrow α β
inductive foo
| mk : arrow Nat foo → foo
#print foo
#print foo.rec
set_option pp.all true
#print foo.below
mutual
inductive foo2 : Type
| mk : arrow2 → foo2
inductive arrow2 : Type
| mk : (Nat → foo2) → arrow2
end
#print foo2.brecOn
|
676fdd0d45114d990f4df51a97f3993b0f18b7a2 | 4727251e0cd73359b15b664c3170e5d754078599 | /src/ring_theory/dedekind_domain/integral_closure.lean | a627b3548870dde63703d0baccb4b92c901c1959 | [
"Apache-2.0"
] | permissive | Vierkantor/mathlib | 0ea59ac32a3a43c93c44d70f441c4ee810ccceca | 83bc3b9ce9b13910b57bda6b56222495ebd31c2f | refs/heads/master | 1,658,323,012,449 | 1,652,256,003,000 | 1,652,256,003,000 | 209,296,341 | 0 | 1 | Apache-2.0 | 1,568,807,655,000 | 1,568,807,655,000 | null | UTF-8 | Lean | false | false | 9,944 | lean | /-
Copyright (c) 2020 Kenji Nakagawa. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio
-/
import ring_theory.dedekind_domain.basic
import ring_theory.trace
/-!
# Integral closure of Dedekind domains
This file shows the integral closure of a Dedekind domain (in particular, the ring of integers
of a number field) is a Dedekind domain.
## Implementation notes
The definitions that involve a field of fractions choose a canonical field of fractions,
but are independent of that choice. The `..._iff` lemmas express this independence.
Often, definitions assume that Dedekind domains are not fields. We found it more practical
to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed.
## References
* [D. Marcus, *Number Fields*][marcus1977number]
* [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic]
* [J. Neukirch, *Algebraic Number Theory*][Neukirch1992]
## Tags
dedekind domain, dedekind ring
-/
variables (R A K : Type*) [comm_ring R] [comm_ring A] [field K]
open_locale non_zero_divisors polynomial
variables [is_domain A]
section is_integral_closure
/-! ### `is_integral_closure` section
We show that an integral closure of a Dedekind domain in a finite separable
field extension is again a Dedekind domain. This implies the ring of integers
of a number field is a Dedekind domain. -/
open algebra
open_locale big_operators
variables {A K} [algebra A K] [is_fraction_ring A K]
variables {L : Type*} [field L] (C : Type*) [comm_ring C]
variables [algebra K L] [finite_dimensional K L] [algebra A L] [is_scalar_tower A K L]
variables [algebra C L] [is_integral_closure C A L] [algebra A C] [is_scalar_tower A C L]
lemma is_integral_closure.range_le_span_dual_basis [is_separable K L]
{ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L)
(hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] :
((algebra.linear_map C L).restrict_scalars A).range ≤
submodule.span A (set.range $ (trace_form K L).dual_basis (trace_form_nondegenerate K L) b) :=
begin
let db := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b,
rintros _ ⟨x, rfl⟩,
simp only [linear_map.coe_restrict_scalars_eq_coe, algebra.linear_map_apply],
have hx : is_integral A (algebra_map C L x) :=
(is_integral_closure.is_integral A L x).algebra_map,
suffices : ∃ (c : ι → A), algebra_map C L x = ∑ i, c i • db i,
{ obtain ⟨c, x_eq⟩ := this,
rw x_eq,
refine submodule.sum_mem _ (λ i _, submodule.smul_mem _ _ (submodule.subset_span _)),
rw set.mem_range,
exact ⟨i, rfl⟩ },
suffices : ∃ (c : ι → K), ((∀ i, is_integral A (c i)) ∧ algebra_map C L x = ∑ i, c i • db i),
{ obtain ⟨c, hc, hx⟩ := this,
have hc' : ∀ i, is_localization.is_integer A (c i) :=
λ i, is_integrally_closed.is_integral_iff.mp (hc i),
use λ i, classical.some (hc' i),
refine hx.trans (finset.sum_congr rfl (λ i _, _)),
conv_lhs { rw [← classical.some_spec (hc' i)] },
rw [← is_scalar_tower.algebra_map_smul K (classical.some (hc' i)) (db i)] },
refine ⟨λ i, db.repr (algebra_map C L x) i, (λ i, _), (db.sum_repr _).symm⟩,
rw bilin_form.dual_basis_repr_apply,
exact is_integral_trace (is_integral_mul hx (hb_int i))
end
lemma integral_closure_le_span_dual_basis [is_separable K L]
{ι : Type*} [fintype ι] [decidable_eq ι] (b : basis ι K L)
(hb_int : ∀ i, is_integral A (b i)) [is_integrally_closed A] :
(integral_closure A L).to_submodule ≤ submodule.span A (set.range $
(trace_form K L).dual_basis (trace_form_nondegenerate K L) b) :=
begin
refine le_trans _ (is_integral_closure.range_le_span_dual_basis (integral_closure A L) b hb_int),
intros x hx,
exact ⟨⟨x, hx⟩, rfl⟩
end
variables (A) (K)
include K
/-- Send a set of `x`'es in a finite extension `L` of the fraction field of `R`
to `(y : R) • x ∈ integral_closure R L`. -/
lemma exists_integral_multiples (s : finset L) :
∃ (y ≠ (0 : A)), ∀ x ∈ s, is_integral A (y • x) :=
begin
haveI := classical.dec_eq L,
refine s.induction _ _,
{ use [1, one_ne_zero],
rintros x ⟨⟩ },
{ rintros x s hx ⟨y, hy, hs⟩,
obtain ⟨x', y', hy', hx'⟩ := exists_integral_multiple
((is_fraction_ring.is_algebraic_iff A K L).mpr (is_algebraic_of_finite _ _ x))
((injective_iff_map_eq_zero (algebra_map A L)).mp _),
refine ⟨y * y', mul_ne_zero hy hy', λ x'' hx'', _⟩,
rcases finset.mem_insert.mp hx'' with (rfl | hx''),
{ rw [mul_smul, algebra.smul_def, algebra.smul_def, mul_comm _ x'', hx'],
exact is_integral_mul is_integral_algebra_map x'.2 },
{ rw [mul_comm, mul_smul, algebra.smul_def],
exact is_integral_mul is_integral_algebra_map (hs _ hx'') },
{ rw is_scalar_tower.algebra_map_eq A K L,
apply (algebra_map K L).injective.comp,
exact is_fraction_ring.injective _ _ } }
end
variables (L)
/-- If `L` is a finite extension of `K = Frac(A)`,
then `L` has a basis over `A` consisting of integral elements. -/
lemma finite_dimensional.exists_is_basis_integral :
∃ (s : finset L) (b : basis s K L), (∀ x, is_integral A (b x)) :=
begin
letI := classical.dec_eq L,
letI : is_noetherian K L := is_noetherian.iff_fg.2 infer_instance,
let s' := is_noetherian.finset_basis_index K L,
let bs' := is_noetherian.finset_basis K L,
obtain ⟨y, hy, his'⟩ := exists_integral_multiples A K (finset.univ.image bs'),
have hy' : algebra_map A L y ≠ 0,
{ refine mt ((injective_iff_map_eq_zero (algebra_map A L)).mp _ _) hy,
rw is_scalar_tower.algebra_map_eq A K L,
exact (algebra_map K L).injective.comp (is_fraction_ring.injective A K) },
refine ⟨s', bs'.map { to_fun := λ x, algebra_map A L y * x,
inv_fun := λ x, (algebra_map A L y)⁻¹ * x,
left_inv := _,
right_inv := _,
.. algebra.lmul _ _ (algebra_map A L y) },
_⟩,
{ intros x, simp only [inv_mul_cancel_left₀ hy'] },
{ intros x, simp only [mul_inv_cancel_left₀ hy'] },
{ rintros ⟨x', hx'⟩,
simp only [algebra.smul_def, finset.mem_image, exists_prop, finset.mem_univ, true_and] at his',
simp only [basis.map_apply, linear_equiv.coe_mk],
exact his' _ ⟨_, rfl⟩ }
end
variables (A K L) [is_separable K L]
include L
/- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is
integrally closed and Noetherian, the integral closure `C` of `A` in `L` is
Noetherian. -/
lemma is_integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] :
is_noetherian_ring C :=
begin
haveI := classical.dec_eq L,
obtain ⟨s, b, hb_int⟩ := finite_dimensional.exists_is_basis_integral A K L,
rw is_noetherian_ring_iff,
let b' := (trace_form K L).dual_basis (trace_form_nondegenerate K L) b,
letI := is_noetherian_span_of_finite A (set.finite_range b'),
let f : C →ₗ[A] submodule.span A (set.range b') :=
(submodule.of_le (is_integral_closure.range_le_span_dual_basis C b hb_int)).comp
((algebra.linear_map C L).restrict_scalars A).range_restrict,
refine is_noetherian_of_tower A (is_noetherian_of_ker_bot f _),
rw [linear_map.ker_comp, submodule.ker_of_le, submodule.comap_bot, linear_map.ker_cod_restrict],
exact linear_map.ker_eq_bot_of_injective (is_integral_closure.algebra_map_injective C A L)
end
variables {A K}
/- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is
integrally closed and Noetherian, the integral closure of `A` in `L` is
Noetherian. -/
lemma integral_closure.is_noetherian_ring [is_integrally_closed A] [is_noetherian_ring A] :
is_noetherian_ring (integral_closure A L) :=
is_integral_closure.is_noetherian_ring A K L (integral_closure A L)
variables (A K) [is_domain C]
/- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain,
the integral closure `C` of `A` in `L` is a Dedekind domain.
Can't be an instance since `A`, `K` or `L` can't be inferred. See also the instance
`integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A`
and `C := integral_closure A L`.
-/
lemma is_integral_closure.is_dedekind_domain [h : is_dedekind_domain A] :
is_dedekind_domain C :=
begin
haveI : is_fraction_ring C L := is_integral_closure.is_fraction_ring_of_finite_extension A K L C,
exact
⟨is_integral_closure.is_noetherian_ring A K L C,
h.dimension_le_one.is_integral_closure _ L _,
(is_integrally_closed_iff L).mpr (λ x hx, ⟨is_integral_closure.mk' C x
(is_integral_trans (is_integral_closure.is_integral_algebra A L) _ hx),
is_integral_closure.algebra_map_mk' _ _ _⟩)⟩
end
/- If `L` is a finite separable extension of `K = Frac(A)`, where `A` is a Dedekind domain,
the integral closure of `A` in `L` is a Dedekind domain.
Can't be an instance since `K` can't be inferred. See also the instance
`integral_closure.is_dedekind_domain_fraction_ring` where `K := fraction_ring A`.
-/
lemma integral_closure.is_dedekind_domain [h : is_dedekind_domain A] :
is_dedekind_domain (integral_closure A L) :=
is_integral_closure.is_dedekind_domain A K L (integral_closure A L)
omit K
variables [algebra (fraction_ring A) L] [is_scalar_tower A (fraction_ring A) L]
variables [finite_dimensional (fraction_ring A) L] [is_separable (fraction_ring A) L]
/- If `L` is a finite separable extension of `Frac(A)`, where `A` is a Dedekind domain,
the integral closure of `A` in `L` is a Dedekind domain.
See also the lemma `integral_closure.is_dedekind_domain` where you can choose
the field of fractions yourself.
-/
instance integral_closure.is_dedekind_domain_fraction_ring
[is_dedekind_domain A] : is_dedekind_domain (integral_closure A L) :=
integral_closure.is_dedekind_domain A (fraction_ring A) L
end is_integral_closure
|
0bd3be4406118dce3c34ec8068aa95da64810e36 | aa3f8992ef7806974bc1ffd468baa0c79f4d6643 | /tests/lean/run/class_bug2.lean | 2ef67428f7527870dbd41a80ae239754eb31565c | [
"Apache-2.0"
] | permissive | codyroux/lean | 7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3 | 0cca265db19f7296531e339192e9b9bae4a31f8b | refs/heads/master | 1,610,909,964,159 | 1,407,084,399,000 | 1,416,857,075,000 | null | 0 | 0 | null | null | null | null | UTF-8 | Lean | false | false | 840 | lean | import logic
inductive category (ob : Type) (mor : ob → ob → Type) : Type :=
mk : Π (comp : Π⦃A B C : ob⦄, mor B C → mor A B → mor A C)
(id : Π {A : ob}, mor A A),
(Π {A B C D : ob} {f : mor A B} {g : mor B C} {h : mor C D},
comp h (comp g f) = comp (comp h g) f) →
(Π {A B : ob} {f : mor A B}, comp f id = f) →
(Π {A B : ob} {f : mor A B}, comp id f = f) →
category ob mor
class category
namespace category
section sec_cat
variable A : Type
inductive foo :=
mk : A → foo
class foo
variables {ob : Type} {mor : ob → ob → Type} {Cat : category ob mor}
definition compose := rec (λ comp id assoc idr idl, comp) Cat
definition id := rec (λ comp id assoc idr idl, id) Cat
infixr `∘`:60 := compose
end sec_cat
end category
|
066f9c13cc0161343a9ecf9673cfefb76ccfa1e0 | 22e97a5d648fc451e25a06c668dc03ac7ed7bc25 | /src/set_theory/ordinal.lean | ed561302c3a69b50a487a964aa3ae0c3447744ec | [
"Apache-2.0"
] | permissive | keeferrowan/mathlib | f2818da875dbc7780830d09bd4c526b0764a4e50 | aad2dfc40e8e6a7e258287a7c1580318e865817e | refs/heads/master | 1,661,736,426,952 | 1,590,438,032,000 | 1,590,438,032,000 | 266,892,663 | 0 | 0 | Apache-2.0 | 1,590,445,835,000 | 1,590,445,835,000 | null | UTF-8 | Lean | false | false | 138,192 | lean | /-
Copyright (c) 2017 Johannes Hölzl. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Mario Carneiro
Ordinal arithmetic.
Ordinals are defined as equivalences of well-ordered sets by order isomorphism.
-/
import set_theory.cardinal
noncomputable theory
open function cardinal set equiv
open_locale classical cardinal
universes u v w
variables {α : Type*} {β : Type*} {γ : Type*}
{r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
/-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≼i s` is an order
embedding whose range is an initial segment. That is, whenever `b < f a` in `β` then `b` is in the
range of `f`. -/
structure initial_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ≼o s :=
(init : ∀ a b, s b (to_order_embedding a) → ∃ a', to_order_embedding a' = b)
local infix ` ≼i `:25 := initial_seg
namespace initial_seg
instance : has_coe (r ≼i s) (r ≼o s) := ⟨initial_seg.to_order_embedding⟩
instance : has_coe_to_fun (r ≼i s) := ⟨λ _, α → β, λ f x, (f : r ≼o s) x⟩
@[simp] theorem coe_fn_mk (f : r ≼o s) (o) :
(@initial_seg.mk _ _ r s f o : α → β) = f := rfl
@[simp] theorem coe_fn_to_order_embedding (f : r ≼i s) : (f.to_order_embedding : α → β) = f := rfl
@[simp] theorem coe_coe_fn (f : r ≼i s) : ((f : r ≼o s) : α → β) = f := rfl
theorem init' (f : r ≼i s) {a : α} {b : β} : s b (f a) → ∃ a', f a' = b :=
f.init _ _
theorem init_iff (f : r ≼i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a :=
⟨λ h, let ⟨a', e⟩ := f.init' h in ⟨a', e, (f : r ≼o s).ord.2 (e.symm ▸ h)⟩,
λ ⟨a', e, h⟩, e ▸ (f : r ≼o s).ord.1 h⟩
/-- An order isomorphism is an initial segment -/
def of_iso (f : r ≃o s) : r ≼i s :=
⟨f, λ a b h, ⟨f.symm b, order_iso.apply_symm_apply f _⟩⟩
/-- The identity function shows that `≼i` is reflexive -/
@[refl] protected def refl (r : α → α → Prop) : r ≼i r :=
⟨order_embedding.refl _, λ a b h, ⟨_, rfl⟩⟩
/-- Composition of functions shows that `≼i` is transitive -/
@[trans] protected def trans (f : r ≼i s) (g : s ≼i t) : r ≼i t :=
⟨f.1.trans g.1, λ a c h, begin
simp at h ⊢,
rcases g.2 _ _ h with ⟨b, rfl⟩, have h := g.1.ord.2 h,
rcases f.2 _ _ h with ⟨a', rfl⟩, exact ⟨a', rfl⟩
end⟩
@[simp] theorem refl_apply (x : α) : initial_seg.refl r x = x := rfl
@[simp] theorem trans_apply (f : r ≼i s) (g : s ≼i t) (a : α) : (f.trans g) a = g (f a) := rfl
theorem unique_of_extensional [is_extensional β s] :
well_founded r → subsingleton (r ≼i s) | ⟨h⟩ :=
⟨λ f g, begin
suffices : (f : α → β) = g, { cases f, cases g,
congr, exact order_embedding.coe_fn_injective this },
funext a, have := h a, induction this with a H IH,
refine @is_extensional.ext _ s _ _ _ (λ x, ⟨λ h, _, λ h, _⟩),
{ rcases f.init_iff.1 h with ⟨y, rfl, h'⟩,
rw IH _ h', exact (g : r ≼o s).ord.1 h' },
{ rcases g.init_iff.1 h with ⟨y, rfl, h'⟩,
rw ← IH _ h', exact (f : r ≼o s).ord.1 h' }
end⟩
instance [is_well_order β s] : subsingleton (r ≼i s) :=
⟨λ a, @subsingleton.elim _ (unique_of_extensional
(@order_embedding.well_founded _ _ r s a is_well_order.wf)) a⟩
protected theorem eq [is_well_order β s] (f g : r ≼i s) (a) : f a = g a :=
by rw subsingleton.elim f g
theorem antisymm.aux [is_well_order α r] (f : r ≼i s) (g : s ≼i r) : left_inverse g f :=
initial_seg.eq (f.trans g) (initial_seg.refl _)
/-- If we have order embeddings between `α` and `β` whose images are initial segments, and β is a well-order then `α` and `β` are order-isomorphic. -/
def antisymm [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : r ≃o s :=
by haveI := f.to_order_embedding.is_well_order; exact
⟨⟨f, g, antisymm.aux f g, antisymm.aux g f⟩, f.ord'⟩
@[simp] theorem antisymm_to_fun [is_well_order β s]
(f : r ≼i s) (g : s ≼i r) : (antisymm f g : α → β) = f := rfl
@[simp] theorem antisymm_symm [is_well_order α r] [is_well_order β s]
(f : r ≼i s) (g : s ≼i r) : (antisymm f g).symm = antisymm g f :=
order_iso.coe_fn_injective rfl
theorem eq_or_principal [is_well_order β s] (f : r ≼i s) : surjective f ∨ ∃ b, ∀ x, s x b ↔ ∃ y, f y = x :=
or_iff_not_imp_right.2 $ λ h b,
acc.rec_on (is_well_order.wf.apply b : acc s b) $ λ x H IH,
not_forall_not.1 $ λ hn,
h ⟨x, λ y, ⟨(IH _), λ ⟨a, e⟩, by rw ← e; exact
(trichotomous _ _).resolve_right
(not_or (hn a) (λ hl, not_exists.2 hn (f.init' hl)))⟩⟩
/-- Restrict the codomain of an initial segment -/
def cod_restrict (p : set β) (f : r ≼i s) (H : ∀ a, f a ∈ p) : r ≼i subrel s p :=
⟨order_embedding.cod_restrict p f H, λ a ⟨b, m⟩ (h : s b (f a)),
let ⟨a', e⟩ := f.init' h in ⟨a', by clear _let_match; subst e; refl⟩⟩
@[simp] theorem cod_restrict_apply (p) (f : r ≼i s) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl
def le_add (r : α → α → Prop) (s : β → β → Prop) : r ≼i sum.lex r s :=
⟨⟨⟨sum.inl, λ _ _, sum.inl.inj⟩, λ a b, sum.lex_inl_inl.symm⟩,
λ a b, by cases b; [exact λ _, ⟨_, rfl⟩, exact false.elim ∘ sum.lex_inr_inl]⟩
@[simp] theorem le_add_apply (r : α → α → Prop) (s : β → β → Prop)
(a) : le_add r s a = sum.inl a := rfl
end initial_seg
structure principal_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ≼o s :=
(top : β)
(down : ∀ b, s b top ↔ ∃ a, to_order_embedding a = b)
local infix ` ≺i `:25 := principal_seg
namespace principal_seg
instance : has_coe (r ≺i s) (r ≼o s) := ⟨principal_seg.to_order_embedding⟩
instance : has_coe_to_fun (r ≺i s) := ⟨λ _, α → β, λ f, f⟩
@[simp] theorem coe_fn_mk (f : r ≼o s) (t o) :
(@principal_seg.mk _ _ r s f t o : α → β) = f := rfl
@[simp] theorem coe_fn_to_order_embedding (f : r ≺i s) : (f.to_order_embedding : α → β) = f := rfl
@[simp] theorem coe_coe_fn (f : r ≺i s) : ((f : r ≼o s) : α → β) = f := rfl
theorem down' (f : r ≺i s) {b : β} : s b f.top ↔ ∃ a, f a = b :=
f.down _
theorem lt_top (f : r ≺i s) (a : α) : s (f a) f.top :=
f.down'.2 ⟨_, rfl⟩
theorem init [is_trans β s] (f : r ≺i s) {a : α} {b : β} (h : s b (f a)) : ∃ a', f a' = b :=
f.down'.1 $ trans h $ f.lt_top _
instance has_coe_initial_seg [is_trans β s] : has_coe (r ≺i s) (r ≼i s) :=
⟨λ f, ⟨f.to_order_embedding, λ a b, f.init⟩⟩
theorem coe_coe_fn' [is_trans β s] (f : r ≺i s) : ((f : r ≼i s) : α → β) = f := rfl
theorem init_iff [is_trans β s] (f : r ≺i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a :=
@initial_seg.init_iff α β r s f a b
theorem irrefl (r : α → α → Prop) [is_well_order α r] (f : r ≺i r) : false :=
begin
have := f.lt_top f.top,
rw [show f f.top = f.top, from
initial_seg.eq ↑f (initial_seg.refl r) f.top] at this,
exact irrefl _ this
end
def lt_le (f : r ≺i s) (g : s ≼i t) : r ≺i t :=
⟨@order_embedding.trans _ _ _ r s t f g, g f.top, λ a,
by simp only [g.init_iff, f.down', exists_and_distrib_left.symm,
exists_swap, order_embedding.trans_apply, exists_eq_right']; refl⟩
@[simp] theorem lt_le_apply (f : r ≺i s) (g : s ≼i t) (a : α) : (f.lt_le g) a = g (f a) :=
order_embedding.trans_apply _ _ _
@[simp] theorem lt_le_top (f : r ≺i s) (g : s ≼i t) : (f.lt_le g).top = g f.top := rfl
@[trans] protected def trans [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : r ≺i t :=
lt_le f g
@[simp] theorem trans_apply [is_trans γ t] (f : r ≺i s) (g : s ≺i t) (a : α) : (f.trans g) a = g (f a) :=
lt_le_apply _ _ _
@[simp] theorem trans_top [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : (f.trans g).top = g f.top := rfl
def equiv_lt (f : r ≃o s) (g : s ≺i t) : r ≺i t :=
⟨@order_embedding.trans _ _ _ r s t f g, g.top, λ c,
suffices (∃ (a : β), g a = c) ↔ ∃ (a : α), g (f a) = c, by simpa [g.down],
⟨λ ⟨b, h⟩, ⟨f.symm b, by simp only [h, order_iso.apply_symm_apply, order_iso.coe_coe_fn]⟩,
λ ⟨a, h⟩, ⟨f a, h⟩⟩⟩
def lt_equiv {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
(f : principal_seg r s) (g : s ≃o t) : principal_seg r t :=
⟨@order_embedding.trans _ _ _ r s t f g, g f.top,
begin
intro x,
rw [← g.right_inv x, order_iso.to_equiv_to_fun, ← g.ord, f.down', exists_congr],
intro y, exact ⟨congr_arg g, λ h, g.to_equiv.bijective.1 h⟩
end⟩
@[simp] theorem equiv_lt_apply (f : r ≃o s) (g : s ≺i t) (a : α) : (equiv_lt f g) a = g (f a) :=
order_embedding.trans_apply _ _ _
@[simp] theorem equiv_lt_top (f : r ≃o s) (g : s ≺i t) : (equiv_lt f g).top = g.top := rfl
instance [is_well_order β s] : subsingleton (r ≺i s) :=
⟨λ f g, begin
have ef : (f : α → β) = g,
{ show ((f : r ≼i s) : α → β) = g,
rw @subsingleton.elim _ _ (f : r ≼i s) g, refl },
have et : f.top = g.top,
{ refine @is_extensional.ext _ s _ _ _ (λ x, _),
simp only [f.down, g.down, ef, coe_fn_to_order_embedding] },
cases f, cases g,
have := order_embedding.coe_fn_injective ef; congr'
end⟩
theorem top_eq [is_well_order γ t]
(e : r ≃o s) (f : r ≺i t) (g : s ≺i t) : f.top = g.top :=
by rw subsingleton.elim f (principal_seg.equiv_lt e g); refl
lemma top_lt_top {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop}
[is_well_order γ t]
(f : principal_seg r s) (g : principal_seg s t) (h : principal_seg r t) : t h.top g.top :=
by { rw [subsingleton.elim h (f.trans g)], apply principal_seg.lt_top }
/-- Any element of a well order yields a principal segment -/
def of_element {α : Type*} (r : α → α → Prop) (a : α) : subrel r {b | r b a} ≺i r :=
⟨subrel.order_embedding _ _, a, λ b,
⟨λ h, ⟨⟨_, h⟩, rfl⟩, λ ⟨⟨_, h⟩, rfl⟩, h⟩⟩
@[simp] theorem of_element_apply {α : Type*} (r : α → α → Prop) (a : α) (b) :
of_element r a b = b.1 := rfl
@[simp] theorem of_element_top {α : Type*} (r : α → α → Prop) (a : α) :
(of_element r a).top = a := rfl
/-- Restrict the codomain of a principal segment -/
def cod_restrict (p : set β) (f : r ≺i s)
(H : ∀ a, f a ∈ p) (H₂ : f.top ∈ p) : r ≺i subrel s p :=
⟨order_embedding.cod_restrict p f H, ⟨f.top, H₂⟩, λ ⟨b, h⟩,
f.down'.trans $ exists_congr $ λ a,
show (⟨f a, H a⟩ : p).1 = _ ↔ _, from ⟨subtype.eq, congr_arg _⟩⟩
@[simp] theorem cod_restrict_apply (p) (f : r ≺i s) (H H₂ a) : cod_restrict p f H H₂ a = ⟨f a, H a⟩ := rfl
@[simp] theorem cod_restrict_top (p) (f : r ≺i s) (H H₂) : (cod_restrict p f H H₂).top = ⟨f.top, H₂⟩ := rfl
end principal_seg
def initial_seg.lt_or_eq [is_well_order β s] (f : r ≼i s) :
(r ≺i s) ⊕ (r ≃o s) :=
if h : surjective f then sum.inr (order_iso.of_surjective f h) else
have h' : _, from (initial_seg.eq_or_principal f).resolve_left h,
sum.inl ⟨f, classical.some h', classical.some_spec h'⟩
theorem initial_seg.lt_or_eq_apply_left [is_well_order β s]
(f : r ≼i s) (g : r ≺i s) (a : α) : g a = f a :=
@initial_seg.eq α β r s _ g f a
theorem initial_seg.lt_or_eq_apply_right [is_well_order β s]
(f : r ≼i s) (g : r ≃o s) (a : α) : g a = f a :=
initial_seg.eq (initial_seg.of_iso g) f a
def initial_seg.le_lt [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) : r ≺i t :=
match f.lt_or_eq with
| sum.inl f' := f'.trans g
| sum.inr f' := principal_seg.equiv_lt f' g
end
@[simp] theorem initial_seg.le_lt_apply [is_well_order β s] [is_trans γ t]
(f : r ≼i s) (g : s ≺i t) (a : α) : (f.le_lt g) a = g (f a) :=
begin
delta initial_seg.le_lt, cases h : f.lt_or_eq with f' f',
{ simp only [principal_seg.trans_apply, f.lt_or_eq_apply_left] },
{ simp only [principal_seg.equiv_lt_apply, f.lt_or_eq_apply_right] }
end
namespace order_embedding
def collapse_F [is_well_order β s] (f : r ≼o s) : Π a, {b // ¬ s (f a) b} :=
(order_embedding.well_founded f $ is_well_order.wf).fix $ λ a IH, begin
let S := {b | ∀ a h, s (IH a h).1 b},
have : f a ∈ S, from λ a' h, ((trichotomous _ _)
.resolve_left $ λ h', (IH a' h).2 $ trans (f.ord.1 h) h')
.resolve_left $ λ h', (IH a' h).2 $ h' ▸ f.ord.1 h,
exact ⟨is_well_order.wf.min S ⟨_, this⟩,
is_well_order.wf.not_lt_min _ _ this⟩
end
theorem collapse_F.lt [is_well_order β s] (f : r ≼o s) {a : α}
: ∀ {a'}, r a' a → s (collapse_F f a').1 (collapse_F f a).1 :=
show (collapse_F f a).1 ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, begin
unfold collapse_F, rw well_founded.fix_eq,
apply well_founded.min_mem _ _
end
theorem collapse_F.not_lt [is_well_order β s] (f : r ≼o s) (a : α)
{b} (h : ∀ a' (h : r a' a), s (collapse_F f a').1 b) : ¬ s b (collapse_F f a).1 :=
begin
unfold collapse_F, rw well_founded.fix_eq,
exact well_founded.not_lt_min _ _ _
(show b ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, from h)
end
/-- Construct an initial segment from an order embedding. -/
def collapse [is_well_order β s] (f : r ≼o s) : r ≼i s :=
by haveI := order_embedding.is_well_order f; exact
⟨order_embedding.of_monotone
(λ a, (collapse_F f a).1) (λ a b, collapse_F.lt f),
λ a b, acc.rec_on (is_well_order.wf.apply b : acc s b) (λ b H IH a h, begin
let S := {a | ¬ s (collapse_F f a).1 b},
have : S.nonempty := ⟨_, asymm h⟩,
existsi (is_well_order.wf : well_founded r).min S this,
refine ((@trichotomous _ s _ _ _).resolve_left _).resolve_right _,
{ exact (is_well_order.wf : well_founded r).min_mem S this },
{ refine collapse_F.not_lt f _ (λ a' h', _),
by_contradiction hn,
exact is_well_order.wf.not_lt_min S this hn h' }
end) a⟩
theorem collapse_apply [is_well_order β s] (f : r ≼o s)
(a) : collapse f a = (collapse_F f a).1 := rfl
end order_embedding
section well_ordering_thm
parameter {σ : Type u}
open function
theorem nonempty_embedding_to_cardinal : nonempty (σ ↪ cardinal.{u}) :=
embedding.total.resolve_left $ λ ⟨⟨f, hf⟩⟩,
let g : σ → cardinal.{u} := inv_fun f in
let ⟨x, (hx : g x = 2 ^ sum g)⟩ := inv_fun_surjective hf (2 ^ sum g) in
have g x ≤ sum g, from le_sum.{u u} g x,
not_le_of_gt (by rw hx; exact cantor _) this
/-- An embedding of any type to the set of cardinals. -/
def embedding_to_cardinal : σ ↪ cardinal.{u} := classical.choice nonempty_embedding_to_cardinal
/-- The relation whose existence is given by the well-ordering theorem -/
def well_ordering_rel : σ → σ → Prop := embedding_to_cardinal ⁻¹'o (<)
instance well_ordering_rel.is_well_order : is_well_order σ well_ordering_rel :=
(order_embedding.preimage _ _).is_well_order
end well_ordering_thm
structure Well_order : Type (u+1) :=
(α : Type u)
(r : α → α → Prop)
(wo : is_well_order α r)
attribute [instance] Well_order.wo
namespace Well_order
instance : inhabited Well_order := ⟨⟨pempty, _, empty_relation.is_well_order⟩⟩
end Well_order
instance ordinal.is_equivalent : setoid Well_order :=
{ r := λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≃o s),
iseqv := ⟨λ⟨α, r, _⟩, ⟨order_iso.refl _⟩,
λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, ⟨e.symm⟩,
λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ }
/-- `ordinal.{u}` is the type of well orders in `Type u`,
quotient by order isomorphism. -/
def ordinal : Type (u + 1) := quotient ordinal.is_equivalent
namespace ordinal
/-- The order type of a well order is an ordinal. -/
def type (r : α → α → Prop) [wo : is_well_order α r] : ordinal :=
⟦⟨α, r, wo⟩⟧
/-- The order type of an element inside a well order. -/
def typein (r : α → α → Prop) [is_well_order α r] (a : α) : ordinal :=
type (subrel r {b | r b a})
theorem type_def (r : α → α → Prop) [wo : is_well_order α r] :
@eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl
@[simp] theorem type_def' (r : α → α → Prop) [is_well_order α r] {wo} :
@eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl
theorem type_eq {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] :
type r = type s ↔ nonempty (r ≃o s) := quotient.eq
@[simp] lemma type_out (o : ordinal) : type o.out.r = o :=
by { refine eq.trans _ (by rw [←quotient.out_eq o]), cases quotient.out o, refl }
@[elab_as_eliminator] theorem induction_on {C : ordinal → Prop}
(o : ordinal) (H : ∀ α r [is_well_order α r], C (type r)) : C o :=
quot.induction_on o $ λ ⟨α, r, wo⟩, @H α r wo
/-- Ordinal less-equal is defined such that
well orders `r` and `s` satisfy `type r ≤ type s` if there exists
a function embedding `r` as an initial segment of `s`. -/
protected def le (a b : ordinal) : Prop :=
quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≼i s)) $
λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩,
propext ⟨
λ ⟨h⟩, ⟨(initial_seg.of_iso f.symm).trans $
h.trans (initial_seg.of_iso g)⟩,
λ ⟨h⟩, ⟨(initial_seg.of_iso f).trans $
h.trans (initial_seg.of_iso g.symm)⟩⟩
instance : has_le ordinal := ⟨ordinal.le⟩
theorem type_le {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] :
type r ≤ type s ↔ nonempty (r ≼i s) := iff.rfl
theorem type_le' {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ≼o s) :=
⟨λ ⟨f⟩, ⟨f⟩, λ ⟨f⟩, ⟨f.collapse⟩⟩
/-- Ordinal less-than is defined such that
well orders `r` and `s` satisfy `type r < type s` if there exists
a function embedding `r` as a principal segment of `s`. -/
def lt (a b : ordinal) : Prop :=
quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≺i s)) $
λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩,
by exactI propext ⟨
λ ⟨h⟩, ⟨principal_seg.equiv_lt f.symm $
h.lt_le (initial_seg.of_iso g)⟩,
λ ⟨h⟩, ⟨principal_seg.equiv_lt f $
h.lt_le (initial_seg.of_iso g.symm)⟩⟩
instance : has_lt ordinal := ⟨ordinal.lt⟩
@[simp] theorem type_lt {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] :
type r < type s ↔ nonempty (r ≺i s) := iff.rfl
instance : partial_order ordinal :=
{ le := (≤),
lt := (<),
le_refl := quot.ind $ by exact λ ⟨α, r, wo⟩, ⟨initial_seg.refl _⟩,
le_trans := λ a b c, quotient.induction_on₃ a b c $
λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ ⟨g⟩, ⟨f.trans g⟩,
lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $
λ ⟨α, r, _⟩ ⟨β, s, _⟩, by exactI
⟨λ ⟨f⟩, ⟨⟨f⟩, λ ⟨g⟩, (f.lt_le g).irrefl _⟩,
λ ⟨⟨f⟩, h⟩, sum.rec_on f.lt_or_eq (λ g, ⟨g⟩)
(λ g, (h ⟨initial_seg.of_iso g.symm⟩).elim)⟩,
le_antisymm := λ x b, show x ≤ b → b ≤ x → x = b, from
quotient.induction_on₂ x b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨h₁⟩ ⟨h₂⟩,
by exactI quot.sound ⟨initial_seg.antisymm h₁ h₂⟩ }
def initial_seg_out {α β : ordinal} (h : α ≤ β) : initial_seg α.out.r β.out.r :=
begin
rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h,
cases quotient.out α, cases quotient.out β, exact classical.choice
end
def principal_seg_out {α β : ordinal} (h : α < β) : principal_seg α.out.r β.out.r :=
begin
rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h,
cases quotient.out α, cases quotient.out β, exact classical.choice
end
def order_iso_out {α β : ordinal} (h : α = β) : order_iso α.out.r β.out.r :=
begin
rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h,
cases quotient.out α, cases quotient.out β, exact classical.choice ∘ quotient.exact
end
theorem typein_lt_type (r : α → α → Prop) [is_well_order α r]
(a : α) : typein r a < type r :=
⟨principal_seg.of_element _ _⟩
@[simp] theorem typein_top {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] (f : r ≺i s) :
typein s f.top = type r :=
eq.symm $ quot.sound ⟨order_iso.of_surjective
(order_embedding.cod_restrict _ f f.lt_top)
(λ ⟨a, h⟩, by rcases f.down'.1 h with ⟨b, rfl⟩; exact ⟨b, rfl⟩)⟩
@[simp] theorem typein_apply {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] (f : r ≼i s) (a : α) :
ordinal.typein s (f a) = ordinal.typein r a :=
eq.symm $ quotient.sound ⟨order_iso.of_surjective
(order_embedding.cod_restrict _
((subrel.order_embedding _ _).trans f)
(λ ⟨x, h⟩, by rw [order_embedding.trans_apply]; exact f.to_order_embedding.ord.1 h))
(λ ⟨y, h⟩, by rcases f.init' h with ⟨a, rfl⟩;
exact ⟨⟨a, f.to_order_embedding.ord.2 h⟩, subtype.eq $ order_embedding.trans_apply _ _ _⟩)⟩
@[simp] theorem typein_lt_typein (r : α → α → Prop) [is_well_order α r]
{a b : α} : typein r a < typein r b ↔ r a b :=
⟨λ ⟨f⟩, begin
have : f.top.1 = a,
{ let f' := principal_seg.of_element r a,
let g' := f.trans (principal_seg.of_element r b),
have : g'.top = f'.top, {rw subsingleton.elim f' g'},
exact this },
rw ← this, exact f.top.2
end, λ h, ⟨principal_seg.cod_restrict _
(principal_seg.of_element r a)
(λ x, @trans _ r _ _ _ _ x.2 h) h⟩⟩
theorem typein_surj (r : α → α → Prop) [is_well_order α r]
{o} (h : o < type r) : ∃ a, typein r a = o :=
induction_on o (λ β s _ ⟨f⟩, by exactI ⟨f.top, typein_top _⟩) h
lemma injective_typein (r : α → α → Prop) [is_well_order α r] : injective (typein r) :=
injective_of_increasing r (<) (typein r) (λ x y, (typein_lt_typein r).2)
theorem typein_inj (r : α → α → Prop) [is_well_order α r]
{a b} : typein r a = typein r b ↔ a = b :=
injective.eq_iff (injective_typein r)
/-- `enum r o h` is the `o`-th element of `α` ordered by `r`.
That is, `enum` maps an initial segment of the ordinals, those
less than the order type of `r`, to the elements of `α`. -/
def enum (r : α → α → Prop) [is_well_order α r] (o) : o < type r → α :=
quot.rec_on o (λ ⟨β, s, _⟩ h, (classical.choice h).top) $
λ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨h⟩, begin
resetI, refine funext (λ (H₂ : type t < type r), _),
have H₁ : type s < type r, {rwa type_eq.2 ⟨h⟩},
have : ∀ {o e} (H : o < type r), @@eq.rec
(λ (o : ordinal), o < type r → α)
(λ (h : type s < type r), (classical.choice h).top)
e H = (classical.choice H₁).top, {intros, subst e},
exact (this H₂).trans (principal_seg.top_eq h
(classical.choice H₁) (classical.choice H₂))
end
theorem enum_type {α β} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s] (f : s ≺i r)
{h : type s < type r} : enum r (type s) h = f.top :=
principal_seg.top_eq (order_iso.refl _) _ _
@[simp] theorem enum_typein (r : α → α → Prop) [is_well_order α r] (a : α)
{h : typein r a < type r} : enum r (typein r a) h = a :=
enum_type (principal_seg.of_element r a)
@[simp] theorem typein_enum (r : α → α → Prop) [is_well_order α r]
{o} (h : o < type r) : typein r (enum r o h) = o :=
let ⟨a, e⟩ := typein_surj r h in
by clear _let_match; subst e; rw enum_typein
def typein_iso (r : α → α → Prop) [is_well_order α r] : r ≃o subrel (<) (< type r) :=
⟨⟨λ x, ⟨typein r x, typein_lt_type r x⟩, λ x, enum r x.1 x.2, λ y, enum_typein r y,
λ ⟨y, hy⟩, subtype.eq (typein_enum r hy)⟩,
λ a b, (typein_lt_typein r).symm⟩
theorem enum_lt {r : α → α → Prop} [is_well_order α r]
{o₁ o₂ : ordinal} (h₁ : o₁ < type r) (h₂ : o₂ < type r) :
r (enum r o₁ h₁) (enum r o₂ h₂) ↔ o₁ < o₂ :=
by rw [← typein_lt_typein r, typein_enum, typein_enum]
lemma order_iso_enum' {α β : Type u} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s]
(f : order_iso r s) (o : ordinal) : ∀(hr : o < type r) (hs : o < type s),
f (enum r o hr) = enum s o hs :=
begin
refine induction_on o _, rintros γ t wo ⟨g⟩ ⟨h⟩,
resetI, rw [enum_type g, enum_type (principal_seg.lt_equiv g f)], refl
end
lemma order_iso_enum {α β : Type u} {r : α → α → Prop} {s : β → β → Prop}
[is_well_order α r] [is_well_order β s]
(f : order_iso r s) (o : ordinal) (hr : o < type r) :
f (enum r o hr) =
enum s o (by {convert hr using 1, apply quotient.sound, exact ⟨f.symm⟩ }) :=
order_iso_enum' _ _ _ _
theorem wf : @well_founded ordinal (<) :=
⟨λ a, induction_on a $ λ α r wo, by exactI
suffices ∀ a, acc (<) (typein r a), from
⟨_, λ o h, let ⟨a, e⟩ := typein_surj r h in e ▸ this a⟩,
λ a, acc.rec_on (wo.wf.apply a) $ λ x H IH, ⟨_, λ o h, begin
rcases typein_surj r (lt_trans h (typein_lt_type r _)) with ⟨b, rfl⟩,
exact IH _ ((typein_lt_typein r).1 h)
end⟩⟩
instance : has_well_founded ordinal := ⟨(<), wf⟩
/-- The cardinal of an ordinal is the cardinal of any
set with that order type. -/
def card (o : ordinal) : cardinal :=
quot.lift_on o (λ ⟨α, r, _⟩, mk α) $
λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, quotient.sound ⟨e.to_equiv⟩
@[simp] theorem card_type (r : α → α → Prop) [is_well_order α r] :
card (type r) = mk α := rfl
lemma card_typein {r : α → α → Prop} [wo : is_well_order α r] (x : α) :
mk {y // r y x} = (typein r x).card := rfl
theorem card_le_card {o₁ o₂ : ordinal} : o₁ ≤ o₂ → card o₁ ≤ card o₂ :=
induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _ ⟨⟨⟨f, _⟩, _⟩⟩, ⟨f⟩
instance : has_zero ordinal :=
⟨⟦⟨pempty, empty_relation, by apply_instance⟩⟧⟩
instance : inhabited ordinal := ⟨0⟩
theorem zero_eq_type_empty : 0 = @type empty empty_relation _ :=
quotient.sound ⟨⟨empty_equiv_pempty.symm, λ _ _, iff.rfl⟩⟩
@[simp] theorem card_zero : card 0 = 0 := rfl
theorem zero_le (o : ordinal) : 0 ≤ o :=
induction_on o $ λ α r _,
⟨⟨⟨embedding.of_not_nonempty $ λ ⟨a⟩, a.elim,
λ a, a.elim⟩, λ a, a.elim⟩⟩
@[simp] theorem le_zero {o : ordinal} : o ≤ 0 ↔ o = 0 :=
by simp only [le_antisymm_iff, zero_le, and_true]
theorem pos_iff_ne_zero {o : ordinal} : 0 < o ↔ o ≠ 0 :=
by simp only [lt_iff_le_and_ne, zero_le, true_and, ne.def, eq_comm]
instance : has_one ordinal :=
⟨⟦⟨punit, empty_relation, by apply_instance⟩⟧⟩
theorem one_eq_type_unit : 1 = @type unit empty_relation _ :=
quotient.sound ⟨⟨punit_equiv_punit, λ _ _, iff.rfl⟩⟩
@[simp] theorem card_one : card 1 = 1 := rfl
instance : has_add ordinal.{u} :=
⟨λo₁ o₂, quotient.lift_on₂ o₁ o₂
(λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨α ⊕ β, sum.lex r s, by exactI sum.lex.is_well_order⟩⟧
: Well_order → Well_order → ordinal) $
λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩,
quot.sound ⟨order_iso.sum_lex_congr f g⟩⟩
@[simp] theorem type_add {α β : Type u} (r : α → α → Prop) (s : β → β → Prop)
[is_well_order α r] [is_well_order β s] : type r + type s = type (sum.lex r s) := rfl
/-- The ordinal successor is the smallest ordinal larger than `o`.
It is defined as `o + 1`. -/
def succ (o : ordinal) : ordinal := o + 1
theorem succ_eq_add_one (o) : succ o = o + 1 := rfl
theorem lt_succ_self (o : ordinal.{u}) : o < succ o :=
induction_on o $ λ α r _, ⟨⟨⟨⟨λ x, sum.inl x, λ _ _, sum.inl.inj⟩,
λ _ _, sum.lex_inl_inl.symm⟩,
sum.inr punit.star, λ b, sum.rec_on b
(λ x, ⟨λ _, ⟨x, rfl⟩, λ _, sum.lex.sep _ _⟩)
(λ x, sum.lex_inr_inr.trans ⟨false.elim, λ ⟨x, H⟩, sum.inl_ne_inr H⟩)⟩⟩
theorem succ_pos (o : ordinal) : 0 < succ o :=
lt_of_le_of_lt (zero_le _) (lt_succ_self _)
theorem succ_ne_zero (o : ordinal) : succ o ≠ 0 :=
ne_of_gt $ succ_pos o
theorem succ_le {a b : ordinal} : succ a ≤ b ↔ a < b :=
⟨lt_of_lt_of_le (lt_succ_self _),
induction_on a $ λ α r hr, induction_on b $ λ β s hs ⟨⟨f, t, hf⟩⟩, begin
refine ⟨⟨@order_embedding.of_monotone (α ⊕ punit) β _ _
(@sum.lex.is_well_order _ _ _ _ hr _).1.1
(@is_asymm_of_is_trans_of_is_irrefl _ _ hs.1.2.2 hs.1.2.1)
(sum.rec _ _) (λ a b, _), λ a b, _⟩⟩,
{ exact f }, { exact λ _, t },
{ rcases a with a|_; rcases b with b|_,
{ simpa only [sum.lex_inl_inl] using f.ord.1 },
{ intro _, rw hf, exact ⟨_, rfl⟩ },
{ exact false.elim ∘ sum.lex_inr_inl },
{ exact false.elim ∘ sum.lex_inr_inr.1 } },
{ rcases a with a|_,
{ intro h, have := @principal_seg.init _ _ _ _ hs.1.2.2 ⟨f, t, hf⟩ _ _ h,
cases this with w h, exact ⟨sum.inl w, h⟩ },
{ intro h, cases (hf b).1 h with w h, exact ⟨sum.inl w, h⟩ } }
end⟩
@[simp] theorem card_add (o₁ o₂ : ordinal) : card (o₁ + o₂) = card o₁ + card o₂ :=
induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _, rfl
@[simp] theorem card_succ (o : ordinal) : card (succ o) = card o + 1 :=
by simp only [succ, card_add, card_one]
@[simp] theorem card_nat (n : ℕ) : card.{u} n = n :=
by induction n; [refl, simp only [card_add, card_one, nat.cast_succ, *]]
theorem nat_cast_succ (n : ℕ) : (succ n : ordinal) = n.succ := rfl
instance : add_monoid ordinal.{u} :=
{ add := (+),
zero := 0,
zero_add := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound
⟨⟨(pempty_sum α).symm, λ a b, sum.lex_inr_inr.symm⟩⟩,
add_zero := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound
⟨⟨(sum_pempty α).symm, λ a b, sum.lex_inl_inl.symm⟩⟩,
add_assoc := λ o₁ o₂ o₃, quotient.induction_on₃ o₁ o₂ o₃ $
λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quot.sound
⟨⟨sum_assoc _ _ _, λ a b,
begin rcases a with ⟨a|a⟩|a; rcases b with ⟨b|b⟩|b;
simp only [sum_assoc_apply_in1, sum_assoc_apply_in2, sum_assoc_apply_in3,
sum.lex_inl_inl, sum.lex_inr_inr, sum.lex.sep, sum.lex_inr_inl] end⟩⟩ }
theorem add_succ (o₁ o₂ : ordinal) : o₁ + succ o₂ = succ (o₁ + o₂) :=
(add_assoc _ _ _).symm
@[simp] theorem succ_zero : succ 0 = 1 := zero_add _
theorem one_le_iff_pos {o : ordinal} : 1 ≤ o ↔ 0 < o :=
by rw [← succ_zero, succ_le]
theorem one_le_iff_ne_zero {o : ordinal} : 1 ≤ o ↔ o ≠ 0 :=
by rw [one_le_iff_pos, pos_iff_ne_zero]
theorem add_le_add_left {a b : ordinal} : a ≤ b → ∀ c, c + a ≤ c + b :=
induction_on a $ λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨⟨⟨f, fo⟩, fi⟩⟩ c,
induction_on c $ λ β s _,
⟨⟨⟨(embedding.refl _).sum_congr f,
λ a b, match a, b with
| sum.inl a, sum.inl b := sum.lex_inl_inl.trans sum.lex_inl_inl.symm
| sum.inl a, sum.inr b := by apply iff_of_true; apply sum.lex.sep
| sum.inr a, sum.inl b := by apply iff_of_false; exact sum.lex_inr_inl
| sum.inr a, sum.inr b := sum.lex_inr_inr.trans $ fo.trans sum.lex_inr_inr.symm
end⟩,
λ a b H, match a, b, H with
| _, sum.inl b, _ := ⟨sum.inl b, rfl⟩
| sum.inl a, sum.inr b, H := (sum.lex_inr_inl H).elim
| sum.inr a, sum.inr b, H := let ⟨w, h⟩ := fi _ _ (sum.lex_inr_inr.1 H) in
⟨sum.inr w, congr_arg sum.inr h⟩
end⟩⟩
theorem le_add_right (a b : ordinal) : a ≤ a + b :=
by simpa only [add_zero] using add_le_add_left (zero_le b) a
theorem add_le_add_iff_left (a) {b c : ordinal} : a + b ≤ a + c ↔ b ≤ c :=
⟨induction_on a $ λ α r hr, induction_on b $ λ β₁ s₁ hs₁, induction_on c $ λ β₂ s₂ hs₂ ⟨f⟩, ⟨
have fl : ∀ a, f (sum.inl a) = sum.inl a := λ a,
by simpa only [initial_seg.trans_apply, initial_seg.le_add_apply]
using @initial_seg.eq _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr hs₂)
((initial_seg.le_add r s₁).trans f) (initial_seg.le_add r s₂) a,
have ∀ b, {b' // f (sum.inr b) = sum.inr b'}, begin
intro b, cases e : f (sum.inr b),
{ rw ← fl at e, have := f.inj' e, contradiction },
{ exact ⟨_, rfl⟩ }
end,
let g (b) := (this b).1 in
have fr : ∀ b, f (sum.inr b) = sum.inr (g b), from λ b, (this b).2,
⟨⟨⟨g, λ x y h, by injection f.inj'
(by rw [fr, fr, h] : f (sum.inr x) = f (sum.inr y))⟩,
λ a b, by simpa only [sum.lex_inr_inr, fr, order_embedding.coe_fn_to_embedding,
initial_seg.coe_fn_to_order_embedding, function.embedding.coe_fn_mk]
using @order_embedding.ord _ _ _ _ f.to_order_embedding (sum.inr a) (sum.inr b)⟩,
λ a b H, begin
rcases f.init' (by rw fr; exact sum.lex_inr_inr.2 H) with ⟨a'|a', h⟩,
{ rw fl at h, cases h },
{ rw fr at h, exact ⟨a', sum.inr.inj h⟩ }
end⟩⟩,
λ h, add_le_add_left h _⟩
theorem add_left_cancel (a) {b c : ordinal} : a + b = a + c ↔ b = c :=
by simp only [le_antisymm_iff, add_le_add_iff_left]
/-- The universe lift operation for ordinals, which embeds `ordinal.{u}` as
a proper initial segment of `ordinal.{v}` for `v > u`. -/
def lift (o : ordinal.{u}) : ordinal.{max u v} :=
quotient.lift_on o (λ ⟨α, r, wo⟩,
@type _ _ (@order_embedding.is_well_order _ _ (@equiv.ulift.{u v} α ⁻¹'o r) r
(order_iso.preimage equiv.ulift.{u v} r) wo)) $
λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨f⟩,
quot.sound ⟨(order_iso.preimage equiv.ulift r).trans $
f.trans (order_iso.preimage equiv.ulift s).symm⟩
theorem lift_type {α} (r : α → α → Prop) [is_well_order α r] :
∃ wo', lift (type r) = @type _ (@equiv.ulift.{u v} α ⁻¹'o r) wo' :=
⟨_, rfl⟩
theorem lift_umax : lift.{u (max u v)} = lift.{u v} :=
funext $ λ a, induction_on a $ λ α r _,
quotient.sound ⟨(order_iso.preimage equiv.ulift r).trans (order_iso.preimage equiv.ulift r).symm⟩
theorem lift_id' (a : ordinal) : lift a = a :=
induction_on a $ λ α r _,
quotient.sound ⟨order_iso.preimage equiv.ulift r⟩
@[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u}
@[simp] theorem lift_lift (a : ordinal) : lift.{(max u v) w} (lift.{u v} a) = lift.{u (max v w)} a :=
induction_on a $ λ α r _,
quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans $
(order_iso.preimage equiv.ulift _).trans (order_iso.preimage equiv.ulift _).symm⟩
theorem lift_type_le {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] :
lift.{u (max v w)} (type r) ≤ lift.{v (max u w)} (type s) ↔ nonempty (r ≼i s) :=
⟨λ ⟨f⟩, ⟨(initial_seg.of_iso (order_iso.preimage equiv.ulift r).symm).trans $
f.trans (initial_seg.of_iso (order_iso.preimage equiv.ulift s))⟩,
λ ⟨f⟩, ⟨(initial_seg.of_iso (order_iso.preimage equiv.ulift r)).trans $
f.trans (initial_seg.of_iso (order_iso.preimage equiv.ulift s).symm)⟩⟩
theorem lift_type_eq {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] :
lift.{u (max v w)} (type r) = lift.{v (max u w)} (type s) ↔ nonempty (r ≃o s) :=
quotient.eq.trans
⟨λ ⟨f⟩, ⟨(order_iso.preimage equiv.ulift r).symm.trans $
f.trans (order_iso.preimage equiv.ulift s)⟩,
λ ⟨f⟩, ⟨(order_iso.preimage equiv.ulift r).trans $
f.trans (order_iso.preimage equiv.ulift s).symm⟩⟩
theorem lift_type_lt {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] :
lift.{u (max v w)} (type r) < lift.{v (max u w)} (type s) ↔ nonempty (r ≺i s) :=
by haveI := @order_embedding.is_well_order _ _ (@equiv.ulift.{u (max v w)} α ⁻¹'o r)
r (order_iso.preimage equiv.ulift.{u (max v w)} r) _;
haveI := @order_embedding.is_well_order _ _ (@equiv.ulift.{v (max u w)} β ⁻¹'o s)
s (order_iso.preimage equiv.ulift.{v (max u w)} s) _; exact
⟨λ ⟨f⟩, ⟨(f.equiv_lt (order_iso.preimage equiv.ulift r).symm).lt_le
(initial_seg.of_iso (order_iso.preimage equiv.ulift s))⟩,
λ ⟨f⟩, ⟨(f.equiv_lt (order_iso.preimage equiv.ulift r)).lt_le
(initial_seg.of_iso (order_iso.preimage equiv.ulift s).symm)⟩⟩
@[simp] theorem lift_le {a b : ordinal} : lift.{u v} a ≤ lift b ↔ a ≤ b :=
induction_on a $ λ α r _, induction_on b $ λ β s _,
by rw ← lift_umax; exactI lift_type_le
@[simp] theorem lift_inj {a b : ordinal} : lift a = lift b ↔ a = b :=
by simp only [le_antisymm_iff, lift_le]
@[simp] theorem lift_lt {a b : ordinal} : lift a < lift b ↔ a < b :=
by simp only [lt_iff_le_not_le, lift_le]
@[simp] theorem lift_zero : lift 0 = 0 :=
quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans
⟨pempty_equiv_pempty, λ a b, iff.rfl⟩⟩
theorem zero_eq_lift_type_empty : 0 = lift.{0 u} (@type empty empty_relation _) :=
by rw [← zero_eq_type_empty, lift_zero]
@[simp] theorem lift_one : lift 1 = 1 :=
quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans
⟨punit_equiv_punit, λ a b, iff.rfl⟩⟩
theorem one_eq_lift_type_unit : 1 = lift.{0 u} (@type unit empty_relation _) :=
by rw [← one_eq_type_unit, lift_one]
@[simp] theorem lift_add (a b) : lift (a + b) = lift a + lift b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans
(order_iso.sum_lex_congr (order_iso.preimage equiv.ulift _)
(order_iso.preimage equiv.ulift _)).symm⟩
@[simp] theorem lift_succ (a) : lift (succ a) = succ (lift a) :=
by unfold succ; simp only [lift_add, lift_one]
@[simp] theorem lift_card (a) : (card a).lift = card (lift a) :=
induction_on a $ λ α r _, rfl
theorem lift_down' {a : cardinal.{u}} {b : ordinal.{max u v}}
(h : card b ≤ a.lift) : ∃ a', lift a' = b :=
let ⟨c, e⟩ := cardinal.lift_down h in
quotient.induction_on c (λ α, induction_on b $ λ β s _ e', begin
resetI,
rw [mk_def, card_type, ← cardinal.lift_id'.{(max u v) u} (mk β),
← cardinal.lift_umax.{u v}, lift_mk_eq.{u (max u v) (max u v)}] at e',
cases e' with f,
have g := order_iso.preimage f s,
haveI := (g : ⇑f ⁻¹'o s ≼o s).is_well_order,
have := lift_type_eq.{u (max u v) (max u v)}.2 ⟨g⟩,
rw [lift_id, lift_umax.{u v}] at this,
exact ⟨_, this⟩
end) e
theorem lift_down {a : ordinal.{u}} {b : ordinal.{max u v}}
(h : b ≤ lift a) : ∃ a', lift a' = b :=
@lift_down' (card a) _ (by rw lift_card; exact card_le_card h)
theorem le_lift_iff {a : ordinal.{u}} {b : ordinal.{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 : ordinal.{u}} {b : ordinal.{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⟩
/-- `ω` is the first infinite ordinal, defined as the order type of `ℕ`. -/
def omega : ordinal.{u} := lift $ @type ℕ (<) _
localized "notation `ω` := ordinal.omega.{0}" in ordinal
theorem card_omega : card omega = cardinal.omega := rfl
@[simp] theorem lift_omega : lift omega = omega := lift_lift _
theorem add_le_add_right {a b : ordinal} : a ≤ b → ∀ c, a + c ≤ b + c :=
induction_on a $ λ α₁ r₁ hr₁, induction_on b $ λ α₂ r₂ hr₂ ⟨⟨⟨f, fo⟩, fi⟩⟩ c,
induction_on c $ λ β s hs, (@type_le' _ _ _ _
(@sum.lex.is_well_order _ _ _ _ hr₁ hs)
(@sum.lex.is_well_order _ _ _ _ hr₂ hs)).2
⟨⟨embedding.sum_congr f (embedding.refl _), λ a b, begin
split; intro H,
{ cases H; constructor; [rwa ← fo, assumption] },
{ cases a with a a; cases b with b b; cases H; constructor; [rwa fo, assumption] }
end⟩⟩
theorem le_add_left (a b : ordinal) : a ≤ b + a :=
by simpa only [zero_add] using add_le_add_right (zero_le b) a
theorem le_total (a b : ordinal) : a ≤ b ∨ b ≤ a :=
match lt_or_eq_of_le (le_add_left b a), lt_or_eq_of_le (le_add_right a b) with
| or.inr h, _ := by rw h; exact or.inl (le_add_right _ _)
| _, or.inr h := by rw h; exact or.inr (le_add_left _ _)
| or.inl h₁, or.inl h₂ := induction_on a (λ α₁ r₁ _,
induction_on b $ λ α₂ r₂ _ ⟨f⟩ ⟨g⟩, begin
resetI,
rw [← typein_top f, ← typein_top g, le_iff_lt_or_eq,
le_iff_lt_or_eq, typein_lt_typein, typein_lt_typein],
rcases trichotomous_of (sum.lex r₁ r₂) g.top f.top with h|h|h;
[exact or.inl (or.inl h), {left, right, rw h}, exact or.inr (or.inl h)]
end) h₁ h₂
end
instance : decidable_linear_order ordinal :=
{ le_total := le_total,
decidable_le := classical.dec_rel _,
..ordinal.partial_order }
@[simp] lemma typein_le_typein (r : α → α → Prop) [is_well_order α r] {x x' : α} :
typein r x ≤ typein r x' ↔ ¬r x' x :=
by rw [←not_lt, typein_lt_typein]
lemma enum_le_enum (r : α → α → Prop) [is_well_order α r] {o o' : ordinal}
(ho : o < type r) (ho' : o' < type r) : ¬r (enum r o' ho') (enum r o ho) ↔ o ≤ o' :=
by rw [←@not_lt _ _ o' o, enum_lt ho']
theorem lt_succ {a b : ordinal} : a < succ b ↔ a ≤ b :=
by rw [← not_le, succ_le, not_lt]
theorem add_lt_add_iff_left (a) {b c : ordinal} : a + b < a + c ↔ b < c :=
by rw [← not_le, ← not_le, add_le_add_iff_left]
theorem lt_of_add_lt_add_right {a b c : ordinal} : a + b < c + b → a < c :=
lt_imp_lt_of_le_imp_le (λ h, add_le_add_right h _)
@[simp] theorem succ_lt_succ {a b : ordinal} : succ a < succ b ↔ a < b :=
by rw [lt_succ, succ_le]
@[simp] theorem succ_le_succ {a b : ordinal} : succ a ≤ succ b ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 succ_lt_succ
theorem succ_inj {a b : ordinal} : succ a = succ b ↔ a = b :=
by simp only [le_antisymm_iff, succ_le_succ]
theorem add_le_add_iff_right {a b : ordinal} (n : ℕ) : a + n ≤ b + n ↔ a ≤ b :=
by induction n with n ih; [rw [nat.cast_zero, add_zero, add_zero],
rw [← nat_cast_succ, add_succ, add_succ, succ_le_succ, ih]]
theorem add_right_cancel {a b : ordinal} (n : ℕ) : a + n = b + n ↔ a = b :=
by simp only [le_antisymm_iff, add_le_add_iff_right]
@[simp] theorem card_eq_zero {o} : card o = 0 ↔ o = 0 :=
⟨induction_on o $ λ α r _ h, begin
refine le_antisymm (le_of_not_lt $
λ hn, ne_zero_iff_nonempty.2 _ h) (zero_le _),
rw [← succ_le, succ_zero] at hn, cases hn with f,
exact ⟨f punit.star⟩
end, λ e, by simp only [e, card_zero]⟩
theorem type_ne_zero_iff_nonempty [is_well_order α r] : type r ≠ 0 ↔ nonempty α :=
(not_congr (@card_eq_zero (type r))).symm.trans ne_zero_iff_nonempty
@[simp] theorem type_eq_zero_iff_empty [is_well_order α r] : type r = 0 ↔ ¬ nonempty α :=
(not_iff_comm.1 type_ne_zero_iff_nonempty).symm
instance : zero_ne_one_class ordinal.{u} :=
{ zero := 0, one := 1, zero_ne_one :=
ne.symm $ type_ne_zero_iff_nonempty.2 ⟨punit.star⟩ }
theorem zero_lt_one : (0 : ordinal) < 1 :=
lt_iff_le_and_ne.2 ⟨zero_le _, zero_ne_one⟩
/-- The ordinal predecessor of `o` is `o'` if `o = succ o'`,
and `o` otherwise. -/
def pred (o : ordinal.{u}) : ordinal.{u} :=
if h : ∃ a, o = succ a then classical.some h else o
@[simp] theorem pred_succ (o) : pred (succ o) = o :=
by have h : ∃ a, succ o = succ a := ⟨_, rfl⟩;
simpa only [pred, dif_pos h] using (succ_inj.1 $ classical.some_spec h).symm
theorem pred_le_self (o) : pred o ≤ o :=
if h : ∃ a, o = succ a then let ⟨a, e⟩ := h in
by rw [e, pred_succ]; exact le_of_lt (lt_succ_self _)
else by rw [pred, dif_neg h]
theorem pred_eq_iff_not_succ {o} : pred o = o ↔ ¬ ∃ a, o = succ a :=
⟨λ e ⟨a, e'⟩, by rw [e', pred_succ] at e; exact ne_of_lt (lt_succ_self _) e,
λ h, dif_neg h⟩
theorem pred_lt_iff_is_succ {o} : pred o < o ↔ ∃ a, o = succ a :=
iff.trans (by simp only [le_antisymm_iff, pred_le_self, true_and, not_le])
(iff_not_comm.1 pred_eq_iff_not_succ).symm
theorem succ_pred_iff_is_succ {o} : succ (pred o) = o ↔ ∃ a, o = succ a :=
⟨λ e, ⟨_, e.symm⟩, λ ⟨a, e⟩, by simp only [e, pred_succ]⟩
theorem succ_lt_of_not_succ {o} (h : ¬ ∃ a, o = succ a) {b} : succ b < o ↔ b < o :=
⟨lt_trans (lt_succ_self _), λ l,
lt_of_le_of_ne (succ_le.2 l) (λ e, h ⟨_, e.symm⟩)⟩
theorem lt_pred {a b} : a < pred b ↔ succ a < b :=
if h : ∃ a, b = succ a then let ⟨c, e⟩ := h in
by rw [e, pred_succ, succ_lt_succ]
else by simp only [pred, dif_neg h, succ_lt_of_not_succ h]
theorem pred_le {a b} : pred a ≤ b ↔ a ≤ succ b :=
le_iff_le_iff_lt_iff_lt.2 lt_pred
@[simp] theorem lift_is_succ {o} : (∃ a, lift o = succ a) ↔ (∃ a, o = succ a) :=
⟨λ ⟨a, h⟩,
let ⟨b, e⟩ := lift_down $ show a ≤ lift o, from le_of_lt $
h.symm ▸ lt_succ_self _ in
⟨b, lift_inj.1 $ by rw [h, ← e, lift_succ]⟩,
λ ⟨a, h⟩, ⟨lift a, by simp only [h, lift_succ]⟩⟩
@[simp] theorem lift_pred (o) : lift (pred o) = pred (lift o) :=
if h : ∃ a, o = succ a then
by cases h with a e; simp only [e, pred_succ, lift_succ]
else by rw [pred_eq_iff_not_succ.2 h,
pred_eq_iff_not_succ.2 (mt lift_is_succ.1 h)]
/-- A limit ordinal is an ordinal which is not zero and not a successor. -/
def is_limit (o : ordinal) : Prop := o ≠ 0 ∧ ∀ a < o, succ a < o
theorem not_zero_is_limit : ¬ is_limit 0
| ⟨h, _⟩ := h rfl
theorem not_succ_is_limit (o) : ¬ is_limit (succ o)
| ⟨_, h⟩ := lt_irrefl _ (h _ (lt_succ_self _))
theorem not_succ_of_is_limit {o} (h : is_limit o) : ¬ ∃ a, o = succ a
| ⟨a, e⟩ := not_succ_is_limit a (e ▸ h)
theorem succ_lt_of_is_limit {o} (h : is_limit o) {a} : succ a < o ↔ a < o :=
⟨lt_trans (lt_succ_self _), h.2 _⟩
theorem le_succ_of_is_limit {o} (h : is_limit o) {a} : o ≤ succ a ↔ o ≤ a :=
le_iff_le_iff_lt_iff_lt.2 $ succ_lt_of_is_limit h
theorem limit_le {o} (h : is_limit o) {a} : o ≤ a ↔ ∀ x < o, x ≤ a :=
⟨λ h x l, le_trans (le_of_lt l) h,
λ H, (le_succ_of_is_limit h).1 $ le_of_not_lt $ λ hn,
not_lt_of_le (H _ hn) (lt_succ_self _)⟩
theorem lt_limit {o} (h : is_limit o) {a} : a < o ↔ ∃ x < o, a < x :=
by simpa only [not_ball, not_le] using not_congr (@limit_le _ h a)
@[simp] theorem lift_is_limit (o) : is_limit (lift o) ↔ is_limit o :=
and_congr (not_congr $ by simpa only [lift_zero] using @lift_inj o 0)
⟨λ H a h, lift_lt.1 $ by simpa only [lift_succ] using H _ (lift_lt.2 h),
λ H a h, let ⟨a', e⟩ := lift_down (le_of_lt h) in
by rw [← e, ← lift_succ, lift_lt];
rw [← e, lift_lt] at h; exact H a' h⟩
theorem is_limit.pos {o : ordinal} (h : is_limit o) : 0 < o :=
lt_of_le_of_ne (zero_le _) h.1.symm
theorem is_limit.one_lt {o : ordinal} (h : is_limit o) : 1 < o :=
by simpa only [succ_zero] using h.2 _ h.pos
theorem is_limit.nat_lt {o : ordinal} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o
| 0 := h.pos
| (n+1) := h.2 _ (is_limit.nat_lt n)
theorem zero_or_succ_or_limit (o : ordinal) :
o = 0 ∨ (∃ a, o = succ a) ∨ is_limit o :=
if o0 : o = 0 then or.inl o0 else
if h : ∃ a, o = succ a then or.inr (or.inl h) else
or.inr $ or.inr ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩
instance : is_well_order ordinal (<) := ⟨wf⟩
@[elab_as_eliminator] def limit_rec_on {C : ordinal → Sort*}
(o : ordinal) (H₁ : C 0) (H₂ : ∀ o, C o → C (succ o))
(H₃ : ∀ o, is_limit o → (∀ o' < o, C o') → C o) : C o :=
wf.fix (λ o IH,
if o0 : o = 0 then by rw o0; exact H₁ else
if h : ∃ a, o = succ a then
by rw ← succ_pred_iff_is_succ.2 h; exact
H₂ _ (IH _ $ pred_lt_iff_is_succ.2 h)
else H₃ _ ⟨o0, λ a, (succ_lt_of_not_succ h).2⟩ IH) o
@[simp] theorem limit_rec_on_zero {C} (H₁ H₂ H₃) : @limit_rec_on C 0 H₁ H₂ H₃ = H₁ :=
by rw [limit_rec_on, well_founded.fix_eq, dif_pos rfl]; refl
@[simp] theorem limit_rec_on_succ {C} (o H₁ H₂ H₃) :
@limit_rec_on C (succ o) H₁ H₂ H₃ = H₂ o (@limit_rec_on C o H₁ H₂ H₃) :=
begin
have h : ∃ a, succ o = succ a := ⟨_, rfl⟩,
rw [limit_rec_on, well_founded.fix_eq,
dif_neg (succ_ne_zero o), dif_pos h],
generalize : limit_rec_on._proof_2 (succ o) h = h₂,
generalize : limit_rec_on._proof_3 (succ o) h = h₃,
revert h₂ h₃, generalize e : pred (succ o) = o', intros,
rw pred_succ at e, subst o', refl
end
@[simp] theorem limit_rec_on_limit {C} (o H₁ H₂ H₃ h) :
@limit_rec_on C o H₁ H₂ H₃ = H₃ o h (λ x h, @limit_rec_on C x H₁ H₂ H₃) :=
by rw [limit_rec_on, well_founded.fix_eq,
dif_neg h.1, dif_neg (not_succ_of_is_limit h)]; refl
lemma has_succ_of_is_limit {α} {r : α → α → Prop} [wo : is_well_order α r]
(h : (type r).is_limit) (x : α) : ∃y, r x y :=
begin
use enum r (typein r x).succ (h.2 _ (typein_lt_type r x)),
convert (enum_lt (typein_lt_type r x) _).mpr (lt_succ_self _), rw [enum_typein]
end
lemma type_subrel_lt (o : ordinal.{u}) :
type (subrel (<) {o' : ordinal | o' < o}) = ordinal.lift.{u u+1} o :=
begin
refine quotient.induction_on o _,
rintro ⟨α, r, wo⟩, resetI, apply quotient.sound,
constructor, symmetry, refine (order_iso.preimage equiv.ulift r).trans (typein_iso r)
end
lemma mk_initial_seg (o : ordinal.{u}) :
#{o' : ordinal | o' < o} = cardinal.lift.{u u+1} o.card :=
by rw [lift_card, ←type_subrel_lt, card_type]
/-- A normal ordinal function is a strictly increasing function which is
order-continuous. -/
def is_normal (f : ordinal → ordinal) : Prop :=
(∀ o, f o < f (succ o)) ∧ ∀ o, is_limit o → ∀ a, f o ≤ a ↔ ∀ b < o, f b ≤ a
theorem is_normal.limit_le {f} (H : is_normal f) : ∀ {o}, is_limit o →
∀ {a}, f o ≤ a ↔ ∀ b < o, f b ≤ a := H.2
theorem is_normal.limit_lt {f} (H : is_normal f) {o} (h : is_limit o) {a} :
a < f o ↔ ∃ b < o, a < f b :=
not_iff_not.1 $ by simpa only [exists_prop, not_exists, not_and, not_lt] using H.2 _ h a
theorem is_normal.lt_iff {f} (H : is_normal f) {a b} : f a < f b ↔ a < b :=
strict_mono.lt_iff_lt $ λ a b,
limit_rec_on b (not.elim (not_lt_of_le $ zero_le _))
(λ b IH h, (lt_or_eq_of_le (lt_succ.1 h)).elim
(λ h, lt_trans (IH h) (H.1 _))
(λ e, e ▸ H.1 _))
(λ b l IH h, lt_of_lt_of_le (H.1 a)
((H.2 _ l _).1 (le_refl _) _ (l.2 _ h)))
theorem is_normal.le_iff {f} (H : is_normal f) {a b} : f a ≤ f b ↔ a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 H.lt_iff
theorem is_normal.inj {f} (H : is_normal f) {a b} : f a = f b ↔ a = b :=
by simp only [le_antisymm_iff, H.le_iff]
theorem is_normal.le_self {f} (H : is_normal f) (a) : a ≤ f a :=
limit_rec_on a (zero_le _)
(λ a IH, succ_le.2 $ lt_of_le_of_lt IH (H.1 _))
(λ a l IH, (limit_le l).2 $ λ b h,
le_trans (IH b h) $ H.le_iff.2 $ le_of_lt h)
theorem is_normal.le_set {f} (H : is_normal f) (p : ordinal → Prop)
(p0 : ∃ x, p x) (S)
(H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → a ≤ o) {o} :
f S ≤ o ↔ ∀ a, p a → f a ≤ o :=
⟨λ h a pa, le_trans (H.le_iff.2 ((H₂ _).1 (le_refl _) _ pa)) h,
λ h, begin
revert H₂, apply limit_rec_on S,
{ intro H₂,
cases p0 with x px,
have := le_zero.1 ((H₂ _).1 (zero_le _) _ px),
rw this at px, exact h _ px },
{ intros S _ H₂,
rcases not_ball.1 (mt (H₂ S).2 $ not_le_of_lt $ lt_succ_self _) with ⟨a, h₁, h₂⟩,
exact le_trans (H.le_iff.2 $ succ_le.2 $ not_le.1 h₂) (h _ h₁) },
{ intros S L _ H₂, apply (H.2 _ L _).2, intros a h',
rcases not_ball.1 (mt (H₂ a).2 (not_le.2 h')) with ⟨b, h₁, h₂⟩,
exact le_trans (H.le_iff.2 $ le_of_lt $ not_le.1 h₂) (h _ h₁) }
end⟩
theorem is_normal.le_set' {f} (H : is_normal f) (p : α → Prop) (g : α → ordinal)
(p0 : ∃ x, p x) (S)
(H₂ : ∀ o, S ≤ o ↔ ∀ a, p a → g a ≤ o) {o} :
f S ≤ o ↔ ∀ a, p a → f (g a) ≤ o :=
(H.le_set (λ x, ∃ y, p y ∧ x = g y)
(let ⟨x, px⟩ := p0 in ⟨_, _, px, rfl⟩) _
(λ o, (H₂ o).trans ⟨λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1,
λ H a h1, H (g a) ⟨a, h1, rfl⟩⟩)).trans
⟨λ H a h, H (g a) ⟨a, h, rfl⟩, λ H a ⟨y, h1, h2⟩, h2.symm ▸ H y h1⟩
theorem is_normal.refl : is_normal id :=
⟨λ x, lt_succ_self _, λ o l a, limit_le l⟩
theorem is_normal.trans {f g} (H₁ : is_normal f) (H₂ : is_normal g) :
is_normal (λ x, f (g x)) :=
⟨λ x, H₁.lt_iff.2 (H₂.1 _),
λ o l a, H₁.le_set' (< o) g ⟨_, l.pos⟩ _ (λ c, H₂.2 _ l _)⟩
theorem is_normal.is_limit {f} (H : is_normal f) {o} (l : is_limit o) :
is_limit (f o) :=
⟨ne_of_gt $ lt_of_le_of_lt (zero_le _) $ H.lt_iff.2 l.pos,
λ a h, let ⟨b, h₁, h₂⟩ := (H.limit_lt l).1 h in
lt_of_le_of_lt (succ_le.2 h₂) (H.lt_iff.2 h₁)⟩
theorem add_le_of_limit {a b c : ordinal.{u}}
(h : is_limit b) : a + b ≤ c ↔ ∀ b' < b, a + b' ≤ c :=
⟨λ h b' l, le_trans (add_le_add_left (le_of_lt l) _) h,
λ H, le_of_not_lt $
induction_on a (λ α r _, induction_on b $ λ β s _ h H l, begin
resetI,
suffices : ∀ x : β, sum.lex r s (sum.inr x) (enum _ _ l),
{ cases enum _ _ l with x x,
{ cases this (enum s 0 h.pos) },
{ exact irrefl _ (this _) } },
intros x,
rw [← typein_lt_typein (sum.lex r s), typein_enum],
have := H _ (h.2 _ (typein_lt_type s x)),
rw [add_succ, succ_le] at this,
refine lt_of_le_of_lt (type_le'.2
⟨order_embedding.of_monotone (λ a, _) (λ a b, _)⟩) this,
{ rcases a with ⟨a | b, h⟩,
{ exact sum.inl a },
{ exact sum.inr ⟨b, by cases h; assumption⟩ } },
{ rcases a with ⟨a | a, h₁⟩; rcases b with ⟨b | b, h₂⟩; cases h₁; cases h₂;
rintro ⟨⟩; constructor; assumption }
end) h H⟩
theorem add_is_normal (a : ordinal) : is_normal ((+) a) :=
⟨λ b, (add_lt_add_iff_left a).2 (lt_succ_self _),
λ b l c, add_le_of_limit l⟩
theorem add_is_limit (a) {b} : is_limit b → is_limit (a + b) :=
(add_is_normal a).is_limit
def typein.principal_seg {α : Type u} (r : α → α → Prop) [is_well_order α r] :
@principal_seg α ordinal.{u} r (<) :=
⟨order_embedding.of_monotone (typein r)
(λ a b, (typein_lt_typein r).2), type r, λ b,
⟨λ h, ⟨enum r _ h, typein_enum r h⟩,
λ ⟨a, e⟩, e ▸ typein_lt_type _ _⟩⟩
@[simp] theorem typein.principal_seg_coe (r : α → α → Prop) [is_well_order α r] :
(typein.principal_seg r : α → ordinal) = typein r := rfl
/-- The minimal element of a nonempty family of ordinals -/
def min {ι} (I : nonempty ι) (f : ι → ordinal) : ordinal :=
wf.min (set.range f) (let ⟨i⟩ := I in ⟨_, set.mem_range_self i⟩)
theorem min_eq {ι} (I) (f : ι → ordinal) : ∃ i, min I f = f i :=
let ⟨i, e⟩ := wf.min_mem (set.range f) _ in ⟨i, e.symm⟩
theorem min_le {ι I} (f : ι → ordinal) (i) : min I f ≤ f i :=
le_of_not_gt $ wf.not_lt_min (set.range f) _ (set.mem_range_self i)
theorem le_min {ι I} {f : ι → ordinal} {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⟩
/-- The minimal element of a nonempty set of ordinals -/
def omin (S : set ordinal.{u}) (H : ∃ x, x ∈ S) : ordinal.{u} :=
@min.{(u+2) u} S (let ⟨x, px⟩ := H in ⟨⟨x, px⟩⟩) subtype.val
theorem omin_mem (S H) : omin S H ∈ S :=
let ⟨⟨i, h⟩, e⟩ := @min_eq S _ _ in
(show omin S H = i, from e).symm ▸ h
theorem le_omin {S H a} : a ≤ omin S H ↔ ∀ i ∈ S, a ≤ i :=
le_min.trans set_coe.forall
theorem omin_le {S H i} (h : i ∈ S) : omin S H ≤ i :=
le_omin.1 (le_refl _) _ h
@[simp] theorem lift_min {ι} (I) (f : ι → ordinal) : 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)
def lift.initial_seg : @initial_seg ordinal.{u} ordinal.{max u v} (<) (<) :=
⟨⟨⟨lift.{u v}, λ a b, lift_inj.1⟩, λ a b, lift_lt.symm⟩,
λ a b h, lift_down (le_of_lt h)⟩
@[simp] theorem lift.initial_seg_coe : (lift.initial_seg : ordinal → ordinal) = lift := rfl
/-- `univ.{u v}` is the order type of the ordinals of `Type u` as a member
of `ordinal.{v}` (when `u < v`). It is an inaccessible cardinal. -/
def univ := lift.{(u+1) v} (@type ordinal.{u} (<) _)
theorem univ_id : univ.{u (u+1)} = @type ordinal.{u} (<) _ := lift_id _
@[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _
theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _
def lift.principal_seg : @principal_seg ordinal.{u} ordinal.{max (u+1) v} (<) (<) :=
⟨↑lift.initial_seg.{u (max (u+1) v)}, univ.{u v}, begin
refine λ b, induction_on b _, introsI β s _,
rw [univ, ← lift_umax], split; intro h,
{ rw ← lift_id (type s) at h ⊢,
cases lift_type_lt.1 h with f, cases f with f a hf,
existsi a, revert hf,
apply induction_on a, intros α r _ hf,
refine lift_type_eq.{u (max (u+1) v) (max (u+1) v)}.2
⟨(order_iso.of_surjective (order_embedding.of_monotone _ _) _).symm⟩,
{ exact λ b, enum r (f b) ((hf _).2 ⟨_, rfl⟩) },
{ refine λ a b h, (typein_lt_typein r).1 _,
rw [typein_enum, typein_enum],
exact f.ord.1 h },
{ intro a', cases (hf _).1 (typein_lt_type _ a') with b e,
existsi b, simp, simp [e] } },
{ cases h with a e, rw [← e],
apply induction_on a, intros α r _,
exact lift_type_lt.{u (u+1) (max (u+1) v)}.2
⟨typein.principal_seg r⟩ }
end⟩
@[simp] theorem lift.principal_seg_coe :
(lift.principal_seg.{u v} : ordinal → ordinal) = lift.{u (max (u+1) v)} := rfl
@[simp] theorem lift.principal_seg_top : lift.principal_seg.top = univ := rfl
theorem lift.principal_seg_top' :
lift.principal_seg.{u (u+1)}.top = @type ordinal.{u} (<) _ :=
by simp only [lift.principal_seg_top, univ_id]
/-- `a - b` is the unique ordinal satisfying
`b + (a - b) = a` when `b ≤ a`. -/
def sub (a b : ordinal.{u}) : ordinal.{u} :=
omin {o | a ≤ b+o} ⟨a, le_add_left _ _⟩
instance : has_sub ordinal := ⟨sub⟩
theorem le_add_sub (a b : ordinal) : a ≤ b + (a - b) :=
omin_mem {o | a ≤ b+o} _
theorem sub_le {a b c : ordinal} : a - b ≤ c ↔ a ≤ b + c :=
⟨λ h, le_trans (le_add_sub a b) (add_le_add_left h _),
λ h, omin_le h⟩
theorem lt_sub {a b c : ordinal} : a < b - c ↔ c + a < b :=
lt_iff_lt_of_le_iff_le sub_le
theorem add_sub_cancel (a b : ordinal) : a + b - a = b :=
le_antisymm (sub_le.2 $ le_refl _)
((add_le_add_iff_left a).1 $ le_add_sub _ _)
theorem sub_eq_of_add_eq {a b c : ordinal} (h : a + b = c) : c - a = b :=
h ▸ add_sub_cancel _ _
theorem sub_le_self (a b : ordinal) : a - b ≤ a :=
sub_le.2 $ le_add_left _ _
theorem add_sub_cancel_of_le {a b : ordinal} (h : b ≤ a) : b + (a - b) = a :=
le_antisymm begin
rcases zero_or_succ_or_limit (a-b) with e|⟨c,e⟩|l,
{ simp only [e, add_zero, h] },
{ rw [e, add_succ, succ_le, ← lt_sub, e], apply lt_succ_self },
{ exact (add_le_of_limit l).2 (λ c l, le_of_lt (lt_sub.1 l)) }
end (le_add_sub _ _)
@[simp] theorem sub_zero (a : ordinal) : a - 0 = a :=
by simpa only [zero_add] using add_sub_cancel 0 a
@[simp] theorem zero_sub (a : ordinal) : 0 - a = 0 :=
by rw ← le_zero; apply sub_le_self
@[simp] theorem sub_self (a : ordinal) : a - a = 0 :=
by simpa only [add_zero] using add_sub_cancel a 0
theorem sub_eq_zero_iff_le {a b : ordinal} : a - b = 0 ↔ a ≤ b :=
⟨λ h, by simpa only [h, add_zero] using le_add_sub a b,
λ h, by rwa [← le_zero, sub_le, add_zero]⟩
theorem sub_sub (a b c : ordinal) : a - b - c = a - (b + c) :=
eq_of_forall_ge_iff $ λ d, by rw [sub_le, sub_le, sub_le, add_assoc]
theorem add_sub_add_cancel (a b c : ordinal) : a + b - (a + c) = b - c :=
by rw [← sub_sub, add_sub_cancel]
theorem sub_is_limit {a b} (l : is_limit a) (h : b < a) : is_limit (a - b) :=
⟨ne_of_gt $ lt_sub.2 $ by rwa add_zero,
λ c h, by rw [lt_sub, add_succ]; exact l.2 _ (lt_sub.1 h)⟩
@[simp] theorem one_add_omega : 1 + omega.{u} = omega :=
begin
refine le_antisymm _ (le_add_left _ _),
rw [omega, one_eq_lift_type_unit, ← lift_add, lift_le, type_add],
have : is_well_order unit empty_relation := by apply_instance,
refine ⟨order_embedding.collapse (order_embedding.of_monotone _ _)⟩,
{ apply sum.rec, exact λ _, 0, exact nat.succ },
{ intros a b, cases a; cases b; intro H; cases H with _ _ H _ _ H;
[cases H, exact nat.succ_pos _, exact nat.succ_lt_succ H] }
end
@[simp, priority 990]
theorem one_add_of_omega_le {o} (h : omega ≤ o) : 1 + o = o :=
by rw [← add_sub_cancel_of_le h, ← add_assoc, one_add_omega]
instance : monoid ordinal.{u} :=
{ mul := λ a b, quotient.lift_on₂ a b
(λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨β × α, prod.lex s r, by exactI prod.lex.is_well_order⟩⟧
: Well_order → Well_order → ordinal) $
λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩,
quot.sound ⟨order_iso.prod_lex_congr g f⟩,
one := 1,
mul_assoc := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩,
eq.symm $ quotient.sound ⟨⟨prod_assoc _ _ _, λ a b, begin
rcases a with ⟨⟨a₁, a₂⟩, a₃⟩,
rcases b with ⟨⟨b₁, b₂⟩, b₃⟩,
simp [prod.lex_def, and_or_distrib_left, or_assoc, and_assoc]
end⟩⟩,
mul_one := λ a, induction_on a $ λ α r _, quotient.sound
⟨⟨punit_prod _, λ a b, by rcases a with ⟨⟨⟨⟩⟩, a⟩; rcases b with ⟨⟨⟨⟩⟩, b⟩;
simp only [prod.lex_def, empty_relation, false_or];
simp only [eq_self_iff_true, true_and]; refl⟩⟩,
one_mul := λ a, induction_on a $ λ α r _, quotient.sound
⟨⟨prod_punit _, λ a b, by rcases a with ⟨a, ⟨⟨⟩⟩⟩; rcases b with ⟨b, ⟨⟨⟩⟩⟩;
simp only [prod.lex_def, empty_relation, and_false, or_false]; refl⟩⟩ }
@[simp] theorem type_mul {α β : Type u} (r : α → α → Prop) (s : β → β → Prop)
[is_well_order α r] [is_well_order β s] : type r * type s = type (prod.lex s r) := rfl
@[simp] theorem lift_mul (a b) : lift (a * b) = lift a * lift b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
quotient.sound ⟨(order_iso.preimage equiv.ulift _).trans
(order_iso.prod_lex_congr (order_iso.preimage equiv.ulift _)
(order_iso.preimage equiv.ulift _)).symm⟩
@[simp] theorem card_mul (a b) : card (a * b) = card a * card b :=
quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩,
mul_comm (mk β) (mk α)
@[simp] theorem mul_zero (a : ordinal) : a * 0 = 0 :=
induction_on a $ λ α _ _, by exactI
type_eq_zero_iff_empty.2 (λ ⟨⟨e, _⟩⟩, e.elim)
@[simp] theorem zero_mul (a : ordinal) : 0 * a = 0 :=
induction_on a $ λ α _ _, by exactI
type_eq_zero_iff_empty.2 (λ ⟨⟨_, e⟩⟩, e.elim)
theorem mul_add (a b c : ordinal) : a * (b + c) = a * b + a * c :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩,
quotient.sound ⟨⟨sum_prod_distrib _ _ _, begin
rintro ⟨a₁|a₁, a₂⟩ ⟨b₁|b₁, b₂⟩; simp only [prod.lex_def,
sum.lex_inl_inl, sum.lex.sep, sum.lex_inr_inl, sum.lex_inr_inr,
sum_prod_distrib_apply_left, sum_prod_distrib_apply_right];
simp only [sum.inl.inj_iff, true_or, false_and, false_or]
end⟩⟩
@[simp] theorem mul_add_one (a b : ordinal) : a * (b + 1) = a * b + a :=
by simp only [mul_add, mul_one]
@[simp] theorem mul_succ (a b : ordinal) : a * succ b = a * b + a := mul_add_one _ _
theorem mul_le_mul_left {a b} (c : ordinal) : a ≤ b → c * a ≤ c * b :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin
resetI,
refine type_le'.2 ⟨order_embedding.of_monotone
(λ a, (f a.1, a.2))
(λ a b h, _)⟩, clear_,
cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h',
{ exact prod.lex.left _ _ (f.to_order_embedding.ord.1 h') },
{ exact prod.lex.right _ h' }
end
theorem mul_le_mul_right {a b} (c : ordinal) : a ≤ b → a * c ≤ b * c :=
quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩, begin
resetI,
refine type_le'.2 ⟨order_embedding.of_monotone
(λ a, (a.1, f a.2))
(λ a b h, _)⟩,
cases h with a₁ b₁ a₂ b₂ h' a b₁ b₂ h',
{ exact prod.lex.left _ _ h' },
{ exact prod.lex.right _ (f.to_order_embedding.ord.1 h') }
end
theorem mul_le_mul {a b c d : ordinal} (h₁ : a ≤ c) (h₂ : b ≤ d) : a * b ≤ c * d :=
le_trans (mul_le_mul_left _ h₂) (mul_le_mul_right _ h₁)
private lemma mul_le_of_limit_aux {α β r s} [is_well_order α r] [is_well_order β s]
{c} (h : is_limit (type s)) (H : ∀ b' < type s, type r * b' ≤ c)
(l : c < type r * type s) : false :=
begin
suffices : ∀ a b, prod.lex s r (b, a) (enum _ _ l),
{ cases enum _ _ l with b a, exact irrefl _ (this _ _) },
intros a b,
rw [← typein_lt_typein (prod.lex s r), typein_enum],
have := H _ (h.2 _ (typein_lt_type s b)),
rw [mul_succ] at this,
have := lt_of_lt_of_le ((add_lt_add_iff_left _).2
(typein_lt_type _ a)) this,
refine lt_of_le_of_lt _ this,
refine (type_le'.2 _),
constructor,
refine order_embedding.of_monotone (λ a, _) (λ a b, _),
{ rcases a with ⟨⟨b', a'⟩, h⟩,
by_cases e : b = b',
{ refine sum.inr ⟨a', _⟩,
subst e, cases h with _ _ _ _ h _ _ _ h,
{ exact (irrefl _ h).elim },
{ exact h } },
{ refine sum.inl (⟨b', _⟩, a'),
cases h with _ _ _ _ h _ _ _ h,
{ exact h }, { exact (e rfl).elim } } },
{ rcases a with ⟨⟨b₁, a₁⟩, h₁⟩,
rcases b with ⟨⟨b₂, a₂⟩, h₂⟩,
intro h, by_cases e₁ : b = b₁; by_cases e₂ : b = b₂,
{ substs b₁ b₂, simpa only [subrel_val, prod.lex_def, @irrefl _ s _ b, true_and, false_or, eq_self_iff_true, dif_pos, sum.lex_inr_inr] using h },
{ subst b₁, simp only [subrel_val, prod.lex_def, e₂, prod.lex_def, dif_pos, subrel_val, eq_self_iff_true, or_false, dif_neg, not_false_iff, sum.lex_inr_inl, false_and] at h ⊢,
cases h₂; [exact asymm h h₂_h, exact e₂ rfl] },
{ simp only [e₂, dif_pos, eq_self_iff_true, dif_neg e₁, not_false_iff, sum.lex.sep] },
{ simpa only [dif_neg e₁, dif_neg e₂, prod.lex_def, subrel_val, subtype.mk_eq_mk, sum.lex_inl_inl] using h } }
end
theorem mul_le_of_limit {a b c : ordinal.{u}}
(h : is_limit b) : a * b ≤ c ↔ ∀ b' < b, a * b' ≤ c :=
⟨λ h b' l, le_trans (mul_le_mul_left _ (le_of_lt l)) h,
λ H, le_of_not_lt $ induction_on a (λ α r _, induction_on b $ λ β s _,
by exactI mul_le_of_limit_aux) h H⟩
theorem mul_is_normal {a : ordinal} (h : 0 < a) : is_normal ((*) a) :=
⟨λ b, by rw mul_succ; simpa only [add_zero] using (add_lt_add_iff_left (a*b)).2 h,
λ b l c, mul_le_of_limit l⟩
theorem lt_mul_of_limit {a b c : ordinal.{u}}
(h : is_limit c) : a < b * c ↔ ∃ c' < c, a < b * c' :=
by simpa only [not_ball, not_le] using not_congr (@mul_le_of_limit b c a h)
theorem mul_lt_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b < a * c ↔ b < c :=
(mul_is_normal a0).lt_iff
theorem mul_le_mul_iff_left {a b c : ordinal} (a0 : 0 < a) : a * b ≤ a * c ↔ b ≤ c :=
(mul_is_normal a0).le_iff
theorem mul_lt_mul_of_pos_left {a b c : ordinal}
(h : a < b) (c0 : 0 < c) : c * a < c * b :=
(mul_lt_mul_iff_left c0).2 h
theorem mul_pos {a b : ordinal} (h₁ : 0 < a) (h₂ : 0 < b) : 0 < a * b :=
by simpa only [mul_zero] using mul_lt_mul_of_pos_left h₂ h₁
theorem mul_ne_zero {a b : ordinal} : a ≠ 0 → b ≠ 0 → a * b ≠ 0 :=
by simpa only [pos_iff_ne_zero] using mul_pos
theorem le_of_mul_le_mul_left {a b c : ordinal}
(h : c * a ≤ c * b) (h0 : 0 < c) : a ≤ b :=
le_imp_le_of_lt_imp_lt (λ h', mul_lt_mul_of_pos_left h' h0) h
theorem mul_right_inj {a b c : ordinal} (a0 : 0 < a) : a * b = a * c ↔ b = c :=
(mul_is_normal a0).inj
theorem mul_is_limit {a b : ordinal}
(a0 : 0 < a) : is_limit b → is_limit (a * b) :=
(mul_is_normal a0).is_limit
theorem mul_is_limit_left {a b : ordinal}
(l : is_limit a) (b0 : 0 < b) : is_limit (a * b) :=
begin
rcases zero_or_succ_or_limit b with rfl|⟨b,rfl⟩|lb,
{ exact (lt_irrefl _).elim b0 },
{ rw mul_succ, exact add_is_limit _ l },
{ exact mul_is_limit l.pos lb }
end
protected lemma div_aux (a b : ordinal.{u}) (h : b ≠ 0) : set.nonempty {o | a < b * succ o} :=
⟨a, succ_le.1 $
by simpa only [succ_zero, one_mul]
using mul_le_mul_right (succ a) (succ_le.2 (pos_iff_ne_zero.2 h))⟩
/-- `a / b` is the unique ordinal `o` satisfying
`a = b * o + o'` with `o' < b`. -/
protected def div (a b : ordinal.{u}) : ordinal.{u} :=
if h : b = 0 then 0 else omin {o | a < b * succ o} (ordinal.div_aux a b h)
instance : has_div ordinal := ⟨ordinal.div⟩
@[simp] theorem div_zero (a : ordinal) : a / 0 = 0 := dif_pos rfl
lemma div_def (a) {b : ordinal} (h : b ≠ 0) :
a / b = omin {o | a < b * succ o} (ordinal.div_aux a b h) := dif_neg h
theorem lt_mul_succ_div (a) {b : ordinal} (h : b ≠ 0) : a < b * succ (a / b) :=
by rw div_def a h; exact omin_mem {o | a < b * succ o} _
theorem lt_mul_div_add (a) {b : ordinal} (h : b ≠ 0) : a < b * (a / b) + b :=
by simpa only [mul_succ] using lt_mul_succ_div a h
theorem div_le {a b c : ordinal} (b0 : b ≠ 0) : a / b ≤ c ↔ a < b * succ c :=
⟨λ h, lt_of_lt_of_le (lt_mul_succ_div a b0) (mul_le_mul_left _ $ succ_le_succ.2 h),
λ h, by rw div_def a b0; exact omin_le h⟩
theorem lt_div {a b c : ordinal} (c0 : c ≠ 0) : a < b / c ↔ c * succ a ≤ b :=
by rw [← not_le, div_le c0, not_lt]
theorem le_div {a b c : ordinal} (c0 : c ≠ 0) :
a ≤ b / c ↔ c * a ≤ b :=
begin
apply limit_rec_on a,
{ simp only [mul_zero, zero_le] },
{ intros, rw [succ_le, lt_div c0] },
{ simp only [mul_le_of_limit, limit_le, iff_self, forall_true_iff] {contextual := tt} }
end
theorem div_lt {a b c : ordinal} (b0 : b ≠ 0) :
a / b < c ↔ a < b * c :=
lt_iff_lt_of_le_iff_le $ le_div b0
theorem div_le_of_le_mul {a b c : ordinal} (h : a ≤ b * c) : a / b ≤ c :=
if b0 : b = 0 then by simp only [b0, div_zero, zero_le] else
(div_le b0).2 $ lt_of_le_of_lt h $
mul_lt_mul_of_pos_left (lt_succ_self _) (pos_iff_ne_zero.2 b0)
theorem mul_lt_of_lt_div {a b c : ordinal} : a < b / c → c * a < b :=
lt_imp_lt_of_le_imp_le div_le_of_le_mul
@[simp] theorem zero_div (a : ordinal) : 0 / a = 0 :=
le_zero.1 $ div_le_of_le_mul $ zero_le _
theorem mul_div_le (a b : ordinal) : b * (a / b) ≤ a :=
if b0 : b = 0 then by simp only [b0, zero_mul, zero_le] else (le_div b0).1 (le_refl _)
theorem mul_add_div (a) {b : ordinal} (b0 : b ≠ 0) (c) : (b * a + c) / b = a + c / b :=
begin
apply le_antisymm,
{ apply (div_le b0).2,
rw [mul_succ, mul_add, add_assoc, add_lt_add_iff_left],
apply lt_mul_div_add _ b0 },
{ rw [le_div b0, mul_add, add_le_add_iff_left],
apply mul_div_le }
end
theorem div_eq_zero_of_lt {a b : ordinal} (h : a < b) : a / b = 0 :=
by rw [← le_zero, div_le $ pos_iff_ne_zero.1 $ lt_of_le_of_lt (zero_le _) h];
simpa only [succ_zero, mul_one] using h
@[simp] theorem mul_div_cancel (a) {b : ordinal} (b0 : b ≠ 0) : b * a / b = a :=
by simpa only [add_zero, zero_div] using mul_add_div a b0 0
@[simp] theorem div_one (a : ordinal) : a / 1 = a :=
by simpa only [one_mul] using mul_div_cancel a one_ne_zero
@[simp] theorem div_self {a : ordinal} (h : a ≠ 0) : a / a = 1 :=
by simpa only [mul_one] using mul_div_cancel 1 h
theorem mul_sub (a b c : ordinal) : a * (b - c) = a * b - a * c :=
if a0 : a = 0 then by simp only [a0, zero_mul, sub_self] else
eq_of_forall_ge_iff $ λ d,
by rw [sub_le, ← le_div a0, sub_le, ← le_div a0, mul_add_div _ a0]
theorem is_limit_add_iff {a b} : is_limit (a + b) ↔ is_limit b ∨ (b = 0 ∧ is_limit a) :=
begin
split; intro h,
{ by_cases h' : b = 0,
{ rw [h', add_zero] at h, right, exact ⟨h', h⟩ },
left, rw [←add_sub_cancel a b], apply sub_is_limit h,
suffices : a + 0 < a + b, simpa only [add_zero],
rwa [add_lt_add_iff_left, pos_iff_ne_zero] },
rcases h with h|⟨rfl, h⟩, exact add_is_limit a h, simpa only [add_zero]
end
/-- Divisibility is defined by right multiplication:
`a ∣ b` if there exists `c` such that `b = a * c`. -/
instance : has_dvd ordinal := ⟨λ a b, ∃ c, b = a * c⟩
theorem dvd_def {a b : ordinal} : a ∣ b ↔ ∃ c, b = a * c := iff.rfl
theorem dvd_mul (a b : ordinal) : a ∣ a * b := ⟨_, rfl⟩
theorem dvd_trans : ∀ {a b c : ordinal}, a ∣ b → b ∣ c → a ∣ c
| a _ _ ⟨b, rfl⟩ ⟨c, rfl⟩ := ⟨b * c, mul_assoc _ _ _⟩
theorem dvd_mul_of_dvd {a b : ordinal} (c) (h : a ∣ b) : a ∣ b * c :=
dvd_trans h (dvd_mul _ _)
theorem dvd_add_iff : ∀ {a b c : ordinal}, a ∣ b → (a ∣ b + c ↔ a ∣ c)
| a _ c ⟨b, rfl⟩ :=
⟨λ ⟨d, e⟩, ⟨d - b, by rw [mul_sub, ← e, add_sub_cancel]⟩,
λ ⟨d, e⟩, by rw [e, ← mul_add]; apply dvd_mul⟩
theorem dvd_add {a b c : ordinal} (h₁ : a ∣ b) : a ∣ c → a ∣ b + c :=
(dvd_add_iff h₁).2
theorem dvd_zero (a : ordinal) : a ∣ 0 := ⟨_, (mul_zero _).symm⟩
theorem zero_dvd {a : ordinal} : 0 ∣ a ↔ a = 0 :=
⟨λ ⟨h, e⟩, by simp only [e, zero_mul], λ e, e.symm ▸ dvd_zero _⟩
theorem one_dvd (a : ordinal) : 1 ∣ a := ⟨a, (one_mul _).symm⟩
theorem div_mul_cancel : ∀ {a b : ordinal}, a ≠ 0 → a ∣ b → a * (b / a) = b
| a _ a0 ⟨b, rfl⟩ := by rw [mul_div_cancel _ a0]
theorem le_of_dvd : ∀ {a b : ordinal}, b ≠ 0 → a ∣ b → a ≤ b
| a _ b0 ⟨b, rfl⟩ := by simpa only [mul_one] using mul_le_mul_left a
(one_le_iff_ne_zero.2 (λ h : b = 0, by simpa only [h, mul_zero] using b0))
theorem dvd_antisymm {a b : ordinal} (h₁ : a ∣ b) (h₂ : b ∣ a) : a = b :=
if a0 : a = 0 then by subst a; exact (zero_dvd.1 h₁).symm else
if b0 : b = 0 then by subst b; exact zero_dvd.1 h₂ else
le_antisymm (le_of_dvd b0 h₁) (le_of_dvd a0 h₂)
/-- `a % b` is the unique ordinal `o'` satisfying
`a = b * o + o'` with `o' < b`. -/
instance : has_mod ordinal := ⟨λ a b, a - b * (a / b)⟩
theorem mod_def (a b : ordinal) : a % b = a - b * (a / b) := rfl
@[simp] theorem mod_zero (a : ordinal) : a % 0 = a :=
by simp only [mod_def, div_zero, zero_mul, sub_zero]
theorem mod_eq_of_lt {a b : ordinal} (h : a < b) : a % b = a :=
by simp only [mod_def, div_eq_zero_of_lt h, mul_zero, sub_zero]
@[simp] theorem zero_mod (b : ordinal) : 0 % b = 0 :=
by simp only [mod_def, zero_div, mul_zero, sub_self]
theorem div_add_mod (a b : ordinal) : b * (a / b) + a % b = a :=
add_sub_cancel_of_le $ mul_div_le _ _
theorem mod_lt (a) {b : ordinal} (h : b ≠ 0) : a % b < b :=
(add_lt_add_iff_left (b * (a / b))).1 $
by rw div_add_mod; exact lt_mul_div_add a h
@[simp] theorem mod_self (a : ordinal) : a % a = 0 :=
if a0 : a = 0 then by simp only [a0, zero_mod] else
by simp only [mod_def, div_self a0, mul_one, sub_self]
@[simp] theorem mod_one (a : ordinal) : a % 1 = 0 :=
by simp only [mod_def, div_one, one_mul, sub_self]
end ordinal
namespace cardinal
open ordinal
/-- The ordinal corresponding to a cardinal `c` is the least ordinal
whose cardinal is `c`. -/
def ord (c : cardinal) : ordinal :=
begin
let ι := λ α, {r // is_well_order α r},
have : Π α, ι α := λ α, ⟨well_ordering_rel, by apply_instance⟩,
let F := λ α, ordinal.min ⟨this _⟩ (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧),
refine quot.lift_on c F _,
suffices : ∀ {α β}, α ≈ β → F α ≤ F β,
from λ α β h, le_antisymm (this h) (this (setoid.symm h)),
intros α β h, cases h with f, refine ordinal.le_min.2 (λ i, _),
haveI := @order_embedding.is_well_order _ _
(f ⁻¹'o i.1) _ ↑(order_iso.preimage f i.1) i.2,
rw ← show type (f ⁻¹'o i.1) = ⟦⟨β, i.1, i.2⟩⟧, from
quot.sound ⟨order_iso.preimage f i.1⟩,
exact ordinal.min_le (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧) ⟨_, _⟩
end
@[nolint def_lemma doc_blame] -- TODO: This should be a theorem but Lean fails to synthesize the placeholder
def ord_eq_min (α : Type u) : ord (mk α) =
@ordinal.min _ _ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) := rfl
theorem ord_eq (α) : ∃ (r : α → α → Prop) [wo : is_well_order α r],
ord (mk α) = @type α r wo :=
let ⟨⟨r, wo⟩, h⟩ := @ordinal.min_eq {r // is_well_order α r}
⟨⟨well_ordering_rel, by apply_instance⟩⟩
(λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) in
⟨r, wo, h⟩
theorem ord_le_type (r : α → α → Prop) [is_well_order α r] : ord (mk α) ≤ ordinal.type r :=
@ordinal.min_le {r // is_well_order α r}
⟨⟨well_ordering_rel, by apply_instance⟩⟩
(λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) ⟨r, _⟩
theorem ord_le {c o} : ord c ≤ o ↔ c ≤ o.card :=
quotient.induction_on c $ λ α, induction_on o $ λ β s _,
let ⟨r, _, e⟩ := ord_eq α in begin
resetI, simp only [mk_def, card_type], split; intro h,
{ rw e at h, exact let ⟨f⟩ := h in ⟨f.to_embedding⟩ },
{ cases h with f,
have g := order_embedding.preimage f s,
haveI := order_embedding.is_well_order g,
exact le_trans (ord_le_type _) (type_le'.2 ⟨g⟩) }
end
theorem lt_ord {c o} : o < ord c ↔ o.card < c :=
by rw [← not_le, ← not_le, ord_le]
@[simp] theorem card_ord (c) : (ord c).card = c :=
quotient.induction_on c $ λ α,
let ⟨r, _, e⟩ := ord_eq α in by simp only [mk_def, e, card_type]
theorem ord_card_le (o : ordinal) : o.card.ord ≤ o :=
ord_le.2 (le_refl _)
lemma lt_ord_succ_card (o : ordinal) : o < o.card.succ.ord :=
by { rw [lt_ord], apply cardinal.lt_succ_self }
@[simp] theorem ord_le_ord {c₁ c₂} : ord c₁ ≤ ord c₂ ↔ c₁ ≤ c₂ :=
by simp only [ord_le, card_ord]
@[simp] theorem ord_lt_ord {c₁ c₂} : ord c₁ < ord c₂ ↔ c₁ < c₂ :=
by simp only [lt_ord, card_ord]
@[simp] theorem ord_zero : ord 0 = 0 :=
le_antisymm (ord_le.2 $ zero_le _) (ordinal.zero_le _)
@[simp] theorem ord_nat (n : ℕ) : ord n = n :=
le_antisymm (ord_le.2 $ by simp only [card_nat]) $ begin
induction n with n IH,
{ apply ordinal.zero_le },
{ exact (@ordinal.succ_le n _).2 (lt_of_le_of_lt IH $
ord_lt_ord.2 $ nat_cast_lt.2 (nat.lt_succ_self n)) }
end
@[simp] theorem lift_ord (c) : (ord c).lift = ord (lift c) :=
eq_of_forall_ge_iff $ λ o, le_iff_le_iff_lt_iff_lt.2 $ begin
split; intro h,
{ rcases ordinal.lt_lift_iff.1 h with ⟨a, e, h⟩,
rwa [← e, lt_ord, ← lift_card, lift_lt, ← lt_ord] },
{ rw lt_ord at h,
rcases lift_down' (le_of_lt h) with ⟨o, rfl⟩,
rw [← lift_card, lift_lt] at h,
rwa [ordinal.lift_lt, lt_ord] }
end
lemma mk_ord_out (c : cardinal) : mk c.ord.out.α = c :=
by rw [←card_type c.ord.out.r, type_out, card_ord]
lemma card_typein_lt (r : α → α → Prop) [is_well_order α r] (x : α)
(h : ord (mk α) = type r) : card (typein r x) < mk α :=
by { rw [←ord_lt_ord, h], refine lt_of_le_of_lt (ord_card_le _) (typein_lt_type r x) }
lemma card_typein_out_lt (c : cardinal) (x : c.ord.out.α) : card (typein c.ord.out.r x) < c :=
by { convert card_typein_lt c.ord.out.r x _, rw [mk_ord_out], rw [type_out, mk_ord_out] }
lemma ord_injective : injective ord :=
by { intros c c' h, rw [←card_ord c, ←card_ord c', h] }
def ord.order_embedding : @order_embedding cardinal ordinal (<) (<) :=
order_embedding.of_monotone cardinal.ord $ λ a b, cardinal.ord_lt_ord.2
@[simp] theorem ord.order_embedding_coe :
(ord.order_embedding : cardinal → ordinal) = ord := rfl
/-- The cardinal `univ` is the cardinality of ordinal `univ`, or
equivalently the cardinal of `ordinal.{u}`, or `cardinal.{u}`,
as an element of `cardinal.{v}` (when `u < v`). -/
def univ := lift.{(u+1) v} (mk ordinal)
theorem univ_id : univ.{u (u+1)} = mk ordinal := lift_id _
@[simp] theorem lift_univ : lift.{_ w} univ.{u v} = univ.{u (max v w)} := lift_lift _
theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _
theorem lift_lt_univ (c : cardinal) : lift.{u (u+1)} c < univ.{u (u+1)} :=
by simpa only [lift.principal_seg_coe, lift_ord, lift_succ, ord_le, succ_le] using le_of_lt
(lift.principal_seg.{u (u+1)}.lt_top (succ c).ord)
theorem lift_lt_univ' (c : cardinal) : lift.{u (max (u+1) v)} c < univ.{u v} :=
by simpa only [lift_lift, lift_univ, univ_umax] using
lift_lt.{_ (max (u+1) v)}.2 (lift_lt_univ c)
@[simp] theorem ord_univ : ord univ.{u v} = ordinal.univ.{u v} :=
le_antisymm (ord_card_le _) $ le_of_forall_lt $ λ o h,
lt_ord.2 begin
rcases lift.principal_seg.{u v}.down'.1
(by simpa only [lift.principal_seg_coe] using h) with ⟨o', rfl⟩,
simp only [lift.principal_seg_coe], rw [← lift_card],
apply lift_lt_univ'
end
theorem lt_univ {c} : c < univ.{u (u+1)} ↔ ∃ c', c = lift.{u (u+1)} c' :=
⟨λ h, begin
have := ord_lt_ord.2 h,
rw ord_univ at this,
cases lift.principal_seg.{u (u+1)}.down'.1
(by simpa only [lift.principal_seg_top]) with o e,
have := card_ord c,
rw [← e, lift.principal_seg_coe, ← lift_card] at this,
exact ⟨_, this.symm⟩
end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ _⟩
theorem lt_univ' {c} : c < univ.{u v} ↔ ∃ c', c = lift.{u (max (u+1) v)} c' :=
⟨λ h, let ⟨a, e, h'⟩ := lt_lift_iff.1 h in begin
rw [← univ_id] at h',
rcases lt_univ.{u}.1 h' with ⟨c', rfl⟩,
exact ⟨c', by simp only [e.symm, lift_lift]⟩
end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ' _⟩
end cardinal
namespace ordinal
@[simp] theorem card_univ : card univ = cardinal.univ := rfl
/-- The supremum of a family of ordinals -/
def sup {ι} (f : ι → ordinal) : ordinal :=
omin {c | ∀ i, f i ≤ c}
⟨(sup (cardinal.succ ∘ card ∘ f)).ord, λ i, le_of_lt $
cardinal.lt_ord.2 (lt_of_lt_of_le (cardinal.lt_succ_self _) (le_sup _ _))⟩
theorem le_sup {ι} (f : ι → ordinal) : ∀ i, f i ≤ sup f :=
omin_mem {c | ∀ i, f i ≤ c} _
theorem sup_le {ι} {f : ι → ordinal} {a} : sup f ≤ a ↔ ∀ i, f i ≤ a :=
⟨λ h i, le_trans (le_sup _ _) h, λ h, omin_le h⟩
theorem lt_sup {ι} {f : ι → ordinal} {a} : a < sup f ↔ ∃ i, a < f i :=
by simpa only [not_forall, not_le] using not_congr (@sup_le _ f a)
theorem is_normal.sup {f} (H : is_normal f)
{ι} {g : ι → ordinal} (h : nonempty ι) : f (sup g) = sup (f ∘ g) :=
eq_of_forall_ge_iff $ λ a,
by rw [sup_le, comp, H.le_set' (λ_:ι, true) g (let ⟨i⟩ := h in ⟨i, ⟨⟩⟩)];
intros; simp only [sup_le, true_implies_iff]
theorem sup_ord {ι} (f : ι → cardinal) : sup (λ i, (f i).ord) = (cardinal.sup f).ord :=
eq_of_forall_ge_iff $ λ a, by simp only [sup_le, cardinal.ord_le, cardinal.sup_le]
lemma sup_succ {ι} (f : ι → ordinal) : sup (λ i, succ (f i)) ≤ succ (sup f) :=
by { rw [ordinal.sup_le], intro i, rw ordinal.succ_le_succ, apply ordinal.le_sup }
lemma unbounded_range_of_sup_ge {α β : Type u} (r : α → α → Prop) [is_well_order α r] (f : β → α)
(h : sup.{u u} (typein r ∘ f) ≥ type r) : unbounded r (range f) :=
begin
apply (not_bounded_iff _).mp, rintro ⟨x, hx⟩, apply not_lt_of_ge h,
refine lt_of_le_of_lt _ (typein_lt_type r x), rw [sup_le], intro y,
apply le_of_lt, rw typein_lt_typein, apply hx, apply mem_range_self
end
/-- The supremum of a family of ordinals indexed by the set
of ordinals less than some `o : ordinal.{u}`.
(This is not a special case of `sup` over the subtype,
because `{a // a < o} : Type (u+1)` and `sup` only works over
families in `Type u`.) -/
def bsup (o : ordinal.{u}) : (Π a < o, ordinal.{max u v}) → ordinal.{max u v} :=
match o, o.out, o.out_eq with
| _, ⟨α, r, _⟩, rfl, f := by exactI sup (λ a, f (typein r a) (typein_lt_type _ _))
end
theorem bsup_le {o f a} : bsup.{u v} o f ≤ a ↔ ∀ i h, f i h ≤ a :=
match o, o.out, o.out_eq, f :
∀ o w (e : ⟦w⟧ = o) (f : Π (a : ordinal.{u}), a < o → ordinal.{(max u v)}),
bsup._match_1 o w e f ≤ a ↔ ∀ i h, f i h ≤ a with
| _, ⟨α, r, _⟩, rfl, f := by rw [bsup._match_1, sup_le]; exactI
⟨λ H i h, by simpa only [typein_enum] using H (enum r i h), λ H b, H _ _⟩
end
theorem bsup_type (r : α → α → Prop) [is_well_order α r] (f) :
bsup (type r) f = sup (λ a, f (typein r a) (typein_lt_type _ _)) :=
eq_of_forall_ge_iff $ λ o,
by rw [bsup_le, sup_le]; exact
⟨λ H b, H _ _, λ H i h, by simpa only [typein_enum] using H (enum r i h)⟩
theorem le_bsup {o} (f : Π a < o, ordinal) (i h) : f i h ≤ bsup o f :=
bsup_le.1 (le_refl _) _ _
theorem lt_bsup {o : ordinal} {f : Π a < o, ordinal}
(hf : ∀{a a'} (ha : a < o) (ha' : a' < o), a < a' → f a ha < f a' ha')
(ho : o.is_limit) (i h) : f i h < bsup o f :=
lt_of_lt_of_le (hf _ _ $ lt_succ_self i) (le_bsup f i.succ $ ho.2 _ h)
theorem bsup_id {o} (ho : is_limit o) : bsup.{u u} o (λ x _, x) = o :=
begin
apply le_antisymm, rw [bsup_le], intro i, apply le_of_lt,
rw [←not_lt], intro h, apply lt_irrefl (bsup.{u u} o (λ x _, x)),
apply lt_of_le_of_lt _ (lt_bsup _ ho _ h), refl, intros, assumption
end
theorem is_normal.bsup {f} (H : is_normal f)
{o : ordinal} : ∀ (g : Π a < o, ordinal) (h : o ≠ 0),
f (bsup o g) = bsup o (λ a h, f (g a h)) :=
induction_on o $ λ α r _ g h,
by resetI; rw [bsup_type,
H.sup (type_ne_zero_iff_nonempty.1 h), bsup_type]
theorem is_normal.bsup_eq {f} (H : is_normal f) {o : ordinal} (h : is_limit o) :
bsup.{u} o (λx _, f x) = f o :=
by { rw [←is_normal.bsup.{u u} H (λ x _, x) h.1, bsup_id h] }
/-- The ordinal exponential, defined by transfinite recursion. -/
def power (a b : ordinal) : ordinal :=
if a = 0 then 1 - b else
limit_rec_on b 1 (λ _ IH, IH * a) (λ b _, bsup.{u u} b)
instance : has_pow ordinal ordinal := ⟨power⟩
local infixr ^ := @pow ordinal ordinal ordinal.has_pow
theorem zero_power' (a : ordinal) : 0 ^ a = 1 - a :=
by simp only [pow, power, if_pos rfl]
@[simp] theorem zero_power {a : ordinal} (a0 : a ≠ 0) : 0 ^ a = 0 :=
by rwa [zero_power', sub_eq_zero_iff_le, one_le_iff_ne_zero]
@[simp] theorem power_zero (a : ordinal) : a ^ 0 = 1 :=
by by_cases a = 0; [simp only [pow, power, if_pos h, sub_zero],
simp only [pow, power, if_neg h, limit_rec_on_zero]]
@[simp] theorem power_succ (a b : ordinal) : a ^ succ b = a ^ b * a :=
if h : a = 0 then by subst a; simp only [zero_power (succ_ne_zero _), mul_zero]
else by simp only [pow, power, limit_rec_on_succ, if_neg h]
theorem power_limit {a b : ordinal} (a0 : a ≠ 0) (h : is_limit b) :
a ^ b = bsup.{u u} b (λ c _, a ^ c) :=
by simp only [pow, power, if_neg a0]; rw limit_rec_on_limit _ _ _ _ h; refl
theorem power_le_of_limit {a b c : ordinal} (a0 : a ≠ 0) (h : is_limit b) :
a ^ b ≤ c ↔ ∀ b' < b, a ^ b' ≤ c :=
by rw [power_limit a0 h, bsup_le]
theorem lt_power_of_limit {a b c : ordinal} (b0 : b ≠ 0) (h : is_limit c) :
a < b ^ c ↔ ∃ c' < c, a < b ^ c' :=
by rw [← not_iff_not, not_exists]; simp only [not_lt, power_le_of_limit b0 h, exists_prop, not_and]
@[simp] theorem power_one (a : ordinal) : a ^ 1 = a :=
by rw [← succ_zero, power_succ]; simp only [power_zero, one_mul]
@[simp] theorem one_power (a : ordinal) : 1 ^ a = 1 :=
begin
apply limit_rec_on a,
{ simp only [power_zero] },
{ intros _ ih, simp only [power_succ, ih, mul_one] },
refine λ b l IH, eq_of_forall_ge_iff (λ c, _),
rw [power_le_of_limit one_ne_zero l],
exact ⟨λ H, by simpa only [power_zero] using H 0 l.pos,
λ H b' h, by rwa IH _ h⟩,
end
theorem power_pos {a : ordinal} (b)
(a0 : 0 < a) : 0 < a ^ b :=
begin
have h0 : 0 < a ^ 0, {simp only [power_zero, zero_lt_one]},
apply limit_rec_on b,
{ exact h0 },
{ intros b IH, rw [power_succ],
exact mul_pos IH a0 },
{ exact λ b l _, (lt_power_of_limit (pos_iff_ne_zero.1 a0) l).2
⟨0, l.pos, h0⟩ },
end
theorem power_ne_zero {a : ordinal} (b)
(a0 : a ≠ 0) : a ^ b ≠ 0 :=
pos_iff_ne_zero.1 $ power_pos b $ pos_iff_ne_zero.2 a0
theorem power_is_normal {a : ordinal} (h : 1 < a) : is_normal ((^) a) :=
have a0 : 0 < a, from lt_trans zero_lt_one h,
⟨λ b, by simpa only [mul_one, power_succ] using
(mul_lt_mul_iff_left (power_pos b a0)).2 h,
λ b l c, power_le_of_limit (ne_of_gt a0) l⟩
theorem power_lt_power_iff_right {a b c : ordinal}
(a1 : 1 < a) : a ^ b < a ^ c ↔ b < c :=
(power_is_normal a1).lt_iff
theorem power_le_power_iff_right {a b c : ordinal}
(a1 : 1 < a) : a ^ b ≤ a ^ c ↔ b ≤ c :=
(power_is_normal a1).le_iff
theorem power_right_inj {a b c : ordinal}
(a1 : 1 < a) : a ^ b = a ^ c ↔ b = c :=
(power_is_normal a1).inj
theorem power_is_limit {a b : ordinal}
(a1 : 1 < a) : is_limit b → is_limit (a ^ b) :=
(power_is_normal a1).is_limit
theorem power_is_limit_left {a b : ordinal}
(l : is_limit a) (hb : b ≠ 0) : is_limit (a ^ b) :=
begin
rcases zero_or_succ_or_limit b with e|⟨b,rfl⟩|l',
{ exact absurd e hb },
{ rw power_succ,
exact mul_is_limit (power_pos _ l.pos) l },
{ exact power_is_limit l.one_lt l' }
end
theorem power_le_power_right {a b c : ordinal}
(h₁ : 0 < a) (h₂ : b ≤ c) : a ^ b ≤ a ^ c :=
begin
cases lt_or_eq_of_le (one_le_iff_pos.2 h₁) with h₁ h₁,
{ exact (power_le_power_iff_right h₁).2 h₂ },
{ subst a, simp only [one_power] }
end
theorem power_le_power_left {a b : ordinal} (c)
(ab : a ≤ b) : a ^ c ≤ b ^ c :=
begin
by_cases a0 : a = 0,
{ subst a, by_cases c0 : c = 0,
{ subst c, simp only [power_zero] },
{ simp only [zero_power c0, zero_le] } },
{ apply limit_rec_on c,
{ simp only [power_zero] },
{ intros c IH, simpa only [power_succ] using mul_le_mul IH ab },
{ exact λ c l IH, (power_le_of_limit a0 l).2
(λ b' h, le_trans (IH _ h) (power_le_power_right
(lt_of_lt_of_le (pos_iff_ne_zero.2 a0) ab) (le_of_lt h))) } }
end
theorem le_power_self {a : ordinal} (b) (a1 : 1 < a) : b ≤ a ^ b :=
(power_is_normal a1).le_self _
theorem power_lt_power_left_of_succ {a b c : ordinal}
(ab : a < b) : a ^ succ c < b ^ succ c :=
by rw [power_succ, power_succ]; exact
lt_of_le_of_lt
(mul_le_mul_right _ $ power_le_power_left _ $ le_of_lt ab)
(mul_lt_mul_of_pos_left ab (power_pos _ (lt_of_le_of_lt (zero_le _) ab)))
theorem power_add (a b c : ordinal) : a ^ (b + c) = a ^ b * a ^ c :=
begin
by_cases a0 : a = 0,
{ subst a,
by_cases c0 : c = 0, {simp only [c0, add_zero, power_zero, mul_one]},
have : b+c ≠ 0 := ne_of_gt (lt_of_lt_of_le
(pos_iff_ne_zero.2 c0) (le_add_left _ _)),
simp only [zero_power c0, zero_power this, mul_zero] },
cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1,
{ subst a1, simp only [one_power, mul_one] },
apply limit_rec_on c,
{ simp only [add_zero, power_zero, mul_one] },
{ intros c IH,
rw [add_succ, power_succ, IH, power_succ, mul_assoc] },
{ intros c l IH,
refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans
(add_is_normal b)).limit_le l).trans _),
simp only [IH] {contextual := tt},
exact (((mul_is_normal $ power_pos b (pos_iff_ne_zero.2 a0)).trans
(power_is_normal a1)).limit_le l).symm }
end
theorem power_dvd_power (a) {b c : ordinal}
(h : b ≤ c) : a ^ b ∣ a ^ c :=
by rw [← add_sub_cancel_of_le h, power_add]; apply dvd_mul
theorem power_dvd_power_iff {a b c : ordinal}
(a1 : 1 < a) : a ^ b ∣ a ^ c ↔ b ≤ c :=
⟨λ h, le_of_not_lt $ λ hn,
not_le_of_lt ((power_lt_power_iff_right a1).2 hn) $
le_of_dvd (power_ne_zero _ $ one_le_iff_ne_zero.1 $ le_of_lt a1) h,
power_dvd_power _⟩
theorem power_mul (a b c : ordinal) : a ^ (b * c) = (a ^ b) ^ c :=
begin
by_cases b0 : b = 0, {simp only [b0, zero_mul, power_zero, one_power]},
by_cases a0 : a = 0,
{ subst a,
by_cases c0 : c = 0, {simp only [c0, mul_zero, power_zero]},
simp only [zero_power b0, zero_power c0, zero_power (mul_ne_zero b0 c0)] },
cases eq_or_lt_of_le (one_le_iff_ne_zero.2 a0) with a1 a1,
{ subst a1, simp only [one_power] },
apply limit_rec_on c,
{ simp only [mul_zero, power_zero] },
{ intros c IH,
rw [mul_succ, power_add, IH, power_succ] },
{ intros c l IH,
refine eq_of_forall_ge_iff (λ d, (((power_is_normal a1).trans
(mul_is_normal (pos_iff_ne_zero.2 b0))).limit_le l).trans _),
simp only [IH] {contextual := tt},
exact (power_le_of_limit (power_ne_zero _ a0) l).symm }
end
/-- The ordinal logarithm is the solution `u` to the equation
`x = b ^ u * v + w` where `v < b` and `w < b`. -/
def log (b : ordinal) (x : ordinal) : ordinal :=
if h : 1 < b then pred $
omin {o | x < b^o} ⟨succ x, succ_le.1 (le_power_self _ h)⟩
else 0
@[simp] theorem log_not_one_lt {b : ordinal} (b1 : ¬ 1 < b) (x : ordinal) : log b x = 0 :=
by simp only [log, dif_neg b1]
theorem log_def {b : ordinal} (b1 : 1 < b) (x : ordinal) : log b x =
pred (omin {o | x < b^o} (log._proof_1 b x b1)) :=
by simp only [log, dif_pos b1]
@[simp] theorem log_zero (b : ordinal) : log b 0 = 0 :=
if b1 : 1 < b then
by rw [log_def b1, ← le_zero, pred_le];
apply omin_le; change 0<b^succ 0;
rw [succ_zero, power_one];
exact lt_trans zero_lt_one b1
else by simp only [log_not_one_lt b1]
theorem succ_log_def {b x : ordinal} (b1 : 1 < b) (x0 : 0 < x) : succ (log b x) =
omin {o | x < b^o} (log._proof_1 b x b1) :=
begin
let t := omin {o | x < b^o} (log._proof_1 b x b1),
have : x < b ^ t := omin_mem {o | x < b^o} _,
rcases zero_or_succ_or_limit t with h|h|h,
{ refine (not_lt_of_le (one_le_iff_pos.2 x0) _).elim,
simpa only [h, power_zero] },
{ rw [show log b x = pred t, from log_def b1 x,
succ_pred_iff_is_succ.2 h] },
{ rcases (lt_power_of_limit (ne_of_gt $ lt_trans zero_lt_one b1) h).1 this with ⟨a, h₁, h₂⟩,
exact (not_le_of_lt h₁).elim (le_omin.1 (le_refl t) a h₂) }
end
theorem lt_power_succ_log {b : ordinal} (b1 : 1 < b) (x : ordinal) :
x < b ^ succ (log b x) :=
begin
cases lt_or_eq_of_le (zero_le x) with x0 x0,
{ rw [succ_log_def b1 x0], exact omin_mem {o | x < b^o} _ },
{ subst x, apply power_pos _ (lt_trans zero_lt_one b1) }
end
theorem power_log_le (b) {x : ordinal} (x0 : 0 < x) :
b ^ log b x ≤ x :=
begin
by_cases b0 : b = 0,
{ rw [b0, zero_power'],
refine le_trans (sub_le_self _ _) (one_le_iff_pos.2 x0) },
cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1,
{ refine le_of_not_lt (λ h, not_le_of_lt (lt_succ_self (log b x)) _),
have := @omin_le {o | x < b^o} _ _ h,
rwa ← succ_log_def b1 x0 at this },
{ rw [← b1, one_power], exact one_le_iff_pos.2 x0 }
end
theorem le_log {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) :
c ≤ log b x ↔ b ^ c ≤ x :=
⟨λ h, le_trans ((power_le_power_iff_right b1).2 h) (power_log_le b x0),
λ h, le_of_not_lt $ λ hn,
not_le_of_lt (lt_power_succ_log b1 x) $
le_trans ((power_le_power_iff_right b1).2 (succ_le.2 hn)) h⟩
theorem log_lt {b x c : ordinal} (b1 : 1 < b) (x0 : 0 < x) :
log b x < c ↔ x < b ^ c :=
lt_iff_lt_of_le_iff_le (le_log b1 x0)
theorem log_le_log (b) {x y : ordinal} (xy : x ≤ y) :
log b x ≤ log b y :=
if x0 : x = 0 then by simp only [x0, log_zero, zero_le] else
have x0 : 0 < x, from pos_iff_ne_zero.2 x0,
if b1 : 1 < b then
(le_log b1 (lt_of_lt_of_le x0 xy)).2 $ le_trans (power_log_le _ x0) xy
else by simp only [log_not_one_lt b1, zero_le]
theorem log_le_self (b x : ordinal) : log b x ≤ x :=
if x0 : x = 0 then by simp only [x0, log_zero, zero_le] else
if b1 : 1 < b then
le_trans (le_power_self _ b1) (power_log_le b (pos_iff_ne_zero.2 x0))
else by simp only [log_not_one_lt b1, zero_le]
@[simp] theorem nat_cast_mul {m n : ℕ} : ((m * n : ℕ) : ordinal) = m * n :=
by induction n with n IH; [simp only [nat.cast_zero, nat.mul_zero, mul_zero],
rw [nat.mul_succ, nat.cast_add, IH, nat.cast_succ, mul_add_one]]
@[simp] theorem nat_cast_power {m n : ℕ} : ((pow m n : ℕ) : ordinal) = m ^ n :=
by induction n with n IH; [simp only [nat.pow_zero, nat.cast_zero, power_zero, nat.cast_one],
rw [nat.pow_succ, nat_cast_mul, IH, nat.cast_succ, ← succ_eq_add_one, power_succ]]
@[simp] theorem nat_cast_le {m n : ℕ} : (m : ordinal) ≤ n ↔ m ≤ n :=
by rw [← cardinal.ord_nat, ← cardinal.ord_nat,
cardinal.ord_le_ord, cardinal.nat_cast_le]
@[simp] theorem nat_cast_lt {m n : ℕ} : (m : ordinal) < n ↔ m < n :=
by simp only [lt_iff_le_not_le, nat_cast_le]
@[simp] theorem nat_cast_inj {m n : ℕ} : (m : ordinal) = n ↔ m = n :=
by simp only [le_antisymm_iff, nat_cast_le]
@[simp] theorem nat_cast_eq_zero {n : ℕ} : (n : ordinal) = 0 ↔ n = 0 :=
@nat_cast_inj n 0
theorem nat_cast_ne_zero {n : ℕ} : (n : ordinal) ≠ 0 ↔ n ≠ 0 :=
not_congr nat_cast_eq_zero
@[simp] theorem nat_cast_pos {n : ℕ} : (0 : ordinal) < n ↔ 0 < n :=
@nat_cast_lt 0 n
@[simp] theorem nat_cast_sub {m n : ℕ} : ((m - n : ℕ) : ordinal) = m - n :=
(_root_.le_total m n).elim
(λ h, by rw [nat.sub_eq_zero_iff_le.2 h, sub_eq_zero_iff_le.2 (nat_cast_le.2 h)]; refl)
(λ h, (add_left_cancel n).1 $ by rw [← nat.cast_add,
nat.add_sub_cancel' h, add_sub_cancel_of_le (nat_cast_le.2 h)])
@[simp] theorem nat_cast_div {m n : ℕ} : ((m / n : ℕ) : ordinal) = m / n :=
if n0 : n = 0 then by simp only [n0, nat.div_zero, nat.cast_zero, div_zero] else
have n0':_, from nat_cast_ne_zero.2 n0,
le_antisymm
(by rw [le_div n0', ← nat_cast_mul, nat_cast_le, mul_comm];
apply nat.div_mul_le_self)
(by rw [div_le n0', succ, ← nat.cast_succ, ← nat_cast_mul,
nat_cast_lt, mul_comm, ← nat.div_lt_iff_lt_mul _ _ (nat.pos_of_ne_zero n0)];
apply nat.lt_succ_self)
@[simp] theorem nat_cast_mod {m n : ℕ} : ((m % n : ℕ) : ordinal) = m % n :=
by rw [← add_left_cancel (n*(m/n)), div_add_mod, ← nat_cast_div, ← nat_cast_mul, ← nat.cast_add,
add_comm, nat.mod_add_div]
@[simp] theorem nat_le_card {o} {n : ℕ} : (n : cardinal) ≤ card o ↔ (n : ordinal) ≤ o :=
⟨λ h, by rwa [← cardinal.ord_le, cardinal.ord_nat] at h,
λ h, card_nat n ▸ card_le_card h⟩
@[simp] theorem nat_lt_card {o} {n : ℕ} : (n : cardinal) < card o ↔ (n : ordinal) < o :=
by rw [← succ_le, ← cardinal.succ_le, ← cardinal.nat_succ, nat_le_card]; refl
@[simp] theorem card_lt_nat {o} {n : ℕ} : card o < n ↔ o < n :=
lt_iff_lt_of_le_iff_le nat_le_card
@[simp] theorem card_le_nat {o} {n : ℕ} : card o ≤ n ↔ o ≤ n :=
le_iff_le_iff_lt_iff_lt.2 nat_lt_card
@[simp] theorem card_eq_nat {o} {n : ℕ} : card o = n ↔ o = n :=
by simp only [le_antisymm_iff, card_le_nat, nat_le_card]
@[simp] theorem type_fin (n : ℕ) : @type (fin n) (<) _ = n :=
by rw [← card_eq_nat, card_type, mk_fin]
@[simp] theorem lift_nat_cast (n : ℕ) : lift n = n :=
by induction n with n ih; [simp only [nat.cast_zero, lift_zero],
simp only [nat.cast_succ, lift_add, ih, lift_one]]
theorem lift_type_fin (n : ℕ) : lift (@type (fin n) (<) _) = n :=
by simp only [type_fin, lift_nat_cast]
theorem fintype_card (r : α → α → Prop) [is_well_order α r] [fintype α] : type r = fintype.card α :=
by rw [← card_eq_nat, card_type, fintype_card]
end ordinal
namespace cardinal
open ordinal
@[simp] theorem ord_omega : ord.{u} omega = ordinal.omega :=
le_antisymm (ord_le.2 $ le_refl _) $
le_of_forall_lt $ λ o h, begin
rcases ordinal.lt_lift_iff.1 h with ⟨o, rfl, h'⟩,
rw [lt_ord, ← lift_card, ← lift_omega.{0 u},
lift_lt, ← typein_enum (<) h'],
exact lt_omega_iff_fintype.2 ⟨set.fintype_lt_nat _⟩
end
@[simp] theorem add_one_of_omega_le {c} (h : omega ≤ c) : c + 1 = c :=
by rw [add_comm, ← card_ord c, ← card_one,
← card_add, one_add_of_omega_le];
rwa [← ord_omega, ord_le_ord]
end cardinal
namespace ordinal
theorem lt_omega {o : ordinal.{u}} : o < omega ↔ ∃ n : ℕ, o = n :=
by rw [← cardinal.ord_omega, cardinal.lt_ord, lt_omega]; simp only [card_eq_nat]
theorem nat_lt_omega (n : ℕ) : (n : ordinal) < omega :=
lt_omega.2 ⟨_, rfl⟩
theorem omega_pos : 0 < omega := nat_lt_omega 0
theorem omega_ne_zero : omega ≠ 0 := ne_of_gt omega_pos
theorem one_lt_omega : 1 < omega := by simpa only [nat.cast_one] using nat_lt_omega 1
theorem omega_is_limit : is_limit omega :=
⟨omega_ne_zero, λ o h,
let ⟨n, e⟩ := lt_omega.1 h in
by rw [e]; exact nat_lt_omega (n+1)⟩
theorem omega_le {o : ordinal.{u}} : omega ≤ o ↔ ∀ n : ℕ, (n : ordinal) ≤ o :=
⟨λ h n, le_trans (le_of_lt (nat_lt_omega _)) h,
λ H, le_of_forall_lt $ λ a h,
let ⟨n, e⟩ := lt_omega.1 h in
by rw [e, ← succ_le]; exact H (n+1)⟩
theorem nat_lt_limit {o} (h : is_limit o) : ∀ n : ℕ, (n : ordinal) < o
| 0 := lt_of_le_of_ne (zero_le o) h.1.symm
| (n+1) := h.2 _ (nat_lt_limit n)
theorem omega_le_of_is_limit {o} (h : is_limit o) : omega ≤ o :=
omega_le.2 $ λ n, le_of_lt $ nat_lt_limit h n
theorem add_omega {a : ordinal} (h : a < omega) : a + omega = omega :=
begin
rcases lt_omega.1 h with ⟨n, rfl⟩,
clear h, induction n with n IH,
{ rw [nat.cast_zero, zero_add] },
{ rw [nat.cast_succ, add_assoc, one_add_of_omega_le (le_refl _), IH] }
end
theorem add_lt_omega {a b : ordinal} (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
theorem mul_lt_omega {a b : ordinal} (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
theorem is_limit_iff_omega_dvd {a : ordinal} : is_limit a ↔ a ≠ 0 ∧ omega ∣ a :=
begin
refine ⟨λ l, ⟨l.1, ⟨a / omega, le_antisymm _ (mul_div_le _ _)⟩⟩, λ h, _⟩,
{ refine (limit_le l).2 (λ x hx, le_of_lt _),
rw [← div_lt omega_ne_zero, ← succ_le, le_div omega_ne_zero,
mul_succ, add_le_of_limit omega_is_limit],
intros b hb,
rcases lt_omega.1 hb with ⟨n, rfl⟩,
exact le_trans (add_le_add_right (mul_div_le _ _) _)
(le_of_lt $ lt_sub.1 $ nat_lt_limit (sub_is_limit l hx) _) },
{ rcases h with ⟨a0, b, rfl⟩,
refine mul_is_limit_left omega_is_limit
(pos_iff_ne_zero.2 $ mt _ a0),
intro e, simp only [e, mul_zero] }
end
local infixr ^ := @pow ordinal ordinal ordinal.has_pow
theorem power_lt_omega {a b : ordinal} (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_power]; apply nat_lt_omega
end
theorem add_omega_power {a b : ordinal} (h : a < omega ^ b) : a + omega ^ b = omega ^ b :=
begin
refine le_antisymm _ (le_add_left _ _),
revert h, apply limit_rec_on b,
{ intro h, rw [power_zero, ← succ_zero, lt_succ, le_zero] at h,
rw [h, zero_add] },
{ intros b _ h, rw [power_succ] at h,
rcases (lt_mul_of_limit omega_is_limit).1 h with ⟨x, xo, ax⟩,
refine le_trans (add_le_add_right (le_of_lt ax) _) _,
rw [power_succ, ← mul_add, add_omega xo] },
{ intros b l IH h, rcases (lt_power_of_limit omega_ne_zero l).1 h with ⟨x, xb, ax⟩,
refine (((add_is_normal a).trans (power_is_normal one_lt_omega))
.limit_le l).2 (λ y yb, _),
let z := max x y,
have := IH z (max_lt xb yb)
(lt_of_lt_of_le ax $ power_le_power_right omega_pos (le_max_left _ _)),
exact le_trans (add_le_add_left (power_le_power_right omega_pos (le_max_right _ _)) _)
(le_trans this (power_le_power_right omega_pos $ le_of_lt $ max_lt xb yb)) }
end
theorem add_lt_omega_power {a b c : ordinal} (h₁ : a < omega ^ c) (h₂ : b < omega ^ c) :
a + b < omega ^ c :=
by rwa [← add_omega_power h₁, add_lt_add_iff_left]
theorem add_absorp {a b c : ordinal} (h₁ : a < omega ^ b) (h₂ : omega ^ b ≤ c) : a + c = c :=
by rw [← add_sub_cancel_of_le h₂, ← add_assoc, add_omega_power h₁]
theorem add_absorp_iff {o : ordinal} (o0 : o > 0) : (∀ a < o, a + o = o) ↔ ∃ a, o = omega ^ a :=
⟨λ H, ⟨log omega o, begin
refine ((lt_or_eq_of_le (power_log_le _ o0))
.resolve_left $ λ h, _).symm,
have := H _ h,
have := lt_power_succ_log one_lt_omega o,
rw [power_succ, lt_mul_of_limit omega_is_limit] at this,
rcases this with ⟨a, ao, h'⟩,
rcases lt_omega.1 ao with ⟨n, rfl⟩, clear ao,
revert h', apply not_lt_of_le,
suffices e : omega ^ log omega o * ↑n + o = o,
{ simpa only [e] using le_add_right (omega ^ log omega o * ↑n) o },
induction n with n IH, {simp only [nat.cast_zero, mul_zero, zero_add]},
simp only [nat.cast_succ, mul_add_one, add_assoc, this, IH]
end⟩,
λ ⟨b, e⟩, e.symm ▸ λ a, add_omega_power⟩
theorem add_mul_limit_aux {a b c : ordinal} (ba : b + a = a)
(l : is_limit c)
(IH : ∀ c' < c, (a + b) * succ c' = a * succ c' + b) :
(a + b) * c = a * c :=
le_antisymm
((mul_le_of_limit l).2 $ λ c' h, begin
apply le_trans (mul_le_mul_left _ (le_of_lt $ lt_succ_self _)),
rw IH _ h,
apply le_trans (add_le_add_left _ _),
{ rw ← mul_succ, exact mul_le_mul_left _ (succ_le.2 $ l.2 _ h) },
{ rw ← ba, exact le_add_right _ _ }
end)
(mul_le_mul_right _ (le_add_right _ _))
theorem add_mul_succ {a b : ordinal} (c) (ba : b + a = a) :
(a + b) * succ c = a * succ c + b :=
begin
apply limit_rec_on c,
{ simp only [succ_zero, mul_one] },
{ intros c IH,
rw [mul_succ, IH, ← add_assoc, add_assoc _ b, ba, ← mul_succ] },
{ intros c l IH,
have := add_mul_limit_aux ba l IH,
rw [mul_succ, add_mul_limit_aux ba l IH, mul_succ, add_assoc] }
end
theorem add_mul_limit {a b c : ordinal} (ba : b + a = a)
(l : is_limit c) : (a + b) * c = a * c :=
add_mul_limit_aux ba l (λ c' _, add_mul_succ c' ba)
theorem mul_omega {a : ordinal} (a0 : 0 < a) (ha : a < omega) : a * omega = omega :=
le_antisymm
((mul_le_of_limit omega_is_limit).2 $ λ b hb, le_of_lt (mul_lt_omega ha hb))
(by simpa only [one_mul] using mul_le_mul_right omega (one_le_iff_pos.2 a0))
theorem mul_lt_omega_power {a b c : ordinal}
(c0 : 0 < c) (ha : a < omega ^ c) (hb : b < omega) : a * b < omega ^ c :=
if b0 : b = 0 then by simp only [b0, mul_zero, power_pos _ omega_pos] else begin
rcases zero_or_succ_or_limit c with rfl|⟨c,rfl⟩|l,
{ exact (lt_irrefl _).elim c0 },
{ rw power_succ at ha,
rcases ((mul_is_normal $ power_pos _ omega_pos).limit_lt
omega_is_limit).1 ha with ⟨n, hn, an⟩,
refine lt_of_le_of_lt (mul_le_mul_right _ (le_of_lt an)) _,
rw [power_succ, mul_assoc, mul_lt_mul_iff_left (power_pos _ omega_pos)],
exact mul_lt_omega hn hb },
{ rcases ((power_is_normal one_lt_omega).limit_lt l).1 ha with ⟨x, hx, ax⟩,
refine lt_of_le_of_lt (mul_le_mul (le_of_lt ax) (le_of_lt hb)) _,
rw [← power_succ, power_lt_power_iff_right one_lt_omega],
exact l.2 _ hx }
end
theorem mul_omega_dvd {a : ordinal}
(a0 : 0 < a) (ha : a < omega) : ∀ {b}, omega ∣ b → a * b = b
| _ ⟨b, rfl⟩ := by rw [← mul_assoc, mul_omega a0 ha]
theorem mul_omega_power_power {a b : ordinal} (a0 : 0 < a) (h : a < omega ^ omega ^ b) :
a * omega ^ omega ^ b = omega ^ omega ^ b :=
begin
by_cases b0 : b = 0, {rw [b0, power_zero, power_one] at h ⊢, exact mul_omega a0 h},
refine le_antisymm _ (by simpa only [one_mul] using mul_le_mul_right (omega^omega^b) (one_le_iff_pos.2 a0)),
rcases (lt_power_of_limit omega_ne_zero (power_is_limit_left omega_is_limit b0)).1 h
with ⟨x, xb, ax⟩,
refine le_trans (mul_le_mul_right _ (le_of_lt ax)) _,
rw [← power_add, add_omega_power xb]
end
theorem power_omega {a : ordinal} (a1 : 1 < a) (h : a < omega) : a ^ omega = omega :=
le_antisymm
((power_le_of_limit (one_le_iff_ne_zero.1 $ le_of_lt a1) omega_is_limit).2
(λ b hb, le_of_lt (power_lt_omega h hb)))
(le_power_self _ a1)
theorem CNF_aux {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) :
o % b ^ log b o < o :=
lt_of_lt_of_le
(mod_lt _ $ power_ne_zero _ b0)
(power_log_le _ $ pos_iff_ne_zero.2 o0)
@[elab_as_eliminator] noncomputable def CNF_rec {b : ordinal} (b0 : b ≠ 0)
{C : ordinal → Sort*}
(H0 : C 0)
(H : ∀ o, o ≠ 0 → o % b ^ log b o < o → C (o % b ^ log b o) → C o)
: ∀ o, C o
| o :=
if o0 : o = 0 then by rw o0; exact H0 else
have _, from CNF_aux b0 o0,
H o o0 this (CNF_rec (o % b ^ log b o))
using_well_founded {dec_tac := `[assumption]}
@[simp] theorem CNF_rec_zero {b} (b0) {C H0 H} : @CNF_rec b b0 C H0 H 0 = H0 :=
by rw [CNF_rec, dif_pos rfl]; refl
@[simp] theorem CNF_rec_ne_zero {b} (b0) {C H0 H o} (o0) :
@CNF_rec b b0 C H0 H o = H o o0 (CNF_aux b0 o0) (@CNF_rec b b0 C H0 H _) :=
by rw [CNF_rec, dif_neg o0]
/-- The Cantor normal form of an ordinal is the list of coefficients
in the base-`b` expansion of `o`.
CNF b (b ^ u₁ * v₁ + b ^ u₂ * v₂) = [(u₁, v₁), (u₂, v₂)] -/
def CNF (b := omega) (o : ordinal) : list (ordinal × ordinal) :=
if b0 : b = 0 then [] else
CNF_rec b0 [] (λ o o0 h IH, (log b o, o / b ^ log b o) :: IH) o
@[simp] theorem zero_CNF (o) : CNF 0 o = [] :=
dif_pos rfl
@[simp] theorem CNF_zero (b) : CNF b 0 = [] :=
if b0 : b = 0 then dif_pos b0 else
(dif_neg b0).trans $ CNF_rec_zero _
theorem CNF_ne_zero {b o : ordinal} (b0 : b ≠ 0) (o0 : o ≠ 0) :
CNF b o = (log b o, o / b ^ log b o) :: CNF b (o % b ^ log b o) :=
by unfold CNF; rw [dif_neg b0, dif_neg b0, CNF_rec_ne_zero b0 o0]
theorem one_CNF {o : ordinal} (o0 : o ≠ 0) :
CNF 1 o = [(0, o)] :=
by rw [CNF_ne_zero one_ne_zero o0, log_not_one_lt (lt_irrefl _), power_zero, mod_one, CNF_zero, div_one]
theorem CNF_foldr {b : ordinal} (b0 : b ≠ 0) (o) :
(CNF b o).foldr (λ p r, b ^ p.1 * p.2 + r) 0 = o :=
CNF_rec b0 (by rw CNF_zero; refl)
(λ o o0 h IH, by rw [CNF_ne_zero b0 o0, list.foldr_cons, IH, div_add_mod]) o
theorem CNF_pairwise_aux (b := omega) (o) :
(∀ p ∈ CNF b o, prod.fst p ≤ log b o) ∧
(CNF b o).pairwise (λ p q, q.1 < p.1) :=
begin
by_cases b0 : b = 0,
{ simp only [b0, zero_CNF, list.pairwise.nil, and_true], exact λ _, false.elim },
cases lt_or_eq_of_le (one_le_iff_ne_zero.2 b0) with b1 b1,
{ refine CNF_rec b0 _ _ o,
{ simp only [CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim },
intros o o0 H IH, cases IH with IH₁ IH₂,
simp only [CNF_ne_zero b0 o0, list.forall_mem_cons, list.pairwise_cons, IH₂, and_true],
refine ⟨⟨le_refl _, λ p m, _⟩, λ p m, _⟩,
{ exact le_trans (IH₁ p m) (log_le_log _ $ le_of_lt H) },
{ refine lt_of_le_of_lt (IH₁ p m) ((log_lt b1 _).2 _),
{ rw pos_iff_ne_zero, intro e,
rw e at m, simpa only [CNF_zero] using m },
{ exact mod_lt _ (power_ne_zero _ b0) } } },
{ by_cases o0 : o = 0,
{ simp only [o0, CNF_zero, list.pairwise.nil, and_true], exact λ _, false.elim },
rw [← b1, one_CNF o0],
simp only [list.mem_singleton, log_not_one_lt (lt_irrefl _), forall_eq, le_refl, true_and, list.pairwise_singleton] }
end
theorem CNF_pairwise (b := omega) (o) :
(CNF b o).pairwise (λ p q, prod.fst q < p.1) :=
(CNF_pairwise_aux _ _).2
theorem CNF_fst_le_log (b := omega) (o) :
∀ p ∈ CNF b o, prod.fst p ≤ log b o :=
(CNF_pairwise_aux _ _).1
theorem CNF_fst_le (b := omega) (o) (p ∈ CNF b o) : prod.fst p ≤ o :=
le_trans (CNF_fst_le_log _ _ p H) (log_le_self _ _)
theorem CNF_snd_lt {b : ordinal} (b1 : 1 < b) (o) :
∀ p ∈ CNF b o, prod.snd p < b :=
begin
have b0 := ne_of_gt (lt_trans zero_lt_one b1),
refine CNF_rec b0 (λ _, by rw [CNF_zero]; exact false.elim) _ o,
intros o o0 H IH,
simp only [CNF_ne_zero b0 o0, list.mem_cons_iff, list.forall_mem_cons', iff_true_intro IH, and_true],
rw [div_lt (power_ne_zero _ b0), ← power_succ],
exact lt_power_succ_log b1 _,
end
theorem CNF_sorted (b := omega) (o) :
((CNF b o).map prod.fst).sorted (>) :=
by rw [list.sorted, list.pairwise_map]; exact CNF_pairwise b o
/-- The next fixed point function, the least fixed point of the
normal function `f` above `a`. -/
def nfp (f : ordinal → ordinal) (a : ordinal) :=
sup (λ n : ℕ, f^[n] a)
theorem iterate_le_nfp (f a n) : f^[n] a ≤ nfp f a :=
le_sup _ n
theorem le_nfp_self (f a) : a ≤ nfp f a :=
iterate_le_nfp f a 0
theorem is_normal.lt_nfp {f} (H : is_normal f) {a b} :
f b < nfp f a ↔ b < nfp f a :=
lt_sup.trans $ iff.trans
(by exact
⟨λ ⟨n, h⟩, ⟨n, lt_of_le_of_lt (H.le_self _) h⟩,
λ ⟨n, h⟩, ⟨n+1, by rw nat.iterate_succ'; exact H.lt_iff.2 h⟩⟩)
lt_sup.symm
theorem is_normal.nfp_le {f} (H : is_normal f) {a b} :
nfp f a ≤ f b ↔ nfp f a ≤ b :=
le_iff_le_iff_lt_iff_lt.2 H.lt_nfp
theorem is_normal.nfp_le_fp {f} (H : is_normal f) {a b}
(ab : a ≤ b) (h : f b ≤ b) : nfp f a ≤ b :=
sup_le.2 $ λ i, begin
induction i with i IH generalizing a, {exact ab},
exact IH (le_trans (H.le_iff.2 ab) h),
end
theorem is_normal.nfp_fp {f} (H : is_normal f) (a) : f (nfp f a) = nfp f a :=
begin
refine le_antisymm _ (H.le_self _),
cases le_or_lt (f a) a with aa aa,
{ rwa le_antisymm (H.nfp_le_fp (le_refl _) aa) (le_nfp_self _ _) },
rcases zero_or_succ_or_limit (nfp f a) with e|⟨b, e⟩|l,
{ refine @le_trans _ _ _ (f a) _ (H.le_iff.2 _) (iterate_le_nfp f a 1),
simp only [e, zero_le] },
{ have : f b < nfp f a := H.lt_nfp.2 (by simp only [e, lt_succ_self]),
rw [e, lt_succ] at this,
have ab : a ≤ b,
{ rw [← lt_succ, ← e],
exact lt_of_lt_of_le aa (iterate_le_nfp f a 1) },
refine le_trans (H.le_iff.2 (H.nfp_le_fp ab this))
(le_trans this (le_of_lt _)),
simp only [e, lt_succ_self] },
{ exact (H.2 _ l _).2 (λ b h, le_of_lt (H.lt_nfp.2 h)) }
end
theorem is_normal.le_nfp {f} (H : is_normal f) {a b} :
f b ≤ nfp f a ↔ b ≤ nfp f a :=
⟨le_trans (H.le_self _), λ h,
by simpa only [H.nfp_fp] using H.le_iff.2 h⟩
theorem nfp_eq_self {f : ordinal → ordinal} {a} (h : f a = a) : nfp f a = a :=
le_antisymm (sup_le.mpr $ λ i, by rw [nat.iterate₀ h]) (le_nfp_self f a)
/-- The derivative of a normal function `f` is
the sequence of fixed points of `f`. -/
def deriv (f : ordinal → ordinal) (o : ordinal) : ordinal :=
limit_rec_on o (nfp f 0)
(λ a IH, nfp f (succ IH))
(λ a l, bsup.{u u} a)
@[simp] theorem deriv_zero (f) : deriv f 0 = nfp f 0 := limit_rec_on_zero _ _ _
@[simp] theorem deriv_succ (f o) : deriv f (succ o) = nfp f (succ (deriv f o)) :=
limit_rec_on_succ _ _ _ _
theorem deriv_limit (f) {o} : is_limit o →
deriv f o = bsup.{u u} o (λ a _, deriv f a) :=
limit_rec_on_limit _ _ _ _
theorem deriv_is_normal (f) : is_normal (deriv f) :=
⟨λ o, by rw [deriv_succ, ← succ_le]; apply le_nfp_self,
λ o l a, by rw [deriv_limit _ l, bsup_le]⟩
theorem is_normal.deriv_fp {f} (H : is_normal f) (o) : f (deriv.{u} f o) = deriv f o :=
begin
apply limit_rec_on o,
{ rw [deriv_zero, H.nfp_fp] },
{ intros o ih, rw [deriv_succ, H.nfp_fp] },
intros o l IH,
rw [deriv_limit _ l, is_normal.bsup.{u u u} H _ l.1],
refine eq_of_forall_ge_iff (λ c, _),
simp only [bsup_le, IH] {contextual:=tt}
end
theorem is_normal.fp_iff_deriv {f} (H : is_normal f)
{a} : f a ≤ a ↔ ∃ o, a = deriv f o :=
⟨λ ha, begin
suffices : ∀ o (_:a ≤ deriv f o), ∃ o, a = deriv f o,
from this a ((deriv_is_normal _).le_self _),
intro o, apply limit_rec_on o,
{ intros h₁,
refine ⟨0, le_antisymm h₁ _⟩,
rw deriv_zero,
exact H.nfp_le_fp (zero_le _) ha },
{ intros o IH h₁,
cases le_or_lt a (deriv f o), {exact IH h},
refine ⟨succ o, le_antisymm h₁ _⟩,
rw deriv_succ,
exact H.nfp_le_fp (succ_le.2 h) ha },
{ intros o l IH h₁,
cases eq_or_lt_of_le h₁, {exact ⟨_, h⟩},
rw [deriv_limit _ l, ← not_le, bsup_le, not_ball] at h,
exact let ⟨o', h, hl⟩ := h in IH o' h (le_of_not_le hl) }
end, λ ⟨o, e⟩, e.symm ▸ le_of_eq (H.deriv_fp _)⟩
end ordinal
namespace cardinal
section using_ordinals
open ordinal
theorem ord_is_limit {c} (co : omega ≤ c) : (ord c).is_limit :=
begin
refine ⟨λ h, omega_ne_zero _, λ a, lt_imp_lt_of_le_imp_le _⟩,
{ rw [← ordinal.le_zero, ord_le] at h,
simpa only [card_zero, le_zero] using le_trans co h },
{ intro h, rw [ord_le] at h ⊢,
rwa [← @add_one_of_omega_le (card a), ← card_succ],
rw [← ord_le, ← le_succ_of_is_limit, ord_le],
{ exact le_trans co h },
{ rw ord_omega, exact omega_is_limit } }
end
def aleph_idx.initial_seg : @initial_seg cardinal ordinal (<) (<) :=
@order_embedding.collapse cardinal ordinal (<) (<) _ cardinal.ord.order_embedding
/-- The `aleph'` index function, which gives the ordinal index of a cardinal.
(The `aleph'` part is because unlike `aleph` this counts also the
finite stages. So `aleph_idx n = n`, `aleph_idx ω = ω`,
`aleph_idx ℵ₁ = ω + 1` and so on.) -/
def aleph_idx : cardinal → ordinal := aleph_idx.initial_seg
@[simp] theorem aleph_idx.initial_seg_coe :
(aleph_idx.initial_seg : cardinal → ordinal) = aleph_idx := rfl
@[simp] theorem aleph_idx_lt {a b} : aleph_idx a < aleph_idx b ↔ a < b :=
aleph_idx.initial_seg.to_order_embedding.ord.symm
@[simp] theorem aleph_idx_le {a b} : aleph_idx a ≤ aleph_idx b ↔ a ≤ b :=
by rw [← not_lt, ← not_lt, aleph_idx_lt]
theorem aleph_idx.init {a b} : b < aleph_idx a → ∃ c, aleph_idx c = b :=
aleph_idx.initial_seg.init _ _
def aleph_idx.order_iso : @order_iso cardinal.{u} ordinal.{u} (<) (<) :=
@order_iso.of_surjective cardinal.{u} ordinal.{u} (<) (<) aleph_idx.initial_seg.{u} $
(initial_seg.eq_or_principal aleph_idx.initial_seg.{u}).resolve_right $
λ ⟨o, e⟩, begin
have : ∀ c, aleph_idx c < o := λ c, (e _).2 ⟨_, rfl⟩,
refine ordinal.induction_on o _ this, introsI α r _ h,
let s := sup.{u u} (λ a:α, inv_fun aleph_idx (ordinal.typein r a)),
apply not_le_of_gt (lt_succ_self s),
have I : injective aleph_idx := aleph_idx.initial_seg.to_embedding.inj,
simpa only [typein_enum, left_inverse_inv_fun I (succ s)] using
le_sup.{u u} (λ a, inv_fun aleph_idx (ordinal.typein r a))
(ordinal.enum r _ (h (succ s))),
end
@[simp] theorem aleph_idx.order_iso_coe :
(aleph_idx.order_iso : cardinal → ordinal) = aleph_idx := rfl
@[simp] theorem type_cardinal : @ordinal.type cardinal (<) _ = ordinal.univ.{u (u+1)} :=
by rw ordinal.univ_id; exact quotient.sound ⟨aleph_idx.order_iso⟩
@[simp] theorem mk_cardinal : mk cardinal = univ.{u (u+1)} :=
by simpa only [card_type, card_univ] using congr_arg card type_cardinal
def aleph'.order_iso := cardinal.aleph_idx.order_iso.symm
/-- The `aleph'` function gives the cardinals listed by their ordinal
index, and is the inverse of `aleph_idx`.
`aleph' n = n`, `aleph' ω = ω`, `aleph' (ω + 1) = ℵ₁, etc. -/
def aleph' : ordinal → cardinal := aleph'.order_iso
@[simp] theorem aleph'.order_iso_coe :
(aleph'.order_iso : ordinal → cardinal) = aleph' := rfl
@[simp] theorem aleph'_lt {o₁ o₂ : ordinal.{u}} : aleph' o₁ < aleph' o₂ ↔ o₁ < o₂ :=
aleph'.order_iso.ord.symm
@[simp] theorem aleph'_le {o₁ o₂ : ordinal.{u}} : aleph' o₁ ≤ aleph' o₂ ↔ o₁ ≤ o₂ :=
le_iff_le_iff_lt_iff_lt.2 aleph'_lt
@[simp] theorem aleph'_aleph_idx (c : cardinal.{u}) : aleph' c.aleph_idx = c :=
cardinal.aleph_idx.order_iso.to_equiv.symm_apply_apply c
@[simp] theorem aleph_idx_aleph' (o : ordinal.{u}) : (aleph' o).aleph_idx = o :=
cardinal.aleph_idx.order_iso.to_equiv.apply_symm_apply o
@[simp] theorem aleph'_zero : aleph' 0 = 0 :=
by rw [← le_zero, ← aleph'_aleph_idx 0, aleph'_le];
apply ordinal.zero_le
@[simp] theorem aleph'_succ {o : ordinal.{u}} : aleph' o.succ = (aleph' o).succ :=
le_antisymm
(cardinal.aleph_idx_le.1 $
by rw [aleph_idx_aleph', ordinal.succ_le, ← aleph'_lt, aleph'_aleph_idx];
apply cardinal.lt_succ_self)
(cardinal.succ_le.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _)
@[simp] theorem aleph'_nat : ∀ n : ℕ, aleph' n = n
| 0 := aleph'_zero
| (n+1) := show aleph' (ordinal.succ n) = n.succ,
by rw [aleph'_succ, aleph'_nat, nat_succ]
theorem aleph'_le_of_limit {o : ordinal.{u}} (l : o.is_limit) {c} :
aleph' o ≤ c ↔ ∀ o' < o, aleph' o' ≤ c :=
⟨λ h o' h', le_trans (aleph'_le.2 $ le_of_lt h') h,
λ h, begin
rw [← aleph'_aleph_idx c, aleph'_le, ordinal.limit_le l],
intros x h',
rw [← aleph'_le, aleph'_aleph_idx],
exact h _ h'
end⟩
@[simp] theorem aleph'_omega : aleph' ordinal.omega = omega :=
eq_of_forall_ge_iff $ λ c, begin
simp only [aleph'_le_of_limit omega_is_limit, ordinal.lt_omega, exists_imp_distrib, omega_le],
exact forall_swap.trans (forall_congr $ λ n, by simp only [forall_eq, aleph'_nat]),
end
/-- aleph' and aleph_idx form an equivalence between `ordinal` and `cardinal` -/
@[simp] def aleph'_equiv : ordinal ≃ cardinal :=
⟨aleph', aleph_idx, aleph_idx_aleph', aleph'_aleph_idx⟩
/-- The `aleph` function gives the infinite cardinals listed by their
ordinal index. `aleph 0 = ω`, `aleph 1 = succ ω` is the first
uncountable cardinal, and so on. -/
def aleph (o : ordinal) : cardinal := aleph' (ordinal.omega + o)
@[simp] theorem aleph_lt {o₁ o₂ : ordinal.{u}} : aleph o₁ < aleph o₂ ↔ o₁ < o₂ :=
aleph'_lt.trans (ordinal.add_lt_add_iff_left _)
@[simp] theorem aleph_le {o₁ o₂ : ordinal.{u}} : aleph o₁ ≤ aleph o₂ ↔ o₁ ≤ o₂ :=
le_iff_le_iff_lt_iff_lt.2 aleph_lt
@[simp] theorem aleph_succ {o : ordinal.{u}} : aleph o.succ = (aleph o).succ :=
by rw [aleph, ordinal.add_succ, aleph'_succ]; refl
@[simp] theorem aleph_zero : aleph 0 = omega :=
by simp only [aleph, add_zero, aleph'_omega]
theorem omega_le_aleph' {o : ordinal} : omega ≤ aleph' o ↔ ordinal.omega ≤ o :=
by rw [← aleph'_omega, aleph'_le]
theorem omega_le_aleph (o : ordinal) : omega ≤ aleph o :=
by rw [aleph, omega_le_aleph']; apply ordinal.le_add_right
theorem ord_aleph_is_limit (o : ordinal) : is_limit (aleph o).ord :=
ord_is_limit $ omega_le_aleph _
theorem exists_aleph {c : cardinal} : omega ≤ c ↔ ∃ o, c = aleph o :=
⟨λ h, ⟨aleph_idx c - ordinal.omega,
by rw [aleph, ordinal.add_sub_cancel_of_le, aleph'_aleph_idx];
rwa [← omega_le_aleph', aleph'_aleph_idx]⟩,
λ ⟨o, e⟩, e.symm ▸ omega_le_aleph _⟩
theorem aleph'_is_normal : is_normal (ord ∘ aleph') :=
⟨λ o, ord_lt_ord.2 $ aleph'_lt.2 $ ordinal.lt_succ_self _,
λ o l a, by simp only [ord_le, aleph'_le_of_limit l]⟩
theorem aleph_is_normal : is_normal (ord ∘ aleph) :=
aleph'_is_normal.trans $ add_is_normal ordinal.omega
/- properties of mul -/
theorem mul_eq_self {c : cardinal} (h : omega ≤ c) : c * c = c :=
begin
refine le_antisymm _
(by simpa only [mul_one] using mul_le_mul_left c (le_trans (le_of_lt one_lt_omega) h)),
refine acc.rec_on (cardinal.wf.apply c) (λ c _,
quotient.induction_on c $ λ α IH ol, _) h,
rcases ord_eq α with ⟨r, wo, e⟩, resetI,
let := decidable_linear_order_of_STO' r,
have : is_well_order α (<) := wo,
let g : α × α → α := λ p, max p.1 p.2,
let f : α × α ↪ ordinal × (α × α) :=
⟨λ p:α×α, (typein (<) (g p), p), λ p q, congr_arg prod.snd⟩,
let s := f ⁻¹'o (prod.lex (<) (prod.lex (<) (<))),
have : is_well_order _ s := (order_embedding.preimage _ _).is_well_order,
suffices : type s ≤ type r, {exact card_le_card this},
refine le_of_forall_lt (λ o h, _),
rcases typein_surj s h with ⟨p, rfl⟩,
rw [← e, lt_ord],
refine lt_of_le_of_lt (_ : _ ≤ card (typein (<) (g p)).succ * card (typein (<) (g p)).succ) _,
{ have : {q|s q p} ⊆ (insert (g p) {x | x < (g p)}).prod (insert (g p) {x | x < (g p)}),
{ intros q h,
simp only [s, embedding.coe_fn_mk, order.preimage, typein_lt_typein, prod.lex_def, typein_inj] at h,
exact max_le_iff.1 (le_iff_lt_or_eq.2 $ h.imp_right and.left) },
suffices H : (insert (g p) {x | r x (g p)} : set α) ≃ ({x | r x (g p)} ⊕ punit),
{ exact ⟨(set.embedding_of_subset _ _ this).trans
((equiv.set.prod _ _).trans (H.prod_congr H)).to_embedding⟩ },
refine (equiv.set.insert _).trans
((equiv.refl _).sum_congr punit_equiv_punit),
apply @irrefl _ r },
cases lt_or_ge (card (typein (<) (g p)).succ) omega with qo qo,
{ exact lt_of_lt_of_le (mul_lt_omega qo qo) ol },
{ suffices, {exact lt_of_le_of_lt (IH _ this qo) this},
rw ← lt_ord, apply (ord_is_limit ol).2,
rw [mk_def, e], apply typein_lt_type }
end
end using_ordinals
theorem mul_eq_max {a b : cardinal} (ha : omega ≤ a) (hb : omega ≤ b) : a * b = max a b :=
le_antisymm
(mul_eq_self (le_trans ha (le_max_left a b)) ▸
mul_le_mul (le_max_left _ _) (le_max_right _ _)) $
max_le
(by simpa only [mul_one] using mul_le_mul_left a (le_trans (le_of_lt one_lt_omega) hb))
(by simpa only [one_mul] using mul_le_mul_right b (le_trans (le_of_lt one_lt_omega) ha))
theorem mul_lt_of_lt {a b c : cardinal} (hc : omega ≤ c)
(h1 : a < c) (h2 : b < c) : a * b < c :=
lt_of_le_of_lt (mul_le_mul (le_max_left a b) (le_max_right a b)) $
(lt_or_le (max a b) omega).elim
(λ h, lt_of_lt_of_le (mul_lt_omega h h) hc)
(λ h, by rw mul_eq_self h; exact max_lt h1 h2)
lemma mul_le_max_of_omega_le_left {a b : cardinal} (h : omega ≤ a) : a * b ≤ max a b :=
begin
convert mul_le_mul (le_max_left a b) (le_max_right a b), rw [mul_eq_self],
refine le_trans h (le_max_left a b)
end
lemma mul_eq_max_of_omega_le_left {a b : cardinal} (h : omega ≤ a) (h' : b ≠ 0) : a * b = max a b :=
begin
apply le_antisymm, apply mul_le_max_of_omega_le_left h,
cases le_or_gt omega b with hb hb, rw [mul_eq_max h hb],
have : b ≤ a, exact le_trans (le_of_lt hb) h,
rw [max_eq_left this], convert mul_le_mul_left _ (one_le_iff_ne_zero.mpr h'), rw [mul_one],
end
lemma mul_eq_left {a b : cardinal} (ha : omega ≤ a) (hb : b ≤ a) (hb' : b ≠ 0) : a * b = a :=
by { rw [mul_eq_max_of_omega_le_left ha hb', max_eq_left hb] }
lemma mul_eq_right {a b : cardinal} (hb : omega ≤ b) (ha : a ≤ b) (ha' : a ≠ 0) : a * b = b :=
by { rw [mul_comm, mul_eq_left hb ha ha'] }
lemma le_mul_left {a b : cardinal} (h : b ≠ 0) : a ≤ b * a :=
by { convert mul_le_mul_right _ (one_le_iff_ne_zero.mpr h), rw [one_mul] }
lemma le_mul_right {a b : cardinal} (h : b ≠ 0) : a ≤ a * b :=
by { rw [mul_comm], exact le_mul_left h }
lemma mul_eq_left_iff {a b : cardinal} : a * b = a ↔ ((max omega b ≤ a ∧ b ≠ 0) ∨ b = 1 ∨ a = 0) :=
begin
rw [max_le_iff], split,
{ intro h,
cases (le_or_lt omega a) with ha ha,
{ have : a ≠ 0, { rintro rfl, exact not_lt_of_le ha omega_pos },
left, use ha,
{ rw [← not_lt], intro hb, apply ne_of_gt _ h, refine lt_of_lt_of_le hb (le_mul_left this) },
{ rintro rfl, apply this, rw [_root_.mul_zero] at h, subst h }},
right, by_cases h2a : a = 0, { right, exact h2a },
have hb : b ≠ 0, { rintro rfl, apply h2a, rw [mul_zero] at h, subst h },
left, rw [← h, mul_lt_omega_iff, lt_omega, lt_omega] at ha,
rcases ha with rfl|rfl|⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, contradiction, contradiction,
rw [← ne] at h2a, rw [← one_le_iff_ne_zero] at h2a hb, norm_cast at h2a hb h ⊢,
apply le_antisymm _ hb, rw [← not_lt], intro h2b,
apply ne_of_gt _ h, rw [gt], conv_lhs { rw [← mul_one n] },
rwa [mul_lt_mul_left], apply nat.lt_of_succ_le h2a },
{ rintro (⟨⟨ha, hab⟩, hb⟩|rfl|rfl),
{ rw [mul_eq_max_of_omega_le_left ha hb, max_eq_left hab] },
all_goals {simp}}
end
/- properties of add -/
theorem add_eq_self {c : cardinal} (h : omega ≤ c) : c + c = c :=
le_antisymm
(by simpa only [nat.cast_bit0, nat.cast_one, mul_eq_self h, two_mul] using
mul_le_mul_right c (le_trans (le_of_lt $ nat_lt_omega 2) h))
(le_add_left c c)
theorem add_eq_max {a b : cardinal} (ha : omega ≤ a) : a + b = max a b :=
le_antisymm
(add_eq_self (le_trans ha (le_max_left a b)) ▸
add_le_add (le_max_left _ _) (le_max_right _ _)) $
max_le (le_add_right _ _) (le_add_left _ _)
theorem add_lt_of_lt {a b c : cardinal} (hc : omega ≤ c)
(h1 : a < c) (h2 : b < c) : a + b < c :=
lt_of_le_of_lt (add_le_add (le_max_left a b) (le_max_right a b)) $
(lt_or_le (max a b) omega).elim
(λ h, lt_of_lt_of_le (add_lt_omega h h) hc)
(λ h, by rw add_eq_self h; exact max_lt h1 h2)
lemma eq_of_add_eq_of_omega_le {a b c : cardinal} (h : a + b = c) (ha : a < c) (hc : omega ≤ c) :
b = c :=
begin
apply le_antisymm,
{ rw [← h], apply cardinal.le_add_left },
rw[← not_lt], intro hb,
have : a + b < c := add_lt_of_lt hc ha hb,
simpa [h, lt_irrefl] using this
end
lemma add_eq_left {a b : cardinal} (ha : omega ≤ a) (hb : b ≤ a) : a + b = a :=
by { rw [add_eq_max ha, max_eq_left hb] }
lemma add_eq_right {a b : cardinal} (hb : omega ≤ b) (ha : a ≤ b) : a + b = b :=
by { rw [add_comm, add_eq_left hb ha] }
lemma add_eq_left_iff {a b : cardinal} : a + b = a ↔ (max omega b ≤ a ∨ b = 0) :=
begin
rw [max_le_iff], split,
{ intro h, cases (le_or_lt omega a) with ha ha,
{ left, use ha, rw [← not_lt], intro hb, apply ne_of_gt _ h,
exact lt_of_lt_of_le hb (le_add_left b a) },
right, rw [← h, add_lt_omega_iff, lt_omega, lt_omega] at ha,
rcases ha with ⟨⟨n, rfl⟩, ⟨m, rfl⟩⟩, norm_cast at h ⊢,
rw [← add_right_inj, h, add_zero] },
{ rintro (⟨h1, h2⟩|h3), rw [add_eq_max h1, max_eq_left h2], rw [h3, add_zero] }
end
lemma add_eq_right_iff {a b : cardinal} : a + b = b ↔ (max omega a ≤ b ∨ a = 0) :=
by { rw [add_comm, add_eq_left_iff] }
lemma add_one_eq {a : cardinal} (ha : omega ≤ a) : a + 1 = a :=
have 1 ≤ a, from le_trans (le_of_lt one_lt_omega) ha,
add_eq_left ha this
protected lemma eq_of_add_eq_add_left {a b c : cardinal} (h : a + b = a + c) (ha : a < omega) :
b = c :=
begin
cases le_or_lt omega b with hb hb,
{ have : a < b := lt_of_lt_of_le ha hb,
rw [add_eq_right hb (le_of_lt this), eq_comm] at h,
rw [eq_of_add_eq_of_omega_le h this hb] },
{ have hc : c < omega,
{ rw [← not_le], intro hc,
apply lt_irrefl omega, apply lt_of_le_of_lt (le_trans hc (le_add_left _ a)),
rw [← h], apply add_lt_omega ha hb },
rw [lt_omega] at *,
rcases ha with ⟨n, rfl⟩, rcases hb with ⟨m, rfl⟩, rcases hc with ⟨k, rfl⟩,
norm_cast at h ⊢, apply eq_of_add_eq_add_left h }
end
protected lemma eq_of_add_eq_add_right {a b c : cardinal} (h : a + b = c + b) (hb : b < omega) :
a = c :=
by { rw [add_comm a b, add_comm c b] at h, exact cardinal.eq_of_add_eq_add_left h hb }
/- properties about power -/
theorem pow_le {κ μ : cardinal.{u}} (H1 : omega ≤ κ) (H2 : μ < omega) : κ ^ μ ≤ κ :=
let ⟨n, H3⟩ := lt_omega.1 H2 in
H3.symm ▸ (quotient.induction_on κ (λ α H1, nat.rec_on n
(le_of_lt $ lt_of_lt_of_le (by rw [nat.cast_zero, power_zero];
from one_lt_omega) H1)
(λ n ih, trans_rel_left _
(by rw [nat.cast_succ, power_add, power_one];
from mul_le_mul_right _ ih)
(mul_eq_self H1))) H1)
lemma power_self_eq {c : cardinal} (h : omega ≤ c) : c ^ c = 2 ^ c :=
begin
apply le_antisymm,
{ apply le_trans (power_le_power_right $ le_of_lt $ cantor c), rw [power_mul, mul_eq_self h] },
{ convert power_le_power_right (le_trans (le_of_lt $ nat_lt_omega 2) h), apply nat.cast_two.symm }
end
lemma power_nat_le {c : cardinal.{u}} {n : ℕ} (h : omega ≤ c) : c ^ (n : cardinal.{u}) ≤ c :=
pow_le h (nat_lt_omega n)
lemma powerlt_omega {c : cardinal} (h : omega ≤ c) : c ^< omega = c :=
begin
apply le_antisymm,
{ rw [powerlt_le], intro c', rw [lt_omega], rintro ⟨n, rfl⟩, apply power_nat_le h },
convert le_powerlt one_lt_omega, rw [power_one]
end
lemma powerlt_omega_le (c : cardinal) : c ^< omega ≤ max c omega :=
begin
cases le_or_gt omega c,
{ rw [powerlt_omega h], apply le_max_left },
rw [powerlt_le], intros c' hc',
refine le_trans (le_of_lt $ power_lt_omega h hc') (le_max_right _ _)
end
/- compute cardinality of various types -/
theorem mk_list_eq_mk {α : Type u} (H1 : omega ≤ mk α) : mk (list α) = mk α :=
eq.symm $ le_antisymm ⟨⟨λ x, [x], λ x y H, (list.cons.inj H).1⟩⟩ $
calc mk (list α)
= sum (λ n : ℕ, mk α ^ (n : cardinal.{u})) : mk_list_eq_sum_pow α
... ≤ sum (λ n : ℕ, mk α) : sum_le_sum _ _ $ λ n, pow_le H1 $ nat_lt_omega n
... = sum (λ n : ulift.{u} ℕ, mk α) : quotient.sound
⟨@sigma_congr_left _ _ (λ _, quotient.out (mk α)) equiv.ulift.symm⟩
... = omega * mk α : sum_const _ _
... = max (omega) (mk α) : mul_eq_max (le_refl _) H1
... = mk α : max_eq_right H1
lemma mk_bounded_set_le_of_omega_le (α : Type u) (c : cardinal) (hα : omega ≤ mk α) :
mk {t : set α // mk t ≤ c} ≤ mk α ^ c :=
begin
refine le_trans _ (by rw [←add_one_eq hα]), refine quotient.induction_on c _, clear c, intro β,
fapply mk_le_of_surjective,
{ intro f, use sum.inl ⁻¹' range f,
refine le_trans (mk_preimage_of_injective _ _ (λ x y, sum.inl.inj)) _,
apply mk_range_le },
rintro ⟨s, ⟨g⟩⟩,
use λ y, if h : ∃(x : s), g x = y then sum.inl (classical.some h).val else sum.inr ⟨⟩,
apply subtype.eq, ext,
split,
{ rintro ⟨y, h⟩, dsimp only at h, by_cases h' : ∃ (z : s), g z = y,
{ rw [dif_pos h'] at h, cases sum.inl.inj h, exact (classical.some h').2 },
{ rw [dif_neg h'] at h, cases h }},
{ intro h, have : ∃(z : s), g z = g ⟨x, h⟩, exact ⟨⟨x, h⟩, rfl⟩,
use g ⟨x, h⟩, dsimp only, rw [dif_pos this], congr',
suffices : classical.some this = ⟨x, h⟩, exact congr_arg subtype.val this,
apply g.2, exact classical.some_spec this }
end
lemma mk_bounded_set_le (α : Type u) (c : cardinal) :
mk {t : set α // mk t ≤ c} ≤ max (mk α) omega ^ c :=
begin
transitivity mk {t : set (ulift.{u} nat ⊕ α) // mk t ≤ c},
{ refine ⟨embedding.subtype_map _ _⟩, apply embedding.image,
use sum.inr, apply sum.inr.inj, intros s hs, exact le_trans mk_image_le hs },
refine le_trans
(mk_bounded_set_le_of_omega_le (ulift.{u} nat ⊕ α) c (le_add_right omega (mk α))) _,
rw [max_comm, ←add_eq_max]; refl
end
lemma mk_bounded_subset_le {α : Type u} (s : set α) (c : cardinal.{u}) :
mk {t : set α // t ⊆ s ∧ mk t ≤ c} ≤ max (mk s) omega ^ c :=
begin
refine le_trans _ (mk_bounded_set_le s c),
refine ⟨embedding.cod_restrict _ _ _⟩,
use λ t, subtype.val ⁻¹' t.1,
{ rintros ⟨t, ht1, ht2⟩ ⟨t', h1t', h2t'⟩ h, apply subtype.eq, dsimp only at h ⊢,
refine (preimage_eq_preimage' _ _).1 h; rw [subtype.range_val]; assumption },
rintro ⟨t, h1t, h2t⟩, exact le_trans (mk_preimage_of_injective _ _ subtype.val_injective) h2t
end
/- compl -/
lemma mk_compl_of_omega_le {α : Type*} (s : set α) (h : omega ≤ #α) (h2 : #s < #α) :
#(-s : set α) = #α :=
by { refine eq_of_add_eq_of_omega_le _ h2 h, exact mk_sum_compl s }
lemma mk_compl_finset_of_omega_le {α : Type*} (s : finset α) (h : omega ≤ #α) :
#(-↑s : set α) = #α :=
by { apply mk_compl_of_omega_le _ h, exact lt_of_lt_of_le (finset_card_lt_omega s) h }
lemma mk_compl_eq_mk_compl_infinite {α : Type*} {s t : set α} (h : omega ≤ #α) (hs : #s < #α)
(ht : #t < #α) : #(-s : set α) = #(-t : set α) :=
by { rw [mk_compl_of_omega_le s h hs, mk_compl_of_omega_le t h ht] }
lemma mk_compl_eq_mk_compl_finite_lift {α : Type u} {β : Type v} {s : set α} {t : set β}
(hα : #α < omega) (h1 : lift.{u (max v w)} (#α) = lift.{v (max u w)} (#β))
(h2 : lift.{u (max v w)} (#s) = lift.{v (max u w)} (#t)) :
lift.{u (max v w)} (#(-s : set α)) = lift.{v (max u w)} (#(-t : set β)) :=
begin
have hα' := hα, have h1' := h1,
rw [← mk_sum_compl s, ← mk_sum_compl t] at h1,
rw [← mk_sum_compl s, add_lt_omega_iff] at hα,
lift #s to ℕ using hα.1 with n hn,
lift #(- s : set α) to ℕ using hα.2 with m hm,
have : #(- t : set β) < omega,
{ refine lt_of_le_of_lt (mk_subtype_le _) _,
rw [← lift_lt, lift_omega, ← h1', ← lift_omega.{u (max v w)}, lift_lt], exact hα' },
lift #(- t : set β) to ℕ using this with k hk,
simp [nat_eq_lift_eq_iff] at h2, rw [nat_eq_lift_eq_iff.{v (max u w)}] at h2,
simp [h2.symm] at h1 ⊢, norm_cast at h1, simp at h1, exact h1
end
lemma mk_compl_eq_mk_compl_finite {α β : Type u} {s : set α} {t : set β}
(hα : #α < omega) (h1 : #α = #β) (h : #s = #t) : #(-s : set α) = #(-t : set β) :=
by { rw [← lift_inj], apply mk_compl_eq_mk_compl_finite_lift hα; rw [lift_inj]; assumption }
lemma mk_compl_eq_mk_compl_finite_same {α : Type*} {s t : set α} (hα : #α < omega)
(h : #s = #t) : #(-s : set α) = #(-t : set α) :=
mk_compl_eq_mk_compl_finite hα rfl h
/- extend an injection to an equiv -/
theorem extend_function {α β : Type*} {s : set α} (f : s ↪ β)
(h : nonempty ((-s : set α) ≃ (- range f : set β))) :
∃ (g : α ≃ β), ∀ x : s, g x = f x :=
begin
intros, have := h, cases this with g,
let h : α ≃ β := (set.sum_compl (s : set α)).symm.trans
((sum_congr (equiv.set.range f f.2) g).trans
(set.sum_compl (range f))),
refine ⟨h, _⟩, rintro ⟨x, hx⟩, simp [set.sum_compl_symm_apply_of_mem, hx]
end
theorem extend_function_finite {α β : Type*} {s : set α} (f : s ↪ β)
(hs : #α < omega) (h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x :=
begin
apply extend_function f,
have := h, cases this with g,
rw [← lift_mk_eq] at h,
rw [←lift_mk_eq, mk_compl_eq_mk_compl_finite_lift hs h],
rw [mk_range_eq_lift], exact f.2
end
theorem extend_function_of_lt {α β : Type*} {s : set α} (f : s ↪ β) (hs : #s < #α)
(h : nonempty (α ≃ β)) : ∃ (g : α ≃ β), ∀ x : s, g x = f x :=
begin
cases (le_or_lt omega (#α)) with hα hα,
{ apply extend_function f, have := h, cases this with g, rw [← lift_mk_eq] at h,
cases cardinal.eq.mp (mk_compl_of_omega_le s hα hs) with g2,
cases cardinal.eq.mp (mk_compl_of_omega_le (range f) _ _) with g3,
{ constructor, exact g2.trans (g.trans g3.symm) },
{ rw [← lift_le, ← h], refine le_trans _ (lift_le.mpr hα), simp },
rwa [← lift_lt, ← h, mk_range_eq_lift, lift_lt], exact f.2 },
{ exact extend_function_finite f hα h }
end
end cardinal
|
a5f1a0d5aa96ebf959e4b9ff3bc10987d86210c2 | fa02ed5a3c9c0adee3c26887a16855e7841c668b | /src/ring_theory/witt_vector/init_tail.lean | 4ab8c316a0265fea48bff546b7f0c5612bae8f01 | [
"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 | 6,549 | lean | /-
Copyright (c) 2020 Johan Commelin, Robert Y. Lewis. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Johan Commelin, Robert Y. Lewis
-/
import ring_theory.witt_vector.basic
import ring_theory.witt_vector.is_poly
/-!
# `init` and `tail`
Given a Witt vector `x`, we are sometimes interested
in its components before and after an index `n`.
This file defines those operations, proves that `init` is polynomial,
and shows how that polynomial interacts with `mv_polynomial.bind₁`.
## Main declarations
* `witt_vector.init n x`: the first `n` coefficients of `x`, as a Witt vector. All coefficients at
indices ≥ `n` are 0.
* `witt_vector.tail n x`: the complementary part to `init`. All coefficients at indices < `n` are 0,
otherwise they are the same as in `x`.
* `witt_vector.coeff_add_of_disjoint`: if `x` and `y` are Witt vectors such that for every `n`
the `n`-th coefficient of `x` or of `y` is `0`, then the coefficients of `x + y`
are just `x.coeff n + y.coeff n`.
## References
* [Hazewinkel, *Witt Vectors*][Haze09]
* [Commelin and Lewis, *Formalizing the Ring of Witt Vectors*][CL21]
-/
variables {p : ℕ} [hp : fact p.prime] (n : ℕ) {R : Type*} [comm_ring R]
local notation `𝕎` := witt_vector p -- type as `\bbW`
namespace tactic
namespace interactive
setup_tactic_parser
/--
`init_ring` is an auxiliary tactic that discharges goals factoring `init` over ring operations.
-/
meta def init_ring (assert : parse (tk "using" >> parser.pexpr)?) : tactic unit := do
`[rw ext_iff,
intros i,
simp only [init, select, coeff_mk],
split_ifs with hi; try {refl}],
match assert with
| none := skip
| some e := do
`[simp only [add_coeff, mul_coeff, neg_coeff],
apply eval₂_hom_congr' (ring_hom.ext_int _ _) _ rfl,
rintro ⟨b, k⟩ h -],
tactic.replace `h ```(%%e p _ h),
`[simp only [finset.mem_range, finset.mem_product, true_and, finset.mem_univ] at h,
have hk : k < n, by linarith,
fin_cases b;
simp only [function.uncurry, matrix.cons_val_zero, matrix.head_cons, coeff_mk,
matrix.cons_val_one, coeff_mk, hk, if_true]]
end
end interactive
end tactic
namespace witt_vector
open mv_polynomial
open_locale classical
noncomputable theory
section
/-- `witt_vector.select P x`, for a predicate `P : ℕ → Prop` is the Witt vector
whose `n`-th coefficient is `x.coeff n` if `P n` is true, and `0` otherwise.
-/
def select (P : ℕ → Prop) (x : 𝕎 R) : 𝕎 R :=
mk p (λ n, if P n then x.coeff n else 0)
section select
variables (P : ℕ → Prop)
/-- The polynomial that witnesses that `witt_vector.select` is a polynomial function.
`select_poly n` is `X n` if `P n` holds, and `0` otherwise. -/
def select_poly (n : ℕ) : mv_polynomial ℕ ℤ := if P n then X n else 0
lemma coeff_select (x : 𝕎 R) (n : ℕ) :
(select P x).coeff n = aeval x.coeff (select_poly P n) :=
begin
dsimp [select, select_poly],
split_ifs with hi,
{ rw aeval_X },
{ rw alg_hom.map_zero }
end
@[is_poly] lemma select_is_poly (P : ℕ → Prop) :
is_poly p (λ R _Rcr x, by exactI select P x) :=
begin
use (select_poly P),
rintro R _Rcr x,
funext i,
apply coeff_select
end
include hp
lemma select_add_select_not :
∀ (x : 𝕎 R), select P x + select (λ i, ¬ P i) x = x :=
begin
ghost_calc _,
intro n,
simp only [ring_hom.map_add],
suffices : (bind₁ (select_poly P)) (witt_polynomial p ℤ n) +
(bind₁ (select_poly (λ i, ¬P i))) (witt_polynomial p ℤ n) = witt_polynomial p ℤ n,
{ apply_fun (aeval x.coeff) at this,
simpa only [alg_hom.map_add, aeval_bind₁, ← coeff_select] },
simp only [witt_polynomial_eq_sum_C_mul_X_pow, select_poly, alg_hom.map_sum, alg_hom.map_pow,
alg_hom.map_mul, bind₁_X_right, bind₁_C_right, ← finset.sum_add_distrib, ← mul_add],
apply finset.sum_congr rfl,
refine λ m hm, mul_eq_mul_left_iff.mpr (or.inl _),
rw [ite_pow, ite_pow, zero_pow (pow_pos hp.out.pos _)],
by_cases Pm : P m,
{ rw [if_pos Pm, if_neg _, add_zero],
exact not_not.mpr Pm },
{ rwa [if_neg Pm, if_pos, zero_add] }
end
lemma coeff_add_of_disjoint (x y : 𝕎 R) (h : ∀ n, x.coeff n = 0 ∨ y.coeff n = 0) :
(x + y).coeff n = x.coeff n + y.coeff n :=
begin
let P : ℕ → Prop := λ n, y.coeff n = 0,
haveI : decidable_pred P := classical.dec_pred P,
set z := mk p (λ n, if P n then x.coeff n else y.coeff n) with hz,
have hx : select P z = x,
{ ext1 n, rw [select, coeff_mk, coeff_mk],
split_ifs with hn, { refl }, { rw (h n).resolve_right hn } },
have hy : select (λ i, ¬ P i) z = y,
{ ext1 n, rw [select, coeff_mk, coeff_mk],
split_ifs with hn, { exact hn.symm }, { refl } },
calc (x + y).coeff n = z.coeff n : by rw [← hx, ← hy, select_add_select_not P z]
... = x.coeff n + y.coeff n : _,
dsimp [z],
split_ifs with hn,
{ dsimp [P] at hn, rw [hn, add_zero] },
{ rw [(h n).resolve_right hn, zero_add] }
end
end select
/-- `witt_vector.init n x` is the Witt vector of which the first `n` coefficients are those from `x`
and all other coefficients are `0`.
See `witt_vector.tail` for the complementary part.
-/
def init (n : ℕ) : 𝕎 R → 𝕎 R := select (λ i, i < n)
/-- `witt_vector.tail n x` is the Witt vector of which the first `n` coefficients are `0`
and all other coefficients are those from `x`.
See `witt_vector.init` for the complementary part. -/
def tail (n : ℕ) : 𝕎 R → 𝕎 R := select (λ i, n ≤ i)
include hp
@[simp] lemma init_add_tail (x : 𝕎 R) (n : ℕ) :
init n x + tail n x = x :=
by simp only [init, tail, ← not_lt, select_add_select_not]
end
@[simp]
lemma init_init (x : 𝕎 R) (n : ℕ) :
init n (init n x) = init n x :=
by init_ring
include hp
lemma init_add (x y : 𝕎 R) (n : ℕ) :
init n (x + y) = init n (init n x + init n y) :=
by init_ring using witt_add_vars
lemma init_mul (x y : 𝕎 R) (n : ℕ) :
init n (x * y) = init n (init n x * init n y) :=
by init_ring using witt_mul_vars
lemma init_neg (x : 𝕎 R) (n : ℕ) :
init n (-x) = init n (-init n x) :=
by init_ring using witt_neg_vars
lemma init_sub (x y : 𝕎 R) (n : ℕ) :
init n (x - y) = init n (init n x - init n y) :=
begin
simp only [sub_eq_add_neg],
rw [init_add, init_neg],
conv_rhs { rw [init_add, init_init] },
end
section
variables (p)
omit hp
/-- `witt_vector.init n x` is polynomial in the coefficients of `x`. -/
lemma init_is_poly (n : ℕ) : is_poly p (λ R _Rcr, by exactI init n) :=
select_is_poly (λ i, i < n)
end
end witt_vector
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.