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
a0e480fd04111b522d122e804b990b50c83baca7
d7189ea2ef694124821b033e533f18905b5e87ef
/galois/arith.lean
999fe21125b4696f2856423877335dcc1595cd9b
[ "Apache-2.0" ]
permissive
digama0/lean-protocol-support
eaa7e6f8b8e0d5bbfff1f7f52bfb79a3b11b0f59
cabfa3abedbdd6fdca6e2da6fbbf91a13ed48dda
refs/heads/master
1,625,421,450,627
1,506,035,462,000
1,506,035,462,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,618
lean
import data.int.basic import data.rat import galois.nat.div_lemmas import data.nat.basic import galois.sum import init.data.ordering import data.vector import galois.nat import .bool universe u @[simp] theorem coe_bool_to_prop (b:bool) : coe b ↔ b = tt := begin cases b; exact dec_trivial, end @[simp] theorem to_bool_is_tt (p : Prop) [inst:decidable p] : (to_bool p = tt) = p := begin cases inst, all_goals { unfold decidable.to_bool, simp [a], }, end namespace nat lemma lt.intro {n m k : ℕ} (h : n + succ k = m) : n < m := h ▸ nat.succ_le_succ (nat.le_add_right n k) end nat namespace list section parameter {α : Type u} parameter (n : ℕ) parameter (f : fin n → α) protected def generate_core : Π (i j : ℕ), i + j = n → list α | i 0 pr := [] | i (nat.succ j) pr := let qr : i < n := nat.lt.intro pr in let rr : i+1 + j = n := begin simp [nat.succ_add i j], exact pr, end in f ⟨i, qr⟩ :: generate_core (i+1) j rr protected def generate : list α := generate_core 0 n (nat.zero_add n) theorem length_generate_core (i j : ℕ) : Π (pr : i + j = n), (generate_core i j pr).length = j := begin revert i, induction j, case nat.zero { intros, exact dec_trivial, }, case nat.succ j ind { intros, simp only [list.generate_core, length_cons], apply congr_arg nat.succ, apply ind, }, end protected theorem length_generate : generate.length = n := begin apply length_generate_core, end end section foldl₂ parameter {α : Type _} parameter {β : Type _} parameter {C : Type _} parameter (f : C → α → β → C) def foldl₂ : C → list α → list β → C | c [] _ := c | c _ [] := c | c (x::xr) (y::yr) := foldl₂ (f c x y) xr yr end foldl₂ section init parameter {α : Type _} protected theorem length_init (l : list α) : l.init.length = l.length - 1 := begin induction l, case nil { simp [init], }, case cons h r ind { cases r, { simp [init], }, case list.cons h2 r { simp only [init, length_cons, ind, nat.succ_sub_succ], trivial, } } end end init end list namespace vector def generate {α : Type u} (n : ℕ) (f : fin n → α) : vector α n := ⟨ list.generate n f, list.length_generate n f⟩ section foldl₂ parameter {α : Type _} parameter {β : Type _} parameter {C : Type _} parameter (f : C → α → β → C) parameter {n:ℕ} def foldl₂ (c:C) (x : vector α n) (y: vector β n) : C := list.foldl₂ f c x.to_list y.to_list end foldl₂ def dotprod {α: Type u} [semiring α] {n:ℕ} : vector α n → vector α n → α := foldl₂ (λc a b, c + a * b) 0 notation `⬝` := dotprod def last {α:Type u} {n:ℕ} (v : vector α (n+1)) : α := v.to_list.last (list.ne_nil_of_length_eq_succ v.property) -- Return all but the last element in a vector. def init {α:Type u} {n:ℕ} (v : vector α (n+1)) : vector α n := let pr : v.to_list.init.length = n := begin simp only [list.length_init, to_list_length], trivial, end in ⟨ v.to_list.init, pr⟩ def scale_mul {α:Type u} [has_mul α] {n:ℕ} (c:α) (v : vector α n) : vector α n := v.map (has_mul.mul c) end vector namespace list protected def maximum {α:Type _} [decidable_linear_order α] : list α → option α | [] := option.none | (h::r) := option.some (r.foldl max h) protected def minimum {α:Type _} [decidable_linear_order α] : list α → option α | [] := option.none | (h::r) := option.some (r.foldl min h) end list namespace rat def to_string (q:ℚ) : string := if q.denom = 1 then to_string (q.num) else to_string (q.num) ++ "/" ++ to_string q.denom instance : has_to_string ℚ := ⟨ to_string ⟩ end rat ----------------------------------------------------------------------- -- bound -- Return true if either option is none, or both are defined and first is -- less than second. def bound_le : option ℚ → option ℚ → Prop | none _ := true | (some l) (some u) := l ≤ u | (some _) none := true theorem bound_le_maximum_minimum (ll ul : list ℚ) (pr : ∀ (l u : ℚ), l ∈ ll → u ∈ ul → l ≤ u) : bound_le (list.maximum ll) (list.minimum ul) := sorry def le_bound (ol: option ℚ) (u : ℚ) : Prop := match ol with | option.none := true | (option.some l) := l ≤ u end instance le_bound.decidable (ol : option ℚ) (u:ℚ) : decidable (le_bound ol u) := begin cases ol; unfold le_bound; apply_instance end def ge_bound (l:ℚ) (ou: option ℚ) : Prop := match ou with | option.none := true | (option.some u) := l ≤ u end instance ge_bound.decidable (l:ℚ) (ou : option ℚ) : decidable (ge_bound l ou) := begin cases ou; unfold ge_bound; apply_instance end def choose_bound : option ℚ → option ℚ → ℚ | (some l) _ := l | none none := 0 | none (some u) := u theorem le_bound_choose_bound (l u : option ℚ) : le_bound l (choose_bound l u) := begin cases l with l, all_goals { simp [le_bound, choose_bound], }, end theorem ge_bound_choose_bound {l u : option ℚ} (pr : bound_le l u) : ge_bound (choose_bound l u) u := begin cases u with u, { simp [ge_bound, choose_bound], }, { cases l with l, { simp [ge_bound, choose_bound], }, { simp [bound_le] at pr, simp [ge_bound, choose_bound, pr], }, }, end ----------------------------------------------------------------------- -- assignment @[reducible] def assignment (α:Type _) (n:ℕ) := vector α n namespace assignment section parameter {α:Type _} /-- The empty assignment. -/ def empty : assignment α 0 := vector.nil def zero_assignment_is_empty (a:assignment α 0) : a = empty := begin simp [empty], apply vector.eq_nil, end def concat {n:ℕ} (xs : assignment α n) (x : α) : assignment α (n+1) := vector.cons x xs def shrink {n:ℕ} (a:assignment α n) (i : fin n) : assignment α i.val := begin have H1 : i.val ≤ n, apply le_of_lt, apply fin.is_lt, have H := vector.take i.val a, unfold min at H, rw (if_pos H1) at H, apply H end -- def last_of_fin {n:ℕ} (a:assignment α n) (i : fin n) : α := -- sorry -- def init {n:ℕ} (a:assignment α (n+1)) : assignment α n := -- sorry -- def last {n:ℕ} (a:assignment α (n+1)) : α := -- sorry @[simp] theorem init_concat {n:ℕ} (a:assignment α n) (z:α) : vector.init (concat a z) = a := sorry @[simp] theorem last_concat {n:ℕ} (a:assignment α n) (z:α) : vector.last (concat a z) = z := sorry end end assignment -- denotes the inequality coef <= bound inductive linear_expr : ℕ → Type | const : Π {n:ℕ}, ℚ → linear_expr n | add : Π {n:ℕ} (c:ℚ) (pr : c ≠ 0) (i : fin n), linear_expr i.val → linear_expr n lemma nat_ordering_char (x y : ℕ) : (match nat.cmp x y with | ordering.lt := x < y | ordering.eq := x = y | ordering.gt := x > y end : Prop) := begin dsimp [nat.cmp], apply (if H : x < y then _ else _), rw (if_pos H), assumption, rw (if_neg H), apply (if H' : x = y then _ else _), rw (if_pos H'), assumption, rw (if_neg H'), dsimp, dsimp [(>)], rw lt_iff_not_ge, intros contra, apply H', apply le_antisymm, assumption, apply le_of_not_gt, assumption, end namespace fin lemma lt_char {n : ℕ} (x y : fin n) : x < y ↔ x.val < y.val := begin induction x; induction y; reflexivity end def extend_le {m n : ℕ} (H : m ≤ n) (x : fin m) : fin n := begin constructor, apply lt_of_lt_of_le, apply fin.is_lt, assumption, assumption, end def restrict_lt {n : ℕ} (x y : fin n) (H : x < y) : fin y.val := ⟨ x.val, begin rw lt_char at H, assumption end ⟩ def ordering_elim {n : ℕ} (C : Sort _) (x y : fin n) (Hlt : x < y → C) (Heq : x = y → C) (Hgt : x > y → C) : C := begin have H := nat_ordering_char x.val y.val, cases (nat.cmp x.val y.val); dsimp at H, { apply Hlt, rw lt_char, assumption }, { induction x, induction y, dsimp at H, apply Heq, subst H, }, { apply Hgt, unfold gt, rw fin.lt_char, assumption }, end end fin namespace linear_expr def scale_mul (x : ℚ) (xne0 : x ≠ 0) : ∀ {n}, linear_expr n → linear_expr n | _ (const c) := const (x * c) | _ (add c cne0 i e) := add (x * c) (mul_ne_zero xne0 cne0) i (scale_mul e) def add_constant (x : ℚ) : ∀ {n}, linear_expr n → linear_expr n | _ (const c) := const (x + c) | _ (add c cne0 i e) := add c cne0 i (add_constant e) def extend {i n :ℕ} : linear_expr i → i ≤ n → linear_expr n | (const c) is_le := const c | (add c pr j e) is_le := add c pr ⟨j.val, lt_of_lt_of_le j.is_lt is_le⟩ e def add_variable (x : ℚ) : ∀ {n}, fin n → linear_expr n → linear_expr n | _ i (const c) := if xne0 : x ≠ 0 then add x xne0 i (const c) else const c | n i (add c cne0 i' e) := begin apply (fin.ordering_elim (linear_expr n) i i'); intros, { apply (add c cne0 i'), apply add_variable, apply fin.restrict_lt, assumption, assumption, }, { apply (if H : x + c ≠ 0 then _ else _), { apply (add (x + c) H i' e), }, { apply e.extend, apply le_of_lt, apply fin.is_lt, } }, { apply (if H : x ≠ 0 then _ else _), { apply (add x H i), apply (add c cne0), admit, admit }, { apply e.extend, apply le_of_lt, apply fin.is_lt, } } end def sum : ∀ {n}, linear_expr n → linear_expr n → linear_expr n | _ (const c) e := add_constant c e | _ (add c cne0 i e) e' := sorry def as_const : linear_expr 0 → ℚ | (const c) := c | (add _ _ i _) := begin have is_lit := i.is_lt, have h := nat.not_lt_zero i.val, contradiction, end def prepend_sum : string → string → string | s "" := s | s t := s ++ " + " ++ t def to_string_core : Π {n:ℕ}, linear_expr n → string → string | _ (const c) s := if s = "" then to_string c else if c = 0 ∧ s ≠ "" then s else s ++ " + " ++ to_string c | _ (add c _ i e) s := to_string_core e (if c = 1 then prepend_sum ("v" ++ to_string i) s else prepend_sum (to_string c ++"×v" ++ to_string i) s) def to_string {n:ℕ} (e:linear_expr n) : string := to_string_core e "" def var {n:ℕ} (i : fin n) : linear_expr n := add 1 dec_trivial i (const 0) /-- Return the last coefficient of the linear_expression. -/ def last {n:ℕ} : linear_expr (n+1) → ℚ | (const c) := 0 | (add c pr i e) := if i.val = n then c else 0 /-- Return the expression with the last variable removed and the coefficient. -/ def drop_last {n:ℕ} : linear_expr (n+1) → linear_expr n | (const c) := const c | (add c pr i e) := if i_lt_n : i.val < n then add c pr ⟨i.val, i_lt_n⟩ e else e.extend (nat.pred_le_pred i.is_lt) section evaluate parameter {n:ℕ} def evaluate_core : ℚ → Π{n:ℕ}, linear_expr n → assignment ℚ n → ℚ | r _ (const c) _ := c + r | r _ (add c pr i e) a := evaluate_core (r + c * a.nth i) e (a.shrink i) def evaluate : Π{n:ℕ}, linear_expr n → assignment ℚ n → ℚ := @evaluate_core 0 end evaluate end linear_expr ----------------------------------------------------------------------- -- linear_expr_list def linear_expr_list (n:ℕ) := list (linear_expr n) namespace linear_expr_list def to_list {n:ℕ} : linear_expr_list n → list (linear_expr n) := id instance (n:ℕ) : has_mem (linear_expr n) (linear_expr_list n) := begin unfold linear_expr_list, apply_instance end section parameter {n:ℕ} def evaluate (l : linear_expr_list n) (a : assignment ℚ n) : list ℚ := l.map (λe, e.evaluate a) theorem evaluate_cons (e : linear_expr n) (l : linear_expr_list n) (a : assignment ℚ n) : evaluate (e :: l) a = e.evaluate a :: l.evaluate a := rfl theorem mem_evaluate_implies {l: linear_expr_list n} {a:assignment ℚ n} {q : ℚ} (pr : q ∈ l.evaluate a) : ∃(e:linear_expr n), e ∈ l ∧ e.evaluate a = q := begin apply list.exists_of_mem_map pr, end end end linear_expr_list --------------------------------------------------------- -- Inequalities -- denotes the inequality lhs <= 0 structure inequality (n:ℕ) := (lhs : linear_expr n) namespace inequality section entails parameter {n:ℕ} def from_pair : linear_expr n → linear_expr n → inequality n := sorry def satisfies (θ:assignment ℚ n) (c:inequality n) : Prop := c.lhs.evaluate θ ≤ 0 theorem satisfies_from_pair (a:assignment ℚ n) (l u:linear_expr n) : satisfies a (from_pair l u) ↔ l.evaluate a ≤ u.evaluate a := sorry instance (c:inequality n) (θ:assignment ℚ n) : decidable (satisfies θ c) := begin unfold satisfies, apply_instance end end entails notation `⊧` := satisfies end inequality /-- A collection on inequalities -/ def ineqs (n:ℕ) := list (inequality n) namespace ineqs instance (n:ℕ) : has_append (ineqs n) := begin unfold ineqs, apply_instance end instance (n:ℕ) : has_mem (inequality n) (ineqs n) := begin unfold ineqs, apply_instance end section satisfies parameter {n:ℕ} parameter (a:assignment ℚ n) -- Returns true if assignment satisfies bound. def satisfies (eqs:ineqs n) : Prop := eqs.all (λb, to_bool (inequality.satisfies a b)) instance (eqs:ineqs n) : decidable (satisfies eqs) := begin unfold satisfies, apply_instance end @[simp] theorem satisfies_nil : satisfies [] := begin simp [satisfies, list.all], end @[simp] theorem satisfies_cons (h : inequality n) (r : ineqs n) : satisfies (h :: r) ↔ inequality.satisfies a h ∧ satisfies r := begin simp [satisfies, list.all, list.foldr], end @[simp] theorem satisfies_append (x y : ineqs n) : satisfies (x ++ y) = (satisfies x ∧ satisfies y) := sorry end satisfies theorem satisfies_list_implies_mem_satisfies {n:ℕ} {e : inequality n} {l : ineqs n} {a:assignment ℚ n} (pr : satisfies a l) (in_list : e ∈ l) : inequality.satisfies a e := sorry /-- Denotes a solution to the equations. -/ def solution {n:ℕ} (eqs:ineqs n) := { a : assignment ℚ n // eqs.satisfies a } /-- A proof that the equations are unsatisfiable. -/ def unsat_proof {n:ℕ} (eqs:ineqs n) := ∀(a:assignment ℚ n), ¬ (satisfies a eqs) end ineqs ----------------------------------------------------------------------- -- bound inductive bound (n:ℕ) : Type -- lower e denotes e <= x | lower : linear_expr n → bound -- upper e denotes x <= e | upper : linear_expr n → bound -- If variable had a zero in the expression. | independent : inequality n → bound namespace bound /-- Given an inequality infers the resulting bound on the last variable. -/ def from_ineq {n:ℕ} (le : inequality (n+1)) : bound n := let e := le.lhs in let c := e.last in let r := e.drop_last in if c > 0 then -- "l + c * v <= 0" ~> "v <= -l/c" let recip := 1/c in bound.upper (linear_expr.scale_mul (-1/c) sorry r) -- "l + c * v <= 0" ~> "l/c <= v" else if c < 0 then bound.lower (linear_expr.scale_mul (1/c) sorry r) else bound.independent ⟨ r ⟩ section parameter {n:ℕ} -- Returns true if assignment satisfies bound. def satisfies (a:assignment ℚ (n+1)) : bound n → Prop | (lower e) := e.evaluate a.init ≤ a.last | (upper e) := a.last ≤ e.evaluate a.init | (independent le) := le.satisfies a.init @[simp] theorem satisfies_from_ineq (a: assignment ℚ (n+1)) (le : inequality (n+1)) : bound.satisfies a (bound.from_ineq le) = inequality.satisfies a le := sorry end end bound ----------------------------------------------------------------------- -- bound_list structure bound_list (n:ℕ) := (lower : linear_expr_list n) (upper : linear_expr_list n) (independent : ineqs n) namespace bound_list def empty (n:ℕ) : bound_list n := { lower := [], upper := [], independent := []} def lower_bound {n:ℕ} (b:bound_list n) (a:assignment ℚ n) : option ℚ := (b.lower.evaluate a).maximum def upper_bound {n:ℕ} (b:bound_list n) (a:assignment ℚ n) : option ℚ := (b.upper.evaluate a).minimum section satisfies parameter {n:ℕ} parameter (a:assignment ℚ (n+1)) -- Returns true if assignment satisfies bound. def satisfies (b:bound_list n) : Prop := le_bound (b.lower_bound a.init) a.last ∧ ge_bound a.last (b.upper_bound a.init) ∧ ineqs.satisfies a.init b.independent instance (b:bound_list n) : decidable (satisfies b) := begin unfold satisfies, apply_instance, end end satisfies @[simp] theorem satisfies_empty (n:ℕ) (a:assignment ℚ (n+1)) : satisfies a (empty n) := begin simp [empty, satisfies, upper_bound, lower_bound, linear_expr_list.evaluate, list.minimum, ge_bound, le_bound], end section from_ineqs parameter {n:ℕ} def add_bound : bound n → bound_list n → bound_list n | (bound.lower e) b := { b with lower := e :: b.lower } | (bound.upper e) b := { b with upper := e :: b.upper } | (bound.independent e) b := { b with independent := e :: b.independent } theorem satisfies_add_bound (a:assignment ℚ (n+1)) (b:bound n) (l: bound_list n) : satisfies a (bound_list.add_bound b l) ↔ (bound.satisfies a b ∧ satisfies a l) := begin apply iff.intro, { cases b, case bound.lower e { cases l, simp [satisfies, add_bound, bound.satisfies, lower_bound, upper_bound], intros ineq_sat, admit, }, case bound.upper e { admit, }, case bound.independent ineq { admit, }, }, { admit, } end /-- Return bounds on last variable. -/ def from_ineqs (l:ineqs (n+1)) : bound_list n := l.foldr (λe, add_bound (bound.from_ineq e)) (empty n) @[simp] theorem from_ineqs_nil : from_ineqs list.nil = empty n := rfl @[simp] theorem from_ineqs_cons (e: inequality (n+1)) (l:ineqs (n+1)) : from_ineqs (e::l) = add_bound (bound.from_ineq e) (from_ineqs l) := begin simp [from_ineqs], end end from_ineqs section parameter {n:ℕ} def to_ineqs (b:bound_list n) : ineqs n := b.independent ++ (do l ← b.lower.to_list, inequality.from_pair l <$> b.upper.to_list) theorem lower_upper_in_to_ineqs {l u:linear_expr n} {b: bound_list n} (in_lower : l ∈ b.lower) (in_upper : u ∈ b.upper) : (inequality.from_pair l u ∈ to_ineqs b) := sorry end def solution {n:ℕ} (eqs:bound_list n) := { a : assignment ℚ (n+1) // eqs.satisfies a } theorem to_ineqs_preserve_sat {n:ℕ} {b: bound_list n} (a:assignment ℚ (n+1)) (pr : bound_list.satisfies a b) : ineqs.satisfies a.init b.to_ineqs := begin admit, end theorem lower_le_upper {n:ℕ} {b: bound_list n} (a:assignment ℚ n) (pr : ineqs.satisfies a b.to_ineqs) : bound_le (b.lower_bound a) (b.upper_bound a) := begin simp [lower_bound, upper_bound], apply bound_le_maximum_minimum, intros l u l_mem u_mem, apply exists.elim (linear_expr_list.mem_evaluate_implies l_mem), intros l_eq l_cond, apply exists.elim (linear_expr_list.mem_evaluate_implies u_mem), intros u_eq u_cond, have in_list := lower_upper_in_to_ineqs l_cond.left u_cond.left, have is_sat := ineqs.satisfies_list_implies_mem_satisfies pr in_list, simp [inequality.satisfies_from_pair] at is_sat, cc, end end bound_list ----------------------------------------------------------------------- -- to_ineqs theorems theorem bounded_list.satisfies_concat {n:ℕ} {b: bound_list n} (a:assignment ℚ n) {z : ℚ} (pr : ineqs.satisfies a b.to_ineqs) (sat_lower : le_bound (b.lower_bound a) z) (sat_upper : ge_bound z (b.upper_bound a)) : bound_list.satisfies (a.concat z) b := begin unfold bound_list.satisfies, simp, simp [bound_list.to_ineqs] at pr, cc, end ----------------------------------------------------------------------- -- from_ineqs theorems theorem from_ineqs_preserve_sat {n:ℕ} {l: ineqs (n+1)} (a:assignment ℚ (n+1)) : bound_list.satisfies a (bound_list.from_ineqs l) ↔ ineqs.satisfies a l := begin induction l, case list.nil { simp, }, case list.cons h r ind { simp [bound_list.satisfies_add_bound], cc, }, end def ineqs.solution.to_bound_list {n:ℕ} {b : bound_list n} : b.to_ineqs.solution → b.solution | ⟨ a, pr ⟩ := let z : ℚ := choose_bound (b.lower_bound a) (b.upper_bound a) in let qr : b.satisfies (assignment.concat a z) := begin apply bounded_list.satisfies_concat _ pr, { apply le_bound_choose_bound, }, { apply ge_bound_choose_bound, apply bound_list.lower_le_upper, apply pr, } end in ⟨ (a.concat z : assignment ℚ (n+1)), qr ⟩ def bound_list.solution.to_ineqs {n:ℕ} {l : ineqs (n+1)} : (bound_list.from_ineqs l).solution → l.solution | ⟨ a, pr ⟩ := let qr : l.satisfies a := iff.mp (from_ineqs_preserve_sat _) pr in ⟨ a, qr ⟩ inductive sat_result {n:ℕ} (eqs:ineqs n) | unsat : eqs.unsat_proof → sat_result | sat : eqs.solution → sat_result def solve_inequalities : Π {n:ℕ} (eqs:ineqs n), sat_result eqs | 0 l := if pr : l.satisfies assignment.empty then sat_result.sat ⟨ assignment.empty, pr ⟩ else sat_result.unsat (begin unfold ineqs.unsat_proof, intros a, rw [assignment.zero_assignment_is_empty a], exact pr, end) | (nat.succ n) l := match solve_inequalities (bound_list.from_ineqs l).to_ineqs with | sat_result.sat a := sat_result.sat a.to_bound_list.to_ineqs | sat_result.unsat pr := sat_result.unsat $ begin unfold ineqs.unsat_proof, intros a contra, unfold ineqs.unsat_proof at pr, apply pr a.init, apply bound_list.to_ineqs_preserve_sat a, apply iff.mpr (from_ineqs_preserve_sat a), exact contra, end end ----------------------------------------------------------------------- ----------------------------------------------------------------------- -- Meta open tactic namespace linear inductive type : Type | nat : type | int : type | rat : type meta def type.resolve : expr → string ⊕ type | `(nat) := pure type.nat | `(int) := pure type.int | `(rat) := pure type.rat | e := sum.inl ("Unknown type:" ++ to_string e) set_option pp.all true meta inductive lexpr : type → Type | foreign : Π(tp:type), expr → lexpr tp | add : Π{tp:type}, lexpr tp → lexpr tp → lexpr tp | zero : Π(tp:type), lexpr tp | one : Π(tp:type), lexpr tp | bit0 : Π{tp:type}, lexpr tp → lexpr tp | bit1 : Π{tp:type}, lexpr tp → lexpr tp protected meta def lexpr.resolve : Π(tp:type), expr → lexpr tp | ltp `(@has_add.add %%tp %%inst %%x %%y) := lexpr.add (lexpr.resolve ltp x) (lexpr.resolve ltp y) | ltp `(@has_zero.zero %%tp %%inst) := lexpr.zero ltp | ltp `(@has_one.one %%tp %%inst) := lexpr.one ltp | ltp `(@bit0 %%tp %%inst %%x) := lexpr.bit0 (lexpr.resolve ltp x) | ltp `(@bit1 %%tp %%one_inst %%add_inst %%x) := lexpr.bit1 (lexpr.resolve ltp x) | ltp e := lexpr.foreign ltp e namespace lexpr section to_string protected meta def to_string : ∀ {tp:type}, lexpr tp → string | tp (foreign ._ x) := "<" ++ has_to_string.to_string x ++ ">" | _ (add x y) := "(add " ++ to_string x ++ " " ++ to_string y ++ ")" | tp (zero ._) := "(zero)" | tp (one ._) := "(one)" | _ (bit0 x) := "(bit0 " ++ to_string x ++ ")" | _ (bit1 x) := "(bit1 " ++ to_string x ++ ")" meta instance {tp:type} : has_to_string (lexpr tp) := ⟨@lexpr.to_string tp⟩ end to_string end lexpr meta inductive prop : Type | eq : Π(tp:type), lexpr tp → lexpr tp → prop | ge : Π(tp:type), lexpr tp → lexpr tp → prop | gt : Π(tp:type), lexpr tp → lexpr tp → prop | le : Π(tp:type), lexpr tp → lexpr tp → prop | lt : Π(tp:type), lexpr tp → lexpr tp → prop set_option pp.all true meta def prop.mk_bin (f : Π(tp:type), lexpr tp → lexpr tp → prop) (resolve_tp : string ⊕ type) (l r : expr) : string ⊕ prop := do tp ← resolve_tp, pure (f tp (lexpr.resolve tp l) (lexpr.resolve tp r)) /- Resovle an expression into a prop. N.B. This may do the wrong thing if the expression contains a non-standard typeclass instance for a primitive type. -/ meta def prop.resolve : expr → string ⊕ prop | `(@eq.{1} %%tp %%l %%r) := prop.mk_bin prop.eq (type.resolve tp) l r | `(@ge %%tp %%inst %%l %%r) := prop.mk_bin prop.ge (type.resolve tp) l r | `(@gt %%tp %%inst %%l %%r) := prop.mk_bin prop.gt (type.resolve tp) l r | `(@has_le.le %%tp %%inst %%l %%r) := prop.mk_bin prop.ge (type.resolve tp) l r | `(@has_lt.lt %%tp %%inst %%l %%r) := prop.mk_bin prop.gt (type.resolve tp) l r | _ := sum.inl "Unknown expr" namespace prop protected meta def to_string : prop → string | (eq tp l r) := "eq " ++ l.to_string ++ " " ++ r.to_string | (ge tp l r) := "ge " ++ l.to_string ++ " " ++ r.to_string | (gt tp l r) := "gt " ++ l.to_string ++ " " ++ r.to_string | (le tp l r) := "le " ++ l.to_string ++ " " ++ r.to_string | (lt tp l r) := "lt " ++ l.to_string ++ " " ++ r.to_string meta instance : has_to_string prop := ⟨ prop.to_string ⟩ end prop meta def linear_solve : tactic unit := do intros, ctx ← local_context, ctx_types ← ctx.mmap infer_type, let pp (e : expr) : tactic unit := (do match prop.resolve e with | sum.inl msg := trace (msg ++ "\n" ++ to_string e) | (sum.inr p) := do trace (to_string p) end), _ ← ctx_types.mmap pp, t ← target, match t with | `(true) := do trace (to_string (ctx.length)), exact `(true.intro) | _ := do let i := ctx_types.index_of t, if i < ctx.length then do match ctx.nth i with | (option.some pr) := exact pr | option.none := fail "ctx.nth failed" end else trace "nope", pure () end example (x y : ℕ) : x = 0 → x = 1 → y = 2 → y = 3 → x = 1 := begin intro p, -- cc, linear_solve, end end linear
69442c56702ec2f5febed717c0160fab8d95eee8
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/equiv/denumerable.lean
0bb64a4c67413ef8977294a5e1ff03a73fc9941f
[ "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
10,532
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.equiv.encodable.basic import data.sigma import data.fintype.basic import data.list.min_max /-! # Denumerable types This file defines denumerable (countably infinite) types as a typeclass extending `encodable`. This is used to provide explicit encode/decode functions from and to `ℕ`, with the information that those functions are inverses of each other. ## Implementation notes This property already has a name, namely `α ≃ ℕ`, but here we are interested in using it as a typeclass. -/ /-- A denumerable type is (constructively) bijective with `ℕ`. Typeclass equivalent of `α ≃ ℕ`. -/ class denumerable (α : Type*) extends encodable α := (decode_inv : ∀ n, ∃ a ∈ decode n, encode a = n) open nat namespace denumerable section variables {α : Type*} {β : Type*} [denumerable α] [denumerable β] open encodable theorem decode_is_some (α) [denumerable α] (n : ℕ) : (decode α n).is_some := option.is_some_iff_exists.2 $ (decode_inv n).imp $ λ a, Exists.fst /-- Returns the `n`-th element of `α` indexed by the decoding. -/ def of_nat (α) [f : denumerable α] (n : ℕ) : α := option.get (decode_is_some α n) @[simp, priority 900] theorem decode_eq_of_nat (α) [denumerable α] (n : ℕ) : decode α n = some (of_nat α n) := option.eq_some_of_is_some _ @[simp] theorem of_nat_of_decode {n b} (h : decode α n = some b) : of_nat α n = b := option.some.inj $ (decode_eq_of_nat _ _).symm.trans h @[simp] theorem encode_of_nat (n) : encode (of_nat α n) = n := let ⟨a, h, e⟩ := decode_inv n in by rwa [of_nat_of_decode h] @[simp] theorem of_nat_encode (a) : of_nat α (encode a) = a := of_nat_of_decode (encodek _) /-- A denumerable type is equivalent to `ℕ`. -/ def eqv (α) [denumerable α] : α ≃ ℕ := ⟨encode, of_nat α, of_nat_encode, encode_of_nat⟩ @[priority 100] -- See Note [lower instance priority] instance : infinite α := infinite.of_surjective _ (eqv α).surjective /-- A type equivalent to `ℕ` is denumerable. -/ def mk' {α} (e : α ≃ ℕ) : denumerable α := { encode := e, decode := some ∘ e.symm, encodek := λ a, congr_arg some (e.symm_apply_apply _), decode_inv := λ n, ⟨_, rfl, e.apply_symm_apply _⟩ } /-- Denumerability is conserved by equivalences. This is transitivity of equivalence the denumerable way. -/ def of_equiv (α) {β} [denumerable α] (e : β ≃ α) : denumerable β := { decode_inv := λ n, by simp, ..encodable.of_equiv _ e } @[simp] theorem of_equiv_of_nat (α) {β} [denumerable α] (e : β ≃ α) (n) : @of_nat β (of_equiv _ e) n = e.symm (of_nat α n) := by apply of_nat_of_decode; show option.map _ _ = _; simp /-- All denumerable types are equivalent. -/ def equiv₂ (α β) [denumerable α] [denumerable β] : α ≃ β := (eqv α).trans (eqv β).symm instance nat : denumerable ℕ := ⟨λ n, ⟨_, rfl, rfl⟩⟩ @[simp] theorem of_nat_nat (n) : of_nat ℕ n = n := rfl /-- If `α` is denumerable, then so is `option α`. -/ instance option : denumerable (option α) := ⟨λ n, begin cases n, { refine ⟨none, _, encode_none⟩, rw [decode_option_zero, option.mem_def] }, refine ⟨some (of_nat α n), _, _⟩, { rw [decode_option_succ, decode_eq_of_nat, option.map_some', option.mem_def] }, rw [encode_some, encode_of_nat], end⟩ /-- If `α` and `β` are denumerable, then so is their sum. -/ instance sum : denumerable (α ⊕ β) := ⟨λ n, begin suffices : ∃ a ∈ @decode_sum α β _ _ n, encode_sum a = bit (bodd n) (div2 n), {simpa [bit_decomp]}, simp [decode_sum]; cases bodd n; simp [decode_sum, bit, encode_sum] end⟩ section sigma variables {γ : α → Type*} [∀ a, denumerable (γ a)] /-- A denumerable collection of denumerable types is denumerable. -/ instance sigma : denumerable (sigma γ) := ⟨λ n, by simp [decode_sigma]; exact ⟨_, _, ⟨rfl, heq.rfl⟩, by simp⟩⟩ @[simp] theorem sigma_of_nat_val (n : ℕ) : of_nat (sigma γ) n = ⟨of_nat α (unpair n).1, of_nat (γ _) (unpair n).2⟩ := option.some.inj $ by rw [← decode_eq_of_nat, decode_sigma_val]; simp; refl end sigma /-- If `α` and `β` are denumerable, then so is their product. -/ instance prod : denumerable (α × β) := of_equiv _ (equiv.sigma_equiv_prod α β).symm @[simp] theorem prod_of_nat_val (n : ℕ) : of_nat (α × β) n = (of_nat α (unpair n).1, of_nat β (unpair n).2) := by simp; refl @[simp] theorem prod_nat_of_nat : of_nat (ℕ × ℕ) = unpair := by funext; simp instance int : denumerable ℤ := denumerable.mk' equiv.int_equiv_nat instance pnat : denumerable ℕ+ := denumerable.mk' equiv.pnat_equiv_nat /-- The lift of a denumerable type is denumerable. -/ instance ulift : denumerable (ulift α) := of_equiv _ equiv.ulift /-- The lift of a denumerable type is denumerable. -/ instance plift : denumerable (plift α) := of_equiv _ equiv.plift /-- If `α` is denumerable, then `α × α` and `α` are equivalent. -/ def pair : α × α ≃ α := equiv₂ _ _ end end denumerable namespace nat.subtype open function encodable /-! ### Subsets of `ℕ` -/ variables {s : set ℕ} [infinite s] section classical open_locale classical lemma exists_succ (x : s) : ∃ n, ↑x + n + 1 ∈ s := classical.by_contradiction $ λ h, have ∀ (a : ℕ) (ha : a ∈ s), a < succ x, from λ a ha, lt_of_not_ge (λ hax, h ⟨a - (x + 1), by rwa [add_right_comm, add_tsub_cancel_of_le hax]⟩), fintype.false ⟨(((multiset.range (succ x)).filter (∈ s)).pmap (λ (y : ℕ) (hy : y ∈ s), subtype.mk y hy) (by simp [-multiset.range_succ])).to_finset, by simpa [subtype.ext_iff_val, multiset.mem_filter, -multiset.range_succ]⟩ end classical variable [decidable_pred (∈ s)] /-- Returns the next natural in a set, according to the usual ordering of `ℕ`. -/ def succ (x : s) : s := have h : ∃ m, ↑x + m + 1 ∈ s, from exists_succ x, ⟨↑x + nat.find h + 1, nat.find_spec h⟩ lemma succ_le_of_lt {x y : s} (h : y < x) : succ y ≤ x := have hx : ∃ m, ↑y + m + 1 ∈ s, from exists_succ _, let ⟨k, hk⟩ := nat.exists_eq_add_of_lt h in have nat.find hx ≤ k, from nat.find_min' _ (hk ▸ x.2), show (y : ℕ) + nat.find hx + 1 ≤ x, by rw hk; exact add_le_add_right (add_le_add_left this _) _ lemma le_succ_of_forall_lt_le {x y : s} (h : ∀ z < x, z ≤ y) : x ≤ succ y := have hx : ∃ m, ↑y + m + 1 ∈ s, from exists_succ _, show ↑x ≤ ↑y + nat.find hx + 1, from le_of_not_gt $ λ hxy, (h ⟨_, nat.find_spec hx⟩ hxy).not_lt $ calc ↑y ≤ ↑y + nat.find hx : le_add_of_nonneg_right (nat.zero_le _) ... < ↑y + nat.find hx + 1 : nat.lt_succ_self _ lemma lt_succ_self (x : s) : x < succ x := calc (x : ℕ) ≤ x + _ : le_self_add ... < succ x : nat.lt_succ_self (x + _) lemma lt_succ_iff_le {x y : s} : x < succ y ↔ x ≤ y := ⟨λ h, le_of_not_gt (λ h', not_le_of_gt h (succ_le_of_lt h')), λ h, lt_of_le_of_lt h (lt_succ_self _)⟩ /-- Returns the `n`-th element of a set, according to the usual ordering of `ℕ`. -/ def of_nat (s : set ℕ) [decidable_pred (∈ s)] [infinite s] : ℕ → s | 0 := ⊥ | (n+1) := succ (of_nat n) lemma of_nat_surjective_aux : ∀ {x : ℕ} (hx : x ∈ s), ∃ n, of_nat s n = ⟨x, hx⟩ | x := λ hx, let t : list s := ((list.range x).filter (λ y, y ∈ s)).pmap (λ (y : ℕ) (hy : y ∈ s), ⟨y, hy⟩) (by simp) in have hmt : ∀ {y : s}, y ∈ t ↔ y < ⟨x, hx⟩, by simp [list.mem_filter, subtype.ext_iff_val, t]; intros; refl, have wf : ∀ m : s, list.maximum t = m → ↑m < x, from λ m hmax, by simpa [hmt] using list.maximum_mem hmax, begin cases hmax : list.maximum t with m, { exact ⟨0, le_antisymm bot_le (le_of_not_gt (λ h, list.not_mem_nil (⊥ : s) $ by rw [← list.maximum_eq_none.1 hmax, hmt]; exact h))⟩ }, cases of_nat_surjective_aux m.2 with a ha, exact ⟨a + 1, le_antisymm (by rw of_nat; exact succ_le_of_lt (by rw ha; exact wf _ hmax)) $ by rw of_nat; exact le_succ_of_forall_lt_le (λ z hz, by rw ha; cases m; exact list.le_maximum_of_mem (hmt.2 hz) hmax)⟩ end using_well_founded {dec_tac := `[tauto]} lemma of_nat_surjective : surjective (of_nat s) := λ ⟨x, hx⟩, of_nat_surjective_aux hx private def to_fun_aux (x : s) : ℕ := (list.range x).countp (∈ s) private lemma to_fun_aux_eq (x : s) : to_fun_aux x = ((finset.range x).filter (∈ s)).card := by rw [to_fun_aux, list.countp_eq_length_filter]; refl open finset private lemma right_inverse_aux : ∀ n, to_fun_aux (of_nat s n) = n | 0 := begin rw [to_fun_aux_eq, card_eq_zero, eq_empty_iff_forall_not_mem], rintro n hn, rw [mem_filter, of_nat, mem_range] at hn, exact bot_le.not_lt (show (⟨n, hn.2⟩ : s) < ⊥, from hn.1), end | (n+1) := have ih : to_fun_aux (of_nat s n) = n, from right_inverse_aux n, have h₁ : (of_nat s n : ℕ) ∉ (range (of_nat s n)).filter (∈ s), by simp, have h₂ : (range (succ (of_nat s n))).filter (∈ s) = insert (of_nat s n) ((range (of_nat s n)).filter (∈ s)), begin simp only [finset.ext_iff, mem_insert, mem_range, mem_filter], exact λ m, ⟨λ h, by simp only [h.2, and_true]; exact or.symm (lt_or_eq_of_le ((@lt_succ_iff_le _ _ _ ⟨m, h.2⟩ _).1 h.1)), λ h, h.elim (λ h, h.symm ▸ ⟨lt_succ_self _, (of_nat s n).prop⟩) (λ h, ⟨h.1.trans (lt_succ_self _), h.2⟩)⟩, end, begin simp only [to_fun_aux_eq, of_nat, range_succ] at ⊢ ih, conv {to_rhs, rw [← ih, ← card_insert_of_not_mem h₁, ← h₂] }, end /-- Any infinite set of naturals is denumerable. -/ def denumerable (s : set ℕ) [decidable_pred (∈ s)] [infinite s] : denumerable s := denumerable.of_equiv ℕ { to_fun := to_fun_aux, inv_fun := of_nat s, left_inv := left_inverse_of_surjective_of_right_inverse of_nat_surjective right_inverse_aux, right_inv := right_inverse_aux } end nat.subtype namespace denumerable open encodable /-- An infinite encodable type is denumerable. -/ def of_encodable_of_infinite (α : Type*) [encodable α] [infinite α] : denumerable α := begin letI := @decidable_range_encode α _; letI : infinite (set.range (@encode α _)) := infinite.of_injective _ (equiv.of_injective _ encode_injective).injective, letI := nat.subtype.denumerable (set.range (@encode α _)), exact denumerable.of_equiv (set.range (@encode α _)) (equiv_range_encode α), end end denumerable
f51d252c0b095ded444a76940bacff193d50334b
618003631150032a5676f229d13a079ac875ff77
/src/linear_algebra/matrix.lean
512a9653e09a0613e1638b09378df377d5fbdc2c
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
11,759
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl, Casper Putz -/ import linear_algebra.dimension /-! # Linear maps and matrices This file defines the maps to send matrices to a linear map, and to send linear maps between modules with a finite bases to matrices. This defines a linear equivalence between linear maps between finite-dimensional vector spaces and matrices indexed by the respective bases. Some results are proved about the linear map corresponding to a diagonal matrix (range, ker and rank). ## Main definitions to_lin, to_matrix, linear_equiv_matrix ## Tags linear_map, matrix, linear_equiv, diagonal -/ noncomputable theory open set submodule universes u v w variables {l m n : Type u} [fintype l] [fintype m] [fintype n] namespace matrix variables {R : Type v} [comm_ring R] instance [decidable_eq m] [decidable_eq n] (R) [fintype R] : fintype (matrix m n R) := by unfold matrix; apply_instance /-- Evaluation of matrices gives a linear map from matrix m n R to linear maps (n → R) →ₗ[R] (m → R). -/ def eval : (matrix m n R) →ₗ[R] ((n → R) →ₗ[R] (m → R)) := begin refine linear_map.mk₂ R mul_vec _ _ _ _, { assume M N v, funext x, change finset.univ.sum (λy:n, (M x y + N x y) * v y) = _, simp only [_root_.add_mul, finset.sum_add_distrib], refl }, { assume c M v, funext x, change finset.univ.sum (λy:n, (c * M x y) * v y) = _, simp only [_root_.mul_assoc, finset.mul_sum.symm], refl }, { assume M v w, funext x, change finset.univ.sum (λy:n, M x y * (v y + w y)) = _, simp [_root_.mul_add, finset.sum_add_distrib], refl }, { assume c M v, funext x, change finset.univ.sum (λy:n, M x y * (c * v y)) = _, rw [show (λy:n, M x y * (c * v y)) = (λy:n, c * (M x y * v y)), { funext n, ac_refl }, ← finset.mul_sum], refl } end /-- Evaluation of matrices gives a map from matrix m n R to linear maps (n → R) →ₗ[R] (m → R). -/ def to_lin : matrix m n R → (n → R) →ₗ[R] (m → R) := eval.to_fun lemma to_lin_add (M N : matrix m n R) : (M + N).to_lin = M.to_lin + N.to_lin := matrix.eval.map_add M N @[simp] lemma to_lin_zero : (0 : matrix m n R).to_lin = 0 := matrix.eval.map_zero @[simp] lemma to_lin_neg (M : matrix m n R) : (-M).to_lin = -M.to_lin := @linear_map.map_neg _ _ ((n → R) →ₗ[R] m → R) _ _ _ _ _ matrix.eval M instance to_lin.is_linear_map : @is_linear_map R (matrix m n R) ((n → R) →ₗ[R] (m → R)) _ _ _ _ _ to_lin := matrix.eval.is_linear instance to_lin.is_add_monoid_hom : @is_add_monoid_hom (matrix m n R) ((n → R) →ₗ[R] (m → R)) _ _ to_lin := { map_zero := to_lin_zero, map_add := to_lin_add } @[simp] lemma to_lin_apply (M : matrix m n R) (v : n → R) : (M.to_lin : (n → R) → (m → R)) v = mul_vec M v := rfl lemma mul_to_lin (M : matrix m n R) (N : matrix n l R) : (M.mul N).to_lin = M.to_lin.comp N.to_lin := by { ext, simp } @[simp] lemma to_lin_one [decidable_eq n] : (1 : matrix n n R).to_lin = linear_map.id := by { ext, simp } end matrix namespace linear_map variables {R : Type v} [comm_ring R] /-- The linear map from linear maps (n → R) →ₗ[R] (m → R) to matrix m n R. -/ def to_matrixₗ [decidable_eq n] : ((n → R) →ₗ[R] (m → R)) →ₗ[R] matrix m n R := begin refine linear_map.mk (λ f i j, f (λ n, ite (j = n) 1 0) i) _ _, { assume f g, simp only [add_apply], refl }, { assume f g, simp only [smul_apply], refl } end /-- The map from linear maps (n → R) →ₗ[R] (m → R) to matrix m n R. -/ def to_matrix [decidable_eq n] : ((n → R) →ₗ[R] (m → R)) → matrix m n R := to_matrixₗ.to_fun @[simp] lemma to_matrix_id [decidable_eq n] : (@linear_map.id _ (n → R) _ _ _).to_matrix = 1 := by { ext, simp [to_matrix, to_matrixₗ, matrix.one_val, eq_comm] } end linear_map section linear_equiv_matrix variables {R : Type v} [comm_ring R] [decidable_eq n] open finsupp matrix linear_map /-- to_lin is the left inverse of to_matrix. -/ lemma to_matrix_to_lin {f : (n → R) →ₗ[R] (m → R)} : to_lin (to_matrix f) = f := begin ext : 1, -- Show that the two sides are equal by showing that they are equal on a basis convert linear_eq_on (set.range _) _ (is_basis.mem_span (@pi.is_basis_fun R n _ _) _), assume e he, rw [@std_basis_eq_single R _ _ _ 1] at he, cases (set.mem_range.mp he) with i h, ext j, change finset.univ.sum (λ k, (f.to_fun (λ l, ite (k = l) 1 0)) j * (e k)) = _, rw [←h], conv_lhs { congr, skip, funext, rw [mul_comm, ←smul_eq_mul, ←pi.smul_apply, ←linear_map.smul], rw [show _ = ite (i = k) (1:R) 0, by convert single_apply], rw [show f.to_fun (ite (i = k) (1:R) 0 • (λ l, ite (k = l) 1 0)) = ite (i = k) (f.to_fun _) 0, { split_ifs, { rw [one_smul] }, { rw [zero_smul], exact linear_map.map_zero f } }] }, convert finset.sum_eq_single i _ _, { rw [if_pos rfl], convert rfl, ext, congr }, { assume _ _ hbi, rw [if_neg $ ne.symm hbi], refl }, { assume hi, exact false.elim (hi $ finset.mem_univ i) } end /-- to_lin is the right inverse of to_matrix. -/ lemma to_lin_to_matrix {M : matrix m n R} : to_matrix (to_lin M) = M := begin ext, change finset.univ.sum (λ y, M i y * ite (j = y) 1 0) = M i j, have h1 : (λ y, M i y * ite (j = y) 1 0) = (λ y, ite (j = y) (M i y) 0), { ext, split_ifs, exact mul_one _, exact ring.mul_zero _ }, have h2 : finset.univ.sum (λ y, ite (j = y) (M i y) 0) = ({j} : finset n).sum (λ y, ite (j = y) (M i y) 0), { refine (finset.sum_subset _ _).symm, { intros _ H, rwa finset.mem_singleton.1 H, exact finset.mem_univ _ }, { exact λ _ _ H, if_neg (mt (finset.mem_singleton.2 ∘ eq.symm) H) } }, rw [h1, h2, finset.sum_singleton], exact if_pos rfl end /-- Linear maps (n → R) →ₗ[R] (m → R) are linearly equivalent to matrix m n R. -/ def linear_equiv_matrix' : ((n → R) →ₗ[R] (m → R)) ≃ₗ[R] matrix m n R := { to_fun := to_matrix, inv_fun := to_lin, right_inv := λ _, to_lin_to_matrix, left_inv := λ _, to_matrix_to_lin, add := to_matrixₗ.add, smul := to_matrixₗ.smul } /-- Given a basis of two modules M₁ and M₂ over a commutative ring R, we get a linear equivalence between linear maps M₁ →ₗ M₂ and matrices over R indexed by the bases. -/ def linear_equiv_matrix {ι κ M₁ M₂ : Type*} [add_comm_group M₁] [module R M₁] [add_comm_group M₂] [module R M₂] [fintype ι] [decidable_eq ι] [fintype κ] {v₁ : ι → M₁} {v₂ : κ → M₂} (hv₁ : is_basis R v₁) (hv₂ : is_basis R v₂) : (M₁ →ₗ[R] M₂) ≃ₗ[R] matrix κ ι R := linear_equiv.trans (linear_equiv.arrow_congr (equiv_fun_basis hv₁) (equiv_fun_basis hv₂)) linear_equiv_matrix' end linear_equiv_matrix namespace matrix open_locale matrix lemma comp_to_matrix_mul {R : Type v} [comm_ring R] [decidable_eq l] [decidable_eq m] (f : (m → R) →ₗ[R] (n → R)) (g : (l → R) →ₗ[R] (m → R)) : (f.comp g).to_matrix = f.to_matrix ⬝ g.to_matrix := suffices (f.comp g) = (f.to_matrix ⬝ g.to_matrix).to_lin, by rw [this, to_lin_to_matrix], by rw [mul_to_lin, to_matrix_to_lin, to_matrix_to_lin] section trace variables {R : Type v} {M : Type w} [ring R] [add_comm_group M] [module R M] /-- The diagonal of a square matrix. -/ def diag (n : Type u) (R : Type v) (M : Type w) [ring R] [add_comm_group M] [module R M] [fintype n] : (matrix n n M) →ₗ[R] n → M := { to_fun := λ A i, A i i, add := by { intros, ext, refl, }, smul := by { intros, ext, refl, } } @[simp] lemma diag_apply (A : matrix n n M) (i : n) : diag n R M A i = A i i := rfl @[simp] lemma diag_one [decidable_eq n] : diag n R R 1 = λ i, 1 := by { dunfold diag, ext, simp [one_val_eq] } @[simp] lemma diag_transpose (A : matrix n n M) : diag n R M Aᵀ = diag n R M A := rfl /-- The trace of a square matrix. -/ def trace (n : Type u) (R : Type v) (M : Type w) [ring R] [add_comm_group M] [module R M] [fintype n] : (matrix n n M) →ₗ[R] M := { to_fun := finset.univ.sum ∘ (diag n R M), add := by { intros, apply finset.sum_add_distrib, }, smul := by { intros, simp [finset.smul_sum], } } @[simp] lemma trace_diag (A : matrix n n M) : trace n R M A = finset.univ.sum (diag n R M A) := rfl @[simp] lemma trace_one [decidable_eq n] : trace n R R 1 = fintype.card n := have h : trace n R R 1 = finset.univ.sum (diag n R R 1) := rfl, by rw [h, diag_one, finset.sum_const, nsmul_one]; refl @[simp] lemma trace_transpose (A : matrix n n M) : trace n R M Aᵀ = trace n R M A := rfl @[simp] lemma trace_transpose_mul (A : matrix m n R) (B : matrix n m R) : trace n R R (Aᵀ ⬝ Bᵀ) = trace m R R (A ⬝ B) := finset.sum_comm lemma trace_mul_comm {S : Type v} [comm_ring S] (A : matrix m n S) (B : matrix n m S) : trace n S S (B ⬝ A) = trace m S S (A ⬝ B) := by rw [←trace_transpose, ←trace_transpose_mul, transpose_mul] end trace section ring variables {R : Type v} [comm_ring R] open linear_map matrix lemma proj_diagonal [decidable_eq m] (i : m) (w : m → R) : (proj i).comp (to_lin (diagonal w)) = (w i) • proj i := by ext j; simp [mul_vec_diagonal] lemma diagonal_comp_std_basis [decidable_eq n] (w : n → R) (i : n) : (diagonal w).to_lin.comp (std_basis R (λ_:n, R) i) = (w i) • std_basis R (λ_:n, R) i := begin ext a j, simp only [linear_map.comp_apply, smul_apply, to_lin_apply, mul_vec_diagonal, smul_apply, pi.smul_apply, smul_eq_mul], by_cases i = j, { subst h }, { rw [std_basis_ne R (λ_:n, R) _ _ (ne.symm h), _root_.mul_zero, _root_.mul_zero] } end lemma diagonal_to_lin [decidable_eq m] (w : m → R) : (diagonal w).to_lin = linear_map.pi (λi, w i • linear_map.proj i) := by ext v j; simp [mul_vec_diagonal] end ring section vector_space variables {K : Type u} [field K] -- maybe try to relax the universe constraint open linear_map matrix lemma rank_vec_mul_vec (w : m → K) (v : n → K) : rank (vec_mul_vec w v).to_lin ≤ 1 := begin rw [vec_mul_vec_eq, mul_to_lin], refine le_trans (rank_comp_le1 _ _) _, refine le_trans (rank_le_domain _) _, rw [dim_fun', ← cardinal.fintype_card], exact le_refl _ end lemma ker_diagonal_to_lin [decidable_eq m] (w : m → K) : ker (diagonal w).to_lin = (⨆i∈{i | w i = 0 }, range (std_basis K (λi, K) i)) := begin rw [← comap_bot, ← infi_ker_proj], simp only [comap_infi, (ker_comp _ _).symm, proj_diagonal, ker_smul'], have : univ ⊆ {i : m | w i = 0} ∪ -{i : m | w i = 0}, { rw set.union_compl_self }, exact (supr_range_std_basis_eq_infi_ker_proj K (λi:m, K) (disjoint_compl {i | w i = 0}) this (finite.of_fintype _)).symm end lemma range_diagonal [decidable_eq m] (w : m → K) : (diagonal w).to_lin.range = (⨆ i ∈ {i | w i ≠ 0}, (std_basis K (λi, K) i).range) := begin dsimp only [mem_set_of_eq], rw [← map_top, ← supr_range_std_basis, map_supr], congr, funext i, rw [← linear_map.range_comp, diagonal_comp_std_basis, ← range_smul'] end lemma rank_diagonal [decidable_eq m] [decidable_eq K] (w : m → K) : rank (diagonal w).to_lin = fintype.card { i // w i ≠ 0 } := begin have hu : univ ⊆ - {i : m | w i = 0} ∪ {i : m | w i = 0}, { rw set.compl_union_self }, have hd : disjoint {i : m | w i ≠ 0} {i : m | w i = 0} := (disjoint_compl {i | w i = 0}).symm, have h₁ := supr_range_std_basis_eq_infi_ker_proj K (λi:m, K) hd hu (finite.of_fintype _), have h₂ := @infi_ker_proj_equiv K _ _ (λi:m, K) _ _ _ _ (by simp; apply_instance) hd hu, rw [rank, range_diagonal, h₁, ←@dim_fun' K], apply linear_equiv.dim_eq, apply h₂, end end vector_space end matrix
aba5f9a9ecad7228cf6c44e1b13fad05761c56f6
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/have3.lean
829f74a19212c2e7fa2c7b6a71baaa2138c1712f
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
246
lean
prelude definition Prop : Type.{1} := Type.{0} constants a b c : Prop axiom Ha : a axiom Hb : b axiom Hc : c #check have H1 : a, from Ha, then have H2 : a, from H1, then have H3 : a, from H2, then have H4 : a, from H3, H4
9e9f67e9979b7b20dfe0d7d496db74d679935dc5
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/linear_algebra/basic.lean
3d26e3ea672e65b0e6f15867529d432f700c97ce
[ "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
104,825
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, Frédéric Dupuis, Heather Macbeth -/ import algebra.big_operators.pi import algebra.module.hom import algebra.module.prod import algebra.module.submodule_lattice import data.dfinsupp import data.finsupp.basic import order.compactly_generated import order.omega_complete_partial_order /-! # Linear algebra This file defines the basics of linear algebra. It sets up the "categorical/lattice structure" of modules over a ring, submodules, and linear maps. Many of the relevant definitions, including `module`, `submodule`, and `linear_map`, are found in `src/algebra/module`. ## Main definitions * Many constructors for (semi)linear maps * `submodule.span s` is defined to be the smallest submodule containing the set `s`. * The kernel `ker` and range `range` of a linear map are submodules of the domain and codomain respectively. * The general linear group is defined to be the group of invertible linear maps from `M` to itself. See `linear_algebra.quotient` for quotients by submodules. ## Main theorems See `linear_algebra.isomorphisms` for Noether's three isomorphism theorems for modules. ## Notations * We continue to use the notations `M →ₛₗ[σ] M₂` and `M →ₗ[R] M₂` for the type of semilinear (resp. linear) maps from `M` to `M₂` over the ring homomorphism `σ` (resp. over the ring `R`). * We introduce the notation `R ∙ v` for the span of a singleton, `submodule.span R {v}`. This is `\.`, not the same as the scalar multiplication `•`/`\bub`. ## Implementation notes We note that, when constructing linear maps, it is convenient to use operations defined on bundled maps (`linear_map.prod`, `linear_map.coprod`, arithmetic operations like `+`) instead of defining a function and proving it is linear. ## TODO * Parts of this file have not yet been generalized to semilinear maps ## Tags linear algebra, vector space, module -/ open function open_locale big_operators pointwise variables {R : Type*} {R₁ : Type*} {R₂ : Type*} {R₃ : Type*} {R₄ : Type*} variables {K : Type*} {K₂ : Type*} variables {M : Type*} {M' : Type*} {M₁ : Type*} {M₂ : Type*} {M₃ : Type*} {M₄ : Type*} variables {N : Type*} {N₂ : Type*} variables {ι : Type*} variables {V : Type*} {V₂ : Type*} namespace finsupp lemma smul_sum {α : Type*} {β : Type*} {R : Type*} {M : Type*} [has_zero β] [monoid R] [add_comm_monoid M] [distrib_mul_action R M] {v : α →₀ β} {c : R} {h : α → β → M} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum @[simp] lemma sum_smul_index_linear_map' {α : Type*} {R : Type*} {M : Type*} {M₂ : Type*} [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] {v : α →₀ M} {c : R} {h : α → M →ₗ[R] M₂} : (c • v).sum (λ a, h a) = c • (v.sum (λ a, h a)) := begin rw [finsupp.sum_smul_index', finsupp.smul_sum], { simp only [linear_map.map_smul], }, { intro i, exact (h i).map_zero }, end variables (α : Type*) [fintype α] variables (R M) [add_comm_monoid M] [semiring R] [module R M] /-- Given `fintype α`, `linear_equiv_fun_on_fintype R` is the natural `R`-linear equivalence between `α →₀ β` and `α → β`. -/ @[simps apply] noncomputable def linear_equiv_fun_on_fintype : (α →₀ M) ≃ₗ[R] (α → M) := { to_fun := coe_fn, map_add' := λ f g, by { ext, refl }, map_smul' := λ c f, by { ext, refl }, .. equiv_fun_on_fintype } @[simp] lemma linear_equiv_fun_on_fintype_single [decidable_eq α] (x : α) (m : M) : (linear_equiv_fun_on_fintype R M α) (single x m) = pi.single x m := begin ext a, change (equiv_fun_on_fintype (single x m)) a = _, convert _root_.congr_fun (equiv_fun_on_fintype_single x m) a, end @[simp] lemma linear_equiv_fun_on_fintype_symm_single [decidable_eq α] (x : α) (m : M) : (linear_equiv_fun_on_fintype R M α).symm (pi.single x m) = single x m := begin ext a, change (equiv_fun_on_fintype.symm (pi.single x m)) a = _, convert congr_fun (equiv_fun_on_fintype_symm_single x m) a, end @[simp] lemma linear_equiv_fun_on_fintype_symm_coe (f : α →₀ M) : (linear_equiv_fun_on_fintype R M α).symm f = f := by { ext, simp [linear_equiv_fun_on_fintype], } end finsupp section open_locale classical /-- decomposing `x : ι → R` as a sum along the canonical basis -/ lemma pi_eq_sum_univ {ι : Type*} [fintype ι] {R : Type*} [semiring R] (x : ι → R) : x = ∑ i, x i • (λj, if i = j then 1 else 0) := by { ext, simp } end /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄] variables [add_comm_monoid M] [add_comm_monoid M₁] [add_comm_monoid M₂] variables [add_comm_monoid M₃] [add_comm_monoid M₄] variables [module R M] [module R M₁] [module R₂ M₂] [module R₃ M₃] [module R₄ M₄] variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₃₄ : R₃ →+* R₄} variables {σ₁₃ : R →+* R₃} {σ₂₄ : R₂ →+* R₄} {σ₁₄ : R →+* R₄} variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₂₃ σ₃₄ σ₂₄] variables [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄] [ring_hom_comp_triple σ₁₂ σ₂₄ σ₁₄] variables (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₃] M₃) include R R₂ theorem comp_assoc (h : M₃ →ₛₗ[σ₃₄] M₄) : ((h.comp g : M₂ →ₛₗ[σ₂₄] M₄).comp f : M →ₛₗ[σ₁₄] M₄) = h.comp (g.comp f : M →ₛₗ[σ₁₃] M₃) := rfl omit R R₂ /-- The restriction of a linear map `f : M → M₂` to a submodule `p ⊆ M` gives a linear map `p → M₂`. -/ def dom_restrict (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) : p →ₛₗ[σ₁₂] M₂ := f.comp p.subtype @[simp] lemma dom_restrict_apply (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) (x : p) : f.dom_restrict p x = f x := rfl /-- A linear map `f : M₂ → M` whose values lie in a submodule `p ⊆ M` can be restricted to a linear map M₂ → p. -/ def cod_restrict (p : submodule R₂ M₂) (f : M →ₛₗ[σ₁₂] M₂) (h : ∀c, f c ∈ p) : M →ₛₗ[σ₁₂] p := by refine {to_fun := λc, ⟨f c, h c⟩, ..}; intros; apply set_coe.ext; simp @[simp] theorem cod_restrict_apply (p : submodule R₂ M₂) (f : M →ₛₗ[σ₁₂] M₂) {h} (x : M) : (cod_restrict p f h x : M₂) = f x := rfl @[simp] lemma comp_cod_restrict (p : submodule R₃ M₃) (h : ∀b, g b ∈ p) : ((cod_restrict p g h).comp f : M →ₛₗ[σ₁₃] p) = cod_restrict p (g.comp f) (assume b, h _) := ext $ assume b, rfl @[simp] lemma subtype_comp_cod_restrict (p : submodule R₂ M₂) (h : ∀b, f b ∈ p) : p.subtype.comp (cod_restrict p f h) = f := ext $ assume b, rfl /-- Restrict domain and codomain of an endomorphism. -/ def restrict (f : M →ₗ[R] M) {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p →ₗ[R] p := (f.dom_restrict p).cod_restrict p $ set_like.forall.2 hf lemma restrict_apply {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) (x : p) : f.restrict hf x = ⟨f x, hf x.1 x.2⟩ := rfl lemma subtype_comp_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : p.subtype.comp (f.restrict hf) = f.dom_restrict p := rfl lemma restrict_eq_cod_restrict_dom_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x ∈ p, f x ∈ p) : f.restrict hf = (f.dom_restrict p).cod_restrict p (λ x, hf x.1 x.2) := rfl lemma restrict_eq_dom_restrict_cod_restrict {f : M →ₗ[R] M} {p : submodule R M} (hf : ∀ x, f x ∈ p) : f.restrict (λ x _, hf x) = (f.cod_restrict p hf).dom_restrict p := rfl instance unique_of_left [subsingleton M] : unique (M →ₛₗ[σ₁₂] M₂) := { uniq := λ f, ext $ λ x, by rw [subsingleton.elim x 0, map_zero, map_zero], .. linear_map.inhabited } instance unique_of_right [subsingleton M₂] : unique (M →ₛₗ[σ₁₂] M₂) := coe_injective.unique /-- Evaluation of a `σ₁₂`-linear map at a fixed `a`, as an `add_monoid_hom`. -/ def eval_add_monoid_hom (a : M) : (M →ₛₗ[σ₁₂] M₂) →+ M₂ := { to_fun := λ f, f a, map_add' := λ f g, linear_map.add_apply f g a, map_zero' := rfl } /-- `linear_map.to_add_monoid_hom` promoted to an `add_monoid_hom` -/ def to_add_monoid_hom' : (M →ₛₗ[σ₁₂] M₂) →+ (M →+ M₂) := { to_fun := to_add_monoid_hom, map_zero' := by ext; refl, map_add' := by intros; ext; refl } lemma sum_apply (t : finset ι) (f : ι → M →ₛₗ[σ₁₂] M₂) (b : M) : (∑ d in t, f d) b = ∑ d in t, f d b := add_monoid_hom.map_sum ((add_monoid_hom.eval b).comp to_add_monoid_hom') f _ section smul_right variables {S : Type*} [semiring S] [module R S] [module S M] [is_scalar_tower R S M] /-- When `f` is an `R`-linear map taking values in `S`, then `λb, f b • x` is an `R`-linear map. -/ def smul_right (f : M₁ →ₗ[R] S) (x : M) : M₁ →ₗ[R] M := { to_fun := λb, f b • x, map_add' := λ x y, by rw [f.map_add, add_smul], map_smul' := λ b y, by dsimp; rw [f.map_smul, smul_assoc] } @[simp] theorem coe_smul_right (f : M₁ →ₗ[R] S) (x : M) : (smul_right f x : M₁ → M) = λ c, f c • x := rfl theorem smul_right_apply (f : M₁ →ₗ[R] S) (x : M) (c : M₁) : smul_right f x c = f c • x := rfl end smul_right instance [nontrivial M] : nontrivial (module.End R M) := begin obtain ⟨m, ne⟩ := (nontrivial_iff_exists_ne (0 : M)).mp infer_instance, exact nontrivial_of_ne 1 0 (λ p, ne (linear_map.congr_fun p m)), end @[simp, norm_cast] lemma coe_fn_sum {ι : Type*} (t : finset ι) (f : ι → M →ₛₗ[σ₁₂] M₂) : ⇑(∑ i in t, f i) = ∑ i in t, (f i : M → M₂) := add_monoid_hom.map_sum ⟨@to_fun R R₂ _ _ σ₁₂ M M₂ _ _ _ _, rfl, λ x y, rfl⟩ _ _ @[simp] lemma pow_apply (f : M →ₗ[R] M) (n : ℕ) (m : M) : (f^n) m = (f^[n] m) := begin induction n with n ih, { refl, }, { simp only [function.comp_app, function.iterate_succ, linear_map.mul_apply, pow_succ, ih], exact (function.commute.iterate_self _ _ m).symm, }, end lemma pow_map_zero_of_le {f : module.End R M} {m : M} {k l : ℕ} (hk : k ≤ l) (hm : (f^k) m = 0) : (f^l) m = 0 := by rw [← nat.sub_add_cancel hk, pow_add, mul_apply, hm, map_zero] lemma commute_pow_left_of_commute {f : M →ₛₗ[σ₁₂] M₂} {g : module.End R M} {g₂ : module.End R₂ M₂} (h : g₂.comp f = f.comp g) (k : ℕ) : (g₂^k).comp f = f.comp (g^k) := begin induction k with k ih, { simpa only [pow_zero], }, { rw [pow_succ, pow_succ, linear_map.mul_eq_comp, linear_map.comp_assoc, ih, ← linear_map.comp_assoc, h, linear_map.comp_assoc, linear_map.mul_eq_comp], }, end lemma submodule_pow_eq_zero_of_pow_eq_zero {N : submodule R M} {g : module.End R N} {G : module.End R M} (h : G.comp N.subtype = N.subtype.comp g) {k : ℕ} (hG : G^k = 0) : g^k = 0 := begin ext m, have hg : N.subtype.comp (g^k) m = 0, { rw [← commute_pow_left_of_commute h, hG, zero_comp, zero_apply], }, simp only [submodule.subtype_apply, comp_app, submodule.coe_eq_zero, coe_comp] at hg, rw [hg, linear_map.zero_apply], end lemma coe_pow (f : M →ₗ[R] M) (n : ℕ) : ⇑(f^n) = (f^[n]) := by { ext m, apply pow_apply, } @[simp] lemma id_pow (n : ℕ) : (id : M →ₗ[R] M)^n = id := one_pow n section variables {f' : M →ₗ[R] M} lemma iterate_succ (n : ℕ) : (f' ^ (n + 1)) = comp (f' ^ n) f' := by rw [pow_succ', mul_eq_comp] lemma iterate_surjective (h : surjective f') : ∀ n : ℕ, surjective ⇑(f' ^ n) | 0 := surjective_id | (n + 1) := by { rw [iterate_succ], exact surjective.comp (iterate_surjective n) h, } lemma iterate_injective (h : injective f') : ∀ n : ℕ, injective ⇑(f' ^ n) | 0 := injective_id | (n + 1) := by { rw [iterate_succ], exact injective.comp (iterate_injective n) h, } lemma iterate_bijective (h : bijective f') : ∀ n : ℕ, bijective ⇑(f' ^ n) | 0 := bijective_id | (n + 1) := by { rw [iterate_succ], exact bijective.comp (iterate_bijective n) h, } lemma injective_of_iterate_injective {n : ℕ} (hn : n ≠ 0) (h : injective ⇑(f' ^ n)) : injective f' := begin rw [← nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr hn), iterate_succ, coe_comp] at h, exact injective.of_comp h, end lemma surjective_of_iterate_surjective {n : ℕ} (hn : n ≠ 0) (h : surjective ⇑(f' ^ n)) : surjective f' := begin rw [← nat.succ_pred_eq_of_pos (pos_iff_ne_zero.mpr hn), nat.succ_eq_add_one, add_comm, pow_add] at h, exact surjective.of_comp h, end end section open_locale classical /-- A linear map `f` applied to `x : ι → R` can be computed using the image under `f` of elements of the canonical basis. -/ lemma pi_apply_eq_sum_univ [fintype ι] (f : (ι → R) →ₗ[R] M) (x : ι → R) : f x = ∑ i, x i • (f (λj, if i = j then 1 else 0)) := begin conv_lhs { rw [pi_eq_sum_univ x, f.map_sum] }, apply finset.sum_congr rfl (λl hl, _), rw f.map_smul end end end add_comm_monoid section module variables {S : Type*} [semiring R] [semiring S] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [module R M] [module R M₂] [module R M₃] [module S M₂] [module S M₃] [smul_comm_class R S M₂] [smul_comm_class R S M₃] (f : M →ₗ[R] M₂) variable (S) /-- Applying a linear map at `v : M`, seen as `S`-linear map from `M →ₗ[R] M₂` to `M₂`. See `linear_map.applyₗ` for a version where `S = R`. -/ @[simps] def applyₗ' : M →+ (M →ₗ[R] M₂) →ₗ[S] M₂ := { to_fun := λ v, { to_fun := λ f, f v, map_add' := λ f g, f.add_apply g v, map_smul' := λ x f, f.smul_apply x v }, map_zero' := linear_map.ext $ λ f, f.map_zero, map_add' := λ x y, linear_map.ext $ λ f, f.map_add _ _ } section variables (R M) /-- The equivalence between R-linear maps from `R` to `M`, and points of `M` itself. This says that the forgetful functor from `R`-modules to types is representable, by `R`. This as an `S`-linear equivalence, under the assumption that `S` acts on `M` commuting with `R`. When `R` is commutative, we can take this to be the usual action with `S = R`. Otherwise, `S = ℕ` shows that the equivalence is additive. See note [bundled maps over different rings]. -/ @[simps] def ring_lmap_equiv_self [module S M] [smul_comm_class R S M] : (R →ₗ[R] M) ≃ₗ[S] M := { to_fun := λ f, f 1, inv_fun := smul_right (1 : R →ₗ[R] R), left_inv := λ f, by { ext, simp }, right_inv := λ x, by simp, .. applyₗ' S (1 : R) } end end module section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] variables (f g : M →ₗ[R] M₂) include R /-- Composition by `f : M₂ → M₃` is a linear map from the space of linear maps `M → M₂` to the space of linear maps `M₂ → M₃`. -/ def comp_right (f : M₂ →ₗ[R] M₃) : (M →ₗ[R] M₂) →ₗ[R] (M →ₗ[R] M₃) := { to_fun := f.comp, map_add' := λ _ _, linear_map.ext $ λ _, f.map_add _ _, map_smul' := λ _ _, linear_map.ext $ λ _, f.map_smul _ _ } /-- Applying a linear map at `v : M`, seen as a linear map from `M →ₗ[R] M₂` to `M₂`. See also `linear_map.applyₗ'` for a version that works with two different semirings. This is the `linear_map` version of `add_monoid_hom.eval`. -/ @[simps] def applyₗ : M →ₗ[R] (M →ₗ[R] M₂) →ₗ[R] M₂ := { to_fun := λ v, { to_fun := λ f, f v, ..applyₗ' R v }, map_smul' := λ x y, linear_map.ext $ λ f, f.map_smul _ _, ..applyₗ' R } /-- Alternative version of `dom_restrict` as a linear map. -/ def dom_restrict' (p : submodule R M) : (M →ₗ[R] M₂) →ₗ[R] (p →ₗ[R] M₂) := { to_fun := λ φ, φ.dom_restrict p, map_add' := by simp [linear_map.ext_iff], map_smul' := by simp [linear_map.ext_iff] } @[simp] lemma dom_restrict'_apply (f : M →ₗ[R] M₂) (p : submodule R M) (x : p) : dom_restrict' p f x = f x := rfl end comm_semiring section comm_ring variables [comm_ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] /-- The family of linear maps `M₂ → M` parameterised by `f ∈ M₂ → R`, `x ∈ M`, is linear in `f`, `x`. -/ def smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M := { to_fun := λ f, { to_fun := linear_map.smul_right f, map_add' := λ m m', by { ext, apply smul_add, }, map_smul' := λ c m, by { ext, apply smul_comm, } }, map_add' := λ f f', by { ext, apply add_smul, }, map_smul' := λ c f, by { ext, apply mul_smul, } } @[simp] lemma smul_rightₗ_apply (f : M₂ →ₗ[R] R) (x : M) (c : M₂) : (smul_rightₗ : (M₂ →ₗ[R] R) →ₗ[R] M →ₗ[R] M₂ →ₗ[R] M) f x c = (f c) • x := rfl end comm_ring end linear_map /-- The `R`-linear equivalence between additive morphisms `A →+ B` and `ℕ`-linear morphisms `A →ₗ[ℕ] B`. -/ @[simps] def add_monoid_hom_lequiv_nat {A B : Type*} (R : Type*) [semiring R] [add_comm_monoid A] [add_comm_monoid B] [module R B] : (A →+ B) ≃ₗ[R] (A →ₗ[ℕ] B) := { to_fun := add_monoid_hom.to_nat_linear_map, inv_fun := linear_map.to_add_monoid_hom, map_add' := by { intros, ext, refl }, map_smul' := by { intros, ext, refl }, left_inv := by { intros f, ext, refl }, right_inv := by { intros f, ext, refl } } /-- The `R`-linear equivalence between additive morphisms `A →+ B` and `ℤ`-linear morphisms `A →ₗ[ℤ] B`. -/ @[simps] def add_monoid_hom_lequiv_int {A B : Type*} (R : Type*) [semiring R] [add_comm_group A] [add_comm_group B] [module R B] : (A →+ B) ≃ₗ[R] (A →ₗ[ℤ] B) := { to_fun := add_monoid_hom.to_int_linear_map, inv_fun := linear_map.to_add_monoid_hom, map_add' := by { intros, ext, refl }, map_smul' := by { intros, ext, refl }, left_inv := by { intros f, ext, refl }, right_inv := by { intros f, ext, refl } } /-! ### Properties of submodules -/ namespace submodule section add_comm_monoid variables [semiring R] [semiring R₂] [semiring R₃] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M'] variables [module R M] [module R M'] [module R₂ M₂] [module R₃ M₃] variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃} variables {σ₂₁ : R₂ →+* R} variables [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] variables (p p' : submodule R M) (q q' : submodule R₂ M₂) variables (q₁ q₁' : submodule R M') variables {r : R} {x y : M} open set variables {p p'} /-- If two submodules `p` and `p'` satisfy `p ⊆ p'`, then `of_le p p'` is the linear map version of this inclusion. -/ def of_le (h : p ≤ p') : p →ₗ[R] p' := p.subtype.cod_restrict p' $ λ ⟨x, hx⟩, h hx @[simp] theorem coe_of_le (h : p ≤ p') (x : p) : (of_le h x : M) = x := rfl theorem of_le_apply (h : p ≤ p') (x : p) : of_le h x = ⟨x, h x.2⟩ := rfl theorem of_le_injective (h : p ≤ p') : function.injective (of_le h) := λ x y h, subtype.val_injective (subtype.mk.inj h) variables (p p') lemma subtype_comp_of_le (p q : submodule R M) (h : p ≤ q) : q.subtype.comp (of_le h) = p.subtype := by { ext ⟨b, hb⟩, refl } variables (R) @[simp] lemma subsingleton_iff : subsingleton (submodule R M) ↔ subsingleton M := have h : subsingleton (submodule R M) ↔ subsingleton (add_submonoid M), { rw [←subsingleton_iff_bot_eq_top, ←subsingleton_iff_bot_eq_top], convert to_add_submonoid_eq.symm; refl, }, h.trans add_submonoid.subsingleton_iff @[simp] lemma nontrivial_iff : nontrivial (submodule R M) ↔ nontrivial M := not_iff_not.mp ( (not_nontrivial_iff_subsingleton.trans $ subsingleton_iff R).trans not_nontrivial_iff_subsingleton.symm) variables {R} instance [subsingleton M] : unique (submodule R M) := ⟨⟨⊥⟩, λ a, @subsingleton.elim _ ((subsingleton_iff R).mpr ‹_›) a _⟩ instance unique' [subsingleton R] : unique (submodule R M) := by haveI := module.subsingleton R M; apply_instance instance [nontrivial M] : nontrivial (submodule R M) := (nontrivial_iff R).mpr ‹_› theorem disjoint_def {p p' : submodule R M} : disjoint p p' ↔ ∀ x ∈ p, x ∈ p' → x = (0:M) := show (∀ x, x ∈ p ∧ x ∈ p' → x ∈ ({0} : set M)) ↔ _, by simp theorem disjoint_def' {p p' : submodule R M} : disjoint p p' ↔ ∀ (x ∈ p) (y ∈ p'), x = y → x = (0:M) := disjoint_def.trans ⟨λ h x hx y hy hxy, h x hx $ hxy.symm ▸ hy, λ h x hx hx', h _ hx x hx' rfl⟩ theorem mem_right_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p} : (x:M) ∈ p' ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x x.2 hx, λ h, h.symm ▸ p'.zero_mem⟩ theorem mem_left_iff_eq_zero_of_disjoint {p p' : submodule R M} (h : disjoint p p') {x : p'} : (x:M) ∈ p ↔ x = 0 := ⟨λ hx, coe_eq_zero.1 $ disjoint_def.1 h x hx x.2, λ h, h.symm ▸ p.zero_mem⟩ section variables [ring_hom_surjective σ₁₂] /-- The pushforward of a submodule `p ⊆ M` by `f : M → M₂` -/ def map (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) : submodule R₂ M₂ := { carrier := f '' p, smul_mem' := begin rintro c x ⟨y, hy, rfl⟩, obtain ⟨a, rfl⟩ := σ₁₂.is_surjective c, exact ⟨_, p.smul_mem a hy, f.map_smulₛₗ _ _⟩, end, .. p.to_add_submonoid.map f.to_add_monoid_hom } @[simp] lemma map_coe (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) : (map f p : set M₂) = f '' p := rfl @[simp] lemma mem_map {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R M} {x : M₂} : x ∈ map f p ↔ ∃ y, y ∈ p ∧ f y = x := iff.rfl theorem mem_map_of_mem {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R M} {r} (h : r ∈ p) : f r ∈ map f p := set.mem_image_of_mem _ h lemma apply_coe_mem_map (f : M →ₛₗ[σ₁₂] M₂) {p : submodule R M} (r : p) : f r ∈ map f p := mem_map_of_mem r.prop @[simp] lemma map_id : map (linear_map.id : M →ₗ[R] M) p = p := submodule.ext $ λ a, by simp lemma map_comp [ring_hom_surjective σ₂₃] [ring_hom_surjective σ₁₃] (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₃] M₃) (p : submodule R M) : map (g.comp f : M →ₛₗ[σ₁₃] M₃) p = map g (map f p) := set_like.coe_injective $ by simp [map_coe]; rw ← image_comp lemma map_mono {f : M →ₛₗ[σ₁₂] M₂} {p p' : submodule R M} : p ≤ p' → map f p ≤ map f p' := image_subset _ @[simp] lemma map_zero : map (0 : M →ₛₗ[σ₁₂] M₂) p = ⊥ := have ∃ (x : M), x ∈ p := ⟨0, p.zero_mem⟩, ext $ by simp [this, eq_comm] lemma map_add_le (f g : M →ₛₗ[σ₁₂] M₂) : map (f + g) p ≤ map f p ⊔ map g p := begin rintros x ⟨m, hm, rfl⟩, exact add_mem_sup (mem_map_of_mem hm) (mem_map_of_mem hm), end lemma range_map_nonempty (N : submodule R M) : (set.range (λ ϕ, submodule.map ϕ N : (M →ₛₗ[σ₁₂] M₂) → submodule R₂ M₂)).nonempty := ⟨_, set.mem_range.mpr ⟨0, rfl⟩⟩ end include σ₂₁ /-- The pushforward of a submodule by an injective linear map is linearly equivalent to the original submodule. -/ noncomputable def equiv_map_of_injective (f : M →ₛₗ[σ₁₂] M₂) (i : injective f) (p : submodule R M) : p ≃ₛₗ[σ₁₂] p.map f := { map_add' := by { intros, simp, refl, }, map_smul' := by { intros, simp, refl, }, ..(equiv.set.image f p i) } @[simp] lemma coe_equiv_map_of_injective_apply (f : M →ₛₗ[σ₁₂] M₂) (i : injective f) (p : submodule R M) (x : p) : (equiv_map_of_injective f i p x : M₂) = f x := rfl omit σ₂₁ /-- The pullback of a submodule `p ⊆ M₂` along `f : M → M₂` -/ def comap (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R₂ M₂) : submodule R M := { carrier := f ⁻¹' p, smul_mem' := λ a x h, by simp [p.smul_mem _ h], .. p.to_add_submonoid.comap f.to_add_monoid_hom } @[simp] lemma comap_coe (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R₂ M₂) : (comap f p : set M) = f ⁻¹' p := rfl @[simp] lemma mem_comap {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R₂ M₂} : x ∈ comap f p ↔ f x ∈ p := iff.rfl lemma comap_id : comap linear_map.id p = p := set_like.coe_injective rfl lemma comap_comp (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₃] M₃) (p : submodule R₃ M₃) : comap (g.comp f : M →ₛₗ[σ₁₃] M₃) p = comap f (comap g p) := rfl lemma comap_mono {f : M →ₛₗ[σ₁₂] M₂} {q q' : submodule R₂ M₂} : q ≤ q' → comap f q ≤ comap f q' := preimage_mono section variables [ring_hom_surjective σ₁₂] lemma map_le_iff_le_comap {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R M} {q : submodule R₂ M₂} : map f p ≤ q ↔ p ≤ comap f q := image_subset_iff lemma gc_map_comap (f : M →ₛₗ[σ₁₂] M₂) : galois_connection (map f) (comap f) | p q := map_le_iff_le_comap @[simp] lemma map_bot (f : M →ₛₗ[σ₁₂] M₂) : map f ⊥ = ⊥ := (gc_map_comap f).l_bot @[simp] lemma map_sup (f : M →ₛₗ[σ₁₂] M₂) : map f (p ⊔ p') = map f p ⊔ map f p' := (gc_map_comap f).l_sup @[simp] lemma map_supr {ι : Sort*} (f : M →ₛₗ[σ₁₂] M₂) (p : ι → submodule R M) : map f (⨆i, p i) = (⨆i, map f (p i)) := (gc_map_comap f).l_supr end @[simp] lemma comap_top (f : M →ₛₗ[σ₁₂] M₂) : comap f ⊤ = ⊤ := rfl @[simp] lemma comap_inf (f : M →ₛₗ[σ₁₂] M₂) : comap f (q ⊓ q') = comap f q ⊓ comap f q' := rfl @[simp] lemma comap_infi [ring_hom_surjective σ₁₂] {ι : Sort*} (f : M →ₛₗ[σ₁₂] M₂) (p : ι → submodule R₂ M₂) : comap f (⨅i, p i) = (⨅i, comap f (p i)) := (gc_map_comap f).u_infi @[simp] lemma comap_zero : comap (0 : M →ₛₗ[σ₁₂] M₂) q = ⊤ := ext $ by simp lemma map_comap_le [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) (q : submodule R₂ M₂) : map f (comap f q) ≤ q := (gc_map_comap f).l_u_le _ lemma le_comap_map [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) (p : submodule R M) : p ≤ comap f (map f p) := (gc_map_comap f).le_u_l _ section galois_insertion variables {f : M →ₛₗ[σ₁₂] M₂} (hf : surjective f) variables [ring_hom_surjective σ₁₂] include hf /-- `map f` and `comap f` form a `galois_insertion` when `f` is surjective. -/ def gi_map_comap : galois_insertion (map f) (comap f) := (gc_map_comap f).to_galois_insertion (λ S x hx, begin rcases hf x with ⟨y, rfl⟩, simp only [mem_map, mem_comap], exact ⟨y, hx, rfl⟩ end) lemma map_comap_eq_of_surjective (p : submodule R₂ M₂) : (p.comap f).map f = p := (gi_map_comap hf).l_u_eq _ lemma map_surjective_of_surjective : function.surjective (map f) := (gi_map_comap hf).l_surjective lemma comap_injective_of_surjective : function.injective (comap f) := (gi_map_comap hf).u_injective lemma map_sup_comap_of_surjective (p q : submodule R₂ M₂) : (p.comap f ⊔ q.comap f).map f = p ⊔ q := (gi_map_comap hf).l_sup_u _ _ lemma map_supr_comap_of_sujective (S : ι → submodule R₂ M₂) : (⨆ i, (S i).comap f).map f = supr S := (gi_map_comap hf).l_supr_u _ lemma map_inf_comap_of_surjective (p q : submodule R₂ M₂) : (p.comap f ⊓ q.comap f).map f = p ⊓ q := (gi_map_comap hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (S : ι → submodule R₂ M₂) : (⨅ i, (S i).comap f).map f = infi S := (gi_map_comap hf).l_infi_u _ lemma comap_le_comap_iff_of_surjective (p q : submodule R₂ M₂) : p.comap f ≤ q.comap f ↔ p ≤ q := (gi_map_comap hf).u_le_u_iff lemma comap_strict_mono_of_surjective : strict_mono (comap f) := (gi_map_comap hf).strict_mono_u end galois_insertion section galois_coinsertion variables [ring_hom_surjective σ₁₂] {f : M →ₛₗ[σ₁₂] M₂} (hf : injective f) include hf /-- `map f` and `comap f` form a `galois_coinsertion` when `f` is injective. -/ def gci_map_comap : galois_coinsertion (map f) (comap f) := (gc_map_comap f).to_galois_coinsertion (λ S x, by simp [mem_comap, mem_map, hf.eq_iff]) lemma comap_map_eq_of_injective (p : submodule R M) : (p.map f).comap f = p := (gci_map_comap hf).u_l_eq _ lemma comap_surjective_of_injective : function.surjective (comap f) := (gci_map_comap hf).u_surjective lemma map_injective_of_injective : function.injective (map f) := (gci_map_comap hf).l_injective lemma comap_inf_map_of_injective (p q : submodule R M) : (p.map f ⊓ q.map f).comap f = p ⊓ q := (gci_map_comap hf).u_inf_l _ _ lemma comap_infi_map_of_injective (S : ι → submodule R M) : (⨅ i, (S i).map f).comap f = infi S := (gci_map_comap hf).u_infi_l _ lemma comap_sup_map_of_injective (p q : submodule R M) : (p.map f ⊔ q.map f).comap f = p ⊔ q := (gci_map_comap hf).u_sup_l _ _ lemma comap_supr_map_of_injective (S : ι → submodule R M) : (⨆ i, (S i).map f).comap f = supr S := (gci_map_comap hf).u_supr_l _ lemma map_le_map_iff_of_injective (p q : submodule R M) : p.map f ≤ q.map f ↔ p ≤ q := (gci_map_comap hf).l_le_l_iff lemma map_strict_mono_of_injective : strict_mono (map f) := (gci_map_comap hf).strict_mono_l end galois_coinsertion --TODO(Mario): is there a way to prove this from order properties? lemma map_inf_eq_map_inf_comap [ring_hom_surjective σ₁₂] {f : M →ₛₗ[σ₁₂] M₂} {p : submodule R M} {p' : submodule R₂ M₂} : map f p ⊓ p' = map f (p ⊓ comap f p') := le_antisymm (by rintro _ ⟨⟨x, h₁, rfl⟩, h₂⟩; exact ⟨_, ⟨h₁, h₂⟩, rfl⟩) (le_inf (map_mono inf_le_left) (map_le_iff_le_comap.2 inf_le_right)) lemma map_comap_subtype : map p.subtype (comap p.subtype p') = p ⊓ p' := ext $ λ x, ⟨by rintro ⟨⟨_, h₁⟩, h₂, rfl⟩; exact ⟨h₁, h₂⟩, λ ⟨h₁, h₂⟩, ⟨⟨_, h₁⟩, h₂, rfl⟩⟩ lemma eq_zero_of_bot_submodule : ∀(b : (⊥ : submodule R M)), b = 0 | ⟨b', hb⟩ := subtype.eq $ show b' = 0, from (mem_bot R).1 hb section variables (R) /-- The span of a set `s ⊆ M` is the smallest submodule of M that contains `s`. -/ def span (s : set M) : submodule R M := Inf {p | s ⊆ p} end variables {s t : set M} lemma mem_span : x ∈ span R s ↔ ∀ p : submodule R M, s ⊆ p → x ∈ p := mem_bInter_iff lemma subset_span : s ⊆ span R s := λ x h, mem_span.2 $ λ p hp, hp h lemma span_le {p} : span R s ≤ p ↔ s ⊆ p := ⟨subset.trans subset_span, λ ss x h, mem_span.1 h _ ss⟩ lemma span_mono (h : s ⊆ t) : span R s ≤ span R t := span_le.2 $ subset.trans h subset_span lemma span_eq_of_le (h₁ : s ⊆ p) (h₂ : p ≤ span R s) : span R s = p := le_antisymm (span_le.2 h₁) h₂ @[simp] lemma span_eq : span R (p : set M) = p := span_eq_of_le _ (subset.refl _) subset_span lemma map_span [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) (s : set M) : (span R s).map f = span R₂ (f '' s) := eq.symm $ span_eq_of_le _ (set.image_subset f subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ λ x hx, subset_span ⟨x, hx, rfl⟩ alias submodule.map_span ← linear_map.map_span lemma map_span_le {R M M₂ : Type*} [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M →ₗ[R] M₂) (s : set M) (N : submodule R M₂) : map f (span R s) ≤ N ↔ ∀ m ∈ s, f m ∈ N := begin rw [f.map_span, span_le, set.image_subset_iff], exact iff.rfl end @[simp] lemma span_insert_zero : span R (insert (0 : M) s) = span R s := begin refine le_antisymm _ (submodule.span_mono (set.subset_insert 0 s)), rw [span_le, set.insert_subset], exact ⟨by simp only [set_like.mem_coe, submodule.zero_mem], submodule.subset_span⟩, end alias submodule.map_span_le ← linear_map.map_span_le /- See also `span_preimage_eq` below. -/ lemma span_preimage_le (f : M →ₛₗ[σ₁₂] M₂) (s : set M₂) : span R (f ⁻¹' s) ≤ (span R₂ s).comap f := by { rw [span_le, comap_coe], exact preimage_mono (subset_span), } alias submodule.span_preimage_le ← linear_map.span_preimage_le /-- An induction principle for span membership. If `p` holds for 0 and all elements of `s`, and is preserved under addition and scalar multiplication, then `p` holds for all elements of the span of `s`. -/ @[elab_as_eliminator] lemma span_induction {p : M → Prop} (h : x ∈ span R s) (Hs : ∀ x ∈ s, p x) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (a:R) x, p x → p (a • x)) : p x := (@span_le _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hs h lemma span_nat_eq_add_submonoid_closure (s : set M) : (span ℕ s).to_add_submonoid = add_submonoid.closure s := begin refine eq.symm (add_submonoid.closure_eq_of_le subset_span _), apply add_submonoid.to_nat_submodule.symm.to_galois_connection.l_le _, rw span_le, exact add_submonoid.subset_closure, end @[simp] lemma span_nat_eq (s : add_submonoid M) : (span ℕ (s : set M)).to_add_submonoid = s := by rw [span_nat_eq_add_submonoid_closure, s.closure_eq] lemma span_int_eq_add_subgroup_closure {M : Type*} [add_comm_group M] (s : set M) : (span ℤ s).to_add_subgroup = add_subgroup.closure s := eq.symm $ add_subgroup.closure_eq_of_le _ subset_span $ λ x hx, span_induction hx (λ x hx, add_subgroup.subset_closure hx) (add_subgroup.zero_mem _) (λ _ _, add_subgroup.add_mem _) (λ _ _ _, add_subgroup.gsmul_mem _ ‹_› _) @[simp] lemma span_int_eq {M : Type*} [add_comm_group M] (s : add_subgroup M) : (span ℤ (s : set M)).to_add_subgroup = s := by rw [span_int_eq_add_subgroup_closure, s.closure_eq] section variables (R M) /-- `span` forms a Galois insertion with the coercion from submodule to set. -/ protected def gi : galois_insertion (@span R M _ _ _) coe := { choice := λ s _, span R s, gc := λ s t, span_le, le_l_u := λ s, subset_span, choice_eq := λ s h, rfl } end @[simp] lemma span_empty : span R (∅ : set M) = ⊥ := (submodule.gi R M).gc.l_bot @[simp] lemma span_univ : span R (univ : set M) = ⊤ := eq_top_iff.2 $ set_like.le_def.2 $ subset_span lemma span_union (s t : set M) : span R (s ∪ t) = span R s ⊔ span R t := (submodule.gi R M).gc.l_sup lemma span_Union {ι} (s : ι → set M) : span R (⋃ i, s i) = ⨆ i, span R (s i) := (submodule.gi R M).gc.l_supr lemma span_eq_supr_of_singleton_spans (s : set M) : span R s = ⨆ x ∈ s, span R {x} := by simp only [←span_Union, set.bUnion_of_singleton s] @[simp] theorem coe_supr_of_directed {ι} [hι : nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) : ((supr S : submodule R M) : set M) = ⋃ i, S i := begin refine subset.antisymm _ (Union_subset $ le_supr S), suffices : (span R (⋃ i, (S i : set M)) : set M) ⊆ ⋃ (i : ι), ↑(S i), by simpa only [span_Union, span_eq] using this, refine (λ x hx, span_induction hx (λ _, id) _ _ _); simp only [mem_Union, exists_imp_distrib], { exact hι.elim (λ i, ⟨i, (S i).zero_mem⟩) }, { intros x y i hi j hj, rcases H i j with ⟨k, ik, jk⟩, exact ⟨k, add_mem _ (ik hi) (jk hj)⟩ }, { exact λ a x i hi, ⟨i, smul_mem _ a hi⟩ }, end @[simp] theorem mem_supr_of_directed {ι} [nonempty ι] (S : ι → submodule R M) (H : directed (≤) S) {x} : x ∈ supr S ↔ ∃ i, x ∈ S i := by { rw [← set_like.mem_coe, coe_supr_of_directed S H, mem_Union], refl } theorem mem_Sup_of_directed {s : set (submodule R M)} {z} (hs : s.nonempty) (hdir : directed_on (≤) s) : z ∈ Sup s ↔ ∃ y ∈ s, z ∈ y := begin haveI : nonempty s := hs.to_subtype, simp only [Sup_eq_supr', mem_supr_of_directed _ hdir.directed_coe, set_coe.exists, subtype.coe_mk] end @[norm_cast, simp] lemma coe_supr_of_chain (a : ℕ →ₘ submodule R M) : (↑(⨆ k, a k) : set M) = ⋃ k, (a k : set M) := coe_supr_of_directed a a.monotone.directed_le /-- We can regard `coe_supr_of_chain` as the statement that `coe : (submodule R M) → set M` is Scott continuous for the ω-complete partial order induced by the complete lattice structures. -/ lemma coe_scott_continuous : omega_complete_partial_order.continuous' (coe : submodule R M → set M) := ⟨set_like.coe_mono, coe_supr_of_chain⟩ @[simp] lemma mem_supr_of_chain (a : ℕ →ₘ submodule R M) (m : M) : m ∈ (⨆ k, a k) ↔ ∃ k, m ∈ a k := mem_supr_of_directed a a.monotone.directed_le section variables {p p'} lemma mem_sup : x ∈ p ⊔ p' ↔ ∃ (y ∈ p) (z ∈ p'), y + z = x := ⟨λ h, begin rw [← span_eq p, ← span_eq p', ← span_union] at h, apply span_induction h, { rintro y (h | h), { exact ⟨y, h, 0, by simp, by simp⟩ }, { exact ⟨0, by simp, y, h, by simp⟩ } }, { exact ⟨0, by simp, 0, by simp⟩ }, { rintro _ _ ⟨y₁, hy₁, z₁, hz₁, rfl⟩ ⟨y₂, hy₂, z₂, hz₂, rfl⟩, exact ⟨_, add_mem _ hy₁ hy₂, _, add_mem _ hz₁ hz₂, by simp [add_assoc]; cc⟩ }, { rintro a _ ⟨y, hy, z, hz, rfl⟩, exact ⟨_, smul_mem _ a hy, _, smul_mem _ a hz, by simp [smul_add]⟩ } end, by rintro ⟨y, hy, z, hz, rfl⟩; exact add_mem _ ((le_sup_left : p ≤ p ⊔ p') hy) ((le_sup_right : p' ≤ p ⊔ p') hz)⟩ lemma mem_sup' : x ∈ p ⊔ p' ↔ ∃ (y : p) (z : p'), (y:M) + z = x := mem_sup.trans $ by simp only [set_like.exists, coe_mk] lemma coe_sup : ↑(p ⊔ p') = (p + p' : set M) := by { ext, rw [set_like.mem_coe, mem_sup, set.mem_add], simp, } end /- This is the character `∙`, with escape sequence `\.`, and is thus different from the scalar multiplication character `•`, with escape sequence `\bub`. -/ notation R`∙`:1000 x := span R (@singleton _ _ set.has_singleton x) lemma mem_span_singleton_self (x : M) : x ∈ R ∙ x := subset_span rfl lemma nontrivial_span_singleton {x : M} (h : x ≠ 0) : nontrivial (R ∙ x) := ⟨begin use [0, x, submodule.mem_span_singleton_self x], intros H, rw [eq_comm, submodule.mk_eq_zero] at H, exact h H end⟩ lemma mem_span_singleton {y : M} : x ∈ (R ∙ y) ↔ ∃ a:R, a • y = x := ⟨λ h, begin apply span_induction h, { rintro y (rfl|⟨⟨⟩⟩), exact ⟨1, by simp⟩ }, { exact ⟨0, by simp⟩ }, { rintro _ _ ⟨a, rfl⟩ ⟨b, rfl⟩, exact ⟨a + b, by simp [add_smul]⟩ }, { rintro a _ ⟨b, rfl⟩, exact ⟨a * b, by simp [smul_smul]⟩ } end, by rintro ⟨a, y, rfl⟩; exact smul_mem _ _ (subset_span $ by simp)⟩ lemma le_span_singleton_iff {s : submodule R M} {v₀ : M} : s ≤ (R ∙ v₀) ↔ ∀ v ∈ s, ∃ r : R, r • v₀ = v := by simp_rw [set_like.le_def, mem_span_singleton] lemma span_singleton_eq_top_iff (x : M) : (R ∙ x) = ⊤ ↔ ∀ v, ∃ r : R, r • x = v := begin rw [eq_top_iff, le_span_singleton_iff], finish, end @[simp] lemma span_zero_singleton : (R ∙ (0:M)) = ⊥ := by { ext, simp [mem_span_singleton, eq_comm] } lemma span_singleton_eq_range (y : M) : ↑(R ∙ y) = range ((• y) : R → M) := set.ext $ λ x, mem_span_singleton lemma span_singleton_smul_le (r : R) (x : M) : (R ∙ (r • x)) ≤ R ∙ x := begin rw [span_le, set.singleton_subset_iff, set_like.mem_coe], exact smul_mem _ _ (mem_span_singleton_self _) end lemma span_singleton_smul_eq {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {r : K} (x : E) (hr : r ≠ 0) : (K ∙ (r • x)) = K ∙ x := begin refine le_antisymm (span_singleton_smul_le r x) _, convert span_singleton_smul_le r⁻¹ (r • x), exact (inv_smul_smul₀ hr _).symm end lemma disjoint_span_singleton {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {s : submodule K E} {x : E} : disjoint s (K ∙ x) ↔ (x ∈ s → x = 0) := begin refine disjoint_def.trans ⟨λ H hx, H x hx $ subset_span $ mem_singleton x, _⟩, assume H y hy hyx, obtain ⟨c, hc⟩ := mem_span_singleton.1 hyx, subst y, classical, by_cases hc : c = 0, by simp only [hc, zero_smul], rw [s.smul_mem_iff hc] at hy, rw [H hy, smul_zero] end lemma disjoint_span_singleton' {K E : Type*} [division_ring K] [add_comm_group E] [module K E] {p : submodule K E} {x : E} (x0 : x ≠ 0) : disjoint p (K ∙ x) ↔ x ∉ p := disjoint_span_singleton.trans ⟨λ h₁ h₂, x0 (h₁ h₂), λ h₁ h₂, (h₁ h₂).elim⟩ lemma mem_span_insert {y} : x ∈ span R (insert y s) ↔ ∃ (a:R) (z ∈ span R s), x = a • y + z := begin simp only [← union_singleton, span_union, mem_sup, mem_span_singleton, exists_prop, exists_exists_eq_and], rw [exists_comm], simp only [eq_comm, add_comm, exists_and_distrib_left] end lemma span_insert_eq_span (h : x ∈ span R s) : span R (insert x s) = span R s := span_eq_of_le _ (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_span : span R (span R s : set M) = span R s := span_eq _ lemma span_eq_bot : span R (s : set M) = ⊥ ↔ ∀ x ∈ s, (x:M) = 0 := eq_bot_iff.trans ⟨ λ H x h, (mem_bot R).1 $ H $ subset_span h, λ H, span_le.2 (λ x h, (mem_bot R).2 $ H x h)⟩ @[simp] lemma span_singleton_eq_bot : (R ∙ x) = ⊥ ↔ x = 0 := span_eq_bot.trans $ by simp @[simp] lemma span_zero : span R (0 : set M) = ⊥ := by rw [←singleton_zero, span_singleton_eq_bot] @[simp] lemma span_image [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) : span R₂ (f '' s) = map f (span R s) := span_eq_of_le _ (image_subset _ subset_span) $ map_le_iff_le_comap.2 $ span_le.2 $ image_subset_iff.1 subset_span lemma apply_mem_span_image_of_mem_span [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) {x : M} {s : set M} (h : x ∈ submodule.span R s) : f x ∈ submodule.span R₂ (f '' s) := begin rw submodule.span_image, exact submodule.mem_map_of_mem h end /-- `f` is an explicit argument so we can `apply` this theorem and obtain `h` as a new goal. -/ lemma not_mem_span_of_apply_not_mem_span_image [ring_hom_surjective σ₁₂] (f : M →ₛₗ[σ₁₂] M₂) {x : M} {s : set M} (h : f x ∉ submodule.span R₂ (f '' s)) : x ∉ submodule.span R s := not.imp h (apply_mem_span_image_of_mem_span f) lemma supr_eq_span {ι : Sort*} (p : ι → submodule R M) : (⨆ (i : ι), p i) = submodule.span R (⋃ (i : ι), ↑(p i)) := le_antisymm (supr_le $ assume i, subset.trans (assume m hm, set.mem_Union.mpr ⟨i, hm⟩) subset_span) (span_le.mpr $ Union_subset_iff.mpr $ assume i m hm, mem_supr_of_mem i hm) lemma span_singleton_le_iff_mem (m : M) (p : submodule R M) : (R ∙ m) ≤ p ↔ m ∈ p := by rw [span_le, singleton_subset_iff, set_like.mem_coe] lemma singleton_span_is_compact_element (x : M) : complete_lattice.is_compact_element (span R {x} : submodule R M) := begin rw complete_lattice.is_compact_element_iff_le_of_directed_Sup_le, intros d hemp hdir hsup, have : x ∈ Sup d, from (set_like.le_def.mp hsup) (mem_span_singleton_self x), obtain ⟨y, ⟨hyd, hxy⟩⟩ := (mem_Sup_of_directed hemp hdir).mp this, exact ⟨y, ⟨hyd, by simpa only [span_le, singleton_subset_iff]⟩⟩, end instance : is_compactly_generated (submodule R M) := ⟨λ s, ⟨(λ x, span R {x}) '' s, ⟨λ t ht, begin rcases (set.mem_image _ _ _).1 ht with ⟨x, hx, rfl⟩, apply singleton_span_is_compact_element, end, by rw [Sup_eq_supr, supr_image, ←span_eq_supr_of_singleton_spans, span_eq]⟩⟩⟩ lemma lt_sup_iff_not_mem {I : submodule R M} {a : M} : I < I ⊔ (R ∙ a) ↔ a ∉ I := begin split, { intro h, by_contra akey, have h1 : I ⊔ (R ∙ a) ≤ I, { simp only [sup_le_iff], split, { exact le_refl I, }, { exact (span_singleton_le_iff_mem a I).mpr akey, } }, have h2 := gt_of_ge_of_gt h1 h, exact lt_irrefl I h2, }, { intro h, apply set_like.lt_iff_le_and_exists.mpr, split, simp only [le_sup_left], use a, split, swap, { assumption, }, { have : (R ∙ a) ≤ I ⊔ (R ∙ a) := le_sup_right, exact this (mem_span_singleton_self a), } }, end lemma mem_supr {ι : Sort*} (p : ι → submodule R M) {m : M} : (m ∈ ⨆ i, p i) ↔ (∀ N, (∀ i, p i ≤ N) → m ∈ N) := begin rw [← span_singleton_le_iff_mem, le_supr_iff], simp only [span_singleton_le_iff_mem], end section open_locale classical /-- For every element in the span of a set, there exists a finite subset of the set such that the element is contained in the span of the subset. -/ lemma mem_span_finite_of_mem_span {S : set M} {x : M} (hx : x ∈ span R S) : ∃ T : finset M, ↑T ⊆ S ∧ x ∈ span R (T : set M) := begin refine span_induction hx (λ x hx, _) _ _ _, { refine ⟨{x}, _, _⟩, { rwa [finset.coe_singleton, set.singleton_subset_iff] }, { rw finset.coe_singleton, exact submodule.mem_span_singleton_self x } }, { use ∅, simp }, { rintros x y ⟨X, hX, hxX⟩ ⟨Y, hY, hyY⟩, refine ⟨X ∪ Y, _, _⟩, { rw finset.coe_union, exact set.union_subset hX hY }, rw [finset.coe_union, span_union, mem_sup], exact ⟨x, hxX, y, hyY, rfl⟩, }, { rintros a x ⟨T, hT, h2⟩, exact ⟨T, hT, smul_mem _ _ h2⟩ } end end /-- The product of two submodules is a submodule. -/ def prod : submodule R (M × M') := { carrier := set.prod p q₁, smul_mem' := by rintro a ⟨x, y⟩ ⟨hx, hy⟩; exact ⟨smul_mem _ a hx, smul_mem _ a hy⟩, .. p.to_add_submonoid.prod q₁.to_add_submonoid } @[simp] lemma prod_coe : (prod p q₁ : set (M × M')) = set.prod p q₁ := rfl @[simp] lemma mem_prod {p : submodule R M} {q : submodule R M'} {x : M × M'} : x ∈ prod p q ↔ x.1 ∈ p ∧ x.2 ∈ q := set.mem_prod lemma span_prod_le (s : set M) (t : set M') : span R (set.prod s t) ≤ prod (span R s) (span R t) := span_le.2 $ set.prod_mono subset_span subset_span @[simp] lemma prod_top : (prod ⊤ ⊤ : submodule R (M × M')) = ⊤ := by ext; simp @[simp] lemma prod_bot : (prod ⊥ ⊥ : submodule R (M × M')) = ⊥ := by ext ⟨x, y⟩; simp [prod.zero_eq_mk] lemma prod_mono {p p' : submodule R M} {q q' : submodule R M'} : p ≤ p' → q ≤ q' → prod p q ≤ prod p' q' := prod_mono @[simp] lemma prod_inf_prod : prod p q₁ ⊓ prod p' q₁' = prod (p ⊓ p') (q₁ ⊓ q₁') := set_like.coe_injective set.prod_inter_prod @[simp] lemma prod_sup_prod : prod p q₁ ⊔ prod p' q₁' = prod (p ⊔ p') (q₁ ⊔ q₁') := begin refine le_antisymm (sup_le (prod_mono le_sup_left le_sup_left) (prod_mono le_sup_right le_sup_right)) _, simp [set_like.le_def], intros xx yy hxx hyy, rcases mem_sup.1 hxx with ⟨x, hx, x', hx', rfl⟩, rcases mem_sup.1 hyy with ⟨y, hy, y', hy', rfl⟩, refine mem_sup.2 ⟨(x, y), ⟨hx, hy⟩, (x', y'), ⟨hx', hy'⟩, rfl⟩ end end add_comm_monoid variables [ring R] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R M₂] [module R M₃] variables (p p' : submodule R M) (q q' : submodule R M₂) variables {r : R} {x y : M} open set @[simp] lemma neg_coe : -(p : set M) = p := set.ext $ λ x, p.neg_mem_iff @[simp] protected lemma map_neg (f : M →ₗ[R] M₂) : map (-f) p = map f p := ext $ λ y, ⟨λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, f.map_neg x⟩, λ ⟨x, hx, hy⟩, hy ▸ ⟨-x, neg_mem _ hx, ((-f).map_neg _).trans (neg_neg (f x))⟩⟩ @[simp] lemma span_neg (s : set M) : span R (-s) = span R s := calc span R (-s) = span R ((-linear_map.id : M →ₗ[R] M) '' s) : by simp ... = map (-linear_map.id) (span R s) : ((-linear_map.id).map_span _).symm ... = span R s : by simp lemma mem_span_insert' {y} {s : set M} : x ∈ span R (insert y s) ↔ ∃(a:R), x + a • y ∈ span R s := begin rw mem_span_insert, split, { rintro ⟨a, z, hz, rfl⟩, exact ⟨-a, by simp [hz, add_assoc]⟩ }, { rintro ⟨a, h⟩, exact ⟨-a, _, h, by simp [add_comm, add_left_comm]⟩ } end end submodule namespace submodule variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₂] [module K V₂] lemma comap_smul (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) (h : a ≠ 0) : p.comap (a • f) = p.comap f := by ext b; simp only [submodule.mem_comap, p.smul_mem_iff h, linear_map.smul_apply] lemma map_smul (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) (h : a ≠ 0) : p.map (a • f) = p.map f := le_antisymm begin rw [map_le_iff_le_comap, comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end begin rw [map_le_iff_le_comap, ← comap_smul f _ a h, ← map_le_iff_le_comap], exact le_refl _ end lemma comap_smul' (f : V →ₗ[K] V₂) (p : submodule K V₂) (a : K) : p.comap (a • f) = (⨅ h : a ≠ 0, p.comap f) := by classical; by_cases a = 0; simp [h, comap_smul] lemma map_smul' (f : V →ₗ[K] V₂) (p : submodule K V) (a : K) : p.map (a • f) = (⨆ h : a ≠ 0, p.map f) := by classical; by_cases a = 0; simp [h, map_smul] end submodule /-! ### Properties of linear maps -/ namespace linear_map section add_comm_monoid variables [semiring R] [semiring R₂] [semiring R₃] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables {σ₁₂ : R →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃} variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] variables [module R M] [module R₂ M₂] [module R₃ M₃] include R open submodule /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. See also `linear_map.eq_on_span'` for a version using `set.eq_on`. -/ lemma eq_on_span {s : set M} {f g : M →ₛₗ[σ₁₂] M₂} (H : set.eq_on f g s) ⦃x⦄ (h : x ∈ span R s) : f x = g x := by apply span_induction h H; simp {contextual := tt} /-- If two linear maps are equal on a set `s`, then they are equal on `submodule.span s`. This version uses `set.eq_on`, and the hidden argument will expand to `h : x ∈ (span R s : set M)`. See `linear_map.eq_on_span` for a version that takes `h : x ∈ span R s` as an argument. -/ lemma eq_on_span' {s : set M} {f g : M →ₛₗ[σ₁₂] M₂} (H : set.eq_on f g s) : set.eq_on f g (span R s : set M) := eq_on_span H /-- If `s` generates the whole module and linear maps `f`, `g` are equal on `s`, then they are equal. -/ lemma ext_on {s : set M} {f g : M →ₛₗ[σ₁₂] M₂} (hv : span R s = ⊤) (h : set.eq_on f g s) : f = g := linear_map.ext (λ x, eq_on_span h (eq_top_iff'.1 hv _)) /-- If the range of `v : ι → M` generates the whole module and linear maps `f`, `g` are equal at each `v i`, then they are equal. -/ lemma ext_on_range {v : ι → M} {f g : M →ₛₗ[σ₁₂] M₂} (hv : span R (set.range v) = ⊤) (h : ∀i, f (v i) = g (v i)) : f = g := ext_on hv (set.forall_range_iff.2 h) section finsupp variables {γ : Type*} [has_zero γ] @[simp] lemma map_finsupp_sum (f : M →ₛₗ[σ₁₂] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_finsupp_sum (t : ι →₀ γ) (g : ι → γ → M →ₛₗ[σ₁₂] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma finsupp_sum_apply (t : ι →₀ γ) (g : ι → γ → M →ₛₗ[σ₁₂] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end finsupp section dfinsupp open dfinsupp variables {γ : ι → Type*} [decidable_eq ι] section sum variables [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)] @[simp] lemma map_dfinsupp_sum (f : M →ₛₗ[σ₁₂] M₂) {t : Π₀ i, γ i} {g : Π i, γ i → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum lemma coe_dfinsupp_sum (t : Π₀ i, γ i) (g : Π i, γ i → M →ₛₗ[σ₁₂] M₂) : ⇑(t.sum g) = t.sum (λ i d, g i d) := coe_fn_sum _ _ @[simp] lemma dfinsupp_sum_apply (t : Π₀ i, γ i) (g : Π i, γ i → M →ₛₗ[σ₁₂] M₂) (b : M) : (t.sum g) b = t.sum (λ i d, g i d b) := sum_apply _ _ _ end sum section sum_add_hom variables [Π i, add_zero_class (γ i)] @[simp] lemma map_dfinsupp_sum_add_hom (f : M →ₛₗ[σ₁₂] M₂) {t : Π₀ i, γ i} {g : Π i, γ i →+ M} : f (sum_add_hom g t) = sum_add_hom (λ i, f.to_add_monoid_hom.comp (g i)) t := f.to_add_monoid_hom.map_dfinsupp_sum_add_hom _ _ end sum_add_hom end dfinsupp variables {σ₂₁ : R₂ →+* R} {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃} variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃] theorem map_cod_restrict [ring_hom_surjective σ₂₁] (p : submodule R M) (f : M₂ →ₛₗ[σ₂₁] M) (h p') : submodule.map (cod_restrict p f h) p' = comap p.subtype (p'.map f) := submodule.ext $ λ ⟨x, hx⟩, by simp [subtype.ext_iff_val] theorem comap_cod_restrict (p : submodule R M) (f : M₂ →ₛₗ[σ₂₁] M) (hf p') : submodule.comap (cod_restrict p f hf) p' = submodule.comap f (map p.subtype p') := submodule.ext $ λ x, ⟨λ h, ⟨⟨_, hf x⟩, h, rfl⟩, by rintro ⟨⟨_, _⟩, h, ⟨⟩⟩; exact h⟩ section /-- The range of a linear map `f : M → M₂` is a submodule of `M₂`. See Note [range copy pattern]. -/ def range [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : submodule R₂ M₂ := (map f ⊤).copy (set.range f) set.image_univ.symm theorem range_coe [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : (range f : set M₂) = set.range f := rfl @[simp] theorem mem_range [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {x} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl lemma range_eq_map [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : f.range = map f ⊤ := by { ext, simp } theorem mem_range_self [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) (x : M) : f x ∈ f.range := ⟨x, rfl⟩ @[simp] theorem range_id : range (linear_map.id : M →ₗ[R] M) = ⊤ := set_like.coe_injective set.range_id theorem range_comp [ring_hom_surjective τ₁₂] [ring_hom_surjective τ₂₃] [ring_hom_surjective τ₁₃] (f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) : range (g.comp f : M →ₛₗ[τ₁₃] M₃) = map g (range f) := set_like.coe_injective (set.range_comp g f) theorem range_comp_le_range [ring_hom_surjective τ₂₃] [ring_hom_surjective τ₁₃] (f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) : range (g.comp f : M →ₛₗ[τ₁₃] M₃) ≤ range g := set_like.coe_mono (set.range_comp_subset_range f g) theorem range_eq_top [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} : range f = ⊤ ↔ surjective f := by rw [set_like.ext'_iff, range_coe, top_coe, set.range_iff_surjective] lemma range_le_iff_comap [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R₂ M₂} : range f ≤ p ↔ comap f p = ⊤ := by rw [range_eq_map, map_le_iff_le_comap, eq_top_iff] lemma map_le_range [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R M} : map f p ≤ range f := set_like.coe_mono (set.image_subset_range f p) end /-- The decreasing sequence of submodules consisting of the ranges of the iterates of a linear map. -/ @[simps] def iterate_range {R M} [ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) : ℕ →ₘ order_dual (submodule R M) := ⟨λ n, (f ^ n).range, λ n m w x h, begin obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w, rw linear_map.mem_range at h, obtain ⟨m, rfl⟩ := h, rw linear_map.mem_range, use (f ^ c) m, rw [pow_add, linear_map.mul_apply], end⟩ /-- Restrict the codomain of a linear map `f` to `f.range`. This is the bundled version of `set.range_factorization`. -/ @[reducible] def range_restrict [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : M →ₛₗ[τ₁₂] f.range := f.cod_restrict f.range f.mem_range_self --set_option trace.class_instances true /-- The range of a linear map is finite if the domain is finite. Note: this instance can form a diamond with `subtype.fintype` in the presence of `fintype M₂`. -/ instance fintype_range [fintype M] [decidable_eq M₂] [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : fintype (range f) := set.fintype_range f section variables (R) (M) /-- Given an element `x` of a module `M` over `R`, the natural map from `R` to scalar multiples of `x`.-/ @[simps] def to_span_singleton (x : M) : R →ₗ[R] M := linear_map.id.smul_right x /-- The range of `to_span_singleton x` is the span of `x`.-/ lemma span_singleton_eq_range (x : M) : (R ∙ x) = (to_span_singleton R M x).range := submodule.ext $ λ y, by {refine iff.trans _ mem_range.symm, exact mem_span_singleton } lemma to_span_singleton_one (x : M) : to_span_singleton R M x 1 = x := one_smul _ _ end /-- The kernel of a linear map `f : M → M₂` is defined to be `comap f ⊥`. This is equivalent to the set of `x : M` such that `f x = 0`. The kernel is a submodule of `M`. -/ def ker (f : M →ₛₗ[τ₁₂] M₂) : submodule R M := comap f ⊥ @[simp] theorem mem_ker {f : M →ₛₗ[τ₁₂] M₂} {y} : y ∈ ker f ↔ f y = 0 := mem_bot R₂ @[simp] theorem ker_id : ker (linear_map.id : M →ₗ[R] M) = ⊥ := rfl @[simp] theorem map_coe_ker (f : M →ₛₗ[τ₁₂] M₂) (x : ker f) : f x = 0 := mem_ker.1 x.2 lemma comp_ker_subtype (f : M →ₛₗ[τ₁₂] M₂) : f.comp f.ker.subtype = 0 := linear_map.ext $ λ x, suffices f x = 0, by simp [this], mem_ker.1 x.2 theorem ker_comp (f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) : ker (g.comp f : M →ₛₗ[τ₁₃] M₃) = comap f (ker g) := rfl theorem ker_le_ker_comp (f : M →ₛₗ[τ₁₂] M₂) (g : M₂ →ₛₗ[τ₂₃] M₃) : ker f ≤ ker (g.comp f : M →ₛₗ[τ₁₃] M₃) := by rw ker_comp; exact comap_mono bot_le theorem disjoint_ker {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R M} : disjoint p (ker f) ↔ ∀ x ∈ p, f x = 0 → x = 0 := by simp [disjoint_def] theorem ker_eq_bot' {f : M →ₛₗ[τ₁₂] M₂} : ker f = ⊥ ↔ (∀ m, f m = 0 → m = 0) := by simpa [disjoint] using @disjoint_ker _ _ _ _ _ _ _ _ _ _ _ f ⊤ theorem ker_eq_bot_of_inverse {τ₂₁ : R₂ →+* R} [ring_hom_inv_pair τ₁₂ τ₂₁] {f : M →ₛₗ[τ₁₂] M₂} {g : M₂ →ₛₗ[τ₂₁] M} (h : (g.comp f : M →ₗ[R] M) = id) : ker f = ⊥ := ker_eq_bot'.2 $ λ m hm, by rw [← id_apply m, ← h, comp_apply, hm, g.map_zero] lemma le_ker_iff_map [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R M} : p ≤ ker f ↔ map f p = ⊥ := by rw [ker, eq_bot_iff, map_le_iff_le_comap] lemma ker_cod_restrict {τ₂₁ : R₂ →+* R} (p : submodule R M) (f : M₂ →ₛₗ[τ₂₁] M) (hf) : ker (cod_restrict p f hf) = ker f := by rw [ker, comap_cod_restrict, map_bot]; refl lemma range_cod_restrict {τ₂₁ : R₂ →+* R} [ring_hom_surjective τ₂₁] (p : submodule R M) (f : M₂ →ₛₗ[τ₂₁] M) (hf) : range (cod_restrict p f hf) = comap p.subtype f.range := by simpa only [range_eq_map] using map_cod_restrict _ _ _ _ lemma ker_restrict {p : submodule R M} {f : M →ₗ[R] M} (hf : ∀ x : M, x ∈ p → f x ∈ p) : ker (f.restrict hf) = (f.dom_restrict p).ker := by rw [restrict_eq_cod_restrict_dom_restrict, ker_cod_restrict] lemma _root_.submodule.map_comap_eq [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) (q : submodule R₂ M₂) : map f (comap f q) = range f ⊓ q := le_antisymm (le_inf map_le_range (map_comap_le _ _)) $ by rintro _ ⟨⟨x, _, rfl⟩, hx⟩; exact ⟨x, hx, rfl⟩ lemma _root_.submodule.map_comap_eq_self [ring_hom_surjective τ₁₂] {f : M →ₛₗ[τ₁₂] M₂} {q : submodule R₂ M₂} (h : q ≤ range f) : map f (comap f q) = q := by rwa [submodule.map_comap_eq, inf_eq_right] @[simp] theorem ker_zero : ker (0 : M →ₛₗ[τ₁₂] M₂) = ⊤ := eq_top_iff'.2 $ λ x, by simp @[simp] theorem range_zero [ring_hom_surjective τ₁₂] : range (0 : M →ₛₗ[τ₁₂] M₂) = ⊥ := by simpa only [range_eq_map] using submodule.map_zero _ theorem ker_eq_top {f : M →ₛₗ[τ₁₂] M₂} : ker f = ⊤ ↔ f = 0 := ⟨λ h, ext $ λ x, mem_ker.1 $ h.symm ▸ trivial, λ h, h.symm ▸ ker_zero⟩ section variables [ring_hom_surjective τ₁₂] lemma range_le_bot_iff (f : M →ₛₗ[τ₁₂] M₂) : range f ≤ ⊥ ↔ f = 0 := by rw [range_le_iff_comap]; exact ker_eq_top theorem range_eq_bot {f : M →ₛₗ[τ₁₂] M₂} : range f = ⊥ ↔ f = 0 := by rw [← range_le_bot_iff, le_bot_iff] lemma range_le_ker_iff {f : M →ₛₗ[τ₁₂] M₂} {g : M₂ →ₛₗ[τ₂₃] M₃} : range f ≤ ker g ↔ (g.comp f : M →ₛₗ[τ₁₃] M₃) = 0 := ⟨λ h, ker_eq_top.1 $ eq_top_iff'.2 $ λ x, h $ ⟨_, rfl⟩, λ h x hx, mem_ker.2 $ exists.elim hx $ λ y hy, by rw [←hy, ←comp_apply, h, zero_apply]⟩ theorem comap_le_comap_iff {f : M →ₛₗ[τ₁₂] M₂} (hf : range f = ⊤) {p p'} : comap f p ≤ comap f p' ↔ p ≤ p' := ⟨λ H x hx, by rcases range_eq_top.1 hf x with ⟨y, hy, rfl⟩; exact H hx, comap_mono⟩ theorem comap_injective {f : M →ₛₗ[τ₁₂] M₂} (hf : range f = ⊤) : injective (comap f) := λ p p' h, le_antisymm ((comap_le_comap_iff hf).1 (le_of_eq h)) ((comap_le_comap_iff hf).1 (ge_of_eq h)) end theorem ker_eq_bot_of_injective {f : M →ₛₗ[τ₁₂] M₂} (hf : injective f) : ker f = ⊥ := begin have : disjoint ⊤ f.ker, by { rw [disjoint_ker, ← map_zero f], exact λ x hx H, hf H }, simpa [disjoint] end /-- The increasing sequence of submodules consisting of the kernels of the iterates of a linear map. -/ @[simps] def iterate_ker {R M} [ring R] [add_comm_group M] [module R M] (f : M →ₗ[R] M) : ℕ →ₘ submodule R M := ⟨λ n, (f ^ n).ker, λ n m w x h, begin obtain ⟨c, rfl⟩ := le_iff_exists_add.mp w, rw linear_map.mem_ker at h, rw [linear_map.mem_ker, add_comm, pow_add, linear_map.mul_apply, h, linear_map.map_zero], end⟩ end add_comm_monoid section add_comm_group variables [semiring R] [semiring R₂] [semiring R₃] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R₂ M₂] [module R₃ M₃] variables {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃} variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃] [ring_hom_surjective τ₁₂] include R open submodule lemma _root_.submodule.comap_map_eq (f : M →ₛₗ[τ₁₂] M₂) (p : submodule R M) : comap f (map f p) = p ⊔ ker f := begin refine le_antisymm _ (sup_le (le_comap_map _ _) (comap_mono bot_le)), rintro x ⟨y, hy, e⟩, exact mem_sup.2 ⟨y, hy, x - y, by simpa using sub_eq_zero.2 e.symm, by simp⟩ end lemma _root_.submodule.comap_map_eq_self {f : M →ₛₗ[τ₁₂] M₂} {p : submodule R M} (h : ker f ≤ p) : comap f (map f p) = p := by rw [submodule.comap_map_eq, sup_of_le_left h] theorem map_le_map_iff (f : M →ₛₗ[τ₁₂] M₂) {p p'} : map f p ≤ map f p' ↔ p ≤ p' ⊔ ker f := by rw [map_le_iff_le_comap, submodule.comap_map_eq] theorem map_le_map_iff' {f : M →ₛₗ[τ₁₂] M₂} (hf : ker f = ⊥) {p p'} : map f p ≤ map f p' ↔ p ≤ p' := by rw [map_le_map_iff, hf, sup_bot_eq] theorem map_injective {f : M →ₛₗ[τ₁₂] M₂} (hf : ker f = ⊥) : injective (map f) := λ p p' h, le_antisymm ((map_le_map_iff' hf).1 (le_of_eq h)) ((map_le_map_iff' hf).1 (ge_of_eq h)) theorem map_eq_top_iff {f : M →ₛₗ[τ₁₂] M₂} (hf : range f = ⊤) {p : submodule R M} : p.map f = ⊤ ↔ p ⊔ f.ker = ⊤ := by simp_rw [← top_le_iff, ← hf, range_eq_map, map_le_map_iff] end add_comm_group section ring variables [ring R] [ring R₂] [ring R₃] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module R M] [module R₂ M₂] [module R₃ M₃] variables {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃} variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃] variables {f : M →ₛₗ[τ₁₂] M₂} include R open submodule theorem sub_mem_ker_iff {x y} : x - y ∈ f.ker ↔ f x = f y := by rw [mem_ker, map_sub, sub_eq_zero] theorem disjoint_ker' {p : submodule R M} : disjoint p (ker f) ↔ ∀ x y ∈ p, f x = f y → x = y := disjoint_ker.trans ⟨λ H x y hx hy h, eq_of_sub_eq_zero $ H _ (sub_mem _ hx hy) (by simp [h]), λ H x h₁ h₂, H x 0 h₁ (zero_mem _) (by simpa using h₂)⟩ theorem inj_of_disjoint_ker {p : submodule R M} {s : set M} (h : s ⊆ p) (hd : disjoint p (ker f)) : ∀ x y ∈ s, f x = f y → x = y := λ x y hx hy, disjoint_ker'.1 hd _ _ (h hx) (h hy) theorem ker_eq_bot : ker f = ⊥ ↔ injective f := by simpa [disjoint] using @disjoint_ker' _ _ _ _ _ _ _ _ _ _ _ f ⊤ lemma ker_le_iff [ring_hom_surjective τ₁₂] {p : submodule R M} : ker f ≤ p ↔ ∃ (y ∈ range f), f ⁻¹' {y} ⊆ p := begin split, { intros h, use 0, rw [← set_like.mem_coe, f.range_coe], exact ⟨⟨0, map_zero f⟩, h⟩, }, { rintros ⟨y, h₁, h₂⟩, rw set_like.le_def, intros z hz, simp only [mem_ker, set_like.mem_coe] at hz, rw [← set_like.mem_coe, f.range_coe, set.mem_range] at h₁, obtain ⟨x, hx⟩ := h₁, have hx' : x ∈ p, { exact h₂ hx, }, have hxz : z + x ∈ p, { apply h₂, simp [hx, hz], }, suffices : z + x - x ∈ p, { simpa only [this, add_sub_cancel], }, exact p.sub_mem hxz hx', }, end end ring section field variables [field K] [field K₂] variables [add_comm_group V] [module K V] variables [add_comm_group V₂] [module K V₂] lemma ker_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : ker (a • f) = ker f := submodule.comap_smul f _ a h lemma ker_smul' (f : V →ₗ[K] V₂) (a : K) : ker (a • f) = ⨅(h : a ≠ 0), ker f := submodule.comap_smul' f _ a lemma range_smul (f : V →ₗ[K] V₂) (a : K) (h : a ≠ 0) : range (a • f) = range f := by simpa only [range_eq_map] using submodule.map_smul f _ a h lemma range_smul' (f : V →ₗ[K] V₂) (a : K) : range (a • f) = ⨆(h : a ≠ 0), range f := by simpa only [range_eq_map] using submodule.map_smul' f _ a lemma span_singleton_sup_ker_eq_top (f : V →ₗ[K] K) {x : V} (hx : f x ≠ 0) : (K ∙ x) ⊔ f.ker = ⊤ := eq_top_iff.2 (λ y hy, submodule.mem_sup.2 ⟨(f y * (f x)⁻¹) • x, submodule.mem_span_singleton.2 ⟨f y * (f x)⁻¹, rfl⟩, ⟨y - (f y * (f x)⁻¹) • x, by rw [linear_map.mem_ker, f.map_sub, f.map_smul, smul_eq_mul, mul_assoc, inv_mul_cancel hx, mul_one, sub_self], by simp only [add_sub_cancel'_right]⟩⟩) end field end linear_map namespace is_linear_map lemma is_linear_map_add [semiring R] [add_comm_monoid M] [module R M] : is_linear_map R (λ (x : M × M), x.1 + x.2) := begin apply is_linear_map.mk, { intros x y, simp, cc }, { intros x y, simp [smul_add] } end lemma is_linear_map_sub {R M : Type*} [semiring R] [add_comm_group M] [module R M]: is_linear_map R (λ (x : M × M), x.1 - x.2) := begin apply is_linear_map.mk, { intros x y, simp [add_comm, add_left_comm, sub_eq_add_neg] }, { intros x y, simp [smul_sub] } end end is_linear_map namespace submodule section add_comm_monoid variables [semiring R] [semiring R₂] [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R₂ M₂] variables (p p' : submodule R M) (q : submodule R₂ M₂) variables {τ₁₂ : R →+* R₂} open linear_map @[simp] theorem map_top [ring_hom_surjective τ₁₂] (f : M →ₛₗ[τ₁₂] M₂) : map f ⊤ = range f := f.range_eq_map.symm @[simp] theorem comap_bot (f : M →ₛₗ[τ₁₂] M₂) : comap f ⊥ = ker f := rfl @[simp] theorem ker_subtype : p.subtype.ker = ⊥ := ker_eq_bot_of_injective $ λ x y, subtype.ext_val @[simp] theorem range_subtype : p.subtype.range = p := by simpa using map_comap_subtype p ⊤ lemma map_subtype_le (p' : submodule R p) : map p.subtype p' ≤ p := by simpa using (map_le_range : map p.subtype p' ≤ p.subtype.range) /-- Under the canonical linear map from a submodule `p` to the ambient space `M`, the image of the maximal submodule of `p` is just `p `. -/ @[simp] lemma map_subtype_top : map p.subtype (⊤ : submodule R p) = p := by simp @[simp] lemma comap_subtype_eq_top {p p' : submodule R M} : comap p.subtype p' = ⊤ ↔ p ≤ p' := eq_top_iff.trans $ map_le_iff_le_comap.symm.trans $ by rw [map_subtype_top] @[simp] lemma comap_subtype_self : comap p.subtype p = ⊤ := comap_subtype_eq_top.2 (le_refl _) @[simp] theorem ker_of_le (p p' : submodule R M) (h : p ≤ p') : (of_le h).ker = ⊥ := by rw [of_le, ker_cod_restrict, ker_subtype] lemma range_of_le (p q : submodule R M) (h : p ≤ q) : (of_le h).range = comap q.subtype p := by rw [← map_top, of_le, linear_map.map_cod_restrict, map_top, range_subtype] end add_comm_monoid section ring variables [ring R] [ring R₂] [add_comm_group M] [add_comm_group M₂] [module R M] [module R₂ M₂] variables (p p' : submodule R M) (q : submodule R₂ M₂) variables {τ₁₂ : R →+* R₂} open linear_map lemma disjoint_iff_comap_eq_bot {p q : submodule R M} : disjoint p q ↔ comap p.subtype q = ⊥ := by rw [eq_bot_iff, ← map_le_map_iff' p.ker_subtype, map_bot, map_comap_subtype, disjoint] /-- If `N ⊆ M` then submodules of `N` are the same as submodules of `M` contained in `N` -/ def map_subtype.rel_iso : submodule R p ≃o {p' : submodule R M // p' ≤ p} := { to_fun := λ p', ⟨map p.subtype p', map_subtype_le p _⟩, inv_fun := λ q, comap p.subtype q, left_inv := λ p', comap_map_eq_self $ by simp, right_inv := λ ⟨q, hq⟩, subtype.ext_val $ by simp [map_comap_subtype p, inf_of_le_right hq], map_rel_iff' := λ p₁ p₂, map_le_map_iff' (ker_subtype p) } /-- If `p ⊆ M` is a submodule, the ordering of submodules of `p` is embedded in the ordering of submodules of `M`. -/ def map_subtype.order_embedding : submodule R p ↪o submodule R M := (rel_iso.to_rel_embedding $ map_subtype.rel_iso p).trans (subtype.rel_embedding _ _) @[simp] lemma map_subtype_embedding_eq (p' : submodule R p) : map_subtype.order_embedding p p' = map p.subtype p' := rfl end ring end submodule namespace linear_map section semiring variables [semiring R] [semiring R₂] [semiring R₃] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R₂ M₂] [module R₃ M₃] variables {τ₁₂ : R →+* R₂} {τ₂₃ : R₂ →+* R₃} {τ₁₃ : R →+* R₃} variables [ring_hom_comp_triple τ₁₂ τ₂₃ τ₁₃] /-- A monomorphism is injective. -/ lemma ker_eq_bot_of_cancel {f : M →ₛₗ[τ₁₂] M₂} (h : ∀ (u v : f.ker →ₗ[R] M), f.comp u = f.comp v → u = v) : f.ker = ⊥ := begin have h₁ : f.comp (0 : f.ker →ₗ[R] M) = 0 := comp_zero _, rw [←submodule.range_subtype f.ker, ←h 0 f.ker.subtype (eq.trans h₁ (comp_ker_subtype f).symm)], exact range_zero end lemma range_comp_of_range_eq_top [ring_hom_surjective τ₁₂] [ring_hom_surjective τ₂₃] [ring_hom_surjective τ₁₃] {f : M →ₛₗ[τ₁₂] M₂} (g : M₂ →ₛₗ[τ₂₃] M₃) (hf : range f = ⊤) : range (g.comp f : M →ₛₗ[τ₁₃] M₃) = range g := by rw [range_comp, hf, submodule.map_top] lemma ker_comp_of_ker_eq_bot (f : M →ₛₗ[τ₁₂] M₂) {g : M₂ →ₛₗ[τ₂₃] M₃} (hg : ker g = ⊥) : ker (g.comp f : M →ₛₗ[τ₁₃] M₃) = ker f := by rw [ker_comp, hg, submodule.comap_bot] end semiring end linear_map @[simp] lemma linear_map.range_range_restrict [semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [module R M] [module R M₂] (f : M →ₗ[R] M₂) : f.range_restrict.range = ⊤ := by simp [f.range_cod_restrict _] /-! ### Linear equivalences -/ namespace linear_equiv section add_comm_monoid section subsingleton variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables [module R M] [module R₂ M₂] variables [subsingleton M] [subsingleton M₂] variables {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R} variables [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] include σ₂₁ /-- Between two zero modules, the zero map is an equivalence. -/ instance : has_zero (M ≃ₛₗ[σ₁₂] M₂) := ⟨{ to_fun := 0, inv_fun := 0, right_inv := λ x, subsingleton.elim _ _, left_inv := λ x, subsingleton.elim _ _, ..(0 : M →ₛₗ[σ₁₂] M₂)}⟩ omit σ₂₁ -- Even though these are implied by `subsingleton.elim` via the `unique` instance below, they're -- nice to have as `rfl`-lemmas for `dsimp`. include σ₂₁ @[simp] lemma zero_symm : (0 : M ≃ₛₗ[σ₁₂] M₂).symm = 0 := rfl @[simp] lemma coe_zero : ⇑(0 : M ≃ₛₗ[σ₁₂] M₂) = 0 := rfl lemma zero_apply (x : M) : (0 : M ≃ₛₗ[σ₁₂] M₂) x = 0 := rfl /-- Between two zero modules, the zero map is the only equivalence. -/ instance : unique (M ≃ₛₗ[σ₁₂] M₂) := { uniq := λ f, to_linear_map_injective (subsingleton.elim _ _), default := 0 } omit σ₂₁ end subsingleton section variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables {module_M : module R M} {module_M₂ : module R₂ M₂} variables {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R} variables {re₁₂ : ring_hom_inv_pair σ₁₂ σ₂₁} {re₂₁ : ring_hom_inv_pair σ₂₁ σ₁₂} variables (e e' : M ≃ₛₗ[σ₁₂] M₂) lemma map_eq_comap {p : submodule R M} : (p.map (e : M →ₛₗ[σ₁₂] M₂) : submodule R₂ M₂) = p.comap (e.symm : M₂ →ₛₗ[σ₂₁] M) := set_like.coe_injective $ by simp [e.image_eq_preimage] /-- A linear equivalence of two modules restricts to a linear equivalence from any submodule `p` of the domain onto the image of that submodule. This is `linear_equiv.of_submodule'` but with `map` on the right instead of `comap` on the left. -/ def of_submodule (p : submodule R M) : p ≃ₛₗ[σ₁₂] ↥(p.map (e : M →ₛₗ[σ₁₂] M₂) : submodule R₂ M₂) := { inv_fun := λ y, ⟨(e.symm : M₂ →ₛₗ[σ₂₁] M) y, by { rcases y with ⟨y', hy⟩, rw submodule.mem_map at hy, rcases hy with ⟨x, hx, hxy⟩, subst hxy, simp only [symm_apply_apply, submodule.coe_mk, coe_coe, hx], }⟩, left_inv := λ x, by simp, right_inv := λ y, by { apply set_coe.ext, simp, }, ..((e : M →ₛₗ[σ₁₂] M₂).dom_restrict p).cod_restrict (p.map (e : M →ₛₗ[σ₁₂] M₂)) (λ x, ⟨x, by simp⟩) } include σ₂₁ @[simp] lemma of_submodule_apply (p : submodule R M) (x : p) : ↑(e.of_submodule p x) = e x := rfl @[simp] lemma of_submodule_symm_apply (p : submodule R M) (x : (p.map (e : M →ₛₗ[σ₁₂] M₂) : submodule R₂ M₂)) : ↑((e.of_submodule p).symm x) = e.symm x := rfl omit σ₂₁ end section finsupp variables {γ : Type*} variables [semiring R] [semiring R₂] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R₂ M₂] [has_zero γ] variables {τ₁₂ : R →+* R₂} {τ₂₁ : R₂ →+* R} variables [ring_hom_inv_pair τ₁₂ τ₂₁] [ring_hom_inv_pair τ₂₁ τ₁₂] include τ₂₁ @[simp] lemma map_finsupp_sum (f : M ≃ₛₗ[τ₁₂] M₂) {t : ι →₀ γ} {g : ι → γ → M} : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum _ omit τ₂₁ end finsupp section dfinsupp open dfinsupp variables [semiring R] [semiring R₂] variables [add_comm_monoid M] [add_comm_monoid M₂] variables [module R M] [module R₂ M₂] variables {τ₁₂ : R →+* R₂} {τ₂₁ : R₂ →+* R} variables [ring_hom_inv_pair τ₁₂ τ₂₁] [ring_hom_inv_pair τ₂₁ τ₁₂] variables {γ : ι → Type*} [decidable_eq ι] include τ₂₁ @[simp] lemma map_dfinsupp_sum [Π i, has_zero (γ i)] [Π i (x : γ i), decidable (x ≠ 0)] (f : M ≃ₛₗ[τ₁₂] M₂) (t : Π₀ i, γ i) (g : Π i, γ i → M) : f (t.sum g) = t.sum (λ i d, f (g i d)) := f.map_sum _ @[simp] lemma map_dfinsupp_sum_add_hom [Π i, add_zero_class (γ i)] (f : M ≃ₛₗ[τ₁₂] M₂) (t : Π₀ i, γ i) (g : Π i, γ i →+ M) : f (sum_add_hom g t) = sum_add_hom (λ i, f.to_add_equiv.to_add_monoid_hom.comp (g i)) t := f.to_add_equiv.map_dfinsupp_sum_add_hom _ _ end dfinsupp section uncurry variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables (V V₂ R) /-- Linear equivalence between a curried and uncurried function. Differs from `tensor_product.curry`. -/ protected def curry : (V × V₂ → R) ≃ₗ[R] (V → V₂ → R) := { map_add' := λ _ _, by { ext, refl }, map_smul' := λ _ _, by { ext, refl }, .. equiv.curry _ _ _ } @[simp] lemma coe_curry : ⇑(linear_equiv.curry R V V₂) = curry := rfl @[simp] lemma coe_curry_symm : ⇑(linear_equiv.curry R V V₂).symm = uncurry := rfl end uncurry section variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄] variables [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] [add_comm_monoid M₄] variables {module_M : module R M} {module_M₂ : module R₂ M₂} {module_M₃ : module R₃ M₃} variables {σ₁₂ : R →+* R₂} {σ₂₁ : R₂ →+* R} variables {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R →+* R₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] variables {σ₃₂ : R₃ →+* R₂} variables {re₁₂ : ring_hom_inv_pair σ₁₂ σ₂₁} {re₂₁ : ring_hom_inv_pair σ₂₁ σ₁₂} variables {re₂₃ : ring_hom_inv_pair σ₂₃ σ₃₂} {re₃₂ : ring_hom_inv_pair σ₃₂ σ₂₃} variables (f : M →ₛₗ[σ₁₂] M₂) (g : M₂ →ₛₗ[σ₂₁] M) (e : M ≃ₛₗ[σ₁₂] M₂) (h : M₂ →ₛₗ[σ₂₃] M₃) variables (e'' : M₂ ≃ₛₗ[σ₂₃] M₃) variables (p q : submodule R M) /-- Linear equivalence between two equal submodules. -/ def of_eq (h : p = q) : p ≃ₗ[R] q := { map_smul' := λ _ _, rfl, map_add' := λ _ _, rfl, .. equiv.set.of_eq (congr_arg _ h) } variables {p q} @[simp] lemma coe_of_eq_apply (h : p = q) (x : p) : (of_eq p q h x : M) = x := rfl @[simp] lemma of_eq_symm (h : p = q) : (of_eq p q h).symm = of_eq q p h.symm := rfl include σ₂₁ /-- A linear equivalence which maps a submodule of one module onto another, restricts to a linear equivalence of the two submodules. -/ def of_submodules (p : submodule R M) (q : submodule R₂ M₂) (h : p.map (e : M →ₛₗ[σ₁₂] M₂) = q) : p ≃ₛₗ[σ₁₂] q := (e.of_submodule p).trans (linear_equiv.of_eq _ _ h) @[simp] lemma of_submodules_apply {p : submodule R M} {q : submodule R₂ M₂} (h : p.map ↑e = q) (x : p) : ↑(e.of_submodules p q h x) = e x := rfl @[simp] lemma of_submodules_symm_apply {p : submodule R M} {q : submodule R₂ M₂} (h : p.map ↑e = q) (x : q) : ↑((e.of_submodules p q h).symm x) = e.symm x := rfl include re₁₂ re₂₁ /-- A linear equivalence of two modules restricts to a linear equivalence from the preimage of any submodule to that submodule. This is `linear_equiv.of_submodule` but with `comap` on the left instead of `map` on the right. -/ def of_submodule' [module R M] [module R₂ M₂] (f : M ≃ₛₗ[σ₁₂] M₂) (U : submodule R₂ M₂) : U.comap (f : M →ₛₗ[σ₁₂] M₂) ≃ₛₗ[σ₁₂] U := (f.symm.of_submodules _ _ f.symm.map_eq_comap).symm lemma of_submodule'_to_linear_map [module R M] [module R₂ M₂] (f : M ≃ₛₗ[σ₁₂] M₂) (U : submodule R₂ M₂) : (f.of_submodule' U).to_linear_map = (f.to_linear_map.dom_restrict _).cod_restrict _ subtype.prop := by { ext, refl } @[simp] lemma of_submodule'_apply [module R M] [module R₂ M₂] (f : M ≃ₛₗ[σ₁₂] M₂) (U : submodule R₂ M₂) (x : U.comap (f : M →ₛₗ[σ₁₂] M₂)) : (f.of_submodule' U x : M₂) = f (x : M) := rfl @[simp] lemma of_submodule'_symm_apply [module R M] [module R₂ M₂] (f : M ≃ₛₗ[σ₁₂] M₂) (U : submodule R₂ M₂) (x : U) : ((f.of_submodule' U).symm x : M) = f.symm (x : M₂) := rfl variable (p) omit σ₂₁ re₁₂ re₂₁ /-- The top submodule of `M` is linearly equivalent to `M`. -/ def of_top (h : p = ⊤) : p ≃ₗ[R] M := { inv_fun := λ x, ⟨x, h.symm ▸ trivial⟩, left_inv := λ ⟨x, h⟩, rfl, right_inv := λ x, rfl, .. p.subtype } @[simp] theorem of_top_apply {h} (x : p) : of_top p h x = x := rfl @[simp] theorem coe_of_top_symm_apply {h} (x : M) : ((of_top p h).symm x : M) = x := rfl theorem of_top_symm_apply {h} (x : M) : (of_top p h).symm x = ⟨x, h.symm ▸ trivial⟩ := rfl include σ₂₁ re₁₂ re₂₁ /-- If a linear map has an inverse, it is a linear equivalence. -/ def of_linear (h₁ : f.comp g = linear_map.id) (h₂ : g.comp f = linear_map.id) : M ≃ₛₗ[σ₁₂] M₂ := { inv_fun := g, left_inv := linear_map.ext_iff.1 h₂, right_inv := linear_map.ext_iff.1 h₁, ..f } omit σ₂₁ re₁₂ re₂₁ include σ₂₁ re₁₂ re₂₁ @[simp] theorem of_linear_apply {h₁ h₂} (x : M) : of_linear f g h₁ h₂ x = f x := rfl omit σ₂₁ re₁₂ re₂₁ include σ₂₁ re₁₂ re₂₁ @[simp] theorem of_linear_symm_apply {h₁ h₂} (x : M₂) : (of_linear f g h₁ h₂).symm x = g x := rfl omit σ₂₁ re₁₂ re₂₁ @[simp] protected theorem range : (e : M →ₛₗ[σ₁₂] M₂).range = ⊤ := linear_map.range_eq_top.2 e.to_equiv.surjective include σ₂₁ re₁₂ re₂₁ lemma eq_bot_of_equiv [module R₂ M₂] (e : p ≃ₛₗ[σ₁₂] (⊥ : submodule R₂ M₂)) : p = ⊥ := begin refine bot_unique (set_like.le_def.2 $ assume b hb, (submodule.mem_bot R).2 _), rw [← p.mk_eq_zero hb, ← e.map_eq_zero_iff], apply submodule.eq_zero_of_bot_submodule end omit σ₂₁ re₁₂ re₂₁ @[simp] protected theorem ker : (e : M →ₛₗ[σ₁₂] M₂).ker = ⊥ := linear_map.ker_eq_bot_of_injective e.to_equiv.injective @[simp] theorem range_comp [ring_hom_surjective σ₁₂] [ring_hom_surjective σ₂₃] [ring_hom_surjective σ₁₃] : (h.comp (e : M →ₛₗ[σ₁₂] M₂) : M →ₛₗ[σ₁₃] M₃).range = h.range := linear_map.range_comp_of_range_eq_top _ e.range include module_M @[simp] theorem ker_comp (l : M →ₛₗ[σ₁₂] M₂) : (((e'' : M₂ →ₛₗ[σ₂₃] M₃).comp l : M →ₛₗ[σ₁₃] M₃) : M →ₛₗ[σ₁₃] M₃).ker = l.ker := linear_map.ker_comp_of_ker_eq_bot _ e''.ker omit module_M variables {f g} include σ₂₁ /-- An linear map `f : M →ₗ[R] M₂` with a left-inverse `g : M₂ →ₗ[R] M` defines a linear equivalence between `M` and `f.range`. This is a computable alternative to `linear_equiv.of_injective`, and a bidirectional version of `linear_map.range_restrict`. -/ def of_left_inverse [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] {g : M₂ → M} (h : function.left_inverse g f) : M ≃ₛₗ[σ₁₂] f.range := { to_fun := f.range_restrict, inv_fun := g ∘ f.range.subtype, left_inv := h, right_inv := λ x, subtype.ext $ let ⟨x', hx'⟩ := linear_map.mem_range.mp x.prop in show f (g x) = x, by rw [←hx', h x'], .. f.range_restrict } omit σ₂₁ @[simp] lemma of_left_inverse_apply [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] (h : function.left_inverse g f) (x : M) : ↑(of_left_inverse h x) = f x := rfl include σ₂₁ @[simp] lemma of_left_inverse_symm_apply [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] (h : function.left_inverse g f) (x : f.range) : (of_left_inverse h).symm x = g x := rfl omit σ₂₁ variables (f) /-- An `injective` linear map `f : M →ₗ[R] M₂` defines a linear equivalence between `M` and `f.range`. See also `linear_map.of_left_inverse`. -/ noncomputable def of_injective [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] (h : injective f) : M ≃ₛₗ[σ₁₂] f.range := of_left_inverse $ classical.some_spec h.has_left_inverse @[simp] theorem of_injective_apply [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] {h : injective f} (x : M) : ↑(of_injective f h x) = f x := rfl /-- A bijective linear map is a linear equivalence. -/ noncomputable def of_bijective [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] (hf₁ : injective f) (hf₂ : surjective f) : M ≃ₛₗ[σ₁₂] M₂ := (of_injective f hf₁).trans (of_top _ $ linear_map.range_eq_top.2 hf₂) @[simp] theorem of_bijective_apply [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] {hf₁ hf₂} (x : M) : of_bijective f hf₁ hf₂ x = f x := rfl end end add_comm_monoid section add_comm_group variables [semiring R] [semiring R₂] [semiring R₃] [semiring R₄] variables [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] variables {module_M : module R M} {module_M₂ : module R₂ M₂} variables {module_M₃ : module R₃ M₃} {module_M₄ : module R₄ M₄} variables {σ₁₂ : R →+* R₂} {σ₃₄ : R₃ →+* R₄} variables {σ₂₁ : R₂ →+* R} {σ₄₃ : R₄ →+* R₃} variables {re₁₂ : ring_hom_inv_pair σ₁₂ σ₂₁} {re₂₁ : ring_hom_inv_pair σ₂₁ σ₁₂} variables {re₃₄ : ring_hom_inv_pair σ₃₄ σ₄₃} {re₄₃ : ring_hom_inv_pair σ₄₃ σ₃₄} variables (e e₁ : M ≃ₛₗ[σ₁₂] M₂) (e₂ : M₃ ≃ₛₗ[σ₃₄] M₄) @[simp] theorem map_neg (a : M) : e (-a) = -e a := e.to_linear_map.map_neg a @[simp] theorem map_sub (a b : M) : e (a - b) = e a - e b := e.to_linear_map.map_sub a b end add_comm_group section neg variables (R) [semiring R] [add_comm_group M] [module R M] /-- `x ↦ -x` as a `linear_equiv` -/ def neg : M ≃ₗ[R] M := { .. equiv.neg M, .. (-linear_map.id : M →ₗ[R] M) } variable {R} @[simp] lemma coe_neg : ⇑(neg R : M ≃ₗ[R] M) = -id := rfl lemma neg_apply (x : M) : neg R x = -x := by simp @[simp] lemma symm_neg : (neg R : M ≃ₗ[R] M).symm = neg R := rfl end neg section comm_semiring variables [comm_semiring R] [add_comm_monoid M] [add_comm_monoid M₂] [add_comm_monoid M₃] variables [module R M] [module R M₂] [module R M₃] open linear_map /-- Multiplying by a unit `a` of the ring `R` is a linear equivalence. -/ def smul_of_unit (a : units R) : M ≃ₗ[R] M := of_linear ((a:R) • 1 : M →ₗ[R] M) (((a⁻¹ : units R) : R) • 1 : M →ₗ[R] M) (by rw [smul_comp, comp_smul, smul_smul, units.mul_inv, one_smul]; refl) (by rw [smul_comp, comp_smul, smul_smul, units.inv_mul, one_smul]; refl) /-- A linear isomorphism between the domains and codomains of two spaces of linear maps gives a linear isomorphism between the two function spaces. -/ def arrow_congr {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_semiring R] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₂₁] [add_comm_monoid M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) : (M₁ →ₗ[R] M₂₁) ≃ₗ[R] (M₂ →ₗ[R] M₂₂) := { to_fun := λ f : M₁ →ₗ[R] M₂₁, (e₂ : M₂₁ →ₗ[R] M₂₂).comp $ f.comp (e₁.symm : M₂ →ₗ[R] M₁), inv_fun := λ f, (e₂.symm : M₂₂ →ₗ[R] M₂₁).comp $ f.comp (e₁ : M₁ →ₗ[R] M₂), left_inv := λ f, by { ext x, simp only [symm_apply_apply, comp_app, coe_comp, coe_coe]}, right_inv := λ f, by { ext x, simp only [comp_app, apply_symm_apply, coe_comp, coe_coe]}, map_add' := λ f g, by { ext x, simp only [map_add, add_apply, comp_app, coe_comp, coe_coe]}, map_smul' := λ c f, by { ext x, simp only [smul_apply, comp_app, coe_comp, map_smulₛₗ, coe_coe]} } @[simp] lemma arrow_congr_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_semiring R] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₂₁] [add_comm_monoid M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₁ →ₗ[R] M₂₁) (x : M₂) : arrow_congr e₁ e₂ f x = e₂ (f (e₁.symm x)) := rfl @[simp] lemma arrow_congr_symm_apply {R M₁ M₂ M₂₁ M₂₂ : Sort*} [comm_semiring R] [add_comm_monoid M₁] [add_comm_monoid M₂] [add_comm_monoid M₂₁] [add_comm_monoid M₂₂] [module R M₁] [module R M₂] [module R M₂₁] [module R M₂₂] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : M₂₁ ≃ₗ[R] M₂₂) (f : M₂ →ₗ[R] M₂₂) (x : M₁) : (arrow_congr e₁ e₂).symm f x = e₂.symm (f (e₁ x)) := rfl lemma arrow_congr_comp {N N₂ N₃ : Sort*} [add_comm_monoid N] [add_comm_monoid N₂] [add_comm_monoid N₃] [module R N] [module R N₂] [module R N₃] (e₁ : M ≃ₗ[R] N) (e₂ : M₂ ≃ₗ[R] N₂) (e₃ : M₃ ≃ₗ[R] N₃) (f : M →ₗ[R] M₂) (g : M₂ →ₗ[R] M₃) : arrow_congr e₁ e₃ (g.comp f) = (arrow_congr e₂ e₃ g).comp (arrow_congr e₁ e₂ f) := by { ext, simp only [symm_apply_apply, arrow_congr_apply, linear_map.comp_apply], } lemma arrow_congr_trans {M₁ M₂ M₃ N₁ N₂ N₃ : Sort*} [add_comm_monoid M₁] [module R M₁] [add_comm_monoid M₂] [module R M₂] [add_comm_monoid M₃] [module R M₃] [add_comm_monoid N₁] [module R N₁] [add_comm_monoid N₂] [module R N₂] [add_comm_monoid N₃] [module R N₃] (e₁ : M₁ ≃ₗ[R] M₂) (e₂ : N₁ ≃ₗ[R] N₂) (e₃ : M₂ ≃ₗ[R] M₃) (e₄ : N₂ ≃ₗ[R] N₃) : (arrow_congr e₁ e₂).trans (arrow_congr e₃ e₄) = arrow_congr (e₁.trans e₃) (e₂.trans e₄) := rfl /-- If `M₂` and `M₃` are linearly isomorphic then the two spaces of linear maps from `M` into `M₂` and `M` into `M₃` are linearly isomorphic. -/ def congr_right (f : M₂ ≃ₗ[R] M₃) : (M →ₗ[R] M₂) ≃ₗ[R] (M →ₗ[R] M₃) := arrow_congr (linear_equiv.refl R M) f /-- If `M` and `M₂` are linearly isomorphic then the two spaces of linear maps from `M` and `M₂` to themselves are linearly isomorphic. -/ def conj (e : M ≃ₗ[R] M₂) : (module.End R M) ≃ₗ[R] (module.End R M₂) := arrow_congr e e lemma conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M) : e.conj f = ((↑e : M →ₗ[R] M₂).comp f).comp (e.symm : M₂ →ₗ[R] M) := rfl lemma symm_conj_apply (e : M ≃ₗ[R] M₂) (f : module.End R M₂) : e.symm.conj f = ((↑e.symm : M₂ →ₗ[R] M).comp f).comp (e : M →ₗ[R] M₂) := rfl lemma conj_comp (e : M ≃ₗ[R] M₂) (f g : module.End R M) : e.conj (g.comp f) = (e.conj g).comp (e.conj f) := arrow_congr_comp e e e f g lemma conj_trans (e₁ : M ≃ₗ[R] M₂) (e₂ : M₂ ≃ₗ[R] M₃) : e₁.conj.trans e₂.conj = (e₁.trans e₂).conj := by { ext f x, refl, } @[simp] lemma conj_id (e : M ≃ₗ[R] M₂) : e.conj linear_map.id = linear_map.id := by { ext, simp [conj_apply], } end comm_semiring section field variables [field K] [add_comm_group M] [add_comm_group M₂] [add_comm_group M₃] variables [module K M] [module K M₂] [module K M₃] variables (K) (M) open linear_map /-- Multiplying by a nonzero element `a` of the field `K` is a linear equivalence. -/ def smul_of_ne_zero (a : K) (ha : a ≠ 0) : M ≃ₗ[K] M := smul_of_unit $ units.mk0 a ha section noncomputable theory open_locale classical lemma ker_to_span_singleton {x : M} (h : x ≠ 0) : (to_span_singleton K M x).ker = ⊥ := begin ext c, split, { intros hc, rw submodule.mem_bot, rw mem_ker at hc, by_contra hc', have : x = 0, calc x = c⁻¹ • (c • x) : by rw [← mul_smul, inv_mul_cancel hc', one_smul] ... = c⁻¹ • ((to_span_singleton K M x) c) : rfl ... = 0 : by rw [hc, smul_zero], tauto }, { rw [mem_ker, submodule.mem_bot], intros h, rw h, simp } end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from `K` to the span of `x`, with invertibility check to consider it as an isomorphism.-/ def to_span_nonzero_singleton (x : M) (h : x ≠ 0) : K ≃ₗ[K] (K ∙ x) := linear_equiv.trans (linear_equiv.of_injective (to_span_singleton K M x) (ker_eq_bot.1 $ ker_to_span_singleton K M h)) (of_eq (to_span_singleton K M x).range (K ∙ x) (span_singleton_eq_range K M x).symm) lemma to_span_nonzero_singleton_one (x : M) (h : x ≠ 0) : to_span_nonzero_singleton K M x h 1 = (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) := begin apply set_like.coe_eq_coe.mp, have : ↑(to_span_nonzero_singleton K M x h 1) = to_span_singleton K M x 1 := rfl, rw [this, to_span_singleton_one, submodule.coe_mk], end /-- Given a nonzero element `x` of a vector space `M` over a field `K`, the natural map from the span of `x` to `K`.-/ abbreviation coord (x : M) (h : x ≠ 0) : (K ∙ x) ≃ₗ[K] K := (to_span_nonzero_singleton K M x h).symm lemma coord_self (x : M) (h : x ≠ 0) : (coord K M x h) (⟨x, submodule.mem_span_singleton_self x⟩ : K ∙ x) = 1 := by rw [← to_span_nonzero_singleton_one K M x h, symm_apply_apply] end end field end linear_equiv namespace submodule section module variables [semiring R] [add_comm_monoid M] [module R M] /-- Given `p` a submodule of the module `M` and `q` a submodule of `p`, `p.equiv_subtype_map q` is the natural `linear_equiv` between `q` and `q.map p.subtype`. -/ def equiv_subtype_map (p : submodule R M) (q : submodule R p) : q ≃ₗ[R] q.map p.subtype := { inv_fun := begin rintro ⟨x, hx⟩, refine ⟨⟨x, _⟩, _⟩; rcases hx with ⟨⟨_, h⟩, _, rfl⟩; assumption end, left_inv := λ ⟨⟨_, _⟩, _⟩, rfl, right_inv := λ ⟨x, ⟨_, h⟩, _, rfl⟩, rfl, .. (p.subtype.dom_restrict q).cod_restrict _ begin rintro ⟨x, hx⟩, refine ⟨x, hx, rfl⟩, end } @[simp] lemma equiv_subtype_map_apply {p : submodule R M} {q : submodule R p} (x : q) : (p.equiv_subtype_map q x : M) = p.subtype.dom_restrict q x := rfl @[simp] lemma equiv_subtype_map_symm_apply {p : submodule R M} {q : submodule R p} (x : q.map p.subtype) : ((p.equiv_subtype_map q).symm x : M) = x := by { cases x, refl } /-- If `s ≤ t`, then we can view `s` as a submodule of `t` by taking the comap of `t.subtype`. -/ @[simps] def comap_subtype_equiv_of_le {p q : submodule R M} (hpq : p ≤ q) : comap q.subtype p ≃ₗ[R] p := { to_fun := λ x, ⟨x, x.2⟩, inv_fun := λ x, ⟨⟨x, hpq x.2⟩, x.2⟩, left_inv := λ x, by simp only [coe_mk, set_like.eta, coe_coe], right_inv := λ x, by simp only [subtype.coe_mk, set_like.eta, coe_coe], map_add' := λ x y, rfl, map_smul' := λ c x, rfl } end module end submodule namespace submodule variables [comm_ring R] [comm_ring R₂] variables [add_comm_group M] [add_comm_group M₂] [module R M] [module R₂ M₂] variables [add_comm_group N] [add_comm_group N₂] [module R N] [module R N₂] variables {τ₁₂ : R →+* R₂} {τ₂₁ : R₂ →+* R} variables [ring_hom_inv_pair τ₁₂ τ₂₁] [ring_hom_inv_pair τ₂₁ τ₁₂] variables (p : submodule R M) (q : submodule R₂ M₂) variables (pₗ : submodule R N) (qₗ : submodule R N₂) include τ₂₁ @[simp] lemma mem_map_equiv {e : M ≃ₛₗ[τ₁₂] M₂} {x : M₂} : x ∈ p.map (e : M →ₛₗ[τ₁₂] M₂) ↔ e.symm x ∈ p := begin rw submodule.mem_map, split, { rintros ⟨y, hy, hx⟩, simp [←hx, hy], }, { intros hx, refine ⟨e.symm x, hx, by simp⟩, }, end omit τ₂₁ lemma map_equiv_eq_comap_symm (e : M ≃ₛₗ[τ₁₂] M₂) (K : submodule R M) : K.map (e : M →ₛₗ[τ₁₂] M₂) = K.comap (e.symm : M₂ →ₛₗ[τ₂₁] M) := submodule.ext (λ _, by rw [mem_map_equiv, mem_comap, linear_equiv.coe_coe]) lemma comap_equiv_eq_map_symm (e : M ≃ₛₗ[τ₁₂] M₂) (K : submodule R₂ M₂) : K.comap (e : M →ₛₗ[τ₁₂] M₂) = K.map (e.symm : M₂ →ₛₗ[τ₂₁] M) := (map_equiv_eq_comap_symm e.symm K).symm lemma comap_le_comap_smul (fₗ : N →ₗ[R] N₂) (c : R) : comap fₗ qₗ ≤ comap (c • fₗ) qₗ := begin rw set_like.le_def, intros m h, change c • (fₗ m) ∈ qₗ, change fₗ m ∈ qₗ at h, apply qₗ.smul_mem _ h, end lemma inf_comap_le_comap_add (f₁ f₂ : M →ₛₗ[τ₁₂] M₂) : comap f₁ q ⊓ comap f₂ q ≤ comap (f₁ + f₂) q := begin rw set_like.le_def, intros m h, change f₁ m + f₂ m ∈ q, change f₁ m ∈ q ∧ f₂ m ∈ q at h, apply q.add_mem h.1 h.2, end /-- Given modules `M`, `M₂` over a commutative ring, together with submodules `p ⊆ M`, `q ⊆ M₂`, the set of maps $\{f ∈ Hom(M, M₂) | f(p) ⊆ q \}$ is a submodule of `Hom(M, M₂)`. -/ def compatible_maps : submodule R (N →ₗ[R] N₂) := { carrier := {fₗ | pₗ ≤ comap fₗ qₗ}, zero_mem' := by { change pₗ ≤ comap 0 qₗ, rw comap_zero, refine le_top, }, add_mem' := λ f₁ f₂ h₁ h₂, by { apply le_trans _ (inf_comap_le_comap_add qₗ f₁ f₂), rw le_inf_iff, exact ⟨h₁, h₂⟩, }, smul_mem' := λ c fₗ h, le_trans h (comap_le_comap_smul qₗ fₗ c), } end submodule namespace equiv variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] /-- An equivalence whose underlying function is linear is a linear equivalence. -/ def to_linear_equiv (e : M ≃ M₂) (h : is_linear_map R (e : M → M₂)) : M ≃ₗ[R] M₂ := { .. e, .. h.mk' e} end equiv namespace add_equiv variables [semiring R] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R M₂] /-- An additive equivalence whose underlying function preserves `smul` is a linear equivalence. -/ def to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : M ≃ₗ[R] M₂ := { map_smul' := h, .. e, } @[simp] lemma coe_to_linear_equiv (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h) = e := rfl @[simp] lemma coe_to_linear_equiv_symm (e : M ≃+ M₂) (h : ∀ (c : R) x, e (c • x) = c • e x) : ⇑(e.to_linear_equiv h).symm = e.symm := rfl end add_equiv section fun_left variables (R M) [semiring R] [add_comm_monoid M] [module R M] variables {m n p : Type*} namespace linear_map /-- Given an `R`-module `M` and a function `m → n` between arbitrary types, construct a linear map `(n → M) →ₗ[R] (m → M)` -/ def fun_left (f : m → n) : (n → M) →ₗ[R] (m → M) := { to_fun := (∘ f), map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl } @[simp] theorem fun_left_apply (f : m → n) (g : n → M) (i : m) : fun_left R M f g i = g (f i) := rfl @[simp] theorem fun_left_id (g : n → M) : fun_left R M _root_.id g = g := rfl theorem fun_left_comp (f₁ : n → p) (f₂ : m → n) : fun_left R M (f₁ ∘ f₂) = (fun_left R M f₂).comp (fun_left R M f₁) := rfl theorem fun_left_surjective_of_injective (f : m → n) (hf : injective f) : surjective (fun_left R M f) := begin classical, intro g, refine ⟨λ x, if h : ∃ y, f y = x then g h.some else 0, _⟩, { ext, dsimp only [fun_left_apply], split_ifs with w, { congr, exact hf w.some_spec, }, { simpa only [not_true, exists_apply_eq_apply] using w } }, end theorem fun_left_injective_of_surjective (f : m → n) (hf : surjective f) : injective (fun_left R M f) := begin obtain ⟨g, hg⟩ := hf.has_right_inverse, suffices : left_inverse (fun_left R M g) (fun_left R M f), { exact this.injective }, intro x, rw [←linear_map.comp_apply, ← fun_left_comp, hg.id, fun_left_id], end end linear_map namespace linear_equiv open linear_map /-- Given an `R`-module `M` and an equivalence `m ≃ n` between arbitrary types, construct a linear equivalence `(n → M) ≃ₗ[R] (m → M)` -/ def fun_congr_left (e : m ≃ n) : (n → M) ≃ₗ[R] (m → M) := linear_equiv.of_linear (fun_left R M e) (fun_left R M e.symm) (linear_map.ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.symm_comp_self, fun_left_id]) (linear_map.ext $ λ x, funext $ λ i, by rw [id_apply, ← fun_left_comp, equiv.self_comp_symm, fun_left_id]) @[simp] theorem fun_congr_left_apply (e : m ≃ n) (x : n → M) : fun_congr_left R M e x = fun_left R M e x := rfl @[simp] theorem fun_congr_left_id : fun_congr_left R M (equiv.refl n) = linear_equiv.refl R (n → M) := rfl @[simp] theorem fun_congr_left_comp (e₁ : m ≃ n) (e₂ : n ≃ p) : fun_congr_left R M (equiv.trans e₁ e₂) = linear_equiv.trans (fun_congr_left R M e₂) (fun_congr_left R M e₁) := rfl @[simp] lemma fun_congr_left_symm (e : m ≃ n) : (fun_congr_left R M e).symm = fun_congr_left R M e.symm := rfl end linear_equiv end fun_left namespace linear_equiv variables [semiring R] [add_comm_monoid M] [module R M] variables (R M) instance automorphism_group : group (M ≃ₗ[R] M) := { mul := λ f g, g.trans f, one := linear_equiv.refl R M, inv := λ f, f.symm, mul_assoc := λ f g h, by {ext, refl}, mul_one := λ f, by {ext, refl}, one_mul := λ f, by {ext, refl}, mul_left_inv := λ f, by {ext, exact f.left_inv x} } /-- Restriction from `R`-linear automorphisms of `M` to `R`-linear endomorphisms of `M`, promoted to a monoid hom. -/ def automorphism_group.to_linear_map_monoid_hom : (M ≃ₗ[R] M) →* (M →ₗ[R] M) := { to_fun := coe, map_one' := rfl, map_mul' := λ _ _, rfl } /-- The tautological action by `M ≃ₗ[R] M` on `M`. This generalizes `function.End.apply_mul_action`. -/ instance apply_distrib_mul_action : distrib_mul_action (M ≃ₗ[R] M) M := { smul := ($), smul_zero := linear_equiv.map_zero, smul_add := linear_equiv.map_add, one_smul := λ _, rfl, mul_smul := λ _ _ _, rfl } @[simp] protected lemma smul_def (f : M ≃ₗ[R] M) (a : M) : f • a = f a := rfl /-- `linear_equiv.apply_distrib_mul_action` is faithful. -/ instance apply_has_faithful_scalar : has_faithful_scalar (M ≃ₗ[R] M) M := ⟨λ _ _, linear_equiv.ext⟩ instance apply_smul_comm_class : smul_comm_class R (M ≃ₗ[R] M) M := { smul_comm := λ r e m, (e.map_smul r m).symm } instance apply_smul_comm_class' : smul_comm_class (M ≃ₗ[R] M) R M := { smul_comm := linear_equiv.map_smul } end linear_equiv namespace linear_map variables [semiring R] [add_comm_monoid M] [module R M] variables (R M) /-- The group of invertible linear maps from `M` to itself -/ @[reducible] def general_linear_group := units (M →ₗ[R] M) namespace general_linear_group variables {R M} instance : has_coe_to_fun (general_linear_group R M) := by apply_instance /-- An invertible linear map `f` determines an equivalence from `M` to itself. -/ def to_linear_equiv (f : general_linear_group R M) : (M ≃ₗ[R] M) := { inv_fun := f.inv.to_fun, left_inv := λ m, show (f.inv * f.val) m = m, by erw f.inv_val; simp, right_inv := λ m, show (f.val * f.inv) m = m, by erw f.val_inv; simp, ..f.val } /-- An equivalence from `M` to itself determines an invertible linear map. -/ def of_linear_equiv (f : (M ≃ₗ[R] M)) : general_linear_group R M := { val := f, inv := (f.symm : M →ₗ[R] M), val_inv := linear_map.ext $ λ _, f.apply_symm_apply _, inv_val := linear_map.ext $ λ _, f.symm_apply_apply _ } variables (R M) /-- The general linear group on `R` and `M` is multiplicatively equivalent to the type of linear equivalences between `M` and itself. -/ def general_linear_equiv : general_linear_group R M ≃* (M ≃ₗ[R] M) := { to_fun := to_linear_equiv, inv_fun := of_linear_equiv, left_inv := λ f, by { ext, refl }, right_inv := λ f, by { ext, refl }, map_mul' := λ x y, by {ext, refl} } @[simp] lemma general_linear_equiv_to_linear_map (f : general_linear_group R M) : (general_linear_equiv R M f : M →ₗ[R] M) = f := by {ext, refl} end general_linear_group end linear_map namespace submodule variables [ring R] [add_comm_group M] [module R M] instance : is_modular_lattice (submodule R M) := ⟨λ x y z xz a ha, begin rw [mem_inf, mem_sup] at ha, rcases ha with ⟨⟨b, hb, c, hc, rfl⟩, haz⟩, rw mem_sup, refine ⟨b, hb, c, mem_inf.2 ⟨hc, _⟩, rfl⟩, rw [← add_sub_cancel c b, add_comm], apply z.sub_mem haz (xz hb), end⟩ end submodule
dcde9ccba861eecc0c295d3e76797e81bbd8157d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Init/Data/Array/QSort.lean
2d46546d68f992d089a1137d7194026c8d121421
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,731
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.Basic namespace Array -- TODO: remove the [Inhabited α] parameters as soon as we have the tactic framework for automating proof generation and using Array.fget def qpartition (as : Array α) (lt : α → α → Bool) (lo hi : Nat) : Nat × Array α := if h : as.size = 0 then (0, as) else have : Inhabited α := ⟨as[0]'(by revert h; cases as.size <;> simp [Nat.zero_lt_succ])⟩ -- TODO: remove let mid := (lo + hi) / 2 let as := if lt (as.get! mid) (as.get! lo) then as.swap! lo mid else as let as := if lt (as.get! hi) (as.get! lo) then as.swap! lo hi else as let as := if lt (as.get! mid) (as.get! hi) then as.swap! mid hi else as let pivot := as.get! hi let rec loop (as : Array α) (i j : Nat) := if h : j < hi then if lt (as.get! j) pivot then let as := as.swap! i j loop as (i+1) (j+1) else loop as i (j+1) else let as := as.swap! i hi (i, as) loop as lo lo termination_by _ => hi - j @[inline] partial def qsort (as : Array α) (lt : α → α → Bool) (low := 0) (high := as.size - 1) : Array α := let rec @[specialize] sort (as : Array α) (low high : Nat) := if low < high then let p := qpartition as lt low high; -- TODO: fix `partial` support in the equation compiler, it breaks if we use `let (mid, as) := partition as lt low high` let mid := p.1 let as := p.2 if mid >= high then as else let as := sort as low mid sort as (mid+1) high else as sort as low high end Array
f32a9dd55c71825bf70552197aae159b12363ae6
fcf3ffa92a3847189ca669cb18b34ef6b2ec2859
/src/world6/level2.lean
49e6e5f3289e177fd719ad3481916f84dc29dcd1
[ "Apache-2.0" ]
permissive
nomoid/lean-proofs
4a80a97888699dee42b092b7b959b22d9aa0c066
b9f03a24623d1a1d111d6c2bbf53c617e2596d6a
refs/heads/master
1,674,955,317,080
1,607,475,706,000
1,607,475,706,000
314,104,281
0
0
null
null
null
null
UTF-8
Lean
false
false
67
lean
example (P : Prop) : P → P := begin intro p, exact p, end
c226a95c0f44bbda29ee549fd7e6e78eb44fcbb3
6e41ee3ac9b96e8980a16295cc21f131e731884f
/hott/algebra/category/set.hlean
63fbe4b977054aa7a353d0430dd2db73b20cfa31
[ "Apache-2.0" ]
permissive
EgbertRijke/lean
3426cfa0e5b3d35d12fc3fd7318b35574cb67dc3
4f2e0c6d7fc9274d953cfa1c37ab2f3e799ab183
refs/heads/master
1,610,834,871,476
1,422,159,801,000
1,422,159,801,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,287
hlean
-- Copyright (c) 2015 Jakob von Raumer. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Jakob von Raumer -- Category of sets import .basic types.pi trunc open truncation sigma sigma.ops pi function eq morphism precategory open equiv namespace precategory universe variable l definition set_precategory : precategory.{l+1 l} (Σ (A : Type.{l}), is_hset A) := begin fapply precategory.mk.{l+1 l}, intros, apply (a.1 → a_1.1), intros, apply trunc_pi, intros, apply b.2, intros, intro x, exact (a_1 (a_2 x)), intros, exact (λ (x : a.1), x), intros, apply funext.path_pi, intro x, apply idp, intros, apply funext.path_pi, intro x, apply idp, intros, apply funext.path_pi, intro x, apply idp, end end precategory namespace category universe variable l attribute precategory.set_precategory.{l+1 l} [instance] definition set_category_equiv_iso (a b : (Σ (A : Type.{l}), is_hset A)) : (a ≅ b) = (a.1 ≃ b.1) := /-begin apply ua, fapply equiv.mk, intro H, apply (isomorphic.rec_on H), intros (H1, H2), apply (is_iso.rec_on H2), intros (H3, H4, H5), fapply equiv.mk, apply (isomorphic.rec_on H), intros (H1, H2), exact H1, fapply is_equiv.adjointify, exact H3, exact sorry, exact sorry, end-/ sorry definition set_category : category.{l+1 l} (Σ (A : Type.{l}), is_hset A) := /-begin assert (C : precategory.{l+1 l} (Σ (A : Type.{l}), is_hset A)), apply precategory.set_precategory, apply category.mk, assert (p : (λ A B p, (set_category_equiv_iso A B) ▹ iso_of_path p) = (λ A B p, @equiv_path A.1 B.1 p)), apply is_equiv.adjointify, intros, apply (isomorphic.rec_on a_1), intros (iso', is_iso'), apply (is_iso.rec_on is_iso'), intros (f', f'sect, f'retr), fapply sigma.path, apply ua, fapply equiv.mk, exact iso', fapply is_equiv.adjointify, exact f', intros, apply (f'retr ▹ _), intros, apply (f'sect ▹ _), apply (@is_hprop.elim), apply is_trunc_is_hprop, intros, end -/ sorry end category
5a20f6389c29dfc186ee6e539dba69417dbf08d2
8e381650eb2c1c5361be64ff97e47d956bf2ab9f
/src/to_mathlib/ideals.lean
f499fec94d1ffc5868f36b68dec7baafbd833cba
[]
no_license
alreadydone/lean-scheme
04c51ab08eca7ccf6c21344d45d202780fa667af
52d7624f57415eea27ed4dfa916cd94189221a1c
refs/heads/master
1,599,418,221,423
1,562,248,559,000
1,562,248,559,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,682
lean
/- Basic constructions involving ideals. TODO : Check how much of this isn't actually somehwere in the mathlib. -/ import data.finset import ring_theory.ideal_operations universes u v variables {α : Type u} {β : Type v} [comm_ring α] [comm_ring β] (f : α → β) [is_ring_hom f] def ideal.mk (I : set α) (J : ideal α) (H : I = J) : ideal α := { carrier := I, zero := H.symm ▸ J.zero, add := H.symm ▸ J.add, smul := H.symm ▸ J.smul } def ker : ideal α := ideal.mk {x | f x = 0} (ideal.comap f ⊥) $ set.ext $ λ x, by simp -- If R is not the zero ring, then the zero ideal is not the whole ring. lemma zero_ne_one_bot_ne_top : (0 : α) ≠ 1 → (⊥ : ideal α) ≠ ⊤ := begin intros Hzno, have Honz : (1 : α) ∉ ({0} : set α), intros HC, rw set.mem_singleton_iff at HC, exact Hzno HC.symm, intros HC, replace HC := (ideal.eq_top_iff_one ⊥).1 HC, exact (Honz HC), end -- Every nonzero ring has a maximal ideal. lemma ideal.exists_maximal : (0 : α) ≠ 1 → ∃ S : ideal α, ideal.is_maximal S := begin intros Hzno, have HTnB : (⊥ : ideal α) ≠ ⊤ := zero_ne_one_bot_ne_top Hzno, rcases (ideal.exists_le_maximal ⊥ HTnB) with ⟨M, ⟨HM, HBM⟩⟩, exact ⟨M, HM⟩, end -- I need this but I really wish I didn't. lemma ideal.span_mem_finset {R : Type u} [decidable_eq R] [comm_ring R] (S : finset R) (f : R → R) : finset.sum S (λ a, f a * a) ∈ (@ideal.span R _ ↑S) := begin unfold ideal.span, apply finset.induction_on S, { simp, }, { intros a S Ha IH, rw finset.coe_insert, rw submodule.mem_span_insert', rw finset.sum_insert Ha, use [-f a], simp [IH], } end
0bd2afe639fd9da3c616f75400ef531cdbace2c1
c6da0300d417abe3464e750ab51a63502b93acfa
/test/break_and.lean
3f10f1527675824a8e031742990f3738119716a3
[ "Apache-2.0" ]
permissive
uwplse/struct_tact
55bc1d260fac498cff83a4d71461041f8ed74bd6
22188ea2e97705d1185f75dde24e6bab88054ab0
refs/heads/master
1,630,670,592,496
1,515,453,299,000
1,515,453,299,000
104,603,771
0
0
null
null
null
null
UTF-8
Lean
false
false
130
lean
import ..src.struct_tact lemma break_conj_test (P Q Z : Prop) : P ∧ Q ∧ Z → Z := begin intros, break_conj, end
f12fe3fd1137bf80d26eb72667cd108c8e025ae9
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/dynamics/circle/rotation_number/translation_number.lean
e48106129c4405b5a064718606b7fb3d21a60681
[ "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
39,650
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 algebra.iterate_hom import analysis.specific_limits import topology.algebra.ordered.monotone_continuity import order.iterate import order.semiconj_Sup /-! # Translation number of a monotone real map that commutes with `x ↦ x + 1` Let `f : ℝ → ℝ` be a monotone map such that `f (x + 1) = f x + 1` for all `x`. Then the limit $$ \tau(f)=\lim_{n\to\infty}{f^n(x)-x}{n} $$ exists and does not depend on `x`. This number is called the *translation number* of `f`. Different authors use different notation for this number: `τ`, `ρ`, `rot`, etc In this file we define a structure `circle_deg1_lift` for bundled maps with these properties, define translation number of `f : circle_deg1_lift`, prove some estimates relating `f^n(x)-x` to `τ(f)`. In case of a continuous map `f` we also prove that `f` admits a point `x` such that `f^n(x)=x+m` if and only if `τ(f)=m/n`. Maps of this type naturally appear as lifts of orientation preserving circle homeomorphisms. More precisely, let `f` be an orientation preserving homeomorphism of the circle $S^1=ℝ/ℤ$, and consider a real number `a` such that `⟦a⟧ = f 0`, where `⟦⟧` means the natural projection `ℝ → ℝ/ℤ`. Then there exists a unique continuous function `F : ℝ → ℝ` such that `F 0 = a` and `⟦F x⟧ = f ⟦x⟧` for all `x` (this fact is not formalized yet). This function is strictly monotone, continuous, and satisfies `F (x + 1) = F x + 1`. The number `⟦τ F⟧ : ℝ / ℤ` is called the *rotation number* of `f`. It does not depend on the choice of `a`. ## Main definitions * `circle_deg1_lift`: a monotone map `f : ℝ → ℝ` such that `f (x + 1) = f x + 1` for all `x`; the type `circle_deg1_lift` is equipped with `lattice` and `monoid` structures; the multiplication is given by composition: `(f * g) x = f (g x)`. * `circle_deg1_lift.translation_number`: translation number of `f : circle_deg1_lift`. ## Main statements We prove the following properties of `circle_deg1_lift.translation_number`. * `circle_deg1_lift.translation_number_eq_of_dist_bounded`: if the distance between `(f^n) 0` and `(g^n) 0` is bounded from above uniformly in `n : ℕ`, then `f` and `g` have equal translation numbers. * `circle_deg1_lift.translation_number_eq_of_semiconj_by`: if two `circle_deg1_lift` maps `f`, `g` are semiconjugate by a `circle_deg1_lift` map, then `τ f = τ g`. * `circle_deg1_lift.translation_number_units_inv`: if `f` is an invertible `circle_deg1_lift` map (equivalently, `f` is a lift of an orientation-preserving circle homeomorphism), then the translation number of `f⁻¹` is the negative of the translation number of `f`. * `circle_deg1_lift.translation_number_mul_of_commute`: if `f` and `g` commute, then `τ (f * g) = τ f + τ g`. * `circle_deg1_lift.translation_number_eq_rat_iff`: the translation number of `f` is equal to a rational number `m / n` if and only if `(f^n) x = x + m` for some `x`. * `circle_deg1_lift.semiconj_of_bijective_of_translation_number_eq`: if `f` and `g` are two bijective `circle_deg1_lift` maps and their translation numbers are equal, then these maps are semiconjugate to each other. * `circle_deg1_lift.semiconj_of_group_action_of_forall_translation_number_eq`: let `f₁` and `f₂` be two actions of a group `G` on the circle by degree 1 maps (formally, `f₁` and `f₂` are two homomorphisms from `G →* circle_deg1_lift`). If the translation numbers of `f₁ g` and `f₂ g` are equal to each other for all `g : G`, then these two actions are semiconjugate by some `F : circle_deg1_lift`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. ## Notation We use a local notation `τ` for the translation number of `f : circle_deg1_lift`. ## Implementation notes We define the translation number of `f : circle_deg1_lift` to be the limit of the sequence `(f ^ (2 ^ n)) 0 / (2 ^ n)`, then prove that `((f ^ n) x - x) / n` tends to this number for any `x`. This way it is much easier to prove that the limit exists and basic properties of the limit. We define translation number for a wider class of maps `f : ℝ → ℝ` instead of lifts of orientation preserving circle homeomorphisms for two reasons: * non-strictly monotone circle self-maps with discontinuities naturally appear as Poincaré maps for some flows on the two-torus (e.g., one can take a constant flow and glue in a few Cherry cells); * definition and some basic properties still work for this class. ## References * [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes] ## TODO Here are some short-term goals. * Introduce a structure or a typeclass for lifts of circle homeomorphisms. We use `units circle_deg1_lift` for now, but it's better to have a dedicated type (or a typeclass?). * Prove that the `semiconj_by` relation on circle homeomorphisms is an equivalence relation. * Introduce `conditionally_complete_lattice` structure, use it in the proof of `circle_deg1_lift.semiconj_of_group_action_of_forall_translation_number_eq`. * Prove that the orbits of the irrational rotation are dense in the circle. Deduce that a homeomorphism with an irrational rotation is semiconjugate to the corresponding irrational translation by a continuous `circle_deg1_lift`. ## Tags circle homeomorphism, rotation number -/ open filter set function (hiding commute) int open_locale topological_space classical /-! ### Definition and monoid structure -/ /-- A lift of a monotone degree one map `S¹ → S¹`. -/ structure circle_deg1_lift : Type := (to_fun : ℝ → ℝ) (monotone' : monotone to_fun) (map_add_one' : ∀ x, to_fun (x + 1) = to_fun x + 1) namespace circle_deg1_lift instance : has_coe_to_fun circle_deg1_lift (λ _, ℝ → ℝ) := ⟨circle_deg1_lift.to_fun⟩ @[simp] lemma coe_mk (f h₁ h₂) : ⇑(mk f h₁ h₂) = f := rfl variables (f g : circle_deg1_lift) protected lemma monotone : monotone f := f.monotone' @[mono] lemma mono {x y} (h : x ≤ y) : f x ≤ f y := f.monotone h lemma strict_mono_iff_injective : strict_mono f ↔ injective f := f.monotone.strict_mono_iff_injective @[simp] lemma map_add_one : ∀ x, f (x + 1) = f x + 1 := f.map_add_one' @[simp] lemma map_one_add (x : ℝ) : f (1 + x) = 1 + f x := by rw [add_comm, map_add_one, add_comm] theorem coe_inj : ∀ ⦃f g : circle_deg1_lift ⦄, (f : ℝ → ℝ) = g → f = g := assume ⟨f, fm, fd⟩ ⟨g, gm, gd⟩ h, by congr; exact h @[ext] theorem ext ⦃f g : circle_deg1_lift ⦄ (h : ∀ x, f x = g x) : f = g := coe_inj $ funext h theorem ext_iff {f g : circle_deg1_lift} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ instance : monoid circle_deg1_lift := { mul := λ f g, { to_fun := f ∘ g, monotone' := f.monotone.comp g.monotone, map_add_one' := λ x, by simp [map_add_one] }, one := ⟨id, monotone_id, λ _, rfl⟩, mul_one := λ f, coe_inj $ function.comp.right_id f, one_mul := λ f, coe_inj $ function.comp.left_id f, mul_assoc := λ f₁ f₂ f₃, coe_inj rfl } instance : inhabited circle_deg1_lift := ⟨1⟩ @[simp] lemma coe_mul : ⇑(f * g) = f ∘ g := rfl lemma mul_apply (x) : (f * g) x = f (g x) := rfl @[simp] lemma coe_one : ⇑(1 : circle_deg1_lift) = id := rfl instance units_has_coe_to_fun : has_coe_to_fun (units circle_deg1_lift) (λ _, ℝ → ℝ) := ⟨λ f, ⇑(f : circle_deg1_lift)⟩ @[simp, norm_cast] lemma units_coe (f : units circle_deg1_lift) : ⇑(f : circle_deg1_lift) = f := rfl @[simp] lemma units_inv_apply_apply (f : units circle_deg1_lift) (x : ℝ) : (f⁻¹ : units circle_deg1_lift) (f x) = x := by simp only [← units_coe, ← mul_apply, f.inv_mul, coe_one, id] @[simp] lemma units_apply_inv_apply (f : units circle_deg1_lift) (x : ℝ) : f ((f⁻¹ : units circle_deg1_lift) x) = x := by simp only [← units_coe, ← mul_apply, f.mul_inv, coe_one, id] /-- If a lift of a circle map is bijective, then it is an order automorphism of the line. -/ def to_order_iso : units circle_deg1_lift →* ℝ ≃o ℝ := { to_fun := λ f, { to_fun := f, inv_fun := ⇑(f⁻¹), left_inv := units_inv_apply_apply f, right_inv := units_apply_inv_apply f, map_rel_iff' := λ x y, ⟨λ h, by simpa using mono ↑(f⁻¹) h, mono f⟩ }, map_one' := rfl, map_mul' := λ f g, rfl } @[simp] lemma coe_to_order_iso (f : units circle_deg1_lift) : ⇑(to_order_iso f) = f := rfl @[simp] lemma coe_to_order_iso_symm (f : units circle_deg1_lift) : ⇑(to_order_iso f).symm = (f⁻¹ : units circle_deg1_lift) := rfl @[simp] lemma coe_to_order_iso_inv (f : units circle_deg1_lift) : ⇑(to_order_iso f)⁻¹ = (f⁻¹ : units circle_deg1_lift) := rfl lemma is_unit_iff_bijective {f : circle_deg1_lift} : is_unit f ↔ bijective f := ⟨λ ⟨u, h⟩, h ▸ (to_order_iso u).bijective, λ h, units.is_unit { val := f, inv := { to_fun := (equiv.of_bijective f h).symm, monotone' := λ x y hxy, (f.strict_mono_iff_injective.2 h.1).le_iff_le.1 (by simp only [equiv.of_bijective_apply_symm_apply f h, hxy]), map_add_one' := λ x, h.1 $ by simp only [equiv.of_bijective_apply_symm_apply f, f.map_add_one] }, val_inv := ext $ equiv.of_bijective_apply_symm_apply f h, inv_val := ext $ equiv.of_bijective_symm_apply_apply f h }⟩ lemma coe_pow : ∀ n : ℕ, ⇑(f^n) = (f^[n]) | 0 := rfl | (n+1) := by {ext x, simp [coe_pow n, pow_succ'] } lemma semiconj_by_iff_semiconj {f g₁ g₂ : circle_deg1_lift} : semiconj_by f g₁ g₂ ↔ semiconj f g₁ g₂ := ext_iff lemma commute_iff_commute {f g : circle_deg1_lift} : commute f g ↔ function.commute f g := ext_iff /-! ### Translate by a constant -/ /-- The map `y ↦ x + y` as a `circle_deg1_lift`. More precisely, we define a homomorphism from `multiplicative ℝ` to `units circle_deg1_lift`, so the translation by `x` is `translation (multiplicative.of_add x)`. -/ def translate : multiplicative ℝ →* units circle_deg1_lift := by refine (units.map _).comp to_units.to_monoid_hom; exact { to_fun := λ x, ⟨λ y, x.to_add + y, λ y₁ y₂ h, add_le_add_left h _, λ y, (add_assoc _ _ _).symm⟩, map_one' := ext $ zero_add, map_mul' := λ x y, ext $ add_assoc _ _ } @[simp] lemma translate_apply (x y : ℝ) : translate (multiplicative.of_add x) y = x + y := rfl @[simp] lemma translate_inv_apply (x y : ℝ) : (translate $ multiplicative.of_add x)⁻¹ y = -x + y := rfl @[simp] lemma translate_zpow (x : ℝ) (n : ℤ) : (translate (multiplicative.of_add x))^n = translate (multiplicative.of_add $ ↑n * x) := by simp only [← zsmul_eq_mul, of_add_zsmul, monoid_hom.map_zpow] @[simp] lemma translate_pow (x : ℝ) (n : ℕ) : (translate (multiplicative.of_add x))^n = translate (multiplicative.of_add $ ↑n * x) := translate_zpow x n @[simp] lemma translate_iterate (x : ℝ) (n : ℕ) : (translate (multiplicative.of_add x))^[n] = translate (multiplicative.of_add $ ↑n * x) := by rw [← units_coe, ← coe_pow, ← units.coe_pow, translate_pow, units_coe] /-! ### Commutativity with integer translations In this section we prove that `f` commutes with translations by an integer number. First we formulate these statements (for a natural or an integer number, addition on the left or on the right, addition or subtraction) using `function.commute`, then reformulate as `simp` lemmas `map_int_add` etc. -/ lemma commute_nat_add (n : ℕ) : function.commute f ((+) n) := by simpa only [nsmul_one, add_left_iterate] using function.commute.iterate_right f.map_one_add n lemma commute_add_nat (n : ℕ) : function.commute f (λ x, x + n) := by simp only [add_comm _ (n:ℝ), f.commute_nat_add n] lemma commute_sub_nat (n : ℕ) : function.commute f (λ x, x - n) := by simpa only [sub_eq_add_neg] using (f.commute_add_nat n).inverses_right (equiv.add_right _).right_inv (equiv.add_right _).left_inv lemma commute_add_int : ∀ n : ℤ, function.commute f (λ x, x + n) | (n:ℕ) := f.commute_add_nat n | -[1+n] := by simpa only [sub_eq_add_neg] using f.commute_sub_nat (n + 1) lemma commute_int_add (n : ℤ) : function.commute f ((+) n) := by simpa only [add_comm _ (n:ℝ)] using f.commute_add_int n lemma commute_sub_int (n : ℤ) : function.commute f (λ x, x - n) := by simpa only [sub_eq_add_neg] using (f.commute_add_int n).inverses_right (equiv.add_right _).right_inv (equiv.add_right _).left_inv @[simp] lemma map_int_add (m : ℤ) (x : ℝ) : f (m + x) = m + f x := f.commute_int_add m x @[simp] lemma map_add_int (x : ℝ) (m : ℤ) : f (x + m) = f x + m := f.commute_add_int m x @[simp] lemma map_sub_int (x : ℝ) (n : ℤ) : f (x - n) = f x - n := f.commute_sub_int n x @[simp] lemma map_add_nat (x : ℝ) (n : ℕ) : f (x + n) = f x + n := f.map_add_int x n @[simp] lemma map_nat_add (n : ℕ) (x : ℝ) : f (n + x) = n + f x := f.map_int_add n x @[simp] lemma map_sub_nat (x : ℝ) (n : ℕ) : f (x - n) = f x - n := f.map_sub_int x n lemma map_int_of_map_zero (n : ℤ) : f n = f 0 + n := by rw [← f.map_add_int, zero_add] @[simp] lemma map_fract_sub_fract_eq (x : ℝ) : f (fract x) - fract x = f x - x := by rw [int.fract, f.map_sub_int, sub_sub_sub_cancel_right] /-! ### Pointwise order on circle maps -/ /-- Monotone circle maps form a lattice with respect to the pointwise order -/ noncomputable instance : lattice circle_deg1_lift := { sup := λ f g, { to_fun := λ x, max (f x) (g x), monotone' := λ x y h, max_le_max (f.mono h) (g.mono h), -- TODO: generalize to `monotone.max` map_add_one' := λ x, by simp [max_add_add_right] }, le := λ f g, ∀ x, f x ≤ g x, le_refl := λ f x, le_refl (f x), le_trans := λ f₁ f₂ f₃ h₁₂ h₂₃ x, le_trans (h₁₂ x) (h₂₃ x), le_antisymm := λ f₁ f₂ h₁₂ h₂₁, ext $ λ x, le_antisymm (h₁₂ x) (h₂₁ x), le_sup_left := λ f g x, le_max_left (f x) (g x), le_sup_right := λ f g x, le_max_right (f x) (g x), sup_le := λ f₁ f₂ f₃ h₁ h₂ x, max_le (h₁ x) (h₂ x), inf := λ f g, { to_fun := λ x, min (f x) (g x), monotone' := λ x y h, min_le_min (f.mono h) (g.mono h), map_add_one' := λ x, by simp [min_add_add_right] }, inf_le_left := λ f g x, min_le_left (f x) (g x), inf_le_right := λ f g x, min_le_right (f x) (g x), le_inf := λ f₁ f₂ f₃ h₂ h₃ x, le_min (h₂ x) (h₃ x) } @[simp] lemma sup_apply (x : ℝ) : (f ⊔ g) x = max (f x) (g x) := rfl @[simp] lemma inf_apply (x : ℝ) : (f ⊓ g) x = min (f x) (g x) := rfl lemma iterate_monotone (n : ℕ) : monotone (λ f : circle_deg1_lift, f^[n]) := λ f g h, f.monotone.iterate_le_of_le h _ lemma iterate_mono {f g : circle_deg1_lift} (h : f ≤ g) (n : ℕ) : f^[n] ≤ (g^[n]) := iterate_monotone n h lemma pow_mono {f g : circle_deg1_lift} (h : f ≤ g) (n : ℕ) : f^n ≤ g^n := λ x, by simp only [coe_pow, iterate_mono h n x] lemma pow_monotone (n : ℕ) : monotone (λ f : circle_deg1_lift, f^n) := λ f g h, pow_mono h n /-! ### Estimates on `(f * g) 0` We prove the estimates `f 0 + ⌊g 0⌋ ≤ f (g 0) ≤ f 0 + ⌈g 0⌉` and some corollaries with added/removed floors and ceils. We also prove that for two semiconjugate maps `g₁`, `g₂`, the distance between `g₁ 0` and `g₂ 0` is less than two. -/ lemma map_le_of_map_zero (x : ℝ) : f x ≤ f 0 + ⌈x⌉ := calc f x ≤ f ⌈x⌉ : f.monotone $ le_ceil _ ... = f 0 + ⌈x⌉ : f.map_int_of_map_zero _ lemma map_map_zero_le : f (g 0) ≤ f 0 + ⌈g 0⌉ := f.map_le_of_map_zero (g 0) lemma floor_map_map_zero_le : ⌊f (g 0)⌋ ≤ ⌊f 0⌋ + ⌈g 0⌉ := calc ⌊f (g 0)⌋ ≤ ⌊f 0 + ⌈g 0⌉⌋ : floor_mono $ f.map_map_zero_le g ... = ⌊f 0⌋ + ⌈g 0⌉ : floor_add_int _ _ lemma ceil_map_map_zero_le : ⌈f (g 0)⌉ ≤ ⌈f 0⌉ + ⌈g 0⌉ := calc ⌈f (g 0)⌉ ≤ ⌈f 0 + ⌈g 0⌉⌉ : ceil_mono $ f.map_map_zero_le g ... = ⌈f 0⌉ + ⌈g 0⌉ : ceil_add_int _ _ lemma map_map_zero_lt : f (g 0) < f 0 + g 0 + 1 := calc f (g 0) ≤ f 0 + ⌈g 0⌉ : f.map_map_zero_le g ... < f 0 + (g 0 + 1) : add_lt_add_left (ceil_lt_add_one _) _ ... = f 0 + g 0 + 1 : (add_assoc _ _ _).symm lemma le_map_of_map_zero (x : ℝ) : f 0 + ⌊x⌋ ≤ f x := calc f 0 + ⌊x⌋ = f ⌊x⌋ : (f.map_int_of_map_zero _).symm ... ≤ f x : f.monotone $ floor_le _ lemma le_map_map_zero : f 0 + ⌊g 0⌋ ≤ f (g 0) := f.le_map_of_map_zero (g 0) lemma le_floor_map_map_zero : ⌊f 0⌋ + ⌊g 0⌋ ≤ ⌊f (g 0)⌋ := calc ⌊f 0⌋ + ⌊g 0⌋ = ⌊f 0 + ⌊g 0⌋⌋ : (floor_add_int _ _).symm ... ≤ ⌊f (g 0)⌋ : floor_mono $ f.le_map_map_zero g lemma le_ceil_map_map_zero : ⌈f 0⌉ + ⌊g 0⌋ ≤ ⌈(f * g) 0⌉ := calc ⌈f 0⌉ + ⌊g 0⌋ = ⌈f 0 + ⌊g 0⌋⌉ : (ceil_add_int _ _).symm ... ≤ ⌈f (g 0)⌉ : ceil_mono $ f.le_map_map_zero g lemma lt_map_map_zero : f 0 + g 0 - 1 < f (g 0) := calc f 0 + g 0 - 1 = f 0 + (g 0 - 1) : add_sub_assoc _ _ _ ... < f 0 + ⌊g 0⌋ : add_lt_add_left (sub_one_lt_floor _) _ ... ≤ f (g 0) : f.le_map_map_zero g lemma dist_map_map_zero_lt : dist (f 0 + g 0) (f (g 0)) < 1 := begin rw [dist_comm, real.dist_eq, abs_lt, lt_sub_iff_add_lt', sub_lt_iff_lt_add', ← sub_eq_add_neg], exact ⟨f.lt_map_map_zero g, f.map_map_zero_lt g⟩ end lemma dist_map_zero_lt_of_semiconj {f g₁ g₂ : circle_deg1_lift} (h : function.semiconj f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := calc dist (g₁ 0) (g₂ 0) ≤ dist (g₁ 0) (f (g₁ 0) - f 0) + dist _ (g₂ 0) : dist_triangle _ _ _ ... = dist (f 0 + g₁ 0) (f (g₁ 0)) + dist (g₂ 0 + f 0) (g₂ (f 0)) : by simp only [h.eq, real.dist_eq, sub_sub, add_comm (f 0), sub_sub_assoc_swap, abs_sub_comm (g₂ (f 0))] ... < 2 : add_lt_add (f.dist_map_map_zero_lt g₁) (g₂.dist_map_map_zero_lt f) lemma dist_map_zero_lt_of_semiconj_by {f g₁ g₂ : circle_deg1_lift} (h : semiconj_by f g₁ g₂) : dist (g₁ 0) (g₂ 0) < 2 := dist_map_zero_lt_of_semiconj $ semiconj_by_iff_semiconj.1 h /-! ### Limits at infinities and continuity -/ protected lemma tendsto_at_bot : tendsto f at_bot at_bot := tendsto_at_bot_mono f.map_le_of_map_zero $ tendsto_at_bot_add_const_left _ _ $ tendsto_at_bot_mono (λ x, (ceil_lt_add_one x).le) $ tendsto_at_bot_add_const_right _ _ tendsto_id protected lemma tendsto_at_top : tendsto f at_top at_top := tendsto_at_top_mono f.le_map_of_map_zero $ tendsto_at_top_add_const_left _ _ $ tendsto_at_top_mono (λ x, (sub_one_lt_floor x).le) $ by simpa [sub_eq_add_neg] using tendsto_at_top_add_const_right _ _ tendsto_id lemma continuous_iff_surjective : continuous f ↔ function.surjective f := ⟨λ h, h.surjective f.tendsto_at_top f.tendsto_at_bot, f.monotone.continuous_of_surjective⟩ /-! ### Estimates on `(f^n) x` If we know that `f x` is `≤`/`<`/`≥`/`>`/`=` to `x + m`, then we have a similar estimate on `f^[n] x` and `x + n * m`. For `≤`, `≥`, and `=` we formulate both `of` (implication) and `iff` versions because implications work for `n = 0`. For `<` and `>` we formulate only `iff` versions. -/ lemma iterate_le_of_map_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) (n : ℕ) : f^[n] x ≤ x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_le_of_map_le f.monotone (monotone_id.add_const m) h n lemma le_iterate_of_add_int_le_map {x : ℝ} {m : ℤ} (h : x + m ≤ f x) (n : ℕ) : x + n * m ≤ (f^[n]) x := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).symm.iterate_le_of_map_le (monotone_id.add_const m) f.monotone h n lemma iterate_eq_of_map_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) (n : ℕ) : f^[n] x = x + n * m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_eq_of_map_eq n h lemma iterate_pos_le_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x ≤ x + n * m ↔ f x ≤ x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_le_iff_map_le f.monotone (strict_mono_id.add_const m) hn lemma iterate_pos_lt_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x < x + n * m ↔ f x < x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_lt_iff_map_lt f.monotone (strict_mono_id.add_const m) hn lemma iterate_pos_eq_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : f^[n] x = x + n * m ↔ f x = x + m := by simpa only [nsmul_eq_mul, add_right_iterate] using (f.commute_add_int m).iterate_pos_eq_iff_map_eq f.monotone (strict_mono_id.add_const m) hn lemma le_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m ≤ (f^[n]) x ↔ x + m ≤ f x := by simpa only [not_lt] using not_congr (f.iterate_pos_lt_iff hn) lemma lt_iterate_pos_iff {x : ℝ} {m : ℤ} {n : ℕ} (hn : 0 < n) : x + n * m < (f^[n]) x ↔ x + m < f x := by simpa only [not_le] using not_congr (f.iterate_pos_le_iff hn) lemma mul_floor_map_zero_le_floor_iterate_zero (n : ℕ) : ↑n * ⌊f 0⌋ ≤ ⌊(f^[n] 0)⌋ := begin rw [le_floor, int.cast_mul, int.cast_coe_nat, ← zero_add ((n : ℝ) * _)], apply le_iterate_of_add_int_le_map, simp [floor_le] end /-! ### Definition of translation number -/ noncomputable theory /-- An auxiliary sequence used to define the translation number. -/ def transnum_aux_seq (n : ℕ) : ℝ := (f^(2^n)) 0 / 2^n /-- The translation number of a `circle_deg1_lift`, $τ(f)=\lim_{n→∞}\frac{f^n(x)-x}{n}$. We use an auxiliary sequence `\frac{f^{2^n}(0)}{2^n}` to define `τ(f)` because some proofs are simpler this way. -/ def translation_number : ℝ := lim at_top f.transnum_aux_seq -- TODO: choose two different symbols for `circle_deg1_lift.translation_number` and the future -- `circle_mono_homeo.rotation_number`, then make them `localized notation`s local notation `τ` := translation_number lemma transnum_aux_seq_def : f.transnum_aux_seq = λ n : ℕ, (f^(2^n)) 0 / 2^n := rfl lemma translation_number_eq_of_tendsto_aux {τ' : ℝ} (h : tendsto f.transnum_aux_seq at_top (𝓝 τ')) : τ f = τ' := h.lim_eq lemma translation_number_eq_of_tendsto₀ {τ' : ℝ} (h : tendsto (λ n:ℕ, f^[n] 0 / n) at_top (𝓝 τ')) : τ f = τ' := f.translation_number_eq_of_tendsto_aux $ by simpa [(∘), transnum_aux_seq_def, coe_pow] using h.comp (nat.tendsto_pow_at_top_at_top_of_one_lt one_lt_two) lemma translation_number_eq_of_tendsto₀' {τ' : ℝ} (h : tendsto (λ n:ℕ, f^[n + 1] 0 / (n + 1)) at_top (𝓝 τ')) : τ f = τ' := f.translation_number_eq_of_tendsto₀ $ (tendsto_add_at_top_iff_nat 1).1 h lemma transnum_aux_seq_zero : f.transnum_aux_seq 0 = f 0 := by simp [transnum_aux_seq] lemma transnum_aux_seq_dist_lt (n : ℕ) : dist (f.transnum_aux_seq n) (f.transnum_aux_seq (n+1)) < (1 / 2) / (2^n) := begin have : 0 < (2^(n+1):ℝ) := pow_pos zero_lt_two _, rw [div_div_eq_div_mul, ← pow_succ, ← abs_of_pos this], replace := abs_pos.2 (ne_of_gt this), convert (div_lt_div_right this).2 ((f^(2^n)).dist_map_map_zero_lt (f^(2^n))), simp_rw [transnum_aux_seq, real.dist_eq], rw [← abs_div, sub_div, pow_succ', pow_succ, ← two_mul, mul_div_mul_left _ _ (@two_ne_zero ℝ _ _), pow_mul, sq, mul_apply] end lemma tendsto_translation_number_aux : tendsto f.transnum_aux_seq at_top (𝓝 $ τ f) := (cauchy_seq_of_le_geometric_two 1 (λ n, le_of_lt $ f.transnum_aux_seq_dist_lt n)).tendsto_lim lemma dist_map_zero_translation_number_le : dist (f 0) (τ f) ≤ 1 := f.transnum_aux_seq_zero ▸ dist_le_of_le_geometric_two_of_tendsto₀ 1 (λ n, le_of_lt $ f.transnum_aux_seq_dist_lt n) f.tendsto_translation_number_aux lemma tendsto_translation_number_of_dist_bounded_aux (x : ℕ → ℝ) (C : ℝ) (H : ∀ n : ℕ, dist ((f^n) 0) (x n) ≤ C) : tendsto (λ n : ℕ, x (2^n) / (2^n)) at_top (𝓝 $ τ f) := begin refine f.tendsto_translation_number_aux.congr_dist (squeeze_zero (λ _, dist_nonneg) _ _), { exact λ n, C / 2^n }, { intro n, have : 0 < (2^n:ℝ) := pow_pos zero_lt_two _, convert (div_le_div_right this).2 (H (2^n)), rw [transnum_aux_seq, real.dist_eq, ← sub_div, abs_div, abs_of_pos this, real.dist_eq] }, { exact mul_zero C ▸ tendsto_const_nhds.mul (tendsto_inv_at_top_zero.comp $ tendsto_pow_at_top_at_top_of_one_lt one_lt_two) } end lemma translation_number_eq_of_dist_bounded {f g : circle_deg1_lift} (C : ℝ) (H : ∀ n : ℕ, dist ((f^n) 0) ((g^n) 0) ≤ C) : τ f = τ g := eq.symm $ g.translation_number_eq_of_tendsto_aux $ f.tendsto_translation_number_of_dist_bounded_aux _ C H @[simp] lemma translation_number_one : τ 1 = 0 := translation_number_eq_of_tendsto₀ _ $ by simp [tendsto_const_nhds] lemma translation_number_eq_of_semiconj_by {f g₁ g₂ : circle_deg1_lift} (H : semiconj_by f g₁ g₂) : τ g₁ = τ g₂ := translation_number_eq_of_dist_bounded 2 $ λ n, le_of_lt $ dist_map_zero_lt_of_semiconj_by $ H.pow_right n lemma translation_number_eq_of_semiconj {f g₁ g₂ : circle_deg1_lift} (H : function.semiconj f g₁ g₂) : τ g₁ = τ g₂ := translation_number_eq_of_semiconj_by $ semiconj_by_iff_semiconj.2 H lemma translation_number_mul_of_commute {f g : circle_deg1_lift} (h : commute f g) : τ (f * g) = τ f + τ g := begin have : tendsto (λ n : ℕ, ((λ k, (f^k) 0 + (g^k) 0) (2^n)) / (2^n)) at_top (𝓝 $ τ f + τ g) := ((f.tendsto_translation_number_aux.add g.tendsto_translation_number_aux).congr $ λ n, (add_div ((f^(2^n)) 0) ((g^(2^n)) 0) ((2:ℝ)^n)).symm), refine tendsto_nhds_unique ((f * g).tendsto_translation_number_of_dist_bounded_aux _ 1 (λ n, _)) this, rw [h.mul_pow, dist_comm], exact le_of_lt ((f^n).dist_map_map_zero_lt (g^n)) end @[simp] lemma translation_number_units_inv (f : units circle_deg1_lift) : τ ↑(f⁻¹) = -τ f := eq_neg_iff_add_eq_zero.2 $ by simp [← translation_number_mul_of_commute (commute.refl _).units_inv_left] @[simp] lemma translation_number_pow : ∀ n : ℕ, τ (f^n) = n * τ f | 0 := by simp | (n+1) := by rw [pow_succ', translation_number_mul_of_commute (commute.pow_self f n), translation_number_pow n, nat.cast_add_one, add_mul, one_mul] @[simp] lemma translation_number_zpow (f : units circle_deg1_lift) : ∀ n : ℤ, τ (f ^ n : units _) = n * τ f | (n : ℕ) := by simp [translation_number_pow f n] | -[1+n] := by { simp, ring } @[simp] lemma translation_number_conj_eq (f : units circle_deg1_lift) (g : circle_deg1_lift) : τ (↑f * g * ↑(f⁻¹)) = τ g := (translation_number_eq_of_semiconj_by (f.mk_semiconj_by g)).symm @[simp] lemma translation_number_conj_eq' (f : units circle_deg1_lift) (g : circle_deg1_lift) : τ (↑(f⁻¹) * g * f) = τ g := translation_number_conj_eq f⁻¹ g lemma dist_pow_map_zero_mul_translation_number_le (n:ℕ) : dist ((f^n) 0) (n * f.translation_number) ≤ 1 := f.translation_number_pow n ▸ (f^n).dist_map_zero_translation_number_le lemma tendsto_translation_number₀' : tendsto (λ n:ℕ, (f^(n+1)) 0 / (n+1)) at_top (𝓝 $ τ f) := begin refine (tendsto_iff_dist_tendsto_zero.2 $ squeeze_zero (λ _, dist_nonneg) (λ n, _) ((tendsto_const_div_at_top_nhds_0_nat 1).comp (tendsto_add_at_top_nat 1))), dsimp, have : (0:ℝ) < n + 1 := n.cast_add_one_pos, rw [real.dist_eq, div_sub' _ _ _ (ne_of_gt this), abs_div, ← real.dist_eq, abs_of_pos this, div_le_div_right this, ← nat.cast_add_one], apply dist_pow_map_zero_mul_translation_number_le end lemma tendsto_translation_number₀ : tendsto (λ n:ℕ, ((f^n) 0) / n) at_top (𝓝 $ τ f) := (tendsto_add_at_top_iff_nat 1).1 f.tendsto_translation_number₀' /-- For any `x : ℝ` the sequence $\frac{f^n(x)-x}{n}$ tends to the translation number of `f`. In particular, this limit does not depend on `x`. -/ lemma tendsto_translation_number (x : ℝ) : tendsto (λ n:ℕ, ((f^n) x - x) / n) at_top (𝓝 $ τ f) := begin rw [← translation_number_conj_eq' (translate $ multiplicative.of_add x)], convert tendsto_translation_number₀ _, ext n, simp [sub_eq_neg_add, units.conj_pow'] end lemma tendsto_translation_number' (x : ℝ) : tendsto (λ n:ℕ, ((f^(n+1)) x - x) / (n+1)) at_top (𝓝 $ τ f) := (tendsto_add_at_top_iff_nat 1).2 (f.tendsto_translation_number x) lemma translation_number_mono : monotone τ := λ f g h, le_of_tendsto_of_tendsto' f.tendsto_translation_number₀ g.tendsto_translation_number₀ $ λ n, div_le_div_of_le_of_nonneg (pow_mono h n 0) n.cast_nonneg lemma translation_number_translate (x : ℝ) : τ (translate $ multiplicative.of_add x) = x := translation_number_eq_of_tendsto₀' _ $ by simp [nat.cast_add_one_ne_zero, mul_div_cancel_left, tendsto_const_nhds] lemma translation_number_le_of_le_add {z : ℝ} (hz : ∀ x, f x ≤ x + z) : τ f ≤ z := translation_number_translate z ▸ translation_number_mono (λ x, trans_rel_left _ (hz x) (add_comm _ _)) lemma le_translation_number_of_add_le {z : ℝ} (hz : ∀ x, x + z ≤ f x) : z ≤ τ f := translation_number_translate z ▸ translation_number_mono (λ x, trans_rel_right _ (add_comm _ _) (hz x)) lemma translation_number_le_of_le_add_int {x : ℝ} {m : ℤ} (h : f x ≤ x + m) : τ f ≤ m := le_of_tendsto' (f.tendsto_translation_number' x) $ λ n, (div_le_iff' (n.cast_add_one_pos : (0 : ℝ) < _)).mpr $ sub_le_iff_le_add'.2 $ (coe_pow f (n + 1)).symm ▸ f.iterate_le_of_map_le_add_int h (n + 1) lemma translation_number_le_of_le_add_nat {x : ℝ} {m : ℕ} (h : f x ≤ x + m) : τ f ≤ m := @translation_number_le_of_le_add_int f x m h lemma le_translation_number_of_add_int_le {x : ℝ} {m : ℤ} (h : x + m ≤ f x) : ↑m ≤ τ f := ge_of_tendsto' (f.tendsto_translation_number' x) $ λ n, (le_div_iff (n.cast_add_one_pos : (0 : ℝ) < _)).mpr $ le_sub_iff_add_le'.2 $ by simp only [coe_pow, mul_comm (m:ℝ), ← nat.cast_add_one, f.le_iterate_of_add_int_le_map h] lemma le_translation_number_of_add_nat_le {x : ℝ} {m : ℕ} (h : x + m ≤ f x) : ↑m ≤ τ f := @le_translation_number_of_add_int_le f x m h /-- If `f x - x` is an integer number `m` for some point `x`, then `τ f = m`. On the circle this means that a map with a fixed point has rotation number zero. -/ lemma translation_number_of_eq_add_int {x : ℝ} {m : ℤ} (h : f x = x + m) : τ f = m := le_antisymm (translation_number_le_of_le_add_int f $ le_of_eq h) (le_translation_number_of_add_int_le f $ le_of_eq h.symm) lemma floor_sub_le_translation_number (x : ℝ) : ↑⌊f x - x⌋ ≤ τ f := le_translation_number_of_add_int_le f $ le_sub_iff_add_le'.1 (floor_le $ f x - x) lemma translation_number_le_ceil_sub (x : ℝ) : τ f ≤ ⌈f x - x⌉ := translation_number_le_of_le_add_int f $ sub_le_iff_le_add'.1 (le_ceil $ f x - x) lemma map_lt_of_translation_number_lt_int {n : ℤ} (h : τ f < n) (x : ℝ) : f x < x + n := not_le.1 $ mt f.le_translation_number_of_add_int_le $ not_le.2 h lemma map_lt_of_translation_number_lt_nat {n : ℕ} (h : τ f < n) (x : ℝ) : f x < x + n := @map_lt_of_translation_number_lt_int f n h x lemma map_lt_add_floor_translation_number_add_one (x : ℝ) : f x < x + ⌊τ f⌋ + 1 := begin rw [add_assoc], norm_cast, refine map_lt_of_translation_number_lt_int _ _ _, push_cast, exact lt_floor_add_one _ end lemma map_lt_add_translation_number_add_one (x : ℝ) : f x < x + τ f + 1 := calc f x < x + ⌊τ f⌋ + 1 : f.map_lt_add_floor_translation_number_add_one x ... ≤ x + τ f + 1 : by { mono*, exact floor_le (τ f) } lemma lt_map_of_int_lt_translation_number {n : ℤ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := not_le.1 $ mt f.translation_number_le_of_le_add_int $ not_le.2 h lemma lt_map_of_nat_lt_translation_number {n : ℕ} (h : ↑n < τ f) (x : ℝ) : x + n < f x := @lt_map_of_int_lt_translation_number f n h x /-- If `f^n x - x`, `n > 0`, is an integer number `m` for some point `x`, then `τ f = m / n`. On the circle this means that a map with a periodic orbit has a rational rotation number. -/ lemma translation_number_of_map_pow_eq_add_int {x : ℝ} {n : ℕ} {m : ℤ} (h : (f^n) x = x + m) (hn : 0 < n) : τ f = m / n := begin have := (f^n).translation_number_of_eq_add_int h, rwa [translation_number_pow, mul_comm, ← eq_div_iff] at this, exact nat.cast_ne_zero.2 (ne_of_gt hn) end /-- If a predicate depends only on `f x - x` and holds for all `0 ≤ x ≤ 1`, then it holds for all `x`. -/ lemma forall_map_sub_of_Icc (P : ℝ → Prop) (h : ∀ x ∈ Icc (0:ℝ) 1, P (f x - x)) (x : ℝ) : P (f x - x) := f.map_fract_sub_fract_eq x ▸ h _ ⟨fract_nonneg _, le_of_lt (fract_lt_one _)⟩ lemma translation_number_lt_of_forall_lt_add (hf : continuous f) {z : ℝ} (hz : ∀ x, f x < x + z) : τ f < z := begin obtain ⟨x, xmem, hx⟩ : ∃ x ∈ Icc (0:ℝ) 1, ∀ y ∈ Icc (0:ℝ) 1, f y - y ≤ f x - x, from is_compact_Icc.exists_forall_ge (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuous_on, refine lt_of_le_of_lt _ (sub_lt_iff_lt_add'.2 $ hz x), apply translation_number_le_of_le_add, simp only [← sub_le_iff_le_add'], exact f.forall_map_sub_of_Icc (λ a, a ≤ f x - x) hx end lemma lt_translation_number_of_forall_add_lt (hf : continuous f) {z : ℝ} (hz : ∀ x, x + z < f x) : z < τ f := begin obtain ⟨x, xmem, hx⟩ : ∃ x ∈ Icc (0:ℝ) 1, ∀ y ∈ Icc (0:ℝ) 1, f x - x ≤ f y - y, from is_compact_Icc.exists_forall_le (nonempty_Icc.2 zero_le_one) (hf.sub continuous_id).continuous_on, refine lt_of_lt_of_le (lt_sub_iff_add_lt'.2 $ hz x) _, apply le_translation_number_of_add_le, simp only [← le_sub_iff_add_le'], exact f.forall_map_sub_of_Icc _ hx end /-- If `f` is a continuous monotone map `ℝ → ℝ`, `f (x + 1) = f x + 1`, then there exists `x` such that `f x = x + τ f`. -/ lemma exists_eq_add_translation_number (hf : continuous f) : ∃ x, f x = x + τ f := begin obtain ⟨a, ha⟩ : ∃ x, f x ≤ x + f.translation_number, { by_contradiction H, push_neg at H, exact lt_irrefl _ (f.lt_translation_number_of_forall_add_lt hf H) }, obtain ⟨b, hb⟩ : ∃ x, x + τ f ≤ f x, { by_contradiction H, push_neg at H, exact lt_irrefl _ (f.translation_number_lt_of_forall_lt_add hf H) }, exact intermediate_value_univ₂ hf (continuous_id.add continuous_const) ha hb end lemma translation_number_eq_int_iff (hf : continuous f) {m : ℤ} : τ f = m ↔ ∃ x, f x = x + m := begin refine ⟨λ h, h ▸ f.exists_eq_add_translation_number hf, _⟩, rintros ⟨x, hx⟩, exact f.translation_number_of_eq_add_int hx end lemma continuous_pow (hf : continuous f) (n : ℕ) : continuous ⇑(f^n : circle_deg1_lift) := by { rw coe_pow, exact hf.iterate n } lemma translation_number_eq_rat_iff (hf : continuous f) {m : ℤ} {n : ℕ} (hn : 0 < n) : τ f = m / n ↔ ∃ x, (f^n) x = x + m := begin rw [eq_div_iff, mul_comm, ← translation_number_pow]; [skip, exact ne_of_gt (nat.cast_pos.2 hn)], exact (f^n).translation_number_eq_int_iff (f.continuous_pow hf n) end /-- Consider two actions `f₁ f₂ : G →* circle_deg1_lift` of a group on the real line by lifts of orientation preserving circle homeomorphisms. Suppose that for each `g : G` the homeomorphisms `f₁ g` and `f₂ g` have equal rotation numbers. Then there exists `F : circle_deg1_lift` such that `F * f₁ g = f₂ g * F` for all `g : G`. This is a version of Proposition 5.4 from [Étienne Ghys, Groupes d'homeomorphismes du cercle et cohomologie bornee][ghys87:groupes]. -/ lemma semiconj_of_group_action_of_forall_translation_number_eq {G : Type*} [group G] (f₁ f₂ : G →* circle_deg1_lift) (h : ∀ g, τ (f₁ g) = τ (f₂ g)) : ∃ F : circle_deg1_lift, ∀ g, semiconj F (f₁ g) (f₂ g) := begin -- Equality of translation number guarantees that for each `x` -- the set `{f₂ g⁻¹ (f₁ g x) | g : G}` is bounded above. have : ∀ x, bdd_above (range $ λ g, f₂ g⁻¹ (f₁ g x)), { refine λ x, ⟨x + 2, _⟩, rintro _ ⟨g, rfl⟩, have : τ (f₂ g⁻¹) = -τ (f₂ g), by rw [← monoid_hom.coe_to_hom_units, monoid_hom.map_inv, translation_number_units_inv, monoid_hom.coe_to_hom_units], calc f₂ g⁻¹ (f₁ g x) ≤ f₂ g⁻¹ (x + τ (f₁ g) + 1) : mono _ (map_lt_add_translation_number_add_one _ _).le ... = f₂ g⁻¹ (x + τ (f₂ g)) + 1 : by rw [h, map_add_one] ... ≤ x + τ (f₂ g) + τ (f₂ g⁻¹) + 1 + 1 : by { mono, exact (map_lt_add_translation_number_add_one _ _).le } ... = x + 2 : by simp [this, bit0, add_assoc] }, -- We have a theorem about actions by `order_iso`, so we introduce auxiliary maps -- to `ℝ ≃o ℝ`. set F₁ := to_order_iso.comp f₁.to_hom_units, set F₂ := to_order_iso.comp f₂.to_hom_units, have hF₁ : ∀ g, ⇑(F₁ g) = f₁ g := λ _, rfl, have hF₂ : ∀ g, ⇑(F₂ g) = f₂ g := λ _, rfl, simp only [← hF₁, ← hF₂], -- Now we apply `cSup_div_semiconj` and go back to `f₁` and `f₂`. refine ⟨⟨_, λ x y hxy, _, λ x, _⟩, cSup_div_semiconj F₂ F₁ (λ x, _)⟩; simp only [hF₁, hF₂, ← monoid_hom.map_inv, coe_mk], { refine csupr_le_csupr (this y) (λ g, _), exact mono _ (mono _ hxy) }, { simp only [map_add_one], exact (map_csupr_of_continuous_at_of_monotone (continuous_at_id.add continuous_at_const) (monotone_id.add_const (1 : ℝ)) (this x)).symm }, { exact this x } end /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `circle_deg1_lift`. This version uses arguments `f₁ f₂ : units circle_deg1_lift` to assume that `f₁` and `f₂` are homeomorphisms. -/ lemma units_semiconj_of_translation_number_eq {f₁ f₂ : units circle_deg1_lift} (h : τ f₁ = τ f₂) : ∃ F : circle_deg1_lift, semiconj F f₁ f₂ := begin have : ∀ n : multiplicative ℤ, τ ((units.coe_hom _).comp (zpowers_hom _ f₁) n) = τ ((units.coe_hom _).comp (zpowers_hom _ f₂) n), { intro n, simp [h] }, exact (semiconj_of_group_action_of_forall_translation_number_eq _ _ this).imp (λ F hF, hF (multiplicative.of_add 1)) end /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `circle_deg1_lift`. This version uses assumptions `is_unit f₁` and `is_unit f₂` to assume that `f₁` and `f₂` are homeomorphisms. -/ lemma semiconj_of_is_unit_of_translation_number_eq {f₁ f₂ : circle_deg1_lift} (h₁ : is_unit f₁) (h₂ : is_unit f₂) (h : τ f₁ = τ f₂) : ∃ F : circle_deg1_lift, semiconj F f₁ f₂ := by { rcases ⟨h₁, h₂⟩ with ⟨⟨f₁, rfl⟩, ⟨f₂, rfl⟩⟩, exact units_semiconj_of_translation_number_eq h } /-- If two lifts of circle homeomorphisms have the same translation number, then they are semiconjugate by a `circle_deg1_lift`. This version uses assumptions `bijective f₁` and `bijective f₂` to assume that `f₁` and `f₂` are homeomorphisms. -/ lemma semiconj_of_bijective_of_translation_number_eq {f₁ f₂ : circle_deg1_lift} (h₁ : bijective f₁) (h₂ : bijective f₂) (h : τ f₁ = τ f₂) : ∃ F : circle_deg1_lift, semiconj F f₁ f₂ := semiconj_of_is_unit_of_translation_number_eq (is_unit_iff_bijective.2 h₁) (is_unit_iff_bijective.2 h₂) h end circle_deg1_lift
1835757735496dadf8c93f55c4535881a25adadc
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/run/1216.lean
714cb93043870acd28bce12fccc05e30a906f946
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
717
lean
open nat inductive Vec (X : Type*) : ℕ → Type* | nil {} : Vec 0 | cons : X → Pi {n : nat}, Vec n → Vec (n + 1) namespace Vec def get₂ {A : Type} : Π {n : ℕ}, Vec A (succ $ succ n) → A | n (cons x₁ (cons x₂ xs)) := x₂ def get₂a {A : Type} : Π {n : ℕ}, Vec A (n+2) → A | 0 (cons x₁ (cons x₂ xs)) := x₂ | (n+1) (cons x₁ (cons x₂ xs)) := x₂ def get₂b {A : Type} : Π {n : ℕ}, Vec A (n+2) → A | n (cons x₁ (cons x₂ xs)) := x₂ def get₂c {A : Type} : Π {n : ℕ}, Vec A (n+2) → A | .n (@cons .A x₁ .(n+1) (@cons .A x₂ n xs)) := x₂ def get₂d {A : Type} : Π {n : ℕ}, Vec A (n+2) → A | .n (@cons .A x₁ (n+1) (@cons .A x₂ .n xs)) := x₂ end Vec
416a0705e4bf0880d7b8d39a3f1a1627e1981d9f
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/analysis/normed_space/hahn_banach.lean
671cfe5a5c6515f6216f3d1cd509db47f4a6ca7a
[ "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
6,865
lean
/- Copyright (c) 2020 Yury Kudryashov All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Heather Macbeth -/ import analysis.normed_space.operator_norm import analysis.normed_space.extend import analysis.convex.cone import data.complex.is_R_or_C /-! # Hahn-Banach theorem In this file we prove a version of Hahn-Banach theorem for continuous linear functions on normed spaces over `ℝ` and `ℂ`. In order to state and prove its corollaries uniformly, we prove the statements for a field `𝕜` satisfying `is_R_or_C 𝕜`. In this setting, `exists_dual_vector` states that, for any nonzero `x`, there exists a continuous linear form `g` of norm `1` with `g x = ∥x∥` (where the norm has to be interpreted as an element of `𝕜`). -/ universes u v /-- The norm of `x` as an element of `𝕜` (a normed algebra over `ℝ`). This is needed in particular to state equalities of the form `g x = norm' 𝕜 x` when `g` is a linear function. For the concrete cases of `ℝ` and `ℂ`, this is just `∥x∥` and `↑∥x∥`, respectively. -/ noncomputable def norm' (𝕜 : Type*) [nondiscrete_normed_field 𝕜] [normed_algebra ℝ 𝕜] {E : Type*} [normed_group E] (x : E) : 𝕜 := algebra_map ℝ 𝕜 ∥x∥ lemma norm'_def (𝕜 : Type*) [nondiscrete_normed_field 𝕜] [normed_algebra ℝ 𝕜] {E : Type*} [normed_group E] (x : E) : norm' 𝕜 x = (algebra_map ℝ 𝕜 ∥x∥) := rfl lemma norm_norm' (𝕜 : Type*) [nondiscrete_normed_field 𝕜] [normed_algebra ℝ 𝕜] (A : Type*) [normed_group A] (x : A) : ∥norm' 𝕜 x∥ = ∥x∥ := by rw [norm'_def, norm_algebra_map_eq, norm_norm] namespace real variables {E : Type*} [normed_group E] [normed_space ℝ E] /-- Hahn-Banach theorem for continuous linear functions over `ℝ`. -/ theorem exists_extension_norm_eq (p : subspace ℝ E) (f : p →L[ℝ] ℝ) : ∃ g : E →L[ℝ] ℝ, (∀ x : p, g x = f x) ∧ ∥g∥ = ∥f∥ := begin rcases exists_extension_of_le_sublinear ⟨p, f⟩ (λ x, ∥f∥ * ∥x∥) (λ c hc x, by simp only [norm_smul c x, real.norm_eq_abs, abs_of_pos hc, mul_left_comm]) (λ x y, _) (λ x, le_trans (le_abs_self _) (f.le_op_norm _)) with ⟨g, g_eq, g_le⟩, set g' := g.mk_continuous (∥f∥) (λ x, abs_le.2 ⟨neg_le.1 $ g.map_neg x ▸ norm_neg x ▸ g_le (-x), g_le x⟩), { refine ⟨g', g_eq, _⟩, { apply le_antisymm (g.mk_continuous_norm_le (norm_nonneg f) _), refine f.op_norm_le_bound (norm_nonneg _) (λ x, _), dsimp at g_eq, rw ← g_eq, apply g'.le_op_norm } }, { simp only [← mul_add], exact mul_le_mul_of_nonneg_left (norm_add_le x y) (norm_nonneg f) } end end real section is_R_or_C open is_R_or_C variables {𝕜 : Type*} [is_R_or_C 𝕜] {F : Type*} [normed_group F] [normed_space 𝕜 F] /-- Hahn-Banach theorem for continuous linear functions over `𝕜` satisyfing `is_R_or_C 𝕜`. -/ theorem exists_extension_norm_eq (p : subspace 𝕜 F) (f : p →L[𝕜] 𝕜) : ∃ g : F →L[𝕜] 𝕜, (∀ x : p, g x = f x) ∧ ∥g∥ = ∥f∥ := begin letI : module ℝ F := restrict_scalars.semimodule ℝ 𝕜 F, letI : is_scalar_tower ℝ 𝕜 F := restrict_scalars.is_scalar_tower _ _ _, letI : normed_space ℝ F := normed_space.restrict_scalars _ 𝕜 _, -- Let `fr: p →L[ℝ] ℝ` be the real part of `f`. let fr := re_clm.comp (f.restrict_scalars ℝ), have fr_apply : ∀ x, fr x = re (f x) := λ x, rfl, -- Use the real version to get a norm-preserving extension of `fr`, which -- we'll call `g : F →L[ℝ] ℝ`. rcases real.exists_extension_norm_eq (p.restrict_scalars ℝ) fr with ⟨g, ⟨hextends, hnormeq⟩⟩, -- Now `g` can be extended to the `F →L[𝕜] 𝕜` we need. use g.extend_to_𝕜, -- It is an extension of `f`. have h : ∀ x : p, g.extend_to_𝕜 x = f x, { assume x, rw [continuous_linear_map.extend_to_𝕜_apply, ←submodule.coe_smul, hextends, hextends], change (re (f x) : 𝕜) - (I : 𝕜) * (re (f ((I : 𝕜) • x))) = f x, apply ext, { simp only [add_zero, algebra.id.smul_eq_mul, I_re, of_real_im, add_monoid_hom.map_add, zero_sub, I_im', zero_mul, of_real_re, eq_self_iff_true, sub_zero, mul_neg_eq_neg_mul_symm, of_real_neg, mul_re, mul_zero, sub_neg_eq_add, continuous_linear_map.map_smul] }, { simp only [algebra.id.smul_eq_mul, I_re, of_real_im, add_monoid_hom.map_add, zero_sub, I_im', zero_mul, of_real_re, mul_neg_eq_neg_mul_symm, mul_im, zero_add, of_real_neg, mul_re, sub_neg_eq_add, continuous_linear_map.map_smul] } }, refine ⟨h, _⟩, -- And we derive the equality of the norms by bounding on both sides. refine le_antisymm _ _, { calc ∥g.extend_to_𝕜∥ ≤ ∥g∥ : g.extend_to_𝕜.op_norm_le_bound g.op_norm_nonneg (norm_bound _) ... = ∥fr∥ : hnormeq ... ≤ ∥re_clm∥ * ∥f∥ : continuous_linear_map.op_norm_comp_le _ _ ... = ∥f∥ : by rw [re_clm_norm, one_mul] }, { exact f.op_norm_le_bound g.extend_to_𝕜.op_norm_nonneg (λ x, h x ▸ g.extend_to_𝕜.le_op_norm x) }, end end is_R_or_C section dual_vector variables {𝕜 : Type v} [is_R_or_C 𝕜] variables {E : Type u} [normed_group E] [normed_space 𝕜 E] open continuous_linear_equiv submodule open_locale classical lemma coord_norm' (x : E) (h : x ≠ 0) : ∥norm' 𝕜 x • coord 𝕜 x h∥ = 1 := by rw [norm_smul, norm_norm', coord_norm, mul_inv_cancel (mt norm_eq_zero.mp h)] /-- Corollary of Hahn-Banach. Given a nonzero element `x` of a normed space, there exists an element of the dual space, of norm `1`, whose value on `x` is `∥x∥`. -/ theorem exists_dual_vector (x : E) (h : x ≠ 0) : ∃ g : E →L[𝕜] 𝕜, ∥g∥ = 1 ∧ g x = norm' 𝕜 x := begin let p : submodule 𝕜 E := 𝕜 ∙ x, let f := norm' 𝕜 x • coord 𝕜 x h, obtain ⟨g, hg⟩ := exists_extension_norm_eq p f, use g, split, { rw [hg.2, coord_norm'] }, { calc g x = g (⟨x, mem_span_singleton_self x⟩ : 𝕜 ∙ x) : by rw coe_mk ... = (norm' 𝕜 x • coord 𝕜 x h) (⟨x, mem_span_singleton_self x⟩ : 𝕜 ∙ x) : by rw ← hg.1 ... = norm' 𝕜 x : by simp } end /-- Variant of Hahn-Banach, eliminating the hypothesis that `x` be nonzero, and choosing the dual element arbitrarily when `x = 0`. -/ theorem exists_dual_vector' [nontrivial E] (x : E) : ∃ g : E →L[𝕜] 𝕜, ∥g∥ = 1 ∧ g x = norm' 𝕜 x := begin by_cases hx : x = 0, { obtain ⟨y, hy⟩ := exists_ne (0 : E), obtain ⟨g, hg⟩ : ∃ g : E →L[𝕜] 𝕜, ∥g∥ = 1 ∧ g y = norm' 𝕜 y := exists_dual_vector y hy, refine ⟨g, hg.left, _⟩, rw [norm'_def, hx, norm_zero, ring_hom.map_zero, continuous_linear_map.map_zero] }, { exact exists_dual_vector x hx } end end dual_vector
bd5522e8e5d5f48189d613fc121ffe956a7bc561
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Util/Trace.lean
b30e11f4b53e2a4d380219f227007e16d5e2255f
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,533
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ import Lean.Message import Lean.MonadEnv universe u namespace Lean open Std (PersistentArray) structure TraceElem where ref : Syntax msg : MessageData deriving Inhabited structure TraceState where enabled : Bool := true traces : PersistentArray TraceElem := {} deriving Inhabited namespace TraceState private def toFormat (traces : PersistentArray TraceElem) (sep : Format) : IO Format := traces.size.foldM (fun i r => do let curr ← (traces.get! i).msg.format pure $ if i > 0 then r ++ sep ++ curr else r ++ curr) Format.nil end TraceState class MonadTrace (m : Type → Type) where modifyTraceState : (TraceState → TraceState) → m Unit getTraceState : m TraceState export MonadTrace (getTraceState modifyTraceState) instance (m n) [MonadLift m n] [MonadTrace m] : MonadTrace n where modifyTraceState := fun f => liftM (modifyTraceState f : m _) getTraceState := liftM (getTraceState : m _) variable {α : Type} {m : Type → Type} [Monad m] [MonadTrace m] def printTraces {m} [Monad m] [MonadTrace m] [MonadLiftT IO m] : m Unit := do let traceState ← getTraceState traceState.traces.forM fun m => do let d ← m.msg.format IO.println d def resetTraceState {m} [MonadTrace m] : m Unit := modifyTraceState (fun _ => {}) private def checkTraceOptionAux (opts : Options) : Name → Bool | n@(Name.str p _ _) => opts.getBool n || (!opts.contains n && checkTraceOptionAux opts p) | _ => false def checkTraceOption (opts : Options) (cls : Name) : Bool := if opts.isEmpty then false else checkTraceOptionAux opts (`trace ++ cls) private def checkTraceOptionM [MonadOptions m] (cls : Name) : m Bool := do let opts ← getOptions pure $ checkTraceOption opts cls @[inline] def isTracingEnabledFor [MonadOptions m] (cls : Name) : m Bool := do let s ← getTraceState if !s.enabled then pure false else checkTraceOptionM cls @[inline] def enableTracing (b : Bool) : m Bool := do let s ← getTraceState let oldEnabled := s.enabled modifyTraceState fun s => { s with enabled := b } pure oldEnabled @[inline] def getTraces : m (PersistentArray TraceElem) := do let s ← getTraceState pure s.traces @[inline] def modifyTraces (f : PersistentArray TraceElem → PersistentArray TraceElem) : m Unit := modifyTraceState fun s => { s with traces := f s.traces } @[inline] def setTraceState (s : TraceState) : m Unit := modifyTraceState fun _ => s private def addNode (oldTraces : PersistentArray TraceElem) (cls : Name) (ref : Syntax) : m Unit := modifyTraces fun traces => if traces.isEmpty then oldTraces else let d := MessageData.tagged cls (MessageData.node (traces.toArray.map fun elem => elem.msg)) oldTraces.push { ref := ref, msg := d } private def getResetTraces : m (PersistentArray TraceElem) := do let oldTraces ← getTraces modifyTraces fun _ => {} pure oldTraces section variable [MonadRef m] [AddMessageContext m] [MonadOptions m] def addTrace (cls : Name) (msg : MessageData) : m Unit := do let ref ← getRef let msg ← addMessageContext msg modifyTraces fun traces => traces.push { ref := ref, msg := MessageData.tagged cls msg } @[inline] def trace (cls : Name) (msg : Unit → MessageData) : m Unit := do if (← isTracingEnabledFor cls) then addTrace cls (msg ()) @[inline] def traceM (cls : Name) (mkMsg : m MessageData) : m Unit := do if (← isTracingEnabledFor cls) then let msg ← mkMsg addTrace cls msg @[inline] def traceCtx [MonadFinally m] (cls : Name) (ctx : m α) : m α := do let b ← isTracingEnabledFor cls if !b then let old ← enableTracing false try ctx finally enableTracing old else let ref ← getRef let oldCurrTraces ← getResetTraces try ctx finally addNode oldCurrTraces cls ref -- TODO: delete after fix old frontend def MonadTracer.trace (cls : Name) (msg : Unit → MessageData) : m Unit := Lean.trace cls msg end def registerTraceClass (traceClassName : Name) : IO Unit := registerOption (`trace ++ traceClassName) { group := "trace", defValue := false, descr := "enable/disable tracing for the given module and submodules" } macro:max "trace!" id:term:max msg:term : term => `(trace $id fun _ => ($msg : MessageData)) syntax "trace[" ident "]!" (interpolatedStr(term) <|> term) : term macro_rules | `(trace[$id]! $s) => if s.getKind == interpolatedStrKind then `(Lean.trace $(quote id.getId) fun _ => m! $s) else `(Lean.trace $(quote id.getId) fun _ => ($s : MessageData)) private def withNestedTracesFinalizer [Monad m] [MonadTrace m] (ref : Syntax) (currTraces : PersistentArray TraceElem) : m Unit := do modifyTraces fun traces => if traces.size == 0 then currTraces else if traces.size == 1 && traces[0].msg.isNest then currTraces ++ traces -- No nest of nest else let d := traces.foldl (init := MessageData.nil) fun d elem => if d.isNil then elem.msg else m!"{d}\n{elem.msg}" currTraces.push { ref := ref, msg := MessageData.nestD d } @[inline] def withNestedTraces [Monad m] [MonadFinally m] [MonadTrace m] [MonadRef m] (x : m α) : m α := do let currTraces ← getTraces modifyTraces fun _ => {} let ref ← getRef try x finally withNestedTracesFinalizer ref currTraces end Lean
fff90c766255da23d02382b6033a8bd5b44ca668
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/declaration_auto.lean
a8802506d57c341b5e70005152fdbd3b02079c2e
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
2,008
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.expr import Mathlib.Lean3Lib.init.meta.name import Mathlib.Lean3Lib.init.meta.task universes l namespace Mathlib /-- Reducibility hints are used in the convertibility checker. When trying to solve a constraint such a (f ...) =?= (g ...) where f and g are definitions, the checker has to decide which one will be unfolded. If f (g) is opaque, then g (f) is unfolded if it is also not marked as opaque, Else if f (g) is abbrev, then f (g) is unfolded if g (f) is also not marked as abbrev, Else if f and g are regular, then we unfold the one with the biggest definitional height. Otherwise both are unfolded. The arguments of the `regular` constructor are: the definitional height and the flag `self_opt`. The definitional height is by default computed by the kernel. It only takes into account other regular definitions used in a definition. When creating declarations using meta-programming, we can specify the definitional depth manually. For definitions marked as regular, we also have a hint for constraints such as (f a) =?= (f b) if self_opt == true, then checker will first try to solve (a =?= b), only if it fails, it unfolds f. Remark: the hint only affects performance. None of the hints prevent the kernel from unfolding a declaration during type checking. Remark: the reducibility_hints are not related to the attributes: reducible/irrelevance/semireducible. These attributes are used by the elaborator. The reducibility_hints are used by the kernel (and elaborator). Moreover, the reducibility_hints cannot be changed after a declaration is added to the kernel. -/ inductive reducibility_hints where | opaque : reducibility_hints | abbrev : reducibility_hints | regular : ℕ → Bool → reducibility_hints end Mathlib
91d06eb44aedc9a7da2247b316dd513d8d33b083
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/category/UniformSpace.lean
a403b98f4aeda930304019bb81c9ad13a261fa1b
[ "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
7,124
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Patrick Massot, Scott Morrison -/ import category_theory.monad.limits import topology.uniform_space.completion import topology.category.Top.basic /-! # The category of uniform spaces We construct the category of uniform spaces, show that the complete separated uniform spaces form a reflective subcategory, and hence possess all limits that uniform spaces do. TODO: show that uniform spaces actually have all limits! -/ universes u open category_theory /-- A (bundled) uniform space. -/ def UniformSpace : Type (u+1) := bundled uniform_space namespace UniformSpace /-- The information required to build morphisms for `UniformSpace`. -/ instance : unbundled_hom @uniform_continuous := ⟨@uniform_continuous_id, @uniform_continuous.comp⟩ attribute [derive [large_category, concrete_category]] UniformSpace instance : has_coe_to_sort UniformSpace Type* := bundled.has_coe_to_sort instance (x : UniformSpace) : uniform_space x := x.str /-- Construct a bundled `UniformSpace` from the underlying type and the typeclass. -/ def of (α : Type u) [uniform_space α] : UniformSpace := ⟨α⟩ instance : inhabited UniformSpace := ⟨UniformSpace.of empty⟩ @[simp] lemma coe_of (X : Type u) [uniform_space X] : (of X : Type u) = X := rfl instance (X Y : UniformSpace) : has_coe_to_fun (X ⟶ Y) (λ _, X → Y) := ⟨category_theory.functor.map (forget UniformSpace)⟩ @[simp] lemma coe_comp {X Y Z : UniformSpace} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g : X → Z) = g ∘ f := rfl @[simp] lemma coe_id (X : UniformSpace) : (𝟙 X : X → X) = id := rfl @[simp] lemma coe_mk {X Y : UniformSpace} (f : X → Y) (hf : uniform_continuous f) : ((⟨f, hf⟩ : X ⟶ Y) : X → Y) = f := rfl lemma hom_ext {X Y : UniformSpace} {f g : X ⟶ Y} : (f : X → Y) = g → f = g := subtype.eq /-- The forgetful functor from uniform spaces to topological spaces. -/ instance has_forget_to_Top : has_forget₂ UniformSpace.{u} Top.{u} := { forget₂ := { obj := λ X, Top.of X, map := λ X Y f, { to_fun := f, continuous_to_fun := uniform_continuous.continuous f.property }, }, } end UniformSpace /-- A (bundled) complete separated uniform space. -/ structure CpltSepUniformSpace := (α : Type u) [is_uniform_space : uniform_space α] [is_complete_space : complete_space α] [is_separated : separated_space α] namespace CpltSepUniformSpace instance : has_coe_to_sort CpltSepUniformSpace (Type u) := ⟨CpltSepUniformSpace.α⟩ attribute [instance] is_uniform_space is_complete_space is_separated /-- The function forgetting that a complete separated uniform spaces is complete and separated. -/ def to_UniformSpace (X : CpltSepUniformSpace) : UniformSpace := UniformSpace.of X instance complete_space (X : CpltSepUniformSpace) : complete_space ((to_UniformSpace X).α) := CpltSepUniformSpace.is_complete_space X instance separated_space (X : CpltSepUniformSpace) : separated_space ((to_UniformSpace X).α) := CpltSepUniformSpace.is_separated X /-- Construct a bundled `UniformSpace` from the underlying type and the appropriate typeclasses. -/ def of (X : Type u) [uniform_space X] [complete_space X] [separated_space X] : CpltSepUniformSpace := ⟨X⟩ @[simp] lemma coe_of (X : Type u) [uniform_space X] [complete_space X] [separated_space X] : (of X : Type u) = X := rfl instance : inhabited CpltSepUniformSpace := begin haveI : separated_space empty := separated_iff_t2.mpr (by apply_instance), exact ⟨CpltSepUniformSpace.of empty⟩ end /-- The category instance on `CpltSepUniformSpace`. -/ instance category : large_category CpltSepUniformSpace := induced_category.category to_UniformSpace /-- The concrete category instance on `CpltSepUniformSpace`. -/ instance concrete_category : concrete_category CpltSepUniformSpace := induced_category.concrete_category to_UniformSpace instance has_forget_to_UniformSpace : has_forget₂ CpltSepUniformSpace UniformSpace := induced_category.has_forget₂ to_UniformSpace end CpltSepUniformSpace namespace UniformSpace open uniform_space open CpltSepUniformSpace /-- The functor turning uniform spaces into complete separated uniform spaces. -/ noncomputable def completion_functor : UniformSpace ⥤ CpltSepUniformSpace := { obj := λ X, CpltSepUniformSpace.of (completion X), map := λ X Y f, ⟨completion.map f.1, completion.uniform_continuous_map⟩, map_id' := λ X, subtype.eq completion.map_id, map_comp' := λ X Y Z f g, subtype.eq (completion.map_comp g.property f.property).symm, }. /-- The inclusion of a uniform space into its completion. -/ def completion_hom (X : UniformSpace) : X ⟶ (forget₂ CpltSepUniformSpace UniformSpace).obj (completion_functor.obj X) := { val := (coe : X → completion X), property := completion.uniform_continuous_coe X } @[simp] lemma completion_hom_val (X : UniformSpace) (x) : (completion_hom X) x = (x : completion X) := rfl /-- The mate of a morphism from a `UniformSpace` to a `CpltSepUniformSpace`. -/ noncomputable def extension_hom {X : UniformSpace} {Y : CpltSepUniformSpace} (f : X ⟶ (forget₂ CpltSepUniformSpace UniformSpace).obj Y) : completion_functor.obj X ⟶ Y := { val := completion.extension f, property := completion.uniform_continuous_extension } @[simp] lemma extension_hom_val {X : UniformSpace} {Y : CpltSepUniformSpace} (f : X ⟶ (forget₂ _ _).obj Y) (x) : (extension_hom f) x = completion.extension f x := rfl. @[simp] lemma extension_comp_coe {X : UniformSpace} {Y : CpltSepUniformSpace} (f : to_UniformSpace (CpltSepUniformSpace.of (completion X)) ⟶ to_UniformSpace Y) : extension_hom (completion_hom X ≫ f) = f := by { apply subtype.eq, funext x, exact congr_fun (completion.extension_comp_coe f.property) x } /-- The completion functor is left adjoint to the forgetful functor. -/ noncomputable def adj : completion_functor ⊣ forget₂ CpltSepUniformSpace UniformSpace := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, completion_hom X ≫ f, inv_fun := λ f, extension_hom f, left_inv := λ f, by { dsimp, erw extension_comp_coe }, right_inv := λ f, begin apply subtype.eq, funext x, cases f, exact @completion.extension_coe _ _ _ _ _ (CpltSepUniformSpace.separated_space _) f_property _ end }, hom_equiv_naturality_left_symm' := λ X X' Y f g, begin apply hom_ext, funext x, dsimp, erw [coe_comp, ←completion.extension_map], refl, exact g.property, exact f.property, end } noncomputable instance : is_right_adjoint (forget₂ CpltSepUniformSpace UniformSpace) := ⟨completion_functor, adj⟩ noncomputable instance : reflective (forget₂ CpltSepUniformSpace UniformSpace) := {} open category_theory.limits -- TODO Once someone defines `has_limits UniformSpace`, turn this into an instance. example [has_limits.{u} UniformSpace.{u}] : has_limits.{u} CpltSepUniformSpace.{u} := has_limits_of_reflective $ forget₂ CpltSepUniformSpace UniformSpace.{u} end UniformSpace
c3f883a751cc2a172004d4b04bafc310281b6e15
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/measure/ae_disjoint.lean
992a83907378ffb5946efe8572854db996828714
[ "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
5,250
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import measure_theory.measure.measure_space_def /-! # Almost everywhere disjoint sets We say that sets `s` and `t` are `μ`-a.e. disjoint (see `measure_theory.ae_disjoint`) if their intersection has measure zero. This assumption can be used instead of `disjoint` in most theorems in measure theory. -/ open set function namespace measure_theory variables {ι α : Type*} {m : measurable_space α} (μ : measure α) /-- Two sets are said to be `μ`-a.e. disjoint if their intersection has measure zero. -/ def ae_disjoint (s t : set α) := μ (s ∩ t) = 0 variables {μ} {s t u v : set α} /-- If `s : ι → set α` is a countable family of pairwise a.e. disjoint sets, then there exists a family of measurable null sets `t i` such that `s i \ t i` are pairwise disjoint. -/ lemma exists_null_pairwise_disjoint_diff [countable ι] {s : ι → set α} (hd : pairwise (ae_disjoint μ on s)) : ∃ t : ι → set α, (∀ i, measurable_set (t i)) ∧ (∀ i, μ (t i) = 0) ∧ pairwise (disjoint on (λ i, s i \ t i)) := begin refine ⟨λ i, to_measurable μ (s i ∩ ⋃ j ∈ ({i}ᶜ : set ι), s j), λ i, measurable_set_to_measurable _ _, λ i, _, _⟩, { simp only [measure_to_measurable, inter_Union], exact (measure_bUnion_null_iff $ to_countable _).2 (λ j hj, hd _ _ (ne.symm hj)) }, { simp only [pairwise, disjoint_left, on_fun, mem_diff, not_and, and_imp, not_not], intros i j hne x hi hU hj, replace hU : x ∉ s i ∩ ⋃ j ≠ i, s j := λ h, hU (subset_to_measurable _ _ h), simp only [mem_inter_eq, mem_Union, not_and, not_exists] at hU, exact (hU hi j hne.symm hj).elim } end namespace ae_disjoint protected lemma eq (h : ae_disjoint μ s t) : μ (s ∩ t) = 0 := h @[symm] protected lemma symm (h : ae_disjoint μ s t) : ae_disjoint μ t s := by rwa [ae_disjoint, inter_comm] protected lemma symmetric : symmetric (ae_disjoint μ) := λ s t h, h.symm protected lemma comm : ae_disjoint μ s t ↔ ae_disjoint μ t s := ⟨λ h, h.symm, λ h, h.symm⟩ protected lemma _root_.disjoint.ae_disjoint (h : disjoint s t) : ae_disjoint μ s t := by rw [ae_disjoint, disjoint_iff_inter_eq_empty.1 h, measure_empty] protected lemma _root_.pairwise.ae_disjoint {f : ι → set α} (hf : pairwise (disjoint on f)) : pairwise (ae_disjoint μ on f) := hf.mono $ λ i j h, h.ae_disjoint protected lemma _root_.set.pairwise_disjoint.ae_disjoint {f : ι → set α} {s : set ι} (hf : s.pairwise_disjoint f) : s.pairwise (ae_disjoint μ on f) := hf.mono' $ λ i j h, h.ae_disjoint lemma mono_ae (h : ae_disjoint μ s t) (hu : u ≤ᵐ[μ] s) (hv : v ≤ᵐ[μ] t) : ae_disjoint μ u v := measure_mono_null_ae (hu.inter hv) h lemma mono (h : ae_disjoint μ s t) (hu : u ⊆ s) (hv : v ⊆ t) : ae_disjoint μ u v := h.mono_ae hu.eventually_le hv.eventually_le @[simp] lemma Union_left_iff [countable ι] {s : ι → set α} : ae_disjoint μ (⋃ i, s i) t ↔ ∀ i, ae_disjoint μ (s i) t := by simp only [ae_disjoint, Union_inter, measure_Union_null_iff] @[simp] lemma Union_right_iff [countable ι] {t : ι → set α} : ae_disjoint μ s (⋃ i, t i) ↔ ∀ i, ae_disjoint μ s (t i) := by simp only [ae_disjoint, inter_Union, measure_Union_null_iff] @[simp] lemma union_left_iff : ae_disjoint μ (s ∪ t) u ↔ ae_disjoint μ s u ∧ ae_disjoint μ t u := by simp [union_eq_Union, and.comm] @[simp] lemma union_right_iff : ae_disjoint μ s (t ∪ u) ↔ ae_disjoint μ s t ∧ ae_disjoint μ s u := by simp [union_eq_Union, and.comm] lemma union_left (hs : ae_disjoint μ s u) (ht : ae_disjoint μ t u) : ae_disjoint μ (s ∪ t) u := union_left_iff.mpr ⟨hs, ht⟩ lemma union_right (ht : ae_disjoint μ s t) (hu : ae_disjoint μ s u) : ae_disjoint μ s (t ∪ u) := union_right_iff.2 ⟨ht, hu⟩ lemma diff_ae_eq_left (h : ae_disjoint μ s t) : (s \ t : set α) =ᵐ[μ] s := @diff_self_inter _ s t ▸ diff_null_ae_eq_self h lemma diff_ae_eq_right (h : ae_disjoint μ s t) : (t \ s : set α) =ᵐ[μ] t := h.symm.diff_ae_eq_left lemma measure_diff_left (h : ae_disjoint μ s t) : μ (s \ t) = μ s := measure_congr h.diff_ae_eq_left lemma measure_diff_right (h : ae_disjoint μ s t) : μ (t \ s) = μ t := measure_congr h.diff_ae_eq_right /-- If `s` and `t` are `μ`-a.e. disjoint, then `s \ u` and `t` are disjoint for some measurable null set `u`. -/ lemma exists_disjoint_diff (h : ae_disjoint μ s t) : ∃ u, measurable_set u ∧ μ u = 0 ∧ disjoint (s \ u) t := ⟨to_measurable μ (s ∩ t), measurable_set_to_measurable _ _, (measure_to_measurable _).trans h, disjoint_diff.symm.mono_left (λ x hx, ⟨hx.1, λ hxt, hx.2 $ subset_to_measurable _ _ ⟨hx.1, hxt⟩⟩)⟩ lemma of_null_right (h : μ t = 0) : ae_disjoint μ s t := measure_mono_null (inter_subset_right _ _) h lemma of_null_left (h : μ s = 0) : ae_disjoint μ s t := (of_null_right h).symm end ae_disjoint lemma ae_disjoint_compl_left : ae_disjoint μ sᶜ s := (@disjoint_compl_left _ _ s).ae_disjoint lemma ae_disjoint_compl_right : ae_disjoint μ s sᶜ := (@disjoint_compl_right _ _ s).ae_disjoint end measure_theory
adfffa76744b300f46448f6c1883dc4f7bcabf74
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/algebra/big_operators.lean
2c17e27f2dad09073ba21a65740837bc7bdb1b6b
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
30,281
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 Some big operators for lists and finite sets. -/ import tactic.tauto data.list.basic data.finset import algebra.group algebra.ordered_group algebra.group_power universes u v w variables {α : Type u} {β : Type v} {γ : Type w} theorem directed.finset_le {r : α → α → Prop} [is_trans α r] {ι} (hι : nonempty ι) {f : ι → α} (D : directed r f) (s : finset ι) : ∃ z, ∀ i ∈ s, r (f i) (f z) := show ∃ z, ∀ i ∈ s.1, r (f i) (f z), from multiset.induction_on s.1 (let ⟨z⟩ := hι in ⟨z, λ _, false.elim⟩) $ λ i s ⟨j, H⟩, let ⟨k, h₁, h₂⟩ := D i j in ⟨k, λ a h, or.cases_on (multiset.mem_cons.1 h) (λ h, h.symm ▸ h₁) (λ h, trans (H _ h) h₂)⟩ theorem finset.exists_le {α : Type u} [nonempty α] [directed_order α] (s : finset α) : ∃ M, ∀ i ∈ s, i ≤ M := directed.finset_le (by apply_instance) directed_order.directed s namespace finset variables {s s₁ s₂ : finset α} {a : α} {f g : α → β} /-- `prod s f` is the product of `f x` as `x` ranges over the elements of the finite set `s`. -/ @[to_additive finset.sum] protected def prod [comm_monoid β] (s : finset α) (f : α → β) : β := (s.1.map f).prod attribute [to_additive finset.sum.equations._eqn_1] finset.prod.equations._eqn_1 @[to_additive finset.sum_eq_fold] theorem prod_eq_fold [comm_monoid β] (s : finset α) (f : α → β) : s.prod f = s.fold (*) 1 f := rfl section comm_monoid variables [comm_monoid β] @[simp, to_additive finset.sum_empty] lemma prod_empty {α : Type u} {f : α → β} : (∅:finset α).prod f = 1 := rfl @[simp, to_additive finset.sum_insert] lemma prod_insert [decidable_eq α] : a ∉ s → (insert a s).prod f = f a * s.prod f := fold_insert @[simp, to_additive finset.sum_singleton] lemma prod_singleton : (singleton a).prod f = f a := eq.trans fold_singleton $ mul_one _ @[simp] lemma prod_const_one : s.prod (λx, (1 : β)) = 1 := by simp only [finset.prod, multiset.map_const, multiset.prod_repeat, one_pow] @[simp] lemma sum_const_zero {β} {s : finset α} [add_comm_monoid β] : s.sum (λx, (0 : β)) = 0 := @prod_const_one _ (multiplicative β) _ _ attribute [to_additive finset.sum_const_zero] prod_const_one @[simp, to_additive finset.sum_image] lemma prod_image [decidable_eq α] {s : finset γ} {g : γ → α} : (∀x∈s, ∀y∈s, g x = g y → x = y) → (s.image g).prod f = s.prod (λx, f (g x)) := fold_image @[simp, to_additive sum_map] lemma prod_map (s : finset α) (e : α ↪ γ) (f : γ → β) : (s.map e).prod f = s.prod (λa, f (e a)) := by rw [finset.prod, finset.map_val, multiset.map_map]; refl @[congr, to_additive finset.sum_congr] lemma prod_congr (h : s₁ = s₂) : (∀x∈s₂, f x = g x) → s₁.prod f = s₂.prod g := by rw [h]; exact fold_congr attribute [congr] finset.sum_congr @[to_additive finset.sum_union_inter] lemma prod_union_inter [decidable_eq α] : (s₁ ∪ s₂).prod f * (s₁ ∩ s₂).prod f = s₁.prod f * s₂.prod f := fold_union_inter @[to_additive finset.sum_union] lemma prod_union [decidable_eq α] (h : s₁ ∩ s₂ = ∅) : (s₁ ∪ s₂).prod f = s₁.prod f * s₂.prod f := by rw [←prod_union_inter, h]; exact (mul_one _).symm @[to_additive finset.sum_sdiff] lemma prod_sdiff [decidable_eq α] (h : s₁ ⊆ s₂) : (s₂ \ s₁).prod f * s₁.prod f = s₂.prod f := by rw [←prod_union (sdiff_inter_self _ _), sdiff_union_of_subset h] @[to_additive finset.sum_bind] lemma prod_bind [decidable_eq α] {s : finset γ} {t : γ → finset α} : (∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅) → (s.bind t).prod f = s.prod (λx, (t x).prod f) := by haveI := classical.dec_eq γ; exact finset.induction_on s (λ _, by simp only [bind_empty, prod_empty]) (assume x s hxs ih hd, have hd' : ∀x∈s, ∀y∈s, x ≠ y → t x ∩ t y = ∅, from assume _ hx _ hy, hd _ (mem_insert_of_mem hx) _ (mem_insert_of_mem hy), have t x ∩ finset.bind s t = ∅, from eq_empty_of_forall_not_mem $ assume a, by rw [mem_inter, mem_bind]; rintro ⟨h₁, y, hys, hy₂⟩; exact eq_empty_iff_forall_not_mem.1 (hd _ (mem_insert_self _ _) _ (mem_insert_of_mem hys) (assume h, hxs (h.symm ▸ hys))) _ (mem_inter_of_mem h₁ hy₂), by simp only [bind_insert, prod_insert hxs, prod_union this, ih hd']) @[to_additive finset.sum_product] lemma prod_product {s : finset γ} {t : finset α} {f : γ×α → β} : (s.product t).prod f = s.prod (λx, t.prod $ λy, f (x, y)) := begin haveI := classical.dec_eq α, haveI := classical.dec_eq γ, rw [product_eq_bind, prod_bind (λ x hx y hy h, eq_empty_of_forall_not_mem _)], { congr, funext, exact prod_image (λ _ _ _ _ H, (prod.mk.inj H).2) }, simp only [mem_inter, mem_image], rintro ⟨_, _⟩ ⟨⟨_, _, _⟩, ⟨_, _, _⟩⟩, apply h, cc end @[to_additive finset.sum_sigma] lemma prod_sigma {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} {f : sigma σ → β} : (s.sigma t).prod f = s.prod (λa, (t a).prod $ λs, f ⟨a, s⟩) := by haveI := classical.dec_eq α; haveI := (λ a, classical.dec_eq (σ a)); exact calc (s.sigma t).prod f = (s.bind (λa, (t a).image (λs, sigma.mk a s))).prod f : by rw sigma_eq_bind ... = s.prod (λa, ((t a).image (λs, sigma.mk a s)).prod f) : prod_bind $ assume a₁ ha a₂ ha₂ h, eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_image]; rintro ⟨_, _⟩ ⟨⟨_, _, _⟩, ⟨_, _, _⟩⟩; apply h; cc ... = (s.prod $ λa, (t a).prod $ λs, f ⟨a, s⟩) : prod_congr rfl $ λ _ _, prod_image $ λ _ _ _ _ _, by cc @[to_additive finset.sum_image'] lemma prod_image' [decidable_eq α] {s : finset γ} {g : γ → α} (h : γ → β) (eq : ∀c∈s, f (g c) = (s.filter (λc', g c' = g c)).prod h) : (s.image g).prod f = s.prod h := begin letI := classical.dec_eq γ, rw [← image_bind_filter_eq s g] {occs := occurrences.pos [2]}, rw [finset.prod_bind], { refine finset.prod_congr rfl (assume a ha, _), rcases finset.mem_image.1 ha with ⟨b, hb, rfl⟩, exact eq b hb }, assume a₀ _ a₁ _ ne, refine disjoint_iff_inter_eq_empty.1 (disjoint_iff_ne.2 _), assume c₀ h₀ c₁ h₁, rcases mem_filter.1 h₀ with ⟨h₀, rfl⟩, rcases mem_filter.1 h₁ with ⟨h₁, rfl⟩, exact mt (congr_arg g) ne end @[to_additive finset.sum_add_distrib] lemma prod_mul_distrib : s.prod (λx, f x * g x) = s.prod f * s.prod g := eq.trans (by rw one_mul; refl) fold_op_distrib @[to_additive finset.sum_comm] lemma prod_comm [decidable_eq γ] {s : finset γ} {t : finset α} {f : γ → α → β} : s.prod (λx, t.prod $ f x) = t.prod (λy, s.prod $ λx, f x y) := finset.induction_on s (by simp only [prod_empty, prod_const_one]) $ λ _ _ H ih, by simp only [prod_insert H, prod_mul_distrib, ih] lemma prod_hom [comm_monoid γ] (g : β → γ) [is_monoid_hom g] : s.prod (λx, g (f x)) = g (s.prod f) := eq.trans (by rw is_monoid_hom.map_one g; refl) (fold_hom $ is_monoid_hom.map_mul g) @[to_additive finset.sum_hom_rel] lemma prod_hom_rel [comm_monoid γ] {r : β → γ → Prop} {f : α → β} {g : α → γ} {s : finset α} (h₁ : r 1 1) (h₂ : ∀a b c, r b c → r (f a * b) (g a * c)) : r (s.prod f) (s.prod g) := begin letI := classical.dec_eq α, refine finset.induction_on s h₁ (assume a s has ih, _), rw [prod_insert has, prod_insert has], exact h₂ a (s.prod f) (s.prod g) ih, end @[to_additive finset.sum_subset] lemma prod_subset (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → f x = 1) : s₁.prod f = s₂.prod f := by haveI := classical.dec_eq α; exact have (s₂ \ s₁).prod f = (s₂ \ s₁).prod (λx, 1), from prod_congr rfl $ by simpa only [mem_sdiff, and_imp], by rw [←prod_sdiff h]; simp only [this, prod_const_one, one_mul] @[to_additive sum_filter] lemma prod_filter (p : α → Prop) [decidable_pred p] (f : α → β) : (s.filter p).prod f = s.prod (λa, if p a then f a else 1) := calc (s.filter p).prod f = (s.filter p).prod (λa, if p a then f a else 1) : prod_congr rfl (assume a h, by rw [if_pos (mem_filter.1 h).2]) ... = s.prod (λa, if p a then f a else 1) : begin refine prod_subset (filter_subset s) (assume x hs h, _), rw [mem_filter, not_and] at h, exact if_neg (h hs) end @[to_additive finset.sum_eq_single] lemma prod_eq_single {s : finset α} {f : α → β} (a : α) (h₀ : ∀b∈s, b ≠ a → f b = 1) (h₁ : a ∉ s → f a = 1) : s.prod f = f a := by haveI := classical.dec_eq α; from classical.by_cases (assume : a ∈ s, calc s.prod f = ({a} : finset α).prod f : begin refine (prod_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { simpa only [mem_singleton] } end ... = f a : prod_singleton) (assume : a ∉ s, (prod_congr rfl $ λ b hb, h₀ b hb $ by rintro rfl; cc).trans $ prod_const_one.trans (h₁ this).symm) @[to_additive finset.sum_attach] lemma prod_attach {f : α → β} : s.attach.prod (λx, f x.val) = s.prod f := by haveI := classical.dec_eq α; exact calc s.attach.prod (λx, f x.val) = ((s.attach).image subtype.val).prod f : by rw [prod_image]; exact assume x _ y _, subtype.eq ... = _ : by rw [attach_image_val] @[to_additive finset.sum_bij] lemma prod_bij {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (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.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = s.attach.prod (λx, f x.val) : prod_attach.symm ... = s.attach.prod (λx, g (i x.1 x.2)) : prod_congr rfl $ assume x hx, h _ _ ... = (s.attach.image $ λx:{x // x ∈ s}, i x.1 x.2).prod g : (prod_image $ assume (a₁:{x // x ∈ s}) _ a₂ _ eq, subtype.eq $ i_inj a₁.1 a₂.1 a₁.2 a₂.2 eq).symm ... = t.prod g : prod_subset (by simp only [subset_iff, mem_image, mem_attach]; rintro _ ⟨⟨_, _⟩, _, rfl⟩; solve_by_elim) (assume b hb hb1, false.elim $ hb1 $ by rcases i_surj b hb with ⟨a, ha, rfl⟩; exact mem_image.2 ⟨⟨_, _⟩, mem_attach _ _, rfl⟩) @[to_additive finset.sum_bij_ne_zero] lemma prod_bij_ne_one {s : finset α} {t : finset γ} {f : α → β} {g : γ → β} (i : Πa∈s, f a ≠ 1 → γ) (hi₁ : ∀a h₁ h₂, i a h₁ h₂ ∈ t) (hi₂ : ∀a₁ a₂ h₁₁ h₁₂ h₂₁ h₂₂, i a₁ h₁₁ h₁₂ = i a₂ h₂₁ h₂₂ → a₁ = a₂) (hi₃ : ∀b∈t, g b ≠ 1 → ∃a h₁ h₂, b = i a h₁ h₂) (h : ∀a h₁ h₂, f a = g (i a h₁ h₂)) : s.prod f = t.prod g := by haveI := classical.prop_decidable; exact calc s.prod f = (s.filter $ λx, f x ≠ 1).prod f : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro).symm ... = (t.filter $ λx, g x ≠ 1).prod g : prod_bij (assume a ha, i a (mem_filter.mp ha).1 (mem_filter.mp ha).2) (assume a ha, (mem_filter.mp ha).elim $ λh₁ h₂, mem_filter.mpr ⟨hi₁ a h₁ h₂, λ hg, h₂ (hg ▸ h a h₁ h₂)⟩) (assume a ha, (mem_filter.mp ha).elim $ h a) (assume a₁ a₂ ha₁ ha₂, (mem_filter.mp ha₁).elim $ λha₁₁ ha₁₂, (mem_filter.mp ha₂).elim $ λha₂₁ ha₂₂, hi₂ a₁ a₂ _ _ _ _) (assume b hb, (mem_filter.mp hb).elim $ λh₁ h₂, let ⟨a, ha₁, ha₂, eq⟩ := hi₃ b h₁ h₂ in ⟨a, mem_filter.mpr ⟨ha₁, ha₂⟩, eq⟩) ... = t.prod g : (prod_subset (filter_subset _) $ by simp only [not_imp_comm, mem_filter]; exact λ _, and.intro) @[to_additive finset.exists_ne_zero_of_sum_ne_zero] lemma exists_ne_one_of_prod_ne_one : s.prod f ≠ 1 → ∃a∈s, f a ≠ 1 := by haveI := classical.dec_eq α; exact finset.induction_on s (λ H, (H rfl).elim) (assume a s has ih h, classical.by_cases (assume ha : f a = 1, let ⟨a, ha, hfa⟩ := ih (by rwa [prod_insert has, ha, one_mul] at h) in ⟨a, mem_insert_of_mem ha, hfa⟩) (assume hna : f a ≠ 1, ⟨a, mem_insert_self _ _, hna⟩)) @[to_additive finset.sum_range_succ] lemma prod_range_succ (f : ℕ → β) (n : ℕ) : (range (nat.succ n)).prod f = f n * (range n).prod f := by rw [range_succ, prod_insert not_mem_range_self] lemma prod_range_succ' (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).prod f = (range n).prod (f ∘ nat.succ) * f 0 | 0 := (prod_range_succ _ _).trans $ mul_comm _ _ | (n + 1) := by rw [prod_range_succ (λ m, f (nat.succ m)), mul_assoc, ← prod_range_succ']; exact prod_range_succ _ _ @[simp] lemma prod_const (b : β) : s.prod (λ a, b) = b ^ s.card := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by rw [prod_insert has, card_insert_of_not_mem has, pow_succ, ih]) lemma prod_pow (s : finset α) (n : ℕ) (f : α → β) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [_root_.mul_pow] {contextual := tt}) lemma prod_nat_pow (s : finset α) (n : ℕ) (f : α → ℕ) : s.prod (λ x, f x ^ n) = s.prod f ^ n := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (by simp [nat.mul_pow] {contextual := tt}) @[to_additive finset.sum_involution] lemma prod_involution {s : finset α} {f : α → β} : ∀ (g : Π a ∈ s, α) (h₁ : ∀ a ha, f a * f (g a ha) = 1) (h₂ : ∀ a ha, f a ≠ 1 → g a ha ≠ a) (h₃ : ∀ a ha, g a ha ∈ s) (h₄ : ∀ a ha, g (g a ha) (h₃ a ha) = a), s.prod f = 1 := by haveI := classical.dec_eq α; haveI := classical.dec_eq β; exact finset.strong_induction_on s (λ s ih g h₁ h₂ h₃ h₄, if hs : s = ∅ then hs.symm ▸ rfl else let ⟨x, hx⟩ := exists_mem_of_ne_empty hs in have hmem : ∀ y ∈ (s.erase x).erase (g x hx), y ∈ s, from λ y hy, (mem_of_mem_erase (mem_of_mem_erase hy)), have g_inj : ∀ {x hx y hy}, g x hx = g y hy → x = y, from λ x hx y hy h, by rw [← h₄ x hx, ← h₄ y hy]; simp [h], have ih': (erase (erase s x) (g x hx)).prod f = (1 : β) := ih ((s.erase x).erase (g x hx)) ⟨subset.trans (erase_subset _ _) (erase_subset _ _), λ h, not_mem_erase (g x hx) (s.erase x) (h (h₃ x hx))⟩ (λ y hy, g y (hmem y hy)) (λ y hy, h₁ y (hmem y hy)) (λ y hy, h₂ y (hmem y hy)) (λ y hy, mem_erase.2 ⟨λ (h : g y _ = g x hx), by simpa [g_inj h] using hy, mem_erase.2 ⟨λ (h : g y _ = x), have y = g x hx, from h₄ y (hmem y hy) ▸ by simp [h], by simpa [this] using hy, h₃ y (hmem y hy)⟩⟩) (λ y hy, h₄ y (hmem y hy)), if hx1 : f x = 1 then ih' ▸ eq.symm (prod_subset hmem (λ y hy hy₁, have y = x ∨ y = g x hx, by simp [hy] at hy₁; tauto, this.elim (λ h, h.symm ▸ hx1) (λ h, h₁ x hx ▸ h ▸ hx1.symm ▸ (one_mul _).symm))) else by rw [← insert_erase hx, prod_insert (not_mem_erase _ _), ← insert_erase (mem_erase.2 ⟨h₂ x hx hx1, h₃ x hx⟩), prod_insert (not_mem_erase _ _), ih', mul_one, h₁ x hx]) @[to_additive finset.sum_eq_zero] lemma prod_eq_one [comm_monoid β] {f : α → β} {s : finset α} (h : ∀x∈s, f x = 1) : s.prod f = 1 := calc s.prod f = s.prod (λx, 1) : finset.prod_congr rfl h ... = 1 : finset.prod_const_one end comm_monoid lemma sum_hom [add_comm_monoid β] [add_comm_monoid γ] (g : β → γ) [is_add_monoid_hom g] : s.sum (λx, g (f x)) = g (s.sum f) := eq.trans (by rw is_add_monoid_hom.map_zero g; refl) (fold_hom $ is_add_monoid_hom.map_add g) attribute [to_additive finset.sum_hom] prod_hom lemma sum_smul [add_comm_monoid β] (s : finset α) (n : ℕ) (f : α → β) : s.sum (λ x, add_monoid.smul n (f x)) = add_monoid.smul n (s.sum f) := @prod_pow _ (multiplicative β) _ _ _ _ attribute [to_additive finset.sum_smul] prod_pow @[simp] lemma sum_const [add_comm_monoid β] (b : β) : s.sum (λ a, b) = add_monoid.smul s.card b := @prod_const _ (multiplicative β) _ _ _ attribute [to_additive finset.sum_const] prod_const lemma sum_range_succ' [add_comm_monoid β] (f : ℕ → β) : ∀ n : ℕ, (range (nat.succ n)).sum f = (range n).sum (f ∘ nat.succ) + f 0 := @prod_range_succ' (multiplicative β) _ _ attribute [to_additive finset.sum_range_succ'] prod_range_succ' lemma sum_nat_cast [add_comm_monoid β] [has_one β] (s : finset α) (f : α → ℕ) : ↑(s.sum f) = s.sum (λa, f a : α → β) := (sum_hom _).symm lemma le_sum_of_subadditive [add_comm_monoid α] [ordered_comm_monoid β] (f : α → β) (h_zero : f 0 = 0) (h_add : ∀x y, f (x + y) ≤ f x + f y) (s : finset γ) (g : γ → α) : f (s.sum g) ≤ s.sum (λc, f (g c)) := begin refine le_trans (multiset.le_sum_of_subadditive f h_zero h_add _) _, rw [multiset.map_map], refl end lemma abs_sum_le_sum_abs [discrete_linear_ordered_field α] {f : β → α} {s : finset β} : abs (s.sum f) ≤ s.sum (λa, abs (f a)) := le_sum_of_subadditive _ abs_zero abs_add s f section comm_group variables [comm_group β] @[simp, to_additive finset.sum_neg_distrib] lemma prod_inv_distrib : s.prod (λx, (f x)⁻¹) = (s.prod f)⁻¹ := prod_hom has_inv.inv end comm_group @[simp] theorem card_sigma {σ : α → Type*} (s : finset α) (t : Π a, finset (σ a)) : card (s.sigma t) = s.sum (λ a, card (t a)) := multiset.card_sigma _ _ lemma card_bind [decidable_eq β] {s : finset α} {t : α → finset β} (h : ∀ x ∈ s, ∀ y ∈ s, x ≠ y → t x ∩ t y = ∅) : (s.bind t).card = s.sum (λ u, card (t u)) := calc (s.bind t).card = (s.bind t).sum (λ _, 1) : by simp ... = s.sum (λ a, (t a).sum (λ _, 1)) : finset.sum_bind h ... = s.sum (λ u, card (t u)) : by simp lemma card_bind_le [decidable_eq β] {s : finset α} {t : α → finset β} : (s.bind t).card ≤ s.sum (λ a, (t a).card) := by haveI := classical.dec_eq α; exact finset.induction_on s (by simp) (λ a s has ih, calc ((insert a s).bind t).card ≤ (t a).card + (s.bind t).card : by rw bind_insert; exact finset.card_union_le _ _ ... ≤ (insert a s).sum (λ a, card (t a)) : by rw sum_insert has; exact add_le_add_left ih _) lemma gsmul_sum [add_comm_group β] {f : α → β} {s : finset α} (z : ℤ) : gsmul z (s.sum f) = s.sum (λa, gsmul z (f a)) := (finset.sum_hom (gsmul z)).symm end finset namespace finset variables {s s₁ s₂ : finset α} {f g : α → β} {b : β} {a : α} @[simp] lemma sum_sub_distrib [add_comm_group β] : s.sum (λx, f x - g x) = s.sum f - s.sum g := sum_add_distrib.trans $ congr_arg _ sum_neg_distrib section semiring variables [semiring β] lemma sum_mul : s.sum f * b = s.sum (λx, f x * b) := (sum_hom (λx, x * b)).symm lemma mul_sum : b * s.sum f = s.sum (λx, b * f x) := (sum_hom (λx, b * x)).symm end semiring section comm_semiring variables [decidable_eq α] [comm_semiring β] lemma prod_eq_zero (ha : a ∈ s) (h : f a = 0) : s.prod f = 0 := calc s.prod f = (insert a (erase s a)).prod f : by rw insert_erase ha ... = 0 : by rw [prod_insert (not_mem_erase _ _), h, zero_mul] lemma prod_sum {δ : α → Type*} [∀a, decidable_eq (δ a)] {s : finset α} {t : Πa, finset (δ a)} {f : Πa, δ a → β} : s.prod (λa, (t a).sum (λb, f a b)) = (s.pi t).sum (λp, s.attach.prod (λx, f x.1 (p x.1 x.2))) := begin induction s using finset.induction with a s ha ih, { rw [pi_empty, sum_singleton], refl }, { have h₁ : ∀x ∈ t a, ∀y ∈ t a, ∀h : x ≠ y, image (pi.cons s a x) (pi s t) ∩ image (pi.cons s a y) (pi s t) = ∅, { assume x hx y hy h, apply eq_empty_of_forall_not_mem, simp only [mem_inter, mem_image], rintro p₁ ⟨⟨p₂, hp, eq⟩, ⟨p₃, hp₃, rfl⟩⟩, have : pi.cons s a x p₂ a (mem_insert_self _ _) = pi.cons s a y p₃ a (mem_insert_self _ _), { rw [eq] }, rw [pi.cons_same, pi.cons_same] at this, exact h this }, rw [prod_insert ha, pi_insert ha, ih, sum_mul, sum_bind h₁], refine sum_congr rfl (λ b _, _), have h₂ : ∀p₁∈pi s t, ∀p₂∈pi s t, pi.cons s a b p₁ = pi.cons s a b p₂ → p₁ = p₂, from assume p₁ h₁ p₂ h₂ eq, injective_pi_cons ha eq, rw [sum_image h₂, mul_sum], refine sum_congr rfl (λ g _, _), rw [attach_insert, prod_insert, prod_image], { simp only [pi.cons_same], congr', ext ⟨v, hv⟩, congr', exact (pi.cons_ne (by rintro rfl; exact ha hv)).symm }, { exact λ _ _ _ _, subtype.eq ∘ subtype.mk.inj }, { simp only [mem_image], rintro ⟨⟨_, hm⟩, _, rfl⟩, exact ha hm } } end end comm_semiring section integral_domain /- add integral_semi_domain to support nat and ennreal -/ variables [decidable_eq α] [integral_domain β] lemma prod_eq_zero_iff : s.prod f = 0 ↔ (∃a∈s, f a = 0) := finset.induction_on s ⟨not.elim one_ne_zero, λ ⟨_, H, _⟩, H.elim⟩ $ λ a s ha ih, by rw [prod_insert ha, mul_eq_zero_iff_eq_zero_or_eq_zero, bex_def, exists_mem_insert, ih, ← bex_def] end integral_domain section ordered_comm_monoid variables [decidable_eq α] [ordered_comm_monoid β] lemma sum_le_sum : (∀x∈s, f x ≤ g x) → s.sum f ≤ s.sum g := finset.induction_on s (λ _, le_refl _) $ assume a s ha ih h, have f a + s.sum f ≤ g a + s.sum g, from add_le_add' (h _ (mem_insert_self _ _)) (ih $ assume x hx, h _ $ mem_insert_of_mem hx), by simpa only [sum_insert ha] lemma sum_nonneg (h : ∀x∈s, 0 ≤ f x) : 0 ≤ s.sum f := le_trans (by rw [sum_const_zero]) (sum_le_sum h) lemma sum_nonpos (h : ∀x∈s, f x ≤ 0) : s.sum f ≤ 0 := le_trans (sum_le_sum h) (by rw [sum_const_zero]) lemma sum_le_sum_of_subset_of_nonneg (h : s₁ ⊆ s₂) (hf : ∀x∈s₂, x ∉ s₁ → 0 ≤ f x) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f ≤ (s₂ \ s₁).sum f + s₁.sum f : le_add_of_nonneg_left' $ sum_nonneg $ by simpa only [mem_sdiff, and_imp] ... = (s₂ \ s₁ ∪ s₁).sum f : (sum_union (sdiff_inter_self _ _)).symm ... = s₂.sum f : by rw [sdiff_union_of_subset h] lemma sum_eq_zero_iff_of_nonneg : (∀x∈s, 0 ≤ f x) → (s.sum f = 0 ↔ ∀x∈s, f x = 0) := finset.induction_on s (λ _, ⟨λ _ _, false.elim, λ _, rfl⟩) $ λ a s ha ih H, have ∀ x ∈ s, 0 ≤ f x, from λ _, H _ ∘ mem_insert_of_mem, by rw [sum_insert ha, add_eq_zero_iff' (H _ $ mem_insert_self _ _) (sum_nonneg this), forall_mem_insert, ih this] lemma single_le_sum (hf : ∀x∈s, 0 ≤ f x) {a} (h : a ∈ s) : f a ≤ s.sum f := have (singleton a).sum f ≤ s.sum f, from sum_le_sum_of_subset_of_nonneg (λ x e, (mem_singleton.1 e).symm ▸ h) (λ x h _, hf x h), by rwa sum_singleton at this end ordered_comm_monoid section canonically_ordered_monoid variables [decidable_eq α] [canonically_ordered_monoid β] [@decidable_rel β (≤)] lemma sum_le_sum_of_subset (h : s₁ ⊆ s₂) : s₁.sum f ≤ s₂.sum f := sum_le_sum_of_subset_of_nonneg h $ assume x h₁ h₂, zero_le _ lemma sum_le_sum_of_ne_zero (h : ∀x∈s₁, f x ≠ 0 → x ∈ s₂) : s₁.sum f ≤ s₂.sum f := calc s₁.sum f = (s₁.filter (λx, f x = 0)).sum f + (s₁.filter (λx, f x ≠ 0)).sum f : by rw [←sum_union, filter_union_filter_neg_eq]; apply filter_inter_filter_neg_eq ... ≤ s₂.sum f : add_le_of_nonpos_of_le' (sum_nonpos $ by simp only [mem_filter, and_imp]; exact λ _ _, le_of_eq) (sum_le_sum_of_subset $ by simpa only [subset_iff, mem_filter, and_imp]) end canonically_ordered_monoid @[simp] lemma card_pi [decidable_eq α] {δ : α → Type*} (s : finset α) (t : Π a, finset (δ a)) : (s.pi t).card = s.prod (λ a, card (t a)) := multiset.card_pi _ _ @[simp] lemma prod_range_id_eq_fact (n : ℕ) : ((range n.succ).erase 0).prod (λ x, x) = nat.fact n := calc ((range n.succ).erase 0).prod (λ x, x) = (range n).prod nat.succ : eq.symm (prod_bij (λ x _, nat.succ x) (λ a h₁, mem_erase.2 ⟨nat.succ_ne_zero _, mem_range.2 $ nat.succ_lt_succ $ by simpa using h₁⟩) (by simp) (λ _ _ _ _, nat.succ_inj) (λ b h, have b.pred.succ = b, from nat.succ_pred_eq_of_pos $ by simp [nat.pos_iff_ne_zero] at *; tauto, ⟨nat.pred b, mem_range.2 $ nat.lt_of_succ_lt_succ (by simp [*] at *), this.symm⟩)) ... = nat.fact n : by induction n; simp [*, range_succ] end finset section geom_sum open finset theorem geom_sum_mul_add [semiring α] (x : α) : ∀ (n : ℕ), ((range n).sum (λ i, (x+1)^i)) * x + 1 = (x+1)^n | 0 := by simp | (n+1) := calc (range (n + 1)).sum (λi, (x + 1) ^ i) * x + 1 = (x + 1)^n * x + (((range n).sum (λ i, (x+1)^i)) * x + 1) : by simp [range_add_one, add_mul] ... = (x + 1)^n * x + (x + 1)^n : by rw geom_sum_mul_add n ... = (x + 1) ^ (n + 1) : by simp [pow_add, mul_add] theorem geom_sum_mul [ring α] (x : α) (n : ℕ) : ((range n).sum (λ i, x^i)) * (x-1) = x^n-1 := have _ := geom_sum_mul_add (x-1) n, by rw [sub_add_cancel] at this; rw [← this, add_sub_cancel] theorem geom_sum [division_ring α] {x : α} (h : x ≠ 1) (n : ℕ) : (range n).sum (λ i, x^i) = (x^n-1)/(x-1) := have x - 1 ≠ 0, by simp [*, -sub_eq_add_neg, sub_eq_iff_eq_add] at *, by rw [← geom_sum_mul, mul_div_cancel _ this] lemma geom_sum_inv [division_ring α] {x : α} (hx1 : x ≠ 1) (hx0 : x ≠ 0) (n : ℕ) : (range n).sum (λ m, x⁻¹ ^ m) = (x - 1)⁻¹ * (x - x⁻¹ ^ n * x) := have h₁ : x⁻¹ ≠ 1, by rwa [inv_eq_one_div, ne.def, div_eq_iff_mul_eq hx0, one_mul], have h₂ : x⁻¹ - 1 ≠ 0, from mt sub_eq_zero.1 h₁, have h₃ : x - 1 ≠ 0, from mt sub_eq_zero.1 hx1, have h₄ : x * x⁻¹ ^ n = x⁻¹ ^ n * x, from nat.cases_on n (by simp) (λ _, by conv { to_rhs, rw [pow_succ', mul_assoc, inv_mul_cancel hx0, mul_one] }; rw [pow_succ, ← mul_assoc, mul_inv_cancel hx0, one_mul]), by rw [geom_sum h₁, div_eq_iff_mul_eq h₂, ← domain.mul_left_inj h₃, ← mul_assoc, ← mul_assoc, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_inv_cancel hx0, mul_assoc, h₄] end geom_sum namespace finset section gauss_sum /-- Gauss' summation formula -/ lemma sum_range_id_mul_two : ∀(n : ℕ), (finset.range n).sum (λi, i) * 2 = n * (n - 1) | 0 := rfl | 1 := rfl | ((n + 1) + 1) := begin rw [sum_range_succ, add_mul, sum_range_id_mul_two (n + 1), mul_comm, two_mul, nat.add_sub_cancel, nat.add_sub_cancel, mul_comm _ n], simp only [add_mul, one_mul, add_comm, add_assoc, add_left_comm] end /-- Gauss' summation formula -/ lemma sum_range_id (n : ℕ) : (finset.range n).sum (λi, i) = (n * (n - 1)) / 2 := by rw [← sum_range_id_mul_two n, nat.mul_div_cancel]; exact dec_trivial end gauss_sum end finset section group open list variables [group α] [group β] @[to_additive is_add_group_hom.map_sum] theorem is_group_hom.map_prod (f : α → β) [is_group_hom f] (l : list α) : f (prod l) = prod (map f l) := by induction l; simp only [*, is_mul_hom.map_mul f, is_group_hom.map_one f, prod_nil, prod_cons, map] theorem is_group_anti_hom.map_prod (f : α → β) [is_group_anti_hom f] (l : list α) : f (prod l) = prod (map f (reverse l)) := by induction l with hd tl ih; [exact is_group_anti_hom.map_one f, simp only [prod_cons, is_group_anti_hom.map_mul f, ih, reverse_cons, map_append, prod_append, map_singleton, prod_cons, prod_nil, mul_one]] theorem inv_prod : ∀ l : list α, (prod l)⁻¹ = prod (map (λ x, x⁻¹) (reverse l)) := λ l, @is_group_anti_hom.map_prod _ _ _ _ _ inv_is_group_anti_hom l -- TODO there is probably a cleaner proof of this end group section comm_group variables [comm_group α] [comm_group β] (f : α → β) [is_group_hom f] @[to_additive is_add_group_hom.multiset_sum] lemma is_group_hom.map_multiset_prod (m : multiset α) : f m.prod = (m.map f).prod := quotient.induction_on m $ assume l, by simp [is_group_hom.map_prod f l] @[to_additive is_add_group_hom.finset_sum] lemma is_group_hom.finset_prod (g : γ → α) (s : finset γ) : f (s.prod g) = s.prod (f ∘ g) := show f (s.val.map g).prod = (s.val.map (f ∘ g)).prod, by rw [is_group_hom.map_multiset_prod f]; simp end comm_group @[to_additive is_add_group_hom_finset_sum] lemma is_group_hom_finset_prod {α β γ} [group α] [comm_group β] (s : finset γ) (f : γ → α → β) [∀c, is_group_hom (f c)] : is_group_hom (λa, s.prod (λc, f c a)) := { map_mul := assume a b, by simp only [λc, is_mul_hom.map_mul (f c), finset.prod_mul_distrib] } attribute [instance] is_group_hom_finset_prod is_add_group_hom_finset_sum namespace multiset variables [decidable_eq α] @[simp] lemma to_finset_sum_count_eq (s : multiset α) : s.to_finset.sum (λa, s.count a) = s.card := multiset.induction_on s rfl (assume a s ih, calc (to_finset (a :: s)).sum (λx, count x (a :: s)) = (to_finset (a :: s)).sum (λx, (if x = a then 1 else 0) + count x s) : finset.sum_congr rfl $ λ _ _, by split_ifs; [simp only [h, count_cons_self, nat.one_add], simp only [count_cons_of_ne h, zero_add]] ... = card (a :: s) : begin by_cases a ∈ s.to_finset, { have : (to_finset s).sum (λx, ite (x = a) 1 0) = (finset.singleton a).sum (λx, ite (x = a) 1 0), { apply (finset.sum_subset _ _).symm, { intros _ H, rwa mem_singleton.1 H }, { exact λ _ _ H, if_neg (mt finset.mem_singleton.2 H) } }, rw [to_finset_cons, finset.insert_eq_of_mem h, finset.sum_add_distrib, ih, this, finset.sum_singleton, if_pos rfl, add_comm, card_cons] }, { have ha : a ∉ s, by rwa mem_to_finset at h, have : (to_finset s).sum (λx, ite (x = a) 1 0) = (to_finset s).sum (λx, 0), from finset.sum_congr rfl (λ x hx, if_neg $ by rintro rfl; cc), rw [to_finset_cons, finset.sum_insert h, if_pos rfl, finset.sum_add_distrib, this, finset.sum_const_zero, ih, count_eq_zero_of_not_mem ha, zero_add, add_comm, card_cons] } end) end multiset
9e6a829977769ddbfc543f997a2db0b75a5f2cba
4fa161becb8ce7378a709f5992a594764699e268
/src/data/set/disjointed.lean
7d74d461923ecaaba3cc37fd0d2d7e9e36b4a043
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
4,116
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 Disjointed sets -/ import data.set.lattice import tactic.wlog open set classical open_locale classical universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {s t u : set α} /-- A relation `p` holds pairwise if `p i j` for all `i ≠ j`. -/ def pairwise {α : Type*} (p : α → α → Prop) := ∀i j, i ≠ j → p i j theorem set.pairwise_on.on_injective {s : set α} {r : α → α → Prop} (hs : pairwise_on s r) {f : β → α} (hf : function.injective f) (hfs : ∀ x, f x ∈ s) : pairwise (r on f) := λ i j hij, hs _ (hfs i) _ (hfs j) (hf.ne hij) theorem pairwise_on_bool {r} (hr : symmetric r) {a b : α} : pairwise (r on (λ c, cond c a b)) ↔ r a b := by simp [pairwise, bool.forall_bool, function.on_fun]; exact and_iff_right_of_imp (@hr _ _) theorem pairwise_disjoint_on_bool [semilattice_inf_bot α] {a b : α} : pairwise (disjoint on (λ c, cond c a b)) ↔ disjoint a b := pairwise_on_bool $ λ _ _, disjoint.symm theorem pairwise.pairwise_on {p : α → α → Prop} (h : pairwise p) (s : set α) : s.pairwise_on p := λ x hx y hy, h x y namespace set /-- If `f : ℕ → set α` is a sequence of sets, then `disjointed f` is the sequence formed with each set subtracted from the later ones in the sequence, to form a disjoint sequence. -/ def disjointed (f : ℕ → set α) (n : ℕ) : set α := f n ∩ (⋂i<n, - f i) lemma disjoint_disjointed {f : ℕ → set α} : pairwise (disjoint on disjointed f) := λ i j h, begin wlog h' : i ≤ j; [skip, {revert a, exact (this h.symm).symm}], rintro a ⟨⟨h₁, _⟩, h₂, h₃⟩, simp at h₃, exact h₃ _ (lt_of_le_of_ne h' h) h₁ end lemma disjoint_disjointed' {f : ℕ → set α} : ∀ i j, i ≠ j → (disjointed f i) ∩ (disjointed f j) = ∅ := begin assume i j hij, have := @disjoint_disjointed _ f i j hij, rw [function.on_fun, disjoint_iff] at this, exact this end lemma disjointed_subset {f : ℕ → set α} {n : ℕ} : disjointed f n ⊆ f n := inter_subset_left _ _ lemma Union_lt_succ {f : ℕ → set α} {n} : (⋃i < nat.succ n, f i) = f n ∪ (⋃i < n, f i) := ext $ λ a, by simp [nat.lt_succ_iff_lt_or_eq, or_and_distrib_right, exists_or_distrib, or_comm] lemma Inter_lt_succ {f : ℕ → set α} {n} : (⋂i < nat.succ n, f i) = f n ∩ (⋂i < n, f i) := ext $ λ a, by simp [nat.lt_succ_iff_lt_or_eq, or_imp_distrib, forall_and_distrib, and_comm] lemma Union_disjointed {f : ℕ → set α} : (⋃n, disjointed f n) = (⋃n, f n) := subset.antisymm (Union_subset_Union $ assume i, inter_subset_left _ _) $ assume x h, have ∃n, x ∈ f n, from mem_Union.mp h, have hn : ∀ (i : ℕ), i < nat.find this → x ∉ f i, from assume i, nat.find_min this, mem_Union.mpr ⟨nat.find this, nat.find_spec this, by simp; assumption⟩ lemma disjointed_induct {f : ℕ → set α} {n : ℕ} {p : set α → Prop} (h₁ : p (f n)) (h₂ : ∀t i, p t → p (t \ f i)) : p (disjointed f n) := begin rw disjointed, generalize_hyp : f n = t at h₁ ⊢, induction n, case nat.zero { simp [nat.not_lt_zero, h₁] }, case nat.succ : n ih { rw [Inter_lt_succ, inter_comm (-f n), ← inter_assoc], exact h₂ _ n ih } end lemma disjointed_of_mono {f : ℕ → set α} {n : ℕ} (hf : monotone f) : disjointed f (n + 1) = f (n + 1) \ f n := have (⋂i (h : i < n + 1), -f i) = - f n, from le_antisymm (infi_le_of_le n $ infi_le_of_le (nat.lt_succ_self _) $ subset.refl _) (le_infi $ assume i, le_infi $ assume hi, compl_le_compl $ hf $ nat.le_of_succ_le_succ hi), by simp [disjointed, this, diff_eq] lemma Union_disjointed_of_mono {f : ℕ → set α} (hf : monotone f) : ∀ n : ℕ, (⋃i<n.succ, disjointed f i) = f n | 0 := by rw [Union_lt_succ]; simp [disjointed, nat.not_lt_zero] | (n+1) := by rw [Union_lt_succ, disjointed_of_mono hf, Union_disjointed_of_mono n, diff_union_self, union_eq_self_of_subset_right (hf (nat.le_succ _))] end set
e716496039d9f4b589ad2abf950e665ae797625d
6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf
/src/game/world10/level13.lean
c52f7c31dd095faa4484328158f29c279531b925
[ "Apache-2.0" ]
permissive
arolihas/natural_number_game
4f0c93feefec93b8824b2b96adff8b702b8b43ce
8e4f7b4b42888a3b77429f90cce16292bd288138
refs/heads/master
1,621,872,426,808
1,586,270,467,000
1,586,270,467,000
253,648,466
0
0
null
1,586,219,694,000
1,586,219,694,000
null
UTF-8
Lean
false
false
601
lean
import game.world10.level12 -- hide namespace mynat -- hide /- # Inequality world. ## Level 13: `not_succ_le_self` Turns out that `¬ P` is *by definition* `P → false`, so you can just start this one with `intro h` if you like. ## Pro tip: ``` conv begin to_lhs, rw hc, end, ``` is an incantation which rewrites `hc` only on the left hand side of the goal. Look carefully at the commas. -/ /- Lemma For all naturals $a$, $\operatorname{succ}(a)$ is not at most $a$. -/ theorem not_succ_le_self (a : mynat) : ¬ (succ a ≤ a) := begin [nat_num_game] end end mynat -- hide
9caadb0856aef5cff70a65628665c5f0f98eea08
2bafba05c98c1107866b39609d15e849a4ca2bb8
/src/week_7/solutions/Part_C_back_to_Z.lean
f66ebd57e5c45828679e4894a13881a090833edb
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/formalising-mathematics
b54c83c94b5c315024ff09997fcd6b303892a749
7cf1d51c27e2038d2804561d63c74711924044a1
refs/heads/master
1,651,267,046,302
1,638,888,459,000
1,638,888,459,000
331,592,375
284
24
Apache-2.0
1,669,593,705,000
1,611,224,849,000
Lean
UTF-8
Lean
false
false
1,829
lean
import week_7.solutions.Part_A_quotients import week_7.solutions.Part_B_universal_property /- # `Z ≃ ℤ` Let's use the previous parts to show that Z and ℤ are isomorphic. -/ -- Let's define pℤ to be the usual subtraction function ℕ² → ℤ def pℤ (ab : N2) : ℤ := (ab.1 : ℤ) - ab.2 @[simp] lemma pℤ_def (a b : ℕ) : pℤ (a, b) = (a : ℤ) - b := rfl -- Start with `intro z, apply int.induction_on z` to prove this. theorem pℤsurj : function.surjective pℤ := begin intro z, apply int.induction_on z, { use (0, 0), simp, }, { rintro i ⟨⟨a, b⟩, h⟩, use ⟨a + 1, b⟩, rw [←h], simp, ring }, { rintro i ⟨⟨a, b⟩, h⟩, use ⟨a, b + 1⟩, rw [←h], simp, ring } end -- The fibres of pℤ are equivalence classes. theorem pℤequiv (ab cd : N2) : ab ≈ cd ↔ pℤ ab = pℤ cd := begin cases ab with a b, cases cd with c d, split; { simp, intros, linarith }, end -- It's helpful to have a random one-sided inverse coming from surjectivity noncomputable def invp : ℤ → N2 := λ z, classical.some (pℤsurj z) -- Here's the proof that it is an inverse. @[simp] theorem invp_inv (z : ℤ) : pℤ (invp z) = z := classical.some_spec (pℤsurj z) -- Now we can prove that ℤ and pℤ are universal. theorem int_is_universal : is_universal ℤ pℤ := begin split, { rintros ⟨a, b⟩ ⟨c, d⟩, rw [N2.equiv_def, pℤ], simp, intros, linarith }, { intros T p h, use (λ z, p (invp z)), split, { ext ab, simp, apply h, rw pℤequiv, simp }, { intros k hk, ext z, rw [hk, function.comp], simp } }, end -- and now we can prove they're in bijection noncomputable example : ℤ ≃ Z := universal_equiv_quotient _ _ _ int_is_universal
8c9788dca0c055b5ce63555e0a31cb4c8c43bc85
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/run/local_notation.lean
30e4d7dc184c0963207d91ed4f141e87c70cf2d6
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
147
lean
section variables {A : Type} variables f : A → A → A local infixl `+++`:10 := f variables a b c : A check f a b check a +++ b end
69cb9a0d4e64d573d310eddec9a1266835db20c2
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/measure_theory/measure/complex.lean
67354eebd6fd30f81120612022b82b8db85d91c3
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
4,466
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.measure.vector_measure /-! # Complex measure This file proves some elementary results about complex measures. In particular, we prove that a complex measure is always in the form `s + it` where `s` and `t` are signed measures. The complex measure is defined to be vector measure over `ℂ`, this definition can be found in `measure_theory.measure.vector_measure` and is known as `measure_theory.complex_measure`. ## Main definitions * `measure_theory.complex_measure.re`: obtains a signed measure `s` from a complex measure `c` such that `s i = (c i).re` for all measurable sets `i`. * `measure_theory.complex_measure.im`: obtains a signed measure `s` from a complex measure `c` such that `s i = (c i).im` for all measurable sets `i`. * `measure_theory.signed_measure.to_complex_measure`: given two signed measures `s` and `t`, `s.to_complex_measure t` provides a complex measure of the form `s + it`. * `measure_theory.complex_measure.equiv_signed_measure`: is the equivalence between the complex measures and the type of the product of the signed measures with itself. # Tags Complex measure -/ noncomputable theory open_locale classical measure_theory ennreal nnreal variables {α β : Type*} {m : measurable_space α} namespace measure_theory open vector_measure namespace complex_measure include m /-- The real part of a complex measure is a signed measure. -/ @[simps apply] def re : complex_measure α →ₗ[ℝ] signed_measure α := map_rangeₗ complex.re_clm complex.continuous_re /-- The imaginary part of a complex measure is a signed measure. -/ @[simps apply] def im : complex_measure α →ₗ[ℝ] signed_measure α := map_rangeₗ complex.im_clm complex.continuous_im /-- Given `s` and `t` signed measures, `s + it` is a complex measure-/ @[simps] def _root_.measure_theory.signed_measure.to_complex_measure (s t : signed_measure α) : complex_measure α := { measure_of' := λ i, ⟨s i, t i⟩, empty' := by rw [s.empty, t.empty]; refl, not_measurable' := λ i hi, by rw [s.not_measurable hi, t.not_measurable hi]; refl, m_Union' := λ f hf hfdisj, (complex.has_sum_iff _ _).2 ⟨s.m_Union hf hfdisj, t.m_Union hf hfdisj⟩ } lemma _root_.measure_theory.signed_measure.to_complex_measure_apply {s t : signed_measure α} {i : set α} : s.to_complex_measure t i = ⟨s i, t i⟩ := rfl lemma to_complex_measure_to_signed_measure (c : complex_measure α) : c.re.to_complex_measure c.im = c := by { ext i hi; refl } lemma _root_.measure_theory.signed_measure.re_to_complex_measure (s t : signed_measure α) : (s.to_complex_measure t).re = s := by { ext i hi, refl } lemma _root_.measure_theory.signed_measure.im_to_complex_measure (s t : signed_measure α) : (s.to_complex_measure t).im = t := by { ext i hi, refl } /-- The complex measures form an equivalence to the type of pairs of signed measures. -/ @[simps] def equiv_signed_measure : complex_measure α ≃ signed_measure α × signed_measure α := { to_fun := λ c, ⟨c.re, c.im⟩, inv_fun := λ ⟨s, t⟩, s.to_complex_measure t, left_inv := λ c, c.to_complex_measure_to_signed_measure, right_inv := λ ⟨s, t⟩, prod.mk.inj_iff.2 ⟨s.re_to_complex_measure t, s.im_to_complex_measure t⟩ } section variables {R : Type*} [semiring R] [module R ℝ] variables [topological_space R] [has_continuous_smul R ℝ] [has_continuous_smul R ℂ] /-- The complex measures form an linear isomorphism to the type of pairs of signed measures. -/ @[simps] def equiv_signed_measureₗ : complex_measure α ≃ₗ[R] signed_measure α × signed_measure α := { map_add' := λ c d, by { ext i hi; refl }, map_smul' := begin intros r c, ext i hi, { change (r • c i).re = r • (c i).re, simp [complex.smul_re] }, { ext i hi, change (r • c i).im = r • (c i).im, simp [complex.smul_im] } end, .. equiv_signed_measure } end lemma absolutely_continuous_ennreal_iff (c : complex_measure α) (μ : vector_measure α ℝ≥0∞) : c ≪ᵥ μ ↔ c.re ≪ᵥ μ ∧ c.im ≪ᵥ μ := begin split; intro h, { split; { intros i hi, simp [h hi] } }, { intros i hi, rw [← complex.re_add_im (c i), (_ : (c i).re = 0), (_ : (c i).im = 0)], exacts [by simp, h.2 hi, h.1 hi] } end end complex_measure end measure_theory
be0622116c630ee716b93124efdc54edb26939b3
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Elab/Tactic/Conv/Simp.lean
2321e7caae8aa3cb943a0df7a44f08aafd179c63
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
1,231
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, Moritz Doll -/ import Lean.Elab.Tactic.Simp import Lean.Elab.Tactic.Split import Lean.Elab.Tactic.Conv.Basic namespace Lean.Elab.Tactic.Conv open Meta def applySimpResult (result : Simp.Result) : TacticM Unit := do if result.proof?.isNone then changeLhs result.expr else updateLhs result.expr (← result.getProof) @[builtinTactic Lean.Parser.Tactic.Conv.simp] def evalSimp : Tactic := fun stx => withMainContext do let { ctx, dischargeWrapper, .. } ← mkSimpContext stx (eraseLocal := false) let lhs ← getLhs let (result, _) ← dischargeWrapper.with fun d? => simp lhs ctx (discharge? := d?) applySimpResult result @[builtinTactic Lean.Parser.Tactic.Conv.simpMatch] def evalSimpMatch : Tactic := fun _ => withMainContext do applySimpResult (← Split.simpMatch (← getLhs)) @[builtinTactic Lean.Parser.Tactic.Conv.dsimp] def evalDSimp : Tactic := fun stx => withMainContext do let { ctx, .. } ← mkSimpContext stx (eraseLocal := false) (kind := .dsimp) changeLhs (← Lean.Meta.dsimp (← getLhs) ctx).1 end Lean.Elab.Tactic.Conv
0f494fb3f93caa87dad646be0b5a337f6700a8e6
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/finLit.lean
64c1205790fb96d2bcb22d45be538405f19bc604
[ "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
358
lean
def f : Fin 2 → Nat | 0 => 5 | 1 => 45 example : f 0 = 5 := rfl example : f 1 = 45 := rfl def g : Fin 15 → Nat | 0 => 5 | 1 => 10 | 2 => 15 | 3 => 2 | 4 => 48 | 5 => 0 | 6 => 87 | 7 => 64 | 8 => 32 | 9 => 64 | 10 => 21 | 11 => 0 | 12 => 5 | 13 => 1 | 14 => 4 def h : Fin 15 → Nat | 0 => 5 | 1 => 45 | _ => 50
f19b49d96213c0c19ce5c65c7698b5f8904ddfd8
92b50235facfbc08dfe7f334827d47281471333b
/library/data/rat/order.lean
6be4c4128bc1df69988c95f1e4ed56f1bfc6dc81
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
12,860
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Adds the ordering, and instantiates the rationals as an ordered field. -/ import data.int algebra.ordered_field .basic open quot eq.ops /- the ordering on representations -/ namespace prerat section int_notation open int variables {a b : prerat} definition pos (a : prerat) : Prop := num a > 0 definition nonneg (a : prerat) : Prop := num a ≥ 0 theorem pos_of_int (a : ℤ) : pos (of_int a) ↔ (#int a > 0) := !iff.rfl theorem nonneg_of_int (a : ℤ) : nonneg (of_int a) ↔ (#int a ≥ 0) := !iff.rfl theorem pos_eq_pos_of_equiv {a b : prerat} (H1 : a ≡ b) : pos a = pos b := propext (iff.intro (num_pos_of_equiv H1) (num_pos_of_equiv H1⁻¹)) theorem nonneg_eq_nonneg_of_equiv (H : a ≡ b) : nonneg a = nonneg b := have H1 : (0 = num a) = (0 = num b), from propext (iff.intro (assume H2, eq.symm (num_eq_zero_of_equiv H H2⁻¹)) (assume H2, eq.symm (num_eq_zero_of_equiv H⁻¹ H2⁻¹))), calc nonneg a = (pos a ∨ 0 = num a) : propext !le_iff_lt_or_eq ... = (pos b ∨ 0 = num a) : pos_eq_pos_of_equiv H ... = (pos b ∨ 0 = num b) : H1 ... = nonneg b : propext !le_iff_lt_or_eq theorem nonneg_zero : nonneg zero := le.refl 0 theorem nonneg_add (H1 : nonneg a) (H2 : nonneg b) : nonneg (add a b) := show num a * denom b + num b * denom a ≥ 0, from add_nonneg (mul_nonneg H1 (le_of_lt (denom_pos b))) (mul_nonneg H2 (le_of_lt (denom_pos a))) theorem nonneg_antisymm (H1 : nonneg a) (H2 : nonneg (neg a)) : a ≡ zero := have H3 : num a = 0, from le.antisymm (nonpos_of_neg_nonneg H2) H1, equiv_zero_of_num_eq_zero H3 theorem nonneg_total (a : prerat) : nonneg a ∨ nonneg (neg a) := or.elim (le.total 0 (num a)) (assume H : 0 ≤ num a, or.inl H) (assume H : 0 ≥ num a, or.inr (neg_nonneg_of_nonpos H)) theorem nonneg_of_pos (H : pos a) : nonneg a := le_of_lt H theorem ne_zero_of_pos (H : pos a) : ¬ a ≡ zero := assume H', ne_of_gt H (num_eq_zero_of_equiv_zero H') theorem pos_of_nonneg_of_ne_zero (H1 : nonneg a) (H2 : ¬ a ≡ zero) : pos a := have H3 : num a ≠ 0, from assume H' : num a = 0, H2 (equiv_zero_of_num_eq_zero H'), lt_of_le_of_ne H1 (ne.symm H3) theorem nonneg_mul (H1 : nonneg a) (H2 : nonneg b) : nonneg (mul a b) := mul_nonneg H1 H2 theorem pos_mul (H1 : pos a) (H2 : pos b) : pos (mul a b) := mul_pos H1 H2 end int_notation end prerat local attribute prerat.setoid [instance] /- The ordering on the rationals. The definitions of pos and nonneg are kept private, because they are only meant for internal use. Users should use a > 0 and a ≥ 0 instead of pos and nonneg. -/ namespace rat variables {a b c : ℚ} /- transfer properties of pos and nonneg -/ private definition pos (a : ℚ) : Prop := quot.lift prerat.pos @prerat.pos_eq_pos_of_equiv a private definition nonneg (a : ℚ) : Prop := quot.lift prerat.nonneg @prerat.nonneg_eq_nonneg_of_equiv a private theorem pos_of_int (a : ℤ) : (#int a > 0) ↔ pos (of_int a) := prerat.pos_of_int a private theorem nonneg_of_int (a : ℤ) : (#int a ≥ 0) ↔ nonneg (of_int a) := prerat.nonneg_of_int a private theorem nonneg_zero : nonneg 0 := prerat.nonneg_zero private theorem nonneg_add : nonneg a → nonneg b → nonneg (a + b) := quot.induction_on₂ a b @prerat.nonneg_add private theorem nonneg_antisymm : nonneg a → nonneg (-a) → a = 0 := quot.induction_on a (take u, assume H1 H2, quot.sound (prerat.nonneg_antisymm H1 H2)) private theorem nonneg_total (a : ℚ) : nonneg a ∨ nonneg (-a) := quot.induction_on a @prerat.nonneg_total private theorem nonneg_of_pos : pos a → nonneg a := quot.induction_on a @prerat.nonneg_of_pos private theorem ne_zero_of_pos : pos a → a ≠ 0 := quot.induction_on a (take u, assume H1 H2, prerat.ne_zero_of_pos H1 (quot.exact H2)) private theorem pos_of_nonneg_of_ne_zero : nonneg a → ¬ a = 0 → pos a := quot.induction_on a (take u, assume H1 : nonneg ⟦u⟧, assume H2 : ⟦u⟧ ≠ (rat.of_num 0), have H3 : ¬ (prerat.equiv u prerat.zero), from assume H, H2 (quot.sound H), prerat.pos_of_nonneg_of_ne_zero H1 H3) private theorem nonneg_mul : nonneg a → nonneg b → nonneg (a * b) := quot.induction_on₂ a b @prerat.nonneg_mul private theorem pos_mul : pos a → pos b → pos (a * b) := quot.induction_on₂ a b @prerat.pos_mul private definition decidable_pos (a : ℚ) : decidable (pos a) := quot.rec_on_subsingleton a (take u, int.decidable_lt 0 (prerat.num u)) /- define order in terms of pos and nonneg -/ definition lt (a b : ℚ) : Prop := pos (b - a) definition le (a b : ℚ) : Prop := nonneg (b - a) definition gt [reducible] (a b : ℚ) := lt b a definition ge [reducible] (a b : ℚ) := le b a infix [priority rat.prio] < := rat.lt infix [priority rat.prio] <= := rat.le infix [priority rat.prio] ≤ := rat.le infix [priority rat.prio] >= := rat.ge infix [priority rat.prio] ≥ := rat.ge infix [priority rat.prio] > := rat.gt theorem of_int_lt_of_int (a b : ℤ) : of_int a < of_int b ↔ (#int a < b) := iff.symm (calc (#int a < b) ↔ (#int b - a > 0) : iff.symm !int.sub_pos_iff_lt ... ↔ pos (of_int (#int b - a)) : iff.symm !pos_of_int ... ↔ pos (of_int b - of_int a) : !of_int_sub ▸ iff.rfl ... ↔ of_int a < of_int b : iff.rfl) theorem of_int_le_of_int (a b : ℤ) : of_int a ≤ of_int b ↔ (#int a ≤ b) := iff.symm (calc (#int a ≤ b) ↔ (#int b - a ≥ 0) : iff.symm !int.sub_nonneg_iff_le ... ↔ nonneg (of_int (#int b - a)) : iff.symm !nonneg_of_int ... ↔ nonneg (of_int b - of_int a) : !of_int_sub ▸ iff.rfl ... ↔ of_int a ≤ of_int b : iff.rfl) theorem of_int_pos (a : ℤ) : (of_int a > 0) ↔ (#int a > 0) := !of_int_lt_of_int theorem of_int_nonneg (a : ℤ) : (of_int a ≥ 0) ↔ (#int a ≥ 0) := !of_int_le_of_int theorem of_nat_lt_of_nat (a b : ℕ) : of_nat a < of_nat b ↔ (#nat a < b) := by rewrite [*of_nat_eq, propext !of_int_lt_of_int]; apply int.of_nat_lt_of_nat theorem of_nat_le_of_nat (a b : ℕ) : of_nat a ≤ of_nat b ↔ (#nat a ≤ b) := by rewrite [*of_nat_eq, propext !of_int_le_of_int]; apply int.of_nat_le_of_nat theorem of_nat_pos (a : ℕ) : (of_nat a > 0) ↔ (#nat a > nat.zero) := !of_nat_lt_of_nat theorem of_nat_nonneg (a : ℕ) : (of_nat a ≥ 0) := iff.mp' !of_nat_le_of_nat !nat.zero_le theorem le.refl (a : ℚ) : a ≤ a := by rewrite [↑rat.le, sub_self]; apply nonneg_zero theorem le.trans (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c := assert H3 : nonneg (c - b + (b - a)), from nonneg_add H2 H1, begin revert H3, rewrite [↑rat.sub, add.assoc, neg_add_cancel_left], intro H3, apply H3 end theorem le.antisymm (H1 : a ≤ b) (H2 : b ≤ a) : a = b := have H3 : nonneg (-(a - b)), from !neg_sub⁻¹ ▸ H1, have H4 : a - b = 0, from nonneg_antisymm H2 H3, eq_of_sub_eq_zero H4 theorem le.total (a b : ℚ) : a ≤ b ∨ b ≤ a := or.elim (nonneg_total (b - a)) (assume H, or.inl H) (assume H, or.inr (!neg_sub ▸ H)) theorem le.by_cases {P : Prop} (a b : ℚ) (H : a ≤ b → P) (H2 : b ≤ a → P) : P := or.elim (!rat.le.total) H H2 theorem lt_iff_le_and_ne (a b : ℚ) : a < b ↔ a ≤ b ∧ a ≠ b := iff.intro (assume H : a < b, have H1 : b - a ≠ 0, from ne_zero_of_pos H, have H2 : a ≠ b, from ne.symm (assume H', H1 (H' ▸ !sub_self)), and.intro (nonneg_of_pos H) H2) (assume H : a ≤ b ∧ a ≠ b, obtain aleb aneb, from H, have H1 : b - a ≠ 0, from (assume H', aneb (eq_of_sub_eq_zero H')⁻¹), pos_of_nonneg_of_ne_zero aleb H1) theorem le_iff_lt_or_eq (a b : ℚ) : a ≤ b ↔ a < b ∨ a = b := iff.intro (assume H : a ≤ b, decidable.by_cases (assume H1 : a = b, or.inr H1) (assume H1 : a ≠ b, or.inl (iff.mp' !lt_iff_le_and_ne (and.intro H H1)))) (assume H : a < b ∨ a = b, or.elim H (assume H1 : a < b, and.left (iff.mp !lt_iff_le_and_ne H1)) (assume H1 : a = b, H1 ▸ !le.refl)) theorem to_nonneg : a ≥ 0 → nonneg a := by intros; rewrite -sub_zero; eassumption theorem add_le_add_left (H : a ≤ b) (c : ℚ) : c + a ≤ c + b := have H1 : c + b - (c + a) = b - a, by rewrite [↑sub, neg_add, -add.assoc, add.comm c, add_neg_cancel_right], show nonneg (c + b - (c + a)), from H1⁻¹ ▸ H theorem mul_nonneg (H1 : a ≥ (0 : ℚ)) (H2 : b ≥ (0 : ℚ)) : a * b ≥ (0 : ℚ) := have H : nonneg (a * b), from nonneg_mul (to_nonneg H1) (to_nonneg H2), !sub_zero⁻¹ ▸ H theorem to_pos : a > 0 → pos a := by intros; rewrite -sub_zero; eassumption theorem mul_pos (H1 : a > (0 : ℚ)) (H2 : b > (0 : ℚ)) : a * b > (0 : ℚ) := have H : pos (a * b), from pos_mul (to_pos H1) (to_pos H2), !sub_zero⁻¹ ▸ H definition decidable_lt [instance] : decidable_rel rat.lt := take a b, decidable_pos (b - a) theorem le_of_lt (H : a < b) : a ≤ b := iff.mp' !le_iff_lt_or_eq (or.inl H) theorem lt_irrefl (a : ℚ) : ¬ a < a := take Ha, let Hand := (iff.mp !lt_iff_le_and_ne) Ha in (and.right Hand) rfl theorem not_le_of_gt (H : a < b) : ¬ b ≤ a := assume Hba, let Heq := le.antisymm (le_of_lt H) Hba in !lt_irrefl (Heq ▸ H) theorem lt_of_lt_of_le (Hab : a < b) (Hbc : b ≤ c) : a < c := let Hab' := le_of_lt Hab in let Hac := le.trans Hab' Hbc in (iff.mp' !lt_iff_le_and_ne) (and.intro Hac (assume Heq, not_le_of_gt (Heq ▸ Hab) Hbc)) theorem lt_of_le_of_lt (Hab : a ≤ b) (Hbc : b < c) : a < c := let Hbc' := le_of_lt Hbc in let Hac := le.trans Hab Hbc' in (iff.mp' !lt_iff_le_and_ne) (and.intro Hac (assume Heq, not_le_of_gt (Heq⁻¹ ▸ Hbc) Hab)) theorem zero_lt_one : (0 : ℚ) < 1 := trivial theorem add_lt_add_left (H : a < b) (c : ℚ) : c + a < c + b := let H' := le_of_lt H in (iff.mp' (lt_iff_le_and_ne _ _)) (and.intro (add_le_add_left H' _) (take Heq, let Heq' := add_left_cancel Heq in !lt_irrefl (Heq' ▸ H))) section migrate_algebra open [classes] algebra protected definition discrete_linear_ordered_field [reducible] : algebra.discrete_linear_ordered_field rat := ⦃algebra.discrete_linear_ordered_field, rat.discrete_field, le_refl := le.refl, le_trans := @le.trans, le_antisymm := @le.antisymm, le_total := @le.total, le_of_lt := @le_of_lt, lt_irrefl := lt_irrefl, lt_of_lt_of_le := @lt_of_lt_of_le, lt_of_le_of_lt := @lt_of_le_of_lt, le_iff_lt_or_eq := @le_iff_lt_or_eq, add_le_add_left := @add_le_add_left, mul_nonneg := @mul_nonneg, mul_pos := @mul_pos, decidable_lt := @decidable_lt, zero_lt_one := zero_lt_one, add_lt_add_left := @add_lt_add_left⦄ local attribute rat.discrete_linear_ordered_field [trans-instance] local attribute rat.discrete_field [instance] definition min : ℚ → ℚ → ℚ := algebra.min definition max : ℚ → ℚ → ℚ := algebra.max definition abs : ℚ → ℚ := algebra.abs definition sign : ℚ → ℚ := algebra.sign migrate from algebra with rat replacing has_le.ge → ge, has_lt.gt → gt, sub → sub, dvd → dvd, divide → divide, max → max, min → min, abs → abs, sign → sign attribute le.trans lt.trans lt_of_lt_of_le lt_of_le_of_lt ge.trans gt.trans gt_of_gt_of_ge gt_of_ge_of_gt [trans] end migrate_algebra theorem rat_of_nat_abs (a : ℤ) : abs (of_int a) = of_nat (int.nat_abs a) := have hsimp [visible] : ∀ n : ℕ, of_int (int.neg_succ_of_nat n) = - of_nat (nat.succ n), from λ n, rfl, int.induction_on a (take b, abs_of_nonneg (!of_nat_nonneg)) (take b, by rewrite [hsimp, abs_neg, abs_of_nonneg (!of_nat_nonneg)]) definition ubound : ℚ → ℕ := λ a : ℚ, nat.succ (int.nat_abs (num a)) theorem ubound_ge (a : ℚ) : of_nat (ubound a) ≥ a := have H : abs a * abs (of_int (denom a)) = abs (of_int (num a)), from !abs_mul ▸ !mul_denom ▸ rfl, have H'' : 1 ≤ abs (of_int (denom a)), begin have J : of_int (denom a) > 0, from (iff.mp' !of_int_pos) !denom_pos, rewrite (abs_of_pos J), apply iff.mp' !of_int_le_of_int, apply denom_pos end, have H' : abs a ≤ abs (of_int (num a)), from le_of_mul_le_of_ge_one (H ▸ !le.refl) !abs_nonneg H'', calc a ≤ abs a : le_abs_self ... ≤ abs (of_int (num a)) : H' ... ≤ abs (of_int (num a)) + 1 : rat.le_add_of_nonneg_right trivial ... = of_nat (int.nat_abs (num a)) + 1 : rat_of_nat_abs ... = of_nat (nat.succ (int.nat_abs (num a))) : of_nat_add theorem ubound_pos (a : ℚ) : nat.gt (ubound a) nat.zero := !nat.succ_pos end rat
64814038c1645870efb9c53a77a76ba174eacbd6
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/tests/lean/coe6.lean
8daf489044a4a92d15b9107a842e493c46a7b6d5
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
322
lean
universe variables u structure Group := (carrier : Type u) (mul : carrier → carrier → carrier) (one : carrier) attribute [instance] definition Group_to_Type : has_coe_to_sort Group := { S := Type u, coe := λ g, g~>carrier } constant g : Group.{1} set_option pp.binder_types true #check λ a b : g, Group.mul g a b
6f90ec62f43208398f7ea0bc6c7826ee8b502b0e
842b7df4a999c5c50bbd215b8617dd705e43c2e1
/nat_num_game/src/Advanced_Addition_World/adv_add_wrld1.lean
936cf1000bbd3cf9a522d55be5039fcc73bea083
[]
no_license
Samyak-Surti/LeanCode
1c245631f74b00057d20483c8ac75916e8643b14
944eac3e5f43e2614ed246083b97fbdf24181d83
refs/heads/master
1,669,023,730,828
1,595,534,784,000
1,595,534,784,000
282,037,186
0
0
null
null
null
null
UTF-8
Lean
false
false
226
lean
theorem succ_inj' {a b : ℕ} (hs : nat.succ(a) = nat.succ(b)) : a = b := begin apply nat.succ.inj hs, end theorem succ_inj' {a b : ℕ} (hs : nat.succ(a) = nat.succ(b)) : a = b := begin exact nat.succ.inj hs, end
23951d4a348b24fbe214b1118916e168bf43382f
6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf
/src/game/world6/level3.lean
e1ca420626c28585eed6b89798b46a8102f4658c
[ "Apache-2.0" ]
permissive
arolihas/natural_number_game
4f0c93feefec93b8824b2b96adff8b702b8b43ce
8e4f7b4b42888a3b77429f90cce16292bd288138
refs/heads/master
1,621,872,426,808
1,586,270,467,000
1,586,270,467,000
253,648,466
0
0
null
1,586,219,694,000
1,586,219,694,000
null
UTF-8
Lean
false
false
2,340
lean
/- # Proposition world. ## Level 3: `have`. Say you have a whole bunch of propositions and implications between them, and your goal is to build a certain proof of a certain proposition. If it helps, you can build intermediate proofs of other propositions along the way, using the `have` command. `have q : Q := ...` is the Lean analogue of saying "We now see that we can prove $Q$, because..." in the middle of a proof. It is often not logically necessary, but on the other hand it is very convenient, for example it can save on notation, or it can break proofs up into smaller steps. In the level below, we have a proof of $P$ and we want a proof of $U$; during the proof we will construct proofs of of some of the other propositions involved. The diagram of propositions and implications looks like this pictorially: ![diagram](https://wwwf.imperial.ac.uk/~buzzard/xena/natural_number_game_images/implies_diag.jpg) and so it's clear how to deduce $U$ from $P$. Indeed, we could solve this level in one move by typing `exact l(j(h(p))),` But let us instead stroll more lazily through the level. We can start by using the `have` tactic to make a proof of $Q$: `have q := h(p),` and then we note that $j(q)$ is a proof of $T$: `have t : T := j(q),` (note how we explicitly told Lean what proposition we thought $t$ was a proof of, with that `: T` thing before the `:=`) and we could even define $u$ to be $l(t)$: `have u : U := l(t),` and then finish the level with `exact u,` . -/ /- Lemma : no-side-bar In the maze of logical implications above, if $P$ is true then so is $U$. -/ lemma maze (P Q R S T U: Prop) (p : P) (h : P → Q) (i : Q → R) (j : Q → T) (k : S → T) (l : T → U) : U := begin end /- If you solved the level using `have`, then click on the last line of your proof (you do know you can move your cursor around with the arrow keys and explore your proof, right?) and note that the local context at that point is in something like the following mess: ``` P Q R S T U : Prop, p : P, h : P → Q, i : Q → R, j : Q → T, k : S → T, l : T → U, q : Q, t : T, u : U ⊢ U ``` It was already bad enough to start with, and we added three more terms to it. In level 4 we will learn about the `apply` tactic which solves the level using another technique, without leaving so much junk behind. -/
b1c2b2c513d4a71aac46d422706e936e22d7d304
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/ring/idempotents.lean
1fd69ef91052f3996f60716e01a00c9e5298524c
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,994
lean
/- Copyright (c) 2022 Christopher Hoskin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Christopher Hoskin -/ import order.basic import algebra.group_power.basic import algebra.ring.defs import tactic.nth_rewrite /-! # Idempotents > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines idempotents for an arbitary multiplication and proves some basic results, including: * `is_idempotent_elem.mul_of_commute`: In a semigroup, the product of two commuting idempotents is an idempotent; * `is_idempotent_elem.one_sub_iff`: In a (non-associative) ring, `p` is an idempotent if and only if `1-p` is an idempotent. * `is_idempotent_elem.pow_succ_eq`: In a monoid `p ^ (n+1) = p` for `p` an idempotent and `n` a natural number. ## Tags projection, idempotent -/ variables {M N S M₀ M₁ R G G₀ : Type*} variables [has_mul M] [monoid N] [semigroup S] [mul_zero_class M₀] [mul_one_class M₁] [non_assoc_ring R] [group G] [cancel_monoid_with_zero G₀] /-- An element `p` is said to be idempotent if `p * p = p` -/ def is_idempotent_elem (p : M) : Prop := p * p = p namespace is_idempotent_elem lemma of_is_idempotent [is_idempotent M (*)] (a : M) : is_idempotent_elem a := is_idempotent.idempotent a lemma eq {p : M} (h : is_idempotent_elem p) : p * p = p := h lemma mul_of_commute {p q : S} (h : commute p q) (h₁ : is_idempotent_elem p) (h₂ : is_idempotent_elem q) : is_idempotent_elem (p * q) := by rw [is_idempotent_elem, mul_assoc, ← mul_assoc q, ← h.eq, mul_assoc p, h₂.eq, ← mul_assoc, h₁.eq] lemma zero : is_idempotent_elem (0 : M₀) := mul_zero _ lemma one : is_idempotent_elem (1 : M₁) := mul_one _ lemma one_sub {p : R} (h : is_idempotent_elem p) : is_idempotent_elem (1 - p) := by rw [is_idempotent_elem, mul_sub, mul_one, sub_mul, one_mul, h.eq, sub_self, sub_zero] @[simp] lemma one_sub_iff {p : R} : is_idempotent_elem (1 - p) ↔ is_idempotent_elem p := ⟨ λ h, sub_sub_cancel 1 p ▸ h.one_sub, is_idempotent_elem.one_sub ⟩ lemma pow {p : N} (n : ℕ) (h : is_idempotent_elem p) : is_idempotent_elem (p ^ n) := nat.rec_on n ((pow_zero p).symm ▸ one) (λ n ih, show p ^ n.succ * p ^ n.succ = p ^ n.succ, by { nth_rewrite 2 ←h.eq, rw [←sq, ←sq, ←pow_mul, ←pow_mul'] }) lemma pow_succ_eq {p : N} (n : ℕ) (h : is_idempotent_elem p) : p ^ (n + 1) = p := nat.rec_on n ((nat.zero_add 1).symm ▸ pow_one p) (λ n ih, by rw [pow_succ, ih, h.eq]) @[simp] lemma iff_eq_one {p : G} : is_idempotent_elem p ↔ p = 1 := iff.intro (λ h, mul_left_cancel ((mul_one p).symm ▸ h.eq : p * p = p * 1)) (λ h, h.symm ▸ one) @[simp] lemma iff_eq_zero_or_one {p : G₀} : is_idempotent_elem p ↔ p = 0 ∨ p = 1 := begin refine iff.intro (λ h, or_iff_not_imp_left.mpr (λ hp, _)) (λ h, h.elim (λ hp, hp.symm ▸ zero) (λ hp, hp.symm ▸ one)), exact mul_left_cancel₀ hp (h.trans (mul_one p).symm) end /-! ### Instances on `subtype is_idempotent_elem` -/ section instances instance : has_zero { p : M₀ // is_idempotent_elem p } := { zero := ⟨ 0, zero ⟩ } @[simp] lemma coe_zero : ↑(0 : {p : M₀ // is_idempotent_elem p}) = (0 : M₀) := rfl instance : has_one { p : M₁ // is_idempotent_elem p } := { one := ⟨ 1, one ⟩ } @[simp] lemma coe_one : ↑(1 : { p : M₁ // is_idempotent_elem p }) = (1 : M₁) := rfl instance : has_compl { p : R // is_idempotent_elem p } := ⟨λ p, ⟨1 - p, p.prop.one_sub⟩⟩ @[simp] lemma coe_compl (p : { p : R // is_idempotent_elem p }) : ↑(pᶜ) = (1 : R) - ↑p := rfl @[simp] lemma compl_compl (p : {p : R // is_idempotent_elem p}) : pᶜᶜ = p := subtype.ext $ sub_sub_cancel _ _ @[simp] lemma zero_compl : (0 : {p : R // is_idempotent_elem p})ᶜ = 1 := subtype.ext $ sub_zero _ @[simp] lemma one_compl : (1 : {p : R // is_idempotent_elem p})ᶜ = 0 := subtype.ext $ sub_self _ end instances end is_idempotent_elem
ff3da14fc159ff491e04f53fdda295a1c14d0b4e
367134ba5a65885e863bdc4507601606690974c1
/src/order/lattice_intervals.lean
d1577e5fb728b4745a8448aa31047c0edc65ee06
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
7,550
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Aaron Anderson. -/ import order.bounded_lattice import data.set.intervals.basic /-! # Intervals in Lattices In this file, we provide instances of lattice structures on intervals within lattices. Some of them depend on the order of the endpoints of the interval, and thus are not made global instances. These are probably not all of the lattice instances that could be placed on these intervals, but more can be added easily along the same lines when needed. ## Main definitions In the following, `*` can represent either `c`, `o`, or `i`. * `set.Ic*.semilattice_inf_bot` * `set.Ii*.semillatice_inf` * `set.I*c.semilattice_sup_top` * `set.I*c.semillatice_inf` * `set.Iic.bounded_lattice`, within a `bounded_lattice` * `set.Ici.bounded_lattice`, within a `bounded_lattice` -/ variable {α : Type*} namespace set namespace Ico variables {a b : α} instance [semilattice_inf α] : semilattice_inf (Ico a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, lt_of_le_of_lt inf_le_left hx.2⟩) /-- `Ico a b` has a bottom element whenever `a < b`. -/ def order_bot [partial_order α] (h : a < b) : order_bot (Ico a b) := { bot := ⟨a, ⟨le_refl a, h⟩⟩, bot_le := λ x, x.prop.1, .. (subtype.partial_order _) } /-- `Ico a b` is a `semilattice_inf_bot` whenever `a < b`. -/ def semilattice_inf_bot [semilattice_inf α] (h : a < b) : semilattice_inf_bot (Ico a b) := { .. (Ico.semilattice_inf), .. (Ico.order_bot h) } end Ico namespace Iio instance [semilattice_inf α] {a : α} : semilattice_inf (Iio a) := subtype.semilattice_inf (λ x y hx hy, lt_of_le_of_lt inf_le_left hx) end Iio namespace Ioc variables {a b : α} instance [semilattice_sup α] : semilattice_sup (Ioc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨lt_of_lt_of_le hx.1 le_sup_left, sup_le hx.2 hy.2⟩) /-- `Ioc a b` has a top element whenever `a < b`. -/ def order_top [partial_order α] (h : a < b) : order_top (Ioc a b) := { top := ⟨b, ⟨h, le_refl b⟩⟩, le_top := λ x, x.prop.2, .. (subtype.partial_order _) } /-- `Ioc a b` is a `semilattice_sup_top` whenever `a < b`. -/ def semilattice_sup_top [semilattice_sup α] (h : a < b) : semilattice_sup_top (Ioc a b) := { .. (Ioc.semilattice_sup), .. (Ioc.order_top h) } end Ioc namespace Iio instance [semilattice_sup α] {a : α} : semilattice_sup (Ioi a) := subtype.semilattice_sup (λ x y hx hy, lt_of_lt_of_le hx le_sup_left) end Iio namespace Iic variables {a : α} instance [semilattice_inf α] : semilattice_inf (Iic a) := subtype.semilattice_inf (λ x y hx hy, le_trans inf_le_left hx) instance [semilattice_sup α] : semilattice_sup (Iic a) := subtype.semilattice_sup (λ x y hx hy, sup_le hx hy) instance [lattice α] : lattice (Iic a) := { .. (Iic.semilattice_inf), .. (Iic.semilattice_sup) } instance [partial_order α] : order_top (Iic a) := { top := ⟨a, le_refl a⟩, le_top := λ x, x.prop, .. (subtype.partial_order _) } @[simp] lemma coe_top [partial_order α] {a : α} : ↑(⊤ : Iic a) = a := rfl instance [semilattice_inf α] : semilattice_inf_top (Iic a) := { .. (Iic.semilattice_inf), .. (Iic.order_top) } instance [semilattice_sup α] : semilattice_sup_top (Iic a) := { .. (Iic.semilattice_sup), .. (Iic.order_top) } instance [order_bot α] : order_bot (Iic a) := { bot := ⟨⊥, bot_le⟩, bot_le := λ ⟨_,_⟩, subtype.mk_le_mk.2 bot_le, .. (infer_instance : partial_order (Iic a)) } @[simp] lemma coe_bot [order_bot α] {a : α} : ↑(⊥ : Iic a) = (⊥ : α) := rfl instance [semilattice_inf_bot α] : semilattice_inf_bot (Iic a) := { .. (Iic.semilattice_inf), .. (Iic.order_bot) } instance [semilattice_sup_bot α] : semilattice_sup_bot (Iic a) := { .. (Iic.semilattice_sup), .. (Iic.order_bot) } instance [bounded_lattice α] : bounded_lattice (Iic a) := { .. (Iic.order_top), .. (Iic.order_bot), .. (Iic.lattice) } end Iic namespace Ici variables {a : α} instance [semilattice_inf α] : semilattice_inf (Ici a) := subtype.semilattice_inf (λ x y hx hy, le_inf hx hy) instance [semilattice_sup α] : semilattice_sup (Ici a) := subtype.semilattice_sup (λ x y hx hy, le_trans hx le_sup_left) instance [lattice α] : lattice (Ici a) := { .. (Ici.semilattice_inf), .. (Ici.semilattice_sup) } instance [partial_order α] : order_bot (Ici a) := { bot := ⟨a, le_refl a⟩, bot_le := λ x, x.prop, .. (subtype.partial_order _) } @[simp] lemma coe_bot [partial_order α] {a : α} : ↑(⊥ : Ici a) = a := rfl instance [semilattice_inf α] : semilattice_inf_bot (Ici a) := { .. (Ici.semilattice_inf), .. (Ici.order_bot) } instance [semilattice_sup α] : semilattice_sup_bot (Ici a) := { .. (Ici.semilattice_sup), .. (Ici.order_bot) } instance [order_top α] : order_top (Ici a) := { top := ⟨⊤, le_top⟩, le_top := λ ⟨_,_⟩, subtype.mk_le_mk.2 le_top, .. (infer_instance : partial_order (Ici a)) } @[simp] lemma coe_top [order_top α] {a : α} : ↑(⊤ : Ici a) = (⊤ : α) := rfl instance [semilattice_sup_top α] : semilattice_sup_top (Ici a) := { .. (Ici.semilattice_sup), .. (Ici.order_top) } instance [semilattice_inf_top α] : semilattice_inf_top (Ici a) := { .. (Ici.semilattice_inf), .. (Ici.order_top) } instance [bounded_lattice α] : bounded_lattice (Ici a) := { .. (Ici.order_top), .. (Ici.order_bot), .. (Ici.lattice) } end Ici namespace Icc instance [semilattice_inf α] {a b : α} : semilattice_inf (Icc a b) := subtype.semilattice_inf (λ x y hx hy, ⟨le_inf hx.1 hy.1, le_trans inf_le_left hx.2⟩) instance [semilattice_sup α] {a b : α} : semilattice_sup (Icc a b) := subtype.semilattice_sup (λ x y hx hy, ⟨le_trans hx.1 le_sup_left, sup_le hx.2 hy.2⟩) instance [lattice α] {a b : α} : lattice (Icc a b) := { .. (Icc.semilattice_inf), .. (Icc.semilattice_sup) } /-- `Icc a b` has a bottom element whenever `a ≤ b`. -/ def order_bot [partial_order α] {a b : α} (h : a ≤ b) : order_bot (Icc a b) := { bot := ⟨a, ⟨le_refl a, h⟩⟩, bot_le := λ x, x.prop.1, .. (subtype.partial_order _) } /-- `Icc a b` has a top element whenever `a ≤ b`. -/ def order_top [partial_order α] {a b : α} (h : a ≤ b) : order_top (Icc a b) := { top := ⟨b, ⟨h, le_refl b⟩⟩, le_top := λ x, x.prop.2, .. (subtype.partial_order _) } /-- `Icc a b` is a `semilattice_inf_bot` whenever `a ≤ b`. -/ def semilattice_inf_bot [semilattice_inf α] {a b : α} (h : a ≤ b) : semilattice_inf_bot (Icc a b) := { .. (Icc.order_bot h), .. (Icc.semilattice_inf) } /-- `Icc a b` is a `semilattice_inf_top` whenever `a ≤ b`. -/ def semilattice_inf_top [semilattice_inf α] {a b : α} (h : a ≤ b) : semilattice_inf_top (Icc a b) := { .. (Icc.order_top h), .. (Icc.semilattice_inf) } /-- `Icc a b` is a `semilattice_sup_bot` whenever `a ≤ b`. -/ def semilattice_sup_bot [semilattice_sup α] {a b : α} (h : a ≤ b) : semilattice_sup_bot (Icc a b) := { .. (Icc.order_bot h), .. (Icc.semilattice_sup) } /-- `Icc a b` is a `semilattice_sup_top` whenever `a ≤ b`. -/ def semilattice_sup_top [semilattice_sup α] {a b : α} (h : a ≤ b) : semilattice_sup_top (Icc a b) := { .. (Icc.order_top h), .. (Icc.semilattice_sup) } /-- `Icc a b` is a `bounded_lattice` whenever `a ≤ b`. -/ def bounded_lattice [lattice α] {a b : α} (h : a ≤ b) : bounded_lattice (Icc a b) := { .. (Icc.semilattice_inf_bot h), .. (Icc.semilattice_sup_top h) } end Icc end set
b96f8edeaf56bcdfd0a1ea6ee741859ee9d3fe2c
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/n4.lean
c02dbf6a395dd30a628b18a5a94f6cd3122bdb96
[ "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
414
lean
definition Prop : Type.{1} := Type.{0} context variable N : Type.{1} variables a b c : N variable and : Prop → Prop → Prop infixr `∧`:35 := and variable le : N → N → Prop variable lt : N → N → Prop precedence `≤`:50 precedence `<`:50 infixl ≤ := le infixl < := lt check a ≤ b definition T : Prop := a ≤ b check T end check T (* print(get_env():find("T"):value()) *)
3850b4944d1841666a462dfd8bce5845780c771c
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/record3.lean
2ffb31875d1e861b64479ad9473de4ea648955f7
[ "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
325
lean
import logic data.unit structure point (A : Type) (B : Type) := mk :: (x : A) (y : B) inductive color := red | green | blue structure color_point (A : Type) (B : Type) extends point A B := mk :: (c : color) constant foo (p: point num num) : num constant p : color_point num num set_option pp.coercions true check foo p
677a7443cb3278f36353fdeb766cbc380ed024d5
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/hott/disable_instances.hlean
1b9c0bad42be668433439fb7e67eccd5d6eada99
[ "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
313
hlean
open is_equiv constants (A B : Type) (f : A → B) definition H : is_equiv f := sorry definition loop [instance] [h : is_equiv f] : is_equiv f := h example (a : A) : let H' : is_equiv f := H in @(is_equiv.inv f) H' (f a) = a := begin with_options [elaborator.ignore_instances true] (apply left_inv f a) end
bc4e42bc5fb5397096e28e0978bc5aa06b468ed8
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/blast11.lean
c344517133cf5bb632598590ac5235a1abdeff09
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
229
lean
import data.nat open algebra nat definition lemma1 (a b : nat) : a + b + 0 = b + a := by blast print lemma1 definition lemma2 (a b c : nat) : a + b + 0 + c + a + a + b = 0 + 0 + c + a + b + a + a + b := by blast print lemma2
3ee898da25d3dd10b61153da7ec332b4a7c48624
35960c5b117752aca7e3e7767c0b393e4dbd72a7
/src/exp/semantics.lean
826b0b95e65536aff3c9654e45721dce76840afd
[ "Apache-2.0" ]
permissive
spl/tts
461dc76b83df8db47e4660d0941dc97e6d4fd7d1
b65298fea68ce47c8ed3ba3dbce71c1a20dd3481
refs/heads/master
1,541,049,198,347
1,537,967,023,000
1,537,967,029,000
119,653,145
1
0
null
null
null
null
UTF-8
Lean
false
false
1,844
lean
import tactics .subst_open namespace tts ------------------------------------------------------------------ namespace exp ------------------------------------------------------------------ variables {V : Type} -- Type of variable names variables [decidable_eq V] variables {e₁ e₂ : exp V} -- Expressions /-- Grammar of values -/ inductive value : exp V → Prop | lam : Π {v} {e : exp V}, lc_body e → value (lam v e) theorem lc_of_value : ∀ {e : exp V}, value e → lc e | _ (value.lam p) := lc_lam.mpr p /-- Reduction rules -/ inductive red : exp V → exp V → Prop | app₁ : Π {ef ef' ea : exp V}, red ef ef' → ea.lc → red (app ef ea) (app ef' ea) | app₂ : Π {ef ea ea' : exp V}, value ef → red ea ea' → red (app ef ea) (app ef ea') | lam : Π {v} {eb ea : exp V}, lc_body eb → value ea → red (app (lam v eb) ea) (open_exp₀ ea eb) | let₁ : Π {v} {ed ed' eb : exp V}, red ed ed' → lc_body eb → red (let_ v ed eb) (let_ v ed' eb) | let₂ : Π {v} {ed eb : exp V}, value ed → lc_body eb → red (let_ v ed eb) (open_exp₀ ed eb) theorem lc_of_red_left (h : red e₁ e₂) : lc e₁ := by induction h; simp [and.assoc] at *; note_all_applied lc_of_value; tauto theorem lc_of_red_right (h : red e₁ e₂) : lc e₂ := begin induction h, case red.app₁ { simp at *, tauto }, case red.app₂ { simp at *, note_all_applied lc_of_value, tauto }, case red.lam : v _ _ lc_eb val_ea { exact lc_open_exp₀ v lc_eb (lc_of_value val_ea) }, case red.let₁ { simp at *, tauto }, case red.let₂ : v _ _ val_ed lc_eb { exact lc_open_exp₀ v lc_eb (lc_of_value val_ed) } end end /- namespace -/ exp -------------------------------------------------------- end /- namespace -/ tts --------------------------------------------------------
cb55217eb3d90c4e4b361feba34be8dc19a41033
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/reducibilityattrs.lean
ddf33032a6bd7ab6561747b44a4b88229a123791
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
1,367
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.lean.attributes namespace Lean inductive ReducibilityStatus | reducible | semireducible | irreducible instance ReducibilityStatus.inhabited : Inhabited ReducibilityStatus := ⟨ReducibilityStatus.semireducible⟩ def mkReducibilityAttrs : IO (EnumAttributes ReducibilityStatus) := registerEnumAttributes `reducibility [(`reducible, "reducible", ReducibilityStatus.reducible), (`semireducible, "semireducible", ReducibilityStatus.semireducible), (`irreducible, "irreducible", ReducibilityStatus.irreducible)] @[init mkReducibilityAttrs] constant reducibilityAttrs : EnumAttributes ReducibilityStatus := default _ @[export lean.get_reducibility_status_core] def getReducibilityStatus (env : Environment) (n : Name) : ReducibilityStatus := match reducibilityAttrs.getValue env n with | some s => s | none => ReducibilityStatus.semireducible @[export lean.set_reducibility_status_core] def setReducibilityStatus (env : Environment) (n : Name) (s : ReducibilityStatus) : Environment := match reducibilityAttrs.setValue env n s with | Except.ok env => env | _ => env -- TODO(Leo): we should extend EnumAttributes.setValue in the future and ensure it never fails end Lean
0dbbf40a3e866a4a36a66158f81ba348e927dd22
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/sheaves/sheaf_condition/opens_le_cover.lean
908ae991af38b93ffa2ba39756853b7aee0e2e88
[ "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,435
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import topology.sheaves.presheaf import category_theory.limits.final import topology.sheaves.sheaf_condition.pairwise_intersections /-! # Another version of the sheaf condition. Given a family of open sets `U : ι → opens X` we can form the subcategory `{ V : opens X // ∃ i, V ≤ U i }`, which has `supr U` as a cocone. The sheaf condition on a presheaf `F` is equivalent to `F` sending the opposite of this cocone to a limit cone in `C`, for every `U`. This condition is particularly nice when checking the sheaf condition because we don't need to do any case bashing (depending on whether we're looking at single or double intersections, or equivalently whether we're looking at the first or second object in an equalizer diagram). ## References * This is the definition Lurie uses in [Spectral Algebraic Geometry][LurieSAG]. -/ universes v u noncomputable theory open category_theory open category_theory.limits open topological_space open opposite open topological_space.opens namespace Top variables {C : Type u} [category.{v} C] variables {X : Top.{v}} (F : presheaf C X) {ι : Type v} (U : ι → opens X) namespace presheaf namespace sheaf_condition /-- The category of open sets contained in some element of the cover. -/ def opens_le_cover : Type v := { V : opens X // ∃ i, V ≤ U i } instance [inhabited ι] : inhabited (opens_le_cover U) := ⟨⟨⊥, default, bot_le⟩⟩ instance : category (opens_le_cover U) := category_theory.full_subcategory _ namespace opens_le_cover variables {U} /-- An arbitrarily chosen index such that `V ≤ U i`. -/ def index (V : opens_le_cover U) : ι := V.property.some /-- The morphism from `V` to `U i` for some `i`. -/ def hom_to_index (V : opens_le_cover U) : V.val ⟶ U (index V) := (V.property.some_spec).hom end opens_le_cover /-- `supr U` as a cocone over the opens sets contained in some element of the cover. (In fact this is a colimit cocone.) -/ def opens_le_cover_cocone : cocone (full_subcategory_inclusion _ : opens_le_cover U ⥤ opens X) := { X := supr U, ι := { app := λ V : opens_le_cover U, V.hom_to_index ≫ opens.le_supr U _, } } end sheaf_condition open sheaf_condition /-- An equivalent formulation of the sheaf condition (which we prove equivalent to the usual one below as `is_sheaf_iff_is_sheaf_opens_le_cover`). A presheaf is a sheaf if `F` sends the cone `(opens_le_cover_cocone U).op` to a limit cone. (Recall `opens_le_cover_cocone U`, has cone point `supr U`, mapping down to any `V` which is contained in some `U i`.) -/ def is_sheaf_opens_le_cover : Prop := ∀ ⦃ι : Type v⦄ (U : ι → opens X), nonempty (is_limit (F.map_cone (opens_le_cover_cocone U).op)) namespace sheaf_condition open category_theory.pairwise /-- Implementation detail: the object level of `pairwise_to_opens_le_cover : pairwise ι ⥤ opens_le_cover U` -/ @[simp] def pairwise_to_opens_le_cover_obj : pairwise ι → opens_le_cover U | (single i) := ⟨U i, ⟨i, le_rfl⟩⟩ | (pair i j) := ⟨U i ⊓ U j, ⟨i, inf_le_left⟩⟩ open category_theory.pairwise.hom /-- Implementation detail: the morphism level of `pairwise_to_opens_le_cover : pairwise ι ⥤ opens_le_cover U` -/ def pairwise_to_opens_le_cover_map : Π {V W : pairwise ι}, (V ⟶ W) → (pairwise_to_opens_le_cover_obj U V ⟶ pairwise_to_opens_le_cover_obj U W) | _ _ (id_single i) := 𝟙 _ | _ _ (id_pair i j) := 𝟙 _ | _ _ (left i j) := hom_of_le inf_le_left | _ _ (right i j) := hom_of_le inf_le_right /-- The category of single and double intersections of the `U i` maps into the category of open sets below some `U i`. -/ @[simps] def pairwise_to_opens_le_cover : pairwise ι ⥤ opens_le_cover U := { obj := pairwise_to_opens_le_cover_obj U, map := λ V W i, pairwise_to_opens_le_cover_map U i, } instance (V : opens_le_cover U) : nonempty (structured_arrow V (pairwise_to_opens_le_cover U)) := ⟨{ right := single (V.index), hom := V.hom_to_index }⟩ /-- The diagram consisting of the `U i` and `U i ⊓ U j` is cofinal in the diagram of all opens contained in some `U i`. -/ -- This is a case bash: for each pair of types of objects in `pairwise ι`, -- we have to explicitly construct a zigzag. instance : functor.final (pairwise_to_opens_le_cover U) := ⟨λ V, is_connected_of_zigzag $ λ A B, begin rcases A with ⟨⟨⟩, ⟨i⟩|⟨i,j⟩, a⟩; rcases B with ⟨⟨⟩, ⟨i'⟩|⟨i',j'⟩, b⟩; dsimp at *, { refine ⟨[ { left := punit.star, right := pair i i', hom := (le_inf a.le b.le).hom, }, _], _, rfl⟩, exact list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i i', }⟩) (list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := right i i', }⟩) list.chain.nil) }, { refine ⟨[ { left := punit.star, right := pair i' i, hom := (le_inf (b.le.trans inf_le_left) a.le).hom, }, { left := punit.star, right := single i', hom := (b.le.trans inf_le_left).hom, }, _], _, rfl⟩, exact list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := right i' i, }⟩) (list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := left i' i, }⟩) (list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i' j', }⟩) list.chain.nil)) }, { refine ⟨[ { left := punit.star, right := single i, hom := (a.le.trans inf_le_left).hom, }, { left := punit.star, right := pair i i', hom := (le_inf (a.le.trans inf_le_left) b.le).hom, }, _], _, rfl⟩, exact list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := left i j, }⟩) (list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i i', }⟩) (list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := right i i', }⟩) list.chain.nil)) }, { refine ⟨[ { left := punit.star, right := single i, hom := (a.le.trans inf_le_left).hom, }, { left := punit.star, right := pair i i', hom := (le_inf (a.le.trans inf_le_left) (b.le.trans inf_le_left)).hom, }, { left := punit.star, right := single i', hom := (b.le.trans inf_le_left).hom, }, _], _, rfl⟩, exact list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := left i j, }⟩) (list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i i', }⟩) (list.chain.cons (or.inl ⟨{ left := 𝟙 _, right := right i i', }⟩) (list.chain.cons (or.inr ⟨{ left := 𝟙 _, right := left i' j', }⟩) list.chain.nil))), }, end⟩ /-- The diagram in `opens X` indexed by pairwise intersections from `U` is isomorphic (in fact, equal) to the diagram factored through `opens_le_cover U`. -/ def pairwise_diagram_iso : pairwise.diagram U ≅ pairwise_to_opens_le_cover U ⋙ full_subcategory_inclusion _ := { hom := { app := begin rintro (i|⟨i,j⟩); exact 𝟙 _, end, }, inv := { app := begin rintro (i|⟨i,j⟩); exact 𝟙 _, end, }, } /-- The cocone `pairwise.cocone U` with cocone point `supr U` over `pairwise.diagram U` is isomorphic to the cocone `opens_le_cover_cocone U` (with the same cocone point) after appropriate whiskering and postcomposition. -/ def pairwise_cocone_iso : (pairwise.cocone U).op ≅ (cones.postcompose_equivalence (nat_iso.op (pairwise_diagram_iso U : _) : _)).functor.obj ((opens_le_cover_cocone U).op.whisker (pairwise_to_opens_le_cover U).op) := cones.ext (iso.refl _) (by tidy) end sheaf_condition open sheaf_condition /-- The sheaf condition in terms of a limit diagram over all `{ V : opens X // ∃ i, V ≤ U i }` is equivalent to the reformulation in terms of a limit diagram over `U i` and `U i ⊓ U j`. -/ lemma is_sheaf_opens_le_cover_iff_is_sheaf_pairwise_intersections (F : presheaf C X) : F.is_sheaf_opens_le_cover ↔ F.is_sheaf_pairwise_intersections := forall₂_congr $ λ ι U, equiv.nonempty_congr $ calc is_limit (F.map_cone (opens_le_cover_cocone U).op) ≃ is_limit ((F.map_cone (opens_le_cover_cocone U).op).whisker (pairwise_to_opens_le_cover U).op) : (functor.initial.is_limit_whisker_equiv (pairwise_to_opens_le_cover U).op _).symm ... ≃ is_limit (F.map_cone ((opens_le_cover_cocone U).op.whisker (pairwise_to_opens_le_cover U).op)) : is_limit.equiv_iso_limit F.map_cone_whisker.symm ... ≃ is_limit ((cones.postcompose_equivalence _).functor.obj (F.map_cone ((opens_le_cover_cocone U).op.whisker (pairwise_to_opens_le_cover U).op))) : (is_limit.postcompose_hom_equiv _ _).symm ... ≃ is_limit (F.map_cone ((cones.postcompose_equivalence _).functor.obj ((opens_le_cover_cocone U).op.whisker (pairwise_to_opens_le_cover U).op))) : is_limit.equiv_iso_limit (functor.map_cone_postcompose_equivalence_functor _).symm ... ≃ is_limit (F.map_cone (pairwise.cocone U).op) : is_limit.equiv_iso_limit ((cones.functoriality _ _).map_iso (pairwise_cocone_iso U : _).symm) variables [has_products C] /-- The sheaf condition in terms of an equalizer diagram is equivalent to the reformulation in terms of a limit diagram over all `{ V : opens X // ∃ i, V ≤ U i }`. -/ lemma is_sheaf_iff_is_sheaf_opens_le_cover (F : presheaf C X) : F.is_sheaf ↔ F.is_sheaf_opens_le_cover := iff.trans (is_sheaf_iff_is_sheaf_pairwise_intersections F) (is_sheaf_opens_le_cover_iff_is_sheaf_pairwise_intersections F).symm end presheaf end Top
4d058b257c26455a7b533bc77a30a963f47cf1b4
508d8fd300d597fd3f7f0f8f3d0f70275d21965f
/src/mathematica_parser.lean
8229c94d46fb687519c4e74079c9ebb26ff36a25
[]
no_license
holtzermann17/mathematica
e3cdf06b4e1a118fcb22dbf8a8b722b33cde93d1
ce589a885ccdea477e98e4ce38d6d3a4ae8940a9
refs/heads/master
1,588,476,421,760
1,553,861,282,000
1,553,861,282,000
178,398,173
0
0
null
1,553,861,103,000
1,553,861,103,000
null
UTF-8
Lean
false
false
6,368
lean
import data.buffer.parser system.io open parser --namespace mathematica meta def htfi : has_to_format ℤ := ⟨λ z, int.rec_on z (λ k, ↑k) (λ k, "-"++↑(k+1))⟩ local attribute [instance] htfi structure mfloat := (sign : nat) (mantisa : nat) (exponent : nat) local notation `float` := mfloat meta instance : has_to_format float := ⟨λ f, to_fmt "(" ++ to_fmt f.sign ++ to_fmt ", " ++ to_fmt f.mantisa ++ ", " ++ to_fmt f.exponent ++ to_fmt ")"⟩ meta instance : has_reflect float | ⟨s, m, e⟩ := ((`(λ s' m' e', mfloat.mk s' m' e').subst (nat.reflect s)).subst (nat.reflect m)).subst (nat.reflect e) /-- The type mmexpr reflects Mathematica expression syntax. -/ inductive mmexpr : Type | sym : string → mmexpr | mstr : string → mmexpr | mint : int → mmexpr | app : mmexpr → list mmexpr → mmexpr | mreal : float → mmexpr meta def mmexpr_list_to_format (f : mmexpr → format) : list mmexpr → format | [] := to_fmt "" | [h] := f h | (h :: t) := f h ++ ", " ++ mmexpr_list_to_format t open mmexpr meta def mmexpr_to_format : mmexpr → format | (sym s) := to_fmt s | (mstr s) := to_fmt "\"" ++ to_fmt s ++ "\"" | (mint i) := to_fmt i | (app e1 ls) := mmexpr_to_format e1 ++ to_fmt "[" ++ mmexpr_list_to_format mmexpr_to_format ls ++ to_fmt "]" | (mreal r) := to_fmt r meta instance : has_to_format mmexpr := ⟨mmexpr_to_format⟩ def nat_of_char : char → nat | '0' := 0 | '1' := 1 | '2' := 2 | '3' := 3 | '4' := 4 | '5' := 5 | '6' := 6 | '7' := 7 | '8' := 8 | '9' := 9 | _ := 0 def nat_of_string_aux : nat → nat → list char → nat | weight acc [] := acc | weight acc (h::t) := nat_of_string_aux (weight*10) (weight * (nat_of_char h) + acc) t def nat_of_string (s : string) : nat := nat_of_string_aux 1 0 s.to_list.reverse def parse_is_neg : parser bool := (ch '-' >> return tt) <|> return ff def parse_int : parser mmexpr := do str "I[", is_neg ← parse_is_neg, n ← (nat_of_string ∘ list.as_string) <$> many (sat char.is_alphanum), ch ']', return $ mmexpr.mint (if is_neg then -n else n) def parse_string : parser mmexpr := do str "T[\"", s ← list.as_string <$> many (sat ((≠) '\"')), ch '\"', ch ']', return $ mmexpr.mstr s def parse_symbol : parser mmexpr := do str "Y[", s ← list.as_string <$> many (sat ((≠) ']')), ch ']', return $ mmexpr.sym s def parse_app_aux (parse_expr : parser mmexpr) : parser mmexpr := do str "A", hd ← parse_expr, ch '[', args ← sep_by (ch ',') parse_expr, ch ']', return $ mmexpr.app hd args def parse_mmexpr_aux (p : parser mmexpr) : parser mmexpr := parse_int <|> parse_string <|> parse_symbol <|> (parse_app_aux p) def parse_mmexpr : parser mmexpr := fix parse_mmexpr_aux private def make_monospaced : char → char | '\n' := ' ' | '\t' := ' ' | '\x0d' := ' ' | c := c def mk_mono_cb (s : char_buffer) : char_buffer := s.map make_monospaced def buffer.back {α} [inhabited α] (b : buffer α) : α := b.read' (b.size-1) meta def strip_trailing_whitespace_cb : char_buffer → char_buffer := λ s, if s.back = '\n' ∨ s.back = ' ' then strip_trailing_whitespace_cb s.pop_back else s def escape_quotes_cb (s : char_buffer) : char_buffer := s.foldl buffer.nil (λ c s', if c = '\"' then s' ++ "\\\"".to_char_buffer else s'.push_back c) def escape_term_buffer_cb (s : char_buffer) : char_buffer := s.foldl buffer.nil (λ c s', if c = '&' then s' ++ "&&".to_char_buffer else s'.push_back c) def quote_string_cb (s : char_buffer) : char_buffer := "\'".to_char_buffer ++ s ++ "\'".to_char_buffer def mk_mono (s : string) : string := (s.to_list.map make_monospaced).as_string meta def strip_trailing_whitespace : string → string := λ s, if s.back = '\n' ∨ s.back = ' ' then strip_trailing_whitespace s.pop_back else s def strip_newline : string → string := λ s, if s.back = '\n' then s.pop_back else s def escape_quotes (s : string) : string := s.fold "" (λ s' c, if c = '\"' then s' ++ "\\\"" else s'.str c) def escape_term (s : string) : string := s.fold "" (λ s' c, if c = '&' then s' ++ "&&" else s'.str c) def escape_slash (s : string) : string := s.fold "" (λ s' c, if c = '\\' then s' ++ "\\\\" else s'.str c) def quote_string (s : string) : string := "\'" ++ s ++ "\'" meta def parse_mmexpr_tac (s : char_buffer) : tactic mmexpr := match parser.run parse_mmexpr ((strip_trailing_whitespace_cb ∘ mk_mono_cb) s) with | sum.inr mme := return mme | sum.inl error := tactic.fail error end def parse_name : parser (list string) := do l ← sep_by (ch '.') (many $ sat ((≠) '.')), return $ (l.map list.as_string).reverse def mk_name_using : list string → name | [] := name.anonymous | (s :: l) := mk_str_name (mk_name_using l) s meta def parse_name_tac (s : string) : tactic name := match parser.run_string parse_name s with | sum.inr ls := return $ mk_name_using ls | sum.inl error := tactic.fail error end /-meta def parse_mmexpr_tac (s : char_buffer) : tactic mmexpr := (do sum.inr mme ← return $ parser.run parse_mmexpr ((strip_trailing_whitespace_cb ∘ mk_mono_cb) s), return mme) -/ namespace mathematica section def write_file (fn : string) (cnts : string) (mode := io.mode.write) : io unit := do h ← io.mk_file_handle fn io.mode.write, io.fs.write h cnts.to_char_buffer, io.fs.close h def exists_file (f : string) : io bool := do ch ← io.proc.spawn { cmd := "test", args := ["-f", f] }, ev ← io.proc.wait ch, return $ ev = 0 meta def new_text_file : string → nat → io nat | base n := do b ← exists_file (base ++ to_string n ++ ".txt"), if b then new_text_file base (n+1) else return n end meta def temp_file_name (base : string) : tactic string := do n ← tactic.unsafe_run_io $ new_text_file base 0, return $ base ++ to_string n ++ ".txt" end mathematica def io.buffer_cmd (args : io.process.spawn_args) : io char_buffer := do child ← io.proc.spawn { args with stdout := io.process.stdio.piped }, buf ← io.fs.read_to_end child.stdout, exitv ← io.proc.wait child, when (exitv ≠ 0) $ io.fail $ "process exited with status " ++ to_string exitv, return buf
6dae0d7bc3df8debf3cd456e33ad04081dd9eb37
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Util/MonadCache.lean
7a71e13bf14e76a7920041bd3aa2258251b4fddb
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,486
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 Std.Data.HashMap namespace Lean /-- Interface for caching results. -/ class MonadCache (α β : Type) (m : Type → Type) := (findCached? : α → m (Option β)) (cache : α → β → m Unit) /-- If entry `a := b` is already in the cache, then return `b`. Otherwise, execute `b ← f a`, store `a := b` in the cache and return `b`. -/ @[inline] def checkCache {α β : Type} {m : Type → Type} [MonadCache α β m] [Monad m] (a : α) (f : α → m β) : m β := do match (← MonadCache.findCached? a) with | some b => pure b | none => do let b ← f a MonadCache.cache a b pure b instance {α β ρ : Type} {m : Type → Type} [MonadCache α β m] : MonadCache α β (ReaderT ρ m) := { findCached? := fun a r => MonadCache.findCached? a, cache := fun a b r => MonadCache.cache a b } instance {α β ε : Type} {m : Type → Type} [MonadCache α β m] [Monad m] : MonadCache α β (ExceptT ε m) := { findCached? := fun a => ExceptT.lift $ MonadCache.findCached? a, cache := fun a b => ExceptT.lift $ MonadCache.cache a b } open Std (HashMap) /-- Adapter for implementing `MonadCache` interface using `HashMap`s. We just have to specify how to extract/modify the `HashMap`. -/ class MonadHashMapCacheAdapter (α β : Type) (m : Type → Type) [BEq α] [Hashable α] := (getCache : m (HashMap α β)) (modifyCache : (HashMap α β → HashMap α β) → m Unit) namespace MonadHashMapCacheAdapter @[inline] def findCached? {α β : Type} {m : Type → Type} [BEq α] [Hashable α] [Monad m] [MonadHashMapCacheAdapter α β m] (a : α) : m (Option β) := do let c ← getCache pure (c.find? a) @[inline] def cache {α β : Type} {m : Type → Type} [BEq α] [Hashable α] [MonadHashMapCacheAdapter α β m] (a : α) (b : β) : m Unit := modifyCache fun s => s.insert a b instance {α β : Type} {m : Type → Type} [BEq α] [Hashable α] [Monad m] [MonadHashMapCacheAdapter α β m] : MonadCache α β m := { findCached? := MonadHashMapCacheAdapter.findCached?, cache := MonadHashMapCacheAdapter.cache } end MonadHashMapCacheAdapter def MonadCacheT {ω} (α β : Type) (m : Type → Type) [STWorld ω m] [BEq α] [Hashable α] := StateRefT (HashMap α β) m namespace MonadCacheT variables {ω α β : Type} {m : Type → Type} [STWorld ω m] [BEq α] [Hashable α] [MonadLiftT (ST ω) m] [Monad m] instance : MonadHashMapCacheAdapter α β (MonadCacheT α β m) := { getCache := (get : StateRefT' ..), modifyCache := fun f => (modify f : StateRefT' ..) } @[inline] def run {σ} (x : MonadCacheT α β m σ) : m σ := x.run' Std.mkHashMap instance : Monad (MonadCacheT α β m) := inferInstanceAs (Monad (StateRefT' _ _ _)) instance : MonadLift m (MonadCacheT α β m) := inferInstanceAs (MonadLift m (StateRefT' _ _ _)) instance (ε) [MonadExceptOf ε m] : MonadExceptOf ε (MonadCacheT α β m) := inferInstanceAs (MonadExceptOf ε (StateRefT' _ _ _)) instance : MonadControl m (MonadCacheT α β m) := inferInstanceAs (MonadControl m (StateRefT' _ _ _)) instance [MonadFinally m] : MonadFinally (MonadCacheT α β m) := inferInstanceAs (MonadFinally (StateRefT' _ _ _)) instance [MonadRef m] : MonadRef (MonadCacheT α β m) := inferInstanceAs (MonadRef (StateRefT' _ _ _)) end MonadCacheT end Lean
5b45b02d9292911c99ed370e658256576c7c4f4d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/Uri.lean
c1ffed890515a27b3131d619c93b38e1be8358f4
[ "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
4,393
lean
open Lean open System.Uri ------------------------------------------------------------------------------ -- see https://github.com/python/cpython/blob/main/Lib/test/test_urllib.py def testEscaping := /- Uri character escaping includes UTF-8 encoding for the 😵 char! -/ assert! (pathToUri "/temp/test.xml?😵=2022") == "file:///temp/test.xml%3F%F0%9F%98%B5%3D2022" /- tilde is NOT escaped -/ assert! (pathToUri "~/git/lean4") == "file:///~/git/lean4" true def testNeverEscape := let do_not_quote := String.join ["ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz", "0123456789", "_.-~<>\"{}|\\^`"] let result := escapeUri do_not_quote assert! result == do_not_quote true def testShouldEscape := let controls := String.mk ((List.range 31).map (fun c => Char.ofNat c)) let should_quote := String.join [controls, "#%[]", (Char.ofNat 127).toString] -- for 0x7F assert! should_quote.data.all (λ c => let x := (escapeUri c.toString) x.length == 3 && x.take 1 == "%") true def testPartialEscape := assert! (escapeUri "ab[]cd") == "ab%5B%5Dcd" true def testSpaceEscape := assert! (escapeUri " ") == "%20" true def testUnicodeEscape := assert! (escapeUri "😵") == "%F0%9F%98%B5" assert! (escapeUri "\u6f22\u5b57") == "%E6%BC%A2%E5%AD%97" true def testRoundTrip := assert! (fileUriToPath? (pathToUri "/temp/test.xml?😵=2022")) == "/temp/test.xml?😵=2022" true def testInvalidFileUri := assert! (fileUriToPath? "invalid") == none true def testUnescapePercent := assert! (unescapeUri "/temp/test%25.xml") == "/temp/test%.xml" true def testUnescapeSinglePercent := assert! (unescapeUri "%") == "%" true def testUnescapeBadHex := assert! (unescapeUri "%xab") == "%xab" assert! (unescapeUri "file://test%W9/%3Fa%3D123") == "file://test%W9/?a=123" true def testTruncatedEscape := assert! (unescapeUri "lean%4") == "lean%4" true def testUnescapeUnicode := assert! (unescapeUri "%F0%9F%98%B5") == "😵" assert! (unescapeUri "br%C3%BCckner") == "brückner" assert! (unescapeUri "br%C3%BCckner") == "brückner" assert! (unescapeUri "\u6f22%C3%BC") == "\u6f22\u00fc" true def testUnescapeMixedCase := assert! (unescapeUri "\u00Ab\u006A") == "«j" true def testShouldUnescape := let controls := String.mk ((List.range 31).map (fun c => Char.ofNat c)) let should_quote := String.join [controls, "#%[]", (Char.ofNat 127).toString] -- for 0x7F assert! should_quote == unescapeUri (escapeUri should_quote) true def testWindowsDriveLetter := if System.Platform.isWindows then assert! pathToUri ("c:" / "temp") == "file:///c%3A/temp" true else true def testWindowsDriveLetterRoundTrip := if System.Platform.isWindows then let x : System.FilePath := "c:" / "temp" / "test.lean" let r := pathToUri x let result := if r == "file:///c%3A/temp/test.lean" then match fileUriToPath? r with | none => "testWindowsDriveLetterEscaping fileUriToPath? returned none" | some y => if y.normalize.toString == x.normalize.toString then "" else s!"testWindowsDriveLetterEscaping '{x.normalize.toString}' != '{y.normalize.toString}'" else s!"testWindowsDriveLetterEscaping escaped to {r}" assert! result == "" true else true def TestUncRoundTrip := let results := ["file:///c:", "file:////folder/test", "file:///c:/foo/bar/spam.foo"].map (fun p => let result := (match fileUriToPath? p with | some uri => unescapeUri (pathToUri uri) | none => "fileUriToPath? failed") if result == p then "ok" else s!"mismatch {result} != {p}") let ok := (results.all (λ c => c == "ok")) assert! ok -- s!"the results are not as expected: {results}" true #eval testEscaping && testNeverEscape && testShouldEscape && testRoundTrip && testPartialEscape && testSpaceEscape && testUnicodeEscape && testInvalidFileUri && testUnescapePercent && testUnescapeSinglePercent && testUnescapeBadHex && testTruncatedEscape && testUnescapeUnicode && testUnescapeMixedCase && testShouldUnescape && testWindowsDriveLetterRoundTrip
86ac141d0a832a82953dc544fc17b5c6ecccf48a
07c76fbd96ea1786cc6392fa834be62643cea420
/library/algebra/order.lean
be70d9e0cd3385af1b728b9ebfa3ce9d69ec633a
[ "Apache-2.0" ]
permissive
fpvandoorn/lean2
5a430a153b570bf70dc8526d06f18fc000a60ad9
0889cf65b7b3cebfb8831b8731d89c2453dd1e9f
refs/heads/master
1,592,036,508,364
1,545,093,958,000
1,545,093,958,000
75,436,854
0
0
null
1,480,718,780,000
1,480,718,780,000
null
UTF-8
Lean
false
false
18,344
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad Weak orders "≤", strict orders "<", and structures that include both. -/ import logic.eq logic.connectives algebra.binary algebra.priority open eq eq.ops function variables {A : Type} /- weak orders -/ structure weak_order [class] (A : Type) extends has_le A := (le_refl : ∀a, le a a) (le_trans : ∀a b c, le a b → le b c → le a c) (le_antisymm : ∀a b, le a b → le b a → a = b) section variables [weak_order A] theorem le.refl [refl] (a : A) : a ≤ a := !weak_order.le_refl theorem le_of_eq {a b : A} (H : a = b) : a ≤ b := H ▸ le.refl a theorem le.trans [trans] {a b c : A} : a ≤ b → b ≤ c → a ≤ c := !weak_order.le_trans theorem ge.trans [trans] {a b c : A} (H1 : a ≥ b) (H2: b ≥ c) : a ≥ c := le.trans H2 H1 theorem le.antisymm {a b : A} : a ≤ b → b ≤ a → a = b := !weak_order.le_antisymm -- Alternate syntax. (Abbreviations do not migrate well.) theorem eq_of_le_of_ge {a b : A} : a ≤ b → b ≤ a → a = b := !le.antisymm end structure linear_weak_order [class] (A : Type) extends weak_order A := (le_total : ∀a b, le a b ∨ le b a) section variables [linear_weak_order A] theorem le.total (a b : A) : a ≤ b ∨ b ≤ a := !linear_weak_order.le_total theorem le_of_not_ge {a b : A} (H : ¬ a ≥ b) : a ≤ b := or.resolve_left !le.total H theorem le_by_cases (a b : A) {P : Prop} (H1 : a ≤ b → P) (H2 : b ≤ a → P) : P := begin cases (le.total a b) with H H, { exact H1 H}, { exact H2 H} end end /- strict orders -/ structure strict_order [class] (A : Type) extends has_lt A := (lt_irrefl : ∀a, ¬ lt a a) (lt_trans : ∀a b c, lt a b → lt b c → lt a c) section variable [strict_order A] theorem lt.irrefl (a : A) : ¬ a < a := !strict_order.lt_irrefl theorem not_lt_self (a : A) : ¬ a < a := !lt.irrefl -- alternate syntax theorem lt_self_iff_false (a : A) : a < a ↔ false := iff_false_intro (lt.irrefl a) theorem lt.trans [trans] {a b c : A} : a < b → b < c → a < c := !strict_order.lt_trans theorem gt.trans [trans] {a b c : A} (H1 : a > b) (H2: b > c) : a > c := lt.trans H2 H1 theorem ne_of_lt {a b : A} (lt_ab : a < b) : a ≠ b := assume eq_ab : a = b, show false, from lt.irrefl b (eq_ab ▸ lt_ab) theorem ne_of_gt {a b : A} (gt_ab : a > b) : a ≠ b := ne.symm (ne_of_lt gt_ab) theorem lt.asymm {a b : A} (H : a < b) : ¬ b < a := assume H1 : b < a, lt.irrefl _ (lt.trans H H1) theorem not_lt_of_gt {a b : A} (H : a > b) : ¬ a < b := !lt.asymm H -- alternate syntax end /- well-founded orders -/ structure wf_strict_order [class] (A : Type) extends strict_order A := (wf_rec : ∀P : A → Type, (∀x, (∀y, lt y x → P y) → P x) → ∀x, P x) definition wf.rec_on {A : Type} [s : wf_strict_order A] {P : A → Type} (x : A) (H : ∀x, (∀y, wf_strict_order.lt y x → P y) → P x) : P x := wf_strict_order.wf_rec P H x theorem wf.ind_on.{u v} {A : Type.{u}} [s : wf_strict_order.{u 0} A] {P : A → Prop} (x : A) (H : ∀x, (∀y, wf_strict_order.lt y x → P y) → P x) : P x := wf.rec_on x H /- structures with a weak and a strict order -/ structure order_pair [class] (A : Type) extends weak_order A, has_lt A := (le_of_lt : ∀ a b, lt a b → le a b) (lt_of_lt_of_le : ∀ a b c, lt a b → le b c → lt a c) (lt_of_le_of_lt : ∀ a b c, le a b → lt b c → lt a c) (lt_irrefl : ∀ a, ¬ lt a a) section variable [s : order_pair A] variables {a b c : A} include s theorem le_of_lt : a < b → a ≤ b := !order_pair.le_of_lt theorem lt_of_lt_of_le [trans] : a < b → b ≤ c → a < c := !order_pair.lt_of_lt_of_le theorem lt_of_le_of_lt [trans] : a ≤ b → b < c → a < c := !order_pair.lt_of_le_of_lt private theorem lt_irrefl (s' : order_pair A) (a : A) : ¬ a < a := !order_pair.lt_irrefl private theorem lt_trans (s' : order_pair A) (a b c: A) (lt_ab : a < b) (lt_bc : b < c) : a < c := lt_of_lt_of_le lt_ab (le_of_lt lt_bc) definition order_pair.to_strict_order [trans_instance] : strict_order A := ⦃ strict_order, s, lt_irrefl := lt_irrefl s, lt_trans := lt_trans s ⦄ theorem gt_of_gt_of_ge [trans] (H1 : a > b) (H2 : b ≥ c) : a > c := lt_of_le_of_lt H2 H1 theorem gt_of_ge_of_gt [trans] (H1 : a ≥ b) (H2 : b > c) : a > c := lt_of_lt_of_le H2 H1 theorem not_le_of_gt (H : a > b) : ¬ a ≤ b := assume H1 : a ≤ b, lt.irrefl _ (lt_of_lt_of_le H H1) theorem not_lt_of_ge (H : a ≥ b) : ¬ a < b := assume H1 : a < b, lt.irrefl _ (lt_of_le_of_lt H H1) end structure strong_order_pair [class] (A : Type) extends weak_order A, has_lt A := (le_iff_lt_or_eq : ∀a b, le a b ↔ lt a b ∨ a = b) (lt_irrefl : ∀ a, ¬ lt a a) section strong_order_pair variable [strong_order_pair A] theorem le_iff_lt_or_eq {a b : A} : a ≤ b ↔ a < b ∨ a = b := !strong_order_pair.le_iff_lt_or_eq theorem lt_or_eq_of_le {a b : A} (le_ab : a ≤ b) : a < b ∨ a = b := iff.mp le_iff_lt_or_eq le_ab theorem le_of_lt_or_eq {a b : A} (lt_or_eq : a < b ∨ a = b) : a ≤ b := iff.mpr le_iff_lt_or_eq lt_or_eq private theorem lt_irrefl' (a : A) : ¬ a < a := !strong_order_pair.lt_irrefl private theorem le_of_lt' (a b : A) : a < b → a ≤ b := take Hlt, le_of_lt_or_eq (or.inl Hlt) private theorem lt_iff_le_and_ne {a b : A} : a < b ↔ (a ≤ b ∧ a ≠ b) := iff.intro (take Hlt, and.intro (le_of_lt_or_eq (or.inl Hlt)) (take Hab, absurd (Hab ▸ Hlt) !lt_irrefl')) (take Hand, have Hor : a < b ∨ a = b, from lt_or_eq_of_le (and.left Hand), or_resolve_left Hor (and.right Hand)) theorem lt_of_le_of_ne {a b : A} : a ≤ b → a ≠ b → a < b := take H1 H2, iff.mpr lt_iff_le_and_ne (and.intro H1 H2) private theorem ne_of_lt' {a b : A} (H : a < b) : a ≠ b := and.right ((iff.mp lt_iff_le_and_ne) H) private theorem lt_of_lt_of_le' (a b c : A) : a < b → b ≤ c → a < c := assume lt_ab : a < b, assume le_bc : b ≤ c, have le_ac : a ≤ c, from le.trans (le_of_lt' _ _ lt_ab) le_bc, have ne_ac : a ≠ c, from assume eq_ac : a = c, have le_ba : b ≤ a, from eq_ac⁻¹ ▸ le_bc, have eq_ab : a = b, from le.antisymm (le_of_lt' _ _ lt_ab) le_ba, show false, from ne_of_lt' lt_ab eq_ab, show a < c, from iff.mpr (lt_iff_le_and_ne) (and.intro le_ac ne_ac) theorem lt_of_le_of_lt' (a b c : A) : a ≤ b → b < c → a < c := assume le_ab : a ≤ b, assume lt_bc : b < c, have le_ac : a ≤ c, from le.trans le_ab (le_of_lt' _ _ lt_bc), have ne_ac : a ≠ c, from assume eq_ac : a = c, have le_cb : c ≤ b, from eq_ac ▸ le_ab, have eq_bc : b = c, from le.antisymm (le_of_lt' _ _ lt_bc) le_cb, show false, from ne_of_lt' lt_bc eq_bc, show a < c, from iff.mpr (lt_iff_le_and_ne) (and.intro le_ac ne_ac) end strong_order_pair definition strong_order_pair.to_order_pair [trans_instance] [s : strong_order_pair A] : order_pair A := ⦃ order_pair, s, lt_irrefl := lt_irrefl', le_of_lt := le_of_lt', lt_of_le_of_lt := lt_of_le_of_lt', lt_of_lt_of_le := lt_of_lt_of_le' ⦄ /- linear orders -/ structure linear_order_pair [class] (A : Type) extends order_pair A, linear_weak_order A structure linear_strong_order_pair [class] (A : Type) extends strong_order_pair A, linear_weak_order A definition linear_strong_order_pair.to_linear_order_pair [trans_instance] [s : linear_strong_order_pair A] : linear_order_pair A := ⦃ linear_order_pair, s, strong_order_pair.to_order_pair ⦄ section variable [linear_strong_order_pair A] variables (a b c : A) theorem lt.trichotomy : a < b ∨ a = b ∨ b < a := or.elim (le.total a b) (assume H : a ≤ b, or.elim (iff.mp !le_iff_lt_or_eq H) (assume H1, or.inl H1) (assume H1, or.inr (or.inl H1))) (assume H : b ≤ a, or.elim (iff.mp !le_iff_lt_or_eq H) (assume H1, or.inr (or.inr H1)) (assume H1, or.inr (or.inl (H1⁻¹)))) theorem lt.by_cases {a b : A} {P : Prop} (H1 : a < b → P) (H2 : a = b → P) (H3 : b < a → P) : P := or.elim !lt.trichotomy (assume H, H1 H) (assume H, or.elim H (assume H', H2 H') (assume H', H3 H')) definition lt_ge_by_cases {a b : A} {P : Prop} (H1 : a < b → P) (H2 : a ≥ b → P) : P := lt.by_cases H1 (λH, H2 (H ▸ le.refl a)) (λH, H2 (le_of_lt H)) theorem le_of_not_gt {a b : A} (H : ¬ a > b) : a ≤ b := lt.by_cases (assume H', absurd H' H) (assume H', H' ▸ !le.refl) (assume H', le_of_lt H') theorem lt_of_not_ge {a b : A} (H : ¬ a ≥ b) : a < b := lt.by_cases (assume H', absurd (le_of_lt H') H) (assume H', absurd (H' ▸ !le.refl) H) (assume H', H') theorem lt_iff_not_ge : a < b ↔ ¬ a ≥ b := iff.intro (suppose a < b, not_le_of_gt this) (suppose ¬ a ≥ b, lt_of_not_ge this) theorem le_iff_not_gt : a ≤ b ↔ ¬ a > b := iff.intro (suppose a ≤ b, not_lt_of_ge this) (suppose ¬ a > b, le_of_not_gt this) theorem gt_iff_not_le : a > b ↔ ¬ a ≤ b := iff.intro (suppose a > b, not_le_of_gt this) (suppose ¬ a ≤ b, lt_of_not_ge this) theorem ge_iff_not_lt : a ≥ b ↔ ¬ a < b := iff.intro (suppose a ≥ b, not_lt_of_ge this) (suppose ¬ a < b, le_of_not_gt this) theorem lt_or_ge : a < b ∨ a ≥ b := lt.by_cases (assume H1 : a < b, or.inl H1) (assume H1 : a = b, or.inr (H1 ▸ le.refl a)) (assume H1 : a > b, or.inr (le_of_lt H1)) theorem le_or_gt : a ≤ b ∨ a > b := !or.swap (lt_or_ge b a) theorem lt_or_gt_of_ne {a b : A} (H : a ≠ b) : a < b ∨ a > b := lt.by_cases (assume H1, or.inl H1) (assume H1, absurd H1 H) (assume H1, or.inr H1) end open decidable structure decidable_linear_order [class] (A : Type) extends linear_strong_order_pair A := (decidable_lt : decidable_rel lt) section variable [s : decidable_linear_order A] variables (a b c d : A) include s open decidable definition decidable_lt [instance] : decidable (a < b) := @decidable_linear_order.decidable_lt _ _ _ _ definition decidable_le [instance] : decidable (a ≤ b) := by_cases (assume H : a < b, inl (le_of_lt H)) (assume H : ¬ a < b, have H1 : b ≤ a, from le_of_not_gt H, by_cases (assume H2 : b < a, inr (not_le_of_gt H2)) (assume H2 : ¬ b < a, inl (le_of_not_gt H2))) variables {a b c d} definition has_decidable_eq [instance] : decidable (a = b) := by_cases (assume H : a ≤ b, by_cases (assume H1 : b ≤ a, inl (le.antisymm H H1)) (assume H1 : ¬ b ≤ a, inr (assume H2 : a = b, H1 (H2 ▸ le.refl a)))) (assume H : ¬ a ≤ b, (inr (assume H1 : a = b, H (H1 ▸ !le.refl)))) theorem eq_or_lt_of_not_lt {a b : A} (H : ¬ a < b) : a = b ∨ b < a := if Heq : a = b then or.inl Heq else or.inr (lt_of_not_ge (λ Hge, H (lt_of_le_of_ne Hge Heq))) theorem eq_or_lt_of_le {a b : A} (H : a ≤ b) : a = b ∨ a < b := begin cases eq_or_lt_of_not_lt (not_lt_of_ge H), exact or.inl a_1⁻¹, exact or.inr a_1 end -- testing equality first may result in more definitional equalities definition lt.cases {B : Type} (a b : A) (t_lt t_eq t_gt : B) : B := if a = b then t_eq else (if a < b then t_lt else t_gt) theorem lt.cases_of_eq {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a = b) : lt.cases a b t_lt t_eq t_gt = t_eq := if_pos H theorem lt.cases_of_lt {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a < b) : lt.cases a b t_lt t_eq t_gt = t_lt := if_neg (ne_of_lt H) ⬝ if_pos H theorem lt.cases_of_gt {B : Type} {a b : A} {t_lt t_eq t_gt : B} (H : a > b) : lt.cases a b t_lt t_eq t_gt = t_gt := if_neg (ne.symm (ne_of_lt H)) ⬝ if_neg (lt.asymm H) definition min (a b : A) : A := if a ≤ b then a else b definition max (a b : A) : A := if a ≤ b then b else a /- these show min and max form a lattice -/ theorem min_le_left (a b : A) : min a b ≤ a := by_cases (assume H : a ≤ b, by rewrite [↑min, if_pos H]) (assume H : ¬ a ≤ b, by rewrite [↑min, if_neg H]; apply le_of_lt (lt_of_not_ge H)) theorem min_le_right (a b : A) : min a b ≤ b := by_cases (assume H : a ≤ b, by rewrite [↑min, if_pos H]; apply H) (assume H : ¬ a ≤ b, by rewrite [↑min, if_neg H]) theorem le_min {a b c : A} (H₁ : c ≤ a) (H₂ : c ≤ b) : c ≤ min a b := by_cases (assume H : a ≤ b, by rewrite [↑min, if_pos H]; apply H₁) (assume H : ¬ a ≤ b, by rewrite [↑min, if_neg H]; apply H₂) theorem le_max_left (a b : A) : a ≤ max a b := by_cases (assume H : a ≤ b, by rewrite [↑max, if_pos H]; apply H) (assume H : ¬ a ≤ b, by rewrite [↑max, if_neg H]) theorem le_max_right (a b : A) : b ≤ max a b := by_cases (assume H : a ≤ b, by rewrite [↑max, if_pos H]) (assume H : ¬ a ≤ b, by rewrite [↑max, if_neg H]; apply le_of_lt (lt_of_not_ge H)) theorem max_le {a b c : A} (H₁ : a ≤ c) (H₂ : b ≤ c) : max a b ≤ c := by_cases (assume H : a ≤ b, by rewrite [↑max, if_pos H]; apply H₂) (assume H : ¬ a ≤ b, by rewrite [↑max, if_neg H]; apply H₁) theorem le_max_left_iff_true (a b : A) : a ≤ max a b ↔ true := iff_true_intro (le_max_left a b) theorem le_max_right_iff_true (a b : A) : b ≤ max a b ↔ true := iff_true_intro (le_max_right a b) /- these are also proved for lattices, but with inf and sup in place of min and max -/ theorem eq_min {a b c : A} (H₁ : c ≤ a) (H₂ : c ≤ b) (H₃ : ∀{d}, d ≤ a → d ≤ b → d ≤ c) : c = min a b := le.antisymm (le_min H₁ H₂) (H₃ !min_le_left !min_le_right) theorem min.comm (a b : A) : min a b = min b a := eq_min !min_le_right !min_le_left (λ c H₁ H₂, le_min H₂ H₁) theorem min.assoc (a b c : A) : min (min a b) c = min a (min b c) := begin apply eq_min, { apply le.trans, apply min_le_left, apply min_le_left }, { apply le_min, apply le.trans, apply min_le_left, apply min_le_right, apply min_le_right }, { intros [d, H₁, H₂], apply le_min, apply le_min H₁, apply le.trans H₂, apply min_le_left, apply le.trans H₂, apply min_le_right } end theorem min.left_comm (a b c : A) : min a (min b c) = min b (min a c) := binary.left_comm (@min.comm A s) (@min.assoc A s) a b c theorem min.right_comm (a b c : A) : min (min a b) c = min (min a c) b := binary.right_comm (@min.comm A s) (@min.assoc A s) a b c theorem min_self (a : A) : min a a = a := by apply eq.symm; apply eq_min (le.refl a) !le.refl; intros; assumption theorem min_eq_left {a b : A} (H : a ≤ b) : min a b = a := by apply eq.symm; apply eq_min !le.refl H; intros; assumption theorem min_eq_right {a b : A} (H : b ≤ a) : min a b = b := eq.subst !min.comm (min_eq_left H) theorem eq_max {a b c : A} (H₁ : a ≤ c) (H₂ : b ≤ c) (H₃ : ∀{d}, a ≤ d → b ≤ d → c ≤ d) : c = max a b := le.antisymm (H₃ !le_max_left !le_max_right) (max_le H₁ H₂) theorem max.comm (a b : A) : max a b = max b a := eq_max !le_max_right !le_max_left (λ c H₁ H₂, max_le H₂ H₁) theorem max.assoc (a b c : A) : max (max a b) c = max a (max b c) := begin apply eq_max, { apply le.trans, apply le_max_left a b, apply le_max_left }, { apply max_le, apply le.trans, apply le_max_right a b, apply le_max_left, apply le_max_right }, { intros [d, H₁, H₂], apply max_le, apply max_le H₁, apply le.trans !le_max_left H₂, apply le.trans !le_max_right H₂} end theorem max.left_comm (a b c : A) : max a (max b c) = max b (max a c) := binary.left_comm (@max.comm A s) (@max.assoc A s) a b c theorem max.right_comm (a b c : A) : max (max a b) c = max (max a c) b := binary.right_comm (@max.comm A s) (@max.assoc A s) a b c theorem max_self (a : A) : max a a = a := by apply eq.symm; apply eq_max (le.refl a) !le.refl; intros; assumption theorem max_eq_left {a b : A} (H : b ≤ a) : max a b = a := by apply eq.symm; apply eq_max !le.refl H; intros; assumption theorem max_eq_right {a b : A} (H : a ≤ b) : max a b = b := eq.subst !max.comm (max_eq_left H) /- these rely on lt_of_lt -/ theorem min_eq_left_of_lt {a b : A} (H : a < b) : min a b = a := min_eq_left (le_of_lt H) theorem min_eq_right_of_lt {a b : A} (H : b < a) : min a b = b := min_eq_right (le_of_lt H) theorem max_eq_left_of_lt {a b : A} (H : b < a) : max a b = a := max_eq_left (le_of_lt H) theorem max_eq_right_of_lt {a b : A} (H : a < b) : max a b = b := max_eq_right (le_of_lt H) /- these use the fact that it is a linear ordering -/ theorem lt_min {a b c : A} (H₁ : a < b) (H₂ : a < c) : a < min b c := or.elim !le_or_gt (assume H : b ≤ c, by rewrite (min_eq_left H); apply H₁) (assume H : b > c, by rewrite (min_eq_right_of_lt H); apply H₂) theorem max_lt {a b c : A} (H₁ : a < c) (H₂ : b < c) : max a b < c := or.elim !le_or_gt (assume H : a ≤ b, by rewrite (max_eq_right H); apply H₂) (assume H : a > b, by rewrite (max_eq_left_of_lt H); apply H₁) end /- order instances -/ definition weak_order_Prop [instance] : weak_order Prop := ⦃ weak_order, le := λx y, x → y, le_refl := λx, id, le_trans := λa b c H1 H2 x, H2 (H1 x), le_antisymm := λf g H1 H2, propext (and.intro H1 H2) ⦄ definition weak_order_fun [instance] (A B : Type) [weak_order B] : weak_order (A → B) := ⦃ weak_order, le := λx y, ∀b, x b ≤ y b, le_refl := λf b, !le.refl, le_trans := λf g h H1 H2 b, !le.trans (H1 b) (H2 b), le_antisymm := λf g H1 H2, funext (λb, !le.antisymm (H1 b) (H2 b)) ⦄ definition weak_order_dual {A : Type} (wo : weak_order A) : weak_order A := ⦃ weak_order, le := λx y, y ≤ x, le_refl := le.refl, le_trans := take a b c `b ≤ a` `c ≤ b`, le.trans `c ≤ b` `b ≤ a`, le_antisymm := take a b `b ≤ a` `a ≤ b`, le.antisymm `a ≤ b` `b ≤ a` ⦄ lemma le_dual_eq_le {A : Type} (wo : weak_order A) (a b : A) : @le _ (@weak_order.to_has_le _ (weak_order_dual wo)) a b = @le _ (@weak_order.to_has_le _ wo) b a := rfl -- what to do with the strict variants?
0381c2b91f4a9cf5fade24b3e95a4cb94191de14
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/p_series.lean
65c2c5f9bbb6ab67764af4336b7a2b7ec43133b1
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
10,240
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import analysis.special_functions.pow /-! # Convergence of `p`-series In this file we prove that the series `∑' k in ℕ, 1 / k ^ p` converges if and only if `p > 1`. The proof is based on the [Cauchy condensation test](https://en.wikipedia.org/wiki/Cauchy_condensation_test): `∑ k, f k` converges if and only if so does `∑ k, 2 ^ k f (2 ^ k)`. We prove this test in `nnreal.summable_condensed_iff` and `summable_condensed_iff_of_nonneg`, then use it to prove `summable_one_div_rpow`. After this transformation, a `p`-series turns into a geometric series. ## TODO It should be easy to generalize arguments to Schlömilch's generalization of the Cauchy condensation test once we need it. ## Tags p-series, Cauchy condensation test -/ open filter open_locale big_operators ennreal nnreal topological_space /-! ### Cauchy condensation test In this section we prove the Cauchy condensation test: for `f : ℕ → ℝ≥0` or `f : ℕ → ℝ`, `∑ k, f k` converges if and only if so does `∑ k, 2 ^ k f (2 ^ k)`. Instead of giving a monolithic proof, we split it into a series of lemmas with explicit estimates of partial sums of each series in terms of the partial sums of the other series. -/ namespace finset variables {M : Type*} [ordered_add_comm_monoid M] {f : ℕ → M} lemma le_sum_condensed' (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) (n : ℕ) : (∑ k in Ico 1 (2 ^ n), f k) ≤ ∑ k in range n, (2 ^ k) • f (2 ^ k) := begin induction n with n ihn, { simp }, suffices : (∑ k in Ico (2 ^ n) (2 ^ (n + 1)), f k) ≤ (2 ^ n) • f (2 ^ n), { rw [sum_range_succ, ← sum_Ico_consecutive], exact add_le_add ihn this, exacts [n.one_le_two_pow, nat.pow_le_pow_of_le_right zero_lt_two n.le_succ] }, have : ∀ k ∈ Ico (2 ^ n) (2 ^ (n + 1)), f k ≤ f (2 ^ n) := λ k hk, hf (pow_pos zero_lt_two _) (Ico.mem.mp hk).1, convert sum_le_sum this, simp [pow_succ, two_mul] end lemma le_sum_condensed (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) (n : ℕ) : (∑ k in range (2 ^ n), f k) ≤ f 0 + ∑ k in range n, (2 ^ k) • f (2 ^ k) := begin convert add_le_add_left (le_sum_condensed' hf n) (f 0), rw [← sum_range_add_sum_Ico _ n.one_le_two_pow, sum_range_succ, sum_range_zero, zero_add] end lemma sum_condensed_le' (hf : ∀ ⦃m n⦄, 1 < m → m ≤ n → f n ≤ f m) (n : ℕ) : (∑ k in range n, (2 ^ k) • f (2 ^ (k + 1))) ≤ ∑ k in Ico 2 (2 ^ n + 1), f k := begin induction n with n ihn, { simp }, suffices : (2 ^ n) • f (2 ^ (n + 1)) ≤ ∑ k in Ico (2 ^ n + 1) (2 ^ (n + 1) + 1), f k, { rw [sum_range_succ, ← sum_Ico_consecutive], exact add_le_add ihn this, exacts [add_le_add_right n.one_le_two_pow _, add_le_add_right (nat.pow_le_pow_of_le_right zero_lt_two n.le_succ) _] }, have : ∀ k ∈ Ico (2 ^ n + 1) (2 ^ (n + 1) + 1), f (2 ^ (n + 1)) ≤ f k := λ k hk, hf (n.one_le_two_pow.trans_lt $ (nat.lt_succ_of_le le_rfl).trans_le (Ico.mem.mp hk).1) (nat.le_of_lt_succ $ (Ico.mem.mp hk).2), convert sum_le_sum this, simp [pow_succ, two_mul] end lemma sum_condensed_le (hf : ∀ ⦃m n⦄, 1 < m → m ≤ n → f n ≤ f m) (n : ℕ) : (∑ k in range (n + 1), (2 ^ k) • f (2 ^ k)) ≤ f 1 + 2 • ∑ k in Ico 2 (2 ^ n + 1), f k := begin convert add_le_add_left (nsmul_le_nsmul_of_le_right (sum_condensed_le' hf n) 2) (f 1), simp [sum_range_succ', add_comm, pow_succ, mul_nsmul, sum_nsmul] end end finset namespace ennreal variable {f : ℕ → ℝ≥0∞} lemma le_tsum_condensed (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) : ∑' k, f k ≤ f 0 + ∑' k : ℕ, (2 ^ k) * f (2 ^ k) := begin rw [ennreal.tsum_eq_supr_nat' (nat.tendsto_pow_at_top_at_top_of_one_lt _root_.one_lt_two)], refine supr_le (λ n, (finset.le_sum_condensed hf n).trans (add_le_add_left _ _)), simp only [nsmul_eq_mul, nat.cast_pow, nat.cast_two], apply ennreal.sum_le_tsum end lemma tsum_condensed_le (hf : ∀ ⦃m n⦄, 1 < m → m ≤ n → f n ≤ f m) : ∑' k : ℕ, (2 ^ k * f (2 ^ k)) ≤ f 1 + 2 * ∑' k, f k := begin rw [ennreal.tsum_eq_supr_nat' (tendsto_at_top_mono nat.le_succ tendsto_id), two_mul, ← two_nsmul], refine supr_le (λ n, le_trans _ (add_le_add_left (nsmul_le_nsmul_of_le_right (ennreal.sum_le_tsum $ finset.Ico 2 (2^n + 1)) _) _)), simpa using finset.sum_condensed_le hf n end end ennreal namespace nnreal /-- Cauchy condensation test for a series of `nnreal` version. -/ lemma summable_condensed_iff {f : ℕ → ℝ≥0} (hf : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) : summable (λ k : ℕ, (2 ^ k) * f (2 ^ k)) ↔ summable f := begin simp only [← ennreal.tsum_coe_ne_top_iff_summable, ne.def, not_iff_not, ennreal.coe_mul, ennreal.coe_pow, ennreal.coe_two], split; intro h, { replace hf : ∀ m n, 1 < m → m ≤ n → (f n : ℝ≥0∞) ≤ f m := λ m n hm hmn, ennreal.coe_le_coe.2 (hf (zero_lt_one.trans hm) hmn), simpa [h, ennreal.add_eq_top] using (ennreal.tsum_condensed_le hf) }, { replace hf : ∀ m n, 0 < m → m ≤ n → (f n : ℝ≥0∞) ≤ f m := λ m n hm hmn, ennreal.coe_le_coe.2 (hf hm hmn), simpa [h, ennreal.add_eq_top] using (ennreal.le_tsum_condensed hf) } end end nnreal /-- Cauchy condensation test for series of nonnegative real numbers. -/ lemma summable_condensed_iff_of_nonneg {f : ℕ → ℝ} (h_nonneg : ∀ n, 0 ≤ f n) (h_mono : ∀ ⦃m n⦄, 0 < m → m ≤ n → f n ≤ f m) : summable (λ k : ℕ, (2 ^ k) * f (2 ^ k)) ↔ summable f := begin set g : ℕ → ℝ≥0 := λ n, ⟨f n, h_nonneg n⟩, have : f = λ n, g n := rfl, simp only [this], have : ∀ ⦃m n⦄, 0 < m → m ≤ n → g n ≤ g m := λ m n hm h, nnreal.coe_le_coe.2 (h_mono hm h), exact_mod_cast nnreal.summable_condensed_iff this end open real /-! ### Convergence of the `p`-series In this section we prove that for a real number `p`, the series `∑' n : ℕ, 1 / (n ^ p)` converges if and only if `1 < p`. There are many different proofs of this fact. The proof in this file uses the Cauchy condensation test we formalized above. This test implies that `∑ n, 1 / (n ^ p)` converges if and only if `∑ n, 2 ^ n / ((2 ^ n) ^ p)` converges, and the latter series is a geometric series with common ratio `2 ^ {1 - p}`. -/ /-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, (n ^ p)⁻¹` converges if and only if `1 < p`. -/ @[simp] lemma real.summable_nat_rpow_inv {p : ℝ} : summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ) ↔ 1 < p := begin cases le_or_lt 0 p with hp hp, /- Cauchy condensation test applies only to monotonically decreasing sequences, so we consider the cases `0 ≤ p` and `p < 0` separately. -/ { rw ← summable_condensed_iff_of_nonneg, { simp_rw [nat.cast_pow, nat.cast_two, ← rpow_nat_cast, ← rpow_mul zero_lt_two.le, mul_comm _ p, rpow_mul zero_lt_two.le, rpow_nat_cast, ← inv_pow', ← mul_pow, summable_geometric_iff_norm_lt_1], nth_rewrite 0 [← rpow_one 2], rw [← division_def, ← rpow_sub zero_lt_two, norm_eq_abs, abs_of_pos (rpow_pos_of_pos zero_lt_two _), rpow_lt_one_iff zero_lt_two.le], norm_num }, { intro n, exact inv_nonneg.2 (rpow_nonneg_of_nonneg n.cast_nonneg _) }, { intros m n hm hmn, exact inv_le_inv_of_le (rpow_pos_of_pos (nat.cast_pos.2 hm) _) (rpow_le_rpow m.cast_nonneg (nat.cast_le.2 hmn) hp) } }, /- If `p < 0`, then `1 / n ^ p` tends to infinity, thus the series diverges. -/ { suffices : ¬summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ), { have : ¬(1 < p) := λ hp₁, hp.not_le (zero_le_one.trans hp₁.le), simpa [this, -one_div] }, { intro h, obtain ⟨k : ℕ, hk₁ : ((k ^ p)⁻¹ : ℝ) < 1, hk₀ : k ≠ 0⟩ := ((h.tendsto_cofinite_zero.eventually (gt_mem_nhds zero_lt_one)).and (eventually_cofinite_ne 0)).exists, apply hk₀, rw [← pos_iff_ne_zero, ← @nat.cast_pos ℝ] at hk₀, simpa [inv_lt_one_iff_of_pos (rpow_pos_of_pos hk₀ _), one_lt_rpow_iff_of_pos hk₀, hp, hp.not_lt, hk₀] using hk₁ } } end /-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, 1 / n ^ p` converges if and only if `1 < p`. -/ lemma real.summable_one_div_nat_rpow {p : ℝ} : summable (λ n, 1 / n ^ p : ℕ → ℝ) ↔ 1 < p := by simp /-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, (n ^ p)⁻¹` converges if and only if `1 < p`. -/ @[simp] lemma real.summable_nat_pow_inv {p : ℕ} : summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ) ↔ 1 < p := by simp only [← rpow_nat_cast, real.summable_nat_rpow_inv, nat.one_lt_cast] /-- Test for congergence of the `p`-series: the real-valued series `∑' n : ℕ, 1 / n ^ p` converges if and only if `1 < p`. -/ lemma real.summable_one_div_nat_pow {p : ℕ} : summable (λ n, 1 / n ^ p : ℕ → ℝ) ↔ 1 < p := by simp /-- Harmonic series is not unconditionally summable. -/ lemma real.not_summable_nat_cast_inv : ¬summable (λ n, n⁻¹ : ℕ → ℝ) := have ¬summable (λ n, (n^1)⁻¹ : ℕ → ℝ), from mt real.summable_nat_pow_inv.1 (lt_irrefl 1), by simpa /-- Harmonic series is not unconditionally summable. -/ lemma real.not_summable_one_div_nat_cast : ¬summable (λ n, 1 / n : ℕ → ℝ) := by simpa only [inv_eq_one_div] using real.not_summable_nat_cast_inv /-- **Divergence of the Harmonic Series** -/ lemma real.tendsto_sum_range_one_div_nat_succ_at_top : tendsto (λ n, ∑ i in finset.range n, (1 / (i + 1) : ℝ)) at_top at_top := begin rw ← not_summable_iff_tendsto_nat_at_top_of_nonneg, { exact_mod_cast mt (summable_nat_add_iff 1).1 real.not_summable_one_div_nat_cast }, { exact λ i, div_nonneg zero_le_one i.cast_add_one_pos.le } end @[simp] lemma nnreal.summable_one_rpow_inv {p : ℝ} : summable (λ n, (n ^ p)⁻¹ : ℕ → ℝ≥0) ↔ 1 < p := by simp [← nnreal.summable_coe] lemma nnreal.summable_one_div_rpow {p : ℝ} : summable (λ n, 1 / n ^ p : ℕ → ℝ≥0) ↔ 1 < p := by simp
7b4158a25ce48c4f69a0dc3a9103e2adb15d541b
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/data/mv_polynomial/basic.lean
733b3afa928f20dfcd2ebdaf822a7e0fd54a3f62
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,023
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.polynomial.eval /-! # Multivariate polynomials This file defines polynomial rings over a base ring (or even semiring), with variables from a general type `σ` (which could be infinite). ## Important definitions Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary type. This file creates the type `mv_polynomial σ R`, which mathematicians might denote $R[X_i : i \in σ]$. It is the type of multivariate (a.k.a. multivariable) polynomials, with variables corresponding to the terms in `σ`, and coefficients in `R`. ### Notation In the definitions below, we use the following notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (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 : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` ### Definitions * `mv_polynomial σ R` : the type of polynomials with variables of type `σ` and coefficients in the commutative semiring `R` * `monomial s a` : the monomial which mathematically would be denoted `a * X^s` * `C a` : the constant polynomial with value `a` * `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`. * `coeff s p` : the coefficient of `s` in `p`. * `eval₂ (f : R → S₁) (g : σ → S₁) p` : given a semiring homomorphism from `R` to another semiring `S₁`, and a map `σ → S₁`, evaluates `p` at this valuation, returning a term of type `S₁`. Note that `eval₂` can be made using `eval` and `map` (see below), and it has been suggested that sticking to `eval` and `map` might make the code less brittle. * `eval (g : σ → R) p` : given a map `σ → R`, evaluates `p` at this valuation, returning a term of type `R` * `map (f : R → S₁) p` : returns the multivariate polynomial obtained from `p` by the change of coefficient semiring corresponding to `f` ## Implementation notes Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`. The definition of `mv_polynomial σ R` is `(σ →₀ ℕ) →₀ R` ; here `σ →₀ ℕ` denotes the space of all monomials in the variables, and the function to `R` sends a monomial to its coefficient in the polynomial being represented. ## Tags polynomial, multivariate polynomial, multivariable polynomial -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v w x variables {R : Type u} {S₁ : Type v} {S₂ : Type w} {S₃ : Type x} /-- Multivariate polynomial, where `σ` is the index set of the variables and `R` is the coefficient ring -/ def mv_polynomial (σ : Type*) (R : Type*) [comm_semiring R] := add_monoid_algebra R (σ →₀ ℕ) namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : R} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_semiring section instances instance decidable_eq_mv_polynomial [comm_semiring R] [decidable_eq σ] [decidable_eq R] : decidable_eq (mv_polynomial σ R) := finsupp.decidable_eq instance [comm_semiring R] : comm_semiring (mv_polynomial σ R) := add_monoid_algebra.comm_semiring instance [comm_semiring R] : inhabited (mv_polynomial σ R) := ⟨0⟩ instance [semiring R] [comm_semiring S₁] [module R S₁] : module R (mv_polynomial σ S₁) := add_monoid_algebra.module instance [semiring R] [semiring S₁] [comm_semiring S₂] [has_scalar R S₁] [module R S₂] [module S₁ S₂] [is_scalar_tower R S₁ S₂] : is_scalar_tower R S₁ (mv_polynomial σ S₂) := add_monoid_algebra.is_scalar_tower instance [semiring R] [semiring S₁][comm_semiring S₂] [module R S₂] [module S₁ S₂] [smul_comm_class R S₁ S₂] : smul_comm_class R S₁ (mv_polynomial σ S₂) := add_monoid_algebra.smul_comm_class instance [comm_semiring R] [comm_semiring S₁] [algebra R S₁] : algebra R (mv_polynomial σ S₁) := add_monoid_algebra.algebra end instances variables [comm_semiring R] [comm_semiring S₁] {p q : mv_polynomial σ R} /-- `monomial s a` is the monomial with coefficient `a` and exponents given by `s` -/ def monomial (s : σ →₀ ℕ) (a : R) : mv_polynomial σ R := single s a lemma single_eq_monomial (s : σ →₀ ℕ) (a : R) : single s a = monomial s a := rfl lemma mul_def : (p * q) = p.sum (λ m a, q.sum $ λ n b, monomial (m + n) (a * b)) := rfl /-- `C a` is the constant polynomial with value `a` -/ def C : R →+* mv_polynomial σ R := { to_fun := monomial 0, ..single_zero_ring_hom } variables (R σ) theorem algebra_map_eq : algebra_map R (mv_polynomial σ R) = C := rfl variables {R σ} /-- `X n` is the degree `1` monomial $X_n$. -/ def X (n : σ) : mv_polynomial σ R := monomial (single n 1) 1 lemma C_apply : (C a : mv_polynomial σ R) = monomial 0 a := rfl @[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ R) := by simp [C_apply, monomial] @[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ R) := rfl lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') := by simp [C_apply, monomial, single_mul_single] @[simp] lemma C_add : (C (a + a') : mv_polynomial σ R) = C a + C a' := single_add @[simp] lemma C_mul : (C (a * a') : mv_polynomial σ R) = C a * C a' := C_mul_monomial.symm @[simp] lemma C_pow (a : R) (n : ℕ) : (C (a^n) : mv_polynomial σ R) = (C a)^n := by induction n; simp [pow_succ, *] lemma C_injective (σ : Type*) (R : Type*) [comm_semiring R] : function.injective (C : R → mv_polynomial σ R) := finsupp.single_injective _ lemma C_surjective {R : Type*} [comm_semiring R] (σ : Type*) (hσ : ¬ nonempty σ) : function.surjective (C : R → mv_polynomial σ R) := begin refine λ p, ⟨p.to_fun 0, finsupp.ext (λ a, _)⟩, simpa [(finsupp.ext (λ x, absurd (nonempty.intro x) hσ) : a = 0), C_apply, monomial], end lemma C_surjective_fin_0 {R : Type*} [comm_ring R] : function.surjective (mv_polynomial.C : R → mv_polynomial (fin 0) R) := C_surjective (fin 0) (λ h, let ⟨n⟩ := h in fin_zero_elim n) @[simp] lemma C_inj {σ : Type*} (R : Type*) [comm_semiring R] (r s : R) : (C r : mv_polynomial σ R) = C s ↔ r = s := (C_injective σ R).eq_iff instance infinite_of_infinite (σ : Type*) (R : Type*) [comm_semiring R] [infinite R] : infinite (mv_polynomial σ R) := infinite.of_injective C (C_injective _ _) instance infinite_of_nonempty (σ : Type*) (R : Type*) [nonempty σ] [comm_semiring R] [nontrivial R] : infinite (mv_polynomial σ R) := infinite.of_injective ((λ s : σ →₀ ℕ, monomial s 1) ∘ single (classical.arbitrary σ)) $ function.injective.comp (λ m n, (finsupp.single_left_inj one_ne_zero).mp) (finsupp.single_injective _) lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ R) = n := by induction n; simp [nat.succ_eq_add_one, *] theorem C_mul' : mv_polynomial.C a * p = a • p := (algebra.smul_def a p).symm lemma smul_eq_C_mul (p : mv_polynomial σ R) (a : R) : a • p = C a * p := C_mul'.symm lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : R) := begin induction e, { simp [X], refl }, { simp [pow_succ, e_ih], simp [X, monomial, single_mul_single, nat.succ_eq_add_one, add_comm] } end lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma single_eq_C_mul_X {s : σ} {a : R} {n : ℕ} : monomial (single s n) a = C a * (X s)^n := by rw [← zero_add (single s n), monomial_add_single, C_apply] @[simp] lemma monomial_add {s : σ →₀ ℕ} {a b : R} : monomial s a + monomial s b = monomial s (a + b) := single_add.symm @[simp] lemma monomial_mul {s s' : σ →₀ ℕ} {a b : R} : monomial s a * monomial s' b = monomial (s + s') (a * b) := add_monoid_algebra.single_mul_single @[simp] lemma monomial_zero {s : σ →₀ ℕ}: monomial s (0 : R) = 0 := single_zero @[simp] lemma sum_monomial {A : Type*} [add_comm_monoid A] {u : σ →₀ ℕ} {r : R} {b : (σ →₀ ℕ) → R → A} (w : b u 0 = 0) : sum (monomial u r) b = b u r := sum_single_index w @[simp] lemma sum_C {A : Type*} [add_comm_monoid A] {b : (σ →₀ ℕ) → R → A} (w : b 0 0 = 0) : sum (C a) b = b 0 a := by simp [C_apply, w] lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ R) := begin apply @finsupp.induction σ ℕ _ _ s, { simp only [C_apply, prod_zero_index]; exact (mul_one _).symm }, { assume n e s hns he ih, rw [monomial_single_add, ih, prod_add_index, prod_single_index, mul_left_comm], { simp only [pow_zero], }, { intro a, simp only [pow_zero], }, { intros, rw pow_add, }, } end @[recursor 5] lemma induction_on {M : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) : M p := have ∀s a, M (monomial s a), begin assume s a, apply @finsupp.induction σ ℕ _ _ s, { show M (monomial 0 a), from h_C a, }, { assume n e p hpn he ih, have : ∀e:ℕ, M (monomial p a * X n ^ e), { intro e, induction e, { simp [ih] }, { simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } }, simp [add_comm, monomial_add_single, this] } end, finsupp.induction p (by have : M (C 0) := h_C 0; rwa [C_0] at this) (assume s a p hsp ha hp, h_add _ _ (this s a) hp) attribute [elab_as_eliminator] theorem induction_on' {P : mv_polynomial σ R → Prop} (p : mv_polynomial σ R) (h1 : ∀ (u : σ →₀ ℕ) (a : R), P (monomial u a)) (h2 : ∀ (p q : mv_polynomial σ R), P p → P q → P (p + q)) : P p := finsupp.induction p (suffices P (monomial 0 0), by rwa monomial_zero at this, show P (monomial 0 0), from h1 0 0) (λ a b f ha hb hPf, h2 _ _ (h1 _ _) hPf) @[ext] lemma ring_hom_ext {A : Type*} [semiring A] {f g : mv_polynomial σ R →+* A} (hC : ∀ r, f (C r) = g (C r)) (hX : ∀ i, f (X i) = g (X i)) : f = g := by { ext, exacts [hC _, hX _] } lemma hom_eq_hom [semiring S₂] (f g : mv_polynomial σ R →+* S₂) (hC : ∀a:R, f (C a) = g (C a)) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ R) : f p = g p := ring_hom.congr_fun (ring_hom_ext hC hX) p lemma is_id (f : mv_polynomial σ R →+* mv_polynomial σ R) (hC : ∀a:R, f (C a) = (C a)) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ R) : f p = p := hom_eq_hom f (ring_hom.id _) hC hX p @[ext] lemma alg_hom_ext {A : Type*} [comm_semiring A] [algebra R A] {f g : mv_polynomial σ R →ₐ[R] A} (hf : ∀ i : σ, f (X i) = g (X i)) : f = g := by { ext, exact hf _ } @[simp] lemma alg_hom_C (f : mv_polynomial σ R →ₐ[R] mv_polynomial σ R) (r : R) : f (C r) = C r := f.commutes r section support /-- The finite set of all `m : σ →₀ ℕ` such that `X^m` has a non-zero coefficient. -/ def support (p : mv_polynomial σ R) : finset (σ →₀ ℕ) := p.support lemma support_monomial [decidable (a = 0)] : (monomial s a).support = if a = 0 then ∅ else {s} := by convert rfl lemma support_monomial_subset : (monomial s a).support ⊆ {s} := support_single_subset lemma support_add : (p + q).support ⊆ p.support ∪ q.support := finsupp.support_add lemma support_X [nontrivial R] : (X n : mv_polynomial σ R).support = {single n 1} := by rw [X, support_monomial, if_neg]; exact one_ne_zero end support section coeff /-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/ def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ R) : R := @coe_fn _ (monoid_algebra.has_coe_to_fun _ _) p m @[simp] lemma mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} : m ∈ p.support ↔ p.coeff m ≠ 0 := by simp [support, coeff] lemma not_mem_support_iff {p : mv_polynomial σ R} {m : σ →₀ ℕ} : m ∉ p.support ↔ p.coeff m = 0 := by simp lemma sum_def {A} [add_comm_monoid A] {p : mv_polynomial σ R} {b : (σ →₀ ℕ) → R → A} : p.sum b = ∑ m in p.support, b m (p.coeff m) := by simp [support, finsupp.sum, coeff] lemma support_mul (p q : mv_polynomial σ R) : (p * q).support ⊆ p.support.bUnion (λ a, q.support.bUnion $ λ b, {a + b}) := by convert add_monoid_algebra.support_mul p q; ext; convert iff.rfl @[ext] lemma ext (p q : mv_polynomial σ R) : (∀ m, coeff m p = coeff m q) → p = q := ext lemma ext_iff (p q : mv_polynomial σ R) : p = q ↔ (∀ m, coeff m p = coeff m q) := ⟨ λ h m, by rw h, ext p q⟩ @[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ R) : coeff m (p + q) = coeff m p + coeff m q := add_apply p q m @[simp] lemma coeff_smul {S₁ : Type*} [semiring S₁] [module S₁ R] (m : σ →₀ ℕ) (c : S₁) (p : mv_polynomial σ R) : coeff m (c • p) = c • coeff m p := smul_apply c p m @[simp] lemma coeff_zero (m : σ →₀ ℕ) : coeff m (0 : mv_polynomial σ R) = 0 := rfl @[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ R) = 0 := single_eq_of_ne (λ h, by cases single_eq_zero.1 h) instance coeff.is_add_monoid_hom (m : σ →₀ ℕ) : is_add_monoid_hom (coeff m : mv_polynomial σ R → R) := { map_add := coeff_add m, map_zero := coeff_zero m } lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ R) (m : σ →₀ ℕ) : coeff m (∑ x in s, f x) = ∑ x in s, coeff m (f x) := (s.sum_hom _).symm lemma monic_monomial_eq (m) : monomial m (1:R) = (m.prod $ λn e, X n ^ e : mv_polynomial σ R) := by simp [monomial_eq] @[simp] lemma coeff_monomial (m n) (a) : coeff m (monomial n a : mv_polynomial σ R) = if n = m then a else 0 := single_apply @[simp] lemma coeff_C (m) (a) : coeff m (C a : mv_polynomial σ R) = if 0 = m then a else 0 := single_apply lemma coeff_X_pow (i : σ) (m) (k : ℕ) : coeff m (X i ^ k : mv_polynomial σ R) = if single i k = m then 1 else 0 := begin have := coeff_monomial m (finsupp.single i k) (1:R), rwa [@monomial_eq _ _ (1:R) (finsupp.single i k) _, C_1, one_mul, finsupp.prod_single_index] at this, exact pow_zero _ end lemma coeff_X' (i : σ) (m) : coeff m (X i : mv_polynomial σ R) = if single i 1 = m then 1 else 0 := by rw [← coeff_X_pow, pow_one] @[simp] lemma coeff_X (i : σ) : coeff (single i 1) (X i : mv_polynomial σ R) = 1 := by rw [coeff_X', if_pos rfl] @[simp] lemma coeff_C_mul (m) (a : R) (p : mv_polynomial σ R) : coeff m (C a * p) = a * coeff m p := begin rw [mul_def, sum_C], { simp [sum_def, coeff_sum] {contextual := tt} }, simp end lemma coeff_mul (p q : mv_polynomial σ R) (n : σ →₀ ℕ) : coeff n (p * q) = ∑ x in (antidiagonal n).support, coeff x.1 p * coeff x.2 q := begin rw mul_def, -- We need to manipulate both sides into a shape to which we can apply `finset.sum_bij_ne_zero`, -- so we need to turn both sides into a sum over a product. have := @finset.sum_product (σ →₀ ℕ) R _ _ p.support q.support (λ x, if (x.1 + x.2 = n) then coeff x.1 p * coeff x.2 q else 0), convert this.symm using 1; clear this, { rw [coeff], iterate 2 { rw sum_apply, apply finset.sum_congr rfl, intros, dsimp only }, exact single_apply }, symmetry, -- We are now ready to show that both sums are equal using `finset.sum_bij_ne_zero`. apply finset.sum_bij_ne_zero (λ (x : (σ →₀ ℕ) × (σ →₀ ℕ)) _ _, (x.1, x.2)), { intros x hx hx', simp only [mem_antidiagonal_support, eq_self_iff_true, if_false, forall_true_iff], contrapose! hx', rw [if_neg hx'] }, { rintros ⟨i, j⟩ ⟨k, l⟩ hij hij' hkl hkl', simpa only [and_imp, prod.mk.inj_iff, heq_iff_eq] using and.intro }, { rintros ⟨i, j⟩ hij hij', refine ⟨⟨i, j⟩, _, _⟩, { simp only [mem_support_iff, finset.mem_product], contrapose! hij', exact mul_eq_zero_of_ne_zero_imp_eq_zero hij' }, { rw [mem_antidiagonal_support] at hij, simp only [exists_prop, true_and, ne.def, if_pos hij, hij', not_false_iff] } }, { intros x hx hx', simp only [ne.def] at hx' ⊢, split_ifs with H, { refl }, { rw if_neg H at hx', contradiction } } end @[simp] lemma coeff_mul_X (m) (s : σ) (p : mv_polynomial σ R) : coeff (m + single s 1) (p * X s) = coeff m p := begin have : (m, single s 1) ∈ (m + single s 1).antidiagonal.support := mem_antidiagonal_support.2 rfl, rw [coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.sum_eq_zero, add_zero, coeff_X, mul_one], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, mem_antidiagonal_support] at hij, by_cases H : single s 1 = j, { subst j, simpa using hij }, { rw [coeff_X', if_neg H, mul_zero] }, end lemma coeff_mul_X' (m) (s : σ) (p : mv_polynomial σ R) : coeff m (p * X s) = if s ∈ m.support then coeff (m - single s 1) p else 0 := begin nontriviality R, split_ifs with h h, { conv_rhs {rw ← coeff_mul_X _ s}, congr' with t, by_cases hj : s = t, { subst t, simp only [nat_sub_apply, add_apply, single_eq_same], refine (nat.sub_add_cancel $ nat.pos_of_ne_zero _).symm, rwa finsupp.mem_support_iff at h }, { simp [single_eq_of_ne hj] } }, { rw ← not_mem_support_iff, intro hm, apply h, have H := support_mul _ _ hm, simp only [finset.mem_bUnion] at H, rcases H with ⟨j, hj, i', hi', H⟩, rw [support_X, finset.mem_singleton] at hi', subst i', rw finset.mem_singleton at H, subst m, rw [finsupp.mem_support_iff, add_apply, single_apply, if_pos rfl], intro H, rw [_root_.add_eq_zero_iff] at H, exact one_ne_zero H.2 } end lemma eq_zero_iff {p : mv_polynomial σ R} : p = 0 ↔ ∀ d, coeff d p = 0 := by { rw ext_iff, simp only [coeff_zero], } lemma ne_zero_iff {p : mv_polynomial σ R} : p ≠ 0 ↔ ∃ d, coeff d p ≠ 0 := by { rw [ne.def, eq_zero_iff], push_neg, } lemma exists_coeff_ne_zero {p : mv_polynomial σ R} (h : p ≠ 0) : ∃ d, coeff d p ≠ 0 := ne_zero_iff.mp h lemma C_dvd_iff_dvd_coeff (r : R) (φ : mv_polynomial σ R) : C r ∣ φ ↔ ∀ i, r ∣ φ.coeff i := begin split, { rintros ⟨φ, rfl⟩ c, rw coeff_C_mul, apply dvd_mul_right }, { intro h, choose c hc using h, classical, let c' : (σ →₀ ℕ) → R := λ i, if i ∈ φ.support then c i else 0, let ψ : mv_polynomial σ R := ∑ i in φ.support, monomial i (c' i), use ψ, apply mv_polynomial.ext, intro i, simp only [coeff_C_mul, coeff_sum, coeff_monomial, finset.sum_ite_eq', c'], split_ifs with hi hi, { rw hc }, { rw not_mem_support_iff at hi, rwa mul_zero } }, end end coeff section constant_coeff /-- `constant_coeff p` returns the constant term of the polynomial `p`, defined as `coeff 0 p`. This is a ring homomorphism. -/ def constant_coeff : mv_polynomial σ R →+* R := { to_fun := coeff 0, map_one' := by simp [coeff, add_monoid_algebra.one_def], map_mul' := by simp [coeff_mul, finsupp.support_single_ne_zero], map_zero' := coeff_zero _, map_add' := coeff_add _ } lemma constant_coeff_eq : (constant_coeff : mv_polynomial σ R → R) = coeff 0 := rfl @[simp] lemma constant_coeff_C (r : R) : constant_coeff (C r : mv_polynomial σ R) = r := by simp [constant_coeff_eq] @[simp] lemma constant_coeff_X (i : σ) : constant_coeff (X i : mv_polynomial σ R) = 0 := by simp [constant_coeff_eq] lemma constant_coeff_monomial (d : σ →₀ ℕ) (r : R) : constant_coeff (monomial d r) = if d = 0 then r else 0 := by rw [constant_coeff_eq, coeff_monomial] variables (σ R) @[simp] lemma constant_coeff_comp_C : constant_coeff.comp (C : R →+* mv_polynomial σ R) = ring_hom.id R := by { ext, apply constant_coeff_C } @[simp] lemma constant_coeff_comp_algebra_map : constant_coeff.comp (algebra_map R (mv_polynomial σ R)) = ring_hom.id R := constant_coeff_comp_C _ _ end constant_coeff section as_sum @[simp] lemma support_sum_monomial_coeff (p : mv_polynomial σ R) : ∑ v in p.support, monomial v (coeff v p) = p := finsupp.sum_single p lemma as_sum (p : mv_polynomial σ R) : p = ∑ v in p.support, monomial v (coeff v p) := (support_sum_monomial_coeff p).symm end as_sum section eval₂ variables (f : R →+* S₁) (g : σ → S₁) /-- Evaluate a polynomial `p` given a valuation `g` of all the variables and a ring hom `f` from the scalar ring to the target -/ def eval₂ (p : mv_polynomial σ R) : S₁ := p.sum (λs a, f a * s.prod (λn e, g n ^ e)) lemma eval₂_eq (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i in d.support, x i ^ d i := rfl lemma eval₂_eq' [fintype σ] (g : R →+* S₁) (x : σ → S₁) (f : mv_polynomial σ R) : f.eval₂ g x = ∑ d in f.support, g (f.coeff d) * ∏ i, x i ^ d i := by { simp only [eval₂_eq, ← finsupp.prod_pow], refl } @[simp] lemma eval₂_zero : (0 : mv_polynomial σ R).eval₂ f g = 0 := finsupp.sum_zero_index section @[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g := finsupp.sum_add_index (by simp [is_semiring_hom.map_zero f]) (by simp [add_mul, is_semiring_hom.map_add f]) @[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) := finsupp.sum_single_index (by simp [is_semiring_hom.map_zero f]) @[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a := by simp [eval₂_monomial, C, prod_zero_index] @[simp] lemma eval₂_one : (1 : mv_polynomial σ R).eval₂ f g = 1 := (eval₂_C _ _ _).trans (is_semiring_hom.map_one f) @[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n := by simp [eval₂_monomial, is_semiring_hom.map_one f, X, prod_single_index, pow_one] lemma eval₂_mul_monomial : ∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) := begin apply mv_polynomial.induction_on p, { assume a' s a, simp [C_mul_monomial, eval₂_monomial, is_semiring_hom.map_mul f] }, { assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] }, { assume p n ih s a, from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g : by simp [monomial_single_add, -add_comm, pow_one, mul_assoc] ... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) : by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm, is_semiring_hom.map_one f, -add_comm] } end @[simp] lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g := begin apply mv_polynomial.induction_on q, { simp [C, eval₂_monomial, eval₂_mul_monomial, prod_zero_index] }, { simp [mul_add, eval₂_add] {contextual := tt} }, { simp [X, eval₂_monomial, eval₂_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} } end @[simp] lemma eval₂_pow {p:mv_polynomial σ R} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n | 0 := by { rw [pow_zero, pow_zero], exact eval₂_one _ _ } | (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow] instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f g) := { map_zero := eval₂_zero _ _, map_one := eval₂_one _ _, map_add := λ p q, eval₂_add _ _, map_mul := λ p q, eval₂_mul _ _ } /-- `mv_polynomial.eval₂` as a `ring_hom`. -/ def eval₂_hom (f : R →+* S₁) (g : σ → S₁) : mv_polynomial σ R →+* S₁ := ring_hom.of (eval₂ f g) @[simp] lemma coe_eval₂_hom (f : R →+* S₁) (g : σ → S₁) : ⇑(eval₂_hom f g) = eval₂ f g := rfl lemma eval₂_hom_congr {f₁ f₂ : R →+* S₁} {g₁ g₂ : σ → S₁} {p₁ p₂ : mv_polynomial σ R} : f₁ = f₂ → g₁ = g₂ → p₁ = p₂ → eval₂_hom f₁ g₁ p₁ = eval₂_hom f₂ g₂ p₂ := by rintros rfl rfl rfl; refl end @[simp] lemma eval₂_hom_C (f : R →+* S₁) (g : σ → S₁) (r : R) : eval₂_hom f g (C r) = f r := eval₂_C f g r @[simp] lemma eval₂_hom_X' (f : R →+* S₁) (g : σ → S₁) (i : σ) : eval₂_hom f g (X i) = g i := eval₂_X f g i @[simp] lemma comp_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) : φ.comp (eval₂_hom f g) = (eval₂_hom (φ.comp f) (λ i, φ (g i))) := begin apply mv_polynomial.ring_hom_ext, { intro r, rw [ring_hom.comp_apply, eval₂_hom_C, eval₂_hom_C, ring_hom.comp_apply] }, { intro i, rw [ring_hom.comp_apply, eval₂_hom_X', eval₂_hom_X'] } end lemma map_eval₂_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₁) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : φ (eval₂_hom f g p) = (eval₂_hom (φ.comp f) (λ i, φ (g i)) p) := by { rw ← comp_eval₂_hom, refl } lemma eval₂_hom_monomial (f : R →+* S₁) (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : eval₂_hom f g (monomial d r) = f r * d.prod (λ i k, g i ^ k) := by simp only [monomial_eq, ring_hom.map_mul, eval₂_hom_C, finsupp.prod, ring_hom.map_prod, ring_hom.map_pow, eval₂_hom_X'] section local attribute [instance, priority 10] is_semiring_hom.comp lemma eval₂_comp_left {S₂} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p) : k (eval₂ f g p) = eval₂ (k.comp f) (k ∘ g) p := by apply mv_polynomial.induction_on p; simp [ eval₂_add, k.map_add, eval₂_mul, k.map_mul] {contextual := tt} end @[simp] lemma eval₂_eta (p : mv_polynomial σ R) : eval₂ C X p = p := by apply mv_polynomial.induction_on p; simp [eval₂_add, eval₂_mul] {contextual := tt} lemma eval₂_congr (g₁ g₂ : σ → S₁) (h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) : p.eval₂ f g₁ = p.eval₂ f g₂ := begin apply finset.sum_congr rfl, intros c hc, dsimp, congr' 1, apply finset.prod_congr rfl, intros i hi, dsimp, congr' 1, apply h hi, rwa finsupp.mem_support_iff at hc end @[simp] lemma eval₂_prod (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (∏ x in s, p x) = ∏ x in s, eval₂ f g (p x) := (s.prod_hom _).symm @[simp] lemma eval₂_sum (s : finset S₂) (p : S₂ → mv_polynomial σ R) : eval₂ f g (∑ x in s, p x) = ∑ x in s, eval₂ f g (p x) := (s.sum_hom _).symm attribute [to_additive] eval₂_prod lemma eval₂_assoc (q : S₂ → mv_polynomial σ R) (p : mv_polynomial S₂ R) : eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) := begin show _ = eval₂_hom f g (eval₂ C q p), rw eval₂_comp_left (eval₂_hom f g), congr' with a, simp, end end eval₂ section eval variables {f : σ → R} /-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/ def eval (f : σ → R) : mv_polynomial σ R →+* R := eval₂_hom (ring_hom.id _) f lemma eval_eq (x : σ → R) (f : mv_polynomial σ R) : eval x f = ∑ d in f.support, f.coeff d * ∏ i in d.support, x i ^ d i := rfl lemma eval_eq' [fintype σ] (x : σ → R) (f : mv_polynomial σ R) : eval x f = ∑ d in f.support, f.coeff d * ∏ i, x i ^ d i := eval₂_eq' (ring_hom.id R) x f lemma eval_monomial : eval f (monomial s a) = a * s.prod (λn e, f n ^ e) := eval₂_monomial _ _ @[simp] lemma eval_C : ∀ a, eval f (C a) = a := eval₂_C _ _ @[simp] lemma eval_X : ∀ n, eval f (X n) = f n := eval₂_X _ _ @[simp] lemma smul_eval (x) (p : mv_polynomial σ R) (s) : eval x (s • p) = s * eval x p := by rw [smul_eq_C_mul, (eval x).map_mul, eval_C] lemma eval_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : eval g (∑ i in s, f i) = ∑ i in s, eval g (f i) := (eval g).map_sum _ _ @[to_additive] lemma eval_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ R) (g : σ → R) : eval g (∏ i in s, f i) = ∏ i in s, eval g (f i) := (eval g).map_prod _ _ theorem eval_assoc {τ} (f : σ → mv_polynomial τ R) (g : τ → R) (p : mv_polynomial σ R) : eval (eval g ∘ f) p = eval g (eval₂ C f p) := begin rw eval₂_comp_left (eval g), unfold eval, simp only [coe_eval₂_hom], congr' with a, simp end end eval section map variables (f : R →+* S₁) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : mv_polynomial σ R →+* mv_polynomial σ S₁ := eval₂_hom (C.comp f) X @[simp] theorem map_monomial (s : σ →₀ ℕ) (a : R) : map f (monomial s a) = monomial s (f a) := (eval₂_monomial _ _).trans monomial_eq.symm @[simp] theorem map_C : ∀ (a : R), map f (C a : mv_polynomial σ R) = C (f a) := map_monomial _ _ @[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ R) = X n := eval₂_X _ _ theorem map_id : ∀ (p : mv_polynomial σ R), map (ring_hom.id R) p = p := eval₂_eta theorem map_map [comm_semiring S₂] (g : S₁ →+* S₂) (p : mv_polynomial σ R) : map g (map f p) = map (g.comp f) p := (eval₂_comp_left (map g) (C.comp f) X p).trans $ begin congr, { ext1 a, simp only [map_C, comp_app, ring_hom.coe_comp], }, { ext1 n, simp only [map_X, comp_app], } end theorem eval₂_eq_eval_map (g : σ → S₁) (p : mv_polynomial σ R) : p.eval₂ f g = eval g (map f p) := begin unfold map eval, simp only [coe_eval₂_hom], have h := eval₂_comp_left (eval₂_hom _ g), dsimp at h, rw h, congr, { ext1 a, simp only [coe_eval₂_hom, ring_hom.id_apply, comp_app, eval₂_C, ring_hom.coe_comp], }, { ext1 n, simp only [comp_app, eval₂_X], }, end lemma eval₂_comp_right {S₂} [comm_semiring S₂] (k : S₁ →+* S₂) (f : R →+* S₁) (g : σ → S₁) (p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, k.map_add, (map f).map_add, eval₂_add, hp, hq] }, { intros p s hp, rw [eval₂_mul, k.map_mul, (map f).map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] } end lemma map_eval₂ (f : R →+* S₁) (g : S₂ → mv_polynomial S₃ R) (p : mv_polynomial S₂ R) : map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, (map f).map_add, hp, hq, (map f).map_add, eval₂_add] }, { intros p s hp, rw [eval₂_mul, (map f).map_mul, hp, (map f).map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] } end lemma coeff_map (p : mv_polynomial σ R) : ∀ (m : σ →₀ ℕ), coeff m (map f p) = f (coeff m p) := begin apply mv_polynomial.induction_on p; clear p, { intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw f.map_zero }, { intros p q hp hq m, simp only [hp, hq, (map f).map_add, coeff_add], rw f.map_add }, { intros p i hp m, simp only [hp, (map f).map_mul, map_X], simp only [hp, mem_support_iff, coeff_mul_X'], split_ifs, {refl}, rw is_semiring_hom.map_zero f } end lemma map_injective (hf : function.injective f) : function.injective (map f : mv_polynomial σ R → mv_polynomial σ S₁) := begin intros p q h, simp only [ext_iff, coeff_map] at h ⊢, intro m, exact hf (h m), end @[simp] lemma eval_map (f : R →+* S₁) (g : σ → S₁) (p : mv_polynomial σ R) : eval g (map f p) = eval₂ f g p := by { apply mv_polynomial.induction_on p; { simp { contextual := tt } } } @[simp] lemma eval₂_map [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : eval₂ φ g (map f p) = eval₂ (φ.comp f) g p := by { rw [← eval_map, ← eval_map, map_map], } @[simp] lemma eval₂_hom_map_hom [comm_semiring S₂] (f : R →+* S₁) (g : σ → S₂) (φ : S₁ →+* S₂) (p : mv_polynomial σ R) : eval₂_hom φ g (map f p) = eval₂_hom (φ.comp f) g p := eval₂_map f g φ p @[simp] lemma constant_coeff_map (f : R →+* S₁) (φ : mv_polynomial σ R) : constant_coeff (mv_polynomial.map f φ) = f (constant_coeff φ) := coeff_map f φ 0 lemma constant_coeff_comp_map (f : R →+* S₁) : (constant_coeff : mv_polynomial σ S₁ →+* S₁).comp (mv_polynomial.map f) = f.comp constant_coeff := by { ext; simp } lemma support_map_subset (p : mv_polynomial σ R) : (map f p).support ⊆ p.support := begin intro x, simp only [mem_support_iff], contrapose!, change p.coeff x = 0 → (map f p).coeff x = 0, rw coeff_map, intro hx, rw hx, exact ring_hom.map_zero f end lemma support_map_of_injective (p : mv_polynomial σ R) {f : R →+* S₁} (hf : injective f) : (map f p).support = p.support := begin apply finset.subset.antisymm, { exact mv_polynomial.support_map_subset _ _ }, intros x hx, rw mem_support_iff, contrapose! hx, simp only [not_not, mem_support_iff], change (map f p).coeff x = 0 at hx, rw [coeff_map, ← f.map_zero] at hx, exact hf hx end lemma C_dvd_iff_map_hom_eq_zero (q : R →+* S₁) (r : R) (hr : ∀ r' : R, q r' = 0 ↔ r ∣ r') (φ : mv_polynomial σ R) : C r ∣ φ ↔ map q φ = 0 := begin rw [C_dvd_iff_dvd_coeff, mv_polynomial.ext_iff], simp only [coeff_map, ring_hom.coe_of, coeff_zero, hr], end lemma map_map_range_eq_iff (f : R →+* S₁) (g : S₁ → R) (hg : g 0 = 0) (φ : mv_polynomial σ S₁) : map f (finsupp.map_range g hg φ) = φ ↔ ∀ d, f (g (coeff d φ)) = coeff d φ := begin rw mv_polynomial.ext_iff, apply forall_congr, intro m, rw [coeff_map], apply eq_iff_eq_cancel_right.mpr, refl end end map section aeval /-! ### The algebra of multivariate polynomials -/ variables (f : σ → S₁) variables [algebra R S₁] [comm_semiring S₂] /-- A map `σ → S₁` where `S₁` is an algebra over `R` generates an `R`-algebra homomorphism from multivariate polynomials over `σ` to `S₁`. -/ def aeval : mv_polynomial σ R →ₐ[R] S₁ := { commutes' := λ r, eval₂_C _ _ _ .. eval₂_hom (algebra_map R S₁) f } theorem aeval_def (p : mv_polynomial σ R) : aeval f p = eval₂ (algebra_map R S₁) f p := rfl lemma aeval_eq_eval₂_hom (p : mv_polynomial σ R) : aeval f p = eval₂_hom (algebra_map R S₁) f p := rfl @[simp] lemma aeval_X (s : σ) : aeval f (X s : mv_polynomial _ R) = f s := eval₂_X _ _ _ @[simp] lemma aeval_C (r : R) : aeval f (C r) = algebra_map R S₁ r := eval₂_C _ _ _ theorem aeval_unique (φ : mv_polynomial σ R →ₐ[R] S₁) : φ = aeval (φ ∘ X) := by { ext i, simp } lemma comp_aeval {B : Type*} [comm_semiring B] [algebra R B] (φ : S₁ →ₐ[R] B) : φ.comp (aeval f) = aeval (λ i, φ (f i)) := by { ext i, simp } @[simp] lemma map_aeval {B : Type*} [comm_semiring B] (g : σ → S₁) (φ : S₁ →+* B) (p : mv_polynomial σ R) : φ (aeval g p) = (eval₂_hom (φ.comp (algebra_map R S₁)) (λ i, φ (g i)) p) := by { rw ← comp_eval₂_hom, refl } @[simp] lemma eval₂_hom_zero (f : R →+* S₂) (p : mv_polynomial σ R) : eval₂_hom f (0 : σ → S₂) p = f (constant_coeff p) := begin suffices : eval₂_hom f (0 : σ → S₂) = f.comp constant_coeff, from ring_hom.congr_fun this p, ext; simp end @[simp] lemma eval₂_hom_zero' (f : R →+* S₂) (p : mv_polynomial σ R) : eval₂_hom f (λ _, 0 : σ → S₂) p = f (constant_coeff p) := eval₂_hom_zero f p @[simp] lemma aeval_zero (p : mv_polynomial σ R) : aeval (0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) := eval₂_hom_zero (algebra_map R S₁) p @[simp] lemma aeval_zero' (p : mv_polynomial σ R) : aeval (λ _, 0 : σ → S₁) p = algebra_map _ _ (constant_coeff p) := aeval_zero p lemma aeval_monomial (g : σ → S₁) (d : σ →₀ ℕ) (r : R) : aeval g (monomial d r) = algebra_map _ _ r * d.prod (λ i k, g i ^ k) := eval₂_hom_monomial _ _ _ _ lemma eval₂_hom_eq_zero (f : R →+* S₂) (g : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, g i = 0) : eval₂_hom f g φ = 0 := begin rw [φ.as_sum, ring_hom.map_sum, finset.sum_eq_zero], intros d hd, obtain ⟨i, hi, hgi⟩ : ∃ i ∈ d.support, g i = 0 := h d (finsupp.mem_support_iff.mp hd), rw [eval₂_hom_monomial, finsupp.prod, finset.prod_eq_zero hi, mul_zero], rw [hgi, zero_pow], rwa [pos_iff_ne_zero, ← finsupp.mem_support_iff] end lemma aeval_eq_zero [algebra R S₂] (f : σ → S₂) (φ : mv_polynomial σ R) (h : ∀ d, φ.coeff d ≠ 0 → ∃ i ∈ d.support, f i = 0) : aeval f φ = 0 := eval₂_hom_eq_zero _ _ _ h end aeval end comm_semiring end mv_polynomial
75eaddf1f05f2d6f0fd51b86f5304f60fa02359a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/abelian/generator.lean
0b943135e7aa6b88e5ed22791a68136ccfe44f5c
[ "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,574
lean
/- Copyright (c) 2022 Markus Himmel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Markus Himmel -/ import category_theory.abelian.subobject import category_theory.limits.essentially_small import category_theory.preadditive.injective import category_theory.preadditive.generator import category_theory.abelian.opposite /-! # A complete abelian category with enough injectives and a separator has an injective coseparator > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Future work * Once we know that Grothendieck categories have enough injectives, we can use this to conclude that Grothendieck categories have an injective coseparator. ## References * [Peter J Freyd, *Abelian Categories* (Theorem 3.37)][freyd1964abelian] -/ open category_theory category_theory.limits opposite universes v u namespace category_theory.abelian variables {C : Type u} [category.{v} C] [abelian C] theorem has_injective_coseparator [has_limits C] [enough_injectives C] (G : C) (hG : is_separator G) : ∃ G : C, injective G ∧ is_coseparator G := begin haveI : well_powered C := well_powered_of_is_detector G hG.is_detector, haveI : has_products_of_shape (subobject (op G)) C := has_products_of_shape_of_small _ _, let T : C := injective.under (pi_obj (λ P : subobject (op G), unop P)), refine ⟨T, infer_instance, (preadditive.is_coseparator_iff _).2 (λ X Y f hf, _)⟩, refine (preadditive.is_separator_iff _).1 hG _ (λ h, _), suffices hh : factor_thru_image (h ≫ f) = 0, { rw [← limits.image.fac (h ≫ f), hh, zero_comp] }, let R := subobject.mk (factor_thru_image (h ≫ f)).op, let q₁ : image (h ≫ f) ⟶ unop R := (subobject.underlying_iso (factor_thru_image (h ≫ f)).op).unop.hom, let q₂ : unop (R : Cᵒᵖ) ⟶ pi_obj (λ P : subobject (op G), unop P) := section_ (pi.π (λ P : subobject (op G), unop P) R), let q : image (h ≫ f) ⟶ T := q₁ ≫ q₂ ≫ injective.ι _, exact zero_of_comp_mono q (by rw [← injective.comp_factor_thru q (limits.image.ι (h ≫ f)), limits.image.fac_assoc, category.assoc, hf, comp_zero]) end theorem has_projective_separator [has_colimits C] [enough_projectives C] (G : C) (hG : is_coseparator G) : ∃ G : C, projective G ∧ is_separator G := begin obtain ⟨T, hT₁, hT₂⟩ := has_injective_coseparator (op G) ((is_separator_op_iff _).2 hG), exactI ⟨unop T, infer_instance, (is_separator_unop_iff _).2 hT₂⟩ end end category_theory.abelian
e205dee8f592cd70ba7e1c53c5616bf554a4ae18
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/analysis/specific_limits.lean
32c58af2a28a239d299f336ab4e5beaa6a43ae4a
[ "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
34,743
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import algebra.geom_sum import order.filter.archimedean import order.iterate import topology.instances.ennreal import tactic.ring_exp import analysis.asymptotics.asymptotics /-! # A collection of specific limit computations -/ noncomputable theory open classical set function filter finset metric asymptotics open_locale classical topological_space nat big_operators uniformity nnreal ennreal variables {α : Type*} {β : Type*} {ι : Type*} lemma tendsto_norm_at_top_at_top : tendsto (norm : ℝ → ℝ) at_top at_top := tendsto_abs_at_top_at_top lemma summable_of_absolute_convergence_real {f : ℕ → ℝ} : (∃r, tendsto (λn, (∑ i in range n, abs (f i))) at_top (𝓝 r)) → summable f | ⟨r, hr⟩ := begin refine summable_of_summable_norm ⟨r, (has_sum_iff_tendsto_nat_of_nonneg _ _).2 _⟩, exact assume i, norm_nonneg _, simpa only using hr end lemma tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ)⁻¹) at_top (𝓝 0) := tendsto_inv_at_top_zero.comp tendsto_coe_nat_at_top_at_top lemma tendsto_const_div_at_top_nhds_0_nat (C : ℝ) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa only [mul_zero] using tendsto_const_nhds.mul tendsto_inverse_at_top_nhds_0_nat lemma nnreal.tendsto_inverse_at_top_nhds_0_nat : tendsto (λ n : ℕ, (n : ℝ≥0)⁻¹) at_top (𝓝 0) := by { rw ← nnreal.tendsto_coe, convert tendsto_inverse_at_top_nhds_0_nat, simp } lemma nnreal.tendsto_const_div_at_top_nhds_0_nat (C : ℝ≥0) : tendsto (λ n : ℕ, C / n) at_top (𝓝 0) := by simpa using tendsto_const_nhds.mul nnreal.tendsto_inverse_at_top_nhds_0_nat lemma tendsto_one_div_add_at_top_nhds_0_nat : tendsto (λ n : ℕ, 1 / ((n : ℝ) + 1)) at_top (𝓝 0) := suffices tendsto (λ n : ℕ, 1 / (↑(n + 1) : ℝ)) at_top (𝓝 0), by simpa, (tendsto_add_at_top_iff_nat 1).2 (tendsto_const_div_at_top_nhds_0_nat 1) /-! ### Powers -/ lemma tendsto_add_one_pow_at_top_at_top_of_pos [linear_ordered_semiring α] [archimedean α] {r : α} (h : 0 < r) : tendsto (λ n:ℕ, (r + 1)^n) at_top at_top := tendsto_at_top_at_top_of_monotone' (λ n m, pow_le_pow (le_add_of_nonneg_left (le_of_lt h))) $ not_bdd_above_iff.2 $ λ x, set.exists_range_iff.2 $ add_one_pow_unbounded_of_pos _ h lemma tendsto_pow_at_top_at_top_of_one_lt [linear_ordered_ring α] [archimedean α] {r : α} (h : 1 < r) : tendsto (λn:ℕ, r ^ n) at_top at_top := sub_add_cancel r 1 ▸ tendsto_add_one_pow_at_top_at_top_of_pos (sub_pos.2 h) lemma nat.tendsto_pow_at_top_at_top_of_one_lt {m : ℕ} (h : 1 < m) : tendsto (λn:ℕ, m ^ n) at_top at_top := nat.sub_add_cancel (le_of_lt h) ▸ tendsto_add_one_pow_at_top_at_top_of_pos (nat.sub_pos_of_lt h) lemma tendsto_norm_zero' {𝕜 : Type*} [normed_group 𝕜] : tendsto (norm : 𝕜 → ℝ) (𝓝[{x | x ≠ 0}] 0) (𝓝[set.Ioi 0] 0) := tendsto_norm_zero.inf $ tendsto_principal_principal.2 $ λ x hx, norm_pos_iff.2 hx lemma normed_field.tendsto_norm_inverse_nhds_within_0_at_top {𝕜 : Type*} [normed_field 𝕜] : tendsto (λ x:𝕜, ∥x⁻¹∥) (𝓝[{x | x ≠ 0}] 0) at_top := (tendsto_inv_zero_at_top.comp tendsto_norm_zero').congr $ λ x, (normed_field.norm_inv x).symm lemma tendsto_pow_at_top_nhds_0_of_lt_1 {𝕜 : Type*} [linear_ordered_field 𝕜] [archimedean 𝕜] [topological_space 𝕜] [order_topology 𝕜] {r : 𝕜} (h₁ : 0 ≤ r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := h₁.eq_or_lt.elim (assume : 0 = r, (tendsto_add_at_top_iff_nat 1).mp $ by simp [pow_succ, ← this, tendsto_const_nhds]) (assume : 0 < r, have tendsto (λn, (r⁻¹ ^ n)⁻¹) at_top (𝓝 0), from tendsto_inv_at_top_zero.comp (tendsto_pow_at_top_at_top_of_one_lt $ one_lt_inv this h₂), this.congr (λ n, by simp)) lemma tendsto_pow_at_top_nhds_within_0_of_lt_1 {𝕜 : Type*} [linear_ordered_field 𝕜] [archimedean 𝕜] [topological_space 𝕜] [order_topology 𝕜] {r : 𝕜} (h₁ : 0 < r) (h₂ : r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝[Ioi 0] 0) := tendsto_inf.2 ⟨tendsto_pow_at_top_nhds_0_of_lt_1 h₁.le h₂, tendsto_principal.2 $ eventually_of_forall $ λ n, pow_pos h₁ _⟩ lemma is_o_pow_pow_of_lt_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ < r₂) : is_o (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top := have H : 0 < r₂ := h₁.trans_lt h₂, is_o_of_tendsto (λ n hn, false.elim $ H.ne' $ pow_eq_zero hn) $ (tendsto_pow_at_top_nhds_0_of_lt_1 (div_nonneg h₁ (h₁.trans h₂.le)) ((div_lt_one H).2 h₂)).congr (λ n, div_pow _ _ _) lemma is_O_pow_pow_of_le_left {r₁ r₂ : ℝ} (h₁ : 0 ≤ r₁) (h₂ : r₁ ≤ r₂) : is_O (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top := h₂.eq_or_lt.elim (λ h, h ▸ is_O_refl _ _) (λ h, (is_o_pow_pow_of_lt_left h₁ h).is_O) lemma is_o_pow_pow_of_abs_lt_left {r₁ r₂ : ℝ} (h : abs r₁ < abs r₂) : is_o (λ n : ℕ, r₁ ^ n) (λ n, r₂ ^ n) at_top := begin refine (is_o.of_norm_left _).of_norm_right, exact (is_o_pow_pow_of_lt_left (abs_nonneg r₁) h).congr (pow_abs r₁) (pow_abs r₂) end /-- Various statements equivalent to the fact that `f n` grows exponentially slower than `R ^ n`. * 0: $f n = o(a ^ n)$ for some $-R < a < R$; * 1: $f n = o(a ^ n)$ for some $0 < a < R$; * 2: $f n = O(a ^ n)$ for some $-R < a < R$; * 3: $f n = O(a ^ n)$ for some $0 < a < R$; * 4: there exist `a < R` and `C` such that one of `C` and `R` is positive and $|f n| ≤ Ca^n$ for all `n`; * 5: there exists `0 < a < R` and a positive `C` such that $|f n| ≤ Ca^n$ for all `n`; * 6: there exists `a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`; * 7: there exists `0 < a < R` such that $|f n| ≤ a ^ n$ for sufficiently large `n`. NB: For backwards compatibility, if you add more items to the list, please append them at the end of the list. -/ lemma tfae_exists_lt_is_o_pow (f : ℕ → ℝ) (R : ℝ) : tfae [∃ a ∈ Ioo (-R) R, is_o f (pow a) at_top, ∃ a ∈ Ioo 0 R, is_o f (pow a) at_top, ∃ a ∈ Ioo (-R) R, is_O f (pow a) at_top, ∃ a ∈ Ioo 0 R, is_O f (pow a) at_top, ∃ (a < R) C (h₀ : 0 < C ∨ 0 < R), ∀ n, abs (f n) ≤ C * a ^ n, ∃ (a ∈ Ioo 0 R) (C > 0), ∀ n, abs (f n) ≤ C * a ^ n, ∃ a < R, ∀ᶠ n in at_top, abs (f n) ≤ a ^ n, ∃ a ∈ Ioo 0 R, ∀ᶠ n in at_top, abs (f n) ≤ a ^ n] := begin have A : Ico 0 R ⊆ Ioo (-R) R, from λ x hx, ⟨(neg_lt_zero.2 (hx.1.trans_lt hx.2)).trans_le hx.1, hx.2⟩, have B : Ioo 0 R ⊆ Ioo (-R) R := subset.trans Ioo_subset_Ico_self A, -- First we prove that 1-4 are equivalent using 2 → 3 → 4, 1 → 3, and 2 → 1 tfae_have : 1 → 3, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩, tfae_have : 2 → 1, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩, tfae_have : 3 → 2, { rintro ⟨a, ha, H⟩, rcases exists_between (abs_lt.2 ha) with ⟨b, hab, hbR⟩, exact ⟨b, ⟨(abs_nonneg a).trans_lt hab, hbR⟩, H.trans_is_o (is_o_pow_pow_of_abs_lt_left (hab.trans_le (le_abs_self b)))⟩ }, tfae_have : 2 → 4, from λ ⟨a, ha, H⟩, ⟨a, ha, H.is_O⟩, tfae_have : 4 → 3, from λ ⟨a, ha, H⟩, ⟨a, B ha, H⟩, -- Add 5 and 6 using 4 → 6 → 5 → 3 tfae_have : 4 → 6, { rintro ⟨a, ha, H⟩, rcases bound_of_is_O_nat_at_top H with ⟨C, hC₀, hC⟩, refine ⟨a, ha, C, hC₀, λ n, _⟩, simpa only [real.norm_eq_abs, abs_pow, abs_of_nonneg ha.1.le] using hC (pow_ne_zero n ha.1.ne') }, tfae_have : 6 → 5, from λ ⟨a, ha, C, H₀, H⟩, ⟨a, ha.2, C, or.inl H₀, H⟩, tfae_have : 5 → 3, { rintro ⟨a, ha, C, h₀, H⟩, rcases sign_cases_of_C_mul_pow_nonneg (λ n, (abs_nonneg _).trans (H n)) with rfl | ⟨hC₀, ha₀⟩, { obtain rfl : f = 0, by { ext n, simpa using H n }, simp only [lt_irrefl, false_or] at h₀, exact ⟨0, ⟨neg_lt_zero.2 h₀, h₀⟩, is_O_zero _ _⟩ }, exact ⟨a, A ⟨ha₀, ha⟩, is_O_of_le' _ (λ n, (H n).trans $ mul_le_mul_of_nonneg_left (le_abs_self _) hC₀.le)⟩ }, -- Add 7 and 8 using 2 → 8 → 7 → 3 tfae_have : 2 → 8, { rintro ⟨a, ha, H⟩, refine ⟨a, ha, (H.def zero_lt_one).mono (λ n hn, _)⟩, rwa [real.norm_eq_abs, real.norm_eq_abs, one_mul, abs_pow, abs_of_pos ha.1] at hn }, tfae_have : 8 → 7, from λ ⟨a, ha, H⟩, ⟨a, ha.2, H⟩, tfae_have : 7 → 3, { rintro ⟨a, ha, H⟩, have : 0 ≤ a, from nonneg_of_eventually_pow_nonneg (H.mono $ λ n, (abs_nonneg _).trans), refine ⟨a, A ⟨this, ha⟩, is_O.of_bound 1 _⟩, simpa only [real.norm_eq_abs, one_mul, abs_pow, abs_of_nonneg this] }, tfae_finish end lemma uniformity_basis_dist_pow_of_lt_1 {α : Type*} [metric_space α] {r : ℝ} (h₀ : 0 < r) (h₁ : r < 1) : (𝓤 α).has_basis (λ k : ℕ, true) (λ k, {p : α × α | dist p.1 p.2 < r ^ k}) := metric.mk_uniformity_basis (λ i _, pow_pos h₀ _) $ λ ε ε0, (exists_pow_lt_of_lt_one ε0 h₁).imp $ λ k hk, ⟨trivial, hk.le⟩ lemma geom_lt {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) {n : ℕ} (hn : 0 < n) (h : ∀ k < n, c * u k < u (k + 1)) : c ^ n * u 0 < u n := begin refine (monotone_mul_left_of_nonneg hc).seq_pos_lt_seq_of_le_of_lt hn _ _ h, { simp }, { simp [pow_succ, mul_assoc, le_refl] } end lemma geom_le {u : ℕ → ℝ} {c : ℝ} (hc : 0 ≤ c) (n : ℕ) (h : ∀ k < n, c * u k ≤ u (k + 1)) : c ^ n * u 0 ≤ u n := by refine (monotone_mul_left_of_nonneg hc).seq_le_seq n _ _ h; simp [pow_succ, mul_assoc, le_refl] /-- For any natural `k` and a real `r > 1` we have `n ^ k = o(r ^ n)` as `n → ∞`. -/ lemma is_o_pow_const_const_pow_of_one_lt {R : Type*} [normed_ring R] (k : ℕ) {r : ℝ} (hr : 1 < r) : is_o (λ n, n ^ k : ℕ → R) (λ n, r ^ n) at_top := begin have : tendsto (λ x : ℝ, x ^ k) (𝓝[Ioi 1] 1) (𝓝 1), from ((continuous_id.pow k).tendsto' (1 : ℝ) 1 (one_pow _)).mono_left inf_le_left, obtain ⟨r' : ℝ, hr' : r' ^ k < r, h1 : 1 < r'⟩ := ((this.eventually (gt_mem_nhds hr)).and self_mem_nhds_within).exists, have h0 : 0 ≤ r' := zero_le_one.trans h1.le, suffices : is_O _ (λ n : ℕ, (r' ^ k) ^ n) at_top, from this.trans_is_o (is_o_pow_pow_of_lt_left (pow_nonneg h0 _) hr'), conv in ((r' ^ _) ^ _) { rw [← pow_mul, mul_comm, pow_mul] }, suffices : ∀ n : ℕ, ∥(n : R)∥ ≤ (r' - 1)⁻¹ * ∥(1 : R)∥ * ∥r' ^ n∥, from (is_O_of_le' _ this).pow _, intro n, rw mul_right_comm, refine n.norm_cast_le.trans (mul_le_mul_of_nonneg_right _ (norm_nonneg _)), simpa [div_eq_inv_mul, real.norm_eq_abs, abs_of_nonneg h0] using n.cast_le_pow_div_sub h1 end /-- For a real `r > 1` we have `n = o(r ^ n)` as `n → ∞`. -/ lemma is_o_coe_const_pow_of_one_lt {R : Type*} [normed_ring R] {r : ℝ} (hr : 1 < r) : is_o (coe : ℕ → R) (λ n, r ^ n) at_top := by simpa only [pow_one] using is_o_pow_const_const_pow_of_one_lt 1 hr /-- If `∥r₁∥ < r₂`, then for any naturak `k` we have `n ^ k r₁ ^ n = o (r₂ ^ n)` as `n → ∞`. -/ lemma is_o_pow_const_mul_const_pow_const_pow_of_norm_lt {R : Type*} [normed_ring R] (k : ℕ) {r₁ : R} {r₂ : ℝ} (h : ∥r₁∥ < r₂) : is_o (λ n, n ^ k * r₁ ^ n : ℕ → R) (λ n, r₂ ^ n) at_top := begin by_cases h0 : r₁ = 0, { refine (is_o_zero _ _).congr' (mem_at_top_sets.2 $ ⟨1, λ n hn, _⟩) eventually_eq.rfl, simp [zero_pow (zero_lt_one.trans_le hn), h0] }, rw [← ne.def, ← norm_pos_iff] at h0, have A : is_o (λ n, n ^ k : ℕ → R) (λ n, (r₂ / ∥r₁∥) ^ n) at_top, from is_o_pow_const_const_pow_of_one_lt k ((one_lt_div h0).2 h), suffices : is_O (λ n, r₁ ^ n) (λ n, ∥r₁∥ ^ n) at_top, by simpa [div_mul_cancel _ (pow_pos h0 _).ne'] using A.mul_is_O this, exact is_O.of_bound 1 (by simpa using eventually_norm_pow_le r₁) end lemma tendsto_pow_const_div_const_pow_of_one_lt (k : ℕ) {r : ℝ} (hr : 1 < r) : tendsto (λ n, n ^ k / r ^ n : ℕ → ℝ) at_top (𝓝 0) := (is_o_pow_const_const_pow_of_one_lt k hr).tendsto_0 /-- If `|r| < 1`, then `n ^ k r ^ n` tends to zero for any natural `k`. -/ lemma tendsto_pow_const_mul_const_pow_of_abs_lt_one (k : ℕ) {r : ℝ} (hr : abs r < 1) : tendsto (λ n, n ^ k * r ^ n : ℕ → ℝ) at_top (𝓝 0) := begin by_cases h0 : r = 0, { exact tendsto_const_nhds.congr' (mem_at_top_sets.2 ⟨1, λ n hn, by simp [zero_lt_one.trans_le hn, h0]⟩) }, have hr' : 1 < (abs r)⁻¹, from one_lt_inv (abs_pos.2 h0) hr, rw tendsto_zero_iff_norm_tendsto_zero, simpa [div_eq_mul_inv] using tendsto_pow_const_div_const_pow_of_one_lt k hr' end /-- If a sequence `v` of real numbers satisfies `k * v n ≤ v (n+1)` with `1 < k`, then it goes to +∞. -/ lemma tendsto_at_top_of_geom_le {v : ℕ → ℝ} {c : ℝ} (h₀ : 0 < v 0) (hc : 1 < c) (hu : ∀ n, c * v n ≤ v (n + 1)) : tendsto v at_top at_top := tendsto_at_top_mono (λ n, geom_le (zero_le_one.trans hc.le) n (λ k hk, hu k)) $ (tendsto_pow_at_top_at_top_of_one_lt hc).at_top_mul_const h₀ lemma nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ≥0} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := nnreal.tendsto_coe.1 $ by simp only [nnreal.coe_pow, nnreal.coe_zero, tendsto_pow_at_top_nhds_0_of_lt_1 r.coe_nonneg hr] lemma ennreal.tendsto_pow_at_top_nhds_0_of_lt_1 {r : ℝ≥0∞} (hr : r < 1) : tendsto (λ n:ℕ, r^n) at_top (𝓝 0) := begin rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, rw [← ennreal.coe_zero], norm_cast at *, apply nnreal.tendsto_pow_at_top_nhds_0_of_lt_1 hr end /-- In a normed ring, the powers of an element x with `∥x∥ < 1` tend to zero. -/ lemma tendsto_pow_at_top_nhds_0_of_norm_lt_1 {R : Type*} [normed_ring R] {x : R} (h : ∥x∥ < 1) : tendsto (λ (n : ℕ), x ^ n) at_top (𝓝 0) := begin apply squeeze_zero_norm' (eventually_norm_pow_le x), exact tendsto_pow_at_top_nhds_0_of_lt_1 (norm_nonneg _) h, end lemma tendsto_pow_at_top_nhds_0_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : tendsto (λn:ℕ, r^n) at_top (𝓝 0) := tendsto_pow_at_top_nhds_0_of_norm_lt_1 h /-! ### Geometric series-/ section geometric lemma has_sum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := have r ≠ 1, from ne_of_lt h₂, have tendsto (λn, (r ^ n - 1) * (r - 1)⁻¹) at_top (𝓝 ((0 - 1) * (r - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_lt_1 h₁ h₂).sub tendsto_const_nhds).mul tendsto_const_nhds, have (λ n, (∑ i in range n, r ^ i)) = (λ n, geom_sum r n) := rfl, (has_sum_iff_tendsto_nat_of_nonneg (pow_nonneg h₁) _).mpr $ by simp [neg_inv, geom_sum_eq, div_eq_mul_inv, *] at * lemma summable_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, has_sum_geometric_of_lt_1 h₁ h₂⟩ lemma tsum_geometric_of_lt_1 {r : ℝ} (h₁ : 0 ≤ r) (h₂ : r < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := (has_sum_geometric_of_lt_1 h₁ h₂).tsum_eq lemma has_sum_geometric_two : has_sum (λn:ℕ, ((1:ℝ)/2) ^ n) 2 := by convert has_sum_geometric_of_lt_1 _ _; norm_num lemma summable_geometric_two : summable (λn:ℕ, ((1:ℝ)/2) ^ n) := ⟨_, has_sum_geometric_two⟩ lemma tsum_geometric_two : ∑'n:ℕ, ((1:ℝ)/2) ^ n = 2 := has_sum_geometric_two.tsum_eq lemma sum_geometric_two_le (n : ℕ) : ∑ (i : ℕ) in range n, (1 / (2 : ℝ)) ^ i ≤ 2 := begin have : ∀ i, 0 ≤ (1 / (2 : ℝ)) ^ i, { intro i, apply pow_nonneg, norm_num }, convert sum_le_tsum (range n) (λ i _, this i) summable_geometric_two, exact tsum_geometric_two.symm end lemma has_sum_geometric_two' (a : ℝ) : has_sum (λn:ℕ, (a / 2) / 2 ^ n) a := begin convert has_sum.mul_left (a / 2) (has_sum_geometric_of_lt_1 (le_of_lt one_half_pos) one_half_lt_one), { funext n, simp, refl, }, { norm_num } end lemma summable_geometric_two' (a : ℝ) : summable (λ n:ℕ, (a / 2) / 2 ^ n) := ⟨a, has_sum_geometric_two' a⟩ lemma tsum_geometric_two' (a : ℝ) : ∑' n:ℕ, (a / 2) / 2^n = a := (has_sum_geometric_two' a).tsum_eq lemma nnreal.has_sum_geometric {r : ℝ≥0} (hr : r < 1) : has_sum (λ n : ℕ, r ^ n) (1 - r)⁻¹ := begin apply nnreal.has_sum_coe.1, push_cast, rw [nnreal.coe_sub (le_of_lt hr)], exact has_sum_geometric_of_lt_1 r.coe_nonneg hr end lemma nnreal.summable_geometric {r : ℝ≥0} (hr : r < 1) : summable (λn:ℕ, r ^ n) := ⟨_, nnreal.has_sum_geometric hr⟩ lemma tsum_geometric_nnreal {r : ℝ≥0} (hr : r < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := (nnreal.has_sum_geometric hr).tsum_eq /-- The series `pow r` converges to `(1-r)⁻¹`. For `r < 1` the RHS is a finite number, and for `1 ≤ r` the RHS equals `∞`. -/ lemma ennreal.tsum_geometric (r : ℝ≥0∞) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := begin cases lt_or_le r 1 with hr hr, { rcases ennreal.lt_iff_exists_coe.1 hr with ⟨r, rfl, hr'⟩, norm_cast at *, convert ennreal.tsum_coe_eq (nnreal.has_sum_geometric hr), rw [ennreal.coe_inv $ ne_of_gt $ nnreal.sub_pos.2 hr] }, { rw [ennreal.sub_eq_zero_of_le hr, ennreal.inv_zero, ennreal.tsum_eq_supr_nat, supr_eq_top], refine λ a ha, (ennreal.exists_nat_gt (lt_top_iff_ne_top.1 ha)).imp (λ n hn, lt_of_lt_of_le hn _), have : ∀ k:ℕ, 1 ≤ r^k, by simpa using canonically_ordered_semiring.pow_le_pow_of_le_left hr, calc (n:ℝ≥0∞) = (∑ i in range n, 1) : by rw [sum_const, nsmul_one, card_range] ... ≤ ∑ i in range n, r ^ i : sum_le_sum (λ k _, this k) } end variables {K : Type*} [normed_field K] {ξ : K} lemma has_sum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : has_sum (λn:ℕ, ξ ^ n) (1 - ξ)⁻¹ := begin have xi_ne_one : ξ ≠ 1, by { contrapose! h, simp [h] }, have A : tendsto (λn, (ξ ^ n - 1) * (ξ - 1)⁻¹) at_top (𝓝 ((0 - 1) * (ξ - 1)⁻¹)), from ((tendsto_pow_at_top_nhds_0_of_norm_lt_1 h).sub tendsto_const_nhds).mul tendsto_const_nhds, have B : (λ n, (∑ i in range n, ξ ^ i)) = (λ n, geom_sum ξ n) := rfl, rw [has_sum_iff_tendsto_nat_of_summable_norm, B], { simpa [geom_sum_eq, xi_ne_one, neg_inv, div_eq_mul_inv] using A }, { simp [normed_field.norm_pow, summable_geometric_of_lt_1 (norm_nonneg _) h] } end lemma summable_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : summable (λn:ℕ, ξ ^ n) := ⟨_, has_sum_geometric_of_norm_lt_1 h⟩ lemma tsum_geometric_of_norm_lt_1 (h : ∥ξ∥ < 1) : ∑'n:ℕ, ξ ^ n = (1 - ξ)⁻¹ := (has_sum_geometric_of_norm_lt_1 h).tsum_eq lemma has_sum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : has_sum (λn:ℕ, r ^ n) (1 - r)⁻¹ := has_sum_geometric_of_norm_lt_1 h lemma summable_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : summable (λn:ℕ, r ^ n) := summable_geometric_of_norm_lt_1 h lemma tsum_geometric_of_abs_lt_1 {r : ℝ} (h : abs r < 1) : ∑'n:ℕ, r ^ n = (1 - r)⁻¹ := tsum_geometric_of_norm_lt_1 h /-- A geometric series in a normed field is summable iff the norm of the common ratio is less than one. -/ @[simp] lemma summable_geometric_iff_norm_lt_1 : summable (λ n : ℕ, ξ ^ n) ↔ ∥ξ∥ < 1 := begin refine ⟨λ h, _, summable_geometric_of_norm_lt_1⟩, obtain ⟨k : ℕ, hk : dist (ξ ^ k) 0 < 1⟩ := (h.tendsto_cofinite_zero.eventually (ball_mem_nhds _ zero_lt_one)).exists, simp only [normed_field.norm_pow, dist_zero_right] at hk, rw [← one_pow k] at hk, exact lt_of_pow_lt_pow _ zero_le_one hk end end geometric section mul_geometric lemma summable_norm_pow_mul_geometric_of_norm_lt_1 {R : Type*} [normed_ring R] (k : ℕ) {r : R} (hr : ∥r∥ < 1) : summable (λ n : ℕ, ∥(n ^ k * r ^ n : R)∥) := begin rcases exists_between hr with ⟨r', hrr', h⟩, exact summable_of_is_O_nat _ (summable_geometric_of_lt_1 ((norm_nonneg _).trans hrr'.le) h) (is_o_pow_const_mul_const_pow_const_pow_of_norm_lt _ hrr').is_O.norm_left end lemma summable_pow_mul_geometric_of_norm_lt_1 {R : Type*} [normed_ring R] [complete_space R] (k : ℕ) {r : R} (hr : ∥r∥ < 1) : summable (λ n, n ^ k * r ^ n : ℕ → R) := summable_of_summable_norm $ summable_norm_pow_mul_geometric_of_norm_lt_1 _ hr /-- If `∥r∥ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`, `has_sum` version. -/ lemma has_sum_coe_mul_geometric_of_norm_lt_1 {𝕜 : Type*} [normed_field 𝕜] [complete_space 𝕜] {r : 𝕜} (hr : ∥r∥ < 1) : has_sum (λ n, n * r ^ n : ℕ → 𝕜) (r / (1 - r) ^ 2) := begin have A : summable (λ n, n * r ^ n : ℕ → 𝕜), by simpa using summable_pow_mul_geometric_of_norm_lt_1 1 hr, have B : has_sum (pow r : ℕ → 𝕜) (1 - r)⁻¹, from has_sum_geometric_of_norm_lt_1 hr, refine A.has_sum_iff.2 _, have hr' : r ≠ 1, by { rintro rfl, simpa [lt_irrefl] using hr }, set s : 𝕜 := ∑' n : ℕ, n * r ^ n, calc s = (1 - r) * s / (1 - r) : (mul_div_cancel_left _ (sub_ne_zero.2 hr'.symm)).symm ... = (s - r * s) / (1 - r) : by rw [sub_mul, one_mul] ... = ((0 : ℕ) * r ^ 0 + (∑' n : ℕ, (n + 1) * r ^ (n + 1)) - r * s) / (1 - r) : by { congr, exact tsum_eq_zero_add A } ... = (r * (∑' n : ℕ, (n + 1) * r ^ n) - r * s) / (1 - r) : by simp [pow_succ, mul_left_comm _ r, tsum_mul_left] ... = r / (1 - r) ^ 2 : by simp [add_mul, tsum_add A B.summable, mul_add, B.tsum_eq, ← div_eq_mul_inv, pow_two, div_div_eq_div_mul] end /-- If `∥r∥ < 1`, then `∑' n : ℕ, n * r ^ n = r / (1 - r) ^ 2`. -/ lemma tsum_coe_mul_geometric_of_norm_lt_1 {𝕜 : Type*} [normed_field 𝕜] [complete_space 𝕜] {r : 𝕜} (hr : ∥r∥ < 1) : (∑' n : ℕ, n * r ^ n : 𝕜) = (r / (1 - r) ^ 2) := (has_sum_coe_mul_geometric_of_norm_lt_1 hr).tsum_eq end mul_geometric /-! ### Sequences with geometrically decaying distance in metric spaces In this paragraph, we discuss sequences in metric spaces or emetric spaces for which the distance between two consecutive terms decays geometrically. We show that such sequences are Cauchy sequences, and bound their distances to the limit. We also discuss series with geometrically decaying terms. -/ section edist_le_geometric variables [emetric_space α] (r C : ℝ≥0∞) (hr : r < 1) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C * r^n) include hr hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, `C ≠ ∞`, `r < 1`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric : cauchy_seq f := begin refine cauchy_seq_of_edist_le_of_tsum_ne_top _ hu _, rw [ennreal.tsum_mul_left, ennreal.tsum_geometric], refine ennreal.mul_ne_top hC (ennreal.inv_ne_top.2 _), exact ne_of_gt (ennreal.zero_lt_sub_iff_lt.2 hr) end omit hr hC /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ (C * r^n) / (1 - r) := begin convert edist_le_tsum_of_edist_le_of_tendsto _ hu ha _, simp only [pow_add, ennreal.tsum_mul_left, ennreal.tsum_geometric, div_eq_mul_inv, mul_assoc] end /-- If `edist (f n) (f (n+1))` is bounded by `C * r^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma edist_le_of_edist_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ C / (1 - r) := by simpa only [pow_zero, mul_one] using edist_le_of_edist_le_geometric_of_tendsto r C hu ha 0 end edist_le_geometric section edist_le_geometric_two variables [emetric_space α] (C : ℝ≥0∞) (hC : C ≠ ⊤) {f : ℕ → α} (hu : ∀n, edist (f n) (f (n+1)) ≤ C / 2^n) {a : α} (ha : tendsto f at_top (𝓝 a)) include hC hu /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then `f` is a Cauchy sequence.-/ lemma cauchy_seq_of_edist_le_geometric_two : cauchy_seq f := begin simp only [div_eq_mul_inv, ennreal.inv_pow] at hu, refine cauchy_seq_of_edist_le_geometric 2⁻¹ C _ hC hu, simp [ennreal.one_lt_two] end omit hC include ha /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f n` to the limit of `f` is bounded above by `2 * C * 2^-n`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto (n : ℕ) : edist (f n) a ≤ 2 * C / 2^n := begin simp only [div_eq_mul_inv, ennreal.inv_pow] at *, rw [mul_assoc, mul_comm], convert edist_le_of_edist_le_geometric_of_tendsto 2⁻¹ C hu ha n, rw [ennreal.one_sub_inv_two, ennreal.inv_inv] end /-- If `edist (f n) (f (n+1))` is bounded by `C * 2^-n`, then the distance from `f 0` to the limit of `f` is bounded above by `2 * C`. -/ lemma edist_le_of_edist_le_geometric_two_of_tendsto₀: edist (f 0) a ≤ 2 * C := by simpa only [pow_zero, div_eq_mul_inv, ennreal.inv_one, mul_one] using edist_le_of_edist_le_geometric_two_of_tendsto C hu ha 0 end edist_le_geometric_two section le_geometric variables [metric_space α] {r C : ℝ} (hr : r < 1) {f : ℕ → α} (hu : ∀n, dist (f n) (f (n+1)) ≤ C * r^n) include hr hu lemma aux_has_sum_of_le_geometric : has_sum (λ n : ℕ, C * r^n) (C / (1 - r)) := begin rcases sign_cases_of_C_mul_pow_nonneg (λ n, dist_nonneg.trans (hu n)) with rfl | ⟨C₀, r₀⟩, { simp [has_sum_zero] }, { refine has_sum.mul_left C _, simpa using has_sum_geometric_of_lt_1 r₀ hr } end variables (r C) /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then `f` is a Cauchy sequence. Note that this lemma does not assume `0 ≤ C` or `0 ≤ r`. -/ lemma cauchy_seq_of_le_geometric : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f n` to the limit of `f` is bounded above by `C * r^n / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C / (1 - r) := (aux_has_sum_of_le_geometric hr hu).tsum_eq ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu ⟨_, aux_has_sum_of_le_geometric hr hu⟩ ha /-- If `dist (f n) (f (n+1))` is bounded by `C * r^n`, `r < 1`, then the distance from `f 0` to the limit of `f` is bounded above by `C / (1 - r)`. -/ lemma dist_le_of_le_geometric_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ (C * r^n) / (1 - r) := begin have := aux_has_sum_of_le_geometric hr hu, convert dist_le_tsum_of_dist_le_of_tendsto _ hu ⟨_, this⟩ ha n, simp only [pow_add, mul_left_comm C, mul_div_right_comm], rw [mul_comm], exact (this.mul_left _).tsum_eq.symm end omit hr hu variable (hu₂ : ∀ n, dist (f n) (f (n+1)) ≤ (C / 2) / 2^n) /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then `f` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_geometric_two : cauchy_seq f := cauchy_seq_of_dist_le_of_summable _ hu₂ $ ⟨_, has_sum_geometric_two' C⟩ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f 0` to the limit of `f` is bounded above by `C`. -/ lemma dist_le_of_le_geometric_two_of_tendsto₀ {a : α} (ha : tendsto f at_top (𝓝 a)) : dist (f 0) a ≤ C := (tsum_geometric_two' C) ▸ dist_le_tsum_of_dist_le_of_tendsto₀ _ hu₂ (summable_geometric_two' C) ha include hu₂ /-- If `dist (f n) (f (n+1))` is bounded by `(C / 2) / 2^n`, then the distance from `f n` to the limit of `f` is bounded above by `C / 2^n`. -/ lemma dist_le_of_le_geometric_two_of_tendsto {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : dist (f n) a ≤ C / 2^n := begin convert dist_le_tsum_of_dist_le_of_tendsto _ hu₂ (summable_geometric_two' C) ha n, simp only [add_comm n, pow_add, ← div_div_eq_div_mul], symmetry, exact ((has_sum_geometric_two' C).div_const _).tsum_eq end end le_geometric section summable_le_geometric variables [normed_group α] {r C : ℝ} {f : ℕ → α} lemma dist_partial_sum_le_of_le_geometric (hf : ∀n, ∥f n∥ ≤ C * r^n) (n : ℕ) : dist (∑ i in range n, f i) (∑ i in range (n+1), f i) ≤ C * r ^ n := begin rw [sum_range_succ, dist_eq_norm, ← norm_neg], convert hf n, rw [neg_sub, add_sub_cancel] end /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` form a Cauchy sequence. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma cauchy_seq_finset_of_geometric_bound (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) : cauchy_seq (λ s : finset (ℕ), ∑ x in s, f x) := cauchy_seq_finset_of_norm_bounded _ (aux_has_sum_of_le_geometric hr (dist_partial_sum_le_of_le_geometric hf)).summable hf /-- If `∥f n∥ ≤ C * r ^ n` for all `n : ℕ` and some `r < 1`, then the partial sums of `f` are within distance `C * r ^ n / (1 - r)` of the sum of the series. This lemma does not assume `0 ≤ r` or `0 ≤ C`. -/ lemma norm_sub_le_of_geometric_bound_of_has_sum (hr : r < 1) (hf : ∀n, ∥f n∥ ≤ C * r^n) {a : α} (ha : has_sum f a) (n : ℕ) : ∥(∑ x in finset.range n, f x) - a∥ ≤ (C * r ^ n) / (1 - r) := begin rw ← dist_eq_norm, apply dist_le_of_le_geometric_of_tendsto r C hr (dist_partial_sum_le_of_le_geometric hf), exact ha.tendsto_sum_nat end end summable_le_geometric section normed_ring_geometric variables {R : Type*} [normed_ring R] [complete_space R] open normed_space /-- A geometric series in a complete normed ring is summable. Proved above (same name, different namespace) for not-necessarily-complete normed fields. -/ lemma normed_ring.summable_geometric_of_norm_lt_1 (x : R) (h : ∥x∥ < 1) : summable (λ (n:ℕ), x ^ n) := begin have h1 : summable (λ (n:ℕ), ∥x∥ ^ n) := summable_geometric_of_lt_1 (norm_nonneg _) h, refine summable_of_norm_bounded_eventually _ h1 _, rw nat.cofinite_eq_at_top, exact eventually_norm_pow_le x, end /-- Bound for the sum of a geometric series in a normed ring. This formula does not assume that the normed ring satisfies the axiom `∥1∥ = 1`. -/ lemma normed_ring.tsum_geometric_of_norm_lt_1 (x : R) (h : ∥x∥ < 1) : ∥∑' n:ℕ, x ^ n∥ ≤ ∥(1:R)∥ - 1 + (1 - ∥x∥)⁻¹ := begin rw tsum_eq_zero_add (normed_ring.summable_geometric_of_norm_lt_1 x h), simp only [pow_zero], refine le_trans (norm_add_le _ _) _, have : ∥∑' b : ℕ, (λ n, x ^ (n + 1)) b∥ ≤ (1 - ∥x∥)⁻¹ - 1, { refine tsum_of_norm_bounded _ (λ b, norm_pow_le' _ (nat.succ_pos b)), convert (has_sum_nat_add_iff' 1).mpr (has_sum_geometric_of_lt_1 (norm_nonneg x) h), simp }, linarith end lemma geom_series_mul_neg (x : R) (h : ∥x∥ < 1) : (∑' i:ℕ, x ^ i) * (1 - x) = 1 := begin have := ((normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_right (1 - x)), refine tendsto_nhds_unique this.tendsto_sum_nat _, have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (𝓝 1), { simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) }, convert ← this, ext n, rw [←geom_sum_mul_neg, geom_sum_def, finset.sum_mul], end lemma mul_neg_geom_series (x : R) (h : ∥x∥ < 1) : (1 - x) * ∑' i:ℕ, x ^ i = 1 := begin have := (normed_ring.summable_geometric_of_norm_lt_1 x h).has_sum.mul_left (1 - x), refine tendsto_nhds_unique this.tendsto_sum_nat _, have : tendsto (λ (n : ℕ), 1 - x ^ n) at_top (nhds 1), { simpa using tendsto_const_nhds.sub (tendsto_pow_at_top_nhds_0_of_norm_lt_1 h) }, convert ← this, ext n, rw [←mul_neg_geom_sum, geom_sum_def, finset.mul_sum] end end normed_ring_geometric /-! ### Positive sequences with small sums on encodable types -/ /-- For any positive `ε`, define on an encodable type a positive sequence with sum less than `ε` -/ def pos_sum_of_encodable {ε : ℝ} (hε : 0 < ε) (ι) [encodable ι] : {ε' : ι → ℝ // (∀ i, 0 < ε' i) ∧ ∃ c, has_sum ε' c ∧ c ≤ ε} := begin let f := λ n, (ε / 2) / 2 ^ n, have hf : has_sum f ε := has_sum_geometric_two' _, have f0 : ∀ n, 0 < f n := λ n, div_pos (half_pos hε) (pow_pos zero_lt_two _), refine ⟨f ∘ encodable.encode, λ i, f0 _, _⟩, rcases hf.summable.comp_injective (@encodable.encode_injective ι _) with ⟨c, hg⟩, refine ⟨c, hg, has_sum_le_inj _ (@encodable.encode_injective ι _) _ _ hg hf⟩, { assume i _, exact le_of_lt (f0 _) }, { assume n, exact le_refl _ } end namespace nnreal theorem exists_pos_sum_of_encodable {ε : ℝ≥0} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ ∃c, has_sum ε' c ∧ c < ε := let ⟨a, a0, aε⟩ := exists_between hε in let ⟨ε', hε', c, hc, hcε⟩ := pos_sum_of_encodable a0 ι in ⟨ λi, ⟨ε' i, le_of_lt $ hε' i⟩, assume i, nnreal.coe_lt_coe.2 $ hε' i, ⟨c, has_sum_le (assume i, le_of_lt $ hε' i) has_sum_zero hc ⟩, nnreal.has_sum_coe.1 hc, lt_of_le_of_lt (nnreal.coe_le_coe.1 hcε) aε ⟩ end nnreal namespace ennreal theorem exists_pos_sum_of_encodable {ε : ℝ≥0∞} (hε : 0 < ε) (ι) [encodable ι] : ∃ ε' : ι → ℝ≥0, (∀ i, 0 < ε' i) ∧ ∑' i, (ε' i : ℝ≥0∞) < ε := begin rcases exists_between hε with ⟨r, h0r, hrε⟩, rcases lt_iff_exists_coe.1 hrε with ⟨x, rfl, hx⟩, rcases nnreal.exists_pos_sum_of_encodable (coe_lt_coe.1 h0r) ι with ⟨ε', hp, c, hc, hcr⟩, exact ⟨ε', hp, (ennreal.tsum_coe_eq hc).symm ▸ lt_trans (coe_lt_coe.2 hcr) hrε⟩ end end ennreal /-! ### Factorial -/ lemma factorial_tendsto_at_top : tendsto nat.factorial at_top at_top := tendsto_at_top_at_top_of_monotone nat.monotone_factorial (λ n, ⟨n, n.self_le_factorial⟩) lemma tendsto_factorial_div_pow_self_at_top : tendsto (λ n, n! / n^n : ℕ → ℝ) at_top (𝓝 0) := tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds (tendsto_const_div_at_top_nhds_0_nat 1) (eventually_of_forall $ λ n, div_nonneg (by exact_mod_cast n.factorial_pos.le) (pow_nonneg (by exact_mod_cast n.zero_le) _)) begin refine (eventually_gt_at_top 0).mono (λ n hn, _), rcases nat.exists_eq_succ_of_ne_zero hn.ne.symm with ⟨k, rfl⟩, rw [← prod_range_add_one_eq_factorial, pow_eq_prod_const, div_eq_mul_inv, ← inv_eq_one_div, prod_nat_cast, nat.cast_succ, ← prod_inv_distrib', ← prod_mul_distrib, finset.prod_range_succ'], simp only [prod_range_succ', one_mul, nat.cast_add, zero_add, nat.cast_one], refine mul_le_of_le_one_left (inv_nonneg.mpr $ by exact_mod_cast hn.le) (prod_le_one _ _); intros x hx; rw finset.mem_range at hx, { refine mul_nonneg _ (inv_nonneg.mpr _); norm_cast; linarith }, { refine (div_le_one $ by exact_mod_cast hn).mpr _, norm_cast, linarith } end
edc72e1ba8b77f05f63e51d1d571dad6751a84ee
37da0369b6c03e380e057bf680d81e6c9fdf9219
/hott/algebra/bundled.hlean
a03ddaeb3e411e6e774721a491539c75dcad6ea2
[ "Apache-2.0" ]
permissive
kodyvajjha/lean2
72b120d95c3a1d77f54433fa90c9810e14a931a4
227fcad22ab2bc27bb7471be7911075d101ba3f9
refs/heads/master
1,627,157,512,295
1,501,855,676,000
1,504,809,427,000
109,317,326
0
0
null
1,509,839,253,000
1,509,655,713,000
C++
UTF-8
Lean
false
false
7,078
hlean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Bundled structures -/ import algebra.ring open algebra pointed is_trunc namespace algebra structure Semigroup := (carrier : Type) (struct : semigroup carrier) attribute Semigroup.carrier [coercion] attribute Semigroup.struct [instance] structure CommSemigroup := (carrier : Type) (struct : comm_semigroup carrier) attribute CommSemigroup.carrier [coercion] attribute CommSemigroup.struct [instance] structure Monoid := (carrier : Type) (struct : monoid carrier) attribute Monoid.carrier [coercion] attribute Monoid.struct [instance] structure CommMonoid := (carrier : Type) (struct : comm_monoid carrier) attribute CommMonoid.carrier [coercion] attribute CommMonoid.struct [instance] structure Group := (carrier : Type) (struct' : group carrier) attribute Group.struct' [instance] section local attribute Group.carrier [coercion] definition pSet_of_Group [constructor] [reducible] [coercion] (G : Group) : Set* := ptrunctype.mk (Group.carrier G) !semigroup.is_set_carrier 1 end definition Group.struct [instance] [priority 2000] (G : Group) : group G := Group.struct' G attribute algebra._trans_of_pSet_of_Group [unfold 1] attribute algebra._trans_of_pSet_of_Group_1 algebra._trans_of_pSet_of_Group_2 [constructor] definition pType_of_Group [reducible] [constructor] (G : Group) : Type* := G definition Set_of_Group [reducible] [constructor] (G : Group) : Set := G definition AddGroup : Type := Group definition pSet_of_AddGroup [constructor] [reducible] [coercion] (G : AddGroup) : Set* := pSet_of_Group G definition AddGroup.mk [constructor] [reducible] (G : Type) (H : add_group G) : AddGroup := Group.mk G H definition AddGroup.struct [reducible] [instance] [priority 2000] (G : AddGroup) : add_group G := Group.struct G attribute algebra._trans_of_pSet_of_AddGroup [unfold 1] attribute algebra._trans_of_pSet_of_AddGroup_1 algebra._trans_of_pSet_of_AddGroup_2 [constructor] definition pType_of_AddGroup [reducible] [constructor] : AddGroup → Type* := algebra._trans_of_pSet_of_AddGroup_1 definition Set_of_AddGroup [reducible] [constructor] : AddGroup → Set := algebra._trans_of_pSet_of_AddGroup_2 structure AbGroup := (carrier : Type) (struct' : ab_group carrier) attribute AbGroup.struct' [instance] section local attribute AbGroup.carrier [coercion] definition Group_of_AbGroup [coercion] [constructor] (G : AbGroup) : Group := Group.mk G _ end definition AbGroup.struct [instance] [priority 2000] (G : AbGroup) : ab_group G := AbGroup.struct' G attribute algebra._trans_of_Group_of_AbGroup_1 algebra._trans_of_Group_of_AbGroup algebra._trans_of_Group_of_AbGroup_3 [constructor] attribute algebra._trans_of_Group_of_AbGroup_2 [unfold 1] definition AddAbGroup : Type := AbGroup definition AddGroup_of_AddAbGroup [coercion] [constructor] (G : AddAbGroup) : AddGroup := Group_of_AbGroup G definition AddAbGroup.struct [reducible] [instance] [priority 2000] (G : AddAbGroup) : add_ab_group G := AbGroup.struct G definition AddAbGroup.mk [constructor] [reducible] (G : Type) (H : add_ab_group G) : AddAbGroup := AbGroup.mk G H attribute algebra._trans_of_AddGroup_of_AddAbGroup_1 algebra._trans_of_AddGroup_of_AddAbGroup algebra._trans_of_AddGroup_of_AddAbGroup_3 [constructor] attribute algebra._trans_of_AddGroup_of_AddAbGroup_2 [unfold 1] -- structure AddSemigroup := -- (carrier : Type) (struct : add_semigroup carrier) -- attribute AddSemigroup.carrier [coercion] -- attribute AddSemigroup.struct [instance] -- structure AddCommSemigroup := -- (carrier : Type) (struct : add_comm_semigroup carrier) -- attribute AddCommSemigroup.carrier [coercion] -- attribute AddCommSemigroup.struct [instance] -- structure AddMonoid := -- (carrier : Type) (struct : add_monoid carrier) -- attribute AddMonoid.carrier [coercion] -- attribute AddMonoid.struct [instance] -- structure AddCommMonoid := -- (carrier : Type) (struct : add_comm_monoid carrier) -- attribute AddCommMonoid.carrier [coercion] -- attribute AddCommMonoid.struct [instance] -- structure AddGroup := -- (carrier : Type) (struct : add_group carrier) -- attribute AddGroup.carrier [coercion] -- attribute AddGroup.struct [instance] -- structure AddAbGroup := -- (carrier : Type) (struct : add_ab_group carrier) -- attribute AddAbGroup.carrier [coercion] -- attribute AddAbGroup.struct [instance] -- some bundled infinity-structures structure InfGroup := (carrier : Type) (struct' : inf_group carrier) attribute InfGroup.struct' [instance] section local attribute InfGroup.carrier [coercion] definition pType_of_InfGroup [constructor] [reducible] [coercion] (G : InfGroup) : Type* := pType.mk G 1 end attribute algebra._trans_of_pType_of_InfGroup [unfold 1] definition InfGroup.struct [instance] [priority 2000] (G : InfGroup) : inf_group G := InfGroup.struct' G definition AddInfGroup : Type := InfGroup definition pType_of_AddInfGroup [constructor] [reducible] [coercion] (G : AddInfGroup) : Type* := pType_of_InfGroup G definition AddInfGroup.mk [constructor] [reducible] (G : Type) (H : add_inf_group G) : AddInfGroup := InfGroup.mk G H definition AddInfGroup.struct [reducible] (G : AddInfGroup) : add_inf_group G := InfGroup.struct G attribute algebra._trans_of_pType_of_AddInfGroup [unfold 1] structure AbInfGroup := (carrier : Type) (struct' : ab_inf_group carrier) attribute AbInfGroup.struct' [instance] section local attribute AbInfGroup.carrier [coercion] definition InfGroup_of_AbInfGroup [coercion] [constructor] (G : AbInfGroup) : InfGroup := InfGroup.mk G _ end definition AbInfGroup.struct [instance] [priority 2000] (G : AbInfGroup) : ab_inf_group G := AbInfGroup.struct' G attribute algebra._trans_of_InfGroup_of_AbInfGroup_1 [constructor] attribute algebra._trans_of_InfGroup_of_AbInfGroup [unfold 1] definition AddAbInfGroup : Type := AbInfGroup definition AddInfGroup_of_AddAbInfGroup [coercion] [constructor] (G : AddAbInfGroup) : AddInfGroup := InfGroup_of_AbInfGroup G definition AddAbInfGroup.struct [reducible] [instance] [priority 2000] (G : AddAbInfGroup) : add_ab_inf_group G := AbInfGroup.struct G definition AddAbInfGroup.mk [constructor] [reducible] (G : Type) (H : add_ab_inf_group G) : AddAbInfGroup := AbInfGroup.mk G H attribute algebra._trans_of_AddInfGroup_of_AddAbInfGroup_1 [constructor] attribute algebra._trans_of_AddInfGroup_of_AddAbInfGroup [unfold 1] definition InfGroup_of_Group [constructor] (G : Group) : InfGroup := InfGroup.mk G _ definition AddInfGroup_of_AddGroup [constructor] (G : AddGroup) : AddInfGroup := AddInfGroup.mk G _ definition AbInfGroup_of_AbGroup [constructor] (G : AbGroup) : AbInfGroup := AbInfGroup.mk G _ definition AddAbInfGroup_of_AddAbGroup [constructor] (G : AddAbGroup) : AddAbInfGroup := AddAbInfGroup.mk G _ /- rings -/ structure Ring := (carrier : Type) (struct : ring carrier) attribute Ring.carrier [coercion] attribute Ring.struct [instance] end algebra
7474cfe88edf11a5fd0124a7feb951e829c49012
54d7e71c3616d331b2ec3845d31deb08f3ff1dea
/tests/lean/defeq_simp3.lean
188622f426d60102e16e516400da34662c146dad
[ "Apache-2.0" ]
permissive
pachugupta/lean
6f3305c4292288311cc4ab4550060b17d49ffb1d
0d02136a09ac4cf27b5c88361750e38e1f485a1a
refs/heads/master
1,611,110,653,606
1,493,130,117,000
1,493,167,649,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
476
lean
attribute [reducible] definition nat_has_add2 : has_add nat := has_add.mk (λ x y : nat, x + y) attribute [reducible] definition nat_has_add3 : nat → has_add nat := λ n, has_add.mk (λ x y : nat, x + y) open tactic set_option pp.all true example (a b : nat) (H : (λ x : nat, @add nat nat_has_add2 a x) = (λ x : nat, @add nat (nat_has_add3 x) a b)) : true := by do s ← simp_lemmas.mk_default, get_local `H >>= infer_type >>= s^.dsimplify >>= trace, constructor
c37cdd725333494d8c317bd0b6f7367a45e390d1
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/jacobson_ideal.lean
f56bd00fec8517c820a0e85d8e2a8c0df24a9b37
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
7,746
lean
/- Copyright (c) 2020 Devon Tuma. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Devon Tuma -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.ideal.operations import Mathlib.ring_theory.polynomial.basic import Mathlib.PostPort universes u v namespace Mathlib /-! # Jacobson radical The Jacobson radical of a ring `R` is defined to be the intersection of all maximal ideals of `R`. This is similar to how the nilradical is equal to the intersection of all prime ideals of `R`. We can extend the idea of the nilradical to ideals of `R`, by letting the radical of an ideal `I` be the intersection of prime ideals containing `I`. Under this extension, the original nilradical is the radical of the zero ideal `⊥`. Here we define the Jacobson radical of an ideal `I` in a similar way, as the intersection of maximal ideals containing `I`. ## Main definitions Let `R` be a commutative ring, and `I` be an ideal of `R` * `jacobson I` is the jacobson radical, i.e. the infimum of all maximal ideals containing I. * `is_local I` is the proposition that the jacobson radical of `I` is itself a maximal ideal ## Main statements * `mem_jacobson_iff` gives a characterization of members of the jacobson of I * `is_local_of_is_maximal_radical`: if the radical of I is maximal then so is the jacobson radical ## Tags Jacobson, Jacobson radical, Local Ideal -/ namespace ideal /-- The Jacobson radical of `I` is the infimum of all maximal ideals containing `I`. -/ def jacobson {R : Type u} [comm_ring R] (I : ideal R) : ideal R := Inf (set_of fun (J : ideal R) => I ≤ J ∧ is_maximal J) theorem le_jacobson {R : Type u} [comm_ring R] {I : ideal R} : I ≤ jacobson I := fun (x : R) (hx : x ∈ I) => iff.mpr mem_Inf fun (J : ideal R) (hJ : J ∈ set_of fun (J : ideal R) => I ≤ J ∧ is_maximal J) => and.left hJ x hx @[simp] theorem jacobson_idem {R : Type u} [comm_ring R] {I : ideal R} : jacobson (jacobson I) = jacobson I := sorry theorem radical_le_jacobson {R : Type u} [comm_ring R] {I : ideal R} : radical I ≤ jacobson I := le_Inf fun (J : ideal R) (hJ : J ∈ set_of fun (J : ideal R) => I ≤ J ∧ is_maximal J) => Eq.symm (radical_eq_Inf I) ▸ Inf_le { left := and.left hJ, right := is_maximal.is_prime (and.right hJ) } theorem eq_radical_of_eq_jacobson {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = I → radical I = I := fun (h : jacobson I = I) => le_antisymm (le_trans radical_le_jacobson (le_of_eq h)) le_radical @[simp] theorem jacobson_top {R : Type u} [comm_ring R] : jacobson ⊤ = ⊤ := iff.mpr eq_top_iff le_jacobson @[simp] theorem jacobson_eq_top_iff {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = ⊤ ↔ I = ⊤ := sorry theorem jacobson_eq_bot {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = ⊥ → I = ⊥ := fun (h : jacobson I = ⊥) => iff.mpr eq_bot_iff (h ▸ le_jacobson) theorem jacobson_eq_self_of_is_maximal {R : Type u} [comm_ring R] {I : ideal R} [H : is_maximal I] : jacobson I = I := le_antisymm (Inf_le { left := le_of_eq rfl, right := H }) le_jacobson protected instance jacobson.is_maximal {R : Type u} [comm_ring R] {I : ideal R} [H : is_maximal I] : is_maximal (jacobson I) := { left := fun (htop : jacobson I = ⊤) => and.left H (iff.mp jacobson_eq_top_iff htop), right := fun (J : ideal R) (hJ : jacobson I < J) => and.right H J (lt_of_le_of_lt le_jacobson hJ) } theorem mem_jacobson_iff {R : Type u} [comm_ring R] {I : ideal R} {x : R} : x ∈ jacobson I ↔ ∀ (y : R), ∃ (z : R), x * y * z + z - 1 ∈ I := sorry /-- An ideal equals its Jacobson radical iff it is the intersection of a set of maximal ideals. Allowing the set to include ⊤ is equivalent, and is included only to simplify some proofs. -/ theorem eq_jacobson_iff_Inf_maximal {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = I ↔ ∃ (M : set (ideal R)), (∀ (J : ideal R), J ∈ M → is_maximal J ∨ J = ⊤) ∧ I = Inf M := sorry theorem eq_jacobson_iff_Inf_maximal' {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = I ↔ ∃ (M : set (ideal R)), (∀ (J : ideal R), J ∈ M → ∀ (K : ideal R), J < K → K = ⊤) ∧ I = Inf M := sorry /-- An ideal `I` equals its Jacobson radical if and only if every element outside `I` also lies outside of a maximal ideal containing `I`. -/ theorem eq_jacobson_iff_not_mem {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = I ↔ ∀ (x : R), ¬x ∈ I → ∃ (M : ideal R), (I ≤ M ∧ is_maximal M) ∧ ¬x ∈ M := sorry theorem map_jacobson_of_surjective {R : Type u} [comm_ring R] {I : ideal R} {S : Type v} [comm_ring S] {f : R →+* S} (hf : function.surjective ⇑f) : ring_hom.ker f ≤ I → map f (jacobson I) = jacobson (map f I) := sorry theorem map_jacobson_of_bijective {R : Type u} [comm_ring R] {I : ideal R} {S : Type v} [comm_ring S] {f : R →+* S} (hf : function.bijective ⇑f) : map f (jacobson I) = jacobson (map f I) := map_jacobson_of_surjective (and.right hf) (le_trans (le_of_eq (iff.mp (ring_hom.injective_iff_ker_eq_bot f) (and.left hf))) bot_le) theorem comap_jacobson {R : Type u} [comm_ring R] {S : Type v} [comm_ring S] {f : R →+* S} {K : ideal S} : comap f (jacobson K) = Inf (comap f '' set_of fun (J : ideal S) => K ≤ J ∧ is_maximal J) := trans (comap_Inf' f (set_of fun (J : ideal S) => K ≤ J ∧ is_maximal J)) (Eq.symm Inf_eq_infi) theorem comap_jacobson_of_surjective {R : Type u} [comm_ring R] {S : Type v} [comm_ring S] {f : R →+* S} (hf : function.surjective ⇑f) {K : ideal S} : comap f (jacobson K) = jacobson (comap f K) := sorry theorem mem_jacobson_bot {R : Type u} [comm_ring R] {x : R} : x ∈ jacobson ⊥ ↔ ∀ (y : R), is_unit (x * y + 1) := sorry /-- An ideal `I` of `R` is equal to its Jacobson radical if and only if the Jacobson radical of the quotient ring `R/I` is the zero ideal -/ theorem jacobson_eq_iff_jacobson_quotient_eq_bot {R : Type u} [comm_ring R] {I : ideal R} : jacobson I = I ↔ jacobson ⊥ = ⊥ := sorry /-- The standard radical and Jacobson radical of an ideal `I` of `R` are equal if and only if the nilradical and Jacobson radical of the quotient ring `R/I` coincide -/ theorem radical_eq_jacobson_iff_radical_quotient_eq_jacobson_bot {R : Type u} [comm_ring R] {I : ideal R} : radical I = jacobson I ↔ radical ⊥ = jacobson ⊥ := sorry theorem jacobson_mono {R : Type u} [comm_ring R] {I : ideal R} {J : ideal R} : I ≤ J → jacobson I ≤ jacobson J := sorry theorem jacobson_radical_eq_jacobson {R : Type u} [comm_ring R] {I : ideal R} : jacobson (radical I) = jacobson I := sorry theorem jacobson_bot_polynomial_le_Inf_map_maximal {R : Type u} [comm_ring R] : jacobson ⊥ ≤ Inf (map polynomial.C '' set_of fun (J : ideal R) => is_maximal J) := sorry theorem jacobson_bot_polynomial_of_jacobson_bot {R : Type u} [comm_ring R] (h : jacobson ⊥ = ⊥) : jacobson ⊥ = ⊥ := sorry /-- An ideal `I` is local iff its Jacobson radical is maximal. -/ def is_local {R : Type u} [comm_ring R] (I : ideal R) := is_maximal (jacobson I) theorem is_local_of_is_maximal_radical {R : Type u} [comm_ring R] {I : ideal R} (hi : is_maximal (radical I)) : is_local I := sorry theorem is_local.le_jacobson {R : Type u} [comm_ring R] {I : ideal R} {J : ideal R} (hi : is_local I) (hij : I ≤ J) (hj : J ≠ ⊤) : J ≤ jacobson I := sorry theorem is_local.mem_jacobson_or_exists_inv {R : Type u} [comm_ring R] {I : ideal R} (hi : is_local I) (x : R) : x ∈ jacobson I ∨ ∃ (y : R), y * x - 1 ∈ I := sorry theorem is_primary_of_is_maximal_radical {R : Type u} [comm_ring R] {I : ideal R} (hi : is_maximal (radical I)) : is_primary I := sorry
7c50bb45609ae6465a6c1a7305453ee5901d1b15
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/linear_algebra/affine_space/combination.lean
63c09ce3fbe8ac5b3556023644f122b88252d330
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,227
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import algebra.invertible import algebra.indicator_function import linear_algebra.affine_space.affine_map import linear_algebra.affine_space.affine_subspace import linear_algebra.finsupp import tactic.fin_cases /-! # Affine combinations of points This file defines affine combinations of points. ## Main definitions * `weighted_vsub_of_point` is a general weighted combination of subtractions with an explicit base point, yielding a vector. * `weighted_vsub` uses an arbitrary choice of base point and is intended to be used when the sum of weights is 0, in which case the result is independent of the choice of base point. * `affine_combination` adds the weighted combination to the arbitrary base point, yielding a point rather than a vector, and is intended to be used when the sum of weights is 1, in which case the result is independent of the choice of base point. These definitions are for sums over a `finset`; versions for a `fintype` may be obtained using `finset.univ`, while versions for a `finsupp` may be obtained using `finsupp.support`. ## References * https://en.wikipedia.org/wiki/Affine_space -/ noncomputable theory open_locale big_operators classical affine namespace finset lemma univ_fin2 : (univ : finset (fin 2)) = {0, 1} := by { ext x, fin_cases x; simp } variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] variables [S : affine_space V P] include S variables {ι : Type*} (s : finset ι) variables {ι₂ : Type*} (s₂ : finset ι₂) /-- A weighted sum of the results of subtracting a base point from the given points, as a linear map on the weights. The main cases of interest are where the sum of the weights is 0, in which case the sum is independent of the choice of base point, and where the sum of the weights is 1, in which case the sum added to the base point is independent of the choice of base point. -/ def weighted_vsub_of_point (p : ι → P) (b : P) : (ι → k) →ₗ[k] V := ∑ i in s, (linear_map.proj i : (ι → k) →ₗ[k] k).smul_right (p i -ᵥ b) @[simp] lemma weighted_vsub_of_point_apply (w : ι → k) (p : ι → P) (b : P) : s.weighted_vsub_of_point p b w = ∑ i in s, w i • (p i -ᵥ b) := by simp [weighted_vsub_of_point, linear_map.sum_apply] /-- Given a family of points, if we use a member of the family as a base point, the `weighted_vsub_of_point` does not depend on the value of the weights at this point. -/ lemma weighted_vsub_of_point_eq_of_weights_eq (p : ι → P) (j : ι) (w₁ w₂ : ι → k) (hw : ∀ i, i ≠ j → w₁ i = w₂ i) : s.weighted_vsub_of_point p (p j) w₁ = s.weighted_vsub_of_point p (p j) w₂ := begin simp only [finset.weighted_vsub_of_point_apply], congr, ext i, cases eq_or_ne i j with h h, { simp [h], }, { simp [hw i h], }, end /-- The weighted sum is independent of the base point when the sum of the weights is 0. -/ lemma weighted_vsub_of_point_eq_of_sum_eq_zero (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 0) (b₁ b₂ : P) : s.weighted_vsub_of_point p b₁ w = s.weighted_vsub_of_point p b₂ w := begin apply eq_of_sub_eq_zero, rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, ←sum_sub_distrib], conv_lhs { congr, skip, funext, rw [←smul_sub, vsub_sub_vsub_cancel_left] }, rw [←sum_smul, h, zero_smul] end /-- The weighted sum, added to the base point, is independent of the base point when the sum of the weights is 1. -/ lemma weighted_vsub_of_point_vadd_eq_of_sum_eq_one (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 1) (b₁ b₂ : P) : s.weighted_vsub_of_point p b₁ w +ᵥ b₁ = s.weighted_vsub_of_point p b₂ w +ᵥ b₂ := begin erw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply, ←@vsub_eq_zero_iff_eq V, vadd_vsub_assoc, vsub_vadd_eq_vsub_sub, ←add_sub_assoc, add_comm, add_sub_assoc, ←sum_sub_distrib], conv_lhs { congr, skip, congr, skip, funext, rw [←smul_sub, vsub_sub_vsub_cancel_left] }, rw [←sum_smul, h, one_smul, vsub_add_vsub_cancel, vsub_self] end /-- The weighted sum is unaffected by removing the base point, if present, from the set of points. -/ @[simp] lemma weighted_vsub_of_point_erase (w : ι → k) (p : ι → P) (i : ι) : (s.erase i).weighted_vsub_of_point p (p i) w = s.weighted_vsub_of_point p (p i) w := begin rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply], apply sum_erase, rw [vsub_self, smul_zero] end /-- The weighted sum is unaffected by adding the base point, whether or not present, to the set of points. -/ @[simp] lemma weighted_vsub_of_point_insert [decidable_eq ι] (w : ι → k) (p : ι → P) (i : ι) : (insert i s).weighted_vsub_of_point p (p i) w = s.weighted_vsub_of_point p (p i) w := begin rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply], apply sum_insert_zero, rw [vsub_self, smul_zero] end /-- The weighted sum is unaffected by changing the weights to the corresponding indicator function and adding points to the set. -/ lemma weighted_vsub_of_point_indicator_subset (w : ι → k) (p : ι → P) (b : P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) : s₁.weighted_vsub_of_point p b w = s₂.weighted_vsub_of_point p b (set.indicator ↑s₁ w) := begin rw [weighted_vsub_of_point_apply, weighted_vsub_of_point_apply], exact set.sum_indicator_subset_of_eq_zero w (λ i wi, wi • (p i -ᵥ b : V)) h (λ i, zero_smul k _) end /-- A weighted sum, over the image of an embedding, equals a weighted sum with the same points and weights over the original `finset`. -/ lemma weighted_vsub_of_point_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) (b : P) : (s₂.map e).weighted_vsub_of_point p b w = s₂.weighted_vsub_of_point (p ∘ e) b (w ∘ e) := begin simp_rw [weighted_vsub_of_point_apply], exact finset.sum_map _ _ _ end /-- A weighted sum of the results of subtracting a default base point from the given points, as a linear map on the weights. This is intended to be used when the sum of the weights is 0; that condition is specified as a hypothesis on those lemmas that require it. -/ def weighted_vsub (p : ι → P) : (ι → k) →ₗ[k] V := s.weighted_vsub_of_point p (classical.choice S.nonempty) /-- Applying `weighted_vsub` with given weights. This is for the case where a result involving a default base point is OK (for example, when that base point will cancel out later); a more typical use case for `weighted_vsub` would involve selecting a preferred base point with `weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero` and then using `weighted_vsub_of_point_apply`. -/ lemma weighted_vsub_apply (w : ι → k) (p : ι → P) : s.weighted_vsub p w = ∑ i in s, w i • (p i -ᵥ (classical.choice S.nonempty)) := by simp [weighted_vsub, linear_map.sum_apply] /-- `weighted_vsub` gives the sum of the results of subtracting any base point, when the sum of the weights is 0. -/ lemma weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 0) (b : P) : s.weighted_vsub p w = s.weighted_vsub_of_point p b w := s.weighted_vsub_of_point_eq_of_sum_eq_zero w p h _ _ /-- The `weighted_vsub` for an empty set is 0. -/ @[simp] lemma weighted_vsub_empty (w : ι → k) (p : ι → P) : (∅ : finset ι).weighted_vsub p w = (0:V) := by simp [weighted_vsub_apply] /-- The weighted sum is unaffected by changing the weights to the corresponding indicator function and adding points to the set. -/ lemma weighted_vsub_indicator_subset (w : ι → k) (p : ι → P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) : s₁.weighted_vsub p w = s₂.weighted_vsub p (set.indicator ↑s₁ w) := weighted_vsub_of_point_indicator_subset _ _ _ h /-- A weighted subtraction, over the image of an embedding, equals a weighted subtraction with the same points and weights over the original `finset`. -/ lemma weighted_vsub_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) : (s₂.map e).weighted_vsub p w = s₂.weighted_vsub (p ∘ e) (w ∘ e) := s₂.weighted_vsub_of_point_map _ _ _ _ /-- A weighted sum of the results of subtracting a default base point from the given points, added to that base point, as an affine map on the weights. This is intended to be used when the sum of the weights is 1, in which case it is an affine combination (barycenter) of the points with the given weights; that condition is specified as a hypothesis on those lemmas that require it. -/ def affine_combination (p : ι → P) : (ι → k) →ᵃ[k] P := { to_fun := λ w, s.weighted_vsub_of_point p (classical.choice S.nonempty) w +ᵥ (classical.choice S.nonempty), linear := s.weighted_vsub p, map_vadd' := λ w₁ w₂, by simp_rw [vadd_vadd, weighted_vsub, vadd_eq_add, linear_map.map_add] } /-- The linear map corresponding to `affine_combination` is `weighted_vsub`. -/ @[simp] lemma affine_combination_linear (p : ι → P) : (s.affine_combination p : (ι → k) →ᵃ[k] P).linear = s.weighted_vsub p := rfl /-- Applying `affine_combination` with given weights. This is for the case where a result involving a default base point is OK (for example, when that base point will cancel out later); a more typical use case for `affine_combination` would involve selecting a preferred base point with `affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one` and then using `weighted_vsub_of_point_apply`. -/ lemma affine_combination_apply (w : ι → k) (p : ι → P) : s.affine_combination p w = s.weighted_vsub_of_point p (classical.choice S.nonempty) w +ᵥ (classical.choice S.nonempty) := rfl /-- `affine_combination` gives the sum with any base point, when the sum of the weights is 1. -/ lemma affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one (w : ι → k) (p : ι → P) (h : ∑ i in s, w i = 1) (b : P) : s.affine_combination p w = s.weighted_vsub_of_point p b w +ᵥ b := s.weighted_vsub_of_point_vadd_eq_of_sum_eq_one w p h _ _ /-- Adding a `weighted_vsub` to an `affine_combination`. -/ lemma weighted_vsub_vadd_affine_combination (w₁ w₂ : ι → k) (p : ι → P) : s.weighted_vsub p w₁ +ᵥ s.affine_combination p w₂ = s.affine_combination p (w₁ + w₂) := by rw [←vadd_eq_add, affine_map.map_vadd, affine_combination_linear] /-- Subtracting two `affine_combination`s. -/ lemma affine_combination_vsub (w₁ w₂ : ι → k) (p : ι → P) : s.affine_combination p w₁ -ᵥ s.affine_combination p w₂ = s.weighted_vsub p (w₁ - w₂) := by rw [←affine_map.linear_map_vsub, affine_combination_linear, vsub_eq_sub] lemma attach_affine_combination_of_injective (s : finset P) (w : P → k) (f : s → P) (hf : function.injective f) : s.attach.affine_combination f (w ∘ f) = (image f univ).affine_combination id w := begin simp only [affine_combination, weighted_vsub_of_point_apply, id.def, vadd_right_cancel_iff, function.comp_app, affine_map.coe_mk], let g₁ : s → V := λ i, w (f i) • (f i -ᵥ classical.choice S.nonempty), let g₂ : P → V := λ i, w i • (i -ᵥ classical.choice S.nonempty), change univ.sum g₁ = (image f univ).sum g₂, have hgf : g₁ = g₂ ∘ f, { ext, simp, }, rw [hgf, sum_image], exact λ _ _ _ _ hxy, hf hxy, end lemma attach_affine_combination_coe (s : finset P) (w : P → k) : s.attach.affine_combination (coe : s → P) (w ∘ coe) = s.affine_combination id w := by rw [attach_affine_combination_of_injective s w (coe : s → P) subtype.coe_injective, univ_eq_attach, attach_image_coe] omit S /-- Viewing a module as an affine space modelled on itself, affine combinations are just linear combinations. -/ @[simp] lemma affine_combination_eq_linear_combination (s : finset ι) (p : ι → V) (w : ι → k) (hw : ∑ i in s, w i = 1) : s.affine_combination p w = ∑ i in s, w i • p i := by simp [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p hw 0] include S /-- An `affine_combination` equals a point if that point is in the set and has weight 1 and the other points in the set have weight 0. -/ @[simp] lemma affine_combination_of_eq_one_of_eq_zero (w : ι → k) (p : ι → P) {i : ι} (his : i ∈ s) (hwi : w i = 1) (hw0 : ∀ i2 ∈ s, i2 ≠ i → w i2 = 0) : s.affine_combination p w = p i := begin have h1 : ∑ i in s, w i = 1 := hwi ▸ sum_eq_single i hw0 (λ h, false.elim (h his)), rw [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p h1 (p i), weighted_vsub_of_point_apply], convert zero_vadd V (p i), convert sum_eq_zero _, intros i2 hi2, by_cases h : i2 = i, { simp [h] }, { simp [hw0 i2 hi2 h] } end /-- An affine combination is unaffected by changing the weights to the corresponding indicator function and adding points to the set. -/ lemma affine_combination_indicator_subset (w : ι → k) (p : ι → P) {s₁ s₂ : finset ι} (h : s₁ ⊆ s₂) : s₁.affine_combination p w = s₂.affine_combination p (set.indicator ↑s₁ w) := by rw [affine_combination_apply, affine_combination_apply, weighted_vsub_of_point_indicator_subset _ _ _ h] /-- An affine combination, over the image of an embedding, equals an affine combination with the same points and weights over the original `finset`. -/ lemma affine_combination_map (e : ι₂ ↪ ι) (w : ι → k) (p : ι → P) : (s₂.map e).affine_combination p w = s₂.affine_combination (p ∘ e) (w ∘ e) := by simp_rw [affine_combination_apply, weighted_vsub_of_point_map] variables {V} /-- Suppose an indexed family of points is given, along with a subset of the index type. A vector can be expressed as `weighted_vsub_of_point` using a `finset` lying within that subset and with a given sum of weights if and only if it can be expressed as `weighted_vsub_of_point` with that sum of weights for the corresponding indexed family whose index type is the subtype corresponding to that subset. -/ lemma eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype {v : V} {x : k} {s : set ι} {p : ι → P} {b : P} : (∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = x), v = fs.weighted_vsub_of_point p b w) ↔ ∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = x), v = fs.weighted_vsub_of_point (λ (i : s), p i) b w := begin simp_rw weighted_vsub_of_point_apply, split, { rintros ⟨fs, hfs, w, rfl, rfl⟩, use [fs.subtype s, λ i, w i, sum_subtype_of_mem _ hfs, (sum_subtype_of_mem _ hfs).symm] }, { rintros ⟨fs, w, rfl, rfl⟩, refine ⟨fs.map (function.embedding.subtype _), map_subtype_subset _, λ i, if h : i ∈ s then w ⟨i, h⟩ else 0, _, _⟩; simp } end variables (k) /-- Suppose an indexed family of points is given, along with a subset of the index type. A vector can be expressed as `weighted_vsub` using a `finset` lying within that subset and with sum of weights 0 if and only if it can be expressed as `weighted_vsub` with sum of weights 0 for the corresponding indexed family whose index type is the subtype corresponding to that subset. -/ lemma eq_weighted_vsub_subset_iff_eq_weighted_vsub_subtype {v : V} {s : set ι} {p : ι → P} : (∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = 0), v = fs.weighted_vsub p w) ↔ ∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = 0), v = fs.weighted_vsub (λ (i : s), p i) w := eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype variables (V) /-- Suppose an indexed family of points is given, along with a subset of the index type. A point can be expressed as an `affine_combination` using a `finset` lying within that subset and with sum of weights 1 if and only if it can be expressed an `affine_combination` with sum of weights 1 for the corresponding indexed family whose index type is the subtype corresponding to that subset. -/ lemma eq_affine_combination_subset_iff_eq_affine_combination_subtype {p0 : P} {s : set ι} {p : ι → P} : (∃ (fs : finset ι) (hfs : ↑fs ⊆ s) (w : ι → k) (hw : ∑ i in fs, w i = 1), p0 = fs.affine_combination p w) ↔ ∃ (fs : finset s) (w : s → k) (hw : ∑ i in fs, w i = 1), p0 = fs.affine_combination (λ (i : s), p i) w := begin simp_rw [affine_combination_apply, eq_vadd_iff_vsub_eq], exact eq_weighted_vsub_of_point_subset_iff_eq_weighted_vsub_of_point_subtype end variables {k V} /-- Affine maps commute with affine combinations. -/ lemma map_affine_combination {V₂ P₂ : Type*} [add_comm_group V₂] [module k V₂] [affine_space V₂ P₂] (p : ι → P) (w : ι → k) (hw : s.sum w = 1) (f : P →ᵃ[k] P₂) : f (s.affine_combination p w) = s.affine_combination (f ∘ p) w := begin have b := classical.choice (infer_instance : affine_space V P).nonempty, have b₂ := classical.choice (infer_instance : affine_space V₂ P₂).nonempty, rw [s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p hw b, s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w (f ∘ p) hw b₂, ← s.weighted_vsub_of_point_vadd_eq_of_sum_eq_one w (f ∘ p) hw (f b) b₂], simp only [weighted_vsub_of_point_apply, ring_hom.id_apply, affine_map.map_vadd, linear_map.map_smulₛₗ, affine_map.linear_map_vsub, linear_map.map_sum], end end finset namespace finset variables (k : Type*) {V : Type*} {P : Type*} [division_ring k] [add_comm_group V] [module k V] variables [affine_space V P] {ι : Type*} (s : finset ι) {ι₂ : Type*} (s₂ : finset ι₂) /-- The weights for the centroid of some points. -/ def centroid_weights : ι → k := function.const ι (card s : k) ⁻¹ /-- `centroid_weights` at any point. -/ @[simp] lemma centroid_weights_apply (i : ι) : s.centroid_weights k i = (card s : k) ⁻¹ := rfl /-- `centroid_weights` equals a constant function. -/ lemma centroid_weights_eq_const : s.centroid_weights k = function.const ι ((card s : k) ⁻¹) := rfl variables {k} /-- The weights in the centroid sum to 1, if the number of points, converted to `k`, is not zero. -/ lemma sum_centroid_weights_eq_one_of_cast_card_ne_zero (h : (card s : k) ≠ 0) : ∑ i in s, s.centroid_weights k i = 1 := by simp [h] variables (k) /-- In the characteristic zero case, the weights in the centroid sum to 1 if the number of points is not zero. -/ lemma sum_centroid_weights_eq_one_of_card_ne_zero [char_zero k] (h : card s ≠ 0) : ∑ i in s, s.centroid_weights k i = 1 := by simp [h] /-- In the characteristic zero case, the weights in the centroid sum to 1 if the set is nonempty. -/ lemma sum_centroid_weights_eq_one_of_nonempty [char_zero k] (h : s.nonempty) : ∑ i in s, s.centroid_weights k i = 1 := s.sum_centroid_weights_eq_one_of_card_ne_zero k (ne_of_gt (card_pos.2 h)) /-- In the characteristic zero case, the weights in the centroid sum to 1 if the number of points is `n + 1`. -/ lemma sum_centroid_weights_eq_one_of_card_eq_add_one [char_zero k] {n : ℕ} (h : card s = n + 1) : ∑ i in s, s.centroid_weights k i = 1 := s.sum_centroid_weights_eq_one_of_card_ne_zero k (h.symm ▸ nat.succ_ne_zero n) include V /-- The centroid of some points. Although defined for any `s`, this is intended to be used in the case where the number of points, converted to `k`, is not zero. -/ def centroid (p : ι → P) : P := s.affine_combination p (s.centroid_weights k) /-- The definition of the centroid. -/ lemma centroid_def (p : ι → P) : s.centroid k p = s.affine_combination p (s.centroid_weights k) := rfl lemma centroid_univ (s : finset P) : univ.centroid k (coe : s → P) = s.centroid k id := by { rw [centroid, centroid, ← s.attach_affine_combination_coe], congr, ext, simp, } /-- The centroid of a single point. -/ @[simp] lemma centroid_singleton (p : ι → P) (i : ι) : ({i} : finset ι).centroid k p = p i := by simp [centroid_def, affine_combination_apply] /-- The centroid of two points, expressed directly as adding a vector to a point. -/ lemma centroid_insert_singleton [invertible (2 : k)] (p : ι → P) (i₁ i₂ : ι) : ({i₁, i₂} : finset ι).centroid k p = (2 ⁻¹ : k) • (p i₂ -ᵥ p i₁) +ᵥ p i₁ := begin by_cases h : i₁ = i₂, { simp [h] }, { have hc : (card ({i₁, i₂} : finset ι) : k) ≠ 0, { rw [card_insert_of_not_mem (not_mem_singleton.2 h), card_singleton], norm_num, exact nonzero_of_invertible _ }, rw [centroid_def, affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one _ _ _ (sum_centroid_weights_eq_one_of_cast_card_ne_zero _ hc) (p i₁)], simp [h], norm_num } end /-- The centroid of two points indexed by `fin 2`, expressed directly as adding a vector to the first point. -/ lemma centroid_insert_singleton_fin [invertible (2 : k)] (p : fin 2 → P) : univ.centroid k p = (2 ⁻¹ : k) • (p 1 -ᵥ p 0) +ᵥ p 0 := begin rw univ_fin2, convert centroid_insert_singleton k p 0 1 end /-- A centroid, over the image of an embedding, equals a centroid with the same points and weights over the original `finset`. -/ lemma centroid_map (e : ι₂ ↪ ι) (p : ι → P) : (s₂.map e).centroid k p = s₂.centroid k (p ∘ e) := by simp [centroid_def, affine_combination_map, centroid_weights] omit V /-- `centroid_weights` gives the weights for the centroid as a constant function, which is suitable when summing over the points whose centroid is being taken. This function gives the weights in a form suitable for summing over a larger set of points, as an indicator function that is zero outside the set whose centroid is being taken. In the case of a `fintype`, the sum may be over `univ`. -/ def centroid_weights_indicator : ι → k := set.indicator ↑s (s.centroid_weights k) /-- The definition of `centroid_weights_indicator`. -/ lemma centroid_weights_indicator_def : s.centroid_weights_indicator k = set.indicator ↑s (s.centroid_weights k) := rfl /-- The sum of the weights for the centroid indexed by a `fintype`. -/ lemma sum_centroid_weights_indicator [fintype ι] : ∑ i, s.centroid_weights_indicator k i = ∑ i in s, s.centroid_weights k i := (set.sum_indicator_subset _ (subset_univ _)).symm /-- In the characteristic zero case, the weights in the centroid indexed by a `fintype` sum to 1 if the number of points is not zero. -/ lemma sum_centroid_weights_indicator_eq_one_of_card_ne_zero [char_zero k] [fintype ι] (h : card s ≠ 0) : ∑ i, s.centroid_weights_indicator k i = 1 := begin rw sum_centroid_weights_indicator, exact s.sum_centroid_weights_eq_one_of_card_ne_zero k h end /-- In the characteristic zero case, the weights in the centroid indexed by a `fintype` sum to 1 if the set is nonempty. -/ lemma sum_centroid_weights_indicator_eq_one_of_nonempty [char_zero k] [fintype ι] (h : s.nonempty) : ∑ i, s.centroid_weights_indicator k i = 1 := begin rw sum_centroid_weights_indicator, exact s.sum_centroid_weights_eq_one_of_nonempty k h end /-- In the characteristic zero case, the weights in the centroid indexed by a `fintype` sum to 1 if the number of points is `n + 1`. -/ lemma sum_centroid_weights_indicator_eq_one_of_card_eq_add_one [char_zero k] [fintype ι] {n : ℕ} (h : card s = n + 1) : ∑ i, s.centroid_weights_indicator k i = 1 := begin rw sum_centroid_weights_indicator, exact s.sum_centroid_weights_eq_one_of_card_eq_add_one k h end include V /-- The centroid as an affine combination over a `fintype`. -/ lemma centroid_eq_affine_combination_fintype [fintype ι] (p : ι → P) : s.centroid k p = univ.affine_combination p (s.centroid_weights_indicator k) := affine_combination_indicator_subset _ _ (subset_univ _) /-- An indexed family of points that is injective on the given `finset` has the same centroid as the image of that `finset`. This is stated in terms of a set equal to the image to provide control of definitional equality for the index type used for the centroid of the image. -/ lemma centroid_eq_centroid_image_of_inj_on {p : ι → P} (hi : ∀ i j ∈ s, p i = p j → i = j) {ps : set P} [fintype ps] (hps : ps = p '' ↑s) : s.centroid k p = (univ : finset ps).centroid k (λ x, x) := begin let f : p '' ↑s → ι := λ x, x.property.some, have hf : ∀ x, f x ∈ s ∧ p (f x) = x := λ x, x.property.some_spec, let f' : ps → ι := λ x, f ⟨x, hps ▸ x.property⟩, have hf' : ∀ x, f' x ∈ s ∧ p (f' x) = x := λ x, hf ⟨x, hps ▸ x.property⟩, have hf'i : function.injective f', { intros x y h, rw [subtype.ext_iff, ←(hf' x).2, ←(hf' y).2, h] }, let f'e : ps ↪ ι := ⟨f', hf'i⟩, have hu : finset.univ.map f'e = s, { ext x, rw mem_map, split, { rintros ⟨i, _, rfl⟩, exact (hf' i).1 }, { intro hx, use [⟨p x, hps.symm ▸ set.mem_image_of_mem _ hx⟩, mem_univ _], refine hi _ _ (hf' _).1 hx _, rw (hf' _).2, refl } }, rw [←hu, centroid_map], congr' with x, change p (f' x) = ↑x, rw (hf' x).2 end /-- Two indexed families of points that are injective on the given `finset`s and with the same points in the image of those `finset`s have the same centroid. -/ lemma centroid_eq_of_inj_on_of_image_eq {p : ι → P} (hi : ∀ i j ∈ s, p i = p j → i = j) {p₂ : ι₂ → P} (hi₂ : ∀ i j ∈ s₂, p₂ i = p₂ j → i = j) (he : p '' ↑s = p₂ '' ↑s₂) : s.centroid k p = s₂.centroid k p₂ := by rw [s.centroid_eq_centroid_image_of_inj_on k hi rfl, s₂.centroid_eq_centroid_image_of_inj_on k hi₂ he] end finset section affine_space' variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] variables {ι : Type*} include V /-- A `weighted_vsub` with sum of weights 0 is in the `vector_span` of an indexed family. -/ lemma weighted_vsub_mem_vector_span {s : finset ι} {w : ι → k} (h : ∑ i in s, w i = 0) (p : ι → P) : s.weighted_vsub p w ∈ vector_span k (set.range p) := begin rcases is_empty_or_nonempty ι with hι|⟨⟨i0⟩⟩, { resetI, simp [finset.eq_empty_of_is_empty s] }, { rw [vector_span_range_eq_span_range_vsub_right k p i0, ←set.image_univ, finsupp.mem_span_image_iff_total, finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero s w p h (p i0), finset.weighted_vsub_of_point_apply], let w' := set.indicator ↑s w, have hwx : ∀ i, w' i ≠ 0 → i ∈ s := λ i, set.mem_of_indicator_ne_zero, use [finsupp.on_finset s w' hwx, set.subset_univ _], rw [finsupp.total_apply, finsupp.on_finset_sum hwx], { apply finset.sum_congr rfl, intros i hi, simp [w', set.indicator_apply, if_pos hi] }, { exact λ _, zero_smul k _ } }, end /-- An `affine_combination` with sum of weights 1 is in the `affine_span` of an indexed family, if the underlying ring is nontrivial. -/ lemma affine_combination_mem_affine_span [nontrivial k] {s : finset ι} {w : ι → k} (h : ∑ i in s, w i = 1) (p : ι → P) : s.affine_combination p w ∈ affine_span k (set.range p) := begin have hnz : ∑ i in s, w i ≠ 0 := h.symm ▸ one_ne_zero, have hn : s.nonempty := finset.nonempty_of_sum_ne_zero hnz, cases hn with i1 hi1, let w1 : ι → k := function.update (function.const ι 0) i1 1, have hw1 : ∑ i in s, w1 i = 1, { rw [finset.sum_update_of_mem hi1, finset.sum_const_zero, add_zero] }, have hw1s : s.affine_combination p w1 = p i1 := s.affine_combination_of_eq_one_of_eq_zero w1 p hi1 (function.update_same _ _ _) (λ _ _ hne, function.update_noteq hne _ _), have hv : s.affine_combination p w -ᵥ p i1 ∈ (affine_span k (set.range p)).direction, { rw [direction_affine_span, ←hw1s, finset.affine_combination_vsub], apply weighted_vsub_mem_vector_span, simp [pi.sub_apply, h, hw1] }, rw ←vsub_vadd (s.affine_combination p w) (p i1), exact affine_subspace.vadd_mem_of_mem_direction hv (mem_affine_span k (set.mem_range_self _)) end variables (k) {V} /-- A vector is in the `vector_span` of an indexed family if and only if it is a `weighted_vsub` with sum of weights 0. -/ lemma mem_vector_span_iff_eq_weighted_vsub {v : V} {p : ι → P} : v ∈ vector_span k (set.range p) ↔ ∃ (s : finset ι) (w : ι → k) (h : ∑ i in s, w i = 0), v = s.weighted_vsub p w := begin split, { rcases is_empty_or_nonempty ι with hι|⟨⟨i0⟩⟩, swap, { rw [vector_span_range_eq_span_range_vsub_right k p i0, ←set.image_univ, finsupp.mem_span_image_iff_total], rintros ⟨l, hl, hv⟩, use insert i0 l.support, set w := (l : ι → k) - function.update (function.const ι 0 : ι → k) i0 (∑ i in l.support, l i) with hwdef, use w, have hw : ∑ i in insert i0 l.support, w i = 0, { rw hwdef, simp_rw [pi.sub_apply, finset.sum_sub_distrib, finset.sum_update_of_mem (finset.mem_insert_self _ _), finset.sum_const_zero, finset.sum_insert_of_eq_zero_if_not_mem finsupp.not_mem_support_iff.1, add_zero, sub_self] }, use hw, have hz : w i0 • (p i0 -ᵥ p i0 : V) = 0 := (vsub_self (p i0)).symm ▸ smul_zero _, change (λ i, w i • (p i -ᵥ p i0 : V)) i0 = 0 at hz, rw [finset.weighted_vsub_eq_weighted_vsub_of_point_of_sum_eq_zero _ w p hw (p i0), finset.weighted_vsub_of_point_apply, ←hv, finsupp.total_apply, finset.sum_insert_zero hz], change ∑ i in l.support, l i • _ = _, congr' with i, by_cases h : i = i0, { simp [h] }, { simp [hwdef, h] } }, { resetI, rw [set.range_eq_empty, vector_span_empty, submodule.mem_bot], rintro rfl, use [∅], simp } }, { rintros ⟨s, w, hw, rfl⟩, exact weighted_vsub_mem_vector_span hw p } end variables {k} /-- A point in the `affine_span` of an indexed family is an `affine_combination` with sum of weights 1. -/ lemma eq_affine_combination_of_mem_affine_span {p1 : P} {p : ι → P} (h : p1 ∈ affine_span k (set.range p)) : ∃ (s : finset ι) (w : ι → k) (hw : ∑ i in s, w i = 1), p1 = s.affine_combination p w := begin have hn : ((affine_span k (set.range p)) : set P).nonempty := ⟨p1, h⟩, rw [affine_span_nonempty, set.range_nonempty_iff_nonempty] at hn, cases hn with i0, have h0 : p i0 ∈ affine_span k (set.range p) := mem_affine_span k (set.mem_range_self i0), have hd : p1 -ᵥ p i0 ∈ (affine_span k (set.range p)).direction := affine_subspace.vsub_mem_direction h h0, rw [direction_affine_span, mem_vector_span_iff_eq_weighted_vsub] at hd, rcases hd with ⟨s, w, h, hs⟩, let s' := insert i0 s, let w' := set.indicator ↑s w, have h' : ∑ i in s', w' i = 0, { rw [←h, set.sum_indicator_subset _ (finset.subset_insert i0 s)] }, have hs' : s'.weighted_vsub p w' = p1 -ᵥ p i0, { rw hs, exact (finset.weighted_vsub_indicator_subset _ _ (finset.subset_insert i0 s)).symm }, let w0 : ι → k := function.update (function.const ι 0) i0 1, have hw0 : ∑ i in s', w0 i = 1, { rw [finset.sum_update_of_mem (finset.mem_insert_self _ _), finset.sum_const_zero, add_zero] }, have hw0s : s'.affine_combination p w0 = p i0 := s'.affine_combination_of_eq_one_of_eq_zero w0 p (finset.mem_insert_self _ _) (function.update_same _ _ _) (λ _ _ hne, function.update_noteq hne _ _), use [s', w0 + w'], split, { simp [pi.add_apply, finset.sum_add_distrib, hw0, h'] }, { rw [add_comm, ←finset.weighted_vsub_vadd_affine_combination, hw0s, hs', vsub_vadd] } end variables (k V) /-- A point is in the `affine_span` of an indexed family if and only if it is an `affine_combination` with sum of weights 1, provided the underlying ring is nontrivial. -/ lemma mem_affine_span_iff_eq_affine_combination [nontrivial k] {p1 : P} {p : ι → P} : p1 ∈ affine_span k (set.range p) ↔ ∃ (s : finset ι) (w : ι → k) (hw : ∑ i in s, w i = 1), p1 = s.affine_combination p w := begin split, { exact eq_affine_combination_of_mem_affine_span }, { rintros ⟨s, w, hw, rfl⟩, exact affine_combination_mem_affine_span hw p } end /-- Given a family of points together with a chosen base point in that family, membership of the affine span of this family corresponds to an identity in terms of `weighted_vsub_of_point`, with weights that are not required to sum to 1. -/ lemma mem_affine_span_iff_eq_weighted_vsub_of_point_vadd [nontrivial k] (p : ι → P) (j : ι) (q : P) : q ∈ affine_span k (set.range p) ↔ ∃ (s : finset ι) (w : ι → k), q = s.weighted_vsub_of_point p (p j) w +ᵥ (p j) := begin split, { intros hq, obtain ⟨s, w, hw, rfl⟩ := eq_affine_combination_of_mem_affine_span hq, exact ⟨s, w, s.affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w p hw (p j)⟩, }, { rintros ⟨s, w, rfl⟩, classical, let w' : ι → k := function.update w j (1 - (s \ {j}).sum w), have h₁ : (insert j s).sum w' = 1, { by_cases hj : j ∈ s, { simp [finset.sum_update_of_mem hj, finset.insert_eq_of_mem hj], }, { simp [w', finset.sum_insert hj, finset.sum_update_of_not_mem hj, hj], }, }, have hww : ∀ i, i ≠ j → w i = w' i, { intros i hij, simp [w', hij], }, rw [s.weighted_vsub_of_point_eq_of_weights_eq p j w w' hww, ← s.weighted_vsub_of_point_insert w' p j, ← (insert j s).affine_combination_eq_weighted_vsub_of_point_vadd_of_sum_eq_one w' p h₁ (p j)], exact affine_combination_mem_affine_span h₁ p, }, end variables {k V} /-- Given a set of points, together with a chosen base point in this set, if we affinely transport all other members of the set along the line joining them to this base point, the affine span is unchanged. -/ lemma affine_span_eq_affine_span_line_map_units [nontrivial k] {s : set P} {p : P} (hp : p ∈ s) (w : s → units k) : affine_span k (set.range (λ (q : s), affine_map.line_map p ↑q (w q : k))) = affine_span k s := begin have : s = set.range (coe : s → P), { simp, }, conv_rhs { rw this, }, apply le_antisymm; intros q hq; erw mem_affine_span_iff_eq_weighted_vsub_of_point_vadd k V _ (⟨p, hp⟩ : s) q at hq ⊢; obtain ⟨t, μ, rfl⟩ := hq; use t; [use λ x, (μ x) * ↑(w x), use λ x, (μ x) * ↑(w x)⁻¹]; simp [smul_smul], end end affine_space' section division_ring variables {k : Type*} {V : Type*} {P : Type*} [division_ring k] [add_comm_group V] [module k V] variables [affine_space V P] {ι : Type*} include V open set finset /-- The centroid lies in the affine span if the number of points, converted to `k`, is not zero. -/ lemma centroid_mem_affine_span_of_cast_card_ne_zero {s : finset ι} (p : ι → P) (h : (card s : k) ≠ 0) : s.centroid k p ∈ affine_span k (range p) := affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_cast_card_ne_zero h) p variables (k) /-- In the characteristic zero case, the centroid lies in the affine span if the number of points is not zero. -/ lemma centroid_mem_affine_span_of_card_ne_zero [char_zero k] {s : finset ι} (p : ι → P) (h : card s ≠ 0) : s.centroid k p ∈ affine_span k (range p) := affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_card_ne_zero k h) p /-- In the characteristic zero case, the centroid lies in the affine span if the set is nonempty. -/ lemma centroid_mem_affine_span_of_nonempty [char_zero k] {s : finset ι} (p : ι → P) (h : s.nonempty) : s.centroid k p ∈ affine_span k (range p) := affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_nonempty k h) p /-- In the characteristic zero case, the centroid lies in the affine span if the number of points is `n + 1`. -/ lemma centroid_mem_affine_span_of_card_eq_add_one [char_zero k] {s : finset ι} (p : ι → P) {n : ℕ} (h : card s = n + 1) : s.centroid k p ∈ affine_span k (range p) := affine_combination_mem_affine_span (s.sum_centroid_weights_eq_one_of_card_eq_add_one k h) p end division_ring namespace affine_map variables {k : Type*} {V : Type*} (P : Type*) [comm_ring k] [add_comm_group V] [module k V] variables [affine_space V P] {ι : Type*} (s : finset ι) include V -- TODO: define `affine_map.proj`, `affine_map.fst`, `affine_map.snd` /-- A weighted sum, as an affine map on the points involved. -/ def weighted_vsub_of_point (w : ι → k) : ((ι → P) × P) →ᵃ[k] V := { to_fun := λ p, s.weighted_vsub_of_point p.fst p.snd w, linear := ∑ i in s, w i • ((linear_map.proj i).comp (linear_map.fst _ _ _) - linear_map.snd _ _ _), map_vadd' := begin rintros ⟨p, b⟩ ⟨v, b'⟩, simp [linear_map.sum_apply, finset.weighted_vsub_of_point, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub, ← sub_add_eq_add_sub, smul_add, finset.sum_add_distrib] end } end affine_map
62df9ebe0ca2a86789fb32dcda65b2b918aa165c
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/shapes/constructions/preserve_binary_products.lean
79323398d5e5ae05c2331aca7661cb3421f68757
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
3,554
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.limits import category_theory.limits.preserves.basic import category_theory.limits.shapes.binary_products /-! Show that a functor `F : C ⥤ D` preserves binary products if and only if `⟨Fπ₁, Fπ₂⟩ : F (A ⨯ B) ⟶ F A ⨯ F B` (that is, `prod_comparison`) is an isomorphism for all `A, B`. -/ noncomputable theory open category_theory namespace category_theory.limits universes v u₁ u₂ u₃ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [category.{v} C] variables {D : Type u₂} [category.{v} D] variables (F : C ⥤ D) /-- (Implementation). Construct a cone for `pair A B ⋙ F` which we will show is limiting. -/ @[simps] def alternative_cone (A B : C) [has_limit (pair (F.obj A) (F.obj B))] : cone (pair A B ⋙ F) := { X := F.obj A ⨯ F.obj B, π := discrete.nat_trans (λ j, walking_pair.cases_on j limits.prod.fst limits.prod.snd)} /-- (Implementation). Show that we have a limit for the shape `pair A B ⋙ F`. -/ def alternative_cone_is_limit (A B : C) [has_limit (pair (F.obj A) (F.obj B))] : is_limit (alternative_cone F A B) := { lift := λ s, prod.lift (s.π.app walking_pair.left) (s.π.app walking_pair.right), fac' := λ s j, walking_pair.cases_on j (prod.lift_fst _ _) (prod.lift_snd _ _), uniq' := λ s m w, prod.hom_ext (by { rw prod.lift_fst, apply w walking_pair.left }) (by { rw prod.lift_snd, apply w walking_pair.right }) } variables [has_binary_products C] [has_binary_products D] /-- If `prod_comparison F A B` is an iso, then `F` preserves the limit `A ⨯ B`. -/ def preserves_binary_prod_of_prod_comparison_iso (A B : C) [is_iso (prod_comparison F A B)] : preserves_limit (pair A B) F := preserves_limit_of_preserves_limit_cone (limit.is_limit (pair A B)) begin apply is_limit.of_iso_limit (alternative_cone_is_limit F A B) _, apply cones.ext _ _, { apply (as_iso (prod_comparison F A B)).symm }, { rintro ⟨j⟩, { apply (as_iso (prod_comparison F A B)).eq_inv_comp.2 (prod.lift_fst _ _) }, { apply (as_iso (prod_comparison F A B)).eq_inv_comp.2 (prod.lift_snd _ _) } }, end /-- If `prod_comparison F A B` is an iso for all `A, B` , then `F` preserves binary products. -/ instance preserves_binary_prods_of_prod_comparison_iso [∀ A B, is_iso (prod_comparison F A B)] : preserves_limits_of_shape (discrete walking_pair) F := { preserves_limit := λ K, begin haveI := preserves_binary_prod_of_prod_comparison_iso F (K.obj walking_pair.left) (K.obj walking_pair.right), apply preserves_limit_of_iso F (diagram_iso_pair K).symm, end } variables [preserves_limits_of_shape (discrete walking_pair) F] /-- The product comparison isomorphism. Technically a special case of `preserves_limit_iso`, but this version is convenient to have. -/ instance prod_comparison_iso_of_preserves_binary_prods (A B : C) : is_iso (prod_comparison F A B) := let t : is_limit (F.map_cone _) := preserves_limit.preserves (limit.is_limit (pair A B)) in { inv := t.lift (alternative_cone F A B), hom_inv_id' := begin apply is_limit.hom_ext t, rintro ⟨j⟩, { rw [category.assoc, t.fac, category.id_comp], apply prod.lift_fst }, { rw [category.assoc, t.fac, category.id_comp], apply prod.lift_snd }, end, inv_hom_id' := by ext ⟨j⟩; { simpa [prod_comparison] using t.fac _ _ } } end category_theory.limits
ff8c9fed69d625d84d4b547898cab6b63aed0aee
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/tests/lean/run/1901.lean
93af42ed6cf55143a5e141317a10100b2b261eb7
[ "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
596
lean
class Funny (F : Type _) (A B : outParam (Type _)) where toFun : F → A → B instance [Funny F A B] : CoeFun F fun _ => A → B where coe := Funny.toFun class MulHomClass (F) (A B : outParam _) [Mul A] [Mul B] extends Funny F A B class Monoid (M) extends Mul M instance [Mul A] : Mul (Id A) := ‹_› #check @Funny.toFun #check @MulHomClass.toFunny example {_ : Monoid A} {_ : Monoid B} [MulHomClass F A B] : Funny F A B := inferInstance -- set_option trace.Meta.synthInstance true example [Monoid A] [Monoid B] [MulHomClass F A B] (f : F) (a : A) : f a = f a := rfl -- infinite loop
f076ed121026e054bf3f145d187f632a4f61140f
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/hott/algebra/group.hlean
852e7c4979ede416c742b913d9c9322be4ba7bb8
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,269
hlean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura Various multiplicative and additive structures. Ported from the standard library -/ import algebra.binary open eq is_trunc binary -- note: ⁻¹ will be overloaded namespace algebra variable {A : Type} /- overloaded symbols -/ structure has_mul [class] (A : Type) := (mul : A → A → A) structure has_inv [class] (A : Type) := (inv : A → A) structure has_neg [class] (A : Type) := (neg : A → A) infixl * := has_mul.mul infixl + := has_add.add postfix ⁻¹ := has_inv.inv prefix - := has_neg.neg notation 1 := !has_one.one notation 0 := !has_zero.zero --a second notation for the inverse, which is not overloaded postfix [parsing_only] `⁻¹ᵍ`:std.prec.max_plus := has_inv.inv /- semigroup -/ structure semigroup [class] (A : Type) extends has_mul A := (is_hset_carrier : is_hset A) (mul_assoc : ∀a b c, mul (mul a b) c = mul a (mul b c)) attribute semigroup.is_hset_carrier [instance] theorem mul.assoc [s : semigroup A] (a b c : A) : a * b * c = a * (b * c) := !semigroup.mul_assoc structure comm_semigroup [class] (A : Type) extends semigroup A := (mul_comm : ∀a b, mul a b = mul b a) theorem mul.comm [s : comm_semigroup A] (a b : A) : a * b = b * a := !comm_semigroup.mul_comm theorem mul.left_comm [s : comm_semigroup A] (a b c : A) : a * (b * c) = b * (a * c) := binary.left_comm (@mul.comm A _) (@mul.assoc A _) a b c theorem mul.right_comm [s : comm_semigroup A] (a b c : A) : (a * b) * c = (a * c) * b := binary.right_comm (@mul.comm A _) (@mul.assoc A _) a b c structure left_cancel_semigroup [class] (A : Type) extends semigroup A := (mul_left_cancel : ∀a b c, mul a b = mul a c → b = c) theorem mul.left_cancel [s : left_cancel_semigroup A] {a b c : A} : a * b = a * c → b = c := !left_cancel_semigroup.mul_left_cancel abbreviation eq_of_mul_eq_mul_left' := @mul.left_cancel structure right_cancel_semigroup [class] (A : Type) extends semigroup A := (mul_right_cancel : ∀a b c, mul a b = mul c b → a = c) theorem mul.right_cancel [s : right_cancel_semigroup A] {a b c : A} : a * b = c * b → a = c := !right_cancel_semigroup.mul_right_cancel abbreviation eq_of_mul_eq_mul_right' := @mul.right_cancel /- additive semigroup -/ structure add_semigroup [class] (A : Type) extends has_add A := (is_hset_carrier : is_hset A) (add_assoc : ∀a b c, add (add a b) c = add a (add b c)) attribute add_semigroup.is_hset_carrier [instance] theorem add.assoc [s : add_semigroup A] (a b c : A) : a + b + c = a + (b + c) := !add_semigroup.add_assoc structure add_comm_semigroup [class] (A : Type) extends add_semigroup A := (add_comm : ∀a b, add a b = add b a) theorem add.comm [s : add_comm_semigroup A] (a b : A) : a + b = b + a := !add_comm_semigroup.add_comm theorem add.left_comm [s : add_comm_semigroup A] (a b c : A) : a + (b + c) = b + (a + c) := binary.left_comm (@add.comm A _) (@add.assoc A _) a b c theorem add.right_comm [s : add_comm_semigroup A] (a b c : A) : (a + b) + c = (a + c) + b := binary.right_comm (@add.comm A _) (@add.assoc A _) a b c structure add_left_cancel_semigroup [class] (A : Type) extends add_semigroup A := (add_left_cancel : ∀a b c, add a b = add a c → b = c) theorem add.left_cancel [s : add_left_cancel_semigroup A] {a b c : A} : a + b = a + c → b = c := !add_left_cancel_semigroup.add_left_cancel abbreviation eq_of_add_eq_add_left := @add.left_cancel structure add_right_cancel_semigroup [class] (A : Type) extends add_semigroup A := (add_right_cancel : ∀a b c, add a b = add c b → a = c) theorem add.right_cancel [s : add_right_cancel_semigroup A] {a b c : A} : a + b = c + b → a = c := !add_right_cancel_semigroup.add_right_cancel abbreviation eq_of_add_eq_add_right := @add.right_cancel /- monoid -/ structure monoid [class] (A : Type) extends semigroup A, has_one A := (one_mul : ∀a, mul one a = a) (mul_one : ∀a, mul a one = a) theorem one_mul [s : monoid A] (a : A) : 1 * a = a := !monoid.one_mul theorem mul_one [s : monoid A] (a : A) : a * 1 = a := !monoid.mul_one structure comm_monoid [class] (A : Type) extends monoid A, comm_semigroup A /- additive monoid -/ structure add_monoid [class] (A : Type) extends add_semigroup A, has_zero A := (zero_add : ∀a, add zero a = a) (add_zero : ∀a, add a zero = a) theorem zero_add [s : add_monoid A] (a : A) : 0 + a = a := !add_monoid.zero_add theorem add_zero [s : add_monoid A] (a : A) : a + 0 = a := !add_monoid.add_zero structure add_comm_monoid [class] (A : Type) extends add_monoid A, add_comm_semigroup A /- group -/ structure group [class] (A : Type) extends monoid A, has_inv A := (mul_left_inv : ∀a, mul (inv a) a = one) -- Note: with more work, we could derive the axiom one_mul section group variable [s : group A] include s theorem mul.left_inv (a : A) : a⁻¹ * a = 1 := !group.mul_left_inv theorem inv_mul_cancel_left (a b : A) : a⁻¹ * (a * b) = b := by rewrite [-mul.assoc, mul.left_inv, one_mul] theorem inv_mul_cancel_right (a b : A) : a * b⁻¹ * b = a := by rewrite [mul.assoc, mul.left_inv, mul_one] theorem inv_eq_of_mul_eq_one {a b : A} (H : a * b = 1) : a⁻¹ = b := by rewrite [-mul_one a⁻¹, -H, inv_mul_cancel_left] theorem one_inv : 1⁻¹ = (1:A) := inv_eq_of_mul_eq_one (one_mul 1) theorem inv_inv (a : A) : (a⁻¹)⁻¹ = a := inv_eq_of_mul_eq_one (mul.left_inv a) theorem inv.inj {a b : A} (H : a⁻¹ = b⁻¹) : a = b := by rewrite [-inv_inv, H, inv_inv] theorem inv_eq_inv_iff_eq (a b : A) : a⁻¹ = b⁻¹ ↔ a = b := iff.intro (assume H, inv.inj H) (assume H, ap _ H) theorem inv_eq_one_iff_eq_one (a b : A) : a⁻¹ = 1 ↔ a = 1 := one_inv ▸ inv_eq_inv_iff_eq a 1 theorem eq_inv_of_eq_inv {a b : A} (H : a = b⁻¹) : b = a⁻¹ := by rewrite [H, inv_inv] theorem eq_inv_iff_eq_inv (a b : A) : a = b⁻¹ ↔ b = a⁻¹ := iff.intro !eq_inv_of_eq_inv !eq_inv_of_eq_inv theorem mul.right_inv (a : A) : a * a⁻¹ = 1 := calc a * a⁻¹ = (a⁻¹)⁻¹ * a⁻¹ : inv_inv ... = 1 : mul.left_inv theorem mul_inv_cancel_left (a b : A) : a * (a⁻¹ * b) = b := calc a * (a⁻¹ * b) = a * a⁻¹ * b : by rewrite mul.assoc ... = 1 * b : mul.right_inv ... = b : one_mul theorem mul_inv_cancel_right (a b : A) : a * b * b⁻¹ = a := calc a * b * b⁻¹ = a * (b * b⁻¹) : mul.assoc ... = a * 1 : mul.right_inv ... = a : mul_one theorem mul_inv (a b : A) : (a * b)⁻¹ = b⁻¹ * a⁻¹ := inv_eq_of_mul_eq_one (calc a * b * (b⁻¹ * a⁻¹) = a * (b * (b⁻¹ * a⁻¹)) : mul.assoc ... = a * a⁻¹ : mul_inv_cancel_left ... = 1 : mul.right_inv) theorem eq_of_mul_inv_eq_one {a b : A} (H : a * b⁻¹ = 1) : a = b := calc a = a * b⁻¹ * b : by rewrite inv_mul_cancel_right ... = 1 * b : H ... = b : one_mul theorem eq_mul_inv_of_mul_eq {a b c : A} (H : a * c = b) : a = b * c⁻¹ := by rewrite [-H, mul_inv_cancel_right] theorem eq_inv_mul_of_mul_eq {a b c : A} (H : b * a = c) : a = b⁻¹ * c := by rewrite [-H, inv_mul_cancel_left] theorem inv_mul_eq_of_eq_mul {a b c : A} (H : b = a * c) : a⁻¹ * b = c := by rewrite [H, inv_mul_cancel_left] theorem mul_inv_eq_of_eq_mul {a b c : A} (H : a = c * b) : a * b⁻¹ = c := by rewrite [H, mul_inv_cancel_right] theorem eq_mul_of_mul_inv_eq {a b c : A} (H : a * c⁻¹ = b) : a = b * c := !inv_inv ▸ (eq_mul_inv_of_mul_eq H) theorem eq_mul_of_inv_mul_eq {a b c : A} (H : b⁻¹ * a = c) : a = b * c := !inv_inv ▸ (eq_inv_mul_of_mul_eq H) theorem mul_eq_of_eq_inv_mul {a b c : A} (H : b = a⁻¹ * c) : a * b = c := !inv_inv ▸ (inv_mul_eq_of_eq_mul H) theorem mul_eq_of_eq_mul_inv {a b c : A} (H : a = c * b⁻¹) : a * b = c := !inv_inv ▸ (mul_inv_eq_of_eq_mul H) theorem mul_eq_iff_eq_inv_mul (a b c : A) : a * b = c ↔ b = a⁻¹ * c := iff.intro eq_inv_mul_of_mul_eq mul_eq_of_eq_inv_mul theorem mul_eq_iff_eq_mul_inv (a b c : A) : a * b = c ↔ a = c * b⁻¹ := iff.intro eq_mul_inv_of_mul_eq mul_eq_of_eq_mul_inv theorem mul_left_cancel {a b c : A} (H : a * b = a * c) : b = c := by rewrite [-inv_mul_cancel_left a b, H, inv_mul_cancel_left] theorem mul_right_cancel {a b c : A} (H : a * b = c * b) : a = c := by rewrite [-mul_inv_cancel_right a b, H, mul_inv_cancel_right] theorem mul_eq_one_of_mul_eq_one {a b : A} (H : b * a = 1) : a * b = 1 := by rewrite [-inv_eq_of_mul_eq_one H, mul.left_inv] theorem mul_eq_one_iff_mul_eq_one (a b : A) : a * b = 1 ↔ b * a = 1 := iff.intro !mul_eq_one_of_mul_eq_one !mul_eq_one_of_mul_eq_one theorem eq_inv_of_mul_eq_one {a b : A} (H : a * b = 1) : a = b⁻¹ := (inv_eq_of_mul_eq_one (mul_eq_one_of_mul_eq_one H))⁻¹ definition group.to_left_cancel_semigroup [instance] [reducible] : left_cancel_semigroup A := ⦃ left_cancel_semigroup, s, mul_left_cancel := @mul_left_cancel A s ⦄ definition group.to_right_cancel_semigroup [instance] [reducible] : right_cancel_semigroup A := ⦃ right_cancel_semigroup, s, mul_right_cancel := @mul_right_cancel A s ⦄ end group structure comm_group [class] (A : Type) extends group A, comm_monoid A /- additive group -/ structure add_group [class] (A : Type) extends add_monoid A, has_neg A := (add_left_inv : ∀a, add (neg a) a = zero) section add_group variables [s : add_group A] include s theorem add.left_inv (a : A) : -a + a = 0 := !add_group.add_left_inv theorem neg_add_cancel_left (a b : A) : -a + (a + b) = b := by rewrite [-add.assoc, add.left_inv, zero_add] theorem neg_add_cancel_right (a b : A) : a + -b + b = a := by rewrite [add.assoc, add.left_inv, add_zero] theorem neg_eq_of_add_eq_zero {a b : A} (H : a + b = 0) : -a = b := by rewrite [-add_zero, -H, neg_add_cancel_left] theorem neg_zero : -0 = (0:A) := neg_eq_of_add_eq_zero (zero_add 0) theorem neg_neg (a : A) : -(-a) = a := neg_eq_of_add_eq_zero (add.left_inv a) theorem eq_neg_of_add_eq_zero {a b : A} (H : a + b = 0) : a = -b := by rewrite [-neg_eq_of_add_eq_zero H, neg_neg] theorem neg.inj {a b : A} (H : -a = -b) : a = b := calc a = -(-a) : neg_neg ... = b : neg_eq_of_add_eq_zero (H⁻¹ ▸ (add.left_inv _)) theorem neg_eq_neg_iff_eq (a b : A) : -a = -b ↔ a = b := iff.intro (assume H, neg.inj H) (assume H, ap _ H) theorem neg_eq_zero_iff_eq_zero (a : A) : -a = 0 ↔ a = 0 := neg_zero ▸ !neg_eq_neg_iff_eq theorem eq_neg_of_eq_neg {a b : A} (H : a = -b) : b = -a := H⁻¹ ▸ (neg_neg b)⁻¹ theorem eq_neg_iff_eq_neg (a b : A) : a = -b ↔ b = -a := iff.intro !eq_neg_of_eq_neg !eq_neg_of_eq_neg theorem add.right_inv (a : A) : a + -a = 0 := calc a + -a = -(-a) + -a : neg_neg ... = 0 : add.left_inv theorem add_neg_cancel_left (a b : A) : a + (-a + b) = b := by rewrite [-add.assoc, add.right_inv, zero_add] theorem add_neg_cancel_right (a b : A) : a + b + -b = a := by rewrite [add.assoc, add.right_inv, add_zero] theorem neg_add_rev (a b : A) : -(a + b) = -b + -a := neg_eq_of_add_eq_zero begin rewrite [add.assoc, add_neg_cancel_left, add.right_inv] end -- TODO: delete these in favor of sub rules? theorem eq_add_neg_of_add_eq {a b c : A} (H : a + c = b) : a = b + -c := H ▸ !add_neg_cancel_right⁻¹ theorem eq_neg_add_of_add_eq {a b c : A} (H : b + a = c) : a = -b + c := H ▸ !neg_add_cancel_left⁻¹ theorem neg_add_eq_of_eq_add {a b c : A} (H : b = a + c) : -a + b = c := H⁻¹ ▸ !neg_add_cancel_left theorem add_neg_eq_of_eq_add {a b c : A} (H : a = c + b) : a + -b = c := H⁻¹ ▸ !add_neg_cancel_right theorem eq_add_of_add_neg_eq {a b c : A} (H : a + -c = b) : a = b + c := !neg_neg ▸ (eq_add_neg_of_add_eq H) theorem eq_add_of_neg_add_eq {a b c : A} (H : -b + a = c) : a = b + c := !neg_neg ▸ (eq_neg_add_of_add_eq H) theorem add_eq_of_eq_neg_add {a b c : A} (H : b = -a + c) : a + b = c := !neg_neg ▸ (neg_add_eq_of_eq_add H) theorem add_eq_of_eq_add_neg {a b c : A} (H : a = c + -b) : a + b = c := !neg_neg ▸ (add_neg_eq_of_eq_add H) theorem add_eq_iff_eq_neg_add (a b c : A) : a + b = c ↔ b = -a + c := iff.intro eq_neg_add_of_add_eq add_eq_of_eq_neg_add theorem add_eq_iff_eq_add_neg (a b c : A) : a + b = c ↔ a = c + -b := iff.intro eq_add_neg_of_add_eq add_eq_of_eq_add_neg theorem add_left_cancel {a b c : A} (H : a + b = a + c) : b = c := calc b = -a + (a + b) : !neg_add_cancel_left⁻¹ ... = -a + (a + c) : H ... = c : neg_add_cancel_left theorem add_right_cancel {a b c : A} (H : a + b = c + b) : a = c := calc a = (a + b) + -b : !add_neg_cancel_right⁻¹ ... = (c + b) + -b : H ... = c : add_neg_cancel_right definition add_group.to_left_cancel_semigroup [instance] [reducible] : add_left_cancel_semigroup A := ⦃ add_left_cancel_semigroup, s, add_left_cancel := @add_left_cancel A s ⦄ definition add_group.to_add_right_cancel_semigroup [instance][reducible] : add_right_cancel_semigroup A := ⦃ add_right_cancel_semigroup, s, add_right_cancel := @add_right_cancel A s ⦄ /- sub -/ -- TODO: derive corresponding facts for div in a field definition sub [reducible] (a b : A) : A := a + -b infix - := sub theorem sub_eq_add_neg (a b : A) : a - b = a + -b := rfl theorem sub_self (a : A) : a - a = 0 := !add.right_inv theorem sub_add_cancel (a b : A) : a - b + b = a := !neg_add_cancel_right theorem add_sub_cancel (a b : A) : a + b - b = a := !add_neg_cancel_right theorem eq_of_sub_eq_zero {a b : A} (H : a - b = 0) : a = b := calc a = (a - b) + b : !sub_add_cancel⁻¹ ... = 0 + b : H ... = b : zero_add theorem eq_iff_sub_eq_zero (a b : A) : a = b ↔ a - b = 0 := iff.intro (assume H, H ▸ !sub_self) (assume H, eq_of_sub_eq_zero H) theorem zero_sub (a : A) : 0 - a = -a := !zero_add theorem sub_zero (a : A) : a - 0 = a := subst (eq.symm neg_zero) !add_zero theorem sub_neg_eq_add (a b : A) : a - (-b) = a + b := by change a + -(-b) = a + b; rewrite neg_neg theorem neg_sub (a b : A) : -(a - b) = b - a := neg_eq_of_add_eq_zero (calc a - b + (b - a) = a - b + b - a : by rewrite -add.assoc ... = a - a : sub_add_cancel ... = 0 : sub_self) theorem add_sub (a b c : A) : a + (b - c) = a + b - c := !add.assoc⁻¹ theorem sub_add_eq_sub_sub_swap (a b c : A) : a - (b + c) = a - c - b := calc a - (b + c) = a + (-c - b) : neg_add_rev ... = a - c - b : by rewrite add.assoc theorem sub_eq_iff_eq_add (a b c : A) : a - b = c ↔ a = c + b := iff.intro (assume H, eq_add_of_add_neg_eq H) (assume H, add_neg_eq_of_eq_add H) theorem eq_sub_iff_add_eq (a b c : A) : a = b - c ↔ a + c = b := iff.intro (assume H, add_eq_of_eq_add_neg H) (assume H, eq_add_neg_of_add_eq H) theorem eq_iff_eq_of_sub_eq_sub {a b c d : A} (H : a - b = c - d) : a = b ↔ c = d := calc a = b ↔ a - b = 0 : eq_iff_sub_eq_zero ... = (c - d = 0) : H ... ↔ c = d : iff.symm (eq_iff_sub_eq_zero c d) theorem eq_sub_of_add_eq {a b c : A} (H : a + c = b) : a = b - c := !eq_add_neg_of_add_eq H theorem sub_eq_of_eq_add {a b c : A} (H : a = c + b) : a - b = c := !add_neg_eq_of_eq_add H theorem eq_add_of_sub_eq {a b c : A} (H : a - c = b) : a = b + c := eq_add_of_add_neg_eq H theorem add_eq_of_eq_sub {a b c : A} (H : a = c - b) : a + b = c := add_eq_of_eq_add_neg H end add_group structure add_comm_group [class] (A : Type) extends add_group A, add_comm_monoid A section add_comm_group variable [s : add_comm_group A] include s theorem sub_add_eq_sub_sub (a b c : A) : a - (b + c) = a - b - c := !add.comm ▸ !sub_add_eq_sub_sub_swap theorem neg_add_eq_sub (a b : A) : -a + b = b - a := !add.comm theorem neg_add (a b : A) : -(a + b) = -a + -b := add.comm (-b) (-a) ▸ neg_add_rev a b theorem sub_add_eq_add_sub (a b c : A) : a - b + c = a + c - b := !add.right_comm theorem sub_sub (a b c : A) : a - b - c = a - (b + c) := by rewrite [▸ a + -b + -c = _, add.assoc, -neg_add] theorem add_sub_add_left_eq_sub (a b c : A) : (c + a) - (c + b) = a - b := by rewrite [sub_add_eq_sub_sub, (add.comm c a), add_sub_cancel] theorem eq_sub_of_add_eq' {a b c : A} (H : c + a = b) : a = b - c := !eq_sub_of_add_eq (!add.comm ▸ H) theorem sub_eq_of_eq_add' {a b c : A} (H : a = b + c) : a - b = c := !sub_eq_of_eq_add (!add.comm ▸ H) theorem eq_add_of_sub_eq' {a b c : A} (H : a - b = c) : a = b + c := !add.comm ▸ eq_add_of_sub_eq H theorem add_eq_of_eq_sub' {a b c : A} (H : b = c - a) : a + b = c := !add.comm ▸ add_eq_of_eq_sub H end add_comm_group definition group_of_add_group (A : Type) [G : add_group A] : group A := ⦃group, mul := has_add.add, mul_assoc := add.assoc, one := !has_zero.zero, one_mul := zero_add, mul_one := add_zero, inv := has_neg.neg, mul_left_inv := add.left_inv, is_hset_carrier := !add_group.is_hset_carrier⦄ /- bundled structures -/ structure Semigroup := (carrier : Type) (struct : semigroup carrier) attribute Semigroup.carrier [coercion] attribute Semigroup.struct [instance] structure CommSemigroup := (carrier : Type) (struct : comm_semigroup carrier) attribute CommSemigroup.carrier [coercion] attribute CommSemigroup.struct [instance] structure Monoid := (carrier : Type) (struct : monoid carrier) attribute Monoid.carrier [coercion] attribute Monoid.struct [instance] structure CommMonoid := (carrier : Type) (struct : comm_monoid carrier) attribute CommMonoid.carrier [coercion] attribute CommMonoid.struct [instance] structure Group := (carrier : Type) (struct : group carrier) attribute Group.carrier [coercion] attribute Group.struct [instance] structure CommGroup := (carrier : Type) (struct : comm_group carrier) attribute CommGroup.carrier [coercion] attribute CommGroup.struct [instance] structure AddSemigroup := (carrier : Type) (struct : add_semigroup carrier) attribute AddSemigroup.carrier [coercion] attribute AddSemigroup.struct [instance] structure AddCommSemigroup := (carrier : Type) (struct : add_comm_semigroup carrier) attribute AddCommSemigroup.carrier [coercion] attribute AddCommSemigroup.struct [instance] structure AddMonoid := (carrier : Type) (struct : add_monoid carrier) attribute AddMonoid.carrier [coercion] attribute AddMonoid.struct [instance] structure AddCommMonoid := (carrier : Type) (struct : add_comm_monoid carrier) attribute AddCommMonoid.carrier [coercion] attribute AddCommMonoid.struct [instance] structure AddGroup := (carrier : Type) (struct : add_group carrier) attribute AddGroup.carrier [coercion] attribute AddGroup.struct [instance] structure AddCommGroup := (carrier : Type) (struct : add_comm_group carrier) attribute AddCommGroup.carrier [coercion] attribute AddCommGroup.struct [instance] end algebra
e78940a64e4bb350014e87a85e2912117c40f082
c777c32c8e484e195053731103c5e52af26a25d1
/src/data/multiset/pi.lean
656f1dfa062522023db198bc168ae3e2f82b61e0
[ "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
5,046
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.multiset.nodup /-! # The cartesian product of multisets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ namespace multiset section pi variables {α : Type*} open function /-- Given `δ : α → Type*`, `pi.empty δ` is the trivial dependent function out of the empty multiset. -/ def pi.empty (δ : α → Sort*) : (Πa∈(0:multiset α), δ a) . variables [decidable_eq α] {β : α → Type*} {δ : α → Sort*} /-- Given `δ : α → Type*`, a multiset `m` and a term `a`, as well as a term `b : δ a` and a function `f` such that `f a' : δ a'` for all `a'` in `m`, `pi.cons m a b f` is a function `g` such that `g a'' : δ a''` for all `a''` in `a ::ₘ m`. -/ def pi.cons (m : multiset α) (a : α) (b : δ a) (f : Πa∈m, δ a) : Πa'∈a ::ₘ m, δ a' := λa' ha', if h : a' = a then eq.rec b h.symm else f a' $ (mem_cons.1 ha').resolve_left h lemma pi.cons_same {m : multiset α} {a : α} {b : δ a} {f : Πa∈m, δ a} (h : a ∈ a ::ₘ m) : pi.cons m a b f a h = b := dif_pos rfl lemma pi.cons_ne {m : multiset α} {a a' : α} {b : δ a} {f : Πa∈m, δ a} (h' : a' ∈ a ::ₘ m) (h : a' ≠ a) : pi.cons m a b f a' h' = f a' ((mem_cons.1 h').resolve_left h) := dif_neg h lemma pi.cons_swap {a a' : α} {b : δ a} {b' : δ a'} {m : multiset α} {f : Πa∈m, δ a} (h : a ≠ a') : pi.cons (a' ::ₘ m) a b (pi.cons m a' b' f) == pi.cons (a ::ₘ m) a' b' (pi.cons m a b f) := begin apply hfunext rfl, rintro a'' _ rfl, refine hfunext (by rw [cons_swap]) (λ ha₁ ha₂ _, _), rcases ne_or_eq a'' a with h₁ | rfl, rcases eq_or_ne a'' a' with rfl | h₂, all_goals { simp [*, pi.cons_same, pi.cons_ne] }, end /-- `pi m t` constructs the Cartesian product over `t` indexed by `m`. -/ def pi (m : multiset α) (t : Πa, multiset (β a)) : multiset (Πa∈m, β a) := m.rec_on {pi.empty β} (λa m (p : multiset (Πa∈m, β a)), (t a).bind $ λb, p.map $ pi.cons m a b) begin intros a a' m n, by_cases eq : a = a', { subst eq }, { simp [map_bind, bind_bind (t a') (t a)], apply bind_hcongr, { rw [cons_swap a a'] }, intros b hb, apply bind_hcongr, { rw [cons_swap a a'] }, intros b' hb', apply map_hcongr, { rw [cons_swap a a'] }, intros f hf, exact pi.cons_swap eq } end @[simp] lemma pi_zero (t : Πa, multiset (β a)) : pi 0 t = {pi.empty β} := rfl @[simp] lemma pi_cons (m : multiset α) (t : Πa, multiset (β a)) (a : α) : pi (a ::ₘ m) t = ((t a).bind $ λb, (pi m t).map $ pi.cons m a b) := rec_on_cons a m lemma pi_cons_injective {a : α} {b : δ a} {s : multiset α} (hs : a ∉ s) : function.injective (pi.cons s a b) := assume f₁ f₂ eq, funext $ assume a', funext $ assume h', have ne : a ≠ a', from assume h, hs $ h.symm ▸ h', have a' ∈ a ::ₘ s, from mem_cons_of_mem h', calc f₁ a' h' = pi.cons s a b f₁ a' this : by rw [pi.cons_ne this ne.symm] ... = pi.cons s a b f₂ a' this : by rw [eq] ... = f₂ a' h' : by rw [pi.cons_ne this ne.symm] lemma card_pi (m : multiset α) (t : Πa, multiset (β a)) : card (pi m t) = prod (m.map $ λa, card (t a)) := multiset.induction_on m (by simp) (by simp [mul_comm] {contextual := tt}) protected lemma nodup.pi {s : multiset α} {t : Π a, multiset (β a)} : nodup s → (∀a∈s, nodup (t a)) → nodup (pi s t) := multiset.induction_on s (assume _ _, nodup_singleton _) begin assume a s ih hs ht, have has : a ∉ s, by simp at hs; exact hs.1, have hs : nodup s, by simp at hs; exact hs.2, simp, refine ⟨λ b hb, (ih hs $ λ a' h', ht a' $ mem_cons_of_mem h').map (pi_cons_injective has), _⟩, refine (ht a $ mem_cons_self _ _).pairwise _, from assume b₁ hb₁ b₂ hb₂ neb, disjoint_map_map.2 (assume f hf g hg eq, have pi.cons s a b₁ f a (mem_cons_self _ _) = pi.cons s a b₂ g a (mem_cons_self _ _), by rw [eq], neb $ show b₁ = b₂, by rwa [pi.cons_same, pi.cons_same] at this) end @[simp] lemma pi.cons_ext {m : multiset α} {a : α} (f : Π a' ∈ a ::ₘ m, δ a') : pi.cons m a (f _ (mem_cons_self _ _)) (λ a' ha', f a' (mem_cons_of_mem ha')) = f := begin ext a' h', by_cases a' = a, { subst h, rw [pi.cons_same] }, { rw [pi.cons_ne _ h] } end lemma mem_pi (m : multiset α) (t : Πa, multiset (β a)) : ∀f:Πa∈m, β a, (f ∈ pi m t) ↔ (∀a (h : a ∈ m), f a h ∈ t a) := begin intro f, induction m using multiset.induction_on with a m ih, { simpa using show f = pi.empty β, by funext a ha; exact ha.elim }, simp_rw [pi_cons, mem_bind, mem_map, ih], split, { rintro ⟨b, hb, f', hf', rfl⟩ a' ha', by_cases a' = a, { subst h, rwa [pi.cons_same] }, { rw [pi.cons_ne _ h], apply hf' } }, { intro hf, refine ⟨_, hf a (mem_cons_self _ _), _, λ a ha, hf a (mem_cons_of_mem ha), _⟩, rw pi.cons_ext } end end pi end multiset
97056b8c6d58eae3e9bff5fa8eede2c36377c289
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/data/set/basic.lean
50bd05d8946ed95cb8cda3696bfe0edcc07ad0fa
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,532
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Leonardo de Moura -/ import logic.connectives logic.identities algebra.binary open eq.ops binary definition set (X : Type) := X → Prop namespace set variable {X : Type} /- membership and subset -/ definition mem (x : X) (a : set X) := a x infix ∈ := mem notation a ∉ b := ¬ mem a b theorem ext {a b : set X} (H : ∀x, x ∈ a ↔ x ∈ b) : a = b := funext (take x, propext (H x)) definition subset (a b : set X) := ∀⦃x⦄, x ∈ a → x ∈ b infix ⊆ := subset definition superset (s t : set X) : Prop := t ⊆ s infix ⊇ := superset theorem subset.refl (a : set X) : a ⊆ a := take x, assume H, H theorem subset.trans {a b c : set X} (subab : a ⊆ b) (subbc : b ⊆ c) : a ⊆ c := take x, assume ax, subbc (subab ax) theorem subset.antisymm {a b : set X} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) -- an alterantive name theorem eq_of_subset_of_subset {a b : set X} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set X} {a : X} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ _ h₂ /- strict subset -/ definition strict_subset (a b : set X) := a ⊆ b ∧ a ≠ b infix ` ⊂ `:50 := strict_subset theorem strict_subset.irrefl (a : set X) : ¬ a ⊂ a := assume h, absurd rfl (and.elim_right h) /- bounded quantification -/ abbreviation bounded_forall (a : set X) (P : X → Prop) := ∀⦃x⦄, x ∈ a → P x notation `forallb` binders `∈` a `, ` r:(scoped:1 P, P) := bounded_forall a r notation `∀₀` binders `∈` a `, ` r:(scoped:1 P, P) := bounded_forall a r abbreviation bounded_exists (a : set X) (P : X → Prop) := ∃⦃x⦄, x ∈ a ∧ P x notation `existsb` binders `∈` a `, ` r:(scoped:1 P, P) := bounded_exists a r notation `∃₀` binders `∈` a `, ` r:(scoped:1 P, P) := bounded_exists a r theorem bounded_exists.intro {P : X → Prop} {s : set X} {x : X} (xs : x ∈ s) (Px : P x) : ∃₀ x ∈ s, P x := exists.intro x (and.intro xs Px) /- empty set -/ definition empty : set X := λx, false notation `∅` := empty theorem not_mem_empty (x : X) : ¬ (x ∈ ∅) := assume H : x ∈ ∅, H theorem mem_empty_eq (x : X) : x ∈ ∅ = false := rfl theorem eq_empty_of_forall_not_mem {s : set X} (H : ∀ x, x ∉ s) : s = ∅ := ext (take x, iff.intro (assume xs, absurd xs (H x)) (assume xe, absurd xe !not_mem_empty)) theorem empty_subset (s : set X) : ∅ ⊆ s := take x, assume H, false.elim H theorem eq_empty_of_subset_empty {s : set X} (H : s ⊆ ∅) : s = ∅ := subset.antisymm H (empty_subset s) theorem subset_empty_iff (s : set X) : s ⊆ ∅ ↔ s = ∅ := iff.intro eq_empty_of_subset_empty (take xeq, by rewrite xeq; apply subset.refl ∅) /- universal set -/ definition univ : set X := λx, true theorem mem_univ (x : X) : x ∈ univ := trivial theorem mem_univ_iff (x : X) : x ∈ univ ↔ true := !iff.refl theorem mem_univ_eq (x : X) : x ∈ univ = true := rfl theorem empty_ne_univ [h : inhabited X] : (empty : set X) ≠ univ := assume H : empty = univ, absurd (mem_univ (inhabited.value h)) (eq.rec_on H (not_mem_empty _)) theorem subset_univ (s : set X) : s ⊆ univ := λ x H, trivial theorem eq_univ_of_univ_subset {s : set X} (H : univ ⊆ s) : s = univ := eq_of_subset_of_subset (subset_univ s) H theorem eq_univ_of_forall {s : set X} (H : ∀ x, x ∈ s) : s = univ := ext (take x, iff.intro (assume H', trivial) (assume H', H x)) /- union -/ definition union (a b : set X) : set X := λx, x ∈ a ∨ x ∈ b notation a ∪ b := union a b theorem mem_union_left {x : X} {a : set X} (b : set X) : x ∈ a → x ∈ a ∪ b := assume h, or.inl h theorem mem_union_right {x : X} {b : set X} (a : set X) : x ∈ b → x ∈ a ∪ b := assume h, or.inr h theorem mem_unionl {x : X} {a b : set X} : x ∈ a → x ∈ a ∪ b := assume h, or.inl h theorem mem_unionr {x : X} {a b : set X} : x ∈ b → x ∈ a ∪ b := assume h, or.inr h theorem mem_or_mem_of_mem_union {x : X} {a b : set X} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : X} {a b : set X} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union_iff (x : X) (a b : set X) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := !iff.refl theorem mem_union_eq (x : X) (a b : set X) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl theorem union_self (a : set X) : a ∪ a = a := ext (take x, !or_self) theorem union_empty (a : set X) : a ∪ ∅ = a := ext (take x, !or_false) theorem empty_union (a : set X) : ∅ ∪ a = a := ext (take x, !false_or) theorem union.comm (a b : set X) : a ∪ b = b ∪ a := ext (take x, or.comm) theorem union.assoc (a b c : set X) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (take x, or.assoc) theorem union.left_comm (s₁ s₂ s₃ : set X) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := !left_comm union.comm union.assoc s₁ s₂ s₃ theorem union.right_comm (s₁ s₂ s₃ : set X) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := !right_comm union.comm union.assoc s₁ s₂ s₃ theorem subset_union_left (s t : set X) : s ⊆ s ∪ t := λ x H, or.inl H theorem subset_union_right (s t : set X) : t ⊆ s ∪ t := λ x H, or.inr H theorem union_subset {s t r : set X} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := λ x xst, or.elim xst (λ xs, sr xs) (λ xt, tr xt) /- intersection -/ definition inter (a b : set X) : set X := λx, x ∈ a ∧ x ∈ b notation a ∩ b := inter a b theorem mem_inter_iff (x : X) (a b : set X) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := !iff.refl theorem mem_inter_eq (x : X) (a b : set X) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : X} {a b : set X} (Ha : x ∈ a) (Hb : x ∈ b) : x ∈ a ∩ b := and.intro Ha Hb theorem mem_of_mem_inter_left {x : X} {a b : set X} (H : x ∈ a ∩ b) : x ∈ a := and.left H theorem mem_of_mem_inter_right {x : X} {a b : set X} (H : x ∈ a ∩ b) : x ∈ b := and.right H theorem inter_self (a : set X) : a ∩ a = a := ext (take x, !and_self) theorem inter_empty (a : set X) : a ∩ ∅ = ∅ := ext (take x, !and_false) theorem empty_inter (a : set X) : ∅ ∩ a = ∅ := ext (take x, !false_and) theorem inter.comm (a b : set X) : a ∩ b = b ∩ a := ext (take x, !and.comm) theorem inter.assoc (a b c : set X) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (take x, !and.assoc) theorem inter.left_comm (s₁ s₂ s₃ : set X) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := !left_comm inter.comm inter.assoc s₁ s₂ s₃ theorem inter.right_comm (s₁ s₂ s₃ : set X) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := !right_comm inter.comm inter.assoc s₁ s₂ s₃ theorem inter_univ (a : set X) : a ∩ univ = a := ext (take x, !and_true) theorem univ_inter (a : set X) : univ ∩ a = a := ext (take x, !true_and) theorem inter_subset_left (s t : set X) : s ∩ t ⊆ s := λ x H, and.left H theorem inter_subset_right (s t : set X) : s ∩ t ⊆ t := λ x H, and.right H theorem subset_inter {s t r : set X} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := λ x xr, and.intro (rs xr) (rt xr) /- distributivity laws -/ theorem inter.distrib_left (s t u : set X) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (take x, !and.left_distrib) theorem inter.distrib_right (s t u : set X) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (take x, !and.right_distrib) theorem union.distrib_left (s t u : set X) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (take x, !or.left_distrib) theorem union.distrib_right (s t u : set X) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (take x, !or.right_distrib) /- set-builder notation -/ -- {x : X | P} definition set_of (P : X → Prop) : set X := P notation `{` binder ` | ` r:(scoped:1 P, set_of P) `}` := r -- {x ∈ s | P} definition sep (P : X → Prop) (s : set X) : set X := λx, x ∈ s ∧ P x notation `{` binder ` ∈ ` s ` | ` r:(scoped:1 p, sep p s) `}` := r /- insert -/ definition insert (x : X) (a : set X) : set X := {y : X | y = x ∨ y ∈ a} -- '{x, y, z} notation `'{`:max a:(foldr `, ` (x b, insert x b) ∅) `}`:0 := a theorem subset_insert (x : X) (a : set X) : a ⊆ insert x a := take y, assume ys, or.inr ys theorem mem_insert (x : X) (s : set X) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : X} {s : set X} (y : X) : x ∈ s → x ∈ insert y s := assume h, or.inr h theorem eq_or_mem_of_mem_insert {x a : X} {s : set X} : x ∈ insert a s → x = a ∨ x ∈ s := assume h, h theorem mem_of_mem_insert_of_ne {x a : X} {s : set X} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := or_resolve_right (eq_or_mem_of_mem_insert xin) theorem mem_insert_eq (x a : X) (s : set X) : x ∈ insert a s = (x = a ∨ x ∈ s) := propext (iff.intro !eq_or_mem_of_mem_insert (or.rec (λH', (eq.substr H' !mem_insert)) !mem_insert_of_mem)) theorem insert_eq_of_mem {a : X} {s : set X} (H : a ∈ s) : insert a s = s := ext (λ x, eq.substr (mem_insert_eq x a s) (or_iff_right_of_imp (λH1, eq.substr H1 H))) theorem insert.comm (x y : X) (s : set X) : insert x (insert y s) = insert y (insert x s) := ext (take a, by rewrite [*mem_insert_eq, propext !or.left_comm]) /- singleton -/ theorem mem_singleton_iff (a b : X) : a ∈ '{b} ↔ a = b := iff.intro (assume ainb, or.elim ainb (λ aeqb, aeqb) (λ f, false.elim f)) (assume aeqb, or.inl aeqb) theorem mem_singleton (a : X) : a ∈ '{a} := !mem_insert theorem eq_of_mem_singleton {x y : X} : x ∈ insert y ∅ → x = y := assume h, or.elim (eq_or_mem_of_mem_insert h) (suppose x = y, this) (suppose x ∈ ∅, absurd this !not_mem_empty) /- separation -/ theorem mem_sep {s : set X} {P : X → Prop} {x : X} (xs : x ∈ s) (Px : P x) : x ∈ {x ∈ s | P x} := and.intro xs Px theorem eq_sep_of_subset {s t : set X} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := ext (take x, iff.intro (suppose x ∈ s, and.intro (ssubt this) this) (suppose x ∈ {x ∈ t | x ∈ s}, and.right this)) theorem mem_sep_iff {s : set X} {P : X → Prop} {x : X} : x ∈ {x ∈ s | P x} ↔ x ∈ s ∧ P x := !iff.refl theorem sep_subset (s : set X) (P : X → Prop) : {x ∈ s | P x} ⊆ s := take x, assume H, and.left H /- complement -/ definition complement (s : set X) : set X := {x | x ∉ s} prefix `-` := complement theorem mem_comp {s : set X} {x : X} (H : x ∉ s) : x ∈ -s := H theorem not_mem_of_mem_comp {s : set X} {x : X} (H : x ∈ -s) : x ∉ s := H theorem mem_comp_iff (s : set X) (x : X) : x ∈ -s ↔ x ∉ s := !iff.refl theorem inter_comp_self (s : set X) : s ∩ -s = ∅ := ext (take x, !and_not_self_iff) theorem comp_inter_self (s : set X) : -s ∩ s = ∅ := ext (take x, !not_and_self_iff) /- some classical identities -/ section open classical theorem union_eq_comp_comp_inter_comp (s t : set X) : s ∪ t = -(-s ∩ -t) := ext (take x, !or_iff_not_and_not) theorem inter_eq_comp_comp_union_comp (s t : set X) : s ∩ t = -(-s ∪ -t) := ext (take x, !and_iff_not_or_not) theorem union_comp_self (s : set X) : s ∪ -s = univ := ext (take x, !or_not_self_iff) theorem comp_union_self (s : set X) : -s ∪ s = univ := ext (take x, !not_or_self_iff) end /- set difference -/ definition diff (s t : set X) : set X := {x ∈ s | x ∉ t} infix `\`:70 := diff theorem mem_diff {s t : set X} {x : X} (H1 : x ∈ s) (H2 : x ∉ t) : x ∈ s \ t := and.intro H1 H2 theorem mem_of_mem_diff {s t : set X} {x : X} (H : x ∈ s \ t) : x ∈ s := and.left H theorem not_mem_of_mem_diff {s t : set X} {x : X} (H : x ∈ s \ t) : x ∉ t := and.right H theorem mem_diff_iff (s t : set X) (x : X) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := !iff.refl theorem mem_diff_eq (s t : set X) (x : X) : x ∈ s \ t = (x ∈ s ∧ x ∉ t) := rfl theorem diff_eq (s t : set X) : s \ t = s ∩ -t := rfl theorem union_diff_cancel {s t : set X} [dec : Π x, decidable (x ∈ s)] (H : s ⊆ t) : s ∪ (t \ s) = t := ext (take x, iff.intro (assume H1 : x ∈ s ∪ (t \ s), or.elim H1 (assume H2, !H H2) (assume H2, and.left H2)) (assume H1 : x ∈ t, decidable.by_cases (suppose x ∈ s, or.inl this) (suppose x ∉ s, or.inr (and.intro H1 this)))) theorem diff_subset (s t : set X) : s \ t ⊆ s := inter_subset_left s _ /- powerset -/ definition powerset (s : set X) : set (set X) := {x : set X | x ⊆ s} prefix `𝒫`:100 := powerset theorem mem_powerset {x s : set X} (H : x ⊆ s) : x ∈ 𝒫 s := H theorem subset_of_mem_powerset {x s : set X} (H : x ∈ 𝒫 s) : x ⊆ s := H theorem mem_powerset_iff (x s : set X) : x ∈ 𝒫 s ↔ x ⊆ s := !iff.refl /- large unions -/ section variables {I : Type} variable a : set I variable b : I → set X variable C : set (set X) definition Inter : set X := {x : X | ∀i, x ∈ b i} definition bInter : set X := {x : X | ∀₀ i ∈ a, x ∈ b i} definition sInter : set X := {x : X | ∀₀ c ∈ C, x ∈ c} definition Union : set X := {x : X | ∃i, x ∈ b i} definition bUnion : set X := {x : X | ∃₀ i ∈ a, x ∈ b i} definition sUnion : set X := {x : X | ∃₀ c ∈ C, x ∈ c} -- TODO: need notation for these theorem Union_subset {b : I → set X} {c : set X} (H : ∀ i, b i ⊆ c) : Union b ⊆ c := take x, suppose x ∈ Union b, obtain i (Hi : x ∈ b i), from this, show x ∈ c, from H i Hi theorem sUnion_insert (s : set (set X)) (a : set X) : sUnion (insert a s) = a ∪ sUnion s := ext (take x, iff.intro (suppose x ∈ sUnion (insert a s), obtain c [(cias : c ∈ insert a s) (xc : x ∈ c)], from this, or.elim cias (suppose c = a, show x ∈ a ∪ sUnion s, from or.inl (this ▸ xc)) (suppose c ∈ s, show x ∈ a ∪ sUnion s, from or.inr (exists.intro c (and.intro this xc)))) (suppose x ∈ a ∪ sUnion s, or.elim this (suppose x ∈ a, have a ∈ insert a s, from or.inl rfl, show x ∈ sUnion (insert a s), from exists.intro a (and.intro this `x ∈ a`)) (suppose x ∈ sUnion s, obtain c [(cs : c ∈ s) (xc : x ∈ c)], from this, have c ∈ insert a s, from or.inr cs, show x ∈ sUnion (insert a s), from exists.intro c (and.intro this `x ∈ c`)))) end end set
c4e6e17b02de31b5155d29f5b13143229771b03b
cb1829c15cd3d28210f93507f96dfb1f56ec0128
/theorem_proving/07-inductive_types.lean
f4e3a3c0eb9a99fb7cb77960b7e95a150629861c
[]
no_license
williamdemeo/LEAN_wjd
69f9f76e35092b89e4479a320be2fa3c18aed6fe
13826c75c06ef435166a26a72e76fe984c15bad7
refs/heads/master
1,609,516,630,137
1,518,123,893,000
1,518,123,893,000
97,740,278
2
0
null
null
null
null
UTF-8
Lean
false
false
30,196
lean
-- 7. Inductive Types /- Every inductive type comes with introduction rules, which show how to construct an element of the type, and elimination rules, which show how to “use” an element of the type in another construction. We have already seen the introduction rules for an inductive type: they are just the constructors that are specified in the definition of the type. The elimination rules provide for a principle of recursion on the type, which includes, as a special case, a principle of induction as well. -/ #print "===========================================" #print "Section 7.1. Enumerated Types" #print " " -- https://leanprover.github.io/theorem_proving_in_lean/inductive_types.html#enumerated-types namespace Sec_7_1 -- The simplest kind of inductive type is a type with a finite, enumerated list of elements. inductive weekday : Type | Sunday : weekday | Monday : weekday | Tuesday : weekday | Wednesday : weekday | Thursday : weekday | Friday : weekday | Saturday : weekday #check weekday.Monday open weekday #check Monday -- Sunday, Monday, ..., Saturday are distinct elements of weekday, with no special properties. /- The elimination principle `weekday.rec` is defined with `weekday` and its constructors. `weekday.rec` is aka a recursor; it is what makes the type "inductive" and allows us to define a function on weekday by assigning values corresponding to each constructor. Intuition: an inductive type is exhaustively generated by its constructors, and has no elements beyond those they construct. -/ /- We will use a slight variant of `weekday.rec`, called `weekday.rec_on`, also generated automatically and taking its arguments in a more convenient order. -/ -- Let's import `nat` and use `weekday.rec_on` to define a fn from weekday to natural numbers: def number_of_day (d : weekday) : ℕ := weekday.rec_on d 1 2 3 4 5 6 7 #reduce number_of_day weekday.Sunday -- result: 1 #reduce number_of_day Sunday -- (`weekday` is already opened, so this works too) #reduce number_of_day Thursday -- result: 5 /- The first (explicit) argument to `rec_on` is the element `d` being "analyzed." The next seven arguments are the values corresponding to the seven constructors. Note that `number_of_day weekday.Sunday` evaluates to 1: the computation rule for `rec_on` sees that `Sunday` is a constructor, and returns the appropriate argument. -/ /- A more restricted variant of `rec_on` is `cases_on`. For enumerated types, `rec_on` and `cases_on` are the same, but `cases_on` emphasizes that the definition is by cases. -/ def number_of_day' (d : weekday) : ℕ := weekday.cases_on d 1 2 3 4 5 6 7 /- It is useful to group related definitions and theorems in a single namespace. We can put `number_of_day` in the `weekday` namespace and then use the shorter name when we open the namespace. -/ /- The names rec_on and cases_on are generated automatically, but they are protected to avoid name clashes, so they're not provided by default when the namespace is opened. However, you can explicitly declare aliases for them using `renaming`. -/ namespace weekday @[reducible] private def cases_on := @weekday.cases_on def number_of_day (d : weekday) : nat := cases_on d 1 2 3 4 5 6 7 end weekday -- We can define functions from weekday to weekday: namespace weekday def next (d : weekday) : weekday := weekday.cases_on d Monday Tuesday Wednesday Thursday Friday Saturday Sunday def previous (d : weekday) : weekday := weekday.cases_on d Saturday Sunday Monday Tuesday Wednesday Thursday Friday #reduce next (next Tuesday) #reduce next (previous Tuesday) example (d : weekday) : next (previous d) = d := weekday.cases_on d (show next (previous Sunday) = Sunday, from rfl) (show next (previous Monday) = Monday, from rfl) -- etc... -- ...but the show is just for clarity; we can just use `rfl` by itself -- as we do for the remaining cases rfl rfl rfl rfl rfl -- with tactics, we can be even more concise example (d : weekday) : next (previous d) = d := by apply weekday.cases_on d; refl end weekday -- Some fundamental data types in the Lean library are instances of enumerated types. namespace hide -- use `hide` so they don't conflict with the stdlib. inductive empty : Type -- an inductive data type with no constructors inductive unit : Type | star : unit inductive bool : Type | ff : bool | tt : bool /- As an exercise, think about the introduction and elimination rules for these types, and define boolean operations `band`, `bor`, `bnot` on the boolean, and verifying common identities; e.g., define `band` using a case split: -/ def band (b1 b2 : bool) : bool := bool.cases_on b1 bool.ff b2 def bor (b1 b2 : bool) : bool := bool.cases_on b1 b2 bool.tt def bnot (b : bool) : bool := bool.cases_on b bool.tt bool.ff #reduce band bool.tt bool.tt -- returns bool.tt #reduce band bool.ff bool.tt -- returns bool.ff #reduce bor bool.tt bool.ff -- returns bool.tt #reduce bor bool.ff bool.ff -- returns bool.ff #reduce bnot bool.ff -- returns bool.tt #reduce bnot bool.tt -- returns bool.ff -- Similarly, most identities can be proved by introducing suitable case splits, and then using rfl. end hide end Sec_7_1 #print "===========================================" #print "Section 7.2. Constructors with Arguments" #print " " -- https://leanprover.github.io/theorem_proving_in_lean/inductive_types.html#constructors-with-arguments namespace Sec_7_2 /- Enumerated types are a special case of inductive types, in which constructors take no arguments. In general, a "construction" can depend on data, which is then represented in the constructed argument. Consider the definitions of the product and sum types:-/ universes u v namespace hide inductive prod (α : Type u) (β : Type v) | mk : α → β → prod inductive sum (α : Type u) (β : Type v) | inl {} : α → sum | inr {} : β → sum end hide /- To define a function on prod α β, we assume input of the form prod.mk a b, and specify the output in terms of a and b. For example, here is the definition of the two projections for prod. -/ -- Remember the std lib uses α × β to denote prod α β and uses (a, b) for prod.mk a b. def fst {α : Type u} {β : Type v} (p : α × β) : α := prod.rec_on p (λ a b, a) def snd {α : Type u} {β : Type v} (p : α × β) : β := prod.rec_on p (λ a b, b) /- `fst` takes pair `p`, applies recursor `prod.rec_on p (λ a b, a)`---which interprets `p` as pair `prod.mk a b`---then uses the 2nd arg to determine what to do with a and b. -/ -- another example def prod_example (p : bool × ℕ) : ℕ := prod.rec_on p (λ b n, cond b (2 * n) (2 * n + 1)) #reduce prod_example (tt, 3) -- returns 6 #reduce prod_example (ff, 3) -- returns 7 -- `cond` is a boolean conditional: `cond b t1 t2` returns `t1` if `b` is true, and `t2` -- otherwise. (It has the same effect as `bool.rec_on b t2 t1`.) /- `sum` has two constructors, `inl` and `inr` and each takes one explicit argument. To define a function on `sum α β`, we must handle 2 cases: if the input is of the form `inl a` (resp., `inr b`) then we must specify an output value in terms of a (resp `b`). -/ def sum_example (s : ℕ ⊕ ℕ) : ℕ := sum.cases_on s (λ n, 2*n) (λ n, 2*n + 1) #reduce sum_example (sum.inl 3) -- returns 6 #reduce sum_example (sum.inr 3) -- returns 7 -- Lean's inductive def syntax allows named args for constructors before the colon: namespace hide₂ inductive prod (α : Type) (β : Type) | mk (fst : α) (snd : β) : prod inductive sum (α : Type) (β : Type) | inl {} (a : α) : sum | inr {} (b : β) : sum /- These result in essentially the same types as the ones above. In `sum`, `{}` refers to the parameters, `α` and `β`; braces specify which args are meant to be left implicit. -/ end hide₂ /- A type, like `prod`, that has only one constructor is purely conjunctive: the constructor simply packs the list of arguments into a single piece of data, essentially a tuple where the type of subsequent arguments can depend on the type of the initial argument. We can think of such a type as a "record" or a "structure." -/ /- In Lean, the keyword `structure` can be used to define such an inductive type as well as its projections, at the same time. -/ namespace hide₃ structure prod (α β : Type) := mk :: (fst : α) (snd : β) /- This simultaneously introduces the inductive type, `prod`, its constructor, `mk`, the usual eliminators (`rec` and `rec_on`), as well as the projections, `fst` and `snd`. -/ end hide₃ /- If you don't name the constructor, Lean uses `mk` as a default. For example, the following defines a record to store a color as a triple of RGB values: -/ structure color := (red : ℕ) (green : ℕ) (blue : ℕ) def yellow := color.mk 255 255 0 #reduce color.red yellow -- result: 255 (`color.red` is projection onto first component) #reduce color.green yellow -- result: 255 #reduce color.blue yellow -- result: 0 -- `structure` is especially useful for defining algebraic structures!!!!!! -- Lean provides substantial infrastructure to support working with them. -- Here's the definition of a semigroup: structure Semigroup := (carrier : Type u) (mul : carrier → carrier → carrier) (mul_assoc : ∀ a b c, mul (mul a b) c = mul a (mul b c)) -- ==> More examples in CHAPTER 9!!!!!!! <== -- Recall, sigma types are also known as the "dependent product" type: namespace hide₄ inductive sigma {α : Type u} (β : α → Type v) | dpair : Π a : α, β a → sigma -- Two more inductive types in the library are `option` and `inhabited`. inductive option (α : Type u) | none {} : option | some : α → option inductive inhabited (α : Type u) | mk : α → inhabited end hide₄ -- `option` type enables us to define partial functions /- In the semantics of dependent type theory, there is no built-in notion of a partial function. Every element of a function type `α → β` or a Pi type `Π x : α, β` is assumed total. The `option` type enables us to represent partial functions. An element of `option β` is either `none` or of the form `some b`, for some value `b : β`. Thus, `α → option β` is the type of partial functions from `α` to `β`; if `a : α`, then `f a` either returns `none`, indicating the `f` is "undefined" at `a`, or `some b`. -/ /- An element of `inhabited α` is simply a witness to existence of an element of `α`. `inhabited` is actually an example of a **type class** in Lean: Lean can be told that suitable base types are inhabited, and can automatically infer that other constructed types are inhabited on that basis. -/ /- As exercises, develop a notion of composition for partial functions from `α` to `β` and `β` to `γ`, and show that it behaves as expected. -/ /- Also, show that `bool` and `nat` are inhabited, that the product of two inhabited types is inhabited, and that the type of functions to an inhabited type is inhabited. -/ end Sec_7_2 #print "===========================================" #print "Section 7.3. Inductively Defined Propositions" #print " " -- https://leanprover.github.io/theorem_proving_in_lean/inductive_types.html#inductively-defined-propositions /- Inductively defined types can live in any type universe, including the bottom-most one, `Prop`. In fact, this is exactly how the logical connectives are defined. -/ namespace Sec_7_3 namespace hide₅ inductive false : Prop inductive true : Prop | intro : true inductive and (a b : Prop) : Prop | intro : a → b → and inductive or (a b : Prop) : Prop | intro_left : a → or | intro_right : b → or -- Alternatively, we could give names to the inhabitants: inductive and_alt (P Q : Prop) : Prop | intro (a : P) (b : Q) : and_alt inductive or_alt (P Q : Prop) : Prop | intro_left (a : P) : or_alt | intro_right (b : Q) : or_alt end hide₅ -- Think about how these give rise to the intro and elim rules we've already seen. -- There are rules that govern what the eliminator of an inductive type can eliminate to; -- that is, what kinds of types can be the target of a recursor. /- Roughly speaking, what characterizes inductive types in Prop is that one can only eliminate to other types in Prop. This agrees with the fact that if `p : Prop`, then an element `hp : p` carries no info. (There is one exception discussed below.) -/ -- Even the existential quantifier is inductively defined: namespace hide₆ universe u inductive Exists {α : Type u} (p : α → Prop) : Prop | intro : ∀(a : α), p a → Exists inductive Exists_alt {α : Type u} (p : α → Prop) : Prop | intro (w : ∀(a : α), p a) : Exists_alt def exists.intro := @Exists.intro end hide₆ -- The notation `∃ x : α, p` is syntactic sugar for `Exists (λ x : α, p)`. /- The defs of `false`, `true`, `and`, and `or` are analogous to the defs of `empty`, `unit`, `prod`, and `sum`. The difference is the former yield elements of `Prop`, and the latter yield elements of `Type u` for some `u`. -/ -- Similarly, `∃ x : α, p` is a `Prop`-valued variant of `Σ x : α, p`. /- Another inductive type, denoted `{x : α | p}`, is sort of a hybrid between `∃ x : α, P` and `Σ x : α, P`. It is the `subtype` type. -/ namespace hide₇ universe u inductive subtype {α : Type u} (p : α → Prop) | mk : Π(x : α), p x → subtype inductive subtype_alt {α : Type u} (p : α → Prop) | mk (w : Π(x : α), p x) : subtype_alt end hide₇ -- This next example is unclear to me. namespace confusing_example universe u variables {α : Type u} (p : α → Prop) -- ==========> UNRESOLVED QUESTIONS: <========== #check subtype p -- why is the result `subtype p : Type u` ?? #check {x : α // p x } -- why is the result `{x // p x } : Type u` ?? end confusing_example -- The notation `{x : α // p x}` is syntactic sugar for subtype `(λ x : α, p x)`. end Sec_7_3 #print "===========================================" #print "Section 7.4. Defining the Natural Numbers" #print " " -- https://leanprover.github.io/theorem_proving_in_lean/inductive_types.html#defining-the-natural-numbers namespace Sec_7_4 /- The inductively defined types we have seen so far are "flat": constructors wrap data and insert it into a type, and the corresponding recursor unpacks the data and acts on it. Things get more interesting when constructors act on elements of the type being defined. -/ -- A canonical example: namespace hide_7_4_1 inductive nat : Type | zero : nat | succ : nat → nat /- The recursor for `nat` defines a dependent function `f` from `nat` to any domain, that is, `nat.rec` defines an element `f` of `Π n : nat, C n` for any `C : nat → Type`. It has to handle two cases: the case where the input is zero, and the case where the input is of the form succ n for some n : nat. First case: we specify a target value of appropriate type. Second case: the recursor assumes f(n) has been computed and the recursor uses the next input arg to specify a value for f (succ n) in terms of n and f n. -/ #check @nat.rec_on -- returns: Π {C : nat → Sort u_1} (n : nat), -- arg 1: major premise -- C nat.zero → -- arg 2: minor premise 1 -- (Π (a : nat), C a → C (nat.succ a)) -- arg 3: specifies how to -- construct f(n+1) -- given n and f(n) -- → C n -- output type namespace nat def add (m n : nat) : nat := nat.rec_on n m (λ n add_m_n, succ add_m_n) #reduce add (succ zero) (succ (succ zero)) -- result: succ (succ (succ zero)) -- Can we recurse on m instead of n? Yes, of course. def add' (m n : nat) : nat := nat.rec_on m n (λ m add_m_n, succ add_m_n) #reduce add' (succ zero) (succ (succ zero)) -- same result as above /- Let's go back to the first definition of `add` and dissect it. + First, `nat.rec_on n` says "recurse on n". + The next symbol is `m` which indicates what to answer in the base case n=zero. + The next group of symbols is `(λ n add_m_n, succ add_m_n)` which gives the answer in the inductive case. The first argument to the λ abstraction is `n`, which means assume we know the value, `add_m_n`, that should be returned on input `m n`. Finally, use this to say what to do when the input is `m (succ n)`; namely, return `succ add_m_n`. That's all there is to it! -/ instance : has_zero nat := has_zero.mk zero instance : has_add nat := has_add.mk add theorem add_zero (m : nat) : m + 0 = m := rfl theorem add_succ (m n : nat) : m + succ n = succ (m + n) := rfl end nat end hide_7_4_1 /- Proving `0 + m = m`, however, requires induction. The induction principle is just a special case of the recursion principle when the codomain `C n` is an element of `Prop`. It represents the familiar pattern of proof by induction: to prove `∀ n, C n`, first prove `C 0`, and then, for arbitrary `n`, assume `ih : C n` and prove `C (succ n)`. -/ namespace hide_7_4_2 open nat theorem zero_add (n : ℕ) : 0 + n = n := nat.rec_on n (show 0 + 0 = 0, from rfl) (assume n, assume ih : 0 + n = n, show 0 + succ n = succ n, from calc 0 + succ n = succ (0 + n) : rfl ... = succ n : by rw ih) /- N.B. when `nat.rec_on` is used in a proof, it's the induction principle in disguise. The `rewrite` and `simp` tactics tend to be effective in proofs like these. -/ theorem zero_add' (n : ℕ) : 0 + n = n := nat.rec_on n rfl (λ n ih, by simp only [add_succ, ih]) theorem zero_add'' (n : ℕ) : 0 + n = n := nat.rec_on n rfl (λ n ih, by simp only [add_succ, ih]) /- N.B. leaving off the `only` modifier would be misleading because `zero_add` is declared in the standard library. Using `only` guarantees `simp` uses only the identities listed.-/ /- Associativity of addition: ∀ m n k, m + n + k = m + (n + k). The hardest part is figuring out which variable to do the induction on. Since addition is defined by recursion on the second argument, k is a good guess. -/ theorem add_assoc (m n k : ℕ) : m + n + k = m + (n + k) := nat.rec_on k (show m + n + 0 = m + (n + 0), from rfl) (assume k, assume ih : m + n + k = m + (n + k), show (m + n) + succ k = m + (n + succ k), from calc (m + n) + succ k = succ ((m + n) + k) : rfl ... = succ (m + (n + k)) : by rw ih ... = m + succ (n + k) : rfl ... = m + (n + succ k) : rfl) -- once again, there is a one-line proof theorem add_assoc' (m n k : ℕ) : m + n + k = m + (n + k) := nat.rec_on k rfl (λ k ih, by simp only [add_succ, ih]) theorem succ_add (m n : ℕ) : succ m + n = succ (m + n) := nat.rec_on n (show succ m + 0 = succ (m + 0), from rfl) (assume n, assume ih : succ m + n = succ (m + n), show succ m + succ n = succ (m + succ n), from calc succ m + succ n = succ (succ m + n) : rfl ... = succ (succ (m + n)) : by rw ih ... = succ (m + succ n) : rfl) -- Commutativity of addition: theorem add_comm (m n : ℕ) : m + n = n + m := nat.rec_on n (show m + 0 = 0 + m, by rw [nat.zero_add, nat.add_zero]) (assume n, assume ih : m + n = n + m, show m + succ n = succ n + m, from calc m + succ n = succ (m + n) : rfl ... = succ (n + m) : by rw ih ... = succ n + m : by simp only [succ_add]) -- Here are the shorter versions of the last two theorems: theorem succ_add' (m n : ℕ) : succ m + n = succ (m + n) := nat.rec_on n rfl (λ n ih, by simp only [succ_add, ih]) theorem add_comm' (m n : ℕ) : m + n = n + m := nat.rec_on n (by simp only [zero_add, add_zero]) (λ n ih, by simp only [add_succ, ih, succ_add]) end hide_7_4_2 end Sec_7_4 #print "===========================================" #print "Section 7.5. Other Recursive Data Types" #print " " -- https://leanprover.github.io/theorem_proving_in_lean/inductive_types.html#other-recursive-data-types -- Here are some more examples of inductively defined types. namespace Sec_7_5 -- For any type, α, the type list α of lists of elements of α is defined in the library. universe u inductive my_list (α : Type u) | nil {} : my_list | cons : α → my_list → my_list namespace my_list variable {α : Type} notation h :: t := cons h t def append (s t : my_list α) : my_list α := my_list.rec t (λ (x: α) (l: my_list α) (u: my_list α), x :: u) s /- Dissection of append: The first arg to `list.rec` is `t`, meaning return `t` when `s` is `null`. The second arg is `(λ x l u, x :: u) s`. I *think* this means the following: assuming `u` is the result of `append l t`, then `append (x :: l) t` results in `x :: u`. ==========> UNRESOLVED QUESTION: What about `s` ....? <========== -/ /- To give some support for the claim that the foregoing interpretation is (roughtly) correct, let's make the types explicit and verify that the definition still type-checks: -/ def append' (s t : my_list α) : my_list α := my_list.rec (t: my_list α) (λ (x : α) (l : my_list α) (u: my_list α), x :: u) (s : my_list α) #check nil -- nil : list ?M_1 #check (nil : my_list ℕ) -- nil : list ℕ #check cons 0 nil -- 0 :: nil : list ℕ #check cons "a" nil -- 0 :: nil : list string #check cons "a" (cons "b" nil) -- a :: b :: nil : list string notation s ++ t := append s t theorem nil_append (t : my_list α) : nil ++ t = t := rfl theorem cons_append (x : α) (s t : my_list α) : (x :: s) ++ t = x :: (s ++ t) := rfl -- Lean allows us to define iterative notation for lists: notation `{` l:(foldr `,` (h t, cons h t) nil) `}` := l section open nat #check {1,2,3,4,5} -- Lean assumes this is a list of nats #check ({1,2,3,4,5} : my_list int) -- Forces Lean to take this as a list of ints. end -- As an exercise, prove the following: theorem append_nil (t : my_list α) : t ++ nil = t := my_list.rec_on t (show (append nil nil) = nil, from rfl) (assume (x : α), assume (t : my_list α), assume ih : (append t nil) = t, show append (x :: t) nil = (x :: t), from calc append (x :: t) nil = x :: append t nil : cons_append x t nil ... = x :: t : by rw ih) -- As an exercise, prove the following: theorem append_nil' (t : my_list α) : t ++ nil = t := my_list.rec_on t rfl -- (base) (λ (x : α) (t : my_list α) (ih : (append t nil) = t), by simp [cons_append, ih]) -- (induct) --theorem append_assoc (r s t : my_list α) : r ++ s ++ t = r ++ (s ++ t) := sorry -- binary trees inductive binary_tree | leaf : binary_tree | node : binary_tree → binary_tree → binary_tree -- countably branching trees inductive cbtree | leaf : cbtree | sup : (ℕ → cbtree) → cbtree namespace cbtree def succ (t : cbtree) : cbtree := sup (λ n, t) -- Note: (λ n, t) is a thunk; i.e., a way to -- view t as a function of type ℕ → cbtree. /- Note the similarity to nat's successor. The third cbtree after t would be `sup (λ n, sup (λ n, sup (λ n, t))` -/ def omega : cbtree := sup (λ n, nat.rec_on n leaf (λ n t, succ t)) end cbtree end my_list end Sec_7_5 #print "===========================================" #print "Section 7.6. Tactics for Inductive Types" #print " " -- https://leanprover.github.io/theorem_proving_in_lean/inductive_types.html#tactics-for-inductive-types namespace Sec_7_6 /- There are a number of tactics designed to work with inductive types effectively. The `cases` tactic works on elements of an inductively defined type by decomposing the element into the ways it could be constructed. -/ namespace example₁ variable p : ℕ → Prop open nat example (hz : p 0) (hs : ∀ n, p (succ n)) : ∀ n, p n := begin intro n, cases n, exact hz, apply hs end /- `cases` lets you choose names for arguments to the constructors using `with`. For example, we can choose the name `m` for the argument to `succ`, so the second case refers to `succ m`. More importantly, `cases` detects items in the local context that depend on the target variable. It reverts these elements, does the split, and reintroduces them. In the example below, notice that `h : n ≠ 0` becomes `h : 0 ≠ 0` in the first branch, and `h : succ m ≠ 0` in the second.-/ example (n : ℕ) (h : n ≠ 0) : succ (pred n) = n := begin cases n with m, -- name cases using variable m -- goal: h : 0 ≠ 0 ⊢ succ (pred 0) = 0 { apply (absurd rfl h) }, -- goal: h : succ m ≠ 0 ⊢ succ (pred (succ m)) = succ m reflexivity end -- `cases` can be also be used to produce data and define functions. def f (n : ℕ) : ℕ := begin cases n, exact 3, exact 7 end example : f 0 = 3 := rfl example : f 5 = 7 := rfl example : f 1000 = 7 := rfl -- in fact, we can prove that f n is constantly 7, except when n = 0. example (n : ℕ) (h : n ≠ 0) : (f n) = 7 := begin cases n, { apply (absurd rfl h) }, -- goal: 0 ≠ 0 ⊢ f 0 = 7 reflexivity -- goal: (succ a ≠ 0) ⊢ f (succ a) = 7 end end example₁ -- Let's define a function that takes an single argument of type `tuple`. -- First define the type `tuple`. namespace functionals universe u open list -- Recall, we define a type that satisfies a predicate like this: def tuple (α : Type u) (n : ℕ) := subtype (λ (l : list α), (list.length l = n)) -- { l : list α // list.length l = n } -- (this didn't work for me) variables {α : Type u} {n : ℕ} def f {n : ℕ} (t : tuple α n) : ℕ := begin cases n, exact 3, exact 7 end def my_tuple : tuple ℕ 3 := ⟨[0, 1, 2], rfl⟩ example : f my_tuple = 7 := rfl -- As above, we prove that f t is constantly 7, except when t.length=0. example (n : ℕ) (t : tuple α n) (h : n ≠ 0) : f t = 7 := begin cases n, apply (absurd rfl h), -- goal: 0 ≠ 0 ⊢ f 0 = 7 reflexivity -- goal: (a : ℕ) (succ a ≠ 0) (t : tuple α (succ a)) ⊢ f t = 7 end end functionals namespace induction_tactic /- Just as `cases` is used to carry out proof by cases, the `induction` tactic is used for proofs by induction. In contrast to `cases`, the argument to `induction` can only come from the local context. -/ open nat theorem zero_add (n : ℕ) : 0 + n = n := begin induction n with n ih, refl, rw [add_succ, ih] end -- The `case` tactic identifies each case with named arguments, making the proof clearer: theorem zero_add' (n : ℕ) : 0 + n = n := begin induction n, case zero { refl }, case succ n ih { rw [add_succ, ih] } end theorem succ_add' (m n : ℕ) : (succ m) + n = succ (m + n) := begin induction n, case zero { refl }, case succ n ih { rw [add_succ, ih] } end theorem add_comm' (m n : ℕ) : m + n = n + m := begin induction n, case zero { rw zero_add, refl }, case succ n ih { rw [add_succ, ih, succ_add] } end -- Here are terse versions of the last three proofs. theorem zero_add'' (n : ℕ) : 0 + n = n := by induction n; simp only [*, add_zero, add_succ] theorem succ_add'' (m n : ℕ) : (succ m) + n = succ (m+n) := by induction n; simp only [*, add_zero, add_succ] theorem add_comm'' (m n : ℕ) : m + n = n + m := by induction n; simp only [*, zero_add, add_zero, add_succ, succ_add] theorem add_assoc'' (m n k : ℕ) : m + n + k = m + (n + k) := by induction k; simp only [*, add_zero, add_succ] end induction_tactic namespace injection_tactic /-We close this section with one last tactic that is designed to facilitate working with inductive types, namely, the injection tactic. By design, the elements of an inductive type are freely generated, which is to say, the constructors are injective and have disjoint ranges. The injection tactic is designed to make use of this fact: -/ end injection_tactic end Sec_7_6 #print "===========================================" #print "Section 7.7. Inductive Families" #print " " namespace Sec_7_7 end Sec_7_7 #print "===========================================" #print "Section 7.8. Axiomatic Details" #print " " namespace Sec_7_8 end Sec_7_8 #print "===========================================" #print "Section 7.9. Mutual and Nested Inductive Types" #print " " namespace Sec_7_9 end Sec_7_9 #print "===========================================" #print "Section 7.10. Exercises" #print " " namespace Sec_7_10 end Sec_7_10
c6707819f9e303b1a7f5082a86765fc0b7234374
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Lean/Elab/InfoTree.lean
1abdeb52182d471d976ed1ab68496ec8fcb79833
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
12,371
lean
/- Copyright (c) 2020 Wojciech Nawrocki. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki, Leonardo de Moura -/ import Lean.Data.Position import Lean.Expr import Lean.Message import Lean.Data.Json import Lean.Meta.Basic import Lean.Meta.PPGoal namespace Lean.Elab open Std (PersistentArray PersistentArray.empty PersistentHashMap) /- Context after executing `liftTermElabM`. Note that the term information collected during elaboration may contain metavariables, and their assignments are stored at `mctx`. -/ structure ContextInfo where env : Environment fileMap : FileMap mctx : MetavarContext := {} options : Options := {} currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] deriving Inhabited structure TermInfo where lctx : LocalContext -- The local context when the term was elaborated. expr : Expr stx : Syntax deriving Inhabited structure CommandInfo where stx : Syntax deriving Inhabited inductive CompletionInfo where | dot (termInfo : TermInfo) (field? : Option Syntax) (expectedType? : Option Expr) | id (stx : Syntax) (id : Name) (danglingDot : Bool) (lctx : LocalContext) (expectedType? : Option Expr) | namespaceId (stx : Syntax) | option (stx : Syntax) | endSection (stx : Syntax) (scopeNames : List String) | tactic (stx : Syntax) (goals : List MVarId) -- TODO `import` def CompletionInfo.stx : CompletionInfo → Syntax | dot i .. => i.stx | id stx .. => stx | namespaceId stx => stx | option stx => stx | endSection stx .. => stx | tactic stx .. => stx structure FieldInfo where name : Name lctx : LocalContext val : Expr stx : Syntax deriving Inhabited /- We store the list of goals before and after the execution of a tactic. We also store the metavariable context at each time since, we want to unassigned metavariables at tactic execution time to be displayed as `?m...`. -/ structure TacticInfo where mctxBefore : MetavarContext goalsBefore : List MVarId stx : Syntax mctxAfter : MetavarContext goalsAfter : List MVarId deriving Inhabited structure MacroExpansionInfo where lctx : LocalContext -- The local context when the macro was expanded. before : Syntax after : Syntax deriving Inhabited inductive Info where | ofTacticInfo (i : TacticInfo) | ofTermInfo (i : TermInfo) | ofCommandInfo (i : CommandInfo) | ofMacroExpansionInfo (i : MacroExpansionInfo) | ofFieldInfo (i : FieldInfo) | ofCompletionInfo (i : CompletionInfo) deriving Inhabited inductive InfoTree where | context (i : ContextInfo) (t : InfoTree) -- The context object is created by `liftTermElabM` at `Command.lean` | node (i : Info) (children : PersistentArray InfoTree) -- The children contains information for nested term elaboration and tactic evaluation | ofJson (j : Json) -- For user data | hole (mvarId : MVarId) -- The elaborator creates holes (aka metavariables) for tactics and postponed terms deriving Inhabited partial def InfoTree.findInfo? (p : Info → Bool) (t : InfoTree) : Option InfoTree := match t with | context _ t => findInfo? p t | node i ts => if p i then some t else ts.findSome? (findInfo? p) | _ => none structure InfoState where enabled : Bool := false assignment : PersistentHashMap MVarId InfoTree := {} -- map from holeId to InfoTree trees : PersistentArray InfoTree := {} deriving Inhabited class MonadInfoTree (m : Type → Type) where getInfoState : m InfoState modifyInfoState : (InfoState → InfoState) → m Unit export MonadInfoTree (getInfoState modifyInfoState) instance [MonadLift m n] [MonadInfoTree m] : MonadInfoTree n where getInfoState := liftM (getInfoState : m _) modifyInfoState f := liftM (modifyInfoState f : m _) partial def InfoTree.substitute (tree : InfoTree) (assignment : PersistentHashMap MVarId InfoTree) : InfoTree := match tree with | node i c => node i <| c.map (substitute · assignment) | context i t => context i (substitute t assignment) | ofJson j => ofJson j | hole id => match assignment.find? id with | none => hole id | some tree => substitute tree assignment def ContextInfo.runMetaM (info : ContextInfo) (lctx : LocalContext) (x : MetaM α) : IO α := do let x := x.run { lctx := lctx } { mctx := info.mctx } let ((a, _), _) ← x.toIO { options := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls } { env := info.env } return a def ContextInfo.toPPContext (info : ContextInfo) (lctx : LocalContext) : PPContext := { env := info.env, mctx := info.mctx, lctx := lctx, opts := info.options, currNamespace := info.currNamespace, openDecls := info.openDecls } def ContextInfo.ppSyntax (info : ContextInfo) (lctx : LocalContext) (stx : Syntax) : IO Format := do ppTerm (info.toPPContext lctx) stx private def formatStxRange (ctx : ContextInfo) (stx : Syntax) : Format := do let pos := stx.getPos?.getD 0 let endPos := stx.getTailPos?.getD pos return f!"{fmtPos pos stx.getHeadInfo}-{fmtPos endPos stx.getTailInfo}" where fmtPos pos info := let pos := format <| ctx.fileMap.toPosition pos match info with | SourceInfo.original .. => pos | _ => f!"{pos}†" def TermInfo.runMetaM (info : TermInfo) (ctx : ContextInfo) (x : MetaM α) : IO α := ctx.runMetaM info.lctx x def TermInfo.format (ctx : ContextInfo) (info : TermInfo) : IO Format := do info.runMetaM ctx do return f!"{← Meta.ppExpr info.expr} : {← Meta.ppExpr (← Meta.inferType info.expr)} @ {formatStxRange ctx info.stx}" def CompletionInfo.format (ctx : ContextInfo) (info : CompletionInfo) : IO Format := match info with | CompletionInfo.dot i (expectedType? := expectedType?) .. => return f!"[.] {← i.format ctx} : {expectedType?}" | CompletionInfo.id stx _ _ lctx expectedType? => ctx.runMetaM lctx do return f!"[.] {stx} : {expectedType?} @ {formatStxRange ctx info.stx}" | _ => return f!"[.] {info.stx} @ {formatStxRange ctx info.stx}" def CommandInfo.format (ctx : ContextInfo) (info : CommandInfo) : IO Format := do return f!"command @ {formatStxRange ctx info.stx}" def FieldInfo.format (ctx : ContextInfo) (info : FieldInfo) : IO Format := do ctx.runMetaM info.lctx do return f!"{info.name} : {← Meta.ppExpr (← Meta.inferType info.val)} := {← Meta.ppExpr info.val} @ {formatStxRange ctx info.stx}" def ContextInfo.ppGoals (ctx : ContextInfo) (goals : List MVarId) : IO Format := if goals.isEmpty then return "no goals" else ctx.runMetaM {} (return Std.Format.prefixJoin "\n" (← goals.mapM Meta.ppGoal)) def TacticInfo.format (ctx : ContextInfo) (info : TacticInfo) : IO Format := do let ctxB := { ctx with mctx := info.mctxBefore } let ctxA := { ctx with mctx := info.mctxAfter } let goalsBefore ← ctxB.ppGoals info.goalsBefore let goalsAfter ← ctxA.ppGoals info.goalsAfter return f!"Tactic @ {formatStxRange ctx info.stx}\nbefore {goalsBefore}\nafter {goalsAfter}" def MacroExpansionInfo.format (ctx : ContextInfo) (info : MacroExpansionInfo) : IO Format := do let before ← ctx.ppSyntax info.lctx info.before let after ← ctx.ppSyntax info.lctx info.after return f!"Macro expansion\n{before}\n===>\n{after}" def Info.format (ctx : ContextInfo) : Info → IO Format | ofTacticInfo i => i.format ctx | ofTermInfo i => i.format ctx | ofCommandInfo i => i.format ctx | ofMacroExpansionInfo i => i.format ctx | ofFieldInfo i => i.format ctx | ofCompletionInfo i => i.format ctx partial def InfoTree.format (tree : InfoTree) (ctx? : Option ContextInfo := none) : IO Format := do match tree with | ofJson j => return toString j | hole id => return toString id | context i t => format t i | node i cs => match ctx? with | none => return "<context-not-available>" | some ctx => if cs.size == 0 then i.format ctx else return f!"{← i.format ctx}{Std.Format.nestD <| Std.Format.prefixJoin "\n" (← cs.toList.mapM fun c => format c ctx?)}" section variable [Monad m] [MonadInfoTree m] @[inline] private def modifyInfoTrees (f : PersistentArray InfoTree → PersistentArray InfoTree) : m Unit := modifyInfoState fun s => { s with trees := f s.trees } private def getResetInfoTrees : m (PersistentArray InfoTree) := do let trees := (← getInfoState).trees modifyInfoTrees fun _ => {} return trees def pushInfoTree (t : InfoTree) : m Unit := do if (← getInfoState).enabled then modifyInfoTrees fun ts => ts.push t def pushInfoLeaf (t : Info) : m Unit := do if (← getInfoState).enabled then pushInfoTree <| InfoTree.node (children := {}) t def addCompletionInfo (info : CompletionInfo) : m Unit := do pushInfoLeaf <| Info.ofCompletionInfo info def resolveGlobalConstNoOverloadWithInfo [MonadResolveName m] [MonadEnv m] [MonadError m] (stx : Syntax) (id := stx.getId) : m Name := do let n ← resolveGlobalConstNoOverload id if (← getInfoState).enabled then pushInfoLeaf <| Info.ofTermInfo { lctx := LocalContext.empty, expr := (← mkConstWithLevelParams n), stx := stx } return n def resolveGlobalConstWithInfos [MonadResolveName m] [MonadEnv m] [MonadError m] (stx : Syntax) (id := stx.getId) : m (List Name) := do let ns ← resolveGlobalConst id if (← getInfoState).enabled then for n in ns do pushInfoLeaf <| Info.ofTermInfo { lctx := LocalContext.empty, expr := (← mkConstWithLevelParams n), stx := stx } return ns def mkInfoNode (info : Info) : m Unit := do if (← getInfoState).enabled then modifyInfoTrees fun ts => PersistentArray.empty.push <| InfoTree.node info ts @[inline] def withInfoContext' [MonadFinally m] (x : m α) (mkInfo : α → m (Sum Info MVarId)) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun a? => do match a? with | none => modifyInfoTrees fun _ => treesSaved | some a => let info ← mkInfo a modifyInfoTrees fun trees => match info with | Sum.inl info => treesSaved.push <| InfoTree.node info trees | Sum.inr mvaId => treesSaved.push <| InfoTree.hole mvaId else x @[inline] def withInfoTreeContext [MonadFinally m] (x : m α) (mkInfoTree : PersistentArray InfoTree → m InfoTree) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun _ => do let st ← getInfoState let tree ← mkInfoTree st.trees modifyInfoTrees fun _ => treesSaved.push tree else x @[inline] def withInfoContext [MonadFinally m] (x : m α) (mkInfo : m Info) : m α := do withInfoTreeContext x (fun trees => do return InfoTree.node (← mkInfo) trees) def getInfoHoleIdAssignment? (mvarId : MVarId) : m (Option InfoTree) := return (← getInfoState).assignment[mvarId] def assignInfoHoleId (mvarId : MVarId) (infoTree : InfoTree) : m Unit := do assert! (← getInfoHoleIdAssignment? mvarId).isNone modifyInfoState fun s => { s with assignment := s.assignment.insert mvarId infoTree } end def withMacroExpansionInfo [MonadFinally m] [Monad m] [MonadInfoTree m] [MonadLCtx m] (before after : Syntax) (x : m α) : m α := let mkInfo : m Info := do return Info.ofMacroExpansionInfo { lctx := (← getLCtx) before := before after := after } withInfoContext x mkInfo @[inline] def withInfoHole [MonadFinally m] [Monad m] [MonadInfoTree m] (mvarId : MVarId) (x : m α) : m α := do if (← getInfoState).enabled then let treesSaved ← getResetInfoTrees Prod.fst <$> MonadFinally.tryFinally' x fun a? => modifyInfoState fun s => if s.trees.size > 0 then { s with trees := treesSaved, assignment := s.assignment.insert mvarId s.trees[s.trees.size - 1] } else { s with trees := treesSaved } else x def enableInfoTree [MonadInfoTree m] (flag := true) : m Unit := modifyInfoState fun s => { s with enabled := flag } def getInfoTrees [MonadInfoTree m] [Monad m] : m (PersistentArray InfoTree) := return (← getInfoState).trees end Lean.Elab
705dea859b33934539d51540f2d8da2cc548a8e1
4727251e0cd73359b15b664c3170e5d754078599
/src/data/set/function.lean
7497ee422bfcb8a716492867fe8ffbec84994312
[ "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
46,920
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu, Yury Kudryashov -/ import data.set.prod import logic.function.conjugate /-! # Functions over sets ## Main definitions ### Predicate * `set.eq_on f₁ f₂ s` : functions `f₁` and `f₂` are equal at every point of `s`; * `set.maps_to f s t` : `f` sends every point of `s` to a point of `t`; * `set.inj_on f s` : restriction of `f` to `s` is injective; * `set.surj_on f s t` : every point in `s` has a preimage in `s`; * `set.bij_on f s t` : `f` is a bijection between `s` and `t`; * `set.left_inv_on f' f s` : for every `x ∈ s` we have `f' (f x) = x`; * `set.right_inv_on f' f t` : for every `y ∈ t` we have `f (f' y) = y`; * `set.inv_on f' f s t` : `f'` is a two-side inverse of `f` on `s` and `t`, i.e. we have `set.left_inv_on f' f s` and `set.right_inv_on f' f t`. ### Functions * `set.restrict f s` : restrict the domain of `f` to the set `s`; * `set.cod_restrict f s h` : given `h : ∀ x, f x ∈ s`, restrict the codomain of `f` to the set `s`; * `set.maps_to.restrict f s t h`: given `h : maps_to f s t`, restrict the domain of `f` to `s` and the codomain to `t`. -/ universes u v w x y variables {α : Type u} {β : Type v} {π : α → Type v} {γ : Type w} {ι : Sort x} open function namespace set /-! ### Restrict -/ /-- Restrict domain of a function `f` to a set `s`. Same as `subtype.restrict` but this version takes an argument `↥s` instead of `subtype s`. -/ def restrict (s : set α) (f : Π a : α, π a) : Π a : s, π a := λ x, f x lemma restrict_eq (f : α → β) (s : set α) : s.restrict f = f ∘ coe := rfl @[simp] lemma restrict_apply (f : α → β) (s : set α) (x : s) : s.restrict f x = f x := rfl @[simp] lemma range_restrict (f : α → β) (s : set α) : set.range (s.restrict f) = f '' s := (range_comp _ _).trans $ congr_arg (('') f) subtype.range_coe lemma image_restrict (f : α → β) (s t : set α) : s.restrict f '' (coe ⁻¹' t) = f '' (t ∩ s) := by rw [restrict, image_comp, image_preimage_eq_inter_range, subtype.range_coe] @[simp] lemma restrict_dite {s : set α} [∀ x, decidable (x ∈ s)] (f : Π a ∈ s, β) (g : Π a ∉ s, β) : s.restrict (λ a, if h : a ∈ s then f a h else g a h) = λ a, f a a.2 := funext $ λ a, dif_pos a.2 @[simp] lemma restrict_dite_compl {s : set α} [∀ x, decidable (x ∈ s)] (f : Π a ∈ s, β) (g : Π a ∉ s, β) : sᶜ.restrict (λ a, if h : a ∈ s then f a h else g a h) = λ a, g a a.2 := funext $ λ a, dif_neg a.2 @[simp] lemma restrict_ite (f g : α → β) (s : set α) [∀ x, decidable (x ∈ s)] : s.restrict (λ a, if a ∈ s then f a else g a) = s.restrict f := restrict_dite _ _ @[simp] lemma restrict_ite_compl (f g : α → β) (s : set α) [∀ x, decidable (x ∈ s)] : sᶜ.restrict (λ a, if a ∈ s then f a else g a) = sᶜ.restrict g := restrict_dite_compl _ _ @[simp] lemma restrict_piecewise (f g : α → β) (s : set α) [∀ x, decidable (x ∈ s)] : s.restrict (piecewise s f g) = s.restrict f := restrict_ite _ _ _ @[simp] lemma restrict_piecewise_compl (f g : α → β) (s : set α) [∀ x, decidable (x ∈ s)] : sᶜ.restrict (piecewise s f g) = sᶜ.restrict g := restrict_ite_compl _ _ _ lemma restrict_extend_range (f : α → β) (g : α → γ) (g' : β → γ) : (range f).restrict (extend f g g') = λ x, g x.coe_prop.some := by convert restrict_dite _ _ @[simp] lemma restrict_extend_compl_range (f : α → β) (g : α → γ) (g' : β → γ) : (range f)ᶜ.restrict (extend f g g') = g' ∘ coe := by convert restrict_dite_compl _ _ lemma range_extend_subset (f : α → β) (g : α → γ) (g' : β → γ) : range (extend f g g') ⊆ range g ∪ g' '' (range f)ᶜ := begin classical, rintro _ ⟨y, rfl⟩, rw extend_def, split_ifs, exacts [or.inl (mem_range_self _), or.inr (mem_image_of_mem _ h)] end lemma range_extend {f : α → β} (hf : injective f) (g : α → γ) (g' : β → γ) : range (extend f g g') = range g ∪ g' '' (range f)ᶜ := begin refine (range_extend_subset _ _ _).antisymm _, rintro z (⟨x, rfl⟩|⟨y, hy, rfl⟩), exacts [⟨f x, extend_apply hf _ _ _⟩, ⟨y, extend_apply' _ _ _ hy⟩] end /-- Restrict codomain of a function `f` to a set `s`. Same as `subtype.coind` but this version has codomain `↥s` instead of `subtype s`. -/ def cod_restrict (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) : α → s := λ x, ⟨f x, h x⟩ @[simp] lemma coe_cod_restrict_apply (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) (x : α) : (cod_restrict f s h x : β) = f x := rfl @[simp] lemma restrict_comp_cod_restrict {f : α → β} {g : β → γ} {b : set β} (h : ∀ x, f x ∈ b) : (b.restrict g) ∘ (b.cod_restrict f h) = g ∘ f := rfl variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} {p : set γ} {f f₁ f₂ f₃ : α → β} {g g₁ g₂ : β → γ} {f' f₁' f₂' : β → α} {g' : γ → β} @[simp] lemma injective_cod_restrict (h : ∀ x, f x ∈ t) : injective (cod_restrict f t h) ↔ injective f := by simp only [injective, subtype.ext_iff, coe_cod_restrict_apply] alias injective_cod_restrict ↔ _ function.injective.cod_restrict /-! ### Equality on a set -/ /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ def eq_on (f₁ f₂ : α → β) (s : set α) : Prop := ∀ ⦃x⦄, x ∈ s → f₁ x = f₂ x @[simp] lemma eq_on_empty (f₁ f₂ : α → β) : eq_on f₁ f₂ ∅ := λ x, false.elim @[symm] lemma eq_on.symm (h : eq_on f₁ f₂ s) : eq_on f₂ f₁ s := λ x hx, (h hx).symm lemma eq_on_comm : eq_on f₁ f₂ s ↔ eq_on f₂ f₁ s := ⟨eq_on.symm, eq_on.symm⟩ @[refl] lemma eq_on_refl (f : α → β) (s : set α) : eq_on f f s := λ _ _, rfl @[trans] lemma eq_on.trans (h₁ : eq_on f₁ f₂ s) (h₂ : eq_on f₂ f₃ s) : eq_on f₁ f₃ s := λ x hx, (h₁ hx).trans (h₂ hx) theorem eq_on.image_eq (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq theorem eq_on.inter_preimage_eq (heq : eq_on f₁ f₂ s) (t : set β) : s ∩ f₁ ⁻¹' t = s ∩ f₂ ⁻¹' t := ext $ λ x, and.congr_right_iff.2 $ λ hx, by rw [mem_preimage, mem_preimage, heq hx] lemma eq_on.mono (hs : s₁ ⊆ s₂) (hf : eq_on f₁ f₂ s₂) : eq_on f₁ f₂ s₁ := λ x hx, hf (hs hx) lemma eq_on.comp_left (h : s.eq_on f₁ f₂) : s.eq_on (g ∘ f₁) (g ∘ f₂) := λ a ha, congr_arg _ $ h ha lemma comp_eq_of_eq_on_range {ι : Sort*} {f : ι → α} {g₁ g₂ : α → β} (h : eq_on g₁ g₂ (range f)) : g₁ ∘ f = g₂ ∘ f := funext $ λ x, h $ mem_range_self _ /-! ### Congruence lemmas -/ section order variables [preorder α] [preorder β] lemma _root_.monotone_on.congr (h₁ : monotone_on f₁ s) (h : s.eq_on f₁ f₂) : monotone_on f₂ s := begin intros a ha b hb hab, rw [←h ha, ←h hb], exact h₁ ha hb hab, end lemma _root_.antitone_on.congr (h₁ : antitone_on f₁ s) (h : s.eq_on f₁ f₂) : antitone_on f₂ s := h₁.dual_right.congr h lemma _root_.strict_mono_on.congr (h₁ : strict_mono_on f₁ s) (h : s.eq_on f₁ f₂) : strict_mono_on f₂ s := begin intros a ha b hb hab, rw [←h ha, ←h hb], exact h₁ ha hb hab, end lemma _root_.strict_anti_on.congr (h₁ : strict_anti_on f₁ s) (h : s.eq_on f₁ f₂) : strict_anti_on f₂ s := h₁.dual_right.congr h lemma eq_on.congr_monotone_on (h : s.eq_on f₁ f₂) : monotone_on f₁ s ↔ monotone_on f₂ s := ⟨λ h₁, h₁.congr h, λ h₂, h₂.congr h.symm⟩ lemma eq_on.congr_antitone_on (h : s.eq_on f₁ f₂) : antitone_on f₁ s ↔ antitone_on f₂ s := ⟨λ h₁, h₁.congr h, λ h₂, h₂.congr h.symm⟩ lemma eq_on.congr_strict_mono_on (h : s.eq_on f₁ f₂) : strict_mono_on f₁ s ↔ strict_mono_on f₂ s := ⟨λ h₁, h₁.congr h, λ h₂, h₂.congr h.symm⟩ lemma eq_on.congr_strict_anti_on (h : s.eq_on f₁ f₂) : strict_anti_on f₁ s ↔ strict_anti_on f₂ s := ⟨λ h₁, h₁.congr h, λ h₂, h₂.congr h.symm⟩ end order /-! ### Mono lemmas-/ section mono variables [preorder α] [preorder β] lemma _root_.monotone_on.mono (h : monotone_on f s) (h' : s₂ ⊆ s) : monotone_on f s₂ := λ x hx y hy, h (h' hx) (h' hy) lemma _root_.antitone_on.mono (h : antitone_on f s) (h' : s₂ ⊆ s) : antitone_on f s₂ := λ x hx y hy, h (h' hx) (h' hy) lemma _root_.strict_mono_on.mono (h : strict_mono_on f s) (h' : s₂ ⊆ s) : strict_mono_on f s₂ := λ x hx y hy, h (h' hx) (h' hy) lemma _root_.strict_anti_on.mono (h : strict_anti_on f s) (h' : s₂ ⊆ s) : strict_anti_on f s₂ := λ x hx y hy, h (h' hx) (h' hy) end mono /-! ### maps to -/ /-- `maps_to f a b` means that the image of `a` is contained in `b`. -/ def maps_to (f : α → β) (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ s → f x ∈ t /-- Given a map `f` sending `s : set α` into `t : set β`, restrict domain of `f` to `s` and the codomain to `t`. Same as `subtype.map`. -/ def maps_to.restrict (f : α → β) (s : set α) (t : set β) (h : maps_to f s t) : s → t := subtype.map f h @[simp] lemma maps_to.coe_restrict_apply (h : maps_to f s t) (x : s) : (h.restrict f s t x : β) = f x := rfl lemma maps_to_iff_exists_map_subtype : maps_to f s t ↔ ∃ g : s → t, ∀ x : s, f x = g x := ⟨λ h, ⟨h.restrict f s t, λ _, rfl⟩, λ ⟨g, hg⟩ x hx, by { erw [hg ⟨x, hx⟩], apply subtype.coe_prop }⟩ theorem maps_to' : maps_to f s t ↔ f '' s ⊆ t := image_subset_iff.symm @[simp] theorem maps_to_singleton {x : α} : maps_to f {x} t ↔ f x ∈ t := singleton_subset_iff theorem maps_to_empty (f : α → β) (t : set β) : maps_to f ∅ t := empty_subset _ theorem maps_to.image_subset (h : maps_to f s t) : f '' s ⊆ t := maps_to'.1 h theorem maps_to.congr (h₁ : maps_to f₁ s t) (h : eq_on f₁ f₂ s) : maps_to f₂ s t := λ x hx, h hx ▸ h₁ hx lemma eq_on.comp_right (hg : t.eq_on g₁ g₂) (hf : s.maps_to f t) : s.eq_on (g₁ ∘ f) (g₂ ∘ f) := λ a ha, hg $ hf ha theorem eq_on.maps_to_iff (H : eq_on f₁ f₂ s) : maps_to f₁ s t ↔ maps_to f₂ s t := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ theorem maps_to.comp (h₁ : maps_to g t p) (h₂ : maps_to f s t) : maps_to (g ∘ f) s p := λ x h, h₁ (h₂ h) theorem maps_to_id (s : set α) : maps_to id s s := λ x, id theorem maps_to.iterate {f : α → α} {s : set α} (h : maps_to f s s) : ∀ n, maps_to (f^[n]) s s | 0 := λ _, id | (n+1) := (maps_to.iterate n).comp h theorem maps_to.iterate_restrict {f : α → α} {s : set α} (h : maps_to f s s) (n : ℕ) : (h.restrict f s s^[n]) = (h.iterate n).restrict _ _ _ := begin funext x, rw [subtype.ext_iff, maps_to.coe_restrict_apply], induction n with n ihn generalizing x, { refl }, { simp [nat.iterate, ihn] } end theorem maps_to.mono (hf : maps_to f s₁ t₁) (hs : s₂ ⊆ s₁) (ht : t₁ ⊆ t₂) : maps_to f s₂ t₂ := λ x hx, ht (hf $ hs hx) theorem maps_to.mono_left (hf : maps_to f s₁ t) (hs : s₂ ⊆ s₁) : maps_to f s₂ t := λ x hx, hf (hs hx) theorem maps_to.mono_right (hf : maps_to f s t₁) (ht : t₁ ⊆ t₂) : maps_to f s t₂ := λ x hx, ht (hf hx) theorem maps_to.union_union (h₁ : maps_to f s₁ t₁) (h₂ : maps_to f s₂ t₂) : maps_to f (s₁ ∪ s₂) (t₁ ∪ t₂) := λ x hx, hx.elim (λ hx, or.inl $ h₁ hx) (λ hx, or.inr $ h₂ hx) theorem maps_to.union (h₁ : maps_to f s₁ t) (h₂ : maps_to f s₂ t) : maps_to f (s₁ ∪ s₂) t := union_self t ▸ h₁.union_union h₂ @[simp] theorem maps_to_union : maps_to f (s₁ ∪ s₂) t ↔ maps_to f s₁ t ∧ maps_to f s₂ t := ⟨λ h, ⟨h.mono (subset_union_left s₁ s₂) (subset.refl t), h.mono (subset_union_right s₁ s₂) (subset.refl t)⟩, λ h, h.1.union h.2⟩ theorem maps_to.inter (h₁ : maps_to f s t₁) (h₂ : maps_to f s t₂) : maps_to f s (t₁ ∩ t₂) := λ x hx, ⟨h₁ hx, h₂ hx⟩ theorem maps_to.inter_inter (h₁ : maps_to f s₁ t₁) (h₂ : maps_to f s₂ t₂) : maps_to f (s₁ ∩ s₂) (t₁ ∩ t₂) := λ x hx, ⟨h₁ hx.1, h₂ hx.2⟩ @[simp] theorem maps_to_inter : maps_to f s (t₁ ∩ t₂) ↔ maps_to f s t₁ ∧ maps_to f s t₂ := ⟨λ h, ⟨h.mono (subset.refl s) (inter_subset_left t₁ t₂), h.mono (subset.refl s) (inter_subset_right t₁ t₂)⟩, λ h, h.1.inter h.2⟩ theorem maps_to_univ (f : α → β) (s : set α) : maps_to f s univ := λ x h, trivial theorem maps_to_image (f : α → β) (s : set α) : maps_to f s (f '' s) := by rw maps_to' theorem maps_to_preimage (f : α → β) (t : set β) : maps_to f (f ⁻¹' t) t := subset.refl _ theorem maps_to_range (f : α → β) (s : set α) : maps_to f s (range f) := (maps_to_image f s).mono (subset.refl s) (image_subset_range _ _) @[simp] lemma maps_image_to (f : α → β) (g : γ → α) (s : set γ) (t : set β) : maps_to f (g '' s) t ↔ maps_to (f ∘ g) s t := ⟨λ h c hc, h ⟨c, hc, rfl⟩, λ h d ⟨c, hc⟩, hc.2 ▸ h hc.1⟩ @[simp] lemma maps_univ_to (f : α → β) (s : set β) : maps_to f univ s ↔ ∀ a, f a ∈ s := ⟨λ h a, h (mem_univ _), λ h x _, h x⟩ @[simp] lemma maps_range_to (f : α → β) (g : γ → α) (s : set β) : maps_to f (range g) s ↔ maps_to (f ∘ g) univ s := by rw [←image_univ, maps_image_to] theorem surjective_maps_to_image_restrict (f : α → β) (s : set α) : surjective ((maps_to_image f s).restrict f s (f '' s)) := λ ⟨y, x, hs, hxy⟩, ⟨⟨x, hs⟩, subtype.ext hxy⟩ theorem maps_to.mem_iff (h : maps_to f s t) (hc : maps_to f sᶜ tᶜ) {x} : f x ∈ t ↔ x ∈ s := ⟨λ ht, by_contra $ λ hs, hc hs ht, λ hx, h hx⟩ /-! ### Injectivity on a set -/ /-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/ def inj_on (f : α → β) (s : set α) : Prop := ∀ ⦃x₁ : α⦄, x₁ ∈ s → ∀ ⦃x₂ : α⦄, x₂ ∈ s → f x₁ = f x₂ → x₁ = x₂ theorem subsingleton.inj_on (hs : s.subsingleton) (f : α → β) : inj_on f s := λ x hx y hy h, hs hx hy @[simp] theorem inj_on_empty (f : α → β) : inj_on f ∅ := subsingleton_empty.inj_on f @[simp] theorem inj_on_singleton (f : α → β) (a : α) : inj_on f {a} := subsingleton_singleton.inj_on f theorem inj_on.eq_iff {x y} (h : inj_on f s) (hx : x ∈ s) (hy : y ∈ s) : f x = f y ↔ x = y := ⟨h hx hy, λ h, h ▸ rfl⟩ theorem inj_on.congr (h₁ : inj_on f₁ s) (h : eq_on f₁ f₂ s) : inj_on f₂ s := λ x hx y hy, h hx ▸ h hy ▸ h₁ hx hy theorem eq_on.inj_on_iff (H : eq_on f₁ f₂ s) : inj_on f₁ s ↔ inj_on f₂ s := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ theorem inj_on.mono (h : s₁ ⊆ s₂) (ht : inj_on f s₂) : inj_on f s₁ := λ x hx y hy H, ht (h hx) (h hy) H theorem inj_on_union (h : disjoint s₁ s₂) : inj_on f (s₁ ∪ s₂) ↔ inj_on f s₁ ∧ inj_on f s₂ ∧ ∀ (x ∈ s₁) (y ∈ s₂), f x ≠ f y := begin refine ⟨λ H, ⟨H.mono $ subset_union_left _ _, H.mono $ subset_union_right _ _, _⟩, _⟩, { intros x hx y hy hxy, obtain rfl : x = y, from H (or.inl hx) (or.inr hy) hxy, exact h ⟨hx, hy⟩ }, { rintro ⟨h₁, h₂, h₁₂⟩, rintro x (hx|hx) y (hy|hy) hxy, exacts [h₁ hx hy hxy, (h₁₂ _ hx _ hy hxy).elim, (h₁₂ _ hy _ hx hxy.symm).elim, h₂ hx hy hxy] } end theorem inj_on_insert {f : α → β} {s : set α} {a : α} (has : a ∉ s) : set.inj_on f (insert a s) ↔ set.inj_on f s ∧ f a ∉ f '' s := have disjoint s {a}, from λ x ⟨hxs, (hxa : x = a)⟩, has (hxa ▸ hxs), by { rw [← union_singleton, inj_on_union this], simp } lemma injective_iff_inj_on_univ : injective f ↔ inj_on f univ := ⟨λ h x hx y hy hxy, h hxy, λ h _ _ heq, h trivial trivial heq⟩ lemma inj_on_of_injective (h : injective f) (s : set α) : inj_on f s := λ x hx y hy hxy, h hxy alias inj_on_of_injective ← function.injective.inj_on theorem inj_on.comp (hg : inj_on g t) (hf: inj_on f s) (h : maps_to f s t) : inj_on (g ∘ f) s := λ x hx y hy heq, hf hx hy $ hg (h hx) (h hy) heq lemma inj_on_iff_injective : inj_on f s ↔ injective (s.restrict f) := ⟨λ H a b h, subtype.eq $ H a.2 b.2 h, λ H a as b bs h, congr_arg subtype.val $ @H ⟨a, as⟩ ⟨b, bs⟩ h⟩ alias inj_on_iff_injective ↔ set.inj_on.injective _ lemma inj_on_preimage {B : set (set β)} (hB : B ⊆ 𝒫 (range f)) : inj_on (preimage f) B := λ s hs t ht hst, (preimage_eq_preimage' (hB hs) (hB ht)).1 hst lemma inj_on.mem_of_mem_image {x} (hf : inj_on f s) (hs : s₁ ⊆ s) (h : x ∈ s) (h₁ : f x ∈ f '' s₁) : x ∈ s₁ := let ⟨x', h', eq⟩ := h₁ in hf (hs h') h eq ▸ h' lemma inj_on.mem_image_iff {x} (hf : inj_on f s) (hs : s₁ ⊆ s) (hx : x ∈ s) : f x ∈ f '' s₁ ↔ x ∈ s₁ := ⟨hf.mem_of_mem_image hs hx, mem_image_of_mem f⟩ lemma inj_on.preimage_image_inter (hf : inj_on f s) (hs : s₁ ⊆ s) : f ⁻¹' (f '' s₁) ∩ s = s₁ := ext $ λ x, ⟨λ ⟨h₁, h₂⟩, hf.mem_of_mem_image hs h₂ h₁, λ h, ⟨mem_image_of_mem _ h, hs h⟩⟩ lemma eq_on.cancel_left (h : s.eq_on (g ∘ f₁) (g ∘ f₂)) (hg : t.inj_on g) (hf₁ : s.maps_to f₁ t) (hf₂ : s.maps_to f₂ t) : s.eq_on f₁ f₂ := λ a ha, hg (hf₁ ha) (hf₂ ha) (h ha) lemma inj_on.cancel_left (hg : t.inj_on g) (hf₁ : s.maps_to f₁ t) (hf₂ : s.maps_to f₂ t) : s.eq_on (g ∘ f₁) (g ∘ f₂) ↔ s.eq_on f₁ f₂ := ⟨λ h, h.cancel_left hg hf₁ hf₂, eq_on.comp_left⟩ /-! ### Surjectivity on a set -/ /-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/ def surj_on (f : α → β) (s : set α) (t : set β) : Prop := t ⊆ f '' s theorem surj_on.subset_range (h : surj_on f s t) : t ⊆ range f := subset.trans h $ image_subset_range f s lemma surj_on_iff_exists_map_subtype : surj_on f s t ↔ ∃ (t' : set β) (g : s → t'), t ⊆ t' ∧ surjective g ∧ ∀ x : s, f x = g x := ⟨λ h, ⟨_, (maps_to_image f s).restrict f s _, h, surjective_maps_to_image_restrict _ _, λ _, rfl⟩, λ ⟨t', g, htt', hg, hfg⟩ y hy, let ⟨x, hx⟩ := hg ⟨y, htt' hy⟩ in ⟨x, x.2, by rw [hfg, hx, subtype.coe_mk]⟩⟩ theorem surj_on_empty (f : α → β) (s : set α) : surj_on f s ∅ := empty_subset _ theorem surj_on_image (f : α → β) (s : set α) : surj_on f s (f '' s) := subset.rfl theorem surj_on.comap_nonempty (h : surj_on f s t) (ht : t.nonempty) : s.nonempty := (ht.mono h).of_image theorem surj_on.congr (h : surj_on f₁ s t) (H : eq_on f₁ f₂ s) : surj_on f₂ s t := by rwa [surj_on, ← H.image_eq] theorem eq_on.surj_on_iff (h : eq_on f₁ f₂ s) : surj_on f₁ s t ↔ surj_on f₂ s t := ⟨λ H, H.congr h, λ H, H.congr h.symm⟩ theorem surj_on.mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (hf : surj_on f s₁ t₂) : surj_on f s₂ t₁ := subset.trans ht $ subset.trans hf $ image_subset _ hs theorem surj_on.union (h₁ : surj_on f s t₁) (h₂ : surj_on f s t₂) : surj_on f s (t₁ ∪ t₂) := λ x hx, hx.elim (λ hx, h₁ hx) (λ hx, h₂ hx) theorem surj_on.union_union (h₁ : surj_on f s₁ t₁) (h₂ : surj_on f s₂ t₂) : surj_on f (s₁ ∪ s₂) (t₁ ∪ t₂) := (h₁.mono (subset_union_left _ _) (subset.refl _)).union (h₂.mono (subset_union_right _ _) (subset.refl _)) theorem surj_on.inter_inter (h₁ : surj_on f s₁ t₁) (h₂ : surj_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) : surj_on f (s₁ ∩ s₂) (t₁ ∩ t₂) := begin intros y hy, rcases h₁ hy.1 with ⟨x₁, hx₁, rfl⟩, rcases h₂ hy.2 with ⟨x₂, hx₂, heq⟩, obtain rfl : x₁ = x₂ := h (or.inl hx₁) (or.inr hx₂) heq.symm, exact mem_image_of_mem f ⟨hx₁, hx₂⟩ end theorem surj_on.inter (h₁ : surj_on f s₁ t) (h₂ : surj_on f s₂ t) (h : inj_on f (s₁ ∪ s₂)) : surj_on f (s₁ ∩ s₂) t := inter_self t ▸ h₁.inter_inter h₂ h theorem surj_on.comp (hg : surj_on g t p) (hf : surj_on f s t) : surj_on (g ∘ f) s p := subset.trans hg $ subset.trans (image_subset g hf) $ (image_comp g f s) ▸ subset.refl _ lemma surjective_iff_surj_on_univ : surjective f ↔ surj_on f univ univ := by simp [surjective, surj_on, subset_def] lemma surj_on_iff_surjective : surj_on f s univ ↔ surjective (s.restrict f) := ⟨λ H b, let ⟨a, as, e⟩ := @H b trivial in ⟨⟨a, as⟩, e⟩, λ H b _, let ⟨⟨a, as⟩, e⟩ := H b in ⟨a, as, e⟩⟩ lemma surj_on.image_eq_of_maps_to (h₁ : surj_on f s t) (h₂ : maps_to f s t) : f '' s = t := eq_of_subset_of_subset h₂.image_subset h₁ lemma image_eq_iff_surj_on_maps_to : f '' s = t ↔ s.surj_on f t ∧ s.maps_to f t := begin refine ⟨_, λ h, h.1.image_eq_of_maps_to h.2⟩, rintro rfl, exact ⟨s.surj_on_image f, s.maps_to_image f⟩, end lemma surj_on.maps_to_compl (h : surj_on f s t) (h' : injective f) : maps_to f sᶜ tᶜ := λ x hs ht, let ⟨x', hx', heq⟩ := h ht in hs $ h' heq ▸ hx' lemma maps_to.surj_on_compl (h : maps_to f s t) (h' : surjective f) : surj_on f sᶜ tᶜ := h'.forall.2 $ λ x ht, mem_image_of_mem _ $ λ hs, ht (h hs) lemma eq_on.cancel_right (hf : s.eq_on (g₁ ∘ f) (g₂ ∘ f)) (hf' : s.surj_on f t) : t.eq_on g₁ g₂ := begin intros b hb, obtain ⟨a, ha, rfl⟩ := hf' hb, exact hf ha, end lemma surj_on.cancel_right (hf : s.surj_on f t) (hf' : s.maps_to f t) : s.eq_on (g₁ ∘ f) (g₂ ∘ f) ↔ t.eq_on g₁ g₂ := ⟨λ h, h.cancel_right hf, λ h, h.comp_right hf'⟩ lemma eq_on_comp_right_iff : s.eq_on (g₁ ∘ f) (g₂ ∘ f) ↔ (f '' s).eq_on g₁ g₂ := (s.surj_on_image f).cancel_right $ s.maps_to_image f /-! ### Bijectivity -/ /-- `f` is bijective from `s` to `t` if `f` is injective on `s` and `f '' s = t`. -/ def bij_on (f : α → β) (s : set α) (t : set β) : Prop := maps_to f s t ∧ inj_on f s ∧ surj_on f s t lemma bij_on.maps_to (h : bij_on f s t) : maps_to f s t := h.left lemma bij_on.inj_on (h : bij_on f s t) : inj_on f s := h.right.left lemma bij_on.surj_on (h : bij_on f s t) : surj_on f s t := h.right.right lemma bij_on.mk (h₁ : maps_to f s t) (h₂ : inj_on f s) (h₃ : surj_on f s t) : bij_on f s t := ⟨h₁, h₂, h₃⟩ lemma bij_on_empty (f : α → β) : bij_on f ∅ ∅ := ⟨maps_to_empty f ∅, inj_on_empty f, surj_on_empty f ∅⟩ lemma bij_on.inter (h₁ : bij_on f s₁ t₁) (h₂ : bij_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) : bij_on f (s₁ ∩ s₂) (t₁ ∩ t₂) := ⟨h₁.maps_to.inter_inter h₂.maps_to, h₁.inj_on.mono $ inter_subset_left _ _, h₁.surj_on.inter_inter h₂.surj_on h⟩ lemma bij_on.union (h₁ : bij_on f s₁ t₁) (h₂ : bij_on f s₂ t₂) (h : inj_on f (s₁ ∪ s₂)) : bij_on f (s₁ ∪ s₂) (t₁ ∪ t₂) := ⟨h₁.maps_to.union_union h₂.maps_to, h, h₁.surj_on.union_union h₂.surj_on⟩ theorem bij_on.subset_range (h : bij_on f s t) : t ⊆ range f := h.surj_on.subset_range lemma inj_on.bij_on_image (h : inj_on f s) : bij_on f s (f '' s) := bij_on.mk (maps_to_image f s) h (subset.refl _) theorem bij_on.congr (h₁ : bij_on f₁ s t) (h : eq_on f₁ f₂ s) : bij_on f₂ s t := bij_on.mk (h₁.maps_to.congr h) (h₁.inj_on.congr h) (h₁.surj_on.congr h) theorem eq_on.bij_on_iff (H : eq_on f₁ f₂ s) : bij_on f₁ s t ↔ bij_on f₂ s t := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ lemma bij_on.image_eq (h : bij_on f s t) : f '' s = t := h.surj_on.image_eq_of_maps_to h.maps_to theorem bij_on.comp (hg : bij_on g t p) (hf : bij_on f s t) : bij_on (g ∘ f) s p := bij_on.mk (hg.maps_to.comp hf.maps_to) (hg.inj_on.comp hf.inj_on hf.maps_to) (hg.surj_on.comp hf.surj_on) theorem bij_on.bijective (h : bij_on f s t) : bijective (t.cod_restrict (s.restrict f) $ λ x, h.maps_to x.val_prop) := ⟨λ x y h', subtype.ext $ h.inj_on x.2 y.2 $ subtype.ext_iff.1 h', λ ⟨y, hy⟩, let ⟨x, hx, hxy⟩ := h.surj_on hy in ⟨⟨x, hx⟩, subtype.eq hxy⟩⟩ lemma bijective_iff_bij_on_univ : bijective f ↔ bij_on f univ univ := iff.intro (λ h, let ⟨inj, surj⟩ := h in ⟨maps_to_univ f _, inj.inj_on _, iff.mp surjective_iff_surj_on_univ surj⟩) (λ h, let ⟨map, inj, surj⟩ := h in ⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩) lemma bij_on.compl (hst : bij_on f s t) (hf : bijective f) : bij_on f sᶜ tᶜ := ⟨hst.surj_on.maps_to_compl hf.1, hf.1.inj_on _, hst.maps_to.surj_on_compl hf.2⟩ /-! ### left inverse -/ /-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/ def left_inv_on (f' : β → α) (f : α → β) (s : set α) : Prop := ∀ ⦃x⦄, x ∈ s → f' (f x) = x lemma left_inv_on.eq_on (h : left_inv_on f' f s) : eq_on (f' ∘ f) id s := h lemma left_inv_on.eq (h : left_inv_on f' f s) {x} (hx : x ∈ s) : f' (f x) = x := h hx lemma left_inv_on.congr_left (h₁ : left_inv_on f₁' f s) {t : set β} (h₁' : maps_to f s t) (heq : eq_on f₁' f₂' t) : left_inv_on f₂' f s := λ x hx, heq (h₁' hx) ▸ h₁ hx theorem left_inv_on.congr_right (h₁ : left_inv_on f₁' f₁ s) (heq : eq_on f₁ f₂ s) : left_inv_on f₁' f₂ s := λ x hx, heq hx ▸ h₁ hx theorem left_inv_on.inj_on (h : left_inv_on f₁' f s) : inj_on f s := λ x₁ h₁ x₂ h₂ heq, calc x₁ = f₁' (f x₁) : eq.symm $ h h₁ ... = f₁' (f x₂) : congr_arg f₁' heq ... = x₂ : h h₂ theorem left_inv_on.surj_on (h : left_inv_on f' f s) (hf : maps_to f s t) : surj_on f' t s := λ x hx, ⟨f x, hf hx, h hx⟩ theorem left_inv_on.maps_to (h : left_inv_on f' f s) (hf : surj_on f s t) : maps_to f' t s := λ y hy, let ⟨x, hs, hx⟩ := hf hy in by rwa [← hx, h hs] theorem left_inv_on.comp (hf' : left_inv_on f' f s) (hg' : left_inv_on g' g t) (hf : maps_to f s t) : left_inv_on (f' ∘ g') (g ∘ f) s := λ x h, calc (f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (hg' (hf h)) ... = x : hf' h theorem left_inv_on.mono (hf : left_inv_on f' f s) (ht : s₁ ⊆ s) : left_inv_on f' f s₁ := λ x hx, hf (ht hx) theorem left_inv_on.image_inter' (hf : left_inv_on f' f s) : f '' (s₁ ∩ s) = f' ⁻¹' s₁ ∩ f '' s := begin apply subset.antisymm, { rintro _ ⟨x, ⟨h₁, h⟩, rfl⟩, exact ⟨by rwa [mem_preimage, hf h], mem_image_of_mem _ h⟩ }, { rintro _ ⟨h₁, ⟨x, h, rfl⟩⟩, exact mem_image_of_mem _ ⟨by rwa ← hf h, h⟩ } end theorem left_inv_on.image_inter (hf : left_inv_on f' f s) : f '' (s₁ ∩ s) = f' ⁻¹' (s₁ ∩ s) ∩ f '' s := begin rw hf.image_inter', refine subset.antisymm _ (inter_subset_inter_left _ (preimage_mono $ inter_subset_left _ _)), rintro _ ⟨h₁, x, hx, rfl⟩, exact ⟨⟨h₁, by rwa hf hx⟩, mem_image_of_mem _ hx⟩ end theorem left_inv_on.image_image (hf : left_inv_on f' f s) : f' '' (f '' s) = s := by rw [image_image, image_congr hf, image_id'] theorem left_inv_on.image_image' (hf : left_inv_on f' f s) (hs : s₁ ⊆ s) : f' '' (f '' s₁) = s₁ := (hf.mono hs).image_image /-! ### Right inverse -/ /-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/ @[reducible] def right_inv_on (f' : β → α) (f : α → β) (t : set β) : Prop := left_inv_on f f' t lemma right_inv_on.eq_on (h : right_inv_on f' f t) : eq_on (f ∘ f') id t := h lemma right_inv_on.eq (h : right_inv_on f' f t) {y} (hy : y ∈ t) : f (f' y) = y := h hy lemma left_inv_on.right_inv_on_image (h : left_inv_on f' f s) : right_inv_on f' f (f '' s) := λ y ⟨x, hx, eq⟩, eq ▸ congr_arg f $ h.eq hx theorem right_inv_on.congr_left (h₁ : right_inv_on f₁' f t) (heq : eq_on f₁' f₂' t) : right_inv_on f₂' f t := h₁.congr_right heq theorem right_inv_on.congr_right (h₁ : right_inv_on f' f₁ t) (hg : maps_to f' t s) (heq : eq_on f₁ f₂ s) : right_inv_on f' f₂ t := left_inv_on.congr_left h₁ hg heq theorem right_inv_on.surj_on (hf : right_inv_on f' f t) (hf' : maps_to f' t s) : surj_on f s t := hf.surj_on hf' theorem right_inv_on.maps_to (h : right_inv_on f' f t) (hf : surj_on f' t s) : maps_to f s t := h.maps_to hf theorem right_inv_on.comp (hf : right_inv_on f' f t) (hg : right_inv_on g' g p) (g'pt : maps_to g' p t) : right_inv_on (f' ∘ g') (g ∘ f) p := hg.comp hf g'pt theorem right_inv_on.mono (hf : right_inv_on f' f t) (ht : t₁ ⊆ t) : right_inv_on f' f t₁ := hf.mono ht theorem inj_on.right_inv_on_of_left_inv_on (hf : inj_on f s) (hf' : left_inv_on f f' t) (h₁ : maps_to f s t) (h₂ : maps_to f' t s) : right_inv_on f f' s := λ x h, hf (h₂ $ h₁ h) h (hf' (h₁ h)) theorem eq_on_of_left_inv_on_of_right_inv_on (h₁ : left_inv_on f₁' f s) (h₂ : right_inv_on f₂' f t) (h : maps_to f₂' t s) : eq_on f₁' f₂' t := λ y hy, calc f₁' y = (f₁' ∘ f ∘ f₂') y : congr_arg f₁' (h₂ hy).symm ... = f₂' y : h₁ (h hy) theorem surj_on.left_inv_on_of_right_inv_on (hf : surj_on f s t) (hf' : right_inv_on f f' s) : left_inv_on f f' t := λ y hy, let ⟨x, hx, heq⟩ := hf hy in by rw [← heq, hf' hx] /-! ### Two-side inverses -/ /-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/ def inv_on (g : β → α) (f : α → β) (s : set α) (t : set β) : Prop := left_inv_on g f s ∧ right_inv_on g f t lemma inv_on.symm (h : inv_on f' f s t) : inv_on f f' t s := ⟨h.right, h.left⟩ lemma inv_on.mono (h : inv_on f' f s t) (hs : s₁ ⊆ s) (ht : t₁ ⊆ t) : inv_on f' f s₁ t₁ := ⟨h.1.mono hs, h.2.mono ht⟩ /-- If functions `f'` and `f` are inverse on `s` and `t`, `f` maps `s` into `t`, and `f'` maps `t` into `s`, then `f` is a bijection between `s` and `t`. The `maps_to` arguments can be deduced from `surj_on` statements using `left_inv_on.maps_to` and `right_inv_on.maps_to`. -/ theorem inv_on.bij_on (h : inv_on f' f s t) (hf : maps_to f s t) (hf' : maps_to f' t s) : bij_on f s t := ⟨hf, h.left.inj_on, h.right.surj_on hf'⟩ end set /-! ### `inv_fun_on` is a left/right inverse -/ namespace function variables [nonempty α] {s : set α} {f : α → β} {a : α} {b : β} local attribute [instance, priority 10] classical.prop_decidable /-- Construct the inverse for a function `f` on domain `s`. This function is a right inverse of `f` on `f '' s`. For a computable version, see `function.injective.inv_of_mem_range`. -/ noncomputable def inv_fun_on (f : α → β) (s : set α) (b : β) : α := if h : ∃a, a ∈ s ∧ f a = b then classical.some h else classical.choice ‹nonempty α› theorem inv_fun_on_pos (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s ∧ f (inv_fun_on f s b) = b := by rw [bex_def] at h; rw [inv_fun_on, dif_pos h]; exact classical.some_spec h theorem inv_fun_on_mem (h : ∃a∈s, f a = b) : inv_fun_on f s b ∈ s := (inv_fun_on_pos h).left theorem inv_fun_on_eq (h : ∃a∈s, f a = b) : f (inv_fun_on f s b) = b := (inv_fun_on_pos h).right theorem inv_fun_on_neg (h : ¬ ∃a∈s, f a = b) : inv_fun_on f s b = classical.choice ‹nonempty α› := by rw [bex_def] at h; rw [inv_fun_on, dif_neg h] end function namespace set open function variables {s s₁ s₂ : set α} {t : set β} {f : α → β} theorem inj_on.left_inv_on_inv_fun_on [nonempty α] (h : inj_on f s) : left_inv_on (inv_fun_on f s) f s := λ a ha, have ∃a'∈s, f a' = f a, from ⟨a, ha, rfl⟩, h (inv_fun_on_mem this) ha (inv_fun_on_eq this) lemma inj_on.inv_fun_on_image [nonempty α] (h : inj_on f s₂) (ht : s₁ ⊆ s₂) : (inv_fun_on f s₂) '' (f '' s₁) = s₁ := h.left_inv_on_inv_fun_on.image_image' ht theorem surj_on.right_inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) : right_inv_on (inv_fun_on f s) f t := λ y hy, inv_fun_on_eq $ mem_image_iff_bex.1 $ h hy theorem bij_on.inv_on_inv_fun_on [nonempty α] (h : bij_on f s t) : inv_on (inv_fun_on f s) f s t := ⟨h.inj_on.left_inv_on_inv_fun_on, h.surj_on.right_inv_on_inv_fun_on⟩ theorem surj_on.inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) : inv_on (inv_fun_on f s) f (inv_fun_on f s '' t) t := begin refine ⟨_, h.right_inv_on_inv_fun_on⟩, rintros _ ⟨y, hy, rfl⟩, rw [h.right_inv_on_inv_fun_on hy] end theorem surj_on.maps_to_inv_fun_on [nonempty α] (h : surj_on f s t) : maps_to (inv_fun_on f s) t s := λ y hy, mem_preimage.2 $ inv_fun_on_mem $ mem_image_iff_bex.1 $ h hy theorem surj_on.bij_on_subset [nonempty α] (h : surj_on f s t) : bij_on f (inv_fun_on f s '' t) t := begin refine h.inv_on_inv_fun_on.bij_on _ (maps_to_image _ _), rintros _ ⟨y, hy, rfl⟩, rwa [h.right_inv_on_inv_fun_on hy] end theorem surj_on_iff_exists_bij_on_subset : surj_on f s t ↔ ∃ s' ⊆ s, bij_on f s' t := begin split, { rcases eq_empty_or_nonempty t with rfl|ht, { exact λ _, ⟨∅, empty_subset _, bij_on_empty f⟩ }, { assume h, haveI : nonempty α := ⟨classical.some (h.comap_nonempty ht)⟩, exact ⟨_, h.maps_to_inv_fun_on.image_subset, h.bij_on_subset⟩ }}, { rintros ⟨s', hs', hfs'⟩, exact hfs'.surj_on.mono hs' (subset.refl _) } end lemma preimage_inv_fun_of_mem [n : nonempty α] {f : α → β} (hf : injective f) {s : set α} (h : classical.choice n ∈ s) : inv_fun f ⁻¹' s = f '' s ∪ (range f)ᶜ := begin ext x, rcases em (x ∈ range f) with ⟨a, rfl⟩|hx, { simp [left_inverse_inv_fun hf _, hf.mem_set_image] }, { simp [mem_preimage, inv_fun_neg hx, h, hx] } end lemma preimage_inv_fun_of_not_mem [n : nonempty α] {f : α → β} (hf : injective f) {s : set α} (h : classical.choice n ∉ s) : inv_fun f ⁻¹' s = f '' s := begin ext x, rcases em (x ∈ range f) with ⟨a, rfl⟩|hx, { rw [mem_preimage, left_inverse_inv_fun hf, hf.mem_set_image] }, { have : x ∉ f '' s, from λ h', hx (image_subset_range _ _ h'), simp only [mem_preimage, inv_fun_neg hx, h, this] }, end end set /-! ### Monotone -/ namespace monotone variables [preorder α] [preorder β] {f : α → β} protected lemma restrict (h : monotone f) (s : set α) : monotone (s.restrict f) := λ x y hxy, h hxy protected lemma cod_restrict (h : monotone f) {s : set β} (hs : ∀ x, f x ∈ s) : monotone (s.cod_restrict f hs) := h protected lemma range_factorization (h : monotone f) : monotone (set.range_factorization f) := h end monotone /-! ### Piecewise defined function -/ namespace set variables {δ : α → Sort y} (s : set α) (f g : Πi, δ i) @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : set α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (set.univ : set α))] : piecewise set.univ f g = f := by { ext i, simp [piecewise] } @[simp] lemma piecewise_insert_self {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] variable [∀j, decidable (j ∈ s)] instance compl.decidable_mem (j : α) : decidable (j ∈ sᶜ) := not.decidable lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) := begin simp [piecewise], ext i, by_cases h : i = j, { rw h, simp }, { by_cases h' : i ∈ s; simp [h, h'] } end @[simp, priority 990] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := if_pos hi @[simp, priority 990] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := if_neg hi lemma piecewise_singleton (x : α) [Π y, decidable (y ∈ ({x} : set α))] [decidable_eq α] (f g : α → β) : piecewise {x} f g = function.update g x (f x) := by { ext y, by_cases hy : y = x, { subst y, simp }, { simp [hy] } } lemma piecewise_eq_on (f g : α → β) : eq_on (s.piecewise f g) f s := λ _, piecewise_eq_of_mem _ _ _ lemma piecewise_eq_on_compl (f g : α → β) : eq_on (s.piecewise f g) g sᶜ := λ _, piecewise_eq_of_not_mem _ _ _ lemma piecewise_le {δ : α → Type*} [Π i, preorder (δ i)] {s : set α} [Π j, decidable (j ∈ s)] {f₁ f₂ g : Π i, δ i} (h₁ : ∀ i ∈ s, f₁ i ≤ g i) (h₂ : ∀ i ∉ s, f₂ i ≤ g i) : s.piecewise f₁ f₂ ≤ g := λ i, if h : i ∈ s then by simp * else by simp * lemma le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {s : set α} [Π j, decidable (j ∈ s)] {f₁ f₂ g : Π i, δ i} (h₁ : ∀ i ∈ s, g i ≤ f₁ i) (h₂ : ∀ i ∉ s, g i ≤ f₂ i) : g ≤ s.piecewise f₁ f₂ := @piecewise_le α (λ i, (δ i)ᵒᵈ) _ s _ _ _ _ h₁ h₂ lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {s : set α} [Π j, decidable (j ∈ s)] {f₁ f₂ g₁ g₂ : Π i, δ i} (h₁ : ∀ i ∈ s, f₁ i ≤ g₁ i) (h₂ : ∀ i ∉ s, f₂ i ≤ g₂ i) : s.piecewise f₁ f₂ ≤ s.piecewise g₁ g₂ := by apply piecewise_le; intros; simp * @[simp, priority 990] lemma piecewise_insert_of_ne {i j : α} (h : i ≠ j) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] @[simp] lemma piecewise_compl [∀ i, decidable (i ∈ sᶜ)] : sᶜ.piecewise f g = s.piecewise g f := funext $ λ x, if hx : x ∈ s then by simp [hx] else by simp [hx] @[simp] lemma piecewise_range_comp {ι : Sort*} (f : ι → α) [Π j, decidable (j ∈ range f)] (g₁ g₂ : α → β) : (range f).piecewise g₁ g₂ ∘ f = g₁ ∘ f := comp_eq_of_eq_on_range $ piecewise_eq_on _ _ _ theorem maps_to.piecewise_ite {s s₁ s₂ : set α} {t t₁ t₂ : set β} {f₁ f₂ : α → β} [∀ i, decidable (i ∈ s)] (h₁ : maps_to f₁ (s₁ ∩ s) (t₁ ∩ t)) (h₂ : maps_to f₂ (s₂ ∩ sᶜ) (t₂ ∩ tᶜ)) : maps_to (s.piecewise f₁ f₂) (s.ite s₁ s₂) (t.ite t₁ t₂) := begin refine (h₁.congr _).union_union (h₂.congr _), exacts [(piecewise_eq_on s f₁ f₂).symm.mono (inter_subset_right _ _), (piecewise_eq_on_compl s f₁ f₂).symm.mono (inter_subset_right _ _)] end theorem eq_on_piecewise {f f' g : α → β} {t} : eq_on (s.piecewise f f') g t ↔ eq_on f g (t ∩ s) ∧ eq_on f' g (t ∩ sᶜ) := begin simp only [eq_on, ← forall_and_distrib], refine forall_congr (λ a, _), by_cases a ∈ s; simp * end theorem eq_on.piecewise_ite' {f f' g : α → β} {t t'} (h : eq_on f g (t ∩ s)) (h' : eq_on f' g (t' ∩ sᶜ)) : eq_on (s.piecewise f f') g (s.ite t t') := by simp [eq_on_piecewise, *] theorem eq_on.piecewise_ite {f f' g : α → β} {t t'} (h : eq_on f g t) (h' : eq_on f' g t') : eq_on (s.piecewise f f') g (s.ite t t') := (h.mono (inter_subset_left _ _)).piecewise_ite' s (h'.mono (inter_subset_left _ _)) lemma piecewise_preimage (f g : α → β) (t) : s.piecewise f g ⁻¹' t = s.ite (f ⁻¹' t) (g ⁻¹' t) := ext $ λ x, by by_cases x ∈ s; simp [*, set.ite] lemma apply_piecewise {δ' : α → Sort*} (h : Π i, δ i → δ' i) {x : α} : h x (s.piecewise f g x) = s.piecewise (λ x, h x (f x)) (λ x, h x (g x)) x := by by_cases hx : x ∈ s; simp [hx] lemma apply_piecewise₂ {δ' δ'' : α → Sort*} (f' g' : Π i, δ' i) (h : Π i, δ i → δ' i → δ'' i) {x : α} : h x (s.piecewise f g x) (s.piecewise f' g' x) = s.piecewise (λ x, h x (f x) (f' x)) (λ x, h x (g x) (g' x)) x := by by_cases hx : x ∈ s; simp [hx] lemma piecewise_op {δ' : α → Sort*} (h : Π i, δ i → δ' i) : s.piecewise (λ x, h x (f x)) (λ x, h x (g x)) = λ x, h x (s.piecewise f g x) := funext $ λ x, (apply_piecewise _ _ _ _).symm lemma piecewise_op₂ {δ' δ'' : α → Sort*} (f' g' : Π i, δ' i) (h : Π i, δ i → δ' i → δ'' i) : s.piecewise (λ x, h x (f x) (f' x)) (λ x, h x (g x) (g' x)) = λ x, h x (s.piecewise f g x) (s.piecewise f' g' x) := funext $ λ x, (apply_piecewise₂ _ _ _ _ _ _).symm @[simp] lemma piecewise_same : s.piecewise f f = f := by { ext x, by_cases hx : x ∈ s; simp [hx] } lemma range_piecewise (f g : α → β) : range (s.piecewise f g) = f '' s ∪ g '' sᶜ := begin ext y, split, { rintro ⟨x, rfl⟩, by_cases h : x ∈ s;[left, right]; use x; simp [h] }, { rintro (⟨x, hx, rfl⟩|⟨x, hx, rfl⟩); use x; simp * at * } end lemma injective_piecewise_iff {f g : α → β} : injective (s.piecewise f g) ↔ inj_on f s ∧ inj_on g sᶜ ∧ (∀ (x ∈ s) (y ∉ s), f x ≠ g y) := begin rw [injective_iff_inj_on_univ, ← union_compl_self s, inj_on_union (@disjoint_compl_right _ s _), (piecewise_eq_on s f g).inj_on_iff, (piecewise_eq_on_compl s f g).inj_on_iff], refine and_congr iff.rfl (and_congr iff.rfl $ forall₄_congr $ λ x hx y hy, _), rw [piecewise_eq_of_mem s f g hx, piecewise_eq_of_not_mem s f g hy] end lemma piecewise_mem_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)} {f g} (hf : f ∈ pi t t') (hg : g ∈ pi t t') : s.piecewise f g ∈ pi t t' := by { intros i ht, by_cases hs : i ∈ s; simp [hf i ht, hg i ht, hs] } @[simp] lemma pi_piecewise {ι : Type*} {α : ι → Type*} (s s' : set ι) (t t' : Π i, set (α i)) [Π x, decidable (x ∈ s')] : pi s (s'.piecewise t t') = pi (s ∩ s') t ∩ pi (s \ s') t' := begin ext x, simp only [mem_pi, mem_inter_eq, ← forall_and_distrib], refine forall_congr (λ i, _), by_cases hi : i ∈ s'; simp * end lemma univ_pi_piecewise {ι : Type*} {α : ι → Type*} (s : set ι) (t : Π i, set (α i)) [Π x, decidable (x ∈ s)] : pi univ (s.piecewise t (λ _, univ)) = pi s t := by simp end set lemma strict_mono_on.inj_on [linear_order α] [preorder β] {f : α → β} {s : set α} (H : strict_mono_on f s) : s.inj_on f := λ x hx y hy hxy, show ordering.eq.compares x y, from (H.compares hx hy).1 hxy lemma strict_anti_on.inj_on [linear_order α] [preorder β] {f : α → β} {s : set α} (H : strict_anti_on f s) : s.inj_on f := @strict_mono_on.inj_on α βᵒᵈ _ _ f s H lemma strict_mono_on.comp [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_mono_on g t) (hf : strict_mono_on f s) (hs : set.maps_to f s t) : strict_mono_on (g ∘ f) s := λ x hx y hy hxy, hg (hs hx) (hs hy) $ hf hx hy hxy lemma strict_mono_on.comp_strict_anti_on [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_mono_on g t) (hf : strict_anti_on f s) (hs : set.maps_to f s t) : strict_anti_on (g ∘ f) s := λ x hx y hy hxy, hg (hs hy) (hs hx) $ hf hx hy hxy lemma strict_anti_on.comp [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_anti_on g t) (hf : strict_anti_on f s) (hs : set.maps_to f s t) : strict_mono_on (g ∘ f) s := λ x hx y hy hxy, hg (hs hy) (hs hx) $ hf hx hy hxy lemma strict_anti_on.comp_strict_mono_on [preorder α] [preorder β] [preorder γ] {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : strict_anti_on g t) (hf : strict_mono_on f s) (hs : set.maps_to f s t) : strict_anti_on (g ∘ f) s := λ x hx y hy hxy, hg (hs hx) (hs hy) $ hf hx hy hxy lemma strict_mono.cod_restrict [preorder α] [preorder β] {f : α → β} (hf : strict_mono f) {s : set β} (hs : ∀ x, f x ∈ s) : strict_mono (set.cod_restrict f s hs) := hf namespace function open set variables {fa : α → α} {fb : β → β} {f : α → β} {g : β → γ} {s t : set α} lemma injective.comp_inj_on (hg : injective g) (hf : s.inj_on f) : s.inj_on (g ∘ f) := (hg.inj_on univ).comp hf (maps_to_univ _ _) lemma surjective.surj_on (hf : surjective f) (s : set β) : surj_on f univ s := (surjective_iff_surj_on_univ.1 hf).mono (subset.refl _) (subset_univ _) lemma left_inverse.left_inv_on {g : β → α} (h : left_inverse f g) (s : set β) : left_inv_on f g s := λ x hx, h x lemma right_inverse.right_inv_on {g : β → α} (h : right_inverse f g) (s : set α) : right_inv_on f g s := λ x hx, h x lemma left_inverse.right_inv_on_range {g : β → α} (h : left_inverse f g) : right_inv_on f g (range g) := forall_range_iff.2 $ λ i, congr_arg g (h i) namespace semiconj lemma maps_to_image (h : semiconj f fa fb) (ha : maps_to fa s t) : maps_to fb (f '' s) (f '' t) := λ y ⟨x, hx, hy⟩, hy ▸ ⟨fa x, ha hx, h x⟩ lemma maps_to_range (h : semiconj f fa fb) : maps_to fb (range f) (range f) := λ y ⟨x, hy⟩, hy ▸ ⟨fa x, h x⟩ lemma surj_on_image (h : semiconj f fa fb) (ha : surj_on fa s t) : surj_on fb (f '' s) (f '' t) := begin rintros y ⟨x, hxt, rfl⟩, rcases ha hxt with ⟨x, hxs, rfl⟩, rw [h x], exact mem_image_of_mem _ (mem_image_of_mem _ hxs) end lemma surj_on_range (h : semiconj f fa fb) (ha : surjective fa) : surj_on fb (range f) (range f) := by { rw ← image_univ, exact h.surj_on_image (ha.surj_on univ) } lemma inj_on_image (h : semiconj f fa fb) (ha : inj_on fa s) (hf : inj_on f (fa '' s)) : inj_on fb (f '' s) := begin rintros _ ⟨x, hx, rfl⟩ _ ⟨y, hy, rfl⟩ H, simp only [← h.eq] at H, exact congr_arg f (ha hx hy $ hf (mem_image_of_mem fa hx) (mem_image_of_mem fa hy) H) end lemma inj_on_range (h : semiconj f fa fb) (ha : injective fa) (hf : inj_on f (range fa)) : inj_on fb (range f) := by { rw ← image_univ at *, exact h.inj_on_image (ha.inj_on univ) hf } lemma bij_on_image (h : semiconj f fa fb) (ha : bij_on fa s t) (hf : inj_on f t) : bij_on fb (f '' s) (f '' t) := ⟨h.maps_to_image ha.maps_to, h.inj_on_image ha.inj_on (ha.image_eq.symm ▸ hf), h.surj_on_image ha.surj_on⟩ lemma bij_on_range (h : semiconj f fa fb) (ha : bijective fa) (hf : injective f) : bij_on fb (range f) (range f) := begin rw [← image_univ], exact h.bij_on_image (bijective_iff_bij_on_univ.1 ha) (hf.inj_on univ) end lemma maps_to_preimage (h : semiconj f fa fb) {s t : set β} (hb : maps_to fb s t) : maps_to fa (f ⁻¹' s) (f ⁻¹' t) := λ x hx, by simp only [mem_preimage, h x, hb hx] lemma inj_on_preimage (h : semiconj f fa fb) {s : set β} (hb : inj_on fb s) (hf : inj_on f (f ⁻¹' s)) : inj_on fa (f ⁻¹' s) := begin intros x hx y hy H, have := congr_arg f H, rw [h.eq, h.eq] at this, exact hf hx hy (hb hx hy this) end end semiconj lemma update_comp_eq_of_not_mem_range' {α β : Sort*} {γ : β → Sort*} [decidable_eq β] (g : Π b, γ b) {f : α → β} {i : β} (a : γ i) (h : i ∉ set.range f) : (λ j, (function.update g i a) (f j)) = (λ j, g (f j)) := update_comp_eq_of_forall_ne' _ _ $ λ x hx, h ⟨x, hx⟩ /-- Non-dependent version of `function.update_comp_eq_of_not_mem_range'` -/ lemma update_comp_eq_of_not_mem_range {α β γ : Sort*} [decidable_eq β] (g : β → γ) {f : α → β} {i : β} (a : γ) (h : i ∉ set.range f) : (function.update g i a) ∘ f = g ∘ f := update_comp_eq_of_not_mem_range' g a h lemma insert_inj_on (s : set α) : sᶜ.inj_on (λ a, insert a s) := λ a ha b _, (insert_inj ha).1 end function
ae6b82c6d0cd632287e51908902337e65f308577
4727251e0cd73359b15b664c3170e5d754078599
/src/data/qpf/multivariate/constructions/fix.lean
2d6733aa52772788205e0795de9806d19730ac5c
[ "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
12,887
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Simon Hudon -/ import data.pfunctor.multivariate.W import data.qpf.multivariate.basic /-! # The initial algebra of a multivariate qpf is again a qpf. For a `(n+1)`-ary QPF `F (α₀,..,αₙ)`, we take the least fixed point of `F` with regards to its last argument `αₙ`. The result is a `n`-ary functor: `fix F (α₀,..,αₙ₋₁)`. Making `fix F` into a functor allows us to take the fixed point, compose with other functors and take a fixed point again. ## Main definitions * `fix.mk` - constructor * `fix.dest - destructor * `fix.rec` - recursor: basis for defining functions by structural recursion on `fix F α` * `fix.drec` - dependent recursor: generalization of `fix.rec` where the result type of the function is allowed to depend on the `fix F α` value * `fix.rec_eq` - defining equation for `recursor` * `fix.ind` - induction principle for `fix F α` ## Implementation notes For `F` a QPF`, we define `fix F α` in terms of the W-type of the polynomial functor `P` of `F`. We define the relation `Wequiv` and take its quotient as the definition of `fix F α`. ```lean inductive Wequiv {α : typevec n} : q.P.W α → q.P.W α → Prop | ind (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f₀ f₁ : q.P.last.B a → q.P.W α) : (∀ x, Wequiv (f₀ x) (f₁ x)) → Wequiv (q.P.W_mk a f' f₀) (q.P.W_mk a f' f₁) | abs (a₀ : q.P.A) (f'₀ : q.P.drop.B a₀ ⟹ α) (f₀ : q.P.last.B a₀ → q.P.W α) (a₁ : q.P.A) (f'₁ : q.P.drop.B a₁ ⟹ α) (f₁ : q.P.last.B a₁ → q.P.W α) : abs ⟨a₀, q.P.append_contents f'₀ f₀⟩ = abs ⟨a₁, q.P.append_contents f'₁ f₁⟩ → Wequiv (q.P.W_mk a₀ f'₀ f₀) (q.P.W_mk a₁ f'₁ f₁) | trans (u v w : q.P.W α) : Wequiv u v → Wequiv v w → Wequiv u w ``` See [avigad-carneiro-hudon2019] for more details. ## Reference * Jeremy Avigad, Mario M. Carneiro and Simon Hudon. [*Data Types as Quotients of Polynomial Functors*][avigad-carneiro-hudon2019] -/ universes u v namespace mvqpf open typevec open mvfunctor (liftp liftr) open_locale mvfunctor variables {n : ℕ} {F : typevec.{u} (n+1) → Type u} [mvfunctor F] [q : mvqpf F] include q /-- `recF` is used as a basis for defining the recursor on `fix F α`. `recF` traverses recursively the W-type generated by `q.P` using a function on `F` as a recursive step -/ def recF {α : typevec n} {β : Type*} (g : F (α.append1 β) → β) : q.P.W α → β := q.P.W_rec (λ a f' f rec, g (abs ⟨a, split_fun f' rec⟩)) theorem recF_eq {α : typevec n} {β : Type*} (g : F (α.append1 β) → β) (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : recF g (q.P.W_mk a f' f) = g (abs ⟨a, split_fun f' (recF g ∘ f)⟩) := by rw [recF, mvpfunctor.W_rec_eq]; refl theorem recF_eq' {α : typevec n} {β : Type*} (g : F (α.append1 β) → β) (x : q.P.W α) : recF g x = g (abs ((append_fun id (recF g)) <$$> q.P.W_dest' x)) := begin apply q.P.W_cases _ x, intros a f' f, rw [recF_eq, q.P.W_dest'_W_mk, mvpfunctor.map_eq, append_fun_comp_split_fun, typevec.id_comp] end /-- Equivalence relation on W-types that represent the same `fix F` value -/ inductive Wequiv {α : typevec n} : q.P.W α → q.P.W α → Prop | ind (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f₀ f₁ : q.P.last.B a → q.P.W α) : (∀ x, Wequiv (f₀ x) (f₁ x)) → Wequiv (q.P.W_mk a f' f₀) (q.P.W_mk a f' f₁) | abs (a₀ : q.P.A) (f'₀ : q.P.drop.B a₀ ⟹ α) (f₀ : q.P.last.B a₀ → q.P.W α) (a₁ : q.P.A) (f'₁ : q.P.drop.B a₁ ⟹ α) (f₁ : q.P.last.B a₁ → q.P.W α) : abs ⟨a₀, q.P.append_contents f'₀ f₀⟩ = abs ⟨a₁, q.P.append_contents f'₁ f₁⟩ → Wequiv (q.P.W_mk a₀ f'₀ f₀) (q.P.W_mk a₁ f'₁ f₁) | trans (u v w : q.P.W α) : Wequiv u v → Wequiv v w → Wequiv u w theorem recF_eq_of_Wequiv (α : typevec n) {β : Type*} (u : F (α.append1 β) → β) (x y : q.P.W α) : Wequiv x y → recF u x = recF u y := begin apply q.P.W_cases _ x, intros a₀ f'₀ f₀, apply q.P.W_cases _ y, intros a₁ f'₁ f₁, intro h, induction h, case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih { simp only [recF_eq, function.comp, ih] }, case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h { simp only [recF_eq', abs_map, mvpfunctor.W_dest'_W_mk, h] }, case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { exact eq.trans ih₁ ih₂ } end theorem Wequiv.abs' {α : typevec n} (x y : q.P.W α) (h : abs (q.P.W_dest' x) = abs (q.P.W_dest' y)) : Wequiv x y := begin revert h, apply q.P.W_cases _ x, intros a₀ f'₀ f₀, apply q.P.W_cases _ y, intros a₁ f'₁ f₁, apply Wequiv.abs end theorem Wequiv.refl {α : typevec n} (x : q.P.W α) : Wequiv x x := by apply q.P.W_cases _ x; intros a f' f; exact Wequiv.abs a f' f a f' f rfl theorem Wequiv.symm {α : typevec n} (x y : q.P.W α) : Wequiv x y → Wequiv y x := begin intro h, induction h, case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih { exact Wequiv.ind _ _ _ _ ih }, case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h { exact Wequiv.abs _ _ _ _ _ _ h.symm }, case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { exact mvqpf.Wequiv.trans _ _ _ ih₂ ih₁} end /-- maps every element of the W type to a canonical representative -/ def Wrepr {α : typevec n} : q.P.W α → q.P.W α := recF (q.P.W_mk' ∘ repr) theorem Wrepr_W_mk {α : typevec n} (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : Wrepr (q.P.W_mk a f' f) = q.P.W_mk' (repr (abs ((append_fun id Wrepr) <$$> ⟨a, q.P.append_contents f' f⟩))) := by rw [Wrepr, recF_eq', q.P.W_dest'_W_mk]; refl theorem Wrepr_equiv {α : typevec n} (x : q.P.W α) : Wequiv (Wrepr x) x := begin apply q.P.W_ind _ x, intros a f' f ih, apply Wequiv.trans _ (q.P.W_mk' ((append_fun id Wrepr) <$$> ⟨a, q.P.append_contents f' f⟩)), { apply Wequiv.abs', rw [Wrepr_W_mk, q.P.W_dest'_W_mk', q.P.W_dest'_W_mk', abs_repr] }, rw [q.P.map_eq, mvpfunctor.W_mk', append_fun_comp_split_fun, id_comp], apply Wequiv.ind, exact ih end theorem Wequiv_map {α β : typevec n} (g : α ⟹ β) (x y : q.P.W α) : Wequiv x y → Wequiv (g <$$> x) (g <$$> y) := begin intro h, induction h, case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih { rw [q.P.W_map_W_mk, q.P.W_map_W_mk], apply Wequiv.ind, apply ih }, case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h { rw [q.P.W_map_W_mk, q.P.W_map_W_mk], apply Wequiv.abs, show abs (q.P.obj_append1 a₀ (g ⊚ f'₀) (λ x, q.P.W_map g (f₀ x))) = abs (q.P.obj_append1 a₁ (g ⊚ f'₁) (λ x, q.P.W_map g (f₁ x))), rw [←q.P.map_obj_append1, ←q.P.map_obj_append1, abs_map, abs_map, h] }, case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { apply mvqpf.Wequiv.trans, apply ih₁, apply ih₂ } end /-- Define the fixed point as the quotient of trees under the equivalence relation. -/ def W_setoid (α : typevec n) : setoid (q.P.W α) := ⟨Wequiv, @Wequiv.refl _ _ _ _ _, @Wequiv.symm _ _ _ _ _, @Wequiv.trans _ _ _ _ _⟩ local attribute [instance] W_setoid /-- Least fixed point of functor F. The result is a functor with one fewer parameters than the input. For `F a b c` a ternary functor, fix F is a binary functor such that ```lean fix F a b = F a b (fix F a b) ``` -/ def fix {n : ℕ} (F : typevec (n+1) → Type*) [mvfunctor F] [q : mvqpf F] (α : typevec n) := quotient (W_setoid α : setoid (q.P.W α)) attribute [nolint has_inhabited_instance] fix /-- `fix F` is a functor -/ def fix.map {α β : typevec n} (g : α ⟹ β) : fix F α → fix F β := quotient.lift (λ x : q.P.W α, ⟦q.P.W_map g x⟧) (λ a b h, quot.sound (Wequiv_map _ _ _ h)) instance fix.mvfunctor : mvfunctor (fix F) := { map := @fix.map _ _ _ _} variable {α : typevec.{u} n} /-- Recursor for `fix F` -/ def fix.rec {β : Type u} (g : F (α ::: β) → β) : fix F α → β := quot.lift (recF g) (recF_eq_of_Wequiv α g) /-- Access W-type underlying `fix F` -/ def fix_to_W : fix F α → q.P.W α := quotient.lift Wrepr (recF_eq_of_Wequiv α (λ x, q.P.W_mk' (repr x))) /-- Constructor for `fix F` -/ def fix.mk (x : F (append1 α (fix F α))) : fix F α := quot.mk _ (q.P.W_mk' (append_fun id fix_to_W <$$> repr x)) /-- Destructor for `fix F` -/ def fix.dest : fix F α → F (append1 α (fix F α)) := fix.rec (mvfunctor.map (append_fun id fix.mk)) theorem fix.rec_eq {β : Type u} (g : F (append1 α β) → β) (x : F (append1 α (fix F α))) : fix.rec g (fix.mk x) = g (append_fun id (fix.rec g) <$$> x) := have recF g ∘ fix_to_W = fix.rec g, by { apply funext, apply quotient.ind, intro x, apply recF_eq_of_Wequiv, apply Wrepr_equiv }, begin conv { to_lhs, rw [fix.rec, fix.mk], dsimp }, cases h : repr x with a f, rw [mvpfunctor.map_eq, recF_eq', ←mvpfunctor.map_eq, mvpfunctor.W_dest'_W_mk'], rw [←mvpfunctor.comp_map, abs_map, ←h, abs_repr, ←append_fun_comp, id_comp, this] end theorem fix.ind_aux (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : fix.mk (abs ⟨a, q.P.append_contents f' (λ x, ⟦f x⟧)⟩) = ⟦q.P.W_mk a f' f⟧ := have fix.mk (abs ⟨a, q.P.append_contents f' (λ x, ⟦f x⟧)⟩) = ⟦Wrepr (q.P.W_mk a f' f)⟧, begin apply quot.sound, apply Wequiv.abs', rw [mvpfunctor.W_dest'_W_mk', abs_map, abs_repr, ←abs_map, mvpfunctor.map_eq], conv { to_rhs, rw [Wrepr_W_mk, q.P.W_dest'_W_mk', abs_repr, mvpfunctor.map_eq] }, congr' 2, rw [mvpfunctor.append_contents, mvpfunctor.append_contents], rw [append_fun, append_fun, ←split_fun_comp, ←split_fun_comp], reflexivity end, by { rw this, apply quot.sound, apply Wrepr_equiv } theorem fix.ind_rec {β : Type*} (g₁ g₂ : fix F α → β) (h : ∀ x : F (append1 α (fix F α)), (append_fun id g₁) <$$> x = (append_fun id g₂) <$$> x → g₁ (fix.mk x) = g₂ (fix.mk x)) : ∀ x, g₁ x = g₂ x := begin apply quot.ind, intro x, apply q.P.W_ind _ x, intros a f' f ih, show g₁ ⟦q.P.W_mk a f' f⟧ = g₂ ⟦q.P.W_mk a f' f⟧, rw [←fix.ind_aux a f' f], apply h, rw [←abs_map, ←abs_map, mvpfunctor.map_eq, mvpfunctor.map_eq], congr' 2, rw [mvpfunctor.append_contents, append_fun, append_fun, ←split_fun_comp, ←split_fun_comp], have : g₁ ∘ (λ x, ⟦f x⟧) = g₂ ∘ (λ x, ⟦f x⟧), { ext x, exact ih x }, rw this end theorem fix.rec_unique {β : Type*} (g : F (append1 α β) → β) (h : fix F α → β) (hyp : ∀ x, h (fix.mk x) = g (append_fun id h <$$> x)) : fix.rec g = h := begin ext x, apply fix.ind_rec, intros x hyp', rw [hyp, ←hyp', fix.rec_eq] end theorem fix.mk_dest (x : fix F α) : fix.mk (fix.dest x) = x := begin change (fix.mk ∘ fix.dest) x = x, apply fix.ind_rec, intro x, dsimp, rw [fix.dest, fix.rec_eq, ←comp_map, ←append_fun_comp, id_comp], intro h, rw h, show fix.mk (append_fun id id <$$> x) = fix.mk x, rw [append_fun_id_id, mvfunctor.id_map] end theorem fix.dest_mk (x : F (append1 α (fix F α))) : fix.dest (fix.mk x) = x := begin unfold fix.dest, rw [fix.rec_eq, ←fix.dest, ←comp_map], conv { to_rhs, rw ←(mvfunctor.id_map x) }, rw [←append_fun_comp, id_comp], have : fix.mk ∘ fix.dest = id, {ext x, apply fix.mk_dest }, rw [this, append_fun_id_id] end theorem fix.ind {α : typevec n} (p : fix F α → Prop) (h : ∀ x : F (α.append1 (fix F α)), liftp (pred_last α p) x → p (fix.mk x)) : ∀ x, p x := begin apply quot.ind, intro x, apply q.P.W_ind _ x, intros a f' f ih, change p ⟦q.P.W_mk a f' f⟧, rw [←fix.ind_aux a f' f], apply h, rw mvqpf.liftp_iff, refine ⟨_, _, rfl, _⟩, intros i j, cases i, { apply ih }, { trivial }, end instance mvqpf_fix : mvqpf (fix F) := { P := q.P.Wp, abs := λ α, quot.mk Wequiv, repr := λ α, fix_to_W, abs_repr := by { intros α, apply quot.ind, intro a, apply quot.sound, apply Wrepr_equiv }, abs_map := begin intros α β g x, conv { to_rhs, dsimp [mvfunctor.map]}, rw fix.map, apply quot.sound, apply Wequiv.refl end } /-- Dependent recursor for `fix F` -/ def fix.drec {β : fix F α → Type u} (g : Π x : F (α ::: sigma β), β (fix.mk $ (id ::: sigma.fst) <$$> x)) (x : fix F α) : β x := let y := @fix.rec _ F _ _ α (sigma β) (λ i, ⟨_,g i⟩) x in have x = y.1, by { symmetry, dsimp [y], apply fix.ind_rec _ id _ x, intros x' ih, rw fix.rec_eq, dsimp, simp [append_fun_id_id] at ih, congr, conv { to_rhs, rw [← ih] }, rw [mvfunctor.map_map,← append_fun_comp,id_comp], }, cast (by rw this) y.2 end mvqpf
172381285d8d9a38a19d04ccea1f4fbed6c8cb0b
737dc4b96c97368cb66b925eeea3ab633ec3d702
/src/Lean/Meta/Match/MatchEqs.lean
795c78d4933408300282419dd8d60a8044f570a2
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,729
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Match.Match import Lean.Meta.Tactic.Apply import Lean.Meta.Tactic.Delta import Lean.Meta.Tactic.SplitIf namespace Lean.Meta.Match structure MatchEqns where eqnNames : Array Name splitterName : Name splitterAltNumParams : Array Nat deriving Inhabited, Repr structure MatchEqnsExtState where map : Std.PHashMap Name MatchEqns := {} deriving Inhabited /- We generate the equations and splitter on demand, and do not save them on .olean files. -/ builtin_initialize matchEqnsExt : EnvExtension MatchEqnsExtState ← registerEnvExtension (pure {}) private def registerMatchEqns (matchDeclName : Name) (matchEqns : MatchEqns) : CoreM Unit := modifyEnv fun env => matchEqnsExt.modifyState env fun s => { s with map := s.map.insert matchDeclName matchEqns } /-- Create a "unique" base name for conditional equations and splitter -/ private partial def mkBaseNameFor (env : Environment) (matchDeclName : Name) : Name := if !env.contains (matchDeclName ++ `splitter) then matchDeclName else go 1 where go (idx : Nat) : Name := let baseName := matchDeclName ++ (`_matchEqns).appendIndexAfter idx if !env.contains (baseName ++ `splitter) then baseName else go (idx + 1) /-- Helper method. Recall that alternatives that do not have variables have a `Unit` parameter to ensure they are not eagerly evaluated. -/ private def toFVarsRHSArgs (ys : Array Expr) (resultType : Expr) : MetaM (Array Expr × Array Expr) := do if ys.size == 1 then if (← inferType ys[0]).isConstOf ``Unit && !(← dependsOn resultType ys[0].fvarId!) then return (#[], #[mkConst ``Unit.unit]) return (ys, ys) /-- Simplify/filter hypotheses that ensure that a match alternative does not match the previous ones. Remark: if there is no overlaping between the alternatives, the empty array is returned. -/ private partial def simpHs (hs : Array Expr) (numPatterns : Nat) : MetaM (Array Expr) := do hs.filterMapM fun h => forallTelescope h fun ys _ => do let xs := ys[:ys.size - numPatterns].toArray let eqs ← ys[ys.size - numPatterns : ys.size].toArray.mapM inferType if let some eqsNew ← simpEqs eqs *> get |>.run |>.run' #[] then let newH ← eqsNew.foldrM (init := mkConst ``False) mkArrow let xs ← xs.filterM fun x => dependsOn newH x.fvarId! return some (← mkForallFVars xs newH) else none where simpEq (lhs : Expr) (rhs : Expr) : OptionT (StateRefT (Array Expr) MetaM) Unit := do if isMatchValue lhs && isMatchValue rhs then unless (← isDefEq lhs rhs) do failure else if rhs.isFVar then -- Ignore case since it matches anything pure () else match lhs.arrayLit?, rhs.arrayLit? with | some (_, lhsArgs), some (_, rhsArgs) => if lhsArgs.length != rhsArgs.length then failure else for lhsArg in lhsArgs, rhsArg in rhsArgs do simpEq lhsArg rhsArg | _, _ => match toCtorIfLit lhs |>.constructorApp? (← getEnv), toCtorIfLit rhs |>.constructorApp? (← getEnv) with | some (lhsCtor, lhsArgs), some (rhsCtor, rhsArgs) => if lhsCtor.name == rhsCtor.name then for lhsArg in lhsArgs[lhsCtor.numParams:], rhsArg in rhsArgs[lhsCtor.numParams:] do simpEq lhsArg rhsArg else failure | _, _ => let newEq ← mkEq lhs rhs modify fun eqs => eqs.push newEq simpEqs (eqs : Array Expr) : OptionT (StateRefT (Array Expr) MetaM) Unit := do eqs.forM fun eq => match eq.eq? with | some (_, lhs, rhs) => simpEq lhs rhs | _ => throwError "failed to generate equality theorems for 'match', equality expected{indentExpr eq}" /-- Helper method for `proveCondEqThm`. Given a goal of the form `C.rec ... xMajor = rhs`, apply `cases xMajor`. -/ private def casesOnStuckLHS (mvarId : MVarId) : MetaM (Array MVarId) := do let target ← getMVarType mvarId if let some (_, lhs, rhs) ← matchEq? target then matchConstRec lhs.getAppFn (fun _ => failed) fun recVal _ => do let args := lhs.getAppArgs if recVal.getMajorIdx >= args.size then failed let mut major := args[recVal.getMajorIdx] unless major.isFVar do failed return (← cases mvarId major.fvarId!).map fun s => s.mvarId else failed where failed {α} : MetaM α := throwError "'casesOnStuckLHS' failed" /-- Helper method for proving a conditional equational theorem associated with an alternative of the `match`-eliminator `matchDeclName`. `type` contains the type of the theorem. -/ partial def proveCondEqThm (matchDeclName : Name) (type : Expr) : MetaM Expr := do let type ← instantiateMVars type withLCtx {} {} <| forallTelescope type fun ys target => do let mvar0 ← mkFreshExprSyntheticOpaqueMVar target let mvarId ← deltaTarget mvar0.mvarId! (. == matchDeclName) trace[Meta.Match.matchEqs] "{MessageData.ofGoal mvarId}" go mvarId 0 mkLambdaFVars ys (← instantiateMVars mvar0) where go (mvarId : MVarId) (depth : Nat) : MetaM Unit := withIncRecDepth do let mvarId' ← modifyTargetEqLHS mvarId whnfCore let mvarId := mvarId' let subgoals ← (do applyRefl mvarId; return #[]) <|> (do contradiction mvarId { genDiseq := true }; return #[]) <|> (casesOnStuckLHS mvarId) <|> (do let mvarId' ← simpIfTarget mvarId (useDecide := true) if mvarId' == mvarId then throwError "simpIf failed" return #[mvarId']) <|> (do if let some (s₁, s₂) ← splitIfTarget? mvarId then let mvarId₁ ← trySubst s₁.mvarId s₁.fvarId return #[mvarId₁, s₂.mvarId] else throwError "spliIf failed") <|> (throwError "failed to generate equality theorems for `match` expression, support for array literals has not been implemented yet\n{MessageData.ofGoal mvarId}") subgoals.forM (go . (depth+1)) /-- Construct new local declarations `xs` with types `altTypes`, and then execute `f xs` -/ private partial def withSplitterAlts (altTypes : Array Expr) (f : Array Expr → MetaM α) : MetaM α := do let rec go (i : Nat) (xs : Array Expr) : MetaM α := do if h : i < altTypes.size then let hName := (`h).appendIndexAfter (i+1) withLocalDeclD hName (altTypes.get ⟨i, h⟩) fun x => go (i+1) (xs.push x) else f xs go 0 #[] inductive InjectionAnyResult where | solved | failed | subgoal (mvarId : MVarId) private def injenctionAny (mvarId : MVarId) : MetaM InjectionAnyResult := withMVarContext mvarId do for localDecl in (← getLCtx) do if let some (_, lhs, rhs) ← matchEq? localDecl.type then unless (← isDefEq lhs rhs) do let lhs ← whnf lhs let rhs ← whnf rhs unless lhs.isNatLit && rhs.isNatLit do try match (← injection mvarId localDecl.fvarId) with | InjectionResult.solved => return InjectionAnyResult.solved | InjectionResult.subgoal mvarId .. => return InjectionAnyResult.subgoal mvarId catch _ => pure () return InjectionAnyResult.failed /-- Construct a proof for the splitter generated by `mkEquationsfor`. The proof uses the definition of the `match`-declaration as a template (argument `template`). - `alts` are free variables corresponding to alternatives of the `match` auxiliary declaration being processed. - `altNews` are the new free variables which contains aditional hypotheses that ensure they are only used when the previous overlapping alternatives are not applicable. -/ private partial def mkSplitterProof (matchDeclName : Name) (template : Expr) (alts altsNew : Array Expr) : MetaM Expr := do trace[Meta.Match.matchEqs] "proof template: {template}" let map := mkMap let (proof, mvarIds) ← convertTemplate map |>.run #[] trace[Meta.Match.matchEqs] "splitter proof: {proof}" for mvarId in mvarIds do proveSubgoal mvarId instantiateMVars proof where mkMap : FVarIdMap Expr := do let mut m := {} for alt in alts, altNew in altsNew do m := m.insert alt.fvarId! altNew return m convertTemplate (m : FVarIdMap Expr) : StateRefT (Array MVarId) MetaM Expr := transform template fun e => do match e.getAppFn with | Expr.fvar fvarId .. => match m.find? fvarId with | some altNew => trace[Meta.Match.matchEqs] ">> {e}, {altNew}" let eNew ← if (← shouldCopyArgs e) then addExtraParams (mkAppN altNew e.getAppArgs) else addExtraParams altNew return TransformStep.done eNew | none => return TransformStep.visit e | _ => return TransformStep.visit e shouldCopyArgs (e : Expr) : MetaM Bool := do if e.getAppNumArgs == 1 then match (← whnfD (← inferType e.appFn!)) with | Expr.forallE _ d b _ => /- If result type does not depend on the argument, then argument is an auxiliary unit used because Lean is an eager language, we should not copy it. -/ return b.hasLooseBVar 0 | _ => unreachable! return true addExtraParams (e : Expr) : StateRefT (Array MVarId) MetaM Expr := do trace[Meta.Match.matchEqs] "addExtraParams {e}" let (mvars, _, _) ← forallMetaTelescopeReducing (← inferType e) (kind := MetavarKind.syntheticOpaque) modify fun s => s ++ (mvars.map (·.mvarId!)) return mkAppN e mvars proveSubgoalLoop (mvarId : MVarId) : MetaM Unit := do if (← contradictionCore mvarId {}) then return () match (← injenctionAny mvarId) with | InjectionAnyResult.solved => return () | InjectionAnyResult.failed => throwError "failed to generate splitter for match auxiliary declaration '{matchDeclName}', unsolved subgoal:\n{MessageData.ofGoal mvarId}" | InjectionAnyResult.subgoal mvarId => proveSubgoalLoop mvarId proveSubgoal (mvarId : MVarId) : MetaM Unit := do trace[Meta.Match.matchEqs] "subgoal {mkMVar mvarId}, {repr (← getMVarDecl mvarId).kind}, {← isExprMVarAssigned mvarId}\n{MessageData.ofGoal mvarId}" let (_, mvarId) ← intros mvarId let mvarId ← tryClearMany mvarId (alts.map (·.fvarId!)) proveSubgoalLoop mvarId /-- Create conditional equations and splitter for the given match auxiliary declaration. -/ private partial def mkEquationsFor (matchDeclName : Name) : MetaM MatchEqns := do let baseName := mkBaseNameFor (← getEnv) matchDeclName let constInfo ← getConstInfo matchDeclName let us := constInfo.levelParams.map mkLevelParam let some matchInfo ← getMatcherInfo? matchDeclName | throwError "'{matchDeclName}' is not a matcher function" forallTelescopeReducing constInfo.type fun xs matchResultType => do let mut eqnNames := #[] let params := xs[:matchInfo.numParams] let motive := xs[matchInfo.getMotivePos] let alts := xs[xs.size - matchInfo.numAlts:] let firstDiscrIdx := matchInfo.numParams + 1 let discrs := xs[firstDiscrIdx : firstDiscrIdx + matchInfo.numDiscrs] let mut notAlts := #[] let mut idx := 1 let mut splitterAltTypes := #[] let mut splitterAltNumParams := #[] for alt in alts do let thmName := baseName ++ ((`eq).appendIndexAfter idx) eqnNames := eqnNames.push thmName let altType ← inferType alt let (notAlt, splitterAltType, splitterAltNumParam) ← forallTelescopeReducing altType fun ys altResultType => do let (ys, rhsArgs) ← toFVarsRHSArgs ys altResultType let patterns := altResultType.getAppArgs let mut hs := #[] for notAlt in notAlts do hs := hs.push (← instantiateForall notAlt patterns) hs ← simpHs hs patterns.size trace[Meta.Match.matchEqs] "hs: {hs}" let splitterAltType ← mkForallFVars ys (← hs.foldrM (init := altResultType) mkArrow) let splitterAltNumParam := hs.size + ys.size -- Create a proposition for representing terms that do not match `patterns` let mut notAlt := mkConst ``False for discr in discrs.toArray.reverse, pattern in patterns.reverse do notAlt ← mkArrow (← mkEq discr pattern) notAlt notAlt ← mkForallFVars (discrs ++ ys) notAlt let lhs := mkAppN (mkConst constInfo.name us) (params ++ #[motive] ++ patterns ++ alts) let rhs := mkAppN alt rhsArgs let thmType ← mkEq lhs rhs let thmType ← hs.foldrM (init := thmType) mkArrow let thmType ← mkForallFVars (params ++ #[motive] ++ alts ++ ys) thmType let thmVal ← proveCondEqThm matchDeclName thmType addDecl <| Declaration.thmDecl { name := thmName levelParams := constInfo.levelParams type := thmType value := thmVal } return (notAlt, splitterAltType, splitterAltNumParam) notAlts := notAlts.push notAlt splitterAltTypes := splitterAltTypes.push splitterAltType splitterAltNumParams := splitterAltNumParams.push splitterAltNumParam trace[Meta.Match.matchEqs] "splitterAltType: {splitterAltType}" idx := idx + 1 -- Define splitter with conditional/refined alternatives withSplitterAlts splitterAltTypes fun altsNew => do let splitterParams := params.toArray ++ #[motive] ++ discrs.toArray ++ altsNew let splitterType ← mkForallFVars splitterParams matchResultType trace[Meta.Match.matchEqs] "splitterType: {splitterType}" let template ← mkAppN (mkConst constInfo.name us) (params ++ #[motive] ++ discrs ++ alts) let template ← deltaExpand template (. == constInfo.name) let splitterVal ← mkLambdaFVars splitterParams (← mkSplitterProof matchDeclName template alts altsNew) let splitterName := baseName ++ `splitter addDecl <| Declaration.thmDecl { name := splitterName levelParams := constInfo.levelParams type := splitterType value := splitterVal } let result := { eqnNames, splitterName, splitterAltNumParams } registerMatchEqns matchDeclName result return result def getEquationsFor (matchDeclName : Name) : MetaM MatchEqns := do match matchEqnsExt.getState (← getEnv) |>.map.find? matchDeclName with | some matchEqns => return matchEqns | none => mkEquationsFor matchDeclName builtin_initialize registerTraceClass `Meta.Match.matchEqs end Lean.Meta.Match
074e9c0a6f4d6f69c55dcbcb41fb750d9e45735b
c17c60327eee1622a8d7defa5af340e08619107f
/src/snippets/essai2structures.lean
5456a90c4996799930dd0eb081b953ebe3185ff1
[]
no_license
FredericLeRoux/dEAduction-lean2
277e3aad5102ff155fb04b188dbd01568ceea005
bf7d7d88c2511ecfda5a98ed96e4ca3bc7ae1151
refs/heads/master
1,667,931,697,036
1,593,174,880,000
1,593,174,880,000
275,150,842
0
0
null
null
null
null
UTF-8
Lean
false
false
19,431
lean
import data.real.basic import data.set import tactic -- import exercices_espaces_metriques open push_neg namespace tactic.interactive open lean.parser tactic interactive open interactive (loc.ns) open interactive.types open tactic expr local postfix *:9001 := many -- sinon ne comprends pas ident* /- décompose en premier caractère, reste INUTILISE-/ def un_car : string → string × string | ⟨(x :: xs)⟩ := ( ⟨ [x] ⟩ , ⟨ xs ⟩ ) | _ := ("","") def deux_car : string → string | ⟨(x :: y :: xs)⟩ := ⟨ [x,y] ⟩ | _ := "" def trois_car : string → string | ⟨(x :: y :: z ::xs)⟩ := ⟨ [x,y,z] ⟩ | _ := "" /- décompose une chaine de caractères selon la première parenthèse ouvrante Le premier terme ne sert qu'à la récursivité INUTILISE-/ meta def debut_chaine : string × string → string × string | (s , t ) := do let d := un_car t, match d with | ("(",reste) := (s,t) | ( ⟨(x)⟩, reste) := (debut_chaine (s ++ d.1, reste )) -- | _ := ("ERREUR", "") end -- set_option trace.eqn_compiler.elim_match true -- ne fonctionne pas : le "Prop" est ignoré, ou bien tout est Prop ?? -- meta def is_prop : expr → bool -- | `(%%e : Prop) := tt -- | _ := ff -- détermine si l'expression est une propriété -- basé sur le fait (peut-être optimiste) que si on échoue à trouver le type, -- c'est qu'il y a des variables libres, -- et donc que c'est une propriété meta def is_prop : expr → tactic bool | e := do { expr_t ← infer_type e, -- expr_tt ← infer_type expr_t, if expr_t = `(Prop) then return tt else return ff } <|> return tt -- test if expr is semantically an implication or a function -- (as opposed to a "∀" expression ) meta def is_arrow' : expr → tactic bool | `(%%P → %%Q) := if has_var_idx Q 0 then return ff else return tt | _ := return ff meta def instanciate (e : expr) : tactic expr := match e with | (pi pp_name binder type body) := do a ← mk_local' pp_name binder type, return $ instantiate_var body a | (lam pp_name binder type body) := do a ← mk_local' pp_name binder type, return $ instantiate_var body a | _ := return e end open tactic example : true := by do e ← to_expr ```(∀ y : ℕ, ∀ x : ℕ, y = x), (es, tgt) ← mk_local_pis e, trace e, trace es, trace tgt /- Décompose la racine d'une expression (un seul pas) LOGICS : ET, OU, SSI, QUELQUESOIT, IMPLIQUE, FONCTION, NON, EXISTE, SETS: INTER, UNION, INCLUS, APPARTIENT, COMPLEMENTAIRE1,s IMAGE_ENSEMBLE, IMAGE_RECIPROQUE, EGALITE, ENSEMBLE1, APPLICATION NUMBERS: -/ private meta def analyse_expr_step (e : expr) : tactic (string × (list expr)) := do S ← (tactic.pp e), let e_joli := to_string S, match e with | (lam name binder type body) := return ("lambda[" ++ to_string name ++ "]", [type,body]) -- name → binder_info → expr → expr → expr ------------------------- LOGIQUE ------------------------- | `(%%p ∧ %%q) := return ("PROP_AND", [p,q]) | `(%%p ∨ %%q) := return ("PROP_OR", [p,q]) | `(%%p ↔ %%q) := return ("PROP_IFF", [p,q]) | `(¬ %%p) := return ("PROP_NOT", [p]) | `(%%p → false) := return ("PROP_NOT", [p]) | (pi name binder type body) := do bool ← (is_arrow' e), if bool then do bool2 ← tactic.is_prop e, if bool2 then return ("PROP_IMPLIES", [type,body]) else return ("FUNCTION", [type,body]) else do inst_body ← instanciate e, return ("QUANT_∀[" ++ to_string name ++ "]", [type, inst_body]) | `(Exists %%p) := do match p with -- améliorer : cas d'une prop, mais attention aux variables !! | (lam name binder type body) := -- la suite teste s'il s'agit de l'existence d'un objet ou d'une propriété -- d'abord, si `body` contient des variables libres, c'est une propriété -- if type.has_var then return ("EXISTE[PROP:" ++ to_string name ++ "]", [type,body]) -- si ce n'est pas le cas, on peut chercher son type, et voir si c'est Prop -- else do type_type ← infer_type type, -- if type_type = `(Prop) do inst_body ← instanciate p, bool ← is_prop p, if bool then return ("PROP_∃[" ++ to_string name ++ "]", [type,inst_body]) else return ("QUANT_∃[" ++ to_string name ++ "]", [type,inst_body]) | _ := return ("ERROR", []) end ------------------------- THEORIE DES ENSEMBLES ------------------------- | `(%%A ∩ %%B) := return ("SET_INTER", [A,B]) | `(%%A ∪ %%B) := return ("SET_UNION", [A,B]) | `(set.compl %%A) := return ("SET_COMPLEMENT", [A]) | `(%%A \ %%B) := return ("SET_SYM_DIFF", [A,B]) | `(%%A ⊆ %%B) := return ("PROP_INCLUDED", [A,B]) | `(%%a ∈ %%A) := return ("PROP_BELONGS", [a,A]) | `(@set.univ %%X) := return ("SET_UNIVERSE", [X]) | `(-%%A) := return ("MINUS", [A]) | `(set.Union %%A) := return ("SET_UNION+", [A]) | `(set.Inter %%A) := return ("SET_INTER+", [A]) | `(%%f '' %%A) := return ("SET_IMAGE", [f,A]) | `(%%f ⁻¹' %%A) := return ("SET_INVERSE", [f,A]) | `(∅) := return ("SET_EMPTY", []) | `(_root_.set %%X) := return ("SET", [X]) -- polymorphe | `(%%a = %%b) := return ("PROP_EQUAL", [a,b]) -- faudrait connaitre le type ? | `(%%a ≠ %%b) := return ("PROP_EQUAL_NOT", [a,b]) -- faudrait connaitre le type ? ----------- TOPOLOGY -------------- -- | `(B(%%x, %%r)) ---------------------------- NOMBRES particuliers (cf aussi plus bas) | `(0:ℝ) := return ("NUMBER[0]",[]) -- OK, mais peut-être faut-il garder l'info 0 : réel | `(0:ℕ) := return ("NUMBER[0]",[]) -- non testé | `(0:ℤ) := return ("NUMBER[0]",[]) -- non testé | `(1:ℝ) := return ("NUMBER[1]",[]) | `(1:ℕ) := return ("NUMBER[1]",[]) -- non testé | `(1:ℤ) := return ("NUMBER[1]",[]) -- non testé -- | `(0 < %%b) := return ("POSITIF", [b]) | `(%%a < %%b) := return ("PROP_<", [a,b]) | `(%%a ≤ %%b) := return ("PROP_≤", [a,b]) -- | `(%%a > 0) := return ("POSITIF", [a]) | `(%%a > %%b) := return ("PROP_>", [a,b]) | `(%%a ≥ %%b) := return ("PROP_≥", [a,b]) ------------------------------ Meta_applications | (app fonction argument) := -- do let Sfonction := to_string(fonction), -- pour les nombres, utiliser la pretty printer de Lean -- récupérer le type ? if is_numeral e then return ("NUMBER["++e_joli ++"]",[]) -- détecter les sous-ensembles -- else if to_string(fonction) = "set.{0}" -- then return("SET", [argument]) -- else return("META_APPLICATION[[pp:" ++ e_joli ++"]]",[fonction,argument]) else return("APPLICATION",[fonction,argument]) | `(ℝ) := return ("TYPE_NUMBER[ℝ]",[]) | `(ℕ) := return ("TYPE_NUMBER[ℕ]",[]) | (const name list_level) := return ("CONSTANT[name:"++ e_joli ++ "/" ++ to_string name ++"]", []) -- name → list level → expr | (var nat) := return ("VAR["++ to_string nat ++ "]", []) -- nat → expr | (sort level) := return ("TYPE", []) -- level → expr | (mvar name pretty_name type) := return ("METAVAR[" ++ to_string pretty_name ++ "]", []) -- name → name → expr → expr | (local_const name pretty_name bi type) := return ("LOCAL_CONSTANT[name:"++ to_string pretty_name++"/identifier:"++ to_string name ++ "]", []) -- name → name → binder_info → expr → expr | (elet name_var type_var expr body) := return ("LET["++ to_string name_var ++"]", [type_var,expr,body]) --name → expr → expr → expr → expr | (macro liste pas_compris) := return ("MACRO", []) -- macro_def → list expr → expr end -- A node will be a leaf of the analysis tree iff it belongs to the following list: -- leaves = ["NOMBRE", "CONSTANT", "VAR", "TYPE", "METAVAR", "LOCAL_CONSTANT", -- "LET", "MACRO", "ERREUR"] -- A leaf is followed by a separateur_virgule or a ")" -- A node which is not a leaf is followed by a "(" def separateur_virgule := "¿, " def separateur_egale := " ¿= " def open_paren := "¿(" def closed_paren := "¿)" /- Analyse récursivement une expression à l'aide de analyse_expr_step, renvoie le résultat sous forme de chaine bien parenthésée-/ private meta def analyse_rec : expr → tactic string | e := do ⟨string, liste_expr⟩ ← analyse_expr_step(e), -- bool ← is_prop e, -- let string := to_string bool ++ "." ++ string, match liste_expr with -- ATTENTION, cas de plus de trois arguiments non traité -- à remplacer par un list.map |[e1] := do string1 ← analyse_rec e1, return(string ++ open_paren ++ string1 ++ closed_paren) |[e1,e2] := do string1 ← analyse_rec e1, string2 ← analyse_rec e2, -- if string = "APPLICATION" -- then return (string1 ++ open_paren ++ string2 ++ closed_paren) else return (string ++ open_paren ++ string1 ++ separateur_virgule ++ string2 ++ closed_paren) |[e1,e2,e3] := do -- non utilisé string1 ← analyse_rec e1, string2 ← analyse_rec e2, string3 ← analyse_rec e3, return (string ++ open_paren ++ string1 ++ separateur_virgule ++ string2 ++ separateur_virgule ++ string3 ++ closed_paren) | _ := return(string) end private meta def analyse_expr : expr → tactic string | e := do expr_t ← infer_type e, bool ← is_prop expr_t, -- expr_tt ← infer_type expr_t, if bool then do -- S ← (tactic.pp expr_t), -- let S1 := to_string S, S ← (tactic.pp expr_t), let et_joli := to_string S, S1b ← analyse_rec e, S2 ← analyse_rec expr_t, let S3 := "PROPERTY[" ++ S1b ++ "/pp_type: " ++ et_joli ++ "]" ++ separateur_egale ++ S2, return(S3) else do -- let S1 := to_string e, S1b ← analyse_rec e, S2 ← analyse_rec expr_t, let S3 := "OBJECT[" ++ S1b ++ separateur_egale ++ S2, return(S3) /- Affiche la liste des objets du contexte, séparés par des retour chariots format : "OBJET" ou "PROPRIETE" : affichage Lean : structure -/ meta def analyse_contexte : tactic unit := do liste_expr ← local_context, trace "context:", liste_expr.mmap (λ h, analyse_expr h >>= trace), return () /- Affiche la liste des buts, même format que analyse_contexte (excepté qu'il n'y a que des PROPRIETES) -/ meta def analyse_buts : tactic unit := do liste_expr ← get_goals, trace "goals:", liste_expr.mmap (λ h, analyse_expr h >>= trace), return () --------------------------------------------------------- --------- NON UTILISES (debuggage) ---------------------------------- --------------------------------------------------------- /- Appelle l'analyse récursive sur le but ou sur une hypothèse. Non utilisé par la suite. -/ meta def analyse (names : parse ident*) : tactic unit := match names with | [] := do goal ← tactic.target, trace (analyse_rec goal) | [nom] := do expr ← get_local nom, expr_t ← infer_type expr, expr_tt ← infer_type expr_t, -- la suite différencie selon la sémantique, -- ie les objets (éléments, ensembles, fonctions) -- vs les propriétés if expr_tt = `(Prop) then trace (analyse_rec expr_t) else do S1 ← (analyse_rec expr), S2 ← (analyse_rec expr_t), --let S2 := to_string expr_t, let S3 := S1 ++ " : "++ S2, trace(S3) | _ := skip end /- Appelle l'analyse en 1 coup sur le but ou sur une hypothèse. Non utilisé par la suite. -/ meta def analyse1 (names : parse ident*) : tactic unit := match names with | [] := do goal ← tactic.target, trace (analyse_expr_step goal) | [nom] := do expr ← get_local nom, expr_t ← infer_type expr, trace (analyse_expr_step expr_t) | _ := skip end -- non utilisé private meta def analyse_expr2 : expr → tactic string | e := do expr_t ← infer_type e, expr_tt ← infer_type expr_t, if expr_tt = `(Prop) then do S ← (tactic.pp expr_t), let S1 := to_string S, S2 ← analyse_rec expr_t, let S3 := "PROPRIETE : " ++ S1 ++ " : " ++ S2, return(S3) else do let S0 := "OBJET : ", let S1 := to_string e, S2 ← analyse_rec expr_t, let S3 := S0 ++ S1 ++ " : "++ S2, return(S3) --------------------------------------------------------- ----------------- Essai de rendu LateX, non abouti ------ --------------------------------------------------------- /- transforme une expression lean en expression latex AMELIORER : tenir compte de la profondeur de l'arbre pour décider si on met des prenthèses-/ /- ET, OU, SSI, QUELQUESOIT, IMPLIQUE, FONCTION, NON1, EXISTE, INTER, UNION, INCLUS, APPARTIENT, COMPLEMENTAIRE1, IMAGE_ENSEMBLE, IMAGE_RECIPROQUE, EGALITE, ENSEMBLE1, APPLICATION-/ meta def latex_expr : expr → tactic string | e := do ⟨string, liste_expr⟩ ← analyse_expr_step e, if list.length liste_expr =2 then do let e1 := list.head liste_expr, let e2 := list.head (list.tail liste_expr), S1 ← latex_expr e1, S2 ← latex_expr e2, match string with | "ET" := return (S1 ++ " et " ++ S2) | "OU" := return (S1 ++ " ou " ++ S2) | "SSI" := return ("(" ++ S1 ++ "" ++") \\Leftrightarrow (" ++ S2 ++ ")") | "INCLUS" := return (S1 ++ "" ++" \\subset " ++ S2) | _ := return "ERREUR" end else if list.length liste_expr =1 then do let e1 := list.head liste_expr, S1 ← latex_expr e1, match string with | "NON" := return ("NON (" ++ S1 ++ ")") | "COMPLEMENTAIRE" := return (S1 ++ "^c") | _ := return "ERREUR" end else return (string) meta def latex_buts : tactic unit := do liste_expr ← get_goals, trace "Buts :", -- liste_buts ← tactic.get_goals, -- types ← list.mmap tactic.infer_type liste_buts, -- trace types, liste_expr.mmap (λ h, latex_expr h >>= trace), return () meta def latex_but : tactic unit := do expr ← target, trace "But :", -- liste_buts ← tactic.get_goals, -- types ← list.mmap tactic.infer_type liste_buts, -- trace types, trace (latex_expr expr), return () ---------------------------------------------- ------------- DEBUGGAGE ------------------- ------------------------------------------- /- debug -/ private meta def analyse_expr_step_brut (e : expr) : tactic (string × (list expr)) := match e with -- autres | (pi name binder type body ) := return ("pi (nom : " ++ to_string name ++ ")",[type,body]) | (app fonction argument) := return ("application", [fonction,argument]) | (const name list_level) := return ("constante :" ++ to_string name, []) -- name → list level → expr | (var nat) := return ("var_"++ to_string nat, []) -- nat → expr | (sort level) := return ("sort", []) -- level → expr | (mvar name pretty_name type) := return ("metavar", []) -- name → name → expr → expr | (local_const name pretty_name bi type) := return ("constante_locale :" ++ to_string pretty_name, []) -- name → name → binder_info → expr → expr | (lam name binder type body) := return ("lambda (nom : " ++ to_string name ++ ")", [type,body]) -- name → binder_info → expr → expr → expr | (elet name_var type_var expr body) := return ("let", []) --name → expr → expr → expr → expr | (macro liste pas_compris) := return ("macro", []) -- macro_def → list expr → expr end /- Debug -/ private meta def analyse_rec_brut : expr → tactic string | e := do ⟨string, liste_expr⟩ ← analyse_expr_step_brut e, match liste_expr with -- ATTENTION, cas de plus de trois arguiments non traité -- à remplacer par un list.map |[e1] := do string1 ← analyse_rec_brut e1, return(string ++ "(" ++ string1 ++ ")") |[e1,e2] := do string1 ← analyse_rec_brut e1, string2 ← analyse_rec_brut e2, if string = "APPLICATION" then do { type2 ← infer_type e2, let string_type2 := to_string type2, -- trace string_type2, if (string_type2 = "Type" ) ∨ (trois_car (to_string(e2)) = "_in" ) -- Type ou instance then return (string1) else return (string1 ++ "(" ++ string2 ++")") } <|> return (string1 ++ "(" ++ string2 ++")") else return (string ++ "(" ++ string1 ++ "," ++ string2 ++ ")") |[e1,e2,e3] := do -- non utilisé string1 ← analyse_rec_brut e1, string2 ← analyse_rec_brut e2, string3 ← analyse_rec_brut e3, return (string ++ "(" ++ string1 ++ "," ++ string2 ++ "," ++ string3 ++ ")") | _ := return(string) end /- Debug -/ meta def analyse_brut (names : parse ident*) : tactic unit := match names with | [] := do goal ← tactic.target, trace (analyse_rec_brut goal) | [nom] := do expr ← get_local nom, expr_t ← infer_type expr, expr_tt ← infer_type expr_t, -- la suite différencie selon la sémantique, -- ie les objets (éléments, ensembles, fonctions) -- vs les propriétés if expr_tt = `(Prop) then trace (analyse_rec_brut expr_t) else do S1 ← (analyse_rec_brut expr), S2 ← (analyse_rec_brut expr_t), --let S2 := to_string expr_t, let S3 := S1 ++ " : "++ S2, trace(S3) | _ := skip end -- débug private meta def analyse_expr_brut : expr → tactic string | e := do expr_t ← infer_type e, expr_tt ← infer_type expr_t, if expr_tt = `(Prop) then do S ← (tactic.pp expr_t), let S1 := to_string S, S2 ← analyse_rec_brut expr_t, let S3 := "PROPRIETE : " ++ S1 ++ " : " ++ S2, return(S3) else do let S0 := "OBJET : ", let S1 := to_string e, S2 ← analyse_rec_brut expr_t, let S3 := S0 ++ S1 ++ " : "++ S2, return(S3) /- Affiche la liste des objets du contexte, séparés par des retour chariots format : "OBJET" ou "PROPRIETE" : affichage Lean : structure -/ meta def analyse_contexte_brut : tactic unit := do liste_expr ← local_context, trace "Contexte :", liste_expr.mmap (λ h, analyse_expr_brut h >>= trace), return () /- Analyse brute de Lean (dans expr) -/ meta def analyse_raw (names : parse ident*) : tactic unit := match names with | [] := do goal ← tactic.target, trace $ to_raw_fmt goal | [nom] := do expr ← get_local nom, expr_t ← infer_type expr, trace $ to_raw_fmt expr_t | _ := skip end end tactic.interactive
6842264b6ea427a5985495824590ceeac70476d7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/monoidal/transport.lean
4943c0ed2deb57eb82dfb092954b21903a1e7b8e
[]
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
4,547
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.monoidal.natural_transformation import Mathlib.PostPort universes u₁ u₂ v₁ v₂ namespace Mathlib /-! # Transport a monoidal structure along an equivalence. When `C` and `D` are equivalent as categories, we can transport a monoidal structure on `C` along the equivalence, obtaining a monoidal structure on `D`. We don't yet prove anything about this transported structure! The next step would be to show that the original functor can be upgraded to a monoidal functor with respect to this new structure. -/ namespace category_theory.monoidal /-- Transport a monoidal structure along an equivalence of (plain) categories. -/ @[simp] theorem transport_tensor_unit {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] (e : C ≌ D) : 𝟙_ = functor.obj (equivalence.functor e) 𝟙_ := Eq.refl 𝟙_ /-- A type synonym for `D`, which will carry the transported monoidal structure. -/ def transported {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] (e : C ≌ D) := D protected instance transported.category_theory.monoidal_category {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] (e : C ≌ D) : monoidal_category (transported e) := transport e protected instance transported.inhabited {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] (e : C ≌ D) : Inhabited (transported e) := { default := 𝟙_ } /-- We can upgrade `e.functor` to a lax monoidal functor from `C` to `D` with the transported structure. -/ @[simp] theorem lax_to_transported_to_functor_map {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] (e : C ≌ D) {X : C} {Y : C} : ∀ (ᾰ : X ⟶ Y), functor.map (lax_monoidal_functor.to_functor (lax_to_transported e)) ᾰ = functor.map (equivalence.functor e) ᾰ := fun (ᾰ : X ⟶ Y) => Eq.refl (functor.map (lax_monoidal_functor.to_functor (lax_to_transported e)) ᾰ) /-- We can upgrade `e.functor` to a monoidal functor from `C` to `D` with the transported structure. -/ @[simp] theorem to_transported_ε_is_iso {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] (e : C ≌ D) : monoidal_functor.ε_is_iso (to_transported e) = id (is_iso.id (functor.obj (equivalence.functor e) 𝟙_)) := Eq.refl (monoidal_functor.ε_is_iso (to_transported e)) /-- We can upgrade `e.inverse` to a lax monoidal functor from `D` with the transported structure to `C`. -/ def lax_from_transported {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] (e : C ≌ D) : lax_monoidal_functor (transported e) C := lax_monoidal_functor.mk (functor.mk (functor.obj (equivalence.inverse e)) (functor.map (equivalence.inverse e))) (nat_trans.app (equivalence.unit e) 𝟙_) fun (X Y : transported e) => nat_trans.app (equivalence.unit e) (functor.obj (equivalence.inverse e) X ⊗ functor.obj (equivalence.inverse e) Y) /-- We can upgrade `e.inverse` to a monoidal functor from `D` with the transported structure to `C`. -/ def from_transported {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] (e : C ≌ D) : monoidal_functor (transported e) C := monoidal_functor.mk (lax_monoidal_functor.mk (lax_monoidal_functor.to_functor (lax_from_transported e)) (lax_monoidal_functor.ε (lax_from_transported e)) (lax_monoidal_functor.μ (lax_from_transported e))) /-- The unit isomorphism upgrades to a monoidal isomorphism. -/ def transported_monoidal_unit_iso {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] (e : C ≌ D) : lax_monoidal_functor.id C ≅ lax_to_transported e ⊗⋙ lax_from_transported e := monoidal_nat_iso.of_components (fun (X : C) => iso.app (equivalence.unit_iso e) X) sorry sorry sorry /-- The counit isomorphism upgrades to a monoidal isomorphism. -/ @[simp] theorem transported_monoidal_counit_iso_hom_to_nat_trans_app {C : Type u₁} [category C] [monoidal_category C] {D : Type u₂} [category D] (e : C ≌ D) (X : transported e) : nat_trans.app (monoidal_nat_trans.to_nat_trans (iso.hom (transported_monoidal_counit_iso e))) X = nat_trans.app (iso.hom (equivalence.counit_iso e)) X := Eq.refl (nat_trans.app (iso.hom (equivalence.counit_iso e)) X)
8afe8f86fe56ba1b6eb25736171a5d7f2c9acaa1
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/slow/path_groupoids.lean
14e7f4769d5b27ffea2a2ee3c46d8afafb0a32a8
[ "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
24,130
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Jeremy Avigad -- Ported from Coq HoTT notation `assume` binders `,` r:(scoped f, f) := r notation `take` binders `,` r:(scoped f, f) := r definition id {A : Type} (a : A) := a definition compose {A : Type} {B : Type} {C : Type} (g : B → C) (f : A → B) := λ x, g (f x) infixl `∘`:60 := compose -- Path -- ---- set_option unifier.max_steps 100000 inductive path {A : Type} (a : A) : A → Type := idpath : path a a definition idpath := @path.idpath infix `≈`:50 := path -- TODO: is this right? notation x `≈`:50 y `:>`:0 A:0 := @path A x y notation `idp`:max := idpath _ -- TODO: can we / should we use `1`? namespace path -- Concatenation and inverse -- ------------------------- definition concat {A : Type} {x y z : A} (p : x ≈ y) (q : y ≈ z) : x ≈ z := path.rec (λu, u) q p definition inverse {A : Type} {x y : A} (p : x ≈ y) : y ≈ x := path.rec (idpath x) p infixl `⬝`:75 := concat postfix `^`:100 := inverse -- In Coq, these are not needed, because concat and inv are kept transparent definition inv_1 {A : Type} (x : A) : (idpath x)^ ≈ idpath x := idp definition concat_11 {A : Type} (x : A) : idpath x ⬝ idpath x ≈ idpath x := idp -- The 1-dimensional groupoid structure -- ------------------------------------ -- The identity path is a right unit. definition concat_p1 {A : Type} {x y : A} (p : x ≈ y) : p ⬝ idp ≈ p := rec_on p idp -- The identity path is a right unit. definition concat_1p {A : Type} {x y : A} (p : x ≈ y) : idp ⬝ p ≈ p := rec_on p idp -- Concatenation is associative. definition concat_p_pp {A : Type} {x y z t : A} (p : x ≈ y) (q : y ≈ z) (r : z ≈ t) : p ⬝ (q ⬝ r) ≈ (p ⬝ q) ⬝ r := rec_on r (rec_on q idp) definition concat_pp_p {A : Type} {x y z t : A} (p : x ≈ y) (q : y ≈ z) (r : z ≈ t) : (p ⬝ q) ⬝ r ≈ p ⬝ (q ⬝ r) := rec_on r (rec_on q idp) -- The left inverse law. definition concat_pV {A : Type} {x y : A} (p : x ≈ y) : p ⬝ p^ ≈ idp := rec_on p idp -- The right inverse law. definition concat_Vp {A : Type} {x y : A} (p : x ≈ y) : p^ ⬝ p ≈ idp := rec_on p idp -- Several auxiliary theorems about canceling inverses across associativity. These are somewhat -- redundant, following from earlier theorems. definition concat_V_pp {A : Type} {x y z : A} (p : x ≈ y) (q : y ≈ z) : p^ ⬝ (p ⬝ q) ≈ q := rec_on q (rec_on p idp) definition concat_p_Vp {A : Type} {x y z : A} (p : x ≈ y) (q : x ≈ z) : p ⬝ (p^ ⬝ q) ≈ q := rec_on q (rec_on p idp) definition concat_pp_V {A : Type} {x y z : A} (p : x ≈ y) (q : y ≈ z) : (p ⬝ q) ⬝ q^ ≈ p := rec_on q (rec_on p idp) definition concat_pV_p {A : Type} {x y z : A} (p : x ≈ z) (q : y ≈ z) : (p ⬝ q^) ⬝ q ≈ p := rec_on q (take p, rec_on p idp) p -- Inverse distributes over concatenation definition inv_pp {A : Type} {x y z : A} (p : x ≈ y) (q : y ≈ z) : (p ⬝ q)^ ≈ q^ ⬝ p^ := rec_on q (rec_on p idp) definition inv_Vp {A : Type} {x y z : A} (p : y ≈ x) (q : y ≈ z) : (p^ ⬝ q)^ ≈ q^ ⬝ p := rec_on q (rec_on p idp) -- universe metavariables definition inv_pV {A : Type} {x y z : A} (p : x ≈ y) (q : z ≈ y) : (p ⬝ q^)^ ≈ q ⬝ p^ := rec_on p (λq, rec_on q idp) q definition inv_VV {A : Type} {x y z : A} (p : y ≈ x) (q : z ≈ y) : (p^ ⬝ q^)^ ≈ q ⬝ p := rec_on p (rec_on q idp) -- Inverse is an involution. definition inv_V {A : Type} {x y : A} (p : x ≈ y) : p^^ ≈ p := rec_on p idp -- Theorems for moving things around in equations -- ---------------------------------------------- definition moveR_Mp {A : Type} {x y z : A} (p : x ≈ z) (q : y ≈ z) (r : y ≈ x) : p ≈ (r^ ⬝ q) → (r ⬝ p) ≈ q := have gen : Πp q, p ≈ (r^ ⬝ q) → (r ⬝ p) ≈ q, from rec_on r (take p q, assume h : p ≈ idp^ ⬝ q, show idp ⬝ p ≈ q, from concat_1p _ ⬝ h ⬝ concat_1p _), gen p q definition moveR_pM {A : Type} {x y z : A} (p : x ≈ z) (q : y ≈ z) (r : y ≈ x) : r ≈ q ⬝ p^ → r ⬝ p ≈ q := rec_on p (take q r h, (concat_p1 _ ⬝ h ⬝ concat_p1 _)) q r definition moveR_Vp {A : Type} {x y z : A} (p : x ≈ z) (q : y ≈ z) (r : x ≈ y) : p ≈ r ⬝ q → r^ ⬝ p ≈ q := rec_on r (take p q h, concat_1p _ ⬝ h ⬝ concat_1p _) p q definition moveR_pV {A : Type} {x y z : A} (p : z ≈ x) (q : y ≈ z) (r : y ≈ x) : r ≈ q ⬝ p → r ⬝ p^ ≈ q := rec_on p (take q r h, concat_p1 _ ⬝ h ⬝ concat_p1 _) q r definition moveL_Mp {A : Type} {x y z : A} (p : x ≈ z) (q : y ≈ z) (r : y ≈ x) : r^ ⬝ q ≈ p → q ≈ r ⬝ p := rec_on r (take p q h, (concat_1p _)^ ⬝ h ⬝ (concat_1p _)^) p q definition moveL_pM {A : Type} {x y z : A} (p : x ≈ z) (q : y ≈ z) (r : y ≈ x) : q ⬝ p^ ≈ r → q ≈ r ⬝ p := rec_on p (take q r h, (concat_p1 _)^ ⬝ h ⬝ (concat_p1 _)^) q r definition moveL_Vp {A : Type} {x y z : A} (p : x ≈ z) (q : y ≈ z) (r : x ≈ y) : r ⬝ q ≈ p → q ≈ r^ ⬝ p := rec_on r (take p q h, (concat_1p _)^ ⬝ h ⬝ (concat_1p _)^) p q definition moveL_pV {A : Type} {x y z : A} (p : z ≈ x) (q : y ≈ z) (r : y ≈ x) : q ⬝ p ≈ r → q ≈ r ⬝ p^ := rec_on p (take q r h, (concat_p1 _)^ ⬝ h ⬝ (concat_p1 _)^) q r definition moveL_1M {A : Type} {x y : A} (p q : x ≈ y) : p ⬝ q^ ≈ idp → p ≈ q := rec_on q (take p h, (concat_p1 _)^ ⬝ h) p definition moveL_M1 {A : Type} {x y : A} (p q : x ≈ y) : q^ ⬝ p ≈ idp → p ≈ q := rec_on q (take p h, (concat_1p _)^ ⬝ h) p definition moveL_1V {A : Type} {x y : A} (p : x ≈ y) (q : y ≈ x) : p ⬝ q ≈ idp → p ≈ q^ := rec_on q (take p h, (concat_p1 _)^ ⬝ h) p definition moveL_V1 {A : Type} {x y : A} (p : x ≈ y) (q : y ≈ x) : q ⬝ p ≈ idp → p ≈ q^ := rec_on q (take p h, (concat_1p _)^ ⬝ h) p definition moveR_M1 {A : Type} {x y : A} (p q : x ≈ y) : idp ≈ p^ ⬝ q → p ≈ q := rec_on p (take q h, h ⬝ (concat_1p _)) q definition moveR_1M {A : Type} {x y : A} (p q : x ≈ y) : idp ≈ q ⬝ p^ → p ≈ q := rec_on p (take q h, h ⬝ (concat_p1 _)) q definition moveR_1V {A : Type} {x y : A} (p : x ≈ y) (q : y ≈ x) : idp ≈ q ⬝ p → p^ ≈ q := rec_on p (take q h, h ⬝ (concat_p1 _)) q definition moveR_V1 {A : Type} {x y : A} (p : x ≈ y) (q : y ≈ x) : idp ≈ p ⬝ q → p^ ≈ q := rec_on p (take q h, h ⬝ (concat_1p _)) q -- Transport -- --------- -- keep transparent, so transport _ idp p is definitionally equal to p definition transport {A : Type} (P : A → Type) {x y : A} (p : x ≈ y) (u : P x) : P y := path.rec_on p u definition transport_1 {A : Type} (P : A → Type) {x : A} (u : P x) : transport _ idp u ≈ u := idp -- TODO: is the binding strength on x reasonable? (It is modeled on the notation for subst -- in the standard library.) -- This idiom makes the operation right associative. notation p `#`:65 x:64 := transport _ p x definition ap ⦃A B : Type⦄ (f : A → B) {x y:A} (p : x ≈ y) : f x ≈ f y := path.rec_on p idp -- TODO: is this better than an alias? Note use of curly brackets definition ap01 := ap definition pointwise_paths {A : Type} {P : A → Type} (f g : Πx, P x) : Type := Πx : A, f x ≈ g x infix `∼`:50 := pointwise_paths definition apD10 {A} {B : A → Type} {f g : Πx, B x} (H : f ≈ g) : f ∼ g := λx, path.rec_on H idp definition ap10 {A B} {f g : A → B} (H : f ≈ g) : f ∼ g := apD10 H definition ap11 {A B} {f g : A → B} (H : f ≈ g) {x y : A} (p : x ≈ y) : f x ≈ g y := rec_on H (rec_on p idp) -- TODO: Note that the next line breaks the proof! -- opaque_hint (hiding rec_on) -- set_option pp.implicit true definition apD {A:Type} {B : A → Type} (f : Πa:A, B a) {x y : A} (p : x ≈ y) : p # (f x) ≈ f y := rec_on p idp -- More theorems for moving things around in equations -- --------------------------------------------------- definition moveR_transport_p {A : Type} (P : A → Type) {x y : A} (p : x ≈ y) (u : P x) (v : P y) : u ≈ p^ # v → p # u ≈ v := rec_on p (take u v, id) u v definition moveR_transport_V {A : Type} (P : A → Type) {x y : A} (p : y ≈ x) (u : P x) (v : P y) : u ≈ p # v → p^ # u ≈ v := rec_on p (take u v, id) u v definition moveL_transport_V {A : Type} (P : A → Type) {x y : A} (p : x ≈ y) (u : P x) (v : P y) : p # u ≈ v → u ≈ p^ # v := rec_on p (take u v, id) u v definition moveL_transport_p {A : Type} (P : A → Type) {x y : A} (p : y ≈ x) (u : P x) (v : P y) : p^ # u ≈ v → u ≈ p # v := rec_on p (take u v, id) u v -- Functoriality of functions -- -------------------------- -- Here we prove that functions behave like functors between groupoids, and that [ap] itself is -- functorial. -- Functions take identity paths to identity paths definition ap_1 {A B : Type} (x : A) (f : A → B) : (ap f idp) ≈ idp :> (f x ≈ f x) := idp definition apD_1 {A B} (x : A) (f : forall x : A, B x) : apD f idp ≈ idp :> (f x ≈ f x) := idp -- Functions commute with concatenation. definition ap_pp {A B : Type} (f : A → B) {x y z : A} (p : x ≈ y) (q : y ≈ z) : ap f (p ⬝ q) ≈ (ap f p) ⬝ (ap f q) := rec_on q (rec_on p idp) definition ap_p_pp {A B : Type} (f : A → B) {w x y z : A} (r : f w ≈ f x) (p : x ≈ y) (q : y ≈ z) : r ⬝ (ap f (p ⬝ q)) ≈ (r ⬝ ap f p) ⬝ (ap f q) := rec_on p (take r q, rec_on q (concat_p_pp r idp idp)) r q definition ap_pp_p {A B : Type} (f : A → B) {w x y z : A} (p : x ≈ y) (q : y ≈ z) (r : f z ≈ f w) : (ap f (p ⬝ q)) ⬝ r ≈ (ap f p) ⬝ (ap f q ⬝ r) := rec_on p (take q, rec_on q (take r, concat_pp_p _ _ _)) q r -- Functions commute with path inverses. definition inverse_ap {A B : Type} (f : A → B) {x y : A} (p : x ≈ y) : (ap f p)^ ≈ ap f (p^) := rec_on p idp definition ap_V {A B : Type} (f : A → B) {x y : A} (p : x ≈ y) : ap f (p^) ≈ (ap f p)^ := rec_on p idp -- TODO: rename id to idmap? definition ap_idmap {A : Type} {x y : A} (p : x ≈ y) : ap id p ≈ p := rec_on p idp definition ap_compose {A B C : Type} (f : A → B) (g : B → C) {x y : A} (p : x ≈ y) : ap (g ∘ f) p ≈ ap g (ap f p) := rec_on p idp -- Sometimes we don't have the actual function [compose]. definition ap_compose' {A B C : Type} (f : A → B) (g : B → C) {x y : A} (p : x ≈ y) : ap (λa, g (f a)) p ≈ ap g (ap f p) := rec_on p idp -- The action of constant maps. definition ap_const {A B : Type} {x y : A} (p : x ≈ y) (z : B) : ap (λu, z) p ≈ idp := rec_on p idp -- Naturality of [ap]. definition concat_Ap {A B : Type} {f g : A → B} (p : forall x, f x ≈ g x) {x y : A} (q : x ≈ y) : (ap f q) ⬝ (p y) ≈ (p x) ⬝ (ap g q) := rec_on q (concat_1p _ ⬝ (concat_p1 _)^) -- Naturality of [ap] at identity. definition concat_A1p {A : Type} {f : A → A} (p : forall x, f x ≈ x) {x y : A} (q : x ≈ y) : (ap f q) ⬝ (p y) ≈ (p x) ⬝ q := rec_on q (concat_1p _ ⬝ (concat_p1 _)^) definition concat_pA1 {A : Type} {f : A → A} (p : forall x, x ≈ f x) {x y : A} (q : x ≈ y) : (p x) ⬝ (ap f q) ≈ q ⬝ (p y) := rec_on q (concat_p1 _ ⬝ (concat_1p _)^) --TODO: note that the Coq proof for the preceding is -- -- match q as i in (_ ≈ y) return (p x ⬝ ap f i ≈ i ⬝ p y) with -- | idpath => concat_p1 _ ⬝ (concat_1p _)^ -- end. -- -- It is nice that we don't have to give the predicate. -- Naturality with other paths hanging around. definition concat_pA_pp {A B : Type} {f g : A → B} (p : forall x, f x ≈ g x) {x y : A} (q : x ≈ y) {w z : B} (r : w ≈ f x) (s : g y ≈ z) : (r ⬝ ap f q) ⬝ (p y ⬝ s) ≈ (r ⬝ p x) ⬝ (ap g q ⬝ s) := rec_on q (take s, rec_on s (take r, idp)) s r -- Action of [apD10] and [ap10] on paths -- ------------------------------------- -- Application of paths between functions preserves the groupoid structure definition apD10_1 {A} {B : A → Type} (f : Πx, B x) (x : A) : apD10 (idpath f) x ≈ idp := idp definition apD10_pp {A} {B : A → Type} {f f' f'' : Πx, B x} (h : f ≈ f') (h' : f' ≈ f'') (x : A) : apD10 (h ⬝ h') x ≈ apD10 h x ⬝ apD10 h' x := rec_on h (take h', rec_on h' idp) h' definition apD10_V {A : Type} {B : A → Type} {f g : Πx : A, B x} (h : f ≈ g) (x : A) : apD10 (h^) x ≈ (apD10 h x)^ := rec_on h idp definition ap10_1 {A B} {f : A → B} (x : A) : ap10 (idpath f) x ≈ idp := idp definition ap10_pp {A B} {f f' f'' : A → B} (h : f ≈ f') (h' : f' ≈ f'') (x : A) : ap10 (h ⬝ h') x ≈ ap10 h x ⬝ ap10 h' x := apD10_pp h h' x definition ap10_V {A B} {f g : A→B} (h : f ≈ g) (x:A) : ap10 (h^) x ≈ (ap10 h x)^ := apD10_V h x -- [ap10] also behaves nicely on paths produced by [ap] definition ap_ap10 {A B C} (f g : A → B) (h : B → C) (p : f ≈ g) (a : A) : ap h (ap10 p a) ≈ ap10 (ap (λ f', h ∘ f') p) a:= rec_on p idp -- Transport and the groupoid structure of paths -- --------------------------------------------- -- TODO: move from above? -- definition transport_1 {A : Type} (P : A → Type) {x : A} (u : P x) -- : idp # u ≈ u := idp definition transport_pp {A : Type} (P : A → Type) {x y z : A} (p : x ≈ y) (q : y ≈ z) (u : P x) : p ⬝ q # u ≈ q # p # u := rec_on q (rec_on p idp) definition transport_pV {A : Type} (P : A → Type) {x y : A} (p : x ≈ y) (z : P y) : p # p^ # z ≈ z := (transport_pp P (p^) p z)^ ⬝ ap (λr, transport P r z) (concat_Vp p) definition transport_Vp {A : Type} (P : A → Type) {x y : A} (p : x ≈ y) (z : P x) : p^ # p # z ≈ z := (transport_pp P p (p^) z)^ ⬝ ap (λr, transport P r z) (concat_pV p) ----------------------------------------------- -- *** Examples of difficult induction problems ----------------------------------------------- theorem double_induction {A : Type} {x y z : A} (p : x ≈ y) (q : y ≈ z) {C : Π(x y z : A), Π(p : x ≈ y), Π(q : y ≈ z), Type} (H : C x x x (idpath x) (idpath x)) : C x y z p q := rec_on p (take z q, rec_on q H) z q theorem double_induction2 {A : Type} {x y z : A} (p : x ≈ y) (q : z ≈ y) {C : Π(x y z : A), Π(p : x ≈ y), Π(q : z ≈ y), Type} (H : C z z z (idpath z) (idpath z)) : C x y z p q := rec_on p (take y q, rec_on q H) y q theorem double_induction2' {A : Type} {x y z : A} (p : x ≈ y) (q : z ≈ y) {C : Π(x y z : A), Π(p : x ≈ y), Π(q : z ≈ y), Type} (H : C z z z (idpath z) (idpath z)) : C x y z p q := rec_on p (take y q, rec_on q H) y q theorem triple_induction {A : Type} {x y z w : A} (p : x ≈ y) (q : y ≈ z) (r : z ≈ w) {C : Π(x y z w : A), Π(p : x ≈ y), Π(q : y ≈ z), Π(r: z ≈ w), Type} (H : C x x x x (idpath x) (idpath x) (idpath x)) : C x y z w p q r := rec_on p (take z q, rec_on q (take w r, rec_on r H)) z q w r -- try this again definition concat_pV_p_new {A : Type} {x y z : A} (p : x ≈ z) (q : y ≈ z) : (p ⬝ q^) ⬝ q ≈ p := double_induction2 p q idp definition transport_p_pp {A : Type} (P : A → Type) {x y z w : A} (p : x ≈ y) (q : y ≈ z) (r : z ≈ w) (u : P x) : ap (λe, e # u) (concat_p_pp p q r) ⬝ (transport_pp P (p ⬝ q) r u) ⬝ ap (transport P r) (transport_pp P p q u) ≈ (transport_pp P p (q ⬝ r) u) ⬝ (transport_pp P q r (p # u)) :> ((p ⬝ (q ⬝ r)) # u ≈ r # q # p # u) := triple_induction p q r (take u, idp) u -- Here is another coherence lemma for transport. definition transport_pVp {A} (P : A → Type) {x y : A} (p : x ≈ y) (z : P x) : transport_pV P p (transport P p z) ≈ ap (transport P p) (transport_Vp P p z) := rec_on p idp -- Dependent transport in a doubly dependent type. definition transportD {A : Type} (B : A → Type) (C : Π a : A, B a → Type) {x1 x2 : A} (p : x1 ≈ x2) (y : B x1) (z : C x1 y) : C x2 (p # y) := rec_on p z -- Transporting along higher-dimensional paths definition transport2 {A : Type} (P : A → Type) {x y : A} {p q : x ≈ y} (r : p ≈ q) (z : P x) : p # z ≈ q # z := ap (λp', p' # z) r -- An alternative definition. definition transport2_is_ap10 {A : Type} (Q : A → Type) {x y : A} {p q : x ≈ y} (r : p ≈ q) (z : Q x) : transport2 Q r z ≈ ap10 (ap (transport Q) r) z := rec_on r idp definition transport2_p2p {A : Type} (P : A → Type) {x y : A} {p1 p2 p3 : x ≈ y} (r1 : p1 ≈ p2) (r2 : p2 ≈ p3) (z : P x) : transport2 P (r1 ⬝ r2) z ≈ transport2 P r1 z ⬝ transport2 P r2 z := rec_on r1 (rec_on r2 idp) -- TODO: another interesting case definition transport2_V {A : Type} (Q : A → Type) {x y : A} {p q : x ≈ y} (r : p ≈ q) (z : Q x) : transport2 Q (r^) z ≈ ((transport2 Q r z)^) := -- rec_on r idp -- doesn't work rec_on r (idpath (inverse (transport2 Q (idpath p) z))) definition concat_AT {A : Type} (P : A → Type) {x y : A} {p q : x ≈ y} {z w : P x} (r : p ≈ q) (s : z ≈ w) : ap (transport P p) s ⬝ transport2 P r w ≈ transport2 P r z ⬝ ap (transport P q) s := rec_on r (concat_p1 _ ⬝ (concat_1p _)^) -- TODO (from Coq library): What should this be called? definition ap_transport {A} {P Q : A → Type} {x y : A} (p : x ≈ y) (f : Πx, P x → Q x) (z : P x) : f y (p # z) ≈ (p # (f x z)) := rec_on p idp -- Transporting in particular fibrations -- ------------------------------------- /- From the Coq HoTT library: One frequently needs lemmas showing that transport in a certain dependent type is equal to some more explicitly defined operation, defined according to the structure of that dependent type. For most dependent types, we prove these lemmas in the appropriate file in the types/ subdirectory. Here we consider only the most basic cases. -/ -- Transporting in a constant fibration. definition transport_const {A B : Type} {x1 x2 : A} (p : x1 ≈ x2) (y : B) : transport (λx, B) p y ≈ y := rec_on p idp definition transport2_const {A B : Type} {x1 x2 : A} {p q : x1 ≈ x2} (r : p ≈ q) (y : B) : transport_const p y ≈ transport2 (λu, B) r y ⬝ transport_const q y := rec_on r (concat_1p _)^ -- Transporting in a pulled back fibration. definition transport_compose {A B} {x y : A} (P : B → Type) (f : A → B) (p : x ≈ y) (z : P (f x)) : transport (λx, P (f x)) p z ≈ transport P (ap f p) z := rec_on p idp definition transport_precompose {A B C} (f : A → B) (g g' : B → C) (p : g ≈ g') : transport (λh : B → C, g ∘ f ≈ h ∘ f) p idp ≈ ap (λh, h ∘ f) p := rec_on p idp definition apD10_ap_precompose {A B C} (f : A → B) (g g' : B → C) (p : g ≈ g') (a : A) : apD10 (ap (λh : B → C, h ∘ f) p) a ≈ apD10 p (f a) := rec_on p idp definition apD10_ap_postcompose {A B C} (f : B → C) (g g' : A → B) (p : g ≈ g') (a : A) : apD10 (ap (λh : A → B, f ∘ h) p) a ≈ ap f (apD10 p a) := rec_on p idp -- TODO: another example where a term has to be given explicitly -- A special case of [transport_compose] which seems to come up a lot. definition transport_idmap_ap A (P : A → Type) x y (p : x ≈ y) (u : P x) : transport P p u ≈ transport (λz, z) (ap P p) u := rec_on p (idpath (transport (λ (z : Type), z) (ap P (idpath x)) u)) -- The behavior of [ap] and [apD] -- ------------------------------ -- In a constant fibration, [apD] reduces to [ap], modulo [transport_const]. definition apD_const {A B} {x y : A} (f : A → B) (p: x ≈ y) : apD f p ≈ transport_const p (f x) ⬝ ap f p := rec_on p idp -- The 2-dimensional groupoid structure -- ------------------------------------ -- Horizontal composition of 2-dimensional paths. definition concat2 {A} {x y z : A} {p p' : x ≈ y} {q q' : y ≈ z} (h : p ≈ p') (h' : q ≈ q') : p ⬝ q ≈ p' ⬝ q' := rec_on h (rec_on h' idp) infixl `⬝⬝`:75 := concat2 -- 2-dimensional path inversion definition inverse2 {A : Type} {x y : A} {p q : x ≈ y} (h : p ≈ q) : p^ ≈ q^ := rec_on h idp -- Whiskering -- ---------- definition whiskerL {A : Type} {x y z : A} (p : x ≈ y) {q r : y ≈ z} (h : q ≈ r) : p ⬝ q ≈ p ⬝ r := idp ⬝⬝ h definition whiskerR {A : Type} {x y z : A} {p q : x ≈ y} (h : p ≈ q) (r : y ≈ z) : p ⬝ r ≈ q ⬝ r := h ⬝⬝ idp -- Unwhiskering, a.k.a. cancelling -- ------------------------------- definition cancelL {A} {x y z : A} (p : x ≈ y) (q r : y ≈ z) : (p ⬝ q ≈ p ⬝ r) → (q ≈ r) := rec_on p (take r, rec_on r (take q a, (concat_1p q)^ ⬝ a)) r q definition cancelR {A} {x y z : A} (p q : x ≈ y) (r : y ≈ z) : (p ⬝ r ≈ q ⬝ r) → (p ≈ q) := rec_on r (take p, rec_on p (take q a, a ⬝ concat_p1 q)) p q -- Whiskering and identity paths. definition whiskerR_p1 {A : Type} {x y : A} {p q : x ≈ y} (h : p ≈ q) : (concat_p1 p)^ ⬝ whiskerR h idp ⬝ concat_p1 q ≈ h := rec_on h (rec_on p idp) definition whiskerR_1p {A : Type} {x y z : A} (p : x ≈ y) (q : y ≈ z) : whiskerR idp q ≈ idp :> (p ⬝ q ≈ p ⬝ q) := rec_on q idp definition whiskerL_p1 {A : Type} {x y z : A} (p : x ≈ y) (q : y ≈ z) : whiskerL p idp ≈ idp :> (p ⬝ q ≈ p ⬝ q) := rec_on q idp definition whiskerL_1p {A : Type} {x y : A} {p q : x ≈ y} (h : p ≈ q) : (concat_1p p) ^ ⬝ whiskerL idp h ⬝ concat_1p q ≈ h := rec_on h (rec_on p idp) definition concat2_p1 {A : Type} {x y : A} {p q : x ≈ y} (h : p ≈ q) : h ⬝⬝ idp ≈ whiskerR h idp :> (p ⬝ idp ≈ q ⬝ idp) := rec_on h idp definition concat2_1p {A : Type} {x y : A} {p q : x ≈ y} (h : p ≈ q) : idp ⬝⬝ h ≈ whiskerL idp h :> (idp ⬝ p ≈ idp ⬝ q) := rec_on h idp -- TODO: note, 4 inductions -- The interchange law for concatenation. definition concat_concat2 {A : Type} {x y z : A} {p p' p'' : x ≈ y} {q q' q'' : y ≈ z} (a : p ≈ p') (b : p' ≈ p'') (c : q ≈ q') (d : q' ≈ q'') : (a ⬝⬝ c) ⬝ (b ⬝⬝ d) ≈ (a ⬝ b) ⬝⬝ (c ⬝ d) := rec_on d (rec_on c (rec_on b (rec_on a idp))) definition concat_whisker {A} {x y z : A} (p p' : x ≈ y) (q q' : y ≈ z) (a : p ≈ p') (b : q ≈ q') : (whiskerR a q) ⬝ (whiskerL p' b) ≈ (whiskerL p b) ⬝ (whiskerR a q') := rec_on b (rec_on a (concat_1p _)^) -- Structure corresponding to the coherence equations of a bicategory. -- The "pentagonator": the 3-cell witnessing the associativity pentagon. definition pentagon {A : Type} {v w x y z : A} (p : v ≈ w) (q : w ≈ x) (r : x ≈ y) (s : y ≈ z) : whiskerL p (concat_p_pp q r s) ⬝ concat_p_pp p (q ⬝ r) s ⬝ whiskerR (concat_p_pp p q r) s ≈ concat_p_pp p q (r ⬝ s) ⬝ concat_p_pp (p ⬝ q) r s := rec_on p (take q, rec_on q (take r, rec_on r (take s, rec_on s idp))) q r s -- The 3-cell witnessing the left unit triangle. definition triangulator {A : Type} {x y z : A} (p : x ≈ y) (q : y ≈ z) : concat_p_pp p idp q ⬝ whiskerR (concat_p1 p) q ≈ whiskerL p (concat_1p q) := rec_on p (take q, rec_on q idp) q definition eckmann_hilton {A : Type} {x:A} (p q : idp ≈ idp :> (x ≈ x)) : p ⬝ q ≈ q ⬝ p := (whiskerR_p1 p ⬝⬝ whiskerL_1p q)^ ⬝ (concat_p1 _ ⬝⬝ concat_p1 _) ⬝ (concat_1p _ ⬝⬝ concat_1p _) ⬝ (concat_whisker _ _ _ _ p q) ⬝ (concat_1p _ ⬝⬝ concat_1p _)^ ⬝ (concat_p1 _ ⬝⬝ concat_p1 _)^ ⬝ (whiskerL_1p q ⬝⬝ whiskerR_p1 p) -- The action of functions on 2-dimensional paths definition ap02 {A B : Type} (f:A → B) {x y : A} {p q : x ≈ y} (r : p ≈ q) : ap f p ≈ ap f q := rec_on r idp definition ap02_pp {A B} (f : A → B) {x y : A} {p p' p'' : x ≈ y} (r : p ≈ p') (r' : p' ≈ p'') : ap02 f (r ⬝ r') ≈ ap02 f r ⬝ ap02 f r' := rec_on r (rec_on r' idp) definition ap02_p2p {A B} (f : A→B) {x y z : A} {p p' : x ≈ y} {q q' :y ≈ z} (r : p ≈ p') (s : q ≈ q') : ap02 f (r ⬝⬝ s) ≈ ap_pp f p q ⬝ (ap02 f r ⬝⬝ ap02 f s) ⬝ (ap_pp f p' q')^ := rec_on r (rec_on s (rec_on q (rec_on p idp))) definition apD02 {A : Type} {B : A → Type} {x y : A} {p q : x ≈ y} (f : Π x, B x) (r : p ≈ q) : apD f p ≈ transport2 B r (f x) ⬝ apD f q := rec_on r (concat_1p _)^ end path
48b3219a7bb41b804d7d35f6217de0cbc929bc41
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/bicategory/free.lean
a47147dbff24885a1f9194513802c8fbec35c051
[ "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,385
lean
/- Copyright (c) 2022 Yuma Mizuno. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yuma Mizuno -/ import category_theory.bicategory.functor /-! # Free bicategories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the free bicategory over a quiver. In this bicategory, the 1-morphisms are freely generated by the arrows in the quiver, and the 2-morphisms are freely generated by the formal identities, the formal unitors, and the formal associators modulo the relation derived from the axioms of a bicategory. ## Main definitions * `free_bicategory B`: the free bicategory over a quiver `B`. * `free_bicategory.lift F`: the pseudofunctor from `free_bicategory B` to `C` associated with a prefunctor `F` from `B` to `C`. -/ universes w w₁ w₂ v v₁ v₂ u u₁ u₂ namespace category_theory open category bicategory open_locale bicategory /-- Free bicategory over a quiver. Its objects are the same as those in the underlying quiver. -/ def free_bicategory (B : Type u) := B instance (B : Type u) : Π [inhabited B], inhabited (free_bicategory B) := id namespace free_bicategory section variables {B : Type u} [quiver.{v+1} B] /-- 1-morphisms in the free bicategory. -/ inductive hom : B → B → Type (max u v) | of {a b : B} (f : a ⟶ b) : hom a b | id (a : B) : hom a a | comp {a b c : B} (f : hom a b) (g : hom b c) : hom a c instance (a b : B) [inhabited (a ⟶ b)] : inhabited (hom a b) := ⟨hom.of default⟩ /-- Representatives of 2-morphisms in the free bicategory. -/ @[nolint has_nonempty_instance] inductive hom₂ : Π {a b : B}, hom a b → hom a b → Type (max u v) | id {a b} (f : hom a b) : hom₂ f f | vcomp {a b} {f g h : hom a b} (η : hom₂ f g) (θ : hom₂ g h) : hom₂ f h | whisker_left {a b c} (f : hom a b) {g h : hom b c} (η : hom₂ g h) : hom₂ (f.comp g) (f.comp h) -- `η` cannot be earlier than `h` since it is a recursive argument. | whisker_right {a b c} {f g : hom a b} (h : hom b c) (η : hom₂ f g) : hom₂ (f.comp h) (g.comp h) | associator {a b c d} (f : hom a b) (g : hom b c) (h : hom c d) : hom₂ ((f.comp g).comp h) (f.comp (g.comp h)) | associator_inv {a b c d} (f : hom a b) (g : hom b c) (h : hom c d) : hom₂ (f.comp (g.comp h)) ((f.comp g).comp h) | right_unitor {a b} (f : hom a b) : hom₂ (f.comp (hom.id b)) f | right_unitor_inv {a b} (f : hom a b) : hom₂ f (f.comp (hom.id b)) | left_unitor {a b} (f : hom a b) : hom₂ ((hom.id a).comp f) f | left_unitor_inv {a b} (f : hom a b) : hom₂ f ((hom.id a).comp f) section variables {B} -- The following notations are only used in the definition of `rel` to simplify the notation. local infixr (name := vcomp) ` ≫ ` := hom₂.vcomp local notation (name := id) `𝟙` := hom₂.id local notation (name := whisker_left) f ` ◁ ` η := hom₂.whisker_left f η local notation (name := whisker_right) η ` ▷ ` h := hom₂.whisker_right h η local notation (name := associator) `α_` := hom₂.associator local notation (name := left_unitor) `λ_` := hom₂.left_unitor local notation (name := right_unitor) `ρ_` := hom₂.right_unitor local notation (name := associator_inv) `α⁻¹_` := hom₂.associator_inv local notation (name := left_unitor_inv) `λ⁻¹_` := hom₂.left_unitor_inv local notation (name := right_unitor_inv) `ρ⁻¹_` := hom₂.right_unitor_inv /-- Relations between 2-morphisms in the free bicategory. -/ inductive rel : Π {a b : B} {f g : hom a b}, hom₂ f g → hom₂ f g → Prop | vcomp_right {a b} {f g h : hom a b} (η : hom₂ f g) (θ₁ θ₂ : hom₂ g h) : rel θ₁ θ₂ → rel (η ≫ θ₁) (η ≫ θ₂) | vcomp_left {a b} {f g h : hom a b} (η₁ η₂ : hom₂ f g) (θ : hom₂ g h) : rel η₁ η₂ → rel (η₁ ≫ θ) (η₂ ≫ θ) | id_comp {a b} {f g : hom a b} (η : hom₂ f g) : rel (𝟙 f ≫ η) η | comp_id {a b} {f g : hom a b} (η : hom₂ f g) : rel (η ≫ 𝟙 g) η | assoc {a b} {f g h i : hom a b} (η : hom₂ f g) (θ : hom₂ g h) (ι : hom₂ h i) : rel ((η ≫ θ) ≫ ι) (η ≫ (θ ≫ ι)) | whisker_left {a b c} (f : hom a b) (g h : hom b c) (η η' : hom₂ g h) : rel η η' → rel (f ◁ η) (f ◁ η') | whisker_left_id {a b c} (f : hom a b) (g : hom b c) : rel (f ◁ 𝟙 g) (𝟙 (f.comp g)) | whisker_left_comp {a b c} (f : hom a b) {g h i : hom b c} (η : hom₂ g h) (θ : hom₂ h i) : rel (f ◁ (η ≫ θ)) (f ◁ η ≫ f ◁ θ) | id_whisker_left {a b} {f g : hom a b} (η : hom₂ f g) : rel (hom.id a ◁ η) (λ_ f ≫ η ≫ λ⁻¹_ g) | comp_whisker_left {a b c d} (f : hom a b) (g : hom b c) {h h' : hom c d} (η : hom₂ h h') : rel ((f.comp g) ◁ η) (α_ f g h ≫ f ◁ g ◁ η ≫ α⁻¹_ f g h') | whisker_right {a b c} (f g : hom a b) (h : hom b c) (η η' : hom₂ f g) : rel η η' → rel (η ▷ h) (η' ▷ h) | id_whisker_right {a b c} (f : hom a b) (g : hom b c) : rel (𝟙 f ▷ g) (𝟙 (f.comp g)) | comp_whisker_right {a b c} {f g h : hom a b} (i : hom b c) (η : hom₂ f g) (θ : hom₂ g h) : rel ((η ≫ θ) ▷ i) (η ▷ i ≫ θ ▷ i) | whisker_right_id {a b} {f g : hom a b} (η : hom₂ f g) : rel (η ▷ hom.id b) (ρ_ f ≫ η ≫ ρ⁻¹_ g) | whisker_right_comp {a b c d} {f f' : hom a b} (g : hom b c) (h : hom c d) (η : hom₂ f f') : rel (η ▷ (g.comp h)) (α⁻¹_ f g h ≫ η ▷ g ▷ h ≫ α_ f' g h) | whisker_assoc {a b c d} (f : hom a b) {g g' : hom b c} (η : hom₂ g g') (h : hom c d) : rel ((f ◁ η) ▷ h) (α_ f g h ≫ f ◁ (η ▷ h)≫ α⁻¹_ f g' h) | whisker_exchange {a b c} {f g : hom a b} {h i : hom b c} (η : hom₂ f g) (θ : hom₂ h i) : rel (f ◁ θ ≫ η ▷ i) (η ▷ h ≫ g ◁ θ) | associator_hom_inv {a b c d} (f : hom a b) (g : hom b c) (h : hom c d) : rel (α_ f g h ≫ α⁻¹_ f g h) (𝟙 ((f.comp g).comp h)) | associator_inv_hom {a b c d} (f : hom a b) (g : hom b c) (h : hom c d) : rel (α⁻¹_ f g h ≫ α_ f g h) (𝟙 (f.comp (g.comp h))) | left_unitor_hom_inv {a b} (f : hom a b) : rel (λ_ f ≫ λ⁻¹_ f) (𝟙 ((hom.id a).comp f)) | left_unitor_inv_hom {a b} (f : hom a b) : rel (λ⁻¹_ f ≫ λ_ f) (𝟙 f) | right_unitor_hom_inv {a b} (f : hom a b) : rel (ρ_ f ≫ ρ⁻¹_ f) (𝟙 (f.comp (hom.id b))) | right_unitor_inv_hom {a b} (f : hom a b) : rel (ρ⁻¹_ f ≫ ρ_ f) (𝟙 f) | pentagon {a b c d e} (f : hom a b) (g : hom b c) (h : hom c d) (i : hom d e) : rel (α_ f g h ▷ i ≫ α_ f (g.comp h) i ≫ f ◁ α_ g h i) (α_ (f.comp g) h i ≫ α_ f g (h.comp i)) | triangle {a b c} (f : hom a b) (g : hom b c) : rel (α_ f (hom.id b) g ≫ f ◁ λ_ g) (ρ_ f ▷ g) end variables {B} instance hom_category (a b : B) : category (hom a b) := { hom := λ f g, quot (@rel _ _ _ _ f g), id := λ f, quot.mk rel (hom₂.id f), comp := λ f g h, quot.map₂ hom₂.vcomp rel.vcomp_right rel.vcomp_left, id_comp' := by { rintros f g ⟨η⟩, exact quot.sound (rel.id_comp η) }, comp_id' := by { rintros f g ⟨η⟩, exact quot.sound (rel.comp_id η) }, assoc' := by { rintros f g h i ⟨η⟩ ⟨θ⟩ ⟨ι⟩, exact quot.sound (rel.assoc η θ ι) } } /-- Bicategory structure on the free bicategory. -/ instance bicategory : bicategory (free_bicategory B) := { hom := λ a b : B, hom a b, id := hom.id, comp := λ a b c, hom.comp, hom_category := free_bicategory.hom_category, whisker_left := λ a b c f g h η, quot.map (hom₂.whisker_left f) (rel.whisker_left f g h) η, whisker_left_id' := λ a b c f g, quot.sound (rel.whisker_left_id f g), whisker_left_comp' := by { rintros a b c f g h i ⟨η⟩ ⟨θ⟩, exact quot.sound (rel.whisker_left_comp f η θ) }, id_whisker_left' := by { rintros a b f g ⟨η⟩, exact quot.sound (rel.id_whisker_left η) }, comp_whisker_left' := by { rintros a b c d f g h h' ⟨η⟩, exact quot.sound (rel.comp_whisker_left f g η) }, whisker_right := λ a b c f g η h, quot.map (hom₂.whisker_right h) (rel.whisker_right f g h) η, id_whisker_right' := λ a b c f g, quot.sound (rel.id_whisker_right f g), comp_whisker_right' := by { rintros a b c f g h ⟨η⟩ ⟨θ⟩ i, exact quot.sound (rel.comp_whisker_right i η θ) }, whisker_right_id' := by { rintros a b f g ⟨η⟩, exact quot.sound (rel.whisker_right_id η) }, whisker_right_comp' := by { rintros a b c d f f' ⟨η⟩ g h, exact quot.sound (rel.whisker_right_comp g h η) }, whisker_assoc' := by { rintros a b c d f g g' ⟨η⟩ h, exact quot.sound (rel.whisker_assoc f η h) }, whisker_exchange' := by { rintros a b c f g h i ⟨η⟩ ⟨θ⟩, exact quot.sound (rel.whisker_exchange η θ) }, associator := λ a b c d f g h, { hom := quot.mk rel (hom₂.associator f g h), inv := quot.mk rel (hom₂.associator_inv f g h), hom_inv_id' := quot.sound (rel.associator_hom_inv f g h), inv_hom_id' := quot.sound (rel.associator_inv_hom f g h) }, left_unitor := λ a b f, { hom := quot.mk rel (hom₂.left_unitor f), inv := quot.mk rel (hom₂.left_unitor_inv f), hom_inv_id' := quot.sound (rel.left_unitor_hom_inv f), inv_hom_id' := quot.sound (rel.left_unitor_inv_hom f) }, right_unitor := λ a b f, { hom := quot.mk rel (hom₂.right_unitor f), inv := quot.mk rel (hom₂.right_unitor_inv f), hom_inv_id' := quot.sound (rel.right_unitor_hom_inv f), inv_hom_id' := quot.sound (rel.right_unitor_inv_hom f) }, pentagon' := λ a b c d e f g h i, quot.sound (rel.pentagon f g h i), triangle' := λ a b c f g, quot.sound (rel.triangle f g) } variables {a b c d : free_bicategory B} @[simp] lemma mk_vcomp {f g h : a ⟶ b} (η : hom₂ f g) (θ : hom₂ g h) : quot.mk rel (η.vcomp θ) = (quot.mk rel η ≫ quot.mk rel θ : f ⟶ h) := rfl @[simp] lemma mk_whisker_left (f : a ⟶ b) {g h : b ⟶ c} (η : hom₂ g h) : quot.mk rel (hom₂.whisker_left f η) = (f ◁ quot.mk rel η : f ≫ g ⟶ f ≫ h) := rfl @[simp] lemma mk_whisker_right {f g : a ⟶ b} (η : hom₂ f g) (h : b ⟶ c) : quot.mk rel (hom₂.whisker_right h η) = (quot.mk rel η ▷ h : f ≫ h ⟶ g ≫ h) := rfl variables (f : a ⟶ b) (g : b ⟶ c) (h : c ⟶ d) lemma id_def : hom.id a = 𝟙 a := rfl lemma comp_def : hom.comp f g = f ≫ g := rfl @[simp] lemma mk_id : quot.mk _ (hom₂.id f) = 𝟙 f := rfl @[simp] lemma mk_associator_hom : quot.mk _ (hom₂.associator f g h) = (α_ f g h).hom := rfl @[simp] lemma mk_associator_inv : quot.mk _ (hom₂.associator_inv f g h) = (α_ f g h).inv := rfl @[simp] lemma mk_left_unitor_hom : quot.mk _ (hom₂.left_unitor f) = (λ_ f).hom := rfl @[simp] lemma mk_left_unitor_inv : quot.mk _ (hom₂.left_unitor_inv f) = (λ_ f).inv := rfl @[simp] lemma mk_right_unitor_hom : quot.mk _ (hom₂.right_unitor f) = (ρ_ f).hom := rfl @[simp] lemma mk_right_unitor_inv : quot.mk _ (hom₂.right_unitor_inv f) = (ρ_ f).inv := rfl /-- Canonical prefunctor from `B` to `free_bicategory B`. -/ @[simps] def of : prefunctor B (free_bicategory B) := { obj := id, map := λ a b, hom.of } end section variables {B : Type u₁} [quiver.{v₁+1} B] {C : Type u₂} [category_struct.{v₂} C] variables (F : prefunctor B C) /-- Auxiliary definition for `lift`. -/ @[simp] def lift_hom : ∀ {a b : B}, hom a b → (F.obj a ⟶ F.obj b) | _ _ (hom.of f) := F.map f | _ _ (hom.id a) := 𝟙 (F.obj a) | _ _ (hom.comp f g) := lift_hom f ≫ lift_hom g @[simp] lemma lift_hom_id (a : free_bicategory B) : lift_hom F (𝟙 a) = 𝟙 (F.obj a) := rfl @[simp] lemma lift_hom_comp {a b c : free_bicategory B} (f : a ⟶ b) (g : b ⟶ c) : lift_hom F (f ≫ g) = lift_hom F f ≫ lift_hom F g := rfl end section variables {B : Type u₁} [quiver.{v₁+1} B] {C : Type u₂} [bicategory.{w₂ v₂} C] variables (F : prefunctor B C) /-- Auxiliary definition for `lift`. -/ @[simp] def lift_hom₂ : ∀ {a b : B} {f g : hom a b}, hom₂ f g → (lift_hom F f ⟶ lift_hom F g) | _ _ _ _ (hom₂.id _) := 𝟙 _ | _ _ _ _ (hom₂.associator _ _ _) := (α_ _ _ _).hom | _ _ _ _ (hom₂.associator_inv _ _ _) := (α_ _ _ _).inv | _ _ _ _ (hom₂.left_unitor _) := (λ_ _).hom | _ _ _ _ (hom₂.left_unitor_inv _) := (λ_ _).inv | _ _ _ _ (hom₂.right_unitor _) := (ρ_ _).hom | _ _ _ _ (hom₂.right_unitor_inv _) := (ρ_ _).inv | _ _ _ _ (hom₂.vcomp η θ) := lift_hom₂ η ≫ lift_hom₂ θ | _ _ _ _ (hom₂.whisker_left f η) := lift_hom F f ◁ lift_hom₂ η | _ _ _ _ (hom₂.whisker_right h η) := lift_hom₂ η ▷ lift_hom F h local attribute [simp] whisker_exchange lemma lift_hom₂_congr {a b : B} {f g : hom a b} {η θ : hom₂ f g} (H : rel η θ) : lift_hom₂ F η = lift_hom₂ F θ := by induction H; tidy /-- A prefunctor from a quiver `B` to a bicategory `C` can be lifted to a pseudofunctor from `free_bicategory B` to `C`. -/ @[simps] def lift : pseudofunctor (free_bicategory B) C := { obj := F.obj, map := λ a b, lift_hom F, map₂ := λ a b f g, quot.lift (lift_hom₂ F) (λ η θ H, lift_hom₂_congr F H), map_id := λ a, iso.refl _, map_comp := λ a b c f g, iso.refl _ } end end free_bicategory end category_theory
6ddb1a143419a2a147f44c99f5dfab6024af6b3b
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/special_functions/non_integrable.lean
e23d717bfece35b4e65a46db5a4c472cce65d0b2
[ "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
9,611
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 analysis.special_functions.integrals import analysis.calculus.fderiv_measurable /-! # Non integrable functions In this file we prove that the derivative of a function that tends to infinity is not interval integrable, see `interval_integral.not_integrable_has_deriv_at_of_tendsto_norm_at_top_filter` and `interval_integral.not_integrable_has_deriv_at_of_tendsto_norm_at_top_punctured`. Then we apply the latter lemma to prove that the function `λ x, x⁻¹` is integrable on `a..b` if and only if `a = b` or `0 ∉ [a, b]`. ## Main results * `not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_punctured`: if `f` tends to infinity along `𝓝[≠] c` and `f' = O(g)` along the same filter, then `g` is not interval integrable on any nontrivial integral `a..b`, `c ∈ [a, b]`. * `not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_filter`: a version of `not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_punctured` that works for one-sided neighborhoods; * `not_interval_integrable_of_sub_inv_is_O_punctured`: if `1 / (x - c) = O(f)` as `x → c`, `x ≠ c`, then `f` is not interval integrable on any nontrivial interval `a..b`, `c ∈ [a, b]`; * `interval_integrable_sub_inv_iff`, `interval_integrable_inv_iff`: integrability conditions for `(x - c)⁻¹` and `x⁻¹`. ## Tags integrable function -/ open_locale measure_theory topological_space interval nnreal ennreal open measure_theory topological_space set filter asymptotics interval_integral variables {E F : Type*} [normed_group E] [normed_space ℝ E] [second_countable_topology E] [complete_space E] [normed_group F] /-- If `f` is eventually differentiable along a nontrivial filter `l : filter ℝ` that is generated by convex sets, the norm of `f` tends to infinity along `l`, and `f' = O(g)` along `l`, where `f'` is the derivative of `f`, then `g` is not integrable on any interval `a..b` such that `[a, b] ∈ l`. -/ lemma not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_filter {f : ℝ → E} {g : ℝ → F} {a b : ℝ} (l : filter ℝ) [ne_bot l] [tendsto_Ixx_class Icc l l] (hl : [a, b] ∈ l) (hd : ∀ᶠ x in l, differentiable_at ℝ f x) (hf : tendsto (λ x, ∥f x∥) l at_top) (hfg : deriv f =O[l] g) : ¬interval_integrable g volume a b := begin intro hgi, obtain ⟨C, hC₀, s, hsl, hsub, hfd, hg⟩ : ∃ (C : ℝ) (hC₀ : 0 ≤ C) (s ∈ l), (∀ (x ∈ s) (y ∈ s), [x, y] ⊆ [a, b]) ∧ (∀ (x ∈ s) (y ∈ s) (z ∈ [x, y]), differentiable_at ℝ f z) ∧ (∀ (x ∈ s) (y ∈ s) (z ∈ [x, y]), ∥deriv f z∥ ≤ C * ∥g z∥), { rcases hfg.exists_nonneg with ⟨C, C₀, hC⟩, have h : ∀ᶠ x : ℝ × ℝ in l.prod l, ∀ y ∈ [x.1, x.2], (differentiable_at ℝ f y ∧ ∥deriv f y∥ ≤ C * ∥g y∥) ∧ y ∈ [a, b], from (tendsto_fst.interval tendsto_snd).eventually ((hd.and hC.bound).and hl).small_sets, rcases mem_prod_self_iff.1 h with ⟨s, hsl, hs⟩, simp only [prod_subset_iff, mem_set_of_eq] at hs, exact ⟨C, C₀, s, hsl, λ x hx y hy z hz, (hs x hx y hy z hz).2, λ x hx y hy z hz, (hs x hx y hy z hz).1.1, λ x hx y hy z hz, (hs x hx y hy z hz).1.2⟩ }, replace hgi : interval_integrable (λ x, C * ∥g x∥) volume a b, by convert hgi.norm.smul C, obtain ⟨c, hc, d, hd, hlt⟩ : ∃ (c ∈ s) (d ∈ s), ∥f c∥ + ∫ y in Ι a b, C * ∥g y∥ < ∥f d∥, { rcases filter.nonempty_of_mem hsl with ⟨c, hc⟩, have : ∀ᶠ x in l, ∥f c∥ + ∫ y in Ι a b, C * ∥g y∥ < ∥f x∥, from hf.eventually (eventually_gt_at_top _), exact ⟨c, hc, (this.and hsl).exists.imp (λ d hd, ⟨hd.2, hd.1⟩)⟩ }, specialize hsub c hc d hd, specialize hfd c hc d hd, replace hg : ∀ x ∈ Ι c d, ∥deriv f x∥ ≤ C * ∥g x∥, from λ z hz, hg c hc d hd z ⟨hz.1.le, hz.2⟩, have hg_ae : ∀ᵐ x ∂(volume.restrict (Ι c d)), ∥deriv f x∥ ≤ C * ∥g x∥, from (ae_restrict_mem measurable_set_interval_oc).mono hg, have hsub' : Ι c d ⊆ Ι a b, from interval_oc_subset_interval_oc_of_interval_subset_interval hsub, have hfi : interval_integrable (deriv f) volume c d, from (hgi.mono_set hsub).mono_fun' (ae_strongly_measurable_deriv _ _) hg_ae, refine hlt.not_le (sub_le_iff_le_add'.1 _), calc ∥f d∥ - ∥f c∥ ≤ ∥f d - f c∥ : norm_sub_norm_le _ _ ... = ∥∫ x in c..d, deriv f x∥ : congr_arg _ (integral_deriv_eq_sub hfd hfi).symm ... = ∥∫ x in Ι c d, deriv f x∥ : norm_integral_eq_norm_integral_Ioc _ ... ≤ ∫ x in Ι c d, ∥deriv f x∥ : norm_integral_le_integral_norm _ ... ≤ ∫ x in Ι c d, C * ∥g x∥ : set_integral_mono_on hfi.norm.def (hgi.def.mono_set hsub') measurable_set_interval_oc hg ... ≤ ∫ x in Ι a b, C * ∥g x∥ : set_integral_mono_set hgi.def (ae_of_all _ $ λ x, mul_nonneg hC₀ (norm_nonneg _)) hsub'.eventually_le end /-- If `a ≠ b`, `c ∈ [a, b]`, `f` is differentiable in the neighborhood of `c` within `[a, b] \ {c}`, `∥f x∥ → ∞` as `x → c` within `[a, b] \ {c}`, and `f' = O(g)` along `𝓝[[a, b] \ {c}] c`, where `f'` is the derivative of `f`, then `g` is not interval integrable on `a..b`. -/ lemma not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_within_diff_singleton {f : ℝ → E} {g : ℝ → F} {a b c : ℝ} (hne : a ≠ b) (hc : c ∈ [a, b]) (h_deriv : ∀ᶠ x in 𝓝[[a, b] \ {c}] c, differentiable_at ℝ f x) (h_infty : tendsto (λ x, ∥f x∥) (𝓝[[a, b] \ {c}] c) at_top) (hg : deriv f =O[𝓝[[a, b] \ {c}] c] g) : ¬interval_integrable g volume a b := begin obtain ⟨l, hl, hl', hle, hmem⟩ : ∃ l : filter ℝ, tendsto_Ixx_class Icc l l ∧ l.ne_bot ∧ l ≤ 𝓝 c ∧ [a, b] \ {c} ∈ l, { cases (min_lt_max.2 hne).lt_or_lt c with hlt hlt, { refine ⟨𝓝[<] c, infer_instance, infer_instance, inf_le_left, _⟩, rw ← Iic_diff_right, exact diff_mem_nhds_within_diff (Icc_mem_nhds_within_Iic ⟨hlt, hc.2⟩) _ }, { refine ⟨𝓝[>] c, infer_instance, infer_instance, inf_le_left, _⟩, rw ← Ici_diff_left, exact diff_mem_nhds_within_diff (Icc_mem_nhds_within_Ici ⟨hc.1, hlt⟩) _ } }, resetI, have : l ≤ 𝓝[[a, b] \ {c}] c, from le_inf hle (le_principal_iff.2 hmem), exact not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_filter l (mem_of_superset hmem (diff_subset _ _)) (h_deriv.filter_mono this) (h_infty.mono_left this) (hg.mono this), end /-- If `f` is differentiable in a punctured neighborhood of `c`, `∥f x∥ → ∞` as `x → c` (more formally, along the filter `𝓝[≠] c`), and `f' = O(g)` along `𝓝[≠] c`, where `f'` is the derivative of `f`, then `g` is not interval integrable on any nontrivial interval `a..b` such that `c ∈ [a, b]`. -/ lemma not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_punctured {f : ℝ → E} {g : ℝ → F} {a b c : ℝ} (h_deriv : ∀ᶠ x in 𝓝[≠] c, differentiable_at ℝ f x) (h_infty : tendsto (λ x, ∥f x∥) (𝓝[≠] c) at_top) (hg : deriv f =O[𝓝[≠] c] g) (hne : a ≠ b) (hc : c ∈ [a, b]) : ¬interval_integrable g volume a b := have 𝓝[[a, b] \ {c}] c ≤ 𝓝[≠] c, from nhds_within_mono _ (inter_subset_right _ _), not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_within_diff_singleton hne hc (h_deriv.filter_mono this) (h_infty.mono_left this) (hg.mono this) /-- If `f` grows in the punctured neighborhood of `c : ℝ` at least as fast as `1 / (x - c)`, then it is not interval integrable on any nontrivial interval `a..b`, `c ∈ [a, b]`. -/ lemma not_interval_integrable_of_sub_inv_is_O_punctured {f : ℝ → F} {a b c : ℝ} (hf : (λ x, (x - c)⁻¹) =O[𝓝[≠] c] f) (hne : a ≠ b) (hc : c ∈ [a, b]) : ¬interval_integrable f volume a b := begin have A : ∀ᶠ x in 𝓝[≠] c, has_deriv_at (λ x, real.log (x - c)) (x - c)⁻¹ x, { filter_upwards [self_mem_nhds_within] with x hx, simpa using ((has_deriv_at_id x).sub_const c).log (sub_ne_zero.2 hx) }, have B : tendsto (λ x, ∥real.log (x - c)∥) (𝓝[≠] c) at_top, { refine tendsto_abs_at_bot_at_top.comp (real.tendsto_log_nhds_within_zero.comp _), rw ← sub_self c, exact ((has_deriv_at_id c).sub_const c).tendsto_punctured_nhds one_ne_zero }, exact not_interval_integrable_of_tendsto_norm_at_top_of_deriv_is_O_punctured (A.mono (λ x hx, hx.differentiable_at)) B (hf.congr' (A.mono $ λ x hx, hx.deriv.symm) eventually_eq.rfl) hne hc end /-- The function `λ x, (x - c)⁻¹` is integrable on `a..b` if and only if `a = b` or `c ∉ [a, b]`. -/ @[simp] lemma interval_integrable_sub_inv_iff {a b c : ℝ} : interval_integrable (λ x, (x - c)⁻¹) volume a b ↔ a = b ∨ c ∉ [a, b] := begin split, { refine λ h, or_iff_not_imp_left.2 (λ hne hc, _), exact not_interval_integrable_of_sub_inv_is_O_punctured (is_O_refl _ _) hne hc h }, { rintro (rfl|h₀), exacts [interval_integrable.refl, interval_integrable_inv (λ x hx, sub_ne_zero.2 $ ne_of_mem_of_not_mem hx h₀) (continuous_on_id.sub continuous_on_const)] } end /-- The function `λ x, x⁻¹` is integrable on `a..b` if and only if `a = b` or `0 ∉ [a, b]`. -/ @[simp] lemma interval_integrable_inv_iff {a b : ℝ} : interval_integrable (λ x, x⁻¹) volume a b ↔ a = b ∨ (0 : ℝ) ∉ [a, b] := by simp only [← interval_integrable_sub_inv_iff, sub_zero]
912bc5a18c88597bc5b263713c3bb368330e9ce2
827124860511172deb7ee955917c49b2bccd1b3c
/data/containers/utils/has_preordering.lean
a399273a347fed8ee811085c7214fe1738e9c351
[]
no_license
joehendrix/lean-containers
afec24c7de19c935774738ff3a0415362894956c
ef6ff0533eada75f18922039f8312badf12e6124
refs/heads/master
1,624,853,911,199
1,505,890,599,000
1,505,890,599,000
103,489,962
1
1
null
null
null
null
UTF-8
Lean
false
false
4,769
lean
/- This defines a preorder comparison function for comparing elements, and the notation of a monotonic search predicate for searching within a ordered set. -/ import .ordering section open ordering /-- Extend has_ordering to require the cmp function is consistent with a total preordering. -/ class has_preordering (α : Type _) extends has_ordering α := (refl : ∀ (a: α), cmp a a = eq) (le_trans : ∀(a b c : α), cmp a b ≤ eq → cmp b c ≤ eq → cmp a c ≠ gt) (gt_lt_symm : ∀ (a b : α), cmp a b = gt ↔ cmp b a = lt) end namespace has_preordering section parameters {α : Type _} [has_preordering α] open has_ordering open ordering theorem eq_symm : ∀ (a b : α), cmp a b = eq → cmp b a = eq := begin intros a b, have h0 := gt_lt_symm a b, have h1 := gt_lt_symm b a, destruct (cmp a b); destruct (cmp b a); cc, end theorem eq_trans : ∀ (a b c : α), cmp a b = eq → cmp b c = eq → cmp a c = eq := begin intros a b c ab bc, have h0 := eq_symm a b, have h1 := eq_symm b c, have h2 := le_trans c b a, have h3 := gt_lt_symm c a, have h4 := le_trans a b c, have h5 : lt ≤ eq := dec_trivial, have h6 : eq ≤ eq := dec_trivial, destruct (cmp a c); cc, end theorem lt_of_lt_of_lt : ∀(a b c : α), cmp a b = lt → cmp b c = lt → cmp a c = lt := begin intros a b c ab bc, have h0 := eq_symm a c, have h1 := le_trans c a b, have h2 : eq ≤ eq := dec_trivial, have h3 : lt ≤ eq := dec_trivial, have h4 := gt_lt_symm c b, have h5 := le_trans a b c, destruct (cmp a c); cc, end theorem lt_of_lt_of_eq : ∀(a b c : α), cmp a b = lt → cmp b c = eq → cmp a c = lt := begin intros a b c, have h0 := gt_lt_symm b a, have h1 := eq_symm a c, have h2 := le_trans b c a, have h3 := le_trans a b c, have h4 : lt ≤ eq := dec_trivial, have h5 : eq ≤ eq := dec_trivial, destruct (cmp a c); cc, end theorem lt_of_eq_of_lt : ∀(a b c : α), cmp a b = eq → cmp b c = lt → cmp a c = lt := begin intros a b c, have h0 := gt_lt_symm a c, have h1 := gt_lt_symm c b, have h2 := eq_symm a c, have h3 := le_trans c a b, have h4 : lt ≤ eq := dec_trivial, have h5 : eq ≤ eq := dec_trivial, destruct (cmp a c); try { cc }, end theorem swap_cmp (x y : α) : (has_ordering.cmp x y).swap = has_ordering.cmp y x := begin have gt_lt := (gt_lt_symm y x), have eq_eq := (eq_symm x y), have lt_gt := (gt_lt_symm x y), destruct (has_ordering.cmp x y); intros d0; simp only [d0, ordering.swap]; cc, end end end has_preordering ----------------------------------------------------------------------- -- monotonic_find section open ordering /-- This is a search procedure which given an element returns whether the element is less than, equal to, or greater than the value being searched for. Note that these axioms will imply that `cmp x = ordering.eq` and `cmp y = ordering.eq` implies `has_ordering.cmp x y`. -/ class monotonic_find {E: Type _} [has_preordering E] (cmp : E → ordering) := (gt_increases : ∀(x y : E), has_ordering.cmp x y = gt → eq ≤ cmp y → cmp x = gt) (eq_preserves : ∀(x y : E), has_ordering.cmp x y = eq → cmp x = cmp y) (lt_decreases : ∀(x y : E), has_ordering.cmp x y = lt → cmp y ≤ eq → cmp x = lt) end namespace monotonic_find /-- This is used to search for an element equivalent to a given element.-/ def eq {α : Type _} [has_preordering α] (e y : α) : ordering := has_ordering.cmp y e instance eq_is_cmp {α : Type _} [has_preordering α] (e : α) : monotonic_find (eq e) := { gt_increases := begin unfold eq, intros x y x_gt_y e_ge_y, have h0 : ¬ (ordering.eq ≤ ordering.lt) := dec_trivial, have h1 := has_preordering.eq_symm y e, have h2 := has_preordering.gt_lt_symm x y, have h3 := has_preordering.gt_lt_symm x e, have h4 := has_preordering.gt_lt_symm y e, have h5 := has_preordering.lt_of_eq_of_lt e y x, have h6 := has_preordering.lt_of_lt_of_lt e y x, destruct has_ordering.cmp y e; intros cmp_y_e; cc, end , eq_preserves := begin unfold eq, intros x y x_eq_y, have h0 := has_preordering.eq_symm x y, have h1 := has_preordering.gt_lt_symm x e, have h2 := has_preordering.gt_lt_symm y e, have h3 := has_preordering.lt_of_eq_of_lt y x e, have h4 := has_preordering.eq_trans y x e, have h5 := has_preordering.lt_of_lt_of_eq e x y, destruct has_ordering.cmp x e; intro cmp_x_e; cc, end , lt_decreases := begin unfold eq, intros x y x_lt_y y_le_e, have h0 : ¬ (ordering.gt ≤ ordering.eq) := dec_trivial, have h1 := has_preordering.lt_of_lt_of_lt x y e, have h2 := has_preordering.lt_of_lt_of_eq x y e, destruct has_ordering.cmp y e; intros cmp_y_e; cc, end } end monotonic_find
db667e4e4dcc5a65392922ab79c612b9ae5f3f6c
69bc7d0780be17e452d542a93f9599488f1c0c8e
/12-03-2019.lean
637f97b91c4436d95ca3afc50cde31154890ed55
[]
no_license
joek13/cs2102-notes
b7352285b1d1184fae25594f89f5926d74e6d7b4
25bb18788641b20af9cf3c429afe1da9b2f5eafb
refs/heads/master
1,673,461,162,867
1,575,561,090,000
1,575,561,090,000
207,573,549
0
0
null
null
null
null
UTF-8
Lean
false
false
2,006
lean
-- Notes 12/03/2019 /- Continuing our journey of learning to prove propositions of the form P ∨ Q -/ axiom Q : Prop axiom q : Q -- axiomatically accept a proof of Q axiom P : Prop example : P ∨ Q := begin apply or.inr q end example : false ∨ Q := begin apply or.inr q end example : 0 = 1 ∨ 2 = 2 := begin apply or.inr, apply rfl, end example : 0 = 1 ∨ 2 = 2 := or.intro_right _ rfl #check @or.intro_right #check @or.inr -- shorthand version example : P ∨ Q := or.intro_right P q -- classical vs. constructive logic example : P ∨ ¬P := sorry -- excluded middle: we can't prove this in constructive logic -- in constructive logic, if we don't have a proof of P, but we also don't have a proof of ¬P, we can't construct a proof of P ∨ ¬P -- c.f. the P=NP problem. We don't have a proof that P = NP, but we also don't have a proof that P != NP. -- the excluded middle is a valid form of reasoning in classical logic axiom excluded_middle : ∀ (P : Prop), P ∨ ¬P example : P ∨ ¬P := excluded_middle P example : P ∨ ¬P := begin apply classical.em end example : ∀ (P : Prop), ¬ ¬ P → P := begin assume P, assume nnp, cases (classical.em P) with hp hnp, -- we rely upon the law of the excluded middle to achieve this proof exact hp, contradiction, end /- Proof by negation: when we want to show ¬P Proof by negation: to prove ¬P, we show that P leads to a contradiction. Assume P, show contradiction gives us ¬P -/ /- Proof by contradiction: prove P by showing ¬P → false (¬¬P → P) If we want a proof that P is true, assume P is false, and show it leads to a contradiction I.e. show that ¬P → false i.e. ¬¬P holds If we have the law of the excluded middle, we can show ¬¬P → P Assume ¬P, show contradiction gives us P -/ axiom Rational : nat → Prop example : ¬¬(Rational 2) → Rational 2 := begin assume nnrt, cases (classical.em (Rational 2)), exact h, contradiction, end
2ed3e704a319161b5f9ec3d75d98cbdbb036b6d7
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/library/standard/logic/axioms/classical.lean
509777bf6d5186d29e6bce83da5a3762bde19e04
[ "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
5,623
lean
---------------------------------------------------------------------------------------------------- -- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura ---------------------------------------------------------------------------------------------------- import logic.connectives.basic logic.connectives.quantifiers logic.connectives.cast using eq_proofs axiom prop_complete (a : Prop) : a = true ∨ a = false theorem case (P : Prop → Prop) (H1 : P true) (H2 : P false) (a : Prop) : P a := or_elim (prop_complete a) (assume Ht : a = true, Ht⁻¹ ▸ H1) (assume Hf : a = false, Hf⁻¹ ▸ H2) theorem em (a : Prop) : a ∨ ¬a := or_elim (prop_complete a) (assume Ht : a = true, or_inl (eqt_elim Ht)) (assume Hf : a = false, or_inr (eqf_elim Hf)) theorem prop_complete_swapped (a : Prop) : a = false ∨ a = true := case (λ x, x = false ∨ x = true) (or_inr (refl true)) (or_inl (refl false)) a theorem not_true : (¬true) = false := have aux : (¬true) ≠ true, from assume H : (¬true) = true, absurd_not_true (H⁻¹ ▸ trivial), resolve_right (prop_complete (¬true)) aux theorem not_false : (¬false) = true := have aux : (¬false) ≠ false, from assume H : (¬false) = false, H ▸ not_false_trivial, resolve_right (prop_complete_swapped (¬false)) aux theorem not_not_eq (a : Prop) : (¬¬a) = a := case (λ x, (¬¬x) = x) (calc (¬¬true) = (¬false) : {not_true} ... = true : not_false) (calc (¬¬false) = (¬true) : {not_false} ... = false : not_true) a theorem not_not_elim {a : Prop} (H : ¬¬a) : a := (not_not_eq a) ◂ H theorem propext {a b : Prop} (Hab : a → b) (Hba : b → a) : a = b := or_elim (prop_complete a) (assume Hat, or_elim (prop_complete b) (assume Hbt, Hat ⬝ Hbt⁻¹) (assume Hbf, false_elim (a = b) (Hbf ▸ (Hab (eqt_elim Hat))))) (assume Haf, or_elim (prop_complete b) (assume Hbt, false_elim (a = b) (Haf ▸ (Hba (eqt_elim Hbt)))) (assume Hbf, Haf ⬝ Hbf⁻¹)) theorem iff_to_eq {a b : Prop} (H : a ↔ b) : a = b := iff_elim (assume H1 H2, propext H1 H2) H theorem iff_eq_eq {a b : Prop} : (a ↔ b) = (a = b) := propext (assume H, iff_to_eq H) (assume H, eq_to_iff H) theorem eqt_intro {a : Prop} (H : a) : a = true := propext (assume H1 : a, trivial) (assume H2 : true, H) theorem eqf_intro {a : Prop} (H : ¬a) : a = false := propext (assume H1 : a, absurd H1 H) (assume H2 : false, false_elim a H2) theorem by_contradiction {a : Prop} (H : ¬a → false) : a := or_elim (em a) (assume H1 : a, H1) (assume H1 : ¬a, false_elim a (H H1)) theorem a_neq_a {A : Type} (a : A) : (a ≠ a) = false := propext (assume H, a_neq_a_elim H) (assume H, false_elim (a ≠ a) H) theorem eq_id {A : Type} (a : A) : (a = a) = true := eqt_intro (refl a) theorem heq_id {A : Type} (a : A) : (a == a) = true := eqt_intro (hrefl a) theorem not_or (a b : Prop) : (¬(a ∨ b)) = (¬a ∧ ¬b) := propext (assume H, or_elim (em a) (assume Ha, absurd_elim (¬a ∧ ¬b) (or_inl Ha) H) (assume Hna, or_elim (em b) (assume Hb, absurd_elim (¬a ∧ ¬b) (or_inr Hb) H) (assume Hnb, and_intro Hna Hnb))) (assume (H : ¬a ∧ ¬b) (N : a ∨ b), or_elim N (assume Ha, absurd Ha (and_elim_left H)) (assume Hb, absurd Hb (and_elim_right H))) theorem not_and (a b : Prop) : (¬(a ∧ b)) = (¬a ∨ ¬b) := propext (assume H, or_elim (em a) (assume Ha, or_elim (em b) (assume Hb, absurd_elim (¬a ∨ ¬b) (and_intro Ha Hb) H) (assume Hnb, or_inr Hnb)) (assume Hna, or_inl Hna)) (assume (H : ¬a ∨ ¬b) (N : a ∧ b), or_elim H (assume Hna, absurd (and_elim_left N) Hna) (assume Hnb, absurd (and_elim_right N) Hnb)) theorem imp_or (a b : Prop) : (a → b) = (¬a ∨ b) := propext (assume H : a → b, (or_elim (em a) (assume Ha : a, or_inr (H Ha)) (assume Hna : ¬a, or_inl Hna))) (assume (H : ¬a ∨ b) (Ha : a), resolve_right H ((not_not_eq a)⁻¹ ◂ Ha)) theorem not_implies (a b : Prop) : (¬(a → b)) = (a ∧ ¬b) := calc (¬(a → b)) = (¬(¬a ∨ b)) : {imp_or a b} ... = (¬¬a ∧ ¬b) : not_or (¬a) b ... = (a ∧ ¬b) : {not_not_eq a} theorem a_eq_not_a (a : Prop) : (a = ¬a) = false := propext (assume H, or_elim (em a) (assume Ha, absurd Ha (H ▸ Ha)) (assume Hna, absurd (H⁻¹ ▸ Hna) Hna)) (assume H, false_elim (a = ¬a) H) theorem true_eq_false : (true = false) = false := not_true ▸ (a_eq_not_a true) theorem false_eq_true : (false = true) = false := not_false ▸ (a_eq_not_a false) theorem a_eq_true (a : Prop) : (a = true) = a := propext (assume H, eqt_elim H) (assume H, eqt_intro H) theorem a_eq_false (a : Prop) : (a = false) = ¬a := propext (assume H, eqf_elim H) (assume H, eqf_intro H) theorem not_exists_forall {A : Type} {P : A → Prop} (H : ¬∃x, P x) : ∀x, ¬P x := take x, or_elim (em (P x)) (assume Hp : P x, absurd_elim (¬P x) (exists_intro x Hp) H) (assume Hn : ¬P x, Hn) theorem not_forall_exists {A : Type} {P : A → Prop} (H : ¬∀x, P x) : ∃x, ¬P x := by_contradiction (assume H1 : ¬∃ x, ¬P x, have H2 : ∀x, ¬¬P x, from not_exists_forall H1, have H3 : ∀x, P x, from take x, not_not_elim (H2 x), absurd H3 H) theorem peirce (a b : Prop) : ((a → b) → a) → a := assume H, by_contradiction (assume Hna : ¬a, have Hnna : ¬¬a, from not_implies_left (mt H Hna), absurd (not_not_elim Hnna) Hna)
1eb391a6b38abfef0deacd7f1926022b2754552b
60bf3fa4185ec5075eaea4384181bfbc7e1dc319
/src/defs.lean
d57f46c32d9925e50154ca59432f3932b20c4545
[ "Apache-2.0" ]
permissive
anrddh/real-number-game
660f1127d03a78fd35986c771d65c3132c5f4025
c708c4e02ec306c657e1ea67862177490db041b0
refs/heads/master
1,668,214,277,092
1,593,105,075,000
1,593,105,075,000
264,269,218
0
0
null
1,589,567,264,000
1,589,567,264,000
null
UTF-8
Lean
false
false
1,969
lean
import data.real.basic import data.set.intervals import tactic.norm_num -- nonempty is a class but let's have it working on set ℝ namespace real_number_game -- hide (need to choose this or P) class nonemptyT (S : set ℝ) : Type := (x : ℝ) (thm : x ∈ S) -- hide (need to choose this or T) class nonemptyP (S : set ℝ) : Prop := (thm' : ∃ x : ℝ, x ∈ S) def nonemptyP.thm (S : set ℝ) [nonemptyP S] : ∃ x : ℝ, x ∈ S := nonemptyP.thm' -- irrelevant example example : ∃ x: ℝ, x < 1 := ⟨0.5, by norm_num⟩ example : (0.5 : ℝ) < 1 := by norm_num -- irrelevant example noncomputable example : nonemptyT (set.Icc 0 1) := { x := 0.5, thm := by {simp,split;norm_num} } -- show def is_upper_bound (S : set ℝ) (b : ℝ) : Prop := ∀ s ∈ S, s ≤ b -- hide this def class bounded_aboveT (S : set ℝ) : Type := (b : ℝ) (thm : is_upper_bound S b) -- hide this def class bounded_aboveP (S : set ℝ) : Prop := (thm' : ∃ b : ℝ, is_upper_bound S b) def bounded_aboveP.thm (S : set ℝ) [bounded_aboveP S] : ∃ b : ℝ, is_upper_bound S b := bounded_aboveP.thm' -- example (for me only) instance : bounded_aboveT (set.Icc 0 1) := { b := 2, thm := λ r ⟨h1, h2⟩, le_trans h2 (by norm_num) } -- hide noncomputable def Sup (S : set ℝ) [nonemptyP S] [bounded_aboveP S] := _root_.Sup S -- state as axiom; hide proof theorem le_Sup {S : set ℝ} [nonemptyP S] [bounded_aboveP S] : ∀ x ∈ S, x ≤ Sup S := begin apply real.le_Sup, cases bounded_aboveP.thm S with b hb, use b, exact hb, end -- state as axiom; hide proof theorem Sup_le {S : set ℝ} [nonemptyP S] [bounded_aboveP S] : ∀ b : ℝ, is_upper_bound S b → Sup S ≤ b := begin intros b hb, show _root_.Sup S ≤ b, rw real.Sup_le, { exact hb}, { cases nonemptyP.thm S with c hc, use c, exact hc}, { use b, exact hb} end -- other axioms: ℤ unbounded, linearly ordered field. -- Might need to introduce later. end real_number_game
554504f690ea6f27fe42f9f1364732060ed36f47
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/noncomputable_constructor_param.lean
27e443902915f44893af6a1640f22bd9bc63cd06
[ "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,027
lean
inductive A {α : Type*} (x : α) | c1 (x y z : ℕ) : A | c2 : A | c3 (x : ℕ) : A def foo0 (h : ∃ (x : ℕ), x = x) : A (classical.some h) := A.c2 def foo1 (h : ∃ (x : ℕ), x = x) : A (classical.some h) := A.c3 4 def foo3 (h : ∃ (x : ℕ), x = x) : A (classical.some h) := A.c1 1 2 3 noncomputable def foo4 (h : ∃ (x : ℕ), x = x) : A (classical.some h) := A.c3 (classical.some h) noncomputable def foo5 (h : ∃ (x : ℕ), x = x) : A (classical.some h) := A.c1 1 (classical.some h) 3 class computable {α : Type*} (x : α) := (compute : α) (compute_eq : compute = x) export computable attribute [inline] compute instance {α : Type*} (x : α) (h : ∃ (y : α), y = x) : computable (classical.some h) := ⟨x, (classical.some_spec h).symm⟩ def foo6 (h : ∃ (n : ℕ), n = 37) := compute (classical.some h) noncomputable def foo7 (h : ∃ (n : ℕ), n = 37) := classical.some h inductive B (α : Type*) | c (x : α) : B noncomputable def foo8 (h : ∃ (n : ℕ), n = 37) := B.c (classical.some h)
061660f8e5014d9e18e7d2effcc0749d13eccdbc
097294e9b80f0d9893ac160b9c7219aa135b51b9
/assignments/hw9.lean
9d490b93ca5375583f0054c3e838b79226a485cd
[]
no_license
AbigailCastro17/CS2102-Discrete-Math
cf296251be9418ce90206f5e66bde9163e21abf9
d741e4d2d6a9b2e0c8380e51706218b8f608cee4
refs/heads/main
1,682,891,087,358
1,621,401,341,000
1,621,401,341,000
368,749,959
0
0
null
null
null
null
UTF-8
Lean
false
false
6,526
lean
/- HOMEWORK #9 There is no need to import our previous definitions. For this homework you will just use Lean's built-in notations and definitions. -/ /- Prove the following. Note that you can read each of the propositions to be proved as either a logical statement or as simply a function definition. Use what you already know about the latter to arrive at a proof, and then understand the proof as one that shows that the logical statement is true. -/ theorem t1 {P Q : Prop} (p2q : P → Q) (p : P) : Q := _ theorem t2 {P Q R : Prop} (p2q : P → Q) (q2r : Q → R): P → R := _ /- Use "example" to state and prove the preceding two theorems but using "cases" style notation rather than C-style. Remember, "example" is a way to state a proposition/type and give an example of a value. Here's an example of the use of "example". Give your answers following this example. -/ -- example example : ℕ := 5 -- Your two answers here /- Now give English-language versions of your two proofs. -/ /- Prove the following using case analysis on one of the arguments (i.e., use match...with...end at a key point in your proof). Use "cases" style notation. -/ theorem t3 : ∀ (P : Prop), false → P | P f := _ /- Prove false → true by applying t3 to a proposition. You have to figure out which one. -/ theorem t4 : false → true := t3 _ /- Define t5 to be the same as t3 but with P taken as an implicit argument. -/ theorem t5 : ∀ {P : Prop}, false → P | P f := _ /- Define t6 to be a proof of false → true by applying t5 to the right argument(s). -/ theorem t6 : false → true := _ /- That is almost magic. In English, t3 proves that false implies *any* proposition, so just *apply* t3 to *true* in particular, but use t5 instead of t3. What you see here is really important: Once we've proved a general theorem (a ∀ proposition) we can *apply the proof* to any *particular* case to yield a proof for that specific case. This is the elimination rule for ∀. It is also known as universal instantiation (UI). -/ /- Next we see the idea that test cases are really just equality propositions to be proved. Here, for example, is a definition of the factorial function. -/ def fac : ℕ → ℕ | 0 := 1 | (n' + 1) := (n' + 1) * fac n' /- Use "example" to write test cases for the first ten natural number arguments to this function. -/ example : fac 0 = 1 := eq.refl 1 example : fac 1 = 1 := eq.refl _ -- Inferred example : fac 2 = 2 := rfl -- Shorthand #check @rfl -- infers type and value -- The rest of your answers here /- Insight: A test case is an equality proposition. It is proved by "running" the program under test to reduce the application of the function to input arguments to produce an output that is then asserted to be equal to an expected output. In many cases, all we have to do is to simplify the expressions on each side of the eq to see if they reduce to exactly the same value. If so, we can *apply* eq.refl (a universal generalization!) to that value. Using rfl we can avoid even having to type that value in cases where Lean can infer it. -/ /- The next problem requires thave you give a proof of a bi-implication, a proposition whose connective is ↔. To prove a bi-implication requires that one prove an implication in each direction. Here you are asked to prove P ∧ Q ↔ Q ∧ P. What this formula asserts is that ∧ is commutative. To construct a proof of this proposition you will have to apply iff.intro to two smaller proofs, one of P → Q and and of Q → P. Start by "assuming" that P and Q are arbitary but specific propositions (∀ introduction), then apply iff.intro to two "stubbed out" arguments (underscores). We suggest that you put the underscores in parentheses on different lines. Then recursively fill in each of these stubs with the required types of proofs. Study the context that Lean shows you in its Messages panel to see what you have to work with at each point in your proof constructions. -/ theorem t7 : ∀ {P Q : Prop}, P ∧ Q ↔ Q ∧ P := _ /- In English, when asked to prove P ↔ Q, one says, "it will suffice to show P → Q and then to show Q → P." One then goes on to give a proof of each implication. It then follows from iff.intro that a proof of P ↔ Q can be constructed, proving the bi-implication. -/ /- The trick here is to do case analysis on porq (use match ... with ... end) and to show that a proof of R can be constructed *in either case*. -/ theorem t8 {P Q R : Prop} (p2r : P → R) (q2r : Q → R) (porq : P ∨ Q) : R := _ /- We suggest that you use "let ... in" to give names to intermediate results that you then combine in a final expression to finish the proof. -/ theorem t9 : ∀ (P Q: Prop), (P → Q) → ¬ (P ∧ ¬ Q) := _ theorem neg_elim' : ∀ (P : Prop), ¬ ¬ P → P := λ P, λ nnp, _ -- STUCK!! theorem neg_elim : ∀ (P : Prop), (P ∨ ¬ P) → (¬ ¬ P → P):= λ P, λ h, λ nnp, match h with | or.inl p := p | or.inr np := false.elim (nnp np) -- false elimination end -- nnp : (¬ P) → false -- np : ¬ P -- nnp np = false! -- Let's use H to mean There is a sub-exponential time algorithm for Boolean sat. -- ¬ H means that there's not one. -- H ∨ ¬H -- make Lean into a classical logic -- axiom em : ∀ (P : Prop), P ∨ ¬ P #check classical.em theorem t10 : ∀ (P : Prop), P ∨ ¬ P := _ #check @or.inl #check @or.inr theorem t11 : ∀ (P Q : Prop), ¬ (P ∨ Q) ↔ ¬ P ∧ ¬ Q := λ P Q, iff.intro (λ not_porq, match (classical.em P) with | or.inl p := false.elim (not_porq (or.inl p)) | or.inr np := match (classical.em Q) with | or.inl q := false.elim (not_porq (or.inr q)) | or.inr nq := and.intro np nq end end ) _ theorem t12 : ∀ (P Q : Prop), ¬ (P ∧ Q) ↔ ¬ P ∨ ¬ Q := _ /- For the following exercises, we assume that there is a type called Person and a binary relation, Likes, on pairs of people. -/ axiom Person : Type axiom Likes : Person → Person → Prop /- Prove the following -/ theorem t13 : (∃ (p : Person), ∀ (q : Person), Likes q p) → (∀ (p : Person), ∃ (q : Person), Likes p q) := λ h, match h with | exists.intro p pf := λ q, (exists.intro p (pf q)) end
898f991f4edb1c01da237db08e22385ed40b9852
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/polynomial/basic.lean
63b7d2f50e473a74f7cda3c89e38f812284f606b
[ "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
43,892
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.char_p.basic import data.mv_polynomial.comm_ring import data.mv_polynomial.equiv import ring_theory.polynomial.content import ring_theory.unique_factorization_domain /-! # Ring-theoretic supplement of data.polynomial. ## Main results * `mv_polynomial.is_domain`: If a ring is an integral domain, then so is its polynomial ring over finitely many variables. * `polynomial.is_noetherian_ring`: Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring. * `polynomial.wf_dvd_monoid`: If an integral domain is a `wf_dvd_monoid`, then so is its polynomial ring. * `polynomial.unique_factorization_monoid`: If an integral domain is a `unique_factorization_monoid`, then so is its polynomial ring. -/ noncomputable theory open_locale classical big_operators universes u v w namespace polynomial instance {R : Type u} [semiring R] (p : ℕ) [h : char_p R p] : char_p (polynomial R) p := let ⟨h⟩ := h in ⟨λ n, by rw [← map_nat_cast C, ← C_0, C_inj, h]⟩ variables (R : Type u) [comm_ring R] /-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker /-- The `R`-submodule of `R[X]` consisting of polynomials of degree < `n`. -/ def degree_lt (n : ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : k ≥ n, (lcoeff R k).ker variable {R} theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} : f ∈ degree_le R n ↔ degree f ≤ n := by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl @[mono] theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n) : degree_le R m ≤ degree_le R n := λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H) theorem degree_le_eq_span_X_pow {n : ℕ} : degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, (X : polynomial R)^n)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_le.1 hp, rw [← polynomial.sum_monomial_eq p, polynomial.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk), rw [monomial_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_le.2, exact (degree_X_pow_le _).trans (with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk) end theorem mem_degree_lt {n : ℕ} {f : polynomial R} : f ∈ degree_lt R n ↔ degree f < n := by { simp_rw [degree_lt, submodule.mem_infi, linear_map.mem_ker, degree, finset.sup_lt_iff (with_bot.bot_lt_coe n), mem_support_iff, with_bot.some_eq_coe, with_bot.coe_lt_coe, lt_iff_not_ge', ne, not_imp_not], refl } @[mono] theorem degree_lt_mono {m n : ℕ} (H : m ≤ n) : degree_lt R m ≤ degree_lt R n := λ f hf, mem_degree_lt.2 (lt_of_lt_of_le (mem_degree_lt.1 hf) $ with_bot.coe_le_coe.2 H) theorem degree_lt_eq_span_X_pow {n : ℕ} : degree_lt R n = submodule.span R ↑((finset.range n).image (λ n, X^n) : finset (polynomial R)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_lt.1 hp, rw [← polynomial.sum_monomial_eq p, polynomial.sum], refine submodule.sum_mem _ (λ k hk, _), show monomial _ _ ∈ _, have := with_bot.coe_lt_coe.1 ((finset.sup_lt_iff $ with_bot.bot_lt_coe n).1 hp k hk), rw [monomial_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 this, rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_lt.2, exact lt_of_le_of_lt (degree_X_pow_le _) (with_bot.coe_lt_coe.2 $ finset.mem_range.1 hk) end /-- The first `n` coefficients on `degree_lt n` form a linear equivalence with `fin n → F`. -/ def degree_lt_equiv (F : Type*) [field F] (n : ℕ) : degree_lt F n ≃ₗ[F] (fin n → F) := { to_fun := λ p n, (↑p : polynomial F).coeff n, inv_fun := λ f, ⟨∑ i : fin n, monomial i (f i), (degree_lt F n).sum_mem (λ i _, mem_degree_lt.mpr (lt_of_le_of_lt (degree_monomial_le i (f i)) (with_bot.coe_lt_coe.mpr i.is_lt)))⟩, map_add' := λ p q, by { ext, rw [submodule.coe_add, coeff_add], refl }, map_smul' := λ x p, by { ext, rw [submodule.coe_smul, coeff_smul], refl }, left_inv := begin rintro ⟨p, hp⟩, ext1, simp only [submodule.coe_mk], by_cases hp0 : p = 0, { subst hp0, simp only [coeff_zero, linear_map.map_zero, finset.sum_const_zero] }, rw [mem_degree_lt, degree_eq_nat_degree hp0, with_bot.coe_lt_coe] at hp, conv_rhs { rw [p.as_sum_range' n hp, ← fin.sum_univ_eq_sum_range] }, end, right_inv := begin intro f, ext i, simp only [finset_sum_coeff, submodule.coe_mk], rw [finset.sum_eq_single i, coeff_monomial, if_pos rfl], { rintro j - hji, rw [coeff_monomial, if_neg], rwa [← subtype.ext_iff] }, { intro h, exact (h (finset.mem_univ _)).elim } end } /-- The finset of nonzero coefficients of a polynomial. -/ def frange (p : polynomial R) : finset R := finset.image (λ n, p.coeff n) p.support lemma frange_zero : frange (0 : polynomial R) = ∅ := rfl lemma mem_frange_iff {p : polynomial R} {c : R} : c ∈ p.frange ↔ ∃ n ∈ p.support, c = p.coeff n := by simp [frange, eq_comm] lemma frange_one : frange (1 : polynomial R) ⊆ {1} := begin simp [frange, finset.image_subset_iff], simp only [← C_1, coeff_C], assume n hn, simp only [exists_prop, ite_eq_right_iff, not_forall] at hn, simp [hn], end lemma coeff_mem_frange (p : polynomial R) (n : ℕ) (h : p.coeff n ≠ 0) : p.coeff n ∈ p.frange := begin simp only [frange, exists_prop, mem_support_iff, finset.mem_image, ne.def], exact ⟨n, h, rfl⟩, end /-- Given a polynomial, return the polynomial whose coefficients are in the ring closure of the original coefficients. -/ def restriction (p : polynomial R) : polynomial (subring.closure (↑p.frange : set R)) := ∑ i in p.support, monomial i (⟨p.coeff i, if H : p.coeff i = 0 then H.symm ▸ (subring.closure _).zero_mem else subring.subset_closure (p.coeff_mem_frange _ H)⟩ : (subring.closure (↑p.frange : set R))) @[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} : ↑(coeff (restriction p) n) = coeff p n := begin simp only [restriction, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq', ne.def, ite_not], split_ifs, { rw h, refl }, { refl } end @[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} : (coeff (restriction p) n).1 = coeff p n := coeff_restriction @[simp] lemma support_restriction (p : polynomial R) : support (restriction p) = support p := begin ext i, simp only [mem_support_iff, not_iff_not, ne.def], conv_rhs { rw [← coeff_restriction] }, exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end @[simp] theorem map_restriction (p : polynomial R) : p.restriction.map (algebra_map _ _) = p := ext $ λ n, by rw [coeff_map, algebra.algebra_map_of_subring_apply, coeff_restriction] @[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree := by simp [degree] @[simp] theorem nat_degree_restriction {p : polynomial R} : (restriction p).nat_degree = p.nat_degree := by simp [nat_degree] @[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p := begin simp only [monic, leading_coeff, nat_degree_restriction], rw [←@coeff_restriction _ _ p], exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end @[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 := by simp only [restriction, finset.sum_empty, support_zero] @[simp] theorem restriction_one : restriction (1 : polynomial R) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl variables {S : Type v} [ring S] {f : R →+* S} {x : S} theorem eval₂_restriction {p : polynomial R} : eval₂ f x p = eval₂ (f.comp (subring.subtype _)) x p.restriction := begin simp only [eval₂_eq_sum, sum, support_restriction, ←@coeff_restriction _ _ p], refl, end section to_subring variables (p : polynomial R) (T : subring R) /-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`, return the corresponding polynomial whose coefficients are in `T. -/ def to_subring (hp : (↑p.frange : set R) ⊆ T) : polynomial T := ∑ i in p.support, monomial i (⟨p.coeff i, if H : p.coeff i = 0 then H.symm ▸ T.zero_mem else hp (p.coeff_mem_frange _ H)⟩ : T) variables (hp : (↑p.frange : set R) ⊆ T) include hp @[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n := begin simp only [to_subring, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq', ne.def, ite_not], split_ifs, { rw h, refl }, { refl } end @[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n := coeff_to_subring _ _ hp @[simp] lemma support_to_subring : support (to_subring p T hp) = support p := begin ext i, simp only [mem_support_iff, not_iff_not, ne.def], conv_rhs { rw [← coeff_to_subring p T hp] }, exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end @[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree := by simp [degree] @[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree := by simp [nat_degree] @[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p := begin simp_rw [monic, leading_coeff, nat_degree_to_subring, ← coeff_to_subring p T hp], exact ⟨λ H, by { rw H, refl }, λ H, subtype.coe_injective H⟩ end omit hp @[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (by simp [frange_zero]) = 0 := by { ext i, simp } @[simp] theorem to_subring_one : to_subring (1 : polynomial R) T (set.subset.trans frange_one $finset.singleton_subset_set_iff.2 T.one_mem) = 1 := ext $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl @[simp] theorem map_to_subring : (p.to_subring T hp).map (subring.subtype T) = p := by { ext n, simp [coeff_map] } end to_subring variables (T : subring R) /-- Given a polynomial whose coefficients are in some subring, return the corresponding polynomial whose coefficients are in the ambient ring. -/ def of_subring (p : polynomial T) : polynomial R := ∑ i in p.support, monomial i (p.coeff i : R) lemma coeff_of_subring (p : polynomial T) (n : ℕ) : coeff (of_subring T p) n = (coeff p n : T) := begin simp only [of_subring, coeff_monomial, finset_sum_coeff, mem_support_iff, finset.sum_ite_eq', ite_eq_right_iff, ne.def, ite_not, not_not, ite_eq_left_iff], assume h, rw h, refl end @[simp] theorem frange_of_subring {p : polynomial T} : (↑(p.of_subring T).frange : set R) ⊆ T := begin assume i hi, simp only [frange, set.mem_image, mem_support_iff, ne.def, finset.mem_coe, finset.coe_image] at hi, rcases hi with ⟨n, hn, h'n⟩, rw [← h'n, coeff_of_subring], exact subtype.mem (coeff p n : T) end section mod_by_monic variables {q : polynomial R} lemma mem_ker_mod_by_monic [nontrivial R] (hq : q.monic) {p : polynomial R} : p ∈ (mod_by_monic_hom hq).ker ↔ q ∣ p := linear_map.mem_ker.trans (dvd_iff_mod_by_monic_eq_zero hq) @[simp] lemma ker_mod_by_monic_hom [nontrivial R] (hq : q.monic) : (polynomial.mod_by_monic_hom hq).ker = (ideal.span {q}).restrict_scalars R := submodule.ext (λ f, (mem_ker_mod_by_monic hq).trans ideal.mem_span_singleton.symm) end mod_by_monic end polynomial variables {R : Type u} {S : Type*} {σ : Type v} {M : Type w} variables [comm_ring R] [comm_ring S] [add_comm_group M] [module R M] namespace ideal open polynomial /-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself -/ lemma polynomial_mem_ideal_of_coeff_mem_ideal (I : ideal (polynomial R)) (p : polynomial R) (hp : ∀ (n : ℕ), (p.coeff n) ∈ I.comap C) : p ∈ I := sum_C_mul_X_eq p ▸ submodule.sum_mem I (λ n hn, I.mul_mem_right _ (hp n)) /-- The push-forward of an ideal `I` of `R` to `polynomial R` via inclusion is exactly the set of polynomials whose coefficients are in `I` -/ theorem mem_map_C_iff {I : ideal R} {f : polynomial R} : f ∈ (ideal.map C I : ideal (polynomial R)) ↔ ∀ n : ℕ, f.coeff n ∈ I := begin split, { intros hf, apply submodule.span_induction hf, { intros f hf n, cases (set.mem_image _ _ _).mp hf with x hx, rw [← hx.right, coeff_C], by_cases (n = 0), { simpa [h] using hx.left }, { simp [h] } }, { simp }, { exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] }, { refine λ f g hg n, _, rw [smul_eq_mul, coeff_mul], exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } }, { intros hf, rw ← sum_monomial_eq f, refine (I.map C : ideal (polynomial R)).sum_mem (λ n hn, _), simp [monomial_eq_C_mul_X], rw mul_comm, exact (I.map C : ideal (polynomial R)).mul_mem_left _ (mem_map_of_mem _ (hf n)) } end lemma _root_.polynomial.ker_map_ring_hom (f : R →+* S) : (polynomial.map_ring_hom f).ker = f.ker.map C := begin ext, rw [mem_map_C_iff, ring_hom.mem_ker, polynomial.ext_iff], simp_rw [coe_map_ring_hom, coeff_map, coeff_zero, ring_hom.mem_ker], end lemma quotient_map_C_eq_zero {I : ideal R} : ∀ a ∈ I, ((quotient.mk (map C I : ideal (polynomial R))).comp C) a = 0 := begin intros a ha, rw [ring_hom.comp_apply, quotient.eq_zero_iff_mem], exact mem_map_of_mem _ ha, end lemma eval₂_C_mk_eq_zero {I : ideal R} : ∀ f ∈ (map C I : ideal (polynomial R)), eval₂_ring_hom (C.comp (quotient.mk I)) X f = 0 := begin intros a ha, rw ← sum_monomial_eq a, dsimp, rw eval₂_sum, refine finset.sum_eq_zero (λ n hn, _), dsimp, rw eval₂_monomial (C.comp (quotient.mk I)) X, refine mul_eq_zero_of_left (polynomial.ext (λ m, _)) (X ^ n), erw coeff_C, by_cases h : m = 0, { simpa [h] using quotient.eq_zero_iff_mem.2 ((mem_map_C_iff.1 ha) n) }, { simp [h] } end /-- If `I` is an ideal of `R`, then the ring polynomials over the quotient ring `I.quotient` is isomorphic to the quotient of `polynomial R` by the ideal `map C I`, where `map C I` contains exactly the polynomials whose coefficients all lie in `I` -/ def polynomial_quotient_equiv_quotient_polynomial (I : ideal R) : polynomial (R ⧸ I) ≃+* polynomial R ⧸ (map C I : ideal (polynomial R)) := { to_fun := eval₂_ring_hom (quotient.lift I ((quotient.mk (map C I : ideal (polynomial R))).comp C) quotient_map_C_eq_zero) ((quotient.mk (map C I : ideal (polynomial R)) X)), inv_fun := quotient.lift (map C I : ideal (polynomial R)) (eval₂_ring_hom (C.comp (quotient.mk I)) X) eval₂_C_mk_eq_zero, map_mul' := λ f g, by simp only [coe_eval₂_ring_hom, eval₂_mul], map_add' := λ f g, by simp only [eval₂_add, coe_eval₂_ring_hom], left_inv := begin intro f, apply polynomial.induction_on' f, { intros p q hp hq, simp only [coe_eval₂_ring_hom] at hp, simp only [coe_eval₂_ring_hom] at hq, simp only [coe_eval₂_ring_hom, hp, hq, ring_hom.map_add] }, { rintros n ⟨x⟩, simp only [monomial_eq_smul_X, C_mul', quotient.lift_mk, submodule.quotient.quot_mk_eq_mk, quotient.mk_eq_mk, eval₂_X_pow, eval₂_smul, coe_eval₂_ring_hom, ring_hom.map_pow, eval₂_C, ring_hom.coe_comp, ring_hom.map_mul, eval₂_X] } end, right_inv := begin rintro ⟨f⟩, apply polynomial.induction_on' f, { simp_intros p q hp hq, rw [hp, hq] }, { intros n a, simp only [monomial_eq_smul_X, ← C_mul' a (X ^ n), quotient.lift_mk, submodule.quotient.quot_mk_eq_mk, quotient.mk_eq_mk, eval₂_X_pow, eval₂_smul, coe_eval₂_ring_hom, ring_hom.map_pow, eval₂_C, ring_hom.coe_comp, ring_hom.map_mul, eval₂_X] }, end, } @[simp] lemma polynomial_quotient_equiv_quotient_polynomial_symm_mk (I : ideal R) (f : polynomial R) : I.polynomial_quotient_equiv_quotient_polynomial.symm (quotient.mk _ f) = f.map (quotient.mk I) := by rw [polynomial_quotient_equiv_quotient_polynomial, ring_equiv.symm_mk, ring_equiv.coe_mk, ideal.quotient.lift_mk, coe_eval₂_ring_hom, eval₂_eq_eval_map, ←polynomial.map_map, ←eval₂_eq_eval_map, polynomial.eval₂_C_X] @[simp] lemma polynomial_quotient_equiv_quotient_polynomial_map_mk (I : ideal R) (f : polynomial R) : I.polynomial_quotient_equiv_quotient_polynomial (f.map I^.quotient.mk) = quotient.mk _ f := begin apply (polynomial_quotient_equiv_quotient_polynomial I).symm.injective, rw [ring_equiv.symm_apply_apply, polynomial_quotient_equiv_quotient_polynomial_symm_mk], end /-- If `P` is a prime ideal of `R`, then `R[x]/(P)` is an integral domain. -/ lemma is_domain_map_C_quotient {P : ideal R} (H : is_prime P) : is_domain (polynomial R ⧸ (map C P : ideal (polynomial R))) := ring_equiv.is_domain (polynomial (R ⧸ P)) (polynomial_quotient_equiv_quotient_polynomial P).symm /-- If `P` is a prime ideal of `R`, then `P.R[x]` is a prime ideal of `R[x]`. -/ lemma is_prime_map_C_of_is_prime {P : ideal R} (H : is_prime P) : is_prime (map C P : ideal (polynomial R)) := (quotient.is_domain_iff_prime (map C P : ideal (polynomial R))).mp (is_domain_map_C_quotient H) /-- Given any ring `R` and an ideal `I` of `polynomial R`, we get a map `R → R[x] → R[x]/I`. If we let `R` be the image of `R` in `R[x]/I` then we also have a map `R[x] → R'[x]`. In particular we can map `I` across this map, to get `I'` and a new map `R' → R'[x] → R'[x]/I`. This theorem shows `I'` will not contain any non-zero constant polynomials -/ lemma eq_zero_of_polynomial_mem_map_range (I : ideal (polynomial R)) (x : ((quotient.mk I).comp C).range) (hx : C x ∈ (I.map (polynomial.map_ring_hom ((quotient.mk I).comp C).range_restrict))) : x = 0 := begin let i := ((quotient.mk I).comp C).range_restrict, have hi' : (polynomial.map_ring_hom i).ker ≤ I, { refine λ f hf, polynomial_mem_ideal_of_coeff_mem_ideal I f (λ n, _), rw [mem_comap, ← quotient.eq_zero_iff_mem, ← ring_hom.comp_apply], rw [ring_hom.mem_ker, coe_map_ring_hom] at hf, replace hf := congr_arg (λ (f : polynomial _), f.coeff n) hf, simp only [coeff_map, coeff_zero] at hf, rwa [subtype.ext_iff, ring_hom.coe_range_restrict] at hf }, obtain ⟨x, hx'⟩ := x, obtain ⟨y, rfl⟩ := (ring_hom.mem_range).1 hx', refine subtype.eq _, simp only [ring_hom.comp_apply, quotient.eq_zero_iff_mem, subring.coe_zero, subtype.val_eq_coe], suffices : C (i y) ∈ (I.map (polynomial.map_ring_hom i)), { obtain ⟨f, hf⟩ := mem_image_of_mem_map_of_surjective (polynomial.map_ring_hom i) (polynomial.map_surjective _ (((quotient.mk I).comp C).range_restrict_surjective)) this, refine sub_add_cancel (C y) f ▸ I.add_mem (hi' _ : (C y - f) ∈ I) hf.1, rw [ring_hom.mem_ker, ring_hom.map_sub, hf.2, sub_eq_zero, coe_map_ring_hom, map_C] }, exact hx, end /-- `polynomial R` is never a field for any ring `R`. -/ lemma polynomial_not_is_field : ¬ is_field (polynomial R) := begin by_contradiction hR, by_cases hR' : ∃ (x y : R), x ≠ y, { haveI : nontrivial R := let ⟨x, y, hxy⟩ := hR' in nontrivial_of_ne x y hxy, obtain ⟨p, hp⟩ := hR.mul_inv_cancel X_ne_zero, by_cases hp0 : p = 0, { replace hp := congr_arg degree hp, rw [hp0, mul_zero, degree_zero, degree_one] at hp, contradiction }, { have : p.degree < (X * p).degree := (mul_comm p X) ▸ degree_lt_degree_mul_X hp0, rw [congr_arg degree hp, degree_one, nat.with_bot.lt_zero_iff, degree_eq_bot] at this, exact hp0 this } }, { push_neg at hR', exact let ⟨x, y, hxy⟩ := hR.exists_pair_ne in hxy (polynomial.ext (λ n, hR' _ _)) } end /-- The only constant in a maximal ideal over a field is `0`. -/ lemma eq_zero_of_constant_mem_of_maximal (hR : is_field R) (I : ideal (polynomial R)) [hI : I.is_maximal] (x : R) (hx : C x ∈ I) : x = 0 := begin refine classical.by_contradiction (λ hx0, hI.ne_top ((eq_top_iff_one I).2 _)), obtain ⟨y, hy⟩ := hR.mul_inv_cancel hx0, convert I.smul_mem (C y) hx, rw [smul_eq_mul, ← C.map_mul, mul_comm y x, hy, ring_hom.map_one], end /-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/ def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) := { carrier := I.carrier, zero_mem' := I.zero_mem, add_mem' := λ _ _, I.add_mem, smul_mem' := λ c x H, by { rw [← C_mul'], exact I.mul_mem_left _ H } } variables {I : ideal (polynomial R)} theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl variables (I) /-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := degree_le R n ⊓ I.of_polynomial /-- Given an ideal `I` of `R[X]`, make the ideal in `R` of leading coefficients of polynomials in `I` with degree ≤ `n`. -/ def leading_coeff_nth (n : ℕ) : ideal R := (I.degree_le n).map $ lcoeff R n theorem mem_leading_coeff_nth (n : ℕ) (x) : x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x := begin simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf, mem_degree_le], split, { rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩, cases lt_or_eq_of_le hpdeg with hpdeg hpdeg, { refine ⟨0, I.zero_mem, bot_le, _⟩, rw [leading_coeff_zero, eq_comm], exact coeff_eq_zero_of_degree_lt hpdeg }, { refine ⟨p, hpI, le_of_eq hpdeg, _⟩, rw [leading_coeff, nat_degree, hpdeg], refl } }, { rintro ⟨p, hpI, hpdeg, rfl⟩, have : nat_degree p + (n - nat_degree p) = n, { exact add_tsub_cancel_of_le (nat_degree_le_of_degree_le hpdeg) }, refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right _ hpI⟩, _⟩, { apply le_trans (degree_mul_le _ _) _, apply le_trans (add_le_add (degree_le_nat_degree) (degree_X_pow_le _)) _, rw [← with_bot.coe_add, this], exact le_rfl }, { rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } } end theorem mem_leading_coeff_nth_zero (x) : x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I := (mem_leading_coeff_nth _ _ _).trans ⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff, nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg), ← eq_C_of_degree_le_zero hpdeg], λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩ theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) : I.leading_coeff_nth m ≤ I.leading_coeff_nth n := begin intros r hr, simp only [set_like.mem_coe, mem_leading_coeff_nth] at hr ⊢, rcases hr with ⟨p, hpI, hpdeg, rfl⟩, refine ⟨p * X ^ (n - m), I.mul_mem_right _ hpI, _, leading_coeff_mul_X_pow⟩, refine le_trans (degree_mul_le _ _) _, refine le_trans (add_le_add hpdeg (degree_X_pow_le _)) _, rw [← with_bot.coe_add, add_tsub_cancel_of_le H], exact le_rfl end /-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the leading coefficients in `I`. -/ def leading_coeff : ideal R := ⨆ n : ℕ, I.leading_coeff_nth n theorem mem_leading_coeff (x) : x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x := begin rw [leading_coeff, submodule.mem_supr_of_directed], simp only [mem_leading_coeff_nth], { split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ }, rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ }, intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _), I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩ end theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) : submodule.fg (I.degree_le n) := is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _ ⟨_, degree_le_eq_span_X_pow.symm⟩) _ end ideal namespace polynomial @[priority 100] instance {R : Type*} [comm_ring R] [is_domain R] [wf_dvd_monoid R] : wf_dvd_monoid (polynomial R) := { well_founded_dvd_not_unit := begin classical, refine rel_hom_class.well_founded (⟨λ (p : polynomial R), ((if p = 0 then ⊤ else ↑p.degree : with_top (with_bot ℕ)), p.leading_coeff), _⟩ : dvd_not_unit →r prod.lex (<) dvd_not_unit) (prod.lex_wf (with_top.well_founded_lt $ with_bot.well_founded_lt nat.lt_wf) ‹wf_dvd_monoid R›.well_founded_dvd_not_unit), rintros a b ⟨ane0, ⟨c, ⟨not_unit_c, rfl⟩⟩⟩, rw [polynomial.degree_mul, if_neg ane0], split_ifs with hac, { rw [hac, polynomial.leading_coeff_zero], apply prod.lex.left, exact lt_of_le_of_ne le_top with_top.coe_ne_top }, have cne0 : c ≠ 0 := right_ne_zero_of_mul hac, simp only [cne0, ane0, polynomial.leading_coeff_mul], by_cases hdeg : c.degree = 0, { simp only [hdeg, add_zero], refine prod.lex.right _ ⟨_, ⟨c.leading_coeff, (λ unit_c, not_unit_c _), rfl⟩⟩, { rwa [ne, polynomial.leading_coeff_eq_zero] }, rw [polynomial.is_unit_iff, polynomial.eq_C_of_degree_eq_zero hdeg], use [c.leading_coeff, unit_c], rw [polynomial.leading_coeff, polynomial.nat_degree_eq_of_degree_eq_some hdeg] }, { apply prod.lex.left, rw polynomial.degree_eq_nat_degree cne0 at *, rw [with_top.coe_lt_coe, polynomial.degree_eq_nat_degree ane0, ← with_bot.coe_add, with_bot.coe_lt_coe], exact lt_add_of_pos_right _ (nat.pos_of_ne_zero (λ h, hdeg (h.symm ▸ with_bot.coe_zero))) }, end } end polynomial /-- Hilbert basis theorem: a polynomial ring over a noetherian ring is a noetherian ring. -/ protected theorem polynomial.is_noetherian_ring [is_noetherian_ring R] : is_noetherian_ring (polynomial R) := is_noetherian_ring_iff.2 ⟨assume I : ideal (polynomial R), let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance)) (set.range I.leading_coeff_nth) ⟨_, ⟨0, rfl⟩⟩ in have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _, let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N) (λ h, HN ▸ I.leading_coeff_nth_mono h) (λ h x hx, classical.by_contradiction $ λ hxm, have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min (well_founded_submodule_gt _ _) _ _ _; exact ⟨k, rfl⟩, this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩), have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)), from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _) (λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ _ hf), ⟨s, le_antisymm (ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $ begin have : submodule.span (polynomial R) ↑s = ideal.span ↑s, by refl, rw this, intros p hp, generalize hn : p.nat_degree = k, induction k using nat.strong_induction_on with k ih generalizing p, cases le_or_lt k N, { subst k, refine hs2 ⟨polynomial.mem_degree_le.2 (le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ }, { have hp0 : p ≠ 0, { rintro rfl, cases hn, exact nat.not_lt_zero _ h }, have : (0 : R) ≠ 1, { intro h, apply hp0, ext i, refine (mul_one _).symm.trans _, rw [← h, mul_zero], refl }, haveI : nontrivial R := ⟨⟨0, 1, this⟩⟩, have : p.leading_coeff ∈ I.leading_coeff_nth N, { rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2 ⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) }, rw I.mem_leading_coeff_nth at this, rcases this with ⟨q, hq, hdq, hlqp⟩, have hq0 : q ≠ 0, { intro H, rw [← polynomial.leading_coeff_eq_zero] at H, rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H }, have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree, { rw [polynomial.degree_mul', polynomial.degree_X_pow], rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0], rw [← with_bot.coe_add, add_tsub_cancel_of_le, hn], { refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) }, rw [polynomial.leading_coeff_X_pow, mul_one], exact mt polynomial.leading_coeff_eq_zero.1 hq0 }, have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff, { rw [← hlqp, polynomial.leading_coeff_mul_X_pow] }, have := polynomial.degree_sub_lt h1 hp0 h2, rw [polynomial.degree_eq_nat_degree hp0] at this, rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)), refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _ _), { by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0, { rw hpq, exact ideal.zero_mem _ }, refine ih _ _ (I.sub_mem hp (I.mul_mem_right _ hq)) rfl, rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this }, exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ } end⟩⟩ attribute [instance] polynomial.is_noetherian_ring namespace polynomial theorem exists_irreducible_of_degree_pos {R : Type u} [comm_ring R] [is_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : 0 < f.degree) : ∃ g, irreducible g ∧ g ∣ f := wf_dvd_monoid.exists_irreducible_factor (λ huf, ne_of_gt hf $ degree_eq_zero_of_is_unit huf) (λ hf0, not_lt_of_lt hf $ hf0.symm ▸ (@degree_zero R _).symm ▸ with_bot.bot_lt_coe _) theorem exists_irreducible_of_nat_degree_pos {R : Type u} [comm_ring R] [is_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : 0 < f.nat_degree) : ∃ g, irreducible g ∧ g ∣ f := exists_irreducible_of_degree_pos $ by { contrapose! hf, exact nat_degree_le_of_degree_le hf } theorem exists_irreducible_of_nat_degree_ne_zero {R : Type u} [comm_ring R] [is_domain R] [wf_dvd_monoid R] {f : polynomial R} (hf : f.nat_degree ≠ 0) : ∃ g, irreducible g ∧ g ∣ f := exists_irreducible_of_nat_degree_pos $ nat.pos_of_ne_zero hf lemma linear_independent_powers_iff_aeval (f : M →ₗ[R] M) (v : M) : linear_independent R (λ n : ℕ, (f ^ n) v) ↔ ∀ (p : polynomial R), aeval f p v = 0 → p = 0 := begin rw linear_independent_iff, simp only [finsupp.total_apply, aeval_endomorphism, forall_iff_forall_finsupp, sum, support, coeff, ← zero_to_finsupp], exact iff.rfl, end lemma disjoint_ker_aeval_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : disjoint (aeval f p).ker (aeval f q).ker := begin intros v hv, rcases hpq with ⟨p', q', hpq'⟩, simpa [linear_map.mem_ker.1 (submodule.mem_inf.1 hv).1, linear_map.mem_ker.1 (submodule.mem_inf.1 hv).2] using congr_arg (λ p : polynomial R, aeval f p v) hpq'.symm, end lemma sup_aeval_range_eq_top_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : (aeval f p).range ⊔ (aeval f q).range = ⊤ := begin rw eq_top_iff, intros v hv, rw submodule.mem_sup, rcases hpq with ⟨p', q', hpq'⟩, use aeval f (p * p') v, use linear_map.mem_range.2 ⟨aeval f p' v, by simp only [linear_map.mul_apply, aeval_mul]⟩, use aeval f (q * q') v, use linear_map.mem_range.2 ⟨aeval f q' v, by simp only [linear_map.mul_apply, aeval_mul]⟩, simpa only [mul_comm p p', mul_comm q q', aeval_one, aeval_add] using congr_arg (λ p : polynomial R, aeval f p v) hpq' end lemma sup_ker_aeval_le_ker_aeval_mul {f : M →ₗ[R] M} {p q : polynomial R} : (aeval f p).ker ⊔ (aeval f q).ker ≤ (aeval f (p * q)).ker := begin intros v hv, rcases submodule.mem_sup.1 hv with ⟨x, hx, y, hy, hxy⟩, have h_eval_x : aeval f (p * q) x = 0, { rw [mul_comm, aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hx, linear_map.map_zero] }, have h_eval_y : aeval f (p * q) y = 0, { rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hy, linear_map.map_zero] }, rw [linear_map.mem_ker, ←hxy, linear_map.map_add, h_eval_x, h_eval_y, add_zero], end lemma sup_ker_aeval_eq_ker_aeval_mul_of_coprime (f : M →ₗ[R] M) {p q : polynomial R} (hpq : is_coprime p q) : (aeval f p).ker ⊔ (aeval f q).ker = (aeval f (p * q)).ker := begin apply le_antisymm sup_ker_aeval_le_ker_aeval_mul, intros v hv, rw submodule.mem_sup, rcases hpq with ⟨p', q', hpq'⟩, have h_eval₂_qpp' := calc aeval f (q * (p * p')) v = aeval f (p' * (p * q)) v : by rw [mul_comm, mul_assoc, mul_comm, mul_assoc, mul_comm q p] ... = 0 : by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero], have h_eval₂_pqq' := calc aeval f (p * (q * q')) v = aeval f (q' * (p * q)) v : by rw [←mul_assoc, mul_comm] ... = 0 : by rw [aeval_mul, linear_map.mul_apply, linear_map.mem_ker.1 hv, linear_map.map_zero], rw aeval_mul at h_eval₂_qpp' h_eval₂_pqq', refine ⟨aeval f (q * q') v, linear_map.mem_ker.1 h_eval₂_pqq', aeval f (p * p') v, linear_map.mem_ker.1 h_eval₂_qpp', _⟩, rw [add_comm, mul_comm p p', mul_comm q q'], simpa using congr_arg (λ p : polynomial R, aeval f p v) hpq' end end polynomial namespace mv_polynomial lemma is_noetherian_ring_fin_0 [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial (fin 0) R) := is_noetherian_ring_of_ring_equiv R ((mv_polynomial.is_empty_ring_equiv R pempty).symm.trans (rename_equiv R fin_zero_equiv'.symm).to_ring_equiv) theorem is_noetherian_ring_fin [is_noetherian_ring R] : ∀ {n : ℕ}, is_noetherian_ring (mv_polynomial (fin n) R) | 0 := is_noetherian_ring_fin_0 | (n+1) := @is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ _ _ (mv_polynomial.fin_succ_equiv _ n).to_ring_equiv.symm (@polynomial.is_noetherian_ring (mv_polynomial (fin n) R) _ (is_noetherian_ring_fin)) /-- The multivariate polynomial ring in finitely many variables over a noetherian ring is itself a noetherian ring. -/ instance is_noetherian_ring [fintype σ] [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial σ R) := @is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _ (rename_equiv R (fintype.equiv_fin σ).symm).to_ring_equiv is_noetherian_ring_fin lemma is_domain_fin_zero (R : Type u) [comm_ring R] [is_domain R] : is_domain (mv_polynomial (fin 0) R) := ring_equiv.is_domain R ((rename_equiv R fin_zero_equiv').to_ring_equiv.trans (mv_polynomial.is_empty_ring_equiv R pempty)) /-- Auxiliary lemma: Multivariate polynomials over an integral domain with variables indexed by `fin n` form an integral domain. This fact is proven inductively, and then used to prove the general case without any finiteness hypotheses. See `mv_polynomial.is_domain` for the general case. -/ lemma is_domain_fin (R : Type u) [comm_ring R] [is_domain R] : ∀ (n : ℕ), is_domain (mv_polynomial (fin n) R) | 0 := is_domain_fin_zero R | (n+1) := begin haveI := is_domain_fin n, exact ring_equiv.is_domain (polynomial (mv_polynomial (fin n) R)) (mv_polynomial.fin_succ_equiv _ n).to_ring_equiv end /-- Auxiliary definition: Multivariate polynomials in finitely many variables over an integral domain form an integral domain. This fact is proven by transport of structure from the `mv_polynomial.is_domain_fin`, and then used to prove the general case without finiteness hypotheses. See `mv_polynomial.is_domain` for the general case. -/ lemma is_domain_fintype (R : Type u) (σ : Type v) [comm_ring R] [fintype σ] [is_domain R] : is_domain (mv_polynomial σ R) := @ring_equiv.is_domain _ (mv_polynomial (fin $ fintype.card σ) R) _ _ (mv_polynomial.is_domain_fin _ _) (rename_equiv R (fintype.equiv_fin σ)).to_ring_equiv protected theorem eq_zero_or_eq_zero_of_mul_eq_zero {R : Type u} [comm_ring R] [is_domain R] {σ : Type v} (p q : mv_polynomial σ R) (h : p * q = 0) : p = 0 ∨ q = 0 := begin obtain ⟨s, p, rfl⟩ := exists_finset_rename p, obtain ⟨t, q, rfl⟩ := exists_finset_rename q, have : rename (subtype.map id (finset.subset_union_left s t) : {x // x ∈ s} → {x // x ∈ s ∪ t}) p * rename (subtype.map id (finset.subset_union_right s t) : {x // x ∈ t} → {x // x ∈ s ∪ t}) q = 0, { apply rename_injective _ subtype.val_injective, simpa using h }, letI := mv_polynomial.is_domain_fintype R {x // x ∈ (s ∪ t)}, rw mul_eq_zero at this, cases this; [left, right], all_goals { simpa using congr_arg (rename subtype.val) this } end /-- The multivariate polynomial ring over an integral domain is an integral domain. -/ instance {R : Type u} {σ : Type v} [comm_ring R] [is_domain R] : is_domain (mv_polynomial σ R) := { eq_zero_or_eq_zero_of_mul_eq_zero := mv_polynomial.eq_zero_or_eq_zero_of_mul_eq_zero, exists_pair_ne := ⟨0, 1, λ H, begin have : eval₂ (ring_hom.id _) (λ s, (0:R)) (0 : mv_polynomial σ R) = eval₂ (ring_hom.id _) (λ s, (0:R)) (1 : mv_polynomial σ R), { congr, exact H }, simpa, end⟩, .. (by apply_instance : comm_ring (mv_polynomial σ R)) } lemma map_mv_polynomial_eq_eval₂ {S : Type*} [comm_ring S] [fintype σ] (ϕ : mv_polynomial σ R →+* S) (p : mv_polynomial σ R) : ϕ p = mv_polynomial.eval₂ (ϕ.comp mv_polynomial.C) (λ s, ϕ (mv_polynomial.X s)) p := begin refine trans (congr_arg ϕ (mv_polynomial.as_sum p)) _, rw [mv_polynomial.eval₂_eq', ϕ.map_sum], congr, ext, simp only [monomial_eq, ϕ.map_pow, ϕ.map_prod, ϕ.comp_apply, ϕ.map_mul, finsupp.prod_pow], end lemma quotient_map_C_eq_zero {I : ideal R} {i : R} (hi : i ∈ I) : (ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R))).comp C i = 0 := begin simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient.eq_zero_iff_mem], exact ideal.mem_map_of_mem _ hi end /-- If every coefficient of a polynomial is in an ideal `I`, then so is the polynomial itself, multivariate version. -/ lemma mem_ideal_of_coeff_mem_ideal (I : ideal (mv_polynomial σ R)) (p : mv_polynomial σ R) (hcoe : ∀ (m : σ →₀ ℕ), p.coeff m ∈ I.comap C) : p ∈ I := begin rw as_sum p, suffices : ∀ m ∈ p.support, monomial m (mv_polynomial.coeff m p) ∈ I, { exact submodule.sum_mem I this }, intros m hm, rw [← mul_one (coeff m p), ← C_mul_monomial], suffices : C (coeff m p) ∈ I, { exact I.mul_mem_right (monomial m 1) this }, simpa [ideal.mem_comap] using hcoe m end /-- The push-forward of an ideal `I` of `R` to `mv_polynomial σ R` via inclusion is exactly the set of polynomials whose coefficients are in `I` -/ theorem mem_map_C_iff {I : ideal R} {f : mv_polynomial σ R} : f ∈ (ideal.map C I : ideal (mv_polynomial σ R)) ↔ ∀ (m : σ →₀ ℕ), f.coeff m ∈ I := begin split, { intros hf, apply submodule.span_induction hf, { intros f hf n, cases (set.mem_image _ _ _).mp hf with x hx, rw [← hx.right, coeff_C], by_cases (n = 0), { simpa [h] using hx.left }, { simp [ne.symm h] } }, { simp }, { exact λ f g hf hg n, by simp [I.add_mem (hf n) (hg n)] }, { refine λ f g hg n, _, rw [smul_eq_mul, coeff_mul], exact I.sum_mem (λ c hc, I.smul_mem (f.coeff c.fst) (hg c.snd)) } }, { intros hf, rw as_sum f, suffices : ∀ m ∈ f.support, monomial m (coeff m f) ∈ (ideal.map C I : ideal (mv_polynomial σ R)), { exact submodule.sum_mem _ this }, intros m hm, rw [← mul_one (coeff m f), ← C_mul_monomial], suffices : C (coeff m f) ∈ (ideal.map C I : ideal (mv_polynomial σ R)), { exact ideal.mul_mem_right _ _ this }, apply ideal.mem_map_of_mem _, exact hf m } end lemma ker_map (f : R →+* S) : (map f : mv_polynomial σ R →+* mv_polynomial σ S).ker = f.ker.map C := begin ext, rw [mv_polynomial.mem_map_C_iff, ring_hom.mem_ker, mv_polynomial.ext_iff], simp_rw [coeff_map, coeff_zero, ring_hom.mem_ker], end lemma eval₂_C_mk_eq_zero {I : ideal R} {a : mv_polynomial σ R} (ha : a ∈ (ideal.map C I : ideal (mv_polynomial σ R))) : eval₂_hom (C.comp (ideal.quotient.mk I)) X a = 0 := begin rw as_sum a, rw [coe_eval₂_hom, eval₂_sum], refine finset.sum_eq_zero (λ n hn, _), simp only [eval₂_monomial, function.comp_app, ring_hom.coe_comp], refine mul_eq_zero_of_left _ _, suffices : coeff n a ∈ I, { rw [← @ideal.mk_ker R _ I, ring_hom.mem_ker] at this, simp only [this, C_0] }, exact mem_map_C_iff.1 ha n end /-- If `I` is an ideal of `R`, then the ring `mv_polynomial σ I.quotient` is isomorphic as an `R`-algebra to the quotient of `mv_polynomial σ R` by the ideal generated by `I`. -/ def quotient_equiv_quotient_mv_polynomial (I : ideal R) : mv_polynomial σ (R ⧸ I) ≃ₐ[R] mv_polynomial σ R ⧸ (ideal.map C I : ideal (mv_polynomial σ R)) := { to_fun := eval₂_hom (ideal.quotient.lift I ((ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R))).comp C) (λ i hi, quotient_map_C_eq_zero hi)) (λ i, ideal.quotient.mk (ideal.map C I : ideal (mv_polynomial σ R)) (X i)), inv_fun := ideal.quotient.lift (ideal.map C I : ideal (mv_polynomial σ R)) (eval₂_hom (C.comp (ideal.quotient.mk I)) X) (λ a ha, eval₂_C_mk_eq_zero ha), map_mul' := ring_hom.map_mul _, map_add' := ring_hom.map_add _, left_inv := begin intro f, apply induction_on f, { rintro ⟨r⟩, rw [coe_eval₂_hom, eval₂_C], simp only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, bind₂_C_right, ring_hom.coe_comp] }, { simp_intros p q hp hq only [ring_hom.map_add, mv_polynomial.coe_eval₂_hom, coe_eval₂_hom, mv_polynomial.eval₂_add, mv_polynomial.eval₂_hom_eq_bind₂, eval₂_hom_eq_bind₂], rw [hp, hq] }, { simp_intros p i hp only [eval₂_hom_eq_bind₂, coe_eval₂_hom], simp only [hp, eval₂_hom_eq_bind₂, coe_eval₂_hom, ideal.quotient.lift_mk, bind₂_X_right, eval₂_mul, ring_hom.map_mul, eval₂_X] } end, right_inv := begin rintro ⟨f⟩, apply induction_on f, { intros r, simp only [submodule.quotient.quot_mk_eq_mk, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, ring_hom.coe_comp, eval₂_hom_C] }, { simp_intros p q hp hq only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, eval₂_add, ring_hom.map_add, coe_eval₂_hom, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk], rw [hp, hq] }, { simp_intros p i hp only [eval₂_hom_eq_bind₂, submodule.quotient.quot_mk_eq_mk, coe_eval₂_hom, ideal.quotient.lift_mk, ideal.quotient.mk_eq_mk, bind₂_X_right, eval₂_mul, ring_hom.map_mul, eval₂_X], simp only [hp] } end, commutes' := λ r, eval₂_hom_C _ _ (ideal.quotient.mk I r) } end mv_polynomial namespace polynomial open unique_factorization_monoid variables {D : Type u} [comm_ring D] [is_domain D] [unique_factorization_monoid D] @[priority 100] instance unique_factorization_monoid : unique_factorization_monoid (polynomial D) := begin haveI := arbitrary (normalization_monoid D), haveI := to_normalized_gcd_monoid D, exact ufm_of_gcd_of_wf_dvd_monoid end end polynomial
87f92aa4315a869c01f62c2cf9b8022237c8ab09
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Parser.lean
57c34a6279b1df03fd9aa8a8598a1271b2b8a7b3
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,005
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.Basic import Lean.Parser.Level import Lean.Parser.Term import Lean.Parser.Tactic import Lean.Parser.Command import Lean.Parser.Module import Lean.Parser.Syntax import Lean.Parser.Do namespace Lean namespace PrettyPrinter namespace Parenthesizer -- Close the mutual recursion loop; see corresponding `[extern]` in the parenthesizer. @[export lean_mk_antiquot_parenthesizer] def mkAntiquot.parenthesizer (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parenthesizer := Parser.mkAntiquot.parenthesizer name kind anonymous -- The parenthesizer auto-generated these instances correctly, but tagged them with the wrong kind, since the actual kind -- (e.g. `ident`) is not equal to the parser name `Lean.Parser.Term.ident`. @[builtinParenthesizer ident] def ident.parenthesizer : Parenthesizer := Parser.Term.ident.parenthesizer @[builtinParenthesizer numLit] def numLit.parenthesizer : Parenthesizer := Parser.Term.num.parenthesizer @[builtinParenthesizer charLit] def charLit.parenthesizer : Parenthesizer := Parser.Term.char.parenthesizer @[builtinParenthesizer strLit] def strLit.parenthesizer : Parenthesizer := Parser.Term.str.parenthesizer end Parenthesizer namespace Formatter @[export lean_mk_antiquot_formatter] def mkAntiquot.formatter (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Formatter := Parser.mkAntiquot.formatter name kind anonymous @[builtinFormatter ident] def ident.formatter : Formatter := Parser.Term.ident.formatter @[builtinFormatter numLit] def numLit.formatter : Formatter := Parser.Term.num.formatter @[builtinFormatter charLit] def charLit.formatter : Formatter := Parser.Term.char.formatter @[builtinFormatter strLit] def strLit.formatter : Formatter := Parser.Term.str.formatter end Formatter end PrettyPrinter end Lean
483d104fb07e480a2d68e49ef67af462180991be
12dabd587ce2621d9a4eff9f16e354d02e206c8e
/world10/level10.lean
ce81e0b833a292d04a3c94cf92e92c982c55d57b
[]
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
91
lean
lemma le_succ_self (a : mynat) : a ≤ succ a := begin apply le_succ, exact le_refl a, end
6e531689d94e0f60ad767509aef43d4047a6a797
02fbe05a45fda5abde7583464416db4366eedfbf
/library/init/control/lawful.lean
88a8c082414de44da6ef8c75854755ed99d49d08
[ "Apache-2.0" ]
permissive
jasonrute/lean
cc12807e11f9ac6b01b8951a8bfb9c2eb35a0154
4be962c167ca442a0ec5e84472d7ff9f5302788f
refs/heads/master
1,672,036,664,637
1,601,642,826,000
1,601,642,826,000
260,777,966
0
0
Apache-2.0
1,588,454,819,000
1,588,454,818,000
null
UTF-8
Lean
false
false
11,177
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ prelude import init.control.monad init.meta.interactive import init.control.state init.control.except init.control.reader init.control.option universes u v open function open tactic meta def control_laws_tac := whnf_target >> intros >> to_expr ``(rfl) >>= exact class is_lawful_functor (f : Type u → Type v) [functor f] : Prop := (map_const_eq : ∀ {α β : Type u}, ((<$) : α → f β → f α) = (<$>) ∘ const β . control_laws_tac) -- `functor` is indeed a categorical functor (id_map : Π {α : Type u} (x : f α), id <$> x = x) (comp_map : Π {α β γ : Type u} (g : α → β) (h : β → γ) (x : f α), (h ∘ g) <$> x = h <$> g <$> x) export is_lawful_functor (map_const_eq id_map comp_map) attribute [simp] id_map -- `comp_map` does not make a good simp lemma class is_lawful_applicative (f : Type u → Type v) [applicative f] extends is_lawful_functor f : Prop := (seq_left_eq : ∀ {α β : Type u} (a : f α) (b : f β), a <* b = const β <$> a <*> b . control_laws_tac) (seq_right_eq : ∀ {α β : Type u} (a : f α) (b : f β), a *> b = const α id <$> a <*> b . control_laws_tac) -- applicative laws (pure_seq_eq_map : ∀ {α β : Type u} (g : α → β) (x : f α), pure g <*> x = g <$> x) (map_pure : ∀ {α β : Type u} (g : α → β) (x : α), g <$> (pure x : f α) = pure (g x)) (seq_pure : ∀ {α β : Type u} (g : f (α → β)) (x : α), g <*> pure x = (λ g : α → β, g x) <$> g) (seq_assoc : ∀ {α β γ : Type u} (x : f α) (g : f (α → β)) (h : f (β → γ)), h <*> (g <*> x) = (@comp α β γ <$> h) <*> g <*> x) -- default functor law (comp_map := begin intros; simp [(pure_seq_eq_map _ _).symm, seq_assoc, map_pure, seq_pure] end) export is_lawful_applicative (seq_left_eq seq_right_eq pure_seq_eq_map map_pure seq_pure seq_assoc) attribute [simp] map_pure seq_pure -- applicative "law" derivable from other laws @[simp] theorem pure_id_seq {α : Type u} {f : Type u → Type v} [applicative f] [is_lawful_applicative f] (x : f α) : pure id <*> x = x := by simp [pure_seq_eq_map] class is_lawful_monad (m : Type u → Type v) [monad m] extends is_lawful_applicative m : Prop := (bind_pure_comp_eq_map : ∀ {α β : Type u} (f : α → β) (x : m α), x >>= pure ∘ f = f <$> x . control_laws_tac) (bind_map_eq_seq : ∀ {α β : Type u} (f : m (α → β)) (x : m α), f >>= (<$> x) = f <*> x . control_laws_tac) -- monad laws (pure_bind : ∀ {α β : Type u} (x : α) (f : α → m β), pure x >>= f = f x) (bind_assoc : ∀ {α β γ : Type u} (x : m α) (f : α → m β) (g : β → m γ), x >>= f >>= g = x >>= λ x, f x >>= g) (pure_seq_eq_map := by intros; rw ←bind_map_eq_seq; simp [pure_bind]) (map_pure := by intros; rw ←bind_pure_comp_eq_map; simp [pure_bind]) (seq_pure := by intros; rw ←bind_map_eq_seq; simp [map_pure, bind_pure_comp_eq_map]) (seq_assoc := by intros; simp [(bind_pure_comp_eq_map _ _).symm, (bind_map_eq_seq _ _).symm, bind_assoc, pure_bind]) export is_lawful_monad (bind_pure_comp_eq_map bind_map_eq_seq pure_bind bind_assoc) attribute [simp] pure_bind -- monad "law" derivable from other laws @[simp] theorem bind_pure {α : Type u} {m : Type u → Type v} [monad m] [is_lawful_monad m] (x : m α) : x >>= pure = x := show x >>= pure ∘ id = x, by rw bind_pure_comp_eq_map; simp [id_map] lemma bind_ext_congr {α β} {m : Type u → Type v} [has_bind m] {x : m α} {f g : α → m β} : (∀ a, f a = g a) → x >>= f = x >>= g := λ h, by simp [show f = g, from funext h] lemma map_ext_congr {α β} {m : Type u → Type v} [functor m] {x : m α} {f g : α → β} : (∀ a, f a = g a) → (f <$> x : m β) = g <$> x := λ h, by simp [show f = g, from funext h] -- instances of previously defined monads namespace id variables {α β : Type} @[simp] lemma map_eq (x : id α) (f : α → β) : f <$> x = f x := rfl @[simp] lemma bind_eq (x : id α) (f : α → id β) : x >>= f = f x := rfl @[simp] lemma pure_eq (a : α) : (pure a : id α) = a := rfl end id instance : is_lawful_monad id := by refine { .. }; intros; refl namespace state_t section variable {σ : Type u} variable {m : Type u → Type v} variables {α β : Type u} variables (x : state_t σ m α) (st : σ) lemma ext {x x' : state_t σ m α} (h : ∀ st, x.run st = x'.run st) : x = x' := by cases x; cases x'; simp [show x = x', from funext h] variable [monad m] @[simp] lemma run_pure (a) : (pure a : state_t σ m α).run st = pure (a, st) := rfl @[simp] lemma run_bind (f : α → state_t σ m β) : (x >>= f).run st = x.run st >>= λ p, (f p.1).run p.2 := by apply bind_ext_congr; intro a; cases a; simp [state_t.bind, state_t.run] @[simp] lemma run_map (f : α → β) [is_lawful_monad m] : (f <$> x).run st = (λ p : α × σ, (f (prod.fst p), prod.snd p)) <$> x.run st := begin rw ← bind_pure_comp_eq_map _ (x.run st), change (x >>= pure ∘ f).run st = _, simp end @[simp] lemma run_monad_lift {n} [has_monad_lift_t n m] (x : n α) : (monad_lift x : state_t σ m α).run st = do a ← (monad_lift x : m α), pure (a, st) := rfl @[simp] lemma run_monad_map {m' n n'} [monad m'] [monad_functor_t n n' m m'] (f : ∀ {α}, n α → n' α) : (monad_map @f x : state_t σ m' α).run st = monad_map @f (x.run st) := rfl @[simp] lemma run_adapt {σ' σ''} (st : σ) (split : σ → σ' × σ'') (join : σ' → σ'' → σ) (x : state_t σ' m α) : (state_t.adapt split join x : state_t σ m α).run st = do let (st, ctx) := split st, (a, st') ← x.run st, pure (a, join st' ctx) := by delta state_t.adapt; refl @[simp] lemma run_get : (state_t.get : state_t σ m σ).run st = pure (st, st) := rfl @[simp] lemma run_put (st') : (state_t.put st' : state_t σ m _).run st = pure (punit.star, st') := rfl end end state_t instance (m : Type u → Type v) [monad m] [is_lawful_monad m] (σ : Type u) : is_lawful_monad (state_t σ m) := { id_map := by intros; apply state_t.ext; intro; simp; erw id_map, pure_bind := by intros; apply state_t.ext; simp, bind_assoc := by intros; apply state_t.ext; simp [bind_assoc] } namespace except_t variables {α β ε : Type u} {m : Type u → Type v} (x : except_t ε m α) lemma ext {x x' : except_t ε m α} (h : x.run = x'.run) : x = x' := by cases x; cases x'; simp * at * variable [monad m] @[simp] lemma run_pure (a) : (pure a : except_t ε m α).run = pure (@except.ok ε α a) := rfl @[simp] lemma run_bind (f : α → except_t ε m β) : (x >>= f).run = x.run >>= except_t.bind_cont f := rfl @[simp] lemma run_map (f : α → β) [is_lawful_monad m] : (f <$> x).run = except.map f <$> x.run := begin rw ← bind_pure_comp_eq_map _ x.run, change x.run >>= except_t.bind_cont (pure ∘ f) = _, apply bind_ext_congr, intro a; cases a; simp [except_t.bind_cont, except.map] end @[simp] lemma run_monad_lift {n} [has_monad_lift_t n m] (x : n α) : (monad_lift x : except_t ε m α).run = except.ok <$> (monad_lift x : m α) := rfl @[simp] lemma run_monad_map {m' n n'} [monad m'] [monad_functor_t n n' m m'] (f : ∀ {α}, n α → n' α) : (monad_map @f x : except_t ε m' α).run = monad_map @f x.run := rfl end except_t instance (m : Type u → Type v) [monad m] [is_lawful_monad m] (ε : Type u) : is_lawful_monad (except_t ε m) := { id_map := begin intros, apply except_t.ext, simp only [except_t.run_map], rw [map_ext_congr, id_map], intro a, cases a; refl end, bind_pure_comp_eq_map := begin intros, apply except_t.ext, simp only [except_t.run_map, except_t.run_bind], rw [bind_ext_congr, bind_pure_comp_eq_map], intro a, cases a; refl end, bind_assoc := begin intros, apply except_t.ext, simp only [except_t.run_bind, bind_assoc], rw [bind_ext_congr], intro a, cases a; simp [except_t.bind_cont] end, pure_bind := by intros; apply except_t.ext; simp [except_t.bind_cont] } namespace reader_t section variable {ρ : Type u} variable {m : Type u → Type v} variables {α β : Type u} variables (x : reader_t ρ m α) (r : ρ) lemma ext {x x' : reader_t ρ m α} (h : ∀ r, x.run r = x'.run r) : x = x' := by cases x; cases x'; simp [show x = x', from funext h] variable [monad m] @[simp] lemma run_pure (a) : (pure a : reader_t ρ m α).run r = pure a := rfl @[simp] lemma run_bind (f : α → reader_t ρ m β) : (x >>= f).run r = x.run r >>= λ a, (f a).run r := rfl @[simp] lemma run_map (f : α → β) [is_lawful_monad m] : (f <$> x).run r = f <$> x.run r := by rw ← bind_pure_comp_eq_map _ (x.run r); refl @[simp] lemma run_monad_lift {n} [has_monad_lift_t n m] (x : n α) : (monad_lift x : reader_t ρ m α).run r = (monad_lift x : m α) := rfl @[simp] lemma run_monad_map {m' n n'} [monad m'] [monad_functor_t n n' m m'] (f : ∀ {α}, n α → n' α) : (monad_map @f x : reader_t ρ m' α).run r = monad_map @f (x.run r) := rfl @[simp] lemma run_read : (reader_t.read : reader_t ρ m ρ).run r = pure r := rfl end end reader_t instance (ρ : Type u) (m : Type u → Type v) [monad m] [is_lawful_monad m] : is_lawful_monad (reader_t ρ m) := { id_map := by intros; apply reader_t.ext; intro; simp, pure_bind := by intros; apply reader_t.ext; intro; simp, bind_assoc := by intros; apply reader_t.ext; intro; simp [bind_assoc] } namespace option_t variables {α β : Type u} {m : Type u → Type v} (x : option_t m α) lemma ext {x x' : option_t m α} (h : x.run = x'.run) : x = x' := by cases x; cases x'; simp * at * variable [monad m] @[simp] lemma run_pure (a) : (pure a : option_t m α).run = pure (some a) := rfl @[simp] lemma run_bind (f : α → option_t m β) : (x >>= f).run = x.run >>= option_t.bind_cont f := rfl @[simp] lemma run_map (f : α → β) [is_lawful_monad m] : (f <$> x).run = option.map f <$> x.run := begin rw ← bind_pure_comp_eq_map _ x.run, change x.run >>= option_t.bind_cont (pure ∘ f) = _, apply bind_ext_congr, intro a; cases a; simp [option_t.bind_cont, option.map, option.bind] end @[simp] lemma run_monad_lift {n} [has_monad_lift_t n m] (x : n α) : (monad_lift x : option_t m α).run = some <$> (monad_lift x : m α) := rfl @[simp] lemma run_monad_map {m' n n'} [monad m'] [monad_functor_t n n' m m'] (f : ∀ {α}, n α → n' α) : (monad_map @f x : option_t m' α).run = monad_map @f x.run := rfl end option_t instance (m : Type u → Type v) [monad m] [is_lawful_monad m] : is_lawful_monad (option_t m) := { id_map := begin intros, apply option_t.ext, simp only [option_t.run_map], rw [map_ext_congr, id_map], intro a, cases a; refl end, bind_assoc := begin intros, apply option_t.ext, simp only [option_t.run_bind, bind_assoc], rw [bind_ext_congr], intro a, cases a; simp [option_t.bind_cont] end, pure_bind := by intros; apply option_t.ext; simp [option_t.bind_cont] }
d35ce5a8d4495b91d2a87d1f248a1bce84b2c622
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/analysis/calculus/fderiv_measurable.lean
192e6c4a9a95581a0905ea4e34ef09e7def7fa55
[ "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
41,086
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Yury Kudryashov -/ import analysis.calculus.deriv import measure_theory.constructions.borel_space import measure_theory.function.strongly_measurable import tactic.ring_exp /-! # Derivative is measurable In this file we prove that the derivative of any function with complete codomain is a measurable function. Namely, we prove: * `measurable_set_of_differentiable_at`: the set `{x | differentiable_at 𝕜 f x}` is measurable; * `measurable_fderiv`: the function `fderiv 𝕜 f` is measurable; * `measurable_fderiv_apply_const`: for a fixed vector `y`, the function `λ x, fderiv 𝕜 f x y` is measurable; * `measurable_deriv`: the function `deriv f` is measurable (for `f : 𝕜 → F`). We also show the same results for the right derivative on the real line (see `measurable_deriv_within_Ici` and ``measurable_deriv_within_Ioi`), following the same proof strategy. ## Implementation We give a proof that avoids second-countability issues, by expressing the differentiability set as a function of open sets in the following way. Define `A (L, r, ε)` to be the set of points where, on a ball of radius roughly `r` around `x`, the function is uniformly approximated by the linear map `L`, up to `ε r`. It is an open set. Let also `B (L, r, s, ε) = A (L, r, ε) ∩ A (L, s, ε)`: we require that at two possibly different scales `r` and `s`, the function is well approximated by the linear map `L`. It is also open. We claim that the differentiability set of `f` is exactly `D = ⋂ ε > 0, ⋃ δ > 0, ⋂ r, s < δ, ⋃ L, B (L, r, s, ε)`. In other words, for any `ε > 0`, we require that there is a size `δ` such that, for any two scales below this size, the function is well approximated by a linear map, common to the two scales. The set `⋃ L, B (L, r, s, ε)` is open, as a union of open sets. Converting the intersections and unions to countable ones (using real numbers of the form `2 ^ (-n)`), it follows that the differentiability set is measurable. To prove the claim, there are two inclusions. One is trivial: if the function is differentiable at `x`, then `x` belongs to `D` (just take `L` to be the derivative, and use that the differentiability exactly says that the map is well approximated by `L`). This is proved in `mem_A_of_differentiable` and `differentiable_set_subset_D`. For the other direction, the difficulty is that `L` in the union may depend on `ε, r, s`. The key point is that, in fact, it doesn't depend too much on them. First, if `x` belongs both to `A (L, r, ε)` and `A (L', r, ε)`, then `L` and `L'` have to be close on a shell, and thus `∥L - L'∥` is bounded by `ε` (see `norm_sub_le_of_mem_A`). Assume now `x ∈ D`. If one has two maps `L` and `L'` such that `x` belongs to `A (L, r, ε)` and to `A (L', r', ε')`, one deduces that `L` is close to `L'` by arguing as follows. Consider another scale `s` smaller than `r` and `r'`. Take a linear map `L₁` that approximates `f` around `x` both at scales `r` and `s` w.r.t. `ε` (it exists as `x` belongs to `D`). Take also `L₂` that approximates `f` around `x` both at scales `r'` and `s` w.r.t. `ε'`. Then `L₁` is close to `L` (as they are close on a shell of radius `r`), and `L₂` is close to `L₁` (as they are close on a shell of radius `s`), and `L'` is close to `L₂` (as they are close on a shell of radius `r'`). It follows that `L` is close to `L'`, as we claimed. It follows that the different approximating linear maps that show up form a Cauchy sequence when `ε` tends to `0`. When the target space is complete, this sequence converges, to a limit `f'`. With the same kind of arguments, one checks that `f` is differentiable with derivative `f'`. To show that the derivative itself is measurable, add in the definition of `B` and `D` a set `K` of continuous linear maps to which `L` should belong. Then, when `K` is complete, the set `D K` is exactly the set of points where `f` is differentiable with a derivative in `K`. ## Tags derivative, measurable function, Borel σ-algebra -/ noncomputable theory open set metric asymptotics filter continuous_linear_map open topological_space (second_countable_topology) measure_theory open_locale topological_space namespace continuous_linear_map variables {𝕜 E F : Type*} [nontrivially_normed_field 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] [normed_add_comm_group F] [normed_space 𝕜 F] lemma measurable_apply₂ [measurable_space E] [opens_measurable_space E] [second_countable_topology E] [second_countable_topology (E →L[𝕜] F)] [measurable_space F] [borel_space F] : measurable (λ p : (E →L[𝕜] F) × E, p.1 p.2) := is_bounded_bilinear_map_apply.continuous.measurable end continuous_linear_map section fderiv variables {𝕜 : Type*} [nontrivially_normed_field 𝕜] variables {E : Type*} [normed_add_comm_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_add_comm_group F] [normed_space 𝕜 F] variables {f : E → F} (K : set (E →L[𝕜] F)) namespace fderiv_measurable_aux /-- The set `A f L r ε` is the set of points `x` around which the function `f` is well approximated at scale `r` by the linear map `L`, up to an error `ε`. We tweak the definition to make sure that this is an open set.-/ def A (f : E → F) (L : E →L[𝕜] F) (r ε : ℝ) : set E := {x | ∃ r' ∈ Ioc (r/2) r, ∀ y z ∈ ball x r', ∥f z - f y - L (z-y)∥ ≤ ε * r} /-- The set `B f K r s ε` is the set of points `x` around which there exists a continuous linear map `L` belonging to `K` (a given set of continuous linear maps) that approximates well the function `f` (up to an error `ε`), simultaneously at scales `r` and `s`. -/ def B (f : E → F) (K : set (E →L[𝕜] F)) (r s ε : ℝ) : set E := ⋃ (L ∈ K), (A f L r ε) ∩ (A f L s ε) /-- The set `D f K` is a complicated set constructed using countable intersections and unions. Its main use is that, when `K` is complete, it is exactly the set of points where `f` is differentiable, with a derivative in `K`. -/ def D (f : E → F) (K : set (E →L[𝕜] F)) : set E := ⋂ (e : ℕ), ⋃ (n : ℕ), ⋂ (p ≥ n) (q ≥ n), B f K ((1/2) ^ p) ((1/2) ^ q) ((1/2) ^ e) lemma is_open_A (L : E →L[𝕜] F) (r ε : ℝ) : is_open (A f L r ε) := begin rw metric.is_open_iff, rintros x ⟨r', r'_mem, hr'⟩, obtain ⟨s, s_gt, s_lt⟩ : ∃ (s : ℝ), r / 2 < s ∧ s < r' := exists_between r'_mem.1, have : s ∈ Ioc (r/2) r := ⟨s_gt, le_of_lt (s_lt.trans_le r'_mem.2)⟩, refine ⟨r' - s, by linarith, λ x' hx', ⟨s, this, _⟩⟩, have B : ball x' s ⊆ ball x r' := ball_subset (le_of_lt hx'), assume y hy z hz, exact hr' y (B hy) z (B hz) end lemma is_open_B {K : set (E →L[𝕜] F)} {r s ε : ℝ} : is_open (B f K r s ε) := by simp [B, is_open_Union, is_open.inter, is_open_A] lemma A_mono (L : E →L[𝕜] F) (r : ℝ) {ε δ : ℝ} (h : ε ≤ δ) : A f L r ε ⊆ A f L r δ := begin rintros x ⟨r', r'r, hr'⟩, refine ⟨r', r'r, λ y hy z hz, (hr' y hy z hz).trans (mul_le_mul_of_nonneg_right h _)⟩, linarith [mem_ball.1 hy, r'r.2, @dist_nonneg _ _ y x], end lemma le_of_mem_A {r ε : ℝ} {L : E →L[𝕜] F} {x : E} (hx : x ∈ A f L r ε) {y z : E} (hy : y ∈ closed_ball x (r/2)) (hz : z ∈ closed_ball x (r/2)) : ∥f z - f y - L (z-y)∥ ≤ ε * r := begin rcases hx with ⟨r', r'mem, hr'⟩, exact hr' _ ((mem_closed_ball.1 hy).trans_lt r'mem.1) _ ((mem_closed_ball.1 hz).trans_lt r'mem.1) end lemma mem_A_of_differentiable {ε : ℝ} (hε : 0 < ε) {x : E} (hx : differentiable_at 𝕜 f x) : ∃ R > 0, ∀ r ∈ Ioo (0 : ℝ) R, x ∈ A f (fderiv 𝕜 f x) r ε := begin have := hx.has_fderiv_at, simp only [has_fderiv_at, has_fderiv_at_filter, is_o_iff] at this, rcases eventually_nhds_iff_ball.1 (this (half_pos hε)) with ⟨R, R_pos, hR⟩, refine ⟨R, R_pos, λ r hr, _⟩, have : r ∈ Ioc (r/2) r := ⟨half_lt_self hr.1, le_rfl⟩, refine ⟨r, this, λ y hy z hz, _⟩, calc ∥f z - f y - (fderiv 𝕜 f x) (z - y)∥ = ∥(f z - f x - (fderiv 𝕜 f x) (z - x)) - (f y - f x - (fderiv 𝕜 f x) (y - x))∥ : by { congr' 1, simp only [continuous_linear_map.map_sub], abel } ... ≤ ∥(f z - f x - (fderiv 𝕜 f x) (z - x))∥ + ∥f y - f x - (fderiv 𝕜 f x) (y - x)∥ : norm_sub_le _ _ ... ≤ ε / 2 * ∥z - x∥ + ε / 2 * ∥y - x∥ : add_le_add (hR _ (lt_trans (mem_ball.1 hz) hr.2)) (hR _ (lt_trans (mem_ball.1 hy) hr.2)) ... ≤ ε / 2 * r + ε / 2 * r : add_le_add (mul_le_mul_of_nonneg_left (le_of_lt (mem_ball_iff_norm.1 hz)) (le_of_lt (half_pos hε))) (mul_le_mul_of_nonneg_left (le_of_lt (mem_ball_iff_norm.1 hy)) (le_of_lt (half_pos hε))) ... = ε * r : by ring end lemma norm_sub_le_of_mem_A {c : 𝕜} (hc : 1 < ∥c∥) {r ε : ℝ} (hε : 0 < ε) (hr : 0 < r) {x : E} {L₁ L₂ : E →L[𝕜] F} (h₁ : x ∈ A f L₁ r ε) (h₂ : x ∈ A f L₂ r ε) : ∥L₁ - L₂∥ ≤ 4 * ∥c∥ * ε := begin have : 0 ≤ 4 * ∥c∥ * ε := mul_nonneg (mul_nonneg (by norm_num : (0 : ℝ) ≤ 4) (norm_nonneg _)) hε.le, refine op_norm_le_of_shell (half_pos hr) this hc _, assume y ley ylt, rw [div_div, div_le_iff' (mul_pos (by norm_num : (0 : ℝ) < 2) (zero_lt_one.trans hc))] at ley, calc ∥(L₁ - L₂) y∥ = ∥(f (x + y) - f x - L₂ ((x + y) - x)) - (f (x + y) - f x - L₁ ((x + y) - x))∥ : by simp ... ≤ ∥(f (x + y) - f x - L₂ ((x + y) - x))∥ + ∥(f (x + y) - f x - L₁ ((x + y) - x))∥ : norm_sub_le _ _ ... ≤ ε * r + ε * r : begin apply add_le_add, { apply le_of_mem_A h₂, { simp only [le_of_lt (half_pos hr), mem_closed_ball, dist_self] }, { simp only [dist_eq_norm, add_sub_cancel', mem_closed_ball, ylt.le], } }, { apply le_of_mem_A h₁, { simp only [le_of_lt (half_pos hr), mem_closed_ball, dist_self] }, { simp only [dist_eq_norm, add_sub_cancel', mem_closed_ball, ylt.le] } }, end ... = 2 * ε * r : by ring ... ≤ 2 * ε * (2 * ∥c∥ * ∥y∥) : mul_le_mul_of_nonneg_left ley (mul_nonneg (by norm_num) hε.le) ... = 4 * ∥c∥ * ε * ∥y∥ : by ring end /-- Easy inclusion: a differentiability point with derivative in `K` belongs to `D f K`. -/ lemma differentiable_set_subset_D : {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ K} ⊆ D f K := begin assume x hx, rw [D, mem_Inter], assume e, have : (0 : ℝ) < (1/2) ^ e := pow_pos (by norm_num) _, rcases mem_A_of_differentiable this hx.1 with ⟨R, R_pos, hR⟩, obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1/2) ^ n < R := exists_pow_lt_of_lt_one R_pos (by norm_num : (1 : ℝ)/2 < 1), simp only [mem_Union, mem_Inter, B, mem_inter_eq], refine ⟨n, λ p hp q hq, ⟨fderiv 𝕜 f x, hx.2, ⟨_, _⟩⟩⟩; { refine hR _ ⟨pow_pos (by norm_num) _, lt_of_le_of_lt _ hn⟩, exact pow_le_pow_of_le_one (by norm_num) (by norm_num) (by assumption) } end /-- Harder inclusion: at a point in `D f K`, the function `f` has a derivative, in `K`. -/ lemma D_subset_differentiable_set {K : set (E →L[𝕜] F)} (hK : is_complete K) : D f K ⊆ {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ K} := begin have P : ∀ {n : ℕ}, (0 : ℝ) < (1/2) ^ n := pow_pos (by norm_num), rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, have cpos : 0 < ∥c∥ := lt_trans zero_lt_one hc, assume x hx, have : ∀ (e : ℕ), ∃ (n : ℕ), ∀ p q, n ≤ p → n ≤ q → ∃ L ∈ K, x ∈ A f L ((1/2) ^ p) ((1/2) ^ e) ∩ A f L ((1/2) ^ q) ((1/2) ^ e), { assume e, have := mem_Inter.1 hx e, rcases mem_Union.1 this with ⟨n, hn⟩, refine ⟨n, λ p q hp hq, _⟩, simp only [mem_Inter, ge_iff_le] at hn, rcases mem_Union.1 (hn p hp q hq) with ⟨L, hL⟩, exact ⟨L, mem_Union.1 hL⟩, }, /- Recast the assumptions: for each `e`, there exist `n e` and linear maps `L e p q` in `K` such that, for `p, q ≥ n e`, then `f` is well approximated by `L e p q` at scale `2 ^ (-p)` and `2 ^ (-q)`, with an error `2 ^ (-e)`. -/ choose! n L hn using this, /- All the operators `L e p q` that show up are close to each other. To prove this, we argue that `L e p q` is close to `L e p r` (where `r` is large enough), as both approximate `f` at scale `2 ^(- p)`. And `L e p r` is close to `L e' p' r` as both approximate `f` at scale `2 ^ (- r)`. And `L e' p' r` is close to `L e' p' q'` as both approximate `f` at scale `2 ^ (- p')`. -/ have M : ∀ e p q e' p' q', n e ≤ p → n e ≤ q → n e' ≤ p' → n e' ≤ q' → e ≤ e' → ∥L e p q - L e' p' q'∥ ≤ 12 * ∥c∥ * (1/2) ^ e, { assume e p q e' p' q' hp hq hp' hq' he', let r := max (n e) (n e'), have I : ((1:ℝ)/2)^e' ≤ (1/2)^e := pow_le_pow_of_le_one (by norm_num) (by norm_num) he', have J1 : ∥L e p q - L e p r∥ ≤ 4 * ∥c∥ * (1/2)^e, { have I1 : x ∈ A f (L e p q) ((1 / 2) ^ p) ((1/2)^e) := (hn e p q hp hq).2.1, have I2 : x ∈ A f (L e p r) ((1 / 2) ^ p) ((1/2)^e) := (hn e p r hp (le_max_left _ _)).2.1, exact norm_sub_le_of_mem_A hc P P I1 I2 }, have J2 : ∥L e p r - L e' p' r∥ ≤ 4 * ∥c∥ * (1/2)^e, { have I1 : x ∈ A f (L e p r) ((1 / 2) ^ r) ((1/2)^e) := (hn e p r hp (le_max_left _ _)).2.2, have I2 : x ∈ A f (L e' p' r) ((1 / 2) ^ r) ((1/2)^e') := (hn e' p' r hp' (le_max_right _ _)).2.2, exact norm_sub_le_of_mem_A hc P P I1 (A_mono _ _ I I2) }, have J3 : ∥L e' p' r - L e' p' q'∥ ≤ 4 * ∥c∥ * (1/2)^e, { have I1 : x ∈ A f (L e' p' r) ((1 / 2) ^ p') ((1/2)^e') := (hn e' p' r hp' (le_max_right _ _)).2.1, have I2 : x ∈ A f (L e' p' q') ((1 / 2) ^ p') ((1/2)^e') := (hn e' p' q' hp' hq').2.1, exact norm_sub_le_of_mem_A hc P P (A_mono _ _ I I1) (A_mono _ _ I I2) }, calc ∥L e p q - L e' p' q'∥ = ∥(L e p q - L e p r) + (L e p r - L e' p' r) + (L e' p' r - L e' p' q')∥ : by { congr' 1, abel } ... ≤ ∥L e p q - L e p r∥ + ∥L e p r - L e' p' r∥ + ∥L e' p' r - L e' p' q'∥ : le_trans (norm_add_le _ _) (add_le_add_right (norm_add_le _ _) _) ... ≤ 4 * ∥c∥ * (1/2)^e + 4 * ∥c∥ * (1/2)^e + 4 * ∥c∥ * (1/2)^e : by apply_rules [add_le_add] ... = 12 * ∥c∥ * (1/2)^e : by ring }, /- For definiteness, use `L0 e = L e (n e) (n e)`, to have a single sequence. We claim that this is a Cauchy sequence. -/ let L0 : ℕ → (E →L[𝕜] F) := λ e, L e (n e) (n e), have : cauchy_seq L0, { rw metric.cauchy_seq_iff', assume ε εpos, obtain ⟨e, he⟩ : ∃ (e : ℕ), (1/2) ^ e < ε / (12 * ∥c∥) := exists_pow_lt_of_lt_one (div_pos εpos (mul_pos (by norm_num) cpos)) (by norm_num), refine ⟨e, λ e' he', _⟩, rw [dist_comm, dist_eq_norm], calc ∥L0 e - L0 e'∥ ≤ 12 * ∥c∥ * (1/2)^e : M _ _ _ _ _ _ le_rfl le_rfl le_rfl le_rfl he' ... < 12 * ∥c∥ * (ε / (12 * ∥c∥)) : mul_lt_mul' le_rfl he (le_of_lt P) (mul_pos (by norm_num) cpos) ... = ε : by { field_simp [(by norm_num : (12 : ℝ) ≠ 0), ne_of_gt cpos], ring } }, /- As it is Cauchy, the sequence `L0` converges, to a limit `f'` in `K`.-/ obtain ⟨f', f'K, hf'⟩ : ∃ f' ∈ K, tendsto L0 at_top (𝓝 f') := cauchy_seq_tendsto_of_is_complete hK (λ e, (hn e (n e) (n e) le_rfl le_rfl).1) this, have Lf' : ∀ e p, n e ≤ p → ∥L e (n e) p - f'∥ ≤ 12 * ∥c∥ * (1/2)^e, { assume e p hp, apply le_of_tendsto (tendsto_const_nhds.sub hf').norm, rw eventually_at_top, exact ⟨e, λ e' he', M _ _ _ _ _ _ le_rfl hp le_rfl le_rfl he'⟩ }, /- Let us show that `f` has derivative `f'` at `x`. -/ have : has_fderiv_at f f' x, { simp only [has_fderiv_at_iff_is_o_nhds_zero, is_o_iff], /- to get an approximation with a precision `ε`, we will replace `f` with `L e (n e) m` for some large enough `e` (yielding a small error by uniform approximation). As one can vary `m`, this makes it possible to cover all scales, and thus to obtain a good linear approximation in the whole ball of radius `(1/2)^(n e)`. -/ assume ε εpos, have pos : 0 < 4 + 12 * ∥c∥ := add_pos_of_pos_of_nonneg (by norm_num) (mul_nonneg (by norm_num) (norm_nonneg _)), obtain ⟨e, he⟩ : ∃ (e : ℕ), (1 / 2) ^ e < ε / (4 + 12 * ∥c∥) := exists_pow_lt_of_lt_one (div_pos εpos pos) (by norm_num), rw eventually_nhds_iff_ball, refine ⟨(1/2) ^ (n e + 1), P, λ y hy, _⟩, -- We need to show that `f (x + y) - f x - f' y` is small. For this, we will work at scale -- `k` where `k` is chosen with `∥y∥ ∼ 2 ^ (-k)`. by_cases y_pos : y = 0, {simp [y_pos] }, have yzero : 0 < ∥y∥ := norm_pos_iff.mpr y_pos, have y_lt : ∥y∥ < (1/2) ^ (n e + 1), by simpa using mem_ball_iff_norm.1 hy, have yone : ∥y∥ ≤ 1 := le_trans (y_lt.le) (pow_le_one _ (by norm_num) (by norm_num)), -- define the scale `k`. obtain ⟨k, hk, h'k⟩ : ∃ (k : ℕ), (1/2) ^ (k + 1) < ∥y∥ ∧ ∥y∥ ≤ (1/2) ^ k := exists_nat_pow_near_of_lt_one yzero yone (by norm_num : (0 : ℝ) < 1/2) (by norm_num : (1 : ℝ)/2 < 1), -- the scale is large enough (as `y` is small enough) have k_gt : n e < k, { have : ((1:ℝ)/2) ^ (k + 1) < (1/2) ^ (n e + 1) := lt_trans hk y_lt, rw pow_lt_pow_iff_of_lt_one (by norm_num : (0 : ℝ) < 1/2) (by norm_num) at this, linarith }, set m := k - 1 with hl, have m_ge : n e ≤ m := nat.le_pred_of_lt k_gt, have km : k = m + 1 := (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) k_gt)).symm, rw km at hk h'k, -- `f` is well approximated by `L e (n e) k` at the relevant scale -- (in fact, we use `m = k - 1` instead of `k` because of the precise definition of `A`). have J1 : ∥f (x + y) - f x - L e (n e) m ((x + y) - x)∥ ≤ (1/2) ^ e * (1/2) ^ m, { apply le_of_mem_A (hn e (n e) m le_rfl m_ge).2.2, { simp only [mem_closed_ball, dist_self], exact div_nonneg (le_of_lt P) (zero_le_two) }, { simpa only [dist_eq_norm, add_sub_cancel', mem_closed_ball, pow_succ', mul_one_div] using h'k } }, have J2 : ∥f (x + y) - f x - L e (n e) m y∥ ≤ 4 * (1/2) ^ e * ∥y∥ := calc ∥f (x + y) - f x - L e (n e) m y∥ ≤ (1/2) ^ e * (1/2) ^ m : by simpa only [add_sub_cancel'] using J1 ... = 4 * (1/2) ^ e * (1/2) ^ (m + 2) : by { field_simp, ring_exp } ... ≤ 4 * (1/2) ^ e * ∥y∥ : mul_le_mul_of_nonneg_left (le_of_lt hk) (mul_nonneg (by norm_num) (le_of_lt P)), -- use the previous estimates to see that `f (x + y) - f x - f' y` is small. calc ∥f (x + y) - f x - f' y∥ = ∥(f (x + y) - f x - L e (n e) m y) + (L e (n e) m - f') y∥ : congr_arg _ (by simp) ... ≤ 4 * (1/2) ^ e * ∥y∥ + 12 * ∥c∥ * (1/2) ^ e * ∥y∥ : norm_add_le_of_le J2 ((le_op_norm _ _).trans (mul_le_mul_of_nonneg_right (Lf' _ _ m_ge) (norm_nonneg _))) ... = (4 + 12 * ∥c∥) * ∥y∥ * (1/2) ^ e : by ring ... ≤ (4 + 12 * ∥c∥) * ∥y∥ * (ε / (4 + 12 * ∥c∥)) : mul_le_mul_of_nonneg_left he.le (mul_nonneg (add_nonneg (by norm_num) (mul_nonneg (by norm_num) (norm_nonneg _))) (norm_nonneg _)) ... = ε * ∥y∥ : by { field_simp [ne_of_gt pos], ring } }, rw ← this.fderiv at f'K, exact ⟨this.differentiable_at, f'K⟩ end theorem differentiable_set_eq_D (hK : is_complete K) : {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ K} = D f K := subset.antisymm (differentiable_set_subset_D _) (D_subset_differentiable_set hK) end fderiv_measurable_aux open fderiv_measurable_aux variables [measurable_space E] [opens_measurable_space E] variables (𝕜 f) /-- The set of differentiability points of a function, with derivative in a given complete set, is Borel-measurable. -/ theorem measurable_set_of_differentiable_at_of_is_complete {K : set (E →L[𝕜] F)} (hK : is_complete K) : measurable_set {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ K} := by simp [differentiable_set_eq_D K hK, D, is_open_B.measurable_set, measurable_set.Inter_Prop, measurable_set.Inter, measurable_set.Union] variable [complete_space F] /-- The set of differentiability points of a function taking values in a complete space is Borel-measurable. -/ theorem measurable_set_of_differentiable_at : measurable_set {x | differentiable_at 𝕜 f x} := begin have : is_complete (univ : set (E →L[𝕜] F)) := complete_univ, convert measurable_set_of_differentiable_at_of_is_complete 𝕜 f this, simp end @[measurability] lemma measurable_fderiv : measurable (fderiv 𝕜 f) := begin refine measurable_of_is_closed (λ s hs, _), have : fderiv 𝕜 f ⁻¹' s = {x | differentiable_at 𝕜 f x ∧ fderiv 𝕜 f x ∈ s} ∪ ({x | ¬differentiable_at 𝕜 f x} ∩ {x | (0 : E →L[𝕜] F) ∈ s}) := set.ext (λ x, mem_preimage.trans fderiv_mem_iff), rw this, exact (measurable_set_of_differentiable_at_of_is_complete _ _ hs.is_complete).union ((measurable_set_of_differentiable_at _ _).compl.inter (measurable_set.const _)) end @[measurability] lemma measurable_fderiv_apply_const [measurable_space F] [borel_space F] (y : E) : measurable (λ x, fderiv 𝕜 f x y) := (continuous_linear_map.measurable_apply y).comp (measurable_fderiv 𝕜 f) variable {𝕜} @[measurability] lemma measurable_deriv [measurable_space 𝕜] [opens_measurable_space 𝕜] [measurable_space F] [borel_space F] (f : 𝕜 → F) : measurable (deriv f) := by simpa only [fderiv_deriv] using measurable_fderiv_apply_const 𝕜 f 1 lemma strongly_measurable_deriv [measurable_space 𝕜] [opens_measurable_space 𝕜] [second_countable_topology F] (f : 𝕜 → F) : strongly_measurable (deriv f) := by { borelize F, exact (measurable_deriv f).strongly_measurable } lemma ae_measurable_deriv [measurable_space 𝕜] [opens_measurable_space 𝕜] [measurable_space F] [borel_space F] (f : 𝕜 → F) (μ : measure 𝕜) : ae_measurable (deriv f) μ := (measurable_deriv f).ae_measurable lemma ae_strongly_measurable_deriv [measurable_space 𝕜] [opens_measurable_space 𝕜] [second_countable_topology F] (f : 𝕜 → F) (μ : measure 𝕜) : ae_strongly_measurable (deriv f) μ := (strongly_measurable_deriv f).ae_strongly_measurable end fderiv section right_deriv variables {F : Type*} [normed_add_comm_group F] [normed_space ℝ F] variables {f : ℝ → F} (K : set F) namespace right_deriv_measurable_aux /-- The set `A f L r ε` is the set of points `x` around which the function `f` is well approximated at scale `r` by the linear map `h ↦ h • L`, up to an error `ε`. We tweak the definition to make sure that this is open on the right. -/ def A (f : ℝ → F) (L : F) (r ε : ℝ) : set ℝ := {x | ∃ r' ∈ Ioc (r/2) r, ∀ y z ∈ Icc x (x + r'), ∥f z - f y - (z-y) • L∥ ≤ ε * r} /-- The set `B f K r s ε` is the set of points `x` around which there exists a vector `L` belonging to `K` (a given set of vectors) such that `h • L` approximates well `f (x + h)` (up to an error `ε`), simultaneously at scales `r` and `s`. -/ def B (f : ℝ → F) (K : set F) (r s ε : ℝ) : set ℝ := ⋃ (L ∈ K), (A f L r ε) ∩ (A f L s ε) /-- The set `D f K` is a complicated set constructed using countable intersections and unions. Its main use is that, when `K` is complete, it is exactly the set of points where `f` is differentiable, with a derivative in `K`. -/ def D (f : ℝ → F) (K : set F) : set ℝ := ⋂ (e : ℕ), ⋃ (n : ℕ), ⋂ (p ≥ n) (q ≥ n), B f K ((1/2) ^ p) ((1/2) ^ q) ((1/2) ^ e) lemma A_mem_nhds_within_Ioi {L : F} {r ε x : ℝ} (hx : x ∈ A f L r ε) : A f L r ε ∈ 𝓝[>] x := begin rcases hx with ⟨r', rr', hr'⟩, rw mem_nhds_within_Ioi_iff_exists_Ioo_subset, obtain ⟨s, s_gt, s_lt⟩ : ∃ (s : ℝ), r / 2 < s ∧ s < r' := exists_between rr'.1, have : s ∈ Ioc (r/2) r := ⟨s_gt, le_of_lt (s_lt.trans_le rr'.2)⟩, refine ⟨x + r' - s, by { simp only [mem_Ioi], linarith }, λ x' hx', ⟨s, this, _⟩⟩, have A : Icc x' (x' + s) ⊆ Icc x (x + r'), { apply Icc_subset_Icc hx'.1.le, linarith [hx'.2] }, assume y hy z hz, exact hr' y (A hy) z (A hz) end lemma B_mem_nhds_within_Ioi {K : set F} {r s ε x : ℝ} (hx : x ∈ B f K r s ε) : B f K r s ε ∈ 𝓝[>] x := begin obtain ⟨L, LK, hL₁, hL₂⟩ : ∃ (L : F), L ∈ K ∧ x ∈ A f L r ε ∧ x ∈ A f L s ε, by simpa only [B, mem_Union, mem_inter_eq, exists_prop] using hx, filter_upwards [A_mem_nhds_within_Ioi hL₁, A_mem_nhds_within_Ioi hL₂] with y hy₁ hy₂, simp only [B, mem_Union, mem_inter_eq, exists_prop], exact ⟨L, LK, hy₁, hy₂⟩ end lemma measurable_set_B {K : set F} {r s ε : ℝ} : measurable_set (B f K r s ε) := measurable_set_of_mem_nhds_within_Ioi (λ x hx, B_mem_nhds_within_Ioi hx) lemma A_mono (L : F) (r : ℝ) {ε δ : ℝ} (h : ε ≤ δ) : A f L r ε ⊆ A f L r δ := begin rintros x ⟨r', r'r, hr'⟩, refine ⟨r', r'r, λ y hy z hz, (hr' y hy z hz).trans (mul_le_mul_of_nonneg_right h _)⟩, linarith [hy.1, hy.2, r'r.2], end lemma le_of_mem_A {r ε : ℝ} {L : F} {x : ℝ} (hx : x ∈ A f L r ε) {y z : ℝ} (hy : y ∈ Icc x (x + r/2)) (hz : z ∈ Icc x (x + r/2)) : ∥f z - f y - (z-y) • L∥ ≤ ε * r := begin rcases hx with ⟨r', r'mem, hr'⟩, have A : x + r / 2 ≤ x + r', by linarith [r'mem.1], exact hr' _ ((Icc_subset_Icc le_rfl A) hy) _ ((Icc_subset_Icc le_rfl A) hz), end lemma mem_A_of_differentiable {ε : ℝ} (hε : 0 < ε) {x : ℝ} (hx : differentiable_within_at ℝ f (Ici x) x) : ∃ R > 0, ∀ r ∈ Ioo (0 : ℝ) R, x ∈ A f (deriv_within f (Ici x) x) r ε := begin have := hx.has_deriv_within_at, simp_rw [has_deriv_within_at_iff_is_o, is_o_iff] at this, rcases mem_nhds_within_Ici_iff_exists_Ico_subset.1 (this (half_pos hε)) with ⟨m, xm, hm⟩, refine ⟨m - x, by linarith [show x < m, from xm], λ r hr, _⟩, have : r ∈ Ioc (r/2) r := ⟨half_lt_self hr.1, le_rfl⟩, refine ⟨r, this, λ y hy z hz, _⟩, calc ∥f z - f y - (z - y) • deriv_within f (Ici x) x∥ = ∥(f z - f x - (z - x) • deriv_within f (Ici x) x) - (f y - f x - (y - x) • deriv_within f (Ici x) x)∥ : by { congr' 1, simp only [sub_smul], abel } ... ≤ ∥f z - f x - (z - x) • deriv_within f (Ici x) x∥ + ∥f y - f x - (y - x) • deriv_within f (Ici x) x∥ : norm_sub_le _ _ ... ≤ ε / 2 * ∥z - x∥ + ε / 2 * ∥y - x∥ : add_le_add (hm ⟨hz.1, hz.2.trans_lt (by linarith [hr.2])⟩) (hm ⟨hy.1, hy.2.trans_lt (by linarith [hr.2])⟩) ... ≤ ε / 2 * r + ε / 2 * r : begin apply add_le_add, { apply mul_le_mul_of_nonneg_left _ (le_of_lt (half_pos hε)), rw [real.norm_of_nonneg]; linarith [hz.1, hz.2] }, { apply mul_le_mul_of_nonneg_left _ (le_of_lt (half_pos hε)), rw [real.norm_of_nonneg]; linarith [hy.1, hy.2] }, end ... = ε * r : by ring end lemma norm_sub_le_of_mem_A {r x : ℝ} (hr : 0 < r) (ε : ℝ) {L₁ L₂ : F} (h₁ : x ∈ A f L₁ r ε) (h₂ : x ∈ A f L₂ r ε) : ∥L₁ - L₂∥ ≤ 4 * ε := begin suffices H : ∥(r/2) • (L₁ - L₂)∥ ≤ (r / 2) * (4 * ε), by rwa [norm_smul, real.norm_of_nonneg (half_pos hr).le, mul_le_mul_left (half_pos hr)] at H, calc ∥(r/2) • (L₁ - L₂)∥ = ∥(f (x + r/2) - f x - (x + r/2 - x) • L₂) - (f (x + r/2) - f x - (x + r/2 - x) • L₁)∥ : by simp [smul_sub] ... ≤ ∥f (x + r/2) - f x - (x + r/2 - x) • L₂∥ + ∥f (x + r/2) - f x - (x + r/2 - x) • L₁∥ : norm_sub_le _ _ ... ≤ ε * r + ε * r : begin apply add_le_add, { apply le_of_mem_A h₂; simp [(half_pos hr).le] }, { apply le_of_mem_A h₁; simp [(half_pos hr).le] }, end ... = (r / 2) * (4 * ε) : by ring end /-- Easy inclusion: a differentiability point with derivative in `K` belongs to `D f K`. -/ lemma differentiable_set_subset_D : {x | differentiable_within_at ℝ f (Ici x) x ∧ deriv_within f (Ici x) x ∈ K} ⊆ D f K := begin assume x hx, rw [D, mem_Inter], assume e, have : (0 : ℝ) < (1/2) ^ e := pow_pos (by norm_num) _, rcases mem_A_of_differentiable this hx.1 with ⟨R, R_pos, hR⟩, obtain ⟨n, hn⟩ : ∃ (n : ℕ), (1/2) ^ n < R := exists_pow_lt_of_lt_one R_pos (by norm_num : (1 : ℝ)/2 < 1), simp only [mem_Union, mem_Inter, B, mem_inter_eq], refine ⟨n, λ p hp q hq, ⟨deriv_within f (Ici x) x, hx.2, ⟨_, _⟩⟩⟩; { refine hR _ ⟨pow_pos (by norm_num) _, lt_of_le_of_lt _ hn⟩, exact pow_le_pow_of_le_one (by norm_num) (by norm_num) (by assumption) } end /-- Harder inclusion: at a point in `D f K`, the function `f` has a derivative, in `K`. -/ lemma D_subset_differentiable_set {K : set F} (hK : is_complete K) : D f K ⊆ {x | differentiable_within_at ℝ f (Ici x) x ∧ deriv_within f (Ici x) x ∈ K} := begin have P : ∀ {n : ℕ}, (0 : ℝ) < (1/2) ^ n := pow_pos (by norm_num), assume x hx, have : ∀ (e : ℕ), ∃ (n : ℕ), ∀ p q, n ≤ p → n ≤ q → ∃ L ∈ K, x ∈ A f L ((1/2) ^ p) ((1/2) ^ e) ∩ A f L ((1/2) ^ q) ((1/2) ^ e), { assume e, have := mem_Inter.1 hx e, rcases mem_Union.1 this with ⟨n, hn⟩, refine ⟨n, λ p q hp hq, _⟩, simp only [mem_Inter, ge_iff_le] at hn, rcases mem_Union.1 (hn p hp q hq) with ⟨L, hL⟩, exact ⟨L, mem_Union.1 hL⟩, }, /- Recast the assumptions: for each `e`, there exist `n e` and linear maps `L e p q` in `K` such that, for `p, q ≥ n e`, then `f` is well approximated by `L e p q` at scale `2 ^ (-p)` and `2 ^ (-q)`, with an error `2 ^ (-e)`. -/ choose! n L hn using this, /- All the operators `L e p q` that show up are close to each other. To prove this, we argue that `L e p q` is close to `L e p r` (where `r` is large enough), as both approximate `f` at scale `2 ^(- p)`. And `L e p r` is close to `L e' p' r` as both approximate `f` at scale `2 ^ (- r)`. And `L e' p' r` is close to `L e' p' q'` as both approximate `f` at scale `2 ^ (- p')`. -/ have M : ∀ e p q e' p' q', n e ≤ p → n e ≤ q → n e' ≤ p' → n e' ≤ q' → e ≤ e' → ∥L e p q - L e' p' q'∥ ≤ 12 * (1/2) ^ e, { assume e p q e' p' q' hp hq hp' hq' he', let r := max (n e) (n e'), have I : ((1:ℝ)/2)^e' ≤ (1/2)^e := pow_le_pow_of_le_one (by norm_num) (by norm_num) he', have J1 : ∥L e p q - L e p r∥ ≤ 4 * (1/2)^e, { have I1 : x ∈ A f (L e p q) ((1 / 2) ^ p) ((1/2)^e) := (hn e p q hp hq).2.1, have I2 : x ∈ A f (L e p r) ((1 / 2) ^ p) ((1/2)^e) := (hn e p r hp (le_max_left _ _)).2.1, exact norm_sub_le_of_mem_A P _ I1 I2 }, have J2 : ∥L e p r - L e' p' r∥ ≤ 4 * (1/2)^e, { have I1 : x ∈ A f (L e p r) ((1 / 2) ^ r) ((1/2)^e) := (hn e p r hp (le_max_left _ _)).2.2, have I2 : x ∈ A f (L e' p' r) ((1 / 2) ^ r) ((1/2)^e') := (hn e' p' r hp' (le_max_right _ _)).2.2, exact norm_sub_le_of_mem_A P _ I1 (A_mono _ _ I I2) }, have J3 : ∥L e' p' r - L e' p' q'∥ ≤ 4 * (1/2)^e, { have I1 : x ∈ A f (L e' p' r) ((1 / 2) ^ p') ((1/2)^e') := (hn e' p' r hp' (le_max_right _ _)).2.1, have I2 : x ∈ A f (L e' p' q') ((1 / 2) ^ p') ((1/2)^e') := (hn e' p' q' hp' hq').2.1, exact norm_sub_le_of_mem_A P _ (A_mono _ _ I I1) (A_mono _ _ I I2) }, calc ∥L e p q - L e' p' q'∥ = ∥(L e p q - L e p r) + (L e p r - L e' p' r) + (L e' p' r - L e' p' q')∥ : by { congr' 1, abel } ... ≤ ∥L e p q - L e p r∥ + ∥L e p r - L e' p' r∥ + ∥L e' p' r - L e' p' q'∥ : le_trans (norm_add_le _ _) (add_le_add_right (norm_add_le _ _) _) ... ≤ 4 * (1/2)^e + 4 * (1/2)^e + 4 * (1/2)^e : by apply_rules [add_le_add] ... = 12 * (1/2)^e : by ring }, /- For definiteness, use `L0 e = L e (n e) (n e)`, to have a single sequence. We claim that this is a Cauchy sequence. -/ let L0 : ℕ → F := λ e, L e (n e) (n e), have : cauchy_seq L0, { rw metric.cauchy_seq_iff', assume ε εpos, obtain ⟨e, he⟩ : ∃ (e : ℕ), (1/2) ^ e < ε / 12 := exists_pow_lt_of_lt_one (div_pos εpos (by norm_num)) (by norm_num), refine ⟨e, λ e' he', _⟩, rw [dist_comm, dist_eq_norm], calc ∥L0 e - L0 e'∥ ≤ 12 * (1/2)^e : M _ _ _ _ _ _ le_rfl le_rfl le_rfl le_rfl he' ... < 12 * (ε / 12) : mul_lt_mul' le_rfl he (le_of_lt P) (by norm_num) ... = ε : by { field_simp [(by norm_num : (12 : ℝ) ≠ 0)], ring } }, /- As it is Cauchy, the sequence `L0` converges, to a limit `f'` in `K`.-/ obtain ⟨f', f'K, hf'⟩ : ∃ f' ∈ K, tendsto L0 at_top (𝓝 f') := cauchy_seq_tendsto_of_is_complete hK (λ e, (hn e (n e) (n e) le_rfl le_rfl).1) this, have Lf' : ∀ e p, n e ≤ p → ∥L e (n e) p - f'∥ ≤ 12 * (1/2)^e, { assume e p hp, apply le_of_tendsto (tendsto_const_nhds.sub hf').norm, rw eventually_at_top, exact ⟨e, λ e' he', M _ _ _ _ _ _ le_rfl hp le_rfl le_rfl he'⟩ }, /- Let us show that `f` has right derivative `f'` at `x`. -/ have : has_deriv_within_at f f' (Ici x) x, { simp only [has_deriv_within_at_iff_is_o, is_o_iff], /- to get an approximation with a precision `ε`, we will replace `f` with `L e (n e) m` for some large enough `e` (yielding a small error by uniform approximation). As one can vary `m`, this makes it possible to cover all scales, and thus to obtain a good linear approximation in the whole interval of length `(1/2)^(n e)`. -/ assume ε εpos, obtain ⟨e, he⟩ : ∃ (e : ℕ), (1 / 2) ^ e < ε / 16 := exists_pow_lt_of_lt_one (div_pos εpos (by norm_num)) (by norm_num), have xmem : x ∈ Ico x (x + (1/2)^(n e + 1)), by simp only [one_div, left_mem_Ico, lt_add_iff_pos_right, inv_pos, pow_pos, zero_lt_bit0, zero_lt_one], filter_upwards [Icc_mem_nhds_within_Ici xmem] with y hy, -- We need to show that `f y - f x - f' (y - x)` is small. For this, we will work at scale -- `k` where `k` is chosen with `∥y - x∥ ∼ 2 ^ (-k)`. rcases eq_or_lt_of_le hy.1 with rfl|xy, { simp only [sub_self, zero_smul, norm_zero, mul_zero]}, have yzero : 0 < y - x := sub_pos.2 xy, have y_le : y - x ≤ (1/2) ^ (n e + 1), by linarith [hy.2], have yone : y - x ≤ 1 := le_trans y_le (pow_le_one _ (by norm_num) (by norm_num)), -- define the scale `k`. obtain ⟨k, hk, h'k⟩ : ∃ (k : ℕ), (1/2) ^ (k + 1) < y - x ∧ y - x ≤ (1/2) ^ k := exists_nat_pow_near_of_lt_one yzero yone (by norm_num : (0 : ℝ) < 1/2) (by norm_num : (1 : ℝ)/2 < 1), -- the scale is large enough (as `y - x` is small enough) have k_gt : n e < k, { have : ((1:ℝ)/2) ^ (k + 1) < (1/2) ^ (n e + 1) := lt_of_lt_of_le hk y_le, rw pow_lt_pow_iff_of_lt_one (by norm_num : (0 : ℝ) < 1/2) (by norm_num) at this, linarith }, set m := k - 1 with hl, have m_ge : n e ≤ m := nat.le_pred_of_lt k_gt, have km : k = m + 1 := (nat.succ_pred_eq_of_pos (lt_of_le_of_lt (zero_le _) k_gt)).symm, rw km at hk h'k, -- `f` is well approximated by `L e (n e) k` at the relevant scale -- (in fact, we use `m = k - 1` instead of `k` because of the precise definition of `A`). have J : ∥f y - f x - (y - x) • L e (n e) m∥ ≤ 4 * (1/2) ^ e * ∥y - x∥ := calc ∥f y - f x - (y - x) • L e (n e) m∥ ≤ (1/2) ^ e * (1/2) ^ m : begin apply le_of_mem_A (hn e (n e) m le_rfl m_ge).2.2, { simp only [one_div, inv_pow, left_mem_Icc, le_add_iff_nonneg_right], exact div_nonneg (inv_nonneg.2 (pow_nonneg zero_le_two _)) zero_le_two }, { simp only [pow_add, tsub_le_iff_left] at h'k, simpa only [hy.1, mem_Icc, true_and, one_div, pow_one] using h'k } end ... = 4 * (1/2) ^ e * (1/2) ^ (m + 2) : by { field_simp, ring_exp } ... ≤ 4 * (1/2) ^ e * (y - x) : mul_le_mul_of_nonneg_left (le_of_lt hk) (mul_nonneg (by norm_num) (le_of_lt P)) ... = 4 * (1/2) ^ e * ∥y - x∥ : by rw [real.norm_of_nonneg yzero.le], calc ∥f y - f x - (y - x) • f'∥ = ∥(f y - f x - (y - x) • L e (n e) m) + (y - x) • (L e (n e) m - f')∥ : by simp only [smul_sub, sub_add_sub_cancel] ... ≤ 4 * (1/2) ^ e * ∥y - x∥ + ∥y - x∥ * (12 * (1/2) ^ e) : norm_add_le_of_le J (by { rw [norm_smul], exact mul_le_mul_of_nonneg_left (Lf' _ _ m_ge) (norm_nonneg _) }) ... = 16 * ∥y - x∥ * (1/2) ^ e : by ring ... ≤ 16 * ∥y - x∥ * (ε / 16) : mul_le_mul_of_nonneg_left he.le (mul_nonneg (by norm_num) (norm_nonneg _)) ... = ε * ∥y - x∥ : by ring }, rw ← this.deriv_within (unique_diff_on_Ici x x le_rfl) at f'K, exact ⟨this.differentiable_within_at, f'K⟩, end theorem differentiable_set_eq_D (hK : is_complete K) : {x | differentiable_within_at ℝ f (Ici x) x ∧ deriv_within f (Ici x) x ∈ K} = D f K := subset.antisymm (differentiable_set_subset_D _) (D_subset_differentiable_set hK) end right_deriv_measurable_aux open right_deriv_measurable_aux variables (f) /-- The set of right differentiability points of a function, with derivative in a given complete set, is Borel-measurable. -/ theorem measurable_set_of_differentiable_within_at_Ici_of_is_complete {K : set F} (hK : is_complete K) : measurable_set {x | differentiable_within_at ℝ f (Ici x) x ∧ deriv_within f (Ici x) x ∈ K} := by simp [differentiable_set_eq_D K hK, D, measurable_set_B, measurable_set.Inter_Prop, measurable_set.Inter, measurable_set.Union] variable [complete_space F] /-- The set of right differentiability points of a function taking values in a complete space is Borel-measurable. -/ theorem measurable_set_of_differentiable_within_at_Ici : measurable_set {x | differentiable_within_at ℝ f (Ici x) x} := begin have : is_complete (univ : set F) := complete_univ, convert measurable_set_of_differentiable_within_at_Ici_of_is_complete f this, simp end @[measurability] lemma measurable_deriv_within_Ici [measurable_space F] [borel_space F] : measurable (λ x, deriv_within f (Ici x) x) := begin refine measurable_of_is_closed (λ s hs, _), have : (λ x, deriv_within f (Ici x) x) ⁻¹' s = {x | differentiable_within_at ℝ f (Ici x) x ∧ deriv_within f (Ici x) x ∈ s} ∪ ({x | ¬differentiable_within_at ℝ f (Ici x) x} ∩ {x | (0 : F) ∈ s}) := set.ext (λ x, mem_preimage.trans deriv_within_mem_iff), rw this, exact (measurable_set_of_differentiable_within_at_Ici_of_is_complete _ hs.is_complete).union ((measurable_set_of_differentiable_within_at_Ici _).compl.inter (measurable_set.const _)) end lemma strongly_measurable_deriv_within_Ici [second_countable_topology F] : strongly_measurable (λ x, deriv_within f (Ici x) x) := by { borelize F, exact (measurable_deriv_within_Ici f).strongly_measurable } lemma ae_measurable_deriv_within_Ici [measurable_space F] [borel_space F] (μ : measure ℝ) : ae_measurable (λ x, deriv_within f (Ici x) x) μ := (measurable_deriv_within_Ici f).ae_measurable lemma ae_strongly_measurable_deriv_within_Ici [second_countable_topology F] (μ : measure ℝ) : ae_strongly_measurable (λ x, deriv_within f (Ici x) x) μ := (strongly_measurable_deriv_within_Ici f).ae_strongly_measurable /-- The set of right differentiability points of a function taking values in a complete space is Borel-measurable. -/ theorem measurable_set_of_differentiable_within_at_Ioi : measurable_set {x | differentiable_within_at ℝ f (Ioi x) x} := by simpa [differentiable_within_at_Ioi_iff_Ici] using measurable_set_of_differentiable_within_at_Ici f @[measurability] lemma measurable_deriv_within_Ioi [measurable_space F] [borel_space F] : measurable (λ x, deriv_within f (Ioi x) x) := by simpa [deriv_within_Ioi_eq_Ici] using measurable_deriv_within_Ici f lemma strongly_measurable_deriv_within_Ioi [second_countable_topology F] : strongly_measurable (λ x, deriv_within f (Ioi x) x) := by { borelize F, exact (measurable_deriv_within_Ioi f).strongly_measurable } lemma ae_measurable_deriv_within_Ioi [measurable_space F] [borel_space F] (μ : measure ℝ) : ae_measurable (λ x, deriv_within f (Ioi x) x) μ := (measurable_deriv_within_Ioi f).ae_measurable lemma ae_strongly_measurable_deriv_within_Ioi [second_countable_topology F] (μ : measure ℝ) : ae_strongly_measurable (λ x, deriv_within f (Ioi x) x) μ := (strongly_measurable_deriv_within_Ioi f).ae_strongly_measurable end right_deriv
513548ef6a134a1a78bd9c03ed29dc518ec027a5
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/instances/ennreal.lean
0fb4fb73cec5954fcc6f65dde645b07f2fbbbcab
[ "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
74,629
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import topology.instances.nnreal import topology.algebra.order.monotone_continuity import topology.algebra.infinite_sum.real import topology.algebra.order.liminf_limsup import topology.metric_space.lipschitz /-! # Extended non-negative reals > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ noncomputable theory open classical set filter metric open_locale classical topology ennreal nnreal big_operators filter variables {α : Type*} {β : Type*} {γ : Type*} namespace ennreal variables {a b c d : ℝ≥0∞} {r p q : ℝ≥0} variables {x y z : ℝ≥0∞} {ε ε₁ ε₂ : ℝ≥0∞} {s : set ℝ≥0∞} section topological_space open topological_space /-- Topology on `ℝ≥0∞`. Note: this is different from the `emetric_space` topology. The `emetric_space` topology has `is_open {⊤}`, while this topology doesn't have singleton elements. -/ instance : topological_space ℝ≥0∞ := preorder.topology ℝ≥0∞ instance : order_topology ℝ≥0∞ := ⟨rfl⟩ instance : t2_space ℝ≥0∞ := by apply_instance -- short-circuit type class inference instance : normal_space ℝ≥0∞ := normal_of_compact_t2 instance : second_countable_topology ℝ≥0∞ := order_iso_unit_interval_birational.to_homeomorph.embedding.second_countable_topology lemma embedding_coe : embedding (coe : ℝ≥0 → ℝ≥0∞) := ⟨⟨begin refine le_antisymm _ _, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0∞ _, ← coinduced_le_iff_le_induced], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : ℝ≥0 | a < ↑b}, { cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] }, show is_open {b : ℝ≥0 | ↑b < a}, { cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } }, { rw [@order_topology.topology_eq_generate_intervals ℝ≥0 _], refine le_generate_from (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨Ioi a, is_open_Ioi, by simp [Ioi]⟩, exact ⟨Iio a, is_open_Iio, by simp [Iio]⟩ } end⟩, assume a b, coe_eq_coe.1⟩ lemma is_open_ne_top : is_open {a : ℝ≥0∞ | a ≠ ⊤} := is_open_ne lemma is_open_Ico_zero : is_open (Ico 0 b) := by { rw ennreal.Ico_eq_Iio, exact is_open_Iio} lemma open_embedding_coe : open_embedding (coe : ℝ≥0 → ℝ≥0∞) := ⟨embedding_coe, by { convert is_open_ne_top, ext (x|_); simp [none_eq_top, some_eq_coe] }⟩ lemma coe_range_mem_nhds : range (coe : ℝ≥0 → ℝ≥0∞) ∈ 𝓝 (r : ℝ≥0∞) := is_open.mem_nhds open_embedding_coe.open_range $ mem_range_self _ @[norm_cast] lemma tendsto_coe {f : filter α} {m : α → ℝ≥0} {a : ℝ≥0} : tendsto (λa, (m a : ℝ≥0∞)) f (𝓝 ↑a) ↔ tendsto m f (𝓝 a) := embedding_coe.tendsto_nhds_iff.symm lemma continuous_coe : continuous (coe : ℝ≥0 → ℝ≥0∞) := embedding_coe.continuous lemma continuous_coe_iff {α} [topological_space α] {f : α → ℝ≥0} : continuous (λa, (f a : ℝ≥0∞)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : ℝ≥0} : 𝓝 (r : ℝ≥0∞) = (𝓝 r).map coe := (open_embedding_coe.map_nhds_eq r).symm lemma tendsto_nhds_coe_iff {α : Type*} {l : filter α} {x : ℝ≥0} {f : ℝ≥0∞ → α} : tendsto f (𝓝 ↑x) l ↔ tendsto (f ∘ coe : ℝ≥0 → α) (𝓝 x) l := show _ ≤ _ ↔ _ ≤ _, by rw [nhds_coe, filter.map_map] lemma continuous_at_coe_iff {α : Type*} [topological_space α] {x : ℝ≥0} {f : ℝ≥0∞ → α} : continuous_at f (↑x) ↔ continuous_at (f ∘ coe : ℝ≥0 → α) x := tendsto_nhds_coe_iff lemma nhds_coe_coe {r p : ℝ≥0} : 𝓝 ((r : ℝ≥0∞), (p : ℝ≥0∞)) = (𝓝 (r, p)).map (λp:ℝ≥0×ℝ≥0, (p.1, p.2)) := ((open_embedding_coe.prod open_embedding_coe).map_nhds_eq (r, p)).symm lemma continuous_of_real : continuous ennreal.of_real := (continuous_coe_iff.2 continuous_id).comp continuous_real_to_nnreal lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (𝓝 a)) : tendsto (λa, ennreal.of_real (m a)) f (𝓝 (ennreal.of_real a)) := tendsto.comp (continuous.tendsto continuous_of_real _) h lemma tendsto_to_nnreal {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_nnreal (𝓝 a) (𝓝 a.to_nnreal) := begin lift a to ℝ≥0 using ha, rw [nhds_coe, tendsto_map'_iff], exact tendsto_id end lemma eventually_eq_of_to_real_eventually_eq {l : filter α} {f g : α → ℝ≥0∞} (hfi : ∀ᶠ x in l, f x ≠ ∞) (hgi : ∀ᶠ x in l, g x ≠ ∞) (hfg : (λ x, (f x).to_real) =ᶠ[l] (λ x, (g x).to_real)) : f =ᶠ[l] g := begin filter_upwards [hfi, hgi, hfg] with _ hfx hgx _, rwa ← ennreal.to_real_eq_to_real hfx hgx, end lemma continuous_on_to_nnreal : continuous_on ennreal.to_nnreal {a | a ≠ ∞} := λ a ha, continuous_at.continuous_within_at (tendsto_to_nnreal ha) lemma tendsto_to_real {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto ennreal.to_real (𝓝 a) (𝓝 a.to_real) := nnreal.tendsto_coe.2 $ tendsto_to_nnreal ha /-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/ def ne_top_homeomorph_nnreal : {a | a ≠ ∞} ≃ₜ ℝ≥0 := { continuous_to_fun := continuous_on_iff_continuous_restrict.1 continuous_on_to_nnreal, continuous_inv_fun := continuous_coe.subtype_mk _, .. ne_top_equiv_nnreal } /-- The set of finite `ℝ≥0∞` numbers is homeomorphic to `ℝ≥0`. -/ def lt_top_homeomorph_nnreal : {a | a < ∞} ≃ₜ ℝ≥0 := by refine (homeomorph.set_congr $ set.ext $ λ x, _).trans ne_top_homeomorph_nnreal; simp only [mem_set_of_eq, lt_top_iff_ne_top] lemma nhds_top : 𝓝 ∞ = ⨅ a ≠ ∞, 𝓟 (Ioi a) := nhds_top_order.trans $ by simp [lt_top_iff_ne_top, Ioi] lemma nhds_top' : 𝓝 ∞ = ⨅ r : ℝ≥0, 𝓟 (Ioi r) := nhds_top.trans $ infi_ne_top _ lemma nhds_top_basis : (𝓝 ∞).has_basis (λ a, a < ∞) (λ a, Ioi a) := nhds_top_basis lemma tendsto_nhds_top_iff_nnreal {m : α → ℝ≥0∞} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ x : ℝ≥0, ∀ᶠ a in f, ↑x < m a := by simp only [nhds_top', tendsto_infi, tendsto_principal, mem_Ioi] lemma tendsto_nhds_top_iff_nat {m : α → ℝ≥0∞} {f : filter α} : tendsto m f (𝓝 ⊤) ↔ ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a := tendsto_nhds_top_iff_nnreal.trans ⟨λ h n, by simpa only [ennreal.coe_nat] using h n, λ h x, let ⟨n, hn⟩ := exists_nat_gt x in (h n).mono (λ y, lt_trans $ by rwa [← ennreal.coe_nat, coe_lt_coe])⟩ lemma tendsto_nhds_top {m : α → ℝ≥0∞} {f : filter α} (h : ∀ n : ℕ, ∀ᶠ a in f, ↑n < m a) : tendsto m f (𝓝 ⊤) := tendsto_nhds_top_iff_nat.2 h lemma tendsto_nat_nhds_top : tendsto (λ n : ℕ, ↑n) at_top (𝓝 ∞) := tendsto_nhds_top $ λ n, mem_at_top_sets.2 ⟨n + 1, λ m hm, mem_set_of.2 $ nat.cast_lt.2 $ nat.lt_of_succ_le hm⟩ @[simp, norm_cast] lemma tendsto_coe_nhds_top {f : α → ℝ≥0} {l : filter α} : tendsto (λ x, (f x : ℝ≥0∞)) l (𝓝 ∞) ↔ tendsto f l at_top := by rw [tendsto_nhds_top_iff_nnreal, at_top_basis_Ioi.tendsto_right_iff]; [simp, apply_instance, apply_instance] lemma tendsto_of_real_at_top : tendsto ennreal.of_real at_top (𝓝 ∞) := tendsto_coe_nhds_top.2 tendsto_real_to_nnreal_at_top lemma nhds_zero : 𝓝 (0 : ℝ≥0∞) = ⨅ a ≠ 0, 𝓟 (Iio a) := nhds_bot_order.trans $ by simp [bot_lt_iff_ne_bot, Iio] lemma nhds_zero_basis : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) (λ a, Iio a) := nhds_bot_basis lemma nhds_zero_basis_Iic : (𝓝 (0 : ℝ≥0∞)).has_basis (λ a : ℝ≥0∞, 0 < a) Iic := nhds_bot_basis_Iic @[instance] lemma nhds_within_Ioi_coe_ne_bot {r : ℝ≥0} : (𝓝[>] (r : ℝ≥0∞)).ne_bot := nhds_within_Ioi_self_ne_bot' ⟨⊤, ennreal.coe_lt_top⟩ @[instance] lemma nhds_within_Ioi_zero_ne_bot : (𝓝[>] (0 : ℝ≥0∞)).ne_bot := nhds_within_Ioi_coe_ne_bot -- using Icc because -- • don't have 'Ioo (x - ε) (x + ε) ∈ 𝓝 x' unless x > 0 -- • (x - y ≤ ε ↔ x ≤ ε + y) is true, while (x - y < ε ↔ x < ε + y) is not lemma Icc_mem_nhds (xt : x ≠ ⊤) (ε0 : ε ≠ 0) : Icc (x - ε) (x + ε) ∈ 𝓝 x := begin rw _root_.mem_nhds_iff, by_cases x0 : x = 0, { use Iio (x + ε), have : Iio (x + ε) ⊆ Icc (x - ε) (x + ε), assume a, rw x0, simpa using le_of_lt, use this, exact ⟨is_open_Iio, mem_Iio_self_add xt ε0⟩ }, { use Ioo (x - ε) (x + ε), use Ioo_subset_Icc_self, exact ⟨is_open_Ioo, mem_Ioo_self_sub_add xt x0 ε0 ε0 ⟩ } end lemma nhds_of_ne_top (xt : x ≠ ⊤) : 𝓝 x = ⨅ ε > 0, 𝓟 (Icc (x - ε) (x + ε)) := begin refine le_antisymm _ _, -- first direction simp only [le_infi_iff, le_principal_iff], assume ε ε0, exact Icc_mem_nhds xt ε0.lt.ne', -- second direction rw nhds_generate_from, refine le_infi (assume s, le_infi $ assume hs, _), rcases hs with ⟨xs, ⟨a, (rfl : s = Ioi a)|(rfl : s = Iio a)⟩⟩, { rcases exists_between xs with ⟨b, ab, bx⟩, have xb_pos : 0 < x - b := tsub_pos_iff_lt.2 bx, have xxb : x - (x - b) = b := sub_sub_cancel xt bx.le, refine infi_le_of_le (x - b) (infi_le_of_le xb_pos _), simp only [mem_principal, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xxb at h₁, calc a < b : ab ... ≤ y : h₁ }, { rcases exists_between xs with ⟨b, xb, ba⟩, have bx_pos : 0 < b - x := tsub_pos_iff_lt.2 xb, have xbx : x + (b - x) = b := add_tsub_cancel_of_le xb.le, refine infi_le_of_le (b - x) (infi_le_of_le bx_pos _), simp only [mem_principal, le_principal_iff], assume y, rintros ⟨h₁, h₂⟩, rw xbx at h₂, calc y ≤ b : h₂ ... < a : ba }, end /-- Characterization of neighborhoods for `ℝ≥0∞` numbers. See also `tendsto_order` for a version with strict inequalities. -/ protected theorem tendsto_nhds {f : filter α} {u : α → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, (u x) ∈ Icc (a - ε) (a + ε) := by simp only [nhds_of_ne_top ha, tendsto_infi, tendsto_principal, mem_Icc] protected lemma tendsto_nhds_zero {f : filter α} {u : α → ℝ≥0∞} : tendsto u f (𝓝 0) ↔ ∀ ε > 0, ∀ᶠ x in f, u x ≤ ε := begin rw ennreal.tendsto_nhds zero_ne_top, simp only [true_and, zero_tsub, zero_le, zero_add, set.mem_Icc], end protected lemma tendsto_at_top [nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} {a : ℝ≥0∞} (ha : a ≠ ⊤) : tendsto f at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, (f n) ∈ Icc (a - ε) (a + ε) := by simp only [ennreal.tendsto_nhds ha, mem_at_top_sets, mem_set_of_eq, filter.eventually] instance : has_continuous_add ℝ≥0∞ := begin refine ⟨continuous_iff_continuous_at.2 _⟩, rintro ⟨(_|a), b⟩, { exact tendsto_nhds_top_mono' continuous_at_fst (λ p, le_add_right le_rfl) }, rcases b with (_|b), { exact tendsto_nhds_top_mono' continuous_at_snd (λ p, le_add_left le_rfl) }, simp only [continuous_at, some_eq_coe, nhds_coe_coe, ← coe_add, tendsto_map'_iff, (∘), tendsto_coe, tendsto_add] end protected lemma tendsto_at_top_zero [hβ : nonempty β] [semilattice_sup β] {f : β → ℝ≥0∞} : filter.at_top.tendsto f (𝓝 0) ↔ ∀ ε > 0, ∃ N, ∀ n ≥ N, f n ≤ ε := begin rw ennreal.tendsto_at_top zero_ne_top, { simp_rw [set.mem_Icc, zero_add, zero_tsub, zero_le _, true_and], }, { exact hβ, }, end lemma tendsto_sub {a b : ℝ≥0∞} (h : a ≠ ∞ ∨ b ≠ ∞) : tendsto (λ p : ℝ≥0∞ × ℝ≥0∞, p.1 - p.2) (𝓝 (a, b)) (𝓝 (a - b)) := begin cases a; cases b, { simp only [eq_self_iff_true, not_true, ne.def, none_eq_top, or_self] at h, contradiction }, { simp only [some_eq_coe, with_top.top_sub_coe, none_eq_top], apply tendsto_nhds_top_iff_nnreal.2 (λ n, _), rw [nhds_prod_eq, eventually_prod_iff], refine ⟨λ z, ((n + (b + 1)) : ℝ≥0∞) < z, Ioi_mem_nhds (by simp only [one_lt_top, add_lt_top, coe_lt_top, and_self]), λ z, z < b + 1, Iio_mem_nhds ((ennreal.lt_add_right coe_ne_top one_ne_zero)), λ x hx y hy, _⟩, dsimp, rw lt_tsub_iff_right, have : ((n : ℝ≥0∞) + y) + (b + 1) < x + (b + 1) := calc ((n : ℝ≥0∞) + y) + (b + 1) = ((n : ℝ≥0∞) + (b + 1)) + y : by abel ... < x + (b + 1) : ennreal.add_lt_add hx hy, exact lt_of_add_lt_add_right this }, { simp only [some_eq_coe, with_top.sub_top, none_eq_top], suffices H : ∀ᶠ (p : ℝ≥0∞ × ℝ≥0∞) in 𝓝 (a, ∞), 0 = p.1 - p.2, from tendsto_const_nhds.congr' H, rw [nhds_prod_eq, eventually_prod_iff], refine ⟨λ z, z < a + 1, Iio_mem_nhds (ennreal.lt_add_right coe_ne_top one_ne_zero), λ z, (a : ℝ≥0∞) + 1 < z, Ioi_mem_nhds (by simp only [one_lt_top, add_lt_top, coe_lt_top, and_self]), λ x hx y hy, _⟩, rw eq_comm, simp only [tsub_eq_zero_iff_le, (has_lt.lt.trans hx hy).le], }, { simp only [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, function.comp, ← ennreal.coe_sub, tendsto_coe], exact continuous.tendsto (by continuity) _ } end protected lemma tendsto.sub {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (hmb : tendsto mb f (𝓝 b)) (h : a ≠ ∞ ∨ b ≠ ∞) : tendsto (λ a, ma a - mb a) f (𝓝 (a - b)) := show tendsto ((λ p : ℝ≥0∞ × ℝ≥0∞, p.1 - p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a - b)), from tendsto.comp (ennreal.tendsto_sub h) (hma.prod_mk_nhds hmb) protected lemma tendsto_mul (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 (a, b)) (𝓝 (a * b)) := have ht : ∀b:ℝ≥0∞, b ≠ 0 → tendsto (λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) (𝓝 ((⊤:ℝ≥0∞), b)) (𝓝 ⊤), begin refine assume b hb, tendsto_nhds_top_iff_nnreal.2 $ assume n, _, rcases lt_iff_exists_nnreal_btwn.1 (pos_iff_ne_zero.2 hb) with ⟨ε, hε, hεb⟩, have : ∀ᶠ c : ℝ≥0∞ × ℝ≥0∞ in 𝓝 (∞, b), ↑n / ↑ε < c.1 ∧ ↑ε < c.2, from (lt_mem_nhds $ div_lt_top coe_ne_top hε.ne').prod_nhds (lt_mem_nhds hεb), refine this.mono (λ c hc, _), exact (ennreal.div_mul_cancel hε.ne' coe_ne_top).symm.trans_lt (mul_lt_mul hc.1 hc.2) end, begin cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] }, cases b, { simp [none_eq_top] at ha, simp [*, nhds_swap (a : ℝ≥0∞) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] }, simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_mul.symm, tendsto_coe, tendsto_mul] end protected lemma tendsto.mul {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λa, ma a * mb a) f (𝓝 (a * b)) := show tendsto ((λp:ℝ≥0∞×ℝ≥0∞, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (𝓝 (a * b)), from tendsto.comp (ennreal.tendsto_mul ha hb) (hma.prod_mk_nhds hmb) lemma _root_.continuous_on.ennreal_mul [topological_space α] {f g : α → ℝ≥0∞} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) (h₁ : ∀ x ∈ s, f x ≠ 0 ∨ g x ≠ ∞) (h₂ : ∀ x ∈ s, g x ≠ 0 ∨ f x ≠ ∞) : continuous_on (λ x, f x * g x) s := λ x hx, ennreal.tendsto.mul (hf x hx) (h₁ x hx) (hg x hx) (h₂ x hx) lemma _root_.continuous.ennreal_mul [topological_space α] {f g : α → ℝ≥0∞} (hf : continuous f) (hg : continuous g) (h₁ : ∀ x, f x ≠ 0 ∨ g x ≠ ∞) (h₂ : ∀ x, g x ≠ 0 ∨ f x ≠ ∞) : continuous (λ x, f x * g x) := continuous_iff_continuous_at.2 $ λ x, ennreal.tendsto.mul hf.continuous_at (h₁ x) hg.continuous_at (h₂ x) protected lemma tendsto.const_mul {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (𝓝 (a * b)) := by_cases (assume : a = 0, by simp [this, tendsto_const_nhds]) (assume ha : a ≠ 0, ennreal.tendsto.mul tendsto_const_nhds (or.inl ha) hm hb) protected lemma tendsto.mul_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ ⊤) : tendsto (λx, m x * b) f (𝓝 (a * b)) := by simpa only [mul_comm] using ennreal.tendsto.const_mul hm ha lemma tendsto_finset_prod_of_ne_top {ι : Type*} {f : ι → α → ℝ≥0∞} {x : filter α} {a : ι → ℝ≥0∞} (s : finset ι) (h : ∀ i ∈ s, tendsto (f i) x (𝓝 (a i))) (h' : ∀ i ∈ s, a i ≠ ∞): tendsto (λ b, ∏ c in s, f c b) x (𝓝 (∏ c in s, a c)) := begin induction s using finset.induction with a s has IH, { simp [tendsto_const_nhds] }, simp only [finset.prod_insert has], apply tendsto.mul (h _ (finset.mem_insert_self _ _)), { right, exact (prod_lt_top (λ i hi, h' _ (finset.mem_insert_of_mem hi))).ne }, { exact IH (λ i hi, h _ (finset.mem_insert_of_mem hi)) (λ i hi, h' _ (finset.mem_insert_of_mem hi)) }, { exact or.inr (h' _ (finset.mem_insert_self _ _)) } end protected lemma continuous_at_const_mul {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at ((*) a) b := tendsto.const_mul tendsto_id h.symm protected lemma continuous_at_mul_const {a b : ℝ≥0∞} (h : a ≠ ⊤ ∨ b ≠ 0) : continuous_at (λ x, x * a) b := tendsto.mul_const tendsto_id h.symm protected lemma continuous_const_mul {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous ((*) a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_const_mul (or.inl ha) protected lemma continuous_mul_const {a : ℝ≥0∞} (ha : a ≠ ⊤) : continuous (λ x, x * a) := continuous_iff_continuous_at.2 $ λ x, ennreal.continuous_at_mul_const (or.inl ha) protected lemma continuous_div_const (c : ℝ≥0∞) (c_ne_zero : c ≠ 0) : continuous (λ (x : ℝ≥0∞), x / c) := begin simp_rw [div_eq_mul_inv, continuous_iff_continuous_at], intro x, exact ennreal.continuous_at_mul_const (or.intro_left _ (inv_ne_top.mpr c_ne_zero)), end @[continuity] lemma continuous_pow (n : ℕ) : continuous (λ a : ℝ≥0∞, a ^ n) := begin induction n with n IH, { simp [continuous_const] }, simp_rw [nat.succ_eq_add_one, pow_add, pow_one, continuous_iff_continuous_at], assume x, refine ennreal.tendsto.mul (IH.tendsto _) _ tendsto_id _; by_cases H : x = 0, { simp only [H, zero_ne_top, ne.def, or_true, not_false_iff]}, { exact or.inl (λ h, H (pow_eq_zero h)) }, { simp only [H, pow_eq_top_iff, zero_ne_top, false_or, eq_self_iff_true, not_true, ne.def, not_false_iff, false_and], }, { simp only [H, true_or, ne.def, not_false_iff] } end lemma continuous_on_sub : continuous_on (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) { p : ℝ≥0∞ × ℝ≥0∞ | p ≠ ⟨∞, ∞⟩ } := begin rw continuous_on, rintros ⟨x, y⟩ hp, simp only [ne.def, set.mem_set_of_eq, prod.mk.inj_iff] at hp, refine tendsto_nhds_within_of_tendsto_nhds (tendsto_sub (not_and_distrib.mp hp)), end lemma continuous_sub_left {a : ℝ≥0∞} (a_ne_top : a ≠ ⊤) : continuous (λ x, a - x) := begin rw (show (λ x, a - x) = (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) ∘ (λ x, ⟨a, x⟩), by refl), apply continuous_on.comp_continuous continuous_on_sub (continuous.prod.mk a), intro x, simp only [a_ne_top, ne.def, mem_set_of_eq, prod.mk.inj_iff, false_and, not_false_iff], end lemma continuous_nnreal_sub {a : ℝ≥0} : continuous (λ (x : ℝ≥0∞), (a : ℝ≥0∞) - x) := continuous_sub_left coe_ne_top lemma continuous_on_sub_left (a : ℝ≥0∞) : continuous_on (λ x, a - x) {x : ℝ≥0∞ | x ≠ ∞} := begin rw (show (λ x, a - x) = (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) ∘ (λ x, ⟨a, x⟩), by refl), apply continuous_on.comp continuous_on_sub (continuous.continuous_on (continuous.prod.mk a)), rintros _ h (_|_), exact h none_eq_top, end lemma continuous_sub_right (a : ℝ≥0∞) : continuous (λ x : ℝ≥0∞, x - a) := begin by_cases a_infty : a = ∞, { simp [a_infty, continuous_const], }, { rw (show (λ x, x - a) = (λ p : ℝ≥0∞ × ℝ≥0∞, p.fst - p.snd) ∘ (λ x, ⟨x, a⟩), by refl), apply continuous_on.comp_continuous continuous_on_sub (continuous_id'.prod_mk continuous_const), intro x, simp only [a_infty, ne.def, mem_set_of_eq, prod.mk.inj_iff, and_false, not_false_iff], }, end protected lemma tendsto.pow {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} {n : ℕ} (hm : tendsto m f (𝓝 a)) : tendsto (λ x, (m x) ^ n) f (𝓝 (a ^ n)) := ((continuous_pow n).tendsto a).comp hm lemma le_of_forall_lt_one_mul_le {x y : ℝ≥0∞} (h : ∀ a < 1, a * x ≤ y) : x ≤ y := begin have : tendsto (* x) (𝓝[<] 1) (𝓝 (1 * x)) := (ennreal.continuous_at_mul_const (or.inr one_ne_zero)).mono_left inf_le_left, rw one_mul at this, haveI : (𝓝[<] (1 : ℝ≥0∞)).ne_bot := nhds_within_Iio_self_ne_bot' ⟨0, zero_lt_one⟩, exact le_of_tendsto this (eventually_nhds_within_iff.2 $ eventually_of_forall h) end lemma infi_mul_left' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) : (⨅ i, a * f i) = a * ⨅ i, f i := begin by_cases H : a = ⊤ ∧ (⨅ i, f i) = 0, { rcases h H.1 H.2 with ⟨i, hi⟩, rw [H.2, mul_zero, ← bot_eq_zero, infi_eq_bot], exact λ b hb, ⟨i, by rwa [hi, mul_zero, ← bot_eq_zero]⟩ }, { rw not_and_distrib at H, casesI is_empty_or_nonempty ι, { rw [infi_of_empty, infi_of_empty, mul_top, if_neg], exact mt h0 (not_nonempty_iff.2 ‹_›) }, { exact (ennreal.mul_left_mono.map_infi_of_continuous_at' (ennreal.continuous_at_const_mul H)).symm } } end lemma infi_mul_left {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, a * f i) = a * ⨅ i, f i := infi_mul_left' h (λ _, ‹nonempty ι›) lemma infi_mul_right' {ι} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) (h0 : a = 0 → nonempty ι) : (⨅ i, f i * a) = (⨅ i, f i) * a := by simpa only [mul_comm a] using infi_mul_left' h h0 lemma infi_mul_right {ι} [nonempty ι] {f : ι → ℝ≥0∞} {a : ℝ≥0∞} (h : a = ⊤ → (⨅ i, f i) = 0 → ∃ i, f i = 0) : (⨅ i, f i * a) = (⨅ i, f i) * a := infi_mul_right' h (λ _, ‹nonempty ι›) lemma inv_map_infi {ι : Sort*} {x : ι → ℝ≥0∞} : (infi x)⁻¹ = (⨆ i, (x i)⁻¹) := order_iso.inv_ennreal.map_infi x lemma inv_map_supr {ι : Sort*} {x : ι → ℝ≥0∞} : (supr x)⁻¹ = (⨅ i, (x i)⁻¹) := order_iso.inv_ennreal.map_supr x lemma inv_limsup {ι : Sort*} {x : ι → ℝ≥0∞} {l : filter ι} : (limsup x l)⁻¹ = liminf (λ i, (x i)⁻¹) l := by simp only [limsup_eq_infi_supr, inv_map_infi, inv_map_supr, liminf_eq_supr_infi] lemma inv_liminf {ι : Sort*} {x : ι → ℝ≥0∞} {l : filter ι} : (liminf x l)⁻¹ = limsup (λ i, (x i)⁻¹) l := by simp only [limsup_eq_infi_supr, inv_map_infi, inv_map_supr, liminf_eq_supr_infi] instance : has_continuous_inv ℝ≥0∞ := ⟨order_iso.inv_ennreal.continuous⟩ @[simp] protected lemma tendsto_inv_iff {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} : tendsto (λ x, (m x)⁻¹) f (𝓝 a⁻¹) ↔ tendsto m f (𝓝 a) := ⟨λ h, by simpa only [inv_inv] using tendsto.inv h, tendsto.inv⟩ protected lemma tendsto.div {f : filter α} {ma : α → ℝ≥0∞} {mb : α → ℝ≥0∞} {a b : ℝ≥0∞} (hma : tendsto ma f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) (hmb : tendsto mb f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λa, ma a / mb a) f (𝓝 (a / b)) := by { apply tendsto.mul hma _ (ennreal.tendsto_inv_iff.2 hmb) _; simp [ha, hb] } protected lemma tendsto.const_div {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 b)) (hb : b ≠ ⊤ ∨ a ≠ ⊤) : tendsto (λb, a / m b) f (𝓝 (a / b)) := by { apply tendsto.const_mul (ennreal.tendsto_inv_iff.2 hm), simp [hb] } protected lemma tendsto.div_const {f : filter α} {m : α → ℝ≥0∞} {a b : ℝ≥0∞} (hm : tendsto m f (𝓝 a)) (ha : a ≠ 0 ∨ b ≠ 0) : tendsto (λx, m x / b) f (𝓝 (a / b)) := by { apply tendsto.mul_const hm, simp [ha] } protected lemma tendsto_inv_nat_nhds_zero : tendsto (λ n : ℕ, (n : ℝ≥0∞)⁻¹) at_top (𝓝 0) := ennreal.inv_top ▸ ennreal.tendsto_inv_iff.2 tendsto_nat_nhds_top lemma supr_add {ι : Sort*} {s : ι → ℝ≥0∞} [h : nonempty ι] : supr s + a = ⨆b, s b + a := monotone.map_supr_of_continuous_at' (continuous_at_id.add continuous_at_const) $ monotone_id.add monotone_const lemma bsupr_add' {ι : Sort*} {p : ι → Prop} (h : ∃ i, p i) {f : ι → ℝ≥0∞} : (⨆ i (hi : p i), f i) + a = ⨆ i (hi : p i), f i + a := by { haveI : nonempty {i // p i} := nonempty_subtype.2 h, simp only [supr_subtype', supr_add] } lemma add_bsupr' {ι : Sort*} {p : ι → Prop} (h : ∃ i, p i) {f : ι → ℝ≥0∞} : a + (⨆ i (hi : p i), f i) = ⨆ i (hi : p i), a + f i := by simp only [add_comm a, bsupr_add' h] lemma bsupr_add {ι} {s : set ι} (hs : s.nonempty) {f : ι → ℝ≥0∞} : (⨆ i ∈ s, f i) + a = ⨆ i ∈ s, f i + a := bsupr_add' hs lemma add_bsupr {ι} {s : set ι} (hs : s.nonempty) {f : ι → ℝ≥0∞} : a + (⨆ i ∈ s, f i) = ⨆ i ∈ s, a + f i := add_bsupr' hs lemma Sup_add {s : set ℝ≥0∞} (hs : s.nonempty) : Sup s + a = ⨆b∈s, b + a := by rw [Sup_eq_supr, bsupr_add hs] lemma add_supr {ι : Sort*} {s : ι → ℝ≥0∞} [nonempty ι] : a + supr s = ⨆b, a + s b := by rw [add_comm, supr_add]; simp [add_comm] lemma supr_add_supr_le {ι ι' : Sort*} [nonempty ι] [nonempty ι'] {f : ι → ℝ≥0∞} {g : ι' → ℝ≥0∞} {a : ℝ≥0∞} (h : ∀ i j, f i + g j ≤ a) : supr f + supr g ≤ a := by simpa only [add_supr, supr_add] using supr₂_le h lemma bsupr_add_bsupr_le' {ι ι'} {p : ι → Prop} {q : ι' → Prop} (hp : ∃ i, p i) (hq : ∃ j, q j) {f : ι → ℝ≥0∞} {g : ι' → ℝ≥0∞} {a : ℝ≥0∞} (h : ∀ i (hi : p i) j (hj : q j), f i + g j ≤ a) : (⨆ i (hi : p i), f i) + (⨆ j (hj : q j), g j) ≤ a := by { simp_rw [bsupr_add' hp, add_bsupr' hq], exact supr₂_le (λ i hi, supr₂_le (h i hi)) } lemma bsupr_add_bsupr_le {ι ι'} {s : set ι} {t : set ι'} (hs : s.nonempty) (ht : t.nonempty) {f : ι → ℝ≥0∞} {g : ι' → ℝ≥0∞} {a : ℝ≥0∞} (h : ∀ (i ∈ s) (j ∈ t), f i + g j ≤ a) : (⨆ i ∈ s, f i) + (⨆ j ∈ t, g j) ≤ a := bsupr_add_bsupr_le' hs ht h lemma supr_add_supr {ι : Sort*} {f g : ι → ℝ≥0∞} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) : supr f + supr g = (⨆ a, f a + g a) := begin casesI is_empty_or_nonempty ι, { simp only [supr_of_empty, bot_eq_zero, zero_add] }, { refine le_antisymm _ (supr_le $ λ a, add_le_add (le_supr _ _) (le_supr _ _)), refine supr_add_supr_le (λ i j, _), rcases h i j with ⟨k, hk⟩, exact le_supr_of_le k hk } end lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι] {f g : ι → ℝ≥0∞} (hf : monotone f) (hg : monotone g) : supr f + supr g = (⨆ a, f a + g a) := supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add (hf $ le_sup_left) (hg $ le_sup_right)⟩ lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ℝ≥0∞} (hf : ∀a, monotone (f a)) : ∑ a in s, supr (f a) = (⨆ n, ∑ a in s, f a n) := begin refine finset.induction_on s _ _, { simp, }, { assume a s has ih, simp only [finset.sum_insert has], rw [ih, supr_add_supr_of_monotone (hf a)], assume i j h, exact (finset.sum_le_sum $ assume a ha, hf a h) } end lemma mul_supr {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : a * supr f = ⨆i, a * f i := begin by_cases hf : ∀ i, f i = 0, { obtain rfl : f = (λ _, 0), from funext hf, simp only [supr_zero_eq_zero, mul_zero] }, { refine (monotone_id.const_mul' _).map_supr_of_continuous_at _ (mul_zero a), refine ennreal.tendsto.const_mul tendsto_id (or.inl _), exact mt supr_eq_zero.1 hf } end lemma mul_Sup {s : set ℝ≥0∞} {a : ℝ≥0∞} : a * Sup s = ⨆i∈s, a * i := by simp only [Sup_eq_supr, mul_supr] lemma supr_mul {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f * a = ⨆i, f i * a := by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm] lemma smul_supr {ι : Sort*} {R} [has_smul R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞] (f : ι → ℝ≥0∞) (c : R) : c • (⨆ i, f i) = ⨆ i, c • f i := by simp only [←smul_one_mul c (f _), ←smul_one_mul c (supr _), ennreal.mul_supr] lemma smul_Sup {R} [has_smul R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞] (s : set ℝ≥0∞) (c : R) : c • Sup s = ⨆ i ∈ s, c • i := by simp_rw [←smul_one_mul c (Sup _), ennreal.mul_Sup, smul_one_mul] lemma supr_div {ι : Sort*} {f : ι → ℝ≥0∞} {a : ℝ≥0∞} : supr f / a = ⨆i, f i / a := supr_mul protected lemma tendsto_coe_sub : ∀{b:ℝ≥0∞}, tendsto (λb:ℝ≥0∞, ↑r - b) (𝓝 b) (𝓝 (↑r - b)) := begin refine forall_ennreal.2 ⟨λ a, _, _⟩, { simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, ← with_top.coe_sub], exact tendsto_const_nhds.sub tendsto_id }, simp, exact (tendsto.congr' (mem_of_superset (lt_mem_nhds $ @coe_lt_top r) $ by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds end lemma sub_supr {ι : Sort*} [nonempty ι] {b : ι → ℝ≥0∞} (hr : a < ⊤) : a - (⨆i, b i) = (⨅i, a - b i) := let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i), from is_glb.Inf_eq $ is_lub_supr.is_glb_of_tendsto (assume x _ y _, tsub_le_tsub (le_refl (r : ℝ≥0∞))) (range_nonempty _) (ennreal.tendsto_coe_sub.comp (tendsto_id'.2 inf_le_left)), by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_rfl lemma exists_countable_dense_no_zero_top : ∃ (s : set ℝ≥0∞), s.countable ∧ dense s ∧ 0 ∉ s ∧ ∞ ∉ s := begin obtain ⟨s, s_count, s_dense, hs⟩ : ∃ s : set ℝ≥0∞, s.countable ∧ dense s ∧ (∀ x, is_bot x → x ∉ s) ∧ (∀ x, is_top x → x ∉ s) := exists_countable_dense_no_bot_top ℝ≥0∞, exact ⟨s, s_count, s_dense, λ h, hs.1 0 (by simp) h, λ h, hs.2 ∞ (by simp) h⟩, end lemma exists_lt_add_of_lt_add {x y z : ℝ≥0∞} (h : x < y + z) (hy : y ≠ 0) (hz : z ≠ 0) : ∃ y' z', y' < y ∧ z' < z ∧ x < y' + z' := begin haveI : ne_bot (𝓝[<] y) := nhds_within_Iio_self_ne_bot' ⟨0, pos_iff_ne_zero.2 hy⟩, haveI : ne_bot (𝓝[<] z) := nhds_within_Iio_self_ne_bot' ⟨0, pos_iff_ne_zero.2 hz⟩, have A : tendsto (λ (p : ℝ≥0∞ × ℝ≥0∞), p.1 + p.2) ((𝓝[<] y).prod (𝓝[<] z)) (𝓝 (y + z)), { apply tendsto.mono_left _ (filter.prod_mono nhds_within_le_nhds nhds_within_le_nhds), rw ← nhds_prod_eq, exact tendsto_add }, rcases (((tendsto_order.1 A).1 x h).and (filter.prod_mem_prod self_mem_nhds_within self_mem_nhds_within)).exists with ⟨⟨y', z'⟩, hx, hy', hz'⟩, exact ⟨y', z', hy', hz', hx⟩, end end topological_space section liminf lemma exists_frequently_lt_of_liminf_ne_top {ι : Type*} {l : filter ι} {x : ι → ℝ} (hx : liminf (λ n, ((x n).nnabs : ℝ≥0∞)) l ≠ ∞) : ∃ R, ∃ᶠ n in l, x n < R := begin by_contra h, simp_rw [not_exists, not_frequently, not_lt] at h, refine hx (ennreal.eq_top_of_forall_nnreal_le $ λ r, le_Liminf_of_le (by is_bounded_default) _), simp only [eventually_map, ennreal.coe_le_coe], filter_upwards [h r] with i hi using hi.trans (le_abs_self (x i)) end lemma exists_frequently_lt_of_liminf_ne_top' {ι : Type*} {l : filter ι} {x : ι → ℝ} (hx : liminf (λ n, ((x n).nnabs : ℝ≥0∞)) l ≠ ∞) : ∃ R, ∃ᶠ n in l, R < x n := begin by_contra h, simp_rw [not_exists, not_frequently, not_lt] at h, refine hx (ennreal.eq_top_of_forall_nnreal_le $ λ r, le_Liminf_of_le (by is_bounded_default) _), simp only [eventually_map, ennreal.coe_le_coe], filter_upwards [h (-r)] with i hi using (le_neg.1 hi).trans (neg_le_abs_self _), end lemma exists_upcrossings_of_not_bounded_under {ι : Type*} {l : filter ι} {x : ι → ℝ} (hf : liminf (λ i, ((x i).nnabs : ℝ≥0∞)) l ≠ ∞) (hbdd : ¬ is_bounded_under (≤) l (λ i, |x i|)) : ∃ a b : ℚ, a < b ∧ (∃ᶠ i in l, x i < a) ∧ (∃ᶠ i in l, ↑b < x i) := begin rw [is_bounded_under_le_abs, not_and_distrib] at hbdd, obtain hbdd | hbdd := hbdd, { obtain ⟨R, hR⟩ := exists_frequently_lt_of_liminf_ne_top hf, obtain ⟨q, hq⟩ := exists_rat_gt R, refine ⟨q, q + 1, (lt_add_iff_pos_right _).2 zero_lt_one, _, _⟩, { refine λ hcon, hR _, filter_upwards [hcon] with x hx using not_lt.2 (lt_of_lt_of_le hq (not_lt.1 hx)).le }, { simp only [is_bounded_under, is_bounded, eventually_map, eventually_at_top, ge_iff_le, not_exists, not_forall, not_le, exists_prop] at hbdd, refine λ hcon, hbdd ↑(q + 1) _, filter_upwards [hcon] with x hx using not_lt.1 hx } }, { obtain ⟨R, hR⟩ := exists_frequently_lt_of_liminf_ne_top' hf, obtain ⟨q, hq⟩ := exists_rat_lt R, refine ⟨q - 1, q, (sub_lt_self_iff _).2 zero_lt_one, _, _⟩, { simp only [is_bounded_under, is_bounded, eventually_map, eventually_at_top, ge_iff_le, not_exists, not_forall, not_le, exists_prop] at hbdd, refine λ hcon, hbdd ↑(q - 1) _, filter_upwards [hcon] with x hx using not_lt.1 hx }, { refine λ hcon, hR _, filter_upwards [hcon] with x hx using not_lt.2 ((not_lt.1 hx).trans hq.le) } } end end liminf section tsum variables {f g : α → ℝ≥0∞} @[norm_cast] protected lemma has_sum_coe {f : α → ℝ≥0} {r : ℝ≥0} : has_sum (λa, (f a : ℝ≥0∞)) ↑r ↔ has_sum f r := have (λs:finset α, ∑ a in s, ↑(f a)) = (coe : ℝ≥0 → ℝ≥0∞) ∘ (λs:finset α, ∑ a in s, f a), from funext $ assume s, ennreal.coe_finset_sum.symm, by unfold has_sum; rw [this, tendsto_coe] protected lemma tsum_coe_eq {f : α → ℝ≥0} (h : has_sum f r) : ∑'a, (f a : ℝ≥0∞) = r := (ennreal.has_sum_coe.2 h).tsum_eq protected lemma coe_tsum {f : α → ℝ≥0} : summable f → ↑(tsum f) = ∑'a, (f a : ℝ≥0∞) | ⟨r, hr⟩ := by rw [hr.tsum_eq, ennreal.tsum_coe_eq hr] protected lemma has_sum : has_sum f (⨆s:finset α, ∑ a in s, f a) := tendsto_at_top_supr $ λ s t, finset.sum_le_sum_of_subset @[simp] protected lemma summable : summable f := ⟨_, ennreal.has_sum⟩ lemma tsum_coe_ne_top_iff_summable {f : β → ℝ≥0} : ∑' b, (f b:ℝ≥0∞) ≠ ∞ ↔ summable f := begin refine ⟨λ h, _, λ h, ennreal.coe_tsum h ▸ ennreal.coe_ne_top⟩, lift (∑' b, (f b:ℝ≥0∞)) to ℝ≥0 using h with a ha, refine ⟨a, ennreal.has_sum_coe.1 _⟩, rw ha, exact ennreal.summable.has_sum end protected lemma tsum_eq_supr_sum : ∑'a, f a = (⨆s:finset α, ∑ a in s, f a) := ennreal.has_sum.tsum_eq protected lemma tsum_eq_supr_sum' {ι : Type*} (s : ι → finset α) (hs : ∀ t, ∃ i, t ⊆ s i) : ∑' a, f a = ⨆ i, ∑ a in s i, f a := begin rw [ennreal.tsum_eq_supr_sum], symmetry, change (⨆i:ι, (λ t : finset α, ∑ a in t, f a) (s i)) = ⨆s:finset α, ∑ a in s, f a, exact (finset.sum_mono_set f).supr_comp_eq hs end protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ℝ≥0∞) : ∑'p:Σa, β a, f p.1 p.2 = ∑'a b, f a b := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_sigma' {β : α → Type*} (f : (Σ a, β a) → ℝ≥0∞) : ∑'p:(Σa, β a), f p = ∑'a b, f ⟨a, b⟩ := tsum_sigma' (assume b, ennreal.summable) ennreal.summable protected lemma tsum_prod {f : α → β → ℝ≥0∞} : ∑' p : α × β, f p.1 p.2 = ∑' a b, f a b := tsum_prod' ennreal.summable $ λ _, ennreal.summable protected lemma tsum_prod' {f : α × β → ℝ≥0∞} : ∑' p : α × β, f p = ∑' a b, f (a, b) := tsum_prod' ennreal.summable $ λ _, ennreal.summable protected lemma tsum_comm {f : α → β → ℝ≥0∞} : ∑'a, ∑'b, f a b = ∑'b, ∑'a, f a b := tsum_comm' ennreal.summable (λ _, ennreal.summable) (λ _, ennreal.summable) protected lemma tsum_add : ∑'a, (f a + g a) = (∑'a, f a) + (∑'a, g a) := tsum_add ennreal.summable ennreal.summable protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : ∑'a, f a ≤ ∑'a, g a := tsum_le_tsum h ennreal.summable ennreal.summable protected lemma sum_le_tsum {f : α → ℝ≥0∞} (s : finset α) : ∑ x in s, f x ≤ ∑' x, f x := sum_le_tsum s (λ x hx, zero_le _) ennreal.summable protected lemma tsum_eq_supr_nat' {f : ℕ → ℝ≥0∞} {N : ℕ → ℕ} (hN : tendsto N at_top at_top) : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range (N i), f a) := ennreal.tsum_eq_supr_sum' _ $ λ t, let ⟨n, hn⟩ := t.exists_nat_subset_range, ⟨k, _, hk⟩ := exists_le_of_tendsto_at_top hN 0 n in ⟨k, finset.subset.trans hn (finset.range_mono hk)⟩ protected lemma tsum_eq_supr_nat {f : ℕ → ℝ≥0∞} : ∑'i:ℕ, f i = (⨆i:ℕ, ∑ a in finset.range i, f a) := ennreal.tsum_eq_supr_sum' _ finset.exists_nat_subset_range protected lemma tsum_eq_liminf_sum_nat {f : ℕ → ℝ≥0∞} : ∑' i, f i = liminf (λ n, ∑ i in finset.range n, f i) at_top := begin rw [ennreal.tsum_eq_supr_nat, filter.liminf_eq_supr_infi_of_nat], congr, refine funext (λ n, le_antisymm _ _), { refine le_infi₂ (λ i hi, finset.sum_le_sum_of_subset_of_nonneg _ (λ _ _ _, zero_le _)), simpa only [finset.range_subset, add_le_add_iff_right] using hi, }, { refine le_trans (infi_le _ n) _, simp [le_refl n, le_refl ((finset.range n).sum f)], }, end protected lemma le_tsum (a : α) : f a ≤ ∑'a, f a := le_tsum' ennreal.summable a @[simp] protected lemma tsum_eq_zero : ∑' i, f i = 0 ↔ ∀ i, f i = 0 := ⟨λ h i, nonpos_iff_eq_zero.1 $ h ▸ ennreal.le_tsum i, λ h, by simp [h]⟩ protected lemma tsum_eq_top_of_eq_top : (∃ a, f a = ∞) → ∑' a, f a = ∞ | ⟨a, ha⟩ := top_unique $ ha ▸ ennreal.le_tsum a protected lemma lt_top_of_tsum_ne_top {a : α → ℝ≥0∞} (tsum_ne_top : ∑' i, a i ≠ ∞) (j : α) : a j < ∞ := begin have key := not_imp_not.mpr ennreal.tsum_eq_top_of_eq_top, simp only [not_exists] at key, exact lt_top_iff_ne_top.mpr (key tsum_ne_top j), end @[simp] protected lemma tsum_top [nonempty α] : ∑' a : α, ∞ = ∞ := let ⟨a⟩ := ‹nonempty α› in ennreal.tsum_eq_top_of_eq_top ⟨a, rfl⟩ lemma tsum_const_eq_top_of_ne_zero {α : Type*} [infinite α] {c : ℝ≥0∞} (hc : c ≠ 0) : (∑' (a : α), c) = ∞ := begin have A : tendsto (λ (n : ℕ), (n : ℝ≥0∞) * c) at_top (𝓝 (∞ * c)), { apply ennreal.tendsto.mul_const tendsto_nat_nhds_top, simp only [true_or, top_ne_zero, ne.def, not_false_iff] }, have B : ∀ (n : ℕ), (n : ℝ≥0∞) * c ≤ (∑' (a : α), c), { assume n, rcases infinite.exists_subset_card_eq α n with ⟨s, hs⟩, simpa [hs] using @ennreal.sum_le_tsum α (λ i, c) s }, simpa [hc] using le_of_tendsto' A B, end protected lemma ne_top_of_tsum_ne_top (h : ∑' a, f a ≠ ∞) (a : α) : f a ≠ ∞ := λ ha, h $ ennreal.tsum_eq_top_of_eq_top ⟨a, ha⟩ protected lemma tsum_mul_left : ∑'i, a * f i = a * ∑'i, f i := if h : ∀i, f i = 0 then by simp [h] else let ⟨i, (hi : f i ≠ 0)⟩ := not_forall.mp h in have sum_ne_0 : ∑'i, f i ≠ 0, from ne_of_gt $ calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm ... ≤ ∑'i, f i : ennreal.le_tsum _, have tendsto (λs:finset α, ∑ j in s, a * f j) at_top (𝓝 (a * ∑'i, f i)), by rw [← show (*) a ∘ (λs:finset α, ∑ j in s, f j) = λs, ∑ j in s, a * f j, from funext $ λ s, finset.mul_sum]; exact ennreal.tendsto.const_mul ennreal.summable.has_sum (or.inl sum_ne_0), has_sum.tsum_eq this protected lemma tsum_mul_right : (∑'i, f i * a) = (∑'i, f i) * a := by simp [mul_comm, ennreal.tsum_mul_left] protected lemma tsum_const_smul {R} [has_smul R ℝ≥0∞] [is_scalar_tower R ℝ≥0∞ ℝ≥0∞] (a : R) : ∑' i, a • f i = a • ∑' i, f i := by simpa only [smul_one_mul] using @ennreal.tsum_mul_left _ (a • 1) _ @[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ℝ≥0∞} : ∑'b:α, (⨆ (h : a = b), f b) = f a := le_antisymm (by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s, calc (∑ b in s, ⨆ (h : a = b), f b) ≤ ∑ b in {a}, ⨆ (h : a = b), f b : finset.sum_le_sum_of_ne_zero $ assume b _ hb, suffices a = b, by simpa using this.symm, classical.by_contradiction $ assume h, by simpa [h] using hb ... = f a : by simp)) (calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl ... ≤ (∑'b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _) lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0∞} (r : ℝ≥0∞) : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin refine ⟨has_sum.tendsto_sum_nat, assume h, _⟩, rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat], { exact ennreal.summable.has_sum }, { exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) } end lemma tendsto_nat_tsum (f : ℕ → ℝ≥0∞) : tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 (∑' n, f n)) := by { rw ← has_sum_iff_tendsto_nat, exact ennreal.summable.has_sum } lemma to_nnreal_apply_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) (x : α) : (((ennreal.to_nnreal ∘ f) x : ℝ≥0) : ℝ≥0∞) = f x := coe_to_nnreal $ ennreal.ne_top_of_tsum_ne_top hf _ lemma summable_to_nnreal_of_tsum_ne_top {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' i, f i ≠ ∞) : summable (ennreal.to_nnreal ∘ f) := by simpa only [←tsum_coe_ne_top_iff_summable, to_nnreal_apply_of_tsum_ne_top hf] using hf lemma tendsto_cofinite_zero_of_tsum_ne_top {α} {f : α → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto f cofinite (𝓝 0) := begin have f_ne_top : ∀ n, f n ≠ ∞, from ennreal.ne_top_of_tsum_ne_top hf, have h_f_coe : f = λ n, ((f n).to_nnreal : ennreal), from funext (λ n, (coe_to_nnreal (f_ne_top n)).symm), rw [h_f_coe, ←@coe_zero, tendsto_coe], exact nnreal.tendsto_cofinite_zero_of_summable (summable_to_nnreal_of_tsum_ne_top hf), end lemma tendsto_at_top_zero_of_tsum_ne_top {f : ℕ → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact tendsto_cofinite_zero_of_tsum_ne_top hf } /-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole space. This does not need a summability assumption, as otherwise all sums are zero. -/ lemma tendsto_tsum_compl_at_top_zero {α : Type*} {f : α → ℝ≥0∞} (hf : ∑' x, f x ≠ ∞) : tendsto (λ (s : finset α), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) := begin lift f to α → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hf, convert ennreal.tendsto_coe.2 (nnreal.tendsto_tsum_compl_at_top_zero f), ext1 s, rw ennreal.coe_tsum, exact nnreal.summable_comp_injective (tsum_coe_ne_top_iff_summable.1 hf) subtype.coe_injective end protected lemma tsum_apply {ι α : Type*} {f : ι → α → ℝ≥0∞} {x : α} : (∑' i, f i) x = ∑' i, f i x := tsum_apply $ pi.summable.mpr $ λ _, ennreal.summable lemma tsum_sub {f : ℕ → ℝ≥0∞} {g : ℕ → ℝ≥0∞} (h₁ : ∑' i, g i ≠ ∞) (h₂ : g ≤ f) : ∑' i, (f i - g i) = (∑' i, f i) - (∑' i, g i) := begin have h₃: ∑' i, (f i - g i) = ∑' i, (f i - g i + g i) - ∑' i, g i, { rw [ennreal.tsum_add, ennreal.add_sub_cancel_right h₁]}, have h₄:(λ i, (f i - g i) + (g i)) = f, { ext n, rw tsub_add_cancel_of_le (h₂ n)}, rw h₄ at h₃, apply h₃, end lemma tsum_mono_subtype (f : α → ℝ≥0∞) {s t : set α} (h : s ⊆ t) : ∑' (x : s), f x ≤ ∑' (x : t), f x := begin simp only [tsum_subtype], apply ennreal.tsum_le_tsum, exact indicator_le_indicator_of_subset h (λ _, zero_le _), end lemma tsum_union_le (f : α → ℝ≥0∞) (s t : set α) : ∑' (x : s ∪ t), f x ≤ ∑' (x : s), f x + ∑' (x : t), f x := calc ∑' (x : s ∪ t), f x = ∑' (x : s ∪ (t \ s)), f x : by { apply tsum_congr_subtype, rw union_diff_self } ... = ∑' (x : s), f x + ∑' (x : t \ s), f x : tsum_union_disjoint disjoint_sdiff_self_right ennreal.summable ennreal.summable ... ≤ ∑' (x : s), f x + ∑' (x : t), f x : add_le_add le_rfl (tsum_mono_subtype _ (diff_subset _ _)) lemma tsum_bUnion_le {ι : Type*} (f : α → ℝ≥0∞) (s : finset ι) (t : ι → set α) : ∑' (x : ⋃ (i ∈ s), t i), f x ≤ ∑ i in s, ∑' (x : t i), f x := begin classical, induction s using finset.induction_on with i s hi ihs h, { simp }, have : (⋃ (j ∈ insert i s), t j) = t i ∪ (⋃ (j ∈ s), t j), by simp, rw tsum_congr_subtype f this, calc ∑' (x : (t i ∪ (⋃ (j ∈ s), t j))), f x ≤ ∑' (x : t i), f x + ∑' (x : ⋃ (j ∈ s), t j), f x : tsum_union_le _ _ _ ... ≤ ∑' (x : t i), f x + ∑ i in s, ∑' (x : t i), f x : add_le_add le_rfl ihs ... = ∑ j in insert i s, ∑' (x : t j), f x : (finset.sum_insert hi).symm end lemma tsum_Union_le {ι : Type*} [fintype ι] (f : α → ℝ≥0∞) (t : ι → set α) : ∑' (x : ⋃ i, t i), f x ≤ ∑ i, ∑' (x : t i), f x := begin classical, have : (⋃ i, t i) = (⋃ (i ∈ (finset.univ : finset ι)), t i), by simp, rw tsum_congr_subtype f this, exact tsum_bUnion_le _ _ _ end lemma tsum_eq_add_tsum_ite {f : β → ℝ≥0∞} (b : β) : ∑' x, f x = f b + ∑' x, ite (x = b) 0 (f x) := tsum_eq_add_tsum_ite' b ennreal.summable lemma tsum_add_one_eq_top {f : ℕ → ℝ≥0∞} (hf : ∑' n, f n = ∞) (hf0 : f 0 ≠ ∞) : ∑' n, f (n + 1) = ∞ := begin rw ← tsum_eq_tsum_of_has_sum_iff_has_sum (λ _, (not_mem_range_equiv 1).has_sum_iff), swap, { apply_instance }, have h₁ : (∑' b : {n // n ∈ finset.range 1}, f b) + (∑' b : {n // n ∉ finset.range 1}, f b) = ∑' b, f b, { exact tsum_add_tsum_compl ennreal.summable ennreal.summable }, rw [finset.tsum_subtype, finset.sum_range_one, hf, ennreal.add_eq_top] at h₁, rw ← h₁.resolve_left hf0, apply tsum_congr, rintro ⟨i, hi⟩, simp only [multiset.mem_range, not_lt] at hi, simp only [tsub_add_cancel_of_le hi, coe_not_mem_range_equiv, function.comp_app, subtype.coe_mk], end /-- A sum of extended nonnegative reals which is finite can have only finitely many terms above any positive threshold.-/ lemma finite_const_le_of_tsum_ne_top {ι : Type*} {a : ι → ℝ≥0∞} (tsum_ne_top : ∑' i, a i ≠ ∞) {ε : ℝ≥0∞} (ε_ne_zero : ε ≠ 0) : {i : ι | ε ≤ a i}.finite := begin by_cases ε_infty : ε = ∞, { rw ε_infty, by_contra maybe_infinite, obtain ⟨j, hj⟩ := set.infinite.nonempty maybe_infinite, exact tsum_ne_top (le_antisymm le_top (le_trans hj (le_tsum' (@ennreal.summable _ a) j))), }, have key := (nnreal.summable_coe.mpr (summable_to_nnreal_of_tsum_ne_top tsum_ne_top)).tendsto_cofinite_zero (Iio_mem_nhds (to_real_pos ε_ne_zero ε_infty)), simp only [filter.mem_map, filter.mem_cofinite, preimage] at key, have obs : {i : ι | ↑((a i).to_nnreal) ∈ Iio ε.to_real}ᶜ = {i : ι | ε ≤ a i}, { ext i, simpa only [mem_Iio, mem_compl_iff, mem_set_of_eq, not_lt] using to_real_le_to_real ε_infty (ennreal.ne_top_of_tsum_ne_top tsum_ne_top _), }, rwa obs at key, end /-- Markov's inequality for `finset.card` and `tsum` in `ℝ≥0∞`. -/ lemma finset_card_const_le_le_of_tsum_le {ι : Type*} {a : ι → ℝ≥0∞} {c : ℝ≥0∞} (c_ne_top : c ≠ ∞) (tsum_le_c : ∑' i, a i ≤ c) {ε : ℝ≥0∞} (ε_ne_zero : ε ≠ 0) : ∃ hf : {i : ι | ε ≤ a i}.finite, ↑hf.to_finset.card ≤ c / ε := begin by_cases ε = ∞, { have obs : {i : ι | ε ≤ a i} = ∅, { rw eq_empty_iff_forall_not_mem, intros i hi, have oops := (le_trans hi (le_tsum' (@ennreal.summable _ a) i)).trans tsum_le_c, rw h at oops, exact c_ne_top (le_antisymm le_top oops), }, simp only [obs, finite_empty, finite.to_finset_empty, finset.card_empty, algebra_map.coe_zero, zero_le', exists_true_left], }, have hf : {i : ι | ε ≤ a i}.finite, from ennreal.finite_const_le_of_tsum_ne_top (lt_of_le_of_lt tsum_le_c c_ne_top.lt_top).ne ε_ne_zero, use hf, have at_least : ∀ i ∈ hf.to_finset, ε ≤ a i, { intros i hi, simpa only [finite.mem_to_finset, mem_set_of_eq] using hi, }, have partial_sum := @sum_le_tsum _ _ _ _ _ a hf.to_finset (λ _ _, zero_le') (@ennreal.summable _ a), have lower_bound := finset.sum_le_sum at_least, simp only [finset.sum_const, nsmul_eq_mul] at lower_bound, have key := (ennreal.le_div_iff_mul_le (or.inl ε_ne_zero) (or.inl h)).mpr lower_bound, exact le_trans key (ennreal.div_le_div_right (partial_sum.trans tsum_le_c) _), end end tsum lemma tendsto_to_real_iff {ι} {fi : filter ι} {f : ι → ℝ≥0∞} (hf : ∀ i, f i ≠ ∞) {x : ℝ≥0∞} (hx : x ≠ ∞) : fi.tendsto (λ n, (f n).to_real) (𝓝 x.to_real) ↔ fi.tendsto f (𝓝 x) := begin refine ⟨λ h, _, λ h, tendsto.comp (ennreal.tendsto_to_real hx) h⟩, have h_eq : f = (λ n, ennreal.of_real (f n).to_real), by { ext1 n, rw ennreal.of_real_to_real (hf n), }, rw [h_eq, ← ennreal.of_real_to_real hx], exact ennreal.tendsto_of_real h, end lemma tsum_coe_ne_top_iff_summable_coe {f : α → ℝ≥0} : ∑' a, (f a : ℝ≥0∞) ≠ ∞ ↔ summable (λ a, (f a : ℝ)) := begin rw nnreal.summable_coe, exact tsum_coe_ne_top_iff_summable, end lemma tsum_coe_eq_top_iff_not_summable_coe {f : α → ℝ≥0} : ∑' a, (f a : ℝ≥0∞) = ∞ ↔ ¬ summable (λ a, (f a : ℝ)) := begin rw [← @not_not (∑' a, ↑(f a) = ⊤)], exact not_congr tsum_coe_ne_top_iff_summable_coe end lemma has_sum_to_real {f : α → ℝ≥0∞} (hsum : ∑' x, f x ≠ ∞) : has_sum (λ x, (f x).to_real) (∑' x, (f x).to_real) := begin lift f to α → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hsum, simp only [coe_to_real, ← nnreal.coe_tsum, nnreal.has_sum_coe], exact (tsum_coe_ne_top_iff_summable.1 hsum).has_sum end lemma summable_to_real {f : α → ℝ≥0∞} (hsum : ∑' x, f x ≠ ∞) : summable (λ x, (f x).to_real) := (has_sum_to_real hsum).summable end ennreal namespace nnreal open_locale nnreal lemma tsum_eq_to_nnreal_tsum {f : β → ℝ≥0} : (∑' b, f b) = (∑' b, (f b : ℝ≥0∞)).to_nnreal := begin by_cases h : summable f, { rw [← ennreal.coe_tsum h, ennreal.to_nnreal_coe] }, { have A := tsum_eq_zero_of_not_summable h, simp only [← ennreal.tsum_coe_ne_top_iff_summable, not_not] at h, simp only [h, ennreal.top_to_nnreal, A] } end /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma exists_le_has_sum_of_le {f g : β → ℝ≥0} {r : ℝ≥0} (hgf : ∀b, g b ≤ f b) (hfr : has_sum f r) : ∃p≤r, has_sum g p := have ∑'b, (g b : ℝ≥0∞) ≤ r, begin refine has_sum_le (assume b, _) ennreal.summable.has_sum (ennreal.has_sum_coe.2 hfr), exact ennreal.coe_le_coe.2 (hgf _) end, let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in ⟨p, hpr, ennreal.has_sum_coe.1 $ eq ▸ ennreal.summable.has_sum⟩ /-- Comparison test of convergence of `ℝ≥0`-valued series. -/ lemma summable_of_le {f g : β → ℝ≥0} (hgf : ∀b, g b ≤ f b) : summable f → summable g | ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_has_sum_of_le hgf hfr in hp.summable /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat {f : ℕ → ℝ≥0} {r : ℝ≥0} : has_sum f r ↔ tendsto (λn:ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin rw [← ennreal.has_sum_coe, ennreal.has_sum_iff_tendsto_nat], simp only [ennreal.coe_finset_sum.symm], exact ennreal.tendsto_coe end lemma not_summable_iff_tendsto_nat_at_top {f : ℕ → ℝ≥0} : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin split, { intros h, refine ((tendsto_of_monotone _).resolve_right h).comp _, exacts [finset.sum_mono_set _, tendsto_finset_range] }, { rintros hnat ⟨r, hr⟩, exact not_tendsto_nhds_of_tendsto_at_top hnat _ (has_sum_iff_tendsto_nat.1 hr) } end lemma summable_iff_not_tendsto_nat_at_top {f : ℕ → ℝ≥0} : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top] lemma summable_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply summable_iff_not_tendsto_nat_at_top.2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ≥0} {c : ℝ≥0} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := tsum_le_of_sum_range_le (summable_of_sum_range_le h) h lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ≥0} (hf : summable f) {i : β → α} (hi : function.injective i) : ∑' x, f (i x) ≤ ∑' x, f x := tsum_le_tsum_of_inj i hi (λ c hc, zero_le _) (λ b, le_rfl) (summable_comp_injective hf hi) hf lemma summable_sigma {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ≥0} : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := begin split, { simp only [← nnreal.summable_coe, nnreal.coe_tsum], exact λ h, ⟨h.sigma_factor, h.sigma⟩ }, { rintro ⟨h₁, h₂⟩, simpa only [← ennreal.tsum_coe_ne_top_iff_summable, ennreal.tsum_sigma', ennreal.coe_tsum, h₁] using h₂ } end lemma indicator_summable {f : α → ℝ≥0} (hf : summable f) (s : set α) : summable (s.indicator f) := begin refine nnreal.summable_of_le (λ a, le_trans (le_of_eq (s.indicator_apply f a)) _) hf, split_ifs, exact le_refl (f a), exact zero_le_coe, end lemma tsum_indicator_ne_zero {f : α → ℝ≥0} (hf : summable f) {s : set α} (h : ∃ a ∈ s, f a ≠ 0) : ∑' x, (s.indicator f) x ≠ 0 := λ h', let ⟨a, ha, hap⟩ := h in hap (trans (set.indicator_apply_eq_self.mpr (absurd ha)).symm (((tsum_eq_zero_iff (indicator_summable hf s)).1 h') a)) open finset /-- For `f : ℕ → ℝ≥0`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin rw ← tendsto_coe, convert tendsto_sum_nat_add (λ i, (f i : ℝ)), norm_cast, end lemma has_sum_lt {f g : α → ℝ≥0} {sf sg : ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hf : has_sum f sf) (hg : has_sum g sg) : sf < sg := begin have A : ∀ (a : α), (f a : ℝ) ≤ g a := λ a, nnreal.coe_le_coe.2 (h a), have : (sf : ℝ) < sg := has_sum_lt A (nnreal.coe_lt_coe.2 hi) (has_sum_coe.2 hf) (has_sum_coe.2 hg), exact nnreal.coe_lt_coe.1 this end @[mono] lemma has_sum_strict_mono {f g : α → ℝ≥0} {sf sg : ℝ≥0} (hf : has_sum f sf) (hg : has_sum g sg) (h : f < g) : sf < sg := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg lemma tsum_lt_tsum {f g : α → ℝ≥0} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hg : summable g) : ∑' n, f n < ∑' n, g n := has_sum_lt h hi (summable_of_le h hg).has_sum hg.has_sum @[mono] lemma tsum_strict_mono {f g : α → ℝ≥0} (hg : summable g) (h : f < g) : ∑' n, f n < ∑' n, g n := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hg lemma tsum_pos {g : α → ℝ≥0} (hg : summable g) (i : α) (hi : 0 < g i) : 0 < ∑' b, g b := by { rw ← tsum_zero, exact tsum_lt_tsum (λ a, zero_le _) hi hg } lemma tsum_eq_add_tsum_ite {f : α → ℝ≥0} (hf : summable f) (i : α) : ∑' x, f x = f i + ∑' x, ite (x = i) 0 (f x) := begin refine tsum_eq_add_tsum_ite' i (nnreal.summable_of_le (λ i', _) hf), rw [function.update_apply], split_ifs; simp only [zero_le', le_rfl] end end nnreal namespace ennreal lemma tsum_to_nnreal_eq {f : α → ℝ≥0∞} (hf : ∀ a, f a ≠ ∞) : (∑' a, f a).to_nnreal = ∑' a, (f a).to_nnreal := (congr_arg ennreal.to_nnreal (tsum_congr $ λ x, (coe_to_nnreal (hf x)).symm)).trans nnreal.tsum_eq_to_nnreal_tsum.symm lemma tsum_to_real_eq {f : α → ℝ≥0∞} (hf : ∀ a, f a ≠ ∞) : (∑' a, f a).to_real = ∑' a, (f a).to_real := by simp only [ennreal.to_real, tsum_to_nnreal_eq hf, nnreal.coe_tsum] lemma tendsto_sum_nat_add (f : ℕ → ℝ≥0∞) (hf : ∑' i, f i ≠ ∞) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin lift f to ℕ → ℝ≥0 using ennreal.ne_top_of_tsum_ne_top hf, replace hf : summable f := tsum_coe_ne_top_iff_summable.1 hf, simp only [← ennreal.coe_tsum, nnreal.summable_nat_add _ hf, ← ennreal.coe_zero], exact_mod_cast nnreal.tendsto_sum_nat_add f end lemma tsum_le_of_sum_range_le {f : ℕ → ℝ≥0∞} {c : ℝ≥0∞} (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := tsum_le_of_sum_range_le ennreal.summable h lemma has_sum_lt {f g : α → ℝ≥0∞} {sf sg : ℝ≥0∞} {i : α} (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) (hsf : sf ≠ ⊤) (hf : has_sum f sf) (hg : has_sum g sg) : sf < sg := begin by_cases hsg : sg = ⊤, { exact hsg.symm ▸ lt_of_le_of_ne le_top hsf }, { have hg' : ∀ x, g x ≠ ⊤:= ennreal.ne_top_of_tsum_ne_top (hg.tsum_eq.symm ▸ hsg), lift f to α → ℝ≥0 using λ x, ne_of_lt (lt_of_le_of_lt (h x) $ lt_of_le_of_ne le_top (hg' x)), lift g to α → ℝ≥0 using hg', lift sf to ℝ≥0 using hsf, lift sg to ℝ≥0 using hsg, simp only [coe_le_coe, coe_lt_coe] at h hi ⊢, exact nnreal.has_sum_lt h hi (ennreal.has_sum_coe.1 hf) (ennreal.has_sum_coe.1 hg) } end lemma tsum_lt_tsum {f g : α → ℝ≥0∞} {i : α} (hfi : tsum f ≠ ⊤) (h : ∀ (a : α), f a ≤ g a) (hi : f i < g i) : ∑' x, f x < ∑' x, g x := has_sum_lt h hi hfi ennreal.summable.has_sum ennreal.summable.has_sum end ennreal lemma tsum_comp_le_tsum_of_inj {β : Type*} {f : α → ℝ} (hf : summable f) (hn : ∀ a, 0 ≤ f a) {i : β → α} (hi : function.injective i) : tsum (f ∘ i) ≤ tsum f := begin lift f to α → ℝ≥0 using hn, rw nnreal.summable_coe at hf, simpa only [(∘), ← nnreal.coe_tsum] using nnreal.tsum_comp_le_tsum_of_inj hf hi end /-- Comparison test of convergence of series of non-negative real numbers. -/ lemma summable_of_nonneg_of_le {f g : β → ℝ} (hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : summable f) : summable g := begin lift f to β → ℝ≥0 using λ b, (hg b).trans (hgf b), lift g to β → ℝ≥0 using hg, rw nnreal.summable_coe at hf ⊢, exact nnreal.summable_of_le (λ b, nnreal.coe_le_coe.1 (hgf b)) hf end lemma summable.to_nnreal {f : α → ℝ} (hf : summable f) : summable (λ n, (f n).to_nnreal) := begin apply nnreal.summable_coe.1, refine summable_of_nonneg_of_le (λ n, nnreal.coe_nonneg _) (λ n, _) hf.abs, simp only [le_abs_self, real.coe_to_nnreal', max_le_iff, abs_nonneg, and_self] end /-- A series of non-negative real numbers converges to `r` in the sense of `has_sum` if and only if the sequence of partial sum converges to `r`. -/ lemma has_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) : has_sum f r ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top (𝓝 r) := begin lift f to ℕ → ℝ≥0 using hf, simp only [has_sum, ← nnreal.coe_sum, nnreal.tendsto_coe'], exact exists_congr (λ hr, nnreal.has_sum_iff_tendsto_nat) end lemma ennreal.of_real_tsum_of_nonneg {f : α → ℝ} (hf_nonneg : ∀ n, 0 ≤ f n) (hf : summable f) : ennreal.of_real (∑' n, f n) = ∑' n, ennreal.of_real (f n) := by simp_rw [ennreal.of_real, ennreal.tsum_coe_eq (nnreal.has_sum_real_to_nnreal_of_nonneg hf_nonneg hf)] lemma not_summable_iff_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : ¬ summable f ↔ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := begin lift f to ℕ → ℝ≥0 using hf, exact_mod_cast nnreal.not_summable_iff_tendsto_nat_at_top end lemma summable_iff_not_tendsto_nat_at_top_of_nonneg {f : ℕ → ℝ} (hf : ∀ n, 0 ≤ f n) : summable f ↔ ¬ tendsto (λ n : ℕ, ∑ i in finset.range n, f i) at_top at_top := by rw [← not_iff_not, not_not, not_summable_iff_tendsto_nat_at_top_of_nonneg hf] lemma summable_sigma_of_nonneg {β : Π x : α, Type*} {f : (Σ x, β x) → ℝ} (hf : ∀ x, 0 ≤ f x) : summable f ↔ (∀ x, summable (λ y, f ⟨x, y⟩)) ∧ summable (λ x, ∑' y, f ⟨x, y⟩) := by { lift f to (Σ x, β x) → ℝ≥0 using hf, exact_mod_cast nnreal.summable_sigma } lemma summable_of_sum_le {ι : Type*} {f : ι → ℝ} {c : ℝ} (hf : 0 ≤ f) (h : ∀ u : finset ι, ∑ x in u, f x ≤ c) : summable f := ⟨ ⨆ u : finset ι, ∑ x in u, f x, tendsto_at_top_csupr (finset.sum_mono_set_of_nonneg hf) ⟨c, λ y ⟨u, hu⟩, hu ▸ h u⟩ ⟩ lemma summable_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : summable f := begin apply (summable_iff_not_tendsto_nat_at_top_of_nonneg hf).2 (λ H, _), rcases exists_lt_of_tendsto_at_top H 0 c with ⟨n, -, hn⟩, exact lt_irrefl _ (hn.trans_le (h n)), end lemma real.tsum_le_of_sum_range_le {f : ℕ → ℝ} {c : ℝ} (hf : ∀ n, 0 ≤ f n) (h : ∀ n, ∑ i in finset.range n, f i ≤ c) : ∑' n, f n ≤ c := tsum_le_of_sum_range_le (summable_of_sum_range_le hf h) h /-- If a sequence `f` with non-negative terms is dominated by a sequence `g` with summable series and at least one term of `f` is strictly smaller than the corresponding term in `g`, then the series of `f` is strictly smaller than the series of `g`. -/ lemma tsum_lt_tsum_of_nonneg {i : ℕ} {f g : ℕ → ℝ} (h0 : ∀ (b : ℕ), 0 ≤ f b) (h : ∀ (b : ℕ), f b ≤ g b) (hi : f i < g i) (hg : summable g) : ∑' n, f n < ∑' n, g n := tsum_lt_tsum h hi (summable_of_nonneg_of_le h0 h hg) hg section variables [emetric_space β] open ennreal filter emetric /-- In an emetric ball, the distance between points is everywhere finite -/ lemma edist_ne_top_of_mem_ball {a : β} {r : ℝ≥0∞} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ := lt_top_iff_ne_top.1 $ calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a ... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2 ... ≤ ⊤ : le_top /-- Each ball in an extended metric space gives us a metric space, as the edist is everywhere finite. -/ def metric_space_emetric_ball (a : β) (r : ℝ≥0∞) : metric_space (ball a r) := emetric_space.to_metric_space edist_ne_top_of_mem_ball local attribute [instance] metric_space_emetric_ball lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ℝ≥0∞) (h : x ∈ ball a r) : 𝓝 x = map (coe : ball a r → β) (𝓝 ⟨x, h⟩) := (map_nhds_subtype_coe_eq _ $ is_open.mem_nhds emetric.is_open_ball h).symm end section variable [pseudo_emetric_space α] open emetric lemma tendsto_iff_edist_tendsto_0 {l : filter β} {f : β → α} {y : α} : tendsto f l (𝓝 y) ↔ tendsto (λ x, edist (f x) y) l (𝓝 0) := by simp only [emetric.nhds_basis_eball.tendsto_right_iff, emetric.mem_ball, @tendsto_order ℝ≥0∞ β _ _, forall_prop_of_false ennreal.not_lt_zero, forall_const, true_and] /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma emetric.cauchy_seq_iff_le_tendsto_0 [nonempty β] [semilattice_sup β] {s : β → α} : cauchy_seq s ↔ (∃ (b: β → ℝ≥0∞), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N) ∧ (tendsto b at_top (𝓝 0))) := ⟨begin assume hs, rw emetric.cauchy_seq_iff at hs, /- `s` is Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/ let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}), --Prove that it bounds the distances of points in the Cauchy sequence have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, { refine λm n N hm hn, le_Sup _, use (prod.mk m n), simp only [and_true, eq_self_iff_true, set.mem_set_of_eq], exact ⟨hm, hn⟩ }, --Prove that it tends to `0`, by using the Cauchy property of `s` have D : tendsto b at_top (𝓝 0), { refine tendsto_order.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩, rcases exists_between εpos with ⟨δ, δpos, δlt⟩, rcases hs δ δpos with ⟨N, hN⟩, refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩, have : b n ≤ δ := Sup_le begin simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists], intros d p q hp hq hd, rw ← hd, exact le_of_lt (hN p (le_trans hn hp) q (le_trans hn hq)) end, simpa using lt_of_le_of_lt this δlt }, -- Conclude exact ⟨b, ⟨C, D⟩⟩ end, begin rintros ⟨b, ⟨b_bound, b_lim⟩⟩, /-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, b_lim : tendsto b at_top (𝓝 0)-/ refine emetric.cauchy_seq_iff.2 (λε εpos, _), have : ∀ᶠ n in at_top, b n < ε := (tendsto_order.1 b_lim ).2 _ εpos, rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩, exact ⟨N, λ m hm n hn, calc edist (s m) (s n) ≤ b N : b_bound m n N hm hn ... < ε : (hN _ (le_refl N)) ⟩ end⟩ lemma continuous_of_le_add_edist {f : α → ℝ≥0∞} (C : ℝ≥0∞) (hC : C ≠ ⊤) (h : ∀ x y, f x ≤ f y + C * edist x y) : continuous f := begin rcases eq_or_ne C 0 with (rfl|C0), { simp only [zero_mul, add_zero] at h, exact continuous_of_const (λ x y, le_antisymm (h _ _) (h _ _)) }, { refine continuous_iff_continuous_at.2 (λ x, _), by_cases hx : f x = ∞, { have : f =ᶠ[𝓝 x] (λ _, ∞), { filter_upwards [emetric.ball_mem_nhds x ennreal.coe_lt_top], refine λ y (hy : edist y x < ⊤), _, rw edist_comm at hy, simpa [hx, ennreal.mul_ne_top hC hy.ne] using h x y }, exact this.continuous_at }, { refine (ennreal.tendsto_nhds hx).2 (λ ε (ε0 : 0 < ε), _), filter_upwards [emetric.closed_ball_mem_nhds x (ennreal.div_pos_iff.2 ⟨ε0.ne', hC⟩)], have hεC : C * (ε / C) = ε := ennreal.mul_div_cancel' C0 hC, refine λ y (hy : edist y x ≤ ε / C), ⟨tsub_le_iff_right.2 _, _⟩, { rw edist_comm at hy, calc f x ≤ f y + C * edist x y : h x y ... ≤ f y + C * (ε / C) : add_le_add_left (mul_le_mul_left' hy C) (f y) ... = f y + ε : by rw hεC }, { calc f y ≤ f x + C * edist y x : h y x ... ≤ f x + C * (ε / C) : add_le_add_left (mul_le_mul_left' hy C) (f x) ... = f x + ε : by rw hεC } } } end theorem continuous_edist : continuous (λp:α×α, edist p.1 p.2) := begin apply continuous_of_le_add_edist 2 (by norm_num), rintros ⟨x, y⟩ ⟨x', y'⟩, calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _ ... = edist x' y' + (edist x x' + edist y y') : by simp [edist_comm]; cc ... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) : add_le_add_left (add_le_add (le_max_left _ _) (le_max_right _ _)) _ ... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm] end @[continuity] theorem continuous.edist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) := continuous_edist.comp (hf.prod_mk hg : _) theorem filter.tendsto.edist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, edist (f x) (g x)) x (𝓝 (edist a b)) := (continuous_edist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma cauchy_seq_of_edist_le_of_tsum_ne_top {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) (hd : tsum d ≠ ∞) : cauchy_seq f := begin lift d to (ℕ → nnreal) using (λ i, ennreal.ne_top_of_tsum_ne_top hd i), rw ennreal.tsum_coe_ne_top_iff_summable at hd, exact cauchy_seq_of_edist_le_of_summable d hf hd end lemma emetric.is_closed_ball {a : α} {r : ℝ≥0∞} : is_closed (closed_ball a r) := is_closed_le (continuous_id.edist continuous_const) continuous_const @[simp] lemma emetric.diam_closure (s : set α) : diam (closure s) = diam s := begin refine le_antisymm (diam_le $ λ x hx y hy, _) (diam_mono subset_closure), have : edist x y ∈ closure (Iic (diam s)), from map_mem_closure₂ continuous_edist hx hy (λ x hx y hy, edist_le_diam_of_mem hx hy), rwa closure_Iic at this end @[simp] lemma metric.diam_closure {α : Type*} [pseudo_metric_space α] (s : set α) : metric.diam (closure s) = diam s := by simp only [metric.diam, emetric.diam_closure] lemma is_closed_set_of_lipschitz_on_with {α β} [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) (s : set α) : is_closed {f : α → β | lipschitz_on_with K f s} := begin simp only [lipschitz_on_with, set_of_forall], refine is_closed_bInter (λ x hx, is_closed_bInter $ λ y hy, is_closed_le _ _), exacts [continuous.edist (continuous_apply x) (continuous_apply y), continuous_const] end lemma is_closed_set_of_lipschitz_with {α β} [pseudo_emetric_space α] [pseudo_emetric_space β] (K : ℝ≥0) : is_closed {f : α → β | lipschitz_with K f} := by simp only [← lipschitz_on_univ, is_closed_set_of_lipschitz_on_with] namespace real /-- For a bounded set `s : set ℝ`, its `emetric.diam` is equal to `Sup s - Inf s` reinterpreted as `ℝ≥0∞`. -/ lemma ediam_eq {s : set ℝ} (h : bounded s) : emetric.diam s = ennreal.of_real (Sup s - Inf s) := begin rcases eq_empty_or_nonempty s with rfl|hne, { simp }, refine le_antisymm (metric.ediam_le_of_forall_dist_le $ λ x hx y hy, _) _, { have := real.subset_Icc_Inf_Sup_of_bounded h, exact real.dist_le_of_mem_Icc (this hx) (this hy) }, { apply ennreal.of_real_le_of_le_to_real, rw [← metric.diam, ← metric.diam_closure], have h' := real.bounded_iff_bdd_below_bdd_above.1 h, calc Sup s - Inf s ≤ dist (Sup s) (Inf s) : le_abs_self _ ... ≤ diam (closure s) : dist_le_diam_of_mem h.closure (cSup_mem_closure hne h'.2) (cInf_mem_closure hne h'.1) } end /-- For a bounded set `s : set ℝ`, its `metric.diam` is equal to `Sup s - Inf s`. -/ lemma diam_eq {s : set ℝ} (h : bounded s) : metric.diam s = Sup s - Inf s := begin rw [metric.diam, real.ediam_eq h, ennreal.to_real_of_real], rw real.bounded_iff_bdd_below_bdd_above at h, exact sub_nonneg.2 (real.Inf_le_Sup s h.1 h.2) end @[simp] lemma ediam_Ioo (a b : ℝ) : emetric.diam (Ioo a b) = ennreal.of_real (b - a) := begin rcases le_or_lt b a with h|h, { simp [h] }, { rw [real.ediam_eq (bounded_Ioo _ _), cSup_Ioo h, cInf_Ioo h] }, end @[simp] lemma ediam_Icc (a b : ℝ) : emetric.diam (Icc a b) = ennreal.of_real (b - a) := begin rcases le_or_lt a b with h|h, { rw [real.ediam_eq (bounded_Icc _ _), cSup_Icc h, cInf_Icc h] }, { simp [h, h.le] } end @[simp] lemma ediam_Ico (a b : ℝ) : emetric.diam (Ico a b) = ennreal.of_real (b - a) := le_antisymm (ediam_Icc a b ▸ diam_mono Ico_subset_Icc_self) (ediam_Ioo a b ▸ diam_mono Ioo_subset_Ico_self) @[simp] lemma ediam_Ioc (a b : ℝ) : emetric.diam (Ioc a b) = ennreal.of_real (b - a) := le_antisymm (ediam_Icc a b ▸ diam_mono Ioc_subset_Icc_self) (ediam_Ioo a b ▸ diam_mono Ioo_subset_Ioc_self) lemma diam_Icc {a b : ℝ} (h : a ≤ b) : metric.diam (Icc a b) = b - a := by simp [metric.diam, ennreal.to_real_of_real, sub_nonneg.2 h] lemma diam_Ico {a b : ℝ} (h : a ≤ b) : metric.diam (Ico a b) = b - a := by simp [metric.diam, ennreal.to_real_of_real, sub_nonneg.2 h] lemma diam_Ioc {a b : ℝ} (h : a ≤ b) : metric.diam (Ioc a b) = b - a := by simp [metric.diam, ennreal.to_real_of_real, sub_nonneg.2 h] lemma diam_Ioo {a b : ℝ} (h : a ≤ b) : metric.diam (Ioo a b) = b - a := by simp [metric.diam, ennreal.to_real_of_real, sub_nonneg.2 h] end real /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`, then the distance from `f n` to the limit is bounded by `∑'_{k=n}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) (n : ℕ) : edist (f n) a ≤ ∑' m, d (n + m) := begin refine le_of_tendsto (tendsto_const_nhds.edist ha) (mem_at_top_sets.2 ⟨n, λ m hnm, _⟩), refine le_trans (edist_le_Ico_sum_of_edist_le hnm (λ k _ _, hf k)) _, rw [finset.sum_Ico_eq_sum_range], exact sum_le_tsum _ (λ _ _, zero_le _) ennreal.summable end /-- If `edist (f n) (f (n+1))` is bounded above by a function `d : ℕ → ℝ≥0∞`, then the distance from `f 0` to the limit is bounded by `∑'_{k=0}^∞ d k`. -/ lemma edist_le_tsum_of_edist_le_of_tendsto₀ {f : ℕ → α} (d : ℕ → ℝ≥0∞) (hf : ∀ n, edist (f n) (f n.succ) ≤ d n) {a : α} (ha : tendsto f at_top (𝓝 a)) : edist (f 0) a ≤ ∑' m, d m := by simpa using edist_le_tsum_of_edist_le_of_tendsto d hf ha 0 end --section
28e42e56a56b302616379e07d1842d529d5c2cee
46125763b4dbf50619e8846a1371029346f4c3db
/src/topology/dense_embedding.lean
d1067645773cd5379d7aa211eace36ac5c642772
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
14,573
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot -/ import topology.separation /-! # Dense embeddings This file defines three properties of functions: * `dense_range f` means `f` has dense image; * `dense_inducing i` means `i` is also `inducing`; * `dense_embedding e` means `e` is also an `embedding`. The main theorem `continuous_extend` gives a criterion for a function `f : X → Z` to a regular (T₃) space Z to extend along a dense embedding `i : X → Y` to a continuous function `g : Y → Z`. Actually `i` only has to be `dense_inducing` (not necessarily injective). -/ noncomputable theory open set filter lattice open_locale classical topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section dense_range variables [topological_space β] [topological_space γ] (f : α → β) (g : β → γ) /-- `f : α → β` has dense range if its range (image) is a dense subset of β. -/ def dense_range := ∀ x, x ∈ closure (range f) variables {f} lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ := eq_univ_iff_forall.symm lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ := eq_univ_iff_forall.mpr h lemma dense_range.comp (hg : dense_range g) (hf : dense_range f) (cg : continuous g) : dense_range (g ∘ f) := begin have : g '' (closure $ range f) ⊆ closure (g '' range f), from image_closure_subset_closure_image cg, have : closure (g '' closure (range f)) ⊆ closure (g '' range f), by simpa [closure_closure] using (closure_mono this), intro c, rw range_comp, apply this, rw [hf.closure_range, image_univ], exact hg c end /-- If `f : α → β` has dense range and `β` contains some element, then `α` must too. -/ def dense_range.inhabited (df : dense_range f) (b : β) : inhabited α := ⟨classical.choice $ by simpa only [univ_inter, range_nonempty_iff_nonempty] using mem_closure_iff.1 (df b) _ is_open_univ trivial⟩ lemma dense_range.nonempty (hf : dense_range f) : nonempty α ↔ nonempty β := ⟨nonempty.map f, λ ⟨b⟩, @nonempty_of_inhabited _ (hf.inhabited b)⟩ lemma dense_range.prod {ι : Type*} {κ : Type*} {f : ι → β} {g : κ → γ} (hf : dense_range f) (hg : dense_range g) : dense_range (λ p : ι × κ, (f p.1, g p.2)) := have closure (range $ λ p : ι×κ, (f p.1, g p.2)) = set.prod (closure $ range f) (closure $ range g), by rw [←closure_prod_eq, prod_range_range_eq], assume ⟨b, d⟩, this.symm ▸ mem_prod.2 ⟨hf _, hg _⟩ end dense_range /-- `i : α → β` is "dense inducing" if it has dense range and the topology on `α` is the one induced by `i` from the topology on `β`. -/ structure dense_inducing [topological_space α] [topological_space β] (i : α → β) extends inducing i : Prop := (dense : dense_range i) namespace dense_inducing variables [topological_space α] [topological_space β] variables {i : α → β} (di : dense_inducing i) lemma nhds_eq_comap (di : dense_inducing i) : ∀ a : α, 𝓝 a = comap i (𝓝 $ i a) := di.to_inducing.nhds_eq_comap protected lemma continuous (di : dense_inducing i) : continuous i := di.to_inducing.continuous lemma closure_range : closure (range i) = univ := di.dense.closure_range lemma self_sub_closure_image_preimage_of_open {s : set β} (di : dense_inducing i) : is_open s → s ⊆ closure (i '' (i ⁻¹' s)) := begin intros s_op b b_in_s, rw [image_preimage_eq_inter_range, mem_closure_iff], intros U U_op b_in, rw ←inter_assoc, exact (dense_iff_inter_open.1 di.closure_range) _ (is_open_inter U_op s_op) ⟨b, b_in, b_in_s⟩ end lemma closure_image_nhds_of_nhds {s : set α} {a : α} (di : dense_inducing i) : s ∈ 𝓝 a → closure (i '' s) ∈ 𝓝 (i a) := begin rw [di.nhds_eq_comap a, mem_comap_sets], intro h, rcases h with ⟨t, t_nhd, sub⟩, rw mem_nhds_sets_iff at t_nhd, rcases t_nhd with ⟨U, U_sub, ⟨U_op, e_a_in_U⟩⟩, have := calc i ⁻¹' U ⊆ i⁻¹' t : preimage_mono U_sub ... ⊆ s : sub, have := calc U ⊆ closure (i '' (i ⁻¹' U)) : self_sub_closure_image_preimage_of_open di U_op ... ⊆ closure (i '' s) : closure_mono (image_subset i this), have U_nhd : U ∈ 𝓝 (i a) := mem_nhds_sets U_op e_a_in_U, exact (𝓝 (i a)).sets_of_superset U_nhd this end /-- The product of two dense inducings is a dense inducing -/ protected lemma prod [topological_space γ] [topological_space δ] {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_inducing e₁) (de₂ : dense_inducing e₂) : dense_inducing (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { induced := (de₁.to_inducing.prod_mk de₂.to_inducing).induced, dense := de₁.dense.prod de₂.dense } variables [topological_space δ] {f : γ → α} {g : γ → δ} {h : δ → β} /-- γ -f→ α g↓ ↓e δ -h→ β -/ lemma tendsto_comap_nhds_nhds {d : δ} {a : α} (di : dense_inducing i) (H : tendsto h (𝓝 d) (𝓝 (i a))) (comm : h ∘ g = i ∘ f) : tendsto f (comap g (𝓝 d)) (𝓝 a) := begin have lim1 : map g (comap g (𝓝 d)) ≤ 𝓝 d := map_comap_le, replace lim1 : map h (map g (comap g (𝓝 d))) ≤ map h (𝓝 d) := map_mono lim1, rw [filter.map_map, comm, ← filter.map_map, map_le_iff_le_comap] at lim1, have lim2 : comap i (map h (𝓝 d)) ≤ comap i (𝓝 (i a)) := comap_mono H, rw ← di.nhds_eq_comap at lim2, exact le_trans lim1 lim2, end protected lemma nhds_inf_ne_bot (di : dense_inducing i) {b : β} : 𝓝 b ⊓ principal (range i) ≠ ⊥ := begin convert di.dense b, simp [closure_eq_nhds] end lemma comap_nhds_ne_bot (di : dense_inducing i) {b : β} : comap i (𝓝 b) ≠ ⊥ := comap_ne_bot $ λ s hs, let ⟨_, ⟨ha, a, rfl⟩⟩ := mem_closure_iff_nhds.1 (di.dense b) s hs in ⟨a, ha⟩ variables [topological_space γ] /-- If `i : α → β` is a dense inducing, then any function `f : α → γ` "extends" to a function `g = extend di f : β → γ`. If `γ` is Hausdorff and `f` has a continuous extension, then `g` is the unique such extension. In general, `g` might not be continuous or even extend `f`. -/ def extend (di : dense_inducing i) (f : α → γ) (b : β) : γ := @lim _ _ ⟨f (dense_range.inhabited di.dense b).default⟩ (map f (comap i (𝓝 b))) lemma extend_eq [t2_space γ] {b : β} {c : γ} {f : α → γ} (hf : map f (comap i (𝓝 b)) ≤ 𝓝 c) : di.extend f b = c := @lim_eq _ _ (id _) _ _ _ (by simp; exact comap_nhds_ne_bot di) hf lemma extend_e_eq [t2_space γ] {f : α → γ} (a : α) (hf : continuous_at f a) : di.extend f (i a) = f a := extend_eq _ $ di.nhds_eq_comap a ▸ hf lemma extend_eq_of_cont [t2_space γ] {f : α → γ} (hf : continuous f) (a : α) : di.extend f (i a) = f a := di.extend_e_eq a (continuous_iff_continuous_at.1 hf a) lemma tendsto_extend [regular_space γ] {b : β} {f : α → γ} (di : dense_inducing i) (hf : {b | ∃c, tendsto f (comap i $ 𝓝 b) (𝓝 c)} ∈ 𝓝 b) : tendsto (di.extend f) (𝓝 b) (𝓝 (di.extend f b)) := let φ := {b | tendsto f (comap i $ 𝓝 b) (𝓝 $ di.extend f b)} in have hφ : φ ∈ 𝓝 b, from (𝓝 b).sets_of_superset hf $ assume b ⟨c, hc⟩, show tendsto f (comap i (𝓝 b)) (𝓝 (di.extend f b)), from (di.extend_eq hc).symm ▸ hc, assume s hs, let ⟨s'', hs''₁, hs''₂, hs''₃⟩ := nhds_is_closed hs in let ⟨s', hs'₁, (hs'₂ : i ⁻¹' s' ⊆ f ⁻¹' s'')⟩ := mem_of_nhds hφ hs''₁ in let ⟨t, (ht₁ : t ⊆ φ ∩ s'), ht₂, ht₃⟩ := mem_nhds_sets_iff.mp $ inter_mem_sets hφ hs'₁ in have h₁ : closure (f '' (i ⁻¹' s')) ⊆ s'', by rw [closure_subset_iff_subset_of_is_closed hs''₃, image_subset_iff]; exact hs'₂, have h₂ : t ⊆ di.extend f ⁻¹' closure (f '' (i ⁻¹' t)), from assume b' hb', have 𝓝 b' ≤ principal t, by simp; exact mem_nhds_sets ht₂ hb', have map f (comap i (𝓝 b')) ≤ 𝓝 (di.extend f b') ⊓ principal (f '' (i ⁻¹' t)), from calc _ ≤ map f (comap i (𝓝 b' ⊓ principal t)) : map_mono $ comap_mono $ le_inf (le_refl _) this ... ≤ map f (comap i (𝓝 b')) ⊓ map f (comap i (principal t)) : le_inf (map_mono $ comap_mono $ inf_le_left) (map_mono $ comap_mono $ inf_le_right) ... ≤ map f (comap i (𝓝 b')) ⊓ principal (f '' (i ⁻¹' t)) : by simp [le_refl] ... ≤ _ : inf_le_inf ((ht₁ hb').left) (le_refl _), show di.extend f b' ∈ closure (f '' (i ⁻¹' t)), begin rw [closure_eq_nhds], apply ne_bot_of_le_ne_bot _ this, simp, exact di.comap_nhds_ne_bot end, (𝓝 b).sets_of_superset (show t ∈ 𝓝 b, from mem_nhds_sets ht₂ ht₃) (calc t ⊆ di.extend f ⁻¹' closure (f '' (i ⁻¹' t)) : h₂ ... ⊆ di.extend f ⁻¹' closure (f '' (i ⁻¹' s')) : preimage_mono $ closure_mono $ image_subset f $ preimage_mono $ subset.trans ht₁ $ inter_subset_right _ _ ... ⊆ di.extend f ⁻¹' s'' : preimage_mono h₁ ... ⊆ di.extend f ⁻¹' s : preimage_mono hs''₂) lemma continuous_extend [regular_space γ] {f : α → γ} (di : dense_inducing i) (hf : ∀b, ∃c, tendsto f (comap i (𝓝 b)) (𝓝 c)) : continuous (di.extend f) := continuous_iff_continuous_at.mpr $ assume b, di.tendsto_extend $ univ_mem_sets' hf lemma mk' (i : α → β) (c : continuous i) (dense : ∀x, x ∈ closure (range i)) (H : ∀ (a:α) s ∈ 𝓝 a, ∃t ∈ 𝓝 (i a), ∀ b, i b ∈ t → b ∈ s) : dense_inducing i := { induced := (induced_iff_nhds_eq i).2 $ λ a, le_antisymm (tendsto_iff_comap.1 $ c.tendsto _) (by simpa [le_def] using H a), dense := dense } end dense_inducing /-- A dense embedding is an embedding with dense image. -/ structure dense_embedding [topological_space α] [topological_space β] (e : α → β) extends dense_inducing e : Prop := (inj : function.injective e) theorem dense_embedding.mk' [topological_space α] [topological_space β] (e : α → β) (c : continuous e) (dense : ∀x, x ∈ closure (range e)) (inj : function.injective e) (H : ∀ (a:α) s ∈ 𝓝 a, ∃t ∈ 𝓝 (e a), ∀ b, e b ∈ t → b ∈ s) : dense_embedding e := { inj := inj, ..dense_inducing.mk' e c dense H} namespace dense_embedding variables [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] variables {e : α → β} (de : dense_embedding e) lemma inj_iff {x y} : e x = e y ↔ x = y := de.inj.eq_iff lemma to_embedding : embedding e := { induced := de.induced, inj := de.inj } /-- The product of two dense embeddings is a dense embedding -/ protected lemma prod {e₁ : α → β} {e₂ : γ → δ} (de₁ : dense_embedding e₁) (de₂ : dense_embedding e₂) : dense_embedding (λ(p : α × γ), (e₁ p.1, e₂ p.2)) := { inj := assume ⟨x₁, x₂⟩ ⟨y₁, y₂⟩, by simp; exact assume h₁ h₂, ⟨de₁.inj h₁, de₂.inj h₂⟩, ..dense_inducing.prod de₁.to_dense_inducing de₂.to_dense_inducing } /-- The dense embedding of a subtype inside its closure. -/ def subtype_emb {α : Type*} (p : α → Prop) (e : α → β) (x : {x // p x}) : {x // x ∈ closure (e '' {x | p x})} := ⟨e x.1, subset_closure $ mem_image_of_mem e x.2⟩ protected lemma subtype (p : α → Prop) : dense_embedding (subtype_emb p e) := { dense_embedding . dense := assume ⟨x, hx⟩, closure_subtype.mpr $ have (λ (x : {x // p x}), e (x.val)) = e ∘ subtype.val, from rfl, begin rw ← image_univ, simp [(image_comp _ _ _).symm, (∘), subtype_emb, -image_univ], rw [this, image_comp, subtype.val_image], simp, assumption end, inj := assume ⟨x, hx⟩ ⟨y, hy⟩ h, subtype.eq $ de.inj $ @@congr_arg subtype.val h, induced := (induced_iff_nhds_eq _).2 (assume ⟨x, hx⟩, by simp [subtype_emb, nhds_subtype_eq_comap, de.to_inducing.nhds_eq_comap, comap_comap_comp, (∘)]) } end dense_embedding lemma is_closed_property [topological_space β] {e : α → β} {p : β → Prop} (he : dense_range e) (hp : is_closed {x | p x}) (h : ∀a, p (e a)) : ∀b, p b := have univ ⊆ {b | p b}, from calc univ = closure (range e) : he.closure_range.symm ... ⊆ closure {b | p b} : closure_mono $ range_subset_iff.mpr h ... = _ : closure_eq_of_is_closed hp, assume b, this trivial lemma is_closed_property2 [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) : ∀b₁ b₂, p b₁ b₂ := have ∀q:β×β, p q.1 q.2, from is_closed_property (he.prod he) hp $ λ _, h _ _, assume b₁ b₂, this ⟨b₁, b₂⟩ lemma is_closed_property3 [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) : ∀b₁ b₂ b₃, p b₁ b₂ b₃ := have ∀q:β×β×β, p q.1 q.2.1 q.2.2, from is_closed_property (he.prod $ he.prod he) hp $ λ _, h _ _ _, assume b₁ b₂ b₃, this ⟨b₁, b₂, b₃⟩ @[elab_as_eliminator] lemma dense_range.induction_on [topological_space β] {e : α → β} (he : dense_range e) {p : β → Prop} (b₀ : β) (hp : is_closed {b | p b}) (ih : ∀a:α, p $ e a) : p b₀ := is_closed_property he hp ih b₀ @[elab_as_eliminator] lemma dense_range.induction_on₂ [topological_space β] {e : α → β} {p : β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β | p q.1 q.2}) (h : ∀a₁ a₂, p (e a₁) (e a₂)) (b₁ b₂ : β) : p b₁ b₂ := is_closed_property2 he hp h _ _ @[elab_as_eliminator] lemma dense_range.induction_on₃ [topological_space β] {e : α → β} {p : β → β → β → Prop} (he : dense_range e) (hp : is_closed {q:β×β×β | p q.1 q.2.1 q.2.2}) (h : ∀a₁ a₂ a₃, p (e a₁) (e a₂) (e a₃)) (b₁ b₂ b₃ : β) : p b₁ b₂ b₃ := is_closed_property3 he hp h _ _ _ section variables [topological_space β] [topological_space γ] [t2_space γ] variables {f : α → β} /-- Two continuous functions to a t2-space that agree on the dense range of a function are equal. -/ lemma dense_range.equalizer (hfd : dense_range f) {g h : β → γ} (hg : continuous g) (hh : continuous h) (H : g ∘ f = h ∘ f) : g = h := funext $ λ y, hfd.induction_on y (is_closed_eq hg hh) $ congr_fun H end
8c3aa805a4721e549a72b99c71b0c3cc3409c09b
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/data/buffer_auto.lean
861db17dad61d827caa4cef117d621bc2be3e703
[]
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
4,652
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default universes u w u_1 namespace Mathlib def buffer (α : Type u) := sigma fun (n : ℕ) => array n α def mk_buffer {α : Type u} : buffer α := sigma.mk 0 (d_array.mk fun (i : fin 0) => fin.elim0 i) def array.to_buffer {α : Type u} {n : ℕ} (a : array n α) : buffer α := sigma.mk n a namespace buffer def nil {α : Type u} : buffer α := mk_buffer def size {α : Type u} (b : buffer α) : ℕ := sigma.fst b def to_array {α : Type u} (b : buffer α) : array (size b) α := sigma.snd b def push_back {α : Type u} : buffer α → α → buffer α := sorry def pop_back {α : Type u} : buffer α → buffer α := sorry def read {α : Type u} (b : buffer α) : fin (size b) → α := sorry def write {α : Type u} (b : buffer α) : fin (size b) → α → buffer α := sorry def read' {α : Type u} [Inhabited α] : buffer α → ℕ → α := sorry def write' {α : Type u} : buffer α → ℕ → α → buffer α := sorry theorem read_eq_read' {α : Type u} [Inhabited α] (b : buffer α) (i : ℕ) (h : i < size b) : read b { val := i, property := h } = read' b i := sorry theorem write_eq_write' {α : Type u} (b : buffer α) (i : ℕ) (h : i < size b) (v : α) : write b { val := i, property := h } v = write' b i v := sorry def to_list {α : Type u} (b : buffer α) : List α := array.to_list (to_array b) protected def to_string (b : buffer char) : string := list.as_string (array.to_list (to_array b)) def append_list {α : Type u} : buffer α → List α → buffer α := sorry def append_string (b : buffer char) (s : string) : buffer char := append_list b (string.to_list s) theorem lt_aux_1 {a : ℕ} {b : ℕ} {c : ℕ} (h : a + c < b) : a < b := lt_of_le_of_lt (nat.le_add_right a c) h theorem lt_aux_2 {n : ℕ} (h : n > 0) : n - 1 < n := (fun (h₁ : 1 > 0) => nat.sub_lt h h₁) (of_as_true trivial) theorem lt_aux_3 {n : ℕ} {i : ℕ} (h : i + 1 < n) : n - bit0 1 - i < n := sorry def append_array {α : Type u} {n : ℕ} (nz : n > 0) : buffer α → array n α → (i : ℕ) → i < n → buffer α := sorry protected def append {α : Type u} : buffer α → buffer α → buffer α := sorry def iterate {α : Type u} {β : Type w} (b : buffer α) : β → (fin (size b) → α → β → β) → β := sorry def foreach {α : Type u} (b : buffer α) : (fin (size b) → α → α) → buffer α := sorry /-- Monadically map a function over the buffer. -/ def mmap {α : Type u} {β : Type w} {m : Type w → Type u_1} [Monad m] (b : buffer α) (f : α → m β) : m (buffer β) := do let b' ← array.mmap (sigma.snd b) f return (array.to_buffer b') /-- Map a function over the buffer. -/ def map {α : Type u} {β : Type w} : buffer α → (α → β) → buffer β := sorry def foldl {α : Type u} {β : Type w} : buffer α → β → (α → β → β) → β := sorry def rev_iterate {α : Type u} {β : Type w} (b : buffer α) : β → (fin (size b) → α → β → β) → β := sorry def take {α : Type u} (b : buffer α) (n : ℕ) : buffer α := dite (n ≤ size b) (fun (h : n ≤ size b) => sigma.mk n (array.take (to_array b) n h)) fun (h : ¬n ≤ size b) => b def take_right {α : Type u} (b : buffer α) (n : ℕ) : buffer α := dite (n ≤ size b) (fun (h : n ≤ size b) => sigma.mk n (array.take_right (to_array b) n h)) fun (h : ¬n ≤ size b) => b def drop {α : Type u} (b : buffer α) (n : ℕ) : buffer α := dite (n ≤ size b) (fun (h : n ≤ size b) => sigma.mk (size b - n) (array.drop (to_array b) n h)) fun (h : ¬n ≤ size b) => b def reverse {α : Type u} (b : buffer α) : buffer α := sigma.mk (size b) (array.reverse (to_array b)) protected def mem {α : Type u} (v : α) (a : buffer α) := ∃ (i : fin (size a)), read a i = v protected instance has_mem {α : Type u} : has_mem α (buffer α) := has_mem.mk buffer.mem protected instance has_append {α : Type u} : Append (buffer α) := { append := buffer.append } protected instance has_repr {α : Type u} [has_repr α] : has_repr (buffer α) := has_repr.mk (repr ∘ to_list) end buffer def list.to_buffer {α : Type u} (l : List α) : buffer α := buffer.append_list mk_buffer l def char_buffer := buffer char /-- Convert a format object into a character buffer with the provided formatting options. -/ def string.to_char_buffer (s : string) : char_buffer := buffer.append_string buffer.nil s end Mathlib
7d23ae73a0f7886bd809b8dd20aa7d42550a85ca
88892181780ff536a81e794003fe058062f06758
/src/advent_of_code_2019/common.lean
b0964d3631778a769403a7408f3c2ad2f01be536
[]
no_license
AtnNn/lean-sandbox
fe2c44280444e8bb8146ab8ac391c82b480c0a2e
8c68afbdc09213173aef1be195da7a9a86060a97
refs/heads/master
1,623,004,395,876
1,579,969,507,000
1,579,969,507,000
146,666,368
0
0
null
null
null
null
UTF-8
Lean
false
false
987
lean
-- Some declarations borrowed or adapted from https://github.com/digama0/advent-of-code/blob/lean-3.4.1/common.lean import system.io data.buffer.parser data.buffer universe u open parser class read (α : Type) := (parser : parser α) def batch {α β : Type} [reader : read α] [has_to_string β] (f : α → β) := io.stdin >>= io.fs.read_to_end >>= λ (buffer : char_buffer) , match parser.run reader.parser buffer with | sum.inl error := io.print error | sum.inr res := io.print (f res) end instance nat.read : read ℕ := ⟨string.to_nat <$> many_char1 (sat char.is_digit)⟩ instance int.read : read ℤ := ⟨(ch '-' *> ((λ x, -↑x) <$> nat.read.parser)) <|> coe <$> nat.read.parser⟩ structure lines (α : Type) := (list : list α) instance lines.read {α : Type} [reader : read α] : read (lines α) := ⟨lines.mk <$> many (reader.parser <* ch '\n')⟩ def both {α β γ : Type} (f : α → β) (g : α → γ) (x : α) : β × γ := ⟨f x, g x⟩
044963061f3dbf44913abd176136bb0218b83f7b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/list/prime.lean
191bd08aa6ba34d80592527a43dcc45ff576b532
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,148
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker, Anne Baanen -/ import algebra.associated import data.list.big_operators.lemmas import data.list.perm /-! # Products of lists of prime elements. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains some theorems relating `prime` and products of `list`s. -/ open list section comm_monoid_with_zero variables {M : Type*} [comm_monoid_with_zero M] /-- Prime `p` divides the product of a list `L` iff it divides some `a ∈ L` -/ lemma prime.dvd_prod_iff {p : M} {L : list M} (pp : prime p) : p ∣ L.prod ↔ ∃ a ∈ L, p ∣ a := begin split, { intros h, induction L with L_hd L_tl L_ih, { rw prod_nil at h, exact absurd h pp.not_dvd_one }, { rw prod_cons at h, cases pp.dvd_or_dvd h with hd hd, { exact ⟨L_hd, mem_cons_self L_hd L_tl, hd⟩ }, { obtain ⟨x, hx1, hx2⟩ := L_ih hd, exact ⟨x, mem_cons_of_mem L_hd hx1, hx2⟩ } } }, { exact λ ⟨a, ha1, ha2⟩, dvd_trans ha2 (dvd_prod ha1) }, end lemma prime.not_dvd_prod {p : M} {L : list M} (pp : prime p) (hL : ∀ a ∈ L, ¬ p ∣ a) : ¬ p ∣ L.prod := mt (prime.dvd_prod_iff pp).mp $ not_bex.mpr hL end comm_monoid_with_zero section cancel_comm_monoid_with_zero variables {M : Type*} [cancel_comm_monoid_with_zero M] [unique (units M)] lemma mem_list_primes_of_dvd_prod {p : M} (hp : prime p) {L : list M} (hL : ∀ q ∈ L, prime q) (hpL : p ∣ L.prod) : p ∈ L := begin obtain ⟨x, hx1, hx2⟩ := hp.dvd_prod_iff.mp hpL, rwa (prime_dvd_prime_iff_eq hp (hL x hx1)).mp hx2 end lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list M}, l₁.prod = l₂.prod → (∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → perm l₁ l₂ | [] [] _ _ _ := perm.nil | [] (a :: l) h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil M _ ▸ 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 M _ ▸ 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₂ := begin classical, 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_cons_erase ha, have hl : prod l₁ = prod ((b :: l₂).erase a) := ((mul_right_inj' (hl₁ a (mem_cons_self _ _)).ne_zero).1 $ by rwa [← prod_cons, ← prod_cons, ← hb.prod_eq]), exact perm.trans ((perm_of_prod_eq_prod hl hl₁' hl₂').cons _) hb.symm end end cancel_comm_monoid_with_zero
3c638a564b5dc7d55f74870926e324877a5f0409
618003631150032a5676f229d13a079ac875ff77
/src/field_theory/mv_polynomial.lean
74843afc336df1c7565bfa7b6516f774cc1423d8
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
9,212
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Multivariate functions of the form `α^n → α` are isomorphic to multivariate polynomials in `n` variables. -/ import linear_algebra.finsupp_vector_space import field_theory.finite noncomputable theory open_locale classical open set linear_map submodule namespace mv_polynomial universes u v variables {σ : Type u} {α : Type v} instance [field α] : vector_space α (mv_polynomial σ α) := finsupp.vector_space _ _ section variables (σ α) [field α] (m : ℕ) def restrict_total_degree : submodule α (mv_polynomial σ α) := finsupp.supported _ _ {n | n.sum (λn e, e) ≤ m } lemma mem_restrict_total_degree (p : mv_polynomial σ α) : p ∈ restrict_total_degree σ α m ↔ p.total_degree ≤ m := begin rw [total_degree, finset.sup_le_iff], refl end end section variables (σ α) def restrict_degree (m : ℕ) [field α] : submodule α (mv_polynomial σ α) := finsupp.supported _ _ {n | ∀i, n i ≤ m } end lemma mem_restrict_degree [field α] (p : mv_polynomial σ α) (n : ℕ) : p ∈ restrict_degree σ α n ↔ (∀s ∈ p.support, ∀i, (s : σ →₀ ℕ) i ≤ n) := begin rw [restrict_degree, finsupp.mem_supported], refl end lemma mem_restrict_degree_iff_sup [field α] (p : mv_polynomial σ α) (n : ℕ) : p ∈ restrict_degree σ α n ↔ ∀i, p.degrees.count i ≤ n := begin simp only [mem_restrict_degree, degrees, multiset.count_sup, finsupp.count_to_multiset, finset.sup_le_iff], exact ⟨assume h n s hs, h s hs n, assume h s hs n, h n s hs⟩ end lemma map_range_eq_map {β : Type*} [comm_ring α] [comm_ring β] (p : mv_polynomial σ α) (f : α → β) [is_semiring_hom f]: finsupp.map_range f (is_semiring_hom.map_zero f) p = p.map f := begin rw [← finsupp.sum_single p, finsupp.sum, finsupp.map_range_finset_sum, ← p.support.sum_hom (map f)], { refine finset.sum_congr rfl (assume n _, _), rw [finsupp.map_range_single, ← monomial, ← monomial, map_monomial] }, apply_instance end section variables (σ α) lemma is_basis_monomials [field α] : is_basis α ((λs, (monomial s 1 : mv_polynomial σ α))) := suffices is_basis α (λ (sa : Σ _, unit), (monomial sa.1 1 : mv_polynomial σ α)), begin apply is_basis.comp this (λ (s : σ →₀ ℕ), ⟨s, punit.star⟩), split, { intros x y hxy, simpa using hxy }, { intros x, rcases x with ⟨x₁, x₂⟩, use x₁, rw punit_eq punit.star x₂ } end, begin apply finsupp.is_basis_single (λ _ _, (1 : α)), intro _, apply is_basis_singleton_one, end end end mv_polynomial namespace mv_polynomial universe u variables (σ : Type u) (α : Type u) [field α] open_locale classical lemma dim_mv_polynomial : vector_space.dim α (mv_polynomial σ α) = cardinal.mk (σ →₀ ℕ) := by rw [← cardinal.lift_inj, ← (is_basis_monomials σ α).mk_eq_dim] end mv_polynomial namespace mv_polynomial variables {α : Type*} {σ : Type*} variables [field α] [fintype α] [fintype σ] def indicator (a : σ → α) : mv_polynomial σ α := finset.univ.prod (λn, 1 - (X n - C (a n))^(fintype.card α - 1)) lemma eval_indicator_apply_eq_one (a : σ → α) : eval a (indicator a) = 1 := have 0 < fintype.card α - 1, begin rw [← finite_field.card_units, fintype.card_pos_iff], exact ⟨1⟩ end, by simp only [indicator, (finset.univ.prod_hom (eval a)).symm, eval_sub, is_ring_hom.map_one (eval a), is_semiring_hom.map_pow (eval a), eval_X, eval_C, sub_self, zero_pow this, sub_zero, finset.prod_const_one] lemma eval_indicator_apply_eq_zero (a b : σ → α) (h : a ≠ b) : eval a (indicator b) = 0 := have ∃i, a i ≠ b i, by rwa [(≠), function.funext_iff, not_forall] at h, begin rcases this with ⟨i, hi⟩, simp only [indicator, (finset.univ.prod_hom (eval a)).symm, eval_sub, is_ring_hom.map_one (eval a), is_semiring_hom.map_pow (eval a), eval_X, eval_C, sub_self, finset.prod_eq_zero_iff], refine ⟨i, finset.mem_univ _, _⟩, rw [finite_field.pow_card_sub_one_eq_one, sub_self], rwa [(≠), sub_eq_zero], end lemma degrees_indicator (c : σ → α) : degrees (indicator c) ≤ finset.univ.sum (λs:σ, (fintype.card α - 1) •ℕ {s}) := begin rw [indicator], refine le_trans (degrees_prod _ _) (finset.sum_le_sum $ assume s hs, _), refine le_trans (degrees_sub _ _) _, rw [degrees_one, ← bot_eq_zero, bot_sup_eq], refine le_trans (degrees_pow _ _) (nsmul_le_nsmul_of_le_right _ _), refine le_trans (degrees_sub _ _) _, rw [degrees_C, ← bot_eq_zero, sup_bot_eq], exact degrees_X _ end lemma indicator_mem_restrict_degree (c : σ → α) : indicator c ∈ restrict_degree σ α (fintype.card α - 1) := begin rw [mem_restrict_degree_iff_sup, indicator], assume n, refine le_trans (multiset.count_le_of_le _ $ degrees_indicator _) (le_of_eq _), rw [← finset.univ.sum_hom (multiset.count n)], simp only [is_add_monoid_hom.map_nsmul (multiset.count n), multiset.singleton_eq_singleton, nsmul_eq_mul, nat.cast_id], transitivity, refine finset.sum_eq_single n _ _, { assume b hb ne, rw [multiset.count_cons_of_ne ne.symm, multiset.count_zero, mul_zero] }, { assume h, exact (h $ finset.mem_univ _).elim }, { rw [multiset.count_cons_self, multiset.count_zero, mul_one] } end section variables (α σ) def evalₗ : mv_polynomial σ α →ₗ[α] (σ → α) → α := ⟨ λp e, p.eval e, assume p q, funext $ assume e, eval_add, assume a p, funext $ assume e, by rw [smul_eq_C_mul, eval_mul, eval_C]; refl ⟩ end section lemma evalₗ_apply (p : mv_polynomial σ α) (e : σ → α) : evalₗ α σ p e = p.eval e := rfl end lemma map_restrict_dom_evalₗ : (restrict_degree σ α (fintype.card α - 1)).map (evalₗ α σ) = ⊤ := begin refine top_unique (submodule.le_def'.2 $ assume e _, mem_map.2 _), refine ⟨finset.univ.sum (λn:σ → α, e n • indicator n), _, _⟩, { exact sum_mem _ (assume c _, smul_mem _ _ (indicator_mem_restrict_degree _)) }, { ext n, simp only [linear_map.map_sum, @pi.finset_sum_apply (σ → α) (λ_, α) _ _ _ _ _, pi.smul_apply, linear_map.map_smul], simp only [evalₗ_apply], transitivity, refine finset.sum_eq_single n _ _, { assume b _ h, rw [eval_indicator_apply_eq_zero _ _ h.symm, smul_zero] }, { assume h, exact (h $ finset.mem_univ n).elim }, { rw [eval_indicator_apply_eq_one, smul_eq_mul, mul_one] } } end end mv_polynomial namespace mv_polynomial universe u variables (σ : Type u) (α : Type u) [fintype σ] [field α] [fintype α] @[derive [add_comm_group, vector_space α, inhabited]] def R : Type u := restrict_degree σ α (fintype.card α - 1) noncomputable instance decidable_restrict_degree (m : ℕ) : decidable_pred (λn, n ∈ {n : σ →₀ ℕ | ∀i, n i ≤ m }) := by simp only [set.mem_set_of_eq]; apply_instance lemma dim_R : vector_space.dim α (R σ α) = fintype.card (σ → α) := calc vector_space.dim α (R σ α) = vector_space.dim α (↥{s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card α - 1} →₀ α) : linear_equiv.dim_eq (finsupp.supported_equiv_finsupp {s : σ →₀ ℕ | ∀n:σ, s n ≤ fintype.card α - 1 }) ... = cardinal.mk {s : σ →₀ ℕ | ∀ (n : σ), s n ≤ fintype.card α - 1} : by rw [finsupp.dim_eq, dim_of_field, mul_one] ... = cardinal.mk {s : σ → ℕ | ∀ (n : σ), s n < fintype.card α } : begin refine quotient.sound ⟨equiv.subtype_congr finsupp.equiv_fun_on_fintype $ assume f, _⟩, refine forall_congr (assume n, nat.le_sub_right_iff_add_le _), exact fintype.card_pos_iff.2 ⟨0⟩ end ... = cardinal.mk (σ → {n // n < fintype.card α}) : quotient.sound ⟨@equiv.subtype_pi_equiv_pi σ (λ_, ℕ) (λs n, n < fintype.card α)⟩ ... = cardinal.mk (σ → fin (fintype.card α)) : quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) (equiv.fin_equiv_subtype _).symm⟩ ... = cardinal.mk (σ → α) : begin refine (trunc.induction_on (fintype.equiv_fin α) $ assume (e : α ≃ fin (fintype.card α)), _), refine quotient.sound ⟨equiv.arrow_congr (equiv.refl σ) e.symm⟩ end ... = fintype.card (σ → α) : cardinal.fintype_card _ def evalᵢ : R σ α →ₗ[α] (σ → α) → α := ((evalₗ α σ).comp (restrict_degree σ α (fintype.card α - 1)).subtype) lemma range_evalᵢ : (evalᵢ σ α).range = ⊤ := begin rw [evalᵢ, linear_map.range_comp, range_subtype], exact map_restrict_dom_evalₗ end lemma ker_evalₗ : (evalᵢ σ α).ker = ⊥ := begin refine injective_of_surjective _ _ _ (range_evalᵢ _ _), { rw [dim_R], exact cardinal.nat_lt_omega _ }, { rw [dim_R, dim_fun, dim_of_field, mul_one] } end lemma eq_zero_of_eval_eq_zero (p : mv_polynomial σ α) (h : ∀v:σ → α, p.eval v = 0) (hp : p ∈ restrict_degree σ α (fintype.card α - 1)) : p = 0 := let p' : R σ α := ⟨p, hp⟩ in have p' ∈ (evalᵢ σ α).ker := by rw [mem_ker]; ext v; exact h v, show p'.1 = (0 : R σ α).1, begin rw [ker_evalₗ, mem_bot] at this, rw [this] end end mv_polynomial
8e14052b3d8caa265ed4841d1110fb02f9067a24
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/def3.lean
dadd04787a4241d3f702e281010e1780f1cb5400
[ "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
108
lean
universe variable u section variable (A : Type u) definition f : A → A := λ x, x #check f end
2ab30b78c275981023950c14ce934752fed9bec2
4727251e0cd73359b15b664c3170e5d754078599
/src/data/list/sigma.lean
55082854cef6f380367ff3448c25b11a93745b7a
[ "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
25,487
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Sean Leather -/ import data.list.range import data.list.perm /-! # Utilities for lists of sigmas This file includes several ways of interacting with `list (sigma β)`, treated as a key-value store. If `α : Type*` and `β : α → Type*`, then we regard `s : sigma β` as having key `s.1 : α` and value `s.2 : β s.1`. Hence, `list (sigma β)` behaves like a key-value store. ## Main Definitions - `list.keys` extracts the list of keys. - `list.nodupkeys` determines if the store has duplicate keys. - `list.lookup`/`lookup_all` accesses the value(s) of a particular key. - `list.kreplace` replaces the first value with a given key by a given value. - `list.kerase` removes a value. - `list.kinsert` inserts a value. - `list.kunion` computes the union of two stores. - `list.kextract` returns a value with a given key and the rest of the values. -/ universes u v namespace list variables {α : Type u} {β : α → Type v} {l l₁ l₂ : list (sigma β)} /-! ### `keys` -/ /-- List of keys from a list of key-value pairs -/ def keys : list (sigma β) → list α := map sigma.fst @[simp] theorem keys_nil : @keys α β [] = [] := rfl @[simp] theorem keys_cons {s} {l : list (sigma β)} : (s :: l).keys = s.1 :: l.keys := rfl theorem mem_keys_of_mem {s : sigma β} {l : list (sigma β)} : s ∈ l → s.1 ∈ l.keys := mem_map_of_mem sigma.fst theorem exists_of_mem_keys {a} {l : list (sigma β)} (h : a ∈ l.keys) : ∃ (b : β a), sigma.mk a b ∈ l := let ⟨⟨a', b'⟩, m, e⟩ := exists_of_mem_map h in eq.rec_on e (exists.intro b' m) theorem mem_keys {a} {l : list (sigma β)} : a ∈ l.keys ↔ ∃ (b : β a), sigma.mk a b ∈ l := ⟨exists_of_mem_keys, λ ⟨b, h⟩, mem_keys_of_mem h⟩ theorem not_mem_keys {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ b : β a, sigma.mk a b ∉ l := (not_iff_not_of_iff mem_keys).trans not_exists theorem not_eq_key {a} {l : list (sigma β)} : a ∉ l.keys ↔ ∀ s : sigma β, s ∈ l → a ≠ s.1 := iff.intro (λ h₁ s h₂ e, absurd (mem_keys_of_mem h₂) (by rwa e at h₁)) (λ f h₁, let ⟨b, h₂⟩ := exists_of_mem_keys h₁ in f _ h₂ rfl) /-! ### `nodupkeys` -/ /-- Determines whether the store uses a key several times. -/ def nodupkeys (l : list (sigma β)) : Prop := l.keys.nodup theorem nodupkeys_iff_pairwise {l} : nodupkeys l ↔ pairwise (λ s s' : sigma β, s.1 ≠ s'.1) l := pairwise_map _ theorem nodupkeys.pairwise_ne {l} (h : nodupkeys l) : pairwise (λ s s' : sigma β, s.1 ≠ s'.1) l := nodupkeys_iff_pairwise.1 h @[simp] theorem nodupkeys_nil : @nodupkeys α β [] := pairwise.nil @[simp] theorem nodupkeys_cons {s : sigma β} {l : list (sigma β)} : nodupkeys (s::l) ↔ s.1 ∉ l.keys ∧ nodupkeys l := by simp [keys, nodupkeys] theorem nodupkeys.eq_of_fst_eq {l : list (sigma β)} (nd : nodupkeys l) {s s' : sigma β} (h : s ∈ l) (h' : s' ∈ l) : s.1 = s'.1 → s = s' := @pairwise.forall_of_forall _ (λ s s' : sigma β, s.1 = s'.1 → s = s') _ (λ s s' H h, (H h.symm).symm) (λ x h _, rfl) ((nodupkeys_iff_pairwise.1 nd).imp (λ s s' h h', (h h').elim)) _ h _ h' theorem nodupkeys.eq_of_mk_mem {a : α} {b b' : β a} {l : list (sigma β)} (nd : nodupkeys l) (h : sigma.mk a b ∈ l) (h' : sigma.mk a b' ∈ l) : b = b' := by cases nd.eq_of_fst_eq h h' rfl; refl theorem nodupkeys_singleton (s : sigma β) : nodupkeys [s] := nodup_singleton _ theorem nodupkeys.sublist {l₁ l₂ : list (sigma β)} (h : l₁ <+ l₂) : nodupkeys l₂ → nodupkeys l₁ := nodup.sublist $ h.map _ protected lemma nodupkeys.nodup {l : list (sigma β)} : nodupkeys l → nodup l := nodup.of_map _ theorem perm_nodupkeys {l₁ l₂ : list (sigma β)} (h : l₁ ~ l₂) : nodupkeys l₁ ↔ nodupkeys l₂ := (h.map _).nodup_iff theorem nodupkeys_join {L : list (list (sigma β))} : nodupkeys (join L) ↔ (∀ l ∈ L, nodupkeys l) ∧ pairwise disjoint (L.map keys) := begin rw [nodupkeys_iff_pairwise, pairwise_join, pairwise_map], refine and_congr (ball_congr $ λ l h, by simp [nodupkeys_iff_pairwise]) _, apply iff_of_eq, congr' with l₁ l₂, simp [keys, disjoint_iff_ne] end theorem nodup_enum_map_fst (l : list α) : (l.enum.map prod.fst).nodup := by simp [list.nodup_range] lemma mem_ext {l₀ l₁ : list (sigma β)} (nd₀ : l₀.nodup) (nd₁ : l₁.nodup) (h : ∀ x, x ∈ l₀ ↔ x ∈ l₁) : l₀ ~ l₁ := begin induction l₀ with x xs generalizing l₁; cases l₁ with y ys, { constructor }, iterate 2 { specialize h x <|> specialize h y, simp at h, cases h }, simp at nd₀ nd₁, classical, obtain rfl | h' := eq_or_ne x y, { constructor, refine l₀_ih nd₀.2 nd₁.2 (λ a, _), specialize h a, simp at h, obtain rfl | h' := eq_or_ne a x, { exact iff_of_false nd₀.1 nd₁.1 }, { simpa [h'] using h } }, { transitivity x :: y :: ys.erase x, { constructor, refine l₀_ih nd₀.2 ((nd₁.2.erase _).cons $ λ h, nd₁.1 $ mem_of_mem_erase h) (λ a, _), { specialize h a, simp at h, obtain rfl | h' := eq_or_ne a x, { exact iff_of_false nd₀.1 (λ h, h.elim h' nd₁.2.not_mem_erase) }, { rw or_iff_right h' at h, rw [h, mem_cons_iff], exact or_congr_right' (mem_erase_of_ne h').symm } } }, transitivity y :: x :: ys.erase x, { constructor }, { constructor, symmetry, apply perm_cons_erase, specialize h x, simp [h'] at h, exact h } } end variables [decidable_eq α] /-! ### `lookup` -/ /-- `lookup a l` is the first value in `l` corresponding to the key `a`, or `none` if no such element exists. -/ def lookup (a : α) : list (sigma β) → option (β a) | [] := none | (⟨a', b⟩ :: l) := if h : a' = a then some (eq.rec_on h b) else lookup l @[simp] theorem lookup_nil (a : α) : lookup a [] = @none (β a) := rfl @[simp] theorem lookup_cons_eq (l) (a : α) (b : β a) : lookup a (⟨a, b⟩::l) = some b := dif_pos rfl @[simp] theorem lookup_cons_ne (l) {a} : ∀ s : sigma β, a ≠ s.1 → lookup a (s::l) = lookup a l | ⟨a', b⟩ h := dif_neg h.symm theorem lookup_is_some {a : α} : ∀ {l : list (sigma β)}, (lookup a l).is_some ↔ a ∈ l.keys | [] := by simp | (⟨a', b⟩ :: l) := begin by_cases h : a = a', { subst a', simp }, { simp [h, lookup_is_some] }, end theorem lookup_eq_none {a : α} {l : list (sigma β)} : lookup a l = none ↔ a ∉ l.keys := by simp [← lookup_is_some, option.is_none_iff_eq_none] theorem of_mem_lookup {a : α} {b : β a} : ∀ {l : list (sigma β)}, b ∈ lookup a l → sigma.mk a b ∈ l | (⟨a', b'⟩ :: l) H := begin by_cases h : a = a', { subst a', simp at H, simp [H] }, { simp [h] at H, exact or.inr (of_mem_lookup H) } end theorem mem_lookup {a} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys) (h : sigma.mk a b ∈ l) : b ∈ lookup a l := begin cases option.is_some_iff_exists.mp (lookup_is_some.mpr (mem_keys_of_mem h)) with b' h', cases nd.eq_of_mk_mem h (of_mem_lookup h'), exact h' end theorem map_lookup_eq_find (a : α) : ∀ l : list (sigma β), (lookup a l).map (sigma.mk a) = find (λ s, a = s.1) l | [] := rfl | (⟨a', b'⟩ :: l) := begin by_cases h : a = a', { subst a', simp }, { simp [h, map_lookup_eq_find] } end theorem mem_lookup_iff {a : α} {b : β a} {l : list (sigma β)} (nd : l.nodupkeys) : b ∈ lookup a l ↔ sigma.mk a b ∈ l := ⟨of_mem_lookup, mem_lookup nd⟩ theorem perm_lookup (a : α) {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup a l₁ = lookup a l₂ := by ext b; simp [mem_lookup_iff, nd₁, nd₂]; exact p.mem_iff lemma lookup_ext {l₀ l₁ : list (sigma β)} (nd₀ : l₀.nodupkeys) (nd₁ : l₁.nodupkeys) (h : ∀ x y, y ∈ l₀.lookup x ↔ y ∈ l₁.lookup x) : l₀ ~ l₁ := mem_ext nd₀.nodup nd₁.nodup (λ ⟨a,b⟩, by rw [← mem_lookup_iff, ← mem_lookup_iff, h]; assumption) /-! ### `lookup_all` -/ /-- `lookup_all a l` is the list of all values in `l` corresponding to the key `a`. -/ def lookup_all (a : α) : list (sigma β) → list (β a) | [] := [] | (⟨a', b⟩ :: l) := if h : a' = a then eq.rec_on h b :: lookup_all l else lookup_all l @[simp] theorem lookup_all_nil (a : α) : lookup_all a [] = @nil (β a) := rfl @[simp] theorem lookup_all_cons_eq (l) (a : α) (b : β a) : lookup_all a (⟨a, b⟩::l) = b :: lookup_all a l := dif_pos rfl @[simp] theorem lookup_all_cons_ne (l) {a} : ∀ s : sigma β, a ≠ s.1 → lookup_all a (s::l) = lookup_all a l | ⟨a', b⟩ h := dif_neg h.symm theorem lookup_all_eq_nil {a : α} : ∀ {l : list (sigma β)}, lookup_all a l = [] ↔ ∀ b : β a, sigma.mk a b ∉ l | [] := by simp | (⟨a', b⟩ :: l) := begin by_cases h : a = a', { subst a', simp }, { simp [h, lookup_all_eq_nil] }, end theorem head_lookup_all (a : α) : ∀ l : list (sigma β), head' (lookup_all a l) = lookup a l | [] := by simp | (⟨a', b⟩ :: l) := by by_cases h : a = a'; [{subst h, simp}, simp *] theorem mem_lookup_all {a : α} {b : β a} : ∀ {l : list (sigma β)}, b ∈ lookup_all a l ↔ sigma.mk a b ∈ l | [] := by simp | (⟨a', b'⟩ :: l) := by by_cases h : a = a'; [{subst h, simp *}, simp *] theorem lookup_all_sublist (a : α) : ∀ l : list (sigma β), (lookup_all a l).map (sigma.mk a) <+ l | [] := by simp | (⟨a', b'⟩ :: l) := begin by_cases h : a = a', { subst h, simp, exact (lookup_all_sublist l).cons2 _ _ _ }, { simp [h], exact (lookup_all_sublist l).cons _ _ _ } end theorem lookup_all_length_le_one (a : α) {l : list (sigma β)} (h : l.nodupkeys) : length (lookup_all a l) ≤ 1 := by have := nodup.sublist ((lookup_all_sublist a l).map _) h; rw map_map at this; rwa [← nodup_repeat, ← map_const _ a] theorem lookup_all_eq_lookup (a : α) {l : list (sigma β)} (h : l.nodupkeys) : lookup_all a l = (lookup a l).to_list := begin rw ← head_lookup_all, have := lookup_all_length_le_one a h, revert this, rcases lookup_all a l with _|⟨b, _|⟨c, l⟩⟩; intro; try {refl}, exact absurd this dec_trivial end theorem lookup_all_nodup (a : α) {l : list (sigma β)} (h : l.nodupkeys) : (lookup_all a l).nodup := by rw lookup_all_eq_lookup a h; apply option.to_list_nodup theorem perm_lookup_all (a : α) {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) (p : l₁ ~ l₂) : lookup_all a l₁ = lookup_all a l₂ := by simp [lookup_all_eq_lookup, nd₁, nd₂, perm_lookup a nd₁ nd₂ p] /-! ### `kreplace` -/ /-- Replaces the first value with key `a` by `b`. -/ def kreplace (a : α) (b : β a) : list (sigma β) → list (sigma β) := lookmap $ λ s, if a = s.1 then some ⟨a, b⟩ else none theorem kreplace_of_forall_not (a : α) (b : β a) {l : list (sigma β)} (H : ∀ b : β a, sigma.mk a b ∉ l) : kreplace a b l = l := lookmap_of_forall_not _ $ begin rintro ⟨a', b'⟩ h, dsimp, split_ifs, { subst a', exact H _ h }, {refl} end theorem kreplace_self {a : α} {b : β a} {l : list (sigma β)} (nd : nodupkeys l) (h : sigma.mk a b ∈ l) : kreplace a b l = l := begin refine (lookmap_congr _).trans (lookmap_id' (option.guard (λ s, a = s.1)) _ _), { rintro ⟨a', b'⟩ h', dsimp [option.guard], split_ifs, { subst a', exact ⟨rfl, heq_of_eq $ nd.eq_of_mk_mem h h'⟩ }, { refl } }, { rintro ⟨a₁, b₁⟩ ⟨a₂, b₂⟩, dsimp [option.guard], split_ifs, { subst a₁, rintro ⟨⟩, simp }, { rintro ⟨⟩ } }, end theorem keys_kreplace (a : α) (b : β a) : ∀ l : list (sigma β), (kreplace a b l).keys = l.keys := lookmap_map_eq _ _ $ by rintro ⟨a₁, b₂⟩ ⟨a₂, b₂⟩; dsimp; split_ifs; simp [h] {contextual := tt} theorem kreplace_nodupkeys (a : α) (b : β a) {l : list (sigma β)} : (kreplace a b l).nodupkeys ↔ l.nodupkeys := by simp [nodupkeys, keys_kreplace] theorem perm.kreplace {a : α} {b : β a} {l₁ l₂ : list (sigma β)} (nd : l₁.nodupkeys) : l₁ ~ l₂ → kreplace a b l₁ ~ kreplace a b l₂ := perm_lookmap _ $ begin refine nd.pairwise_ne.imp _, intros x y h z h₁ w h₂, split_ifs at h₁ h₂; cases h₁; cases h₂, exact (h (h_2.symm.trans h_1)).elim end /-! ### `kerase` -/ /-- Remove the first pair with the key `a`. -/ def kerase (a : α) : list (sigma β) → list (sigma β) := erasep $ λ s, a = s.1 @[simp] theorem kerase_nil {a} : @kerase _ β _ a [] = [] := rfl @[simp, priority 990] theorem kerase_cons_eq {a} {s : sigma β} {l : list (sigma β)} (h : a = s.1) : kerase a (s :: l) = l := by simp [kerase, h] @[simp, priority 990] theorem kerase_cons_ne {a} {s : sigma β} {l : list (sigma β)} (h : a ≠ s.1) : kerase a (s :: l) = s :: kerase a l := by simp [kerase, h] @[simp, priority 980] theorem kerase_of_not_mem_keys {a} {l : list (sigma β)} (h : a ∉ l.keys) : kerase a l = l := by induction l with _ _ ih; [refl, { simp [not_or_distrib] at h, simp [h.1, ih h.2] }] theorem kerase_sublist (a : α) (l : list (sigma β)) : kerase a l <+ l := erasep_sublist _ theorem kerase_keys_subset (a) (l : list (sigma β)) : (kerase a l).keys ⊆ l.keys := ((kerase_sublist a l).map _).subset theorem mem_keys_of_mem_keys_kerase {a₁ a₂} {l : list (sigma β)} : a₁ ∈ (kerase a₂ l).keys → a₁ ∈ l.keys := @kerase_keys_subset _ _ _ _ _ _ theorem exists_of_kerase {a : α} {l : list (sigma β)} (h : a ∈ l.keys) : ∃ (b : β a) (l₁ l₂ : list (sigma β)), a ∉ l₁.keys ∧ l = l₁ ++ ⟨a, b⟩ :: l₂ ∧ kerase a l = l₁ ++ l₂ := begin induction l, case list.nil { cases h }, case list.cons : hd tl ih { by_cases e : a = hd.1, { subst e, exact ⟨hd.2, [], tl, by simp, by cases hd; refl, by simp⟩ }, { simp at h, cases h, case or.inl : h { exact absurd h e }, case or.inr : h { rcases ih h with ⟨b, tl₁, tl₂, h₁, h₂, h₃⟩, exact ⟨b, hd :: tl₁, tl₂, not_mem_cons_of_ne_of_not_mem e h₁, by rw h₂; refl, by simp [e, h₃]⟩ } } } end @[simp, priority 990] theorem mem_keys_kerase_of_ne {a₁ a₂} {l : list (sigma β)} (h : a₁ ≠ a₂) : a₁ ∈ (kerase a₂ l).keys ↔ a₁ ∈ l.keys := iff.intro mem_keys_of_mem_keys_kerase $ λ p, if q : a₂ ∈ l.keys then match l, kerase a₂ l, exists_of_kerase q, p with | _, _, ⟨_, _, _, _, rfl, rfl⟩, p := by simpa [keys, h] using p end else by simp [q, p] theorem keys_kerase {a} {l : list (sigma β)} : (kerase a l).keys = l.keys.erase a := by rw [keys, kerase, ←erasep_map sigma.fst l, erase_eq_erasep] theorem kerase_kerase {a a'} {l : list (sigma β)} : (kerase a' l).kerase a = (kerase a l).kerase a' := begin by_cases a = a', { subst a' }, induction l with x xs, { refl }, { by_cases a' = x.1, { subst a', simp [kerase_cons_ne h,kerase_cons_eq rfl] }, by_cases h' : a = x.1, { subst a, simp [kerase_cons_eq rfl,kerase_cons_ne (ne.symm h)] }, { simp [kerase_cons_ne,*] } } end lemma nodupkeys.kerase (a : α) : nodupkeys l → (kerase a l).nodupkeys := nodupkeys.sublist $ kerase_sublist _ _ theorem perm.kerase {a : α} {l₁ l₂ : list (sigma β)} (nd : l₁.nodupkeys) : l₁ ~ l₂ → kerase a l₁ ~ kerase a l₂ := perm.erasep _ $ (nodupkeys_iff_pairwise.1 nd).imp $ by rintro x y h rfl; exact h @[simp] theorem not_mem_keys_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) : a ∉ (kerase a l).keys := begin induction l, case list.nil { simp }, case list.cons : hd tl ih { simp at nd, by_cases h : a = hd.1, { subst h, simp [nd.1] }, { simp [h, ih nd.2] } } end @[simp] theorem lookup_kerase (a) {l : list (sigma β)} (nd : l.nodupkeys) : lookup a (kerase a l) = none := lookup_eq_none.mpr (not_mem_keys_kerase a nd) @[simp] theorem lookup_kerase_ne {a a'} {l : list (sigma β)} (h : a ≠ a') : lookup a (kerase a' l) = lookup a l := begin induction l, case list.nil { refl }, case list.cons : hd tl ih { cases hd with ah bh, by_cases h₁ : a = ah; by_cases h₂ : a' = ah, { substs h₁ h₂, cases ne.irrefl h }, { subst h₁, simp [h₂] }, { subst h₂, simp [h] }, { simp [h₁, h₂, ih] } } end theorem kerase_append_left {a} : ∀ {l₁ l₂ : list (sigma β)}, a ∈ l₁.keys → kerase a (l₁ ++ l₂) = kerase a l₁ ++ l₂ | [] _ h := by cases h | (s :: l₁) l₂ h₁ := if h₂ : a = s.1 then by simp [h₂] else by simp at h₁; cases h₁; [exact absurd h₁ h₂, simp [h₂, kerase_append_left h₁]] theorem kerase_append_right {a} : ∀ {l₁ l₂ : list (sigma β)}, a ∉ l₁.keys → kerase a (l₁ ++ l₂) = l₁ ++ kerase a l₂ | [] _ h := rfl | (_ :: l₁) l₂ h := by simp [not_or_distrib] at h; simp [h.1, kerase_append_right h.2] theorem kerase_comm (a₁ a₂) (l : list (sigma β)) : kerase a₂ (kerase a₁ l) = kerase a₁ (kerase a₂ l) := if h : a₁ = a₂ then by simp [h] else if ha₁ : a₁ ∈ l.keys then if ha₂ : a₂ ∈ l.keys then match l, kerase a₁ l, exists_of_kerase ha₁, ha₂ with | _, _, ⟨b₁, l₁, l₂, a₁_nin_l₁, rfl, rfl⟩, a₂_in_l₁_app_l₂ := if h' : a₂ ∈ l₁.keys then by simp [kerase_append_left h', kerase_append_right (mt (mem_keys_kerase_of_ne h).mp a₁_nin_l₁)] else by simp [kerase_append_right h', kerase_append_right a₁_nin_l₁, @kerase_cons_ne _ _ _ a₂ ⟨a₁, b₁⟩ _ (ne.symm h)] end else by simp [ha₂, mt mem_keys_of_mem_keys_kerase ha₂] else by simp [ha₁, mt mem_keys_of_mem_keys_kerase ha₁] lemma sizeof_kerase {α} {β : α → Type*} [decidable_eq α] [has_sizeof (sigma β)] (x : α) (xs : list (sigma β)) : sizeof (list.kerase x xs) ≤ sizeof xs := begin unfold_wf, induction xs with y ys, { simp }, { by_cases x = y.1; simp [*, list.sizeof] }, end /-! ### `kinsert` -/ /-- Insert the pair `⟨a, b⟩` and erase the first pair with the key `a`. -/ def kinsert (a : α) (b : β a) (l : list (sigma β)) : list (sigma β) := ⟨a, b⟩ :: kerase a l @[simp] theorem kinsert_def {a} {b : β a} {l : list (sigma β)} : kinsert a b l = ⟨a, b⟩ :: kerase a l := rfl theorem mem_keys_kinsert {a a'} {b' : β a'} {l : list (sigma β)} : a ∈ (kinsert a' b' l).keys ↔ a = a' ∨ a ∈ l.keys := by by_cases h : a = a'; simp [h] theorem kinsert_nodupkeys (a) (b : β a) {l : list (sigma β)} (nd : l.nodupkeys) : (kinsert a b l).nodupkeys := nodupkeys_cons.mpr ⟨not_mem_keys_kerase a nd, nd.kerase a⟩ theorem perm.kinsert {a} {b : β a} {l₁ l₂ : list (sigma β)} (nd₁ : l₁.nodupkeys) (p : l₁ ~ l₂) : kinsert a b l₁ ~ kinsert a b l₂ := (p.kerase nd₁).cons _ theorem lookup_kinsert {a} {b : β a} (l : list (sigma β)) : lookup a (kinsert a b l) = some b := by simp only [kinsert, lookup_cons_eq] theorem lookup_kinsert_ne {a a'} {b' : β a'} {l : list (sigma β)} (h : a ≠ a') : lookup a (kinsert a' b' l) = lookup a l := by simp [h] /-! ### `kextract` -/ /-- Finds the first entry with a given key `a` and returns its value (as an `option` because there might be no entry with key `a`) alongside with the rest of the entries. -/ def kextract (a : α) : list (sigma β) → option (β a) × list (sigma β) | [] := (none, []) | (s::l) := if h : s.1 = a then (some (eq.rec_on h s.2), l) else let (b', l') := kextract l in (b', s :: l') @[simp] theorem kextract_eq_lookup_kerase (a : α) : ∀ l : list (sigma β), kextract a l = (lookup a l, kerase a l) | [] := rfl | (⟨a', b⟩::l) := begin simp [kextract], dsimp, split_ifs, { subst a', simp [kerase] }, { simp [kextract, ne.symm h, kextract_eq_lookup_kerase l, kerase] } end /-! ### `dedupkeys` -/ /-- Remove entries with duplicate keys from `l : list (sigma β)`. -/ def dedupkeys : list (sigma β) → list (sigma β) := list.foldr (λ x, kinsert x.1 x.2) [] lemma dedupkeys_cons {x : sigma β} (l : list (sigma β)) : dedupkeys (x :: l) = kinsert x.1 x.2 (dedupkeys l) := rfl lemma nodupkeys_dedupkeys (l : list (sigma β)) : nodupkeys (dedupkeys l) := begin dsimp [dedupkeys], generalize hl : nil = l', have : nodupkeys l', { rw ← hl, apply nodup_nil }, clear hl, induction l with x xs, { apply this }, { cases x, simp [dedupkeys], split, { simp [keys_kerase], apply l_ih.not_mem_erase }, { exact l_ih.kerase _ } } end lemma lookup_dedupkeys (a : α) (l : list (sigma β)) : lookup a (dedupkeys l) = lookup a l := begin induction l, refl, cases l_hd with a' b, by_cases a = a', { subst a', rw [dedupkeys_cons,lookup_kinsert,lookup_cons_eq] }, { rw [dedupkeys_cons,lookup_kinsert_ne h,l_ih,lookup_cons_ne], exact h }, end lemma sizeof_dedupkeys {α} {β : α → Type*} [decidable_eq α] [has_sizeof (sigma β)] (xs : list (sigma β)) : sizeof (list.dedupkeys xs) ≤ sizeof xs := begin unfold_wf, induction xs with x xs, { simp [list.dedupkeys] }, { simp only [dedupkeys_cons, list.sizeof, kinsert_def, add_le_add_iff_left, sigma.eta], transitivity, apply sizeof_kerase, assumption } end /-! ### `kunion` -/ /-- `kunion l₁ l₂` is the append to l₁ of l₂ after, for each key in l₁, the first matching pair in l₂ is erased. -/ def kunion : list (sigma β) → list (sigma β) → list (sigma β) | [] l₂ := l₂ | (s :: l₁) l₂ := s :: kunion l₁ (kerase s.1 l₂) @[simp] theorem nil_kunion {l : list (sigma β)} : kunion [] l = l := rfl @[simp] theorem kunion_nil : ∀ {l : list (sigma β)}, kunion l [] = l | [] := rfl | (_ :: l) := by rw [kunion, kerase_nil, kunion_nil] @[simp] theorem kunion_cons {s} {l₁ l₂ : list (sigma β)} : kunion (s :: l₁) l₂ = s :: kunion l₁ (kerase s.1 l₂) := rfl @[simp] theorem mem_keys_kunion {a} {l₁ l₂ : list (sigma β)} : a ∈ (kunion l₁ l₂).keys ↔ a ∈ l₁.keys ∨ a ∈ l₂.keys := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : s l₁ ih { by_cases h : a = s.1; [simp [h], simp [h, ih]] } end @[simp] theorem kunion_kerase {a} : ∀ {l₁ l₂ : list (sigma β)}, kunion (kerase a l₁) (kerase a l₂) = kerase a (kunion l₁ l₂) | [] _ := rfl | (s :: _) l := by by_cases h : a = s.1; simp [h, kerase_comm a s.1 l, kunion_kerase] lemma nodupkeys.kunion (nd₁ : l₁.nodupkeys) (nd₂ : l₂.nodupkeys) : (kunion l₁ l₂).nodupkeys := begin induction l₁ generalizing l₂, case list.nil { simp only [nil_kunion, nd₂] }, case list.cons : s l₁ ih { simp at nd₁, simp [not_or_distrib, nd₁.1, nd₂, ih nd₁.2 (nd₂.kerase s.1)] } end theorem perm.kunion_right {l₁ l₂ : list (sigma β)} (p : l₁ ~ l₂) (l) : kunion l₁ l ~ kunion l₂ l := begin induction p generalizing l, case list.perm.nil { refl }, case list.perm.cons : hd tl₁ tl₂ p ih { simp [ih (kerase hd.1 l), perm.cons] }, case list.perm.swap : s₁ s₂ l { simp [kerase_comm, perm.swap] }, case list.perm.trans : l₁ l₂ l₃ p₁₂ p₂₃ ih₁₂ ih₂₃ { exact perm.trans (ih₁₂ l) (ih₂₃ l) } end theorem perm.kunion_left : ∀ l {l₁ l₂ : list (sigma β)}, l₁.nodupkeys → l₁ ~ l₂ → kunion l l₁ ~ kunion l l₂ | [] _ _ _ p := p | (s :: l) l₁ l₂ nd₁ p := by simp [((p.kerase nd₁).kunion_left l $ nd₁.kerase s.1).cons s] theorem perm.kunion {l₁ l₂ l₃ l₄ : list (sigma β)} (nd₃ : l₃.nodupkeys) (p₁₂ : l₁ ~ l₂) (p₃₄ : l₃ ~ l₄) : kunion l₁ l₃ ~ kunion l₂ l₄ := (p₁₂.kunion_right l₃).trans (p₃₄.kunion_left l₂ nd₃) @[simp] theorem lookup_kunion_left {a} {l₁ l₂ : list (sigma β)} (h : a ∈ l₁.keys) : lookup a (kunion l₁ l₂) = lookup a l₁ := begin induction l₁ with s _ ih generalizing l₂; simp at h; cases h; cases s with a', { subst h, simp }, { rw kunion_cons, by_cases h' : a = a', { subst h', simp }, { simp [h', ih h] } } end @[simp] theorem lookup_kunion_right {a} {l₁ l₂ : list (sigma β)} (h : a ∉ l₁.keys) : lookup a (kunion l₁ l₂) = lookup a l₂ := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : _ _ ih { simp [not_or_distrib] at h, simp [h.1, ih h.2] } end @[simp] theorem mem_lookup_kunion {a} {b : β a} {l₁ l₂ : list (sigma β)} : b ∈ lookup a (kunion l₁ l₂) ↔ b ∈ lookup a l₁ ∨ a ∉ l₁.keys ∧ b ∈ lookup a l₂ := begin induction l₁ generalizing l₂, case list.nil { simp }, case list.cons : s _ ih { cases s with a', by_cases h₁ : a = a', { subst h₁, simp }, { let h₂ := @ih (kerase a' l₂), simp [h₁] at h₂, simp [h₁, h₂] } } end theorem mem_lookup_kunion_middle {a} {b : β a} {l₁ l₂ l₃ : list (sigma β)} (h₁ : b ∈ lookup a (kunion l₁ l₃)) (h₂ : a ∉ keys l₂) : b ∈ lookup a (kunion (kunion l₁ l₂) l₃) := match mem_lookup_kunion.mp h₁ with | or.inl h := mem_lookup_kunion.mpr (or.inl (mem_lookup_kunion.mpr (or.inl h))) | or.inr h := mem_lookup_kunion.mpr $ or.inr ⟨mt mem_keys_kunion.mp (not_or_distrib.mpr ⟨h.1, h₂⟩), h.2⟩ end end list
2cb249d94896f02afed07a4209c8d0a68f7fc753
00c000939652bc85fffcfe8ba5dd194580a13c4b
/src/mvqpf/fix.lean
921d931ae58f6d37626c710e436b9431072bc3ef
[ "Apache-2.0" ]
permissive
johoelzl/qpf
a795220c4e872014a62126800313b74ba3b06680
d93ab1fb41d085e49ae476fa364535f40388f44d
refs/heads/master
1,587,372,400,745
1,548,633,467,000
1,548,633,467,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,628
lean
/- Copyright (c) 2018 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad The initial algebra of a multivariate qpf is again a qpf. -/ import ..mvpfunctor.W .basic universe u namespace mvqpf open typevec variables {n : ℕ} {F : typevec.{u} (n+1) → Type u} [mvfunctor F] [q : mvqpf F] include q /-- does recursion on `q.P.W` using `g : F α → α` rather than `g : P α → α` -/ def recF {α : typevec n} {β : Type*} (g : F (α.append1 β) → β) : q.P.W α → β := q.P.W_rec (λ a f' f rec, g (abs ⟨a, mvpfunctor.append_contents _ f' rec⟩)) theorem recF_eq {α : typevec n} {β : Type*} (g : F (α.append1 β) → β) (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : recF g (q.P.W_mk a f' f) = g (abs ⟨a, mvpfunctor.append_contents _ f' (recF g ∘ f)⟩) := by rw [recF, mvpfunctor.W_rec_eq] theorem recF_eq' {α : typevec n} {β : Type*} (g : F (α.append1 β) → β) (x : q.P.W α) : recF g x = g (abs ((append_fun id (recF g)) <$$> q.P.W_dest' x)) := begin apply q.P.W_cases _ x, intros a f' f, rw [recF_eq, q.P.W_dest'_W_mk, mvpfunctor.map_eq, mvpfunctor.append_fun_comp_append_contents, typevec.id_comp] end inductive Wequiv {α : typevec n} : q.P.W α → q.P.W α → Prop | ind (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f₀ f₁ : q.P.last.B a → q.P.W α) : (∀ x, Wequiv (f₀ x) (f₁ x)) → Wequiv (q.P.W_mk a f' f₀) (q.P.W_mk a f' f₁) | abs (a₀ : q.P.A) (f'₀ : q.P.drop.B a₀ ⟹ α) (f₀ : q.P.last.B a₀ → q.P.W α) (a₁ : q.P.A) (f'₁ : q.P.drop.B a₁ ⟹ α) (f₁ : q.P.last.B a₁ → q.P.W α) : abs ⟨a₀, q.P.append_contents f'₀ f₀⟩ = abs ⟨a₁, q.P.append_contents f'₁ f₁⟩ → Wequiv (q.P.W_mk a₀ f'₀ f₀) (q.P.W_mk a₁ f'₁ f₁) | trans (u v w : q.P.W α) : Wequiv u v → Wequiv v w → Wequiv u w theorem recF_eq_of_Wequiv (α : typevec n) {β : Type*} (u : F (α.append1 β) → β) (x y : q.P.W α) : Wequiv x y → recF u x = recF u y := begin apply q.P.W_cases _ x, intros a₀ f'₀ f₀, apply q.P.W_cases _ y, intros a₁ f'₁ f₁, intro h, induction h, case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih { simp only [recF_eq, function.comp, ih] }, case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h ih { simp only [recF_eq', abs_map, mvpfunctor.W_dest'_W_mk, h] }, case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { exact eq.trans ih₁ ih₂ } end theorem Wequiv.abs' {α : typevec n} (x y : q.P.W α) (h : abs (q.P.W_dest' x) = abs (q.P.W_dest' y)) : Wequiv x y := begin revert h, apply q.P.W_cases _ x, intros a₀ f'₀ f₀, apply q.P.W_cases _ y, intros a₁ f'₁ f₁, apply Wequiv.abs end theorem Wequiv.refl {α : typevec n} (x : q.P.W α) : Wequiv x x := by apply q.P.W_cases _ x; intros a f' f; exact Wequiv.abs a f' f a f' f rfl theorem Wequiv.symm {α : typevec n} (x y : q.P.W α) : Wequiv x y → Wequiv y x := begin intro h, induction h, case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih { exact Wequiv.ind _ _ _ _ ih }, case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h ih { exact Wequiv.abs _ _ _ _ _ _ h.symm }, case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { exact mvqpf.Wequiv.trans _ _ _ ih₂ ih₁} end /-- maps every element of the W type to a canonical representative -/ def Wrepr {α : typevec n} : q.P.W α → q.P.W α := recF (q.P.W_mk' ∘ repr) theorem Wrepr_W_mk {α : typevec n} (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : Wrepr (q.P.W_mk a f' f) = q.P.W_mk' (repr (abs ((append_fun id Wrepr) <$$> ⟨a, q.P.append_contents f' f⟩))) := by rw [Wrepr, recF_eq', q.P.W_dest'_W_mk] theorem Wrepr_equiv {α : typevec n} (x : q.P.W α) : Wequiv (Wrepr x) x := begin apply q.P.W_ind _ x, intros a f' f ih, apply Wequiv.trans _ (q.P.W_mk' ((append_fun id Wrepr) <$$> ⟨a, q.P.append_contents f' f⟩)), { apply Wequiv.abs', rw [Wrepr_W_mk, q.P.W_dest'_W_mk', q.P.W_dest'_W_mk', abs_repr] }, rw [q.P.map_eq, mvpfunctor.W_mk', q.P.append_fun_comp_append_contents, id_comp, q.P.contents_dest_left_append_contents, q.P.contents_dest_right_append_contents], apply Wequiv.ind, exact ih end theorem Wequiv_map {α β : typevec n} (g : α ⟹ β) (x y : q.P.W α) : Wequiv x y → Wequiv (g <$$> x) (g <$$> y) := begin intro h, induction h, case mvqpf.Wequiv.ind : a f' f₀ f₁ h ih { rw [q.P.W_map_W_mk, q.P.W_map_W_mk], apply Wequiv.ind, apply ih }, case mvqpf.Wequiv.abs : a₀ f'₀ f₀ a₁ f'₁ f₁ h ih { rw [q.P.W_map_W_mk, q.P.W_map_W_mk], apply Wequiv.abs, show abs (q.P.apply_append1 a₀ (g ⊚ f'₀) (λ x, q.P.W_map g (f₀ x))) = abs (q.P.apply_append1 a₁ (g ⊚ f'₁) (λ x, q.P.W_map g (f₁ x))), rw [←q.P.map_apply_append1, ←q.P.map_apply_append1, abs_map, abs_map, h]}, case mvqpf.Wequiv.trans : x y z e₁ e₂ ih₁ ih₂ { apply mvqpf.Wequiv.trans, apply ih₁, apply ih₂ } end /- Define the fixed point as the quotient of trees under the equivalence relation. -/ def W_setoid (α : typevec n) : setoid (q.P.W α) := ⟨Wequiv, @Wequiv.refl _ _ _ _ _, @Wequiv.symm _ _ _ _ _, @Wequiv.trans _ _ _ _ _⟩ local attribute [instance] W_setoid def fix {n : ℕ} (F : typevec (n+1) → Type*) [mvfunctor F] [q : mvqpf F] (α : typevec n) := quotient (W_setoid α : setoid (q.P.W α)) def fix.map {α β : typevec n} (g : α ⟹ β) : fix F α → fix F β := quotient.lift (λ x : q.P.W α, ⟦q.P.W_map g x⟧) (λ a b h, quot.sound (Wequiv_map _ _ _ h)) instance : mvfunctor (fix F) := { map := @fix.map _ _ _ _} variable {α : typevec.{u} n} -- TODO: should this be quotient.lift? def fix.rec {β : Type u} (g : F (append1 α β) → β) : fix F α → β := quot.lift (recF g) (recF_eq_of_Wequiv α g) def fix_to_W : fix F α → q.P.W α := quotient.lift Wrepr (recF_eq_of_Wequiv α (λ x, q.P.W_mk' (repr x))) def fix.mk (x : F (append1 α (fix F α))) : fix F α := quot.mk _ (q.P.W_mk' (append_fun id fix_to_W <$$> repr x)) def fix.dest : fix F α → F (append1 α (fix F α)) := fix.rec (mvfunctor.map (append_fun id fix.mk)) theorem fix.rec_eq {β : Type u} (g : F (append1 α β) → β) (x : F (append1 α (fix F α))) : fix.rec g (fix.mk x) = g (append_fun id (fix.rec g) <$$> x) := have recF g ∘ fix_to_W = fix.rec g, by { apply funext, apply quotient.ind, intro x, apply recF_eq_of_Wequiv, apply Wrepr_equiv }, begin conv { to_lhs, rw [fix.rec, fix.mk], dsimp }, cases h : repr x with a f, rw [mvpfunctor.map_eq, recF_eq', ←mvpfunctor.map_eq, mvpfunctor.W_dest'_W_mk'], rw [←mvpfunctor.comp_map, abs_map, ←h, abs_repr, ←append_fun_comp, id_comp, this] end theorem fix.ind_aux (a : q.P.A) (f' : q.P.drop.B a ⟹ α) (f : q.P.last.B a → q.P.W α) : fix.mk (abs ⟨a, q.P.append_contents f' (λ x, ⟦f x⟧)⟩) = ⟦q.P.W_mk a f' f⟧ := have fix.mk (abs ⟨a, q.P.append_contents f' (λ x, ⟦f x⟧)⟩) = ⟦Wrepr (q.P.W_mk a f' f)⟧, begin apply quot.sound, apply Wequiv.abs', rw [mvpfunctor.W_dest'_W_mk', abs_map, abs_repr, ←abs_map, mvpfunctor.map_eq], conv { to_rhs, rw [Wrepr_W_mk, q.P.W_dest'_W_mk', abs_repr, mvpfunctor.map_eq] }, congr' 2, rw [mvpfunctor.append_contents, mvpfunctor.append_contents], rw [←typevec.comp_assoc, ←append_fun_comp, ←typevec.comp_assoc, ←append_fun_comp], reflexivity end, by { rw this, apply quot.sound, apply Wrepr_equiv } theorem fix.ind {β : Type*} (g₁ g₂ : fix F α → β) (h : ∀ x : F (append1 α (fix F α)), (append_fun id g₁) <$$> x = (append_fun id g₂) <$$> x → g₁ (fix.mk x) = g₂ (fix.mk x)) : ∀ x, g₁ x = g₂ x := begin apply quot.ind, intro x, apply q.P.W_ind _ x, intros a f' f ih, show g₁ ⟦q.P.W_mk a f' f⟧ = g₂ ⟦q.P.W_mk a f' f⟧, rw [←fix.ind_aux a f' f], apply h, rw [←abs_map, ←abs_map, mvpfunctor.map_eq, mvpfunctor.map_eq], congr' 2, rw [mvpfunctor.append_contents, ←comp_assoc, ←comp_assoc], rw [←append_fun_comp, ←append_fun_comp], have : g₁ ∘ (λ x, ⟦f x⟧) = g₂ ∘ (λ x, ⟦f x⟧), { ext x, exact ih x }, rw this end theorem fix.rec_unique {β : Type*} (g : F (append1 α β) → β) (h : fix F α → β) (hyp : ∀ x, h (fix.mk x) = g (append_fun id h <$$> x)) : fix.rec g = h := begin ext x, apply fix.ind, intros x hyp', rw [hyp, ←hyp', fix.rec_eq] end theorem fix.mk_dest (x : fix F α) : fix.mk (fix.dest x) = x := begin change (fix.mk ∘ fix.dest) x = x, apply fix.ind, intro x, dsimp, rw [fix.dest, fix.rec_eq, ←comp_map, ←append_fun_comp, id_comp], intro h, rw h, show fix.mk (append_fun id id <$$> x) = fix.mk x, rw [append_fun_id_id, id_map] end theorem fix.dest_mk (x : F (append1 α (fix F α))) : fix.dest (fix.mk x) = x := begin unfold fix.dest, rw [fix.rec_eq, ←fix.dest, ←comp_map], conv { to_rhs, rw ←(id_map x) }, rw [←append_fun_comp, id_comp], have : fix.mk ∘ fix.dest = id, {ext x, apply fix.mk_dest }, rw [this, append_fun_id_id] end instance mvqpf_fix (α : typevec n) : mvqpf (fix F) := { P := q.P.Wp, abs := λ α, quot.mk Wequiv, repr' := λ α, fix_to_W, abs_repr' := by { intros α, apply quot.ind, intro a, apply quot.sound, apply Wrepr_equiv }, abs_map := begin intros α β g x, conv { to_rhs, dsimp [mvfunctor.map]}, rw fix.map, apply quot.sound, apply Wequiv.refl end } end mvqpf
0f452facd4fd2b0b8aff97fea5809c9b300e5e28
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport/Syntax/Translate/Tactic/Lean3.lean
322ffe46e4d29ce3bc3f54a094b0da1ac71d6846
[ "Apache-2.0" ]
permissive
leanprover-community/mathport
2c9bdc8292168febf59799efdc5451dbf0450d4a
13051f68064f7638970d39a8fecaede68ffbf9e1
refs/heads/master
1,693,841,364,079
1,693,813,111,000
1,693,813,111,000
379,357,010
27
10
Apache-2.0
1,691,309,132,000
1,624,384,521,000
Lean
UTF-8
Lean
false
false
30,747
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathport.Syntax.Translate.Tactic.Basic open Lean open Lean.Elab.Tactic (Location) namespace Mathport.Translate open AST3 Mathport.Translate.Parser def mkConvBlock (args : Array Syntax.Conv) : TSyntax ``Parser.Tactic.Conv.convSeq := mkNode ``Parser.Tactic.Conv.convSeq #[mkNode ``Parser.Tactic.Conv.convSeq1Indented #[ mkNullNode.mkSep args]] mutual partial def trConvBlock : Block → M (TSyntax ``Parser.Tactic.Conv.convSeq) | ⟨_, none, none, #[]⟩ => return mkConvBlock #[← `(conv| skip)] | ⟨_, none, none, tacs⟩ => mkConvBlock <$> tacs.mapM trConv | ⟨_, _cl, _cfg, _tacs⟩ => warn! "unsupported (TODO): conv block with cfg" partial def trConv : Spanned Tactic → M Syntax.Conv := spanningS fun | Tactic.block bl => do `(conv| · $(← trConvBlock bl):convSeq) | Tactic.by tac => do `(conv| · $(← trConv tac):conv) | Tactic.«;» _tacs => warn! "unsupported (impossible)" | Tactic.«<|>» tacs => do `(conv| first $[| $(← tacs.mapM trConv):conv]*) | Tactic.«[]» _tacs => warn! "unsupported (impossible)" | Tactic.exact_shortcut _ => warn! "unsupported (impossible)" | Tactic.expr e => do match ← trExpr e with | `(do $[$els]*) => `(conv| run_conv $[$els:doSeqItem]*) | stx => `(conv| run_conv $stx:term) | Tactic.interactive n args => do match (← get).convs.find? n with | some f => try f args catch e => warn! "in {n}: {← e.toMessageData.toString}" | none => warn! "unsupported conv tactic {repr n}" end namespace Tactic def trLoc : (loc : Location) → M (Option (TSyntax ``Parser.Tactic.location)) | Location.wildcard => some <$> `(Parser.Tactic.location| at *) | Location.targets #[] false => warn! "unsupported" | Location.targets #[] true => pure none | Location.targets hs goal => let hs : Array Term := hs.map (⟨·⟩) let goal := optTk goal some <$> `(Parser.Tactic.location| at $[$hs]* $[⊢%$goal]?) @[tr_tactic propagate_tags] def trPropagateTags : TacM Syntax.Tactic := do `(tactic| propagate_tags $(← trBlock (← itactic)):tacticSeq) @[tr_tactic intro] def trIntro : TacM Syntax.Tactic := do match ← parse (ident_)? with | some (BinderName.ident h) => `(tactic| intro $(mkIdent h):ident) | _ => `(tactic| intro) @[tr_tactic intros] def trIntros : TacM Syntax.Tactic := do match ← parse ident_* with | #[] => `(tactic| intros) | hs => `(tactic| intro $[$(hs.map trIdent_)]*) @[tr_tactic introv] def trIntrov : TacM Syntax.Tactic := do `(tactic| introv $((← parse ident_*).map trBinderIdent)*) @[tr_tactic rename] def trRename : TacM Syntax.Tactic := do let renames ← parse renameArgs let as := renames.map fun (a, _) => mkIdent a let bs := renames.map fun (_, b) => mkIdent b `(tactic| rename' $[$as:ident => $bs],*) @[tr_tactic apply] def trApply : TacM Syntax.Tactic := do `(tactic| apply $(← trExpr (← parse pExpr))) @[tr_tactic fapply] def trFApply : TacM Syntax.Tactic := do `(tactic| fapply $(← trExpr (← parse pExpr))) @[tr_tactic eapply] def trEApply : TacM Syntax.Tactic := do `(tactic| eapply $(← trExpr (← parse pExpr))) @[tr_tactic apply_with] def trApplyWith : TacM Syntax.Tactic := do let expr ← trExpr (← parse pExpr) let cfg ← trExpr (← expr!) `(tactic| apply (config := $cfg) $expr) @[tr_tactic mapply] def trMApply : TacM Syntax.Tactic := do `(tactic| mapply $(← trExpr (← parse pExpr))) @[tr_tactic apply_instance] def trApplyInstance : TacM Syntax.Tactic := `(tactic| infer_instance) @[tr_ni_tactic tactic.apply_instance] def trNIApplyInstance (_ : AST3.Expr) : M Syntax.Tactic := `(tactic| infer_instance) @[tr_tactic refine] def trRefine : TacM Syntax.Tactic := do `(tactic| refine' $(← trExpr (← parse pExpr))) @[tr_tactic assumption] def trAssumption : TacM Syntax.Tactic := do `(tactic| assumption) @[tr_ni_tactic tactic.assumption] def trNIAssumption (_ : AST3.Expr) : M Syntax.Tactic := `(tactic| assumption) @[tr_tactic assumption'] def trAssumption' : TacM Syntax.Tactic := do `(tactic| assumption') @[tr_tactic change] def trChange : TacM Syntax.Tactic := do let q ← trExpr (← parse pExpr) let h ← parse (tk "with" *> pExpr)? let loc ← trLoc (← parse location) match h with | none => `(tactic| change $q $[$loc]?) | some h => `(tactic| change $q with $(← trExpr h) $[$loc]?) @[tr_tactic exact «from»] def trExact : TacM Syntax.Tactic := do `(tactic| exact $(← trExpr (← parse pExpr))) @[tr_tactic exacts] def trExacts : TacM Syntax.Tactic := do `(tactic| exacts [$(← liftM $ (← parse pExprListOrTExpr).mapM trExpr),*]) @[tr_tactic revert] def trRevert : TacM Syntax.Tactic := do `(tactic| revert $[$((← parse ident*).map mkIdent)]*) def trRwRule (r : RwRule) : M (TSyntax ``Parser.Tactic.rwRule) := do let e ← trExpr r.rule if r.symm then `(Parser.Tactic.rwRule| ← $e) else `(Parser.Tactic.rwRule| $e:term) def trRwArgs : TacM (Array (TSyntax ``Parser.Tactic.rwRule) × Option (TSyntax ``Parser.Tactic.location)) := do let q ← liftM $ (← parse rwRules).mapM trRwRule let loc ← trLoc (← parse location) if let some cfg ← expr? then warn! "warning: unsupported: rw with cfg: {repr cfg}" pure (q, loc) @[tr_tactic rewrite rw] def trRw : TacM Syntax.Tactic := do let (q, loc) ← trRwArgs; `(tactic| rw [$q,*] $(loc)?) @[tr_tactic rwa] def trRwA : TacM Syntax.Tactic := do let (q, loc) ← trRwArgs; `(tactic| rwa [$q,*] $(loc)?) @[tr_tactic erewrite erw] def trERw : TacM Syntax.Tactic := do let (q, loc) ← trRwArgs; `(tactic| erw [$q,*] $(loc)?) @[tr_tactic with_cases] def trWithCases : TacM Syntax.Tactic := do warn! "warning: unsupported: with_cases" trIdTactic (← itactic) @[tr_tactic generalize] def trGeneralize : TacM Syntax.Tactic := do let h ← parse (ident)? <* parse (tk ":") let (e, x) ← parse generalizeArg `(tactic| generalize $[$(h.map mkIdent) :]? $(← trExpr e) = $(mkIdent x)) @[tr_tactic induction] def trInduction : TacM Syntax.Tactic := do let (hp, e) ← parse casesArg let e ← trExpr e let rec_name ← liftM $ (← parse usingIdent).mapM mkIdentI let ids ← parse withIdentList let revert := (← parse (tk "generalizing" *> ident*)?).getD #[] |>.map mkIdent |>.asNonempty match hp, ids with | none, #[] => `(tactic| induction $e $[using $rec_name]? $[generalizing $[$revert]*]?) | _, _ => `(tactic| induction' $[$(hp.map mkIdent) :]? $e $[using $rec_name]? with $(ids.map trBinderIdent)* $[generalizing $revert*]?) @[tr_tactic case] def trCase : TacM Syntax.Tactic := do let args ← parse case let tac ← trBlock (← itactic) let trCaseArg := fun (tags, xs) => do let tag ← tags.foldlM (init := Name.anonymous) fun | acc, .ident (.str _ id) => pure (acc.str id) | acc, tag => warn! "weird case tag {repr tag}" | pure acc let xs := xs.map trBinderIdent `(Parser.Tactic.caseArg| $(mkIdent tag):ident $xs*) `(tactic| case $(← args.mapM trCaseArg)|* => $tac:tacticSeq) @[tr_tactic destruct] def trDestruct : TacM Syntax.Tactic := do `(tactic| destruct $(← trExpr (← parse pExpr))) @[tr_tactic cases] def trCases : TacM Syntax.Tactic := do let (hp, e) ← parse casesArg let e ← trExpr e let ids ← parse withIdentList match ids with | #[] => `(tactic| cases $[$(hp.map mkIdent) :]? $e) | _ => `(tactic| cases' $[$(hp.map mkIdent) :]? $e with $(ids.map trBinderIdent)*) @[tr_tactic cases_matching casesm] def trCasesM : TacM Syntax.Tactic := do let _rec ← parse (tk "*")? let ps ← liftM $ (← parse pExprListOrTExpr).mapM trExpr match _rec with | none => `(tactic| casesm $ps,*) | some () => `(tactic| casesm* $ps,*) @[tr_tactic cases_type] def trCasesType : TacM Syntax.Tactic := do let bang ← parse (tk "!")? let star := optTk (← parse (tk "*")?).isSome let idents := (← parse ident*).map mkIdent if bang.isSome then `(tactic|cases_type! $[*%$star]? $[$idents]*) else `(tactic|cases_type $[*%$star]? $[$idents]*) @[tr_tactic trivial] def trTrivial : TacM Syntax.Tactic := `(tactic| trivial) @[tr_tactic admit «sorry»] def trSorry : TacM Syntax.Tactic := do match ← parse (Parser.itactic)? with | none => `(tactic| sorry) | some bl => `(tactic| stop $(← trBlock bl):tacticSeq) @[tr_tactic contradiction] def trContradiction : TacM Syntax.Tactic := `(tactic| contradiction) @[tr_tactic iterate] def trIterate : TacM Syntax.Tactic := do match ← parse (smallNat)?, ← trBlock (← itactic) with | none, tac => `(tactic| repeat $tac:tacticSeq) | some n, tac => `(tactic| iterate $(Quote.quote n) $tac:tacticSeq) @[tr_tactic «repeat»] def trRepeat : TacM Syntax.Tactic := do `(tactic| repeat' $(← trBlock (← itactic)):tacticSeq) @[tr_tactic «try»] def trTry : TacM Syntax.Tactic := do `(tactic| try $(← trBlock (← itactic)):tacticSeq) @[tr_tactic skip] def trSkip : TacM Syntax.Tactic := `(tactic| skip) @[tr_tactic solve1] def trSolve1 : TacM Syntax.Tactic := do `(tactic| · ($(← trBlock (← itactic)):tacticSeq)) @[tr_tactic abstract] def trAbstract : TacM Syntax.Tactic := do `(tactic| abstract $(← liftM $ (← parse (ident)?).mapM mkIdentF)? $(← trBlock (← itactic)):tacticSeq) @[tr_tactic all_goals] def trAllGoals : TacM Syntax.Tactic := do `(tactic| all_goals $(← trBlock (← itactic)):tacticSeq) @[tr_tactic any_goals] def trAnyGoals : TacM Syntax.Tactic := do `(tactic| any_goals $(← trBlock (← itactic)):tacticSeq) @[tr_tactic focus] def trFocus : TacM Syntax.Tactic := do `(tactic| focus $(← trBlock (← itactic)):tacticSeq) @[tr_tactic assume] def trAssume : TacM Syntax.Tactic := do match ← parse (Sum.inl <$> (tk ":" *> pExpr) <|> Sum.inr <$> parseBinders) with | Sum.inl ty => `(tactic| intro ($(mkIdent `this) : $(← trExpr ty))) | Sum.inr bis => `(tactic| intro $[$(← trIntroBinders bis)]*) where trIntroBinder : Binder → M (Array Term) | Binder.binder _ none _ _ _ => return #[← `(_)] | Binder.binder _ (some vars) _ none _ => return vars.map (trIdent_ ·.kind) | Binder.binder _ (some vars) bis (some ty) _ => do let ty ← trDArrow bis ty vars.mapM fun v => `(($(trIdent_ v.kind) : $ty)) | Binder.collection _ _ _ _ => warn! "unsupported: assume with binder collection" | Binder.notation _ => warn! "unsupported: assume notation" trIntroBinders (bis : Array (Spanned Binder)) : M (Array Term) := bis.concatMapM (trIntroBinder ·.kind) @[tr_tactic «have»] def trHave : TacM Syntax.Tactic := do let h := (← parse (ident)?).filter (· != `this) |>.map mkIdent let ty ← (← parse (tk ":" *> pExpr)?).mapM (trExpr ·) match h, ← (← parse (tk ":=" *> pExpr)?).mapM (trExpr ·) with | none, none => `(tactic| have $[: $ty]?) | some h, none => `(tactic| have $h:ident $[: $ty]?) | none, some pr => `(tactic| have $[: $ty]? := $pr) | some h, some pr => `(tactic| have $h $[: $ty]? := $pr) @[tr_tactic «let»] def trLet : TacM Syntax.Tactic := do let h := (← parse (ident)?).filter (· != `this) |>.map mkIdent let ty ← (← parse (tk ":" *> pExpr)?).mapM (trExpr ·) match h, ← (← parse (tk ":=" *> pExpr)?).mapM (trExpr ·) with | none, none => `(tactic| let $[: $ty]?) | some h, none => `(tactic| let $h:ident $[: $ty]?) | none, some pr => `(tactic| let this $[: $ty]? := $pr) | some h, some pr => `(tactic| let $h:ident $[: $ty]? := $pr) @[tr_tactic «suffices»] def trSuffices : TacM Syntax.Tactic := do let h := (← parse (ident)?).map mkIdent let ty ← (← parse (tk ":" *> pExpr)?).mapM (trExpr ·) match h with | none => `(tactic| suffices $[: $ty]?) | some h => `(tactic| suffices $h:ident $[: $ty]?) @[tr_tactic trace_state] def trTraceState : TacM Syntax.Tactic := `(tactic| trace_state) @[tr_tactic trace] def trTrace : TacM Syntax.Tactic := do `(tactic| trace $(← trExpr (← expr!)):term) @[tr_tactic existsi] def trExistsI : TacM Syntax.Tactic := do `(tactic| exists $(← liftM $ (← parse pExprListOrTExpr).mapM trExpr),*) @[tr_tactic constructor] def trConstructor : TacM Syntax.Tactic := `(tactic| constructor) @[tr_tactic econstructor] def trEConstructor : TacM Syntax.Tactic := `(tactic| econstructor) @[tr_tactic left] def trLeft : TacM Syntax.Tactic := `(tactic| left) @[tr_tactic right] def trRight : TacM Syntax.Tactic := `(tactic| right) @[tr_tactic split] def trSplit : TacM Syntax.Tactic := `(tactic| constructor) @[tr_tactic constructor_matching] def trConstructorM : TacM Syntax.Tactic := do let _rec ← parse (tk "*")? let ps ← liftM $ (← parse pExprListOrTExpr).mapM trExpr match _rec with | none => `(tactic| constructorm $ps,*) | some () => `(tactic| constructorm* $ps,*) @[tr_tactic exfalso] def trExfalso : TacM Syntax.Tactic := `(tactic| exfalso) @[tr_tactic injection] def trInjection : TacM Syntax.Tactic := do let e ← trExpr (← parse pExpr) let hs := (← parse withIdentList).map trIdent_ |>.asNonempty `(tactic| injection $e $[with $hs*]?) @[tr_tactic injections] def trInjections : TacM Syntax.Tactic := do let hs := (← parse withIdentList).map trIdent_ `(tactic| injections $hs*) def parseSimpConfig : Option (Spanned AST3.Expr) → M (Option Meta.Simp.Config × Option (TSyntax ``Parser.Tactic.discharger)) | none => pure (none, none) | some ⟨_, AST3.Expr.«{}»⟩ => pure (none, none) | some ⟨_, AST3.Expr.structInst _ none flds #[] false⟩ => do let mut cfg : Meta.Simp.Config := {} let mut discharger := none for (⟨_, n⟩, e) in flds do match n, e.kind with | `max_steps, Expr.nat n => cfg := {cfg with maxSteps := n} | `contextual, e => cfg := asBool e cfg fun cfg b => {cfg with contextual := b} | `zeta, e => cfg := asBool e cfg fun cfg b => {cfg with zeta := b} | `beta, e => cfg := asBool e cfg fun cfg b => {cfg with beta := b} | `eta, e => cfg := asBool e cfg fun cfg b => {cfg with eta := b} | `iota, e => cfg := asBool e cfg fun cfg b => {cfg with iota := b} | `proj, e => cfg := asBool e cfg fun cfg b => {cfg with proj := b} | `single_pass, e => cfg := asBool e cfg fun cfg b => {cfg with singlePass := b} | `memoize, e => cfg := asBool e cfg fun cfg b => {cfg with memoize := b} | `discharger, _ => let disch ← Translate.trTactic (Spanned.dummy <| Tactic.expr e) discharger := some (← `(Lean.Parser.Tactic.discharger| (disch := $disch:tactic))) | _, _ => warn! "warning: unsupported simp config option: {n}" pure (cfg, discharger) | some _ => warn! "warning: unsupported simp config syntax" | pure (none, none) where asBool {α} : AST3.Expr → α → (α → Bool → α) → α | AST3.Expr.const ⟨_, `tt⟩ _ _, a, f => f a true | AST3.Expr.const ⟨_, `ff⟩ _ _, a, f => f a false | _, a, _ => a def quoteSimpConfig (cfg : Meta.Simp.Config) : Option Term := Id.run do if cfg == {} then return none -- `Quote Bool` fully qualifies true and false but we are trying to generate -- the unqualified form here. let _inst : Quote Bool := ⟨fun b => mkIdent (if b then `true else `false)⟩ let a := #[] |> push cfg {} `maxSteps (·.maxSteps) |> push cfg {} `maxDischargeDepth (·.maxDischargeDepth) |> push cfg {} `contextual (·.contextual) |> push cfg {} `memoize (·.memoize) |> push cfg {} `singlePass (·.singlePass) |> push cfg {} `zeta (·.zeta) |> push cfg {} `beta (·.beta) |> push cfg {} `eta (·.eta) |> push cfg {} `iota (·.iota) |> push cfg {} `proj (·.proj) |> push cfg {} `decide (·.decide) `({ $[$a:structInstField],* }) where push {β} [BEq β] {α} (a b : α) [Quote β] (n : Name) (f : α → β) (args : Array (TSyntax ``Parser.Term.structInstField)) : Array (TSyntax ``Parser.Term.structInstField) := Id.run do if f a == f b then args else args.push <| Id.run `(Parser.Term.structInstField| $(mkIdent n):ident := $(quote (f a))) def trSimpLemma (e : Spanned AST3.Expr) : M (TSyntax ``Parser.Tactic.simpLemma) := do `(Parser.Tactic.simpLemma| $(← trExpr e):term) def mkConfigStx? (stx : Option Term) : M (Option (TSyntax ``Parser.Tactic.config)) := stx.mapM fun stx => `(Lean.Parser.Tactic.config| (config := $stx)) def trSimpArg : Parser.SimpArg → M (TSyntax ``Parser.Tactic.simpArg) | .allHyps => `(Parser.Tactic.simpArg| *) | .expr false e => do `(Parser.Tactic.simpArg| $(← trExpr e):term) | .expr true e => do `(Parser.Tactic.simpArg| ← $(← trExpr e)) | .except e => do `(Parser.Tactic.simpArg| - $(← mkIdentI e)) def trSimpExt [Coe (TSyntax ``Parser.Tactic.simpLemma) (TSyntax α)] (n : Name) : TSyntax α := Id.run `(Parser.Tactic.simpLemma| $(mkIdent n):ident) instance : Coe (TSyntax ``Parser.Tactic.simpLemma) (TSyntax ``Parser.Tactic.simpArg) where coe s := ⟨s⟩ -- AWFUL HACK: `(simp [$_]) gets wrong antiquotation type :-/ instance : Coe (TSyntax ``Parser.Tactic.simpArg) (TSyntax ``Parser.Tactic.simpStar) where coe s := ⟨s⟩ def trSimpArgs (hs : Array Parser.SimpArg) : M (Array (TSyntax ``Parser.Tactic.simpArg)) := hs.mapM trSimpArg def filterSimpStar (hs : Array (TSyntax ``Parser.Tactic.simpArg)) : Array (TSyntax [``Parser.Tactic.simpErase, ``Parser.Tactic.simpLemma]) × Bool := hs.foldl (init := (#[], false)) fun (out, all) stx => if stx.1.isOfKind ``Parser.Tactic.simpStar then (out, true) else (out.push ⟨stx⟩, all) def trSimpCore (autoUnfold trace : Bool) : TacM Syntax.Tactic := do let o := optTk (← parse onlyFlag) let hs ← trSimpArgs (← parse simpArgList) let (hs', all) := filterSimpStar hs let attrs := (← parse (tk "with" *> ident*)?).getD #[] let loc ← parse location let (cfg, disch) ← parseSimpConfig (← expr?) let cfg ← mkConfigStx? (cfg.bind quoteSimpConfig) let simpAll := all && loc matches Location.wildcard if simpAll then let hs' := (hs' ++ attrs.map trSimpExt).asNonempty match autoUnfold, trace with | true, true => `(tactic| simp_all?! $(cfg)? $(disch)? $[only%$o]? $[[$[$hs'],*]]?) | false, true => `(tactic| simp_all? $(cfg)? $(disch)? $[only%$o]? $[[$[$hs'],*]]?) | true, false => `(tactic| simp_all! $(cfg)? $(disch)? $[only%$o]? $[[$[$hs'],*]]?) | false, false => `(tactic| simp_all $(cfg)? $(disch)? $[only%$o]? $[[$[$hs'],*]]?) else let hs := (hs ++ attrs.map trSimpExt).asNonempty let loc ← trLoc loc match autoUnfold, trace with | true, true => `(tactic| simp?! $(cfg)? $(disch)? $[only%$o]? $[[$[$hs],*]]? $(loc)?) | false, true => `(tactic| simp? $(cfg)? $(disch)? $[only%$o]? $[[$[$hs],*]]? $(loc)?) | true, false => `(tactic| simp! $(cfg)? $(disch)? $[only%$o]? $[[$[$hs],*]]? $(loc)?) | false, false => `(tactic| simp $(cfg)? $(disch)? $[only%$o]? $[[$[$hs],*]]? $(loc)?) @[tr_tactic simp] def trSimp : TacM Syntax.Tactic := do let autoUnfold ← parse (tk "!")?; let trace ← parse (tk "?")? trSimpCore autoUnfold.isSome trace.isSome @[tr_tactic trace_simp_set] def trTraceSimpSet : TacM Syntax.Tactic := do let _o ← parse onlyFlag let _hs ← parse simpArgList let _attrs ← parse withIdentList warn! "unsupported: trace_simp_set" @[tr_tactic simp_intros] def trSimpIntros : TacM Syntax.Tactic := do let ids := (← parse ident_*).map trBinderIdent let o := optTk (← parse onlyFlag) let hs ← trSimpArgs (← parse simpArgList) let attrs := (← parse (tk "with" *> ident*)?).getD #[] let hs := (hs ++ attrs.map trSimpExt).asNonempty let cfg := (← parseSimpConfig (← expr?)).1.bind quoteSimpConfig `(tactic| simp_intro $[(config := $cfg)]? $[$ids]* $[only%$o]? $[[$hs,*]]?) def trDSimpCore (autoUnfold trace : Bool) (parseCfg : TacM (Option (Spanned AST3.Expr))) : TacM Syntax.Tactic := do let o := optTk (← parse onlyFlag) let hs ← trSimpArgs (← parse simpArgList) let (hs, _all) := filterSimpStar hs -- dsimp [*] is always pointless let attrs := (← parse (tk "with" *> ident*)?).getD #[] let hs := (hs ++ attrs.map trSimpExt).asNonempty let loc ← trLoc (← parse location) let cfg := (← parseSimpConfig (← parseCfg)).1.bind quoteSimpConfig match autoUnfold, trace with | true, true => `(tactic| dsimp?! $[(config := $cfg)]? $[only%$o]? $[[$hs,*]]? $(loc)?) | false, true => `(tactic| dsimp? $[(config := $cfg)]? $[only%$o]? $[[$hs,*]]? $(loc)?) | true, false => `(tactic| dsimp! $[(config := $cfg)]? $[only%$o]? $[[$hs,*]]? $(loc)?) | false, false => `(tactic| dsimp $[(config := $cfg)]? $[only%$o]? $[[$hs,*]]? $(loc)?) @[tr_tactic dsimp] def trDSimp : TacM Syntax.Tactic := trDSimpCore false false expr? @[tr_tactic reflexivity refl] def trRefl : TacM Syntax.Tactic := `(tactic| rfl) @[tr_ni_tactic tactic.interactive.refl] def trNIRefl (_ : AST3.Expr) : M Syntax.Tactic := `(tactic| rfl) @[tr_tactic symmetry] def trSymmetry : TacM Syntax.Tactic := `(tactic| symm) @[tr_tactic transitivity] def trTransitivity : TacM Syntax.Tactic := do `(tactic| trans $[$(← liftM $ (← parse (pExpr)?).mapM trExpr)]?) @[tr_tactic ac_reflexivity ac_refl] def trACRefl : TacM Syntax.Tactic := `(tactic| ac_rfl) @[tr_tactic cc] def trCC : TacM Syntax.Tactic := `(tactic| cc) @[tr_tactic subst] def trSubst : TacM Syntax.Tactic := do `(tactic| subst $(← trExpr (← parse pExpr))) @[tr_tactic subst_vars] def trSubstVars : TacM Syntax.Tactic := `(tactic| subst_vars) @[tr_tactic clear] def trClear : TacM Syntax.Tactic := do match ← parse ident* with | #[] => `(tactic| skip) | ids => `(tactic| clear $[$(ids.map mkIdent)]*) @[tr_tactic dunfold] def trDUnfold : TacM Syntax.Tactic := do let cs ← parse ident* let loc ← parse location let cfg ← mkConfigStx? $ (← parseSimpConfig (← expr?)).1.bind quoteSimpConfig let cs ← liftM $ cs.mapM mkIdentI `(tactic| dsimp $[$cfg:config]? only [$[$cs:ident],*] $[$(← trLoc loc):location]?) @[tr_tactic delta] def trDelta : TacM Syntax.Tactic := do `(tactic| delta $(← liftM $ (← parse ident*).mapM mkIdentI)* $[$(← trLoc (← parse location))]?) @[tr_tactic unfold_projs] def trUnfoldProjs : TacM Syntax.Tactic := do let loc ← parse location if (← expr?).isSome then warn! "warning: unsupported: unfold_projs config" `(tactic| unfold_projs $[$(← trLoc loc):location]?) @[tr_tactic unfold] def trUnfold : TacM Syntax.Tactic := do let cs ← parse ident* let loc ← parse location if (← expr?).isSome then warn! "warning: unsupported: unfold config" let cs ← liftM $ cs.mapM mkIdentI `(tactic| unfold $[$cs:ident]* $[$(← trLoc loc):location]?) @[tr_tactic unfold1] def trUnfold1 : TacM Syntax.Tactic := do let cs ← parse ident* let loc ← parse location if (← expr?).isSome then warn! "warning: unsupported: unfold config" let cs ← liftM $ cs.mapM mkIdentI let loc ← trLoc loc let tac ← cs.mapM fun c => `(tactic| unfold $c:ident $[$loc:location]?) match tac with | #[tac] => pure tac | _ => `(tactic| first $[| $tac:tactic]*) @[tr_tactic apply_opt_param apply_auto_param] def trInferParam : TacM Syntax.Tactic := `(tactic| infer_param) @[tr_tactic fail_if_success success_if_fail] def trFailIfSuccess : TacM Syntax.Tactic := do `(tactic| fail_if_success $(← trBlock (← itactic)):tacticSeq) @[tr_tactic guard_expr_eq] def trGuardExprEq : TacM Syntax.Tactic := do `(tactic| guard_expr $(← trExpr (← expr!)) =ₐ $(← trExpr (← parse (tk ":=" *> pExpr)))) @[tr_tactic guard_target] def trGuardTarget : TacM Syntax.Tactic := do `(tactic| guard_target =ₐ $(← trExpr (← parse pExpr))) @[tr_tactic guard_hyp] def trGuardHyp : TacM Syntax.Tactic := do `(tactic| guard_hyp $(mkIdent (← parse ident)) $[:ₐ $(← liftM $ (← parse (tk ":" *> pExpr)?).mapM trExpr)]? $[:=ₐ $(← liftM $ (← parse (tk ":=" *> pExpr)?).mapM trExpr)]?) @[tr_tactic match_target] def trMatchTarget : TacM Syntax.Tactic := do let t ← trExpr (← parse pExpr) let m ← expr? if m.isSome then warn! "warning: unsupported: match_target reducibility" `(tactic| match_target $t) @[tr_tactic by_cases] def trByCases : TacM Syntax.Tactic := do let (n, q) ← parse casesArg let q ← trExpr q `(tactic| by_cases $[$(n.map mkIdent) :]? $q) @[tr_tactic funext] def trFunext : TacM Syntax.Tactic := do `(tactic| funext $[$((← parse ident_*).map trIdent_)]*) @[tr_tactic by_contradiction by_contra] def trByContra : TacM Syntax.Tactic := do `(tactic| by_contra $[$((← parse (ident)?).map mkIdent):ident]?) @[tr_tactic type_check] def trTypeCheck : TacM Syntax.Tactic := do `(tactic| type_check $(← trExpr (← parse pExpr))) @[tr_tactic done] def trDone : TacM Syntax.Tactic := do `(tactic| done) @[tr_tactic «show»] def trShow : TacM Syntax.Tactic := do `(tactic| show $(← trExpr (← parse pExpr))) @[tr_tactic specialize] def trSpecialize : TacM Syntax.Tactic := do let (head, args) ← trAppArgs (← parse pExpr) fun e => match e.kind.unparen with | Expr.ident h => pure h | Expr.«@» false ⟨_, Expr.ident h⟩ => warn! "unsupported: specialize @hyp" | pure h | _ => warn! "unsupported: specialize non-hyp" `(tactic| specialize $(Syntax.mkApp (mkIdent head) args)) @[tr_tactic congr] def trCongr : TacM Syntax.Tactic := do `(tactic| congr) @[tr_tactic rsimp] def trRSimp : TacM Syntax.Tactic := do `(tactic| rsimp) @[tr_tactic comp_val] def trCompVal : TacM Syntax.Tactic := do `(tactic| comp_val) @[tr_tactic async] def trAsync : TacM Syntax.Tactic := do `(tactic| async $(← trBlock (← itactic)):tacticSeq) @[tr_tactic conv] def trConvTac : TacM Syntax.Tactic := do `(tactic| conv $[at $((← parse (tk "at" *> ident)?).map mkIdent)]? $[in $(← liftM $ (← parse (tk "in" *> pExpr)?).mapM trExpr):term]? => $(← trConvBlock (← itactic)):convSeq) @[tr_conv conv] def trConvConv : TacM Syntax.Conv := do `(conv| conv => $(← trConvBlock (← itactic)):convSeq) @[tr_conv skip] def trSkipConv : TacM Syntax.Conv := `(conv| skip) @[tr_conv whnf] def trWhnfConv : TacM Syntax.Conv := `(conv| whnf) @[tr_conv dsimp] def trDSimpConv : TacM Syntax.Conv := do let o := optTk (← parse onlyFlag) let hs ← trSimpArgs (← parse simpArgList) let (hs, _all) := filterSimpStar hs -- dsimp [*] is always pointless let attrs := (← parse (tk "with" *> ident*)?).getD #[] let hs := (hs ++ attrs.map trSimpExt).asNonempty let cfg := (← parseSimpConfig (← expr?)).1.bind quoteSimpConfig `(conv| dsimp $[(config := $cfg)]? $[only%$o]? $[[$hs,*]]?) @[tr_conv trace_lhs] def trTraceLHSConv : TacM Syntax.Conv := `(conv| trace_state) @[tr_conv change] def trChangeConv : TacM Syntax.Conv := do `(conv| change $(← trExpr (← parse pExpr))) @[tr_conv congr] def trCongrConv : TacM Syntax.Conv := `(conv| congr) @[tr_conv funext] def trFunextConv : TacM Syntax.Conv := `(conv| ext) @[tr_conv to_lhs] def trToLHSConv : TacM Syntax.Conv := `(conv| lhs) @[tr_conv to_rhs] def trToRHSConv : TacM Syntax.Conv := `(conv| rhs) @[tr_conv done] def trDoneConv : TacM Syntax.Conv := `(conv| done) @[tr_conv find] def trFindConv : TacM Syntax.Conv := do `(conv| (pattern $(← trExpr (← parse pExpr)):term; ($(← trConvBlock (← itactic)):convSeq))) @[tr_conv «for»] def trForConv : TacM Syntax.Conv := do let pat ← trExpr (← parse pExpr) let occs ← parse (listOf smallNat) let tac ← trConvBlock (← itactic) `(conv| pattern (occs := $[$(occs.map quote):num]*) $pat:term <;> ($tac)) @[tr_conv simp] def trSimpConv : TacM Syntax.Conv := do let o := optTk (← parse onlyFlag) let hs ← trSimpArgs (← parse simpArgList) let attrs := (← parse (tk "with" *> ident*)?).getD #[] let hs := (hs ++ attrs.map trSimpExt).asNonempty let (cfg, disch) ← parseSimpConfig (← expr?) let cfg ← mkConfigStx? (cfg.bind quoteSimpConfig) `(conv| simp $(cfg)? $(disch)? $[only%$o]? $[[$hs,*]]?) @[tr_conv guard_lhs] def trGuardLHSConv : TacM Syntax.Conv := do `(conv| guard_target =ₐ $(← trExpr (← parse pExpr))) @[tr_conv rewrite rw] def trRwConv : TacM Syntax.Conv := do let q ← liftM $ (← parse rwRules).mapM trRwRule if let some cfg ← expr? then warn! "warning: unsupported: rw with cfg: {repr cfg}" `(conv| rw [$q,*]) section variable (input : String) (p : ParserM α) private partial def getChunk (acc : String) (i : String.Pos) : Bool × String.Pos × String := if input.atEnd i then (false, i, acc) else let c := input.get i let i := input.next i if c == '{' then if input.get i == '{' then getChunk (acc ++ "\\{") (input.next i) else (true, i, acc) else getChunk (acc.push c) i private partial def parseChunks [Repr α] (acc : String) (i : String.Pos) (out : Array (Sum String α)) : ParserM (Array (Sum String α)) := do let (next, i, acc) := getChunk input acc i if next then let (a, sz) ← withInput p let i := i + ⟨sz⟩ guard (input.get i == '}'); let i := input.next i parseChunks "}" i (out.push (Sum.inl (acc.push '{')) |>.push (Sum.inr a)) else pure $ out.push (Sum.inl (acc.push '\"')) private partial def getStr : AST3.Expr → M String | Expr.string s => pure s | Expr.notation n #[⟨_, Arg.expr s1⟩, ⟨_, Arg.expr s2⟩] => do if n.name == `«expr ++ » then pure $ (← getStr s1.unparen) ++ (← getStr s2.unparen) else warn! "unsupported: interpolated non string literal" | _ => warn! "unsupported: interpolated non string literal" open TSyntax.Compat in def trInterpolatedStr (f : Syntax → TacM Syntax := pure) : TacM (TSyntax interpolatedStrKind) := do let s ← getStr (← expr!).kind.unparen let chunks ← parse $ parseChunks s pExpr "\"" 0 #[] mkNode interpolatedStrKind <$> chunks.mapM fun | Sum.inl s => pure (Syntax.mkLit interpolatedStrLitKind s).1 | Sum.inr e => do f (← trExpr e) end @[tr_user_nota format_macro] def trFormatMacro : TacM Syntax.Term := do `(f! $(← trInterpolatedStr)) @[tr_user_nota sformat_macro] def trSFormatMacro : TacM Syntax.Term := do `(s! $(← trInterpolatedStr)) @[tr_tactic min_tac] def trMinTac : TacM Syntax.Tactic := do -- wrong, but better than breakage `(tactic| exact minTac $(← trExpr (← parse pExpr)) $(← trExpr (← parse pExpr))) @[tr_ni_tactic control_laws_tac] def trControlLawsTac (_ : AST3.Expr) : M Syntax.Tactic := `(tactic| (intros; rfl)) @[tr_tactic blast_disjs] def trBlastDisjs : TacM Syntax.Tactic := `(tactic| cases_type* or)
7c387a86fb502bc5ae98cf929026db827d435044
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/while/Reduce.lean
e5fb744effee7c13e71698131deece444f508a26
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
5,934
lean
import Stmt open Stmt axiom LEM : forall (p:Prop), p ∨ ¬p -- Small step semantics, aka reduction relation inductive Reduce : Stmt → Env → Stmt → Env → Prop | ASN : ∀ (x:string) (a:AExp) (s:Env), Reduce (assign x a) s skip (bindVar x a s) | SEQ_STEP: ∀ (e₁ e₁' e₂:Stmt) (s s':Env), Reduce e₁ s e₁' s' → Reduce (e₁ ;; e₂) s (e₁' ;; e₂) s' | SEQ_SKIP: ∀ (e:Stmt) (s:Env), Reduce (skip ;; e) s e s | IF_T : ∀ (b:BExp) (e₁ e₂:Stmt) (s:Env), b s → Reduce (ite b e₁ e₂) s e₁ s | IF_F : ∀ (b:BExp) (e₁ e₂:Stmt) (s:Env), ¬ b s → Reduce (ite b e₁ e₂) s e₂ s | WHILE : ∀ (b:BExp) (e:Stmt) (s:Env), Reduce (while b e) s (ite b (e ;; (while b e)) skip) s open Reduce -- Predicate expressing that no further reduction is possible def Value (e:Stmt) (s:Env) : Prop := ¬ (∃ (e':Stmt) (s':Env), Reduce e s e' s') -- Sequential statement always reduces lemma seqReduce : ∀ (e₁ e₂:Stmt) (s:Env), (∃ (e':Stmt) (s':Env), Reduce (e₁ ;; e₂) s e' s') := begin intros e₁, induction e₁ with x a e₁ e₁' IH1 IH1' b e₁ e₁' IH1 IH1' b e₁ IH1; intros e₂ s, { existsi e₂, existsi s, constructor }, { existsi (skip ;; e₂), existsi (bindVar x a s), apply SEQ_STEP, apply ASN }, { clear IH1', cases (IH1 e₁' s) with e H1, cases H1 with s' H1, existsi (e ;; e₂), existsi s', apply SEQ_STEP, assumption }, { cases (LEM (b s)) with H1 H1, { existsi (e₁ ;; e₂), existsi s, apply SEQ_STEP, apply IF_T, assumption }, { existsi (e₁' ;; e₂), existsi s, apply SEQ_STEP, apply IF_F, assumption }}, { existsi ((ite b (e₁ ;; while b e₁) skip) ;; e₂), existsi s, apply SEQ_STEP, apply WHILE}, end lemma ValueIsSkip : ∀ (e:Stmt) (s:Env), Value e s ↔ e = skip := begin intros e s, split; intros H, { unfold Value at H, revert s, cases e with x a e₁ e₂ b e₁ e₂ b e₁; intros s H, { refl }, { exfalso, apply H, existsi skip, existsi (bindVar x a s), constructor }, { exfalso, apply H, apply seqReduce }, { exfalso, apply H, cases (LEM (b s)), { existsi e₁, existsi s, constructor, assumption }, { existsi e₂, existsi s, constructor, assumption }}, { exfalso, apply H, existsi (ite b (e₁ ;; while b e₁) skip), existsi s, constructor}}, { intros H1, cases H1 with e' H1, cases H1 with s' H1, cases H1 with x a H1 e₁ e₁' e₂ H1 _ _ _ _ b _ e H1 _ b e₁ H1 _ _ b e₁ H1, { cases H }, { cases H }, { cases H }, { cases H }, { cases H }, { cases H }} end lemma ReduceDeterministic : ∀ (e e₁ e₂:Stmt) (s s₁ s₂:Env), Reduce e s e₁ s₁ → Reduce e s e₂ s₂ → e₁ = e₂ ∧ s₁ = s₂ := begin intros e e₁ e₂ s s₁ s₂ H1, revert e₂ s₂, induction H1 with x a s e' e₁ e₂ s' s₁ H1 IH e₁ s₁ b e₁ e₁' s₁ H1 b e₁' e₁ s₁ H1 b e₁ s₁; intros e₂ s₂ H2, { cases H2, split, { refl }, { unfold bindVar}}, { cases H2 with _ _ _ _ e₁' _ _ _ H3, { cases (IH e₁' s₂ H3) with H4 H5, split, { rw H4 }, { assumption }}, { exfalso, have H3 : Value skip s' := begin rw ValueIsSkip end , apply H3, existsi e₁, existsi s₁, assumption }}, { cases H2 with _ _ _ _ e₂ _ _ _ H3, { exfalso, have H4 : Value skip s₁ := begin rw ValueIsSkip end, apply H4, existsi e₂, existsi s₂, assumption }, { split; refl }}, { cases H2 with _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H3, { split; refl }, { exfalso, apply H3, assumption }}, { cases H2 with _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H3, { exfalso, apply H1, assumption, }, { split; refl }}, { cases H2, split; refl } end lemma ReduceSkipIff : ∀ (e:Stmt) (s t:Env), ¬ Reduce skip s e t := begin intros e s t H1, have H2 : Value skip s := begin rw ValueIsSkip end, apply H2, existsi e, existsi t, assumption end @[simp] lemma ReduceSeqIff : ∀ (e₁ e₂ e':Stmt) (s s':Env), Reduce (e₁ ;; e₂) s e' s' ↔ (exists (e₁':Stmt), Reduce e₁ s e₁' s' ∧ e' = (e₁' ;; e₂)) ∨ (e₁ = skip ∧ e' = e₂ ∧ s' = s) := begin intros e₁ e₂ e' s s', split; intros H1, { cases H1 with _ _ _ _ e₁' _ _ _ H2, { left, existsi e₁', split, { assumption }, { refl }}, { right, split, { refl }, { split; refl }}}, { cases H1 with H1 H1, { cases H1 with e₁' H1, cases H1 with H1 H2, rw H2, constructor, assumption }, { cases H1 with H1 H2, cases H2 with H2 H3, rw [H1,H2,H3], constructor }} end @[simp] lemma ReduceIteIff : ∀ (b:BExp) (e₁ e₂ e':Stmt) (s s':Env), Reduce (ite b e₁ e₂) s e' s' ↔ (b s ∧ e' = e₁ ∧ s' = s) ∨ (¬ b s ∧ e' = e₂ ∧ s' = s) := begin intros b e₁ e₂ e' s s', split; intros H1, { cases H1 with _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ H2, { left, split, { assumption }, { split; refl }}, { right, split, { assumption }, { split; refl }}}, { cases H1 with H1 H1, { cases H1 with H1 H2, cases H2 with H2 H3, rw [H2,H3], constructor, assumption }, { cases H1 with H1 H2, cases H2 with H2 H3, rw [H2, H3], constructor, assumption }} end lemma ReduceWhileIff : ∀ (b:BExp) (e e':Stmt) (s s':Env), Reduce (while b e) s e' s' ↔ e' = ite b (e ;; while b e) skip ∧ s' = s := begin intros b e e' s s', split; intros H1, { cases H1, split; refl}, { cases H1 with H1 H2, rw [H1,H2], constructor } end lemma ReduceAssignIff : ∀ (x:string) (a:AExp) (e':Stmt) (s s':Env), Reduce (x :== a) s e' s' ↔ e' = skip ∧ s' = bindVar x a s := begin intros x a e' s s', split; intros H1, { cases H1, split; refl }, { cases H1 with H1 H2, rw [H1, H2], constructor } end
37890c092a091935d3d3399e1c26b032088bf492
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/impbug2.lean
66f2dccfba8ed59115d830979a86d604d6be4fad
[ "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
726
lean
-- category definition Prop := Type.{0} constant eq {A : Type} : A → A → Prop infix `=`:50 := eq inductive category (ob : Type) (mor : ob → ob → Type) : Type := mk : Π (id : Π (A : ob), mor A A), (Π (A B : ob) (f : mor A A), id A = f) → category ob mor definition id (ob : Type) (mor : ob → ob → Type) (Cat : category ob mor) := category.rec (λ id idl, id) Cat constant ob : Type.{1} constant mor : ob → ob → Type.{1} constant Cat : category ob mor theorem id_left (A : ob) (f : mor A A) : @eq (mor A A) (id ob mor Cat A) f := @category.rec ob mor (λ (C : category ob mor), @eq (mor A A) (id ob mor C A) f) (λ (id : Π (T : ob), mor T T) (idl : Π (T : ob), _), idl A A f) Cat
cd335b1d5274816f17c6352201f376ff1bb8ea07
49ffcd4736fa3bdcc1cdbb546d4c855d67c0f28a
/tests/lean/structure_instance_info.lean
cbcd4d2c63cf0b3eca8e42ecca0718c4d184f30a
[ "Apache-2.0" ]
permissive
black13/lean
979e24d09e17b2fdf8ec74aac160583000086bc8
1a80ea9c8e28902cadbfb612896bcd45ba4ce697
refs/heads/master
1,626,839,620,164
1,509,113,016,000
1,509,122,889,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
463
lean
open tactic run_cmd do let e := pexpr.mk_structure_instance { struct := some "prod", field_names := ["fst", "snd"], field_values := [``(1), ``(2)] }, let f := pexpr.mk_structure_instance { source := some e, field_names := ["snd"], field_values := [``(1)] }, to_expr e >>= trace, to_expr f >>= trace, trace $ e.get_structure_instance_info >>= structure_instance_info.struct, trace $ f.get_structure_instance_info >>= structure_instance_info.struct
6d9176fc903c76746c5143e96ab9ad06c0836666
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/data/equiv/local_equiv.lean
a82f75a9c31322b432a4d2b83a329cfd1c93163f
[ "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
23,988
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.equiv.basic /-! # Local equivalences This files defines equivalences between subsets of given types. An element `e` of `local_equiv α β` is made of two maps `e.to_fun` and `e.inv_fun` respectively from α to β and from β to α (just like equivs), which are inverse to each other on the subsets `e.source` and `e.target` of respectively α and β. They are designed in particular to define charts on manifolds. The main functionality is `e.trans f`, which composes the two local equivalences by restricting the source and target to the maximal set where the composition makes sense. As for equivs, we register a coercion to functions and use it in our simp normal form: we write `e x` and `e.symm y` instead of `e.to_fun x` and `e.inv_fun y`. ## Main definitions `equiv.to_local_equiv`: associating a local equiv to an equiv, with source = target = univ `local_equiv.symm` : the inverse of a local equiv `local_equiv.trans` : the composition of two local equivs `local_equiv.refl` : the identity local equiv `local_equiv.of_set` : the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local equivs (see below in implementation notes) ## Implementation notes There are at least three possible implementations of local equivalences: * equivs on subtypes * pairs of functions taking values in `option α` and `option β`, equal to none where the local equivalence is not defined * pairs of functions defined everywhere, keeping the source and target as additional data Each of these implementations has pros and cons. * When dealing with subtypes, one still need to define additional API for composition and restriction of domains. Checking that one always belongs to the right subtype makes things very tedious, and leads quickly to DTT hell (as the subtype `u ∩ v` is not the "same" as `v ∩ u`, for instance). * With option-valued functions, the composition is very neat (it is just the usual composition, and the domain is restricted automatically). These are implemented in `pequiv.lean`. For manifolds, where one wants to discuss thoroughly the smoothness of the maps, this creates however a lot of overhead as one would need to extend all classes of smoothness to option-valued maps. * The local_equiv version as explained above is easier to use for manifolds. The drawback is that there is extra useless data (the values of `to_fun` and `inv_fun` outside of `source` and `target`). In particular, the equality notion between local equivs is not "the right one", i.e., coinciding source and target and equality there. Moreover, there are no local equivs in this sense between an empty type and a nonempty type. Since empty types are not that useful, and since one almost never needs to talk about equal local equivs, this is not an issue in practice. Still, we introduce an equivalence relation `eq_on_source` that captures this right notion of equality, and show that many properties are invariant under this equivalence relation. -/ mk_simp_attribute mfld_simps "The simpset `mfld_simps` records several simp lemmas that are especially useful in manifolds. It is a subset of the whole set of simp lemmas, but it makes it possible to have quicker proofs (when used with `squeeze_simp` or `simp only`) while retaining readability. The typical use case is the following, in a file on manifolds: If `simp [foo, bar]` is slow, replace it with `squeeze_simp [foo, bar] with mfld_simps` and paste its output. The list of lemmas should be reasonable (contrary to the output of `squeeze_simp [foo, bar]` which might contain tens of lemmas), and the outcome should be quick enough. " open function set variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Local equivalence between subsets `source` and `target` of α and β respectively. The (global) maps `to_fun : α → β` and `inv_fun : β → α` map `source` to `target` and conversely, and are inverse to each other there. The values of `to_fun` outside of `source` and of `inv_fun` outside of `target` are irrelevant. -/ @[nolint has_inhabited_instance] structure local_equiv (α : Type*) (β : Type*) := (to_fun : α → β) (inv_fun : β → α) (source : set α) (target : set β) (map_source' : ∀{x}, x ∈ source → to_fun x ∈ target) (map_target' : ∀{x}, x ∈ target → inv_fun x ∈ source) (left_inv' : ∀{x}, x ∈ source → inv_fun (to_fun x) = x) (right_inv' : ∀{x}, x ∈ target → to_fun (inv_fun x) = x) /-- Associating a local_equiv to an equiv-/ def equiv.to_local_equiv (e : equiv α β) : local_equiv α β := { to_fun := e.to_fun, inv_fun := e.inv_fun, source := univ, target := univ, map_source' := λx hx, mem_univ _, map_target' := λy hy, mem_univ _, left_inv' := λx hx, e.left_inv x, right_inv' := λx hx, e.right_inv x } namespace local_equiv variables (e : local_equiv α β) (e' : local_equiv β γ) /-- The inverse of a local equiv -/ protected def symm : local_equiv β α := { to_fun := e.inv_fun, inv_fun := e.to_fun, source := e.target, target := e.source, map_source' := e.map_target', map_target' := e.map_source', left_inv' := e.right_inv', right_inv' := e.left_inv' } instance : has_coe_to_fun (local_equiv α β) := ⟨_, local_equiv.to_fun⟩ @[simp, mfld_simps] theorem coe_mk (f : α → β) (g s t ml mr il ir) : (local_equiv.mk f g s t ml mr il ir : α → β) = f := rfl @[simp, mfld_simps] theorem coe_symm_mk (f : α → β) (g s t ml mr il ir) : ((local_equiv.mk f g s t ml mr il ir).symm : β → α) = g := rfl @[simp, mfld_simps] lemma to_fun_as_coe : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_as_coe : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h protected lemma maps_to : maps_to e e.source e.target := λ _, e.map_source @[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to @[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h protected lemma left_inv_on : left_inv_on e.symm e e.source := λ _, e.left_inv @[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h protected lemma right_inv_on : right_inv_on e.symm e e.target := λ _, e.right_inv /-- Associating to a local_equiv an equiv between the source and the target -/ protected def to_equiv : equiv (e.source) (e.target) := { to_fun := λ x, ⟨e x, e.map_source x.mem⟩, inv_fun := λ y, ⟨e.symm y, e.map_target y.mem⟩, left_inv := λ⟨x, hx⟩, subtype.eq $ e.left_inv hx, right_inv := λ⟨y, hy⟩, subtype.eq $ e.right_inv hy } @[simp, mfld_simps] lemma symm_source : e.symm.source = e.target := rfl @[simp, mfld_simps] lemma symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := by { cases e, refl } /-- A local equiv induces a bijection between its source and target -/ lemma bij_on_source : bij_on e e.source e.target := inv_on.bij_on ⟨e.left_inv_on, e.right_inv_on⟩ e.maps_to e.symm_maps_to lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := begin refine subset.antisymm (λx hx, _) (λx hx, _), { rcases (mem_image _ _ _).1 hx with ⟨y, ys, hy⟩, rw ← hy, split, { apply e.map_source, exact h ys }, { rwa [mem_preimage, e.left_inv (h ys)] } }, { rw ← e.right_inv hx.1, exact mem_image_of_mem _ hx.2 } end lemma image_inter_source_eq (s : set α) : e '' (s ∩ e.source) = e.target ∩ e.symm ⁻¹' (s ∩ e.source) := e.image_eq_target_inter_inv_preimage (inter_subset_right _ _) lemma image_inter_source_eq' (s : set α) : e '' (s ∩ e.source) = e.target ∩ e.symm ⁻¹' s := begin rw e.image_eq_target_inter_inv_preimage (inter_subset_right _ _), ext x, split; { assume hx, simp at hx, simp [hx] } end lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma symm_image_inter_target_eq (s : set β) : e.symm '' (s ∩ e.target) = e.source ∩ e ⁻¹' (s ∩ e.target) := e.symm.image_inter_source_eq _ lemma symm_image_inter_target_eq' (s : set β) : e.symm '' (s ∩ e.target) = e.source ∩ e ⁻¹' s := e.symm.image_inter_source_eq' _ lemma source_inter_preimage_inv_preimage (s : set α) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := begin ext, split, { rintros ⟨hx, xs⟩, simp only [mem_preimage, hx, e.left_inv, mem_preimage] at xs, exact ⟨hx, xs⟩ }, { rintros ⟨hx, xs⟩, simp [hx, xs] } end lemma target_inter_inv_preimage_preimage (s : set β) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ lemma image_source_eq_target : e '' e.source = e.target := e.bij_on_source.image_eq lemma source_subset_preimage_target : e.source ⊆ e ⁻¹' e.target := λx hx, e.map_source hx lemma inv_image_target_eq_source : e.symm '' e.target = e.source := e.symm.bij_on_source.image_eq lemma target_subset_preimage_source : e.target ⊆ e.symm ⁻¹' e.source := λx hx, e.map_target hx /-- Two local equivs that have the same `source`, same `to_fun` and same `inv_fun`, coincide. -/ @[ext] protected lemma ext {e e' : local_equiv α β} (h : ∀x, e x = e' x) (hsymm : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := begin have A : (e : α → β) = e', by { ext x, exact h x }, have B : (e.symm : β → α) = e'.symm, by { ext x, exact hsymm x }, have I : e '' e.source = e.target := e.image_source_eq_target, have I' : e' '' e'.source = e'.target := e'.image_source_eq_target, rw [A, hs, I'] at I, cases e; cases e', simp * at * end /-- Restricting a local equivalence to e.source ∩ s -/ protected def restr (s : set α) : local_equiv α β := { to_fun := e, inv_fun := e.symm, source := e.source ∩ s, target := e.target ∩ e.symm⁻¹' s, map_source' := λx hx, begin apply mem_inter, { apply e.map_source, exact hx.1 }, { rw [mem_preimage, e.left_inv], exact hx.2, exact hx.1 }, end, map_target' := λy hy, begin apply mem_inter, { apply e.map_target, exact hy.1 }, { exact hy.2 }, end, left_inv' := λx hx, e.left_inv hx.1, right_inv' := λy hy, e.right_inv hy.1 } @[simp, mfld_simps] lemma restr_coe (s : set α) : (e.restr s : α → β) = e := rfl @[simp, mfld_simps] lemma restr_coe_symm (s : set α) : ((e.restr s).symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ s := rfl @[simp, mfld_simps] lemma restr_target (s : set α) : (e.restr s).target = e.target ∩ e.symm ⁻¹' s := rfl lemma restr_eq_of_source_subset {e : local_equiv α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := local_equiv.ext (λ_, rfl) (λ_, rfl) (by simp [inter_eq_self_of_subset_left h]) @[simp, mfld_simps] lemma restr_univ {e : local_equiv α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) /-- The identity local equiv -/ protected def refl (α : Type*) : local_equiv α α := (equiv.refl α).to_local_equiv @[simp, mfld_simps] lemma refl_source : (local_equiv.refl α).source = univ := rfl @[simp, mfld_simps] lemma refl_target : (local_equiv.refl α).target = univ := rfl @[simp, mfld_simps] lemma refl_coe : (local_equiv.refl α : α → α) = id := rfl @[simp, mfld_simps] lemma refl_symm : (local_equiv.refl α).symm = local_equiv.refl α := rfl @[simp, mfld_simps] lemma refl_restr_source (s : set α) : ((local_equiv.refl α).restr s).source = s := by simp @[simp, mfld_simps] lemma refl_restr_target (s : set α) : ((local_equiv.refl α).restr s).target = s := by { change univ ∩ id⁻¹' s = s, simp } /-- The identity local equiv on a set `s` -/ def of_set (s : set α) : local_equiv α α := { to_fun := id, inv_fun := id, source := s, target := s, map_source' := λx hx, hx, map_target' := λx hx, hx, left_inv' := λx hx, rfl, right_inv' := λx hx, rfl } @[simp, mfld_simps] lemma of_set_source (s : set α) : (local_equiv.of_set s).source = s := rfl @[simp, mfld_simps] lemma of_set_target (s : set α) : (local_equiv.of_set s).target = s := rfl @[simp, mfld_simps] lemma of_set_coe (s : set α) : (local_equiv.of_set s : α → α) = id := rfl @[simp, mfld_simps] lemma of_set_symm (s : set α) : (local_equiv.of_set s).symm = local_equiv.of_set s := rfl /-- Composing two local equivs if the target of the first coincides with the source of the second. -/ protected def trans' (e' : local_equiv β γ) (h : e.target = e'.source) : local_equiv α γ := { to_fun := e' ∘ e, inv_fun := e.symm ∘ e'.symm, source := e.source, target := e'.target, map_source' := λx hx, by simp [h.symm, hx], map_target' := λy hy, by simp [h, hy], left_inv' := λx hx, by simp [hx, h.symm], right_inv' := λy hy, by simp [hy, h] } /-- Composing two local equivs, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_equiv α γ := local_equiv.trans' (e.symm.restr (e'.source)).symm (e'.restr (e.target)) (inter_comm _ _) @[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl @[simp, mfld_simps] lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := rfl lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := begin symmetry, calc e.source ∩ e ⁻¹' (e.target ∩ e'.source) = (e.source ∩ e ⁻¹' (e.target)) ∩ e ⁻¹' (e'.source) : by rw [preimage_inter, inter_assoc] ... = e.source ∩ e ⁻¹' (e'.source) : by { congr' 1, apply inter_eq_self_of_subset_left e.source_subset_preimage_target } ... = (e.trans e').source : rfl end lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := by rw [e.trans_source', inter_comm e.target, e.symm_image_inter_target_eq] lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := image_source_eq_target (local_equiv.symm (local_equiv.restr (local_equiv.symm e) (e'.source))) @[simp, mfld_simps] lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_equiv γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, @preimage_comp α β γ, inter_assoc]) @[simp, mfld_simps] lemma trans_refl : e.trans (local_equiv.refl β) = e := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source]) @[simp, mfld_simps] lemma refl_trans : (local_equiv.refl α).trans e = e := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source, preimage_id]) lemma trans_refl_restr (s : set β) : e.trans ((local_equiv.refl β).restr s) = e.restr (e ⁻¹' s) := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [trans_source]) lemma trans_refl_restr' (s : set β) : e.trans ((local_equiv.refl β).restr s) = e.restr (e.source ∩ e ⁻¹' s) := local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source], rw [← inter_assoc, inter_self] } lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := local_equiv.ext (λx, rfl) (λx, rfl) $ by { simp [trans_source, inter_comm], rwa inter_assoc } /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. Then `e` and `e'` should really be considered the same local equiv. -/ def eq_on_source (e e' : local_equiv α β) : Prop := e.source = e'.source ∧ (e.source.eq_on e e') /-- `eq_on_source` is an equivalence relation -/ instance eq_on_source_setoid : setoid (local_equiv α β) := { r := eq_on_source, iseqv := ⟨ λe, by simp [eq_on_source], λe e' h, by { simp [eq_on_source, h.1.symm], exact λx hx, (h.2 hx).symm }, λe e' e'' h h', ⟨by rwa [← h'.1, ← h.1], λx hx, by { rw [← h'.2, h.2 hx], rwa ← h.1 }⟩⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- Two equivalent local equivs have the same source -/ lemma eq_on_source.source_eq {e e' : local_equiv α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local equivs coincide on the source -/ lemma eq_on_source.eq_on {e e' : local_equiv α β} (h : e ≈ e') : e.source.eq_on e e' := h.2 /-- Two equivalent local equivs have the same target -/ lemma eq_on_source.target_eq {e e' : local_equiv α β} (h : e ≈ e') : e.target = e'.target := by simp only [← image_source_eq_target, ← h.source_eq, h.2.image_eq] /-- If two local equivs are equivalent, so are their inverses. -/ lemma eq_on_source.symm' {e e' : local_equiv α β} (h : e ≈ e') : e.symm ≈ e'.symm := begin refine ⟨h.target_eq, eq_on_of_left_inv_on_of_right_inv_on e.left_inv_on _ _⟩; simp only [symm_source, h.target_eq, h.source_eq, e'.symm_maps_to], exact e'.right_inv_on.congr_right e'.symm_maps_to (h.source_eq ▸ h.eq_on.symm), end /-- Two equivalent local equivs have coinciding inverses on the target -/ lemma eq_on_source.symm_eq_on {e e' : local_equiv α β} (h : e ≈ e') : eq_on e.symm e'.symm e.target := h.symm'.eq_on /-- Composition of local equivs respects equivalence -/ lemma eq_on_source.trans' {e e' : local_equiv α β} {f f' : local_equiv β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := begin split, { rw [trans_source'', trans_source'', ← he.target_eq, ← hf.1], exact (he.symm'.eq_on.mono $ inter_subset_left _ _).image_eq }, { assume x hx, rw trans_source at hx, simp [(he.2 hx.1).symm, hf.2 hx.2] } end /-- Restriction of local equivs respects equivalence -/ lemma eq_on_source.restr {e e' : local_equiv α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := begin split, { simp [he.1] }, { assume x hx, simp only [mem_inter_eq, restr_source] at hx, exact he.2 hx.1 } end /-- Preimages are respected by equivalence -/ lemma eq_on_source.source_inter_preimage_eq {e e' : local_equiv α β} (he : e ≈ e') (s : set β) : e.source ∩ e ⁻¹' s = e'.source ∩ e' ⁻¹' s := begin ext x, simp only [mem_inter_eq, mem_preimage], split, { assume hx, rwa [← he.2 hx.1, ← he.source_eq] }, { assume hx, rwa [← (setoid.symm he).2 hx.1, he.source_eq] } end /-- Composition of a local equiv and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_equiv.of_set e.source := begin have A : (e.trans e.symm).source = e.source, by simp [trans_source, inter_eq_self_of_subset_left (source_subset_preimage_target _)], refine ⟨by simp [A], λx hx, _⟩, rw A at hx, simp [hx] end /-- Composition of the inverse of a local equiv and this local equiv is equivalent to the restriction of the identity to the target -/ lemma trans_symm_self : e.symm.trans e ≈ local_equiv.of_set e.target := trans_self_symm (e.symm) /-- Two equivalent local equivs are equal when the source and target are univ -/ lemma eq_of_eq_on_source_univ (e e' : local_equiv α β) (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := begin apply local_equiv.ext (λx, _) (λx, _) h.1, { apply h.2, rw s, exact mem_univ _ }, { apply h.symm'.2, rw [symm_source, t], exact mem_univ _ } end section prod /-- The product of two local equivs, as a local equiv on the product. -/ def prod (e : local_equiv α β) (e' : local_equiv γ δ) : local_equiv (α × γ) (β × δ) := { source := set.prod e.source e'.source, target := set.prod e.target e'.target, to_fun := λp, (e p.1, e' p.2), inv_fun := λp, (e.symm p.1, e'.symm p.2), map_source' := λp hp, by { simp at hp, simp [hp] }, map_target' := λp hp, by { simp at hp, simp [map_target, hp] }, left_inv' := λp hp, by { simp at hp, simp [hp] }, right_inv' := λp hp, by { simp at hp, simp [hp] } } @[simp, mfld_simps] lemma prod_source (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').source = set.prod e.source e'.source := rfl @[simp, mfld_simps] lemma prod_target (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').target = set.prod e.target e'.target := rfl @[simp, mfld_simps] lemma prod_coe (e : local_equiv α β) (e' : local_equiv γ δ) : ((e.prod e') : α × γ → β × δ) = (λp, (e p.1, e' p.2)) := rfl lemma prod_coe_symm (e : local_equiv α β) (e' : local_equiv γ δ) : ((e.prod e').symm : β × δ → α × γ) = (λp, (e.symm p.1, e'.symm p.2)) := rfl @[simp, mfld_simps] lemma prod_symm (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').symm = (e.symm.prod e'.symm) := by ext x; simp [prod_coe_symm] @[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*} (e : local_equiv α β) (f : local_equiv β γ) (e' : local_equiv δ η) (f' : local_equiv η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := by ext x; simp [ext_iff]; tauto end prod end local_equiv namespace set -- All arguments are explicit to avoid missing information in the pretty printer output /-- A bijection between two sets `s : set α` and `t : set β` provides a local equivalence between `α` and `β`. -/ @[simps] noncomputable def bij_on.to_local_equiv [nonempty α] (f : α → β) (s : set α) (t : set β) (hf : bij_on f s t) : local_equiv α β := { to_fun := f, inv_fun := inv_fun_on f s, source := s, target := t, map_source' := hf.maps_to, map_target' := hf.surj_on.maps_to_inv_fun_on, left_inv' := hf.inv_on_inv_fun_on.1, right_inv' := hf.inv_on_inv_fun_on.2 } /-- A map injective on a subset of its domain provides a local equivalence. -/ @[simp, mfld_simps] noncomputable def inj_on.to_local_equiv [nonempty α] (f : α → β) (s : set α) (hf : inj_on f s) : local_equiv α β := hf.bij_on_image.to_local_equiv f s (f '' s) end set namespace equiv /- equivs give rise to local_equiv. We set up simp lemmas to reduce most properties of the local equiv to that of the equiv. -/ variables (e : equiv α β) (e' : equiv β γ) @[simp, mfld_simps] lemma to_local_equiv_coe : (e.to_local_equiv : α → β) = e := rfl @[simp, mfld_simps] lemma to_local_equiv_symm_coe : (e.to_local_equiv.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma to_local_equiv_source : e.to_local_equiv.source = univ := rfl @[simp, mfld_simps] lemma to_local_equiv_target : e.to_local_equiv.target = univ := rfl @[simp, mfld_simps] lemma refl_to_local_equiv : (equiv.refl α).to_local_equiv = local_equiv.refl α := rfl @[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl @[simp, mfld_simps] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := local_equiv.ext (λx, rfl) (λx, rfl) (by simp [local_equiv.trans_source, equiv.to_local_equiv]) end equiv
47d5afe77dff6f44a8a2ad0c2102aab1e886b7a5
c777c32c8e484e195053731103c5e52af26a25d1
/src/number_theory/number_field/embeddings.lean
2e1883a6753cd744e1f12a653aecaa332dde24bc
[ "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
19,563
lean
/- Copyright (c) 2022 Xavier Roblot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex J. Best, Xavier Roblot -/ import analysis.complex.polynomial import field_theory.minpoly.is_integrally_closed import number_theory.number_field.basic import ring_theory.norm import topology.instances.complex /-! # Embeddings of number fields This file defines the embeddings of a number field into an algebraic closed field. ## Main Results * `number_field.embeddings.range_eval_eq_root_set_minpoly`: let `x ∈ K` with `K` number field and let `A` be an algebraic closed field of char. 0, then the images of `x` by the embeddings of `K` in `A` are exactly the roots in `A` of the minimal polynomial of `x` over `ℚ`. * `number_field.embeddings.pow_eq_one_of_norm_eq_one`: an algebraic integer whose conjugates are all of norm one is a root of unity. ## Tags number field, embeddings, places, infinite places -/ open_locale classical namespace number_field.embeddings section fintype open finite_dimensional variables (K : Type*) [field K] [number_field K] variables (A : Type*) [field A] [char_zero A] /-- There are finitely many embeddings of a number field. -/ noncomputable instance : fintype (K →+* A) := fintype.of_equiv (K →ₐ[ℚ] A) ring_hom.equiv_rat_alg_hom.symm variables [is_alg_closed A] /-- The number of embeddings of a number field is equal to its finrank. -/ lemma card : fintype.card (K →+* A) = finrank ℚ K := by rw [fintype.of_equiv_card ring_hom.equiv_rat_alg_hom.symm, alg_hom.card] instance : nonempty (K →+* A) := begin rw [← fintype.card_pos_iff, number_field.embeddings.card K A], exact finite_dimensional.finrank_pos, end end fintype section roots open set polynomial variables (K A : Type*) [field K] [number_field K] [field A] [algebra ℚ A] [is_alg_closed A] (x : K) /-- Let `A` be an algebraically closed field and let `x ∈ K`, with `K` a number field. The images of `x` by the embeddings of `K` in `A` are exactly the roots in `A` of the minimal polynomial of `x` over `ℚ`. -/ lemma range_eval_eq_root_set_minpoly : range (λ φ : K →+* A, φ x) = (minpoly ℚ x).root_set A := begin convert (number_field.is_algebraic K).range_eval_eq_root_set_minpoly A x using 1, ext a, exact ⟨λ ⟨φ, hφ⟩, ⟨φ.to_rat_alg_hom, hφ⟩, λ ⟨φ, hφ⟩, ⟨φ.to_ring_hom, hφ⟩⟩, end end roots section bounded open finite_dimensional polynomial set variables {K : Type*} [field K] [number_field K] variables {A : Type*} [normed_field A] [is_alg_closed A] [normed_algebra ℚ A] lemma coeff_bdd_of_norm_le {B : ℝ} {x : K} (h : ∀ φ : K →+* A, ‖φ x‖ ≤ B) (i : ℕ) : ‖(minpoly ℚ x).coeff i‖ ≤ (max B 1) ^ (finrank ℚ K) * (finrank ℚ K).choose ((finrank ℚ K) / 2) := begin have hx := is_separable.is_integral ℚ x, rw [← norm_algebra_map' A, ← coeff_map (algebra_map ℚ A)], refine coeff_bdd_of_roots_le _ (minpoly.monic hx) (is_alg_closed.splits_codomain _) (minpoly.nat_degree_le hx) (λ z hz, _) i, classical, rw ← multiset.mem_to_finset at hz, obtain ⟨φ, rfl⟩ := (range_eval_eq_root_set_minpoly K A x).symm.subset hz, exact h φ, end variables (K A) /-- Let `B` be a real number. The set of algebraic integers in `K` whose conjugates are all smaller in norm than `B` is finite. -/ lemma finite_of_norm_le (B : ℝ) : {x : K | is_integral ℤ x ∧ ∀ φ : K →+* A, ‖φ x‖ ≤ B}.finite := begin let C := nat.ceil ((max B 1) ^ (finrank ℚ K) * (finrank ℚ K).choose ((finrank ℚ K) / 2)), have := bUnion_roots_finite (algebra_map ℤ K) (finrank ℚ K) (finite_Icc (-C : ℤ) C), refine this.subset (λ x hx, _), simp_rw mem_Union, have h_map_ℚ_minpoly := minpoly.is_integrally_closed_eq_field_fractions' ℚ hx.1, refine ⟨_, ⟨_, λ i, _⟩, mem_root_set.2 ⟨minpoly.ne_zero hx.1, minpoly.aeval ℤ x⟩⟩, { rw [← (minpoly.monic hx.1).nat_degree_map (algebra_map ℤ ℚ), ← h_map_ℚ_minpoly], exact minpoly.nat_degree_le (is_integral_of_is_scalar_tower hx.1) }, rw [mem_Icc, ← abs_le, ← @int.cast_le ℝ], refine (eq.trans_le _ $ coeff_bdd_of_norm_le hx.2 i).trans (nat.le_ceil _), rw [h_map_ℚ_minpoly, coeff_map, eq_int_cast, int.norm_cast_rat, int.norm_eq_abs, int.cast_abs], end /-- An algebraic integer whose conjugates are all of norm one is a root of unity. -/ lemma pow_eq_one_of_norm_eq_one {x : K} (hxi : is_integral ℤ x) (hx : ∀ φ : K →+* A, ‖φ x‖ = 1) : ∃ (n : ℕ) (hn : 0 < n), x ^ n = 1 := begin obtain ⟨a, -, b, -, habne, h⟩ := @set.infinite.exists_ne_map_eq_of_maps_to _ _ _ _ ((^) x : ℕ → K) set.infinite_univ _ (finite_of_norm_le K A (1:ℝ)), { wlog hlt : b < a, { exact this hxi hx b a habne.symm h.symm (habne.lt_or_lt.resolve_right hlt) }, refine ⟨a - b, tsub_pos_of_lt hlt, _⟩, rw [← nat.sub_add_cancel hlt.le, pow_add, mul_left_eq_self₀] at h, refine h.resolve_right (λ hp, _), specialize hx (is_alg_closed.lift (number_field.is_algebraic K)).to_ring_hom, rw [pow_eq_zero hp, map_zero, norm_zero] at hx, norm_num at hx }, { exact λ a _, ⟨hxi.pow a, λ φ, by simp only [hx φ, norm_pow, one_pow, map_pow]⟩ }, end end bounded end number_field.embeddings section place variables {K : Type*} [field K] {A : Type*} [normed_division_ring A] [nontrivial A] (φ : K →+* A) /-- An embedding into a normed division ring defines a place of `K` -/ def number_field.place : absolute_value K ℝ := (is_absolute_value.to_absolute_value (norm : A → ℝ)).comp φ.injective @[simp] lemma number_field.place_apply (x : K) : (number_field.place φ) x = norm (φ x) := rfl end place namespace number_field.complex_embedding open complex number_field open_locale complex_conjugate variables {K : Type*} [field K] /-- The conjugate of a complex embedding as a complex embedding. -/ @[reducible] def conjugate (φ : K →+* ℂ) : K →+* ℂ := star φ @[simp] lemma conjugate_coe_eq (φ : K →+* ℂ) (x : K) : (conjugate φ) x = conj (φ x) := rfl lemma place_conjugate (φ : K →+* ℂ) : place (conjugate φ) = place φ := by { ext, simp only [place_apply, norm_eq_abs, abs_conj, conjugate_coe_eq] } /-- A embedding into `ℂ` is real if it is fixed by complex conjugation. -/ @[reducible] def is_real (φ : K →+* ℂ) : Prop := is_self_adjoint φ lemma is_real_iff {φ : K →+* ℂ} : is_real φ ↔ conjugate φ = φ := is_self_adjoint_iff /-- A real embedding as a ring homomorphism from `K` to `ℝ` . -/ def is_real.embedding {φ : K →+* ℂ} (hφ : is_real φ) : K →+* ℝ := { to_fun := λ x, (φ x).re, map_one' := by simp only [map_one, one_re], map_mul' := by simp only [complex.conj_eq_iff_im.mp (ring_hom.congr_fun hφ _), map_mul, mul_re, mul_zero, tsub_zero, eq_self_iff_true, forall_const], map_zero' := by simp only [map_zero, zero_re], map_add' := by simp only [map_add, add_re, eq_self_iff_true, forall_const], } @[simp] lemma is_real.coe_embedding_apply {φ : K →+* ℂ} (hφ : is_real φ) (x : K) : (hφ.embedding x : ℂ) = φ x := begin ext, { refl, }, { rw [of_real_im, eq_comm, ← complex.conj_eq_iff_im], rw is_real at hφ, exact ring_hom.congr_fun hφ x, }, end lemma is_real.place_embedding {φ : K →+* ℂ} (hφ : is_real φ) : place hφ.embedding = place φ := by { ext x, simp only [place_apply, real.norm_eq_abs, ←abs_of_real, norm_eq_abs, hφ.coe_embedding_apply x], } lemma is_real_conjugate_iff {φ : K →+* ℂ} : is_real (conjugate φ) ↔ is_real φ := is_self_adjoint.star_iff end number_field.complex_embedding section infinite_place open number_field variables (K : Type*) [field K] /-- An infinite place of a number field `K` is a place associated to a complex embedding. -/ def number_field.infinite_place := { w : absolute_value K ℝ // ∃ φ : K →+* ℂ, place φ = w} instance [number_field K] : nonempty (number_field.infinite_place K) := set.range.nonempty _ variables {K} /-- Return the infinite place defined by a complex embedding `φ`. -/ noncomputable def number_field.infinite_place.mk (φ : K →+* ℂ) : number_field.infinite_place K := ⟨place φ, ⟨φ, rfl⟩⟩ namespace number_field.infinite_place open number_field instance : has_coe_to_fun (infinite_place K) (λ _, K → ℝ) := { coe := λ w, w.1 } instance : monoid_with_zero_hom_class (infinite_place K) K ℝ := { coe := λ w x, w.1 x, coe_injective' := λ _ _ h, subtype.eq (absolute_value.ext (λ x, congr_fun h x)), map_mul := λ w _ _, w.1.map_mul _ _, map_one := λ w, w.1.map_one, map_zero := λ w, w.1.map_zero, } instance : nonneg_hom_class (infinite_place K) K ℝ := { coe := λ w x, w x, coe_injective' := λ _ _ h, subtype.eq (absolute_value.ext (λ x, congr_fun h x)), map_nonneg := λ w x, w.1.nonneg _ } lemma coe_mk (φ : K →+* ℂ) : ⇑(mk φ) = place φ := rfl lemma apply (φ : K →+* ℂ) (x : K) : (mk φ) x = complex.abs (φ x) := rfl /-- For an infinite place `w`, return an embedding `φ` such that `w = infinite_place φ` . -/ noncomputable def embedding (w : infinite_place K) : K →+* ℂ := (w.2).some @[simp] lemma mk_embedding (w : infinite_place K) : mk (embedding w) = w := subtype.ext (w.2).some_spec @[simp] lemma abs_embedding (w : infinite_place K) (x : K) : complex.abs (embedding w x) = w x := congr_fun (congr_arg coe_fn w.2.some_spec) x lemma eq_iff_eq (x : K) (r : ℝ) : (∀ w : infinite_place K, w x = r) ↔ (∀ φ : K →+* ℂ, ‖φ x‖ = r) := ⟨λ hw φ, hw (mk φ), λ hφ ⟨w, ⟨φ, rfl⟩⟩, hφ φ⟩ lemma le_iff_le (x : K) (r : ℝ) : (∀ w : infinite_place K, w x ≤ r) ↔ (∀ φ : K →+* ℂ, ‖φ x‖ ≤ r) := ⟨λ hw φ, hw (mk φ), λ hφ ⟨w, ⟨φ, rfl⟩⟩, hφ φ⟩ lemma pos_iff {w : infinite_place K} {x : K} : 0 < w x ↔ x ≠ 0 := absolute_value.pos_iff w.1 @[simp] lemma mk_conjugate_eq (φ : K →+* ℂ) : mk (complex_embedding.conjugate φ) = mk φ := begin ext x, exact congr_fun (congr_arg coe_fn (complex_embedding.place_conjugate φ)) x, end @[simp] lemma mk_eq_iff {φ ψ : K →+* ℂ} : mk φ = mk ψ ↔ φ = ψ ∨ complex_embedding.conjugate φ = ψ := begin split, { -- We prove that the map ψ ∘ φ⁻¹ between φ(K) and ℂ is uniform continuous, thus it is either the -- inclusion or the complex conjugation using complex.uniform_continuous_ring_hom_eq_id_or_conj intro h₀, obtain ⟨j, hiφ⟩ := φ.injective.has_left_inverse, let ι := ring_equiv.of_left_inverse hiφ, have hlip : lipschitz_with 1 (ring_hom.comp ψ ι.symm.to_ring_hom), { change lipschitz_with 1 (ψ ∘ ι.symm), apply lipschitz_with.of_dist_le_mul, intros x y, rw [nonneg.coe_one, one_mul, normed_field.dist_eq, ← map_sub, ← map_sub], apply le_of_eq, suffices : ‖φ ((ι.symm) (x - y))‖ = ‖ψ ((ι.symm) (x - y))‖, { rw [← this, ← ring_equiv.of_left_inverse_apply hiφ _ , ring_equiv.apply_symm_apply ι _], refl, }, exact congr_fun (congr_arg coe_fn h₀) _, }, cases (complex.uniform_continuous_ring_hom_eq_id_or_conj φ.field_range hlip.uniform_continuous), { left, ext1 x, convert (congr_fun h (ι x)).symm, exact (ring_equiv.apply_symm_apply ι.symm x).symm, }, { right, ext1 x, convert (congr_fun h (ι x)).symm, exact (ring_equiv.apply_symm_apply ι.symm x).symm, }}, { rintros (⟨h⟩ | ⟨h⟩), { exact congr_arg mk h, }, { rw ← mk_conjugate_eq, exact congr_arg mk h, }}, end /-- An infinite place is real if it is defined by a real embedding. -/ def is_real (w : infinite_place K) : Prop := ∃ φ : K →+* ℂ, complex_embedding.is_real φ ∧ mk φ = w /-- An infinite place is complex if it is defined by a complex (ie. not real) embedding. -/ def is_complex (w : infinite_place K) : Prop := ∃ φ : K →+* ℂ, ¬ complex_embedding.is_real φ ∧ mk φ = w @[simp] lemma _root_.number_field.complex_embeddings.is_real.embedding_mk {φ : K →+* ℂ} (h : complex_embedding.is_real φ) : embedding (mk φ) = φ := begin have := mk_eq_iff.mp (mk_embedding (mk φ)).symm, rwa [complex_embedding.is_real_iff.mp h, or_self, eq_comm] at this, end lemma is_real_iff {w : infinite_place K} : is_real w ↔ complex_embedding.is_real (embedding w) := begin split, { rintros ⟨φ, ⟨hφ, rfl⟩⟩, rwa _root_.number_field.complex_embeddings.is_real.embedding_mk hφ, }, { exact λ h, ⟨embedding w, h, mk_embedding w⟩, }, end lemma is_complex_iff {w : infinite_place K} : is_complex w ↔ ¬ complex_embedding.is_real (embedding w) := begin split, { rintros ⟨φ, ⟨hφ, rfl⟩⟩, contrapose! hφ, cases mk_eq_iff.mp (mk_embedding (mk φ)), { rwa ← h, }, { rw ← complex_embedding.is_real_conjugate_iff at hφ, rwa ← h, }}, { exact λ h, ⟨embedding w, h, mk_embedding w⟩, }, end @[simp] lemma not_is_real_iff_is_complex {w : infinite_place K} : ¬ is_real w ↔ is_complex w := by rw [is_complex_iff, is_real_iff] @[simp] lemma not_is_complex_iff_is_real {w : infinite_place K} : ¬ is_complex w ↔ is_real w := by rw [←not_is_real_iff_is_complex, not_not] lemma is_real_or_is_complex (w : infinite_place K) : is_real w ∨ is_complex w := by { rw ←not_is_real_iff_is_complex, exact em _ } /-- For `w` a real infinite place, return the corresponding embedding as a morphism `K →+* ℝ`. -/ noncomputable def is_real.embedding {w : infinite_place K} (hw : is_real w) : K →+* ℝ := (is_real_iff.mp hw).embedding @[simp] lemma is_real.place_embedding_apply {w : infinite_place K} (hw : is_real w) (x : K): place (is_real.embedding hw) x = w x := begin rw [is_real.embedding, complex_embedding.is_real.place_embedding, ← coe_mk], exact congr_fun (congr_arg coe_fn (mk_embedding w)) x, end @[simp] lemma is_real.abs_embedding_apply {w : infinite_place K} (hw : is_real w) (x : K) : |is_real.embedding hw x| = w x := by { rw ← is_real.place_embedding_apply hw x, congr, } variable (K) /-- The map from real embeddings to real infinite places as an equiv -/ noncomputable def mk_real : {φ : K →+* ℂ // complex_embedding.is_real φ} ≃ {w : infinite_place K // is_real w} := { to_fun := subtype.map mk (λ φ hφ, ⟨φ, hφ, rfl⟩), inv_fun := λ w, ⟨w.1.embedding, is_real_iff.1 w.2⟩, left_inv := λ φ, subtype.ext_iff.2 (number_field.complex_embeddings.is_real.embedding_mk φ.2), right_inv := λ w, subtype.ext_iff.2 (mk_embedding w.1), } /-- The map from nonreal embeddings to complex infinite places -/ noncomputable def mk_complex : {φ : K →+* ℂ // ¬ complex_embedding.is_real φ} → {w : infinite_place K // is_complex w} := subtype.map mk (λ φ hφ, ⟨φ, hφ, rfl⟩) lemma mk_complex_embedding (φ : {φ : K →+* ℂ // ¬ complex_embedding.is_real φ}) : ((mk_complex K φ) : infinite_place K).embedding = φ ∨ ((mk_complex K φ) : infinite_place K).embedding = complex_embedding.conjugate φ := begin rw [@eq_comm _ _ ↑φ, @eq_comm _ _ (complex_embedding.conjugate ↑φ), ← mk_eq_iff, mk_embedding], refl, end @[simp] lemma mk_real_coe (φ : {φ : K →+* ℂ // complex_embedding.is_real φ}) : (mk_real K φ : infinite_place K) = mk (φ : K →+* ℂ) := rfl @[simp] lemma mk_complex_coe (φ : {φ : K →+* ℂ // ¬ complex_embedding.is_real φ}) : (mk_complex K φ : infinite_place K) = mk (φ : K →+* ℂ) := rfl @[simp] lemma mk_real.apply (φ : {φ : K →+* ℂ // complex_embedding.is_real φ}) (x : K) : mk_real K φ x = complex.abs (φ x) := apply φ x @[simp] lemma mk_complex.apply (φ : {φ : K →+* ℂ // ¬ complex_embedding.is_real φ}) (x : K) : mk_complex K φ x = complex.abs (φ x) := apply φ x variable [number_field K] lemma mk_complex.filter (w : { w : infinite_place K // w.is_complex }) : finset.univ.filter (λ φ, mk_complex K φ = w) = { ⟨w.1.embedding, is_complex_iff.1 w.2⟩, ⟨complex_embedding.conjugate w.1.embedding, complex_embedding.is_real_conjugate_iff.not.2 (is_complex_iff.1 w.2)⟩ } := begin ext φ, simp_rw [finset.mem_filter, subtype.val_eq_coe, finset.mem_insert, finset.mem_singleton, @subtype.ext_iff_val (infinite_place K), @subtype.ext_iff_val (K →+* ℂ), @eq_comm _ φ.val, ← mk_eq_iff, mk_embedding, @eq_comm _ _ w.val], simpa only [finset.mem_univ, true_and], end lemma mk_complex.filter_card (w : { w : infinite_place K // w.is_complex }) : (finset.univ.filter (λ φ, mk_complex K φ = w)).card = 2 := begin rw mk_complex.filter, exact finset.card_doubleton (subtype.mk_eq_mk.not.2 $ ne_comm.1 $ complex_embedding.is_real_iff.not.1 $ is_complex_iff.1 w.2), end noncomputable instance number_field.infinite_place.fintype : fintype (infinite_place K) := set.fintype_range _ /-- The infinite part of the product formula : for `x ∈ K`, we have `Π_w ‖x‖_w = |norm(x)|` where `‖·‖_w` is the normalized absolute value for `w`. -/ lemma prod_eq_abs_norm (x : K) : finset.univ.prod (λ w : infinite_place K, ite (w.is_real) (w x) ((w x) ^ 2)) = abs (algebra.norm ℚ x) := begin convert (congr_arg complex.abs (@algebra.norm_eq_prod_embeddings ℚ _ _ _ _ ℂ _ _ _ _ _ x)).symm, { rw [map_prod, ← equiv.prod_comp' ring_hom.equiv_rat_alg_hom (λ f, complex.abs (f x)) (λ φ, complex.abs (φ x)) (λ _, by simpa only [ring_hom.equiv_rat_alg_hom_apply])], dsimp only, conv { to_rhs, congr, skip, funext, rw ( by simp only [if_t_t] : complex.abs (f x) = ite (complex_embedding.is_real f) (complex.abs (f x)) (complex.abs (f x))) }, rw [finset.prod_ite, finset.prod_ite], refine congr (congr_arg has_mul.mul _) _, { rw [← finset.prod_subtype_eq_prod_filter, ← finset.prod_subtype_eq_prod_filter], convert (equiv.prod_comp' (mk_real K) (λ φ, complex.abs (φ x)) (λ w, w x) _).symm, any_goals { ext, simp only [finset.mem_subtype, finset.mem_univ], }, exact λ φ, mk_real.apply K φ x, }, { rw [finset.filter_congr (λ (w : infinite_place K) _, @not_is_real_iff_is_complex K _ w), ← finset.prod_subtype_eq_prod_filter, ← finset.prod_subtype_eq_prod_filter], convert finset.prod_fiberwise finset.univ (λ φ, mk_complex K φ) (λ φ, complex.abs (φ x)), any_goals { ext, simp only [finset.mem_subtype, finset.mem_univ, not_is_real_iff_is_complex], }, { ext w, rw [@finset.prod_congr _ _ _ _ _ (λ φ, w x) _ (eq.refl _) (λ φ hφ, (mk_complex.apply K φ x).symm.trans (congr_fun (congr_arg coe_fn (finset.mem_filter.1 hφ).2) x)), finset.prod_const, mk_complex.filter_card K w], refl, }}}, { rw [eq_rat_cast, ← complex.abs_of_real, complex.of_real_rat_cast], }, end open fintype lemma card_real_embeddings : card {φ : K →+* ℂ // complex_embedding.is_real φ} = card {w : infinite_place K // is_real w} := by convert (fintype.of_equiv_card (mk_real K)).symm lemma card_complex_embeddings : card {φ : K →+* ℂ // ¬ complex_embedding.is_real φ} = 2 * card {w : infinite_place K // is_complex w} := begin rw [fintype.card, fintype.card, mul_comm, ← algebra.id.smul_eq_mul, ← finset.sum_const], conv { to_rhs, congr, skip, funext, rw ← mk_complex.filter_card K x }, simp_rw finset.card_eq_sum_ones, exact (finset.sum_fiberwise finset.univ (λ φ, mk_complex K φ) (λ φ, 1)).symm end end number_field.infinite_place end infinite_place
21e3906e9a941afadfc69829dc5020aceba039a1
137c667471a40116a7afd7261f030b30180468c2
/src/algebra/group/to_additive.lean
2fb74d2e8186d21fa348b96c40d88fb48f261aa2
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,387
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury Kudryashov, Floris van Doorn -/ import tactic.transform_decl import tactic.algebra /-! # Transport multiplicative to additive This file defines an attribute `to_additive` that can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. Usage information is contained in the doc string of `to_additive.attr`. ### Missing features * Automatically transport structures and other inductive types. * For structures, automatically generate theorems like `group α ↔ add_group (additive α)`. -/ namespace to_additive open tactic setup_tactic_parser section performance_hack -- see Note [user attribute parameters] local attribute [semireducible] reflected /-- Temporarily change the `has_reflect` instance for `name`. -/ local attribute [instance, priority 9000] meta def hacky_name_reflect : has_reflect name := λ n, `(id %%(expr.const n []) : name) /-- An auxiliary attribute used to store the names of the additive versions of declarations that have been processed by `to_additive`. -/ @[user_attribute] meta def aux_attr : user_attribute (name_map name) name := { name := `to_additive_aux, descr := "Auxiliary attribute for `to_additive`. DON'T USE IT", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n', do let n := match n' with | name.mk_string s pre := if s = "_to_additive" then pre else n' | _ := n' end, param ← aux_attr.get_param_untyped n', pure $ dict.insert n param.app_arg.const_name) mk_name_map, []⟩, parser := lean.parser.ident } end performance_hack section extra_attributes /-- An attribute that tells `@[to_additive]` that certain arguments of this definition are not involved when using `@[to_additive]`. This helps the heuristic of `@[to_additive]` by also transforming definitions if `ℕ` or another fixed type occurs as one of these arguments. -/ @[user_attribute] meta def ignore_args_attr : user_attribute (name_map $ list ℕ) (list ℕ) := { name := `to_additive_ignore_args, descr := "Auxiliary attribute for `to_additive` stating that certain arguments are not additivized.", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do param ← ignore_args_attr.get_param_untyped n, -- see Note [user attribute parameters] return $ dict.insert n (param.to_list expr.to_nat).iget) mk_name_map, []⟩, parser := (lean.parser.small_nat)* } /-- An attribute that stores all the declarations that needs their arguments reordered when applying `@[to_additive]`. Currently, we only support swapping consecutive arguments. The list of the natural numbers contains the positions of the first of the two arguments to be swapped. Example: `@[to_additive_reorder 1 4]` swaps the first two arguments and the arguments in positions 4 and 5. -/ @[user_attribute] meta def reorder_attr : user_attribute (name_map $ list ℕ) (list ℕ) := { name := `to_additive_reorder, descr := "Auxiliary attribute for `to_additive` that stores arguments that need to be reordered.", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do param ← reorder_attr.get_param_untyped n, -- see Note [user attribute parameters] return $ dict.insert n (param.to_list expr.to_nat).iget) mk_name_map, []⟩, parser := do l ← (lean.parser.small_nat)*, guard (l.all (≠ 0)) <|> exceptional.fail "The reorder positions must be positive", return l } end extra_attributes /-- A command that can be used to have future uses of `to_additive` change the `src` namespace to the `tgt` namespace. For example: ``` run_cmd to_additive.map_namespace `quotient_group `quotient_add_group ``` Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created in the `quotient_add_group` namespaces. -/ meta def map_namespace (src tgt : name) : command := do let n := src.mk_string "_to_additive", let decl := declaration.thm n [] `(unit) (pure (reflect ())), add_decl decl, aux_attr.set n tgt tt /-- `value_type` is the type of the arguments that can be provided to `to_additive`. `to_additive.parser` parses the provided arguments: * `replace_all`: replace all multiplicative declarations, do not use the heuristic. * `trace`: output the generated additive declaration. * `tgt : name`: the name of the target (the additive declaration). * `doc`: an optional doc string. -/ @[derive has_reflect, derive inhabited] structure value_type : Type := (replace_all : bool) (trace : bool) (tgt : name) (doc : option string) /-- `add_comm_prefix x s` returns `"comm_" ++ s` if `x = tt` and `s` otherwise. -/ meta def add_comm_prefix : bool → string → string | tt s := ("comm_" ++ s) | ff s := s /-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/ meta def tr : bool → list string → list string | is_comm ("one" :: "le" :: s) := add_comm_prefix is_comm "nonneg" :: tr ff s | is_comm ("one" :: "lt" :: s) := add_comm_prefix is_comm "pos" :: tr ff s | is_comm ("le" :: "one" :: s) := add_comm_prefix is_comm "nonpos" :: tr ff s | is_comm ("lt" :: "one" :: s) := add_comm_prefix is_comm "neg" :: tr ff s | is_comm ("mul" :: "support" :: s) := add_comm_prefix is_comm "support" :: tr ff s | is_comm ("mul" :: "indicator" :: s) := add_comm_prefix is_comm "indicator" :: tr ff s | is_comm ("mul" :: s) := add_comm_prefix is_comm "add" :: tr ff s | is_comm ("smul" :: s) := add_comm_prefix is_comm "vadd" :: tr ff s | is_comm ("inv" :: s) := add_comm_prefix is_comm "neg" :: tr ff s | is_comm ("div" :: s) := add_comm_prefix is_comm "sub" :: tr ff s | is_comm ("one" :: s) := add_comm_prefix is_comm "zero" :: tr ff s | is_comm ("prod" :: s) := add_comm_prefix is_comm "sum" :: tr ff s | is_comm ("finprod" :: s) := add_comm_prefix is_comm "finsum" :: tr ff s | is_comm ("npow" :: s) := add_comm_prefix is_comm "nsmul" :: tr ff s | is_comm ("gpow" :: s) := add_comm_prefix is_comm "gsmul" :: tr ff s | is_comm ("monoid" :: s) := ("add_" ++ add_comm_prefix is_comm "monoid") :: tr ff s | is_comm ("submonoid" :: s) := ("add_" ++ add_comm_prefix is_comm "submonoid") :: tr ff s | is_comm ("group" :: s) := ("add_" ++ add_comm_prefix is_comm "group") :: tr ff s | is_comm ("subgroup" :: s) := ("add_" ++ add_comm_prefix is_comm "subgroup") :: tr ff s | is_comm ("semigroup" :: s) := ("add_" ++ add_comm_prefix is_comm "semigroup") :: tr ff s | is_comm ("magma" :: s) := ("add_" ++ add_comm_prefix is_comm "magma") :: tr ff s | is_comm ("comm" :: s) := tr tt s | is_comm (x :: s) := (add_comm_prefix is_comm x :: tr ff s) | tt [] := ["comm"] | ff [] := [] /-- Autogenerate target name for `to_additive`. -/ meta def guess_name : string → string := string.map_tokens ''' $ λ s, string.intercalate (string.singleton '_') $ tr ff (s.split_on '_') /-- Return the provided target name or autogenerate one if one was not provided. -/ meta def target_name (src tgt : name) (dict : name_map name) : tactic name := (if tgt.get_prefix ≠ name.anonymous -- `tgt` is a full name then pure tgt else match src with | (name.mk_string s pre) := do let tgt_auto := guess_name s, guard (tgt.to_string ≠ tgt_auto ∨ tgt = src) <|> trace ("`to_additive " ++ src.to_string ++ "`: correctly autogenerated target " ++ "name, you may remove the explicit " ++ tgt_auto ++ " argument."), pure $ name.mk_string (if tgt = name.anonymous then tgt_auto else tgt.to_string) (pre.map_prefix dict.find) | _ := fail ("to_additive: can't transport " ++ src.to_string) end) >>= (λ res, if res = src ∧ tgt ≠ src then fail ("to_additive: can't transport " ++ src.to_string ++ " to itself. Give the desired additive name explicitly using `@[to_additive additive_name]`. ") else pure res) /-- the parser for the arguments to `to_additive`. -/ meta def parser : lean.parser value_type := do bang ← option.is_some <$> (tk "!")?, ques ← option.is_some <$> (tk "?")?, tgt ← ident?, e ← texpr?, doc ← match e with | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string) | none := pure none end, return ⟨bang, ques, tgt.get_or_else name.anonymous, doc⟩ private meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) : command := do src_fields ← f src, tgt_fields ← f tgt, guard (src_fields.length = tgt_fields.length) <|> fail ("Failed to map fields of " ++ src.to_string), (src_fields.zip tgt_fields).mmap' $ λ names, guard (names.fst = names.snd) <|> aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio /-- Add the `aux_attr` attribute to the structure fields of `src` so that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/ meta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command := let aux := proceed_fields_aux src tgt prio in do aux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >> aux (λ n, (list.map (λ (x : name), "to_" ++ x.to_string) <$> get_tagged_ancestors n)) >> aux (λ n, (env.constructors_of n).mmap $ λ cs, match cs with | (name.mk_string s pre) := (guard (pre = n) <|> fail "Bad constructor name") >> pure s | _ := fail "Bad constructor name" end) /-- The attribute `to_additive` can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. To use this attribute, just write: ``` @[to_additive] theorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm ``` This code will generate a theorem named `add_comm'`. It is also possible to manually specify the name of the new declaration, and provide a documentation string: ``` @[to_additive add_foo "add_foo doc string"] /-- foo doc string -/ theorem foo := sorry ``` The transport tries to do the right thing in most cases using several heuristics described below. However, in some cases it fails, and requires manual intervention. If the declaration to be transported has attributes which need to be copied to the additive version, then `to_additive` should come last: ``` @[simp, to_additive] lemma mul_one' {G : Type*} [group G] (x : G) : x * 1 = x := mul_one x ``` The exception to this rule is the `simps` attribute, which should come after `to_additive`: ``` @[to_additive, simps] instance {M N} [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ ``` ## Implementation notes The transport process generally works by taking all the names of identifiers appearing in the name, type, and body of a declaration and creating a new declaration by mapping those names to additive versions using a simple string-based dictionary and also using all declarations that have previously been labeled with `to_additive`. In the `mul_comm'` example above, `to_additive` maps: * `mul_comm'` to `add_comm'`, * `comm_semigroup` to `add_comm_semigroup`, * `x * y` to `x + y` and `y * x` to `y + x`, and * `comm_semigroup.mul_comm'` to `add_comm_semigroup.add_comm'`. ### Heuristics `to_additive` uses heuristics to determine whether a particular identifier has to be mapped to its additive version. The basic heuristic is * Only map an identifier to its additive version if its first argument doesn't contain any unapplied identifiers. Examples: * `@has_mul.mul ℕ n m` (i.e. `(n * m : ℕ)`) will not change to `+`, since its first argument is `ℕ`, an identifier not applied to any arguments. * `@has_mul.mul (α × β) x y` will change to `+`. It's first argument contains only the identifier `prod`, but this is applied to arguments, `α` and `β`. * `@has_mul.mul (α × ℤ) x y` will not change to `+`, since its first argument contains `ℤ`. The reasoning behind the heuristic is that the first argument is the type which is "additivized", and this usually doesn't make sense if this is on a fixed type. There are two exceptions in this heuristic: * Identifiers that have the `@[to_additive]` attribute are ignored. For example, multiplication in `↥Semigroup` is replaced by addition in `↥AddSemigroup`. * If an identifier has attribute `@[to_additive_ignore_args n1 n2 ...]` then all the arguments in positions `n1`, `n2`, ... will not be checked for unapplied identifiers (start counting from 1). For example, `times_cont_mdiff_map` has attribute `@[to_additive_ignore_args 21]`, which means that its 21st argument `(n : with_top ℕ)` can contain `ℕ` (usually in the form `has_top.top ℕ ...`) and still be additivized. So `@has_mul.mul (C^∞⟮I, N; I', G⟯) _ f g` will be additivized. If you want to disable this heuristic and replace all multiplicative identifiers with their additive counterpart, use `@[to_additive!]`. If `to_additive` is unable to automatically generate the additive version of a declaration, it can be useful to apply the attribute manually: ``` attribute [to_additive foo_add_bar] foo_bar ``` This will allow future uses of `to_additive` to recognize that `foo_bar` should be replaced with `foo_add_bar`. ### Handling of hidden definitions Before transporting the “main” declaration `src`, `to_additive` first scans its type and value for names starting with `src`, and transports them. This includes auxiliary definitions like `src._match_1`, `src._proof_1`. After transporting the “main” declaration, `to_additive` transports its equational lemmas. ### Structure fields and constructors If `src` is a structure, then `to_additive` automatically adds structure fields to its mapping, and similarly for constructors of inductive types. For new structures this means that `to_additive` automatically handles coercions, and for old structures it does the same, if ancestry information is present in `@[ancestor]` attributes. The `ancestor` attribute must come before the `to_additive` attribute, and it is essential that the order of the base structures passed to `ancestor` matches between the multiplicative and additive versions of the structure. ### Name generation * If `@[to_additive]` is called without a `name` argument, then the new name is autogenerated. First, it takes the longest prefix of the source name that is already known to `to_additive`, and replaces this prefix with its additive counterpart. Second, it takes the last part of the name (i.e., after the last dot), and replaces common name parts (“mul”, “one”, “inv”, “prod”) with their additive versions. * Namespaces can be transformed using `map_namespace`. For example: ``` run_cmd to_additive.map_namespace `quotient_group `quotient_add_group ``` Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created in the `quotient_add_group` namespaces. * If `@[to_additive]` is called with a `name` argument `new_name` /without a dot/, then `to_additive` updates the prefix as described above, then replaces the last part of the name with `new_name`. * If `@[to_additive]` is called with a `name` argument `new_namespace.new_name` /with a dot/, then `to_additive` uses this new name as is. As a safety check, in the first case `to_additive` double checks that the new name differs from the original one. -/ @[user_attribute] protected meta def attr : user_attribute unit value_type := { name := `to_additive, descr := "Transport multiplicative to additive", parser := parser, after_set := some $ λ src prio persistent, do guard persistent <|> fail "`to_additive` can't be used as a local attribute", env ← get_env, val ← attr.get_param src, dict ← aux_attr.get_cache, ignore ← ignore_args_attr.get_cache, reorder ← reorder_attr.get_cache, tgt ← target_name src val.tgt dict, aux_attr.set src tgt tt, let dict := dict.insert src tgt, if env.contains tgt then proceed_fields env src tgt prio else do transform_decl_with_prefix_dict dict val.replace_all val.trace ignore reorder src tgt [`reducible, `_refl_lemma, `simp, `instance, `refl, `symm, `trans, `elab_as_eliminator, `no_rsimp, `measurability], mwhen (has_attribute' `simps src) (trace "Apply the simps attribute after the to_additive attribute"), match val.doc with | some doc := add_doc_string tgt doc | none := skip end } add_tactic_doc { name := "to_additive", category := doc_category.attr, decl_names := [`to_additive.attr], tags := ["transport", "environment", "lemma derivation"] } end to_additive /- map operations -/ attribute [to_additive] has_mul has_one has_inv has_div /- the following types are supported by `@[to_additive]` and mapped to themselves. -/ attribute [to_additive empty] empty attribute [to_additive pempty] pempty attribute [to_additive punit] punit attribute [to_additive unit] unit /- We ignore the third argument of `has_coe_to_fun.F` when deciding whether the operation needs to be additivized. The reason is that this argument is the element to be coerced, which usually does not actually show up in the type after reduction. Hypothetically, this could be ignoring too much, in that case, we can remove this, but in that case we have to add the `to_additive_ignore_args` attribute more systematically to a lot of other definitions (like `times_cont_mdiff_map.comp`). -/ attribute [to_additive_ignore_args 3] has_coe_to_fun.F
57d6609e03a288b0ab81d96215bb2a96ad6adffd
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/structInst4.lean
a0eefded0c64eb0df35d65519691d0c6f2b77616
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
499
lean
universes u def a : Array ((Nat × Nat) × Bool) := #[] def b : Array Nat := #[] structure Foo := (x : Array ((Nat × Nat) × Bool) := #[]) (y : Nat := 0) new_frontend #check (b).modifyOp (idx := 1) (fun s => 2) #check { b with [1] := 2 } #check { a with [1].fst.2 := 1 } def foo : Foo := {} #check foo.x[1].1.2 #check { foo with x[1].2 := true } #check { foo with x[1].fst.snd := 1 } #check { foo with x[1].1.fst := 1 } #check { foo with x[1].1.1 := 5 } #check { foo with x[1].1.2 := 5 }
908050335744ed755a1e55742e778463d6bda15d
bb31430994044506fa42fd667e2d556327e18dfe
/src/linear_algebra/linear_independent.lean
ce81c6baf68e42e0777ab7c1b89e21699dfabf46
[ "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
57,503
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp, Anne Baanen -/ import algebra.big_operators.fin import linear_algebra.finsupp import linear_algebra.prod import set_theory.cardinal.basic /-! # Linear independence This file defines linear independence in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. We define `linear_independent R v` as `ker (finsupp.total ι M R v) = ⊥`. Here `finsupp.total` is the linear map sending a function `f : ι →₀ R` with finite support to the linear combination of vectors from `v` with these coefficients. Then we prove that several other statements are equivalent to this one, including injectivity of `finsupp.total ι M R v` and some versions with explicitly written linear combinations. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. ## Main statements We prove several specialized tests for linear independence of families of vectors and of sets of vectors. * `fintype.linear_independent_iff`: if `ι` is a finite type, then any function `f : ι → R` has finite support, so we can reformulate the statement using `∑ i : ι, f i • v i` instead of a sum over an auxiliary `s : finset ι`; * `linear_independent_empty_type`: a family indexed by an empty type is linearly independent; * `linear_independent_unique_iff`: if `ι` is a singleton, then `linear_independent K v` is equivalent to `v default ≠ 0`; * linear_independent_option`, `linear_independent_sum`, `linear_independent_fin_cons`, `linear_independent_fin_succ`: type-specific tests for linear independence of families of vector fields; * `linear_independent_insert`, `linear_independent_union`, `linear_independent_pair`, `linear_independent_singleton`: linear independence tests for set operations. In many cases we additionally provide dot-style operations (e.g., `linear_independent.union`) to make the linear independence tests usable as `hv.insert ha` etc. We also prove that, when working over a division ring, any family of vectors includes a linear independent subfamily spanning the same subspace. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence -/ noncomputable theory open function set submodule open_locale classical big_operators cardinal universes u variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*} section module variables {v : ι → M} variables [semiring R] [add_comm_monoid M] [add_comm_monoid M'] [add_comm_monoid M''] variables [module R M] [module R M'] [module R M''] variables {a b : R} {x y : M} variables (R) (v) /-- `linear_independent R v` states the family of vectors `v` is linearly independent over `R`. -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, ∑ i in s, g i • v i = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (∑ i in s, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = ∑ j in s, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j)) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = (∑ j in s, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ theorem linear_independent_iff'' : linear_independent R v ↔ ∀ (s : finset ι) (g : ι → R) (hg : ∀ i ∉ s, g i = 0), ∑ i in s, g i • v i = 0 → ∀ i, g i = 0 := linear_independent_iff'.trans ⟨λ H s g hg hv i, if his : i ∈ s then H s g hv i his else hg i his, λ H s g hg i hi, by { convert H s (λ j, if j ∈ s then g j else 0) (λ j hj, if_neg hj) (by simp_rw [ite_smul, zero_smul, finset.sum_extend_by_zero, hg]) i, exact (if_pos hi).symm }⟩ theorem not_linear_independent_iff : ¬ linear_independent R v ↔ ∃ s : finset ι, ∃ g : ι → R, (∑ i in s, g i • v i) = 0 ∧ (∃ i ∈ s, g i ≠ 0) := begin rw linear_independent_iff', simp only [exists_prop, not_forall], end theorem fintype.linear_independent_iff [fintype ι] : linear_independent R v ↔ ∀ g : ι → R, ∑ i, g i • v i = 0 → ∀ i, g i = 0 := begin refine ⟨λ H g, by simpa using linear_independent_iff'.1 H finset.univ g, λ H, linear_independent_iff''.2 $ λ s g hg hs i, H _ _ _⟩, rw ← hs, refine (finset.sum_subset (finset.subset_univ _) (λ i _ hi, _)).symm, rw [hg i hi, zero_smul] end /-- A finite family of vectors `v i` is linear independent iff the linear map that sends `c : ι → R` to `∑ i, c i • v i` has the trivial kernel. -/ theorem fintype.linear_independent_iff' [fintype ι] : linear_independent R v ↔ (linear_map.lsum R (λ i : ι, R) ℕ (λ i, linear_map.id.smul_right (v i))).ker = ⊥ := by simp [fintype.linear_independent_iff, linear_map.ker_eq_bot', funext_iff]; skip lemma fintype.not_linear_independent_iff [fintype ι] : ¬linear_independent R v ↔ ∃ g : ι → R, (∑ i, g i • v i) = 0 ∧ (∃ i, g i ≠ 0) := by simpa using (not_iff_not.2 fintype.linear_independent_iff) lemma linear_independent_empty_type [is_empty ι] : linear_independent R v := linear_independent_iff.mpr $ λ v hv, subsingleton.elim v 0 lemma linear_independent.ne_zero [nontrivial R] (i : ι) (hv : linear_independent R v) : v i ≠ 0 := λ h, zero_ne_one' R $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), { simp }, { simp [h] } end /-- A subfamily of a linearly independent family (i.e., a composition with an injective map) is a linearly independent family. -/ lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext x, convert h_map_domain x, rw [finsupp.map_domain_apply hf] end lemma linear_independent.coe_range (i : linear_independent R v) : linear_independent R (coe : range v → M) := by simpa using i.comp _ (range_splitting_injective v) /-- If `v` is a linearly independent family of vectors and the kernel of a linear map `f` is disjoint with the submodule spanned by the vectors of `v`, then `f ∘ v` is a linearly independent family of vectors. See also `linear_independent.map'` for a special case assuming `ker f = ⊥`. -/ lemma linear_independent.map (hv : linear_independent R v) {f : M →ₗ[R] M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint_iff_inf_le, ← set.image_univ, finsupp.span_image_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv ⊢, rw [hv, le_bot_iff] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [finsupp.total_comp, @finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, linear_map.ker_comp, hf_inj], exact λ _, rfl, end /-- An injective linear map sends linearly independent families of vectors to linearly independent families of vectors. See also `linear_independent.map` for a more general statement. -/ lemma linear_independent.map' (hv : linear_independent R v) (f : M →ₗ[R] M') (hf_inj : f.ker = ⊥) : linear_independent R (f ∘ v) := hv.map $ by simp [hf_inj] /-- If the image of a family of vectors under a linear map is linearly independent, then so is the original family. -/ lemma linear_independent.of_comp (f : M →ₗ[R] M') (hfv : linear_independent R (f ∘ v)) : linear_independent R v := linear_independent_iff'.2 $ λ s g hg i his, have ∑ (i : ι) in s, g i • f (v i) = 0, by simp_rw [← f.map_smul, ← f.map_sum, hg, f.map_zero], linear_independent_iff'.1 hfv s g this i his /-- If `f` is an injective linear map, then the family `f ∘ v` is linearly independent if and only if the family `v` is linearly independent. -/ protected lemma linear_map.linear_independent_iff (f : M →ₗ[R] M') (hf_inj : f.ker = ⊥) : linear_independent R (f ∘ v) ↔ linear_independent R v := ⟨λ h, h.of_comp f, λ h, h.map $ by simp only [hf_inj, disjoint_bot_right]⟩ @[nontriviality] lemma linear_independent_of_subsingleton [subsingleton R] : linear_independent R v := linear_independent_iff.2 (λ l hl, subsingleton.elim _ _) theorem linear_independent_equiv (e : ι ≃ ι') {f : ι' → M} : linear_independent R (f ∘ e) ↔ linear_independent R f := ⟨λ h, function.comp.right_id f ▸ e.self_comp_symm ▸ h.comp _ e.symm.injective, λ h, h.comp _ e.injective⟩ theorem linear_independent_equiv' (e : ι ≃ ι') {f : ι' → M} {g : ι → M} (h : f ∘ e = g) : linear_independent R g ↔ linear_independent R f := h ▸ linear_independent_equiv e theorem linear_independent_subtype_range {ι} {f : ι → M} (hf : injective f) : linear_independent R (coe : range f → M) ↔ linear_independent R f := iff.symm $ linear_independent_equiv' (equiv.of_injective f hf) rfl alias linear_independent_subtype_range ↔ linear_independent.of_subtype_range _ theorem linear_independent_image {ι} {s : set ι} {f : ι → M} (hf : set.inj_on f s) : linear_independent R (λ x : s, f x) ↔ linear_independent R (λ x : f '' s, (x : M)) := linear_independent_equiv' (equiv.set.image_of_inj_on _ _ hf) rfl lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := linear_independent.of_comp (span R (range v)).subtype hs /-- See `linear_independent.fin_cons` for a family of elements in a vector space. -/ lemma linear_independent.fin_cons' {m : ℕ} (x : M) (v : fin m → M) (hli : linear_independent R v) (x_ortho : (∀ (c : R) (y : submodule.span R (set.range v)), c • x + y = (0 : M) → c = 0)) : linear_independent R (fin.cons x v : fin m.succ → M) := begin rw fintype.linear_independent_iff at hli ⊢, rintros g total_eq j, simp_rw [fin.sum_univ_succ, fin.cons_zero, fin.cons_succ] at total_eq, have : g 0 = 0, { refine x_ortho (g 0) ⟨∑ (i : fin m), g i.succ • v i, _⟩ total_eq, exact sum_mem (λ i _, smul_mem _ _ (subset_span ⟨i, rfl⟩)) }, rw [this, zero_smul, zero_add] at total_eq, exact fin.cases this (hli _ total_eq) j, end /-- A set of linearly independent vectors in a module `M` over a semiring `K` is also linearly independent over a subring `R` of `K`. The implementation uses minimal assumptions about the relationship between `R`, `K` and `M`. The version where `K` is an `R`-algebra is `linear_independent.restrict_scalars_algebras`. -/ lemma linear_independent.restrict_scalars [semiring K] [smul_with_zero R K] [module K M] [is_scalar_tower R K M] (hinj : function.injective (λ r : R, r • (1 : K))) (li : linear_independent K v) : linear_independent R v := begin refine linear_independent_iff'.mpr (λ s g hg i hi, hinj (eq.trans _ (zero_smul _ _).symm)), refine (linear_independent_iff'.mp li : _) _ _ _ i hi, simp_rw [smul_assoc, one_smul], exact hg, end /-- Every finite subset of a linearly independent set is linearly independent. -/ lemma linear_independent_finset_map_embedding_subtype (s : set M) (li : linear_independent R (coe : s → M)) (t : finset s) : linear_independent R (coe : (finset.map (embedding.subtype s) t) → M) := begin let f : t.map (embedding.subtype s) → s := λ x, ⟨x.1, begin obtain ⟨x, h⟩ := x, rw [finset.mem_map] at h, obtain ⟨a, ha, rfl⟩ := h, simp only [subtype.coe_prop, embedding.coe_subtype], end⟩, convert linear_independent.comp li f _, rintros ⟨x, hx⟩ ⟨y, hy⟩, rw [finset.mem_map] at hx hy, obtain ⟨a, ha, rfl⟩ := hx, obtain ⟨b, hb, rfl⟩ := hy, simp only [imp_self, subtype.mk_eq_mk], end /-- If every finite set of linearly independent vectors has cardinality at most `n`, then the same is true for arbitrary sets of linearly independent vectors. -/ lemma linear_independent_bounded_of_finset_linear_independent_bounded {n : ℕ} (H : ∀ s : finset M, linear_independent R (λ i : s, (i : M)) → s.card ≤ n) : ∀ s : set M, linear_independent R (coe : s → M) → #s ≤ n := begin intros s li, apply cardinal.card_le_of, intro t, rw ← finset.card_map (embedding.subtype s), apply H, apply linear_independent_finset_map_embedding_subtype _ li, end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin simp only [linear_independent_iff, (∘), finsupp.mem_supported, finsupp.total_apply, set.subset_def, finset.mem_coe], split, { intros h l hl₁ hl₂, have := h (l.subtype_domain s) ((finsupp.sum_subtype_domain_index hl₁).trans hl₂), exact (finsupp.subtype_domain_eq_zero_iff hl₁).1 this }, { intros h l hl, refine finsupp.emb_domain_eq_zero.1 (h (l.emb_domain $ function.embedding.subtype s) _ _), { suffices : ∀ i hi, ¬l ⟨i, hi⟩ = 0 → i ∈ s, by simpa, intros, assumption }, { rwa [finsupp.emb_domain_eq_map_domain, finsupp.sum_map_domain_index], exacts [λ _, zero_smul _ _, λ _ _ _, add_smul _ _ _] } } end lemma linear_dependent_comp_subtype' {s : set ι} : ¬ linear_independent R (v ∘ coe : s → M) ↔ ∃ f : ι →₀ R, f ∈ finsupp.supported R R s ∧ finsupp.total ι M R v f = 0 ∧ f ≠ 0 := by simp [linear_independent_comp_subtype] /-- A version of `linear_dependent_comp_subtype'` with `finsupp.total` unfolded. -/ lemma linear_dependent_comp_subtype {s : set ι} : ¬ linear_independent R (v ∘ coe : s → M) ↔ ∃ f : ι →₀ R, f ∈ finsupp.supported R R s ∧ ∑ i in f.support, f i • v i = 0 ∧ f ≠ 0 := linear_dependent_comp_subtype' theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint_iff_inf_le, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ coe : s → M)) : linear_independent R (s.restrict v) := hs variables (R M) lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] variables {R M} lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint.mono_left (finsupp.supported_mono h)) end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, set.finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin by_cases hη : nonempty η, { resetI, refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ Union₂_subset $ λ j hj, hi j (fi.mem_to_finset.2 hj)) }, { refine (linear_independent_empty _ _).mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed hs.directed_coe (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed (directed_comp.2 $ hs.directed_coe) (by simpa using h) end subtype end module /-! ### Properties which require `ring R` -/ section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] [add_comm_group M''] variables [module R M] [module R M'] [module R M''] variables {a b : R} {x y : M} theorem linear_independent_iff_injective_total : linear_independent R v ↔ function.injective (finsupp.total ι M R v) := linear_independent_iff.trans (injective_iff_map_eq_zero (finsupp.total ι M R v).to_add_monoid_hom).symm alias linear_independent_iff_injective_total ↔ linear_independent.injective_total _ lemma linear_independent.injective [nontrivial R] (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { simp_rw [linear_map.map_sub, finsupp.total_apply], simp [hij] }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, simpa [finsupp.single_eq_single_iff] using h_single_eq end theorem linear_independent.to_subtype_range {ι} {f : ι → M} (hf : linear_independent R f) : linear_independent R (coe : range f → M) := begin nontriviality R, exact (linear_independent_subtype_range hf.injective).2 hf end theorem linear_independent.to_subtype_range' {ι} {f : ι → M} (hf : linear_independent R f) {t} (ht : range f = t) : linear_independent R (coe : t → M) := ht ▸ hf.to_subtype_range theorem linear_independent.image_of_comp {ι ι'} (s : set ι) (f : ι → ι') (g : ι' → M) (hs : linear_independent R (λ x : s, g (f x))) : linear_independent R (λ x : f '' s, g x) := begin nontriviality R, have : inj_on f s, from inj_on_iff_injective.2 hs.injective.of_comp, exact (linear_independent_equiv' (equiv.set.image_of_inj_on f s this) rfl).1 hs end theorem linear_independent.image {ι} {s : set ι} {f : ι → M} (hs : linear_independent R (λ x : s, f x)) : linear_independent R (λ x : f '' s, (x : M)) := by convert linear_independent.image_of_comp s f id hs lemma linear_independent.group_smul {G : Type*} [hG : group G] [distrib_mul_action G R] [distrib_mul_action G M] [is_scalar_tower G R M] [smul_comm_class G R M] {v : ι → M} (hv : linear_independent R v) (w : ι → G) : linear_independent R (w • v) := begin rw linear_independent_iff'' at hv ⊢, intros s g hgs hsum i, refine (smul_eq_zero_iff_eq (w i)).1 _, refine hv s (λ i, w i • g i) (λ i hi, _) _ i, { dsimp only, exact (hgs i hi).symm ▸ smul_zero _ }, { rw [← hsum, finset.sum_congr rfl _], intros, erw [pi.smul_apply, smul_assoc, smul_comm] }, end -- This lemma cannot be proved with `linear_independent.group_smul` since the action of -- `Rˣ` on `R` is not commutative. lemma linear_independent.units_smul {v : ι → M} (hv : linear_independent R v) (w : ι → Rˣ) : linear_independent R (w • v) := begin rw linear_independent_iff'' at hv ⊢, intros s g hgs hsum i, rw ← (w i).mul_left_eq_zero, refine hv s (λ i, g i • w i) (λ i hi, _) _ i, { dsimp only, exact (hgs i hi).symm ▸ zero_smul _ _ }, { rw [← hsum, finset.sum_congr rfl _], intros, erw [pi.smul_apply, smul_assoc], refl } end section maximal universes v w /-- A linearly independent family is maximal if there is no strictly larger linearly independent family. -/ @[nolint unused_arguments] def linear_independent.maximal {ι : Type w} {R : Type u} [semiring R] {M : Type v} [add_comm_monoid M] [module R M] {v : ι → M} (i : linear_independent R v) : Prop := ∀ (s : set M) (i' : linear_independent R (coe : s → M)) (h : range v ≤ s), range v = s /-- An alternative characterization of a maximal linearly independent family, quantifying over types (in the same universe as `M`) into which the indexing family injects. -/ lemma linear_independent.maximal_iff {ι : Type w} {R : Type u} [ring R] [nontrivial R] {M : Type v} [add_comm_group M] [module R M] {v : ι → M} (i : linear_independent R v) : i.maximal ↔ ∀ (κ : Type v) (w : κ → M) (i' : linear_independent R w) (j : ι → κ) (h : w ∘ j = v), surjective j := begin fsplit, { rintros p κ w i' j rfl, specialize p (range w) i'.coe_range (range_comp_subset_range _ _), rw [range_comp, ←@image_univ _ _ w] at p, exact range_iff_surjective.mp (image_injective.mpr i'.injective p), }, { intros p w i' h, specialize p w (coe : w → M) i' (λ i, ⟨v i, range_subset_iff.mp h i⟩) (by { ext, simp, }), have q := congr_arg (λ s, (coe : w → M) '' s) p.range_eq, dsimp at q, rw [←image_univ, image_image] at q, simpa using q, }, end end maximal /-- Linear independent families are injective, even if you multiply either side. -/ lemma linear_independent.eq_of_smul_apply_eq_smul_apply {M : Type*} [add_comm_group M] [module R M] {v : ι → M} (li : linear_independent R v) (c d : R) (i j : ι) (hc : c ≠ 0) (h : c • v i = d • v j) : i = j := begin let l : ι →₀ R := finsupp.single i c - finsupp.single j d, have h_total : finsupp.total ι M R v l = 0, { simp_rw [linear_map.map_sub, finsupp.total_apply], simp [h] }, have h_single_eq : finsupp.single i c = finsupp.single j d, { rw linear_independent_iff at li, simp [eq_add_of_sub_eq' (li l h_total)] }, rcases (finsupp.single_eq_single_iff _ _ _ _).mp h_single_eq with ⟨this, _⟩ | ⟨hc, _⟩, { exact this }, { contradiction }, end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ lemma linear_independent.disjoint_span_image (hv : linear_independent R v) {s t : set ι} (hs : disjoint s t) : disjoint (submodule.span R $ v '' s) (submodule.span R $ v '' t) := begin simp only [disjoint_def, finsupp.mem_span_image_iff_total], rintros _ ⟨l₁, hl₁, rfl⟩ ⟨l₂, hl₂, H⟩, rw [hv.injective_total.eq_iff] at H, subst l₂, have : l₁ = 0 := submodule.disjoint_def.mp (finsupp.disjoint_supported_supported hs) _ hl₁ hl₂, simp [this] end lemma linear_independent.not_mem_span_image [nontrivial R] (hv : linear_independent R v) {s : set ι} {x : ι} (h : x ∉ s) : v x ∉ submodule.span R (v '' s) := begin have h' : v x ∈ submodule.span R (v '' {x}), { rw set.image_singleton, exact mem_span_singleton_self (v x), }, intro w, apply linear_independent.ne_zero x hv, refine disjoint_def.1 (hv.disjoint_span_image _) (v x) h' w, simpa using h, end lemma linear_independent.total_ne_of_not_mem_support [nontrivial R] (hv : linear_independent R v) {x : ι} (f : ι →₀ R) (h : x ∉ f.support) : finsupp.total ι M R v f ≠ v x := begin replace h : x ∉ (f.support : set ι) := h, have p := hv.not_mem_span_image h, intro w, rw ←w at p, rw finsupp.span_image_eq_map_total at p, simp only [not_exists, not_and, mem_map] at p, exact p f (f.mem_supported_support R) rfl, end lemma linear_independent_sum {v : ι ⊕ ι' → M} : linear_independent R v ↔ linear_independent R (v ∘ sum.inl) ∧ linear_independent R (v ∘ sum.inr) ∧ disjoint (submodule.span R (range (v ∘ sum.inl))) (submodule.span R (range (v ∘ sum.inr))) := begin rw [range_comp v, range_comp v], refine ⟨λ h, ⟨h.comp _ sum.inl_injective, h.comp _ sum.inr_injective, h.disjoint_span_image is_compl_range_inl_range_inr.1⟩, _⟩, rintro ⟨hl, hr, hlr⟩, rw [linear_independent_iff'] at *, intros s g hg i hi, have : ∑ i in s.preimage sum.inl (sum.inl_injective.inj_on _), (λ x, g x • v x) (sum.inl i) + ∑ i in s.preimage sum.inr (sum.inr_injective.inj_on _), (λ x, g x • v x) (sum.inr i) = 0, { rw [finset.sum_preimage', finset.sum_preimage', ← finset.sum_union, ← finset.filter_or], { simpa only [← mem_union, range_inl_union_range_inr, mem_univ, finset.filter_true] }, { exact finset.disjoint_filter.2 (λ x _ hx, disjoint_left.1 is_compl_range_inl_range_inr.1 hx) } }, { rw ← eq_neg_iff_add_eq_zero at this, rw [disjoint_def'] at hlr, have A := hlr _ (sum_mem $ λ i hi, _) _ (neg_mem $ sum_mem $ λ i hi, _) this, { cases i with i i, { exact hl _ _ A i (finset.mem_preimage.2 hi) }, { rw [this, neg_eq_zero] at A, exact hr _ _ A i (finset.mem_preimage.2 hi) } }, { exact smul_mem _ _ (subset_span ⟨sum.inl i, mem_range_self _, rfl⟩) }, { exact smul_mem _ _ (subset_span ⟨sum.inr i, mem_range_self _, rfl⟩) } } end lemma linear_independent.sum_type {v' : ι' → M} (hv : linear_independent R v) (hv' : linear_independent R v') (h : disjoint (submodule.span R (range v)) (submodule.span R (range v'))) : linear_independent R (sum.elim v v') := linear_independent_sum.2 ⟨hv, hv', h⟩ lemma linear_independent.union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := (hs.sum_type ht $ by simpa).to_subtype_range' $ by simp lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, t.finite → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, { apply directed_of_sup, exact (λ t₁ t₂ ht, Union_mono $ λ i, Union_subset_Union_const $ λ h, ht h) }, assume t, induction t using finset.induction_on with i s his ih, { refine (linear_independent_empty _ _).mono _, simp }, { rw [finset.set_bUnion_insert], refine (hl _).union ih _, rw span_Union₂, exact hd i s s.finite_to_set his } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, t.finite → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin nontriviality R, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim ((hindep x₁).ne_zero _ h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ @[simps {rhs_md := semireducible}] def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), split, { rw [← linear_map.ker_eq_bot, linear_map.ker_cod_restrict], apply hv }, { rw [← linear_map.range_eq_top, linear_map.range_eq_map, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, exact le_rfl }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm @[simp] lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.ext_iff.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.ext_iff.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end lemma linear_independent.span_repr_eq [nontrivial R] (x) : span.repr R (set.range v) x = (hv.repr x).equiv_map_domain (equiv.of_injective _ hv.injective) := begin have p : (span.repr R (set.range v) x).equiv_map_domain (equiv.of_injective _ hv.injective).symm = hv.repr x, { apply (linear_independent.total_equiv hv).injective, ext, simp only [linear_independent.total_equiv_apply_coe, equiv.self_comp_of_injective_symm, linear_independent.total_repr, finsupp.total_equiv_map_domain, span.finsupp_total_repr], }, ext ⟨_, ⟨i, rfl⟩⟩, simp [←p], end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_image_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_image_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ /-- See also `complete_lattice.independent_iff_linear_independent_of_ne_zero`. -/ lemma linear_independent.independent_span_singleton (hv : linear_independent R v) : complete_lattice.independent $ λ i, R ∙ v i := begin refine complete_lattice.independent_def.mp (λ i, _), rw disjoint_iff_inf_le, intros m hm, simp only [mem_inf, mem_span_singleton, supr_subtype', ← span_range_eq_supr] at hm, obtain ⟨⟨r, rfl⟩, hm⟩ := hm, suffices : r = 0, { simp [this], }, apply linear_independent_iff_not_smul_mem_span.mp hv i, convert hm, ext, simp, end variable (R) lemma exists_maximal_independent' (s : ι → M) : ∃ I : set ι, linear_independent R (λ x : I, s x) ∧ ∀ J : set ι, I ⊆ J → linear_independent R (λ x : J, s x) → I = J := begin let indep : set ι → Prop := λ I, linear_independent R (s ∘ coe : I → M), let X := { I : set ι // indep I }, let r : X → X → Prop := λ I J, I.1 ⊆ J.1, have key : ∀ c : set X, is_chain r c → indep (⋃ (I : X) (H : I ∈ c), I), { intros c hc, dsimp [indep], rw [linear_independent_comp_subtype], intros f hsupport hsum, rcases eq_empty_or_nonempty c with rfl | hn, { simpa using hsupport }, haveI : is_refl X r := ⟨λ _, set.subset.refl _⟩, obtain ⟨I, I_mem, hI⟩ : ∃ I ∈ c, (f.support : set ι) ⊆ I := hc.directed_on.exists_mem_subset_of_finset_subset_bUnion hn hsupport, exact linear_independent_comp_subtype.mp I.2 f hI hsum }, have trans : transitive r := λ I J K, set.subset.trans, obtain ⟨⟨I, hli : indep I⟩, hmax : ∀ a, r ⟨I, hli⟩ a → r a ⟨I, hli⟩⟩ := @exists_maximal_of_chains_bounded _ r (λ c hc, ⟨⟨⋃ I ∈ c, (I : set ι), key c hc⟩, λ I, set.subset_bUnion_of_mem⟩) trans, exact ⟨I, hli, λ J hsub hli, set.subset.antisymm hsub (hmax ⟨J, hli⟩ hsub)⟩, end lemma exists_maximal_independent (s : ι → M) : ∃ I : set ι, linear_independent R (λ x : I, s x) ∧ ∀ i ∉ I, ∃ a : R, a ≠ 0 ∧ a • s i ∈ span R (s '' I) := begin classical, rcases exists_maximal_independent' R s with ⟨I, hIlinind, hImaximal⟩, use [I, hIlinind], intros i hi, specialize hImaximal (I ∪ {i}) (by simp), set J := I ∪ {i} with hJ, have memJ : ∀ {x}, x ∈ J ↔ x = i ∨ x ∈ I, by simp [hJ], have hiJ : i ∈ J := by simp, have h := mt hImaximal _, swap, { intro h2, rw h2 at hi, exact absurd hiJ hi }, obtain ⟨f, supp_f, sum_f, f_ne⟩ := linear_dependent_comp_subtype.mp h, have hfi : f i ≠ 0, { contrapose hIlinind, refine linear_dependent_comp_subtype.mpr ⟨f, _, sum_f, f_ne⟩, simp only [finsupp.mem_supported, hJ] at ⊢ supp_f, rintro x hx, refine (memJ.mp (supp_f hx)).resolve_left _, rintro rfl, exact hIlinind (finsupp.mem_support_iff.mp hx) }, use [f i, hfi], have hfi' : i ∈ f.support := finsupp.mem_support_iff.mpr hfi, rw [← finset.insert_erase hfi', finset.sum_insert (finset.not_mem_erase _ _), add_eq_zero_iff_eq_neg] at sum_f, rw sum_f, refine neg_mem (sum_mem (λ c hc, smul_mem _ _ (subset_span ⟨c, _, rfl⟩))), exact (memJ.mp (supp_f (finset.erase_subset _ _ hc))).resolve_left (finset.ne_of_mem_erase hc), end end repr lemma surjective_of_linear_independent_of_span [nontrivial R] (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) : surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.injective).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.injective).total_repr, { refl } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype [nontrivial R] {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.coe_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image_subtype {s : set M} {f : M →ₗ[R] M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [← @subtype.range_coe _ s] at hf_inj, refine (hs.map hf_inj).to_subtype_range' _, simp [set.range_comp f] end lemma linear_independent.inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin refine (hs.image_subtype _).union (ht.image_subtype _) _; [simp, simp, skip], simp only [span_image], simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := (hv.map' (inl R M M') ker_inl).sum_type (hv'.map' (inr R M M') ker_inr) $ begin refine is_compl_range_inl_inr.disjoint.mono _ _; simp only [span_le, range_coe, range_comp_subset_range], end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note -- <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [comm_ring L] [no_zero_divisors L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the -- monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. (∑ i in s, ((g i * i x - g i * a x) • i : G → L)) y = ∑ i in s, (g i * i x - g i * a x) * i y : finset.sum_apply _ _ _ ... = ∑ i in s, (g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = ∑ i in s, g i * i x * i y - ∑ i in s, g i * a x * i y : finset.sum_sub_distrib ... = (g a * a x * a y + ∑ i in s, g i * i x * i y) - (g a * a x * a y + ∑ i in s, g i * a x * i y) : by rw add_sub_add_left_eq_sub ... = ∑ i in insert a s, g i * i x * i y - ∑ i in insert a s, g i * a x * i y : by rw [finset.sum_insert has, finset.sum_insert has] ... = ∑ i in insert a s, g i * i (x * y) - ∑ i in insert a s, a x * (g i * i y) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (∑ i in insert a s, (g i • i : G → L)) (x * y) - a x * (∑ i in insert a s, (g i • i : G → L)) y : by rw [finset.sum_apply, finset.sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (∑ i in insert a s, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element -- of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M)) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span hl hsu htu, span_mono⟩ end module section nontrivial variables [ring R] [nontrivial R] [add_comm_group M] [add_comm_group M'] variables [module R M] [no_zero_smul_divisors R M] [module R M'] variables {v : ι → M} {s t : set M} {x y z : M} lemma linear_independent_unique_iff (v : ι → M) [unique ι] : linear_independent R v ↔ v default ≠ 0 := begin simp only [linear_independent_iff, finsupp.total_unique, smul_eq_zero], refine ⟨λ h hv, _, λ hv l hl, finsupp.unique_ext $ hl.resolve_right hv⟩, have := h (finsupp.single default 1) (or.inr hv), exact one_ne_zero (finsupp.single_eq_zero.1 this) end alias linear_independent_unique_iff ↔ _ linear_independent_unique lemma linear_independent_singleton {x : M} (hx : x ≠ 0) : linear_independent R (λ x, x : ({x} : set M) → M) := linear_independent_unique coe hx end nontrivial /-! ### Properties which require `division_ring K` These can be considered generalizations of properties of linear independence in vector spaces. -/ section module variables [division_ring K] [add_comm_group V] [add_comm_group V'] variables [module K V] [module K V'] variables {v : ι → V} {s t : set V} {x y z : V} open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem (span K s)) hx, apply hs.union (linear_independent_singleton x0), rwa [disjoint_span_singleton' x0] end lemma linear_independent_option' : linear_independent K (λ o, option.cases_on' o x v : option ι → V) ↔ linear_independent K v ∧ (x ∉ submodule.span K (range v)) := begin rw [← linear_independent_equiv (equiv.option_equiv_sum_punit ι).symm, linear_independent_sum, @range_unique _ punit, @linear_independent_unique_iff punit, disjoint_span_singleton], dsimp [(∘)], refine ⟨λ h, ⟨h.1, λ hx, h.2.1 $ h.2.2 hx⟩, λ h, ⟨h.1, _, λ hx, (h.2 hx).elim⟩⟩, rintro rfl, exact h.2 (zero_mem _) end lemma linear_independent.option (hv : linear_independent K v) (hx : x ∉ submodule.span K (range v)) : linear_independent K (λ o, option.cases_on' o x v : option ι → V) := linear_independent_option'.2 ⟨hv, hx⟩ lemma linear_independent_option {v : option ι → V} : linear_independent K v ↔ linear_independent K (v ∘ coe : ι → V) ∧ v none ∉ submodule.span K (range (v ∘ coe : ι → V)) := by simp only [← linear_independent_option', option.cases_on'_none_coe] theorem linear_independent_insert' {ι} {s : set ι} {a : ι} {f : ι → V} (has : a ∉ s) : linear_independent K (λ x : insert a s, f x) ↔ linear_independent K (λ x : s, f x) ∧ f a ∉ submodule.span K (f '' s) := by { rw [← linear_independent_equiv ((equiv.option_equiv_sum_punit _).trans (equiv.set.insert has).symm), linear_independent_option], simp [(∘), range_comp f] } theorem linear_independent_insert (hxs : x ∉ s) : linear_independent K (λ b : insert x s, (b : V)) ↔ linear_independent K (λ b : s, (b : V)) ∧ x ∉ submodule.span K s := (@linear_independent_insert' _ _ _ _ _ _ _ _ id hxs).trans $ by simp lemma linear_independent_pair {x y : V} (hx : x ≠ 0) (hy : ∀ a : K, a • x ≠ y) : linear_independent K (coe : ({x, y} : set V) → V) := pair_comm y x ▸ (linear_independent_singleton hx).insert $ mt mem_span_singleton.1 (not_exists.2 hy) lemma linear_independent_fin_cons {n} {v : fin n → V} : linear_independent K (fin.cons x v : fin (n + 1) → V) ↔ linear_independent K v ∧ x ∉ submodule.span K (range v) := begin rw [← linear_independent_equiv (fin_succ_equiv n).symm, linear_independent_option], convert iff.rfl, { ext, -- TODO: why doesn't simp use `fin_succ_equiv_symm_coe` here? rw [comp_app, comp_app, fin_succ_equiv_symm_coe, fin.cons_succ] }, { ext, rw [comp_app, comp_app, fin_succ_equiv_symm_coe, fin.cons_succ] } end lemma linear_independent_fin_snoc {n} {v : fin n → V} : linear_independent K (fin.snoc v x : fin (n + 1) → V) ↔ linear_independent K v ∧ x ∉ submodule.span K (range v) := by rw [fin.snoc_eq_cons_rotate, linear_independent_equiv, linear_independent_fin_cons] /-- See `linear_independent.fin_cons'` for an uglier version that works if you only have a module over a semiring. -/ lemma linear_independent.fin_cons {n} {v : fin n → V} (hv : linear_independent K v) (hx : x ∉ submodule.span K (range v)) : linear_independent K (fin.cons x v : fin (n + 1) → V) := linear_independent_fin_cons.2 ⟨hv, hx⟩ lemma linear_independent_fin_succ {n} {v : fin (n + 1) → V} : linear_independent K v ↔ linear_independent K (fin.tail v) ∧ v 0 ∉ submodule.span K (range $ fin.tail v) := by rw [← linear_independent_fin_cons, fin.cons_self_tail] lemma linear_independent_fin_succ' {n} {v : fin (n + 1) → V} : linear_independent K v ↔ linear_independent K (fin.init v) ∧ v (fin.last _) ∉ submodule.span K (range $ fin.init v) := by rw [← linear_independent_fin_snoc, fin.snoc_init_self] lemma linear_independent_fin2 {f : fin 2 → V} : linear_independent K f ↔ f 1 ≠ 0 ∧ ∀ a : K, a • f 1 ≠ f 0 := by rw [linear_independent_fin_succ, linear_independent_unique_iff, range_unique, mem_span_singleton, not_exists, show fin.tail f default = f 1, by rw ← fin.succ_zero_eq_one; refl] lemma exists_linear_independent_extension (hs : linear_independent K (coe : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (coe : b → V) := begin rcases zorn_subset_nonempty {b | b ⊆ t ∧ linear_independent K (coe : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end variables (K t) lemma exists_linear_independent : ∃ b ⊆ t, span K b = span K t ∧ linear_independent K (coe : b → V) := begin obtain ⟨b, hb₁, -, hb₂, hb₃⟩ := exists_linear_independent_extension (linear_independent_empty K V) (set.empty_subset t), exact ⟨b, hb₁, (span_eq_of_le _ hb₂ (submodule.span_mono hb₁)).symm, hb₃⟩, end variables {K t} /-- `linear_independent.extend` adds vectors to a linear independent set `s ⊆ t` until it spans all elements of `t`. -/ noncomputable def linear_independent.extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : set V := classical.some (exists_linear_independent_extension hs hst) lemma linear_independent.extend_subset (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : hs.extend hst ⊆ t := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent_extension hs hst) in hbt lemma linear_independent.subset_extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : s ⊆ hs.extend hst := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent_extension hs hst) in hsb lemma linear_independent.subset_span_extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : t ⊆ span K (hs.extend hst) := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent_extension hs hst) in htb lemma linear_independent.linear_independent_extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : linear_independent K (coe : hs.extend hst → V) := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent_extension hs hst) in hli variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { ext1 x, by_cases x ∈ s; simp * }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : t.finite) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : s.finite, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have s.finite, from u.finite_to_set.subset hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ end module
05b801c497313a3e23d21b15891d73267038f01c
43390109ab88557e6090f3245c47479c123ee500
/src/M1F/problem_bank/0302/Q0302.lean
1f99f18244c31b27a3ab137097ae04ee0fa0458f
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,529
lean
theorem Q2a {x y : fake_reals} : (x > 0) → (y < 0) → x * y < 0 := sorry theorem neg_pos_of_neg' {x : fake_reals} : x < 0 → -x > 0 := begin intro Hx_neg, have H : x + (-x) < 0 + (-x) := A1 Hx_neg, rwa [add_neg_self,zero_add] at H, end theorem neg_eq_neg_one_mul' {x : fake_reals} : -x = (-1)*x := neg_eq_neg_one_mul x theorem neg_one_squared : (-1:fake_reals)*(-1)=1 := calc (-1:fake_reals)*(-1)=-(-1) : eq.symm (@neg_eq_neg_one_mul' (-1)) ... = 1 : neg_neg 1 theorem pos_eq_neg_mul_neg {x y : fake_reals} : x < 0 → y < 0 → x * y > 0 := begin intros Hxneg Hyneg, have Hneg_x_pos : -x > 0 := neg_pos_of_neg' Hxneg, have Hneg_y_pos : -y > 0 := neg_pos_of_neg' Hyneg, exact calc x * y = -x * -y : by rw [neg_eq_neg_one_mul',@neg_eq_neg_one_mul' y,←mul_one (x * y),←neg_one_squared];simp ... > 0 : A4 Hneg_x_pos Hneg_y_pos, end theorem Q2b {x y : fake_reals} : x < 0 → y < 0 → x * y > 0 := sorry theorem zero_not_pos : ¬ ((0:fake_reals) < 0) := (@A3 0 0).right.right.right (rfl) theorem fake_reals_integral_domain {x y : fake_reals} : x * y = 0 → x = 0 ∨ y = 0 := begin intro Hxy_zero, cases (@A3 0 x).left with Hx_pos Hx_nonpos, cases (@A3 0 y).left with Hy_pos Hy_nonpos, exfalso, exact zero_not_pos (calc 0 < x * y : A4 Hx_pos Hy_pos ... = 0 : Hxy_zero), cases Hy_nonpos with Hy_0 Hy_neg, right,exact eq.symm Hy_0, exfalso, apply zero_not_pos, exact calc 0 = x*y : eq.symm Hxy_zero ... <0 : Q2a Hx_pos Hy_neg, cases Hx_nonpos with Hx_0 Hx_neg, left,exact eq.symm Hx_0, cases (@A3 0 y).left with Hy_pos Hy_nonpos, exfalso, apply zero_not_pos, exact calc 0=x*y : eq.symm Hxy_zero ... = y*x : by rw[mul_comm] ... <0 : Q2a Hy_pos Hx_neg, cases Hy_nonpos with Hy_0 Hy_neg, right,exact eq.symm Hy_0, exfalso, apply zero_not_pos, exact calc 0 < x * y : Q2b Hx_neg Hy_neg ... = 0 : Hxy_zero, end theorem Q2c : ∀ x y : fake_reals, x * y = 0 → x = 0 ∨ y = 0 := sorry end M1F_Sheet03 axiom A5 : ∀ x : fake_reals, x > 0 → ∃ y : fake_reals, y > 0 ∧ y*y=x ∧ ∀ z : fake_reals, z > 0 ∧ z*z=x → z=y section M1F_Sheet03 theorem Q2d : ∀ x : fake_reals, x > 0 → ∃ z1 z2 : fake_reals, z1*z1=x ∧ z2*z2=x ∧ ∀ z : fake_reals, z*z=x → z=z1 ∨ z=z2 := sorry end M1F_Sheet03 axiom A6 : ∀ n : ℕ, n > 0 → ∀ x : fake_reals, x > 0 → ∃ y : fake_reals, y > 0 ∧ y ^ n = x ∧ ∀ z : fake_reals, z > 0 ∧ z ^ n = x → z = y section M1F_Sheet03
d1aa51b3b357c981ea68cb07d68274ff9e318cae
1dd482be3f611941db7801003235dc84147ec60a
/src/ring_theory/matrix.lean
d71c39a68c623a0195b01d59e9e4f3d912773585
[ "Apache-2.0" ]
permissive
sanderdahmen/mathlib
479039302bd66434bb5672c2a4cecf8d69981458
8f0eae75cd2d8b7a083cf935666fcce4565df076
refs/heads/master
1,587,491,322,775
1,549,672,060,000
1,549,672,060,000
169,748,224
0
0
Apache-2.0
1,549,636,694,000
1,549,636,694,000
null
UTF-8
Lean
false
false
8,163
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 Matrices -/ import algebra.module data.fintype algebra.pi_instances universes u v 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]⟩ @[extensionality] theorem ext : (∀ i j, M i j = N i j) → M = N := ext_iff.mp end ext 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 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 @[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] protected def mul [has_mul α] [add_comm_monoid α] (M : matrix l m α) (N : matrix m n α) : matrix l n α := λ i k, finset.univ.sum (λ j, M i j * N j k) theorem mul_val [has_mul α] [add_comm_monoid α] {M : matrix l m α} {N : matrix m n α} {i k} : (M.mul N) i k = finset.univ.sum (λ j, M i j * N j k) := rfl local attribute [simp] mul_val 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.mul N := rfl theorem mul_val' [has_mul α] [add_comm_monoid α] {M N : matrix n n α} {i k} : (M * N) i k = finset.univ.sum (λ j, M i j * N j k) := rfl section semigroup variables [decidable_eq m] [decidable_eq n] [semiring α] protected theorem mul_assoc (L : matrix l m α) (M : matrix m n α) (N : matrix n o α) : (L.mul M).mul N = L.mul (M.mul N) := by funext i k; simp [finset.mul_sum, finset.sum_mul, mul_assoc]; rw finset.sum_comm 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 α] theorem mul_zero (M : matrix m n α) : M.mul (0 : matrix n n α) = 0 := by ext i j; simp theorem zero_mul (M : matrix m n α) : (0 : matrix m m α).mul M = 0 := by ext i j; simp theorem mul_add (L : matrix m n α) (M N : matrix n n α) : L.mul (M + N) = L.mul M + L.mul N := by ext i j; simp [finset.sum_add_distrib, mul_add] theorem add_mul (L M : matrix m m α) (N : matrix m n α) : (L + M).mul N = L.mul N + M.mul N := by ext i j; simp [finset.sum_add_distrib, add_mul] @[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 := by simp; rw finset.sum_eq_single i; simp [diagonal_val_ne'] {contextual := tt} @[simp] theorem mul_diagonal [decidable_eq n] (d : n → α) (M : matrix m n α) (i j) : M.mul (diagonal d) i j = M i j * d j := by simp; rw finset.sum_eq_single j; simp {contextual := tt} protected theorem one_mul [decidable_eq m] (M : matrix m n α) : (1 : matrix m m α).mul M = M := by ext i j; rw [← diagonal_one, diagonal_mul, one_mul] protected theorem mul_one [decidable_eq n] (M : matrix m n α) : M.mul (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 := mul_zero, zero_mul := zero_mul, left_distrib := mul_add, right_distrib := add_mul, ..matrix.add_comm_monoid, ..matrix.monoid } @[simp] theorem diagonal_mul_diagonal' [decidable_eq n] (d₁ d₂ : n → α) : (diagonal d₁).mul (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' _ _ end semiring instance [decidable_eq n] [ring α] : ring (matrix n n α) := { ..matrix.add_comm_group, ..matrix.semiring } instance [has_mul α] : has_scalar α (matrix m n α) := ⟨λ a M i j, a * M i j⟩ instance [ring α] : module α (matrix m n α) := module.of_core { smul_add := λ a M N, ext $ λ i j, _root_.mul_add a (M i j) (N i j), add_smul := λ a b M, ext $ λ i j, _root_.add_mul a b (M i j), mul_smul := λ a b M, ext $ λ i j, mul_assoc a b (M i j), one_smul := λ M, ext $ λ i j, one_mul (M i j), .. (infer_instance : has_scalar α (matrix m n α)) } def minor (A : matrix m n α) (col : l → m) (row : o → n) : matrix l o α := λ i j, A (col i) (row 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) end matrix
eaa40889c45c174b85b3ac2cef37c886f404db57
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0103.lean
4c48a6655886b0df92a0ea1699c7ab81c3005f7e
[]
no_license
Ailrun/Theorem_Proving_in_Lean
ae6a23f3c54d62d401314d6a771e8ff8b4132db2
2eb1b5caf93c6a5a555c79e9097cf2ba5a66cf68
refs/heads/master
1,609,838,270,467
1,586,846,743,000
1,586,846,743,000
240,967,761
1
0
null
null
null
null
UTF-8
Lean
false
false
115
lean
constant Proof : Prop → Type constant modus_ponens : Π p q : Prop, Proof (implies p q) → Proof p → Proof q
03d114a3600a860a47b2c5a5357368748307463d
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Lean/Meta/Tactic/Intro.lean
c3c1796bbd5e4233d604fa536db83c6343c3f9bf
[ "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,964
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.Tactic.Util namespace Lean.Meta @[inline] private partial def introNImp {σ} (mvarId : MVarId) (n : Nat) (mkName : LocalContext → Name → Bool → σ → MetaM (Name × σ)) (s : σ) : MetaM (Array FVarId × MVarId) := withMVarContext mvarId do checkNotAssigned mvarId `introN let mvarType ← getMVarType mvarId let lctx ← getLCtx let rec @[specialize] loop : Nat → LocalContext → Array Expr → Nat → σ → Expr → MetaM (Array Expr × MVarId) | 0, lctx, fvars, j, _, type => let type := type.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstances fvars j do let tag ← getMVarTag mvarId let type := type.headBeta let newMVar ← mkFreshExprSyntheticOpaqueMVar type tag let lctx ← getLCtx let newVal ← mkLambdaFVars fvars newMVar assignExprMVar mvarId newVal pure $ (fvars, newMVar.mvarId!) | (i+1), lctx, fvars, j, s, Expr.letE n type val body _ => do let type := type.instantiateRevRange j fvars.size fvars let type := type.headBeta let val := val.instantiateRevRange j fvars.size fvars let fvarId ← mkFreshId let (n, s) ← mkName lctx n true s let lctx := lctx.mkLetDecl fvarId n type val let fvar := mkFVar fvarId let fvars := fvars.push fvar loop i lctx fvars j s body | (i+1), lctx, fvars, j, s, Expr.forallE n type body c => do let type := type.instantiateRevRange j fvars.size fvars let type := type.headBeta let fvarId ← mkFreshId let (n, s) ← mkName lctx n c.binderInfo.isExplicit s let lctx := lctx.mkLocalDecl fvarId n type c.binderInfo let fvar := mkFVar fvarId let fvars := fvars.push fvar loop i lctx fvars j s body | (i+1), lctx, fvars, j, s, type => let type := type.instantiateRevRange j fvars.size fvars withReader (fun ctx => { ctx with lctx := lctx }) do withNewLocalInstances fvars j do let newType ← whnf type if newType.isForall then loop (i+1) lctx fvars fvars.size s newType else throwTacticEx `introN mvarId "insufficient number of binders" let (fvars, mvarId) ← loop n lctx #[] 0 s mvarType pure (fvars.map Expr.fvarId!, mvarId) register_builtin_option tactic.hygienic : Bool := { defValue := true group := "tactic" descr := "make sure tactics are hygienic" } def getHygienicIntro : MetaM Bool := do return tactic.hygienic.get (← getOptions) private def mkAuxNameImp (preserveBinderNames : Bool) (hygienic : Bool) (useNamesForExplicitOnly : Bool) (lctx : LocalContext) (binderName : Name) (isExplicit : Bool) : List Name → MetaM (Name × List Name) | [] => mkAuxNameWithoutGivenName [] | n :: rest => do if useNamesForExplicitOnly && !isExplicit then mkAuxNameWithoutGivenName (n :: rest) else if n != Name.mkSimple "_" then pure (n, rest) else mkAuxNameWithoutGivenName rest where mkAuxNameWithoutGivenName (rest : List Name) : MetaM (Name × List Name) := do if preserveBinderNames then pure (binderName, rest) else if hygienic then let binderName ← mkFreshUserName binderName pure (binderName, rest) else pure (lctx.getUnusedName binderName, rest) def introNCore (mvarId : MVarId) (n : Nat) (givenNames : List Name) (useNamesForExplicitOnly : Bool) (preserveBinderNames : Bool) : MetaM (Array FVarId × MVarId) := do let hygienic ← getHygienicIntro if n == 0 then pure (#[], mvarId) else introNImp mvarId n (mkAuxNameImp preserveBinderNames hygienic useNamesForExplicitOnly) givenNames abbrev introN (mvarId : MVarId) (n : Nat) (givenNames : List Name := []) (useNamesForExplicitOnly := false) : MetaM (Array FVarId × MVarId) := introNCore mvarId n givenNames (useNamesForExplicitOnly := useNamesForExplicitOnly) (preserveBinderNames := false) abbrev introNP (mvarId : MVarId) (n : Nat) : MetaM (Array FVarId × MVarId) := introNCore mvarId n [] (useNamesForExplicitOnly := false) (preserveBinderNames := true) def intro (mvarId : MVarId) (name : Name) : MetaM (FVarId × MVarId) := do let (fvarIds, mvarId) ← introN mvarId 1 [name] pure (fvarIds.get! 0, mvarId) def intro1Core (mvarId : MVarId) (preserveBinderNames : Bool) : MetaM (FVarId × MVarId) := do let (fvarIds, mvarId) ← introNCore mvarId 1 [] (useNamesForExplicitOnly := false) preserveBinderNames pure (fvarIds.get! 0, mvarId) abbrev intro1 (mvarId : MVarId) : MetaM (FVarId × MVarId) := intro1Core mvarId false abbrev intro1P (mvarId : MVarId) : MetaM (FVarId × MVarId) := intro1Core mvarId true end Lean.Meta
703c714a24b13bd066d4184fc3942fe5c776593e
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/tactic_state_pp.lean
7a3323895a0d11d6173e89d3013f13dbf1c1c00f
[ "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
1,062
lean
universe variables u inductive Vec (α : Type u) : nat → Type u | nil : Vec 0 | cons : ∀ {n}, α → Vec n → Vec (nat.succ n) constant f {α : Type u} {n : nat} : Vec α n → nat axiom fax1 (α : Type u) : f (Vec.nil α) = 0 axiom fax2 {α : Type u} {n : nat} (v : Vec α (nat.succ n)) : f v = 1 open tactic meta def pp_state_core : tactic format := do t ← target, t_fmt ← pp t, return $ to_fmt "Goal: " ++ t_fmt meta def pp_state (s : tactic_state) : format := match pp_state_core s with | result.success r _ := r | result.exception _ _ _ := "failed to pretty print" end meta instance i2 : has_to_format tactic_state := ⟨λ s, to_fmt "My custom goal visualizer" ++ format.line ++ pp_state s⟩ example {α : Type u} {n : nat} (v : Vec α n) : f v ≠ 2 := begin destruct v, intros, intro, have h := fax1 α, cc, -- intros n1 h t, intros, intro, have h := fax2 (Vec.cons h t), cc end open nat example : ∀ n, 0 < n → succ (pred n) = n := begin intro n, destruct n, dsimp, intros, have h := lt_irrefl 0, cc, end
ad1c60c344b2ae1882ffe0c97b7fdf2cf1128a93
1a2aed113dcb5f1c07ae98040953fba5e6563624
/lean_root/src/graveyard.lean
ca5390572bc8f92033eda680cf351f08e4416e95
[ "Apache-2.0" ]
permissive
kevindoran/lean
61d9fb90363b04587624036136482b29e3c16ebd
77e755095a31e3a214010eb48a61e48d65dfdec9
refs/heads/master
1,670,372,072,769
1,598,920,365,000
1,598,920,365,000
264,824,992
0
0
null
null
null
null
UTF-8
Lean
false
false
2,549
lean
namespace graveyard lemma closure_squeeze_term(X Y : set ℝ) (h₁ : X ⊆ Y) (h₂ : Y ⊆ closure(X)) : closure(X) = closure(Y) := -- Can either use set.eq_of_subset_of_subset or set.ext. The difference -- being whether we are showing that two sets are subsets of each other or -- whether we are showing that an object is an element of set X iff it is an -- element of Y. Both are equivalent, but we need to choose which to use. set.eq_of_subset_of_subset (assume x, assume h₃ : x ∈ closure(X), show x ∈ closure(Y), from begin intro ε, intro h₄, have h₅ : ∃ x' ∈ X, |x - x'| ≤ ε, from h₃ ε h₄, show ∃ y ∈ Y, |x - y| ≤ ε, from exists.elim h₅ ( assume (x' : ℝ) (h: (∃hh₁ : (x' ∈ X), |x - x'| ≤ ε)), exists.elim h ( assume (hhh₁ : x' ∈ X) (hhh₂ : |x - x'| ≤ ε), have hhh₃ : x' ∈ Y, from h₁ hhh₁, show ∃y ∈ Y, |x - y| ≤ ε, from exists.intro x' (exists.intro hhh₃ hhh₂))), end) (assume y, assume h₃ : y ∈ closure(Y), show y ∈ closure(X), from assume ε, assume h₄, have h₅ : ∃δ : ℝ, δ = ε/3, from exists_eq, have h₆ : ∃x ∈ X, |y - x| ≤ ε, from exists.elim h₅ (assume (δ : ℝ) (hh₁ : δ = ε/3), have hh₃ : δ > 0, by linarith, have hh₂ : ∃ y' ∈ Y, |y - y'| ≤ δ, from h₃ δ hh₃, exists.elim hh₂ (assume (y' : ℝ) (hh₄ : ∃ hhh₁ : y' ∈ Y, | y - y'| ≤ δ), exists.elim hh₄ (assume (h4₁ : y' ∈ Y) (h4₂ : |y - y'| ≤ δ), have h4₃ : y' ∈ closure(X), from h₂ h4₁, have h4₄ : ∃x ∈ X, |y' - x| ≤ δ, from h4₃ δ hh₃, exists.elim h4₄ (assume (x : ℝ) (h4₅ : ∃ h5₁ : x ∈ X, |y' - x| ≤ δ), exists.elim h4₅ (assume (h5₁ : x ∈ X) (h5₂ : |y' - x| ≤ δ), --norm_add_le_of_le (by apply_instance) h4₂ h5₂ have h5₇ : |y - x| ≤ 2*δ, from sorry, have h5₈ : |y - x| ≤ ε, by linarith, have h5₉ : ∃x' ∈ X, |y - x'| ≤ ε, from exists.intro x (exists.intro h5₁ h5₈), h5₉))))), h₆) end graveyard