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
af9f6264157e75e475d77260ddc1fb85397811e5
f3849be5d845a1cb97680f0bbbe03b85518312f0
/library/tools/super/prover_state.lean
380c1b1690a94a2e6e427928bbd3eae34feca846
[ "Apache-2.0" ]
permissive
bjoeris/lean
0ed95125d762b17bfcb54dad1f9721f953f92eeb
4e496b78d5e73545fa4f9a807155113d8e6b0561
refs/heads/master
1,611,251,218,281
1,495,337,658,000
1,495,337,658,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,528
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause .lpo .cdcl_solver open tactic functor monad expr namespace super structure score := (priority : ℕ) (in_sos : bool) (cost : ℕ) (age : ℕ) namespace score def prio.immediate : ℕ := 0 def prio.default : ℕ := 1 def prio.never : ℕ := 2 def sched_default (sc : score) : score := { sc with priority := prio.default } def sched_now (sc : score) : score := { sc with priority := prio.immediate } def inc_cost (sc : score) (n : ℕ) : score := { sc with cost := sc.cost + n } def min (a b : score) : score := { priority := nat.min a.priority b.priority, in_sos := a.in_sos && b.in_sos, cost := nat.min a.cost b.cost, age := nat.min a.age b.age } def combine (a b : score) : score := { priority := nat.max a.priority b.priority, in_sos := a.in_sos && b.in_sos, cost := a.cost + b.cost, age := nat.max a.age b.age } end score namespace score meta instance : has_to_string score := ⟨λe, "[" ++ to_string e.priority ++ "," ++ to_string e.cost ++ "," ++ to_string e.age ++ ",sos=" ++ to_string e.in_sos ++ "]"⟩ end score def clause_id := ℕ namespace clause_id def to_nat (id : clause_id) : ℕ := id instance : decidable_eq clause_id := nat.decidable_eq instance : has_ordering clause_id := nat.has_ordering end clause_id meta structure derived_clause := (id : clause_id) (c : clause) (selected : list ℕ) (assertions : list expr) (sc : score) namespace derived_clause meta instance : has_to_tactic_format derived_clause := ⟨λc, do prf_fmt ← pp c.c.proof, c_fmt ← pp c.c, ass_fmt ← pp (c.assertions.map (λa, a.local_type)), return $ to_string c.sc ++ " " ++ prf_fmt ++ " " ++ c_fmt ++ " <- " ++ ass_fmt ++ " (selected: " ++ to_fmt c.selected ++ ")" ⟩ meta def clause_with_assertions (ac : derived_clause) : clause := ac.c.close_constn ac.assertions meta def update_proof (dc : derived_clause) (p : expr) : derived_clause := { dc with c := { (dc.c) with proof := p } } end derived_clause meta structure locked_clause := (dc : derived_clause) (reasons : list (list expr)) namespace locked_clause meta instance : has_to_tactic_format locked_clause := ⟨λc, do c_fmt ← pp c.dc, reasons_fmt ← pp (c.reasons.map (λr, r.for (λa, a.local_type))), return $ c_fmt ++ " (locked in case of: " ++ reasons_fmt ++ ")" ⟩ end locked_clause meta structure prover_state := (active : rb_map clause_id derived_clause) (passive : rb_map clause_id derived_clause) (newly_derived : list derived_clause) (prec : list expr) (locked : list locked_clause) (local_false : expr) (sat_solver : cdcl.state) (current_model : rb_map expr bool) (sat_hyps : rb_map expr (expr × expr)) (needs_sat_run : bool) (clause_counter : nat) open prover_state private meta def join_with_nl : list format → format := list.foldl (λx y, x ++ format.line ++ y) format.nil private meta def prover_state_tactic_fmt (s : prover_state) : tactic format := do active_fmts ← mapm pp $ rb_map.values s.active, passive_fmts ← mapm pp $ rb_map.values s.passive, new_fmts ← mapm pp s.newly_derived, locked_fmts ← mapm pp s.locked, sat_fmts ← mapm pp s.sat_solver.clauses, sat_model_fmts ← for s.current_model.to_list (λx, if x.2 = tt then pp x.1 else pp `(not %%x.1)), prec_fmts ← mapm pp s.prec, return (join_with_nl ([to_fmt "active:"] ++ ((append (to_fmt " ")) <$> active_fmts) ++ [to_fmt "passive:"] ++ ((append (to_fmt " ")) <$> passive_fmts) ++ [to_fmt "new:"] ++ ((append (to_fmt " ")) <$> new_fmts) ++ [to_fmt "locked:"] ++ ((append (to_fmt " ")) <$> locked_fmts) ++ [to_fmt "sat formulas:"] ++ ((append (to_fmt " ")) <$> sat_fmts) ++ [to_fmt "sat model:"] ++ ((append (to_fmt " ")) <$> sat_model_fmts) ++ [to_fmt "precedence order: " ++ to_fmt prec_fmts])) meta instance : has_to_tactic_format prover_state := ⟨prover_state_tactic_fmt⟩ meta def prover := state_t prover_state tactic namespace prover meta instance : monad prover := state_t.monad _ _ meta instance : has_monad_lift tactic prover := monad.monad_transformer_lift (state_t prover_state) tactic meta instance (α : Type) : has_coe (tactic α) (prover α) := ⟨monad.monad_lift⟩ meta def fail {α β : Type} [has_to_format β] (msg : β) : prover α := tactic.fail msg meta def orelse (A : Type) (p1 p2 : prover A) : prover A := take state, p1 state <|> p2 state meta instance : alternative prover := { prover.monad with failure := λα, fail "failed", orelse := orelse } end prover meta def selection_strategy := derived_clause → prover derived_clause meta def get_active : prover (rb_map clause_id derived_clause) := do state ← state_t.read, return state.active meta def add_active (a : derived_clause) : prover unit := do state ← state_t.read, state_t.write { state with active := state.active.insert a.id a } meta def get_passive : prover (rb_map clause_id derived_clause) := lift passive state_t.read meta def get_precedence : prover (list expr) := do state ← state_t.read, return state.prec meta def get_term_order : prover (expr → expr → bool) := do state ← state_t.read, return $ mk_lpo (name_of_funsym <$> state.prec) private meta def set_precedence (new_prec : list expr) : prover unit := do state ← state_t.read, state_t.write { state with prec := new_prec } meta def register_consts_in_precedence (consts : list expr) := do p ← get_precedence, p_set ← return (rb_map.set_of_list (name_of_funsym <$> p)), new_syms ← return $ list.filter (λc, ¬p_set.contains (name_of_funsym c)) consts, set_precedence (new_syms ++ p) meta def in_sat_solver {A} (cmd : cdcl.solver A) : prover A := do state ← state_t.read, result ← cmd state.sat_solver, state_t.write { state with sat_solver := result.2 }, return result.1 meta def collect_ass_hyps (c : clause) : prover (list expr) := let lcs := contained_lconsts c.proof in do st ← state_t.read, return (do hs ← st.sat_hyps.values, h ← [hs.1, hs.2], guard $ lcs.contains h.local_uniq_name, [h]) meta def get_clause_count : prover ℕ := do s ← state_t.read, return s.clause_counter meta def get_new_cls_id : prover clause_id := do state ← state_t.read, state_t.write { state with clause_counter := state.clause_counter + 1 }, return state.clause_counter meta def mk_derived (c : clause) (sc : score) : prover derived_clause := do ass ← collect_ass_hyps c, id ← get_new_cls_id, return { id := id, c := c, selected := [], assertions := ass, sc := sc } meta def add_inferred (c : derived_clause) : prover unit := do c' ← c.c.normalize, c' ← return { c with c := c' }, register_consts_in_precedence (contained_funsyms c'.c.type).values, state ← state_t.read, state_t.write { state with newly_derived := c' :: state.newly_derived } -- FIXME: what if we've seen the variable before, but with a weaker score? meta def mk_sat_var (v : expr) (suggested_ph : bool) (suggested_ev : score) : prover unit := do st ← state_t.read, if st.sat_hyps.contains v then return () else do hpv ← mk_local_def `h v, hnv ← mk_local_def `hn $ imp v st.local_false, state_t.modify $ λst, { st with sat_hyps := st.sat_hyps.insert v (hpv, hnv) }, in_sat_solver $ cdcl.mk_var_core v suggested_ph, match v with | (pi _ _ _ _) := do c ← clause.of_proof st.local_false hpv, mk_derived c suggested_ev >>= add_inferred | _ := do cp ← clause.of_proof st.local_false hpv, mk_derived cp suggested_ev >>= add_inferred, cn ← clause.of_proof st.local_false hnv, mk_derived cn suggested_ev >>= add_inferred end meta def get_sat_hyp_core (v : expr) (ph : bool) : prover (option expr) := flip monad.lift state_t.read $ λst, match st.sat_hyps.find v with | some (hp, hn) := some $ if ph then hp else hn | none := none end meta def get_sat_hyp (v : expr) (ph : bool) : prover expr := do hyp_opt ← get_sat_hyp_core v ph, match hyp_opt with | some hyp := return hyp | none := fail $ "unknown sat variable: " ++ v.to_string end meta def add_sat_clause (c : clause) (suggested_ev : score) : prover unit := do c ← c.distinct, already_added ← flip monad.lift state_t.read $ λst, decidable.to_bool $ c.type ∈ st.sat_solver.clauses.map (λd, d.type), if already_added then return () else do for c.get_lits $ λl, mk_sat_var l.formula l.is_neg suggested_ev, in_sat_solver $ cdcl.mk_clause c, state_t.modify $ λst, { st with needs_sat_run := tt } meta def sat_eval_lit (v : expr) (pol : bool) : prover bool := do v_st ← flip monad.lift state_t.read $ λst, st.current_model.find v, match v_st with | some ph := return $ if pol then ph else bnot ph | none := return tt end meta def sat_eval_assertion (assertion : expr) : prover bool := do lf ← flip monad.lift state_t.read $ λst, st.local_false, match is_local_not lf assertion.local_type with | some v := sat_eval_lit v ff | none := sat_eval_lit assertion.local_type tt end meta def sat_eval_assertions : list expr → prover bool | (a::ass) := do v_a ← sat_eval_assertion a, if v_a then sat_eval_assertions ass else return ff | [] := return tt private meta def intern_clause (c : derived_clause) : prover derived_clause := do hyp_name ← get_unused_name (mk_simple_name $ "clause_" ++ to_string c.id.to_nat) none, c' ← return $ c.c.close_constn c.assertions, assertv hyp_name c'.type c'.proof, proof' ← get_local hyp_name, type ← infer_type proof', -- FIXME: otherwise "" return $ c.update_proof $ app_of_list proof' c.assertions meta def register_as_passive (c : derived_clause) : prover unit := do c ← intern_clause c, ass_v ← sat_eval_assertions c.assertions, if c.c.num_quants = 0 ∧ c.c.num_lits = 0 then add_sat_clause c.clause_with_assertions c.sc else if ¬ass_v then do state_t.modify $ λst, { st with locked := ⟨c, []⟩ :: st.locked } else do state_t.modify $ λst, { st with passive := st.passive.insert c.id c } meta def remove_passive (id : clause_id) : prover unit := do state ← state_t.read, state_t.write { state with passive := state.passive.erase id } meta def move_locked_to_passive : prover unit := do locked ← flip monad.lift state_t.read (λst, st.locked), new_locked ← flip filter locked (λlc, do reason_vals ← mapm sat_eval_assertions lc.reasons, c_val ← sat_eval_assertions lc.dc.assertions, if reason_vals.for_all (λr, r = ff) ∧ c_val then do state_t.modify $ λst, { st with passive := st.passive.insert lc.dc.id lc.dc }, return ff else return tt ), state_t.modify $ λst, { st with locked := new_locked } meta def move_active_to_locked : prover unit := do active ← get_active, for' active.values $ λac, do c_val ← sat_eval_assertions ac.assertions, if ¬c_val then do state_t.modify $ λst, { st with active := st.active.erase ac.id, locked := ⟨ac, []⟩ :: st.locked } else return () meta def move_passive_to_locked : prover unit := do passive ← flip monad.lift state_t.read $ λst, st.passive, for' passive.to_list $ λpc, do c_val ← sat_eval_assertions pc.2.assertions, if ¬c_val then do state_t.modify $ λst, { st with passive := st.passive.erase pc.1, locked := ⟨pc.2, []⟩ :: st.locked } else return () def super_cc_config : cc_config := { em := ff } meta def do_sat_run : prover (option expr) := do sat_result ← in_sat_solver $ cdcl.run (cdcl.theory_solver_of_tactic $ using_smt $ return ()), state_t.modify $ λst, { st with needs_sat_run := ff }, old_model ← lift prover_state.current_model state_t.read, match sat_result with | (cdcl.result.unsat proof) := return (some proof) | (cdcl.result.sat new_model) := do state_t.modify $ λst, { st with current_model := new_model }, move_locked_to_passive, move_active_to_locked, move_passive_to_locked, return none end meta def take_newly_derived : prover (list derived_clause) := do state ← state_t.read, state_t.write { state with newly_derived := [] }, return state.newly_derived meta def remove_redundant (id : clause_id) (parents : list derived_clause) : prover unit := do when (not $ parents.for_all $ λp, p.id ≠ id) (fail "clause is redundant because of itself"), red ← flip monad.lift state_t.read (λst, st.active.find id), match red with | none := return () | some red := do let reasons := parents.map (λp, p.assertions), let assertion := red.assertions, if reasons.for_all $ λr, r.subset_of assertion then do state_t.modify $ λst, { st with active := st.active.erase id } else do state_t.modify $ λst, { st with active := st.active.erase id, locked := ⟨red, reasons⟩ :: st.locked } end meta def inference := derived_clause → prover unit meta structure inf_decl := (prio : ℕ) (inf : inference) @[user_attribute] meta def inf_attr : user_attribute := ⟨ `super.inf, "inference for the super prover" ⟩ meta def seq_inferences : list inference → inference | [] := λgiven, return () | (inf::infs) := λgiven, do inf given, now_active ← get_active, if rb_map.contains now_active given.id then seq_inferences infs given else return () meta def simp_inference (simpl : derived_clause → prover (option clause)) : inference := λgiven, do maybe_simpld ← simpl given, match maybe_simpld with | some simpld := do derived_simpld ← mk_derived simpld given.sc.sched_now, add_inferred derived_simpld, remove_redundant given.id [] | none := return () end meta def preprocessing_rule (f : list derived_clause → prover (list derived_clause)) : prover unit := do state ← state_t.read, newly_derived' ← f state.newly_derived, state' ← state_t.read, state_t.write { state' with newly_derived := newly_derived' } meta def clause_selection_strategy := ℕ → prover clause_id namespace prover_state meta def empty (local_false : expr) : prover_state := { active := rb_map.mk _ _, passive := rb_map.mk _ _, newly_derived := [], prec := [], clause_counter := 0, local_false := local_false, locked := [], sat_solver := cdcl.state.initial local_false, current_model := rb_map.mk _ _, sat_hyps := rb_map.mk _ _, needs_sat_run := ff } meta def initial (local_false : expr) (clauses : list clause) : tactic prover_state := do after_setup ← for' clauses (λc, let in_sos := ((contained_lconsts c.proof).erase local_false.local_uniq_name).size = 0 in do mk_derived c { priority := score.prio.immediate, in_sos := in_sos, age := 0, cost := 0 } >>= add_inferred ) $ empty local_false, return after_setup.2 end prover_state meta def inf_score (add_cost : ℕ) (scores : list score) : prover score := do age ← get_clause_count, return $ list.foldl score.combine { priority := score.prio.default, in_sos := tt, age := age, cost := add_cost } scores meta def inf_if_successful (add_cost : ℕ) (parent : derived_clause) (tac : tactic (list clause)) : prover unit := (do inferred ← tac, for' inferred $ λc, inf_score add_cost [parent.sc] >>= mk_derived c >>= add_inferred) <|> return () meta def simp_if_successful (parent : derived_clause) (tac : tactic (list clause)) : prover unit := (do inferred ← tac, for' inferred $ λc, mk_derived c parent.sc.sched_now >>= add_inferred, remove_redundant parent.id []) <|> return () end super
cf5f5b958cd845923a798691f32dd4ee538455e2
82e44445c70db0f03e30d7be725775f122d72f3e
/src/algebra/euclidean_domain.lean
e7274a176448d892a15c96724bc7f25949779134
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
17,179
lean
/- Copyright (c) 2018 Louis Carlin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Louis Carlin, Mario Carneiro -/ import data.int.basic import algebra.field /-! # Euclidean domains This file introduces Euclidean domains and provides the extended Euclidean algorithm. To be precise, a slightly more general version is provided which is sometimes called a transfinite Euclidean domain and differs in the fact that the degree function need not take values in `ℕ` but can take values in any well-ordered set. Transfinite Euclidean domains were introduced by Motzkin and examples which don't satisfy the classical notion were provided independently by Hiblot and Nagata. ## Main definitions * `euclidean_domain`: Defines Euclidean domain with functions `quotient` and `remainder`. Instances of `has_div` and `has_mod` are provided, so that one can write `a = b * (a / b) + a % b`. * `gcd`: defines the greatest common divisors of two elements of a Euclidean domain. * `xgcd`: given two elements `a b : R`, `xgcd a b` defines the pair `(x, y)` such that `x * a + y * b = gcd a b`. * `lcm`: defines the lowest common multiple of two elements `a` and `b` of a Euclidean domain as `a * b / (gcd a b)` ## Main statements * `gcd_eq_gcd_ab`: states Bézout's lemma for Euclidean domains. * `int.euclidean_domain`: shows that `ℤ` is a Euclidean domain. * `field.to_euclidean_domain`: shows that any field is a Euclidean domain. ## Notation `≺` denotes the well founded relation on the Euclidean domain, e.g. in the example of the polynomial ring over a field, `p ≺ q` for polynomials `p` and `q` if and only if the degree of `p` is less than the degree of `q`. ## Implementation details Instead of working with a valuation, `euclidean_domain` is implemented with the existence of a well founded relation `r` on the integral domain `R`, which in the example of `ℤ` would correspond to setting `i ≺ j` for integers `i` and `j` if the absolute value of `i` is smaller than the absolute value of `j`. ## References * [Th. Motzkin, *The Euclidean algorithm*][MR32592] * [J.-J. Hiblot, *Des anneaux euclidiens dont le plus petit algorithme n'est pas à valeurs finies*] [MR399081] * [M. Nagata, *On Euclid algorithm*][MR541021] ## Tags Euclidean domain, transfinite Euclidean domain, Bézout's lemma -/ universe u section old_structure_cmd set_option old_structure_cmd true /-- A `euclidean_domain` is an `integral_domain` with a division and a remainder, satisfying `b * (a / b) + a % b = a`. The definition of a euclidean domain usually includes a valuation function `R → ℕ`. This definition is slightly generalised to include a well founded relation `r` with the property that `r (a % b) b`, instead of a valuation. -/ @[protect_proj without mul_left_not_lt r_well_founded] class euclidean_domain (R : Type u) extends comm_ring R, nontrivial R := (quotient : R → R → R) (quotient_zero : ∀ a, quotient a 0 = 0) (remainder : R → R → R) (quotient_mul_add_remainder_eq : ∀ a b, b * quotient a b + remainder a b = a) (r : R → R → Prop) (r_well_founded : well_founded r) (remainder_lt : ∀ a {b}, b ≠ 0 → r (remainder a b) b) (mul_left_not_lt : ∀ a {b}, b ≠ 0 → ¬r (a * b) a) end old_structure_cmd namespace euclidean_domain variable {R : Type u} variables [euclidean_domain R] local infix ` ≺ `:50 := euclidean_domain.r @[priority 70] -- see Note [lower instance priority] instance : has_div R := ⟨euclidean_domain.quotient⟩ @[priority 70] -- see Note [lower instance priority] instance : has_mod R := ⟨euclidean_domain.remainder⟩ theorem div_add_mod (a b : R) : b * (a / b) + a % b = a := euclidean_domain.quotient_mul_add_remainder_eq _ _ lemma mod_add_div (a b : R) : a % b + b * (a / b) = a := (add_comm _ _).trans (div_add_mod _ _) lemma mod_add_div' (m k : R) : m % k + (m / k) * k = m := by { rw mul_comm, exact mod_add_div _ _ } lemma div_add_mod' (m k : R) : (m / k) * k + m % k = m := by { rw mul_comm, exact div_add_mod _ _ } lemma mod_eq_sub_mul_div {R : Type*} [euclidean_domain R] (a b : R) : a % b = a - b * (a / b) := calc a % b = b * (a / b) + a % b - b * (a / b) : (add_sub_cancel' _ _).symm ... = a - b * (a / b) : by rw div_add_mod theorem mod_lt : ∀ a {b : R}, b ≠ 0 → (a % b) ≺ b := euclidean_domain.remainder_lt theorem mul_right_not_lt {a : R} (b) (h : a ≠ 0) : ¬(a * b) ≺ b := by rw mul_comm; exact mul_left_not_lt b h lemma mul_div_cancel_left {a : R} (b) (a0 : a ≠ 0) : a * b / a = b := eq.symm $ eq_of_sub_eq_zero $ classical.by_contradiction $ λ h, begin have := mul_left_not_lt a h, rw [mul_sub, sub_eq_iff_eq_add'.2 (div_add_mod (a*b) a).symm] at this, exact this (mod_lt _ a0) end lemma mul_div_cancel (a) {b : R} (b0 : b ≠ 0) : a * b / b = a := by rw mul_comm; exact mul_div_cancel_left a b0 @[simp] lemma mod_zero (a : R) : a % 0 = a := by simpa only [zero_mul, zero_add] using div_add_mod a 0 @[simp] lemma mod_eq_zero {a b : R} : a % b = 0 ↔ b ∣ a := ⟨λ h, by rw [← div_add_mod a b, h, add_zero]; exact dvd_mul_right _ _, λ ⟨c, e⟩, begin rw [e, ← add_left_cancel_iff, div_add_mod, add_zero], haveI := classical.dec, by_cases b0 : b = 0, { simp only [b0, zero_mul] }, { rw [mul_div_cancel_left _ b0] } end⟩ @[simp] lemma mod_self (a : R) : a % a = 0 := mod_eq_zero.2 (dvd_refl _) lemma dvd_mod_iff {a b c : R} (h : c ∣ b) : c ∣ a % b ↔ c ∣ a := by rw [dvd_add_iff_right (dvd_mul_of_dvd_left h _), div_add_mod] lemma lt_one (a : R) : a ≺ (1:R) → a = 0 := by haveI := classical.dec; exact not_imp_not.1 (λ h, by simpa only [one_mul] using mul_left_not_lt 1 h) lemma val_dvd_le : ∀ a b : R, b ∣ a → a ≠ 0 → ¬a ≺ b | _ b ⟨d, rfl⟩ ha := mul_left_not_lt b (mt (by rintro rfl; exact mul_zero _) ha) @[simp] lemma mod_one (a : R) : a % 1 = 0 := mod_eq_zero.2 (one_dvd _) @[simp] lemma zero_mod (b : R) : 0 % b = 0 := mod_eq_zero.2 (dvd_zero _) @[simp, priority 900] lemma div_zero (a : R) : a / 0 = 0 := euclidean_domain.quotient_zero a @[simp, priority 900] lemma zero_div {a : R} : 0 / a = 0 := classical.by_cases (λ a0 : a = 0, a0.symm ▸ div_zero 0) (λ a0, by simpa only [zero_mul] using mul_div_cancel 0 a0) @[simp, priority 900] lemma div_self {a : R} (a0 : a ≠ 0) : a / a = 1 := by simpa only [one_mul] using mul_div_cancel 1 a0 lemma eq_div_of_mul_eq_left {a b c : R} (hb : b ≠ 0) (h : a * b = c) : a = c / b := by rw [← h, mul_div_cancel _ hb] lemma eq_div_of_mul_eq_right {a b c : R} (ha : a ≠ 0) (h : a * b = c) : b = c / a := by rw [← h, mul_div_cancel_left _ ha] theorem mul_div_assoc (x : R) {y z : R} (h : z ∣ y) : x * y / z = x * (y / z) := begin classical, by_cases hz : z = 0, { subst hz, rw [div_zero, div_zero, mul_zero] }, rcases h with ⟨p, rfl⟩, rw [mul_div_cancel_left _ hz, mul_left_comm, mul_div_cancel_left _ hz] end section open_locale classical @[elab_as_eliminator] theorem gcd.induction {P : R → R → Prop} : ∀ a b : R, (∀ x, P 0 x) → (∀ a b, a ≠ 0 → P (b % a) a → P a b) → P a b | a := λ b H0 H1, if a0 : a = 0 then by rw [a0]; apply H0 else have h:_ := mod_lt b a0, H1 _ _ a0 (gcd.induction (b%a) a H0 H1) using_well_founded {dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨_, r_well_founded⟩]} end section gcd variable [decidable_eq R] /-- `gcd a b` is a (non-unique) element such that `gcd a b ∣ a` `gcd a b ∣ b`, and for any element `c` such that `c ∣ a` and `c ∣ b`, then `c ∣ gcd a b` -/ def gcd : R → R → R | a := λ b, if a0 : a = 0 then b else have h:_ := mod_lt b a0, gcd (b%a) a using_well_founded {dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨_, r_well_founded⟩]} @[simp] theorem gcd_zero_left (a : R) : gcd 0 a = a := by rw gcd; exact if_pos rfl @[simp] theorem gcd_zero_right (a : R) : gcd a 0 = a := by rw gcd; split_ifs; simp only [h, zero_mod, gcd_zero_left] theorem gcd_val (a b : R) : gcd a b = gcd (b % a) a := by rw gcd; split_ifs; [simp only [h, mod_zero, gcd_zero_right], refl] theorem gcd_dvd (a b : R) : gcd a b ∣ a ∧ gcd a b ∣ b := gcd.induction a b (λ b, by rw [gcd_zero_left]; exact ⟨dvd_zero _, dvd_refl _⟩) (λ a b aneq ⟨IH₁, IH₂⟩, by rw gcd_val; exact ⟨IH₂, (dvd_mod_iff IH₂).1 IH₁⟩) theorem gcd_dvd_left (a b : R) : gcd a b ∣ a := (gcd_dvd a b).left theorem gcd_dvd_right (a b : R) : gcd a b ∣ b := (gcd_dvd a b).right protected theorem gcd_eq_zero_iff {a b : R} : gcd a b = 0 ↔ a = 0 ∧ b = 0 := ⟨λ h, by simpa [h] using gcd_dvd a b, by rintro ⟨rfl, rfl⟩; simp⟩ theorem dvd_gcd {a b c : R} : c ∣ a → c ∣ b → c ∣ gcd a b := gcd.induction a b (λ _ _ H, by simpa only [gcd_zero_left] using H) (λ a b a0 IH ca cb, by rw gcd_val; exact IH ((dvd_mod_iff ca).2 cb) ca) theorem gcd_eq_left {a b : R} : gcd a b = a ↔ a ∣ b := ⟨λ h, by rw ← h; apply gcd_dvd_right, λ h, by rw [gcd_val, mod_eq_zero.2 h, gcd_zero_left]⟩ @[simp] theorem gcd_one_left (a : R) : gcd 1 a = 1 := gcd_eq_left.2 (one_dvd _) @[simp] theorem gcd_self (a : R) : gcd a a = a := gcd_eq_left.2 (dvd_refl _) /-- An implementation of the extended GCD algorithm. At each step we are computing a triple `(r, s, t)`, where `r` is the next value of the GCD algorithm, to compute the greatest common divisor of the input (say `x` and `y`), and `s` and `t` are the coefficients in front of `x` and `y` to obtain `r` (i.e. `r = s * x + t * y`). The function `xgcd_aux` takes in two triples, and from these recursively computes the next triple: ``` xgcd_aux (r, s, t) (r', s', t') = xgcd_aux (r' % r, s' - (r' / r) * s, t' - (r' / r) * t) (r, s, t) ``` -/ def xgcd_aux : R → R → R → R → R → R → R × R × R | r := λ s t r' s' t', if hr : r = 0 then (r', s', t') else have r' % r ≺ r, from mod_lt _ hr, let q := r' / r in xgcd_aux (r' % r) (s' - q * s) (t' - q * t) r s t using_well_founded {dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨_, r_well_founded⟩]} @[simp] theorem xgcd_zero_left {s t r' s' t' : R} : xgcd_aux 0 s t r' s' t' = (r', s', t') := by unfold xgcd_aux; exact if_pos rfl theorem xgcd_aux_rec {r s t r' s' t' : R} (h : r ≠ 0) : xgcd_aux r s t r' s' t' = xgcd_aux (r' % r) (s' - (r' / r) * s) (t' - (r' / r) * t) r s t := by conv {to_lhs, rw [xgcd_aux]}; exact if_neg h /-- Use the extended GCD algorithm to generate the `a` and `b` values satisfying `gcd x y = x * a + y * b`. -/ def xgcd (x y : R) : R × R := (xgcd_aux x 1 0 y 0 1).2 /-- The extended GCD `a` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_a (x y : R) : R := (xgcd x y).1 /-- The extended GCD `b` value in the equation `gcd x y = x * a + y * b`. -/ def gcd_b (x y : R) : R := (xgcd x y).2 @[simp] theorem gcd_a_zero_left {s : R} : gcd_a 0 s = 0 := by { unfold gcd_a, rw [xgcd, xgcd_zero_left] } @[simp] theorem gcd_b_zero_left {s : R} : gcd_b 0 s = 1 := by { unfold gcd_b, rw [xgcd, xgcd_zero_left] } @[simp] theorem xgcd_aux_fst (x y : R) : ∀ s t s' t', (xgcd_aux x s t y s' t').1 = gcd x y := gcd.induction x y (by intros; rw [xgcd_zero_left, gcd_zero_left]) (λ x y h IH s t s' t', by simp only [xgcd_aux_rec h, if_neg h, IH]; rw ← gcd_val) theorem xgcd_aux_val (x y : R) : xgcd_aux x 1 0 y 0 1 = (gcd x y, xgcd x y) := by rw [xgcd, ← xgcd_aux_fst x y 1 0 0 1, prod.mk.eta] theorem xgcd_val (x y : R) : xgcd x y = (gcd_a x y, gcd_b x y) := prod.mk.eta.symm private def P (a b : R) : R × R × R → Prop | (r, s, t) := (r : R) = a * s + b * t theorem xgcd_aux_P (a b : R) {r r' : R} : ∀ {s t s' t'}, P a b (r, s, t) → P a b (r', s', t') → P a b (xgcd_aux r s t r' s' t') := gcd.induction r r' (by intros; simpa only [xgcd_zero_left]) $ λ x y h IH s t s' t' p p', begin rw [xgcd_aux_rec h], refine IH _ p, unfold P at p p' ⊢, rw [mul_sub, mul_sub, add_sub, sub_add_eq_add_sub, ← p', sub_sub, mul_comm _ s, ← mul_assoc, mul_comm _ t, ← mul_assoc, ← add_mul, ← p, mod_eq_sub_mul_div] end /-- An explicit version of **Bézout's lemma** for Euclidean domains. -/ theorem gcd_eq_gcd_ab (a b : R) : (gcd a b : R) = a * gcd_a a b + b * gcd_b a b := by have := @xgcd_aux_P _ _ _ a b a b 1 0 0 1 (by rw [P, mul_one, mul_zero, add_zero]) (by rw [P, mul_one, mul_zero, zero_add]); rwa [xgcd_aux_val, xgcd_val] at this @[priority 70] -- see Note [lower instance priority] instance (R : Type*) [e : euclidean_domain R] : integral_domain R := by haveI := classical.dec_eq R; exact { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, (or_iff_not_and_not.2 $ λ h0, h0.1 $ by rw [← mul_div_cancel a h0.2, h, zero_div]), zero := 0, add := (+), mul := (*), ..e } end gcd section lcm variables [decidable_eq R] /-- `lcm a b` is a (non-unique) element such that `a ∣ lcm a b` `b ∣ lcm a b`, and for any element `c` such that `a ∣ c` and `b ∣ c`, then `lcm a b ∣ c` -/ def lcm (x y : R) : R := x * y / gcd x y theorem dvd_lcm_left (x y : R) : x ∣ lcm x y := classical.by_cases (assume hxy : gcd x y = 0, by rw [lcm, hxy, div_zero]; exact dvd_zero _) (λ hxy, let ⟨z, hz⟩ := (gcd_dvd x y).2 in ⟨z, eq.symm $ eq_div_of_mul_eq_left hxy $ by rw [mul_right_comm, mul_assoc, ← hz]⟩) theorem dvd_lcm_right (x y : R) : y ∣ lcm x y := classical.by_cases (assume hxy : gcd x y = 0, by rw [lcm, hxy, div_zero]; exact dvd_zero _) (λ hxy, let ⟨z, hz⟩ := (gcd_dvd x y).1 in ⟨z, eq.symm $ eq_div_of_mul_eq_right hxy $ by rw [← mul_assoc, mul_right_comm, ← hz]⟩) theorem lcm_dvd {x y z : R} (hxz : x ∣ z) (hyz : y ∣ z) : lcm x y ∣ z := begin rw lcm, by_cases hxy : gcd x y = 0, { rw [hxy, div_zero], rw euclidean_domain.gcd_eq_zero_iff at hxy, rwa hxy.1 at hxz }, rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩, suffices : x * y ∣ z * gcd x y, { cases this with p hp, use p, generalize_hyp : gcd x y = g at hxy hs hp ⊢, subst hs, rw [mul_left_comm, mul_div_cancel_left _ hxy, ← mul_left_inj' hxy, hp], rw [← mul_assoc], simp only [mul_right_comm] }, rw [gcd_eq_gcd_ab, mul_add], apply dvd_add, { rw mul_left_comm, exact mul_dvd_mul_left _ (dvd_mul_of_dvd_left hyz _) }, { rw [mul_left_comm, mul_comm], exact mul_dvd_mul_left _ (dvd_mul_of_dvd_left hxz _) } end @[simp] lemma lcm_dvd_iff {x y z : R} : lcm x y ∣ z ↔ x ∣ z ∧ y ∣ z := ⟨λ hz, ⟨dvd_trans (dvd_lcm_left _ _) hz, dvd_trans (dvd_lcm_right _ _) hz⟩, λ ⟨hxz, hyz⟩, lcm_dvd hxz hyz⟩ @[simp] lemma lcm_zero_left (x : R) : lcm 0 x = 0 := by rw [lcm, zero_mul, zero_div] @[simp] lemma lcm_zero_right (x : R) : lcm x 0 = 0 := by rw [lcm, mul_zero, zero_div] @[simp] lemma lcm_eq_zero_iff {x y : R} : lcm x y = 0 ↔ x = 0 ∨ y = 0 := begin split, { intro hxy, rw [lcm, mul_div_assoc _ (gcd_dvd_right _ _), mul_eq_zero] at hxy, apply or_of_or_of_imp_right hxy, intro hy, by_cases hgxy : gcd x y = 0, { rw euclidean_domain.gcd_eq_zero_iff at hgxy, exact hgxy.2 }, { rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩, generalize_hyp : gcd x y = g at hr hs hy hgxy ⊢, subst hs, rw [mul_div_cancel_left _ hgxy] at hy, rw [hy, mul_zero] } }, rintro (hx | hy), { rw [hx, lcm_zero_left] }, { rw [hy, lcm_zero_right] } end @[simp] lemma gcd_mul_lcm (x y : R) : gcd x y * lcm x y = x * y := begin rw lcm, by_cases h : gcd x y = 0, { rw [h, zero_mul], rw euclidean_domain.gcd_eq_zero_iff at h, rw [h.1, zero_mul] }, rcases gcd_dvd x y with ⟨⟨r, hr⟩, ⟨s, hs⟩⟩, generalize_hyp : gcd x y = g at h hr ⊢, subst hr, rw [mul_assoc, mul_div_cancel_left _ h] end end lcm end euclidean_domain instance int.euclidean_domain : euclidean_domain ℤ := { add := (+), mul := (*), one := 1, zero := 0, neg := has_neg.neg, quotient := (/), quotient_zero := int.div_zero, remainder := (%), quotient_mul_add_remainder_eq := λ a b, int.div_add_mod _ _, r := λ a b, a.nat_abs < b.nat_abs, r_well_founded := measure_wf (λ a, int.nat_abs a), remainder_lt := λ a b b0, int.coe_nat_lt.1 $ by rw [int.nat_abs_of_nonneg (int.mod_nonneg _ b0), ← int.abs_eq_nat_abs]; exact int.mod_lt _ b0, mul_left_not_lt := λ a b b0, not_lt_of_ge $ by rw [← mul_one a.nat_abs, int.nat_abs_mul]; exact mul_le_mul_of_nonneg_left (int.nat_abs_pos_of_ne_zero b0) (nat.zero_le _), .. int.comm_ring, .. int.nontrivial } @[priority 100] -- see Note [lower instance priority] instance field.to_euclidean_domain {K : Type u} [field K] : euclidean_domain K := { add := (+), mul := (*), one := 1, zero := 0, neg := has_neg.neg, quotient := (/), remainder := λ a b, a - a * b / b, quotient_zero := div_zero, quotient_mul_add_remainder_eq := λ a b, by classical; by_cases b = 0; simp [h, mul_div_cancel'], r := λ a b, a = 0 ∧ b ≠ 0, r_well_founded := well_founded.intro $ λ a, acc.intro _ $ λ b ⟨hb, hna⟩, acc.intro _ $ λ c ⟨hc, hnb⟩, false.elim $ hnb hb, remainder_lt := λ a b hnb, by simp [hnb], mul_left_not_lt := λ a b hnb ⟨hab, hna⟩, or.cases_on (mul_eq_zero.1 hab) hna hnb, .. ‹field K› }
e25b2beed17fb13abbac786e46d6658343dd19ba
4727251e0cd73359b15b664c3170e5d754078599
/src/data/polynomial/div.lean
d00f41b8ff3987dff80c7c387d1960f46055656e
[ "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
21,078
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Scott Morrison, Jens Wagemaker -/ import data.polynomial.inductions import data.polynomial.monic import ring_theory.multiplicity /-! # Division of univariate polynomials The main defs are `div_by_monic` and `mod_by_monic`. The compatibility between these is given by `mod_by_monic_add_div`. We also define `root_multiplicity`. -/ noncomputable theory open_locale classical big_operators polynomial open finset namespace polynomial universes u v w z variables {R : Type u} {S : Type v} {T : Type w} {A : Type z} {a b : R} {n : ℕ} section comm_semiring variables [comm_semiring R] theorem X_dvd_iff {α : Type u} [comm_semiring α] {f : α[X]} : X ∣ f ↔ f.coeff 0 = 0 := ⟨λ ⟨g, hfg⟩, by rw [hfg, mul_comm, coeff_mul_X_zero], λ hf, ⟨f.div_X, by rw [mul_comm, ← add_zero (f.div_X * X), ← C_0, ← hf, div_X_mul_X_add]⟩⟩ end comm_semiring section comm_semiring variables [comm_semiring R] {p q : R[X]} lemma multiplicity_finite_of_degree_pos_of_monic (hp : (0 : with_bot ℕ) < degree p) (hmp : monic p) (hq : q ≠ 0) : multiplicity.finite p q := have zn0 : (0 : R) ≠ 1, by haveI := nontrivial.of_polynomial_ne hq; exact zero_ne_one, ⟨nat_degree q, λ ⟨r, hr⟩, have hp0 : p ≠ 0, from λ hp0, by simp [hp0] at hp; contradiction, have hr0 : r ≠ 0, from λ hr0, by simp * at *, have hpn1 : leading_coeff p ^ (nat_degree q + 1) = 1, by simp [show _ = _, from hmp], have hpn0' : leading_coeff p ^ (nat_degree q + 1) ≠ 0, from hpn1.symm ▸ zn0.symm, have hpnr0 : leading_coeff (p ^ (nat_degree q + 1)) * leading_coeff r ≠ 0, by simp only [leading_coeff_pow' hpn0', leading_coeff_eq_zero, hpn1, one_pow, one_mul, ne.def, hr0]; simp, have hnp : 0 < nat_degree p, by rw [← with_bot.coe_lt_coe, ← degree_eq_nat_degree hp0]; exact hp, begin have := congr_arg nat_degree hr, rw [nat_degree_mul' hpnr0, nat_degree_pow' hpn0', add_mul, add_assoc] at this, exact ne_of_lt (lt_add_of_le_of_pos (le_mul_of_one_le_right (nat.zero_le _) hnp) (add_pos_of_pos_of_nonneg (by rwa one_mul) (nat.zero_le _))) this end⟩ end comm_semiring section ring variables [ring R] {p q : R[X]} lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) : degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, have hq0 : q ≠ 0 := hq.ne_zero_of_polynomial_ne h.2, have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1 (by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0]; exact h.1), degree_sub_lt (by rw [hq.degree_mul, degree_C_mul_X_pow _ hp, degree_eq_nat_degree h.2, degree_eq_nat_degree hq0, ← with_bot.coe_add, tsub_add_cancel_of_le hlt]) h.2 (by rw [leading_coeff_mul_monic hq, leading_coeff_mul_X_pow, leading_coeff_C]) /-- See `div_by_monic`. -/ noncomputable def div_mod_by_monic_aux : Π (p : R[X]) {q : R[X]}, monic q → R[X] × R[X] | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in have wf : _ := div_wf_lemma h hq, let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else ⟨0, p⟩ using_well_founded {dec_tac := tactic.assumption} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : R[X]) : R[X] := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/ def mod_by_monic (p q : R[X]) : R[X] := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p infixl ` /ₘ ` : 70 := div_by_monic infixl ` %ₘ ` : 70 := mod_by_monic lemma degree_mod_by_monic_lt [nontrivial R] : ∀ (p : R[X]) {q : R[X]} (hq : monic q), degree (p %ₘ q) < degree q | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq, have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q := degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else or.cases_on (not_and_distrib.1 h) begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h], exact lt_of_not_ge, end begin assume hp, unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, not_not.1 hp], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 hq.ne_zero)), end using_well_founded {dec_tac := tactic.assumption} @[simp] lemma zero_mod_by_monic (p : R[X]) : 0 %ₘ p = 0 := begin unfold mod_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma zero_div_by_monic (p : R[X]) : 0 /ₘ p = 0 := begin unfold div_by_monic div_mod_by_monic_aux, by_cases hp : monic p, { rw [dif_pos hp, if_neg (mt and.right (not_not_intro rfl))] }, { rw [dif_neg hp] } end @[simp] lemma mod_by_monic_zero (p : R[X]) : p %ₘ 0 = p := if h : monic (0 : R[X]) then (subsingleton_of_monic_zero h).1 _ _ else by unfold mod_by_monic div_mod_by_monic_aux; rw dif_neg h @[simp] lemma div_by_monic_zero (p : R[X]) : p /ₘ 0 = 0 := if h : monic (0 : R[X]) then (subsingleton_of_monic_zero h).1 _ _ else by unfold div_by_monic div_mod_by_monic_aux; rw dif_neg h lemma div_by_monic_eq_of_not_monic (p : R[X]) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq lemma mod_by_monic_eq_of_not_monic (p : R[X]) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq lemma mod_by_monic_eq_self_iff [nontrivial R] (hq : monic q) : p %ₘ q = p ↔ degree p < degree q := ⟨λ h, h ▸ degree_mod_by_monic_lt _ hq, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold mod_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ theorem degree_mod_by_monic_le (p : R[X]) {q : R[X]} (hq : monic q) : degree (p %ₘ q) ≤ degree q := by { nontriviality R, exact (degree_mod_by_monic_lt _ hq).le } end ring section comm_ring variables [comm_ring R] {p q : R[X]} lemma mod_by_monic_eq_sub_mul_div : ∀ (p : R[X]) {q : R[X]} (hq : monic q), p %ₘ q = p - q * (p /ₘ q) | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, unfold div_by_monic, rw [dif_pos hq, dif_pos hq, if_pos h, mul_add, sub_add_eq_sub_sub, mul_comm] end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h, mul_zero, sub_zero] end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_add_div (p : R[X]) {q : R[X]} (hq : monic q) : p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) lemma div_by_monic_eq_zero_iff [nontrivial R] (hq : monic q) : p /ₘ q = 0 ↔ degree p < degree q := ⟨λ h, by have := mod_by_monic_add_div p hq; rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq] at this, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold div_by_monic div_mod_by_monic_aux; rw [dif_pos hq, if_neg (mt and.left this)]⟩ lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) : degree q + degree (p /ₘ q) = degree p := begin nontriviality R, have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq, not_lt], have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero], have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) := calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq ... ≤ _ : by rw [degree_mul' hlc, degree_eq_nat_degree hq.ne_zero, degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe]; exact nat.le_add_right _ _, calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul' hlc) ... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_right_of_degree_lt hmod).symm ... = _ : congr_arg _ (mod_by_monic_add_div _ hq) end lemma degree_div_by_monic_le (p q : R[X]) : degree (p /ₘ q) ≤ degree p := if hp0 : p = 0 then by simp only [hp0, zero_div_by_monic, le_refl] else if hq : monic q then if h : degree q ≤ degree p then by haveI := nontrivial.of_polynomial_ne hp0; rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq.ne_zero, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq).1 (not_lt.2 h))]; exact with_bot.coe_le_coe.2 (nat.le_add_left _ _) else by unfold div_by_monic div_mod_by_monic_aux; simp only [dif_pos hq, h, false_and, if_false, degree_zero, bot_le] else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le lemma degree_div_by_monic_lt (p : R[X]) {q : R[X]} (hq : monic q) (hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p := if hpq : degree p < degree q then begin haveI := nontrivial.of_polynomial_ne hp0, rw [(div_by_monic_eq_zero_iff hq).2 hpq, degree_eq_nat_degree hp0], exact with_bot.bot_lt_coe _ end else begin haveI := nontrivial.of_polynomial_ne hp0, rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq.ne_zero, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq).1 hpq)], exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left (with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq.ne_zero) ▸ h0q)) end theorem nat_degree_div_by_monic {R : Type u} [comm_ring R] (f : R[X]) {g : R[X]} (hg : g.monic) : nat_degree (f /ₘ g) = nat_degree f - nat_degree g := begin nontriviality R, by_cases hfg : f /ₘ g = 0, { rw [hfg, nat_degree_zero], rw div_by_monic_eq_zero_iff hg at hfg, rw tsub_eq_zero_iff_le.mpr (nat_degree_le_nat_degree $ le_of_lt hfg) }, have hgf := hfg, rw div_by_monic_eq_zero_iff hg at hgf, push_neg at hgf, have := degree_add_div_by_monic hg hgf, have hf : f ≠ 0, { intro hf, apply hfg, rw [hf, zero_div_by_monic] }, rw [degree_eq_nat_degree hf, degree_eq_nat_degree hg.ne_zero, degree_eq_nat_degree hfg, ← with_bot.coe_add, with_bot.coe_eq_coe] at this, rw [← this, add_tsub_cancel_left] end lemma div_mod_by_monic_unique {f g} (q r : R[X]) (hg : monic g) (h : r + g * q = f ∧ degree r < degree g) : f /ₘ g = q ∧ f %ₘ g = r := begin nontriviality R, have h₁ : r - f %ₘ g = -g * (q - f /ₘ g), from eq_of_sub_eq_zero (by rw [← sub_eq_zero_of_eq (h.1.trans (mod_by_monic_add_div f hg).symm)]; simp [mul_add, mul_comm, sub_eq_add_neg, add_comm, add_left_comm, add_assoc]), have h₂ : degree (r - f %ₘ g) = degree (g * (q - f /ₘ g)), by simp [h₁], have h₄ : degree (r - f %ₘ g) < degree g, from calc degree (r - f %ₘ g) ≤ max (degree r) (degree (f %ₘ g)) : degree_sub_le _ _ ... < degree g : max_lt_iff.2 ⟨h.2, degree_mod_by_monic_lt _ hg⟩, have h₅ : q - (f /ₘ g) = 0, from by_contradiction (λ hqf, not_le_of_gt h₄ $ calc degree g ≤ degree g + degree (q - f /ₘ g) : by erw [degree_eq_nat_degree hg.ne_zero, degree_eq_nat_degree hqf, with_bot.coe_le_coe]; exact nat.le_add_right _ _ ... = degree (r - f %ₘ g) : by rw [h₂, degree_mul']; simpa [monic.def.1 hg]), exact ⟨eq.symm $ eq_of_sub_eq_zero h₅, eq.symm $ eq_of_sub_eq_zero $ by simpa [h₅] using h₁⟩ end lemma map_mod_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f ∧ (p %ₘ q).map f = p.map f %ₘ q.map f := begin nontriviality S, haveI : nontrivial R := f.domain_nontrivial, have : map f p /ₘ map f q = map f (p /ₘ q) ∧ map f p %ₘ map f q = map f (p %ₘ q), { exact (div_mod_by_monic_unique ((p /ₘ q).map f) _ (hq.map f) ⟨eq.symm $ by rw [← polynomial.map_mul, ← polynomial.map_add, mod_by_monic_add_div _ hq], calc _ ≤ degree (p %ₘ q) : degree_map_le _ _ ... < degree q : degree_mod_by_monic_lt _ hq ... = _ : eq.symm $ degree_map_eq_of_leading_coeff_ne_zero _ (by rw [monic.def.1 hq, f.map_one]; exact one_ne_zero)⟩) }, exact ⟨this.1.symm, this.2.symm⟩ end lemma map_div_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p /ₘ q).map f = p.map f /ₘ q.map f := (map_mod_div_by_monic f hq).1 lemma map_mod_by_monic [comm_ring S] (f : R →+* S) (hq : monic q) : (p %ₘ q).map f = p.map f %ₘ q.map f := (map_mod_div_by_monic f hq).2 lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, begin nontriviality R, obtain ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h, by_contradiction hpq0, have hmod : p %ₘ q = q * (r - p /ₘ q), { rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr] }, have : degree (q * (r - p /ₘ q)) < degree q := hmod ▸ degree_mod_by_monic_lt _ hq, have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 := λ h, hpq0 $ leading_coeff_eq_zero.1 (by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]), have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul], rw [degree_mul' hlc, degree_eq_nat_degree hq.ne_zero, degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this, exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this) end⟩ theorem map_dvd_map [comm_ring S] (f : R →+* S) (hf : function.injective f) {x y : R[X]} (hx : x.monic) : x.map f ∣ y.map f ↔ x ∣ y := begin rw [← dvd_iff_mod_by_monic_eq_zero hx, ← dvd_iff_mod_by_monic_eq_zero (hx.map f), ← map_mod_by_monic f hx], exact ⟨λ H, map_injective f hf $ by rw [H, polynomial.map_zero], λ H, by rw [H, polynomial.map_zero]⟩ end @[simp] lemma mod_by_monic_one (p : R[X]) : p %ₘ 1 = 0 := (dvd_iff_mod_by_monic_eq_zero (by convert monic_one)).2 (one_dvd _) @[simp] lemma div_by_monic_one (p : R[X]) : p /ₘ 1 = p := by conv_rhs { rw [← mod_by_monic_add_div p monic_one] }; simp @[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : R[X]) (a : R) : p %ₘ (X - C a) = C (p.eval a) := begin nontriviality R, have h : (p %ₘ (X - C a)).eval a = p.eval a, { rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero] }, have : degree (p %ₘ (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a), have : degree (p %ₘ (X - C a)) ≤ 0, { cases (degree (p %ₘ (X - C a))), { exact bot_le }, { exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } }, rw [eq_C_of_degree_le_zero this, eval_C] at h, rw [eq_C_of_degree_le_zero this, h] end lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a := ⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h, λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩ lemma mod_by_monic_X (p : R[X]) : p %ₘ X = C (p.eval 0) := by rw [← mod_by_monic_X_sub_C_eq_C_eval, C_0, sub_zero] lemma eval₂_mod_by_monic_eq_self_of_root [comm_ring S] {f : R →+* S} {p q : R[X]} (hq : q.monic) {x : S} (hx : q.eval₂ f x = 0) : (p %ₘ q).eval₂ f x = p.eval₂ f x := by rw [mod_by_monic_eq_sub_mul_div p hq, eval₂_sub, eval₂_mul, hx, zero_mul, sub_zero] lemma sum_mod_by_monic_coeff (hq : q.monic) {n : ℕ} (hn : q.degree ≤ n) : ∑ (i : fin n), monomial i ((p %ₘ q).coeff i) = p %ₘ q := begin nontriviality R, exact (sum_fin (λ i c, monomial i c) (by simp) ((degree_mod_by_monic_lt _ hq).trans_le hn)).trans (sum_monomial_eq _) end lemma sub_dvd_eval_sub (a b : R) (p : R[X]) : a - b ∣ p.eval a - p.eval b := begin suffices : X - C b ∣ p - C (p.eval b), { simpa only [coe_eval_ring_hom, eval_sub, eval_X, eval_C] using (eval_ring_hom a).map_dvd this }, simp [dvd_iff_is_root] end variable (R) lemma not_is_field : ¬ is_field R[X] := begin nontriviality R, rw ring.not_is_field_iff_exists_ideal_bot_lt_and_lt_top, use ideal.span {polynomial.X}, split, { rw [bot_lt_iff_ne_bot, ne.def, ideal.span_singleton_eq_bot], exact polynomial.X_ne_zero, }, { rw [lt_top_iff_ne_top, ne.def, ideal.eq_top_iff_one, ideal.mem_span_singleton, polynomial.X_dvd_iff, polynomial.coeff_one_zero], exact one_ne_zero, } end variable {R} section multiplicity /-- An algorithm for deciding polynomial divisibility. The algorithm is "compute `p %ₘ q` and compare to `0`". ` See `polynomial.mod_by_monic` for the algorithm that computes `%ₘ`. -/ def decidable_dvd_monic (p : R[X]) (hq : monic q) : decidable (q ∣ p) := decidable_of_iff (p %ₘ q = 0) (dvd_iff_mod_by_monic_eq_zero hq) open_locale classical lemma multiplicity_X_sub_C_finite (a : R) (h0 : p ≠ 0) : multiplicity.finite (X - C a) p := begin haveI := nontrivial.of_polynomial_ne h0, refine multiplicity_finite_of_degree_pos_of_monic _ (monic_X_sub_C _) h0, rw degree_X_sub_C, dec_trivial, end /-- The largest power of `X - C a` which divides `p`. This is computable via the divisibility algorithm `decidable_dvd_monic`. -/ def root_multiplicity (a : R) (p : R[X]) : ℕ := if h0 : p = 0 then 0 else let I : decidable_pred (λ n : ℕ, ¬(X - C a) ^ (n + 1) ∣ p) := λ n, @not.decidable _ (decidable_dvd_monic p ((monic_X_sub_C a).pow (n + 1))) in by exactI nat.find (multiplicity_X_sub_C_finite a h0) lemma root_multiplicity_eq_multiplicity (p : R[X]) (a : R) : root_multiplicity a p = if h0 : p = 0 then 0 else (multiplicity (X - C a) p).get (multiplicity_X_sub_C_finite a h0) := by simp [multiplicity, root_multiplicity, part.dom]; congr; funext; congr @[simp] lemma root_multiplicity_zero {x : R} : root_multiplicity x 0 = 0 := dif_pos rfl lemma root_multiplicity_eq_zero {p : R[X]} {x : R} (h : ¬ is_root p x) : root_multiplicity x p = 0 := begin rw root_multiplicity_eq_multiplicity, split_ifs, { refl }, rw [← enat.coe_inj, enat.coe_get, multiplicity.multiplicity_eq_zero_of_not_dvd, nat.cast_zero], intro hdvd, exact h (dvd_iff_is_root.mp hdvd) end lemma root_multiplicity_pos {p : R[X]} (hp : p ≠ 0) {x : R} : 0 < root_multiplicity x p ↔ is_root p x := begin rw [← dvd_iff_is_root, root_multiplicity_eq_multiplicity, dif_neg hp, ← enat.coe_lt_coe, enat.coe_get], exact multiplicity.dvd_iff_multiplicity_pos end @[simp] lemma root_multiplicity_C (r a : R) : root_multiplicity a (C r) = 0 := begin rcases eq_or_ne r 0 with rfl|hr, { simp }, { exact root_multiplicity_eq_zero (not_is_root_C _ _ hr) } end lemma pow_root_multiplicity_dvd (p : R[X]) (a : R) : (X - C a) ^ root_multiplicity a p ∣ p := if h : p = 0 then by simp [h] else by rw [root_multiplicity_eq_multiplicity, dif_neg h]; exact multiplicity.pow_multiplicity_dvd _ lemma div_by_monic_mul_pow_root_multiplicity_eq (p : R[X]) (a : R) : p /ₘ ((X - C a) ^ root_multiplicity a p) * (X - C a) ^ root_multiplicity a p = p := have monic ((X - C a) ^ root_multiplicity a p), from (monic_X_sub_C _).pow _, by conv_rhs { rw [← mod_by_monic_add_div p this, (dvd_iff_mod_by_monic_eq_zero this).2 (pow_root_multiplicity_dvd _ _)] }; simp [mul_comm] lemma eval_div_by_monic_pow_root_multiplicity_ne_zero {p : R[X]} (a : R) (hp : p ≠ 0) : eval a (p /ₘ ((X - C a) ^ root_multiplicity a p)) ≠ 0 := begin haveI : nontrivial R := nontrivial.of_polynomial_ne hp, rw [ne.def, ← is_root.def, ← dvd_iff_is_root], rintros ⟨q, hq⟩, have := div_by_monic_mul_pow_root_multiplicity_eq p a, rw [mul_comm, hq, ← mul_assoc, ← pow_succ', root_multiplicity_eq_multiplicity, dif_neg hp] at this, exact multiplicity.is_greatest' (multiplicity_finite_of_degree_pos_of_monic (show (0 : with_bot ℕ) < degree (X - C a), by rw degree_X_sub_C; exact dec_trivial) (monic_X_sub_C _) hp) (nat.lt_succ_self _) (dvd_of_mul_right_eq _ this) end end multiplicity end comm_ring end polynomial
638b1d69d2a14535e3a10d86958e3a9a88435f4e
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Parser/Basic.lean
e5f8b2746984bcef5e98e7d0d16fc0abae28d165
[ "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
69,957
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 -/ /-! # Basic Lean parser infrastructure The Lean parser was developed with the following primary goals in mind: * flexibility: Lean's grammar is complex and includes indentation and other whitespace sensitivity. It should be possible to introduce such custom "tweaks" locally without having to adjust the fundamental parsing approach. * extensibility: Lean's grammar can be extended on the fly within a Lean file, and with Lean 4 we want to extend this to cover embedding domain-specific languages that may look nothing like Lean, down to using a separate set of tokens. * losslessness: The parser should produce a concrete syntax tree that preserves all whitespace and other "sub-token" information for the use in tooling. * performance: The overhead of the parser building blocks, and the overall parser performance on average-complexity input, should be comparable with that of the previous parser hand-written in C++. No fancy optimizations should be necessary for this. Given these constraints, we decided to implement a combinatoric, non-monadic, lexer-less, memoizing recursive-descent parser. Using combinators instead of some more formal and introspectible grammar representation ensures ultimate flexibility as well as efficient extensibility: there is (almost) no pre-processing necessary when extending the grammar with a new parser. However, because the all results the combinators produce are of the homogeneous `Syntax` type, the basic parser type is not actually a monad but a monomorphic linear function `ParserState → ParserState`, avoiding constructing and deconstructing countless monadic return values. Instead of explicitly returning syntax objects, parsers push (zero or more of) them onto a syntax stack inside the linear state. Chaining parsers via `>>` accumulates their output on the stack. Combinators such as `node` then pop off all syntax objects produced during their invocation and wrap them in a single `Syntax.node` object that is again pushed on this stack. Instead of calling `node` directly, we usually use the macro `parser! p`, which unfolds to `node k p` where the new syntax node kind `k` is the name of the declaration being defined. The lack of a dedicated lexer ensures we can modify and replace the lexical grammar at any point, and simplifies detecting and propagating whitespace. The parser still has a concept of "tokens", however, and caches the most recent one for performance: when `tokenFn` is called twice at the same position in the input, it will reuse the result of the first call. `tokenFn` recognizes some built-in variable-length tokens such as identifiers as well as any fixed token in the `ParserContext`'s `TokenTable` (a trie); however, the same cache field and strategy could be reused by custom token parsers. Tokens also play a central role in the `prattParser` combinator, which selects a *leading* parser followed by zero or more *trailing* parsers based on the current token (via `peekToken`); see the documentation of `prattParser` for more details. Tokens are specified via the `symbol` parser, or with `symbolNoWs` for tokens that should not be preceded by whitespace. The `Parser` type is extended with additional metadata over the mere parsing function to propagate token information: `collectTokens` collects all tokens within a parser for registering. `firstTokens` holds information about the "FIRST" token set used to speed up parser selection in `prattParser`. This approach of combining static and dynamic information in the parser type is inspired by the paper "Deterministic, Error-Correcting Combinator Parsers" by Swierstra and Duponcheel. If multiple parsers accept the same current token, `prattParser` tries all of them using the backtracking `longestMatchFn` combinator. This is the only case where standard parsers might execute arbitrary backtracking. At the moment there is no memoization shared by these parallel parsers apart from the first token, though we might change this in the future if the need arises. Finally, error reporting follows the standard combinatoric approach of collecting a single unexpected token/... and zero or more expected tokens (see `Error` below). Expected tokens are e.g. set by `symbol` and merged by `<|>`. Combinators running multiple parsers should check if an error message is set in the parser state (`hasError`) and act accordingly. Error recovery is left to the designer of the specific language; for example, Lean's top-level `parseCommand` loop skips tokens until the next command keyword on error. -/ import Lean.Data.Trie import Lean.Data.Position import Lean.Syntax import Lean.ToExpr import Lean.Environment import Lean.Attributes import Lean.Message import Lean.Compiler.InitAttr import Lean.ResolveName namespace Lean namespace Parser def isLitKind (k : SyntaxNodeKind) : Bool := k == strLitKind || k == numLitKind || k == charLitKind || k == nameLitKind || k == scientificLitKind abbrev mkAtom (info : SourceInfo) (val : String) : Syntax := Syntax.atom info val abbrev mkIdent (info : SourceInfo) (rawVal : Substring) (val : Name) : Syntax := Syntax.ident info rawVal val [] /- Return character after position `pos` -/ def getNext (input : String) (pos : Nat) : Char := input.get (input.next pos) /- Maximal (and function application) precedence. In the standard lean language, no parser has precedence higher than `maxPrec`. Note that nothing prevents users from using a higher precedence, but we strongly discourage them from doing it. -/ def maxPrec : Nat := evalPrec! max def leadPrec : Nat := evalPrec! lead def minPrec : Nat := evalPrec! min abbrev Token := String structure TokenCacheEntry where startPos : String.Pos := 0 stopPos : String.Pos := 0 token : Syntax := Syntax.missing structure ParserCache where tokenCache : TokenCacheEntry def initCacheForInput (input : String) : ParserCache := { tokenCache := { startPos := input.bsize + 1 /- make sure it is not a valid position -/} } abbrev TokenTable := Trie Token abbrev SyntaxNodeKindSet := Std.PersistentHashMap SyntaxNodeKind Unit def SyntaxNodeKindSet.insert (s : SyntaxNodeKindSet) (k : SyntaxNodeKind) : SyntaxNodeKindSet := Std.PersistentHashMap.insert s k () /- Input string and related data. Recall that the `FileMap` is a helper structure for mapping `String.Pos` in the input string to line/column information. -/ structure InputContext where input : String fileName : String fileMap : FileMap deriving Inhabited /-- Input context derived from elaboration of previous commands. -/ structure ParserModuleContext where env : Environment options : Options -- for name lookup currNamespace : Name := Name.anonymous openDecls : List OpenDecl := [] structure ParserContext extends InputContext, ParserModuleContext where prec : Nat tokens : TokenTable insideQuot : Bool := false suppressInsideQuot : Bool := false savedPos? : Option String.Pos := none forbiddenTk? : Option Token := none def ParserContext.resolveName (ctx : ParserContext) (id : Name) : List (Name × List String) := ResolveName.resolveGlobalName ctx.env ctx.currNamespace ctx.openDecls id structure Error where unexpected : String := "" expected : List String := [] deriving Inhabited, BEq namespace Error private def expectedToString : List String → String | [] => "" | [e] => e | [e1, e2] => e1 ++ " or " ++ e2 | e::es => e ++ ", " ++ expectedToString es protected def toString (e : Error) : String := let unexpected := if e.unexpected == "" then [] else [e.unexpected] let expected := if e.expected == [] then [] else let expected := e.expected.toArray.qsort (fun e e' => e < e') let expected := expected.toList.eraseReps ["expected " ++ expectedToString expected] "; ".intercalate $ unexpected ++ expected instance : ToString Error := ⟨Error.toString⟩ def merge (e₁ e₂ : Error) : Error := match e₂ with | { unexpected := u, .. } => { unexpected := if u == "" then e₁.unexpected else u, expected := e₁.expected ++ e₂.expected } end Error structure ParserState where stxStack : Array Syntax := #[] pos : String.Pos := 0 cache : ParserCache errorMsg : Option Error := none namespace ParserState @[inline] def hasError (s : ParserState) : Bool := s.errorMsg != none @[inline] def stackSize (s : ParserState) : Nat := s.stxStack.size def restore (s : ParserState) (iniStackSz : Nat) (iniPos : Nat) : ParserState := { s with stxStack := s.stxStack.shrink iniStackSz, errorMsg := none, pos := iniPos } def setPos (s : ParserState) (pos : Nat) : ParserState := { s with pos := pos } def setCache (s : ParserState) (cache : ParserCache) : ParserState := { s with cache := cache } def pushSyntax (s : ParserState) (n : Syntax) : ParserState := { s with stxStack := s.stxStack.push n } def popSyntax (s : ParserState) : ParserState := { s with stxStack := s.stxStack.pop } def shrinkStack (s : ParserState) (iniStackSz : Nat) : ParserState := { s with stxStack := s.stxStack.shrink iniStackSz } def next (s : ParserState) (input : String) (pos : Nat) : ParserState := { s with pos := input.next pos } def toErrorMsg (ctx : ParserContext) (s : ParserState) : String := match s.errorMsg with | none => "" | some msg => let pos := ctx.fileMap.toPosition s.pos mkErrorStringWithPos ctx.fileName pos (toString msg) def mkNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, pos, cache, err⟩ => if err != none && stack.size == iniStackSz then -- If there is an error but there are no new nodes on the stack, we just return `s` s else let newNode := Syntax.node k (stack.extract iniStackSz stack.size) let stack := stack.shrink iniStackSz let stack := stack.push newNode ⟨stack, pos, cache, err⟩ def mkTrailingNode (s : ParserState) (k : SyntaxNodeKind) (iniStackSz : Nat) : ParserState := match s with | ⟨stack, pos, cache, err⟩ => let newNode := Syntax.node k (stack.extract (iniStackSz - 1) stack.size) let stack := stack.shrink iniStackSz let stack := stack.push newNode ⟨stack, pos, cache, err⟩ def mkError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩ def mkUnexpectedError (s : ParserState) (msg : String) : ParserState := match s with | ⟨stack, pos, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩ def mkEOIError (s : ParserState) : ParserState := s.mkUnexpectedError "end of input" def mkErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState := match s with | ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := [ msg ] }⟩ def mkErrorsAt (s : ParserState) (ex : List String) (pos : String.Pos) : ParserState := match s with | ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { expected := ex }⟩ def mkUnexpectedErrorAt (s : ParserState) (msg : String) (pos : String.Pos) : ParserState := match s with | ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩ end ParserState def ParserFn := ParserContext → ParserState → ParserState instance : Inhabited ParserFn where default := fun ctx s => s inductive FirstTokens where | epsilon : FirstTokens | unknown : FirstTokens | tokens : List Token → FirstTokens | optTokens : List Token → FirstTokens deriving Inhabited namespace FirstTokens def seq : FirstTokens → FirstTokens → FirstTokens | epsilon, tks => tks | optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | optTokens s₁, tokens s₂ => tokens (s₁ ++ s₂) | tks, _ => tks def toOptional : FirstTokens → FirstTokens | tokens tks => optTokens tks | tks => tks def merge : FirstTokens → FirstTokens → FirstTokens | epsilon, tks => toOptional tks | tks, epsilon => toOptional tks | tokens s₁, tokens s₂ => tokens (s₁ ++ s₂) | optTokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | tokens s₁, optTokens s₂ => optTokens (s₁ ++ s₂) | optTokens s₁, tokens s₂ => optTokens (s₁ ++ s₂) | _, _ => unknown def toStr : FirstTokens → String | epsilon => "epsilon" | unknown => "unknown" | tokens tks => toString tks | optTokens tks => "?" ++ toString tks instance : ToString FirstTokens := ⟨toStr⟩ end FirstTokens structure ParserInfo where collectTokens : List Token → List Token := id collectKinds : SyntaxNodeKindSet → SyntaxNodeKindSet := id firstTokens : FirstTokens := FirstTokens.unknown deriving Inhabited structure Parser where info : ParserInfo := {} fn : ParserFn deriving Inhabited abbrev TrailingParser := Parser @[noinline] def epsilonInfo : ParserInfo := { firstTokens := FirstTokens.epsilon } @[inline] def checkStackTopFn (p : Syntax → Bool) (msg : String) : ParserFn := fun c s => if p s.stxStack.back then s else s.mkUnexpectedError msg @[inline] def checkStackTop (p : Syntax → Bool) (msg : String) : Parser := { info := epsilonInfo, fn := checkStackTopFn p msg } @[inline] def andthenFn (p q : ParserFn) : ParserFn := fun c s => let s := p c s if s.hasError then s else q c s @[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens, collectKinds := p.collectKinds ∘ q.collectKinds, firstTokens := p.firstTokens.seq q.firstTokens } @[inline] def andthen (p q : Parser) : Parser := { info := andthenInfo p.info q.info, fn := andthenFn p.fn q.fn } instance : AndThen Parser := ⟨andthen⟩ @[inline] def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkNode n iniSz @[inline] def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := p c s s.mkTrailingNode n iniSz @[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := fun s => (p.collectKinds s).insert n, firstTokens := p.firstTokens } @[inline] def node (n : SyntaxNodeKind) (p : Parser) : Parser := { info := nodeInfo n p.info, fn := nodeFn n p.fn } def errorFn (msg : String) : ParserFn := fun _ s => s.mkUnexpectedError msg @[inline] def error (msg : String) : Parser := { info := epsilonInfo, fn := errorFn msg } def errorAtSavedPosFn (msg : String) (delta : Bool) : ParserFn := fun c s => match c.savedPos? with | none => s | some pos => let pos := if delta then c.input.next pos else pos match s with | ⟨stack, _, cache, _⟩ => ⟨stack, pos, cache, some { unexpected := msg }⟩ /- Generate an error at the position saved with the `withPosition` combinator. If `delta == true`, then it reports at saved position+1. This useful to make sure a parser consumed at least one character. -/ @[inline] def errorAtSavedPos (msg : String) (delta : Bool) : Parser := { fn := errorAtSavedPosFn msg delta } /- Succeeds if `c.prec <= prec` -/ def checkPrecFn (prec : Nat) : ParserFn := fun c s => if c.prec <= prec then s else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term" @[inline] def checkPrec (prec : Nat) : Parser := { info := epsilonInfo, fn := checkPrecFn prec } def checkInsideQuotFn : ParserFn := fun c s => if c.insideQuot then s else s.mkUnexpectedError "unexpected syntax outside syntax quotation" @[inline] def checkInsideQuot : Parser := { info := epsilonInfo, fn := checkInsideQuotFn } def checkOutsideQuotFn : ParserFn := fun c s => if !c.insideQuot then s else s.mkUnexpectedError "unexpected syntax inside syntax quotation" @[inline] def checkOutsideQuot : Parser := { info := epsilonInfo, fn := checkOutsideQuotFn } def toggleInsideQuotFn (p : ParserFn) : ParserFn := fun c s => if c.suppressInsideQuot then p c s else p { c with insideQuot := !c.insideQuot } s @[inline] def toggleInsideQuot (p : Parser) : Parser := { info := p.info, fn := toggleInsideQuotFn p.fn } def suppressInsideQuotFn (p : ParserFn) : ParserFn := fun c s => p { c with suppressInsideQuot := true } s @[inline] def suppressInsideQuot (p : Parser) : Parser := { info := p.info, fn := suppressInsideQuotFn p.fn } @[inline] def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser := checkPrec prec >> node n p @[inline] def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser := { info := nodeInfo n p.info, fn := trailingNodeFn n p.fn } @[inline] def trailingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : TrailingParser := checkPrec prec >> trailingNodeAux n p def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : Nat) (mergeErrors : Bool) : ParserState := match s with | ⟨stack, pos, cache, some error2⟩ => if pos == iniPos then ⟨stack, pos, cache, some (if mergeErrors then error1.merge error2 else error2)⟩ else s | other => other def orelseFnCore (p q : ParserFn) (mergeErrors : Bool) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s match s.errorMsg with | some errorMsg => if s.pos == iniPos then mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos mergeErrors else s | none => s @[inline] def orelseFn (p q : ParserFn) : ParserFn := orelseFnCore p q true @[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ q.collectTokens, collectKinds := p.collectKinds ∘ q.collectKinds, firstTokens := p.firstTokens.merge q.firstTokens } /-- Run `p`, falling back to `q` if `p` failed without consuming any input. NOTE: In order for the pretty printer to retrace an `orelse`, `p` must be a call to `node` or some other parser producing a single node kind. Nested `orelse` calls are flattened for this, i.e. `(node k1 p1 <|> node k2 p2) <|> ...` is fine as well. -/ @[inline] def orelse (p q : Parser) : Parser := { info := orelseInfo p.info q.info, fn := orelseFn p.fn q.fn } instance : OrElse Parser := ⟨orelse⟩ @[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo := { collectTokens := info.collectTokens, collectKinds := info.collectKinds } def atomicFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos match p c s with | ⟨stack, _, cache, some msg⟩ => ⟨stack.shrink iniSz, iniPos, cache, some msg⟩ | other => other @[inline] def atomic (p : Parser) : Parser := { info := p.info, fn := atomicFn p.fn } def optionalFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s s.mkNode nullKind iniSz @[noinline] def optionaInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := p.collectKinds, firstTokens := p.firstTokens.toOptional } @[inline] def optionalNoAntiquot (p : Parser) : Parser := { info := optionaInfo p.info, fn := optionalFn p.fn } def lookaheadFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s else s.restore iniSz iniPos @[inline] def lookahead (p : Parser) : Parser := { info := p.info, fn := lookaheadFn p.fn } def notFollowedByFn (p : ParserFn) (msg : String) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then s.restore iniSz iniPos else let s := s.restore iniSz iniPos s.mkUnexpectedError s!"unexpected {msg}" @[inline] def notFollowedBy (p : Parser) (msg : String) : Parser := { fn := notFollowedByFn p.fn msg } partial def manyAux (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := p c s if s.hasError then if iniPos == s.pos then s.restore iniSz iniPos else s else if iniPos == s.pos then s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything" else manyAux p c s @[inline] def manyFn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := manyAux p c s s.mkNode nullKind iniSz @[inline] def manyNoAntiquot (p : Parser) : Parser := { info := noFirstTokenInfo p.info, fn := manyFn p.fn } @[inline] def many1Fn (p : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let s := andthenFn p (manyAux p) c s s.mkNode nullKind iniSz @[inline] def many1NoAntiquot (p : Parser) : Parser := { info := p.info, fn := many1Fn p.fn } private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) (pOpt : Bool) : ParserFn := let rec parse (pOpt : Bool) (c s) := let sz := s.stackSize let pos := s.pos let s := p c s if s.hasError then if s.pos > pos then s else if pOpt then let s := s.restore sz pos s.mkNode nullKind iniSz else -- append `Syntax.missing` to make clear that List is incomplete let s := s.pushSyntax Syntax.missing s.mkNode nullKind iniSz else let sz := s.stackSize let pos := s.pos let s := sep c s if s.hasError then let s := s.restore sz pos s.mkNode nullKind iniSz else parse allowTrailingSep c s parse pOpt def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz true c s def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize sepByFnAux p sep allowTrailingSep iniSz false c s @[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens, collectKinds := p.collectKinds ∘ sep.collectKinds } @[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens ∘ sep.collectTokens, collectKinds := p.collectKinds ∘ sep.collectKinds, firstTokens := p.firstTokens } @[inline] def sepByNoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepByInfo p.info sep.info, fn := sepByFn allowTrailingSep p.fn sep.fn } @[inline] def sepBy1NoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := { info := sepBy1Info p.info sep.info, fn := sepBy1Fn allowTrailingSep p.fn sep.fn } /- Apply `f` to the syntax object produced by `p` -/ def withResultOfFn (p : ParserFn) (f : Syntax → Syntax) : ParserFn := fun c s => let s := p c s if s.hasError then s else let stx := s.stxStack.back s.popSyntax.pushSyntax (f stx) @[noinline] def withResultOfInfo (p : ParserInfo) : ParserInfo := { collectTokens := p.collectTokens, collectKinds := p.collectKinds } @[inline] def withResultOf (p : Parser) (f : Syntax → Syntax) : Parser := { info := withResultOfInfo p.info, fn := withResultOfFn p.fn f } @[inline] def many1Unbox (p : Parser) : Parser := withResultOf (many1NoAntiquot p) fun stx => if stx.getNumArgs == 1 then stx.getArg 0 else stx partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s.mkEOIError else if p (c.input.get i) then s.next c.input i else s.mkUnexpectedError errorMsg partial def takeUntilFn (p : Char → Bool) : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else if p (c.input.get i) then s else takeUntilFn p c (s.next c.input i) def takeWhileFn (p : Char → Bool) : ParserFn := takeUntilFn (fun c => !p c) @[inline] def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn := andthenFn (satisfyFn p errorMsg) (takeWhileFn p) partial def finishCommentBlock (nesting : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let i := input.next i if curr == '-' then if input.atEnd i then s.mkEOIError else let curr := input.get i if curr == '/' then -- "-/" end of comment if nesting == 1 then s.next input i else finishCommentBlock (nesting-1) c (s.next input i) else finishCommentBlock nesting c (s.next input i) else if curr == '/' then if input.atEnd i then s.mkEOIError else let curr := input.get i if curr == '-' then finishCommentBlock (nesting+1) c (s.next input i) else finishCommentBlock nesting c (s.setPos i) else finishCommentBlock nesting c (s.setPos i) /- Consume whitespace and comments -/ partial def whitespace : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s else let curr := input.get i if curr.isWhitespace then whitespace c (s.next input i) else if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i) else s else if curr == '/' then let i := input.next i let curr := input.get i if curr == '-' then let i := input.next i let curr := input.get i if curr == '-' then s -- "/--" doc comment is an actual token else andthenFn (finishCommentBlock 1) whitespace c (s.next input i) else s else s def mkEmptySubstringAt (s : String) (p : Nat) : Substring := { str := s, startPos := p, stopPos := p } private def rawAux (startPos : Nat) (trailingWs : Bool) : ParserFn := fun c s => let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos if trailingWs then let s := whitespace c s let stopPos' := s.pos let trailing := { str := input, startPos := stopPos, stopPos := stopPos' : Substring } let atom := mkAtom (SourceInfo.original leading startPos trailing) val s.pushSyntax atom else let trailing := mkEmptySubstringAt input stopPos let atom := mkAtom (SourceInfo.original leading startPos trailing) val s.pushSyntax atom /-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/ @[inline] def rawFn (p : ParserFn) (trailingWs := false) : ParserFn := fun c s => let startPos := s.pos let s := p c s if s.hasError then s else rawAux startPos trailingWs c s @[inline] def chFn (c : Char) (trailingWs := false) : ParserFn := rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs def rawCh (c : Char) (trailingWs := false) : Parser := { fn := chFn c trailingWs } def hexDigitFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let i := input.next i if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i else s.mkUnexpectedError "invalid hexadecimal numeral" def quotedCharCoreFn (isQuotable : Char → Bool) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i if isQuotable curr then s.next input i else if curr == 'x' then andthenFn hexDigitFn hexDigitFn c (s.next input i) else if curr == 'u' then andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next input i) else s.mkUnexpectedError "invalid escape sequence" def isQuotableCharDefault (c : Char) : Bool := c == '\\' || c == '\"' || c == '\'' || c == 'r' || c == 'n' || c == 't' def quotedCharFn : ParserFn := quotedCharCoreFn isQuotableCharDefault /-- Push `(Syntax.node tk <new-atom>)` into syntax stack -/ def mkNodeToken (n : SyntaxNodeKind) (startPos : Nat) : ParserFn := fun c s => let input := c.input let stopPos := s.pos let leading := mkEmptySubstringAt input startPos let val := input.extract startPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let info := SourceInfo.original leading startPos trailing s.pushSyntax (Syntax.mkLit n val info) def charLitFnAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let s := s.setPos (input.next i) let s := if curr == '\\' then quotedCharFn c s else s if s.hasError then s else let i := s.pos let curr := input.get i let s := s.setPos (input.next i) if curr == '\'' then mkNodeToken charLitKind startPos c s else s.mkUnexpectedError "missing end of character literal" partial def strLitFnAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i let s := s.setPos (input.next i) if curr == '\"' then mkNodeToken strLitKind startPos c s else if curr == '\\' then andthenFn quotedCharFn (strLitFnAux startPos) c s else strLitFnAux startPos c s def decimalNumberFn (startPos : Nat) (c : ParserContext) : ParserState → ParserState := fun s => let s := takeWhileFn (fun c => c.isDigit) c s let input := c.input let i := s.pos let curr := input.get i if curr == '.' || curr == 'e' || curr == 'E' then let s := parseOptDot s let s := parseOptExp s mkNodeToken scientificLitKind startPos c s else mkNodeToken numLitKind startPos c s where parseOptDot s := let input := c.input let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.setPos i else s parseOptExp s := let input := c.input let i := s.pos let curr := input.get i if curr == 'e' || curr == 'E' then let i := input.next i let i := if input.get i == '-' then input.next i else i let curr := input.get i if curr.isDigit then takeWhileFn (fun c => c.isDigit) c (s.setPos i) else s.setPos i else s def binNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s mkNodeToken numLitKind startPos c s def octalNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s mkNodeToken numLitKind startPos c s def hexNumberFn (startPos : Nat) : ParserFn := fun c s => let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" c s mkNodeToken numLitKind startPos c s def numberFnAux : ParserFn := fun c s => let input := c.input let startPos := s.pos if input.atEnd startPos then s.mkEOIError else let curr := input.get startPos if curr == '0' then let i := input.next startPos let curr := input.get i if curr == 'b' || curr == 'B' then binNumberFn startPos c (s.next input i) else if curr == 'o' || curr == 'O' then octalNumberFn startPos c (s.next input i) else if curr == 'x' || curr == 'X' then hexNumberFn startPos c (s.next input i) else decimalNumberFn startPos c (s.setPos i) else if curr.isDigit then decimalNumberFn startPos c (s.next input startPos) else s.mkError "numeral" def isIdCont : String → ParserState → Bool := fun input s => let i := s.pos let curr := input.get i if curr == '.' then let i := input.next i if input.atEnd i then false else let curr := input.get i isIdFirst curr || isIdBeginEscape curr else false private def isToken (idStartPos idStopPos : Nat) (tk : Option Token) : Bool := match tk with | none => false | some tk => -- if a token is both a symbol and a valid identifier (i.e. a keyword), -- we want it to be recognized as a symbol tk.bsize ≥ idStopPos - idStartPos def mkTokenAndFixPos (startPos : Nat) (tk : Option Token) : ParserFn := fun c s => match tk with | none => s.mkErrorAt "token" startPos | some tk => if c.forbiddenTk? == some tk then s.mkErrorAt "forbidden token" startPos else let input := c.input let leading := mkEmptySubstringAt input startPos let stopPos := startPos + tk.bsize let s := s.setPos stopPos let s := whitespace c s let wsStopPos := s.pos let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring } let atom := mkAtom (SourceInfo.original leading startPos trailing) tk s.pushSyntax atom def mkIdResult (startPos : Nat) (tk : Option Token) (val : Name) : ParserFn := fun c s => let stopPos := s.pos if isToken startPos stopPos tk then mkTokenAndFixPos startPos tk c s else let input := c.input let rawVal := { str := input, startPos := startPos, stopPos := stopPos : Substring } let s := whitespace c s let trailingStopPos := s.pos let leading := mkEmptySubstringAt input startPos let trailing := { str := input, startPos := stopPos, stopPos := trailingStopPos : Substring } let info := SourceInfo.original leading startPos trailing let atom := mkIdent info rawVal val s.pushSyntax atom partial def identFnAux (startPos : Nat) (tk : Option Token) (r : Name) : ParserFn := let rec parse (r : Name) (c s) := let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let curr := input.get i if isIdBeginEscape curr then let startPart := input.next i let s := takeUntilFn isIdEndEscape c (s.setPos startPart) let stopPart := s.pos let s := satisfyFn isIdEndEscape "missing end of escaped identifier" c s if s.hasError then s else let r := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else if isIdFirst curr then let startPart := i let s := takeWhileFn isIdRest c (s.next input i) let stopPart := s.pos let r := Name.mkStr r (input.extract startPart stopPart) if isIdCont input s then let s := s.next input s.pos parse r c s else mkIdResult startPos tk r c s else mkTokenAndFixPos startPos tk c s parse r private def isIdFirstOrBeginEscape (c : Char) : Bool := isIdFirst c || isIdBeginEscape c private def nameLitAux (startPos : Nat) : ParserFn := fun c s => let input := c.input let s := identFnAux startPos none Name.anonymous c (s.next input startPos) if s.hasError then s.mkErrorAt "invalid Name literal" startPos else let stx := s.stxStack.back match stx with | Syntax.ident _ rawStr _ _ => let s := s.popSyntax s.pushSyntax (Syntax.node nameLitKind #[mkAtomFrom stx rawStr.toString]) | _ => s.mkError "invalid Name literal" private def tokenFnAux : ParserFn := fun c s => let input := c.input let i := s.pos let curr := input.get i if curr == '\"' then strLitFnAux i c (s.next input i) else if curr == '\'' then charLitFnAux i c (s.next input i) else if curr.isDigit then numberFnAux c s else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then nameLitAux i c s else let (_, tk) := c.tokens.matchPrefix input i identFnAux i tk Name.anonymous c s private def updateCache (startPos : Nat) (s : ParserState) : ParserState := match s with | ⟨stack, pos, cache, none⟩ => if stack.size == 0 then s else let tk := stack.back ⟨stack, pos, { tokenCache := { startPos := startPos, stopPos := pos, token := tk } }, none⟩ | other => other def tokenFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else let tkc := s.cache.tokenCache if tkc.startPos == i then let s := s.pushSyntax tkc.token s.setPos tkc.stopPos else let s := tokenFnAux c s updateCache i s def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Option Syntax := let iniSz := s.stackSize let iniPos := s.pos let s := tokenFn c s if s.hasError then (s.restore iniSz iniPos, none) else let stx := s.stxStack.back (s.restore iniSz iniPos, some stx) def peekToken (c : ParserContext) (s : ParserState) : ParserState × Option Syntax := let tkc := s.cache.tokenCache if tkc.startPos == s.pos then (s, some tkc.token) else peekTokenAux c s /- Treat keywords as identifiers. -/ def rawIdentFn : ParserFn := fun c s => let input := c.input let i := s.pos if input.atEnd i then s.mkEOIError else identFnAux i none Name.anonymous c s @[inline] def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn := fun c s => let startPos := s.pos let s := tokenFn c s if s.hasError then s.mkErrorsAt expected startPos else match s.stxStack.back with | Syntax.atom _ sym => if p sym then s else s.mkErrorsAt expected startPos | _ => s.mkErrorsAt expected startPos def symbolFnAux (sym : String) (errorMsg : String) : ParserFn := satisfySymbolFn (fun s => s == sym) [errorMsg] def symbolInfo (sym : String) : ParserInfo := { collectTokens := fun tks => sym :: tks, firstTokens := FirstTokens.tokens [ sym ] } @[inline] def symbolFn (sym : String) : ParserFn := symbolFnAux sym ("'" ++ sym ++ "'") @[inline] def symbolNoAntiquot (sym : String) : Parser := let sym := sym.trim { info := symbolInfo sym, fn := symbolFn sym } def checkTailNoWs (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing => trailing.stopPos == trailing.startPos | _ => false /-- Check if the following token is the symbol _or_ identifier `sym`. Useful for parsing local tokens that have not been added to the token table (but may have been so by some unrelated code). For example, the universe `max` Function is parsed using this combinator so that it can still be used as an identifier outside of universes (but registering it as a token in a Term Syntax would not break the universe Parser). -/ def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn := fun c s => let startPos := s.pos let s := tokenFn c s if s.hasError then s.mkErrorAt errorMsg startPos else match s.stxStack.back with | Syntax.atom _ sym' => if sym == sym' then s else s.mkErrorAt errorMsg startPos | Syntax.ident info rawVal _ _ => if sym == rawVal.toString then let s := s.popSyntax s.pushSyntax (Syntax.atom info sym) else s.mkErrorAt errorMsg startPos | _ => s.mkErrorAt errorMsg startPos @[inline] def nonReservedSymbolFn (sym : String) : ParserFn := nonReservedSymbolFnAux sym ("'" ++ sym ++ "'") def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo := { firstTokens := if includeIdent then FirstTokens.tokens [ sym, "ident" ] else FirstTokens.tokens [ sym ] } @[inline] def nonReservedSymbolNoAntiquot (sym : String) (includeIdent := false) : Parser := let sym := sym.trim { info := nonReservedSymbolInfo sym includeIdent, fn := nonReservedSymbolFn sym } partial def strAux (sym : String) (errorMsg : String) (j : Nat) :ParserFn := let rec parse (j c s) := if sym.atEnd j then s else let i := s.pos let input := c.input if input.atEnd i || sym.get j != input.get i then s.mkError errorMsg else parse (sym.next j) c (s.next input i) parse j def checkTailWs (prev : Syntax) : Bool := match prev.getTailInfo with | SourceInfo.original _ _ trailing => trailing.stopPos > trailing.startPos | _ => false def checkWsBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := s.stxStack.back if checkTailWs prev then s else s.mkError errorMsg def checkWsBefore (errorMsg : String := "space before") : Parser := { info := epsilonInfo, fn := checkWsBeforeFn errorMsg } private def pickNonNone (stack : Array Syntax) : Syntax := match stack.findRev? $ fun stx => !stx.isNone with | none => Syntax.missing | some stx => stx def checkNoWsBeforeFn (errorMsg : String) : ParserFn := fun c s => let prev := pickNonNone s.stxStack if checkTailNoWs prev then s else s.mkError errorMsg def checkNoWsBefore (errorMsg : String := "no space before") : Parser := { info := epsilonInfo, fn := checkNoWsBeforeFn errorMsg } def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn := satisfySymbolFn (fun s => s == sym || s == asciiSym) expected def unicodeSymbolInfo (sym asciiSym : String) : ParserInfo := { collectTokens := fun tks => sym :: asciiSym :: tks, firstTokens := FirstTokens.tokens [ sym, asciiSym ] } @[inline] def unicodeSymbolFn (sym asciiSym : String) : ParserFn := unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"] @[inline] def unicodeSymbolNoAntiquot (sym asciiSym : String) : Parser := let sym := sym.trim let asciiSym := asciiSym.trim { info := unicodeSymbolInfo sym asciiSym, fn := unicodeSymbolFn sym asciiSym } def mkAtomicInfo (k : String) : ParserInfo := { firstTokens := FirstTokens.tokens [ k ] } def numLitFn : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError || !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos else s @[inline] def numLitNoAntiquot : Parser := { fn := numLitFn, info := mkAtomicInfo "numLit" } def scientificLitFn : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError || !(s.stxStack.back.isOfKind scientificLitKind) then s.mkErrorAt "scientific number" iniPos else s @[inline] def scientificLitNoAntiquot : Parser := { fn := scientificLitFn, info := mkAtomicInfo "scientificLit" } def strLitFn : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError || !(s.stxStack.back.isOfKind strLitKind) then s.mkErrorAt "string literal" iniPos else s @[inline] def strLitNoAntiquot : Parser := { fn := strLitFn, info := mkAtomicInfo "strLit" } def charLitFn : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError || !(s.stxStack.back.isOfKind charLitKind) then s.mkErrorAt "character literal" iniPos else s @[inline] def charLitNoAntiquot : Parser := { fn := charLitFn, info := mkAtomicInfo "charLit" } def nameLitFn : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError || !(s.stxStack.back.isOfKind nameLitKind) then s.mkErrorAt "Name literal" iniPos else s @[inline] def nameLitNoAntiquot : Parser := { fn := nameLitFn, info := mkAtomicInfo "nameLit" } def identFn : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError || !(s.stxStack.back.isIdent) then s.mkErrorAt "identifier" iniPos else s @[inline] def identNoAntiquot : Parser := { fn := identFn, info := mkAtomicInfo "ident" } @[inline] def rawIdentNoAntiquot : Parser := { fn := rawIdentFn } def identEqFn (id : Name) : ParserFn := fun c s => let iniPos := s.pos let s := tokenFn c s if s.hasError then s.mkErrorAt "identifier" iniPos else match s.stxStack.back with | Syntax.ident _ _ val _ => if val != id then s.mkErrorAt ("expected identifier '" ++ toString id ++ "'") iniPos else s | _ => s.mkErrorAt "identifier" iniPos @[inline] def identEq (id : Name) : Parser := { fn := identEqFn id, info := mkAtomicInfo "ident" } namespace ParserState def keepNewError (s : ParserState) (oldStackSize : Nat) : ParserState := match s with | ⟨stack, pos, cache, err⟩ => ⟨stack.shrink oldStackSize, pos, cache, err⟩ def keepPrevError (s : ParserState) (oldStackSize : Nat) (oldStopPos : String.Pos) (oldError : Option Error) : ParserState := match s with | ⟨stack, _, cache, _⟩ => ⟨stack.shrink oldStackSize, oldStopPos, cache, oldError⟩ def mergeErrors (s : ParserState) (oldStackSize : Nat) (oldError : Error) : ParserState := match s with | ⟨stack, pos, cache, some err⟩ => if oldError == err then s else ⟨stack.shrink oldStackSize, pos, cache, some (oldError.merge err)⟩ | other => other def keepLatest (s : ParserState) (startStackSize : Nat) : ParserState := match s with | ⟨stack, pos, cache, _⟩ => let node := stack.back let stack := stack.shrink startStackSize let stack := stack.push node ⟨stack, pos, cache, none⟩ def replaceLongest (s : ParserState) (startStackSize : Nat) : ParserState := s.keepLatest startStackSize end ParserState def invalidLongestMatchParser (s : ParserState) : ParserState := s.mkError "longestMatch parsers must generate exactly one Syntax node" /-- Auxiliary function used to execute parsers provided to `longestMatchFn`. Push `left?` into the stack if it is not `none`, and execute `p`. After executing `p`, remove `left`. Remark: `p` must produce exactly one syntax node. Remark: the `left?` is not none when we are processing trailing parsers. -/ def runLongestMatchParser (left? : Option Syntax) (p : ParserFn) : ParserFn := fun c s => let startSize := s.stackSize match left? with | none => let s := p c s if s.hasError then s else -- stack contains `[..., result ]` if s.stackSize == startSize + 1 then s else invalidLongestMatchParser s | some left => let s := s.pushSyntax left let s := p c s if s.hasError then s else -- stack contains `[..., left, result ]` we must remove `left` if s.stackSize == startSize + 2 then -- `p` created one node, then we just remove `left` and keep it let r := s.stxStack.back let s := s.shrinkStack startSize -- remove `r` and `left` s.pushSyntax r -- add `r` back else invalidLongestMatchParser s def longestMatchStep (left? : Option Syntax) (startSize : Nat) (startPos : String.Pos) (prevPrio : Nat) (prio : Nat) (p : ParserFn) : ParserContext → ParserState → ParserState × Nat := fun c s => let prevErrorMsg := s.errorMsg let prevStopPos := s.pos let prevSize := s.stackSize let s := s.restore prevSize startPos let s := runLongestMatchParser left? p c s match prevErrorMsg, s.errorMsg with | none, none => -- both succeeded if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.replaceLongest startSize, prio) else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then (s.restore prevSize prevStopPos, prevPrio) -- keep prev else (s, prio) | none, some _ => -- prev succeeded, current failed (s.restore prevSize prevStopPos, prevPrio) | some oldError, some _ => -- both failed if s.pos > prevStopPos || (s.pos == prevStopPos && prio > prevPrio) then (s.keepNewError prevSize, prio) else if s.pos < prevStopPos || (s.pos == prevStopPos && prio < prevPrio) then (s.keepPrevError prevSize prevStopPos prevErrorMsg, prevPrio) else (s.mergeErrors prevSize oldError, prio) | some _, none => -- prev failed, current succeeded let successNode := s.stxStack.back let s := s.shrinkStack startSize -- restore stack to initial size to make sure (failure) nodes are removed from the stack (s.pushSyntax successNode, prio) -- put successNode back on the stack def longestMatchMkResult (startSize : Nat) (s : ParserState) : ParserState := if !s.hasError && s.stackSize > startSize + 1 then s.mkNode choiceKind startSize else s def longestMatchFnAux (left? : Option Syntax) (startSize : Nat) (startPos : String.Pos) (prevPrio : Nat) (ps : List (Parser × Nat)) : ParserFn := let rec parse (prevPrio : Nat) (ps : List (Parser × Nat)) := match ps with | [] => fun _ s => longestMatchMkResult startSize s | p::ps => fun c s => let (s, prevPrio) := longestMatchStep left? startSize startPos prevPrio p.2 p.1.fn c s parse prevPrio ps c s parse prevPrio ps def longestMatchFn (left? : Option Syntax) : List (Parser × Nat) → ParserFn | [] => fun _ s => s.mkError "longestMatch: empty list" | [p] => runLongestMatchParser left? p.1.fn | p::ps => fun c s => let startSize := s.stackSize let startPos := s.pos let s := runLongestMatchParser left? p.1.fn c s if s.hasError then let s := s.shrinkStack startSize longestMatchFnAux left? startSize startPos p.2 ps c s else longestMatchFnAux left? startSize startPos p.2 ps c s def anyOfFn : List Parser → ParserFn | [], _, s => s.mkError "anyOf: empty list" | [p], c, s => p.fn c s | p::ps, c, s => orelseFn p.fn (anyOfFn ps) c s @[inline] def checkColGeFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column ≥ savedPos.column then s else s.mkError errorMsg @[inline] def checkColGe (errorMsg : String := "checkColGe") : Parser := { fn := checkColGeFn errorMsg } @[inline] def checkColGtFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.column > savedPos.column then s else s.mkError errorMsg @[inline] def checkColGt (errorMsg : String := "checkColGt") : Parser := { fn := checkColGtFn errorMsg } @[inline] def checkLineEqFn (errorMsg : String) : ParserFn := fun c s => match c.savedPos? with | none => s | some savedPos => let savedPos := c.fileMap.toPosition savedPos let pos := c.fileMap.toPosition s.pos if pos.line == savedPos.line then s else s.mkError errorMsg @[inline] def checkLineEq (errorMsg : String := "checkLineEq") : Parser := { fn := checkLineEqFn errorMsg } @[inline] def withPosition (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with savedPos? := s.pos } s } @[inline] def withoutPosition (p : Parser) : Parser := { info := p.info, fn := fun c s => let pos := c.fileMap.toPosition s.pos p.fn { c with savedPos? := none } s } @[inline] def withForbidden (tk : Token) (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with forbiddenTk? := tk } s } @[inline] def withoutForbidden (p : Parser) : Parser := { info := p.info, fn := fun c s => p.fn { c with forbiddenTk? := none } s } def eoiFn : ParserFn := fun c s => let i := s.pos if c.input.atEnd i then s else s.mkError "expected end of file" @[inline] def eoi : Parser := { fn := eoiFn } open Std (RBMap RBMap.empty) /-- A multimap indexed by tokens. Used for indexing parsers by their leading token. -/ def TokenMap (α : Type) := RBMap Name (List α) Name.quickLt namespace TokenMap def insert (map : TokenMap α) (k : Name) (v : α) : TokenMap α := match map.find? k with | none => Std.RBMap.insert map k [v] | some vs => Std.RBMap.insert map k (v::vs) instance : Inhabited (TokenMap α) := ⟨RBMap.empty⟩ instance : EmptyCollection (TokenMap α) := ⟨RBMap.empty⟩ end TokenMap structure PrattParsingTables where leadingTable : TokenMap (Parser × Nat) := {} leadingParsers : List (Parser × Nat) := [] -- for supporting parsers we cannot obtain first token trailingTable : TokenMap (Parser × Nat) := {} trailingParsers : List (Parser × Nat) := [] -- for supporting parsers such as function application instance : Inhabited PrattParsingTables := ⟨{}⟩ /- The type `leadingIdentBehavior` specifies how the parsing table lookup function behaves for identifiers. The function `prattParser` uses two tables `leadingTable` and `trailingTable`. They map tokens to parsers. - `LeadingIdentBehavior.default`: if the leading token is an identifier, then `prattParser` just executes the parsers associated with the auxiliary token "ident". - `LeadingIdentBehavior.symbol`: if the leading token is an identifier `<foo>`, and there are parsers `P` associated with the toek `<foo>`, then it executes `P`. Otherwise, it executes only the parsers associated with the auxiliary token "ident". - `LeadingIdentBehavior.both`: if the leading token an identifier `<foo>`, the it executes the parsers associated with token `<foo>` and parsers associated with the auxiliary token "ident". We use `LeadingIdentBehavior.symbol` and `LeadingIdentBehavior.both` and `nonReservedSymbol` parser to implement the `tactic` parsers. The idea is to avoid creating a reserved symbol for each builtin tactic (e.g., `apply`, `assumption`, etc.). That is, users may still use these symbols as identifiers (e.g., naming a function). -/ inductive LeadingIdentBehavior where | default | symbol | both deriving Inhabited, BEq /-- Each parser category is implemented using a Pratt's parser. The system comes equipped with the following categories: `level`, `term`, `tactic`, and `command`. Users and plugins may define extra categories. The method ``` categoryParser `term prec ``` executes the Pratt's parser for category `term` with precedence `prec`. That is, only parsers with precedence at least `prec` are considered. The method `termParser prec` is equivalent to the method above. -/ structure ParserCategory where tables : PrattParsingTables behavior : LeadingIdentBehavior deriving Inhabited abbrev ParserCategories := Std.PersistentHashMap Name ParserCategory def indexed {α : Type} (map : TokenMap α) (c : ParserContext) (s : ParserState) (behavior : LeadingIdentBehavior) : ParserState × List α := let (s, stx) := peekToken c s let find (n : Name) : ParserState × List α := match map.find? n with | some as => (s, as) | _ => (s, []) match stx with | some (Syntax.atom _ sym) => find (Name.mkSimple sym) | some (Syntax.ident _ _ val _) => match behavior with | LeadingIdentBehavior.default => find identKind | LeadingIdentBehavior.symbol => match map.find? val with | some as => (s, as) | none => find identKind | LeadingIdentBehavior.both => match map.find? val with | some as => match map.find? identKind with | some as' => (s, as ++ as') | _ => (s, as) | none => find identKind | some (Syntax.node k _) => find k | _ => (s, []) abbrev CategoryParserFn := Name → ParserFn builtin_initialize categoryParserFnRef : IO.Ref CategoryParserFn ← IO.mkRef fun _ => whitespace builtin_initialize categoryParserFnExtension : EnvExtension CategoryParserFn ← registerEnvExtension $ categoryParserFnRef.get def categoryParserFn (catName : Name) : ParserFn := fun ctx s => categoryParserFnExtension.getState ctx.env catName ctx s def categoryParser (catName : Name) (prec : Nat) : Parser := { fn := fun c s => categoryParserFn catName { c with prec := prec } s } -- Define `termParser` here because we need it for antiquotations @[inline] def termParser (prec : Nat := 0) : Parser := categoryParser `term prec /- ============== -/ /- Antiquotations -/ /- ============== -/ /-- Fail if previous token is immediately followed by ':'. -/ def checkNoImmediateColon : Parser := { fn := fun c s => let prev := s.stxStack.back if checkTailNoWs prev then let input := c.input let i := s.pos if input.atEnd i then s else let curr := input.get i if curr == ':' then s.mkUnexpectedError "unexpected ':'" else s else s } def setExpectedFn (expected : List String) (p : ParserFn) : ParserFn := fun c s => match p c s with | s'@{ errorMsg := some msg, .. } => { s' with errorMsg := some { msg with expected := [] } } | s' => s' def setExpected (expected : List String) (p : Parser) : Parser := { fn := setExpectedFn expected p.fn, info := p.info } def pushNone : Parser := { fn := fun c s => s.pushSyntax mkNullNode } -- We support two kinds of antiquotations: `$id` and `$(t)`, where `id` is a term identifier and `t` is a term. def antiquotNestedExpr : Parser := node `antiquotNestedExpr (symbolNoAntiquot "(" >> toggleInsideQuot termParser >> symbolNoAntiquot ")") def antiquotExpr : Parser := identNoAntiquot <|> antiquotNestedExpr @[inline] def tokenWithAntiquotFn (p : ParserFn) : ParserFn := fun c s => do let s := p c s if s.hasError then return s let iniSz := s.stackSize let iniPos := s.pos let s := (checkNoWsBefore >> symbolNoAntiquot "%" >> symbolNoAntiquot "$" >> checkNoWsBefore >> antiquotExpr).fn c s if s.hasError then return s.restore iniSz iniPos s.mkNode (`token_antiquot) (iniSz - 1) @[inline] def tokenWithAntiquot (p : Parser) : Parser where fn := tokenWithAntiquotFn p.fn info := p.info @[inline] def symbol (sym : String) : Parser := tokenWithAntiquot (symbolNoAntiquot sym) instance : Coe String Parser := ⟨fun s => symbol s ⟩ @[inline] def nonReservedSymbol (sym : String) (includeIdent := false) : Parser := tokenWithAntiquot (nonReservedSymbolNoAntiquot sym includeIdent) @[inline] def unicodeSymbol (sym asciiSym : String) : Parser := tokenWithAntiquot (unicodeSymbolNoAntiquot sym asciiSym) /-- Define parser for `$e` (if anonymous == true) and `$e:name`. Both forms can also be used with an appended `*` to turn them into an antiquotation "splice". If `kind` is given, it will additionally be checked when evaluating `match_syntax`. Antiquotations can be escaped as in `$$e`, which produces the syntax tree for `$e`. -/ def mkAntiquot (name : String) (kind : Option SyntaxNodeKind) (anonymous := true) : Parser := let kind := (kind.getD Name.anonymous) ++ `antiquot let nameP := node `antiquotName $ checkNoWsBefore ("no space before ':" ++ name ++ "'") >> symbol ":" >> nonReservedSymbol name -- if parsing the kind fails and `anonymous` is true, check that we're not ignoring a different -- antiquotation kind via `noImmediateColon` let nameP := if anonymous then nameP <|> checkNoImmediateColon >> pushNone else nameP -- antiquotations are not part of the "standard" syntax, so hide "expected '$'" on error leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> antiquotExpr >> nameP def tryAnti (c : ParserContext) (s : ParserState) : Bool := let (s, stx?) := peekToken c s match stx? with | some stx@(Syntax.atom _ sym) => sym == "$" | _ => false @[inline] def withAntiquotFn (antiquotP p : ParserFn) : ParserFn := fun c s => if tryAnti c s then orelseFn antiquotP p c s else p c s /-- Optimized version of `mkAntiquot ... <|> p`. -/ @[inline] def withAntiquot (antiquotP p : Parser) : Parser := { fn := withAntiquotFn antiquotP.fn p.fn, info := orelseInfo antiquotP.info p.info } def withoutInfo (p : Parser) : Parser := { fn := p.fn } /-- Parse `$[p]suffix`, e.g. `$[p],*`. -/ def mkAntiquotSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := let kind := kind ++ `antiquot_scope leadingNode kind maxPrec $ atomic $ setExpected [] "$" >> manyNoAntiquot (checkNoWsBefore "" >> "$") >> checkNoWsBefore "no space before spliced term" >> symbol "[" >> node nullKind p >> symbol "]" >> suffix @[inline] def withAntiquotSuffixSpliceFn (kind : SyntaxNodeKind) (p suffix : ParserFn) : ParserFn := fun c s => do let s := p c s if s.hasError || !s.stxStack.back.isAntiquot then return s let iniSz := s.stackSize let iniPos := s.pos let s := suffix c s if s.hasError then return s.restore iniSz iniPos s.mkNode (kind ++ `antiquot_suffix_splice) (s.stxStack.size - 2) /-- Parse `suffix` after an antiquotation, e.g. `$x,*`, and put both into a new node. -/ @[inline] def withAntiquotSuffixSplice (kind : SyntaxNodeKind) (p suffix : Parser) : Parser := { info := andthenInfo p.info suffix.info, fn := withAntiquotSuffixSpliceFn kind p.fn suffix.fn } def withAntiquotSpliceAndSuffix (kind : SyntaxNodeKind) (p suffix : Parser) := -- prevent `p`'s info from being collected twice withAntiquot (mkAntiquotSplice kind (withoutInfo p) suffix) (withAntiquotSuffixSplice kind p suffix) def nodeWithAntiquot (name : String) (kind : SyntaxNodeKind) (p : Parser) (anonymous := false) : Parser := withAntiquot (mkAntiquot name kind anonymous) $ node kind p /- ===================== -/ /- End of Antiquotations -/ /- ===================== -/ def sepByElemParser (p : Parser) (sep : String) : Parser := withAntiquotSpliceAndSuffix `sepBy p (symbol (sep.trim ++ "*")) def sepBy (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepByNoAntiquot (sepByElemParser p sep) psep allowTrailingSep def sepBy1 (p : Parser) (sep : String) (psep : Parser := symbol sep) (allowTrailingSep : Bool := false) : Parser := sepBy1NoAntiquot (sepByElemParser p sep) psep allowTrailingSep def categoryParserOfStackFn (offset : Nat) : ParserFn := fun ctx s => let stack := s.stxStack if stack.size < offset + 1 then s.mkUnexpectedError ("failed to determine parser category using syntax stack, stack is too small") else match stack.get! (stack.size - offset - 1) with | Syntax.ident _ _ catName _ => categoryParserFn catName ctx s | _ => s.mkUnexpectedError ("failed to determine parser category using syntax stack, the specified element on the stack is not an identifier") def categoryParserOfStack (offset : Nat) (prec : Nat := 0) : Parser := { fn := fun c s => categoryParserOfStackFn offset { c with prec := prec } s } unsafe def evalParserConstUnsafe (declName : Name) : ParserFn := fun ctx s => match ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.Parser declName <|> ctx.env.evalConstCheck Parser ctx.options `Lean.Parser.TrailingParser declName with | Except.ok p => p.fn ctx s | Except.error e => s.mkUnexpectedError s!"error running parser {declName}: {e}" @[implementedBy evalParserConstUnsafe] constant evalParserConst (declName : Name) : ParserFn unsafe def parserOfStackFnUnsafe (offset : Nat) : ParserFn := fun ctx s => let stack := s.stxStack if stack.size < offset + 1 then s.mkUnexpectedError ("failed to determine parser using syntax stack, stack is too small") else match stack.get! (stack.size - offset - 1) with | Syntax.ident (val := parserName) .. => match ctx.resolveName parserName with | [(parserName, [])] => let iniSz := s.stackSize let s := evalParserConst parserName ctx s if !s.hasError && s.stackSize != iniSz + 1 then s.mkUnexpectedError "expected parser to return exactly one syntax object" else s | _::_::_ => s.mkUnexpectedError s!"ambiguous parser name {parserName}" | _ => s.mkUnexpectedError s!"unknown parser {parserName}" | _ => s.mkUnexpectedError ("failed to determine parser using syntax stack, the specified element on the stack is not an identifier") @[implementedBy parserOfStackFnUnsafe] constant parserOfStackFn (offset : Nat) : ParserFn def parserOfStack (offset : Nat) (prec : Nat := 0) : Parser := { fn := fun c s => parserOfStackFn offset { c with prec := prec } s } /-- Run `declName` if possible and inside a quotation, or else `p`. The `ParserInfo` will always be taken from `p`. -/ def evalInsideQuot (declName : Name) (p : Parser) : Parser := { p with fn := fun c s => if c.insideQuot && c.env.contains declName then evalParserConst declName c s else p.fn c s } private def mkResult (s : ParserState) (iniSz : Nat) : ParserState := if s.stackSize == iniSz + 1 then s else s.mkNode nullKind iniSz -- throw error instead? def leadingParserAux (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) : ParserFn := fun c s => let iniSz := s.stackSize let (s, ps) := indexed tables.leadingTable c s behavior let ps := tables.leadingParsers ++ ps if ps.isEmpty then s.mkError (toString kind) else let s := longestMatchFn none ps c s mkResult s iniSz @[inline] def leadingParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := withAntiquotFn antiquotParser (leadingParserAux kind tables behavior) def trailingLoopStep (tables : PrattParsingTables) (left : Syntax) (ps : List (Parser × Nat)) : ParserFn := fun c s => longestMatchFn left (ps ++ tables.trailingParsers) c s private def mkTrailingResult (s : ParserState) (iniSz : Nat) : ParserState := let s := mkResult s iniSz -- Stack contains `[..., left, result]` -- We must remove `left` let result := s.stxStack.back let s := s.popSyntax.popSyntax s.pushSyntax result partial def trailingLoop (tables : PrattParsingTables) (c : ParserContext) (s : ParserState) : ParserState := let (s, ps) := indexed tables.trailingTable c s LeadingIdentBehavior.default if ps.isEmpty && tables.trailingParsers.isEmpty then s -- no available trailing parser else let left := s.stxStack.back let iniSz := s.stackSize let iniPos := s.pos let s := trailingLoopStep tables left ps c s if s.hasError then if s.pos == iniPos then s.restore iniSz iniPos else s else let s := mkTrailingResult s iniSz trailingLoop tables c s /-- Implements a variant of Pratt's algorithm. In Pratt's algorithms tokens have a right and left binding power. In our implementation, parsers have precedence instead. This method selects a parser (or more, via `longestMatchFn`) from `leadingTable` based on the current token. Note that the unindexed `leadingParsers` parsers are also tried. We have the unidexed `leadingParsers` because some parsers do not have a "first token". Example: ``` syntax term:51 "≤" ident "<" term "|" term : index ``` Example, in principle, the set of first tokens for this parser is any token that can start a term, but this set is always changing. Thus, this parsing rule is stored as an unindexed leading parser at `leadingParsers`. After processing the leading parser, we chain with parsers from `trailingTable`/`trailingParsers` that have precedence at least `c.prec` where `c` is the `ParsingContext`. Recall that `c.prec` is set by `categoryParser`. Note that in the original Pratt's algorith, precedences are only checked before calling trailing parsers. In our implementation, leading *and* trailing parsers check the precendece. We claim our algorithm is more flexible, modular and easier to understand. `antiquotParser` should be a `mkAntiquot` parser (or always fail) and is tried before all other parsers. It should not be added to the regular leading parsers because it would heavily overlap with antiquotation parsers nested inside them. -/ @[inline] def prattParser (kind : Name) (tables : PrattParsingTables) (behavior : LeadingIdentBehavior) (antiquotParser : ParserFn) : ParserFn := fun c s => let iniSz := s.stackSize let iniPos := s.pos let s := leadingParser kind tables behavior antiquotParser c s if s.hasError then s else trailingLoop tables c s def fieldIdxFn : ParserFn := fun c s => let iniPos := s.pos let curr := c.input.get iniPos if curr.isDigit && curr != '0' then let s := takeWhileFn (fun c => c.isDigit) c s mkNodeToken fieldIdxKind iniPos c s else s.mkErrorAt "field index" iniPos @[inline] def fieldIdx : Parser := withAntiquot (mkAntiquot "fieldIdx" `fieldIdx) { fn := fieldIdxFn, info := mkAtomicInfo "fieldIdx" } @[inline] def skip : Parser := { fn := fun c s => s, info := epsilonInfo } end Parser namespace Syntax section variable {β : Type} {m : Type → Type} [Monad m] @[inline] def foldArgsM (s : Syntax) (f : Syntax → β → m β) (b : β) : m β := s.getArgs.foldlM (flip f) b @[inline] def foldArgs (s : Syntax) (f : Syntax → β → β) (b : β) : β := Id.run (s.foldArgsM f b) @[inline] def forArgsM (s : Syntax) (f : Syntax → m Unit) : m Unit := s.foldArgsM (fun s _ => f s) () end end Syntax end Lean
fb085b5922d95166723578bdff15d28fe2dbf098
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Level.lean
c52afa33d027bc74b4222e99ab011a02c3a76199
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
21,862
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Std.Data.HashMap import Std.Data.HashSet import Std.Data.PersistentHashMap import Std.Data.PersistentHashSet import Lean.Hygiene import Lean.Data.Name import Lean.Data.Format def Nat.imax (n m : Nat) : Nat := if m = 0 then 0 else Nat.max n m namespace Lean /-- Cached hash code, cached results, and other data for `Level`. hash : 32-bits hasMVar : 1-bit hasParam : 1-bit depth : 24-bits -/ def Level.Data := UInt64 instance : Inhabited Level.Data := inferInstanceAs (Inhabited UInt64) def Level.Data.hash (c : Level.Data) : UInt64 := c.toUInt32.toUInt64 instance : BEq Level.Data := ⟨fun (a b : UInt64) => a == b⟩ def Level.Data.depth (c : Level.Data) : UInt32 := (c.shiftRight 40).toUInt32 def Level.Data.hasMVar (c : Level.Data) : Bool := ((c.shiftRight 32).land 1) == 1 def Level.Data.hasParam (c : Level.Data) : Bool := ((c.shiftRight 33).land 1) == 1 def Level.mkData (h : UInt64) (depth : Nat := 0) (hasMVar hasParam : Bool := false) : Level.Data := if depth > Nat.pow 2 24 - 1 then panic! "universe level depth is too big" else let r : UInt64 := h.toUInt32.toUInt64 + hasMVar.toUInt64.shiftLeft 32 + hasParam.toUInt64.shiftLeft 33 + depth.toUInt64.shiftLeft 40 r instance : Repr Level.Data where reprPrec v prec := Id.run do let mut r := "Level.mkData " ++ toString v.hash if v.depth != 0 then r := r ++ " (depth := " ++ toString v.depth ++ ")" if v.hasMVar then r := r ++ " (hasMVar := " ++ toString v.hasMVar ++ ")" if v.hasParam then r := r ++ " (hasParam := " ++ toString v.hasParam ++ ")" Repr.addAppParen r prec open Level /-- Universe level metavariable Id -/ structure LevelMVarId where name : Name deriving Inhabited, BEq, Hashable, Repr /-- Short for `LevelMVarId` -/ abbrev LMVarId := LevelMVarId instance : Repr LMVarId where reprPrec n p := reprPrec n.name p def LMVarIdSet := Std.RBTree LMVarId (Name.quickCmp ·.name ·.name) deriving Inhabited, EmptyCollection instance : ForIn m LMVarIdSet LMVarId := inferInstanceAs (ForIn _ (Std.RBTree ..) ..) def LMVarIdMap (α : Type) := Std.RBMap LMVarId α (Name.quickCmp ·.name ·.name) instance : EmptyCollection (LMVarIdMap α) := inferInstanceAs (EmptyCollection (Std.RBMap ..)) instance : ForIn m (LMVarIdMap α) (LMVarId × α) := inferInstanceAs (ForIn _ (Std.RBMap ..) ..) instance : Inhabited (LMVarIdMap α) where default := {} inductive Level where | zero : Level | succ : Level → Level | max : Level → Level → Level | imax : Level → Level → Level | param : Name → Level | mvar : LMVarId → Level with @[computedField] data : Level → Data | .zero => mkData 2221 0 false false | .mvar mvarId => mkData (mixHash 2237 <| hash mvarId) 0 true false | .param name => mkData (mixHash 2239 <| hash name) 0 false true | .succ u => mkData (mixHash 2243 <| u.data.hash) (u.data.depth.toNat + 1) u.data.hasMVar u.data.hasParam | .max u v => mkData (mixHash 2251 <| mixHash (u.data.hash) (v.data.hash)) (Nat.max u.data.depth.toNat v.data.depth.toNat + 1) (u.data.hasMVar || v.data.hasMVar) (u.data.hasParam || v.data.hasParam) | .imax u v => mkData (mixHash 2267 <| mixHash (u.data.hash) (v.data.hash)) (Nat.max u.data.depth.toNat v.data.depth.toNat + 1) (u.data.hasMVar || v.data.hasMVar) (u.data.hasParam || v.data.hasParam) deriving Inhabited, Repr namespace Level protected def hash (u : Level) : UInt64 := u.data.hash instance : Hashable Level := ⟨Level.hash⟩ def depth (u : Level) : Nat := u.data.depth.toNat def hasMVar (u : Level) : Bool := u.data.hasMVar def hasParam (u : Level) : Bool := u.data.hasParam @[export lean_level_hash] def hashEx (u : Level) : UInt32 := hash u |>.toUInt32 @[export lean_level_has_mvar] def hasMVarEx : Level → Bool := hasMVar @[export lean_level_has_param] def hasParamEx : Level → Bool := hasParam @[export lean_level_depth] def depthEx (u : Level) : UInt32 := u.data.depth end Level def levelZero := Level.zero def mkLevelMVar (mvarId : LMVarId) := Level.mvar mvarId def mkLevelParam (name : Name) := Level.param name def mkLevelSucc (u : Level) := Level.succ u def mkLevelMax (u v : Level) := Level.max u v def mkLevelIMax (u v : Level) := Level.imax u v def levelOne := mkLevelSucc levelZero @[export lean_level_mk_zero] def mkLevelZeroEx : Unit → Level := fun _ => levelZero @[export lean_level_mk_succ] def mkLevelSuccEx : Level → Level := mkLevelSucc @[export lean_level_mk_mvar] def mkLevelMVarEx : LMVarId → Level := mkLevelMVar @[export lean_level_mk_param] def mkLevelParamEx : Name → Level := mkLevelParam @[export lean_level_mk_max] def mkLevelMaxEx : Level → Level → Level := mkLevelMax @[export lean_level_mk_imax] def mkLevelIMaxEx : Level → Level → Level := mkLevelIMax namespace Level def isZero : Level → Bool | zero => true | _ => false def isSucc : Level → Bool | succ .. => true | _ => false def isMax : Level → Bool | max .. => true | _ => false def isIMax : Level → Bool | imax .. => true | _ => false def isMaxIMax : Level → Bool | max .. => true | imax .. => true | _ => false def isParam : Level → Bool | param .. => true | _ => false def isMVar : Level → Bool | mvar .. => true | _ => false def mvarId! : Level → LMVarId | mvar mvarId => mvarId | _ => panic! "metavariable expected" /-- If result is true, then forall assignments `A` which assigns all parameters and metavariables occuring in `l`, `l[A] != zero` -/ def isNeverZero : Level → Bool | zero => false | param .. => false | mvar .. => false | succ .. => true | max l₁ l₂ => isNeverZero l₁ || isNeverZero l₂ | imax _ l₂ => isNeverZero l₂ def ofNat : Nat → Level | 0 => levelZero | n+1 => mkLevelSucc (ofNat n) def addOffsetAux : Nat → Level → Level | 0, u => u | (n+1), u => addOffsetAux n (mkLevelSucc u) def addOffset (u : Level) (n : Nat) : Level := u.addOffsetAux n def isExplicit : Level → Bool | zero => true | succ u => !u.hasMVar && !u.hasParam && isExplicit u | _ => false def getOffsetAux : Level → Nat → Nat | succ u , r => getOffsetAux u (r+1) | _, r => r def getOffset (lvl : Level) : Nat := getOffsetAux lvl 0 def getLevelOffset : Level → Level | succ u => getLevelOffset u | u => u def toNat (lvl : Level) : Option Nat := match lvl.getLevelOffset with | zero => lvl.getOffset | _ => none @[extern "lean_level_eq"] protected opaque beq (a : @& Level) (b : @& Level) : Bool instance : BEq Level := ⟨Level.beq⟩ /-- `occurs u l` return `true` iff `u` occurs in `l`. -/ def occurs : Level → Level → Bool | u, v@(succ v₁ ) => u == v || occurs u v₁ | u, v@(max v₁ v₂ ) => u == v || occurs u v₁ || occurs u v₂ | u, v@(imax v₁ v₂ ) => u == v || occurs u v₁ || occurs u v₂ | u, v => u == v def ctorToNat : Level → Nat | zero .. => 0 | param .. => 1 | mvar .. => 2 | succ .. => 3 | max .. => 4 | imax .. => 5 /- TODO: use well founded recursion. -/ partial def normLtAux : Level → Nat → Level → Nat → Bool | succ l₁, k₁, l₂, k₂ => normLtAux l₁ (k₁+1) l₂ k₂ | l₁, k₁, succ l₂, k₂ => normLtAux l₁ k₁ l₂ (k₂+1) | l₁@(max l₁₁ l₁₂), k₁, l₂@(max l₂₁ l₂₂), k₂ => if l₁ == l₂ then k₁ < k₂ else if l₁₁ != l₂₁ then normLtAux l₁₁ 0 l₂₁ 0 else normLtAux l₁₂ 0 l₂₂ 0 | l₁@(imax l₁₁ l₁₂), k₁, l₂@(imax l₂₁ l₂₂), k₂ => if l₁ == l₂ then k₁ < k₂ else if l₁₁ != l₂₁ then normLtAux l₁₁ 0 l₂₁ 0 else normLtAux l₁₂ 0 l₂₂ 0 | param n₁, k₁, param n₂, k₂ => if n₁ == n₂ then k₁ < k₂ else Name.lt n₁ n₂ -- use `Name.lt` because it is lexicographical /- We also use `Name.lt` in the following case to make sure universe parameters in a declaration are not affected by shifted indices. We used to use `Name.quickLt` which is not stable over shifted indices (the hashcodes change), and changes to the elaborator could affect the universe parameters and break code that relies on an explicit order. Example: test `tests/lean/343.lean`. -/ | mvar n₁, k₁, mvar n₂, k₂ => if n₁ == n₂ then k₁ < k₂ else Name.lt n₁.name n₂.name | l₁, k₁, l₂, k₂ => if l₁ == l₂ then k₁ < k₂ else ctorToNat l₁ < ctorToNat l₂ /-- A total order on level expressions that has the following properties - `succ l` is an immediate successor of `l`. - `zero` is the minimal element. This total order is used in the normalization procedure. -/ def normLt (l₁ l₂ : Level) : Bool := normLtAux l₁ 0 l₂ 0 private def isAlreadyNormalizedCheap : Level → Bool | zero => true | param _ => true | mvar _ => true | succ u => isAlreadyNormalizedCheap u | _ => false /- Auxiliary function used at `normalize` -/ private def mkIMaxAux : Level → Level → Level | _, zero => zero | zero, u => u | u₁, u₂ => if u₁ == u₂ then u₁ else mkLevelIMax u₁ u₂ /- Auxiliary function used at `normalize` -/ @[specialize] private partial def getMaxArgsAux (normalize : Level → Level) : Level → Bool → Array Level → Array Level | max l₁ l₂, alreadyNormalized, lvls => getMaxArgsAux normalize l₂ alreadyNormalized (getMaxArgsAux normalize l₁ alreadyNormalized lvls) | l, false, lvls => getMaxArgsAux normalize (normalize l) true lvls | l, true, lvls => lvls.push l private def accMax (result : Level) (prev : Level) (offset : Nat) : Level := if result.isZero then prev.addOffset offset else mkLevelMax result (prev.addOffset offset) /- Auxiliary function used at `normalize`. Remarks: - `lvls` are sorted using `normLt` - `extraK` is the outer offset of the `max` term. We will push it inside. - `i` is the current array index - `prev + prevK` is the "previous" level that has not been added to `result` yet. - `result` is the accumulator -/ private partial def mkMaxAux (lvls : Array Level) (extraK : Nat) (i : Nat) (prev : Level) (prevK : Nat) (result : Level) : Level := if h : i < lvls.size then let lvl := lvls.get ⟨i, h⟩ let curr := lvl.getLevelOffset let currK := lvl.getOffset if curr == prev then mkMaxAux lvls extraK (i+1) curr currK result else mkMaxAux lvls extraK (i+1) curr currK (accMax result prev (extraK + prevK)) else accMax result prev (extraK + prevK) /- Auxiliary function for `normalize`. It assumes `lvls` has been sorted using `normLt`. It finds the first position that is not an explicit universe. -/ private partial def skipExplicit (lvls : Array Level) (i : Nat) : Nat := if h : i < lvls.size then let lvl := lvls.get ⟨i, h⟩ if lvl.getLevelOffset.isZero then skipExplicit lvls (i+1) else i else i /-- Auxiliary function for `normalize`. `maxExplicit` is the maximum explicit universe level at `lvls`. Return true if it finds a level with offset ≥ maxExplicit. `i` starts at the first non explicit level. It assumes `lvls` has been sorted using `normLt`. -/ private partial def isExplicitSubsumedAux (lvls : Array Level) (maxExplicit : Nat) (i : Nat) : Bool := if h : i < lvls.size then let lvl := lvls.get ⟨i, h⟩ if lvl.getOffset ≥ maxExplicit then true else isExplicitSubsumedAux lvls maxExplicit (i+1) else false /- Auxiliary function for `normalize`. See `isExplicitSubsumedAux` -/ private def isExplicitSubsumed (lvls : Array Level) (firstNonExplicit : Nat) : Bool := if firstNonExplicit == 0 then false else let max := (lvls.get! (firstNonExplicit - 1)).getOffset; isExplicitSubsumedAux lvls max firstNonExplicit partial def normalize (l : Level) : Level := if isAlreadyNormalizedCheap l then l else let k := l.getOffset let u := l.getLevelOffset match u with | max l₁ l₂ => let lvls := getMaxArgsAux normalize l₁ false #[] let lvls := getMaxArgsAux normalize l₂ false lvls let lvls := lvls.qsort normLt let firstNonExplicit := skipExplicit lvls 0 let i := if isExplicitSubsumed lvls firstNonExplicit then firstNonExplicit else firstNonExplicit - 1 let lvl₁ := lvls[i]! let prev := lvl₁.getLevelOffset let prevK := lvl₁.getOffset mkMaxAux lvls k (i+1) prev prevK levelZero | imax l₁ l₂ => if l₂.isNeverZero then addOffset (normalize (mkLevelMax l₁ l₂)) k else let l₁ := normalize l₁ let l₂ := normalize l₂ addOffset (mkIMaxAux l₁ l₂) k | _ => unreachable! /-- Return true if `u` and `v` denote the same level. Check is currently incomplete. -/ def isEquiv (u v : Level) : Bool := u == v || u.normalize == v.normalize /-- Reduce (if possible) universe level by 1 -/ def dec : Level → Option Level | zero => none | param _ => none | mvar _ => none | succ l => l | max l₁ l₂ => return mkLevelMax (← dec l₁) (← dec l₂) /- Remark: `mkLevelMax` in the following line is not a typo. If `dec l₂` succeeds, then `imax l₁ l₂` is equivalent to `max l₁ l₂`. -/ | imax l₁ l₂ => return mkLevelMax (← dec l₁) (← dec l₂) /- Level to Format/Syntax -/ namespace PP inductive Result where | leaf : Name → Result | num : Nat → Result | offset : Result → Nat → Result | maxNode : List Result → Result | imaxNode : List Result → Result def Result.succ : Result → Result | Result.offset f k => Result.offset f (k+1) | Result.num k => Result.num (k+1) | f => Result.offset f 1 def Result.max : Result → Result → Result | f, Result.maxNode Fs => Result.maxNode (f::Fs) | f₁, f₂ => Result.maxNode [f₁, f₂] def Result.imax : Result → Result → Result | f, Result.imaxNode Fs => Result.imaxNode (f::Fs) | f₁, f₂ => Result.imaxNode [f₁, f₂] def toResult : Level → Result | zero => Result.num 0 | succ l => Result.succ (toResult l) | max l₁ l₂ => Result.max (toResult l₁) (toResult l₂) | imax l₁ l₂ => Result.imax (toResult l₁) (toResult l₂) | param n => Result.leaf n | mvar n => let n := n.name.replacePrefix `_uniq (Name.mkSimple "?u"); Result.leaf n private def parenIfFalse : Format → Bool → Format | f, true => f | f, false => f.paren mutual private partial def Result.formatLst : List Result → Format | [] => Format.nil | r::rs => Format.line ++ format r false ++ formatLst rs partial def Result.format : Result → Bool → Format | Result.leaf n, _ => Std.format n | Result.num k, _ => toString k | Result.offset f 0, r => format f r | Result.offset f (k+1), r => let f' := format f false; parenIfFalse (f' ++ "+" ++ Std.format (k+1)) r | Result.maxNode fs, r => parenIfFalse (Format.group <| "max" ++ formatLst fs) r | Result.imaxNode fs, r => parenIfFalse (Format.group <| "imax" ++ formatLst fs) r end protected partial def Result.quote (r : Result) (prec : Nat) : Syntax.Level := let addParen (s : Syntax.Level) := if prec > 0 then Unhygienic.run `(level| ( $s )) else s match r with | Result.leaf n => Unhygienic.run `(level| $(mkIdent n):ident) | Result.num k => Unhygienic.run `(level| $(quote k):num) | Result.offset r 0 => Result.quote r prec | Result.offset r (k+1) => addParen <| Unhygienic.run `(level| $(Result.quote r 65) + $(quote (k+1)):num) | Result.maxNode rs => addParen <| Unhygienic.run `(level| max $(rs.toArray.map (Result.quote · max_prec))*) | Result.imaxNode rs => addParen <| Unhygienic.run `(level| imax $(rs.toArray.map (Result.quote · max_prec))*) end PP protected def format (u : Level) : Format := (PP.toResult u).format true instance : ToFormat Level where format u := Level.format u instance : ToString Level where toString u := Format.pretty (Level.format u) protected def quote (u : Level) (prec : Nat := 0) : Syntax.Level := (PP.toResult u).quote prec instance : Quote Level `level where quote := Level.quote end Level @[inline] private def mkLevelMaxCore (u v : Level) (elseK : Unit → Level) : Level := let subsumes (u v : Level) : Bool := if v.isExplicit && u.getOffset ≥ v.getOffset then true else match u with | Level.max u₁ u₂ => v == u₁ || v == u₂ | _ => false if u == v then u else if u.isZero then v else if v.isZero then u else if subsumes u v then u else if subsumes v u then v else if u.getLevelOffset == v.getLevelOffset then if u.getOffset ≥ v.getOffset then u else v else elseK () /- Similar to `mkLevelMax`, but applies cheap simplifications -/ def mkLevelMax' (u v : Level) : Level := mkLevelMaxCore u v fun _ => mkLevelMax u v def simpLevelMax' (u v : Level) (d : Level) : Level := mkLevelMaxCore u v fun _ => d @[inline] private def mkLevelIMaxCore (u v : Level) (elseK : Unit → Level) : Level := if v.isNeverZero then mkLevelMax' u v else if v.isZero then v else if u.isZero then v else if u == v then u else elseK () /- Similar to `mkLevelIMax`, but applies cheap simplifications -/ def mkLevelIMax' (u v : Level) : Level := mkLevelIMaxCore u v fun _ => mkLevelIMax u v def simpLevelIMax' (u v : Level) (d : Level) := mkLevelIMaxCore u v fun _ => d namespace Level /-! The update functions try to avoid allocating new values using pointer equality. Note that if the `update*!` functions are used under a match-expression, the compiler will eliminate the double-match. -/ @[inline] private unsafe def updateSucc!Impl (lvl : Level) (newLvl : Level) : Level := match lvl with | succ l => if ptrEq l newLvl then lvl else mkLevelSucc newLvl | _ => panic! "succ level expected" @[implementedBy updateSucc!Impl] def updateSucc! (lvl : Level) (newLvl : Level) : Level := match lvl with | succ _ => mkLevelSucc newLvl | _ => panic! "succ level expected" @[inline] private unsafe def updateMax!Impl (lvl : Level) (newLhs : Level) (newRhs : Level) : Level := match lvl with | max lhs rhs => if ptrEq lhs newLhs && ptrEq rhs newRhs then simpLevelMax' newLhs newRhs lvl else mkLevelMax' newLhs newRhs | _ => panic! "max level expected" @[implementedBy updateMax!Impl] def updateMax! (lvl : Level) (newLhs : Level) (newRhs : Level) : Level := match lvl with | max _ _ => mkLevelMax' newLhs newRhs | _ => panic! "max level expected" @[inline] private unsafe def updateIMax!Impl (lvl : Level) (newLhs : Level) (newRhs : Level) : Level := match lvl with | imax lhs rhs => if ptrEq lhs newLhs && ptrEq rhs newRhs then simpLevelIMax' newLhs newRhs lvl else mkLevelIMax' newLhs newRhs | _ => panic! "imax level expected" @[implementedBy updateIMax!Impl] def updateIMax! (lvl : Level) (newLhs : Level) (newRhs : Level) : Level := match lvl with | imax _ _ => mkLevelIMax' newLhs newRhs | _ => panic! "imax level expected" def mkNaryMax : List Level → Level | [] => levelZero | [u] => u | u::us => mkLevelMax' u (mkNaryMax us) /- Level to Format -/ @[specialize] def instantiateParams (s : Name → Option Level) : Level → Level | u@(zero) => u | u@(succ v) => if u.hasParam then u.updateSucc! (instantiateParams s v) else u | u@(max v₁ v₂) => if u.hasParam then u.updateMax! (instantiateParams s v₁) (instantiateParams s v₂) else u | u@(imax v₁ v₂) => if u.hasParam then u.updateIMax! (instantiateParams s v₁) (instantiateParams s v₂) else u | u@(param n) => match s n with | some u' => u' | none => u | u => u def geq (u v : Level) : Bool := go u.normalize v.normalize where go (u v : Level) : Bool := u == v || match u, v with | _, zero => true | u, max v₁ v₂ => go u v₁ && go u v₂ | max u₁ u₂, v => go u₁ v || go u₂ v | u, imax v₁ v₂ => go u v₁ && go u v₂ | imax _ u₂, v => go u₂ v | succ u, succ v => go u v | _, _ => let v' := v.getLevelOffset (u.getLevelOffset == v' || v'.isZero) && u.getOffset ≥ v.getOffset termination_by _ u v => (u, v) end Level open Std (HashMap HashSet PHashMap PHashSet) abbrev LevelMap (α : Type) := HashMap Level α abbrev PersistentLevelMap (α : Type) := PHashMap Level α abbrev LevelSet := HashSet Level abbrev PersistentLevelSet := PHashSet Level abbrev PLevelSet := PersistentLevelSet def Level.collectMVars (u : Level) (s : LMVarIdSet := {}) : LMVarIdSet := match u with | succ v => collectMVars v s | max u v => collectMVars u (collectMVars v s) | imax u v => collectMVars u (collectMVars v s) | mvar n => s.insert n | _ => s def Level.find? (u : Level) (p : Level → Bool) : Option Level := let rec visit (u : Level) : Option Level := if p u then return u else match u with | succ v => visit v | max u v => visit u <|> visit v | imax u v => visit u <|> visit v | _ => failure visit u def Level.any (u : Level) (p : Level → Bool) : Bool := u.find? p |>.isSome end Lean abbrev Nat.toLevel (n : Nat) : Lean.Level := Lean.Level.ofNat n
2fbea9c0c2165db30c40a27360311ba9b7b138c1
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/ring_theory/ideal/operations.lean
30a2357306cf9e77e67eac127c51b97cb2732e47
[ "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
66,490
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.operations import algebra.algebra.tower import data.equiv.ring import data.nat.choose.sum import ring_theory.ideal.basic import ring_theory.non_zero_divisors /-! # More operations on modules and ideals -/ universes u v w x open_locale big_operators namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] instance has_scalar' : has_scalar (ideal R) (submodule R M) := ⟨λ I N, ⨆ r : I, N.map (r.1 • linear_map.id)⟩ /-- `N.annihilator` is the ideal of all elements `r : R` such that `r • N = 0`. -/ def annihilator (N : submodule R M) : ideal R := (linear_map.lsmul R N).ker /-- `N.colon P` is the ideal of all elements `r : R` such that `r • P ⊆ N`. -/ def colon (N P : submodule R M) : ideal R := annihilator (P.map N.mkq) variables {I J : ideal R} {N N₁ N₂ P P₁ P₂ : submodule R M} theorem mem_annihilator {r} : r ∈ N.annihilator ↔ ∀ n ∈ N, r • n = (0:M) := ⟨λ hr n hn, congr_arg subtype.val (linear_map.ext_iff.1 (linear_map.mem_ker.1 hr) ⟨n, hn⟩), λ h, linear_map.mem_ker.2 $ linear_map.ext $ λ n, subtype.eq $ h n.1 n.2⟩ theorem mem_annihilator' {r} : r ∈ N.annihilator ↔ N ≤ comap (r • linear_map.id) ⊥ := mem_annihilator.trans ⟨λ H n hn, (mem_bot R).2 $ H n hn, λ H n hn, (mem_bot R).1 $ H hn⟩ theorem annihilator_bot : (⊥ : submodule R M).annihilator = ⊤ := (ideal.eq_top_iff_one _).2 $ mem_annihilator'.2 bot_le theorem annihilator_eq_top_iff : N.annihilator = ⊤ ↔ N = ⊥ := ⟨λ H, eq_bot_iff.2 $ λ (n:M) hn, (mem_bot R).2 $ one_smul R n ▸ mem_annihilator.1 ((ideal.eq_top_iff_one _).1 H) n hn, λ H, H.symm ▸ annihilator_bot⟩ theorem annihilator_mono (h : N ≤ P) : P.annihilator ≤ N.annihilator := λ r hrp, mem_annihilator.2 $ λ n hn, mem_annihilator.1 hrp n $ h hn theorem annihilator_supr (ι : Sort w) (f : ι → submodule R M) : (annihilator ⨆ i, f i) = ⨅ i, annihilator (f i) := le_antisymm (le_infi $ λ i, annihilator_mono $ le_supr _ _) (λ r H, mem_annihilator'.2 $ supr_le $ λ i, have _ := (mem_infi _).1 H i, mem_annihilator'.1 this) theorem mem_colon {r} : r ∈ N.colon P ↔ ∀ p ∈ P, r • p ∈ N := mem_annihilator.trans ⟨λ H p hp, (quotient.mk_eq_zero N).1 (H (quotient.mk p) (mem_map_of_mem hp)), λ H m ⟨p, hp, hpm⟩, hpm ▸ (N.mkq).map_smul r p ▸ (quotient.mk_eq_zero N).2 $ H p hp⟩ theorem mem_colon' {r} : r ∈ N.colon P ↔ P ≤ comap (r • linear_map.id) N := mem_colon theorem colon_mono (hn : N₁ ≤ N₂) (hp : P₁ ≤ P₂) : N₁.colon P₂ ≤ N₂.colon P₁ := λ r hrnp, mem_colon.2 $ λ p₁ hp₁, hn $ mem_colon.1 hrnp p₁ $ hp hp₁ theorem infi_colon_supr (ι₁ : Sort w) (f : ι₁ → submodule R M) (ι₂ : Sort x) (g : ι₂ → submodule R M) : (⨅ i, f i).colon (⨆ j, g j) = ⨅ i j, (f i).colon (g j) := le_antisymm (le_infi $ λ i, le_infi $ λ j, colon_mono (infi_le _ _) (le_supr _ _)) (λ r H, mem_colon'.2 $ supr_le $ λ j, map_le_iff_le_comap.1 $ le_infi $ λ i, map_le_iff_le_comap.2 $ mem_colon'.1 $ have _ := ((mem_infi _).1 H i), have _ := ((mem_infi _).1 this j), this) theorem smul_mem_smul {r} {n} (hr : r ∈ I) (hn : n ∈ N) : r • n ∈ I • N := (le_supr _ ⟨r, hr⟩ : _ ≤ I • N) ⟨n, hn, rfl⟩ theorem smul_le {P : submodule R M} : I • N ≤ P ↔ ∀ (r ∈ I) (n ∈ N), r • n ∈ P := ⟨λ H r hr n hn, H $ smul_mem_smul hr hn, λ H, supr_le $ λ r, map_le_iff_le_comap.2 $ λ n hn, H r.1 r.2 n hn⟩ @[elab_as_eliminator] theorem smul_induction_on {p : M → Prop} {x} (H : x ∈ I • N) (Hb : ∀ (r ∈ I) (n ∈ N), p (r • n)) (H0 : p 0) (H1 : ∀ x y, p x → p y → p (x + y)) (H2 : ∀ (c:R) n, p n → p (c • n)) : p x := (@smul_le _ _ _ _ _ _ _ ⟨p, H0, H1, H2⟩).2 Hb H theorem mem_smul_span_singleton {I : ideal R} {m : M} {x : M} : x ∈ I • span R ({m} : set M) ↔ ∃ y ∈ I, y • m = x := ⟨λ hx, smul_induction_on hx (λ r hri n hnm, let ⟨s, hs⟩ := mem_span_singleton.1 hnm in ⟨r * s, I.mul_mem_right _ hri, hs ▸ mul_smul r s m⟩) ⟨0, I.zero_mem, by rw [zero_smul]⟩ (λ m1 m2 ⟨y1, hyi1, hy1⟩ ⟨y2, hyi2, hy2⟩, ⟨y1 + y2, I.add_mem hyi1 hyi2, by rw [add_smul, hy1, hy2]⟩) (λ c r ⟨y, hyi, hy⟩, ⟨c * y, I.mul_mem_left _ hyi, by rw [mul_smul, hy]⟩), λ ⟨y, hyi, hy⟩, hy ▸ smul_mem_smul hyi (subset_span $ set.mem_singleton m)⟩ theorem smul_le_right : I • N ≤ N := smul_le.2 $ λ r hr n, N.smul_mem r theorem smul_mono (hij : I ≤ J) (hnp : N ≤ P) : I • N ≤ J • P := smul_le.2 $ λ r hr n hn, smul_mem_smul (hij hr) (hnp hn) theorem smul_mono_left (h : I ≤ J) : I • N ≤ J • N := smul_mono h (le_refl N) theorem smul_mono_right (h : N ≤ P) : I • N ≤ I • P := smul_mono (le_refl I) h variables (I J N P) @[simp] theorem smul_bot : I • (⊥ : submodule R M) = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hri s hsb, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hsb).symm ▸ smul_zero r @[simp] theorem bot_smul : (⊥ : ideal R) • N = ⊥ := eq_bot_iff.2 $ smul_le.2 $ λ r hrb s hsi, (submodule.mem_bot R).2 $ ((submodule.mem_bot R).1 hrb).symm ▸ zero_smul _ s @[simp] theorem top_smul : (⊤ : ideal R) • N = N := le_antisymm smul_le_right $ λ r hri, one_smul R r ▸ smul_mem_smul mem_top hri theorem smul_sup : I • (N ⊔ P) = I • N ⊔ I • P := le_antisymm (smul_le.2 $ λ r hri m hmnp, let ⟨n, hn, p, hp, hnpm⟩ := mem_sup.1 hmnp in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hri hp, hnpm ▸ (smul_add _ _ _).symm⟩) (sup_le (smul_mono_right le_sup_left) (smul_mono_right le_sup_right)) theorem sup_smul : (I ⊔ J) • N = I • N ⊔ J • N := le_antisymm (smul_le.2 $ λ r hrij n hn, let ⟨ri, hri, rj, hrj, hrijr⟩ := mem_sup.1 hrij in mem_sup.2 ⟨_, smul_mem_smul hri hn, _, smul_mem_smul hrj hn, hrijr ▸ (add_smul _ _ _).symm⟩) (sup_le (smul_mono_left le_sup_left) (smul_mono_left le_sup_right)) protected theorem smul_assoc : (I • J) • N = I • (J • N) := le_antisymm (smul_le.2 $ λ rs hrsij t htn, smul_induction_on hrsij (λ r hr s hs, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ smul_mem_smul hr (smul_mem_smul hs htn)) ((zero_smul R t).symm ▸ submodule.zero_mem _) (λ x y, (add_smul x y t).symm ▸ submodule.add_mem _) (λ r s h, (@smul_eq_mul R _ r s).symm ▸ smul_smul r s t ▸ submodule.smul_mem _ _ h)) (smul_le.2 $ λ r hr sn hsn, suffices J • N ≤ submodule.comap (r • linear_map.id) ((I • J) • N), from this hsn, smul_le.2 $ λ s hs n hn, show r • (s • n) ∈ (I • J) • N, from mul_smul r s n ▸ smul_mem_smul (smul_mem_smul hr hs) hn) variables (S : set R) (T : set M) theorem span_smul_span : (ideal.span S) • (span R T) = span R (⋃ (s ∈ S) (t ∈ T), {s • t}) := le_antisymm (smul_le.2 $ λ r hrS n hnT, span_induction hrS (λ r hrS, span_induction hnT (λ n hnT, subset_span $ set.mem_bUnion hrS $ set.mem_bUnion hnT $ set.mem_singleton _) ((smul_zero r : r • 0 = (0:M)).symm ▸ submodule.zero_mem _) (λ x y, (smul_add r x y).symm ▸ submodule.add_mem _) (λ c m, by rw [smul_smul, mul_comm, mul_smul]; exact submodule.smul_mem _ _)) ((zero_smul R n).symm ▸ submodule.zero_mem _) (λ r s, (add_smul r s n).symm ▸ submodule.add_mem _) (λ c r, by rw [smul_eq_mul, mul_smul]; exact submodule.smul_mem _ _)) $ span_le.2 $ set.bUnion_subset $ λ r hrS, set.bUnion_subset $ λ n hnT, set.singleton_subset_iff.2 $ smul_mem_smul (subset_span hrS) (subset_span hnT) variables {M' : Type w} [add_comm_group M'] [module R M'] theorem map_smul'' (f : M →ₗ[R] M') : (I • N).map f = I • N.map f := le_antisymm (map_le_iff_le_comap.2 $ smul_le.2 $ λ r hr n hn, show f (r • n) ∈ I • N.map f, from (f.map_smul r n).symm ▸ smul_mem_smul hr (mem_map_of_mem hn)) $ smul_le.2 $ λ r hr n hn, let ⟨p, hp, hfp⟩ := mem_map.1 hn in hfp ▸ f.map_smul r p ▸ mem_map_of_mem (smul_mem_smul hr hp) end submodule namespace ideal section chinese_remainder variables {R : Type u} [comm_ring R] {ι : Type v} theorem exists_sub_one_mem_and_mem (s : finset ι) {f : ι → ideal R} (hf : ∀ i ∈ s, ∀ j ∈ s, i ≠ j → f i ⊔ f j = ⊤) (i : ι) (his : i ∈ s) : ∃ r : R, r - 1 ∈ f i ∧ ∀ j ∈ s, j ≠ i → r ∈ f j := begin have : ∀ j ∈ s, j ≠ i → ∃ r : R, ∃ H : r - 1 ∈ f i, r ∈ f j, { intros j hjs hji, specialize hf i his j hjs hji.symm, rw [eq_top_iff_one, submodule.mem_sup] at hf, rcases hf with ⟨r, hri, s, hsj, hrs⟩, refine ⟨1 - r, _, _⟩, { rw [sub_right_comm, sub_self, zero_sub], exact (f i).neg_mem hri }, { rw [← hrs, add_sub_cancel'], exact hsj } }, classical, have : ∃ g : ι → R, (∀ j, g j - 1 ∈ f i) ∧ ∀ j ∈ s, j ≠ i → g j ∈ f j, { choose g hg1 hg2, refine ⟨λ j, if H : j ∈ s ∧ j ≠ i then g j H.1 H.2 else 1, λ j, _, λ j, _⟩, { split_ifs with h, { apply hg1 }, rw sub_self, exact (f i).zero_mem }, { intros hjs hji, rw dif_pos, { apply hg2 }, exact ⟨hjs, hji⟩ } }, rcases this with ⟨g, hgi, hgj⟩, use (∏ x in s.erase i, g x), split, { rw [← quotient.eq, ring_hom.map_one, ring_hom.map_prod], apply finset.prod_eq_one, intros, rw [← ring_hom.map_one, quotient.eq], apply hgi }, intros j hjs hji, rw [← quotient.eq_zero_iff_mem, ring_hom.map_prod], refine finset.prod_eq_zero (finset.mem_erase_of_ne_of_mem hji hjs) _, rw quotient.eq_zero_iff_mem, exact hgj j hjs hji end theorem exists_sub_mem [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) (g : ι → R) : ∃ r : R, ∀ i, r - g i ∈ f i := begin have : ∃ φ : ι → R, (∀ i, φ i - 1 ∈ f i) ∧ (∀ i j, i ≠ j → φ i ∈ f j), { have := exists_sub_one_mem_and_mem (finset.univ : finset ι) (λ i _ j _ hij, hf i j hij), choose φ hφ, existsi λ i, φ i (finset.mem_univ i), exact ⟨λ i, (hφ i _).1, λ i j hij, (hφ i _).2 j (finset.mem_univ j) hij.symm⟩ }, rcases this with ⟨φ, hφ1, hφ2⟩, use ∑ i, g i * φ i, intros i, rw [← quotient.eq, ring_hom.map_sum], refine eq.trans (finset.sum_eq_single i _ _) _, { intros j _ hji, rw quotient.eq_zero_iff_mem, exact (f i).mul_mem_left _ (hφ2 j i hji) }, { intros hi, exact (hi $ finset.mem_univ i).elim }, specialize hφ1 i, rw [← quotient.eq, ring_hom.map_one] at hφ1, rw [ring_hom.map_mul, hφ1, mul_one] end /-- The homomorphism from `R/(⋂ i, f i)` to `∏ i, (R / f i)` featured in the Chinese Remainder Theorem. It is bijective if the ideals `f i` are comaximal. -/ def quotient_inf_to_pi_quotient (f : ι → ideal R) : (⨅ i, f i).quotient →+* Π i, (f i).quotient := begin refine quotient.lift (⨅ i, f i) _ _, { convert @@pi.ring_hom (λ i, quotient (f i)) (λ i, ring.to_semiring) ring.to_semiring (λ i, quotient.mk (f i)) }, { intros r hr, rw submodule.mem_infi at hr, ext i, exact quotient.eq_zero_iff_mem.2 (hr i) } end theorem quotient_inf_to_pi_quotient_bijective [fintype ι] {f : ι → ideal R} (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : function.bijective (quotient_inf_to_pi_quotient f) := ⟨λ x y, quotient.induction_on₂' x y $ λ r s hrs, quotient.eq.2 $ (submodule.mem_infi _).2 $ λ i, quotient.eq.1 $ show quotient_inf_to_pi_quotient f (quotient.mk' r) i = _, by rw hrs; refl, λ g, let ⟨r, hr⟩ := exists_sub_mem hf (λ i, quotient.out' (g i)) in ⟨quotient.mk _ r, funext $ λ i, quotient.out_eq' (g i) ▸ quotient.eq.2 (hr i)⟩⟩ /-- Chinese Remainder Theorem. Eisenbud Ex.2.6. Similar to Atiyah-Macdonald 1.10 and Stacks 00DT -/ noncomputable def quotient_inf_ring_equiv_pi_quotient [fintype ι] (f : ι → ideal R) (hf : ∀ i j, i ≠ j → f i ⊔ f j = ⊤) : (⨅ i, f i).quotient ≃+* Π i, (f i).quotient := { .. equiv.of_bijective _ (quotient_inf_to_pi_quotient_bijective hf), .. quotient_inf_to_pi_quotient f } end chinese_remainder section mul_and_radical variables {R : Type u} {ι : Type*} [comm_ring R] variables {I J K L: ideal R} instance : has_mul (ideal R) := ⟨(•)⟩ @[simp] lemma add_eq_sup : I + J = I ⊔ J := rfl @[simp] lemma zero_eq_bot : (0 : ideal R) = ⊥ := rfl @[simp] lemma one_eq_top : (1 : ideal R) = ⊤ := by erw [submodule.one_eq_map_top, submodule.map_id] theorem mul_mem_mul {r s} (hr : r ∈ I) (hs : s ∈ J) : r * s ∈ I * J := submodule.smul_mem_smul hr hs theorem mul_mem_mul_rev {r s} (hr : r ∈ I) (hs : s ∈ J) : s * r ∈ I * J := mul_comm r s ▸ mul_mem_mul hr hs theorem mul_le : I * J ≤ K ↔ ∀ (r ∈ I) (s ∈ J), r * s ∈ K := submodule.smul_le lemma mul_le_left : I * J ≤ J := ideal.mul_le.2 (λ r hr s, J.mul_mem_left _) lemma mul_le_right : I * J ≤ I := ideal.mul_le.2 (λ r hr s hs, I.mul_mem_right _ hr) @[simp] lemma sup_mul_right_self : I ⊔ (I * J) = I := sup_eq_left.2 ideal.mul_le_right @[simp] lemma sup_mul_left_self : I ⊔ (J * I) = I := sup_eq_left.2 ideal.mul_le_left @[simp] lemma mul_right_self_sup : (I * J) ⊔ I = I := sup_eq_right.2 ideal.mul_le_right @[simp] lemma mul_left_self_sup : (J * I) ⊔ I = I := sup_eq_right.2 ideal.mul_le_left variables (I J K) protected theorem mul_comm : I * J = J * I := le_antisymm (mul_le.2 $ λ r hrI s hsJ, mul_mem_mul_rev hsJ hrI) (mul_le.2 $ λ r hrJ s hsI, mul_mem_mul_rev hsI hrJ) protected theorem mul_assoc : (I * J) * K = I * (J * K) := submodule.smul_assoc I J K theorem span_mul_span (S T : set R) : span S * span T = span ⋃ (s ∈ S) (t ∈ T), {s * t} := submodule.span_smul_span S T variables {I J K} lemma span_mul_span' (S T : set R) : span S * span T = span (S*T) := by { unfold span, rw submodule.span_mul_span,} lemma span_singleton_mul_span_singleton (r s : R) : span {r} * span {s} = (span {r * s} : ideal R) := by { unfold span, rw [submodule.span_mul_span, set.singleton_mul_singleton],} theorem mul_le_inf : I * J ≤ I ⊓ J := mul_le.2 $ λ r hri s hsj, ⟨I.mul_mem_right s hri, J.mul_mem_left r hsj⟩ theorem prod_le_inf {s : finset ι} {f : ι → ideal R} : s.prod f ≤ s.inf f := begin classical, refine s.induction_on _ _, { rw [finset.prod_empty, finset.inf_empty], exact le_top }, intros a s has ih, rw [finset.prod_insert has, finset.inf_insert], exact le_trans mul_le_inf (inf_le_inf (le_refl _) ih) end theorem mul_eq_inf_of_coprime (h : I ⊔ J = ⊤) : I * J = I ⊓ J := le_antisymm mul_le_inf $ λ r ⟨hri, hrj⟩, let ⟨s, hsi, t, htj, hst⟩ := submodule.mem_sup.1 ((eq_top_iff_one _).1 h) in mul_one r ▸ hst ▸ (mul_add r s t).symm ▸ ideal.add_mem (I * J) (mul_mem_mul_rev hsi hrj) (mul_mem_mul hri htj) variables (I) theorem mul_bot : I * ⊥ = ⊥ := submodule.smul_bot I theorem bot_mul : ⊥ * I = ⊥ := submodule.bot_smul I theorem mul_top : I * ⊤ = I := ideal.mul_comm ⊤ I ▸ submodule.top_smul I theorem top_mul : ⊤ * I = I := submodule.top_smul I variables {I} theorem mul_mono (hik : I ≤ K) (hjl : J ≤ L) : I * J ≤ K * L := submodule.smul_mono hik hjl theorem mul_mono_left (h : I ≤ J) : I * K ≤ J * K := submodule.smul_mono_left h theorem mul_mono_right (h : J ≤ K) : I * J ≤ I * K := submodule.smul_mono_right h variables (I J K) theorem mul_sup : I * (J ⊔ K) = I * J ⊔ I * K := submodule.smul_sup I J K theorem sup_mul : (I ⊔ J) * K = I * K ⊔ J * K := submodule.sup_smul I J K variables {I J K} lemma pow_le_pow {m n : ℕ} (h : m ≤ n) : I^n ≤ I^m := begin cases nat.exists_eq_add_of_le h with k hk, rw [hk, pow_add], exact le_trans (mul_le_inf) (inf_le_left) end lemma mul_eq_bot {R : Type*} [integral_domain R] {I J : ideal R} : I * J = ⊥ ↔ I = ⊥ ∨ J = ⊥ := ⟨λ hij, or_iff_not_imp_left.mpr (λ I_ne_bot, J.eq_bot_iff.mpr (λ j hj, let ⟨i, hi, ne0⟩ := I.ne_bot_iff.mp I_ne_bot in or.resolve_left (mul_eq_zero.mp ((I * J).eq_bot_iff.mp hij _ (mul_mem_mul hi hj))) ne0)), λ h, by cases h; rw [← ideal.mul_bot, h, ideal.mul_comm]⟩ instance {R : Type*} [integral_domain R] : no_zero_divisors (ideal R) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ I J, mul_eq_bot.1 } /-- A product of ideals in an integral domain is zero if and only if one of the terms is zero. -/ lemma prod_eq_bot {R : Type*} [integral_domain R] {s : multiset (ideal R)} : s.prod = ⊥ ↔ ∃ I ∈ s, I = ⊥ := prod_zero_iff_exists_zero /-- The radical of an ideal `I` consists of the elements `r` such that `r^n ∈ I` for some `n`. -/ def radical (I : ideal R) : ideal R := { carrier := { r | ∃ n : ℕ, r ^ n ∈ I }, zero_mem' := ⟨1, (pow_one (0:R)).symm ▸ I.zero_mem⟩, add_mem' := λ x y ⟨m, hxmi⟩ ⟨n, hyni⟩, ⟨m + n, (add_pow x y (m + n)).symm ▸ I.sum_mem $ show ∀ c ∈ finset.range (nat.succ (m + n)), x ^ c * y ^ (m + n - c) * (nat.choose (m + n) c) ∈ I, from λ c hc, or.cases_on (le_total c m) (λ hcm, I.mul_mem_right _ $ I.mul_mem_left _ $ nat.add_comm n m ▸ (nat.add_sub_assoc hcm n).symm ▸ (pow_add y n (m-c)).symm ▸ I.mul_mem_right _ hyni) (λ hmc, I.mul_mem_right _ $ I.mul_mem_right _ $ nat.add_sub_cancel' hmc ▸ (pow_add x m (c-m)).symm ▸ I.mul_mem_right _ hxmi)⟩, smul_mem' := λ r s ⟨n, hsni⟩, ⟨n, (mul_pow r s n).symm ▸ I.mul_mem_left (r^n) hsni⟩ } theorem le_radical : I ≤ radical I := λ r hri, ⟨1, (pow_one r).symm ▸ hri⟩ variables (R) theorem radical_top : (radical ⊤ : ideal R) = ⊤ := (eq_top_iff_one _).2 ⟨0, submodule.mem_top⟩ variables {R} theorem radical_mono (H : I ≤ J) : radical I ≤ radical J := λ r ⟨n, hrni⟩, ⟨n, H hrni⟩ variables (I) @[simp] theorem radical_idem : radical (radical I) = radical I := le_antisymm (λ r ⟨n, k, hrnki⟩, ⟨n * k, (pow_mul r n k).symm ▸ hrnki⟩) le_radical variables {I} theorem radical_eq_top : radical I = ⊤ ↔ I = ⊤ := ⟨λ h, (eq_top_iff_one _).2 $ let ⟨n, hn⟩ := (eq_top_iff_one _).1 h in @one_pow R _ n ▸ hn, λ h, h.symm ▸ radical_top R⟩ theorem is_prime.radical (H : is_prime I) : radical I = I := le_antisymm (λ r ⟨n, hrni⟩, H.mem_of_pow_mem n hrni) le_radical variables (I J) theorem radical_sup : radical (I ⊔ J) = radical (radical I ⊔ radical J) := le_antisymm (radical_mono $ sup_le_sup le_radical le_radical) $ λ r ⟨n, hrnij⟩, let ⟨s, hs, t, ht, hst⟩ := submodule.mem_sup.1 hrnij in @radical_idem _ _ (I ⊔ J) ▸ ⟨n, hst ▸ ideal.add_mem _ (radical_mono le_sup_left hs) (radical_mono le_sup_right ht)⟩ theorem radical_inf : radical (I ⊓ J) = radical I ⊓ radical J := le_antisymm (le_inf (radical_mono inf_le_left) (radical_mono inf_le_right)) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ I.mul_mem_right _ hrm, (pow_add r m n).symm ▸ J.mul_mem_left _ hrn⟩) theorem radical_mul : radical (I * J) = radical I ⊓ radical J := le_antisymm (radical_inf I J ▸ radical_mono $ @mul_le_inf _ _ I J) (λ r ⟨⟨m, hrm⟩, ⟨n, hrn⟩⟩, ⟨m + n, (pow_add r m n).symm ▸ mul_mem_mul hrm hrn⟩) variables {I J} theorem is_prime.radical_le_iff (hj : is_prime J) : radical I ≤ J ↔ I ≤ J := ⟨le_trans le_radical, λ hij r ⟨n, hrni⟩, hj.mem_of_pow_mem n $ hij hrni⟩ theorem radical_eq_Inf (I : ideal R) : radical I = Inf { J : ideal R | I ≤ J ∧ is_prime J } := le_antisymm (le_Inf $ λ J hJ, hJ.2.radical_le_iff.2 hJ.1) $ λ r hr, classical.by_contradiction $ λ hri, let ⟨m, (hrm : r ∉ radical m), him, hm⟩ := zorn.zorn_partial_order₀ {K : ideal R | r ∉ radical K} (λ c hc hcc y hyc, ⟨Sup c, λ ⟨n, hrnc⟩, let ⟨y, hyc, hrny⟩ := (submodule.mem_Sup_of_directed ⟨y, hyc⟩ hcc.directed_on).1 hrnc in hc hyc ⟨n, hrny⟩, λ z, le_Sup⟩) I hri in have ∀ x ∉ m, r ∈ radical (m ⊔ span {x}) := λ x hxm, classical.by_contradiction $ λ hrmx, hxm $ hm (m ⊔ span {x}) hrmx le_sup_left ▸ (le_sup_right : _ ≤ m ⊔ span {x}) (subset_span $ set.mem_singleton _), have is_prime m, from ⟨by rintro rfl; rw radical_top at hrm; exact hrm trivial, λ x y hxym, or_iff_not_imp_left.2 $ λ hxm, classical.by_contradiction $ λ hym, let ⟨n, hrn⟩ := this _ hxm, ⟨p, hpm, q, hq, hpqrn⟩ := submodule.mem_sup.1 hrn, ⟨c, hcxq⟩ := mem_span_singleton'.1 hq in let ⟨k, hrk⟩ := this _ hym, ⟨f, hfm, g, hg, hfgrk⟩ := submodule.mem_sup.1 hrk, ⟨d, hdyg⟩ := mem_span_singleton'.1 hg in hrm ⟨n + k, by rw [pow_add, ← hpqrn, ← hcxq, ← hfgrk, ← hdyg, add_mul, mul_add (c*x), mul_assoc c x (d*y), mul_left_comm x, ← mul_assoc]; refine m.add_mem (m.mul_mem_right _ hpm) (m.add_mem (m.mul_mem_left _ hfm) (m.mul_mem_left _ hxym))⟩⟩, hrm $ this.radical.symm ▸ (Inf_le ⟨him, this⟩ : Inf {J : ideal R | I ≤ J ∧ is_prime J} ≤ m) hr @[simp] lemma radical_bot_of_integral_domain {R : Type u} [integral_domain R] : radical (⊥ : ideal R) = ⊥ := eq_bot_iff.2 (λ x hx, hx.rec_on (λ n hn, pow_eq_zero hn)) instance : comm_semiring (ideal R) := submodule.comm_semiring variables (R) theorem top_pow (n : ℕ) : (⊤ ^ n : ideal R) = ⊤ := nat.rec_on n one_eq_top $ λ n ih, by rw [pow_succ, ih, top_mul] variables {R} variables (I) theorem radical_pow (n : ℕ) (H : n > 0) : radical (I^n) = radical I := nat.rec_on n (not.elim dec_trivial) (λ n ih H, or.cases_on (lt_or_eq_of_le $ nat.le_of_lt_succ H) (λ H, calc radical (I^(n+1)) = radical I ⊓ radical (I^n) : radical_mul _ _ ... = radical I ⊓ radical I : by rw ih H ... = radical I : inf_idem) (λ H, H ▸ (pow_one I).symm ▸ rfl)) H theorem is_prime.mul_le {I J P : ideal R} (hp : is_prime P) : I * J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, or_iff_not_imp_left.2 $ λ hip j hj, let ⟨i, hi, hip⟩ := set.not_subset.1 hip in (hp.mem_or_mem $ h $ mul_mem_mul hi hj).resolve_left hip, λ h, or.cases_on h (le_trans $ le_trans mul_le_inf inf_le_left) (le_trans $ le_trans mul_le_inf inf_le_right)⟩ theorem is_prime.inf_le {I J P : ideal R} (hp : is_prime P) : I ⊓ J ≤ P ↔ I ≤ P ∨ J ≤ P := ⟨λ h, hp.mul_le.1 $ le_trans mul_le_inf h, λ h, or.cases_on h (le_trans inf_le_left) (le_trans inf_le_right)⟩ theorem is_prime.prod_le {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hne: s.nonempty) : s.prod f ≤ P ↔ ∃ i ∈ s, f i ≤ P := suffices s.prod f ≤ P → ∃ i ∈ s, f i ≤ P, from ⟨this, λ ⟨i, his, hip⟩, le_trans prod_le_inf $ le_trans (finset.inf_le his) hip⟩, begin classical, obtain ⟨b, hb⟩ : ∃ b, b ∈ s := hne.bex, obtain ⟨t, hbt, rfl⟩ : ∃ t, b ∉ t ∧ s = insert b t, from ⟨s.erase b, s.not_mem_erase b, (finset.insert_erase hb).symm⟩, revert hbt, refine t.induction_on _ _, { simp only [finset.not_mem_empty, insert_emptyc_eq, exists_prop, finset.prod_singleton, imp_self, exists_eq_left, not_false_iff, finset.mem_singleton] }, intros a s has ih hbs h, have : a ∉ insert b s, { contrapose! has, apply finset.mem_of_mem_insert_of_ne has, rintro rfl, contradiction }, rw [finset.insert.comm, finset.prod_insert this, hp.mul_le] at h, rw finset.insert.comm, cases h, { exact ⟨a, finset.mem_insert_self a _, h⟩ }, obtain ⟨i, hi, ih⟩ : ∃ i ∈ insert b s, f i ≤ P := ih (mt finset.mem_insert_of_mem hbs) h, exact ⟨i, finset.mem_insert_of_mem hi, ih⟩ end theorem is_prime.inf_le' {s : finset ι} {f : ι → ideal R} {P : ideal R} (hp : is_prime P) (hsne: s.nonempty) : s.inf f ≤ P ↔ ∃ i ∈ s, f i ≤ P := ⟨λ h, (hp.prod_le hsne).1 $ le_trans prod_le_inf h, λ ⟨i, his, hip⟩, le_trans (finset.inf_le his) hip⟩ theorem subset_union {I J K : ideal R} : (I : set R) ⊆ J ∪ K ↔ I ≤ J ∨ I ≤ K := ⟨λ h, or_iff_not_imp_left.2 $ λ hij s hsi, let ⟨r, hri, hrj⟩ := set.not_subset.1 hij in classical.by_contradiction $ λ hsk, or.cases_on (h $ I.add_mem hri hsi) (λ hj, hrj $ add_sub_cancel r s ▸ J.sub_mem hj ((h hsi).resolve_right hsk)) (λ hk, hsk $ add_sub_cancel' r s ▸ K.sub_mem hk ((h hri).resolve_left hrj)), λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset_union_left J K) (λ h, set.subset.trans h $ set.subset_union_right J K)⟩ theorem subset_union_prime' {s : finset ι} {f : ι → ideal R} {a b : ι} (hp : ∀ i ∈ s, is_prime (f i)) {I : ideal R} : (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) ↔ I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ f a ∪ f b ∪ (⋃ i ∈ (↑s : set ι), f i) → I ≤ f a ∨ I ≤ f b ∨ ∃ i ∈ s, I ≤ f i, from ⟨this, λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_left _ _) (set.subset_union_left _ _)) $ λ h, or.cases_on h (λ h, set.subset.trans h $ set.subset.trans (set.subset_union_right _ _) (set.subset_union_left _ _)) $ λ ⟨i, his, hi⟩, by refine (set.subset.trans hi $ set.subset.trans _ $ set.subset_union_right _ _); exact set.subset_bUnion_of_mem (finset.mem_coe.2 his)⟩, begin generalize hn : s.card = n, intros h, unfreezingI { induction n with n ih generalizing a b s }, { clear hp, rw finset.card_eq_zero at hn, subst hn, rw [finset.coe_empty, set.bUnion_empty, set.union_empty, subset_union] at h, simpa only [exists_prop, finset.not_mem_empty, false_and, exists_false, or_false] }, classical, replace hn : ∃ (i : ι) (t : finset ι), i ∉ t ∧ insert i t = s ∧ t.card = n := finset.card_eq_succ.1 hn, unfreezingI { rcases hn with ⟨i, t, hit, rfl, hn⟩ }, replace hp : is_prime (f i) ∧ ∀ x ∈ t, is_prime (f x) := (t.forall_mem_insert _ _).1 hp, by_cases Ht : ∃ j ∈ t, f j ≤ f i, { obtain ⟨j, hjt, hfji⟩ : ∃ j ∈ t, f j ≤ f i := Ht, obtain ⟨u, hju, rfl⟩ : ∃ u, j ∉ u ∧ insert j u = t, { exact ⟨t.erase j, t.not_mem_erase j, finset.insert_erase hjt⟩ }, have hp' : ∀ k ∈ insert i u, is_prime (f k), { rw finset.forall_mem_insert at hp ⊢, exact ⟨hp.1, hp.2.2⟩ }, have hiu : i ∉ u := mt finset.mem_insert_of_mem hit, have hn' : (insert i u).card = n, { rwa finset.card_insert_of_not_mem at hn ⊢, exacts [hiu, hju] }, have h' : (I : set R) ⊆ f a ∪ f b ∪ (⋃ k ∈ (↑(insert i u) : set ι), f k), { rw finset.coe_insert at h ⊢, rw finset.coe_insert at h, simp only [set.bUnion_insert] at h ⊢, rw [← set.union_assoc ↑(f i)] at h, erw [set.union_eq_self_of_subset_right hfji] at h, exact h }, specialize @ih a b (insert i u) hp' hn' h', refine ih.imp id (or.imp id (exists_imp_exists $ λ k, _)), simp only [exists_prop], exact and.imp (λ hk, finset.insert_subset_insert i (finset.subset_insert j u) hk) id }, by_cases Ha : f a ≤ f i, { have h' : (I : set R) ⊆ f i ∪ f b ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_right_comm ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Ha] at h, exact h }, specialize @ih i b t hp.2 hn h', right, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inr ⟨i, finset.mem_insert_self i t, ih⟩ }, { exact or.inl ih }, { exact or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, by_cases Hb : f b ≤ f i, { have h' : (I : set R) ⊆ f a ∪ f i ∪ (⋃ j ∈ (↑t : set ι), f j), { rw [finset.coe_insert, set.bUnion_insert, ← set.union_assoc, set.union_assoc ↑(f a)] at h, erw [set.union_eq_self_of_subset_left Hb] at h, exact h }, specialize @ih a i t hp.2 hn h', rcases ih with ih | ih | ⟨k, hkt, ih⟩, { exact or.inl ih }, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, ih⟩) }, { exact or.inr (or.inr ⟨k, finset.mem_insert_of_mem hkt, ih⟩) } }, by_cases Hi : I ≤ f i, { exact or.inr (or.inr ⟨i, finset.mem_insert_self i t, Hi⟩) }, have : ¬I ⊓ f a ⊓ f b ⊓ t.inf f ≤ f i, { rcases t.eq_empty_or_nonempty with (rfl | hsne), { rw [finset.inf_empty, inf_top_eq, hp.1.inf_le, hp.1.inf_le, not_or_distrib, not_or_distrib], exact ⟨⟨Hi, Ha⟩, Hb⟩ }, simp only [hp.1.inf_le, hp.1.inf_le' hsne, not_or_distrib], exact ⟨⟨⟨Hi, Ha⟩, Hb⟩, Ht⟩ }, rcases set.not_subset.1 this with ⟨r, ⟨⟨⟨hrI, hra⟩, hrb⟩, hr⟩, hri⟩, by_cases HI : (I : set R) ⊆ f a ∪ f b ∪ ⋃ j ∈ (↑t : set ι), f j, { specialize ih hp.2 hn HI, rcases ih with ih | ih | ⟨k, hkt, ih⟩, { left, exact ih }, { right, left, exact ih }, { right, right, exact ⟨k, finset.mem_insert_of_mem hkt, ih⟩ } }, exfalso, rcases set.not_subset.1 HI with ⟨s, hsI, hs⟩, rw [finset.coe_insert, set.bUnion_insert] at h, have hsi : s ∈ f i := ((h hsI).resolve_left (mt or.inl hs)).resolve_right (mt or.inr hs), rcases h (I.add_mem hrI hsI) with ⟨ha | hb⟩ | hi | ht, { exact hs (or.inl $ or.inl $ add_sub_cancel' r s ▸ (f a).sub_mem ha hra) }, { exact hs (or.inl $ or.inr $ add_sub_cancel' r s ▸ (f b).sub_mem hb hrb) }, { exact hri (add_sub_cancel r s ▸ (f i).sub_mem hi hsi) }, { rw set.mem_bUnion_iff at ht, rcases ht with ⟨j, hjt, hj⟩, simp only [finset.inf_eq_infi, set_like.mem_coe, submodule.mem_infi] at hr, exact hs (or.inr $ set.mem_bUnion hjt $ add_sub_cancel' r s ▸ (f j).sub_mem hj $ hr j hjt) } end /-- Prime avoidance. Atiyah-Macdonald 1.11, Eisenbud 3.3, Stacks 00DS, Matsumura Ex.1.6. -/ theorem subset_union_prime {s : finset ι} {f : ι → ideal R} (a b : ι) (hp : ∀ i ∈ s, i ≠ a → i ≠ b → is_prime (f i)) {I : ideal R} : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) ↔ ∃ i ∈ s, I ≤ f i := suffices (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i) → ∃ i, i ∈ s ∧ I ≤ f i, from ⟨λ h, bex_def.2 $ this h, λ ⟨i, his, hi⟩, set.subset.trans hi $ set.subset_bUnion_of_mem $ show i ∈ (↑s : set ι), from his⟩, assume h : (I : set R) ⊆ (⋃ i ∈ (↑s : set ι), f i), begin classical, tactic.unfreeze_local_instances, by_cases has : a ∈ s, { obtain ⟨t, hat, rfl⟩ : ∃ t, a ∉ t ∧ insert a t = s := ⟨s.erase a, finset.not_mem_erase a s, finset.insert_erase has⟩, by_cases hbt : b ∈ t, { obtain ⟨u, hbu, rfl⟩ : ∃ u, b ∉ u ∧ insert b u = t := ⟨t.erase b, finset.not_mem_erase b t, finset.insert_erase hbt⟩, have hp' : ∀ i ∈ u, is_prime (f i), { intros i hiu, refine hp i (finset.mem_insert_of_mem (finset.mem_insert_of_mem hiu)) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, finset.coe_insert, set.bUnion_insert, set.bUnion_insert, ← set.union_assoc, subset_union_prime' hp', bex_def] at h, rwa [finset.exists_mem_insert, finset.exists_mem_insert] }, { have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f a : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } }, { by_cases hbs : b ∈ s, { obtain ⟨t, hbt, rfl⟩ : ∃ t, b ∉ t ∧ insert b t = s := ⟨s.erase b, finset.not_mem_erase b s, finset.insert_erase hbs⟩, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f b : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert }, cases s.eq_empty_or_nonempty with hse hsne, { subst hse, rw [finset.coe_empty, set.bUnion_empty, set.subset_empty_iff] at h, have : (I : set R) ≠ ∅ := set.nonempty.ne_empty (set.nonempty_of_mem I.zero_mem), exact absurd h this }, { cases hsne.bex with i his, obtain ⟨t, hit, rfl⟩ : ∃ t, i ∉ t ∧ insert i t = s := ⟨s.erase i, finset.not_mem_erase i s, finset.insert_erase his⟩, have hp' : ∀ j ∈ t, is_prime (f j), { intros j hj, refine hp j (finset.mem_insert_of_mem hj) _ _; rintro rfl; solve_by_elim only [finset.mem_insert_of_mem, *], }, rw [finset.coe_insert, set.bUnion_insert, ← set.union_self (f i : set R), subset_union_prime' hp', ← or_assoc, or_self, bex_def] at h, rwa finset.exists_mem_insert } } end end mul_and_radical section map_and_comap variables {R : Type u} {S : Type v} [comm_ring R] [comm_ring S] variables (f : R →+* S) variables {I J : ideal R} {K L : ideal S} /-- `I.map f` is the span of the image of the ideal `I` under `f`, which may be bigger than the image itself. -/ def map (I : ideal R) : ideal S := span (f '' I) /-- `I.comap f` is the preimage of `I` under `f`. -/ def comap (I : ideal S) : ideal R := { carrier := f ⁻¹' I, smul_mem' := λ c x hx, show f (c * x) ∈ I, by { rw f.map_mul, exact I.mul_mem_left _ hx }, .. I.to_add_submonoid.comap (f : R →+ S) } variables {f} theorem map_mono (h : I ≤ J) : map f I ≤ map f J := span_mono $ set.image_subset _ h theorem mem_map_of_mem {x} (h : x ∈ I) : f x ∈ map f I := subset_span ⟨x, h, rfl⟩ theorem map_le_iff_le_comap : map f I ≤ K ↔ I ≤ comap f K := span_le.trans set.image_subset_iff @[simp] theorem mem_comap {x} : x ∈ comap f K ↔ f x ∈ K := iff.rfl theorem comap_mono (h : K ≤ L) : comap f K ≤ comap f L := set.preimage_mono (λ x hx, h hx) variables (f) theorem comap_ne_top (hK : K ≠ ⊤) : comap f K ≠ ⊤ := (ne_top_iff_one _).2 $ by rw [mem_comap, f.map_one]; exact (ne_top_iff_one _).1 hK theorem is_prime.comap [hK : K.is_prime] : (comap f K).is_prime := ⟨comap_ne_top _ hK.1, λ x y, by simp only [mem_comap, f.map_mul]; apply hK.2⟩ variables (I J K L) theorem map_top : map f ⊤ = ⊤ := (eq_top_iff_one _).2 $ subset_span ⟨1, trivial, f.map_one⟩ theorem map_mul : map f (I * J) = map f I * map f J := le_antisymm (map_le_iff_le_comap.2 $ mul_le.2 $ λ r hri s hsj, show f (r * s) ∈ _, by rw f.map_mul; exact mul_mem_mul (mem_map_of_mem hri) (mem_map_of_mem hsj)) (trans_rel_right _ (span_mul_span _ _) $ span_le.2 $ set.bUnion_subset $ λ i ⟨r, hri, hfri⟩, set.bUnion_subset $ λ j ⟨s, hsj, hfsj⟩, set.singleton_subset_iff.2 $ hfri ▸ hfsj ▸ by rw [← f.map_mul]; exact mem_map_of_mem (mul_mem_mul hri hsj)) variable (f) lemma gc_map_comap : galois_connection (ideal.map f) (ideal.comap f) := λ I J, ideal.map_le_iff_le_comap @[simp] lemma comap_id : I.comap (ring_hom.id R) = I := ideal.ext $ λ _, iff.rfl @[simp] lemma map_id : I.map (ring_hom.id R) = I := (gc_map_comap (ring_hom.id R)).l_unique galois_connection.id comap_id lemma comap_comap {T : Type*} [comm_ring T] {I : ideal T} (f : R →+* S) (g : S →+*T) : (I.comap g).comap f = I.comap (g.comp f) := rfl lemma map_map {T : Type*} [comm_ring T] {I : ideal R} (f : R →+* S) (g : S →+*T) : (I.map f).map g = I.map (g.comp f) := ((gc_map_comap f).compose _ _ _ _ (gc_map_comap g)).l_unique (gc_map_comap (g.comp f)) (λ _, comap_comap _ _) variables {f I J K L} lemma map_le_of_le_comap : I ≤ K.comap f → I.map f ≤ K := (gc_map_comap f).l_le lemma le_comap_of_map_le : I.map f ≤ K → I ≤ K.comap f := (gc_map_comap f).le_u lemma le_comap_map : I ≤ (I.map f).comap f := (gc_map_comap f).le_u_l _ lemma map_comap_le : (K.comap f).map f ≤ K := (gc_map_comap f).l_u_le _ @[simp] lemma comap_top : (⊤ : ideal S).comap f = ⊤ := (gc_map_comap f).u_top @[simp] lemma comap_eq_top_iff {I : ideal S} : I.comap f = ⊤ ↔ I = ⊤ := ⟨ λ h, I.eq_top_iff_one.mpr (f.map_one ▸ mem_comap.mp ((I.comap f).eq_top_iff_one.mp h)), λ h, by rw [h, comap_top] ⟩ @[simp] lemma map_bot : (⊥ : ideal R).map f = ⊥ := (gc_map_comap f).l_bot variables (f I J K L) @[simp] lemma map_comap_map : ((I.map f).comap f).map f = I.map f := congr_fun (gc_map_comap f).l_u_l_eq_l I @[simp] lemma comap_map_comap : ((K.comap f).map f).comap f = K.comap f := congr_fun (gc_map_comap f).u_l_u_eq_u K lemma map_sup : (I ⊔ J).map f = I.map f ⊔ J.map f := (gc_map_comap f).l_sup theorem comap_inf : comap f (K ⊓ L) = comap f K ⊓ comap f L := rfl variables {ι : Sort*} lemma map_supr (K : ι → ideal R) : (supr K).map f = ⨆ i, (K i).map f := (gc_map_comap f).l_supr lemma comap_infi (K : ι → ideal S) : (infi K).comap f = ⨅ i, (K i).comap f := (gc_map_comap f).u_infi lemma map_Sup (s : set (ideal R)): (Sup s).map f = ⨆ I ∈ s, (I : ideal R).map f := (gc_map_comap f).l_Sup lemma comap_Inf (s : set (ideal S)): (Inf s).comap f = ⨅ I ∈ s, (I : ideal S).comap f := (gc_map_comap f).u_Inf lemma comap_Inf' (s : set (ideal S)) : (Inf s).comap f = ⨅ I ∈ (comap f '' s), I := trans (comap_Inf f s) (by rw infi_image) theorem comap_radical : comap f (radical K) = radical (comap f K) := le_antisymm (λ r ⟨n, hfrnk⟩, ⟨n, show f (r ^ n) ∈ K, from (f.map_pow r n).symm ▸ hfrnk⟩) (λ r ⟨n, hfrnk⟩, ⟨n, f.map_pow r n ▸ hfrnk⟩) theorem comap_is_prime [H : is_prime K] : is_prime (comap f K) := ⟨comap_ne_top f H.ne_top, λ x y h, H.mem_or_mem $ by rwa [mem_comap, ring_hom.map_mul] at h⟩ @[simp] lemma map_quotient_self : map (quotient.mk I) I = ⊥ := eq_bot_iff.2 $ ideal.map_le_iff_le_comap.2 $ λ x hx, (submodule.mem_bot I.quotient).2 $ ideal.quotient.eq_zero_iff_mem.2 hx variables {I J K L} theorem map_inf_le : map f (I ⊓ J) ≤ map f I ⊓ map f J := (gc_map_comap f).monotone_l.map_inf_le _ _ theorem map_radical_le : map f (radical I) ≤ radical (map f I) := map_le_iff_le_comap.2 $ λ r ⟨n, hrni⟩, ⟨n, f.map_pow r n ▸ mem_map_of_mem hrni⟩ theorem le_comap_sup : comap f K ⊔ comap f L ≤ comap f (K ⊔ L) := (gc_map_comap f).monotone_u.le_map_sup _ _ theorem le_comap_mul : comap f K * comap f L ≤ comap f (K * L) := map_le_iff_le_comap.1 $ (map_mul f (comap f K) (comap f L)).symm ▸ mul_mono (map_le_iff_le_comap.2 $ le_refl _) (map_le_iff_le_comap.2 $ le_refl _) section surjective variables (hf : function.surjective f) include hf open function theorem map_comap_of_surjective (I : ideal S) : map f (comap f I) = I := le_antisymm (map_le_iff_le_comap.2 (le_refl _)) (λ s hsi, let ⟨r, hfrs⟩ := hf s in hfrs ▸ (mem_map_of_mem $ show f r ∈ I, from hfrs.symm ▸ hsi)) /-- `map` and `comap` are adjoint, and the composition `map f ∘ comap f` is the identity -/ def gi_map_comap : galois_insertion (map f) (comap f) := galois_insertion.monotone_intro ((gc_map_comap f).monotone_u) ((gc_map_comap f).monotone_l) (λ _, le_comap_map) (map_comap_of_surjective _ hf) lemma map_surjective_of_surjective : surjective (map f) := (gi_map_comap f hf).l_surjective lemma comap_injective_of_surjective : injective (comap f) := (gi_map_comap f hf).u_injective lemma map_sup_comap_of_surjective (I J : ideal S) : (I.comap f ⊔ J.comap f).map f = I ⊔ J := (gi_map_comap f hf).l_sup_u _ _ lemma map_supr_comap_of_surjective (K : ι → ideal S) : (⨆i, (K i).comap f).map f = supr K := (gi_map_comap f hf).l_supr_u _ lemma map_inf_comap_of_surjective (I J : ideal S) : (I.comap f ⊓ J.comap f).map f = I ⊓ J := (gi_map_comap f hf).l_inf_u _ _ lemma map_infi_comap_of_surjective (K : ι → ideal S) : (⨅i, (K i).comap f).map f = infi K := (gi_map_comap f hf).l_infi_u _ theorem mem_image_of_mem_map_of_surjective {I : ideal R} {y} (H : y ∈ map f I) : y ∈ f '' I := submodule.span_induction H (λ _, id) ⟨0, I.zero_mem, f.map_zero⟩ (λ y1 y2 ⟨x1, hx1i, hxy1⟩ ⟨x2, hx2i, hxy2⟩, ⟨x1 + x2, I.add_mem hx1i hx2i, hxy1 ▸ hxy2 ▸ f.map_add _ _⟩) (λ c y ⟨x, hxi, hxy⟩, let ⟨d, hdc⟩ := hf c in ⟨d • x, I.smul_mem _ hxi, hdc ▸ hxy ▸ f.map_mul _ _⟩) lemma mem_map_iff_of_surjective {I : ideal R} {y} : y ∈ map f I ↔ ∃ x, x ∈ I ∧ f x = y := ⟨λ h, (set.mem_image _ _ _).2 (mem_image_of_mem_map_of_surjective f hf h), λ ⟨x, hx⟩, hx.right ▸ (mem_map_of_mem hx.left)⟩ theorem comap_map_of_surjective (I : ideal R) : comap f (map f I) = I ⊔ comap f ⊥ := le_antisymm (assume r h, let ⟨s, hsi, hfsr⟩ := mem_image_of_mem_map_of_surjective f hf h in submodule.mem_sup.2 ⟨s, hsi, r - s, (submodule.mem_bot S).2 $ by rw [f.map_sub, hfsr, sub_self], add_sub_cancel'_right s r⟩) (sup_le (map_le_iff_le_comap.1 (le_refl _)) (comap_mono bot_le)) lemma le_map_of_comap_le_of_surjective : comap f K ≤ I → K ≤ map f I := λ h, (map_comap_of_surjective f hf K) ▸ map_mono h /-- Correspondence theorem -/ def rel_iso_of_surjective : ideal S ≃o { p : ideal R // comap f ⊥ ≤ p } := { to_fun := λ J, ⟨comap f J, comap_mono bot_le⟩, inv_fun := λ I, map f I.1, left_inv := λ J, map_comap_of_surjective f hf J, right_inv := λ I, subtype.eq $ show comap f (map f I.1) = I.1, from (comap_map_of_surjective f hf I).symm ▸ le_antisymm (sup_le (le_refl _) I.2) le_sup_left, map_rel_iff' := λ I1 I2, ⟨λ H, map_comap_of_surjective f hf I1 ▸ map_comap_of_surjective f hf I2 ▸ map_mono H, comap_mono⟩ } /-- The map on ideals induced by a surjective map preserves inclusion. -/ def order_embedding_of_surjective : ideal S ↪o ideal R := (rel_iso_of_surjective f hf).to_rel_embedding.trans (subtype.rel_embedding _ _) theorem map_eq_top_or_is_maximal_of_surjective (H : is_maximal I) : (map f I) = ⊤ ∨ is_maximal (map f I) := begin refine or_iff_not_imp_left.2 (λ ne_top, ⟨⟨λ h, ne_top h, λ J hJ, _⟩⟩), { refine (rel_iso_of_surjective f hf).injective (subtype.ext_iff.2 (eq.trans (H.1.2 (comap f J) (lt_of_le_of_ne _ _)) comap_top.symm)), { exact (map_le_iff_le_comap).1 (le_of_lt hJ) }, { exact λ h, hJ.right (le_map_of_comap_le_of_surjective f hf (le_of_eq h.symm)) } } end theorem comap_is_maximal_of_surjective [H : is_maximal K] : is_maximal (comap f K) := begin refine ⟨⟨comap_ne_top _ H.1.1, λ J hJ, _⟩⟩, suffices : map f J = ⊤, { replace this := congr_arg (comap f) this, rw [comap_top, comap_map_of_surjective _ hf, eq_top_iff] at this, rw eq_top_iff, exact le_trans this (sup_le (le_of_eq rfl) (le_trans (comap_mono (bot_le)) (le_of_lt hJ))) }, refine H.1.2 (map f J) (lt_of_le_of_ne (le_map_of_comap_le_of_surjective _ hf (le_of_lt hJ)) (λ h, ne_of_lt hJ (trans (congr_arg (comap f) h) _))), rw [comap_map_of_surjective _ hf, sup_eq_left], exact le_trans (comap_mono bot_le) (le_of_lt hJ) end end surjective lemma mem_quotient_iff_mem (hIJ : I ≤ J) {x : R} : quotient.mk I x ∈ J.map (quotient.mk I) ↔ x ∈ J := begin refine iff.trans (mem_map_iff_of_surjective _ quotient.mk_surjective) _, split, { rintros ⟨x, x_mem, x_eq⟩, simpa using J.add_mem (hIJ (quotient.eq.mp x_eq.symm)) x_mem }, { intro x_mem, exact ⟨x, x_mem, rfl⟩ } end section injective variables (hf : function.injective f) include hf open function lemma comap_bot_le_of_injective : comap f ⊥ ≤ I := begin refine le_trans (λ x hx, _) bot_le, rw [mem_comap, submodule.mem_bot, ← ring_hom.map_zero f] at hx, exact eq.symm (hf hx) ▸ (submodule.zero_mem ⊥) end end injective section bijective variables (hf : function.bijective f) include hf open function /-- Special case of the correspondence theorem for isomorphic rings -/ def rel_iso_of_bijective : ideal S ≃o ideal R := { to_fun := comap f, inv_fun := map f, left_inv := (rel_iso_of_surjective f hf.right).left_inv, right_inv := λ J, subtype.ext_iff.1 ((rel_iso_of_surjective f hf.right).right_inv ⟨J, comap_bot_le_of_injective f hf.left⟩), map_rel_iff' := (rel_iso_of_surjective f hf.right).map_rel_iff' } lemma comap_le_iff_le_map : comap f K ≤ I ↔ K ≤ map f I := ⟨λ h, le_map_of_comap_le_of_surjective f hf.right h, λ h, ((rel_iso_of_bijective f hf).right_inv I) ▸ comap_mono h⟩ theorem map.is_maximal (H : is_maximal I) : is_maximal (map f I) := by refine or_iff_not_imp_left.1 (map_eq_top_or_is_maximal_of_surjective f hf.right H) (λ h, H.1.1 _); calc I = comap f (map f I) : ((rel_iso_of_bijective f hf).right_inv I).symm ... = comap f ⊤ : by rw h ... = ⊤ : by rw comap_top end bijective lemma ring_equiv.bot_maximal_iff (e : R ≃+* S) : (⊥ : ideal R).is_maximal ↔ (⊥ : ideal S).is_maximal := ⟨λ h, (@map_bot _ _ _ _ e.to_ring_hom) ▸ map.is_maximal e.to_ring_hom e.bijective h, λ h, (@map_bot _ _ _ _ e.symm.to_ring_hom) ▸ map.is_maximal e.symm.to_ring_hom e.symm.bijective h⟩ end map_and_comap section is_primary variables {R : Type u} [comm_ring R] /-- A proper ideal `I` is primary iff `xy ∈ I` implies `x ∈ I` or `y ∈ radical I`. -/ def is_primary (I : ideal R) : Prop := I ≠ ⊤ ∧ ∀ {x y : R}, x * y ∈ I → x ∈ I ∨ y ∈ radical I theorem is_primary.to_is_prime (I : ideal R) (hi : is_prime I) : is_primary I := ⟨hi.1, λ x y hxy, (hi.mem_or_mem hxy).imp id $ λ hyi, le_radical hyi⟩ theorem mem_radical_of_pow_mem {I : ideal R} {x : R} {m : ℕ} (hx : x ^ m ∈ radical I) : x ∈ radical I := radical_idem I ▸ ⟨m, hx⟩ theorem is_prime_radical {I : ideal R} (hi : is_primary I) : is_prime (radical I) := ⟨mt radical_eq_top.1 hi.1, λ x y ⟨m, hxy⟩, begin rw mul_pow at hxy, cases hi.2 hxy, { exact or.inl ⟨m, h⟩ }, { exact or.inr (mem_radical_of_pow_mem h) } end⟩ theorem is_primary_inf {I J : ideal R} (hi : is_primary I) (hj : is_primary J) (hij : radical I = radical J) : is_primary (I ⊓ J) := ⟨ne_of_lt $ lt_of_le_of_lt inf_le_left (lt_top_iff_ne_top.2 hi.1), λ x y ⟨hxyi, hxyj⟩, begin rw [radical_inf, hij, inf_idem], cases hi.2 hxyi with hxi hyi, cases hj.2 hxyj with hxj hyj, { exact or.inl ⟨hxi, hxj⟩ }, { exact or.inr hyj }, { rw hij at hyi, exact or.inr hyi } end⟩ end is_primary end ideal namespace ring_hom variables {R : Type u} {S : Type v} [comm_ring R] section comm_ring variables [comm_ring S] (f : R →+* S) /-- Kernel of a ring homomorphism as an ideal of the domain. -/ def ker : ideal R := ideal.comap f ⊥ /-- An element is in the kernel if and only if it maps to zero.-/ lemma mem_ker {r} : r ∈ ker f ↔ f r = 0 := by rw [ker, ideal.mem_comap, submodule.mem_bot] lemma ker_eq : ((ker f) : set R) = is_add_group_hom.ker f := rfl lemma ker_eq_comap_bot (f : R →+* S) : f.ker = ideal.comap f ⊥ := rfl lemma injective_iff_ker_eq_bot : function.injective f ↔ ker f = ⊥ := by rw [set_like.ext'_iff, ker_eq]; exact is_add_group_hom.injective_iff_trivial_ker f lemma ker_eq_bot_iff_eq_zero : ker f = ⊥ ↔ ∀ x, f x = 0 → x = 0 := by rw [set_like.ext'_iff, ker_eq]; exact is_add_group_hom.trivial_ker_iff_eq_zero f /-- If the target is not the zero ring, then one is not in the kernel.-/ lemma not_one_mem_ker [nontrivial S] (f : R →+* S) : (1:R) ∉ ker f := by { rw [mem_ker, f.map_one], exact one_ne_zero } @[simp] lemma ker_coe_equiv (f : R ≃+* S) : ker (f : R →+* S) = ⊥ := by simpa only [←injective_iff_ker_eq_bot] using f.injective /-- The induced map from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_equiv_of_right_inverse`) / is surjective (`quotient_ker_equiv_of_surjective`). -/ def ker_lift (f : R →+* S) : f.ker.quotient →+* S := ideal.quotient.lift _ f $ λ r, f.mem_ker.mp @[simp] lemma ker_lift_mk (f : R →+* S) (r : R) : ker_lift f (ideal.quotient.mk f.ker r) = f r := ideal.quotient.lift_mk _ _ _ /-- The induced map from the quotient by the kernel is injective. -/ lemma ker_lift_injective (f : R →+* S) : function.injective (ker_lift f) := assume a b, quotient.induction_on₂' a b $ assume a b (h : f a = f b), quotient.sound' $ show a - b ∈ ker f, by rw [mem_ker, map_sub, h, sub_self] variable {f} /-- The first isomorphism theorem for commutative rings, computable version. -/ def quotient_ker_equiv_of_right_inverse {g : S → R} (hf : function.right_inverse g f) : f.ker.quotient ≃+* S := { to_fun := ker_lift f, inv_fun := (ideal.quotient.mk f.ker) ∘ g, left_inv := begin rintro ⟨x⟩, apply ker_lift_injective, simp [hf (f x)], end, right_inv := hf, ..ker_lift f} @[simp] lemma quotient_ker_equiv_of_right_inverse.apply {g : S → R} (hf : function.right_inverse g f) (x : f.ker.quotient) : quotient_ker_equiv_of_right_inverse hf x = ker_lift f x := rfl @[simp] lemma quotient_ker_equiv_of_right_inverse.symm.apply {g : S → R} (hf : function.right_inverse g f) (x : S) : (quotient_ker_equiv_of_right_inverse hf).symm x = ideal.quotient.mk f.ker (g x) := rfl /-- The first isomorphism theorem for commutative rings. -/ noncomputable def quotient_ker_equiv_of_surjective (hf : function.surjective f) : f.ker.quotient ≃+* S := quotient_ker_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) end comm_ring /-- The kernel of a homomorphism to an integral domain is a prime ideal.-/ lemma ker_is_prime [integral_domain S] (f : R →+* S) : (ker f).is_prime := ⟨by { rw [ne.def, ideal.eq_top_iff_one], exact not_one_mem_ker f }, λ x y, by simpa only [mem_ker, f.map_mul] using @eq_zero_or_eq_zero_of_mul_eq_zero S _ _ _ _ _⟩ end ring_hom namespace ideal variables {R : Type*} {S : Type*} [comm_ring R] [comm_ring S] lemma map_eq_bot_iff_le_ker {I : ideal R} (f : R →+* S) : I.map f = ⊥ ↔ I ≤ f.ker := by rw [ring_hom.ker, eq_bot_iff, map_le_iff_le_comap] @[simp] lemma mk_ker {I : ideal R} : (quotient.mk I).ker = I := by ext; rw [ring_hom.ker, mem_comap, submodule.mem_bot, quotient.eq_zero_iff_mem] lemma ker_le_comap {K : ideal S} (f : R →+* S) : f.ker ≤ comap f K := λ x hx, mem_comap.2 (((ring_hom.mem_ker f).1 hx).symm ▸ K.zero_mem) lemma map_Inf {A : set (ideal R)} {f : R →+* S} (hf : function.surjective f) : (∀ J ∈ A, ring_hom.ker f ≤ J) → map f (Inf A) = Inf (map f '' A) := begin refine λ h, le_antisymm (le_Inf _) _, { intros j hj y hy, cases (mem_map_iff_of_surjective f hf).1 hy with x hx, cases (set.mem_image _ _ _).mp hj with J hJ, rw [← hJ.right, ← hx.right], exact mem_map_of_mem (Inf_le_of_le hJ.left (le_of_eq rfl) hx.left) }, { intros y hy, cases hf y with x hx, refine hx ▸ (mem_map_of_mem _), have : ∀ I ∈ A, y ∈ map f I, by simpa using hy, rw [submodule.mem_Inf], intros J hJ, rcases (mem_map_iff_of_surjective f hf).1 (this J hJ) with ⟨x', hx', rfl⟩, have : x - x' ∈ J, { apply h J hJ, rw [ring_hom.mem_ker, ring_hom.map_sub, hx, sub_self] }, simpa only [sub_add_cancel] using J.add_mem this hx' } end theorem map_is_prime_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} [H : is_prime I] (hk : ring_hom.ker f ≤ I) : is_prime (map f I) := begin refine ⟨λ h, H.ne_top (eq_top_iff.2 _), λ x y, _⟩, { replace h := congr_arg (comap f) h, rw [comap_map_of_surjective _ hf, comap_top] at h, exact h ▸ sup_le (le_of_eq rfl) hk }, { refine λ hxy, (hf x).rec_on (λ a ha, (hf y).rec_on (λ b hb, _)), rw [← ha, ← hb, ← ring_hom.map_mul, mem_map_iff_of_surjective _ hf] at hxy, rcases hxy with ⟨c, hc, hc'⟩, rw [← sub_eq_zero, ← ring_hom.map_sub] at hc', have : a * b ∈ I, { convert I.sub_mem hc (hk (hc' : c - a * b ∈ f.ker)), ring }, exact (H.mem_or_mem this).imp (λ h, ha ▸ mem_map_of_mem h) (λ h, hb ▸ mem_map_of_mem h) } end theorem map_is_prime_of_equiv (f : R ≃+* S) {I : ideal R} [is_prime I] : is_prime (map (f : R →+* S) I) := map_is_prime_of_surjective f.surjective $ by simp theorem map_radical_of_surjective {f : R →+* S} (hf : function.surjective f) {I : ideal R} (h : ring_hom.ker f ≤ I) : map f (I.radical) = (map f I).radical := begin rw [radical_eq_Inf, radical_eq_Inf], have : ∀ J ∈ {J : ideal R | I ≤ J ∧ J.is_prime}, f.ker ≤ J := λ J hJ, le_trans h hJ.left, convert map_Inf hf this, refine funext (λ j, propext ⟨_, _⟩), { rintros ⟨hj, hj'⟩, haveI : j.is_prime := hj', exact ⟨comap f j, ⟨⟨map_le_iff_le_comap.1 hj, comap_is_prime f j⟩, map_comap_of_surjective f hf j⟩⟩ }, { rintro ⟨J, ⟨hJ, hJ'⟩⟩, haveI : J.is_prime := hJ.right, refine ⟨hJ' ▸ map_mono hJ.left, hJ' ▸ map_is_prime_of_surjective hf (le_trans h hJ.left)⟩ }, end @[simp] lemma bot_quotient_is_maximal_iff (I : ideal R) : (⊥ : ideal I.quotient).is_maximal ↔ I.is_maximal := ⟨λ hI, (@mk_ker _ _ I) ▸ @comap_is_maximal_of_surjective _ _ _ _ (quotient.mk I) ⊥ quotient.mk_surjective hI, λ hI, @bot_is_maximal _ (@quotient.field _ _ I hI) ⟩ section quotient_algebra variables (R) {A : Type*} [comm_ring A] [algebra R A] /-- The `R`-algebra structure on `A/I` for an `R`-algebra `A` -/ instance {I : ideal A} : algebra R (ideal.quotient I) := (ring_hom.comp (ideal.quotient.mk I) (algebra_map R A)).to_algebra /-- The canonical morphism `A →ₐ[R] I.quotient` as morphism of `R`-algebras, for `I` an ideal of `A`, where `A` is an `R`-algebra. -/ def quotient.mkₐ (I : ideal A) : A →ₐ[R] I.quotient := ⟨λ a, submodule.quotient.mk a, rfl, λ _ _, rfl, rfl, λ _ _, rfl, λ _, rfl⟩ lemma quotient.alg_map_eq (I : ideal A) : algebra_map R I.quotient = (algebra_map A I.quotient).comp (algebra_map R A) := by simp only [ring_hom.algebra_map_to_algebra, ring_hom.comp_id] instance [algebra S A] [algebra S R] [is_scalar_tower S R A] {I : ideal A} : is_scalar_tower S R (ideal.quotient I) := is_scalar_tower.of_algebra_map_eq' $ by rw [quotient.alg_map_eq R, quotient.alg_map_eq S, ring_hom.comp_assoc, is_scalar_tower.algebra_map_eq S R A] lemma quotient.mkₐ_to_ring_hom (I : ideal A) : (quotient.mkₐ R I).to_ring_hom = ideal.quotient.mk I := rfl @[simp] lemma quotient.mkₐ_eq_mk (I : ideal A) : ⇑(quotient.mkₐ R I) = ideal.quotient.mk I := rfl /-- The canonical morphism `A →ₐ[R] I.quotient` is surjective. -/ lemma quotient.mkₐ_surjective (I : ideal A) : function.surjective (quotient.mkₐ R I) := surjective_quot_mk _ /-- The kernel of `A →ₐ[R] I.quotient` is `I`. -/ @[simp] lemma quotient.mkₐ_ker (I : ideal A) : (quotient.mkₐ R I).to_ring_hom.ker = I := ideal.mk_ker variables {R} {B : Type*} [comm_ring B] [algebra R B] lemma ker_lift.map_smul (f : A →ₐ[R] B) (r : R) (x : f.to_ring_hom.ker.quotient) : f.to_ring_hom.ker_lift (r • x) = r • f.to_ring_hom.ker_lift x := begin obtain ⟨a, rfl⟩ := quotient.mkₐ_surjective R _ x, rw [← alg_hom.map_smul, quotient.mkₐ_eq_mk, ring_hom.ker_lift_mk], exact f.map_smul _ _ end /-- The induced algebras morphism from the quotient by the kernel to the codomain. This is an isomorphism if `f` has a right inverse (`quotient_ker_alg_equiv_of_right_inverse`) / is surjective (`quotient_ker_alg_equiv_of_surjective`). -/ def ker_lift_alg (f : A →ₐ[R] B) : f.to_ring_hom.ker.quotient →ₐ[R] B := alg_hom.mk' f.to_ring_hom.ker_lift (λ _ _, ker_lift.map_smul f _ _) @[simp] lemma ker_lift_alg_mk (f : A →ₐ[R] B) (a : A) : ker_lift_alg f (quotient.mk f.to_ring_hom.ker a) = f a := rfl @[simp] lemma ker_lift_alg_to_ring_hom (f : A →ₐ[R] B) : (ker_lift_alg f).to_ring_hom = ring_hom.ker_lift f := rfl /-- The induced algebra morphism from the quotient by the kernel is injective. -/ lemma ker_lift_alg_injective (f : A →ₐ[R] B) : function.injective (ker_lift_alg f) := ring_hom.ker_lift_injective f /-- The first isomorphism theorem for agebras, computable version. -/ def quotient_ker_alg_equiv_of_right_inverse {f : A →ₐ[R] B} {g : B → A} (hf : function.right_inverse g f) : f.to_ring_hom.ker.quotient ≃ₐ[R] B := { ..ring_hom.quotient_ker_equiv_of_right_inverse (λ x, show f.to_ring_hom (g x) = x, from hf x), ..ker_lift_alg f} @[simp] lemma quotient_ker_alg_equiv_of_right_inverse.apply {f : A →ₐ[R] B} {g : B → A} (hf : function.right_inverse g f) (x : f.to_ring_hom.ker.quotient) : quotient_ker_alg_equiv_of_right_inverse hf x = ker_lift_alg f x := rfl @[simp] lemma quotient_ker_alg_equiv_of_right_inverse_symm.apply {f : A →ₐ[R] B} {g : B → A} (hf : function.right_inverse g f) (x : B) : (quotient_ker_alg_equiv_of_right_inverse hf).symm x = quotient.mkₐ R f.to_ring_hom.ker (g x) := rfl /-- The first isomorphism theorem for agebras. -/ noncomputable def quotient_ker_alg_equiv_of_surjective {f : A →ₐ[R] B} (hf : function.surjective f) : f.to_ring_hom.ker.quotient ≃ₐ[R] B := quotient_ker_alg_equiv_of_right_inverse (classical.some_spec hf.has_right_inverse) /-- The ring hom `R/I →+* S/J` induced by a ring hom `f : R →+* S` with `I ≤ f⁻¹(J)` -/ def quotient_map {I : ideal R} (J : ideal S) (f : R →+* S) (hIJ : I ≤ J.comap f) : I.quotient →+* J.quotient := (quotient.lift I ((quotient.mk J).comp f) (λ _ ha, by simpa [function.comp_app, ring_hom.coe_comp, quotient.eq_zero_iff_mem] using hIJ ha)) @[simp] lemma quotient_map_mk {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} {x : R} : quotient_map I f H (quotient.mk J x) = quotient.mk I (f x) := quotient.lift_mk J _ _ lemma quotient_map_comp_mk {J : ideal R} {I : ideal S} {f : R →+* S} (H : J ≤ I.comap f) : (quotient_map I f H).comp (quotient.mk J) = (quotient.mk I).comp f := ring_hom.ext (λ x, by simp only [function.comp_app, ring_hom.coe_comp, ideal.quotient_map_mk]) /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f (map f.symm) = I`. -/ @[simp] lemma map_of_equiv (I : ideal R) (f : R ≃+* S) : (I.map (f : R →+* S)).map (f.symm : S →+* R) = I := by simp [← ring_equiv.to_ring_hom_eq_coe, map_map] /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `comap f.symm (comap f) = I`. -/ @[simp] lemma comap_of_equiv (I : ideal R) (f : R ≃+* S) : (I.comap (f.symm : S →+* R)).comap (f : R →+* S) = I := by simp [← ring_equiv.to_ring_hom_eq_coe, comap_comap] /-- If `f : R ≃+* S` is a ring isomorphism and `I : ideal R`, then `map f I = comap f.symm I`. -/ lemma map_comap_of_equiv (I : ideal R) (f : R ≃+* S) : I.map (f : R →+* S) = I.comap f.symm := le_antisymm (le_comap_of_map_le (map_of_equiv I f).le) (le_map_of_comap_le_of_surjective _ f.surjective (comap_of_equiv I f).le) /-- The ring equiv `R/I ≃+* S/J` induced by a ring equiv `f : R ≃+** S`, where `J = f(I)`. -/ @[simps] def quotient_equiv (I : ideal R) (J : ideal S) (f : R ≃+* S) (hIJ : J = I.map (f : R →+* S)) : I.quotient ≃+* J.quotient := { inv_fun := quotient_map I ↑f.symm (by {rw hIJ, exact le_of_eq (map_comap_of_equiv I f)}), left_inv := by {rintro ⟨r⟩, simp }, right_inv := by {rintro ⟨s⟩, simp }, ..quotient_map J ↑f (by {rw hIJ, exact @le_comap_map _ S _ _ _ _}) } /-- `H` and `h` are kept as separate hypothesis since H is used in constructing the quotient map. -/ lemma quotient_map_injective' {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (h : I.comap f ≤ J) : function.injective (quotient_map I f H) := begin refine (quotient_map I f H).injective_iff.2 (λ a ha, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, rw [quotient_map_mk, quotient.eq_zero_iff_mem] at ha, exact (quotient.eq_zero_iff_mem).mpr (h ha), end /-- If we take `J = I.comap f` then `quotient_map` is injective automatically. -/ lemma quotient_map_injective {I : ideal S} {f : R →+* S} : function.injective (quotient_map I f le_rfl) := quotient_map_injective' le_rfl lemma quotient_map_surjective {J : ideal R} {I : ideal S} {f : R →+* S} {H : J ≤ I.comap f} (hf : function.surjective f) : function.surjective (quotient_map I f H) := λ x, let ⟨x, hx⟩ := quotient.mk_surjective x in let ⟨y, hy⟩ := hf x in ⟨(quotient.mk J) y, by simp [hx, hy]⟩ /-- Commutativity of a square is preserved when taking quotients by an ideal. -/ lemma comp_quotient_map_eq_of_comp_eq {R' S' : Type*} [comm_ring R'] [comm_ring S'] {f : R →+* S} {f' : R' →+* S'} {g : R →+* R'} {g' : S →+* S'} (hfg : f'.comp g = g'.comp f) (I : ideal S') : (quotient_map I g' le_rfl).comp (quotient_map (I.comap g') f le_rfl) = (quotient_map I f' le_rfl).comp (quotient_map (I.comap f') g (le_of_eq (trans (comap_comap f g') (hfg ▸ (comap_comap g f'))))) := begin refine ring_hom.ext (λ a, _), obtain ⟨r, rfl⟩ := quotient.mk_surjective a, simp only [ring_hom.comp_apply, quotient_map_mk], exact congr_arg (quotient.mk I) (trans (g'.comp_apply f r).symm (hfg ▸ (f'.comp_apply g r))), end variables {I : ideal R} {J: ideal S} [algebra R S] /-- The algebra hom `A/I →+* S/J` induced by an algebra hom `f : A →ₐ[R] S` with `I ≤ f⁻¹(J)`. -/ def quotient_mapₐ {I : ideal A} (J : ideal S) (f : A →ₐ[R] S) (hIJ : I ≤ J.comap f) : I.quotient →ₐ[R] J.quotient := { commutes' := λ r, begin have h : (algebra_map R I.quotient) r = (quotient.mk I) (algebra_map R A r) := rfl, simpa [h] end ..quotient_map J ↑f hIJ } @[simp] lemma quotient_map_mkₐ {I : ideal A} (J : ideal S) (f : A →ₐ[R] S) (H : I ≤ J.comap f) {x : A} : quotient_mapₐ J f H (quotient.mk I x) = quotient.mkₐ R J (f x) := rfl lemma quotient_map_comp_mkₐ {I : ideal A} (J : ideal S) (f : A →ₐ[R] S) (H : I ≤ J.comap f) : (quotient_mapₐ J f H).comp (quotient.mkₐ R I) = (quotient.mkₐ R J).comp f := alg_hom.ext (λ x, by simp only [quotient_map_mkₐ, quotient.mkₐ_eq_mk, alg_hom.comp_apply]) /-- The algebra equiv `A/I ≃ₐ[R] S/J` induced by an algebra equiv `f : A ≃ₐ[R] S`, where`J = f(I)`. -/ def quotient_equiv_alg (I : ideal A) (J : ideal S) (f : A ≃ₐ[R] S) (hIJ : J = I.map (f : A →+* S)) : I.quotient ≃ₐ[R] J.quotient := { commutes' := λ r, begin have h : (algebra_map R I.quotient) r = (quotient.mk I) (algebra_map R A r) := rfl, simpa [h] end, ..quotient_equiv I J (f : A ≃+* S) hIJ } @[priority 100] instance quotient_algebra : algebra (J.comap (algebra_map R S)).quotient J.quotient := (quotient_map J (algebra_map R S) (le_of_eq rfl)).to_algebra lemma algebra_map_quotient_injective : function.injective (algebra_map (J.comap (algebra_map R S)).quotient J.quotient) := begin rintros ⟨a⟩ ⟨b⟩ hab, replace hab := quotient.eq.mp hab, rw ← ring_hom.map_sub at hab, exact quotient.eq.mpr hab end end quotient_algebra end ideal namespace submodule variables {R : Type u} {M : Type v} variables [comm_ring R] [add_comm_group M] [module R M] -- It is even a semialgebra. But those aren't in mathlib yet. instance semimodule_submodule : semimodule (ideal R) (submodule R M) := { smul_add := smul_sup, add_smul := sup_smul, mul_smul := submodule.smul_assoc, one_smul := by simp, zero_smul := bot_smul, smul_zero := smul_bot } end submodule namespace ring_hom variables {A B C : Type*} [comm_ring A] [comm_ring B] [comm_ring C] variables (f : A →+* B) (f_inv : B → A) /-- Auxiliary definition used to define `lift_of_right_inverse` -/ def lift_of_right_inverse_aux (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) : B →+* C := { to_fun := λ b, g (f_inv b), map_one' := begin rw [← g.map_one, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_one], exact hf 1 end, map_mul' := begin intros x y, rw [← g.map_mul, ← sub_eq_zero, ← g.map_sub, ← g.mem_ker], apply hg, rw [f.mem_ker, f.map_sub, sub_eq_zero, f.map_mul], simp only [hf _], end, .. add_monoid_hom.lift_of_right_inverse f.to_add_monoid_hom f_inv hf ⟨g.to_add_monoid_hom, hg⟩ } @[simp] lemma lift_of_right_inverse_aux_comp_apply (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (a : A) : (f.lift_of_right_inverse_aux f_inv hf g hg) (f a) = g a := f.to_add_monoid_hom.lift_of_right_inverse_comp_apply f_inv hf ⟨g.to_add_monoid_hom, hg⟩ a /-- `lift_of_right_inverse f hf g hg` is the unique ring homomorphism `φ` * such that `φ.comp f = g` (`ring_hom.lift_of_right_inverse_comp`), * where `f : A →+* B` is has a right_inverse `f_inv` (`hf`), * and `g : B →+* C` satisfies `hg : f.ker ≤ g.ker`. See `ring_hom.eq_lift_of_right_inverse` for the uniqueness lemma. ``` A . | \ f | \ g | \ v \⌟ B ----> C ∃!φ ``` -/ def lift_of_right_inverse (hf : function.right_inverse f_inv f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) := { to_fun := λ g, f.lift_of_right_inverse_aux f_inv hf g.1 g.2, inv_fun := λ φ, ⟨φ.comp f, λ x hx, (mem_ker _).mpr $ by simp [(mem_ker _).mp hx]⟩, left_inv := λ g, by { ext, simp only [comp_apply, lift_of_right_inverse_aux_comp_apply, subtype.coe_mk, subtype.val_eq_coe], }, right_inv := λ φ, by { ext b, simp [lift_of_right_inverse_aux, hf b], } } /-- A non-computable version of `ring_hom.lift_of_right_inverse` for when no computable right inverse is available, that uses `function.surj_inv`. -/ @[simp] noncomputable abbreviation lift_of_surjective (hf : function.surjective f) : {g : A →+* C // f.ker ≤ g.ker} ≃ (B →+* C) := f.lift_of_right_inverse (function.surj_inv hf) (function.right_inverse_surj_inv hf) lemma lift_of_right_inverse_comp_apply (hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) (x : A) : (f.lift_of_right_inverse f_inv hf g) (f x) = g x := f.lift_of_right_inverse_aux_comp_apply f_inv hf g.1 g.2 x lemma lift_of_right_inverse_comp (hf : function.right_inverse f_inv f) (g : {g : A →+* C // f.ker ≤ g.ker}) : (f.lift_of_right_inverse f_inv hf g).comp f = g := ring_hom.ext $ f.lift_of_right_inverse_comp_apply f_inv hf g lemma eq_lift_of_right_inverse (hf : function.right_inverse f_inv f) (g : A →+* C) (hg : f.ker ≤ g.ker) (h : B →+* C) (hh : h.comp f = g) : h = (f.lift_of_right_inverse f_inv hf ⟨g, hg⟩) := begin simp_rw ←hh, exact ((f.lift_of_right_inverse f_inv hf).apply_symm_apply _).symm, end end ring_hom
8784bfb07e8e0c31749f45c62f6f26d32e386ffb
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/measure_theory/integral/integrable_on.lean
0fb400772b063f132485c87711ce1d7fae777f63
[ "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
22,576
lean
/- Copyright (c) 2021 Rémy Degenne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Yury Kudryashov -/ import measure_theory.function.l1_space import analysis.normed_space.indicator_function /-! # Functions integrable on a set and at a filter We define `integrable_on f s μ := integrable f (μ.restrict s)` and prove theorems like `integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ`. Next we define a predicate `integrable_at_filter (f : α → E) (l : filter α) (μ : measure α)` saying that `f` is integrable at some set `s ∈ l` and prove that a measurable function is integrable at `l` with respect to `μ` provided that `f` is bounded above at `l ⊓ μ.ae` and `μ` is finite at `l`. -/ noncomputable theory open set filter topological_space measure_theory function open_locale classical topological_space interval big_operators filter ennreal measure_theory variables {α β E F : Type*} [measurable_space α] section variables [measurable_space β] {l l' : filter α} {f g : α → β} {μ ν : measure α} /-- A function `f` is measurable at filter `l` w.r.t. a measure `μ` if it is ae-measurable w.r.t. `μ.restrict s` for some `s ∈ l`. -/ def measurable_at_filter (f : α → β) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, ae_measurable f (μ.restrict s) @[simp] lemma measurable_at_bot {f : α → β} : measurable_at_filter f ⊥ μ := ⟨∅, mem_bot, by simp⟩ protected lemma measurable_at_filter.eventually (h : measurable_at_filter f l μ) : ∀ᶠ s in l.lift' powerset, ae_measurable f (μ.restrict s) := (eventually_lift'_powerset' $ λ s t, ae_measurable.mono_set).2 h protected lemma measurable_at_filter.filter_mono (h : measurable_at_filter f l μ) (h' : l' ≤ l) : measurable_at_filter f l' μ := let ⟨s, hsl, hs⟩ := h in ⟨s, h' hsl, hs⟩ protected lemma ae_measurable.measurable_at_filter (h : ae_measurable f μ) : measurable_at_filter f l μ := ⟨univ, univ_mem, by rwa measure.restrict_univ⟩ lemma ae_measurable.measurable_at_filter_of_mem {s} (h : ae_measurable f (μ.restrict s)) (hl : s ∈ l) : measurable_at_filter f l μ := ⟨s, hl, h⟩ protected lemma measurable.measurable_at_filter (h : measurable f) : measurable_at_filter f l μ := h.ae_measurable.measurable_at_filter end namespace measure_theory section normed_group lemma has_finite_integral_restrict_of_bounded [normed_group E] {f : α → E} {s : set α} {μ : measure α} {C} (hs : μ s < ∞) (hf : ∀ᵐ x ∂(μ.restrict s), ∥f x∥ ≤ C) : has_finite_integral f (μ.restrict s) := by haveI : is_finite_measure (μ.restrict s) := ⟨by rwa [measure.restrict_apply_univ]⟩; exact has_finite_integral_of_bounded hf variables [normed_group E] [measurable_space E] {f g : α → E} {s t : set α} {μ ν : measure α} /-- A function is `integrable_on` a set `s` if it is almost everywhere measurable on `s` and if the integral of its pointwise norm over `s` is less than infinity. -/ def integrable_on (f : α → E) (s : set α) (μ : measure α . volume_tac) : Prop := integrable f (μ.restrict s) lemma integrable_on.integrable (h : integrable_on f s μ) : integrable f (μ.restrict s) := h @[simp] lemma integrable_on_empty : integrable_on f ∅ μ := by simp [integrable_on, integrable_zero_measure] @[simp] lemma integrable_on_univ : integrable_on f univ μ ↔ integrable f μ := by rw [integrable_on, measure.restrict_univ] lemma integrable_on_zero : integrable_on (λ _, (0:E)) s μ := integrable_zero _ _ _ lemma integrable_on_const {C : E} : integrable_on (λ _, C) s μ ↔ C = 0 ∨ μ s < ∞ := integrable_const_iff.trans $ by rw [measure.restrict_apply_univ] lemma integrable_on.mono (h : integrable_on f t ν) (hs : s ⊆ t) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono_measure $ measure.restrict_mono hs hμ lemma integrable_on.mono_set (h : integrable_on f t μ) (hst : s ⊆ t) : integrable_on f s μ := h.mono hst (le_refl _) lemma integrable_on.mono_measure (h : integrable_on f s ν) (hμ : μ ≤ ν) : integrable_on f s μ := h.mono (subset.refl _) hμ lemma integrable_on.mono_set_ae (h : integrable_on f t μ) (hst : s ≤ᵐ[μ] t) : integrable_on f s μ := h.integrable.mono_measure $ restrict_mono_ae hst lemma integrable_on.congr_set_ae (h : integrable_on f t μ) (hst : s =ᵐ[μ] t) : integrable_on f s μ := h.mono_set_ae hst.le lemma integrable.integrable_on (h : integrable f μ) : integrable_on f s μ := h.mono_measure $ measure.restrict_le_self lemma integrable.integrable_on' (h : integrable f (μ.restrict s)) : integrable_on f s μ := h lemma integrable_on.restrict (h : integrable_on f s μ) (hs : measurable_set s) : integrable_on f s (μ.restrict t) := by { rw [integrable_on, measure.restrict_restrict hs], exact h.mono_set (inter_subset_left _ _) } lemma integrable_on.left_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f s μ := h.mono_set $ subset_union_left _ _ lemma integrable_on.right_of_union (h : integrable_on f (s ∪ t) μ) : integrable_on f t μ := h.mono_set $ subset_union_right _ _ lemma integrable_on.union (hs : integrable_on f s μ) (ht : integrable_on f t μ) : integrable_on f (s ∪ t) μ := (hs.add_measure ht).mono_measure $ measure.restrict_union_le _ _ @[simp] lemma integrable_on_union : integrable_on f (s ∪ t) μ ↔ integrable_on f s μ ∧ integrable_on f t μ := ⟨λ h, ⟨h.left_of_union, h.right_of_union⟩, λ h, h.1.union h.2⟩ @[simp] lemma integrable_on_singleton_iff {x : α} [measurable_singleton_class α]: integrable_on f {x} μ ↔ f x = 0 ∨ μ {x} < ∞ := begin have : f =ᵐ[μ.restrict {x}] (λ y, f x), { filter_upwards [ae_restrict_mem (measurable_set_singleton x)], assume a ha, simp only [mem_singleton_iff.1 ha] }, rw [integrable_on, integrable_congr this, integrable_const_iff], simp, end @[simp] lemma integrable_on_finite_Union {s : set β} (hs : finite s) {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := begin apply hs.induction_on, { simp }, { intros a s ha hs hf, simp [hf, or_imp_distrib, forall_and_distrib] } end @[simp] lemma integrable_on_finset_Union {s : finset β} {t : β → set α} : integrable_on f (⋃ i ∈ s, t i) μ ↔ ∀ i ∈ s, integrable_on f (t i) μ := integrable_on_finite_Union s.finite_to_set @[simp] lemma integrable_on_fintype_Union [fintype β] {t : β → set α} : integrable_on f (⋃ i, t i) μ ↔ ∀ i, integrable_on f (t i) μ := by simpa using @integrable_on_finset_Union _ _ _ _ _ _ f μ finset.univ t lemma integrable_on.add_measure (hμ : integrable_on f s μ) (hν : integrable_on f s ν) : integrable_on f s (μ + ν) := by { delta integrable_on, rw measure.restrict_add, exact hμ.integrable.add_measure hν } @[simp] lemma integrable_on_add_measure : integrable_on f s (μ + ν) ↔ integrable_on f s μ ∧ integrable_on f s ν := ⟨λ h, ⟨h.mono_measure (measure.le_add_right (le_refl _)), h.mono_measure (measure.le_add_left (le_refl _))⟩, λ h, h.1.add_measure h.2⟩ lemma _root_.measurable_embedding.integrable_on_map_iff [measurable_space β] {e : α → β} (he : measurable_embedding e) {f : β → E} {μ : measure α} {s : set β} : integrable_on f s (measure.map e μ) ↔ integrable_on (f ∘ e) (e ⁻¹' s) μ := by simp only [integrable_on, he.restrict_map, he.integrable_map_iff] lemma integrable_on_map_equiv [measurable_space β] (e : α ≃ᵐ β) {f : β → E} {μ : measure α} {s : set β} : integrable_on f s (measure.map e μ) ↔ integrable_on (f ∘ e) (e ⁻¹' s) μ := by simp only [integrable_on, e.restrict_map, integrable_map_equiv e] lemma integrable_indicator_iff (hs : measurable_set s) : integrable (indicator s f) μ ↔ integrable_on f s μ := by simp [integrable_on, integrable, has_finite_integral, nnnorm_indicator_eq_indicator_nnnorm, ennreal.coe_indicator, lintegral_indicator _ hs, ae_measurable_indicator_iff hs] lemma integrable_on.indicator (h : integrable_on f s μ) (hs : measurable_set s) : integrable (indicator s f) μ := (integrable_indicator_iff hs).2 h lemma integrable.indicator (h : integrable f μ) (hs : measurable_set s) : integrable (indicator s f) μ := h.integrable_on.indicator hs lemma integrable_indicator_const_Lp {E} [normed_group E] [measurable_space E] [borel_space E] [second_countable_topology E] {p : ℝ≥0∞} {s : set α} (hs : measurable_set s) (hμs : μ s ≠ ∞) (c : E) : integrable (indicator_const_Lp p hs hμs c) μ := begin rw [integrable_congr indicator_const_Lp_coe_fn, integrable_indicator_iff hs, integrable_on, integrable_const_iff, lt_top_iff_ne_top], right, simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply] using hμs, end lemma integrable_on_Lp_of_measure_ne_top {E} [normed_group E] [measurable_space E] [borel_space E] [second_countable_topology E] {p : ℝ≥0∞} {s : set α} (f : Lp E p μ) (hp : 1 ≤ p) (hμs : μ s ≠ ∞) : integrable_on f s μ := begin refine mem_ℒp_one_iff_integrable.mp _, have hμ_restrict_univ : (μ.restrict s) set.univ < ∞, by simpa only [set.univ_inter, measurable_set.univ, measure.restrict_apply, lt_top_iff_ne_top], haveI hμ_finite : is_finite_measure (μ.restrict s) := ⟨hμ_restrict_univ⟩, exact ((Lp.mem_ℒp _).restrict s).mem_ℒp_of_exponent_le hp, end /-- We say that a function `f` is *integrable at filter* `l` if it is integrable on some set `s ∈ l`. Equivalently, it is eventually integrable on `s` in `l.lift' powerset`. -/ def integrable_at_filter (f : α → E) (l : filter α) (μ : measure α . volume_tac) := ∃ s ∈ l, integrable_on f s μ variables {l l' : filter α} protected lemma integrable_at_filter.eventually (h : integrable_at_filter f l μ) : ∀ᶠ s in l.lift' powerset, integrable_on f s μ := by { refine (eventually_lift'_powerset' $ λ s t hst ht, _).2 h, exact ht.mono_set hst } lemma integrable_at_filter.filter_mono (hl : l ≤ l') (hl' : integrable_at_filter f l' μ) : integrable_at_filter f l μ := let ⟨s, hs, hsf⟩ := hl' in ⟨s, hl hs, hsf⟩ lemma integrable_at_filter.inf_of_left (hl : integrable_at_filter f l μ) : integrable_at_filter f (l ⊓ l') μ := hl.filter_mono inf_le_left lemma integrable_at_filter.inf_of_right (hl : integrable_at_filter f l μ) : integrable_at_filter f (l' ⊓ l) μ := hl.filter_mono inf_le_right @[simp] lemma integrable_at_filter.inf_ae_iff {l : filter α} : integrable_at_filter f (l ⊓ μ.ae) μ ↔ integrable_at_filter f l μ := begin refine ⟨_, λ h, h.filter_mono inf_le_left⟩, rintros ⟨s, ⟨t, ht, u, hu, rfl⟩, hf⟩, refine ⟨t, ht, _⟩, refine hf.integrable.mono_measure (λ v hv, _), simp only [measure.restrict_apply hv], refine measure_mono_ae (mem_of_superset hu $ λ x hx, _), exact λ ⟨hv, ht⟩, ⟨hv, ⟨ht, hx⟩⟩ end alias integrable_at_filter.inf_ae_iff ↔ measure_theory.integrable_at_filter.of_inf_ae _ /-- If `μ` is a measure finite at filter `l` and `f` is a function such that its norm is bounded above at `l`, then `f` is integrable at `l`. -/ lemma measure.finite_at_filter.integrable_at_filter {l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) (hf : l.is_bounded_under (≤) (norm ∘ f)) : integrable_at_filter f l μ := begin obtain ⟨C, hC⟩ : ∃ C, ∀ᶠ s in (l.lift' powerset), ∀ x ∈ s, ∥f x∥ ≤ C, from hf.imp (λ C hC, eventually_lift'_powerset.2 ⟨_, hC, λ t, id⟩), rcases (hfm.eventually.and (hμ.eventually.and hC)).exists_measurable_mem_of_lift' with ⟨s, hsl, hsm, hfm, hμ, hC⟩, refine ⟨s, hsl, ⟨hfm, has_finite_integral_restrict_of_bounded hμ _⟩⟩, exact C, rw [ae_restrict_eq hsm, eventually_inf_principal], exact eventually_of_forall hC end lemma measure.finite_at_filter.integrable_at_filter_of_tendsto_ae {l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f (l ⊓ μ.ae) (𝓝 b)) : integrable_at_filter f l μ := (hμ.inf_of_left.integrable_at_filter (hfm.filter_mono inf_le_left) hf.norm.is_bounded_under_le).of_inf_ae alias measure.finite_at_filter.integrable_at_filter_of_tendsto_ae ← filter.tendsto.integrable_at_filter_ae lemma measure.finite_at_filter.integrable_at_filter_of_tendsto {l : filter α} [is_measurably_generated l] (hfm : measurable_at_filter f l μ) (hμ : μ.finite_at_filter l) {b} (hf : tendsto f l (𝓝 b)) : integrable_at_filter f l μ := hμ.integrable_at_filter hfm hf.norm.is_bounded_under_le alias measure.finite_at_filter.integrable_at_filter_of_tendsto ← filter.tendsto.integrable_at_filter variables [borel_space E] [second_countable_topology E] lemma integrable_add_of_disjoint {f g : α → E} (h : disjoint (support f) (support g)) (hf : measurable f) (hg : measurable g) : integrable (f + g) μ ↔ integrable f μ ∧ integrable g μ := begin refine ⟨λ hfg, ⟨_, _⟩, λ h, h.1.add h.2⟩, { rw ← indicator_add_eq_left h, exact hfg.indicator (measurable_set_support hf) }, { rw ← indicator_add_eq_right h, exact hfg.indicator (measurable_set_support hg) } end end normed_group end measure_theory open measure_theory variables [measurable_space E] [normed_group E] /-- If a function is integrable at `𝓝[s] x` for each point `x` of a compact set `s`, then it is integrable on `s`. -/ lemma is_compact.integrable_on_of_nhds_within [topological_space α] {μ : measure α} {s : set α} (hs : is_compact s) {f : α → E} (hf : ∀ x ∈ s, integrable_at_filter f (𝓝[s] x) μ) : integrable_on f s μ := is_compact.induction_on hs integrable_on_empty (λ s t hst ht, ht.mono_set hst) (λ s t hs ht, hs.union ht) hf /-- A function which is continuous on a set `s` is almost everywhere measurable with respect to `μ.restrict s`. -/ lemma continuous_on.ae_measurable [topological_space α] [opens_measurable_space α] [measurable_space β] [topological_space β] [borel_space β] {f : α → β} {s : set α} {μ : measure α} (hf : continuous_on f s) (hs : measurable_set s) : ae_measurable f (μ.restrict s) := begin nontriviality α, inhabit α, have : piecewise s f (λ _, f (default α)) =ᵐ[μ.restrict s] f := piecewise_ae_eq_restrict hs, refine ⟨piecewise s f (λ _, f (default α)), _, this.symm⟩, apply measurable_of_is_open, assume t ht, obtain ⟨u, u_open, hu⟩ : ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := _root_.continuous_on_iff'.1 hf t ht, rw [piecewise_preimage, set.ite, hu], exact (u_open.measurable_set.inter hs).union ((measurable_const ht.measurable_set).diff hs) end lemma continuous_on.integrable_at_nhds_within [topological_space α] [opens_measurable_space α] [borel_space E] {μ : measure α} [is_locally_finite_measure μ] {a : α} {t : set α} {f : α → E} (hft : continuous_on f t) (ht : measurable_set t) (ha : a ∈ t) : integrable_at_filter f (𝓝[t] a) μ := by haveI : (𝓝[t] a).is_measurably_generated := ht.nhds_within_is_measurably_generated _; exact (hft a ha).integrable_at_filter ⟨_, self_mem_nhds_within, hft.ae_measurable ht⟩ (μ.finite_at_nhds_within _ _) /-- A function `f` continuous on a compact set `s` is integrable on this set with respect to any locally finite measure. -/ lemma continuous_on.integrable_on_compact [topological_space α] [opens_measurable_space α] [borel_space E] [t2_space α] {μ : measure α} [is_locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous_on f s) : integrable_on f s μ := hs.integrable_on_of_nhds_within $ λ x hx, hf.integrable_at_nhds_within hs.measurable_set hx lemma continuous_on.integrable_on_Icc [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [is_locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous_on f (Icc a b)) : integrable_on f (Icc a b) μ := hf.integrable_on_compact is_compact_Icc lemma continuous_on.integrable_on_interval [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [is_locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous_on f [a, b]) : integrable_on f [a, b] μ := hf.integrable_on_compact is_compact_interval /-- A continuous function `f` is integrable on any compact set with respect to any locally finite measure. -/ lemma continuous.integrable_on_compact [topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E] {μ : measure α} [is_locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} (hf : continuous f) : integrable_on f s μ := hf.continuous_on.integrable_on_compact hs lemma continuous.integrable_on_Icc [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [is_locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous f) : integrable_on f (Icc a b) μ := hf.integrable_on_compact is_compact_Icc lemma continuous.integrable_on_Ioc [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [is_locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous f) : integrable_on f (Ioc a b) μ := hf.integrable_on_Icc.mono_set Ioc_subset_Icc_self lemma continuous.integrable_on_interval [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [is_locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous f) : integrable_on f [a, b] μ := hf.integrable_on_compact is_compact_interval lemma continuous.integrable_on_interval_oc [borel_space E] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] [measurable_space β] [opens_measurable_space β] {μ : measure β} [is_locally_finite_measure μ] {a b : β} {f : β → E} (hf : continuous f) : integrable_on f (Ι a b) μ := hf.integrable_on_Ioc /-- A continuous function with compact closure of the support is integrable on the whole space. -/ lemma continuous.integrable_of_compact_closure_support [topological_space α] [opens_measurable_space α] [t2_space α] [borel_space E] {μ : measure α} [is_locally_finite_measure μ] {f : α → E} (hf : continuous f) (hfc : is_compact (closure $ support f)) : integrable f μ := begin rw [← indicator_eq_self.2 (@subset_closure _ _ (support f)), integrable_indicator_iff is_closed_closure.measurable_set], { exact hf.integrable_on_compact hfc }, { apply_instance } end section variables [topological_space α] [opens_measurable_space α] {μ : measure α} {s t : set α} {f g : α → ℝ} lemma measure_theory.integrable_on.mul_continuous_on_of_subset (hf : integrable_on f s μ) (hg : continuous_on g t) (hs : measurable_set s) (ht : is_compact t) (hst : s ⊆ t) : integrable_on (λ x, f x * g x) s μ := begin rcases is_compact.exists_bound_of_continuous_on ht hg with ⟨C, hC⟩, rw [integrable_on, ← mem_ℒp_one_iff_integrable] at hf ⊢, have : ∀ᵐ x ∂(μ.restrict s), ∥f x * g x∥ ≤ C * ∥f x∥, { filter_upwards [ae_restrict_mem hs], assume x hx, rw [real.norm_eq_abs, abs_mul, mul_comm, real.norm_eq_abs], apply mul_le_mul_of_nonneg_right (hC x (hst hx)) (abs_nonneg _) }, exact mem_ℒp.of_le_mul hf (hf.ae_measurable.mul ((hg.mono hst).ae_measurable hs)) this, end lemma measure_theory.integrable_on.mul_continuous_on [t2_space α] (hf : integrable_on f s μ) (hg : continuous_on g s) (hs : is_compact s) : integrable_on (λ x, f x * g x) s μ := hf.mul_continuous_on_of_subset hg hs.measurable_set hs (subset.refl _) lemma measure_theory.integrable_on.continuous_on_mul_of_subset (hf : integrable_on f s μ) (hg : continuous_on g t) (hs : measurable_set s) (ht : is_compact t) (hst : s ⊆ t) : integrable_on (λ x, g x * f x) s μ := by simpa [mul_comm] using hf.mul_continuous_on_of_subset hg hs ht hst lemma measure_theory.integrable_on.continuous_on_mul [t2_space α] (hf : integrable_on f s μ) (hg : continuous_on g s) (hs : is_compact s) : integrable_on (λ x, g x * f x) s μ := hf.continuous_on_mul_of_subset hg hs.measurable_set hs (subset.refl _) end section monotone variables [topological_space α] [borel_space α] [borel_space E] [conditionally_complete_linear_order α] [conditionally_complete_linear_order E] [order_topology α] [order_topology E] [second_countable_topology E] {μ : measure α} [is_locally_finite_measure μ] {s : set α} (hs : is_compact s) {f : α → E} include hs lemma monotone_on.integrable_on_compact (hmono : monotone_on f s) : integrable_on f s μ := begin obtain rfl | h := s.eq_empty_or_nonempty, { exact integrable_on_empty }, have hbelow : bdd_below (f '' s) := ⟨f (Inf s), λ x ⟨y, hy, hyx⟩, hyx ▸ hmono (hs.Inf_mem h) hy (cInf_le hs.bdd_below hy)⟩, have habove : bdd_above (f '' s) := ⟨f (Sup s), λ x ⟨y, hy, hyx⟩, hyx ▸ hmono hy (hs.Sup_mem h) (le_cSup hs.bdd_above hy)⟩, have : metric.bounded (f '' s) := metric.bounded_of_bdd_above_of_bdd_below habove hbelow, rcases bounded_iff_forall_norm_le.mp this with ⟨C, hC⟩, exact integrable.mono' (continuous_const.integrable_on_compact hs) (ae_measurable_restrict_of_monotone_on hs.measurable_set hmono) ((ae_restrict_iff' hs.measurable_set).mpr $ ae_of_all _ $ λ y hy, hC (f y) (mem_image_of_mem f hy)), end lemma antitone_on.integrable_on_compact (hanti : antitone_on f s) : integrable_on f s μ := @monotone_on.integrable_on_compact α (order_dual E) _ _ ‹_› _ _ ‹_› _ _ _ _ ‹_› _ _ _ hs _ hanti lemma monotone.integrable_on_compact (hmono : monotone f) : integrable_on f s μ := monotone_on.integrable_on_compact hs (λ x y _ _ hxy, hmono hxy) lemma antitone.integrable_on_compact (hanti : antitone f) : integrable_on f s μ := @monotone.integrable_on_compact α (order_dual E) _ _ ‹_› _ _ ‹_› _ _ _ _ ‹_› _ _ _ hs _ hanti end monotone
a2f6b38c235183f18ca2397ee4160bdf470abe4f
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/order/basic.lean
2037538ace0ffd83bb71949e3d496d779f3deaac
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
28,290
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Mario Carneiro -/ import logic.basic data.sum data.set.basic algebra.order open function /- TODO: automatic construction of dual definitions / theorems -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} {r : α → α → Prop} theorem ge_of_eq [preorder α] {a b : α} : a = b → a ≥ b := λ h, h ▸ le_refl a theorem is_refl.swap (r) [is_refl α r] : is_refl α (swap r) := ⟨refl_of r⟩ theorem is_irrefl.swap (r) [is_irrefl α r] : is_irrefl α (swap r) := ⟨irrefl_of r⟩ theorem is_trans.swap (r) [is_trans α r] : is_trans α (swap r) := ⟨λ a b c h₁ h₂, trans_of r h₂ h₁⟩ theorem is_antisymm.swap (r) [is_antisymm α r] : is_antisymm α (swap r) := ⟨λ a b h₁ h₂, antisymm h₂ h₁⟩ theorem is_asymm.swap (r) [is_asymm α r] : is_asymm α (swap r) := ⟨λ a b h₁ h₂, asymm_of r h₂ h₁⟩ theorem is_total.swap (r) [is_total α r] : is_total α (swap r) := ⟨λ a b, (total_of r a b).swap⟩ theorem is_trichotomous.swap (r) [is_trichotomous α r] : is_trichotomous α (swap r) := ⟨λ a b, by simpa [swap, or.comm, or.left_comm] using trichotomous_of r a b⟩ theorem is_preorder.swap (r) [is_preorder α r] : is_preorder α (swap r) := {..@is_refl.swap α r _, ..@is_trans.swap α r _} theorem is_strict_order.swap (r) [is_strict_order α r] : is_strict_order α (swap r) := {..@is_irrefl.swap α r _, ..@is_trans.swap α r _} theorem is_partial_order.swap (r) [is_partial_order α r] : is_partial_order α (swap r) := {..@is_preorder.swap α r _, ..@is_antisymm.swap α r _} theorem is_total_preorder.swap (r) [is_total_preorder α r] : is_total_preorder α (swap r) := {..@is_preorder.swap α r _, ..@is_total.swap α r _} theorem is_linear_order.swap (r) [is_linear_order α r] : is_linear_order α (swap r) := {..@is_partial_order.swap α r _, ..@is_total.swap α r _} lemma antisymm_of_asymm (r) [is_asymm α r] : is_antisymm α r := ⟨λ x y h₁ h₂, (asymm h₁ h₂).elim⟩ /- Convert algebraic structure style to explicit relation style typeclasses -/ instance [preorder α] : is_refl α (≤) := ⟨le_refl⟩ instance [preorder α] : is_refl α (≥) := is_refl.swap _ instance [preorder α] : is_trans α (≤) := ⟨@le_trans _ _⟩ instance [preorder α] : is_trans α (≥) := is_trans.swap _ instance [preorder α] : is_preorder α (≤) := {} instance [preorder α] : is_preorder α (≥) := {} instance [preorder α] : is_irrefl α (<) := ⟨lt_irrefl⟩ instance [preorder α] : is_irrefl α (>) := is_irrefl.swap _ instance [preorder α] : is_trans α (<) := ⟨@lt_trans _ _⟩ instance [preorder α] : is_trans α (>) := is_trans.swap _ instance [preorder α] : is_asymm α (<) := ⟨@lt_asymm _ _⟩ instance [preorder α] : is_asymm α (>) := is_asymm.swap _ instance [preorder α] : is_antisymm α (<) := antisymm_of_asymm _ instance [preorder α] : is_antisymm α (>) := antisymm_of_asymm _ instance [preorder α] : is_strict_order α (<) := {} instance [preorder α] : is_strict_order α (>) := {} instance preorder.is_total_preorder [preorder α] [is_total α (≤)] : is_total_preorder α (≤) := {} instance [partial_order α] : is_antisymm α (≤) := ⟨@le_antisymm _ _⟩ instance [partial_order α] : is_antisymm α (≥) := is_antisymm.swap _ instance [partial_order α] : is_partial_order α (≤) := {} instance [partial_order α] : is_partial_order α (≥) := {} instance [linear_order α] : is_total α (≤) := ⟨le_total⟩ instance [linear_order α] : is_total α (≥) := is_total.swap _ instance linear_order.is_total_preorder [linear_order α] : is_total_preorder α (≤) := by apply_instance instance [linear_order α] : is_total_preorder α (≥) := {} instance [linear_order α] : is_linear_order α (≤) := {} instance [linear_order α] : is_linear_order α (≥) := {} instance [linear_order α] : is_trichotomous α (<) := ⟨lt_trichotomy⟩ instance [linear_order α] : is_trichotomous α (>) := is_trichotomous.swap _ theorem preorder.ext {α} {A B : preorder α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := begin resetI, cases A, cases B, congr, { funext x y, exact propext (H x y) }, { funext x y, dsimp [(≤)] at A_lt_iff_le_not_le B_lt_iff_le_not_le H, simp [A_lt_iff_le_not_le, B_lt_iff_le_not_le, H] }, end theorem partial_order.ext {α} {A B : partial_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := preorder.ext H; cases A; cases B; injection this; congr' theorem linear_order.ext {α} {A B : linear_order α} (H : ∀ x y : α, (by haveI := A; exact x ≤ y) ↔ x ≤ y) : A = B := by haveI this := partial_order.ext H; cases A; cases B; injection this; congr' /-- Given an order `R` on `β` and a function `f : α → β`, the preimage order on `α` is defined by `x ≤ y ↔ f x ≤ f y`. It is the unique order on `α` making `f` an order embedding (assuming `f` is injective). -/ @[simp] def order.preimage {α β} (f : α → β) (s : β → β → Prop) (x y : α) := s (f x) (f y) infix ` ⁻¹'o `:80 := order.preimage /-- The preimage of a decidable order is decidable. -/ instance order.preimage.decidable {α β} (f : α → β) (s : β → β → Prop) [H : decidable_rel s] : decidable_rel (f ⁻¹'o s) := λ x y, H _ _ section monotone variables [preorder α] [preorder β] [preorder γ] /-- A function between preorders is monotone if `a ≤ b` implies `f a ≤ f b`. -/ def monotone (f : α → β) := ∀⦃a b⦄, a ≤ b → f a ≤ f b theorem monotone_id : @monotone α α _ _ id := assume x y h, h theorem monotone_const {b : β} : monotone (λ(a:α), b) := assume x y h, le_refl b protected theorem monotone.comp {g : β → γ} {f : α → β} (m_g : monotone g) (m_f : monotone f) : monotone (g ∘ f) := assume a b h, m_g (m_f h) lemma monotone_of_monotone_nat {f : ℕ → α} (hf : ∀n, f n ≤ f (n + 1)) : monotone f | n m h := begin induction h, { refl }, { transitivity, assumption, exact hf _ } end lemma reflect_lt {α β} [linear_order α] [preorder β] {f : α → β} (hf : monotone f) {x x' : α} (h : f x < f x') : x < x' := by { rw [← not_le], intro h', apply not_le_of_lt h, exact hf h' } end monotone /-- Type tag for a set with dual order: `≤` means `≥` and `<` means `>`. -/ def order_dual (α : Type*) := α namespace order_dual instance (α : Type*) [h : nonempty α] : nonempty (order_dual α) := h instance (α : Type*) [has_le α] : has_le (order_dual α) := ⟨λx y:α, y ≤ x⟩ instance (α : Type*) [has_lt α] : has_lt (order_dual α) := ⟨λx y:α, y < x⟩ -- `dual_le` and `dual_lt` should not be simp lemmas: -- they cause a loop since `α` and `order_dual α` are definitionally equal lemma dual_le [has_le α] {a b : α} : @has_le.le (order_dual α) _ a b ↔ @has_le.le α _ b a := iff.rfl lemma dual_lt [has_lt α] {a b : α} : @has_lt.lt (order_dual α) _ a b ↔ @has_lt.lt α _ b a := iff.rfl instance (α : Type*) [preorder α] : preorder (order_dual α) := { le_refl := le_refl, le_trans := assume a b c hab hbc, le_trans hbc hab, lt_iff_le_not_le := λ _ _, lt_iff_le_not_le, .. order_dual.has_le α, .. order_dual.has_lt α } instance (α : Type*) [partial_order α] : partial_order (order_dual α) := { le_antisymm := assume a b hab hba, @le_antisymm α _ a b hba hab, .. order_dual.preorder α } instance (α : Type*) [linear_order α] : linear_order (order_dual α) := { le_total := assume a b:α, le_total b a, .. order_dual.partial_order α } instance (α : Type*) [decidable_linear_order α] : decidable_linear_order (order_dual α) := { decidable_le := show decidable_rel (λa b:α, b ≤ a), by apply_instance, decidable_lt := show decidable_rel (λa b:α, b < a), by apply_instance, .. order_dual.linear_order α } instance : Π [inhabited α], inhabited (order_dual α) := id end order_dual /- order instances on the function space -/ instance pi.preorder {ι : Type u} {α : ι → Type v} [∀i, preorder (α i)] : preorder (Πi, α i) := { le := λx y, ∀i, x i ≤ y i, le_refl := assume a i, le_refl (a i), le_trans := assume a b c h₁ h₂ i, le_trans (h₁ i) (h₂ i) } instance pi.partial_order {ι : Type u} {α : ι → Type v} [∀i, partial_order (α i)] : partial_order (Πi, α i) := { le_antisymm := λf g h1 h2, funext (λb, le_antisymm (h1 b) (h2 b)), ..pi.preorder } theorem comp_le_comp_left_of_monotone [preorder α] [preorder β] {f : β → α} {g h : γ → β} (m_f : monotone f) (le_gh : g ≤ h) : has_le.le.{max w u} (f ∘ g) (f ∘ h) := assume x, m_f (le_gh x) section monotone variables [preorder α] [preorder γ] theorem monotone_lam {f : α → β → γ} (m : ∀b, monotone (λa, f a b)) : monotone f := assume a a' h b, m b h theorem monotone_app (f : β → α → γ) (b : β) (m : monotone (λa b, f b a)) : monotone (f b) := assume a a' h, m h b end monotone def preorder.lift {α β} (f : α → β) (i : preorder β) : preorder α := by exactI { le := λx y, f x ≤ f y, le_refl := λ a, le_refl _, le_trans := λ a b c, le_trans, lt := λx y, f x < f y, lt_iff_le_not_le := λ a b, lt_iff_le_not_le } def partial_order.lift {α β} (f : α → β) (inj : injective f) (i : partial_order β) : partial_order α := by exactI { le_antisymm := λ a b h₁ h₂, inj (le_antisymm h₁ h₂), .. preorder.lift f (by apply_instance) } def linear_order.lift {α β} (f : α → β) (inj : injective f) (i : linear_order β) : linear_order α := by exactI { le_total := λx y, le_total (f x) (f y), .. partial_order.lift f inj (by apply_instance) } def decidable_linear_order.lift {α β} (f : α → β) (inj : injective f) (i : decidable_linear_order β) : decidable_linear_order α := by exactI { decidable_le := λ x y, show decidable (f x ≤ f y), by apply_instance, decidable_lt := λ x y, show decidable (f x < f y), by apply_instance, decidable_eq := λ x y, decidable_of_iff _ ⟨@inj x y, congr_arg f⟩, .. linear_order.lift f inj (by apply_instance) } instance subtype.preorder {α} [i : preorder α] (p : α → Prop) : preorder (subtype p) := preorder.lift subtype.val i instance subtype.partial_order {α} [i : partial_order α] (p : α → Prop) : partial_order (subtype p) := partial_order.lift subtype.val subtype.val_injective i instance subtype.linear_order {α} [i : linear_order α] (p : α → Prop) : linear_order (subtype p) := linear_order.lift subtype.val subtype.val_injective i instance subtype.decidable_linear_order {α} [i : decidable_linear_order α] (p : α → Prop) : decidable_linear_order (subtype p) := decidable_linear_order.lift subtype.val subtype.val_injective i instance prod.has_le (α : Type u) (β : Type v) [has_le α] [has_le β] : has_le (α × β) := ⟨λp q, p.1 ≤ q.1 ∧ p.2 ≤ q.2⟩ instance prod.preorder (α : Type u) (β : Type v) [preorder α] [preorder β] : preorder (α × β) := { le_refl := assume ⟨a, b⟩, ⟨le_refl a, le_refl b⟩, le_trans := assume ⟨a, b⟩ ⟨c, d⟩ ⟨e, f⟩ ⟨hac, hbd⟩ ⟨hce, hdf⟩, ⟨le_trans hac hce, le_trans hbd hdf⟩, .. prod.has_le α β } /-- The pointwise partial order on a product. (The lexicographic ordering is defined in order/lexicographic.lean, and the instances are available via the type synonym `lex α β = α × β`.) -/ instance prod.partial_order (α : Type u) (β : Type v) [partial_order α] [partial_order β] : partial_order (α × β) := { le_antisymm := assume ⟨a, b⟩ ⟨c, d⟩ ⟨hac, hbd⟩ ⟨hca, hdb⟩, prod.ext (le_antisymm hac hca) (le_antisymm hbd hdb), .. prod.preorder α β } /- additional order classes -/ /-- order without a top element; somtimes called cofinal -/ class no_top_order (α : Type u) [preorder α] : Prop := (no_top : ∀a:α, ∃a', a < a') lemma no_top [preorder α] [no_top_order α] : ∀a:α, ∃a', a < a' := no_top_order.no_top /-- order without a bottom element; somtimes called coinitial or dense -/ class no_bot_order (α : Type u) [preorder α] : Prop := (no_bot : ∀a:α, ∃a', a' < a) lemma no_bot [preorder α] [no_bot_order α] : ∀a:α, ∃a', a' < a := no_bot_order.no_bot instance order_dual.no_top_order (α : Type u) [preorder α] [no_bot_order α] : no_top_order (order_dual α) := ⟨λ a, @no_bot α _ _ a⟩ instance order_dual.no_bot_order (α : Type u) [preorder α] [no_top_order α] : no_bot_order (order_dual α) := ⟨λ a, @no_top α _ _ a⟩ /-- An order is dense if there is an element between any pair of distinct elements. -/ class densely_ordered (α : Type u) [preorder α] : Prop := (dense : ∀a₁ a₂:α, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂) lemma dense [preorder α] [densely_ordered α] : ∀{a₁ a₂:α}, a₁ < a₂ → ∃a, a₁ < a ∧ a < a₂ := densely_ordered.dense instance order_dual.densely_ordered (α : Type u) [preorder α] [densely_ordered α] : densely_ordered (order_dual α) := ⟨λ a₁ a₂ ha, (@dense α _ _ _ _ ha).imp $ λ a, and.symm⟩ lemma le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h : ∀a₃>a₂, a₁ ≤ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_lt_of_le ‹a < a₁› (h _ ‹a₂ < a›) lemma eq_of_le_of_forall_le_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃>a₂, a₁ ≤ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_le_of_dense h₂) h₁ lemma le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α}(h : ∀a₃<a₁, a₂ ≥ a₃) : a₁ ≤ a₂ := le_of_not_gt $ assume ha, let ⟨a, ha₁, ha₂⟩ := dense ha in lt_irrefl a $ lt_of_le_of_lt (h _ ‹a < a₁›) ‹a₂ < a› lemma eq_of_le_of_forall_ge_of_dense [linear_order α] [densely_ordered α] {a₁ a₂ : α} (h₁ : a₂ ≤ a₁) (h₂ : ∀a₃<a₁, a₂ ≥ a₃) : a₁ = a₂ := le_antisymm (le_of_forall_ge_of_dense h₂) h₁ lemma dense_or_discrete [linear_order α] (a₁ a₂ : α) : (∃a, a₁ < a ∧ a < a₂) ∨ ((∀a>a₁, a ≥ a₂) ∧ (∀a<a₂, a ≤ a₁)) := classical.or_iff_not_imp_left.2 $ assume h, ⟨assume a ha₁, le_of_not_gt $ assume ha₂, h ⟨a, ha₁, ha₂⟩, assume a ha₂, le_of_not_gt $ assume ha₁, h ⟨a, ha₁, ha₂⟩⟩ lemma trans_trichotomous_left [is_trans α r] [is_trichotomous α r] {a b c : α} : ¬r b a → r b c → r a c := begin intros h₁ h₂, rcases trichotomous_of r a b with h₃|h₃|h₃, exact trans h₃ h₂, rw h₃, exact h₂, exfalso, exact h₁ h₃ end lemma trans_trichotomous_right [is_trans α r] [is_trichotomous α r] {a b c : α} : r a b → ¬r c b → r a c := begin intros h₁ h₂, rcases trichotomous_of r b c with h₃|h₃|h₃, exact trans h₁ h₃, rw ←h₃, exact h₁, exfalso, exact h₂ h₃ end variables {s : β → β → Prop} {t : γ → γ → Prop} theorem is_irrefl_of_is_asymm [is_asymm α r] : is_irrefl α r := ⟨λ a h, asymm h h⟩ /-- Construct a partial order from a `is_strict_order` relation -/ def partial_order_of_SO (r) [is_strict_order α r] : partial_order α := { le := λ x y, x = y ∨ r x y, lt := r, le_refl := λ x, or.inl rfl, le_trans := λ x y z h₁ h₂, match y, z, h₁, h₂ with | _, _, or.inl rfl, h₂ := h₂ | _, _, h₁, or.inl rfl := h₁ | _, _, or.inr h₁, or.inr h₂ := or.inr (trans h₁ h₂) end, le_antisymm := λ x y h₁ h₂, match y, h₁, h₂ with | _, or.inl rfl, h₂ := rfl | _, h₁, or.inl rfl := rfl | _, or.inr h₁, or.inr h₂ := (asymm h₁ h₂).elim end, lt_iff_le_not_le := λ x y, ⟨λ h, ⟨or.inr h, not_or (λ e, by rw e at h; exact irrefl _ h) (asymm h)⟩, λ ⟨h₁, h₂⟩, h₁.resolve_left (λ e, h₂ $ e ▸ or.inl rfl)⟩ } section prio set_option default_priority 100 -- see Note [default priority] /-- This is basically the same as `is_strict_total_order`, but that definition is in Type (probably by mistake) and also has redundant assumptions. -/ @[algebra] class is_strict_total_order' (α : Type u) (lt : α → α → Prop) extends is_trichotomous α lt, is_strict_order α lt : Prop. end prio /-- Construct a linear order from a `is_strict_total_order'` relation -/ def linear_order_of_STO' (r) [is_strict_total_order' α r] : linear_order α := { le_total := λ x y, match y, trichotomous_of r x y with | y, or.inl h := or.inl (or.inr h) | _, or.inr (or.inl rfl) := or.inl (or.inl rfl) | _, or.inr (or.inr h) := or.inr (or.inr h) end, ..partial_order_of_SO r } /-- Construct a decidable linear order from a `is_strict_total_order'` relation -/ def decidable_linear_order_of_STO' (r) [is_strict_total_order' α r] [decidable_rel r] : decidable_linear_order α := by letI LO := linear_order_of_STO' r; exact { decidable_le := λ x y, decidable_of_iff (¬ r y x) (@not_lt _ _ y x), ..LO } noncomputable def classical.DLO (α) [LO : linear_order α] : decidable_linear_order α := { decidable_le := classical.dec_rel _, ..LO } theorem is_strict_total_order'.swap (r) [is_strict_total_order' α r] : is_strict_total_order' α (swap r) := {..is_trichotomous.swap r, ..is_strict_order.swap r} instance [linear_order α] : is_strict_total_order' α (<) := {} /-- A connected order is one satisfying the condition `a < c → a < b ∨ b < c`. This is recognizable as an intuitionistic substitute for `a ≤ b ∨ b ≤ a` on the constructive reals, and is also known as negative transitivity, since the contrapositive asserts transitivity of the relation `¬ a < b`. -/ @[algebra] class is_order_connected (α : Type u) (lt : α → α → Prop) : Prop := (conn : ∀ a b c, lt a c → lt a b ∨ lt b c) theorem is_order_connected.neg_trans {r : α → α → Prop} [is_order_connected α r] {a b c} (h₁ : ¬ r a b) (h₂ : ¬ r b c) : ¬ r a c := mt (is_order_connected.conn a b c) $ by simp [h₁, h₂] theorem is_strict_weak_order_of_is_order_connected [is_asymm α r] [is_order_connected α r] : is_strict_weak_order α r := { trans := λ a b c h₁ h₂, (is_order_connected.conn _ c _ h₁).resolve_right (asymm h₂), incomp_trans := λ a b c ⟨h₁, h₂⟩ ⟨h₃, h₄⟩, ⟨is_order_connected.neg_trans h₁ h₃, is_order_connected.neg_trans h₄ h₂⟩, ..@is_irrefl_of_is_asymm α r _ } @[priority 100] -- see Note [lower instance priority] instance is_order_connected_of_is_strict_total_order' [is_strict_total_order' α r] : is_order_connected α r := ⟨λ a b c h, (trichotomous _ _).imp_right (λ o, o.elim (λ e, e ▸ h) (λ h', trans h' h))⟩ @[priority 100] -- see Note [lower instance priority] instance is_strict_total_order_of_is_strict_total_order' [is_strict_total_order' α r] : is_strict_total_order α r := {..is_strict_weak_order_of_is_order_connected} instance [linear_order α] : is_strict_total_order α (<) := by apply_instance instance [linear_order α] : is_order_connected α (<) := by apply_instance instance [linear_order α] : is_incomp_trans α (<) := by apply_instance instance [linear_order α] : is_strict_weak_order α (<) := by apply_instance /-- An extensional relation is one in which an element is determined by its set of predecessors. It is named for the `x ∈ y` relation in set theory, whose extensionality is one of the first axioms of ZFC. -/ @[algebra] class is_extensional (α : Type u) (r : α → α → Prop) : Prop := (ext : ∀ a b, (∀ x, r x a ↔ r x b) → a = b) @[priority 100] -- see Note [lower instance priority] instance is_extensional_of_is_strict_total_order' [is_strict_total_order' α r] : is_extensional α r := ⟨λ a b H, ((@trichotomous _ r _ a b) .resolve_left $ mt (H _).2 (irrefl a)) .resolve_right $ mt (H _).1 (irrefl b)⟩ section prio set_option default_priority 100 -- see Note [default priority] /-- A well order is a well-founded linear order. -/ @[algebra] class is_well_order (α : Type u) (r : α → α → Prop) extends is_strict_total_order' α r : Prop := (wf : well_founded r) end prio @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_strict_total_order {α} (r : α → α → Prop) [is_well_order α r] : is_strict_total_order α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_extensional {α} (r : α → α → Prop) [is_well_order α r] : is_extensional α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_trichotomous {α} (r : α → α → Prop) [is_well_order α r] : is_trichotomous α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_trans {α} (r : α → α → Prop) [is_well_order α r] : is_trans α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_irrefl {α} (r : α → α → Prop) [is_well_order α r] : is_irrefl α r := by apply_instance @[priority 100] -- see Note [lower instance priority] instance is_well_order.is_asymm {α} (r : α → α → Prop) [is_well_order α r] : is_asymm α r := by apply_instance noncomputable def decidable_linear_order_of_is_well_order (r : α → α → Prop) [is_well_order α r] : decidable_linear_order α := by { haveI := linear_order_of_STO' r, exact classical.DLO α } instance empty_relation.is_well_order [subsingleton α] : is_well_order α empty_relation := { trichotomous := λ a b, or.inr $ or.inl $ subsingleton.elim _ _, irrefl := λ a, id, trans := λ a b c, false.elim, wf := ⟨λ a, ⟨_, λ y, false.elim⟩⟩ } instance nat.lt.is_well_order : is_well_order ℕ (<) := ⟨nat.lt_wf⟩ instance sum.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α ⊕ β) (sum.lex r s) := { trichotomous := λ a b, by cases a; cases b; simp; apply trichotomous, irrefl := λ a, by cases a; simp; apply irrefl, trans := λ a b c, by cases a; cases b; simp; cases c; simp; apply trans, wf := sum.lex_wf (is_well_order.wf r) (is_well_order.wf s) } instance prod.lex.is_well_order [is_well_order α r] [is_well_order β s] : is_well_order (α × β) (prod.lex r s) := { trichotomous := λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩, match @trichotomous _ r _ a₁ b₁ with | or.inl h₁ := or.inl $ prod.lex.left _ _ _ h₁ | or.inr (or.inr h₁) := or.inr $ or.inr $ prod.lex.left _ _ _ h₁ | or.inr (or.inl e) := e ▸ match @trichotomous _ s _ a₂ b₂ with | or.inl h := or.inl $ prod.lex.right _ _ h | or.inr (or.inr h) := or.inr $ or.inr $ prod.lex.right _ _ h | or.inr (or.inl e) := e ▸ or.inr $ or.inl rfl end end, irrefl := λ ⟨a₁, a₂⟩ h, by cases h with _ _ _ _ h _ _ _ h; [exact irrefl _ h, exact irrefl _ h], trans := λ a b c h₁ h₂, begin cases h₁ with a₁ a₂ b₁ b₂ ab a₁ b₁ b₂ ab; cases h₂ with _ _ c₁ c₂ bc _ _ c₂ bc, { exact prod.lex.left _ _ _ (trans ab bc) }, { exact prod.lex.left _ _ _ ab }, { exact prod.lex.left _ _ _ bc }, { exact prod.lex.right _ _ (trans ab bc) } end, wf := prod.lex_wf (is_well_order.wf r) (is_well_order.wf s) } /-- An unbounded or cofinal set -/ def unbounded (r : α → α → Prop) (s : set α) : Prop := ∀ a, ∃ b ∈ s, ¬ r b a /-- A bounded or final set -/ def bounded (r : α → α → Prop) (s : set α) : Prop := ∃a, ∀ b ∈ s, r b a @[simp] lemma not_bounded_iff {r : α → α → Prop} (s : set α) : ¬bounded r s ↔ unbounded r s := begin classical, simp only [bounded, unbounded, not_forall, not_exists, exists_prop, not_and, not_not] end @[simp] lemma not_unbounded_iff {r : α → α → Prop} (s : set α) : ¬unbounded r s ↔ bounded r s := by { classical, rw [not_iff_comm, not_bounded_iff] } namespace well_founded /-- If `r` is a well founded relation, then any nonempty set has a minimum element with respect to `r`. -/ theorem has_min {α} {r : α → α → Prop} (H : well_founded r) (s : set α) : s.nonempty → ∃ a ∈ s, ∀ x ∈ s, ¬ r x a | ⟨a, ha⟩ := (acc.rec_on (H.apply a) $ λ x _ IH, classical.not_imp_not.1 $ λ hne hx, hne $ ⟨x, hx, λ y hy hyx, hne $ IH y hyx hy⟩) ha /-- The minimum element of a nonempty set in a well-founded order -/ noncomputable def min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p.nonempty) : α := classical.some (H.has_min p h) theorem min_mem {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p.nonempty) : H.min p h ∈ p := let ⟨h, _⟩ := classical.some_spec (H.has_min p h) in h theorem not_lt_min {α} {r : α → α → Prop} (H : well_founded r) (p : set α) (h : p.nonempty) {x} (xp : x ∈ p) : ¬ r x (H.min p h) := let ⟨_, h'⟩ := classical.some_spec (H.has_min p h) in h' _ xp open set protected noncomputable def sup {α} {r : α → α → Prop} (wf : well_founded r) (s : set α) (h : bounded r s) : α := wf.min { x | ∀a ∈ s, r a x } h protected lemma lt_sup {α} {r : α → α → Prop} (wf : well_founded r) {s : set α} (h : bounded r s) {x} (hx : x ∈ s) : r x (wf.sup s h) := min_mem wf { x | ∀a ∈ s, r a x } h x hx section open_locale classical protected noncomputable def succ {α} {r : α → α → Prop} (wf : well_founded r) (x : α) : α := if h : ∃y, r x y then wf.min { y | r x y } h else x protected lemma lt_succ {α} {r : α → α → Prop} (wf : well_founded r) {x : α} (h : ∃y, r x y) : r x (wf.succ x) := by { rw [well_founded.succ, dif_pos h], apply min_mem } end protected lemma lt_succ_iff {α} {r : α → α → Prop} [wo : is_well_order α r] {x : α} (h : ∃y, r x y) (y : α) : r y (wo.wf.succ x) ↔ r y x ∨ y = x := begin split, { intro h', have : ¬r x y, { intro hy, rw [well_founded.succ, dif_pos] at h', exact wo.wf.not_lt_min _ h hy h' }, rcases trichotomous_of r x y with hy | hy | hy, exfalso, exact this hy, right, exact hy.symm, left, exact hy }, rintro (hy | rfl), exact trans hy (wo.wf.lt_succ h), exact wo.wf.lt_succ h end end well_founded variable (r) local infix ` ≼ ` : 50 := r /-- A family of elements of α is directed (with respect to a relation `≼` on α) if there is a member of the family `≼`-above any pair in the family. -/ def directed {ι : Sort v} (f : ι → α) := ∀x y, ∃z, f x ≼ f z ∧ f y ≼ f z /-- A subset of α is directed if there is an element of the set `≼`-above any pair of elements in the set. -/ def directed_on (s : set α) := ∀ (x ∈ s) (y ∈ s), ∃z ∈ s, x ≼ z ∧ y ≼ z theorem directed_on_iff_directed {s} : @directed_on α r s ↔ directed r (coe : s → α) := by simp [directed, directed_on]; refine ball_congr (λ x hx, by simp; refl) theorem directed_on_image {s} {f : β → α} : directed_on r (f '' s) ↔ directed_on (f ⁻¹'o r) s := by simp only [directed_on, set.ball_image_iff, set.bex_image_iff, order.preimage] theorem directed_on.mono {s : set α} (h : directed_on r s) {r' : α → α → Prop} (H : ∀ {a b}, r a b → r' a b) : directed_on r' s := λ x hx y hy, let ⟨z, zs, xz, yz⟩ := h x hx y hy in ⟨z, zs, H xz, H yz⟩ theorem directed_comp {ι} (f : ι → β) (g : β → α) : directed r (g ∘ f) ↔ directed (g ⁻¹'o r) f := iff.rfl variable {r} theorem directed.mono {s : α → α → Prop} {ι} {f : ι → α} (H : ∀ a b, r a b → s a b) (h : directed r f) : directed s f := λ a b, let ⟨c, h₁, h₂⟩ := h a b in ⟨c, H _ _ h₁, H _ _ h₂⟩ theorem directed.mono_comp {ι} {rb : β → β → Prop} {g : α → β} {f : ι → α} (hg : ∀ ⦃x y⦄, x ≼ y → rb (g x) (g y)) (hf : directed r f) : directed rb (g ∘ f) := (directed_comp rb f g).2 $ hf.mono hg section prio set_option default_priority 100 -- see Note [default priority] class directed_order (α : Type u) extends preorder α := (directed : ∀ i j : α, ∃ k, i ≤ k ∧ j ≤ k) end prio
0261a51cbdc3e8679fa387641f284c9ee62bf28f
f608b09bd951f29eccb4c27187f55223000fa85f
/2020/lean/love01_definitions_and_statements_demo.lean
9579fd37e3ad69de5764d525ccd3f8b267b91853
[]
no_license
bobismijnnaam/advent-of-code
9482d954b8f381b28a4823337e3688963fd05d6d
471b9cad04eba7010da79416aef7a3218b1f4541
refs/heads/master
1,639,530,767,572
1,639,425,773,000
1,639,425,773,000
225,140,719
0
0
null
null
null
null
UTF-8
Lean
false
false
10,753
lean
import .lovelib #eval 2 + 2 /- # LoVe Preface ## Proof Assistants Proof assistants (also called interactive theorem provers) * check and help develop formal proofs; * can be used to prove big theorems, not only logic puzzles; * can be tedious to use; * are highly addictive (think video games). A selection of proof assistants, classified by logical foundations: * set theory: Isabelle/ZF, Metamath, Mizar; * simple type theory: HOL4, HOL Light, Isabelle/HOL; * **dependent type theory**: Agda, Coq, **Lean**, Matita, PVS. ## Success Stories Mathematics: * the four-color theorem (in Coq); * the odd-order theorem (in Coq); * the Kepler conjecture (in HOL Light and Isabelle/HOL). Computer science: * hardware * operating systems * programming language theory * compilers * security ## Lean Lean is a proof assistant developed primarily by Leonardo de Moura (Microsoft Research) since 2012. Its mathematical library, `mathlib`, is developed under the leadership of Jeremy Avigad (Carnegie Mellon University). We use community version 3.20.0. We use its basic libraries, `mathlib`, and `LoVelib`. Lean is a research project. Strengths: * highly expressive logic based on a dependent type theory called the **calculus of inductive constructions**; * extended with classical axioms and quotient types; * metaprogramming framework; * modern user interface; * documentation; * open source; * endless source of puns (Lean Forward, Lean Together, Boolean, …). ## This Course ### Web Site https://lean-forward.github.io/logical-verification/2020/index.html ### Installation Instructions https://github.com/blanchette/logical_verification_2020/blob/master/README.md#logical-verification-2020---installation-instructions ### Repository (Demos, Exercises, Homework) https://github.com/blanchette/logical_verification_2020 The file you are currently looking at is a demo. There are * 13 demo files; * 13 exercise sheets; * 11 homework sheets (10 points each); * 1 project (20 points). You may submit at most 10 homework, or at most 8 homework and the project. Homework, including the project, must be done individually. The homework builds on the exercises, which build on the demos. ### The Hitchhiker's Guide to Logical Verification https://github.com/blanchette/logical_verification_2020/blob/master/hitchhikers_guide.pdf https://github.com/blanchette/logical_verification_2020/blob/master/hitchhikers_guide_tablet.pdf The lecture notes consist of a preface and 13 chapters. They cover the same material as the corresponding lectures but with more details. Sometimes there will not be enough time to cover everything in class, so reading the lecture notes will be necessary. ### Final Exam The course aims at teaching concepts, not syntax. Therefore, the final exam is on paper. ## Our Goal We want you to * master fundamental theory and techniques in interactive theorem proving; * familiarize yourselves with some application areas; * develop some practical skills you can apply on a larger project (as a hobby, for an MSc or PhD, or in industry); * feel ready to move to another proof assistant and apply what you have learned; * understand the domain well enough to start reading scientific papers. This course is neither a pure metatheory course nor a Lean tutorial. Lean is our vehicle, not an end in itself. # LoVe Demo 1: Definitions and Statements We introduce the basics of Lean and proof assistants, without trying to carry out actual proofs yet. We focus on specifying objects and statements of their intended properties. -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /- ## A View of Lean In a first approximation: Lean = functional programming + logic In today's lecture, we cover inductive types, recursive functions, and lemma statements. If you are not familiar with typed functional programming (e.g., Haskell, ML, OCaml, Scala), we recommend that you study a tutorial, such as the first chapters of the online tutorial __Learn You a Haskell for Great Good!__: http://learnyouahaskell.com/chapters Make sure to at least reach the section titled "Lambdas". ## Types and Terms Similar to simply typed λ-calculus or typed functional programming languages (ML, OCaml, Haskell). Types `σ`, `τ`, `υ`: * type variables `α`; * basic types `T`; * complex types `T σ1 … σN`. Some type constructors `T` are written infix, e.g., `→` (function type). The function arrow is right-associative: `σ₁ → σ₂ → σ₃ → τ` = `σ₁ → (σ₂ → (σ₃ → τ))`. In Lean, type variables must be bound using `∀`, e.g., `∀α, α → α`. Terms `t`, `u`: * constants `c`; * variables `x`; * applications `t u`; * λ-expressions `λx, t`. __Currying__: functions can be * fully applied (e.g., `f x y z` if `f` is ternary); * partially applied (e.g., `f x y`, `f x`); * left unapplied (e.g., `f`). Application is left-associative: `f x y z` = `((f x) y) z`. -/ #check ℕ #check ℤ #check empty #check unit #check bool #check ℕ → ℤ #check ℤ → ℕ #check bool → ℕ → ℤ #check (bool → ℕ) → ℤ #check ℕ → (bool → ℕ) → ℤ #check λx : ℕ, x #check λf : ℕ → ℕ, λg : ℕ → ℕ, λh : ℕ → ℕ, λx : ℕ, h (g (f x)) #check λ(f g h : ℕ → ℕ) (x : ℕ), h (g (f x)) constants a b : ℤ constant f : ℤ → ℤ constant g : ℤ → ℤ → ℤ #check λx : ℤ, g (f (g a x)) (g x b) #check λx, g (f (g a x)) (g x b) #check λx, x constant trool : Type constants trool.true trool.false trool.maybe : trool /- ### Type Checking and Type Inference Type checking and type inference are decidable problems, but this property is quickly lost if features such as overloading or subtyping are added. Type judgment: `C ⊢ t : σ`, meaning `t` has type `σ` in local context `C`. Typing rules: —————————— Cst if c is declared with type σ C ⊢ c : σ —————————— Var if x : σ occurs in C C ⊢ x : σ C ⊢ t : σ → τ C ⊢ u : σ ——————————————————————————— App C ⊢ t u : τ C, x : σ ⊢ t : τ ———————————————————————— Lam C ⊢ (λx : σ, t) : σ → τ ### Type Inhabitation Given a type `σ`, the __type inhabitation__ problem consists of finding a term of that type. Recursive procedure: 1. If `σ` is of the form `τ → υ`, a candidate inhabitant is an anonymous function of the form `λx, _`. 2. Alternatively, you can use any constant or variable `x : τ₁ → ⋯ → τN → σ` to build the term `x _ … _`. -/ constants α β γ : Type def some_fun_of_type : (α → β → γ) → ((β → α) → β) → α → γ := λf g a, f a (g (λb, a)) /- ## Type Definitions An __inductive type__ (also called __inductive datatype__, __algebraic datatype__, or just __datatype__) is a type that consists all the values that can be built using a finite number of applications of its __constructors__, and only those. ### Natural Numbers -/ namespace my_nat /- Definition of type `nat` (= `ℕ`) of natural numbers, using Peano-style unary notation: -/ inductive nat : Type | zero : nat | succ : nat → nat #check nat #check nat.zero #check nat.succ end my_nat #print nat #print ℕ /- ### Arithmetic Expressions -/ inductive aexp : Type | num : ℤ → aexp | var : string → aexp | add : aexp → aexp → aexp | sub : aexp → aexp → aexp | mul : aexp → aexp → aexp | div : aexp → aexp → aexp /- ### Lists -/ namespace my_list inductive list (α : Type) : Type | nil : list | cons : α → list → list #check list.nil #check list.cons end my_list #print list /- ## Function Definitions The syntax for defining a function operating on an inductive type is very compact: We define a single function and use __pattern matching__ to extract the arguments to the constructors. -/ def add : ℕ → ℕ → ℕ | m nat.zero := m | m (nat.succ n) := nat.succ (add m n) #eval add 2 7 #reduce add 2 7 def mul : ℕ → ℕ → ℕ | _ nat.zero := nat.zero | m (nat.succ n) := add m (mul m n) #eval mul 2 7 #print mul #print mul._main def power : ℕ → ℕ → ℕ | _ nat.zero := 1 | m (nat.succ n) := m * power m n #eval power 2 5 def power₂ (m : ℕ) : ℕ → ℕ | nat.zero := 1 | (nat.succ n) := m * power₂ n #eval power₂ 2 5 def iter (α : Type) (z : α) (f : α → α) : ℕ → α | nat.zero := z | (nat.succ n) := f (iter n) #check iter def power₃ (m n : ℕ) : ℕ := iter ℕ 1 (λl, m * l) n #eval power₃ 2 5 def append (α : Type) : list α → list α → list α | list.nil ys := ys | (list.cons x xs) ys := list.cons x (append xs ys) #check append #eval append _ [3, 1] [4, 1, 5] /- Aliases: `[]` := `nil` `x :: xs` := `cons x xs` `[x₁, …, xN]` := `x₁ :: … :: xN` -/ def append₂ {α : Type} : list α → list α → list α | list.nil ys := ys | (list.cons x xs) ys := list.cons x (append₂ xs ys) #check append₂ #eval append₂ [3, 1] [4, 1, 5] #check @append₂ #eval @append₂ _ [3, 1] [4, 1, 5] def append₃ {α : Type} : list α → list α → list α | [] ys := ys | (x :: xs) ys := x :: append₃ xs ys def reverse {α : Type} : list α → list α | [] := [] | (x :: xs) := reverse xs ++ [x] def eval (env : string → ℤ) : aexp → ℤ | (aexp.num i) := i | (aexp.var x) := env x | (aexp.add e₁ e₂) := eval e₁ + eval e₂ | (aexp.sub e₁ e₂) := eval e₁ - eval e₂ | (aexp.mul e₁ e₂) := eval e₁ * eval e₂ | (aexp.div e₁ e₂) := eval e₁ / eval e₂ /- Lean only accepts the function definitions for which it can prove termination. In particular, it accepts __structurally recursive__ functions, which peel off exactly one constructor at a time. ## Lemma Statements Notice the similarity with `def` commands. -/ namespace sorry_lemmas lemma add_comm (m n : ℕ) : add m n = add n m := sorry lemma add_assoc (l m n : ℕ) : add (add l m) n = add l (add m n) := sorry lemma mul_comm (m n : ℕ) : mul m n = mul n m := sorry lemma mul_assoc (l m n : ℕ) : mul (mul l m) n = mul l (mul m n) := sorry lemma mul_add (l m n : ℕ) : mul l (add m n) = add (mul l m) (mul l n) := sorry lemma reverse_reverse {α : Type} (xs : list α) : reverse (reverse xs) = xs := sorry /- Axioms are like lemmas but without proofs (`:= …`). Constant declarations are like definitions but without bodies (`:= …`). -/ constants a b : ℤ axiom a_less_b : a < b end sorry_lemmas end LoVe
4e641857d8833a74a04b886e7eb408310a505715
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Elab/Deriving/Basic.lean
e3b35b6e6630072b31e79871b4e6270abbf86d22
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
3,818
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Wojciech Nawrocki -/ import Lean.Elab.Command import Lean.Elab.MutualDef namespace Lean.Elab open Command def DerivingHandler := (typeNames : Array Name) → (args? : Option (TSyntax ``Parser.Term.structInst)) → CommandElabM Bool def DerivingHandlerNoArgs := (typeNames : Array Name) → CommandElabM Bool builtin_initialize derivingHandlersRef : IO.Ref (NameMap (List DerivingHandler)) ← IO.mkRef {} /-- A `DerivingHandler` is called on the fully qualified names of all types it is running for as well as the syntax of a `with` argument, if present. For example, `deriving instance Foo with fooArgs for Bar, Baz` invokes ``fooHandler #[`Bar, `Baz] `(fooArgs)``. -/ def registerDerivingHandlerWithArgs (className : Name) (handler : DerivingHandler) : IO Unit := do unless (← initializing) do throw (IO.userError "failed to register deriving handler, it can only be registered during initialization") derivingHandlersRef.modify fun m => match m.find? className with | some handlers => m.insert className (handler :: handlers) | none => m.insert className [handler] /-- Like `registerBuiltinDerivingHandlerWithArgs` but ignoring any `with` argument. -/ def registerDerivingHandler (className : Name) (handler : DerivingHandlerNoArgs) : IO Unit := do registerDerivingHandlerWithArgs className fun typeNames _ => handler typeNames def defaultHandler (className : Name) (typeNames : Array Name) : CommandElabM Unit := do throwError "default handlers have not been implemented yet, class: '{className}' types: {typeNames}" def applyDerivingHandlers (className : Name) (typeNames : Array Name) (args? : Option (TSyntax ``Parser.Term.structInst)) : CommandElabM Unit := do match (← derivingHandlersRef.get).find? className with | some handlers => for handler in handlers do if (← handler typeNames args?) then return () defaultHandler className typeNames | none => defaultHandler className typeNames private def tryApplyDefHandler (className : Name) (declName : Name) : CommandElabM Bool := liftTermElabM do Term.processDefDeriving className declName @[builtinCommandElab «deriving»] def elabDeriving : CommandElab | `(deriving instance $[$classes $[with $argss?]?],* for $[$declNames],*) => do let declNames ← declNames.mapM resolveGlobalConstNoOverloadWithInfo for cls in classes, args? in argss? do try let className ← resolveGlobalConstNoOverloadWithInfo cls withRef cls do if declNames.size == 1 && args?.isNone then if (← tryApplyDefHandler className declNames[0]!) then return () applyDerivingHandlers className declNames args? catch ex => logException ex | _ => throwUnsupportedSyntax structure DerivingClassView where ref : Syntax className : Name args? : Option (TSyntax ``Parser.Term.structInst) def getOptDerivingClasses [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadInfoTree m] (optDeriving : Syntax) : m (Array DerivingClassView) := do match optDeriving with | `(Parser.Command.optDeriving| deriving $[$classes $[with $argss?]?],*) => let mut ret := #[] for cls in classes, args? in argss? do let className ← resolveGlobalConstNoOverloadWithInfo cls ret := ret.push { ref := cls, className := className, args? } return ret | _ => return #[] def DerivingClassView.applyHandlers (view : DerivingClassView) (declNames : Array Name) : CommandElabM Unit := withRef view.ref do applyDerivingHandlers view.className declNames view.args? builtin_initialize registerTraceClass `Elab.Deriving end Lean.Elab
0dd65989a72d235e71570dc8d9241ffdeefe516d
ed27983dd289b3bcad416f0b1927105d6ef19db8
/src/inClassNotes/type_library/list.lean
e8d37461c8ce173c37014e7b9192d5538d446ab1
[]
no_license
liuxin-James/complogic-s21
0d55b76dbe25024473d31d98b5b83655c365f811
13e03e0114626643b44015c654151fb651603486
refs/heads/master
1,681,109,264,463
1,618,848,261,000
1,618,848,261,000
337,599,491
0
0
null
1,613,141,619,000
1,612,925,555,000
null
UTF-8
Lean
false
false
651
lean
namespace hidden universe u inductive list (α : Type u) : Type u | nil {} : list | cons (h : α) (t : list) : list #check list #check list #check list nat #check list string #check list bool def l : list nat := list.nil def t : list nat := list.cons (3) (list.cons (4) (list.cons 5 list.nil) ) #reduce l #check l #reduce t #check (list.cons 5 list.nil) -- [3,4,5] /- inductive list (α : Type u) : Type u | nil {} : list | cons (h : α) (t : list) : list -/ def list_len {α : Type u} : list α → nat | list.nil := 0 | (list.cons h t) := (list_len t) + 1 #eval list_len t #print list end hidden
53bf67c5e6a06a6258db7b68fd507135acaa341c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/combinatorics/simple_graph/connectivity.lean
1fd28aca8c8cc0596f72e0129e8fd8b972ccec79
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
66,191
lean
/- Copyright (c) 2021 Kyle Miller. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kyle Miller -/ import combinatorics.simple_graph.basic import combinatorics.simple_graph.subgraph import data.list.rotate /-! # Graph connectivity In a simple graph, * A *walk* is a finite sequence of adjacent vertices, and can be thought of equally well as a sequence of directed edges. * A *trail* is a walk whose edges each appear no more than once. * A *path* is a trail whose vertices appear no more than once. * A *cycle* is a nonempty trail whose first and last vertices are the same and whose vertices except for the first appear no more than once. **Warning:** graph theorists mean something different by "path" than do homotopy theorists. A "walk" in graph theory is a "path" in homotopy theory. Another warning: some graph theorists use "path" and "simple path" for "walk" and "path." Some definitions and theorems have inspiration from multigraph counterparts in [Chou1994]. ## Main definitions * `simple_graph.walk` (with accompanying pattern definitions `simple_graph.walk.nil'` and `simple_graph.walk.cons'`) * `simple_graph.walk.is_trail`, `simple_graph.walk.is_path`, and `simple_graph.walk.is_cycle`. * `simple_graph.path` * `simple_graph.walk.map` and `simple_graph.path.map` for the induced map on walks, given an (injective) graph homomorphism. * `simple_graph.reachable` for the relation of whether there exists a walk between a given pair of vertices * `simple_graph.preconnected` and `simple_graph.connected` are predicates on simple graphs for whether every vertex can be reached from every other, and in the latter case, whether the vertex type is nonempty. * `simple_graph.subgraph.connected` gives subgraphs the connectivity predicate via `simple_graph.subgraph.coe`. * `simple_graph.connected_component` is the type of connected components of a given graph. * `simple_graph.is_bridge` for whether an edge is a bridge edge ## Main statements * `simple_graph.is_bridge_iff_mem_and_forall_cycle_not_mem` characterizes bridge edges in terms of there being no cycle containing them. ## Tags walks, trails, paths, circuits, cycles, bridge edges -/ open function universes u v w namespace simple_graph variables {V : Type u} {V' : Type v} {V'' : Type w} variables (G : simple_graph V) (G' : simple_graph V') (G'' : simple_graph V'') /-- A walk is a sequence of adjacent vertices. For vertices `u v : V`, the type `walk u v` consists of all walks starting at `u` and ending at `v`. We say that a walk *visits* the vertices it contains. The set of vertices a walk visits is `simple_graph.walk.support`. See `simple_graph.walk.nil'` and `simple_graph.walk.cons'` for patterns that can be useful in definitions since they make the vertices explicit. -/ @[derive decidable_eq] inductive walk : V → V → Type u | nil {u : V} : walk u u | cons {u v w: V} (h : G.adj u v) (p : walk v w) : walk u w attribute [refl] walk.nil @[simps] instance walk.inhabited (v : V) : inhabited (G.walk v v) := ⟨walk.nil⟩ /-- The one-edge walk associated to a pair of adjacent vertices. -/ @[pattern, reducible] def adj.to_walk {G : simple_graph V} {u v : V} (h : G.adj u v) : G.walk u v := walk.cons h walk.nil namespace walk variables {G} /-- Pattern to get `walk.nil` with the vertex as an explicit argument. -/ @[pattern] abbreviation nil' (u : V) : G.walk u u := walk.nil /-- Pattern to get `walk.cons` with the vertices as explicit arguments. -/ @[pattern] abbreviation cons' (u v w : V) (h : G.adj u v) (p : G.walk v w) : G.walk u w := walk.cons h p /-- Change the endpoints of a walk using equalities. This is helpful for relaxing definitional equality constraints and to be able to state otherwise difficult-to-state lemmas. While this is a simple wrapper around `eq.rec`, it gives a canonical way to write it. The simp-normal form is for the `copy` to be pushed outward. That way calculations can occur within the "copy context." -/ protected def copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : G.walk u' v' := eq.rec (eq.rec p hv) hu @[simp] lemma copy_rfl_rfl {u v} (p : G.walk u v) : p.copy rfl rfl = p := rfl @[simp] lemma copy_copy {u v u' v' u'' v''} (p : G.walk u v) (hu : u = u') (hv : v = v') (hu' : u' = u'') (hv' : v' = v'') : (p.copy hu hv).copy hu' hv' = p.copy (hu.trans hu') (hv.trans hv') := by { subst_vars, refl } @[simp] lemma copy_nil {u u'} (hu : u = u') : (walk.nil : G.walk u u).copy hu hu = walk.nil := by { subst_vars, refl } lemma copy_cons {u v w u' w'} (h : G.adj u v) (p : G.walk v w) (hu : u = u') (hw : w = w') : (walk.cons h p).copy hu hw = walk.cons (by rwa ← hu) (p.copy rfl hw) := by { subst_vars, refl } @[simp] lemma cons_copy {u v w v' w'} (h : G.adj u v) (p : G.walk v' w') (hv : v' = v) (hw : w' = w) : walk.cons h (p.copy hv hw) = (walk.cons (by rwa hv) p).copy rfl hw := by { subst_vars, refl } lemma exists_eq_cons_of_ne : Π {u v : V} (hne : u ≠ v) (p : G.walk u v), ∃ (w : V) (h : G.adj u w) (p' : G.walk w v), p = cons h p' | _ _ hne nil := (hne rfl).elim | _ _ _ (cons h p') := ⟨_, h, p', rfl⟩ /-- The length of a walk is the number of edges/darts along it. -/ def length : Π {u v : V}, G.walk u v → ℕ | _ _ nil := 0 | _ _ (cons _ q) := q.length.succ /-- The concatenation of two compatible walks. -/ @[trans] def append : Π {u v w : V}, G.walk u v → G.walk v w → G.walk u w | _ _ _ nil q := q | _ _ _ (cons h p) q := cons h (p.append q) /-- The concatenation of the reverse of the first walk with the second walk. -/ protected def reverse_aux : Π {u v w : V}, G.walk u v → G.walk u w → G.walk v w | _ _ _ nil q := q | _ _ _ (cons h p) q := reverse_aux p (cons (G.symm h) q) /-- The walk in reverse. -/ @[symm] def reverse {u v : V} (w : G.walk u v) : G.walk v u := w.reverse_aux nil /-- Get the `n`th vertex from a walk, where `n` is generally expected to be between `0` and `p.length`, inclusive. If `n` is greater than or equal to `p.length`, the result is the path's endpoint. -/ def get_vert : Π {u v : V} (p : G.walk u v) (n : ℕ), V | u v nil _ := u | u v (cons _ _) 0 := u | u v (cons _ q) (n+1) := q.get_vert n @[simp] lemma get_vert_zero {u v} (w : G.walk u v) : w.get_vert 0 = u := by { cases w; refl } lemma get_vert_of_length_le {u v} (w : G.walk u v) {i : ℕ} (hi : w.length ≤ i) : w.get_vert i = v := begin induction w with _ x y z hxy wyz IH generalizing i, { refl }, { cases i, { cases hi, }, { exact IH (nat.succ_le_succ_iff.1 hi) } } end @[simp] lemma get_vert_length {u v} (w : G.walk u v) : w.get_vert w.length = v := w.get_vert_of_length_le rfl.le lemma adj_get_vert_succ {u v} (w : G.walk u v) {i : ℕ} (hi : i < w.length) : G.adj (w.get_vert i) (w.get_vert (i+1)) := begin induction w with _ x y z hxy wyz IH generalizing i, { cases hi, }, { cases i, { simp [get_vert, hxy] }, { exact IH (nat.succ_lt_succ_iff.1 hi) } }, end @[simp] lemma cons_append {u v w x : V} (h : G.adj u v) (p : G.walk v w) (q : G.walk w x) : (cons h p).append q = cons h (p.append q) := rfl @[simp] lemma cons_nil_append {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h nil).append p = cons h p := rfl @[simp] lemma append_nil : Π {u v : V} (p : G.walk u v), p.append nil = p | _ _ nil := rfl | _ _ (cons h p) := by rw [cons_append, append_nil] @[simp] lemma nil_append {u v : V} (p : G.walk u v) : nil.append p = p := rfl lemma append_assoc : Π {u v w x : V} (p : G.walk u v) (q : G.walk v w) (r : G.walk w x), p.append (q.append r) = (p.append q).append r | _ _ _ _ nil _ _ := rfl | _ _ _ _ (cons h p') q r := by { dunfold append, rw append_assoc, } @[simp] lemma append_copy_copy {u v w u' v' w'} (p : G.walk u v) (q : G.walk v w) (hu : u = u') (hv : v = v') (hw : w = w') : (p.copy hu hv).append (q.copy hv hw) = (p.append q).copy hu hw := by { subst_vars, refl } @[simp] lemma reverse_nil {u : V} : (nil : G.walk u u).reverse = nil := rfl lemma reverse_singleton {u v : V} (h : G.adj u v) : (cons h nil).reverse = cons (G.symm h) nil := rfl @[simp] lemma cons_reverse_aux {u v w x : V} (p : G.walk u v) (q : G.walk w x) (h : G.adj w u) : (cons h p).reverse_aux q = p.reverse_aux (cons (G.symm h) q) := rfl @[simp] protected lemma append_reverse_aux : Π {u v w x : V} (p : G.walk u v) (q : G.walk v w) (r : G.walk u x), (p.append q).reverse_aux r = q.reverse_aux (p.reverse_aux r) | _ _ _ _ nil _ _ := rfl | _ _ _ _ (cons h p') q r := append_reverse_aux p' q (cons (G.symm h) r) @[simp] protected lemma reverse_aux_append : Π {u v w x : V} (p : G.walk u v) (q : G.walk u w) (r : G.walk w x), (p.reverse_aux q).append r = p.reverse_aux (q.append r) | _ _ _ _ nil _ _ := rfl | _ _ _ _ (cons h p') q r := by simp [reverse_aux_append p' (cons (G.symm h) q) r] protected lemma reverse_aux_eq_reverse_append {u v w : V} (p : G.walk u v) (q : G.walk u w) : p.reverse_aux q = p.reverse.append q := by simp [reverse] @[simp] lemma reverse_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).reverse = p.reverse.append (cons (G.symm h) nil) := by simp [reverse] @[simp] lemma reverse_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).reverse = p.reverse.copy hv hu := by { subst_vars, refl } @[simp] lemma reverse_append {u v w : V} (p : G.walk u v) (q : G.walk v w) : (p.append q).reverse = q.reverse.append p.reverse := by simp [reverse] @[simp] lemma reverse_reverse : Π {u v : V} (p : G.walk u v), p.reverse.reverse = p | _ _ nil := rfl | _ _ (cons h p) := by simp [reverse_reverse] @[simp] lemma length_nil {u : V} : (nil : G.walk u u).length = 0 := rfl @[simp] lemma length_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).length = p.length + 1 := rfl @[simp] lemma length_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).length = p.length := by { subst_vars, refl } @[simp] lemma length_append : Π {u v w : V} (p : G.walk u v) (q : G.walk v w), (p.append q).length = p.length + q.length | _ _ _ nil _ := by simp | _ _ _ (cons _ _) _ := by simp [length_append, add_left_comm, add_comm] @[simp] protected lemma length_reverse_aux : Π {u v w : V} (p : G.walk u v) (q : G.walk u w), (p.reverse_aux q).length = p.length + q.length | _ _ _ nil _ := by simp! | _ _ _ (cons _ _) _ := by simp [length_reverse_aux, nat.add_succ, nat.succ_add] @[simp] lemma length_reverse {u v : V} (p : G.walk u v) : p.reverse.length = p.length := by simp [reverse] lemma eq_of_length_eq_zero : Π {u v : V} {p : G.walk u v}, p.length = 0 → u = v | _ _ nil _ := rfl @[simp] lemma exists_length_eq_zero_iff {u v : V} : (∃ (p : G.walk u v), p.length = 0) ↔ u = v := begin split, { rintro ⟨p, hp⟩, exact eq_of_length_eq_zero hp, }, { rintro rfl, exact ⟨nil, rfl⟩, }, end @[simp] lemma length_eq_zero_iff {u : V} {p : G.walk u u} : p.length = 0 ↔ p = nil := by cases p; simp /-- The `support` of a walk is the list of vertices it visits in order. -/ def support : Π {u v : V}, G.walk u v → list V | u v nil := [u] | u v (cons h p) := u :: p.support /-- The `darts` of a walk is the list of darts it visits in order. -/ def darts : Π {u v : V}, G.walk u v → list G.dart | u v nil := [] | u v (cons h p) := ⟨(u, _), h⟩ :: p.darts /-- The `edges` of a walk is the list of edges it visits in order. This is defined to be the list of edges underlying `simple_graph.walk.darts`. -/ def edges {u v : V} (p : G.walk u v) : list (sym2 V) := p.darts.map dart.edge @[simp] lemma support_nil {u : V} : (nil : G.walk u u).support = [u] := rfl @[simp] lemma support_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).support = u :: p.support := rfl @[simp] lemma support_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).support = p.support := by { subst_vars, refl } lemma support_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : (p.append p').support = p.support ++ p'.support.tail := by induction p; cases p'; simp [*] @[simp] lemma support_reverse {u v : V} (p : G.walk u v) : p.reverse.support = p.support.reverse := by induction p; simp [support_append, *] lemma support_ne_nil {u v : V} (p : G.walk u v) : p.support ≠ [] := by cases p; simp lemma tail_support_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : (p.append p').support.tail = p.support.tail ++ p'.support.tail := by rw [support_append, list.tail_append_of_ne_nil _ _ (support_ne_nil _)] lemma support_eq_cons {u v : V} (p : G.walk u v) : p.support = u :: p.support.tail := by cases p; simp @[simp] lemma start_mem_support {u v : V} (p : G.walk u v) : u ∈ p.support := by cases p; simp @[simp] lemma end_mem_support {u v : V} (p : G.walk u v) : v ∈ p.support := by induction p; simp [*] lemma mem_support_iff {u v w : V} (p : G.walk u v) : w ∈ p.support ↔ w = u ∨ w ∈ p.support.tail := by cases p; simp lemma mem_support_nil_iff {u v : V} : u ∈ (nil : G.walk v v).support ↔ u = v := by simp @[simp] lemma mem_tail_support_append_iff {t u v w : V} (p : G.walk u v) (p' : G.walk v w) : t ∈ (p.append p').support.tail ↔ t ∈ p.support.tail ∨ t ∈ p'.support.tail := by rw [tail_support_append, list.mem_append] @[simp] lemma end_mem_tail_support_of_ne {u v : V} (h : u ≠ v) (p : G.walk u v) : v ∈ p.support.tail := by { obtain ⟨_, _, _, rfl⟩ := exists_eq_cons_of_ne h p, simp } @[simp] lemma mem_support_append_iff {t u v w : V} (p : G.walk u v) (p' : G.walk v w) : t ∈ (p.append p').support ↔ t ∈ p.support ∨ t ∈ p'.support := begin simp only [mem_support_iff, mem_tail_support_append_iff], by_cases h : t = v; by_cases h' : t = u; subst_vars; try { have := ne.symm h' }; simp [*], end @[simp] lemma subset_support_append_left {V : Type u} {G : simple_graph V} {u v w : V} (p : G.walk u v) (q : G.walk v w) : p.support ⊆ (p.append q).support := by simp only [walk.support_append, list.subset_append_left] @[simp] lemma subset_support_append_right {V : Type u} {G : simple_graph V} {u v w : V} (p : G.walk u v) (q : G.walk v w) : q.support ⊆ (p.append q).support := by { intro h, simp only [mem_support_append_iff, or_true, implies_true_iff] { contextual := tt }} lemma coe_support {u v : V} (p : G.walk u v) : (p.support : multiset V) = {u} + p.support.tail := by cases p; refl lemma coe_support_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : ((p.append p').support : multiset V) = {u} + p.support.tail + p'.support.tail := by rw [support_append, ←multiset.coe_add, coe_support] lemma coe_support_append' [decidable_eq V] {u v w : V} (p : G.walk u v) (p' : G.walk v w) : ((p.append p').support : multiset V) = p.support + p'.support - {v} := begin rw [support_append, ←multiset.coe_add], simp only [coe_support], rw add_comm {v}, simp only [← add_assoc, add_tsub_cancel_right], end lemma chain_adj_support : Π {u v w : V} (h : G.adj u v) (p : G.walk v w), list.chain G.adj u p.support | _ _ _ h nil := list.chain.cons h list.chain.nil | _ _ _ h (cons h' p) := list.chain.cons h (chain_adj_support h' p) lemma chain'_adj_support : Π {u v : V} (p : G.walk u v), list.chain' G.adj p.support | _ _ nil := list.chain.nil | _ _ (cons h p) := chain_adj_support h p lemma chain_dart_adj_darts : Π {d : G.dart} {v w : V} (h : d.snd = v) (p : G.walk v w), list.chain G.dart_adj d p.darts | _ _ _ h nil := list.chain.nil | _ _ _ h (cons h' p) := list.chain.cons h (chain_dart_adj_darts (by exact rfl) p) lemma chain'_dart_adj_darts : Π {u v : V} (p : G.walk u v), list.chain' G.dart_adj p.darts | _ _ nil := trivial | _ _ (cons h p) := chain_dart_adj_darts rfl p /-- Every edge in a walk's edge list is an edge of the graph. It is written in this form (rather than using `⊆`) to avoid unsightly coercions. -/ lemma edges_subset_edge_set : Π {u v : V} (p : G.walk u v) ⦃e : sym2 V⦄ (h : e ∈ p.edges), e ∈ G.edge_set | _ _ (cons h' p') e h := by rcases h with ⟨rfl, h⟩; solve_by_elim lemma adj_of_mem_edges {u v x y : V} (p : G.walk u v) (h : ⟦(x, y)⟧ ∈ p.edges) : G.adj x y := edges_subset_edge_set p h @[simp] lemma darts_nil {u : V} : (nil : G.walk u u).darts = [] := rfl @[simp] lemma darts_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).darts = ⟨(u, v), h⟩ :: p.darts := rfl @[simp] lemma darts_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).darts = p.darts := by { subst_vars, refl } @[simp] lemma darts_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : (p.append p').darts = p.darts ++ p'.darts := by induction p; simp [*] @[simp] lemma darts_reverse {u v : V} (p : G.walk u v) : p.reverse.darts = (p.darts.map dart.symm).reverse := by induction p; simp [*, sym2.eq_swap] lemma mem_darts_reverse {u v : V} {d : G.dart} {p : G.walk u v} : d ∈ p.reverse.darts ↔ d.symm ∈ p.darts := by simp lemma cons_map_snd_darts {u v : V} (p : G.walk u v) : u :: p.darts.map dart.snd = p.support := by induction p; simp! [*] lemma map_snd_darts {u v : V} (p : G.walk u v) : p.darts.map dart.snd = p.support.tail := by simpa using congr_arg list.tail (cons_map_snd_darts p) lemma map_fst_darts_append {u v : V} (p : G.walk u v) : p.darts.map dart.fst ++ [v] = p.support := by induction p; simp! [*] lemma map_fst_darts {u v : V} (p : G.walk u v) : p.darts.map dart.fst = p.support.init := by simpa! using congr_arg list.init (map_fst_darts_append p) @[simp] lemma edges_nil {u : V} : (nil : G.walk u u).edges = [] := rfl @[simp] lemma edges_cons {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).edges = ⟦(u, v)⟧ :: p.edges := rfl @[simp] lemma edges_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).edges = p.edges := by { subst_vars, refl } @[simp] lemma edges_append {u v w : V} (p : G.walk u v) (p' : G.walk v w) : (p.append p').edges = p.edges ++ p'.edges := by simp [edges] @[simp] lemma edges_reverse {u v : V} (p : G.walk u v) : p.reverse.edges = p.edges.reverse := by simp [edges] @[simp] lemma length_support {u v : V} (p : G.walk u v) : p.support.length = p.length + 1 := by induction p; simp * @[simp] lemma length_darts {u v : V} (p : G.walk u v) : p.darts.length = p.length := by induction p; simp * @[simp] lemma length_edges {u v : V} (p : G.walk u v) : p.edges.length = p.length := by simp [edges] lemma dart_fst_mem_support_of_mem_darts : Π {u v : V} (p : G.walk u v) {d : G.dart}, d ∈ p.darts → d.fst ∈ p.support | u v (cons h p') d hd := begin simp only [support_cons, darts_cons, list.mem_cons_iff] at hd ⊢, rcases hd with (rfl|hd), { exact or.inl rfl, }, { exact or.inr (dart_fst_mem_support_of_mem_darts _ hd), }, end lemma dart_snd_mem_support_of_mem_darts {u v : V} (p : G.walk u v) {d : G.dart} (h : d ∈ p.darts) : d.snd ∈ p.support := by simpa using p.reverse.dart_fst_mem_support_of_mem_darts (by simp [h] : d.symm ∈ p.reverse.darts) lemma fst_mem_support_of_mem_edges {t u v w : V} (p : G.walk v w) (he : ⟦(t, u)⟧ ∈ p.edges) : t ∈ p.support := begin obtain ⟨d, hd, he⟩ := list.mem_map.mp he, rw dart_edge_eq_mk_iff' at he, rcases he with ⟨rfl, rfl⟩ | ⟨rfl, rfl⟩, { exact dart_fst_mem_support_of_mem_darts _ hd, }, { exact dart_snd_mem_support_of_mem_darts _ hd, }, end lemma snd_mem_support_of_mem_edges {t u v w : V} (p : G.walk v w) (he : ⟦(t, u)⟧ ∈ p.edges) : u ∈ p.support := by { rw sym2.eq_swap at he, exact p.fst_mem_support_of_mem_edges he } lemma darts_nodup_of_support_nodup {u v : V} {p : G.walk u v} (h : p.support.nodup) : p.darts.nodup := begin induction p, { simp, }, { simp only [darts_cons, support_cons, list.nodup_cons] at h ⊢, refine ⟨λ h', h.1 (dart_fst_mem_support_of_mem_darts p_p h'), p_ih h.2⟩, } end lemma edges_nodup_of_support_nodup {u v : V} {p : G.walk u v} (h : p.support.nodup) : p.edges.nodup := begin induction p, { simp, }, { simp only [edges_cons, support_cons, list.nodup_cons] at h ⊢, exact ⟨λ h', h.1 (fst_mem_support_of_mem_edges p_p h'), p_ih h.2⟩, } end /-! ### Trails, paths, circuits, cycles -/ /-- A *trail* is a walk with no repeating edges. -/ structure is_trail {u v : V} (p : G.walk u v) : Prop := (edges_nodup : p.edges.nodup) /-- A *path* is a walk with no repeating vertices. Use `simple_graph.walk.is_path.mk'` for a simpler constructor. -/ structure is_path {u v : V} (p : G.walk u v) extends to_trail : is_trail p : Prop := (support_nodup : p.support.nodup) /-- A *circuit* at `u : V` is a nonempty trail beginning and ending at `u`. -/ structure is_circuit {u : V} (p : G.walk u u) extends to_trail : is_trail p : Prop := (ne_nil : p ≠ nil) /-- A *cycle* at `u : V` is a circuit at `u` whose only repeating vertex is `u` (which appears exactly twice). -/ structure is_cycle {u : V} (p : G.walk u u) extends to_circuit : is_circuit p : Prop := (support_nodup : p.support.tail.nodup) lemma is_trail_def {u v : V} (p : G.walk u v) : p.is_trail ↔ p.edges.nodup := ⟨is_trail.edges_nodup, λ h, ⟨h⟩⟩ @[simp] lemma is_trail_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).is_trail ↔ p.is_trail := by { subst_vars, refl } lemma is_path.mk' {u v : V} {p : G.walk u v} (h : p.support.nodup) : is_path p := ⟨⟨edges_nodup_of_support_nodup h⟩, h⟩ lemma is_path_def {u v : V} (p : G.walk u v) : p.is_path ↔ p.support.nodup := ⟨is_path.support_nodup, is_path.mk'⟩ @[simp] lemma is_path_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).is_path ↔ p.is_path := by { subst_vars, refl } lemma is_circuit_def {u : V} (p : G.walk u u) : p.is_circuit ↔ is_trail p ∧ p ≠ nil := iff.intro (λ h, ⟨h.1, h.2⟩) (λ h, ⟨h.1, h.2⟩) @[simp] lemma is_circuit_copy {u u'} (p : G.walk u u) (hu : u = u') : (p.copy hu hu).is_circuit ↔ p.is_circuit := by { subst_vars, refl } lemma is_cycle_def {u : V} (p : G.walk u u) : p.is_cycle ↔ is_trail p ∧ p ≠ nil ∧ p.support.tail.nodup := iff.intro (λ h, ⟨h.1.1, h.1.2, h.2⟩) (λ h, ⟨⟨h.1, h.2.1⟩, h.2.2⟩) @[simp] lemma is_cycle_copy {u u'} (p : G.walk u u) (hu : u = u') : (p.copy hu hu).is_cycle ↔ p.is_cycle := by { subst_vars, refl } @[simp] lemma is_trail.nil {u : V} : (nil : G.walk u u).is_trail := ⟨by simp [edges]⟩ lemma is_trail.of_cons {u v w : V} {h : G.adj u v} {p : G.walk v w} : (cons h p).is_trail → p.is_trail := by simp [is_trail_def] @[simp] lemma cons_is_trail_iff {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).is_trail ↔ p.is_trail ∧ ⟦(u, v)⟧ ∉ p.edges := by simp [is_trail_def, and_comm] lemma is_trail.reverse {u v : V} (p : G.walk u v) (h : p.is_trail) : p.reverse.is_trail := by simpa [is_trail_def] using h @[simp] lemma reverse_is_trail_iff {u v : V} (p : G.walk u v) : p.reverse.is_trail ↔ p.is_trail := by split; { intro h, convert h.reverse _, try { rw reverse_reverse } } lemma is_trail.of_append_left {u v w : V} {p : G.walk u v} {q : G.walk v w} (h : (p.append q).is_trail) : p.is_trail := by { rw [is_trail_def, edges_append, list.nodup_append] at h, exact ⟨h.1⟩ } lemma is_trail.of_append_right {u v w : V} {p : G.walk u v} {q : G.walk v w} (h : (p.append q).is_trail) : q.is_trail := by { rw [is_trail_def, edges_append, list.nodup_append] at h, exact ⟨h.2.1⟩ } lemma is_trail.count_edges_le_one [decidable_eq V] {u v : V} {p : G.walk u v} (h : p.is_trail) (e : sym2 V) : p.edges.count e ≤ 1 := list.nodup_iff_count_le_one.mp h.edges_nodup e lemma is_trail.count_edges_eq_one [decidable_eq V] {u v : V} {p : G.walk u v} (h : p.is_trail) {e : sym2 V} (he : e ∈ p.edges) : p.edges.count e = 1 := list.count_eq_one_of_mem h.edges_nodup he lemma is_path.nil {u : V} : (nil : G.walk u u).is_path := by { fsplit; simp } lemma is_path.of_cons {u v w : V} {h : G.adj u v} {p : G.walk v w} : (cons h p).is_path → p.is_path := by simp [is_path_def] @[simp] lemma cons_is_path_iff {u v w : V} (h : G.adj u v) (p : G.walk v w) : (cons h p).is_path ↔ p.is_path ∧ u ∉ p.support := by split; simp [is_path_def] { contextual := tt } @[simp] lemma is_path_iff_eq_nil {u : V} (p : G.walk u u) : p.is_path ↔ p = nil := by { cases p; simp [is_path.nil] } lemma is_path.reverse {u v : V} {p : G.walk u v} (h : p.is_path) : p.reverse.is_path := by simpa [is_path_def] using h @[simp] lemma is_path_reverse_iff {u v : V} (p : G.walk u v) : p.reverse.is_path ↔ p.is_path := by split; intro h; convert h.reverse; simp lemma is_path.of_append_left {u v w : V} {p : G.walk u v} {q : G.walk v w} : (p.append q).is_path → p.is_path := by { simp only [is_path_def, support_append], exact list.nodup.of_append_left } lemma is_path.of_append_right {u v w : V} {p : G.walk u v} {q : G.walk v w} (h : (p.append q).is_path) : q.is_path := begin rw ←is_path_reverse_iff at h ⊢, rw reverse_append at h, apply h.of_append_left, end @[simp] lemma is_cycle.not_of_nil {u : V} : ¬ (nil : G.walk u u).is_cycle := λ h, h.ne_nil rfl lemma cons_is_cycle_iff {u v : V} (p : G.walk v u) (h : G.adj u v) : (walk.cons h p).is_cycle ↔ p.is_path ∧ ¬ ⟦(u, v)⟧ ∈ p.edges := begin simp only [walk.is_cycle_def, walk.is_path_def, walk.is_trail_def, edges_cons, list.nodup_cons, support_cons, list.tail_cons], have : p.support.nodup → p.edges.nodup := edges_nodup_of_support_nodup, tauto, end /-! ### About paths -/ instance [decidable_eq V] {u v : V} (p : G.walk u v) : decidable p.is_path := by { rw is_path_def, apply_instance } lemma is_path.length_lt [fintype V] {u v : V} {p : G.walk u v} (hp : p.is_path) : p.length < fintype.card V := by { rw [nat.lt_iff_add_one_le, ← length_support], exact hp.support_nodup.length_le_card } /-! ### Walk decompositions -/ section walk_decomp variables [decidable_eq V] /-- Given a vertex in the support of a path, give the path up until (and including) that vertex. -/ def take_until : Π {v w : V} (p : G.walk v w) (u : V) (h : u ∈ p.support), G.walk v u | v w nil u h := by rw mem_support_nil_iff.mp h | v w (cons r p) u h := if hx : v = u then by subst u else cons r (take_until p _ $ h.cases_on (λ h', (hx h'.symm).elim) id) /-- Given a vertex in the support of a path, give the path from (and including) that vertex to the end. In other words, drop vertices from the front of a path until (and not including) that vertex. -/ def drop_until : Π {v w : V} (p : G.walk v w) (u : V) (h : u ∈ p.support), G.walk u w | v w nil u h := by rw mem_support_nil_iff.mp h | v w (cons r p) u h := if hx : v = u then by { subst u, exact cons r p } else drop_until p _ $ h.cases_on (λ h', (hx h'.symm).elim) id /-- The `take_until` and `drop_until` functions split a walk into two pieces. The lemma `count_support_take_until_eq_one` specifies where this split occurs. -/ @[simp] lemma take_spec {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.take_until u h).append (p.drop_until u h) = p := begin induction p, { rw mem_support_nil_iff at h, subst u, refl, }, { obtain (rfl|h) := h, { simp! }, { simp! only, split_ifs with h'; subst_vars; simp [*], } }, end lemma mem_support_iff_exists_append {V : Type u} {G : simple_graph V} {u v w : V} {p : G.walk u v} : w ∈ p.support ↔ ∃ (q : G.walk u w) (r : G.walk w v), p = q.append r := begin classical, split, { exact λ h, ⟨_, _, (p.take_spec h).symm⟩ }, { rintro ⟨q, r, rfl⟩, simp only [mem_support_append_iff, end_mem_support, start_mem_support, or_self], }, end @[simp] lemma count_support_take_until_eq_one {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.take_until u h).support.count u = 1 := begin induction p, { rw mem_support_nil_iff at h, subst u, simp!, }, { obtain (rfl|h) := h, { simp! }, { simp! only, split_ifs with h'; rw eq_comm at h'; subst_vars; simp! [*, list.count_cons], } }, end lemma count_edges_take_until_le_one {u v w : V} (p : G.walk v w) (h : u ∈ p.support) (x : V) : (p.take_until u h).edges.count ⟦(u, x)⟧ ≤ 1 := begin induction p with u' u' v' w' ha p' ih, { rw mem_support_nil_iff at h, subst u, simp!, }, { obtain (rfl|h) := h, { simp!, }, { simp! only, split_ifs with h', { subst h', simp, }, { rw [edges_cons, list.count_cons], split_ifs with h'', { rw sym2.eq_iff at h'', obtain (⟨rfl,rfl⟩|⟨rfl,rfl⟩) := h'', { exact (h' rfl).elim }, { cases p'; simp! } }, { apply ih, } } } }, end @[simp] lemma take_until_copy {u v w v' w'} (p : G.walk v w) (hv : v = v') (hw : w = w') (h : u ∈ (p.copy hv hw).support) : (p.copy hv hw).take_until u h = (p.take_until u (by { subst_vars, exact h })).copy hv rfl := by { subst_vars, refl } @[simp] lemma drop_until_copy {u v w v' w'} (p : G.walk v w) (hv : v = v') (hw : w = w') (h : u ∈ (p.copy hv hw).support) : (p.copy hv hw).drop_until u h = (p.drop_until u (by { subst_vars, exact h })).copy rfl hw := by { subst_vars, refl } lemma support_take_until_subset {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.take_until u h).support ⊆ p.support := λ x hx, by { rw [← take_spec p h, mem_support_append_iff], exact or.inl hx } lemma support_drop_until_subset {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.drop_until u h).support ⊆ p.support := λ x hx, by { rw [← take_spec p h, mem_support_append_iff], exact or.inr hx } lemma darts_take_until_subset {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.take_until u h).darts ⊆ p.darts := λ x hx, by { rw [← take_spec p h, darts_append, list.mem_append], exact or.inl hx } lemma darts_drop_until_subset {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.drop_until u h).darts ⊆ p.darts := λ x hx, by { rw [← take_spec p h, darts_append, list.mem_append], exact or.inr hx } lemma edges_take_until_subset {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.take_until u h).edges ⊆ p.edges := list.map_subset _ (p.darts_take_until_subset h) lemma edges_drop_until_subset {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.drop_until u h).edges ⊆ p.edges := list.map_subset _ (p.darts_drop_until_subset h) lemma length_take_until_le {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.take_until u h).length ≤ p.length := begin have := congr_arg walk.length (p.take_spec h), rw [length_append] at this, exact nat.le.intro this, end lemma length_drop_until_le {u v w : V} (p : G.walk v w) (h : u ∈ p.support) : (p.drop_until u h).length ≤ p.length := begin have := congr_arg walk.length (p.take_spec h), rw [length_append, add_comm] at this, exact nat.le.intro this, end protected lemma is_trail.take_until {u v w : V} {p : G.walk v w} (hc : p.is_trail) (h : u ∈ p.support) : (p.take_until u h).is_trail := is_trail.of_append_left (by rwa ← take_spec _ h at hc) protected lemma is_trail.drop_until {u v w : V} {p : G.walk v w} (hc : p.is_trail) (h : u ∈ p.support) : (p.drop_until u h).is_trail := is_trail.of_append_right (by rwa ← take_spec _ h at hc) protected lemma is_path.take_until {u v w : V} {p : G.walk v w} (hc : p.is_path) (h : u ∈ p.support) : (p.take_until u h).is_path := is_path.of_append_left (by rwa ← take_spec _ h at hc) protected lemma is_path.drop_until {u v w : V} (p : G.walk v w) (hc : p.is_path) (h : u ∈ p.support) : (p.drop_until u h).is_path := is_path.of_append_right (by rwa ← take_spec _ h at hc) /-- Rotate a loop walk such that it is centered at the given vertex. -/ def rotate {u v : V} (c : G.walk v v) (h : u ∈ c.support) : G.walk u u := (c.drop_until u h).append (c.take_until u h) @[simp] lemma support_rotate {u v : V} (c : G.walk v v) (h : u ∈ c.support) : (c.rotate h).support.tail ~r c.support.tail := begin simp only [rotate, tail_support_append], apply list.is_rotated.trans list.is_rotated_append, rw [←tail_support_append, take_spec], end lemma rotate_darts {u v : V} (c : G.walk v v) (h : u ∈ c.support) : (c.rotate h).darts ~r c.darts := begin simp only [rotate, darts_append], apply list.is_rotated.trans list.is_rotated_append, rw [←darts_append, take_spec], end lemma rotate_edges {u v : V} (c : G.walk v v) (h : u ∈ c.support) : (c.rotate h).edges ~r c.edges := (rotate_darts c h).map _ protected lemma is_trail.rotate {u v : V} {c : G.walk v v} (hc : c.is_trail) (h : u ∈ c.support) : (c.rotate h).is_trail := begin rw [is_trail_def, (c.rotate_edges h).perm.nodup_iff], exact hc.edges_nodup, end protected lemma is_circuit.rotate {u v : V} {c : G.walk v v} (hc : c.is_circuit) (h : u ∈ c.support) : (c.rotate h).is_circuit := begin refine ⟨hc.to_trail.rotate _, _⟩, cases c, { exact (hc.ne_nil rfl).elim, }, { intro hn, have hn' := congr_arg length hn, rw [rotate, length_append, add_comm, ← length_append, take_spec] at hn', simpa using hn', }, end protected lemma is_cycle.rotate {u v : V} {c : G.walk v v} (hc : c.is_cycle) (h : u ∈ c.support) : (c.rotate h).is_cycle := begin refine ⟨hc.to_circuit.rotate _, _⟩, rw list.is_rotated.nodup_iff (support_rotate _ _), exact hc.support_nodup, end end walk_decomp end walk /-! ### Type of paths -/ /-- The type for paths between two vertices. -/ abbreviation path (u v : V) := {p : G.walk u v // p.is_path} namespace path variables {G G'} @[simp] protected lemma is_path {u v : V} (p : G.path u v) : (p : G.walk u v).is_path := p.property @[simp] protected lemma is_trail {u v : V} (p : G.path u v) : (p : G.walk u v).is_trail := p.property.to_trail /-- The length-0 path at a vertex. -/ @[refl, simps] protected def nil {u : V} : G.path u u := ⟨walk.nil, walk.is_path.nil⟩ /-- The length-1 path between a pair of adjacent vertices. -/ @[simps] def singleton {u v : V} (h : G.adj u v) : G.path u v := ⟨walk.cons h walk.nil, by simp [h.ne]⟩ lemma mk_mem_edges_singleton {u v : V} (h : G.adj u v) : ⟦(u, v)⟧ ∈ (singleton h : G.walk u v).edges := by simp [singleton] /-- The reverse of a path is another path. See also `simple_graph.walk.reverse`. -/ @[symm, simps] def reverse {u v : V} (p : G.path u v) : G.path v u := ⟨walk.reverse p, p.property.reverse⟩ lemma count_support_eq_one [decidable_eq V] {u v w : V} {p : G.path u v} (hw : w ∈ (p : G.walk u v).support) : (p : G.walk u v).support.count w = 1 := list.count_eq_one_of_mem p.property.support_nodup hw lemma count_edges_eq_one [decidable_eq V] {u v : V} {p : G.path u v} (e : sym2 V) (hw : e ∈ (p : G.walk u v).edges) : (p : G.walk u v).edges.count e = 1 := list.count_eq_one_of_mem p.property.to_trail.edges_nodup hw @[simp] lemma nodup_support {u v : V} (p : G.path u v) : (p : G.walk u v).support.nodup := (walk.is_path_def _).mp p.property lemma loop_eq {v : V} (p : G.path v v) : p = path.nil := begin obtain ⟨_|_, this⟩ := p, { refl }, { simpa }, end lemma not_mem_edges_of_loop {v : V} {e : sym2 V} {p : G.path v v} : ¬ e ∈ (p : G.walk v v).edges := by simp [p.loop_eq] lemma cons_is_cycle {u v : V} (p : G.path v u) (h : G.adj u v) (he : ¬ ⟦(u, v)⟧ ∈ (p : G.walk v u).edges) : (walk.cons h ↑p).is_cycle := by simp [walk.is_cycle_def, walk.cons_is_trail_iff, he] end path /-! ### Walks to paths -/ namespace walk variables {G} [decidable_eq V] /-- Given a walk, produces a walk from it by bypassing subwalks between repeated vertices. The result is a path, as shown in `simple_graph.walk.bypass_is_path`. This is packaged up in `simple_graph.walk.to_path`. -/ def bypass : Π {u v : V}, G.walk u v → G.walk u v | u v nil := nil | u v (cons ha p) := let p' := p.bypass in if hs : u ∈ p'.support then p'.drop_until u hs else cons ha p' @[simp] lemma bypass_copy {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') : (p.copy hu hv).bypass = p.bypass.copy hu hv := by { subst_vars, refl } lemma bypass_is_path {u v : V} (p : G.walk u v) : p.bypass.is_path := begin induction p, { simp!, }, { simp only [bypass], split_ifs, { apply is_path.drop_until, assumption, }, { simp [*, cons_is_path_iff], } }, end lemma length_bypass_le {u v : V} (p : G.walk u v) : p.bypass.length ≤ p.length := begin induction p, { refl }, { simp only [bypass], split_ifs, { transitivity, apply length_drop_until_le, rw [length_cons], exact le_add_right p_ih, }, { rw [length_cons, length_cons], exact add_le_add_right p_ih 1, } }, end /-- Given a walk, produces a path with the same endpoints using `simple_graph.walk.bypass`. -/ def to_path {u v : V} (p : G.walk u v) : G.path u v := ⟨p.bypass, p.bypass_is_path⟩ lemma support_bypass_subset {u v : V} (p : G.walk u v) : p.bypass.support ⊆ p.support := begin induction p, { simp!, }, { simp! only, split_ifs, { apply list.subset.trans (support_drop_until_subset _ _), apply list.subset_cons_of_subset, assumption, }, { rw support_cons, apply list.cons_subset_cons, assumption, }, }, end lemma support_to_path_subset {u v : V} (p : G.walk u v) : (p.to_path : G.walk u v).support ⊆ p.support := support_bypass_subset _ lemma darts_bypass_subset {u v : V} (p : G.walk u v) : p.bypass.darts ⊆ p.darts := begin induction p, { simp!, }, { simp! only, split_ifs, { apply list.subset.trans (darts_drop_until_subset _ _), apply list.subset_cons_of_subset _ p_ih, }, { rw darts_cons, exact list.cons_subset_cons _ p_ih, }, }, end lemma edges_bypass_subset {u v : V} (p : G.walk u v) : p.bypass.edges ⊆ p.edges := list.map_subset _ p.darts_bypass_subset lemma darts_to_path_subset {u v : V} (p : G.walk u v) : (p.to_path : G.walk u v).darts ⊆ p.darts := darts_bypass_subset _ lemma edges_to_path_subset {u v : V} (p : G.walk u v) : (p.to_path : G.walk u v).edges ⊆ p.edges := edges_bypass_subset _ end walk /-! ### Mapping paths -/ namespace walk variables {G G' G''} /-- Given a graph homomorphism, map walks to walks. -/ protected def map (f : G →g G') : Π {u v : V}, G.walk u v → G'.walk (f u) (f v) | _ _ nil := nil | _ _ (cons h p) := cons (f.map_adj h) (map p) variables (f : G →g G') (f' : G' →g G'') {u v u' v' : V} (p : G.walk u v) @[simp] lemma map_nil : (nil : G.walk u u).map f = nil := rfl @[simp] lemma map_cons {w : V} (h : G.adj w u) : (cons h p).map f = cons (f.map_adj h) (p.map f) := rfl @[simp] lemma map_copy (hu : u = u') (hv : v = v') : (p.copy hu hv).map f = (p.map f).copy (by rw hu) (by rw hv) := by { subst_vars, refl } @[simp] lemma map_id (p : G.walk u v) : p.map hom.id = p := by { induction p; simp [*] } @[simp] lemma map_map : (p.map f).map f' = p.map (f'.comp f) := by { induction p; simp [*] } /-- Unlike categories, for graphs vertex equality is an important notion, so needing to be able to to work with equality of graph homomorphisms is a necessary evil. -/ lemma map_eq_of_eq {f : G →g G'} (f' : G →g G') (h : f = f') : p.map f = (p.map f').copy (by rw h) (by rw h) := by { subst_vars, refl } @[simp] lemma map_eq_nil_iff {p : G.walk u u} : p.map f = nil ↔ p = nil := by cases p; simp @[simp] lemma length_map : (p.map f).length = p.length := by induction p; simp [*] lemma map_append {u v w : V} (p : G.walk u v) (q : G.walk v w) : (p.append q).map f = (p.map f).append (q.map f) := by induction p; simp [*] @[simp] lemma reverse_map : (p.map f).reverse = p.reverse.map f := by induction p; simp [map_append, *] @[simp] lemma support_map : (p.map f).support = p.support.map f := by induction p; simp [*] @[simp] lemma darts_map : (p.map f).darts = p.darts.map f.map_dart := by induction p; simp [*] @[simp] lemma edges_map : (p.map f).edges = p.edges.map (sym2.map f) := by induction p; simp [*] variables {p f} lemma map_is_path_of_injective (hinj : function.injective f) (hp : p.is_path) : (p.map f).is_path := begin induction p with w u v w huv hvw ih, { simp, }, { rw walk.cons_is_path_iff at hp, simp [ih hp.1], intros x hx hf, cases hinj hf, exact hp.2 hx, }, end protected lemma is_path.of_map {f : G →g G'} (hp : (p.map f).is_path) : p.is_path := begin induction p with w u v w huv hvw ih, { simp }, { rw [map_cons, walk.cons_is_path_iff, support_map] at hp, rw walk.cons_is_path_iff, cases hp with hp1 hp2, refine ⟨ih hp1, _⟩, contrapose! hp2, exact list.mem_map_of_mem f hp2, } end lemma map_is_path_iff_of_injective (hinj : function.injective f) : (p.map f).is_path ↔ p.is_path := ⟨is_path.of_map, map_is_path_of_injective hinj⟩ lemma map_is_trail_iff_of_injective (hinj : function.injective f) : (p.map f).is_trail ↔ p.is_trail := begin induction p with w u v w huv hvw ih, { simp }, { rw [map_cons, cons_is_trail_iff, cons_is_trail_iff, edges_map], change _ ∧ sym2.map f ⟦(u, v)⟧ ∉ _ ↔ _, rw list.mem_map_of_injective (sym2.map.injective hinj), exact and_congr_left' ih, }, end alias map_is_trail_iff_of_injective ↔ _ map_is_trail_of_injective lemma map_is_cycle_iff_of_injective {p : G.walk u u} (hinj : function.injective f) : (p.map f).is_cycle ↔ p.is_cycle := by rw [is_cycle_def, is_cycle_def, map_is_trail_iff_of_injective hinj, ne.def, map_eq_nil_iff, support_map, ← list.map_tail, list.nodup_map_iff hinj] alias map_is_cycle_iff_of_injective ↔ _ map_is_cycle_of_injective variables (p f) lemma map_injective_of_injective {f : G →g G'} (hinj : function.injective f) (u v : V) : function.injective (walk.map f : G.walk u v → G'.walk (f u) (f v)) := begin intros p p' h, induction p with _ _ _ _ _ _ ih generalizing p', { cases p', { refl }, simpa using h, }, { induction p', { simpa using h, }, { simp only [map_cons] at h, cases hinj h.1, simp only [eq_self_iff_true, heq_iff_eq, true_and], apply ih, simpa using h.2, } }, end /-- The specialization of `simple_graph.walk.map` for mapping walks to supergraphs. -/ @[reducible] def map_le {G G' : simple_graph V} (h : G ≤ G') {u v : V} (p : G.walk u v) : G'.walk u v := p.map (hom.map_spanning_subgraphs h) @[simp] lemma map_le_is_trail {G G' : simple_graph V} (h : G ≤ G') {u v : V} {p : G.walk u v} : (p.map_le h).is_trail ↔ p.is_trail := map_is_trail_iff_of_injective (function.injective_id) alias map_le_is_trail ↔ is_trail.of_map_le is_trail.map_le @[simp] lemma map_le_is_path {G G' : simple_graph V} (h : G ≤ G') {u v : V} {p : G.walk u v} : (p.map_le h).is_path ↔ p.is_path := map_is_path_iff_of_injective (function.injective_id) alias map_le_is_path ↔ is_path.of_map_le is_path.map_le @[simp] lemma map_le_is_cycle {G G' : simple_graph V} (h : G ≤ G') {u : V} {p : G.walk u u} : (p.map_le h).is_cycle ↔ p.is_cycle := map_is_cycle_iff_of_injective (function.injective_id) alias map_le_is_cycle ↔ is_cycle.of_map_le is_cycle.map_le end walk namespace path variables {G G'} /-- Given an injective graph homomorphism, map paths to paths. -/ @[simps] protected def map (f : G →g G') (hinj : function.injective f) {u v : V} (p : G.path u v) : G'.path (f u) (f v) := ⟨walk.map f p, walk.map_is_path_of_injective hinj p.2⟩ lemma map_injective {f : G →g G'} (hinj : function.injective f) (u v : V) : function.injective (path.map f hinj : G.path u v → G'.path (f u) (f v)) := begin rintros ⟨p, hp⟩ ⟨p', hp'⟩ h, simp only [path.map, subtype.coe_mk] at h, simp [walk.map_injective_of_injective hinj u v h], end /-- Given a graph embedding, map paths to paths. -/ @[simps] protected def map_embedding (f : G ↪g G') {u v : V} (p : G.path u v) : G'.path (f u) (f v) := path.map f.to_hom f.injective p lemma map_embedding_injective (f : G ↪g G') (u v : V) : function.injective (path.map_embedding f : G.path u v → G'.path (f u) (f v)) := map_injective f.injective u v end path /-! ### Transferring between graphs -/ namespace walk variables {G} /-- The walk `p` transferred to lie in `H`, given that `H` contains its edges. -/ @[protected, simp] def transfer : Π {u v : V} (p : G.walk u v) (H : simple_graph V) (h : ∀ e, e ∈ p.edges → e ∈ H.edge_set), H.walk u v | _ _ (walk.nil) H h := walk.nil | _ _ (walk.cons' u v w a p) H h := walk.cons (h (⟦(u, v)⟧ : sym2 V) (by simp)) (p.transfer H (λ e he, h e (by simp [he]))) variables {u v w : V} (p : G.walk u v) (q : G.walk v w) {H : simple_graph V} (hp : ∀ e, e ∈ p.edges → e ∈ H.edge_set) (hq : ∀ e, e ∈ q.edges → e ∈ H.edge_set) lemma transfer_self : p.transfer G p.edges_subset_edge_set = p := by { induction p; simp only [*, transfer, eq_self_iff_true, heq_iff_eq, and_self], } lemma transfer_eq_map_of_le (GH : G ≤ H) : p.transfer H hp = p.map (simple_graph.hom.map_spanning_subgraphs GH) := by { induction p; simp only [*, transfer, map_cons, hom.map_spanning_subgraphs_apply, eq_self_iff_true, heq_iff_eq, and_self, map_nil], } @[simp] lemma edges_transfer : (p.transfer H hp).edges = p.edges := by { induction p; simp only [*, transfer, edges_nil, edges_cons, eq_self_iff_true, and_self], } @[simp] lemma support_transfer : (p.transfer H hp).support = p.support := by { induction p; simp only [*, transfer, eq_self_iff_true, and_self, support_nil, support_cons], } @[simp] lemma length_transfer : (p.transfer H hp).length = p.length := by induction p; simp [*] variables {p} protected lemma is_path.transfer (pp : p.is_path) : (p.transfer H hp).is_path := begin induction p; simp only [transfer, is_path.nil, cons_is_path_iff, support_transfer] at pp ⊢, { tauto, }, end protected lemma is_cycle.transfer {p : G.walk u u} (pc : p.is_cycle) (hp) : (p.transfer H hp).is_cycle := begin cases p; simp only [transfer, is_cycle.not_of_nil, cons_is_cycle_iff, transfer, edges_transfer] at pc ⊢, { exact pc, }, { exact ⟨pc.left.transfer _, pc.right⟩, }, end variables (p) @[simp] lemma transfer_transfer {K : simple_graph V} (hp' : ∀ e, e ∈ p.edges → e ∈ K.edge_set) : (p.transfer H hp).transfer K (by { rw p.edges_transfer hp, exact hp', }) = p.transfer K hp' := by { induction p; simp only [transfer, eq_self_iff_true, heq_iff_eq, true_and], apply p_ih, } @[simp] lemma transfer_append (hpq) : (p.append q).transfer H hpq = (p.transfer H (λ e he, by { apply hpq, simp [he] })).append (q.transfer H (λ e he, by { apply hpq, simp [he] })) := begin induction p; simp only [transfer, nil_append, cons_append, eq_self_iff_true, heq_iff_eq, true_and], apply p_ih, end @[simp] lemma reverse_transfer : (p.transfer H hp).reverse = p.reverse.transfer H (by { simp only [edges_reverse, list.mem_reverse], exact hp, }) := begin induction p; simp only [*, transfer_append, transfer, reverse_nil, reverse_cons], refl, end end walk /-! ## Deleting edges -/ namespace walk variables {G} /-- Given a walk that avoids a set of edges, produce a walk in the graph with those edges deleted. -/ @[reducible] def to_delete_edges (s : set (sym2 V)) {v w : V} (p : G.walk v w) (hp : ∀ e, e ∈ p.edges → ¬ e ∈ s) : (G.delete_edges s).walk v w := p.transfer _ (by { simp only [edge_set_delete_edges, set.mem_diff], exact λ e ep, ⟨edges_subset_edge_set p ep, hp e ep⟩, }) @[simp] lemma to_delete_edges_nil (s : set (sym2 V)) {v : V} (hp) : (walk.nil : G.walk v v).to_delete_edges s hp = walk.nil := rfl @[simp] lemma to_delete_edges_cons (s : set (sym2 V)) {u v w : V} (h : G.adj u v) (p : G.walk v w) (hp) : (walk.cons h p).to_delete_edges s hp = walk.cons ⟨h, hp _ (or.inl rfl)⟩ (p.to_delete_edges s $ λ _ he, hp _ $ or.inr he) := rfl /-- Given a walk that avoids an edge, create a walk in the subgraph with that edge deleted. This is an abbreviation for `simple_graph.walk.to_delete_edges`. -/ abbreviation to_delete_edge {v w : V} (e : sym2 V) (p : G.walk v w) (hp : e ∉ p.edges) : (G.delete_edges {e}).walk v w := p.to_delete_edges {e} (λ e', by { contrapose!, simp [hp] { contextual := tt } }) @[simp] lemma map_to_delete_edges_eq (s : set (sym2 V)) {v w : V} {p : G.walk v w} (hp) : walk.map (hom.map_spanning_subgraphs (G.delete_edges_le s)) (p.to_delete_edges s hp) = p := by rw [←transfer_eq_map_of_le, transfer_transfer, transfer_self] protected lemma is_path.to_delete_edges (s : set (sym2 V)) {v w : V} {p : G.walk v w} (h : p.is_path) (hp) : (p.to_delete_edges s hp).is_path := h.transfer _ protected lemma is_cycle.to_delete_edges (s : set (sym2 V)) {v : V} {p : G.walk v v} (h : p.is_cycle) (hp) : (p.to_delete_edges s hp).is_cycle := h.transfer _ @[simp] lemma to_delete_edges_copy (s : set (sym2 V)) {u v u' v'} (p : G.walk u v) (hu : u = u') (hv : v = v') (h) : (p.copy hu hv).to_delete_edges s h = (p.to_delete_edges s (by { subst_vars, exact h })).copy hu hv := by { subst_vars, refl } end walk /-! ## `reachable` and `connected` -/ /-- Two vertices are *reachable* if there is a walk between them. This is equivalent to `relation.refl_trans_gen` of `G.adj`. See `simple_graph.reachable_iff_refl_trans_gen`. -/ def reachable (u v : V) : Prop := nonempty (G.walk u v) variables {G} lemma reachable_iff_nonempty_univ {u v : V} : G.reachable u v ↔ (set.univ : set (G.walk u v)).nonempty := set.nonempty_iff_univ_nonempty protected lemma reachable.elim {p : Prop} {u v : V} (h : G.reachable u v) (hp : G.walk u v → p) : p := nonempty.elim h hp protected lemma reachable.elim_path {p : Prop} {u v : V} (h : G.reachable u v) (hp : G.path u v → p) : p := begin classical, exact h.elim (λ q, hp q.to_path), end protected lemma walk.reachable {G : simple_graph V} {u v : V} (p : G.walk u v) : G.reachable u v := ⟨p⟩ protected lemma adj.reachable {u v : V} (h : G.adj u v) : G.reachable u v := h.to_walk.reachable @[refl] protected lemma reachable.refl (u : V) : G.reachable u u := by { fsplit, refl } protected lemma reachable.rfl {u : V} : G.reachable u u := reachable.refl _ @[symm] protected lemma reachable.symm {u v : V} (huv : G.reachable u v) : G.reachable v u := huv.elim (λ p, ⟨p.reverse⟩) lemma reachable_comm {u v : V} : G.reachable u v ↔ G.reachable v u := ⟨reachable.symm, reachable.symm⟩ @[trans] protected lemma reachable.trans {u v w : V} (huv : G.reachable u v) (hvw : G.reachable v w) : G.reachable u w := huv.elim (λ puv, hvw.elim (λ pvw, ⟨puv.append pvw⟩)) lemma reachable_iff_refl_trans_gen (u v : V) : G.reachable u v ↔ relation.refl_trans_gen G.adj u v := begin split, { rintro ⟨h⟩, induction h, { refl, }, { exact (relation.refl_trans_gen.single h_h).trans h_ih, }, }, { intro h, induction h with _ _ _ ha hr, { refl, }, { exact reachable.trans hr ⟨walk.cons ha walk.nil⟩, }, }, end protected lemma reachable.map {G : simple_graph V} {G' : simple_graph V'} (f : G →g G') {u v : V} (h : G.reachable u v) : G'.reachable (f u) (f v) := h.elim (λ p, ⟨p.map f⟩) variables (G) lemma reachable_is_equivalence : equivalence G.reachable := mk_equivalence _ (@reachable.refl _ G) (@reachable.symm _ G) (@reachable.trans _ G) /-- The equivalence relation on vertices given by `simple_graph.reachable`. -/ def reachable_setoid : setoid V := setoid.mk _ G.reachable_is_equivalence /-- A graph is preconnected if every pair of vertices is reachable from one another. -/ def preconnected : Prop := ∀ (u v : V), G.reachable u v lemma preconnected.map {G : simple_graph V} {H : simple_graph V'} (f : G →g H) (hf : surjective f) (hG : G.preconnected) : H.preconnected := hf.forall₂.2 $ λ a b, nonempty.map (walk.map _) $ hG _ _ lemma iso.preconnected_iff {G : simple_graph V} {H : simple_graph V'} (e : G ≃g H) : G.preconnected ↔ H.preconnected := ⟨preconnected.map e.to_hom e.to_equiv.surjective, preconnected.map e.symm.to_hom e.symm.to_equiv.surjective⟩ /-- A graph is connected if it's preconnected and contains at least one vertex. This follows the convention observed by mathlib that something is connected iff it has exactly one connected component. There is a `has_coe_to_fun` instance so that `h u v` can be used instead of `h.preconnected u v`. -/ @[protect_proj, mk_iff] structure connected : Prop := (preconnected : G.preconnected) [nonempty : nonempty V] instance : has_coe_to_fun G.connected (λ _, Π (u v : V), G.reachable u v) := ⟨λ h, h.preconnected⟩ lemma connected.map {G : simple_graph V} {H : simple_graph V'} (f : G →g H) (hf : surjective f) (hG : G.connected) : H.connected := by { haveI := hG.nonempty.map f, exact ⟨hG.preconnected.map f hf⟩ } lemma iso.connected_iff {G : simple_graph V} {H : simple_graph V'} (e : G ≃g H) : G.connected ↔ H.connected := ⟨connected.map e.to_hom e.to_equiv.surjective, connected.map e.symm.to_hom e.symm.to_equiv.surjective⟩ /-- The quotient of `V` by the `simple_graph.reachable` relation gives the connected components of a graph. -/ def connected_component := quot G.reachable /-- Gives the connected component containing a particular vertex. -/ def connected_component_mk (v : V) : G.connected_component := quot.mk G.reachable v @[simps] instance connected_component.inhabited [inhabited V] : inhabited G.connected_component := ⟨G.connected_component_mk default⟩ section connected_component variables {G} @[elab_as_eliminator] protected lemma connected_component.ind {β : G.connected_component → Prop} (h : ∀ (v : V), β (G.connected_component_mk v)) (c : G.connected_component) : β c := quot.ind h c @[elab_as_eliminator] protected lemma connected_component.ind₂ {β : G.connected_component → G.connected_component → Prop} (h : ∀ (v w : V), β (G.connected_component_mk v) (G.connected_component_mk w)) (c d : G.connected_component) : β c d := quot.induction_on₂ c d h protected lemma connected_component.sound {v w : V} : G.reachable v w → G.connected_component_mk v = G.connected_component_mk w := quot.sound protected lemma connected_component.exact {v w : V} : G.connected_component_mk v = G.connected_component_mk w → G.reachable v w := @quotient.exact _ G.reachable_setoid _ _ @[simp] protected lemma connected_component.eq {v w : V} : G.connected_component_mk v = G.connected_component_mk w ↔ G.reachable v w := @quotient.eq _ G.reachable_setoid _ _ /-- The `connected_component` specialization of `quot.lift`. Provides the stronger assumption that the vertices are connected by a path. -/ protected def connected_component.lift {β : Sort*} (f : V → β) (h : ∀ (v w : V) (p : G.walk v w), p.is_path → f v = f w) : G.connected_component → β := quot.lift f (λ v w (h' : G.reachable v w), h'.elim_path (λ hp, h v w hp hp.2)) @[simp] protected lemma connected_component.lift_mk {β : Sort*} {f : V → β} {h : ∀ (v w : V) (p : G.walk v w), p.is_path → f v = f w} {v : V} : connected_component.lift f h (G.connected_component_mk v) = f v := rfl protected lemma connected_component.«exists» {p : G.connected_component → Prop} : (∃ (c : G.connected_component), p c) ↔ ∃ v, p (G.connected_component_mk v) := (surjective_quot_mk G.reachable).exists protected lemma connected_component.«forall» {p : G.connected_component → Prop} : (∀ (c : G.connected_component), p c) ↔ ∀ v, p (G.connected_component_mk v) := (surjective_quot_mk G.reachable).forall lemma preconnected.subsingleton_connected_component (h : G.preconnected) : subsingleton G.connected_component := ⟨connected_component.ind₂ (λ v w, connected_component.sound (h v w))⟩ end connected_component variables {G} /-- A subgraph is connected if it is connected as a simple graph. -/ abbreviation subgraph.connected (H : G.subgraph) : Prop := H.coe.connected lemma singleton_subgraph_connected {v : V} : (G.singleton_subgraph v).connected := begin split, rintros ⟨a, ha⟩ ⟨b, hb⟩, simp only [singleton_subgraph_verts, set.mem_singleton_iff] at ha hb, subst_vars end @[simp] lemma subgraph_of_adj_connected {v w : V} (hvw : G.adj v w) : (G.subgraph_of_adj hvw).connected := begin split, rintro ⟨a, ha⟩ ⟨b, hb⟩, simp only [subgraph_of_adj_verts, set.mem_insert_iff, set.mem_singleton_iff] at ha hb, obtain (rfl|rfl) := ha; obtain (rfl|rfl) := hb; refl <|> { apply adj.reachable, simp }, end lemma preconnected.set_univ_walk_nonempty (hconn : G.preconnected) (u v : V) : (set.univ : set (G.walk u v)).nonempty := by { rw ← set.nonempty_iff_univ_nonempty, exact hconn u v } lemma connected.set_univ_walk_nonempty (hconn : G.connected) (u v : V) : (set.univ : set (G.walk u v)).nonempty := hconn.preconnected.set_univ_walk_nonempty u v /-! ### Walks of a given length -/ section walk_counting lemma set_walk_self_length_zero_eq (u : V) : {p : G.walk u u | p.length = 0} = {walk.nil} := by { ext p, simp } lemma set_walk_length_zero_eq_of_ne {u v : V} (h : u ≠ v) : {p : G.walk u v | p.length = 0} = ∅ := begin ext p, simp only [set.mem_set_of_eq, set.mem_empty_iff_false, iff_false], exact λ h', absurd (walk.eq_of_length_eq_zero h') h, end lemma set_walk_length_succ_eq (u v : V) (n : ℕ) : {p : G.walk u v | p.length = n.succ} = ⋃ (w : V) (h : G.adj u w), walk.cons h '' {p' : G.walk w v | p'.length = n} := begin ext p, cases p with _ _ w _ huw pwv, { simp [eq_comm], }, { simp only [nat.succ_eq_add_one, set.mem_set_of_eq, walk.length_cons, add_left_inj, set.mem_Union, set.mem_image, exists_prop], split, { rintro rfl, exact ⟨w, huw, pwv, rfl, rfl, heq.rfl⟩, }, { rintro ⟨w, huw, pwv, rfl, rfl, rfl⟩, refl, } }, end variables (G) [decidable_eq V] section locally_finite variables [locally_finite G] /-- The `finset` of length-`n` walks from `u` to `v`. This is used to give `{p : G.walk u v | p.length = n}` a `fintype` instance, and it can also be useful as a recursive description of this set when `V` is finite. See `simple_graph.coe_finset_walk_length_eq` for the relationship between this `finset` and the set of length-`n` walks. -/ def finset_walk_length : Π (n : ℕ) (u v : V), finset (G.walk u v) | 0 u v := if h : u = v then by { subst u, exact {walk.nil} } else ∅ | (n+1) u v := finset.univ.bUnion (λ (w : G.neighbor_set u), (finset_walk_length n w v).map ⟨λ p, walk.cons w.property p, λ p q, by simp⟩) lemma coe_finset_walk_length_eq (n : ℕ) (u v : V) : (G.finset_walk_length n u v : set (G.walk u v)) = {p : G.walk u v | p.length = n} := begin induction n with n ih generalizing u v, { obtain rfl | huv := eq_or_ne u v; simp [finset_walk_length, set_walk_length_zero_eq_of_ne, *], }, { simp only [finset_walk_length, set_walk_length_succ_eq, finset.coe_bUnion, finset.mem_coe, finset.mem_univ, set.Union_true], ext p, simp only [mem_neighbor_set, finset.coe_map, embedding.coe_fn_mk, set.Union_coe_set, set.mem_Union, set.mem_image, finset.mem_coe, set.mem_set_of_eq], congr' with w, congr' with h, congr' with q, have := set.ext_iff.mp (ih w v) q, simp only [finset.mem_coe, set.mem_set_of_eq] at this, rw ← this, refl, }, end variables {G} lemma walk.mem_finset_walk_length_iff_length_eq {n : ℕ} {u v : V} (p : G.walk u v) : p ∈ G.finset_walk_length n u v ↔ p.length = n := set.ext_iff.mp (G.coe_finset_walk_length_eq n u v) p variables (G) instance fintype_set_walk_length (u v : V) (n : ℕ) : fintype {p : G.walk u v | p.length = n} := fintype.of_finset (G.finset_walk_length n u v) $ λ p, by rw [←finset.mem_coe, coe_finset_walk_length_eq] lemma set_walk_length_to_finset_eq (n : ℕ) (u v : V) : {p : G.walk u v | p.length = n}.to_finset = G.finset_walk_length n u v := by { ext p, simp [←coe_finset_walk_length_eq] } /- See `simple_graph.adj_matrix_pow_apply_eq_card_walk` for the cardinality in terms of the `n`th power of the adjacency matrix. -/ lemma card_set_walk_length_eq (u v : V) (n : ℕ) : fintype.card {p : G.walk u v | p.length = n} = (G.finset_walk_length n u v).card := fintype.card_of_finset (G.finset_walk_length n u v) $ λ p, by rw [←finset.mem_coe, coe_finset_walk_length_eq] instance fintype_set_path_length (u v : V) (n : ℕ) : fintype {p : G.walk u v | p.is_path ∧ p.length = n} := fintype.of_finset ((G.finset_walk_length n u v).filter walk.is_path) $ by simp [walk.mem_finset_walk_length_iff_length_eq, and_comm] end locally_finite section finite variables [fintype V] [decidable_rel G.adj] lemma reachable_iff_exists_finset_walk_length_nonempty (u v : V) : G.reachable u v ↔ ∃ (n : fin (fintype.card V)), (G.finset_walk_length n u v).nonempty := begin split, { intro r, refine r.elim_path (λ p, _), refine ⟨⟨_, p.is_path.length_lt⟩, p, _⟩, simp [walk.mem_finset_walk_length_iff_length_eq], }, { rintro ⟨_, p, _⟩, use p }, end instance : decidable_rel G.reachable := λ u v, decidable_of_iff' _ (reachable_iff_exists_finset_walk_length_nonempty G u v) instance : fintype G.connected_component := @quotient.fintype _ _ G.reachable_setoid (infer_instance : decidable_rel G.reachable) instance : decidable G.preconnected := by { unfold preconnected, apply_instance } instance : decidable G.connected := by { rw [connected_iff, ← finset.univ_nonempty_iff], exact and.decidable } end finite end walk_counting section bridge_edges /-! ### Bridge edges -/ /-- An edge of a graph is a *bridge* if, after removing it, its incident vertices are no longer reachable from one another. -/ def is_bridge (G : simple_graph V) (e : sym2 V) : Prop := e ∈ G.edge_set ∧ sym2.lift ⟨λ v w, ¬ (G.delete_edges {e}).reachable v w, by simp [reachable_comm]⟩ e lemma is_bridge_iff {u v : V} : G.is_bridge ⟦(u, v)⟧ ↔ G.adj u v ∧ ¬ (G.delete_edges {⟦(u, v)⟧}).reachable u v := iff.rfl lemma reachable_delete_edges_iff_exists_walk {v w : V} : (G.delete_edges {⟦(v, w)⟧}).reachable v w ↔ ∃ (p : G.walk v w), ¬ ⟦(v, w)⟧ ∈ p.edges := begin split, { rintro ⟨p⟩, use p.map (hom.map_spanning_subgraphs (G.delete_edges_le _)), simp_rw [walk.edges_map, list.mem_map, hom.map_spanning_subgraphs_apply, sym2.map_id', id.def], rintro ⟨e, h, rfl⟩, simpa using p.edges_subset_edge_set h, }, { rintro ⟨p, h⟩, exact ⟨p.to_delete_edge _ h⟩, }, end lemma is_bridge_iff_adj_and_forall_walk_mem_edges {v w : V} : G.is_bridge ⟦(v, w)⟧ ↔ G.adj v w ∧ ∀ (p : G.walk v w), ⟦(v, w)⟧ ∈ p.edges := begin rw [is_bridge_iff, and_congr_right'], rw [reachable_delete_edges_iff_exists_walk, not_exists_not], end lemma reachable_delete_edges_iff_exists_cycle.aux [decidable_eq V] {u v w : V} (hb : ∀ (p : G.walk v w), ⟦(v, w)⟧ ∈ p.edges) (c : G.walk u u) (hc : c.is_trail) (he : ⟦(v, w)⟧ ∈ c.edges) (hw : w ∈ (c.take_until v (c.fst_mem_support_of_mem_edges he)).support) : false := begin have hv := c.fst_mem_support_of_mem_edges he, -- decompose c into -- puw pwv pvu -- u ----> w ----> v ----> u let puw := (c.take_until v hv).take_until w hw, let pwv := (c.take_until v hv).drop_until w hw, let pvu := c.drop_until v hv, have : c = (puw.append pwv).append pvu := by simp, -- We have two walks from v to w -- pvu puw -- v ----> u ----> w -- | ^ -- `-------------' -- pwv.reverse -- so they both contain the edge ⟦(v, w)⟧, but that's a contradiction since c is a trail. have hbq := hb (pvu.append puw), have hpq' := hb pwv.reverse, rw [walk.edges_reverse, list.mem_reverse] at hpq', rw [walk.is_trail_def, this, walk.edges_append, walk.edges_append, list.nodup_append_comm, ← list.append_assoc, ← walk.edges_append] at hc, exact list.disjoint_of_nodup_append hc hbq hpq', end lemma adj_and_reachable_delete_edges_iff_exists_cycle {v w : V} : G.adj v w ∧ (G.delete_edges {⟦(v, w)⟧}).reachable v w ↔ ∃ (u : V) (p : G.walk u u), p.is_cycle ∧ ⟦(v, w)⟧ ∈ p.edges := begin classical, rw reachable_delete_edges_iff_exists_walk, split, { rintro ⟨h, p, hp⟩, refine ⟨w, walk.cons h.symm p.to_path, _, _⟩, { apply path.cons_is_cycle, rw [sym2.eq_swap], intro h, exact absurd (walk.edges_to_path_subset p h) hp, }, simp only [sym2.eq_swap, walk.edges_cons, list.mem_cons_iff, eq_self_iff_true, true_or], }, { rintro ⟨u, c, hc, he⟩, have hvc : v ∈ c.support := walk.fst_mem_support_of_mem_edges c he, have hwc : w ∈ c.support := walk.snd_mem_support_of_mem_edges c he, let puv := c.take_until v hvc, let pvu := c.drop_until v hvc, obtain (hw | hw') : w ∈ puv.support ∨ w ∈ pvu.support, { rwa [← walk.mem_support_append_iff, walk.take_spec] }, { by_contra' h, specialize h (c.adj_of_mem_edges he), exact reachable_delete_edges_iff_exists_cycle.aux h c hc.to_trail he hw, }, { by_contra' hb, specialize hb (c.adj_of_mem_edges he), have hb' : ∀ (p : G.walk w v), ⟦(w, v)⟧ ∈ p.edges, { intro p, simpa [sym2.eq_swap] using hb p.reverse, }, apply reachable_delete_edges_iff_exists_cycle.aux hb' (pvu.append puv) (hc.to_trail.rotate hvc) _ (walk.start_mem_support _), rwa [walk.edges_append, list.mem_append, or_comm, ← list.mem_append, ← walk.edges_append, walk.take_spec, sym2.eq_swap], } }, end lemma is_bridge_iff_adj_and_forall_cycle_not_mem {v w : V} : G.is_bridge ⟦(v, w)⟧ ↔ G.adj v w ∧ ∀ ⦃u : V⦄ (p : G.walk u u), p.is_cycle → ⟦(v, w)⟧ ∉ p.edges := begin rw [is_bridge_iff, and.congr_right_iff], intro h, rw ← not_iff_not, push_neg, rw ← adj_and_reachable_delete_edges_iff_exists_cycle, simp only [h, true_and], end lemma is_bridge_iff_mem_and_forall_cycle_not_mem {e : sym2 V} : G.is_bridge e ↔ e ∈ G.edge_set ∧ ∀ ⦃u : V⦄ (p : G.walk u u), p.is_cycle → e ∉ p.edges := sym2.ind (λ v w, is_bridge_iff_adj_and_forall_cycle_not_mem) e end bridge_edges end simple_graph
1741cbcee55895a2ddea26222cf795eb89987f10
ce6917c5bacabee346655160b74a307b4a5ab620
/src/ch3/ex0212.lean
38d2999cd3b353ae7344a9e2cf6e73650ce33a8f
[]
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
192
lean
theorem t1 (p q : Prop) (hp : p) (hq : q) : p := hp variables p q r s : Prop #check t1 p q #check t1 r s #check t1 (r → s) (s → r) variable h : r → s #check t1 (r → s) (s → r) h
d0fedbcfcaa5311eca3fcc2d49d546e416cdc8ab
e0b0b1648286e442507eb62344760d5cd8d13f2d
/src/Lean/Elab/Syntax.lean
72f1b41ada3ea4a4bc9368059e8c4623759d987a
[ "Apache-2.0" ]
permissive
MULXCODE/lean4
743ed389e05e26e09c6a11d24607ad5a697db39b
4675817a9e89824eca37192364cd47a4027c6437
refs/heads/master
1,682,231,879,857
1,620,423,501,000
1,620,423,501,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
29,640
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Command import Lean.Parser.Syntax namespace Lean.Elab.Term /- Expand `optional «precedence»` where «precedence» := leading_parser " : " >> precedenceParser -/ def expandOptPrecedence (stx : Syntax) : MacroM (Option Nat) := if stx.isNone then return none else return some (← evalPrec stx[0][1]) private def mkParserSeq (ds : Array Syntax) : TermElabM Syntax := do if ds.size == 0 then throwUnsupportedSyntax else if ds.size == 1 then pure ds[0] else let mut r := ds[0] for d in ds[1:ds.size] do r ← `(ParserDescr.binary `andthen $r $d) return r structure ToParserDescrContext where catName : Name first : Bool leftRec : Bool -- true iff left recursion is allowed /- See comment at `Parser.ParserCategory`. -/ behavior : Parser.LeadingIdentBehavior abbrev ToParserDescrM := ReaderT ToParserDescrContext (StateRefT (Option Nat) TermElabM) private def markAsTrailingParser (lhsPrec : Nat) : ToParserDescrM Unit := set (some lhsPrec) @[inline] private def withNotFirst {α} (x : ToParserDescrM α) : ToParserDescrM α := withReader (fun ctx => { ctx with first := false }) x @[inline] private def withNestedParser {α} (x : ToParserDescrM α) : ToParserDescrM α := withReader (fun ctx => { ctx with leftRec := false, first := false }) x def checkLeftRec (stx : Syntax) : ToParserDescrM Bool := do let ctx ← read unless ctx.first && stx.getKind == `Lean.Parser.Syntax.cat do return false let cat := stx[0].getId.eraseMacroScopes unless cat == ctx.catName do return false let prec? ← liftMacroM <| expandOptPrecedence stx[1] unless ctx.leftRec do throwErrorAt stx[3] "invalid occurrence of '{cat}', parser algorithm does not allow this form of left recursion" markAsTrailingParser (prec?.getD 0) return true /-- Given a `stx` of category `syntax`, return a pair `(newStx, lhsPrec?)`, where `newStx` is of category `term`. After elaboration, `newStx` should have type `TrailingParserDescr` if `lhsPrec?.isSome`, and `ParserDescr` otherwise. -/ partial def toParserDescr (stx : Syntax) (catName : Name) : TermElabM (Syntax × Option Nat) := do let env ← getEnv let behavior := Parser.leadingIdentBehavior env catName (process stx { catName := catName, first := true, leftRec := true, behavior := behavior }).run none where process (stx : Syntax) : ToParserDescrM Syntax := withRef stx do let kind := stx.getKind if kind == nullKind then processSeq stx else if kind == choiceKind then process stx[0] else if kind == `Lean.Parser.Syntax.paren then process stx[1] else if kind == `Lean.Parser.Syntax.cat then processNullaryOrCat stx else if kind == `Lean.Parser.Syntax.unary then processUnary stx else if kind == `Lean.Parser.Syntax.binary then processBinary stx else if kind == `Lean.Parser.Syntax.sepBy then processSepBy stx else if kind == `Lean.Parser.Syntax.sepBy1 then processSepBy1 stx else if kind == `Lean.Parser.Syntax.atom then processAtom stx else if kind == `Lean.Parser.Syntax.nonReserved then processNonReserved stx else let stxNew? ← liftM (liftMacroM (expandMacro? stx) : TermElabM _) match stxNew? with | some stxNew => process stxNew | none => throwErrorAt stx "unexpected syntax kind of category `syntax`: {kind}" /- Sequence (aka NullNode) -/ processSeq (stx : Syntax) := do let args := stx.getArgs if (← checkLeftRec stx[0]) then if args.size == 1 then throwErrorAt stx "invalid atomic left recursive syntax" let args := args.eraseIdx 0 let args ← args.mapM fun arg => withNestedParser do process arg mkParserSeq args else let args ← args.mapIdxM fun i arg => withReader (fun ctx => { ctx with first := ctx.first && i.val == 0 }) do process arg mkParserSeq args /- Resolve the given parser name and return a list of candidates. Each candidate is a pair `(resolvedParserName, isDescr)`. `isDescr == true` if the type of `resolvedParserName` is a `ParserDescr`. -/ resolveParserName (parserName : Name) : ToParserDescrM (List (Name × Bool)) := do try let candidates ← resolveGlobalConstWithInfos (← getRef) parserName /- Convert `candidates` in a list of pairs `(c, isDescr)`, where `c` is the parser name, and `isDescr` is true iff `c` has type `Lean.ParserDescr` or `Lean.TrailingParser` -/ let env ← getEnv candidates.filterMap fun c => match env.find? c with | none => none | some info => match info.type with | Expr.const `Lean.Parser.TrailingParser _ _ => (c, false) | Expr.const `Lean.Parser.Parser _ _ => (c, false) | Expr.const `Lean.ParserDescr _ _ => (c, true) | Expr.const `Lean.TrailingParserDescr _ _ => (c, true) | _ => none catch _ => return [] ensureNoPrec (stx : Syntax) := unless stx[1].isNone do throwErrorAt stx[1] "unexpected precedence" processParserCategory (stx : Syntax) := do let catName := stx[0].getId.eraseMacroScopes if (← read).first && catName == (← read).catName then throwErrorAt stx "invalid atomic left recursive syntax" let prec? ← liftMacroM <| expandOptPrecedence stx[1] let prec := prec?.getD 0 `(ParserDescr.cat $(quote catName) $(quote prec)) processNullaryOrCat (stx : Syntax) := do let id := stx[0].getId.eraseMacroScopes match (← withRef stx[0] <| resolveParserName id) with | [(c, true)] => ensureNoPrec stx; return mkIdentFrom stx c | [(c, false)] => ensureNoPrec stx; `(ParserDescr.parser $(quote c)) | cs@(_ :: _ :: _) => throwError "ambiguous parser declaration {cs.map (·.1)}" | [] => if Parser.isParserCategory (← getEnv) id then processParserCategory stx else if (← Parser.isParserAlias id) then ensureNoPrec stx Parser.ensureConstantParserAlias id `(ParserDescr.const $(quote id)) else throwError "unknown parser declaration/category/alias '{id}'" processUnary (stx : Syntax) := do let aliasName := (stx[0].getId).eraseMacroScopes Parser.ensureUnaryParserAlias aliasName let d ← withNestedParser do process stx[2] `(ParserDescr.unary $(quote aliasName) $d) processBinary (stx : Syntax) := do let aliasName := (stx[0].getId).eraseMacroScopes Parser.ensureBinaryParserAlias aliasName let d₁ ← withNestedParser do process stx[2] let d₂ ← withNestedParser do process stx[4] `(ParserDescr.binary $(quote aliasName) $d₁ $d₂) processSepBy (stx : Syntax) := do let p ← withNestedParser $ process stx[1] let sep := stx[3] let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else process stx[4][1] let allowTrailingSep := !stx[5].isNone `(ParserDescr.sepBy $p $sep $psep $(quote allowTrailingSep)) processSepBy1 (stx : Syntax) := do let p ← withNestedParser do process stx[1] let sep := stx[3] let psep ← if stx[4].isNone then `(ParserDescr.symbol $sep) else process stx[4][1] let allowTrailingSep := !stx[5].isNone `(ParserDescr.sepBy1 $p $sep $psep $(quote allowTrailingSep)) processAtom (stx : Syntax) := do match stx[0].isStrLit? with | some atom => /- For syntax categories where initialized with `LeadingIdentBehavior` different from default (e.g., `tactic`), we automatically mark the first symbol as nonReserved. -/ if (← read).behavior != Parser.LeadingIdentBehavior.default && (← read).first then `(ParserDescr.nonReservedSymbol $(quote atom) false) else `(ParserDescr.symbol $(quote atom)) | none => throwUnsupportedSyntax processNonReserved (stx : Syntax) := do match stx[1].isStrLit? with | some atom => `(ParserDescr.nonReservedSymbol $(quote atom) false) | none => throwUnsupportedSyntax end Term namespace Command open Lean.Syntax open Lean.Parser.Term hiding macroArg open Lean.Parser.Command private def getCatSuffix (catName : Name) : String := match catName with | Name.str _ s _ => s | _ => unreachable! private def declareSyntaxCatQuotParser (catName : Name) : CommandElabM Unit := do let quotSymbol := "`(" ++ getCatSuffix catName ++ "|" let name := catName ++ `quot -- TODO(Sebastian): this might confuse the pretty printer, but it lets us reuse the elaborator let kind := ``Lean.Parser.Term.quot let cmd ← `( @[termParser] def $(mkIdent name) : Lean.ParserDescr := Lean.ParserDescr.node $(quote kind) $(quote Lean.Parser.maxPrec) (Lean.ParserDescr.binary `andthen (Lean.ParserDescr.symbol $(quote quotSymbol)) (Lean.ParserDescr.binary `andthen (Lean.ParserDescr.unary `incQuotDepth (Lean.ParserDescr.cat $(quote catName) 0)) (Lean.ParserDescr.symbol ")")))) elabCommand cmd @[builtinCommandElab syntaxCat] def elabDeclareSyntaxCat : CommandElab := fun stx => do let catName := stx[1].getId let attrName := catName.appendAfter "Parser" let env ← getEnv let env ← liftIO $ Parser.registerParserCategory env attrName catName setEnv env declareSyntaxCatQuotParser catName /-- Auxiliary function for creating declaration names from parser descriptions. Example: Given ``` syntax term "+" term : term syntax "[" sepBy(term, ", ") "]" : term ``` It generates the names `term_+_` and `term[_,]` -/ partial def mkNameFromParserSyntax (catName : Name) (stx : Syntax) : MacroM Name := do mkUnusedBaseName <| Name.mkSimple <| appendCatName <| visit stx "" where visit (stx : Syntax) (acc : String) : String := match stx.isStrLit? with | some val => acc ++ (val.trim.map fun c => if c.isWhitespace then '_' else c).capitalize | none => match stx with | Syntax.node k args => if k == `Lean.Parser.Syntax.cat then acc ++ "_" else args.foldl (init := acc) fun acc arg => visit arg acc | Syntax.ident .. => acc | Syntax.atom .. => acc | Syntax.missing => acc appendCatName (str : String) := match catName with | Name.str _ s _ => s ++ str | _ => str /- We assume a new syntax can be treated as an atom when it starts and ends with a token. Here are examples of atom-like syntax. ``` syntax "(" term ")" : term syntax "[" (sepBy term ",") "]" : term syntax "foo" : term ``` -/ private partial def isAtomLikeSyntax (stx : Syntax) : Bool := let kind := stx.getKind if kind == nullKind then isAtomLikeSyntax stx[0] && isAtomLikeSyntax stx[stx.getNumArgs - 1] else if kind == choiceKind then isAtomLikeSyntax stx[0] -- see toParserDescr else if kind == `Lean.Parser.Syntax.paren then isAtomLikeSyntax stx[1] else kind == `Lean.Parser.Syntax.atom @[builtinCommandElab «syntax»] def elabSyntax : CommandElab := fun stx => do let `($attrKind:attrKind syntax $[: $prec? ]? $[(name := $name?)]? $[(priority := $prio?)]? $[$ps:stx]* : $catStx) ← pure stx | throwUnsupportedSyntax let cat := catStx.getId.eraseMacroScopes unless (Parser.isParserCategory (← getEnv) cat) do throwErrorAt catStx "unknown category '{cat}'" let syntaxParser := mkNullNode ps -- If the user did not provide an explicit precedence, we assign `maxPrec` to atom-like syntax and `leadPrec` otherwise. let precDefault := if isAtomLikeSyntax syntaxParser then Parser.maxPrec else Parser.leadPrec let prec ← match prec? with | some prec => liftMacroM <| evalPrec prec | none => precDefault let name ← match name? with | some name => pure name.getId | none => liftMacroM <| mkNameFromParserSyntax cat syntaxParser let prio ← liftMacroM <| evalOptPrio prio? let stxNodeKind := (← getCurrNamespace) ++ name let catParserId := mkIdentFrom stx (cat.appendAfter "Parser") let (val, lhsPrec?) ← runTermElabM none fun _ => Term.toParserDescr syntaxParser cat let declName := mkIdentFrom stx name let d ← if let some lhsPrec := lhsPrec? then `(@[$attrKind:attrKind $catParserId:ident $(quote prio):numLit] def $declName : Lean.TrailingParserDescr := ParserDescr.trailingNode $(quote stxNodeKind) $(quote prec) $(quote lhsPrec) $val) else `(@[$attrKind:attrKind $catParserId:ident $(quote prio):numLit] def $declName : Lean.ParserDescr := ParserDescr.node $(quote stxNodeKind) $(quote prec) $val) trace `Elab fun _ => d withMacroExpansion stx d <| elabCommand d /- def syntaxAbbrev := leading_parser "syntax " >> ident >> " := " >> many1 syntaxParser -/ @[builtinCommandElab «syntaxAbbrev»] def elabSyntaxAbbrev : CommandElab := fun stx => do let declName := stx[1] -- TODO: nonatomic names let (val, _) ← runTermElabM none $ fun _ => Term.toParserDescr stx[3] Name.anonymous let stxNodeKind := (← getCurrNamespace) ++ declName.getId let stx' ← `(def $declName : Lean.ParserDescr := ParserDescr.nodeWithAntiquot $(quote (toString declName.getId)) $(quote stxNodeKind) $val) withMacroExpansion stx stx' $ elabCommand stx' private def checkRuleKind (given expected : SyntaxNodeKind) : Bool := given == expected || given == expected ++ `antiquot /- Remark: `k` is the user provided kind with the current namespace included. Recall that syntax node kinds contain the current namespace. -/ def elabMacroRulesAux (attrKind : Syntax) (k : SyntaxNodeKind) (alts : Array Syntax) : CommandElabM Syntax := do let alts ← alts.mapM fun alt => match alt with | `(matchAltExpr| | $pats,* => $rhs) => do let pat := pats.elemsAndSeps[0] if !pat.isQuot then throwUnsupportedSyntax let quoted := getQuotContent pat let k' := quoted.getKind if checkRuleKind k' k then pure alt else if k' == choiceKind then match quoted.getArgs.find? fun quotAlt => checkRuleKind quotAlt.getKind k with | none => throwErrorAt alt "invalid macro_rules alternative, expected syntax node kind '{k}'" | some quoted => let pat := pat.setArg 1 quoted let pats := pats.elemsAndSeps.set! 0 pat `(matchAltExpr| | $pats,* => $rhs) else throwErrorAt alt "invalid macro_rules alternative, unexpected syntax node kind '{k'}'" | _ => throwUnsupportedSyntax `(@[$attrKind:attrKind macro $(Lean.mkIdent k)] def myMacro : Macro := fun $alts:matchAlt* | _ => throw Lean.Macro.Exception.unsupportedSyntax) def inferMacroRulesAltKind : Syntax → CommandElabM SyntaxNodeKind | `(matchAltExpr| | $pats,* => $rhs) => do let pat := pats.elemsAndSeps[0] if !pat.isQuot then throwUnsupportedSyntax let quoted := getQuotContent pat pure quoted.getKind | _ => throwUnsupportedSyntax def elabNoKindMacroRulesAux (attrKind : Syntax) (alts : Array Syntax) : CommandElabM Syntax := do let mut k ← inferMacroRulesAltKind alts[0] if k.isStr && k.getString! == "antiquot" then k := k.getPrefix if k == choiceKind then throwErrorAt alts[0] "invalid macro_rules alternative, multiple interpretations for pattern (solution: specify node kind using `macro_rules [<kind>] ...`)" else let altsK ← alts.filterM fun alt => return checkRuleKind (← inferMacroRulesAltKind alt) k let altsNotK ← alts.filterM fun alt => return !checkRuleKind (← inferMacroRulesAltKind alt) k let defCmd ← elabMacroRulesAux attrKind k altsK if altsNotK.isEmpty then pure defCmd else `($defCmd:command $attrKind:attrKind macro_rules $altsNotK:matchAlt*) @[builtinCommandElab «macro_rules»] def elabMacroRules : CommandElab := adaptExpander fun stx => match stx with | `($attrKind:attrKind macro_rules $alts:matchAlt*) => elabNoKindMacroRulesAux attrKind alts | `($attrKind:attrKind macro_rules (kind := $kind) | $x:ident => $rhs) => `(@[$attrKind:attrKind macro $kind] def myMacro : Macro := fun $x:ident => $rhs) | `($attrKind:attrKind macro_rules (kind := $kind) $alts:matchAlt*) => do elabMacroRulesAux attrKind ((← getCurrNamespace) ++ kind.getId) alts | _ => throwUnsupportedSyntax @[builtinMacro Lean.Parser.Command.mixfix] def expandMixfix : Macro := fun stx => withAttrKindGlobal stx fun stx => do match stx with | `(infixl $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => let prec1 := quote <| (← evalOptPrec prec) + 1 `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? lhs$[:$prec]? $op:strLit rhs:$prec1 => $f lhs rhs) | `(infix $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => let prec1 := quote <| (← evalOptPrec prec) + 1 `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? lhs:$prec1 $op:strLit rhs:$prec1 => $f lhs rhs) | `(infixr $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => let prec1 := quote <| (← evalOptPrec prec) + 1 `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? lhs:$prec1 $op:strLit rhs $[: $prec]? => $f lhs rhs) | `(prefix $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op:strLit arg $[: $prec]? => $f arg) | `(postfix $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? $op => $f) => `(notation $[: $prec]? $[(name := $name)]? $[(priority := $prio)]? arg$[:$prec]? $op:strLit => $f arg) | _ => Macro.throwUnsupported where -- set "global" `attrKind`, apply `f`, and restore `attrKind` to result withAttrKindGlobal stx f := do let attrKind := stx[0] let stx := stx.setArg 0 mkAttrKindGlobal let stx ← f stx return stx.setArg 0 attrKind /- Wrap all occurrences of the given `ident` nodes in antiquotations -/ private partial def antiquote (vars : Array Syntax) : Syntax → Syntax | stx => match stx with | `($id:ident) => if (vars.findIdx? (fun var => var.getId == id.getId)).isSome then mkAntiquotNode id else stx | _ => match stx with | Syntax.node k args => Syntax.node k (args.map (antiquote vars)) | stx => stx /- Convert `notation` command lhs item into a `syntax` command item -/ def expandNotationItemIntoSyntaxItem (stx : Syntax) : MacroM Syntax := let k := stx.getKind if k == `Lean.Parser.Command.identPrec then pure $ Syntax.node `Lean.Parser.Syntax.cat #[mkIdentFrom stx `term, stx[1]] else if k == strLitKind then pure $ Syntax.node `Lean.Parser.Syntax.atom #[stx] else Macro.throwUnsupported def strLitToPattern (stx: Syntax) : MacroM Syntax := match stx.isStrLit? with | some str => pure $ mkAtomFrom stx str | none => Macro.throwUnsupported /- Convert `notation` command lhs item into a pattern element -/ def expandNotationItemIntoPattern (stx : Syntax) : MacroM Syntax := let k := stx.getKind if k == `Lean.Parser.Command.identPrec then mkAntiquotNode stx[0] else if k == strLitKind then strLitToPattern stx else Macro.throwUnsupported /-- Try to derive a `SimpleDelab` from a notation. The notation must be of the form `notation ... => c var_1 ... var_n` where `c` is a declaration in the current scope and the `var_i` are a permutation of the LHS vars. -/ def mkSimpleDelab (attrKind : Syntax) (vars : Array Syntax) (pat qrhs : Syntax) : OptionT MacroM Syntax := do match qrhs with | `($c:ident $args*) => let [(c, [])] ← Macro.resolveGlobalName c.getId | failure guard <| args.all (Syntax.isIdent ∘ getAntiquotTerm) guard <| args.allDiff -- replace head constant with (unused) antiquotation so we're not dependent on the exact pretty printing of the head let qrhs ← `($(mkAntiquotNode (← `(_))) $args*) `(@[$attrKind:attrKind appUnexpander $(mkIdent c):ident] def unexpand : Lean.PrettyPrinter.Unexpander := fun | `($qrhs) => `($pat) | _ => throw ()) | `($c:ident) => let [(c, [])] ← Macro.resolveGlobalName c.getId | failure `(@[$attrKind:attrKind appUnexpander $(mkIdent c):ident] def unexpand : Lean.PrettyPrinter.Unexpander := fun _ => `($pat)) | _ => failure private def isLocalAttrKind (attrKind : Syntax) : Bool := match attrKind with | `(Parser.Term.attrKind| local) => true | _ => false private def expandNotationAux (ref : Syntax) (currNamespace : Name) (attrKind : Syntax) (prec? : Option Syntax) (name? : Option Syntax) (prio? : Option Syntax) (items : Array Syntax) (rhs : Syntax) : MacroM Syntax := do let prio ← evalOptPrio prio? -- build parser let syntaxParts ← items.mapM expandNotationItemIntoSyntaxItem let cat := mkIdentFrom ref `term let name ← match name? with | some name => pure name.getId | none => mkNameFromParserSyntax `term (mkNullNode syntaxParts) -- build macro rules let vars := items.filter fun item => item.getKind == `Lean.Parser.Command.identPrec let vars := vars.map fun var => var[0] let qrhs := antiquote vars rhs let patArgs ← items.mapM expandNotationItemIntoPattern /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let fullName := currNamespace ++ name let pat := Syntax.node fullName patArgs let stxDecl ← `($attrKind:attrKind syntax $[: $prec?]? (name := $(mkIdent name)) (priority := $(quote prio):numLit) $[$syntaxParts]* : $cat) let mut macroDecl ← `(macro_rules | `($pat) => ``($qrhs)) if isLocalAttrKind attrKind then -- Make sure the quotation pre-checker takes section variables into account for local notation. macroDecl ← `(section set_option quotPrecheck.allowSectionVars true $macroDecl end) match (← mkSimpleDelab attrKind vars pat qrhs |>.run) with | some delabDecl => mkNullNode #[stxDecl, macroDecl, delabDecl] | none => mkNullNode #[stxDecl, macroDecl] @[builtinMacro Lean.Parser.Command.notation] def expandNotation : Macro | stx@`($attrKind:attrKind notation $[: $prec? ]? $[(name := $name?)]? $[(priority := $prio?)]? $items* => $rhs) => do -- trigger scoped checks early and only once let _ ← toAttributeKind attrKind expandNotationAux stx (← Macro.getCurrNamespace) attrKind prec? name? prio? items rhs | _ => Macro.throwUnsupported /- Convert `macro` argument into a `syntax` command item -/ def expandMacroArgIntoSyntaxItem : Macro | `(macroArg|$id:ident:$stx) => stx -- can't match against `$s:strLit%$id` because the latter part would be interpreted as an antiquotation on the token -- `strLit`. | `(macroArg|$s:macroArgSymbol) => `(stx|$(s[0]):strLit) | _ => Macro.throwUnsupported /- Convert `macro` arg into a pattern element -/ def expandMacroArgIntoPattern (stx : Syntax) : MacroM Syntax := do match (← expandMacros stx) with | `(macroArg|$id:ident:optional($stx)) => mkSplicePat `optional id "?" | `(macroArg|$id:ident:many($stx)) => mkSplicePat `many id "*" | `(macroArg|$id:ident:many1($stx)) => mkSplicePat `many id "*" | `(macroArg|$id:ident:sepBy($stx, $sep:strLit $[, $stxsep]? $[, allowTrailingSep]?)) => mkSplicePat `sepBy id ((isStrLit? sep).get! ++ "*") | `(macroArg|$id:ident:sepBy1($stx, $sep:strLit $[, $stxsep]? $[, allowTrailingSep]?)) => mkSplicePat `sepBy id ((isStrLit? sep).get! ++ "*") | `(macroArg|$id:ident:$stx) => mkAntiquotNode id | `(macroArg|$s:strLit) => strLitToPattern s -- `"tk"%id` ~> `"tk"%$id` | `(macroArg|$s:macroArgSymbol) => mkNode `token_antiquot #[← strLitToPattern s[0], mkAtom "%", mkAtom "$", s[1][1]] | _ => Macro.throwUnsupported where mkSplicePat kind id suffix := mkNullNode #[mkAntiquotSuffixSpliceNode kind (mkAntiquotNode id) suffix] /- «macro» := leading_parser suppressInsideQuot (Term.attrKind >> "macro " >> optPrecedence >> optNamedName >> optNamedPrio >> macroHead >> many macroArg >> macroTail) -/ @[builtinMacro Lean.Parser.Command.macro] def expandMacro : Macro := fun stx => do let attrKind := stx[0] let prec := stx[2].getOptional? let name? ← expandOptNamedName stx[3] let prio ← expandOptNamedPrio stx[4] let head := stx[5] let args := stx[6].getArgs let cat := stx[8] -- build parser let stxPart ← expandMacroArgIntoSyntaxItem head let stxParts ← args.mapM expandMacroArgIntoSyntaxItem let stxParts := #[stxPart] ++ stxParts -- name let name ← match name? with | some name => pure name | none => mkNameFromParserSyntax cat.getId (mkNullNode stxParts) -- build macro rules let patHead ← expandMacroArgIntoPattern head let patArgs ← args.mapM expandMacroArgIntoPattern /- The command `syntax [<kind>] ...` adds the current namespace to the syntax node kind. So, we must include current namespace when we create a pattern for the following `macro_rules` commands. -/ let pat := Syntax.node ((← Macro.getCurrNamespace) ++ name) (#[patHead] ++ patArgs) if stx.getArgs.size == 11 then -- `stx` is of the form `macro $head $args* : $cat => term` let rhs := stx[10] let stxCmd ← `(Parser.Command.syntax| $attrKind:attrKind syntax $(prec)? (name := $(mkIdentFrom stx name):ident) (priority := $(quote prio):numLit) $[$stxParts]* : $cat) let macroRulesCmd ← `(macro_rules | `($pat) => $rhs) return mkNullNode #[stxCmd, macroRulesCmd] else -- `stx` is of the form `macro $head $args* : $cat => `( $body )` let rhsBody := stx[11] let stxCmd ← `(Parser.Command.syntax| $attrKind:attrKind syntax $(prec)? (name := $(mkIdentFrom stx name):ident) (priority := $(quote prio):numLit) $[$stxParts]* : $cat) let macroRulesCmd ← `(macro_rules | `($pat) => `($rhsBody)) return mkNullNode #[stxCmd, macroRulesCmd] builtin_initialize registerTraceClass `Elab.syntax @[inline] def withExpectedType (expectedType? : Option Expr) (x : Expr → TermElabM Expr) : TermElabM Expr := do Term.tryPostponeIfNoneOrMVar expectedType? let some expectedType ← pure expectedType? | throwError "expected type must be known" x expectedType /- def elabTail := try (" : " >> ident) >> darrow >> termParser def «elab» := leading_parser suppressInsideQuot (Term.attrKind >> "elab " >> optPrecedence >> optNamedName >> optNamedPrio >> elabHead >> many elabArg >> elabTail) -/ def expandElab (currNamespace : Name) (stx : Syntax) : CommandElabM Syntax := do let ref := stx let attrKind := stx[0] let prec := stx[2].getOptional? let name? ← liftMacroM <| expandOptNamedName stx[3] let prio ← liftMacroM <| expandOptNamedPrio stx[4] let head := stx[5] let args := stx[6].getArgs let cat := stx[8] let expectedTypeSpec := stx[9] let rhs := stx[11] let catName := cat.getId -- build parser let stxPart ← liftMacroM <| expandMacroArgIntoSyntaxItem head let stxParts ← liftMacroM <| args.mapM expandMacroArgIntoSyntaxItem let stxParts := #[stxPart] ++ stxParts -- name let name ← match name? with | some name => pure name | none => liftMacroM <| mkNameFromParserSyntax cat.getId (mkNullNode stxParts) -- build pattern for syntax `match` let patHead ← liftMacroM <| expandMacroArgIntoPattern head let patArgs ← liftMacroM <| args.mapM expandMacroArgIntoPattern let pat := Syntax.node (currNamespace ++ name) (#[patHead] ++ patArgs) let stxCmd ← `(Parser.Command.syntax| $attrKind:attrKind syntax $(prec)? (name := $(mkIdentFrom stx name):ident) (priority := $(quote prio):numLit) $[$stxParts]* : $cat) let elabCmd ← if expectedTypeSpec.hasArgs then if catName == `term then let expId := expectedTypeSpec[1] `(@[termElab $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Term.TermElab := fun stx expectedType? => match stx with | `($pat) => Lean.Elab.Command.withExpectedType expectedType? fun $expId => $rhs | _ => throwUnsupportedSyntax) else throwErrorAt expectedTypeSpec "syntax category '{catName}' does not support expected type specification" else if catName == `term then `(@[termElab $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Term.TermElab := fun stx _ => match stx with | `($pat) => $rhs | _ => throwUnsupportedSyntax) else if catName == `command then `(@[commandElab $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Command.CommandElab := fun | `($pat) => $rhs | _ => throwUnsupportedSyntax) else if catName == `tactic then `(@[tactic $(mkIdentFrom stx name):ident] def elabFn : Lean.Elab.Tactic.Tactic := fun | `(tactic|$pat) => $rhs | _ => throwUnsupportedSyntax) else -- We considered making the command extensible and support new user-defined categories. We think it is unnecessary. -- If users want this feature, they add their own `elab` macro that uses this one as a fallback. throwError "unsupported syntax category '{catName}'" return mkNullNode #[stxCmd, elabCmd] @[builtinCommandElab «elab»] def elabElab : CommandElab := adaptExpander fun stx => do expandElab (← getCurrNamespace) stx end Lean.Elab.Command
d0753c729fe3379ed4be0fa07b2b451552199646
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/tactic/omega/nat/neg_elim.lean
eadcf20e35cf0267b05a7d55c8434f6d6cd3a7e0
[ "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,958
lean
/- Copyright (c) 2019 Seul Baek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Seul Baek -/ /- Negation elimination. -/ import tactic.omega.nat.form namespace omega namespace nat open_locale omega.nat /-- push_neg p returns the result of normalizing ¬ p by pushing the outermost negation all the way down, until it reaches either a negation or an atom -/ @[simp] def push_neg : preform → preform | (p ∨* q) := (push_neg p) ∧* (push_neg q) | (p ∧* q) := (push_neg p) ∨* (push_neg q) | (¬*p) := p | p := ¬* p lemma push_neg_equiv : ∀ {p : preform}, preform.equiv (push_neg p) (¬* p) := begin preform.induce `[intros v; try {refl}], { simp only [not_not, preform.holds, push_neg] }, { simp only [preform.holds, push_neg, not_or_distrib, ihp v, ihq v] }, { simp only [preform.holds, push_neg, not_and_distrib, ihp v, ihq v] } end /-- NNF transformation -/ def nnf : preform → preform | (¬* p) := push_neg (nnf p) | (p ∨* q) := (nnf p) ∨* (nnf q) | (p ∧* q) := (nnf p) ∧* (nnf q) | a := a /-- Asserts that the given preform is in NNF -/ def is_nnf : preform → Prop | (t =* s) := true | (t ≤* s) := true | ¬*(t =* s) := true | ¬*(t ≤* s) := true | (p ∨* q) := is_nnf p ∧ is_nnf q | (p ∧* q) := is_nnf p ∧ is_nnf q | _ := false lemma is_nnf_push_neg : ∀ p : preform, is_nnf p → is_nnf (push_neg p) := begin preform.induce `[intro h1; try {trivial}], { cases p; try {cases h1}; trivial }, { cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption }, { cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption } end lemma is_nnf_nnf : ∀ p : preform, is_nnf (nnf p) := begin preform.induce `[try {trivial}], { apply is_nnf_push_neg _ ih }, { constructor; assumption }, { constructor; assumption } end lemma nnf_equiv : ∀ {p : preform}, preform.equiv (nnf p) p := begin preform.induce `[intros v; try {refl}; simp only [nnf]], { rw push_neg_equiv, apply not_iff_not_of_iff, apply ih }, { apply pred_mono_2' (ihp v) (ihq v) }, { apply pred_mono_2' (ihp v) (ihq v) } end @[simp] def neg_elim_core : preform → preform | (¬* (t =* s)) := (t.add_one ≤* s) ∨* (s.add_one ≤* t) | (¬* (t ≤* s)) := s.add_one ≤* t | (p ∨* q) := (neg_elim_core p) ∨* (neg_elim_core q) | (p ∧* q) := (neg_elim_core p) ∧* (neg_elim_core q) | p := p lemma neg_free_neg_elim_core : ∀ p, is_nnf p → (neg_elim_core p).neg_free := begin preform.induce `[intro h1, try {simp only [neg_free, neg_elim_core]}, try {trivial}], { cases p; try {cases h1}; try {trivial}, constructor; trivial }, { cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption }, { cases h1, constructor; [{apply ihp}, {apply ihq}]; assumption } end lemma le_and_le_iff_eq {α : Type} [partial_order α] {a b : α} : (a ≤ b ∧ b ≤ a) ↔ a = b := begin constructor; intro h1, { cases h1, apply le_antisymm; assumption }, { constructor; apply le_of_eq; rw h1 } end lemma implies_neg_elim_core : ∀ {p : preform}, preform.implies p (neg_elim_core p) := begin preform.induce `[intros v h, try {apply h}], { cases p with t s t s; try {apply h}, { apply or.symm, simpa only [preform.holds, le_and_le_iff_eq.symm, not_and_distrib, not_le] using h }, simpa only [preform.holds, not_le, int.add_one_le_iff] using h }, { simp only [neg_elim_core], cases h; [{left, apply ihp}, {right, apply ihq}]; assumption }, apply and.imp (ihp _) (ihq _) h end /-- Eliminate all negations in a preform -/ def neg_elim : preform → preform := neg_elim_core ∘ nnf lemma neg_free_neg_elim {p : preform} : (neg_elim p).neg_free := neg_free_neg_elim_core _ (is_nnf_nnf _) lemma implies_neg_elim {p : preform} : preform.implies p (neg_elim p) := begin intros v h1, apply implies_neg_elim_core, apply (nnf_equiv v).elim_right h1 end end nat end omega
b409b14b420966cd856a7853effcc1a9a93b404d
0845ae2ca02071debcfd4ac24be871236c01784f
/library/init/lean/compiler/ir/resetreuse.lean
2a71fb09aecbd05a942daaa992d1e7da4ee1f448
[ "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
6,070
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.control.state import init.control.reader import init.lean.compiler.ir.basic import init.lean.compiler.ir.livevars import init.lean.compiler.ir.format namespace Lean namespace IR namespace ResetReuse /- Remark: the insertResetReuse transformation is applied before we have inserted `inc/dec` instructions, and perfomed lower level optimizations that introduce the instructions `release` and `set`. -/ /- Remark: the functions `S`, `D` and `R` defined here implement the corresponding functions in the paper "Counting Immutable Beans" Here are the main differences: - We use the State monad to manage the generation of fresh variable names. - Support for join points, and `uset` and `sset` instructions for unboxed data. - `D` uses the auxiliary function `Dmain`. - `Dmain` returns a pair `(b, found)` to avoid quadratic behavior when checking the last occurrence of the variable `x`. - Because we have join points in the actual implementation, a variable may be live even if it does not occur in a function body. See example at `livevars.lean`. -/ private def mayReuse (c₁ c₂ : CtorInfo) : Bool := c₁.size == c₂.size && c₁.usize == c₂.usize && c₁.ssize == c₂.ssize && /- The following condition is a heuristic. We don't want to reuse cells from different types even when they are compatible because it produces counterintuitive behavior. -/ c₁.name.getPrefix == c₂.name.getPrefix private partial def S (w : VarId) (c : CtorInfo) : FnBody → FnBody | (FnBody.vdecl x t v@(Expr.ctor c' ys) b) := if mayReuse c c' then let updtCidx := c.cidx != c'.cidx; FnBody.vdecl x t (Expr.reuse w c' updtCidx ys) b else FnBody.vdecl x t v (S b) | (FnBody.jdecl j ys v b) := let v' := S v; if v == v' then FnBody.jdecl j ys v (S b) else FnBody.jdecl j ys v' b | (FnBody.case tid x alts) := FnBody.case tid x $ alts.map $ fun alt => alt.modifyBody S | b := if b.isTerminal then b else let (instr, b) := b.split; instr.setBody (S b) /- We use `Context` to track join points in scope. -/ abbrev M := ReaderT LocalContext (StateT Index Id) private def mkFresh : M VarId := do idx ← getModify (fun n => n + 1); pure { idx := idx } private def tryS (x : VarId) (c : CtorInfo) (b : FnBody) : M FnBody := do w ← mkFresh; let b' := S w c b; if b == b' then pure b else pure $ FnBody.vdecl w IRType.object (Expr.reset c.size x) b' private def Dfinalize (x : VarId) (c : CtorInfo) : FnBody × Bool → M FnBody | (b, true) := pure b | (b, false) := tryS x c b private def argsContainsVar (ys : Array Arg) (x : VarId) : Bool := ys.any $ fun arg => match arg with | Arg.var y => x == y | _ => false private def isCtorUsing (b : FnBody) (x : VarId) : Bool := match b with | (FnBody.vdecl _ _ (Expr.ctor _ ys) _) => argsContainsVar ys x | _ => false /- Given `Dmain b`, the resulting pair `(new_b, flag)` contains the new body `new_b`, and `flag == true` if `x` is live in `b`. Note that, in the function `D` defined in the paper, for each `let x := e; F`, `D` checks whether `x` is live in `F` or not. This is great for clarity but it is expensive: `O(n^2)` where `n` is the size of the function body. -/ private partial def Dmain (x : VarId) (c : CtorInfo) : FnBody → M (FnBody × Bool) | e@(FnBody.case tid y alts) := do ctx ← read; if e.hasLiveVar ctx x then do /- If `x` is live in `e`, we recursively process each branch. -/ alts ← alts.mmap $ fun alt => alt.mmodifyBody (fun b => Dmain b >>= Dfinalize x c); pure (FnBody.case tid y alts, true) else pure (e, false) | (FnBody.jdecl j ys v b) := do (b, found) ← adaptReader (fun (ctx : LocalContext) => ctx.addJP j ys v) (Dmain b); (v, _ /- found' -/) ← Dmain v; /- If `found' == true`, then `Dmain b` must also have returned `(b, true)` since we assume the IR does not have dead join points. So, if `x` is live in `j` (i.e., `v`), then it must also live in `b` since `j` is reachable from `b` with a `jmp`. On the other hand, `x` may be live in `b` but dead in `j` (i.e., `v`). -/ pure (FnBody.jdecl j ys v b, found) | e := do ctx ← read; if e.isTerminal then pure (e, e.hasLiveVar ctx x) else do let (instr, b) := e.split; if isCtorUsing instr x then /- If the scrutinee `x` (the one that is providing memory) is being stored in a constructor, then reuse will probably not be able to reuse memory at runtime. It may work only if the new cell is consumed, but we ignore this case. -/ pure (e, true) else do (b, found) ← Dmain b; /- Remark: it is fine to use `hasFreeVar` instead of `hasLiveVar` since `instr` is not a `FnBody.jmp` (it is not a terminal) nor it is a `FnBody.jdecl`. -/ if found || !instr.hasFreeVar x then pure (instr.setBody b, found) else do b ← tryS x c b; pure (instr.setBody b, true) private def D (x : VarId) (c : CtorInfo) (b : FnBody) : M FnBody := Dmain x c b >>= Dfinalize x c partial def R : FnBody → M FnBody | (FnBody.case tid x alts) := do alts ← alts.mmap $ fun alt => do { alt ← alt.mmodifyBody R; match alt with | Alt.ctor c b => if c.isScalar then pure alt else Alt.ctor c <$> D x c b | _ => pure alt }; pure $ FnBody.case tid x alts | (FnBody.jdecl j ys v b) := do v ← R v; b ← adaptReader (fun (ctx : LocalContext) => ctx.addJP j ys v) (R b); pure $ FnBody.jdecl j ys v b | e := do if e.isTerminal then pure e else do let (instr, b) := e.split; b ← R b; pure (instr.setBody b) end ResetReuse open ResetReuse def Decl.insertResetReuse : Decl → Decl | d@(Decl.fdecl f xs t b) := let nextIndex := d.maxIndex + 1; let b := (R b {}).run' nextIndex; Decl.fdecl f xs t b | other := other end IR end Lean
31a4cbe828db675d170c5dad1e82e36e35aa6151
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/hott/types/bool.hlean
f11b82261dfe3fbd4e97586431220444f06570a6
[ "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
4,919
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura, Floris van Doorn Partially ported from the standard library -/ open eq eq.ops decidable namespace bool local attribute bor [reducible] local attribute band [reducible] theorem dichotomy (b : bool) : b = ff ⊎ b = tt := bool.cases_on b (sum.inl rfl) (sum.inr rfl) theorem cond_ff {A : Type} (t e : A) : cond ff t e = e := rfl theorem cond_tt {A : Type} (t e : A) : cond tt t e = t := rfl theorem eq_tt_of_ne_ff : Π {a : bool}, a ≠ ff → a = tt | @eq_tt_of_ne_ff tt H := rfl | @eq_tt_of_ne_ff ff H := absurd rfl H theorem eq_ff_of_ne_tt : Π {a : bool}, a ≠ tt → a = ff | @eq_ff_of_ne_tt tt H := absurd rfl H | @eq_ff_of_ne_tt ff H := rfl theorem absurd_of_eq_ff_of_eq_tt {B : Type} {a : bool} (H₁ : a = ff) (H₂ : a = tt) : B := absurd (H₁⁻¹ ⬝ H₂) ff_ne_tt theorem tt_bor (a : bool) : bor tt a = tt := rfl notation a || b := bor a b theorem bor_tt (a : bool) : a || tt = tt := bool.cases_on a rfl rfl theorem ff_bor (a : bool) : ff || a = a := bool.cases_on a rfl rfl theorem bor_ff (a : bool) : a || ff = a := bool.cases_on a rfl rfl theorem bor_self (a : bool) : a || a = a := bool.cases_on a rfl rfl theorem bor.comm (a b : bool) : a || b = b || a := by cases a; repeat (cases b | reflexivity) theorem bor.assoc (a b c : bool) : (a || b) || c = a || (b || c) := match a with | ff := by rewrite *ff_bor | tt := by rewrite *tt_bor end theorem or_of_bor_eq {a b : bool} : a || b = tt → a = tt ⊎ b = tt := bool.rec_on a (suppose ff || b = tt, have b = tt, from !ff_bor ▸ this, sum.inr this) (suppose tt || b = tt, sum.inl rfl) theorem bor_inl {a b : bool} (H : a = tt) : a || b = tt := by rewrite H theorem bor_inr {a b : bool} (H : b = tt) : a || b = tt := bool.rec_on a (by rewrite H) (by rewrite H) theorem ff_band (a : bool) : ff && a = ff := rfl theorem tt_band (a : bool) : tt && a = a := bool.cases_on a rfl rfl theorem band_ff (a : bool) : a && ff = ff := bool.cases_on a rfl rfl theorem band_tt (a : bool) : a && tt = a := bool.cases_on a rfl rfl theorem band_self (a : bool) : a && a = a := bool.cases_on a rfl rfl theorem band.comm (a b : bool) : a && b = b && a := bool.cases_on a (bool.cases_on b rfl rfl) (bool.cases_on b rfl rfl) theorem band.assoc (a b c : bool) : (a && b) && c = a && (b && c) := match a with | ff := by rewrite *ff_band | tt := by rewrite *tt_band end theorem band_elim_left {a b : bool} (H : a && b = tt) : a = tt := sum.elim (dichotomy a) (suppose a = ff, absurd (calc ff = ff && b : ff_band ... = a && b : this ... = tt : H) ff_ne_tt) (suppose a = tt, this) theorem band_intro {a b : bool} (H₁ : a = tt) (H₂ : b = tt) : a && b = tt := by rewrite [H₁, H₂] theorem band_elim_right {a b : bool} (H : a && b = tt) : b = tt := band_elim_left (!band.comm ⬝ H) theorem bnot_bnot (a : bool) : bnot (bnot a) = a := bool.cases_on a rfl rfl theorem bnot_empty : bnot ff = tt := rfl theorem bnot_unit : bnot tt = ff := rfl theorem eq_tt_of_bnot_eq_ff {a : bool} : bnot a = ff → a = tt := bool.cases_on a (by contradiction) (λ h, rfl) theorem eq_ff_of_bnot_eq_tt {a : bool} : bnot a = tt → a = ff := bool.cases_on a (λ h, rfl) (by contradiction) definition bxor (x:bool) (y:bool) := cond x (bnot y) y /- HoTT-related stuff -/ open is_equiv equiv function is_trunc option unit decidable definition is_equiv_bnot [constructor] [instance] [priority 500] : is_equiv bnot := begin fapply is_equiv.mk, exact bnot, all_goals (intro b;cases b), do 6 reflexivity -- all_goals (focus (intro b;cases b;all_goals reflexivity)), end definition bnot_ne : Π(b : bool), bnot b ≠ b | bnot_ne tt := ff_ne_tt | bnot_ne ff := ne.symm ff_ne_tt definition equiv_bnot [constructor] : bool ≃ bool := equiv.mk bnot _ definition eq_bnot : bool = bool := ua equiv_bnot definition eq_bnot_ne_idp : eq_bnot ≠ idp := assume H : eq_bnot = idp, have H2 : bnot = id, from !cast_ua_fn⁻¹ ⬝ ap cast H, absurd (ap10 H2 tt) ff_ne_tt theorem is_set_bool : is_set bool := _ theorem not_is_prop_bool_eq_bool : ¬ is_prop (bool = bool) := λ H, eq_bnot_ne_idp !is_prop.elim definition bool_equiv_option_unit [constructor] : bool ≃ option unit := begin fapply equiv.MK, { intro b, cases b, exact none, exact some star}, { intro u, cases u, exact ff, exact tt}, { intro u, cases u with u, reflexivity, cases u, reflexivity}, { intro b, cases b, reflexivity, reflexivity}, end definition tbool [constructor] : Set := trunctype.mk bool _ end bool
d52de93e8d55f424c6586998c505be2266ef5e09
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/list/sort.lean
92ba2fed19d5511a5aaacd6af88a9d29d58ef79e
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
14,769
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import data.list.perm /-! # Sorting algorithms on lists In this file we define `list.sorted r l` to be an alias for `pairwise r l`. This alias is preferred in the case that `r` is a `<` or `≤`-like relation. Then we define two sorting algorithms: `list.insertion_sort` and `list.merge_sort`, and prove their correctness. -/ open list.perm universe uu namespace list /-! ### The predicate `list.sorted` -/ section sorted variables {α : Type uu} {r : α → α → Prop} {a : α} {l : list α} /-- `sorted r l` is the same as `pairwise r l`, preferred in the case that `r` is a `<` or `≤`-like relation (transitive and antisymmetric or asymmetric) -/ def sorted := @pairwise instance decidable_sorted [decidable_rel r] (l : list α) : decidable (sorted r l) := list.decidable_pairwise _ @[simp] theorem sorted_nil : sorted r [] := pairwise.nil lemma sorted.of_cons : sorted r (a :: l) → sorted r l := pairwise.of_cons theorem sorted.tail {r : α → α → Prop} {l : list α} (h : sorted r l) : sorted r l.tail := h.tail theorem rel_of_sorted_cons {a : α} {l : list α} : sorted r (a :: l) → ∀ b ∈ l, r a b := rel_of_pairwise_cons @[simp] theorem sorted_cons {a : α} {l : list α} : sorted r (a :: l) ↔ (∀ b ∈ l, r a b) ∧ sorted r l := pairwise_cons protected theorem sorted.nodup {r : α → α → Prop} [is_irrefl α r] {l : list α} (h : sorted r l) : nodup l := h.nodup theorem eq_of_perm_of_sorted [is_antisymm α r] {l₁ l₂ : list α} (p : l₁ ~ l₂) (s₁ : sorted r l₁) (s₂ : sorted r l₂) : l₁ = l₂ := begin induction s₁ with a l₁ h₁ s₁ IH generalizing l₂, { exact p.nil_eq }, { have : a ∈ l₂ := p.subset (mem_cons_self _ _), rcases mem_split this with ⟨u₂, v₂, rfl⟩, have p' := (perm_cons a).1 (p.trans perm_middle), obtain rfl := IH p' (s₂.sublist $ by simp), change a::u₂ ++ v₂ = u₂ ++ ([a] ++ v₂), rw ← append_assoc, congr, have : ∀ (x : α) (h : x ∈ u₂), x = a := λ x m, antisymm ((pairwise_append.1 s₂).2.2 _ m a (mem_cons_self _ _)) (h₁ _ (by simp [m])), rw [(@eq_repeat _ a (length u₂ + 1) (a::u₂)).2, (@eq_repeat _ a (length u₂ + 1) (u₂++[a])).2]; split; simp [iff_true_intro this, or_comm] } end theorem sublist_of_subperm_of_sorted [is_antisymm α r] {l₁ l₂ : list α} (p : l₁ <+~ l₂) (s₁ : l₁.sorted r) (s₂ : l₂.sorted r) : l₁ <+ l₂ := let ⟨_, h, h'⟩ := p in by rwa ←eq_of_perm_of_sorted h (s₂.sublist h') s₁ @[simp] theorem sorted_singleton (a : α) : sorted r [a] := pairwise_singleton _ _ lemma sorted.rel_nth_le_of_lt {l : list α} (h : l.sorted r) {a b : ℕ} (ha : a < l.length) (hb : b < l.length) (hab : a < b) : r (l.nth_le a ha) (l.nth_le b hb) := list.pairwise_iff_nth_le.1 h a b hb hab lemma sorted.rel_nth_le_of_le [is_refl α r] {l : list α} (h : l.sorted r) {a b : ℕ} (ha : a < l.length) (hb : b < l.length) (hab : a ≤ b) : r (l.nth_le a ha) (l.nth_le b hb) := begin cases eq_or_lt_of_le hab with H H, { subst H, exact refl _ }, { exact h.rel_nth_le_of_lt _ _ H } end lemma sorted.rel_of_mem_take_of_mem_drop {l : list α} (h : list.sorted r l) {k : ℕ} {x y : α} (hx : x ∈ list.take k l) (hy : y ∈ list.drop k l) : r x y := begin obtain ⟨iy, hiy, rfl⟩ := nth_le_of_mem hy, obtain ⟨ix, hix, rfl⟩ := nth_le_of_mem hx, rw [nth_le_take', nth_le_drop'], rw length_take at hix, exact h.rel_nth_le_of_lt _ _ (ix.lt_add_right _ _ (lt_min_iff.mp hix).left) end end sorted section monotone variables {n : ℕ} {α : Type uu} [preorder α] {f : fin n → α} /-- A tuple is monotone if and only if the list obtained from it is sorted. -/ lemma monotone_iff_of_fn_sorted : monotone f ↔ (of_fn f).sorted (≤) := begin simp_rw [sorted, pairwise_iff_nth_le, length_of_fn, nth_le_of_fn', monotone_iff_forall_lt], exact ⟨λ h i j hj hij, h $ fin.mk_lt_mk.mpr hij, λ h ⟨i, _⟩ ⟨j, hj⟩ hij, h i j hj hij⟩, end /-- The list obtained from a monotone tuple is sorted. -/ lemma monotone.of_fn_sorted (h : monotone f) : (of_fn f).sorted (≤) := monotone_iff_of_fn_sorted.1 h end monotone section sort variables {α : Type uu} (r : α → α → Prop) [decidable_rel r] local infix ` ≼ ` : 50 := r /-! ### Insertion sort -/ section insertion_sort /-- `ordered_insert a l` inserts `a` into `l` at such that `ordered_insert a l` is sorted if `l` is. -/ @[simp] def ordered_insert (a : α) : list α → list α | [] := [a] | (b :: l) := if a ≼ b then a :: b :: l else b :: ordered_insert l /-- `insertion_sort l` returns `l` sorted using the insertion sort algorithm. -/ @[simp] def insertion_sort : list α → list α | [] := [] | (b :: l) := ordered_insert r b (insertion_sort l) @[simp] lemma ordered_insert_nil (a : α) : [].ordered_insert r a = [a] := rfl theorem ordered_insert_length : Π (L : list α) (a : α), (L.ordered_insert r a).length = L.length + 1 | [] a := rfl | (hd :: tl) a := by { dsimp [ordered_insert], split_ifs; simp [ordered_insert_length], } /-- An alternative definition of `ordered_insert` using `take_while` and `drop_while`. -/ lemma ordered_insert_eq_take_drop (a : α) : ∀ l : list α, l.ordered_insert r a = l.take_while (λ b, ¬(a ≼ b)) ++ (a :: l.drop_while (λ b, ¬(a ≼ b))) | [] := rfl | (b :: l) := by { dsimp only [ordered_insert], split_ifs; simp [take_while, drop_while, *] } lemma insertion_sort_cons_eq_take_drop (a : α) (l : list α) : insertion_sort r (a :: l) = (insertion_sort r l).take_while (λ b, ¬(a ≼ b)) ++ (a :: (insertion_sort r l).drop_while (λ b, ¬(a ≼ b))) := ordered_insert_eq_take_drop r a _ section correctness open perm theorem perm_ordered_insert (a) : ∀ l : list α, ordered_insert r a l ~ a :: l | [] := perm.refl _ | (b :: l) := by by_cases a ≼ b; [simp [ordered_insert, h], simpa [ordered_insert, h] using ((perm_ordered_insert l).cons _).trans (perm.swap _ _ _)] theorem ordered_insert_count [decidable_eq α] (L : list α) (a b : α) : count a (L.ordered_insert r b) = count a L + if (a = b) then 1 else 0 := begin rw [(L.perm_ordered_insert r b).count_eq, count_cons], split_ifs; simp only [nat.succ_eq_add_one, add_zero], end theorem perm_insertion_sort : ∀ l : list α, insertion_sort r l ~ l | [] := perm.nil | (b :: l) := by simpa [insertion_sort] using (perm_ordered_insert _ _ _).trans ((perm_insertion_sort l).cons b) variable {r} /-- If `l` is already `list.sorted` with respect to `r`, then `insertion_sort` does not change it. -/ lemma sorted.insertion_sort_eq : ∀ {l : list α} (h : sorted r l), insertion_sort r l = l | [] _ := rfl | [a] _ := rfl | (a :: b :: l) h := begin rw [insertion_sort, sorted.insertion_sort_eq, ordered_insert, if_pos], exacts [rel_of_sorted_cons h _ (or.inl rfl), h.tail] end section total_and_transitive variables [is_total α r] [is_trans α r] theorem sorted.ordered_insert (a : α) : ∀ l, sorted r l → sorted r (ordered_insert r a l) | [] h := sorted_singleton a | (b :: l) h := begin by_cases h' : a ≼ b, { simpa [ordered_insert, h', h] using λ b' bm, trans h' (rel_of_sorted_cons h _ bm) }, { suffices : ∀ (b' : α), b' ∈ ordered_insert r a l → r b b', { simpa [ordered_insert, h', h.of_cons.ordered_insert l] }, intros b' bm, cases (show b' = a ∨ b' ∈ l, by simpa using (perm_ordered_insert _ _ _).subset bm) with be bm, { subst b', exact (total_of r _ _).resolve_left h' }, { exact rel_of_sorted_cons h _ bm } } end variable (r) /-- The list `list.insertion_sort r l` is `list.sorted` with respect to `r`. -/ theorem sorted_insertion_sort : ∀ l, sorted r (insertion_sort r l) | [] := sorted_nil | (a :: l) := (sorted_insertion_sort l).ordered_insert a _ end total_and_transitive end correctness end insertion_sort /-! ### Merge sort -/ section merge_sort -- TODO(Jeremy): observation: if instead we write (a :: (split l).1, b :: (split l).2), the -- equation compiler can't prove the third equation /-- Split `l` into two lists of approximately equal length. split [1, 2, 3, 4, 5] = ([1, 3, 5], [2, 4]) -/ @[simp] def split : list α → list α × list α | [] := ([], []) | (a :: l) := let (l₁, l₂) := split l in (a :: l₂, l₁) theorem split_cons_of_eq (a : α) {l l₁ l₂ : list α} (h : split l = (l₁, l₂)) : split (a :: l) = (a :: l₂, l₁) := by rw [split, h]; refl theorem length_split_le : ∀ {l l₁ l₂ : list α}, split l = (l₁, l₂) → length l₁ ≤ length l ∧ length l₂ ≤ length l | [] ._ ._ rfl := ⟨nat.le_refl 0, nat.le_refl 0⟩ | (a::l) l₁' l₂' h := begin cases e : split l with l₁ l₂, injection (split_cons_of_eq _ e).symm.trans h, substs l₁' l₂', cases length_split_le e with h₁ h₂, exact ⟨nat.succ_le_succ h₂, nat.le_succ_of_le h₁⟩ end theorem length_split_lt {a b} {l l₁ l₂ : list α} (h : split (a::b::l) = (l₁, l₂)) : length l₁ < length (a::b::l) ∧ length l₂ < length (a::b::l) := begin cases e : split l with l₁' l₂', injection (split_cons_of_eq _ (split_cons_of_eq _ e)).symm.trans h, substs l₁ l₂, cases length_split_le e with h₁ h₂, exact ⟨nat.succ_le_succ (nat.succ_le_succ h₁), nat.succ_le_succ (nat.succ_le_succ h₂)⟩ end theorem perm_split : ∀ {l l₁ l₂ : list α}, split l = (l₁, l₂) → l ~ l₁ ++ l₂ | [] ._ ._ rfl := perm.refl _ | (a::l) l₁' l₂' h := begin cases e : split l with l₁ l₂, injection (split_cons_of_eq _ e).symm.trans h, substs l₁' l₂', exact ((perm_split e).trans perm_append_comm).cons a, end /-- Merge two sorted lists into one in linear time. merge [1, 2, 4, 5] [0, 1, 3, 4] = [0, 1, 1, 2, 3, 4, 4, 5] -/ def merge : list α → list α → list α | [] l' := l' | l [] := l | (a :: l) (b :: l') := if a ≼ b then a :: merge l (b :: l') else b :: merge (a :: l) l' include r /-- Implementation of a merge sort algorithm to sort a list. -/ def merge_sort : list α → list α | [] := [] | [a] := [a] | (a::b::l) := begin cases e : split (a::b::l) with l₁ l₂, cases length_split_lt e with h₁ h₂, exact merge r (merge_sort l₁) (merge_sort l₂) end using_well_founded { rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩], dec_tac := tactic.assumption } theorem merge_sort_cons_cons {a b} {l l₁ l₂ : list α} (h : split (a::b::l) = (l₁, l₂)) : merge_sort r (a::b::l) = merge r (merge_sort r l₁) (merge_sort r l₂) := begin suffices : ∀ (L : list α) h1, @@and.rec (λ a a (_ : length l₁ < length l + 1 + 1 ∧ length l₂ < length l + 1 + 1), L) h1 h1 = L, { simp [merge_sort, h], apply this }, intros, cases h1, refl end section correctness theorem perm_merge : ∀ (l l' : list α), merge r l l' ~ l ++ l' | [] [] := by simp [merge] | [] (b :: l') := by simp [merge] | (a :: l) [] := by simp [merge] | (a :: l) (b :: l') := begin by_cases a ≼ b, { simpa [merge, h] using perm_merge _ _ }, { suffices : b :: merge r (a :: l) l' ~ a :: (l ++ b :: l'), {simpa [merge, h]}, exact ((perm_merge _ _).cons _).trans ((swap _ _ _).trans (perm_middle.symm.cons _)) } end theorem perm_merge_sort : ∀ l : list α, merge_sort r l ~ l | [] := by simp [merge_sort] | [a] := by simp [merge_sort] | (a::b::l) := begin cases e : split (a::b::l) with l₁ l₂, cases length_split_lt e with h₁ h₂, rw [merge_sort_cons_cons r e], apply (perm_merge r _ _).trans, exact ((perm_merge_sort l₁).append (perm_merge_sort l₂)).trans (perm_split e).symm end using_well_founded { rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩], dec_tac := tactic.assumption } @[simp] lemma length_merge_sort (l : list α) : (merge_sort r l).length = l.length := (perm_merge_sort r _).length_eq section total_and_transitive variables {r} [is_total α r] [is_trans α r] theorem sorted.merge : ∀ {l l' : list α}, sorted r l → sorted r l' → sorted r (merge r l l') | [] [] h₁ h₂ := by simp [merge] | [] (b :: l') h₁ h₂ := by simpa [merge] using h₂ | (a :: l) [] h₁ h₂ := by simpa [merge] using h₁ | (a :: l) (b :: l') h₁ h₂ := begin by_cases a ≼ b, { suffices : ∀ (b' : α) (_ : b' ∈ merge r l (b :: l')), r a b', { simpa [merge, h, h₁.of_cons.merge h₂] }, intros b' bm, rcases (show b' = b ∨ b' ∈ l ∨ b' ∈ l', by simpa [or.left_comm] using (perm_merge _ _ _).subset bm) with be | bl | bl', { subst b', assumption }, { exact rel_of_sorted_cons h₁ _ bl }, { exact trans h (rel_of_sorted_cons h₂ _ bl') } }, { suffices : ∀ (b' : α) (_ : b' ∈ merge r (a :: l) l'), r b b', { simpa [merge, h, h₁.merge h₂.of_cons] }, intros b' bm, have ba : b ≼ a := (total_of r _ _).resolve_left h, rcases (show b' = a ∨ b' ∈ l ∨ b' ∈ l', by simpa using (perm_merge _ _ _).subset bm) with be | bl | bl', { subst b', assumption }, { exact trans ba (rel_of_sorted_cons h₁ _ bl) }, { exact rel_of_sorted_cons h₂ _ bl' } } end variable (r) theorem sorted_merge_sort : ∀ l : list α, sorted r (merge_sort r l) | [] := by simp [merge_sort] | [a] := by simp [merge_sort] | (a::b::l) := begin cases e : split (a::b::l) with l₁ l₂, cases length_split_lt e with h₁ h₂, rw [merge_sort_cons_cons r e], exact (sorted_merge_sort l₁).merge (sorted_merge_sort l₂) end using_well_founded { rel_tac := λ_ _, `[exact ⟨_, inv_image.wf length nat.lt_wf⟩], dec_tac := tactic.assumption } theorem merge_sort_eq_self [is_antisymm α r] {l : list α} : sorted r l → merge_sort r l = l := eq_of_perm_of_sorted (perm_merge_sort _ _) (sorted_merge_sort _ _) theorem merge_sort_eq_insertion_sort [is_antisymm α r] (l : list α) : merge_sort r l = insertion_sort r l := eq_of_perm_of_sorted ((perm_merge_sort r l).trans (perm_insertion_sort r l).symm) (sorted_merge_sort r l) (sorted_insertion_sort r l) end total_and_transitive end correctness @[simp] theorem merge_sort_nil : [].merge_sort r = [] := by rw list.merge_sort @[simp] theorem merge_sort_singleton (a : α) : [a].merge_sort r = [a] := by rw list.merge_sort end merge_sort end sort /- try them out! -/ --#eval insertion_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] --#eval merge_sort (λ m n : ℕ, m ≤ n) [5, 27, 221, 95, 17, 43, 7, 2, 98, 567, 23, 12] end list
2ce1420ac9ee4f8aca10de60cd3bcd9c52c9924f
431385f9e6a07bcb49fbcb5d7d1dc527cd33580a
/src/tls_tactic.lean
c9374da91da5ad555216f15779123b939b5e0652
[]
no_license
maxkaske/zfolean
c853044cbff465b92269fafe1bd8e078e192b2f0
b74bb7accf01b25a6efb3af6b06538f98e7e5a6c
refs/heads/master
1,677,841,414,729
1,613,649,566,000
1,613,649,566,000
336,965,499
1
0
null
null
null
null
UTF-8
Lean
false
false
332
lean
open tactic interactive interactive.types namespace tactic namespace interactive /- apply followed by simp with tls. not yet useful -/ meta def sapply (q : parse texpr) : tactic unit := concat_tags (do h ← i_to_expr_for_apply q, tactic.apply h) >> (simp none none ff {} {"tls"} (loc.ns [none]) ) end interactive end tactic
88179a2dc5f13b54e98ff1ec8505015491ead5cb
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/dedekind_domain/basic.lean
b5c2442176aab1c419f94b0bf717464267e390d9
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,318
lean
/- Copyright (c) 2020 Kenji Nakagawa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio -/ import ring_theory.ideal.over import ring_theory.polynomial.rational_root /-! # Dedekind domains This file defines the notion of a Dedekind domain (or Dedekind ring), as a Noetherian integrally closed commutative ring of Krull dimension at most one. ## Main definitions - `is_dedekind_domain` defines a Dedekind domain as a commutative ring that is Noetherian, integrally closed in its field of fractions and has Krull dimension at most one. `is_dedekind_domain_iff` shows that this does not depend on the choice of field of fractions. ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. The `..._iff` lemmas express this independence. Often, definitions assume that Dedekind domains are not fields. We found it more practical to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [J. Neukirch, *Algebraic Number Theory*][Neukirch1992] ## Tags dedekind domain, dedekind ring -/ variables (R A K : Type*) [comm_ring R] [comm_ring A] [field K] open_locale non_zero_divisors polynomial /-- A ring `R` has Krull dimension at most one if all nonzero prime ideals are maximal. -/ def ring.dimension_le_one : Prop := ∀ p ≠ (⊥ : ideal R), p.is_prime → p.is_maximal open ideal ring namespace ring lemma dimension_le_one.principal_ideal_ring [is_domain A] [is_principal_ideal_ring A] : dimension_le_one A := λ p nonzero prime, by { haveI := prime, exact is_prime.to_maximal_ideal nonzero } lemma dimension_le_one.is_integral_closure (B : Type*) [comm_ring B] [is_domain B] [nontrivial R] [algebra R A] [algebra R B] [algebra B A] [is_scalar_tower R B A] [is_integral_closure B R A] (h : dimension_le_one R) : dimension_le_one B := λ p ne_bot prime, by exactI is_integral_closure.is_maximal_of_is_maximal_comap A p (h _ (is_integral_closure.comap_ne_bot A ne_bot) infer_instance) lemma dimension_le_one.integral_closure [nontrivial R] [is_domain A] [algebra R A] (h : dimension_le_one R) : dimension_le_one (integral_closure R A) := h.is_integral_closure R A (integral_closure R A) end ring variables [is_domain A] /-- A Dedekind domain is an integral domain that is Noetherian, integrally closed, and has Krull dimension at most one. This is definition 3.2 of [Neukirch1992]. The integral closure condition is independent of the choice of field of fractions: use `is_dedekind_domain_iff` to prove `is_dedekind_domain` for a given `fraction_map`. This is the default implementation, but there are equivalent definitions, `is_dedekind_domain_dvr` and `is_dedekind_domain_inv`. TODO: Prove that these are actually equivalent definitions. -/ class is_dedekind_domain : Prop := (is_noetherian_ring : is_noetherian_ring A) (dimension_le_one : dimension_le_one A) (is_integrally_closed : is_integrally_closed A) -- See library note [lower instance priority] attribute [instance, priority 100] is_dedekind_domain.is_noetherian_ring is_dedekind_domain.is_integrally_closed /-- An integral domain is a Dedekind domain iff and only if it is Noetherian, has dimension ≤ 1, and is integrally closed in a given fraction field. In particular, this definition does not depend on the choice of this fraction field. -/ lemma is_dedekind_domain_iff (K : Type*) [field K] [algebra A K] [is_fraction_ring A K] : is_dedekind_domain A ↔ is_noetherian_ring A ∧ dimension_le_one A ∧ (∀ {x : K}, is_integral A x → ∃ y, algebra_map A K y = x) := ⟨λ ⟨hr, hd, hi⟩, ⟨hr, hd, λ x, (is_integrally_closed_iff K).mp hi⟩, λ ⟨hr, hd, hi⟩, ⟨hr, hd, (is_integrally_closed_iff K).mpr @hi⟩⟩ @[priority 100] -- See library note [lower instance priority] instance is_principal_ideal_ring.is_dedekind_domain [is_principal_ideal_ring A] : is_dedekind_domain A := ⟨principal_ideal_ring.is_noetherian_ring, ring.dimension_le_one.principal_ideal_ring A, unique_factorization_monoid.is_integrally_closed⟩
5db182c585cff8a31a6d7860e353e33f893e7663
cf798a5faaa43a993adcc42d1a99d5eab647e00b
/Basics.lean
a120d595f02eef7bf6c4aabaae25ac90180cea17
[]
no_license
myuon/lean-software-foundations
dbbcd37e3552b58c6e139370b16b25c69a42799b
a1a08810f2664493c920742c2d66a3131fb3ae75
refs/heads/master
1,610,261,785,986
1,459,922,839,000
1,459,922,839,000
50,269,716
4
1
null
null
null
null
UTF-8
Lean
false
false
3,843
lean
import data inductive day : Type := | monday : day | tuesday : day | wednesday : day | thursday : day | friday : day | saturday : day | sunday : day open day definition next_weekday : day → day | monday := tuesday | tuesday := wednesday | wednesday := thursday | thursday := friday | friday := monday | saturday := monday | sunday := monday eval (next_weekday friday) eval (next_weekday (next_weekday saturday)) example : ((next_weekday (next_weekday saturday)) = tuesday) := rfl open bool -- Exercise: 1 star (nandb) definition nandb : bool → bool → bool | tt tt := ff | _ _ := tt example : nandb tt ff = tt := rfl example : nandb ff ff = tt := rfl example : nandb ff tt = tt := rfl example : nandb tt tt = ff := rfl -- Exercise: 1 star (andb3) definition andb3 : bool → bool → bool → bool | a b c := a && b && c check bnot open nat definition pred : nat → nat | zero := zero | (succ n) := n definition minustwo : nat → nat | zero := zero | (succ zero) := zero | (succ (succ n)) := n eval minustwo 4 definition evenb : nat → bool | zero := tt | (succ zero) := ff | (succ (succ n)) := evenb n definition oddb n := bnot (evenb n) example : oddb 1 = tt := rfl example : oddb 4 = ff := rfl -- Exercise: 1 star (factorial) definition factorial : nat → nat | 0 := 1 | (succ n) := (succ n) * factorial n eval (0 : nat) + 1 + 1 definition beq_nat : nat → nat → bool | 0 0 := tt | 0 (succ m) := ff | (succ n) 0 := ff | (succ n) (succ m) := beq_nat n m lemma beq_nat_eq : ∀ n m, beq_nat n m = tt → n = m | 0 0 := λe, rfl | 0 (succ m) := by intro; contradiction | (succ n) 0 := by intro; contradiction | (succ n) (succ m) := λe, congr_arg succ (beq_nat_eq n m e) definition ble_nat : nat → nat → bool | 0 _ := tt | (succ n) 0 := ff | (succ n) (succ m) := ble_nat n m lemma ble_nat_le : ∀ n m, ble_nat n m = tt → n ≤ m | 0 m := λe, !zero_le | (succ n) 0 := by intro; contradiction | (succ n) (succ m) := λe, succ_le_succ (ble_nat_le n m e) -- Exercise: 2 stars (blt_nat) definition blt_nat (n m : nat) : bool := ble_nat n m && (bnot (beq_nat n m)) example : blt_nat 2 2 = ff := rfl example : blt_nat 2 4 = tt := rfl example : blt_nat 4 2 = ff := rfl theorem plus_0_r (n : nat) : n + 0 = n := rfl theorem plus_1_r (n : nat) : n + 1 = succ n := rfl theorem mult_0_r (n : nat) : n * 0 = 0 := rfl -- Exercise: 1 star (plus_id_exercise) theorem plus_id_exercise (n m o : nat) : n = m → m = o → n + m = m + o := begin intro p q, rewrite p, rewrite q end theorem mult_0_plus (n m : nat) : (n + 0) * m = n * m := rfl -- Exercise: 2 stars (mult_S_1) theorem mult_s_1 (n m : nat) : m = succ n → m * (n + 1) = m * m := begin intro p, rewrite plus_1_r, rewrite p end theorem plus_1_neq_0 (n : nat) : beq_nat (n + 1) 0 = ff := rfl theorem bnot_involutive (b : bool) : bnot (bnot b) = b := begin cases b, apply rfl, apply rfl end -- Exercise: 1 star (zero_nbeq_plus_1) theorem zeo_nbeq_plus_1 (n : nat) : beq_nat 0 (n + 1) = ff := rfl -- Exercise: 2 stars (boolean_functions) theorem identity_fn_applied_twice : ∀ (f : bool → bool), (∀x, f x = x) → ∀b, f (f b) = b := begin intros, rewrite a, rewrite a end -- Exercise: 2 stars (andb_eq_orb) theorem andb_eq_orb : ∀ (b c : bool), (b && c = b || c) → b = c | tt c p := calc tt = tt || c : tt_bor ... = tt && c : p ... = c : tt_band | ff c p := calc ff = ff && c : ff_band ... = ff || c : p ... = c : ff_bor -- Exercise: 3 stars (binary) inductive bin := | zero : bin | twice : bin → bin | twice_one : bin → bin definition incr : bin → bin | bin.zero := bin.twice_one bin.zero | (bin.twice b) := bin.twice_one b | (bin.twice_one b) := bin.twice (incr b) definition bin_nat : bin → nat | bin.zero := zero | (bin.twice b) := 2 * bin_nat b | (bin.twice_one b) := 2 * bin_nat b + 1
6609f33f803fc7556efba5dae6a29b19aba84569
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebra/group/with_one/defs.lean
813e0abb03ac52d0a09eb9eda9494430c6200fac
[ "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
12,255
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johan Commelin -/ import order.with_bot import algebra.ring.defs /-! # Adjoining a zero/one to semigroups and related algebraic structures > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file contains different results about adjoining an element to an algebraic structure which then behaves like a zero or a one. An example is adjoining a one to a semigroup to obtain a monoid. That this provides an example of an adjunction is proved in `algebra.category.Mon.adjunctions`. Another result says that adjoining to a group an element `zero` gives a `group_with_zero`. For more information about these structures (which are not that standard in informal mathematics, see `algebra.group_with_zero.basic`) -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Add an extra element `1` to a type -/ @[to_additive "Add an extra element `0` to a type"] def with_one (α) := option α namespace with_one instance [has_repr α] : has_repr (with_zero α) := ⟨λ o, match o with | none := "0" | (some a) := "↑" ++ repr a end⟩ @[to_additive] instance [has_repr α] : has_repr (with_one α) := ⟨λ o, match o with | none := "1" | (some a) := "↑" ++ repr a end⟩ @[to_additive] instance : monad with_one := option.monad @[to_additive] instance : has_one (with_one α) := ⟨none⟩ @[to_additive] instance [has_mul α] : has_mul (with_one α) := ⟨option.lift_or_get (*)⟩ @[to_additive] instance [has_inv α] : has_inv (with_one α) := ⟨λ a, option.map has_inv.inv a⟩ @[to_additive] instance [has_involutive_inv α] : has_involutive_inv (with_one α) := { inv_inv := λ a, (option.map_map _ _ _).trans $ by simp_rw [inv_comp_inv, option.map_id, id], ..with_one.has_inv } @[to_additive] instance [has_inv α] : inv_one_class (with_one α) := { inv_one := rfl, ..with_one.has_one, ..with_one.has_inv } @[to_additive] instance : inhabited (with_one α) := ⟨1⟩ @[to_additive] instance [nonempty α] : nontrivial (with_one α) := option.nontrivial @[to_additive] instance : has_coe_t α (with_one α) := ⟨some⟩ /-- Recursor for `with_one` using the preferred forms `1` and `↑a`. -/ @[elab_as_eliminator, to_additive "Recursor for `with_zero` using the preferred forms `0` and `↑a`."] def rec_one_coe {C : with_one α → Sort*} (h₁ : C 1) (h₂ : Π (a : α), C a) : Π (n : with_one α), C n := option.rec h₁ h₂ /-- Deconstruct a `x : with_one α` to the underlying value in `α`, given a proof that `x ≠ 1`. -/ @[to_additive unzero "Deconstruct a `x : with_zero α` to the underlying value in `α`, given a proof that `x ≠ 0`."] def unone {x : with_one α} (hx : x ≠ 1) : α := with_bot.unbot x hx @[simp, to_additive unzero_coe] lemma unone_coe {x : α} (hx : (x : with_one α) ≠ 1) : unone hx = x := rfl @[simp, to_additive coe_unzero] lemma coe_unone {x : with_one α} (hx : x ≠ 1) : ↑(unone hx) = x := with_bot.coe_unbot x hx @[to_additive] lemma some_eq_coe {a : α} : (some a : with_one α) = ↑a := rfl @[simp, to_additive] lemma coe_ne_one {a : α} : (a : with_one α) ≠ (1 : with_one α) := option.some_ne_none a @[simp, to_additive] lemma one_ne_coe {a : α} : (1 : with_one α) ≠ a := coe_ne_one.symm @[to_additive] lemma ne_one_iff_exists {x : with_one α} : x ≠ 1 ↔ ∃ (a : α), ↑a = x := option.ne_none_iff_exists @[to_additive] instance can_lift : can_lift (with_one α) α coe (λ a, a ≠ 1) := { prf := λ a, ne_one_iff_exists.1 } @[simp, norm_cast, to_additive] lemma coe_inj {a b : α} : (a : with_one α) = b ↔ a = b := option.some_inj @[elab_as_eliminator, to_additive] protected lemma cases_on {P : with_one α → Prop} : ∀ (x : with_one α), P 1 → (∀ a : α, P a) → P x := option.cases_on -- the `show` statements in the proofs are important, because otherwise the generated lemmas -- `with_one.mul_one_class._proof_{1,2}` have an ill-typed statement after `with_one` is made -- irreducible. @[to_additive] instance [has_mul α] : mul_one_class (with_one α) := { mul := (*), one := (1), one_mul := show ∀ x : with_one α, 1 * x = x, from (option.lift_or_get_is_left_id _).1, mul_one := show ∀ x : with_one α, x * 1 = x, from (option.lift_or_get_is_right_id _).1 } @[to_additive] instance [semigroup α] : monoid (with_one α) := { mul_assoc := (option.lift_or_get_assoc _).1, ..with_one.mul_one_class } example [semigroup α] : @monoid.to_mul_one_class _ (@with_one.monoid α _) = @with_one.mul_one_class α _ := rfl @[to_additive] instance [comm_semigroup α] : comm_monoid (with_one α) := { mul_comm := (option.lift_or_get_comm _).1, ..with_one.monoid } attribute [irreducible] with_one @[simp, norm_cast, to_additive] lemma coe_mul [has_mul α] (a b : α) : ((a * b : α) : with_one α) = a * b := rfl @[simp, norm_cast, to_additive] lemma coe_inv [has_inv α] (a : α) : ((a⁻¹ : α) : with_one α) = a⁻¹ := rfl end with_one namespace with_zero instance [one : has_one α] : has_one (with_zero α) := { ..one } @[simp, norm_cast] lemma coe_one [has_one α] : ((1 : α) : with_zero α) = 1 := rfl instance [has_mul α] : mul_zero_class (with_zero α) := { mul := λ o₁ o₂, o₁.bind (λ a, option.map (λ b, a * b) o₂), zero_mul := λ a, rfl, mul_zero := λ a, by cases a; refl, ..with_zero.has_zero } @[simp, norm_cast] lemma coe_mul {α : Type u} [has_mul α] {a b : α} : ((a * b : α) : with_zero α) = a * b := rfl @[simp] lemma zero_mul {α : Type u} [has_mul α] (a : with_zero α) : 0 * a = 0 := rfl @[simp] lemma mul_zero {α : Type u} [has_mul α] (a : with_zero α) : a * 0 = 0 := by cases a; refl instance [has_mul α] : no_zero_divisors (with_zero α) := ⟨by { rintro (a|a) (b|b) h, exacts [or.inl rfl, or.inl rfl, or.inr rfl, option.no_confusion h] }⟩ instance [semigroup α] : semigroup_with_zero (with_zero α) := { mul_assoc := λ a b c, match a, b, c with | none, _, _ := rfl | some a, none, _ := rfl | some a, some b, none := rfl | some a, some b, some c := congr_arg some (mul_assoc _ _ _) end, ..with_zero.mul_zero_class } instance [comm_semigroup α] : comm_semigroup (with_zero α) := { mul_comm := λ a b, match a, b with | none, _ := (mul_zero _).symm | some a, none := rfl | some a, some b := congr_arg some (mul_comm _ _) end, ..with_zero.semigroup_with_zero } instance [mul_one_class α] : mul_zero_one_class (with_zero α) := { one_mul := λ a, match a with | none := rfl | some a := congr_arg some $ one_mul _ end, mul_one := λ a, match a with | none := rfl | some a := congr_arg some $ mul_one _ end, ..with_zero.mul_zero_class, ..with_zero.has_one } instance [has_one α] [has_pow α ℕ] : has_pow (with_zero α) ℕ := ⟨λ x n, match x, n with | none, 0 := 1 | none, n + 1 := 0 | some x, n := ↑(x ^ n) end⟩ @[simp, norm_cast] lemma coe_pow [has_one α] [has_pow α ℕ] {a : α} (n : ℕ) : ↑(a ^ n : α) = (↑a ^ n : with_zero α) := rfl instance [monoid α] : monoid_with_zero (with_zero α) := { npow := λ n x, x ^ n, npow_zero' := λ x, match x with | none := rfl | some x := congr_arg some $ pow_zero _ end, npow_succ' := λ n x, match x with | none := rfl | some x := congr_arg some $ pow_succ _ _ end, .. with_zero.mul_zero_one_class, .. with_zero.semigroup_with_zero } instance [comm_monoid α] : comm_monoid_with_zero (with_zero α) := { ..with_zero.monoid_with_zero, ..with_zero.comm_semigroup } /-- Given an inverse operation on `α` there is an inverse operation on `with_zero α` sending `0` to `0`-/ instance [has_inv α] : has_inv (with_zero α) := ⟨λ a, option.map has_inv.inv a⟩ @[simp, norm_cast] lemma coe_inv [has_inv α] (a : α) : ((a⁻¹ : α) : with_zero α) = a⁻¹ := rfl @[simp] lemma inv_zero [has_inv α] : (0 : with_zero α)⁻¹ = 0 := rfl instance [has_involutive_inv α] : has_involutive_inv (with_zero α) := { inv_inv := λ a, (option.map_map _ _ _).trans $ by simp_rw [inv_comp_inv, option.map_id, id], ..with_zero.has_inv } instance [inv_one_class α] : inv_one_class (with_zero α) := { inv_one := show ((1⁻¹ : α) : with_zero α) = 1, by simp, ..with_zero.has_one, ..with_zero.has_inv } instance [has_div α] : has_div (with_zero α) := ⟨λ o₁ o₂, o₁.bind (λ a, option.map (λ b, a / b) o₂)⟩ @[norm_cast] lemma coe_div [has_div α] (a b : α) : ↑(a / b : α) = (a / b : with_zero α) := rfl instance [has_one α] [has_pow α ℤ] : has_pow (with_zero α) ℤ := ⟨λ x n, match x, n with | none, int.of_nat 0 := 1 | none, int.of_nat (nat.succ n) := 0 | none, int.neg_succ_of_nat n := 0 | some x, n := ↑(x ^ n) end⟩ @[simp, norm_cast] lemma coe_zpow [div_inv_monoid α] {a : α} (n : ℤ) : ↑(a ^ n : α) = (↑a ^ n : with_zero α) := rfl instance [div_inv_monoid α] : div_inv_monoid (with_zero α) := { div_eq_mul_inv := λ a b, match a, b with | none, _ := rfl | some a, none := rfl | some a, some b := congr_arg some (div_eq_mul_inv _ _) end, zpow := λ n x, x ^ n, zpow_zero' := λ x, match x with | none := rfl | some x := congr_arg some $ zpow_zero _ end, zpow_succ' := λ n x, match x with | none := rfl | some x := congr_arg some $ div_inv_monoid.zpow_succ' _ _ end, zpow_neg' := λ n x, match x with | none := rfl | some x := congr_arg some $ div_inv_monoid.zpow_neg' _ _ end, .. with_zero.has_div, .. with_zero.has_inv, .. with_zero.monoid_with_zero, } instance [div_inv_one_monoid α] : div_inv_one_monoid (with_zero α) := { ..with_zero.div_inv_monoid, ..with_zero.inv_one_class } instance [division_monoid α] : division_monoid (with_zero α) := { mul_inv_rev := λ a b, match a, b with | none, none := rfl | none, some b := rfl | some a, none := rfl | some a, some b := congr_arg some $ mul_inv_rev _ _ end, inv_eq_of_mul := λ a b, match a, b with | none, none := λ _, rfl | none, some b := by contradiction | some a, none := by contradiction | some a, some b := λ h, congr_arg some $ inv_eq_of_mul_eq_one_right $ option.some_injective _ h end, .. with_zero.div_inv_monoid, .. with_zero.has_involutive_inv } instance [division_comm_monoid α] : division_comm_monoid (with_zero α) := { .. with_zero.division_monoid, .. with_zero.comm_semigroup } section group variables [group α] /-- if `G` is a group then `with_zero G` is a group with zero. -/ instance : group_with_zero (with_zero α) := { inv_zero := inv_zero, mul_inv_cancel := λ a ha, by { lift a to α using ha, norm_cast, apply mul_right_inv }, .. with_zero.monoid_with_zero, .. with_zero.div_inv_monoid, .. with_zero.nontrivial } end group instance [comm_group α] : comm_group_with_zero (with_zero α) := { .. with_zero.group_with_zero, .. with_zero.comm_monoid_with_zero } instance [add_monoid_with_one α] : add_monoid_with_one (with_zero α) := { nat_cast := λ n, if n = 0 then 0 else (n.cast : α), nat_cast_zero := rfl, nat_cast_succ := λ n, begin cases n, show (((1 : ℕ) : α) : with_zero α) = 0 + 1, by rw [nat.cast_one, coe_one, zero_add], show (((n + 2 : ℕ) : α) : with_zero α) = ((n + 1 : ℕ) : α) + 1, by rw [nat.cast_succ, coe_add, coe_one], end, .. with_zero.add_monoid, ..with_zero.has_one } instance [semiring α] : semiring (with_zero α) := { left_distrib := λ a b c, begin cases a with a, {refl}, cases b with b; cases c with c; try {refl}, exact congr_arg some (left_distrib _ _ _) end, right_distrib := λ a b c, begin cases c with c, { change (a + b) * 0 = a * 0 + b * 0, simp }, cases a with a; cases b with b; try {refl}, exact congr_arg some (right_distrib _ _ _) end, ..with_zero.add_monoid_with_one, ..with_zero.add_comm_monoid, ..with_zero.mul_zero_class, ..with_zero.monoid_with_zero } attribute [irreducible] with_zero end with_zero
82d7b719e91b9020f63ec2293664102b5b4c9115
618003631150032a5676f229d13a079ac875ff77
/test/norm_cast_int.lean
b861ff123a7647d6a9245ac22eafdf0acada5403
[ "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
568
lean
import tactic.norm_cast import data.int.basic set_option pp.numerals false set_option pp.notation false -- set_option trace.simplify.rewrite true #eval norm_cast.numeral_to_coe `(0 : ℤ) #eval norm_cast.numeral_to_coe `(1 : ℤ) #eval norm_cast.numeral_to_coe `(2 : ℤ) #eval norm_cast.numeral_to_coe `(3 : ℤ) #eval norm_cast.coe_to_numeral `((0 : ℕ) : ℤ) #eval norm_cast.coe_to_numeral `((1 : ℕ) : ℤ) #eval norm_cast.coe_to_numeral `((2 : ℕ) : ℤ) #eval norm_cast.coe_to_numeral `((3 : ℕ) : ℤ) example : ((42 : ℕ) : ℤ) = 42 := by norm_cast
178c5769e0dbb12d68a3b62b7116ed0cd98c6897
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/closed/ideal.lean
42d0b6e57085a5104b91b7707534cfd20bc54e9b
[ "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
11,796
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.limits.preserves.shapes.binary_products import category_theory.limits.constructions.finite_products_of_binary_products import category_theory.monad.limits import category_theory.adjunction.fully_faithful import category_theory.adjunction.reflective import category_theory.closed.cartesian import category_theory.subterminal /-! # Exponential ideals An exponential ideal of a cartesian closed category `C` is a subcategory `D ⊆ C` such that for any `B : D` and `A : C`, the exponential `A ⟹ B` is in `D`: resembling ring theoretic ideals. We define the notion here for inclusion functors `i : D ⥤ C` rather than explicit subcategories to preserve the principle of equivalence. We additionally show that if `C` is cartesian closed and `i : D ⥤ C` is a reflective functor, the following are equivalent. * The left adjoint to `i` preserves binary (equivalently, finite) products. * `i` is an exponential ideal. -/ universes v₁ v₂ u₁ u₂ noncomputable theory namespace category_theory open limits category section ideal variables {C : Type u₁} {D : Type u₂} [category.{v₁} C] [category.{v₁} D] {i : D ⥤ C} variables (i) [has_finite_products C] [cartesian_closed C] /-- The subcategory `D` of `C` expressed as an inclusion functor is an *exponential ideal* if `B ∈ D` implies `A ⟹ B ∈ D` for all `A`. -/ class exponential_ideal : Prop := (exp_closed : ∀ {B}, B ∈ i.ess_image → ∀ A, (A ⟹ B) ∈ i.ess_image) /-- To show `i` is an exponential ideal it suffices to show that `A ⟹ iB` is "in" `D` for any `A` in `C` and `B` in `D`. -/ lemma exponential_ideal.mk' (h : ∀ (B : D) (A : C), (A ⟹ i.obj B) ∈ i.ess_image) : exponential_ideal i := ⟨λ B hB A, begin rcases hB with ⟨B', ⟨iB'⟩⟩, exact functor.ess_image.of_iso ((exp A).map_iso iB') (h B' A), end⟩ /-- The entire category viewed as a subcategory is an exponential ideal. -/ instance : exponential_ideal (𝟭 C) := exponential_ideal.mk' _ (λ B A, ⟨_, ⟨iso.refl _⟩⟩) open cartesian_closed /-- The subcategory of subterminal objects is an exponential ideal. -/ instance : exponential_ideal (subterminal_inclusion C) := begin apply exponential_ideal.mk', intros B A, refine ⟨⟨A ⟹ B.1, λ Z g h, _⟩, ⟨iso.refl _⟩⟩, exact uncurry_injective (B.2 (cartesian_closed.uncurry g) (cartesian_closed.uncurry h)) end /-- If `D` is a reflective subcategory, the property of being an exponential ideal is equivalent to the presence of a natural isomorphism `i ⋙ exp A ⋙ left_adjoint i ⋙ i ≅ i ⋙ exp A`, that is: `(A ⟹ iB) ≅ i L (A ⟹ iB)`, naturally in `B`. The converse is given in `exponential_ideal.mk_of_iso`. -/ def exponential_ideal_reflective (A : C) [reflective i] [exponential_ideal i] : i ⋙ exp A ⋙ left_adjoint i ⋙ i ≅ i ⋙ exp A := begin symmetry, apply nat_iso.of_components _ _, { intro X, haveI := (exponential_ideal.exp_closed (i.obj_mem_ess_image X) A).unit_is_iso, apply as_iso ((adjunction.of_right_adjoint i).unit.app (A ⟹ i.obj X)) }, { simp } end /-- Given a natural isomorphism `i ⋙ exp A ⋙ left_adjoint i ⋙ i ≅ i ⋙ exp A`, we can show `i` is an exponential ideal. -/ lemma exponential_ideal.mk_of_iso [reflective i] (h : Π (A : C), i ⋙ exp A ⋙ left_adjoint i ⋙ i ≅ i ⋙ exp A) : exponential_ideal i := begin apply exponential_ideal.mk', intros B A, exact ⟨_, ⟨(h A).app B⟩⟩, end end ideal section variables {C : Type u₁} {D : Type u₂} [category.{v₁} C] [category.{v₁} D] variables (i : D ⥤ C) lemma reflective_products [has_finite_products C] [reflective i] : has_finite_products D := ⟨λ J 𝒥₁ 𝒥₂, by exactI has_limits_of_shape_of_reflective i⟩ local attribute [instance, priority 10] reflective_products open cartesian_closed variables [has_finite_products C] [reflective i] [cartesian_closed C] /-- If the reflector preserves binary products, the subcategory is an exponential ideal. This is the converse of `preserves_binary_products_of_exponential_ideal`. -/ @[priority 10] instance exponential_ideal_of_preserves_binary_products [preserves_limits_of_shape (discrete walking_pair) (left_adjoint i)] : exponential_ideal i := begin let ir := adjunction.of_right_adjoint i, let L : C ⥤ D := left_adjoint i, let η : 𝟭 C ⟶ L ⋙ i := ir.unit, let ε : i ⋙ L ⟶ 𝟭 D := ir.counit, apply exponential_ideal.mk', intros B A, let q : i.obj (L.obj (A ⟹ i.obj B)) ⟶ A ⟹ i.obj B, apply cartesian_closed.curry (ir.hom_equiv _ _ _), apply _ ≫ (ir.hom_equiv _ _).symm ((ev A).app (i.obj B)), refine prod_comparison L A _ ≫ limits.prod.map (𝟙 _) (ε.app _) ≫ inv (prod_comparison _ _ _), have : η.app (A ⟹ i.obj B) ≫ q = 𝟙 (A ⟹ i.obj B), { dsimp, rw [← curry_natural_left, curry_eq_iff, uncurry_id_eq_ev, ← ir.hom_equiv_naturality_left, ir.hom_equiv_apply_eq, assoc, assoc, prod_comparison_natural_assoc, L.map_id, ← prod.map_id_comp_assoc, ir.left_triangle_components, prod.map_id_id, id_comp], apply is_iso.hom_inv_id_assoc }, haveI : split_mono (η.app (A ⟹ i.obj B)) := ⟨_, this⟩, apply mem_ess_image_of_unit_split_mono, end variables [exponential_ideal i] /-- If `i` witnesses that `D` is a reflective subcategory and an exponential ideal, then `D` is itself cartesian closed. -/ def cartesian_closed_of_reflective : cartesian_closed D := { closed := λ B, { is_adj := { right := i ⋙ exp (i.obj B) ⋙ left_adjoint i, adj := begin apply adjunction.restrict_fully_faithful i i (exp.adjunction (i.obj B)), { symmetry, apply nat_iso.of_components _ _, { intro X, haveI := adjunction.right_adjoint_preserves_limits (adjunction.of_right_adjoint i), apply as_iso (prod_comparison i B X) }, { intros X Y f, dsimp, rw prod_comparison_natural, simp, } }, { apply (exponential_ideal_reflective i _).symm } end } } } -- It's annoying that I need to do this. local attribute [-instance] category_theory.preserves_limit_of_creates_limit_and_has_limit category_theory.preserves_limit_of_shape_of_creates_limits_of_shape_and_has_limits_of_shape /-- We construct a bijection between morphisms `L(A ⨯ B) ⟶ X` and morphisms `LA ⨯ LB ⟶ X`. This bijection has two key properties: * It is natural in `X`: See `bijection_natural`. * When `X = LA ⨯ LB`, then the backwards direction sends the identity morphism to the product comparison morphism: See `bijection_symm_apply_id`. Together these help show that `L` preserves binary products. This should be considered *internal implementation* towards `preserves_binary_products_of_exponential_ideal`. -/ noncomputable def bijection (A B : C) (X : D) : ((left_adjoint i).obj (A ⨯ B) ⟶ X) ≃ ((left_adjoint i).obj A ⨯ (left_adjoint i).obj B ⟶ X) := calc _ ≃ (A ⨯ B ⟶ i.obj X) : (adjunction.of_right_adjoint i).hom_equiv _ _ ... ≃ (B ⨯ A ⟶ i.obj X) : (limits.prod.braiding _ _).hom_congr (iso.refl _) ... ≃ (A ⟶ B ⟹ i.obj X) : (exp.adjunction _).hom_equiv _ _ ... ≃ (i.obj ((left_adjoint i).obj A) ⟶ B ⟹ i.obj X) : unit_comp_partial_bijective _ (exponential_ideal.exp_closed (i.obj_mem_ess_image _) _) ... ≃ (B ⨯ i.obj ((left_adjoint i).obj A) ⟶ i.obj X) : ((exp.adjunction _).hom_equiv _ _).symm ... ≃ (i.obj ((left_adjoint i).obj A) ⨯ B ⟶ i.obj X) : (limits.prod.braiding _ _).hom_congr (iso.refl _) ... ≃ (B ⟶ i.obj ((left_adjoint i).obj A) ⟹ i.obj X) : (exp.adjunction _).hom_equiv _ _ ... ≃ (i.obj ((left_adjoint i).obj B) ⟶ i.obj ((left_adjoint i).obj A) ⟹ i.obj X) : unit_comp_partial_bijective _ (exponential_ideal.exp_closed (i.obj_mem_ess_image _) _) ... ≃ (i.obj ((left_adjoint i).obj A) ⨯ i.obj ((left_adjoint i).obj B) ⟶ i.obj X) : ((exp.adjunction _).hom_equiv _ _).symm ... ≃ (i.obj ((left_adjoint i).obj A ⨯ (left_adjoint i).obj B) ⟶ i.obj X) : begin apply iso.hom_congr _ (iso.refl _), haveI : preserves_limits i := (adjunction.of_right_adjoint i).right_adjoint_preserves_limits, exact (preserves_limit_pair.iso _ _ _).symm, end ... ≃ ((left_adjoint i).obj A ⨯ (left_adjoint i).obj B ⟶ X) : (equiv_of_fully_faithful _).symm lemma bijection_symm_apply_id (A B : C) : (bijection i A B _).symm (𝟙 _) = prod_comparison _ _ _ := begin dsimp [bijection], rw [comp_id, comp_id, comp_id, i.map_id, comp_id, unit_comp_partial_bijective_symm_apply, unit_comp_partial_bijective_symm_apply, uncurry_natural_left, uncurry_curry, uncurry_natural_left, uncurry_curry, prod.lift_map_assoc, comp_id, prod.lift_map_assoc, comp_id, prod.comp_lift_assoc, prod.lift_snd, prod.lift_fst_assoc, prod.lift_fst_comp_snd_comp, ←adjunction.eq_hom_equiv_apply, adjunction.hom_equiv_unit, iso.comp_inv_eq, assoc, preserves_limit_pair.iso_hom], apply prod.hom_ext, { rw [limits.prod.map_fst, assoc, assoc, prod_comparison_fst, ←i.map_comp, prod_comparison_fst], apply (adjunction.of_right_adjoint i).unit.naturality }, { rw [limits.prod.map_snd, assoc, assoc, prod_comparison_snd, ←i.map_comp, prod_comparison_snd], apply (adjunction.of_right_adjoint i).unit.naturality }, end lemma bijection_natural (A B : C) (X X' : D) (f : ((left_adjoint i).obj (A ⨯ B) ⟶ X)) (g : X ⟶ X') : bijection i _ _ _ (f ≫ g) = bijection i _ _ _ f ≫ g := begin dsimp [bijection], apply i.map_injective, rw [i.image_preimage, i.map_comp, i.image_preimage, comp_id, comp_id, comp_id, comp_id, comp_id, comp_id, adjunction.hom_equiv_naturality_right, ← assoc, curry_natural_right _ (i.map g), unit_comp_partial_bijective_natural, uncurry_natural_right, ← assoc, curry_natural_right, unit_comp_partial_bijective_natural, uncurry_natural_right, assoc], end /-- The bijection allows us to show that `prod_comparison L A B` is an isomorphism, where the inverse is the forward map of the identity morphism. -/ lemma prod_comparison_iso (A B : C) : is_iso (prod_comparison (left_adjoint i) A B) := ⟨⟨bijection i _ _ _ (𝟙 _), by rw [←(bijection i _ _ _).injective.eq_iff, bijection_natural, ← bijection_symm_apply_id, equiv.apply_symm_apply, id_comp], by rw [←bijection_natural, id_comp, ←bijection_symm_apply_id, equiv.apply_symm_apply]⟩⟩ local attribute [instance] prod_comparison_iso /-- If a reflective subcategory is an exponential ideal, then the reflector preserves binary products. This is the converse of `exponential_ideal_of_preserves_binary_products`. -/ noncomputable def preserves_binary_products_of_exponential_ideal : preserves_limits_of_shape (discrete walking_pair) (left_adjoint i) := { preserves_limit := λ K, begin apply limits.preserves_limit_of_iso_diagram _ (diagram_iso_pair K).symm, apply preserves_limit_pair.of_iso_prod_comparison, end } /-- If a reflective subcategory is an exponential ideal, then the reflector preserves finite products. -/ noncomputable def preserves_finite_products_of_exponential_ideal (J : Type*) [fintype J] : preserves_limits_of_shape (discrete J) (left_adjoint i) := begin letI := preserves_binary_products_of_exponential_ideal i, letI := left_adjoint_preserves_terminal_of_reflective i, apply preserves_finite_products_of_preserves_binary_and_terminal (left_adjoint i) J end end end category_theory
87b438f23afc76ea26dfdee96015f582604a0dd3
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/group/type_tags.lean
684ca9f8b0ccf000e4b7575cd942c929655a8828
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,002
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.order.group.instances import algebra.order.monoid.type_tags /-! # Ordered group structures on `multiplicative α` and `additive α`. -/ variables {α : Type*} instance [ordered_add_comm_group α] : ordered_comm_group (multiplicative α) := { ..multiplicative.comm_group, ..multiplicative.ordered_comm_monoid } instance [ordered_comm_group α] : ordered_add_comm_group (additive α) := { ..additive.add_comm_group, ..additive.ordered_add_comm_monoid } instance [linear_ordered_add_comm_group α] : linear_ordered_comm_group (multiplicative α) := { ..multiplicative.linear_order, ..multiplicative.ordered_comm_group } instance [linear_ordered_comm_group α] : linear_ordered_add_comm_group (additive α) := { ..additive.linear_order, ..additive.ordered_add_comm_group }
9c61d959daa7b34304287d9c865db2d7660e07fa
c777c32c8e484e195053731103c5e52af26a25d1
/src/probability/process/hitting_time.lean
7881a97d1152d585019209c6a322a144bfea69e8
[ "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
13,089
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Rémy Degenne -/ import probability.process.stopping /-! # Hitting time Given a stochastic process, the hitting time provides the first time the process ``hits'' some subset of the state space. The hitting time is a stopping time in the case that the time index is discrete and the process is adapted (this is true in a far more general setting however we have only proved it for the discrete case so far). ## Main definition * `measure_theory.hitting`: the hitting time of a stochastic process ## Main results * `measure_theory.hitting_is_stopping_time`: a discrete hitting time of an adapted process is a stopping time ## Implementation notes In the definition of the hitting time, we bound the hitting time by an upper and lower bound. This is to ensure that our result is meaningful in the case we are taking the infimum of an empty set or the infimum of a set which is unbounded from below. With this, we can talk about hitting times indexed by the natural numbers or the reals. By taking the bounds to be `⊤` and `⊥`, we obtain the standard definition in the case that the index is `ℕ∞` or `ℝ≥0∞`. -/ open filter order topological_space open_locale classical measure_theory nnreal ennreal topology big_operators namespace measure_theory variables {Ω β ι : Type*} {m : measurable_space Ω} /-- Hitting time: given a stochastic process `u` and a set `s`, `hitting u s n m` is the first time `u` is in `s` after time `n` and before time `m` (if `u` does not hit `s` after time `n` and before `m` then the hitting time is simply `m`). The hitting time is a stopping time if the process is adapted and discrete. -/ noncomputable def hitting [preorder ι] [has_Inf ι] (u : ι → Ω → β) (s : set β) (n m : ι) : Ω → ι := λ x, if ∃ j ∈ set.Icc n m, u j x ∈ s then Inf (set.Icc n m ∩ {i : ι | u i x ∈ s}) else m section inequalities variables [conditionally_complete_linear_order ι] {u : ι → Ω → β} {s : set β} {n i : ι} {ω : Ω} /-- This lemma is strictly weaker than `hitting_of_le`. -/ lemma hitting_of_lt {m : ι} (h : m < n) : hitting u s n m ω = m := begin simp_rw [hitting], have h_not : ¬ ∃ (j : ι) (H : j ∈ set.Icc n m), u j ω ∈ s, { push_neg, intro j, rw set.Icc_eq_empty_of_lt h, simp only [set.mem_empty_iff_false, is_empty.forall_iff], }, simp only [h_not, if_false], end lemma hitting_le {m : ι} (ω : Ω) : hitting u s n m ω ≤ m := begin cases le_or_lt n m with h_le h_lt, { simp only [hitting], split_ifs, { obtain ⟨j, hj₁, hj₂⟩ := h, exact (cInf_le (bdd_below.inter_of_left bdd_below_Icc) (set.mem_inter hj₁ hj₂)).trans hj₁.2 }, { exact le_rfl }, }, { rw hitting_of_lt h_lt, }, end lemma not_mem_of_lt_hitting {m k : ι} (hk₁ : k < hitting u s n m ω) (hk₂ : n ≤ k) : u k ω ∉ s := begin classical, intro h, have hexists : ∃ j ∈ set.Icc n m, u j ω ∈ s, refine ⟨k, ⟨hk₂, le_trans hk₁.le $ hitting_le _⟩, h⟩, refine not_le.2 hk₁ _, simp_rw [hitting, if_pos hexists], exact cInf_le bdd_below_Icc.inter_of_left ⟨⟨hk₂, le_trans hk₁.le $ hitting_le _⟩, h⟩, end lemma hitting_eq_end_iff {m : ι} : hitting u s n m ω = m ↔ (∃ j ∈ set.Icc n m, u j ω ∈ s) → Inf (set.Icc n m ∩ {i : ι | u i ω ∈ s}) = m := by rw [hitting, ite_eq_right_iff] lemma hitting_of_le {m : ι} (hmn : m ≤ n) : hitting u s n m ω = m := begin obtain (rfl | h) := le_iff_eq_or_lt.1 hmn, { simp only [hitting, set.Icc_self, ite_eq_right_iff, set.mem_Icc, exists_prop, forall_exists_index, and_imp], intros i hi₁ hi₂ hi, rw [set.inter_eq_left_iff_subset.2, cInf_singleton], exact set.singleton_subset_iff.2 (le_antisymm hi₂ hi₁ ▸ hi) }, { exact hitting_of_lt h } end lemma le_hitting {m : ι} (hnm : n ≤ m) (ω : Ω) : n ≤ hitting u s n m ω := begin simp only [hitting], split_ifs, { refine le_cInf _ (λ b hb, _), { obtain ⟨k, hk_Icc, hk_s⟩ := h, exact ⟨k, hk_Icc, hk_s⟩, }, { rw set.mem_inter_iff at hb, exact hb.1.1, }, }, { exact hnm }, end lemma le_hitting_of_exists {m : ι} (h_exists : ∃ j ∈ set.Icc n m, u j ω ∈ s) : n ≤ hitting u s n m ω := begin refine le_hitting _ ω, by_contra, rw set.Icc_eq_empty_of_lt (not_le.mp h) at h_exists, simpa using h_exists, end lemma hitting_mem_Icc {m : ι} (hnm : n ≤ m) (ω : Ω) : hitting u s n m ω ∈ set.Icc n m := ⟨le_hitting hnm ω, hitting_le ω⟩ lemma hitting_mem_set [is_well_order ι (<)] {m : ι} (h_exists : ∃ j ∈ set.Icc n m, u j ω ∈ s) : u (hitting u s n m ω) ω ∈ s := begin simp_rw [hitting, if_pos h_exists], have h_nonempty : (set.Icc n m ∩ {i : ι | u i ω ∈ s}).nonempty, { obtain ⟨k, hk₁, hk₂⟩ := h_exists, exact ⟨k, set.mem_inter hk₁ hk₂⟩, }, have h_mem := Inf_mem h_nonempty, rw [set.mem_inter_iff] at h_mem, exact h_mem.2, end lemma hitting_mem_set_of_hitting_lt [is_well_order ι (<)] {m : ι} (hl : hitting u s n m ω < m) : u (hitting u s n m ω) ω ∈ s := begin by_cases h : ∃ j ∈ set.Icc n m, u j ω ∈ s, { exact hitting_mem_set h }, { simp_rw [hitting, if_neg h] at hl, exact false.elim (hl.ne rfl) } end lemma hitting_le_of_mem {m : ι} (hin : n ≤ i) (him : i ≤ m) (his : u i ω ∈ s) : hitting u s n m ω ≤ i := begin have h_exists : ∃ k ∈ set.Icc n m, u k ω ∈ s := ⟨i, ⟨hin, him⟩, his⟩, simp_rw [hitting, if_pos h_exists], exact cInf_le (bdd_below.inter_of_left bdd_below_Icc) (set.mem_inter ⟨hin, him⟩ his), end lemma hitting_le_iff_of_exists [is_well_order ι (<)] {m : ι} (h_exists : ∃ j ∈ set.Icc n m, u j ω ∈ s) : hitting u s n m ω ≤ i ↔ ∃ j ∈ set.Icc n i, u j ω ∈ s := begin split; intro h', { exact ⟨hitting u s n m ω, ⟨le_hitting_of_exists h_exists, h'⟩, hitting_mem_set h_exists⟩, }, { have h'' : ∃ k ∈ set.Icc n (min m i), u k ω ∈ s, { obtain ⟨k₁, hk₁_mem, hk₁_s⟩ := h_exists, obtain ⟨k₂, hk₂_mem, hk₂_s⟩ := h', refine ⟨min k₁ k₂, ⟨le_min hk₁_mem.1 hk₂_mem.1, min_le_min hk₁_mem.2 hk₂_mem.2⟩, _⟩, exact min_rec' (λ j, u j ω ∈ s) hk₁_s hk₂_s, }, obtain ⟨k, hk₁, hk₂⟩ := h'', refine le_trans _ (hk₁.2.trans (min_le_right _ _)), exact hitting_le_of_mem hk₁.1 (hk₁.2.trans (min_le_left _ _)) hk₂, }, end lemma hitting_le_iff_of_lt [is_well_order ι (<)] {m : ι} (i : ι) (hi : i < m) : hitting u s n m ω ≤ i ↔ ∃ j ∈ set.Icc n i, u j ω ∈ s := begin by_cases h_exists : ∃ j ∈ set.Icc n m, u j ω ∈ s, { rw hitting_le_iff_of_exists h_exists, }, { simp_rw [hitting, if_neg h_exists], push_neg at h_exists, simp only [not_le.mpr hi, set.mem_Icc, false_iff, not_exists, and_imp], exact λ k hkn hki, h_exists k ⟨hkn, hki.trans hi.le⟩, }, end lemma hitting_lt_iff [is_well_order ι (<)] {m : ι} (i : ι) (hi : i ≤ m) : hitting u s n m ω < i ↔ ∃ j ∈ set.Ico n i, u j ω ∈ s := begin split; intro h', { have h : ∃ j ∈ set.Icc n m, u j ω ∈ s, { by_contra, simp_rw [hitting, if_neg h, ← not_le] at h', exact h' hi, }, exact ⟨hitting u s n m ω, ⟨le_hitting_of_exists h, h'⟩, hitting_mem_set h⟩, }, { obtain ⟨k, hk₁, hk₂⟩ := h', refine lt_of_le_of_lt _ hk₁.2, exact hitting_le_of_mem hk₁.1 (hk₁.2.le.trans hi) hk₂, }, end lemma hitting_eq_hitting_of_exists {m₁ m₂ : ι} (h : m₁ ≤ m₂) (h' : ∃ j ∈ set.Icc n m₁, u j ω ∈ s) : hitting u s n m₁ ω = hitting u s n m₂ ω := begin simp only [hitting, if_pos h'], obtain ⟨j, hj₁, hj₂⟩ := h', rw if_pos, { refine le_antisymm _ (cInf_le_cInf bdd_below_Icc.inter_of_left ⟨j, hj₁, hj₂⟩ (set.inter_subset_inter_left _ (set.Icc_subset_Icc_right h))), refine le_cInf ⟨j, set.Icc_subset_Icc_right h hj₁, hj₂⟩ (λ i hi, _), by_cases hi' : i ≤ m₁, { exact cInf_le bdd_below_Icc.inter_of_left ⟨⟨hi.1.1, hi'⟩, hi.2⟩ }, { exact ((cInf_le bdd_below_Icc.inter_of_left ⟨hj₁, hj₂⟩).trans (hj₁.2.trans le_rfl)).trans (le_of_lt (not_le.1 hi')) } }, exact ⟨j, ⟨hj₁.1, hj₁.2.trans h⟩, hj₂⟩, end lemma hitting_mono {m₁ m₂ : ι} (hm : m₁ ≤ m₂) : hitting u s n m₁ ω ≤ hitting u s n m₂ ω := begin by_cases h : ∃ j ∈ set.Icc n m₁, u j ω ∈ s, { exact (hitting_eq_hitting_of_exists hm h).le }, { simp_rw [hitting, if_neg h], split_ifs with h', { obtain ⟨j, hj₁, hj₂⟩ := h', refine le_cInf ⟨j, hj₁, hj₂⟩ _, by_contra hneg, push_neg at hneg, obtain ⟨i, hi₁, hi₂⟩ := hneg, exact h ⟨i, ⟨hi₁.1.1, hi₂.le⟩, hi₁.2⟩ }, { exact hm } } end end inequalities /-- A discrete hitting time is a stopping time. -/ lemma hitting_is_stopping_time [conditionally_complete_linear_order ι] [is_well_order ι (<)] [countable ι] [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] {f : filtration ι m} {u : ι → Ω → β} {s : set β} {n n' : ι} (hu : adapted f u) (hs : measurable_set s) : is_stopping_time f (hitting u s n n') := begin intro i, cases le_or_lt n' i with hi hi, { have h_le : ∀ ω, hitting u s n n' ω ≤ i := λ x, (hitting_le x).trans hi, simp [h_le], }, { have h_set_eq_Union : {ω | hitting u s n n' ω ≤ i} = ⋃ j ∈ set.Icc n i, u j ⁻¹' s, { ext x, rw [set.mem_set_of_eq, hitting_le_iff_of_lt _ hi], simp only [set.mem_Icc, exists_prop, set.mem_Union, set.mem_preimage], }, rw h_set_eq_Union, exact measurable_set.Union (λ j, measurable_set.Union $ λ hj, f.mono hj.2 _ ((hu j).measurable hs)) } end lemma stopped_value_hitting_mem [conditionally_complete_linear_order ι] [is_well_order ι (<)] {u : ι → Ω → β} {s : set β} {n m : ι} {ω : Ω} (h : ∃ j ∈ set.Icc n m, u j ω ∈ s) : stopped_value u (hitting u s n m) ω ∈ s := begin simp only [stopped_value, hitting, if_pos h], obtain ⟨j, hj₁, hj₂⟩ := h, have : Inf (set.Icc n m ∩ {i | u i ω ∈ s}) ∈ set.Icc n m ∩ {i | u i ω ∈ s} := Inf_mem (set.nonempty_of_mem ⟨hj₁, hj₂⟩), exact this.2, end /-- The hitting time of a discrete process with the starting time indexed by a stopping time is a stopping time. -/ lemma is_stopping_time_hitting_is_stopping_time [conditionally_complete_linear_order ι] [is_well_order ι (<)] [countable ι] [topological_space ι] [order_topology ι] [first_countable_topology ι] [topological_space β] [pseudo_metrizable_space β] [measurable_space β] [borel_space β] {f : filtration ι m} {u : ι → Ω → β} {τ : Ω → ι} (hτ : is_stopping_time f τ) {N : ι} (hτbdd : ∀ x, τ x ≤ N) {s : set β} (hs : measurable_set s) (hf : adapted f u) : is_stopping_time f (λ x, hitting u s (τ x) N x) := begin intro n, have h₁ : {x | hitting u s (τ x) N x ≤ n} = (⋃ i ≤ n, {x | τ x = i} ∩ {x | hitting u s i N x ≤ n}) ∪ (⋃ i > n, {x | τ x = i} ∩ {x | hitting u s i N x ≤ n}), { ext x, simp [← exists_or_distrib, ← or_and_distrib_right, le_or_lt] }, have h₂ : (⋃ i > n, {x | τ x = i} ∩ {x | hitting u s i N x ≤ n}) = ∅, { ext x, simp only [gt_iff_lt, set.mem_Union, set.mem_inter_iff, set.mem_set_of_eq, exists_prop, set.mem_empty_iff_false, iff_false, not_exists, not_and, not_le], rintro m hm rfl, exact lt_of_lt_of_le hm (le_hitting (hτbdd _) _) }, rw [h₁, h₂, set.union_empty], exact measurable_set.Union (λ i, measurable_set.Union (λ hi, (f.mono hi _ (hτ.measurable_set_eq i)).inter (hitting_is_stopping_time hf hs n))), end section complete_lattice variables [complete_lattice ι] {u : ι → Ω → β} {s : set β} {f : filtration ι m} lemma hitting_eq_Inf (ω : Ω) : hitting u s ⊥ ⊤ ω = Inf {i : ι | u i ω ∈ s} := begin simp only [hitting, set.mem_Icc, bot_le, le_top, and_self, exists_true_left, set.Icc_bot, set.Iic_top, set.univ_inter, ite_eq_left_iff, not_exists], intro h_nmem_s, symmetry, rw Inf_eq_top, exact λ i hi_mem_s, absurd hi_mem_s (h_nmem_s i), end end complete_lattice section conditionally_complete_linear_order_bot variables [conditionally_complete_linear_order_bot ι] [is_well_order ι (<)] variables {u : ι → Ω → β} {s : set β} {f : filtration ℕ m} lemma hitting_bot_le_iff {i n : ι} {ω : Ω} (hx : ∃ j, j ≤ n ∧ u j ω ∈ s) : hitting u s ⊥ n ω ≤ i ↔ ∃ j ≤ i, u j ω ∈ s := begin cases lt_or_le i n with hi hi, { rw hitting_le_iff_of_lt _ hi, simp, }, { simp only [(hitting_le ω).trans hi, true_iff], obtain ⟨j, hj₁, hj₂⟩ := hx, exact ⟨j, hj₁.trans hi, hj₂⟩, }, end end conditionally_complete_linear_order_bot end measure_theory
c476b369c0d37809a88b89d67b71e44289038ca9
06be757c84c5c318d56b5d07f1dff4eb19b949d8
/src/power_bounded.lean
c8759e9dd17eacf139a07e8bc1d3cc5b13f3195e
[ "Apache-2.0" ]
permissive
mr-infty/perfectoid-spaces
ea3e5d161072f6de646b660cc55217838d3ceded
1a49b3897ec3c7b871d8c970926c00f727a4e2a6
refs/heads/master
1,587,252,317,856
1,547,326,614,000
1,547,326,614,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,733
lean
import tactic.where import tactic.ring import analysis.topology.topological_space import analysis.topology.topological_structures import algebra.group_power import ring_theory.subring universe u variables {R : Type u} [comm_ring R] [topological_space R] [topological_ring R] /-- Wedhorn Definition 5.27 page 36 -/ definition is_bounded (B : set R) : Prop := ∀ U ∈ (nhds (0 : R)).sets, ∃ V ∈ (nhds (0 : R)).sets, ∀ v ∈ V, ∀ b ∈ B, v*b ∈ U definition is_power_bounded (r : R) : Prop := is_bounded (powers r) variable (R) definition power_bounded_subring := {r : R | is_power_bounded r} namespace power_bounded instance : has_coe (power_bounded_subring R) R := ⟨subtype.val⟩ lemma zero_mem : (0 : R) ∈ power_bounded_subring R := λ U hU, ⟨U, begin split, {exact hU}, intros v hv b H, cases H with n H, induction n ; { simp [H.symm, pow_succ, mem_of_nhds hU], try {assumption} } end⟩ lemma one_mem : (1 : R) ∈ power_bounded_subring R := λ U hU, ⟨U, begin split, {exact hU}, intros v hv b H, cases H with n H, simpa [H.symm] end⟩ lemma mul_mem : ∀ {a b : R}, a ∈ power_bounded_subring R → b ∈ power_bounded_subring R → a * b ∈ power_bounded_subring R := λ a b ha hb U U_nhd, begin rcases hb U U_nhd with ⟨Vb, ⟨Vb_nhd, hVb⟩⟩, rcases ha Vb Vb_nhd with ⟨Va, ⟨Va_nhd, hVa⟩⟩, clear ha hb, existsi Va, split, {exact Va_nhd}, { intros v hv x H, cases H with n hx, rw [← hx, mul_pow, ← mul_assoc], apply hVb (v * a^n) _ _ _, apply hVa v hv _ _, repeat { dsimp [powers], existsi n, refl } } end lemma neg_mem : ∀ {a : R}, a ∈ power_bounded_subring R → -a ∈ power_bounded_subring R := λ a ha U hU, begin let Usymm := U ∩ {u | -u ∈ U}, let hUsymm : Usymm ∈ (nhds (0 : R)).sets := begin apply filter.inter_mem_sets hU, apply continuous.tendsto (topological_add_group.continuous_neg R) 0, simpa end, rcases ha Usymm hUsymm with ⟨V, ⟨V_nhd, hV⟩⟩, clear hUsymm, existsi V, split, {exact V_nhd}, intros v hv b H, cases H with n hb, rw ← hb, rw show v * (-a)^n = ((-1)^n * v) * a^n, begin rw [neg_eq_neg_one_mul, mul_pow], ring, end, have H := hV v hv (a^n) _, suffices : (-1)^n * v * a^n ∈ Usymm, { exact this.1 }, { simp, cases (@neg_one_pow_eq_or R _ n) with h h; { dsimp [Usymm] at H, simp [h, H.1, H.2] } }, { dsimp [powers], existsi n, refl } end instance submonoid : is_submonoid (power_bounded_subring R) := { one_mem := power_bounded.one_mem R, mul_mem := λ a b, power_bounded.mul_mem R } definition is_uniform : Prop := is_bounded (power_bounded_subring R) end power_bounded
5d1c9e1571395ed78c6ab27856ef20b714c00439
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed_space/dual.lean
230af5dd29c23c381587ca7d4e03a97afa70a774
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
10,345
lean
/- Copyright (c) 2020 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.normed_space.hahn_banach.extension import analysis.normed_space.is_R_or_C import analysis.locally_convex.polar /-! # The topological dual of a normed space In this file we define the topological dual `normed_space.dual` of a normed space, and the continuous linear map `normed_space.inclusion_in_double_dual` from a normed space into its double dual. For base field `𝕜 = ℝ` or `𝕜 = ℂ`, this map is actually an isometric embedding; we provide a version `normed_space.inclusion_in_double_dual_li` of the map which is of type a bundled linear isometric embedding, `E →ₗᵢ[𝕜] (dual 𝕜 (dual 𝕜 E))`. Since a lot of elementary properties don't require `eq_of_dist_eq_zero` we start setting up the theory for `seminormed_add_comm_group` and we specialize to `normed_add_comm_group` when needed. ## Main definitions * `inclusion_in_double_dual` and `inclusion_in_double_dual_li` are the inclusion of a normed space in its double dual, considered as a bounded linear map and as a linear isometry, respectively. * `polar 𝕜 s` is the subset of `dual 𝕜 E` consisting of those functionals `x'` for which `‖x' z‖ ≤ 1` for every `z ∈ s`. ## Tags dual -/ noncomputable theory open_locale classical topological_space universes u v namespace normed_space section general variables (𝕜 : Type*) [nontrivially_normed_field 𝕜] variables (E : Type*) [seminormed_add_comm_group E] [normed_space 𝕜 E] variables (F : Type*) [normed_add_comm_group F] [normed_space 𝕜 F] /-- The topological dual of a seminormed space `E`. -/ @[derive [inhabited, seminormed_add_comm_group, normed_space 𝕜]] def dual := E →L[𝕜] 𝕜 instance : continuous_linear_map_class (dual 𝕜 E) 𝕜 E 𝕜 := continuous_linear_map.continuous_semilinear_map_class instance : has_coe_to_fun (dual 𝕜 E) (λ _, E → 𝕜) := continuous_linear_map.to_fun instance : normed_add_comm_group (dual 𝕜 F) := continuous_linear_map.to_normed_add_comm_group instance [finite_dimensional 𝕜 E] : finite_dimensional 𝕜 (dual 𝕜 E) := continuous_linear_map.finite_dimensional /-- The inclusion of a normed space in its double (topological) dual, considered as a bounded linear map. -/ def inclusion_in_double_dual : E →L[𝕜] (dual 𝕜 (dual 𝕜 E)) := continuous_linear_map.apply 𝕜 𝕜 @[simp] lemma dual_def (x : E) (f : dual 𝕜 E) : inclusion_in_double_dual 𝕜 E x f = f x := rfl lemma inclusion_in_double_dual_norm_eq : ‖inclusion_in_double_dual 𝕜 E‖ = ‖(continuous_linear_map.id 𝕜 (dual 𝕜 E))‖ := continuous_linear_map.op_norm_flip _ lemma inclusion_in_double_dual_norm_le : ‖inclusion_in_double_dual 𝕜 E‖ ≤ 1 := by { rw inclusion_in_double_dual_norm_eq, exact continuous_linear_map.norm_id_le } lemma double_dual_bound (x : E) : ‖(inclusion_in_double_dual 𝕜 E) x‖ ≤ ‖x‖ := by simpa using continuous_linear_map.le_of_op_norm_le _ (inclusion_in_double_dual_norm_le 𝕜 E) x /-- The dual pairing as a bilinear form. -/ def dual_pairing : (dual 𝕜 E) →ₗ[𝕜] E →ₗ[𝕜] 𝕜 := continuous_linear_map.coe_lm 𝕜 @[simp] lemma dual_pairing_apply {v : dual 𝕜 E} {x : E} : dual_pairing 𝕜 E v x = v x := rfl lemma dual_pairing_separating_left : (dual_pairing 𝕜 E).separating_left := begin rw [linear_map.separating_left_iff_ker_eq_bot, linear_map.ker_eq_bot], exact continuous_linear_map.coe_injective, end end general section bidual_isometry variables (𝕜 : Type v) [is_R_or_C 𝕜] {E : Type u} [normed_add_comm_group E] [normed_space 𝕜 E] /-- If one controls the norm of every `f x`, then one controls the norm of `x`. Compare `continuous_linear_map.op_norm_le_bound`. -/ lemma norm_le_dual_bound (x : E) {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ (f : dual 𝕜 E), ‖f x‖ ≤ M * ‖f‖) : ‖x‖ ≤ M := begin classical, by_cases h : x = 0, { simp only [h, hMp, norm_zero] }, { obtain ⟨f, hf₁, hfx⟩ : ∃ f : E →L[𝕜] 𝕜, ‖f‖ = 1 ∧ f x = ‖x‖ := exists_dual_vector 𝕜 x h, calc ‖x‖ = ‖(‖x‖ : 𝕜)‖ : is_R_or_C.norm_coe_norm.symm ... = ‖f x‖ : by rw hfx ... ≤ M * ‖f‖ : hM f ... = M : by rw [hf₁, mul_one] } end lemma eq_zero_of_forall_dual_eq_zero {x : E} (h : ∀ f : dual 𝕜 E, f x = (0 : 𝕜)) : x = 0 := norm_le_zero_iff.mp (norm_le_dual_bound 𝕜 x le_rfl (λ f, by simp [h f])) lemma eq_zero_iff_forall_dual_eq_zero (x : E) : x = 0 ↔ ∀ g : dual 𝕜 E, g x = 0 := ⟨λ hx, by simp [hx], λ h, eq_zero_of_forall_dual_eq_zero 𝕜 h⟩ /-- See also `geometric_hahn_banach_point_point`. -/ lemma eq_iff_forall_dual_eq {x y : E} : x = y ↔ ∀ g : dual 𝕜 E, g x = g y := begin rw [← sub_eq_zero, eq_zero_iff_forall_dual_eq_zero 𝕜 (x - y)], simp [sub_eq_zero], end /-- The inclusion of a normed space in its double dual is an isometry onto its image.-/ def inclusion_in_double_dual_li : E →ₗᵢ[𝕜] (dual 𝕜 (dual 𝕜 E)) := { norm_map' := begin intros x, apply le_antisymm, { exact double_dual_bound 𝕜 E x }, rw continuous_linear_map.norm_def, refine le_cInf continuous_linear_map.bounds_nonempty _, rintros c ⟨hc1, hc2⟩, exact norm_le_dual_bound 𝕜 x hc1 hc2 end, .. inclusion_in_double_dual 𝕜 E } end bidual_isometry section polar_sets open metric set normed_space /-- Given a subset `s` in a normed space `E` (over a field `𝕜`), the polar `polar 𝕜 s` is the subset of `dual 𝕜 E` consisting of those functionals which evaluate to something of norm at most one at all points `z ∈ s`. -/ def polar (𝕜 : Type*) [nontrivially_normed_field 𝕜] {E : Type*} [seminormed_add_comm_group E] [normed_space 𝕜 E] : set E → set (dual 𝕜 E) := (dual_pairing 𝕜 E).flip.polar variables (𝕜 : Type*) [nontrivially_normed_field 𝕜] variables {E : Type*} [seminormed_add_comm_group E] [normed_space 𝕜 E] lemma mem_polar_iff {x' : dual 𝕜 E} (s : set E) : x' ∈ polar 𝕜 s ↔ ∀ z ∈ s, ‖x' z‖ ≤ 1 := iff.rfl @[simp] lemma polar_univ : polar 𝕜 (univ : set E) = {(0 : dual 𝕜 E)} := (dual_pairing 𝕜 E).flip.polar_univ (linear_map.flip_separating_right.mpr (dual_pairing_separating_left 𝕜 E)) lemma is_closed_polar (s : set E) : is_closed (polar 𝕜 s) := begin dunfold normed_space.polar, simp only [linear_map.polar_eq_Inter, linear_map.flip_apply], refine is_closed_bInter (λ z hz, _), exact is_closed_Iic.preimage (continuous_linear_map.apply 𝕜 𝕜 z).continuous.norm end @[simp] lemma polar_closure (s : set E) : polar 𝕜 (closure s) = polar 𝕜 s := ((dual_pairing 𝕜 E).flip.polar_antitone subset_closure).antisymm $ (dual_pairing 𝕜 E).flip.polar_gc.l_le $ closure_minimal ((dual_pairing 𝕜 E).flip.polar_gc.le_u_l s) $ by simpa [linear_map.flip_flip] using (is_closed_polar _ _).preimage (inclusion_in_double_dual 𝕜 E).continuous variables {𝕜} /-- If `x'` is a dual element such that the norms `‖x' z‖` are bounded for `z ∈ s`, then a small scalar multiple of `x'` is in `polar 𝕜 s`. -/ lemma smul_mem_polar {s : set E} {x' : dual 𝕜 E} {c : 𝕜} (hc : ∀ z, z ∈ s → ‖ x' z ‖ ≤ ‖c‖) : c⁻¹ • x' ∈ polar 𝕜 s := begin by_cases c_zero : c = 0, { simp only [c_zero, inv_zero, zero_smul], exact (dual_pairing 𝕜 E).flip.zero_mem_polar _ }, have eq : ∀ z, ‖ c⁻¹ • (x' z) ‖ = ‖ c⁻¹ ‖ * ‖ x' z ‖ := λ z, norm_smul c⁻¹ _, have le : ∀ z, z ∈ s → ‖ c⁻¹ • (x' z) ‖ ≤ ‖ c⁻¹ ‖ * ‖ c ‖, { intros z hzs, rw eq z, apply mul_le_mul (le_of_eq rfl) (hc z hzs) (norm_nonneg _) (norm_nonneg _), }, have cancel : ‖ c⁻¹ ‖ * ‖ c ‖ = 1, by simp only [c_zero, norm_eq_zero, ne.def, not_false_iff, inv_mul_cancel, norm_inv], rwa cancel at le, end lemma polar_ball_subset_closed_ball_div {c : 𝕜} (hc : 1 < ‖c‖) {r : ℝ} (hr : 0 < r) : polar 𝕜 (ball (0 : E) r) ⊆ closed_ball (0 : dual 𝕜 E) (‖c‖ / r) := begin intros x' hx', rw mem_polar_iff at hx', simp only [polar, mem_set_of_eq, mem_closed_ball_zero_iff, mem_ball_zero_iff] at *, have hcr : 0 < ‖c‖ / r, from div_pos (zero_lt_one.trans hc) hr, refine continuous_linear_map.op_norm_le_of_shell hr hcr.le hc (λ x h₁ h₂, _), calc ‖x' x‖ ≤ 1 : hx' _ h₂ ... ≤ (‖c‖ / r) * ‖x‖ : (inv_pos_le_iff_one_le_mul' hcr).1 (by rwa inv_div) end variables (𝕜) lemma closed_ball_inv_subset_polar_closed_ball {r : ℝ} : closed_ball (0 : dual 𝕜 E) r⁻¹ ⊆ polar 𝕜 (closed_ball (0 : E) r) := λ x' hx' x hx, calc ‖x' x‖ ≤ ‖x'‖ * ‖x‖ : x'.le_op_norm x ... ≤ r⁻¹ * r : mul_le_mul (mem_closed_ball_zero_iff.1 hx') (mem_closed_ball_zero_iff.1 hx) (norm_nonneg _) (dist_nonneg.trans hx') ... = r / r : inv_mul_eq_div _ _ ... ≤ 1 : div_self_le_one r /-- The `polar` of closed ball in a normed space `E` is the closed ball of the dual with inverse radius. -/ lemma polar_closed_ball {𝕜 E : Type*} [is_R_or_C 𝕜] [normed_add_comm_group E] [normed_space 𝕜 E] {r : ℝ} (hr : 0 < r) : polar 𝕜 (closed_ball (0 : E) r) = closed_ball (0 : dual 𝕜 E) r⁻¹ := begin refine subset.antisymm _ (closed_ball_inv_subset_polar_closed_ball _), intros x' h, simp only [mem_closed_ball_zero_iff], refine continuous_linear_map.op_norm_le_of_ball hr (inv_nonneg.mpr hr.le) (λ z hz, _), simpa only [one_div] using linear_map.bound_of_ball_bound' hr 1 x'.to_linear_map h z end /-- Given a neighborhood `s` of the origin in a normed space `E`, the dual norms of all elements of the polar `polar 𝕜 s` are bounded by a constant. -/ lemma bounded_polar_of_mem_nhds_zero {s : set E} (s_nhd : s ∈ 𝓝 (0 : E)) : bounded (polar 𝕜 s) := begin obtain ⟨a, ha⟩ : ∃ a : 𝕜, 1 < ‖a‖ := normed_field.exists_one_lt_norm 𝕜, obtain ⟨r, r_pos, r_ball⟩ : ∃ (r : ℝ) (hr : 0 < r), ball 0 r ⊆ s := metric.mem_nhds_iff.1 s_nhd, exact bounded_closed_ball.mono (((dual_pairing 𝕜 E).flip.polar_antitone r_ball).trans $ polar_ball_subset_closed_ball_div ha r_pos) end end polar_sets end normed_space
5680f0f53990c2d97f55ddc6e32f6ebf93a3ad4c
c3f2fcd060adfa2ca29f924839d2d925e8f2c685
/hott/init/reserved_notation.hlean
a8f96c8f53615101ce6d33fd1d3a5ed2ebda284a
[ "Apache-2.0" ]
permissive
respu/lean
6582d19a2f2838a28ecd2b3c6f81c32d07b5341d
8c76419c60b63d0d9f7bc04ebb0b99812d0ec654
refs/heads/master
1,610,882,451,231
1,427,747,084,000
1,427,747,429,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,422
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: init.reserved_notation Authors: Leonardo de Moura -/ prelude import init.datatypes notation `assume` binders `,` r:(scoped f, f) := r notation `take` binders `,` r:(scoped f, f) := r /- Global declarations of right binding strength If a module reassigns these, it will be incompatible with other modules that adhere to these conventions. When hovering over a symbol, use "C-u C-x =" to see how to input it. -/ /- Logical operations and relations -/ definition std.prec.max : num := 1024 -- the strength of application, identifiers, (, [, etc. definition std.prec.arrow : num := 25 /- The next definition is "max + 10". It can be used e.g. for postfix operations that should be stronger than application. -/ definition std.prec.max_plus := num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ (num.succ std.prec.max))))))))) /- Logical operations and relations -/ reserve prefix `¬`:40 reserve prefix `~`:40 reserve infixr `∧`:35 reserve infixr `/\`:35 reserve infixr `\/`:30 reserve infixr `∨`:30 reserve infix `<->`:25 reserve infix `↔`:25 reserve infix `=`:50 reserve infix `≠`:50 reserve infix `≈`:50 reserve infix `∼`:50 reserve infixr `∘`:60 -- input with \comp reserve postfix `⁻¹`:std.prec.max_plus -- input with \sy or \-1 or \inv reserve infixl `⬝`:75 reserve infixr `▸`:75 /- types and type constructors -/ reserve infixr `⊎`:25 reserve infixr `×`:30 /- arithmetic operations -/ reserve infixl `+`:65 reserve infixl `-`:65 reserve infixl `*`:70 reserve infixl `div`:70 reserve infixl `mod`:70 reserve infixl `/`:70 reserve prefix `-`:100 reserve infix `<=`:50 reserve infix `≤`:50 reserve infix `<`:50 reserve infix `>=`:50 reserve infix `≥`:50 reserve infix `>`:50 /- boolean operations -/ reserve infixl `&&`:70 reserve infixl `||`:65 /- set operations -/ reserve infix `∈`:50 reserve infix `∉`:50 reserve infixl `∩`:70 reserve infixl `∪`:65 /- other symbols -/ reserve notation `(` a `|` b `)` reserve infixl `++`:65 reserve infixr `::`:65 -- Yet another trick to anotate an expression with a type definition is_typeof (A : Type) (a : A) : A := a notation `typeof` t `:` T := is_typeof T t notation `(` t `:` T `)` := is_typeof T t
5b0404cb17e8e91f36c35465eb2708674c58ae81
367134ba5a65885e863bdc4507601606690974c1
/src/linear_algebra/direct_sum/finsupp.lean
8b56ab8ffee8123b8dbecb098d53234ccc1a5573
[ "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
3,270
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 -/ import linear_algebra.finsupp import linear_algebra.direct_sum.tensor_product /-! # Results on direct sums and finitely supported functions. 1. The linear equivalence between finitely supported functions `ι →₀ M` and the direct sum of copies of `M` indexed by `ι`. 2. The tensor product of ι →₀ M and κ →₀ N is linearly equivalent to (ι × κ) →₀ (M ⊗ N). -/ universes u v w noncomputable theory open_locale classical direct_sum open set linear_map submodule variables {R : Type u} {M : Type v} {N : Type w} [ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] section finsupp_lequiv_direct_sum variables (R M) (ι : Type*) [decidable_eq ι] /-- The finitely supported functions ι →₀ M are in linear equivalence with the direct sum of copies of M indexed by ι. -/ def finsupp_lequiv_direct_sum : (ι →₀ M) ≃ₗ[R] ⨁ i : ι, M := linear_equiv.of_linear (finsupp.lsum ℕ (show ι → (M →ₗ[R] ⨁ i, M), from direct_sum.lof R ι _)) (direct_sum.to_module _ _ _ finsupp.lsingle) (linear_map.ext $ direct_sum.to_module.ext _ $ λ i, linear_map.ext $ λ x, by simp [finsupp.sum_single_index]) (linear_map.ext $ λ f, finsupp.ext $ λ i, by simp [finsupp.lsum_apply]) @[simp] theorem finsupp_lequiv_direct_sum_single (i : ι) (m : M) : finsupp_lequiv_direct_sum R M ι (finsupp.single i m) = direct_sum.lof R ι _ i m := finsupp.sum_single_index $ linear_map.map_zero _ @[simp] theorem finsupp_lequiv_direct_sum_symm_lof (i : ι) (m : M) : (finsupp_lequiv_direct_sum R M ι).symm (direct_sum.lof R ι _ i m) = finsupp.single i m := direct_sum.to_module_lof _ _ _ end finsupp_lequiv_direct_sum section tensor_product open_locale tensor_product /-- The tensor product of ι →₀ M and κ →₀ N is linearly equivalent to (ι × κ) →₀ (M ⊗ N). -/ def finsupp_tensor_finsupp (R M N ι κ : Sort*) [comm_ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] : (ι →₀ M) ⊗[R] (κ →₀ N) ≃ₗ[R] (ι × κ) →₀ (M ⊗[R] N) := linear_equiv.trans (tensor_product.congr (finsupp_lequiv_direct_sum R M ι) (finsupp_lequiv_direct_sum R N κ)) $ linear_equiv.trans (tensor_product.direct_sum R ι κ (λ _, M) (λ _, N)) (finsupp_lequiv_direct_sum R (M ⊗[R] N) (ι × κ)).symm @[simp] theorem finsupp_tensor_finsupp_single (R M N ι κ : Sort*) [comm_ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] (i : ι) (m : M) (k : κ) (n : N) : finsupp_tensor_finsupp R M N ι κ (finsupp.single i m ⊗ₜ finsupp.single k n) = finsupp.single (i, k) (m ⊗ₜ n) := by simp [finsupp_tensor_finsupp] @[simp] theorem finsupp_tensor_finsupp_symm_single (R M N ι κ : Sort*) [comm_ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] (i : ι × κ) (m : M) (n : N) : (finsupp_tensor_finsupp R M N ι κ).symm (finsupp.single i (m ⊗ₜ n)) = (finsupp.single i.1 m ⊗ₜ finsupp.single i.2 n) := prod.cases_on i $ λ i k, (linear_equiv.symm_apply_eq _).2 (finsupp_tensor_finsupp_single _ _ _ _ _ _ _ _ _).symm end tensor_product
8e2fccd7ef0e482769ff88938cc1aa11cdf75f1a
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/category/Twop.lean
249180e4dfe7e472fa3a35c011ff448be3cfc227
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
5,111
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import category_theory.category.Bipointed import data.two_pointing /-! # The category of two-pointed types This defines `Twop`, the category of two-pointed types. ## References * [nLab, *coalgebra of the real interval*] (https://ncatlab.org/nlab/show/coalgebra+of+the+real+interval) -/ open category_theory option universes u variables {α β : Type*} /-- The category of two-pointed types. -/ structure Twop : Type.{u+1} := (X : Type.{u}) (to_two_pointing : two_pointing X) namespace Twop instance : has_coe_to_sort Twop Type* := ⟨X⟩ attribute [protected] Twop.X /-- Turns a two-pointing into a two-pointed type. -/ def of {X : Type*} (to_two_pointing : two_pointing X) : Twop := ⟨X, to_two_pointing⟩ @[simp] lemma coe_of {X : Type*} (to_two_pointing : two_pointing X) : ↥(of to_two_pointing) = X := rfl alias of ← two_pointing.Twop instance : inhabited Twop := ⟨of two_pointing.bool⟩ /-- Turns a two-pointed type into a bipointed type, by forgetting that the pointed elements are distinct. -/ def to_Bipointed (X : Twop) : Bipointed := X.to_two_pointing.to_prod.Bipointed @[simp] lemma coe_to_Bipointed (X : Twop) : ↥X.to_Bipointed = ↥X := rfl instance large_category : large_category Twop := induced_category.category to_Bipointed instance concrete_category : concrete_category Twop := induced_category.concrete_category to_Bipointed instance has_forget_to_Bipointed : has_forget₂ Twop Bipointed := induced_category.has_forget₂ to_Bipointed /-- Swaps the pointed elements of a two-pointed type. `two_pointing.swap` as a functor. -/ @[simps] def swap : Twop ⥤ Twop := { obj := λ X, ⟨X, X.to_two_pointing.swap⟩, map := λ X Y f, ⟨f.to_fun, f.map_snd, f.map_fst⟩ } /-- The equivalence between `Twop` and itself induced by `prod.swap` both ways. -/ @[simps] def swap_equiv : Twop ≌ Twop := equivalence.mk swap swap (nat_iso.of_components (λ X, { hom := ⟨id, rfl, rfl⟩, inv := ⟨id, rfl, rfl⟩ }) $ λ X Y f, rfl) (nat_iso.of_components (λ X, { hom := ⟨id, rfl, rfl⟩, inv := ⟨id, rfl, rfl⟩ }) $ λ X Y f, rfl) @[simp] lemma swap_equiv_symm : swap_equiv.symm = swap_equiv := rfl end Twop @[simp] lemma Twop_swap_comp_forget_to_Bipointed : Twop.swap ⋙ forget₂ Twop Bipointed = forget₂ Twop Bipointed ⋙ Bipointed.swap := rfl /-- The functor from `Pointed` to `Twop` which adds a second point. -/ @[simps] def Pointed_to_Twop_fst : Pointed.{u} ⥤ Twop := { obj := λ X, ⟨option X, ⟨X.point, none⟩, some_ne_none _⟩, map := λ X Y f, ⟨option.map f.to_fun, congr_arg _ f.map_point, rfl⟩, map_id' := λ X, Bipointed.hom.ext _ _ option.map_id, map_comp' := λ X Y Z f g, Bipointed.hom.ext _ _ (option.map_comp_map _ _).symm } /-- The functor from `Pointed` to `Twop` which adds a first point. -/ @[simps] def Pointed_to_Twop_snd : Pointed.{u} ⥤ Twop := { obj := λ X, ⟨option X, ⟨none, X.point⟩, (some_ne_none _).symm⟩, map := λ X Y f, ⟨option.map f.to_fun, rfl, congr_arg _ f.map_point⟩, map_id' := λ X, Bipointed.hom.ext _ _ option.map_id, map_comp' := λ X Y Z f g, Bipointed.hom.ext _ _ (option.map_comp_map _ _).symm } @[simp] lemma Pointed_to_Twop_fst_comp_swap : Pointed_to_Twop_fst ⋙ Twop.swap = Pointed_to_Twop_snd := rfl @[simp] lemma Pointed_to_Twop_snd_comp_swap : Pointed_to_Twop_snd ⋙ Twop.swap = Pointed_to_Twop_fst := rfl @[simp] lemma Pointed_to_Twop_fst_comp_forget_to_Bipointed : Pointed_to_Twop_fst ⋙ forget₂ Twop Bipointed = Pointed_to_Bipointed_fst := rfl @[simp] lemma Pointed_to_Twop_snd_comp_forget_to_Bipointed : Pointed_to_Twop_snd ⋙ forget₂ Twop Bipointed = Pointed_to_Bipointed_snd := rfl /-- Adding a second point is left adjoint to forgetting the second point. -/ def Pointed_to_Twop_fst_forget_comp_Bipointed_to_Pointed_fst_adjunction : Pointed_to_Twop_fst ⊣ forget₂ Twop Bipointed ⋙ Bipointed_to_Pointed_fst := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, ⟨f.to_fun ∘ option.some, f.map_fst⟩, inv_fun := λ f, ⟨λ o, o.elim Y.to_two_pointing.to_prod.2 f.to_fun, f.map_point, rfl⟩, left_inv := λ f, by { ext, cases x, exact f.map_snd.symm, refl }, right_inv := λ f, Pointed.hom.ext _ _ rfl }, hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext, cases x; refl } } /-- Adding a first point is left adjoint to forgetting the first point. -/ def Pointed_to_Twop_snd_forget_comp_Bipointed_to_Pointed_snd_adjunction : Pointed_to_Twop_snd ⊣ forget₂ Twop Bipointed ⋙ Bipointed_to_Pointed_snd := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, ⟨f.to_fun ∘ option.some, f.map_snd⟩, inv_fun := λ f, ⟨λ o, o.elim Y.to_two_pointing.to_prod.1 f.to_fun, rfl, f.map_point⟩, left_inv := λ f, by { ext, cases x, exact f.map_fst.symm, refl }, right_inv := λ f, Pointed.hom.ext _ _ rfl }, hom_equiv_naturality_left_symm' := λ X' X Y f g, by { ext, cases x; refl } }
2a2a1749fde2d807f6c63f1f6760caf20d2caef4
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/category/Module/products.lean
e5cd44f09bb19d14b66b25521b6744514c35ed08
[ "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
1,951
lean
/- Copyright (c) 2022 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.category.Module.epi_mono import linear_algebra.pi /-! # The concrete products in the category of modules are products in the categorical sense. -/ open category_theory open category_theory.limits universes u v w namespace Module variables {R : Type u} [ring R] variables {ι : Type v} (Z : ι → Module.{max v w} R) /-- The product cone induced by the concrete product. -/ def product_cone : fan Z := fan.mk (Module.of R (Π i : ι, Z i)) (λ i, (linear_map.proj i : (Π i : ι, Z i) →ₗ[R] Z i)) /-- The concrete product cone is limiting. -/ def product_cone_is_limit : is_limit (product_cone Z) := { lift := λ s, (linear_map.pi (λ j, s.π.app ⟨j⟩) : s.X →ₗ[R] (Π i : ι, Z i)), fac' := λ s j, by { cases j, tidy, }, uniq' := λ s m w, by { ext x i, exact linear_map.congr_fun (w ⟨i⟩) x, }, } -- While we could use this to construct a `has_products (Module R)` instance, -- we already have `has_limits (Module R)` in `algebra.category.Module.limits`. variables [has_product Z] /-- The categorical product of a family of objects in `Module` agrees with the usual module-theoretical product. -/ noncomputable def pi_iso_pi : ∏ Z ≅ Module.of R (Π i, Z i) := limit.iso_limit_cone ⟨_, product_cone_is_limit Z⟩ -- We now show this isomorphism commutes with the inclusion of the kernel into the source. @[simp, elementwise] lemma pi_iso_pi_inv_kernel_ι (i : ι) : (pi_iso_pi Z).inv ≫ pi.π Z i = (linear_map.proj i : (Π i : ι, Z i) →ₗ[R] Z i) := limit.iso_limit_cone_inv_π _ _ @[simp, elementwise] lemma pi_iso_pi_hom_ker_subtype (i : ι) : (pi_iso_pi Z).hom ≫ (linear_map.proj i : (Π i : ι, Z i) →ₗ[R] Z i) = pi.π Z i := is_limit.cone_point_unique_up_to_iso_inv_comp _ (limit.is_limit _) (discrete.mk i) end Module
9dfa73fea6cab051cc4b86491d595b7990aa7a54
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/meta/simp_tactic.lean
11fd452097ab6026368708c42135d23b5d67e9d1
[ "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
18,558
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.tactic init.meta.attribute init.meta.constructor_tactic import init.meta.relation_tactics init.meta.occurrences import init.data.option.instances open tactic meta constant simp_lemmas : Type meta constant simp_lemmas.mk : simp_lemmas meta constant simp_lemmas.join : simp_lemmas → simp_lemmas → simp_lemmas meta constant simp_lemmas.erase : simp_lemmas → list name → simp_lemmas meta constant simp_lemmas.mk_default_core : transparency → tactic simp_lemmas meta constant simp_lemmas.add_core : transparency → simp_lemmas → expr → tactic simp_lemmas meta constant simp_lemmas.add_simp_core : transparency → simp_lemmas → name → tactic simp_lemmas meta constant simp_lemmas.add_congr_core : transparency → simp_lemmas → name → tactic simp_lemmas meta def simp_lemmas.mk_default : tactic simp_lemmas := simp_lemmas.mk_default_core reducible meta def simp_lemmas.add : simp_lemmas → expr → tactic simp_lemmas := simp_lemmas.add_core reducible meta def simp_lemmas.add_simp : simp_lemmas → name → tactic simp_lemmas := simp_lemmas.add_simp_core reducible meta def simp_lemmas.add_congr : simp_lemmas → name → tactic simp_lemmas := simp_lemmas.add_congr_core reducible meta def simp_lemmas.append : simp_lemmas → list expr → tactic simp_lemmas | sls [] := return sls | sls (l::ls) := do new_sls ← simp_lemmas.add sls l, simp_lemmas.append new_sls ls /- (simp_lemmas.rewrite_core m s prove R e) apply a simplification lemma from 's' - 'prove' is used to discharge proof obligations. - 'R' is the equivalence relation being used (e.g., 'eq', 'iff') - 'e' is the expression to be "simplified" Result (new_e, pr) is the new expression 'new_e' and a proof (pr : e R new_e) -/ meta constant simp_lemmas.rewrite_core : transparency → simp_lemmas → tactic unit → name → expr → tactic (expr × expr) meta def simp_lemmas.rewrite : simp_lemmas → tactic unit → name → expr → tactic (expr × expr) := simp_lemmas.rewrite_core reducible /- (simp_lemmas.drewrite s e) tries to rewrite 'e' using only refl lemmas in 's' -/ meta constant simp_lemmas.drewrite_core : transparency → simp_lemmas → expr → tactic expr meta def simp_lemmas.drewrite : simp_lemmas → expr → tactic expr := simp_lemmas.drewrite_core reducible /- (Definitional) Simplify the given expression using *only* reflexivity equality lemmas from the given set of lemmas. The resulting expression is definitionally equal to the input. -/ meta constant simp_lemmas.dsimplify_core (max_steps : nat) (visit_instances : bool) : simp_lemmas → expr → tactic expr meta constant is_valid_simp_lemma_cnst : transparency → name → tactic bool meta constant is_valid_simp_lemma : transparency → expr → tactic bool def default_max_steps := 10000000 meta def simp_lemmas.dsimplify : simp_lemmas → expr → tactic expr := simp_lemmas.dsimplify_core default_max_steps ff meta constant simp_lemmas.pp : simp_lemmas → tactic format namespace tactic /- (get_eqn_lemmas_for deps d) returns the automatically generated equational lemmas for definition d. If deps is tt, then lemmas for automatically generated auxiliary declarations used to define d are also included. -/ meta constant get_eqn_lemmas_for : bool → name → tactic (list name) meta constant dsimplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) (max_steps : nat) /- If visit_instances = ff, then instance implicit arguments are not visited, but tactic will canonize them. -/ (visit_instances : bool) /- (pre a e) is invoked before visiting the children of subterm 'e', if it succeeds the result (new_a, new_e, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression that must be definitionally equal to 'e', - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → expr → tactic (α × expr × bool)) /- (post a e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → expr → tactic (α × expr × bool)) : expr → tactic (α × expr) meta def dsimplify (pre : expr → tactic (expr × bool)) (post : expr → tactic (expr × bool)) : expr → tactic expr := λ e, do (a, new_e) ← dsimplify_core () default_max_steps ff (λ u e, do r ← pre e, return (u, r)) (λ u e, do r ← post e, return (u, r)) e, return new_e meta constant dunfold_expr_core : transparency → expr → tactic expr /- Remark: we use transparency.instances by default to make sure that we can unfold projections of type classes. Example: dunfold_expr (@has_add.add nat nat.has_add a b) -/ meta def dunfold_expr : expr → tactic expr := dunfold_expr_core transparency.instances meta constant unfold_projection_core : transparency → expr → tactic expr meta def unfold_projection : expr → tactic expr := unfold_projection_core transparency.instances meta constant dunfold_occs_core (m : transparency) (max_steps : nat) (occs : occurrences) (cs : list name) (e : expr) : tactic expr meta constant dunfold_core (m : transparency) (max_steps : nat) (cs : list name) (e : expr) : tactic expr meta def dunfold : list name → tactic unit := λ cs, target >>= dunfold_core transparency.instances default_max_steps cs >>= unsafe_change meta def dunfold_occs_of (occs : list nat) (c : name) : tactic unit := target >>= dunfold_occs_core transparency.instances default_max_steps (occurrences.pos occs) [c] >>= unsafe_change meta def dunfold_core_at (occs : occurrences) (cs : list name) (h : expr) : tactic unit := do num_reverted ← revert h, (expr.pi n bi d b : expr) ← target, new_d ← dunfold_occs_core transparency.instances default_max_steps occs cs d, unsafe_change $ expr.pi n bi new_d b, intron num_reverted meta def dunfold_at (cs : list name) (h : expr) : tactic unit := do num_reverted ← revert h, (expr.pi n bi d b : expr) ← target, new_d ← dunfold_core transparency.instances default_max_steps cs d, unsafe_change $ expr.pi n bi new_d b, intron num_reverted structure delta_config := (max_steps := default_max_steps) (visit_instances := tt) private meta def is_delta_target (e : expr) (cs : list name) : bool := cs.any (λ c, if e.is_app_of c then tt /- Exact match -/ else let f := e.get_app_fn in /- f is an auxiliary constant generated when compiling c -/ f.is_constant && f.const_name.is_internal && (f.const_name.get_prefix = c)) /- Delta reduce the given constant names -/ meta def delta_core (cfg : delta_config) (cs : list name) (e : expr) : tactic expr := let unfold (u : unit) (e : expr) : tactic (unit × expr × bool) := do guard (is_delta_target e cs), (expr.const f_name f_lvls) ← return e.get_app_fn, env ← get_env, decl ← env.get f_name, new_f ← decl.instantiate_value_univ_params f_lvls, new_e ← head_beta (expr.mk_app new_f e.get_app_args), return (u, new_e, tt) in do (c, new_e) ← dsimplify_core () cfg.max_steps cfg.visit_instances (λ c e, failed) unfold e, return new_e meta def delta (cs : list name) : tactic unit := target >>= delta_core {} cs >>= unsafe_change meta def delta_at (cs : list name) (h : expr) : tactic unit := do num_reverted ← revert h, (expr.pi n bi d b : expr) ← target, new_d ← delta_core {} cs d, unsafe_change $ expr.pi n bi new_d b, intron num_reverted structure simp_config := (max_steps : nat := default_max_steps) (contextual : bool := ff) (lift_eq : bool := tt) (canonize_instances : bool := tt) (canonize_proofs : bool := ff) (use_axioms : bool := tt) (zeta : bool := tt) (beta : bool := tt) (eta : bool := tt) (proj : bool := tt) -- reduce projections meta constant simplify_core (c : simp_config) (s : simp_lemmas) (r : name) : expr → tactic (expr × expr) meta constant ext_simplify_core /- The user state type. -/ {α : Type} /- Initial user data -/ (a : α) (c : simp_config) /- Congruence and simplification lemmas. Remark: the simplification lemmas at not applied automatically like in the simplify_core tactic. the caller must use them at pre/post. -/ (s : simp_lemmas) /- Tactic for dischaging hypothesis in conditional rewriting rules. The argument 'α' is the current user state. -/ (prove : α → tactic α) /- (pre a S r s p e) is invoked before visiting the children of subterm 'e', 'r' is the simplification relation being used, 's' is the updated set of lemmas if 'contextual' is tt, 'p' is the "parent" expression (if there is one). if it succeeds the result is (new_a, new_e, new_pr, flag) where - 'new_a' is the new value for the user data - 'new_e' is a new expression s.t. 'e r new_e' - 'new_pr' is a proof for 'e r new_e', If it is none, the proof is assumed to be by reflexivity - 'flag' if tt 'new_e' children should be visited, and 'post' invoked. -/ (pre : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- (post a r s p e) is invoked after visiting the children of subterm 'e', The output is similar to (pre a r s p e), but the 'flag' indicates whether the new expression should be revisited or not. -/ (post : α → simp_lemmas → name → option expr → expr → tactic (α × expr × option expr × bool)) /- simplification relation -/ (r : name) : expr → tactic (α × expr × expr) meta def simplify (S : simp_lemmas) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := do e_type ← infer_type e >>= whnf, simplify_core cfg S `eq e meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, eq_type ← mk_app `eq [t, new_target], locked_pr ← return $ expr.app (expr.app (expr.const ``id_locked [level.zero]) eq_type) pr, mk_eq_mpr locked_pr ht >>= exact meta def simplify_goal (S : simp_lemmas) (cfg : simp_config := {}) : tactic unit := do t ← target, (new_t, pr) ← simplify S t cfg, replace_target new_t pr meta def simp (cfg : simp_config := {}) : tactic unit := do S ← simp_lemmas.mk_default, simplify_goal S cfg >> try triv >> try (reflexivity reducible) meta def simp_using (hs : list expr) (cfg : simp_config := {}) : tactic unit := do S ← simp_lemmas.mk_default, S ← S.append hs, simplify_goal S cfg >> try triv meta def dsimp_core (s : simp_lemmas) : tactic unit := target >>= s.dsimplify >>= unsafe_change meta def dsimp : tactic unit := simp_lemmas.mk_default >>= dsimp_core meta def dsimp_at_core (s : simp_lemmas) (h : expr) : tactic unit := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, h_simp ← s.dsimplify d, unsafe_change $ expr.pi n bi h_simp b, intron num_reverted meta def dsimp_at (h : expr) : tactic unit := do s ← simp_lemmas.mk_default, dsimp_at_core s h private meta def is_equation : expr → bool | (expr.pi n bi d b) := is_equation b | e := match (expr.is_eq e) with (some a) := tt | none := ff end private meta def collect_simps : list expr → tactic (list expr) | [] := return [] | (h :: hs) := do result ← collect_simps hs, htype ← infer_type h >>= whnf, if is_equation htype then return (h :: result) else do pr ← is_prop htype, return $ if pr then (h :: result) else result meta def collect_ctx_simps : tactic (list expr) := local_context >>= collect_simps /-- Simplify target using all hypotheses in the local context. -/ meta def simp_using_hs (cfg : simp_config := {}) : tactic unit := do es ← collect_ctx_simps, simp_using es cfg meta def simph (cfg : simp_config := {}) := simp_using_hs cfg meta def intro1_aux : bool → list name → tactic expr | ff _ := intro1 | tt (n::ns) := intro n | _ _ := failed meta def simp_intro_aux (cfg : simp_config) (updt : bool) : simp_lemmas → bool → list name → tactic simp_lemmas | S tt [] := try (simplify_goal S cfg) >> return S | S use_ns ns := do t ← target, if t.is_napp_of `not 1 then intro1_aux use_ns ns >> simp_intro_aux S use_ns ns.tail else if t.is_arrow then do { d ← return t.binding_domain, (new_d, h_d_eq_new_d) ← simplify S d cfg, h_d ← intro1_aux use_ns ns, h_new_d ← mk_eq_mp h_d_eq_new_d h_d, assertv_core h_d.local_pp_name new_d h_new_d, clear h_d, h_new ← intro1, new_S ← if updt && is_equation new_d then S.add h_new else return S, simp_intro_aux new_S use_ns ns.tail } <|> -- failed to simplify... we just introduce and continue (intro1_aux use_ns ns >> simp_intro_aux S use_ns ns.tail) else if t.is_pi || t.is_let then intro1_aux use_ns ns >> simp_intro_aux S use_ns ns.tail else do new_t ← whnf t reducible, if new_t.is_pi then unsafe_change new_t >> simp_intro_aux S use_ns ns else try (simplify_goal S cfg) >> mcond (expr.is_pi <$> target) (simp_intro_aux S use_ns ns) (if use_ns ∧ ¬ns.empty then failed else return S) meta def simp_intros_using (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ simp_intro_aux cfg ff s ff [] meta def simph_intros_using (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ do s ← collect_ctx_simps >>= s.append, simp_intro_aux cfg tt s ff [] meta def simp_intro_lst_using (ns : list name) (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ simp_intro_aux cfg ff s tt ns meta def simph_intro_lst_using (ns : list name) (s : simp_lemmas) (cfg : simp_config := {}) : tactic unit := step $ do s ← collect_ctx_simps >>= s.append, simp_intro_aux cfg tt s tt ns meta def replace_hyp (h : expr) (h_new_type : expr) (pr : expr) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name h_new_type, mk_eq_mp pr h >>= exact, try $ clear h, return new_h meta def simp_at (h : expr) (extra_lemmas : list expr := []) (cfg : simp_config := {}) : tactic expr := do when (expr.is_local_constant h = ff) (fail "tactic simp_at failed, the given expression is not a hypothesis"), htype ← infer_type h, S ← simp_lemmas.mk_default, S ← S.append extra_lemmas, (h_new_type, pr) ← simplify S htype cfg, replace_hyp h h_new_type pr meta def simp_at_using_hs (h : expr) (extra_lemmas : list expr := []) (cfg : simp_config := {}) : tactic expr := do hs ← collect_ctx_simps, simp_at h (list.filter (≠ h) hs ++ extra_lemmas) cfg meta def simph_at (h : expr) (extra_lemmas : list expr := []) (cfg : simp_config := {}) : tactic expr := simp_at_using_hs h extra_lemmas cfg meta def mk_eq_simp_ext (simp_ext : expr → tactic (expr × expr)) : tactic unit := do (lhs, rhs) ← target >>= match_eq, (new_rhs, heq) ← simp_ext lhs, unify rhs new_rhs, exact heq /- Simp attribute support -/ meta def to_simp_lemmas : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (n::ns) := do S' ← S.add_simp n, to_simp_lemmas S' ns meta def mk_simp_attr (attr_name : name) : command := do let t := `(caching_user_attribute simp_lemmas), let v := `({name := attr_name, descr := "simplifier attribute", mk_cache := λ ns, do {tactic.to_simp_lemmas simp_lemmas.mk ns}, dependencies := [`reducibility] } : caching_user_attribute simp_lemmas), add_decl (declaration.defn attr_name [] t v reducibility_hints.abbrev ff), attribute.register attr_name meta def get_user_simp_lemmas (attr_name : name) : tactic simp_lemmas := if attr_name = `default then simp_lemmas.mk_default else do cnst ← return (expr.const attr_name []), attr ← eval_expr (caching_user_attribute simp_lemmas) cnst, caching_user_attribute.get_cache attr meta def join_user_simp_lemmas_core : simp_lemmas → list name → tactic simp_lemmas | S [] := return S | S (attr_name::R) := do S' ← get_user_simp_lemmas attr_name, join_user_simp_lemmas_core (S.join S') R meta def join_user_simp_lemmas (no_dflt : bool) (attrs : list name) : tactic simp_lemmas := if no_dflt then join_user_simp_lemmas_core simp_lemmas.mk attrs else do s ← simp_lemmas.mk_default, join_user_simp_lemmas_core s attrs /- Normalize numerical expression, returns a pair (n, pr) where n is the resultant numeral, and pr is a proof that the input argument is equal to n. -/ meta constant norm_num : expr → tactic (expr × expr) meta def simplify_top_down {α} (a : α) (pre : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← pre a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) (λ _ _ _ _ _, failed) `eq e meta def simp_top_down (pre : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_top_down () (λ _ e, do (new_e, pr) ← pre e, return ((), new_e, pr)) t cfg, replace_target new_target pr meta def simplify_bottom_up {α} (a : α) (post : α → expr → tactic (α × expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (α × expr × expr) := ext_simplify_core a cfg simp_lemmas.mk (λ _, failed) (λ _ _ _ _ _, failed) (λ a _ _ _ e, do (new_a, new_e, pr) ← post a e, guard (¬ new_e =ₐ e), return (new_a, new_e, some pr, tt)) `eq e meta def simp_bottom_up (post : expr → tactic (expr × expr)) (cfg : simp_config := {}) : tactic unit := do t ← target, (_, new_target, pr) ← simplify_bottom_up () (λ _ e, do (new_e, pr) ← post e, return ((), new_e, pr)) t cfg, replace_target new_target pr /- debugging support for algebraic normalizer -/ meta constant trace_algebra_info : expr → tactic unit end tactic export tactic (mk_simp_attr)
6f35030b17e90a3b1f86e308417f9a260b724dcb
4727251e0cd73359b15b664c3170e5d754078599
/src/topology/uniform_space/uniform_convergence_topology.lean
cdcad276b1c9432118680f7a8f8a6caaddf96ecf
[ "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
10,481
lean
/- Copyright (c) 2022 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anatole Dedecker -/ import topology.uniform_space.uniform_convergence import topology.uniform_space.pi /-! # Topology and uniform structure of uniform convergence This files endows `α → β` with the topologies / uniform structures of - uniform convergence on `α` (in the `uniform_convergence` namespace) - uniform convergence on a specified family `𝔖` of sets of `α` (in the `uniform_convergence_on` namespace), also called `𝔖`-convergence Usual examples of the second construction include : - the topology of compact convergence, when `𝔖` is the set of compacts of `α` - the strong topology on the dual of a TVS `E`, when `𝔖` is the set of Von Neuman bounded subsets of `E` - the weak-* topology on the dual of a TVS `E`, when `𝔖` is the set of singletons of `E`. ## Main definitions * `uniform_convergence.gen` : basis sets for the uniformity of uniform convergence * `uniform_convergence.uniform_space` : uniform structure of uniform convergence * `uniform_convergence_on.uniform_space` : uniform structure of 𝔖-convergence ## Main statements * `uniform_convergence.uniform_continuous_eval` : evaluation is uniformly continuous * `uniform_convergence.t2_space` : the topology of uniform convergence on `α → β` is T2 if `β` is T2. * `uniform_convergence.tendsto_iff_tendsto_uniformly` : `uniform_convergence.uniform_space` is indeed the uniform structure of uniform convergence * `uniform_convergence_on.uniform_continuous_eval_of_mem` : evaluation at a point contained in a set of `𝔖` is uniformly continuous * `uniform_convergence.t2_space` : the topology of `𝔖`-convergence on `α → β` is T2 if `β` is T2 and `𝔖` covers `α` * `uniform_convergence_on.tendsto_iff_tendsto_uniformly_on` : `uniform_convergence_on.uniform_space` is indeed the uniform structure of `𝔖`-convergence ## Implementation details We do not declare these structures as instances, since they would conflict with `Pi.uniform_space`. ## TODO * Show that the uniform structure of `𝔖`-convergence is exactly the structure of `𝔖'`-convergence, where `𝔖'` is the bornology generated by `𝔖`. * Add a type synonym for `α → β` endowed with the structures of uniform convergence ## References * [N. Bourbaki, *General Topology*][bourbaki1966] ## Tags uniform convergence -/ noncomputable theory open_locale topological_space classical uniformity filter local attribute [-instance] Pi.uniform_space open set filter namespace uniform_convergence variables (α β : Type*) {γ ι : Type*} variables {F : ι → α → β} {f : α → β} {s s' : set α} {x : α} {p : filter ι} {g : ι → α} /-- Basis sets for the uniformity of uniform convergence -/ protected def gen (V : set (β × β)) : set ((α → β) × (α → β)) := {uv : (α → β) × (α → β) | ∀ x, (uv.1 x, uv.2 x) ∈ V} variables [uniform_space β] protected lemma is_basis_gen : is_basis (λ V : set (β × β), V ∈ 𝓤 β) (uniform_convergence.gen α β) := ⟨⟨univ, univ_mem⟩, λ U V hU hV, ⟨U ∩ V, inter_mem hU hV, λ uv huv, ⟨λ x, (huv x).left, λ x, (huv x).right⟩⟩⟩ /-- Filter basis for the uniformity of uniform convergence -/ protected def uniformity_basis : filter_basis ((α → β) × (α → β)) := (uniform_convergence.is_basis_gen α β).filter_basis /-- Core of the uniform structure of uniform convergence -/ protected def uniform_core : uniform_space.core (α → β) := uniform_space.core.mk_of_basis (uniform_convergence.uniformity_basis α β) (λ U ⟨V, hV, hVU⟩ f, hVU ▸ λ x, refl_mem_uniformity hV) (λ U ⟨V, hV, hVU⟩, hVU ▸ ⟨uniform_convergence.gen α β (prod.swap ⁻¹' V), ⟨prod.swap ⁻¹' V, tendsto_swap_uniformity hV, rfl⟩, λ uv huv x, huv x⟩) (λ U ⟨V, hV, hVU⟩, hVU ▸ let ⟨W, hW, hWV⟩ := comp_mem_uniformity_sets hV in ⟨uniform_convergence.gen α β W, ⟨W, hW, rfl⟩, λ uv ⟨w, huw, hwv⟩ x, hWV ⟨w x, by exact ⟨huw x, hwv x⟩⟩⟩) /-- Uniform structure of uniform convergence -/ protected def uniform_space : uniform_space (α → β) := uniform_space.of_core (uniform_convergence.uniform_core α β) protected lemma has_basis_uniformity : (@uniformity (α → β) (uniform_convergence.uniform_space α β)).has_basis (λ V, V ∈ 𝓤 β) (uniform_convergence.gen α β) := (uniform_convergence.is_basis_gen α β).has_basis /-- Topology of uniform convergence -/ protected def topological_space : topological_space (α → β) := (uniform_convergence.uniform_space α β).to_topological_space protected lemma has_basis_nhds : (@nhds (α → β) (uniform_convergence.topological_space α β) f).has_basis (λ V, V ∈ 𝓤 β) (λ V, {g | (g, f) ∈ uniform_convergence.gen α β V}) := begin letI : uniform_space (α → β) := uniform_convergence.uniform_space α β, exact nhds_basis_uniformity (uniform_convergence.has_basis_uniformity α β) end variables {α} lemma uniform_continuous_eval (x : α) : @uniform_continuous _ _ (uniform_convergence.uniform_space α β) _ (function.eval x) := begin change _ ≤ _, rw [map_le_iff_le_comap, (uniform_convergence.has_basis_uniformity α β).le_basis_iff ((𝓤 _).basis_sets.comap _)], exact λ U hU, ⟨U, hU, λ uv huv, huv x⟩ end variables {β} lemma t2_space [t2_space β] : @t2_space _ (uniform_convergence.topological_space α β) := { t2 := begin letI : uniform_space (α → β) := uniform_convergence.uniform_space α β, letI : topological_space (α → β) := uniform_convergence.topological_space α β, intros f g h, obtain ⟨x, hx⟩ := not_forall.mp (mt funext h), exact separated_by_continuous (uniform_continuous_eval β x).continuous hx end } protected lemma le_Pi : uniform_convergence.uniform_space α β ≤ Pi.uniform_space (λ _, β) := begin rw [le_iff_uniform_continuous_id, uniform_continuous_pi], intros x, exact uniform_continuous_eval β x end protected lemma tendsto_iff_tendsto_uniformly : tendsto F p (@nhds _ (uniform_convergence.topological_space α β) f) ↔ tendsto_uniformly F f p := begin letI : uniform_space (α → β) := uniform_convergence.uniform_space α β, rw [(uniform_convergence.has_basis_nhds α β).tendsto_right_iff, tendsto_uniformly], split; { intros h U hU, filter_upwards [h (prod.swap ⁻¹' U) (tendsto_swap_uniformity hU)], exact λ n, id } end variable {α} end uniform_convergence namespace uniform_convergence_on variables (α β : Type*) {γ ι : Type*} [uniform_space β] (𝔖 : set (set α)) variables {F : ι → α → β} {f : α → β} {s s' : set α} {x : α} {p : filter ι} {g : ι → α} /-- Uniform structure of uniform convergence on the sets of `𝔖`. -/ protected def uniform_space : uniform_space (α → β) := ⨅ (s : set α) (hs : s ∈ 𝔖), uniform_space.comap (λ f, s.restrict f) (uniform_convergence.uniform_space s β) /-- Topology of uniform convergence on the sets of `𝔖`. -/ protected def topological_space : topological_space (α → β) := (uniform_convergence_on.uniform_space α β 𝔖).to_topological_space protected lemma topological_space_eq : uniform_convergence_on.topological_space α β 𝔖 = ⨅ (s : set α) (hs : s ∈ 𝔖), topological_space.induced (λ f, s.restrict f) (uniform_convergence.topological_space s β) := begin simp only [uniform_convergence_on.topological_space, to_topological_space_infi, to_topological_space_infi, to_topological_space_comap], refl end protected lemma uniform_continuous_restrict (h : s ∈ 𝔖) : @uniform_continuous _ _ (uniform_convergence_on.uniform_space α β 𝔖) (uniform_convergence.uniform_space s β) s.restrict := begin change _ ≤ _, rw [uniform_convergence_on.uniform_space, map_le_iff_le_comap, uniformity, infi_uniformity], refine infi_le_of_le s _, rw infi_uniformity, exact infi_le _ h, end protected lemma uniform_space_antitone : antitone (uniform_convergence_on.uniform_space α β) := λ 𝔖₁ 𝔖₂ h₁₂, infi_le_infi_of_subset h₁₂ variables {α} lemma uniform_continuous_eval_of_mem {x : α} (hxs : x ∈ s) (hs : s ∈ 𝔖) : @uniform_continuous _ _ (uniform_convergence_on.uniform_space α β 𝔖) _ (function.eval x) := begin change _ ≤ _, rw [map_le_iff_le_comap, ((𝓤 _).basis_sets.comap _).ge_iff, uniform_convergence_on.uniform_space, infi_uniformity'], intros U hU, refine mem_infi_of_mem s _, rw infi_uniformity', exact mem_infi_of_mem hs (mem_comap.mpr ⟨ uniform_convergence.gen s β U, (uniform_convergence.has_basis_uniformity s β).mem_of_mem hU, λ uv huv, huv ⟨x, hxs⟩ ⟩) end variables {β} lemma t2_space_of_covering [t2_space β] (h : ⋃₀ 𝔖 = univ) : @t2_space _ (uniform_convergence_on.topological_space α β 𝔖) := { t2 := begin letI : uniform_space (α → β) := uniform_convergence_on.uniform_space α β 𝔖, letI : topological_space (α → β) := uniform_convergence_on.topological_space α β 𝔖, intros f g hfg, obtain ⟨x, hx⟩ := not_forall.mp (mt funext hfg), obtain ⟨s, hs, hxs⟩ : ∃ s ∈ 𝔖, x ∈ s := mem_sUnion.mp (h.symm ▸ true.intro), exact separated_by_continuous (uniform_continuous_eval_of_mem β 𝔖 hxs hs).continuous hx end } protected lemma le_Pi_of_covering (h : ⋃₀ 𝔖 = univ) : uniform_convergence_on.uniform_space α β 𝔖 ≤ Pi.uniform_space (λ _, β) := begin rw [le_iff_uniform_continuous_id, uniform_continuous_pi], intros x, obtain ⟨s, hs, hxs⟩ : ∃ s ∈ 𝔖, x ∈ s := mem_sUnion.mp (h.symm ▸ true.intro), exact uniform_continuous_eval_of_mem β 𝔖 hxs hs end protected lemma tendsto_iff_tendsto_uniformly_on : tendsto F p (@nhds _ (uniform_convergence_on.topological_space α β 𝔖) f) ↔ ∀ s ∈ 𝔖, tendsto_uniformly_on F f p s := begin letI : uniform_space (α → β) := uniform_convergence_on.uniform_space α β 𝔖, rw [uniform_convergence_on.topological_space_eq, nhds_infi, tendsto_infi], refine forall_congr (λ s, _), rw [nhds_infi, tendsto_infi], refine forall_congr (λ hs, _), rw [nhds_induced, tendsto_comap_iff, tendsto_uniformly_on_iff_tendsto_uniformly_comp_coe, uniform_convergence.tendsto_iff_tendsto_uniformly], refl end end uniform_convergence_on
156773a5c71033c0067715249e8d20d58a79cecf
b561a44b48979a98df50ade0789a21c79ee31288
/src/Lean/Widget/InteractiveCode.lean
b7dcd15660daea7b7901ca9cae142252886d1176
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,910
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Wojciech Nawrocki -/ import Lean.PrettyPrinter import Lean.Server.Rpc.Basic import Lean.Widget.TaggedText /-! RPC infrastructure for storing and formatting code fragments, in particular `Expr`s, with environment and subexpression information. -/ namespace Lean.Widget open Server -- TODO: Some of the `WithBlah` types exist mostly because we cannot derive multi-argument RPC wrappers. -- They will be gone eventually. structure InfoWithCtx where ctx : Elab.ContextInfo info : Elab.Info deriving Inhabited, RpcEncoding with { withRef := true } structure CodeToken where info : WithRpcRef InfoWithCtx -- TODO(WN): add fields for semantic highlighting -- kind : Lsp.SymbolKind deriving Inhabited, RpcEncoding /-- Pretty-printed syntax (usually but not necessarily an `Expr`) with embedded `Info`s. -/ abbrev CodeWithInfos := TaggedText CodeToken def CodeWithInfos.pretty (tt : CodeWithInfos) := tt.stripTags open Expr in /-- Find a subexpression of `e` using the pretty-printer address scheme. -/ -- NOTE(WN): not currently in use partial def traverse (e : Expr) (addr : Nat) : MetaM (LocalContext × Expr):= do let e ← Meta.instantiateMVars e go (tritsLE [] addr |>.drop 1) (← getLCtx) e where tritsLE (acc : List Nat) (n : Nat) : List Nat := if n == 0 then acc else tritsLE (n % 3 :: acc) (n / 3) go (addr : List Nat) (lctx : LocalContext) (e : Expr) : MetaM (LocalContext × Expr) := do match addr with | [] => (lctx, e) | a::as => do let go' (e' : Expr) := do go as (← getLCtx) e' let eExpr ← match a, e with | 0, app e₁ e₂ _ => go' e₁ | 1, app e₁ e₂ _ => go' e₂ | 0, lam _ e₁ e₂ _ => go' e₁ | 1, lam n e₁ e₂ data => Meta.withLocalDecl n data.binderInfo e₁ fun fvar => go' (e₂.instantiate1 fvar) | 0, forallE _ e₁ e₂ _ => go' e₁ | 1, forallE n e₁ e₂ data => Meta.withLocalDecl n data.binderInfo e₁ fun fvar => go' (e₂.instantiate1 fvar) | 0, letE _ e₁ e₂ e₃ _ => go' e₁ | 1, letE _ e₁ e₂ e₃ _ => go' e₂ | 2, letE n e₁ e₂ e₃ _ => Meta.withLetDecl n e₁ e₂ fun fvar => do go' (e₃.instantiate1 fvar) | 0, mdata _ e₁ _ => go' e₁ | 0, proj _ _ e₁ _ => go' e₁ | _, _ => (lctx, e) -- panic! s!"cannot descend {a} into {e.expr}" -- TODO(WN): should the two fns below go in `Lean.PrettyPrinter` ? open PrettyPrinter in private def formatWithOpts (e : Expr) (optsPerPos : Delaborator.OptionsPerPos) : MetaM (Format × Std.RBMap Nat Elab.Info compare) := do let currNamespace ← getCurrNamespace let openDecls ← getOpenDecls let opts ← getOptions let e ← Meta.instantiateMVars e let (stx, infos) ← PrettyPrinter.delabCore currNamespace openDecls e optsPerPos let stx := sanitizeSyntax stx |>.run' { options := opts } let stx ← PrettyPrinter.parenthesizeTerm stx let fmt ← PrettyPrinter.formatTerm stx return (fmt, infos) /-- Pretty-print the expression and its subexpression information. -/ def formatInfos (e : Expr) : MetaM (Format × Std.RBMap Nat Elab.Info compare) := formatWithOpts e {} /-- Like `formatInfos` but with `pp.all` set at the top-level expression. -/ def formatExplicitInfos (e : Expr) : MetaM (Format × Std.RBMap Nat Elab.Info compare) := let optsPerPos := Std.RBMap.ofList [(1, KVMap.empty.setBool `pp.all true)] formatWithOpts e optsPerPos /-- Tags a pretty-printed `Expr` with infos from the delaborator. -/ partial def tagExprInfos (ctx : Elab.ContextInfo) (infos : Std.RBMap Nat Elab.Info compare) (tt : TaggedText (Nat × Nat)) : CodeWithInfos := go tt where go (tt : TaggedText (Nat × Nat)) := tt.rewrite fun (n, _) subTt => match infos.find? n with | none => go subTt | some i => TaggedText.tag ⟨WithRpcRef.mk { ctx, info := i }⟩ (go subTt) def exprToInteractive (e : Expr) : MetaM CodeWithInfos := do let (fmt, infos) ← formatInfos e let tt := TaggedText.prettyTagged fmt let ctx := { env := ← getEnv mctx := ← getMCtx options := ← getOptions currNamespace := ← getCurrNamespace openDecls := ← getOpenDecls fileMap := arbitrary } tagExprInfos ctx infos tt def exprToInteractiveExplicit (e : Expr) : MetaM CodeWithInfos := do let (fmt, infos) ← formatExplicitInfos e let tt := TaggedText.prettyTagged fmt let ctx := { env := ← getEnv mctx := ← getMCtx options := ← getOptions currNamespace := ← getCurrNamespace openDecls := ← getOpenDecls fileMap := arbitrary } tagExprInfos ctx infos tt end Lean.Widget
e5d4b24e1de474cf71f03db7caf4c8069dbaca03
8930e38ac0fae2e5e55c28d0577a8e44e2639a6d
/linear_algebra/basic.lean
e0bdb3b5fe39a0b32b7a985e766b2c4bf14d3397
[ "Apache-2.0" ]
permissive
SG4316/mathlib
3d64035d02a97f8556ad9ff249a81a0a51a3321a
a7846022507b531a8ab53b8af8a91953fceafd3a
refs/heads/master
1,584,869,960,527
1,530,718,645,000
1,530,724,110,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
37,217
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Linear algebra -- classical This file is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. We define the following concepts: * `lc α β`: linear combinations over `β` (`α` is the scalar ring) * `span s`: the submodule generated by `s` * `linear_independent s`: states that `s` are linear independent * `linear_independent.repr s b`: choose the linear combination representing `b` on the linear independent vectors `s`. `b` should be in `span b` (uses classical choice) * `is_basis s`: if `s` is a basis, i.e. linear independent and spans the entire space * `is_basis.repr s b`: like `linear_independent.repr` but as a `linear_map` * `is_basis.constr s g`: constructs a `linear_map` by extending `g` from the basis `s` -/ import algebra algebra.big_operators order.zorn data.finset data.finsupp noncomputable theory open classical set function lattice local attribute [instance] prop_decidable reserve infix `≃ₗ` : 50 universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type y} {ι : Type x} @[simp] lemma set.diff_self {s : set α} : s \ s = ∅ := set.ext $ by simp lemma zero_ne_one_or_forall_eq_0 (α : Type u) [ring α] : (0 : α) ≠ 1 ∨ (∀a:α, a = 0) := not_or_of_imp $ λ h a, by simpa using congr_arg ((*) a) h.symm namespace finset lemma smul_sum [ring γ] [module γ β] {s : finset α} {a : γ} {f : α → β} : a • (s.sum f) = s.sum (λc, a • f c) := (finset.sum_hom ((•) a) (@smul_zero γ β _ _ a) (assume _ _, smul_add)).symm end finset namespace finsupp lemma smul_sum [has_zero β] [ring γ] [module γ δ] {v : α →₀ β} {c : γ} {h : α → β → δ} : c • (v.sum h) = v.sum (λa b, c • h a b) := finset.smul_sum end finsupp /-- The type of linear coefficients, which are simply the finitely supported functions from the module `β` to the scalar ring `α`. -/ @[reducible] def lc (α : Type u) (β : Type v) [ring α] [module α β] : Type (max u v) := β →₀ α namespace lc variables [ring α] [module α β] instance : has_scalar α (lc α β) := finsupp.to_has_scalar instance : module α (lc α β) := finsupp.to_module lemma is_linear_map_sum [module α γ] [module α δ] {f : β → α → γ} {g : δ → lc α β} (hf : ∀b, is_linear_map (f b)) (hg : is_linear_map g) : is_linear_map (λd, (g d).sum f) := ⟨assume d₁ d₂, by simp [hg.add, finsupp.sum_add_index, (hf _).zero, (hf _).add], assume a d, by simp [hg.smul, finsupp.sum_smul_index, (hf _).zero, finsupp.smul_sum, ((hf _).smul _ _).symm]⟩ end lc namespace is_linear_map @[simp] lemma finsupp_sum [ring α] [module α β] [module α γ] [has_zero δ] {f : β → γ} {t : ι →₀ δ} {g : ι → δ → β} (hf : is_linear_map f) : f (t.sum g) = t.sum (λi d, f (g i d)) := hf.sum end is_linear_map structure linear_equiv {α : Type u} [ring α] (β : Type v) (γ : Type w) [module α β] [module α γ] extends equiv β γ := (linear_fun : is_linear_map to_fun) infix ` ≃ₗ ` := linear_equiv namespace linear_equiv variables [ring α] [module α β] [module α γ] [module α δ] include α lemma linear_inv (e : β ≃ₗ γ) : is_linear_map e.inv_fun := e.linear_fun.inverse e.left_inv e.right_inv section variable (β) def refl : β ≃ₗ β := { linear_fun := is_linear_map.id, .. equiv.refl β } end def symm (e : β ≃ₗ γ) : γ ≃ₗ β := { linear_fun := e.linear_inv, .. e.to_equiv.symm } def trans (e₁ : β ≃ₗ γ) (e₂ : γ ≃ₗ δ) : β ≃ₗ δ := { linear_fun := is_linear_map.comp e₂.linear_fun e₁.linear_fun, .. e₁.to_equiv.trans e₂.to_equiv } end linear_equiv section module variables [ring α] [module α β] [module α γ] [module α δ] variables {a a' : α} {s t : set β} {b b' b₁ b₂ : β} include α /-- Linear span of a set of vectors -/ def span (s : set β) : set β := { x | ∃(v : lc α β), (∀x∉s, v x = 0) ∧ x = v.sum (λb a, a • b) } instance is_submodule_span : is_submodule (span s) := { zero_ := ⟨0, by simp [finsupp.sum_zero_index]⟩, add_ := assume x y ⟨vx, hx, eqx⟩ ⟨vy, hy, eqy⟩, ⟨vx + vy, by simp [hx, hy, eqx, eqy, finsupp.sum_add_index, add_smul] {contextual := tt}⟩, smul := assume a b ⟨v, hv, veq⟩, ⟨a • v, by simp [hv, veq, finsupp.sum_smul_index, finsupp.smul_sum, smul_smul] {contextual := tt}⟩ } lemma subset_span : s ⊆ span s := assume b (hb : b ∈ s), have ∀b'∉s, b ≠ b', by intros b' hb' ne; cc, ⟨finsupp.single b 1, by simp [finsupp.sum_single_index, this] {contextual := tt}⟩ lemma span_eq_of_is_submodule (hs : is_submodule s) : span s = s := have span s ⊆ s, from assume b ⟨v, hv, eq⟩, have ∀c, v c • c ∈ s, from assume c, is_submodule.smul_ne_0 $ not_imp_comm.mp $ hv c, eq.symm ▸ is_submodule.sum (by simp [this] {contextual := tt}), subset.antisymm this subset_span lemma span_mono (h : t ⊆ s) : span t ⊆ span s := assume b ⟨v, hv, eq⟩, ⟨v, assume b, hv b ∘ mt (@h b), eq⟩ lemma span_minimal (hs : is_submodule s) (h : t ⊆ s) : span t ⊆ s := calc span t ⊆ span s : span_mono h ... = s : span_eq_of_is_submodule hs lemma span_eq (hs : is_submodule s) (hts : t ⊆ s) (hst : s ⊆ span t) : span t = s := subset.antisymm (span_minimal hs hts) hst @[simp] lemma span_empty : span (∅ : set β) = {0} := span_eq is_submodule.single_zero (empty_subset _) (by simp [subset_def, is_submodule.zero]) lemma is_submodule_range_smul : is_submodule $ range (λa, a • b) := is_submodule.range $ is_linear_map.map_smul_left is_linear_map.id lemma span_singleton : span {b} = range (λa, a • b) := span_eq is_submodule_range_smul (assume b' hb', ⟨1, by simp * at *⟩) (assume b' ⟨a, eq⟩, eq ▸ is_submodule.smul _ $ subset_span $ mem_singleton _) lemma span_union : span (s ∪ t) = {z | ∃x∈span s, ∃y∈span t, z = x + y } := span_eq is_submodule.add_submodule (union_subset (assume x hx, ⟨x, subset_span hx, 0, is_submodule.zero, by simp⟩) (assume y hy, ⟨0, is_submodule.zero, y, subset_span hy, by simp⟩)) (assume b ⟨x, hx, y, hy, eq⟩, eq.symm ▸ is_submodule.add (span_mono (subset_union_left _ _) hx) (span_mono (subset_union_right _ _) hy)) lemma span_insert_eq_span (h : b ∈ span s) : span (insert b s) = span s := span_eq is_submodule_span (set.insert_subset.mpr ⟨h, subset_span⟩) (span_mono $ subset_insert _ _) lemma span_insert : span (insert b s) = {z | ∃a, ∃x∈span s, z = a • b + x } := set.ext $ assume b', begin apply iff.intro; simp [insert_eq, span_union, span_singleton, set.set_eq_def, range, -add_comm], exact (assume y a eq_y x hx eq, ⟨a, x, hx, by simp [eq_y, eq]⟩), exact (assume a b₂ hb₂ eq, ⟨a • b, ⟨a, rfl⟩, b₂, hb₂, eq⟩) end lemma mem_span_insert : b₁ ∈ span (insert b s) ↔ ∃a, b₁ + a • b ∈ span s := begin simp [span_insert], constructor, exact assume ⟨a, b, hb, eq⟩, ⟨-a, by simp [eq, hb]⟩, exact assume ⟨a, hb⟩, ⟨-a, _, hb, by simp⟩ end @[simp] lemma span_span : span (span s) = span s := span_eq_of_is_submodule is_submodule_span @[simp] lemma span_image_of_linear_map {f : β → γ} (hf : is_linear_map f) : span (f '' s) = f '' span s := subset.antisymm (span_minimal (is_submodule.image hf) (image_subset _ subset_span)) (image_subset_iff.mpr $ span_minimal (is_submodule.preimage hf) (image_subset_iff.mp subset_span)) lemma linear_eq_on {f g : β → γ} (hf : is_linear_map f) (hg : is_linear_map g) (h : ∀x∈s, f x = g x) : ∀{x}, x ∈ span s → f x = g x | _ ⟨l, hl, rfl⟩ := begin simp [hf.finsupp_sum, hg.finsupp_sum], apply finset.sum_congr rfl, assume b hb, have : b ∈ s, { by_contradiction, simp * at * }, simp [this, h, hf.smul, hg.smul] end /-- Linearly independent set of vectors -/ def linear_independent (s : set β) : Prop := ∀l : lc α β, (∀x∉s, l x = 0) → l.sum (λv c, c • v) = 0 → l = 0 lemma linear_independent_empty : linear_independent (∅ : set β) := assume l hl eq, finsupp.ext $ by simp * at * lemma linear_independent.mono (hs : linear_independent s) (h : t ⊆ s) : linear_independent t := assume l hl eq, hs l (assume b, hl b ∘ mt (@h b)) eq lemma zero_not_mem_of_linear_independent (ne : 0 ≠ (1:α)) (hs : linear_independent s) : (0:β) ∉ s := assume (h : 0 ∈ s), let l : lc α β := finsupp.single 0 1 in have l = 0, from hs l (by intro x; by_cases 0 = x; simp [l, finsupp.single_apply, *] at *) (by simp [finsupp.sum_single_index]), have l 0 = 1, from finsupp.single_eq_same, by rw [‹l = 0›] at this; simp * at * lemma linear_independent_union {s t : set β} (hs : linear_independent s) (ht : linear_independent t) (hst : span s ∩ span t = {0}) : linear_independent (s ∪ t) := (zero_ne_one_or_forall_eq_0 α).elim (assume ne l hl eq0, let ls := l.filter $ λb, b ∈ s, lt := l.filter $ λb, b ∈ t in have hls : ↑ls.support ⊆ s, by simp [ls, subset_def], have hlt : ↑lt.support ⊆ t, by simp [ls, subset_def], have lt.sum (λb a, a • b) ∈ span t, from is_submodule.sum $ assume b hb, is_submodule.smul _ $ subset_span $ hlt hb, have l = ls + lt, from have ∀b, b ∈ s → b ∉ t, from assume b hbs hbt, have b ∈ span s ∩ span t, from ⟨subset_span hbs, subset_span hbt⟩, have b = 0, by rw [hst] at this; simp * at *, zero_not_mem_of_linear_independent ne hs $ this ▸ hbs, have lt = l.filter (λb, b ∉ s), from finsupp.ext $ assume b, by by_cases b ∈ t; by_cases b ∈ s; simp * at *, by rw [this]; exact finsupp.filter_pos_add_filter_neg.symm, have ls.sum (λb a, a • b) + lt.sum (λb a, a • b) = l.sum (λb a, a • b), by rw [this, finsupp.sum_add_index]; simp [add_smul], have ls_eq_neg_lt : ls.sum (λb a, a • b) = - lt.sum (λb a, a • b), from eq_of_sub_eq_zero $ by simp [this, eq0], have ls_sum_eq : ls.sum (λb a, a • b) = 0, from have - lt.sum (λb a, a • b) ∈ span t, from is_submodule.neg $ is_submodule.sum $ assume b hb, is_submodule.smul _ $ subset_span $ hlt hb, have ls.sum (λb a, a • b) ∈ span s ∩ span t, from ⟨is_submodule.sum $ assume b hb, is_submodule.smul _ $ subset_span $ hls hb, ls_eq_neg_lt.symm ▸ this⟩, by rw [hst] at this; simp * at *, have ls = 0, from hs _ (finsupp.support_subset_iff.mp hls) ls_sum_eq, have lt_sum_eq : lt.sum (λb a, a • b) = 0, from eq_of_neg_eq_neg $ by rw [←ls_eq_neg_lt, ls_sum_eq]; simp, have lt = 0, from ht _ (finsupp.support_subset_iff.mp hlt) lt_sum_eq, by simp [‹l = ls + lt›, ‹ls = 0›, ‹lt = 0›]) (assume eq_0 l _ _, finsupp.ext $ assume b, eq_0 _) lemma linear_independent_Union_of_directed {s : set (set β)} (hs : ∀a∈s, ∀b∈s, ∃c∈s, a ∪ b ⊆ c) (h : ∀a∈s, linear_independent a) : linear_independent (⋃₀s) := assume l hl eq, have ∀f:finset β, {x | x ∈ f} ⊆ ⋃₀ s → f = ∅ ∨ (∃t∈s, {x | x ∈ f} ⊆ t), from assume f, finset.induction_on f (by simp) $ assume a f haf ih haf_s, let ⟨t, ht, hat⟩ := haf_s $ finset.mem_insert_self _ _ in have f = ∅ ∨ ∃ (t : set β) (H : t ∈ s), {x : β | x ∈ f} ⊆ t, from ih $ assume x hx, haf_s $ finset.mem_insert_of_mem hx, or.inr $ this.elim (assume : f = ∅, ⟨t, ht, by simp [this, hat, subset_def]⟩) (assume ⟨t', ht', hft⟩, let ⟨t'', ht''s, ht''⟩ := hs t ht t' ht' in have a ∈ t'', from ht'' $ or.inl hat, have ∀x, x ∈ f → x ∈ t'', from subset.trans (subset.trans hft $ subset_union_right _ _) ht'', ⟨t'', ht''s, by simp [subset_def, or_imp_distrib, *] {contextual := tt}⟩), have l.support = ∅ ∨ (∃t∈s, {x | x ∈ l.support} ⊆ t), from this _ $ by intros x hx; by_contradiction; simp * at *, this.elim (assume : l.support = ∅, by simp [finset.ext] at this; exact finsupp.ext this) (assume ⟨t, ht, hts⟩, have ∀x, l x ≠ 0 → x ∈ t, by simpa using hts, h t ht l (assume x, not_imp_comm.mp $ this x) eq) lemma linear_independent_bUnion_of_directed {ι : Type w} {i : set ι} {s : ι → set β} (hs : ∀a∈i, ∀b∈i, ∃c∈i, s a ∪ s b ⊆ s c) (h : ∀a∈i, linear_independent (s a)) : linear_independent (⋃a∈i, s a) := have linear_independent (⋃₀ (s '' i)), from linear_independent_Union_of_directed (assume a ⟨j, hj, a_eq⟩ b ⟨l, hl, b_eq⟩, let ⟨k, hk, h⟩ := hs j hj l hl in ⟨s k, mem_image_of_mem _ hk, a_eq ▸ b_eq ▸ h⟩) (assume a ⟨j, hj, a_eq⟩, a_eq ▸ h j hj), by rwa [sUnion_image] at this lemma linear_independent.unique (hs : linear_independent s) {l₁ l₂ : lc α β} (h₁ : ∀x∉s, l₁ x = 0) (h₂ : ∀x∉s, l₂ x = 0) (eq : l₁.sum (λv c, c • v) = l₂.sum (λv c, c • v)) : l₁ = l₂ := eq_of_sub_eq_zero $ show l₁ - l₂ = 0, from hs (l₁ - l₂) (by simp [h₁, h₂] {contextual:=tt}) (by simp [finsupp.sum_sub_index, eq, sub_smul, -sub_eq_add_neg, sub_self]) section repr variables (hs : linear_independent s) def linear_independent.repr (hs : linear_independent s) (b : β) : lc α β := if h : b ∈ span s then classical.some h else 0 lemma repr_not_span (h : b ∉ span s) : hs.repr b = 0 := dif_neg h lemma repr_spec (h : b ∈ span s) : (∀b'∉s, hs.repr b b' = 0) ∧ b = (hs.repr b).sum (λb a, a • b) := have hs.repr b = classical.some h, from dif_pos h, by rw [this]; exact classical.some_spec h lemma repr_eq_zero (hb' : b' ∉ s) : hs.repr b b' = 0 := by_cases (assume : b ∈ span s, (repr_spec hs this).left _ hb') (assume : b ∉ span s, by rw [repr_not_span hs this]; refl) lemma repr_sum_eq (hb : b ∈ span s) : (hs.repr b).sum (λb a, a • b) = b := (repr_spec hs hb).right.symm lemma repr_eq {l : lc α β} (hb : b ∈ span s) (h : ∀x∉s, l x = 0) (eq : l.sum (λv c, c • v) = b) : hs.repr b = l := hs.unique (assume b, repr_eq_zero hs) h (by rw [repr_sum_eq hs hb, eq]) lemma repr_eq_single (hb : b ∈ s) : hs.repr b = finsupp.single b 1 := repr_eq hs (subset_span hb) (assume b' hb', finsupp.single_eq_of_ne $ show b ≠ b', from assume eq, by simp * at *) (by simp [finsupp.sum_single_index, add_smul]) @[simp] lemma repr_zero : hs.repr 0 = 0 := repr_eq hs is_submodule.zero (by simp) (by simp [finsupp.sum_zero_index]) lemma repr_support : ↑(hs.repr b).support ⊆ s := assume x hx, classical.by_contradiction $ assume hxs, by simp at hx; exact hx (repr_eq_zero hs hxs) @[simp] lemma repr_add (hb : b ∈ span s) (hb' : b' ∈ span s) : hs.repr (b + b') = hs.repr b + hs.repr b' := repr_eq hs (is_submodule.add hb hb') (by simp [repr_eq_zero] {contextual := tt}) (by simp [finsupp.sum_add_index, add_smul, repr_sum_eq hs, hb, hb']) @[simp] lemma repr_smul (hb : b ∈ span s) : hs.repr (a • b) = a • hs.repr b := repr_eq hs (is_submodule.smul _ hb) (by simp [repr_eq_zero] {contextual := tt}) (calc (a • hs.repr b).sum (λb a, a • b) = (hs.repr b).sum (λb a', a • (a' • b)) : by simp [finsupp.sum_smul_index, add_smul, smul_smul] ... = a • (hs.repr b).sum (λb a', a' • b) : finsupp.smul_sum.symm ... = a • b : by rw [repr_sum_eq hs hb]) @[simp] lemma repr_neg : hs.repr (- b) = - hs.repr b := by_cases (assume hb : b ∈ span s, have hs.repr ((-1) • b) = (-1) • hs.repr b, from repr_smul hs hb, by simpa) (assume hb : b ∉ span s, have -b ∉ span s, from assume hb, have - - b ∈ span s, from is_submodule.neg hb, by simpa, by simp [repr_not_span, this, hb]) @[simp] lemma repr_sub (hb : b ∈ span s) (hb' : b' ∈ span s) : hs.repr (b - b') = hs.repr b - hs.repr b' := by simp [repr_add hs hb, repr_neg hs, is_submodule.neg hb'] @[simp] lemma repr_sum {ι : Type w} {f : finset ι} {b : ι → β} : (∀i∈f, b i ∈ span s) → hs.repr (f.sum b) = f.sum (λi, hs.repr (b i)) := by apply f.induction_on; simp [or_imp_distrib, forall_and_distrib, repr_add hs, is_submodule.sum] {contextual := tt} @[simp] lemma repr_finsupp_sum {ι : Type w} {δ : Type x} [has_zero δ] {f : ι →₀ δ} {b : ι → δ → β} : (∀i∈f.support, b i (f i) ∈ span s) → hs.repr (f.sum b) = f.sum (λi d, hs.repr (b i d)) := repr_sum hs lemma repr_eq_repr_of_subset {ht : linear_independent t} (h : t ⊆ s) (hb : b ∈ span t) : ht.repr b = hs.repr b := eq.symm $ repr_eq hs (span_mono h hb) (assume x hx, repr_eq_zero _ $ assume hxt, hx $ h hxt) (repr_sum_eq ht hb) end repr section variables {f : β → γ} {l : lc α β} (hs : linear_independent (f '' s)) (hf : is_linear_map f) (hf_inj : ∀a∈s, ∀b∈s, f a = f b → a = b) (hl : ∀x∉s, l x = 0) include hs hf hf_inj private lemma l_eq_0 (h : f (l.sum (λb a, a • b)) = 0) : l = 0 := have l_imp_s : ∀{x}, l x ≠ 0 → x ∈ s, from assume x hx, classical.by_contradiction $ assume hnx, hx $ hl _ $ hnx, have ∀c, c ∉ f '' s → c ∉ (l.map_domain f).support, from assume c, mt $ assume hb, have c ∈ l.support.image f, from finsupp.map_domain_support hb, have ∃b, l b ≠ 0 ∧ f b = c, by simpa, let ⟨b, hb, c_eq⟩ := this in ⟨b, l_imp_s hb, c_eq⟩, have l.map_domain f = 0, from hs _ (by simpa) $ calc (l.map_domain f).sum (λb a, a • b) = f (l.sum (λb a, a • b)): by simp [finsupp.sum_map_domain_index, add_smul, hf.finsupp_sum, hf.smul] ... = 0 : h, calc l = l.map_domain id : by rw [finsupp.map_domain_id] ... = l.map_domain (@inv_fun_on _ ⟨0⟩ _ f s ∘ f) : finsupp.map_domain_congr $ assume b hb, (@inv_fun_on_eq' _ ⟨0⟩ _ _ _ _ hf_inj $ l_imp_s $ by simpa using hb).symm ... = 0 : by rw [finsupp.map_domain_comp, this, finsupp.map_domain_zero] lemma linear_independent.of_image : linear_independent s := assume l hl eq, l_eq_0 hs hf hf_inj hl $ by simp [eq, hf.zero] lemma linear_independent.eq_0_of_span : ∀a∈span s, f a = 0 → a = 0 | _ ⟨l, hl, rfl⟩ eq_0 := by simp [l_eq_0 hs hf hf_inj hl eq_0, finsupp.sum_zero_index] end /-- A set of vectors is a basis if it is linearly independent and all vectors are in the span -/ def is_basis (s : set β) := linear_independent s ∧ (∀x, x ∈ span s) section is_basis lemma is_basis.map_repr (hs : is_basis s) : is_linear_map hs.1.repr := ⟨assume b₁ b₂, repr_add hs.1 (hs.2 _) (hs.2 _), assume a b, repr_smul hs.1 (hs.2 _)⟩ def is_basis.constr (hs : is_basis s) (f : β → γ) (b : β) : γ := (hs.1.repr b).sum (λb a, a • f b) lemma is_basis.map_constr (hs : is_basis s) {f : β → γ} : is_linear_map (hs.constr f) := lc.is_linear_map_sum (assume b, is_linear_map.map_smul_left is_linear_map.id) hs.map_repr lemma is_basis.eq_linear_map {f g : β → γ} (hf : is_linear_map f) (hg : is_linear_map g) (hs : is_basis s) (h : ∀b∈s, f b = g b) : f = g := funext $ assume b, linear_eq_on hf hg h (hs.2 b) lemma constr_congr {f g : β → γ} {b : β} (hs : is_basis s) (h : ∀b∈s, f b = g b) : hs.constr f = hs.constr g := funext $ assume b', finset.sum_congr rfl $ assume b hb, have b ∈ s, from repr_support hs.1 hb, by simp [h b this] lemma constr_basis {f : β → γ} {b : β} (hs : is_basis s) (hb : b ∈ s) : (hs.constr f : β → γ) b = f b := show (hs.1.repr b).sum (λb a, a • f b) = f b, by simp [hs.1, hs.2, hb, repr_eq_single, finsupp.sum_single_index] lemma constr_eq {g : β → γ} {f : β → γ} (hs : is_basis s) (hf : is_linear_map f) (h : ∀x∈s, g x = f x) : hs.constr g = f := hs.eq_linear_map hs.map_constr hf $ assume b hb, h b hb ▸ constr_basis hs hb lemma constr_zero (hs : is_basis s) : hs.constr (λb, (0 : γ)) = (λb, 0) := constr_eq hs is_linear_map.map_zero $ by simp lemma constr_add {g f : β → γ} (hs : is_basis s) : hs.constr (λb, f b + g b) = (λb, hs.constr f b + hs.constr g b) := constr_eq hs (is_linear_map.map_add hs.map_constr hs.map_constr) $ by simp [constr_basis hs] {contextual := tt} lemma constr_sub {g f : β → γ} (hs : is_basis s) : hs.constr (λb, f b - g b) = (λb, hs.constr f b - hs.constr g b) := constr_eq hs (is_linear_map.map_sub hs.map_constr hs.map_constr) $ by simp [constr_basis hs] {contextual := tt} lemma constr_neg {f : β → γ} (hs : is_basis s) : hs.constr (λb, - f b) = (λb, - hs.constr f b) := constr_eq hs hs.map_constr.map_neg $ by simp [constr_basis hs] {contextual := tt} -- this only works on functions if `α` is a commutative ring lemma constr_smul {α : Type u} {β : Type v} {γ : Type w} [comm_ring α] [module α β] [module α γ] {f : β → γ} {a : α} {s : set β} (hs : is_basis s) {b : β} : hs.constr (λb, a • f b) = (λb, a • (hs.constr f) b) := constr_eq hs hs.map_constr.map_smul_right $ by simp [constr_basis hs] {contextual := tt} lemma constr_mem_span (hs : is_basis s) {f : β → γ} : (hs.constr f : β → γ) b ∈ span (f '' s) := is_submodule.sum $ assume b' hb', have b' ∈ s, from repr_support hs.1 hb', is_submodule.smul _ $ subset_span $ mem_image_of_mem _ this lemma constr_im_eq_span (hs : is_basis s) {f : β → γ} : range (hs.constr f) = span (f '' s) := eq.symm $ span_eq (is_submodule.range hs.map_constr) (assume b' ⟨b, hb, eq⟩, ⟨b, eq ▸ constr_basis hs hb⟩) (assume b' ⟨b, hb⟩, hb ▸ constr_mem_span hs) def module_equiv_lc (hs : is_basis s) : β ≃ (s →₀ α) := { to_fun := assume b, (hs.1.repr b).subtype_domain _, inv_fun := assume v, v.sum $ λb a, a • b.1, left_inv := assume b, calc ((hs.1.repr b).subtype_domain s).sum (λb a, a • b.1) = (hs.1.repr b).sum (λb a, a • b) : @finsupp.sum_subtype_domain_index β _ _ _ _ (λx, x ∈ s) _ _ _ _ (λb a, a • b) (repr_support hs.1) ... = _ : repr_sum_eq _ $ hs.2 _, right_inv := assume v, finsupp.ext $ assume ⟨b, hb⟩, have v.sum (λb' a, hs.1.repr (a • b'.val) b) = v ⟨b, hb⟩, from calc v.sum (λb' a, hs.1.repr (a • b'.val) b) = v.sum (λb' a, a * (finsupp.single b'.val 1 : lc α β) b) : finset.sum_congr rfl $ assume ⟨b', hb'⟩ h', by dsimp; rw [repr_smul hs.1 (hs.2 _), repr_eq_single _ hb']; refl ... = ({⟨b, hb⟩} : finset s).sum (λb', v b' * (finsupp.single b'.val 1 : lc α β) b) : finset.sum_bij_ne_zero (λx hx x0, x) (assume ⟨x, hx⟩, by by_cases x = b; simp [*]) (by simp) (assume ⟨x, hx⟩, by simp; intro e; subst x; exact assume h, ⟨b, hb, assume h', by simp * at *, h, rfl⟩) (by simp) ... = v ⟨b, hb⟩ : by simp, begin dsimp, rw [repr_finsupp_sum, finsupp.sum_apply], { exact this }, { simp [hs.2] } end } def equiv_of_is_basis {s : set β} {t : set γ} {f : β → γ} {g : γ → β} (hs : is_basis s) (ht : is_basis t) (hf : ∀b∈s, f b ∈ t) (hg : ∀c∈t, g c ∈ s) (hgf : ∀b∈s, g (f b) = b) (hfg : ∀c∈t, f (g c) = c) : β ≃ₗ γ := { to_fun := hs.constr f, inv_fun := ht.constr g, left_inv := assume b, congr_fun (hs.eq_linear_map (ht.map_constr.comp hs.map_constr) is_linear_map.id $ by simp [constr_basis, hs, ht, hf, hgf, (∘)] {contextual := tt}) b, right_inv := assume c, congr_fun (ht.eq_linear_map (hs.map_constr.comp ht.map_constr) is_linear_map.id $ by simp [constr_basis, hs, ht, hg, hfg, (∘)] {contextual := tt}) c, linear_fun := hs.map_constr } end is_basis lemma linear_independent.inj_span_iff_inj {s : set β} {f : β → γ} (hf : is_linear_map f) (hfs : linear_independent (f '' s)) : (∀a∈span s, ∀b∈span s, f a = f b → a = b) ↔ (∀a∈s, ∀b∈s, f a = f b → a = b) := iff.intro (assume h a ha b hb eq, h a (subset_span ha) b (subset_span hb) eq) (assume h a ha b hb eq, eq_of_sub_eq_zero $ hfs.eq_0_of_span hf h _ (is_submodule.sub ha hb) (by simp [eq, hf.add, hf.neg])) -- TODO: clean up proof / alternative proof lemma linear_independent.image {s : set β} {f : β → γ} (hf : is_linear_map f) (hs : linear_independent s) (hf_inj : ∀a∈span s, ∀b∈span s, f a = f b → a = b) : linear_independent (f '' s) := let g := @inv_fun_on _ ⟨0⟩ _ f (span s) in have hg : ∀x∈span s, g (f x) = x, from assume x, @inv_fun_on_eq' _ ⟨0⟩ _ _ _ _ hf_inj, assume l hl eq, have l_g : ∀b∈(l.map_domain g).support, b ∈ s, from assume b hb, have b ∈ l.support.image g, from finsupp.map_domain_support hb, have ∃c, l c ≠ 0 ∧ g c = b, by simpa, let ⟨c, hc, b_eq⟩ := this in have c ∈ f '' s, by by_contradiction h; simp * at *, let ⟨b', hb', c_eq⟩ := this in have b' = b, from b_eq ▸ c_eq ▸ (hg _ $ subset_span hb').symm, this ▸ hb', have l_f_g : l.map_domain (f ∘ g) = l.map_domain id, from finsupp.map_domain_congr $ assume c hc, have c ∈ f '' s, by by_contradiction h; simp * at *, let ⟨b, hb, c_eq⟩ := this in by simp [c_eq.symm, (∘), hg, subset_span hb], have l.map_domain g = 0, from have l_g_s : (l.map_domain g).sum (λb a, a • b) ∈ span s, from is_submodule.sum $ assume b hb, is_submodule.smul _ $ subset_span $ l_g b hb, have f_sum : f ((l.map_domain g).sum (λb a, a • b)) = 0, from calc f ((l.map_domain g).sum (λb a, a • b)) = ((l.map_domain g).map_domain f).sum (λb a, a • b) : by simp [finsupp.sum_map_domain_index, add_smul, hf.finsupp_sum, hf.smul] ... = 0 : by rw [←finsupp.map_domain_comp, l_f_g, finsupp.map_domain_id, eq], have ∀b∉s, (l.map_domain g) b = 0, from assume b hb, classical.by_contradiction $ assume hnb, hb $ l_g b $ by simp *, hs _ this $ hf_inj _ l_g_s _ is_submodule.zero (by simpa [hf.zero] using f_sum), calc l = (l.map_domain g).map_domain f : by rw [←finsupp.map_domain_comp, l_f_g, finsupp.map_domain_id] ... = 0 : by rw [this, finsupp.map_domain_zero] lemma linear_map.linear_independent_image_iff {s : set β} {f : β → γ} (hf : is_linear_map f) (hf_inj : ∀a∈span s, ∀b∈span s, f a = f b → a = b) : linear_independent (f '' s) ↔ linear_independent s := iff.intro (assume h, h.of_image hf $ assume x hx y hy, hf_inj x (subset_span hx) y (subset_span hy)) (assume h, h.image hf hf_inj) end module section vector_space variables [field α] [vector_space α β] [vector_space α γ] {s t : set β} {b b₁ b₂ : β} include α local attribute [instance] is_submodule_span /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type classs) -/ lemma mem_span_insert_exchange : b₁ ∈ span (insert b₂ s) → b₁ ∉ span s → b₂ ∈ span (insert b₁ s) := begin simp [span_insert], exact assume a b₃ hb₃ b₁_eq hb₁, have a ≠ 0, from assume a0, by simp * at *, ⟨1/a, (- 1/a) • b₃, is_submodule.smul _ hb₃, by simp [b₁_eq, smul_add, smul_smul, mul_inv_cancel, this, neg_div]⟩ end lemma linear_independent_iff_not_mem_span : linear_independent s ↔ (∀b∈s, b ∉ span (s \ {b})) := iff.intro (assume (hs : linear_independent s) b hb ⟨l, hl, b_eq⟩, let l' := l - finsupp.single b 1 in have ∀b', b' ∉ s → l' b' = 0, from assume b' hb', have ne: b ≠ b', from assume h, hb' $ h ▸ hb, have b' ∉ s \ {b}, from assume ⟨h₁, h₂⟩, hb' h₁, by simp [ne, hl b' this], have l' = 0, from hs l' this $ by simp [l', finsupp.sum_add_index, finsupp.sum_neg_index, add_smul, b_eq.symm, finsupp.sum_single_index], have - l' b = 1, from have b ∉ s \ {b}, by simp, by simp [hl _ this], by rw [‹l' = 0›] at this; simp at this; assumption) (assume hs l hl eq, finsupp.ext $ assume b, classical.by_contradiction $ assume h : l b ≠ 0, let a := -1 / l b in hs b (show b ∈ s, from classical.by_contradiction $ assume hnb, h $ hl b hnb) ⟨a • l + finsupp.single b 1, assume b', by_cases (assume : b' = b, by simp [this, h, neg_div, a]) (assume : b' ≠ b, by simp [finsupp.sub_apply, hl, this, this.symm] {contextual:=tt}), have l.sum (λb a', (a * a') • b) = a • l.sum (λb a, a • b), by simp [finsupp.smul_sum, smul_smul], by simp [-sub_eq_add_neg, add_smul, finsupp.sum_add_index, finsupp.sum_single_index, finsupp.sum_smul_index, this, eq]⟩) lemma linear_independent_singleton {b : β} (hb : b ≠ 0) : linear_independent ({b} : set β) := linear_independent_iff_not_mem_span.mpr $ by simp [hb] {contextual := tt} lemma linear_independent.insert (hs : linear_independent s) (hb : b ∉ span s) : linear_independent (insert b s) := assume l hl eq, by_cases (assume : l b = 0, hs l (assume x hx, by_cases (assume h : x = b, h.symm ▸ this) (assume h', hl _ $ by simp [not_or_distrib, hx, h'])) eq) (assume lb_ne_zero : l b ≠ 0, have (1 / l b) • (- (- l b • b)) ∈ span s, from is_submodule.smul _ $ is_submodule.neg ⟨l - finsupp.single b (l b), assume x hx, by_cases (assume : b = x, by simp [this.symm]) (assume ne : b ≠ x, have x ∉ insert b s, by simp [not_or_distrib, hx, ne.symm], by simp [hl x this, ne] {contextual := tt}), by simp [finsupp.sum_sub_index, finsupp.sum_single_index, -sub_eq_add_neg, sub_smul, eq]; simp⟩, have (1 / l b) • (- (- l b • b)) = b, by simp [smul_smul, mul_comm, mul_inv_cancel lb_ne_zero], by simp * at *) lemma exists_linear_independent (hs : linear_independent s) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span b ∧ linear_independent b := let C := { b : set β // s ⊆ b ∧ b ⊆ t ∧ linear_independent b }, s' : C := ⟨s, le_refl s, hst, hs⟩ in have ∀c, zorn.chain (λa b:C, a.val ⊆ b.val) c → c ≠ ∅ → ∃(m : C), ∀a:C, a ∈ c → a.val ⊆ m.val, from assume c hc ne, let ⟨a, ha⟩ := exists_mem_of_ne_empty ne in ⟨⟨(⋃a ∈ c, (a : C).val), subset.trans a.property.1 $ subset_bUnion_of_mem ha, bUnion_subset $ assume c hc, c.property.right.left, linear_independent_bUnion_of_directed (assume a ha b hb, by_cases (assume h : a = b, ⟨a, ha, h ▸ le_of_eq (@sup_idem (set _) _ a.val)⟩) (assume h : a ≠ b, (hc a ha b hb h).elim (assume h, ⟨b, hb, union_subset h (subset.refl _)⟩) (assume h, ⟨a, ha, union_subset (subset.refl _) h⟩))) (assume a ha, a.property.2.2)⟩, assume a ha, subset_bUnion_of_mem ha⟩, have ∃m:C, ∀a:C, m.val ⊆ a.val → a.val ⊆ m.val, from zorn.zorn (assume c hc, by_cases (assume : c = ∅, ⟨s', assume a, this.symm ▸ false.elim⟩) (this c hc)) (assume a b c, subset.trans), let ⟨⟨m, hsm, hmt, hml⟩, hm⟩ := this in have t ⊆ span m, from classical.by_contradiction $ assume : ¬ t ⊆ span m, let ⟨b, hb⟩ := classical.not_forall.mp this, ⟨hbt, hbm⟩ := not_imp.mp hb in have insert b m ⊆ m, from hm ⟨_, subset.trans hsm $ subset_insert _ _, by simp [set.insert_subset, hmt, hbt], hml.insert hbm⟩ (subset_insert _ _), have b ∈ span m, from subset_span $ this $ mem_insert _ _, hbm this, ⟨m, hmt, hsm, this, hml⟩ lemma exists_subset_is_basis (hs : linear_independent s) : ∃b, s ⊆ b ∧ is_basis b := let ⟨b, hb₀, hb₁, hb₂, hb₃⟩ := exists_linear_independent hs (@subset_univ _ _) in ⟨b, hb₁, hb₃, assume x, hb₂ trivial⟩ variable (β) lemma exists_is_basis : ∃b : set β, is_basis b := let ⟨b, _, hb⟩ := exists_subset_is_basis linear_independent_empty in ⟨b, hb⟩ variable {β} lemma eq_of_linear_independent_of_span (hs : linear_independent s) (h : t ⊆ s) (hst : s ⊆ span t) : s = t := suffices s ⊆ t, from subset.antisymm this h, assume b hb, have (hs.mono h).repr b = finsupp.single b 1, from calc (hs.mono h).repr b = hs.repr b : repr_eq_repr_of_subset hs h $ hst hb ... = finsupp.single b 1 : repr_eq_single hs hb, have b ∈ (↑((hs.mono h).repr b).support : set β), by simp [this], repr_support _ this lemma exists_of_linear_independent_of_finite_span {t : finset β} (hs : linear_independent s) (hst : s ⊆ span ↑t) : ∃t':finset β, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset β), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ span ↑(s' ∪ t) → ∃t':finset β, ↑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 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), by_cases (assume : s ⊆ span ↑(s' ∪ t), 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 [set.insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ span ↑(s' ∪ t), let ⟨b₂, hb₂s, hb₂t⟩ := set.not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ span ↑(insert b₂ s' ∪ t), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set β), by simp [insert_eq, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span (insert b₁ (insert b₂ ↑(s' ∪ t) : set β)), from span_mono this (hss' hb₃), have s ⊆ span (insert b₁ ↑(s' ∪ t)), by simpa [insert_eq] using hss', have hb₁ : b₁ ∈ span (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 [set.insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by rw [finset.union_comm] at hb₂t'; simp [eq, hb₂t', hb₁t, hb₁s']⟩)), have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, from finset.ext.mpr $ assume x, by by_cases x ∈ s; simp *, let ⟨u, h₁, h₂, h⟩ := this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.set_eq_def] {contextual := tt}) (by rwa [eq]) in ⟨u, subset.trans h₁ (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h₂, by rwa [eq] at h⟩ lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent s) (hst : s ⊆ span t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ span ↑(ht.to_finset), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from finite_subset u.finite_to_set hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ lemma exists_left_inverse_linear_map_of_injective {f : β → γ} (hf : is_linear_map f) (hf_inj : injective f) : ∃g:γ → β, is_linear_map g ∧ g ∘ f = id := let ⟨bβ, hbβ⟩ := exists_is_basis β in have linear_independent (f '' bβ), from hbβ.1.image hf $ assume b₁ _ b₂ _ eq, hf_inj eq, let ⟨bγ, hbγ₁, hbγ₂⟩ := exists_subset_is_basis this in have ∀b∈bβ, (hbγ₂.constr (@inv_fun _ ⟨0⟩ _ f) : γ → β) (f b) = b, begin assume b hb, rw [constr_basis], { exact @inv_fun_on_eq' β ⟨0⟩ γ f univ b (assume b₁ _ b₂ _ eq, hf_inj eq) trivial }, { exact hbγ₁ (mem_image_of_mem _ hb) } end, ⟨hbγ₂.constr $ @inv_fun _ ⟨0⟩ _ f, hbγ₂.map_constr, hbβ.eq_linear_map (hbγ₂.map_constr.comp hf) is_linear_map.id this⟩ lemma exists_right_inverse_linear_map_of_surjective {f : β → γ} (hf : is_linear_map f) (hf_surj : surjective f) : ∃g:γ → β, is_linear_map g ∧ f ∘ g = id := let g := @inv_fun _ ⟨0⟩ _ f in have ri_gf : right_inverse g f, from @right_inverse_inv_fun _ ⟨0⟩ _ _ hf_surj, have injective g, from injective_of_left_inverse ri_gf, let ⟨bγ, hbγ⟩ := exists_is_basis γ in have ∀c∈bγ, f ((hbγ.constr g : γ → β) c) = c, from assume c hc, by rw [constr_basis hbγ hc, ri_gf], ⟨hbγ.constr g, hbγ.map_constr, hbγ.eq_linear_map (hf.comp hbγ.map_constr) is_linear_map.id this⟩ end vector_space
c041186ffc14db26a30f95eced8ca8ac4e9a6e53
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/run/coeIssue3.lean
c84587b826d5251f2bdce6d58039fc532496f473
[ "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
500
lean
structure Var : Type := (name : String) instance Var.nameCoe : Coe String Var := ⟨Var.mk⟩ structure A : Type := (u : Unit) structure B : Type := (u : Unit) def a : A := A.mk () def b : B := B.mk () def Foo.chalk : A → List Var → Unit := fun _ _ => () def Bar.chalk : B → Unit := fun _ => () instance listCoe {α β} [Coe α β] : Coe (List α) (List β) := ⟨fun as => as.map fun a => coe a⟩ open Foo open Bar #check Foo.chalk a ["foo"] -- works #check chalk a ["foo"] -- works
9f2bceeab41bad5794434de6dcc9aa4a3da1c1ba
03bd658c402412f41d3026d1040ee8ca8c0fc579
/src/MITM_baby.lean
3f02946cf80b8c0d9a49da0d8cb17971c3c6b112
[]
no_license
ImperialCollegeLondon/dots_and_boxes
c205f6dbad8af9625f56715e4d1bed96b0ac1022
f7bd0b1603674a657170c5395adb717c4f670220
refs/heads/master
1,663,752,058,476
1,591,438,614,000
1,591,438,614,000
139,707,103
2
0
null
null
null
null
UTF-8
Lean
false
false
3,407
lean
import list.simple_value list.modify.basic open list /-- Man in the middle for all-chain or all-loop situations -/ theorem MITM_baby (tf : ℤ) (L1 L2 : list ℤ) (d : ℤ) (h : list.modify L1 L2 d) (n : ℕ) (hL1 : L1.length = n) (hL2 : L2.length = n) (i : fin n) : abs (list.value_i tf n L1 i hL1 - list.value_i tf n L2 i hL2) ≤ d := begin revert L1 L2, -- so the inductive hypothesis does not depend on the exact choice of L1 and L2 induction n with e he, -- by induction on the number of components -- base case : n = 0 {cases i.is_lt}, -- inductive step : n = nat.succ e {intros L1 L2 h hL1 hL2, unfold list.value_i, /- after unfolding, the goal is : abs (aux_fun (nth_le L1 (i.val) _) tf (min' (of_fn (λ (j : fin e), value_i tf e (remove_nth L1 (i.val)) j _))) - aux_fun (nth_le L2 (i.val) _) tf (min' (of_fn (λ (j : fin e), value_i tf e (remove_nth L2 (i.val)) j _)))) ≤ d -/ /- now either we opened the component in which the games differ or not-/ by_cases hin : h.n = i.val, { -- i = place where lists differ have heq := h.heq, rw hin at heq, -- after substitution, heq is remove_nth L1 (i.val) = remove_nth L2 (i.val) simp only [heq], -- simp only rewrites in the arguments of nth_le as well apply list.aux_fun_L1, -- see list.simple_value convert h.bound, -- goal is basically just h.bound exact hin.symm, /- need to prove i.val = h.n, as the goal described the indices using i.val, and h.bound used h.n-/ exact hin.symm, -- because i.val/h.n comes up twice }, { -- i ≠ place where lists differ /- so this time by another lemma nth_le L1 (i.val) _ = nth_le L2 (i.val) _ -/ rw list.modify_same h i.val _ (begin rw hL2, exact i.is_lt end) hin, -- see list.modify.basic apply list.aux_fun_L2, -- see list.simple_value -- apply "lists differ by at most d -> min differs by at most d" apply list.min'_change, -- see list.min.basic {simp only [list.length_of_fn]}, -- use that length (of_fn (λ (j : fin e), ...))) = e --prove 0 <= d from h using that the absolute value is non-negative {apply le_trans _ h.bound, -- transitivity of ≤ show abs (nth_le L1 h.n h.ha - nth_le L2 h.n h.hb) ≥ 0, exact abs_nonneg _,}, -- absolute values are non-negative {intros n HnL HnM, rw eq_comm at hin, -- commutativity of = --need the following as argument for he (in he L1 = (remove_nth L1 (i.val)) --and L2 = (remove_nth L2 (i.val))) have P : list.modify (remove_nth L1 (i.val)) (remove_nth L2 (i.val)) d, {exact list.modify_remove_nth h i.val hin}, -- see list.modify.basic -- put the goal into the correct form for the inductive hypothis he rw length_of_fn at HnL, rw nth_le_of_fn _ ⟨n, HnL⟩, /- nth_le (of_fn f) ⟨n, HnL⟩ = f (⟨n, HnL⟩) (where f is : λ (j : fin e), value_i tf e (remove_nth L1 (i.val)) j _)) -/ rw nth_le_of_fn _ ⟨n, HnL⟩, exact he _ _ _ P _ _, /- use inductive hypothesis (every argument other than P can be inferred)-/ }, }, } end
718ddfa474716ea90b26df52461a15ee4eba07ca
92b50235facfbc08dfe7f334827d47281471333b
/hott/init/logic.hlean
af1ea7d8a9d639af36bcb2bc3e73fbd85cc4b783
[ "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
13,440
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.reserved_notation /- not -/ definition not (a : Type) := a → empty prefix `¬` := not definition absurd {a b : Type} (H₁ : a) (H₂ : ¬a) : b := empty.rec (λ e, b) (H₂ H₁) definition mt {a b : Type} (H₁ : a → b) (H₂ : ¬b) : ¬a := assume Ha : a, absurd (H₁ Ha) H₂ protected definition not_empty : ¬ empty := assume H : empty, H definition not_not_intro {a : Type} (Ha : a) : ¬¬a := assume Hna : ¬a, absurd Ha Hna definition not.elim {a : Type} (H₁ : ¬a) (H₂ : a) : empty := H₁ H₂ definition not.intro {a : Type} (H : a → empty) : ¬a := H definition not_not_of_not_implies {a b : Type} (H : ¬(a → b)) : ¬¬a := assume Hna : ¬a, absurd (assume Ha : a, absurd Ha Hna) H definition not_of_not_implies {a b : Type} (H : ¬(a → b)) : ¬b := assume Hb : b, absurd (assume Ha : a, Hb) H /- eq -/ notation a = b := eq a b definition rfl {A : Type} {a : A} := eq.refl a namespace eq variables {A : Type} {a b c : A} definition subst [unfold 5] {P : A → Type} (H₁ : a = b) (H₂ : P a) : P b := eq.rec H₂ H₁ definition trans [unfold 5] (H₁ : a = b) (H₂ : b = c) : a = c := subst H₂ H₁ definition symm [unfold 4] (H : a = b) : b = a := subst H (refl a) namespace ops notation H `⁻¹` := symm H --input with \sy or \-1 or \inv notation H1 ⬝ H2 := trans H1 H2 notation H1 ▸ H2 := subst H1 H2 end ops end eq definition congr {A B : Type} {f₁ f₂ : A → B} {a₁ a₂ : A} (H₁ : f₁ = f₂) (H₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := eq.subst H₁ (eq.subst H₂ rfl) section variables {A : Type} {a b c: A} open eq.ops definition trans_rel_left (R : A → A → Type) (H₁ : R a b) (H₂ : b = c) : R a c := H₂ ▸ H₁ definition trans_rel_right (R : A → A → Type) (H₁ : a = b) (H₂ : R b c) : R a c := H₁⁻¹ ▸ H₂ end attribute eq.subst [subst] attribute eq.refl [refl] attribute eq.trans [trans] attribute eq.symm [symm] namespace lift definition down_up.{l₁ l₂} {A : Type.{l₁}} (a : A) : down (up.{l₁ l₂} a) = a := rfl definition up_down.{l₁ l₂} {A : Type.{l₁}} (a : lift.{l₁ l₂} A) : up (down a) = a := lift.rec_on a (λ d, rfl) end lift /- ne -/ definition ne {A : Type} (a b : A) := ¬(a = b) notation a ≠ b := ne a b namespace ne open eq.ops variable {A : Type} variables {a b : A} definition intro : (a = b → empty) → a ≠ b := assume H, H definition elim : a ≠ b → a = b → empty := assume H₁ H₂, H₁ H₂ definition irrefl : a ≠ a → empty := assume H, H rfl definition symm : a ≠ b → b ≠ a := assume (H : a ≠ b) (H₁ : b = a), H H₁⁻¹ end ne section open eq.ops variables {A : Type} {a b c : A} definition false.of_ne : a ≠ a → empty := assume H, H rfl definition ne.of_eq_of_ne : a = b → b ≠ c → a ≠ c := assume H₁ H₂, H₁⁻¹ ▸ H₂ definition ne.of_ne_of_eq : a ≠ b → b = c → a ≠ c := assume H₁ H₂, H₂ ▸ H₁ end /- iff -/ definition iff (a b : Type) := prod (a → b) (b → a) notation a <-> b := iff a b notation a ↔ b := iff a b namespace iff variables {a b c : Type} definition def : (a ↔ b) = (prod (a → b) (b → a)) := rfl definition intro (H₁ : a → b) (H₂ : b → a) : a ↔ b := prod.mk H₁ H₂ definition elim (H₁ : (a → b) → (b → a) → c) (H₂ : a ↔ b) : c := prod.rec H₁ H₂ definition elim_left (H : a ↔ b) : a → b := elim (assume H₁ H₂, H₁) H definition mp := @elim_left definition elim_right (H : a ↔ b) : b → a := elim (assume H₁ H₂, H₂) H definition mp' := @elim_right definition flip_sign (H₁ : a ↔ b) : ¬a ↔ ¬b := intro (assume Hna, mt (elim_right H₁) Hna) (assume Hnb, mt (elim_left H₁) Hnb) definition refl (a : Type) : a ↔ a := intro (assume H, H) (assume H, H) definition rfl {a : Type} : a ↔ a := refl a definition trans (H₁ : a ↔ b) (H₂ : b ↔ c) : a ↔ c := intro (assume Ha, elim_left H₂ (elim_left H₁ Ha)) (assume Hc, elim_right H₁ (elim_right H₂ Hc)) definition symm (H : a ↔ b) : b ↔ a := intro (assume Hb, elim_right H Hb) (assume Ha, elim_left H Ha) definition true_elim (H : a ↔ unit) : a := mp (symm H) unit.star definition false_elim (H : a ↔ empty) : ¬a := assume Ha : a, mp H Ha open eq.ops definition of_eq {a b : Type} (H : a = b) : a ↔ b := iff.intro (λ Ha, H ▸ Ha) (λ Hb, H⁻¹ ▸ Hb) definition pi_iff_pi {A : Type} {P Q : A → Type} (H : Πa, (P a ↔ Q a)) : (Πa, P a) ↔ Πa, Q a := iff.intro (λp a, iff.elim_left (H a) (p a)) (λq a, iff.elim_right (H a) (q a)) theorem imp_iff {P : Type} (Q : Type) (p : P) : (P → Q) ↔ Q := iff.intro (λf, f p) (λq p, q) end iff attribute iff.refl [refl] attribute iff.trans [trans] attribute iff.symm [symm] /- inhabited -/ inductive inhabited [class] (A : Type) : Type := mk : A → inhabited A namespace inhabited protected definition destruct {A : Type} {B : Type} (H1 : inhabited A) (H2 : A → B) : B := inhabited.rec H2 H1 definition inhabited_fun [instance] (A : Type) {B : Type} [H : inhabited B] : inhabited (A → B) := inhabited.destruct H (λb, mk (λa, b)) definition inhabited_Pi [instance] (A : Type) {B : A → Type} [H : Πx, inhabited (B x)] : inhabited (Πx, B x) := mk (λa, inhabited.destruct (H a) (λb, b)) definition default (A : Type) [H : inhabited A] : A := inhabited.destruct H (take a, a) end inhabited /- decidable -/ inductive decidable.{l} [class] (p : Type.{l}) : Type.{l} := | inl : p → decidable p | inr : ¬p → decidable p namespace decidable variables {p q : Type} definition pos_witness [C : decidable p] (H : p) : p := decidable.rec_on C (λ Hp, Hp) (λ Hnp, absurd H Hnp) definition neg_witness [C : decidable p] (H : ¬ p) : ¬ p := decidable.rec_on C (λ Hp, absurd Hp H) (λ Hnp, Hnp) definition by_cases {q : Type} [C : decidable p] (Hpq : p → q) (Hnpq : ¬p → q) : q := decidable.rec_on C (assume Hp, Hpq Hp) (assume Hnp, Hnpq Hnp) definition em (p : Type) [H : decidable p] : sum p ¬p := by_cases (λ Hp, sum.inl Hp) (λ Hnp, sum.inr Hnp) definition by_contradiction [Hp : decidable p] (H : ¬p → empty) : p := by_cases (assume H₁ : p, H₁) (assume H₁ : ¬p, empty.rec (λ e, p) (H H₁)) definition decidable_iff_equiv (Hp : decidable p) (H : p ↔ q) : decidable q := decidable.rec_on Hp (assume Hp : p, inl (iff.elim_left H Hp)) (assume Hnp : ¬p, inr (iff.elim_left (iff.flip_sign H) Hnp)) definition decidable_eq_equiv.{l} {p q : Type.{l}} (Hp : decidable p) (H : p = q) : decidable q := decidable_iff_equiv Hp (iff.of_eq H) end decidable section variables {p q : Type} open decidable (rec_on inl inr) definition decidable_unit [instance] : decidable unit := inl unit.star definition decidable_empty [instance] : decidable empty := inr not_empty definition decidable_prod [instance] [Hp : decidable p] [Hq : decidable q] : decidable (prod p q) := rec_on Hp (assume Hp : p, rec_on Hq (assume Hq : q, inl (prod.mk Hp Hq)) (assume Hnq : ¬q, inr (λ H : prod p q, prod.rec_on H (λ Hp Hq, absurd Hq Hnq)))) (assume Hnp : ¬p, inr (λ H : prod p q, prod.rec_on H (λ Hp Hq, absurd Hp Hnp))) definition decidable_sum [instance] [Hp : decidable p] [Hq : decidable q] : decidable (sum p q) := rec_on Hp (assume Hp : p, inl (sum.inl Hp)) (assume Hnp : ¬p, rec_on Hq (assume Hq : q, inl (sum.inr Hq)) (assume Hnq : ¬q, inr (λ H : sum p q, sum.rec_on H (λ Hp, absurd Hp Hnp) (λ Hq, absurd Hq Hnq)))) definition decidable_not [instance] [Hp : decidable p] : decidable (¬p) := rec_on Hp (assume Hp, inr (not_not_intro Hp)) (assume Hnp, inl Hnp) definition decidable_implies [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p → q) := rec_on Hp (assume Hp : p, rec_on Hq (assume Hq : q, inl (assume H, Hq)) (assume Hnq : ¬q, inr (assume H : p → q, absurd (H Hp) Hnq))) (assume Hnp : ¬p, inl (assume Hp, absurd Hp Hnp)) definition decidable_if [instance] [Hp : decidable p] [Hq : decidable q] : decidable (p ↔ q) := show decidable (prod (p → q) (q → p)), from _ end definition decidable_pred [reducible] {A : Type} (R : A → Type) := Π (a : A), decidable (R a) definition decidable_rel [reducible] {A : Type} (R : A → A → Type) := Π (a b : A), decidable (R a b) definition decidable_eq [reducible] (A : Type) := decidable_rel (@eq A) definition decidable_ne [instance] {A : Type} [H : decidable_eq A] : decidable_rel (@ne A) := show Π x y : A, decidable (x = y → empty), from _ definition ite (c : Type) [H : decidable c] {A : Type} (t e : A) : A := decidable.rec_on H (λ Hc, t) (λ Hnc, e) definition if_pos {c : Type} [H : decidable c] (Hc : c) {A : Type} {t e : A} : (if c then t else e) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t e)) (λ Hnc : ¬c, absurd Hc Hnc) H definition if_neg {c : Type} [H : decidable c] (Hnc : ¬c) {A : Type} {t e : A} : (if c then t else e) = e := decidable.rec (λ Hc : c, absurd Hc Hnc) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t e)) H definition if_t_t (c : Type) [H : decidable c] {A : Type} (t : A) : (if c then t else t) = t := decidable.rec (λ Hc : c, eq.refl (@ite c (decidable.inl Hc) A t t)) (λ Hnc : ¬c, eq.refl (@ite c (decidable.inr Hnc) A t t)) H definition if_unit {A : Type} (t e : A) : (if unit then t else e) = t := if_pos unit.star definition if_empty {A : Type} (t e : A) : (if empty then t else e) = e := if_neg not_empty section open eq.ops definition if_cond_congr {c₁ c₂ : Type} [H₁ : decidable c₁] [H₂ : decidable c₂] (Heq : c₁ ↔ c₂) {A : Type} (t e : A) : (if c₁ then t else e) = (if c₂ then t else e) := decidable.rec_on H₁ (λ Hc₁ : c₁, decidable.rec_on H₂ (λ Hc₂ : c₂, if_pos Hc₁ ⬝ (if_pos Hc₂)⁻¹) (λ Hnc₂ : ¬c₂, absurd (iff.elim_left Heq Hc₁) Hnc₂)) (λ Hnc₁ : ¬c₁, decidable.rec_on H₂ (λ Hc₂ : c₂, absurd (iff.elim_right Heq Hc₂) Hnc₁) (λ Hnc₂ : ¬c₂, if_neg Hnc₁ ⬝ (if_neg Hnc₂)⁻¹)) definition if_congr_aux {c₁ c₂ : Type} [H₁ : decidable c₁] [H₂ : decidable c₂] {A : Type} {t₁ t₂ e₁ e₂ : A} (Hc : c₁ ↔ c₂) (Ht : t₁ = t₂) (He : e₁ = e₂) : (if c₁ then t₁ else e₁) = (if c₂ then t₂ else e₂) := Ht ▸ He ▸ (if_cond_congr Hc t₁ e₁) definition if_congr {c₁ c₂ : Type} [H₁ : decidable c₁] {A : Type} {t₁ t₂ e₁ e₂ : A} (Hc : c₁ ↔ c₂) (Ht : t₁ = t₂) (He : e₁ = e₂) : (if c₁ then t₁ else e₁) = (@ite c₂ (decidable.decidable_iff_equiv H₁ Hc) A t₂ e₂) := have H2 [visible] : decidable c₂, from (decidable.decidable_iff_equiv H₁ Hc), if_congr_aux Hc Ht He theorem implies_of_if_pos {c t e : Type} [H : decidable c] (h : if c then t else e) : c → t := assume Hc, eq.rec_on (if_pos Hc) h theorem implies_of_if_neg {c t e : Type} [H : decidable c] (h : if c then t else e) : ¬c → e := assume Hnc, eq.rec_on (if_neg Hnc) h -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches definition dite (c : Type) [H : decidable c] {A : Type} (t : c → A) (e : ¬ c → A) : A := decidable.rec_on H (λ Hc, t Hc) (λ Hnc, e Hnc) definition dif_pos {c : Type} [H : decidable c] (Hc : c) {A : Type} {t : c → A} {e : ¬ c → A} : (if H : c then t H else e H) = t (decidable.pos_witness Hc) := decidable.rec (λ Hc : c, eq.refl (@dite c (decidable.inl Hc) A t e)) (λ Hnc : ¬c, absurd Hc Hnc) H definition dif_neg {c : Type} [H : decidable c] (Hnc : ¬c) {A : Type} {t : c → A} {e : ¬ c → A} : (if H : c then t H else e H) = e (decidable.neg_witness Hnc) := decidable.rec (λ Hc : c, absurd Hc Hnc) (λ Hnc : ¬c, eq.refl (@dite c (decidable.inr Hnc) A t e)) H -- Remark: dite and ite are "definitionally equal" when we ignore the proofs. definition dite_ite_eq (c : Type) [H : decidable c] {A : Type} (t : A) (e : A) : dite c (λh, t) (λh, e) = ite c t e := rfl end open eq.ops unit definition is_unit (c : Type) [H : decidable c] : Type₀ := if c then unit else empty definition is_empty (c : Type) [H : decidable c] : Type₀ := if c then empty else unit theorem of_is_unit {c : Type} [H₁ : decidable c] (H₂ : is_unit c) : c := decidable.rec_on H₁ (λ Hc, Hc) (λ Hnc, empty.rec _ (if_neg Hnc ▸ H₂)) notation `dec_trivial` := of_is_unit star theorem not_of_not_is_unit {c : Type} [H₁ : decidable c] (H₂ : ¬ is_unit c) : ¬ c := decidable.rec_on H₁ (λ Hc, absurd star (if_pos Hc ▸ H₂)) (λ Hnc, Hnc) theorem not_of_is_empty {c : Type} [H₁ : decidable c] (H₂ : is_empty c) : ¬ c := decidable.rec_on H₁ (λ Hc, empty.rec _ (if_pos Hc ▸ H₂)) (λ Hnc, Hnc) theorem of_not_is_empty {c : Type} [H₁ : decidable c] (H₂ : ¬ is_empty c) : c := decidable.rec_on H₁ (λ Hc, Hc) (λ Hnc, absurd star (if_neg Hnc ▸ H₂))
b08ccf41d1ae27b2312839f3d8f6af98fefbb6f0
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/ordmap/ordnode.lean
762691a2b7d6ccfce373582fbe1dca2920a7649f
[]
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
33,639
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.list.defs import Mathlib.data.nat.psub import Mathlib.PostPort universes u l u_1 u_2 namespace Mathlib /-! # Ordered sets This file defines a data structure for ordered sets, supporting a variety of useful operations including insertion and deletion, logarithmic time lookup, set operations, folds, and conversion from lists. The `ordnode α` operations all assume that `α` has the structure of a total preorder, meaning a `≤` operation that is * Transitive: `x ≤ y → y ≤ z → x ≤ z` * Reflexive: `x ≤ x` * Total: `x ≤ y ∨ y ≤ x` For example, in order to use this data structure as a map type, one can store pairs `(k, v)` where `(k, v) ≤ (k', v')` is defined to mean `k ≤ k'` (assuming that the key values are linearly ordered). Two values `x,y` are equivalent if `x ≤ y` and `y ≤ x`. An `ordnode α` maintains the invariant that it never stores two equivalent nodes; the insertion operation comes with two variants depending on whether you want to keep the old value or the new value in case you insert a value that is equivalent to one in the set. The operations in this file are not verified, in the sense that they provide "raw operations" that work for programming purposes but the invariants are not explicitly in the structure. See `ordset` for a verified version of this data structure. ## Main definitions * `ordnode α`: A set of values of type `α` ## Implementation notes Based on weight balanced trees: * Stephen Adams, "Efficient sets: a balancing act", Journal of Functional Programming 3(4):553-562, October 1993, <http://www.swiss.ai.mit.edu/~adams/BB/>. * J. Nievergelt and E.M. Reingold, "Binary search trees of bounded balance", SIAM journal of computing 2(1), March 1973. Ported from Haskell's `Data.Set`. ## Tags ordered map, ordered set, data structure -/ /-- An `ordnode α` is a finite set of values, represented as a tree. The operations on this type maintain that the tree is balanced and correctly stores subtree sizes at each level. -/ inductive ordnode (α : Type u) where | nil : ordnode α | node : ℕ → ordnode α → α → ordnode α → ordnode α namespace ordnode protected instance has_emptyc {α : Type u} : has_emptyc (ordnode α) := has_emptyc.mk nil protected instance inhabited {α : Type u} : Inhabited (ordnode α) := { default := nil } /-- **Internal use only** The maximal relative difference between the sizes of two trees, it corresponds with the `w` in Adams' paper. According to the Haskell comment, only `(delta, ratio)` settings of `(3, 2)` and `(4, 2)` will work, and the proofs in `ordset.lean` assume `delta := 3` and `ratio := 2`. -/ def delta : ℕ := bit1 1 /-- **Internal use only** The ratio between an outer and inner sibling of the heavier subtree in an unbalanced setting. It determines whether a double or single rotation should be performed to restore balance. It is corresponds with the inverse of `α` in Adam's article. -/ def ratio : ℕ := bit0 1 /-- O(1). Construct a singleton set containing value `a`. singleton 3 = {3} -/ protected def singleton {α : Type u} (a : α) : ordnode α := node 1 nil a nil protected instance has_singleton {α : Type u} : has_singleton α (ordnode α) := has_singleton.mk ordnode.singleton /-- O(1). Get the size of the set. size {2, 1, 1, 4} = 3 -/ @[simp] def size {α : Type u} : ordnode α → ℕ := sorry /-- O(1). Is the set empty? empty ∅ = tt empty {1, 2, 3} = ff -/ def empty {α : Type u} : ordnode α → Bool := sorry /-- **Internal use only**, because it violates the BST property on the original order. O(n). The dual of a tree is a tree with its left and right sides reversed throughout. The dual of a valid BST is valid under the dual order. This is convenient for exploiting symmetries in the algorithms. -/ @[simp] def dual {α : Type u} : ordnode α → ordnode α := sorry /-- **Internal use only** O(1). Construct a node with the correct size information, without rebalancing. -/ def node' {α : Type u} (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := node (size l + size r + 1) l x r /-- Basic pretty printing for `ordnode α` that shows the structure of the tree. repr {3, 1, 2, 4} = ((∅ 1 ∅) 2 ((∅ 3 ∅) 4 ∅)) -/ def repr {α : Type u_1} [has_repr α] : ordnode α → string := sorry protected instance has_repr {α : Type u_1} [has_repr α] : has_repr (ordnode α) := has_repr.mk repr /-- **Internal use only** O(1). Rebalance a tree which was previously balanced but has had its left side grow by 1, or its right side shrink by 1. -/ -- Note: The function has been written with tactics to avoid extra junk def balance_l {α : Type u} (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := sorry /-- **Internal use only** O(1). Rebalance a tree which was previously balanced but has had its right side grow by 1, or its left side shrink by 1. -/ def balance_r {α : Type u} (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := sorry /-- **Internal use only** O(1). Rebalance a tree which was previously balanced but has had one side change by at most 1. -/ def balance {α : Type u} (l : ordnode α) (x : α) (r : ordnode α) : ordnode α := sorry /-- O(n). Does every element of the map satisfy property `P`? all (λ x, x < 5) {1, 2, 3} = true all (λ x, x < 5) {1, 2, 3, 5} = false -/ def all {α : Type u} (P : α → Prop) : ordnode α → Prop := sorry protected instance all.decidable {α : Type u} {P : α → Prop} [decidable_pred P] (t : ordnode α) : Decidable (all P t) := ordnode.rec (id decidable.true) (fun (t_size : ℕ) (t_l : ordnode α) (t_x : α) (t_r : ordnode α) (t_ih_l : Decidable (all P t_l)) (t_ih_r : Decidable (all P t_r)) => id and.decidable) t /-- O(n). Does any element of the map satisfy property `P`? any (λ x, x < 2) {1, 2, 3} = true any (λ x, x < 2) {2, 3, 5} = false -/ def any {α : Type u} (P : α → Prop) : ordnode α → Prop := sorry protected instance any.decidable {α : Type u} {P : α → Prop} [decidable_pred P] (t : ordnode α) : Decidable (any P t) := ordnode.rec (id decidable.false) (fun (t_size : ℕ) (t_l : ordnode α) (t_x : α) (t_r : ordnode α) (t_ih_l : Decidable (any P t_l)) (t_ih_r : Decidable (any P t_r)) => id or.decidable) t /-- O(n). Exact membership in the set. This is useful primarily for stating correctness properties; use `∈` for a version that actually uses the BST property of the tree. emem 2 {1, 2, 3} = true emem 4 {1, 2, 3} = false -/ def emem {α : Type u} (x : α) : ordnode α → Prop := any (Eq x) protected instance emem.decidable {α : Type u} [DecidableEq α] (x : α) (t : ordnode α) : Decidable (emem x t) := any.decidable /-- O(n). Approximate membership in the set, that is, whether some element in the set is equivalent to this one in the preorder. This is useful primarily for stating correctness properties; use `∈` for a version that actually uses the BST property of the tree. amem 2 {1, 2, 3} = true amem 4 {1, 2, 3} = false To see the difference with `emem`, we need a preorder that is not a partial order. For example, suppose we compare pairs of numbers using only their first coordinate. Then: emem (0, 1) {(0, 0), (1, 2)} = false amem (0, 1) {(0, 0), (1, 2)} = true (0, 1) ∈ {(0, 0), (1, 2)} = true The `∈` relation is equivalent to `amem` as long as the `ordnode` is well formed, and should always be used instead of `amem`. -/ def amem {α : Type u} [HasLessEq α] (x : α) : ordnode α → Prop := any fun (y : α) => x ≤ y ∧ y ≤ x protected instance amem.decidable {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) (t : ordnode α) : Decidable (amem x t) := any.decidable /-- O(log n). Return the minimum element of the tree, or the provided default value. find_min' 37 {1, 2, 3} = 1 find_min' 37 ∅ = 37 -/ def find_min' {α : Type u} : ordnode α → α → α := sorry /-- O(log n). Return the minimum element of the tree, if it exists. find_min {1, 2, 3} = some 1 find_min ∅ = none -/ def find_min {α : Type u} : ordnode α → Option α := sorry /-- O(log n). Return the maximum element of the tree, or the provided default value. find_max' 37 {1, 2, 3} = 3 find_max' 37 ∅ = 37 -/ def find_max' {α : Type u} : α → ordnode α → α := sorry /-- O(log n). Return the maximum element of the tree, if it exists. find_max {1, 2, 3} = some 3 find_max ∅ = none -/ def find_max {α : Type u} : ordnode α → Option α := sorry /-- O(log n). Remove the minimum element from the tree, or do nothing if it is already empty. erase_min {1, 2, 3} = {2, 3} erase_min ∅ = ∅ -/ def erase_min {α : Type u} : ordnode α → ordnode α := sorry /-- O(log n). Remove the maximum element from the tree, or do nothing if it is already empty. erase_max {1, 2, 3} = {1, 2} erase_max ∅ = ∅ -/ def erase_max {α : Type u} : ordnode α → ordnode α := sorry /-- **Internal use only**, because it requires a balancing constraint on the inputs. O(log n). Extract and remove the minimum element from a nonempty tree. -/ def split_min' {α : Type u} : ordnode α → α → ordnode α → α × ordnode α := sorry /-- O(log n). Extract and remove the minimum element from the tree, if it exists. split_min {1, 2, 3} = some (1, {2, 3}) split_min ∅ = none -/ def split_min {α : Type u} : ordnode α → Option (α × ordnode α) := sorry /-- **Internal use only**, because it requires a balancing constraint on the inputs. O(log n). Extract and remove the maximum element from a nonempty tree. -/ def split_max' {α : Type u} : ordnode α → α → ordnode α → ordnode α × α := sorry /-- O(log n). Extract and remove the maximum element from the tree, if it exists. split_max {1, 2, 3} = some ({1, 2}, 3) split_max ∅ = none -/ def split_max {α : Type u} : ordnode α → Option (ordnode α × α) := sorry /-- **Internal use only** O(log(m+n)). Concatenate two trees that are balanced and ordered with respect to each other. -/ def glue {α : Type u} : ordnode α → ordnode α → ordnode α := sorry /-- O(log(m+n)). Concatenate two trees that are ordered with respect to each other. merge {1, 2} {3, 4} = {1, 2, 3, 4} merge {3, 4} {1, 2} = precondition violation -/ def merge {α : Type u} (l : ordnode α) : ordnode α → ordnode α := ordnode.rec_on l (fun (r : ordnode α) => r) fun (ls : ℕ) (ll : ordnode α) (lx : α) (lr : ordnode α) (IHll IHlr : ordnode α → ordnode α) (r : ordnode α) => ordnode.rec_on r (node ls ll lx lr) fun (rs : ℕ) (rl : ordnode α) (rx : α) (rr IHrl IHrr : ordnode α) => ite (delta * ls < rs) (balance_l IHrl rx rr) (ite (delta * rs < ls) (balance_r ll lx (IHlr (node rs rl rx rr))) (glue (node ls ll lx lr) (node rs rl rx rr))) /-- O(log n). Insert an element above all the others, without any comparisons. (Assumes that the element is in fact above all the others). insert_max {1, 2} 4 = {1, 2, 4} insert_max {1, 2} 0 = precondition violation -/ def insert_max {α : Type u} : ordnode α → α → ordnode α := sorry /-- O(log n). Insert an element below all the others, without any comparisons. (Assumes that the element is in fact below all the others). insert_min {1, 2} 0 = {0, 1, 2} insert_min {1, 2} 4 = precondition violation -/ def insert_min {α : Type u} (x : α) : ordnode α → ordnode α := sorry /-- O(log(m+n)). Build a tree from an element between two trees, without any assumption on the relative sizes. link {1, 2} 4 {5, 6} = {1, 2, 4, 5, 6} link {1, 3} 2 {5} = precondition violation -/ def link {α : Type u} (l : ordnode α) (x : α) : ordnode α → ordnode α := ordnode.rec_on l (insert_min x) fun (ls : ℕ) (ll : ordnode α) (lx : α) (lr : ordnode α) (IHll IHlr : ordnode α → ordnode α) (r : ordnode α) => ordnode.rec_on r (insert_max l x) fun (rs : ℕ) (rl : ordnode α) (rx : α) (rr IHrl IHrr : ordnode α) => ite (delta * ls < rs) (balance_l IHrl rx rr) (ite (delta * rs < ls) (balance_r ll lx (IHlr r)) (node' l x r)) /-- O(n). Filter the elements of a tree satisfying a predicate. filter (λ x, x < 3) {1, 2, 4} = {1, 2} filter (λ x, x > 5) {1, 2, 4} = ∅ -/ def filter {α : Type u} (p : α → Prop) [decidable_pred p] : ordnode α → ordnode α := sorry /-- O(n). Split the elements of a tree into those satisfying, and not satisfying, a predicate. partition (λ x, x < 3) {1, 2, 4} = ({1, 2}, {3}) -/ def partition {α : Type u} (p : α → Prop) [decidable_pred p] : ordnode α → ordnode α × ordnode α := sorry /-- O(n). Map a function across a tree, without changing the structure. Only valid when the function is strictly monotonic, i.e. `x < y → f x < f y`. partition (λ x, x + 2) {1, 2, 4} = {2, 3, 6} partition (λ x : ℕ, x - 2) {1, 2, 4} = precondition violation -/ def map {α : Type u} {β : Type u_1} (f : α → β) : ordnode α → ordnode β := sorry /-- O(n). Fold a function across the structure of a tree. fold z f {1, 2, 4} = f (f z 1 z) 2 (f z 4 z) The exact structure of function applications depends on the tree and so is unspecified. -/ def fold {α : Type u} {β : Sort u_1} (z : β) (f : β → α → β → β) : ordnode α → β := sorry /-- O(n). Fold a function from left to right (in increasing order) across the tree. foldl f z {1, 2, 4} = f (f (f z 1) 2) 4 -/ def foldl {α : Type u} {β : Sort u_1} (f : β → α → β) : β → ordnode α → β := sorry /-- O(n). Fold a function from right to left (in decreasing order) across the tree. foldl f {1, 2, 4} z = f 1 (f 2 (f 4 z)) -/ def foldr {α : Type u} {β : Sort u_1} (f : α → β → β) : ordnode α → β → β := sorry /-- O(n). Build a list of elements in ascending order from the tree. to_list {1, 2, 4} = [1, 2, 4] to_list {2, 1, 1, 4} = [1, 2, 4] -/ def to_list {α : Type u} (t : ordnode α) : List α := foldr List.cons t [] /-- O(n). Build a list of elements in descending order from the tree. to_rev_list {1, 2, 4} = [4, 2, 1] to_rev_list {2, 1, 1, 4} = [4, 2, 1] -/ def to_rev_list {α : Type u} (t : ordnode α) : List α := foldl (flip List.cons) [] t protected instance has_to_string {α : Type u} [has_to_string α] : has_to_string (ordnode α) := has_to_string.mk fun (t : ordnode α) => string.str string.empty (char.of_nat (bit1 (bit1 (bit0 (bit1 (bit1 (bit1 1))))))) ++ string.intercalate (string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit1 (bit1 (bit0 1))))))) (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1))))))) (list.map to_string (to_list t)) ++ string.str string.empty (char.of_nat (bit1 (bit0 (bit1 (bit1 (bit1 (bit1 1))))))) /-- O(n). True if the trees have the same elements, ignoring structural differences. equiv {1, 2, 4} {2, 1, 1, 4} = true equiv {1, 2, 4} {1, 2, 3} = false -/ def equiv {α : Type u} (t₁ : ordnode α) (t₂ : ordnode α) := size t₁ = size t₂ ∧ to_list t₁ = to_list t₂ protected instance equiv.decidable_rel {α : Type u} [DecidableEq α] : DecidableRel equiv := fun (t₁ t₂ : ordnode α) => and.decidable /-- O(2^n). Constructs the powerset of a given set, that is, the set of all subsets. powerset {1, 2, 3} = {∅, {1}, {2}, {3}, {1,2}, {1,3}, {2,3}, {1,2,3}} -/ def powerset {α : Type u} (t : ordnode α) : ordnode (ordnode α) := insert_min nil (foldr (fun (x : α) (ts : ordnode (ordnode α)) => glue (insert_min (ordnode.singleton x) (map (insert_min x) ts)) ts) t nil) /-- O(m*n). The cartesian product of two sets: `(a, b) ∈ s.prod t` iff `a ∈ s` and `b ∈ t`. prod {1, 2} {2, 3} = {(1, 2), (1, 3), (2, 2), (2, 3)} -/ protected def prod {α : Type u} {β : Type u_1} (t₁ : ordnode α) (t₂ : ordnode β) : ordnode (α × β) := fold nil (fun (s₁ : ordnode (α × β)) (a : α) (s₂ : ordnode (α × β)) => merge s₁ (merge (map (Prod.mk a) t₂) s₂)) t₁ /-- O(m+n). Build a set on the disjoint union by combining sets on the factors. `inl a ∈ s.copair t` iff `a ∈ s`, and `inr b ∈ s.copair t` iff `b ∈ t`. copair {1, 2} {2, 3} = {inl 1, inl 2, inr 2, inr 3} -/ protected def copair {α : Type u} {β : Type u_1} (t₁ : ordnode α) (t₂ : ordnode β) : ordnode (α ⊕ β) := merge (map sum.inl t₁) (map sum.inr t₂) /-- O(n). Map a partial function across a set. The result depends on a proof that the function is defined on all members of the set. pmap (fin.mk : ∀ n, n < 4 → fin 4) {1, 2} H = {(1 : fin 4), (2 : fin 4)} -/ def pmap {α : Type u} {P : α → Prop} {β : Type u_1} (f : (a : α) → P a → β) (t : ordnode α) : all P t → ordnode β := sorry /-- O(n). "Attach" the information that every element of `t` satisfies property P to these elements inside the set, producing a set in the subtype. attach' (λ x, x < 4) {1, 2} H = ({1, 2} : ordnode {x // x<4}) -/ def attach' {α : Type u} {P : α → Prop} (t : ordnode α) : all P t → ordnode (Subtype fun (a : α) => P a) := pmap Subtype.mk /-- O(log n). Get the `i`th element of the set, by its index from left to right. nth {a, b, c, d} 2 = some c nth {a, b, c, d} 5 = none -/ def nth {α : Type u} : ordnode α → ℕ → Option α := sorry /-- O(log n). Remove the `i`th element of the set, by its index from left to right. remove_nth {a, b, c, d} 2 = {a, b, d} remove_nth {a, b, c, d} 5 = {a, b, c, d} -/ def remove_nth {α : Type u} : ordnode α → ℕ → ordnode α := sorry /-- Auxiliary definition for `take`. (Can also be used in lieu of `take` if you know the index is within the range of the data structure.) take_aux {a, b, c, d} 2 = {a, b} take_aux {a, b, c, d} 5 = {a, b, c, d} -/ def take_aux {α : Type u} : ordnode α → ℕ → ordnode α := sorry /-- O(log n). Get the first `i` elements of the set, counted from the left. take 2 {a, b, c, d} = {a, b} take 5 {a, b, c, d} = {a, b, c, d} -/ def take {α : Type u} (i : ℕ) (t : ordnode α) : ordnode α := ite (size t ≤ i) t (take_aux t i) /-- Auxiliary definition for `drop`. (Can also be used in lieu of `drop` if you know the index is within the range of the data structure.) drop_aux {a, b, c, d} 2 = {c, d} drop_aux {a, b, c, d} 5 = ∅ -/ def drop_aux {α : Type u} : ordnode α → ℕ → ordnode α := sorry /-- O(log n). Remove the first `i` elements of the set, counted from the left. drop 2 {a, b, c, d} = {c, d} drop 5 {a, b, c, d} = ∅ -/ def drop {α : Type u} (i : ℕ) (t : ordnode α) : ordnode α := ite (size t ≤ i) nil (drop_aux t i) /-- Auxiliary definition for `split_at`. (Can also be used in lieu of `split_at` if you know the index is within the range of the data structure.) split_at_aux {a, b, c, d} 2 = ({a, b}, {c, d}) split_at_aux {a, b, c, d} 5 = ({a, b, c, d}, ∅) -/ def split_at_aux {α : Type u} : ordnode α → ℕ → ordnode α × ordnode α := sorry /-- O(log n). Split a set at the `i`th element, getting the first `i` and everything else. split_at 2 {a, b, c, d} = ({a, b}, {c, d}) split_at 5 {a, b, c, d} = ({a, b, c, d}, ∅) -/ def split_at {α : Type u} (i : ℕ) (t : ordnode α) : ordnode α × ordnode α := ite (size t ≤ i) (t, nil) (split_at_aux t i) /-- O(log n). Get an initial segment of the set that satisfies the predicate `p`. `p` is required to be antitone, that is, `x < y → p y → p x`. take_while (λ x, x < 4) {1, 2, 3, 4, 5} = {1, 2, 3} take_while (λ x, x > 4) {1, 2, 3, 4, 5} = precondition violation -/ def take_while {α : Type u} (p : α → Prop) [decidable_pred p] : ordnode α → ordnode α := sorry /-- O(log n). Remove an initial segment of the set that satisfies the predicate `p`. `p` is required to be antitone, that is, `x < y → p y → p x`. drop_while (λ x, x < 4) {1, 2, 3, 4, 5} = {4, 5} drop_while (λ x, x > 4) {1, 2, 3, 4, 5} = precondition violation -/ def drop_while {α : Type u} (p : α → Prop) [decidable_pred p] : ordnode α → ordnode α := sorry /-- O(log n). Split the set into those satisfying and not satisfying the predicate `p`. `p` is required to be antitone, that is, `x < y → p y → p x`. span (λ x, x < 4) {1, 2, 3, 4, 5} = ({1, 2, 3}, {4, 5}) span (λ x, x > 4) {1, 2, 3, 4, 5} = precondition violation -/ def span {α : Type u} (p : α → Prop) [decidable_pred p] : ordnode α → ordnode α × ordnode α := sorry /-- Auxiliary definition for `of_asc_list`. **Note:** This function is defined by well founded recursion, so it will probably not compute in the kernel, meaning that you probably can't prove things like `of_asc_list [1, 2, 3] = {1, 2, 3}` by `rfl`. This implementation is optimized for VM evaluation. -/ def of_asc_list_aux₁ {α : Type u} (l : List α) : ℕ → ordnode α × Subtype fun (l' : List α) => list.length l' ≤ list.length l := sorry /-- Auxiliary definition for `of_asc_list`. -/ def of_asc_list_aux₂ {α : Type u} : List α → ordnode α → ℕ → ordnode α := sorry /-- O(n). Build a set from a list which is already sorted. Performs no comparisons. of_asc_list [1, 2, 3] = {1, 2, 3} of_asc_list [3, 2, 1] = precondition violation -/ def of_asc_list {α : Type u} : List α → ordnode α := sorry /-- O(log n). Does the set (approximately) contain the element `x`? That is, is there an element that is equivalent to `x` in the order? 1 ∈ {1, 2, 3} = true 4 ∈ {1, 2, 3} = false Using a preorder on `ℕ × ℕ` that only compares the first coordinate: (1, 1) ∈ {(0, 1), (1, 2)} = true (3, 1) ∈ {(0, 1), (1, 2)} = false -/ def mem {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → Bool := sorry /-- O(log n). Retrieve an element in the set that is equivalent to `x` in the order, if it exists. find 1 {1, 2, 3} = some 1 find 4 {1, 2, 3} = none Using a preorder on `ℕ × ℕ` that only compares the first coordinate: find (1, 1) {(0, 1), (1, 2)} = some (1, 2) find (3, 1) {(0, 1), (1, 2)} = none -/ def find {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → Option α := sorry protected instance has_mem {α : Type u} [HasLessEq α] [DecidableRel LessEq] : has_mem α (ordnode α) := has_mem.mk fun (x : α) (t : ordnode α) => ↥(mem x t) protected instance mem.decidable {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) (t : ordnode α) : Decidable (x ∈ t) := bool.decidable_eq (mem x t) tt /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the function `f` is used to generate the element to insert (being passed the current value in the set). insert_with f 0 {1, 2, 3} = {0, 1, 2, 3} insert_with f 1 {1, 2, 3} = {f 1, 2, 3} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: insert_with f (1, 1) {(0, 1), (1, 2)} = {(0, 1), f (1, 2)} insert_with f (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2), (3, 1)} -/ def insert_with {α : Type u} [HasLessEq α] [DecidableRel LessEq] (f : α → α) (x : α) : ordnode α → ordnode α := sorry /-- O(log n). Modify an element in the set with the given function, doing nothing if the key is not found. Note that the element returned by `f` must be equivalent to `x`. adjust_with f 0 {1, 2, 3} = {1, 2, 3} adjust_with f 1 {1, 2, 3} = {f 1, 2, 3} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: adjust_with f (1, 1) {(0, 1), (1, 2)} = {(0, 1), f (1, 2)} adjust_with f (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2)} -/ def adjust_with {α : Type u} [HasLessEq α] [DecidableRel LessEq] (f : α → α) (x : α) : ordnode α → ordnode α := sorry /-- O(log n). Modify an element in the set with the given function, doing nothing if the key is not found. Note that the element returned by `f` must be equivalent to `x`. update_with f 0 {1, 2, 3} = {1, 2, 3} update_with f 1 {1, 2, 3} = {2, 3} if f 1 = none = {a, 2, 3} if f 1 = some a -/ def update_with {α : Type u} [HasLessEq α] [DecidableRel LessEq] (f : α → Option α) (x : α) : ordnode α → ordnode α := sorry /-- O(log n). Modify an element in the set with the given function, doing nothing if the key is not found. Note that the element returned by `f` must be equivalent to `x`. alter f 0 {1, 2, 3} = {1, 2, 3} if f none = none = {a, 1, 2, 3} if f none = some a alter f 1 {1, 2, 3} = {2, 3} if f 1 = none = {a, 2, 3} if f 1 = some a -/ def alter {α : Type u} [HasLessEq α] [DecidableRel LessEq] (f : Option α → Option α) (x : α) : ordnode α → ordnode α := sorry /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, this replaces it. insert 1 {1, 2, 3} = {1, 2, 3} insert 4 {1, 2, 3} = {1, 2, 3, 4} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: insert (1, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 1)} insert (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2), (3, 1)} -/ protected def insert {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → ordnode α := sorry protected instance has_insert {α : Type u} [HasLessEq α] [DecidableRel LessEq] : has_insert α (ordnode α) := has_insert.mk ordnode.insert /-- O(log n). Insert an element into the set, preserving balance and the BST property. If an equivalent element is already in the set, the set is returned as is. insert' 1 {1, 2, 3} = {1, 2, 3} insert' 4 {1, 2, 3} = {1, 2, 3, 4} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: insert' (1, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2)} insert' (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2), (3, 1)} -/ def insert' {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → ordnode α := sorry /-- O(log n). Split the tree into those smaller than `x` and those greater than it. If an element equivalent to `x` is in the set, it is discarded. split 2 {1, 2, 4} = ({1}, {4}) split 3 {1, 2, 4} = ({1, 2}, {4}) split 4 {1, 2, 4} = ({1, 2}, ∅) Using a preorder on `ℕ × ℕ` that only compares the first coordinate: split (1, 1) {(0, 1), (1, 2)} = ({(0, 1)}, ∅) split (3, 1) {(0, 1), (1, 2)} = ({(0, 1), (1, 2)}, ∅) -/ def split {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → ordnode α × ordnode α := sorry /-- O(log n). Split the tree into those smaller than `x` and those greater than it, plus an element equivalent to `x`, if it exists. split 2 {1, 2, 4} = ({1}, some 2, {4}) split 3 {1, 2, 4} = ({1, 2}, none, {4}) split 4 {1, 2, 4} = ({1, 2}, some 4, ∅) Using a preorder on `ℕ × ℕ` that only compares the first coordinate: split (1, 1) {(0, 1), (1, 2)} = ({(0, 1)}, some (1, 2), ∅) split (3, 1) {(0, 1), (1, 2)} = ({(0, 1), (1, 2)}, none, ∅) -/ def split3 {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → ordnode α × Option α × ordnode α := sorry /-- O(log n). Remove an element from the set equivalent to `x`. Does nothing if there is no such element. erase 1 {1, 2, 3} = {2, 3} erase 4 {1, 2, 3} = {1, 2, 3} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: erase (1, 1) {(0, 1), (1, 2)} = {(0, 1)} erase (3, 1) {(0, 1), (1, 2)} = {(0, 1), (1, 2)} -/ def erase {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → ordnode α := sorry /-- Auxiliary definition for `find_lt`. -/ def find_lt_aux {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → α → α := sorry /-- O(log n). Get the largest element in the tree that is `< x`. find_lt 2 {1, 2, 4} = some 1 find_lt 3 {1, 2, 4} = some 2 find_lt 0 {1, 2, 4} = none -/ def find_lt {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → Option α := sorry /-- Auxiliary definition for `find_gt`. -/ def find_gt_aux {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → α → α := sorry /-- O(log n). Get the smallest element in the tree that is `> x`. find_lt 2 {1, 2, 4} = some 4 find_lt 3 {1, 2, 4} = some 4 find_lt 4 {1, 2, 4} = none -/ def find_gt {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → Option α := sorry /-- Auxiliary definition for `find_le`. -/ def find_le_aux {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → α → α := sorry /-- O(log n). Get the largest element in the tree that is `≤ x`. find_le 2 {1, 2, 4} = some 2 find_le 3 {1, 2, 4} = some 2 find_le 0 {1, 2, 4} = none -/ def find_le {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → Option α := sorry /-- Auxiliary definition for `find_ge`. -/ def find_ge_aux {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → α → α := sorry /-- O(log n). Get the smallest element in the tree that is `≥ x`. find_le 2 {1, 2, 4} = some 2 find_le 3 {1, 2, 4} = some 4 find_le 5 {1, 2, 4} = none -/ def find_ge {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → Option α := sorry /-- Auxiliary definition for `find_index`. -/ def find_index_aux {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) : ordnode α → ℕ → Option ℕ := sorry /-- O(log n). Get the index, counting from the left, of an element equivalent to `x` if it exists. find_index 2 {1, 2, 4} = some 1 find_index 4 {1, 2, 4} = some 2 find_index 5 {1, 2, 4} = none -/ def find_index {α : Type u} [HasLessEq α] [DecidableRel LessEq] (x : α) (t : ordnode α) : Option ℕ := find_index_aux x t 0 /-- Auxiliary definition for `is_subset`. -/ def is_subset_aux {α : Type u} [HasLessEq α] [DecidableRel LessEq] : ordnode α → ordnode α → Bool := sorry /-- O(m+n). Is every element of `t₁` equivalent to some element of `t₂`? is_subset {1, 4} {1, 2, 4} = tt is_subset {1, 3} {1, 2, 4} = ff -/ def is_subset {α : Type u} [HasLessEq α] [DecidableRel LessEq] (t₁ : ordnode α) (t₂ : ordnode α) : Bool := to_bool (size t₁ ≤ size t₂) && is_subset_aux t₁ t₂ /-- O(m+n). Is every element of `t₁` not equivalent to any element of `t₂`? disjoint {1, 3} {2, 4} = tt disjoint {1, 2} {2, 4} = ff -/ def disjoint {α : Type u} [HasLessEq α] [DecidableRel LessEq] : ordnode α → ordnode α → Bool := sorry /-- O(m * log(|m ∪ n| + 1)), m ≤ n. The union of two sets, preferring members of `t₁` over those of `t₂` when equivalent elements are encountered. union {1, 2} {2, 3} = {1, 2, 3} union {1, 3} {2} = {1, 2, 3} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: union {(1, 1)} {(0, 1), (1, 2)} = {(0, 1), (1, 1)} -/ def union {α : Type u} [HasLessEq α] [DecidableRel LessEq] : ordnode α → ordnode α → ordnode α := sorry /-- O(m * log(|m ∪ n| + 1)), m ≤ n. Difference of two sets. diff {1, 2} {2, 3} = {1} diff {1, 2, 3} {2} = {1, 3} -/ def diff {α : Type u} [HasLessEq α] [DecidableRel LessEq] : ordnode α → ordnode α → ordnode α := sorry /-- O(m * log(|m ∪ n| + 1)), m ≤ n. Intersection of two sets, preferring members of `t₁` over those of `t₂` when equivalent elements are encountered. inter {1, 2} {2, 3} = {2} inter {1, 3} {2} = ∅ -/ def inter {α : Type u} [HasLessEq α] [DecidableRel LessEq] : ordnode α → ordnode α → ordnode α := sorry /-- O(n * log n). Build a set from a list, preferring elements that appear earlier in the list in the case of equivalent elements. of_list [1, 2, 3] = {1, 2, 3} of_list [2, 1, 1, 3] = {1, 2, 3} Using a preorder on `ℕ × ℕ` that only compares the first coordinate: of_list [(1, 1), (0, 1), (1, 2)] = {(0, 1), (1, 1)} -/ def of_list {α : Type u} [HasLessEq α] [DecidableRel LessEq] (l : List α) : ordnode α := list.foldr insert nil l /-- O(n * log n). Adaptively chooses between the linear and log-linear algorithm depending on whether the input list is already sorted. of_list' [1, 2, 3] = {1, 2, 3} of_list' [2, 1, 1, 3] = {1, 2, 3} -/ def of_list' {α : Type u} [HasLessEq α] [DecidableRel LessEq] : List α → ordnode α := sorry /-- O(n * log n). Map a function on a set. Unlike `map` this has no requirements on `f`, and the resulting set may be smaller than the input if `f` is noninjective. Equivalent elements are selected with a preference for smaller source elements. image (λ x, x + 2) {1, 2, 4} = {3, 4, 6} image (λ x : ℕ, x - 2) {1, 2, 4} = {0, 2} -/ def image {α : Type u_1} {β : Type u_2} [HasLessEq β] [DecidableRel LessEq] (f : α → β) (t : ordnode α) : ordnode β := of_list (list.map f (to_list t))
d0bb09d2c1499714f9b5a224deddc5a0172ff59b
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/order/filter/at_top_bot.lean
06e8429575ece09e73b51ece304207faff63c8e0
[ "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
61,695
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov, Patrick Massot -/ import order.filter.bases import data.finset.preimage /-! # `at_top` and `at_bot` filters on preorded sets, monoids and groups. In this file we define the filters * `at_top`: corresponds to `n → +∞`; * `at_bot`: corresponds to `n → -∞`. Then we prove many lemmas like “if `f → +∞`, then `f ± c → +∞`”. -/ variables {ι ι' α β γ : Type*} open set open_locale classical filter big_operators namespace filter /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, 𝓟 (Ici a) /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, 𝓟 (Iic a) lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ := mem_infi_of_mem a $ subset.refl _ lemma Ioi_mem_at_top [preorder α] [no_top_order α] (x : α) : Ioi x ∈ (at_top : filter α) := let ⟨z, hz⟩ := no_top x in mem_of_superset (mem_at_top z) $ λ y h, lt_of_lt_of_le hz h lemma mem_at_bot [preorder α] (a : α) : {b : α | b ≤ a} ∈ @at_bot α _ := mem_infi_of_mem a $ subset.refl _ lemma Iio_mem_at_bot [preorder α] [no_bot_order α] (x : α) : Iio x ∈ (at_bot : filter α) := let ⟨z, hz⟩ := no_bot x in mem_of_superset (mem_at_bot z) $ λ y h, lt_of_le_of_lt h hz lemma at_top_basis [nonempty α] [semilattice_sup α] : (@at_top α _).has_basis (λ _, true) Ici := has_basis_infi_principal (directed_of_sup $ λ a b, Ici_subset_Ici.2) lemma at_top_basis' [semilattice_sup α] (a : α) : (@at_top α _).has_basis (λ x, a ≤ x) Ici := ⟨λ t, (@at_top_basis α ⟨a⟩ _).mem_iff.trans ⟨λ ⟨x, _, hx⟩, ⟨x ⊔ a, le_sup_right, λ y hy, hx (le_trans le_sup_left hy)⟩, λ ⟨x, _, hx⟩, ⟨x, trivial, hx⟩⟩⟩ lemma at_bot_basis [nonempty α] [semilattice_inf α] : (@at_bot α _).has_basis (λ _, true) Iic := @at_top_basis (order_dual α) _ _ lemma at_bot_basis' [semilattice_inf α] (a : α) : (@at_bot α _).has_basis (λ x, x ≤ a) Iic := @at_top_basis' (order_dual α) _ _ @[instance] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : ne_bot (at_top : filter α) := at_top_basis.ne_bot_iff.2 $ λ a _, nonempty_Ici @[instance] lemma at_bot_ne_bot [nonempty α] [semilattice_inf α] : ne_bot (at_bot : filter α) := @at_top_ne_bot (order_dual α) _ _ @[simp] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := at_top_basis.mem_iff.trans $ exists_congr $ λ _, exists_const _ @[simp] lemma mem_at_bot_sets [nonempty α] [semilattice_inf α] {s : set α} : s ∈ (at_bot : filter α) ↔ ∃a:α, ∀b≤a, b ∈ s := @mem_at_top_sets (order_dual α) _ _ _ @[simp] lemma eventually_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ b ≥ a, p b) := mem_at_top_sets @[simp] lemma eventually_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ b ≤ a, p b) := mem_at_bot_sets lemma eventually_ge_at_top [preorder α] (a : α) : ∀ᶠ x in at_top, a ≤ x := mem_at_top a lemma eventually_le_at_bot [preorder α] (a : α) : ∀ᶠ x in at_bot, x ≤ a := mem_at_bot a lemma eventually_gt_at_top [preorder α] [no_top_order α] (a : α) : ∀ᶠ x in at_top, a < x := Ioi_mem_at_top a lemma eventually_lt_at_bot [preorder α] [no_bot_order α] (a : α) : ∀ᶠ x in at_bot, x < a := Iio_mem_at_bot a lemma at_top_basis_Ioi [nonempty α] [semilattice_sup α] [no_top_order α] : (@at_top α _).has_basis (λ _, true) Ioi := at_top_basis.to_has_basis (λ a ha, ⟨a, ha, Ioi_subset_Ici_self⟩) $ λ a ha, (no_top a).imp $ λ b hb, ⟨ha, Ici_subset_Ioi.2 hb⟩ lemma at_top_countable_basis [nonempty α] [semilattice_sup α] [encodable α] : has_countable_basis (at_top : filter α) (λ _, true) Ici := { countable := countable_encodable _, .. at_top_basis } lemma at_bot_countable_basis [nonempty α] [semilattice_inf α] [encodable α] : has_countable_basis (at_bot : filter α) (λ _, true) Iic := { countable := countable_encodable _, .. at_bot_basis } lemma is_countably_generated_at_top [nonempty α] [semilattice_sup α] [encodable α] : (at_top : filter $ α).is_countably_generated := at_top_countable_basis.is_countably_generated lemma is_countably_generated_at_bot [nonempty α] [semilattice_inf α] [encodable α] : (at_bot : filter $ α).is_countably_generated := at_bot_countable_basis.is_countably_generated lemma order_top.at_top_eq (α) [order_top α] : (at_top : filter α) = pure ⊤ := le_antisymm (le_pure_iff.2 $ (eventually_ge_at_top ⊤).mono $ λ b, top_unique) (le_infi $ λ b, le_principal_iff.2 le_top) lemma order_bot.at_bot_eq (α) [order_bot α] : (at_bot : filter α) = pure ⊥ := @order_top.at_top_eq (order_dual α) _ @[nontriviality] lemma subsingleton.at_top_eq (α) [subsingleton α] [preorder α] : (at_top : filter α) = ⊤ := begin refine top_unique (λ s hs x, _), letI : unique α := ⟨⟨x⟩, λ y, subsingleton.elim y x⟩, rw [at_top, infi_unique, unique.default_eq x, mem_principal] at hs, exact hs left_mem_Ici end @[nontriviality] lemma subsingleton.at_bot_eq (α) [subsingleton α] [preorder α] : (at_bot : filter α) = ⊤ := @subsingleton.at_top_eq (order_dual α) _ _ lemma tendsto_at_top_pure [order_top α] (f : α → β) : tendsto f at_top (pure $ f ⊤) := (order_top.at_top_eq α).symm ▸ tendsto_pure_pure _ _ lemma tendsto_at_bot_pure [order_bot α] (f : α → β) : tendsto f at_bot (pure $ f ⊥) := @tendsto_at_top_pure (order_dual α) _ _ _ lemma eventually.exists_forall_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_top, p x) : ∃ a, ∀ b ≥ a, p b := eventually_at_top.mp h lemma eventually.exists_forall_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_bot, p x) : ∃ a, ∀ b ≤ a, p b := eventually_at_bot.mp h lemma frequently_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b ≥ a, p b) := by simp [at_top_basis.frequently_iff] lemma frequently_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b ≤ a, p b) := @frequently_at_top (order_dual α) _ _ _ lemma frequently_at_top' [semilattice_sup α] [nonempty α] [no_top_order α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b > a, p b) := by simp [at_top_basis_Ioi.frequently_iff] lemma frequently_at_bot' [semilattice_inf α] [nonempty α] [no_bot_order α] {p : α → Prop} : (∃ᶠ x in at_bot, p x) ↔ (∀ a, ∃ b < a, p b) := @frequently_at_top' (order_dual α) _ _ _ _ lemma frequently.forall_exists_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_top, p x) : ∀ a, ∃ b ≥ a, p b := frequently_at_top.mp h lemma frequently.forall_exists_of_at_bot [semilattice_inf α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_bot, p x) : ∀ a, ∃ b ≤ a, p b := frequently_at_bot.mp h lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, 𝓟 $ f '' {a' | a ≤ a'}) := (at_top_basis.map _).eq_infi lemma map_at_bot_eq [nonempty α] [semilattice_inf α] {f : α → β} : at_bot.map f = (⨅a, 𝓟 $ f '' {a' | a' ≤ a}) := @map_at_top_eq (order_dual α) _ _ _ _ lemma tendsto_at_top [preorder β] {m : α → β} {f : filter α} : tendsto m f at_top ↔ (∀b, ∀ᶠ a in f, b ≤ m a) := by simp only [at_top, tendsto_infi, tendsto_principal, mem_Ici] lemma tendsto_at_bot [preorder β] {m : α → β} {f : filter α} : tendsto m f at_bot ↔ (∀b, ∀ᶠ a in f, m a ≤ b) := @tendsto_at_top α (order_dual β) _ m f lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₁ l at_top → tendsto f₂ l at_top := assume h₁, tendsto_at_top.2 $ λ b, mp_mem (tendsto_at_top.1 h₁ b) (monotone_mem (λ a ha ha₁, le_trans ha₁ ha) h) lemma tendsto_at_bot_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₂ l at_bot → tendsto f₁ l at_bot := @tendsto_at_top_mono' _ (order_dual β) _ _ _ _ h lemma tendsto_at_top_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto f l at_top → tendsto g l at_top := tendsto_at_top_mono' l $ eventually_of_forall h lemma tendsto_at_bot_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto g l at_bot → tendsto f l at_bot := @tendsto_at_top_mono _ (order_dual β) _ _ _ _ h /-! ### Sequences -/ lemma inf_map_at_top_ne_bot_iff [semilattice_sup α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_top)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≥ N, u n ∈ U := by simp_rw [inf_ne_bot_iff_frequently_left, frequently_map, frequently_at_top]; refl lemma inf_map_at_bot_ne_bot_iff [semilattice_inf α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_bot)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≤ N, u n ∈ U := @inf_map_at_top_ne_bot_iff (order_dual α) _ _ _ _ _ lemma extraction_of_frequently_at_top' {P : ℕ → Prop} (h : ∀ N, ∃ n > N, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin choose u hu using h, cases forall_and_distrib.mp hu with hu hu', exact ⟨u ∘ (nat.rec 0 (λ n v, u v)), strict_mono_nat_of_lt_succ (λ n, hu _), λ n, hu' _⟩, end lemma extraction_of_frequently_at_top {P : ℕ → Prop} (h : ∃ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin rw frequently_at_top' at h, exact extraction_of_frequently_at_top' h, end lemma extraction_of_eventually_at_top {P : ℕ → Prop} (h : ∀ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := extraction_of_frequently_at_top h.frequently lemma extraction_forall_of_frequently {P : ℕ → ℕ → Prop} (h : ∀ n, ∃ᶠ k in at_top, P n k) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) := begin simp only [frequently_at_top'] at h, choose u hu hu' using h, use (λ n, nat.rec_on n (u 0 0) (λ n v, u (n+1) v) : ℕ → ℕ), split, { apply strict_mono_nat_of_lt_succ, intro n, apply hu }, { intros n, cases n ; simp [hu'] }, end lemma extraction_forall_of_eventually {P : ℕ → ℕ → Prop} (h : ∀ n, ∀ᶠ k in at_top, P n k) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) := extraction_forall_of_frequently (λ n, (h n).frequently) lemma extraction_forall_of_eventually' {P : ℕ → ℕ → Prop} (h : ∀ n, ∃ N, ∀ k ≥ N, P n k) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P n (φ n) := extraction_forall_of_eventually (by simp [eventually_at_top, h]) lemma exists_le_of_tendsto_at_top [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b ≤ u a' := begin have : ∀ᶠ x in at_top, a ≤ x ∧ b ≤ u x := (eventually_ge_at_top a).and (h.eventually $ eventually_ge_at_top b), haveI : nonempty α := ⟨a⟩, rcases this.exists with ⟨a', ha, hb⟩, exact ⟨a', ha, hb⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_le_of_tendsto_at_bot [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' ≤ b := @exists_le_of_tendsto_at_top _ (order_dual β) _ _ _ h lemma exists_lt_of_tendsto_at_top [semilattice_sup α] [preorder β] [no_top_order β] {u : α → β} (h : tendsto u at_top at_top) (a : α) (b : β) : ∃ a' ≥ a, b < u a' := begin cases no_top b with b' hb', rcases exists_le_of_tendsto_at_top h a b' with ⟨a', ha', ha''⟩, exact ⟨a', ha', lt_of_lt_of_le hb' ha''⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_lt_of_tendsto_at_bot [semilattice_sup α] [preorder β] [no_bot_order β] {u : α → β} (h : tendsto u at_top at_bot) : ∀ a b, ∃ a' ≥ a, u a' < b := @exists_lt_of_tendsto_at_top _ (order_dual β) _ _ _ _ h /-- If `u` is a sequence which is unbounded above, then after any point, it reaches a value strictly greater than all previous values. -/ lemma high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∀ N, ∃ n ≥ N, ∀ k < n, u k < u n := begin intros N, obtain ⟨k : ℕ, hkn : k ≤ N, hku : ∀ l ≤ N, u l ≤ u k⟩ : ∃ k ≤ N, ∀ l ≤ N, u l ≤ u k, from exists_max_image _ u (finite_le_nat N) ⟨N, le_refl N⟩, have ex : ∃ n ≥ N, u k < u n, from exists_lt_of_tendsto_at_top hu _ _, obtain ⟨n : ℕ, hnN : n ≥ N, hnk : u k < u n, hn_min : ∀ m, m < n → N ≤ m → u m ≤ u k⟩ : ∃ n ≥ N, u k < u n ∧ ∀ m, m < n → N ≤ m → u m ≤ u k, { rcases nat.find_x ex with ⟨n, ⟨hnN, hnk⟩, hn_min⟩, push_neg at hn_min, exact ⟨n, hnN, hnk, hn_min⟩ }, use [n, hnN], rintros (l : ℕ) (hl : l < n), have hlk : u l ≤ u k, { cases (le_total l N : l ≤ N ∨ N ≤ l) with H H, { exact hku l H }, { exact hn_min l hl H } }, calc u l ≤ u k : hlk ... < u n : hnk end /-- If `u` is a sequence which is unbounded below, then after any point, it reaches a value strictly smaller than all previous values. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∀ N, ∃ n ≥ N, ∀ k < n, u n < u k := @high_scores (order_dual β) _ _ _ hu /-- If `u` is a sequence which is unbounded above, then it `frequently` reaches a value strictly greater than all previous values. -/ lemma frequently_high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ᶠ n in at_top, ∀ k < n, u k < u n := by simpa [frequently_at_top] using high_scores hu /-- If `u` is a sequence which is unbounded below, then it `frequently` reaches a value strictly smaller than all previous values. -/ lemma frequently_low_scores [linear_order β] [no_bot_order β] {u : ℕ → β} (hu : tendsto u at_top at_bot) : ∃ᶠ n in at_top, ∀ k < n, u n < u k := @frequently_high_scores (order_dual β) _ _ _ hu lemma strict_mono_subseq_of_tendsto_at_top {β : Type*} [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := let ⟨φ, h, h'⟩ := extraction_of_frequently_at_top (frequently_high_scores hu) in ⟨φ, h, λ n m hnm, h' m _ (h hnm)⟩ lemma strict_mono_subseq_of_id_le {u : ℕ → ℕ} (hu : ∀ n, n ≤ u n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := strict_mono_subseq_of_tendsto_at_top (tendsto_at_top_mono hu tendsto_id) lemma _root_.strict_mono.tendsto_at_top {φ : ℕ → ℕ} (h : strict_mono φ) : tendsto φ at_top at_top := tendsto_at_top_mono h.id_le tendsto_id section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_add_nonneg_left' (hf : ∀ᶠ x in l, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (hf.mono (λ x, le_add_of_nonneg_left)) hg lemma tendsto_at_bot_add_nonpos_left' (hf : ∀ᶠ x in l, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (eventually_of_forall hf) hg lemma tendsto_at_bot_add_nonpos_left (hf : ∀ x, f x ≤ 0) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_left _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem (λ x, le_add_of_nonneg_right) hg) hf lemma tendsto_at_bot_add_nonpos_right' (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right' _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_right' hf (eventually_of_forall hg) lemma tendsto_at_bot_add_nonpos_right (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ 0) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_nonneg_right _ (order_dual β) _ _ _ _ hf hg lemma tendsto_at_top_add (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (tendsto_at_top.mp hf 0) hg lemma tendsto_at_bot_add (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add _ (order_dual β) _ _ _ _ hf hg lemma tendsto.nsmul_at_top (hf : tendsto f l at_top) {n : ℕ} (hn : 0 < n) : tendsto (λ x, n • f x) l at_top := tendsto_at_top.2 $ λ y, (tendsto_at_top.1 hf y).mp $ (tendsto_at_top.1 hf 0).mono $ λ x h₀ hy, calc y ≤ f x : hy ... = 1 • f x : (one_nsmul _).symm ... ≤ n • f x : nsmul_le_nsmul h₀ hn lemma tendsto.nsmul_at_bot (hf : tendsto f l at_bot) {n : ℕ} (hn : 0 < n) : tendsto (λ x, n • f x) l at_bot := @tendsto.nsmul_at_top α (order_dual β) _ l f hf n hn lemma tendsto_bit0_at_top : tendsto bit0 (at_top : filter β) at_top := tendsto_at_top_add tendsto_id tendsto_id lemma tendsto_bit0_at_bot : tendsto bit0 (at_bot : filter β) at_bot := tendsto_at_bot_add tendsto_id tendsto_id end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (C + b)).mono (λ x, le_of_add_le_add_left) lemma tendsto_at_bot_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ assume b, (tendsto_at_top.1 hf (b + C)).mono (λ x, le_of_add_le_add_right) lemma tendsto_at_bot_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_const_right _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : ∀ᶠ x in l, f x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_right hx (g x))) h) lemma tendsto_at_bot_of_add_bdd_below_left' (C) (hC : ∀ᶠ x in l, C ≤ f x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' C (univ_mem' hC) lemma tendsto_at_bot_of_add_bdd_below_left (C) (hC : ∀ x, C ≤ f x) : tendsto (λ x, f x + g x) l at_bot → tendsto g l at_bot := @tendsto_at_top_of_add_bdd_above_left _ (order_dual β) _ _ _ _ C hC lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : ∀ᶠ x in l, g x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_left hx (f x))) h) lemma tendsto_at_bot_of_add_bdd_below_right' (C) (hC : ∀ᶠ x in l, C ≤ g x) (h : tendsto (λ x, f x + g x) l at_bot) : tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right' _ (order_dual β) _ _ _ _ C hC h lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' C (univ_mem' hC) lemma tendsto_at_bot_of_add_bdd_below_right (C) (hC : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_bot → tendsto f l at_bot := @tendsto_at_top_of_add_bdd_above_right _ (order_dual β) _ _ _ _ C hC end ordered_cancel_add_comm_monoid section ordered_group variables [ordered_add_comm_group β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_left_of_le' (C : β) (hf : ∀ᶠ x in l, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C) (by simpa) (by simpa) lemma tendsto_at_bot_add_left_of_ge' (C : β) (hf : ∀ᶠ x in l, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem' hf) hg lemma tendsto_at_bot_add_left_of_ge (C : β) (hf : ∀ x, f x ≤ C) (hg : tendsto g l at_bot) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_left_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C) (by simp [hg]) (by simp [hf]) lemma tendsto_at_bot_add_right_of_ge' (C : β) (hf : tendsto f l at_bot) (hg : ∀ᶠ x in l, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le' _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem' hg) lemma tendsto_at_bot_add_right_of_ge (C : β) (hf : tendsto f l at_bot) (hg : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_bot := @tendsto_at_top_add_right_of_le _ (order_dual β) _ _ _ _ C hf hg lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) : tendsto (λ x, C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem' $ λ _, le_refl C) hf lemma tendsto_at_bot_add_const_left (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, C + f x) l at_bot := @tendsto_at_top_add_const_left _ (order_dual β) _ _ _ C hf lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) : tendsto (λ x, f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem' $ λ _, le_refl C) lemma tendsto_at_bot_add_const_right (C : β) (hf : tendsto f l at_bot) : tendsto (λ x, f x + C) l at_bot := @tendsto_at_top_add_const_right _ (order_dual β) _ _ _ C hf lemma tendsto_neg_at_top_at_bot : tendsto (has_neg.neg : β → β) at_top at_bot := begin simp only [tendsto_at_bot, neg_le], exact λ b, eventually_ge_at_top _ end lemma tendsto_neg_at_bot_at_top : tendsto (has_neg.neg : β → β) at_bot at_top := @tendsto_neg_at_top_at_bot (order_dual β) _ end ordered_group section ordered_semiring variables [ordered_semiring α] {l : filter β} {f g : β → α} lemma tendsto_bit1_at_top : tendsto bit1 (at_top : filter α) at_top := tendsto_at_top_add_nonneg_right tendsto_bit0_at_top (λ _, zero_le_one) lemma tendsto.at_top_mul_at_top (hf : tendsto f l at_top) (hg : tendsto g l at_top) : tendsto (λ x, f x * g x) l at_top := begin refine tendsto_at_top_mono' _ _ hg, filter_upwards [hg.eventually (eventually_ge_at_top 0), hf.eventually (eventually_ge_at_top 1)], exact λ x, le_mul_of_one_le_left end lemma tendsto_mul_self_at_top : tendsto (λ x : α, x * x) at_top at_top := tendsto_id.at_top_mul_at_top tendsto_id /-- The monomial function `x^n` tends to `+∞` at `+∞` for any positive natural `n`. A version for positive real powers exists as `tendsto_rpow_at_top`. -/ lemma tendsto_pow_at_top {n : ℕ} (hn : 1 ≤ n) : tendsto (λ x : α, x ^ n) at_top at_top := begin refine tendsto_at_top_mono' _ ((eventually_ge_at_top 1).mono $ λ x hx, _) tendsto_id, simpa only [pow_one] using pow_le_pow hx hn end end ordered_semiring lemma zero_pow_eventually_eq [monoid_with_zero α] : (λ n : ℕ, (0 : α) ^ n) =ᶠ[at_top] (λ n, 0) := eventually_at_top.2 ⟨1, λ n hn, zero_pow (zero_lt_one.trans_le hn)⟩ section ordered_ring variables [ordered_ring α] {l : filter β} {f g : β → α} lemma tendsto.at_top_mul_at_bot (hf : tendsto f l at_top) (hg : tendsto g l at_bot) : tendsto (λ x, f x * g x) l at_bot := have _ := (hf.at_top_mul_at_top $ tendsto_neg_at_bot_at_top.comp hg), by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp this lemma tendsto.at_bot_mul_at_top (hf : tendsto f l at_bot) (hg : tendsto g l at_top) : tendsto (λ x, f x * g x) l at_bot := have tendsto (λ x, (-f x) * g x) l at_top := ( (tendsto_neg_at_bot_at_top.comp hf).at_top_mul_at_top hg), by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_top_at_bot.comp this lemma tendsto.at_bot_mul_at_bot (hf : tendsto f l at_bot) (hg : tendsto g l at_bot) : tendsto (λ x, f x * g x) l at_top := have tendsto (λ x, (-f x) * (-g x)) l at_top := (tendsto_neg_at_bot_at_top.comp hf).at_top_mul_at_top (tendsto_neg_at_bot_at_top.comp hg), by simpa only [neg_mul_neg] using this end ordered_ring section linear_ordered_add_comm_group variables [linear_ordered_add_comm_group α] /-- $\lim_{x\to+\infty}|x|=+\infty$ -/ lemma tendsto_abs_at_top_at_top : tendsto (abs : α → α) at_top at_top := tendsto_at_top_mono le_abs_self tendsto_id /-- $\lim_{x\to-\infty}|x|=+\infty$ -/ lemma tendsto_abs_at_bot_at_top : tendsto (abs : α → α) at_bot at_top := tendsto_at_top_mono neg_le_abs_self tendsto_neg_at_bot_at_top end linear_ordered_add_comm_group section linear_ordered_semiring variables [linear_ordered_semiring α] {l : filter β} {f : β → α} lemma tendsto.at_top_of_const_mul {c : α} (hc : 0 < c) (hf : tendsto (λ x, c * f x) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ λ b, (tendsto_at_top.1 hf (c * b)).mono $ λ x hx, le_of_mul_le_mul_left hx hc lemma tendsto.at_top_of_mul_const {c : α} (hc : 0 < c) (hf : tendsto (λ x, f x * c) l at_top) : tendsto f l at_top := tendsto_at_top.2 $ λ b, (tendsto_at_top.1 hf (b * c)).mono $ λ x hx, le_of_mul_le_mul_right hx hc end linear_ordered_semiring lemma nonneg_of_eventually_pow_nonneg [linear_ordered_ring α] {a : α} (h : ∀ᶠ n in at_top, 0 ≤ a ^ (n : ℕ)) : 0 ≤ a := let ⟨n, hn⟩ := (tendsto_bit1_at_top.eventually h).exists in pow_bit1_nonneg_iff.1 hn section linear_ordered_field variables [linear_ordered_field α] {l : filter β} {f : β → α} {r : α} /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `filter.tendsto.const_mul_at_top'` instead. -/ lemma tendsto.const_mul_at_top (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, r * f x) l at_top := tendsto.at_top_of_const_mul (inv_pos.2 hr) $ by simpa only [inv_mul_cancel_left₀ hr.ne'] /-- If a function tends to infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to infinity. For a version working in `ℕ` or `ℤ`, use `filter.tendsto.at_top_mul_const'` instead. -/ lemma tendsto.at_top_mul_const (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, f x * r) l at_top := by simpa only [mul_comm] using hf.const_mul_at_top hr /-- If a function tends to infinity along a filter, then this function divided by a positive constant also tends to infinity. -/ lemma tendsto.at_top_div_const (hr : 0 < r) (hf : tendsto f l at_top) : tendsto (λx, f x / r) l at_top := by simpa only [div_eq_mul_inv] using hf.at_top_mul_const (inv_pos.2 hr) /-- If a function tends to infinity along a filter, then this function multiplied by a negative constant (on the left) tends to negative infinity. -/ lemma tendsto.neg_const_mul_at_top (hr : r < 0) (hf : tendsto f l at_top) : tendsto (λ x, r * f x) l at_bot := by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_top_at_bot.comp (hf.const_mul_at_top (neg_pos.2 hr)) /-- If a function tends to infinity along a filter, then this function multiplied by a negative constant (on the right) tends to negative infinity. -/ lemma tendsto.at_top_mul_neg_const (hr : r < 0) (hf : tendsto f l at_top) : tendsto (λ x, f x * r) l at_bot := by simpa only [mul_comm] using hf.neg_const_mul_at_top hr /-- If a function tends to negative infinity along a filter, then this function multiplied by a positive constant (on the left) also tends to negative infinity. -/ lemma tendsto.const_mul_at_bot (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, r * f x) l at_bot := by simpa only [(∘), neg_mul_eq_mul_neg, neg_neg] using tendsto_neg_at_top_at_bot.comp ((tendsto_neg_at_bot_at_top.comp hf).const_mul_at_top hr) /-- If a function tends to negative infinity along a filter, then this function multiplied by a positive constant (on the right) also tends to negative infinity. -/ lemma tendsto.at_bot_mul_const (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, f x * r) l at_bot := by simpa only [mul_comm] using hf.const_mul_at_bot hr /-- If a function tends to negative infinity along a filter, then this function divided by a positive constant also tends to negative infinity. -/ lemma tendsto.at_bot_div_const (hr : 0 < r) (hf : tendsto f l at_bot) : tendsto (λx, f x / r) l at_bot := by simpa only [div_eq_mul_inv] using hf.at_bot_mul_const (inv_pos.2 hr) /-- If a function tends to negative infinity along a filter, then this function multiplied by a negative constant (on the left) tends to positive infinity. -/ lemma tendsto.neg_const_mul_at_bot (hr : r < 0) (hf : tendsto f l at_bot) : tendsto (λ x, r * f x) l at_top := by simpa only [(∘), neg_mul_eq_neg_mul, neg_neg] using tendsto_neg_at_bot_at_top.comp (hf.const_mul_at_bot (neg_pos.2 hr)) /-- If a function tends to negative infinity along a filter, then this function multiplied by a negative constant (on the right) tends to positive infinity. -/ lemma tendsto.at_bot_mul_neg_const (hr : r < 0) (hf : tendsto f l at_bot) : tendsto (λ x, f x * r) l at_top := by simpa only [mul_comm] using hf.neg_const_mul_at_bot hr lemma tendsto_const_mul_pow_at_top {c : α} {n : ℕ} (hn : 1 ≤ n) (hc : 0 < c) : tendsto (λ x, c * x^n) at_top at_top := tendsto.const_mul_at_top hc (tendsto_pow_at_top hn) lemma tendsto_const_mul_pow_at_top_iff (c : α) (n : ℕ) : tendsto (λ x, c * x^n) at_top at_top ↔ 1 ≤ n ∧ 0 < c := begin refine ⟨λ h, _, λ h, tendsto_const_mul_pow_at_top h.1 h.2⟩, simp only [tendsto_at_top, eventually_at_top] at h, have : 0 < c := let ⟨x, hx⟩ := h 1 in pos_of_mul_pos_right (lt_of_lt_of_le zero_lt_one (hx (max x 1) (le_max_left x 1))) (pow_nonneg (le_trans zero_le_one (le_max_right x 1)) n), refine ⟨nat.succ_le_iff.mp (lt_of_le_of_ne (zero_le n) (ne.symm (λ hn, _))), this⟩, obtain ⟨x, hx⟩ := h (c + 1), specialize hx x le_rfl, rw [hn, pow_zero, mul_one, add_le_iff_nonpos_right] at hx, exact absurd hx (not_le.mpr zero_lt_one), end lemma tendsto_neg_const_mul_pow_at_top {c : α} {n : ℕ} (hn : 1 ≤ n) (hc : c < 0) : tendsto (λ x, c * x^n) at_top at_bot := tendsto.neg_const_mul_at_top hc (tendsto_pow_at_top hn) lemma tendsto_neg_const_mul_pow_at_top_iff (c : α) (n : ℕ) : tendsto (λ x, c * x^n) at_top at_bot ↔ 1 ≤ n ∧ c < 0 := begin refine ⟨λ h, _, λ h, tendsto_neg_const_mul_pow_at_top h.1 h.2⟩, simp only [tendsto_at_bot, eventually_at_top] at h, have : c < 0 := let ⟨x, hx⟩ := h (-1) in neg_of_mul_neg_right (lt_of_le_of_lt (hx (max x 1) (le_max_left x 1)) (by simp [zero_lt_one])) (pow_nonneg (le_trans zero_le_one (le_max_right x 1)) n), refine ⟨nat.succ_le_iff.mp (lt_of_le_of_ne (zero_le n) (ne.symm (λ hn, _))), this⟩, obtain ⟨x, hx⟩ := h (c - 1), specialize hx x le_rfl, rw [hn, pow_zero, mul_one, le_sub, sub_self] at hx, exact absurd hx (not_le.mpr zero_lt_one), end end linear_ordered_field open_locale filter lemma tendsto_at_top' [nonempty α] [semilattice_sup α] {f : α → β} {l : filter β} : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl lemma tendsto_at_bot' [nonempty α] [semilattice_inf α] {f : α → β} {l : filter β} : tendsto f at_bot l ↔ (∀s ∈ l, ∃a, ∀b≤a, f b ∈ s) := @tendsto_at_top' (order_dual α) _ _ _ _ _ theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (𝓟 s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl theorem tendsto_at_bot_principal [nonempty β] [semilattice_inf β] {f : β → α} {s : set α} : tendsto f at_bot (𝓟 s) ↔ ∃N, ∀n≤N, f n ∈ s := @tendsto_at_top_principal _ (order_dual β) _ _ _ _ /-- A function `f` grows to `+∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal lemma tendsto_at_top_at_bot [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → f a ≤ b := @tendsto_at_top_at_top α (order_dual β) _ _ _ f lemma tendsto_at_bot_at_top [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_top ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → b ≤ f a := @tendsto_at_top_at_top (order_dual α) β _ _ _ f lemma tendsto_at_bot_at_bot [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} : tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → f a ≤ b := @tendsto_at_top_at_top (order_dual α) (order_dual β) _ _ _ f lemma tendsto_at_top_at_top_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, b ≤ f a) : tendsto f at_top at_top := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_of_superset (mem_at_top a) $ λ a' ha', le_trans ha (hf ha') lemma tendsto_at_bot_at_bot_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, f a ≤ b) : tendsto f at_bot at_bot := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_of_superset (mem_at_bot a) $ λ a' ha', le_trans (hf ha') ha lemma tendsto_at_top_at_top_iff_of_monotone [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a := tendsto_at_top_at_top.trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩ lemma tendsto_at_bot_at_bot_iff_of_monotone [nonempty α] [semilattice_inf α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_bot at_bot ↔ ∀ b : β, ∃ a : α, f a ≤ b := tendsto_at_bot_at_bot.trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans (hf ha') h⟩ alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top alias tendsto_at_bot_at_bot_of_monotone ← monotone.tendsto_at_bot_at_bot alias tendsto_at_top_at_top_iff_of_monotone ← monotone.tendsto_at_top_at_top_iff alias tendsto_at_bot_at_bot_iff_of_monotone ← monotone.tendsto_at_bot_at_bot_iff lemma tendsto_at_top_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := begin refine ⟨_, (tendsto_at_top_at_top_of_monotone (λ b₁ b₂, (hm b₁ b₂).2) hu).comp⟩, rw [tendsto_at_top, tendsto_at_top], exact λ hc b, (hc (e b)).mono (λ a, (hm b (f a)).1) end /-- A function `f` goes to `-∞` independent of an order-preserving embedding `e`. -/ lemma tendsto_at_bot_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, e b ≤ c) : tendsto (e ∘ f) l at_bot ↔ tendsto f l at_bot := @tendsto_at_top_embedding α (order_dual β) (order_dual γ) _ _ f e l (function.swap hm) hu lemma tendsto_finset_range : tendsto finset.range at_top at_top := finset.range_mono.tendsto_at_top_at_top finset.exists_nat_subset_range lemma at_top_finset_eq_infi : (at_top : filter $ finset α) = ⨅ x : α, 𝓟 (Ici {x}) := begin refine le_antisymm (le_infi (λ i, le_principal_iff.2 $ mem_at_top {i})) _, refine le_infi (λ s, le_principal_iff.2 $ mem_infi_of_Inter s.finite_to_set (λ i, mem_principal_self _) _), simp only [subset_def, mem_Inter, set_coe.forall, mem_Ici, finset.le_iff_subset, finset.mem_singleton, finset.subset_iff, forall_eq], dsimp, exact λ t, id end /-- If `f` is a monotone sequence of `finset`s and each `x` belongs to one of `f n`, then `tendsto f at_top at_top`. -/ lemma tendsto_at_top_finset_of_monotone [preorder β] {f : β → finset α} (h : monotone f) (h' : ∀ x : α, ∃ n, x ∈ f n) : tendsto f at_top at_top := begin simp only [at_top_finset_eq_infi, tendsto_infi, tendsto_principal], intro a, rcases h' a with ⟨b, hb⟩, exact eventually.mono (mem_at_top b) (λ b' hb', le_trans (finset.singleton_subset_iff.2 hb) (h hb')), end alias tendsto_at_top_finset_of_monotone ← monotone.tendsto_at_top_finset lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : function.left_inverse j i) : tendsto (finset.image j) at_top at_top := (finset.image_mono j).tendsto_at_top_finset $ assume a, ⟨{i a}, by simp only [finset.image_singleton, h a, finset.mem_singleton]⟩ lemma tendsto_finset_preimage_at_top_at_top {f : α → β} (hf : function.injective f) : tendsto (λ s : finset β, s.preimage f (hf.inj_on _)) at_top at_top := (finset.monotone_preimage hf).tendsto_at_top_finset $ λ x, ⟨{f x}, finset.mem_preimage.2 $ finset.mem_singleton_self _⟩ lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] : (at_top : filter β₁) ×ᶠ (at_top : filter β₂) = (at_top : filter (β₁ × β₂)) := begin casesI (is_empty_or_nonempty β₁).symm, casesI (is_empty_or_nonempty β₂).symm, { simp [at_top, prod_infi_left, prod_infi_right, infi_prod], exact infi_comm, }, { simp only [at_top.filter_eq_bot_of_is_empty, prod_bot] }, { simp only [at_top.filter_eq_bot_of_is_empty, bot_prod] }, end lemma prod_at_bot_at_bot_eq {β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] : (at_bot : filter β₁) ×ᶠ (at_bot : filter β₂) = (at_bot : filter (β₁ × β₂)) := @prod_at_top_at_top_eq (order_dual β₁) (order_dual β₂) _ _ lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_top) ×ᶠ (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] lemma prod_map_at_bot_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_inf β₁] [semilattice_inf β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_bot) ×ᶠ (map u₂ at_bot) = map (prod.map u₁ u₂) at_bot := @prod_map_at_top_eq _ _ (order_dual β₁) (order_dual β₂) _ _ _ _ lemma tendsto.subseq_mem {F : filter α} {V : ℕ → set α} (h : ∀ n, V n ∈ F) {u : ℕ → α} (hu : tendsto u at_top F) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, u (φ n) ∈ V n := extraction_forall_of_eventually' (λ n, tendsto_at_top'.mp hu _ (h n) : ∀ n, ∃ N, ∀ k ≥ N, u k ∈ V n) lemma tendsto_at_bot_diagonal [semilattice_inf α] : tendsto (λ a : α, (a, a)) at_bot at_bot := by { rw ← prod_at_bot_at_bot_eq, exact tendsto_id.prod_mk tendsto_id } lemma tendsto_at_top_diagonal [semilattice_sup α] : tendsto (λ a : α, (a, a)) at_top at_top := by { rw ← prod_at_top_at_top_eq, exact tendsto_id.prod_mk tendsto_id } lemma tendsto.prod_map_prod_at_bot [semilattice_inf γ] {F : filter α} {G : filter β} {f : α → γ} {g : β → γ} (hf : tendsto f F at_bot) (hg : tendsto g G at_bot) : tendsto (prod.map f g) (F ×ᶠ G) at_bot := by { rw ← prod_at_bot_at_bot_eq, exact hf.prod_map hg, } lemma tendsto.prod_map_prod_at_top [semilattice_sup γ] {F : filter α} {G : filter β} {f : α → γ} {g : β → γ} (hf : tendsto f F at_top) (hg : tendsto g G at_top) : tendsto (prod.map f g) (F ×ᶠ G) at_top := by { rw ← prod_at_top_at_top_eq, exact hf.prod_map hg, } lemma tendsto.prod_at_bot [semilattice_inf α] [semilattice_inf γ] {f g : α → γ} (hf : tendsto f at_bot at_bot) (hg : tendsto g at_bot at_bot) : tendsto (prod.map f g) at_bot at_bot := by { rw ← prod_at_bot_at_bot_eq, exact hf.prod_map_prod_at_bot hg, } lemma tendsto.prod_at_top [semilattice_sup α] [semilattice_sup γ] {f g : α → γ} (hf : tendsto f at_top at_top) (hg : tendsto g at_top at_top) : tendsto (prod.map f g) at_top at_top := by { rw ← prod_at_top_at_top_eq, exact hf.prod_map_prod_at_top hg, } lemma eventually_at_bot_prod_self [semilattice_inf α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ k l, k ≤ a → l ≤ a → p (k, l)) := by simp [← prod_at_bot_at_bot_eq, at_bot_basis.prod_self.eventually_iff] lemma eventually_at_top_prod_self [semilattice_sup α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ k l, a ≤ k → a ≤ l → p (k, l)) := by simp [← prod_at_top_at_top_eq, at_top_basis.prod_self.eventually_iff] lemma eventually_at_bot_prod_self' [semilattice_inf α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_bot, p x) ↔ (∃ a, ∀ k ≤ a, ∀ l ≤ a, p (k, l)) := begin rw filter.eventually_at_bot_prod_self, apply exists_congr, tauto, end lemma eventually_at_top_prod_self' [semilattice_sup α] [nonempty α] {p : α × α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ k ≥ a, ∀ l ≥ a, p (k, l)) := begin rw filter.eventually_at_top_prod_self, apply exists_congr, tauto, end /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin refine le_antisymm (hf.tendsto_at_top_at_top $ λ b, ⟨g (b ⊔ b'), le_sup_left.trans $ hgi _ le_sup_right⟩) _, rw [@map_at_top_eq _ _ ⟨g b'⟩], refine le_infi (λ a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 $ λ b hb, _), rw [mem_Ici, sup_le_iff] at hb, exact ⟨g b, (gc _ _ hb.2).1 hb.1, le_antisymm ((gc _ _ hb.2).2 (le_refl _)) (hgi _ hb.2)⟩ end lemma map_at_bot_eq_of_gc [semilattice_inf α] [semilattice_inf β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≤b', b ≤ f a ↔ g b ≤ a) (hgi : ∀b≤b', f (g b) ≤ b) : map f at_bot = at_bot := @map_at_top_eq_of_gc (order_dual α) (order_dual β) _ _ _ _ _ hf.dual gc hgi lemma map_coe_at_top_of_Ici_subset [semilattice_sup α] {a : α} {s : set α} (h : Ici a ⊆ s) : map (coe : s → α) at_top = at_top := begin have : directed (≥) (λ x : s, 𝓟 (Ici x)), { intros x y, use ⟨x ⊔ y ⊔ a, h le_sup_right⟩, simp only [ge_iff_le, principal_mono, Ici_subset_Ici, ← subtype.coe_le_coe, subtype.coe_mk], exact ⟨le_sup_left.trans le_sup_left, le_sup_right.trans le_sup_left⟩ }, haveI : nonempty s := ⟨⟨a, h le_rfl⟩⟩, simp only [le_antisymm_iff, at_top, le_infi_iff, le_principal_iff, mem_map, mem_set_of_eq, map_infi_eq this, map_principal], split, { intro x, refine mem_of_superset (mem_infi_of_mem ⟨x ⊔ a, h le_sup_right⟩ (mem_principal_self _)) _, rintro _ ⟨y, hy, rfl⟩, exact le_trans le_sup_left (subtype.coe_le_coe.2 hy) }, { intro x, filter_upwards [mem_at_top (↑x ⊔ a)], intros b hb, exact ⟨⟨b, h $ le_sup_right.trans hb⟩, subtype.coe_le_coe.1 (le_sup_left.trans hb), rfl⟩ } end /-- The image of the filter `at_top` on `Ici a` under the coercion equals `at_top`. -/ @[simp] lemma map_coe_Ici_at_top [semilattice_sup α] (a : α) : map (coe : Ici a → α) at_top = at_top := map_coe_at_top_of_Ici_subset (subset.refl _) /-- The image of the filter `at_top` on `Ioi a` under the coercion equals `at_top`. -/ @[simp] lemma map_coe_Ioi_at_top [semilattice_sup α] [no_top_order α] (a : α) : map (coe : Ioi a → α) at_top = at_top := begin rcases no_top a with ⟨b, hb⟩, exact map_coe_at_top_of_Ici_subset (Ici_subset_Ioi.2 hb) end /-- The `at_top` filter for an open interval `Ioi a` comes from the `at_top` filter in the ambient order. -/ lemma at_top_Ioi_eq [semilattice_sup α] (a : α) : at_top = comap (coe : Ioi a → α) at_top := begin nontriviality, rcases nontrivial_iff_nonempty.1 ‹_› with ⟨b, hb⟩, rw [← map_coe_at_top_of_Ici_subset (Ici_subset_Ioi.2 hb), comap_map subtype.coe_injective] end /-- The `at_top` filter for an open interval `Ici a` comes from the `at_top` filter in the ambient order. -/ lemma at_top_Ici_eq [semilattice_sup α] (a : α) : at_top = comap (coe : Ici a → α) at_top := by rw [← map_coe_Ici_at_top a, comap_map subtype.coe_injective] /-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient order. -/ @[simp] lemma map_coe_Iio_at_bot [semilattice_inf α] [no_bot_order α] (a : α) : map (coe : Iio a → α) at_bot = at_bot := @map_coe_Ioi_at_top (order_dual α) _ _ _ /-- The `at_bot` filter for an open interval `Iio a` comes from the `at_bot` filter in the ambient order. -/ lemma at_bot_Iio_eq [semilattice_inf α] (a : α) : at_bot = comap (coe : Iio a → α) at_bot := @at_top_Ioi_eq (order_dual α) _ _ /-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient order. -/ @[simp] lemma map_coe_Iic_at_bot [semilattice_inf α] (a : α) : map (coe : Iic a → α) at_bot = at_bot := @map_coe_Ici_at_top (order_dual α) _ _ /-- The `at_bot` filter for an open interval `Iic a` comes from the `at_bot` filter in the ambient order. -/ lemma at_bot_Iic_eq [semilattice_inf α] (a : α) : at_bot = comap (coe : Iic a → α) at_bot := @at_top_Ici_eq (order_dual α) _ _ lemma tendsto_Ioi_at_top [semilattice_sup α] {a : α} {f : β → Ioi a} {l : filter β} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l at_top := by rw [at_top_Ioi_eq, tendsto_comap_iff] lemma tendsto_Iio_at_bot [semilattice_inf α] {a : α} {f : β → Iio a} {l : filter β} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l at_bot := by rw [at_bot_Iio_eq, tendsto_comap_iff] lemma tendsto_Ici_at_top [semilattice_sup α] {a : α} {f : β → Ici a} {l : filter β} : tendsto f l at_top ↔ tendsto (λ x, (f x : α)) l at_top := by rw [at_top_Ici_eq, tendsto_comap_iff] lemma tendsto_Iic_at_bot [semilattice_inf α] {a : α} {f : β → Iic a} {l : filter β} : tendsto f l at_bot ↔ tendsto (λ x, (f x : α)) l at_bot := by rw [at_bot_Iic_eq, tendsto_comap_iff] @[simp] lemma tendsto_comp_coe_Ioi_at_top [semilattice_sup α] [no_top_order α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Ioi a, f x) at_top l ↔ tendsto f at_top l := by rw [← map_coe_Ioi_at_top a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Ici_at_top [semilattice_sup α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Ici a, f x) at_top l ↔ tendsto f at_top l := by rw [← map_coe_Ici_at_top a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Iio_at_bot [semilattice_inf α] [no_bot_order α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Iio a, f x) at_bot l ↔ tendsto f at_bot l := by rw [← map_coe_Iio_at_bot a, tendsto_map'_iff] @[simp] lemma tendsto_comp_coe_Iic_at_bot [semilattice_inf α] {a : α} {f : α → β} {l : filter β} : tendsto (λ x : Iic a, f x) at_bot l ↔ tendsto f at_bot l := by rw [← map_coe_Iic_at_bot a, tendsto_map'_iff] lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (nat.le_sub_right_iff_add_le h).symm) (assume a h, by rw [nat.sub_add_cancel h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, nat.sub_le_sub_right h _) (assume a b _, nat.sub_le_right_iff_le_add) (assume b _, by rw [nat.add_sub_cancel]) lemma tendsto_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendsto_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : 0 < k) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, rw [add_mul, one_mul, nat.succ_sub_succ_eq_sub, nat.sub_zero, nat.add_succ, nat.lt_succ_iff], end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded above, then `tendsto u at_top at_top`. -/ lemma tendsto_at_top_at_top_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_above (range u)) : tendsto u at_top at_top := begin apply h.tendsto_at_top_at_top, intro b, rcases not_bdd_above_iff.1 H b with ⟨_, ⟨N, rfl⟩, hN⟩, exact ⟨N, le_of_lt hN⟩, end /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded below, then `tendsto u at_bot at_bot`. -/ lemma tendsto_at_bot_at_bot_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_below (range u)) : tendsto u at_bot at_bot := @tendsto_at_top_at_top_of_monotone' (order_dual ι) (order_dual α) _ _ _ h.dual H lemma unbounded_of_tendsto_at_top [nonempty α] [semilattice_sup α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_top at_top) : ¬ bdd_above (range f) := begin rintros ⟨M, hM⟩, cases mem_at_top_sets.mp (h $ Ioi_mem_at_top M) with a ha, apply lt_irrefl M, calc M < f a : ha a (le_refl _) ... ≤ M : hM (set.mem_range_self a) end lemma unbounded_of_tendsto_at_bot [nonempty α] [semilattice_sup α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_top at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top _ (order_dual β) _ _ _ _ _ h lemma unbounded_of_tendsto_at_top' [nonempty α] [semilattice_inf α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_bot at_top) : ¬ bdd_above (range f) := @unbounded_of_tendsto_at_top (order_dual α) _ _ _ _ _ _ h lemma unbounded_of_tendsto_at_bot' [nonempty α] [semilattice_inf α] [preorder β] [no_bot_order β] {f : α → β} (h : tendsto f at_bot at_bot) : ¬ bdd_below (range f) := @unbounded_of_tendsto_at_top (order_dual α) (order_dual β) _ _ _ _ _ h /-- If a monotone function `u : ι → α` tends to `at_top` along *some* non-trivial filter `l`, then it tends to `at_top` along `at_top`. -/ lemma tendsto_at_top_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_top) : tendsto u at_top at_top := h.tendsto_at_top_at_top $ λ b, (hu.eventually (mem_at_top b)).exists /-- If a monotone function `u : ι → α` tends to `at_bot` along *some* non-trivial filter `l`, then it tends to `at_bot` along `at_bot`. -/ lemma tendsto_at_bot_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_bot) : tendsto u at_bot at_bot := @tendsto_at_top_of_monotone_of_filter (order_dual ι) (order_dual α) _ _ _ _ h.dual _ hu lemma tendsto_at_top_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_top) : tendsto u at_top at_top := tendsto_at_top_of_monotone_of_filter h (tendsto_map' H) lemma tendsto_at_bot_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_bot) : tendsto u at_bot at_bot := tendsto_at_bot_of_monotone_of_filter h (tendsto_map' H) /-- Let `f` and `g` be two maps to the same commutative monoid. This lemma gives a sufficient condition for comparison of the filter `at_top.map (λ s, ∏ b in s, f b)` with `at_top.map (λ s, ∏ b in s, g b)`. This is useful to compare the set of limit points of `Π b in s, f b` as `s → at_top` with the similar set for `g`. -/ @[to_additive] lemma map_at_top_finset_prod_le_of_prod_eq [comm_monoid α] {f : β → α} {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∏ x in u', g x = ∏ b in v', f b) : at_top.map (λs:finset β, ∏ b in s, f b) ≤ at_top.map (λs:finset γ, ∏ x in s, g x) := by rw [map_at_top_eq, map_at_top_eq]; from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $ by simp [set.image_subset_iff]; exact hv) lemma has_antitone_basis.tendsto [semilattice_sup ι] [nonempty ι] {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : l.has_antitone_basis p s) {φ : ι → α} (h : ∀ i : ι, φ i ∈ s i) : tendsto φ at_top l := (at_top_basis.tendsto_iff hl.to_has_basis).2 $ assume i hi, ⟨i, trivial, λ j hij, hl.decreasing hi (hl.mono hij hi) hij (h j)⟩ namespace is_countably_generated /-- An abstract version of continuity of sequentially continuous functions on metric spaces: if a filter `k` is countably generated then `tendsto f k l` iff for every sequence `u` converging to `k`, `f ∘ u` tends to `l`. -/ lemma tendsto_iff_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : tendsto f k l ↔ (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) := suffices (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l, from ⟨by intros; apply tendsto.comp; assumption, by assumption⟩, begin obtain ⟨g, gbasis, gmon, -⟩ := hcb.exists_antitone_basis, contrapose, simp only [not_forall, gbasis.tendsto_left_iff, exists_const, not_exists, not_imp], rintro ⟨B, hBl, hfBk⟩, choose x h using hfBk, use x, split, { exact (at_top_basis.tendsto_iff gbasis).2 (λ i _, ⟨i, trivial, λ j hj, gmon trivial trivial hj (h j).1⟩) }, { simp only [tendsto_at_top', (∘), not_forall, not_exists], use [B, hBl], intro i, use [i, (le_refl _)], apply (h i).right }, end lemma tendsto_of_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l := hcb.tendsto_iff_seq_tendsto.2 lemma subseq_tendsto {f : filter α} (hf : is_countably_generated f) {u : ℕ → α} (hx : ne_bot (f ⊓ map u at_top)) : ∃ (θ : ℕ → ℕ), (strict_mono θ) ∧ (tendsto (u ∘ θ) at_top f) := begin obtain ⟨B, h⟩ := hf.exists_antitone_basis, have : ∀ N, ∃ n ≥ N, u n ∈ B N, from λ N, filter.inf_map_at_top_ne_bot_iff.mp hx _ (h.to_has_basis.mem_of_mem trivial) N, choose φ hφ using this, cases forall_and_distrib.mp hφ with φ_ge φ_in, have lim_uφ : tendsto (u ∘ φ) at_top f, from h.tendsto φ_in, have lim_φ : tendsto φ at_top at_top, from (tendsto_at_top_mono φ_ge tendsto_id), obtain ⟨ψ, hψ, hψφ⟩ : ∃ ψ : ℕ → ℕ, strict_mono ψ ∧ strict_mono (φ ∘ ψ), from strict_mono_subseq_of_tendsto_at_top lim_φ, exact ⟨φ ∘ ψ, hψφ, lim_uφ.comp hψ.tendsto_at_top⟩, end end is_countably_generated end filter open filter finset section variables {R : Type*} [linear_ordered_semiring R] lemma exists_lt_mul_self (a : R) : ∃ x ≥ 0, a < x * x := let ⟨x, hxa, hx0⟩ :=((tendsto_mul_self_at_top.eventually (eventually_gt_at_top a)).and (eventually_ge_at_top 0)).exists in ⟨x, hx0, hxa⟩ lemma exists_le_mul_self (a : R) : ∃ x ≥ 0, a ≤ x * x := let ⟨x, hx0, hxa⟩ := exists_lt_mul_self a in ⟨x, hx0, hxa.le⟩ end namespace order_iso variables [preorder α] [preorder β] @[simp] lemma comap_at_top (e : α ≃o β) : comap e at_top = at_top := by simp [at_top, ← e.surjective.infi_comp] @[simp] lemma comap_at_bot (e : α ≃o β) : comap e at_bot = at_bot := e.dual.comap_at_top @[simp] lemma map_at_top (e : α ≃o β) : map ⇑e at_top = at_top := by rw [← e.comap_at_top, map_comap_of_surjective e.surjective] @[simp] lemma map_at_bot (e : α ≃o β) : map ⇑e at_bot = at_bot := e.dual.map_at_top lemma tendsto_at_top (e : α ≃o β) : tendsto e at_top at_top := e.map_at_top.le lemma tendsto_at_bot (e : α ≃o β) : tendsto e at_bot at_bot := e.map_at_bot.le @[simp] lemma tendsto_at_top_iff {l : filter γ} {f : γ → α} (e : α ≃o β) : tendsto (λ x, e (f x)) l at_top ↔ tendsto f l at_top := by rw [← e.comap_at_top, tendsto_comap_iff] @[simp] lemma tendsto_at_bot_iff {l : filter γ} {f : γ → α} (e : α ≃o β) : tendsto (λ x, e (f x)) l at_bot ↔ tendsto f l at_bot := e.dual.tendsto_at_top_iff end order_iso /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to a commutative monoid. Suppose that `f x = 1` outside of the range of `g`. Then the filters `at_top.map (λ s, ∏ i in s, f (g i))` and `at_top.map (λ s, ∏ i in s, f i)` coincide. The additive version of this lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ @[to_additive] lemma function.injective.map_at_top_finset_prod_eq [comm_monoid α] {g : γ → β} (hg : function.injective g) {f : β → α} (hf : ∀ x ∉ set.range g, f x = 1) : map (λ s, ∏ i in s, f (g i)) at_top = map (λ s, ∏ i in s, f i) at_top := begin apply le_antisymm; refine map_at_top_finset_prod_le_of_prod_eq (λ s, _), { refine ⟨s.preimage g (hg.inj_on _), λ t ht, _⟩, refine ⟨t.image g ∪ s, finset.subset_union_right _ _, _⟩, rw [← finset.prod_image (hg.inj_on _)], refine (prod_subset (subset_union_left _ _) _).symm, simp only [finset.mem_union, finset.mem_image], refine λ y hy hyt, hf y (mt _ hyt), rintros ⟨x, rfl⟩, exact ⟨x, ht (finset.mem_preimage.2 $ hy.resolve_left hyt), rfl⟩ }, { refine ⟨s.image g, λ t ht, _⟩, simp only [← prod_preimage _ _ (hg.inj_on _) _ (λ x _, hf x)], exact ⟨_, (image_subset_iff_subset_preimage _).1 ht, rfl⟩ } end /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to an additive commutative monoid. Suppose that `f x = 0` outside of the range of `g`. Then the filters `at_top.map (λ s, ∑ i in s, f (g i))` and `at_top.map (λ s, ∑ i in s, f i)` coincide. This lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ add_decl_doc function.injective.map_at_top_finset_sum_eq
577f177c571d0afa5435c895745f20a223157790
fe25de614feb5587799621c41487aaee0d083b08
/stage0/src/Lean/PrettyPrinter/Delaborator/Basic.lean
d23957605f985c89042e49ac4120efad0ada429d
[ "Apache-2.0" ]
permissive
pollend/lean4
e8469c2f5fb8779b773618c3267883cf21fb9fac
c913886938c4b3b83238a3f99673c6c5a9cec270
refs/heads/master
1,687,973,251,481
1,628,039,739,000
1,628,039,739,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,893
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ /-! The delaborator is the first stage of the pretty printer, and the inverse of the elaborator: it turns fully elaborated `Expr` core terms back into surface-level `Syntax`, omitting some implicit information again and using higher-level syntax abstractions like notations where possible. The exact behavior can be customized using pretty printer options; activating `pp.all` should guarantee that the delaborator is injective and that re-elaborating the resulting `Syntax` round-trips. Pretty printer options can be given not only for the whole term, but also specific subterms. This is used both when automatically refining pp options until round-trip and when interactively selecting pp options for a subterm (both TBD). The association of options to subterms is done by assigning a unique, synthetic Nat position to each subterm derived from its position in the full term. This position is added to the corresponding Syntax object so that elaboration errors and interactions with the pretty printer output can be traced back to the subterm. The delaborator is extensible via the `[delab]` attribute. -/ import Lean.KeyedDeclsAttribute import Lean.ProjFns import Lean.Syntax import Lean.Meta.Match import Lean.Elab.Term import Lean.PrettyPrinter.Delaborator.Options import Lean.PrettyPrinter.Delaborator.SubExpr import Lean.PrettyPrinter.Delaborator.TopDownAnalyze namespace Lean.PrettyPrinter.Delaborator open Lean.Meta SubExpr structure Context where defaultOptions : Options optionsPerPos : OptionsPerPos currNamespace : Name openDecls : List OpenDecl inPattern : Bool := false -- true whe delaborating `match` patterns -- Exceptions from delaborators are not expected. We use an internal exception to signal whether -- the delaborator was able to produce a Syntax object. builtin_initialize delabFailureId : InternalExceptionId ← registerInternalExceptionId `delabFailure abbrev DelabM := ReaderT Context (ReaderT SubExpr MetaM) abbrev Delab := DelabM Syntax instance {α} : Inhabited (DelabM α) where default := throw arbitrary @[inline] protected def orElse {α} (d₁ d₂ : DelabM α) : DelabM α := do catchInternalId delabFailureId d₁ (fun _ => d₂) protected def failure {α} : DelabM α := throw $ Exception.internal delabFailureId instance : Alternative DelabM := { orElse := Delaborator.orElse, failure := Delaborator.failure } -- HACK: necessary since it would otherwise prefer the instance from MonadExcept instance {α} : OrElse (DelabM α) := ⟨Delaborator.orElse⟩ -- Macro scopes in the delaborator output are ultimately ignored by the pretty printer, -- so give a trivial implementation. instance : MonadQuotation DelabM := { getCurrMacroScope := pure arbitrary, getMainModule := pure arbitrary, withFreshMacroScope := fun x => x } unsafe def mkDelabAttribute : IO (KeyedDeclsAttribute Delab) := KeyedDeclsAttribute.init { builtinName := `builtinDelab, name := `delab, descr := "Register a delaborator. [delab k] registers a declaration of type `Lean.PrettyPrinter.Delaborator.Delab` for the `Lean.Expr` constructor `k`. Multiple delaborators for a single constructor are tried in turn until the first success. If the term to be delaborated is an application of a constant `c`, elaborators for `app.c` are tried first; this is also done for `Expr.const`s (\"nullary applications\") to reduce special casing. If the term is an `Expr.mdata` with a single key `k`, `mdata.k` is tried first.", valueTypeName := `Lean.PrettyPrinter.Delaborator.Delab } `Lean.PrettyPrinter.Delaborator.delabAttribute @[builtinInit mkDelabAttribute] constant delabAttribute : KeyedDeclsAttribute Delab def getExprKind : DelabM Name := do let e ← getExpr pure $ match e with | Expr.bvar _ _ => `bvar | Expr.fvar _ _ => `fvar | Expr.mvar _ _ => `mvar | Expr.sort _ _ => `sort | Expr.const c _ _ => -- we identify constants as "nullary applications" to reduce special casing `app ++ c | Expr.app fn _ _ => match fn.getAppFn with | Expr.const c _ _ => `app ++ c | _ => `app | Expr.lam _ _ _ _ => `lam | Expr.forallE _ _ _ _ => `forallE | Expr.letE _ _ _ _ _ => `letE | Expr.lit _ _ => `lit | Expr.mdata m _ _ => match m.entries with | [(key, _)] => `mdata ++ key | _ => `mdata | Expr.proj _ _ _ _ => `proj def getOptionsAtCurrPos : DelabM Options := do let ctx ← read let mut opts := ctx.defaultOptions if let some opts' ← ctx.optionsPerPos.find? (← getPos) then for (k, v) in opts' do opts := opts.insert k v opts /-- Evaluate option accessor, using subterm-specific options if set. -/ def getPPOption (opt : Options → Bool) : DelabM Bool := do return opt (← getOptionsAtCurrPos) def whenPPOption (opt : Options → Bool) (d : Delab) : Delab := do let b ← getPPOption opt if b then d else failure def whenNotPPOption (opt : Options → Bool) (d : Delab) : Delab := do let b ← getPPOption opt if b then failure else d partial def annotatePos (pos : Nat) : Syntax → Syntax | stx@(Syntax.ident _ _ _ _) => stx.setInfo (SourceInfo.synthetic pos pos) -- app => annotate function | stx@(Syntax.node `Lean.Parser.Term.app args) => stx.modifyArg 0 (annotatePos pos) -- otherwise, annotate first direct child token if any | stx => match stx.getArgs.findIdx? Syntax.isAtom with | some idx => stx.modifyArg idx (Syntax.setInfo (SourceInfo.synthetic pos pos)) | none => stx def annotateCurPos (stx : Syntax) : Delab := do annotatePos (← getPos) stx def getUnusedName (suggestion : Name) (body : Expr) : DelabM Name := do -- Use a nicer binder name than `[anonymous]`. We probably shouldn't do this in all LocalContext use cases, so do it here. let suggestion := if suggestion.isAnonymous then `a else suggestion; let suggestion := suggestion.eraseMacroScopes let lctx ← getLCtx if !lctx.usesUserName suggestion then return suggestion else if (← getPPOption getPPSafeShadowing) && !bodyUsesSuggestion lctx suggestion then return suggestion else return lctx.getUnusedName suggestion where bodyUsesSuggestion (lctx : LocalContext) (suggestion' : Name) : Bool := Option.isSome <| body.find? fun | Expr.fvar fvarId _ => match lctx.find? fvarId with | none => false | some decl => decl.userName == suggestion' | _ => false def withBindingBodyUnusedName {α} (d : Syntax → DelabM α) : DelabM α := do let n ← getUnusedName (← getExpr).bindingName! (← getExpr).bindingBody! let stxN ← annotateCurPos (mkIdent n) withBindingBody n $ d stxN @[inline] def liftMetaM {α} (x : MetaM α) : DelabM α := liftM x partial def delabFor : Name → Delab | Name.anonymous => failure | k => do (delabAttribute.getValues (← getEnv) k).firstM id >>= annotateCurPos <|> -- have `app.Option.some` fall back to `app` etc. delabFor k.getRoot partial def delab : Delab := do checkMaxHeartbeats "delab" let e ← getExpr -- no need to hide atomic proofs if ← !e.isAtomic <&&> !(← getPPOption getPPProofs) <&&> (try Meta.isProof e catch ex => false) then if ← getPPOption getPPProofsWithType then let stx ← withType delab return ← ``((_ : $stx)) else return ← ``(_) let k ← getExprKind let stx ← delabFor k <|> (liftM $ show MetaM Syntax from throwError "don't know how to delaborate '{k}'") if ← getPPOption getPPAnalyzeTypeAscriptions <&&> getPPOption getPPAnalysisNeedsType <&&> !e.isMData then let typeStx ← withType delab `(($stx:term : $typeStx:term)) >>= annotateCurPos else stx unsafe def mkAppUnexpanderAttribute : IO (KeyedDeclsAttribute Unexpander) := KeyedDeclsAttribute.init { name := `appUnexpander, descr := "Register an unexpander for applications of a given constant. [appUnexpander c] registers a `Lean.PrettyPrinter.Unexpander` for applications of the constant `c`. The unexpander is passed the result of pre-pretty printing the application *without* implicitly passed arguments. If `pp.explicit` is set to true or `pp.notation` is set to false, it will not be called at all.", valueTypeName := `Lean.PrettyPrinter.Unexpander } `Lean.PrettyPrinter.Delaborator.appUnexpanderAttribute @[builtinInit mkAppUnexpanderAttribute] constant appUnexpanderAttribute : KeyedDeclsAttribute Unexpander end Delaborator open Delaborator (OptionsPerPos topDownAnalyze) /-- "Delaborate" the given term into surface-level syntax using the default and given subterm-specific options. -/ def delab (currNamespace : Name) (openDecls : List OpenDecl) (e : Expr) (optionsPerPos : OptionsPerPos := {}) : MetaM Syntax := do trace[PrettyPrinter.delab.input] "{Std.format e}" let mut opts ← MonadOptions.getOptions -- default `pp.proofs` to `true` if `e` is a proof if pp.proofs.get? opts == none then try if ← Meta.isProof e then opts := pp.proofs.set opts true catch _ => pure () let e ← if getPPInstantiateMVars opts then ← Meta.instantiateMVars e else e let optionsPerPos ← if !getPPAll opts && getPPAnalyze opts && optionsPerPos.isEmpty then withTheReader Core.Context (fun ctx => { ctx with options := opts }) do topDownAnalyze e else optionsPerPos catchInternalId Delaborator.delabFailureId (Delaborator.delab.run { defaultOptions := opts, optionsPerPos := optionsPerPos, currNamespace := currNamespace, openDecls := openDecls } (Delaborator.SubExpr.mkRoot e)) (fun _ => unreachable!) builtin_initialize registerTraceClass `PrettyPrinter.delab end Lean.PrettyPrinter
79139fa878bd7287ff3361b982ef9a093e032b7f
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/structInst4.lean
508fb07cac4ec5bfaf9083ef6de709a7529e38a3
[ "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
485
lean
universes u def a : Array ((Nat × Nat) × Bool) := #[] def b : Array Nat := #[] structure Foo := (x : Array ((Nat × Nat) × Bool) := #[]) (y : Nat := 0) #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 }
f28a3608ff816e194f3a360594895a2405cf9da5
6096e76aa1d83b3f250d2c69eeda5b692d6bd3e2
/src/calculus.lean
f80033da96cc2fe0cd79be1347f43bc4200c033b
[]
no_license
ChrisHughes24/lean-differential-topology
3782f1841e5205f76a122b7e8ceb9c65ace06088
0abdf5a61414459fb0833f39b4d04c3528404454
refs/heads/master
1,584,570,674,323
1,527,526,729,000
1,527,526,729,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,001
lean
import analysis.real import analysis.limits import norms import continuous_linear_maps noncomputable theory local attribute [instance] classical.prop_decidable open filter is_bounded_linear_map local notation f `→_{`:50 a `}`:0 b := filter.tendsto f (nhds a) (nhds b) local notation `lim_{`:50 a`}`:0 f := lim (map f (nhds a)) local notation `∥` e `∥` := norm e section differential variables {E : Type*} {F : Type*} {G : Type*} [normed_space ℝ E] [normed_space ℝ F] [normed_space ℝ G] def is_differential (f : E → F) (a : E) (L : E → F) : Prop := (is_bounded_linear_map L) ∧ (∃ ε : E → F, (∀ h, f (a + h) = f a + L h + ∥h∥ • ε h) ∧ (ε →_{0} 0)) lemma div_mul_le_div_mul_left {a b c d : ℝ} : 0 ≤ d → a ≤ b → c > 0 → a/c*d ≤ b/c*d := assume d0 ab c0, mul_le_mul_of_nonneg_right (div_le_div_of_le_of_pos ab c0) d0 @[simp] lemma norm_norm { e : E } : ∥∥e∥∥ = ∥e∥ := abs_of_nonneg norm_nonneg theorem chain_rule (f : E → F) (g : F → G) (a : E) (L : E → F) (P : F → G) : is_differential f a L → is_differential g (f a) P → is_differential (g ∘ f) a (P ∘ L) := λ ⟨cont_lin_L, ε, TEf, lim_ε⟩ ⟨cont_lin_P, η, TEg, lim_η⟩, let cont_linPL := is_bounded_linear_map.comp cont_lin_L cont_lin_P in ⟨cont_linPL, begin rcases cont_lin_P with ⟨lin_P , MP, MP_pos, ineq_P⟩, rcases cont_lin_L with ⟨lin_L , ML, ML_pos, ineq_L⟩, let δ := λ h, if (h = 0) then 0 else P (ε h) + (∥ L h + ∥h∥•ε h ∥/∥h∥)• η (L h + ∥h∥•ε h), existsi δ, split, { -- prove (g ∘ f) (a + h) = (g ∘ f) a + (P ∘ L) h + ∥h∥ • δ h intro h, by_cases H : h = 0, { -- h = 0 case simp [H, cont_linPL.1.zero] }, { -- h ≠ 0 case have fact1 := calc (g ∘ f) (a + h) = g (f (a + h)): by refl ... = g (f a + L h + ∥h∥ • ε h) : by rw TEf ... = g (f a + (L h + ∥h∥ • ε h)) : by {simp, } ... = g (f a) + P (L h + ∥h∥ • ε h) + ∥ L h + ∥h∥ • ε h∥ • η (L h + ∥h∥ • ε h) : by rw TEg ... = g (f a) + P (L h) + ∥h∥ • P (ε h) + ∥ L h + ∥h∥ • ε h∥ • η (L h + ∥h∥ • ε h) : by { simp[lin_P.add, lin_P.smul] }, simp[δ, H, fact1], -- now we only need computing and h ≠ 0 -- clear fact1 lin_L ineq_L ML_pos ML lin_P ineq_P MP_pos MP cont_linPL δ TEf TEg f g lim_ε lim_η a, rw[smul_add, smul_smul], congr' 1, apply (congr_arg (λ x, x • η (L h + ∥h∥ • ε h))), rw [←mul_div_assoc, mul_comm, mul_div_cancel], exact mt norm_zero_iff_zero.1 H }, }, { -- prove δ →_0 0 apply tendsto_iff_norm_tendsto_zero.2, simp, have bound_δ : ∀ h :E, ∥ δ h ∥ ≤ MP*∥ε h∥ + ( ML + ∥ε h ∥)*∥ η (L h + ∥h∥•ε h)∥, { intro h, by_cases H : h = 0, { -- h = 0 case simp [δ], simp [H], apply add_nonneg'; apply mul_nonneg, exact le_of_lt MP_pos, exact norm_nonneg, exact add_nonneg' (le_of_lt ML_pos) norm_nonneg, exact norm_nonneg }, { -- h ≠ 0 case simp [δ], simp [H], have norm_h_pos : ∥h∥ > 0 := norm_pos_iff.2 H, have norm_h_non_zero : ∥h∥ ≠ 0 := ne_of_gt norm_h_pos, have prelim1 : ∥∥L h + ∥h∥ • ε h∥ / ∥h∥∥ = ∥L h + ∥h∥ • ε h∥ / ∥h∥ := abs_of_nonneg (div_nonneg_of_nonneg_of_pos norm_nonneg norm_h_pos), have prelim2 : ∥L h + ∥h∥ • ε h∥/∥h∥*∥η (L h + ∥h∥ • ε h)∥ ≤ (∥L h∥ + ∥∥h∥ • ε h∥)/∥h∥ * ∥η (L h + ∥h∥ • ε h)∥ := div_mul_le_div_mul_left norm_nonneg (norm_triangle _ _) norm_h_pos, have prelim3 : (∥L h∥ + ∥h∥ * ∥ε h∥) / ∥h∥ * ∥η (L h + ∥h∥ • ε h)∥ ≤ (ML * ∥h∥ + ∥h∥ * ∥ε h∥) / ∥h∥ * ∥η (L h + ∥h∥ • ε h)∥ := div_mul_le_div_mul_left norm_nonneg (add_le_add_right (ineq_L h) _) norm_h_pos, exact calc ∥P (ε h) + (∥L h + ∥h∥ • ε h∥ / ∥h∥) • η (L h + ∥h∥ • ε h)∥ ≤ ∥P (ε h)∥ + ∥ (∥L h + ∥h∥ • ε h∥ / ∥h∥) • η (L h + ∥h∥ • ε h)∥ : by simp[norm_triangle] ... ≤ MP*∥ε h∥ + (∥L h + ∥h∥ • ε h∥ / ∥h∥) * ∥ η (L h + ∥h∥ • ε h)∥ : by simp[norm_triangle, ineq_P, norm_smul, prelim1] ... ≤ MP*∥ε h∥ + ((∥L h∥ + ∥ ∥h∥ • ε h∥) / ∥h∥) * ∥ η (L h + ∥h∥ • ε h)∥ : by simp[norm_triangle, prelim2] ... ≤ MP*∥ε h∥ + ((ML*∥h∥ + ∥h∥ *∥ε h∥) / ∥h∥) * ∥ η (L h + ∥h∥ • ε h)∥ : by simp[norm_smul, prelim3] ... = MP*∥ε h∥ + (ML + ∥ε h∥)*∥h∥ / ∥h∥ * ∥ η (L h + ∥h∥ • ε h)∥ : by simp[mul_comm, add_mul] ... = MP*∥ε h∥ + (ML + ∥ε h∥) * ∥ η (L h + ∥h∥ • ε h)∥ : by simp[mul_div_cancel _ norm_h_non_zero] }, }, -- end of bound_δ proof apply squeeze_zero, exact assume t, norm_nonneg, exact bound_δ, rw [show (0:ℝ) = 0 + 0, by simp], apply tendsto_add _ _, { apply_instance }, { have limMP : (λ (h : E), MP) →_{0} MP := tendsto_const_nhds, simpa using tendsto_mul limMP (tendsto_iff_norm_tendsto_zero.1 lim_ε) }, { rw [show (0:ℝ) = ML*0, by simp], apply tendsto_mul _ _, { apply_instance }, { have limML : (λ (h : E), ML) →_{0} ML := tendsto_const_nhds, simpa using tendsto_add limML (tendsto_iff_norm_tendsto_zero.1 lim_ε) }, { have lim1 := tendsto_add (lim_zero_bounded_linear_map ⟨lin_L , ML, ML_pos, ineq_L⟩) (tendsto_smul lim_norm_zero lim_ε), simp at lim1, have := tendsto.comp lim1 lim_η, exact tendsto.comp this lim_norm_zero } }, } end⟩ end differential
01e5d85df7bb34b8f826a29f70f838c21997a0ef
07c76fbd96ea1786cc6392fa834be62643cea420
/hott/algebra/graph.hlean
7817aa8da1c0020816f52d11e3da84aff5dcb2bb
[ "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
14,202
hlean
/- Copyright (c) 2016 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Graphs and operations on graphs Currently we only define the notion of a path in a graph, and prove properties and operations on paths. -/ open eq sigma nat /- A path is a list of vertexes which are adjacent. We maybe use a weird ordering of cons, because the major example where we use this is a category where this ordering makes more sense. For the operations on paths we use the names from the corresponding operations on lists. Opening both the list and the paths namespace will lead to many name clashes, so that is not advised. -/ inductive paths {A : Type} (R : A → A → Type) : A → A → Type := | nil {} : Π{a : A}, paths R a a | cons : Π{a₁ a₂ a₃ : A} (r : R a₂ a₃), paths R a₁ a₂ → paths R a₁ a₃ namespace paths notation h :: t := cons h t notation `[` l:(foldr `, ` (h t, cons h t) nil `]`) := l variables {A : Type} {R : A → A → Type} {a a' a₁ a₂ a₃ a₄ : A} definition concat (r : R a₁ a₂) (l : paths R a₂ a₃) : paths R a₁ a₃ := begin induction l with a a₂ a₃ a₄ r' l IH, { exact [r]}, { exact r' :: IH r} end theorem concat_nil (r : R a₁ a₂) : concat r (@nil A R a₂) = [r] := idp theorem concat_cons (r : R a₁ a₂) (r' : R a₃ a₄) (l : paths R a₂ a₃) : concat r (r'::l) = r'::(concat r l) := idp definition append (l₂ : paths R a₂ a₃) (l₁ : paths R a₁ a₂) : paths R a₁ a₃ := begin induction l₂, { exact l₁}, { exact cons r (v_0 l₁)} end infix ` ++ ` := append definition nil_append (l : paths R a₁ a₂) : nil ++ l = l := idp definition cons_append (r : R a₃ a₄) (l₂ : paths R a₂ a₃) (l₁ : paths R a₁ a₂) : (r :: l₂) ++ l₁ = r :: (l₂ ++ l₁) := idp definition singleton_append (r : R a₂ a₃) (l : paths R a₁ a₂) : [r] ++ l = r :: l := idp definition append_singleton (l : paths R a₂ a₃) (r : R a₁ a₂) : l ++ [r] = concat r l := begin induction l, { reflexivity}, { exact ap (cons r) !v_0} end definition append_nil (l : paths R a₁ a₂) : l ++ nil = l := begin induction l, { reflexivity}, { exact ap (cons r) v_0} end definition append_assoc (l₃ : paths R a₃ a₄) (l₂ : paths R a₂ a₃) (l₁ : paths R a₁ a₂) : (l₃ ++ l₂) ++ l₁ = l₃ ++ (l₂ ++ l₁) := begin induction l₃, { reflexivity}, { refine ap (cons r) !v_0} end theorem append_concat (l₂ : paths R a₃ a₄) (l₁ : paths R a₂ a₃) (r : R a₁ a₂) : l₂ ++ concat r l₁ = concat r (l₂ ++ l₁) := begin induction l₂, { reflexivity}, { exact ap (cons r_1) !v_0} end theorem concat_append (l₂ : paths R a₃ a₄) (r : R a₂ a₃) (l₁ : paths R a₁ a₂) : concat r l₂ ++ l₁ = l₂ ++ r :: l₁ := begin induction l₂, { reflexivity}, { exact ap (cons r) !v_0} end definition paths.rec_tail {C : Π⦃a a' : A⦄, paths R a a' → Type} (H0 : Π {a : A}, @C a a nil) (H1 : Π {a₁ a₂ a₃ : A} (r : R a₁ a₂) (l : paths R a₂ a₃), C l → C (concat r l)) : Π{a a' : A} (l : paths R a a'), C l := begin have Π{a₁ a₂ a₃ : A} (l₂ : paths R a₂ a₃) (l₁ : paths R a₁ a₂) (c : C l₂), C (l₂ ++ l₁), begin intros, revert a₃ l₂ c, induction l₁: intros a₃ l₂ c, { rewrite append_nil, exact c}, { rewrite [-concat_append], apply v_0, apply H1, exact c} end, intros, rewrite [-nil_append], apply this, apply H0 end definition cons_eq_concat (r : R a₂ a₃) (l : paths R a₁ a₂) : Σa (r' : R a₁ a) (l' : paths R a a₃), r :: l = concat r' l' := begin revert a₃ r, induction l: intros a₃' r', { exact ⟨a₃', r', nil, idp⟩}, { cases (v_0 a₃ r) with a₄ w, cases w with r₂ w, cases w with l p, clear v_0, exact ⟨a₄, r₂, r' :: l, ap (cons r') p⟩} end definition length (l : paths R a₁ a₂) : ℕ := begin induction l, { exact 0}, { exact succ v_0} end /- If we can reverse edges in the graph we can reverse paths -/ definition reverse (rev : Π⦃a a'⦄, R a a' → R a' a) (l : paths R a₁ a₂) : paths R a₂ a₁ := begin induction l, { exact nil}, { exact concat (rev r) v_0} end theorem reverse_nil (rev : Π⦃a a'⦄, R a a' → R a' a) : reverse rev (@nil A R a₁) = [] := idp theorem reverse_cons (rev : Π⦃a a'⦄, R a a' → R a' a) (r : R a₂ a₃) (l : paths R a₁ a₂) : reverse rev (r::l) = concat (rev r) (reverse rev l) := idp theorem reverse_singleton (rev : Π⦃a a'⦄, R a a' → R a' a) (r : R a₁ a₂) : reverse rev [r] = [rev r] := idp theorem reverse_pair (rev : Π⦃a a'⦄, R a a' → R a' a) (r₂ : R a₂ a₃) (r₁ : R a₁ a₂) : reverse rev [r₂, r₁] = [rev r₁, rev r₂] := idp theorem reverse_concat (rev : Π⦃a a'⦄, R a a' → R a' a) (r : R a₁ a₂) (l : paths R a₂ a₃) : reverse rev (concat r l) = rev r :: (reverse rev l) := begin induction l, { reflexivity}, { rewrite [concat_cons, reverse_cons, v_0]} end theorem reverse_append (rev : Π⦃a a'⦄, R a a' → R a' a) (l₂ : paths R a₂ a₃) (l₁ : paths R a₁ a₂) : reverse rev (l₂ ++ l₁) = reverse rev l₁ ++ reverse rev l₂ := begin induction l₂, { exact !append_nil⁻¹}, { rewrite [cons_append, +reverse_cons, append_concat, v_0]} end definition realize (P : A → A → Type) (f : Π⦃a a'⦄, R a a' → P a a') (ρ : Πa, P a a) (c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃) ⦃a a' : A⦄ (l : paths R a a') : P a a' := begin induction l, { exact ρ a}, { exact c v_0 (f r)} end definition realize_nil (P : A → A → Type) (f : Π⦃a a'⦄, R a a' → P a a') (ρ : Πa, P a a) (c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃) (a : A) : realize P f ρ c nil = ρ a := idp definition realize_cons (P : A → A → Type) (f : Π⦃a a'⦄, R a a' → P a a') (ρ : Πa, P a a) (c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃) ⦃a₁ a₂ a₃ : A⦄ (r : R a₂ a₃) (l : paths R a₁ a₂) : realize P f ρ c (r :: l) = c (realize P f ρ c l) (f r) := idp theorem realize_singleton {P : A → A → Type} {f : Π⦃a a'⦄, R a a' → P a a'} {ρ : Πa, P a a} {c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃} (id_left : Π⦃a₁ a₂⦄ (p : P a₁ a₂), c (ρ a₁) p = p) ⦃a₁ a₂ : A⦄ (r : R a₁ a₂) : realize P f ρ c [r] = f r := id_left (f r) theorem realize_pair {P : A → A → Type} {f : Π⦃a a'⦄, R a a' → P a a'} {ρ : Πa, P a a} {c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃} (id_left : Π⦃a₁ a₂⦄ (p : P a₁ a₂), c (ρ a₁) p = p) ⦃a₁ a₂ a₃ : A⦄ (r₂ : R a₂ a₃) (r₁ : R a₁ a₂) : realize P f ρ c [r₂, r₁] = c (f r₁) (f r₂) := ap (λx, c x (f r₂)) (realize_singleton id_left r₁) theorem realize_append {P : A → A → Type} {f : Π⦃a a'⦄, R a a' → P a a'} {ρ : Πa, P a a} {c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃} (assoc : Π⦃a₁ a₂ a₃ a₄⦄ (p : P a₁ a₂) (q : P a₂ a₃) (r : P a₃ a₄), c (c p q) r = c p (c q r)) (id_right : Π⦃a₁ a₂⦄ (p : P a₁ a₂), c p (ρ a₂) = p) ⦃a₁ a₂ a₃ : A⦄ (l₂ : paths R a₂ a₃) (l₁ : paths R a₁ a₂) : realize P f ρ c (l₂ ++ l₁) = c (realize P f ρ c l₁) (realize P f ρ c l₂) := begin induction l₂, { exact !id_right⁻¹}, { rewrite [cons_append, +realize_cons, v_0, assoc]} end /- We sometimes want to take quotients of paths (this library was developed to define the pushout of categories). The definition paths_rel will - given some basic reduction rules codified by Q - extend the reduction to a reflexive transitive relation respecting concatenation of paths. -/ inductive paths_rel {A : Type} {R : A → A → Type} (Q : Π⦃a a' : A⦄, paths R a a' → paths R a a' → Type) : Π⦃a a' : A⦄, paths R a a' → paths R a a' → Type := | rrefl : Π{a a' : A} (l : paths R a a'), paths_rel Q l l | rel : Π{a₁ a₂ a₃ : A} {l₂ l₃ : paths R a₂ a₃} (l : paths R a₁ a₂) (q : Q l₂ l₃), paths_rel Q (l₂ ++ l) (l₃ ++ l) | rcons : Π{a₁ a₂ a₃ : A} {l₁ l₂ : paths R a₁ a₂} (r : R a₂ a₃), paths_rel Q l₁ l₂ → paths_rel Q (cons r l₁) (cons r l₂) | rtrans : Π{a₁ a₂ : A} {l₁ l₂ l₃ : paths R a₁ a₂}, paths_rel Q l₁ l₂ → paths_rel Q l₂ l₃ → paths_rel Q l₁ l₃ open paths_rel attribute rrefl [refl] attribute rtrans [trans] variables {Q : Π⦃a a' : A⦄, paths R a a' → paths R a a' → Type} definition paths_rel_of_Q {l₁ l₂ : paths R a₁ a₂} (q : Q l₁ l₂) : paths_rel Q l₁ l₂ := begin rewrite [-append_nil l₁, -append_nil l₂], exact rel nil q, end theorem rel_respect_append_left (l : paths R a₂ a₃) {l₃ l₄ : paths R a₁ a₂} (H : paths_rel Q l₃ l₄) : paths_rel Q (l ++ l₃) (l ++ l₄) := begin induction l, { exact H}, { exact rcons r (v_0 _ _ H)} end theorem rel_respect_append_right {l₁ l₂ : paths R a₂ a₃} (l : paths R a₁ a₂) (H₁ : paths_rel Q l₁ l₂) : paths_rel Q (l₁ ++ l) (l₂ ++ l) := begin induction H₁ with a₁ a₂ l₁ a₂ a₃ a₄ l₂ l₂' l₁ q a₂ a₃ a₄ l₁ l₂ r H₁ IH a₂ a₃ l₁ l₂ l₂' H₁ H₁' IH IH', { reflexivity}, { rewrite [+ append_assoc], exact rel _ q}, { exact rcons r (IH l) }, { exact rtrans (IH l) (IH' l)} end theorem rel_respect_append {l₁ l₂ : paths R a₂ a₃} {l₃ l₄ : paths R a₁ a₂} (H₁ : paths_rel Q l₁ l₂) (H₂ : paths_rel Q l₃ l₄) : paths_rel Q (l₁ ++ l₃) (l₂ ++ l₄) := begin induction H₁ with a₁ a₂ l a₂ a₃ a₄ l₂ l₂' l q a₂ a₃ a₄ l₁ l₂ r H₁ IH a₂ a₃ l₁ l₂ l₂' H₁ H₁' IH IH', { exact rel_respect_append_left _ H₂}, { rewrite [+ append_assoc], transitivity _, exact rel _ q, apply rel_respect_append_left, apply rel_respect_append_left, exact H₂}, { exact rcons r (IH _ _ H₂) }, { refine rtrans (IH _ _ H₂) _, apply rel_respect_append_right, exact H₁'} end /- assuming some extra properties the relation respects reversing -/ theorem rel_respect_reverse (rev : Π⦃a a'⦄, R a a' → R a' a) {l₁ l₂ : paths R a₁ a₂} (H : paths_rel Q l₁ l₂) (rev_rel : Π⦃a a' : A⦄ {l l' : paths R a a'}, Q l l' → paths_rel Q (reverse rev l) (reverse rev l')) : paths_rel Q (reverse rev l₁) (reverse rev l₂) := begin induction H, { reflexivity}, { rewrite [+ reverse_append], apply rel_respect_append_left, apply rev_rel q}, { rewrite [+reverse_cons,-+append_singleton], apply rel_respect_append_right, exact v_0}, { exact rtrans v_0 v_1} end theorem rel_left_inv (rev : Π⦃a a'⦄, R a a' → R a' a) (l : paths R a₁ a₂) (li : Π⦃a a' : A⦄ (r : R a a'), paths_rel Q [rev r, r] nil) : paths_rel Q (reverse rev l ++ l) nil := begin induction l, { reflexivity}, { rewrite [reverse_cons, concat_append], refine rtrans _ v_0, apply rel_respect_append_left, exact rel_respect_append_right _ (li r)} end theorem rel_right_inv (rev : Π⦃a a'⦄, R a a' → R a' a) (l : paths R a₁ a₂) (ri : Π⦃a a' : A⦄ (r : R a a'), paths_rel Q [r, rev r] nil) : paths_rel Q (l ++ reverse rev l) nil := begin induction l using paths.rec_tail, { reflexivity}, { rewrite [reverse_concat, concat_append], refine rtrans _ a, apply rel_respect_append_left, exact rel_respect_append_right _ (ri r)} end definition realize_eq {P : A → A → Type} {f : Π⦃a a'⦄, R a a' → P a a'} {ρ : Πa, P a a} {c : Π⦃a₁ a₂ a₃⦄, P a₁ a₂ → P a₂ a₃ → P a₁ a₃} (assoc : Π⦃a₁ a₂ a₃ a₄⦄ (p : P a₁ a₂) (q : P a₂ a₃) (r : P a₃ a₄), c (c p q) r = c p (c q r)) (id_right : Π⦃a₁ a₂⦄ (p : P a₁ a₂), c p (ρ a₂) = p) (resp_rel : Π⦃a₁ a₂⦄ {l₁ l₂ : paths R a₁ a₂}, Q l₁ l₂ → realize P f ρ c l₁ = realize P f ρ c l₂) ⦃a a' : A⦄ {l l' : paths R a a'} (H : paths_rel Q l l') : realize P f ρ c l = realize P f ρ c l' := begin induction H, { reflexivity}, { rewrite [+realize_append assoc id_right], apply ap (c _), exact resp_rel q}, { exact ap (λx, c x (f r)) v_0}, { exact v_0 ⬝ v_1} end inductive all (T : Π⦃a₁ a₂ : A⦄, R a₁ a₂ → Type) : Π⦃a₁ a₂ : A⦄, paths R a₁ a₂ → Type := | nil {} : Π{a : A}, all T (@nil A R a) | cons : Π{a₁ a₂ a₃ : A} {r : R a₂ a₃} {p : paths R a₁ a₂}, T r → all T p → all T (cons r p) inductive Exists (T : Π⦃a₁ a₂ : A⦄, R a₁ a₂ → Type) : Π⦃a₁ a₂ : A⦄, paths R a₁ a₂ → Type := | base : Π{a₁ a₂ a₃ : A} {r : R a₂ a₃} (p : paths R a₁ a₂), T r → Exists T (cons r p) | cons : Π{a₁ a₂ a₃ : A} (r : R a₂ a₃) {p : paths R a₁ a₂}, Exists T p → Exists T (cons r p) inductive mem (l : R a₃ a₄) : Π⦃a₁ a₂ : A⦄, paths R a₁ a₂ → Type := | base : Π{a₂ : A} (p : paths R a₂ a₃), mem l (cons l p) | cons : Π{a₁ a₂ a₃ : A} (r : R a₂ a₃) {p : paths R a₁ a₂}, mem l p → mem l (cons r p) definition len (p : paths R a₁ a₂) : ℕ := begin induction p with a a₁ a₂ a₃ r p IH, { exact 0 }, { exact nat.succ IH } end end paths
750e3a1d318452e5d3b7abfb11074340fef11bf5
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/equiv/local_equiv.lean
d2b2758f5e6ad00a9316b004ece525dcc849d158
[ "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
33,890
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 import data.set.function /-! # 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. ### Local coding conventions If a lemma deals with the intersection of a set with either source or target of a `local_equiv`, then it should use `e.source ∩ s` or `e.target ∩ t`, not `s ∩ e.source` or `t ∩ e.target`. -/ mk_simp_attribute mfld_simps "The simpset `mfld_simps` records several simp lemmas that are especially useful in manifolds. It is a subset of the whole set of simp lemmas, but it makes it possible to have quicker proofs (when used with `squeeze_simp` or `simp only`) while retaining readability. The typical use case is the following, in a file on manifolds: If `simp [foo, bar]` is slow, replace it with `squeeze_simp [foo, bar] with mfld_simps` and paste its output. The list of lemmas should be reasonable (contrary to the output of `squeeze_simp [foo, bar]` which might contain tens of lemmas), and the outcome should be quick enough. " -- register in the simpset `mfld_simps` several lemmas that are often useful when dealing -- with manifolds attribute [mfld_simps] id.def function.comp.left_id set.mem_set_of_eq set.image_eq_empty set.univ_inter set.preimage_univ set.prod_mk_mem_set_prod_eq and_true set.mem_univ set.mem_image_of_mem true_and set.mem_inter_eq set.mem_preimage function.comp_app set.inter_subset_left set.mem_prod set.range_id set.range_prod_map and_self set.mem_range_self eq_self_iff_true forall_const forall_true_iff set.inter_univ set.preimage_id function.comp.right_id not_false_iff and_imp set.prod_inter_prod set.univ_prod_univ true_or or_true prod.map_mk set.preimage_inter heq_iff_eq equiv.sigma_equiv_prod_apply equiv.sigma_equiv_prod_symm_apply subtype.coe_mk equiv.to_fun_as_coe equiv.inv_fun_as_coe /-- Common `@[simps]` configuration options used for manifold-related declarations. -/ def mfld_cfg : simps_cfg := {attrs := [`simp, `mfld_simps], fully_applied := ff} namespace tactic.interactive /-- A very basic tactic to show that sets showing up in manifolds coincide or are included in one another. -/ meta def mfld_set_tac : tactic unit := do goal ← tactic.target, match goal with | `(%%e₁ = %%e₂) := `[ext my_y, split; { assume h_my_y, try { simp only [*, -h_my_y] with mfld_simps at h_my_y }, simp only [*] with mfld_simps }] | `(%%e₁ ⊆ %%e₂) := `[assume my_y h_my_y, try { simp only [*, -h_my_y] with mfld_simps at h_my_y }, simp only [*] with mfld_simps] | _ := tactic.fail "goal should be an equality or an inclusion" end end tactic.interactive open function set variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} /-- Local equivalence between subsets `source` and `target` of α and β respectively. The (global) maps `to_fun : α → β` and `inv_fun : β → α` map `source` to `target` and conversely, and are inverse to each other there. The values of `to_fun` outside of `source` and of `inv_fun` outside of `target` are irrelevant. -/ @[nolint has_inhabited_instance] structure local_equiv (α : Type*) (β : Type*) := (to_fun : α → β) (inv_fun : β → α) (source : set α) (target : set β) (map_source' : ∀{x}, x ∈ source → to_fun x ∈ target) (map_target' : ∀{x}, x ∈ target → inv_fun x ∈ source) (left_inv' : ∀{x}, x ∈ source → inv_fun (to_fun x) = x) (right_inv' : ∀{x}, x ∈ target → to_fun (inv_fun x) = x) /-- Associating a local_equiv to an equiv-/ def equiv.to_local_equiv (e : α ≃ β) : local_equiv α β := { to_fun := e, inv_fun := e.symm, 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⟩ /-- See Note [custom simps projection] -/ def simps.symm_apply (e : local_equiv α β) : β → α := e.symm initialize_simps_projections local_equiv (to_fun → apply, inv_fun → symm_apply) @[simp, mfld_simps] theorem coe_mk (f : α → β) (g s t ml mr il ir) : (local_equiv.mk f g s t ml mr il ir : α → β) = f := rfl @[simp, mfld_simps] theorem coe_symm_mk (f : α → β) (g s t ml mr il ir) : ((local_equiv.mk f g s t ml mr il ir).symm : β → α) = g := rfl @[simp, mfld_simps] lemma to_fun_as_coe : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_as_coe : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h @[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h protected lemma maps_to : maps_to e e.source e.target := λ x, e.map_source lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to protected lemma left_inv_on : left_inv_on e.symm e e.source := λ x, e.left_inv protected lemma right_inv_on : right_inv_on e.symm e e.target := λ x, e.right_inv protected lemma inv_on : inv_on e.symm e e.source e.target := ⟨e.left_inv_on, e.right_inv_on⟩ protected lemma inj_on : inj_on e e.source := e.left_inv_on.inj_on protected lemma bij_on : bij_on e e.source e.target := e.inv_on.bij_on e.maps_to e.symm_maps_to protected lemma surj_on : surj_on e e.source e.target := e.bij_on.surj_on /-- Create a copy of a `local_equiv` providing better definitional equalities. -/ @[simps] def copy (e : local_equiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g) (s : set α) (hs : e.source = s) (t : set β) (ht : e.target = t) : local_equiv α β := { to_fun := f, inv_fun := g, source := s, target := t, map_source' := λ x, ht ▸ hs ▸ hf ▸ e.map_source, map_target' := λ y, hs ▸ ht ▸ hg ▸ e.map_target, left_inv' := λ x, hs ▸ hf ▸ hg ▸ e.left_inv, right_inv' := λ x, ht ▸ hf ▸ hg ▸ e.right_inv } lemma copy_eq_self (e : local_equiv α β) (f : α → β) (hf : ⇑e = f) (g : β → α) (hg : ⇑e.symm = g) (s : set α) (hs : e.source = s) (t : set β) (ht : e.target = t) : e.copy f hf g hg s hs t ht = e := by { substs f g s t, cases e, refl } /-- Associating to a local_equiv an equiv between the source and the target -/ protected def to_equiv : equiv (e.source) (e.target) := { to_fun := λ x, ⟨e x, e.map_source x.mem⟩, inv_fun := λ y, ⟨e.symm y, e.map_target y.mem⟩, left_inv := λ⟨x, hx⟩, subtype.eq $ e.left_inv hx, right_inv := λ⟨y, hy⟩, subtype.eq $ e.right_inv hy } @[simp, mfld_simps] lemma symm_source : e.symm.source = e.target := rfl @[simp, mfld_simps] lemma symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := by { cases e, refl } lemma image_source_eq_target : e '' e.source = e.target := e.bij_on.image_eq /-- We say that `t : set β` is an image of `s : set α` under a local equivalence if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). -/ def is_image (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ e.source → (e x ∈ t ↔ x ∈ s) namespace is_image variables {e} {s : set α} {t : set β} {x : α} {y : β} lemma apply_mem_iff (h : e.is_image s t) (hx : x ∈ e.source) : e x ∈ t ↔ x ∈ s := h hx lemma symm_apply_mem_iff (h : e.is_image s t) : ∀ ⦃y⦄, y ∈ e.target → (e.symm y ∈ s ↔ y ∈ t) := by { rw [← e.image_source_eq_target, ball_image_iff], intros x hx, rw [e.left_inv hx, h hx] } protected lemma symm (h : e.is_image s t) : e.symm.is_image t s := h.symm_apply_mem_iff @[simp] lemma symm_iff : e.symm.is_image t s ↔ e.is_image s t := ⟨λ h, h.symm, λ h, h.symm⟩ protected lemma maps_to (h : e.is_image s t) : maps_to e (e.source ∩ s) (e.target ∩ t) := λ x hx, ⟨e.maps_to hx.1, (h hx.1).2 hx.2⟩ lemma symm_maps_to (h : e.is_image s t) : maps_to e.symm (e.target ∩ t) (e.source ∩ s) := h.symm.maps_to /-- Restrict a `local_equiv` to a pair of corresponding sets. -/ @[simps] def restr (h : e.is_image s t) : local_equiv α β := { to_fun := e, inv_fun := e.symm, source := e.source ∩ s, target := e.target ∩ t, map_source' := h.maps_to, map_target' := h.symm_maps_to, left_inv' := e.left_inv_on.mono (inter_subset_left _ _), right_inv' := e.right_inv_on.mono (inter_subset_left _ _) } lemma image_eq (h : e.is_image s t) : e '' (e.source ∩ s) = e.target ∩ t := h.restr.image_source_eq_target lemma symm_image_eq (h : e.is_image s t) : e.symm '' (e.target ∩ t) = e.source ∩ s := h.symm.image_eq lemma iff_preimage_eq : e.is_image s t ↔ e.source ∩ e ⁻¹' t = e.source ∩ s := by simp only [is_image, set.ext_iff, mem_inter_eq, and.congr_right_iff, mem_preimage] alias iff_preimage_eq ↔ local_equiv.is_image.preimage_eq local_equiv.is_image.of_preimage_eq lemma iff_symm_preimage_eq : e.is_image s t ↔ e.target ∩ e.symm ⁻¹' s = e.target ∩ t := symm_iff.symm.trans iff_preimage_eq alias iff_symm_preimage_eq ↔ local_equiv.is_image.symm_preimage_eq local_equiv.is_image.of_symm_preimage_eq lemma of_image_eq (h : e '' (e.source ∩ s) = e.target ∩ t) : e.is_image s t := of_symm_preimage_eq $ eq.trans (of_symm_preimage_eq rfl).image_eq.symm h lemma of_symm_image_eq (h : e.symm '' (e.target ∩ t) = e.source ∩ s) : e.is_image s t := of_preimage_eq $ eq.trans (of_preimage_eq rfl).symm_image_eq.symm h protected lemma compl (h : e.is_image s t) : e.is_image sᶜ tᶜ := λ x hx, not_congr (h hx) protected lemma inter {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∩ s') (t ∩ t') := λ x hx, and_congr (h hx) (h' hx) protected lemma union {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∪ s') (t ∪ t') := λ x hx, or_congr (h hx) (h' hx) protected lemma diff {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s \ s') (t \ t') := h.inter h'.compl lemma left_inv_on_piecewise {e' : local_equiv α β} [∀ i, decidable (i ∈ s)] [∀ i, decidable (i ∈ t)] (h : e.is_image s t) (h' : e'.is_image s t) : left_inv_on (t.piecewise e.symm e'.symm) (s.piecewise e e') (s.ite e.source e'.source) := begin rintro x (⟨he, hs⟩|⟨he, hs : x ∉ s⟩), { rw [piecewise_eq_of_mem _ _ _ hs, piecewise_eq_of_mem _ _ _ ((h he).2 hs), e.left_inv he], }, { rw [piecewise_eq_of_not_mem _ _ _ hs, piecewise_eq_of_not_mem _ _ _ ((h'.compl he).2 hs), e'.left_inv he] } end lemma inter_eq_of_inter_eq_of_eq_on {e' : local_equiv α β} (h : e.is_image s t) (h' : e'.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : e.target ∩ t = e'.target ∩ t := by rw [← h.image_eq, ← h'.image_eq, ← hs, Heq.image_eq] lemma symm_eq_on_of_inter_eq_of_eq_on {e' : local_equiv α β} (h : e.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : eq_on e.symm e'.symm (e.target ∩ t) := begin rw [← h.image_eq], rintros y ⟨x, hx, rfl⟩, have hx' := hx, rw hs at hx', rw [e.left_inv hx.1, Heq hx, e'.left_inv hx'.1] end end is_image lemma is_image_source_target : e.is_image e.source e.target := λ x hx, by simp [hx] lemma is_image_source_target_of_disjoint (e' : local_equiv α β) (hs : disjoint e.source e'.source) (ht : disjoint e.target e'.target) : e.is_image e'.source e'.target := assume x hx, have x ∉ e'.source, from λ hx', hs ⟨hx, hx'⟩, have e x ∉ e'.target, from λ hx', ht ⟨e.maps_to hx, hx'⟩, by simp only * lemma image_source_inter_eq' (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' s := by rw [inter_comm, e.left_inv_on.image_inter', image_source_eq_target, inter_comm] lemma image_source_inter_eq (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' (e.source ∩ s) := by rw [inter_comm, e.left_inv_on.image_inter, image_source_eq_target, inter_comm] lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := by rw [← e.image_source_inter_eq', inter_eq_self_of_subset_right h] lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma symm_image_target_inter_eq (s : set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' (e.target ∩ s) := e.symm.image_source_inter_eq _ lemma symm_image_target_inter_eq' (s : set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' s := e.symm.image_source_inter_eq' _ lemma source_inter_preimage_inv_preimage (s : set α) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := set.ext $ λ x, and.congr_right_iff.2 $ λ hx, by simp only [mem_preimage, e.left_inv hx] lemma source_inter_preimage_target_inter (s : set β) : e.source ∩ (e ⁻¹' (e.target ∩ s)) = e.source ∩ (e ⁻¹' s) := ext $ λ x, ⟨λ hx, ⟨hx.1, hx.2.2⟩, λ hx, ⟨hx.1, e.map_source hx.1, hx.2⟩⟩ lemma target_inter_inv_preimage_preimage (s : set β) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ lemma source_subset_preimage_target : e.source ⊆ e ⁻¹' e.target := e.maps_to lemma symm_image_target_eq_source : e.symm '' e.target = e.source := e.symm.image_source_eq_target lemma target_subset_preimage_source : e.target ⊆ e.symm ⁻¹' e.source := e.symm_maps_to /-- 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 α β := (@is_image.of_symm_preimage_eq α β e s (e.symm ⁻¹' s) rfl).restr @[simp, mfld_simps] lemma restr_coe (s : set α) : (e.restr s : α → β) = e := rfl @[simp, mfld_simps] lemma restr_coe_symm (s : set α) : ((e.restr s).symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ s := rfl @[simp, mfld_simps] lemma restr_target (s : set α) : (e.restr s).target = e.target ∩ e.symm ⁻¹' s := rfl lemma restr_eq_of_source_subset {e : local_equiv α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := local_equiv.ext (λ_, rfl) (λ_, rfl) (by simp [inter_eq_self_of_subset_left h]) @[simp, mfld_simps] lemma restr_univ {e : local_equiv α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) /-- The identity local equiv -/ protected def refl (α : Type*) : local_equiv α α := (equiv.refl α).to_local_equiv @[simp, mfld_simps] lemma refl_source : (local_equiv.refl α).source = univ := rfl @[simp, mfld_simps] lemma refl_target : (local_equiv.refl α).target = univ := rfl @[simp, mfld_simps] lemma refl_coe : (local_equiv.refl α : α → α) = id := rfl @[simp, mfld_simps] lemma refl_symm : (local_equiv.refl α).symm = local_equiv.refl α := rfl @[simp, mfld_simps] lemma refl_restr_source (s : set α) : ((local_equiv.refl α).restr s).source = s := by simp @[simp, mfld_simps] lemma refl_restr_target (s : set α) : ((local_equiv.refl α).restr s).target = s := by { change univ ∩ id⁻¹' s = s, simp } /-- The identity local equiv on a set `s` -/ def of_set (s : set α) : local_equiv α α := { to_fun := id, inv_fun := id, source := s, target := s, map_source' := λx hx, hx, map_target' := λx hx, hx, left_inv' := λx hx, rfl, right_inv' := λx hx, rfl } @[simp, mfld_simps] lemma of_set_source (s : set α) : (local_equiv.of_set s).source = s := rfl @[simp, mfld_simps] lemma of_set_target (s : set α) : (local_equiv.of_set s).target = s := rfl @[simp, mfld_simps] lemma of_set_coe (s : set α) : (local_equiv.of_set s : α → α) = id := rfl @[simp, mfld_simps] lemma of_set_symm (s : set α) : (local_equiv.of_set s).symm = local_equiv.of_set s := rfl /-- Composing two local equivs if the target of the first coincides with the source of the second. -/ protected def trans' (e' : local_equiv β γ) (h : e.target = e'.source) : local_equiv α γ := { to_fun := e' ∘ e, inv_fun := e.symm ∘ e'.symm, source := e.source, target := e'.target, map_source' := λx hx, by simp [h.symm, hx], map_target' := λy hy, by simp [h, hy], left_inv' := λx hx, by simp [hx, h.symm], right_inv' := λy hy, by simp [hy, h] } /-- Composing two local equivs, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_equiv α γ := local_equiv.trans' (e.symm.restr (e'.source)).symm (e'.restr (e.target)) (inter_comm _ _) @[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl @[simp, mfld_simps] lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := rfl lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := by mfld_set_tac lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := by rw [e.trans_source', e.symm_image_target_inter_eq] lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := (e.symm.restr e'.source).symm.image_source_eq_target @[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 := by rw [he.eq_on.inter_preimage_eq, he.source_eq] /-- Composition of a local equiv and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_equiv.of_set e.source := begin have A : (e.trans e.symm).source = e.source, by mfld_set_tac, refine ⟨by simp [A], λx hx, _⟩, rw A at hx, simp only [hx] with mfld_simps end /-- Composition of the inverse of a local equiv and this local equiv is equivalent to the restriction of the identity to the target -/ lemma trans_symm_self : e.symm.trans e ≈ local_equiv.of_set e.target := trans_self_symm (e.symm) /-- Two equivalent local equivs are equal when the source and target are univ -/ lemma eq_of_eq_on_source_univ (e e' : local_equiv α β) (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := begin apply local_equiv.ext (λx, _) (λx, _) h.1, { apply h.2, rw s, exact mem_univ _ }, { apply h.symm'.2, rw [symm_source, t], exact mem_univ _ } end section prod /-- The product of two local equivs, as a local equiv on the product. -/ def prod (e : local_equiv α β) (e' : local_equiv γ δ) : local_equiv (α × γ) (β × δ) := { source := set.prod e.source e'.source, target := set.prod e.target e'.target, to_fun := λp, (e p.1, e' p.2), inv_fun := λp, (e.symm p.1, e'.symm p.2), map_source' := λp hp, by { simp at hp, simp [hp] }, map_target' := λp hp, by { simp at hp, simp [map_target, hp] }, left_inv' := λp hp, by { simp at hp, simp [hp] }, right_inv' := λp hp, by { simp at hp, simp [hp] } } @[simp, mfld_simps] lemma prod_source (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').source = set.prod e.source e'.source := rfl @[simp, mfld_simps] lemma prod_target (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').target = set.prod e.target e'.target := rfl @[simp, mfld_simps] lemma prod_coe (e : local_equiv α β) (e' : local_equiv γ δ) : ((e.prod e') : α × γ → β × δ) = (λp, (e p.1, e' p.2)) := rfl lemma prod_coe_symm (e : local_equiv α β) (e' : local_equiv γ δ) : ((e.prod e').symm : β × δ → α × γ) = (λp, (e.symm p.1, e'.symm p.2)) := rfl @[simp, mfld_simps] lemma prod_symm (e : local_equiv α β) (e' : local_equiv γ δ) : (e.prod e').symm = (e.symm.prod e'.symm) := by ext x; simp [prod_coe_symm] @[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*} (e : local_equiv α β) (f : local_equiv β γ) (e' : local_equiv δ η) (f' : local_equiv η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := by ext x; simp [ext_iff]; tauto end prod /-- Combine two `local_equiv`s using `set.piecewise`. The source of the new `local_equiv` is `s.ite e.source e'.source = e.source ∩ s ∪ e'.source \ s`, and similarly for target. The function sends `e.source ∩ s` to `e.target ∩ t` using `e` and `e'.source \ s` to `e'.target \ t` using `e'`, and similarly for the inverse function. The definition assumes `e.is_image s t` and `e'.is_image s t`. -/ @[simps] def piecewise (e e' : local_equiv α β) (s : set α) (t : set β) [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) : local_equiv α β := { to_fun := s.piecewise e e', inv_fun := t.piecewise e.symm e'.symm, source := s.ite e.source e'.source, target := t.ite e.target e'.target, map_source' := H.maps_to.piecewise_ite H'.compl.maps_to, map_target' := H.symm.maps_to.piecewise_ite H'.symm.compl.maps_to, left_inv' := H.left_inv_on_piecewise H', right_inv' := H.symm.left_inv_on_piecewise H'.symm } lemma symm_piecewise (e e' : local_equiv α β) {s : set α} {t : set β} [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) : (e.piecewise e' s t H H').symm = e.symm.piecewise e'.symm t s H.symm H'.symm := rfl /-- Combine two `local_equiv`s with disjoint sources and disjoint targets. We reuse `local_equiv.piecewise`, then override `source` and `target` to ensure better definitional equalities. -/ @[simps] def disjoint_union (e e' : local_equiv α β) (hs : disjoint e.source e'.source) (ht : disjoint e.target e'.target) [∀ x, decidable (x ∈ e.source)] [∀ y, decidable (y ∈ e.target)] : local_equiv α β := (e.piecewise e' e.source e.target e.is_image_source_target $ e'.is_image_source_target_of_disjoint _ hs.symm ht.symm).copy _ rfl _ rfl (e.source ∪ e'.source) (ite_left _ _) (e.target ∪ e'.target) (ite_left _ _) lemma disjoint_union_eq_piecewise (e e' : local_equiv α β) (hs : disjoint e.source e'.source) (ht : disjoint e.target e'.target) [∀ x, decidable (x ∈ e.source)] [∀ y, decidable (y ∈ e.target)] : e.disjoint_union e' hs ht = e.piecewise e' e.source e.target e.is_image_source_target (e'.is_image_source_target_of_disjoint _ hs.symm ht.symm) := copy_eq_self _ _ _ _ _ _ _ _ _ section pi variables {ι : Type*} {αi βi : ι → Type*} (ei : Π i, local_equiv (αi i) (βi i)) /-- The product of a family of local equivs, as a local equiv on the pi type. -/ @[simps source target] protected def pi : local_equiv (Π i, αi i) (Π i, βi i) := { to_fun := λ f i, ei i (f i), inv_fun := λ f i, (ei i).symm (f i), source := pi univ (λ i, (ei i).source), target := pi univ (λ i, (ei i).target), map_source' := λ f hf i hi, (ei i).map_source (hf i hi), map_target' := λ f hf i hi, (ei i).map_target (hf i hi), left_inv' := λ f hf, funext $ λ i, (ei i).left_inv (hf i trivial), right_inv' := λ f hf, funext $ λ i, (ei i).right_inv (hf i trivial) } attribute [mfld_simps] pi_source pi_target @[simp, mfld_simps] lemma pi_coe : ⇑(local_equiv.pi ei) = λ (f : Π i, αi i) i, ei i (f i) := rfl @[simp, mfld_simps] lemma pi_symm : (local_equiv.pi ei).symm = local_equiv.pi (λ i, (ei i).symm) := rfl end pi 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
a7fbeb81aec024261a0d66f9c73be71ad8bf6fb1
556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e
/src/starkware/cairo/common/cairo_secp/verification/signature_recover_public_key_spec.lean
34cf1cea39862b4be640fa908ea406bf0536d5ed
[]
permissive
starkware-libs/formal-proofs
d6b731604461bf99e6ba820e68acca62a21709e8
f5fa4ba6a471357fd171175183203d0b437f6527
refs/heads/master
1,691,085,444,753
1,690,507,386,000
1,690,507,386,000
410,476,629
32
9
Apache-2.0
1,690,506,773,000
1,632,639,790,000
Lean
UTF-8
Lean
false
false
2,604
lean
/- Specifications file for signature_recover_public_key_spec.cairo Do not modify the constant definitions, structure definitions, or automatic specifications. Do not change the name or arguments of the user specifications and soundness theorems. You may freely move the definitions around in the file. You may add definitions and theorems wherever you wish in this file. -/ import starkware.cairo.lean.semantics.soundness.prelude import starkware.cairo.common.cairo_secp.bigint_spec import starkware.cairo.common.cairo_secp.ec_spec import starkware.cairo.common.cairo_secp.signature_spec import starkware.cairo.common.cairo_secp.field_spec import starkware.cairo.common.math_spec open starkware.cairo.common.cairo_secp.bigint open starkware.cairo.common.cairo_secp.ec open starkware.cairo.common.cairo_secp.signature open starkware.cairo.common.cairo_secp.field open starkware.cairo.common.math namespace starkware.cairo.common.cairo_secp.verification.signature_recover_public_key variables {F : Type} [field F] [decidable_eq F] [prelude_hyps F] -- End of automatically generated prelude. /- -- Function: call_recover_public_key -/ /- call_recover_public_key autogenerated specification -/ -- Do not change this definition. def auto_spec_call_recover_public_key (mem : F → F) (κ : ℕ) (range_check_ptr : F) (msg_hash r s : BigInt3 F) (v ρ_range_check_ptr : F) (ρ_public_key_point : EcPoint F) : Prop := ∃ (κ₁ : ℕ), spec_recover_public_key mem κ₁ range_check_ptr msg_hash r s v ρ_range_check_ptr ρ_public_key_point ∧ κ₁ + 13 ≤ κ -- You may change anything in this definition except the name and arguments. def spec_call_recover_public_key (mem : F → F) (κ : ℕ) (range_check_ptr : F) (msg_hash r s : BigInt3 F) (v ρ_range_check_ptr : F) (ρ_public_key_point : EcPoint F) : Prop := auto_spec_call_recover_public_key mem κ range_check_ptr msg_hash r s v ρ_range_check_ptr ρ_public_key_point /- call_recover_public_key soundness theorem -/ -- Do not change the statement of this theorem. You may change the proof. theorem sound_call_recover_public_key {mem : F → F} (κ : ℕ) (range_check_ptr : F) (msg_hash r s : BigInt3 F) (v ρ_range_check_ptr : F) (ρ_public_key_point : EcPoint F) (h_auto : auto_spec_call_recover_public_key mem κ range_check_ptr msg_hash r s v ρ_range_check_ptr ρ_public_key_point) : spec_call_recover_public_key mem κ range_check_ptr msg_hash r s v ρ_range_check_ptr ρ_public_key_point := begin exact h_auto end end starkware.cairo.common.cairo_secp.verification.signature_recover_public_key
8469165c52d4b2399571dd1c9527b2d84ffff931
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/linear_independent.lean
6909aa5e94a1d6907233ff0996a2aa7e4f775b9b
[ "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
57,222
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 linear_algebra.finsupp import linear_algebra.prod import logic.equiv.fin 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] 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, ← 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, have zero_not_mem : (0 : fin m.succ) ∉ finset.univ.image (fin.succ : fin m → fin m.succ), { rw finset.mem_image, rintro ⟨x, hx, succ_eq⟩, exact fin.succ_ne_zero _ succ_eq }, simp only [submodule.coe_mk, fin.univ_succ, finset.sum_insert zero_not_mem, fin.cons_zero, fin.cons_succ, forall_true_iff, imp_self, fin.succ_inj, finset.sum_image] 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⟩)) }, refine fin.cases this (λ j, _) j, apply hli (λ i, g i.succ), simpa only [this, zero_smul, zero_add] using total_eq 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, ← 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, 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 := finsupp.disjoint_supported_supported hs (submodule.mem_inf.2 ⟨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) } }, { 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 ι, finite t → 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 η, finite t → 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) _), { 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⟩ 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 }, { exact f.injective } }, 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 : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, 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 finite s, 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
b2e4d0749d5bfd31da2b3f2c73aff7b57da679e0
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/eqn_issue.lean
c1ba39156f689c89264c6b6f9642283a34781f75
[ "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
200
lean
universe variable u variable {α : Type u} def split : list α → list α × list α | [] := ([], []) | [a] := ([a], []) | (a :: b :: l) := (a :: (split l).1, b :: (split l).2)
caf1e4f2f054f17e2430205ce2357e880d72df79
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/field_theory/finite/polynomial.lean
75cdcd888409b8a205ebc3aa859a2abc5bfeae2f
[]
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,174
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.field_theory.finite.basic import Mathlib.field_theory.mv_polynomial import Mathlib.data.mv_polynomial.expand import Mathlib.linear_algebra.basic import Mathlib.PostPort universes u_1 u_2 u namespace Mathlib /-! ## Polynomials over finite fields -/ namespace mv_polynomial /-- A polynomial over the integers is divisible by `n : ℕ` if and only if it is zero over `zmod n`. -/ theorem C_dvd_iff_zmod {σ : Type u_1} (n : ℕ) (φ : mv_polynomial σ ℤ) : coe_fn C ↑n ∣ φ ↔ coe_fn (map (int.cast_ring_hom (zmod n))) φ = 0 := C_dvd_iff_map_hom_eq_zero (int.cast_ring_hom (zmod n)) (↑n) (char_p.int_cast_eq_zero_iff (zmod n) n) φ theorem frobenius_zmod {σ : Type u_1} {p : ℕ} [fact (nat.prime p)] (f : mv_polynomial σ (zmod p)) : coe_fn (frobenius (mv_polynomial σ (zmod p)) p) f = coe_fn (expand p) f := sorry theorem expand_zmod {σ : Type u_1} {p : ℕ} [fact (nat.prime p)] (f : mv_polynomial σ (zmod p)) : coe_fn (expand p) f = f ^ p := Eq.symm (frobenius_zmod f) end mv_polynomial namespace mv_polynomial def indicator {K : Type u_1} {σ : Type u_2} [field K] [fintype K] [fintype σ] (a : σ → K) : mv_polynomial σ K := finset.prod finset.univ fun (n : σ) => 1 - (X n - coe_fn C (a n)) ^ (fintype.card K - 1) theorem eval_indicator_apply_eq_one {K : Type u_1} {σ : Type u_2} [field K] [fintype K] [fintype σ] (a : σ → K) : coe_fn (eval a) (indicator a) = 1 := sorry theorem eval_indicator_apply_eq_zero {K : Type u_1} {σ : Type u_2} [field K] [fintype K] [fintype σ] (a : σ → K) (b : σ → K) (h : a ≠ b) : coe_fn (eval a) (indicator b) = 0 := sorry theorem degrees_indicator {K : Type u_1} {σ : Type u_2} [field K] [fintype K] [fintype σ] (c : σ → K) : degrees (indicator c) ≤ finset.sum finset.univ fun (s : σ) => (fintype.card K - 1) •ℕ singleton s := sorry theorem indicator_mem_restrict_degree {K : Type u_1} {σ : Type u_2} [field K] [fintype K] [fintype σ] (c : σ → K) : indicator c ∈ restrict_degree σ K (fintype.card K - 1) := sorry def evalₗ (K : Type u_1) (σ : Type u_2) [field K] [fintype K] [fintype σ] : linear_map K (mv_polynomial σ K) ((σ → K) → K) := linear_map.mk (fun (p : mv_polynomial σ K) (e : σ → K) => coe_fn (eval e) p) sorry sorry theorem evalₗ_apply {K : Type u_1} {σ : Type u_2} [field K] [fintype K] [fintype σ] (p : mv_polynomial σ K) (e : σ → K) : coe_fn (evalₗ K σ) p e = coe_fn (eval e) p := rfl theorem map_restrict_dom_evalₗ {K : Type u_1} {σ : Type u_2} [field K] [fintype K] [fintype σ] : submodule.map (evalₗ K σ) (restrict_degree σ K (fintype.card K - 1)) = ⊤ := sorry end mv_polynomial namespace mv_polynomial def R (σ : Type u) (K : Type u) [fintype σ] [field K] [fintype K] := ↥(restrict_degree σ K (fintype.card K - 1)) protected instance decidable_restrict_degree (σ : Type u) [fintype σ] (m : ℕ) : decidable_pred fun (n : σ →₀ ℕ) => n ∈ set_of fun (n : σ →₀ ℕ) => ∀ (i : σ), coe_fn n i ≤ m := eq.mpr sorry fun (a : σ →₀ ℕ) => fintype.decidable_forall_fintype theorem dim_R (σ : Type u) (K : Type u) [fintype σ] [field K] [fintype K] : vector_space.dim K (R σ K) = ↑(fintype.card (σ → K)) := sorry def evalᵢ (σ : Type u) (K : Type u) [fintype σ] [field K] [fintype K] : linear_map K (R σ K) ((σ → K) → K) := linear_map.comp (evalₗ K σ) (submodule.subtype (restrict_degree σ K (fintype.card K - 1))) theorem range_evalᵢ (σ : Type u) (K : Type u) [fintype σ] [field K] [fintype K] : linear_map.range (evalᵢ σ K) = ⊤ := sorry theorem ker_evalₗ (σ : Type u) (K : Type u) [fintype σ] [field K] [fintype K] : linear_map.ker (evalᵢ σ K) = ⊥ := sorry theorem eq_zero_of_eval_eq_zero (σ : Type u) (K : Type u) [fintype σ] [field K] [fintype K] (p : mv_polynomial σ K) (h : ∀ (v : σ → K), coe_fn (eval v) p = 0) (hp : p ∈ restrict_degree σ K (fintype.card K - 1)) : p = 0 := sorry
90aa1525f39c2257e62b246da5f3807c8cb3e437
4f9ca1935adf84f1bae9c5740ec1f2ad406716fa
/src/topology/algebra/module.lean
d6db00c9ad1c4bf9272139f15b91387693e5132d
[ "Apache-2.0" ]
permissive
matthew-hilty/mathlib
36fd7db866365e9ee4a0ba1d6f8ad34d068cec6c
585e107f9811719832c6656f49e1263a8eef5380
refs/heads/master
1,607,100,509,178
1,578,151,707,000
1,578,151,707,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,942
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo -/ import topology.algebra.ring linear_algebra.basic ring_theory.algebra /-! # Theory of topological modules and continuous linear maps. We define classes `topological_semimodule`, `topological_module` and `topological_vector_spaces`, as extensions of the corresponding algebraic classes where the algebraic operations are continuous. We also define continuous linear maps, as linear maps between topological modules which are continuous. The set of continuous linear maps between the topological `R`-modules `M` and `M₂` is denoted by `M →L[R] M₂`. Continuous linear equivalences are denoted by `M ≃L[R] M₂`. ## Implementation notes Topological vector spaces are defined as an `abbreviation` for topological modules, if the base ring is a field. This has as advantage that topological vector spaces are completely transparent for type class inference, which means that all instances for topological modules are immediately picked up for vector spaces as well. A cosmetic disadvantage is that one can not extend topological vector spaces. The solution is to extend `topological_module` instead. -/ open topological_space universes u v w u' section prio set_option default_priority 100 -- see Note [default priority] /-- A topological semimodule, over a semiring which is also a topological space, is a semimodule in which scalar multiplication is continuous. In applications, R will be a topological semiring and M a topological additive semigroup, but this is not needed for the definition -/ class topological_semimodule (R : Type u) (M : Type v) [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] : Prop := (continuous_smul : continuous (λp : R × M, p.1 • p.2)) end prio section variables {R : Type u} {M : Type v} [semiring R] [topological_space R] [topological_space M] [add_comm_monoid M] [semimodule R M] [topological_semimodule R M] lemma continuous_smul : continuous (λp:R×M, p.1 • p.2) := topological_semimodule.continuous_smul R M lemma continuous.smul {M₂ : Type*} [topological_space M₂] {f : M₂ → R} {g : M₂ → M} (hf : continuous f) (hg : continuous g) : continuous (λp, f p • g p) := continuous_smul.comp (hf.prod_mk hg) end section prio set_option default_priority 100 -- see Note [default priority] /-- A topological module, over a ring which is also a topological space, is a module in which scalar multiplication is continuous. In applications, `R` will be a topological ring and `M` a topological additive group, but this is not needed for the definition -/ class topological_module (R : Type u) (M : Type v) [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] extends topological_semimodule R M : Prop /-- A topological vector space is a topological module over a field. -/ abbreviation topological_vector_space (R : Type u) (M : Type v) [discrete_field R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] := topological_module R M end prio section variables {R : Type*} {M : Type*} [ring R] [topological_space R] [topological_space M] [add_comm_group M] [module R M] [topological_module R M] /-- Scalar multiplication by a unit is a homeomorphism from a topological module onto itself. -/ protected def homeomorph.smul_of_unit (a : units R) : M ≃ₜ M := { to_fun := λ x, (a : R) • x, inv_fun := λ x, ((a⁻¹ : units R) : R) • x, right_inv := λ x, calc (a : R) • ((a⁻¹ : units R) : R) • x = x : by rw [smul_smul, units.mul_inv, one_smul], left_inv := λ x, calc ((a⁻¹ : units R) : R) • (a : R) • x = x : by rw [smul_smul, units.inv_mul, one_smul], continuous_to_fun := continuous_const.smul continuous_id, continuous_inv_fun := continuous_const.smul continuous_id } lemma is_open_map_smul_of_unit (a : units R) : is_open_map (λ (x : M), (a : R) • x) := (homeomorph.smul_of_unit a).is_open_map lemma is_closed_map_smul_of_unit (a : units R) : is_closed_map (λ (x : M), (a : R) • x) := (homeomorph.smul_of_unit a).is_closed_map end section variables {R : Type*} {M : Type*} {a : R} [discrete_field R] [topological_space R] [topological_space M] [add_comm_group M] [vector_space R M] [topological_vector_space R M] set_option class.instance_max_depth 36 /-- Scalar multiplication by a non-zero field element is a homeomorphism from a topological vector space onto itself. -/ protected def homeomorph.smul_of_ne_zero (ha : a ≠ 0) : M ≃ₜ M := {.. homeomorph.smul_of_unit ((equiv.units_equiv_ne_zero _).inv_fun ⟨_, ha⟩)} lemma is_open_map_smul_of_ne_zero (ha : a ≠ 0) : is_open_map (λ (x : M), a • x) := (homeomorph.smul_of_ne_zero ha).is_open_map lemma is_closed_map_smul_of_ne_zero (ha : a ≠ 0) : is_closed_map (λ (x : M), a • x) := (homeomorph.smul_of_ne_zero ha).is_closed_map end /-- Continuous linear maps between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ structure continuous_linear_map (R : Type*) [ring R] (M : Type*) [topological_space M] [add_comm_group M] (M₂ : Type*) [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂] extends linear_map R M M₂ := (cont : continuous to_fun) notation M ` →L[`:25 R `] ` M₂ := continuous_linear_map R M M₂ /-- Continuous linear equivalences between modules. We only put the type classes that are necessary for the definition, although in applications `M` and `M₂` will be topological modules over the topological ring `R`. -/ structure continuous_linear_equiv (R : Type*) [ring R] (M : Type*) [topological_space M] [add_comm_group M] (M₂ : Type*) [topological_space M₂] [add_comm_group M₂] [module R M] [module R M₂] extends linear_equiv R M M₂ := (continuous_to_fun : continuous to_fun) (continuous_inv_fun : continuous inv_fun) notation M ` ≃L[`:50 R `] ` M₂ := continuous_linear_equiv R M M₂ namespace continuous_linear_map section general_ring /- Properties that hold for non-necessarily commutative rings. -/ variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] /-- Coerce continuous linear maps to linear maps. -/ instance : has_coe (M →L[R] M₂) (M →ₗ[R] M₂) := ⟨to_linear_map⟩ protected lemma continuous (f : M →L[R] M₂) : continuous f := f.2 /-- Coerce continuous linear maps to functions. -/ instance to_fun : has_coe_to_fun $ M →L[R] M₂ := ⟨_, λ f, f.to_fun⟩ @[ext] theorem ext {f g : M →L[R] M₂} (h : ∀ x, f x = g x) : f = g := by cases f; cases g; congr' 1; ext x; apply h theorem ext_iff {f g : M →L[R] M₂} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, by rw h, by ext⟩ variables (c : R) (f g : M →L[R] M₂) (h : M₂ →L[R] M₃) (x y z : M) -- make some straightforward lemmas available to `simp`. @[simp] lemma map_zero : f (0 : M) = 0 := (to_linear_map _).map_zero @[simp] lemma map_add : f (x + y) = f x + f y := (to_linear_map _).map_add _ _ @[simp] lemma map_sub : f (x - y) = f x - f y := (to_linear_map _).map_sub _ _ @[simp] lemma map_smul : f (c • x) = c • f x := (to_linear_map _).map_smul _ _ @[simp] lemma map_neg : f (-x) = - (f x) := (to_linear_map _).map_neg _ @[simp, squash_cast] lemma coe_coe : ((f : M →ₗ[R] M₂) : (M → M₂)) = (f : M → M₂) := rfl /-- The continuous map that is constantly zero. -/ def zero : M →L[R] M₂ := ⟨0, by exact continuous_const⟩ instance: has_zero (M →L[R] M₂) := ⟨zero⟩ @[simp] lemma zero_apply : (0 : M →L[R] M₂) x = 0 := rfl @[simp, elim_cast] lemma coe_zero : ((0 : M →L[R] M₂) : M →ₗ[R] M₂) = 0 := rfl /- no simp attribute on the next line as simp does not always simplify `0 x` to `0` when `0` is the zero function, while it does for the zero continuous linear map, and this is the most important property we care about. -/ @[elim_cast] lemma coe_zero' : ((0 : M →L[R] M₂) : M → M₂) = 0 := rfl /-- the identity map as a continuous linear map. -/ def id : M →L[R] M := ⟨linear_map.id, continuous_id⟩ instance : has_one (M →L[R] M) := ⟨id⟩ @[simp] lemma id_apply : (id : M →L[R] M) x = x := rfl @[simp, elim_cast] lemma coe_id : ((id : M →L[R] M) : M →ₗ[R] M) = linear_map.id := rfl @[simp, elim_cast] lemma coe_id' : ((id : M →L[R] M) : M → M) = _root_.id := rfl @[simp] lemma one_apply : (1 : M →L[R] M) x = x := rfl section add variables [topological_add_group M₂] instance : has_add (M →L[R] M₂) := ⟨λ f g, ⟨f + g, f.2.add g.2⟩⟩ @[simp] lemma add_apply : (f + g) x = f x + g x := rfl @[simp, move_cast] lemma coe_add : (((f + g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) + g := rfl @[move_cast] lemma coe_add' : (((f + g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) + g := rfl instance : has_neg (M →L[R] M₂) := ⟨λ f, ⟨-f, f.2.neg⟩⟩ @[simp] lemma neg_apply : (-f) x = - (f x) := rfl @[simp, move_cast] lemma coe_neg : (((-f) : M →L[R] M₂) : M →ₗ[R] M₂) = -(f : M →ₗ[R] M₂) := rfl @[move_cast] lemma coe_neg' : (((-f) : M →L[R] M₂) : M → M₂) = -(f : M → M₂) := rfl instance : add_comm_group (M →L[R] M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp @[simp] lemma sub_apply (x : M) : (f - g) x = f x - g x := rfl @[simp, move_cast] lemma coe_sub : (((f - g) : M →L[R] M₂) : M →ₗ[R] M₂) = (f : M →ₗ[R] M₂) - g := rfl @[simp, move_cast] lemma coe_sub' : (((f - g) : M →L[R] M₂) : M → M₂) = (f : M → M₂) - g := rfl end add /-- Composition of bounded linear maps. -/ def comp (g : M₂ →L[R] M₃) (f : M →L[R] M₂) : M →L[R] M₃ := ⟨linear_map.comp g.to_linear_map f.to_linear_map, g.2.comp f.2⟩ @[simp, move_cast] lemma coe_comp : ((h.comp f) : (M →ₗ[R] M₃)) = (h : M₂ →ₗ[R] M₃).comp f := rfl @[simp, move_cast] lemma coe_comp' : ((h.comp f) : (M → M₃)) = (h : M₂ → M₃) ∘ f := rfl @[simp] theorem comp_id : f.comp id = f := ext $ λ x, rfl @[simp] theorem id_comp : id.comp f = f := ext $ λ x, rfl @[simp] theorem comp_zero : f.comp (0 : M₃ →L[R] M) = 0 := by { ext, simp } @[simp] theorem zero_comp : (0 : M₂ →L[R] M₃).comp f = 0 := by { ext, simp } @[simp] lemma comp_add [topological_add_group M₂] [topological_add_group M₃] (g : M₂ →L[R] M₃) (f₁ f₂ : M →L[R] M₂) : g.comp (f₁ + f₂) = g.comp f₁ + g.comp f₂ := by { ext, simp } @[simp] lemma add_comp [topological_add_group M₃] (g₁ g₂ : M₂ →L[R] M₃) (f : M →L[R] M₂) : (g₁ + g₂).comp f = g₁.comp f + g₂.comp f := by { ext, simp } instance : has_mul (M →L[R] M) := ⟨comp⟩ instance [topological_add_group M] : ring (M →L[R] M) := { mul := (*), one := 1, mul_one := λ _, ext $ λ _, rfl, one_mul := λ _, ext $ λ _, rfl, mul_assoc := λ _ _ _, ext $ λ _, rfl, left_distrib := λ _ _ _, ext $ λ _, map_add _ _ _, right_distrib := λ _ _ _, ext $ λ _, linear_map.add_apply _ _ _, ..continuous_linear_map.add_comm_group } /-- The cartesian product of two bounded linear maps, as a bounded linear map. -/ def prod (f₁ : M →L[R] M₂) (f₂ : M →L[R] M₃) : M →L[R] (M₂ × M₃) := { cont := f₁.2.prod_mk f₂.2, ..f₁.to_linear_map.prod f₂.to_linear_map } end general_ring section comm_ring variables {R : Type*} [comm_ring R] [topological_space R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] [topological_module R M₃] instance : has_scalar R (M →L[R] M₃) := ⟨λ c f, ⟨c • f, continuous_const.smul f.2⟩⟩ variables (c : R) (h : M₂ →L[R] M₃) (f g : M →L[R] M₂) (x y z : M) @[simp] lemma smul_comp : (c • h).comp f = c • (h.comp f) := rfl variable [topological_module R M₂] @[simp] lemma smul_apply : (c • f) x = c • (f x) := rfl @[simp, move_cast] lemma coe_apply : (((c • f) : M →L[R] M₂) : M →ₗ[R] M₂) = c • (f : M →ₗ[R] M₂) := rfl @[move_cast] lemma coe_apply' : (((c • f) : M →L[R] M₂) : M → M₂) = c • (f : M → M₂) := rfl @[simp] lemma comp_smul : h.comp (c • f) = c • (h.comp f) := by { ext, simp } /-- The linear map `λ x, c x • f`. Associates to a scalar-valued linear map and an element of `M₂` the `M₂`-valued linear map obtained by multiplying the two (a.k.a. tensoring by `M₂`) -/ def smul_right (c : M →L[R] R) (f : M₂) : M →L[R] M₂ := { cont := c.2.smul continuous_const, ..c.to_linear_map.smul_right f } @[simp] lemma smul_right_apply {c : M →L[R] R} {f : M₂} {x : M} : (smul_right c f : M → M₂) x = (c : M → R) x • f := rfl @[simp] lemma smul_right_one_one (c : R →L[R] M₂) : smul_right 1 ((c : R → M₂) 1) = c := by ext; simp [-continuous_linear_map.map_smul, (continuous_linear_map.map_smul _ _ _).symm] @[simp] lemma smul_right_one_eq_iff {f f' : M₂} : smul_right (1 : R →L[R] R) f = smul_right 1 f' ↔ f = f' := ⟨λ h, have (smul_right (1 : R →L[R] R) f : R → M₂) 1 = (smul_right (1 : R →L[R] R) f' : R → M₂) 1, by rw h, by simp at this; assumption, by cc⟩ variable [topological_add_group M₂] instance : module R (M →L[R] M₂) := { smul_zero := λ _, ext $ λ _, smul_zero _, zero_smul := λ _, ext $ λ _, zero_smul _ _, one_smul := λ _, ext $ λ _, one_smul _ _, mul_smul := λ _ _ _, ext $ λ _, mul_smul _ _ _, add_smul := λ _ _ _, ext $ λ _, add_smul _ _ _, smul_add := λ _ _ _, ext $ λ _, smul_add _ _ _ } set_option class.instance_max_depth 55 instance : is_ring_hom (λ c : R, c • (1 : M₂ →L[R] M₂)) := { map_one := one_smul _ _, map_add := λ _ _, ext $ λ _, add_smul _ _ _, map_mul := λ _ _, ext $ λ _, mul_smul _ _ _ } instance : algebra R (M₂ →L[R] M₂) := { to_fun := λ c, c • 1, smul_def' := λ _ _, rfl, commutes' := λ _ _, ext $ λ _, map_smul _ _ _ } end comm_ring end continuous_linear_map namespace continuous_linear_equiv variables {R : Type*} [ring R] {M : Type*} [topological_space M] [add_comm_group M] {M₂ : Type*} [topological_space M₂] [add_comm_group M₂] {M₃ : Type*} [topological_space M₃] [add_comm_group M₃] [module R M] [module R M₂] [module R M₃] /-- A continuous linear equivalence induces a continuous linear map. -/ def to_continuous_linear_map (e : M ≃L[R] M₂) : M →L[R] M₂ := { cont := e.continuous_to_fun, ..e.to_linear_equiv.to_linear_map } /-- Coerce continuous linear equivs to continuous linear maps. -/ instance : has_coe (M ≃L[R] M₂) (M →L[R] M₂) := ⟨to_continuous_linear_map⟩ /-- Coerce continuous linear equivs to maps. -/ instance : has_coe_to_fun (M ≃L[R] M₂) := ⟨_, λ f, ((f : M →L[R] M₂) : M → M₂)⟩ @[simp] theorem coe_apply (e : M ≃L[R] M₂) (b : M) : (e : M →L[R] M₂) b = e b := rfl @[squash_cast] lemma coe_coe (e : M ≃L[R] M₂) : ((e : M →L[R] M₂) : M → M₂) = e := rfl @[ext] lemma ext {f g : M ≃L[R] M₂} (h : (f : M → M₂) = g) : f = g := begin cases f; cases g, simp only [], ext x, simp only [coe_fn_coe_base] at h, induction h, refl end /-- A continuous linear equivalence induces a homeomorphism. -/ def to_homeomorph (e : M ≃L[R] M₂) : M ≃ₜ M₂ := { ..e } -- Make some straightforward lemmas available to `simp`. @[simp] lemma map_zero (e : M ≃L[R] M₂) : e (0 : M) = 0 := (e : M →L[R] M₂).map_zero @[simp] lemma map_add (e : M ≃L[R] M₂) (x y : M) : e (x + y) = e x + e y := (e : M →L[R] M₂).map_add x y @[simp] lemma map_sub (e : M ≃L[R] M₂) (x y : M) : e (x - y) = e x - e y := (e : M →L[R] M₂).map_sub x y @[simp] lemma map_smul (e : M ≃L[R] M₂) (c : R) (x : M) : e (c • x) = c • (e x) := (e : M →L[R] M₂).map_smul c x @[simp] lemma map_neg (e : M ≃L[R] M₂) (x : M) : e (-x) = -e x := (e : M →L[R] M₂).map_neg x section variable (M) /-- The identity map as a continuous linear equivalence. -/ @[refl] protected def refl : M ≃L[R] M := { continuous_to_fun := continuous_id, continuous_inv_fun := continuous_id, .. linear_equiv.refl M } end /-- The inverse of a continuous linear equivalence as a continuous linear equivalence-/ @[symm] protected def symm (e : M ≃L[R] M₂) : M₂ ≃L[R] M := { continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, .. e.to_linear_equiv.symm } @[simp] lemma symm_to_linear_equiv (e : M ≃L[R] M₂) : e.symm.to_linear_equiv = e.to_linear_equiv.symm := by { ext, refl } /-- The composition of two continuous linear equivalences as a continuous linear equivalence. -/ @[trans] protected def trans (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : M ≃L[R] M₃ := { continuous_to_fun := e₂.continuous_to_fun.comp e₁.continuous_to_fun, continuous_inv_fun := e₁.continuous_inv_fun.comp e₂.continuous_inv_fun, .. e₁.to_linear_equiv.trans e₂.to_linear_equiv } @[simp] lemma trans_to_linear_equiv (e₁ : M ≃L[R] M₂) (e₂ : M₂ ≃L[R] M₃) : (e₁.trans e₂).to_linear_equiv = e₁.to_linear_equiv.trans e₂.to_linear_equiv := by { ext, refl } @[simp] theorem apply_symm_apply (e : M ≃L[R] M₂) (c : M₂) : e (e.symm c) = c := e.1.6 c @[simp] theorem symm_apply_apply (e : M ≃L[R] M₂) (b : M) : e.symm (e b) = b := e.1.5 b end continuous_linear_equiv
42f91876f5a440e0834ebcdf4b812157e6b6df7d
130c49f47783503e462c16b2eff31933442be6ff
/stage0/src/Lean/Meta/Tactic/Simp/SimpLemmas.lean
415204496e7cffb7c181a747077328dd5a7d5673
[ "Apache-2.0" ]
permissive
Hazel-Brown/lean4
8aa5860e282435ffc30dcdfccd34006c59d1d39c
79e6732fc6bbf5af831b76f310f9c488d44e7a16
refs/heads/master
1,689,218,208,951
1,629,736,869,000
1,629,736,896,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,366
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.ScopedEnvExtension import Lean.Util.Recognizers import Lean.Meta.LevelDefEq import Lean.Meta.DiscrTree import Lean.Meta.AppBuilder import Lean.Meta.Tactic.AuxLemma namespace Lean.Meta /-- The fields `levelParams` and `proof` are used to encode the proof of the simp lemma. If the `proof` is a global declaration `c`, we store `Expr.const c []` at `proof` without the universe levels, and `levelParams` is set to `#[]` When using the lemma, we create fresh universe metavariables. Motivation: most simp lemmas are global declarations, and this approach is faster and saves memory. The field `levelParams` is not empty only when we elaborate an expression provided by the user, and it contains universe metavariables. Then, we use `abstractMVars` to abstract the universe metavariables and create new fresh universe parameters that are stored at the field `levelParams`. -/ structure SimpLemma where keys : Array DiscrTree.Key levelParams : Array Name -- non empty for local universe polymorhic proofs. proof : Expr priority : Nat post : Bool perm : Bool -- true is lhs and rhs are identical modulo permutation of variables name? : Option Name := none -- for debugging and tracing purposes deriving Inhabited def SimpLemma.getName (s : SimpLemma) : Name := match s.name? with | some n => n | none => "<unknown>" instance : ToFormat SimpLemma where format s := let perm := if s.perm then ":perm" else "" let name := format s.getName let prio := f!":{s.priority}" name ++ prio ++ perm instance : ToMessageData SimpLemma where toMessageData s := format s instance : BEq SimpLemma where beq e₁ e₂ := e₁.proof == e₂.proof structure SimpLemmas where pre : DiscrTree SimpLemma := DiscrTree.empty post : DiscrTree SimpLemma := DiscrTree.empty lemmaNames : Std.PHashSet Name := {} toUnfold : Std.PHashSet Name := {} erased : Std.PHashSet Name := {} deriving Inhabited def addSimpLemmaEntry (d : SimpLemmas) (e : SimpLemma) : SimpLemmas := if e.post then { d with post := d.post.insertCore e.keys e, lemmaNames := updateLemmaNames d.lemmaNames } else { d with pre := d.pre.insertCore e.keys e, lemmaNames := updateLemmaNames d.lemmaNames } where updateLemmaNames (s : Std.PHashSet Name) : Std.PHashSet Name := match e.name? with | none => s | some name => s.insert name def SimpLemmas.addDeclToUnfold (d : SimpLemmas) (declName : Name) : SimpLemmas := { d with toUnfold := d.toUnfold.insert declName } def SimpLemmas.isDeclToUnfold (d : SimpLemmas) (declName : Name) : Bool := d.toUnfold.contains declName def SimpLemmas.isLemma (d : SimpLemmas) (declName : Name) : Bool := d.lemmaNames.contains declName def SimpLemmas.eraseCore [Monad m] [MonadError m] (d : SimpLemmas) (declName : Name) : m SimpLemmas := do return { d with erased := d.erased.insert declName, lemmaNames := d.lemmaNames.erase declName, toUnfold := d.toUnfold.erase declName } def SimpLemmas.erase [Monad m] [MonadError m] (d : SimpLemmas) (declName : Name) : m SimpLemmas := do unless d.isLemma declName || d.isDeclToUnfold declName do throwError "'{declName}' does not have [simp] attribute" d.eraseCore declName private partial def isPerm : Expr → Expr → MetaM Bool | Expr.app f₁ a₁ _, Expr.app f₂ a₂ _ => isPerm f₁ f₂ <&&> isPerm a₁ a₂ | Expr.mdata _ s _, t => isPerm s t | s, Expr.mdata _ t _ => isPerm s t | s@(Expr.mvar ..), t@(Expr.mvar ..) => isDefEq s t | Expr.forallE n₁ d₁ b₁ _, Expr.forallE n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x) | Expr.lam n₁ d₁ b₁ _, Expr.lam n₂ d₂ b₂ _ => isPerm d₁ d₂ <&&> withLocalDeclD n₁ d₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x) | Expr.letE n₁ t₁ v₁ b₁ _, Expr.letE n₂ t₂ v₂ b₂ _ => isPerm t₁ t₂ <&&> isPerm v₁ v₂ <&&> withLetDecl n₁ t₁ v₁ fun x => isPerm (b₁.instantiate1 x) (b₂.instantiate1 x) | Expr.proj _ i₁ b₁ _, Expr.proj _ i₂ b₂ _ => i₁ == i₂ <&&> isPerm b₁ b₂ | s, t => s == t private partial def shouldPreprocess (type : Expr) : MetaM Bool := forallTelescopeReducing type fun xs result => return !result.isEq private partial def preprocess (e type : Expr) (inv : Bool) : MetaM (List (Expr × Expr)) := do let type ← whnf type if type.isForall then forallTelescopeReducing type fun xs type => do let e := mkAppN e xs let ps ← preprocess e type inv ps.mapM fun (e, type) => return (← mkLambdaFVars xs e, ← mkForallFVars xs type) else if let some (_, lhs, rhs) := type.eq? then if inv then let type ← mkEq rhs lhs let e ← mkEqSymm e return [(e, type)] else return [(e, type)] else if let some (lhs, rhs) := type.iff? then if inv then let type ← mkEq rhs lhs let e ← mkEqSymm (← mkPropExt e) return [(e, type)] else let type ← mkEq lhs rhs let e ← mkPropExt e return [(e, type)] else if let some (_, lhs, rhs) := type.ne? then if inv then throwError "invalid '←' modifier in rewrite rule to 'False'" let type ← mkEq (← mkEq lhs rhs) (mkConst ``False) let e ← mkEqFalse e return [(e, type)] else if let some p := type.not? then if inv then throwError "invalid '←' modifier in rewrite rule to 'False'" let type ← mkEq p (mkConst ``False) let e ← mkEqFalse e return [(e, type)] else if let some (type₁, type₂) := type.and? then let e₁ := mkProj ``And 0 e let e₂ := mkProj ``And 1 e return (← preprocess e₁ type₁ inv) ++ (← preprocess e₂ type₂ inv) else if inv then throwError "invalid '←' modifier in rewrite rule to 'True'" let type ← mkEq type (mkConst ``True) let e ← mkEqTrue e return [(e, type)] private def checkTypeIsProp (type : Expr) : MetaM Unit := unless (← isProp type) do throwError "invalid 'simp', proposition expected{indentExpr type}" private def mkSimpLemmaCore (e : Expr) (levelParams : Array Name) (proof : Expr) (post : Bool) (prio : Nat) (name? : Option Name) : MetaM SimpLemma := do let type ← instantiateMVars (← inferType e) withNewMCtxDepth do let (xs, _, type) ← withReducible <| forallMetaTelescopeReducing type let type ← whnfR type let (keys, perm) ← match type.eq? with | some (_, lhs, rhs) => pure (← DiscrTree.mkPath lhs, ← isPerm lhs rhs) | none => throwError "unexpected kind of 'simp' theorem{indentExpr type}" return { keys := keys, perm := perm, post := post, levelParams := levelParams, proof := proof, name? := name?, priority := prio } private def mkSimpLemmasFromConst (declName : Name) (post : Bool) (inv : Bool) (prio : Nat) : MetaM (Array SimpLemma) := do let cinfo ← getConstInfo declName let val := mkConst declName (cinfo.levelParams.map mkLevelParam) withReducible do let type ← inferType val checkTypeIsProp type if inv || (← shouldPreprocess type) then let mut r := #[] for (val, type) in (← preprocess val type inv) do let auxName ← mkAuxLemma cinfo.levelParams type val r := r.push <| (← mkSimpLemmaCore (mkConst auxName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst auxName) post prio declName) return r else #[← mkSimpLemmaCore (mkConst declName (cinfo.levelParams.map mkLevelParam)) #[] (mkConst declName) post prio declName] inductive SimpEntry where | lemma : SimpLemma → SimpEntry | toUnfold : Name → SimpEntry deriving Inhabited abbrev SimpExtension := SimpleScopedEnvExtension SimpEntry SimpLemmas def SimpExtension.getLemmas (ext : SimpExtension) : CoreM SimpLemmas := return ext.getState (← getEnv) def addSimpLemma (ext : SimpExtension) (declName : Name) (post : Bool) (inv : Bool) (attrKind : AttributeKind) (prio : Nat) : MetaM Unit := do let simpLemmas ← mkSimpLemmasFromConst declName post inv prio for simpLemma in simpLemmas do ext.add (SimpEntry.lemma simpLemma) attrKind def mkSimpAttr (attrName : Name) (attrDescr : String) (ext : SimpExtension) : IO Unit := registerBuiltinAttribute { name := attrName descr := attrDescr add := fun declName stx attrKind => let go : MetaM Unit := do let info ← getConstInfo declName if (← isProp info.type) then let post := if stx[1].isNone then true else stx[1][0].getKind == ``Lean.Parser.Tactic.simpPost let prio ← getAttrParamOptPrio stx[2] addSimpLemma ext declName post (inv := false) attrKind prio else if info.hasValue then ext.add (SimpEntry.toUnfold declName) attrKind else throwError "invalid 'simp', it is not a proposition nor a definition (to unfold)" discard <| go.run {} {} erase := fun declName => do let s ← ext.getState (← getEnv) let s ← s.erase declName modifyEnv fun env => ext.modifyState env fun _ => s } def mkSimpExt (extName : Name) : IO SimpExtension := registerSimpleScopedEnvExtension { name := extName initial := {} addEntry := fun d e => match e with | SimpEntry.lemma e => addSimpLemmaEntry d e | SimpEntry.toUnfold n => d.addDeclToUnfold n } def registerSimpAttr (attrName : Name) (attrDescr : String) (extName : Name := attrName.appendAfter "Ext") : IO SimpExtension := do let ext ← mkSimpExt extName mkSimpAttr attrName attrDescr ext return ext builtin_initialize simpExtension : SimpExtension ← registerSimpAttr `simp "simplification theorem" def getSimpLemmas : CoreM SimpLemmas := simpExtension.getLemmas /- Auxiliary method for adding a global declaration to a `SimpLemmas` datastructure. -/ def SimpLemmas.addConst (s : SimpLemmas) (declName : Name) (post : Bool := true) (inv : Bool := false) (prio : Nat := eval_prio default) : MetaM SimpLemmas := do let simpLemmas ← mkSimpLemmasFromConst declName post inv prio return simpLemmas.foldl addSimpLemmaEntry s def SimpLemma.getValue (simpLemma : SimpLemma) : MetaM Expr := do if simpLemma.proof.isConst && simpLemma.levelParams.isEmpty then let info ← getConstInfo simpLemma.proof.constName! if info.levelParams.isEmpty then return simpLemma.proof else return simpLemma.proof.updateConst! (← info.levelParams.mapM (fun _ => mkFreshLevelMVar)) else let us ← simpLemma.levelParams.mapM fun _ => mkFreshLevelMVar simpLemma.proof.instantiateLevelParamsArray simpLemma.levelParams us private def preprocessProof (val : Expr) (inv : Bool) : MetaM (Array Expr) := do let type ← inferType val checkTypeIsProp type let ps ← preprocess val type inv return ps.toArray.map fun (val, _) => val /- Auxiliary method for creating simp lemmas from a proof term `val`. -/ def mkSimpLemmas (levelParams : Array Name) (proof : Expr) (post : Bool := true) (inv : Bool := false) (prio : Nat := eval_prio default) (name? : Option Name := none): MetaM (Array SimpLemma) := withReducible do (← preprocessProof proof inv).mapM fun val => mkSimpLemmaCore val levelParams val post prio name? /- Auxiliary method for adding a local simp lemma to a `SimpLemmas` datastructure. -/ def SimpLemmas.add (s : SimpLemmas) (levelParams : Array Name) (proof : Expr) (inv : Bool := false) (post : Bool := true) (prio : Nat := eval_prio default) (name? : Option Name := none): MetaM SimpLemmas := do if proof.isConst then s.addConst proof.constName! post inv prio else let simpLemmas ← mkSimpLemmas levelParams proof post inv prio (← getName? proof) return simpLemmas.foldl addSimpLemmaEntry s where getName? (e : Expr) : MetaM (Option Name) := do match name? with | some _ => return name? | none => let f := e.getAppFn if f.isConst then return f.constName! else if f.isFVar then let localDecl ← getFVarLocalDecl f return localDecl.userName else return none end Lean.Meta
3f9d69c90a75089c48533069c7b548e7674693a9
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/data/matrix/kronecker.lean
4b3c9b9eab590976026b2307743a33fa1efe4992
[ "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
15,602
lean
/- Copyright (c) 2021 Filippo A. E. Nuccio. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Filippo A. E. Nuccio, Eric Wieser -/ import data.matrix.basic import linear_algebra.tensor_product import ring_theory.tensor_product /-! # Kronecker product of matrices This defines the [Kronecker product](https://en.wikipedia.org/wiki/Kronecker_product). ## Main definitions * `matrix.kronecker_map`: A generalization of the Kronecker product: given a map `f : α → β → γ` and matrices `A` and `B` with coefficients in `α` and `β`, respectively, it is defined as the matrix with coefficients in `γ` such that `kronecker_map f A B (i₁, i₂) (j₁, j₂) = f (A i₁ j₁) (B i₁ j₂)`. * `matrix.kronecker_map_bilinear`: when `f` is bilinear, so is `kronecker_map f`. ## Specializations * `matrix.kronecker`: An alias of `kronecker_map (*)`. Prefer using the notation. * `matrix.kronecker_bilinear`: `matrix.kronecker` is bilinear * `matrix.kronecker_tmul`: An alias of `kronecker_map (⊗ₜ)`. Prefer using the notation. * `matrix.kronecker_tmul_bilinear`: `matrix.tmul_kronecker` is bilinear ## Notations These require `open_locale kronecker`: * `A ⊗ₖ B` for `kronecker_map (*) A B`. Lemmas about this notation use the token `kronecker`. * `A ⊗ₖₜ B` and `A ⊗ₖₜ[R] B` for `kronecker_map (⊗ₜ) A B`. Lemmas about this notation use the token `kronecker_tmul`. -/ namespace matrix open_locale matrix variables {R α α' β β' γ γ' : Type*} variables {l m n p : Type*} {q r : Type*} {l' m' n' p' : Type*} section kronecker_map /-- Produce a matrix with `f` applied to every pair of elements from `A` and `B`. -/ @[simp] def kronecker_map (f : α → β → γ) (A : matrix l m α) (B : matrix n p β) : matrix (l × n) (m × p) γ | i j := f (A i.1 j.1) (B i.2 j.2) lemma kronecker_map_transpose (f : α → β → γ) (A : matrix l m α) (B : matrix n p β) : kronecker_map f Aᵀ Bᵀ = (kronecker_map f A B)ᵀ := ext $ λ i j, rfl lemma kronecker_map_map_left (f : α' → β → γ) (g : α → α') (A : matrix l m α) (B : matrix n p β) : kronecker_map f (A.map g) B = kronecker_map (λ a b, f (g a) b) A B := ext $ λ i j, rfl lemma kronecker_map_map_right (f : α → β' → γ) (g : β → β') (A : matrix l m α) (B : matrix n p β) : kronecker_map f A (B.map g) = kronecker_map (λ a b, f a (g b)) A B := ext $ λ i j, rfl lemma kronecker_map_map (f : α → β → γ) (g : γ → γ') (A : matrix l m α) (B : matrix n p β) : (kronecker_map f A B).map g = kronecker_map (λ a b, g (f a b)) A B := ext $ λ i j, rfl @[simp] lemma kronecker_map_zero_left [has_zero α] [has_zero γ] (f : α → β → γ) (hf : ∀ b, f 0 b = 0) (B : matrix n p β) : kronecker_map f (0 : matrix l m α) B = 0:= ext $ λ i j,hf _ @[simp] lemma kronecker_map_zero_right [has_zero β] [has_zero γ] (f : α → β → γ) (hf : ∀ a, f a 0 = 0) (A : matrix l m α) : kronecker_map f A (0 : matrix n p β) = 0 := ext $ λ i j, hf _ lemma kronecker_map_add_left [has_add α] [has_add γ] (f : α → β → γ) (hf : ∀ a₁ a₂ b, f (a₁ + a₂) b = f a₁ b + f a₂ b) (A₁ A₂ : matrix l m α) (B : matrix n p β) : kronecker_map f (A₁ + A₂) B = kronecker_map f A₁ B + kronecker_map f A₂ B := ext $ λ i j, hf _ _ _ lemma kronecker_map_add_right [has_add β] [has_add γ] (f : α → β → γ) (hf : ∀ a b₁ b₂, f a (b₁ + b₂) = f a b₁ + f a b₂) (A : matrix l m α) (B₁ B₂ : matrix n p β) : kronecker_map f A (B₁ + B₂) = kronecker_map f A B₁ + kronecker_map f A B₂ := ext $ λ i j, hf _ _ _ lemma kronecker_map_smul_left [has_smul R α] [has_smul R γ] (f : α → β → γ) (r : R) (hf : ∀ a b, f (r • a) b = r • f a b) (A : matrix l m α) (B : matrix n p β) : kronecker_map f (r • A) B = r • kronecker_map f A B := ext $ λ i j, hf _ _ lemma kronecker_map_smul_right [has_smul R β] [has_smul R γ] (f : α → β → γ) (r : R) (hf : ∀ a b, f a (r • b) = r • f a b) (A : matrix l m α) (B : matrix n p β) : kronecker_map f A (r • B) = r • kronecker_map f A B := ext $ λ i j, hf _ _ lemma kronecker_map_diagonal_diagonal [has_zero α] [has_zero β] [has_zero γ] [decidable_eq m] [decidable_eq n] (f : α → β → γ) (hf₁ : ∀ b, f 0 b = 0) (hf₂ : ∀ a, f a 0 = 0) (a : m → α) (b : n → β): kronecker_map f (diagonal a) (diagonal b) = diagonal (λ mn, f (a mn.1) (b mn.2)) := begin ext ⟨i₁, i₂⟩ ⟨j₁, j₂⟩, simp [diagonal, apply_ite f, ite_and, ite_apply, apply_ite (f (a i₁)), hf₁, hf₂], end @[simp] lemma kronecker_map_one_one [has_zero α] [has_zero β] [has_zero γ] [has_one α] [has_one β] [has_one γ] [decidable_eq m] [decidable_eq n] (f : α → β → γ) (hf₁ : ∀ b, f 0 b = 0) (hf₂ : ∀ a, f a 0 = 0) (hf₃ : f 1 1 = 1) : kronecker_map f (1 : matrix m m α) (1 : matrix n n β) = 1 := (kronecker_map_diagonal_diagonal _ hf₁ hf₂ _ _).trans $ by simp only [hf₃, diagonal_one] lemma kronecker_map_reindex (f : α → β → γ) (el : l ≃ l') (em : m ≃ m') (en : n ≃ n') (ep : p ≃ p') (M : matrix l m α) (N : matrix n p β) : kronecker_map f (reindex el em M) (reindex en ep N) = reindex (el.prod_congr en) (em.prod_congr ep) (kronecker_map f M N) := by { ext ⟨i, i'⟩ ⟨j, j'⟩, refl } lemma kronecker_map_reindex_left (f : α → β → γ) (el : l ≃ l') (em : m ≃ m') (M : matrix l m α) (N : matrix n n' β) : kronecker_map f (matrix.reindex el em M) N = reindex (el.prod_congr (equiv.refl _)) (em.prod_congr (equiv.refl _)) (kronecker_map f M N) := kronecker_map_reindex _ _ _ (equiv.refl _) (equiv.refl _) _ _ lemma kronecker_map_reindex_right (f : α → β → γ) (em : m ≃ m') (en : n ≃ n') (M : matrix l l' α) (N : matrix m n β) : kronecker_map f M (reindex em en N) = reindex ((equiv.refl _).prod_congr em) ((equiv.refl _).prod_congr en) (kronecker_map f M N) := kronecker_map_reindex _ (equiv.refl _) (equiv.refl _) _ _ _ _ lemma kronecker_map_assoc {δ ξ ω ω' : Type*} (f : α → β → γ) (g : γ → δ → ω) (f' : α → ξ → ω') (g' : β → δ → ξ) (A : matrix l m α) (B : matrix n p β) (D : matrix q r δ) (φ : ω ≃ ω') (hφ : ∀ a b d, φ (g (f a b) d) = f' a (g' b d)) : (reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r)).trans (equiv.map_matrix φ) (kronecker_map g (kronecker_map f A B) D) = kronecker_map f' A (kronecker_map g' B D) := ext $ λ i j, hφ _ _ _ lemma kronecker_map_assoc₁ {δ ξ ω : Type*} (f : α → β → γ) (g : γ → δ → ω) (f' : α → ξ → ω) (g' : β → δ → ξ) (A : matrix l m α) (B : matrix n p β) (D : matrix q r δ) (h : ∀ a b d, (g (f a b) d) = f' a (g' b d)) : reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r) (kronecker_map g (kronecker_map f A B) D) = kronecker_map f' A (kronecker_map g' B D) := ext $ λ i j, h _ _ _ /-- When `f` is bilinear then `matrix.kronecker_map f` is also bilinear. -/ @[simps] def kronecker_map_bilinear [comm_semiring R] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] [module R α] [module R β] [module R γ] (f : α →ₗ[R] β →ₗ[R] γ) : matrix l m α →ₗ[R] matrix n p β →ₗ[R] matrix (l × n) (m × p) γ := linear_map.mk₂ R (kronecker_map (λ r s, f r s)) (kronecker_map_add_left _ $ f.map_add₂) (λ r, kronecker_map_smul_left _ _ $ f.map_smul₂ _) (kronecker_map_add_right _ $ λ a, (f a).map_add) (λ r, kronecker_map_smul_right _ _ $ λ a, (f a).map_smul r) /-- `matrix.kronecker_map_bilinear` commutes with `⬝` if `f` commutes with `*`. This is primarily used with `R = ℕ` to prove `matrix.mul_kronecker_mul`. -/ lemma kronecker_map_bilinear_mul_mul [comm_semiring R] [fintype m] [fintype m'] [non_unital_non_assoc_semiring α] [non_unital_non_assoc_semiring β] [non_unital_non_assoc_semiring γ] [module R α] [module R β] [module R γ] (f : α →ₗ[R] β →ₗ[R] γ) (h_comm : ∀ a b a' b', f (a * b) (a' * b') = f a a' * f b b') (A : matrix l m α) (B : matrix m n α) (A' : matrix l' m' β) (B' : matrix m' n' β) : kronecker_map_bilinear f (A ⬝ B) (A' ⬝ B') = (kronecker_map_bilinear f A A') ⬝ (kronecker_map_bilinear f B B') := begin ext ⟨i, i'⟩ ⟨j, j'⟩, simp only [kronecker_map_bilinear_apply_apply, mul_apply, ← finset.univ_product_univ, finset.sum_product, kronecker_map], simp_rw [f.map_sum, linear_map.sum_apply, linear_map.map_sum, h_comm], end end kronecker_map /-! ### Specialization to `matrix.kronecker_map (*)` -/ section kronecker variables (R) open_locale matrix /-- The Kronecker product. This is just a shorthand for `kronecker_map (*)`. Prefer the notation `⊗ₖ` rather than this definition. -/ @[simp] def kronecker [has_mul α] : matrix l m α → matrix n p α → matrix (l × n) (m × p) α := kronecker_map (*) localized "infix ` ⊗ₖ `:100 := matrix.kronecker_map (*)" in kronecker @[simp] lemma kronecker_apply [has_mul α] (A : matrix l m α) (B : matrix n p α) (i₁ i₂ j₁ j₂) : (A ⊗ₖ B) (i₁, i₂) (j₁, j₂) = A i₁ j₁ * B i₂ j₂ := rfl /-- `matrix.kronecker` as a bilinear map. -/ def kronecker_bilinear [comm_semiring R] [semiring α] [algebra R α] : matrix l m α →ₗ[R] matrix n p α →ₗ[R] matrix (l × n) (m × p) α := kronecker_map_bilinear (algebra.lmul R α) /-! What follows is a copy, in order, of every `matrix.kronecker_map` lemma above that has hypotheses which can be filled by properties of `*`. -/ @[simp] lemma zero_kronecker [mul_zero_class α] (B : matrix n p α) : (0 : matrix l m α) ⊗ₖ B = 0 := kronecker_map_zero_left _ zero_mul B @[simp] lemma kronecker_zero [mul_zero_class α] (A : matrix l m α) : A ⊗ₖ (0 : matrix n p α) = 0 := kronecker_map_zero_right _ mul_zero A lemma add_kronecker [distrib α] (A₁ A₂ : matrix l m α) (B : matrix n p α) : (A₁ + A₂) ⊗ₖ B = A₁ ⊗ₖ B + A₂ ⊗ₖ B := kronecker_map_add_left _ add_mul _ _ _ lemma kronecker_add [distrib α] (A : matrix l m α) (B₁ B₂ : matrix n p α) : A ⊗ₖ (B₁ + B₂) = A ⊗ₖ B₁ + A ⊗ₖ B₂ := kronecker_map_add_right _ mul_add _ _ _ lemma smul_kronecker [monoid R] [monoid α] [mul_action R α] [is_scalar_tower R α α] (r : R) (A : matrix l m α) (B : matrix n p α) : (r • A) ⊗ₖ B = r • (A ⊗ₖ B) := kronecker_map_smul_left _ _ (λ _ _, smul_mul_assoc _ _ _) _ _ lemma kronecker_smul [monoid R] [monoid α] [mul_action R α] [smul_comm_class R α α] (r : R) (A : matrix l m α) (B : matrix n p α) : A ⊗ₖ (r • B) = r • (A ⊗ₖ B) := kronecker_map_smul_right _ _ (λ _ _, mul_smul_comm _ _ _) _ _ lemma diagonal_kronecker_diagonal [mul_zero_class α] [decidable_eq m] [decidable_eq n] (a : m → α) (b : n → α): (diagonal a) ⊗ₖ (diagonal b) = diagonal (λ mn, (a mn.1) * (b mn.2)) := kronecker_map_diagonal_diagonal _ zero_mul mul_zero _ _ @[simp] lemma one_kronecker_one [mul_zero_one_class α] [decidable_eq m] [decidable_eq n] : (1 : matrix m m α) ⊗ₖ (1 : matrix n n α) = 1 := kronecker_map_one_one _ zero_mul mul_zero (one_mul _) lemma mul_kronecker_mul [fintype m] [fintype m'] [comm_semiring α] (A : matrix l m α) (B : matrix m n α) (A' : matrix l' m' α) (B' : matrix m' n' α) : (A ⬝ B) ⊗ₖ (A' ⬝ B') = (A ⊗ₖ A') ⬝ (B ⊗ₖ B') := kronecker_map_bilinear_mul_mul (algebra.lmul ℕ α).to_linear_map mul_mul_mul_comm A B A' B' @[simp] lemma kronecker_assoc [semigroup α] (A : matrix l m α) (B : matrix n p α) (C : matrix q r α) : reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r) ((A ⊗ₖ B) ⊗ₖ C) = A ⊗ₖ (B ⊗ₖ C) := kronecker_map_assoc₁ _ _ _ _ A B C mul_assoc end kronecker /-! ### Specialization to `matrix.kronecker_map (⊗ₜ)` -/ section kronecker_tmul variables (R) open tensor_product open_locale matrix tensor_product section module variables [comm_semiring R] [add_comm_monoid α] [add_comm_monoid β] [add_comm_monoid γ] variables [module R α] [module R β] [module R γ] /-- The Kronecker tensor product. This is just a shorthand for `kronecker_map (⊗ₜ)`. Prefer the notation `⊗ₖₜ` rather than this definition. -/ @[simp] def kronecker_tmul : matrix l m α → matrix n p β → matrix (l × n) (m × p) (α ⊗[R] β) := kronecker_map (⊗ₜ) localized "infix ` ⊗ₖₜ `:100 := matrix.kronecker_map (⊗ₜ)" in kronecker localized "notation x ` ⊗ₖₜ[`:100 R `] `:0 y:100 := matrix.kronecker_map (tensor_product.tmul R) x y" in kronecker @[simp] lemma kronecker_tmul_apply (A : matrix l m α) (B : matrix n p β) (i₁ i₂ j₁ j₂) : (A ⊗ₖₜ B) (i₁, i₂) (j₁, j₂) = A i₁ j₁ ⊗ₜ[R] B i₂ j₂ := rfl /-- `matrix.kronecker` as a bilinear map. -/ def kronecker_tmul_bilinear : matrix l m α →ₗ[R] matrix n p β →ₗ[R] matrix (l × n) (m × p) (α ⊗[R] β) := kronecker_map_bilinear (tensor_product.mk R α β) /-! What follows is a copy, in order, of every `matrix.kronecker_map` lemma above that has hypotheses which can be filled by properties of `⊗ₜ`. -/ @[simp] lemma zero_kronecker_tmul (B : matrix n p β) : (0 : matrix l m α) ⊗ₖₜ[R] B = 0 := kronecker_map_zero_left _ (zero_tmul α) B @[simp] lemma kronecker_tmul_zero (A : matrix l m α) : A ⊗ₖₜ[R] (0 : matrix n p β) = 0 := kronecker_map_zero_right _ (tmul_zero β) A lemma add_kronecker_tmul (A₁ A₂ : matrix l m α) (B : matrix n p α) : (A₁ + A₂) ⊗ₖₜ[R] B = A₁ ⊗ₖₜ B + A₂ ⊗ₖₜ B := kronecker_map_add_left _ add_tmul _ _ _ lemma kronecker_tmul_add (A : matrix l m α) (B₁ B₂ : matrix n p α) : A ⊗ₖₜ[R] (B₁ + B₂) = A ⊗ₖₜ B₁ + A ⊗ₖₜ B₂ := kronecker_map_add_right _ tmul_add _ _ _ lemma smul_kronecker_tmul (r : R) (A : matrix l m α) (B : matrix n p α) : (r • A) ⊗ₖₜ[R] B = r • (A ⊗ₖₜ B) := kronecker_map_smul_left _ _ (λ _ _, smul_tmul' _ _ _) _ _ lemma kronecker_tmul_smul (r : R) (A : matrix l m α) (B : matrix n p α) : A ⊗ₖₜ[R] (r • B) = r • (A ⊗ₖₜ B) := kronecker_map_smul_right _ _ (λ _ _, tmul_smul _ _ _) _ _ lemma diagonal_kronecker_tmul_diagonal [decidable_eq m] [decidable_eq n] (a : m → α) (b : n → α): (diagonal a) ⊗ₖₜ[R] (diagonal b) = diagonal (λ mn, a mn.1 ⊗ₜ b mn.2) := kronecker_map_diagonal_diagonal _ (zero_tmul _) (tmul_zero _) _ _ @[simp] lemma kronecker_tmul_assoc (A : matrix l m α) (B : matrix n p β) (C : matrix q r γ) : reindex (equiv.prod_assoc l n q) (equiv.prod_assoc m p r) (((A ⊗ₖₜ[R] B) ⊗ₖₜ[R] C).map (tensor_product.assoc _ _ _ _)) = A ⊗ₖₜ[R] (B ⊗ₖₜ[R] C) := ext $ λ i j, assoc_tmul _ _ _ end module section algebra variables [comm_semiring R] [semiring α] [semiring β] [algebra R α] [algebra R β] open_locale kronecker open algebra.tensor_product @[simp] lemma one_kronecker_tmul_one [decidable_eq m] [decidable_eq n] : (1 : matrix m m α) ⊗ₖₜ[R] (1 : matrix n n α) = 1 := kronecker_map_one_one _ (zero_tmul _) (tmul_zero _) rfl lemma mul_kronecker_tmul_mul [fintype m] [fintype m'] (A : matrix l m α) (B : matrix m n α) (A' : matrix l' m' β) (B' : matrix m' n' β) : (A ⬝ B) ⊗ₖₜ[R] (A' ⬝ B') = (A ⊗ₖₜ A') ⬝ (B ⊗ₖₜ B') := kronecker_map_bilinear_mul_mul (tensor_product.mk R α β) tmul_mul_tmul A B A' B' end algebra -- insert lemmas specific to `kronecker_tmul` below this line end kronecker_tmul end matrix
4224f1758dfbb02218803ef1f0234cbf32efeb8a
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/normed_space/star/matrix.lean
62fc8b30f360637ca969e1626faddbd012481a61
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
2,466
lean
/- Copyright (c) 2022 Hans Parshall. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Hans Parshall -/ import analysis.matrix import analysis.normed_space.basic import data.complex.is_R_or_C import linear_algebra.unitary_group /-! # Unitary matrices This file collects facts about the unitary matrices over `𝕜` (either `ℝ` or `ℂ`). -/ open_locale big_operators matrix variables {𝕜 m n E : Type*} section entrywise_sup_norm variables [is_R_or_C 𝕜] [fintype n] [decidable_eq n] lemma entry_norm_bound_of_unitary {U : matrix n n 𝕜} (hU : U ∈ matrix.unitary_group n 𝕜) (i j : n): ∥U i j∥ ≤ 1 := begin -- The norm squared of an entry is at most the L2 norm of its row. have norm_sum : ∥ U i j ∥^2 ≤ (∑ x, ∥ U i x ∥^2), { apply multiset.single_le_sum, { intros x h_x, rw multiset.mem_map at h_x, cases h_x with a h_a, rw ← h_a.2, apply sq_nonneg }, { rw multiset.mem_map, use j, simp only [eq_self_iff_true, finset.mem_univ_val, and_self, sq_eq_sq] } }, -- The L2 norm of a row is a diagonal entry of U ⬝ Uᴴ have diag_eq_norm_sum : (U ⬝ Uᴴ) i i = ∑ (x : n), ∥ U i x ∥^2, { simp only [matrix.mul_apply, matrix.conj_transpose_apply, ←star_ring_end_apply, is_R_or_C.mul_conj, is_R_or_C.norm_sq_eq_def', is_R_or_C.of_real_pow] }, -- The L2 norm of a row is a diagonal entry of U ⬝ Uᴴ, real part have re_diag_eq_norm_sum : is_R_or_C.re ((U ⬝ Uᴴ) i i) = ∑ (x : n), ∥ U i x ∥^2, { rw is_R_or_C.ext_iff at diag_eq_norm_sum, rw diag_eq_norm_sum.1, norm_cast }, -- Since U is unitary, the diagonal entries of U ⬝ Uᴴ are all 1 have mul_eq_one : (U ⬝ Uᴴ) = 1, from unitary.mul_star_self_of_mem hU, have diag_eq_one : is_R_or_C.re ((U ⬝ Uᴴ) i i) = 1, { simp only [mul_eq_one, eq_self_iff_true, matrix.one_apply_eq, is_R_or_C.one_re] }, -- Putting it all together rw [← sq_le_one_iff (norm_nonneg (U i j)), ← diag_eq_one, re_diag_eq_norm_sum], exact norm_sum, end local attribute [instance] matrix.normed_add_comm_group /-- The entrywise sup norm of a unitary matrix is at most 1. -/ lemma entrywise_sup_norm_bound_of_unitary {U : matrix n n 𝕜} (hU : U ∈ matrix.unitary_group n 𝕜) : ∥ U ∥ ≤ 1 := begin simp_rw pi_norm_le_iff zero_le_one, intros i j, exact entry_norm_bound_of_unitary hU _ _ end end entrywise_sup_norm
127dec992483409e5d1cf62bcb91d214f67d8d3d
eb9357a70318e50e095b58730bebfe0cffee457f
/lean/love03_forward_proofs_exercise_sheet.lean
460ffe16c6ec7e0f50002facfaa7920345ba626c
[]
no_license
Vierkantor/logical_verification_2021
7485dd916953131d501760f023d5b30fbb74d36a
9500b9c194e22a9ab4067321cfed7a1f445afcfc
refs/heads/main
1,692,560,845,086
1,624,721,275,000
1,624,721,275,000
416,354,079
0
0
null
null
null
null
UTF-8
Lean
false
false
3,171
lean
import .lovelib /-! # LoVe Exercise 3: Forward Proofs -/ set_option pp.beta true set_option pp.generalized_field_notation false namespace LoVe /-! ## Question 1: Connectives and Quantifiers 1.1. Supply structured proofs of the following lemmas. -/ lemma I (a : Prop) : a → a := sorry lemma K (a b : Prop) : a → b → b := sorry lemma C (a b c : Prop) : (a → b → c) → b → a → c := sorry lemma proj_1st (a : Prop) : a → a → a := sorry /-! Please give a different answer than for `proj_1st`. -/ lemma proj_2nd (a : Prop) : a → a → a := sorry lemma some_nonsense (a b c : Prop) : (a → b → c) → a → (a → c) → b → c := sorry /-! 1.2. Supply a structured proof of the contraposition rule. -/ lemma contrapositive (a b : Prop) : (a → b) → ¬ b → ¬ a := sorry /-! 1.3. Supply a structured proof of the distributivity of `∀` over `∧`. -/ lemma forall_and {α : Type} (p q : α → Prop) : (∀x, p x ∧ q x) ↔ (∀x, p x) ∧ (∀x, q x) := sorry /-! 1.4 (**optional**). Reuse, if possible, the lemma `forall_and` from question 1.3 to prove the following instance of the lemma. -/ lemma forall_and_inst {α : Type} (r s : α → α → Prop) : (∀x, r x x ∧ s x x) ↔ (∀x, r x x) ∧ (∀x, s x x) := sorry /-! 1.5. Supply a structured proof of the following property, which can be used pull a `∀`-quantifier past an `∃`-quantifier. -/ lemma forall_exists_of_exists_forall {α : Type} (p : α → α → Prop) : (∃x, ∀y, p x y) → (∀y, ∃x, p x y) := sorry /-! ## Question 2: Chain of Equalities 2.1. Write the following proof using `calc`. (a + b) * (a + b) = a * (a + b) + b * (a + b) = a * a + a * b + b * a + b * b = a * a + a * b + a * b + b * b = a * a + 2 * a * b + b * b Hint: You might need the tactics `simp` and `cc` and the lemmas `mul_add`, `add_mul`, and `two_mul`. -/ lemma binomial_square (a b : ℕ) : (a + b) * (a + b) = a * a + 2 * a * b + b * b := sorry /-! 2.2 (**optional**). Prove the same argument again, this time as a structured proof, with `have` steps corresponding to the `calc` equations. Try to reuse as much of the above proof idea as possible, proceeding mechanically. -/ lemma binomial_square₂ (a b : ℕ) : (a + b) * (a + b) = a * a + 2 * a * b + b * b := sorry /-! 2.3. Prove the same lemma again, this time using tactics. -/ lemma binomial_square₃ (a b : ℕ) : (a + b) * (a + b) = a * a + 2 * a * b + b * b := begin sorry end /-! ## Question 3 (**optional**): One-Point Rules 3.1 (**optional**). Prove that the following wrong formulation of the one-point rule for `∀` is inconsistent, using a structured proof. -/ axiom forall.one_point_wrong {α : Type} {t : α} {p : α → Prop} : (∀x : α, x = t ∧ p x) ↔ p t lemma proof_of_false : false := sorry /-! 3.2 (**optional**). Prove that the following wrong formulation of the one-point rule for `∃` is inconsistent, using a tactical or structured proof. -/ axiom exists.one_point_wrong {α : Type} {t : α} {p : α → Prop} : (∃x : α, x = t → p x) ↔ p t lemma proof_of_false₂ : false := sorry end LoVe
bd5f83e6e16bd1440fb14f6ff0ee70fb769e2d63
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/src/Init/Conv.lean
bc19809f2528edaf9d72d53dac6d9c8fbede7963
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
8,312
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 Notation for operators defined at Prelude.lean -/ prelude import Init.NotationExtra namespace Lean.Parser.Tactic.Conv /-- `conv` is the syntax category for a "conv tactic", where "conv" is short for conversion. A conv tactic is a program which receives a target, printed as `| a`, and is tasked with coming up with some term `b` and a proof of `a = b`. It is mainly used for doing targeted term transformations, for example rewriting only on the left side of an equality. -/ declare_syntax_cat conv (behavior := both) syntax convSeq1Indented := withPosition((colGe conv ";"?)+) syntax convSeqBracketed := "{" (conv ";"?)* "}" -- Order is important: a missing `conv` proof should not be parsed as `{ <missing> }`, -- automatically closing goals syntax convSeq := convSeqBracketed <|> convSeq1Indented /-- `conv => ...` allows the user to perform targeted rewriting on a goal or hypothesis, by focusing on particular subexpressions. See <https://leanprover.github.io/theorem_proving_in_lean4/conv.html> for more details. Basic forms: * `conv => cs` will rewrite the goal with conv tactics `cs`. * `conv at h => cs` will rewrite hypothesis `h`. * `conv in pat => cs` will rewrite the first subexpression matching `pat`. -/ syntax (name := conv) "conv " (" at " ident)? (" in " term)? " => " convSeq : tactic /-- `skip` does nothing. -/ syntax (name := skip) "skip" : conv /-- Traverses into the left subterm of a binary operator. (In general, for an `n`-ary operator, it traverses into the second to last argument.) -/ syntax (name := lhs) "lhs" : conv /-- Traverses into the right subterm of a binary operator. (In general, for an `n`-ary operator, it traverses into the last argument.) -/ syntax (name := rhs) "rhs" : conv /-- Reduces the target to Weak Head Normal Form. This reduces definitions in "head position" until a constructor is exposed. For example, `List.map f [a, b, c]` weak head normalizes to `f a :: List.map f [b, c]`. -/ syntax (name := whnf) "whnf" : conv /-- Expand let-declarations and let-variables. -/ syntax (name := zeta) "zeta" : conv /-- Put term in normal form, this tactic is ment for debugging purposes only -/ syntax (name := reduce) "reduce" : conv /-- Performs one step of "congruence", which takes a term and produces subgoals for all the function arguments. For example, if the target is `f x y` then `congr` produces two subgoals, one for `x` and one for `y`. -/ syntax (name := congr) "congr" : conv /-- * `arg i` traverses into the `i`'th argument of the target. For example if the target is `f a b c d` then `arg 1` traverses to `a` and `arg 3` traverses to `c`. * `arg @i` is the same as `arg i` but it counts all arguments instead of just the explicit arguments. -/ syntax (name := arg) "arg " "@"? num : conv /-- `ext x` traverses into a binder (a `fun x => e` or `∀ x, e` expression) to target `e`, introducing name `x` in the process. -/ syntax (name := ext) "ext " (colGt ident)* : conv /-- `change t'` replaces the target `t` with `t'`, assuming `t` and `t'` are definitionally equal. -/ syntax (name := change) "change " term : conv /-- `delta foo` unfolds all occurrences of `foo` in the target. Like the `delta` tactic, this ignores any definitional equations and uses primitive delta-reduction instead, which may result in leaking implementation details. Users should prefer `unfold` for unfolding definitions. -/ syntax (name := delta) "delta " ident : conv /-- `unfold foo` unfolds all occurrences of `foo` in the target. Like the `unfold` tactic, this uses equational lemmas for the chosen definition to rewrite the target. For recursive definitions, only one layer of unfolding is performed. -/ syntax (name := unfold) "unfold " ident : conv /-- `pattern pat` traverses to the first subterm of the target that matches `pat`. -/ syntax (name := pattern) "pattern " term : conv /-- `rw [thm]` rewrites the target using `thm`. See the `rw` tactic for more information. -/ syntax (name := rewrite) "rewrite " (config)? rwRuleSeq : conv /-- `simp [thm]` performs simplification using `thm` and marked `@[simp]` lemmas. See the `simp` tactic for more information. -/ syntax (name := simp) "simp " (config)? (discharger)? (&"only ")? ("[" (simpStar <|> simpErase <|> simpLemma),* "]")? : conv /-- `simp_match` simplifies match expressions. For example, ``` match [a, b] with | [] => 0 | hd :: tl => hd ``` simplifies to `a`. -/ syntax (name := simpMatch) "simp_match" : conv /-- Execute the given tactic block without converting `conv` goal into a regular goal -/ syntax (name := nestedTacticCore) "tactic'" " => " tacticSeq : conv /-- Focus, convert the `conv` goal `⊢ lhs` into a regular goal `⊢ lhs = rhs`, and then execute the given tactic block. -/ syntax (name := nestedTactic) "tactic" " => " tacticSeq : conv /-- `{ convs }` runs the list of `convs` on the current target, and any subgoals that remain are trivially closed by `skip`. -/ syntax (name := nestedConv) convSeqBracketed : conv /-- `(convs)` runs the `convs` in sequence on the current list of targets. This is pure grouping with no added effects. -/ syntax (name := paren) "(" convSeq ")" : conv /-- `conv => cs` runs `cs` in sequence on the target `t`, resulting in `t'`, which becomes the new target subgoal. -/ syntax (name := convConvSeq) "conv " " => " convSeq : conv /-- `· conv` focuses on the main conv goal and tries to solve it using `s` -/ macro dot:("·" <|> ".") s:convSeq : conv => `({%$dot ($s) }) /-- `rw [rules]` applies the given list of rewrite rules to the target. See the `rw` tactic for more information. -/ macro "rw " c:(config)? s:rwRuleSeq : conv => `(rewrite $[$c]? $s) /-- `erw [rules]` is a shorthand for `rw (config := { transparency := .default }) [rules]`. This does rewriting up to unfolding of regular definitions (by comparison to regular `rw` which only unfolds `@[reducible]` definitions). -/ macro "erw " s:rwRuleSeq : conv => `(rw (config := { transparency := .default }) $s) /-- `args` traverses into all arguments. Synonym for `congr`. -/ macro "args" : conv => `(congr) /-- `left` traverses into the left argument. Synonym for `lhs`. -/ macro "left" : conv => `(lhs) /-- `right` traverses into the right argument. Synonym for `rhs`. -/ macro "right" : conv => `(rhs) /-- `intro` traverses into binders. Synonym for `ext`. -/ macro "intro " xs:(colGt ident)* : conv => `(conv| ext $xs*) syntax enterArg := ident <|> ("@"? num) /-- `enter [arg, ...]` is a compact way to describe a path to a subterm. It is a shorthand for other conv tactics as follows: * `enter [i]` is equivalent to `arg i`. * `enter [@i]` is equivalent to `arg @i`. * `enter [x]` (where `x` is an identifier) is equivalent to `ext x`. For example, given the target `f (g a (fun x => x b))`, `enter [1, 2, x, 1]` will traverse to the subterm `b`. -/ syntax "enter " "[" (colGt enterArg),+ "]": conv macro_rules | `(conv| enter [$i:num]) => `(conv| arg $i) | `(conv| enter [@$i]) => `(conv| arg @$i) | `(conv| enter [$id:ident]) => `(conv| ext $id) | `(conv| enter [$arg, $args,*]) => `(conv| (enter [$arg]; enter [$args,*])) /-- `rfl` closes one conv goal "trivially", by using reflexivity (that is, no rewriting). -/ macro "rfl" : conv => `(tactic => rfl) /-- `done` succeeds iff there are no goals remaining. -/ macro "done" : conv => `(tactic' => done) /-- `trace_state` prints the current goal state. -/ macro "trace_state" : conv => `(tactic' => trace_state) /-- The `apply thm` conv tactic is the same as `apply thm` the tactic. There are no restrictions on `thm`, but strange results may occur if `thm` cannot be reasonably interpreted as proving one equality from a list of others. -/ -- TODO: error if non-conv subgoals? macro "apply " e:term : conv => `(tactic => apply $e) /-- `first | conv | ...` runs each `conv` until one succeeds, or else fails. -/ syntax (name := first) "first " withPosition((colGe "|" convSeq)+) : conv /-- `repeat convs` runs the sequence `convs` repeatedly until it fails to apply. -/ syntax "repeat " convSeq : conv macro_rules | `(conv| repeat $seq) => `(conv| first | ($seq); repeat $seq | rfl) end Lean.Parser.Tactic.Conv
ba81be9c2a4990f23b01f1ed3cddf510e4d3c25e
7cef822f3b952965621309e88eadf618da0c8ae9
/src/data/list/min_max.lean
4e618b11f21c9768eca14a6e565471324182060b
[ "Apache-2.0" ]
permissive
rmitta/mathlib
8d90aee30b4db2b013e01f62c33f297d7e64a43d
883d974b608845bad30ae19e27e33c285200bf84
refs/heads/master
1,585,776,832,544
1,576,874,096,000
1,576,874,096,000
153,663,165
0
2
Apache-2.0
1,544,806,490,000
1,539,884,365,000
Lean
UTF-8
Lean
false
false
11,240
lean
/- Copyright (c) 2019 Minchao Wu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Minchao Wu, Chris Hughes -/ import data.list.basic /- # Minimum and maximum of lists ## Main definitions The main definitions are `argmax`, `argmin`, `minimum` and `maximum` for lists. `argmax f l` returns `some a`, where `a` of `l` that maximises `f a`. If there are `a b` such that `f a = f b`, it returns whichever of `a` or `b` comes first in the list. `argmax f []` = none` `minimum l` returns an `with_top α`, the smallest element of `l` for nonempty lists, and `⊤` for `[]` -/ namespace list variables {α : Type*} {β : Type*} [decidable_linear_order β] /-- Auxiliary definition to define `argmax` -/ def argmax₂ (f : α → β) (a : option α) (b : α) : option α := option.cases_on a (some b) (λ c, if f b ≤ f c then some c else some b) /-- `argmax f l` returns `some a`, where `a` of `l` that maximises `f a`. If there are `a b` such that `f a = f b`, it returns whichever of `a` or `b` comes first in the list. `argmax f []` = none` -/ def argmax (f : α → β) (l : list α) : option α := l.foldl (argmax₂ f) none /-- `argmin f l` returns `some a`, where `a` of `l` that minimises `f a`. If there are `a b` such that `f a = f b`, it returns whichever of `a` or `b` comes first in the list. `argmin f []` = none` -/ def argmin (f : α → β) (l : list α) := @argmax _ (order_dual β) _ f l @[simp] lemma argmax_two_self (f : α → β) (a : α) : argmax₂ f (some a) a = a := if_pos (le_refl _) @[simp] lemma argmax_nil (f : α → β) : argmax f [] = none := rfl @[simp] lemma argmin_nil (f : α → β) : argmin f [] = none := rfl @[simp] lemma argmax_singleton {f : α → β} {a : α} : argmax f [a] = some a := rfl @[simp] lemma argmin_singleton {f : α → β} {a : α} : argmin f [a] = a := rfl @[simp] lemma foldl_argmax₂_eq_none {f : α → β} {l : list α} {o : option α} : l.foldl (argmax₂ f) o = none ↔ l = [] ∧ o = none := list.reverse_rec_on l (by simp) $ (assume tl hd, by simp [argmax₂]; cases foldl (argmax₂ f) o tl; simp; try {split_ifs}; simp) private theorem le_of_foldl_argmax₂ {f : α → β} {l} : Π {a m : α} {o : option α}, a ∈ l → m ∈ foldl (argmax₂ f) o l → f a ≤ f m := list.reverse_rec_on l (λ _ _ _ h, absurd h $ not_mem_nil _) begin intros tl _ ih _ _ _ h ho, rw [foldl_append, foldl_cons, foldl_nil, argmax₂] at ho, cases hf : foldl (argmax₂ f) o tl, { rw [hf] at ho, rw [foldl_argmax₂_eq_none] at hf, simp [hf.1, hf.2, *] at * }, rw [hf, option.mem_def] at ho, dsimp only at ho, cases mem_append.1 h with h h, { refine le_trans (ih h hf) _, have := @le_of_lt _ _ (f val) (f m), split_ifs at ho; simp * at * }, { split_ifs at ho; simp * at * } end private theorem foldl_argmax₂_mem (f : α → β) (l) : Π (a m : α), m ∈ foldl (argmax₂ f) (some a) l → m ∈ a :: l := list.reverse_rec_on l (by simp [eq_comm]) begin assume tl hd ih a m, simp only [foldl_append, foldl_cons, foldl_nil, argmax₂], cases hf : foldl (argmax₂ f) (some a) tl, { simp {contextual := tt} }, { dsimp only, split_ifs, { finish [ih _ _ hf] }, { simp {contextual := tt} } } end theorem argmax_mem {f : α → β} : Π {l : list α} {m : α}, m ∈ argmax f l → m ∈ l | [] m := by simp | (hd::tl) m := by simpa [argmax, argmax₂] using foldl_argmax₂_mem f tl hd m theorem argmin_mem {f : α → β} : Π {l : list α} {m : α}, m ∈ argmin f l → m ∈ l := @argmax_mem _ (order_dual β) _ _ @[simp] theorem argmax_eq_none {f : α → β} {l : list α} : l.argmax f = none ↔ l = [] := by simp [argmax] @[simp] theorem argmin_eq_none {f : α → β} {l : list α} : l.argmin f = none ↔ l = [] := @argmax_eq_none _ (order_dual β) _ _ _ theorem le_argmax_of_mem {f : α → β} {a m : α} {l : list α} : a ∈ l → m ∈ argmax f l → f a ≤ f m := le_of_foldl_argmax₂ theorem argmin_le_of_mem {f : α → β} {a m : α} {l : list α} : a ∈ l → m ∈ argmin f l → f m ≤ f a:= @le_argmax_of_mem _ (order_dual β) _ _ _ _ _ theorem argmax_concat (f : α → β) (a : α) (l : list α) : argmax f (l ++ [a]) = option.cases_on (argmax f l) (some a) (λ c, if f a ≤ f c then some c else some a) := by rw [argmax, argmax]; simp [argmax₂] theorem argmin_concat (f : α → β) (a : α) (l : list α) : argmin f (l ++ [a]) = option.cases_on (argmin f l) (some a) (λ c, if f c ≤ f a then some c else some a) := @argmax_concat _ (order_dual β) _ _ _ _ theorem argmax_cons (f : α → β) (a : α) (l : list α) : argmax f (a :: l) = option.cases_on (argmax f l) (some a) (λ c, if f c ≤ f a then some a else some c) := list.reverse_rec_on l rfl $ assume hd tl ih, begin rw [← cons_append, argmax_concat, ih, argmax_concat], cases h : argmax f hd with m, { simp [h] }, { simp [h], dsimp, by_cases ham : f m ≤ f a, { rw if_pos ham, dsimp, by_cases htlm : f tl ≤ f m, { rw if_pos htlm, dsimp, rw [if_pos (le_trans htlm ham), if_pos ham] }, { rw if_neg htlm } }, { rw if_neg ham, dsimp, by_cases htlm : f tl ≤ f m, { rw if_pos htlm, dsimp, rw if_neg ham }, { rw if_neg htlm, dsimp, rw [if_neg (not_le_of_gt (lt_trans (lt_of_not_ge ham) (lt_of_not_ge htlm)))] } } } end theorem argmin_cons (f : α → β) (a : α) (l : list α) : argmin f (a :: l) = option.cases_on (argmin f l) (some a) (λ c, if f a ≤ f c then some a else some c) := @argmax_cons _ (order_dual β) _ _ _ _ theorem index_of_argmax [decidable_eq α] {f : α → β} : Π {l : list α} {m : α}, m ∈ argmax f l → ∀ {a}, a ∈ l → f m ≤ f a → l.index_of m ≤ l.index_of a | [] m _ _ _ _ := by simp | (hd::tl) m hm a ha ham := begin simp only [index_of_cons, argmax_cons, option.mem_def] at ⊢ hm, cases h : argmax f tl, { rw h at hm, simp * at * }, { rw h at hm, dsimp only at hm, cases ha with hahd hatl, { clear index_of_argmax, subst hahd, split_ifs at hm, { subst hm }, { subst hm, contradiction } }, { have := index_of_argmax h hatl, clear index_of_argmax, split_ifs at *; refl <|> exact nat.zero_le _ <|> simp [*, nat.succ_le_succ_iff, -not_le] at * } } end theorem index_of_argmin [decidable_eq α] {f : α → β} : Π {l : list α} {m : α}, m ∈ argmin f l → ∀ {a}, a ∈ l → f a ≤ f m → l.index_of m ≤ l.index_of a := @index_of_argmax _ (order_dual β) _ _ _ theorem mem_argmax_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} : m ∈ argmax f l ↔ m ∈ l ∧ (∀ a ∈ l, f a ≤ f m) ∧ (∀ a ∈ l, f m ≤ f a → l.index_of m ≤ l.index_of a) := ⟨λ hm, ⟨argmax_mem hm, λ a ha, le_argmax_of_mem ha hm, λ _, index_of_argmax hm⟩, begin rintros ⟨hml, ham, hma⟩, cases harg : argmax f l with n, { simp * at * }, { have := le_antisymm (hma n (argmax_mem harg) (le_argmax_of_mem hml harg)) (index_of_argmax harg hml (ham _ (argmax_mem harg))), rw [(index_of_inj hml (argmax_mem harg)).1 this, option.mem_def] } end⟩ theorem argmax_eq_some_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} : argmax f l = some m ↔ m ∈ l ∧ (∀ a ∈ l, f a ≤ f m) ∧ (∀ a ∈ l, f m ≤ f a → l.index_of m ≤ l.index_of a) := mem_argmax_iff theorem mem_argmin_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} : m ∈ argmin f l ↔ m ∈ l ∧ (∀ a ∈ l, f m ≤ f a) ∧ (∀ a ∈ l, f a ≤ f m → l.index_of m ≤ l.index_of a) := @mem_argmax_iff _ (order_dual β) _ _ _ _ _ theorem argmin_eq_some_iff [decidable_eq α] {f : α → β} {m : α} {l : list α} : argmin f l = some m ↔ m ∈ l ∧ (∀ a ∈ l, f m ≤ f a) ∧ (∀ a ∈ l, f a ≤ f m → l.index_of m ≤ l.index_of a) := mem_argmin_iff variable [decidable_linear_order α] /-- `maximum l` returns an `with_bot α`, the largest element of `l` for nonempty lists, and `⊥` for `[]` -/ def maximum (l : list α) : with_bot α := argmax id l /-- `minimum l` returns an `with_top α`, the smallest element of `l` for nonempty lists, and `⊤` for `[]` -/ def minimum (l : list α) : with_top α := argmin id l @[simp] lemma maximum_nil : maximum ([] : list α) = ⊥ := rfl @[simp] lemma minimum_nil : minimum ([] : list α) = ⊤ := rfl @[simp] lemma maximum_singleton (a : α) : maximum [a] = a := rfl @[simp] lemma minimum_singleton (a : α) : minimum [a] = a := rfl theorem maximum_mem {l : list α} {m : α} : (maximum l : with_top α) = m → m ∈ l := argmax_mem theorem minimum_mem {l : list α} {m : α} : (minimum l : with_bot α) = m → m ∈ l := argmin_mem @[simp] theorem maximum_eq_none {l : list α} : l.maximum = none ↔ l = [] := argmax_eq_none @[simp] theorem minimum_eq_none {l : list α} : l.minimum = none ↔ l = [] := argmin_eq_none theorem le_maximum_of_mem {a m : α} {l : list α} : a ∈ l → (maximum l : with_bot α) = m → a ≤ m := le_argmax_of_mem theorem minimum_le_of_mem {a m : α} {l : list α} : a ∈ l → (minimum l : with_top α) = m → m ≤ a := argmin_le_of_mem theorem le_maximum_of_mem' {a : α} {l : list α} (ha : a ∈ l) : (a : with_bot α) ≤ maximum l := option.cases_on (maximum l) (λ _ h, absurd ha ((h rfl).symm ▸ not_mem_nil _)) (λ m hm _, with_bot.coe_le_coe.2 $ hm _ rfl) (λ m, @le_maximum_of_mem _ _ _ m _ ha) (@maximum_eq_none _ _ l).1 theorem le_minimum_of_mem' {a : α} {l : list α} (ha : a ∈ l) : minimum l ≤ (a : with_top α) := @le_maximum_of_mem' (order_dual α) _ _ _ ha theorem maximum_concat (a : α) (l : list α) : maximum (l ++ [a]) = max (maximum l) a := begin rw max_comm, simp only [maximum, argmax_concat, id, max], cases h : argmax id l, { rw [if_neg], refl, exact not_le_of_gt (with_bot.bot_lt_some _) }, change (coe : α → with_bot α) with some, simp, congr end theorem minimum_concat (a : α) (l : list α) : minimum (l ++ [a]) = min (minimum l) a := by simp only [min_comm _ (a : with_top α)]; exact @maximum_concat (order_dual α) _ _ _ theorem maximum_cons (a : α) (l : list α) : maximum (a :: l) = max a (maximum l) := list.reverse_rec_on l (by simp [@max_eq_left (with_bot α) _ _ _ lattice.bot_le]) (λ tl hd ih, by rw [← cons_append, maximum_concat, ih, maximum_concat, max_assoc]) theorem minimum_cons (a : α) (l : list α) : minimum (a :: l) = min a (minimum l) := min_comm (minimum l) a ▸ @maximum_cons (order_dual α) _ _ _ theorem maximum_eq_coe_iff {m : α} {l : list α} : maximum l = m ↔ m ∈ l ∧ (∀ a ∈ l, a ≤ m) := begin unfold_coes, simp only [maximum, argmax_eq_some_iff, id], split, { simp only [true_and, forall_true_iff] {contextual := tt} }, { simp only [true_and, forall_true_iff] {contextual := tt}, intros h a hal hma, rw [le_antisymm hma (h.2 a hal)] } end theorem minimum_eq_coe_iff {m : α} {l : list α} : minimum l = m ↔ m ∈ l ∧ (∀ a ∈ l, m ≤ a) := @maximum_eq_coe_iff (order_dual α) _ _ _ end list
4bffbabe4a941e26daf50755931cf4497619f825
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/measure_theory/measure/with_density_vector_measure.lean
ce413647f600edf65c30c6a5a5821c1ae13444fb
[ "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
8,782
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 import measure_theory.function.ae_eq_of_integral /-! # Vector measure defined by an integral Given a measure `μ` and an integrable function `f : α → E`, we can define a vector measure `v` such that for all measurable set `s`, `v i = ∫ x in s, f x ∂μ`. This definition is useful for the Radon-Nikodym theorem for signed measures. ## Main definitions * `measure_theory.measure.with_densityᵥ`: the vector measure formed by integrating a function `f` with respect to a measure `μ` on some set if `f` is integrable, and `0` otherwise. -/ noncomputable theory open_locale classical measure_theory nnreal ennreal variables {α β : Type*} {m : measurable_space α} namespace measure_theory open topological_space variables {μ ν : measure α} variables {E : Type*} [normed_group E] [measurable_space E] [second_countable_topology E] [normed_space ℝ E] [complete_space E] [borel_space E] /-- Given a measure `μ` and an integrable function `f`, `μ.with_densityᵥ f` is the vector measure which maps the set `s` to `∫ₛ f ∂μ`. -/ def measure.with_densityᵥ {m : measurable_space α} (μ : measure α) (f : α → E) : vector_measure α E := if hf : integrable f μ then { measure_of' := λ s, if measurable_set s then ∫ x in s, f x ∂μ else 0, empty' := by simp, not_measurable' := λ s hs, if_neg hs, m_Union' := λ s hs₁ hs₂, begin convert has_sum_integral_Union hs₁ hs₂ hf.integrable_on, { ext n, rw if_pos (hs₁ n) }, { rw if_pos (measurable_set.Union hs₁) } end } else 0 open measure include m variables {f g : α → E} lemma with_densityᵥ_apply (hf : integrable f μ) {s : set α} (hs : measurable_set s) : μ.with_densityᵥ f s = ∫ x in s, f x ∂μ := by { rw [with_densityᵥ, dif_pos hf], exact dif_pos hs } @[simp] lemma with_densityᵥ_zero : μ.with_densityᵥ (0 : α → E) = 0 := by { ext1 s hs, erw [with_densityᵥ_apply (integrable_zero α E μ) hs], simp, } @[simp] lemma with_densityᵥ_neg : μ.with_densityᵥ (-f) = -μ.with_densityᵥ f := begin by_cases hf : integrable f μ, { ext1 i hi, rw [vector_measure.neg_apply, with_densityᵥ_apply hf hi, ← integral_neg, with_densityᵥ_apply hf.neg hi], refl }, { rw [with_densityᵥ, with_densityᵥ, dif_neg hf, dif_neg, neg_zero], rwa integrable_neg_iff } end lemma with_densityᵥ_neg' : μ.with_densityᵥ (λ x, -f x) = -μ.with_densityᵥ f := with_densityᵥ_neg @[simp] lemma with_densityᵥ_add (hf : integrable f μ) (hg : integrable g μ) : μ.with_densityᵥ (f + g) = μ.with_densityᵥ f + μ.with_densityᵥ g := begin ext1 i hi, rw [with_densityᵥ_apply (hf.add hg) hi, vector_measure.add_apply, with_densityᵥ_apply hf hi, with_densityᵥ_apply hg hi], simp_rw [pi.add_apply], rw integral_add; rw ← integrable_on_univ, { exact hf.integrable_on.restrict measurable_set.univ }, { exact hg.integrable_on.restrict measurable_set.univ } end lemma with_densityᵥ_add' (hf : integrable f μ) (hg : integrable g μ) : μ.with_densityᵥ (λ x, f x + g x) = μ.with_densityᵥ f + μ.with_densityᵥ g := with_densityᵥ_add hf hg @[simp] lemma with_densityᵥ_sub (hf : integrable f μ) (hg : integrable g μ) : μ.with_densityᵥ (f - g) = μ.with_densityᵥ f - μ.with_densityᵥ g := by rw [sub_eq_add_neg, sub_eq_add_neg, with_densityᵥ_add hf hg.neg, with_densityᵥ_neg] lemma with_densityᵥ_sub' (hf : integrable f μ) (hg : integrable g μ) : μ.with_densityᵥ (λ x, f x - g x) = μ.with_densityᵥ f - μ.with_densityᵥ g := with_densityᵥ_sub hf hg @[simp] lemma with_densityᵥ_smul {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℝ 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] (f : α → E) (r : 𝕜) : μ.with_densityᵥ (r • f) = r • μ.with_densityᵥ f := begin by_cases hf : integrable f μ, { ext1 i hi, rw [with_densityᵥ_apply (hf.smul r) hi, vector_measure.smul_apply, with_densityᵥ_apply hf hi, ← integral_smul r f], refl }, { by_cases hr : r = 0, { rw [hr, zero_smul, zero_smul, with_densityᵥ_zero] }, { rw [with_densityᵥ, with_densityᵥ, dif_neg hf, dif_neg, smul_zero], rwa integrable_smul_iff hr f } } end lemma with_densityᵥ_smul' {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [normed_space 𝕜 E] [smul_comm_class ℝ 𝕜 E] [measurable_space 𝕜] [opens_measurable_space 𝕜] (f : α → E) (r : 𝕜) : μ.with_densityᵥ (λ x, r • f x) = r • μ.with_densityᵥ f := with_densityᵥ_smul f r lemma measure.with_densityᵥ_absolutely_continuous (μ : measure α) (f : α → ℝ) : μ.with_densityᵥ f ≪ μ.to_ennreal_vector_measure := begin by_cases hf : integrable f μ, { refine vector_measure.absolutely_continuous.mk (λ i hi₁ hi₂, _), rw to_ennreal_vector_measure_apply_measurable hi₁ at hi₂, rw [with_densityᵥ_apply hf hi₁, measure.restrict_zero_set hi₂, integral_zero_measure] }, { rw [with_densityᵥ, dif_neg hf], exact vector_measure.absolutely_continuous.zero _ } end /-- Having the same density implies the underlying functions are equal almost everywhere. -/ lemma integrable.ae_eq_of_with_densityᵥ_eq {f g : α → E} (hf : integrable f μ) (hg : integrable g μ) (hfg : μ.with_densityᵥ f = μ.with_densityᵥ g) : f =ᵐ[μ] g := begin refine hf.ae_eq_of_forall_set_integral_eq f g hg (λ i hi _, _), rw [← with_densityᵥ_apply hf hi, hfg, with_densityᵥ_apply hg hi] end lemma with_densityᵥ_eq.congr_ae {f g : α → E} (h : f =ᵐ[μ] g) : μ.with_densityᵥ f = μ.with_densityᵥ g := begin by_cases hf : integrable f μ, { ext i hi, rw [with_densityᵥ_apply hf hi, with_densityᵥ_apply (hf.congr h) hi], exact integral_congr_ae (ae_restrict_of_ae h) }, { have hg : ¬ integrable g μ, { intro hg, exact hf (hg.congr h.symm) }, rw [with_densityᵥ, with_densityᵥ, dif_neg hf, dif_neg hg] } end lemma integrable.with_densityᵥ_eq_iff {f g : α → E} (hf : integrable f μ) (hg : integrable g μ) : μ.with_densityᵥ f = μ.with_densityᵥ g ↔ f =ᵐ[μ] g := ⟨λ hfg, hf.ae_eq_of_with_densityᵥ_eq hg hfg, λ h, with_densityᵥ_eq.congr_ae h⟩ section signed_measure lemma with_densityᵥ_to_real {f : α → ℝ≥0∞} (hfm : ae_measurable f μ) (hf : ∫⁻ x, f x ∂μ ≠ ∞) : μ.with_densityᵥ (λ x, (f x).to_real) = @to_signed_measure α _ (μ.with_density f) (is_finite_measure_with_density hf) := begin have hfi := integrable_to_real_of_lintegral_ne_top hfm hf, ext i hi, rw [with_densityᵥ_apply hfi hi, to_signed_measure_apply_measurable hi, with_density_apply _ hi, integral_to_real hfm.restrict], refine ae_lt_top' hfm.restrict (ne_top_of_le_ne_top hf _), conv_rhs { rw ← set_lintegral_univ }, exact lintegral_mono_set (set.subset_univ _), end lemma with_densityᵥ_eq_with_density_pos_part_sub_with_density_neg_part {f : α → ℝ} (hfi : integrable f μ) : μ.with_densityᵥ f = @to_signed_measure α _ (μ.with_density (λ x, ennreal.of_real $ f x)) (is_finite_measure_with_density_of_real hfi.2) - @to_signed_measure α _ (μ.with_density (λ x, ennreal.of_real $ -f x)) (is_finite_measure_with_density_of_real hfi.neg.2) := begin ext i hi, rw [with_densityᵥ_apply hfi hi, integral_eq_lintegral_pos_part_sub_lintegral_neg_part hfi.integrable_on, vector_measure.sub_apply, to_signed_measure_apply_measurable hi, to_signed_measure_apply_measurable hi, with_density_apply _ hi, with_density_apply _ hi], end lemma integrable.with_densityᵥ_trim_eq_integral {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) {f : α → ℝ} (hf : integrable f μ) {i : set α} (hi : measurable_set[m] i) : (μ.with_densityᵥ f).trim hm i = ∫ x in i, f x ∂μ := by rw [vector_measure.trim_measurable_set_eq hm hi, with_densityᵥ_apply hf (hm _ hi)] lemma integrable.with_densityᵥ_trim_absolutely_continuous {m m0 : measurable_space α} {μ : measure α} (hm : m ≤ m0) (hfi : integrable f μ) : (μ.with_densityᵥ f).trim hm ≪ (μ.trim hm).to_ennreal_vector_measure := begin refine vector_measure.absolutely_continuous.mk (λ j hj₁ hj₂, _), rw [measure.to_ennreal_vector_measure_apply_measurable hj₁, trim_measurable_set_eq hm hj₁] at hj₂, rw [vector_measure.trim_measurable_set_eq hm hj₁, with_densityᵥ_apply hfi (hm _ hj₁)], simp only [measure.restrict_eq_zero.mpr hj₂, integral_zero_measure] end end signed_measure end measure_theory
e97f18ca7d6b889158584148dbcf1a0288cc6a12
e898bfefd5cb60a60220830c5eba68cab8d02c79
/uexp/src/uexp/SDP.lean
b571d18866cbb8a2b3aa9f522463bc7f82561ef3
[ "BSD-2-Clause" ]
permissive
kkpapa/Cosette
9ed09e2dc4c1ecdef815c30b5501f64a7383a2ce
fda8fdbbf0de6c1be9b4104b87bbb06cede46329
refs/heads/master
1,584,573,128,049
1,526,370,422,000
1,526,370,422,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,372
lean
import .sql import .tactics import .u_semiring import .extra_constants import .cosette_tactics import .TDP -- assume there is only sig inside squash lemma sig2_distr_plus {s₁ s₂ : Schema} {f₁ f₂ : Tuple s₁ → Tuple s₂ → usr} : (∑ t₁ t₂ , f₁ t₁ t₂ + f₂ t₁ t₂) = (∑ t₁ t₂ , f₁ t₁ t₂) + (∑ t₁ t₂, f₂ t₁ t₂) := begin rw ← sig_distr_plus, apply congr_arg, funext, apply sig_distr_plus, end meta def inside_squash (e: expr) : tactic expr := match e with | `(usr.squash %%d) := tactic.to_expr ``(%%d) | _ := do tactic.fail "no squash to match" end meta def add_sqush (e: expr) : tactic expr := tactic.to_expr ``(usr.squash %%e) meta def solve_lem (n: nat) : tactic unit := do repeat_n n (tactic.applyc `congr_arg >> tactic.funext), `[rw eq_lem], remove_all_unit, tactic.try tactic.ac_refl -- add lem of ith binder and jth binder meta def add_lem (i j: nat) : tactic unit := do lhs ← get_lhs, le ← inside_squash lhs, -- orginal sig lsr ← return $ sigma_expr_to_sigma_repr le, ⟨body, binders⟩ ← sigma_repr_to_closed_body_expr' lsr, binders' ← return $ list.reverse binders, let (exprs, names) := binders'.unzip, let t₁ := list.ilast $ list.take (i+1) exprs, let t₂ := list.ilast $ list.take (j+1) exprs, lem ← tactic.to_expr ``((%%t₁ ≃ %%t₂) + usr.not (%%t₁ ≃ %%t₂)), lr ← product_to_repr body, new_lr ← return $ lem :: lr, new_body ← repr_to_product new_lr, abstracted ← return $ expr.abstract_locals new_body names, new ← sigma_repr_to_sigma_expr ⟨lsr.var_schemas, abstracted⟩, eq_lemma ← tactic.to_expr ``(%%le = %%new), ng_before ← list.length <$> tactic.get_goals, lemma_name ← tactic.mk_fresh_name, tactic.assert lemma_name eq_lemma, tactic.focus1 $ solve_lem (list.length lsr.var_schemas), ng_after ← list.length <$> tactic.get_goals, if ng_after > ng_before then tactic.fail "add_lem fail" else (do eq_lemma_name ← tactic.resolve_name lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma_name, tactic.clear eq_lemma_name) meta def is_plus : expr → bool | `(_ + _) := tt | _ := ff meta def solve_split_ins (n:nat) : tactic unit := do repeat_n n (tactic.applyc `congr_arg >> tactic.funext), `[rw time_distrib_r] /- split + introduced by lem -/ meta def split_lem : tactic unit := do lhs ← get_lhs, le ← inside_squash lhs, -- orginal sig lsr ← return $ sigma_expr_to_sigma_repr le, ⟨body, binders⟩ ← sigma_repr_to_closed_body_expr' lsr, binders' ← return $ list.reverse binders, let (exprs, names) := binders'.unzip, lr ← product_to_repr body, if not $ is_plus (list.head lr) then return () --do nothing else do (a, b) ← match (list.head lr) with | `(%%a + %%b) := return (a, b) | _ := tactic.fail "spli_lem fail" end, b1 ← repr_to_product (a::(list.tail lr)), b2 ← repr_to_product (b::(list.tail lr)), new ← tactic.to_expr ``(%%b1 + %%b2), abstracted ← return $ expr.abstract_locals new names, new_ex ← sigma_repr_to_sigma_expr ⟨lsr.var_schemas, abstracted⟩, eq_lemma ← tactic.to_expr ``(%%le = %%new_ex), ng_before ← list.length <$> tactic.get_goals, lemma_name ← tactic.mk_fresh_name, tactic.assert lemma_name eq_lemma, tactic.focus1 $ solve_split_ins (list.length lsr.var_schemas), ng_after ← list.length <$> tactic.get_goals, if ng_after > ng_before then tactic.fail "add_lem fail" else (do eq_lemma_name ← tactic.resolve_name lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma_name, tactic.clear eq_lemma_name) meta def solve_distr_lem (n:nat) : tactic unit := do repeat_n (n - 1) `[rw ← sig_distr_plus, apply congr_arg, funext], tactic.applyc `sig_distr_plus meta def distr_lem : tactic unit := do lhs ← get_lhs, le ← inside_squash lhs, -- orginal sig lsr ← return $ sigma_expr_to_sigma_repr le, ⟨body, binders⟩ ← sigma_repr_to_closed_body_expr' lsr, binders' ← return $ list.reverse binders, let (exprs, names) := binders'.unzip, if not $ is_plus body then return () --do nothing else do (a, b) ← match body with | `(%%a + %%b) := return (a, b) | _ := tactic.fail "spli_lem fail" end, a1 ← return $ expr.abstract_locals a names, a2 ← return $ expr.abstract_locals b names, new1 ← sigma_repr_to_sigma_expr ⟨lsr.var_schemas, a1⟩, new2 ← sigma_repr_to_sigma_expr ⟨lsr.var_schemas, a2⟩, eq_lemma ← tactic.to_expr ``(%%le = %%new1 + %%new2), ng_before ← list.length <$> tactic.get_goals, lemma_name ← tactic.mk_fresh_name, tactic.assert lemma_name eq_lemma, tactic.focus1 $ solve_distr_lem (list.length lsr.var_schemas), ng_after ← list.length <$> tactic.get_goals, if ng_after > ng_before then tactic.fail "add_lem fail" else (do eq_lemma_name ← tactic.resolve_name lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma_name, tactic.clear eq_lemma_name) -- get a from ∥ a + b ∥ meta def first_in_squash (scope: tactic expr) : tactic expr := do ex ← scope, match ex with | `(usr.squash (%%a + %%b)) := return a | _ := tactic.fail "no squashed union in scope" end meta def snd_in_squash (scope: tactic expr) : tactic expr := do ex ← scope, match ex with | `(usr.squash (%%a + %%b)) := return b | _ := tactic.fail "no squashed union in scope" end meta def unwrap_squash (scope: tactic expr) : tactic expr := do ex ← scope, match ex with | `(usr.squash %%a) := return a | _ := tactic.fail "no squash to unwrap" end meta def is_one (e:expr) :bool := match e with | `(has_one.one usr) := true | _ := false end meta def unit_ueq_to_one (lp: list expr) : tactic (list expr) := do let f : expr → tactic expr := λ e, match e with | `(%%a ≃ %%b) := if a = b then tactic.to_expr ``(has_one.one usr) else return e | ex := return ex end in do l ← monad.mapm f lp, return $ list.filter (λ x, ¬ (is_one x)) l meta def prove_in_sig (n: nat) (solver: tactic unit ) : tactic unit := do repeat_n n $ tactic.applyc `congr_arg >> tactic.funext, solver /- simplification inside sigma target: expr getter trans: transformation on AST solver: proof for transformation -/ meta def simplify_in_sig (target: tactic expr) (trans: list expr → tactic (list expr)) (solver: tactic unit): tactic unit := do old ← target, lsr ← return $ sigma_expr_to_sigma_repr old, ⟨body, binders⟩ ← sigma_repr_to_closed_body_expr' lsr, binders' ← return $ list.reverse binders, let (exprs, names) := binders'.unzip, lr ← product_to_repr body, new_lr ← trans lr, new_body ← repr_to_product new_lr, abstracted ← return $ expr.abstract_locals new_body names, new ← sigma_repr_to_sigma_expr ⟨lsr.var_schemas, abstracted⟩, eq_lemma ← tactic.to_expr ``(%%old = %%new), ng_before ← list.length <$> tactic.get_goals, lemma_name ← tactic.mk_fresh_name, tactic.assert lemma_name eq_lemma, tactic.focus1 $ prove_in_sig (list.length names) solver, ng_after ← list.length <$> tactic.get_goals, if ng_after > ng_before then tactic.fail "simplify_inside_sig fail" else (do eq_lemma_name ← tactic.resolve_name lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma_name, tactic.clear eq_lemma_name) meta def unify_binder_i_j (i j: nat) : tactic unit := do add_lem i j, -- add lem of i-th and j-th binders split_lem, -- split plus inside sig distr_lem, -- distribute plus over sig -- remove dup sig on one side remove_dup_sigs (first_in_squash get_lhs), `[rw plus_comm], remove_dup_sigs (first_in_squash get_lhs), -- simplify after remove_dup_sigs simplify_in_sig (first_in_squash get_lhs) unit_ueq_to_one `[repeat {rw eq_unit}, remove_all_unit], `[rw plus_comm], simplify_in_sig (first_in_squash get_lhs) unit_ueq_to_one `[repeat {rw eq_unit}, remove_all_unit], -- remove redundant relation -- factorize -- reduce done return () example {Γ s : Schema} (a : relation s) (g : Tuple Γ) (t : Tuple s): ∥(∑ (t₁ t₂ : Tuple s), denote_r a t₁ * (denote_r a t₂ * (t≃t₁)))∥ = ∥(∑ (t_1 : Tuple s), denote_r a t_1 * (t≃t_1))∥ := begin unify_binder_i_j 0 1, rw dup_in_squashed_union, have h: (∑ (x : Tuple s), denote_r a x * (denote_r a t * usr.not (t≃x))) = denote_r a t * (∑ (x : Tuple s), denote_r a x * usr.not (t≃x)), focus{ simp, TDP, }, rewrite h, clear h, rw squash_union_factor, apply ueq_symm, remove_dup_sigs $ unwrap_squash get_lhs, refl, end example {Γ s : Schema} {ty0 ty1 : datatype} (a : relation s) (c0 : Column ty0 s) (c1 : Column ty1 s) (g : Tuple Γ) (t : Tuple (tree.leaf ty0 ++ tree.leaf ty1)): ∥(∑ (t₁ t₂ : Tuple s), (denoteProj c0 t₁≃denoteProj c0 t₂) * (denote_r a t₁ * (denote_r a t₂ * ((denoteProj c1 t₁≃denoteProj c1 t₂) * (t≃(denoteProj c0 t₂, denoteProj c1 t₂))))))∥ = ∥(∑ (t_1 : Tuple s), denote_r a t_1 * (t≃(denoteProj c0 t_1, denoteProj c1 t_1)))∥ := begin unify_binder_i_j 0 1, sorry, end example {Γ s1 s2 : Schema} (a : SQL Γ s1) (b : SQL Γ s2) (ty0 ty1 : datatype) (x : Column ty0 s1) (ya : Column ty1 s1) (yb : Column ty1 s2) (g : Tuple Γ) (t : Tuple (tree.leaf ty0)): ∥(∑ (t₁ : Tuple s1) (t₂ : Tuple s2), denoteSQL a g t₁ * (denoteSQL b g t₂ * ((t≃denoteProj x t₁) * (denoteProj ya t₁≃denoteProj yb t₂))))∥ = ∥(∑ (t₁ t₂ : Tuple s1) (t₂_1 : Tuple s2), (denoteProj ya t₁≃denoteProj yb t₂_1) * ((denoteProj x t₁≃denoteProj x t₂) * (denoteSQL a g t₁ * (denoteSQL b g t₂_1 * (denoteSQL a g t₂ * (t≃denoteProj x t₁))))))∥ := begin apply ueq_symm, unify_binder_i_j 0 1, sorry, end
0f76aed203b2c8fefbf0ea606d11d3724a147956
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/nat/cast.lean
ad1339c3cb4da721b404b165ba3b4ac05b66dc00
[ "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
4,458
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import tactic.interactive algebra.order algebra.ordered_group algebra.ring import tactic.norm_cast namespace nat variables {α : Type*} section variables [has_zero α] [has_one α] [has_add α] /-- Canonical homomorphism from `ℕ` to a type `α` with `0`, `1` and `+`. -/ protected def cast : ℕ → α | 0 := 0 | (n+1) := cast n + 1 @[priority 0] instance cast_coe : has_coe ℕ α := ⟨nat.cast⟩ @[simp, squash_cast] theorem cast_zero : ((0 : ℕ) : α) = 0 := rfl theorem cast_add_one (n : ℕ) : ((n + 1 : ℕ) : α) = n + 1 := rfl @[simp, move_cast] theorem cast_succ (n : ℕ) : ((succ n : ℕ) : α) = n + 1 := rfl end @[simp, squash_cast] theorem cast_one [add_monoid α] [has_one α] : ((1 : ℕ) : α) = 1 := zero_add _ @[simp, move_cast] theorem cast_add [add_monoid α] [has_one α] (m) : ∀ n, ((m + n : ℕ) : α) = m + n | 0 := (add_zero _).symm | (n+1) := show ((m + n : ℕ) : α) + 1 = m + (n + 1), by rw [cast_add n, add_assoc] instance [add_monoid α] [has_one α] : is_add_monoid_hom (coe : ℕ → α) := { map_zero := cast_zero, map_add := cast_add } @[simp, squash_cast, move_cast] theorem cast_bit0 [add_monoid α] [has_one α] (n : ℕ) : ((bit0 n : ℕ) : α) = bit0 n := cast_add _ _ @[simp, squash_cast, move_cast] theorem cast_bit1 [add_monoid α] [has_one α] (n : ℕ) : ((bit1 n : ℕ) : α) = bit1 n := by rw [bit1, cast_add_one, cast_bit0]; refl lemma cast_two {α : Type*} [semiring α] : ((2 : ℕ) : α) = 2 := by simp @[simp, move_cast] theorem cast_pred [add_group α] [has_one α] : ∀ {n}, n > 0 → ((n - 1 : ℕ) : α) = n - 1 | (n+1) h := (add_sub_cancel (n:α) 1).symm @[simp, move_cast] theorem cast_sub [add_group α] [has_one α] {m n} (h : m ≤ n) : ((n - m : ℕ) : α) = n - m := eq_sub_of_add_eq $ by rw [← cast_add, nat.sub_add_cancel h] @[simp, move_cast] theorem cast_mul [semiring α] (m) : ∀ n, ((m * n : ℕ) : α) = m * n | 0 := (mul_zero _).symm | (n+1) := (cast_add _ _).trans $ show ((m * n : ℕ) : α) + m = m * (n + 1), by rw [cast_mul n, left_distrib, mul_one] instance [semiring α] : is_semiring_hom (coe : ℕ → α) := by refine_struct {..}; simp theorem mul_cast_comm [semiring α] (a : α) (n : ℕ) : a * n = n * a := by induction n; simp [left_distrib, right_distrib, *] @[simp] theorem cast_nonneg [linear_ordered_semiring α] : ∀ n : ℕ, 0 ≤ (n : α) | 0 := le_refl _ | (n+1) := add_nonneg (cast_nonneg n) zero_le_one @[simp, elim_cast] theorem cast_le [linear_ordered_semiring α] : ∀ {m n : ℕ}, (m : α) ≤ n ↔ m ≤ n | 0 n := by simp [zero_le] | (m+1) 0 := by simpa [not_succ_le_zero] using lt_add_of_lt_of_nonneg zero_lt_one (@cast_nonneg α _ m) | (m+1) (n+1) := (add_le_add_iff_right 1).trans $ (@cast_le m n).trans $ (add_le_add_iff_right 1).symm @[simp, elim_cast] theorem cast_lt [linear_ordered_semiring α] {m n : ℕ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_pos [linear_ordered_semiring α] {n : ℕ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] lemma cast_add_one_pos [linear_ordered_semiring α] (n : ℕ) : 0 < (n : α) + 1 := add_pos_of_nonneg_of_pos n.cast_nonneg zero_lt_one theorem eq_cast [add_monoid α] [has_one α] (f : ℕ → α) (H0 : f 0 = 0) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) : ∀ n : ℕ, f n = n | 0 := H0 | (n+1) := by rw [Hadd, H1, eq_cast]; refl theorem eq_cast' [add_group α] [has_one α] (f : ℕ → α) (H1 : f 1 = 1) (Hadd : ∀ x y, f (x + y) = f x + f y) : ∀ n : ℕ, f n = n := eq_cast _ (by rw [← add_left_inj (f 0), add_zero, ← Hadd]) H1 Hadd @[simp, squash_cast] theorem cast_id (n : ℕ) : ↑n = n := (eq_cast id rfl rfl (λ _ _, rfl) n).symm @[simp, move_cast] theorem cast_min [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, move_cast] theorem cast_max [decidable_linear_ordered_semiring α] {a b : ℕ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, elim_cast] theorem abs_cast [decidable_linear_ordered_comm_ring α] (a : ℕ) : abs (a : α) = a := abs_of_nonneg (cast_nonneg a) end nat
ba3f8fffe7847b78bb190f8675113523b413aba3
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Lean/Compiler/LCNF/Passes.lean
e0494f84e1e6b93e8c5765f58c1d0b18076dffc7
[ "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
3,082
lean
/- Copyright (c) 2022 Henrik Böving. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Henrik Böving -/ import Lean.Compiler.LCNF.PassManager import Lean.Compiler.LCNF.PullLetDecls import Lean.Compiler.LCNF.CSE import Lean.Compiler.LCNF.Simp import Lean.Compiler.LCNF.PullFunDecls import Lean.Compiler.LCNF.ReduceJpArity import Lean.Compiler.LCNF.JoinPoints import Lean.Compiler.LCNF.Specialize import Lean.Compiler.LCNF.PhaseExt namespace Lean.Compiler.LCNF open PassInstaller def init : Pass where name := `init run := fun decls => do decls.forM (·.saveBase) return decls phase := .base def normalizeFVarIds (decl : Decl) : CoreM Decl := do let ngenSaved ← getNGen setNGen {} try CompilerM.run <| decl.internalize finally setNGen ngenSaved def saveBase : Pass := .mkPerDeclaration `saveBase (fun decl => do (← normalizeFVarIds decl).saveBase; return decl) .base def builtinPassManager : PassManager := { passes := #[ init, pullInstances, cse, simp, findJoinPoints, pullFunDecls, reduceJpArity, -- extendJoinPointContext, simp { etaPoly := true, inlinePartial := true, implementedBy := true } (occurrence := 1), specialize, simp (occurrence := 2), cse, saveBase -- End of base phase ] } def runImportedDecls (importedDeclNames : Array (Array Name)) : CoreM PassManager := do let mut m := builtinPassManager for declNames in importedDeclNames do for declName in declNames do m ← runFromDecl m declName return m builtin_initialize passManagerExt : PersistentEnvExtension Name (Name × PassManager) (List Name × PassManager) ← registerPersistentEnvExtension { name := `cpass mkInitial := return ([], builtinPassManager) addImportedFn := fun ns => return ([], ← ImportM.runCoreM <| runImportedDecls ns) addEntryFn := fun (installerDeclNames, _) (installerDeclName, managerNew) => (installerDeclName :: installerDeclNames, managerNew) exportEntriesFn := fun s => s.1.reverse.toArray } def getPassManager : CoreM PassManager := return passManagerExt.getState (← getEnv) |>.2 def addPass (declName : Name) : CoreM Unit := do let info ← getConstInfo declName match info.type with | .const `Lean.Compiler.LCNF.PassInstaller .. => let managerNew ← runFromDecl (← getPassManager) declName modifyEnv fun env => passManagerExt.addEntry env (declName, managerNew) | _ => throwError "invalid 'cpass' only 'PassInstaller's can be added via the 'cpass' attribute: {info.type}" builtin_initialize registerBuiltinAttribute { name := `cpass descr := "compiler passes for the code generator" add := fun declName stx kind => do Attribute.Builtin.ensureNoArgs stx unless kind == AttributeKind.global do throwError "invalid attribute 'cpass', must be global" discard <| addPass declName applicationTime := .afterCompilation } builtin_initialize registerTraceClass `Compiler.saveBase (inherited := true) end Lean.Compiler.LCNF
bcbb5de5c32087746d60f8303d87e3ffd747f2a2
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/category_theory/opposites.lean
7992686d0a0bc19d72f6e53c528b47286a70b386
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
14,825
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison -/ import category_theory.types import category_theory.equivalence universes v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes]. open opposite variables {C : Type u₁} section quiver variables [quiver.{v₁} C] lemma quiver.hom.op_inj {X Y : C} : function.injective (quiver.hom.op : (X ⟶ Y) → (op Y ⟶ op X)) := λ _ _ H, congr_arg quiver.hom.unop H lemma quiver.hom.unop_inj {X Y : Cᵒᵖ} : function.injective (quiver.hom.unop : (X ⟶ Y) → (unop Y ⟶ unop X)) := λ _ _ H, congr_arg quiver.hom.op H @[simp] lemma quiver.hom.unop_op {X Y : C} {f : X ⟶ Y} : f.op.unop = f := rfl @[simp] lemma quiver.hom.op_unop {X Y : Cᵒᵖ} {f : X ⟶ Y} : f.unop.op = f := rfl end quiver namespace category_theory variables [category.{v₁} C] /-- The opposite category. See https://stacks.math.columbia.edu/tag/001M. -/ instance category.opposite : category.{v₁} Cᵒᵖ := { comp := λ _ _ _ f g, (g.unop ≫ f.unop).op, id := λ X, (𝟙 (unop X)).op } @[simp] lemma op_comp {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).op = g.op ≫ f.op := rfl @[simp] lemma op_id {X : C} : (𝟙 X).op = 𝟙 (op X) := rfl @[simp] lemma unop_comp {X Y Z : Cᵒᵖ} {f : X ⟶ Y} {g : Y ⟶ Z} : (f ≫ g).unop = g.unop ≫ f.unop := rfl @[simp] lemma unop_id {X : Cᵒᵖ} : (𝟙 X).unop = 𝟙 (unop X) := rfl @[simp] lemma unop_id_op {X : C} : (𝟙 (op X)).unop = 𝟙 X := rfl @[simp] lemma op_id_unop {X : Cᵒᵖ} : (𝟙 (unop X)).op = 𝟙 X := rfl section variables (C) /-- The functor from the double-opposite of a category to the underlying category. -/ @[simps] def op_op : (Cᵒᵖ)ᵒᵖ ⥤ C := { obj := λ X, unop (unop X), map := λ X Y f, f.unop.unop } /-- The functor from a category to its double-opposite. -/ @[simps] def unop_unop : C ⥤ Cᵒᵖᵒᵖ := { obj := λ X, op (op X), map := λ X Y f, f.op.op } /-- The double opposite category is equivalent to the original. -/ @[simps] def op_op_equivalence : Cᵒᵖᵒᵖ ≌ C := { functor := op_op C, inverse := unop_unop C, unit_iso := iso.refl (𝟭 Cᵒᵖᵒᵖ), counit_iso := iso.refl (unop_unop C ⋙ op_op C) } end /-- If `f.op` is an isomorphism `f` must be too. (This cannot be an instance as it would immediately loop!) -/ lemma is_iso_of_op {X Y : C} (f : X ⟶ Y) [is_iso f.op] : is_iso f := ⟨⟨(inv (f.op)).unop, ⟨quiver.hom.op_inj (by simp), quiver.hom.op_inj (by simp)⟩⟩⟩ namespace functor section variables {D : Type u₂} [category.{v₂} D] variables {C D} /-- The opposite of a functor, i.e. considering a functor `F : C ⥤ D` as a functor `Cᵒᵖ ⥤ Dᵒᵖ`. In informal mathematics no distinction is made between these. -/ @[simps] protected def op (F : C ⥤ D) : Cᵒᵖ ⥤ Dᵒᵖ := { obj := λ X, op (F.obj (unop X)), map := λ X Y f, (F.map f.unop).op } /-- Given a functor `F : Cᵒᵖ ⥤ Dᵒᵖ` we can take the "unopposite" functor `F : C ⥤ D`. In informal mathematics no distinction is made between these. -/ @[simps] protected def unop (F : Cᵒᵖ ⥤ Dᵒᵖ) : C ⥤ D := { obj := λ X, unop (F.obj (op X)), map := λ X Y f, (F.map f.op).unop } /-- The isomorphism between `F.op.unop` and `F`. -/ @[simps] def op_unop_iso (F : C ⥤ D) : F.op.unop ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) /-- The isomorphism between `F.unop.op` and `F`. -/ @[simps] def unop_op_iso (F : Cᵒᵖ ⥤ Dᵒᵖ) : F.unop.op ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) variables (C D) /-- Taking the opposite of a functor is functorial. -/ @[simps] def op_hom : (C ⥤ D)ᵒᵖ ⥤ (Cᵒᵖ ⥤ Dᵒᵖ) := { obj := λ F, (unop F).op, map := λ F G α, { app := λ X, (α.unop.app (unop X)).op, naturality' := λ X Y f, quiver.hom.unop_inj (α.unop.naturality f.unop).symm } } /-- Take the "unopposite" of a functor is functorial. -/ @[simps] def op_inv : (Cᵒᵖ ⥤ Dᵒᵖ) ⥤ (C ⥤ D)ᵒᵖ := { obj := λ F, op F.unop, map := λ F G α, quiver.hom.op { app := λ X, (α.app (op X)).unop, naturality' := λ X Y f, quiver.hom.op_inj $ (α.naturality f.op).symm } } variables {C D} /-- Another variant of the opposite of functor, turning a functor `C ⥤ Dᵒᵖ` into a functor `Cᵒᵖ ⥤ D`. In informal mathematics no distinction is made. -/ @[simps] protected def left_op (F : C ⥤ Dᵒᵖ) : Cᵒᵖ ⥤ D := { obj := λ X, unop (F.obj (unop X)), map := λ X Y f, (F.map f.unop).unop } /-- Another variant of the opposite of functor, turning a functor `Cᵒᵖ ⥤ D` into a functor `C ⥤ Dᵒᵖ`. In informal mathematics no distinction is made. -/ @[simps] protected def right_op (F : Cᵒᵖ ⥤ D) : C ⥤ Dᵒᵖ := { obj := λ X, op (F.obj (op X)), map := λ X Y f, (F.map f.op).op } instance {F : C ⥤ D} [full F] : full F.op := { preimage := λ X Y f, (F.preimage f.unop).op } instance {F : C ⥤ D} [faithful F] : faithful F.op := { map_injective' := λ X Y f g h, quiver.hom.unop_inj $ by simpa using map_injective F (quiver.hom.op_inj h) } /-- If F is faithful then the right_op of F is also faithful. -/ instance right_op_faithful {F : Cᵒᵖ ⥤ D} [faithful F] : faithful F.right_op := { map_injective' := λ X Y f g h, quiver.hom.op_inj (map_injective F (quiver.hom.op_inj h)) } /-- If F is faithful then the left_op of F is also faithful. -/ instance left_op_faithful {F : C ⥤ Dᵒᵖ} [faithful F] : faithful F.left_op := { map_injective' := λ X Y f g h, quiver.hom.unop_inj (map_injective F (quiver.hom.unop_inj h)) } /-- The isomorphism between `F.left_op.right_op` and `F`. -/ @[simps] def left_op_right_op_iso (F : C ⥤ Dᵒᵖ) : F.left_op.right_op ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) /-- The isomorphism between `F.right_op.left_op` and `F`. -/ @[simps] def right_op_left_op_iso (F : Cᵒᵖ ⥤ D) : F.right_op.left_op ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) end end functor namespace nat_trans variables {D : Type u₂} [category.{v₂} D] section variables {F G : C ⥤ D} local attribute [semireducible] quiver.opposite /-- The opposite of a natural transformation. -/ @[simps] protected def op (α : F ⟶ G) : G.op ⟶ F.op := { app := λ X, (α.app (unop X)).op, naturality' := begin tidy, erw α.naturality, refl, end } @[simp] lemma op_id (F : C ⥤ D) : nat_trans.op (𝟙 F) = 𝟙 (F.op) := rfl /-- The "unopposite" of a natural transformation. -/ @[simps] protected def unop {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ⟶ G) : G.unop ⟶ F.unop := { app := λ X, (α.app (op X)).unop, naturality' := begin tidy, erw α.naturality, refl, end } @[simp] lemma unop_id (F : Cᵒᵖ ⥤ Dᵒᵖ) : nat_trans.unop (𝟙 F) = 𝟙 (F.unop) := rfl /-- Given a natural transformation `α : F.op ⟶ G.op`, we can take the "unopposite" of each component obtaining a natural transformation `G ⟶ F`. -/ @[simps] protected def remove_op (α : F.op ⟶ G.op) : G ⟶ F := { app := λ X, (α.app (op X)).unop, naturality' := begin intros X Y f, have := congr_arg quiver.hom.op (α.naturality f.op), dsimp at this, erw this, refl, end } @[simp] lemma remove_op_id (F : C ⥤ D) : nat_trans.remove_op (𝟙 F.op) = 𝟙 F := rfl end section variables {F G : C ⥤ Dᵒᵖ} local attribute [semireducible] quiver.opposite /-- Given a natural transformation `α : F ⟶ G`, for `F G : C ⥤ Dᵒᵖ`, taking `unop` of each component gives a natural transformation `G.left_op ⟶ F.left_op`. -/ @[simps] protected def left_op (α : F ⟶ G) : G.left_op ⟶ F.left_op := { app := λ X, (α.app (unop X)).unop, naturality' := begin intros X Y f, dsimp, erw α.naturality, refl, end } /-- Given a natural transformation `α : F.left_op ⟶ G.left_op`, for `F G : C ⥤ Dᵒᵖ`, taking `op` of each component gives a natural transformation `G ⟶ F`. -/ @[simps] protected def remove_left_op (α : F.left_op ⟶ G.left_op) : G ⟶ F := { app := λ X, (α.app (op X)).op, naturality' := begin intros X Y f, have := congr_arg quiver.hom.op (α.naturality f.op), dsimp at this, erw this end } end section variables {F G : Cᵒᵖ ⥤ D} local attribute [semireducible] quiver.opposite /-- Given a natural transformation `α : F ⟶ G`, for `F G : Cᵒᵖ ⥤ D`, taking `op` of each component gives a natural transformation `G.right_op ⟶ F.right_op`. -/ @[simps] protected def right_op (α : F ⟶ G) : G.right_op ⟶ F.right_op := { app := λ X, (α.app _).op, naturality' := begin intros X Y f, dsimp, erw α.naturality, refl, end } /-- Given a natural transformation `α : F.right_op ⟶ G.right_op`, for `F G : Cᵒᵖ ⥤ D`, taking `unop` of each component gives a natural transformation `G ⟶ F`. -/ @[simps] protected def remove_right_op (α : F.right_op ⟶ G.right_op) : G ⟶ F := { app := λ X, (α.app X.unop).unop, naturality' := begin intros X Y f, have := congr_arg quiver.hom.unop (α.naturality f.unop), dsimp at this, erw this, end } end end nat_trans namespace iso variables {X Y : C} /-- The opposite isomorphism. -/ @[simps] protected def op (α : X ≅ Y) : op Y ≅ op X := { hom := α.hom.op, inv := α.inv.op, hom_inv_id' := quiver.hom.unop_inj α.inv_hom_id, inv_hom_id' := quiver.hom.unop_inj α.hom_inv_id } /-- The isomorphism obtained from an isomorphism in the opposite category. -/ @[simps] def unop {X Y : Cᵒᵖ} (f : X ≅ Y) : Y.unop ≅ X.unop := { hom := f.hom.unop, inv := f.inv.unop, hom_inv_id' := by simp only [← unop_comp, f.inv_hom_id, unop_id], inv_hom_id' := by simp only [← unop_comp, f.hom_inv_id, unop_id] } @[simp] lemma unop_op {X Y : Cᵒᵖ} (f : X ≅ Y) : f.unop.op = f := by ext; refl @[simp] lemma op_unop {X Y : C} (f : X ≅ Y) : f.op.unop = f := by ext; refl end iso namespace nat_iso variables {D : Type u₂} [category.{v₂} D] variables {F G : C ⥤ D} /-- The natural isomorphism between opposite functors `G.op ≅ F.op` induced by a natural isomorphism between the original functors `F ≅ G`. -/ @[simps] protected def op (α : F ≅ G) : G.op ≅ F.op := { hom := nat_trans.op α.hom, inv := nat_trans.op α.inv, hom_inv_id' := begin ext, dsimp, rw ←op_comp, rw α.inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←op_comp, rw α.hom_inv_id_app, refl, end } /-- The natural isomorphism between functors `G ≅ F` induced by a natural isomorphism between the opposite functors `F.op ≅ G.op`. -/ @[simps] protected def remove_op (α : F.op ≅ G.op) : G ≅ F := { hom := nat_trans.remove_op α.hom, inv := nat_trans.remove_op α.inv, hom_inv_id' := begin ext, dsimp, rw ←unop_comp, rw α.inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←unop_comp, rw α.hom_inv_id_app, refl, end } /-- The natural isomorphism between functors `G.unop ≅ F.unop` induced by a natural isomorphism between the original functors `F ≅ G`. -/ @[simps] protected def unop {F G : Cᵒᵖ ⥤ Dᵒᵖ} (α : F ≅ G) : G.unop ≅ F.unop := { hom := nat_trans.unop α.hom, inv := nat_trans.unop α.inv, hom_inv_id' := begin ext, dsimp, rw ←unop_comp, rw α.inv_hom_id_app, refl, end, inv_hom_id' := begin ext, dsimp, rw ←unop_comp, rw α.hom_inv_id_app, refl, end } end nat_iso namespace equivalence variables {D : Type u₂} [category.{v₂} D] /-- An equivalence between categories gives an equivalence between the opposite categories. -/ @[simps] def op (e : C ≌ D) : Cᵒᵖ ≌ Dᵒᵖ := { functor := e.functor.op, inverse := e.inverse.op, unit_iso := (nat_iso.op e.unit_iso).symm, counit_iso := (nat_iso.op e.counit_iso).symm, functor_unit_iso_comp' := λ X, by { apply quiver.hom.unop_inj, dsimp, simp, }, } /-- An equivalence between opposite categories gives an equivalence between the original categories. -/ @[simps] def unop (e : Cᵒᵖ ≌ Dᵒᵖ) : C ≌ D := { functor := e.functor.unop, inverse := e.inverse.unop, unit_iso := (nat_iso.unop e.unit_iso).symm, counit_iso := (nat_iso.unop e.counit_iso).symm, functor_unit_iso_comp' := λ X, by { apply quiver.hom.op_inj, dsimp, simp, }, } end equivalence /-- The equivalence between arrows of the form `A ⟶ B` and `B.unop ⟶ A.unop`. Useful for building adjunctions. Note that this (definitionally) gives variants ``` def op_equiv' (A : C) (B : Cᵒᵖ) : (opposite.op A ⟶ B) ≃ (B.unop ⟶ A) := op_equiv _ _ def op_equiv'' (A : Cᵒᵖ) (B : C) : (A ⟶ opposite.op B) ≃ (B ⟶ A.unop) := op_equiv _ _ def op_equiv''' (A B : C) : (opposite.op A ⟶ opposite.op B) ≃ (B ⟶ A) := op_equiv _ _ ``` -/ @[simps] def op_equiv (A B : Cᵒᵖ) : (A ⟶ B) ≃ (B.unop ⟶ A.unop) := { to_fun := λ f, f.unop, inv_fun := λ g, g.op, left_inv := λ _, rfl, right_inv := λ _, rfl } instance subsingleton_of_unop (A B : Cᵒᵖ) [subsingleton (unop B ⟶ unop A)] : subsingleton (A ⟶ B) := (op_equiv A B).subsingleton instance decidable_eq_of_unop (A B : Cᵒᵖ) [decidable_eq (unop B ⟶ unop A)] : decidable_eq (A ⟶ B) := (op_equiv A B).decidable_eq universes v variables {α : Type v} [preorder α] /-- Construct a morphism in the opposite of a preorder category from an inequality. -/ def op_hom_of_le {U V : αᵒᵖ} (h : unop V ≤ unop U) : U ⟶ V := h.hom.op lemma le_of_op_hom {U V : αᵒᵖ} (h : U ⟶ V) : unop V ≤ unop U := h.unop.le namespace functor variables (C) variables (D : Type u₂) [category.{v₂} D] /-- The equivalence of functor categories induced by `op` and `unop`. -/ @[simps] def op_unop_equiv : (C ⥤ D)ᵒᵖ ≌ Cᵒᵖ ⥤ Dᵒᵖ := { functor := op_hom _ _, inverse := op_inv _ _, unit_iso := nat_iso.of_components (λ F, F.unop.op_unop_iso.op) begin intros F G f, dsimp [op_unop_iso], rw [(show f = f.unop.op, by simp), ← op_comp, ← op_comp], congr' 1, tidy, end, counit_iso := nat_iso.of_components (λ F, F.unop_op_iso) (by tidy) }. /-- The equivalence of functor categories induced by `left_op` and `right_op`. -/ @[simps] def left_op_right_op_equiv : (Cᵒᵖ ⥤ D)ᵒᵖ ≌ (C ⥤ Dᵒᵖ) := { functor := { obj := λ F, F.unop.right_op, map := λ F G η, η.unop.right_op }, inverse := { obj := λ F, op F.left_op, map := λ F G η, η.left_op.op }, unit_iso := nat_iso.of_components (λ F, F.unop.right_op_left_op_iso.op) begin intros F G η, dsimp, rw [(show η = η.unop.op, by simp), ← op_comp, ← op_comp], congr' 1, tidy, end, counit_iso := nat_iso.of_components (λ F, F.left_op_right_op_iso) (by tidy) } end functor end category_theory
ee81f8cb307670442c7eaca41cad50e31867226f
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/free_module_pid.lean
41d03b3aa88c0f984cd216589c6fe1a0944d9e00
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
17,772
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen -/ import linear_algebra.basis import linear_algebra.finsupp_vector_space import ring_theory.principal_ideal_domain import ring_theory.finiteness /-! # Free modules over PID A free `R`-module `M` is a module with a basis over `R`, equivalently it is an `R`-module linearly equivalent to `ι →₀ R` for some `ι`. This file proves a submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain (PID), i.e. we have instances `[integral_domain R] [is_principal_ideal_ring R]`. We express "free `R`-module of finite rank" as a module `M` which has a basis `b : ι → R`, where `ι` is a `fintype`. We call the cardinality of `ι` the rank of `M` in this file; it would be equal to `finrank R M` if `R` is a field and `M` is a vector space. ## Main results - `submodule.induction_on_rank`: if `M` is free and finitely generated, if `P` holds for `⊥ : submodule R M` and if `P N` follows from `P N'` for all `N'` that are of lower rank, then `P` holds on all submodules - `submodule.exists_basis_of_pid`: if `M` is free and finitely generated and `R` is a PID, then `N : submodule R M` is free and finitely generated. This is the first part of the structure theorem for modules. ## Tags free module, finitely generated module, rank, structure theorem -/ open_locale big_operators section comm_ring universes u v variables {R : Type u} {M : Type v} [comm_ring R] [add_comm_group M] [module R M] variables {ι : Type*} (b : basis ι R M) open submodule.is_principal lemma eq_bot_of_rank_eq_zero [no_zero_divisors R] (b : basis ι R M) (N : submodule R M) (rank_eq : ∀ {m : ℕ} (v : fin m → N), linear_independent R (coe ∘ v : fin m → M) → m = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, contrapose! rank_eq with x_ne, refine ⟨1, λ _, ⟨x, hx⟩, _, one_ne_zero⟩, rw fintype.linear_independent_iff, rintros g sum_eq i, fin_cases i, simp only [function.const_apply, fin.default_eq_zero, submodule.coe_mk, univ_unique, function.comp_const, finset.sum_singleton] at sum_eq, exact (b.smul_eq_zero.mp sum_eq).resolve_right x_ne end open submodule lemma eq_bot_of_generator_maximal_map_eq_zero (b : basis ι R M) {N : submodule R M} {ϕ : M →ₗ[R] R} (hϕ : ∀ (ψ : M →ₗ[R] R), N.map ϕ ≤ N.map ψ → N.map ψ = N.map ϕ) [(N.map ϕ).is_principal] (hgen : generator (N.map ϕ) = 0) : N = ⊥ := begin rw submodule.eq_bot_iff, intros x hx, refine b.ext_elem (λ i, _), rw (eq_bot_iff_generator_eq_zero _).mpr hgen at hϕ, rw [linear_equiv.map_zero, finsupp.zero_apply], exact (submodule.eq_bot_iff _).mp (hϕ ((finsupp.lapply i).comp b.repr) bot_le) _ ⟨x, hx, rfl⟩ end -- Note that the converse may not hold if `ϕ` is not injective. lemma generator_map_dvd_of_mem {N : submodule R M} (ϕ : M →ₗ[R] R) [(N.map ϕ).is_principal] {x : M} (hx : x ∈ N) : generator (N.map ϕ) ∣ ϕ x := by { rw [← mem_iff_generator_dvd, submodule.mem_map], exact ⟨x, hx, rfl⟩ } end comm_ring section integral_domain variables {ι : Type*} {R : Type*} [integral_domain R] variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M} lemma not_mem_of_ortho {x : M} {N : submodule R M} (ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) : x ∉ N := by { intro hx, simpa using ortho (-1) x hx } lemma ne_zero_of_ortho {x : M} {N : submodule R M} (ortho : ∀ (c : R) (y ∈ N), c • x + y = (0 : M) → c = 0) : x ≠ 0 := mt (λ h, show x ∈ N, from h.symm ▸ N.zero_mem) (not_mem_of_ortho ortho) /-- If `N` is a submodule with finite rank, do induction on adjoining a linear independent element to a submodule. -/ def submodule.induction_on_rank_aux (b : basis ι R M) (P : submodule R M → Sort*) (ih : ∀ (N : submodule R M), (∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N) (n : ℕ) (N : submodule R M) (rank_le : ∀ {m : ℕ} (v : fin m → N), linear_independent R (coe ∘ v : fin m → M) → m ≤ n) : P N := begin haveI : decidable_eq M := classical.dec_eq M, have Pbot : P ⊥, { apply ih, intros N N_le x x_mem x_ortho, exfalso, simpa using x_ortho 1 0 N.zero_mem }, induction n with n rank_ih generalizing N, { suffices : N = ⊥, { rwa this }, apply eq_bot_of_rank_eq_zero b _ (λ m v hv, nat.le_zero_iff.mp (rank_le v hv)) }, apply ih, intros N' N'_le x x_mem x_ortho, apply rank_ih, intros m v hli, refine nat.succ_le_succ_iff.mp (rank_le (fin.cons ⟨x, x_mem⟩ (λ i, ⟨v i, N'_le (v i).2⟩)) _), convert hli.fin_cons' x _ _, { ext i, refine fin.cases _ _ i; simp }, { intros c y hcy, refine x_ortho c y (submodule.span_le.mpr _ y.2) hcy, rintros _ ⟨z, rfl⟩, exact (v z).2 } end /-- In an `n`-dimensional space, the rank is at most `m`. -/ lemma basis.card_le_card_of_linear_independent_aux {R : Type*} [integral_domain R] (n : ℕ) {m : ℕ} (v : fin m → fin n → R) : linear_independent R v → m ≤ n := begin revert m, refine nat.rec_on n _ _, { intros m v hv, cases m, { refl }, exfalso, have : v 0 = 0, { ext i, exact fin_zero_elim i }, have := hv.ne_zero 0, contradiction }, intros n ih m v hv, cases m, { exact nat.zero_le _ }, -- Induction: try deleting a dimension and a vector. suffices : ∃ (v' : fin m → fin n → R), linear_independent R v', { obtain ⟨v', hv'⟩ := this, exact nat.succ_le_succ (ih v' hv') }, -- Either the `0`th dimension is irrelevant... by_cases this : linear_independent R (λ i, v i ∘ fin.succ), { exact ⟨_, this.comp fin.succ (fin.succ_injective _)⟩ }, -- ... or we can write (x, 0, 0, ...) = ∑ i, c i • v i where c i ≠ 0 for some i. simp only [fintype.linear_independent_iff, not_forall, not_imp] at this, obtain ⟨c, hc, i, hi⟩ := this, have hc : ∀ (j : fin n), ∑ (i : fin m.succ), c i * v i j.succ = 0, { intro j, convert congr_fun hc j, rw [@finset.sum_apply (fin n) (λ _, R) _ _ _], simp }, set x := ∑ i', c i' * v i' 0 with x_eq, -- We'll show each equation of the form (y, 0, 0, ...) = ∑ i', c' i' • v i' must have c' i ≠ 0. use λ i' j', v (i.succ_above i') j'.succ, rw fintype.linear_independent_iff at ⊢ hv, -- Assume that ∑ i, c' i • v i = (y, 0, 0, ...). intros c' hc' i', set y := ∑ i', c' i' * v (i.succ_above i') 0 with y_eq, have hc' : ∀ (j : fin n), (∑ (i' : fin m), c' i' * v (i.succ_above i') j.succ) = 0, { intro j, convert congr_fun hc' j, rw [@finset.sum_apply (fin n) (λ _, R) _ _ _], simp }, -- Combine these equations to get a linear dependence on the full space. have : ∑ i', (y * c i' - x * (@fin.insert_nth _ (λ _, R) i 0 c') i') • v i' = 0, { simp only [sub_smul, mul_smul, finset.sum_sub_distrib, ← finset.smul_sum], ext j, rw [pi.zero_apply, @pi.sub_apply (fin n.succ) (λ _, R) _ _ _ _], simp only [finset.sum_apply, pi.smul_apply, smul_eq_mul, sub_eq_zero], symmetry, rw [fin.sum_univ_succ_above _ i, fin.insert_nth_apply_same, zero_mul, zero_add, mul_comm], simp only [fin.insert_nth_apply_succ_above], refine fin.cases _ _ j, { simp }, { intro j, rw [hc', hc, zero_mul, mul_zero] } }, have hyc := hv _ this i, simp only [fin.insert_nth_apply_same, mul_zero, sub_zero, mul_eq_zero] at hyc, -- Therefore, either `c i = 0` (which contradicts the assumption on `i`) or `y = 0`. have hy := hyc.resolve_right hi, -- If `y = 0`, then we can extend `c'` to a linear dependence on the full space, -- which implies `c'` is trivial. convert hv (@fin.insert_nth _ (λ _, R) i 0 c') _ (i.succ_above i'), { rw fin.insert_nth_apply_succ_above }, ext j, -- After a bit of calculation, we find that `∑ i, c' i • v i = (y, 0, 0, ...) = 0` as promised. rw [@finset.sum_apply (fin n.succ) (λ _, R) _ _ _, pi.zero_apply], simp only [pi.smul_apply, smul_eq_mul], rw [fin.sum_univ_succ_above _ i, fin.insert_nth_apply_same, zero_mul, zero_add], simp only [fin.insert_nth_apply_succ_above], refine fin.cases _ _ j, { rw [← y_eq, hy] }, { exact hc' }, end lemma basis.card_le_card_of_linear_independent {R : Type*} [integral_domain R] [module R M] {ι : Type*} [fintype ι] (b : basis ι R M) {ι' : Type*} [fintype ι'] {v : ι' → M} (hv : linear_independent R v) : fintype.card ι' ≤ fintype.card ι := begin haveI := classical.dec_eq ι, haveI := classical.dec_eq ι', let e := fintype.equiv_fin ι, let e' := fintype.equiv_fin ι', let b := b.reindex e, have hv := (linear_independent_equiv e'.symm).mpr hv, have hv := hv.map' _ b.equiv_fun.ker, exact basis.card_le_card_of_linear_independent_aux (fintype.card ι) _ hv, end /-- If we have two bases on the same space, their indices are in bijection. -/ noncomputable def basis.index_equiv {R ι ι' : Type*} [integral_domain R] [module R M] [fintype ι] [fintype ι'] (b : basis ι R M) (b' : basis ι' R M) : ι ≃ ι' := (fintype.card_eq.mp (le_antisymm (b'.card_le_card_of_linear_independent b.linear_independent) (b.card_le_card_of_linear_independent b'.linear_independent))).some /-- If `N` is a submodule in a free, finitely generated module, do induction on adjoining a linear independent element to a submodule. -/ def submodule.induction_on_rank [fintype ι] (b : basis ι R M) (P : submodule R M → Sort*) (ih : ∀ (N : submodule R M), (∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N) (N : submodule R M) : P N := submodule.induction_on_rank_aux b P ih (fintype.card ι) N (λ s hs hli, by simpa using b.card_le_card_of_linear_independent hli) open submodule.is_principal end integral_domain section principal_ideal_domain open submodule.is_principal set submodule variables {ι : Type*} {R : Type*} [integral_domain R] [is_principal_ideal_ring R] variables {M : Type*} [add_comm_group M] [module R M] {b : ι → M} open_locale matrix /-- A submodule of a free `R`-module of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. -/ noncomputable def submodule.basis_of_pid {ι : Type*} [fintype ι] (b : basis ι R M) (N : submodule R M) : Σ (n : ℕ), basis (fin n) R N := begin haveI := classical.dec_eq M, refine N.induction_on_rank b _ _, intros N ih, -- Let `ϕ` be a maximal projection of `M` onto `R`, in the sense that there is -- no `ψ` whose image of `N` is larger than `ϕ`'s image of `N`. have : ∃ ϕ : M →ₗ[R] R, ∀ (ψ : M →ₗ[R] R), N.map ϕ ≤ N.map ψ → N.map ψ = N.map ϕ, { obtain ⟨P, P_eq, P_max⟩ := set_has_maximal_iff_noetherian.mpr (infer_instance : is_noetherian R R) _ (submodule.range_map_nonempty N), obtain ⟨ϕ, rfl⟩ := set.mem_range.mp P_eq, use ϕ, intros ψ hψ, exact P_max (N.map ψ) ⟨_, rfl⟩ hψ }, let ϕ := this.some, have ϕ_max := this.some_spec, -- Since `N.map ϕ` is a `R`-submodule of the PID `R`, it is principal and generated by some `a`. have a_mem : generator (N.map ϕ) ∈ N.map ϕ := generator_mem _, -- If `a` is zero, then the submodule is trivial. So let's assume `a ≠ 0`, `N ≠ ⊥` by_cases a_zero : generator (N.map ϕ) = 0, { rw eq_bot_of_generator_maximal_map_eq_zero b ϕ_max a_zero, exact ⟨0, basis.empty _⟩ }, -- We claim that `ϕ⁻¹ a = y` can be taken as basis element of `N`. let y := a_mem.some, obtain ⟨y_mem, ϕy_eq⟩ := a_mem.some_spec, have ϕy_ne_zero := λ h, a_zero (ϕy_eq.symm.trans h), -- If `N'` is `ker (ϕ : N → R)`, it is smaller than `N` so by the induction hypothesis, -- it has a basis `bN'`. have N'_le_ker : (ϕ.ker ⊓ N) ≤ ϕ.ker := inf_le_left, have N'_le_N : (ϕ.ker ⊓ N) ≤ N := inf_le_right, -- Note that `y` is orthogonal to `N'`. have y_ortho_N' : ∀ (c : R) (z : M), z ∈ ϕ.ker ⊓ N → c • y + z = 0 → c = 0, { intros c x hx hc, have hx' : x ∈ ϕ.ker := (inf_le_left : _ ⊓ N ≤ _) hx, rw linear_map.mem_ker at hx', simpa [ϕy_ne_zero, hx'] using congr_arg ϕ hc }, obtain ⟨nN', bN'⟩ := ih (ϕ.ker ⊓ N) N'_le_N y y_mem y_ortho_N', use nN'.succ, -- Extend `bN'` with `y`, we'll show it's linear independent and spans `N`. let bN'y : fin (nN'.succ) → N := fin.cons ⟨y, y_mem⟩ (submodule.of_le N'_le_N ∘ bN'), refine @basis.mk _ _ _ bN'y _ _ _ _ _, { apply (bN'.linear_independent .map' (submodule.of_le N'_le_N) (submodule.ker_of_le _ _ _)) .fin_cons' _ _ _, intros c z hc, apply y_ortho_N' c z (submodule.mem_inf.mpr ⟨_, z.1.2⟩) (congr_arg coe hc), have : submodule.span R (set.range (submodule.of_le N'_le_N ∘ bN')) ≤ (ϕ.dom_restrict N).ker, { rw submodule.span_le, rintros _ ⟨i, rfl⟩, exact N'_le_ker (bN' i).2 }, exact this z.2 }, { rw eq_top_iff, rintro x -, rw [fin.range_cons, set.range_comp, submodule.mem_span_insert, submodule.span_image], obtain ⟨b, hb⟩ : _ ∣ ϕ x := generator_map_dvd_of_mem ϕ x.2, refine ⟨b, x - b • ⟨_, y_mem⟩, _, _⟩, { rw submodule.mem_map, refine ⟨⟨x - b • _, _⟩, bN'.mem_span _, rfl⟩, refine submodule.mem_inf.mpr ⟨linear_map.mem_ker.mpr _, N.sub_mem x.2 (N.smul_mem _ y_mem)⟩, dsimp only, rw [linear_map.map_sub, linear_map.map_smul, hb, ϕy_eq, smul_eq_mul, mul_comm, sub_self] }, { ext, simp only [ϕy_eq, add_sub_cancel'_right] } }, end /-- A submodule inside a free `R`-submodule of finite rank is also a free `R`-module of finite rank, if `R` is a principal ideal domain. -/ noncomputable def submodule.basis_of_pid_of_le {ι : Type*} [fintype ι] {N O : submodule R M} (hNO : N ≤ O) (b : basis ι R O) : Σ (n : ℕ), basis (fin n) R N := let ⟨n, bN'⟩ := submodule.basis_of_pid b (N.comap O.subtype) in ⟨n, bN'.map (submodule.comap_subtype_equiv_of_le hNO)⟩ /-- A submodule inside the span of a linear independent family is a free `R`-module of finite rank, if `R` is a principal ideal domain. -/ noncomputable def submodule.basis_of_pid_of_le_span {ι : Type*} [fintype ι] {b : ι → M} (hb : linear_independent R b) {N : submodule R M} (le : N ≤ submodule.span R (set.range b)) : Σ (n : ℕ), basis (fin n) R N := submodule.basis_of_pid_of_le le (basis.span hb) variable {M} /-- A finite type torsion free module over a PID is free. -/ noncomputable def module.free_of_finite_type_torsion_free [fintype ι] {s : ι → M} (hs : span R (range s) = ⊤) [no_zero_smul_divisors R M] : Σ (n : ℕ), basis (fin n) R M := begin classical, -- We define `N` as the submodule spanned by a maximal linear independent subfamily of `s` have := exists_maximal_independent R s, let I : set ι := this.some, obtain ⟨indepI : linear_independent R (s ∘ coe : I → M), hI : ∀ i ∉ I, ∃ a : R, a ≠ 0 ∧ a • s i ∈ span R (s '' I)⟩ := this.some_spec, let N := span R (range $ (s ∘ coe : I → M)), -- same as `span R (s '' I)` but more convenient let sI : I → N := λ i, ⟨s i.1, subset_span (mem_range_self i)⟩, -- `s` restricted to `I` let sI_basis : basis I R N, -- `s` restricted to `I` is a basis of `N` from basis.span indepI, -- Our first goal is to build `A ≠ 0` such that `A • M ⊆ N` have exists_a : ∀ i : ι, ∃ a : R, a ≠ 0 ∧ a • s i ∈ N, { intro i, by_cases hi : i ∈ I, { use [1, zero_ne_one.symm], rw one_smul, exact subset_span (mem_range_self (⟨i, hi⟩ : I)) }, { simpa [image_eq_range s I] using hI i hi } }, choose a ha ha' using exists_a, let A := ∏ i, a i, have hA : A ≠ 0, { rw finset.prod_ne_zero_iff, simpa using ha }, -- `M ≃ A • M` because `M` is torsion free and `A ≠ 0` let φ : M →ₗ[R] M := linear_map.lsmul R M A, have : φ.ker = ⊥, from linear_map.ker_lsmul hA, let ψ : M ≃ₗ[R] φ.range := linear_equiv.of_injective φ this, have : φ.range ≤ N, -- as announced, `A • M ⊆ N` { suffices : ∀ i, φ (s i) ∈ N, { rw [linear_map.range_eq_map, ← hs, φ.map_span_le], rintros _ ⟨i, rfl⟩, apply this }, intro i, calc (∏ j, a j) • s i = (∏ j in {i}ᶜ, a j) • a i • s i : by rw [fintype.prod_eq_prod_compl_mul i, mul_smul] ... ∈ N : N.smul_mem _ (ha' i) }, -- Since a submodule of a free `R`-module is free, we get that `A • M` is free obtain ⟨n, b : basis (fin n) R φ.range⟩ := submodule.basis_of_pid_of_le this sI_basis, -- hence `M` is free. exact ⟨n, b.map ψ.symm⟩ end /-- A finite type torsion free module over a PID is free. -/ noncomputable def module.free_of_finite_type_torsion_free' [module.finite R M] [no_zero_smul_divisors R M] : Σ (n : ℕ), basis (fin n) R M := module.free_of_finite_type_torsion_free module.finite.exists_fin.some_spec.some_spec end principal_ideal_domain /-- A set of linearly independent vectors in a module `M` over a semiring `S` is also linearly independent over a subring `R` of `K`. -/ lemma linear_independent.restrict_scalars_algebras {R S M ι : Type*} [comm_semiring R] [semiring S] [add_comm_monoid M] [algebra R S] [module R M] [module S M] [is_scalar_tower R S M] (hinj : function.injective (algebra_map R S)) {v : ι → M} (li : linear_independent S v) : linear_independent R v := linear_independent.restrict_scalars (by rwa algebra.algebra_map_eq_smul_one' at hinj) li
62cfa14e462454adaa791b806a282696135b815b
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/ring_theory/polynomial/bernstein.lean
58432174dad0e5c7b1cea331b1359c43523901d7
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
15,835
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.polynomial.derivative import data.polynomial.algebra_map import data.mv_polynomial.pderiv import data.nat.choose.sum import linear_algebra.basis import ring_theory.polynomial.pochhammer /-! # Bernstein polynomials The definition of the Bernstein polynomials ``` bernstein_polynomial (R : Type*) [comm_ring R] (n ν : ℕ) : polynomial R := (choose n ν) * X^ν * (1 - X)^(n - ν) ``` and the fact that for `ν : fin (n+1)` these are linearly independent over `ℚ`. We prove the basic identities * `(finset.range (n + 1)).sum (λ ν, bernstein_polynomial R n ν) = 1` * `(finset.range (n + 1)).sum (λ ν, ν • bernstein_polynomial R n ν) = n • X` * `(finset.range (n + 1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) = (n * (n-1)) • X^2` ## Notes See also `analysis.special_functions.bernstein`, which defines the Bernstein approximations of a continuous function `f : C([0,1], ℝ)`, and shows that these converge uniformly to `f`. -/ noncomputable theory open nat (choose) open polynomial (X) variables (R : Type*) [comm_ring R] /-- `bernstein_polynomial R n ν` is `(choose n ν) * X^ν * (1 - X)^(n - ν)`. Although the coefficients are integers, it is convenient to work over an arbitrary commutative ring. -/ def bernstein_polynomial (n ν : ℕ) : polynomial R := choose n ν * X^ν * (1 - X)^(n - ν) example : bernstein_polynomial ℤ 3 2 = 3 * X^2 - 3 * X^3 := begin norm_num [bernstein_polynomial, choose], ring, end namespace bernstein_polynomial lemma eq_zero_of_lt {n ν : ℕ} (h : n < ν) : bernstein_polynomial R n ν = 0 := by simp [bernstein_polynomial, nat.choose_eq_zero_of_lt h] section variables {R} {S : Type*} [comm_ring S] @[simp] lemma map (f : R →+* S) (n ν : ℕ) : (bernstein_polynomial R n ν).map f = bernstein_polynomial S n ν := by simp [bernstein_polynomial] end lemma flip (n ν : ℕ) (h : ν ≤ n) : (bernstein_polynomial R n ν).comp (1-X) = bernstein_polynomial R n (n-ν) := begin dsimp [bernstein_polynomial], simp [h, nat.sub_sub_assoc, mul_right_comm], end lemma flip' (n ν : ℕ) (h : ν ≤ n) : bernstein_polynomial R n ν = (bernstein_polynomial R n (n-ν)).comp (1-X) := begin rw [←flip _ _ _ h, polynomial.comp_assoc], simp, end lemma eval_at_0 (n ν : ℕ) : (bernstein_polynomial R n ν).eval 0 = if ν = 0 then 1 else 0 := begin dsimp [bernstein_polynomial], split_ifs, { subst h, simp, }, { simp [zero_pow (nat.pos_of_ne_zero h)], }, end lemma eval_at_1 (n ν : ℕ) : (bernstein_polynomial R n ν).eval 1 = if ν = n then 1 else 0 := begin dsimp [bernstein_polynomial], split_ifs, { subst h, simp, }, { obtain w | w := (n - ν).eq_zero_or_pos, { simp [nat.choose_eq_zero_of_lt ((nat.le_of_sub_eq_zero w).lt_of_ne (ne.symm h))] }, { simp [zero_pow w] } }, end. lemma derivative_succ_aux (n ν : ℕ) : (bernstein_polynomial R (n+1) (ν+1)).derivative = (n+1) * (bernstein_polynomial R n ν - bernstein_polynomial R n (ν + 1)) := begin dsimp [bernstein_polynomial], suffices : ↑((n + 1).choose (ν + 1)) * ((↑ν + 1) * X ^ ν) * (1 - X) ^ (n - ν) -(↑((n + 1).choose (ν + 1)) * X ^ (ν + 1) * (↑(n - ν) * (1 - X) ^ (n - ν - 1))) = (↑n + 1) * (↑(n.choose ν) * X ^ ν * (1 - X) ^ (n - ν) - ↑(n.choose (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1))), { simpa [polynomial.derivative_pow, ←sub_eq_add_neg], }, conv_rhs { rw mul_sub, }, -- We'll prove the two terms match up separately. refine congr (congr_arg has_sub.sub _) _, { simp only [←mul_assoc], refine congr (congr_arg (*) (congr (congr_arg (*) _) rfl)) rfl, -- Now it's just about binomial coefficients exact_mod_cast congr_arg (λ m : ℕ, (m : polynomial R)) (nat.succ_mul_choose_eq n ν).symm, }, { rw nat.sub_sub, rw [←mul_assoc,←mul_assoc], congr' 1, rw mul_comm , rw [←mul_assoc,←mul_assoc], congr' 1, norm_cast, congr' 1, convert (nat.choose_mul_succ_eq n (ν + 1)).symm using 1, { convert mul_comm _ _ using 2, simp, }, { apply mul_comm, }, }, end lemma derivative_succ (n ν : ℕ) : (bernstein_polynomial R n (ν+1)).derivative = n * (bernstein_polynomial R (n-1) ν - bernstein_polynomial R (n-1) (ν+1)) := begin cases n, { simp [bernstein_polynomial], }, { apply derivative_succ_aux, } end lemma derivative_zero (n : ℕ) : (bernstein_polynomial R n 0).derivative = -n * bernstein_polynomial R (n-1) 0 := begin dsimp [bernstein_polynomial], simp [polynomial.derivative_pow], end lemma iterate_derivative_at_0_eq_zero_of_lt (n : ℕ) {ν k : ℕ} : k < ν → (polynomial.derivative^[k] (bernstein_polynomial R n ν)).eval 0 = 0 := begin cases ν, { rintro ⟨⟩, }, { rw nat.lt_succ_iff, induction k with k ih generalizing n ν, { simp [eval_at_0], }, { simp only [derivative_succ, int.coe_nat_eq_zero, int.nat_cast_eq_coe_nat, mul_eq_zero, function.comp_app, function.iterate_succ, polynomial.iterate_derivative_sub, polynomial.iterate_derivative_cast_nat_mul, polynomial.eval_mul, polynomial.eval_nat_cast, polynomial.eval_sub], intro h, apply mul_eq_zero_of_right, rw [ih _ _ (nat.le_of_succ_le h), sub_zero], convert ih _ _ (nat.pred_le_pred h), exact (nat.succ_pred_eq_of_pos (k.succ_pos.trans_le h)).symm } }, end @[simp] lemma iterate_derivative_succ_at_0_eq_zero (n ν : ℕ) : (polynomial.derivative^[ν] (bernstein_polynomial R n (ν+1))).eval 0 = 0 := iterate_derivative_at_0_eq_zero_of_lt R n (lt_add_one ν) open polynomial @[simp] lemma iterate_derivative_at_0 (n ν : ℕ) : (polynomial.derivative^[ν] (bernstein_polynomial R n ν)).eval 0 = (pochhammer R ν).eval (n - (ν - 1) : ℕ) := begin by_cases h : ν ≤ n, { induction ν with ν ih generalizing n h, { simp [eval_at_0], }, { have h' : ν ≤ n-1 := nat.le_sub_right_of_add_le h, simp only [derivative_succ, ih (n-1) h', iterate_derivative_succ_at_0_eq_zero, nat.succ_sub_succ_eq_sub, nat.sub_zero, sub_zero, iterate_derivative_sub, iterate_derivative_cast_nat_mul, eval_one, eval_mul, eval_add, eval_sub, eval_X, eval_comp, eval_nat_cast, function.comp_app, function.iterate_succ, pochhammer_succ_left], obtain rfl | h'' := ν.eq_zero_or_pos, { simp }, { have : n - 1 - (ν - 1) = n - ν, { rw ←nat.succ_le_iff at h'', rw [nat.sub_sub, add_comm, nat.sub_add_cancel h''] }, rw [this, pochhammer_eval_succ], rw_mod_cast nat.sub_add_cancel (h'.trans n.pred_le) } } }, { simp only [not_le] at h, rw [nat.sub_eq_zero_of_le (nat.le_pred_of_lt h), eq_zero_of_lt R h], simp [pos_iff_ne_zero.mp (pos_of_gt h)] }, end lemma iterate_derivative_at_0_ne_zero [char_zero R] (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[ν] (bernstein_polynomial R n ν)).eval 0 ≠ 0 := begin simp only [int.coe_nat_eq_zero, bernstein_polynomial.iterate_derivative_at_0, ne.def, nat.cast_eq_zero], simp only [←pochhammer_eval_cast], norm_cast, apply ne_of_gt, obtain rfl|h' := nat.eq_zero_or_pos ν, { simp, }, { rw ← nat.succ_pred_eq_of_pos h' at h, exact pochhammer_pos _ _ (nat.sub_pos_of_lt (nat.lt_of_succ_le h)) } end /-! Rather than redoing the work of evaluating the derivatives at 1, we use the symmetry of the Bernstein polynomials. -/ lemma iterate_derivative_at_1_eq_zero_of_lt (n : ℕ) {ν k : ℕ} : k < n - ν → (polynomial.derivative^[k] (bernstein_polynomial R n ν)).eval 1 = 0 := begin intro w, rw flip' _ _ _ (nat.lt_of_sub_pos (pos_of_gt w)).le, simp [polynomial.eval_comp, iterate_derivative_at_0_eq_zero_of_lt R n w], end @[simp] lemma iterate_derivative_at_1 (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[n-ν] (bernstein_polynomial R n ν)).eval 1 = (-1)^(n-ν) * (pochhammer R (n - ν)).eval (ν + 1) := begin rw flip' _ _ _ h, simp [polynomial.eval_comp, h], obtain rfl | h' := h.eq_or_lt, { simp, }, { congr, norm_cast, rw [nat.sub_sub, nat.sub_sub_self (nat.succ_le_iff.mpr h')] }, end lemma iterate_derivative_at_1_ne_zero [char_zero R] (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[n-ν] (bernstein_polynomial R n ν)).eval 1 ≠ 0 := begin rw [bernstein_polynomial.iterate_derivative_at_1 _ _ _ h, ne.def, neg_one_pow_mul_eq_zero_iff, ←nat.cast_succ, ←pochhammer_eval_cast, ←nat.cast_zero, nat.cast_inj], exact (pochhammer_pos _ _ (nat.succ_pos ν)).ne', end open submodule lemma linear_independent_aux (n k : ℕ) (h : k ≤ n + 1): linear_independent ℚ (λ ν : fin k, bernstein_polynomial ℚ n ν) := begin induction k with k ih, { apply linear_independent_empty_type, rintro ⟨⟨n, ⟨⟩⟩⟩, }, { apply linear_independent_fin_succ'.mpr, fsplit, { exact ih (le_of_lt h), }, { -- The actual work! -- We show that the (n-k)-th derivative at 1 doesn't vanish, -- but vanishes for everything in the span. clear ih, simp only [nat.succ_eq_add_one, add_le_add_iff_right] at h, simp only [fin.coe_last, fin.init_def], dsimp, apply not_mem_span_of_apply_not_mem_span_image ((polynomial.derivative_lhom ℚ)^(n-k)), simp only [not_exists, not_and, submodule.mem_map, submodule.span_image], intros p m, apply_fun (polynomial.eval (1 : ℚ)), simp only [polynomial.derivative_lhom_coe, linear_map.pow_apply], -- The right hand side is nonzero, -- so it will suffice to show the left hand side is always zero. suffices : (polynomial.derivative^[n-k] p).eval 1 = 0, { rw [this], exact (iterate_derivative_at_1_ne_zero ℚ n k h).symm, }, apply span_induction m, { simp, rintro ⟨a, w⟩, simp only [fin.coe_mk], rw [iterate_derivative_at_1_eq_zero_of_lt ℚ n ((nat.sub_lt_sub_left_iff h).mpr w)] }, { simp, }, { intros x y hx hy, simp [hx, hy], }, { intros a x h, simp [h], }, }, }, end /-- The Bernstein polynomials are linearly independent. We prove by induction that the collection of `bernstein_polynomial n ν` for `ν = 0, ..., k` are linearly independent. The inductive step relies on the observation that the `(n-k)`-th derivative, evaluated at 1, annihilates `bernstein_polynomial n ν` for `ν < k`, but has a nonzero value at `ν = k`. -/ lemma linear_independent (n : ℕ) : linear_independent ℚ (λ ν : fin (n+1), bernstein_polynomial ℚ n ν) := linear_independent_aux n (n+1) (le_refl _) lemma sum (n : ℕ) : (finset.range (n + 1)).sum (λ ν, bernstein_polynomial R n ν) = 1 := begin -- We calculate `(x + (1-x))^n` in two different ways. conv { congr, congr, skip, funext, dsimp [bernstein_polynomial], rw [mul_assoc, mul_comm], }, rw ←add_pow, simp, end open polynomial open mv_polynomial lemma sum_smul (n : ℕ) : (finset.range (n + 1)).sum (λ ν, ν • bernstein_polynomial R n ν) = n • X := begin -- We calculate the `x`-derivative of `(x+y)^n`, evaluated at `y=(1-x)`, -- either directly or by using the binomial theorem. -- We'll work in `mv_polynomial bool R`. let x : mv_polynomial bool R := mv_polynomial.X tt, let y : mv_polynomial bool R := mv_polynomial.X ff, have pderiv_tt_x : pderiv tt x = 1, { simp [x], }, have pderiv_tt_y : pderiv tt y = 0, { simp [pderiv_X, y], }, let e : bool → polynomial R := λ i, cond i X (1-X), -- Start with `(x+y)^n = (x+y)^n`, -- take the `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`: have h : (x+y)^n = (x+y)^n := rfl, apply_fun (pderiv tt) at h, apply_fun (aeval e) at h, apply_fun (λ p, p * X) at h, -- On the left hand side we'll use the binomial theorem, then simplify. -- We first prepare a tedious rewrite: have w : ∀ k : ℕ, ↑k * polynomial.X ^ (k - 1) * (1 - polynomial.X) ^ (n - k) * ↑(n.choose k) * polynomial.X = k • bernstein_polynomial R n k, { rintro (_|k), { simp, }, { dsimp [bernstein_polynomial], simp only [←nat_cast_mul, nat.succ_eq_add_one, nat.add_succ_sub_one, add_zero, pow_succ], push_cast, ring, }, }, conv at h { to_lhs, rw [add_pow, (pderiv tt).map_sum, (mv_polynomial.aeval e).map_sum, finset.sum_mul], -- Step inside the sum: apply_congr, skip, simp [pderiv_mul, pderiv_tt_x, pderiv_tt_y, e, w], }, -- On the right hand side, we'll just simplify. conv at h { to_rhs, rw [pderiv_pow, (pderiv tt).map_add, pderiv_tt_x, pderiv_tt_y], simp [e] }, simpa using h, end lemma sum_mul_smul (n : ℕ) : (finset.range (n + 1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) = (n * (n-1)) • X^2 := begin -- We calculate the second `x`-derivative of `(x+y)^n`, evaluated at `y=(1-x)`, -- either directly or by using the binomial theorem. -- We'll work in `mv_polynomial bool R`. let x : mv_polynomial bool R := mv_polynomial.X tt, let y : mv_polynomial bool R := mv_polynomial.X ff, have pderiv_tt_x : pderiv tt x = 1, { simp [x], }, have pderiv_tt_y : pderiv tt y = 0, { simp [pderiv_X, y], }, let e : bool → polynomial R := λ i, cond i X (1-X), -- Start with `(x+y)^n = (x+y)^n`, -- take the second `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`: have h : (x+y)^n = (x+y)^n := rfl, apply_fun (pderiv tt) at h, apply_fun (pderiv tt) at h, apply_fun (aeval e) at h, apply_fun (λ p, p * X^2) at h, -- On the left hand side we'll use the binomial theorem, then simplify. -- We first prepare a tedious rewrite: have w : ∀ k : ℕ, ↑k * (↑(k-1) * polynomial.X ^ (k - 1 - 1)) * (1 - polynomial.X) ^ (n - k) * ↑(n.choose k) * polynomial.X^2 = (k * (k-1)) • bernstein_polynomial R n k, { rintro (_|k), { simp, }, { rcases k with (_|k), { simp, }, { dsimp [bernstein_polynomial], simp only [←nat_cast_mul, nat.succ_eq_add_one, nat.add_succ_sub_one, add_zero, pow_succ], push_cast, ring, }, }, }, conv at h { to_lhs, rw [add_pow, (pderiv tt).map_sum, (pderiv tt).map_sum, (mv_polynomial.aeval e).map_sum, finset.sum_mul], -- Step inside the sum: apply_congr, skip, simp [pderiv_mul, pderiv_tt_x, pderiv_tt_y, e, w] }, -- On the right hand side, we'll just simplify. conv at h { to_rhs, simp only [pderiv_one, pderiv_mul, pderiv_pow, pderiv_nat_cast, (pderiv tt).map_add, pderiv_tt_x, pderiv_tt_y], simp [e, smul_smul] }, simpa using h, end /-- A certain linear combination of the previous three identities, which we'll want later. -/ lemma variance (n : ℕ) : (finset.range (n+1)).sum (λ ν, (n • polynomial.X - ν)^2 * bernstein_polynomial R n ν) = n • polynomial.X * (1 - polynomial.X) := begin have p : (finset.range (n+1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) + (1 - (2 * n) • polynomial.X) * (finset.range (n+1)).sum (λ ν, ν • bernstein_polynomial R n ν) + (n^2 • X^2) * (finset.range (n+1)).sum (λ ν, bernstein_polynomial R n ν) = _ := rfl, conv at p { to_lhs, rw [finset.mul_sum, finset.mul_sum, ←finset.sum_add_distrib, ←finset.sum_add_distrib], simp only [←nat_cast_mul], simp only [←mul_assoc], simp only [←add_mul], }, conv at p { to_rhs, rw [sum, sum_smul, sum_mul_smul, ←nat_cast_mul], }, calc _ = _ : finset.sum_congr rfl (λ k m, _) ... = _ : p ... = _ : _, { congr' 1, simp only [←nat_cast_mul] with push_cast, cases k; { simp, ring, }, }, { simp only [←nat_cast_mul] with push_cast, cases n; { simp, ring, }, }, end end bernstein_polynomial
39a05d32a214bf6a211f2f3e3d3f78dad31104da
03bd658c402412f41d3026d1040ee8ca8c0fc579
/src/list/modify/basic.lean
e785bb2cb6870f404881318855052ea0cde6dacd
[]
no_license
ImperialCollegeLondon/dots_and_boxes
c205f6dbad8af9625f56715e4d1bed96b0ac1022
f7bd0b1603674a657170c5395adb717c4f670220
refs/heads/master
1,663,752,058,476
1,591,438,614,000
1,591,438,614,000
139,707,103
2
0
null
null
null
null
UTF-8
Lean
false
false
14,781
lean
import data.list.basic tactic.linarith import list.lemmas.long_lemmas open list /--Two lists are equal except one entry differs by at most d-/ structure list.modify (A : list ℤ) (B : list ℤ) (d : ℤ) := (n : ℕ) --entry in which the lists differ (ha : n < A.length) (hb : n < B.length) (heq : A.remove_nth n = B.remove_nth n) --lists are equal otherwise (bound : abs (A.nth_le n ha - B.nth_le n hb) ≤ d) -- differing entries differ by at most d /--reflexivity of list.modify for non-empty lists-/ def list.modify_refl {L : list ℤ } {d : ℤ} (h : 0 < length L) (p : 0 ≤ d): list.modify L L d := { n := 0, -- can choose an arbitrary entry in the list, as they differ by 0 everywhere ha := h, hb := h, heq := by refl, bound := begin cases L with m M, -- L = nil exfalso, -- contradicts h : 0 < length L exact nat.not_succ_le_zero 0 h, -- L = (m :: M) rw nth_le, -- get goal abs(m-m) ≤ d simp only [abs_zero, add_right_neg, sub_eq_add_neg], -- left side is zero exact p, end } /--Two lists that are equal except one entry differs by at most d have equal length-/ theorem eq_size_of_modify_list {l1 l2 : list ℤ } {d : ℤ} (h : list.modify l1 l2 d) : l1.length = l2.length := begin -- split list.modify condition into its fields cases h, -- as the lists below are equal by h_heq, their length must be equal have P : length(remove_nth l1 h_n) = length(remove_nth l2 h_n), rw h_heq, --which is h.heq rw length_remove_nth l1 h_n h_ha at P, /- lemma says, if n < length L , then length (remove_nth L n) = length L - 1 for any list L, natural number n -/ rw length_remove_nth l2 h_n h_hb at P, --need this for finish to work have Q : ¬ h_n < 0, simp, -- follows as h.n is a natural number /- Now P gives the result by cancelling -1 on both sides, but this only works if both lists have length > 0. Hence split into easy cases and let Lean do the rest by itself-/ cases l1, dsimp at h_ha, exfalso, finish, cases l2, dsimp at h_hb, exfalso, finish, finish, end /--Two lists that are equal except one entry differs by at most d are element- wise equal in all entries except the one at which they differ-/ theorem list.modify_same {A : list ℤ} {B : list ℤ} {d : ℤ} (h : list.modify A B d) (m : ℕ) (hmA : m < A.length) (hmB : m < B.length) (hmn : h.n ≠ m) : A.nth_le m hmA = B.nth_le m hmB := begin have H : length A = length B, exact eq_size_of_modify_list h,-- exactly the conclusion of the theorem above cases h, /- rewrite to put h.heq in the form take h_n A ++ tail (drop h_n A) = take h_n B ++ tail (drop h_n B) -/ rw remove_nth_eq_nth_tail at h_heq, rw modify_nth_tail_eq_take_drop at h_heq, rw remove_nth_eq_nth_tail at h_heq, rw modify_nth_tail_eq_take_drop at h_heq, /- from this we want to derive that take h_n A = take h_n B and tail (drop h_n A) = tail (drop h_n B) , because we will formuate nth_le through head, take and drop later-/ have p : length (tail (drop h_n A)) = length (tail (drop h_n B)), rw length_tail, rw length_tail, rw length_drop, rw length_drop, rw H, have h_eq_left : take h_n A = take h_n B , exact append_inj_right' h_heq p, have h_eq_right : tail (drop h_n A) = tail (drop h_n B), exact append_inj_left' h_heq p, rw ← head_reverse_take, rw ← head_reverse_take, --get rid of nth_le -- state of first goal : head (reverse (take (m + 1) A)) = head (reverse (take (m + 1) B)) /-now we need to consider where the lists could have been modified in relation to m+1 so we can show both sides give the same entry and it is not the modified one-/ have m_cases : (m+1) ≤ h_n ∨ h_n < (m+1) , exact le_or_lt (m + 1) h_n, cases m_cases, -- (m+1) ≤ h_n rw take_aux_2 m_cases h_eq_left, --solves goal as both sides will be the same --(for the lemma, see list.lemmas.long_lemmas) -- h_n < (m+1) /-this time h_eq_right will give the result, because we will use the lemma take_drop_head_eq (see list.lemmas.long_lemmas) But first we need the necessary assumptions for take_drop_head_eq, which will be h1 and hmA/hmB-/ rw nat.lt_iff_add_one_le at hmA, rw nat.lt_iff_add_one_le at hmB, have h1 : 1 ≤ m, cases m, -- m = 0 => goal : 1 ≤ 0 exfalso, have hn_0 : h_n = 0, rw nat.lt_add_one_iff at m_cases, -- for all a, b in ℕ, a < b + 1 ↔ a ≤ b exact nat.eq_zero_of_le_zero m_cases, -- for all n in ℕ, if n ≤ 0 then n = 0 exact false.elim (hmn hn_0), --hypotheses exactly contradict each other -- goal : 1 ≤ nat.succ m exact dec_trivial, --now we have all we need to use take_drop_head_eq rw take_drop_head_eq h1 hmA, rw take_drop_head_eq h1 hmB, -- from h_eq_right we can derive the following, which soves the main goal have P : tail (drop (m - 1) A) = tail (drop (m - 1) B), { rw tail_drop, --(see list.lemmas.simple) rw tail_drop, rw tail_drop at h_eq_right, rw tail_drop at h_eq_right, -- we want to use drop_lemma. For that we need the following hypothesis have h2 : nat.succ h_n ≤ nat.succ (m-1), rw nat.succ_le_succ_iff, -- for all m, n in ℕ, succ m ≤ succ n ↔ m ≤ n rw nat.lt_add_one_iff at m_cases, -- for all a, b in ℕ, a < b + 1 ↔ a ≤ b apply nat.le_pred_of_lt, -- for all m, n in ℕ, if m < n, then m ≤ n - 1 exact lt_of_le_of_ne' m_cases hmn, -- for all a, b in ℕ, if a ≤ b and a ≠ b, then a < b exact drop_aux_2 h2 h_eq_right, --(for the lemma, see list.lemmas.long_lemmas) }, rw P, refl, -- trivial assumption needed for modify_nth_tail_eq_take_drop in line 75 refl, -- same trivial assumption needed for modify_nth_tail_eq_take_drop in line 77 end /--symmetry of list.modify-/ def list.modify.symm (A B : list ℤ) (d : ℤ) (m : list.modify A B d) : list.modify B A d := { n := m.n, -- still differ in the same place ha := m.hb, hb := m.ha, heq := m.heq.symm, -- by symmetry of = in m.heq bound := by rw [←neg_sub, abs_neg]; exact m.bound -- as abs(a-b) = abs(b-a) for integers a,b } /--If you remove the same entry, that is not the modified one from both modified lists, you get a modified list-/ def list.modify_remove_nth {L1 : list ℤ} {L2 : list ℤ} {d : ℤ} (h : list.modify L1 L2 d) (m : ℕ) (h_neq : m ≠ h.n): list.modify (remove_nth L1 m) (remove_nth L2 m) d:= begin /-if index m is not in the list, then remove_nth L m = L, for any list L, so we can separate into the cases m < length L1 and length L1 ≤ m-/ by_cases hm : m < length L1, swap, -- we solve the second goal first, because it is easier -- ¬ (m < length L1) {push_neg at hm, -- ¬ (m < length L1) is defined as length L1 ≤ m have x1 : remove_nth L1 m = L1, exact remove_nth_large_n L1 hm, rw x1, rw (eq_size_of_modify_list h) at hm, have x2 : remove_nth L2 m = L2, exact remove_nth_large_n L2 hm, rw x2, exact h, }, -- m < length L1 /-this time we actually need to prove the existence of all 5 fields of list.modify-/ have hlength : length L1 = length L2, -- will need this to get heq exact eq_size_of_modify_list h, cases h, --split h into fields /-the entry at which the lists differ depends on h_n, where L1 and L2 differ. If m is less than h_n, then removing m shifts the index they differ in one space to the front. Otherwise, as we assume m ≠ h_n, they also differ in index h_n-/ by_cases hi : m < h_n, -- m < h_n {split, --split list.modify goal into a goal for each field swap 3,-- swap order of goals, so we can fix n first -- FIELD n {exact (h_n - 1)}, -- as said before, the index is one before h_n -- FIELD heq {rw remove_nth_remove_nth, --(see list.lemmas.long_lemmas) split_ifs with ite1, --split if-then-else into cases /- if-case (named ite1): m < h_n - 1 + 1 => first goal : remove_nth (remove_nth L1 (h_n - 1 + 1)) m = remove_nth (remove_nth L2 m) (h_n - 1)-/ {rw nat.sub_add_cancel, -- h_n - 1 + 1 = h_n, if 1 ≤ h_n rw h_heq, rw remove_nth_remove_nth, split_ifs with ite2, /- if-case (named ite2): h_n < m + 1 contradicts hi : m < h_n-/ exfalso, exact nat.lt_le_antisymm ite2 hi, -- a < b and b ≤ a together imply false /- else-case (named ite2): ¬ (h_n < m + 1)-/ refl, -- solves new first goal : remove_nth (remove_nth L2 m) (h_n - 1) = remove_nth (remove_nth L2 m) (h_n - 1) exact le_of_lt h_hb, -- gives h_n ≤ length L2, necessary first assumption for second remove_nth_remove_nth --new first goal : m + 1 ≤ length L2 (second necessary assumption for second remove_nt_remove_nth) rw ← hlength, exact hm, -- m < length L1 is definitionally equivalent to m + 1 ≤ length L1 exact nat.one_le_of_lt hi, },-- assumption needed for nat.sub_add_cancel, because 0-1 = 0 in ℕ /- else-case (named ite1): ¬ (m < h_n - 1 + 1) contradicts hi-/ { exfalso, rw nat.sub_add_cancel at ite1, exact false.elim (ite1 hi), exact nat.one_le_of_lt hi, }, {exact le_of_lt hm, },/- lemma says : for all a,b of the same type, a < b implies a ≤ b line proves first necessary assumtion for first remove_nt_remove_nth-/ --prove second necessary assumption for first remove_nt_remove_nth {rw nat.sub_add_cancel, exact le_of_lt h_ha, exact nat.one_le_of_lt hi,}, -- assumption needed for nat.sub_add_cancel }, -- FIELD bound {have p2 : h_n-1 < h_n, /- will be needed in line 276/277 (proving it here makes this hypothesis hold universally inside these {}-brackets)-/ cases h_n, -- h_n = 0 exfalso, -- contradicts hi as m ∈ ℕ exact nat.not_succ_le_zero m hi, -- nat.succ h_n exact lt_add_one (nat.succ h_n - 1), -- lemma says: for all a, a < a + 1 rw nth_le_remove_nth, --(see list.lemmas.long_lemmas) rw nth_le_remove_nth, split_ifs with ite, --split if-then-else into cases /- if-case (named ite): m ≤ h_n - 1 => first goal : abs (nth_le L1 (h_n - 1 + 1) ?m_1 - nth_le L2 (h_n - 1 + 1) ?m_2) ≤ d That is true by h_bound and as h_n - 1 + 1 = h_n-/ convert h_bound using 1, have x : h_n - 1 + 1 = h_n, apply nat.sub_add_cancel, exact nat.one_le_of_lt hi, simp only [x], /- simp only because proofs of existence of indices for nth_le need to be rewritten at the same time -/ -- proofs of some necessary hypotheses through convert rw nat.sub_add_cancel, exact h_ha, exact nat.one_le_of_lt hi, rw ← hlength, rw nat.sub_add_cancel, exact h_ha, exact nat.one_le_of_lt hi, /- else-case (named ite): ¬ (m ≤ h_n - 1) contradicts hi-/ exfalso, have p : m ≤ h_n -1, exact nat.le_pred_of_lt hi, -- lemma says : forall m,n in ℕ, if m < n, then m ≤ n - 1 exact false.elim (ite p), -- proof of some necessary hypotheses from nth_le_remove_nth exact lt.trans p2 h_hb, exact lt.trans p2 h_ha, }, -- FIELD ha {rw length_remove_nth, cases h_n, --h_n = 0 exfalso, exact nat.not_succ_le_zero m hi, -- nat.succ h_n rw nat.succ_eq_add_one, rw nat.add_sub_cancel, exact nat.lt_pred_iff.mpr h_ha, -- lemma says: for all n, m in ℕ, n < pred m ↔ succ n < m exact hm, }, -- FIELD hb {rw length_remove_nth, rw ← hlength, cases h_n, --h_n = 0 exfalso, exact nat.not_succ_le_zero m hi, -- nat.succ h_n rw nat.succ_eq_add_one, rw nat.add_sub_cancel, exact nat.lt_pred_iff.mpr h_ha, rw ← hlength, exact hm, },}, -- hi becomes ¬ (m < h_n) {have hx : h_n < m, -- because of hi and our initial assumption that m ≠ h_n push_neg at hi, exact lt_of_le_of_ne hi (ne.symm h_neq), split, --split list.modify goal into a goal for each field swap 3, -- swap order of goals, so we can fix n first -- FIELD n {exact h_n}, /- now we remove an element after h_n, so the position of h_n does not change in relation to the beginning of the list-/ -- FIELD heq {rw remove_nth_remove_nth, split_ifs with ite1, --split if-then-else into cases /- if-case (named ite1): m < h_n + 1 contradicts hx-/ {exfalso, exact nat.lt_le_antisymm ite1 hx, }, /- else-case (named ite1): ¬ (m ≤ h_n + 1) => first goal : remove_nth (remove_nth L1 h_n) (m - 1) = remove_nth (remove_nth L2 m) h_n True by h_heq and changing order of element removal again-/ {rw h_heq, rw remove_nth_remove_nth, split_ifs with ite2, /- if-case (named ite2): h_n < m - 1 + 1 => first goal : remove_nth (remove_nth L2 (m - 1 + 1)) h_n = remove_nth (remove_nth L2 m) h_n True as 1 ≤ m because of hx abd h_n being a natural number-/ {rw nat.sub_add_cancel, exact nat.one_le_of_lt hx}, -- proves necessary hypothesis for nat.sub_add_cancel /- else-case (named ite1): ¬ (h_n < m - 1 + 1) contradicts hx-/ {exfalso, rw nat.sub_add_cancel at ite2, exact false.elim (ite2 hx), exact nat.one_le_of_lt hx, -- proves necessary hypothesis for nat.sub_add_cancel }, -- prove necessary hypotheses for remove_nth_remove_nth exact le_of_lt h_hb, rw ← hlength, rw nat.sub_add_cancel, exact le_of_lt hm, exact nat.one_le_of_lt hx, }, exact le_of_lt hm, exact h_ha,}, -- FIELD bound /- true because the h_n-th element of (remove_nth L1 m) is also the h_n-th element of L1 (similarly for L2)-/ {rw nth_le_remove_nth, rw nth_le_remove_nth, split_ifs with ite, --split if-then-else into cases /- if-case (named ite): m ≤ h_n - 1 contradicts hx-/ exfalso, exact nat.lt_le_antisymm hx ite, /- else-case (named ite): ¬ (m ≤ h_n) => first goal : abs (nth_le L1 h_n ?m_1 - nth_le L2 h_n ?m_2) ≤ d That is just h_bound-/ convert h_bound using 1, -- prove necessary hypotheses for remove_nth_remove_nth rw ← hlength, exact lt_of_le_of_lt hx hm, exact lt_of_le_of_lt hx hm,}, -- FIELD ha {rw length_remove_nth, /- lemma says, if n < length L , then length (remove_nth L n) = length L - 1 for any list L, natural number n -/ have p2 : m ≤ length L1 - 1, exact nat.le_pred_of_lt hm, exact lt_of_lt_of_le hx p2, exact hm, --necessary hypothesis for length_remove_nth }, -- FIELD hb {rw length_remove_nth, rw ← hlength, have p2 : m ≤ length L1 - 1, exact nat.le_pred_of_lt hm, exact lt_of_lt_of_le hx p2, --necessary hypothesis for length_remove_nth rw ← hlength, exact hm, },}, end
76042cfaedf19932dbd0fa8d4d968c2b7aad4f89
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/skeletal.lean
2992995d7999e64cef45fc4d5517554fc02dc13d
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
10,873
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.adjunction.basic import category_theory.category.preorder import category_theory.isomorphism_classes import category_theory.thin /-! # Skeleton of a category Define skeletal categories as categories in which any two isomorphic objects are equal. Construct the skeleton of an arbitrary category by taking isomorphism classes, and show it is a skeleton of the original category. In addition, construct the skeleton of a thin category as a partial ordering, and (noncomputably) show it is a skeleton of the original category. The advantage of this special case being handled separately is that lemmas and definitions about orderings can be used directly, for example for the subobject lattice. In addition, some of the commutative diagrams about the functors commute definitionally on the nose which is convenient in practice. -/ universes v₁ v₂ v₃ u₁ u₂ u₃ namespace category_theory open category variables (C : Type u₁) [category.{v₁} C] variables (D : Type u₂) [category.{v₂} D] variables {E : Type u₃} [category.{v₃} E] /-- A category is skeletal if isomorphic objects are equal. -/ def skeletal : Prop := ∀ ⦃X Y : C⦄, is_isomorphic X Y → X = Y /-- `is_skeleton_of C D F` says that `F : D ⥤ C` exhibits `D` as a skeletal full subcategory of `C`, in particular `F` is a (strong) equivalence and `D` is skeletal. -/ structure is_skeleton_of (F : D ⥤ C) := (skel : skeletal D) (eqv : is_equivalence F) local attribute [instance] is_isomorphic_setoid variables {C D} /-- If `C` is thin and skeletal, then any naturally isomorphic functors to `C` are equal. -/ lemma functor.eq_of_iso {F₁ F₂ : D ⥤ C} [quiver.is_thin C] (hC : skeletal C) (hF : F₁ ≅ F₂) : F₁ = F₂ := functor.ext (λ X, hC ⟨hF.app X⟩) (λ _ _ _, subsingleton.elim _ _) /-- If `C` is thin and skeletal, `D ⥤ C` is skeletal. `category_theory.functor_thin` shows it is thin also. -/ lemma functor_skeletal [quiver.is_thin C] (hC : skeletal C) : skeletal (D ⥤ C) := λ F₁ F₂ h, h.elim (functor.eq_of_iso hC) variables (C D) /-- Construct the skeleton category as the induced category on the isomorphism classes, and derive its category structure. -/ @[derive category] def skeleton : Type u₁ := induced_category C quotient.out instance [inhabited C] : inhabited (skeleton C) := ⟨⟦default⟧⟩ /-- The functor from the skeleton of `C` to `C`. -/ @[simps, derive [full, faithful]] noncomputable def from_skeleton : skeleton C ⥤ C := induced_functor _ instance : ess_surj (from_skeleton C) := { mem_ess_image := λ X, ⟨quotient.mk X, quotient.mk_out X⟩ } noncomputable instance : is_equivalence (from_skeleton C) := equivalence.of_fully_faithfully_ess_surj (from_skeleton C) /-- The equivalence between the skeleton and the category itself. -/ noncomputable def skeleton_equivalence : skeleton C ≌ C := (from_skeleton C).as_equivalence lemma skeleton_skeletal : skeletal (skeleton C) := begin rintro X Y ⟨h⟩, have : X.out ≈ Y.out := ⟨(from_skeleton C).map_iso h⟩, simpa using quotient.sound this, end /-- The `skeleton` of `C` given by choice is a skeleton of `C`. -/ noncomputable def skeleton_is_skeleton : is_skeleton_of C (skeleton C) (from_skeleton C) := { skel := skeleton_skeletal C, eqv := from_skeleton.is_equivalence C } section variables {C D} /-- Two categories which are categorically equivalent have skeletons with equivalent objects. -/ noncomputable def equivalence.skeleton_equiv (e : C ≌ D) : skeleton C ≃ skeleton D := let f := ((skeleton_equivalence C).trans e).trans (skeleton_equivalence D).symm in { to_fun := f.functor.obj, inv_fun := f.inverse.obj, left_inv := λ X, skeleton_skeletal C ⟨(f.unit_iso.app X).symm⟩, right_inv := λ Y, skeleton_skeletal D ⟨(f.counit_iso.app Y)⟩, } end /-- Construct the skeleton category by taking the quotient of objects. This construction gives a preorder with nice definitional properties, but is only really appropriate for thin categories. If your original category is not thin, you probably want to be using `skeleton` instead of this. -/ def thin_skeleton : Type u₁ := quotient (is_isomorphic_setoid C) instance inhabited_thin_skeleton [inhabited C] : inhabited (thin_skeleton C) := ⟨quotient.mk default⟩ instance thin_skeleton.preorder : preorder (thin_skeleton C) := { le := quotient.lift₂ (λ X Y, nonempty (X ⟶ Y)) begin rintros _ _ _ _ ⟨i₁⟩ ⟨i₂⟩, exact propext ⟨nonempty.map (λ f, i₁.inv ≫ f ≫ i₂.hom), nonempty.map (λ f, i₁.hom ≫ f ≫ i₂.inv)⟩, end, le_refl := begin refine quotient.ind (λ a, _), exact ⟨𝟙 _⟩, end, le_trans := λ a b c, quotient.induction_on₃ a b c $ λ A B C, nonempty.map2 (≫) } /-- The functor from a category to its thin skeleton. -/ @[simps] def to_thin_skeleton : C ⥤ thin_skeleton C := { obj := quotient.mk, map := λ X Y f, hom_of_le (nonempty.intro f) } /-! The constructions here are intended to be used when the category `C` is thin, even though some of the statements can be shown without this assumption. -/ namespace thin_skeleton /-- The thin skeleton is thin. -/ instance thin : quiver.is_thin (thin_skeleton C) := λ _ _, ⟨by { rintros ⟨⟨f₁⟩⟩ ⟨⟨f₂⟩⟩, refl }⟩ variables {C} {D} /-- A functor `C ⥤ D` computably lowers to a functor `thin_skeleton C ⥤ thin_skeleton D`. -/ @[simps] def map (F : C ⥤ D) : thin_skeleton C ⥤ thin_skeleton D := { obj := quotient.map F.obj $ λ X₁ X₂ ⟨hX⟩, ⟨F.map_iso hX⟩, map := λ X Y, quotient.rec_on_subsingleton₂ X Y $ λ x y k, hom_of_le (k.le.elim (λ t, ⟨F.map t⟩)) } lemma comp_to_thin_skeleton (F : C ⥤ D) : F ⋙ to_thin_skeleton D = to_thin_skeleton C ⋙ map F := rfl /-- Given a natural transformation `F₁ ⟶ F₂`, induce a natural transformation `map F₁ ⟶ map F₂`.-/ def map_nat_trans {F₁ F₂ : C ⥤ D} (k : F₁ ⟶ F₂) : map F₁ ⟶ map F₂ := { app := λ X, quotient.rec_on_subsingleton X (λ x, ⟨⟨⟨k.app x⟩⟩⟩) } -- TODO: state the lemmas about what happens when you compose with `to_thin_skeleton` /-- A functor `C ⥤ D ⥤ E` computably lowers to a functor `thin_skeleton C ⥤ thin_skeleton D ⥤ thin_skeleton E` -/ @[simps] def map₂ (F : C ⥤ D ⥤ E) : thin_skeleton C ⥤ thin_skeleton D ⥤ thin_skeleton E := { obj := λ x, { obj := λ y, quotient.map₂ (λ X Y, (F.obj X).obj Y) (λ X₁ X₂ ⟨hX⟩ Y₁ Y₂ ⟨hY⟩, ⟨(F.obj X₁).map_iso hY ≪≫ (F.map_iso hX).app Y₂⟩) x y, map := λ y₁ y₂, quotient.rec_on_subsingleton x $ λ X, quotient.rec_on_subsingleton₂ y₁ y₂ $ λ Y₁ Y₂ hY, hom_of_le (hY.le.elim (λ g, ⟨(F.obj X).map g⟩)) }, map := λ x₁ x₂, quotient.rec_on_subsingleton₂ x₁ x₂ $ λ X₁ X₂ f, { app := λ y, quotient.rec_on_subsingleton y (λ Y, hom_of_le (f.le.elim (λ f', ⟨(F.map f').app Y⟩))) } } variables (C) section variables [quiver.is_thin C] instance to_thin_skeleton_faithful : faithful (to_thin_skeleton C) := {} /-- Use `quotient.out` to create a functor out of the thin skeleton. -/ @[simps] noncomputable def from_thin_skeleton : thin_skeleton C ⥤ C := { obj := quotient.out, map := λ x y, quotient.rec_on_subsingleton₂ x y $ λ X Y f, (nonempty.some (quotient.mk_out X)).hom ≫ f.le.some ≫ (nonempty.some (quotient.mk_out Y)).inv } noncomputable instance from_thin_skeleton_equivalence : is_equivalence (from_thin_skeleton C) := { inverse := to_thin_skeleton C, counit_iso := nat_iso.of_components (λ X, (nonempty.some (quotient.mk_out X))) (by tidy), unit_iso := nat_iso.of_components (λ x, quotient.rec_on_subsingleton x (λ X, eq_to_iso (quotient.sound ⟨(nonempty.some (quotient.mk_out X)).symm⟩))) (by tidy) } /-- The equivalence between the thin skeleton and the category itself. -/ noncomputable def equivalence : thin_skeleton C ≌ C := (from_thin_skeleton C).as_equivalence variables {C} lemma equiv_of_both_ways {X Y : C} (f : X ⟶ Y) (g : Y ⟶ X) : X ≈ Y := ⟨iso_of_both_ways f g⟩ instance thin_skeleton_partial_order : partial_order (thin_skeleton C) := { le_antisymm := quotient.ind₂ begin rintros _ _ ⟨f⟩ ⟨g⟩, apply quotient.sound (equiv_of_both_ways f g), end, ..category_theory.thin_skeleton.preorder C } lemma skeletal : skeletal (thin_skeleton C) := λ X Y, quotient.induction_on₂ X Y $ λ x y h, h.elim $ λ i, i.1.le.antisymm i.2.le lemma map_comp_eq (F : E ⥤ D) (G : D ⥤ C) : map (F ⋙ G) = map F ⋙ map G := functor.eq_of_iso skeletal $ nat_iso.of_components (λ X, quotient.rec_on_subsingleton X (λ x, iso.refl _)) (by tidy) lemma map_id_eq : map (𝟭 C) = 𝟭 (thin_skeleton C) := functor.eq_of_iso skeletal $ nat_iso.of_components (λ X, quotient.rec_on_subsingleton X (λ x, iso.refl _)) (by tidy) lemma map_iso_eq {F₁ F₂ : D ⥤ C} (h : F₁ ≅ F₂) : map F₁ = map F₂ := functor.eq_of_iso skeletal { hom := map_nat_trans h.hom, inv := map_nat_trans h.inv } /-- `from_thin_skeleton C` exhibits the thin skeleton as a skeleton. -/ noncomputable def thin_skeleton_is_skeleton : is_skeleton_of C (thin_skeleton C) (from_thin_skeleton C) := { skel := skeletal, eqv := thin_skeleton.from_thin_skeleton_equivalence C } noncomputable instance is_skeleton_of_inhabited : inhabited (is_skeleton_of C (thin_skeleton C) (from_thin_skeleton C)) := ⟨thin_skeleton_is_skeleton⟩ end variables {C} /-- An adjunction between thin categories gives an adjunction between their thin skeletons. -/ def lower_adjunction (R : D ⥤ C) (L : C ⥤ D) (h : L ⊣ R) : thin_skeleton.map L ⊣ thin_skeleton.map R := adjunction.mk_of_unit_counit { unit := { app := λ X, begin letI := is_isomorphic_setoid C, refine quotient.rec_on_subsingleton X (λ x, hom_of_le ⟨h.unit.app x⟩), -- TODO: make quotient.rec_on_subsingleton' so the letI isn't needed end }, counit := { app := λ X, begin letI := is_isomorphic_setoid D, refine quotient.rec_on_subsingleton X (λ x, hom_of_le ⟨h.counit.app x⟩), end } } end thin_skeleton open thin_skeleton section variables {C} {α : Type*} [partial_order α] /-- When `e : C ≌ α` is a categorical equivalence from a thin category `C` to some partial order `α`, the `thin_skeleton C` is order isomorphic to `α`. -/ noncomputable def equivalence.thin_skeleton_order_iso [quiver.is_thin C] (e : C ≌ α) : thin_skeleton C ≃o α := ((thin_skeleton.equivalence C).trans e).to_order_iso end end category_theory
3bc6942a83d9a14246313b44167223a5e2f01bfa
fffbc47930dc6615e66ece42324ce57a21d5b64b
/src/tactic/basic.lean
0841ac6a52f5169234d72c724fc43a09510191c1
[ "Apache-2.0" ]
permissive
skbaek/mathlib
3caae8ae413c66862293a95fd2fbada3647b1228
f25340175631cdc85ad768a262433f968d0d6450
refs/heads/master
1,588,130,123,636
1,558,287,609,000
1,558,287,609,000
160,935,713
0
0
Apache-2.0
1,544,271,146,000
1,544,271,146,000
null
UTF-8
Lean
false
false
342
lean
import tactic.alias tactic.cache tactic.converter.interactive tactic.core tactic.ext tactic.generalize_proofs tactic.interactive tactic.library_search tactic.mk_iff_of_inductive_prop tactic.rcases tactic.replacer tactic.restate_axiom tactic.rewrite tactic.simpa tactic.split_ifs tactic.squeeze tactic.where
b9c0a439cfd946c3bb45aadd3cd32a357d2dc9f0
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Init/Data/Repr.lean
5472c750182aa7efe5adec73f294e03f171c50db
[ "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
6,888
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.Data.Format.Basic import Init.Data.Int.Basic import Init.Data.Nat.Div import Init.Data.UInt import Init.Control.Id open Sum Subtype Nat open Std class Repr (α : Type u) where reprPrec : α → Nat → Format export Repr (reprPrec) abbrev repr [Repr α] (a : α) : Format := reprPrec a 0 abbrev reprStr [Repr α] (a : α) : String := reprPrec a 0 |>.pretty abbrev reprArg [Repr α] (a : α) : Format := reprPrec a max_prec /- Auxiliary class for marking types that should be considered atomic by `Repr` methods. We use it at `Repr (List α)` to decide whether `bracketFill` should be used or not. -/ class ReprAtom (α : Type u) -- This instance is needed because `id` is not reducible instance [Repr α] : Repr (id α) := inferInstanceAs (Repr α) instance [Repr α] : Repr (Id α) := inferInstanceAs (Repr α) instance : Repr Bool where reprPrec | true, _ => "true" | false, _ => "false" def Repr.addAppParen (f : Format) (prec : Nat) : Format := if prec >= max_prec then Format.paren f else f instance : Repr (Decidable p) where reprPrec | Decidable.isTrue _, prec => Repr.addAppParen "isTrue _" prec | Decidable.isFalse _, prec => Repr.addAppParen "isFalse _" prec instance : Repr PUnit.{u+1} where reprPrec _ _ := "PUnit.unit" instance [Repr α] : Repr (ULift.{v} α) where reprPrec v prec := Repr.addAppParen ("ULift.up " ++ reprArg v.1) prec instance : Repr Unit where reprPrec v _ := "()" instance [Repr α] : Repr (Option α) where reprPrec | none, _ => "none" | some a, prec => Repr.addAppParen ("some " ++ reprArg a) prec instance [Repr α] [Repr β] : Repr (Sum α β) where reprPrec | Sum.inl a, prec => Repr.addAppParen ("Sum.inl " ++ reprArg a) prec | Sum.inr b, prec => Repr.addAppParen ("Sum.inr " ++ reprArg b) prec class ReprTuple (α : Type u) where reprTuple : α → List Format → List Format export ReprTuple (reprTuple) instance [Repr α] : ReprTuple α where reprTuple a xs := repr a :: xs instance [Repr α] [ReprTuple β] : ReprTuple (α × β) where reprTuple | (a, b), xs => reprTuple b (repr a :: xs) instance [Repr α] [ReprTuple β] : Repr (α × β) where reprPrec | (a, b), _ => Format.bracket "(" (Format.joinSep (reprTuple b [repr a]).reverse ("," ++ Format.line)) ")" instance {β : α → Type v} [Repr α] [s : (x : α) → Repr (β x)] : Repr (Sigma β) where reprPrec | ⟨a, b⟩, _ => Format.bracket "⟨" (repr a ++ ", " ++ repr b) "⟩" instance {p : α → Prop} [Repr α] : Repr (Subtype p) where reprPrec s prec := reprPrec s.val prec namespace Nat def digitChar (n : Nat) : Char := if n = 0 then '0' else if n = 1 then '1' else if n = 2 then '2' else if n = 3 then '3' else if n = 4 then '4' else if n = 5 then '5' else if n = 6 then '6' else if n = 7 then '7' else if n = 8 then '8' else if n = 9 then '9' else if n = 0xa then 'a' else if n = 0xb then 'b' else if n = 0xc then 'c' else if n = 0xd then 'd' else if n = 0xe then 'e' else if n = 0xf then 'f' else '*' def toDigitsCore (base : Nat) : Nat → Nat → List Char → List Char | 0, n, ds => ds | fuel+1, n, ds => let d := digitChar <| n % base; let n' := n / base; if n' = 0 then d::ds else toDigitsCore base fuel n' (d::ds) def toDigits (base : Nat) (n : Nat) : List Char := toDigitsCore base (n+1) n [] protected def repr (n : Nat) : String := (toDigits 10 n).asString def superDigitChar (n : Nat) : Char := if n = 0 then '⁰' else if n = 1 then '¹' else if n = 2 then '²' else if n = 3 then '³' else if n = 4 then '⁴' else if n = 5 then '⁵' else if n = 6 then '⁶' else if n = 7 then '⁷' else if n = 8 then '⁸' else if n = 9 then '⁹' else '*' partial def toSuperDigitsAux : Nat → List Char → List Char | n, ds => let d := superDigitChar <| n % 10; let n' := n / 10; if n' = 0 then d::ds else toSuperDigitsAux n' (d::ds) def toSuperDigits (n : Nat) : List Char := toSuperDigitsAux n [] def toSuperscriptString (n : Nat) : String := (toSuperDigits n).asString end Nat instance : Repr Nat where reprPrec n _ := Nat.repr n def Int.repr : Int → String | ofNat m => Nat.repr m | negSucc m => "-" ++ Nat.repr (succ m) instance : Repr Int where reprPrec i _ := i.repr def hexDigitRepr (n : Nat) : String := String.singleton <| Nat.digitChar n def charToHex (c : Char) : String := let n := Char.toNat c; let d2 := n / 16; let d1 := n % 16; hexDigitRepr d2 ++ hexDigitRepr d1 def Char.quoteCore (c : Char) : String := if c = '\n' then "\\n" else if c = '\t' then "\\t" else if c = '\\' then "\\\\" else if c = '\"' then "\\\"" else if c.toNat <= 31 ∨ c = '\x7f' then "\\x" ++ charToHex c else String.singleton c def Char.quote (c : Char) : String := "'" ++ Char.quoteCore c ++ "'" instance : Repr Char where reprPrec c _ := c.quote protected def Char.repr (c : Char) : String := c.quote def String.quote (s : String) : String := if s.isEmpty then "\"\"" else s.foldl (fun s c => s ++ c.quoteCore) "\"" ++ "\"" instance : Repr String where reprPrec s _ := s.quote instance : Repr Substring where reprPrec s _ := Format.text <| String.quote s.toString ++ ".toSubstring" instance : Repr String.Iterator where reprPrec | ⟨s, pos⟩, prec => Repr.addAppParen ("String.Iterator.mk " ++ reprArg s ++ " " ++ reprArg pos) prec instance (n : Nat) : Repr (Fin n) where reprPrec f _ := repr f.val instance : Repr UInt8 where reprPrec n _ := repr n.toNat instance : Repr UInt16 where reprPrec n _ := repr n.toNat instance : Repr UInt32 where reprPrec n _ := repr n.toNat instance : Repr UInt64 where reprPrec n _ := repr n.toNat instance : Repr USize where reprPrec n _ := repr n.toNat instance [Repr α] : Repr (List α) where reprPrec a n := let _ : ToFormat α := ⟨repr⟩ match a, n with | [], _ => "[]" | as, _ => Format.bracket "[" (Format.joinSep as ("," ++ Format.line)) "]" instance [Repr α] [ReprAtom α] : Repr (List α) where reprPrec a n := let _ : ToFormat α := ⟨repr⟩ match a, n with | [], _ => "[]" | as, _ => Format.bracketFill "[" (Format.joinSep as ("," ++ Format.line)) "]" instance : ReprAtom Bool := ⟨⟩ instance : ReprAtom Nat := ⟨⟩ instance : ReprAtom Int := ⟨⟩ instance : ReprAtom Char := ⟨⟩ instance : ReprAtom String := ⟨⟩ instance : ReprAtom UInt8 := ⟨⟩ instance : ReprAtom UInt16 := ⟨⟩ instance : ReprAtom UInt32 := ⟨⟩ instance : ReprAtom UInt64 := ⟨⟩ instance : ReprAtom USize := ⟨⟩ deriving instance Repr for Lean.SourceInfo
fe4e17c168362ebe00f8856bda9d9d7c4bfff5a5
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/ring_theory/valuation/basic.lean
2b18aa0d9744122c86118cb6fd3498e6a6588a9a
[ "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
24,967
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Johan Commelin, Patrick Massot -/ import algebra.group_power import algebra.order.with_zero import algebra.punit_instances import ring_theory.ideal.operations /-! # The basics of valuation theory. The basic theory of valuations (non-archimedean norms) on a commutative ring, following T. Wedhorn's unpublished notes “Adic Spaces” ([wedhorn_adic]). The definition of a valuation we use here is Definition 1.22 of [wedhorn_adic]. A valuation on a ring `R` is a monoid homomorphism `v` to a linearly ordered commutative monoid with zero, that in addition satisfies the following two axioms: * `v 0 = 0` * `∀ x y, v (x + y) ≤ max (v x) (v y)` `valuation R Γ₀`is the type of valuations `R → Γ₀`, with a coercion to the underlying function. If `v` is a valuation from `R` to `Γ₀` then the induced group homomorphism `units(R) → Γ₀` is called `unit_map v`. The equivalence "relation" `is_equiv v₁ v₂ : Prop` defined in 1.27 of [wedhorn_adic] is not strictly speaking a relation, because `v₁ : valuation R Γ₁` and `v₂ : valuation R Γ₂` might not have the same type. This corresponds in ZFC to the set-theoretic difficulty that the class of all valuations (as `Γ₀` varies) on a ring `R` is not a set. The "relation" is however reflexive, symmetric and transitive in the obvious sense. Note that we use 1.27(iii) of [wedhorn_adic] as the definition of equivalence. The support of a valuation `v : valuation R Γ₀` is `supp v`. If `J` is an ideal of `R` with `h : J ⊆ supp v` then the induced valuation on R / J = `ideal.quotient J` is `on_quot v h`. ## Main definitions * `valuation R Γ₀`, the type of valuations on `R` with values in `Γ₀` * `valuation.is_equiv`, the heterogeneous equivalence relation on valuations * `valuation.supp`, the support of a valuation * `add_valuation R Γ₀`, the type of additive valuations on `R` with values in a linearly ordered additive commutative group with a top element, `Γ₀`. ## Implementation Details `add_valuation R Γ₀` is implemented as `valuation R (multiplicative (order_dual Γ₀))`. -/ open_locale classical big_operators noncomputable theory open function ideal variables {R : Type*} -- This will be a ring, assumed commutative in some sections section variables (R) (Γ₀ : Type*) [linear_ordered_comm_monoid_with_zero Γ₀] [ring R] /-- The type of `Γ₀`-valued valuations on `R`. -/ @[nolint has_inhabited_instance] structure valuation extends monoid_with_zero_hom R Γ₀ := (map_add' : ∀ x y, to_fun (x + y) ≤ max (to_fun x) (to_fun y)) /-- The `monoid_with_zero_hom` underlying a valuation. -/ add_decl_doc valuation.to_monoid_with_zero_hom end namespace valuation variables {Γ₀ : Type*} variables {Γ'₀ : Type*} variables {Γ''₀ : Type*} [linear_ordered_comm_monoid_with_zero Γ''₀] section basic variables (R) (Γ₀) [ring R] section monoid variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] /-- A valuation is coerced to the underlying function `R → Γ₀`. -/ instance : has_coe_to_fun (valuation R Γ₀) (λ _, R → Γ₀) := { coe := λ v, v.to_monoid_with_zero_hom.to_fun } /-- A valuation is coerced to a monoid morphism R → Γ₀. -/ instance : has_coe (valuation R Γ₀) (monoid_with_zero_hom R Γ₀) := ⟨valuation.to_monoid_with_zero_hom⟩ variables {R} {Γ₀} (v : valuation R Γ₀) {x y z : R} @[simp, norm_cast] lemma coe_coe : ((v : monoid_with_zero_hom R Γ₀) : R → Γ₀) = v := rfl @[simp] lemma map_zero : v 0 = 0 := v.map_zero' @[simp] lemma map_one : v 1 = 1 := v.map_one' @[simp] lemma map_mul : ∀ x y, v (x * y) = v x * v y := v.map_mul' @[simp] lemma map_add : ∀ x y, v (x + y) ≤ max (v x) (v y) := v.map_add' lemma map_add_le {x y g} (hx : v x ≤ g) (hy : v y ≤ g) : v (x + y) ≤ g := le_trans (v.map_add x y) $ max_le hx hy lemma map_add_lt {x y g} (hx : v x < g) (hy : v y < g) : v (x + y) < g := lt_of_le_of_lt (v.map_add x y) $ max_lt hx hy lemma map_sum_le {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hf : ∀ i ∈ s, v (f i) ≤ g) : v (∑ i in s, f i) ≤ g := begin refine finset.induction_on s (λ _, trans_rel_right (≤) v.map_zero zero_le') (λ a s has ih hf, _) hf, rw finset.forall_mem_insert at hf, rw finset.sum_insert has, exact v.map_add_le hf.1 (ih hf.2) end lemma map_sum_lt {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g ≠ 0) (hf : ∀ i ∈ s, v (f i) < g) : v (∑ i in s, f i) < g := begin refine finset.induction_on s (λ _, trans_rel_right (<) v.map_zero (zero_lt_iff.2 hg)) (λ a s has ih hf, _) hf, rw finset.forall_mem_insert at hf, rw finset.sum_insert has, exact v.map_add_lt hf.1 (ih hf.2) end lemma map_sum_lt' {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : 0 < g) (hf : ∀ i ∈ s, v (f i) < g) : v (∑ i in s, f i) < g := v.map_sum_lt (ne_of_gt hg) hf @[simp] lemma map_pow : ∀ x (n:ℕ), v (x^n) = (v x)^n := v.to_monoid_with_zero_hom.to_monoid_hom.map_pow @[ext] lemma ext {v₁ v₂ : valuation R Γ₀} (h : ∀ r, v₁ r = v₂ r) : v₁ = v₂ := by { rcases v₁ with ⟨⟨⟩⟩, rcases v₂ with ⟨⟨⟩⟩, congr, funext r, exact h r } lemma ext_iff {v₁ v₂ : valuation R Γ₀} : v₁ = v₂ ↔ ∀ r, v₁ r = v₂ r := ⟨λ h r, congr_arg _ h, ext⟩ -- The following definition is not an instance, because we have more than one `v` on a given `R`. -- In addition, type class inference would not be able to infer `v`. /-- A valuation gives a preorder on the underlying ring. -/ def to_preorder : preorder R := preorder.lift v /-- If `v` is a valuation on a division ring then `v(x) = 0` iff `x = 0`. -/ @[simp] lemma zero_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x = 0 ↔ x = 0 := v.to_monoid_with_zero_hom.map_eq_zero lemma ne_zero_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x ≠ 0 ↔ x ≠ 0 := v.to_monoid_with_zero_hom.map_ne_zero theorem unit_map_eq (u : units R) : (units.map (v : R →* Γ₀) u : Γ₀) = v u := rfl /-- A ring homomorphism `S → R` induces a map `valuation R Γ₀ → valuation S Γ₀`. -/ def comap {S : Type*} [ring S] (f : S →+* R) (v : valuation R Γ₀) : valuation S Γ₀ := { to_fun := v ∘ f, map_add' := λ x y, by simp only [comp_app, map_add, f.map_add], .. v.to_monoid_with_zero_hom.comp f.to_monoid_with_zero_hom, } @[simp] lemma comap_id : v.comap (ring_hom.id R) = v := ext $ λ r, rfl lemma comap_comp {S₁ : Type*} {S₂ : Type*} [ring S₁] [ring S₂] (f : S₁ →+* S₂) (g : S₂ →+* R) : v.comap (g.comp f) = (v.comap g).comap f := ext $ λ r, rfl /-- A `≤`-preserving group homomorphism `Γ₀ → Γ'₀` induces a map `valuation R Γ₀ → valuation R Γ'₀`. -/ def map (f : monoid_with_zero_hom Γ₀ Γ'₀) (hf : monotone f) (v : valuation R Γ₀) : valuation R Γ'₀ := { to_fun := f ∘ v, map_add' := λ r s, calc f (v (r + s)) ≤ f (max (v r) (v s)) : hf (v.map_add r s) ... = max (f (v r)) (f (v s)) : hf.map_max, .. monoid_with_zero_hom.comp f v.to_monoid_with_zero_hom } /-- Two valuations on `R` are defined to be equivalent if they induce the same preorder on `R`. -/ def is_equiv (v₁ : valuation R Γ₀) (v₂ : valuation R Γ'₀) : Prop := ∀ r s, v₁ r ≤ v₁ s ↔ v₂ r ≤ v₂ s end monoid section group variables [linear_ordered_comm_group_with_zero Γ₀] {R} {Γ₀} (v : valuation R Γ₀) {x y z : R} @[simp] lemma map_inv {K : Type*} [division_ring K] (v : valuation K Γ₀) {x : K} : v x⁻¹ = (v x)⁻¹ := v.to_monoid_with_zero_hom.map_inv x lemma map_units_inv (x : units R) : v (x⁻¹ : units R) = (v x)⁻¹ := v.to_monoid_with_zero_hom.to_monoid_hom.map_units_inv x @[simp] lemma map_neg (x : R) : v (-x) = v x := v.to_monoid_with_zero_hom.to_monoid_hom.map_neg x lemma map_sub_swap (x y : R) : v (x - y) = v (y - x) := v.to_monoid_with_zero_hom.to_monoid_hom.map_sub_swap x y lemma map_sub (x y : R) : v (x - y) ≤ max (v x) (v y) := calc v (x - y) = v (x + -y) : by rw [sub_eq_add_neg] ... ≤ max (v x) (v $ -y) : v.map_add _ _ ... = max (v x) (v y) : by rw map_neg lemma map_sub_le {x y g} (hx : v x ≤ g) (hy : v y ≤ g) : v (x - y) ≤ g := begin rw sub_eq_add_neg, exact v.map_add_le hx (le_trans (le_of_eq (v.map_neg y)) hy) end lemma map_add_of_distinct_val (h : v x ≠ v y) : v (x + y) = max (v x) (v y) := begin suffices : ¬v (x + y) < max (v x) (v y), from or_iff_not_imp_right.1 (le_iff_eq_or_lt.1 (v.map_add x y)) this, intro h', wlog vyx : v y < v x using x y, { apply lt_or_gt_of_ne h.symm }, { rw max_eq_left_of_lt vyx at h', apply lt_irrefl (v x), calc v x = v ((x+y) - y) : by simp ... ≤ max (v $ x + y) (v y) : map_sub _ _ _ ... < v x : max_lt h' vyx }, { apply this h.symm, rwa [add_comm, max_comm] at h' } end lemma map_eq_of_sub_lt (h : v (y - x) < v x) : v y = v x := begin have := valuation.map_add_of_distinct_val v (ne_of_gt h).symm, rw max_eq_right (le_of_lt h) at this, simpa using this end /-- The subgroup of elements whose valuation is less than a certain unit.-/ def lt_add_subgroup (v : valuation R Γ₀) (γ : units Γ₀) : add_subgroup R := { carrier := {x | v x < γ}, zero_mem' := by { have h := units.ne_zero γ, contrapose! h, simpa using h }, add_mem' := λ x y x_in y_in, lt_of_le_of_lt (v.map_add x y) (max_lt x_in y_in), neg_mem' := λ x x_in, by rwa [set.mem_set_of_eq, map_neg] } end group end basic -- end of section namespace is_equiv variables [ring R] variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] variables {v : valuation R Γ₀} variables {v₁ : valuation R Γ₀} {v₂ : valuation R Γ'₀} {v₃ : valuation R Γ''₀} @[refl] lemma refl : v.is_equiv v := λ _ _, iff.refl _ @[symm] lemma symm (h : v₁.is_equiv v₂) : v₂.is_equiv v₁ := λ _ _, iff.symm (h _ _) @[trans] lemma trans (h₁₂ : v₁.is_equiv v₂) (h₂₃ : v₂.is_equiv v₃) : v₁.is_equiv v₃ := λ _ _, iff.trans (h₁₂ _ _) (h₂₃ _ _) lemma of_eq {v' : valuation R Γ₀} (h : v = v') : v.is_equiv v' := by { subst h } lemma map {v' : valuation R Γ₀} (f : monoid_with_zero_hom Γ₀ Γ'₀) (hf : monotone f) (inf : injective f) (h : v.is_equiv v') : (v.map f hf).is_equiv (v'.map f hf) := let H : strict_mono f := hf.strict_mono_of_injective inf in λ r s, calc f (v r) ≤ f (v s) ↔ v r ≤ v s : by rw H.le_iff_le ... ↔ v' r ≤ v' s : h r s ... ↔ f (v' r) ≤ f (v' s) : by rw H.le_iff_le /-- `comap` preserves equivalence. -/ lemma comap {S : Type*} [ring S] (f : S →+* R) (h : v₁.is_equiv v₂) : (v₁.comap f).is_equiv (v₂.comap f) := λ r s, h (f r) (f s) lemma val_eq (h : v₁.is_equiv v₂) {r s : R} : v₁ r = v₁ s ↔ v₂ r = v₂ s := by simpa only [le_antisymm_iff] using and_congr (h r s) (h s r) lemma ne_zero (h : v₁.is_equiv v₂) {r : R} : v₁ r ≠ 0 ↔ v₂ r ≠ 0 := begin have : v₁ r ≠ v₁ 0 ↔ v₂ r ≠ v₂ 0 := not_iff_not_of_iff h.val_eq, rwa [v₁.map_zero, v₂.map_zero] at this, end end is_equiv -- end of namespace section lemma is_equiv_of_map_strict_mono [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] [ring R] {v : valuation R Γ₀} (f : monoid_with_zero_hom Γ₀ Γ'₀) (H : strict_mono f) : is_equiv (v.map f (H.monotone)) v := λ x y, ⟨H.le_iff_le.mp, λ h, H.monotone h⟩ lemma is_equiv_of_val_le_one [linear_ordered_comm_group_with_zero Γ₀] [linear_ordered_comm_group_with_zero Γ'₀] {K : Type*} [division_ring K] (v : valuation K Γ₀) (v' : valuation K Γ'₀) (h : ∀ {x:K}, v x ≤ 1 ↔ v' x ≤ 1) : v.is_equiv v' := begin intros x y, by_cases hy : y = 0, { simp [hy, zero_iff], }, rw show y = 1 * y, by rw one_mul, rw [← (inv_mul_cancel_right₀ hy x)], iterate 2 {rw [v.map_mul _ y, v'.map_mul _ y]}, rw [v.map_one, v'.map_one], split; intro H, { apply mul_le_mul_right', replace hy := v.ne_zero_iff.mpr hy, replace H := le_of_le_mul_right hy H, rwa h at H, }, { apply mul_le_mul_right', replace hy := v'.ne_zero_iff.mpr hy, replace H := le_of_le_mul_right hy H, rwa h, }, end end section supp variables [comm_ring R] variables [linear_ordered_comm_monoid_with_zero Γ₀] [linear_ordered_comm_monoid_with_zero Γ'₀] variables (v : valuation R Γ₀) /-- The support of a valuation `v : R → Γ₀` is the ideal of `R` where `v` vanishes. -/ def supp : ideal R := { carrier := {x | v x = 0}, zero_mem' := map_zero v, add_mem' := λ x y hx hy, le_zero_iff.mp $ calc v (x + y) ≤ max (v x) (v y) : v.map_add x y ... ≤ 0 : max_le (le_zero_iff.mpr hx) (le_zero_iff.mpr hy), smul_mem' := λ c x hx, calc v (c * x) = v c * v x : map_mul v c x ... = v c * 0 : congr_arg _ hx ... = 0 : mul_zero _ } @[simp] lemma mem_supp_iff (x : R) : x ∈ supp v ↔ v x = 0 := iff.rfl -- @[simp] lemma mem_supp_iff' (x : R) : x ∈ (supp v : set R) ↔ v x = 0 := iff.rfl /-- The support of a valuation is a prime ideal. -/ instance [nontrivial Γ₀] [no_zero_divisors Γ₀] : ideal.is_prime (supp v) := ⟨λ (h : v.supp = ⊤), one_ne_zero $ show (1 : Γ₀) = 0, from calc 1 = v 1 : v.map_one.symm ... = 0 : show (1:R) ∈ supp v, by { rw h, trivial }, λ x y hxy, begin show v x = 0 ∨ v y = 0, change v (x * y) = 0 at hxy, rw [v.map_mul x y] at hxy, exact eq_zero_or_eq_zero_of_mul_eq_zero hxy end⟩ lemma map_add_supp (a : R) {s : R} (h : s ∈ supp v) : v (a + s) = v a := begin have aux : ∀ a s, v s = 0 → v (a + s) ≤ v a, { intros a' s' h', refine le_trans (v.map_add a' s') (max_le (le_refl _) _), simp [h'], }, apply le_antisymm (aux a s h), calc v a = v (a + s + -s) : by simp ... ≤ v (a + s) : aux (a + s) (-s) (by rwa ←ideal.neg_mem_iff at h) end /-- If `hJ : J ⊆ supp v` then `on_quot_val hJ` is the induced function on R/J as a function. Note: it's just the function; the valuation is `on_quot hJ`. -/ def on_quot_val {J : ideal R} (hJ : J ≤ supp v) : J.quotient → Γ₀ := λ q, quotient.lift_on' q v $ λ a b h, calc v a = v (b + (a - b)) : by simp ... = v b : v.map_add_supp b (hJ h) /-- The extension of valuation v on R to valuation on R/J if J ⊆ supp v -/ def on_quot {J : ideal R} (hJ : J ≤ supp v) : valuation J.quotient Γ₀ := { to_fun := v.on_quot_val hJ, map_zero' := v.map_zero, map_one' := v.map_one, map_mul' := λ xbar ybar, quotient.ind₂' v.map_mul xbar ybar, map_add' := λ xbar ybar, quotient.ind₂' v.map_add xbar ybar } @[simp] lemma on_quot_comap_eq {J : ideal R} (hJ : J ≤ supp v) : (v.on_quot hJ).comap (ideal.quotient.mk J) = v := ext $ λ r, begin refine @quotient.lift_on_mk _ _ (J.quotient_rel) v (λ a b h, _) _, calc v a = v (b + (a - b)) : by simp ... = v b : v.map_add_supp b (hJ h) end lemma comap_supp {S : Type*} [comm_ring S] (f : S →+* R) : supp (v.comap f) = ideal.comap f v.supp := ideal.ext $ λ x, begin rw [mem_supp_iff, ideal.mem_comap, mem_supp_iff], refl, end lemma self_le_supp_comap (J : ideal R) (v : valuation (quotient J) Γ₀) : J ≤ (v.comap (ideal.quotient.mk J)).supp := by { rw [comap_supp, ← ideal.map_le_iff_le_comap], simp } @[simp] lemma comap_on_quot_eq (J : ideal R) (v : valuation J.quotient Γ₀) : (v.comap (ideal.quotient.mk J)).on_quot (v.self_le_supp_comap J) = v := ext $ by { rintro ⟨x⟩, refl } /-- The quotient valuation on R/J has support supp(v)/J if J ⊆ supp v. -/ lemma supp_quot {J : ideal R} (hJ : J ≤ supp v) : supp (v.on_quot hJ) = (supp v).map (ideal.quotient.mk J) := begin apply le_antisymm, { rintro ⟨x⟩ hx, apply ideal.subset_span, exact ⟨x, hx, rfl⟩ }, { rw ideal.map_le_iff_le_comap, intros x hx, exact hx } end lemma supp_quot_supp : supp (v.on_quot (le_refl _)) = 0 := by { rw supp_quot, exact ideal.map_quotient_self _ } end supp -- end of section end valuation section add_monoid variables (R) [ring R] (Γ₀ : Type*) [linear_ordered_add_comm_monoid_with_top Γ₀] /-- The type of `Γ₀`-valued additive valuations on `R`. -/ @[nolint has_inhabited_instance] def add_valuation := valuation R (multiplicative (order_dual Γ₀)) end add_monoid namespace add_valuation variables {Γ₀ : Type*} {Γ'₀ : Type*} section basic section monoid variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀] variables (R) (Γ₀) [ring R] /-- A valuation is coerced to the underlying function `R → Γ₀`. -/ instance : has_coe_to_fun (add_valuation R Γ₀) (λ _, R → Γ₀) := { coe := λ v, v.to_monoid_with_zero_hom.to_fun } variables {R} {Γ₀} (v : add_valuation R Γ₀) {x y z : R} section variables (f : R → Γ₀) (h0 : f 0 = ⊤) (h1 : f 1 = 0) variables (hadd : ∀ x y, min (f x) (f y) ≤ f (x + y)) (hmul : ∀ x y, f (x * y) = f x + f y) /-- An alternate constructor of `add_valuation`, that doesn't reference `multiplicative (order_dual Γ₀)` -/ def of : add_valuation R Γ₀ := { to_fun := f, map_one' := h1, map_zero' := h0, map_add' := hadd, map_mul' := hmul } variables {h0} {h1} {hadd} {hmul} {r : R} @[simp] theorem of_apply : (of f h0 h1 hadd hmul) r = f r := rfl end @[simp] lemma map_zero : v 0 = ⊤ := v.map_zero @[simp] lemma map_one : v 1 = 0 := v.map_one @[simp] lemma map_mul : ∀ x y, v (x * y) = v x + v y := v.map_mul @[simp] lemma map_add : ∀ x y, min (v x) (v y) ≤ v (x + y) := v.map_add lemma map_le_add {x y g} (hx : g ≤ v x) (hy : g ≤ v y) : g ≤ v (x + y) := v.map_add_le hx hy lemma map_lt_add {x y g} (hx : g < v x) (hy : g < v y) : g < v (x + y) := v.map_add_lt hx hy lemma map_le_sum {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hf : ∀ i ∈ s, g ≤ v (f i)) : g ≤ v (∑ i in s, f i) := v.map_sum_le hf lemma map_lt_sum {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g ≠ ⊤) (hf : ∀ i ∈ s, g < v (f i)) : g < v (∑ i in s, f i) := v.map_sum_lt hg hf lemma map_lt_sum' {ι : Type*} {s : finset ι} {f : ι → R} {g : Γ₀} (hg : g < ⊤) (hf : ∀ i ∈ s, g < v (f i)) : g < v (∑ i in s, f i) := v.map_sum_lt' hg hf @[simp] lemma map_pow : ∀ x (n:ℕ), v (x^n) = n • (v x) := v.map_pow @[ext] lemma ext {v₁ v₂ : add_valuation R Γ₀} (h : ∀ r, v₁ r = v₂ r) : v₁ = v₂ := valuation.ext h lemma ext_iff {v₁ v₂ : add_valuation R Γ₀} : v₁ = v₂ ↔ ∀ r, v₁ r = v₂ r := valuation.ext_iff -- The following definition is not an instance, because we have more than one `v` on a given `R`. -- In addition, type class inference would not be able to infer `v`. /-- A valuation gives a preorder on the underlying ring. -/ def to_preorder : preorder R := preorder.lift v /-- If `v` is an additive valuation on a division ring then `v(x) = ⊤` iff `x = 0`. -/ @[simp] lemma top_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : add_valuation K Γ₀) {x : K} : v x = ⊤ ↔ x = 0 := v.zero_iff lemma ne_top_iff [nontrivial Γ₀] {K : Type*} [division_ring K] (v : add_valuation K Γ₀) {x : K} : v x ≠ ⊤ ↔ x ≠ 0 := v.ne_zero_iff /-- A ring homomorphism `S → R` induces a map `add_valuation R Γ₀ → add_valuation S Γ₀`. -/ def comap {S : Type*} [ring S] (f : S →+* R) (v : add_valuation R Γ₀) : add_valuation S Γ₀ := v.comap f @[simp] lemma comap_id : v.comap (ring_hom.id R) = v := v.comap_id lemma comap_comp {S₁ : Type*} {S₂ : Type*} [ring S₁] [ring S₂] (f : S₁ →+* S₂) (g : S₂ →+* R) : v.comap (g.comp f) = (v.comap g).comap f := v.comap_comp f g /-- A `≤`-preserving, `⊤`-preserving group homomorphism `Γ₀ → Γ'₀` induces a map `add_valuation R Γ₀ → add_valuation R Γ'₀`. -/ def map (f : Γ₀ →+ Γ'₀) (ht : f ⊤ = ⊤) (hf : monotone f) (v : add_valuation R Γ₀) : add_valuation R Γ'₀ := v.map { to_fun := f, map_mul' := f.map_add, map_one' := f.map_zero, map_zero' := ht } (λ x y h, hf h) /-- Two additive valuations on `R` are defined to be equivalent if they induce the same preorder on `R`. -/ def is_equiv (v₁ : add_valuation R Γ₀) (v₂ : add_valuation R Γ'₀) : Prop := v₁.is_equiv v₂ end monoid section group variables [linear_ordered_add_comm_group_with_top Γ₀] [ring R] (v : add_valuation R Γ₀) {x y z : R} @[simp] lemma map_inv {K : Type*} [division_ring K] (v : add_valuation K Γ₀) {x : K} : v x⁻¹ = - (v x) := v.map_inv lemma map_units_inv (x : units R) : v (x⁻¹ : units R) = - (v x) := v.map_units_inv x @[simp] lemma map_neg (x : R) : v (-x) = v x := v.map_neg x lemma map_sub_swap (x y : R) : v (x - y) = v (y - x) := v.map_sub_swap x y lemma map_sub (x y : R) : min (v x) (v y) ≤ v (x - y) := v.map_sub x y lemma map_le_sub {x y g} (hx : g ≤ v x) (hy : g ≤ v y) : g ≤ v (x - y) := v.map_sub_le hx hy lemma map_add_of_distinct_val (h : v x ≠ v y) : v (x + y) = min (v x) (v y) := v.map_add_of_distinct_val h lemma map_eq_of_lt_sub (h : v x < v (y - x)) : v y = v x := v.map_eq_of_sub_lt h end group end basic namespace is_equiv variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀] variables [ring R] variables {Γ''₀ : Type*} [linear_ordered_add_comm_monoid_with_top Γ''₀] variables {v : add_valuation R Γ₀} variables {v₁ : add_valuation R Γ₀} {v₂ : add_valuation R Γ'₀} {v₃ : add_valuation R Γ''₀} @[refl] lemma refl : v.is_equiv v := valuation.is_equiv.refl @[symm] lemma symm (h : v₁.is_equiv v₂) : v₂.is_equiv v₁ := h.symm @[trans] lemma trans (h₁₂ : v₁.is_equiv v₂) (h₂₃ : v₂.is_equiv v₃) : v₁.is_equiv v₃ := h₁₂.trans h₂₃ lemma of_eq {v' : add_valuation R Γ₀} (h : v = v') : v.is_equiv v' := valuation.is_equiv.of_eq h lemma map {v' : add_valuation R Γ₀} (f : Γ₀ →+ Γ'₀) (ht : f ⊤ = ⊤) (hf : monotone f) (inf : injective f) (h : v.is_equiv v') : (v.map f ht hf).is_equiv (v'.map f ht hf) := h.map { to_fun := f, map_mul' := f.map_add, map_one' := f.map_zero, map_zero' := ht } (λ x y h, hf h) inf /-- `comap` preserves equivalence. -/ lemma comap {S : Type*} [ring S] (f : S →+* R) (h : v₁.is_equiv v₂) : (v₁.comap f).is_equiv (v₂.comap f) := h.comap f lemma val_eq (h : v₁.is_equiv v₂) {r s : R} : v₁ r = v₁ s ↔ v₂ r = v₂ s := h.val_eq lemma ne_top (h : v₁.is_equiv v₂) {r : R} : v₁ r ≠ ⊤ ↔ v₂ r ≠ ⊤ := h.ne_zero end is_equiv section supp variables [linear_ordered_add_comm_monoid_with_top Γ₀] [linear_ordered_add_comm_monoid_with_top Γ'₀] variables [comm_ring R] variables (v : add_valuation R Γ₀) /-- The support of an additive valuation `v : R → Γ₀` is the ideal of `R` where `v x = ⊤` -/ def supp : ideal R := v.supp @[simp] lemma mem_supp_iff (x : R) : x ∈ supp v ↔ v x = ⊤ := v.mem_supp_iff x lemma map_add_supp (a : R) {s : R} (h : s ∈ supp v) : v (a + s) = v a := v.map_add_supp a h /-- If `hJ : J ⊆ supp v` then `on_quot_val hJ` is the induced function on R/J as a function. Note: it's just the function; the valuation is `on_quot hJ`. -/ def on_quot_val {J : ideal R} (hJ : J ≤ supp v) : J.quotient → Γ₀ := v.on_quot_val hJ /-- The extension of valuation v on R to valuation on R/J if J ⊆ supp v -/ def on_quot {J : ideal R} (hJ : J ≤ supp v) : add_valuation J.quotient Γ₀ := v.on_quot hJ @[simp] lemma on_quot_comap_eq {J : ideal R} (hJ : J ≤ supp v) : (v.on_quot hJ).comap (ideal.quotient.mk J) = v := v.on_quot_comap_eq hJ lemma comap_supp {S : Type*} [comm_ring S] (f : S →+* R) : supp (v.comap f) = ideal.comap f v.supp := v.comap_supp f lemma self_le_supp_comap (J : ideal R) (v : add_valuation (quotient J) Γ₀) : J ≤ (v.comap (ideal.quotient.mk J)).supp := v.self_le_supp_comap J @[simp] lemma comap_on_quot_eq (J : ideal R) (v : add_valuation J.quotient Γ₀) : (v.comap (ideal.quotient.mk J)).on_quot (v.self_le_supp_comap J) = v := v.comap_on_quot_eq J /-- The quotient valuation on R/J has support supp(v)/J if J ⊆ supp v. -/ lemma supp_quot {J : ideal R} (hJ : J ≤ supp v) : supp (v.on_quot hJ) = (supp v).map (ideal.quotient.mk J) := v.supp_quot hJ lemma supp_quot_supp : supp (v.on_quot (le_refl _)) = 0 := v.supp_quot_supp end supp -- end of section attribute [irreducible] add_valuation end add_valuation
14ab8c95c06fef5d133c99a25322e1224dc043b8
572fb32b6f5b7c2bf26921ffa2abea054cce881a
/src/week_1/Part_C_functions.lean
56ca6067155ca1c669cf5d33ac4fb805d680b7ef
[ "Apache-2.0" ]
permissive
kgeorgiy/lean-formalising-mathematics
2deb30756d5a54bee1cfa64873e86f641c59c7dc
73429a8ded68f641c896b6ba9342450d4d3ae50f
refs/heads/master
1,683,029,640,682
1,621,403,041,000
1,621,403,041,000
367,790,347
0
0
null
null
null
null
UTF-8
Lean
false
false
3,208
lean
import tactic -- injective and surjective functions are already in Lean. -- They are called `function.injective` and `function.surjective`. -- It gets a bit boring typing `function.` a lot so we start -- by opening the `function` namespace open function -- We now move into the `xena` namespace namespace xena -- let X, Y, Z be "types", i.e. sets, and let `f : X → Y` and `g : Y → Z` -- be functions variables {X Y Z : Type} {f : X → Y} {g : Y → Z} -- let a,b,x be elements of X, let y be an element of Y and let z be an -- element of Z variables (a b x : X) (y : Y) (z : Z) /-! # Injective functions -/ -- let's start by checking the definition of injective is -- what we think it is. lemma injective_def : injective f ↔ ∀ a b : X, f a = f b → a = b := begin -- true by definition refl end -- You can now `rw injective_def` to change `injective f` into its definition. -- The identity function id : X → X is defined by id(x) = x. Let's check this lemma id_def : id x = x := begin -- true by definition refl end -- you can now `rw id_def` to change `id x` into `x` /-- The identity function is injective -/ lemma injective_id : injective (id : X → X) := λ a b h, h -- function composition g ∘ f is satisfies (g ∘ f) (x) = g(f(x)). This -- is true by definition. Let's check this lemma comp_def : (g ∘ f) x = g (f x) := rfl /-- Composite of two injective functions is injective -/ lemma injective_comp (hf : injective f) (hg : injective g) : injective (g ∘ f) := begin -- you could start with `rw injective_def at *` if you like. -- In some sense it doesn't do anything, but it might make you happier. rw injective_def at *, exact λ a b ha, hf _ _ (hg _ _ ha), end /-! ### Surjective functions -/ -- Let's start by checking the definition of surjectivity is what we think it is lemma surjective_def : surjective f ↔ ∀ y : Y, ∃ x : X, f x = y := by refl /-- The identity function is surjective -/ lemma surjective_id : surjective (id : X → X) := λ y, ⟨y, rfl⟩ -- If you started with `rw surjective_def` -- try deleting it. -- Probably your proof still works! This is because -- `surjective_def` is true *by definition*. The proof is `refl`. -- For this next one, the `have` tactic is helpful. /-- Composite of two surjective functions is surjective -/ lemma surjective_comp (hf : surjective f) (hg : surjective g) : surjective (g ∘ f) := begin intro y, rcases hg y with ⟨z, rfl⟩, rcases hf z with ⟨x, rfl⟩, exact ⟨x, rfl⟩, end /-! ### Bijective functions In Lean a function is defined to be bijective if it is injective and surjective. Let's check this. -/ lemma bijective_def : bijective f ↔ injective f ∧ surjective f := begin -- true by definition refl end -- You can now use the lemmas you've proved already to make these -- proofs very short. /-- The identity function is bijective. -/ lemma bijective_id : bijective (id : X → X) := ⟨injective_id, surjective_id⟩ /-- A composite of bijective functions is bijective. -/ lemma bijective_comp (hf : bijective f) (hg : bijective g) : bijective (g ∘ f) := ⟨injective_comp hf.1 hg.1, surjective_comp hf.2 hg.2⟩ end xena
91b1d8e525959b446c842c27dc2dd66bc2ca5114
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/inliner_loop.lean
d95128c84c09015aae9db09eb74441bee73bfe5f
[ "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
140
lean
unsafe inductive t | mk : (t → t) → t unsafe def loop' : t → t | t.mk f => f (t.mk f) unsafe def loop : t := loop' (t.mk loop')
4c90a71b195d8dac4393c4a2a312902272ae0b61
a7eef317ddec01b9fc6cfbb876fe7ac00f205ac7
/src/ring_theory/noetherian.lean
b0f1a334e3b2c5ca8aa442ebd58a6ebe3acd5de4
[ "Apache-2.0" ]
permissive
kmill/mathlib
ea5a007b67ae4e9e18dd50d31d8aa60f650425ee
1a419a9fea7b959317eddd556e1bb9639f4dcc05
refs/heads/master
1,668,578,197,719
1,593,629,163,000
1,593,629,163,000
276,482,939
0
0
null
1,593,637,960,000
1,593,637,959,000
null
UTF-8
Lean
false
false
23,074
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import ring_theory.ideal_operations import linear_algebra.basis /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators namespace submodule variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ideal.quotient.mk_one] at hr1 hc1 ⊢, rw [ideal.quotient.mk_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_group P] [module R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨prod.inl '' tb ∪ prod.inr '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ variable (f) /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [ring R] [add_comm_group M] [module R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian R (Π i : (↑s : set ι), M i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext ⟨⟩, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function @[nolint ge_or_gt] -- see Note [nolint_ge] theorem is_noetherian_iff_well_founded {R M} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := ⟨λ h, begin apply order_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let Q := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian Q) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set M), { rw [← submodule.coe_supr_of_directed N _], { show t ⊆ Q, rw ← h₂, apply submodule.subset_span }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : Q ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ P ≤ N, ∃ s, finite s ∧ P ⊔ submodule.span R s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ P, h.induction P _, intros P IH PN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ P, { cases le_antisymm PN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬P ⊔ submodule.span R {x} ≤ P, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (P ⊔ submodule.span R {x}) ⟨@le_sup_left _ _ P _, this⟩ (sup_le PN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, hs.insert x, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {R M} [comm_ring R] [nonzero R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, order_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff zero_ne_one hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ @[class] def is_noetherian_ring (R) [ring R] : Prop := is_noetherian R R instance is_noetherian_ring.to_is_noetherian {R : Type*} [ring R] : ∀ [is_noetherian_ring R], is_noetherian R R := id @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one R h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.map_subtype.lt_order_embedding N)) h end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.comap_mkq.lt_order_embedding N)) h end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.semimodule _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x.1, subtype.eq _⟩, change ∑ i in s.attach, l i.1 • i.1 = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin unfold is_noetherian_ring at H ⊢, rw is_noetherian_iff_well_founded at H ⊢, convert order_embedding.well_founded (order_embedding.rsymm (ideal.lt_order_embedding_of_surjective f hf)) H end instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace is_noetherian_ring variables {R : Type*} [integral_domain R] [is_noetherian_ring R] open associates nat local attribute [elab_as_eliminator] well_founded.fix lemma well_founded_dvd_not_unit : well_founded (λ a b : R, a ≠ 0 ∧ ∃ x, ¬is_unit x ∧ b = a * x) := by simp only [ideal.span_singleton_lt_span_singleton.symm]; exact inv_image.wf (λ a, ideal.span ({a} : set R)) (well_founded_submodule_gt _ _) lemma exists_irreducible_factor {a : R} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_refl _⟩) (well_founded.fix well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, dvd.trans hi.2 (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma irreducible_induction_on {P : R → Prop} (a : R) (h0 : P 0) (hu : ∀ u : R, is_unit u → P u) (hi : ∀ a i : R, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : R) : a ≠ 0 → ∃f : multiset R, (∀b ∈ f, irreducible b) ∧ associated a f.prod := is_noetherian_ring.irreducible_induction_on a (λ h, (h rfl).elim) (λ u hu _, ⟨0, by simp [associated_one_iff_is_unit, hu]⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i::s, ⟨by clear _let_match; finish, by rw multiset.prod_cons; exact associated_mul_mul (by refl) hs.2⟩⟩) end is_noetherian_ring namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) local attribute [instance] set.pointwise_mul_semiring theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, set.pointwise_mul_finite hfm hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
058a852218619a28d17b6d6f9e32932f65b08cae
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/instances/real_vector_space.lean
82fa5979dff9a44c7b63b2a9a176199e72db6015
[ "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
2,412
lean
/- Copyright (c) 2020 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.algebra.module.basic import topology.instances.real /-! # Continuous additive maps are `ℝ`-linear In this file we prove that a continuous map `f : E →+ F` between two topological vector spaces over `ℝ` is `ℝ`-linear -/ variables {E : Type*} [add_comm_group E] [module ℝ E] [topological_space E] [has_continuous_smul ℝ E] {F : Type*} [add_comm_group F] [module ℝ F] [topological_space F] [has_continuous_smul ℝ F] [t2_space F] namespace add_monoid_hom /-- A continuous additive map between two vector spaces over `ℝ` is `ℝ`-linear. -/ lemma map_real_smul (f : E →+ F) (hf : continuous f) (c : ℝ) (x : E) : f (c • x) = c • f x := suffices (λ c : ℝ, f (c • x)) = λ c : ℝ, c • f x, from _root_.congr_fun this c, rat.dense_embedding_coe_real.dense.equalizer (hf.comp $ continuous_id.smul continuous_const) (continuous_id.smul continuous_const) (funext $ λ r, f.map_rat_cast_smul ℝ ℝ r x) /-- Reinterpret a continuous additive homomorphism between two real vector spaces as a continuous real-linear map. -/ def to_real_linear_map (f : E →+ F) (hf : continuous f) : E →L[ℝ] F := ⟨{ to_fun := f, map_add' := f.map_add, map_smul' := f.map_real_smul hf }, hf⟩ @[simp] lemma coe_to_real_linear_map (f : E →+ F) (hf : continuous f) : ⇑(f.to_real_linear_map hf) = f := rfl end add_monoid_hom /-- Reinterpret a continuous additive equivalence between two real vector spaces as a continuous real-linear map. -/ def add_equiv.to_real_linear_equiv (e : E ≃+ F) (h₁ : continuous e) (h₂ : continuous e.symm) : E ≃L[ℝ] F := { .. e, .. e.to_add_monoid_hom.to_real_linear_map h₁ } /-- A topological group carries at most one structure of a topological `ℝ`-module, so for any topological `ℝ`-algebra `A` (e.g. `A = ℂ`) and any topological group that is both a topological `ℝ`-module and a topological `A`-module, these structures agree. -/ @[priority 900] instance real.is_scalar_tower [t2_space E] {A : Type*} [topological_space A] [ring A] [algebra ℝ A] [module A E] [has_continuous_smul ℝ A] [has_continuous_smul A E] : is_scalar_tower ℝ A E := ⟨λ r x y, ((smul_add_hom A E).flip y).map_real_smul (continuous_id.smul continuous_const) r x⟩
310637cfaec0c3bf2d0d33f05dfa8199e0fae063
b2fe74b11b57d362c13326bc5651244f111fa6f4
/src/linear_algebra/affine_space/affine_subspace.lean
076914ca31013d490e4a4411c8d53f8becd7a984
[ "Apache-2.0" ]
permissive
midfield/mathlib
c4db5fa898b5ac8f2f80ae0d00c95eb6f745f4c7
775edc615ecec631d65b6180dbcc7bc26c3abc26
refs/heads/master
1,675,330,551,921
1,608,304,514,000
1,608,304,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
44,314
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import linear_algebra.affine_space.basic import linear_algebra.tensor_product import data.set.intervals.unordered_interval /-! # Affine spaces This file defines affine subspaces (over modules) and the affine span of a set of points. ## Main definitions * `affine_subspace k P` is the type of affine subspaces. Unlike affine spaces, affine subspaces are allowed to be empty, and lemmas that do not apply to empty affine subspaces have `nonempty` hypotheses. There is a `complete_lattice` structure on affine subspaces. * `affine_subspace.direction` gives the `submodule` spanned by the pairwise differences of points in an `affine_subspace`. There are various lemmas relating to the set of vectors in the `direction`, and relating the lattice structure on affine subspaces to that on their directions. * `affine_span` gives the affine subspace spanned by a set of points, with `vector_span` giving its direction. `affine_span` is defined in terms of `span_points`, which gives an explicit description of the points contained in the affine span; `span_points` itself should generally only be used when that description is required, with `affine_span` being the main definition for other purposes. Two other descriptions of the affine span are proved equivalent: it is the `Inf` of affine subspaces containing the points, and (if `[nontrivial k]`) it contains exactly those points that are affine combinations of points in the given set. ## Implementation notes `out_param` is used in the definiton of `add_torsor V P` to make `V` an implicit argument (deduced from `P`) in most cases; `include V` is needed in many cases for `V`, and type classes using it, to be added as implicit arguments to individual lemmas. As for modules, `k` is an explicit argument rather than implied by `P` or `V`. This file only provides purely algebraic definitions and results. Those depending on analysis or topology are defined elsewhere; see `analysis.normed_space.add_torsor` and `topology.algebra.affine`. ## TODO * Coercions from an `affine_subspace` to the subtype of its points, and a corresponding `affine_space` instance on that subtype in the case of a nonempty subspace. ## References * https://en.wikipedia.org/wiki/Affine_space * https://en.wikipedia.org/wiki/Principal_homogeneous_space -/ noncomputable theory open_locale big_operators classical affine open set section variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] variables [affine_space V P] include V /-- The submodule spanning the differences of a (possibly empty) set of points. -/ def vector_span (s : set P) : submodule k V := submodule.span k (s -ᵥ s) /-- The definition of `vector_span`, for rewriting. -/ lemma vector_span_def (s : set P) : vector_span k s = submodule.span k (s -ᵥ s) := rfl /-- `vector_span` is monotone. -/ lemma vector_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : vector_span k s₁ ≤ vector_span k s₂ := submodule.span_mono (vsub_self_mono h) variables (P) /-- The `vector_span` of the empty set is `⊥`. -/ @[simp] lemma vector_span_empty : vector_span k (∅ : set P) = (⊥ : submodule k V) := by rw [vector_span_def, vsub_empty, submodule.span_empty] variables {P} /-- The `vector_span` of a single point is `⊥`. -/ @[simp] lemma vector_span_singleton (p : P) : vector_span k ({p} : set P) = ⊥ := by simp [vector_span_def] /-- The `s -ᵥ s` lies within the `vector_span k s`. -/ lemma vsub_set_subset_vector_span (s : set P) : s -ᵥ s ⊆ ↑(vector_span k s) := submodule.subset_span /-- Each pairwise difference is in the `vector_span`. -/ lemma vsub_mem_vector_span {s : set P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : p1 -ᵥ p2 ∈ vector_span k s := vsub_set_subset_vector_span k s (vsub_mem_vsub hp1 hp2) /-- The points in the affine span of a (possibly empty) set of points. Use `affine_span` instead to get an `affine_subspace k P`. -/ def span_points (s : set P) : set P := {p | ∃ p1 ∈ s, ∃ v ∈ (vector_span k s), p = v +ᵥ p1} /-- A point in a set is in its affine span. -/ lemma mem_span_points (p : P) (s : set P) : p ∈ s → p ∈ span_points k s | hp := ⟨p, hp, 0, submodule.zero_mem _, (zero_vadd V p).symm⟩ /-- A set is contained in its `span_points`. -/ lemma subset_span_points (s : set P) : s ⊆ span_points k s := λ p, mem_span_points k p s /-- The `span_points` of a set is nonempty if and only if that set is. -/ @[simp] lemma span_points_nonempty (s : set P) : (span_points k s).nonempty ↔ s.nonempty := begin split, { contrapose, rw [set.not_nonempty_iff_eq_empty, set.not_nonempty_iff_eq_empty], intro h, simp [h, span_points] }, { exact λ h, h.mono (subset_span_points _ _) } end /-- Adding a point in the affine span and a vector in the spanning submodule produces a point in the affine span. -/ lemma vadd_mem_span_points_of_mem_span_points_of_mem_vector_span {s : set P} {p : P} {v : V} (hp : p ∈ span_points k s) (hv : v ∈ vector_span k s) : v +ᵥ p ∈ span_points k s := begin rcases hp with ⟨p2, ⟨hp2, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv2p, vadd_assoc], use [p2, hp2, v + v2, (vector_span k s).add_mem hv hv2, rfl] end /-- Subtracting two points in the affine span produces a vector in the spanning submodule. -/ lemma vsub_mem_vector_span_of_mem_span_points_of_mem_span_points {s : set P} {p1 p2 : P} (hp1 : p1 ∈ span_points k s) (hp2 : p2 ∈ span_points k s) : p1 -ᵥ p2 ∈ vector_span k s := begin rcases hp1 with ⟨p1a, ⟨hp1a, ⟨v1, ⟨hv1, hv1p⟩⟩⟩⟩, rcases hp2 with ⟨p2a, ⟨hp2a, ⟨v2, ⟨hv2, hv2p⟩⟩⟩⟩, rw [hv1p, hv2p, vsub_vadd_eq_vsub_sub (v1 +ᵥ p1a), vadd_vsub_assoc, add_comm, add_sub_assoc], have hv1v2 : v1 - v2 ∈ vector_span k s, { rw sub_eq_add_neg, apply (vector_span k s).add_mem hv1, rw ←neg_one_smul k v2, exact (vector_span k s).smul_mem (-1 : k) hv2 }, refine (vector_span k s).add_mem _ hv1v2, exact vsub_mem_vector_span k hp1a hp2a end end /-- An `affine_subspace k P` is a subset of an `affine_space V P` that, if not empty, has an affine space structure induced by a corresponding subspace of the `module k V`. -/ structure affine_subspace (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] := (carrier : set P) (smul_vsub_vadd_mem : ∀ (c : k) {p1 p2 p3 : P}, p1 ∈ carrier → p2 ∈ carrier → p3 ∈ carrier → c • (p1 -ᵥ p2 : V) +ᵥ p3 ∈ carrier) namespace submodule variables {k V : Type*} [ring k] [add_comm_group V] [module k V] /-- Reinterpret `p : submodule k V` as an `affine_subspace k V`. -/ def to_affine_subspace (p : submodule k V) : affine_subspace k V := { carrier := p, smul_vsub_vadd_mem := λ c p₁ p₂ p₃ h₁ h₂ h₃, p.add_mem (p.smul_mem _ (p.sub_mem h₁ h₂)) h₃ } end submodule namespace affine_subspace variables (k : Type*) {V : Type*} (P : Type*) [ring k] [add_comm_group V] [module k V] [affine_space V P] include V instance : has_coe (affine_subspace k P) (set P) := ⟨carrier⟩ instance : has_mem P (affine_subspace k P) := ⟨λ p s, p ∈ (s : set P)⟩ /-- A point is in an affine subspace coerced to a set if and only if it is in that affine subspace. -/ @[simp] lemma mem_coe (p : P) (s : affine_subspace k P) : p ∈ (s : set P) ↔ p ∈ s := iff.rfl variables {k P} /-- The direction of an affine subspace is the submodule spanned by the pairwise differences of points. (Except in the case of an empty affine subspace, where the direction is the zero submodule, every vector in the direction is the difference of two points in the affine subspace.) -/ def direction (s : affine_subspace k P) : submodule k V := vector_span k (s : set P) /-- The direction equals the `vector_span`. -/ lemma direction_eq_vector_span (s : affine_subspace k P) : s.direction = vector_span k (s : set P) := rfl /-- Alternative definition of the direction when the affine subspace is nonempty. This is defined so that the order on submodules (as used in the definition of `submodule.span`) can be used in the proof of `coe_direction_eq_vsub_set`, and is not intended to be used beyond that proof. -/ def direction_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : submodule k V := { carrier := (s : set P) -ᵥ s, zero_mem' := begin cases h with p hp, exact (vsub_self p) ▸ vsub_mem_vsub hp hp end, add_mem' := begin intros a b ha hb, rcases ha with ⟨p1, p2, hp1, hp2, rfl⟩, rcases hb with ⟨p3, p4, hp3, hp4, rfl⟩, rw [←vadd_vsub_assoc], refine vsub_mem_vsub _ hp4, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp3, rw one_smul end, smul_mem' := begin intros c v hv, rcases hv with ⟨p1, p2, hp1, hp2, rfl⟩, rw [←vadd_vsub (c • (p1 -ᵥ p2)) p2], refine vsub_mem_vsub _ hp2, exact s.smul_vsub_vadd_mem c hp1 hp2 hp2 end } /-- `direction_of_nonempty` gives the same submodule as `direction`. -/ lemma direction_of_nonempty_eq_direction {s : affine_subspace k P} (h : (s : set P).nonempty) : direction_of_nonempty h = s.direction := le_antisymm (vsub_set_subset_vector_span k s) (submodule.span_le.2 set.subset.rfl) /-- The set of vectors in the direction of a nonempty affine subspace is given by `vsub_set`. -/ lemma coe_direction_eq_vsub_set {s : affine_subspace k P} (h : (s : set P).nonempty) : (s.direction : set V) = (s : set P) -ᵥ s := direction_of_nonempty_eq_direction h ▸ rfl /-- A vector is in the direction of a nonempty affine subspace if and only if it is the subtraction of two vectors in the subspace. -/ lemma mem_direction_iff_eq_vsub {s : affine_subspace k P} (h : (s : set P).nonempty) (v : V) : v ∈ s.direction ↔ ∃ p1 ∈ s, ∃ p2 ∈ s, v = p1 -ᵥ p2 := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set h], exact ⟨λ ⟨p1, p2, hp1, hp2, hv⟩, ⟨p1, hp1, p2, hp2, hv.symm⟩, λ ⟨p1, hp1, p2, hp2, hv⟩, ⟨p1, p2, hp1, hp2, hv.symm⟩⟩ end /-- Adding a vector in the direction to a point in the subspace produces a point in the subspace. -/ lemma vadd_mem_of_mem_direction {s : affine_subspace k P} {v : V} (hv : v ∈ s.direction) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s := begin rw mem_direction_iff_eq_vsub ⟨p, hp⟩ at hv, rcases hv with ⟨p1, hp1, p2, hp2, hv⟩, rw hv, convert s.smul_vsub_vadd_mem 1 hp1 hp2 hp, rw one_smul end /-- Subtracting two points in the subspace produces a vector in the direction. -/ lemma vsub_mem_direction {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) : (p1 -ᵥ p2) ∈ s.direction := vsub_mem_vector_span k hp1 hp2 /-- Adding a vector to a point in a subspace produces a point in the subspace if and only if the vector is in the direction. -/ lemma vadd_mem_iff_mem_direction {s : affine_subspace k P} (v : V) {p : P} (hp : p ∈ s) : v +ᵥ p ∈ s ↔ v ∈ s.direction := ⟨λ h, by simpa using vsub_mem_direction h hp, λ h, vadd_mem_of_mem_direction h hp⟩ /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the right. -/ lemma coe_direction_eq_vsub_set_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ p) '' s := begin rw coe_direction_eq_vsub_set ⟨p, hp⟩, refine le_antisymm _ _, { rintros v ⟨p1, p2, hp1, hp2, rfl⟩, exact ⟨p1 -ᵥ p2 +ᵥ p, vadd_mem_of_mem_direction (vsub_mem_direction hp1 hp2) hp, (vadd_vsub _ _)⟩ }, { rintros v ⟨p2, hp2, rfl⟩, exact ⟨p2, p, hp2, hp, rfl⟩ } end /-- Given a point in an affine subspace, the set of vectors in its direction equals the set of vectors subtracting that point on the left. -/ lemma coe_direction_eq_vsub_set_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) : (s.direction : set V) = (-ᵥ) p '' s := begin ext v, rw [submodule.mem_coe, ←submodule.neg_mem_iff, ←submodule.mem_coe, coe_direction_eq_vsub_set_right hp, set.mem_image_iff_bex, set.mem_image_iff_bex], conv_lhs { congr, funext, rw [←neg_vsub_eq_vsub_rev, neg_inj] } end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the right. -/ lemma mem_direction_iff_eq_vsub_right {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p2 -ᵥ p := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set_right hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a vector is in its direction if and only if it results from subtracting that point on the left. -/ lemma mem_direction_iff_eq_vsub_left {s : affine_subspace k P} {p : P} (hp : p ∈ s) (v : V) : v ∈ s.direction ↔ ∃ p2 ∈ s, v = p -ᵥ p2 := begin rw [←submodule.mem_coe, coe_direction_eq_vsub_set_left hp], exact ⟨λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩, λ ⟨p2, hp2, hv⟩, ⟨p2, hp2, hv.symm⟩⟩ end /-- Given a point in an affine subspace, a result of subtracting that point on the right is in the direction if and only if the other point is in the subspace. -/ lemma vsub_right_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p2 -ᵥ p ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_right hp, simp end /-- Given a point in an affine subspace, a result of subtracting that point on the left is in the direction if and only if the other point is in the subspace. -/ lemma vsub_left_mem_direction_iff_mem {s : affine_subspace k P} {p : P} (hp : p ∈ s) (p2 : P) : p -ᵥ p2 ∈ s.direction ↔ p2 ∈ s := begin rw mem_direction_iff_eq_vsub_left hp, simp end /-- Two affine subspaces are equal if they have the same points. -/ @[ext] lemma ext {s1 s2 : affine_subspace k P} (h : (s1 : set P) = s2) : s1 = s2 := begin cases s1, cases s2, congr, exact h end /-- Two affine subspaces with the same direction and nonempty intersection are equal. -/ lemma ext_of_direction_eq {s1 s2 : affine_subspace k P} (hd : s1.direction = s2.direction) (hn : ((s1 : set P) ∩ s2).nonempty) : s1 = s2 := begin ext p, have hq1 := set.mem_of_mem_inter_left hn.some_mem, have hq2 := set.mem_of_mem_inter_right hn.some_mem, split, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq2, rw ←hd, exact vsub_mem_direction hp hq1 }, { intro hp, rw ←vsub_vadd p hn.some, refine vadd_mem_of_mem_direction _ hq1, rw hd, exact vsub_mem_direction hp hq2 } end /-- Two affine subspaces with nonempty intersection are equal if and only if their directions are equal. -/ lemma eq_iff_direction_eq_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : s₁ = s₂ ↔ s₁.direction = s₂.direction := ⟨λ h, h ▸ rfl, λ h, ext_of_direction_eq h ⟨p, h₁, h₂⟩⟩ /-- Construct an affine subspace from a point and a direction. -/ def mk' (p : P) (direction : submodule k V) : affine_subspace k P := { carrier := {q | ∃ v ∈ direction, q = v +ᵥ p}, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, begin rcases hp1 with ⟨v1, hv1, hp1⟩, rcases hp2 with ⟨v2, hv2, hp2⟩, rcases hp3 with ⟨v3, hv3, hp3⟩, use [c • (v1 - v2) + v3, direction.add_mem (direction.smul_mem c (direction.sub_mem hv1 hv2)) hv3], simp [hp1, hp2, hp3, vadd_assoc] end } /-- An affine subspace constructed from a point and a direction contains that point. -/ lemma self_mem_mk' (p : P) (direction : submodule k V) : p ∈ mk' p direction := ⟨0, ⟨direction.zero_mem, (zero_vadd _ _).symm⟩⟩ /-- An affine subspace constructed from a point and a direction contains the result of adding a vector in that direction to that point. -/ lemma vadd_mem_mk' {v : V} (p : P) {direction : submodule k V} (hv : v ∈ direction) : v +ᵥ p ∈ mk' p direction := ⟨v, hv, rfl⟩ /-- An affine subspace constructed from a point and a direction is nonempty. -/ lemma mk'_nonempty (p : P) (direction : submodule k V) : (mk' p direction : set P).nonempty := ⟨p, self_mem_mk' p direction⟩ /-- The direction of an affine subspace constructed from a point and a direction. -/ @[simp] lemma direction_mk' (p : P) (direction : submodule k V) : (mk' p direction).direction = direction := begin ext v, rw mem_direction_iff_eq_vsub (mk'_nonempty _ _), split, { rintros ⟨p1, ⟨v1, hv1, hp1⟩, p2, ⟨v2, hv2, hp2⟩, hv⟩, rw [hv, hp1, hp2, vadd_vsub_vadd_cancel_right], exact direction.sub_mem hv1 hv2 }, { exact λ hv, ⟨v +ᵥ p, vadd_mem_mk' _ hv, p, self_mem_mk' _ _, (vadd_vsub _ _).symm⟩ } end /-- Constructing an affine subspace from a point in a subspace and that subspace's direction yields the original subspace. -/ @[simp] lemma mk'_eq {s : affine_subspace k P} {p : P} (hp : p ∈ s) : mk' p s.direction = s := ext_of_direction_eq (direction_mk' p s.direction) ⟨p, set.mem_inter (self_mem_mk' _ _) hp⟩ /-- If an affine subspace contains a set of points, it contains the `span_points` of that set. -/ lemma span_points_subset_coe_of_subset_coe {s : set P} {s1 : affine_subspace k P} (h : s ⊆ s1) : span_points k s ⊆ s1 := begin rintros p ⟨p1, hp1, v, hv, hp⟩, rw hp, have hp1s1 : p1 ∈ (s1 : set P) := set.mem_of_mem_of_subset hp1 h, refine vadd_mem_of_mem_direction _ hp1s1, have hs : vector_span k s ≤ s1.direction := vector_span_mono k h, rw submodule.le_def at hs, rw ←submodule.mem_coe, exact set.mem_of_mem_of_subset hv hs end end affine_subspace section affine_span variables (k : Type*) {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The affine span of a set of points is the smallest affine subspace containing those points. (Actually defined here in terms of spans in modules.) -/ def affine_span (s : set P) : affine_subspace k P := { carrier := span_points k s, smul_vsub_vadd_mem := λ c p1 p2 p3 hp1 hp2 hp3, vadd_mem_span_points_of_mem_span_points_of_mem_vector_span k hp3 ((vector_span k s).smul_mem c (vsub_mem_vector_span_of_mem_span_points_of_mem_span_points k hp1 hp2)) } /-- The affine span, converted to a set, is `span_points`. -/ @[simp] lemma coe_affine_span (s : set P) : (affine_span k s : set P) = span_points k s := rfl /-- A set is contained in its affine span. -/ lemma subset_affine_span (s : set P) : s ⊆ affine_span k s := subset_span_points k s /-- The direction of the affine span is the `vector_span`. -/ lemma direction_affine_span (s : set P) : (affine_span k s).direction = vector_span k s := begin apply le_antisymm, { refine submodule.span_le.2 _, rintros v ⟨p1, p3, ⟨p2, hp2, v1, hv1, hp1⟩, ⟨p4, hp4, v2, hv2, hp3⟩, rfl⟩, rw [hp1, hp3, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, submodule.mem_coe], exact (vector_span k s).sub_mem ((vector_span k s).add_mem hv1 (vsub_mem_vector_span k hp2 hp4)) hv2 }, { exact vector_span_mono k (subset_span_points k s) } end /-- A point in a set is in its affine span. -/ lemma mem_affine_span {p : P} {s : set P} (hp : p ∈ s) : p ∈ affine_span k s := mem_span_points k p s hp end affine_span namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [S : affine_space V P] include S instance : complete_lattice (affine_subspace k P) := { sup := λ s1 s2, affine_span k (s1 ∪ s2), le_sup_left := λ s1 s2, set.subset.trans (set.subset_union_left s1 s2) (subset_span_points k _), le_sup_right := λ s1 s2, set.subset.trans (set.subset_union_right s1 s2) (subset_span_points k _), sup_le := λ s1 s2 s3 hs1 hs2, span_points_subset_coe_of_subset_coe (set.union_subset hs1 hs2), inf := λ s1 s2, mk (s1 ∩ s2) (λ c p1 p2 p3 hp1 hp2 hp3, ⟨s1.smul_vsub_vadd_mem c hp1.1 hp2.1 hp3.1, s2.smul_vsub_vadd_mem c hp1.2 hp2.2 hp3.2⟩), inf_le_left := λ _ _, set.inter_subset_left _ _, inf_le_right := λ _ _, set.inter_subset_right _ _, le_inf := λ _ _ _, set.subset_inter, top := { carrier := set.univ, smul_vsub_vadd_mem := λ _ _ _ _ _ _ _, set.mem_univ _ }, le_top := λ _ _ _, set.mem_univ _, bot := { carrier := ∅, smul_vsub_vadd_mem := λ _ _ _ _, false.elim }, bot_le := λ _ _, false.elim, Sup := λ s, affine_span k (⋃ s' ∈ s, (s' : set P)), Inf := λ s, mk (⋂ s' ∈ s, (s' : set P)) (λ c p1 p2 p3 hp1 hp2 hp3, set.mem_bInter_iff.2 $ λ s2 hs2, s2.smul_vsub_vadd_mem c (set.mem_bInter_iff.1 hp1 s2 hs2) (set.mem_bInter_iff.1 hp2 s2 hs2) (set.mem_bInter_iff.1 hp3 s2 hs2)), le_Sup := λ _ _ h, set.subset.trans (set.subset_bUnion_of_mem h) (subset_span_points k _), Sup_le := λ _ _ h, span_points_subset_coe_of_subset_coe (set.bUnion_subset h), Inf_le := λ _ _, set.bInter_subset_of_mem, le_Inf := λ _ _, set.subset_bInter, .. partial_order.lift (coe : affine_subspace k P → set P) (λ _ _, ext) } instance : inhabited (affine_subspace k P) := ⟨⊤⟩ /-- The `≤` order on subspaces is the same as that on the corresponding sets. -/ lemma le_def (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ (s1 : set P) ⊆ s2 := iff.rfl /-- One subspace is less than or equal to another if and only if all its points are in the second subspace. -/ lemma le_def' (s1 s2 : affine_subspace k P) : s1 ≤ s2 ↔ ∀ p ∈ s1, p ∈ s2 := iff.rfl /-- The `<` order on subspaces is the same as that on the corresponding sets. -/ lemma lt_def (s1 s2 : affine_subspace k P) : s1 < s2 ↔ (s1 : set P) ⊂ s2 := iff.rfl /-- One subspace is not less than or equal to another if and only if it has a point not in the second subspace. -/ lemma not_le_iff_exists (s1 s2 : affine_subspace k P) : ¬ s1 ≤ s2 ↔ ∃ p ∈ s1, p ∉ s2 := set.not_subset /-- If a subspace is less than another, there is a point only in the second. -/ lemma exists_of_lt {s1 s2 : affine_subspace k P} (h : s1 < s2) : ∃ p ∈ s2, p ∉ s1 := set.exists_of_ssubset h /-- A subspace is less than another if and only if it is less than or equal to the second subspace and there is a point only in the second. -/ lemma lt_iff_le_and_exists (s1 s2 : affine_subspace k P) : s1 < s2 ↔ s1 ≤ s2 ∧ ∃ p ∈ s2, p ∉ s1 := by rw [lt_iff_le_not_le, not_le_iff_exists] /-- If an affine subspace is nonempty and contained in another with the same direction, they are equal. -/ lemma eq_of_direction_eq_of_nonempty_of_le {s₁ s₂ : affine_subspace k P} (hd : s₁.direction = s₂.direction) (hn : (s₁ : set P).nonempty) (hle : s₁ ≤ s₂) : s₁ = s₂ := let ⟨p, hp⟩ := hn in ext_of_direction_eq hd ⟨p, hp, hle hp⟩ variables (k V) /-- The affine span is the `Inf` of subspaces containing the given points. -/ lemma affine_span_eq_Inf (s : set P) : affine_span k s = Inf {s' | s ⊆ s'} := le_antisymm (span_points_subset_coe_of_subset_coe (set.subset_bInter (λ _ h, h))) (Inf_le (subset_span_points k _)) variables (P) /-- The Galois insertion formed by `affine_span` and coercion back to a set. -/ protected def gi : galois_insertion (affine_span k) (coe : affine_subspace k P → set P) := { choice := λ s _, affine_span k s, gc := λ s1 s2, ⟨λ h, set.subset.trans (subset_span_points k s1) h, span_points_subset_coe_of_subset_coe⟩, le_l_u := λ _, subset_span_points k _, choice_eq := λ _ _, rfl } /-- The span of the empty set is `⊥`. -/ @[simp] lemma span_empty : affine_span k (∅ : set P) = ⊥ := (affine_subspace.gi k V P).gc.l_bot /-- The span of `univ` is `⊤`. -/ @[simp] lemma span_univ : affine_span k (set.univ : set P) = ⊤ := eq_top_iff.2 $ subset_span_points k _ variables {P} /-- The affine span of a single point, coerced to a set, contains just that point. -/ @[simp] lemma coe_affine_span_singleton (p : P) : (affine_span k ({p} : set P) : set P) = {p} := begin ext x, rw [mem_coe, ←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_singleton p)) _, direction_affine_span], simp end /-- A point is in the affine span of a single point if and only if they are equal. -/ @[simp] lemma mem_affine_span_singleton (p1 p2 : P) : p1 ∈ affine_span k ({p2} : set P) ↔ p1 = p2 := by simp [←mem_coe] /-- The span of a union of sets is the sup of their spans. -/ lemma span_union (s t : set P) : affine_span k (s ∪ t) = affine_span k s ⊔ affine_span k t := (affine_subspace.gi k V P).gc.l_sup /-- The span of a union of an indexed family of sets is the sup of their spans. -/ lemma span_Union {ι : Type*} (s : ι → set P) : affine_span k (⋃ i, s i) = ⨆ i, affine_span k (s i) := (affine_subspace.gi k V P).gc.l_supr variables (P) /-- `⊤`, coerced to a set, is the whole set of points. -/ @[simp] lemma top_coe : ((⊤ : affine_subspace k P) : set P) = set.univ := rfl variables {P} /-- All points are in `⊤`. -/ lemma mem_top (p : P) : p ∈ (⊤ : affine_subspace k P) := set.mem_univ p variables (P) /-- The direction of `⊤` is the whole module as a submodule. -/ @[simp] lemma direction_top : (⊤ : affine_subspace k P).direction = ⊤ := begin cases S.nonempty with p, ext v, refine ⟨imp_intro submodule.mem_top, λ hv, _⟩, have hpv : (v +ᵥ p -ᵥ p : V) ∈ (⊤ : affine_subspace k P).direction := vsub_mem_direction (mem_top k V _) (mem_top k V _), rwa vadd_vsub at hpv end /-- `⊥`, coerced to a set, is the empty set. -/ @[simp] lemma bot_coe : ((⊥ : affine_subspace k P) : set P) = ∅ := rfl variables {P} /-- No points are in `⊥`. -/ lemma not_mem_bot (p : P) : p ∉ (⊥ : affine_subspace k P) := set.not_mem_empty p variables (P) /-- The direction of `⊥` is the submodule `⊥`. -/ @[simp] lemma direction_bot : (⊥ : affine_subspace k P).direction = ⊥ := by rw [direction_eq_vector_span, bot_coe, vector_span_def, vsub_empty, submodule.span_empty] variables {k V P} /-- A nonempty affine subspace is `⊤` if and only if its direction is `⊤`. -/ @[simp] lemma direction_eq_top_iff_of_nonempty {s : affine_subspace k P} (h : (s : set P).nonempty) : s.direction = ⊤ ↔ s = ⊤ := begin split, { intro hd, rw ←direction_top k V P at hd, refine ext_of_direction_eq hd _, simp [h] }, { rintro rfl, simp } end /-- The inf of two affine subspaces, coerced to a set, is the intersection of the two sets of points. -/ @[simp] lemma inf_coe (s1 s2 : affine_subspace k P) : ((s1 ⊓ s2) : set P) = s1 ∩ s2 := rfl /-- A point is in the inf of two affine subspaces if and only if it is in both of them. -/ lemma mem_inf_iff (p : P) (s1 s2 : affine_subspace k P) : p ∈ s1 ⊓ s2 ↔ p ∈ s1 ∧ p ∈ s2 := iff.rfl /-- The direction of the inf of two affine subspaces is less than or equal to the inf of their directions. -/ lemma direction_inf (s1 s2 : affine_subspace k P) : (s1 ⊓ s2).direction ≤ s1.direction ⊓ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact le_inf (Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_left _ _)) hp)) (Inf_le_Inf (λ p hp, trans (vsub_self_mono (inter_subset_right _ _)) hp)) end /-- If two affine subspaces have a point in common, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem {s₁ s₂ : affine_subspace k P} {p : P} (h₁ : p ∈ s₁) (h₂ : p ∈ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := begin ext v, rw [submodule.mem_inf, ←vadd_mem_iff_mem_direction v h₁, ←vadd_mem_iff_mem_direction v h₂, ←vadd_mem_iff_mem_direction v ((mem_inf_iff p s₁ s₂).2 ⟨h₁, h₂⟩), mem_inf_iff] end /-- If two affine subspaces have a point in their inf, the direction of their inf equals the inf of their directions. -/ lemma direction_inf_of_mem_inf {s₁ s₂ : affine_subspace k P} {p : P} (h : p ∈ s₁ ⊓ s₂) : (s₁ ⊓ s₂).direction = s₁.direction ⊓ s₂.direction := direction_inf_of_mem ((mem_inf_iff p s₁ s₂).1 h).1 ((mem_inf_iff p s₁ s₂).1 h).2 /-- If one affine subspace is less than or equal to another, the same applies to their directions. -/ lemma direction_le {s1 s2 : affine_subspace k P} (h : s1 ≤ s2) : s1.direction ≤ s2.direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact vector_span_mono k h end /-- If one nonempty affine subspace is less than another, the same applies to their directions -/ lemma direction_lt_of_nonempty {s1 s2 : affine_subspace k P} (h : s1 < s2) (hn : (s1 : set P).nonempty) : s1.direction < s2.direction := begin cases hn with p hp, rw lt_iff_le_and_exists at h, rcases h with ⟨hle, p2, hp2, hp2s1⟩, rw submodule.lt_iff_le_and_exists, use [direction_le hle, p2 -ᵥ p, vsub_mem_direction hp2 (hle hp)], intro hm, rw vsub_right_mem_direction_iff_mem hp p2 at hm, exact hp2s1 hm end /-- The sup of the directions of two affine subspaces is less than or equal to the direction of their sup. -/ lemma sup_direction_le (s1 s2 : affine_subspace k P) : s1.direction ⊔ s2.direction ≤ (s1 ⊔ s2).direction := begin repeat { rw [direction_eq_vector_span, vector_span_def] }, exact sup_le (Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_left : s1 ≤ s1 ⊔ s2)) hp)) (Inf_le_Inf (λ p hp, set.subset.trans (vsub_self_mono (le_sup_right : s2 ≤ s1 ⊔ s2)) hp)) end /-- The sup of the directions of two nonempty affine subspaces with empty intersection is less than the direction of their sup. -/ lemma sup_direction_lt_of_nonempty_of_inter_empty {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (he : (s1 ∩ s2 : set P) = ∅) : s1.direction ⊔ s2.direction < (s1 ⊔ s2).direction := begin cases h1 with p1 hp1, cases h2 with p2 hp2, rw submodule.lt_iff_le_and_exists, use [sup_direction_le s1 s2, p2 -ᵥ p1, vsub_mem_direction ((le_sup_right : s2 ≤ s1 ⊔ s2) hp2) ((le_sup_left : s1 ≤ s1 ⊔ s2) hp1)], intro h, rw submodule.mem_sup at h, rcases h with ⟨v1, hv1, v2, hv2, hv1v2⟩, rw [←sub_eq_zero, sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm v1, add_assoc, ←vadd_vsub_assoc, ←neg_neg v2, add_comm, ←sub_eq_add_neg, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hv1v2, refine set.nonempty.ne_empty _ he, use [v1 +ᵥ p1, vadd_mem_of_mem_direction hv1 hp1], rw hv1v2, exact vadd_mem_of_mem_direction (submodule.neg_mem _ hv2) hp2 end /-- If the directions of two nonempty affine subspaces span the whole module, they have nonempty intersection. -/ lemma inter_nonempty_of_nonempty_of_sup_direction_eq_top {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : s1.direction ⊔ s2.direction = ⊤) : ((s1 : set P) ∩ s2).nonempty := begin by_contradiction h, rw set.not_nonempty_iff_eq_empty at h, have hlt := sup_direction_lt_of_nonempty_of_inter_empty h1 h2 h, rw hd at hlt, exact not_top_lt hlt end /-- If the directions of two nonempty affine subspaces are complements of each other, they intersect in exactly one point. -/ lemma inter_eq_singleton_of_nonempty_of_is_compl {s1 s2 : affine_subspace k P} (h1 : (s1 : set P).nonempty) (h2 : (s2 : set P).nonempty) (hd : is_compl s1.direction s2.direction) : ∃ p, (s1 : set P) ∩ s2 = {p} := begin cases inter_nonempty_of_nonempty_of_sup_direction_eq_top h1 h2 hd.sup_eq_top with p hp, use p, ext q, rw set.mem_singleton_iff, split, { rintros ⟨hq1, hq2⟩, have hqp : q -ᵥ p ∈ s1.direction ⊓ s2.direction := ⟨vsub_mem_direction hq1 hp.1, vsub_mem_direction hq2 hp.2⟩, rwa [hd.inf_eq_bot, submodule.mem_bot, vsub_eq_zero_iff_eq] at hqp }, { exact λ h, h.symm ▸ hp } end /-- Coercing a subspace to a set then taking the affine span produces the original subspace. -/ @[simp] lemma affine_span_coe (s : affine_subspace k P) : affine_span k (s : set P) = s := begin refine le_antisymm _ (subset_span_points _ _), rintros p ⟨p1, hp1, v, hv, rfl⟩, exact vadd_mem_of_mem_direction hv hp1 end end affine_subspace 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 open affine_subspace set /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_eq_span_vsub_set_left {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_left p1 p2 p at hv, rw [←hv, submodule.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p2, hp2, rfl⟩) (hm ⟨p1, hp1, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p, p2, hp, hp2, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_eq_span_vsub_set_right {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' s) := begin rw vector_span_def, refine le_antisymm _ (submodule.span_mono _), { rw submodule.span_le, rintros v ⟨p1, p2, hp1, hp2, hv⟩, rw ←vsub_sub_vsub_cancel_right p1 p2 p at hv, rw [←hv, submodule.mem_coe, submodule.mem_span], exact λ m hm, submodule.sub_mem _ (hm ⟨p1, hp1, rfl⟩) (hm ⟨p2, hp2, rfl⟩) }, { rintros v ⟨p2, hp2, hv⟩, exact ⟨p2, p, hp2, hp, hv⟩ } end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_left_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ) p '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_eq_span_vsub_set_right_ne {s : set P} {p : P} (hp : p ∈ s) : vector_span k s = submodule.span k ((-ᵥ p) '' (s \ {p})) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k hp, ←set.insert_eq_of_mem hp, ←set.insert_diff_singleton, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_left_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ) (p i) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_left k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of the image of a function is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_image_eq_span_vsub_set_right_ne (p : ι → P) {s : set ι} {i : ι} (hi : i ∈ s) : vector_span k (p '' s) = submodule.span k ((-ᵥ (p i)) '' (p '' (s \ {i}))) := begin conv_lhs { rw [vector_span_eq_span_vsub_set_right k (set.mem_image_of_mem p hi), ←set.insert_eq_of_mem hi, ←set.insert_diff_singleton, set.image_insert_eq, set.image_insert_eq] }, simp [submodule.span_insert_eq_span] end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left. -/ lemma vector_span_range_eq_span_range_vsub_left (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i0 -ᵥ p i)) := by rw [vector_span_eq_span_vsub_set_left k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right. -/ lemma vector_span_range_eq_span_range_vsub_right (p : ι → P) (i0 : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : ι), p i -ᵥ p i0)) := by rw [vector_span_eq_span_vsub_set_right k (set.mem_range_self i0), ←set.range_comp] /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the left, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_left_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i₀ -ᵥ p i)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_left_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The `vector_span` of an indexed family is the span of the pairwise subtractions with a given point on the right, excluding the subtraction of that point from itself. -/ lemma vector_span_range_eq_span_range_vsub_right_ne (p : ι → P) (i₀ : ι) : vector_span k (set.range p) = submodule.span k (set.range (λ (i : {x // x ≠ i₀}), p i -ᵥ p i₀)) := begin rw [←set.image_univ, vector_span_image_eq_span_vsub_set_right_ne k _ (set.mem_univ i₀)], congr' with v, simp only [set.mem_range, set.mem_image, set.mem_diff, set.mem_singleton_iff, subtype.exists, subtype.coe_mk], split, { rintros ⟨x, ⟨i₁, ⟨⟨hi₁u, hi₁⟩, rfl⟩⟩, hv⟩, exact ⟨i₁, hi₁, hv⟩ }, { exact λ ⟨i₁, hi₁, hv⟩, ⟨p i₁, ⟨i₁, ⟨set.mem_univ _, hi₁⟩, rfl⟩, hv⟩ } end /-- The affine span of a set is nonempty if and only if that set is. -/ lemma affine_span_nonempty (s : set P) : (affine_span k s : set P).nonempty ↔ s.nonempty := span_points_nonempty k s variables {k} /-- Suppose a set of vectors spans `V`. Then a point `p`, together with those vectors added to `p`, spans `P`. -/ lemma affine_span_singleton_union_vadd_eq_top_of_span_eq_top {s : set V} (p : P) (h : submodule.span k (set.range (coe : s → V)) = ⊤) : affine_span k ({p} ∪ (λ v, v +ᵥ p) '' s) = ⊤ := begin convert ext_of_direction_eq _ ⟨p, mem_affine_span k (set.mem_union_left _ (set.mem_singleton _)), mem_top k V p⟩, rw [direction_affine_span, direction_top, vector_span_eq_span_vsub_set_right k ((set.mem_union_left _ (set.mem_singleton _)) : p ∈ _), eq_top_iff, ←h], apply submodule.span_mono, rintros v ⟨v', rfl⟩, use (v' : V) +ᵥ p, simp end variables (k) /-- `affine_span` is monotone. -/ lemma affine_span_mono {s₁ s₂ : set P} (h : s₁ ⊆ s₂) : affine_span k s₁ ≤ affine_span k s₂ := span_points_subset_coe_of_subset_coe (set.subset.trans h (subset_affine_span k _)) /-- Taking the affine span of a set, adding a point and taking the span again produces the same results as adding the point to the set and taking the span. -/ lemma affine_span_insert_affine_span (p : P) (ps : set P) : affine_span k (insert p (affine_span k ps : set P)) = affine_span k (insert p ps) := by rw [set.insert_eq, set.insert_eq, span_union, span_union, affine_span_coe] /-- If a point is in the affine span of a set, adding it to that set does not change the affine span. -/ lemma affine_span_insert_eq_affine_span {p : P} {ps : set P} (h : p ∈ affine_span k ps) : affine_span k (insert p ps) = affine_span k ps := begin rw ←mem_coe at h, rw [←affine_span_insert_affine_span, set.insert_eq_of_mem h, affine_span_coe] end end affine_space' namespace affine_subspace variables {k : Type*} {V : Type*} {P : Type*} [ring k] [add_comm_group V] [module k V] [affine_space V P] include V /-- The direction of the sup of two nonempty affine subspaces is the sup of the two directions and of any one difference between points in the two subspaces. -/ lemma direction_sup {s1 s2 : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s1) (hp2 : p2 ∈ s2) : (s1 ⊔ s2).direction = s1.direction ⊔ s2.direction ⊔ submodule.span k {p2 -ᵥ p1} := begin refine le_antisymm _ _, { change (affine_span k ((s1 : set P) ∪ s2)).direction ≤ _, rw ←mem_coe at hp1, rw [direction_affine_span, vector_span_eq_span_vsub_set_right k (set.mem_union_left _ hp1), submodule.span_le], rintros v ⟨p3, hp3, rfl⟩, cases hp3, { rw [sup_assoc, sup_comm, submodule.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw zero_add }, { rw [sup_assoc, submodule.mem_coe, submodule.mem_sup], use [0, submodule.zero_mem _, p3 -ᵥ p1], rw [and_comm, zero_add], use rfl, rw [←vsub_add_vsub_cancel p3 p2 p1, submodule.mem_sup], use [p3 -ᵥ p2, vsub_mem_direction hp3 hp2, p2 -ᵥ p1, submodule.mem_span_singleton_self _] } }, { refine sup_le (sup_direction_le _ _) _, rw [direction_eq_vector_span, vector_span_def], exact Inf_le_Inf (λ p hp, set.subset.trans (set.singleton_subset_iff.2 (vsub_mem_vsub (mem_span_points k p2 _ (set.mem_union_right _ hp2)) (mem_span_points k p1 _ (set.mem_union_left _ hp1)))) hp) } end /-- The direction of the span of the result of adding a point to a nonempty affine subspace is the sup of the direction of that subspace and of any one difference between that point and a point in the subspace. -/ lemma direction_affine_span_insert {s : affine_subspace k P} {p1 p2 : P} (hp1 : p1 ∈ s) : (affine_span k (insert p2 (s : set P))).direction = submodule.span k {p2 -ᵥ p1} ⊔ s.direction := begin rw [sup_comm, ←set.union_singleton, ←coe_affine_span_singleton k V p2], change (s ⊔ affine_span k {p2}).direction = _, rw [direction_sup hp1 (mem_affine_span k (set.mem_singleton _)), direction_affine_span], simp end /-- Given a point `p1` in an affine subspace `s`, and a point `p2`, a point `p` is in the span of `s` with `p2` added if and only if it is a multiple of `p2 -ᵥ p1` added to a point in `s`. -/ lemma mem_affine_span_insert_iff {s : affine_subspace k P} {p1 : P} (hp1 : p1 ∈ s) (p2 p : P) : p ∈ affine_span k (insert p2 (s : set P)) ↔ ∃ (r : k) (p0 : P) (hp0 : p0 ∈ s), p = r • (p2 -ᵥ p1 : V) +ᵥ p0 := begin rw ←mem_coe at hp1, rw [←vsub_right_mem_direction_iff_mem (mem_affine_span k (set.mem_insert_of_mem _ hp1)), direction_affine_span_insert hp1, submodule.mem_sup], split, { rintros ⟨v1, hv1, v2, hv2, hp⟩, rw submodule.mem_span_singleton at hv1, rcases hv1 with ⟨r, rfl⟩, use [r, v2 +ᵥ p1, vadd_mem_of_mem_direction hv2 hp1], symmetry' at hp, rw [←sub_eq_zero_iff_eq, ←vsub_vadd_eq_vsub_sub, vsub_eq_zero_iff_eq] at hp, rw [hp, vadd_assoc] }, { rintros ⟨r, p3, hp3, rfl⟩, use [r • (p2 -ᵥ p1), submodule.mem_span_singleton.2 ⟨r, rfl⟩, p3 -ᵥ p1, vsub_mem_direction hp3 hp1], rw [vadd_vsub_assoc, add_comm] } end end affine_subspace
29e96694f5113af24b8a75eb28d527e0c8f12eb3
5756a081670ba9c1d1d3fca7bd47cb4e31beae66
/Mathport/Syntax/Translate/Parser.lean
dbe0017566965e1b39e0bc76bf1de52ccc1ddeee
[ "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
12,710
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.AST3 import Mathlib.Mathport.Syntax open Lean hiding Expr Command open Lean.Elab Tactic namespace Mathport namespace Translate open AST3 namespace Parser structure Context where cmds : Array Command arr : Array (Spanned VMCall) abbrev ParserM := ReaderT Context $ ExceptT String (StateM Nat) instance : Alternative ParserM where failure := throw "failed" orElse a b r s := match a r s with | (.ok a, s) => (.ok a, s) | _ => b () r s def ParserM.run (p : ParserM α) (ctx : Context) : Except String α := do match (p ctx).run 0 with | (.error e, i) => Except.error s!"parse error @ arg {i}: {e}" | (.ok a, i) => if i = ctx.arr.size then Except.ok a else Except.error "too many args" def next : ParserM (Spanned VMCall) := fun s i => if h : i < s.arr.size then (pure (s.arr.get ⟨i, h⟩), i+1) else (throw "next failed, no more args", i) def ident : ParserM Name := do let ⟨_, VMCall.ident n⟩ ← next | {throw "ident failed"}; pure n def smallNat : ParserM Nat := do let ⟨_, VMCall.nat n⟩ ← next | {throw "smallNat failed"}; pure n def pExpr : (pat :_:= false) → ParserM (Spanned Expr) | false => do let ⟨m, VMCall.expr e⟩ ← next | {throw "pExpr failed"}; pure ⟨m, e⟩ | true => do let ⟨m, VMCall.pat e⟩ ← next | {throw "pExpr failed"}; pure ⟨m, e⟩ def itactic : ParserM AST3.Block := do let ⟨_, VMCall.block bl⟩ ← next | {throw "itactic failed"}; pure bl def commandLike? : ParserM (Option (Spanned AST3.Command)) := do let ⟨m, VMCall.command i⟩ ← next | throw "commandLike? failed" i.mapM fun i => return ⟨m, (← read).cmds[i]!⟩ def commandLike : ParserM (Spanned AST3.Command) := do let some i ← commandLike? | {throw "commandLike failed"}; pure i def skipAll : ParserM Unit := do set (← read).arr.size def withInput (p : ParserM α) : ParserM (α × Nat) := do let ⟨_, VMCall.withInput arr n⟩ ← next | throw "withInput failed" fun c i => (return (← p { c with arr } |>.run' 0, n), i) def emittedCommandHere : ParserM (Option Command) := return (← withInput commandLike?).1.map (·.kind) partial def emittedCodeHere : ParserM (Array Command) := aux #[] where aux (out : Array Command) : ParserM (Array Command) := do match ← emittedCommandHere <|> pure none with | none => pure out | some c => aux (out.push c) def tk (tk : String) : ParserM Unit := do let ⟨_, VMCall.token t⟩ ← next | throw s!"tk \"{tk}\" failed, not a token" unless tk = t do throw s!"tk \"{tk}\" failed, found {t}" partial def manyList (x : ParserM α) : ParserM (List α) := (return (← x) :: (← manyList x)) <|> pure [] def many (x : ParserM α) : ParserM (Array α) := List.toArray <$> manyList x scoped postfix:max "?" => optional scoped postfix:max "*" => many def sepByList (s : ParserM Unit) (p : ParserM α) : ParserM (List α) := (return (← p) :: (← manyList (s *> p))) <|> pure [] def sepBy (s : ParserM Unit) (p : ParserM α) : ParserM (Array α) := List.toArray <$> sepByList s p def brackets (l r) (p : ParserM α) := tk l *> p <* tk r def listOf (p : ParserM α) := brackets "[" "]" $ sepBy (tk ",") p def maybeListOf (p : ParserM α) := listOf p <|> return #[← p] def ident_ := BinderName.ident <$> ident <|> tk "_" *> pure BinderName._ def usingIdent := (tk "using" *> ident)? def withIdentList := (tk "with" *> ident_*) <|> pure #[] def withoutIdentList := (tk "without" *> ident*) <|> pure #[] open Lean.Elab.Tactic in def Location.ofOption (l : Array (Option Name)) : Location := let (hs, ty) := l.foldl (init := (#[], false)) fun | (hs, _), none => (hs, true) | (hs, ty), some n => (hs.push (mkIdent n), ty) Location.targets hs ty open Lean.Elab.Tactic in def location := (tk "at" *> (tk "*" *> pure Location.wildcard <|> (Location.ofOption <$> (((tk "⊢" <|> tk "|-") *> pure none) <|> some <$> ident)*))) <|> pure (Location.targets #[] true) def pExprList := listOf pExpr def optPExprList := listOf pExpr <|> pure #[] def pExprListOrTExpr := maybeListOf pExpr def onlyFlag := (tk "only" *> pure true) <|> pure false def optTk (yes : Bool) : Option Syntax := if yes then some default else none def parseBinders : ParserM Binders := do let ⟨_, VMCall.binders bis⟩ ← next | {throw "parseBinders failed"}; pure bis def inductiveDecl : ParserM InductiveCmd := do let ⟨_, VMCall.inductive i⟩ ← next | throw "inductiveDecl failed" let Command.inductive c := (← read).cmds[i]! | unreachable! pure c def renameArg : ParserM (Name × Name) := return (← ident, ← (tk "->")? *> ident) def renameArgs : ParserM (Array (Name × Name)) := (return #[← renameArg]) <|> listOf renameArg structure RwRule where symm : Bool rule : Spanned Expr def rwRule : ParserM RwRule := do pure ⟨Option.isSome (← (tk "<-")?), ← pExpr⟩ def rwRules : ParserM (Array RwRule) := maybeListOf rwRule def generalizeArg : ParserM (Spanned Expr × Name) := do let AST3.Expr.notation n args := (← pExpr).kind.unparen | failure let (`«expr = », #[⟨mlhs, Arg.expr lhs⟩, ⟨_, Arg.expr rhs⟩]) := (n.name, args) | failure let AST3.Expr.ident x := rhs.unparen | failure pure (⟨mlhs, lhs⟩, x) def hGeneralizeArg : ParserM (Spanned Expr × Name) := do let AST3.Expr.notation n args := (← pExpr).kind.unparen | failure let (`«expr == », #[⟨mlhs, Arg.expr lhs⟩, ⟨_, Arg.expr rhs⟩]) := (n.name, args) | failure let AST3.Expr.ident x := rhs.unparen | failure pure (⟨mlhs, lhs⟩, x) def generalizesArgEq (e : Spanned AST3.Expr) : ParserM (Spanned Expr × Name) := do let AST3.Expr.notation n args := e.kind.unparen | failure match n.name with | `«expr = » => pure () | `«expr == » => pure () | _ => failure let #[⟨mlhs, Arg.expr lhs⟩, ⟨_, Arg.expr rhs⟩] := args | failure let AST3.Expr.ident x := rhs.unparen | failure pure (⟨mlhs, lhs⟩, x) def generalizesArg : ParserM (Option Name × Spanned Expr × Name) := do let t ← pExpr (tk ":" *> do let AST3.Expr.ident x := t.kind.unparen | failure pure (some x, ← generalizesArgEq (← pExpr))) <|> (return (none, ← generalizesArgEq t)) def casesArg : ParserM (Option Name × Spanned Expr) := do let t ← pExpr match t.kind.unparen with | AST3.Expr.ident x => (return (some x, ← tk ":" *> pExpr)) <|> return (none, t) | _ => pure (none, t) def caseArg : ParserM (Array BinderName × Array BinderName) := return (← ident_*, (← (tk ":" *> ident_*)?).getD #[]) def case : ParserM (Array (Array BinderName × Array BinderName)) := maybeListOf caseArg inductive SimpArg | allHyps | except (n : Name) | expr (sym : Bool) (e : Spanned Expr) def simpArg : ParserM SimpArg := (tk "*" *> pure SimpArg.allHyps) <|> (tk "-" *> SimpArg.except <$> ident) <|> (tk "<-" *> SimpArg.expr true <$> pExpr) <|> SimpArg.expr false <$> pExpr def simpArgList : ParserM (Array SimpArg) := (tk "*" *> pure #[SimpArg.allHyps]) <|> listOf simpArg <|> pure #[] inductive RCasesPat : Type | one : BinderName → RCasesPat | clear : RCasesPat | explicit : RCasesPat → RCasesPat | typed : RCasesPat → Spanned AST3.Expr → RCasesPat | tuple : Array RCasesPat → RCasesPat | alts : Array RCasesPat → RCasesPat deriving Inhabited def RCasesPat.alts' : Array RCasesPat → RCasesPat | #[p] => p | ps => alts ps mutual partial def rcasesPat : Bool → ParserM RCasesPat | true => (brackets "(" ")" (rcasesPat false)) <|> (.tuple <$> brackets "⟨" "⟩" (sepBy (tk ",") (rcasesPat false))) <|> (tk "-" *> pure .clear) <|> (tk "@" *> .explicit <$> rcasesPat true) <|> (.one <$> ident_) | false => do let pat ← .alts' <$> rcasesPatList (tk ":" *> pat.typed <$> pExpr) <|> pure pat partial def rcasesPatList (pats : Array RCasesPat := #[]) : ParserM (Array RCasesPat) := do pats.push (← rcasesPat true) |> rcasesPatListRest partial def rcasesPatListRest (pats : Array RCasesPat) : ParserM (Array RCasesPat) := (tk "|" *> rcasesPatList pats) <|> -- hack to support `-|-` patterns, because `|-` is a token (tk "|-" *> rcasesPatListRest (pats.push .clear)) <|> pure pats end inductive RCasesArgs | hint (tgt : Sum (Spanned AST3.Expr) (Array (Spanned AST3.Expr))) (depth : Option ℕ) | rcases (name : Option Name) (tgt : Spanned AST3.Expr) (pat : RCasesPat) | rcasesMany (tgt : Array (Spanned AST3.Expr)) (pat : RCasesPat) set_option linter.unusedVariables false in -- FIXME(Mario): spurious warning on let p ← ... def rcasesArgs : ParserM RCasesArgs := do let hint ← (tk "?")? let p ← (Sum.inr <$> brackets "⟨" "⟩" (sepBy (tk ",") pExpr)) <|> (Sum.inl <$> pExpr) match hint with | none => do let p ← (do let Sum.inl t := p | failure let AST3.Expr.ident h := t.kind.unparen | failure return Sum.inl (h, ← tk ":" *> pExpr)) <|> pure (Sum.inr p) let ids ← (tk "with" *> rcasesPat false)? let ids := ids.getD (RCasesPat.tuple #[]) pure $ match p with | Sum.inl (name, tgt) => RCasesArgs.rcases (some name) tgt ids | Sum.inr (Sum.inl tgt) => RCasesArgs.rcases none tgt ids | Sum.inr (Sum.inr tgts) => RCasesArgs.rcasesMany tgts ids | some _ => do let depth ← (tk ":" *> smallNat)? pure $ RCasesArgs.hint p depth inductive RIntroPat : Type | one : RCasesPat → RIntroPat | binder : Array RIntroPat → Option (Spanned AST3.Expr) → RIntroPat deriving Inhabited mutual partial def rintroPatHi : ParserM RIntroPat := brackets "(" ")" rintroPat <|> RIntroPat.one <$> rcasesPat true partial def rintroPat : ParserM RIntroPat := do match ← rintroPatHi* with | #[] => failure | #[RIntroPat.one pat] => let pat1 := RCasesPat.alts' (← rcasesPatListRest #[pat]) pure $ match ← (tk ":" *> pExpr)? with | none => RIntroPat.one pat1 | some e => RIntroPat.one $ pat1.typed e | pats => RIntroPat.binder pats <$> (tk ":" *> pExpr)? end /-- Syntax for a `rintro` patern: `('?' (: n)?) | rintro_pat`. -/ def rintroArg : ParserM (Sum (Array RIntroPat × Option (Spanned AST3.Expr)) (Option ℕ)) := (tk "?" *> Sum.inr <$> (tk ":" *> smallNat)?) <|> return Sum.inl (← rintroPatHi*, ← (tk ":" *> pExpr)?) /-- Parses `patt? (: expr)? (:= expr)?`, the arguments for `obtain`. (This is almost the same as `rcasesPat false`, but it allows the pattern part to be empty.) -/ def obtainArg : ParserM ((Option RCasesPat × Option (Spanned AST3.Expr)) × Option (Array (Spanned AST3.Expr))) := do let (pat, tp) ← (return match ← rcasesPat false with | RCasesPat.typed pat tp => (some pat, some tp) | pat => (some pat, none)) <|> (return (none, ← (tk ":" *> pExpr)?)) pure ((pat, tp), ← (tk ":=" *> do (guard tp.isNone *> brackets "⟨" "⟩" (sepBy (tk ",") pExpr)) <|> (return #[← pExpr]))?) inductive LintVerbosity | low | medium | high def lintVerbosity : ParserM LintVerbosity := (tk "-" *> pure LintVerbosity.low) <|> (tk "+" *> pure LintVerbosity.high) <|> pure LintVerbosity.medium def lintOpts : ParserM (Bool × LintVerbosity) := do match ← lintVerbosity, (← (tk "*")?).isSome with | LintVerbosity.medium, fast => pure (fast, ← lintVerbosity) | v, fast => pure (fast, v) def lintArgs : ParserM ((Bool × LintVerbosity) × Bool × Array Name) := return (← lintOpts, ← onlyFlag, ← ident*) inductive ExtParam | arrow | all | ident (n : Name) def extParam : ParserM (Bool × ExtParam) := return ( (← (tk "-")?).isSome, ← (brackets "(" ")" (tk "->") *> pure ExtParam.arrow) <|> (tk "*" *> pure ExtParam.all) <|> (ExtParam.ident <$> ident)) def extParams : ParserM (Array (Bool × ExtParam)) := (return #[← extParam]) <|> listOf extParam <|> pure #[] def simpsRule : ParserM (Sum (Name × Name) Name × Bool) := do let lhs ← (return Sum.inl (← ident, ← tk "->" *> ident)) <|> (return Sum.inr (← tk "-" *> ident)) return (lhs, (← (tk "as_prefix")?).isSome) def simpsRules : ParserM (Array (Sum (Name × Name) Name × Bool)) := brackets "(" ")" (sepBy (tk ",") simpsRule) def structInst : ParserM Expr := do tk "{" let ls ← sepBy (tk ",") $ Sum.inl <$> (tk ".." *> pExpr) <|> return Sum.inr (← ident <* tk ":=", ← pExpr) tk "}" let mut srcs := #[] let mut fields := #[] for l in ls do match l with | Sum.inl src => srcs := srcs.push src | Sum.inr (n, v) => fields := fields.push (Spanned.dummy n, v) pure $ Expr.structInst none none fields srcs false end Parser
bf6a5564d8bacadb6ad13df3b34ed45cb10bdcb6
94e33a31faa76775069b071adea97e86e218a8ee
/src/analysis/normed_space/ray.lean
992d0ead9f6670da8222f3532eff100029baaaab
[ "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
4,658
lean
/- Copyright (c) 2022 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Yaël Dillies -/ import linear_algebra.ray import analysis.normed_space.basic /-! # Rays in a real normed vector space In this file we prove some lemmas about the `same_ray` predicate in case of a real normed space. In this case, for two vectors `x y` in the same ray, the norm of their sum is equal to the sum of their norms and `∥y∥ • x = ∥x∥ • y`. -/ open real variables {E : Type*} [semi_normed_group E] [normed_space ℝ E] {F : Type*} [normed_group F] [normed_space ℝ F] namespace same_ray variables {x y : E} /-- If `x` and `y` are on the same ray, then the triangle inequality becomes the equality: the norm of `x + y` is the sum of the norms of `x` and `y`. The converse is true for a strictly convex space. -/ lemma norm_add (h : same_ray ℝ x y) : ∥x + y∥ = ∥x∥ + ∥y∥ := begin rcases h.exists_eq_smul with ⟨u, a, b, ha, hb, -, rfl, rfl⟩, rw [← add_smul, norm_smul_of_nonneg (add_nonneg ha hb), norm_smul_of_nonneg ha, norm_smul_of_nonneg hb, add_mul] end lemma norm_sub (h : same_ray ℝ x y) : ∥x - y∥ = |∥x∥ - ∥y∥| := begin rcases h.exists_eq_smul with ⟨u, a, b, ha, hb, -, rfl, rfl⟩, wlog hab : b ≤ a := le_total b a using [a b, b a] tactic.skip, { rw ← sub_nonneg at hab, rw [← sub_smul, norm_smul_of_nonneg hab, norm_smul_of_nonneg ha, norm_smul_of_nonneg hb, ← sub_mul, abs_of_nonneg (mul_nonneg hab (norm_nonneg _))] }, { intros ha hb hab, rw [norm_sub_rev, this hb ha hab.symm, abs_sub_comm] } end lemma norm_smul_eq (h : same_ray ℝ x y) : ∥x∥ • y = ∥y∥ • x := begin rcases h.exists_eq_smul with ⟨u, a, b, ha, hb, -, rfl, rfl⟩, simp only [norm_smul_of_nonneg, *, mul_smul, smul_comm (∥u∥)], apply smul_comm end end same_ray variables {x y : F} lemma norm_inj_on_ray_left (hx : x ≠ 0) : {y | same_ray ℝ x y}.inj_on norm := begin rintro y hy z hz h, rcases hy.exists_nonneg_left hx with ⟨r, hr, rfl⟩, rcases hz.exists_nonneg_left hx with ⟨s, hs, rfl⟩, rw [norm_smul, norm_smul, mul_left_inj' (norm_ne_zero_iff.2 hx), norm_of_nonneg hr, norm_of_nonneg hs] at h, rw h end lemma norm_inj_on_ray_right (hy : y ≠ 0) : {x | same_ray ℝ x y}.inj_on norm := by simpa only [same_ray_comm] using norm_inj_on_ray_left hy lemma same_ray_iff_norm_smul_eq : same_ray ℝ x y ↔ ∥x∥ • y = ∥y∥ • x := ⟨same_ray.norm_smul_eq, λ h, or_iff_not_imp_left.2 $ λ hx, or_iff_not_imp_left.2 $ λ hy, ⟨∥y∥, ∥x∥, norm_pos_iff.2 hy, norm_pos_iff.2 hx, h.symm⟩⟩ /-- Two nonzero vectors `x y` in a real normed space are on the same ray if and only if the unit vectors `∥x∥⁻¹ • x` and `∥y∥⁻¹ • y` are equal. -/ lemma same_ray_iff_inv_norm_smul_eq_of_ne (hx : x ≠ 0) (hy : y ≠ 0) : same_ray ℝ x y ↔ ∥x∥⁻¹ • x = ∥y∥⁻¹ • y := by rw [inv_smul_eq_iff₀, smul_comm, eq_comm, inv_smul_eq_iff₀, same_ray_iff_norm_smul_eq]; rwa norm_ne_zero_iff alias same_ray_iff_inv_norm_smul_eq_of_ne ↔ same_ray.inv_norm_smul_eq _ /-- Two vectors `x y` in a real normed space are on the ray if and only if one of them is zero or the unit vectors `∥x∥⁻¹ • x` and `∥y∥⁻¹ • y` are equal. -/ lemma same_ray_iff_inv_norm_smul_eq : same_ray ℝ x y ↔ x = 0 ∨ y = 0 ∨ ∥x∥⁻¹ • x = ∥y∥⁻¹ • y := begin rcases eq_or_ne x 0 with rfl|hx, { simp [same_ray.zero_left] }, rcases eq_or_ne y 0 with rfl|hy, { simp [same_ray.zero_right] }, simp only [same_ray_iff_inv_norm_smul_eq_of_ne hx hy, *, false_or] end /-- Two vectors of the same norm are on the same ray if and only if they are equal. -/ lemma same_ray_iff_of_norm_eq (h : ∥x∥ = ∥y∥) : same_ray ℝ x y ↔ x = y := begin obtain rfl | hy := eq_or_ne y 0, { rw [norm_zero, norm_eq_zero] at h, exact iff_of_true (same_ray.zero_right _) h }, { exact ⟨λ hxy, norm_inj_on_ray_right hy hxy same_ray.rfl h, λ hxy, hxy ▸ same_ray.rfl⟩ } end lemma not_same_ray_iff_of_norm_eq (h : ∥x∥ = ∥y∥) : ¬ same_ray ℝ x y ↔ x ≠ y := (same_ray_iff_of_norm_eq h).not /-- If two points on the same ray have the same norm, then they are equal. -/ lemma same_ray.eq_of_norm_eq (h : same_ray ℝ x y) (hn : ∥x∥ = ∥y∥) : x = y := (same_ray_iff_of_norm_eq hn).mp h /-- The norms of two vectors on the same ray are equal if and only if they are equal. -/ lemma same_ray.norm_eq_iff (h : same_ray ℝ x y) : ∥x∥ = ∥y∥ ↔ x = y := ⟨h.eq_of_norm_eq, λ h, h ▸ rfl⟩
e6bbb54d4dee58a240d9d3867d44e37a2a73644b
682dc1c167e5900ba3168b89700ae1cf501cfa29
/src/basicmodal/paths.lean
31264bb7cbe6165f6874e905ba98bb06ba5d72a0
[]
no_license
paulaneeley/modal
834558c87f55cdd6d8a29bb46c12f4d1de3239bc
ee5d149d4ecb337005b850bddf4453e56a5daf04
refs/heads/master
1,675,911,819,093
1,609,785,144,000
1,609,785,144,000
270,388,715
13
1
null
null
null
null
UTF-8
Lean
false
false
2,547
lean
/- Copyright (c) 2021 Paula Neeley. All rights reserved. Author: Paula Neeley -/ import data.list data.set.basic variable {α : Type*} def path (R : α → α → Prop) : α → list α → Prop | x [] := true | x (y::ys) := R x y ∧ path y ys def last (R : α → α → Prop) : α → list α → α | x [] := x | x (y::ys) := last y ys def reachable (R : α → α → Prop) (x y : α) : Prop := ∃ l : list α, path R x l ∧ last R x l = y ---------------------- Lemmas about R* ---------------------- lemma reach_right : ∀ x y z : α, ∀ R : α → α → Prop, reachable R x y ∧ R y z → reachable R x z := begin intros x y z R h1, cases h1 with h1 h2, cases h1 with l h1, revert x, induction l, {intros x h, cases h with h1 h3, rw last at h3, existsi ([z] : list α), split, split, apply eq.subst h3.symm, exact h2, trivial, repeat {rw last}}, {intros x h1, cases h1 with h1 h3, cases h1 with h1 h4, have h5 := l_ih l_hd (and.intro h4 h3), cases h5 with l h5, existsi (l_hd::l : list α), split, exact and.intro h1 h5.left, exact h5.right} end lemma ref_close : ∀ x : α, ∀ R : α → α → Prop, reachable R x x := begin intros x R, existsi ([] : list α), split, trivial, rw last end lemma trans_close : ∀ x y z : α, ∀ R : α → α → Prop, reachable R x y ∧ reachable R y z → reachable R x z := begin intros x y z R h, cases h with h1 h2, cases h1 with l1 h1, cases h2 with l2 h2, revert x y z, induction l1, {intros x y z h1 h2, cases h1 with h1 h3, cases h2 with h2 h4, rw last at h3, existsi (l2 : list α), split, apply eq.subst h3.symm, exact h2, apply eq.subst h3.symm, exact h4}, {intros x y z h1 h2, cases h1 with h1 h3, cases h2 with h2 h4, cases h1 with h1 h5, have h6 := l1_ih l1_hd y z (and.intro h5 h3) (and.intro h2 h4), cases h6 with l h6, existsi (l1_hd::l : list α), split, split, exact h1, exact h6.left, exact h6.right} end lemma containsR : ∀ x y : α, ∀ R : α → α → Prop, R x y → reachable R x y := begin intros x y R h, existsi ([y] : list α), split, split, exact h, trivial, repeat {rw last} end open set lemma smallest (R S : α → α → Prop) (reflS : reflexive S) (transS : transitive S) : (∀ x y : α, R x y → S x y) → (∀ x y : α, reachable R x y → S x y) := begin intros h1 x z h2, cases h2 with l h2, cases h2 with h2 h3, revert x z, induction l, {intros x z h2 h3, apply eq.subst h3, exact reflS x}, {intros x z h2 h3, cases h2 with h2 h4, exact (transS ((h1 x) l_hd h2)) (l_ih l_hd z h4 h3)} end
7921a9ebb142a73546bc3111b0322ef3ac725359
534c92d7322a8676cfd1583e26f5946134561b54
/src/Exercises/02_and_or_forall_exists/ch02all.lean
176d79c7e0919a275902ffcd6e997f901fcc2ea0
[ "Apache-2.0" ]
permissive
kbuzzard/mathematics-in-lean
53f387174f04d6077f434e27c407aee9425837f7
3fad7bb7e888dabef94921101af8671b78a4304a
refs/heads/master
1,586,812,457,439
1,546,893,744,000
1,546,893,744,000
163,450,734
8
0
null
null
null
null
UTF-8
Lean
false
false
1,071
lean
variables p q r : Prop example : p ∨ q → q ∨ p := begin sorry end example : p ∨ (q ∨ r) → (p ∨ q) ∨ r := begin sorry end example : p ∧ q → q ∧ p := begin sorry end example : p ∧ (q ∧ r) → (p ∧ q) ∧ r := begin sorry end example : p ∧ (q ∨ r) ↔ (p ∧ q) ∨ (p ∧ r) := begin sorry end example : ¬ (p ∧ q) ↔ ¬ p ∨ ¬ q := begin sorry end example : ¬ (p ∨ q) ↔ ¬ p ∧ ¬ q := begin sorry end example : ¬ (p ↔ ¬ p) := begin sorry end example : p ∨ ¬ p := begin sorry end example : (p → q) ↔ (¬ q → ¬ p) := begin sorry end variables (X : Type) (P Q : X → Prop) -- sorry David example : (∀ x, P x ∧ Q x) → (∀ x, Q x ∧ P x) := begin sorry end example : (∃ x, P x ∨ Q x) → (∃ x, Q x ∨ P x) := begin sorry end example : (∀ x, P x) ∧ (∀ x, Q x) ↔ (∀ x, P x ∧ Q x) := begin sorry end example : (∃ x, P x) ∨ (∃ x, Q x) ↔ (∃ x, P x ∨ Q x) := begin sorry end example : ¬ (∀ x, P x) ↔ ∃ x, ¬ P x := begin sorry end
be57a1142d05704f8ff46cd8b07028a5408518b7
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Compiler/InlineAttrs.lean
ef4f9615154073cda41b6e93288d67bc0082363f
[ "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
2,242
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.Attributes import Lean.Compiler.Util namespace Lean.Compiler inductive InlineAttributeKind where | inline | noinline | macroInline | inlineIfReduce deriving Inhabited, BEq builtin_initialize inlineAttrs : EnumAttributes InlineAttributeKind ← registerEnumAttributes `inlineAttrs [(`inline, "mark definition to always be inlined", InlineAttributeKind.inline), (`inlineIfReduce, "mark definition to be inlined when resultant term after reduction is not a `cases_on` application", InlineAttributeKind.inlineIfReduce), (`noinline, "mark definition to never be inlined", InlineAttributeKind.noinline), (`macroInline, "mark definition to always be inlined before ANF conversion", InlineAttributeKind.macroInline)] (fun declName _ => do let env ← getEnv ofExcept $ checkIsDefinition env declName) private partial def hasInlineAttrAux (env : Environment) (kind : InlineAttributeKind) (n : Name) : Bool := /- We never inline auxiliary declarations created by eager lambda lifting -/ if isEagerLambdaLiftingName n then false else match inlineAttrs.getValue env n with | some k => kind == k | none => if n.isInternal then hasInlineAttrAux env kind n.getPrefix else false @[export lean_has_inline_attribute] def hasInlineAttribute (env : Environment) (n : Name) : Bool := hasInlineAttrAux env InlineAttributeKind.inline n @[export lean_has_inline_if_reduce_attribute] def hasInlineIfReduceAttribute (env : Environment) (n : Name) : Bool := hasInlineAttrAux env InlineAttributeKind.inlineIfReduce n @[export lean_has_noinline_attribute] def hasNoInlineAttribute (env : Environment) (n : Name) : Bool := hasInlineAttrAux env InlineAttributeKind.noinline n @[export lean_has_macro_inline_attribute] def hasMacroInlineAttribute (env : Environment) (n : Name) : Bool := hasInlineAttrAux env InlineAttributeKind.macroInline n def setInlineAttribute (env : Environment) (declName : Name) (kind : InlineAttributeKind) : Except String Environment := inlineAttrs.setValue env declName kind end Lean.Compiler
5fc01c967f30d4e84d6a3b5f519303a0ed1ccb5e
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/dedekind_domain/selmer_group.lean
f729e75d1c898b6e513b2fe3c5dfd27a1e700661
[ "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
9,743
lean
/- Copyright (c) 2022 David Kurniadi Angdinata. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Kurniadi Angdinata -/ import algebra.hom.equiv.type_tags import data.zmod.quotient import ring_theory.dedekind_domain.adic_valuation import ring_theory.norm /-! # Selmer groups of fraction fields of Dedekind domains Let $K$ be the field of fractions of a Dedekind domain $R$. For any set $S$ of prime ideals in the height one spectrum of $R$, and for any natural number $n$, the Selmer group $K(S, n)$ is defined to be the subgroup of the unit group $K^\times$ modulo $n$-th powers where each element has $v$-adic valuation divisible by $n$ for all prime ideals $v$ away from $S$. In other words, this is precisely $$ K(S, n) := \{x(K^\times)^n \in K^\times / (K^\times)^n \ \mid \ \forall v \notin S, \ \mathrm{ord}_v(x) \equiv 0 \pmod n\}. $$ There is a fundamental short exact sequence $$ 1 \to R_S^\times / (R_S^\times)^n \to K(S, n) \to \mathrm{Cl}_S(R)[n] \to 0, $$ where $R_S^\times$ is the $S$-unit group of $R$ and $\mathrm{Cl}_S(R)$ is the $S$-class group of $R$. If the flanking groups are both finite, then $K(S, n)$ is finite by the first isomorphism theorem. Such is the case when $R$ is the ring of integers of a number field $K$, $S$ is finite, and $n$ is positive, in which case $R_S^\times$ is finitely generated by Dirichlet's unit theorem and $\mathrm{Cl}_S(R)$ is finite by the class number theorem. This file defines the Selmer group $K(S, n)$ and some basic facts. ## Main definitions * `is_dedekind_domain.selmer_group`: the Selmer group. * TODO: maps in the sequence. ## Main statements * TODO: proofs of exactness of the sequence. * TODO: proofs of finiteness for global fields. ## Notations * `K⟮S, n⟯`: the Selmer group with parameters `K`, `S`, and `n`. ## Implementation notes The Selmer group is typically defined as a subgroup of the Galois cohomology group $H^1(K, \mu_n)$ with certain local conditions defined by $v$-adic valuations, where $\mu_n$ is the group of $n$-th roots of unity over a separable closure of $K$. Here $H^1(K, \mu_n)$ is identified with $K^\times / (K^\times)^n$ by the long exact sequence from Kummer theory and Hilbert's theorem 90, and the fundamental short exact sequence becomes an easy consequence of the snake lemma. This file will define all the maps explicitly for computational purposes, but isomorphisms to the Galois cohomological definition will be provided when possible. ## References https://doc.sagemath.org/html/en/reference/number_fields/sage/rings/number_field/selmer_group.html ## Tags class group, selmer group, unit group -/ local notation (name := quot) K/n := Kˣ ⧸ (pow_monoid_hom n : Kˣ →* Kˣ).range namespace is_dedekind_domain noncomputable theory open_locale classical discrete_valuation non_zero_divisors universes u v variables {R : Type u} [comm_ring R] [is_domain R] [is_dedekind_domain R] {K : Type v} [field K] [algebra R K] [is_fraction_ring R K] (v : height_one_spectrum R) /-! ### Valuations of non-zero elements -/ namespace height_one_spectrum /-- The multiplicative `v`-adic valuation on `Kˣ`. -/ def valuation_of_ne_zero_to_fun (x : Kˣ) : multiplicative ℤ := let hx := is_localization.sec R⁰ (x : K) in multiplicative.of_add $ (-(associates.mk v.as_ideal).count (associates.mk $ ideal.span {hx.fst}).factors : ℤ) - (-(associates.mk v.as_ideal).count (associates.mk $ ideal.span {(hx.snd : R)}).factors : ℤ) @[simp] lemma valuation_of_ne_zero_to_fun_eq (x : Kˣ) : (v.valuation_of_ne_zero_to_fun x : ℤₘ₀) = v.valuation (x : K) := begin change _ = _ * _, rw [units.coe_inv], change _ = ite _ _ _ * (ite (coe _ = _) _ _)⁻¹, rw [is_localization.to_localization_map_sec, if_neg $ is_localization.sec_fst_ne_zero le_rfl x.ne_zero, if_neg $ non_zero_divisors.coe_ne_zero _], any_goals { exact is_domain.to_nontrivial R }, refl end /-- The multiplicative `v`-adic valuation on `Kˣ`. -/ def valuation_of_ne_zero : Kˣ →* multiplicative ℤ := { to_fun := v.valuation_of_ne_zero_to_fun, map_one' := by { rw [← with_zero.coe_inj, valuation_of_ne_zero_to_fun_eq], exact map_one _ }, map_mul' := λ _ _, by { rw [← with_zero.coe_inj, with_zero.coe_mul], simp only [valuation_of_ne_zero_to_fun_eq], exact map_mul _ _ _ } } @[simp] lemma valuation_of_ne_zero_eq (x : Kˣ) : (v.valuation_of_ne_zero x : ℤₘ₀) = v.valuation (x : K) := valuation_of_ne_zero_to_fun_eq v x @[simp] lemma valuation_of_unit_eq (x : Rˣ) : v.valuation_of_ne_zero (units.map (algebra_map R K : R →* K) x) = 1 := begin rw [← with_zero.coe_inj, valuation_of_ne_zero_eq, units.coe_map, eq_iff_le_not_lt], split, { exact v.valuation_le_one x }, { cases x with x _ hx _, change ¬v.valuation (algebra_map R K x) < 1, apply_fun v.int_valuation at hx, rw [map_one, map_mul] at hx, rw [not_lt, ← hx, ← mul_one $ v.valuation _, valuation_of_algebra_map, mul_le_mul_left₀ $ left_ne_zero_of_mul_eq_one hx], exact v.int_valuation_le_one _ } end local attribute [semireducible] mul_opposite /-- The multiplicative `v`-adic valuation on `Kˣ` modulo `n`-th powers. -/ def valuation_of_ne_zero_mod (n : ℕ) : K/n →* multiplicative (zmod n) := (int.quotient_zmultiples_nat_equiv_zmod n).to_multiplicative.to_monoid_hom.comp $ quotient_group.map (pow_monoid_hom n : Kˣ →* Kˣ).range (add_subgroup.zmultiples (n : ℤ)).to_subgroup v.valuation_of_ne_zero begin rintro _ ⟨x, rfl⟩, exact ⟨v.valuation_of_ne_zero x, by simpa only [pow_monoid_hom_apply, map_pow, int.to_add_pow]⟩ end @[simp] lemma valuation_of_unit_mod_eq (n : ℕ) (x : Rˣ) : v.valuation_of_ne_zero_mod n (units.map (algebra_map R K : R →* K) x : K/n) = 1 := by rw [valuation_of_ne_zero_mod, monoid_hom.comp_apply, ← quotient_group.coe_mk', quotient_group.map_mk', valuation_of_unit_eq, quotient_group.coe_one, map_one] end height_one_spectrum /-! ### Selmer groups -/ variables {S S' : set $ height_one_spectrum R} {n : ℕ} /-- The Selmer group `K⟮S, n⟯`. -/ def selmer_group : subgroup $ K/n := { carrier := {x : K/n | ∀ v ∉ S, (v : height_one_spectrum R).valuation_of_ne_zero_mod n x = 1}, one_mem' := λ _ _, by rw [map_one], mul_mem' := λ _ _ hx hy v hv, by rw [map_mul, hx v hv, hy v hv, one_mul], inv_mem' := λ _ hx v hv, by rw [map_inv, hx v hv, inv_one] } localized "notation K`⟮`S, n`⟯` := @selmer_group _ _ _ _ K _ _ _ S n" in selmer_group namespace selmer_group lemma monotone (hS : S ≤ S') : K⟮S, n⟯ ≤ (K⟮S', n⟯) := λ _ hx v, hx v ∘ mt (@hS v) /-- The multiplicative `v`-adic valuations on `K⟮S, n⟯` for all `v ∈ S`. -/ def valuation : K⟮S, n⟯ →* S → multiplicative (zmod n) := { to_fun := λ x v, (v : height_one_spectrum R).valuation_of_ne_zero_mod n (x : K/n), map_one' := funext $ λ v, map_one _, map_mul' := λ x y, funext $ λ v, map_mul _ x y } lemma valuation_ker_eq : valuation.ker = (K⟮(∅ : set $ height_one_spectrum R), n⟯).subgroup_of (K⟮S, n⟯) := begin ext ⟨_, hx⟩, split, { intros hx' v _, by_cases hv : v ∈ S, { exact congr_fun hx' ⟨v, hv⟩ }, { exact hx v hv } }, { exact λ hx', funext $ λ v, hx' v $ set.not_mem_empty v } end /-- The natural homomorphism from `Rˣ` to `K⟮∅, n⟯`. -/ def from_unit {n : ℕ} : Rˣ →* K⟮(∅ : set $ height_one_spectrum R), n⟯ := { to_fun := λ x, ⟨quotient_group.mk $ units.map (algebra_map R K).to_monoid_hom x, λ v _, v.valuation_of_unit_mod_eq n x⟩, map_one' := by simpa only [map_one], map_mul' := λ _ _, by simpa only [map_mul] } lemma from_unit_ker [hn : fact $ 0 < n] : (@from_unit R _ _ _ K _ _ _ n).ker = (pow_monoid_hom n : Rˣ →* Rˣ).range := begin ext ⟨_, _, _, _⟩, split, { intro hx, rcases (quotient_group.eq_one_iff _).mp (subtype.mk.inj hx) with ⟨⟨v, i, vi, iv⟩, hx⟩, have hv : ↑(_ ^ n : Kˣ) = algebra_map R K _ := congr_arg units.val hx, have hi : ↑(_ ^ n : Kˣ)⁻¹ = algebra_map R K _ := congr_arg units.inv hx, rw [units.coe_pow] at hv, rw [← inv_pow, units.inv_mk, units.coe_pow] at hi, rcases @is_integrally_closed.exists_algebra_map_eq_of_is_integral_pow R _ _ _ _ _ _ _ v _ hn.out (hv.symm ▸ is_integral_algebra_map) with ⟨v', rfl⟩, rcases @is_integrally_closed.exists_algebra_map_eq_of_is_integral_pow R _ _ _ _ _ _ _ i _ hn.out (hi.symm ▸ is_integral_algebra_map) with ⟨i', rfl⟩, rw [← map_mul, map_eq_one_iff _ $ no_zero_smul_divisors.algebra_map_injective R K] at vi, rw [← map_mul, map_eq_one_iff _ $ no_zero_smul_divisors.algebra_map_injective R K] at iv, rw [units.coe_mk, ← map_pow] at hv, exact ⟨⟨v', i', vi, iv⟩, by simpa only [units.ext_iff, pow_monoid_hom_apply, units.coe_pow] using no_zero_smul_divisors.algebra_map_injective R K hv⟩ }, { rintro ⟨_, hx⟩, rw [← hx], exact subtype.mk_eq_mk.mpr ((quotient_group.eq_one_iff _).mpr ⟨_, by simp only [pow_monoid_hom_apply, map_pow]⟩) } end /-- The injection induced by the natural homomorphism from `Rˣ` to `K⟮∅, n⟯`. -/ def from_unit_lift [fact $ 0 < n] : R/n →* K⟮(∅ : set $ height_one_spectrum R), n⟯ := (quotient_group.ker_lift _).comp (quotient_group.quotient_mul_equiv_of_eq from_unit_ker).symm.to_monoid_hom lemma from_unit_lift_injective [fact $ 0 < n] : function.injective $ @from_unit_lift R _ _ _ K _ _ _ n _ := function.injective.comp (quotient_group.ker_lift_injective _) (mul_equiv.injective _) end selmer_group end is_dedekind_domain
bc5873542e3f73c8e92dc72f23f3972863c165de
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/category_theory/sites/dense_subsite.lean
219c23c20a391c0c3c2451e87a62a50a52a47b22
[ "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
16,390
lean
/- Copyright (c) 2021 Andrew Yang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andrew Yang -/ import category_theory.sites.sheaf /-! # Dense subsites We define `cover_dense` functors into sites as functors such that there exists a covering sieve that factors through images of the functor for each object in `D`. We will primarily consider cover-dense functors that are also full, since this notion is in general not well-behaved otherwise. Note that https://ncatlab.org/nlab/show/dense+sub-site indeed has a weaker notion of cover-dense that loosens this requirement, but it would not have all the properties we would need, and some sheafification would be needed for here and there. ## Main results - `category_theory.cover_dense.presheaf_hom`: If `G : C ⥤ (D, K)` is full and cover-dense, then given any presheaf `ℱ` and sheaf `ℱ'` on `D`, and a morphism `α : G ⋙ ℱ ⟶ G ⋙ ℱ'`, we may glue them together to obtain a morphism of presheaves `ℱ ⟶ ℱ'`. - `category_theory.cover_dense.sheaf_iso`: If `ℱ` above is a sheaf and `α` is an iso, then the result is also an iso. - `category_theory.cover_dense.iso_of_restrict_iso`: If `G : C ⥤ (D, K)` is full and cover-dense, then given any sheaves `ℱ, ℱ'` on `D`, and a morphism `α : ℱ ⟶ ℱ'`, then `α` is an iso if `G ⋙ ℱ ⟶ G ⋙ ℱ'` is iso. ## References * [Elephant]: *Sketches of an Elephant*, ℱ. T. Johnstone: C2.2. * https://ncatlab.org/nlab/show/dense+sub-site * https://ncatlab.org/nlab/show/comparison+lemma -/ universes v namespace category_theory variables {C : Type*} [category C] {D : Type*} [category D] {E : Type*} [category E] variables (J : grothendieck_topology C) (K : grothendieck_topology D) variables {L : grothendieck_topology E} /-- An auxiliary structure that witnesses the fact that `f` factors through an image object of `G`. -/ @[nolint has_inhabited_instance] structure presieve.cover_by_image_structure (G : C ⥤ D) {V U : D} (f : V ⟶ U) := (obj : C) (lift : V ⟶ G.obj obj) (map : G.obj obj ⟶ U) (fac' : lift ≫ map = f . obviously) restate_axiom presieve.cover_by_image_structure.fac' attribute [simp, reassoc] presieve.cover_by_image_structure.fac /-- For a functor `G : C ⥤ D`, and an object `U : D`, `presieve.cover_by_image G U` is the presieve of `U` consisting of those arrows that factor through images of `G`. -/ def presieve.cover_by_image (G : C ⥤ D) (U : D) : presieve U := λ Y f, nonempty (presieve.cover_by_image_structure G f) /-- For a functor `G : C ⥤ D`, and an object `U : D`, `sieve.cover_by_image G U` is the sieve of `U` consisting of those arrows that factor through images of `G`. -/ def sieve.cover_by_image (G : C ⥤ D) (U : D) : sieve U := ⟨presieve.cover_by_image G U, λ X Y f ⟨⟨Z, f₁, f₂, (e : _ = _)⟩⟩ g, ⟨⟨Z, g ≫ f₁, f₂, show (g ≫ f₁) ≫ f₂ = g ≫ f, by rw [category.assoc, ← e]⟩⟩⟩ lemma presieve.in_cover_by_image (G : C ⥤ D) {X : D} {Y : C} (f : G.obj Y ⟶ X) : presieve.cover_by_image G X f := ⟨⟨Y, 𝟙 _, f, by simp⟩⟩ /-- A functor `G : (C, J) ⥤ (D, K)` is called `cover_dense` if for each object in `D`, there exists a covering sieve in `D` that factors through images of `G`. This definition can be found in https://ncatlab.org/nlab/show/dense+sub-site Definition 2.2. -/ structure cover_dense (K : grothendieck_topology D) (G : C ⥤ D) : Prop := (is_cover : ∀ (U : D), sieve.cover_by_image G U ∈ K U) open presieve opposite namespace cover_dense variable {K} variables {A : Type*} [category A] {G : C ⥤ D} (H : cover_dense K G) -- this is not marked with `@[ext]` because `H` can not be inferred from the type lemma ext (H : cover_dense K G) (ℱ : SheafOfTypes K) (X : D) {s t : ℱ.val.obj (op X)} (h : ∀ ⦃Y : C⦄ (f : G.obj Y ⟶ X), ℱ.val.map f.op s = ℱ.val.map f.op t) : s = t := begin apply (ℱ.property (sieve.cover_by_image G X) (H.is_cover X)).is_separated_for.ext, rintros Y _ ⟨Z, f₁, f₂, ⟨rfl⟩⟩, simp [h f₂] end lemma functor_pullback_pushforward_covering [full G] (H : cover_dense K G) {X : C} (T : K (G.obj X)) : (T.val.functor_pullback G).functor_pushforward G ∈ K (G.obj X) := begin refine K.superset_covering _ (K.bind_covering T.property (λ Y f Hf, H.is_cover Y)), rintros Y _ ⟨Z, _, f, hf, ⟨W, g, f', ⟨rfl⟩⟩, rfl⟩, use W, use G.preimage (f' ≫ f), use g, split, { simpa using T.val.downward_closed hf f' }, { simp }, end /-- (Implementation). Given an hom between the pullbacks of two sheaves, we can whisker it with `coyoneda` to obtain an hom between the pullbacks of the sheaves of maps from `X`. -/ @[simps] def hom_over {ℱ : Dᵒᵖ ⥤ A} {ℱ' : Sheaf K A} (α : G.op ⋙ ℱ ⟶ G.op ⋙ ℱ'.val) (X : A) : G.op ⋙ (ℱ ⋙ coyoneda.obj (op X)) ⟶ G.op ⋙ (sheaf_over ℱ' X).val := whisker_right α (coyoneda.obj (op X)) /-- (Implementation). Given an iso between the pullbacks of two sheaves, we can whisker it with `coyoneda` to obtain an iso between the pullbacks of the sheaves of maps from `X`. -/ @[simps] def iso_over {ℱ ℱ' : Sheaf K A} (α : G.op ⋙ ℱ.val ≅ G.op ⋙ ℱ'.val) (X : A) : G.op ⋙ (sheaf_over ℱ X).val ≅ G.op ⋙ (sheaf_over ℱ' X).val := iso_whisker_right α (coyoneda.obj (op X)) lemma sheaf_eq_amalgamation (ℱ : Sheaf K A) {X : A} {U : D} {T : sieve U} (hT) (x : family_of_elements _ T) (hx) (t) (h : x.is_amalgamation t) : t = (ℱ.property X T hT).amalgamate x hx := (ℱ.property X T hT).is_separated_for x t _ h ((ℱ.property X T hT).is_amalgamation hx) include H variable [full G] namespace types variables {ℱ : Dᵒᵖ ⥤ Type v} {ℱ' : SheafOfTypes.{v} K} (α : G.op ⋙ ℱ ⟶ G.op ⋙ ℱ'.val) /-- (Implementation). Given a section of `ℱ` on `X`, we can obtain a family of elements valued in `ℱ'` that is defined on a cover generated by the images of `G`. -/ @[simp, nolint unused_arguments] noncomputable def pushforward_family {X} (x : ℱ.obj (op X)) : family_of_elements ℱ'.val (cover_by_image G X) := λ Y f hf, ℱ'.val.map hf.some.lift.op $ α.app (op _) (ℱ.map hf.some.map.op x : _) /-- (Implementation). The `pushforward_family` defined is compatible. -/ lemma pushforward_family_compatible {X} (x : ℱ.obj (op X)) : (pushforward_family H α x).compatible := begin intros Y₁ Y₂ Z g₁ g₂ f₁ f₂ h₁ h₂ e, apply H.ext, intros Y f, simp only [pushforward_family, ← functor_to_types.map_comp_apply, ← op_comp], change (ℱ.map _ ≫ α.app (op _) ≫ ℱ'.val.map _) _ = (ℱ.map _ ≫ α.app (op _) ≫ ℱ'.val.map _) _, rw ← G.image_preimage (f ≫ g₁ ≫ _), rw ← G.image_preimage (f ≫ g₂ ≫ _), erw ← α.naturality (G.preimage _).op, erw ← α.naturality (G.preimage _).op, refine congr_fun _ x, simp only [quiver.hom.unop_op, functor.comp_map, ← op_comp, ← category.assoc, functor.op_map, ← ℱ.map_comp, G.image_preimage], congr' 3, simp [e] end /-- (Implementation). The morphism `ℱ(X) ⟶ ℱ'(X)` given by gluing the `pushforward_family`. -/ noncomputable def app_hom (X : D) : ℱ.obj (op X) ⟶ ℱ'.val.obj (op X) := λ x, (ℱ'.property _ (H.is_cover X)).amalgamate (pushforward_family H α x) (pushforward_family_compatible H α x) @[simp] lemma pushforward_family_apply {X} (x : ℱ.obj (op X)) {Y : C} (f : G.obj Y ⟶ X) : pushforward_family H α x f (presieve.in_cover_by_image G f) = α.app (op Y) (ℱ.map f.op x) := begin unfold pushforward_family, refine congr_fun _ x, rw ← G.image_preimage (nonempty.some _ : presieve.cover_by_image_structure _ _).lift, change ℱ.map _ ≫ α.app (op _) ≫ ℱ'.val.map _ = ℱ.map f.op ≫ α.app (op Y), erw ← α.naturality (G.preimage _).op, simp only [← functor.map_comp, ← category.assoc, functor.comp_map, G.image_preimage, G.op_map, quiver.hom.unop_op, ← op_comp, presieve.cover_by_image_structure.fac], end @[simp] lemma app_hom_restrict {X : D} {Y : C} (f : op X ⟶ op (G.obj Y)) (x) : ℱ'.val.map f (app_hom H α X x) = α.app (op Y) (ℱ.map f x) := begin refine ((ℱ'.property _ (H.is_cover X)).valid_glue (pushforward_family_compatible H α x) f.unop (presieve.in_cover_by_image G f.unop)).trans _, apply pushforward_family_apply end @[simp] lemma app_hom_valid_glue {X : D} {Y : C} (f : op X ⟶ op (G.obj Y)) : app_hom H α X ≫ ℱ'.val.map f = ℱ.map f ≫ α.app (op Y) := by { ext, apply app_hom_restrict } /-- (Implementation). The maps given in `app_iso` is inverse to each other and gives a `ℱ(X) ≅ ℱ'(X)`. -/ @[simps] noncomputable def app_iso {ℱ ℱ' : SheafOfTypes.{v} K} (i : G.op ⋙ ℱ.val ≅ G.op ⋙ ℱ'.val) (X : D) : ℱ.val.obj (op X) ≅ ℱ'.val.obj (op X) := { hom := app_hom H i.hom X, inv := app_hom H i.inv X, hom_inv_id' := by { ext x, apply H.ext, intros Y f, simp }, inv_hom_id' := by { ext x, apply H.ext, intros Y f, simp } } /-- Given an natural transformation `G ⋙ ℱ ⟶ G ⋙ ℱ'` between presheaves of types, where `G` is full and cover-dense, and `ℱ'` is a sheaf, we may obtain a natural transformation between sheaves. -/ @[simps] noncomputable def presheaf_hom (α : G.op ⋙ ℱ ⟶ G.op ⋙ ℱ'.val) : ℱ ⟶ ℱ'.val := { app := λ X, app_hom H α (unop X), naturality' := λ X Y f, begin ext x, apply H.ext ℱ' (unop Y), intros Y' f', simp only [app_hom_restrict, types_comp_apply, ← functor_to_types.map_comp_apply], rw app_hom_restrict H α (f ≫ f'.op : op (unop X) ⟶ _) end } /-- Given an natural isomorphism `G ⋙ ℱ ≅ G ⋙ ℱ'` between presheaves of types, where `G` is full and cover-dense, and `ℱ, ℱ'` are sheaves, we may obtain a natural isomorphism between presheaves. -/ @[simps] noncomputable def presheaf_iso {ℱ ℱ' : SheafOfTypes.{v} K} (i : G.op ⋙ ℱ.val ≅ G.op ⋙ ℱ'.val) : ℱ.val ≅ ℱ'.val := nat_iso.of_components (λ X, app_iso H i (unop X)) (presheaf_hom H i.hom).naturality /-- Given an natural isomorphism `G ⋙ ℱ ≅ G ⋙ ℱ'` between presheaves of types, where `G` is full and cover-dense, and `ℱ, ℱ'` are sheaves, we may obtain a natural isomorphism between sheaves. -/ @[simps] noncomputable def sheaf_iso {ℱ ℱ' : SheafOfTypes.{v} K} (i : G.op ⋙ ℱ.val ≅ G.op ⋙ ℱ'.val) : ℱ ≅ ℱ' := { hom := (presheaf_iso H i).hom, inv := (presheaf_iso H i).inv, hom_inv_id' := (presheaf_iso H i).hom_inv_id, inv_hom_id' := (presheaf_iso H i).inv_hom_id } end types open types variables {ℱ : Dᵒᵖ ⥤ A} {ℱ' : Sheaf K A} /-- (Implementation). The sheaf map given in `types.sheaf_hom` is natural in terms of `X`. -/ @[simps] noncomputable def sheaf_coyoneda_hom (α : G.op ⋙ ℱ ⟶ G.op ⋙ ℱ'.val) : coyoneda ⋙ (whiskering_left Dᵒᵖ A Type*).obj ℱ ⟶ coyoneda ⋙ (whiskering_left Dᵒᵖ A Type*).obj ℱ'.val := { app := λ X, presheaf_hom H (hom_over α (unop X)), naturality' := λ X Y f, begin ext U x, change app_hom H (hom_over α (unop Y)) (unop U) (f.unop ≫ x) = f.unop ≫ app_hom H (hom_over α (unop X)) (unop U) x, symmetry, apply sheaf_eq_amalgamation, apply H.is_cover, intros Y' f' hf', change unop X ⟶ ℱ.obj (op (unop _)) at x, simp only [pushforward_family, functor.comp_map, coyoneda_obj_map, hom_over_app, category.assoc], congr' 1, conv_lhs { rw ← hf'.some.fac }, simp only [← category.assoc, op_comp, functor.map_comp], congr' 1, refine (app_hom_restrict H (hom_over α (unop X)) hf'.some.map.op x).trans _, simp end } /-- (Implementation). `sheaf_coyoneda_hom` but the order of the arguments of the functor are swapped. -/ noncomputable def sheaf_yoneda_hom (α : G.op ⋙ ℱ ⟶ G.op ⋙ ℱ'.val) : ℱ ⋙ yoneda ⟶ ℱ'.val ⋙ yoneda := begin let α := sheaf_coyoneda_hom H α, refine { app := _, naturality' := _ }, { intro U, refine { app := λ X, (α.app X).app U, naturality' := λ X Y f, by simpa using congr_app (α.naturality f) U } }, { intros U V i, ext X x, exact congr_fun ((α.app X).naturality i) x }, end /-- Given an natural transformation `G ⋙ ℱ ⟶ G ⋙ ℱ'` between presheaves of arbitrary category, where `G` is full and cover-dense, and `ℱ'` is a sheaf, we may obtain a natural transformation between presheaves. -/ noncomputable def sheaf_hom (α : G.op ⋙ ℱ ⟶ G.op ⋙ ℱ'.val) : ℱ ⟶ ℱ'.val := let α' := sheaf_yoneda_hom H α in { app := λ X, yoneda.preimage (α'.app X), naturality' := λ X Y f, yoneda.map_injective (by simpa using α'.naturality f) } /-- Given an natural isomorphism `G ⋙ ℱ ≅ G ⋙ ℱ'` between presheaves of arbitrary category, where `G` is full and cover-dense, and `ℱ', ℱ` are sheaves, we may obtain a natural isomorphism between presheaves. -/ @[simps] noncomputable def presheaf_iso {ℱ ℱ' : Sheaf K A} (i : G.op ⋙ ℱ.val ≅ G.op ⋙ ℱ'.val) : ℱ.val ≅ ℱ'.val := begin haveI : ∀ (X : Dᵒᵖ), is_iso ((sheaf_hom H i.hom).app X), { intro X, apply is_iso_of_reflects_iso _ yoneda, use (sheaf_yoneda_hom H i.inv).app X, split; ext x : 2; simp only [sheaf_hom, nat_trans.comp_app, nat_trans.id_app, functor.image_preimage], exact ((presheaf_iso H (iso_over i (unop x))).app X).hom_inv_id, exact ((presheaf_iso H (iso_over i (unop x))).app X).inv_hom_id, apply_instance }, haveI : is_iso (sheaf_hom H i.hom) := by apply nat_iso.is_iso_of_is_iso_app, apply as_iso (sheaf_hom H i.hom), end /-- Given an natural isomorphism `G ⋙ ℱ ≅ G ⋙ ℱ'` between presheaves of arbitrary category, where `G` is full and cover-dense, and `ℱ', ℱ` are sheaves, we may obtain a natural isomorphism between presheaves. -/ @[simps] noncomputable def sheaf_iso {ℱ ℱ' : Sheaf K A} (i : G.op ⋙ ℱ.val ≅ G.op ⋙ ℱ'.val) : ℱ ≅ ℱ' := { hom := (presheaf_iso H i).hom, inv := (presheaf_iso H i).inv, hom_inv_id' := (presheaf_iso H i).hom_inv_id, inv_hom_id' := (presheaf_iso H i).inv_hom_id } /-- The constructed `sheaf_hom α` is equal to `α` when restricted onto `C`. -/ lemma sheaf_hom_restrict_eq (α : G.op ⋙ ℱ ⟶ G.op ⋙ ℱ'.val) : whisker_left G.op (sheaf_hom H α) = α := begin ext X, apply yoneda.map_injective, ext U, erw yoneda.image_preimage, symmetry, change (show (ℱ'.val ⋙ coyoneda.obj (op (unop U))).obj (op (G.obj (unop X))), from _) = _, apply sheaf_eq_amalgamation ℱ' (H.is_cover _), intros Y f hf, conv_lhs { rw ← hf.some.fac }, simp only [pushforward_family, functor.comp_map, yoneda_map_app, coyoneda_obj_map, op_comp, functor_to_types.map_comp_apply, hom_over_app, ← category.assoc], congr' 1, simp only [category.assoc], congr' 1, rw ← G.image_preimage hf.some.map, symmetry, apply α.naturality (G.preimage hf.some.map).op, apply_instance end /-- If the pullback map is obtained via whiskering, then the result `sheaf_hom (whisker_left G.op α)` is equal to `α`. -/ lemma sheaf_hom_eq (α : ℱ ⟶ ℱ'.val) : sheaf_hom H (whisker_left G.op α) = α := begin ext X, apply yoneda.map_injective, ext U, erw yoneda.image_preimage, symmetry, change (show (ℱ'.val ⋙ coyoneda.obj (op (unop U))).obj (op (unop X)), from _) = _, apply sheaf_eq_amalgamation ℱ' (H.is_cover _), intros Y f hf, conv_lhs { rw ← hf.some.fac }, simp [-presieve.cover_by_image_structure.fac], erw α.naturality_assoc, refl, apply_instance end /-- A full and cover-dense functor `G` induces an equivalence between morphisms into a sheaf and morphisms over the restrictions via `G`. -/ noncomputable def restrict_hom_equiv_hom : (G.op ⋙ ℱ ⟶ G.op ⋙ ℱ'.val) ≃ (ℱ ⟶ ℱ'.val) := { to_fun := sheaf_hom H, inv_fun := whisker_left G.op, left_inv := sheaf_hom_restrict_eq H, right_inv := sheaf_hom_eq H } /-- Given a full and cover-dense functor `G` and a natural transformation of sheaves `α : ℱ ⟶ ℱ'`, if the pullback of `α` along `G` is iso, then `α` is also iso. -/ lemma iso_of_restrict_iso {ℱ ℱ' : Sheaf K A} (α : ℱ ⟶ ℱ') (i : is_iso (whisker_left G.op α)) : is_iso α := begin convert is_iso.of_iso (sheaf_iso H (as_iso (whisker_left G.op α))), symmetry, apply sheaf_hom_eq end end cover_dense end category_theory
f03111defcb1e5a05cfee9854df25cf52cba9aa8
c777c32c8e484e195053731103c5e52af26a25d1
/src/topology/sheaves/stalks.lean
f6b7277e45807da29b0ba7a18dac76263267301d
[ "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
26,674
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Justus Springer -/ import topology.category.Top.open_nhds import topology.sheaves.presheaf import topology.sheaves.sheaf_condition.unique_gluing import category_theory.adjunction.evaluation import category_theory.limits.types import category_theory.limits.preserves.filtered import category_theory.limits.final import tactic.elementwise import algebra.category.Ring.colimits import category_theory.sites.pushforward /-! # Stalks For a presheaf `F` on a topological space `X`, valued in some category `C`, the *stalk* of `F` at the point `x : X` is defined as the colimit of the composition of the inclusion of categories `(nhds x)ᵒᵖ ⥤ (opens X)ᵒᵖ` and the functor `F : (opens X)ᵒᵖ ⥤ C`. For an open neighborhood `U` of `x`, we define the map `F.germ x : F.obj (op U) ⟶ F.stalk x` as the canonical morphism into this colimit. Taking stalks is functorial: For every point `x : X` we define a functor `stalk_functor C x`, sending presheaves on `X` to objects of `C`. Furthermore, for a map `f : X ⟶ Y` between topological spaces, we define `stalk_pushforward` as the induced map on the stalks `(f _* ℱ).stalk (f x) ⟶ ℱ.stalk x`. Some lemmas about stalks and germs only hold for certain classes of concrete categories. A basic property of forgetful functors of categories of algebraic structures (like `Mon`, `CommRing`,...) is that they preserve filtered colimits. Since stalks are filtered colimits, this ensures that the stalks of presheaves valued in these categories behave exactly as for `Type`-valued presheaves. For example, in `germ_exist` we prove that in such a category, every element of the stalk is the germ of a section. Furthermore, if we require the forgetful functor to reflect isomorphisms and preserve limits (as is the case for most algebraic structures), we have access to the unique gluing API and can prove further properties. Most notably, in `is_iso_iff_stalk_functor_map_iso`, we prove that in such a category, a morphism of sheaves is an isomorphism if and only if all of its stalk maps are isomorphisms. See also the definition of "algebraic structures" in the stacks project: https://stacks.math.columbia.edu/tag/007L -/ noncomputable theory universes v u v' u' open category_theory open Top open category_theory.limits open topological_space open opposite variables {C : Type u} [category.{v} C] variables [has_colimits.{v} C] variables {X Y Z : Top.{v}} namespace Top.presheaf variables (C) /-- Stalks are functorial with respect to morphisms of presheaves over a fixed `X`. -/ def stalk_functor (x : X) : X.presheaf C ⥤ C := ((whiskering_left _ _ C).obj (open_nhds.inclusion x).op) ⋙ colim variables {C} /-- The stalk of a presheaf `F` at a point `x` is calculated as the colimit of the functor nbhds x ⥤ opens F.X ⥤ C -/ def stalk (ℱ : X.presheaf C) (x : X) : C := (stalk_functor C x).obj ℱ -- -- colimit ((open_nhds.inclusion x).op ⋙ ℱ) @[simp] lemma stalk_functor_obj (ℱ : X.presheaf C) (x : X) : (stalk_functor C x).obj ℱ = ℱ.stalk x := rfl /-- The germ of a section of a presheaf over an open at a point of that open. -/ def germ (F : X.presheaf C) {U : opens X} (x : U) : F.obj (op U) ⟶ stalk F x := colimit.ι ((open_nhds.inclusion x.1).op ⋙ F) (op ⟨U, x.2⟩) @[simp, elementwise] lemma germ_res (F : X.presheaf C) {U V : opens X} (i : U ⟶ V) (x : U) : F.map i.op ≫ germ F x = germ F (i x : V) := let i' : (⟨U, x.2⟩ : open_nhds x.1) ⟶ ⟨V, (i x : V).2⟩ := i in colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op /-- A morphism from the stalk of `F` at `x` to some object `Y` is completely determined by its composition with the `germ` morphisms. -/ lemma stalk_hom_ext (F : X.presheaf C) {x} {Y : C} {f₁ f₂ : F.stalk x ⟶ Y} (ih : ∀ (U : opens X) (hxU : x ∈ U), F.germ ⟨x, hxU⟩ ≫ f₁ = F.germ ⟨x, hxU⟩ ≫ f₂) : f₁ = f₂ := colimit.hom_ext $ λ U, by { induction U using opposite.rec, cases U with U hxU, exact ih U hxU } @[simp, reassoc, elementwise] lemma stalk_functor_map_germ {F G : X.presheaf C} (U : opens X) (x : U) (f : F ⟶ G) : germ F x ≫ (stalk_functor C x.1).map f = f.app (op U) ≫ germ G x := colimit.ι_map (whisker_left ((open_nhds.inclusion x.1).op) f) (op ⟨U, x.2⟩) variables (C) /-- For a presheaf `F` on a space `X`, a continuous map `f : X ⟶ Y` induces a morphisms between the stalk of `f _ * F` at `f x` and the stalk of `F` at `x`. -/ def stalk_pushforward (f : X ⟶ Y) (F : X.presheaf C) (x : X) : (f _* F).stalk (f x) ⟶ F.stalk x := begin -- This is a hack; Lean doesn't like to elaborate the term written directly. transitivity, swap, exact colimit.pre _ (open_nhds.map f x).op, exact colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) F), end @[simp, elementwise, reassoc] lemma stalk_pushforward_germ (f : X ⟶ Y) (F : X.presheaf C) (U : opens Y) (x : (opens.map f).obj U) : (f _* F).germ ⟨f x, x.2⟩ ≫ F.stalk_pushforward C f x = F.germ x := begin rw [stalk_pushforward, germ, colimit.ι_map_assoc, colimit.ι_pre, whisker_right_app], erw [category_theory.functor.map_id, category.id_comp], refl, end -- Here are two other potential solutions, suggested by @fpvandoorn at -- <https://github.com/leanprover-community/mathlib/pull/1018#discussion_r283978240> -- However, I can't get the subsequent two proofs to work with either one. -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- colim.map ((functor.associator _ _ _).inv ≫ -- whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op -- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) : -- (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x := -- (colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) : -- colim.obj ((open_nhds.inclusion (f x) ⋙ opens.map f).op ⋙ ℱ) ⟶ _) ≫ -- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op namespace stalk_pushforward local attribute [tidy] tactic.op_induction' @[simp] lemma id (ℱ : X.presheaf C) (x : X) : ℱ.stalk_pushforward C (𝟙 X) x = (stalk_functor C x).map ((pushforward.id ℱ).hom) := begin dsimp [stalk_pushforward, stalk_functor], ext1, tactic.op_induction', rcases j with ⟨⟨_, _⟩, _⟩, rw [colimit.ι_map_assoc, colimit.ι_map, colimit.ι_pre, whisker_left_app, whisker_right_app, pushforward.id_hom_app, eq_to_hom_map, eq_to_hom_refl], dsimp, -- FIXME A simp lemma which unfortunately doesn't fire: erw [category_theory.functor.map_id], end -- This proof is sadly not at all robust: -- having to use `erw` at all is a bad sign. @[simp] lemma comp (ℱ : X.presheaf C) (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) : ℱ.stalk_pushforward C (f ≫ g) x = ((f _* ℱ).stalk_pushforward C g (f x)) ≫ (ℱ.stalk_pushforward C f x) := begin dsimp [stalk_pushforward, stalk_functor], ext U, induction U using opposite.rec, rcases U with ⟨⟨_, _⟩, _⟩, simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc, whisker_right_app, category.assoc], dsimp, -- FIXME: Some of these are simp lemmas, but don't fire successfully: erw [category_theory.functor.map_id, category.id_comp, category.id_comp, category.id_comp, colimit.ι_pre, colimit.ι_pre], refl, end lemma stalk_pushforward_iso_of_open_embedding {f : X ⟶ Y} (hf : open_embedding f) (F : X.presheaf C) (x : X) : is_iso (F.stalk_pushforward _ f x) := begin haveI := functor.initial_of_adjunction (hf.is_open_map.adjunction_nhds x), convert is_iso.of_iso ((functor.final.colimit_iso (hf.is_open_map.functor_nhds x).op ((open_nhds.inclusion (f x)).op ⋙ f _* F) : _).symm ≪≫ colim.map_iso _), swap, { fapply nat_iso.of_components, { intro U, refine F.map_iso (eq_to_iso _), dsimp only [functor.op], exact congr_arg op (opens.ext $ set.preimage_image_eq (unop U).1.1 hf.inj) }, { intros U V i, erw [← F.map_comp, ← F.map_comp], congr } }, { ext U, rw ← iso.comp_inv_eq, erw colimit.ι_map_assoc, rw [colimit.ι_pre, category.assoc], erw [colimit.ι_map_assoc, colimit.ι_pre, ← F.map_comp_assoc], apply colimit.w ((open_nhds.inclusion (f x)).op ⋙ f _* F) _, dsimp only [functor.op], refine ((hom_of_le _).op : op (unop U) ⟶ _), exact set.image_preimage_subset _ _ }, end end stalk_pushforward section stalk_pullback /-- The morphism `ℱ_{f x} ⟶ (f⁻¹ℱ)ₓ` that factors through `(f_*f⁻¹ℱ)_{f x}`. -/ def stalk_pullback_hom (f : X ⟶ Y) (F : Y.presheaf C) (x : X) : F.stalk (f x) ⟶ (pullback_obj f F).stalk x := (stalk_functor _ (f x)).map ((pushforward_pullback_adjunction C f).unit.app F) ≫ stalk_pushforward _ _ _ x /-- The morphism `(f⁻¹ℱ)(U) ⟶ ℱ_{f(x)}` for some `U ∋ x`. -/ def germ_to_pullback_stalk (f : X ⟶ Y) (F : Y.presheaf C) (U : opens X) (x : U) : (pullback_obj f F).obj (op U) ⟶ F.stalk (f x) := colimit.desc (Lan.diagram (opens.map f).op F (op U)) { X := F.stalk (f x), ι := { app := λ V, F.germ ⟨f x, V.hom.unop.le x.2⟩, naturality' := λ _ _ i, by { erw category.comp_id, exact F.germ_res i.left.unop _ } } } /-- The morphism `(f⁻¹ℱ)ₓ ⟶ ℱ_{f(x)}`. -/ def stalk_pullback_inv (f : X ⟶ Y) (F : Y.presheaf C) (x : X) : (pullback_obj f F).stalk x ⟶ F.stalk (f x) := colimit.desc ((open_nhds.inclusion x).op ⋙ presheaf.pullback_obj f F) { X := F.stalk (f x), ι := { app := λ U, F.germ_to_pullback_stalk _ f (unop U).1 ⟨x, (unop U).2⟩, naturality' := λ _ _ _, by { erw [colimit.pre_desc, category.comp_id], congr } } } /-- The isomorphism `ℱ_{f(x)} ≅ (f⁻¹ℱ)ₓ`. -/ def stalk_pullback_iso (f : X ⟶ Y) (F : Y.presheaf C) (x : X) : F.stalk (f x) ≅ (pullback_obj f F).stalk x := { hom := stalk_pullback_hom _ _ _ _, inv := stalk_pullback_inv _ _ _ _, hom_inv_id' := begin delta stalk_pullback_hom stalk_pullback_inv stalk_functor presheaf.pullback stalk_pushforward germ_to_pullback_stalk germ, ext j, induction j using opposite.rec, cases j, simp only [topological_space.open_nhds.inclusion_map_iso_inv, whisker_right_app, whisker_left_app, whiskering_left_obj_map, functor.comp_map, colimit.ι_map_assoc, nat_trans.op_id, Lan_obj_map, pushforward_pullback_adjunction_unit_app_app, category.assoc, colimit.ι_pre_assoc], erw [colimit.ι_desc, colimit.pre_desc, colimit.ι_desc, category.comp_id], simpa end, inv_hom_id' := begin delta stalk_pullback_hom stalk_pullback_inv stalk_functor presheaf.pullback stalk_pushforward, ext U j, induction U using opposite.rec, cases U, cases j, rcases j_right with ⟨⟨⟩⟩, erw [colimit.map_desc, colimit.map_desc, colimit.ι_desc_assoc, colimit.ι_desc_assoc, colimit.ι_desc, category.comp_id], simp only [cocone.whisker_ι, colimit.cocone_ι, open_nhds.inclusion_map_iso_inv, cocones.precompose_obj_ι, whisker_right_app, whisker_left_app, nat_trans.comp_app, whiskering_left_obj_map, nat_trans.op_id, Lan_obj_map, pushforward_pullback_adjunction_unit_app_app], erw ←colimit.w _ (@hom_of_le (open_nhds x) _ ⟨_, U_property⟩ ⟨(opens.map f).obj (unop j_left), j_hom.unop.le U_property⟩ j_hom.unop.le).op, erw colimit.ι_pre_assoc (Lan.diagram _ F _) (costructured_arrow.map _), erw colimit.ι_pre_assoc (Lan.diagram _ F _) (costructured_arrow.map _), congr, simp only [category.assoc, costructured_arrow.map_mk], delta costructured_arrow.mk, congr, end } end stalk_pullback section stalk_specializes variables {C} /-- If `x` specializes to `y`, then there is a natural map `F.stalk y ⟶ F.stalk x`. -/ noncomputable def stalk_specializes (F : X.presheaf C) {x y : X} (h : x ⤳ y) : F.stalk y ⟶ F.stalk x := begin refine colimit.desc _ ⟨_,λ U, _,_⟩, { exact colimit.ι ((open_nhds.inclusion x).op ⋙ F) (op ⟨(unop U).1, (specializes_iff_forall_open.mp h _ (unop U).1.2 (unop U).2 : _)⟩) }, { intros U V i, dsimp, rw category.comp_id, let U' : open_nhds x := ⟨_, (specializes_iff_forall_open.mp h _ (unop U).1.2 (unop U).2 : _)⟩, let V' : open_nhds x := ⟨_, (specializes_iff_forall_open.mp h _ (unop V).1.2 (unop V).2 : _)⟩, exact colimit.w ((open_nhds.inclusion x).op ⋙ F) (show V' ⟶ U', from i.unop).op } end @[simp, reassoc, elementwise] lemma germ_stalk_specializes (F : X.presheaf C) {U : opens X} {y : U} {x : X} (h : x ⤳ y) : F.germ y ≫ F.stalk_specializes h = F.germ (⟨x, h.mem_open U.is_open y.prop⟩ : U) := colimit.ι_desc _ _ @[simp, reassoc, elementwise] lemma germ_stalk_specializes' (F : X.presheaf C) {U : opens X} {x y : X} (h : x ⤳ y) (hy : y ∈ U) : F.germ ⟨y, hy⟩ ≫ F.stalk_specializes h = F.germ ⟨x, h.mem_open U.is_open hy⟩ := colimit.ι_desc _ _ @[simp] lemma stalk_specializes_refl {C : Type*} [category C] [limits.has_colimits C] {X : Top} (F : X.presheaf C) (x : X) : F.stalk_specializes (specializes_refl x) = 𝟙 _ := F.stalk_hom_ext $ λ _ _, by { dsimp, simpa } @[simp, reassoc, elementwise] lemma stalk_specializes_comp {C : Type*} [category C] [limits.has_colimits C] {X : Top} (F : X.presheaf C) {x y z : X} (h : x ⤳ y) (h' : y ⤳ z) : F.stalk_specializes h' ≫ F.stalk_specializes h = F.stalk_specializes (h.trans h') := F.stalk_hom_ext $ λ _ _, by simp @[simp, reassoc, elementwise] lemma stalk_specializes_stalk_functor_map {F G : X.presheaf C} (f : F ⟶ G) {x y : X} (h : x ⤳ y) : F.stalk_specializes h ≫ (stalk_functor C x).map f = (stalk_functor C y).map f ≫ G.stalk_specializes h := by { ext, delta stalk_functor, simpa [stalk_specializes] } @[simp, reassoc, elementwise] lemma stalk_specializes_stalk_pushforward (f : X ⟶ Y) (F : X.presheaf C) {x y : X} (h : x ⤳ y) : (f _* F).stalk_specializes (f.map_specializes h) ≫ F.stalk_pushforward _ f x = F.stalk_pushforward _ f y ≫ F.stalk_specializes h := by { ext, delta stalk_pushforward, simpa [stalk_specializes] } /-- The stalks are isomorphic on inseparable points -/ @[simps] def stalk_congr {X : Top} {C : Type*} [category C] [has_colimits C] (F : X.presheaf C) {x y : X} (e : inseparable x y) : F.stalk x ≅ F.stalk y := ⟨F.stalk_specializes e.ge, F.stalk_specializes e.le, by simp, by simp⟩ end stalk_specializes section concrete variables {C} variables [concrete_category.{v} C] local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun @[ext] lemma germ_ext (F : X.presheaf C) {U V : opens X} {x : X} {hxU : x ∈ U} {hxV : x ∈ V} (W : opens X) (hxW : x ∈ W) (iWU : W ⟶ U) (iWV : W ⟶ V) {sU : F.obj (op U)} {sV : F.obj (op V)} (ih : F.map iWU.op sU = F.map iWV.op sV) : F.germ ⟨x, hxU⟩ sU = F.germ ⟨x, hxV⟩ sV := by erw [← F.germ_res iWU ⟨x, hxW⟩, ← F.germ_res iWV ⟨x, hxW⟩, comp_apply, comp_apply, ih] variables [preserves_filtered_colimits (forget C)] /-- For presheaves valued in a concrete category whose forgetful functor preserves filtered colimits, every element of the stalk is the germ of a section. -/ lemma germ_exist (F : X.presheaf C) (x : X) (t : stalk F x) : ∃ (U : opens X) (m : x ∈ U) (s : F.obj (op U)), F.germ ⟨x, m⟩ s = t := begin obtain ⟨U, s, e⟩ := types.jointly_surjective.{v v} _ (is_colimit_of_preserves (forget C) (colimit.is_colimit _)) t, revert s e, rw [(show U = op (unop U), from rfl)], generalize : unop U = V, clear U, cases V with V m, intros s e, exact ⟨V, m, s, e⟩, end lemma germ_eq (F : X.presheaf C) {U V : opens X} (x : X) (mU : x ∈ U) (mV : x ∈ V) (s : F.obj (op U)) (t : F.obj (op V)) (h : germ F ⟨x, mU⟩ s = germ F ⟨x, mV⟩ t) : ∃ (W : opens X) (m : x ∈ W) (iU : W ⟶ U) (iV : W ⟶ V), F.map iU.op s = F.map iV.op t := begin obtain ⟨W, iU, iV, e⟩ := (types.filtered_colimit.is_colimit_eq_iff.{v v} _ (is_colimit_of_preserves _ (colimit.is_colimit ((open_nhds.inclusion x).op ⋙ F)))).mp h, exact ⟨(unop W).1, (unop W).2, iU.unop, iV.unop, e⟩, end lemma stalk_functor_map_injective_of_app_injective {F G : presheaf C X} (f : F ⟶ G) (h : ∀ U : opens X, function.injective (f.app (op U))) (x : X) : function.injective ((stalk_functor C x).map f) := λ s t hst, begin rcases germ_exist F x s with ⟨U₁, hxU₁, s, rfl⟩, rcases germ_exist F x t with ⟨U₂, hxU₂, t, rfl⟩, simp only [stalk_functor_map_germ_apply _ ⟨x,_⟩] at hst, obtain ⟨W, hxW, iWU₁, iWU₂, heq⟩ := G.germ_eq x hxU₁ hxU₂ _ _ hst, rw [← comp_apply, ← comp_apply, ← f.naturality, ← f.naturality, comp_apply, comp_apply] at heq, replace heq := h W heq, convert congr_arg (F.germ ⟨x,hxW⟩) heq, exacts [(F.germ_res_apply iWU₁ ⟨x,hxW⟩ s).symm, (F.germ_res_apply iWU₂ ⟨x,hxW⟩ t).symm], end variables [has_limits C] [preserves_limits (forget C)] [reflects_isomorphisms (forget C)] /-- Let `F` be a sheaf valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then two sections who agree on every stalk must be equal. -/ lemma section_ext (F : sheaf C X) (U : opens X) (s t : F.1.obj (op U)) (h : ∀ x : U, F.presheaf.germ x s = F.presheaf.germ x t) : s = t := begin -- We use `germ_eq` and the axiom of choice, to pick for every point `x` a neighbourhood -- `V x`, such that the restrictions of `s` and `t` to `V x` coincide. choose V m i₁ i₂ heq using λ x : U, F.presheaf.germ_eq x.1 x.2 x.2 s t (h x), -- Since `F` is a sheaf, we can prove the equality locally, if we can show that these -- neighborhoods form a cover of `U`. apply F.eq_of_locally_eq' V U i₁, { intros x hxU, rw [opens.mem_supr], exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ }, { intro x, rw [heq, subsingleton.elim (i₁ x) (i₂ x)] } end /- Note that the analogous statement for surjectivity is false: Surjectivity on stalks does not imply surjectivity of the components of a sheaf morphism. However it does imply that the morphism is an epi, but this fact is not yet formalized. -/ lemma app_injective_of_stalk_functor_map_injective {F : sheaf C X} {G : presheaf C X} (f : F.1 ⟶ G) (U : opens X) (h : ∀ x : U, function.injective ((stalk_functor C x.val).map f)) : function.injective (f.app (op U)) := λ s t hst, section_ext F _ _ _ $ λ x, h x $ by rw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply, hst] lemma app_injective_iff_stalk_functor_map_injective {F : sheaf C X} {G : presheaf C X} (f : F.1 ⟶ G) : (∀ x : X, function.injective ((stalk_functor C x).map f)) ↔ (∀ U : opens X, function.injective (f.app (op U))) := ⟨λ h U, app_injective_of_stalk_functor_map_injective f U (λ x, h x.1), stalk_functor_map_injective_of_app_injective f⟩ instance stalk_functor_preserves_mono (x : X) : functor.preserves_monomorphisms (sheaf.forget C X ⋙ stalk_functor C x) := ⟨λ 𝓐 𝓑 f m, concrete_category.mono_of_injective _ $ (app_injective_iff_stalk_functor_map_injective f.1).mpr (λ c, (@@concrete_category.mono_iff_injective_of_preserves_pullback _ _ (f.1.app (op c)) _).mp ((nat_trans.mono_iff_mono_app _ f.1).mp (@@category_theory.presheaf_mono_of_mono _ _ _ _ _ _ _ _ _ _ _ m) $ op c)) x⟩ lemma stalk_mono_of_mono {F G : sheaf C X} (f : F ⟶ G) [mono f] : Π x, mono $ (stalk_functor C x).map f.1 := λ x, by convert functor.map_mono (sheaf.forget.{v} C X ⋙ stalk_functor C x) f lemma mono_of_stalk_mono {F G : sheaf C X} (f : F ⟶ G) [Π x, mono $ (stalk_functor C x).map f.1] : mono f := (Sheaf.hom.mono_iff_presheaf_mono _ _ _).mpr $ (nat_trans.mono_iff_mono_app _ _).mpr $ λ U, (concrete_category.mono_iff_injective_of_preserves_pullback _).mpr $ app_injective_of_stalk_functor_map_injective f.1 U.unop $ λ ⟨x, hx⟩, (concrete_category.mono_iff_injective_of_preserves_pullback _).mp $ infer_instance lemma mono_iff_stalk_mono {F G : sheaf C X} (f : F ⟶ G) : mono f ↔ ∀ x, mono ((stalk_functor C x).map f.1) := ⟨by { introI m, exact stalk_mono_of_mono _ }, by { introI m, exact mono_of_stalk_mono _ }⟩ /-- For surjectivity, we are given an arbitrary section `t` and need to find a preimage for it. We claim that it suffices to find preimages *locally*. That is, for each `x : U` we construct a neighborhood `V ≤ U` and a section `s : F.obj (op V))` such that `f.app (op V) s` and `t` agree on `V`. -/ lemma app_surjective_of_injective_of_locally_surjective {F G : sheaf C X} (f : F ⟶ G) (U : opens X) (hinj : ∀ x : U, function.injective ((stalk_functor C x.1).map f.1)) (hsurj : ∀ (t) (x : U), ∃ (V : opens X) (m : x.1 ∈ V) (iVU : V ⟶ U) (s : F.1.obj (op V)), f.1.app (op V) s = G.1.map iVU.op t) : function.surjective (f.1.app (op U)) := begin intro t, -- We use the axiom of choice to pick around each point `x` an open neighborhood `V` and a -- preimage under `f` on `V`. choose V mV iVU sf heq using hsurj t, -- These neighborhoods clearly cover all of `U`. have V_cover : U ≤ supr V, { intros x hxU, rw [opens.mem_supr], exact ⟨⟨x, hxU⟩, mV ⟨x, hxU⟩⟩ }, -- Since `F` is a sheaf, we can glue all the local preimages together to get a global preimage. obtain ⟨s, s_spec, -⟩ := F.exists_unique_gluing' V U iVU V_cover sf _, { use s, apply G.eq_of_locally_eq' V U iVU V_cover, intro x, rw [← comp_apply, ← f.1.naturality, comp_apply, s_spec, heq] }, { intros x y, -- What's left to show here is that the secions `sf` are compatible, i.e. they agree on -- the intersections `V x ⊓ V y`. We prove this by showing that all germs are equal. apply section_ext, intro z, -- Here, we need to use injectivity of the stalk maps. apply (hinj ⟨z, (iVU x).le ((inf_le_left : V x ⊓ V y ≤ V x) z.2)⟩), dsimp only, erw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply], simp_rw [← comp_apply, f.1.naturality, comp_apply, heq, ← comp_apply, ← G.1.map_comp], refl } end lemma app_surjective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G) (U : opens X) (h : ∀ x : U, function.bijective ((stalk_functor C x.val).map f.1)) : function.surjective (f.1.app (op U)) := begin refine app_surjective_of_injective_of_locally_surjective f U (λ x, (h x).1) (λ t x, _), -- Now we need to prove our initial claim: That we can find preimages of `t` locally. -- Since `f` is surjective on stalks, we can find a preimage `s₀` of the germ of `t` at `x` obtain ⟨s₀,hs₀⟩ := (h x).2 (G.presheaf.germ x t), -- ... and this preimage must come from some section `s₁` defined on some open neighborhood `V₁` obtain ⟨V₁,hxV₁,s₁,hs₁⟩ := F.presheaf.germ_exist x.1 s₀, subst hs₁, rename hs₀ hs₁, erw stalk_functor_map_germ_apply V₁ ⟨x.1,hxV₁⟩ f.1 s₁ at hs₁, -- Now, the germ of `f.app (op V₁) s₁` equals the germ of `t`, hence they must coincide on -- some open neighborhood `V₂`. obtain ⟨V₂, hxV₂, iV₂V₁, iV₂U, heq⟩ := G.presheaf.germ_eq x.1 hxV₁ x.2 _ _ hs₁, -- The restriction of `s₁` to that neighborhood is our desired local preimage. use [V₂, hxV₂, iV₂U, F.1.map iV₂V₁.op s₁], rw [← comp_apply, f.1.naturality, comp_apply, heq], end lemma app_bijective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G) (U : opens X) (h : ∀ x : U, function.bijective ((stalk_functor C x.val).map f.1)) : function.bijective (f.1.app (op U)) := ⟨app_injective_of_stalk_functor_map_injective f.1 U (λ x, (h x).1), app_surjective_of_stalk_functor_map_bijective f U h⟩ lemma app_is_iso_of_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) (U : opens X) [∀ x : U, is_iso ((stalk_functor C x.val).map f.1)] : is_iso (f.1.app (op U)) := begin -- Since the forgetful functor of `C` reflects isomorphisms, it suffices to see that the -- underlying map between types is an isomorphism, i.e. bijective. suffices : is_iso ((forget C).map (f.1.app (op U))), { exactI is_iso_of_reflects_iso (f.1.app (op U)) (forget C) }, rw is_iso_iff_bijective, apply app_bijective_of_stalk_functor_map_bijective, intro x, apply (is_iso_iff_bijective _).mp, exact functor.map_is_iso (forget C) ((stalk_functor C x.1).map f.1) end /-- Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then if the stalk maps of a morphism `f : F ⟶ G` are all isomorphisms, `f` must be an isomorphism. -/ -- Making this an instance would cause a loop in typeclass resolution with `functor.map_is_iso` lemma is_iso_of_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) [∀ x : X, is_iso ((stalk_functor C x).map f.1)] : is_iso f := begin -- Since the inclusion functor from sheaves to presheaves is fully faithful, it suffices to -- show that `f`, as a morphism between _presheaves_, is an isomorphism. suffices : is_iso ((sheaf.forget C X).map f), { exactI is_iso_of_fully_faithful (sheaf.forget C X) f }, -- We show that all components of `f` are isomorphisms. suffices : ∀ U : (opens X)ᵒᵖ, is_iso (f.1.app U), { exact @nat_iso.is_iso_of_is_iso_app _ _ _ _ F.1 G.1 f.1 this, }, intro U, induction U using opposite.rec, apply app_is_iso_of_stalk_functor_map_iso end /-- Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects isomorphisms, preserves limits and filtered colimits. Then a morphism `f : F ⟶ G` is an isomorphism if and only if all of its stalk maps are isomorphisms. -/ lemma is_iso_iff_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) : is_iso f ↔ ∀ x : X, is_iso ((stalk_functor C x).map f.1) := begin split, { intros h x, resetI, exact @functor.map_is_iso _ _ _ _ _ _ (stalk_functor C x) f.1 ((sheaf.forget C X).map_is_iso f) }, { intro h, exactI is_iso_of_stalk_functor_map_iso f } end end concrete instance (F : X.presheaf CommRing) {U : opens X} (x : U) : algebra (F.obj $ op U) (F.stalk x) := (F.germ x).to_algebra @[simp] lemma stalk_open_algebra_map {X : Top} (F : X.presheaf CommRing) {U : opens X} (x : U) : algebra_map (F.obj $ op U) (F.stalk x) = F.germ x := rfl end Top.presheaf
9bf3baa785df49f4759de409f763d431b5fcef4f
26ac254ecb57ffcb886ff709cf018390161a9225
/src/topology/order.lean
87203e563e30f032f85515d2da0e150bbae75a85
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
27,637
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import topology.basic /-! # Ordering on topologies and (co)induced topologies Topologies on a fixed type `α` are ordered, by reverse inclusion. That is, for topologies `t₁` and `t₂` on `α`, we write `t₁ ≤ t₂` if every set open in `t₂` is also open in `t₁`. (One also calls `t₁` finer than `t₂`, and `t₂` coarser than `t₁`.) Any function `f : α → β` induces `induced f : topological_space β → topological_space α` and `coinduced f : topological_space α → topological_space β`. Continuity, the ordering on topologies and (co)induced topologies are related as follows: * The identity map (α, t₁) → (α, t₂) is continuous iff t₁ ≤ t₂. * A map f : (α, t) → (β, u) is continuous iff t ≤ induced f u (`continuous_iff_le_induced`) iff coinduced f t ≤ u (`continuous_iff_coinduced_le`). Topologies on α form a complete lattice, with ⊥ the discrete topology and ⊤ the indiscrete topology. For a function f : α → β, (coinduced f, induced f) is a Galois connection between topologies on α and topologies on β. ## Implementation notes There is a Galois insertion between topologies on α (with the inclusion ordering) and all collections of sets in α. The complete lattice structure on topologies on α is defined as the reverse of the one obtained via this Galois insertion. ## Tags finer, coarser, induced topology, coinduced topology -/ open set filter classical open_locale classical topological_space filter universes u v w namespace topological_space variables {α : Type u} /-- The open sets of the least topology containing a collection of basic sets. -/ inductive generate_open (g : set (set α)) : set α → Prop | basic : ∀s∈g, generate_open s | univ : generate_open univ | inter : ∀s t, generate_open s → generate_open t → generate_open (s ∩ t) | sUnion : ∀k, (∀s∈k, generate_open s) → generate_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from (g : set (set α)) : topological_space α := { is_open := generate_open g, is_open_univ := generate_open.univ, is_open_inter := generate_open.inter, is_open_sUnion := generate_open.sUnion } lemma nhds_generate_from {g : set (set α)} {a : α} : @nhds α (generate_from g) a = (⨅s∈{s | a ∈ s ∧ s ∈ g}, 𝓟 s) := by rw nhds_def; exact le_antisymm (infi_le_infi $ assume s, infi_le_infi_const $ assume ⟨as, sg⟩, ⟨as, generate_open.basic _ sg⟩) (le_infi $ assume s, le_infi $ assume ⟨as, hs⟩, begin revert as, clear_, induction hs, case generate_open.basic : s hs { exact assume as, infi_le_of_le s $ infi_le _ ⟨as, hs⟩ }, case generate_open.univ { rw [principal_univ], exact assume _, le_top }, case generate_open.inter : s t hs' ht' hs ht { exact assume ⟨has, hat⟩, calc _ ≤ 𝓟 s ⊓ 𝓟 t : le_inf (hs has) (ht hat) ... = _ : inf_principal }, case generate_open.sUnion : k hk' hk { exact λ ⟨t, htk, hat⟩, calc _ ≤ 𝓟 t : hk t htk hat ... ≤ _ : le_principal_iff.2 $ subset_sUnion_of_mem htk } end) lemma tendsto_nhds_generate_from {β : Type*} {m : α → β} {f : filter α} {g : set (set β)} {b : β} (h : ∀s∈g, b ∈ s → m ⁻¹' s ∈ f) : tendsto m f (@nhds β (generate_from g) b) := by rw [nhds_generate_from]; exact (tendsto_infi.2 $ assume s, tendsto_infi.2 $ assume ⟨hbs, hsg⟩, tendsto_principal.2 $ h s hsg hbs) /-- Construct a topology on α given the filter of neighborhoods of each point of α. -/ protected def mk_of_nhds (n : α → filter α) : topological_space α := { is_open := λs, ∀a∈s, s ∈ n a, is_open_univ := assume x h, univ_mem_sets, is_open_inter := assume s t hs ht x ⟨hxs, hxt⟩, inter_mem_sets (hs x hxs) (ht x hxt), is_open_sUnion := assume s hs a ⟨x, hx, hxa⟩, mem_sets_of_superset (hs x hx _ hxa) (set.subset_sUnion_of_mem hx) } lemma nhds_mk_of_nhds (n : α → filter α) (a : α) (h₀ : pure ≤ n) (h₁ : ∀{a s}, s ∈ n a → ∃ t ∈ n a, t ⊆ s ∧ ∀a' ∈ t, s ∈ n a') : @nhds α (topological_space.mk_of_nhds n) a = n a := begin letI := topological_space.mk_of_nhds n, refine le_antisymm (assume s hs, _) (assume s hs, _), { have h₀ : {b | s ∈ n b} ⊆ s := assume b hb, mem_pure_sets.1 $ h₀ b hb, have h₁ : {b | s ∈ n b} ∈ 𝓝 a, { refine mem_nhds_sets (assume b (hb : s ∈ n b), _) hs, rcases h₁ hb with ⟨t, ht, hts, h⟩, exact mem_sets_of_superset ht h }, exact mem_sets_of_superset h₁ h₀ }, { rcases (@mem_nhds_sets_iff α (topological_space.mk_of_nhds n) _ _).1 hs with ⟨t, hts, ht, hat⟩, exact (n a).sets_of_superset (ht _ hat) hts }, end end topological_space section lattice variables {α : Type u} {β : Type v} /-- The inclusion ordering on topologies on α. We use it to get a complete lattice instance via the Galois insertion method, but the partial order that we will eventually impose on `topological_space α` is the reverse one. -/ def tmp_order : partial_order (topological_space α) := { le := λt s, t.is_open ≤ s.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₁ h₂, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, @le_trans _ _ a.is_open b.is_open c.is_open h₁ h₂ } local attribute [instance] tmp_order /- We'll later restate this lemma in terms of the correct order on `topological_space α`. -/ private lemma generate_from_le_iff_subset_is_open {g : set (set α)} {t : topological_space α} : topological_space.generate_from g ≤ t ↔ g ⊆ {s | t.is_open s} := iff.intro (assume ht s hs, ht _ $ topological_space.generate_open.basic s hs) (assume hg s hs, hs.rec_on (assume v hv, hg hv) t.is_open_univ (assume u v _ _, t.is_open_inter u v) (assume k _, t.is_open_sUnion k)) /-- If `s` equals the collection of open sets in the topology it generates, then `s` defines a topology. -/ protected def mk_of_closure (s : set (set α)) (hs : {u | (topological_space.generate_from s).is_open u} = s) : topological_space α := { is_open := λu, u ∈ s, is_open_univ := hs ▸ topological_space.generate_open.univ, is_open_inter := hs ▸ topological_space.generate_open.inter, is_open_sUnion := hs ▸ topological_space.generate_open.sUnion } lemma mk_of_closure_sets {s : set (set α)} {hs : {u | (topological_space.generate_from s).is_open u} = s} : mk_of_closure s hs = topological_space.generate_from s := topological_space_eq hs.symm /-- The Galois insertion between `set (set α)` and `topological_space α` whose lower part sends a collection of subsets of α to the topology they generate, and whose upper part sends a topology to its collection of open subsets. -/ def gi_generate_from (α : Type*) : galois_insertion topological_space.generate_from (λt:topological_space α, {s | t.is_open s}) := { gc := assume g t, generate_from_le_iff_subset_is_open, le_l_u := assume ts s hs, topological_space.generate_open.basic s hs, choice := λg hg, mk_of_closure g (subset.antisymm hg $ generate_from_le_iff_subset_is_open.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } lemma generate_from_mono {α} {g₁ g₂ : set (set α)} (h : g₁ ⊆ g₂) : topological_space.generate_from g₁ ≤ topological_space.generate_from g₂ := (gi_generate_from _).gc.monotone_l h /-- The complete lattice of topological spaces, but built on the inclusion ordering. -/ def tmp_complete_lattice {α : Type u} : complete_lattice (topological_space α) := (gi_generate_from α).lift_complete_lattice /-- The ordering on topologies on the type `α`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ instance : partial_order (topological_space α) := { le := λ t s, s.is_open ≤ t.is_open, le_antisymm := assume t s h₁ h₂, topological_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl t.is_open, le_trans := assume a b c h₁ h₂, le_trans h₂ h₁ } lemma le_generate_from_iff_subset_is_open {g : set (set α)} {t : topological_space α} : t ≤ topological_space.generate_from g ↔ g ⊆ {s | t.is_open s} := generate_from_le_iff_subset_is_open /-- Topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of topologies is the topology generated by all their open sets, while the supremem is the topology whose open sets are those sets open in every member of the collection. -/ instance : complete_lattice (topological_space α) := @order_dual.complete_lattice _ tmp_complete_lattice /-- A topological space is discrete if every set is open, that is, its topology equals the discrete topology `⊥`. -/ class discrete_topology (α : Type*) [t : topological_space α] : Prop := (eq_bot [] : t = ⊥) @[simp] lemma is_open_discrete [topological_space α] [discrete_topology α] (s : set α) : is_open s := (discrete_topology.eq_bot α).symm ▸ trivial @[simp] lemma is_closed_discrete [topological_space α] [discrete_topology α] (s : set α) : is_closed s := (discrete_topology.eq_bot α).symm ▸ trivial lemma continuous_of_discrete_topology [topological_space α] [discrete_topology α] [topological_space β] {f : α → β} : continuous f := λs hs, is_open_discrete _ lemma nhds_bot (α : Type*) : (@nhds α ⊥) = pure := begin refine le_antisymm _ (@pure_le_nhds α ⊥), assume a s hs, exact @mem_nhds_sets α ⊥ a s trivial hs end lemma nhds_discrete (α : Type*) [topological_space α] [discrete_topology α] : (@nhds α _) = pure := (discrete_topology.eq_bot α).symm ▸ nhds_bot α lemma le_of_nhds_le_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x ≤ @nhds α t₂ x) : t₁ ≤ t₂ := assume s, show @is_open α t₂ s → @is_open α t₁ s, by { simp only [is_open_iff_nhds, le_principal_iff], exact assume hs a ha, h _ $ hs _ ha } lemma eq_of_nhds_eq_nhds {t₁ t₂ : topological_space α} (h : ∀x, @nhds α t₁ x = @nhds α t₂ x) : t₁ = t₂ := le_antisymm (le_of_nhds_le_nhds $ assume x, le_of_eq $ h x) (le_of_nhds_le_nhds $ assume x, le_of_eq $ (h x).symm) lemma eq_bot_of_singletons_open {t : topological_space α} (h : ∀ x, t.is_open {x}) : t = ⊥ := bot_unique $ λ s hs, bUnion_of_singleton s ▸ is_open_bUnion (λ x _, h x) end lattice section galois_connection variables {α : Type*} {β : Type*} {γ : Type*} /-- Given `f : α → β` and a topology on `β`, the induced topology on `α` is the collection of sets that are preimages of some open set in `β`. This is the coarsest topology that makes `f` continuous. -/ def topological_space.induced {α : Type u} {β : Type v} (f : α → β) (t : topological_space β) : topological_space α := { is_open := λs, ∃s', t.is_open s' ∧ f ⁻¹' s' = s, is_open_univ := ⟨univ, t.is_open_univ, preimage_univ⟩, is_open_inter := by rintro s₁ s₂ ⟨s'₁, hs₁, rfl⟩ ⟨s'₂, hs₂, rfl⟩; exact ⟨s'₁ ∩ s'₂, t.is_open_inter _ _ hs₁ hs₂, preimage_inter⟩, is_open_sUnion := assume s h, begin simp only [classical.skolem] at h, cases h with f hf, apply exists.intro (⋃(x : set α) (h : x ∈ s), f x h), simp only [sUnion_eq_bUnion, preimage_Union, (λx h, (hf x h).right)], refine ⟨_, rfl⟩, exact (@is_open_Union β _ t _ $ assume i, show is_open (⋃h, f i h), from @is_open_Union β _ t _ $ assume h, (hf i h).left) end } lemma is_open_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_open α (t.induced f) s ↔ (∃t, is_open t ∧ f ⁻¹' t = s) := iff.rfl lemma is_closed_induced_iff [t : topological_space β] {s : set α} {f : α → β} : @is_closed α (t.induced f) s ↔ (∃t, is_closed t ∧ s = f ⁻¹' t) := ⟨assume ⟨t, ht, heq⟩, ⟨tᶜ, is_closed_compl_iff.2 ht, by simp only [preimage_compl, heq, compl_compl]⟩, assume ⟨t, ht, heq⟩, ⟨tᶜ, ht, by simp only [preimage_compl, heq.symm]⟩⟩ /-- Given `f : α → β` and a topology on `α`, the coinduced topology on `β` is defined such that `s:set β` is open if the preimage of `s` is open. This is the finest topology that makes `f` continuous. -/ def topological_space.coinduced {α : Type u} {β : Type v} (f : α → β) (t : topological_space α) : topological_space β := { is_open := λs, t.is_open (f ⁻¹' s), is_open_univ := by rw preimage_univ; exact t.is_open_univ, is_open_inter := assume s₁ s₂ h₁ h₂, by rw preimage_inter; exact t.is_open_inter _ _ h₁ h₂, is_open_sUnion := assume s h, by rw [preimage_sUnion]; exact (@is_open_Union _ _ t _ $ assume i, show is_open (⋃ (H : i ∈ s), f ⁻¹' i), from @is_open_Union _ _ t _ $ assume hi, h i hi) } lemma is_open_coinduced {t : topological_space α} {s : set β} {f : α → β} : @is_open β (topological_space.coinduced f t) s ↔ is_open (f ⁻¹' s) := iff.rfl variables {t t₁ t₂ : topological_space α} {t' : topological_space β} {f : α → β} {g : β → α} lemma coinduced_le_iff_le_induced {f : α → β } {tα : topological_space α} {tβ : topological_space β} : tα.coinduced f ≤ tβ ↔ tα ≤ tβ.induced f := iff.intro (assume h s ⟨t, ht, hst⟩, hst ▸ h _ ht) (assume h s hs, show tα.is_open (f ⁻¹' s), from h _ ⟨s, hs, rfl⟩) lemma gc_coinduced_induced (f : α → β) : galois_connection (topological_space.coinduced f) (topological_space.induced f) := assume f g, coinduced_le_iff_le_induced lemma induced_mono (h : t₁ ≤ t₂) : t₁.induced g ≤ t₂.induced g := (gc_coinduced_induced g).monotone_u h lemma coinduced_mono (h : t₁ ≤ t₂) : t₁.coinduced f ≤ t₂.coinduced f := (gc_coinduced_induced f).monotone_l h @[simp] lemma induced_top : (⊤ : topological_space α).induced g = ⊤ := (gc_coinduced_induced g).u_top @[simp] lemma induced_inf : (t₁ ⊓ t₂).induced g = t₁.induced g ⊓ t₂.induced g := (gc_coinduced_induced g).u_inf @[simp] lemma induced_infi {ι : Sort w} {t : ι → topological_space α} : (⨅i, t i).induced g = (⨅i, (t i).induced g) := (gc_coinduced_induced g).u_infi @[simp] lemma coinduced_bot : (⊥ : topological_space α).coinduced f = ⊥ := (gc_coinduced_induced f).l_bot @[simp] lemma coinduced_sup : (t₁ ⊔ t₂).coinduced f = t₁.coinduced f ⊔ t₂.coinduced f := (gc_coinduced_induced f).l_sup @[simp] lemma coinduced_supr {ι : Sort w} {t : ι → topological_space α} : (⨆i, t i).coinduced f = (⨆i, (t i).coinduced f) := (gc_coinduced_induced f).l_supr lemma induced_id [t : topological_space α] : t.induced id = t := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', hs, h⟩, h ▸ hs, assume hs, ⟨s, hs, rfl⟩⟩ lemma induced_compose [tγ : topological_space γ] {f : α → β} {g : β → γ} : (tγ.induced g).induced f = tγ.induced (g ∘ f) := topological_space_eq $ funext $ assume s, propext $ ⟨assume ⟨s', ⟨s, hs, h₂⟩, h₁⟩, h₁ ▸ h₂ ▸ ⟨s, hs, rfl⟩, assume ⟨s, hs, h⟩, ⟨preimage g s, ⟨s, hs, rfl⟩, h ▸ rfl⟩⟩ lemma coinduced_id [t : topological_space α] : t.coinduced id = t := topological_space_eq rfl lemma coinduced_compose [tα : topological_space α] {f : α → β} {g : β → γ} : (tα.coinduced f).coinduced g = tα.coinduced (g ∘ f) := topological_space_eq rfl end galois_connection /- constructions using the complete lattice structure -/ section constructions open topological_space variables {α : Type u} {β : Type v} instance inhabited_topological_space {α : Type u} : inhabited (topological_space α) := ⟨⊤⟩ @[priority 100] instance subsingleton.discrete_topology [topological_space α] [subsingleton α] : discrete_topology α := ⟨eq_bot_of_singletons_open $ λ x, subsingleton.set_cases is_open_empty is_open_univ ({x} : set α)⟩ instance : topological_space empty := ⊥ instance : discrete_topology empty := ⟨rfl⟩ instance : topological_space unit := ⊥ instance : discrete_topology unit := ⟨rfl⟩ instance : topological_space bool := ⊥ instance : discrete_topology bool := ⟨rfl⟩ instance : topological_space ℕ := ⊥ instance : discrete_topology ℕ := ⟨rfl⟩ instance : topological_space ℤ := ⊥ instance : discrete_topology ℤ := ⟨rfl⟩ instance sierpinski_space : topological_space Prop := generate_from {{true}} lemma le_generate_from {t : topological_space α} { g : set (set α) } (h : ∀s∈g, is_open s) : t ≤ generate_from g := le_generate_from_iff_subset_is_open.2 h lemma induced_generate_from_eq {α β} {b : set (set β)} {f : α → β} : (generate_from b).induced f = topological_space.generate_from (preimage f '' b) := le_antisymm (le_generate_from $ ball_image_iff.2 $ assume s hs, ⟨s, generate_open.basic _ hs, rfl⟩) (coinduced_le_iff_le_induced.1 $ le_generate_from $ assume s hs, generate_open.basic _ $ mem_image_of_mem _ hs) /-- This construction is left adjoint to the operation sending a topology on `α` to its neighborhood filter at a fixed point `a : α`. -/ protected def topological_space.nhds_adjoint (a : α) (f : filter α) : topological_space α := { is_open := λs, a ∈ s → s ∈ f, is_open_univ := assume s, univ_mem_sets, is_open_inter := assume s t hs ht ⟨has, hat⟩, inter_mem_sets (hs has) (ht hat), is_open_sUnion := assume k hk ⟨u, hu, hau⟩, mem_sets_of_superset (hk u hu hau) (subset_sUnion_of_mem hu) } lemma gc_nhds (a : α) : galois_connection (topological_space.nhds_adjoint a) (λt, @nhds α t a) := assume f t, by { rw le_nhds_iff, exact ⟨λ H s hs has, H _ has hs, λ H s has hs, H _ hs has⟩ } lemma nhds_mono {t₁ t₂ : topological_space α} {a : α} (h : t₁ ≤ t₂) : @nhds α t₁ a ≤ @nhds α t₂ a := (gc_nhds a).monotone_u h lemma nhds_infi {ι : Sort*} {t : ι → topological_space α} {a : α} : @nhds α (infi t) a = (⨅i, @nhds α (t i) a) := (gc_nhds a).u_infi lemma nhds_Inf {s : set (topological_space α)} {a : α} : @nhds α (Inf s) a = (⨅t∈s, @nhds α t a) := (gc_nhds a).u_Inf lemma nhds_inf {t₁ t₂ : topological_space α} {a : α} : @nhds α (t₁ ⊓ t₂) a = @nhds α t₁ a ⊓ @nhds α t₂ a := (gc_nhds a).u_inf lemma nhds_top {a : α} : @nhds α ⊤ a = ⊤ := (gc_nhds a).u_top local notation `cont` := @continuous _ _ local notation `tspace` := topological_space open topological_space variables {γ : Type*} {f : α → β} {ι : Sort*} lemma continuous_iff_coinduced_le {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ coinduced f t₁ ≤ t₂ := iff.rfl lemma continuous_iff_le_induced {t₁ : tspace α} {t₂ : tspace β} : cont t₁ t₂ f ↔ t₁ ≤ induced f t₂ := iff.trans continuous_iff_coinduced_le (gc_coinduced_induced f _ _) theorem continuous_generated_from {t : tspace α} {b : set (set β)} (h : ∀s∈b, is_open (f ⁻¹' s)) : cont t (generate_from b) f := continuous_iff_coinduced_le.2 $ le_generate_from h lemma continuous_induced_dom {t : tspace β} : cont (induced f t) t f := assume s h, ⟨_, h, rfl⟩ lemma continuous_induced_rng {g : γ → α} {t₂ : tspace β} {t₁ : tspace γ} (h : cont t₁ t₂ (f ∘ g)) : cont t₁ (induced f t₂) g := assume s ⟨t, ht, s_eq⟩, s_eq ▸ h t ht lemma continuous_coinduced_rng {t : tspace α} : cont t (coinduced f t) f := assume s h, h lemma continuous_coinduced_dom {g : β → γ} {t₁ : tspace α} {t₂ : tspace γ} (h : cont t₁ t₂ (g ∘ f)) : cont (coinduced f t₁) t₂ g := assume s hs, h s hs lemma continuous_le_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : t₂ ≤ t₁) (h₂ : cont t₁ t₃ f) : cont t₂ t₃ f := assume s h, h₁ _ (h₂ s h) lemma continuous_le_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : t₂ ≤ t₃) (h₂ : cont t₁ t₂ f) : cont t₁ t₃ f := assume s h, h₂ s (h₁ s h) lemma continuous_sup_dom {t₁ t₂ : tspace α} {t₃ : tspace β} (h₁ : cont t₁ t₃ f) (h₂ : cont t₂ t₃ f) : cont (t₁ ⊔ t₂) t₃ f := assume s h, ⟨h₁ s h, h₂ s h⟩ lemma continuous_sup_rng_left {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₂ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_left lemma continuous_sup_rng_right {t₁ : tspace α} {t₃ t₂ : tspace β} : cont t₁ t₃ f → cont t₁ (t₂ ⊔ t₃) f := continuous_le_rng le_sup_right lemma continuous_Sup_dom {t₁ : set (tspace α)} {t₂ : tspace β} (h : ∀t∈t₁, cont t t₂ f) : cont (Sup t₁) t₂ f := continuous_iff_le_induced.2 $ Sup_le $ assume t ht, continuous_iff_le_induced.1 $ h t ht lemma continuous_Sup_rng {t₁ : tspace α} {t₂ : set (tspace β)} {t : tspace β} (h₁ : t ∈ t₂) (hf : cont t₁ t f) : cont t₁ (Sup t₂) f := continuous_iff_coinduced_le.2 $ le_Sup_of_le h₁ $ continuous_iff_coinduced_le.1 hf lemma continuous_supr_dom {t₁ : ι → tspace α} {t₂ : tspace β} (h : ∀i, cont (t₁ i) t₂ f) : cont (supr t₁) t₂ f := continuous_Sup_dom $ assume t ⟨i, (t_eq : t₁ i = t)⟩, t_eq ▸ h i lemma continuous_supr_rng {t₁ : tspace α} {t₂ : ι → tspace β} {i : ι} (h : cont t₁ (t₂ i) f) : cont t₁ (supr t₂) f := continuous_Sup_rng ⟨i, rfl⟩ h lemma continuous_inf_rng {t₁ : tspace α} {t₂ t₃ : tspace β} (h₁ : cont t₁ t₂ f) (h₂ : cont t₁ t₃ f) : cont t₁ (t₂ ⊓ t₃) f := continuous_iff_coinduced_le.2 $ le_inf (continuous_iff_coinduced_le.1 h₁) (continuous_iff_coinduced_le.1 h₂) lemma continuous_inf_dom_left {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₁ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_left lemma continuous_inf_dom_right {t₁ t₂ : tspace α} {t₃ : tspace β} : cont t₂ t₃ f → cont (t₁ ⊓ t₂) t₃ f := continuous_le_dom inf_le_right lemma continuous_Inf_dom {t₁ : set (tspace α)} {t₂ : tspace β} {t : tspace α} (h₁ : t ∈ t₁) : cont t t₂ f → cont (Inf t₁) t₂ f := continuous_le_dom $ Inf_le h₁ lemma continuous_Inf_rng {t₁ : tspace α} {t₂ : set (tspace β)} (h : ∀t∈t₂, cont t₁ t f) : cont t₁ (Inf t₂) f := continuous_iff_coinduced_le.2 $ le_Inf $ assume b hb, continuous_iff_coinduced_le.1 $ h b hb lemma continuous_infi_dom {t₁ : ι → tspace α} {t₂ : tspace β} {i : ι} : cont (t₁ i) t₂ f → cont (infi t₁) t₂ f := continuous_le_dom $ infi_le _ _ lemma continuous_infi_rng {t₁ : tspace α} {t₂ : ι → tspace β} (h : ∀i, cont t₁ (t₂ i) f) : cont t₁ (infi t₂) f := continuous_iff_coinduced_le.2 $ le_infi $ assume i, continuous_iff_coinduced_le.1 $ h i lemma continuous_bot {t : tspace β} : cont ⊥ t f := continuous_iff_le_induced.2 $ bot_le lemma continuous_top {t : tspace α} : cont t ⊤ f := continuous_iff_coinduced_le.2 $ le_top /- 𝓝 in the induced topology -/ theorem mem_nhds_induced [T : topological_space α] (f : β → α) (a : β) (s : set β) : s ∈ @nhds β (topological_space.induced f T) a ↔ ∃ u ∈ 𝓝 (f a), f ⁻¹' u ⊆ s := begin simp only [mem_nhds_sets_iff, is_open_induced_iff, exists_prop, set.mem_set_of_eq], split, { rintros ⟨u, usub, ⟨v, openv, ueq⟩, au⟩, exact ⟨v, ⟨v, set.subset.refl v, openv, by rwa ←ueq at au⟩, by rw ueq; exact usub⟩ }, rintros ⟨u, ⟨v, vsubu, openv, amem⟩, finvsub⟩, exact ⟨f ⁻¹' v, set.subset.trans (set.preimage_mono vsubu) finvsub, ⟨⟨v, openv, rfl⟩, amem⟩⟩ end theorem nhds_induced [T : topological_space α] (f : β → α) (a : β) : @nhds β (topological_space.induced f T) a = comap f (𝓝 (f a)) := filter_eq $ by ext s; rw mem_nhds_induced; rw mem_comap_sets lemma induced_iff_nhds_eq [tα : topological_space α] [tβ : topological_space β] (f : β → α) : tβ = tα.induced f ↔ ∀ b, 𝓝 b = comap f (𝓝 $ f b) := ⟨λ h a, h.symm ▸ nhds_induced f a, λ h, eq_of_nhds_eq_nhds $ λ x, by rw [h, nhds_induced]⟩ theorem map_nhds_induced_of_surjective [T : topological_space α] {f : β → α} (hf : function.surjective f) (a : β) : map f (@nhds β (topological_space.induced f T) a) = 𝓝 (f a) := by rw [nhds_induced, map_comap_of_surjective hf] end constructions section induced open topological_space variables {α : Type*} {β : Type*} variables [t : topological_space β] {f : α → β} theorem is_open_induced_eq {s : set α} : @is_open _ (induced f t) s ↔ s ∈ preimage f '' {s | is_open s} := iff.rfl theorem is_open_induced {s : set β} (h : is_open s) : (induced f t).is_open (f ⁻¹' s) := ⟨s, h, rfl⟩ lemma map_nhds_induced_eq {a : α} (h : range f ∈ 𝓝 (f a)) : map f (@nhds α (induced f t) a) = 𝓝 (f a) := by rw [nhds_induced, filter.map_comap h] lemma closure_induced [t : topological_space β] {f : α → β} {a : α} {s : set α} (hf : ∀x y, f x = f y → x = y) : a ∈ @closure α (topological_space.induced f t) s ↔ f a ∈ closure (f '' s) := have ne_bot (comap f (𝓝 (f a) ⊓ 𝓟 (f '' s))) ↔ ne_bot (𝓝 (f a) ⊓ 𝓟 (f '' s)), from ⟨assume h₁ h₂, h₁ $ h₂.symm ▸ comap_bot, assume h, forall_sets_nonempty_iff_ne_bot.mp $ assume s₁ ⟨s₂, hs₂, (hs : f ⁻¹' s₂ ⊆ s₁)⟩, have f '' s ∈ 𝓝 (f a) ⊓ 𝓟 (f '' s), from mem_inf_sets_of_right $ by simp [subset.refl], have s₂ ∩ f '' s ∈ 𝓝 (f a) ⊓ 𝓟 (f '' s), from inter_mem_sets hs₂ this, let ⟨b, hb₁, ⟨a, ha, ha₂⟩⟩ := h.nonempty_of_mem this in ⟨_, hs $ by rwa [←ha₂] at hb₁⟩⟩, calc a ∈ @closure α (topological_space.induced f t) s ↔ (@nhds α (topological_space.induced f t) a) ⊓ 𝓟 s ≠ ⊥ : by rw [closure_eq_cluster_pts]; refl ... ↔ comap f (𝓝 (f a)) ⊓ 𝓟 (f ⁻¹' (f '' s)) ≠ ⊥ : by rw [nhds_induced, preimage_image_eq _ hf] ... ↔ comap f (𝓝 (f a) ⊓ 𝓟 (f '' s)) ≠ ⊥ : by rw [comap_inf, ←comap_principal] ... ↔ _ : by rwa [closure_eq_cluster_pts] end induced section sierpinski variables {α : Type*} [topological_space α] @[simp] lemma is_open_singleton_true : is_open ({true} : set Prop) := topological_space.generate_open.basic _ (by simp) lemma continuous_Prop {p : α → Prop} : continuous p ↔ is_open {x | p x} := ⟨assume h : continuous p, have is_open (p ⁻¹' {true}), from h _ is_open_singleton_true, by simp [preimage, eq_true] at this; assumption, assume h : is_open {x | p x}, continuous_generated_from $ assume s (hs : s ∈ {{true}}), by simp at hs; simp [hs, preimage, eq_true, h]⟩ end sierpinski section infi variables {α : Type u} {ι : Type v} {t : ι → topological_space α} lemma is_open_supr_iff {s : set α} : @is_open _ (⨆ i, t i) s ↔ ∀ i, @is_open _ (t i) s := begin -- s defines a map from α to Prop, which is continuous iff s is open. suffices : @continuous _ _ (⨆ i, t i) _ s ↔ ∀ i, @continuous _ _ (t i) _ s, { simpa only [continuous_Prop] using this }, simp only [continuous_iff_le_induced, supr_le_iff] end lemma is_closed_infi_iff {s : set α} : @is_closed _ (⨆ i, t i) s ↔ ∀ i, @is_closed _ (t i) s := is_open_supr_iff end infi
aba4e3d0ecfbf7d8042d92e0c9c6a7f8949fbfef
36938939954e91f23dec66a02728db08a7acfcf9
/lean4/app/Main.lean
9e915c482e2476b6bada4d518e654703beb5ece5
[]
no_license
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
2,632
lean
import ReoptVCG.Annotations import ReoptVCG.ReoptVCG open ReoptVCG -- Modes of execution for `reopt-vcg` inductive VCGCmd | showHelp : VCGCmd | runVCG : VCGConfig → VCGCmd -- A container to accumulate user-provided command line arguments in -- while the are being processed. structure VCGArgs := (annFile : Option String) (mode : VerificationMode) (verbose : Bool) -- | State of argument parsing before any user arguments have actually -- been processed. def initVCGArgs := VCGArgs.mk Option.none VerificationMode.defaultMode true -- Function for parsing command line arguments to reopt-vcg. partial def parseArgs : List String → VCGArgs → Except String VCGCmd | [], args => do annPath <- (args.annFile.map Except.ok).getD (throw "Missing VCG file to run."); pure $ VCGCmd.runVCG $ VCGConfig.mk annPath args.mode args.verbose | (s::ss), args => if s == "--help" then pure $ VCGCmd.showHelp else if s == "--verbose" then parseArgs ss $ {args with verbose := true} else if s == "--export" then do unless args.mode.isDefault $ throw "Cannot specify --export or --solver multiple times."; match ss with | [] => throw "missing argument for `--export` flag" | s'::ss' => parseArgs ss' $ {args with mode := VerificationMode.exportMode s'} else if s == "--solver" then do unless args.mode.isDefault $ throw "Cannot specify --export or --solver multiple times."; match ss with | [] => throw "missing argument for `--solver` flag" | s'::ss' => match String.split s' Char.isWhitespace with | [] => throw "Expected a solver name and command line argument(s)." | (solver::solverArgs) => parseArgs ss' $ {args with mode := VerificationMode.runSolverMode solver solverArgs} else do when (String.isPrefixOf "--" s) $ throw $ "Unexpected flag " ++ s; when (Option.isSome args.annFile) $ throw "Multiple VCG files specified."; parseArgs ss $ {args with annFile := (Option.some s)} def showUsage : IO Unit := do IO.println "Usage: reopt-vcg [--verbose] <input.json> {--export <export-dir> | --solver <solver-path>}" def showHelp : IO Unit := do showUsage; IO.println $ "reopt-vcg generates verification conditions to prove that reopt generated\n" ++ " LLVM is faithful to the input binary.\n" def main (args:List String) : IO UInt32 := match parseArgs args initVCGArgs with | Except.error msg => do IO.println $ "Error encountered while parsing reopt-vcg command line arguments: " ++ msg; showUsage; pure 1 | Except.ok VCGCmd.showHelp => do showHelp; pure 0 | Except.ok (VCGCmd.runVCG cfg) => runVCG cfg
92976269eaeb72ace8d0efd2134c4bbca8fad47c
9028d228ac200bbefe3a711342514dd4e4458bff
/src/algebra/group_power/lemmas.lean
247b6e0e2cb4bdc69ddf3c7059e5850c2394ad4a
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
22,167
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.group_power.basic import algebra.opposites import data.list.basic import data.int.cast import data.equiv.basic import deprecated.group /-! # Lemmas about power operations on monoids and groups This file contains lemmas about `monoid.pow`, `group.pow`, `nsmul`, `gsmul` which require additional imports besides those available in `.basic`. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-! ### (Additive) monoid -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem nsmul_one [has_one A] : ∀ n : ℕ, n •ℕ (1 : A) = n := add_monoid_hom.eq_nat_cast ⟨λ n, n •ℕ (1 : A), zero_nsmul _, λ _ _, add_nsmul _ _ _⟩ (one_nsmul _) @[simp, priority 500] theorem list.prod_repeat (a : M) (n : ℕ) : (list.repeat a n).prod = a ^ n := begin induction n with n ih, { refl }, { rw [list.repeat_succ, list.prod_cons, ih], refl, } end @[simp, priority 500] theorem list.sum_repeat : ∀ (a : A) (n : ℕ), (list.repeat a n).sum = n •ℕ a := @list.prod_repeat (multiplicative A) _ @[simp, norm_cast] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n := (units.coe_hom M).map_pow u n lemma is_unit_of_pow_eq_one (x : M) (n : ℕ) (hx : x ^ n = 1) (hn : 0 < n) : is_unit x := begin cases n, { exact (nat.not_lt_zero _ hn).elim }, refine ⟨⟨x, x ^ n, _, _⟩, rfl⟩, { rwa [pow_succ] at hx }, { rwa [pow_succ'] at hx } end end monoid theorem nat.nsmul_eq_mul (m n : ℕ) : m •ℕ n = m * n := by induction m with m ih; [rw [zero_nsmul, zero_mul], rw [succ_nsmul', ih, nat.succ_mul]] section group variables [group G] [group H] [add_group A] [add_group B] open int local attribute [ematch] le_of_lt open nat theorem gsmul_one [has_one A] (n : ℤ) : n •ℤ (1 : A) = n := by cases n; simp lemma gpow_add_one (a : G) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a | (of_nat n) := by simp [← int.coe_nat_succ, pow_succ'] | -[1+0] := by simp [int.neg_succ_of_nat_eq] | -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, gpow_neg, neg_add, neg_add_cancel_right, gpow_neg, ← int.coe_nat_succ, gpow_coe_nat, gpow_coe_nat, pow_succ _ (n + 1), mul_inv_rev, inv_mul_cancel_right] theorem add_one_gsmul : ∀ (a : A) (i : ℤ), (i + 1) •ℤ a = i •ℤ a + a := @gpow_add_one (multiplicative A) _ lemma gpow_sub_one (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ := calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm ... = a^n * a⁻¹ : by rw [← gpow_add_one, sub_add_cancel] lemma gpow_add (a : G) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, gpow_add_one, ihn, mul_assoc] }, { rw [gpow_sub_one, ← mul_assoc, ← ihn, ← gpow_sub_one, add_sub_assoc] } end lemma mul_self_gpow (b : G) (m : ℤ) : b*b^m = b^(m+1) := by { conv_lhs {congr, rw ← gpow_one b }, rw [← gpow_add, add_comm] } lemma mul_gpow_self (b : G) (m : ℤ) : b^m*b = b^(m+1) := by { conv_lhs {congr, skip, rw ← gpow_one b }, rw [← gpow_add, add_comm] } theorem add_gsmul : ∀ (a : A) (i j : ℤ), (i + j) •ℤ a = i •ℤ a + j •ℤ a := @gpow_add (multiplicative A) _ lemma gpow_sub (a : G) (m n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := by rw [sub_eq_add_neg, gpow_add, gpow_neg] lemma sub_gsmul (m n : ℤ) (a : A) : (m - n) •ℤ a = m •ℤ a - n •ℤ a := @gpow_sub (multiplicative A) _ _ _ _ theorem gpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [gpow_add, gpow_one] theorem one_add_gsmul : ∀ (a : A) (i : ℤ), (1 + i) •ℤ a = a + i •ℤ a := @gpow_one_add (multiplicative A) _ theorem gpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← gpow_add, ← gpow_add, add_comm] theorem gsmul_add_comm : ∀ (a : A) (i j), i •ℤ a + j •ℤ a = j •ℤ a + i •ℤ a := @gpow_mul_comm (multiplicative A) _ theorem gpow_mul (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ m) ^ n := int.induction_on n (by simp) (λ n ihn, by simp [mul_add, gpow_add, ihn]) (λ n ihn, by simp only [mul_sub, gpow_sub, ihn, mul_one, gpow_one]) theorem gsmul_mul' : ∀ (a : A) (m n : ℤ), m * n •ℤ a = n •ℤ (m •ℤ a) := @gpow_mul (multiplicative A) _ theorem gpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, gpow_mul] theorem gsmul_mul (a : A) (m n : ℤ) : m * n •ℤ a = m •ℤ (n •ℤ a) := by rw [mul_comm, gsmul_mul'] theorem gpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _ theorem bit0_gsmul (a : A) (n : ℤ) : bit0 n •ℤ a = n •ℤ a + n •ℤ a := gpow_add _ _ _ theorem gpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, gpow_add, gpow_bit0, gpow_one] theorem bit1_gsmul : ∀ (a : A) (n : ℤ), bit1 n •ℤ a = n •ℤ a + n •ℤ a + a := @gpow_bit1 (multiplicative A) _ theorem monoid_hom.map_gpow (f : G →* H) (a : G) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; [exact f.map_pow _ _, exact (f.map_inv _).trans (congr_arg _ $ f.map_pow _ _)] theorem add_monoid_hom.map_gsmul (f : A →+ B) (a : A) (n : ℤ) : f (n •ℤ a) = n •ℤ f a := f.to_multiplicative.map_gpow a n @[simp, norm_cast] lemma units.coe_gpow (u : units G) (n : ℤ) : ((u ^ n : units G) : G) = u ^ n := (units.coe_hom G).map_gpow u n end group section ordered_add_comm_group variables [ordered_add_comm_group A] /-! Lemmas about `gsmul` under ordering, placed here (rather than in `algebra.group_power.basic` with their friends) because they require facts from `data.int.basic`-/ open int lemma gsmul_pos {a : A} (ha : 0 < a) {k : ℤ} (hk : (0:ℤ) < k) : 0 < k •ℤ a := begin lift k to ℕ using int.le_of_lt hk, apply nsmul_pos ha, exact coe_nat_pos.mp hk, end theorem gsmul_le_gsmul {a : A} {n m : ℤ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℤ a ≤ m •ℤ a := calc n •ℤ a = n •ℤ a + 0 : (add_zero _).symm ... ≤ n •ℤ a + (m - n) •ℤ a : add_le_add_left (gsmul_nonneg ha (sub_nonneg.mpr h)) _ ... = m •ℤ a : by { rw [← add_gsmul], simp } theorem gsmul_lt_gsmul {a : A} {n m : ℤ} (ha : 0 < a) (h : n < m) : n •ℤ a < m •ℤ a := calc n •ℤ a = n •ℤ a + 0 : (add_zero _).symm ... < n •ℤ a + (m - n) •ℤ a : add_lt_add_left (gsmul_pos ha (sub_pos.mpr h)) _ ... = m •ℤ a : by { rw [← add_gsmul], simp } end ordered_add_comm_group section decidable_linear_ordered_add_comm_group variable [decidable_linear_ordered_add_comm_group A] theorem gsmul_le_gsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n •ℤ a ≤ m •ℤ a ↔ n ≤ m := begin refine ⟨λ h, _, gsmul_le_gsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (gsmul_lt_gsmul ha (not_le.mp H)) h) end theorem gsmul_lt_gsmul_iff {a : A} {n m : ℤ} (ha : 0 < a) : n •ℤ a < m •ℤ a ↔ n < m := begin refine ⟨λ h, _, gsmul_lt_gsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (gsmul_le_gsmul (le_of_lt ha) $ not_lt.mp H) h) end theorem nsmul_le_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n •ℕ a ≤ m •ℕ a ↔ n ≤ m := begin refine ⟨λ h, _, nsmul_le_nsmul $ le_of_lt ha⟩, by_contra H, exact lt_irrefl _ (lt_of_lt_of_le (nsmul_lt_nsmul ha (not_le.mp H)) h) end theorem nsmul_lt_nsmul_iff {a : A} {n m : ℕ} (ha : 0 < a) : n •ℕ a < m •ℕ a ↔ n < m := begin refine ⟨λ h, _, nsmul_lt_nsmul ha⟩, by_contra H, exact lt_irrefl _ (lt_of_le_of_lt (nsmul_le_nsmul (le_of_lt ha) $ not_lt.mp H) h) end end decidable_linear_ordered_add_comm_group @[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : ℕ) : ((nsmul n a : A) : with_bot A) = nsmul n a := add_monoid_hom.map_nsmul ⟨(coe : A → with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n theorem nsmul_eq_mul' [semiring R] (a : R) (n : ℕ) : n •ℕ a = a * n := by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero], rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]] @[simp] theorem nsmul_eq_mul [semiring R] (n : ℕ) (a : R) : n •ℕ a = n * a := by rw [nsmul_eq_mul', (n.cast_commute a).eq] theorem mul_nsmul_left [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = a * (n •ℕ b) := by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc] theorem mul_nsmul_assoc [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = n •ℕ a * b := by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc] @[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact nat.cast_one, rw [pow_succ', pow_succ', nat.cast_mul, ih]] @[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [pow_succ', pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, pow_succ', ih]] -- The next four lemmas allow us to replace multiplication by a numeral with a `gsmul` expression. -- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`. lemma bit0_mul [ring R] {n r : R} : bit0 n * r = gsmul 2 (n * r) := by { dsimp [bit0], rw [add_mul, add_gsmul, one_gsmul], } lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = gsmul 2 (r * n) := by { dsimp [bit0], rw [mul_add, add_gsmul, one_gsmul], } lemma bit1_mul [ring R] {n r : R} : bit1 n * r = gsmul 2 (n * r) + r := by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], } lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = gsmul 2 (r * n) + r := by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], } @[simp] theorem gsmul_eq_mul [ring R] (a : R) : ∀ n, n •ℤ a = n * a | (n : ℕ) := nsmul_eq_mul _ _ | -[1+ n] := show -(_ •ℕ _)=-_*_, by rw [neg_mul_eq_neg_mul_symm, nsmul_eq_mul, nat.cast_succ] theorem gsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n •ℤ a = a * n := by rw [gsmul_eq_mul, (n.cast_commute a).eq] theorem mul_gsmul_left [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) := by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc] theorem mul_gsmul_assoc [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b := by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc] @[simp] lemma gsmul_int_int (a b : ℤ) : a •ℤ b = a * b := by simp [gsmul_eq_mul] lemma gsmul_int_one (n : ℤ) : n •ℤ 1 = n := by simp @[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact int.cast_one, rw [pow_succ, pow_succ, int.cast_mul, ih]] lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = (-1) ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two] section linear_ordered_semiring variable [linear_ordered_semiring R] /-- Bernoulli's inequality. This version works for semirings but requires an additional hypothesis `0 ≤ a * a`. -/ theorem one_add_mul_le_pow' {a : R} (Hsqr : 0 ≤ a * a) (H : 0 ≤ 1 + a) : ∀ (n : ℕ), 1 + n •ℕ a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | (n+1) := calc 1 + (n + 1) •ℕ a ≤ (1 + a) * (1 + n •ℕ a) : by simpa [succ_nsmul, mul_add, add_mul, mul_nsmul_left, add_comm, add_left_comm] using nsmul_nonneg Hsqr n ... ≤ (1 + a)^(n+1) : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) H private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin simp only [add_zero], rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw ←one_mul (a^i), apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by rw [←add_assoc, ←one_mul (a^i)]; exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_le_pow_of_le_one {a : R} (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_one {x : R} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1 | 0 h0 h1 := le_refl (1 : R) | (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) end linear_ordered_semiring /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow [linear_ordered_ring R] {a : R} (H : -2 ≤ a) : ∀ (n : ℕ), 1 + n •ℕ a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | 1 := by simp | (n+2) := have H' : 0 ≤ 2 + a, from neg_le_iff_add_nonneg.1 H, have 0 ≤ n •ℕ (a * a * (2 + a)) + a * a, from add_nonneg (nsmul_nonneg (mul_nonneg (mul_self_nonneg a) H') n) (mul_self_nonneg a), calc 1 + (n + 2) •ℕ a ≤ 1 + (n + 2) •ℕ a + (n •ℕ (a * a * (2 + a)) + a * a) : (le_add_iff_nonneg_right _).2 this ... = (1 + a) * (1 + a) * (1 + n •ℕ a) : by { simp only [add_mul, mul_add, mul_two, mul_one, one_mul, succ_nsmul, nsmul_add, mul_nsmul_assoc, (mul_nsmul_left _ _ _).symm], ac_refl } ... ≤ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow n) (mul_self_nonneg (1 + a)) ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_sub_mul_le_pow [linear_ordered_ring R] {a : R} (H : -1 ≤ a) (n : ℕ) : 1 + n •ℕ (a - 1) ≤ a ^ n := have -2 ≤ a - 1, by { rw [bit0, neg_add], exact sub_le_sub_right H 1 }, by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n namespace int lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one] @[simp] lemma nat_abs_pow_two (x : ℤ) : (x.nat_abs ^ 2 : ℤ) = x ^ 2 := by rw [pow_two, int.nat_abs_mul_self', pow_two] end int variables (M G A) /-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image of `multiplicative.of_add 1`. -/ def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, pow_zero x, λ m n, pow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := pow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_nsmul] } } /-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image of `multiplicative.of_add 1`. -/ def gpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, gpow_zero x, λ m n, gpow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := gpow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_gpow, ← of_add_gsmul ] } } /-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/ def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) := { to_fun := λ x, ⟨λ n, n •ℕ x, zero_nsmul x, λ m n, add_nsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_nsmul, right_inv := λ f, add_monoid_hom.ext_nat $ one_nsmul (f 1) } /-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/ def gmultiples_hom [add_group A] : A ≃ (ℤ →+ A) := { to_fun := λ x, ⟨λ n, n •ℤ x, zero_gsmul x, λ m n, add_gsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_gsmul, right_inv := λ f, add_monoid_hom.ext_int $ one_gsmul (f 1) } variables {M G A} @[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) : powers_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) : (powers_hom M).symm f = f (multiplicative.of_add 1) := rfl lemma mnat_monoid_hom_eq [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply] lemma mnat_monoid_hom_ext [monoid M] ⦃f g : multiplicative ℕ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [mnat_monoid_hom_eq f, mnat_monoid_hom_eq g, h] /-! ### Commutativity (again) Facts about `semiconj_by` and `commute` that require `gpow` or `gsmul`, or the fact that integer multiplication equals semiring multiplication. -/ namespace semiconj_by section variables [semiring R] {a x y : R} @[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : ℕ) : semiconj_by a ((n : R) * x) (n * y) := semiconj_by.mul_right (nat.commute_cast _ _) h @[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : ℕ) : semiconj_by ((n : R) * a) x y := semiconj_by.mul_left (nat.cast_commute _ _) h @[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : ℕ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_nat_mul_left m).cast_nat_mul_right n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {x y : units M} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (↑(x^m)) (↑(y^m)) | (n : ℕ) := by simp only [gpow_coe_nat, units.coe_pow, h, pow_right] | -[1+n] := by simp only [gpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right] variables {a b x y x' y' : R} @[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : ℤ) : semiconj_by a ((m : ℤ) * x) (m * y) := semiconj_by.mul_right (int.commute_cast _ _) h @[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : ℤ) : semiconj_by ((m : R) * a) x y := semiconj_by.mul_left (int.cast_commute _ _) h @[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : ℤ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_int_mul_left m).cast_int_mul_right n end semiconj_by namespace commute section variables [semiring R] {a b : R} @[simp] theorem cast_nat_mul_right (h : commute a b) (n : ℕ) : commute a ((n : R) * b) := h.cast_nat_mul_right n @[simp] theorem cast_nat_mul_left (h : commute a b) (n : ℕ) : commute ((n : R) * a) b := h.cast_nat_mul_left n @[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : ℕ) : commute ((m : R) * a) (n * b) := h.cast_nat_mul_cast_nat_mul m n @[simp] theorem self_cast_nat_mul (n : ℕ) : commute a (n * a) := (commute.refl a).cast_nat_mul_right n @[simp] theorem cast_nat_mul_self (n : ℕ) : commute ((n : R) * a) a := (commute.refl a).cast_nat_mul_left n @[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : ℕ) : commute ((m : R) * a) (n * a) := (commute.refl a).cast_nat_mul_cast_nat_mul m n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {u : units M} (h : commute a u) (m : ℤ) : commute a (↑(u^m)) := h.units_gpow_right m @[simp] lemma units_gpow_left {u : units M} {a : M} (h : commute ↑u a) (m : ℤ) : commute (↑(u^m)) a := (h.symm.units_gpow_right m).symm variables {a b : R} @[simp] lemma cast_int_mul_right (h : commute a b) (m : ℤ) : commute a (m * b) := h.cast_int_mul_right m @[simp] lemma cast_int_mul_left (h : commute a b) (m : ℤ) : commute ((m : R) * a) b := h.cast_int_mul_left m lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : ℤ) : commute ((m : R) * a) (n * b) := h.cast_int_mul_cast_int_mul m n variables (a) (m n : ℤ) @[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n @[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) := (commute.refl a).cast_int_mul_cast_int_mul m n end commute section multiplicative open multiplicative @[simp] lemma nat.to_add_pow (a : multiplicative ℕ) (b : ℕ) : to_add (a ^ b) = to_add a * b := begin induction b with b ih, { erw [pow_zero, to_add_one, mul_zero] }, { simp [*, pow_succ, add_comm, nat.mul_succ] } end @[simp] lemma nat.of_add_mul (a b : ℕ) : of_add (a * b) = of_add a ^ b := (nat.to_add_pow _ _).symm @[simp] lemma int.to_add_pow (a : multiplicative ℤ) (b : ℕ) : to_add (a ^ b) = to_add a * b := by induction b; simp [*, mul_add, pow_succ, add_comm] @[simp] lemma int.to_add_gpow (a : multiplicative ℤ) (b : ℤ) : to_add (a ^ b) = to_add a * b := int.induction_on b (by simp) (by simp [gpow_add, mul_add] {contextual := tt}) (by simp [gpow_add, mul_add, sub_eq_add_neg] {contextual := tt}) @[simp] lemma int.of_add_mul (a b : ℤ) : of_add (a * b) = of_add a ^ b := (int.to_add_gpow _ _).symm end multiplicative namespace units variables [monoid M] lemma conj_pow (u : units M) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) := (divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm lemma conj_pow' (u : units M) (x : M) (n : ℕ) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:= (u⁻¹).conj_pow x n open opposite /-- Moving to the opposite monoid commutes with taking powers. -/ @[simp] lemma op_pow (x : M) (n : ℕ) : op (x ^ n) = (op x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', op_mul, h, pow_succ] } end @[simp] lemma unop_pow (x : Mᵒᵖ) (n : ℕ) : unop (x ^ n) = (unop x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', unop_mul, h, pow_succ] } end end units
46e7d6caaf7a79299e61e140b6f04ce764d442ea
271e26e338b0c14544a889c31c30b39c989f2e0f
/tests/lean/run/typeclass_metas_internal_goals.lean
f6713d80a81a431fffbe3b96ce4687d50dba042f
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,915
lean
#exit namespace T1 class Foo (α : Type) : Type := (u : Unit := ()) class Bar (α : Type) : Type := (u : Unit := ()) class Top : Type := (u : Unit := ()) instance FooAll (α : Type) : Foo α := {u:=()} instance BarNat : Bar Nat := {u:=()} instance FooBarToTop (α : Type) [Foo α] [Bar α] : Top := {u:=()} #synth Top end T1 namespace T2 class Foo (α β : Type) : Type := (u : Unit := ()) class Bar (α β : Type) : Type := (u : Unit := ()) class Top : Type := (u : Unit := ()) instance FooNatA (β : Type) : Foo Nat β := {u:=()} instance BarANat (α : Type) : Bar α Nat := {u:=()} instance FooBarToTop (α β : Type) [Foo α β] [Bar α β] : Top := {u:=()} #synth Top end T2 namespace T3 class Base (α : Type) := (u:Unit) class Depends (α : Type) [Base α] := (u:Unit) class Top := (u:Unit) instance AllBase {α : Type} : Base α := {u:=()} instance DependsNotConstrainingImplicit {α : Type} /- [Base α] -/ {_:Base α} : Depends α := {u:=()} instance BaseAsImplicit₁ {α : Type} {_:Base α} [Depends α] : Top := {u:=()} instance BaseAsInstImplicit {α : Type} [Base α] [Depends α] : Top := {u:=()} instance BaseAsImplicit₂ {α : Type} {_:Base α} [Depends α] : Top := {u:=()} axiom K : Type instance BaseK : Base K := {u:=()} #synth Top end T3 namespace T4 class Foo (α β γ : Type) := (u:Unit) class Bar (α β γ : Type) := (u:Unit) class Top := (u:Unit) instance FooBarToTop (α β γ : Type) [Foo α β γ] [Bar α β γ] : Top := {u:=()} instance Foo₁ (β γ : Type) : Foo Unit β γ := {u:=()} instance Foo₂ (α γ : Type) : Foo α Unit γ := {u:=()} instance Foo₃ (α β : Type) : Foo α β Unit := {u:=()} instance Foo₁₂ (γ : Type) : Foo Unit Nat γ := {u:=()} instance Foo₂₃ (α : Type) : Foo α Unit Nat := {u:=()} instance Foo₃₁ (β : Type) : Foo Nat β Unit := {u:=()} instance Bar0 : Bar Unit Int (List Int) := {u:=()} #synth Top end T4
6adeffdcdf4a2d62f3c50fb0be31bf5b6f839a18
4727251e0cd73359b15b664c3170e5d754078599
/src/tactic/simpa.lean
2f90df9cf89d138e31655ce044b938b90f8fe2d6
[ "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
2,408
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.doc_commands open interactive open interactive.types namespace tactic namespace interactive open expr lean.parser local postfix `?`:9001 := optional /-- This is a "finishing" tactic modification of `simp`. It has two forms. * `simpa [rules, ...] using e` will simplify the goal and the type of `e` using `rules`, then try to close the goal using `e`. Simplifying the type of `e` makes it more likely to match the goal (which has also been simplified). This construction also tends to be more robust under changes to the simp lemma set. * `simpa [rules, ...]` will simplify the goal and the type of a hypothesis `this` if present in the context, then try to close the goal using the `assumption` tactic. -/ meta def simpa (use_iota_eqn : parse $ (tk "!")?) (trace_lemmas : parse $ (tk "?")?) (no_dflt : parse only_flag) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (tgt : parse (tk "using" *> texpr)?) (cfg : simp_config_ext := {}) : tactic unit := let simp_at lc (close_tac : tactic unit) := focus1 $ simp use_iota_eqn trace_lemmas no_dflt hs attr_names (loc.ns lc) {fail_if_unchanged := ff, ..cfg} >> (((close_tac <|> trivial) >> done) <|> fail "simpa failed") in match tgt with | none := get_local `this >> simp_at [some `this, none] assumption <|> simp_at [none] assumption | some e := focus1 $ do e ← i_to_expr e <|> do { ty ← target, -- for positional error messages, we don't care about the result e ← i_to_expr_strict ``(%%e : %%ty), pty ← pp ty, ptgt ← pp e, -- Fail deliberately, to advise regarding `simp; exact` usage fail ("simpa failed, 'using' expression type not directly " ++ "inferrable. Try:\n\nsimpa ... using\nshow " ++ to_fmt pty ++ ",\nfrom " ++ ptgt : format) }, match e with | local_const _ lc _ _ := simp_at [some lc, none] (get_local lc >>= tactic.exact) | e := do t ← infer_type e, assertv `this t e, simp_at [some `this, none] (get_local `this >>= tactic.exact), all_goals (try apply_instance) end end add_tactic_doc { name := "simpa", category := doc_category.tactic, decl_names := [`tactic.interactive.simpa], tags := ["simplification"] } end interactive end tactic
a6464cb3b5e3326d82b15d3de49783f0667344af
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/tools/super/clause_ops.lean
6cafed207737921e57033f87b53c00104905f59f
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,429
lean
/- Copyright (c) 2016 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import .clause open monad tactic expr namespace super local attribute [instance] has_monad_lift_to_has_coe meta def on_left_at {m} [monad m] (c : clause) (i : ℕ) [has_monad_lift_t tactic m] -- f gets a type and returns a list of proofs of that type (f : expr → m (list (list expr × expr))) : m (list clause) := do op ← c^.open_constn (c^.num_quants + i), @guard tactic _ (op.1^.get_lit 0)^.is_neg _, new_hyps ← f (op.1^.get_lit 0)^.formula, return $ new_hyps^.for (λnew_hyp, (op.1^.inst new_hyp.2)^.close_constn (op.2 ++ new_hyp.1)) meta def on_left_at_dn {m} [monad m] [alternative m] (c : clause) (i : ℕ) [has_monad_lift_t tactic m] -- f gets a hypothesis of ¬type and returns a list of proofs of false (f : expr → m (list (list expr × expr))) : m (list clause) := do qf ← c^.open_constn c^.num_quants, op ← qf.1^.open_constn c^.num_lits, lci ← (op.2^.nth i)^.to_monad, @guard tactic _ (qf.1^.get_lit i)^.is_neg _, h ← mk_local_def `h $ imp (qf.1^.get_lit i)^.formula c^.local_false, new_hyps ← f h, return $ new_hyps^.for $ λnew_hyp, (((clause.mk 0 0 new_hyp.2 c^.local_false c^.local_false)^.close_const h)^.inst (op.1^.close_const lci)^.proof)^.close_constn (qf.2 ++ op.2^.remove_nth i ++ new_hyp.1) meta def on_right_at {m} [monad m] (c : clause) (i : ℕ) [has_monad_lift_t tactic m] -- f gets a hypothesis and returns a list of proofs of false (f : expr → m (list (list expr × expr))) : m (list clause) := do op ← c^.open_constn (c^.num_quants + i), @guard tactic _ ((op.1^.get_lit 0)^.is_pos) _, h ← mk_local_def `h (op.1^.get_lit 0)^.formula, new_hyps ← f h, return $ new_hyps^.for (λnew_hyp, (op.1^.inst (lambdas [h] new_hyp.2))^.close_constn (op.2 ++ new_hyp.1)) meta def on_right_at' {m} [monad m] (c : clause) (i : ℕ) [has_monad_lift_t tactic m] -- f gets a hypothesis and returns a list of proofs (f : expr → m (list (list expr × expr))) : m (list clause) := do op ← c^.open_constn (c^.num_quants + i), @guard tactic _ ((op.1^.get_lit 0)^.is_pos) _, h ← mk_local_def `h (op.1^.get_lit 0)^.formula, new_hyps ← f h, for new_hyps (λnew_hyp, do type ← infer_type new_hyp.2, nh ← mk_local_def `nh $ imp type c^.local_false, return $ (op.1^.inst (lambdas [h] (app nh new_hyp.2)))^.close_constn (op.2 ++ new_hyp.1 ++ [nh])) meta def on_first_right (c : clause) (f : expr → tactic (list (list expr × expr))) : tactic (list clause) := first $ do i ← list.range c^.num_lits, [on_right_at c i f] meta def on_first_right' (c : clause) (f : expr → tactic (list (list expr × expr))) : tactic (list clause) := first $ do i ← list.range c^.num_lits, [on_right_at' c i f] meta def on_first_left (c : clause) (f : expr → tactic (list (list expr × expr))) : tactic (list clause) := first $ do i ← list.range c^.num_lits, [on_left_at c i f] meta def on_first_left_dn (c : clause) (f : expr → tactic (list (list expr × expr))) : tactic (list clause) := first $ do i ← list.range c^.num_lits, [on_left_at_dn c i f] end super
8afad18cebff2123813e841d237f27c9e72142e8
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Elab/Tactic/Location.lean
6ae34f3678a7ac887ed940dc4bb9aa21876ce83b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
2,232
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Tactic.Basic import Lean.Elab.Tactic.ElabTerm namespace Lean.Elab.Tactic /-- Denotes a set of locations where a tactic should be applied for the main goal. See also `withLocation`. -/ inductive Location where | /-- Apply the tactic everywhere. -/ wildcard | /-- `hypotheses` are hypothesis names in the main goal that the tactic should be applied to. If `type` is true, then the tactic should also be applied to the target type. -/ targets (hypotheses : Array Syntax) (type : Bool) /- Recall that ``` syntax locationWildcard := "*" syntax locationHyp := (colGt term:max)+ ("⊢" <|> "|-")? syntax location := withPosition("at " locationWildcard <|> locationHyp) ``` -/ def expandLocation (stx : Syntax) : Location := let arg := stx[1] if arg.getKind == ``Parser.Tactic.locationWildcard then Location.wildcard else Location.targets arg[0].getArgs (!arg[1].isNone) def expandOptLocation (stx : Syntax) : Location := if stx.isNone then Location.targets #[] true else expandLocation stx[0] open Meta /-- Runs the given `atLocal` and `atTarget` methods on each of the locations selected by the given `loc`. If any of the selected tactic applications fail, it will call `failed` with the main goal mvar. -/ def withLocation (loc : Location) (atLocal : FVarId → TacticM Unit) (atTarget : TacticM Unit) (failed : MVarId → TacticM Unit) : TacticM Unit := do match loc with | Location.targets hyps type => hyps.forM fun hyp => withMainContext do let fvarId ← getFVarId hyp atLocal fvarId if type then atTarget | Location.wildcard => let worked ← tryTactic <| withMainContext <| atTarget withMainContext do let mut worked := worked -- We must traverse backwards because the given `atLocal` may use the revert/intro idiom for fvarId in (← getLCtx).getFVarIds.reverse do worked := worked || (← tryTactic <| withMainContext <| atLocal fvarId) unless worked do failed (← getMainGoal) end Lean.Elab.Tactic
bb40d0e23ecb34d65f08b829a25b9757d0c3f85c
3705439886316285035ef1fd985632bc87eb06e7
/LeanProto.lean
2d9b13a3e5cd06b8c32ef3eb5eadf2efe0442361
[ "MIT" ]
permissive
zygi/lean-proto
ce74f29d33f12f240878f0f8cbe4960c41b70fcb
4d64844d8978c68c8038886013d33048c23a7674
refs/heads/master
1,680,996,798,349
1,618,444,323,000
1,618,444,323,000
342,923,095
0
0
null
null
null
null
UTF-8
Lean
false
false
29,026
lean
import Init.Data.ByteArray import Init.Data.UInt import AssertCmd import LeanProtoNativeHelpers -- TODO list: -- ) It would be much easier if Int32/64 were wrapped namespace LeanProto namespace Utils def byteArrayToHex(b: ByteArray) : String := let parts := b.data.map (fun x => String.singleton (Nat.digitChar (x.toNat / 16)) ++ String.singleton (Nat.digitChar (x.toNat % 16))) String.join parts.toList -- Adapted from Lean: lean4/src/Lean/Data/Json/Parser.lean @[inline] def hexChar (c: Char): Option Nat := do if '0' ≤ c ∧ c ≤ '9' then return some $ c.val.toNat - '0'.val.toNat else if 'a' ≤ c ∧ c ≤ 'f' then return some $ c.val.toNat - 'a'.val.toNat + 10 else if 'A' ≤ c ∧ c ≤ 'F' then return some $ c.val.toNat - 'A'.val.toNat + 10 else none def hexToByteArray(s: String): Option ByteArray := do if s.length % 2 != 0 then return none let mut res := ByteArray.mkEmpty $ s.length / 2 for i in [:((s.length)/2)] do let v1 := hexChar (s[2*i]) let v2 := hexChar (s[2*i+1]) match (v1, v2) with | (some v1, some v2) => res := res.push $ UInt8.ofNat ((16 * v1) + v2) | _ => return none return res def hexToByteArray!(s: String): ByteArray := do if s.length % 2 != 0 then return arbitrary let mut res := ByteArray.mkEmpty $ s.length / 2 for i in [:((s.length)/2)] do let v1 := match hexChar (s[2*i]) with | Option.none => panic! "Bad hex" | Option.some x => x let v2 := match hexChar (s[2*i+1]) with | Option.none => panic! "Bad hex" | Option.some x => x res := res.push $ UInt8.ofNat ((16 * v1) + v2) return res -- Currently LeanProto depends on some custom native code. Since #assert statements are executed -- by the interpreter, they won't see custom native code and will cause errors until looking -- up c ffi symbols from plugins is mainlined. This hack is here to override the #asserts -- into noops for the "release" version. syntax (name := assert) "#cassert " term:max " == " term : command syntax (name := assertVia) "#cassert " term:max comparator term " via " term : command macro_rules -- | `(#cassert%$tk $actual == $expected) => `(#assert%$tk $actual == $expected) -- | `(#cassert%$tk $actual == $expected via $pred) => `(#assert%$tk $actual == $expected via $pred) | `(#cassert%$tk $actual == $expected) => `(#eval "Inline tests disabled") | `(#cassert%$tk $actual == $expected via $pred) => `(#eval "Inline tests disabled") section def hexTest(x: String) : Option Bool := do match hexToByteArray x with | none => return none | some r => x == byteArrayToHex r #cassert (some true) == (hexTest "") #cassert (some true) == (hexTest "08ffffffffffffffffff0110feffffffffffffffff01180328013100000000000014403d000040c0420b68656c6c6f20776f726c644a01615001") end end Utils -- High-level class definitions -- I wanted to make this toUInt64/ofUInt64 but pattern matching on UInt64 seems to be broken class ProtoEnum (α: Type u) where toInt : α -> Int ofInt : Int -> Option α class ProtoSerialize (α: Type u) where serialize : α -> Except IO.Error ByteArray serializeToHex : α -> Except IO.Error String := fun a => Utils.byteArrayToHex <$> (serialize a) class ProtoDeserialize (α: Type u) where deserialize : ByteArray -> Except IO.Error α deserializeFromHex : String -> Except IO.Error α := fun x => do match Utils.hexToByteArray x with | none => Except.error $ IO.userError "Failed to parse hex string" | some val => deserialize val -- HACKHACKHACK until we have our own Default class. Currently Float's Inhabited returns UInt 1, not 0, -- so we override that here. instance : Inhabited Float := ⟨ 0.0 ⟩ instance : BEq ByteArray where beq := fun a b => a.data == b.data -- TODO: consider removing this, possibly too opinionated instance : Repr ByteArray where reprPrec n x := reprPrec (Utils.byteArrayToHex n) x deriving instance BEq, Repr for Std.AssocList deriving instance BEq, Repr for IO.Error deriving instance BEq, Repr for EStateM.Result namespace EncDec -- Definitions for testing def UInt32Max : Nat := UInt32.size - 1 def UInt64Max : Nat := UInt64.size - 1 def Int32Max : Int := (Int.ofNat ((UInt32.size / 2))) - 1 def Int32Min : Int := -1*(Int.ofNat ((UInt32.size / 2))) def Int64Max : Int := (Int.ofNat ((UInt64.size / 2))) - 1 def Int64Min : Int := -1*(Int.ofNat ((UInt64.size / 2))) open Lean open Lean.Elab open Utils (hexToByteArray!) -- Helper for testing def SameEvalVal [BEq α] [BEq ε] (x y: EStateM.Result ε σ α) : Bool := match x, y with | EStateM.Result.ok a _, EStateM.Result.ok b _ => a == b | EStateM.Result.error a _, EStateM.Result.error b _ => a == b | _, _=> false inductive WireType where | Varint : WireType | t64Bit : WireType | LengthDelimited : WireType | t32Bit : WireType deriving BEq, Repr, Inhabited def WireType.toNat: WireType -> Nat | WireType.Varint => 0 | WireType.t64Bit => 1 | WireType.LengthDelimited => 2 | WireType.t32Bit => 5 -- TODO: Pattern matching on UInt8 doesn't seem to work :( def WireType.ofNat (u: Nat) : Option WireType := if u == 0 then some WireType.Varint else if u == 1 then some WireType.t64Bit else if u == 2 then some WireType.LengthDelimited else if u == 5 then some WireType.t32Bit else none -- Helper to ensure generated code correctness: the generated code contains -- Nat constants representign WireType. To ensure we don't put invalid values, we codegen -- `WireType.ofLit <wtNat> rfl`. private def WireType.natIsValid (x: Nat) : Bool := x == 0 || x == 1 || x == 2 || x == 5 def WireType.ofLit : (u: Nat) -> WireType.natIsValid u = true -> WireType | 0, _ => WireType.Varint | 1, _ => WireType.t64Bit | 2, _ => WireType.LengthDelimited | 5, _ => WireType.t32Bit | 3, prf => Bool.noConfusion prf | 4, prf => Bool.noConfusion prf | Nat.succ $ Nat.succ $ Nat.succ $ Nat.succ $ Nat.succ $ Nat.succ _, prf => Bool.noConfusion prf -- Mini parsing monad structure ParseState where d: ByteArray i: Nat := 0 deriving Inhabited, Repr abbrev ProtoParseM := EStateM IO.Error ParseState def resultToExcept (v: EStateM.Result IO.Error ParseState α ) : Except IO.Error α := match v with | EStateM.Result.ok r _ => Except.ok r | EStateM.Result.error r _ => Except.error r def mkOkResult (v: α) : EStateM.Result ε ParseState α := EStateM.Result.ok v arbitrary def parseAt (d: ByteArray) (idx: Nat) (f: ProtoParseM α) := EStateM.run f { d := d, i := idx } def parse (d: ByteArray) (f: ProtoParseM α) := parseAt d 0 f def done: ProtoParseM Bool := do let s <- get return s.d.size <= s.i #cassert (parseAt (ByteArray.mkEmpty 0) 0 done) == (mkOkResult true) via SameEvalVal #cassert (parseAt (ByteArray.mk #[0x00]) 0 done) == (mkOkResult false) via SameEvalVal #cassert (parseAt (ByteArray.mk #[0x00, 0x00, 0x00]) 2 done) == (mkOkResult false) via SameEvalVal #cassert (parseAt (ByteArray.mk #[0x00, 0x00, 0x00]) 500 done) == (mkOkResult true) via SameEvalVal def readByte: ProtoParseM UInt8 := do let s <- get unless s.i + 1 <= s.d.size do throw $ IO.userError "OOB" set {s with i := s.i + 1} s.d.get! s.i def copyBytes (x: Nat): ProtoParseM ByteArray := do let s <- get unless s.i + x <= s.d.size do throw $ IO.userError "OOB" set {s with i := s.i + x} -- TODO: return Byte Subarray once that's easy s.d.extract s.i (s.i+x) -- Mini serialization monad abbrev ProtoSerAction := EStateM IO.Error ByteArray Unit def serialize (f: ProtoSerAction) := EStateM.run f (ByteArray.mkEmpty 0) def writeByte (b: UInt8): ProtoSerAction := do let s <- get set (s.push b) def writeByteArray (b: ByteArray): ProtoSerAction := do let s <- get set (s.append b) def resultStateToExcept (v: EStateM.Result ε σ α ) : Except ε σ := match v with | EStateM.Result.ok _ s => Except.ok s | EStateM.Result.error e _ => Except.error e def mkOkSerResult (s: String) : EStateM.Result ε ByteArray Unit := EStateM.Result.ok () (hexToByteArray! s) def serDeser [BEq α] [Repr α] (s: α -> ProtoSerAction) (d: ProtoParseM α) (a: α) : Option IO.Error := do let sRes ← serialize $ s a match sRes with | EStateM.Result.error e s => return some e | EStateM.Result.ok _ s => let dRes ← parse s d match dRes with | EStateM.Result.error e s => return some e | EStateM.Result.ok a' _ => if a' == a then none else IO.userError s!"Ser {reprStr a}, deser {reprStr a'}" -- TODO: make native def parseFixedUInt64: ProtoParseM UInt64 := do let bytes ← copyBytes 8 let v1: UInt64 := (UInt64.ofUInt8 $ bytes.get! 0).shiftLeft (8*0) let v2: UInt64 := (UInt64.ofUInt8 $ bytes.get! 1).shiftLeft (8*1) let v3: UInt64 := (UInt64.ofUInt8 $ bytes.get! 2).shiftLeft (8*2) let v4: UInt64 := (UInt64.ofUInt8 $ bytes.get! 3).shiftLeft (8*3) let v5: UInt64 := (UInt64.ofUInt8 $ bytes.get! 4).shiftLeft (8*4) let v6: UInt64 := (UInt64.ofUInt8 $ bytes.get! 5).shiftLeft (8*5) let v7: UInt64 := (UInt64.ofUInt8 $ bytes.get! 6).shiftLeft (8*6) let v8: UInt64 := (UInt64.ofUInt8 $ bytes.get! 7).shiftLeft (8*7) return (v1.lor (v2.lor (v3.lor (v4.lor (v5.lor (v6.lor (v7.lor v8))))))) def parseFixedUInt32: ProtoParseM UInt32 := do let bytes ← copyBytes 4 let v1: UInt32 := (UInt32.ofUInt8 $ bytes.get! 0).shiftLeft (8*0) let v2: UInt32 := (UInt32.ofUInt8 $ bytes.get! 1).shiftLeft (8*1) let v3: UInt32 := (UInt32.ofUInt8 $ bytes.get! 2).shiftLeft (8*2) let v4: UInt32 := (UInt32.ofUInt8 $ bytes.get! 3).shiftLeft (8*3) return (v1.lor (v2.lor (v3.lor v4))) def serializeFixedUInt64 (v: UInt64) : ProtoSerAction := do writeByte (UInt64.toUInt8 (v.shiftRight (8*0))) writeByte (UInt64.toUInt8 (v.shiftRight (8*1))) writeByte (UInt64.toUInt8 (v.shiftRight (8*2))) writeByte (UInt64.toUInt8 (v.shiftRight (8*3))) writeByte (UInt64.toUInt8 (v.shiftRight (8*4))) writeByte (UInt64.toUInt8 (v.shiftRight (8*5))) writeByte (UInt64.toUInt8 (v.shiftRight (8*6))) writeByte (UInt64.toUInt8 (v.shiftRight (8*7))) def serializeFixedUInt32 (v: UInt32) : ProtoSerAction := do writeByte (UInt32.toUInt8 (v.shiftRight (8*0))) writeByte (UInt32.toUInt8 (v.shiftRight (8*1))) writeByte (UInt32.toUInt8 (v.shiftRight (8*2))) writeByte (UInt32.toUInt8 (v.shiftRight (8*3))) #cassert none == serDeser serializeFixedUInt64 parseFixedUInt64 5 #cassert none == serDeser serializeFixedUInt64 parseFixedUInt64 0 #cassert none == serDeser serializeFixedUInt64 parseFixedUInt64 5555555 -- Verify endianness #cassert (serialize (serializeFixedUInt32 1)) == (mkOkSerResult "01000000") #cassert (serialize (serializeFixedUInt32 12345678)) == (mkOkSerResult "4E61BC00") #cassert none == serDeser serializeFixedUInt32 parseFixedUInt32 12345678 #cassert none == serDeser serializeFixedUInt32 parseFixedUInt32 0 #cassert none == serDeser serializeFixedUInt32 parseFixedUInt32 (UInt32.size.toUInt32) -- Proto field numbers are limited to 64bit so we use UInt64 as a result type partial def parseVarInt : ProtoParseM UInt64 := do let v <- readByte let msb := UInt8.shiftRight v 7 let val := UInt64.ofUInt8 $ UInt8.land v 0x7F if msb == 0 then val else return UInt64.lor val (UInt64.shiftLeft (<- parseVarInt) 7) #cassert (parse (ByteArray.mk #[0x00]) parseVarInt) == (mkOkResult $ UInt64.ofNat 0) via SameEvalVal #cassert (parse (ByteArray.mk #[0x01]) parseVarInt) == (mkOkResult $ UInt64.ofNat 1) via SameEvalVal #cassert (parse (ByteArray.mk #[0x7F]) parseVarInt) == (mkOkResult $ UInt64.ofNat 127) via SameEvalVal #cassert (parseAt (ByteArray.mk #[0x08, 0x96, 0x01]) 1 parseVarInt) == (mkOkResult $ UInt64.ofNat 150) via SameEvalVal #cassert (parseAt (ByteArray.mk #[0x08, 0x96, 0x01, 0x33]) 1 parseVarInt) == (mkOkResult $ UInt64.ofNat 150) via SameEvalVal partial def serializeVarInt (v: UInt64) : ProtoSerAction := do if v < 128 then writeByte v.toUInt8 else writeByte (UInt64.lor v 0x80).toUInt8 serializeVarInt (v.shiftRight 7) #cassert (serialize (serializeVarInt 0)) == (mkOkSerResult "00") #cassert (serialize (serializeVarInt 5)) == (mkOkSerResult "05") #cassert (serialize (serializeVarInt 127)) == (mkOkSerResult "7F") #cassert (serialize (do let _ ← serializeVarInt 127; serializeVarInt 5)) == (mkOkSerResult "7F05") #cassert (serialize (serializeVarInt 150)) == (mkOkSerResult "9601") def parseKey: ProtoParseM (WireType × Nat) := do let i := (<- parseVarInt).toNat -- make this faster via bit shift let wt := WireType.ofNat (Nat.mod i 8) match wt with | none => throw $ IO.userError s!"Invalid wire type {i}" | some x => (x, i/8) #cassert (parse (ByteArray.mk #[0x08]) parseKey) == mkOkResult ((WireType.Varint, 1)) via SameEvalVal def serializeTag (args : (WireType × Nat)) : ProtoSerAction := serializeVarInt $ UInt64.ofNat $ args.snd * 8 + WireType.toNat args.fst -- Avoids encoding and redecoding wiretype because we got a proof that it's correct def serializeTagLit (d: ByteArray) (wt: Nat) (h: WireType.natIsValid wt = true) (idx: Nat) := serializeVarInt $ UInt64.ofNat $ idx * 8 + wt #cassert none == serDeser serializeTag parseKey (WireType.t32Bit, 5000) def allOnes64 : UInt64 := 0xffffffffffffffff def allOnes32 : UInt32 := 0xffffffff -- Since integers aren't wrapped for now we use uintX and pretend they're intX -- represented in twos complement def UInt64.toInt2C (x: UInt64) : Int := let pos := x.shiftRight 63 == 0 if pos then Int.ofNat $ x.toNat else Int.negSucc $ (x.xor allOnes64).toNat def UInt32.toInt2C (x: UInt32) : Int := let pos := x.shiftRight 31 == 0 if pos then Int.ofNat $ x.toNat else Int.negSucc $ (x.xor allOnes32).toNat def Int.toUInt642C : Int -> UInt64 | Int.ofNat x => UInt64.ofNat x | Int.negSucc x => (UInt64.ofNat x).xor allOnes64 def Int.toUInt322C : Int -> UInt32 | Int.ofNat x => UInt32.ofNat x | Int.negSucc x => (UInt32.ofNat x).xor allOnes32 #cassert (Int.toUInt322C (-1)) == UInt32.ofNat (UInt32.size - 1) #cassert (Int.toUInt322C Int32Min) == UInt32.ofNat (2^31) #cassert (Int.toUInt642C (-1)) == UInt64.ofNat (UInt64.size - 1) #cassert (Int.toUInt642C Int64Min) == UInt64.ofNat (2^63) #cassert (UInt64.toInt2C (Int.toUInt642C (0:Int))) == (0:Int) #cassert (UInt64.toInt2C (Int.toUInt642C Int64Max)) == Int64Max #cassert (UInt64.toInt2C (Int.toUInt642C (Int32Min))) == (Int32Min) #cassert (UInt64.toInt2C (Int.toUInt642C (Int64Min))) == (Int64Min) #cassert (UInt32.toInt2C (Int.toUInt322C (555:Int))) == (555:Int) #cassert (UInt32.toInt2C (Int.toUInt322C (-555))) == (-555) #cassert (UInt32.toInt2C (Int.toUInt322C Int32Min)) == Int32Min -- def parseInt32AsInt: ProtoParseM Int := do UInt32.toInt2C (<- parseVarInt).toUInt32 def parseInt32AsInt: ProtoParseM Int := do UInt32.toInt2C (<- parseVarInt).toInt32Transmute def parseInt64AsInt: ProtoParseM Int := do UInt64.toInt2C (<- parseVarInt) -- def serializeIntAsInt32 (d: ByteArray) (v: Int) : ByteArray := serializeVarInt d $ UInt32.toUInt64 $ Int.toUInt322C v -- TODO: clamp Ints or somehow make it obvious that what doesn't fit into int32/64 will be lost. def serializeIntAsInt32 (v: Int) : ProtoSerAction := serializeVarInt $ Int.toUInt642C v def serializeIntAsInt64 (v: Int) : ProtoSerAction := serializeVarInt $ Int.toUInt642C v #cassert none == serDeser serializeIntAsInt32 parseInt32AsInt 5 #cassert none == serDeser serializeIntAsInt32 parseInt32AsInt Int32Max #cassert none == serDeser serializeIntAsInt32 parseInt32AsInt Int32Min #cassert none == serDeser serializeIntAsInt32 parseInt32AsInt 0 #cassert none == serDeser serializeIntAsInt32 parseInt32AsInt (-15555) #cassert none == serDeser serializeIntAsInt64 parseInt64AsInt 5 #cassert none == serDeser serializeIntAsInt64 parseInt64AsInt Int64Max #cassert none == serDeser serializeIntAsInt64 parseInt64AsInt Int64Min #cassert none == serDeser serializeIntAsInt64 parseInt64AsInt 0 #cassert none == serDeser serializeIntAsInt64 parseInt64AsInt (-15555) def parseUInt32AsNat: ProtoParseM Nat := do (← parseVarInt).toNat def parseUInt64AsNat: ProtoParseM Nat := do (← parseVarInt).toNat def serializeNatAsUInt32 (v: Nat) : ProtoSerAction := serializeVarInt $ UInt32.toUInt64 $ (v % UInt32.size).toUInt32 def serializeNatAsUInt64 (v: Nat) : ProtoSerAction := serializeVarInt $ (v % UInt64.size).toUInt64 #cassert none == serDeser serializeNatAsUInt32 parseUInt32AsNat 5 #cassert none == serDeser serializeNatAsUInt32 parseUInt32AsNat 0 #cassert none == serDeser serializeNatAsUInt32 parseUInt32AsNat UInt32Max #cassert none == serDeser serializeNatAsUInt64 parseUInt64AsNat 5 #cassert none == serDeser serializeNatAsUInt64 parseUInt64AsNat 0 #cassert none == serDeser serializeNatAsUInt64 parseUInt64AsNat UInt64Max -- Fixed size ints def parseFixedInt32AsInt: ProtoParseM Int := do UInt32.toInt2C (<- parseFixedUInt32) def parseFixedInt64AsInt: ProtoParseM Int := do UInt64.toInt2C (<- parseFixedUInt64) def serializeIntAsFixedInt32 (v: Int) : ProtoSerAction := serializeFixedUInt32 $ Int.toUInt322C v def serializeIntAsFixedInt64 (v: Int) : ProtoSerAction := serializeFixedUInt64 $ Int.toUInt642C v #cassert none == serDeser serializeIntAsFixedInt32 parseFixedInt32AsInt 5 #cassert none == serDeser serializeIntAsFixedInt32 parseFixedInt32AsInt 0 #cassert none == serDeser serializeIntAsFixedInt32 parseFixedInt32AsInt Int32Max #cassert none == serDeser serializeIntAsFixedInt32 parseFixedInt32AsInt Int32Min #cassert none == serDeser serializeIntAsFixedInt64 parseFixedInt64AsInt 5 #cassert none == serDeser serializeIntAsFixedInt64 parseFixedInt64AsInt 0 #cassert none == serDeser serializeIntAsFixedInt64 parseFixedInt64AsInt Int64Max #cassert none == serDeser serializeIntAsFixedInt64 parseFixedInt64AsInt Int64Min -- sint{32,64} def fixedparseSInt32(x: UInt32) : Int := UInt32.toInt2C ((x.shiftRight 1).xor (0 - (x.land 1))) def fixedparseSInt64(x: UInt64) : Int := UInt64.toInt2C ((x.shiftRight 1).xor (0 - (x.land 1))) def fixedserializeIntToSInt32(v: Int) : UInt32 := let x := Int.toUInt322C v ((x.shiftLeft 1).xor (x.arithShiftRight 31)) def fixedserializeIntToSInt64(v: Int) : UInt64 := let x := Int.toUInt642C v ((x.shiftLeft 1).xor (x.arithShiftRight 63)) #cassert (fixedparseSInt32 $ fixedserializeIntToSInt32 (0:Int)) == (0:Int) #cassert (fixedparseSInt32 $ fixedserializeIntToSInt32 Int32Max) == Int32Max #cassert (fixedparseSInt32 $ fixedserializeIntToSInt32 Int32Min) == Int32Min #cassert (fixedparseSInt64 $ fixedserializeIntToSInt64 Int64Max) == Int64Max #cassert (fixedparseSInt64 $ fixedserializeIntToSInt64 (Int64Min / 2)) == (Int64Min / 2) #cassert (fixedparseSInt64 $ fixedserializeIntToSInt64 Int64Min) == Int64Min def parseSInt32: ProtoParseM Int := do return fixedparseSInt32 (<- parseVarInt).toUInt32 def parseSInt64: ProtoParseM Int := do let num ← parseVarInt pure $ fixedparseSInt64 num def serializeIntAsSInt32 (v: Int) : ProtoSerAction := serializeVarInt $ UInt32.toUInt64 $ fixedserializeIntToSInt32 v def serializeIntAsSInt64 (v: Int) : ProtoSerAction := serializeVarInt $ fixedserializeIntToSInt64 v #cassert none == serDeser serializeIntAsSInt32 parseSInt32 5 #cassert none == serDeser serializeIntAsSInt32 parseSInt32 0 #cassert none == serDeser serializeIntAsSInt32 parseSInt32 Int32Max #cassert none == serDeser serializeIntAsSInt32 parseSInt32 Int32Min #cassert none == serDeser serializeIntAsSInt64 parseSInt64 5 #cassert none == serDeser serializeIntAsSInt64 parseSInt64 0 #cassert none == serDeser serializeIntAsSInt64 parseSInt64 Int64Max #cassert none == serDeser serializeIntAsSInt64 parseSInt64 Int64Min -- sfixed{32,64} def parseSFixed32: ProtoParseM Int := do return fixedparseSInt32 $ (← parseFixedUInt32) def parseSFixed64: ProtoParseM Int := do return fixedparseSInt64 $ (← parseFixedUInt64) def serializeIntAsSFixed32 (v: Int) : ProtoSerAction := serializeFixedUInt32 $ fixedserializeIntToSInt32 v def serializeIntAsSFixed64 (v: Int) : ProtoSerAction := serializeFixedUInt64 $ fixedserializeIntToSInt64 v #cassert none == serDeser serializeIntAsSFixed32 parseSFixed32 5 #cassert none == serDeser serializeIntAsSFixed32 parseSFixed32 0 #cassert none == serDeser serializeIntAsSFixed32 parseSFixed32 Int32Max #cassert none == serDeser serializeIntAsSFixed32 parseSFixed32 Int32Min #cassert none == serDeser serializeIntAsSFixed64 parseSFixed64 5 #cassert none == serDeser serializeIntAsSFixed64 parseSFixed64 0 #cassert none == serDeser serializeIntAsSFixed64 parseSFixed64 Int64Max #cassert none == serDeser serializeIntAsSFixed64 parseSFixed64 Int64Min -- Bools def parseBool : ProtoParseM Bool := do (<- parseVarInt) != 0 def serializeBool (v: Bool) : ProtoSerAction := serializeVarInt v.toUInt64 #cassert none == serDeser serializeBool parseBool true #cassert none == serDeser serializeBool parseBool false -- Floats -- These four are not at all unsafe, why do you ask? def parseFloat32AsFloat: ProtoParseM Float := do let uint32 ← parseFixedUInt32 Float.ofUInt32Transmute uint32 def parseFloat64AsFloat: ProtoParseM Float := do let uint64 ← parseFixedUInt64 Float.ofUInt64Transmute uint64 def serializeFloatAsFloat32 (v: Float) : ProtoSerAction := serializeFixedUInt32 $ v.toUInt32Transmute def serializeFloatAsFloat64 (v: Float) : ProtoSerAction := serializeFixedUInt64 $ v.toUInt64Transmute #cassert (parse (hexToByteArray! "0000A040") parseFloat32AsFloat) == (mkOkResult 5.0) via SameEvalVal #cassert (parse (hexToByteArray! "000C73C6") parseFloat32AsFloat) == (mkOkResult (-15555.0)) via SameEvalVal #cassert none == serDeser serializeFloatAsFloat32 parseFloat32AsFloat 5.0 #cassert none == serDeser serializeFloatAsFloat32 parseFloat32AsFloat 0.0 #cassert none == serDeser serializeFloatAsFloat32 parseFloat32AsFloat (-15555.0) #cassert (parse (hexToByteArray! "0000000000001440") parseFloat64AsFloat) == (mkOkResult 5.0) via SameEvalVal #cassert (parse (hexToByteArray! "000000008061CEC0") parseFloat64AsFloat) == (mkOkResult (-15555.0)) via SameEvalVal #cassert none == serDeser serializeFloatAsFloat64 parseFloat64AsFloat 5.0 #cassert none == serDeser serializeFloatAsFloat64 parseFloat64AsFloat 0.0 #cassert none == serDeser serializeFloatAsFloat64 parseFloat64AsFloat (-15555.0) -- Strings def parseString : ProtoParseM String := do let len <- parseVarInt let bytes <- copyBytes len.toNat String.fromUTF8Unchecked bytes def serializeString (s: String) : ProtoSerAction := do let s := s.toUTF8 serializeVarInt s.size.toUInt64 writeByteArray s #cassert none == serDeser serializeString parseString "" #cassert none == serDeser serializeString parseString "hellolongstring" #cassert none == serDeser serializeString parseString "おはようございます" -- ByteArrays def parseByteArray : ProtoParseM ByteArray := do let len <- parseVarInt copyBytes len.toNat def serializeByteArray (s: ByteArray) : ProtoSerAction := do serializeVarInt s.size.toUInt64 writeByteArray s #cassert none == serDeser serializeByteArray parseByteArray "".toUTF8 #cassert none == serDeser serializeByteArray parseByteArray "hellolongstring".toUTF8 -- Enums def parseEnum [ProtoEnum α] : ProtoParseM α := do let numVal ← parseInt32AsInt match ProtoEnum.ofInt (α:=α) numVal with | none => throw $ IO.userError s!"Invalid proto value received: {numVal}" | some x => x def serializeEnum [ProtoEnum α] (s: α) : ProtoSerAction:= serializeIntAsInt32 $ ProtoEnum.toInt s def serializeWithSize (s: ProtoSerAction) : ProtoSerAction := do match serialize s with | EStateM.Result.error e _ => throw e | EStateM.Result.ok _ b => serializeVarInt b.size.toUInt64 writeByteArray b -- Packed arrays def parsePackedArray (parseElem: ProtoParseM α) : ProtoParseM $ Array α := do let len := (← parseVarInt).toNat let mut res := #[] let endIdx := (← get).i + len -- would love to have a while loop here for i in [:len] do if (← get).i >= endIdx then return res res := res.push (← parseElem) res def serializePackedArray (serializeElem: α -> ProtoSerAction) (s: Array α) : ProtoSerAction := serializeWithSize $ s.forM serializeElem #cassert none == serDeser (serializePackedArray serializeNatAsUInt64) (parsePackedArray parseUInt64AsNat) #[] #cassert none == serDeser (serializePackedArray serializeNatAsUInt64) (parsePackedArray parseUInt64AsNat) #[1, 2, 3, 55555555555] #cassert none == serDeser (serializePackedArray serializeIntAsInt32) (parsePackedArray parseInt32AsInt) #[] #cassert none == serDeser (serializePackedArray serializeIntAsInt32) (parsePackedArray parseInt32AsInt) #[5, -25] -- Messages def parseMessage (rawparseFn: ProtoParseM α) : ProtoParseM $ α := do let len ← parseVarInt let data ← copyBytes len.toNat -- todo we don't have to copy here--replace with array view when that becomes easy match (parse data rawparseFn) with | EStateM.Result.ok val _ => val | EStateM.Result.error r _ => throw r def serializeMessage (serializeFn: α -> ProtoSerAction) (s: α) : ProtoSerAction := do serializeWithSize $ serializeFn s -- Composite functions that serialize whole fields (key + body) def serializeWithTag (fn: α -> ProtoSerAction) (wt: WireType) (number: Nat) (val: α) : ProtoSerAction := do serializeTag (wt, number) fn val def parseKeyAndMixedArray (parseElem: ProtoParseM α) (wt: WireType) (soFar: Array α): ProtoParseM $ Array α := do if (wt == WireType.LengthDelimited) then return soFar.append (← parsePackedArray parseElem) soFar.push (← parseElem) def parseKeyAndNonPackedArray (parseElem: ProtoParseM α) (wt: WireType) (soFar: Array α): ProtoParseM $ Array α := do soFar.push (← parseElem) -- Maps -- A map entry is an autogenerated proto with two fields, key with idx 1 and value with idx 2 partial def parseMapEntryAux [Inhabited α] [Inhabited β] (parseMapKey: ProtoParseM α) (parseMapVal: ProtoParseM β) (x: Option α) (y: Option β) : ProtoParseM $ (Option α × Option β) := do if (← done) then return (x, y) let (_, idx) ← parseKey if idx == 1 then let keyVal ← parseMapKey parseMapEntryAux parseMapKey parseMapVal (some keyVal) y else if idx == 2 then let valVal ← parseMapVal parseMapEntryAux parseMapKey parseMapVal x (some valVal) else parseMapEntryAux parseMapKey parseMapVal x y def parseMapEntry [Inhabited α] [Inhabited β] (parseMapKey: ProtoParseM α) (parseMapVal: ProtoParseM β): ProtoParseM $ (α × β) := do let len ← parseVarInt let data ← copyBytes len.toNat match (parse data (parseMapEntryAux parseMapKey parseMapVal none none)) with | EStateM.Result.ok (f, s) _ => (f.getD arbitrary, s.getD arbitrary) | EStateM.Result.error r _ => throw r def serializeMapWithTag (serializeMapKey: α -> ProtoSerAction) (serializeMapVal: β -> ProtoSerAction) (wtKey: WireType) (wtVal: WireType) (number: Nat) (map: Std.AssocList α β) : ProtoSerAction := do for (k, v) in map do -- Each entry is a pseudo-proto where field 1 represents the key and field 2 the value. let serEntry : ProtoSerAction := do serializeTag (wtKey, 1) serializeMapKey k serializeTag (wtVal, 2) serializeMapVal v serializeTag (WireType.LengthDelimited, number) serializeWithSize serEntry def serializeSkipDefault [Inhabited α] [BEq α] (serializeFn: α -> ProtoSerAction) (val: α) : ProtoSerAction := if val == arbitrary then () else serializeFn val def serializeOptNotMsg [Inhabited α] [BEq α] (serializeFn: α -> ProtoSerAction) (val: Option α) : ProtoSerAction := match val with | none => () | some x => if x == arbitrary then () else serializeFn x def serializeOpt [Inhabited α] [BEq α] (serializeFn: α -> ProtoSerAction) (val: Option α) : ProtoSerAction := match val with | none => () | some x => serializeFn x def serializeOptDef [Inhabited α] (serializeFn: α -> ProtoSerAction) (val: Option α) : ProtoSerAction := match val with | none => serializeFn arbitrary | some x => serializeFn x def serializeIfNonempty [Inhabited α] (serializeFn: Array α -> ProtoSerAction) (val: Array α) : ProtoSerAction := -- serializeFn b $ val.getD arbitrary match val.size with | 0 => () | _ => serializeFn val def serializeUnpackedArrayWithTag [Inhabited α] [BEq α] (fn: α -> ProtoSerAction) (wt: WireType) (number: Nat) (vals: Array α) : ProtoSerAction := do for val in vals do serializeTag (wt, number) fn val def withIgnoredState (x: ProtoParseM α) (_: α) : ProtoParseM α := x -- Drop unknown fields for now def parseUnknown (wt: WireType) : ProtoParseM Unit := do match wt with | WireType.Varint => let _ ← parseVarInt; () | WireType.t64Bit => let _ ← parseFixedUInt64; () | WireType.LengthDelimited => let _ ← parseString; () | WireType.t32Bit => let _ ← parseFixedUInt32; () -- For debugging -- partial def keepConsuming (ctr: Nat): ProtoParseM Nat := do -- if (← LeanProto.EncDec.done) then return ctr -- let (_type, key) ← LeanProto.EncDec.parseKey -- let _ ← LeanProto.EncDec.parseUnknown _type -- keepConsuming $ ctr+1 end EncDec end LeanProto
e109d92d2e5c94010366ab9c8591d017b5fc9924
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/bench/deriv.lean
fece04381c411b9df9a660f953d742bd364bf120
[ "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
2,831
lean
/- Benchmark for new code generator -/ inductive Expr | Val : Int → Expr | Var : String → Expr | Add : Expr → Expr → Expr | Mul : Expr → Expr → Expr | Pow : Expr → Expr → Expr | Ln : Expr → Expr open Expr partial def pown : Int → Int → Int | a 0 := 1 | a 1 := a | a n := let b := pown a (n / 2) in b * b * (if n % 2 = 0 then 1 else a) partial def add : Expr → Expr → Expr | (Val n) (Val m) := Val (n + m) | (Val 0) f := f | f (Val 0) := f | f (Val n) := add (Val n) f | (Val n) (Add (Val m) f) := add (Val (n+m)) f | f (Add (Val n) g) := add (Val n) (add f g) | (Add f g) h := add f (add g h) | f g := Add f g partial def mul : Expr → Expr → Expr | (Val n) (Val m) := Val (n*m) | (Val 0) _ := Val 0 | _ (Val 0) := Val 0 | (Val 1) f := f | f (Val 1) := f | f (Val n) := mul (Val n) f | (Val n) (Mul (Val m) f) := mul (Val (n*m)) f | f (Mul (Val n) g) := mul (Val n) (mul f g) | (Mul f g) h := mul f (mul g h) | f g := Mul f g def pow : Expr → Expr → Expr | (Val m) (Val n) := Val (pown m n) | _ (Val 0) := Val 1 | f (Val 1) := f | (Val 0) _ := Val 0 | f g := Pow f g def ln : Expr → Expr | (Val 1) := Val 0 | f := Ln f def d (x : String) : Expr → Expr | (Val _) := Val 0 | (Var y) := if x = y then Val 1 else Val 0 | (Add f g) := add (d f) (d g) | (Mul f g) := add (mul f (d g)) (mul g (d f)) | (Pow f g) := mul (pow f g) (add (mul (mul g (d f)) (pow f (Val (-1)))) (mul (ln f) (d g))) | (Ln f) := mul (d f) (pow f (Val (-1))) def count : Expr → UInt32 | (Val _) := 1 | (Var _) := 1 | (Add f g) := count f + count g | (Mul f g) := count f + count g | (Pow f g) := count f + count g | (Ln f) := count f def Expr.toString : Expr → String | (Val n) := toString n | (Var x) := x | (Add f g) := "(" ++ Expr.toString f ++ " + " ++ Expr.toString g ++ ")" | (Mul f g) := "(" ++ Expr.toString f ++ " * " ++ Expr.toString g ++ ")" | (Pow f g) := "(" ++ Expr.toString f ++ " ^ " ++ Expr.toString g ++ ")" | (Ln f) := "ln(" ++ Expr.toString f ++ ")" instance : HasToString Expr := ⟨Expr.toString⟩ def nestAux (s : Nat) (f : Nat → Expr → IO Expr) : Nat → Expr → IO Expr | 0 x := pure x | m@(n+1) x := f (s - m) x >>= nestAux n def nest (f : Nat → Expr → IO Expr) (n : Nat) (e : Expr) : IO Expr := nestAux n f n e def deriv (i : Nat) (f : Expr) : IO Expr := do let d := d "x" f; IO.println (toString (i+1) ++ " count: " ++ (toString $ count d)); pure d def main (xs : List String) : IO UInt32 := do let x := Var "x"; let f := pow x x; nest deriv 10 f; pure 0
f13e1e8e4751f2d796ee06be594d9c90035a68ef
a6b711a4e8db20755026231f7ed529a9014b2b6d
/ZZ_IGNORE/S17/class-s17/Exam2/Exam2.lean
36062f8facb405bf045a86c2ae2724369be57d6a
[]
no_license
chaseboettner/cs-dm-1
b67d4a7e86f56bce59d2af115503769749d423b2
80b35f2957ffaa45b8b7a4479a3570a2d6eb4db0
refs/heads/master
1,585,367,603,488
1,536,235,675,000
1,536,235,675,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,095
lean
/- This is Exam2 for CS2101, Spring 2018 (Sullivan). COLLABORATION POLICY: NO COLLABORATION ALLOWED. This is an individual evaluation. You are not allowed to communicate with *anyone* about this exam, except the instructor, by any means, until you have completed and submitted the exam and anyone you're communicating with has as well. Do not communicate about this exam with anyone not in class until all students have completed and submitted the exam. Cheating on this exam will result in an Honor Committee referral. Don't do it. You MAY use all class materials, your own notes, and material you find through on-line searches, or in books, or other resources, on this exam. Note: This exam document is written using Lean, to take advantage of Lean's support for logical notation. It does not test any concepts that we have covered using Lean. The problems add up to 100 points. -/ /- *********************************************** Problem #1 [30 pts]. One of the basic connectives in propositional logic is called *equivalence*. If P and Q are propositions, the proposition that P is equivalent to Q is written as P ↔ Q. It can be read as "P if and only if Q". Mathematicians shorten it to "P iff Q." What it means is nothing other than P → Q ∧ Q → P. That is, P → Q and also Q → P. In Dafny (not Lean!), the equivalence operator (a binary Boolean operator) is written as <==>. Sadly, our initial implementation of propositional logic doesn't support this operator. You job is to extend the implementation so that it does. (A) Extend our syntax for propositional logic with a new constructor, pEquiv, taking two propositions as arguments. (B) Extend our semantics for propositional logic with a rule for evaluating propositions of this form under a given interpretation. (C) Just as the other logical connectives have introduction and elimination rules in the natural deduction system of logical reasoning, so does the equivalence connective. The introduction rules states that in a context in which P → Q is true and Q → P is true then it is valid to deduce P ↔ Q. Your job is to validate this inference rule using the method of truth tables. Extend consequence_test.dfy by adding a check of this rule and confirming based on the output of the program that it's a valid rule. Similarly, ↔ has two elimination rules. From a context in which P ↔ Q is true, you can deduce by the iff left elimination rule that P → Q is true, and from the right elimination rule that Q → P is true. Represent and validate these two rules as well by extending consequence_test.dfy accordingly. *********************************************** Problem #2 [70 points] Open and complete the work required in the file Exam2.dfy. ************************************************ Submit the files syntax.dfy, evaluation.dfy, consequence_test.dfy, any other files that you had to change, and Exam2.dfy on Collab. The exam is due before 9:30AM next Tuesday. Do NOT submit it late! Late submissions, if taken at all, will have 15 points off for being late. -/
4542ed4fe9ed7ec6d52da75d9bba968da63c6a80
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/group/default.lean
317094a9fe77ebc8d1439a7284e0b26684155856
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
605
lean
/- 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, Michael Howes -/ import algebra.group.to_additive import algebra.group.basic import algebra.group.units import algebra.group.hom import algebra.group.type_tags import algebra.group.conj import algebra.group.with_one import algebra.group.anti_hom import algebra.group.units_hom import algebra.group.is_unit /-! # Various multiplicative and additive structures. This file `import`s all files in this subdirectory except for `prod`. -/
42c962599910876a7c3309f0fe5075a746a8930f
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/group_theory/monoid_localization.lean
ec0c6de6ffb5158a12d17bc3cdaeafd27e04dff5
[]
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
68,767
lean
/- Copyright (c) 2019 Amelia Livingston. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Amelia Livingston -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.group_theory.congruence import Mathlib.group_theory.submonoid.default import Mathlib.algebra.group.units import Mathlib.algebra.punit_instances import Mathlib.PostPort universes u_1 u_2 l u_3 u_4 u_5 u_6 namespace Mathlib /-! # Localizations of commutative monoids Localizing a commutative ring at one of its submonoids does not rely on the ring's addition, so we can generalize localizations to commutative monoids. We characterize the localization of a commutative monoid `M` at a submonoid `S` up to isomorphism; that is, a commutative monoid `N` is the localization of `M` at `S` iff we can find a monoid homomorphism `f : M →* N` satisfying 3 properties: 1. For all `y ∈ S`, `f y` is a unit; 2. For all `z : N`, there exists `(x, y) : M × S` such that `z * f y = f x`; 3. For all `x, y : M`, `f x = f y` iff there exists `c ∈ S` such that `x * c = y * c`. Given such a localization map `f : M →* N`, we can define the surjection `localization_map.mk'` sending `(x, y) : M × S` to `f x * (f y)⁻¹`, and `localization_map.lift`, the homomorphism from `N` induced by a homomorphism from `M` which maps elements of `S` to invertible elements of the codomain. Similarly, given commutative monoids `P, Q`, a submonoid `T` of `P` and a localization map for `T` from `P` to `Q`, then a homomorphism `g : M →* P` such that `g(S) ⊆ T` induces a homomorphism of localizations, `localization_map.map`, from `N` to `Q`. We treat the special case of localizing away from an element in the sections `away_map` and `away`. We also define the quotient of `M × S` by the unique congruence relation (equivalence relation preserving a binary operation) `r` such that for any other congruence relation `s` on `M × S` satisfying '`∀ y ∈ S`, `(1, 1) ∼ (y, y)` under `s`', we have that `(x₁, y₁) ∼ (x₂, y₂)` by `s` whenever `(x₁, y₁) ∼ (x₂, y₂)` by `r`. We show this relation is equivalent to the standard localization relation. This defines the localization as a quotient type, `localization`, but the majority of subsequent lemmas in the file are given in terms of localizations up to isomorphism, using maps which satisfy the characteristic predicate. ## Implementation notes In maths it is natural to reason up to isomorphism, but in Lean we cannot naturally `rewrite` one structure with an isomorphic one; one way around this is to isolate a predicate characterizing a structure up to isomorphism, and reason about things that satisfy the predicate. The infimum form of the localization congruence relation is chosen as 'canonical' here, since it shortens some proofs. To apply a localization map `f` as a function, we use `f.to_map`, as coercions don't work well for this structure. To reason about the localization as a quotient type, use `mk_eq_monoid_of_mk'` and associated lemmas. These show the quotient map `mk : M → S → localization S` equals the surjection `localization_map.mk'` induced by the map `monoid_of : localization_map S (localization S)` (where `of` establishes the localization as a quotient type satisfies the characteristic predicate). The lemma `mk_eq_monoid_of_mk'` hence gives you access to the results in the rest of the file, which are about the `localization_map.mk'` induced by any localization map. ## Tags localization, monoid localization, quotient monoid, congruence relation, characteristic predicate, commutative monoid -/ namespace add_submonoid /-- The type of add_monoid homomorphisms satisfying the characteristic predicate: if `f : M →+ N` satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/ structure localization_map {M : Type u_1} [add_comm_monoid M] (S : add_submonoid M) (N : Type u_2) [add_comm_monoid N] extends M →+ N where map_add_units' : ∀ (y : ↥S), is_add_unit (to_fun ↑y) surj' : ∀ (z : N), ∃ (x : M × ↥S), z + to_fun ↑(prod.snd x) = to_fun (prod.fst x) eq_iff_exists' : ∀ (x y : M), to_fun x = to_fun y ↔ ∃ (c : ↥S), x + ↑c = y + ↑c /-- The add_monoid hom underlying a `localization_map` of `add_comm_monoid`s. -/ end add_submonoid namespace submonoid /-- The type of monoid homomorphisms satisfying the characteristic predicate: if `f : M →* N` satisfies this predicate, then `N` is isomorphic to the localization of `M` at `S`. -/ structure localization_map {M : Type u_1} [comm_monoid M] (S : submonoid M) (N : Type u_2) [comm_monoid N] extends M →* N where map_units' : ∀ (y : ↥S), is_unit (to_fun ↑y) surj' : ∀ (z : N), ∃ (x : M × ↥S), z * to_fun ↑(prod.snd x) = to_fun (prod.fst x) eq_iff_exists' : ∀ (x y : M), to_fun x = to_fun y ↔ ∃ (c : ↥S), x * ↑c = y * ↑c /-- The monoid hom underlying a `localization_map`. -/ end submonoid namespace localization /-- The congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`, defined as the unique congruence relation on `M × S` such that for any other congruence relation `s` on `M × S` where for all `y ∈ S`, `(1, 1) ∼ (y, y)` under `s`, we have that `(x₁, y₁) ∼ (x₂, y₂)` by `r` implies `(x₁, y₁) ∼ (x₂, y₂)` by `s`. -/ def Mathlib.add_localization.r {M : Type u_1} [add_comm_monoid M] (S : add_submonoid M) : add_con (M × ↥S) := Inf (set_of fun (c : add_con (M × ↥S)) => ∀ (y : ↥S), coe_fn c 0 (↑y, y)) /-- An alternate form of the congruence relation on `M × S`, `M` a `comm_monoid` and `S` a submonoid of `M`, whose quotient is the localization of `M` at `S`. -/ def Mathlib.add_localization.r' {M : Type u_1} [add_comm_monoid M] (S : add_submonoid M) : add_con (M × ↥S) := add_con.mk (fun (a b : M × ↥S) => ∃ (c : ↥S), prod.fst a + ↑(prod.snd b) + ↑c = prod.fst b + ↑(prod.snd a) + ↑c) sorry sorry /-- The congruence relation used to localize a `comm_monoid` at a submonoid can be expressed equivalently as an infimum (see `localization.r`) or explicitly (see `localization.r'`). -/ theorem r_eq_r' {M : Type u_1} [comm_monoid M] (S : submonoid M) : r S = r' S := sorry theorem Mathlib.add_localization.r_iff_exists {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {x : M × ↥S} {y : M × ↥S} : coe_fn (add_localization.r S) x y ↔ ∃ (c : ↥S), prod.fst x + ↑(prod.snd y) + ↑c = prod.fst y + ↑(prod.snd x) + ↑c := sorry end localization /-- The localization of a `comm_monoid` at one of its submonoids (as a quotient type). -/ def localization {M : Type u_1} [comm_monoid M] (S : submonoid M) := con.quotient sorry namespace localization protected instance inhabited {M : Type u_1} [comm_monoid M] (S : submonoid M) : Inhabited (localization S) := con.quotient.inhabited protected instance comm_monoid {M : Type u_1} [comm_monoid M] (S : submonoid M) : comm_monoid (localization S) := con.comm_monoid (r S) /-- Given a `comm_monoid` `M` and submonoid `S`, `mk` sends `x : M`, `y ∈ S` to the equivalence class of `(x, y)` in the localization of `M` at `S`. -/ def Mathlib.add_localization.mk {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} (x : M) (y : ↥S) : add_localization S := coe_fn (add_con.mk' (add_localization.r S)) (x, y) theorem Mathlib.add_localization.ind {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {p : add_localization S → Prop} (H : ∀ (y : M × ↥S), p (add_localization.mk (prod.fst y) (prod.snd y))) (x : add_localization S) : p x := sorry theorem Mathlib.add_localization.induction_on {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {p : add_localization S → Prop} (x : add_localization S) (H : ∀ (y : M × ↥S), p (add_localization.mk (prod.fst y) (prod.snd y))) : p x := add_localization.ind H x theorem induction_on₂ {M : Type u_1} [comm_monoid M] {S : submonoid M} {p : localization S → localization S → Prop} (x : localization S) (y : localization S) (H : ∀ (x y : M × ↥S), p (mk (prod.fst x) (prod.snd x)) (mk (prod.fst y) (prod.snd y))) : p x y := induction_on x fun (x : M × ↥S) => induction_on y (H x) theorem induction_on₃ {M : Type u_1} [comm_monoid M] {S : submonoid M} {p : localization S → localization S → localization S → Prop} (x : localization S) (y : localization S) (z : localization S) (H : ∀ (x y z : M × ↥S), p (mk (prod.fst x) (prod.snd x)) (mk (prod.fst y) (prod.snd y)) (mk (prod.fst z) (prod.snd z))) : p x y z := induction_on₂ x y fun (x y : M × ↥S) => induction_on z (H x y) theorem one_rel {M : Type u_1} [comm_monoid M] {S : submonoid M} (y : ↥S) : coe_fn (r S) 1 (↑y, y) := fun (b : con (M × ↥S)) (hb : b ∈ set_of fun (c : con (M × ↥S)) => ∀ (y : ↥S), coe_fn c 1 (↑y, y)) => hb y theorem Mathlib.add_localization.r_of_eq {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {x : M × ↥S} {y : M × ↥S} (h : prod.fst y + ↑(prod.snd x) = prod.fst x + ↑(prod.snd y)) : coe_fn (add_localization.r S) x y := sorry end localization namespace monoid_hom /-- Makes a localization map from a `comm_monoid` hom satisfying the characteristic predicate. -/ def Mathlib.add_monoid_hom.to_localization_map {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : M →+ N) (H1 : ∀ (y : ↥S), is_add_unit (coe_fn f ↑y)) (H2 : ∀ (z : N), ∃ (x : M × ↥S), z + coe_fn f ↑(prod.snd x) = coe_fn f (prod.fst x)) (H3 : ∀ (x y : M), coe_fn f x = coe_fn f y ↔ ∃ (c : ↥S), x + ↑c = y + ↑c) : add_submonoid.localization_map S N := add_submonoid.localization_map.mk (add_monoid_hom.to_fun f) sorry sorry H1 H2 H3 end monoid_hom namespace submonoid namespace localization_map /-- Short for `to_monoid_hom`; used to apply a localization map as a function. -/ def to_map {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) : M →* N := to_monoid_hom f theorem Mathlib.add_submonoid.localization_map.ext {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : add_submonoid.localization_map S N} {g : add_submonoid.localization_map S N} (h : ∀ (x : M), coe_fn (add_submonoid.localization_map.to_map f) x = coe_fn (add_submonoid.localization_map.to_map g) x) : f = g := sorry theorem ext_iff {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : localization_map S N} {g : localization_map S N} : f = g ↔ ∀ (x : M), coe_fn (to_map f) x = coe_fn (to_map g) x := { mp := fun (h : f = g) (x : M) => h ▸ rfl, mpr := ext } theorem to_map_injective {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] : function.injective to_map := fun (_x _x_1 : localization_map S N) (h : to_map _x = to_map _x_1) => ext (iff.mp monoid_hom.ext_iff h) theorem map_units {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (y : ↥S) : is_unit (coe_fn (to_map f) ↑y) := map_units' f y theorem surj {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (z : N) : ∃ (x : M × ↥S), z * coe_fn (to_map f) ↑(prod.snd x) = coe_fn (to_map f) (prod.fst x) := surj' f z theorem eq_iff_exists {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) {x : M} {y : M} : coe_fn (to_map f) x = coe_fn (to_map f) y ↔ ∃ (c : ↥S), x * ↑c = y * ↑c := eq_iff_exists' f x y /-- Given a localization map `f : M →* N`, a section function sending `z : N` to some `(x, y) : M × S` such that `f x * (f y)⁻¹ = z`. -/ def sec {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (z : N) : M × ↥S := classical.some (surj f z) theorem Mathlib.add_submonoid.localization_map.sec_spec {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : add_submonoid.localization_map S N} (z : N) : z + coe_fn (add_submonoid.localization_map.to_map f) ↑(prod.snd (add_submonoid.localization_map.sec f z)) = coe_fn (add_submonoid.localization_map.to_map f) (prod.fst (add_submonoid.localization_map.sec f z)) := classical.some_spec (add_submonoid.localization_map.surj f z) theorem Mathlib.add_submonoid.localization_map.sec_spec' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : add_submonoid.localization_map S N} (z : N) : coe_fn (add_submonoid.localization_map.to_map f) (prod.fst (add_submonoid.localization_map.sec f z)) = coe_fn (add_submonoid.localization_map.to_map f) ↑(prod.snd (add_submonoid.localization_map.sec f z)) + z := sorry /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `w : M, z : N` and `y ∈ S`, we have `w * (f y)⁻¹ = z ↔ w = f y * z`. -/ theorem Mathlib.add_submonoid.localization_map.add_neg_left {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : M →+ N} (h : ∀ (y : ↥S), is_add_unit (coe_fn f ↑y)) (y : ↥S) (w : N) (z : N) : w + ↑(-coe_fn (is_add_unit.lift_right (add_monoid_hom.mrestrict f S) h) y) = z ↔ w = coe_fn f ↑y + z := sorry /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `w : M, z : N` and `y ∈ S`, we have `z = w * (f y)⁻¹ ↔ z * f y = w`. -/ theorem mul_inv_right {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : M →* N} (h : ∀ (y : ↥S), is_unit (coe_fn f ↑y)) (y : ↥S) (w : N) (z : N) : z = w * ↑(coe_fn (is_unit.lift_right (monoid_hom.mrestrict f S) h) y⁻¹) ↔ z * coe_fn f ↑y = w := sorry /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `x₁ x₂ : M` and `y₁, y₂ ∈ S`, we have `f x₁ * (f y₁)⁻¹ = f x₂ * (f y₂)⁻¹ ↔ f (x₁ * y₂) = f (x₂ * y₁)`. -/ @[simp] theorem mul_inv {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : M →* N} (h : ∀ (y : ↥S), is_unit (coe_fn f ↑y)) {x₁ : M} {x₂ : M} {y₁ : ↥S} {y₂ : ↥S} : coe_fn f x₁ * ↑(coe_fn (is_unit.lift_right (monoid_hom.mrestrict f S) h) y₁⁻¹) = coe_fn f x₂ * ↑(coe_fn (is_unit.lift_right (monoid_hom.mrestrict f S) h) y₂⁻¹) ↔ coe_fn f (x₁ * ↑y₂) = coe_fn f (x₂ * ↑y₁) := sorry /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `y, z ∈ S`, we have `(f y)⁻¹ = (f z)⁻¹ → f y = f z`. -/ theorem Mathlib.add_submonoid.localization_map.neg_inj {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : M →+ N} (hf : ∀ (y : ↥S), is_add_unit (coe_fn f ↑y)) {y : ↥S} {z : ↥S} (h : -coe_fn (is_add_unit.lift_right (add_monoid_hom.mrestrict f S) hf) y = -coe_fn (is_add_unit.lift_right (add_monoid_hom.mrestrict f S) hf) z) : coe_fn f ↑y = coe_fn f ↑z := sorry /-- Given a monoid hom `f : M →* N` and submonoid `S ⊆ M` such that `f(S) ⊆ units N`, for all `y ∈ S`, `(f y)⁻¹` is unique. -/ theorem Mathlib.add_submonoid.localization_map.neg_unique {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : M →+ N} (h : ∀ (y : ↥S), is_add_unit (coe_fn f ↑y)) {y : ↥S} {z : N} (H : coe_fn f ↑y + z = 0) : ↑(-coe_fn (is_add_unit.lift_right (add_monoid_hom.mrestrict f S) h) y) = z := sorry theorem map_right_cancel {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) {x : M} {y : M} {c : ↥S} (h : coe_fn (to_map f) (↑c * x) = coe_fn (to_map f) (↑c * y)) : coe_fn (to_map f) x = coe_fn (to_map f) y := sorry theorem Mathlib.add_submonoid.localization_map.map_left_cancel {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) {x : M} {y : M} {c : ↥S} (h : coe_fn (add_submonoid.localization_map.to_map f) (x + ↑c) = coe_fn (add_submonoid.localization_map.to_map f) (y + ↑c)) : coe_fn (add_submonoid.localization_map.to_map f) x = coe_fn (add_submonoid.localization_map.to_map f) y := sorry /-- Given a localization map `f : M →* N`, the surjection sending `(x, y) : M × S` to `f x * (f y)⁻¹`. -/ def mk' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x : M) (y : ↥S) : N := coe_fn (to_map f) x * ↑(coe_fn (is_unit.lift_right (monoid_hom.mrestrict (to_map f) S) (map_units f)) y⁻¹) theorem Mathlib.add_submonoid.localization_map.mk'_add {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (x₁ : M) (x₂ : M) (y₁ : ↥S) (y₂ : ↥S) : add_submonoid.localization_map.mk' f (x₁ + x₂) (y₁ + y₂) = add_submonoid.localization_map.mk' f x₁ y₁ + add_submonoid.localization_map.mk' f x₂ y₂ := sorry theorem mk'_one {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x : M) : mk' f x 1 = coe_fn (to_map f) x := sorry /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, for all `z : N` we have that if `x : M, y ∈ S` are such that `z * f y = f x`, then `f x * (f y)⁻¹ = z`. -/ @[simp] theorem Mathlib.add_submonoid.localization_map.mk'_sec {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (z : N) : add_submonoid.localization_map.mk' f (prod.fst (add_submonoid.localization_map.sec f z)) (prod.snd (add_submonoid.localization_map.sec f z)) = z := sorry theorem mk'_surjective {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (z : N) : ∃ (x : M), ∃ (y : ↥S), mk' f x y = z := Exists.intro (prod.fst (sec f z)) (Exists.intro (prod.snd (sec f z)) (mk'_sec f z)) theorem mk'_spec {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x : M) (y : ↥S) : mk' f x y * coe_fn (to_map f) ↑y = coe_fn (to_map f) x := sorry theorem mk'_spec' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x : M) (y : ↥S) : coe_fn (to_map f) ↑y * mk' f x y = coe_fn (to_map f) x := sorry theorem eq_mk'_iff_mul_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) {x : M} {y : ↥S} {z : N} : z = mk' f x y ↔ z * coe_fn (to_map f) ↑y = coe_fn (to_map f) x := sorry theorem Mathlib.add_submonoid.localization_map.mk'_eq_iff_eq_add {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) {x : M} {y : ↥S} {z : N} : add_submonoid.localization_map.mk' f x y = z ↔ coe_fn (add_submonoid.localization_map.to_map f) x = z + coe_fn (add_submonoid.localization_map.to_map f) ↑y := sorry theorem Mathlib.add_submonoid.localization_map.mk'_eq_iff_eq {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) {x₁ : M} {x₂ : M} {y₁ : ↥S} {y₂ : ↥S} : add_submonoid.localization_map.mk' f x₁ y₁ = add_submonoid.localization_map.mk' f x₂ y₂ ↔ coe_fn (add_submonoid.localization_map.to_map f) (x₁ + ↑y₂) = coe_fn (add_submonoid.localization_map.to_map f) (x₂ + ↑y₁) := sorry protected theorem eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) {a₁ : M} {b₁ : M} {a₂ : ↥S} {b₂ : ↥S} : mk' f a₁ a₂ = mk' f b₁ b₂ ↔ ∃ (c : ↥S), a₁ * ↑b₂ * ↑c = b₁ * ↑a₂ * ↑c := iff.trans (mk'_eq_iff_eq f) (eq_iff_exists f) protected theorem eq' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) {a₁ : M} {b₁ : M} {a₂ : ↥S} {b₂ : ↥S} : mk' f a₁ a₂ = mk' f b₁ b₂ ↔ coe_fn (localization.r S) (a₁, a₂) (b₁, b₂) := sorry theorem Mathlib.add_submonoid.localization_map.eq_iff_eq {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) (g : add_submonoid.localization_map S P) {x : M} {y : M} : coe_fn (add_submonoid.localization_map.to_map f) x = coe_fn (add_submonoid.localization_map.to_map f) y ↔ coe_fn (add_submonoid.localization_map.to_map g) x = coe_fn (add_submonoid.localization_map.to_map g) y := iff.trans (add_submonoid.localization_map.eq_iff_exists f) (iff.symm (add_submonoid.localization_map.eq_iff_exists g)) theorem mk'_eq_iff_mk'_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) (g : localization_map S P) {x₁ : M} {x₂ : M} {y₁ : ↥S} {y₂ : ↥S} : mk' f x₁ y₁ = mk' f x₂ y₂ ↔ mk' g x₁ y₁ = mk' g x₂ y₂ := iff.trans (localization_map.eq' f) (iff.symm (localization_map.eq' g)) /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, for all `x₁ : M` and `y₁ ∈ S`, if `x₂ : M, y₂ ∈ S` are such that `f x₁ * (f y₁)⁻¹ * f y₂ = f x₂`, then there exists `c ∈ S` such that `x₁ * y₂ * c = x₂ * y₁ * c`. -/ theorem Mathlib.add_submonoid.localization_map.exists_of_sec_mk' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (x : M) (y : ↥S) : ∃ (c : ↥S), x + ↑(prod.snd (add_submonoid.localization_map.sec f (add_submonoid.localization_map.mk' f x y))) + ↑c = prod.fst (add_submonoid.localization_map.sec f (add_submonoid.localization_map.mk' f x y)) + ↑y + ↑c := iff.mp (add_submonoid.localization_map.eq_iff_exists f) (iff.mp (add_submonoid.localization_map.mk'_eq_iff_eq f) (Eq.symm (add_submonoid.localization_map.mk'_sec f (add_submonoid.localization_map.mk' f x y)))) theorem mk'_eq_of_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) {a₁ : M} {b₁ : M} {a₂ : ↥S} {b₂ : ↥S} (H : b₁ * ↑a₂ = a₁ * ↑b₂) : mk' f a₁ a₂ = mk' f b₁ b₂ := iff.mpr (mk'_eq_iff_eq f) (H ▸ rfl) @[simp] theorem Mathlib.add_submonoid.localization_map.mk'_self' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (y : ↥S) : add_submonoid.localization_map.mk' f (↑y) y = 0 := sorry @[simp] theorem mk'_self {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x : M) (H : x ∈ S) : mk' f x { val := x, property := H } = 1 := sorry theorem mul_mk'_eq_mk'_of_mul {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x₁ : M) (x₂ : M) (y : ↥S) : coe_fn (to_map f) x₁ * mk' f x₂ y = mk' f (x₁ * x₂) y := sorry theorem Mathlib.add_submonoid.localization_map.mk'_add_eq_mk'_of_add {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (x₁ : M) (x₂ : M) (y : ↥S) : add_submonoid.localization_map.mk' f x₂ y + coe_fn (add_submonoid.localization_map.to_map f) x₁ = add_submonoid.localization_map.mk' f (x₁ + x₂) y := sorry theorem Mathlib.add_submonoid.localization_map.add_mk'_zero_eq_mk' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (x : M) (y : ↥S) : coe_fn (add_submonoid.localization_map.to_map f) x + add_submonoid.localization_map.mk' f 0 y = add_submonoid.localization_map.mk' f x y := sorry @[simp] theorem mk'_mul_cancel_right {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) (x : M) (y : ↥S) : mk' f (x * ↑y) y = coe_fn (to_map f) x := sorry theorem Mathlib.add_submonoid.localization_map.mk'_add_cancel_left {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (x : M) (y : ↥S) : add_submonoid.localization_map.mk' f (↑y + x) y = coe_fn (add_submonoid.localization_map.to_map f) x := sorry theorem is_unit_comp {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) (j : N →* P) (y : ↥S) : is_unit (coe_fn (monoid_hom.comp j (to_map f)) ↑y) := sorry /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M` and a map of `comm_monoid`s `g : M →* P` such that `g(S) ⊆ units P`, `f x = f y → g x = g y` for all `x y : M`. -/ theorem eq_of_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} (hg : ∀ (y : ↥S), is_unit (coe_fn g ↑y)) {x : M} {y : M} (h : coe_fn (to_map f) x = coe_fn (to_map f) y) : coe_fn g x = coe_fn g y := sorry /-- Given `comm_monoid`s `M, P`, localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, and `g : M →* P` such that `g(S) ⊆ T`, `f x = f y` implies `k (g x) = k (g y)`. -/ theorem comp_eq_of_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} {T : submonoid P} {Q : Type u_4} [comm_monoid Q] (hg : ∀ (y : ↥S), coe_fn g ↑y ∈ T) (k : localization_map T Q) {x : M} {y : M} (h : coe_fn (to_map f) x = coe_fn (to_map f) y) : coe_fn (to_map k) (coe_fn g x) = coe_fn (to_map k) (coe_fn g y) := sorry /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M` and a map of `comm_monoid`s `g : M →* P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` sending `z : N` to `g x * (g y)⁻¹`, where `(x, y) : M × S` are such that `z = f x * (f y)⁻¹`. -/ def lift {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} (hg : ∀ (y : ↥S), is_unit (coe_fn g ↑y)) : N →* P := monoid_hom.mk (fun (z : N) => coe_fn g (prod.fst (sec f z)) * ↑(coe_fn (is_unit.lift_right (monoid_hom.mrestrict g S) hg) (prod.snd (sec f z))⁻¹)) sorry sorry /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M` and a map of `comm_monoid`s `g : M →* P` such that `g y` is invertible for all `y : S`, the homomorphism induced from `N` to `P` maps `f x * (f y)⁻¹` to `g x * (g y)⁻¹` for all `x : M, y ∈ S`. -/ theorem lift_mk' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} (hg : ∀ (y : ↥S), is_unit (coe_fn g ↑y)) (x : M) (y : ↥S) : coe_fn (lift f hg) (mk' f x y) = coe_fn g x * ↑(coe_fn (is_unit.lift_right (monoid_hom.mrestrict g S) hg) y⁻¹) := sorry /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N, v : P`, we have `f.lift hg z = v ↔ g x = g y * v`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem Mathlib.add_submonoid.localization_map.lift_spec {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M →+ P} (hg : ∀ (y : ↥S), is_add_unit (coe_fn g ↑y)) (z : N) (v : P) : coe_fn (add_submonoid.localization_map.lift f hg) z = v ↔ coe_fn g (prod.fst (add_submonoid.localization_map.sec f z)) = coe_fn g ↑(prod.snd (add_submonoid.localization_map.sec f z)) + v := add_submonoid.localization_map.add_neg_left hg (prod.snd (add_submonoid.localization_map.sec f z)) (coe_fn g (prod.fst (add_submonoid.localization_map.sec f z))) v /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N, v w : P`, we have `f.lift hg z * w = v ↔ g x * w = g y * v`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem Mathlib.add_submonoid.localization_map.lift_spec_add {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M →+ P} (hg : ∀ (y : ↥S), is_add_unit (coe_fn g ↑y)) (z : N) (w : P) (v : P) : coe_fn (add_submonoid.localization_map.lift f hg) z + w = v ↔ coe_fn g (prod.fst (add_submonoid.localization_map.sec f z)) + w = coe_fn g ↑(prod.snd (add_submonoid.localization_map.sec f z)) + v := sorry theorem lift_mk'_spec {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} (hg : ∀ (y : ↥S), is_unit (coe_fn g ↑y)) (x : M) (v : P) (y : ↥S) : coe_fn (lift f hg) (mk' f x y) = v ↔ coe_fn g x = coe_fn g ↑y * v := eq.mpr (id (Eq._oldrec (Eq.refl (coe_fn (lift f hg) (mk' f x y) = v ↔ coe_fn g x = coe_fn g ↑y * v)) (lift_mk' f hg x y))) (mul_inv_left hg y (coe_fn g x) v) /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N`, we have `f.lift hg z * g y = g x`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem lift_mul_right {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} (hg : ∀ (y : ↥S), is_unit (coe_fn g ↑y)) (z : N) : coe_fn (lift f hg) z * coe_fn g ↑(prod.snd (sec f z)) = coe_fn g (prod.fst (sec f z)) := sorry /-- Given a localization map `f : M →* N` for a submonoid `S ⊆ M`, if a `comm_monoid` map `g : M →* P` induces a map `f.lift hg : N →* P` then for all `z : N`, we have `g y * f.lift hg z = g x`, where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem Mathlib.add_submonoid.localization_map.lift_add_left {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M →+ P} (hg : ∀ (y : ↥S), is_add_unit (coe_fn g ↑y)) (z : N) : coe_fn g ↑(prod.snd (add_submonoid.localization_map.sec f z)) + coe_fn (add_submonoid.localization_map.lift f hg) z = coe_fn g (prod.fst (add_submonoid.localization_map.sec f z)) := sorry @[simp] theorem lift_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} (hg : ∀ (y : ↥S), is_unit (coe_fn g ↑y)) (x : M) : coe_fn (lift f hg) (coe_fn (to_map f) x) = coe_fn g x := sorry theorem Mathlib.add_submonoid.localization_map.lift_eq_iff {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M →+ P} (hg : ∀ (y : ↥S), is_add_unit (coe_fn g ↑y)) {x : M × ↥S} {y : M × ↥S} : coe_fn (add_submonoid.localization_map.lift f hg) (add_submonoid.localization_map.mk' f (prod.fst x) (prod.snd x)) = coe_fn (add_submonoid.localization_map.lift f hg) (add_submonoid.localization_map.mk' f (prod.fst y) (prod.snd y)) ↔ coe_fn g (prod.fst x + ↑(prod.snd y)) = coe_fn g (prod.fst y + ↑(prod.snd x)) := sorry @[simp] theorem Mathlib.add_submonoid.localization_map.lift_comp {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M →+ P} (hg : ∀ (y : ↥S), is_add_unit (coe_fn g ↑y)) : add_monoid_hom.comp (add_submonoid.localization_map.lift f hg) (add_submonoid.localization_map.to_map f) = g := add_monoid_hom.ext fun (x : M) => add_submonoid.localization_map.lift_eq f hg x @[simp] theorem lift_of_comp {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) (j : N →* P) : lift f (is_unit_comp f j) = j := sorry theorem epic_of_localization_map {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {j : N →* P} {k : N →* P} (h : ∀ (a : M), coe_fn (monoid_hom.comp j (to_map f)) a = coe_fn (monoid_hom.comp k (to_map f)) a) : j = k := sorry theorem Mathlib.add_submonoid.localization_map.lift_unique {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M →+ P} (hg : ∀ (y : ↥S), is_add_unit (coe_fn g ↑y)) {j : N →+ P} (hj : ∀ (x : M), coe_fn j (coe_fn (add_submonoid.localization_map.to_map f) x) = coe_fn g x) : add_submonoid.localization_map.lift f hg = j := sorry @[simp] theorem Mathlib.add_submonoid.localization_map.lift_id {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (x : N) : coe_fn (add_submonoid.localization_map.lift f (add_submonoid.localization_map.map_units f)) x = x := iff.mp add_monoid_hom.ext_iff (add_submonoid.localization_map.lift_of_comp f (add_monoid_hom.id N)) x /-- Given two localization maps `f : M →* N, k : M →* P` for a submonoid `S ⊆ M`, the hom from `P` to `N` induced by `f` is left inverse to the hom from `N` to `P` induced by `k`. -/ @[simp] theorem lift_left_inverse {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {k : localization_map S P} (z : N) : coe_fn (lift k (map_units f)) (coe_fn (lift f (map_units k)) z) = z := sorry theorem lift_surjective_iff {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} (hg : ∀ (y : ↥S), is_unit (coe_fn g ↑y)) : function.surjective ⇑(lift f hg) ↔ ∀ (v : P), ∃ (x : M × ↥S), v * coe_fn g ↑(prod.snd x) = coe_fn g (prod.fst x) := sorry theorem lift_injective_iff {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} (hg : ∀ (y : ↥S), is_unit (coe_fn g ↑y)) : function.injective ⇑(lift f hg) ↔ ∀ (x y : M), coe_fn (to_map f) x = coe_fn (to_map f) y ↔ coe_fn g x = coe_fn g y := sorry /-- Given a `comm_monoid` homomorphism `g : M →* P` where for submonoids `S ⊆ M, T ⊆ P` we have `g(S) ⊆ T`, the induced monoid homomorphism from the localization of `M` at `S` to the localization of `P` at `T`: if `f : M →* N` and `k : P →* Q` are localization maps for `S` and `T` respectively, we send `z : N` to `k (g x) * (k (g y))⁻¹`, where `(x, y) : M × S` are such that `z = f x * (f y)⁻¹`. -/ def map {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} {T : submonoid P} (hy : ∀ (y : ↥S), coe_fn g ↑y ∈ T) {Q : Type u_4} [comm_monoid Q] (k : localization_map T Q) : N →* Q := lift f sorry theorem Mathlib.add_submonoid.localization_map.map_eq {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M →+ P} {T : add_submonoid P} (hy : ∀ (y : ↥S), coe_fn g ↑y ∈ T) {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} (x : M) : coe_fn (add_submonoid.localization_map.map f hy k) (coe_fn (add_submonoid.localization_map.to_map f) x) = coe_fn (add_submonoid.localization_map.to_map k) (coe_fn g x) := add_submonoid.localization_map.lift_eq f (fun (y : ↥S) => add_submonoid.localization_map.map_units k { val := coe_fn g ↑y, property := hy y }) x @[simp] theorem Mathlib.add_submonoid.localization_map.map_comp {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M →+ P} {T : add_submonoid P} (hy : ∀ (y : ↥S), coe_fn g ↑y ∈ T) {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} : add_monoid_hom.comp (add_submonoid.localization_map.map f hy k) (add_submonoid.localization_map.to_map f) = add_monoid_hom.comp (add_submonoid.localization_map.to_map k) g := add_submonoid.localization_map.lift_comp f fun (y : ↥S) => add_submonoid.localization_map.map_units k { val := coe_fn g ↑y, property := hy y } theorem map_mk' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} {T : submonoid P} (hy : ∀ (y : ↥S), coe_fn g ↑y ∈ T) {Q : Type u_4} [comm_monoid Q] {k : localization_map T Q} (x : M) (y : ↥S) : coe_fn (map f hy k) (mk' f x y) = mk' k (coe_fn g x) { val := coe_fn g ↑y, property := hy y } := sorry /-- Given localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M →* P` induces a `f.map hy k : N →* Q`, then for all `z : N`, `u : Q`, we have `f.map hy k z = u ↔ k (g x) = k (g y) * u` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem map_spec {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} {T : submonoid P} (hy : ∀ (y : ↥S), coe_fn g ↑y ∈ T) {Q : Type u_4} [comm_monoid Q] {k : localization_map T Q} (z : N) (u : Q) : coe_fn (map f hy k) z = u ↔ coe_fn (to_map k) (coe_fn g (prod.fst (sec f z))) = coe_fn (to_map k) (coe_fn g ↑(prod.snd (sec f z))) * u := lift_spec f (fun (y : ↥S) => map_units k { val := coe_fn g ↑y, property := hy y }) z u /-- Given localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M →* P` induces a `f.map hy k : N →* Q`, then for all `z : N`, we have `f.map hy k z * k (g y) = k (g x)` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem map_mul_right {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} {T : submonoid P} (hy : ∀ (y : ↥S), coe_fn g ↑y ∈ T) {Q : Type u_4} [comm_monoid Q] {k : localization_map T Q} (z : N) : coe_fn (map f hy k) z * coe_fn (to_map k) (coe_fn g ↑(prod.snd (sec f z))) = coe_fn (to_map k) (coe_fn g (prod.fst (sec f z))) := lift_mul_right f (fun (y : ↥S) => map_units k { val := coe_fn g ↑y, property := hy y }) z /-- Given localization maps `f : M →* N, k : P →* Q` for submonoids `S, T` respectively, if a `comm_monoid` homomorphism `g : M →* P` induces a `f.map hy k : N →* Q`, then for all `z : N`, we have `k (g y) * f.map hy k z = k (g x)` where `x : M, y ∈ S` are such that `z * f y = f x`. -/ theorem Mathlib.add_submonoid.localization_map.map_add_left {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M →+ P} {T : add_submonoid P} (hy : ∀ (y : ↥S), coe_fn g ↑y ∈ T) {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} (z : N) : coe_fn (add_submonoid.localization_map.to_map k) (coe_fn g ↑(prod.snd (add_submonoid.localization_map.sec f z))) + coe_fn (add_submonoid.localization_map.map f hy k) z = coe_fn (add_submonoid.localization_map.to_map k) (coe_fn g (prod.fst (add_submonoid.localization_map.sec f z))) := sorry @[simp] theorem Mathlib.add_submonoid.localization_map.map_id {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) (z : N) : coe_fn (add_submonoid.localization_map.map f (fun (y : ↥S) => (fun (this : coe_fn (add_monoid_hom.id M) ↑y ∈ S) => this) (subtype.property y)) f) z = z := add_submonoid.localization_map.lift_id f z /-- If `comm_monoid` homs `g : M →* P, l : P →* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ theorem map_comp_map {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {g : M →* P} {T : submonoid P} (hy : ∀ (y : ↥S), coe_fn g ↑y ∈ T) {Q : Type u_4} [comm_monoid Q] {k : localization_map T Q} {A : Type u_5} [comm_monoid A] {U : submonoid A} {R : Type u_6} [comm_monoid R] (j : localization_map U R) {l : P →* A} (hl : ∀ (w : ↥T), coe_fn l ↑w ∈ U) : monoid_hom.comp (map k hl j) (map f hy k) = map f (fun (x : ↥S) => (fun (this : coe_fn (monoid_hom.comp l g) ↑x ∈ U) => this) (hl { val := coe_fn g ↑x, property := hy x })) j := sorry /-- If `comm_monoid` homs `g : M →* P, l : P →* A` induce maps of localizations, the composition of the induced maps equals the map of localizations induced by `l ∘ g`. -/ theorem Mathlib.add_submonoid.localization_map.map_map {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {g : M →+ P} {T : add_submonoid P} (hy : ∀ (y : ↥S), coe_fn g ↑y ∈ T) {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} {A : Type u_5} [add_comm_monoid A] {U : add_submonoid A} {R : Type u_6} [add_comm_monoid R] (j : add_submonoid.localization_map U R) {l : P →+ A} (hl : ∀ (w : ↥T), coe_fn l ↑w ∈ U) (x : N) : coe_fn (add_submonoid.localization_map.map k hl j) (coe_fn (add_submonoid.localization_map.map f hy k) x) = coe_fn (add_submonoid.localization_map.map f (fun (x : ↥S) => (fun (this : coe_fn (add_monoid_hom.comp l g) ↑x ∈ U) => this) (hl { val := coe_fn g ↑x, property := hy x })) j) x := sorry /-- Given `x : M`, the type of `comm_monoid` homomorphisms `f : M →* N` such that `N` is isomorphic to the localization of `M` at the submonoid generated by `x`. -/ def away_map {M : Type u_1} [comm_monoid M] (x : M) (N' : Type u_2) [comm_monoid N'] := localization_map (powers x) N' /-- Given `x : M` and a localization map `F : M →* N` away from `x`, `inv_self` is `(F x)⁻¹`. -/ def away_map.inv_self {M : Type u_1} [comm_monoid M] {N : Type u_2} [comm_monoid N] (x : M) (F : away_map x N) : N := mk' F 1 { val := x, property := sorry } /-- Given `x : M`, a localization map `F : M →* N` away from `x`, and a map of `comm_monoid`s `g : M →* P` such that `g x` is invertible, the homomorphism induced from `N` to `P` sending `z : N` to `g y * (g x)⁻ⁿ`, where `y : M, n : ℕ` are such that `z = F y * (F x)⁻ⁿ`. -/ def away_map.lift {M : Type u_1} [comm_monoid M] {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] {g : M →* P} (x : M) (F : away_map x N) (hg : is_unit (coe_fn g x)) : N →* P := lift F sorry @[simp] theorem away_map.lift_eq {M : Type u_1} [comm_monoid M] {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] {g : M →* P} (x : M) (F : away_map x N) (hg : is_unit (coe_fn g x)) (a : M) : coe_fn (away_map.lift x F hg) (coe_fn (to_map F) a) = coe_fn g a := lift_eq F (away_map.lift._proof_1 x hg) a @[simp] theorem away_map.lift_comp {M : Type u_1} [comm_monoid M] {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] {g : M →* P} (x : M) (F : away_map x N) (hg : is_unit (coe_fn g x)) : monoid_hom.comp (away_map.lift x F hg) (to_map F) = g := lift_comp F (away_map.lift._proof_1 x hg) /-- Given `x y : M` and localization maps `F : M →* N, G : M →* P` away from `x` and `x * y` respectively, the homomorphism induced from `N` to `P`. -/ def away_to_away_right {M : Type u_1} [comm_monoid M] {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (x : M) (F : away_map x N) (y : M) (G : away_map (x * y) P) : N →* P := away_map.lift x F sorry end localization_map end submonoid namespace add_submonoid namespace localization_map /-- Given `x : A` and a localization map `F : A →+ B` away from `x`, `neg_self` is `- (F x)`. -/ def away_map.neg_self {A : Type u_4} [add_comm_monoid A] (x : A) {B : Type u_5} [add_comm_monoid B] (F : away_map x B) : B := mk' F 0 { val := x, property := sorry } /-- Given `x : A`, a localization map `F : A →+ B` away from `x`, and a map of `add_comm_monoid`s `g : A →+ C` such that `g x` is invertible, the homomorphism induced from `B` to `C` sending `z : B` to `g y - n • g x`, where `y : A, n : ℕ` are such that `z = F y - n • F x`. -/ def away_map.lift {A : Type u_4} [add_comm_monoid A] (x : A) {B : Type u_5} [add_comm_monoid B] (F : away_map x B) {C : Type u_6} [add_comm_monoid C] {g : A →+ C} (hg : is_add_unit (coe_fn g x)) : B →+ C := lift F sorry @[simp] theorem away_map.lift_eq {A : Type u_4} [add_comm_monoid A] (x : A) {B : Type u_5} [add_comm_monoid B] (F : away_map x B) {C : Type u_6} [add_comm_monoid C] {g : A →+ C} (hg : is_add_unit (coe_fn g x)) (a : A) : coe_fn (away_map.lift x F hg) (coe_fn (to_map F) a) = coe_fn g a := lift_eq F (away_map.lift._proof_1 x hg) a @[simp] theorem away_map.lift_comp {A : Type u_4} [add_comm_monoid A] (x : A) {B : Type u_5} [add_comm_monoid B] (F : away_map x B) {C : Type u_6} [add_comm_monoid C] {g : A →+ C} (hg : is_add_unit (coe_fn g x)) : add_monoid_hom.comp (away_map.lift x F hg) (to_map F) = g := lift_comp F (away_map.lift._proof_1 x hg) /-- Given `x y : A` and localization maps `F : A →+ B, G : A →+ C` away from `x` and `x + y` respectively, the homomorphism induced from `B` to `C`. -/ def away_to_away_right {A : Type u_4} [add_comm_monoid A] (x : A) {B : Type u_5} [add_comm_monoid B] (F : away_map x B) {C : Type u_6} [add_comm_monoid C] (y : A) (G : away_map (x + y) C) : B →+ C := away_map.lift x F sorry end localization_map end add_submonoid namespace submonoid namespace localization_map /-- If `f : M →* N` and `k : M →* P` are localization maps for a submonoid `S`, we get an isomorphism of `N` and `P`. -/ def mul_equiv_of_localizations {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) (k : localization_map S P) : N ≃* P := mul_equiv.mk (⇑(lift f (map_units k))) (⇑(lift k (map_units f))) (lift_left_inverse f) (lift_left_inverse k) sorry @[simp] theorem Mathlib.add_submonoid.localization_map.add_equiv_of_localizations_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {k : add_submonoid.localization_map S P} {x : N} : coe_fn (add_submonoid.localization_map.add_equiv_of_localizations f k) x = coe_fn (add_submonoid.localization_map.lift f (add_submonoid.localization_map.map_units k)) x := rfl @[simp] theorem Mathlib.add_submonoid.localization_map.add_equiv_of_localizations_symm_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {k : add_submonoid.localization_map S P} {x : P} : coe_fn (add_equiv.symm (add_submonoid.localization_map.add_equiv_of_localizations f k)) x = coe_fn (add_submonoid.localization_map.lift k (add_submonoid.localization_map.map_units f)) x := rfl theorem Mathlib.add_submonoid.localization_map.add_equiv_of_localizations_symm_eq_add_equiv_of_localizations {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {k : add_submonoid.localization_map S P} : add_equiv.symm (add_submonoid.localization_map.add_equiv_of_localizations k f) = add_submonoid.localization_map.add_equiv_of_localizations f k := rfl /-- If `f : M →* N` is a localization map for a submonoid `S` and `k : N ≃* P` is an isomorphism of `comm_monoid`s, `k ∘ f` is a localization map for `M` at `S`. -/ def of_mul_equiv_of_localizations {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) (k : N ≃* P) : localization_map S P := monoid_hom.to_localization_map (monoid_hom.comp (mul_equiv.to_monoid_hom k) (to_map f)) sorry sorry sorry @[simp] theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_localizations_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {k : N ≃+ P} (x : M) : coe_fn (add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_localizations f k)) x = coe_fn k (coe_fn (add_submonoid.localization_map.to_map f) x) := rfl theorem of_mul_equiv_of_localizations_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {k : N ≃* P} : to_map (of_mul_equiv_of_localizations f k) = monoid_hom.comp (mul_equiv.to_monoid_hom k) (to_map f) := rfl theorem symm_comp_of_mul_equiv_of_localizations_apply {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {k : N ≃* P} (x : M) : coe_fn (mul_equiv.symm k) (coe_fn (to_map (of_mul_equiv_of_localizations f k)) x) = coe_fn (to_map f) x := mul_equiv.symm_apply_apply k (coe_fn (to_map f) x) theorem symm_comp_of_mul_equiv_of_localizations_apply' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {k : P ≃* N} (x : M) : coe_fn k (coe_fn (to_map (of_mul_equiv_of_localizations f (mul_equiv.symm k))) x) = coe_fn (to_map f) x := mul_equiv.apply_symm_apply k (coe_fn (to_map f) x) theorem of_mul_equiv_of_localizations_eq_iff_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {k : N ≃* P} {x : M} {y : P} : coe_fn (to_map (of_mul_equiv_of_localizations f k)) x = y ↔ coe_fn (to_map f) x = coe_fn (mul_equiv.symm k) y := iff.symm (equiv.eq_symm_apply (mul_equiv.to_equiv k)) theorem mul_equiv_of_localizations_right_inv {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) (k : localization_map S P) : of_mul_equiv_of_localizations f (mul_equiv_of_localizations f k) = k := to_map_injective (lift_comp f (map_units k)) theorem Mathlib.add_submonoid.localization_map.add_equiv_of_localizations_right_inv_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {k : add_submonoid.localization_map S P} {x : M} : coe_fn (add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_localizations f (add_submonoid.localization_map.add_equiv_of_localizations f k))) x = coe_fn (add_submonoid.localization_map.to_map k) x := iff.mp add_submonoid.localization_map.ext_iff (add_submonoid.localization_map.add_equiv_of_localizations_right_inv f k) x theorem Mathlib.add_submonoid.localization_map.add_equiv_of_localizations_left_neg {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) (k : N ≃+ P) : add_submonoid.localization_map.add_equiv_of_localizations f (add_submonoid.localization_map.of_add_equiv_of_localizations f k) = k := add_equiv.ext (iff.mp add_monoid_hom.ext_iff (add_submonoid.localization_map.lift_of_comp f (add_equiv.to_add_monoid_hom k))) @[simp] theorem mul_equiv_of_localizations_left_inv_apply {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {k : N ≃* P} (x : N) : coe_fn (mul_equiv_of_localizations f (of_mul_equiv_of_localizations f k)) x = coe_fn k x := sorry @[simp] theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_localizations_id {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] (f : add_submonoid.localization_map S N) : add_submonoid.localization_map.of_add_equiv_of_localizations f (add_equiv.refl N) = f := sorry theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_localizations_comp {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {Q : Type u_4} [add_comm_monoid Q] {k : N ≃+ P} {j : P ≃+ Q} : add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_localizations f (add_equiv.trans k j)) = add_monoid_hom.comp (add_equiv.to_add_monoid_hom j) (add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_localizations f k)) := sorry /-- Given `comm_monoid`s `M, P` and submonoids `S ⊆ M, T ⊆ P`, if `f : M →* N` is a localization map for `S` and `k : P ≃* M` is an isomorphism of `comm_monoid`s such that `k(T) = S`, `f ∘ k` is a localization map for `T`. -/ def Mathlib.add_submonoid.localization_map.of_add_equiv_of_dom {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {k : P ≃+ M} (H : add_submonoid.map (add_equiv.to_add_monoid_hom k) T = S) : add_submonoid.localization_map T N := add_monoid_hom.to_localization_map (add_monoid_hom.comp (add_submonoid.localization_map.to_map f) (add_equiv.to_add_monoid_hom k)) sorry sorry sorry @[simp] theorem of_mul_equiv_of_dom_apply {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {T : submonoid P} {k : P ≃* M} (H : map (mul_equiv.to_monoid_hom k) T = S) (x : P) : coe_fn (to_map (of_mul_equiv_of_dom f H)) x = coe_fn (to_map f) (coe_fn k x) := rfl theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_dom_eq {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {k : P ≃+ M} (H : add_submonoid.map (add_equiv.to_add_monoid_hom k) T = S) : add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_dom f H) = add_monoid_hom.comp (add_submonoid.localization_map.to_map f) (add_equiv.to_add_monoid_hom k) := rfl theorem of_mul_equiv_of_dom_comp_symm {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {T : submonoid P} {k : P ≃* M} (H : map (mul_equiv.to_monoid_hom k) T = S) (x : M) : coe_fn (to_map (of_mul_equiv_of_dom f H)) (coe_fn (mul_equiv.symm k) x) = coe_fn (to_map f) x := congr_arg (⇑(to_map f)) (mul_equiv.apply_symm_apply k x) theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_dom_comp {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {k : M ≃+ P} (H : add_submonoid.map (add_equiv.to_add_monoid_hom (add_equiv.symm k)) T = S) (x : M) : coe_fn (add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_dom f H)) (coe_fn k x) = coe_fn (add_submonoid.localization_map.to_map f) x := congr_arg (⇑(add_submonoid.localization_map.to_map f)) (add_equiv.symm_apply_apply k x) /-- A special case of `f ∘ id = f`, `f` a localization map. -/ @[simp] theorem of_mul_equiv_of_dom_id {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : localization_map S N) : of_mul_equiv_of_dom f ((fun (this : map (mul_equiv.to_monoid_hom (mul_equiv.refl M)) S = S) => this) (ext fun (x : M) => { mp := fun (_x : x ∈ map (mul_equiv.to_monoid_hom (mul_equiv.refl M)) S) => (fun (_a : x ∈ map (mul_equiv.to_monoid_hom (mul_equiv.refl M)) S) => Exists.dcases_on _a fun (w : M) (h : w ∈ ↑S ∧ coe_fn (mul_equiv.to_monoid_hom (mul_equiv.refl M)) w = x) => and.dcases_on h fun (h_left : w ∈ ↑S) (h_right : coe_fn (mul_equiv.to_monoid_hom (mul_equiv.refl M)) w = x) => idRhs ((fun (_x : M) => _x ∈ S) x) (h_right ▸ h_left)) _x, mpr := fun (h : x ∈ S) => Exists.intro x { left := h, right := rfl } })) = f := sorry /-- Given localization maps `f : M →* N, k : P →* U` for submonoids `S, T` respectively, an isomorphism `j : M ≃* P` such that `j(S) = T` induces an isomorphism of localizations `N ≃* U`. -/ def Mathlib.add_submonoid.localization_map.add_equiv_of_add_equiv {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {Q : Type u_4} [add_comm_monoid Q] (k : add_submonoid.localization_map T Q) {j : M ≃+ P} (H : add_submonoid.map (add_equiv.to_add_monoid_hom j) S = T) : N ≃+ Q := add_submonoid.localization_map.add_equiv_of_localizations f (add_submonoid.localization_map.of_add_equiv_of_dom k H) @[simp] theorem Mathlib.add_submonoid.localization_map.add_equiv_of_add_equiv_eq_map_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} {j : M ≃+ P} (H : add_submonoid.map (add_equiv.to_add_monoid_hom j) S = T) (x : N) : coe_fn (add_submonoid.localization_map.add_equiv_of_add_equiv f k H) x = coe_fn (add_submonoid.localization_map.map f (fun (y : ↥S) => (fun (this : coe_fn (add_equiv.to_add_monoid_hom j) ↑y ∈ T) => this) (H ▸ set.mem_image_of_mem (⇑j) (subtype.property y))) k) x := rfl theorem mul_equiv_of_mul_equiv_eq_map {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {T : submonoid P} {Q : Type u_4} [comm_monoid Q] {k : localization_map T Q} {j : M ≃* P} (H : map (mul_equiv.to_monoid_hom j) S = T) : mul_equiv.to_monoid_hom (mul_equiv_of_mul_equiv f k H) = map f (fun (y : ↥S) => (fun (this : coe_fn (mul_equiv.to_monoid_hom j) ↑y ∈ T) => this) (H ▸ set.mem_image_of_mem (⇑j) (subtype.property y))) k := rfl @[simp] theorem mul_equiv_of_mul_equiv_eq {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {P : Type u_3} [comm_monoid P] (f : localization_map S N) {T : submonoid P} {Q : Type u_4} [comm_monoid Q] {k : localization_map T Q} {j : M ≃* P} (H : map (mul_equiv.to_monoid_hom j) S = T) (x : M) : coe_fn (mul_equiv_of_mul_equiv f k H) (coe_fn (to_map f) x) = coe_fn (to_map k) (coe_fn j x) := map_eq f (fun (y : ↥S) => H ▸ set.mem_image_of_mem (⇑j) (subtype.property y)) x @[simp] theorem Mathlib.add_submonoid.localization_map.add_equiv_of_add_equiv_mk' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} {j : M ≃+ P} (H : add_submonoid.map (add_equiv.to_add_monoid_hom j) S = T) (x : M) (y : ↥S) : coe_fn (add_submonoid.localization_map.add_equiv_of_add_equiv f k H) (add_submonoid.localization_map.mk' f x y) = add_submonoid.localization_map.mk' k (coe_fn j x) { val := coe_fn j ↑y, property := H ▸ set.mem_image_of_mem (⇑j) (subtype.property y) } := add_submonoid.localization_map.map_mk' f (fun (y : ↥S) => H ▸ set.mem_image_of_mem (⇑j) (subtype.property y)) x y @[simp] theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_add_equiv_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} {j : M ≃+ P} (H : add_submonoid.map (add_equiv.to_add_monoid_hom j) S = T) (x : M) : coe_fn (add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_localizations f (add_submonoid.localization_map.add_equiv_of_add_equiv f k H))) x = coe_fn (add_submonoid.localization_map.to_map k) (coe_fn j x) := sorry theorem Mathlib.add_submonoid.localization_map.of_add_equiv_of_add_equiv {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {P : Type u_3} [add_comm_monoid P] (f : add_submonoid.localization_map S N) {T : add_submonoid P} {Q : Type u_4} [add_comm_monoid Q] {k : add_submonoid.localization_map T Q} {j : M ≃+ P} (H : add_submonoid.map (add_equiv.to_add_monoid_hom j) S = T) : add_submonoid.localization_map.to_map (add_submonoid.localization_map.of_add_equiv_of_localizations f (add_submonoid.localization_map.add_equiv_of_add_equiv f k H)) = add_monoid_hom.comp (add_submonoid.localization_map.to_map k) (add_equiv.to_add_monoid_hom j) := add_monoid_hom.ext (add_submonoid.localization_map.of_add_equiv_of_add_equiv_apply f H) end localization_map end submonoid namespace localization /-- Natural hom sending `x : M`, `M` a `comm_monoid`, to the equivalence class of `(x, 1)` in the localization of `M` at a submonoid. -/ def monoid_of {M : Type u_1} [comm_monoid M] (S : submonoid M) : submonoid.localization_map S (localization S) := submonoid.localization_map.mk (monoid_hom.to_fun (monoid_hom.comp (con.mk' (r S)) (monoid_hom.inl M ↥S))) sorry sorry sorry sorry sorry theorem Mathlib.add_localization.mk_zero_eq_add_monoid_of_mk {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} (x : M) : add_localization.mk x 0 = coe_fn (add_submonoid.localization_map.to_map (add_localization.add_monoid_of S)) x := rfl theorem Mathlib.add_localization.mk_eq_add_monoid_of_mk'_apply {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} (x : M) (y : ↥S) : add_localization.mk x y = add_submonoid.localization_map.mk' (add_localization.add_monoid_of S) x y := sorry @[simp] theorem Mathlib.add_localization.mk_eq_add_monoid_of_mk' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} : add_localization.mk = add_submonoid.localization_map.mk' (add_localization.add_monoid_of S) := funext fun (_x : M) => funext fun (_x_1 : ↥S) => add_localization.mk_eq_add_monoid_of_mk'_apply _x _x_1 /-- Given a localization map `f : M →* N` for a submonoid `S`, we get an isomorphism between the localization of `M` at `S` as a quotient type and `N`. -/ def mul_equiv_of_quotient {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] (f : submonoid.localization_map S N) : localization S ≃* N := submonoid.localization_map.mul_equiv_of_localizations (monoid_of S) f @[simp] theorem mul_equiv_of_quotient_apply {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : submonoid.localization_map S N} (x : localization S) : coe_fn (mul_equiv_of_quotient f) x = coe_fn (submonoid.localization_map.lift (monoid_of S) (submonoid.localization_map.map_units f)) x := rfl @[simp] theorem mul_equiv_of_quotient_mk' {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : submonoid.localization_map S N} (x : M) (y : ↥S) : coe_fn (mul_equiv_of_quotient f) (submonoid.localization_map.mk' (monoid_of S) x y) = submonoid.localization_map.mk' f x y := submonoid.localization_map.lift_mk' (monoid_of S) (submonoid.localization_map.map_units f) x y theorem mul_equiv_of_quotient_mk {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : submonoid.localization_map S N} (x : M) (y : ↥S) : coe_fn (mul_equiv_of_quotient f) (mk x y) = submonoid.localization_map.mk' f x y := sorry @[simp] theorem Mathlib.add_localization.add_equiv_of_quotient_add_monoid_of {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : add_submonoid.localization_map S N} (x : M) : coe_fn (add_localization.add_equiv_of_quotient f) (coe_fn (add_submonoid.localization_map.to_map (add_localization.add_monoid_of S)) x) = coe_fn (add_submonoid.localization_map.to_map f) x := add_submonoid.localization_map.lift_eq (add_localization.add_monoid_of S) (add_submonoid.localization_map.map_units f) x @[simp] theorem Mathlib.add_localization.add_equiv_of_quotient_symm_mk' {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : add_submonoid.localization_map S N} (x : M) (y : ↥S) : coe_fn (add_equiv.symm (add_localization.add_equiv_of_quotient f)) (add_submonoid.localization_map.mk' f x y) = add_submonoid.localization_map.mk' (add_localization.add_monoid_of S) x y := add_submonoid.localization_map.lift_mk' f (add_submonoid.localization_map.map_units (add_localization.add_monoid_of S)) x y theorem Mathlib.add_localization.add_equiv_of_quotient_symm_mk {M : Type u_1} [add_comm_monoid M] {S : add_submonoid M} {N : Type u_2} [add_comm_monoid N] {f : add_submonoid.localization_map S N} (x : M) (y : ↥S) : coe_fn (add_equiv.symm (add_localization.add_equiv_of_quotient f)) (add_submonoid.localization_map.mk' f x y) = add_localization.mk x y := sorry @[simp] theorem mul_equiv_of_quotient_symm_monoid_of {M : Type u_1} [comm_monoid M] {S : submonoid M} {N : Type u_2} [comm_monoid N] {f : submonoid.localization_map S N} (x : M) : coe_fn (mul_equiv.symm (mul_equiv_of_quotient f)) (coe_fn (submonoid.localization_map.to_map f) x) = coe_fn (submonoid.localization_map.to_map (monoid_of S)) x := submonoid.localization_map.lift_eq f (submonoid.localization_map.map_units (monoid_of S)) x /-- Given `x : M`, the localization of `M` at the submonoid generated by `x`, as a quotient. -/ def Mathlib.add_localization.away {M : Type u_1} [add_comm_monoid M] (x : M) := add_localization (add_submonoid.multiples x) /-- Given `x : M`, `inv_self` is `x⁻¹` in the localization (as a quotient type) of `M` at the submonoid generated by `x`. -/ def away.inv_self {M : Type u_1} [comm_monoid M] (x : M) : away x := mk 1 { val := x, property := sorry } /-- Given `x : M`, the natural hom sending `y : M`, `M` a `comm_monoid`, to the equivalence class of `(y, 1)` in the localization of `M` at the submonoid generated by `x`. -/ def away.monoid_of {M : Type u_1} [comm_monoid M] (x : M) : submonoid.localization_map.away_map x (away x) := monoid_of (submonoid.powers x) @[simp] theorem Mathlib.add_localization.away.mk_eq_add_monoid_of_mk' {M : Type u_1} [add_comm_monoid M] (x : M) : add_localization.mk = add_submonoid.localization_map.mk' (add_localization.away.add_monoid_of x) := add_localization.mk_eq_add_monoid_of_mk' /-- Given `x : M` and a localization map `f : M →* N` away from `x`, we get an isomorphism between the localization of `M` at the submonoid generated by `x` as a quotient type and `N`. -/ def away.mul_equiv_of_quotient {M : Type u_1} [comm_monoid M] {N : Type u_2} [comm_monoid N] (x : M) (f : submonoid.localization_map.away_map x N) : away x ≃* N := mul_equiv_of_quotient f
b85214e7141c01c030529be64f6e9c96a419ebee
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Elab/BindersUtil.lean
9247ba043f8b405789b0b318bbb2dc958db26888
[ "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
467
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 -/ namespace Lean.Elab.Term /- Recall that ``` def typeSpec := leading_parser " : " >> termParser def optType : Parser := optional typeSpec ``` -/ def expandOptType (ref : Syntax) (optType : Syntax) : Syntax := if optType.isNone then mkHole ref else optType[0][1] end Lean.Elab.Term
9f40ea3605b3a5216d078fae5fc9e89e0c6c7699
9dc8cecdf3c4634764a18254e94d43da07142918
/src/algebra/hom/equiv.lean
6c97f007cdda4dc1b870c5a404b27bce2cafa84d
[ "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
29,711
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, Callum Sutton, Yury Kudryashov -/ import algebra.group.type_tags import algebra.group_with_zero.basic import data.pi.algebra /-! # Multiplicative and additive equivs In this file we define two extensions of `equiv` called `add_equiv` and `mul_equiv`, which are datatypes representing isomorphisms of `add_monoid`s/`add_group`s and `monoid`s/`group`s. ## Notations * ``infix ` ≃* `:25 := mul_equiv`` * ``infix ` ≃+ `:25 := add_equiv`` The extended equivs all have coercions to functions, and the coercions are the canonical notation when treating the isomorphisms as maps. ## Implementation notes The fields for `mul_equiv`, `add_equiv` now avoid the unbundled `is_mul_hom` and `is_add_hom`, as these are deprecated. ## Tags equiv, mul_equiv, add_equiv -/ variables {F α β A B M N P Q G H : Type*} /-- Makes a multiplicative inverse from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive inverse from a bijection which preserves addition."] def mul_hom.inverse [has_mul M] [has_mul N] (f : M →ₙ* N) (g : N → M) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : N →ₙ* M := { to_fun := g, map_mul' := λ x y, calc g (x * y) = g (f (g x) * f (g y)) : by rw [h₂ x, h₂ y] ... = g (f (g x * g y)) : by rw f.map_mul ... = g x * g y : h₁ _, } /-- The inverse of a bijective `monoid_hom` is a `monoid_hom`. -/ @[to_additive "The inverse of a bijective `add_monoid_hom` is an `add_monoid_hom`.", simps] def monoid_hom.inverse {A B : Type*} [monoid A] [monoid B] (f : A →* B) (g : B → A) (h₁ : function.left_inverse g f) (h₂ : function.right_inverse g f) : B →* A := { to_fun := g, map_one' := by rw [← f.map_one, h₁], .. (f : A →ₙ* B).inverse g h₁ h₂, } set_option old_structure_cmd true /-- add_equiv α β is the type of an equiv α ≃ β which preserves addition. -/ @[ancestor equiv add_hom] structure add_equiv (A B : Type*) [has_add A] [has_add B] extends A ≃ B, add_hom A B /-- `add_equiv_class F A B` states that `F` is a type of addition-preserving morphisms. You should extend this class when you extend `add_equiv`. -/ class add_equiv_class (F A B : Type*) [has_add A] [has_add B] extends equiv_like F A B := (map_add : ∀ (f : F) a b, f (a + b) = f a + f b) /-- The `equiv` underlying an `add_equiv`. -/ add_decl_doc add_equiv.to_equiv /-- The `add_hom` underlying a `add_equiv`. -/ add_decl_doc add_equiv.to_add_hom /-- `mul_equiv α β` is the type of an equiv `α ≃ β` which preserves multiplication. -/ @[ancestor equiv mul_hom, to_additive] structure mul_equiv (M N : Type*) [has_mul M] [has_mul N] extends M ≃ N, M →ₙ* N /-- The `equiv` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_equiv /-- The `mul_hom` underlying a `mul_equiv`. -/ add_decl_doc mul_equiv.to_mul_hom /-- `mul_equiv_class F A B` states that `F` is a type of multiplication-preserving morphisms. You should extend this class when you extend `mul_equiv`. -/ @[to_additive] class mul_equiv_class (F A B : Type*) [has_mul A] [has_mul B] extends equiv_like F A B := (map_mul : ∀ (f : F) a b, f (a * b) = f a * f b) infix ` ≃* `:25 := mul_equiv infix ` ≃+ `:25 := add_equiv namespace mul_equiv_class variables (F) @[priority 100, -- See note [lower instance priority] to_additive] instance [has_mul M] [has_mul N] [h : mul_equiv_class F M N] : mul_hom_class F M N := { coe := (coe : F → M → N), coe_injective' := @fun_like.coe_injective F _ _ _, .. h } @[priority 100, -- See note [lower instance priority] to_additive] instance [mul_one_class M] [mul_one_class N] [mul_equiv_class F M N] : monoid_hom_class F M N := { coe := (coe : F → M → N), map_one := λ e, calc e 1 = e 1 * 1 : (mul_one _).symm ... = e 1 * e (inv e (1 : N) : M) : congr_arg _ (right_inv e 1).symm ... = e (inv e (1 : N)) : by rw [← map_mul, one_mul] ... = 1 : right_inv e 1, .. mul_equiv_class.mul_hom_class F } @[priority 100] -- See note [lower instance priority] instance to_monoid_with_zero_hom_class {α β : Type*} [mul_zero_one_class α] [mul_zero_one_class β] [mul_equiv_class F α β] : monoid_with_zero_hom_class F α β := { map_zero := λ e, calc e 0 = e 0 * e (equiv_like.inv e 0) : by rw [←map_mul, zero_mul] ... = 0 : by { convert mul_zero _, exact equiv_like.right_inv e _ } ..mul_equiv_class.monoid_hom_class _ } variables {F} @[simp, to_additive] lemma map_eq_one_iff {M N} [mul_one_class M] [mul_one_class N] [mul_equiv_class F M N] (h : F) {x : M} : h x = 1 ↔ x = 1 := map_eq_one_iff h (equiv_like.injective h) @[to_additive] lemma map_ne_one_iff {M N} [mul_one_class M] [mul_one_class N] [mul_equiv_class F M N] (h : F) {x : M} : h x ≠ 1 ↔ x ≠ 1 := map_ne_one_iff h (equiv_like.injective h) end mul_equiv_class @[to_additive] instance [has_mul α] [has_mul β] [mul_equiv_class F α β] : has_coe_t F (α ≃* β) := ⟨λ f, { to_fun := f, inv_fun := equiv_like.inv f, left_inv := equiv_like.left_inv f, right_inv := equiv_like.right_inv f, map_mul' := map_mul f }⟩ namespace mul_equiv @[to_additive] instance [has_mul M] [has_mul N] : has_coe_to_fun (M ≃* N) (λ _, M → N) := ⟨mul_equiv.to_fun⟩ @[to_additive] instance [has_mul M] [has_mul N] : mul_equiv_class (M ≃* N) M N := { coe := to_fun, inv := inv_fun, left_inv := left_inv, right_inv := right_inv, coe_injective' := λ f g h₁ h₂, by { cases f, cases g, congr' }, map_mul := map_mul' } variables [has_mul M] [has_mul N] [has_mul P] [has_mul Q] @[simp, to_additive] lemma to_equiv_eq_coe (f : M ≃* N) : f.to_equiv = f := rfl @[simp, to_additive] lemma to_fun_eq_coe {f : M ≃* N} : f.to_fun = f := rfl @[simp, to_additive] lemma coe_to_equiv {f : M ≃* N} : ⇑(f : M ≃ N) = f := rfl @[simp, to_additive] lemma coe_to_mul_hom {f : M ≃* N} : ⇑f.to_mul_hom = f := rfl /-- A multiplicative isomorphism preserves multiplication. -/ @[to_additive "An additive isomorphism preserves addition."] protected lemma map_mul (f : M ≃* N) : ∀ x y, f (x * y) = f x * f y := map_mul f /-- Makes a multiplicative isomorphism from a bijection which preserves multiplication. -/ @[to_additive "Makes an additive isomorphism from a bijection which preserves addition."] def mk' (f : M ≃ N) (h : ∀ x y, f (x * y) = f x * f y) : M ≃* N := ⟨f.1, f.2, f.3, f.4, h⟩ @[to_additive] protected lemma bijective (e : M ≃* N) : function.bijective e := equiv_like.bijective e @[to_additive] protected lemma injective (e : M ≃* N) : function.injective e := equiv_like.injective e @[to_additive] protected lemma surjective (e : M ≃* N) : function.surjective e := equiv_like.surjective e /-- The identity map is a multiplicative isomorphism. -/ @[refl, to_additive "The identity map is an additive isomorphism."] def refl (M : Type*) [has_mul M] : M ≃* M := { map_mul' := λ _ _, rfl, ..equiv.refl _} @[to_additive] instance : inhabited (M ≃* M) := ⟨refl M⟩ /-- The inverse of an isomorphism is an isomorphism. -/ @[symm, to_additive "The inverse of an isomorphism is an isomorphism."] def symm (h : M ≃* N) : N ≃* M := { map_mul' := (h.to_mul_hom.inverse h.to_equiv.symm h.left_inv h.right_inv).map_mul, .. h.to_equiv.symm} @[simp, to_additive] lemma inv_fun_eq_symm {f : M ≃* N} : f.inv_fun = f.symm := rfl /-- See Note [custom simps projection] -/ -- we don't hyperlink the note in the additive version, since that breaks syntax highlighting -- in the whole file. @[to_additive "See Note custom simps projection"] def simps.symm_apply (e : M ≃* N) : N → M := e.symm initialize_simps_projections add_equiv (to_fun → apply, inv_fun → symm_apply) initialize_simps_projections mul_equiv (to_fun → apply, inv_fun → symm_apply) @[simp, to_additive] theorem to_equiv_symm (f : M ≃* N) : f.symm.to_equiv = f.to_equiv.symm := rfl @[simp, to_additive] theorem coe_mk (f : M → N) (g h₁ h₂ h₃) : ⇑(mul_equiv.mk f g h₁ h₂ h₃) = f := rfl @[simp, to_additive] lemma to_equiv_mk (f : M → N) (g : N → M) (h₁ h₂ h₃) : (mk f g h₁ h₂ h₃).to_equiv = ⟨f, g, h₁, h₂⟩ := rfl @[simp, to_additive] lemma symm_symm : ∀ (f : M ≃* N), f.symm.symm = f | ⟨f, g, h₁, h₂, h₃⟩ := rfl @[to_additive] lemma symm_bijective : function.bijective (symm : (M ≃* N) → (N ≃* M)) := equiv.bijective ⟨symm, symm, symm_symm, symm_symm⟩ @[simp, to_additive] theorem symm_mk (f : M → N) (g h₁ h₂ h₃) : (mul_equiv.mk f g h₁ h₂ h₃).symm = { to_fun := g, inv_fun := f, ..(mul_equiv.mk f g h₁ h₂ h₃).symm} := rfl @[simp, to_additive] theorem refl_symm : (refl M).symm = refl M := rfl /-- Transitivity of multiplication-preserving isomorphisms -/ @[trans, to_additive "Transitivity of addition-preserving isomorphisms"] def trans (h1 : M ≃* N) (h2 : N ≃* P) : (M ≃* P) := { map_mul' := λ x y, show h2 (h1 (x * y)) = h2 (h1 x) * h2 (h1 y), by rw [h1.map_mul, h2.map_mul], ..h1.to_equiv.trans h2.to_equiv } /-- `e.symm` is a right inverse of `e`, written as `e (e.symm y) = y`. -/ @[simp, to_additive "`e.symm` is a right inverse of `e`, written as `e (e.symm y) = y`."] lemma apply_symm_apply (e : M ≃* N) (y : N) : e (e.symm y) = y := e.to_equiv.apply_symm_apply y /-- `e.symm` is a left inverse of `e`, written as `e.symm (e y) = y`. -/ @[simp, to_additive "`e.symm` is a left inverse of `e`, written as `e.symm (e y) = y`."] lemma symm_apply_apply (e : M ≃* N) (x : M) : e.symm (e x) = x := e.to_equiv.symm_apply_apply x @[simp, to_additive] theorem symm_comp_self (e : M ≃* N) : e.symm ∘ e = id := funext e.symm_apply_apply @[simp, to_additive] theorem self_comp_symm (e : M ≃* N) : e ∘ e.symm = id := funext e.apply_symm_apply @[simp, to_additive] theorem coe_refl : ⇑(refl M) = id := rfl @[simp, to_additive] theorem refl_apply (m : M) : refl M m = m := rfl @[simp, to_additive] theorem coe_trans (e₁ : M ≃* N) (e₂ : N ≃* P) : ⇑(e₁.trans e₂) = e₂ ∘ e₁ := rfl @[simp, to_additive] theorem trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (m : M) : e₁.trans e₂ m = e₂ (e₁ m) := rfl @[simp, to_additive] theorem symm_trans_apply (e₁ : M ≃* N) (e₂ : N ≃* P) (p : P) : (e₁.trans e₂).symm p = e₁.symm (e₂.symm p) := rfl @[simp, to_additive] theorem apply_eq_iff_eq (e : M ≃* N) {x y : M} : e x = e y ↔ x = y := e.injective.eq_iff @[to_additive] lemma apply_eq_iff_symm_apply (e : M ≃* N) {x : M} {y : N} : e x = y ↔ x = e.symm y := e.to_equiv.apply_eq_iff_eq_symm_apply @[to_additive] lemma symm_apply_eq (e : M ≃* N) {x y} : e.symm x = y ↔ x = e y := e.to_equiv.symm_apply_eq @[to_additive] lemma eq_symm_apply (e : M ≃* N) {x y} : y = e.symm x ↔ e y = x := e.to_equiv.eq_symm_apply @[to_additive] lemma eq_comp_symm {α : Type*} (e : M ≃* N) (f : N → α) (g : M → α) : f = g ∘ e.symm ↔ f ∘ e = g := e.to_equiv.eq_comp_symm f g @[to_additive] lemma comp_symm_eq {α : Type*} (e : M ≃* N) (f : N → α) (g : M → α) : g ∘ e.symm = f ↔ g = f ∘ e := e.to_equiv.comp_symm_eq f g @[to_additive] lemma eq_symm_comp {α : Type*} (e : M ≃* N) (f : α → M) (g : α → N) : f = e.symm ∘ g ↔ e ∘ f = g := e.to_equiv.eq_symm_comp f g @[to_additive] lemma symm_comp_eq {α : Type*} (e : M ≃* N) (f : α → M) (g : α → N) : e.symm ∘ g = f ↔ g = e ∘ f := e.to_equiv.symm_comp_eq f g /-- Two multiplicative isomorphisms agree if they are defined by the same underlying function. -/ @[ext, to_additive "Two additive isomorphisms agree if they are defined by the same underlying function."] lemma ext {f g : mul_equiv M N} (h : ∀ x, f x = g x) : f = g := fun_like.ext f g h @[to_additive] lemma ext_iff {f g : mul_equiv M N} : f = g ↔ ∀ x, f x = g x := fun_like.ext_iff @[simp, to_additive] lemma mk_coe (e : M ≃* N) (e' h₁ h₂ h₃) : (⟨e, e', h₁, h₂, h₃⟩ : M ≃* N) = e := ext $ λ _, rfl @[simp, to_additive] lemma mk_coe' (e : M ≃* N) (f h₁ h₂ h₃) : (mul_equiv.mk f ⇑e h₁ h₂ h₃ : N ≃* M) = e.symm := symm_bijective.injective $ ext $ λ x, rfl @[to_additive] protected lemma congr_arg {f : mul_equiv M N} {x x' : M} : x = x' → f x = f x' := fun_like.congr_arg f @[to_additive] protected lemma congr_fun {f g : mul_equiv M N} (h : f = g) (x : M) : f x = g x := fun_like.congr_fun h x /-- The `mul_equiv` between two monoids with a unique element. -/ @[to_additive "The `add_equiv` between two add_monoids with a unique element."] def mul_equiv_of_unique {M N} [unique M] [unique N] [has_mul M] [has_mul N] : M ≃* N := { map_mul' := λ _ _, subsingleton.elim _ _, ..equiv.equiv_of_unique M N } /-- There is a unique monoid homomorphism between two monoids with a unique element. -/ @[to_additive "There is a unique additive monoid homomorphism between two additive monoids with a unique element."] instance {M N} [unique M] [unique N] [has_mul M] [has_mul N] : unique (M ≃* N) := { default := mul_equiv_of_unique , uniq := λ _, ext $ λ x, subsingleton.elim _ _} /-! ## Monoids -/ /-- A multiplicative isomorphism of monoids sends `1` to `1` (and is hence a monoid isomorphism). -/ @[to_additive "An additive isomorphism of additive monoids sends `0` to `0` (and is hence an additive monoid isomorphism)."] protected lemma map_one {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) : h 1 = 1 := map_one h @[to_additive] protected lemma map_eq_one_iff {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) {x : M} : h x = 1 ↔ x = 1 := mul_equiv_class.map_eq_one_iff h @[to_additive] lemma map_ne_one_iff {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) {x : M} : h x ≠ 1 ↔ x ≠ 1 := mul_equiv_class.map_ne_one_iff h /-- A bijective `semigroup` homomorphism is an isomorphism -/ @[to_additive "A bijective `add_semigroup` homomorphism is an isomorphism", simps apply] noncomputable def of_bijective {M N F} [has_mul M] [has_mul N] [mul_hom_class F M N] (f : F) (hf : function.bijective f) : M ≃* N := { map_mul' := map_mul f, ..equiv.of_bijective f hf } @[simp] lemma of_bijective_apply_symm_apply {M N} [mul_one_class M] [mul_one_class N] {n : N} (f : M →* N) (hf : function.bijective f) : f ((equiv.of_bijective f hf).symm n) = n := (mul_equiv.of_bijective f hf).apply_symm_apply n /-- Extract the forward direction of a multiplicative equivalence as a multiplication-preserving function. -/ @[to_additive "Extract the forward direction of an additive equivalence as an addition-preserving function."] def to_monoid_hom {M N} [mul_one_class M] [mul_one_class N] (h : M ≃* N) : (M →* N) := { map_one' := h.map_one, .. h } @[simp, to_additive] lemma coe_to_monoid_hom {M N} [mul_one_class M] [mul_one_class N] (e : M ≃* N) : ⇑e.to_monoid_hom = e := rfl @[to_additive] lemma to_monoid_hom_injective {M N} [mul_one_class M] [mul_one_class N] : function.injective (to_monoid_hom : (M ≃* N) → M →* N) := λ f g h, mul_equiv.ext (monoid_hom.ext_iff.1 h) /-- A multiplicative analogue of `equiv.arrow_congr`, where the equivalence between the targets is multiplicative. -/ @[to_additive "An additive analogue of `equiv.arrow_congr`, where the equivalence between the targets is additive.", simps apply] def arrow_congr {M N P Q : Type*} [has_mul P] [has_mul Q] (f : M ≃ N) (g : P ≃* Q) : (M → P) ≃* (N → Q) := { to_fun := λ h n, g (h (f.symm n)), inv_fun := λ k m, g.symm (k (f m)), left_inv := λ h, by { ext, simp, }, right_inv := λ k, by { ext, simp, }, map_mul' := λ h k, by { ext, simp, }, } /-- A multiplicative analogue of `equiv.arrow_congr`, for multiplicative maps from a monoid to a commutative monoid. -/ @[to_additive "An additive analogue of `equiv.arrow_congr`, for additive maps from an additive monoid to a commutative additive monoid.", simps apply] def monoid_hom_congr {M N P Q} [mul_one_class M] [mul_one_class N] [comm_monoid P] [comm_monoid Q] (f : M ≃* N) (g : P ≃* Q) : (M →* P) ≃* (N →* Q) := { to_fun := λ h, g.to_monoid_hom.comp (h.comp f.symm.to_monoid_hom), inv_fun := λ k, g.symm.to_monoid_hom.comp (k.comp f.to_monoid_hom), left_inv := λ h, by { ext, simp, }, right_inv := λ k, by { ext, simp, }, map_mul' := λ h k, by { ext, simp, }, } /-- A family of multiplicative equivalences `Π j, (Ms j ≃* Ns j)` generates a multiplicative equivalence between `Π j, Ms j` and `Π j, Ns j`. This is the `mul_equiv` version of `equiv.Pi_congr_right`, and the dependent version of `mul_equiv.arrow_congr`. -/ @[to_additive add_equiv.Pi_congr_right "A family of additive equivalences `Π j, (Ms j ≃+ Ns j)` generates an additive equivalence between `Π j, Ms j` and `Π j, Ns j`. This is the `add_equiv` version of `equiv.Pi_congr_right`, and the dependent version of `add_equiv.arrow_congr`.", simps apply] def Pi_congr_right {η : Type*} {Ms Ns : η → Type*} [Π j, has_mul (Ms j)] [Π j, has_mul (Ns j)] (es : ∀ j, Ms j ≃* Ns j) : (Π j, Ms j) ≃* (Π j, Ns j) := { to_fun := λ x j, es j (x j), inv_fun := λ x j, (es j).symm (x j), map_mul' := λ x y, funext $ λ j, (es j).map_mul (x j) (y j), .. equiv.Pi_congr_right (λ j, (es j).to_equiv) } @[simp] lemma Pi_congr_right_refl {η : Type*} {Ms : η → Type*} [Π j, has_mul (Ms j)] : Pi_congr_right (λ j, mul_equiv.refl (Ms j)) = mul_equiv.refl _ := rfl @[simp] lemma Pi_congr_right_symm {η : Type*} {Ms Ns : η → Type*} [Π j, has_mul (Ms j)] [Π j, has_mul (Ns j)] (es : ∀ j, Ms j ≃* Ns j) : (Pi_congr_right es).symm = (Pi_congr_right $ λ i, (es i).symm) := rfl @[simp] lemma Pi_congr_right_trans {η : Type*} {Ms Ns Ps : η → Type*} [Π j, has_mul (Ms j)] [Π j, has_mul (Ns j)] [Π j, has_mul (Ps j)] (es : ∀ j, Ms j ≃* Ns j) (fs : ∀ j, Ns j ≃* Ps j) : (Pi_congr_right es).trans (Pi_congr_right fs) = (Pi_congr_right $ λ i, (es i).trans (fs i)) := rfl /-- A family indexed by a nonempty subsingleton type is equivalent to the element at the single index. -/ @[to_additive add_equiv.Pi_subsingleton "A family indexed by a nonempty subsingleton type is equivalent to the element at the single index.", simps] def Pi_subsingleton {ι : Type*} (M : ι → Type*) [Π j, has_mul (M j)] [subsingleton ι] (i : ι) : (Π j, M j) ≃* M i := { map_mul' := λ f1 f2, pi.mul_apply _ _ _, ..equiv.Pi_subsingleton M i } /-! # Groups -/ /-- A multiplicative equivalence of groups preserves inversion. -/ @[to_additive "An additive equivalence of additive groups preserves negation."] protected lemma map_inv [group G] [division_monoid H] (h : G ≃* H) (x : G) : h x⁻¹ = (h x)⁻¹ := map_inv h x /-- A multiplicative equivalence of groups preserves division. -/ @[to_additive "An additive equivalence of additive groups preserves subtractions."] protected lemma map_div [group G] [division_monoid H] (h : G ≃* H) (x y : G) : h (x / y) = h x / h y := map_div h x y end mul_equiv /-- Given a pair of monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an multiplicative equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for monoid homomorphisms. -/ @[to_additive /-"Given a pair of additive monoid homomorphisms `f`, `g` such that `g.comp f = id` and `f.comp g = id`, returns an additive equivalence with `to_fun = f` and `inv_fun = g`. This constructor is useful if the underlying type(s) have specialized `ext` lemmas for additive monoid homomorphisms."-/, simps {fully_applied := ff}] def monoid_hom.to_mul_equiv [mul_one_class M] [mul_one_class N] (f : M →* N) (g : N →* M) (h₁ : g.comp f = monoid_hom.id _) (h₂ : f.comp g = monoid_hom.id _) : M ≃* N := { to_fun := f, inv_fun := g, left_inv := monoid_hom.congr_fun h₁, right_inv := monoid_hom.congr_fun h₂, map_mul' := f.map_mul } /-- A group is isomorphic to its group of units. -/ @[to_additive "An additive group is isomorphic to its group of additive units"] def to_units [group G] : G ≃* Gˣ := { to_fun := λ x, ⟨x, x⁻¹, mul_inv_self _, inv_mul_self _⟩, inv_fun := coe, left_inv := λ x, rfl, right_inv := λ u, units.ext rfl, map_mul' := λ x y, units.ext rfl } @[simp, to_additive] lemma coe_to_units [group G] (g : G) : (to_units g : G) = g := rfl namespace units variables [monoid M] [monoid N] [monoid P] /-- A multiplicative equivalence of monoids defines a multiplicative equivalence of their groups of units. -/ def map_equiv (h : M ≃* N) : Mˣ ≃* Nˣ := { inv_fun := map h.symm.to_monoid_hom, left_inv := λ u, ext $ h.left_inv u, right_inv := λ u, ext $ h.right_inv u, .. map h.to_monoid_hom } /-- Left multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Left addition of an additive unit is a permutation of the underlying type.", simps apply {fully_applied := ff}] def mul_left (u : Mˣ) : equiv.perm M := { to_fun := λx, u * x, inv_fun := λx, ↑u⁻¹ * x, left_inv := u.inv_mul_cancel_left, right_inv := u.mul_inv_cancel_left } @[simp, to_additive] lemma mul_left_symm (u : Mˣ) : u.mul_left.symm = u⁻¹.mul_left := equiv.ext $ λ x, rfl @[to_additive] lemma mul_left_bijective (a : Mˣ) : function.bijective ((*) a : M → M) := (mul_left a).bijective /-- Right multiplication by a unit of a monoid is a permutation of the underlying type. -/ @[to_additive "Right addition of an additive unit is a permutation of the underlying type.", simps apply {fully_applied := ff}] def mul_right (u : Mˣ) : equiv.perm M := { to_fun := λx, x * u, inv_fun := λx, x * ↑u⁻¹, left_inv := λ x, mul_inv_cancel_right x u, right_inv := λ x, inv_mul_cancel_right x u } @[simp, to_additive] lemma mul_right_symm (u : Mˣ) : u.mul_right.symm = u⁻¹.mul_right := equiv.ext $ λ x, rfl @[to_additive] lemma mul_right_bijective (a : Mˣ) : function.bijective ((* a) : M → M) := (mul_right a).bijective end units namespace equiv section has_involutive_neg variables (G) [has_involutive_inv G] /-- Inversion on a `group` or `group_with_zero` is a permutation of the underlying type. -/ @[to_additive "Negation on an `add_group` is a permutation of the underlying type.", simps apply {fully_applied := ff}] protected def inv : perm G := inv_involutive.to_perm _ variable {G} @[simp, to_additive] lemma inv_symm : (equiv.inv G).symm = equiv.inv G := rfl end has_involutive_neg section group variables [group G] /-- Left multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Left addition in an `add_group` is a permutation of the underlying type."] protected def mul_left (a : G) : perm G := (to_units a).mul_left @[simp, to_additive] lemma coe_mul_left (a : G) : ⇑(equiv.mul_left a) = (*) a := rfl /-- Extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp, nolint simp_nf, to_additive "Extra simp lemma that `dsimp` can use. `simp` will never use this."] lemma mul_left_symm_apply (a : G) : ((equiv.mul_left a).symm : G → G) = (*) a⁻¹ := rfl @[simp, to_additive] lemma mul_left_symm (a : G) : (equiv.mul_left a).symm = equiv.mul_left a⁻¹ := ext $ λ x, rfl @[to_additive] lemma _root_.group.mul_left_bijective (a : G) : function.bijective ((*) a) := (equiv.mul_left a).bijective /-- Right multiplication in a `group` is a permutation of the underlying type. -/ @[to_additive "Right addition in an `add_group` is a permutation of the underlying type."] protected def mul_right (a : G) : perm G := (to_units a).mul_right @[simp, to_additive] lemma coe_mul_right (a : G) : ⇑(equiv.mul_right a) = λ x, x * a := rfl @[simp, to_additive] lemma mul_right_symm (a : G) : (equiv.mul_right a).symm = equiv.mul_right a⁻¹ := ext $ λ x, rfl /-- Extra simp lemma that `dsimp` can use. `simp` will never use this. -/ @[simp, nolint simp_nf, to_additive "Extra simp lemma that `dsimp` can use. `simp` will never use this."] lemma mul_right_symm_apply (a : G) : ((equiv.mul_right a).symm : G → G) = λ x, x * a⁻¹ := rfl @[to_additive] lemma _root_.group.mul_right_bijective (a : G) : function.bijective (* a) := (equiv.mul_right a).bijective /-- A version of `equiv.mul_left a b⁻¹` that is defeq to `a / b`. -/ @[to_additive /-" A version of `equiv.add_left a (-b)` that is defeq to `a - b`. "-/, simps] protected def div_left (a : G) : G ≃ G := { to_fun := λ b, a / b, inv_fun := λ b, b⁻¹ * a, left_inv := λ b, by simp [div_eq_mul_inv], right_inv := λ b, by simp [div_eq_mul_inv] } @[to_additive] lemma div_left_eq_inv_trans_mul_left (a : G) : equiv.div_left a = (equiv.inv G).trans (equiv.mul_left a) := ext $ λ _, div_eq_mul_inv _ _ /-- A version of `equiv.mul_right a⁻¹ b` that is defeq to `b / a`. -/ @[to_additive /-" A version of `equiv.add_right (-a) b` that is defeq to `b - a`. "-/, simps] protected def div_right (a : G) : G ≃ G := { to_fun := λ b, b / a, inv_fun := λ b, b * a, left_inv := λ b, by simp [div_eq_mul_inv], right_inv := λ b, by simp [div_eq_mul_inv] } @[to_additive] lemma div_right_eq_mul_right_inv (a : G) : equiv.div_right a = equiv.mul_right a⁻¹ := ext $ λ _, div_eq_mul_inv _ _ end group section group_with_zero variables [group_with_zero G] /-- Left multiplication by a nonzero element in a `group_with_zero` is a permutation of the underlying type. -/ @[simps {fully_applied := ff}] protected def mul_left₀ (a : G) (ha : a ≠ 0) : perm G := (units.mk0 a ha).mul_left lemma _root_.mul_left_bijective₀ (a : G) (ha : a ≠ 0) : function.bijective ((*) a : G → G) := (equiv.mul_left₀ a ha).bijective /-- Right multiplication by a nonzero element in a `group_with_zero` is a permutation of the underlying type. -/ @[simps {fully_applied := ff}] protected def mul_right₀ (a : G) (ha : a ≠ 0) : perm G := (units.mk0 a ha).mul_right lemma _root_.mul_right_bijective₀ (a : G) (ha : a ≠ 0) : function.bijective ((* a) : G → G) := (equiv.mul_right₀ a ha).bijective end group_with_zero end equiv /-- In a `division_comm_monoid`, `equiv.inv` is a `mul_equiv`. There is a variant of this `mul_equiv.inv' G : G ≃* Gᵐᵒᵖ` for the non-commutative case. -/ @[to_additive "When the `add_group` is commutative, `equiv.neg` is an `add_equiv`.", simps apply] def mul_equiv.inv (G : Type*) [division_comm_monoid G] : G ≃* G := { to_fun := has_inv.inv, inv_fun := has_inv.inv, map_mul' := mul_inv, ..equiv.inv G } @[simp] lemma mul_equiv.inv_symm (G : Type*) [division_comm_monoid G] : (mul_equiv.inv G).symm = mul_equiv.inv G := rfl section type_tags /-- Reinterpret `G ≃+ H` as `multiplicative G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative [add_zero_class G] [add_zero_class H] : (G ≃+ H) ≃ (multiplicative G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative, f.symm.to_add_monoid_hom.to_multiplicative, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* H` as `additive G ≃+ additive H`. -/ def mul_equiv.to_additive [mul_one_class G] [mul_one_class H] : (G ≃* H) ≃ (additive G ≃+ additive H) := { to_fun := λ f, ⟨f.to_monoid_hom.to_additive, f.symm.to_monoid_hom.to_additive, f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_add_monoid_hom, f.symm.to_add_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `additive G ≃+ H` as `G ≃* multiplicative H`. -/ def add_equiv.to_multiplicative' [mul_one_class G] [add_zero_class H] : (additive G ≃+ H) ≃ (G ≃* multiplicative H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative', f.symm.to_add_monoid_hom.to_multiplicative'', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `G ≃* multiplicative H` as `additive G ≃+ H` as. -/ def mul_equiv.to_additive' [mul_one_class G] [add_zero_class H] : (G ≃* multiplicative H) ≃ (additive G ≃+ H) := add_equiv.to_multiplicative'.symm /-- Reinterpret `G ≃+ additive H` as `multiplicative G ≃* H`. -/ def add_equiv.to_multiplicative'' [add_zero_class G] [mul_one_class H] : (G ≃+ additive H) ≃ (multiplicative G ≃* H) := { to_fun := λ f, ⟨f.to_add_monoid_hom.to_multiplicative'', f.symm.to_add_monoid_hom.to_multiplicative', f.3, f.4, f.5⟩, inv_fun := λ f, ⟨f.to_monoid_hom, f.symm.to_monoid_hom, f.3, f.4, f.5⟩, left_inv := λ x, by { ext, refl, }, right_inv := λ x, by { ext, refl, }, } /-- Reinterpret `multiplicative G ≃* H` as `G ≃+ additive H` as. -/ def mul_equiv.to_additive'' [add_zero_class G] [mul_one_class H] : (multiplicative G ≃* H) ≃ (G ≃+ additive H) := add_equiv.to_multiplicative''.symm end type_tags section variables (G) (H) /-- `additive (multiplicative G)` is just `G`. -/ def add_equiv.additive_multiplicative [add_zero_class G] : additive (multiplicative G) ≃+ G := mul_equiv.to_additive'' (mul_equiv.refl (multiplicative G)) /-- `multiplicative (additive H)` is just `H`. -/ def mul_equiv.multiplicative_additive [mul_one_class H] : multiplicative (additive H) ≃* H := add_equiv.to_multiplicative'' (add_equiv.refl (additive H)) end
8cb377433a3e9085e875607ecf343e6970e1de71
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/quot_abuse2.lean
0bc93c3f099e9e2e915c7ed10940f09517413b19
[ "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
158
lean
prelude init_quotient /- definit eq as the empty type -/ inductive {u} eq {α : Sort u} (a : α) : α → Sort 0 | refl : ∀ (b : α), eq b init_quotient
ab6a15c946dba30bbba6c559730fdff480688db5
1890046a4987fbd27f3f50dbac83f3ce095556d5
/01_Equality/03_type_inference.lean
1d1802a759be778bf58e320bd7ffe74be1177c19
[]
no_license
kbhuynh/cs-dm
9f335727d1779f7c3d9e8221a52b4c9c106659ba
4041bd73618a49ef6870a1a80764e8947e60e768
refs/heads/master
1,585,353,017,958
1,536,055,215,000
1,536,055,215,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,312
lean
/- Type Inference -/ /- Now as we've seen, given a value, t, of some type, T, Lean can tell us what T is. The #check command tells us the type of any value or expression. The key observation is that if you give Lean a value, Lean can determine its type. We can use the ability of Lean to determine the types of given values to make it easier to apply the eq_refl rule. If we give a value, t, as an argument, Lean can automatically figure out its type, T, which we means we shouldn't have to say explicitly what t is. EXERCISE: If t = 0, what is T? If t = tt, what is T? If t = "Hello Lean!" what is T? Lean supports what we call type inference to relieve us of having to give values for type parameters explicitly when they can be inferred from from the context. The context in this case is the value of t. We will thus rewrite the eq_refl inference rule to indicate that we mean for the value of the T parameter to be inferred. We'll do this by putting braces around this argument. Here's the rule as we defined it up until now. T: Type, t : T -------------- (eq.refl) pf: t = t Here's the rewritten rule. { T: Type }, t : T ------------------ (eq.refl) pf: t = t The new version means exactly the same thing but it indicates that when we write expressions where eq_refl is applied, we can leave out the explicit argument, T. What this slightly modified rule provides is the ability to expressions in which eq_refl is applied to just one argument, namely a value, t. Rather than writing "eq_refl nat 0", for example, we'd write "eq_refl 0". A value for T is still required, but it is inferred from the context (that t = 0 and 0 is of type nat), and thus does not need to be given explicitly. -/ /- In Lean, the eq-refl rule is defined in just this way and is called eq.refl. It just takes one value, t, infers T from it, and returns a proof that that t equals itself! Read the output of the following check command very carefully. It says that (eq.refl 0) is a proof of 0 = 0! That is, when eq.refl is applied to the value 0, a proof of 0 = 0 is produced. -/ #check (eq.refl 0) /- EXERCISE: Use #check to confirm similar conclusions for the cases where t = tt and t = "Hello Lean!". EXERCISE: In the case where t = tt, what value does Lean infer for the parameter, T? -/
c5d27ee65b811250941387a5ec1359e9dbda454d
453dcd7c0d1ef170b0843a81d7d8caedc9741dce
/data/set/basic.lean
99347e5487bb6512600c1e5aaf992f86e1c8ff05
[ "Apache-2.0" ]
permissive
amswerdlow/mathlib
9af77a1f08486d8fa059448ae2d97795bd12ec0c
27f96e30b9c9bf518341705c99d641c38638dfd0
refs/heads/master
1,585,200,953,598
1,534,275,532,000
1,534,275,532,000
144,564,700
0
0
null
1,534,156,197,000
1,534,156,197,000
null
UTF-8
Lean
false
false
38,701
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 tactic.ext tactic.finish data.subtype open function namespace set universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} {a : α} {s t : set α} instance : inhabited (set α) := ⟨∅⟩ @[extensionality] theorem ext {a b : set α} (h : ∀ x, x ∈ a ↔ x ∈ b) : a = b := funext (assume x, propext (h x)) theorem ext_iff (s t : set α) : s = t ↔ ∀ x, x ∈ s ↔ x ∈ t := ⟨begin intros h x, rw h end, set.ext⟩ @[trans] theorem mem_of_mem_of_subset {α : Type u} {x : α} {s t : set α} (hx : x ∈ s) (h : s ⊆ t) : x ∈ t := h hx /- mem and set_of -/ @[simp] theorem mem_set_of_eq {a : α} {p : α → Prop} : a ∈ {a | p a} = p a := rfl @[simp] theorem nmem_set_of_eq {a : α} {P : α → Prop} : a ∉ {a : α | P a} = ¬ P a := rfl @[simp] theorem set_of_mem_eq {s : set α} : {x | x ∈ s} = s := rfl theorem mem_def {a : α} {s : set α} : a ∈ s ↔ s a := iff.rfl instance decidable_mem (s : set α) [H : decidable_pred s] : ∀ a, decidable (a ∈ s) := H instance decidable_set_of (p : α → Prop) [H : decidable_pred p] : decidable_pred {a | p a} := H @[simp] theorem set_of_subset_set_of {p q : α → Prop} : {a | p a} ⊆ {a | q a} ↔ (∀a, p a → q a) := iff.rfl /- set coercion to a type -/ instance : has_coe_to_sort (set α) := ⟨_, λ s, {x // x ∈ s}⟩ @[simp] theorem set_coe_eq_subtype (s : set α) : coe_sort.{(u+1) (u+2)} s = {x // x ∈ s} := rfl @[simp] theorem set_coe.forall {s : set α} {p : s → Prop} : (∀ x : s, p x) ↔ (∀ x (h : x ∈ s), p ⟨x, h⟩) := subtype.forall @[simp] theorem set_coe.exists {s : set α} {p : s → Prop} : (∃ x : s, p x) ↔ (∃ x (h : x ∈ s), p ⟨x, h⟩) := subtype.exists @[simp] theorem set_coe_cast : ∀ {s t : set α} (H' : s = t) (H : @eq (Type u) s t) (x : s), cast H x = ⟨x.1, H' ▸ x.2⟩ | s _ rfl _ ⟨x, h⟩ := rfl /- subset -/ -- TODO(Jeremy): write a tactic to unfold specific instances of generic notation? theorem subset_def {s t : set α} : (s ⊆ t) = ∀ x, x ∈ s → x ∈ t := rfl @[refl] theorem subset.refl (a : set α) : a ⊆ a := assume x, id @[trans] theorem subset.trans {a b c : set α} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := assume x h, bc (ab h) @[trans] theorem mem_of_eq_of_mem {α : Type u} {x y : α} {s : set α} (hx : x = y) (h : y ∈ s) : x ∈ s := hx.symm ▸ h theorem subset.antisymm {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := ext (λ x, iff.intro (λ ina, h₁ ina) (λ inb, h₂ inb)) theorem subset.antisymm_iff {a b : set α} : a = b ↔ a ⊆ b ∧ b ⊆ a := ⟨λ e, e ▸ ⟨subset.refl _, subset.refl _⟩, λ ⟨h₁, h₂⟩, subset.antisymm h₁ h₂⟩ -- an alterantive name theorem eq_of_subset_of_subset {a b : set α} (h₁ : a ⊆ b) (h₂ : b ⊆ a) : a = b := subset.antisymm h₁ h₂ theorem mem_of_subset_of_mem {s₁ s₂ : set α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := assume h₁ h₂, h₁ h₂ theorem not_subset : (¬ s ⊆ t) ↔ ∃a, a ∈ s ∧ a ∉ t := by simp [subset_def, classical.not_forall] /- strict subset -/ /-- `s ⊂ t` means that `s` is a strict subset of `t`, that is, `s ⊆ t` but `s ≠ t`. -/ def strict_subset (s t : set α) := s ⊆ t ∧ s ≠ t instance : has_ssubset (set α) := ⟨strict_subset⟩ theorem ssubset_def : (s ⊂ t) = (s ⊆ t ∧ s ≠ t) := rfl lemma exists_of_ssubset {α : Type u} {s t : set α} (h : s ⊂ t) : (∃x∈t, x ∉ s) := classical.by_contradiction $ assume hn, have t ⊆ s, from assume a hat, classical.by_contradiction $ assume has, hn ⟨a, hat, has⟩, h.2 $ subset.antisymm h.1 this lemma ssubset_iff_subset_not_subset {s t : set α} : s ⊂ t ↔ s ⊆ t ∧ ¬ t ⊆ s := by split; simp [set.ssubset_def, ne.def, set.subset.antisymm_iff] {contextual := tt} theorem not_mem_empty (x : α) : ¬ (x ∈ (∅ : set α)) := assume h : x ∈ ∅, h @[simp] theorem not_not_mem [decidable (a ∈ s)] : ¬ (a ∉ s) ↔ a ∈ s := not_not /- empty set -/ theorem empty_def : (∅ : set α) = {x | false} := rfl @[simp] theorem mem_empty_eq (x : α) : x ∈ (∅ : set α) = false := rfl @[simp] theorem set_of_false : {a : α | false} = ∅ := rfl theorem eq_empty_iff_forall_not_mem {s : set α} : s = ∅ ↔ ∀ x, x ∉ s := by simp [ext_iff] theorem ne_empty_of_mem {s : set α} {x : α} (h : x ∈ s) : s ≠ ∅ := by { intro hs, rw hs at h, apply not_mem_empty _ h } @[simp] theorem empty_subset (s : set α) : ∅ ⊆ s := assume x, assume h, false.elim h theorem subset_empty_iff {s : set α} : s ⊆ ∅ ↔ s = ∅ := by simp [subset.antisymm_iff] theorem eq_empty_of_subset_empty {s : set α} : s ⊆ ∅ → s = ∅ := subset_empty_iff.1 theorem ne_empty_iff_exists_mem {s : set α} : s ≠ ∅ ↔ ∃ x, x ∈ s := by haveI := classical.prop_decidable; simp [eq_empty_iff_forall_not_mem] theorem exists_mem_of_ne_empty {s : set α} : s ≠ ∅ → ∃ x, x ∈ s := ne_empty_iff_exists_mem.1 -- TODO: remove when simplifier stops rewriting `a ≠ b` to `¬ a = b` theorem not_eq_empty_iff_exists {s : set α} : ¬ (s = ∅) ↔ ∃ x, x ∈ s := ne_empty_iff_exists_mem theorem subset_eq_empty {s t : set α} (h : t ⊆ s) (e : s = ∅) : t = ∅ := subset_empty_iff.1 $ e ▸ h theorem subset_ne_empty {s t : set α} (h : t ⊆ s) : t ≠ ∅ → s ≠ ∅ := mt (subset_eq_empty h) theorem ball_empty_iff {p : α → Prop} : (∀ x ∈ (∅ : set α), p x) ↔ true := by simp [iff_def] /- universal set -/ theorem univ_def : @univ α = {x | true} := rfl @[simp] theorem mem_univ (x : α) : x ∈ @univ α := trivial theorem empty_ne_univ [h : inhabited α] : (∅ : set α) ≠ univ := by simp [ext_iff] @[simp] theorem subset_univ (s : set α) : s ⊆ univ := λ x H, trivial theorem univ_subset_iff {s : set α} : univ ⊆ s ↔ s = univ := by simp [subset.antisymm_iff] theorem eq_univ_of_univ_subset {s : set α} : univ ⊆ s → s = univ := univ_subset_iff.1 theorem eq_univ_iff_forall {s : set α} : s = univ ↔ ∀ x, x ∈ s := by simp [ext_iff] theorem eq_univ_of_forall {s : set α} : (∀ x, x ∈ s) → s = univ := eq_univ_iff_forall.2 /- union -/ theorem union_def {s₁ s₂ : set α} : s₁ ∪ s₂ = {a | a ∈ s₁ ∨ a ∈ s₂} := rfl theorem mem_union_left {x : α} {a : set α} (b : set α) : x ∈ a → x ∈ a ∪ b := or.inl theorem mem_union_right {x : α} {b : set α} (a : set α) : x ∈ b → x ∈ a ∪ b := or.inr theorem mem_or_mem_of_mem_union {x : α} {a b : set α} (H : x ∈ a ∪ b) : x ∈ a ∨ x ∈ b := H theorem mem_union.elim {x : α} {a b : set α} {P : Prop} (H₁ : x ∈ a ∪ b) (H₂ : x ∈ a → P) (H₃ : x ∈ b → P) : P := or.elim H₁ H₂ H₃ theorem mem_union (x : α) (a b : set α) : x ∈ a ∪ b ↔ x ∈ a ∨ x ∈ b := iff.rfl @[simp] theorem mem_union_eq (x : α) (a b : set α) : x ∈ a ∪ b = (x ∈ a ∨ x ∈ b) := rfl @[simp] theorem union_self (a : set α) : a ∪ a = a := ext (assume x, or_self _) @[simp] theorem union_empty (a : set α) : a ∪ ∅ = a := ext (assume x, or_false _) @[simp] theorem empty_union (a : set α) : ∅ ∪ a = a := ext (assume x, false_or _) theorem union_comm (a b : set α) : a ∪ b = b ∪ a := ext (assume x, or.comm) theorem union_assoc (a b c : set α) : (a ∪ b) ∪ c = a ∪ (b ∪ c) := ext (assume x, or.assoc) instance union_is_assoc : is_associative (set α) (∪) := ⟨union_assoc⟩ instance union_is_comm : is_commutative (set α) (∪) := ⟨union_comm⟩ theorem union_left_comm (s₁ s₂ s₃ : set α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := by finish theorem union_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := by finish theorem union_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∪ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∪ t = s := by finish [subset_def, ext_iff, iff_def] @[simp] theorem subset_union_left (s t : set α) : s ⊆ s ∪ t := λ x, or.inl @[simp] theorem subset_union_right (s t : set α) : t ⊆ s ∪ t := λ x, or.inr theorem union_subset {s t r : set α} (sr : s ⊆ r) (tr : t ⊆ r) : s ∪ t ⊆ r := by finish [subset_def, union_def] @[simp] theorem union_subset_iff {s t u : set α} : s ∪ t ⊆ u ↔ s ⊆ u ∧ t ⊆ u := by finish [iff_def, subset_def] theorem union_subset_union {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ s₂) (h₂ : t₁ ⊆ t₂) : s₁ ∪ t₁ ⊆ s₂ ∪ t₂ := by finish [subset_def] theorem union_subset_union_left {s₁ s₂ : set α} (t) (h : s₁ ⊆ s₂) : s₁ ∪ t ⊆ s₂ ∪ t := union_subset_union h (by refl) theorem union_subset_union_right (s) {t₁ t₂ : set α} (h : t₁ ⊆ t₂) : s ∪ t₁ ⊆ s ∪ t₂ := union_subset_union (by refl) h @[simp] theorem union_empty_iff {s t : set α} : s ∪ t = ∅ ↔ s = ∅ ∧ t = ∅ := ⟨by finish [ext_iff], by finish [ext_iff]⟩ /- intersection -/ theorem inter_def {s₁ s₂ : set α} : s₁ ∩ s₂ = {a | a ∈ s₁ ∧ a ∈ s₂} := rfl theorem mem_inter_iff (x : α) (a b : set α) : x ∈ a ∩ b ↔ x ∈ a ∧ x ∈ b := iff.rfl @[simp] theorem mem_inter_eq (x : α) (a b : set α) : x ∈ a ∩ b = (x ∈ a ∧ x ∈ b) := rfl theorem mem_inter {x : α} {a b : set α} (ha : x ∈ a) (hb : x ∈ b) : x ∈ a ∩ b := ⟨ha, hb⟩ theorem mem_of_mem_inter_left {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ a := h.left theorem mem_of_mem_inter_right {x : α} {a b : set α} (h : x ∈ a ∩ b) : x ∈ b := h.right @[simp] theorem inter_self (a : set α) : a ∩ a = a := ext (assume x, and_self _) @[simp] theorem inter_empty (a : set α) : a ∩ ∅ = ∅ := ext (assume x, and_false _) @[simp] theorem empty_inter (a : set α) : ∅ ∩ a = ∅ := ext (assume x, false_and _) theorem inter_comm (a b : set α) : a ∩ b = b ∩ a := ext (assume x, and.comm) theorem inter_assoc (a b c : set α) : (a ∩ b) ∩ c = a ∩ (b ∩ c) := ext (assume x, and.assoc) instance inter_is_assoc : is_associative (set α) (∩) := ⟨inter_assoc⟩ instance inter_is_comm : is_commutative (set α) (∩) := ⟨inter_comm⟩ theorem inter_left_comm (s₁ s₂ s₃ : set α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := by finish theorem inter_right_comm (s₁ s₂ s₃ : set α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := by finish @[simp] theorem inter_subset_left (s t : set α) : s ∩ t ⊆ s := λ x H, and.left H @[simp] theorem inter_subset_right (s t : set α) : s ∩ t ⊆ t := λ x H, and.right H theorem subset_inter {s t r : set α} (rs : r ⊆ s) (rt : r ⊆ t) : r ⊆ s ∩ t := by finish [subset_def, inter_def] @[simp] theorem subset_inter_iff {s t r : set α} : r ⊆ s ∩ t ↔ r ⊆ s ∧ r ⊆ t := ⟨λ h, ⟨subset.trans h (inter_subset_left _ _), subset.trans h (inter_subset_right _ _)⟩, λ ⟨h₁, h₂⟩, subset_inter h₁ h₂⟩ @[simp] theorem inter_univ (a : set α) : a ∩ univ = a := ext (assume x, and_true _) @[simp] theorem univ_inter (a : set α) : univ ∩ a = a := ext (assume x, true_and _) theorem inter_subset_inter_left {s t : set α} (u : set α) (H : s ⊆ t) : s ∩ u ⊆ t ∩ u := by finish [subset_def] theorem inter_subset_inter_right {s t : set α} (u : set α) (H : s ⊆ t) : u ∩ s ⊆ u ∩ t := by finish [subset_def] theorem inter_subset_inter {s₁ s₂ t₁ t₂ : set α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∩ s₂ ⊆ t₁ ∩ t₂ := by finish [subset_def] theorem inter_eq_self_of_subset_left {s t : set α} (h : s ⊆ t) : s ∩ t = s := by finish [subset_def, ext_iff, iff_def] theorem inter_eq_self_of_subset_right {s t : set α} (h : t ⊆ s) : s ∩ t = t := by finish [subset_def, ext_iff, iff_def] theorem union_inter_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) ∩ s = s := by finish [ext_iff, iff_def] theorem union_inter_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) ∩ t = t := by finish [ext_iff, iff_def] -- TODO(Mario): remove? theorem nonempty_of_inter_nonempty_right {s t : set α} (h : s ∩ t ≠ ∅) : t ≠ ∅ := by finish [ext_iff, iff_def] theorem nonempty_of_inter_nonempty_left {s t : set α} (h : s ∩ t ≠ ∅) : s ≠ ∅ := by finish [ext_iff, iff_def] /- distributivity laws -/ theorem inter_distrib_left (s t u : set α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := ext (assume x, and_or_distrib_left) theorem inter_distrib_right (s t u : set α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := ext (assume x, or_and_distrib_right) theorem union_distrib_left (s t u : set α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := ext (assume x, or_and_distrib_left) theorem union_distrib_right (s t u : set α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := ext (assume x, and_or_distrib_right) /- insert -/ theorem insert_def (x : α) (s : set α) : insert x s = { y | y = x ∨ y ∈ s } := rfl @[simp] theorem insert_of_has_insert (x : α) (s : set α) : has_insert.insert x s = insert x s := rfl @[simp] theorem subset_insert (x : α) (s : set α) : s ⊆ insert x s := assume y ys, or.inr ys theorem mem_insert (x : α) (s : set α) : x ∈ insert x s := or.inl rfl theorem mem_insert_of_mem {x : α} {s : set α} (y : α) : x ∈ s → x ∈ insert y s := or.inr theorem eq_or_mem_of_mem_insert {x a : α} {s : set α} : x ∈ insert a s → x = a ∨ x ∈ s := id theorem mem_of_mem_insert_of_ne {x a : α} {s : set α} (xin : x ∈ insert a s) : x ≠ a → x ∈ s := by finish [insert_def] @[simp] theorem mem_insert_iff {x a : α} {s : set α} : x ∈ insert a s ↔ (x = a ∨ x ∈ s) := iff.rfl @[simp] theorem insert_eq_of_mem {a : α} {s : set α} (h : a ∈ s) : insert a s = s := by finish [ext_iff, iff_def] theorem insert_subset : insert a s ⊆ t ↔ (a ∈ t ∧ s ⊆ t) := by simp [subset_def, or_imp_distrib, forall_and_distrib] theorem insert_subset_insert (h : s ⊆ t) : insert a s ⊆ insert a t := assume a', or.imp_right (@h a') theorem ssubset_insert {s : set α} {a : α} (h : a ∉ s) : s ⊂ insert a s := by finish [ssubset_def, ext_iff] theorem insert_comm (a b : α) (s : set α) : insert a (insert b s) = insert b (insert a s) := ext $ by simp [or.left_comm] theorem insert_union : insert a s ∪ t = insert a (s ∪ t) := set.ext $ assume a, by simp [or.comm, or.left_comm] @[simp] theorem union_insert : s ∪ insert a t = insert a (s ∪ t) := set.ext $ assume a, by simp [or.comm, or.left_comm] -- TODO(Jeremy): make this automatic theorem insert_ne_empty (a : α) (s : set α) : insert a s ≠ ∅ := by safe [ext_iff, iff_def]; have h' := a_1 a; finish -- useful in proofs by induction theorem forall_of_forall_insert {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ insert a s → P x) : ∀ x, x ∈ s → P x := by finish theorem forall_insert_of_forall {P : α → Prop} {a : α} {s : set α} (h : ∀ x, x ∈ s → P x) (ha : P a) : ∀ x, x ∈ insert a s → P x := by finish theorem ball_insert_iff {P : α → Prop} {a : α} {s : set α} : (∀ x ∈ insert a s, P x) ↔ P a ∧ (∀x ∈ s, P x) := by finish [iff_def] /- singletons -/ theorem singleton_def (a : α) : ({a} : set α) = insert a ∅ := rfl @[simp] theorem mem_singleton_iff {a b : α} : a ∈ ({b} : set α) ↔ a = b := by finish [singleton_def] -- TODO: again, annotation needed @[simp] theorem mem_singleton (a : α) : a ∈ ({a} : set α) := by finish theorem eq_of_mem_singleton {x y : α} (h : x ∈ ({y} : set α)) : x = y := by finish @[simp] theorem singleton_eq_singleton_iff {x y : α} : {x} = ({y} : set α) ↔ x = y := by finish [ext_iff, iff_def] theorem mem_singleton_of_eq {x y : α} (H : x = y) : x ∈ ({y} : set α) := by finish theorem insert_eq (x : α) (s : set α) : insert x s = ({x} : set α) ∪ s := by finish [ext_iff, or_comm] @[simp] theorem pair_eq_singleton (a : α) : ({a, a} : set α) = {a} := by finish @[simp] theorem singleton_ne_empty (a : α) : ({a} : set α) ≠ ∅ := insert_ne_empty _ _ @[simp] theorem singleton_subset_iff {a : α} {s : set α} : {a} ⊆ s ↔ a ∈ s := ⟨λh, h (by simp), λh b e, by simp at e; simp [*]⟩ theorem set_compr_eq_eq_singleton {a : α} : {b | b = a} = {a} := set.ext $ by simp theorem union_singleton : s ∪ {a} = insert a s := by simp [singleton_def] theorem singleton_inter_eq_empty : {a} ∩ s = ∅ ↔ a ∉ s := by simp [eq_empty_iff_forall_not_mem] theorem inter_singleton_eq_empty : s ∩ {a} = ∅ ↔ a ∉ s := by rw [inter_comm, singleton_inter_eq_empty] /- separation -/ theorem mem_sep {s : set α} {p : α → Prop} {x : α} (xs : x ∈ s) (px : p x) : x ∈ {x ∈ s | p x} := ⟨xs, px⟩ @[simp] theorem mem_sep_eq {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} = (x ∈ s ∧ p x) := rfl theorem mem_sep_iff {s : set α} {p : α → Prop} {x : α} : x ∈ {x ∈ s | p x} ↔ x ∈ s ∧ p x := iff.rfl theorem eq_sep_of_subset {s t : set α} (ssubt : s ⊆ t) : s = {x ∈ t | x ∈ s} := by finish [ext_iff, iff_def, subset_def] theorem sep_subset (s : set α) (p : α → Prop) : {x ∈ s | p x} ⊆ s := assume x, and.left theorem forall_not_of_sep_empty {s : set α} {p : α → Prop} (h : {x ∈ s | p x} = ∅) : ∀ x ∈ s, ¬ p x := by finish [ext_iff] /- complement -/ theorem mem_compl {s : set α} {x : α} (h : x ∉ s) : x ∈ -s := h theorem not_mem_of_mem_compl {s : set α} {x : α} (h : x ∈ -s) : x ∉ s := h @[simp] theorem mem_compl_eq (s : set α) (x : α) : x ∈ -s = (x ∉ s) := rfl theorem mem_compl_iff (s : set α) (x : α) : x ∈ -s ↔ x ∉ s := iff.rfl @[simp] theorem inter_compl_self (s : set α) : s ∩ -s = ∅ := by finish [ext_iff] @[simp] theorem compl_inter_self (s : set α) : -s ∩ s = ∅ := by finish [ext_iff] @[simp] theorem compl_empty : -(∅ : set α) = univ := by finish [ext_iff] @[simp] theorem compl_union (s t : set α) : -(s ∪ t) = -s ∩ -t := by finish [ext_iff] @[simp] theorem compl_compl (s : set α) : -(-s) = s := by finish [ext_iff] -- ditto theorem compl_inter (s t : set α) : -(s ∩ t) = -s ∪ -t := by finish [ext_iff] @[simp] theorem compl_univ : -(univ : set α) = ∅ := by finish [ext_iff] theorem union_eq_compl_compl_inter_compl (s t : set α) : s ∪ t = -(-s ∩ -t) := by simp [compl_inter, compl_compl] theorem inter_eq_compl_compl_union_compl (s t : set α) : s ∩ t = -(-s ∪ -t) := by simp [compl_compl] @[simp] theorem union_compl_self (s : set α) : s ∪ -s = univ := by finish [ext_iff] @[simp] theorem compl_union_self (s : set α) : -s ∪ s = univ := by finish [ext_iff] theorem compl_comp_compl : compl ∘ compl = @id (set α) := funext compl_compl theorem compl_subset_comm {s t : set α} : -s ⊆ t ↔ -t ⊆ s := by haveI := classical.prop_decidable; exact forall_congr (λ a, not_imp_comm) lemma compl_subset_compl {s t : set α} : -s ⊆ -t ↔ t ⊆ s := by rw [compl_subset_comm, compl_compl] theorem compl_subset_iff_union {s t : set α} : -s ⊆ t ↔ s ∪ t = univ := iff.symm $ eq_univ_iff_forall.trans $ forall_congr $ λ a, by haveI := classical.prop_decidable; exact or_iff_not_imp_left theorem subset_compl_comm {s t : set α} : s ⊆ -t ↔ t ⊆ -s := forall_congr $ λ a, imp_not_comm theorem subset_compl_iff_disjoint {s t : set α} : s ⊆ -t ↔ s ∩ t = ∅ := iff.trans (forall_congr $ λ a, and_imp.symm) subset_empty_iff /- set difference -/ theorem diff_eq (s t : set α) : s \ t = s ∩ -t := rfl @[simp] theorem mem_diff {s t : set α} (x : α) : x ∈ s \ t ↔ x ∈ s ∧ x ∉ t := iff.rfl theorem mem_diff_of_mem {s t : set α} {x : α} (h1 : x ∈ s) (h2 : x ∉ t) : x ∈ s \ t := ⟨h1, h2⟩ theorem mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∈ s := h.left theorem not_mem_of_mem_diff {s t : set α} {x : α} (h : x ∈ s \ t) : x ∉ t := h.right theorem union_diff_cancel {s t : set α} (h : s ⊆ t) : s ∪ (t \ s) = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_left {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ s = t := by finish [ext_iff, iff_def, subset_def] theorem union_diff_cancel_right {s t : set α} (h : s ∩ t ⊆ ∅) : (s ∪ t) \ t = s := by finish [ext_iff, iff_def, subset_def] theorem union_diff_left {s t : set α} : (s ∪ t) \ s = t \ s := by finish [ext_iff, iff_def] theorem union_diff_right {s t : set α} : (s ∪ t) \ t = s \ t := by finish [ext_iff, iff_def] theorem union_diff_distrib {s t u : set α} : (s ∪ t) \ u = s \ u ∪ t \ u := inter_distrib_right _ _ _ theorem inter_diff_assoc (a b c : set α) : (a ∩ b) \ c = a ∩ (b \ c) := inter_assoc _ _ _ theorem inter_diff_self (a b : set α) : a ∩ (b \ a) = ∅ := by finish [ext_iff] theorem inter_union_diff (s t : set α) : (s ∩ t) ∪ (s \ t) = s := by finish [ext_iff, iff_def] theorem diff_subset (s t : set α) : s \ t ⊆ s := by finish [subset_def] theorem diff_subset_diff {s₁ s₂ t₁ t₂ : set α} : s₁ ⊆ s₂ → t₂ ⊆ t₁ → s₁ \ t₁ ⊆ s₂ \ t₂ := by finish [subset_def] theorem diff_subset_diff_left {s₁ s₂ t : set α} (h : s₁ ⊆ s₂) : s₁ \ t ⊆ s₂ \ t := diff_subset_diff h (by refl) theorem diff_subset_diff_right {s t u : set α} (h : t ⊆ u) : s \ u ⊆ s \ t := diff_subset_diff (subset.refl s) h theorem compl_eq_univ_diff (s : set α) : -s = univ \ s := by finish [ext_iff] theorem diff_eq_empty {s t : set α} : s \ t = ∅ ↔ s ⊆ t := ⟨assume h x hx, classical.by_contradiction $ assume : x ∉ t, show x ∈ (∅ : set α), from h ▸ ⟨hx, this⟩, assume h, eq_empty_of_subset_empty $ assume x ⟨hx, hnx⟩, hnx $ h hx⟩ @[simp] theorem diff_empty {s : set α} : s \ ∅ = s := set.ext $ assume x, ⟨assume ⟨hx, _⟩, hx, assume h, ⟨h, not_false⟩⟩ theorem diff_diff {u : set α} : s \ t \ u = s \ (t ∪ u) := set.ext $ by simp [not_or_distrib, and.comm, and.left_comm] lemma diff_subset_iff {s t u : set α} : s \ t ⊆ u ↔ s ⊆ t ∪ u := ⟨assume h x xs, classical.by_cases or.inl (assume nxt, or.inr (h ⟨xs, nxt⟩)), assume h x ⟨xs, nxt⟩, or.resolve_left (h xs) nxt⟩ lemma diff_subset_comm {s t u : set α} : s \ t ⊆ u ↔ s \ u ⊆ t := by rw [diff_subset_iff, diff_subset_iff, union_comm] @[simp] theorem insert_diff (h : a ∈ t) : insert a s \ t = s \ t := set.ext $ by intro; constructor; simp [or_imp_distrib, h] {contextual := tt} theorem union_diff_self {s t : set α} : s ∪ (t \ s) = s ∪ t := by finish [ext_iff, iff_def] theorem diff_union_self {s t : set α} : (s \ t) ∪ t = s ∪ t := by rw [union_comm, union_diff_self, union_comm] theorem diff_inter_self {a b : set α} : (b \ a) ∩ a = ∅ := set.ext $ by simp [iff_def] {contextual:=tt} theorem diff_eq_self {s t : set α} : s \ t = s ↔ t ∩ s ⊆ ∅ := by finish [ext_iff, iff_def, subset_def] @[simp] theorem diff_singleton_eq_self {a : α} {s : set α} (h : a ∉ s) : s \ {a} = s := diff_eq_self.2 $ by simp [singleton_inter_eq_empty.2 h] @[simp] theorem insert_diff_singleton {a : α} {s : set α} : insert a (s \ {a}) = insert a s := by simp [insert_eq, union_diff_self] /- powerset -/ theorem mem_powerset {x s : set α} (h : x ⊆ s) : x ∈ powerset s := h theorem subset_of_mem_powerset {x s : set α} (h : x ∈ powerset s) : x ⊆ s := h theorem mem_powerset_iff (x s : set α) : x ∈ powerset s ↔ x ⊆ s := iff.rfl /- inverse image -/ /-- The preimage of `s : set β` by `f : α → β`, written `f ⁻¹' s`, is the set of `x : α` such that `f x ∈ s`. -/ def preimage {α : Type u} {β : Type v} (f : α → β) (s : set β) : set α := {x | f x ∈ s} infix ` ⁻¹' `:80 := preimage section preimage variables {f : α → β} {g : β → γ} @[simp] theorem preimage_empty : f ⁻¹' ∅ = ∅ := rfl @[simp] theorem mem_preimage_eq {s : set β} {a : α} : (a ∈ f ⁻¹' s) = (f a ∈ s) := rfl theorem preimage_mono {s t : set β} (h : s ⊆ t) : f ⁻¹' s ⊆ f ⁻¹' t := assume x hx, h hx @[simp] theorem preimage_univ : f ⁻¹' univ = univ := rfl @[simp] theorem preimage_inter {s t : set β} : f ⁻¹' (s ∩ t) = f ⁻¹' s ∩ f ⁻¹' t := rfl @[simp] theorem preimage_union {s t : set β} : f ⁻¹' (s ∪ t) = f ⁻¹' s ∪ f ⁻¹' t := rfl @[simp] theorem preimage_compl {s : set β} : f ⁻¹' (- s) = - (f ⁻¹' s) := rfl @[simp] theorem preimage_diff (f : α → β) (s t : set β) : f ⁻¹' (s \ t) = f ⁻¹' s \ f ⁻¹' t := rfl @[simp] theorem preimage_set_of_eq {p : α → Prop} {f : β → α} : f ⁻¹' {a | p a} = {a | p (f a)} := rfl theorem preimage_id {s : set α} : id ⁻¹' s = s := rfl theorem preimage_comp {s : set γ} : (g ∘ f) ⁻¹' s = f ⁻¹' (g ⁻¹' s) := rfl theorem eq_preimage_subtype_val_iff {p : α → Prop} {s : set (subtype p)} {t : set α} : s = subtype.val ⁻¹' t ↔ (∀x (h : p x), (⟨x, h⟩ : subtype p) ∈ s ↔ x ∈ t) := ⟨assume s_eq x h, by rw [s_eq]; simp, assume h, set.ext $ assume ⟨x, hx⟩, by simp [h]⟩ end preimage /- function image -/ section image infix ` '' `:80 := image /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ @[reducible] def eq_on (f1 f2 : α → β) (a : set α) : Prop := ∀ x ∈ a, f1 x = f2 x -- TODO(Jeremy): use bounded exists in image theorem mem_image_iff_bex {f : α → β} {s : set α} {y : β} : y ∈ f '' s ↔ ∃ x (_ : x ∈ s), f x = y := bex_def.symm theorem mem_image_eq (f : α → β) (s : set α) (y: β) : y ∈ f '' s = ∃ x, x ∈ s ∧ f x = y := rfl @[simp] theorem mem_image (f : α → β) (s : set α) (y : β) : y ∈ f '' s ↔ ∃ x, x ∈ s ∧ f x = y := iff.rfl theorem mem_image_of_mem (f : α → β) {x : α} {a : set α} (h : x ∈ a) : f x ∈ f '' a := ⟨_, h, rfl⟩ theorem mem_image_of_injective {f : α → β} {a : α} {s : set α} (hf : injective f) : f a ∈ f '' s ↔ a ∈ s := iff.intro (assume ⟨b, hb, eq⟩, (hf eq) ▸ hb) (assume h, mem_image_of_mem _ h) theorem ball_image_of_ball {f : α → β} {s : set α} {p : β → Prop} (h : ∀ x ∈ s, p (f x)) : ∀ y ∈ f '' s, p y := by finish [mem_image_eq] @[simp] theorem ball_image_iff {f : α → β} {s : set α} {p : β → Prop} : (∀ y ∈ f '' s, p y) ↔ (∀ x ∈ s, p (f x)) := iff.intro (assume h a ha, h _ $ mem_image_of_mem _ ha) (assume h b ⟨a, ha, eq⟩, eq ▸ h a ha) theorem mono_image {f : α → β} {s t : set α} (h : s ⊆ t) : f '' s ⊆ f '' t := assume x ⟨y, hy, y_eq⟩, y_eq ▸ mem_image_of_mem _ $ h hy theorem mem_image_elim {f : α → β} {s : set α} {C : β → Prop} (h : ∀ (x : α), x ∈ s → C (f x)) : ∀{y : β}, y ∈ f '' s → C y | ._ ⟨a, a_in, rfl⟩ := h a a_in theorem mem_image_elim_on {f : α → β} {s : set α} {C : β → Prop} {y : β} (h_y : y ∈ f '' s) (h : ∀ (x : α), x ∈ s → C (f x)) : C y := mem_image_elim h h_y @[congr] lemma image_congr {f g : α → β} {s : set α} (h : ∀a∈s, f a = g a) : f '' s = g '' s := by safe [ext_iff, iff_def] theorem image_eq_image_of_eq_on {f₁ f₂ : α → β} {s : set α} (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq theorem image_comp (f : β → γ) (g : α → β) (a : set α) : (f ∘ g) '' a = f '' (g '' a) := subset.antisymm (ball_image_of_ball $ assume a ha, mem_image_of_mem _ $ mem_image_of_mem _ ha) (ball_image_of_ball $ ball_image_of_ball $ assume a ha, mem_image_of_mem _ ha) /- Proof is removed as it uses generated names TODO(Jeremy): make automatic, begin safe [ext_iff, iff_def, mem_image, (∘)], have h' := h_2 (g a_2), finish end -/ theorem image_subset {a b : set α} (f : α → β) (h : a ⊆ b) : f '' a ⊆ f '' b := by finish [subset_def, mem_image_eq] theorem image_union (f : α → β) (s t : set α) : f '' (s ∪ t) = f '' s ∪ f '' t := by finish [ext_iff, iff_def, mem_image_eq] @[simp] theorem image_empty (f : α → β) : f '' ∅ = ∅ := ext $ by simp theorem image_inter_on {f : α → β} {s t : set α} (h : ∀x∈t, ∀y∈s, f x = f y → x = y) : f '' s ∩ f '' t = f '' (s ∩ t) := subset.antisymm (assume b ⟨⟨a₁, ha₁, h₁⟩, ⟨a₂, ha₂, h₂⟩⟩, have a₂ = a₁, from h _ ha₂ _ ha₁ (by simp *), ⟨a₁, ⟨ha₁, this ▸ ha₂⟩, h₁⟩) (subset_inter (mono_image $ inter_subset_left _ _) (mono_image $ inter_subset_right _ _)) theorem image_inter {f : α → β} {s t : set α} (H : injective f) : f '' s ∩ f '' t = f '' (s ∩ t) := image_inter_on (assume x _ y _ h, H h) theorem image_univ_of_surjective {ι : Type*} {f : ι → β} (H : surjective f) : f '' univ = univ := eq_univ_of_forall $ by simp [image]; exact H @[simp] theorem image_singleton {f : α → β} {a : α} : f '' {a} = {f a} := set.ext $ λ x, by simp [image]; rw eq_comm theorem fix_set_compl (t : set α) : compl t = - t := rfl -- TODO(Jeremy): there is an issue with - t unfolding to compl t theorem mem_compl_image (t : set α) (S : set (set α)) : t ∈ compl '' S ↔ -t ∈ S := begin suffices : ∀ x, -x = t ↔ -t = x, {simp [fix_set_compl, this]}, intro x, split; { intro e, subst e, simp } end @[simp] theorem image_id (s : set α) : id '' s = s := ext $ by simp theorem compl_compl_image (S : set (set α)) : compl '' (compl '' S) = S := by rw [← image_comp, compl_comp_compl, image_id] theorem image_insert_eq {f : α → β} {a : α} {s : set α} : f '' (insert a s) = insert (f a) (f '' s) := ext $ by simp [and_or_distrib_left, exists_or_distrib, eq_comm, or_comm, and_comm] theorem image_subset_preimage_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set α) : f '' s ⊆ g ⁻¹' s := λ b ⟨a, h, e⟩, e ▸ ((I a).symm ▸ h : g (f a) ∈ s) theorem preimage_subset_image_of_inverse {f : α → β} {g : β → α} (I : left_inverse g f) (s : set β) : f ⁻¹' s ⊆ g '' s := λ b h, ⟨f b, h, I b⟩ theorem image_eq_preimage_of_inverse {f : α → β} {g : β → α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : image f = preimage g := funext $ λ s, subset.antisymm (image_subset_preimage_of_inverse h₁ s) (preimage_subset_image_of_inverse h₂ s) theorem mem_image_iff_of_inverse {f : α → β} {g : β → α} {b : β} {s : set α} (h₁ : left_inverse g f) (h₂ : right_inverse g f) : b ∈ f '' s ↔ g b ∈ s := by rw image_eq_preimage_of_inverse h₁ h₂; refl theorem image_compl_subset {f : α → β} {s : set α} (H : injective f) : f '' -s ⊆ -(f '' s) := subset_compl_iff_disjoint.2 $ by simp [image_inter H] theorem subset_image_compl {f : α → β} {s : set α} (H : surjective f) : -(f '' s) ⊆ f '' -s := compl_subset_iff_union.2 $ by rw ← image_union; simp [image_univ_of_surjective H] theorem image_compl_eq {f : α → β} {s : set α} (H : bijective f) : f '' -s = -(f '' s) := subset.antisymm (image_compl_subset H.1) (subset_image_compl H.2) /- image and preimage are a Galois connection -/ theorem image_subset_iff {s : set α} {t : set β} {f : α → β} : f '' s ⊆ t ↔ s ⊆ f ⁻¹' t := ball_image_iff theorem image_preimage_subset (f : α → β) (s : set β) : f '' (f ⁻¹' s) ⊆ s := image_subset_iff.2 (subset.refl _) theorem subset_preimage_image (f : α → β) (s : set α) : s ⊆ f ⁻¹' (f '' s) := λ x, mem_image_of_mem f theorem preimage_image_eq {f : α → β} (s : set α) (h : injective f) : f ⁻¹' (f '' s) = s := subset.antisymm (λ x ⟨y, hy, e⟩, h e ▸ hy) (subset_preimage_image f s) theorem image_preimage_eq {f : α → β} {s : set β} (h : surjective f) : f '' (f ⁻¹' s) = s := subset.antisymm (image_preimage_subset f s) (λ x hx, let ⟨y, e⟩ := h x in ⟨y, (e.symm ▸ hx : f y ∈ s), e⟩) theorem compl_image : image (@compl α) = preimage compl := image_eq_preimage_of_inverse compl_compl compl_compl theorem compl_image_set_of {α : Type u} {p : set α → Prop} : compl '' {x | p x} = {x | p (- x)} := congr_fun compl_image p theorem inter_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∩ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∩ t) := λ x h, ⟨mem_image_of_mem _ h.left, h.right⟩ theorem union_preimage_subset (s : set α) (t : set β) (f : α → β) : s ∪ f ⁻¹' t ⊆ f ⁻¹' (f '' s ∪ t) := λ x h, or.elim h (λ l, or.inl $ mem_image_of_mem _ l) (λ r, or.inr r) theorem subset_image_union (f : α → β) (s : set α) (t : set β) : f '' (s ∪ f ⁻¹' t) ⊆ f '' s ∪ t := image_subset_iff.2 (union_preimage_subset _ _ _) lemma subtype_val_image {p : α → Prop} {s : set (subtype p)} : subtype.val '' s = {x | ∃h : p x, (⟨x, h⟩ : subtype p) ∈ s} := set.ext $ assume a, ⟨assume ⟨⟨a', ha'⟩, in_s, h_eq⟩, h_eq ▸ ⟨ha', in_s⟩, assume ⟨ha, in_s⟩, ⟨⟨a, ha⟩, in_s, rfl⟩⟩ end image theorem univ_eq_true_false : univ = ({true, false} : set Prop) := eq.symm $ eq_univ_of_forall $ classical.cases (by simp) (by simp) section range variables {f : ι → α} open function /-- Range of a function. This function is more flexible than `f '' univ`, as the image requires that the domain is in Type and not an arbitrary Sort. -/ def range (f : ι → α) : set α := {x | ∃y, f y = x} @[simp] theorem mem_range {x : α} : x ∈ range f ↔ ∃ y, f y = x := iff.rfl theorem mem_range_self (i : ι) : f i ∈ range f := ⟨i, rfl⟩ theorem forall_range_iff {p : α → Prop} : (∀ a ∈ range f, p a) ↔ (∀ i, p (f i)) := ⟨assume h i, h (f i) (mem_range_self _), assume h a ⟨i, (hi : f i = a)⟩, hi ▸ h i⟩ theorem range_iff_surjective : range f = univ ↔ surjective f := eq_univ_iff_forall @[simp] theorem range_id : range (@id α) = univ := range_iff_surjective.2 surjective_id @[simp] theorem image_univ {ι : Type*} {f : ι → β} : f '' univ = range f := set.ext $ by simp [image, range] theorem range_comp {g : α → β} : range (g ∘ f) = g '' range f := subset.antisymm (forall_range_iff.mpr $ assume i, mem_image_of_mem g (mem_range_self _)) (ball_image_iff.mpr $ forall_range_iff.mpr mem_range_self) theorem range_subset_iff {ι : Type*} {f : ι → β} {s : set β} : range f ⊆ s ↔ ∀ y, f y ∈ s := forall_range_iff theorem image_preimage_eq_inter_range {f : α → β} {t : set β} : f '' preimage f t = t ∩ range f := set.ext $ assume x, ⟨assume ⟨x, hx, heq⟩, heq ▸ ⟨hx, mem_range_self _⟩, assume ⟨hx, ⟨y, h_eq⟩⟩, h_eq ▸ mem_image_of_mem f $ show y ∈ preimage f t, by simp [preimage, h_eq, hx]⟩ @[simp] theorem quot_mk_range_eq [setoid α] : range (λx : α, ⟦x⟧) = univ := range_iff_surjective.2 quot.exists_rep end range lemma subtype_val_range {p : α → Prop} : range (@subtype.val _ p) = {x | p x} := by rw ← image_univ; simp [-image_univ, subtype_val_image] /-- The set `s` is pairwise `r` if `r x y` for all *distinct* `x y ∈ s`. -/ def pairwise_on (s : set α) (r : α → α → Prop) := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → r x y end set namespace set section prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} /-- The cartesian product `prod s t` is the set of `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def prod (s : set α) (t : set β) : set (α × β) := {p | p.1 ∈ s ∧ p.2 ∈ t} theorem mem_prod_eq {p : α × β} : p ∈ set.prod s t = (p.1 ∈ s ∧ p.2 ∈ t) := rfl @[simp] theorem mem_prod {p : α × β} : p ∈ set.prod s t ↔ p.1 ∈ s ∧ p.2 ∈ t := iff.rfl @[simp] theorem prod_empty {s : set α} : set.prod s ∅ = (∅ : set (α × β)) := set.ext $ by simp [set.prod] @[simp] theorem empty_prod {t : set β} : set.prod ∅ t = (∅ : set (α × β)) := set.ext $ by simp [set.prod] theorem insert_prod {a : α} {s : set α} {t : set β} : set.prod (insert a s) t = (prod.mk a '' t) ∪ set.prod s t := set.ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_insert {b : β} {s : set α} {t : set β} : set.prod s (insert b t) = ((λa, (a, b)) '' s) ∪ set.prod s t := set.ext begin simp [set.prod, image, iff_def, or_imp_distrib] {contextual := tt}; cc end theorem prod_preimage_eq {f : γ → α} {g : δ → β} : set.prod (preimage f s) (preimage g t) = preimage (λp, (f p.1, g p.2)) (set.prod s t) := rfl theorem prod_mono {s₁ s₂ : set α} {t₁ t₂ : set β} (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) : set.prod s₁ t₁ ⊆ set.prod s₂ t₂ := assume x ⟨h₁, h₂⟩, ⟨hs h₁, ht h₂⟩ theorem prod_inter_prod : set.prod s₁ t₁ ∩ set.prod s₂ t₂ = set.prod (s₁ ∩ s₂) (t₁ ∩ t₂) := subset.antisymm (assume ⟨a, b⟩ ⟨⟨ha₁, hb₁⟩, ⟨ha₂, hb₂⟩⟩, ⟨⟨ha₁, ha₂⟩, ⟨hb₁, hb₂⟩⟩) (subset_inter (prod_mono (inter_subset_left _ _) (inter_subset_left _ _)) (prod_mono (inter_subset_right _ _) (inter_subset_right _ _))) theorem image_swap_prod : (λp:β×α, (p.2, p.1)) '' set.prod t s = set.prod s t := set.ext $ assume ⟨a, b⟩, by simp [mem_image_eq, set.prod, and_comm]; exact ⟨ assume ⟨b', a', ⟨h_a, h_b⟩, h⟩, by subst a'; subst b'; assumption, assume h, ⟨b, a, ⟨rfl, rfl⟩, h⟩⟩ theorem image_swap_eq_preimage_swap : image (@prod.swap α β) = preimage prod.swap := image_eq_preimage_of_inverse prod.swap_left_inverse prod.swap_right_inverse theorem prod_image_image_eq {m₁ : α → γ} {m₂ : β → δ} : set.prod (image m₁ s) (image m₂ t) = image (λp:α×β, (m₁ p.1, m₂ p.2)) (set.prod s t) := set.ext $ by simp [-exists_and_distrib_right, exists_and_distrib_right.symm, and.left_comm, and.assoc, and.comm] theorem prod_range_range_eq {α β γ δ} {m₁ : α → γ} {m₂ : β → δ} : set.prod (range m₁) (range m₂) = range (λp:α×β, (m₁ p.1, m₂ p.2)) := set.ext $ by simp [range] @[simp] theorem prod_singleton_singleton {a : α} {b : β} : set.prod {a} {b} = ({(a, b)} : set (α×β)) := set.ext $ by simp [set.prod] theorem prod_neq_empty_iff {s : set α} {t : set β} : set.prod s t ≠ ∅ ↔ (s ≠ ∅ ∧ t ≠ ∅) := by simp [not_eq_empty_iff_exists] @[simp] theorem prod_mk_mem_set_prod_eq {a : α} {b : β} {s : set α} {t : set β} : (a, b) ∈ set.prod s t = (a ∈ s ∧ b ∈ t) := rfl @[simp] theorem univ_prod_univ : set.prod univ univ = (univ : set (α×β)) := set.ext $ assume ⟨a, b⟩, by simp end prod end set
526ff630a5f2ff9611908270393f35cc6cb2fdee
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/bad_unification_hint.lean
8720444b543f7313848f67e32e17e1e40cce056a
[ "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
723
lean
-- Good hint @[unify] def {u} cons_append_hint (α : Type u) (a b : α) (l₁ l₂ l₃: list α) : unification_hint := { pattern := (a :: l₁) ++ l₂ =?= b :: l₃, constraints := [l₃ =?= l₁ ++ l₂, a =?= b] } -- Bad hint: pattern is incorrect @[unify] def {u} append_cons_hint (α : Type u) (a b : α) (l₁ l₂ l₃: list α) : unification_hint := { pattern := l₁ ++ (a :: l₂) =?= b :: l₃, constraints := [l₃ =?= l₁ ++ l₂, a =?= b] } -- Bad hint: constraint #1 is incorrect @[unify] def {u} cons_append_hint' (α : Type u) (a b : α) (l₁ l₂ l₃: list α) : unification_hint := { pattern := (a :: l₁) ++ l₂ =?= b :: l₃, constraints := [l₃ =?= l₁ ++ l₃, a =?= b] }